1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5
6 :- module(custom_explicit_sets,[is_set_value/2,
7 is_custom_explicit_set/1, is_custom_explicit_set/2, is_custom_explicit_set_nonvar/1,
8 %equal_explicit_sets/2,
9 equal_explicit_sets_wf/3,
10 not_equal_explicit_sets_wf/3,
11 equality_explicit_sets_wf/4, same_texpr_body/2, same_closure/2,
12 is_empty_explicit_set/1, is_empty_explicit_set_wf/2, is_empty_closure_wf/4,
13 is_non_empty_explicit_set/1, is_non_empty_explicit_set_wf/2,
14 is_non_empty_closure_wf/4,
15 test_empty_explicit_set_wf/3, test_empty_closure_wf/5,
16 is_definitely_maximal_set/1,
17 explicit_set_cardinality/2, explicit_set_cardinality_wf/3,
18 explicit_set_cardinality_for_wf/2,
19 card_for_specific_custom_set/3, % only succeeds if we can compute it efficiently
20 card_for_specific_closure/4,
21 efficient_card_for_set/3, % same, but also for lists
22 quick_custom_explicit_set_approximate_size/2,
23 avl_approximate_size/2, avl_approximate_size/3,
24 is_infinite_explicit_set/1, is_infinite_closure/3,
25 is_infinite_global_set/2, is_simple_infinite_set/1,
26 is_infinite_or_symbolic_set/1,
27 dont_expand_this_explicit_set/1, dont_expand_this_explicit_set/2,
28 dont_expand_symbolic_explicit_set/1,
29 definitely_expand_this_explicit_set/1,
30 is_infinite_or_very_large_explicit_set/1,
31 is_infinite_or_very_large_explicit_set/2,
32 is_cartesian_product_closure/3,
33 expand_custom_set/2, expand_custom_set_wf/4,
34 try_expand_custom_set/2, try_expand_custom_set_with_catch/3,
35 try_expand_custom_set_wf/4,
36 expand_custom_set_to_list/2, expand_custom_set_to_list/4,
37 expand_custom_set_to_list_wf/5,
38 try_expand_custom_set_to_list_wf/5,
39 expand_custom_set_to_list_no_dups_wf/5,
40 expand_custom_set_to_list_gg/4,
41 try_expand_custom_set_to_list/4,
42 expand_interval_closure_to_avl/3,
43 expand_custom_set_to_list_now/2,
44 expand_closure_to_avl_or_list/6,
45 expand_closure_to_list/7,
46 expand_only_custom_closure_global/4, %try_expand_only_custom_closure_global/2,
47 expand_and_convert_to_avl_set/4,
48 ord_list_to_avlset_direct/3, sorted_ground_normalised_list_to_avlset/3,
49 try_expand_and_convert_to_avl/2, convert_to_avl/2,
50 should_be_converted_to_avl_from_lists/1, should_be_converted_to_avl/1,
51 try_expand_and_convert_to_avl_with_check/3,
52 try_expand_and_convert_to_avl_with_check/4,
53 try_expand_and_convert_to_avl_unless_large_wf/3,
54 %try_expand_and_convert_to_avl_unless_large_wf/3,
55 try_expand_and_convert_to_avl_if_smaller_than/3,
56 is_small_specific_custom_set/2,
57 quick_propagation_element_information/4,
58 element_of_custom_set/2, element_of_custom_set_wf/3,
59 element_of_closure/5,
60 check_element_of_function_closure/6,
61 not_element_of_custom_set_wf/3,
62 membership_custom_set/3, membership_custom_set_wf/4, membership_avl_set_wf/4,
63 quick_test_avl_membership/3,
64 lazy_check_elements_of_closure/6,
65
66 is_efficient_custom_set/1,
67 remove_minimum_element_custom_set/3,
68
69 is_maximal_global_set/1, quick_is_definitely_maximal_set/1,
70 quick_definitely_maximal_set_avl/1,
71 is_one_element_custom_set/2, singleton_set/2, construct_singleton_avl_set/2,
72 is_one_element_avl/2,
73 construct_one_element_custom_set/2,
74 avl_is_interval/3,
75
76 %closure0_for_explicit_set/2,
77 closure1_for_explicit_set/2, closure1_for_explicit_set_from/3,
78 check_in_domain_of_avlset_wf/3, check_unique_in_domain_of_avlset/2,
79 domain_of_explicit_set_wf/3, range_of_explicit_set_wf/3,
80 is_avl_partial_function/1, is_not_avl_partial_function/2,
81 is_avl_total_function_over_domain/2,
82 quick_definitely_maximal_total_function_avl/1,
83 is_avl_relation/1,
84 is_avl_relation_over_domain/3,
85 is_avl_relation_over_range/3,
86 is_not_avl_relation_over_domain_range/4, is_not_avl_relation_over_range/3,
87 is_avl_sequence/1, safe_is_avl_sequence/1,
88 get_avl_sequence/2,
89 is_injective_avl_relation/2,
90 invert_explicit_set/2, union_of_explicit_set/3,
91 union_generalized_explicit_set/3,
92 difference_of_explicit_set_wf/4,
93 intersection_of_explicit_set_wf/4, intersection_with_interval_closure/3,
94 disjoint_intervals_with_inf/4,
95 image_for_id_closure/3, image_for_explicit_set/4,
96 rel_composition_for_explicit_set/3,
97 element_can_be_added_or_removed_to_avl/1,
98 add_element_to_explicit_set_wf/4, remove_element_from_explicit_set/3,
99 delete_element_from_explicit_set/3,
100 at_most_one_match_possible/3,
101 apply_to_avl_set/5, try_apply_to_avl_set_wf/4,
102 min_of_explicit_set_wf/3, max_of_explicit_set_wf/3,
103 sum_or_mul_of_explicit_set/3,
104 %sum_of_range_custom_explicit_set/2, mul_of_range_custom_explicit_set/2,
105 domain_restriction_explicit_set_wf/4,
106 range_restriction_explicit_set_wf/4,
107 domain_subtraction_explicit_set_wf/4,
108 range_subtraction_explicit_set_wf/4,
109 override_pair_explicit_set/4,
110 direct_product_explicit_set/3,
111 override_custom_explicit_set_wf/4,
112 symbolic_functionality_check_closure/2, symbolic_injectivity_check_closure/2,
113
114 subset_of_explicit_set/4, not_subset_of_explicit_set/4,
115 test_subset_of_explicit_set/5,
116
117 conc_custom_explicit_set/4,
118 prefix_of_custom_explicit_set/4, suffix_of_custom_explicit_set/4,
119 concat_custom_explicit_set/4, prepend_custom_explicit_set/5,
120 append_custom_explicit_set/4,
121 tail_sequence_custom_explicit_set/5,
122 last_sequence_explicit_set/4, %first_sequence_explicit_set/2,
123 front_sequence_custom_explicit_set/4,
124 reverse_custom_explicit_set/3,
125 size_of_custom_explicit_set/3,
126
127 get_first_avl_elements/4,
128 construct_avl_from_lists/2, construct_avl_from_lists_wf/3,
129 equal_avl_tree/2,
130 check_avl_in_interval/3, check_interval_in_custom_set/4,
131 check_avl_subset/2,
132 construct_closure/4, is_closure/4, % from closures
133 construct_member_closure/5, % from closures
134
135 construct_interval_closure/3,
136 is_interval_closure/3, % checks if we have a finite interval closure Low..Up (but bounds can be variables)
137 is_interval_closure/5,
138 is_interval_closure_or_integerset/3, is_interval_closure_or_integerset/4,
139 is_interval_with_integer_bounds/3, % checks that bounds are known
140 intersect_intervals_with_inf/6,
141
142 is_powerset_closure/3,
143
144 dom_range_for_specific_closure/5,
145 dom_for_specific_closure/4,
146 dom_for_lambda_closure/2,
147 portray_custom_explicit_set/1,
148 closure_occurs_check/4
149 ]).
150
151 :- meta_predicate call_card_for_relations(-,-,0).
152
153 :- use_module(module_information,[module_info/2]).
154 :- module_info(group,kernel).
155 :- module_info(description,'This module provides customised operations for the custom explicit set representations of ProB (closures, avl_sets and global_sets).').
156
157 :- use_module(error_manager).
158 :- use_module(self_check).
159 :- use_module(preferences,[get_preference/2]).
160 :- use_module(library(avl)).
161 :- use_module(kernel_waitflags).
162 :- use_module(kernel_tools).
163 :- use_module(delay).
164 :- use_module(tools).
165 :- use_module(avl_tools).
166 :- use_module(library(clpfd)).
167 :- use_module(debug).
168 :- use_module(tools_printing,[print_term_summary/1, print_error/1]).
169 :- use_module(preferences,[preference/2]).
170 :- use_module(kernel_objects,[equal_object/2, equal_object/3]).
171 :- use_module(kernel_freetypes,[enumerate_freetype_wf/4,freetype_cardinality/2,
172 is_infinite_freetype/1, is_empty_freetype/1,
173 is_non_empty_freetype/1, test_empty_freetype/2]).
174 :- use_module(clpfd_interface,[try_post_constraint/1, clpfd_reify_inlist/4]).
175 :- use_module(closures).
176 :- use_module(performance_messages).
177 :- use_module(b_compiler).
178 :- use_module(btypechecker,[couplise_list/2, unify_types_strict/2, merge_types/3]).
179
180 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
181
182 /* These meta_predicate declarations do not seem to have the right effect;
183 the predicates below return code, they do not get passed code
184 :- meta_predicate card_for_specific_custom_set(*,*,0).
185 :- meta_predicate card_for_specific_closure(*,*,0).
186 :- meta_predicate is_a_relation(*,*,*,*,*,*,0).
187 :- meta_predicate subset_of_explicit_set(*,*,0,*).
188 :- meta_predicate not_subset_of_explicit_set(*,*,0,*).
189 */
190
191 construct_avl_from_lists(S,Res) :-
192 (convert_to_avl(S,CS) -> true ; print(convert_to_avl_failed(S,CS)),nl,CS=S),
193 Res = CS.
194
195 % version with WF to see call stack in case of virtual time-outs due to expansions
196 construct_avl_from_lists_wf(S,Res,WF) :-
197 (convert_to_avl_wf(S,CS,WF) -> true ; print(convert_to_avl_wf_failed(S,CS)),nl,CS=S),
198 Res = CS.
199
200 :- use_module(tools,[safe_sort/3]).
201 :- block normalised_list_to_avl_when_ground(-,?).
202 normalised_list_to_avl_when_ground(S,R) :- % call if you are not sure that S will be ground; e.g. after closure expansion
203 ground_value_check(S,GS),
204 blocking_normalised_list_to_avl(GS,S,R).
205 :- block blocking_normalised_list_to_avl(-,?,?).
206 blocking_normalised_list_to_avl(_,S,R) :- normalised_list_to_avl(S,R).
207
208 normalised_list_to_avl(S,R) :- safe_sort(normalised_list_to_avl,S,SS),
209 ord_list_to_avlset_direct(SS,AVL,normalised_list_to_avl),
210 equal_object(AVL,R). % due to co-routine, R can now be instantiated
211
212 %set_to_avl(List,R) :- empty_avl(A), add_to_avl(List,A,AR), R=avl_set(AR).
213 add_to_avl([],R,R).
214 add_to_avl([H|T],AVL,AVLOUT) :- avl_store(H,AVL,true,AVL1),
215 add_to_avl(T,AVL1,AVLOUT).
216
217
218 % get only the first x elements of an AVL tree
219 get_first_avl_elements(empty,_,R,all) :- !,R=[].
220 get_first_avl_elements(AVL,X,FirstXEls,CutOff) :-
221 avl_min(AVL,Min), get_first_els(X,Min,AVL,FirstXEls,CutOff).
222
223 get_first_els(X,_,_AVL,R,CutOff) :- X<1,!,R=[], CutOff=not_all.
224 get_first_els(X,Cur,AVL,[Cur|T],CutOff) :-
225 (avl_next(Cur,AVL,Nxt) -> X1 is X-1,get_first_els(X1,Nxt,AVL,T,CutOff)
226 ; T=[],CutOff=all).
227
228 %expand_and_try_convert_to_avl(C,R) :- is_closure(C,_,_,_), expand_custom_set(C,EC), expand_and_convert_to_avl
229 %expand_and_convert_to_avl(C,R) :- convert_to_avl(C,R).
230
231 /* convert all list data-values (with all-sub-values) into avl-form */
232 /* assumption: the value is ground when convert_to_avl is called */
233
234 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
235 :- if(environ(prob_safe_mode,true)).
236 convert_to_avl(X,R) :- \+ ground_value(X), !, add_error(convert_to_avl,'Non-ground argument: ',convert_to_avl(X,R)), R=X.
237 :- endif.
238 convert_to_avl(X,R) :- var(X), !, add_error(convert_to_avl,'Variable argument: ',convert_to_avl(X,R)), R=X.
239 ?convert_to_avl(Term,R) :- no_conversion_necessary(Term),!,
240 R=Term.
241 convert_to_avl(closure(P,T,B),R) :- !,
242 R=closure(P,T,B).
243 convert_to_avl(avl_set(A),R) :- !,(A==empty -> add_warning(convert_to_avl,'Emtpy avl_set'), R=[]
244 ; R=avl_set(A)).
245 convert_to_avl((A,B),(CA,CB)) :- !,convert_to_avl(A,CA), convert_to_avl(B,CB).
246 convert_to_avl(freetype(X),R) :- !, R=freetype(X).
247 convert_to_avl(freeval(ID,Case,Value),R) :- !, R=freeval(ID,Case,CValue),convert_to_avl(Value,CValue).
248 convert_to_avl(rec(Fields),R) :- !, convert_fields(Fields,CFields), R=rec(CFields).
249 convert_to_avl(global_set(GS),R) :- !, R=global_set(GS).
250 ?convert_to_avl([H|T],R) :- !, convert_cons_to_avl_inside_set_wf(H,T,R,no_wf_available).
251 %convert_to_avl(abort(X),_R) :- print(deprecetated_convert_to_avl(abort(X))),nl,!, fail.
252 convert_to_avl(X,R) :- add_internal_error('Unknown term: ',convert_to_avl(X,R)), R=X.
253
254 % pass WF for call stack in case of expansions TODO: complete
255 convert_to_avl_wf((A,B),(CA,CB),WF) :- !,convert_to_avl_wf(A,CA,WF), convert_to_avl_wf(B,CB,WF).
256 convert_to_avl_wf([H|T],R,WF) :- !, convert_cons_to_avl_inside_set_wf(H,T,R,WF).
257 convert_to_avl_wf(X,R,_) :- convert_to_avl(X,R).
258
259 convert_fields(Var,R) :- var(Var),!,
260 add_internal_error('Var arg: ',convert_fields(Var,R)),fail.
261 convert_fields([],[]).
262 convert_fields([field(FieldName,Value)|T],[field(FieldName,CValue)|CT]) :-
263 convert_to_avl_inside_set(Value,CValue),
264 convert_fields(T,CT).
265
266 l_convert_to_avl_wf(Var,_,WF) :- var(Var),!,
267 add_warning_wf(l_convert_to_avl_wf,'Cannot expand variable to avl: ',Var,unknown,WF),
268 fail.
269 l_convert_to_avl_wf([],[],_).
270 l_convert_to_avl_wf(avl_set(A),R,WF) :-
271 expand_custom_set_wf(avl_set(A),ES,l_convert_to_avl,WF),
272 l_convert_to_avl_wf(ES,R,WF).
273 l_convert_to_avl_wf(closure(P,T,B),R,WF) :-
274 expand_custom_set_wf(closure(P,T,B),ES,l_convert_to_avl,WF),
275 l_convert_to_avl_wf(ES,R,WF).
276 l_convert_to_avl_wf([H|T],[CH-true|CT],WF) :-
277 ? convert_to_avl_inside_set_wf(H,CH,WF), l_convert_to_avl_wf(T,CT,WF).
278
279 :- assert_must_succeed((X=(fd(1,'Name'),fd(2,'Name')),
280 custom_explicit_sets:convert_to_avl_inside_set(X,R), R==X)).
281
282 convert_to_avl_inside_set(Var,R) :- var(Var),!,
283 add_internal_error('Var arg: ',convert_to_avl_inside_set(Var,R)),fail.
284 :- if(environ(prob_safe_mode,true)).
285 convert_to_avl_inside_set(fd(A,T),R) :- var(A),!,
286 add_error(convert_to_avl,'Non-ground FD-Term: ',convert_to_avl_inside_set(fd(A,T),R)), R=fd(A,T).
287 convert_to_avl_inside_set(int(X),R) :- var(X),!,
288 add_error(convert_to_avl,'Non-ground integer: ',convert_to_avl_inside_set(int(X),R)), R=int(X).
289 convert_to_avl_inside_set(string(X),R) :- var(X),!,
290 add_error(convert_to_avl,'Non-ground string: ',convert_to_avl_inside_set(string(X),R)), R=string(X).
291 convert_to_avl_inside_set(term(X),R) :- (var(X) ; X=floating(F), var(F)), !,
292 add_error(convert_to_avl,'Non-ground term: ',convert_to_avl_inside_set(term(X),R)), R=term(X).
293 :- endif.
294 ?convert_to_avl_inside_set(Term,R) :- no_conversion_necessary(Term),!,R=Term.
295 convert_to_avl_inside_set(closure(P,T,B),R) :- !,
296 % inside a set, closures need to be expanded to check against other elements
297 expand_closure_to_avl_wf(P,T,B,R,no_wf_available).
298 %convert_to_avl_inside_set(closure_x(_P,_T,_B,E),R) :- !, convert_to_avl_inside_set(E,R).
299 convert_to_avl_inside_set(avl_set(A),R) :- !, normalise_avl_set(A,R). %AVL's inside other AVL's need to be normalised !
300 convert_to_avl_inside_set((A,B),(CA,CB)) :- !,convert_to_avl_inside_set(A,CA), convert_to_avl_inside_set(B,CB).
301 convert_to_avl_inside_set(freetype(X),R) :- !,
302 expand_custom_set(freetype(X),EC,check), convert_to_avl_inside_set(EC,R).
303 convert_to_avl_inside_set(freeval(ID,Case,Value),R) :- !,
304 R=freeval(ID,Case,CValue),convert_to_avl_inside_set(Value,CValue).
305 convert_to_avl_inside_set(rec(Fields),R) :- !, convert_fields(Fields,CFields), R=rec(CFields).
306 convert_to_avl_inside_set(global_set(GS),R) :- !,
307 % first check if GS infinite integer set: in this case do not expand; there can be no confusion with finite avl_sets
308 ? (is_infinite_global_set(GS,_) -> R = global_set(GS)
309 ; expand_only_custom_closure_global(global_set(GS),EC,check,no_wf_available), convert_to_avl_inside_set(EC,R)).
310 convert_to_avl_inside_set([H|T],R) :- !,convert_cons_to_avl_inside_set_wf(H,T,R,no_wf_available).
311 convert_to_avl_inside_set(X,R) :-
312 add_internal_error('Unknown or non-ground argument: ',convert_to_avl_inside_set(X,R)),
313 fail.
314
315 ?convert_to_avl_inside_set_wf(Term,R,_WF) :- no_conversion_necessary(Term),!,R=Term.
316 convert_to_avl_inside_set_wf(closure(P,T,B),R,WF) :- !,
317 ? expand_closure_to_avl_wf(P,T,B,R,WF). % inside a set, closures need to be expanded to check against other elements
318 convert_to_avl_inside_set_wf((A,B),(CA,CB),WF) :- !,
319 ? convert_to_avl_inside_set_wf(A,CA,WF), convert_to_avl_inside_set_wf(B,CB,WF).
320 convert_to_avl_inside_set_wf([H|T],R,WF) :- !,convert_cons_to_avl_inside_set_wf(H,T,R,WF).
321 convert_to_avl_inside_set_wf(V,CV,_WF) :- % use version without WF; TO DO: adapt fully
322 convert_to_avl_inside_set(V,CV).
323
324 % true when we have a simple value that does not need to be converted for use within an avl_set:
325 no_conversion_necessary([]).
326 no_conversion_necessary(pred_false). /* bool_false */
327 no_conversion_necessary(pred_true). /* bool_true */
328 no_conversion_necessary(fd(FD,_)) :- nonvar(FD).
329 no_conversion_necessary(int(I)) :- nonvar(I).
330 no_conversion_necessary(string(S)) :- nonvar(S).
331 ?no_conversion_necessary(term(T)) :- nonvar(T), no_conversion_nec_term(T).
332
333 no_conversion_nec_term(floating(T)) :- nonvar(T).
334 no_conversion_nec_term(T) :- atom(T).
335
336 normalise_avl_set(A,R) :- A=node(_,_,0,empty,empty), !,R=avl_set(A).
337 normalise_avl_set(A,R) :-
338 avl_to_list(A,L),
339 ord_list_to_avlset_direct(L,R,convert_to_avl_inside_set). %AVL's inside other AVL's need to be normalised !
340
341 convert_cons_to_avl_inside_set_wf(H,T,R,WF) :- T==[], !,
342 convert_to_avl_inside_set_wf(H,CH,WF),
343 R = avl_set(node(CH,true,0,empty,empty)).
344 ?convert_cons_to_avl_inside_set_wf(H,T,R,WF) :- l_convert_to_avl_wf([H|T],S,WF),
345 sort(S,SS),
346 ord_list_to_avlset_direct(SS,R,convert_to_avl_inside_set).
347
348 construct_singleton_avl_set(Val,avl_set(node(Val,true,0,empty,empty))).
349
350
351 is_set_value(X,Origin) :- var(X), !,print(is_set_value(Origin)),nl,fail.
352 is_set_value([],_) :- !.
353 is_set_value([_|_],_) :- !.
354 is_set_value(X,_) :- is_custom_explicit_set(X).
355
356 is_custom_explicit_set(X,Origin) :- var(X), !,print(var_is_custom_explicit_set(Origin)),nl,fail.
357 is_custom_explicit_set(X,_) :- is_custom_explicit_set(X).
358
359 is_custom_explicit_set(X) :- var(X), !,print(var_is_custom_explicit_set),nl,fail.
360 is_custom_explicit_set(global_set(_)).
361 is_custom_explicit_set(freetype(_)).
362 %is_custom_explicit_set(integer_global_set(_)).
363 is_custom_explicit_set(avl_set(_)).
364 is_custom_explicit_set(closure(_Parameters,_PT,_Cond)).
365
366 % use if you know the argument to be nonvar
367 is_custom_explicit_set_nonvar(global_set(_)).
368 is_custom_explicit_set_nonvar(freetype(_)).
369 is_custom_explicit_set_nonvar(avl_set(_)).
370 is_custom_explicit_set_nonvar(closure(_Parameters,_PT,_Cond)).
371
372 %:- assert_must_succeed(( custom_explicit_sets:portray_custom_explicit_set(avl_set(empty)) )). % now generates error
373 :- use_module(translate,[translate_bvalue/2]).
374 portray_custom_explicit_set(S) :- translate_bvalue(S,A), format(A,[]),nl.
375
376 /* a predicate to check equality of two custom explicit sets */
377
378 %equal_explicit_sets(A,B) :- equal_explicit_sets_wf(A,B,no_wf_available).
379
380 %equal_explicit_sets(X,Y) :- print_term_summary(equal_explicit_sets(X,Y)),fail.
381 :- block equal_explicit_sets_wf(-,?,?), equal_explicit_sets_wf(?,-,?).
382 ?equal_explicit_sets_wf(A,B,WF) :- equal_explicit_sets4(A,B,allow_expansion,WF).
383
384 equal_explicit_sets4(global_set(X),global_set(Y),_,_WF) :- !,X=Y.
385 equal_explicit_sets4(global_set(B),avl_set(A),E,WF) :- !,equal_explicit_sets4(avl_set(A),global_set(B),E,WF).
386 equal_explicit_sets4(freetype(X),freetype(Y),_,_WF) :- !,X=Y.
387 equal_explicit_sets4(avl_set(A),avl_set(B),_,_WF) :- !,
388 equal_avl_tree(A,B). % alternatively, we could normalise avl_trees and only store normalised versions
389 equal_explicit_sets4(avl_set(A),I2,_,_WF) :-
390 is_interval_closure_or_integerset(I2,L2,U2,Finite2),!, % also covers I2=global_set(...)
391 Finite2=finite, % only a finite interval can be equal to an AVL set
392 avl_equal_to_interval(A,L2,U2).
393 equal_explicit_sets4(avl_set(A),global_set(B),_,WF) :- \+ b_global_sets:b_integer_set(B), !, % integersets dealt with above
394 explicit_set_cardinality_wf(global_set(B),Card,WF),
395 is_finite_card(Card), % Card \= inf as avl_set must be finite
396 explicit_set_cardinality_wf(avl_set(A),Card,WF). /* the sets must be identical as global_set contains all values */
397 equal_explicit_sets4(avl_set(A),CPB,_,WF) :-
398 is_cartesian_product_closure(CPB,B1,B2),!,
399 decompose_avl_set_into_cartesian_product_wf(A,A1,A2,WF),
400 kernel_objects:equal_object_wf(A1,B1,equal_explicit_sets4,WF),
401 kernel_objects:equal_object_wf(A2,B2,equal_explicit_sets4,WF).
402 ?equal_explicit_sets4(closure(P,T,B),avl_set(A),E,WF) :- !, equal_explicit_sets4(avl_set(A),closure(P,T,B),E,WF).
403 equal_explicit_sets4(I1,I2,_,WF) :- is_interval_closure_or_integerset(I1,L1,U1,Finite1),
404 is_interval_closure_or_integerset(I2,L2,U2,Finite2), !,
405 Finite1=Finite2, % either both finite or infinite
406 (Finite1=finite
407 -> finite_interval_equality_wf(L1,U1,L2,U2,pred_true,WF) % empty intervals can have different bounds
408 ; L1=L2, U1=U2).
409 equal_explicit_sets4(CPA,CPB,_,WF) :-
410 ? is_cartesian_product_closure(CPA,A1,A2),
411 is_cartesian_product_closure(CPB,B1,B2),!,
412 equal_cartesian_product_wf(A1,A2,B1,B2,WF).
413 % what if both subset or relations or functions ... closure: TO DO: add support
414 equal_explicit_sets4(S1,S2,_,WF) :-
415 is_not_member_value_closure_or_integerset(S1,TYPE,MS1),
416 is_not_member_value_closure_or_integerset(S2,TYPE,MS2),
417 !,
418 kernel_objects:equal_object_wf(MS1,MS2,equal_explicit_sets4,WF).
419 equal_explicit_sets4(closure(P1,T1,B1),closure(P2,T2,B2),_,_WF) :-
420 same_closure_body(P1,T1,B1,P2,T2,B2),!.
421 %equal_explicit_sets4(X,Y) :- X==Y,!.
422 equal_explicit_sets4(Set1,Set2,allow_expansion,WF) :-
423 %kernel_objects:test_finite_set_wf(Set1,F1,WF), kernel_objects:test_finite_set_wf(Set2,F2,WF), equal_expansions(F1,F2,Set1,Set2)
424 card_for_specific_custom_set(Set1,Card1,Code1), % TO DO: do not throw info away if Set2 cannot be determined
425 card_for_specific_custom_set(Set2,Card2,Code2),
426 !,
427 call(Code1), call(Code2),
428 % TO DO: if one of the two sets is infinite, then it would be enough to know that the other is not infinite for failure without expansion
429 equal_expansions(Card1,Card2,Set1,Set2,WF).
430 ?equal_explicit_sets4(Set1,Set2,allow_expansion,WF) :- equal_expansions(0,0,Set1,Set2,WF).
431
432
433 % detect e.g. when one closure has seq(Type) and the other one set(integer,Type)
434 same_types([],[]).
435 same_types([H1|T1],[H2|T2]) :- unify_types_strict(H1,H2), same_types(T1,T2).
436
437 :- block equal_expansions(-,?,?,?,?).
438 equal_expansions(F1,F2,Set1,Set2,WF) :- (number(F1);number(F2)),!,
439 % NOTE: sometimes we get inf for finite but very large sets
440 F1=F2, % unify; can propagate info back to closure; e.g. prj2(BOOL,NAT) = prj2(BOOL,0..n)
441 ? equal_expansions2(F1,F2,Set1,Set2,WF).
442 equal_expansions(F1,F2,Set1,Set2,WF) :-
443 equal_expansions2(F1,F2,Set1,Set2,WF).
444
445 :- block equal_expansions2(-,?,?,?,?), equal_expansions2(?,-,?,?,?).
446 %equal_expansions(0,0,avl_set(A),closure(P,T,B)) :- check_subset ?? in both directions ?
447 %equal_expansions2(inf,inf,Set1,Set2,WF) :- WF \= no_wf_available, !, % symbolic treatment
448 equal_expansions2(F,F,Set1,Set2,WF) :-
449 % only expand if both sets have same cardinality
450 % print_term_summary(equal_expansions3(F,Set1,Set2)),nl,
451 ? equal_expansions3(F,Set1,Set2,WF).
452
453 % TO DO: check if this brings something:
454 %equal_expansions3(avl_set(A),closure(P,T,B),_WF) :- !,
455 % expand_closure_to_avl_or_list(P,T,B,E2,check), % in case E2 is avl_set; we can use equal_avl_tree
456 % ((nonvar(E2),E2=avl_set(B2))
457 % -> print(eql_avl),nl, print_term_summary(equal_avl_tree(A,B2)),nl, equal_avl_tree(A,B2)
458 % ; print(eql_non_avl),nl,equal_object(avl_set(A),E2,equal_expansions3)
459 % ).
460 %:- use_module(library(lists),[perm2/4]).
461 %equal_expansions3(F,Set1,Set2,_WF) :- number(F), F>100, % test with: {{},{TRUE},{FALSE},{TRUE,FALSE}} = /*@symbolic */ {x|x<:BOOL} or
462 % {x|x<:POW(BOOL*BOOL) & (x={} or card(x)>0)} = /*@symbolic */ {x|x<:POW(BOOL*BOOL)} 26 sec -> 14 sec
463 % case does not seem to appear very often
464 % perm2(Set1,Set2,avl_set(_),Set),
465 % is_definitely_maximal_set(Set),
466 %Set2 is maximal and has the same cardinality as F, hence Set1 must be identical to Set2
467 % !,
468 % debug_println(9,equal_to_maximal_closure(F)).
469 equal_expansions3(F,Set1,Set2,WF) :-
470 ? get_identity_as_equivalence(F,Set1,Set2,EQUIV),
471 !,% translate:print_bexpr(EQUIV),nl,
472 opt_push_wait_flag_call_stack_info(WF,b_operator_call(equal,[Set1,Set2],unknown),WF2),
473 copy_wf_start(WF2,equal_expansions,CWF),
474 b_test_boolean_expression(EQUIV,[],[],CWF),
475 copy_wf_finish(WF2,CWF).
476 % Alternative could be, if difference were to be fully treated symbolically:
477 % difference_of_explicit_set_wf(Set1,Set2,R12,WF), difference_of_explicit_set_wf(Set2,Set1,R21,WF),
478 % kernel_objects:empty_set_wf(R12,WF), kernel_objects:empty_set_wf(R21,WF).
479 equal_expansions3(_,Set1,Set2,WF) :-
480 expand_custom_set_wf(Set1,E1,equal_expansions1,WF),
481 expand_custom_set_wf(Set2,E2,equal_expansions2,WF),
482 E1=E2. /* ensure that ordering and normalization is same for all representations ! */
483
484
485 :- use_module(bsyntaxtree, [create_forall/3]).
486 :- use_module(b_ast_cleanup, [clean_up/3]).
487 get_identity_as_equivalence(F,Set1,Set2,CleanedEQUIV) :-
488 (F=inf %; is_infinite_explicit_set(Set1) ; is_infinite_explicit_set(Set2)
489 ; Set1 \= avl_set(_),Set2 \= avl_set(_), % if one of the two sets is an AVL Set: better compute the other set explicitly instead of using this symbolic treatment
490 (dont_expand_this_explicit_set(Set1,100000) ;
491 dont_expand_this_explicit_set(Set2,100000)
492 )
493 % avl_test check for test 1081; TO DO: instead of test try to expand set and if this leads to enum warning use symbolic check
494 ),
495 ? get_identity_as_equivalence_aux(Set1,Set2,EQUIV),
496 clean_up(EQUIV,[],CleanedEQUIV).
497 % can be useful to replace x : {v|P(v)} --> x:P(x) (remove_member_comprehension) and reuse predicates, see 2483
498 get_identity_as_equivalence_aux(Set1,Set2,EQUIV) :-
499 ? kernel_objects:infer_value_type(Set1,S1Type),
500 ? kernel_objects:infer_value_type(Set2,S2Type),
501 merge_types(S1Type,S2Type,SType),
502 is_set_type(SType,Type),
503 % Construct: !x.(x:Set1 <=> x:Set2) ?? see test 2009
504 get_pos_infos_for_explicit_set(Set1,I1),
505 get_pos_infos_for_explicit_set(Set2,I2),
506 I12 = I1, % we could merge position_info; but two sets could be very far apart
507 TID = b(identifier('_equality_sets_'),Type,[]),
508 Mem1 = b(member(TID,b(value(Set1),SType,I1)),pred,I1),
509 Mem2 = b(member(TID,b(value(Set2),SType,I2)),pred,I2),
510 Body1 = b(equivalence(Mem1,Mem2),pred,I12),
511 create_forall([TID],Body1,EQUIV).
512 %translate:print_bexpr(EQUIV),nl.
513
514 :- use_module(bsyntaxtree, [get_texpr_pos/2]).
515 get_pos_infos_for_explicit_set(closure(_,_,Body),[Pos]) :- get_texpr_pos(Body,Pos),!.
516 get_pos_infos_for_explicit_set(_,[]).
517
518 :- use_module(kernel_equality,[eq_atomic/4, equality_objects/3,
519 equality_objects_wf_no_enum/4, equality_objects_with_type_wf/5]).
520 /* maybe rewrite equal_explicit_sets and not_... to use this to avoid maintaining multiple versions */
521 equality_explicit_sets_wf(global_set(X),global_set(Y),R,_WF) :- !, eq_atomic(X,Y,set,R).
522 equality_explicit_sets_wf(global_set(B),avl_set(A),R,WF) :- !,equality_explicit_sets_wf(avl_set(A),global_set(B),R,WF).
523 equality_explicit_sets_wf(freetype(X),freetype(Y),R,_) :- !, eq_atomic(X,Y,set,R).
524 equality_explicit_sets_wf(avl_set(A),avl_set(B),R,_) :- !,
525 (equal_avl_tree(A,B) -> R=pred_true ; R=pred_false). % alternatively, we could normalise avl_trees and only store normalised versions
526 equality_explicit_sets_wf(avl_set(A),I2,R,WF) :- is_interval_closure_or_integerset(I2,L2,U2),!,
527 % also covers I2=global_set(...)
528 avl_equality_to_interval(A,L2,U2,R,WF).
529 equality_explicit_sets_wf(avl_set(A),global_set(B),R,WF) :- \+ b_global_sets:b_integer_set(B), !,
530 explicit_set_cardinality_wf(global_set(B),Card,WF),
531 (is_finite_card(Card), % Card \= inf, %as avl_set must be finite
532 explicit_set_cardinality_wf(avl_set(A),Card,WF)
533 -> R=pred_true /* the sets must be identical as global_set contains all values */
534 ; R=pred_false).
535 equality_explicit_sets_wf(avl_set(A),CPB,R,WF) :-
536 is_cartesian_product_closure(CPB,B1,B2),!,
537 if(decompose_avl_set_into_cartesian_product_wf(A,A1,A2,WF), % should not produce pending co-routines
538 equality_cartesian_product_wf(A1,A2,B1,B2,R,WF),
539 R=pred_false % no cartesian product can be equal to this avl_set
540 ).
541 equality_explicit_sets_wf(closure(P,T,B),avl_set(A),R,WF) :- !,
542 equality_explicit_sets_wf(avl_set(A),closure(P,T,B),R,WF).
543 equality_explicit_sets_wf(I1,I2,R,WF) :- is_interval_closure_or_integerset(I1,L1,U1,Finite1),
544 is_interval_closure_or_integerset(I2,L2,U2,Finite2), !,
545 (Finite1\=Finite2 -> R = pred_false
546 ; Finite1=finite -> finite_interval_equality_wf(L1,U1,L2,U2,R,WF) % empty intervals can have different bounds
547 ; equality_objects_wf_no_enum((int(L1),int(U1)),(int(L2),int(U2)),R,WF)
548 ).
549 equality_explicit_sets_wf(CPA,CPB,R,WF) :-
550 is_cartesian_product_closure(CPA,A1,A2), is_cartesian_product_closure(CPB,B1,B2),!,
551 equality_cartesian_product_wf(A1,A2,B1,B2,R,WF).
552 equality_explicit_sets_wf(S1,S2,R,WF) :-
553 is_not_member_value_closure_or_integerset(S1,TYPE,MS1),
554 is_not_member_value_closure_or_integerset(S2,TYPE,MS2),!,
555 equality_objects_with_type_wf(TYPE,MS1,MS2,R,WF).
556 equality_explicit_sets_wf(closure(P,T,B),closure(P,T,B2),R,_) :-
557 same_texpr_body(B,B2),!,R=pred_true.
558 equality_explicit_sets_wf(Set1,Set2,R,WF) :-
559 Set1 \= [_|_], Set2 \= [_|_], % below we check for avl_set; i.e., useful are only closure/3, global_set/1, ...
560 ? get_identity_as_equivalence(unknown,Set1,Set2,EQUIV),!,
561 opt_push_wait_flag_call_stack_info(WF,b_operator_call(equal,[Set1,Set2],unknown),WF2),
562 copy_wf_start(WF2,equal_expansions,CWF),
563 % EQUIV is a universal quantification, usually over an infinite domain
564 b_interpreter_check:b_force_check_boolean_expression(EQUIV,[],[],CWF,R), % we know EQUIV cannot be reified
565 copy_wf_finish(WF2,CWF).
566 % TO DO: add complement sets,
567
568 /* Cartesian Product Comparison */
569 :- use_module(kernel_equality,[empty_cartesian_product_wf/4]).
570 % A1*A2 = B1*B2 <=> (((A1={} or A2={}) & (B1={} or B2={})) or (A1=B1 & A2=B2))
571 equal_cartesian_product_wf(A1,A2,B1,B2,WF) :-
572 equality_cartesian_product_wf(A1,A2,B1,B2,pred_true,WF).
573 not_equal_cartesian_product_wf(A1,A2,B1,B2,WF) :-
574 equality_cartesian_product_wf(A1,A2,B1,B2,pred_false,WF).
575
576 equality_cartesian_product_wf(A1,A2,B1,B2,R,_WF) :-
577 nonvar(A1), A1=closure(P,T,BdyA1),
578 nonvar(B1), B1=closure(P,T,BdyB1),
579 nonvar(A2), A2=closure(P2,T2,BdyA2),
580 nonvar(B2), B2=closure(P2,T2,BdyB2),
581 % they have the same names; probably we are comparing identical values (e.g., in bvisual2)
582 same_texpr_body(BdyA1,BdyB1),
583 % note: we cannot simply call equality of A2 and B2 as cartesian products can be empty, see test 2072
584 same_texpr_body(BdyA2,BdyB2),
585 !,
586 R=pred_true.
587 equality_cartesian_product_wf(A1,A2,B1,B2,R,WF) :-
588 empty_cartesian_product_wf(A1,A2,EmptyA,WF),
589 equality_cart_product2(EmptyA,A1,A2,B1,B2,R,WF).
590 :- block equality_cart_product2(-, ?,?,?,?,?,?).
591 equality_cart_product2(pred_true,_,_,B1,B2,R,WF) :- empty_cartesian_product_wf(B1,B2,R,WF).
592 equality_cart_product2(pred_false,A1,A2,B1,B2,R,WF) :- equality_objects_wf_no_enum((A1,A2),(B1,B2),R,WF).
593
594 /* COMPARING AVL-SET with INTERVAL */
595
596 % check if an avl tree is equal to an interval range
597 avl_equal_to_interval(_A,L2,U2) :-
598 infinite_interval(L2,U2),!,fail. % otherwise infinite & avl_set is finite
599 % we can now assume L2, U2 are numbers (but could not yet be instantiated)
600 avl_equal_to_interval(A,L2,U2) :-
601 avl_min(A,int(L2)), avl_max(A,int(U2)),
602 Card is 1+U2-L2,
603 explicit_set_cardinality(avl_set(A),Card). % sets are equal: same size + same lower & upper bound
604
605 avl_not_equal_to_interval(A,L2,U2,WF) :- avl_equality_to_interval(A,L2,U2,pred_false,WF).
606
607 avl_equality_to_interval(_A,L2,U2,R,_WF) :-
608 infinite_interval(L2,U2),!,R=pred_false. % interval infinite & avl_set is finite
609 % we can now assume L2, U2 are numbers (but could not yet be instantiated)
610 avl_equality_to_interval(A,L2,U2,R,WF) :-
611 avl_min(A,int(AL)), avl_max(A,int(AU)),
612 Card is 1+AU-AL,
613 explicit_set_cardinality_wf(avl_set(A),ACard,WF),
614 equality_objects_wf_no_enum((int(ACard),(int(AL),int(AU))),
615 (int(Card),(int(L2),int(U2))),R,WF).
616 % sets are equal if same size + same lower & upper bound
617
618
619 % reified equality of two finite intervals L1..U1 and L2..U2
620 % two empty intervals are equal, even if their bounds differ (e.g., 3..1 = 5..2)
621 finite_interval_equality_wf(L1,U1,L2,U2,R,WF) :-
622 b_interpreter_check:check_arithmetic_operator('<=',L1,U1,NonEmpty1),
623 b_interpreter_check:check_arithmetic_operator('<=',L2,U2,NonEmpty2),
624 finite_interval_eq_aux(NonEmpty1,NonEmpty2,L1,U1,L2,U2,R,WF).
625
626 :- block finite_interval_eq_aux(-,-,?,?,?,?,?,?).
627 finite_interval_eq_aux(NonEmpty1,NonEmpty2,_,_,_,_,R,_) :- NonEmpty1==pred_false,!,
628 negate(NonEmpty2,R). % first interval empty: equal iff second also empty
629 finite_interval_eq_aux(NonEmpty1,NonEmpty2,_,_,_,_,R,_) :- NonEmpty2==pred_false,!,
630 negate(NonEmpty1,R).
631 finite_interval_eq_aux(_F1,_F2,L1,U1,L2,U2,R,WF) :-
632 % one interval is non-empty: the intervals are equal iff they have the same bounds
633 (R==pred_false
634 -> dif((L1,U1),(L2,U2)) % relevant for test 1003, /prob_examples/examples/Setlog/prob-ttf/qsee-TransmitMemoryDumpOk21_SP_8.prob
635 % possibly only because enumeration order is change (TODO: investigate)
636 ; equality_objects_wf_no_enum((int(L1),int(U1)),(int(L2),int(U2)),R,WF)
637 ).
638
639 /* COMPARING TWO CLOSURES */
640
641 % a variation of equal_explicit_sets which tries not expand and just compares two closures
642
643 same_closure(I1,I2) :-
644 is_interval_closure_or_integerset(I1,L1,U1,Finite1),
645 is_interval_closure_or_integerset(I2,L2,U2,Finite2), !,
646 Finite1=Finite2,
647 (Finite1=finite, number(L1), number(U1), number(L2), number(U2), L1>U1, L2>U2
648 -> true % two empty intervals
649 ; L1=L2, U1=U2).
650 same_closure(CPA,CPB) :-
651 is_cartesian_product_closure(CPA,A1,A2),
652 is_cartesian_product_closure(CPB,B1,B2),!,
653 equal_cartesian_product_wf(A1,A2,B1,B2,no_wf_available). % could be expensive
654 same_closure(S1,S2) :-
655 is_not_member_value_closure_or_integerset(S1,TYPE,MS1),
656 is_not_member_value_closure_or_integerset(S2,TYPE,MS2),
657 !,
658 kernel_objects:equal_object(MS1,MS2,same_closure). % could be expensive
659 same_closure(closure(P1,T1,B1),closure(P2,T2,B2)) :- same_closure_body_with_parameter_renaming(P1,T1,B1,P2,T2,B2).
660
661 same_closure_body(P,T1, B1, P,T2,B2) :-
662 same_types(T1,T2),
663 same_texpr_body(B1,B2).
664
665 % a version of same_closure_body which allows renaming of the parameters
666 same_closure_body_with_parameter_renaming(P1,T1, B1, P2,T2,B2) :-
667 same_types(T1,T2),
668 create_renaming(P1,P2,Renaming),
669 % TO DO: pass Renaming in AVL tree and rename on the fly
670 rename_bt(B2,Renaming,RenamedB2),
671 same_texpr_body(B1,RenamedB2).
672
673 create_renaming([],[],[]).
674 create_renaming([ID|T1],[ID|T2],TR) :- !, create_renaming(T1,T2,TR).
675 create_renaming([ID1|T1],[ID2|T2],[rename(ID2,ID1)|TR]) :-
676 create_renaming(T1,T2,TR).
677
678
679 % check if two wrapped expressions are equal (modulo associated Info, e.g. source loc info)
680 % and checking inserted values for equality (sometimes storing a closure will convert small inner closures into AVL sets)
681 same_texpr_body(E1,E2) :- empty_avl(E),same_texpr_body(E1,E,E2).
682 same_texpr_body(b(E1,Type1,_),AVL,b(E2,Type2,_)) :-
683 unify_types_strict(Type1,Type2), % check in principle redundant
684 same_texpr2(E1,AVL,E2).
685
686 :- use_module(value_persistance,[cache_is_activated/0]).
687 :- use_module(bsyntaxtree,[safe_syntaxelement_det/5, is_set_type/2,get_texpr_ids/2,
688 get_texpr_expr/2, get_negated_operator_expr/2]).
689 same_texpr2(value(V1),AVL,RHS) :- !,same_texpr_value2(RHS,AVL,V1).
690 same_texpr2(LHS,AVL,value(V2)) :- !,same_texpr_value2(LHS,AVL,V2).
691 same_texpr2(lazy_let_expr(ID,LHS,RHS),AVL,lazy_let_expr(ID2,LHS2,RHS2)) :- !,
692 same_texpr_body(LHS,AVL,LHS2),
693 avl_store(ID,AVL,ID2,NewAVL),
694 same_texpr_body(RHS,NewAVL,RHS2).
695 same_texpr2(lazy_let_pred(ID,LHS,RHS),AVL,lazy_let_pred(ID2,LHS2,RHS2)) :- !,
696 same_texpr_body(LHS,AVL,LHS2),
697 avl_store(ID,AVL,ID2,NewAVL),
698 same_texpr_body(RHS,NewAVL,RHS2).
699 same_texpr2(lazy_lookup(ID1), AVL,lazy_lookup(ID2)) :- !, avl_fetch(ID1,AVL,ID2).
700 same_texpr2(E1,AVL,E2) :- % Should we only enable this for same_closure_body_with_parameter_renaming?
701 quantifier_construct(E1,Functor,TParas1,Body1),
702 quantifier_construct(E2,Functor,TParas2,Body2),
703 !,
704 same_quantified_expression(TParas1,Body1,AVL,TParas2,Body2).
705 same_texpr2(assertion_expression(Pred,MsgStr,EXPR),AVL,assertion_expression(Pred2,MsgStr2,EXPR2)) :- !,
706 (MsgStr==MsgStr2 -> true
707 ; cache_is_activated,
708 debug_println(19,ignoring_difference_in_assertion_msg(MsgStr,MsgStr2))),
709 % difference can happen when constant was computed in other context,
710 % e.g, when cache_is_activated with different position info (with and wo file info, see Debug_6min_zone_du_PAS)
711 % Value-wise MsgStr cannot make a difference; only makes a difference in error message when expr not WD
712 same_texpr_body(Pred,AVL,Pred2),
713 same_texpr_body(EXPR,AVL,EXPR2).
714 same_texpr2(E1,AVL,E2) :-
715 functor(E1,F,Arity),
716 functor(E2,F,Arity),!,
717 safe_syntaxelement_det(E1,Subs1,_Names1,_List1,Constant1),
718 safe_syntaxelement_det(E2,Subs2,_Names2,_List2,Constant2),
719 Constant2==Constant1,
720 same_sub_expressions(Subs1,AVL,Subs2).
721 same_texpr2(E1,AVL,E2) :- same_texpr_with_rewrite(E1,AVL,E2),!.
722 same_texpr2(E1,AVL,E2) :- same_texpr_with_rewrite(E2,AVL,E1).
723 %same_texpr2(E1,_,E2) :-
724 % functor(E1,F1,Arity1),
725 % functor(E2,F2,Arity2), print(not_eq(F1,Arity1,F2,Arity2)),nl, print(E1),nl, print(E2),nl,nl,fail.
726 % some differences: assertion_expression/3 and function/2, ...
727
728 % some rewrite rules from ast_cleanup; but we cannot replicate all rules here
729 same_texpr_with_rewrite(negation(TE1),AVL,E2) :-
730 get_negated_operator_expr(b(E2,pred,[]),NegE2),!,
731 get_texpr_expr(TE1,E1),
732 same_texpr2(E1,AVL,NegE2).
733 same_texpr_with_rewrite(member(X1,b(value(Set1),_,_)),AVL,equal(X2,b(El2,_,_))) :-
734 singleton_set(Set1,El1), !,
735 % X : {El} <===> X = El ; required for JSON trace replay of test 1491
736 same_texpr_body(X1,X2),
737 same_texpr_value2(El2,AVL,El1).
738 same_texpr_with_rewrite(not_member(X1,b(value(Set1),_,_)),AVL,not_equal(X2,b(El2,_,_))) :-
739 singleton_set(Set1,El1), !,
740 % X /: {El} <===> X /= El ; required for JSON trace replay of test 1491
741 same_texpr_body(X1,X2),
742 same_texpr_value2(El2,AVL,El1).
743
744 % constructs with local quantified parameters:
745 quantifier_construct(comprehension_set(TParas,Body),comprehension_set,TParas,Body).
746 quantifier_construct(exists(TParas,Body),exists,TParas,Body).
747 quantifier_construct(forall(TParas,LHS,RHS),forall,TParas,Body) :-
748 Body = b(implication(LHS,RHS),pred,[]).
749 % TODO?: SIGMA, PI, UNION, INTER
750
751 :- use_module(bsyntaxtree,[split_names_and_types/3]).
752 same_quantified_expression(TParas1,Body1,AVL,TParas2,Body2) :-
753 split_names_and_types(TParas1,P1,T1),
754 split_names_and_types(TParas2,P2,T2),
755 same_types(T1,T2),
756 create_renaming(P1,P2,Renaming),
757 rename_bt(Body2,Renaming,RenamedB2), % TODO: store renaming in AVL and lookup on the fly
758 same_texpr_body(Body1,AVL,RenamedB2).
759
760 :- assert_must_succeed((custom_explicit_sets:same_texpr_body(b(value(pred_true),boolean,[]),b(boolean_true,boolean,[])))).
761 :- assert_must_succeed((custom_explicit_sets:same_texpr_body(b(boolean_false,boolean,[]),b(value(pred_false),boolean,[])))).
762 :- assert_must_succeed((custom_explicit_sets:same_texpr_body(b(value(string(abc)),string,[]),b(string(abc),string,[])))).
763 :- assert_must_succeed((custom_explicit_sets:same_texpr_body(b(value(global_set('STRING')),set(string),[]),b(string_set,set(string),[])))).
764 :- assert_must_succeed((custom_explicit_sets:convert_to_avl([int(1),int(2),int(3)],AVL),
765 custom_explicit_sets:same_texpr_body(b(value(AVL),set(integer),[]),
766 b(interval(b(integer(1),integer,[]),b(integer(3),integer,[])),set(integer),[])))).
767 :- assert_must_succeed((custom_explicit_sets:convert_to_avl([int(1),int(2),int(3)],AVL),
768 custom_explicit_sets:same_texpr_body(b(interval(b(integer(1),integer,[]),b(integer(3),integer,[])),set(integer),[]),
769 b(value(AVL),set(integer),[])))).
770 :- assert_must_fail((custom_explicit_sets:convert_to_avl([int(1),int(2),int(3)],AVL),
771 custom_explicit_sets:same_texpr_body(b(value(AVL),set(integer),[]),
772 b(interval(b(integer(1),integer,[]),b(integer(4),integer,[])),set(integer),[])))).
773
774
775 % same_texpr_value2(TExpr2,AVL,Value1) % arg1 was value(Value1)
776 same_texpr_value2(E2,_,V2) :- var(V2),!,V2==E2.
777 same_texpr_value2(value(V2),_,V1) :- !,
778 same_value_inside_closure(V1,V2).
779 %(same_value_inside_closure(V1,V2) -> true ; print(not_eq_vals(V1,V2)),nl,fail).
780 same_texpr_value2(comprehension_set(Paras,B2),AVL,closure(P,_,B1)) :- !,
781 get_texpr_ids(Paras,P),!,
782 same_texpr_body(B1,AVL,B2).
783 same_texpr_value2(cartesian_product(TB1,TB2),AVL,V1) :-
784 decompose_value_into_cartesian_product(V1,A1,A2), !,
785 %print(cart(A1,A2)),nl,
786 get_texpr_expr(TB1,B1),
787 same_texpr_value2(B1,AVL,A1),
788 get_texpr_expr(TB2,B2),
789 same_texpr_value2(B2,AVL,A2).
790 same_texpr_value2(StaticExpr,_,int(Nr)) :- number(Nr),
791 b_ast_cleanup:pre_compute_static_int_expression(StaticExpr,Nr),!.
792 % TO DO: maybe also check if both sides can be evaluated
793 % TO DO: move pre_compute_static_int_expression to another module
794 same_texpr_value2(E2,AVL,Val1) :- rewrite_value(Val1,E2,NewE1),!,
795 same_texpr2(NewE1,AVL,E2).
796 %same_texpr_value2(E1,_,E2) :-
797 % functor(E1,F1,Arity1),
798 % functor(E2,F2,Arity2), print(not_eq_val(F1,Arity1,F2,Arity2)),nl, fail,print(E1),nl, print(E2),nl,nl,fail.
799
800 decompose_value_into_cartesian_product(avl_set(A),A1,A2) :- !,
801 decompose_avl_set_into_cartesian_product_wf(A,A1,A2,no_wf_available).
802 decompose_value_into_cartesian_product(Closure,A1,A2) :- is_cartesian_product_closure(Closure,A1,A2).
803
804
805 % rewrite values back to AST nodes, to help match OtherVal
806 rewrite_value(V,OtherVal,New) :- nonvar(V),
807 rewrite_value_aux(V,OtherVal,New).
808 %rewrite_value(function(Lambda,Argument),assertion_expression(_,_,_),assertion_expression(Cond,Msg,Expr)) :- b_ast_cleanup:rewrite_function_application(Lambda,Argument,[],assertion_expression(Cond,Msg,Expr)).
809 rewrite_value_aux(closure(P,T,B),_,Set) :-
810 is_member_closure(P,T,B,_,Set). % TO DO: ensure that ast_cleanup does not generate useless member closures ?
811 rewrite_value_aux(global_set(GS),_,AST) :-
812 rewrite_glob_set(GS,AST).
813 rewrite_value_aux(avl_set(A),interval(_,_),interval(TLow,TUp)) :- % occurs in JSON trace replay for test 268
814 avl_equal_to_interval(A,Low,Up),
815 TLow = b(integer(Low),integer,[]), TUp = b(integer(Up),integer,[]).
816 rewrite_value_aux(int(A),integer(_),integer(A)) :- number(A).
817 rewrite_value_aux(pred_true,_,boolean_true).
818 rewrite_value_aux(pred_false,_,boolean_false).
819 rewrite_value_aux(string(A),string(_),string(A)) :- % value(string(A)) rewritten to AST node string(A)
820 atom(A).
821
822
823 rewrite_glob_set('REAL',real_set).
824 rewrite_glob_set('FLOAT',float_set).
825 rewrite_glob_set('STRING',string_set).
826 rewrite_glob_set(I,integer_set(I)) :-
827 kernel_objects:integer_global_set(I).
828
829 allow_expansion(avl_set(_),closure(P,T,B)) :-
830 is_small_specific_custom_set(closure(P,T,B),100).
831 allow_expansion(closure(P,T,B),avl_set(_)) :-
832 is_small_specific_custom_set(closure(P,T,B),100).
833
834 same_sub_expressions([],_,[]).
835 same_sub_expressions([H1|T1],AVL,[H2|T2]) :-
836 same_texpr_body(H1,AVL,H2),
837 same_sub_expressions(T1,AVL,T2).
838
839 same_value_inside_closure(V1,V2) :- var(V1),!, V1==V2.
840 same_value_inside_closure(_,V2) :- var(V2),!,fail.
841 same_value_inside_closure(rec(Fields1),rec(Fields2)) :- !,
842 % sets of records come in this form: struct(b(value(rec(FIELDS)),record(_),_))
843 same_fields_inside_closure(Fields1,Fields2).
844 same_value_inside_closure(V1,V2) :-
845 % we could attempt this only if the outer closure was large/infinite ??
846 is_custom_explicit_set(V1), is_custom_explicit_set(V2),
847 !,
848 (allow_expansion(V1,V2) -> EXP=allow_expansion ; EXP = no_expansion),
849 equal_explicit_sets4(V1,V2,EXP,no_wf_available). % usually only sets compiled differently inside closures
850 same_value_inside_closure([H1|T1],avl_set(A2)) :- !, % relevant for JSON trace replay for test 1263
851 try_convert_to_avl([H1|T1],V1), V1=avl_set(A1),
852 equal_avl_tree(A1,A2).
853 same_value_inside_closure(avl_set(A2),[H1|T1]) :- !,
854 try_convert_to_avl([H1|T1],V1), V1=avl_set(A1),
855 equal_avl_tree(A1,A2).
856 same_value_inside_closure(V1,V2) :- V1==V2.
857
858 same_fields_inside_closure(V1,V2) :- var(V1),!, V1==V2.
859 same_fields_inside_closure(_,V2) :- var(V2),!,fail.
860 same_fields_inside_closure([],[]).
861 same_fields_inside_closure([field(Name,V1)|T1],[field(Name,V2)|T2]) :-
862 same_value_inside_closure(V1,V2),
863 same_fields_inside_closure(T1,T2).
864
865 /*
866 same_texpr_body_debug(H1,H2) :-
867 (same_texpr_body(H1,H2) -> true
868 ; print('FAIL: '),nl,
869 translate:print_bexpr(H1),nl, translate:print_bexpr(H2),nl, print(H1),nl, print(H2),nl, fail). */
870
871 %test(Y2,Z2) :- empty_avl(X), avl_store(1,X,2,Y), avl_store(2,X,3,Z),
872 % avl_store(2,Y,3,Y2), avl_store(1,Z,2,Z2), equal_avl_tree(Y2,Z2).
873
874 %equal_avl_tree(A,B) :- avl_min(A,Min), avl_min(B,Min), cmp(Min,A,B).
875 %cmp(El,A,B) :-
876 % (avl_next(El,A,Nxt) -> (avl_next(El,B,Nxt), cmp(Nxt,A,B))
877 % ; \+ avl_next(El,B,Nxt) ).
878
879 % The following is faster than using avl_next
880 equal_avl_tree(A,B) :-
881 % statistics(walltime,[WT1,_]),if(equal_avl_tree2(A,B),true,(statistics(walltime,[_,W]),print(wall(W)),nl)).
882 %equal_avl_tree2(A,B) :-
883 avl_min(A,Min),
884 !,
885 avl_min(B,Min),
886 avl_max(A,Max), avl_max(B,Max),
887 % maybe also check avl_height +/- factor of 1.4405 (page 460, Knuth 3) ? but it seems this would trigger only extremely rarely
888 %avl_height(A,H1), avl_height(A,H2), log(check(Min,Max,H1,H2)),
889 avl_domain(A,L), avl_domain(B,L).
890 equal_avl_tree(empty,B) :- !, format(user_error,'*** Warning: empty AVL tree in equal_avl_tree~n',[]),
891 B=empty.
892 equal_avl_tree(A,B) :- add_internal_error('Illegal AVL tree: ',equal_avl_tree(A,B)),fail.
893
894 /* a predicate to check equality of two custom explicit sets */
895
896 % TO DO: deal with second set being a variable with kernel_cardinality_attr attribute
897 :- block not_equal_explicit_sets_wf(-,?,?), not_equal_explicit_sets_wf(?,-,?).
898 not_equal_explicit_sets_wf(global_set(X),global_set(Y),_) :- !,dif(X,Y).
899 not_equal_explicit_sets_wf(global_set(B),avl_set(A),WF) :- !,
900 \+ equal_explicit_sets4(avl_set(A),global_set(B),allow_expansion,WF).
901 not_equal_explicit_sets_wf(freetype(X),freetype(Y),_) :- !,dif(X,Y).
902 not_equal_explicit_sets_wf(avl_set(A),avl_set(B),_) :- !,
903 \+ equal_avl_tree(A,B).
904 %not_equal_explicit_sets_wf(X,Y,_) :- X==Y,!,fail.
905 not_equal_explicit_sets_wf(avl_set(A),I2,WF) :- is_interval_closure_or_integerset(I2,L2,U2),!, % also covers I2=global_set(...)
906 avl_not_equal_to_interval(A,L2,U2,WF).
907 not_equal_explicit_sets_wf(avl_set(A),global_set(B),WF) :- !,
908 \+ equal_explicit_sets4(avl_set(A),global_set(B),allow_expansion,WF).
909 not_equal_explicit_sets_wf(avl_set(A),CPB,WF) :-
910 is_cartesian_product_closure(CPB,B1,B2),!,
911 if(decompose_avl_set_into_cartesian_product_wf(A,A1,A2,WF), % should not produce pending co-routines, but better safe
912 kernel_objects:not_equal_object_wf((A1,A2),(B1,B2),WF),
913 true % no cartesian product can be equal to this avl_set
914 ).
915 not_equal_explicit_sets_wf(closure(P,T,B),avl_set(A),WF) :- !,
916 not_equal_explicit_sets_wf(avl_set(A),closure(P,T,B),WF).
917 not_equal_explicit_sets_wf(I1,I2,WF) :- is_interval_closure_or_integerset(I1,L1,U1,Finite1),
918 is_interval_closure_or_integerset(I2,L2,U2,Finite2), !,
919 (Finite1=finite, Finite2=finite
920 -> finite_interval_equality_wf(L1,U1,L2,U2,pred_false,WF) % empty intervals can have different bounds
921 ; dif((Finite1,L1,U1),(Finite2,L2,U2))). % maybe we should call not_equal_objects on integers (not on inf values)?
922 not_equal_explicit_sets_wf(CPA,CPB,WF) :-
923 ? is_cartesian_product_closure(CPA,A1,A2), is_cartesian_product_closure(CPB,B1,B2),!,
924 not_equal_cartesian_product_wf(A1,A2,B1,B2,WF).
925 not_equal_explicit_sets_wf(S1,S2,WF) :-
926 is_not_member_value_closure_or_integerset(S1,TYPE,MS1),
927 is_not_member_value_closure_or_integerset(S2,TYPE,MS2),!,
928 kernel_objects:not_equal_object_wf(MS1,MS2,WF).
929 not_equal_explicit_sets_wf(closure(P,T,B),closure(P,T,B2),_) :-
930 same_texpr_body(B,B2),!,fail.
931 % TO DO: maybe support interval & avl_set comparison
932 not_equal_explicit_sets_wf(Set1,Set2,WF) :-
933 card_for_specific_custom_set(Set1,Card1,Code1), card_for_specific_custom_set(Set2,Card2,Code2),
934 call(Code1), call(Code2),!,
935 ? not_equal_expansions(Card1,Card2,Set1,Set2,WF).
936 ?not_equal_explicit_sets_wf(Set1,Set2,WF) :- not_equal_expansions(0,0,Set1,Set2,WF).
937
938
939 :- block not_equal_expansions(-,?,?,?,?), not_equal_expansions(?,-,?,?,?).
940 not_equal_expansions(F1,F2,_,_,_) :- F1 \= F2,!. % sets guaranteed to be different
941 not_equal_expansions(F,F,Set1,Set2,WF) :-
942 ? get_identity_as_equivalence(F,Set1,Set2,EQUIV),
943 !, %write(not),nl,translate:print_bexpr(EQUIV),nl,
944 opt_push_wait_flag_call_stack_info(WF,b_operator_call(equal,[Set1,Set2],unknown),WF2),
945 copy_wf_start(WF2,equal_expansions,CWF),
946 b_not_test_boolean_expression(EQUIV,[],[],CWF),
947 ? copy_wf_finish(WF2,CWF).
948 not_equal_expansions(F,F,Set1,Set2,WF) :-
949 % only expand if both sets have same cardinality
950 expand_custom_set_wf(Set1,E1,not_equal_expansions1,WF),
951 expand_custom_set_wf(Set2,E2,not_equal_expansions2,WF),
952 dif(E1,E2). /* TO DO: ensure that ordering and normalization is same for all representations ! */
953
954
955
956
957 :- use_module(b_global_sets,[b_empty_global_set/1, b_non_empty_global_set/1, b_global_set_cardinality/2]).
958 is_empty_explicit_set_wf(closure(P,T,B),WF) :- !,
959 is_empty_closure_wf(P,T,B,WF).
960 is_empty_explicit_set_wf(S,_WF) :- is_empty_explicit_set(S).
961
962 % with WF we can delay computing Card; see test 1272 / card({x|x:1..10 & x*x<i}) = 0 & i>1
963 % TO DO: ideally we could just write this: is_empty_closure_wf(P,T,B,WF) :- closure_cardinality(P,T,B,0,WF). ; but empty_set / not_exists optimisation not triggered in closure_cardinality (yet); would avoid duplicate code
964 is_empty_closure_wf(P,T,B,WF) :-
965 is_lambda_value_domain_closure(P,T,B, DomainValue,_Expr),!,
966 kernel_objects:empty_set_wf(DomainValue,WF).
967 is_empty_closure_wf(P,T,B,WF) :- is_cartesian_product_closure_aux(P,T,B,A1,A2),!,
968 very_approximate_cardinality(A1,C1,WF),
969 very_approximate_cardinality(A2,C2,WF),
970 blocking_safe_mul(C1,C2,0).
971 is_empty_closure_wf(P,T,B,_WF) :-
972 card_for_specific_closure2(P,T,B,CC,Code),
973 !,
974 call(Code),CC=0.
975 is_empty_closure_wf(P,T,Body,WF) :-
976 WF \== no_wf_available, % only do this if we have a WF store; see comments for closure_cardinality ; code relevant for test 1272; card({x|x:1..10 & x*x<i}) = 0 & i>1
977 \+ ground_bexpr(Body), % otherwise better to use not_test_exists below (e.g., Bosch v6 Codespeed benchmark)
978 b_interpreter_check:reify_closure_with_small_cardinality(P,T,Body, WF, ReifiedList),
979 !,
980 domain(ReifiedList,0,1),
981 sum(ReifiedList,'#=',0).
982 is_empty_closure_wf(P,T,B,WF) :-
983 ? get_recursive_identifier_of_closure_body(B,TRID),!,
984 def_get_texpr_id(TRID,RID),
985 gen_typed_ids(P,T,TypedParas),
986 % now add Recursive ID's value to local state:
987 b_interpreter:b_not_test_exists(TypedParas,B,[used_ids([RID])],[bind(RID,closure(P,T,B))],[],no_compile,WF).
988 is_empty_closure_wf(P,T,B,WF) :- !, % try and check that not(#(P).(B)); i.e., there is no solution for the Body B; solves tests 1542, detecting that {x|x>100 & x mod 102 = 2} = {} is false
989 gen_typed_ids(P,T,TypedParas),
990 b_interpreter:b_not_test_exists(TypedParas,B,[used_ids([])],[],[],no_compile,WF). % used_ids are empty, as all variables already compiled into values
991
992 % very_approximate_cardinality: only required to return 0 for empty set, and number or inf for non-empty set, tested in 1893
993 :- block very_approximate_cardinality(-,?,?).
994 very_approximate_cardinality(avl_set(A),C,_) :- !, (A=empty -> print(empty_avl),nl,C=0 ; C=1).
995 very_approximate_cardinality([],C,_) :- !, C=0.
996 very_approximate_cardinality([_|_],C,_) :- !, C=1.
997 very_approximate_cardinality(Set,C,WF) :- kernel_objects:cardinality_as_int_wf(Set,int(C),WF).
998 % TO DO: maybe call is_empty_closure or similar for closures
999
1000 gen_typed_ids([],[],R) :- !, R=[].
1001 gen_typed_ids([ID|IT],[Type|TT],[b(identifier(ID),Type,[])|TTT]) :- !,
1002 % TO DO: add Info field from outer set comprehension
1003 gen_typed_ids(IT,TT,TTT).
1004 gen_typed_ids(I,T,TI) :- add_internal_error('Call failed: ',gen_typed_ids(I,T,TI)),fail.
1005
1006 % version with WF can also deal with closures via exists !
1007 is_empty_explicit_set(global_set(GS)) :- !, b_empty_global_set(GS).
1008 is_empty_explicit_set(freetype(ID)) :- !, is_empty_freetype(ID).
1009 is_empty_explicit_set(avl_set(A)) :- !,
1010 (var(A) -> add_warning(is_empty_explicit_set,'Variable avl_set')
1011 ; empty_avl(A), add_warning(is_empty_explicit_set,'Empty avl_set')
1012 ).
1013 is_empty_explicit_set(C) :- card_for_specific_closure(C,CC,Code),!,call(Code),CC=0.
1014 is_empty_explicit_set(ES) :- expand_custom_set(ES,[],is_empty_explicit_set).
1015
1016
1017 is_non_empty_explicit_set(CS) :- is_non_empty_explicit_set_wf(CS,no_wf_available).
1018
1019 is_non_empty_explicit_set_wf(global_set(GS),_WF) :- !, b_non_empty_global_set(GS).
1020 is_non_empty_explicit_set_wf(freetype(ID),_WF) :- !, is_non_empty_freetype(ID).
1021 is_non_empty_explicit_set_wf(avl_set(A),_WF) :- !,
1022 (empty_avl(A) -> print('### Warning: empty avl_set (2)'),nl,fail
1023 ; true).
1024 ?is_non_empty_explicit_set_wf(closure(P,T,B),WF) :- !, is_non_empty_closure_wf(P,T,B,WF).
1025 %is_non_empty_explicit_set_wf(ES,_WF) :- expand_custom_set(ES,[_|_],is_non_empty_explicit_set).
1026
1027
1028 % TO DO: this code is a bit redundant with is_empty_closure_wf
1029 is_non_empty_closure_wf(P,T,B,WF) :-
1030 is_lambda_value_domain_closure(P,T,B, DomainValue,_Expr),!,
1031 ? kernel_objects:not_empty_set_wf(DomainValue,WF).
1032 is_non_empty_closure_wf(P,T,B,WF) :- is_cartesian_product_closure_aux(P,T,B,A1,A2),!,
1033 very_approximate_cardinality(A1,C1,WF),
1034 very_approximate_cardinality(A2,C2,WF),
1035 blocking_safe_mul(C1,C2,CC),gt0(CC).
1036 is_non_empty_closure_wf(P,T,B,_WF) :-
1037 card_for_specific_closure2(P,T,B,CC,Code),!,call(Code),gt0(CC).
1038 % TO DO: reify_closure_with_small_cardinality
1039 is_non_empty_closure_wf(P,T,B,WF) :- WF \== no_wf_available,
1040 ? get_recursive_identifier_of_closure_body(B,TRID),!,
1041 def_get_texpr_id(TRID,RID),
1042 gen_typed_ids(P,T,TypedParas),
1043 % now add Recursive ID's value to local state:
1044 b_interpreter:b_test_exists(TypedParas,B,[used_ids([RID])],[bind(RID,closure(P,T,B))],[],WF).
1045 is_non_empty_closure_wf(P,T,B,WF) :- WF \== no_wf_available,
1046 % otherwise enumeration of test_exists will behave strangely; leading to enumeration warnings,... [TO DO: ensure we always have a WF or fix this below ?]
1047 % try and check that not(#(P).(B)); i.e., there is no solution for the Body B; solves tests 1542; test 1146 also triggers this code
1048 (debug_level_inactive_for(19) -> true ; print(non_empty_closure_test(P)),nl, translate:print_bexpr(B),nl),
1049 gen_typed_ids(P,T,TypedParas),
1050 !,
1051 ? b_interpreter:b_test_exists(TypedParas,B,[used_ids([])],[],[],WF). % used_ids are empty, as all variables already compiled into values
1052 % some rules for set_subtraction, ... closures ?? if left part infinite and right part finite it must be infinite
1053 is_non_empty_closure_wf(P,T,B,WF) :-
1054 expand_custom_set_wf(closure(P,T,B),[_|_],is_non_empty_closure_wf,WF).
1055
1056
1057 % TO DO: expand cart / reify and use for pf_test
1058 test_empty_closure_wf(P,T,B,Res,WF) :-
1059 is_lambda_value_domain_closure(P,T,B, DomainValue,_Expr),!,
1060 kernel_equality:empty_set_test_wf(DomainValue,Res,WF).
1061 %test_empty_closure_wf(P,T,B,WF) :- is_cartesian_product_closure_aux(P,T,B,A1,A2),!,
1062 test_empty_closure_wf(P,T,B,Res,_WF) :-
1063 card_for_specific_closure2(P,T,B,CC,Code),!,call(Code),leq0(CC,Res).
1064 test_empty_closure_wf(P,T,B,Res,WF) :-
1065 \+ is_memoization_closure(P,T,B,_MemoID),
1066 preferences:preference(use_closure_expansion_memoization,false),
1067 !,
1068 bexpr_variables(B,ClosureWaitVars),
1069 % this does not perform a few optimisations of expand_normal closure:
1070 % memoization, stored_memo_expansion, is_closure1_value_closure, is_lambda_closure
1071 % print(test_empty_closure_wf),nl, translate:print_bexpr(B),nl,
1072 when((ground(ClosureWaitVars) ; nonvar(Res)),
1073 test_empty_closure_wf2(P,T,B,Res,WF)).
1074 test_empty_closure_wf(P,T,B,Res,WF) :- % print(expand_test(P)),nl,
1075 % was expand_custom_set_wf(closure(P,T,B),ExpES,test_empty_closure_wf,WF), in turn calls expand_closure_to_list
1076 expand_normal_closure(P,T,B,ExpES,_CDone,check(test_empty_closure_wf),WF),
1077 kernel_equality:empty_set_test_wf(ExpES,Res,WF).
1078 % /*@symbolic */ {x|x:1..100000000 & x mod 22=1} = x & (x={} <=> B=TRUE)
1079
1080 test_empty_closure_wf2(P,T,B,Res,WF) :-
1081 Res == pred_true,!,
1082 is_empty_closure_wf(P,T,B,WF).
1083 test_empty_closure_wf2(P,T,B,Res,WF) :- Res == pred_false,!,
1084 is_non_empty_closure_wf(P,T,B,WF).
1085 test_empty_closure_wf2(P,T,B,Res,WF) :-
1086 (is_empty_closure_now(P,T,B,WF) % we need to force expansion here to be able to use local cut ->
1087 % expand_normal_closure would now also expand the closure;
1088 -> Res=pred_true
1089 ; Res=pred_false).
1090
1091 % check if closure now; ground everything except WFE
1092 is_empty_closure_now(P,T,B,OuterWF) :-
1093 create_inner_wait_flags(OuterWF,is_empty_closure_now,WF),
1094 debug_opt_push_wait_flag_call_stack_info(WF,
1095 external_call('Check if empty set',[closure(P,T,B)],unknown),WF2),
1096 is_empty_closure_wf(P,T,B,WF2),
1097 ground_inner_wait_flags(WF2). % does not ground WFE in case WD errors are pending
1098
1099 :- block leq0(-,?).
1100 leq0(inf,Res) :- !, Res=pred_false.
1101 leq0(inf_overflow,Res) :- !, Res=pred_false.
1102 leq0(CC,Res) :- (CC>0 -> Res=pred_false ; Res=pred_true).
1103
1104 test_empty_explicit_set_wf(V,Res,_) :- var(V),!,
1105 add_internal_error('Illegal call: ',test_empty_explicit_set(V,Res,_)),fail.
1106 test_empty_explicit_set_wf(global_set(GS),Res,_WF) :- !,
1107 (b_empty_global_set(GS) -> Res=pred_true ; Res=pred_false).
1108 test_empty_explicit_set_wf(freetype(ID),Res,_WF) :- !, test_empty_freetype(ID,Res).
1109 test_empty_explicit_set_wf(avl_set(A),Res,_WF) :- !,
1110 (var(A) -> add_warning(test_empty_explicit_set_wf,'Variable avl_set'), Res=pred_true
1111 ; empty_avl(A), add_warning(test_empty_explicit_set_wf,'Empty avl_set'), Res = pred_true
1112 ; Res=pred_false).
1113 test_empty_explicit_set_wf(closure(P,T,B),Res,WF) :- !,
1114 test_empty_closure_wf(P,T,B,Res,WF).
1115 test_empty_explicit_set_wf(ES,Res,WF) :-
1116 expand_custom_set(ES,ExpES,test_empty_explicit_set),
1117 kernel_equality:empty_set_test_wf(ExpES,Res,WF).
1118
1119 :- block gt0(-).
1120 gt0(CC) :- (CC=inf -> true ; CC=inf_overflow -> true ; CC>0).
1121
1122 % a version to compute cardinality for
1123 explicit_set_cardinality_for_wf(closure(P,T,B),Card) :-
1124 (is_symbolic_closure_or_symbolic_mode(P,T,B) ; \+ ground_bexpr(B)),
1125 !,
1126 Card = inf. % assume card is infinite for WF computation; it may be finite!
1127 %explicit_set_cardinality_for_wf(avl_set(AVL),Size) :- !, quick_avl_approximate_size(AVL,Size).
1128 explicit_set_cardinality_for_wf(CS,Card) :- card_for_specific_custom_set(CS,Card,Code),!,
1129 on_enumeration_warning(call(Code),Card=inf). % see test 1519 for relevance
1130 explicit_set_cardinality_for_wf(_,inf). % assume card is infinite for WF computation; it may be finite!
1131 % TO DO: maybe never expand closures here !? -> closure_cardinality can expand closure !!!!!!
1132 %explicit_set_cardinality_for_wf(CS,Card) :-
1133 % on_enumeration_warning(
1134 % explicit_set_cardinality(CS,Card),
1135 % (debug_println(assuming_inf_card_for_wf), % see test 1519 for relevance
1136 % Card = inf)). % assume card is infinite for WF computation; it may be finite!
1137
1138 explicit_set_cardinality(CS,Card) :-
1139 % init_wait_flags(WF,[explicit_set_cardinality]), % there are a few checks for no_wf_available below
1140 explicit_set_cardinality_wf(CS,Card,no_wf_available).
1141 % ground_wait_flags(WF).
1142
1143 explicit_set_cardinality_wf(global_set(GS),Card,_) :- !,b_global_set_cardinality(GS,Card).
1144 explicit_set_cardinality_wf(freetype(GS),Card,_WF) :- !, freetype_cardinality(GS,Card).
1145 explicit_set_cardinality_wf(avl_set(S),Card,_WF) :- !,avl_size(S,Card).
1146 ?explicit_set_cardinality_wf(closure(P,T,B),Card,WF) :- closure_cardinality(P,T,B,Card,WF).
1147
1148 closure_cardinality(P,T,B,Card,WF) :-
1149 is_lambda_value_domain_closure(P,T,B, DomainValue,_Expr),!,
1150 kernel_objects:cardinality_as_int_wf(DomainValue,int(Card),WF). % always compute it; card_for_specific_closure will only compute it if it can be done efficiently
1151 closure_cardinality(P,T,B,Card,WF) :- is_cartesian_product_closure_aux(P,T,B,A1,A2),!,
1152 kernel_objects:cardinality_as_int_wf(A1,int(C1),WF),
1153 kernel_objects:cardinality_as_int_wf(A2,int(C2),WF),
1154 blocking_safe_mul(C1,C2,Card).
1155 % TO DO: card_for_specific_closure2 calls is_lambda_value_domain_closure and is_cartesian_product_closure_aux again !
1156 closure_cardinality(P,T,B,Card,_WF) :-
1157 card_for_specific_closure2(P,T,B,CC,Code),
1158 !,
1159 call(Code),Card=CC.
1160 closure_cardinality(P,T,Body,Card,WF) :-
1161 (WF == no_wf_available -> CBody=Body
1162 ? ; b_compiler:b_compile(Body,P,[],[],CBody)
1163 ),
1164 % reify will work better if we used b_compiler:compile so that more sets can be detected as small
1165 closure_cardinality2(P,T,CBody,Card,WF).
1166 closure_cardinality2(P,T,Body,Card,WF) :-
1167 WF \== no_wf_available, % only do this if we have a WF store
1168 ? if(b_interpreter_check:reify_closure_with_small_cardinality(P,T,Body, WF, ReifiedList),
1169 true,
1170 (perfmessagecall(reify,reification_of_closure_for_card_failed(P),translate:print_bexpr(Body),Body),fail)),
1171 !,
1172 domain(ReifiedList,0,1),
1173 sum(ReifiedList,'#=',Card),
1174 % in this case we know card to be finite ! TO DO: ensure that check_finite propagates Card variable
1175 debug_println(9,reified_cardinality_sum(ReifiedList,Card)). % fd_dom(Card,Dom),print(dom(Card,Dom)),nl.
1176 % should we add a special check if Card=0 ? usually Card not instantiated at this point !
1177 %closure_cardinality(P,T,B,Card,WF) :- Card==0, %is_symbolic_closure(P,T,B),
1178 % !, is_empty_closure_wf(P,T,B,WF).
1179 closure_cardinality2(P,T,B,Card,WF) :-
1180 % TO DO: bexpr_variables(ClosureBody,ClosureWaitVars) and wait until those are bound; if Card = 0 -> empty_set; we can try to reifiy again
1181 expand_custom_set_wf(closure(P,T,B),Expansion,closure_cardinality,WF),
1182 my_length(Expansion,0,Card).
1183
1184 :- block my_length(-,?,?).
1185 my_length([],A,A).
1186 my_length([_|T],A,R) :- A1 is A+1, my_length(T,A1,R).
1187
1188 % compute domain and range for specific relations;
1189 % not the closure is total over the domain and surjective over the range
1190 % WARNING: this should never enumerate on its own, it is often called with
1191 % a cut straight after it; if some enumeration happens then only first solution
1192 % will be pursued (e.g., cond_assign_eq_obj)
1193 dom_range_for_specific_closure([],[],[],function(bijection),_WF).
1194 dom_range_for_specific_closure(closure(P,T,Pred),Domain,Range,Functionality,WF) :-
1195 dom_range_for_specific_closure2(P,T,Pred, Domain,Range,dom_and_range,Functionality,WF).
1196
1197 dom_range_for_specific_closure2(Par,Typ,Body, Domain,Range,Required,Functionality,WF) :-
1198 is_member_closure(Par,Typ,Body,_TYPE,SET),
1199 ? dom_range_for_member_closure(SET,Domain,Range,Required,Functionality,WF),!.
1200 dom_range_for_specific_closure2(Par,Typ,Body, DOMAIN,RANGE,_,Functionality,WF) :-
1201 is_cartesian_product_closure_aux(Par,Typ,Body,SET1,SET2),!,
1202 (singleton_set(SET2,_) % checks nonvar
1203 -> Functionality = function(total) % function if card(SET2)=1
1204 ; Functionality=relation),
1205 kernel_equality:empty_set_test_wf(SET1,EqRes1,WF),
1206 cond_assign_eq_obj_wf(EqRes1,RANGE,[],SET2,WF), % if SET1=[] then Range=[]
1207 kernel_equality:empty_set_test_wf(SET2,EqRes2,WF),
1208 cond_assign_eq_obj_wf(EqRes2,DOMAIN,[],SET1,WF). %if SET2=[] then Domain=[]
1209 dom_range_for_specific_closure2(Par,Typ,Body, DomainRange,DomainRange,_,function(bijection),_WF) :-
1210 is_id_closure_over(Par,Typ,Body,DomainRange,_).
1211
1212
1213 dom_range_for_member_closure(identity(b(value(SET1),ST1,_)),SET1,SET1,_,function(bijection),_) :-
1214 is_set_type(ST1,_). /* _SEQT=id(T1) */
1215 dom_range_for_member_closure(closure(V),Domain,Range,Required,Functionality,WF) :- % closure1 transitive closure
1216 % rx : A <-> B <=> closure1(rx) : A <-> B means we can simply remove closure1(.) wrapper
1217 V = b(value(VAL),_,_), nonvar(VAL),
1218 %write(peel_clos1_dom_range(Required)),nl, tools_printing:print_term_summary(closure(V)),nl,
1219 (VAL = closure(P,T,B)
1220 -> dom_range_for_specific_closure2(P,T,B,Domain,Range,Required,Functionality,WF)
1221 ; Functionality = relation, % we do not know if this is going to be a function
1222 (Required=domain_only -> true ; range_of_explicit_set_or_simple_value_wf(VAL,Range,WF)),
1223 (Required=range_only -> true ; domain_of_explicit_set_or_simple_value_wf(VAL,Domain,WF))
1224 ).
1225 dom_range_for_member_closure(Expr,Domain,Range,Required,Functionality,WF) :-
1226 is_comprehension_set_or_closure(Expr,P,T,Pred),
1227 (Required=domain_only
1228 -> Range = term(undefined), dom_for_specific_closure_aux(P,T,Pred, Domain,Functionality,WF)
1229 ; dom_range_for_specific_closure2(P,T,Pred, Domain,Range,Required,Functionality,WF)).
1230
1231
1232 domain_of_explicit_set_or_simple_value_wf([],Domain,_WF) :- !, Domain=[].
1233 domain_of_explicit_set_or_simple_value_wf([H|T],Domain,WF) :- !, T==[], % see test 2102
1234 H = (DomEl,_), equal_object_wf(Domain,[DomEl],domain_of_explicit_set_or_simple_value_wf,WF).
1235 domain_of_explicit_set_or_simple_value_wf(VAL,Domain,WF) :- domain_of_explicit_set_wf(VAL,Domain,WF).
1236
1237 range_of_explicit_set_or_simple_value_wf([],Range,_WF) :- !, Range=[].
1238 range_of_explicit_set_or_simple_value_wf([H|T],Range,WF) :- !, T==[],
1239 H = (_,RanEl), equal_object_wf(Range,[RanEl],range_of_explicit_set_or_simple_value_wf,WF).
1240 range_of_explicit_set_or_simple_value_wf(VAL,Range,WF) :- range_of_explicit_set_wf(VAL,Range,WF).
1241
1242
1243 is_comprehension_set_or_closure(comprehension_set(TP,Pred),P,T,Pred) :- split_names_and_types(TP,P,T).
1244 is_comprehension_set_or_closure(value(V),P,T,Pred) :- nonvar(V), V = closure(P,T,Pred).
1245
1246 % not sure if we need this: memoized functions are infinite usually and range can never be computed anyway
1247 %dom_range_for_member_closure(Expr,Domain,Range,Func) :-
1248 % expand_memoize_stored_function_reference(Expr,ExpandedValue),
1249 % dom_range_for_specific_closure(ExpandedValue,Domain,Range,Func,no_wf_available).
1250
1251 :- block cond_assign_eq_obj_wf(-,?,?,?,?).
1252 %cond_assign_eq_obj_wf(PTF,R,A,B,_) :- var(PTF), add_error(cond_assign_eq_obj,'block declaration bug warning: ',cond_assign_eq_obj(PTF,R,A,B)),fail. % comment in to detect if affected by block declaration bug
1253 cond_assign_eq_obj_wf(pred_true,Res,A,_,WF) :- equal_object_wf(Res,A,cond_assign_eq_obj_wf_1,WF).
1254 cond_assign_eq_obj_wf(pred_false,Res,_,B,WF) :- equal_object_wf(Res,B,cond_assign_eq_obj_wf_2,WF).
1255
1256 is_cartesian_product_closure(closure(Par,Typ,Body),SET1,SET2) :-
1257 ? is_cartesian_product_closure_aux(Par,Typ,Body,SET1,SET2).
1258 is_cartesian_product_closure_aux(Par,Types,b(truth,pred,Info),SET1,SET2) :- Par=[_,_|_],!,
1259 append(LPar,[RParID],Par), append(LTypes,[RType],Types),
1260 construct_closure_if_necessary(LPar,LTypes,b(truth,pred,Info),SET1),
1261 construct_closure_if_necessary([RParID],[RType],b(truth,pred,Info),SET2).
1262 is_cartesian_product_closure_aux(Par,Types,Body,SET1,SET2) :- Par=[_,_|_],!,
1263 append(LPar,[RParID],Par), append(LTypes,[RType],Types),!,
1264 split_conjunct(Body,[RParID], RConjL, LPar, LConjL),
1265 bsyntaxtree:conjunct_predicates(RConjL,RConj), bsyntaxtree:conjunct_predicates(LConjL,LConj),
1266 construct_closure_if_necessary(LPar,LTypes,LConj,SET1),
1267 construct_closure_if_necessary([RParID],[RType],RConj,SET2).
1268 is_cartesian_product_closure_aux(Par,Typ,Body,SET1,SET2) :-
1269 SET = cartesian_product(b(value(SET1),ST1,_), b(value(SET2),ST2,_)),
1270 is_member_closure(Par,Typ,Body,couple(T1m,T2m),SET),
1271 is_set_type(ST1,T1),unify_types_strict(T1,T1m),
1272 is_set_type(ST2,T2),unify_types_strict(T2,T2m),!.
1273 %is_cartesian_product_closure_aux([ID1,ID2],[T1,T2],FBody,SET1,SET2) :- % is this not redundant wrt split ??
1274 % % a closure of the form {ID1,ID2|ID1 : SET1 & ID2 : SET2} ;
1275 % % can get generated when computing domain symbolically of lambda abstraction
1276 % FBody = b(Body,pred,_),
1277 % is_cartesian_product_body(Body,ID1,ID2,T1,T2,SET1,SET2). % ,print(cart_res(SET1,SET2)),nl.
1278
1279 % try and split conjunct into two disjoint parts (for detecting cartesian products)
1280 % on the specified variables
1281 % fails if it cannot be done
1282 split_conjunct(b(PRED,pred,Info),Vars1,C1,Vars2,C2) :-
1283 split_conjunct_aux(PRED,Info,Vars1,C1,Vars2,C2).
1284 split_conjunct_aux(truth,_Info,_Vars1,C1,_Vars2,C2) :- !,C1=[],C2=[].
1285 split_conjunct_aux(conjunct(A,B),_Info,Vars1,C1,Vars2,C2) :- !, % TO DO: use DCG
1286 split_conjunct(B,Vars1,CB1,Vars2,CB2), !, % Note: conjunct_predicates will create inner conjunct in A and atomic Expression in B
1287 split_conjunct(A,Vars1,CA1,Vars2,CA2),!,
1288 append(CA1,CB1,C1), append(CA2,CB2,C2).
1289 split_conjunct_aux(E,Info,Vars1,C1,_Vars2,C2) :- unique_id_comparison(E,ID),!,
1290 (member(ID,Vars1) -> C1=[b(E,pred,Info)], C2=[] ; C1=[], C2=[b(E,pred,Info)]).
1291
1292 unique_id_comparison(less(b(L,_,_),b(R,_,_)), ID) :- unique_id_comparison_aux(L,R,ID).
1293 unique_id_comparison(less_equal(b(L,_,_),b(R,_,_)), ID) :- unique_id_comparison_aux(L,R,ID).
1294 unique_id_comparison(greater(b(L,_,_),b(R,_,_)), ID) :- unique_id_comparison_aux(L,R,ID).
1295 unique_id_comparison(greater_equal(b(L,_,_),b(R,_,_)), ID) :- unique_id_comparison_aux(L,R,ID).
1296 unique_id_comparison(member(b(identifier(ID),_,_),b(V,_,_)), ID) :- explicit_value(V).
1297 unique_id_comparison(subset(b(identifier(ID),_,_),b(V,_,_)), ID) :- explicit_value(V).
1298 unique_id_comparison(equal(b(L,_,_),b(R,_,_)), ID) :- unique_id_comparison_aux(L,R,ID). % means we also detect something like %x.(x : INTEGER|0) as cartesian product
1299 % what about not_equal
1300
1301 unique_id_comparison_aux(identifier(ID),V,ID) :- !,explicit_value(V).
1302 unique_id_comparison_aux(V,identifier(ID),ID) :- explicit_value(V).
1303
1304 explicit_value(value(_)) :- !.
1305 explicit_value(integer(_)) :- !.
1306 explicit_value(unary_minus(TV)) :- !, explicit_tvalue(TV).
1307 explicit_value(interval(TV1,TV2)) :- !,
1308 explicit_tvalue(TV1), explicit_tvalue(TV2).
1309 explicit_value(seq(B)) :- !, explicit_tvalue(B). % usually encoded as values by b_compile
1310 explicit_value(seq1(B)) :- !, explicit_tvalue(B).
1311 explicit_value(iseq(B)) :- !, explicit_tvalue(B).
1312 explicit_value(iseq1(B)) :- !, explicit_tvalue(B).
1313 explicit_value(struct(B)) :- !, explicit_tvalue(B).
1314 explicit_value(rec(Fields)) :- !,
1315 explicit_tfields(Fields). % triggered in test 2274, 2358, 1983, 2388, 2275, 2484
1316 explicit_value(fin_subset(A)) :- !, explicit_tvalue(A).
1317 explicit_value(fin1_subset(A)) :- !, explicit_tvalue(A).
1318 explicit_value(pow_subset(A)) :- !, explicit_tvalue(A).
1319 explicit_value(pow1_subset(A)) :- !, explicit_tvalue(A).
1320 explicit_value(cartesian_product(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1321 explicit_value(total_bijection(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B). % see test 1897 for cases below
1322 explicit_value(total_injection(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1323 explicit_value(total_function(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1324 explicit_value(total_surjection(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1325 explicit_value(partial_function(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1326 explicit_value(partial_injection(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1327 explicit_value(partial_surjection(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1328 explicit_value(relations(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1329 explicit_value(total_relation(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1330 explicit_value(surjection_relation(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1331 explicit_value(total_surjection_relation(A,B)) :- !, explicit_tvalue(A),explicit_tvalue(B).
1332 explicit_value(real_set) :- !.
1333 explicit_value(string_set) :- !.
1334
1335 explicit_tvalue(b(B,_,_)) :- !, explicit_value(B).
1336
1337 explicit_tfields(V) :- var(V),!,fail.
1338 explicit_tfields([]).
1339 explicit_tfields([field(N,V)|T]) :- ground(N),explicit_tvalue(V),explicit_tfields(T).
1340
1341 % conjunct_predicates([CA1,CB1],C1),
1342 % conjunct_predicates([CA2,CB2],C2).
1343
1344 /* *********
1345 is_cartesian_product_body(conjunct(A,B),ID1,ID2,_T1,_T2,SET1,SET2) :- !,
1346 member_pred_value(A,CID1,CSET1),
1347 member_pred_value(B,CID2,CSET2),
1348 (ID1=CID1,ID2=CID2,SET1=CSET1,SET2=CSET2 ; ID1=CID2,ID2=CID1,SET1=CSET2,SET2=CSET1).
1349 is_cartesian_product_body(A,ID1,ID2,T1,T2,SET1,SET2) :-
1350 member_pred_value2(A,AID,ASET),
1351 ( AID=ID1 -> SET1=ASET, construct_closure_if_necessary([ID2],[T2],b(truth,pred,[]),SET2)
1352 ; AID=ID2 -> SET2=ASET, construct_closure_if_necessary([ID1],[T1],b(truth,pred,[]),SET1)).
1353
1354 member_pred_value(b(B,pred,_), ID,VAL) :- print(member_pred_value2(B,ID,VAL)),nl,
1355 member_pred_value2(B,ID,VAL).
1356 member_pred_value2(member(b(identifier(ID),_CT1,_),b(value(VAL),_SCT1,_)), ID,VAL). %_SCT1 = set(CT1)
1357 */
1358
1359 % check if we have POW(SET1) or SET1<->SET2 (equiv. to POW(SET1*SET2))
1360 is_full_powerset_or_relations_or_struct_closure(closure(Par,Typ,Body),SUBSETS) :-
1361 %TYPE = set(T),
1362 is_member_closure(Par,Typ,Body,TYPE,SET),
1363 is_full_powset_aux(SET,TYPE,SUBSETS).
1364
1365 :- use_module(library(lists),[maplist/3, maplist/4]).
1366 is_full_powset_aux(pow_subset(b(value(SET1),set(T1),_)),set(T1),[SET1]).
1367 is_full_powset_aux(relations(S1,S2),set(couple(T1,T2)),[SET1,SET2]) :-
1368 S1 = b(value(SET1),set(T1),_), S2 = b(value(SET2),set(T2),_).
1369 is_full_powset_aux(struct(b(value(rec(FIELDS)),record(_),_)),record(_),FieldValueSets) :-
1370 maplist(get_field_val,FIELDS,FieldValueSets).
1371
1372 get_field_val(field(_,Val),Val).
1373
1374 %[field(duration,global_set('INTEGER')),field(rhythm,global_set('INTEGER')),field(slot,avl_set(...))]
1375
1376 is_powerset_closure(closure(Par,Typ,Body),PType,Subset) :-
1377 is_member_closure(Par,Typ,Body,TYPE,SET),
1378 is_set_type(TYPE,T),
1379 nonvar(SET),
1380 is_powset_aux(SET,PType,b(VS,set(T),_)), % should never be seq(.) type
1381 nonvar(VS), VS = value(Subset). %,print(powerset(Subset)),nl.
1382 is_powset_aux(pow_subset(A),pow,A).
1383 is_powset_aux(pow1_subset(A),pow1,A).
1384 is_powset_aux(fin_subset(A),fin,A).
1385 is_powset_aux(fin1_subset(A),fin1,A).
1386
1387 % group together closures which can be treated like cartesian products in the sense that:
1388 % Closure is empty if either Set1 or Set2 (could also be empty in other conditions though)
1389 % Closure is subset of other Closure if same Constructor and both sets are subsets
1390 /* is_cartesian_product_like_closure(Closure,Constructor,Set1,Set2) :-
1391 is_cartesian_product_closure(Closure,S11,S12),!,
1392 Constructor = cartesian_product,Set1=S11,Set2=S12.
1393 is_cartesian_product_like_closure(closure(Par,Typ,Body),Constructor,Set1,Set2) :-
1394 is_member_closure(Par,Typ,Body,TYPE,SET),
1395 is_cart_like_relation(SET,Constructor,b(value(Set1),set(_T1),_), b(value(Set1),set(_T2),_)).
1396 is_cart_like_relation(relations(A,B),relations,A,B).
1397 is_cart_like_relation(partial_function(A,B),partial_function,A,B).
1398 is_cart_like_relation(partial_injection(A,B),partial_injection,A,B). */
1399
1400 % (closure([_zzzz_unary],[set(couple(integer,string))],b(member(b(identifier(_zzzz_unary),set(couple(integer,string)),[]),b(relations(b(value(global_set(INTEGER)),set(integer),[]),b(value(global_set(STRING)),set(string),[])),set(set(couple(integer,string))),[])),pred,[])))
1401 % 1 1 Fail: custom_explicit_sets:is_powset_aux(relations(b(value(global_set('INTEGER')),set(integer),[]),b(value(global_set('STRING')),set(string),[])),couple(integer,string),_19584) ?
1402
1403 % card_for_specific_custom_set(+Set,-Cardinality,-CodeToComputeCardinality)
1404 % succeeds if card can be computed efficiently
1405 card_for_specific_custom_set(CS,C,Cd) :- var(CS),!,
1406 add_internal_error('Internal error: var ',card_for_specific_custom_set(CS,C,Cd)),fail.
1407 card_for_specific_custom_set(global_set(GS),Card,true) :- !, b_global_set_cardinality(GS,Card).
1408 card_for_specific_custom_set(freetype(Id),Card,true) :- !, freetype_cardinality(Id,Card).
1409 card_for_specific_custom_set(avl_set(S),Card,true) :- !,avl_size(S,Card).
1410 card_for_specific_custom_set(closure(P,T,B),Card,CodeToComputeCard) :-
1411 card_for_specific_closure3(_,P,T,B,Card,CodeToComputeCard).
1412
1413 card_for_specific_closure(closure(P,T,Pred),Card,CodeToComputeCard) :-
1414 card_for_specific_closure3(_ClosureKind,P,T,Pred,Card,CodeToComputeCard).
1415 card_for_specific_closure(closure(P,T,Pred),ClosureKind,Card,CodeToComputeCard) :-
1416 card_for_specific_closure3(ClosureKind,P,T,Pred,Card,CodeToComputeCard).
1417
1418 :- use_module(bsyntaxtree,[is_truth/1]).
1419 card_for_specific_closure2(Par,Typ,Body, Card,Code) :-
1420 card_for_specific_closure3(_ClosureKind,Par,Typ,Body, Card,Code).
1421
1422 :- use_module(kernel_reals,[is_real_interval_closure_with_known_card/4]).
1423 % first argument for debugging purposes or filtering
1424 card_for_specific_closure3(special_closure,Par,Typ,Body, Card,Code) :-
1425 is_special_infinite_closure(Par,Typ,Body),!,Card=inf, Code=true.
1426 card_for_specific_closure3(truth_closure,_,Types,Body,Card,Code) :- is_truth(Body),!,
1427 % TO DO: also treat multiple parameters
1428 couplise_list(Types,Type),
1429 Code=kernel_objects:max_cardinality(Type,Card).
1430 card_for_specific_closure3(interval_closure,Par,Typ,Body, Card,Code) :-
1431 ? is_geq_leq_interval_closure(Par,Typ,Body,Low,Up), !,
1432 card_of_interval_inf(Low,Up,Card),
1433 Code=true. % should we return card_of_interval_inf as code ?
1434 card_for_specific_closure3(real_interval_closure,Par,Typ,Body, Card,Code) :-
1435 ? is_real_interval_closure_with_known_card(Par,Typ,Body,CC), !,
1436 Card=CC, Code=true.
1437 % TO DO: deal with non-infinite not_member_closures, prj1, prj2, id, ...
1438 card_for_specific_closure3(lambda_closure,Par,Typ,Body, Card,Code) :-
1439 is_lambda_value_domain_closure(Par,Typ,Body, DomainValue,_Expr),!, nonvar(DomainValue),
1440 efficient_card_for_set(DomainValue,Card,Code).
1441 card_for_specific_closure3(cartesian_product,Par,Typ,Body, Card,Code) :-
1442 is_cartesian_product_closure_aux(Par,Typ,Body,A1,A2),!,
1443 card_for_cartesian_product_of_values(A1,A2,Card,Code).
1444 card_for_specific_closure3(member_closure,Par,Typ,Body, Card,Code) :-
1445 is_member_closure(Par,Typ,Body,TYPE,SET),
1446 nonvar(SET),!,
1447 card_for_member_closure(SET,TYPE,Card,Code).
1448 % Note: _ExprInfo could have: contains_wd_condition,
1449 % but if lambda is well-defined we compute the correct card ; if not then card is not well-defined anyway
1450 % maybe we should check contains_wd_condition produce a warning msg ?
1451
1452 % generate code to compute card for cartesian product closure of two values A and B
1453 card_for_cartesian_product_of_values(A1,A2,Card,Code) :- nonvar(A1), nonvar(A2),
1454 efficient_card_for_set(A1,Card1,Code1),
1455 efficient_card_for_set(A2,Card2,Code2),
1456 Code = (Code1,Code2, custom_explicit_sets:blocking_safe_mul(Card1,Card2,Card)).
1457
1458
1459 % inner values can sometimes be a list, e.g., [pred_true,pred_false] for BOOL
1460 efficient_card_for_set(VAR,_,_) :- var(VAR),!,fail.
1461 efficient_card_for_set([],Card,Code) :- !, Card=0,Code=true.
1462 efficient_card_for_set([_|T],Card,Code) :- known_length(T,1,C), !, Card = C, Code=true.
1463 efficient_card_for_set(CS,Card,Code) :- card_for_specific_custom_set(CS,Card,Code).
1464 known_length(X,_,_) :- var(X),!,fail.
1465 known_length([],A,A).
1466 known_length([_|T],A,R) :- A1 is A+1, known_length(T,A1,R).
1467 known_length(avl_set(S),Acc,Res) :- avl_size(S,Card),
1468 Res is Acc+Card.
1469 % TO DO: also support closures
1470
1471 card_for_member_closure(cartesian_product(A,B),_T,Card,CodeToComputeCard) :- !,
1472 A = b(value(AVal),_,_), B = b(value(BVal),_,_), % TODO: do we need to generalise this?
1473 card_for_cartesian_product_of_values(AVal,BVal,Card,CodeToComputeCard).
1474 card_for_member_closure(parallel_product(A,B),_T,Card,CodeToComputeCard) :- !,
1475 A = b(value(AVal),_,_), B = b(value(BVal),_,_),
1476 card_for_cartesian_product_of_values(AVal,BVal,Card,CodeToComputeCard).
1477 % cardinality computed like for cartesian_product.
1478 card_for_member_closure(seq(b(Value,ST1,_)),_SEQT,Card,CodeToComputeCard) :- !, /* _SEQT=seq(T1) */
1479 is_set_type(ST1,_T1),
1480 get_cart_product_of_values_for_emptiness_check(Value,ListOfSets), % accept a value or cartesian product of values
1481 CodeToComputeCard = custom_explicit_sets:seq_card_of_cart_product(ListOfSets,1,Card). % Card is 1 or inf
1482 card_for_member_closure(seq1(b(Value,ST1,_)),_SEQT,Card,CodeToComputeCard) :- !, /* _SEQT=seq1(T1) */
1483 is_set_type(ST1,_T1),
1484 get_cart_product_of_values_for_emptiness_check(Value,ListOfSets), % accept a value or cartesian product of values
1485 CodeToComputeCard = custom_explicit_sets:seq_card_of_cart_product(ListOfSets,0,Card). % Card is 0 or inf
1486 card_for_member_closure(perm(b(value(SET1),ST1,_)),_SEQT,Card,CodeToComputeCard) :- !, /* _SEQT=perm(T1) */
1487 is_set_type(ST1,_T1),
1488 CodeToComputeCard = (kernel_objects:cardinality_as_int(SET1,int(SCard)),
1489 custom_explicit_sets:blocking_factorial(SCard,Card)).
1490 card_for_member_closure(iseq(b(value(SET1),ST1,_)),_SEQT,Card,CodeToComputeCard) :- !, /* _SEQT=iseq(T1) */
1491 is_set_type(ST1,_T1),
1492 CodeToComputeCard = (kernel_objects:cardinality_as_int(SET1,int(SCard)),
1493 kernel_card_arithmetic:blocking_nr_iseq(SCard,Card)).
1494 card_for_member_closure(iseq1(b(value(SET1),ST1,_)),_SEQT,Card,CodeToComputeCard) :- !, /* _SEQT=iseq1(T1) */
1495 is_set_type(ST1,_T1),
1496 CodeToComputeCard = (kernel_objects:cardinality_as_int(SET1,int(SCard)),
1497 kernel_card_arithmetic:blocking_nr_iseq1(SCard,Card)).
1498 card_for_member_closure(identity(b(value(SET1),ST1,_)),_SEQT,Card,CodeToComputeCard) :- !, /* _SEQT=id(T1) */
1499 is_set_type(ST1,_T1),
1500 CodeToComputeCard =
1501 kernel_objects:cardinality_as_int(SET1,int(Card)).
1502 card_for_member_closure(struct(b(RecVal,record(_FieldSetTypes),_)), record(_FieldTypes), % set of records
1503 Card,CodeToComputeCard) :-
1504 !,
1505 (RecVal=value(RECF), nonvar(RECF), RECF=rec(FIELDS) % value has been computed:
1506 -> CodeToComputeCard = custom_explicit_sets:get_field_cardinality(FIELDS,Card)
1507 ; RecVal = rec(TypedFields), % we still have a typed AST
1508 maplist(get_field_val_type,TypedFields,Exprs,Types),
1509 l_card_for_member_closure(Exprs,Types,Card, CodeToComputeCard)
1510 ).
1511 card_for_member_closure(value(Value), _Type, Card,CodeToComputeCard) :- !,
1512 % we have a closure of the type {x|x:S}; equivalent to S
1513 (nonvar(Value),
1514 Value=closure(P,T,B)
1515 -> % cardinality_as_int may expand it ! is bad if e.g. we called this code to check if a closure is infinite
1516 card_for_specific_closure2(P,T,B,Card,CodeToComputeCard) % will not expand, but fail if cannot be computed
1517 % TO DO: provide an argument: precise_or_efficient
1518 ; CodeToComputeCard = kernel_objects:cardinality_as_int(Value,int(Card))
1519 ).
1520 card_for_member_closure(comprehension_set(TP,B), _Type, Card,CodeToComputeCard) :- !, % see test 2571
1521 split_names_and_types(TP,P,T), % what if Body reads variables; b_compile should have removed them??
1522 card_for_specific_closure3(_ClosureKind,P,T,B,Card,CodeToComputeCard).
1523 % now dealt with separately above: card_for_member_closure(cartesian_product(b(value(SET1),set(T1),_), b(value(SET2),set(T2),_)),
1524 % couple(T1,T2), Card,CodeToComputeCard) :- !,
1525 % CodeToComputeCard =
1526 % (kernel_objects:cardinality_as_int(SET1,int(SCard1)),
1527 % kernel_objects:cardinality_as_int(SET2,int(SCard2)),
1528 % custom_explicit_sets:blocking_safe_mul(SCard1,SCard2,Card) ).
1529 card_for_member_closure(POW,TYPE, Card,CodeToComputeCard) :-
1530 (POW = pow_subset(b(value(SET),TYPE,_)) ;
1531 POW = fin_subset(b(value(SET),TYPE,_))),!,
1532 CodeToComputeCard =
1533 (kernel_objects:cardinality_as_int(SET,int(SCard)),
1534 custom_explicit_sets:blocking_safe_pow2(SCard,Card)
1535 ).
1536 card_for_member_closure(POW,TYPE, Card,CodeToComputeCard) :-
1537 (POW = pow1_subset(b(value(SET),TYPE,_)) ;
1538 POW = fin1_subset(b(value(SET),TYPE,_))),!,
1539 CodeToComputeCard =
1540 (kernel_objects:cardinality_as_int(SET,int(SCard)),
1541 custom_explicit_sets:blocking_safe_pow2(SCard,C1),
1542 custom_explicit_sets:safe_dec(C1,Card)
1543 ).
1544 card_for_member_closure(RELEXPR,SType, Card,CodeToComputeCard) :-
1545 is_set_type(SType,couple(T1,T2)),
1546 is_a_relation(RELEXPR, b(value(DOM),set(T1),_),
1547 b(value(RAN),set(T2),_), DCard,RCard,Card,RELCODE),!,
1548 CodeToComputeCard =
1549 (
1550 kernel_objects:cardinality_as_int(DOM,int(DCard)),
1551 kernel_objects:cardinality_as_int(RAN,int(RCard)),
1552 custom_explicit_sets:call_card_for_relations(DCard,RCard,RELCODE)
1553 ).
1554 card_for_member_closure(BODY, integer, Card,CodeToComputeCard) :-
1555 is_interval_with_integer_bounds(BODY,Low,Up),!,
1556 CodeToComputeCard = custom_explicit_sets:card_of_interval_inf(Low,Up,Card).
1557 %card_for_member_closure(BODY, Type, Card,CodeToComputeCard) :- print(try_card(BODY,Type)),nl,fail.
1558 % TO DO: add maybe other common closures ? simple value closure
1559 % also: what if subexpressions are not of value() type ?
1560
1561 :- public call_card_for_relations/3.
1562 :- block call_card_for_relations(-,?,?), call_card_for_relations(?,-,?).
1563 call_card_for_relations(_,_,RELCODE) :- call(RELCODE).
1564
1565 get_field_val_type(field(_F1,b(Expr1,Type1,_)),Expr1,Type1).
1566
1567 l_card_for_member_closure([Expr1],[Type1],Card,CodeToComputeCard) :- !,
1568 card_for_member_closure(Expr1,Type1,Card, CodeToComputeCard).
1569 l_card_for_member_closure([Expr1|ET],[Type1|TT],Card,CodeToComputeCard) :-
1570 CodeToComputeCard = (Code1,Code2, custom_explicit_sets:blocking_safe_mul(Card1,Card2,Card)),
1571 card_for_member_closure(Expr1,Type1,Card1, Code1),
1572 l_card_for_member_closure(ET,TT,Card2,Code2).
1573
1574 :- public safe_dec/2. % used in card_for_member_closure
1575 :- block safe_dec(-,?).
1576 safe_dec(inf,R) :- !, R=inf.
1577 safe_dec(inf_overflow,R) :- !, R=inf_overflow.
1578 safe_dec(X,R) :- R is X-1.
1579
1580 :- use_module(kernel_equality,[empty_set_test/2]).
1581 :- public seq_card/3. % used in card_for_member_closure
1582 :- block seq_card(-,?,?).
1583 seq_card([],EmptyVal,R) :- !,R=EmptyVal.
1584 seq_card([_|_],_,R) :- !,R=inf.
1585 seq_card(X,EmptyVal,Res) :- empty_set_test(X,EqRes),
1586 set_card_or_inf(EqRes,EmptyVal,Res).
1587
1588 :- block set_card_or_inf(-,?,?).
1589 set_card_or_inf(pred_true,Nr,Nr).
1590 set_card_or_inf(pred_false,_,inf).
1591 % card(seq({n|n>10 & (n mod 20=3 & n mod 20 = 4) }))
1592
1593 % for list [S1,S2,...,Sn] of sets we compute
1594 % cardinality of seq(1)( S1 ** S2 ... ** Sn) to be either 0/1 (if one set is empty) or inf (if all sets are non-empty)
1595 :- public seq_card_of_cart_product/3. % used in card_for_member_closure
1596 :- assert_must_succeed((custom_explicit_sets:seq_card_of_cart_product([[int(1)],[int(2)]],1,R), R==inf)).
1597 :- assert_must_succeed((custom_explicit_sets:seq_card_of_cart_product([[int(1)],[int(2)],[]],1,R), R==1)).
1598 :- assert_must_succeed((custom_explicit_sets:seq_card_of_cart_product([[int(1)],[],[int(2)]],0,R), R==0)).
1599 :- assert_must_succeed((custom_explicit_sets:seq_card_of_cart_product([[],[int(2)]],0,R), R==0)).
1600 seq_card_of_cart_product([Set],EmptyCard,Res) :- !,
1601 seq_card(Set,EmptyCard,Res).
1602 seq_card_of_cart_product([Set1|T],EmptyCard,Res) :-
1603 seq_card(Set1,EmptyCard,Res1),
1604 (Res1==EmptyCard -> Res=Res1
1605 ; combine_card(Res1,Res2,Res),
1606 seq_card_of_cart_product(T,EmptyCard,Res2)
1607 ).
1608
1609 % combine cardinalities of either 0/1 and inf
1610 :- block combine_card(-,-,?).
1611 combine_card(X,Y,R) :- X==inf,!,R=Y.
1612 combine_card(X,Y,R) :- Y==inf,!,R=X.
1613 combine_card(X,_,R) :- integer(X),!,R=X.
1614 combine_card(_,R,R).
1615
1616 % get a list of set values for emptiness check: the Value is the empty set iff one element in the list is empty
1617 % it accepts a value or a cartesian product of values
1618 % the result will be used for emptyness check and should NOT be used to compute the cardinality
1619 get_cart_product_of_values_for_emptiness_check(Value,ListOfSetValues) :-
1620 get_cart_product_of_values(Value,ListOfSetValues,[]). %write(get_cart(ListOfSetValues)),nl,nl.
1621 get_cart_product_of_values(value(SET)) --> !, [SET].
1622 get_cart_product_of_values(cartesian_product(A,B)) --> !,
1623 tcart_product_of_values(A), tcart_product_of_values(B).
1624 get_cart_product_of_values(pow_subset(_)) --> !, [ [[]] ]. % create some non-empty set; POW({}) = {{}} is not empty
1625 get_cart_product_of_values(fin_subset(_)) --> !, [ [[]] ]. % ditto
1626 get_cart_product_of_values(seq(_)) --> !, [ [[]] ]. % ditto, the empty sequence [] is always in seq(S)
1627 get_cart_product_of_values(iseq(_)) --> !,[ [[]] ]. % ditto
1628 get_cart_product_of_values(pow1_subset(A)) --> !, tcart_product_of_values(A). % POW1(S)={} <=> S={}
1629 get_cart_product_of_values(fin1_subset(A)) --> !, tcart_product_of_values(A). % FIN1(S)={} <=> S={}
1630 get_cart_product_of_values(seq1(A)) --> !, tcart_product_of_values(A). % seq1(S)={} <=> S={}
1631 get_cart_product_of_values(iseq1(A)) --> !, tcart_product_of_values(A). % iseq1(S)={} <=> S={}
1632 %get_cart_product_of_values(X) --> {functor(X,F,N), write(uncov_get_cart(F,N)),nl,fail}.
1633 % TODO: records,relations,...
1634
1635 tcart_product_of_values(b(E,_,_)) --> get_cart_product_of_values(E).
1636
1637
1638
1639 :- public get_field_cardinality/2. % used in card_for_member_closure
1640 get_field_cardinality([],1).
1641 get_field_cardinality([field(_Name,Value)|T],ResCard) :-
1642 kernel_objects:cardinality_as_int(Value,int(SCard1)),
1643 get_field_cardinality(T,RestCard), blocking_safe_mul(SCard1,RestCard,ResCard).
1644
1645 :- use_module(kernel_card_arithmetic).
1646
1647 :- block blocking_safe_mul(-,-,?).
1648 blocking_safe_mul(A,B,R) :-
1649 ( A==0 -> R=0
1650 ; B==0 -> R=0
1651 ; A==1 -> R=B
1652 ; B==1 -> R=A
1653 ; blocking_safe_mul2(A,B,R) ).
1654
1655 :- block blocking_safe_mul2(-,?,?), blocking_safe_mul2(?,-,?).
1656 blocking_safe_mul2(A,B,Res) :-
1657 (safe_mul(A,B,AB) -> Res=AB
1658 ; add_warning(blocking_safe_mul2,'Call failed: ',blocking_safe_mul2(A,B,Res)),
1659 % could happen for something like prj2(BOOL,NAT) = prj2(BOOL,0..n)
1660 fail).
1661
1662 :- public blocking_safe_pow2/2. % used in card_for_member_closure above
1663 :- block blocking_safe_pow2(-,?).
1664 blocking_safe_pow2(A,Res) :-
1665 (safe_pow2(A,A2) -> Res=A2
1666 ; add_warning(blocking_safe_pow2,'Call failed: ',safe_pow2(A,Res)),fail).
1667
1668
1669
1670
1671 :- assert_must_succeed((custom_explicit_sets:card_for_specific_closure2(['_zzzz_binary'],[integer],
1672 b(member(b(identifier('_zzzz_binary'),integer,[generated]),
1673 b(interval(b(value(int(1)),integer,[]),b(value(int(10)),integer,[])),set(integer),[])),pred,[]),R,C),
1674 call(C),
1675 R=10)).
1676
1677 %! is_interval_closure_or_integerset(+I,-L,-U)
1678 is_interval_closure_or_integerset(Var,_,_) :- var(Var),!,fail.
1679 is_interval_closure_or_integerset(global_set(X),Low,Up) :- !, get_integer_set_interval(X,Low,Up).
1680 is_interval_closure_or_integerset(Set,El,El) :- singleton_set(Set,ELX),
1681 nonvar(ELX), ELX=int(El),!. % new, useful??
1682 is_interval_closure_or_integerset(closure(P,T,B),Low,Up) :-
1683 ? (is_geq_leq_interval_closure(P,T,B,Low,Up) -> true ; is_interval_closure(P,T,B,Low,Up)).
1684
1685 % with an additional argument to know if the set is finite or infinite:
1686 is_interval_closure_or_integerset(Set,Low,Up,Finite) :-
1687 is_interval_closure_or_integerset(Set,Low,Up),
1688 % if we obtain Low, Up as variables then these must be finite numbers; they cannot stand for inf
1689 (infinite_interval(Low,Up) -> Finite=infinite ; Finite=finite).
1690
1691 % a version that also accepts real intervals
1692 :- use_module(kernel_reals,[is_interval_closure_or_realset/3]).
1693 is_interval_closure_or_numberset(Set,Low,Up) :- is_interval_closure_or_integerset(Set,L,U),!, Low=L,Up=U.
1694 ?is_interval_closure_or_numberset(Set,Low,Up) :- is_interval_closure_or_realset(Set,Low,Up).
1695
1696 get_integer_set_interval('NAT',0,MAXINT) :- (preferences:preference(maxint,MAXINT)->true).
1697 get_integer_set_interval('NAT1',1,MAXINT) :- (preferences:preference(maxint,MAXINT)->true).
1698 get_integer_set_interval('INT',MININT,MAXINT) :-
1699 ((preferences:preference(maxint,MAXINT),preferences:preference(minint,MININT))->true).
1700 get_integer_set_interval('NATURAL',0,inf).
1701 get_integer_set_interval('NATURAL1',1,inf).
1702 get_integer_set_interval('INTEGER',minus_inf,inf).
1703 % TO DO: add minus_inf to kernel_objects !
1704
1705 :- block geq_inf(-,?), geq_inf(?,-).
1706 geq_inf(inf,_) :- !.
1707 geq_inf(minus_inf,B) :- !, B=minus_inf.
1708 geq_inf(_,minus_inf) :- !.
1709 geq_inf(A,inf) :- !, A=inf.
1710 geq_inf(inf_overflow,_) :- !.
1711 geq_inf(A,inf_overflow) :- !, A=inf_overflow.
1712 geq_inf(A,B) :- A >= B.
1713
1714 :- block minimum_with_inf(-,-,?).
1715 % in the first three cases we can determine outcome without knowing both args
1716 minimum_with_inf(A,B,R) :- (A==minus_inf ; B==minus_inf),!,R=minus_inf.
1717 minimum_with_inf(A,B,R) :- A==inf,!,R=B.
1718 minimum_with_inf(A,B,R) :- B==inf,!,R=A.
1719 minimum_with_inf(A,B,R) :- minimum_with_inf1(A,B,R), geq_inf(A,R), geq_inf(B,R).
1720 :- block minimum_with_inf1(-,?,?), minimum_with_inf1(?,-,?).
1721 minimum_with_inf1(minus_inf,_,R) :- !, R=minus_inf.
1722 minimum_with_inf1(_,minus_inf,R) :- !, R=minus_inf.
1723 minimum_with_inf1(inf,B,R) :- !, R=B.
1724 minimum_with_inf1(A,inf,R) :- !, R=A.
1725 minimum_with_inf1(inf_overflow,B,R) :- !, R=B.
1726 minimum_with_inf1(A,inf_overflow,R) :- !, R=A.
1727 minimum_with_inf1(A,B,R) :- (A<B -> R=A ; R=B).
1728
1729 :- block maximum_with_inf(-,-,?).
1730 % in the first three cases we can determine outcome without knowing both args
1731 maximum_with_inf(A,B,R) :- (A==inf ; B==inf),!,R=inf.
1732 maximum_with_inf(A,B,R) :- A==minus_inf,!,R=B.
1733 maximum_with_inf(A,B,R) :- B==minus_inf,!,R=A.
1734 maximum_with_inf(A,B,R) :- maximum_with_inf1(A,B,R), geq_inf(R,A), geq_inf(R,B).
1735 :- block maximum_with_inf1(-,?,?), maximum_with_inf1(?,-,?).
1736 maximum_with_inf1(inf,_,R) :- !, R=inf.
1737 maximum_with_inf1(_,inf,R) :- !, R=inf.
1738 maximum_with_inf1(minus_inf,B,R) :- !, R=B.
1739 maximum_with_inf1(A,minus_inf,R) :- !, R=A.
1740 maximum_with_inf1(inf_overflow,_,R) :- !, R=inf_overflow.
1741 maximum_with_inf1(_,inf_overflow,R) :- !, R=inf_overflow.
1742 maximum_with_inf1(A,B,R) :- (A>B -> R=A ; R=B).
1743
1744 /* utilities for detecting interval closures */
1745 construct_interval_closure(Low,Up,Res) :- (Low==inf;Up==minus_inf),!,Res=[].
1746 construct_interval_closure(Low,Up,Res) :- number(Low),number(Up), Low>Up,!,Res=[].
1747 construct_interval_closure(Low,Up,Res) :- Up==inf,!,
1748 ( Low==0 -> Res = global_set('NATURAL')
1749 ; Low==1 -> Res = global_set('NATURAL1')
1750 ; Low==minus_inf -> Res = global_set('INTEGER')
1751 ; Low==inf -> Res = []
1752 ; construct_greater_equal_closure(Low,Res)
1753 ).
1754 construct_interval_closure(Low,Up,Res) :- Low==minus_inf,!,
1755 construct_less_equal_closure(Up,Res).
1756 construct_interval_closure(Low,Up,Res) :- Low==Up,!,
1757 (number(Low) -> construct_one_element_custom_set(int(Low),Res)
1758 ; Res = [int(Low)]).
1759 construct_interval_closure(Low,Up,Res) :-
1760 construct_interval_set(Low,Up,Set),
1761 construct_member_closure('_zzzz_unary',integer,[],Set,Res).
1762
1763 transform_global_sets_into_closure(closure(P,T,B),closure(P,T,B)).
1764 transform_global_sets_into_closure(global_set(X),Res) :-
1765 transform_global_set_into_closure_aux(X,Res).
1766 transform_global_set_into_closure_aux('NATURAL',Res) :-
1767 construct_greater_equal_closure(0,Res).
1768 transform_global_set_into_closure_aux('NATURAL1',Res) :-
1769 construct_greater_equal_closure(1,Res).
1770 % TO DO: add INTEGER
1771
1772
1773
1774 is_geq_leq_interval_closure([Par],[integer],b(Body,pred,Span),Low,Up) :-
1775 (var(Par)
1776 -> add_internal_error('Non-ground closure: ',closure([Par],[integer],b(Body,pred,Span))),fail
1777 ? ; get_geq_leq_bounds(Body,Par,Low,Up)).
1778
1779 infinite_interval(Low,Up) :- (Low==minus_inf -> true ; Up==inf).
1780
1781 :- assert_must_succeed((card_of_interval_inf(1,10,10))).
1782 :- assert_must_succeed((card_of_interval_inf(1,inf,R),R==inf)).
1783 :- assert_must_succeed((card_of_interval_inf(_,inf,R),R==inf)).
1784 :- assert_must_succeed((card_of_interval_inf(minus_inf,0,R),R==inf)).
1785 :- assert_must_succeed((card_of_interval_inf(minus_inf,_,R),R==inf)).
1786 :- assert_must_succeed((card_of_interval_inf(minus_inf,inf,R),R==inf)).
1787 :- assert_must_succeed((card_of_interval_inf(2,2,R), R==1)).
1788 :- assert_must_succeed((card_of_interval_inf(12,2,R), R==0)).
1789 :- assert_must_succeed((card_of_interval_inf(2,B,10), B==11)).
1790 :- assert_must_succeed((card_of_interval_inf(A,12,10), A==3)).
1791 :- assert_must_succeed((card_of_interval_inf(A,12,0), A=222)).
1792 :- assert_must_succeed((card_of_interval_inf(12,B,0), B=11)).
1793 :- assert_must_fail((card_of_interval_inf(A,12,0), A=12)).
1794 % compute cardinality of interval; allow bounds to be inf and minus_inf (but if so, they must be bound straightaway)
1795 card_of_interval_inf(A,B,Card) :-
1796 ? at_least_two_vars(A,B,Card), % initially this will usually be true, if only one variable we can compute result
1797 preferences:preference(use_clpfd_solver,true),
1798 !,
1799 clpfd_interface:post_constraint(Card #= max(0,1+B-A),custom_explicit_sets:block_card_of_interval_inf(A,B,Card)).
1800 card_of_interval_inf(A,B,Card) :- A==minus_inf,!,
1801 (B==minus_inf -> add_internal_error('Illegal call: ',card_of_interval_inf(A,B,Card)) ; true),
1802 Card=inf.
1803 card_of_interval_inf(A,B,Card) :- B==inf,!,
1804 (A==inf -> add_internal_error('Illegal call: ',card_of_interval_inf(A,B,Card)) ; true),
1805 Card=inf.
1806 card_of_interval_inf(A,B,Card) :- block_card_of_interval_inf(A,B,Card).
1807
1808 ?at_least_two_vars(A,B,C) :- var(A),!,(var(B) -> not_infinite_bound(C) ; number(B),var(C)).
1809 at_least_two_vars(A,B,C) :- number(A), var(B),var(C).
1810 not_infinite_bound(A) :- (var(A) ; number(A)). % inf can only appear immediately, not for variables
1811
1812 :- block block_card_of_interval_inf(-,?,-),block_card_of_interval_inf(?,-,-).
1813 block_card_of_interval_inf(A,_,Card) :- A==minus_inf,!, Card=inf.
1814 block_card_of_interval_inf(_,B,Card) :- B==inf,!, Card=inf.
1815 block_card_of_interval_inf(From,To,Card) :- number(From),number(To),!,
1816 (From>To -> Card=0 ; Card is (To-From)+1).
1817 block_card_of_interval_inf(A,B,C) :- number(C),!, number_card_of_interval_inf_aux(C,A,B).
1818 block_card_of_interval_inf(A,B,C) :- C==inf,!,
1819 % TODO: probably this should systematically fail; if A and B are not inf/minus_inf now they will never be
1820 debug_println(19,infinite_interval_requested(A,B,C)),
1821 when((nonvar(A),nonvar(B)), block_card_of_interval_inf(A,B,C)).
1822 block_card_of_interval_inf(A,B,C) :- add_internal_error('Illegal call: ',card_of_interval_inf(A,B,C)).
1823 :- use_module(inf_arith,[block_inf_greater/2]).
1824 number_card_of_interval_inf_aux(0,A,B) :- !, % empty interval
1825 % if A and B are variables then they will not become inf later ??
1826 % inf can only be set directly for sets such as {x|x>4} or NATURAL1
1827 (((var(A);number(A)),(var(B);number(B)))
1828 % hence we can use ordinary comparison (with CLPFD) here
1829 -> kernel_objects:less_than_direct(B,A)
1830 % TO DO: we could do this even if both A and B are variables !! ex : {n,m|n..m = {} & m..100={} & 103..n={}}
1831 ; block_inf_greater(A,B)).
1832 %number_card_of_interval_inf_aux(Card,From,B) :- number(From),!, B is (From+Card)-1.
1833 %number_card_of_interval_inf_aux(Card,A,To) :- number(To),!, A is 1+To-Card.
1834 number_card_of_interval_inf_aux(Card,A,B) :-
1835 Card>0, C1 is Card-1,
1836 kernel_objects:int_minus(int(B),int(A),int(C1)).
1837
1838
1839 get_geq_leq_bounds(conjunct(b(LEFT,pred,_),b(RIGHT,pred,_)), Par,Low,Up) :-
1840 ? get_geq_leq_bounds(LEFT,Par,From1,To1),
1841 ? get_geq_leq_bounds(RIGHT,Par,From2,To2),
1842 intersect_intervals_with_inf(From1,To1,From2,To2,Low,Up).
1843 get_geq_leq_bounds(member(b(identifier(Par),integer,_),
1844 b(Value,set(integer),_)),Par,Low,Up) :-
1845 get_value_bounds(Value,Low,Up).
1846 ?get_geq_leq_bounds(greater_equal(b(A,_,_),b(B,_,_)),Par,Low,Up) :- get_bounds2(greater_equal,A,B,Par,Low,Up).
1847 ?get_geq_leq_bounds( less_equal(b(A,_,_),b(B,_,_)),Par,Low,Up) :- get_bounds2(less_equal,A,B,Par,Low,Up).
1848 ?get_geq_leq_bounds( greater(b(A,_,_),b(B,_,_)),Par,Low,Up) :- get_bounds2(greater,A,B,Par,Low,Up).
1849 ?get_geq_leq_bounds( less(b(A,_,_),b(B,_,_)),Par,Low,Up) :- get_bounds2(less,A,B,Par,Low,Up).
1850
1851 get_value_bounds(value(GS),Low,Up) :- is_interval_closure_or_integerset(GS,Low,Up). % recursive call
1852 % nonvar(GS), GS=global_set(ISET), get_integer_set_interval(ISET,Low,Up).
1853 get_value_bounds(interval(b(TLow,_,_),b(TUp,_,_)),Low,Up) :-
1854 integer_value(TLow,Low),
1855 integer_value(TUp,Up).
1856
1857 get_bounds2(greater_equal,identifier(Par),V,Par,X,inf) :- integer_value(V,X).
1858 get_bounds2(greater_equal,V,identifier(Par),Par,minus_inf,X) :- integer_value(V,X).
1859 get_bounds2(less_equal,identifier(Par),V,Par,minus_inf,X) :- integer_value(V,X).
1860 get_bounds2(less_equal,V,identifier(Par),Par,X,inf) :- integer_value(V,X).
1861 get_bounds2(greater,identifier(Par),V,Par,X1,inf) :- integer_value(V,X), kernel_objects:int_plus(int(X),int(1),int(X1)). %, X1 is X+1.
1862 get_bounds2(greater,V,identifier(Par),Par,minus_inf,X1) :- integer_value(V,X), kernel_objects:int_minus(int(X),int(1),int(X1)). %X1 is X-1.
1863 get_bounds2(less,V,identifier(Par),Par,X1,inf) :- integer_value(V,X), kernel_objects:int_plus(int(X),int(1),int(X1)). %X1 is X+1.
1864 get_bounds2(less,identifier(Par),V,Par,minus_inf,X1) :- integer_value(V,X),
1865 kernel_objects:int_minus(int(X),int(1),int(X1)). %X1 is X-1.
1866 % to do: add negation thereof ??
1867
1868 integer_value(V,_) :- var(V),!, print(var_integer_value(V)),nl,fail.
1869 integer_value(integer(X),R) :- !, R=X.
1870 integer_value(unary_minus(b(X,_,_)),R) :- !, integer_value(X,RM),
1871 number(RM), % if RM is not a number we could setup CLPFD constraint ?!
1872 R is -(RM).
1873 integer_value(minus(b(X,_,_),b(Y,_,_)),R) :- !, % some AST compilation rules generate X-1, X+1 ...
1874 integer_value(X,RMX),
1875 integer_value(Y,RMY),
1876 kernel_objects:int_minus(int(RMX),int(RMY),int(R)).
1877 integer_value(plus(b(X,_,_),b(Y,_,_)),R) :- !, % some AST compilation rules generate X-1, X+1 ...
1878 integer_value(X,RMX),
1879 integer_value(Y,RMY),
1880 kernel_objects:int_plus(int(RMX),int(RMY),int(R)).
1881 integer_value(value(V),R) :- V=int(R).
1882
1883 is_interval_closure(closure(Par,[integer],Pred),Low,Up) :-
1884 is_interval_closure_aux(Par,Pred,Low,Up).
1885 is_interval_closure(Par,[integer],Pred,Low,Up) :-
1886 is_interval_closure_aux(Par,Pred,Low,Up).
1887 is_interval_closure_aux(Par,Pred,Low,Up) :-
1888 is_member_closure(Par,[integer],Pred,integer,Set),
1889 is_interval_with_integer_bounds(Set,Low,Up).
1890 %is_interval_closure(closure_x(Par,[integer],Pred,_),Low,Up) :-
1891 % is_interval_closure(closure(Par,[integer],Pred),Low,Up).
1892
1893 is_interval_closure_body(Body,ID,Low,Up) :-
1894 is_member_closure([ID],[integer],Body,integer,Set),!,
1895 is_interval_with_integer_bounds(Set,Low,Up).
1896 is_interval_closure_body(Body,ID,Low,Up) :-
1897 ? is_geq_leq_interval_closure([ID],[integer],Body,Low,Up),
1898 number(Low), number(Up).
1899
1900 :- use_module(bsyntaxtree,[get_texpr_info/2,get_texpr_id/2]).
1901 % do a single check if we have interval, member or not-member closure, avoiding redundant checking
1902 % TO DO: move this and related predicates to closures module ?
1903 is_special_closure(_Ids,_Types,Pred,Result) :-
1904 get_texpr_info(Pred,Info),memberchk(prob_annotation(recursive(RId)),Info),!,
1905 Result = recursive_special_closure(RId).
1906 is_special_closure(Ids,Types,Pred,Result) :-
1907 ? is_memoization_closure(Ids,Types,Pred,MemoID),!,
1908 Result = memoization_closure(MemoID).
1909 is_special_closure([ID],[TYPE],b(PRED,_,_), Result) :-
1910 ( closures:is_member_closure_aux(PRED, [ID],[TYPE],_,SET) ->
1911 ( (TYPE=integer, is_interval_with_integer_bounds(SET,Low,Up)) ->
1912 Result = interval(Low,Up)
1913 ; Result = member_closure(ID,TYPE,SET))
1914 ; closures:is_not_member_closure_aux(PRED,ID,TYPE,SET) ->
1915 Result = not_member_closure(ID,TYPE,SET)
1916 ? ; (TYPE=integer,get_geq_leq_bounds(PRED,ID,Low,Up),number(Low), number(Up)) ->
1917 Result = interval(Low,Up)
1918 ).
1919
1920
1921 construct_interval_set(Low,Up,Res) :-
1922 Res = interval(b(value(int(Low)),integer,[]),
1923 b(value(int(Up)), integer,[])).
1924 is_interval_with_integer_bounds(X,L,U) :- var(X),!,
1925 add_internal_error('var arg: ',is_interval_with_integer_bounds(X,L,U)),fail.
1926 is_interval_with_integer_bounds(interval(b(TLOW,integer,_),b(TUP, integer,_)),Low,Up) :-
1927 integer_value(TLOW,Low), integer_value(TUP,Up).
1928
1929
1930 is_a_relation(relations(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '<->'
1931 Code = (kernel_card_arithmetic:safe_mul(DCard,RCard,Exp), kernel_card_arithmetic:safe_pow2(Exp,Card)).
1932 is_a_relation(partial_function(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '+->'
1933 Code = (kernel_card_arithmetic:safe_add_card(RCard,1,R1),kernel_card_arithmetic:safe_pown(R1,DCard,Card)).
1934 is_a_relation(total_function(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '-->'
1935 Code = (kernel_card_arithmetic:safe_pown(RCard,DCard,Card)).
1936 is_a_relation(partial_bijection(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '>+>>'
1937 Code = (kernel_card_arithmetic:partial_bijection_card(DCard,RCard,Card)).
1938 is_a_relation(total_bijection(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '>->>'
1939 Code = (kernel_card_arithmetic:total_bijection_card(DCard,RCard,Card)).
1940 is_a_relation(total_injection(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '>->'
1941 Code = (kernel_card_arithmetic:blocking_factorial_k(RCard,DCard,Card)).
1942 is_a_relation(partial_injection(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '>+>'
1943 Code = (kernel_card_arithmetic:partial_injection_card(DCard,RCard,Card)).
1944 is_a_relation(total_surjection(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '-->>'
1945 Code = (kernel_card_arithmetic:total_surjection_card(DCard,RCard,Card)).
1946 is_a_relation(partial_surjection(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '+->>'
1947 Code = (kernel_card_arithmetic:partial_surjection_card(DCard,RCard,Card)).
1948 is_a_relation(total_relation(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '<<->'
1949 Code = (kernel_card_arithmetic:total_relation_card(DCard,RCard,Card)).
1950 is_a_relation(surjection_relation(Domain,Range),Domain,Range,DCard,RCard,Card,Code) :- %% '<->>'
1951 % just swap args: card(A<->>B) = card(B<<->A)
1952 Code = (kernel_card_arithmetic:total_relation_card(RCard,DCard,Card)).
1953 % TO DO: total_surjection_relation <<->>
1954
1955
1956
1957 :- use_module(b_global_sets,[infinite_global_set/1]).
1958
1959 :- block is_infinite_global_set(-,?).
1960 is_infinite_global_set('NATURAL',integer).
1961 is_infinite_global_set('NATURAL1',integer).
1962 is_infinite_global_set('INTEGER',integer).
1963 is_infinite_global_set('FLOAT',real).
1964 is_infinite_global_set('REAL',real).
1965 is_infinite_global_set('STRING',string).
1966 is_infinite_global_set(G,global(G)) :- infinite_global_set(G).
1967
1968 %is_finite_integer_global_set('NAT').
1969 %is_finite_integer_global_set('NAT1').
1970 %is_finite_integer_global_set('INT').
1971
1972 % detects (certain) infinite explict sets
1973 is_infinite_explicit_set(X) :- var(X),!, add_internal_error(is_infinite_explicit_set,var(X)),fail.
1974 ?is_infinite_explicit_set(global_set(X)) :- is_infinite_global_set(X,_).
1975 is_infinite_explicit_set(freetype(X)) :- is_infinite_freetype(X).
1976 is_infinite_explicit_set(closure(Par,T,Body)) :- is_infinite_closure(Par,T,Body).
1977
1978 % this detects infinite and symbolic closures:
1979 is_infinite_or_symbolic_set(X) :- var(X),!, add_internal_error(is_infinite_or_symbolic_set,var(X)),fail.
1980 is_infinite_or_symbolic_set(global_set(X)) :- is_infinite_global_set(X,_).
1981 is_infinite_or_symbolic_set(freetype(X)) :- is_infinite_freetype(X).
1982 is_infinite_or_symbolic_set(closure(Par,T,Body)) :- is_infinite_or_symbolic_closure(Par,T,Body).
1983
1984
1985 % detect some closure that we should definitely expand; even in SYMBOLIC mode or for ABSTRACT_CONSTANTS
1986 definitely_expand_this_explicit_set(Var) :- var(Var),!,fail.
1987 definitely_expand_this_explicit_set(closure(P,T,B)) :-
1988 (B = b(Body,_,_), definitely_expand(Body,P) -> true
1989 ; is_interval_closure(P,T,B,Low,Up), do_expand_interval(Low,Up)).
1990 % some lambda functions have small domain, but are very complicated to compute (test 1078, 1376)
1991 % hence the following is not sufficient:
1992 % ;is_small_specific_custom_set(closure(P,T,B),100), print(exp(T)),nl,translate:print_bexpr(B),nl,fail).
1993
1994 :- use_module(bsyntaxtree,[occurs_in_expr/2]).
1995 definitely_expand(Body,_) :- avl_mem_construct(Body,_).
1996 definitely_expand(exists(ExistsTIDs,Body),P) :- P = [ID],
1997 % detect AVL projection expressions like {res|#y.(y:AVL & res=Expr(y))} % test 1101
1998 Body = b(conjunct(b(Mem,pred,_),Eq),pred,_),
1999 Eq = b(equal(EqA,EqB),pred,_),
2000 avl_mem_construct(Mem,LHS),
2001 tlhs_uses_exists(LHS,ExistsTIDs,[]),
2002 ( get_texpr_id(EqA,ID) -> \+ occurs_in_expr(ID,EqB)
2003 ; get_texpr_id(EqB,ID) -> \+ occurs_in_expr(ID,EqA) ). % we assign to set compr. ID
2004 % example where ID occurs in other expression: {v|#w.(w : (1 .. 10) & v = (v + w) - 2)}; test 2516
2005
2006 tlhs_uses_exists(b(E,_,_)) --> lhs_uses_exists(E).
2007 ?lhs_uses_exists(identifier(EID),In,Out) :-!, select(TEID,In,Out),
2008 get_texpr_id(TEID,EID),!. % TODO: we could allow using an identifier twice
2009 lhs_uses_exists(value(V)) --> {nonvar(V), simple_value(V), ground_value(V)}.
2010 lhs_uses_exists(couple(A,B)) --> tlhs_uses_exists(A), tlhs_uses_exists(B).
2011 lhs_uses_exists(boolean_true) --> [].
2012 lhs_uses_exists(boolean_false) --> [].
2013 lhs_uses_exists(empty_set) --> [].
2014 lhs_uses_exists(empty_sequence) --> [].
2015 lhs_uses_exists(integer(_)) --> [].
2016 lhs_uses_exists(real(_)) --> [].
2017 lhs_uses_exists(string(_)) --> [].
2018
2019 avl_mem_construct(member(LHS,RHS),LHS) :- RHS = b(value(V),_,_), nonvar(V),
2020 (V=avl_set(_) -> true
2021 ; is_interval_closure_or_integerset(V,L,U), integer(L), integer(U), U-L < 1000
2022 ).
2023
2024 % dont_expand_this_explicit_set with default limit (20000)
2025 dont_expand_this_explicit_set(closure(P,T,B)) :- !,
2026 dont_expand_this_closure(P,T,B).
2027 dont_expand_this_explicit_set(S) :-
2028 is_infinite_or_very_large_explicit_set(S).
2029
2030 % dont_expand_this_explicit_set with extra limit argument:
2031 dont_expand_this_explicit_set(closure(P,T,B),Limit) :- !, dont_expand_this_closure(P,T,B,Limit).
2032 dont_expand_this_explicit_set(S,_) :- is_infinite_or_very_large_explicit_set(S).
2033
2034 % true if we have a closure / global_set that should not be expanded
2035 % TO DO: we could detect finite (is_lambda_value_domain_closure) closures which contain infinite elements such as %p.(p : BOOL|%t.(t : NATURAL|t .. t + 7))
2036 dont_expand_symbolic_explicit_set(closure(P,T,B)) :- !,
2037 dont_expand_this_closure(P,T,B).
2038 dont_expand_symbolic_explicit_set(avl_set(_)) :- !,
2039 fail. % already expanded
2040 dont_expand_symbolic_explicit_set(S) :-
2041 is_infinite_or_very_large_explicit_set(S).
2042
2043
2044 dont_expand_this_closure(P,T,B) :-
2045 get_preference(comprehension_set_symbolic_limit,Limit), % Default 20000
2046 dont_expand_this_closure(P,T,B,Limit). % % increase limit in Data valid mode?
2047
2048 dont_expand_this_closure(_P,_T,b(_,_,INFO),_Limit) :-
2049 ? member(prob_annotation(KIND),INFO),
2050 (KIND = 'SYMBOLIC' -> ! % cf is_symbolic_closure in closures
2051 ; KIND = 'FORCE' -> !, fail). % was wrapped in FORCE external_function
2052 dont_expand_this_closure(P,T,B,_Limit) :-
2053 ? is_interval_closure_or_numberset(closure(P,T,B),Low,Up), !,
2054 % interval closures are quite efficient for certain manipulations
2055 (integer(Low), integer(Up)
2056 -> dont_expand_interval(Low,Up)
2057 % ; float(Low), float(Up) -> Low < Up % probably very many values between; requires new 4.10 solver to detect emptyness TODO
2058 ; true % we have a closure with inf/minus_inf or variables as bounds or floats; in all cases keep the closure
2059 ).
2060 dont_expand_this_closure(P,T,B,Limit) :-
2061 is_infinite_or_very_large_closure(P,T,B,Limit).
2062 %% TODO: also prevent expansion of things like ff = %x.(x:STRING & REGEX_MATCH(x,"[a-z]+")=TRUE|TRUE)
2063
2064 % do not automatically expand these integer intervals
2065 dont_expand_interval(Low,Up) :-
2066 Up+1-Low > 100. % another magic constant ; which value to choose ??
2067 % do expand these integer intervals:
2068 do_expand_interval(Low,Up) :- Up+1-Low =< 100.
2069
2070 is_converted_lambda_closure(_P,_T,b(_,_,INFO)) :-
2071 ? member(prob_annotation('LAMBDA'),INFO).
2072
2073 is_symbolic_closure_or_symbolic_mode(P,T,B) :-
2074 ? (is_symbolic_closure(P,T,B) -> true
2075 ; preference(convert_comprehension_sets_into_closures,true)
2076 % by default suppose closures should be dealt with symbolically
2077 ).
2078 /*
2079 % check both LAMBDA + not RECURSIVE
2080 is_converted_non_recursive_lambda_closure(_,_,b(_,_,INFO)) :- is_conv_lambda_nonrec(INFO).
2081 is_conv_lambda_nonrec([prob_annotation(A)|T]) :- !,
2082 (A='LAMBDA' -> \+ memberchk(prob_annotation('RECURSIVE'),T)
2083 ; A\='RECURSIVE' -> is_conv_lambda_nonrec(T)).
2084 is_conv_lambda_nonrec([_|T]) :- is_conv_lambda_nonrec(T). */
2085
2086
2087
2088 % a set that is so large that expanding it would probably cause problems
2089 is_infinite_or_very_large_explicit_set(S) :-
2090 get_preference(comprehension_set_symbolic_limit,Limit), % Default 20000
2091 is_infinite_or_very_large_explicit_set(S,Limit). % increase limit in Data valid mode?
2092
2093 :- use_module(inf_arith,[infgreater/2]).
2094
2095 is_infinite_or_very_large_explicit_set(X,_) :- var(X),!,print(var_is_infinite_check(X)),nl,fail.
2096 is_infinite_or_very_large_explicit_set(closure(P,T,B),Limit) :- !,
2097 % treat closure separately here; some special rules
2098 is_infinite_or_very_large_closure(P,T,B,Limit).
2099 is_infinite_or_very_large_explicit_set(avl_set(A),Limit) :- !, % we could compute log and use avl_height_less_than
2100 quick_avl_approximate_size(A,Size), Size >= Limit.
2101 is_infinite_or_very_large_explicit_set(X,Limit) :- % closures are checked above
2102 explicit_set_cardinality(X,Card),
2103 nonvar(Card),infgreater(Card,Limit).
2104
2105
2106 is_very_large_or_symbolic_closure(P,T,B,Limit) :-
2107 ? (is_symbolic_closure(P,T,B) -> true ; is_infinite_or_very_large_closure(P,T,B,Limit)).
2108 :- use_module(bsyntaxtree,[is_a_disjunct/3]).
2109 is_infinite_or_very_large_closure(P,T,B,Limit) :-
2110 is_a_disjunct(B,D1,D2), % Assumption: there is no card_for_specific_closure code for disjuncts
2111 !,
2112 (is_infinite_or_very_large_closure(P,T,D1,Limit) -> true
2113 ; is_infinite_or_very_large_closure(P,T,D2,Limit)).
2114 is_infinite_or_very_large_closure(Par,T,Body,Limit) :-
2115 is_closure1_value_closure(Par,T,Body,VAL),!,
2116 nonvar(VAL), % it could still be large or infinite
2117 (Limit>1 -> NLimit is Limit/2 ; NLimit = Limit), % reduce limit as closure1 usually blows up
2118 is_infinite_or_very_large_explicit_set(VAL,NLimit).
2119 is_infinite_or_very_large_closure(P,T,B,Limit) :-
2120 card_for_specific_closure3(Kind,P,T,B,Card,Code),
2121 on_enumeration_warning(call(Code),
2122 (debug_println(9,cannot_expand_specific_closure_for_card(Kind,Limit)),
2123 % see test 1519 for relevance
2124 Card=inf)), % assume it is large
2125 !,
2126 nonvar(Card),infgreater(Card,Limit),
2127 perfmessages_bexpr(symbolic_closure,['Keeping comprehension set symbolic, cardinality ',Card,' greater than limit ',Limit,' for '],B).
2128
2129 is_infinite_or_symbolic_closure(P,T,B) :-
2130 ? (is_symbolic_closure(P,T,B) -> true ; is_infinite_closure(P,T,B)).
2131 is_infinite_closure(P,T,B) :-
2132 is_a_disjunct(B,D1,D2), % Assumption: there is no card_for_specific_closure code for disjuncts
2133 !,
2134 ? (is_infinite_closure(P,T,D1) -> true ; is_infinite_closure(P,T,D2)).
2135
2136 is_infinite_closure(Par,Types,Body) :-
2137 is_member_closure(Par,Types,Body,Type,MemSET), !,
2138 nonvar(MemSET),
2139 ? is_infinite_member_closure_body(MemSET,Type).
2140 is_infinite_closure(Par,T,Body) :-
2141 card_for_specific_closure(closure(Par,T,Body),Card,Code),
2142 call(Code), % TO DO: catch enumeration exceptions (see is_infinite_or_very_large_closure above)
2143 Card == inf. % TODO: instantiate inf before to avoid computing huge numbers
2144
2145 is_infinite_member_closure_body(closure(b(VALExpr,_,_)),couple(A,A)) :-
2146 is_infinite_member_closure_body(VALExpr,couple(A,A)).
2147 % if VALExpr is a var value: it could still be infinite !! TO DO fix
2148 % % TO DO: also check closure1 is infinite
2149 is_infinite_member_closure_body(value(VAL),_) :- nonvar(VAL),
2150 is_infinite_explicit_set(VAL).
2151 is_infinite_member_closure_body(comprehension_set(Par,Body),_) :-
2152 split_names_and_types(Par,P,T),
2153 is_infinite_closure(P,T,Body).
2154 % TODO: call unary_member_closure_for_finite(SET,Check,SET1), with Check=finite
2155 is_infinite_member_closure_body(Body,TYPE) :-
2156 card_for_member_closure(Body,TYPE,Card,Code),
2157 call(Code), % TO DO: catch enumeration exceptions (see is_infinite_or_very_large_closure above)
2158 Card == inf. % TODO: instantiate inf before to avoid computing huge numbers
2159
2160
2161 :- use_module(memoization,[compute_memo_hash/2, get_stored_memo_expansion/3, store_memo_expansion/3]).
2162 /* transitive closure */
2163 closure1_for_explicit_set(avl_set(A),Res) :-
2164 preferences:preference(use_closure_expansion_memoization,true),!,
2165 compute_memo_hash(closure1_for_explicit_set(A),Hash),
2166 (get_stored_memo_expansion(Hash,closure1_for_explicit_set(A),StoredResult)
2167 -> Res = StoredResult
2168 ; closure1_for_explicit_set_direct(avl_set(A),Result),
2169 store_memo_expansion(Hash,closure1_for_explicit_set(A),Result),
2170 Res = Result
2171 ).
2172 closure1_for_explicit_set(avl_set(A),Res) :- closure1_for_explicit_set_direct(avl_set(A),Res).
2173
2174 % sometimes faster, but can also be considerably slower:
2175 %:- use_module(extrasrc(avl_ugraphs),[avl_transitive_closure/2]).
2176 %closure1_for_explicit_set_direct(avl_set(A),Res) :-
2177 % avl_transitive_closure(A,TC),
2178 % construct_avl_set(TC,Res).
2179 closure1_for_explicit_set_direct(avl_set(A),Res) :-
2180 perfmessage_bexpr(closure1,'Computing transitive closure1 of: ',b(value(avl_set(A)),any,[])),
2181 avl_domain(A,AList),
2182 iterate_closure(AList,A,A,IterationRes),
2183 construct_avl_set(IterationRes,Res).
2184
2185 /* transitive closure starting from some initial set */
2186 /* not sure if we should do this:
2187 closure1_for_explicit_set_from(avl_set(A),StartFrom,Res) :-
2188 preferences:preference(use_closure_expansion_memoization,true),
2189 compute_memo_hash(closure1_for_explicit_set(A),Hash),
2190 stored_expansion(Hash,closure1_for_explicit_set(A),StoredResult),!,
2191 domain_restriction_explicit_set(StartFrom,StoredResult,Res). */
2192 % StartFrom can be avl_set(empty)
2193 closure1_for_explicit_set_from(avl_set(A),StartFrom,Res) :-
2194 avl_domain(A,AList),
2195 filter_start_relation(AList,StartFrom,FAList),
2196 (FAList = [] -> Res=[]
2197 ; convert_to_avl(FAList,avl_set(Start)),
2198 iterate_closure(FAList,A,Start,IterationRes),
2199 construct_avl_set(IterationRes,Res)).
2200 filter_start_relation([],_,[]).
2201 filter_start_relation([(X,Y)|T],StartSet,Res) :-
2202 ? (element_of_custom_set(X,StartSet) -> Res = [(X,Y)|RT] ; Res=RT),
2203 filter_start_relation(T,StartSet,RT).
2204
2205 iterate_closure([],_,Res,Res).
2206 iterate_closure([(X,Y)|T],InitialRelation,Relation,Res) :-
2207 %(Key = (X,Y) -> true ; add_error_and_fail(iterate_closure,'Not a relation element: ',Key)),
2208 add_tuples(X,Y,InitialRelation,Relation,NewRelation,AddedTuples),
2209 % better: do added tuples straight away ?
2210 iterate_closure(T,InitialRelation,NewRelation,NewRelation2),
2211 iterate_closure(AddedTuples,InitialRelation,NewRelation2,Res).
2212
2213 add_tuples(X,Y,AVL,AVLClosureSoFar,Res,NewTuples) :-
2214 findall((X,Z), (avl_fetch_pair(Y,AVL,Z), %ok instead of safe_avl_member((Y,Z),AVL),; Y in AVL form, Z var
2215 %Y \= Z, % self-loops are already in initial AVLClosure, this will never add a new pair
2216 % if we use AVLClosureSoFar instead of AVL: considerably slower
2217 \+ avl_fetch((X,Z),AVLClosureSoFar)), NewTuples),
2218 add_to_avl(NewTuples,AVLClosureSoFar,Res).
2219
2220 :- use_module(bsyntaxtree,[create_negation/2]).
2221 % SUBSET_OF <:
2222 % subset_of_explicit_set: returns code to be executed if this subset check can be done in an optimized way
2223 % TO DO: add strict_subset <<: + more cases, e.g., interval & avl_set, ...
2224 % interval & interval already handled in check_subset_of_global_sets
2225 subset_of_explicit_set(AVL,Closure,Code,_WF) :- nonvar(AVL),AVL=avl_set(A),
2226 is_interval_closure_or_integerset(Closure,Low,Up),!,
2227 Code=custom_explicit_sets:check_avl_in_interval(A,Low,Up).
2228 subset_of_explicit_set(Closure,CS,Code,WF) :- nonvar(CS), is_custom_explicit_set(CS),
2229 is_interval_closure_or_integerset(Closure,Low,Up),
2230 Low \== minus_inf, Up \== inf, % check_interval_in_custom_set fails for infinite intervals
2231 !,
2232 Code=custom_explicit_sets:check_interval_in_custom_set(Low,Up,CS,WF).
2233 subset_of_explicit_set(AVL1,AVL2,Code,_WF) :-
2234 nonvar(AVL1),AVL1=avl_set(A1), nonvar(AVL2),AVL2=avl_set(A2),!,
2235 Code = custom_explicit_sets:check_avl_subset(A1,A2).
2236 subset_of_explicit_set(C1,AVL2,Code,_WF) :- nonvar(C1),
2237 simple_finite_set(AVL2),
2238 ? is_simple_infinite_set(C1),!, % infinite set cannot be subset of finite one
2239 Code = fail.
2240 subset_of_explicit_set(C1,C2,Code,WF) :- nonvar(C1),
2241 is_cartesian_product_closure(C1,S11,S12),!,
2242 ((S11==[] ; S12==[]) -> Code=true /* we always have a subset */
2243 ; is_definitely_not_empty(S11),
2244 is_definitely_not_empty(S12), % only use optimisation if we know S11, S12 to be non-empty
2245 nonvar(C2), is_cartesian_product_closure(C2,S21,S22),
2246 Code = (kernel_objects:check_subset_of_wf(S11,S21,WF),
2247 kernel_objects:check_subset_of_wf(S12,S22,WF) )
2248 ).
2249 subset_of_explicit_set(Set1,Set2,Code,WF) :-
2250 nonvar(Set2),is_cartesian_product_closure(Set2,S21,S22),!,
2251 % TO DO: maybe don't do this if Set1 is avl_set ??
2252 debug_println(9,'Applying C <: S21*S22 <=> C : S21 <-> S22'),
2253 Code = kernel_relations:relation_over_wf(Set1,S21,S22,WF).
2254 subset_of_explicit_set(C1,C2,Code,WF) :- nonvar(C1), nonvar(C2),
2255 is_powerset_closure(C1,Constructor1,Set1),
2256 is_powerset_closure(C2,Constructor2,Set2),
2257 subset_constructor(Constructor1,Constructor2,R),
2258 !,
2259 Code = (R=pred_true, kernel_objects:check_subset_of_wf(Set1,Set2,WF)).
2260 subset_of_explicit_set(Set1,Set2,Code,WF) :-
2261 AllowRegularClosure=false,
2262 symbolic_subset_of_explicit_set(Set1,Set2,AllowRegularClosure,Code,WF).
2263
2264 symbolic_subset_of_explicit_set(Set1,Set2,AllowRegularClosure,Code,WF) :-
2265 %print_term_summary(subset(Set1,Set2)),nl,
2266 get_subset_counter_example_closure(Set1,Set2,NewP,NewT,NewB,AllowRegularClosure,DefResult),
2267 % {x|P1} <: {x|P2} <=> {x|P1 & not(P2)}={}
2268 !, %translate:print_bexpr(NewB),nl,
2269 (DefResult==definitely_non_empty -> Code = fail
2270 ; clean_up(NewB,[],CNewB), % can be useful to apply remove_member_comprehension
2271 Code = custom_explicit_sets:is_empty_closure_wf(NewP,NewT,CNewB,WF)).
2272
2273 % get closure representing the counter examples to Set1 <: Set2: i.e. elements in Set1 and not in Set2
2274 % used for symbolic treatment of subset, not_subset and test_subset
2275 % note: in case this fails subset_test1 will expand Set1
2276 % DefiniteResultFlag may return the information that the generated closure is definitely not empty
2277 % AllowRegularClosure=false means it will only be applied for symbolic or infinite closures
2278 get_subset_counter_example_closure(Set1,Set2,NewP,NewT,NewB,AllowRegularClosure,DefiniteResultFlag) :-
2279 get_closure(Set1,P1,T1,B1),
2280 get_subset_counter_aux(P1,T1,B1,Set2,NewP,NewT,NewB,AllowRegularClosure,DefiniteResultFlag).
2281
2282 get_subset_counter_aux(P1,T1,B1,Set2,NewP,NewT,NewB,AllowRegularClosure,DefRes) :-
2283 nonvar(Set2), is_definitely_finite(Set2), !,
2284 create_couple_term(P1,T1,P1Couple), % can currently still fail for more than 2 args
2285 (is_infinite_closure(P1,T1,B1)
2286 -> DefRes=definitely_non_empty % there are definitely counter examples as Set2 is finite
2287 ; AllowRegularClosure=true -> DefRes = unknown
2288 ? ; is_symbolic_closure(P1,T1,B1) -> DefRes=unknown
2289 ),
2290 NewP=P1, NewT=T1,
2291 % {x|P1} <: {a1,...} <=> {x|P1 & x /: {a1,...}}={}
2292 get_texpr_type(P1Couple,CoupleType1),
2293 VSet2 = b(value(Set2),set(CoupleType1),[]),
2294 create_texpr(not_member(P1Couple,VSet2),pred,[],NegPred2),
2295 conjunct_predicates([B1,NegPred2],NewB).
2296 get_subset_counter_aux(P1,T1,B1,Set2,NewP,NewT,NewB,AllowRegularClosure,unknown) :-
2297 get_closure(Set2,P2,T2,B2),
2298 (AllowRegularClosure=true -> true
2299 ; is_infinite_or_symbolic_closure(P1,T1,B1) -> true
2300 % should we also allow ??
2301 % ; is_symbolic_closure(P2,T2,B2)
2302 ),
2303 % not necessary maybe as subset_test1 only expands Set1
2304 % {x|P1} <: {x|P2} <=> {x|P1 & not(P2)}={}
2305 unify_closure_predicates(P1,T1,B1, P2,T2,B2 , NewP,NewT, NewB1,NewB2),
2306 create_negation(NewB2,NegNewB2),
2307 bsyntaxtree:conjunct_predicates([NewB1,NegNewB2],NewB).
2308
2309
2310 % get_closure or infinite global set:
2311 get_closure(V,_,_,_) :- var(V),!,fail.
2312 get_closure(closure(P,T,B),P,T,B).
2313 ?get_closure(global_set(G),P,T,B) :- is_infinite_global_set(G,Type),!,
2314 ID = '_zzzz_unary',
2315 TID = b(identifier(ID),Type,[]),
2316 TSet = b(value(global_set(G)),set(Type),[]),
2317 P = [ID], T=[Type], B= b(member(TID,TSet),pred,[prob_annotation('SYMBOLIC')]).
2318
2319
2320 subset_constructor(X,X,R) :- !,R=pred_true.
2321 subset_constructor(fin1,_,R) :- !,R=pred_true.
2322 subset_constructor(fin,pow,R) :- !,R=pred_true.
2323 subset_constructor(X,Y,R) :- strict_subset_constructor(X,Y),!,R=pred_true.
2324 subset_constructor(X,Y,R) :- strict_subset_constructor(Y,X),!,R=pred_false.
2325 % pow1,fin1 ; pow,fin ; and pow1,fin only ok if type infinite
2326 strict_subset_constructor(pow1,pow).
2327 strict_subset_constructor(fin1,fin).
2328
2329 % more rules for <->, +->, ...
2330 % what if same closure: then we also know it is a subset
2331
2332 % to be completed:
2333 % code that instantiates R to subset or not_subset, may have to delay
2334 test_subset_of_explicit_set(Set1,_,_,_,_) :- var(Set1),!,fail.
2335 test_subset_of_explicit_set(avl_set(A),Closure,R,WF,Code) :-
2336 is_interval_closure_or_integerset(Closure,Low,Up),!,
2337 Code=custom_explicit_sets:test_avl_in_interval(A,Low,Up,R,WF).
2338 test_subset_of_explicit_set(_,Set2,_,_,_) :- var(Set2),!,fail.
2339 test_subset_of_explicit_set(avl_set(A1),avl_set(A2),R,_WF,Code) :-
2340 Code = (custom_explicit_sets:check_avl_subset(A1,A2) -> R=pred_true ; R=pred_false).
2341 test_subset_of_explicit_set(global_set(G),Set2,R,_WF,Code) :-
2342 ? is_infinite_global_set(G,_), % TODO: we could extend this to other infinite sets
2343 is_definitely_finite(Set2), !,
2344 Code =(R=pred_false).
2345 test_subset_of_explicit_set(Set1,Set2,Res,WF,Code) :-
2346 AllowRegular=false,
2347 get_subset_counter_example_closure(Set1,Set2,NewP,NewT,NewB,AllowRegular,DefResult),
2348 % {x|P1} <: {x|P2} <=> {x|P1 & not(P2)}={}
2349 !,
2350 (DefResult==definitely_non_empty -> Code = (Res=pred_false)
2351 ; Code = custom_explicit_sets:test_empty_closure_wf(NewP,NewT,NewB,Res,WF)
2352 ).
2353 % TO DO: add is_cartesian_product_closure case
2354 is_definitely_finite([]).
2355 is_definitely_finite(avl_set(_)).
2356
2357 :- use_module(kernel_equality,[test_interval_subset_wf/6]).
2358
2359 :- public test_avl_in_interval/5. % used in test_subset_of_explicit_set
2360 % see also check_avl_in_interval(A,Low,Up), check_avl_not_in_interval(A,Low,Up).
2361 test_avl_in_interval(A,Low2,Up2,Res,WF) :-
2362 avl_min(A,int(Min)), % not needed if Low2==minus_inf
2363 avl_max(A,int(Max)), % not needed if Up2==inf
2364 test_interval_subset_wf(Min,Max,Low2,Up2,Res,WF).
2365
2366 % ----------------------
2367
2368 is_definitely_not_empty(X) :- nonvar(X),
2369 (X=[_|_] -> true
2370 ; is_custom_explicit_set(X), is_non_empty_explicit_set(X)).
2371
2372 % check if defnitely not empty and provide a witness
2373 is_definitely_not_empty_with_witness(X,El) :- nonvar(X),
2374 get_witness_element(X,El).
2375 get_witness_element([H|_],H).
2376 get_witness_element(avl_set(node(H,_True,_,_,_)),H).
2377 % TO DO: add global_set(GS),...
2378
2379 check_avl_subset(A1,A2) :- avl_max(A1,Max1), avl_max(A2,Max2),
2380 Max1@>Max2,!, % then A1 cannot be subset of A2
2381 fail.
2382 check_avl_subset(A1,A2) :-
2383 avl_min(A1,Cur1), avl_min(A2,Cur2),
2384 check_avl_subset_loop(Cur1,A1,Cur2,A2).
2385 check_avl_subset_loop(Cur1,AVL1,Cur2,AVL2) :-
2386 (Cur1 @> Cur2 -> avl_next(Cur2,AVL2,NC2), check_avl_subset_loop(Cur1,AVL1,NC2,AVL2)
2387 ; Cur1=Cur2 -> (avl_next(Cur1,AVL1,NC1)
2388 -> avl_next(Cur2,AVL2,NC2),
2389 check_avl_subset_loop(NC1,AVL1,NC2,AVL2)
2390 ; true /* all objects of AVL1 inspected */)
2391 ).
2392
2393 % check A <: Low..Up
2394 check_avl_in_interval(A,Low,Up) :- % does not have to delay: if we have minus_inf & inf they will be known straightaway
2395 (Low==minus_inf -> true
2396 ; avl_min(A,Min), kernel_objects:less_than_equal(int(Low),Min)),
2397 (Up==inf -> true
2398 ; avl_max(A,Max), kernel_objects:less_than_equal(Max,int(Up))).
2399
2400 % some experiments:
2401 % 1..x <: {1,2,3,5} & x>1 & !y.(y>x & y<10 => 1..y /<: {1,2,3,5})
2402 % {ss | ss <: 0..0 & ss /= {} & ss=0..max(ss)}
2403 % {ss | ss <: 0..0 & ss /= {} & ss=min(ss)..max(ss)} // does not work yet
2404 % x..x+1 <: {0,2,3,5}
2405 % x..x+2 <: {0,2,3,5} // does not work yet
2406 % r = {x|x:1..400 & x mod 3/=0} & res={v|v:0..1300 & v..v+1 <: r}
2407 % check Low..Up <: Avl
2408
2409 check_interval_in_custom_set(Low,Up,CS,WF) :-
2410 Low \== minus_inf,
2411 Up \== inf,
2412 b_interpreter_check:check_arithmetic_operator('<=',Low,Up,LeqRes),
2413 (var(LeqRes) -> get_binary_choice_wait_flag_exp_backoff(16,check_interval_in_custom_set,WF,WF2) ; true),
2414 ? check_interval_in_custom_set_aux(LeqRes,Low,Up,CS,WF,WF2).
2415
2416 :- block check_interval_in_custom_set_aux(-,?,?,?,?,-).
2417 check_interval_in_custom_set_aux(pred_true,Low,Up,CS,WF,_WF2) :-
2418 ? element_of_custom_set_wf(int(Low),CS,WF),
2419 ? element_of_custom_set_wf(int(Up),CS,WF),
2420 ? interval_in_avl_block(Low,Up,CS,WF).
2421 check_interval_in_custom_set_aux(pred_false,_Low,_Up,_CS,_WF,_WF2). % Interval is empty; but infinitely many solutions for Low and Up exist in principle
2422
2423 :- block interval_in_avl_block(-,?,?,?), interval_in_avl_block(?,-,?,?).
2424 interval_in_avl_block(Low,Up,CS,WF) :-
2425 ? Low1 is Low+1, interval_in_avl_loop(Low1,Up,CS,WF).
2426 interval_in_avl_loop(Low,Up,_CS,_WF) :- Low>=Up,!. % Lower bound and upper bound already checked
2427 interval_in_avl_loop(Low,Up,CS,WF) :-
2428 ? element_of_custom_set_wf(int(Low),CS,WF), L1 is Low+1,
2429 ? interval_in_avl_loop(L1,Up,CS,WF).
2430
2431
2432 :- public not_check_avl_subset/2. % used in not_subset_of_explicit_set_aux
2433 not_check_avl_subset(A1,A2) :- \+ check_avl_subset(A1,A2).
2434
2435 not_subset_of_explicit_set(S1,S2,Code,WF) :- nonvar(S1),
2436 ? not_subset_of_explicit_set_aux(S1,S2,Code,WF).
2437 not_subset_of_explicit_set_aux(avl_set(A),Closure,Code,_WF) :-
2438 is_interval_closure_or_integerset(Closure,Low,Up),!,
2439 Code=custom_explicit_sets:check_avl_not_in_interval(A,Low,Up).
2440 not_subset_of_explicit_set_aux(avl_set(A1),AVL2,Code,_WF) :-
2441 nonvar(AVL2),AVL2=avl_set(A2),
2442 Code = custom_explicit_sets:not_check_avl_subset(A1,A2).
2443 not_subset_of_explicit_set_aux(CS,AVL,Code,_WF) :-
2444 ? is_simple_infinite_set(CS),
2445 % TO DO: provide code for interval/NAT/INT /<: AVL
2446 simple_finite_set(AVL),
2447 !,
2448 Code = true. % G cannot be subset of finite set
2449 not_subset_of_explicit_set_aux(C1,C2,Code,WF) :- is_cartesian_product_closure(C1,S11,S12),
2450 ((S11==[] ; S12==[]) -> Code=fail /* we always have a subset */
2451 ; is_definitely_not_empty(S11),
2452 is_definitely_not_empty(S12), % only use optimisation if we know S11, S12 to be non-empty
2453 nonvar(C2), is_cartesian_product_closure(C2,S21,S22),
2454 Code = (kernel_objects:not_both_subset_of(S11,S12, S21,S22, WF))
2455 ), !.
2456 not_subset_of_explicit_set_aux(C1,C2,Code,WF) :- nonvar(C2),
2457 is_powerset_closure(C1,Constructor1,Set1),
2458 is_powerset_closure(C2,Constructor2,Set2),
2459 subset_constructor(Constructor1,Constructor2,R),!,
2460 Code = (R=pred_false -> true ; kernel_objects:not_subset_of_wf(Set1,Set2,WF)).
2461 not_subset_of_explicit_set_aux(Set1,Set2,Code,WF) :-
2462 AllowRegular=false,
2463 get_subset_counter_example_closure(Set1,Set2,NewP,NewT,NewB,AllowRegular,DefResult),
2464 % {x|P1} <: {x|P2} <=> {x|P1 & not(P2)}={}
2465 !,
2466 (DefResult==definitely_non_empty -> Code = true
2467 ; Code = custom_explicit_sets:is_non_empty_closure_wf(NewP,NewT,NewB,WF)
2468 ).
2469
2470
2471 :- public check_avl_not_in_interval/3. % used in not_subset_of_explicit_set_aux
2472 :- block check_avl_not_in_interval(?,-,?). % TO DO: use non-blocking version, minus_inf, and inf set directly
2473 check_avl_not_in_interval(A,Low,Up) :- avl_min(A,int(Min)),
2474 check_avl_not_in_interval4(Low,Up,A,Min).
2475
2476 check_avl_not_in_interval4(Low,_Up,_A,Min) :- Low \== minus_inf, Min < Low,!.
2477 check_avl_not_in_interval4(_Low,Up,A,_Min) :-
2478 Up \== inf, avl_max(A,Max),
2479 kernel_objects:less_than(int(Up),Max). % Up could still be a variable
2480
2481
2482 % checks for simple infinite sets, without Cartesian Product, ... decomposition
2483 ?is_simple_infinite_set(global_set(X)) :- !, is_infinite_global_set(X,_).
2484 is_simple_infinite_set(CS) :- is_interval_closure_or_integerset(CS,Low,Up), infinite_interval(Low,Up).
2485
2486 simple_finite_set(AVL) :- nonvar(AVL), (AVL=avl_set(_) -> true ; AVL = []).
2487
2488 % IMAGE [.]
2489 image_for_id_closure(closure(Par,Types,Body),Set,Res) :-
2490 is_full_id_closure(Par,Types,Body),!,
2491 Res=Set.
2492
2493 image_for_explicit_set(closure(Par,Types,Body),Set,Res,WF) :-
2494 ? image_for_closure(Par,Types,Body,Set,Res,WF).
2495 image_for_explicit_set(avl_set(A),Set,Res,WF) :- nonvar(Set),
2496 image_for_explicit_avl_set(A,Set,Res,WF).
2497
2498
2499 image_for_closure(Par,Types,Body,Set,Res,_WF) :-
2500 is_id_closure_over(Par,Types,Body,ID_Domain,Full),!,
2501 (Full=true -> Res=Set ; kernel_objects:intersection(ID_Domain,Set,Res)).
2502 % infinite function case dealt with in image1 in kernel_relations
2503 % TO DO: other closure(); Maybe special case if Set is an interval ?
2504 image_for_closure(Par,Types,Body,Set,Res,WF) :-
2505 is_closure1_value_closure(Par,Types,Body,VAL), % TODO: also detect reflexive closure, iteration (iterate(rel,k))
2506 % compute closure1(VAL)[Set]
2507 ? kernel_relations:image_for_closure1_wf(VAL,Set,Res,WF).
2508
2509 is_closure1_value_closure(Par,Types,Body,VAL) :-
2510 is_member_closure(Par,Types,Body,couple(A,A),MemSET), nonvar(MemSET),
2511 MemSET = closure(V), % this is the closure1 B operator !
2512 nonvar(V), V=b(value(VAL),_,_).
2513
2514 image_for_explicit_avl_set(A,Set,Res,_WF) :- % Set is nonvar
2515 is_interval_closure_or_integerset(Set,From1,To1),!,
2516 % Note: if From1, To1 not yet known we will block and not revert to other image calculation code
2517 % Important e.g. for performance of San Juan (AdaptedBModelPropCheck/acs_as_env_cfg_ipart.mch)
2518 %we used to check for: ground(From1),ground(To1),
2519 interval_image_for_explicit_avl_set(From1,To1,A,Set,Res).
2520 image_for_explicit_avl_set(A,Set,Res,WF) :-
2521 \+ kernel_relations:keep_symbolic(Set), % in this case we fall back to treatment in kernel_relations (image1)
2522 expand_custom_set_to_list_gg(Set,ESet,GG,image_for_explicit_avl_set),
2523 empty_avl(Empty),
2524 (GG=guaranteed_ground -> image_explicit_ground(ESet,A,Empty,Res,WF)
2525 ; image_explicit(ESet,A,Empty,Res,WF)).
2526
2527 :- block interval_image_for_explicit_avl_set(-,?,?,?,?),
2528 interval_image_for_explicit_avl_set(?,-,?,?,?).
2529 interval_image_for_explicit_avl_set(From1,To1,_A,_Set,Res) :-
2530 number(From1), number(To1), From1>To1,!,
2531 kernel_objects:empty_set(Res).
2532 interval_image_for_explicit_avl_set(From1,To1,A,_Set,Res) :-
2533 findall(Image-true, avl_image_interval(From1,To1, A,Image),ImageList),
2534 normalised_list_to_avl(ImageList,ImageAvl),
2535 ? equal_object(ImageAvl,Res).
2536
2537
2538 %! singleton_set(+Set,-Element).
2539 singleton_set(X,_) :- var(X),!,fail.
2540 singleton_set([H|T],R) :- T==[], R=H.
2541 singleton_set(avl_set(node(Y,_,_,empty,empty)),Y). % same as is_one_element_custom_set
2542
2543 is_one_element_custom_set(avl_set(node(Y,_,_,empty,empty)),Y).
2544 is_one_element_avl(node(Y,_,_,empty,empty),Y).
2545
2546 % requires El to be ground
2547 construct_one_element_custom_set(El,avl_set(AVL)) :-
2548 empty_avl(E),avl_store(El,E,true,AVL).
2549
2550 construct_avl_set(Avl,Res) :- empty_avl(Avl) -> Res = [] ; Res = avl_set(Avl).
2551
2552 :- block image_explicit(-,?,?,?,?).
2553 image_explicit([],_,Acc,Res,WF) :- !,
2554 construct_avl_set(Acc,AVLS),
2555 ? kernel_objects:equal_object_wf(Res,AVLS,image_explicit,WF).
2556 image_explicit([D1|T],AVLRelation,In,Out,WF) :- !,
2557 ground_value_check(D1,G1),
2558 ((var(T);T==[]) % TO DO: see below, make propagation also interesting in other circumstances
2559 -> must_be_in_domain_check(G1,D1,T,AVLRelation,In,Out,WF)
2560 ; true),
2561 ? image_explicit_aux(G1,D1,AVLRelation,T,In,Out,WF).
2562 image_explicit(Set,_,_,_,_) :- add_error_and_fail(image_explicit,'Unknown set: ',Set).
2563
2564 % a version of image_explicit where the list is guaranteed to be ground
2565 image_explicit_ground([],_,Acc,Res,WF) :- !,
2566 construct_avl_set(Acc,AVLS),
2567 kernel_objects:equal_object_wf(Res,AVLS,image_explicit,WF).
2568 image_explicit_ground([D1|T],AVLRelation,In,Out,WF) :- !,
2569 image_explicit_aux_ground(D1,AVLRelation,T,In,Out,WF).
2570 image_explicit_ground(Set,_,_,_,_) :- add_error_and_fail(image_explicit_ground,'Unknown set: ',Set).
2571
2572 :- block must_be_in_domain_check(-,?,?,?,?,-,?),
2573 must_be_in_domain_check(-,?,-,?,?,?,?).
2574 % if result requires at least one more element, then D must be in domain of Relation
2575 % ensures that we get a domain for j in x = {1|->2,2|->4, 4|->8} & x[{j}]={8}
2576 % we could even propagate using inverse of AVLRelation ?!
2577 must_be_in_domain_check(GroundD,D,T,AVLRelation,In,Out,WF) :-
2578 T==[], % apart from D, there are no more elements to be added
2579 var(GroundD), % otherwise we already have a value for D
2580 delta_witness(In,Out,Witness), % obtain at least one value that D must map to
2581 !,
2582 quick_propagation_element_information(avl_set(AVLRelation),(D,Witness),WF,_). % Witness avoids pending co-routines
2583 % TO DO: we could check that *all* elements of Out have this value
2584 % TO DO: below we could check that In is a subset of Out; e.g., for x = %i.(i:1..10|i+i) & x[{5,j,k}]={16,11}; we could also check that Out is subset of range of relation
2585 must_be_in_domain_check(_,_D,_T,_,_In,_Out,_). % :- print(must_be(D,T,In,Out)),nl.
2586
2587 % provide, if possible, a witness element in Out not in In
2588 delta_witness(In,Out,_Witness) :- (var(In) ; var(Out)),!,fail.
2589 %delta_witness(empty,Out,Witness) :- is_definitely_not_empty_with_witness(Out,Witness).
2590 delta_witness(In,Out,Witness) :-
2591 is_custom_explicit_set(Out,delta_witness),
2592 difference_of_explicit_set(Out,avl_set(In),Diff), % could be expensive to compute !? delay ? print(delta(Diff)),nl,
2593 is_definitely_not_empty_with_witness(Diff,Witness).
2594
2595
2596 :- block image_explicit_aux(-,?,?, ?,?,?,?). % we know that D1 is ground
2597 image_explicit_aux(_,D1,AVLRelation,T,In,Out,WF) :-
2598 all_images(D1,AVLRelation,NewImages), % compute AVLRelation[{D1}]
2599 add_to_avl(NewImages,In,In2),
2600 ? image_explicit(T,AVLRelation,In2,Out,WF).
2601 image_explicit_aux_ground(D1,AVLRelation,T,In,Out,WF) :-
2602 all_images(D1,AVLRelation,NewImages), % compute AVLRelation[{D1}]
2603 add_to_avl(NewImages,In,In2),
2604 image_explicit_ground(T,AVLRelation,In2,Out,WF).
2605
2606 all_images(From,AVLRelation,Images) :-
2607 findall(AY,avl_member_pair_arg1_ground(From,AY,AVLRelation),Images).
2608 % we know that From is ground and AY free variable
2609
2610
2611 % compute relational composition ( ; ) if second arg is an AVL set
2612 % TO DO: add support for infinite closures; avoid expanding them [currently handled by symbolic composition in kernel_relations]
2613 rel_composition_for_explicit_set(Rel1,Rel2,Comp) :- nonvar(Rel2),
2614 Rel2=avl_set(A2), % TO DO: see if we can maybe convert Rel2 to AVL ?
2615 % \+ kernel_relations:keep_symbolic(Rel1), check already done in bsets
2616 expand_custom_set_to_list_gg(Rel1,Relation1,GG,rel_composition_for_explicit_set),
2617 empty_avl(In),
2618 (GG=guaranteed_ground
2619 -> rel_avl_compose2_ground(Relation1,A2,In,Comp)
2620 ; rel_avl_compose2(Relation1,A2,In,Comp)).
2621
2622 :- block rel_avl_compose2(-,?,?,?).
2623 rel_avl_compose2([],_,In,Res) :- construct_avl_set(In,A),
2624 ? equal_object(Res,A,rel_avl_compose2). % as we delay; we need to use equal_object at the end
2625 rel_avl_compose2([(X,Y)|T],A2,In,Out) :-
2626 when((ground(X),ground(Y)),
2627 (all_image_pairs_ground(X,Y,A2,ImagePairs),
2628 add_to_avl(ImagePairs,In,In2),
2629 rel_avl_compose2(T,A2,In2,Out))).
2630
2631 % a version where argument is guaranteed to be ground; no when-ground checks
2632 rel_avl_compose2_ground([],_,In,Res) :- construct_avl_set(In,A),
2633 equal_object(Res,A,rel_avl_compose2). % as we delay; we need to use equal_object at the end
2634 rel_avl_compose2_ground([(X,Y)|T],A2,In,Out) :-
2635 all_image_pairs_ground(X,Y,A2,ImagePairs),
2636 add_to_avl(ImagePairs,In,In2),
2637 rel_avl_compose2_ground(T,A2,In2,Out).
2638
2639 all_image_pairs_ground(From,To,AVLRelation,ImagePairs) :-
2640 findall((From,AY),avl_member_pair_arg1_ground(To,AY,AVLRelation),ImagePairs).
2641 % To: already in AVL format; AY is variable -> we could use avl_fetch_pair directly : findall((From,AY),avl_fetch_pair(To,AVLRelation,AY),ImagePairs).
2642
2643 /* succeeds if it can compute domain by some clever way */
2644 domain_of_explicit_set_wf(global_set(GS),_R,_) :- !,
2645 add_error_and_fail(domain_of_explicit_set_wf,'Cannot compute domain of global set: ',GS).
2646 domain_of_explicit_set_wf(freetype(GS),_R,_) :- !,
2647 add_error_and_fail(domain_of_explicit_set_wf,'Cannot compute domain of freetype: ',GS).
2648 domain_of_explicit_set_wf(avl_set(A),Res,_) :- !,
2649 domain_of_avl_set(A,Res).
2650 ?domain_of_explicit_set_wf(C,R,WF) :- dom_for_specific_closure(C,Dom,_,WF),!,
2651 Dom=R.
2652 domain_of_explicit_set_wf(C,R,_) :-
2653 ? dom_symbolic(C,CC),!,
2654 R=CC.
2655 domain_of_explicit_set_wf(closure(P,T,B),Res,WF) :-
2656 % does not seem to be reached, as dom_symbolic now seems to cover all cases
2657 expand_custom_set_wf(closure(P,T,B),EC,domain_of_explicit_set,WF),
2658 domain_of_list_blocking(EC,R),
2659 normalised_list_to_avl_when_ground(R,Res).
2660
2661 % avl tree is a relation with an integer domain
2662 %avl_integer_domain(node((int(_From),_KeyTo),_True,_,_L,_R)).
2663
2664 % the first clause is in principle faster
2665 % but we don't gain time compared to treatment in second clause; we just avoid building up the domain list
2666 %domain_of_avl_set(A,Res) :- avl_integer_domain(A),
2667 % \+ avl_tools:avl_height_less_than(A,10), % try and detect interval if height >= 10
2668 % avl_is_pf_with_interval_domain(A,First,Last),!,
2669 % construct_interval_closure(First,Last,Res).
2670 domain_of_avl_set(A,Res) :-
2671 avl_domain(A,EC), % -> expand_custom_set(avl_set(A),EC),
2672 domain_of_sorted_list(EC,SizeRes,R), % size of list can be smaller than A if we have a relation
2673 (SizeRes=size_res(Size,int(Last)), R=[int(First)-true|_],
2674 Size>1000,
2675 Size is Last+1-First % we have an interval; quite common that we have functions with intervals as domain
2676 -> debug_println(19,constructing_interval_for_domain(First,Last)),
2677 construct_interval_closure(First,Last,Res)
2678 ; ord_list_to_avlset(R,Res,domain)
2679 ).
2680
2681 % check if an AVL tree represents a function with an interval domain
2682 %avl_is_pf_with_interval_domain(AVL,Min,Max) :-
2683 % avl_min(AVL,(int(Min),_)),avl_max(AVL,(int(Max),_)),
2684 % Size is 1+Max-Min, avl_size_possible(AVL,Size),
2685 % is_avl_partial_function(AVL),
2686 % % now check real size
2687 % avl_size(AVL,Size).
2688
2689 % check if an avl represents a set of integers:
2690 avl_integer_set(node(int(_TOP),_True,_,_L,_R)).
2691
2692 % check if an avl set is an interval:
2693 avl_is_interval(AVL,Min,Max) :-
2694 avl_integer_set(AVL),
2695 avl_min(AVL,int(Min)),avl_max(AVL,int(Max)),
2696 Size is 1+Max-Min,
2697 avl_size_possible(AVL,Size),
2698 avl_size(AVL,Size).
2699
2700
2701
2702 :- use_module(bsyntaxtree,[create_typed_id/3]).
2703 dom_symbolic(closure(Paras,Types,Pred), Res) :-
2704 expand_pair_closure(Paras,Types,Pred,[X,Y],[TX,TY],NewPred),
2705 !, % single argument which is a pair
2706 % simply call code for range ; inverting arguments
2707 bsyntaxtree:check_used_ids_in_ast(Pred),
2708 bsyntaxtree:check_used_ids_in_ast(NewPred),
2709 ran_symbolic_closure(Y,[X],TY,[TX],NewPred,Res).
2710 dom_symbolic(closure(Paras,Types,Pred), Res) :-
2711 append(Xs,[Y],Paras), Xs \= [],
2712 append(TXs,[TY],Types),
2713 % simply call code for range ; inverting arguments
2714 ran_symbolic_closure(Y,Xs,TY,TXs,Pred,Res).
2715 % TO DO: allow computation if Paras is a single argument and more than pair
2716
2717 % just computes domain: it can also be successful for lambda closures
2718 dom_for_specific_closure(closure(P,T,Pred),Domain,Functionality,WF) :-
2719 ? dom_for_specific_closure_aux(P,T,Pred,Domain,Functionality,WF).
2720 dom_for_specific_closure_aux(P,T,Pred,Domain,Functionality,_WF) :-
2721 is_lambda_value_domain_closure(P,T,Pred, DomainValue,Expr),
2722 (preference(find_abort_values,full) -> bsyntaxtree:always_well_defined_or_disprover_mode(Expr)
2723 ; true),
2724 % Warning: this will lead to dom(%x.(x:1..3|1/0)) = 1..3 to be true; discarding WD condition
2725 % this is not as bad as {1|->2}(0) = 3 to be silently failing though; hence only done if TRY_FIND_ABORT = full
2726 !,
2727 Domain=DomainValue,
2728 Functionality=function(total).
2729 %dom_for_specific_closure_aux([ID],[Type],Pred,Domain,Functionality,_WF) :- Functionality=relation,
2730 % Pred = b(exists(Paras,ClosurePred),pred,Info1),
2731 % % dom({res|#(paras).(.... & res= domVal|->ran)}) = {res|#(paras).(.... & res= domVal)}
2732 % closures:select_equality(ClosurePred,ID,RHSExpr,Type,Info,RestPred),
2733 % RHSExpr = couple(DomValue,_),
2734 % closures:does_not_occur_in(ID,RestPred),
2735 % Type = couple(DomT,_),
2736 % TID = b(identifier(ID),DomT,[]),
2737 % % safe_create_texpr
2738 % conjunct_predicates([RestPred,b(equal(TID,DomValue),pred,[])],NewClosurePred),
2739 % NewPred = b(exists(Paras,NewClosurePred),pred,Info1),
2740 % Domain = closure([ID],[DomT],NewPred).
2741 dom_for_specific_closure_aux(P,T,Pred,Domain,Functionality,WF) :-
2742 dom_range_for_specific_closure2(P,T,Pred, Domain,_Range,domain_only,Functionality,WF).
2743 dom_for_specific_closure_aux(P,T,Pred,Domain,Functionality,WF) :-
2744 % see test 2571, also triggered in tests 1970, 2102 for reflexive closure, 1878
2745 Functionality = relation, % TODO: check if DomainA,B disjoint -> Functionality is function(.) if FuncA,FuncB are functions, see invariant rho_c ∈ REAL +-> REAL in f_m1 of Abrial hybrid flight; also do similar treatment for range
2746 is_a_disjunct(Pred,PredA,PredB),
2747 % example from test 2571: f = {x,y| x|->y : %xx.(xx>0|xx) or (x <= 0 & y=1)} & f: INTEGER --> INTEGER
2748 ? dom_for_specific_closure_aux(P,T,PredA,DomainA,_FuncA,WF),
2749 ? dom_for_specific_closure_aux(P,T,PredB,DomainB,_FuncB,WF),
2750 kernel_objects:union_wf(DomainA,DomainB,Domain,WF).
2751
2752
2753
2754 %TO DO treat overwrite closure dom(F1<+F2) = dom(F1) \/ dom(F2)
2755
2756 dom_for_lambda_closure(closure(P,T,Pred),Domain) :-
2757 is_lambda_value_domain_closure(P,T,Pred, DomainValue,_Expr),
2758 Domain=DomainValue.
2759
2760 % TO DO: add total functions
2761 %dom_for_specific_closure2([F],[T],
2762 % b(member(b(identifier(F),T,_), b(total_function(value(A),B),set(couple(DOM,RAN)),_)), pred,_) ,
2763 % A).
2764
2765 :- block domain_of_list_blocking(-,?).
2766 % the list will be sorted according to the term ordering for (_,_); hence it will
2767 % already be sorted for the projection onto the first element
2768 % maybe the speed difference is not worth it ??
2769 domain_of_list_blocking([],[]).
2770 domain_of_list_blocking([(A,_B)|T],[A-true|DT]) :- domain_blocking_aux(T,A,DT).
2771 :- block domain_blocking_aux(-,?,?).
2772 domain_blocking_aux([],_,[]).
2773 domain_blocking_aux([(A,_B)|T],Prev,Res) :-
2774 compare(Comp,A,Prev),
2775 (Comp = '='
2776 -> domain_blocking_aux(T,Prev,Res)
2777 ; Res = [A-true|DT],
2778 (Comp = '<' -> add_error_fail(custom_explicit_sets,'Domain list not_sorted: ',(A,Prev)) ; true),
2779 domain_blocking_aux(T,A,DT) ).
2780
2781 % and now a non-blocking version:
2782 domain_of_sorted_list([],size_res(0,'$none'),[]).
2783 domain_of_sorted_list([(A,_B)|T],Size,[A-true|DT]) :- domain_aux(T,A,DT,1,Size).
2784
2785 % also counts the number of distinct domain elements, used by domain_of_avl_set to detect intervals
2786 domain_aux([],Prev,[],Acc,size_res(Acc,Prev)).
2787 domain_aux([(A,_B)|T],Prev,Res,SizeAcc,Size) :-
2788 compare(Comp,A,Prev),
2789 (Comp = '='
2790 -> domain_aux(T,Prev,Res,SizeAcc,Size) % only count distinct domain elements
2791 ; Res = [A-true|DT], SA1 is SizeAcc+1,
2792 (Comp = '<' -> add_error_fail(custom_explicit_sets,'Domain list not_sorted: ',(A,Prev)) ; true),
2793 domain_aux(T,A,DT,SA1,Size) ).
2794
2795 /* succeeds if it can compute domain by some clever way */
2796 range_of_explicit_set_wf(global_set(GS),_R,_) :- !,
2797 add_error_and_fail(range_of_explicit_set_wf,'Cannot compute range of global set: ',GS).
2798 range_of_explicit_set_wf(freetype(GS),_R,_) :- !,
2799 add_error_and_fail(range_of_explicit_set_wf,'Cannot compute range of freetype: ',GS).
2800 range_of_explicit_set_wf(avl_set(A),Res,_) :- !,
2801 avl_domain(A,EC), % -> expand_custom_set(avl_set(A),EC),
2802 range(EC,R),
2803 normalised_list_to_avl(R,Res).
2804 range_of_explicit_set_wf(C,R,WF) :-
2805 ran_for_specific_closure(C,Ran,WF),!,
2806 Ran=R.
2807 range_of_explicit_set_wf(C,R,_) :-
2808 ran_symbolic(C,CC),!,
2809 R=CC.
2810 range_of_explicit_set_wf(closure(P,T,B),Res,WF) :-
2811 expand_custom_set_wf(closure(P,T,B),EC,range_of_explicit_set_wf,WF),
2812 % TO DO: it would be more useful here to directly just expand the projection onto the last component of P
2813 range_blocking(EC,R),
2814 normalised_list_to_avl_when_ground(R,Res).
2815
2816 % TO DO: in future it is maybe better to add an in_range_wf kernel predicate
2817 ran_symbolic(closure(Paras,Types,Pred), Res) :-
2818 ? (is_memoization_closure(Paras,Types,Pred,_)
2819 -> !,fail % memoization closures can never be dealt with symbolically; we need expansion
2820 ; true),
2821 expand_pair_closure(Paras,Types,Pred,[Y,X],[TY,TX],NewPred),!,
2822 % following test (1541) works with this: 2 : ran({y|#(x).(y = x |-> x + 2 & x : NATURAL)})
2823 ran_symbolic_closure(Y,[X],TY,[TX],NewPred,Res). %, print('res: '),translate:print_bvalue(Res),nl.
2824 ran_symbolic(closure([Y,X],[TY,TX],Pred), Res) :-
2825 ran_symbolic_closure(Y,[X],TY,[TX],Pred,Res).
2826 % TO DO: treat closures with more arguments: we need to quantify Y1,...Yn [Y1,...,Yn,X]
2827
2828 % Replace single Identifier YX of type pair by pair (Y,X) where Y,X are (fresh) variables not occuring in Pred
2829 % example: {y| #(x).(y = x |-> x + 2 & x : NATURAL)} --> {y__1,y__2|#(x).(y__1 |-> y__2 = x |-> x + 2 & x : NATURAL)}
2830 expand_pair_closure([YX],[TYX],Pred,[Y,X],[TY,TX],NewPred) :- TYX = couple(TY,TX),
2831 % Replace single ID YX of type pair by pair (Y,X) where Y,X are (fresh) variables not occuring in Pred
2832 % example: {y| #(x).(y = x |-> x + 2 & x : NATURAL)} --> {y__1,y__2|#(x).(y__1 |-> y__2 = x |-> x + 2 & x : NATURAL)}
2833 % following test (1541) works with this: 2 : ran({y|#(x).(y = x |-> x + 2 & x : NATURAL)})
2834 gensym:gensym(YX,Y),gensym:gensym(YX,X),
2835 create_typed_id(Y,TY,YTID), create_typed_id(X,TX,XTID),
2836 Pair = b(couple(YTID,XTID),TYX,[]),
2837 bsyntaxtree:replace_id_by_expr(Pred,YX,Pair,NewPred).
2838
2839 :- use_module(bsyntaxtree,[create_exists_opt_liftable/3]).
2840 %:- use_module(bsyntaxtree,[add_texpr_info_if_new/3]).
2841 ran_symbolic_closure(Y,Xs,TY,TXs,Pred,Res) :-
2842 % create closure for {Xs | #Y.(Pred)} where Pred uses Y|->Xs
2843 rename_ran_ids(Xs,Pred,[],XIDs,Pred2),
2844 create_typed_id(Y,TY,YTID),
2845 create_exists_opt_liftable([YTID],Pred2,Exists), % Y is liftable as the source is a closure with all ids
2846 %bsyntaxtree:check_used_ids_in_ast(Exists),
2847 %bsyntaxtree:create_exists_opt([YTID],[Pred2],Exists), %or
2848 %b_interpreter_components:create_and_simplify_exists([YTID],Pred2,Exists),
2849 %bsyntaxtree:add_texpr_info_if_new(Exists,allow_to_lift_exists,Exists2), % leads to pending co-routines in self_checks for bsets for apply_to;
2850 % Reason: the tests ground only det WF; without lifting the exists is fully evaluated (and its waitflags with prio 2 and higher grounded) as the wait arguments are ground; with lifting only the det WF is grounded leading to pending coroutines
2851 Res = closure(XIDs,TXs,Exists).
2852
2853
2854
2855 :- use_module(library(lists),[select/3]).
2856
2857 % rename lambda_results :
2858 rename_ran_ids([],Pred,_,[],Pred).
2859 rename_ran_ids([X|TX],Pred,Acc,[XID|TTX],Pred2) :-
2860 % in case X is _lambda_result_ we need to rename it as it then would not get enumerated !
2861 (X == '_lambda_result_'
2862 -> get_fresh_id('_was_lambda_result_',TX,Acc,XID),
2863 % we could remove lambda_result info field, but it will no longer match new id anyway
2864 ? rename_bt(Pred,[rename(X,XID)],Pred2),
2865 TTX=TX
2866 % TODO: maybe we should also remove the prob_annotation('LAMBDA-EQUALITY') info inside Pred for the ids and equality !?
2867 ? ; XID = X, rename_ran_ids(TX,Pred,[X|Acc],TTX,Pred2)
2868 ).
2869
2870 :- use_module(b_ast_cleanup,[get_unique_id/2]).
2871 get_fresh_id(ID,List1,List2,Res) :- nonmember(ID,List1), nonmember(ID,List2),!, Res=ID.
2872 get_fresh_id(ID,_,_,FRESHID) :- nl,print('*** VARIABLE_CLASH PREVENTED: '), print(ID),nl,
2873 get_unique_id(ID,FRESHID).
2874
2875 :- block range_blocking(-,?).
2876 range_blocking([],[]).
2877 range_blocking([(_A,B)|T],[B-true|DT]) :- range_blocking(T,DT).
2878 % and a non-blocking version:
2879 range([],[]).
2880 range([(_A,B)|T],[B-true|DT]) :- range(T,DT).
2881
2882 ran_for_specific_closure(closure(P,T,Pred),Range,WF) :-
2883 dom_range_for_specific_closure2(P,T,Pred, _Domain,Range,range_only,_Functionality,WF).
2884 %ran_for_specific_closure(closure_x(P,T,Pred,_Exp),Card,_) :- ran_for_specific_closure2(P,T,Pred,Card).
2885
2886 :- use_module(bsyntaxtree,[conjunct_predicates/2, disjunct_predicates/2, create_typed_id/3, get_texpr_type/2]).
2887 override_custom_explicit_set_wf(R,S,Res,WF) :- /* R <+ S */
2888 ? nonvar(R),override_custom_explicit_set_aux(R,S,Res,WF).
2889 override_custom_explicit_set_aux(CL,Rel2,Res,_WF) :-
2890 CL=closure(P0,T,B0),
2891 ( preference(convert_comprehension_sets_into_closures,true), % cf keep_symbolic in kernel_relations
2892 (var(Rel2) -> true
2893 ; Rel2 \= avl_set(_)) % if Rel2 is avl_set then maybe better to compute explicitly; unless infinite
2894 ; quick_size_check_larger_than(Rel2,Size2,133) ->
2895 % if we have a large AVL set; then allow expansion up to a larger limit; cf machine 670_002.mch
2896 % a lot of machines use A*B*C <+ {....} to more compactly define large explicit sets
2897 (Size2=inf -> Limit = 200000
2898 ; Limit is min(200000,Size2*150)),
2899 dont_expand_this_closure(P0,T,B0,Limit)
2900 ; dont_expand_this_closure(P0,T,B0) % use default limit and checks for symbolic closure
2901 ),
2902 !,
2903 ? rename_ran_ids(P0,B0,[],P,B), % any '_lambda_result_' id is no longer guaranteed to be assigned a value in all cases
2904 NewClosure=closure(P,T,NewBody),
2905 % B <+ Rel2 ---> NewBody = P:Rel2 or (prj1(P) /: dom(Rel2) & B)
2906 % TODO better? : %x.(x:Domain|IF x:dom(SFF) THEN SFF(x) ELSE DEFAULT)?
2907 generate_typed_id_pairs(P,T,NestedPairs),
2908 get_texpr_type(NestedPairs,PairsType),
2909 RelPairsType = set(PairsType),
2910 ValS = b(value(Rel2),RelPairsType,[]),
2911 MemS = b(member(NestedPairs,ValS),pred,[]), % P:Rel2
2912 get_prj1(NestedPairs,DomExpr),
2913 get_texpr_type(DomExpr,DomType),
2914 Domain = b(domain(ValS),set(DomType),[]), % TO DO: perform some optimisations like dom(%x.(P|E)) --> {x|P}
2915 %kernel_relations:domain_wf(Rel2,DomainOfRel2,WF), Domain = b(value(DomainOfRel2),DomType,[]), % this DOES NOT work for 1619, 1706 where override is used for infinite functions
2916 NotMemDomS = b(not_member(DomExpr,Domain),pred,[]), % prj1(P) /: dom(Rel2)
2917 conjunct_predicates([NotMemDomS,B],RHS),
2918 disjunct_predicates([MemS,RHS],NewBody),
2919 %print(override),nl, bsyntaxtree:check_used_ids_in_ast(NewBody),
2920 mark_closure_as_symbolic(NewClosure,Res).
2921 % TO DO: add a case where for second set we have: dont_expand_this_closure
2922 override_custom_explicit_set_aux(R,S,Res,WF) :-
2923 is_custom_explicit_set(R,override_custom_explicit_set),
2924 nonvar(S), is_custom_explicit_set(S,override_custom_explicit_set),
2925 %% hit_profiler:add_profile_hit(override(R,S),3), %%
2926 override_custom_explicit_set2(R,S,Res,WF).
2927
2928 override_custom_explicit_set2(R,S,Res,_WF) :- is_one_element_custom_set(S,(X,Y)),
2929 override_pair_explicit_set(R,X,Y,NewR),!, % override pair only succeeds for avl_set
2930 Res=NewR.
2931 % TO DO: if R is very large and S relatively small : iterate by calling override_pair_explicit_set
2932 override_custom_explicit_set2(R,S,Res,WF) :-
2933 \+ dont_expand_this_explicit_set(S), % see test 2564
2934 expand_custom_set_wf(R,ER,override_custom_explicit_set_aux1,WF),
2935 expand_custom_set_wf(S,ES,override_custom_explicit_set_aux2,WF),
2936 override_list(ER,ES,LRes,Done),
2937 finish_restriction(Done,LRes,Res).
2938
2939 quick_size_check_larger_than(Set,Size,Limit) :-
2940 quick_custom_explicit_set_approximate_size(Set,Size),
2941 (is_inf_or_overflow_card(Size) -> true ; Size > Limit).
2942 get_prj1(b(couple(DomExpr,_),_,_),Prj1) :- !, Prj1 = DomExpr.
2943 get_prj1(BE,b(first_of_pair(BE),DT,[])) :- % some closures have a single identifier; we need to apply prj1
2944 BE = b(_E,couple(DT,_RT),_I).
2945
2946 % translate a parameter name and type list into a nested-pair value
2947 generate_typed_id_pairs([ID|IT],[Type|TT],Res) :- create_typed_id(ID,Type,TypedID),
2948 conv2(IT,TT,TypedID,Res).
2949 conv2([],[],X,X).
2950 conv2([ID|IT],[Type|TT],Acc,Res) :- create_typed_id(ID,Type,TypedID),
2951 get_texpr_type(Acc,AccType),
2952 Couple = b(couple(Acc,TypedID),couple(AccType,Type),[]),
2953 conv2(IT,TT,Couple,Res).
2954
2955 :- block override_list(-,?,?,?), override_list(?,-,?,?).
2956 override_list([],S,Res,Done) :- !, copy_to_true_list(S,Res,Done).
2957 override_list(R,[],Res,Done) :- !, copy_to_true_list(R,Res,Done).
2958 override_list([(From1,To1)|T1],[(From2,To2)|T2],Res,Done) :-
2959 (From1 @< From2
2960 -> Res = [(From1,To1)-true|TR], override_list(T1,[(From2,To2)|T2],TR,Done)
2961 ; From2 @< From1
2962 -> Res = [(From2,To2)-true|TR], override_list([(From1,To1)|T1],T2,TR,Done)
2963 ; override_list(T1,[(From2,To2)|T2],Res,Done)).
2964
2965 :- block copy_to_true_list(-,?,?).
2966 % add -true to get lists that can be converted to avl
2967 copy_to_true_list([],[],true).
2968 copy_to_true_list([H|T],[H-true|CT],Done) :- copy_to_true_list(T,CT,Done).
2969
2970 %:- use_module(extrasrc(b_expression_sharing),[cse_optimize_predicate/2]).
2971 :- use_module(closures,[get_domain_range_for_closure_types/3]).
2972 % compute a closure with the functionality violations of a closure
2973 symbolic_functionality_check_closure(closure(P,T,B),closure([DID,ID1,ID2],[DomType,RanType,RanType],Body)) :-
2974 % construct {d,z_,z__| (d,z_):R & (d,z__):R & z_\= z__}
2975 generate_typed_id_pairs(P,T,NestedPairs),
2976 get_texpr_type(NestedPairs,PairsType),
2977 RelPairsType = set(PairsType),
2978 TRel = b(value(closure(P,T,B)),RelPairsType,[]),
2979 DID = '_domain_el', % element in domain, for which we search for two different range elements:
2980 ID1 = '_zzzz_unary', ID2 = '_zzzz_binary',
2981 TDID = b(identifier(DID),DomType,[]),
2982 TID1 = b(identifier(ID1),RanType,[]),
2983 TID2 = b(identifier(ID2),RanType,[]),
2984 construct_pair_membership(TDID,TID1,PairsType,TRel,Mem1),
2985 construct_pair_membership(TDID,TID2,PairsType,TRel,Mem2),
2986 get_domain_range_for_closure_types(T,DomType,RanType),
2987 NeqRan = b(not_equal(TID1,TID2), pred, []),
2988 conjunct_predicates([Mem1,Mem2,NeqRan],Body),
2989 %TODO: cse_optimize_predicate(UnOptBody,Body),
2990 bsyntaxtree:check_used_ids_in_ast(Body).
2991 %bsyntaxtree:check_ast(Body).
2992
2993 :- use_module(bsyntaxtree,[replace_ids_by_exprs/4]).
2994 % assumes TID1 and TID2 are distinct identifiers
2995 construct_pair_membership(TID1,TID2,_PairsType,b(Rel,_,_),MemPred) :-
2996 is_comprehension_set_or_closure(Rel,P,_T,Pred0),
2997 P = [ID1,ID2],
2998 !, % TID1|->TID2 : {x,y|P(x,y)} ==> P(TID1,TID2); see also remove_member_comprehension ast_cleanup rule
2999 replace_ids_by_exprs(Pred0,[ID1,ID2],[TID1,TID2],MemPred), % simultaneous replacement, in case of clashes !
3000 debug_println(9,inlined_pair_membership(ID1,ID2)).
3001 construct_pair_membership(TID1,TID2,PairsType,TRel,MemPred) :-
3002 MemPred = b(member( b(couple(TID1,TID2),PairsType,[]),TRel),pred,[]).
3003
3004
3005
3006 % compute a closure with the injectivity violations of a closure
3007 symbolic_injectivity_check_closure(closure(P,T,B),closure([RID,ID1,ID2],[RanType,DomType,DomType],Body)) :-
3008 % construct {r,z_,z__| (z_,r):R & (z__,r):R & z_\= z__}
3009 generate_typed_id_pairs(P,T,NestedPairs),
3010 get_texpr_type(NestedPairs,PairsType),
3011 RelPairsType = set(PairsType),
3012 TRel = b(value(closure(P,T,B)),RelPairsType,[]), % what if closure body B has WD condition?
3013 RID = '_range', ID1 = '_zzzz_unary', ID2 = '_zzzz_binary',
3014 TRID = b(identifier(RID),RanType,[]),
3015 TID1 = b(identifier(ID1),DomType,[]),
3016 TID2 = b(identifier(ID2),DomType,[]),
3017 construct_pair_membership(TID1,TRID,PairsType,TRel,Mem1),
3018 construct_pair_membership(TID2,TRID,PairsType,TRel,Mem2),
3019 get_domain_range_for_closure_types(T,DomType,RanType),
3020 NeqRan = b(not_equal(TID1,TID2), pred, []),
3021 conjunct_predicates([Mem1,Mem2,NeqRan],Body),
3022 bsyntaxtree:check_used_ids_in_ast(Body).
3023 %bsyntaxtree:check_ast(Body).
3024
3025 % -------------------------
3026
3027
3028 % check whether we have a partial function
3029 is_avl_partial_function(empty) :- !.
3030 is_avl_partial_function(node((KeyFrom,_KeyTo),_True,_,L,R)) :- !,
3031 is_avl_partial_function2(L,'$$MIN$$',KeyFrom),
3032 is_avl_partial_function2(R,KeyFrom,'$$MAX$$').
3033 is_avl_partial_function(X) :- add_internal_error('Not avl_set or relation: ',is_avl_partial_function(X)),fail.
3034
3035 % we traverse the tree from top to bottom, keeping track of possible upper- and lower-bounds
3036 % if any value matches the upper or lower bound, the we do not have a partial function
3037 is_avl_partial_function2(empty,_,_).
3038 is_avl_partial_function2(node((KeyFrom,_KeyTo),_True,_,L,R),ParentFrom,ParentTo) :-
3039 KeyFrom \= ParentFrom, KeyFrom \= ParentTo,
3040 is_avl_partial_function2(L,ParentFrom,KeyFrom),
3041 is_avl_partial_function2(R,KeyFrom,ParentTo).
3042
3043 % the dual of the above, returning a counter example
3044 is_not_avl_partial_function(node((KeyFrom,_KeyTo),_True,_,L,R),DuplicateKey) :- !,
3045 (is_not_avl_partial_function2(L,'$$MIN$$',KeyFrom,DuplicateKey) -> true
3046 ; is_not_avl_partial_function2(R,KeyFrom,'$$MAX$$',DuplicateKey)).
3047 is_not_avl_partial_function2(node((KeyFrom,_KeyTo),_True,_,L,R),ParentFrom,ParentTo,DuplicateKey) :-
3048 ( KeyFrom = ParentFrom -> DuplicateKey=KeyFrom
3049 ; KeyFrom = ParentTo -> DuplicateKey=KeyFrom
3050 ; is_not_avl_partial_function2(L,ParentFrom,KeyFrom,DuplicateKey) -> true
3051 ; is_not_avl_partial_function2(R,KeyFrom,ParentTo,DuplicateKey) -> true).
3052
3053
3054 % check whether we have a function which is total over a given domain; both as AVL sets
3055 is_avl_total_function_over_domain(empty,empty) :- !.
3056 is_avl_total_function_over_domain(AVLFun,AVLDom) :-
3057 avl_domain(AVLFun,FunList),
3058 avl_domain(AVLDom,DomList),
3059 is_avl_total_fun2(FunList,DomList).
3060
3061 is_avl_total_fun2([],[]).
3062 is_avl_total_fun2([(From,_To)|FT],[From|DomT]) :- is_avl_total_fun2(FT,DomT).
3063
3064
3065 %not_is_avl_partial_function(AVLF) :- \+ is_avl_partial_function(AVLF).
3066
3067 :- use_module(kernel_equality,[membership_test_wf/4]).
3068 % check whether an AVL Relation is not over a specific domain & range
3069 is_not_avl_relation_over_domain_range(AVLRel,Domain,Range,WF) :- AVLRel \= empty,
3070 avl_min_pair(AVLRel,RFrom,RTo),
3071 membership_test_wf(Domain,RFrom,MemRes,WF),
3072 is_not_avl_rel_dom1(MemRes,RFrom,RTo,AVLRel,Domain,Range,WF).
3073
3074 :- block is_not_avl_rel_dom1(-, ?,?,?,?,?,?).
3075 is_not_avl_rel_dom1(pred_false,_,_,_,_,_,_WF).
3076 is_not_avl_rel_dom1(pred_true,RFrom,RTo,AVLRel,Domain,Range,WF) :-
3077 membership_test_wf(Range,RTo,MemRes,WF),
3078 is_not_avl_rel_dom2(MemRes,RFrom,RTo,AVLRel,Domain,Range,WF).
3079
3080 :- block is_not_avl_rel_dom2(-, ?,?,?,?,?,?).
3081 is_not_avl_rel_dom2(pred_false,_,_,_,_,_,_WF).
3082 is_not_avl_rel_dom2(pred_true,RFrom,RTo,AVLRel,Domain,Range,WF) :-
3083 avl_next((RFrom,RTo),AVLRel,(RFrom2,RTo2)),
3084 membership_test_wf(Domain,RFrom2,MemRes,WF),
3085 is_not_avl_rel_dom1(MemRes,RFrom2,RTo2,AVLRel,Domain,Range,WF).
3086
3087 % check whether an AVL Relation is not over a specific range
3088 is_not_avl_relation_over_range(AVLRel,Range,WF) :- AVLRel \= empty,
3089 avl_min_pair(AVLRel,RFrom,RTo),
3090 membership_test_wf(Range,RTo,MemRes,WF),
3091 is_not_avl_rel_ran2(MemRes,RFrom,RTo,AVLRel,Range,WF).
3092
3093 :- block is_not_avl_rel_ran2(-, ?,?,?,?,?).
3094 is_not_avl_rel_ran2(pred_false,_,_,_,_,_WF).
3095 is_not_avl_rel_ran2(pred_true,RFrom,RTo,AVLRel,Range,WF) :-
3096 avl_next((RFrom,RTo),AVLRel,(RFrom2,RTo2)),
3097 kernel_equality:membership_test_wf(Range,RTo2,MemRes,WF),
3098 is_not_avl_rel_ran2(MemRes,RFrom2,RTo2,AVLRel,Range,WF).
3099
3100 % check whether we have a relation
3101 is_avl_relation(node((_KeyFrom,_KeyTo),_True,_,_,_)).
3102
3103 % check whether a Relation has all its range elments in a certain Range (not necessarily AVL)
3104 % TO DO: if Domain is an interval: we could take avl_min and avl_max and rely on lexicographic ordering
3105 is_avl_relation_over_domain(AVL,IntervalClosure,_WF) :-
3106 is_interval_closure_or_integerset(IntervalClosure,Low,Up),!,
3107 ((avl_min(AVL,(int(ALow),_)), avl_max(AVL,(int(AUp),_)))
3108 -> cs_greater_than_equal(ALow,Low), cs_greater_than_equal(Up,AUp) %,print(ok),nl
3109 ; (AVL=empty -> true ; add_error_and_fail(is_avl_relation_over_domain,'Not a relation with integer domain: ',AVL))).
3110 is_avl_relation_over_domain(_,Domain,_) :-
3111 quick_is_definitely_maximal_set(Domain),!.
3112 %is_definitely_maximal_set(Domain),!.
3113 ?is_avl_relation_over_domain(AVL,Domain,WF) :- is_avl_relation_over_domain2(AVL,Domain,WF).
3114 is_avl_relation_over_domain2(empty,_,_).
3115 is_avl_relation_over_domain2(node((KeyFrom,_KeyTo),_,_,L,R), Domain,WF) :-
3116 ? is_avl_relation_over_domain2(L, Domain,WF),
3117 ? is_avl_relation_over_domain2(R, Domain,WF),
3118 ? kernel_objects:check_element_of_wf(KeyFrom,Domain,WF).
3119
3120 % : faster to check than is_definitely_maximal_set
3121 quick_is_definitely_maximal_set(X) :- nonvar(X),
3122 quick_is_definitely_maximal_set_aux(X).
3123 quick_is_definitely_maximal_set_aux(global_set(GS)) :-
3124 nonvar(GS),is_maximal_global_set(GS).
3125 quick_is_definitely_maximal_set_aux(avl_set(AVL)) :-
3126 quick_definitely_maximal_set_avl(AVL).
3127
3128 % check whether a Relation has all its range elments in a certain Range (not necessarily AVL)
3129
3130
3131
3132 is_avl_relation_over_range(empty,_,_) :- !.
3133 is_avl_relation_over_range(_,Range,_) :-
3134 %quick_is_definitely_maximal_set(Range),
3135 is_definitely_maximal_set(Range),
3136 !.
3137 ?is_avl_relation_over_range(AVL,Range,WF) :- is_avl_relation_over_range2(AVL,Range,WF).
3138
3139 is_avl_relation_over_range2(empty,_,_).
3140 is_avl_relation_over_range2(node((_KeyFrom,KeyTo),_,_,L,R), Range,WF) :-
3141 ? is_avl_relation_over_range(L, Range,WF),
3142 ? kernel_objects:check_element_of_wf(KeyTo,Range,WF),
3143 ? is_avl_relation_over_range2(R, Range,WF).
3144
3145 % safe version of is_avl_sequence, does not throw error when type cannot be a sequence
3146 safe_is_avl_sequence(empty) :- !.
3147 safe_is_avl_sequence(node((int(KeyFrom),_KeyTo),_True,_,L,R)) :- !,
3148 is_avl_sequence2(L,0,KeyFrom),
3149 is_avl_sequence2(R,KeyFrom,'$$MAX$$').
3150
3151 is_avl_sequence(empty) :- !.
3152 is_avl_sequence(node((int(KeyFrom),_KeyTo),_True,_,L,R)) :- !,
3153 is_avl_sequence2(L,0,KeyFrom),
3154 is_avl_sequence2(R,KeyFrom,'$$MAX$$').
3155 is_avl_sequence(X) :- add_error_and_fail(is_avl_sequence,'Not avl_set or sequence: ',X).
3156
3157 % we traverse the tree from top to bottom, keeping track of possible upper- and lower-bounds
3158 % if any value matches the upper or lower bound, then we do not have a partial function
3159 is_avl_sequence2(empty,X,Y) :-
3160 (Y=='$$MAX$$' -> true ; Y is X+1). % otherwise there is a gap in the sequence
3161 is_avl_sequence2(node((int(KeyFrom),_KeyTo),_,_,L,R),ParentFrom,ParentTo) :-
3162 KeyFrom > ParentFrom, KeyFrom \= ParentTo,
3163 is_avl_sequence2(L,ParentFrom,KeyFrom),
3164 is_avl_sequence2(R,KeyFrom,ParentTo).
3165
3166 % for performance: it is not worthwhile to make a version that checks that
3167 % we have a sequence over a range using a single traversal
3168
3169
3170 % get avl_sequence elements as sorted list (without indices)
3171 % used by external function REPLACE
3172 get_avl_sequence(AVL,SeqList) :-
3173 get_avl_sequence_dcg(AVL,SeqList,[]).
3174
3175 get_avl_sequence_dcg(empty) --> [].
3176 get_avl_sequence_dcg(node((int(_),SeqEl),_True,_,L,R)) -->
3177 get_avl_sequence_dcg(L),
3178 [SeqEl],
3179 get_avl_sequence_dcg(R).
3180
3181
3182 % ---------------------------
3183 prefix_of_custom_explicit_set(avl_set(A),MinIndex,Result,WF) :-
3184 size_of_avl_sequence(A,Size,WF),
3185 (MinIndex > Size
3186 -> add_wd_error('index larger than size of sequence in prefix_sequence (/|\\)! ', '>'(MinIndex,Size),WF)
3187 % ; MinIndex = 0 -> Result = [] % case already treated in kernel_relations
3188 ; MinIndex = Size -> Result=avl_set(A)
3189 ; prefix_of_custom_explicit_set2(A,MinIndex,OrdList,[]),
3190 ord_list_to_avlset(OrdList,Result,prefix_of_custom_explicit_set)
3191 ).
3192 prefix_of_custom_explicit_set2(empty,_MaxIndex) --> {true}.
3193 prefix_of_custom_explicit_set2(node((int(KeyFrom),KeyTo),_True,_,L,R),MaxIndex) -->
3194 ({KeyFrom = MaxIndex}
3195 -> prefix_of_custom_explicit_set2(L,MaxIndex), [((int(KeyFrom),KeyTo)-true)]
3196 ; {KeyFrom > MaxIndex} -> prefix_of_custom_explicit_set2(L,MaxIndex)
3197 ; prefix_of_custom_explicit_set2(L,MaxIndex), [((int(KeyFrom),KeyTo)-true)],
3198 prefix_of_custom_explicit_set2(R,MaxIndex)
3199 ).
3200
3201 % size is only well-defined for sequences:
3202 size_of_custom_explicit_set(avl_set(AVL),int(Size),WF) :- size_of_avl_sequence(AVL,Size,WF).
3203 size_of_custom_explicit_set(closure(P,T,B),Res,WF) :-
3204 is_lambda_value_domain_closure(P,T,B, DomainValue,_Expr),
3205 kernel_cardinality_attr:finite_cardinality_as_int_wf(DomainValue,Res,WF).
3206
3207 size_of_avl_sequence(AVL,Size,WF) :-
3208 avl_min_pair(AVL,int(One),_), One =\= 1,
3209 !,
3210 avl_size(AVL,Sz),
3211 add_wd_error('Applying size to a value which is not a sequence (minimum index is not 1)',b(value(avl_set(AVL)),seq(any),[]),WF),
3212 Size=Sz. % other calls to size_of_avl_sequence currently expect a value
3213 size_of_avl_sequence(AVL,Size,WF) :-
3214 \+ preference(find_abort_values,false),
3215 \+ is_avl_sequence(AVL), % perform full sequence check
3216 !,
3217 avl_size(AVL,Sz),
3218 add_wd_error('Applying size to a value which is not a sequence',b(value(avl_set(AVL)),seq(any),[]),WF),
3219 Size=Sz. % other calls to size_of_avl_sequence currently expect a value
3220 size_of_avl_sequence(AVL,Size,WF) :-
3221 avl_max_pair(AVL,int(Sz),_),
3222 avl_height(AVL,H), % we cannot compute the height together with max; we need the longest path!
3223 get_min_max_card(H,MinSize,MaxSize),
3224 %avl_size(AVL,Real),format('AVL SeqSize: ~w, height: ~w, real size:~w, min: ~w, max: ~w~n',[Sz,H,Real,MinSize,MaxSize]),
3225 (Sz > MaxSize
3226 -> add_wd_error('Applying size to a value which is not a sequence (maximum index too large)',b(value(avl_set(AVL)),seq(any),[]),WF),
3227 avl_size(AVL,Size)
3228 % triggered by e.g. size({0|->1,0|->2,1|->3}) or size({0|->1,1|->2,3|->3,1|->22,1|->23,1|->24,1|->25,1|->26})
3229 ; Sz < MinSize
3230 -> add_wd_error('Applying size to a value which is not a sequence (maximum index too small)',b(value(avl_set(AVL)),seq(any),[]),WF),
3231 avl_size(AVL,Size)
3232 % triggered by e.g. size([0,2,2,2] |> {2})
3233 ; Size=Sz).
3234
3235 get_min_max_card(Height,MinCard,MaxCard) :-
3236 % page 460, Knuth 3: The height of a balanced tree with N internal nodes always lies between lg(N+1) and 1.4405 lg(N+2) - 0.3277
3237 MaxCard is 2^Height - 1,
3238 % 1.618034 is golden ration phi 0.5(1+sqrt(5)) , 2.236068 is sqrt(5)
3239 % proof in Knuth uses fact: N > phi^(h+2)/sqrt(5) - 2
3240 MinCard is ceiling((1.61803398875**(Height+2)) / 2.2360679775 - 2).
3241
3242 % check if a candidate size is possible given height:
3243 avl_size_possible(AVL,SizeCandidate) :-
3244 avl_height(AVL,Height), % TO DO: restrict to something like log2 of Height
3245 get_min_max_card(Height,MinCard,MaxCard),
3246 MinCard =< SizeCandidate,
3247 SizeCandidate =< MaxCard.
3248
3249
3250 suffix_of_custom_explicit_set(avl_set(A),MinIndex,Result,WF) :-
3251 size_of_avl_sequence(A,Size,WF),
3252 (MinIndex > Size
3253 -> add_wd_error('index larger than size of sequence in suffix_sequence (\\|/)! ', '>'(MinIndex,Size),WF)
3254 % ; MinIndex = 0 -> Result = avl_set(A) % case already treated in kernel_relations
3255 ; MinIndex = Size -> Result=[]
3256 ; suffix_of_custom_explicit_set2(A,MinIndex,OrdList,[]),
3257 ord_list_to_avlset(OrdList,Result,suffix_of_custom_explicit_set)
3258 ).
3259 suffix_of_custom_explicit_set2(empty,_MinIndex) --> {true}.
3260 suffix_of_custom_explicit_set2(node((int(KeyFrom),KeyTo),_True,_,L,R),MinIndex) -->
3261 ({KeyFrom =< MinIndex} -> suffix_of_custom_explicit_set2(R,MinIndex)
3262 ; {ShiftedKeyFrom is KeyFrom-MinIndex},
3263 ({KeyFrom =:= MinIndex+1}
3264 -> {true} ; suffix_of_custom_explicit_set2(L,MinIndex)),
3265 [((int(ShiftedKeyFrom),KeyTo)-true)],
3266 suffix_of_custom_explicit_set2(R,MinIndex)
3267 ).
3268
3269 shift_avl_sequence_to_ord_list(AVL,Offset,ShiftedOrdList) :-
3270 avl_to_list(AVL,List),shift_seq(List,Offset,ShiftedOrdList).
3271 % it does not seem to be worth to use avl_to_list_dcg_offset or a variation thereof
3272 % it is not really slower to do two traversals (avl_to_list and shift_seq)
3273
3274 shift_seq([],_,[]).
3275 shift_seq([(int(I),Val)-true|T],Offset,[(int(NI),Val)-true|ST]) :- NI is I+Offset,
3276 shift_seq(T,Offset,ST).
3277
3278 % a version of shift_avl_sequence_to_ord_list which also checks that we have a sequence,
3279 % i.e., the indices are exactly 1..n; IsSeq is set to false if this is not the case
3280 shift_check_avl_sequence_to_ord_list(AVL,Offset,ShiftedOrdList,IsSeq) :-
3281 avl_to_list(AVL,List),
3282 shift_check_seq(List,1,Offset,ShiftedOrdList,IsSeq).
3283
3284 shift_check_seq([],_,_,[],true).
3285 shift_check_seq([(int(I),Val)-true|T],Expected,Offset,[(int(NI),Val)-true|ST],IsSeq) :- NI is I+Offset,
3286 (I==Expected -> E1 is Expected+1, shift_check_seq(T,E1,Offset,ST,IsSeq)
3287 ; IsSeq=false, shift_seq(T,Offset,ST)).
3288
3289 % CheckSeq is either wd_check(Span,WF): add a WD error if the argument is not a sequence
3290 % or no_check: e.g., when used for backwards propagation from a result value
3291 check_is_sequence(IsSeq,Op,AVL,wd_check(Span,WF)) :- IsSeq==false, !,
3292 add_wd_error_span('Sequence operator applied to a value which is not a sequence: ',
3293 Op:b(value(avl_set(AVL)),seq(any),[]),Span,WF).
3294 check_is_sequence(_,_,_,_).
3295
3296 concat_custom_explicit_set(avl_set(S1),Seq2,Res,WF) :- nonvar(Seq2), Seq2=avl_set(S2),
3297 size_of_avl_sequence(S1,Size1,WF),
3298 shift_check_avl_sequence_to_ord_list(S2,Size1,OL2,IsSeq),
3299 check_is_sequence(IsSeq,'^ (concatenation)',S2,wd_check(unknown,WF)),
3300 % if OL2 is small we could use avl_store like in append_custom_explicit_set
3301 %avl_to_list(S1,OL1),
3302 avl_to_list_dcg(S1,NewOrdList,OL2), % use OL2 rather than [] as tail
3303 %append(OL1,OL2,NewOrdList), % we could avoid traversing OL1 again by doing a custom avl_to_list/3 which specifies tail
3304 ord_list_to_avlset(NewOrdList,Res,concat). % , print_term_summary(res_concat(Res)).
3305
3306 % a DCG version of avl_to_list; allows to call it with something else than [] as tail
3307 avl_to_list_dcg(empty) --> [].
3308 avl_to_list_dcg(node(Key,Val,_,L,R)) -->
3309 avl_to_list_dcg(L), [(Key-Val)],
3310 avl_to_list_dcg(R).
3311
3312 /* conc: concatenation of sequence of sequences (general_concat) */
3313 conc_custom_explicit_set(avl_set(AVL),Res,Span,WF) :-
3314 avl_min_pair(AVL,int(ONE),First),
3315 conc2_cs(First,ONE,1,AVL,0,NewOrdList,IsSeq),
3316 check_is_sequence(IsSeq,conc,AVL,wd_check(Span,WF)),
3317 ord_list_to_avlset(NewOrdList,Res,conc).
3318
3319 % IsSeq is set to false if the outer or one of the inner arguments is not a sequence
3320 % (otherwise IsSeq is left unbound)
3321 conc2_cs(Seq,NrSeq,Expected,AVL,Offset,OrdList,IsSeq) :-
3322 (NrSeq==Expected -> true ; IsSeq=false),
3323 add_seq(Seq,Offset,OrdList,NewOffset,TailOrd,IsSeq),
3324 (avl_next((int(NrSeq),Seq),AVL,(int(N2),Seq2))
3325 -> E1 is Expected+1,
3326 conc2_cs(Seq2,N2,E1,AVL,NewOffset,TailOrd,IsSeq)
3327 ; TailOrd=[]).
3328
3329 add_seq([],Offset,OrdRes,NewOffset,TailOrdRes,_) :- !, NewOffset=Offset, TailOrdRes=OrdRes.
3330 add_seq(avl_set(ASeq),Offset,OrdRes,NewOffset,TailOrd,IsSeq) :- !,
3331 avl_to_list_dcg_offset_chk(ASeq,Offset,1,Next,IsSeq,OrdRes,TailOrd), NewOffset is Offset+Next-1.
3332 add_seq(Seq,Offset,OrdRes,NewOffset,TailOrd,IsSeq) :-
3333 add_internal_error('Unexpected value:',add_seq(Seq,Offset,OrdRes,NewOffset,TailOrd,IsSeq)),
3334 fail.
3335
3336 % a version of avl_to_list for sequences which autmatically adds an offset
3337 % it also checks that the indices are exactly Expected, Expected+1, ...
3338 % IsSeq is set to false if this is not the case; Next is the next expected index after the traversal
3339 avl_to_list_dcg_offset_chk(empty,_,E,E,_) --> [].
3340 avl_to_list_dcg_offset_chk(node((int(Idx),El),Val,_,L,R),Offset,E0,E2,IsSeq) -->
3341 avl_to_list_dcg_offset_chk(L,Offset,E0,E1,IsSeq),
3342 {NIdx is Idx+Offset, (Idx==E1 -> true ; IsSeq=false), E11 is E1+1},
3343 [((int(NIdx),El)-Val)],
3344 avl_to_list_dcg_offset_chk(R,Offset,E11,E2,IsSeq).
3345
3346
3347 prepend_custom_explicit_set(avl_set(S1),ObjectToPrepend,Res,Span,WF) :-
3348 %hit_profiler:add_profile_hit(prepend_custom_explicit_set(avl_set(S1),ObjectToPrepend,Res)),
3349 element_can_be_added_or_removed_to_avl(ObjectToPrepend),
3350 shift_check_avl_sequence_to_ord_list(S1,1,OL1,IsSeq),
3351 check_is_sequence(IsSeq,'-> (insert front)',S1,wd_check(Span,WF)),
3352 ord_list_to_avlset([(int(1),ObjectToPrepend)-true|OL1],Res).
3353
3354 append_custom_explicit_set(avl_set(S1),ObjectToAppend,Res,WF) :-
3355 element_can_be_added_or_removed_to_avl(ObjectToAppend), % implies that ObjectToAppend is ground
3356 size_of_avl_sequence(S1,Size1,WF), NewSize is Size1+1,
3357 add_ground_element_to_explicit_set_wf(avl_set(S1),(int(NewSize),ObjectToAppend),Res,WF).
3358
3359 % compute tail of a sequence and also return first element
3360 tail_sequence_custom_explicit_set(avl_set(S1),First,Res,Span,WF) :-
3361 shift_check_avl_sequence_to_ord_list(S1,-1,NewOrdList,IsSeq),
3362 (NewOrdList = [(int(0),First)-true|TailOL]
3363 -> check_is_sequence(IsSeq,tail,S1,wd_check(Span,WF)),
3364 ord_list_to_avlset(TailOL,Res)
3365 ; add_wd_error_span('tail argument is not a sequence!', avl_set(S1),Span,WF)
3366 % add_error_fail(tail_sequence,'tail applied to ', NewOrdList))
3367 ).
3368 last_sequence_explicit_set(avl_set(AVL),Last,_Span,WF) :-
3369 size_of_avl_sequence(AVL,_,WF), % checks that we have a sequence: cheap checks; full check only if TRY_FIND_ABORT is set
3370 avl_max_pair(AVL,int(_Sz),Last).
3371 %first_sequence_explicit_set(avl_set(AVL),First) :- % not used anymore; apply_to used instead
3372 % avl_min_pair(AVL,int(_One),First).
3373
3374 % compute front and return last element at the same time
3375 % CheckSeq is wd_check(Span,WF) or no_check
3376 front_sequence_custom_explicit_set(avl_set(AVL),Last,Res,CheckSeq) :-
3377 (CheckSeq = wd_check(_,WF)
3378 -> size_of_avl_sequence(AVL,_,WF) % cheap checks; full check only if TRY_FIND_ABORT is set
3379 ; true),
3380 avl_max_pair(AVL,int(Size),Last),
3381 direct_remove_element_from_avl(AVL, (int(Size),Last), Res). % we know Last is already in AVL-converted format
3382
3383
3384 reverse_custom_explicit_set(avl_set(AVL),Res,CheckSeq) :-
3385 avl_to_list_dcg_offset_chk(AVL,0,1,S1,IsSeq,List,[]), % S1 = Size+1
3386 (CheckSeq=no_check -> IsSeq \== false % fail and use general code if result is not a sequence
3387 ; check_is_sequence(IsSeq,rev,AVL,CheckSeq)),
3388 reverse_list(List,S1,[],RevList),
3389 ord_list_to_avl(RevList,RevAVL),
3390 Res=avl_set(RevAVL).
3391
3392 reverse_list([],_,Acc,Acc).
3393 reverse_list([(int(Idx),El)-V|T],S1,Acc,Res) :-
3394 NewIdx is S1 - Idx,
3395 reverse_list(T,S1,[(int(NewIdx),El)-V|Acc],Res).
3396
3397 % check if a relation is injective ; compute range at the same time; note AVL can be empty
3398 is_injective_avl_relation(AVL,RangeRes) :-
3399 avl_domain(AVL,ElList),
3400 empty_avl(EmptyAcc),
3401 is_avl_inj_list(ElList,EmptyAcc,Range),
3402 construct_avl_set(Range,RangeRes).
3403
3404 is_avl_inj_list([],Range,Range).
3405 is_avl_inj_list([(_From,To)|T],InRange,OutRange) :-
3406 (avl_fetch(To,InRange) -> fail /* this is not an injection; a range element is repeated */
3407 ; avl_store(To,InRange,true,InRange1),
3408 is_avl_inj_list(T,InRange1,OutRange)
3409 ).
3410
3411 % Example predicates that work with code below:
3412 % card(id((1..1000)*(1..1000))~)=1000*1000
3413 % card(((1..1000)*(1..1000))~)=1000*1000
3414 invert_explicit_set(global_set(GS),_R) :- !,
3415 add_error_and_fail(invert_explicit_set,'Cannot compute inverse of global set: ',GS).
3416 invert_explicit_set(freetype(GS),_R) :- !,
3417 add_error_and_fail(invert_explicit_set,'Cannot compute inverse of freetype: ',GS).
3418 invert_explicit_set(closure([P1,P2],[T1,T2],Clo),R) :- !,
3419 % TODO: also invert closures with single argument or more arguments
3420 % e.g., {a,b,c|a=1 & b=1 &c:1..10}~ = {c,ab|ab=(1,1) & c:1..10}
3421 R = closure([P2,P1],[T2,T1],Clo).
3422 invert_explicit_set(closure([P1],[T1],Clo),R) :-
3423 is_member_closure_with_info([P1],[T1],Clo,_Type,Info,MEM),
3424 invert_member_predicate(MEM,T1,InvMEM,InvT1),!,
3425 construct_member_closure(P1,InvT1,Info,InvMEM,R).
3426 invert_explicit_set(C,AVL) :- expand_custom_set(C,EC,invert_explicit_set), %% convert to AVL ?
3427 inv_and_norm(EC,AVL).
3428
3429 invert_member_predicate(cartesian_product(A,B),couple(TA,TB),
3430 cartesian_product(B,A),couple(TB,TA)).
3431 invert_member_predicate(identity(A),TA,identity(A),TA).
3432
3433
3434 :- block inv_and_norm(-,?).
3435 inv_and_norm(EC,AVL) :- inv(EC,R,Done), norm(Done,R,AVL).
3436
3437 :- block norm(-,?,?).
3438 norm(_,R,AVL) :- normalised_list_to_avl(R,AVL).
3439
3440 :- block inv(-,?,?).
3441 inv([],[],done).
3442 inv([(A,B)|T],[(B,A)-true|DT],Done) :- inv(T,DT,Done).
3443
3444
3445
3446 % checks whether a ground value is in the domain of an AVL relation
3447 check_in_domain_of_avlset_wf(X,AVL,_WF) :-
3448 convert_to_avl_inside_set(X,AX),!,
3449 ? (avl_fetch_pair(AX,AVL,_) -> true ; fail).
3450 check_in_domain_of_avlset_wf(X,AVL,WF) :-
3451 perfmessage(domain,'Could not convert arg for check_in_domain_of_avlset:',X),
3452 safe_flex_avl_member_default_wf((X,_),AVL,WF).
3453
3454 % checks whether a ground value is in the domain of an AVL relation and has only one solution
3455 check_unique_in_domain_of_avlset(X,AVL) :- convert_to_avl_inside_set(X,AX),!,
3456 ? avl_fetch_pair(AX,AVL,AY1),!,
3457 ? (avl_fetch_pair(AX,AVL,AY2), AY1 \= AY2 -> fail
3458 ; true).
3459
3460
3461 % utility to check if for a value there is at most one matching element in an AVL set
3462 % optimized for function application
3463 at_most_one_match_possible(Element,AVL,Matches) :- nonvar(Element),
3464 Element=(Index,_Rest), % Function Application; TO DO: does this cover all func. appl ?
3465 element_can_be_added_or_removed_to_avl(Index),
3466 convert_to_avl_inside_set(Index,AX), % is ground and normalised ?
3467 % TO DO: check AVL size ? Check other patterns ?
3468 findall((AX,Match),avl_tools:avl_fetch_pair(AX,AVL,Match),Matches),
3469 Matches \= [_,_|_].
3470
3471
3472
3473 apply_to_avl_set(A,X,Y,Span,WF) :-
3474 ground_value_check(X,GroundX),
3475 ? apply_to_avl_set_aux(A,X,Y,GroundX,Span,WF).
3476
3477 apply_to_avl_set_aux(A,X,Y,GroundX,Span,WF) :- nonvar(GroundX),!,
3478 ? apply_check_tuple(X,Y,A,Span,WF). % we could call apply_check_tuple_ground to avoid one ground test
3479 % We know that A is a function: we can deterministically apply if X is ground;
3480 % if Y is ground this is only the cases for injective functions
3481 apply_to_avl_set_aux(A,X,Y,GroundX,Span,WF) :-
3482 %(preference(data_validation_mode,true); % we now reduce priority of backpropagation below
3483 \+ preference(find_abort_values,false),
3484 % do not try inverse propagation onto argument X of function application A(X) = Y
3485 !,
3486 avl_approximate_size(A,3,ApproxSizeA),
3487 apply_check_tuple_delay(X,Y,A,ApproxSizeA,Span,WF,GroundX,_,_).
3488 apply_to_avl_set_aux(A,X,Y,GroundX,Span,WF) :-
3489 ground_value_check(Y,GroundY),
3490 avl_approximate_size(A,3,ApproxSizeA), % exact size for height <= 3; approximate size above
3491 (ApproxSizeA < 4 -> SPrio=ApproxSizeA ; SPrio is ApproxSizeA * 10), % magic number; ideally we want X or Y to be known beforehand; if none are known we may miss WD errors and may enumerate useless intermediate variables
3492 get_bounded_wait_flag(SPrio,apply_to_explicit(X,Y),WF,WF1), % this only makes sense if X is a domain variable to be enumerated
3493 %propagate_avl_element_information((X,Y),A,ApproxSizeA,WF), % could be done; but would prevent WD problems from being detected
3494 % this waitflag is used when neither X nor Y are ground;
3495 % quite often not much is gained by enumerating possible values; unless X or Y are constrained or trigger other computations
3496 % WSz is 10*ApproxSizeA, % magic value
3497 %(ApproxSizeA > 100 -> InversePrioSize = 4
3498 % ; avl_range_size_and_propagate_element_info(A,X,Y,RSize), InversePrioSize is ApproxSizeA // RSize), % we could probably compute the exact worst case with the same complexity
3499 % delay_get_wait_flag(GroundY,GroundX,WF1,InversePrioSize,apply_to_explicit_inverse(X,Y),WF,WF2),
3500 %(ApproxSizeA<4000 -> propagate_apply(X,Y,A,ApproxSizeA,WF,GroundX,GroundY) ; true),
3501 ? apply_check_tuple_delay(X,Y,A,ApproxSizeA,Span,WF,GroundX,WF1,GroundY),
3502 (preference(use_clpfd_solver,false) -> true
3503 % should we also check: preference(find_abort_values,true)?
3504 ; get_wait_flag0(WF,WF0),
3505 ? propagate_apply(X,Y,A,ApproxSizeA,WF,WF0,GroundX,WF1,GroundY)).
3506
3507 :- block propagate_apply(?,?,?,?,?,-,?,?,?).
3508 propagate_apply(X,Y,AVL,ApproxSizeA,WF,_,GroundX,WF1,GroundY) :-
3509 var(GroundX), var(WF1), var(GroundY),
3510 (preference(disprover_mode,true)
3511 -> XX=X % this will also instantiate X and prevent finding WD errors
3512 ; (ApproxSizeA<128 -> true
3513 ; preference(solver_strength,SS), ApproxSizeA < 128+SS*100), % up until 4000 it may make sense to constrain Y
3514 preference(data_validation_mode,false), % note: this can slow down ProB, e.g., test 1105; hence allow disabling it
3515 preference(find_abort_values,false), % TO DO: v = %x.(x:1..20|x+x) & {y,z|y<4 & z=v(y) & (y:{-1,2})} =res: no WD ERROR found
3516 propagate_value(X,XX) % only instantiate X, propagation only makes sense for propagate_avl_element_information_small, as otherwise only X will be bounded
3517 ),
3518 !,
3519 ? propagate_avl_element_information_direct((XX,Y),AVL,ApproxSizeA,WF).
3520 propagate_apply(_,_,_,_,_,_,_,_,_).
3521
3522 % only propagate in one direction to allow to find WD errors but also prevent pending co-routines/constraints
3523 :- block propagate_value(-,?).
3524 propagate_value(int(X),R) :- !,
3525 (
3526 %%integer(X) -> R=int(X) ; % relevant for SWI 8.5.10 and older where fd_set fails for integers, see test 788; should be fixed in next release
3527 propagate_fd_dom(X,RX), R=int(RX), propagate_atomic_value(X,RX)
3528 ).
3529 propagate_value(fd(X,T),R) :- !,
3530 (
3531 %%integer(X) -> R=fd(X,T) ; % for SWI 8.5.10 and older, see above
3532 propagate_fd_dom(X,RX), R=fd(RX,T), propagate_atomic_value(X,RX)
3533 ).
3534 propagate_value((X1,X2),R) :- !, R=(RX1,RX2), propagate_value(X1,RX1), propagate_value(X2,RX2).
3535 propagate_value(pred_true,R) :- !, if(R=pred_true,true,debug_println(9,function_arg_outside_domain(pred_true))).
3536 propagate_value(pred_false,R) :- !, if(R=pred_false,true,debug_println(9,function_arg_outside_domain(pred_false))).
3537 propagate_value(string(X),R) :- !, R=string(RX),propagate_atomic_value(X,RX).
3538 propagate_value(X,RX) :- equal_object(X,RX). % TO DO: get rid of this: this propagates and prevents finding WD errors
3539 :- block propagate_atomic_value(-,?).
3540 propagate_atomic_value(X,Y) :-
3541 if(X=Y,true,debug_println(9,function_arg_outside_domain(X))).
3542
3543 %propagate_fd_dom(X,RX) :- integer(X),!,RX=X. % relevant for SWI 8.5.10 and older where fd_set fails for integers
3544 propagate_fd_dom(X,RX) :- fd_set(X,Dom),in_set(RX,Dom).
3545
3546
3547 /*
3548 :- block propagate_apply(-,?,?,?,?,-,-).
3549 % call propagate as soon as we know something about the function argument and we do not propgagate completely using GroundX/Y anyway
3550 propagate_apply(X,Y,AVL,Size,WF,GroundX,GroundY) :- print(prop_apply(Size,GroundX,GroundY,X,Y)),nl,
3551 (nonvar(GroundX) -> true ; nonvar(GroundY) -> true
3552 ; propagate_avl_element_information((X,Y),AVL,Size,WF)).
3553
3554 % get the waitflag when first WF set and other two not
3555 :- block delay_get_wait_flag(-,-,-,?,?,?,?).
3556 delay_get_wait_flag(_,WF1,WF2, _,_,_,_) :- (nonvar(WF1);nonvar(WF2)),!. % DO NOTHING
3557 delay_get_wait_flag(_,_,_,Prio,Info,WF,WF2) :- get_wait_flag(Prio,Info,WF,WF2).
3558 */
3559
3560 :- block apply_check_tuple_delay(?,?,?, ?,?,?, -,-,-).
3561 apply_check_tuple_delay(X,Y,AVL,_ApproxSizeA,Span,WF,GroundX,WF1,_) :-
3562 (nonvar(GroundX);nonvar(WF1)),!,
3563 ? apply_check_tuple(X,Y,AVL,Span,WF).
3564 apply_check_tuple_delay(X,Y,AVL,ApproxSizeA,Span,WF,GroundX,_WF1,_GroundY) :-
3565 % Y is ground; try to do an inverse function lookup
3566 ? inverse_apply_ok(Y,X,AVL,ApproxSizeA,Span),
3567 !,
3568 % the inverse lookup does not check that X has a unique image; check this once X is known:
3569 apply_check_tuple_when_ground(GroundX,X,Y,AVL,Span,WF),
3570 % print(inverse_apply(Y,X,ApproxSizeA,_GroundX)),nl,
3571 inverse_get_possible_values(X,Y,AVL,Res),
3572 Res=avl_set(InvAVL), % if empty set : we fail
3573 (preference(data_validation_mode,true),
3574 avl_approximate_size(InvAVL,10,ApproxSize),
3575 ApproxSize>1
3576 -> A2 is (ApproxSize*15*ApproxSize)//ApproxSizeA, % used to be A2 is ApproxSize*100,
3577 A22 is max(A2,ApproxSize),
3578 ? (get_inversion_penalty(Span)
3579 -> A23 is A22 * 100 %, add_message(f,'Inversion Penalty: ',Y:A22,Span)
3580 ; A23=A22),
3581 % give lower priority for backwards propagation, upto 15 times if no reduction from backwards propagation
3582 % but also take into account how much we reduce the size by inverting
3583 % relevant for, e.g., Machines_perf_0111/Thales_All/rule_OPS_SDS_3940.mch
3584 % or rule_OPS_SDS_6496 -> 15 instead of 150 improves performance
3585 get_bounded_wait_flag(A23,element_of_avl_inverse_apply_ok(X),WF,WF2),
3586 % does not call propagate_avl_element_information(X,InvAVL,ApproxSize,WF) or avl_to_table
3587 element_of_avl_set_wf3(X,InvAVL,ApproxSize,WF2,WF) % TODO: pass GroundX
3588 %apply_check_tuple_delay(X,Y,AVL,ApproxSizeA,Span,WF,GroundX,WF1,_) % now wait on WF1 or GroundX
3589 ? ; element_of_avl_set_wf(InvAVL,X,WF)
3590 ).
3591 apply_check_tuple_delay(X,Y,AVL,ApproxSizeA,Span,WF,GroundX,WF1,_GroundY) :-
3592 apply_check_tuple_delay(X,Y,AVL,ApproxSizeA,Span,WF,GroundX,WF1,_). % now wait on WF1 or GroundX
3593
3594 :- block apply_check_tuple_when_ground(-,?,?,?,?,?).
3595 apply_check_tuple_when_ground(_,X,Y,AVL,Span,WF) :- apply_check_tuple(X,Y,AVL,Span,WF).
3596
3597 % check if the function call was annotated as not suitable for backwards inverse function lookup propagation
3598 get_inversion_penalty(span_predicate(b(_Function,_,Info),_LS,_S)) :- !,
3599 ? get_inversion_penalty(Info).
3600 get_inversion_penalty(Info) :-
3601 ? member(prob_annotation('INVERSION_PENALTY'),Info).
3602
3603 inverse_get_possible_values(X,Y,AVL,Res) :-
3604 get_template(X,XX,_),
3605 copy_term(XX,XX_Copy), % avoid that findall instantiates X
3606 % TODO: copy_value_term similar to ground_value to avoid traversing avl_sets; but usually X is not a set
3607 findall(XX_Copy, safe_avl_member_default((XX_Copy,Y),AVL), PossibleValues),
3608 PossibleValues \= [], % fail straightaway
3609 sort(PossibleValues,SPV),
3610 % length(SPV,Len),print(inverse_image(Y,Len)),nl, print_term_summary(apply_check_tuple_delay(X,Y,AVL)),nl,
3611 convert_to_avl(SPV,Res).
3612
3613 % is it ok to compute inverse ? only makes sense if AVL tree not too big and quite functional
3614 inverse_apply_ok(pred_true,_,_AVL,ApproxSizeA,_) :- !, % only two values possible, probably half of AVL will be returned
3615 ApproxSizeA < 1023. % corresponds to avl_height < 10
3616 inverse_apply_ok(pred_false,_,_AVL,ApproxSizeA,_) :- !,ApproxSizeA < 1023.
3617 % TO DO: other small types, such as fd(_,_)
3618 inverse_apply_ok(_,_,_AVL,ApproxSizeA,_) :- ApproxSizeA < 255,!.
3619 inverse_apply_ok(_,X,_AVL,ApproxSizeA,Span) :- ApproxSizeA < 65535, % corresponds Height < 16
3620 (preference(data_validation_mode,true) ->
3621 (preference(solver_strength,SS), ApproxSizeA < 16383+SS -> true
3622 ; perfmessage(inverse,'Function call not inverted (increase SOLVER_STRENGTH to enable this), approximate function size: ',ApproxSizeA,Span),
3623 fail
3624 )
3625 ; true),
3626 ? quick_non_ground_check(X).
3627 %inverse_apply_ok(_,_,_,_).
3628
3629 % sometimes the ground_value_check co-routine hasn't grounded GroundX yet ! so do a quick check
3630 quick_non_ground_check(X) :- var(X),!.
3631 quick_non_ground_check([]) :- !,fail.
3632 quick_non_ground_check(avl_set(_)) :- !,fail.
3633 quick_non_ground_check(pred_true) :- !,fail.
3634 quick_non_ground_check(pred_false) :- !,fail.
3635 quick_non_ground_check(int(X)) :- !,var(X).
3636 quick_non_ground_check(string(X)) :- !,var(X).
3637 quick_non_ground_check(fd(X,T)) :- !,(var(X) ; var(T)).
3638 quick_non_ground_check((A,B)) :- !, (quick_non_ground_check(A) -> true ; quick_non_ground_check(B)).
3639 quick_non_ground_check(_). % assume it is non ground
3640
3641
3642
3643 % apply_check_tuple is allowed to enumerate: either X is ground or Y is ground
3644 apply_check_tuple(X,Y,A,Span,WF) :-
3645 ground_value(X),
3646 convert_to_avl_inside_set_wf(X,AX,WF),!, % we can do optimized lookup + checking in one go
3647 % (but avl_apply only does partial check)
3648 avl_apply(AX,A,XY,Span,WF),
3649 ? kernel_objects:equal_object_wf(XY,Y,apply_check_tuple,WF).
3650 :- if(environ(no_wd_checking, true)).
3651 apply_check_tuple(X,Y,A,_Span,WF) :- safe_avl_member_default_wf((X,Y),A,WF).
3652 :- else.
3653 apply_check_tuple(X,Y,A,_Span,WF) :- preferences:preference(find_abort_values,false), !,
3654 ? safe_flex_avl_member_default_wf((X,Y),A,WF). % will do a ground check again for X in flexible_decompose_index
3655 apply_check_tuple(X,Y,A,Span,WF) :- !,
3656 if(safe_flex_avl_member_default_wf((X,XY),A,WF), % does not detect abort errors if X unbound
3657 kernel_objects:equal_object_wf(XY,Y,apply_check_tuple_avl,WF),
3658 add_wd_error_span('function applied outside of domain (#4): ','@fun'(X,avl_set(A)),Span,WF)).
3659 :- endif.
3660
3661
3662 % ------------------------------------------
3663
3664
3665 :- use_module(b_global_sets,[b_type2_set/2]).
3666 :- use_module(bsyntaxtree,[rename_bt/3]).
3667 union_of_explicit_set(global_set(GS),_,R) :- is_maximal_global_set(GS), !,
3668 R= global_set(GS). /* global_set is already maximal */
3669 union_of_explicit_set(freetype(GS),_,R) :- !, R= freetype(GS). /* freetype is already maximal */
3670 union_of_explicit_set(closure(P,T,B),_,R) :- is_definitely_maximal_closure(P,T,B), !,
3671 R= closure(P,T,B). /* global_set is already maximal */
3672 union_of_explicit_set(_,S2,R) :- is_definitely_maximal_set(S2),!, % will also look at AVL set
3673 R=S2.
3674 union_of_explicit_set(S1,S2,R) :- nonvar(S2), S2 = [], !, R=S1.
3675 union_of_explicit_set(S1,S2,_) :- (var(S1);var(S2)),!,fail. % then we cannot compute it here
3676 union_of_explicit_set(S2,S1,R) :-
3677 is_not_member_value_closure(S1,TYPE,MS1), nonvar(MS1), is_efficient_custom_set(MS1),
3678 % also works if S2 is complement closure
3679 difference_of_explicit_set(MS1,S2,Diff),!,
3680 construct_complement_closure_if_necessary(Diff,TYPE,R).
3681 union_of_explicit_set(avl_set(A1),S2,R) :- !, union_of_avl_set(S2,A1,R).
3682 union_of_explicit_set(S1,S2,R) :-
3683 ? is_not_member_value_closure(S1,TYPE,MS1), nonvar(MS1), is_efficient_custom_set(MS1),
3684 difference_of_explicit_set(MS1,S2,Diff),!,
3685 construct_complement_closure_if_necessary(Diff,TYPE,R).
3686 union_of_explicit_set(S1,avl_set(A2),R) :- !, union_of_avl_set(S1,A2,R).
3687 union_of_explicit_set(I1,I2,R) :- is_interval_closure_or_integerset(I1,From1,To1), ground(From1), ground(To1),
3688 is_interval_closure_or_integerset(I2,From2,To2), ground(From2), ground(To2),
3689 !,
3690 (union_of_interval(From1,To1,From2,To2,FromRes,ToRes)
3691 -> construct_interval_closure(FromRes,ToRes,R)
3692 ; small_enough_for_expansion(From1,To1),small_enough_for_expansion(From2,To2) ->
3693 % do not attempt union_of_closure below
3694 expand_interval_closure_to_avl(From1,To1,R1), R1=avl_set(A1), % empty interval already dealt with above !?
3695 expand_interval_closure_to_avl(From2,To2,R2), R2=avl_set(A2), % Note: unification after call as expand_interval calls equal_object (which gets confused by partially instantiated avl_set(_))
3696 union_of_avl(A1,A2,ARes),R=avl_set(ARes) /* AVL not normalised */
3697 ; transform_global_sets_into_closure(I1,closure(Par,T,Body)),
3698 union_of_closure(I2,Par,T,Body,R)
3699 ).
3700 union_of_explicit_set(closure(P,T,B),C2,Res) :-
3701 union_of_closure(C2,P,T,B,Res).
3702
3703 small_enough_for_expansion(From1,To1) :- number(To1), number(From1), To1-From1<250.
3704
3705 :- use_module(bsyntaxtree,[extract_info/2, extract_info_wo_used_ids/2, extract_info/3, rename_bt/3, replace_id_by_expr/4]).
3706
3707 union_of_closure(global_set(X),P,T,B,Res) :- !, transform_global_sets_into_closure(global_set(X),C),
3708 union_of_closure(C,P,T,B,Res).
3709 union_of_closure(closure(P2,T2,B2),P,T,B,Res) :- !,
3710 % T2 should be equal to T, module seq(_) <-> set(couple(integer,_))
3711 unify_closure_predicates(P,T,B, P2,T2,B2 , NewP,NewT, NewB1,NewB2),
3712 debug:debug_println(9,union_of_two_closures(P,P2,NewP,NewT)),
3713 extract_info(B,B2,NewInfo),
3714 construct_disjunct(NewB1,NewB2,Disj),
3715 Res = closure(NewP,NewT,b(Disj,pred,NewInfo)).
3716
3717 % rename predicates of two closures so that they work on common closure parameter ids
3718 % and can then be either joined by conjunction or disjunction
3719 unify_closure_predicates(P,T,B, P2,T2,B2 , NewP,NewT, NewB1,NewB2) :-
3720 length(P,Len1), length(P2,Len2),
3721 (Len1=Len2
3722 -> generate_renaming_list(P,P2,RL),
3723 rename_bt(B2,RL,NewB2),
3724 NewP=P, NewT=T, NewB1 = B
3725 ; Len1 < Len2 -> unify_clos_lt(P,T,B, P2,T2,B2 , NewP,NewT, NewB1,NewB2)
3726 ; unify_clos_lt(P2,T2,B2, P,T,B , NewP,NewT, NewB2,NewB1) % inverted the predicate
3727 ).
3728
3729 % TO DO: generalize: currently only works for single identifier on left
3730 % but works for id(NATURAL) \/ %x.(x<0|-x) or abs = id(NATURAL) \/ %x.(x<0|-x) & abs(2)=a2 & abs(-2)=am2
3731 unify_clos_lt([ID1],[couple(_,_)],B, P2,T2,B2 , NewP,NewT, NewB1,NewB2) :-
3732 rename_lambda_result_id(P2,B2,P3,B3),
3733 create_couple_term(P3,T2,Pair),
3734 replace_id_by_expr(B,ID1,Pair,NewB1),
3735 NewP=P3, NewT=T2, NewB2=B3.
3736
3737 % _lambda_result_ id is not enumerated, hence we have to avoid inserting such ids into NewB1 as part of the pPair
3738 rename_lambda_result_id(['_lambda_result_',ID2],B2,[FRESHID,ID2],B3) :- !,get_unique_id('_RANGE_',FRESHID),
3739 rename_bt(B2,[rename('_lambda_result_',FRESHID)],B3).
3740 rename_lambda_result_id([ID1,'_lambda_result_'],B2,[ID1,FRESHID],B3) :- !,get_unique_id('_RANGE_',FRESHID),
3741 rename_bt(B2,[rename('_lambda_result_',FRESHID)],B3).
3742 rename_lambda_result_id(P2,B2,P2,B2).
3743
3744 % translate a list of atomic ids and a list of types into a couple-term
3745 create_couple_term([ID1],[T1],Res) :- !,
3746 create_texpr(identifier(ID1),T1,[],Res).
3747 create_couple_term([ID1,ID2],[T1,T2],Res) :-
3748 bsyntaxtree:create_couple(b(identifier(ID1),T1,[]),b(identifier(ID2),T2,[]),Res).
3749 % TODO: extend for more than two args
3750
3751 generate_renaming_list([],[],[]).
3752 generate_renaming_list([ID|T],[ID2|T2],RL) :-
3753 (ID==ID2 -> generate_renaming_list(T,T2,RL)
3754 ; RL = [rename(ID2,ID)|RL2],
3755 generate_renaming_list(T,T2,RL2)).
3756
3757
3758 % a more clever way of constructing a disjunct; factor out common prefixes
3759 % (A & B1) or (A1 & B2) <=> A1 & (B1 or B2)
3760 % TO DO: we should try and get the leftmost basic conjunct !
3761 /* construct_disjunct(b(conjunct(A1,A2),pred,IA), b(conjunct(B1,B2),pred,_IB), Res) :-
3762
3763 print('TRY DISJUNCT FACTOR: '), translate:print_bexpr(A1),nl,
3764 translate:print_bexpr(B1),nl,
3765 same_texpr_body(A1,B1),!,
3766 print('DISJUNCT FACTOR: '), translate:print_bexpr(A1),nl,
3767 Res = conjunct(A1,b(Disj,pred,IA)),
3768 construct_disjunct(A2,B2,Disj).
3769 */
3770 construct_disjunct(A,B,disjunct(A,B)).
3771
3772 % TO DO: quick_check if AVL A1 is maximal ?
3773 union_of_avl_set(avl_set(A2),A1,R) :- !, union_of_avl(A1,A2,ARes), R=avl_set(ARes). /* AVL not normalised */
3774 union_of_avl_set(I2,A1,R) :- is_interval_closure_or_integerset(I2,From2,To2), !,
3775 ground(From2), ground(To2), % we can only compute it if bounds known
3776 (avl_min(A1,int(Min)), low_border(From2,Min,FromRes), avl_max(A1,int(Max)), up_border(To2,Max,ToRes)
3777 -> /* AVL contained (almost) in Interval */
3778 construct_interval_closure(FromRes,ToRes,R)
3779 ; \+ small_interval(From2,To2) ->
3780 transform_global_sets_into_closure(I2,closure(Par,T,Body)), % we may have something like NATURAL1,...
3781 union_of_avl_set_with_closure(Par,T,Body,A1,R)
3782 ; expand_and_convert_to_avl_set(I2,A2,union_of_avl_set,'? \\/ ARG'), % can generate ARel=empty; will fail if not possible to convert
3783 union_of_avl(A1,A2,ARes), R=avl_set(ARes)
3784 ).
3785 union_of_avl_set(closure(Par,T,Body),A1,Res) :- is_infinite_or_symbolic_closure(Par,T,Body),!,
3786 % TO DO: what if we are in SYMBOLIC mode and the type of T is infinite; maybe we should also keep the union symbolic ?? (cf Ticket/Georghe1)
3787 union_of_avl_set_with_closure(Par,T,Body,A1,Res).
3788 union_of_avl_set(S2,A1,Res) :-
3789 S2 \= freetype(_),
3790 ground_value(S2), % could be a closure
3791 !,
3792 (try_expand_and_convert_to_avl_set(S2,A2,union)
3793 -> union_of_avl(A1,A2,ARes), Res=avl_set(ARes) /* AVL not normalised */
3794 ; S2=closure(Par,T,Body),
3795 union_of_avl_set_with_closure(Par,T,Body,A1,Res)).
3796
3797 try_expand_and_convert_to_avl_set(S2,A2,Source) :-
3798 % false: do not add enumeration warning events as errors
3799 catch_enumeration_warning_exceptions(expand_and_convert_to_avl_set(S2,A2,Source,''),fail,false,ignore(Source)).
3800
3801 % try expanding to list, but catch enumeration warnings and fail if they do occur
3802 % used by override(...)
3803 %try_expand_custom_set_to_list(CS,_,_,_) :- nonvar(CS),CS=global_set(GS),is_infinite_global_set(GS,_),
3804 % !,
3805 % fail.
3806 try_expand_custom_set_to_list(CS,_,_,_) :- nonvar(CS),
3807 (is_symbolic_closure(CS) ; is_infinite_explicit_set(CS)),
3808 !, % we could also check is_symbolic_closure
3809 fail.
3810 try_expand_custom_set_to_list(CS,List,Done,Source) :-
3811 % false: do not add enumeration warning events as errors
3812 catch_enumeration_warning_exceptions(expand_custom_set_to_list(CS,List,Done,Source),fail,false,ignore(Source)).
3813
3814
3815 small_interval(From,To) :- number(From), number(To), To-From < 10000.
3816
3817 union_of_avl_set_with_closure(Par,T,Body,A1,Res) :-
3818 Body = b(_,BodyT,_),
3819 setup_typed_ids(Par,T,TypedPar),
3820 couplise_list(TypedPar,TypedCPar),
3821 generate_couple_types(TypedCPar,ParExpr,ParType),
3822 debug:debug_println(9,union_of_avl_and_infinite_closure(Par,T,BodyT)),
3823 BodyAvl = b(member(ParExpr,b(value(avl_set(A1)),set(ParType),[])),pred,[]),
3824 extract_info_wo_used_ids(Body,NewInfo),
3825 Res = closure(Par,T,b(disjunct(BodyAvl,Body),pred,NewInfo)).
3826 % mark_closure_as_symbolic(closure(Par,T,b(disjunct(BodyAvl,Body),pred,NewInfo)),Res).
3827
3828 low_border(Low,AVLMin,R) :- geq_inf(AVLMin,Low),!,R=Low.
3829 low_border(Low,AVLMin,R) :- number(Low),AVLMin is Low-1,R=AVLMin. % extend lower border by one
3830 up_border(Up,AVLMax,R) :- geq_inf(Up,AVLMax),!,R=Up.
3831 up_border(Up,AVLMax,R) :- number(Up),AVLMax is Up+1,R=AVLMax. % extend upper border by one
3832
3833
3834 setup_typed_ids([],[],[]).
3835 setup_typed_ids([ID|TI],[Type|TT],[b(identifier(ID),Type,[])|BT]) :- setup_typed_ids(TI,TT,BT).
3836
3837 generate_couple_types(couple(A,B),b(couple(TA,TB),Type,[]),Type) :- !, Type = couple(TTA,TTB),
3838 generate_couple_types(A,TA,TTA),
3839 generate_couple_types(B,TB,TTB).
3840 generate_couple_types(b(X,T,I),b(X,T,I),T).
3841
3842
3843 % try to see if two intervals can be unioned into a new interval
3844 union_of_interval(F1,T1,F2,T2,FR,TR) :-
3845 geq_inf(F2,F1), geq_inf(T1,T2),!,FR=F1,TR=T1. % interval [F2,T2] contained in [F1,T1]
3846 union_of_interval(F2,T2,F1,T1,FR,TR) :- geq_inf(F2,F1), geq_inf(T1,T2),!,FR=F1,TR=T1. % see above
3847 union_of_interval(F1,T1,F2,T2,FR,TR) :- number(F2),
3848 geq_inf(F2,F1), number(T1),T11 is T1+1,geq_inf(T11,F2), geq_inf(T2,F2),!,FR=F1,TR=T2. % intervals can be joined
3849 union_of_interval(F2,T2,F1,T1,FR,TR) :- number(F2),
3850 geq_inf(F2,F1), number(T1),T11 is T1+1,geq_inf(T11,F2), geq_inf(T2,F2),!,FR=F1,TR=T2. % see above
3851
3852 :- use_module(library(ordsets),[ord_union/3]).
3853 union_of_avl(A1,A2,ARes) :-
3854 avl_height(A2,Sz2),
3855 (Sz2 < 2 % we have something like Set := Set \/ {x}; no need to compute height of A1
3856 -> union_of_avl1(A1,99999,A2,Sz2,ARes)
3857 ; avl_height(A1,Sz1), % TODO: we could call avl_height_less_than or avl_height_compare
3858 (Sz1<Sz2 -> union_of_avl1(A2,Sz2,A1,Sz1,ARes) ; union_of_avl1(A1,Sz1,A2,Sz2,ARes))
3859 ).
3860 union_of_avl1(A1,Sz1,A2,Sz2,ARes) :- Sz2>2, Sz1 =< Sz2+3, % difference not too big; Sz2 at least a certain size
3861 !,
3862 avl_to_list(A2,List2), % get all members
3863 avl_to_list(A1,List1),
3864 ord_union(List1,List2,L12),
3865 ord_list_to_avl(L12,ARes).
3866 union_of_avl1(A1,_Sz1,A2,_Sz2,ARes) :- % this version is better when A2 is small compared to A1
3867 avl_domain(A2,List2), % get all members
3868 add_to_avl(List2,A1,ARes).
3869
3870 :- use_module(library(lists),[reverse/2]).
3871 % a custom version for union(A) where A is AVL set; avoid converting/expanding accumulators and computing avl_height
3872 % runtime of e.g., UNION(x).(x:1000..1514|0..x) 0.65 sec or UNION(n).(n:10000..10010|UNION(x).(x:n..n+1000|n..x)) 4.8 sec is considerably smaller with this version
3873 union_generalized_explicit_set(avl_set(SetsOfSets),Res,WF) :-
3874 expand_custom_set_to_list_wf(avl_set(SetsOfSets),ESetsOfSets,_,union_generalized_wf,WF),
3875 % length(ESetsOfSets,Len),print(union_gen(Len)),nl,
3876 (ESetsOfSets=[OneSet]
3877 -> Res=OneSet % avoid converting to list and back to Avl
3878 ; reverse(ESetsOfSets,RESetsOfSets), % be sure to insert larger values first, so that ord_union has less work to do below; useful if you have many small singleton sets, for example union(ran(%x.(x : 1 .. 10000|{x * x}))) 2.37 secs --> 0.15 secs
3879 % note: dom({r,x|x:1..50000 & r:{x*x}}) is still 3 times faster
3880 union_of_avls(RESetsOfSets,[],Res)).
3881
3882 % take the union of a list of avl_sets
3883 union_of_avls([],Acc,Res) :- ord_list_to_avl(Acc,ARes), construct_avl_set(ARes,Res).
3884 union_of_avls([H|T],Acc,Res) :-
3885 union_of_avl_with_acc(H,Acc,NewAcc),
3886 union_of_avls(T,NewAcc,Res).
3887
3888 union_of_avl_with_acc(avl_set(H),Acc,NewAcc) :- !,
3889 avl_to_list(H,HList),
3890 ord_union(Acc,HList,NewAcc).
3891 union_of_avl_with_acc([],Acc,Res) :- !,Res=Acc.
3892 % other custom sets should normally not appear, we obtain the list as elements stored in an avl_set
3893 union_of_avl_with_acc(G,_,_) :- add_internal_error('Uncovered element: ',union_of_avl_with_acc(G,_,_)),fail.
3894
3895
3896
3897 % TO DO: there are no rules for is_not_member_value_closure for intersection below
3898 intersection_of_explicit_set_wf(global_set(GS),S2,R,_WF) :- is_maximal_global_set(GS), !, R=S2.
3899 intersection_of_explicit_set_wf(freetype(_GS),S2,R,_WF) :- !, R=S2.
3900 intersection_of_explicit_set_wf(_,S2,_,_WF) :- var(S2),!,fail. % code below may instantiate S2
3901 intersection_of_explicit_set_wf(S1,S2,R,_WF) :- is_definitely_maximal_set(S2), !, R=S1.
3902 intersection_of_explicit_set_wf(_S1,[],R,_WF) :-!, R=[].
3903 intersection_of_explicit_set_wf(avl_set(A1),I2,R,_WF) :-
3904 is_interval_closure_or_integerset(I2,From1,To1),
3905 !,
3906 intersect_avl_interval(A1,From1,To1,R).
3907 intersection_of_explicit_set_wf(I1,I2,R,_WF) :-
3908 intersection_with_interval_closure(I1,I2,R),!.
3909 intersection_of_explicit_set_wf(S1,S2,R,_WF) :-
3910 get_avl_sets(S1,S2,A1,A2),
3911 !, % if too large: better to apply normal intersection code ?
3912 % if one of the args is an interval this is already caught in kernel_objects calling intersection_with_interval_closure; see SetIntersectionBig.mch
3913 avl_domain(A1,ES), % A1 has the smaller height; important for e.g. SetIntersectionBig2.mch
3914 inter2(ES,A2,IRes),
3915 ord_list_to_avlset(IRes,R,intersection). % we have generated the elements in the right order already
3916 intersection_of_explicit_set_wf(Set1,Set2,R,WF) :-
3917 transform_global_sets_into_closure(Set1,closure(P1,T1,B1)),
3918 transform_global_sets_into_closure(Set2,closure(P2,T2,B2)),
3919 % gets called, e.g., for {x|x /: NATURAL1} /\ NATURAL1
3920 unify_closure_predicates(P1,T1,B1, P2,T2,B2 , NewP,NewT, NewB1,NewB2),
3921 debug:debug_println(9,intersection_of_two_closures(P1,P2,NewP,NewT)),
3922 conjunct_predicates([NewB1,NewB2],BI),
3923 % create a conjunction: can be much more efficient than seperately expanding;
3924 % also works well if one of the closures is infinite
3925 C = closure(NewP,NewT,BI),
3926 expand_custom_set_wf(C,R,intersection_of_explicit_set_wf,WF). % we could keep it symbolic; maybe use SYMBOLIC pref
3927 % to do: also use above for closure and AVL set with member(P,value(avl_set(A)))
3928 % we could also apply the same principle to difference_of_explicit_set
3929 % currently we enable intersection to be treated symbolically (not_symbolic_binary(intersection) commented out)
3930 % This means the above clause for intersection_of_explicit_set_wf is less useful
3931 % a special case; just for interval closures
3932 intersection_with_interval_closure(I1,I2,R) :-
3933 is_interval_closure_or_integerset(I1,From1,To1), nonvar(I2),
3934 intersection_with_interval_closure_aux(I2,From1,To1,R).
3935 intersection_with_interval_closure(avl_set(A1),I2,R) :-
3936 is_interval_closure_or_integerset(I2,From1,To1),
3937 !,
3938 intersect_avl_interval(A1,From1,To1,R).
3939
3940 % try and get AVL sets from two args; first AVL set is smaller one according to height
3941 get_avl_sets(avl_set(A1),S2,AA1,AA2) :- nonvar(S2), S2=avl_set(A2),
3942 ? (avl_height_compare(A1,A2,R), R=lt
3943 -> (AA1,AA2)=(A1,A2)
3944 ; (AA1,AA2)=(A2,A1)).
3945 %get_avl_sets(S1,S2,AA1,AA2) :- nonvar(S2),S2=avl_set(A2), get_avl_set_arg(S1,A1),
3946 % (avl_height_compare(A1,A2,R),R=gt -> (AA1,AA2)=(A2,A1) ; (AA1,AA2)=(A1,A2)).
3947
3948
3949 %intersection_with_interval_closure_aux(avl_set(A),...
3950 intersection_with_interval_closure_aux(I2,From1,To1,R) :-
3951 is_interval_closure_or_integerset(I2,From2,To2),!,
3952 intersect_intervals_with_inf(From1,To1,From2,To2,FromRes,ToRes),
3953 construct_interval_closure(FromRes,ToRes,R).
3954 % (is_interval_closure_or_integerset(R,F,T) -> print(ok(F,T)),nl ; print(ko),nl).
3955 intersection_with_interval_closure_aux(avl_set(A2),From1,To1,R) :-
3956 intersect_avl_interval(A2,From1,To1,R).
3957
3958 % intersect avl with interval
3959 % TO DO: expand interval if small (or small intersection with AVL) and use avl intersection
3960 intersect_avl_interval(_,From2,To2,_) :- (var(From2) ; var(To2)),!,fail.
3961 intersect_avl_interval(A1,From2,To2,R) :- avl_min(A1,int(Min)),
3962 geq_inf(Min,From2),
3963 geq_inf(To2,Min), avl_max(A1,int(Max)),
3964 geq_inf(To2,Max),
3965 % AVL fully contained in interval; no need to expand to list and back again
3966 !,
3967 construct_avl_set(A1,R).
3968 intersect_avl_interval(A1,From2,To2,R) :-
3969 avl_domain(A1,ES),
3970 inter_interval(ES,From2,To2,IRes),
3971 ord_list_to_avlset(IRes,R,intersect_avl_interval).
3972
3973 inter_interval([],_,_, []).
3974 inter_interval([IH|T],From2,To2, Res) :- IH = int(H),
3975 (geq_inf(To2,H) ->
3976 (geq_inf(H,From2) -> Res = [IH-true|Res2] ; Res = Res2),
3977 inter_interval(T,From2,To2,Res2)
3978 ; Res = [] % we have exceeded the upper limit of the interval
3979 ).
3980
3981 % also works with real/float intervals:
3982 intersect_intervals_with_inf(From1,To1,From2,To2,FromRes,ToRes) :-
3983 minimum_with_inf(To1,To2,ToRes),
3984 maximum_with_inf(From1,From2,FromRes).
3985
3986 % check if two intervals are disjoint
3987 disjoint_intervals_with_inf(From1,To1,From2,To2) :-
3988 intersect_intervals_with_inf(From1,To1,From2,To2,Low,Up),
3989 number(Up), number(Low), Low > Up.
3990
3991 inter2([],_, []).
3992 inter2([H|T],A1, Res) :-
3993 (avl_fetch(H,A1) -> Res = [H-true|Res2] ; Res = Res2), inter2(T,A1,Res2).
3994
3995 ord_list_to_avlset(OL,R) :- ord_list_to_avlset(OL,R,unknown).
3996 ord_list_to_avlset(OrdList,Res,Origin) :-
3997 % assumes that we have generated the elements in the right order already
3998 (OrdList=[] -> Res=[]
3999 ; check_sorted(OrdList,Origin),
4000 ord_list_to_avl(OrdList,ARes), Res=avl_set(ARes)).
4001
4002 % a version which accepts a list of values without -true
4003 % values have to be ground and already converted for use in avl_set
4004 sorted_ground_normalised_list_to_avlset(List,Res,PP) :-
4005 add_true_to_list(List,LT),
4006 ord_list_to_avlset_direct(LT,Res,PP).
4007
4008 add_true_to_list([],[]).
4009 add_true_to_list([H|T],[H-true|TT]) :- add_true_to_list(T,TT).
4010
4011 % the same, but without checking sorted (only use if you are really sure the list is sorted)
4012 ord_list_to_avlset_direct([],[],_).
4013 ord_list_to_avlset_direct([H|T],Res,_):-
4014 (T==[] -> H=Key-Val, Res = avl_set(node(Key,Val,0,empty,empty)) % slightly faster than calling ord_list_to_avl
4015 ; ord_list_to_avl([H|T],ARes), Res = avl_set(ARes)).
4016
4017 check_sorted([],_) :- !.
4018 check_sorted([H-_|T],Origin) :- !, check_sorted2(T,H,Origin).
4019 check_sorted(X,Origin) :- add_error_and_fail(ord_list_to_avlset,'Not a list of -/2 pairs: ',Origin:X).
4020
4021 check_sorted2([],_,_) :- !.
4022 check_sorted2([H-_|T],PH,Origin) :- PH @< H,!, check_sorted2(T,H,Origin).
4023 check_sorted2(X,Prev,Origin) :-
4024 add_error_and_fail(ord_list_to_avlset,'Not a sorted list of -/2 pairs: ',Origin:(X,Prev)).
4025
4026 % ------------------
4027
4028 :- use_module(kernel_freetypes,[is_maximal_freetype/1]).
4029 is_definitely_maximal_set(S) :- nonvar(S),
4030 is_definitely_maximal_set2(S).
4031 is_definitely_maximal_set2(freetype(ID)) :- is_maximal_freetype(ID).
4032 is_definitely_maximal_set2(global_set(GS)) :- is_maximal_global_set(GS).
4033 is_definitely_maximal_set2(closure(P,T,B)) :- is_definitely_maximal_closure(P,T,B).
4034 is_definitely_maximal_set2(avl_set(S)) :- quick_definitely_maximal_set_avl(S).
4035 is_definitely_maximal_set2([H|T]) :- nonvar(H), is_definitely_maximal_list(H,T). %, nl,print(maximal(H,T)),nl,nl.
4036 %H==pred_true, T == [pred_false]. % for some reason BOOL is sometimes presented this way
4037 is_definitely_maximal_set2(empty) :- % detect unwrapped AVL sets
4038 add_internal_error('Not a set: ',is_definitely_maximal_set2(empty)),fail.
4039 is_definitely_maximal_set2(node(A,B,C,D,E)) :-
4040 add_internal_error('Not a set: ',is_definitely_maximal_set2(node(A,B,C,D,E))),fail.
4041
4042 is_definitely_maximal_list(pred_true,T) :- nonvar(T), T=[_|_]. %
4043 is_definitely_maximal_list(pred_false,T) :- nonvar(T), T=[_|_].%
4044 is_definitely_maximal_list(fd(_,Type),T) :- nonvar(T),b_global_set_cardinality(Type,Card),
4045 % check if we have the same number of elements as the type: then the set must me maximal
4046 length_at_least(T,Card).
4047 % We could try and and also treat pairs
4048
4049 length_at_least(1,_) :- !. % we have already removed 1 element; T can be nil
4050 length_at_least(N,T) :- nonvar(T), T=[_|TT], N1 is N-1, length_at_least(N1,TT).
4051
4052 is_definitely_maximal_closure(_,_,b(truth,_Pred,_)) :- !.
4053 is_definitely_maximal_closure(P,T,B) :- is_cartesian_product_closure_aux(P,T,B,S1,S2),!,
4054 is_definitely_maximal_set(S1),is_definitely_maximal_set(S2).
4055 is_definitely_maximal_closure(P,T,B) :-
4056 is_full_powerset_or_relations_or_struct_closure(closure(P,T,B),Sets),
4057 l_is_definitely_maximal_set(Sets).
4058
4059 l_is_definitely_maximal_set([]).
4060 l_is_definitely_maximal_set([H|T]) :- is_definitely_maximal_set(H), l_is_definitely_maximal_set(T).
4061
4062 % check if we have an AVL tree covering all elements of the underlying type
4063 quick_definitely_maximal_set_avl(AVL) :-
4064 AVL=node(El,_True,_,_Left,_Right),
4065 quick_definitely_maximal_set_avl_aux(El,AVL).
4066 quick_definitely_maximal_set_avl_aux(El,AVL) :-
4067 try_get_finite_max_card_from_ground_value(El,Card),
4068 % this could fail if El contains empty sets !
4069 % also: it must fail if Card is infinite (no avl_set can be maximal)
4070 (Card < 1000 -> true
4071 ; preferences:preference(solver_strength,SS), Card < 1000+SS*100
4072 ), % otherwise too expensive a check avl_size
4073 quick_avl_approximate_size(AVL,MaxSize),
4074 MaxSize >= Card, % otherwise no sense in computing avl_size, which is linear in size of AVL
4075 avl_size(AVL,Size),
4076 %(MaxSize>=Size -> print(ok(Size,all(Card))),nl ; print('**** ERROR: '), print(Size),nl,trace),
4077 Size=Card.
4078
4079 % check if we have an AVL function with domain covering all elements of the underlying type
4080 quick_definitely_maximal_total_function_avl(AVL) :-
4081 AVL=node(El,_True,_,_Left,_Right),
4082 El=(DomEl,_),
4083 quick_definitely_maximal_set_avl_aux(DomEl,AVL), % the size is exactly the size of the domain
4084 is_avl_partial_function(AVL).
4085
4086 % ----------------------
4087 % set_subtraction /
4088 difference_of_explicit_set(S1,S2,R) :-
4089 difference_of_explicit_set_wf(S1,S2,R,no_wf_available).
4090 % this is called with first argument nonvar (for set_subtraction operator):
4091 difference_of_explicit_set_wf(_S1,S2,R,_) :-
4092 is_definitely_maximal_set(S2), !, R=[].
4093 difference_of_explicit_set_wf(S1,S2,R,_) :- nonvar(S2), S2=[],!, R=S1.
4094 difference_of_explicit_set_wf(S1,S2,R,_) :-
4095 %nonvar(S1),
4096 ? is_very_large_maximal_global_set(S1,Type), !, % TO DO: also for freetype ? cartesian products,...
4097 /* we have a complement-set */
4098 complement_set(S2,Type,R).
4099 difference_of_explicit_set_wf(S1,S2,Result,_) :-
4100 is_not_member_value_closure(S1,Type,MS1),
4101 nonvar(MS1), is_custom_explicit_set(MS1,difference_of_explicit_set_wf),!,
4102 union_complement_set(MS1,S2,Type,Result).
4103 difference_of_explicit_set_wf(_,S2,_,_) :- var(S2), !, fail. % then we cannot do anything below
4104 difference_of_explicit_set_wf(S1,S2,R,WF) :-
4105 is_not_member_value_closure(S2,_Type,MS2), nonvar(MS2),
4106 intersection_of_explicit_set_wf(MS2,S1,R,WF),!.
4107 difference_of_explicit_set_wf(I1,I2,R,_) :-
4108 is_interval_closure_or_integerset(I1,From1,To1),
4109 is_interval_closure_or_integerset(I2,From2,To2),
4110 difference_interval(From1,To1,From2,To2,FromRes,ToRes),
4111 % TO DO: also treat case when difference yields two disjoint intervals
4112 % i.e., do not fail and forget info about interval bounds in case we cannot compute difference as a an interval, e.g., INT - {0}
4113 !,
4114 construct_interval_closure(FromRes,ToRes,R).
4115 difference_of_explicit_set_wf(avl_set(A1),S2,R,WF) :-
4116 (S2=avl_set(A2) ;
4117 ground_value(S2), expand_and_convert_to_avl_set_unless_very_large(S2,A2,WF)),!,
4118 avl_height(A2,H2),
4119 %avl_min(A1,Min1),avl_max(A1,Max1), avl_min(A2,Min2),avl_max(A2,Max2), avl_height(A1,H1),nl,print(diff(avl(H1,Min1,Max1),avl(H2,Min2,Max2))),nl,
4120 avl_height(A1,H1),
4121 ((H2<2 -> true ; H1 > H2+1) % then it is more efficient to expand A2 and remove the A2 elements from A1;
4122 % note that difference_of_explicit_set2 now also sometimes expands both:
4123 % exact threshold when it is beneficial: difference_of_explicit_set2/3
4124 % for {x|x:1..200000 & x mod 2 = 0} - {y|y:2500..29010 & y mod 2 = 0} -> 150 ms vs 80 ms avl(17,int(2),int(200000)),avl(14,int(2500),int(29010)
4125 % {x|x:1..200000 & x mod 2 = 0} - {y|y:2500..59010 & y mod 2 = 0} -> 180 ms vs 80 ms avl(17,int(2),int(200000)),avl(15,int(2500),int(59010))
4126 % {x|x:1..200000 & x mod 2 = 0} - {y|y:500..159010 & y mod 2 = 0} -> 180 ms vs 250 ms avl(17,int(2),int(200000)),avl(17,int(500),int(159010))
4127 -> expand_custom_set_to_sorted_list(S2,ES,_,difference_of_explicit_set1,WF),
4128 difference_of_explicit_set3(ES,A1,R)
4129 ; expand_custom_set_to_sorted_list(avl_set(A1),ES,Done,difference_of_explicit_set2,WF),
4130 difference_of_explicit_set2(ES,H1,A2,H2,R,Done)).
4131 difference_of_explicit_set_wf(S1,S2,R,WF) :-
4132 (S2=avl_set(A2) ;
4133 ground_value(S2), expand_and_convert_to_avl_set_unless_very_large(S2,A2,WF)),!,
4134 avl_height(A2,A2Height),
4135 difference_with_avl(S1,A2,A2Height,R,WF).
4136 % to do: we could detect same_texpr_body for two closures and return R=[]
4137
4138 :- use_module(avl_tools,[avl_approximate_size_from_height/2]).
4139 :- use_module(bsyntaxtree,[safe_create_texpr/4, create_texpr/4, conjunct_predicates/2, mark_bexpr_as_symbolic/2]).
4140 difference_with_avl(S1,A2,A2Height,R,_) :-
4141 is_closure_or_integer_set(S1,[ID],[T],B),
4142 % check if the first argument is infinite; then do the difference set symbolically
4143 % this could supersed the complement set construction and be generalised to other sets apart from avl_sets as A2
4144 avl_approximate_size_from_height(A2Height,A2Size),
4145 Limit is max(A2Size*10,1000000), % if A2 is more than 10% size of S1, probably better to compute difference explicitly
4146 is_very_large_or_symbolic_closure([ID],[T],B,Limit),
4147 !, % TO DO: also allow multiple identifiers
4148 create_texpr(identifier(ID),T,[],TID),
4149 create_texpr(value(avl_set(A2)),set(T),[],A2Value),
4150 create_texpr(not_member(TID,A2Value),pred,[],NotMemA2),
4151 conjunct_predicates([B,NotMemA2],NewBody),
4152 mark_bexpr_as_symbolic(NewBody,NewBodyS),
4153 R = closure([ID],[T],NewBodyS).
4154 difference_with_avl(S1,A2,A2Height,R,WF) :-
4155 (nonvar(S1),S1=avl_set(A1) -> avl_height(A1,H1) ; H1=unknown),
4156 expand_custom_set_to_sorted_list(S1,ES,Done,difference_of_explicit_set3,WF),
4157 difference_of_explicit_set2(ES,H1,A2,A2Height,R,Done).
4158
4159
4160 % construct complement of a set
4161 union_complement_set(S1,S2,Type,Result) :-
4162 ground_value_check(S2,G2),
4163 when(nonvar(G2),union_complement_set2(S1,S2,Type,Result)).
4164 union_complement_set2(S1,S2,Type,Result) :-
4165 union_of_explicit_set(S1,S2,S12),
4166 construct_complement_closure_if_necessary(S12,Type,R),
4167 kernel_objects:equal_object(R,Result,union_complement_set2).
4168
4169 % construct complement of a set
4170 complement_set(S2,Type,Result) :-
4171 ground_value_check(S2,G2),
4172 when(nonvar(G2),complement_set2(S2,Type,Result)).
4173 complement_set2(S2,Type,Result) :-
4174 is_not_member_value_closure(S2,Type,MS2),!, % complement of complement
4175 kernel_objects:equal_object(MS2,Result,complement_set2).
4176 complement_set2(S2,Type,Result) :-
4177 try_expand_and_convert_to_avl_with_check(S2,ExpandedS2,difference_complement_set),
4178 construct_complement_closure_if_necessary(ExpandedS2,Type,R),
4179 kernel_objects:equal_object(R,Result,complement_set2).
4180
4181 :- block construct_complement_closure_if_necessary(-,?,?).
4182 construct_complement_closure_if_necessary(Set,TYPE,R) :-
4183 (Set=[] -> b_type2_set(TYPE,R)
4184 ; is_not_member_value_closure(Set,TYPE,MS) -> R=MS % complement of complement
4185 ; construct_complement_closure(Set,TYPE,R)).
4186
4187 % succeeds if difference of two intervals is also an interval
4188 % SourceLow..SourceUp \ DiffLow..DiffUp
4189 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,9,11,1,8)).
4190 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,9,inf,1,8)).
4191 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,10,12,1,9)).
4192 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,11,12,1,10)).
4193 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,12,13,1,10)).
4194 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,11,inf,1,10)).
4195 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,inf,11,inf,1,10)).
4196 % :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,9,8,1,10)). % 9..8 empty not detected
4197 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,1,8,9,10)).
4198 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,1,10,11,10)). % empty
4199 :- assert_must_succeed(custom_explicit_sets:difference_interval(1,10,1,inf,inf,10)).
4200 :- assert_must_succeed(custom_explicit_sets:difference_interval(3,10,1,2,3,10)).
4201 :- assert_must_succeed(custom_explicit_sets:difference_interval(3,inf,1,2,3,inf)).
4202 :- assert_must_succeed(custom_explicit_sets:difference_interval(3,10,1,3,4,10)).
4203 :- assert_must_succeed(custom_explicit_sets:difference_interval(3,10,1,9,10,10)).
4204 :- assert_must_succeed(custom_explicit_sets:difference_interval(3,10,1,10,11,10)).
4205 difference_interval(SourceLow,SourceUp,DiffLow,DiffUp,ResLow,ResUp) :-
4206 (nonvar(SourceLow),nonvar(DiffLow),nonvar(DiffUp),
4207 geq_inf(SourceLow,DiffLow)
4208 -> % DiffLow is to left of SourceLow
4209 inc(DiffUp,D1),
4210 maximum_with_inf(D1,SourceLow,ResLow),
4211 ResUp=SourceUp % also works if SourceUp is a variable
4212 ; nonvar(DiffUp),nonvar(SourceUp),nonvar(DiffLow),
4213 geq_inf(DiffUp,SourceUp)
4214 -> % DiffUp is to right of SourceUp
4215 ResLow=SourceLow, % also works if SourceLow is a variable
4216 dec(DiffLow,D1),
4217 minimum_with_inf(SourceUp,D1,ResUp)).
4218
4219 inc(N,R) :- N==inf,!,R=inf.
4220 inc(N,N1) :- N1 is N+1.
4221 dec(N,R) :- N==inf,!,R=inf.
4222 dec(N,N1) :- N1 is N-1.
4223
4224 :- use_module(library(ordsets), [ord_subtract/3]).
4225 :- block difference_of_explicit_set2(?,?,?,?,?,-).
4226 difference_of_explicit_set2(ES,A1Height,A2,A2Height,R,_) :-
4227 (number(A1Height), A1Height+4 >= A2Height -> true
4228 ; A2Height < 5
4229 ; Limit is 2**(A2Height-4),
4230 length_larger_than(ES,Limit)
4231 % TO DO: we could try and pass sizes from specific closures to this predicate
4232 ),
4233 % A1 is not much larger than A2, then it is probably faster to use ord_subtract on expanded A2
4234 % {x|x mod 2 =0 & x:1..10000} - {y|y mod 3 =0 & y : 1..200000} : still more efficient with ord_subtract
4235 !,
4236 avl_domain(A2,A2Expanded),
4237 ord_subtract(ES,A2Expanded,OrdRes),
4238 sorted_ground_normalised_list_to_avlset(OrdRes,AVL,difference_of_explicit_set2),
4239 equal_object(AVL,R).
4240 difference_of_explicit_set2(ES,_A1Height,A2,_A2Height,R,_) :-
4241 avl_min(A2,Min),
4242 diff1(ES,Min,A2,IRes),
4243 ord_list_to_avlset(IRes,AVL,difference), % we have generated the elements in the right order already
4244 equal_object(AVL,R). % due to delays in expansion the result could be instantiated
4245
4246
4247 length_larger_than([_|T],Limit) :-
4248 (Limit<1 -> true
4249 ; L1 is Limit-1, length_larger_than(T,L1)).
4250
4251 diff1([],_, _,[]).
4252 diff1([H|T],Min,A1, Res) :-
4253 (H @< Min -> Res = [H-true|Res2],diff1(T,Min,A1,Res2)
4254 ; diff2([H|T],A1,Res)).% TO DO: compute avl_max
4255
4256 diff2([],_, []).
4257 diff2([H|T],A1, Res) :-
4258 (avl_fetch(H,A1) -> Res = Res2 ; Res = [H-true|Res2]), diff2(T,A1,Res2).
4259
4260 % another version to be used when second set small in comparison to first set
4261 difference_of_explicit_set3([],A1,Res) :- construct_avl_set(A1,AVL),
4262 equal_object(AVL,Res). % due to delay in expansion, Res could now be instantiated
4263 difference_of_explicit_set3([H|T],A1,ARes) :-
4264 (avl_delete(H,A1,_True,A2) -> true ; A2=A1),
4265 difference_of_explicit_set3(T,A2,ARes).
4266
4267 % -------------------------
4268
4269 % a version of add_element_to_explicit_set where we have already done the groundness check
4270 add_ground_element_to_explicit_set_wf(avl_set(A),Element,R,WF) :- !,
4271 convert_to_avl_inside_set_wf(Element,AEl,WF),
4272 avl_store(AEl,A,true,A2),!,R=avl_set(A2).
4273 add_ground_element_to_explicit_set_wf(Set,Element,R,WF) :-
4274 add_element_to_explicit_set_wf(Set,Element,R,WF).
4275
4276 add_element_to_explicit_set_wf(global_set(GS),_,R,_) :- is_maximal_global_set(GS), !, R=global_set(GS).
4277 add_element_to_explicit_set_wf(freetype(ID),_,R,_) :- is_maximal_freetype(ID),!, R=freetype(ID).
4278 add_element_to_explicit_set_wf(avl_set(A),Element,R,WF) :-
4279 ground_value(Element), %% was element_can_be_added_or_removed_to_avl(Element),
4280 convert_to_avl_inside_set_wf(Element,AEl,WF),
4281 avl_store(AEl,A,true,A2),!,R=avl_set(A2). /* AVL not normalised */
4282 /* do we need to add support for (special) closures ??
4283 add_element_to_explicit_set_wf(Clos,Element,R,_) :- nonvar(Element),Element=int(X), nonvar(X),
4284 is_interval_closure_or_integerset(Clos,Low,Up), ground(Low), ground(Up),
4285 union_of_interval(X,X,Low,Up,FromRes,ToRes),
4286 !,
4287 construct_interval_closure(FromRes,ToRes,R).
4288 % not-member closure not dealt with here
4289 */
4290
4291 element_can_be_added_or_removed_to_avl(Element) :-
4292 ground_value(Element),
4293 does_not_contain_closure(Element).
4294 ground_element_can_be_added_or_removed_to_avl(Element) :- /* use if you know the element to be ground */
4295 does_not_contain_closure(Element).
4296
4297 % does not contain closure or infinite other sets
4298 does_not_contain_closure([]).
4299 does_not_contain_closure([H|T]) :-
4300 (simple_value(H) -> true /* TO DO: check if we could have a closure at the end ?? */
4301 ; does_not_contain_closure(H),list_does_not_contain_closure(T)).
4302 does_not_contain_closure(fd(_,_)).
4303 does_not_contain_closure(pred_true /* bool_true */).
4304 does_not_contain_closure(pred_false /* bool_false */).
4305 does_not_contain_closure(int(_)).
4306 does_not_contain_closure(string(_)).
4307 does_not_contain_closure(term(_)). % real/floating number
4308 does_not_contain_closure((X,Y)) :- does_not_contain_closure(X), does_not_contain_closure(Y).
4309 does_not_contain_closure(avl_set(_)).
4310 ?does_not_contain_closure(global_set(G)) :- \+ is_infinite_global_set(G,_).
4311 %does_not_contain_closure(freetype(_)).
4312 does_not_contain_closure(freeval(_,_,Value)) :- does_not_contain_closure(Value).
4313 does_not_contain_closure(rec(Fields)) :- does_not_contain_closure_fields(Fields).
4314
4315 does_not_contain_closure_fields([]).
4316 does_not_contain_closure_fields([field(_,Val)|T]) :- does_not_contain_closure(Val),
4317 does_not_contain_closure_fields(T).
4318
4319 list_does_not_contain_closure([]).
4320 list_does_not_contain_closure([H|T]) :-
4321 does_not_contain_closure(H),list_does_not_contain_closure(T).
4322 list_does_not_contain_closure(avl_set(_)).
4323 list_does_not_contain_closure(global_set(G)) :- \+ is_infinite_global_set(G,_).
4324
4325 simple_value(fd(_,_)).
4326 simple_value(pred_true /* bool_true */).
4327 simple_value(pred_false /* bool_false */).
4328 simple_value(int(_)).
4329 simple_value((A,B)) :- simple_value(A), simple_value(B).
4330 simple_value(string(_)).
4331
4332
4333 % a version of the above which throws error if element cannot be added
4334 % assumes element_can_be_added_or_removed_to_avl has been checked
4335 remove_element_from_explicit_set(avl_set(A),Element,R) :-
4336 element_can_be_added_or_removed_to_avl(Element), % remove check?
4337 convert_to_avl_inside_set(Element,AEl), !,
4338 direct_remove_element_from_avl(A,AEl,R).
4339 remove_element_from_explicit_set(ES,Element,R) :-
4340 add_internal_error('Cannot remove element from explicit set:',remove_element_from_explicit_set(ES,Element,R)).
4341
4342 direct_remove_element_from_avl(A,AEl,R) :-
4343 avl_delete(AEl,A,_True,A2),
4344 construct_avl_set(A2,R). /* AVL not normalised */
4345
4346 /* same as remove but element can be absent */
4347 delete_element_from_explicit_set(avl_set(A),Element,R) :-
4348 element_can_be_added_or_removed_to_avl(Element),
4349 convert_to_avl_inside_set(Element,AEl), !,
4350 (avl_delete(AEl,A,_True,A2)
4351 -> construct_avl_set(A2,R)
4352 ; R = avl_set(A)
4353 ). /* AVL not normalised */
4354
4355 is_maximal_global_set(GS) :- is_maximal_global_set(GS,_Type).
4356 is_maximal_global_set(GS,_) :- var(GS),!,fail.
4357 is_maximal_global_set('INTEGER',Type) :- !, Type=integer.
4358 is_maximal_global_set('REAL',Type) :- !, Type=real.
4359 is_maximal_global_set('FLOAT',_) :- !, fail.
4360 is_maximal_global_set('STRING',Type) :- !, Type=string.
4361 is_maximal_global_set(GS,global(GS)) :-
4362 \+ kernel_objects:integer_global_set(GS).
4363
4364 % To do: maybe get rid of all complement set code; add in_difference_set as symbolic binary operator
4365 %is_very_large_maximal_global_set(X,_) :- print(very(X)),nl,fail.
4366 is_very_large_maximal_global_set(closure(P,T,B),Type) :- is_definitely_maximal_closure(P,T,B),
4367 couplise_list(T,Type).
4368 is_very_large_maximal_global_set(global_set('INTEGER'),integer).
4369 is_very_large_maximal_global_set(global_set('STRING'),string).
4370 is_very_large_maximal_global_set(global_set('REAL'),real).
4371 is_very_large_maximal_global_set(freetype(ID),freetype(ID)) :- is_infinite_freetype(ID).
4372
4373
4374
4375 remove_minimum_element_custom_set(avl_set(S),X,RES) :- !,
4376 avl_del_min(S,X,_True,Res0),
4377 (empty_avl(Res0) -> RES=[] ; RES = avl_set(Res0)).
4378 %remove_minimum_element_custom_set(closure(P,T,B),X,RES) :-
4379 % is_interval_closure_or_integerset(Clos,Low,Up),!,
4380 % X = Low, TO DO: construct new interval closure
4381 remove_minimum_element_custom_set(CS,X,RES) :-
4382 expand_custom_set_to_list(CS,ECS,Done,remove_minimum_element_custom_set),
4383 remove_minimum_element_custom_set2(ECS,X,RES,Done).
4384
4385 :- block remove_minimum_element_custom_set2(?,?,?,-).
4386 % wait until Done: otherwise the Tail of the list could be instantiated by somebody else; interfering with expand_custom_set_to_list
4387 remove_minimum_element_custom_set2([H|T],X,RES,_) :- equal_object((H,T),(X,RES)).
4388
4389
4390 min_of_explicit_set_wf(avl_set(S),Min,_) :- !, avl_min(S,Min).
4391 min_of_explicit_set_wf(Clos,Min,WF) :-
4392 is_interval_closure_or_integerset(Clos,Low,Up),
4393 (Low == minus_inf
4394 -> add_wd_error('minimum of unbounded infinite set not defined:',Clos,WF)
4395 ; cs_greater_than_equal(Up,Low),
4396 Min=int(Low)).
4397
4398 cs_greater_than_equal(X,Y) :-
4399 ((X==inf;Y==minus_inf) -> true ; kernel_objects:less_than_equal_direct(Y,X)).
4400
4401
4402 max_of_explicit_set_wf(avl_set(S),Max,_) :- !,avl_max(S,Max).
4403 max_of_explicit_set_wf(Clos,Max,WF) :-
4404 is_interval_closure_or_integerset(Clos,Low,Up),
4405 (Up==inf
4406 -> add_wd_error('maximum of unbounded infinite set not defined:',Clos,WF)
4407 ; cs_greater_than_equal(Up,Low),
4408 Max=int(Up)).
4409
4410 % ------------- SIGMA/PI --------------
4411
4412 % compute sum or product of an integer set:
4413 sum_or_mul_of_explicit_set(avl_set(S),SUMorMUL,Result) :-
4414 avl_domain(S,Dom),
4415 (SUMorMUL=sum -> simple_sum_list(Dom,0,R) ; simple_mul_list(Dom,1,R)),
4416 Result = int(R).
4417 sum_or_mul_of_explicit_set(CS,SUMorMUL,Result) :- SUMorMUL == sum,
4418 is_interval_closure(CS,Low,Up),
4419 sum_interval(Low,Up,Result),
4420 sum_interval_clpfd_prop(Low,Up,Result).
4421
4422 :- block sum_interval(-,?,?), sum_interval(?,-,?).
4423 sum_interval(Low,Up,_) :- (\+ number(Low) ; \+ number(Up)),!,
4424 add_error(sum_interval,'Cannot compute sum of interval: ',Low:Up),fail.
4425 sum_interval(Low,Up,Result) :- Low>Up,!, Result=int(0).
4426 sum_interval(Low,Up,Result) :-
4427 R is ((1+Up-Low)*(Low+Up)) // 2, % generalisation of Gauss formula k*(k+1)//2
4428 Result = int(R).
4429
4430 sum_interval_clpfd_prop(Low,Up,Result) :-
4431 preferences:preference(use_clpfd_solver,true), Result=int(R),
4432 var(R), % we haven't computed the result yet; the bounds are not known; set up constraint propagation rules
4433 !,
4434 % note: the sum is 0 for empty intervals and for 0..0
4435 try_post_constraint((Low #>= 0) #=> (R #>= 0)), % we could provide better bounds here for negative numbers
4436 try_post_constraint(((Low #>= 0) #/\ (Up #> 0) #/\ (Low #=< Up)) #=> (R #> 0)),
4437 try_post_constraint(((Low #=< Up) #\/ (R #\= 0)) #=> (R #= ((1+Up-Low)*(Low+Up))//2)),
4438 try_post_constraint((Low #> Up) #=> (R #= 0)).
4439 % not working yet: x = SIGMA(i).(i:-3..n|i) & x=0 & n< -1
4440 sum_interval_clpfd_prop(_,_,_).
4441
4442 simple_sum_list([],A,A).
4443 simple_sum_list([int(H)|T],Acc,R) :- NA is Acc+H, simple_sum_list(T,NA,R).
4444 simple_mul_list([],A,A).
4445 simple_mul_list([int(H)|T],Acc,R) :- NA is Acc*H, simple_mul_list(T,NA,R).
4446
4447
4448 /*
4449 direct_product_symbolic(S,R,Res) :- % NOT YET FINISHED
4450 nonvar(S), S=closure(PS,[T1,TS2],RS),
4451 nonvar(R), R=closure(PR,[T1,TR1],RR),
4452 is_lambda_value_domain_closure(PS,TS,RS, SDomainValue,SExpr),
4453 is_lambda_value_domain_closure(PR,TR,RR, RDomainValue,RExpr),
4454 construct_closure(['zzz','_lambda_result_'],[T1,couple(TR1,TR2)],
4455 member(zzz,SDomainValue) , member(zzz,RDomainValue), eq(lambda,pair(SExpr,RExpr))).
4456 */
4457
4458 % we assume that try_expand_and_convert_to_avl_unless_very_large already called on arguments
4459 direct_product_explicit_set(S,R,Res) :-
4460 nonvar(R), %is_custom_explicit_set(R,direct_product),
4461 nonvar(S), %is_custom_explicit_set(S,direct_product),
4462 direct_product_explicit_set_aux(S,R,Res).
4463 %direct_product_explicit_set_aux(S,R,Res) :- (S = closure(_,_,_) ; R = closure(_,_,_)),
4464 % print_term_summary(direct_product_explicit_set_aux(S,R,Res)),nl,
4465 % % TO DO: generate closure
4466 % fail.
4467 direct_product_explicit_set_aux(avl_set(AS),avl_set(AR),Res) :-
4468 % the expansion guarantees that we have the lists ES and ER then in sorted order
4469 avl_domain(AS,ES), % -> expand_custom_set(avl_set(AS),ES),
4470 avl_domain(AR,ER), % -> expand_custom_set(avl_set(AR),ER),
4471 direct_product3(ES,ER,DPList),
4472 ord_list_to_avlset(DPList,DPAVL,direct_product), % is it really ordered ? findall must also return things ordered!
4473 equal_object(DPAVL,Res,direct_product_explicit_set).
4474
4475 direct_product3([],_Rel2,[]).
4476 direct_product3([(From,To1)|T1],Rel2,Res) :-
4477 get_next_mapped_to_eq(T1,From,TTo,Tail1), ToList1 = [To1|TTo],
4478 get_next_mapped_to(Rel2,From,ToList2,Tail2),
4479 calc_direct_product(ToList1,From,ToList2,Res,Rest),
4480 (Tail2=[] -> Rest=[] ; direct_product3(Tail1,Tail2,Rest)).
4481
4482 % get all elements which map to From, supposing that the list is sorted & we have already had a match
4483 get_next_mapped_to_eq([],_,[],[]).
4484 get_next_mapped_to_eq([(From2,To2)|T],From,Result,Tail) :-
4485 (From=From2 -> Result = [To2|RR], get_next_mapped_to_eq(T,From,RR,Tail)
4486 ; Result = [], Tail = [(From2,To2)|T]
4487 ).
4488
4489 % get all elements which map to From, supposing the list is sorted
4490 get_next_mapped_to([],_,[],[]).
4491 get_next_mapped_to([(From2,To2)|T],From,Result,Tail) :-
4492 (From=From2 -> Result = [To2|RR], get_next_mapped_to_eq(T,From,RR,Tail)
4493 ; From2 @> From -> Result = [], Tail = [(From2,To2)|T]
4494 ; get_next_mapped_to(T,From,Result,Tail)
4495 ).
4496
4497 calc_direct_product([],_From,_,Tail,Tail).
4498 calc_direct_product([To1|T1],From,To2List,Result,Tail) :-
4499 findall((From,(To1,To2))-true,member(To2,To2List),Result,ResResult),
4500 calc_direct_product(T1,From,To2List,ResResult,Tail).
4501
4502 % TO DO: maybe also add a special rule for infinite R such as event_b_identity ?
4503 domain_restriction_explicit_set_wf(S,R,Res,WF) :- /* S <| R */
4504 nonvar(R),
4505 (nonvar(S),is_one_element_custom_set(S,El),R \= closure(_,_,_) ->
4506 domain_restrict_singleton_element(El,R,Res)
4507 ; restriction_explicit_set_wf(S,R,Res,domain,pred_true,WF)).
4508 domain_subtraction_explicit_set_wf(S,R,Res,WF) :- /* S <<| R */
4509 (nonvar(S),is_one_element_custom_set(S,El), nonvar(R), R=avl_set(AVL) ->
4510 avl_domain_subtraction_singleton(AVL,El,ARes),
4511 construct_avl_set(ARes,Res) % TO DO: use this also when S is small and R large
4512 ; restriction_explicit_set_wf(S,R,Res,domain,pred_false,WF)).
4513 range_restriction_explicit_set_wf(R,S,Res,WF) :- /* R |> S */
4514 restriction_explicit_set_wf(S,R,Res,range,pred_true,WF).
4515 range_subtraction_explicit_set_wf(R,S,Res,WF) :- /* R |>> S */
4516 restriction_explicit_set_wf(S,R,Res,range,pred_false,WF).
4517
4518
4519 domain_restrict_singleton_element(El,R,Res) :- /* {El} <| R ; TO DO maybe apply this technique for "small" sets as well */
4520 nonvar(R), is_custom_explicit_set(R,domain_restrict_singleton_element),
4521 expand_and_convert_to_avl_set(R,AR,domain_restrict_singleton_element,''), % can generate ARel=empty; will fail if not possible to convert
4522 findall((El,Z)-true, avl_fetch_pair(El,AR,Z), RTuples),
4523 ord_list_to_avlset(RTuples,Res,domain_restrict_singleton_element).
4524
4525 restriction_explicit_set_wf(Set,Rel,Res,_RanOrDom,AddWhen,WF) :- Set==[],!,
4526 (AddWhen=pred_false
4527 -> equal_object_wf(Rel,Res,restriction_explicit_set_wf,WF) % {} <<| Rel = Rel |>> {} = Rel
4528 ; kernel_objects:empty_set_wf(Res,WF)
4529 ).
4530 restriction_explicit_set_wf(Set,Rel,Res,_RanOrDom,AddWhen,WF) :- is_definitely_maximal_set(Set),!,
4531 (AddWhen=pred_true
4532 -> equal_object_wf(Rel,Res,restriction_explicit_set_wf,WF) % TYPE <| Rel = Rel |> TYPE = Rel
4533 ; kernel_objects:empty_set_wf(Res,WF)
4534 ).
4535 restriction_explicit_set_wf(_,Rel,_,_,_,_) :- var(Rel),!,fail.
4536 restriction_explicit_set_wf(Set,closure(Paras,Types,Body),Res,RanOrDom,AddWhen,WF) :-
4537 % perform symbolic treatment by adding restriction predicate to Body
4538 !,
4539 (RanOrDom=domain
4540 -> get_domain_id_or_expr(Paras,Types,TID,TT)
4541 ; get_range_id_or_expr(Paras,Types,TID,TT)
4542 ),
4543 TSet=b(value(Set),set(TT),[]),
4544 (AddWhen = pred_true
4545 -> PRED = member(TID,TSet)
4546 ; PRED = not_member(TID,TSet) ),
4547 conjunct_predicates([b(PRED,pred,[]),Body],NewBody),
4548 % translate:print_bexpr(NewBody),nl,
4549 try_expand_and_convert_to_avl_with_catch_wf(closure(Paras,Types,NewBody),Res,restriction_explicit_set_wf,WF).
4550 restriction_explicit_set_wf(Set,Rel,Res,RanOrDom,AddWhen,WF) :-
4551 is_custom_explicit_set(Rel,restriction_explicit_set_wf),
4552 expand_and_convert_to_avl_set(Rel,ARel,restriction_explicit_set_wf,''), % can generate ARel=empty; will fail if not possible to convert
4553 avl_domain(ARel,ERel), % -> expand_custom_set(avl_set(ARel),ERel),
4554 %try_expand_and_convert_to_avl_unless_large_wf(Set,ES,WF),
4555 (nonvar(Set),Set=avl_set(AVLS)
4556 -> restrict2_avl(ERel,AVLS,DRes,RanOrDom,AddWhen,Done)
4557 ; restrict2(ERel,Set,DRes,RanOrDom,AddWhen,Done,WF)
4558 ),
4559 finish_restriction(Done,DRes,Res).
4560
4561 % extract domain expression for domain restriction/subtraction predicate:
4562 get_domain_id_or_expr([DR],[couple(TD,TR)], PRJ1, TD) :- !, % special case: just one parameter in closure
4563 TID = b(identifier(DR),couple(TD,TR),[]),
4564 PRJ1 = b(first_of_pair(TID),TD,[]).
4565 get_domain_id_or_expr([D1|Paras],[TD1|Types],Expr,Type) :-
4566 get_dom_couple_aux(Paras,Types, b(identifier(D1),TD1,[]), TD1, Expr,Type).
4567
4568 get_dom_couple_aux([_RangeID],[_], AccExpr, AccType, Expr, Type) :- !, Expr=AccExpr, Type=AccType.
4569 get_dom_couple_aux([D2|TParas],[TD2|Types], AccExpr, AccType, Expr, Type) :-
4570 TID2 = b(identifier(D2),TD2,[]),
4571 NewAccType = couple(AccType,TD2),
4572 NewAcc = b(couple(AccExpr,TID2),NewAccType,[]),
4573 get_dom_couple_aux(TParas,Types,NewAcc,NewAccType,Expr,Type).
4574
4575 :- use_module(library(lists),[last/2]).
4576 % extract range expression for range restriction/subtraction predicate:
4577 get_range_id_or_expr( [DR],[CType], PRJ2, TR) :- !, % special case: just one parameter in closure
4578 CType = couple(_TD,TR),
4579 TID = b(identifier(DR),CType,[]),
4580 PRJ2 = b(second_of_pair(TID),TR,[]).
4581 get_range_id_or_expr( [_|Paras],[_|Types], b(identifier(R),TR,[]), TR) :-
4582 last(Paras,R), last(Types,TR).
4583
4584 :- block finish_restriction(-,?,?).
4585 finish_restriction(_,DRes,Res) :-
4586 ord_list_to_avlset(DRes,Restriction,restriction),
4587 ? equal_object(Restriction,Res,finish_restriction). % as we may block below: we need to use equal_object
4588
4589 restrict2([],_,[],_,_,done,_WF).
4590 restrict2([(From,To)|T],S,Res,RanOrDom,AddWhen,Done,WF) :-
4591 (RanOrDom==domain -> El=From ; El=To),
4592 kernel_equality:membership_test_wf(S,El,MemRes,WF), % TO DO: WF Version !!
4593 /* this only makes sense once we have the full result as argument:
4594 (nonvar(MemRes) -> true % it is already decided
4595 ; AddWhen=pred_true -> kernel_equality:membership_test_wf(Res,(From,To),MemRes,WF)
4596 ; kernel_equality:membership_test_wf(Res,(From,To),InResult,WF), bool_pred:negate(InResult,MemRes)
4597 ), */
4598 ? restrict3(MemRes,From,To,T,S,Res,RanOrDom,AddWhen,Done,WF).
4599 :- block restrict3(-, ?,?, ?,?,?, ?,?,?,?).
4600 restrict3(MemRes, From,To, T,S,Res, RanOrDom,AddWhen,Done,WF) :-
4601 (AddWhen=MemRes -> Res = [(From,To)-true|TRes]
4602 ; Res=TRes),
4603 ? restrict2(T,S,TRes,RanOrDom,AddWhen,Done,WF).
4604
4605 % optimised version when second set is also an AVL tree: less blocking,...
4606 restrict2_avl([],_,[],_,_,done).
4607 restrict2_avl([(From,To)|T],AVLS,Res,RanOrDom,AddWhen,Done) :-
4608 fetch(RanOrDom,From,To,AVLS,MemRes),
4609 (AddWhen=MemRes -> Res = [(From,To)-true|TRes]
4610 ; Res=TRes),
4611 restrict2_avl(T,AVLS,TRes,RanOrDom,AddWhen,Done).
4612
4613 fetch(domain,El,_,AVLS,MemRes) :- (avl_fetch(El,AVLS) -> MemRes=pred_true ; MemRes = pred_false).
4614 fetch(range,_,El,AVLS,MemRes) :- (avl_fetch(El,AVLS) -> MemRes=pred_true ; MemRes = pred_false).
4615
4616 % override R(X) := Y
4617 override_pair_explicit_set(avl_set(S),X,Y,avl_set(NewAVL)) :- element_can_be_added_or_removed_to_avl(X),
4618 element_can_be_added_or_removed_to_avl(Y),
4619 convert_to_avl_inside_set(X,AX),
4620 convert_to_avl_inside_set(Y,AY),
4621 avl_domain_subtraction_singleton(S,AX,AVL2),
4622 avl_store((AX,AY), AVL2, true, NewAVL).
4623
4624 avl_domain_subtraction_singleton(AVL,AX,NewAVL) :-
4625 avl_delete_pair(AX,AVL,_True,AVL2),
4626 !, % recurse, in case we have multiple entries
4627 % this recursion could be avoided if we know AVL to be a function
4628 avl_domain_subtraction_singleton(AVL2,AX,NewAVL).
4629 avl_domain_subtraction_singleton(AVL,_,AVL).
4630
4631 % try and decompose an AVL set into a cartesian product
4632 % AVL = Set1 * Set2
4633 % much faster e.g. for let xx = ((1..10)*(3..1000)\/ {0}*(3..1000)) and then xx = AA*BB
4634 % should not produce pending co-routines
4635 decompose_avl_set_into_cartesian_product_wf(AVL,DomainSet,RangeSet,WF) :-
4636 avl_domain(AVL,Expansion),
4637 decompose_cart(Expansion,'$none',DomainList,[],RangeList),
4638 construct_avl_from_lists_wf(DomainList,DomainSet,WF),
4639 construct_avl_from_lists_wf(RangeList,RangeSet,WF).
4640
4641 decompose_cart([],_,[],[],_).
4642 decompose_cart([(A,B)|T],Prev,Domain,Range,FullRange) :-
4643 (A=Prev
4644 -> Range = [B|TRange],
4645 decompose_cart(T,Prev,Domain,TRange,FullRange)
4646 ; Domain = [A|TDom], Range=[],
4647 FullRange = [B|TRange],
4648 decompose_cart(T,A,TDom,TRange,FullRange)
4649 ).
4650
4651 /* --------- */
4652 /* EXPANSION */
4653 /* --------- */
4654
4655 :- use_module(b_global_sets,[all_elements_of_type_wf/3, all_elements_of_type_rand_wf/3]).
4656 :- use_module(kernel_freetypes,[expand_freetype/3]).
4657
4658 expand_custom_set(X,R) :- expand_custom_set_wf(X,R,expand_custom_set,no_wf_available).
4659 expand_custom_set(X,R,Src) :- expand_custom_set_wf(X,R,Src,no_wf_available).
4660 expand_custom_set_wf(X,R,Source,WF) :- var(X), !,
4661 add_error_and_fail(expand_custom_set_wf, 'Variable as argument: ',expand_custom_set_wf(X,R,Source,WF)).
4662 expand_custom_set_wf(global_set(GS),ExpandedSet,_,WF) :- !,
4663 all_elements_of_type_wf(GS,ExpandedSet,WF). % they are generated in order
4664 expand_custom_set_wf(freetype(GS),ValueList,_,WF) :- !,
4665 expand_freetype(GS,ValueList,WF).
4666 expand_custom_set_wf(avl_set(AVL),ExpandedSet,_,_) :- !,
4667 avl_domain(AVL,ExpandedSet).
4668 expand_custom_set_wf(closure(Parameters,PTypes,Cond),Res,Source,WF) :- !,
4669 ? expand_closure_to_list(Parameters,PTypes,Cond,Res,_Done,Source,WF).
4670 %wait_try_expand_custom_set(Res1,Res). % could be in AVL form; no longer the case !
4671 expand_custom_set_wf(Set,_,Source,_) :-
4672 add_error_and_fail(expand_custom_set(Source),'Cannot expand custom set: ',Set).
4673
4674
4675
4676 %try_expand_only_custom_closure_global(X,Y) :-
4677 % (var(X) -> X=Y ; expand_only_custom_closure_global(X,Y,check)).
4678
4679 expand_only_custom_closure_global(X,R,C,_WF) :- var(X), !,
4680 add_error_and_fail(expand_only_custom_closure_global, 'Variable as argument: ',expand_only_custom_closure_global(X,R,C)).
4681 expand_only_custom_closure_global(global_set(GS),ExpandedSet,_,WF) :- !,all_elements_of_type_wf(GS,ExpandedSet,WF).
4682 expand_only_custom_closure_global(freetype(GS),ExpandedSet,_,_WF) :- !,ExpandedSet=freetype(GS).
4683 expand_only_custom_closure_global(avl_set(AVL),ExpandedSet,_,_WF) :- !, ExpandedSet=avl_set(AVL).
4684 expand_only_custom_closure_global(closure(Parameters,PTypes,Cond),Res,CheckTimeOuts,WF) :- !,
4685 (Res==[] -> is_empty_explicit_set(closure(Parameters,PTypes,Cond)) % TO DO: think about other special cases
4686 ; expand_closure_to_avl_or_list(Parameters,PTypes,Cond,Res,CheckTimeOuts,WF)).
4687 expand_only_custom_closure_global(Set,Set,_CheckTimeOuts,_WF).
4688 %:- add_error_and_fail(expand_only_custom_closure_global,'Cannot expand custom set: ',Set).
4689
4690
4691 try_expand_custom_set_with_catch(CS,Expansion,PP) :-
4692 on_enumeration_warning(try_expand_custom_set_wf(CS,Expansion,PP,no_wf_available),
4693 Expansion=CS).
4694
4695 try_expand_custom_set(CS,Expansion) :-
4696 try_expand_custom_set_wf(CS,Expansion,try_expand_custom_set,no_wf_available).
4697
4698
4699 try_expand_custom_set_wf(CS,Res,_,_) :- var(CS),!,Res=CS.
4700 try_expand_custom_set_wf([],Res,_,_) :- !, Res=[].
4701 try_expand_custom_set_wf([H|T],Res,_,_) :- !, Res=[H|T].
4702 try_expand_custom_set_wf(CS,Res,Src,WF) :-
4703 expand_custom_set_wf(CS,Res,Src,WF). % will generate error message for illegal sets
4704
4705
4706 :- assert_must_succeed((expand_custom_set_to_list(closure(['_zzzz_unit_tests'],
4707 [couple(integer,integer)],
4708 b(member(b(identifier('_zzzz_unit_tests'),couple(integer,integer),[generated]),
4709 b(value([(int(1),int(22))]),set(couple(integer,integer)),[])),pred,[])),R),R==[(int(1),int(22))])).
4710
4711 expand_custom_set_to_list(CS,List) :- expand_custom_set_to_list(CS,List,_Done,unknown).
4712
4713 % a version of expansion which returns guaranteed_ground if the List is guaranteed to be ground
4714 expand_custom_set_to_list_gg(CS,List,GuaranteedGround,_PP) :-
4715 nonvar(CS), CS=avl_set(AVL), var(List),
4716 !,
4717 GuaranteedGround = guaranteed_ground,
4718 avl_domain(AVL,List).
4719 expand_custom_set_to_list_gg(CS,List,not_guaranteed_ground,PP) :-
4720 expand_custom_set_to_list(CS,List,_Done,PP).
4721
4722 % a version where the expansion should happen straightaway and should not block:
4723 expand_custom_set_to_list_now(CS,List) :- expand_custom_set_to_list(CS,List,Done,unknown),
4724 (Done==true -> true ; print_error(expand_custom_set_to_list_not_done(CS,List))).
4725
4726 :- block expand_custom_set_to_sorted_list(-,-,?,?,?).
4727 % sorts the resulting list if needed
4728 % due to random enumeration
4729 expand_custom_set_to_sorted_list(From,To,Done,Source,WF) :-
4730 expand_custom_set_to_list(From,UnsortedTo,Done,Source),
4731 (get_preference(randomise_enumeration_order,true)
4732 -> sort_when_done(Done,UnsortedTo,To,WF) ; UnsortedTo = To).
4733
4734 :- block sort_when_done(-,?,?,?).
4735 sort_when_done(_,Unsorted,Res,WF) :- sort(Unsorted,Sorted),
4736 equal_object_wf(Sorted,Res,sort_when_done,WF).
4737
4738 expand_custom_set_to_list(From,To,Done,Source) :-
4739 expand_custom_set_to_list_wf(From,To,Done,Source,no_wf_available).
4740
4741 :- use_module(kernel_objects,[equal_object_wf/4]).
4742
4743 % try expand custom set to list; on enumeration warning set Done to enumeration_warning
4744 try_expand_custom_set_to_list_wf(From,To,Done,Source,WF) :-
4745 on_enumeration_warning(expand_custom_set_to_list_wf(From,To,Done,Source,WF),
4746 (Done=enumeration_warning)).
4747
4748 expand_custom_set_to_list_wf(From,To,Done,Source,WF) :-
4749 expand_custom_set_to_list_k_wf(From,To,Done,_Kind,Source,WF).
4750
4751 % a variation of expand_custom_set_to_list which also checks that there are no duplicates in the list
4752 expand_custom_set_to_list_no_dups_wf(From,To,Done,Source,WF) :-
4753 expand_custom_set_to_list_k_wf(From,To,Done,Kind,Source,WF),
4754 check_dups(Kind,To,WF).
4755
4756 :- block check_dups(-,?,?).
4757 check_dups(unsorted_list,List,WF) :- !,
4758 kernel_objects:check_no_duplicates_in_list(List,[],WF).
4759 check_dups(_,_,_).
4760
4761 % warn if duplicates in list; to do: use in prob_safe mode
4762 %:- block warn_dups(-,?,?,?).
4763 %warn_dups(unsorted_list,List,Src,WF) :- !,
4764 % kernel_objects:warn_if_duplicates_in_list(List,Src,WF).
4765 %warn_dups(_,_,_,_).
4766
4767
4768
4769 :- block expand_custom_set_to_list_k_wf(-,-,?,?,?,?).
4770 % ensures that the output is a pure list; the list skeleton should not be instantiated by anybody else
4771 expand_custom_set_to_list_k_wf(From,To,Done,Kind,Source,WF) :-
4772 (var(From) ->
4773 (is_list_skeleton(To)
4774 ? -> equal_object_wf(To,From,Source,WF), Done=true, Kind=unsorted_list
4775 ? ; expand_custom_set_to_list2(To,From,Done,Kind,Source,WF))
4776 ; var(To),is_list_skeleton(From)
4777 -> To=From, Done=true, Kind=unsorted_list % equal_object_wf will also to a Prolog unification
4778 ? ; expand_custom_set_to_list2(From,To,Done,Kind,Source,WF)).
4779
4780 expand_custom_set_to_list2([],ExpandedSet,Done,Kind,_Source,WF) :- !,
4781 ? equal_object_wf([],ExpandedSet,expand_custom_set_to_list2,WF),Done=true,Kind=empty_set.
4782 expand_custom_set_to_list2([H|T],ExpandedSet,Done,Kind,Source,WF) :- !, Kind=unsorted_list,
4783 ? equal_object_wf([H|ET],ExpandedSet,expand_custom_set_to_list2,WF),
4784 ? expand_custom_set_to_list3(T,ET,Done,Source,WF).
4785 expand_custom_set_to_list2(global_set(GS),ExpandedSet,Done,Kind,_Source,WF) :- !,
4786 all_elements_of_type_rand_wf(GS,R,WF),
4787 check_list(R,expand_custom_set_to_list2),
4788 equal_object_wf(R,ExpandedSet,expand_custom_set_to_list2,WF),Done=true,Kind=sorted_list.
4789 expand_custom_set_to_list2(avl_set(AVL),ExpandedSet,Done,Kind,_Source,WF) :- !,
4790 avl_domain(AVL,R),
4791 ? equal_object_wf(R,ExpandedSet,expand_custom_set_to_list2,WF), Done=true,Kind=sorted_list.
4792 expand_custom_set_to_list2(closure(Parameters,PTypes,Cond),ExpandedSet,Done,Kind,Source,WF) :- !,
4793 expand_closure_to_list(Parameters,PTypes,Cond,ExpandedSet,Done,Source,WF),
4794 Kind=sorted_list.
4795 %assign_expand_result(CDone,Res,ExpandedSet,Done).
4796 expand_custom_set_to_list2(freetype(ID),ExpandedSet,Done,Kind,_Source,WF) :- !,
4797 expand_freetype(ID,R,WF),
4798 equal_object_wf(R,ExpandedSet,expand_custom_set_to_list2,WF),
4799 Done=true,Kind=sorted_list.
4800 % missing avl_set wrapper:
4801 expand_custom_set_to_list2(node(A,B,C,D,E),ExpandedSet,Done,Kind,Source,WF) :- !,
4802 add_internal_error('Illegal argument: ',expand_custom_set_to_list2(node(A,B,C,D,E),ExpandedSet,Done,Source)),
4803 expand_custom_set_to_list2(avl_set(node(A,B,C,D,E)),ExpandedSet,Done,Kind,Source,WF).
4804 expand_custom_set_to_list2(E,ES,Done,Kind,Source,WF) :-
4805 add_internal_error('Illegal argument: ',expand_custom_set_to_list2(E,ES,Done,Kind,Source,WF)),fail.
4806
4807 :- block expand_custom_set_to_list3(-,-,?,?,?). % we are no longer sure which was From and which is To
4808 expand_custom_set_to_list3(From,To,Done,Source,WF) :-
4809 ? (var(From) -> expand_custom_set_to_list2(To,From,Done,_,Source,WF) ;
4810 ? expand_custom_set_to_list2(From,To,Done,_,Source,WF)).
4811
4812
4813 is_list_skeleton(X) :- var(X),!,fail.
4814 is_list_skeleton([]).
4815 is_list_skeleton([_|T]) :- is_list_skeleton(T).
4816
4817 % true if it is more efficient to keep this, rather than expand into list
4818 is_efficient_custom_set(avl_set(_)).
4819 is_efficient_custom_set(closure(P,T,B)) :-
4820 (is_interval_closure(closure(P,T,B),_,_) -> true ; is_infinite_or_symbolic_closure(P,T,B)).
4821 ?is_efficient_custom_set(global_set(X)) :- is_infinite_global_set(X,_).
4822 is_efficient_custom_set(freetype(_)).
4823
4824 % tries to expand & convert to avl_set; fails if not possible: NOTE: also generates empty AVL
4825 expand_and_convert_to_avl_set(R,AER,Origin,Source) :-
4826 try_expand_and_convert_to_avl(R,ER,Origin,Source),
4827 nonvar(ER),(ER==[] -> AER=empty ; ER=avl_set(AER)).
4828
4829
4830 expand_and_convert_to_avl_set_unless_very_large(R,AER,WF) :-
4831 try_expand_and_convert_to_avl_unless_very_large_wf(R,ER,WF),
4832 nonvar(ER),(ER==[] -> AER=empty ; ER=avl_set(AER)).
4833
4834
4835 % similar to unless_large version, but will only expand if it is guaranteed to be small
4836
4837 try_expand_and_convert_to_avl_if_smaller_than(freetype(GS),Res,_) :- !, Res = freetype(GS).
4838 try_expand_and_convert_to_avl_if_smaller_than([H|T],Res,_) :- !, try_expand_and_convert_to_avl([H|T],Res).
4839 try_expand_and_convert_to_avl_if_smaller_than(avl_set(A),Res,_) :- !, Res=avl_set(A).
4840 try_expand_and_convert_to_avl_if_smaller_than(CS,Res,Limit) :-
4841 (is_small_specific_custom_set(CS,Limit)
4842 -> try_expand_and_convert_to_avl(CS,Res,try_expand_and_convert_to_avl_if_smaller_than,'')
4843 ; Res = CS % TO DO: maybe look at cardinality of types and determine max. cardinality
4844 ).
4845 is_small_specific_custom_set(CS,Limit) :- card_for_specific_custom_set(CS,Card,Code),
4846 call(Code), is_finite_card(Card), Card<Limit.
4847 get_card_for_specific_custom_set(CS,Card) :-
4848 card_for_specific_custom_set(CS,Card,Code),
4849 call(Code), ground(Card).
4850
4851 try_expand_and_convert_to_avl_unless_very_large_wf(CS,Res,WF) :-
4852 try_expand_and_convert_to_avl_unless_large_wf(CS,Res,10000,WF).
4853
4854 try_expand_and_convert_to_avl_unless_large_wf(CS,Res,WF) :-
4855 try_expand_and_convert_to_avl_unless_large_wf(CS,Res,2000,WF).
4856
4857 try_expand_and_convert_to_avl_unless_large_wf(CS,Res,_,_WF) :- var(CS), !, CS=Res.
4858 try_expand_and_convert_to_avl_unless_large_wf(global_set(GS),Res,_,_WF) :- !, Res = global_set(GS).
4859 try_expand_and_convert_to_avl_unless_large_wf(freetype(GS),Res,_,_WF) :- !, Res = freetype(GS).
4860 %try_expand_and_convert_to_avl_unless_large_wf(CS,Res,_WF) :- is_interval_closure(CS,Low,Up),!,
4861 % ((ground(Low),ground(Up),Size is 1+Up-Low, Size<2000)
4862 %% -> try_expand_and_convert_to_avl(CS,Res)
4863 % ; Res = CS
4864 % ).
4865 try_expand_and_convert_to_avl_unless_large_wf(closure(P,T,B),Res,Limit,_WF) :-
4866 is_very_large_or_symbolic_closure(P,T,B,Limit),!, % is explicitly marked as SYMBOLIC
4867 Res=closure(P,T,B).
4868 try_expand_and_convert_to_avl_unless_large_wf(CS,Res,_Limit,WF) :-
4869 % TO DO: check if maybe we cannot determine card explicitly, but have a large lower-bound
4870 try_expand_and_convert_to_avl_wf(CS,Res,try_expand_and_convert_to_avl_unless_large,'',WF).
4871
4872
4873
4874 % calls try_expand_and_convert_to_avl and returns original value if enumeration warning occured
4875 try_expand_and_convert_to_avl_with_catch_wf(CS,Res,Origin,WF) :-
4876 on_enumeration_warning(try_expand_and_convert_to_avl_wf(CS,Res,Origin,'',WF),
4877 Res=CS).
4878
4879 /* tries to generate an avl-structure, if possible */
4880 try_expand_and_convert_to_avl(CS,Res) :-
4881 try_expand_and_convert_to_avl_wf(CS,Res,try_expand_and_convert_to_avl,'',no_wf_available).
4882
4883 try_expand_and_convert_to_avl(CS,Res,Origin,Source) :-
4884 try_expand_and_convert_to_avl_wf(CS,Res,Origin,Source,no_wf_available).
4885
4886 try_expand_and_convert_to_avl_wf(CS,Res,_,_,_WF) :- var(CS), !, CS=Res.
4887 try_expand_and_convert_to_avl_wf(avl_set(A),R,_,_,_WF) :- !, R=avl_set(A).
4888 try_expand_and_convert_to_avl_wf([],R,_,_,_WF) :- !, R=[].
4889 try_expand_and_convert_to_avl_wf([H|T],R,_,_,WF) :- !, try_convert_to_avl_wf([H|T],R,WF).
4890 try_expand_and_convert_to_avl_wf(closure(P,T,B),Res,Origin,_Source,WF) :- !,
4891 debug_opt_push_wait_flag_call_stack_info(WF,
4892 external_call('TRY EXPANDING',[closure(P,T,B)],unknown),WF2),
4893 expand_only_custom_closure_global(closure(P,T,B),Expansion,check(Origin),WF2),
4894 try_convert_to_avl_wf(Expansion,Res,WF).
4895 try_expand_and_convert_to_avl_wf(CS,Res,Origin,_Source,WF) :-
4896 (\+ is_custom_explicit_set(CS,try_expand_and_convert_to_avl_wf)
4897 -> Expansion = CS
4898 ; expand_only_custom_closure_global(CS,Expansion,check(Origin),WF)
4899 ),
4900 try_convert_to_avl_wf(Expansion,Res,WF).
4901
4902 try_convert_to_avl(Expansion,Res) :-
4903 (should_be_converted_to_avl_from_lists(Expansion) -> construct_avl_from_lists(Expansion,Res) ; Res=Expansion).
4904 try_convert_to_avl_wf(Expansion,Res,WF) :-
4905 (should_be_converted_to_avl_from_lists(Expansion) -> construct_avl_from_lists_wf(Expansion,Res,WF) ; Res=Expansion).
4906
4907 should_be_converted_to_avl_from_lists(Value) :- var(Value),!,fail.
4908 should_be_converted_to_avl_from_lists(Value) :-
4909 \+ is_custom_explicit_set(Value,should_be_converted_to_avl_from_lists), % already avl_set, global_set or closure
4910 ? \+ do_not_convert_aux(Value),
4911 ground_value(Value).
4912
4913 do_not_convert_aux(V) :- var(V),!.
4914 do_not_convert_aux((A,B)) :- !,
4915 ? (do_not_convert_aux(A) -> true ; do_not_convert_aux(B)).
4916 do_not_convert_aux([H|T]) :- !, % do not convert a set containing a symbolic closure
4917 ? (var(T) -> true ; do_not_convert_aux(H)).
4918 do_not_convert_aux(rec(Fields)) :- !,
4919 (var(Fields) -> true
4920 ? ; member(field(_,V),Fields), do_not_convert_aux(V) -> true).
4921 do_not_convert_aux(H) :-
4922 ? is_symbolic_closure(H).
4923
4924 should_be_converted_to_avl(Value) :- %preference(use_avl_trees_for_sets,true),
4925 ground_value(Value).
4926
4927 try_expand_and_convert_to_avl_with_check(CS,Res,Origin) :-
4928 try_expand_and_convert_to_avl_with_check(CS,Res,do_not_keep_intervals,Origin).
4929
4930 try_expand_and_convert_to_avl_with_check(CS,Res,_,_Origin) :- var(CS),!, Res = CS.
4931 try_expand_and_convert_to_avl_with_check([],Res,_,_Origin) :- !, Res=[].
4932 try_expand_and_convert_to_avl_with_check(avl_set(A),Res,_,_Origin) :- !, Res=avl_set(A).
4933 try_expand_and_convert_to_avl_with_check([H|T],Res,_,Origin) :- !, try_expand_and_convert_to_avl([H|T],Res,Origin,'').
4934 %try_expand_and_convert_to_avl_with_check(CS,Res,_Origin) :-
4935 % \+ is_custom_explicit_set(CS,try_expand_and_convert_to_avl),!, Res = CS.
4936 try_expand_and_convert_to_avl_with_check(CS,Res,KeepIntervals,_Origin) :-
4937 is_interval_closure(CS,Low,Up),
4938 (var(Low) -> true ; var(Up) -> true % better keep this symbolic as we may be able to do constraint propagation
4939 ; KeepIntervals=keep_intervals(Size) -> Up-Low >= Size
4940 ),
4941 !, % TO DO: see if we should do this check in try_expand_and_convert_to_avl above instead
4942 Res=CS.
4943 try_expand_and_convert_to_avl_with_check(CS,Res,_,Origin) :-
4944 get_card_for_specific_custom_set(CS,Size), % TO DO: avoid checking for special closures twice (below in try_expand_and_convert_to_avl ?)
4945 !,
4946 try_expconv_to_avl_with_size(Size,CS,Res,Origin).
4947 try_expand_and_convert_to_avl_with_check(CS,Res,_,Origin) :-
4948 try_expand_and_convert_to_avl(CS,Res,Origin,'').
4949
4950 try_expconv_to_avl_with_size(inf,CS,Res,Origin) :- !,
4951 debug_format(9,'### Not expanding infinite set~n### ORIGIN: ~w~n',[Origin]),
4952 Res=CS.
4953 try_expconv_to_avl_with_size(inf_overflow,CS,Res,Origin) :- !,
4954 debug_format(9,'### Not expanding very large set~n### ORIGIN: ~w~n',[Origin]),
4955 Res=CS.
4956 try_expconv_to_avl_with_size(Size,CS,Res,Origin) :- Size>=10000000, !,
4957 /* will probably never terminate */
4958 debug_format(9,'### Not expanding very large set with cardinality ~w~n### ORIGIN: ~w~n',[Size,Origin]),
4959 Res=CS.
4960 try_expconv_to_avl_with_size(Size,CS,Res,Origin) :- Size>=50000, !,
4961 print('### WARNING: expanding very large comprehension set, size = '), print(Size),nl,
4962 print('### ORIGIN: '), print(Origin),nl,
4963 try_expand_and_convert_to_avl(CS,Res,Origin,'').
4964 try_expconv_to_avl_with_size(_Size,CS,Res,Origin) :-
4965 try_expand_and_convert_to_avl(CS,Res,Origin,'').
4966
4967 /* underlying assumption for var case: if G is a global set: we get back the
4968 global_set tag immediately: no need to use when to wait;
4969 better: ensure that b_compute_expression always returns a nonvar term */
4970
4971
4972 :- assert_must_succeed((custom_explicit_sets:try_expand_custom_set(closure([xx],[integer],b(falsity,pred,[])),R),R = [])).
4973 :- assert_must_succeed((custom_explicit_sets:test_closure(X),custom_explicit_sets:expand_custom_set(X,EX),
4974 EX = [(fd(1,'Name'),_),(fd(3,'Name'),_)])).
4975
4976 test_closure(X) :- X = closure(['_zzzz_binary'],[couple(global('Name'),set(global('Name')))],
4977 b(member(b(identifier('_zzzz_binary'),couple(global('Name'),set(global('Name'))),[generated]),
4978 b(cartesian_product(b(value([fd(1,'Name'),fd(3,'Name')]),set(global('Name')),[]),
4979 b(value([[fd(2,'Name'),fd(3,'Name')]]),set(set(global('Name'))),[])),
4980 set(couple(global('Name'),set(global('Name')))),[])),pred,[])).
4981
4982
4983 /* --------- */
4984 /* ELEMENT_OF */
4985 /* --------- */
4986
4987
4988 /* A function that instantiates last argument when membership test can be decided */
4989
4990 membership_custom_set(CS,X,R) :- print(warning_deprecated_non_wf_version(CS,X,R)),nl,
4991 membership_custom_set_wf(CS,X,R,_WF).
4992
4993 ?membership_custom_set_wf(avl_set(A),X,R,WF) :- !, membership_avl_set_wf(A,X,R,WF).
4994 membership_custom_set_wf(freetype(_GS),_X,R,_WF) :- !, R=pred_true. % should be covered by clause above
4995 membership_custom_set_wf(CS,X,R,WF) :- R==pred_true,!, element_of_custom_set_wf(X,CS,WF).
4996 membership_custom_set_wf(CS,X,R,WF) :- R==pred_false,!, not_element_of_custom_set_wf(X,CS,WF).
4997 membership_custom_set_wf(CS,_X,R,_WF) :-
4998 is_definitely_maximal_set(CS),!,
4999 R=pred_true.
5000 membership_custom_set_wf(closure(Par,Types,Body),X,R,WF) :- !,
5001 ? closure_membership_wf(X,Par,Types,Body,R,WF).
5002 %membership_custom_set_wf(CS,X,R,WF) :- is_one_element_custom_set(CS,Y),!, % only succeeds for AVL
5003 % kernel_equality:equality_objects_wf_no_enumr(X,Y,R,WF).
5004 membership_custom_set_wf(global_set(GS),X,R,WF) :- !,
5005 membership_global_set(GS,X,R,WF).
5006 membership_custom_set_wf(CS,X,R,WF) :-
5007 add_internal_error('Illegal custom set: ',membership_custom_set_wf(CS,X,R,WF)),fail.
5008
5009 membership_avl_set_wf(A,X,R,WF) :- R==pred_true,!, element_of_avl_set_wf(A,X,WF).
5010 membership_avl_set_wf(A,X,R,WF) :- R==pred_false,!, not_element_of_custom_set_wf(X,avl_set(A),WF).
5011 membership_avl_set_wf(A,X,R,WF) :- is_one_element_avl(A,Y),!,
5012 ? kernel_equality:equality_objects_wf_no_enum(X,Y,R,WF).
5013 membership_avl_set_wf(A,_X,R,_WF) :-
5014 quick_definitely_maximal_set_avl(A),!,
5015 R=pred_true.
5016 membership_avl_set_wf(A,X,R,WF) :- reify_avl_membership(A,X,R,FullReification),
5017 (FullReification==true
5018 -> true %print_term_summary(full_reification(A,X,R)),nl,nl %% did slow down e.g. Bosch Deadlock v9, seems no longer the case
5019 ? ; when((ground(X);nonvar(R)),membership_avl_set_wf2(A,X,R,WF))).
5020
5021 ?membership_avl_set_wf2(A,X,R,WF) :- R==pred_true,!, element_of_avl_set_wf(A,X,WF).
5022 membership_avl_set_wf2(A,X,R,WF) :- R==pred_false,!, not_element_of_custom_set_wf(X,avl_set(A),WF).
5023 membership_avl_set_wf2(AVL,X,R,_WF) :-
5024 ground_element_can_be_added_or_removed_to_avl(X), !,
5025 ? (safe_avl_member(X,AVL) %safe_avl_member_ground(X,AVL)
5026 -> R=pred_true ; R=pred_false).
5027 membership_avl_set_wf2(AVL,X,Res,WF) :- % X is ground but cannot be added
5028 (Res \== pred_false, element_of_avl_set_wf(AVL,X,WF), Res=pred_true
5029 ;
5030 Res \== pred_true, not_element_of_custom_set_wf(X,avl_set(AVL),WF), Res=pred_false).
5031
5032 membership_global_set(GS,_X,R,_WF) :- is_maximal_global_set(GS),!,
5033 R=pred_true.
5034 membership_global_set(GS,X,R,WF) :- ground(X),!,
5035 (element_of_global_set_wf(X,GS,WF) -> R=pred_true ; R=pred_false).
5036 membership_global_set(GS,X,R,_WF) :- get_integer_set_interval(GS,Low,Up),!,
5037 membership_interval(X,Low,Up,R).
5038 membership_global_set(GS,X,R,WF) :- % this case should probably never apply
5039 (GS=='FLOAT' -> true % currently it actually is also treated like REAL
5040 ; print(uncovered_membership(GS,X,R,WF)),nl),
5041 when(ground(X), (element_of_global_set_wf(X,GS,WF) -> R=pred_true ; R=pred_false)).
5042
5043 membership_interval(X,Low,Up,Res) :- nonvar(Up),Up=inf,!,X=int(IX),
5044 b_interpreter_check:check_arithmetic_operator('<=',Low,IX,Res).
5045 membership_interval(X,Low,Up,Res) :- kernel_equality:in_nat_range_test(X,int(Low),int(Up),Res).
5046
5047 :- use_module(bool_pred).
5048 closure_membership_wf(X,[ZZZZ],[integer],CondClosure,Res,_WF) :-
5049 is_interval_closure_body(CondClosure,ZZZZ,LOW,UP),!,
5050 kernel_equality:in_nat_range_test(X,int(LOW),int(UP),Res).
5051 % TO DO: deal with open intervals 0..inf ...
5052 closure_membership_wf(X,Par,Types,Body,Res,WF) :-
5053 is_member_closure(Par,Types,Body,_Type,VAL),
5054 (VAL=value(_) ; VAL = cartesian_product(b(value(A),_,_),b(value(B),_,_))),!,
5055 (VAL=value(Set)
5056 -> kernel_objects:membership_test_wf(Set,X,Res,WF)
5057 ? ; kernel_equality:cartesian_pair_test_wf(X,A,B,Res,WF)).
5058 closure_membership_wf(X,Par,Typ,Body,Res,WF) :-
5059 is_not_member_closure(Par,Typ,Body,_Type,value(Set)),!,
5060 bool_pred:negate(ResXSet,Res), % was kernel_equality:inv_mem_obj(ResXSet,Res),
5061 kernel_objects:membership_test_wf(Set,X,ResXSet,WF).
5062 % TO DO: if closure = POW closure -> translate into subset_test pow_subset
5063 % TO DO: support a few other closures related to symbolic unary/binary operators: closure1, POW(..), ... ?
5064 % TO DO: expand if set is small
5065 closure_membership_wf(X,Par,Types,Body,Res,WF) :- ground_value(X),!,
5066 closure_membership_ground_wf(X,closure(Par,Types,Body),Res,WF).
5067 closure_membership_wf(X,Par,Types,Body,Res,WF) :-
5068 CS = closure(Par,Types,Body),
5069 is_small_specific_custom_set(CS,100),
5070 try_expand_and_convert_to_avl_wf(CS,Expanded,closure_membership_wf,'',WF),
5071 nonvar(Expanded), Expanded=avl_set(_),
5072 !,
5073 membership_custom_set_wf(Expanded,X,Res,WF).
5074 closure_membership_wf(X,Par,Types,Body,Res,WF) :-
5075 Body \= b(member(_,_),_,_), % otherwise we may have an infinite loop; b_check_boolean_expression will generate a closure which will call closure_membership_wf again; TO DO: refine to allow certain memberships to go through
5076 get_texpr_info(Body,BodyInfo),
5077 \+ member(prob_annotation(recursive(_RID)),BodyInfo), % otherwise we can get errors as recursive identifier _RID needs to be added to local state ! (test 1151 fails otherwise)
5078 % TO DO: add recursive parameter below in set_up_typed_localstate2; + in which other circumstances do we need to set up recursion identifier !
5079 % Try reifiyng the body
5080 NegationContext=positive,
5081 copy_wf_start(WF,closure_membership_wf,CWF),
5082 b_interpreter:set_up_typed_localstate2(Par,Types,BodyInfo,ParValues,TypedVals,[],State,NegationContext),
5083 %couplise_list(Types,XType),
5084 convert_list_into_pairs(ParValues,SingleParValue),
5085 kernel_objects:equal_object(X,SingleParValue,closure_membership_wf),
5086 b_interpreter_check:b_check_boolean_expression(Body,[],State,CWF,PredRes),
5087 !,
5088 (debug_level_active_for(19) -> print('REIFICATION of closure: '), translate:print_bexpr(Body),nl, print(pred_res(X,PredRes)),nl ; true),
5089 b_enumerate:b_tighter_enumerate_all_values(TypedVals,WF), % not necessary ?? as X should get enumerated
5090 Res=PredRes,
5091 copy_wf_finish(WF,CWF).
5092 closure_membership_wf(X,Par,Types,Body,Res,WF) :-
5093 when( (ground(X);nonvar(Res)), %%
5094 % used to be ground(X), % with (ground(X);nonvar(Res)), test 292 failed {x,t|t : BOOL & (x : POW(1024 .. 1025) & bool(x : POW(NATURAL1)) = t)} = {{} |-> TRUE,{1024} |-> TRUE,{1024,1025} |-> TRUE,{1025} |-> TRUE} and test 1088 failed
5095 closure_membership_ground_wf(X,closure(Par,Types,Body),Res,WF)).
5096
5097 closure_membership_ground_wf(X,CS,Res,WF) :- nonvar(Res),!,
5098 % this optimization is checked in test 1452
5099 ? (Res==pred_true -> element_of_custom_set_wf(X,CS,WF) ; not_element_of_custom_set_wf(X,CS,WF)).
5100 closure_membership_ground_wf(X,CS,Res,WF) :-
5101 % to ensure that we leave no choice point behind we have to force full evaluation of element/not_element calls:
5102 % hence we do not call element_of_custom_set_wf or not_element_of_custom_set_wf below !!
5103 kernel_waitflags:get_idle_wait_flag(closure_membership_ground_wf,WF,LWF), % enable other triggered co-routines to fire first; some maybe much more efficient to deal with than closure expansion;
5104 % used to be important for test 1146, but this is no longer the case
5105 %term_variables(CS,Vars),print(closure_membership_ground_wf_aux(LWF,vars(Vars),CS)),nl,
5106 ground_value_check(CS,CSGr),
5107 %when((nonvar(LWF),(nonvar(CSGr);nonvar(Res))),closure_membership_ground_wf_aux(X,CS,Res)).
5108 block_closure_membership_ground_wf_aux(X,CS,Res,CSGr,LWF,WF). % Note: wrong block in commit 332cb17487017d819e9140427b1017a3045b3685 caused problem for test 1162
5109
5110 :- block block_closure_membership_ground_wf_aux(?,?,?,?,-,?),
5111 block_closure_membership_ground_wf_aux(?,?,-,-,?,?).
5112 block_closure_membership_ground_wf_aux(X,CS,Res, _,_,WF) :-
5113 ? closure_membership_ground_wf_aux(X,CS,Res,WF).
5114
5115 % X & CS are ground or Res is known
5116 closure_membership_ground_wf_aux(X,CS,Res,WF) :- Res==pred_true,!,
5117 ? element_of_custom_set_wf(X,CS,WF).
5118 closure_membership_ground_wf_aux(X,CS,Res,WF) :- Res==pred_false,!,
5119 not_element_of_custom_set_wf(X,CS,WF).
5120 closure_membership_ground_wf_aux(X,CS,Res,_WF) :-
5121 % we know that X is a ground value and CS is ground: we can determine completely whether X is element of CS or not
5122 ? if(element_of_custom_set(X,CS),Res=pred_true, Res=pred_false).
5123 /* used to be: (Res \== pred_false, element_of_custom_set(X,CS), Res=pred_true
5124 ; Res \== pred_true, not_element_of_custom_set(X,CS), Res=pred_false)).
5125 */
5126
5127
5128
5129 :- use_module(kernel_objects,[element_of_global_set/2,element_of_global_set_wf/3]).
5130 element_of_custom_set_wf(X,CS,WF) :-
5131 ? element_of_custom_set_wf2(CS,X,WF). %, print(check_ok(X)),nl.
5132
5133 element_of_custom_set_wf2(node(A,B,C,D,E),X,WF) :-
5134 add_internal_error('Unwrapped avl_set: ',element_of_custom_set_wf2(node(A,B,C,D,E),X,WF)),fail.
5135 element_of_custom_set_wf2(global_set(GS),X,WF) :- element_of_global_set_wf(X,GS,WF).
5136 element_of_custom_set_wf2(freetype(ID),X,WF) :-
5137 (is_maximal_freetype(ID) -> true
5138 ; add_internal_error('Uncovered case: ',element_of_custom_set_wf2(freetype(ID),X,WF))
5139 ). % we assume freetypes to be maximal !
5140 ?element_of_custom_set_wf2(avl_set(AVL),X,WF) :- element_of_avl_set_wf(AVL,X,WF).
5141 element_of_custom_set_wf2(closure(Parameters,PT,Cond),X,WF) :-
5142 ? element_of_closure(X,Parameters,PT,Cond,WF).
5143
5144 element_of_avl_set_wf(node(Y,_,_,empty,empty),X,WF) :- !,
5145 ? kernel_objects:equal_object_wf(X,Y,element_of_custom_set_wf2,WF).
5146 ?element_of_avl_set_wf(AVL,X,_WF) :- ground_value(X),!, safe_avl_member(X,AVL). %safe_avl_member_ground(X,AVL).
5147 element_of_avl_set_wf(AVL,X,WF) :-
5148 avl_approximate_size(AVL,10,ApproxSize),
5149 ? element_of_avl_set_wf(AVL,ApproxSize,X,WF).
5150
5151 :- use_module(clpfd_tables).
5152
5153 element_of_avl_set_wf(AVL,ApproxSize,X,WF) :-
5154 % first check if worthwhile to attempt table treatment
5155 % after fixing table/2 bug runtimes have slowed down and test 1753 became much slower
5156 % for test 1753 a threshold of < 63 would be ideal; but test 1716 requires size 91
5157 % TODO: re-evaluate when SICStus 4.8 available
5158 preferences:preference(use_clpfd_solver,true),
5159 preferences:preference(solver_strength,SS),
5160 ApproxSize < 100+SS,
5161 (var(X) -> true
5162 ; X = (X1,_X2) -> (ground_value(X1) -> ApproxSize < 10+SS ; true)
5163 ; X=rec(_) -> true
5164 %; X=int(_) -> true ; X=fd(_,_) -> true % for scalar values we already use in_fd_value_list_wf via avl_fd_value_check
5165 ),
5166 can_translate_avl_to_table(AVL,SkeletonType,WF),
5167 !,
5168 ? check_element_of_avl_with_table(X,SkeletonType,AVL,WF).
5169 element_of_avl_set_wf(AVL,ApproxSize,X,WF) :-
5170 ? propagate_avl_element_information(X,AVL,ApproxSize,WF), %translate:translate_bvalue(avl_set(AVL),SS),
5171 get_bounded_wait_flag(ApproxSize,element_of_avl(X),WF,WF1),
5172 ? element_of_avl_set_wf3(X,AVL,ApproxSize,WF1,WF).
5173
5174
5175 % compute an approximate size (small sets are computed exactly)
5176 avl_approximate_size(AVL,Size) :- avl_approximate_size(AVL,10,Size).
5177
5178 avl_approximate_size(AVL,HeightBound,Size) :- var(AVL),!,
5179 add_internal_error('AVL Set is variable: ', avl_approximate_size(AVL,HeightBound,Size)),
5180 Size=1000000.
5181 avl_approximate_size(AVL,HeightBound,Size) :- % when the AVL gets too large; not so important that we have a precise estimation anyway
5182 % so: save some time and just compute height
5183 avl_height(AVL,Height),
5184 (Height>HeightBound
5185 -> Size is floor(2**Height-1)
5186 ; avl_size(AVL,Size)).
5187
5188 :- block element_of_avl_set_wf3(-,?,?,-,?).
5189 element_of_avl_set_wf3(X,AVL,_ApproxSize,_WF1,_WF) :- var(X), !,
5190 ? safe_avl_member(X,AVL).
5191 % TO DO: if randomise_enumeration_order is true then choose elements in random order
5192 element_of_avl_set_wf3((X,Y),AVL,ApproxSize,WF1,WF) :- !,
5193 ground_value_check(X,GrX), % as soon as X is ground we can efficiently find possible values for Y
5194 % TODO: it could be that X is also a pair or a record with first field known;
5195 % see flexible_decompose_index and safe_flex_avl_member_default_wf
5196 ? block_couple_element_of_avl_set_grX_wf1(X,Y,AVL,ApproxSize,GrX,WF1,WF).
5197 element_of_avl_set_wf3(X,AVL,_ApproxSize,WF1,_WF) :-
5198 ground_value_check(X,GrX),
5199 ? safe_avl_member_block(X,AVL,GrX,WF1).
5200
5201 :- block safe_avl_member_block(?,?,-,-).
5202 safe_avl_member_block(X,AVL,_,_) :-
5203 ? safe_avl_member(X,AVL).
5204
5205 % ---------------------------------------------------
5206
5207
5208 :- block block_couple_element_of_avl_set_grX_wf1(?, - ,?,?,-,-,?).
5209 block_couple_element_of_avl_set_grX_wf1(X,Y,AVL,ApproxSize,GrX,WF1,WF) :-
5210 var(GrX), var(WF1),
5211 !,
5212 % we know the result Y but not yet fully the input value X
5213 (ApproxSize < 129 % TO DO: improve this; unify with inverse_apply_ok(Y,X,AVL,ApproxSize) ?
5214 -> ground_value_check(Y,GrY) % wait until Y is fully known
5215 ; (preference(solver_strength,SS), ApproxSize < 129+SS)
5216 -> ground_value_check(Y,GrY)
5217 % TO DO: we could look at avl_min and avl_max and estimate spread of range keys
5218 ; cond_perfmessage([data_validation_mode/false],no_inverse_avl_lookup(ApproxSize,Y)) % do not bind GrY; we wait until GrX or WF1 is bound
5219 ),
5220 ? block_couple_element_of_avl_set_grX_grY_wf1(X,Y,AVL,ApproxSize,GrX,GrY,WF1,WF).
5221 block_couple_element_of_avl_set_grX_wf1(X,Y,AVL,_ApproxSize,GrX,WF1,WF) :-
5222 ? couple_element_of_avl_set(X,Y,AVL,GrX,WF1,WF).
5223
5224 :- block block_couple_element_of_avl_set_grX_grY_wf1(?,?,?,?, -,-,-,?).
5225 block_couple_element_of_avl_set_grX_grY_wf1(X,Y,AVL,_ApproxSize, GrX,_GrY,WF1,WF) :-
5226 var(GrX), var(WF1), % i.e., Y is known
5227 % we know the result Y but not yet fully the input value X
5228 %inverse_apply_ok(Y,X,AVL,ApproxSize),
5229 !,
5230 inverse_get_possible_values(X,Y,AVL,Res),
5231 Res = avl_set(InvAVL),
5232 ? element_of_avl_set_wf(InvAVL,X,WF).
5233 block_couple_element_of_avl_set_grX_grY_wf1(X,Y,AVL,_ApproxSize,GrX,_GrY,WF1,WF) :-
5234 ? couple_element_of_avl_set(X,Y,AVL,GrX,WF1,WF).
5235
5236
5237 % special treatment for relations: if the first component is known: then we can check how many images there are
5238 couple_element_of_avl_set(X,Y,AVL,GrX,WF1,WF) :-
5239 nonvar(WF1), var(GrX), %\+ground(X),
5240 !,
5241 ? safe_flex_avl_member_default_wf((X,Y),AVL,WF).
5242 couple_element_of_avl_set(X,Y,AVLRelation,_GrX,_,WF) :- % X must be ground
5243 get_template(Y,TY,_ToUnifyAfter), % was copy_term(Y,CY) but could cause issues with closures with variables
5244 copy_term(TY,CY), % avoid that we instantiate Y and trigger co-routines
5245 findall(CY,avl_member_pair_arg1_ground(X,CY,AVLRelation),Images),
5246 Images \= [],
5247 construct_avl_from_lists_wf(Images,AVL,WF),
5248 ? element_of_custom_set_wf2(AVL,Y,WF). % will set up waitflag if necessary
5249
5250 % a version of safe_avl_member_default_wf which tries to flexibly find a usable index into the AVL first
5251 % it checks if a value can be decomposed into a ground index and the rest of a value
5252 % it also works for records indexing on first field
5253 % see tests 2351, 2353, 1966;
5254 safe_flex_avl_member_default_wf(Element,AVL,WF) :-
5255 \+ avl_height_less_than(AVL,4), % AVL tree large enough for indexing; check not necessary?; see test 2287
5256 flexible_decompose_index(Element,Key,Rest1,Path),!, % TODO: if fails: perfmessage
5257 % see Machine_Nov25/RVF428_MSTE_FOLIO.mch where this optimisation is very useful
5258 ? avl_fetch_with_flexible_index(Key, Path, AVL ,Rest2),
5259 ? kernel_objects:equal_object_wf(Rest1,Rest2,avl_fetch_with_flexible_index,WF).
5260 safe_flex_avl_member_default_wf(Element,AVL,WF) :-
5261 ? safe_avl_member_default_wf(Element,AVL,WF).
5262
5263 % set Res -> pred_true or pred_false if membership can be decided early
5264 % interval closures already dealt with by closure_membership
5265 % maximal sets are also already dealt with by membership_custom_set
5266 reify_avl_membership(AVL,Element,Res,FullReification) :-
5267 is_avl_simple_set(AVL,Type),
5268 preferences:preference(use_clpfd_solver,true), % to do: require maybe only for integer type !?
5269 \+ ground_value(Element),
5270 !,
5271 reify_avl_mem2(Type,Element,AVL,Res,FullReification).
5272 reify_avl_membership(_,_,_,false).
5273
5274
5275 is_avl_simple_set(node(El,_True,_,_,_),Type) :- simple_type(El,Type).
5276 simple_type(int(_),integer).
5277 simple_type(fd(_,GS),global(GS)).
5278
5279
5280 reify_avl_mem2(integer,int(El),AVL,Res,FullReification) :-
5281 avl_min(AVL,int(Min)), avl_max(AVL,int(Max)),
5282 (reify_integer_avl_mem(AVL,Min,Max) % reify if AVL small enough
5283 -> avl_domain(AVL,R),project_avl_domain_on_fd(R,FDList),
5284 clpfd_reify_inlist(El,FDList,FDRes,Posted),
5285 propagate_fd_membership(FDRes,Res,inlist(El,FDList)),
5286 FullReification=Posted
5287 ; clpfd_interface:try_post_constraint((El in Min..Max) #<=> FDRes),
5288 propagate_not_membership(FDRes,Res,int(El,Min,Max)),
5289 FullReification=false
5290 ).
5291 % this could also be enabled with CLPFD = FALSE ?? no overflows are possible
5292 reify_avl_mem2(global(GS),fd(El,GS),AVL,Res,FullReification) :-
5293 avl_domain(AVL,R),project_avl_domain_on_fd(R,FDList),
5294 b_global_sets:b_get_fd_type_bounds(GS,Low,Up),
5295 (is_full_fdlist(FDList,Low,Up)
5296 -> Res=pred_true, % all the values are in the list; it must be a member
5297 % normally this should also be detected by clpfd_reify_inlist, unless no constraint was set up for El
5298 % it seems to have an effect for test 426: probcli examples/EventBPrologPackages/SSF/Bepi_Soton/M1_mch.eventb -cbc all -strict -p CLPFD TRUE -p SMT TRUE -strict -p STRICT_RAISE_WARNINGS TRUE
5299 FullReification=true
5300 ; clpfd_reify_inlist(El,FDList,FDRes,Posted),
5301 propagate_fd_membership(FDRes,Res,inlist(El,FDList)),
5302 FullReification=Posted
5303 ).
5304 %reify_avl_mem2(global(GS),fd(El,GS),AVL,Res) :-
5305 % avl_min(AVL,fd(Min,GS)), avl_max(AVL,fd(Max,GS)),
5306 % clpfd_interface:try_post_constraint((El in Min..Max) #<=> FDRes),
5307 % propagate_not_membership(FDRes,Res,fd(El,GS,Min,Max)).
5308
5309 % assumes list is sorted
5310 is_full_fdlist(List,Low,Up) :- integer(Up), is_full_fdlist2(List,Low,Up).
5311 is_full_fdlist2([],Low,Up) :- Low>Up.
5312 is_full_fdlist2([Low|T],Low,Up) :- L1 is Low+1, is_full_fdlist2(T,L1,Up).
5313
5314 % check if avl small enough to call clpfd_reify_inlist
5315 reify_integer_avl_mem(_AVL,Min,Max) :- MaxSizeM1 is Max-Min, MaxSizeM1 =< 20,!.
5316 reify_integer_avl_mem(AVL,_Min,_Max) :- avl_height_less_than_with_solver_strength(AVL,5).
5317
5318
5319
5320 project_avl_domain_on_fd([],[]).
5321 project_avl_domain_on_fd([H|T],[PH|PT]) :- project_avl_domain(H,PH), project_avl_domain_on_fd(T,PT).
5322 project_avl_domain(int(X),X).
5323 project_avl_domain(fd(X,_),X).
5324
5325
5326 :- block propagate_fd_membership(-,-,?).
5327 % if we make it propagate_fd_membership(-,-?) Bosch examples becomes much slower ?
5328 % Indeed: membership_custom_set will already force membership or non-membership !
5329 %propagate_fd_membership(X,M,Info) :- var(X),!, print(propagate_fd(X,M,Info)),nl, (M=pred_true ->X=1 ; X=0).
5330 propagate_fd_membership(1,pred_true,_Info).
5331 propagate_fd_membership(0,pred_false,_Info).
5332
5333 :- block propagate_not_membership(-,?,?).
5334 propagate_not_membership(1,_,_). % there could be elements in the interval which are not in the set
5335 propagate_not_membership(0,Res,_Info) :-
5336 Res=pred_false.
5337
5338 % -----------------
5339
5340 % fails if not possible to quickly compute approximate size
5341 quick_custom_explicit_set_approximate_size(V,_) :- var(V),!,fail.
5342 quick_custom_explicit_set_approximate_size(avl_set(AVL),Size) :- !,
5343 quick_avl_approximate_size(AVL,Size).
5344 quick_custom_explicit_set_approximate_size(CS,Size) :-
5345 card_for_specific_custom_set(CS,Size,Code),
5346 on_enumeration_warning(call(Code),fail),
5347 atomic(Size). % inf or number; sometimes card_for_specific_custom_set can return a variable
5348
5349 :- use_module(clpfd_lists,[try_get_fd_value_list/4, get_fd_value/3, in_fd_value_list_wf/4]).
5350 % a membership propagation, but only done if it can be done quickly
5351
5352
5353 % quick_propagation_element_information(Set, Element, WF, PossiblyCompiledSet)
5354 % use last element for next iteration if you call quick_propagation_element_information in a loop
5355 :- block quick_propagation_element_information(-,?,?,?).
5356 quick_propagation_element_information(Set,_El,_,R) :-
5357 preferences:preference(use_clpfd_solver,false),
5358 !, R=Set.
5359 quick_propagation_element_information(avl_set(AVL),Element,WF,NewSet) :- !,
5360 quick_avl_approximate_size(AVL,Size),
5361 NewSet=avl_set_with_size(AVL,Size),
5362 propagate_avl_element_information_direct(Element,AVL,Size,WF).
5363 quick_propagation_element_information(avl_set_with_size(AVL,Size),Element,WF,NewSet) :- !,
5364 NewSet = avl_set_with_size(AVL,Size),
5365 propagate_avl_element_information_direct(Element,AVL,Size,WF).
5366 quick_propagation_element_information(closure(P,T,B),Element,WF,NewSet) :- !,
5367 NewSet = closure(P,T,B),
5368 ? element_of_closure(Element,P,T,B,WF).
5369 quick_propagation_element_information(fd_value_list(FDList,GroundList,Type),El,WF,NewSet) :- !,
5370 NewSet = fd_value_list(FDList,GroundList,Type),
5371 get_fd_value(Type,El,ElFD),
5372 in_fd_value_list_wf(GroundList,ElFD,FDList,WF).
5373 quick_propagation_element_information(Set,El,WF,NewSet) :-
5374 ? try_get_fd_value_list(Set,Type,FDList,GroundList),!,
5375 FDList \= [], % if list is empty membership fails
5376 NewSet = fd_value_list(FDList,GroundList,Type),
5377 % clpfd_inlist requires list of integers as second argument
5378 ? get_fd_value(Type,El,ElFD),
5379 % We could apply filter_non_matching_elements here
5380 in_fd_value_list_wf(GroundList,ElFD,FDList,WF).
5381 quick_propagation_element_information(Set,_,_,Set).
5382
5383 % -----------------
5384
5385 % infer information about an element of an AVL set
5386 propagate_avl_element_information(Element,AVL,Size,WF) :-
5387 (preferences:preference(use_clpfd_solver,true)
5388 ? -> propagate_avl_element_information_direct(Element,AVL,Size,WF)
5389 ; true).
5390
5391 propagate_avl_element_information_direct(Element,AVL,Size,WF) :-
5392 (Size<100 -> %30 which magic constant to use here; use larger value in SMT mode ?
5393 ? propagate_avl_element_information_small(Element,AVL,WF)
5394 ; is_avl_fd_index_set(AVL,Type) ->
5395 propagate_avl_element_information_large(Type,Element,AVL),
5396 (Size < 4000, nonvar(Element), Element = (_,_) % another magic constant
5397 -> Prio is Size // 60,
5398 get_wait_flag(Prio,propagate_avl_element_information(Element),WF,LWF),
5399 propagate_avl_el_large_block(Element,AVL,WF,LWF) % will do precise propagation
5400 ; true)
5401 ; true).
5402 % TO DO: we could call in_nat_range_wf; this way it would also work in non-CLPFD mode
5403
5404 :- block propagate_avl_el_large_block(?,?,?,-).
5405 propagate_avl_el_large_block((A,B),_,_,_) :-
5406 (ground(A); ground_value(B)), % in first: case we will apply AVL set ; in second case probably no benefit as propagate_avl_element_information_large already propagated first element
5407 !.
5408 propagate_avl_el_large_block(Element,AVL,WF,_LWF) :-
5409 % TO DO: maybe look if we should not use clpfd_list, but only upper & lower bound
5410 ? propagate_avl_element_information_small(Element,AVL,WF). % will do precise propagation.
5411
5412 :- use_module(clpfd_lists,[avl_fd_value_check/4]).
5413 :- use_module(clpfd_interface,[catch_and_ignore_clpfd_overflow/2]).
5414 propagate_avl_element_information_small(Element,AVL,WF) :-
5415 ? catch_and_ignore_clpfd_overflow(propagate_avl_element_information_small, % relevant test e.g. 1708 (with used_ids_defined_by_equality)
5416 avl_fd_value_check(AVL,Element,WF,_FullyChecked)).
5417
5418 propagate_avl_element_information_large(Type,El,AVL) :-
5419 avl_min(AVL,Min), avl_max(AVL,Max),
5420 % if Size small enough and smaller than Max-Min we call clpfd_inlist on domain
5421 % Note: overflows should be caught below; we could check that Min/Max are within CLPFD range
5422 couple_prj1_in_range(Type,El,Min,Max).
5423
5424 couple_prj1_in_range(integer,int(El),int(Min),int(Max)) :- clpfd_interface:clpfd_inrange(El,Min,Max).
5425 couple_prj1_in_range(global(GS),fd(El,GS),fd(Min,GS),fd(Max,GS)) :- clpfd_interface:clpfd_inrange(El,Min,Max).
5426 couple_prj1_in_range(couple_prj1(T),(El,_),(Min,_),(Max,_)) :- couple_prj1_in_range(T,El,Min,Max).
5427 couple_prj1_in_range(rec_first_field(Name,T),rec([field(Name,El)|TF]),
5428 rec([field(Name,Min)|TMin]),rec([field(Name,Max)|_])) :-
5429 (var(TF)
5430 -> copy_field_names(TMin,TF) % if Fields not yet instantiated: copy over all fields
5431 ; true),
5432 couple_prj1_in_range(T,El,Min,Max).
5433
5434 copy_field_names([],[]).
5435 copy_field_names([field(N,_)|T],[field(N,_)|CT]) :- copy_field_names(T,CT).
5436
5437 % check if the first component of the AVL elements of a type such that we can propagate FD information
5438 is_avl_fd_index_set(node(El,_True,_,_,_),Type) :-
5439 simple_index_type(El,Type).
5440 simple_index_type((El,_),couple_prj1(T)) :- simple_index_type(El,T).
5441 simple_index_type(int(_),integer).
5442 simple_index_type(fd(_,GS),global(GS)).
5443 simple_index_type(rec(Fields),rec_first_field(Name,T)) :- nonvar(Fields),
5444 Fields = [field(Name,El)|_],
5445 simple_index_type(El,T).
5446 %simple_index_type((int(_),_),couple_integer).
5447 %simple_index_type(((int(_),_),_),couple_couple_integer).
5448 %simple_index_type((fd(_,GS),_),couple_global(GS)).
5449
5450
5451 /* avoid instantiating non-normalised with normalised values leading to failure */
5452 :- assert_must_succeed((X=(fd(1,'Name'),fd(2,'Name')), A=node(X,true,0,empty,empty),
5453 custom_explicit_sets:safe_avl_member(X,A) )).
5454
5455 ?safe_avl_member(X,AVL) :- var(X), !, my_avl_member(X,AVL).
5456 %safe_avl_member(Value,AVL) :- decompose_index(Value,Key,RestVal), avl_fetch_indexed(Value,Key,RestVal,AVL).
5457 %safe_avl_member(X,AVL) :- ground_value(X), convert_to_avl_inside_set(X,AX), !, avl_fetch(AX,AVL).
5458 ?safe_avl_member(X,AVL) :- safe_flex_avl_member_default_wf(X,AVL,no_wf_available).
5459
5460
5461 % a version of safe_avl_member where the first argument is guaranteed to be ground
5462 % somehow using this seems to slow-down evaluation for vesg_Dec12; Caching ??
5463 %safe_avl_member_ground(X,AVL) :-
5464 % convert_to_avl_inside_set(X,AX), !, avl_fetch(AX,AVL).
5465 %safe_avl_member_ground((X,Y),AVL) :- !, avl_member_pair_arg1_ground(X,Y,AVL).
5466 %safe_avl_member_ground(X,AVL) :- safe_avl_member_default_wf(X,AVL,no_wf_available).
5467
5468
5469 % can be used to try and lookup a function value without creating WD errors, ...
5470 % used in b_compiler to compile function applications
5471 try_apply_to_avl_set_wf(X,Y,AVL,WF) :- ground_value(X),
5472 avl_member_pair_arg1_ground_wf(X,Y,AVL,WF).
5473
5474 % we know X is ground; typically Y is a free variable and it is used within a findall:
5475 avl_member_pair_arg1_ground(X,Y,AVL) :-
5476 ? avl_member_pair_arg1_ground_wf(X,Y,AVL,no_wf_available).
5477
5478 avl_member_pair_arg1_ground_wf(X,Y,AVL,WF) :- convert_to_avl_inside_set(X,AX), !,
5479 get_template(Y,RY,ToUnifyAfter),
5480 ? avl_fetch_pair(AX,AVL,RY), % see flexible_decompose_index, safe_flex_avl_member_default_wf
5481 unify_after_wf(ToUnifyAfter,WF).
5482 avl_member_pair_arg1_ground_wf(X,Y,AVL,_WF) :-
5483 safe_avl_member_default((X,Y),AVL).
5484
5485 safe_avl_member_default(X,AVL) :-
5486 ? safe_avl_member_default_wf(X,AVL,no_wf_available).
5487 safe_avl_member_default_wf(X,AVL,WF) :- % statistics(runtime,_),
5488 get_template(X,Template,ToUnifyAfter),
5489 ? my_avl_member(Template,AVL),
5490 % statistics(runtime,[_,T2]), print(avl_member(Template,T2)),nl,
5491 ? unify_after_wf(ToUnifyAfter,WF). % kernel_objects:equal_object(Template,X)).
5492
5493 unify_after_wf([],_).
5494 ?unify_after_wf([A/B|T],WF) :- kernel_objects:equal_object_wf(A,B,unify_after,WF),
5495 ? unify_after_wf(T,WF).
5496
5497
5498
5499 get_template(A,R,ToUnifyAfter) :-
5500 (var(A) -> ToUnifyAfter=[A/R]
5501 ; get_template2(A,R,ToUnifyAfter) -> true
5502 ; add_internal_error('Could_not_get_template: ',get_template(A,R,_))).
5503
5504 get_template2((A,B),(TA,TB),ToUnifyAfter) :- get_template(A,TA,ToUnifyAfter1), get_template(B,TB,ToUnifyAfter2),
5505 append(ToUnifyAfter1,ToUnifyAfter2,ToUnifyAfter). % TO DO: use DifferenceLists / DCG
5506 get_template2(int(X),int(X),[]).
5507 get_template2(fd(A,B),fd(A,B),[]).
5508 get_template2([],[],[]).
5509 get_template2(pred_false /* bool_false */,pred_false /* bool_false */,[]).
5510 get_template2(pred_true /* bool_true */,pred_true /* bool_true */,[]).
5511 get_template2([H|T],R,ToUnifyAfter) :-
5512 (ground_value(H),ground_value(T)
5513 -> convert_to_avl_inside_set([H|T],R),ToUnifyAfter=[]
5514 ; ToUnifyAfter=[[H|T]/R]).
5515 % ; R=avl_set(A), ToUnifyAfter=[[H|T]/avl_set(A)]).
5516 get_template2(closure(P,T,B),R,[]) :- ground_value(closure(P,T,B)),
5517 expand_closure_to_avl_wf(P,T,B,R,no_wf_available),!.
5518 get_template2(closure(P,T,B),AVL_OR_EMPTY_OR_GS,[closure(P,T,B)/AVL_OR_EMPTY_OR_GS]). % closure could be empty or an infinite global set ?
5519 %get_template2(closure_x(_,_,_),_AVL_OR_EMPTY).
5520 get_template2(avl_set(A),avl_set(NA),[]) :- convert_to_avl_inside_set(avl_set(A),avl_set(NA)). % do we need to normalise here ??
5521 get_template2(string(X),string(X),[]).
5522 get_template2(term(X),term(X),[]).
5523 get_template2(freetype(X),R,[]) :- convert_to_avl_inside_set(freetype(X),R).
5524 get_template2(rec(Fields),rec(TFields),ToUnifyAfter) :- get_fields_template(Fields,TFields,ToUnifyAfter).
5525 get_template2(freeval(ID,Case,Value),freeval(ID,Case,TValue),ToUnifyAfter) :- get_template(Value,TValue,ToUnifyAfter).
5526 get_template2(global_set(GS),R,[]) :- convert_to_avl_inside_set(global_set(GS),R).
5527
5528
5529 get_fields_template(A,R,[rec(A)/rec(R)]) :- var(A),!.
5530 get_fields_template([],[],ToUnifyAfter) :- !, ToUnifyAfter=[].
5531 get_fields_template([field(Name,Val)|T],[field(Name,TVal)|TT],ToUnifyAfter) :- nonvar(Name),!,
5532 get_template(Val,TVal,ToUnifyAfter1),
5533 get_fields_template(T,TT,ToUnifyAfter2), append(ToUnifyAfter1,ToUnifyAfter2,ToUnifyAfter).
5534 get_fields_template(A,R,[rec(A)/rec(R)]).
5535
5536
5537 % succeed if we can decide membership of an avl_set on the spot
5538 quick_test_avl_membership(AVL,X,Res) :-
5539 element_can_be_added_or_removed_to_avl(X),
5540 convert_to_avl_inside_set(X,AX),
5541 (avl_fetch(AX,AVL) -> Res=pred_true ; Res=pred_false).
5542
5543 % ---------------------
5544
5545 % a dispatch predicate
5546 my_avl_member(Key,AVL) :-
5547 (preferences:preference(randomise_enumeration_order,true)
5548 ? -> random_avl_member(Key,AVL) ; avl_member_opt(Key,AVL)).
5549 :- use_module(library(random),[random/3]).
5550 ?random_avl_member(Key,AVL) :- avl_height(AVL,Height), H1 is Height+1, random_avl_member(Key,H1,AVL).
5551 % TO DO: make more intelligent; this is not really a very uniform way of randomly enumerating an AVL set (e.g., Key never occurs between L and R)
5552 random_avl_member(Key, H, node(K,_,_,L,R)) :-
5553 random(1,H,1), !, H1 is H-1,
5554 ? (Key=K ; random_avl_member(Key,H1,L) ; random_avl_member(Key,H1,R)).
5555 random_avl_member(Key, H, node(K,_,_,L,R)) :- random(1,3,1), !, H1 is H-1,
5556 ? (random_avl_member(Key,H1,L) ; random_avl_member(Key,H1,R) ; Key=K).
5557 random_avl_member(Key, H, node(K,_,_,L,R)) :- H1 is H-1,
5558 ? (random_avl_member(Key,H1,R) ; random_avl_member(Key,H1,L) ; Key=K).
5559
5560 % a variation of avl_member from library(avl) which tries to avoid leaving choice points behind
5561 avl_member_opt(Key, node(K,_,_,L,R)) :-
5562 ? ( avl_member_opt(Key, L)
5563 ; R=empty -> Key = K % avoid trailing choice_point
5564 ? ; (Key=K ; avl_member_opt(Key, R))
5565 ).
5566
5567 % ---------------------
5568
5569 :- use_module(kernel_objects,[check_element_of_wf/3,not_element_of_wf/3]).
5570 :- use_module(memoization,[element_of_memoization_closure/6]).
5571 element_of_special_closure(interval(LOW,UP),X,WF,_,_,_) :- !,
5572 %hit_profiler:add_profile_hit(in_nat_range(X,LOW,UP,CondClosure)),
5573 kernel_objects:in_nat_range_wf(X,int(LOW),int(UP),WF).
5574 element_of_special_closure(member_closure(_ID,_Type,VAL),X,WF,_,_,_) :-
5575 (VAL=value(_) ; VAL = cartesian_product(b(value(A),_,_),b(value(B),_,_))),!,
5576 %hit_profiler:add_profile_hit(in_member_closure(X,Par,Typ,Body)),
5577 (VAL=value(Set) -> check_element_of_wf(X,Set,WF)
5578 ; X=(XA,XB),
5579 ? kernel_objects:check_element_of_wf(XA,A,WF),
5580 ? kernel_objects:check_element_of_wf(XB,B,WF)).
5581 element_of_special_closure(not_member_closure(_ID,_Type,value(Set)),X,WF,_,_,_) :- !,
5582 %hit_profiler:add_profile_hit(in_not_member_closure(X,Par,Typ,Set)),
5583 not_element_of_wf(X,Set,WF).
5584 % we used to have to add enumerator, as not_element_of does not instantiate; e.g. relevant when doing X :: GS - {y}
5585 % This is no longer required
5586 % see test 6 (../prob_examples/public_examples/B/FeatureChecks/NotMemberCheck.mch)
5587 element_of_special_closure(recursive_special_closure(RId),X,WF,Parameters,PT,CondClosure) :- !,
5588 add_recursive_parameter(Parameters,PT,X,RId,CondClosure,NewParameters,NewPT,Value,WF),
5589 ? element_of_normal_closure(Value,NewParameters,NewPT,CondClosure,WF).
5590 element_of_special_closure(memoization_closure(MemoID),X,WF,P,T,B) :- !,
5591 element_of_memoization_closure(MemoID,X,WF,P,T,B).
5592 element_of_special_closure(_,X,WF,Parameters,PT,CondClosure) :-
5593 % none of the special cases above apply after all
5594 ? element_of_normal_closure(X,Parameters,PT,CondClosure,WF).
5595
5596 :- block element_of_closure(?,-,?,?,?), element_of_closure(?,?,?,-,?).
5597 % element_of_closure(X,Para,T,Body,_WF): check if X is a member of closure(Para,T,Body)
5598 element_of_closure(X,Parameters,PT,CondClosure,WF) :-
5599 is_special_closure(Parameters,PT,CondClosure, SpecialClosure),!,
5600 %print_term_summary(element_of_special_closure(SpecialClosure,X,WF,Parameters,PT,CondClosure)), trace_in_debug_mode,
5601 ? element_of_special_closure(SpecialClosure,X,WF,Parameters,PT,CondClosure).
5602 element_of_closure(X,Parameters,PT,CondClosure,WF) :-
5603 %print_term_summary(element_of_normal_closure(X,Parameters,PT,CondClosure,WF)), trace_in_debug_mode,
5604 ? element_of_normal_closure(X,Parameters,PT,CondClosure,WF).
5605 element_of_normal_closure(X,Parameters,PT,CondClosure,WF) :-
5606 %hit_profiler:add_profile_hit(element_of_closure(X,Parameters,PT,CondClosure)),
5607 same_length(Parameters,ParValues),
5608 convert_list_into_pairs(ParValues,X),
5609 ? b_test_closure_wo_enum(Parameters,PT,CondClosure,ParValues,WF).
5610
5611 :- use_module(store,[set_up_localstate/4]).
5612 :- block b_test_closure_wo_enum(?,?,-,?,?).
5613 b_test_closure_wo_enum(Parameters,ParameterTypes,ClosurePred,ParValues,WF) :-
5614 % same_length(Parameters,ParValues), % not necessary
5615 set_up_localstate(Parameters,ParValues,[],LocalState),
5616 ? b_enumerate:b_type_values_in_store(Parameters,ParameterTypes,LocalState),
5617 copy_wf_start(WF,b_test_closure_wo_enum(Parameters),InnerWF),
5618 % avoid that WF0 actions triggered before we have had a chance to traverse the expression
5619 ? b_test_boolean_expression(ClosurePred,LocalState,[],InnerWF),
5620 ? copy_wf_finish(WF,InnerWF).
5621
5622 % recursive identifier to list of parameters with body as value
5623 % NewValue is the Value that should be checked for membership in the adapted closure; it has one argument more
5624 add_recursive_parameter(Parameters,Types,Value,TId,CondClosure,NewParameters,NewTypes,NewValue,WF) :-
5625 TId = b(identifier(RId),SetType,_), % unification replaces: get_texpr_id(TId,RId), get_texpr_type(TId,SetType),
5626 append(Parameters,[RId],NewParameters),
5627 append(Types,[SetType],NewTypes),
5628 %tools_printing:print_term_summary(recursion(Value)),nl,
5629 % TO DO check some variant decreases
5630 (kernel_waitflags:pending_abort_error(WF)
5631 -> NewValue = (_,_) % prevent further expansion of recursion, in case WD error in recursive function
5632 % TO DO: detect whether WD error occurs within recursive function,
5633 % indeed, the expansion of the recursive function could be unrelated to WD error and be important to detect inconsistency which prevents WD error: e.g., 1/x=res & recfun(x) \= 0
5634 ,debug_println(19,stopping_recursion_due_to_wd_error)
5635 ; NewValue = (Value,closure(Parameters,Types,CondClosure))
5636 ).
5637
5638
5639 % same as above, but without a waitflag
5640 ?element_of_custom_set(X,CS) :- element_of_custom_set2(CS,X).
5641
5642 element_of_custom_set2(global_set(GS),X) :- !,element_of_global_set(X,GS).
5643 element_of_custom_set2(freetype(ID),_) :- is_maximal_freetype(ID),!. % freetypes are always maximal at the moment
5644 element_of_custom_set2(avl_set(AVL),X) :- !,
5645 ? safe_avl_member(X,AVL).
5646 element_of_custom_set2(CS,X) :- init_wait_flags(WF,[element_of_custom_set2]),
5647 ? element_of_custom_set_wf2(CS,X,WF),
5648 ? ground_wait_flags(WF).
5649
5650 % ---------------
5651
5652 % function application for closure
5653
5654 % same as check_element_of_wf but does not wait on Y:
5655 % should also work for relation ??
5656
5657 check_element_of_function_closure(X,Y,Parameters,PT,CondClosure,WF) :-
5658 is_special_closure(Parameters,PT,CondClosure, SpecialClosure),!, % this covers recursive closures
5659 ? element_of_special_closure(SpecialClosure,(X,Y),WF,Parameters,PT,CondClosure).
5660 check_element_of_function_closure(X,Y, P,T,ClosureBody, WF) :-
5661 % affects test 1312, unless we add s:seq(0..9) before calling num
5662 % a special rule which tries and avoid enumerating solutions to arguments of function application
5663 % usually a function application will either be given all arguments or maybe be used in inverse
5664 ? is_converted_lambda_closure(P,T,ClosureBody), %is_converted_non_recursive_lambda_closure(P,T,ClosureBody),
5665 % TO DO: also make this work for recursive closures by adding recursive args (see e.g. test 1302)
5666 is_lambda_closure(P,T,ClosureBody, OtherIDs, OtherTypes, DomainPred, EXPR),
5667 (debug:debug_level_active_for(4) ->
5668 print('Apply Fun : '), translate:print_bexpr(DomainPred), print(' | '), translate:print_bexpr(EXPR),nl,
5669 get_texpr_info(ClosureBody,I), print(info(I,WF)),nl,
5670 print_term_summary((X,Y)),nl %,trace
5671 ; true),
5672 !,
5673 % alternative: annotate X,Y as inner variable ?
5674 get_texpr_info(ClosureBody,BInfo),
5675 ? b_interpreter:set_up_typed_localstate2(OtherIDs,OtherTypes,BInfo,ParValues,_TypedVals,[],LocalState,positive),
5676 convert_list_into_pairs(ParValues,SingleParValue),
5677 ? kernel_objects:equal_object_wf(X,SingleParValue,check_element_of_function_closure,WF),
5678 (is_truth(DomainPred) -> true
5679 ; init_wait_flags(InnerWF,[check_element_of_function_closure]),
5680 %copy_wf01e_wait_flags(WF,InnerWF), % we could delay copying WF0 until after test_boolean_expression of DomainPred ?
5681 ? b_test_boolean_expression(DomainPred,LocalState,[],InnerWF),
5682 ? get_wait_flag0(WF,WF0), get_wait_flag0(InnerWF,WF0), % was: ground_wait_flag0(InnerWF), but this can result in inner WF0 being set when outer is not yet set; see test 1948
5683 ground_value_check(X,GrX),
5684 (nonvar(GrX) -> copy_waitflag_store(InnerWF,WF) % block would trigger already
5685 ; ground_value_check(Y,GrY),
5686 (nonvar(GrY) -> copy_waitflag_store(InnerWF,WF) % block would trigger already
5687 ; get_last_wait_flag(check_element_of_function_closure(OtherIDs),WF,LastWF),
5688 block_copy_waitflag_store(InnerWF,WF,GrX,GrY,LastWF)
5689 )
5690 )
5691 ),
5692 ? b_interpreter:b_compute_expression(EXPR,LocalState,[],Y,WF).
5693 check_element_of_function_closure(X,Y, P,T,ClosureBody, WF) :-
5694 ? element_of_normal_closure((X,Y),P,T,ClosureBody,WF).
5695 % we could memoize on X here if /*@symbolic-memo */ pragma used and closure has special ID associated with it
5696
5697 :- block block_copy_waitflag_store(?,?,-,-,-).
5698 block_copy_waitflag_store(InnerWF,WF,_GrX,_GrY,_LWF) :-
5699 % copy waitflags from InnerWF store to WF
5700 copy_waitflag_store(InnerWF,WF).
5701
5702 /* -------------- */
5703 /* NOT_ELEMENT_OF */
5704 /* -------------- */
5705
5706 :- use_module(kernel_objects,[not_element_of_global_set/2]).
5707
5708 not_element_of_custom_set_wf(X,CS,WF) :-
5709 ? not_element_of_custom_set_wf2(CS,X,WF).
5710
5711 not_element_of_custom_set_wf2(global_set(GS),X,_WF) :- not_element_of_global_set(X,GS).
5712 not_element_of_custom_set_wf2(freetype(_),_,_) :- !,fail. % TO DO: what if we have List(1..3) ? can that occur ??
5713 not_element_of_custom_set_wf2(avl_set(node(Y,_,_,empty,empty)),X,WF) :- !,
5714 % X /: {Y} <=> X /= Y
5715 ? kernel_objects:not_equal_object_wf(X,Y,WF). % improve if X is ground
5716 not_element_of_custom_set_wf2(avl_set(AVL),X,_WF) :- !,
5717 ground_value_check(X,GrX),
5718 ? propagate_avl_not_element_information(X,GrX,AVL),
5719 not_element_of_avl_set_block(GrX,X,AVL).
5720 not_element_of_custom_set_wf2(closure(Parameters,PT,Cond),X,WF) :-
5721 ? closure_not_member(X,Parameters,PT,Cond,WF).
5722
5723 :- block not_element_of_avl_set_block(-,?,?).
5724 not_element_of_avl_set_block(_,X,AVL) :-
5725 convert_to_avl_inside_set(X,CX),
5726 \+ avl_fetch(CX,AVL). %% IMPROVE ??
5727
5728 propagate_avl_not_element_information(_,GrEl,_) :- nonvar(GrEl),!.
5729 propagate_avl_not_element_information(Element,_,AVL) :- preferences:preference(use_clpfd_solver,true),
5730 is_avl_simple_set(AVL,Type), % integer or global(GS) \+ground(Element) ,
5731 ((Type=integer -> avl_height_less_than_with_solver_strength(AVL,6) % 16-31 elements - was: avl_size<20
5732 ; true)
5733 -> !,
5734 ? propagate_avl_not_element_information3(Type,Element,AVL) % uses clpfd_not_inlist
5735 ; Type=integer, avl_height_less_than_with_solver_strength(AVL,15),
5736 avl_is_interval(AVL,Min,Max)
5737 -> !,
5738 kernel_objects:not_in_nat_range(Element,int(Min),int(Max)) % WF not used anyway in _wf version
5739 ).
5740 propagate_avl_not_element_information(_Element,_,AVL) :-
5741 quick_definitely_maximal_set_avl(AVL),
5742 !, % we require something not to be an element of the full set; impossible
5743 fail.
5744 % to do: check if all but one element is in set
5745 propagate_avl_not_element_information(_,_,_).
5746
5747 avl_height_less_than_with_solver_strength(AVL,Limit) :- preference(solver_strength,SS),
5748 RealLimit is Limit + SS/100,
5749 avl_height_less_than(AVL,RealLimit).
5750
5751 % try and compute a small finite cardinality for a ground value; fail if not possible
5752 try_get_finite_max_card_from_ground_value(pred_true,2).
5753 try_get_finite_max_card_from_ground_value(pred_false,2).
5754 try_get_finite_max_card_from_ground_value(fd(_,Type),Card) :-
5755 b_global_sets:b_fd_card(Type,Card), integer(Card).
5756 try_get_finite_max_card_from_ground_value((A,B),Card) :-
5757 try_get_finite_max_card_from_ground_value(A,CA),
5758 try_get_finite_max_card_from_ground_value(B,CB),
5759 Card is CA*CB,
5760 Card < 20000.
5761 try_get_finite_max_card_from_ground_value(rec(Fields),Card) :-
5762 try_get_finite_max_card_from_fields(Fields,Card).
5763 try_get_finite_max_card_from_ground_value(freeval(FreetypeId,_CaseId,_EArgs),Card) :-
5764 freetype_cardinality(FreetypeId,Card), number(Card), Card < 20000.
5765 try_get_finite_max_card_from_ground_value(avl_set(node(El,_True,_,_,_)),Card) :-
5766 try_get_finite_max_card_from_ground_value(El,CEl),
5767 CEl < 16,
5768 safe_pow2(CEl,Card).
5769 % int(_), term(floating(_)), string(_) are all infinite
5770
5771 try_get_finite_max_card_from_fields([],1).
5772 try_get_finite_max_card_from_fields([field(_,A)|TF],Card) :-
5773 try_get_finite_max_card_from_ground_value(A,CA),
5774 try_get_finite_max_card_from_fields(TF,CB),
5775 Card is CA*CB,
5776 Card < 20000.
5777
5778 :- use_module(b_global_sets,[get_global_type_value/3]).
5779 propagate_avl_not_element_information3(integer,int(El),AVL) :-
5780 avl_domain(AVL,R),project_avl_domain_on_fd(R,FDList),
5781 ? clpfd_interface:clpfd_not_inlist(El,FDList).
5782 propagate_avl_not_element_information3(global(GS),FD,AVL) :-
5783 get_global_type_value(FD,GS,El), % sets up the FD constraint if var; maybe we can detect inconsistency straightaway below
5784 avl_domain(AVL,R),project_avl_domain_on_fd(R,FDList), % maybe we can compute directly the complement ?
5785 ? clpfd_interface:clpfd_not_inlist(El,FDList).
5786
5787
5788 :- block closure_not_member(?,-,?,?,?).
5789 %, closure_not_member(-,?,?,?,?). /* El is unlikely to be instantiated by not_element_of test , but test 6 requires commenting out block declaration */
5790
5791 closure_not_member(X,Parameters,Types,Body,WF) :-
5792 is_special_closure(Parameters,Types,Body,SpecialClosure),!,
5793 ? not_element_of_special_closure(SpecialClosure,X,WF,Parameters,Types,Body).
5794 closure_not_member(El,Parameters,PT,Cond,WF) :-
5795 normal_closure_not_member(El,Parameters,PT,Cond,WF).
5796
5797 :- use_module(memoization,[not_element_of_memoization_closure/6]).
5798 not_element_of_special_closure(interval(LOW,UP),X,_WF,_Parameters,_Types,_Body) :-
5799 !,kernel_objects:not_in_nat_range(X,int(LOW),int(UP)).
5800 not_element_of_special_closure(member_closure(_ID,_Type,VAL),X,WF,_Parameters,_Types,_Body) :-
5801 ( VAL = value(_)
5802 ; VAL = cartesian_product(b(value(A),_,_),b(value(B),_,_))),!,
5803 %hit_profiler:add_profile_hit(member(X,Par,Typ,Body)),
5804 ( VAL=value(Set) -> kernel_objects:not_element_of_wf(X,Set,WF)
5805 ; kernel_objects:not_is_cartesian_pair(X,A,B,WF)).
5806 not_element_of_special_closure(not_member_closure(_ID,_Type,value(Set)),X,WF,_Parameters,_Types,_Body) :-
5807 ? !,kernel_objects:check_element_of_wf(X,Set,WF).
5808 not_element_of_special_closure(memoization_closure(MemoID),X,WF,P,T,B) :- !,
5809 not_element_of_memoization_closure(MemoID,X,WF,P,T,B).
5810 not_element_of_special_closure(recursive_special_closure(RId),X,WF,Parameters,Types,Body) :-
5811 !,
5812 add_recursive_parameter(Parameters,Types,X,RId,Body,NewParameters,NewPT,Value,WF),
5813 normal_closure_not_member(Value,NewParameters,NewPT,Body,WF).
5814
5815 not_element_of_special_closure(SC,_X,_WF,Parameters,Types,Body) :-
5816 SC \= interval(_,_),
5817 SC \= not_member_closure(_,_,_),
5818 is_definitely_maximal_closure(Parameters,Types,Body),
5819 !,
5820 fail.
5821 not_element_of_special_closure(_,X,WF,Parameters,Types,Body) :-
5822 % falling back to normal test
5823 normal_closure_not_member(X,Parameters,Types,Body,WF).
5824
5825 :- use_module(library(lists),[same_length/2]).
5826
5827 normal_closure_not_member(El,Parameters,PT,Cond,WF) :-
5828 %hit_profiler:add_profile_hit(closure_not_member(El,Parameters,PT,Cond,WF)),
5829 same_length(Parameters,ParValues),
5830 convert_list_into_pairs(ParValues,El),
5831 b_not_test_closure_wf(Parameters,PT,Cond,ParValues,WF).
5832
5833
5834
5835
5836 /* -------------------------- */
5837 /* VARIOUS CLOSURE PREDICATES */
5838 /* -------------------------- */
5839
5840
5841 :- use_module(tools,[convert_list_into_pairs/2]).
5842 :- use_module(b_interpreter,[b_test_boolean_expression/4, b_not_test_boolean_expression/4]).
5843 :- use_module(b_enumerate).
5844
5845 :- assert_pre(custom_explicit_sets:expand_closure_to_list(_,_,ClosureBody,_Result,_Done,_,_WF),
5846 (nonvar(ClosureBody),
5847 bsyntaxtree:check_if_typed_predicate(ClosureBody))).
5848 :- assert_post(custom_explicit_sets:expand_closure_to_list(_,_,_,Result,_Done,_,_WF),
5849 b_interpreter:value_type(Result)).
5850
5851 :- block expand_interval_closure_to_avl(-,?,?), expand_interval_closure_to_avl(?,-,?).
5852 expand_interval_closure_to_avl(Low,Up,Result) :-
5853 Delta is Up-Low,
5854 (Delta>9999 -> perfmessage(expanding_interval(Low,Up)) ; true),
5855 construct_interval_ord_list(Low,Up,OL),
5856 ord_list_to_avlset_direct(OL,ARes,expand_interval),
5857 ? equal_object(ARes,Result,expand_interval_closure_to_avl).
5858 construct_interval_ord_list(Low,Up,Res) :-
5859 (Low>Up -> Res = []
5860 ; Res = [int(Low)-true|T], L1 is Low+1, construct_interval_ord_list(L1,Up,T)
5861 ).
5862
5863 :- block expand_interval_closure_to_list(-,?,?,?), expand_interval_closure_to_list(?,-,?,?).
5864 expand_interval_closure_to_list(Low,Up,Result,Done) :-
5865 construct_interval_list(Low,Up,OL),
5866 ? equal_object(OL,Result,expand_interval_closure_to_list),
5867 Done=true.
5868 construct_interval_list(Low,Up,Res) :-
5869 (Low>Up -> Res = []
5870 ; Res = [int(Low)|T], L1 is Low+1, construct_interval_list(L1,Up,T)
5871 ).
5872
5873 expand_closure_to_list([X],[integer],Body,Result,Done,_,_) :-
5874 ? is_interval_closure_body(Body,X,Low,Up),!,
5875 expand_interval_closure_to_list(Low,Up,Result,Done).
5876 expand_closure_to_list(Par,Types,Body,Result,Done,Source,WF) :-
5877 ? expand_normal_closure(Par,Types,Body,CResult,CDone,expand_closure_to_list(Source),WF),
5878 expand_if_avl(CResult,Result,CDone,Done,Source),
5879 lazy_check_elements_of_closure(Result,CDone, Par,Types,Body,WF).
5880
5881 % Note: does slow down test 1306 (91ms mc time becomes 918 ms)
5882 % as long as a closure has not been fully expanded, lazily check elements
5883 % that are instantiated from the outside satisfy the closure predicate
5884 % Note: this can also instantiate unknown values used inside the closure body
5885 lazy_check_elements_of_closure(Result,CDone, Par,Types,Body,WF) :-
5886 (WF==no_wf_available -> true
5887 ? ; lazy_check_elements6(Result,CDone, Par,Types,Body,WF),
5888 propagate_closure_body_value_set(Par,Types,Body,Result,CDone,WF)
5889 ).
5890 % TODO: check if closure is a non-ground projection-member closure and check elements
5891 :- block lazy_check_elements6(-,-, ?,?,?,?).
5892 lazy_check_elements6(_Result,CDone, _Par,_Types,_Body,_WF) :- nonvar(CDone),!.
5893 lazy_check_elements6([H|T],CDone, Par,Types,Body,WF) :- !,
5894 ? element_of_closure(H,Par,Types,Body,WF),
5895 ? lazy_check_elements6(T,CDone, Par,Types,Body,WF).
5896 lazy_check_elements6(avl_set(A),_CDone, Par,Types,Body,WF) :- !,
5897 avl_max(A,X),
5898 element_of_closure(X,Par,Types,Body,WF).
5899 % TO DO: also check avl_min or even all elements ?
5900 lazy_check_elements6(_,_,_,_,_,_).
5901
5902 :- use_module(probsrc(bsyntaxtree),[create_typed_ids/3]).
5903 % lazy check elements from non-var closure body against a result
5904 % for example if we have {x| TRUE |-> x : Value } = Result and Value is not-ground,
5905 % we can check that for all elements TRUE|->x of Value the corresponding x is in Result, see test 2466
5906 % slows down test 1987
5907 :- block propagate_closure_body_value_set(?,?,?,-,-,?).
5908 % we delay until the result is known, possibly in SMT mode it could be useful to propagate earlier
5909 propagate_closure_body_value_set(ParIDs,Types,Body,Result,CDone,WF) :-
5910 var(CDone), % the closure has not yet been fully expanded
5911 % check if this closure can profit from set membership propagation:
5912 b_interpreter:is_for_all_set_membership_predicate2(Body,ParIDs,ParIDs,UnmatchedIDs,Set,_Pattern,_ParValues,_),
5913 UnmatchedIDs=[],
5914 Set = b(value(_Value),_,_), % check that the set is a value; it must be non-ground, otherwise CDone would be true
5915 create_couple_term(ParIDs,Types,CoupleTerm),
5916 SetTerm=b(value(Result),any,[]),
5917 safe_create_texpr(member(CoupleTerm,SetTerm),pred,[],RHS),
5918 create_typed_ids(ParIDs,Types,TIDs),
5919 !,
5920 propagate_closure_body_for_all(TIDs,Body,RHS,Result,CDone,WF).
5921 propagate_closure_body_value_set(_,_,_,_,_,_WF).
5922
5923 :- block propagate_closure_body_for_all(?,?,?,-,-,?).
5924 propagate_closure_body_for_all(TIDs,Body,RHS,_,CDone,WF) :- var(CDone),!,
5925 add_debug_message(closure,'Propagating from closure body to result: ',Body,Body),
5926 Infos=[],
5927 b_interpreter:b_for_all(TIDs,Infos,Body,RHS,[],[],WF).
5928 propagate_closure_body_for_all(_,_,_,_Result,_CDone,_WF). % propagation not required; closure expanded, cf test 1987
5929
5930 %check_valid_avl(AVL,Origin) :-
5931 % (nonvar(AVL) -> true
5932 % ; add_internal_error('Var avl_set: ', check_valid_avl(AVL,Origin)),fail).
5933
5934 :- block expand_if_avl(?,?,-,?,?).
5935 expand_if_avl(avl_set(S),Result,_,Done,Source) :- !, % we could transmit a flag to expand_normal_closure so that transform_result_into_set does not expand to avl
5936 ? expand_custom_set_to_list2(avl_set(S),Result,Done,_,expand_if_avl(Source),no_wf_available).
5937 expand_if_avl(Res,Result,_,Done,Source) :- check_list(Res,expand_if_avl(Source)),
5938 ? equal_object(Res,Result), Done=true.
5939
5940 check_list(Res,_) :- nonvar(Res), is_list(Res),!.
5941 check_list(Res,Src) :- add_error(Src,'Could not expand to list: ',Res).
5942 is_list([]). is_list([_|_]).
5943
5944 expand_closure_to_avl_or_list([X],[integer],Body,Result,_CheckTimeouts,_WF) :-
5945 ? is_interval_closure_body(Body,X,Low,Up),!,
5946 expand_interval_closure_to_avl(Low,Up,Result).
5947 %expand_closure_to_avl_or_list(P,T,Body,Result,_WF) :- is_member_closure(P,T,Body,TS,Set),
5948 % print(expand_member_closure(P,T,Body,TS,Set)),nl,fail.
5949 expand_closure_to_avl_or_list(Par,Types,Body,Result,CheckTimeouts,WF) :-
5950 expand_normal_closure(Par,Types,Body,CResult,_Done,CheckTimeouts,WF),
5951 kernel_objects:equal_object(Result,CResult,expand_closure_to_avl_or_list). % may convert to AVL, should we wait for _Done?
5952
5953
5954 % use WF just for call stack messages; we should not delay creating result
5955 expand_closure_to_avl_wf([X],[integer],Body,Result,_WF) :-
5956 is_interval_closure_body(Body,X,Low,Up),!,
5957 expand_interval_closure_to_avl(Low,Up,Result). % we could pass WF
5958 expand_closure_to_avl_wf(Par,Types,Body,Result,WF) :-
5959 ? expand_normal_closure(Par,Types,Body,S,_Done,check(expand_closure_to_avl),WF),
5960 (ground_value(S) % ground value is sufficient to proceed; we do not need to check Done
5961 -> convert_to_avl_inside_set(S,R),equal_object(R,Result,expand_closure_to_avl)
5962 ; perfmessage(expand_closure_to_avl_wf,'Cannot convert closure value to AVL:',closure(Par,Types,Body)),
5963 %translate:print_bexpr(Body),nl,trace,
5964 fail).
5965
5966
5967 % possible values for CheckTimeouts: check, check_no_inf, no_check, ...
5968 % Note: we no longer check is_infinite_explicit_set(closure(Parameters,ParameterTypes,ClosureBody))
5969 % and no longer raise add_closure_warning(Source,Parameters,ParameterTypes,ClosureBody,'### WARNING: expanding infinite comprehension set: ')
5970 % and no longer use preference warn_when_expanding_infinite_closures
5971 % this is relevant for e.g., test 1291
5972 expand_normal_closure(Parameters,ParameterTypes,ClosureBody,Result,Done,CheckTimeouts,WF) :-
5973 ? expand_normal_closure_memo(CheckTimeouts,Parameters,ParameterTypes,ClosureBody,Result,Done,WF).
5974
5975 :- public add_closure_warning_wf/6.
5976 add_closure_warning_wf(Source,Parameters,_ParameterTypes,_ClosureBody,_MSG,_WF) :-
5977 preference(provide_trace_information,false),preference(strict_raise_warnings,false),!,
5978 format('### TIME-OUT raised during closure expansion (~w,~w).~n### set TRACE_INFO preference to TRUE for more details.~n',[Parameters,Source]).
5979 add_closure_warning_wf(Source,Parameters,ParameterTypes,ClosureBody,MSG,WF) :-
5980 (debug_mode(on) -> Limit = 2500, AvlLim=10 ; Limit = 500, AvlLim=5),
5981 preferences:temporary_set_preference(expand_avl_upto,AvlLim,CHNG),
5982 call_cleanup(translate:translate_bvalue_with_limit(closure(Parameters,ParameterTypes,ClosureBody),Limit,CT),
5983 preferences:reset_temporary_preference(expand_avl_upto,CHNG)),
5984 bsyntaxtree:get_texpr_info(ClosureBody,Infos),
5985 add_warning_wf(Source,MSG,CT,Infos,WF), debug_print(19,'! infos: '), debug_println(Infos). %,trace.
5986
5987
5988 :- use_module(memoization,[is_memoization_closure/4,get_complete_memoization_expansion/6]).
5989
5990 % a version of closure expansion which memoizes its results; stored_expansion needs to be cleared when new machine loaded
5991 expand_normal_closure_memo(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF) :-
5992 ? is_memoization_closure(Parameters,ParameterTypes,ClosureBody,MemoID),
5993 !, Span=ClosureBody,
5994 % MemoID can be a variable
5995 (var(MemoID) -> perfmessage(CHECK,'Getting full value of a memoized function',ClosureBody) ; true),
5996 get_complete_memoization_expansion(MemoID,FullResult,Done,Span,expand_normal_closure_memo(CHECK),WF).
5997 expand_normal_closure_memo(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF) :-
5998 preferences:preference(use_closure_expansion_memoization,false),!,
5999 ? expand_normal_closure1(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF).
6000 expand_normal_closure_memo(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF) :-
6001 % maybe we should only memo when ClosureWaitVars are ground ?
6002 MemoLookupTerm = closure(Parameters,ParameterTypes,ClosureBody),
6003 compute_memo_hash(MemoLookupTerm,Hash),
6004 % idea: maybe store expansion only on second hit ?
6005 (get_stored_memo_expansion(Hash,MemoLookupTerm,StoredResult)
6006 -> %print_term_summary(reusing_expansion(Hash,Parameters,ParameterTypes,ClosureBody,StoredResult)),nl,
6007 UPV=StoredResult, %state_packing:unpack_value(StoredResult,UPV),
6008 FullResult = UPV, Done=true
6009 ; %statistics(runtime,[T1,_]), %%
6010 expand_normal_closure1(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF),
6011 %statistics(runtime,[T2,_]), Time is T2-T1, store_memo_computation_time(Hash,Time),
6012 (Done==true/* ,T2-T1>0*/
6013 -> PackedValue=FullResult, %state_packing:pack_value(FullResult,PackedValue),
6014 store_memo_expansion(Hash,MemoLookupTerm,PackedValue)
6015 ; true)
6016 ).
6017
6018 expand_normal_closure1(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF) :-
6019 preference(provide_trace_information,false),!,
6020 ? expand_normal_closure2(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF).
6021 expand_normal_closure1(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF) :-
6022 get_texpr_info(ClosureBody,Info),
6023 push_wait_flag_call_stack_info(WF,
6024 quantifier_call(comprehension_set(all_solutions),Parameters,[],Info),WF2),
6025 expand_normal_closure2(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF2).
6026
6027
6028 expand_normal_closure2(_CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF) :-
6029 % TO DO: add more symbolic member closures who have expression computation code
6030 is_closure1_value_closure(Parameters,ParameterTypes,ClosureBody,VAL),!,
6031 ? kernel_relations:relational_trans_closure_wf(VAL,FullResult,WF),
6032 ground_value_check(FullResult,FRGr),
6033 when(nonvar(FRGr),Done=true).
6034 expand_normal_closure2(CHECK,Parameters,ParameterTypes,ClosureBody,FullResult,Done,WF) :-
6035 % special treatment for lambda closures: Advantage: we don't have to wait for variables in EXPR body of closure
6036 % Disadvantage: EXPR only gets evaluated after a solution has been found for args: can mean repeated computations !
6037 % (cf pas_as_env_inv_cv_sui, negated version of !(cv_i).(cv_i : t_cv_pas => closure(%cv_o2.((...|>> {cv_i} : t_cv_pas <-> t_cv_pas) ASSERTION
6038 % Advantage: it can solve constraints such as f = %x.(x:1..10|x+y) & f(5)=1005 (finding y without enumeration); see test 1168
6039 \+ preferences:preference(use_smt_mode,false),
6040 is_lambda_closure(Parameters,ParameterTypes,ClosureBody, OtherIDs,OtherTypes, DomainPred, EXPR),
6041 \+ ground_bexpr(EXPR), % if EXPR is ground, there is nothing to be gained by special treatment here
6042 WF \= no_wf_available, % otherwise we may have to enumerate EXPR result leading to choice points, e.g. in phase 0
6043 !,
6044 bexpr_variables(DomainPred,ClosureWaitVars),
6045 (CHECK=no_check -> TIMEOUTCODE = true ;
6046 TIMEOUTCODE = add_closure_warning_wf(CHECK,Parameters,ParameterTypes,ClosureBody,
6047 'TIME-OUT occurred while ProB was expanding: ',WF)),
6048 (CHECK=check_no_inf -> VIRTUALTIMEOUTCODE=true ; VIRTUALTIMEOUTCODE=TIMEOUTCODE),
6049 delay_setof_check_wf( ParTuple,
6050 (custom_explicit_sets:b_test_closure(OtherIDs,OtherTypes,DomainPred,OtherValues,all_solutions,WF),
6051 convert_list_into_pairs(OtherValues,ParTuple)
6052 % TO DO: compile EXPR when we start expanding the closure: to avoid repeated re-computation of expressions for every instance
6053 ),
6054 Result, ClosureWaitVars, __Done,
6055 TIMEOUTCODE,VIRTUALTIMEOUTCODE,WF,DomainPred),
6056 (WF = no_wf_available
6057 -> init_wait_flags(WF1,[expansion_context(lambda_function_result,Parameters)])
6058 ; WF1=WF
6059 ),
6060 evaluate_result_expr(Result,EXPR,OtherIDs,EvResult,EvDone,WF1),
6061 when(nonvar(EvDone),(
6062 (WF = no_wf_available -> ground_wait_flags(WF1) ; true),
6063 kernel_objects:equal_object_wf(EvResult,FullResult,expand_normal_closure2,WF),
6064 Done=true)).
6065 expand_normal_closure2(no_check,Parameters,ParameterTypes,ClosureBody,Result,Done,WF) :- !,
6066 expand_normal_closure_direct(Parameters,ParameterTypes,ClosureBody,Result,Done,WF).
6067 expand_normal_closure2(CHECK,Parameters,ParameterTypes,ClosureBody,Result,Done,WF) :-
6068 bexpr_variables(ClosureBody,ClosureWaitVars),
6069 TIMEOUTCODE = add_closure_warning_wf(CHECK,Parameters,ParameterTypes,ClosureBody,
6070 'TIME-OUT occurred while ProB was expanding: ',WF),
6071 (CHECK=check_no_inf -> VIRTUALTIMEOUTCODE=true ; VIRTUALTIMEOUTCODE=TIMEOUTCODE),
6072 % Note: delay_setof_check_wf will throw enumeration warning for virtual timeouts, after VIRTUALTIMEOUTCODE
6073 delay_setof_check_wf( ParTuple,
6074 custom_explicit_sets:test_closure_and_convert(Parameters,ParameterTypes,ClosureBody, ParTuple,WF),
6075 Result, ClosureWaitVars, Done, TIMEOUTCODE, VIRTUALTIMEOUTCODE,WF,ClosureBody).
6076
6077 expand_normal_closure_direct(Parameters,ParameterTypes,ClosureBody,Result,Done,WF) :-
6078 bexpr_variables(ClosureBody,ClosureWaitVars),
6079 Span = ClosureBody,
6080 delay_setof_wf( ParTuple,
6081 % TO DO: refresh waitflag in outer WF store to let pending code run to completion and avoid spurious WD errors ?
6082 custom_explicit_sets:test_closure_and_convert(Parameters,ParameterTypes,ClosureBody, ParTuple,WF),
6083 Result, ClosureWaitVars, Done,WF, Span).
6084
6085
6086
6087 :- block evaluate_result_expr(-,?,?,?,?,?).
6088 evaluate_result_expr(avl_set(AVL),EXPR,OtherIDs,Res,Done,WF) :-
6089 avl_domain(AVL,R),
6090 evaluate_result_expr(R,EXPR,OtherIDs,Res,Done,WF).
6091 evaluate_result_expr([],_EXPR,_OtherIDs,[],Done,_WF) :-
6092 %ground_wait_flags(WF),
6093 Done=true.
6094 evaluate_result_expr([ParTuple|T],EXPR,OtherIDs,[FullTuple|ET],Done,WF) :-
6095 % same_length(OtherIDs,ParValues), % not necessary
6096 set_up_localstate(OtherIDs,ParValues,[],LocalState),
6097 convert_list_into_pairs(ParValues,ParTuple), % bind values in ParTuple to LocalState
6098 b_interpreter:b_compute_expression(EXPR,LocalState,[],EXPRVALUE,WF),
6099 append(ParValues,[EXPRVALUE],FullValues),
6100 convert_list_into_pairs(FullValues,FullTuple),
6101 evaluate_result_expr(T,EXPR,OtherIDs,ET,Done,WF).
6102
6103 :- use_module(bsyntaxtree,[split_names_and_types/3]).
6104 :- use_module(probsrc(bsyntaxtree), [def_get_texpr_id/2]).
6105 %:- use_module(library(lists),[prefix_length/3, suffix_length/3]).
6106 % test a closure and convert into pairs; assume we want all solutions
6107 test_closure_and_convert(Parameters,ParameterTypes,ClosureBody, ParTuple, WF) :-
6108 ? is_recursive_closure(Parameters,ParameterTypes,ClosureBody),
6109 ? get_recursive_identifier_of_closure_body(ClosureBody,TRID),!,
6110 def_get_texpr_id(TRID,RID), get_texpr_type(TRID,RType),
6111 %print(test_recursion(RID)),nl, translate:nested_print_bexpr(ClosureBody),nl,
6112 RecVal = closure(Parameters,ParameterTypes,ClosureBody), % Recursive Value added to parameters
6113 same_length(Parameters,ParValues),
6114 reset_closure_solution_counter(Parameters),
6115 ? b_test_closure([RID|Parameters],[RType|ParameterTypes],ClosureBody,[RecVal|ParValues],all_solutions,WF),
6116 convert_sol_list_into_pairs(ParValues,Parameters,ParTuple). % convert tuple without recursive value to ParTuple
6117 test_closure_and_convert(Parameters,ParameterTypes,b(exists(EParAndTypes,ClosureBody),pred,OuterInfo), ParTuple, WF) :-
6118 % Motivation: enumerating Parameters can be quite inefficient
6119 % if for example we have something like {x|#y.(y:SmallSet & x=f(y))}
6120 % Problem: the existential quantifier will be delayed until the Parameters are instantiated !
6121 % relevant test: 1162
6122 % Note: this is duplicating to some extent the code in b_test_exists_wo_expansion
6123 % However, here we can also apply lambda_closure optimisation in b_test_closure below, this is
6124 % relevant for private_examples/2023/.../rule_FICHIER_MRGATKSAATPAR_RVF219_MRGA_DE.mch
6125 ? exists_should_be_lifted(Parameters,ParameterTypes,OuterInfo,ClosureBody),
6126 split_names_and_types(EParAndTypes,EPar,ETypes),
6127 !,
6128 % print(' Lifting existential quantifier (i.e., enumerating paras with closure paras): '), print(EPar),nl,
6129 % print(outer_paras(Parameters)),nl,
6130 % append Parameters at end; in case we have a lambda function
6131 append(EPar,Parameters,FullPar), length(Parameters,NrParas),
6132 append(ETypes,ParameterTypes,FullTypes),
6133 length(EPar,NrExistsParas),
6134 length(IrrelevantParas,NrExistsParas), length(Suffix,NrParas),
6135 append(IrrelevantParas,Suffix,FullParList),
6136 copy_identifier_infos(OuterInfo,ClosureBody,ClosureBody2),
6137 reset_closure_solution_counter(Parameters),
6138 % bsyntaxtree:check_used_ids_in_ast(ClosureBody2),
6139 ? b_test_closure(FullPar,FullTypes,ClosureBody2, FullParList,all_solutions,WF),
6140 convert_sol_list_into_pairs(Suffix,Parameters,ParTuple).
6141 test_closure_and_convert(Parameters,ParameterTypes,ClosureBody, ParTuple, WF) :-
6142 reset_closure_solution_counter(Parameters),
6143 % print(test),nl, translate:nested_print_bexpr(ClosureBody),nl,
6144 length(Parameters,Len), length(ParValues,Len),
6145 %(annotate_exists(Parameters,ParameterTypes,ClosureBody,Body2) -> true ; Body2=ClosureBody),
6146 ? b_test_closure(Parameters,ParameterTypes,ClosureBody,ParValues,all_solutions,WF),
6147 convert_sol_list_into_pairs(ParValues,Parameters,ParTuple). % ,print(solution(ParTuple)),nl,nl.
6148
6149 % Lifting existential quantifier was previously done here, but was duplicating code in b_test_exists_wo_expansion
6150 % we now simply generate the allow_to_lift_exists annotation here and let b_test_exists_wo_expansion do its job
6151 %annotate_exists(Parameters,ParameterTypes,
6152 % b(exists(EParAndTypes,ClosureBody),pred,OuterInfo),
6153 % b(exists(EParAndTypes,ClosureBody),pred,[allow_to_lift_exists|OuterInfo])) :-
6154 % exists_should_be_lifted(Parameters,ParameterTypes,OuterInfo,ClosureBody).
6155
6156 % check if a top-level exists with body ExistsClosureBody should be lifted
6157 % within a closure with paras Parameters of type ParameterTypes:
6158 exists_should_be_lifted(Parameters,ParameterTypes,OuterInfo,ExistsClosureBody) :-
6159 (Parameters == ['_was_lambda_result_'] % here we are quite sure that we gain by this optimisation
6160 ? ; member(allow_to_lift_exists,OuterInfo) % parameters were originally from a set comprehension,
6161 % see test 306: in this case existential quantifier is lifted in b_interpreter anyway;
6162 % Note we counter the rewrite ran({x1,...xn|P}) ---> {xn| #(x1,...).(P)} and similarly for dom({...})
6163 ; ExistsClosureBody = b(member(_,_),_,_) % we have a simple projection closure
6164 % TO DO: maybe support other ones as well
6165 ? ; basic_type_list_cardinality(ParameterTypes,Card),
6166 (Card=inf -> true ; Card=inf_overflow -> true ; Card>10000) % geq_inf(Card,10001)
6167 % if here are only a few parameter values: do not lift existential quantified variables
6168 ).
6169
6170 % we need to copy important infos about the outer Parameters to ClosureBody
6171 copy_identifier_infos(Info,b(InnerPred,T,II),b(InnerPred,T,II2)) :-
6172 findall(I,identifier_info(I,Info),ToCopy),
6173 append(ToCopy,II,II2).
6174 identifier_info(I,Info) :- I=prob_annotation('DO_NOT_ENUMERATE'(ID)),
6175 ? member(I,Info), ID \= '$$NONE$$'.
6176
6177 convert_sol_list_into_pairs(ParaValues,Parameters,ParTuple) :-
6178 convert_list_into_pairs(ParaValues,ParTuple),
6179 update_closure_solution_counter(Parameters,ParTuple).
6180
6181 :- if(environ(prob_debug_flag,true)).
6182 :- dynamic closure_solution_counter/3.
6183 % debugging long expansions of comprehension_set / closures
6184 reset_closure_solution_counter(Parameters) :- retractall(closure_solution_counter(Parameters,_,_)).
6185
6186 update_closure_solution_counter(Parameters,ParTuple) :-
6187 retract(closure_solution_counter(Parameters,OldCount,OldTime)),!,
6188 statistics(walltime,[W2,_]), Delta is W2-OldTime,
6189 NewCount is OldCount+1,
6190 ((Delta > 5000 ; NewCount mod 1000 =:= 0)
6191 -> format('--> Solution ~w for expansion of closure ~w (delta ~w ms): ',[NewCount,Parameters,Delta]),
6192 translate:print_bvalue(ParTuple),nl,
6193 assert(closure_solution_counter(Parameters,NewCount,W2))
6194 ; assert(closure_solution_counter(Parameters,NewCount,OldTime))
6195 ).
6196 update_closure_solution_counter(Parameters,_ParTuple) :-
6197 statistics(walltime,[W2,_]),
6198 assert(closure_solution_counter(Parameters,1,W2)).
6199 :- else.
6200 reset_closure_solution_counter(_).
6201 update_closure_solution_counter(_,_).
6202 :- endif.
6203
6204
6205
6206 % compute cardinality of a list of basic types
6207 basic_type_list_cardinality([],1).
6208 basic_type_list_cardinality([BasicType|T],Res) :-
6209 ? basic_type_list_cardinality(T,TCard),
6210 (TCard=inf -> Res=inf
6211 ? ; kernel_objects:max_cardinality(BasicType,Card),
6212 safe_mul(Card,TCard,Res)
6213 ).
6214
6215 % for lambda closures we can set up a second waitflag for the expression and only ground it when body enumeration finished
6216 % idea is to avoid perturbation of constraint solving of main closure predicate by lambda expression, see test 1737
6217 % something like %(x,y).(x:1..200 & y:1..100 & y+x<259 & y*x>10|(y+x*x+y) mod 100) is faster
6218 % this is slower : %(x,y).(x:1..200 & y:1..100 |(y+x*x+y))
6219 % currently this slows down test 1336
6220 :- block b_test_closure(?,?,-,?,?,?).
6221 b_test_closure(Parameters,ParameterTypes,ClosureBody, FullParValues, NegationContext, OuterWF) :-
6222 (preference(data_validation_mode,true)
6223 -> true % avoids ineraction between domain and range expression enumeration; see
6224 % private_examples/ClearSy/2019_May/perf_3264/rule_186.mch or
6225 % computation of 631 ic___DMI_MRGATKSAAT___Parametre_Identifiant_indices_function in rule_FICHIER_MRGATKSAATPAR_RVF219_MRGA_DE.mch
6226 % however, as b_optimize below does *not* evaluate nested set comprehensions, there can be a slowdown:
6227 % the nested set comprehension gets re-evaluated for every soluiton of the lambda parameters !
6228 % this was the case of private_examples/ClearSy/2019_Nov/rule_Regle_31C_0005/rule.mch before using SORT
6229 ; \+ preferences:preference(use_smt_mode,false)), % TO DO: enable in normal mode when performance of 1336 fixed
6230 % print(test_closure(Parameters,FullParValues)),nl,
6231 is_lambda_closure(Parameters,ParameterTypes,ClosureBody, OtherIDs,OtherTypes, DomainPred, EXPR),
6232 % TO DO: detect not only equalities at end, but any equality which is irrelevant for the rest
6233 % nl,print(lambda_closure(OtherIDs)),nl, translate:print_bexpr(EXPR),nl,
6234 append(ParValues,[LambdaResult],FullParValues),
6235 !,
6236 get_texpr_info(ClosureBody,BInfo),
6237 ? b_interpreter:set_up_typed_localstate2(OtherIDs,OtherTypes,BInfo,ParValues,TypedVals,[],LocalState,NegationContext),
6238 simplify_span(ClosureBody,BSpan), % sometimes BInfo no longer contains a position info, but first_sub_expr does
6239 init_quantifier_wait_flag(OuterWF,comprehension_set(NegationContext),OtherIDs,ParValues,BSpan,WF),
6240 ? b_test_boolean_expression(DomainPred,LocalState,[],WF),
6241 %print('PRED: '),translate:print_bexpr(ClosureBody),nl,
6242 b_tighter_enumerate_values_in_ctxt(TypedVals,DomainPred,WF), % also does: project_away_useless_enumeration_values
6243 init_quantifier_wait_flag(OuterWF,comprehension_set(NegationContext),OtherIDs,ParValues,BSpan,WF2),
6244 ? b_compiler:b_optimize(EXPR,[],LocalState,[],CEXPR,WF), % already pre-compile lookup, without constraint processing; is not sufficient for test 1336
6245 ? ground_wait_flags(WF), % TODO: also call ground inner WF in context
6246 ? b_interpreter:b_compute_expression(CEXPR,LocalState,[],LambdaResult,WF2),
6247 ground_inner_wait_flags_in_context(NegationContext,WF2).
6248 b_test_closure(Parameters,ParameterTypes,ClosureBody,ParValues,NegationContext, OuterWF) :-
6249 % tools:print_bt_message(b_test_closure_testing_closure(Parameters,ParValues)), %%
6250 get_texpr_info(ClosureBody,BInfo),
6251 ? b_interpreter:set_up_typed_localstate2(Parameters,ParameterTypes,BInfo,
6252 ParValues,TypedVals,[],LocalState,NegationContext),
6253 % print_message(b_interpreter:b_test_boolean_expression(ClosureBody,LocalState,[],WF)),
6254 simplify_span(ClosureBody,BSpan), % sometimes BInfo no longer contains a position info, but first_sub_expr does
6255 init_quantifier_wait_flag(OuterWF,comprehension_set(NegationContext),Parameters,ParValues,BSpan,WF),
6256 %external_functions:observe_parameters(Parameters,LocalState), %%
6257 ? b_test_boolean_expression(ClosureBody,LocalState,[],WF),
6258 % tools:print_bt_message(tested_bool_expr), translate:print_bexpr(ClosureBody),nl,
6259 b_enumerate:b_tighter_enumerate_values_in_ctxt(TypedVals,ClosureBody,WF), % also detects useless enumeration ids
6260 ? ground_inner_wait_flags_in_context(NegationContext,WF).
6261
6262
6263
6264 :- block b_not_test_closure_wf(?,?,?,-,?).
6265 b_not_test_closure_wf(Parameters,ParameterTypes,Closure,ParValues,WF) :-
6266 % same_length(Parameters,ParValues), % not necessary
6267 set_up_localstate(Parameters,ParValues,[],LocalState),
6268 b_enumerate:b_type_values_in_store(Parameters,ParameterTypes,LocalState),
6269 b_not_test_boolean_expression(Closure,LocalState,[],WF),
6270 get_last_wait_flag(b_not_test_closure_wf(Parameters),WF,WF2),
6271 get_texpr_info(Closure,Infos),
6272 b_not_test_closure_enum(Parameters,ParameterTypes,Infos,LocalState,WF,WF2).
6273
6274 :- block b_not_test_closure_enum(-,?,?,?,?,?).
6275 b_not_test_closure_enum(Parameters,ParameterTypes,Infos,LocalState,WF,WF2) :-
6276 b_enumerate:b_extract_typedvalc(Parameters,ParameterTypes,Infos,LocalState,TypedVals),
6277 (var(WF2) -> ground_typedvals_check(TypedVals,GrVals) ; true),
6278 b_not_test_closure_enum_aux(GrVals,WF2,TypedVals,WF).
6279
6280 :- block b_not_test_closure_enum_aux(-,-,?,?).
6281 b_not_test_closure_enum_aux(_,_,TypedVals,WF) :-
6282 b_enumerate:b_tighter_enumerate_all_values(TypedVals,WF).
6283 % , print(finished_enum(Parameters)),nl.
6284
6285
6286 :- use_module(library(terms)).
6287 % check whether a VARIABLE occurs inside a closure
6288 closure_occurs_check(VARIABLE,_Par,_ParTypes,ClosureBody) :- expression_contains_setvar(ClosureBody,VARIABLE).
6289 % /* occurs check; x = closure1(x) ; for other closures this cannot happen ???!!! TO DO: Check */
6290 % custom_explicit_sets:is_closure1_value_closure(Par,ParTypes,ClosureBody,Val),
6291 % contains_var(VARIABLE,Val).
6292
6293 expression_contains_setvar(b(E,_,_),Variable) :- !,
6294 expression_contains_setvar_aux(E,Variable).
6295 expression_contains_setvar(E,V) :- add_internal_error('Illegal Expression: ', expression_contains_setvar(E,V)),
6296 contains_var(V,E).
6297
6298 expression_contains_setvar_aux(value(Val),Variable) :- !,value_contains_setvar(Val,Variable).
6299 % a few very common cases for performance; currently this predicate is often called for recursive functions
6300 expression_contains_setvar_aux(identifier(_),_) :- !,fail.
6301 expression_contains_setvar_aux(equal(A,B),Variable) :- !,
6302 (expression_contains_setvar(A,Variable) -> true ; expression_contains_setvar(B,Variable)).
6303 expression_contains_setvar_aux(conjunct(A,B),Variable) :- !,
6304 (expression_contains_setvar(A,Variable) -> true ; expression_contains_setvar(B,Variable)).
6305 expression_contains_setvar_aux(function(A,B),Variable) :- !,
6306 (expression_contains_setvar(A,Variable) -> true ; expression_contains_setvar(B,Variable)).
6307 expression_contains_setvar_aux(union(A,B),Variable) :- !,
6308 (expression_contains_setvar(A,Variable) -> true ; expression_contains_setvar(B,Variable)).
6309 expression_contains_setvar_aux(couple(A,B),Variable) :- !,
6310 (expression_contains_setvar(A,Variable) -> true ; expression_contains_setvar(B,Variable)).
6311 % the rest via safe_syntaxelement:
6312 expression_contains_setvar_aux(Expr,V) :-
6313 safe_syntaxelement_det(Expr,Subs,_Names,_,_),!,
6314 ? member(Sub,Subs), expression_contains_setvar(Sub,V),!.
6315 expression_contains_setvar_aux(E,V) :- add_internal_error('Illegal Expression: ', expression_contains_setvar_aux(E,V)),
6316 contains_var(V,E).
6317
6318 value_contains_setvar(Val,V) :- var(Val),!,Val==V.
6319 value_contains_setvar(avl_set(_),_V) :- !, fail. % assume avl_set always properly grounded; avoid looking inside
6320 value_contains_setvar(closure(_,_,Body),V) :- !,
6321 expression_contains_setvar(Body,V).
6322 value_contains_setvar(int(_),_) :- !,fail. % we check for set variables
6323 value_contains_setvar(global_set(_),_) :- !,fail. % we check for set variables
6324 value_contains_setvar(freetype(_),_) :- !,fail. % we check for set variables
6325 value_contains_setvar(freeval(_ID,_Case,Val),V) :- !, value_contains_setvar(Val,V).
6326 value_contains_setvar(string(_),_) :- !,fail. % we check for set variables
6327 value_contains_setvar(fd(_,_),_) :- !,fail. % we check for set variables
6328 value_contains_setvar((A,B),V) :- !, (value_contains_setvar(A,V) ; value_contains_setvar(B,V)).
6329 value_contains_setvar([A|B],V) :- !, (value_contains_setvar(A,V) ; value_contains_setvar(B,V)).
6330 value_contains_setvar(Val,V) :-
6331 contains_var(V,Val).
6332
6333 % ------------------