1 % (c) 2009-2024 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 :- module(kernel_objects,[basic_type/2,
6 enumerate_basic_type/2, enumerate_basic_type_wf/3, enumerate_basic_type_wf/4,
7 all_objects_of_type/2,
8 max_cardinality/2,
9 enumerate_type/3, % last argument basic or tight
10 enumerate_type_wf/4,
11 enumerate_type/4, % last argument false/true disables/enables enum warning
12 enumerate_basic_type/3,
13 enumerate_tight_type/2, enumerate_tight_type/3, enumerate_tight_type_wf/4,
14 enumerate_int/3,
15 gen_enum_warning_wf/6,
16 all_strings_wf/2, is_string/2, is_not_string/1,
17
18 top_level_dif/2,
19 equal_object_optimized/2, equal_object_optimized/3, equal_object_optimized_wf/4,
20 equal_object/2, equal_object/3, equal_object_wf/3, equal_object_wf/4,
21 not_equal_object/2, not_equal_object_wf/3,
22 equal_cons/3, equal_cons_wf/4, equal_cons_lwf/5,
23 get_next_element/3,
24 is_marked_to_be_computed/1, mark_as_to_be_computed/1,
25
26 %equality_objects/3,
27 membership_test_wf/4,
28
29 %is_a_set/1,
30 empty_set/1, empty_set_wf/2,
31 not_empty_set/1, not_empty_set_wf/2,
32 exact_element_of/2,
33 check_element_of/2, check_element_of_wf/3,
34 not_element_of/2, not_element_of_wf/3,
35
36 add_element/3, add_element/4, add_element_wf/4, add_element_wf/5,
37 add_new_element_wf/4,
38 delete_element_wf/4,
39 %remove_element/3,
40 remove_element_wf/4,remove_element_wf/5,remove_element_wf_if_not_infinite_or_closure/6,
41 remove_exact_first_element/3,
42 check_no_duplicates_in_list/3,
43
44 partition_wf/3, not_partition_wf/3, test_partition_wf/4,
45 %all_different/2,
46 disjoint_sets/3, not_disjoint_sets/3,
47
48 union/3, union_wf/4, union_generalized/2, union_generalized_wf/3,
49 intersection/3, intersection_generalized_wf/4,
50 difference_set/3, difference_set_wf/4,
51 in_difference_set_wf/4, not_in_difference_set_wf/4,
52 in_union_set_wf/4, not_in_union_set_wf/4,
53 in_intersection_set_wf/4, not_in_intersection_set_wf/4,
54
55 strict_subset_of/2, strict_subset_of_wf/3,
56 check_subset_of/2, check_subset_of_wf/3, check_finite_subset_of_wf/3,
57 check_non_empty_subset_of_wf/3, check_finite_non_empty_subset_of_wf/3,
58 not_subset_of/2, not_subset_of_wf/3, not_both_subset_of/5,
59 not_finite_subset_of_wf/3,
60 not_strict_subset_of/2, not_strict_subset_of_wf/3,
61 not_non_empty_subset_of_wf/3, not_non_empty_finite_subset_of_wf/3,
62 both_global_sets/4,check_subset_of_global_sets/2, check_not_subset_of_global_sets/2,
63
64 first_of_pair/2, second_of_pair/2,
65 minimum_of_set_extension_list/4,
66 maximum_of_set_extension_list/4,
67 minimum_of_set/4, maximum_of_set/4,
68 is_finite_set_wf/2, is_infinite_set_wf/2, test_finite_set_wf/3,
69 %finite_cardinality_as_int/3, % now we use kernel_cardinality_attr
70 cardinality_as_int_for_wf/2,
71 cardinality_as_int_wf/3,
72 cardinality_as_int/2, %cardinality_peano_wf/3,
73 card_convert_int_to_peano/2,
74 same_cardinality_wf/3,
75 % card_geq/2,
76 cardinality_greater/5, cardinality_greater_equal/5,
77 cardinality_of_range/3,
78 cardinality_of_set_extension_list/3,
79
80 cartesian_product_wf/4,
81 is_cartesian_pair_wf/4, not_is_cartesian_pair/4,
82
83 power_set/2, non_empty_power_set/2,
84
85 % is_boolean/1, %is_not_boolean/1,
86 is_integer/2, is_not_integer/1,
87 is_natural/2, is_natural1/2,
88 is_implementable_int/2,is_implementable_nat/2, is_implementable_nat1/2,
89 is_not_natural/1, is_not_natural1/1,
90 is_not_implementable_int/1,is_not_implementable_nat/1, is_not_implementable_nat1/1,
91
92 less_than/2, less_than_equal/2,
93 less_than_direct/2, less_than_equal_direct/2,
94 safe_less_than_equal/2, safe_less_than_equal/3,
95 safe_pow2/2, safe_mul/3, safe_add/3, safe_pown/3,
96 greater_than/2, greater_than_equal/2,
97 int_plus/3,
98 division/5, floored_division/5,
99 modulo/5,
100 int_minus/3, unary_minus_wf/3,
101 % nat_range/3, % removed
102 in_nat_range_wf/4, not_in_nat_range/3, not_in_nat_range_wf/4, test_in_nat_range_wf/5,
103 in_nat_range/3, % version without enumeration
104 times/3, square/3,
105 int_power/5,
106 % pred/2, succ/2, removed
107 integer_global_set/1,
108
109 element_of_global_set/2,element_of_global_set_wf/3,not_element_of_global_set/2,
110
111 exhaustive_kernel_check/1, exhaustive_kernel_check_wf/2, exhaustive_kernel_check_wf/3,
112 exhaustive_kernel_check_wfdet/2, exhaustive_kernel_check_wf_upto/3,
113 exhaustive_kernel_succeed_check/1, exhaustive_kernel_fail_check/1,
114 exhaustive_kernel_fail_check_wf/2, exhaustive_kernel_fail_check_wfdet/2,
115 exhaustive_kernel_fail_check_wf_upto/3,
116 exhaustive_kernel_fail_check_wfinit/2,
117 exhaustive_kernel_check/2, exhaustive_kernel_succeed_check/2, exhaustive_kernel_fail_check/2,
118
119 singleton_set_element/4, singleton_set_element_wd/4,
120 infer_value_type/2,
121 contains_any/1
122 ]).
123
124 :- meta_predicate exhaustive_kernel_check_opt(-,0).
125 :- meta_predicate exhaustive_kernel_fail_check_opt(-,0).
126 :- meta_predicate not_strict_eq_check(-,0).
127
128 %:- use_module('../extensions/profiler/profiler.pl').
129 %:- use_module('../extensions/profiler/profiler_te.pl').
130 %:- enable_profiling(enumerate_basic_type/3).
131 %:- enable_profiling(enumerate_type/3).
132 %:- enable_profiling(enumerate_tight_type/2).
133
134 %:- print(loading_kernel_objects),nl.
135
136 %:- multifile user:portray_message/2.
137 %user:portray_message(informational, _).
138 :- use_module(library(terms)).
139 :- use_module(self_check).
140
141 :- use_module(debug).
142 :- use_module(tools_printing).
143 :- use_module(tools).
144
145 :- use_module(module_information,[module_info/2]).
146 :- module_info(group,kernel).
147 :- module_info(description,'This module provides operations for the basic datatypes of ProB (equal, not_equal, enumeration).').
148
149 :- use_module(typechecker).
150 :- use_module(error_manager).
151 :- use_module(b_global_sets). %,[global_type/2, b_global_set_cardinality/2, b_empty_global_set/1]).
152 :- use_module(kernel_waitflags).
153 :- use_module(library(lists)).
154 :- use_module(library(avl),[avl_min/2, avl_max/2]).
155 :- use_module(library(clpfd)).
156 :- use_module(fd_utils_clpfd).
157 :- use_module(kernel_freetypes).
158 :- use_module(custom_explicit_sets).
159 :- use_module(typechecker).
160 %:- use_module(clpfd_off_interface). %
161 % on a 32 bit system: use clpfd_off_interface; on 64 bit system clpfd_interface should be ok (integer overflows)
162 :- use_module(clpfd_interface). %
163 :- use_module(bsyntaxtree, [get_texpr_id/2, get_texpr_pos/2]).
164
165 :- type atomic_type +--> (term(integer,[]) ; term(string,[]) ; constant(list(atomic)) ; abort ; boolean ; global(atomic)).
166 :- type atomic_any_type +--> (type(atomic_type) ; term(any,[]) ).
167 :- type basic_type_descriptor +--> (type(atomic_any_type) ; set(basic_type_descriptor) ;
168 seq(basic_type_descriptor) ;
169 couple(basic_type_descriptor,basic_type_descriptor) ;
170 record(list(type(field_type))) ;
171 freetype(atomic)).
172
173 :- type inferred_basic_type_descriptor +--> (var ; type(atomic_type) ; set(inferred_basic_type_descriptor) ;
174 seq(inferred_basic_type_descriptor) ;
175 couple(inferred_basic_type_descriptor,inferred_basic_type_descriptor)).
176
177 :- type fd_index +--> (integer ; var).
178 :- type fd_set +--> (atomic ; var).
179 :- type fd_term +--> fd(fd_index,fd_set).
180 :- type bsets_integer +--> int((integer ; var)).
181 :- type bsets_string +--> string((atomic ; var)).
182 :- type bsets_bool +--> (pred_false /* bool_false */ ; pred_true /* bool_true */).
183 :- type field_type +--> field(atomic,basic_type_descriptor).
184
185 %:- type bsets_sequence +--> (nil_seq ; cons(type(bsets_object),type(bsets_sequence))).
186 %:- type bsets_set +--> vlist(type(bsets_object)).
187 :- functor([_|_],ListFunctor,_),
188 (type bsets_set +--> (term([],[]) ; var ; term(ListFunctor,[type(bsets_object),type(bsets_set)]) ;
189 avl_set( ground ) ;
190 closure(list(type(variable_id)),
191 list(type(basic_type_descriptor)),type(boolean_expression))
192 ; closure_x(list(type(variable_id)),
193 list(type(basic_type_descriptor)),type(boolean_expression),any))).
194 :- type bsets_couple +--> term(',',[type(bsets_object),type(bsets_object)]).
195 :- type bsets_global +--> global_set((atomic ; var)).
196 :- type bsets_field +--> field(atomic,type(bsets_object)).
197 :- type bsets_record +--> rec((var ; list(bsets_field))).
198 :- type bsets_freetype +--> freeval(atomic,(atomic ; var),type(bsets_object)).
199
200 :- type bsets_object +--> (fd_term ; bsets_integer ; bsets_bool ; term(term,[any]) ; bsets_set ;
201 % abort(any) ; % deprecated
202 bsets_couple ; bsets_string ; bsets_global ; var;
203 bsets_record ; bsets_freetype).
204
205
206 :- assert_must_succeed(kernel_waitflags:set_silent(true)). % disable waitflag store not init msgs
207
208
209
210
211 % a predicate to exhaustively check a kernel predicate with all possible modes
212
213 :- use_module(tools_timeout,[time_out_call/1]).
214 exhaustive_kernel_check_opt(C,Cond) :- (Cond -> exhaustive_kernel_check(C) ; true).
215 exhaustive_kernel_check(C) :- exhaustive_kernel_check4([],C,true,true).
216 exhaustive_kernel_check(Opts,C) :- exhaustive_kernel_check4(Opts,C,true,true).
217 exhaustive_kernel_check_wf(C,WF) :- exhaustive_kernel_check_wf([],C,WF).
218 exhaustive_kernel_check_wf(Opts,C,WF) :-
219 exhaustive_kernel_check4(Opts,C,kernel_waitflags:init_wait_flags(WF),
220 kernel_waitflags:ground_wait_flags(WF)).
221 exhaustive_kernel_check_wfdet(C,WF) :-
222 exhaustive_kernel_check4([],C,kernel_waitflags:init_wait_flags(WF),
223 kernel_waitflags:ground_det_wait_flag(WF)).
224 exhaustive_kernel_check_wf_upto(C,WF,Limit) :-
225 exhaustive_kernel_check4([],C,kernel_waitflags:init_wait_flags(WF),
226 (kernel_waitflags:ground_wait_flag_to(WF,Limit),
227 kernel_waitflags:portray_waitflags(WF))).
228
229 exhaustive_kernel_check4(Opts,Call,Pre,Post) :- enumerate_kernel_call(Call,Opts,ECall,Code),
230 debug_println(9,exhaustive_kernel_check(ECall,Code)),
231 flatten_call((Pre,ECall,Code,Post),FullCall),
232 must_succeed_without_residue_and_time_out(FullCall), debug_println(9,ok),
233 fail.
234 exhaustive_kernel_check4(_,_,_,_).
235
236 flatten_call((A,B),Res) :- !,flatten_call(A,FA), flatten_call(B,FB), conjoin_call(FA,FB,Res).
237 flatten_call(Module:Call,Res) :- !, flatten_call(Call,F), Res=Module:F.
238 flatten_call(X,X).
239
240 conjoin_call(true,X,R) :- !,R=X.
241 conjoin_call(X,true,R) :- !, R=X.
242 conjoin_call(X,Y,(X,Y)).
243
244 exhaustive_kernel_succeed_check(C) :- exhaustive_kernel_succeed_check([],C).
245 exhaustive_kernel_succeed_check(Opts,Call) :- enumerate_kernel_call(Call,Opts,ECall,Code),
246 debug_println(9,exhaustive_kernel_succeed_check(ECall,Code)),
247 flatten_call((ECall,Code),FullCall),
248 time_out_call(must_succeed(FullCall)),debug_println(9,ok),
249 fail.
250 exhaustive_kernel_succeed_check(_,_).
251
252 exhaustive_kernel_fail_check_opt(C,Cond) :- (Cond -> exhaustive_kernel_fail_check(C) ; true).
253 exhaustive_kernel_fail_check(C) :- exhaustive_kernel_fail_check4([],C,true,true).
254 exhaustive_kernel_fail_check(Opts,C) :- exhaustive_kernel_fail_check4(Opts,C,true,true).
255 exhaustive_kernel_fail_check_wf(C,WF) :-
256 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF),
257 kernel_waitflags:ground_wait_flags(WF)).
258 exhaustive_kernel_fail_check_wfdet(C,WF) :-
259 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF),
260 kernel_waitflags:ground_det_wait_flag(WF)).
261 exhaustive_kernel_fail_check_wf_upto(C,WF,Limit) :-
262 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF),
263 kernel_waitflags:ground_wait_flag_to(WF,Limit)).
264 exhaustive_kernel_fail_check_wfinit(C,WF) :-
265 exhaustive_kernel_fail_check4([],C,kernel_waitflags:init_wait_flags(WF), true).
266
267 exhaustive_kernel_fail_check4(Opts,Call,Pre,Post) :- enumerate_kernel_call(Call,Opts,ECall,Code),
268 debug_println(9,exhaustive_kernel_fail_check(ECall,Code)),
269 flatten_call((Pre,ECall,Code,Post),FullCall),
270 time_out_call(must_fail(FullCall)),debug_println(9,ok),
271 fail.
272 exhaustive_kernel_fail_check4(_,_,_,_).
273
274 % enumerate_kernel_call(Call, OptionList, NewCall, CodeAfter)
275 enumerate_kernel_call((A,B),Opts,(EA,EB),(CA,CB)) :- !,
276 enumerate_kernel_call(A,Opts,EA,CA), enumerate_kernel_call(B,Opts,EB,CB).
277 enumerate_kernel_call(Module:Call,Opts,Module:ECall,Code) :- !, enumerate_kernel_call(Call,Opts,ECall,Code).
278 enumerate_kernel_call(Call,Opts,ECall,Code) :- Call=..[KernelPred|CArgs],
279 (member(commutative,Opts)
280 -> (Args=CArgs ; CArgs=[A1,A2|T], Args=[A2,A1|T])
281 ; Args=CArgs
282 ),
283 l_enumerate_kernel_args(Args,EArgs,Code,KernelPred,1), ECall=..[KernelPred|EArgs].
284 l_enumerate_kernel_args([],[],true,_,_).
285 l_enumerate_kernel_args([H|T],[EH|ET],Code,KernelPred,Nr) :-
286 enumerate_kernel_args(H,EH,C1,KernelPred/Nr),
287 N1 is Nr+1,
288 l_enumerate_kernel_args(T,ET,C2,KernelPred,N1),
289 permute_code((C1,C2),Code).
290
291 permute_code((true,C),R) :- !,R=C.
292 permute_code((C,true),R) :- !, R=C.
293 permute_code((C1,C2),(C1,C2)).
294 permute_code((C1,C2),(C2,C1)).
295
296 enumerate_kernel_args(Var,Res,Code,_) :- var(Var),!, Res=Var, Code=true.
297 enumerate_kernel_args(X,Res,Code,KP_Nr) :- do_not_delay(X,KP_Nr),!, Res=X, Code=true.
298 enumerate_kernel_args(Arg,Arg,true,_). % just keep the argument
299 enumerate_kernel_args(Args,NewArg,Code,KP_Nr) :- arg_is_list(KP_Nr),!,
300 % we have a list of B expressions (e.g., in partition_wf)
301 (Code = '='(NewArg,Args) ; l_enumerate_kernel_args(Args,NewArg,Code,arg_is_list,1)).
302 enumerate_kernel_args(Arg,NewArg,Code,_) :- % delay the argument fully
303 (term_is_of_type(Arg,bsets_object,no)
304 -> Code = equal_object(NewArg,Arg,enumerate_kernel_args)
305 ; Code = '='(NewArg,Arg)).
306 enumerate_kernel_args(int(X),int(XX),Code,_) :- nonvar(X), Code = '='(X,XX). % delay setting number content
307 enumerate_kernel_args(string(X),string(XX),Code,_) :- nonvar(X), Code = '='(X,XX). % delay setting string content
308 enumerate_kernel_args(term(floating(X)),term(floating(XX)),Code,_) :- nonvar(X), Code = '='(X,XX). % delay setting real number content
309 enumerate_kernel_args((A,B),(AA,BB),(CodeA,CodeB),KP_Nr) :-
310 enumerate_kernel_args(A,AA,CodeA,KP_Nr),enumerate_kernel_args(B,BB,CodeB,KP_Nr),
311 (AA,BB) \== (A,B). % avoid re-generating case 3 above (just keep argument)
312 enumerate_kernel_args(freeval(ID,Case,A),freeval(ID,Case,AA),CodeA,KP_Nr) :-
313 enumerate_kernel_args(A,AA,CodeA,KP_Nr),
314 AA \== A. % avoid re-generating case 3 above (just keep argument)
315 enumerate_kernel_args([H|T],[H|NewT],Code,_) :- Code = equal_object(NewT,T). % delay tail
316 enumerate_kernel_args([H|T],[(int(NewI),H2)|T],Code,_) :- nonvar(H), % make index (e.g. of sequence) nonvar first
317 H = (II,H2), ground(II), II=int(I), \+ member((int(I),_),T), % the element is unique in domain
318 Code = '='(NewI,I).
319 enumerate_kernel_args([H|T],[(H1,NewH2)|T],Code,_) :- nonvar(H),
320 H = (H1,H2), ground(H2), \+ member((_,H2),T), % the element is unique in ragne
321 Code = equal_object(NewH2,H2).
322 enumerate_kernel_args([H|T],Res,Code,KP_Nr) :-
323 try_expand_and_convert_to_avl([H|T],AVL),
324 AVL \= [H|T], enumerate_kernel_args(AVL,Res,Code,KP_Nr).
325 enumerate_kernel_args([H|T],Res,Code,KP_Nr) :- ground([H|T]),generate_member_closure([H|T],Closure),
326 enumerate_kernel_args(Closure,Res,Code,KP_Nr).
327
328 % check if an argument is a list not a set.
329 arg_is_list(KernelPred/Nr) :- argument_is_list_not_set(KernelPred,Nr).
330 %arg_is_not_list(KernelPred/Nr) :- \+ argument_is_list_not_set(KernelPred,Nr).
331 argument_is_list_not_set(partition_wf,2).
332 argument_is_list_not_set(not_partition_wf,2).
333 argument_is_list_not_set(test_partition_wf,2).
334 argument_is_list_not_set(disjoint_union_generalized_wf,1).
335
336 do_not_delay(b(_,_,_),_). % do not delay instantiation B predicates and expressions
337 do_not_delay(global_set(G),KP/ArgNr) :- custom_explicit_sets:is_infinite_global_set(G,_),
338 do_not_delay_arg(KP,ArgNr).
339 % these arguments cause difficulty if infinite sets are delayed (i.e., instantiated later)
340 do_not_delay_arg(partial_function_wf,2).
341 do_not_delay_arg(partial_function_wf,3).
342 do_not_delay_arg(subset_test,2).
343 do_not_delay_arg(subset_strict_test,2).
344
345 generate_member_closure(ExplicitSet,closure(['_zzzz_unit_tests'],[Type],Pred)) :-
346 infer_type(ExplicitSet,set(Type)),
347 Pred =
348 b(member(b(identifier('_zzzz_unit_tests'),Type,[generated]),
349 b(value(ExplicitSet),set(Type),[])),pred,[]).
350
351 infer_type(Value,Type) :- (infer_value_type(Value,Type)
352 -> true %,print(inferred(Type,Value)),nl
353 ; print('### Could not infer type: '), print(Value),nl,fail).
354
355 :- use_module(btypechecker,[couplise_list/2]).
356 infer_value_type(Var,Type) :- var(Var),!,Type=any.
357 infer_value_type([],set(any)).
358 infer_value_type([H|T],set(ResType)) :- infer_value_type(H,Type),
359 ((contains_any(Type),T=[H2|_], % try H2; maybe we can infer a better type here
360 infer_value_type(H2,Type2), \+ contains_any(Type2))
361 -> ResType = Type2
362 ; ResType = Type).
363 infer_value_type(avl_set(node(H,_True,_,_,_)),set(Type)) :- infer_value_type(H,Type).
364 infer_value_type(int(_),integer).
365 infer_value_type(string(_),string).
366 infer_value_type((A,B),couple(TA,TB)) :- infer_value_type(A,TA), infer_value_type(B,TB).
367 infer_value_type(fd(_,T),global(T)).
368 infer_value_type(pred_true /* bool_true */,boolean).
369 infer_value_type(pred_false /* bool_false */,boolean).
370 infer_value_type(rec(Fields),record(FieldTypes)) :- infer_field_types(Fields,FieldTypes).
371 infer_value_type(freeval(Id,_Case,_Val),freetype(Id)).
372 infer_value_type(closure(_,Types,_),set(Res)) :- couplise_list(Types,Res).
373 infer_value_type(global_set('STRING'),R) :- !, R=set(string). % what if Event-B/TLA have a deferred set of that name
374 infer_value_type(global_set('FLOAT'),R) :- !, R=set(real).
375 infer_value_type(global_set('REAL'),R) :- !, R=set(real).
376 infer_value_type(global_set(X),R) :- b_integer_set(X),!,R=set(integer).
377 ?infer_value_type(global_set(Name),set(global(Name))) :- b_global_set(Name).
378 infer_value_type(term(floating(_)),real). % see kernel_reals:is_real(.)
379
380 infer_field_types([],[]).
381 infer_field_types([field(Name1,Val)|T],[field(Name1,VT)|TT]) :-
382 infer_value_type(Val,VT),
383 infer_field_types(T,TT).
384
385 contains_any(any).
386 contains_any(couple(A,B)) :- (contains_any(A) -> true ; contains_any(B)).
387 contains_any(set(A)) :- contains_any(A).
388 % to do: fields
389
390 :- assert_pre(kernel_objects:basic_type(Obj,Type), (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
391 :- assert_post(kernel_objects:basic_type(Obj,_), type_check(Obj,bsets_object)).
392
393 %:- block basic_type(-,-).
394
395 basic_type(FD,global(T)) :- !, global_type(FD,T). % will set up CLP(FD) domain for X
396 % TO DO: Also: what about global(T) inside other structures (pairs) ?
397 basic_type(Rec,record(FieldTypes)) :- !, Rec=rec(Fields),
398 ? basic_field_types(Fields,FieldTypes).
399 %basic_type(Set,set(Type)) :- !, basic_type_set(Type,Set,inf).
400 basic_type(_X,_TY). %basic_type2(TY,X) %basic_symbreak(TY,X)
401 %print(ignore_basic_type(X,Y)),nl %, basic_type2(TY,X) %%STILL REQUIRED ?????
402
403 basic_field_types([],[]).
404 basic_field_types([field(Name1,Val)|T],[field(Name2,VT)|TT]) :-
405 check_field_name_compatibility(Name1,Name2,basic_field_types2),
406 ? basic_type(Val,VT),basic_field_types(T,TT).
407
408
409
410 /* ------------------------- */
411 /* enumerate_basic_type/2 */
412 /* ------------------------- */
413 /* a version of basic_type that enumerates */
414
415 :- assert_must_succeed(enumerate_basic_type([],set(couple(integer,integer)) )).
416 :- assert_must_succeed(enumerate_basic_type([([],int(2)), ([int(3)],int(4))],
417 set(couple(set(integer),integer)) )).
418 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
419 set(couple(integer,integer)) )).
420 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
421 seq(integer) )).
422 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
423 seq(integer) )).
424 :- assert_must_succeed((enumerate_basic_type(X,global('Name')),
425 equal_object(X,fd(1,'Name')) )).
426 :- assert_must_succeed((enumerate_basic_type(X,global('Name')),
427 equal_object(X,fd(2,'Name')) )).
428 :- assert_must_succeed((enumerate_basic_type(X,global('Name')),
429 X==fd(2,'Name')) ).
430 :- assert_must_succeed((enumerate_basic_type(X,record([field(a,global('Name'))])),
431 equal_object(X,rec([field(a,fd(1,'Name'))])) )).
432 :- assert_must_succeed((enumerate_basic_type(X,record([field(a,integer),field(b,global('Name'))])),
433 equal_object(X,rec([field(a,int(1)),field(b,fd(1,'Name'))])) )).
434 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc1,[case(a,constant([a])),case(b,integer)]),
435 kernel_freetypes:set_freetype_depth(2),
436 enumerate_basic_type(X,freetype(selfc1)),equal_object(X,freeval(selfc1,a,term(a))),
437 kernel_freetypes:reset_freetypes)).
438 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc5,[case(a,constant([a])),case(b,integer)]),
439 kernel_freetypes:set_freetype_depth(2),
440 enumerate_basic_type(X,freetype(selfc5)),equal_object(X,freeval(selfc5,b,int(1))),
441 kernel_freetypes:reset_freetypes)).
442 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc7,[case(nil,constant([nil])),case(node,couple(freetype(selfc7),freetype(selfc7)))]),
443 kernel_freetypes:set_freetype_depth(3),
444 findall(X,enumerate_basic_type(X,freetype(selfc7)),Solutions),
445 length(Solutions,5),
446 kernel_freetypes:reset_freetypes)).
447 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc2,[case(a,constant([a])),case(b,freetype(selfc3))]),
448 kernel_freetypes:add_freetype(selfc3,[case(c,constant([c])),case(d,freetype(selfc2))]),
449 kernel_freetypes:set_freetype_depth(4),
450 enumerate_basic_type(X,freetype(selfc2)),
451 equal_object(X,freeval(selfc2,b,freeval(selfc3,d,freeval(selfc2,b,freeval(selfc3,c,term(c)))))),
452 kernel_freetypes:reset_freetypes)).
453 :- assert_must_succeed((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
454 equal_object(X,[(fd(1,'Name'),fd(1,'Code'))])) ).
455 :- assert_must_succeed((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
456 equal_object(X,[(fd(2,'Name'),fd(1,'Code')), (fd(1,'Name'),fd(2,'Code'))])) ).
457 :- assert_must_succeed((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
458 equal_object(X,[(fd(1,'Name'),fd(2,'Code')), (fd(2,'Name'),fd(1,'Code'))])) ).
459 :- assert_must_succeed_any((enumerate_basic_type(X,set(couple(global('Name'),global('Code'))) ),
460 equal_object(X,[(fd(1,'Name'),fd(2,'Code')), (fd(2,'Name'),fd(1,'Code'))])) ).
461 :- assert_must_succeed(enumerate_basic_type([(int(2),(int(1),int(2))),
462 (int(1),(int(3),int(4)))],
463 set(couple(integer,couple(integer,integer))) )).
464 :- assert_must_succeed(enumerate_basic_type([(int(2),(int(1),int(2))),
465 (int(55),(int(3),int(4)))],
466 set(couple(integer,couple(integer,integer))) )).
467 :- assert_must_succeed(enumerate_basic_type([term('err')],set(constant([err])))).
468 :- assert_must_succeed(enumerate_basic_type([(int(1),int(2)),(int(3),int(4))],
469 set(couple(integer,integer)))).
470
471 :- assert_must_succeed_multiple(enumerate_basic_type([(int(2),fd(_A,'Name')),(int(3),fd(_B,'Name')),
472 (int(4),fd(_C,'Name')),(int(5),fd(_D,'Name')),(int(6),fd(_E,'Name')),(int(7),fd(_F,'Name')),
473 (int(8),fd(_G,'Name')),(int(9),fd(_H,'Name')),(int(10),fd(_I,'Name')),
474 (int(11),fd(_,'Name')),(int(12),fd(_,'Name')),(int(13),fd(_,'Name')),
475 (int(14),fd(_,'Name'))],set(couple(integer,global('Name'))))).
476
477 :- assert_must_fail(( findall(XX,enumerate_basic_type(XX, set(set(global('Code')))) ,S), member(X,S), remove(S,X,R), member(X2,R), equal_object(X,X2) )).
478
479 :- assert_must_succeed(( enumerate_basic_type(global_set('Code'),
480 set(global('Code'))) )).
481
482 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([(fd(1,'Name'),fd(2,'Code')), (fd(2,'Name'),fd(1,'Code'))],set(couple(global('Name'),global('Code')))))).
483 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([(fd(1,'Name'),pred_true), (fd(2,'Name'),pred_false), (fd(2,'Name'),pred_true)],set(couple(global('Name'),boolean))))).
484 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([pred_true,pred_false],set(boolean)))).
485 :- assert_must_succeed(exhaustive_kernel_succeed_check(enumerate_basic_type([[],[pred_true,pred_false]],set(set(boolean))))).
486
487 :- assert_pre(kernel_objects:enumerate_basic_type(Obj,Type),
488 (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
489 :- assert_post(kernel_objects:enumerate_basic_type(Obj,_), (type_check(Obj,bsets_object),ground_check(Obj))).
490
491 enumerate_basic_type_wf(Obj,Type,WF) :-
492 ? enumerate_basic_type_wf(Obj,Type,enumerate_basic_type,WF).
493 :- block enumerate_basic_type_wf(?,-,?,?).
494 enumerate_basic_type_wf(Obj,Type,EnumWarning,WF) :-
495 ? enumerate_basic_type4(Type,Obj,basic,trigger_true(EnumWarning),WF). % add WF context info
496
497 :- block enumerate_basic_type(?,-).
498 enumerate_basic_type(Obj,Type) :-
499 %enumerate_basic_type2(Obj,Type).
500 enumerate_basic_type4(Type,Obj,basic,trigger_true(enumerate_basic_type),no_wf_available).
501 %(ground(Obj) -> true ; enumerate_basic_type3(Type,Obj,basic)).
502
503 :- block enumerate_basic_type(?,-,-).
504 enumerate_basic_type(Obj,Type,EnumWarning) :-
505 ? enumerate_basic_type4(Type,Obj,basic,EnumWarning,no_wf_available).
506
507
508 :- block enumerate_type(?,-,?). % last argument: basic or tight
509 enumerate_type(Obj,Type,Tight) :-
510 %enumerate_basic_type2(Obj,Type).
511 enumerate_basic_type4(Type,Obj,Tight,trigger_true(enumerate_type_3),no_wf_available).
512
513 :- block enumerate_type(?,-,?,?), enumerate_type(?,?,?,-).
514 enumerate_type(Obj,Type,Tight,EnumWarning) :-
515 enumerate_basic_type4(Type,Obj,Tight,EnumWarning,no_wf_available).
516
517 enumerate_type_wf(Obj,Type,Tight,WF) :-
518 ? enumerate_type_wf(Obj,Type,Tight,trigger_true(enumerate_type_wf),WF).
519
520 :- block enumerate_type_wf(?,-,?,?,?), enumerate_type_wf(?,?,?,-,?).
521 enumerate_type_wf(Obj,Type,Tight,EnumWarning,WF) :-
522 ? enumerate_basic_type4(Type,Obj,Tight,EnumWarning,WF).
523
524 %enumerate_basic_type2(X,Type) :-
525 % (ground(X) -> (basic_type(X,Type) -> true
526 % ; add_internal_error('Type error: ',enumerate_basic_type2(X,Type)))
527 % ; enumerate_basic_type3(Type,X)).
528
529 enumerate_basic_type4(global(T),R,_Tight,EnumWarning,WF) :-
530 ? enumerate_global_type_with_enum_warning(R,T,EnumWarning,WF).
531 enumerate_basic_type4(set(X),Set,Tight,EnumWarning,WF) :-
532 ? enumerate_basic_type_set(Set,X,Tight,EnumWarning,WF).
533 enumerate_basic_type4(seq(SeqRanType),Seq,Tight,EnumWarning,WF) :-
534 ? (Tight = tight -> enumerate_seq_type_wf(Seq,SeqRanType,EnumWarning,WF) % might trigger warning. push flag.
535 ; enumerate_basic_type4(set(couple(integer,SeqRanType)),Seq,basic,EnumWarning,WF)).
536 enumerate_basic_type4(couple(XT,YT),(X,Y),Tight,EnumWarning,WF) :-
537 ? enumerate_type_wf(X,XT,Tight,EnumWarning,WF),
538 ? enumerate_type_wf(Y,YT,Tight,EnumWarning,WF).
539 ?enumerate_basic_type4(boolean,B,_Tight,_EnumWarning,_WF) :- enumerate_bool(B).
540 ?enumerate_basic_type4(real,R,_Tight,EnumWarning,WF) :- enumerate_real_wf(R,EnumWarning,WF).
541 ?enumerate_basic_type4(string,string(S),_Tight,EnumWarning,WF) :- enumerate_string_wf(S,EnumWarning,WF).
542 enumerate_basic_type4(constant([V]),term(V),_Tight,_EnumWarning,_WF).
543 enumerate_basic_type4(record(FT),rec(F),Tight,EnumWarning,WF) :-
544 ? enumerate_basic_field_types(F,FT,Tight,EnumWarning,WF).
545 enumerate_basic_type4(freetype(Id),freeval(Id2,C,Value),Tight,EnumWarning,WF) :-
546 (Id=Id2 -> true
547 ; add_internal_error('Freetypes do not match:',enumerate_basic_type4(freetype(Id),freeval(Id2,C,Value),Tight,_,_))),
548 (ground_value(freeval(Id2,C,Value)) -> true
549 ; (is_recursive_freetype(Id),
550 max_freetype_enum_depth(Depth)
551 -> gen_enum_warning_wf(Id,0:inf,0:Depth,EnumWarning,unknown,WF)
552 ; true),
553 ? enumerate_freetype_wf(Tight,freeval(Id,C,Value),freetype(Id),WF)
554 ).
555 enumerate_basic_type4(freetype_lim_depth(Id,Depth),freeval(Id2,C,Value),Tight,_EnumWarning,WF) :-
556 (Id=Id2 -> true
557 ; add_internal_error('Freetypes do not match:',enumerate_basic_type4(freetype_lim_depth(Id,Depth),freeval(Id2,C,Value),Tight,_,_))),
558 % freetype_lim_depth is created artificially by enumerate_freetype
559 ? enumerate_freetype_wf(Tight,freeval(Id,C,Value),freetype_lim_depth(Id,Depth),WF).
560 enumerate_basic_type4(integer,int(N),Tight,EnumWarning,WF) :-
561 ? (nonvar(N)
562 -> (integer(N) -> true
563 ; add_internal_error('Illegal value:',enumerate_basic_type4(integer,int(N),Tight,EnumWarning,WF))
564 )
565 ? ; enumerate_int_with_span(N,EnumWarning,unknown,WF)).
566 enumerate_basic_type4(abort,V,Tight,EnumWarning,WF) :-
567 add_internal_error(deprecated_abort_type,enumerate_basic_type4(abort,V,Tight,EnumWarning,WF)).
568 enumerate_basic_type4(constant,V,Tight,EnumWarning,WF) :-
569 add_internal_error(deprecated_abort_type,enumerate_basic_type4(constant,V,Tight,EnumWarning,WF)).
570 enumerate_basic_type4(any,Obj,_Tight,EnumWarning,WF) :- enumerate_any_wf(Obj,EnumWarning,WF).
571
572 :- use_module(library(random),[random/3]).
573 enumerate_bool(X) :- preferences:preference(randomise_enumeration_order,true),
574 random(1,3,1),!,
575 (X=pred_false ; X=pred_true).
576 enumerate_bool(pred_true). /* was bool_true */
577 enumerate_bool(pred_false).
578
579 max_cardinality_string(inf). % was 2
580 all_strings_wf(AS,WF) :- findall(string(S),enumerate_string_wf(S,trigger_throw(all_strings),WF),AS).
581 :- use_module(btypechecker,[machine_string/1]).
582 enumerate_string_wf(S,_EnumWarning,_WF) :- atomic(S),!.
583 enumerate_string_wf(S,EnumWarning,WF) :- %print('### WARNING, Enumerating STRING'),nl,
584 % frozen(S,Goal), print(enum(S,Goal)),nl,
585 % MAYBE TO DO: we could check if prolog:dif(S,'"STR1"') are in frozen Goal and then enumerate more?
586 % if we do this we need to adapt dont_expand(global('STRING')) :- ... further below
587 gen_enum_warning_wf('STRING',inf,'"STRING1","STRING2",...',EnumWarning,unknown,WF),
588 (S = 'STRING1', \+ machine_string(S) % used to be '"STR1"'
589 ; S = 'STRING2', \+ machine_string(S) % used to be '"STR2"'
590 ? ; machine_string(S)).
591
592 is_string(string(_),_WF).
593 is_not_string(X) :- top_level_dif(X,string).
594
595
596 :- use_module(library(random),[random/3]).
597 :- use_module(kernel_reals,[is_ground_real/1, construct_real/2, is_real/2]).
598 enumerate_real_wf(S,_EnumWarning,_) :- is_ground_real(S),!.
599 enumerate_real_wf(S,EnumWarning,WF) :-
600 gen_enum_warning_wf('REAL',inf,'"0.0","1.0",...',EnumWarning,unknown,WF),
601 ( construct_real('0.0',S)
602 ; construct_real('1.0',S)
603 ; construct_real('-1.0',S)
604 ; random(0.0,1.0,R), is_real(S,R)
605 ; random(-1.0,0.0,R), is_real(S,R)
606 ; preferences:preference(maxint,MaxInt), random(1.0,MaxInt,R), is_real(S,R)
607 ; preferences:preference(minint,MinInt), random(MinInt,-1.0,R), is_real(S,R)
608 ).
609
610
611 :- block enumerate_any_wf(-,?,?).
612 enumerate_any_wf(fd(X,T),EnumWarning,WF) :- !,
613 when(nonvar(T),enumerate_global_type_with_enum_warning(fd(X,T),T,EnumWarning,WF)).
614 enumerate_any_wf(int(N),EnumWarning,WF) :- !,enumerate_basic_type4(integer,int(N),basic,EnumWarning,WF).
615 enumerate_any_wf(term(X),_EnumWarning,_WF) :- !, print_message(could_not_enumerate_term(X)).
616 enumerate_any_wf(string(S),EnumWarning,WF) :- !, enumerate_string_wf(S,EnumWarning,WF).
617 enumerate_any_wf(pred_true /* bool_true */,_EnumWarning,_WF) :- !.
618 enumerate_any_wf(pred_false /* bool_false */,_EnumWarning,_WF) :- !.
619 enumerate_any_wf([],_EnumWarning,_WF) :- !.
620 enumerate_any_wf([H|T],EnumWarning,WF) :- !, enumerate_any_wf(H,EnumWarning,WF), enumerate_any_wf(T,EnumWarning,WF).
621 enumerate_any_wf(avl_set(_),_EnumWarning,_WF) :- !.
622 enumerate_any_wf(global_set(_),_EnumWarning,_WF) :- !.
623 enumerate_any_wf((H,T),EnumWarning,WF) :- !, enumerate_any_wf(H,EnumWarning,WF), enumerate_any_wf(T,EnumWarning,WF).
624 enumerate_any_wf(rec(Fields),EnumWarning,WF) :- !, enumerate_any_wf(Fields,EnumWarning,WF).
625 enumerate_any_wf(field(_,V),EnumWarning,WF) :- !, enumerate_any_wf(V,EnumWarning,WF).
626 % we could support: closure values...
627 enumerate_any_wf(T,_EnumWarning,_WF) :- add_message(enumerate_any_wf,'Could_not_enumerate value: ',T).
628
629
630 :- use_module(preferences,[preference/2]).
631
632 % enumerate an INTEGER variable
633 enumerate_int_with_span(N,EnumWarning,Span,WF) :-
634 clpfd_domain(N,FDLow,FDUp), % print(enum(N,FDLow,FDUp)),nl,
635 (finite_domain(FDLow,FDUp)
636 ? -> label(N,FDLow,FDUp)
637 ? ; enum_unbounded(FDLow,FDUp,N,EnumWarning,Span,WF)
638 ).
639 label(N,FDLow,FDUp) :-
640 gen_enum_warning_if_large(N,FDLow,FDUp),
641 ? clpfd_interface:clpfd_randomised_labeling([],[N]).
642 % Note: CLP(FD) labeling does not necessarily try all values in range (disjunctive domains)
643
644 % when in CLP(FD) mode; try and do a case-split and see if that narrows down the possible ranges
645 enum_unbounded(X,Y,N,EnumWarning,Span,WF) :- preferences:preference(use_clpfd_solver,true),!,
646 ? enum_unbounded_clp(X,Y,N,EnumWarning,Span,WF).
647 enum_unbounded(X,Y,N,EnumWarning,Span,WF) :- %frozen(N,G), print(frozen(N,G,X,Y,EnumWarning)),nl,
648 clpfd_off_domain(N,X,Y,NX,NY),
649 ? (finite_domain(NX,NY) -> enumerate_int1(N,NX,NY)
650 ; enum_unbounded_clpfd_off(NX,NY,N,EnumWarning,Span,WF)).
651
652 enum_unbounded_clpfd_off(_FDLow,_FDUp,N,_EnumWarning,_,_WF) :- is_wdguarded_result_variable(N),!.
653 enum_unbounded_clpfd_off(FDLow,FDUp,N,EnumWarning,Span,WF) :-
654 make_domain_finite(FDLow,FDUp,Min,Max),
655 gen_enum_warning_wf('INTEGER',FDLow:FDUp,Min:Max,EnumWarning,Span,WF),
656 enumerate_int1(N,Min,Max). % will also do a case split, but without posting constraints
657
658 % try to determine integer variable bounds from pending co-routines for CLPFD off mode
659 clpfd_off_domain(Var,Low,Up,NewLow,NewUp) :-
660 frozen(Var,Goal), narrow_down_interval(Goal,Var,Low,Up,NewLow,NewUp).
661 % ((Lowx,Up)==(NewLow,NewUp) -> true ; print(narrowed_down(Var,Low,Up,NewLow,NewUp)),nl).
662 narrow_down_interval((A,B),Var,Low,Up,NewLow,NewUp) :- !,
663 narrow_down_interval(A,Var,Low,Up,Low1,Up1),
664 narrow_down_interval(B,Var,Low1,Up1,NewLow,NewUp).
665 narrow_down_interval(kernel_objects:safe_less_than_equal(_,V1,V2),Var,Low,Up,NewLow,NewUp) :- !,
666 (V1==Var,number(V2) -> NewLow=Low,fd_min(Up,V2,NewUp)
667 ; V2==Var,number(V1) -> fd_max(Low,V1,NewLow),NewUp=Up
668 ; NewLow=Low,NewUp=Up).
669 narrow_down_interval(kernel_objects:safe_less_than(V1,V2),Var,Low,Up,NewLow,NewUp) :- !,
670 (V1==Var,number(V2) -> NewLow=Low,V2m1 is V2-1, fd_min(Up,V2m1,NewUp)
671 ; V2==Var,number(V1) -> V1p1 is V1+1, fd_max(Low,V1p1,NewLow),NewUp=Up
672 ; NewLow=Low,NewUp=Up).
673 narrow_down_interval(_,_,L,U,L,U).
674
675 % check if this variable is marked as being assigned to by currently not-well-defined construct such as min,max,...:
676 is_wdguarded_result_variable(N) :- % write('-WDG-'),
677 frozen(N,FrozenGoal), % TO DO: use attribute rather than frozen
678 ? is_wdguarded_result_variable_aux(FrozenGoal,N).
679 is_wdguarded_result_variable_aux(kernel_waitflags:is_wd_guarded_result(V),N) :- !, N==V.
680 is_wdguarded_result_variable_aux((A,B),N) :-
681 ? is_wdguarded_result_variable_aux(A,N) ; is_wdguarded_result_variable_aux(B,N).
682
683 % enumerate unbounded integer variable N in a CLP(FD) fashion:
684 enum_unbounded_clp(0,Y,N,EnumWarning,Span,WF) :- (Y=sup ; Y>0),
685 % we span 0 and positive numbers
686 !,
687 (N=0
688 % for division/modulo... 0 is often a special case
689 ; try_post_constraint(N #>0),
690 ? force_enumerate_int_wo_case_split(N,'INTEGER',EnumWarning,Span,WF)
691 ).
692 enum_unbounded_clp(X,Y,N,EnumWarning,Span,WF) :-
693 (X=inf -> true ; X<0), (Y=sup ; Y>0),
694 % we span both negative and positive numbers
695 !,
696 % do a case split
697 (N=0
698 % Instead of doing a case-split on 0; we could try and detect other relevant values (e.g., what if we have x / (y-1)
699 ; try_post_constraint(N #>0), % TO DO: use clpfd_lt_expr(0,N), ?and in other calls; this is an area where time-outs are more likely, but we cannot do anything about them anyway
700 ? force_enumerate_int_wo_case_split(N,'INTEGER',EnumWarning,Span,WF)
701 ; try_post_constraint(N #<0),
702 ? force_enumerate_int_wo_case_split(N,'INTEGER',EnumWarning,Span,WF)
703 ).
704 enum_unbounded_clp(FDLow,FDUp,N,EnumWarning,Span,WF) :-
705 % we cover only negative or only positive numbers
706 ? force_enumerate_with_warning(N,FDLow,FDUp,'INTEGER',EnumWarning,Span,WF).
707
708 % force enumeration without case split:
709 force_enumerate_int_wo_case_split(N,Msg,EnumWarning,Span,WF) :-
710 clpfd_domain(N,FDLow,FDUp), % print(enum(N,FDLow,FDUp)),nl,
711 (finite_domain(FDLow,FDUp)
712 ? -> label(N,FDLow,FDUp)
713 ; %print(force_enumerate_int_wo_case_split(FDLow,FDUp)),nl,
714 ? force_enumerate_with_warning(N,FDLow,FDUp,Msg,EnumWarning,Span,WF)
715 ).
716
717 force_enumerate_with_warning(N,_FDLow,_FDUp,_Msg,_EnumWarning,_Span,_WF) :- % check if we should enumerate at all
718 ? is_wdguarded_result_variable(N),!. % affects tests 1825, 2017
719 force_enumerate_with_warning(N,FDLow,FDUp,Msg,EnumWarning,Span,WF) :-
720 make_domain_finite(FDLow,FDUp,Min,Max),
721 gen_enum_warning_wf(Msg,FDLow:FDUp,Min:Max,EnumWarning,Span,WF),
722 %try_post_constraint(N in Min..Max), % I am not sure whether this is useful or not
723 ? enumerate_int2(N,Min,Max).
724
725
726 % generate enumeration warning:
727 gen_enum_warning_wf(TYPE,RANGE,RESTRICTED_RANGE,Trigger,Span,WF) :-
728 Warning = enumeration_warning(enumerating(Info),TYPE,RANGE,RESTRICTED_RANGE,critical),
729 (get_trigger_info(Trigger,Info)
730 -> (Span=unknown,Info=b(_,_,_),get_texpr_pos(Info,Span2) -> true ; Span2=Span)
731 ; Info=unknown, Span2=Span
732 ),
733 (add_new_event_in_error_scope(Warning,
734 print_enum_warning(Trigger,TYPE,RANGE,RESTRICTED_RANGE,Span2,WF))
735 % may also throw(Warning)
736 ->
737 (preference(allow_enumeration_of_infinite_types,false)
738 -> formatsilent('### VIRTUAL TIME-OUT generated because ENUMERATE_INFINITE_TYPES=false~n',[]),
739 % print_pending_abort_error(WF),
740 (silent_mode(on) -> true ; print_span_nl(Span2)),
741 throw(Warning)
742 ; Trigger = trigger_throw(Source)
743 -> (silent_mode(on) -> true
744 ; Source=b(identifier(ID),_,_) ->
745 format('### VIRTUAL TIME-OUT generated for ~w ',[ID]),
746 print_span_nl(Span2)
747 ; format('### VIRTUAL TIME-OUT generated for ~w ',[Source]),
748 print_span_nl(Span2)
749 ),
750 throw(Warning)
751 ; true)
752 ; true).
753
754 %get_trigger_info(trigger_false(I),Info) :- get_trigger_info2(I,Info). % was non_critical ; no longer used
755 get_trigger_info(trigger_true(I),Info) :- get_trigger_info2(I,Info).
756 get_trigger_info(trigger_throw(I),Info) :- get_trigger_info2(I,Info).
757 %get_trigger_info2(enum_wf_context(_,Info),Res) :- !,Res=Info. % no longer used; WF now passed
758 get_trigger_info2(Info,Info).
759
760
761 % TO DO: pass WF explicitly rather than extracting it from enumeration warning terms
762 :- use_module(translate,[translate_span/2, translate_error_term/3]).
763 print_pending_abort_error(WF) :-
764 pending_abort_error(WF,Msg,ErrTerm,Span),
765 !, % just print one error
766 translate_span(Span,TSpan),
767 translate_error_term(ErrTerm,Span,TT),
768 format_with_colour(user_output,[bold],' (could be due to WD-Error ~w: ~w ~w)~n',[TSpan,Msg,TT]).
769 print_pending_abort_error(_).
770
771 % try and get get_pending_abort_error_for_trigger
772 get_pending_abort_error_for_info(WF,Span,FullMsg,ErrTerm) :-
773 pending_abort_error(WF,Msg,ErrTerm,Span),
774 ajoin(['Enumeration warning occured, probably caused by WD-Error: ',Msg],FullMsg).
775
776 :- use_module(translate,[print_span/1, print_span_nl/1]).
777 % THROWING,OuterSpan added by add_new_event_in_error_scope
778 print_enum_warning(_,_,_,_,_,_WF,THROWING,_) :-
779 THROWING \= throwing, % maybe we should also be silent if THROWING=throwing; see test 1522
780 silent_mode(on), % we could also check: performance_monitoring_on,
781 !. % do not print
782 print_enum_warning(Trigger,_,_,_,_LocalSpan,WF,THROWING,OuterThrowSpan) :-
783 will_throw_enum_warning(THROWING),
784 debug_mode(off),
785 !, % do not print detailed enumeration warning with reduced scopes; we print another message instead
786 print_throwing_wf(THROWING,Trigger,OuterThrowSpan,WF).
787 print_enum_warning(_,_,_,_,_,_WF,THROWING,_) :- THROWING \= throwing,
788 inc_counter(non_critical_enum_warnings,Nr), Nr>50,!, % do not print anymore
789 (Nr=51 -> write('### No longer printing non-critical enumeration warnings; limit exceeded.'),nl
790 ; true).
791 print_enum_warning(Trigger,TYPE,RANGE,RESTRICTED_RANGE,LocalSpan,WF,THROWING,OuterThrowSpan) :-
792 write('### Unbounded enumeration of '), % error_manager:trace_if_user_wants_it,
793 print_trigger_var(Trigger),
794 format('~w : ~w ---> ~w ',[TYPE,RANGE,RESTRICTED_RANGE]),
795 print_wf_context(WF),
796 print_span(LocalSpan),nl,
797 print_throwing_wf(THROWING,Trigger,OuterThrowSpan,WF).
798
799 % just count number of enum warnings
800 :- use_module(extension('counter/counter'),
801 [counter_init/0, new_counter/1, inc_counter/2, reset_counter/1]).
802 kernel_objects_startup :- % call once at startup to ensure all counters exist
803 counter_init,
804 new_counter(non_critical_enum_warnings).
805 kernel_objects_reset :- reset_counter(non_critical_enum_warnings).
806
807 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
808 :- register_event_listener(startup_prob,kernel_objects_startup,
809 'Initialise kernel_objects counters.').
810 :- register_event_listener(clear_specification,kernel_objects_reset,
811 'Reset kernel_objects counters.').
812
813 % -----------
814
815 will_throw_enum_warning(THROWING) :-
816 (THROWING=throwing -> true ; preference(strict_raise_enum_warnings,true)).
817
818 :- use_module(tools_printing,[format_with_colour/4]).
819 print_throwing(THROWING,Span) :- print_throwing_wf(THROWING,unknown_info,Span,no_wf_available).
820 print_throwing_wf(THROWING,TriggerInfo,ThrowSpan,WF) :-
821 peel_trigger(TriggerInfo,Info),
822 (preference(strict_raise_enum_warnings,true)
823 -> (get_pending_abort_error_for_info(WF,Span,Msg,ErrTerm)
824 -> add_error(strict_raise_enum_warnings,Msg,ErrTerm,Span)
825 ; add_error(strict_raise_enum_warnings,'Enumeration warning occured','',ThrowSpan)
826 )
827 ; true
828 ),
829 (THROWING=throwing ->
830 (get_trigger_info_variable(Info,VarID)
831 -> format_with_colour(user_output,[bold],'Generating VIRTUAL TIME-OUT for unbounded enumeration of ~w!~n',[VarID])
832 ; format_with_colour(user_output,[bold],'Generating VIRTUAL TIME-OUT for unbounded enumeration warning!~n',[])
833 ),
834 print_pending_abort_error(WF),
835 ? (get_wait_flags_context_msg(WF,Msg) % % get call stack or other context message from WF
836 -> format_with_colour(user_output,[bold],' ~w~n',[Msg])
837 ; true),
838 (extract_span_description(ThrowSpan,PosMsg) -> format_with_colour(user_output,[bold],' ~w~n',[PosMsg]) ; true)
839 ; true).
840
841 peel_trigger(trigger_true(Info),Info) :- !.
842 peel_trigger(trigger_throw(Info),Info) :- !.
843 peel_trigger(Info,Info).
844
845 print_trigger_var(trigger_true(Info)) :- !, print_trigger_var_info(Info), write(' : ').
846 print_trigger_var(trigger_throw(Info)) :- !, print_trigger_var_info(Info), write(' : (all_solutions) : ').
847 %print_trigger_var(trigger_false(Info)) :- !, print_trigger_var_info(Info), print(' (not critical [unless failure]) : '). % no longer used
848 print_trigger_var(X) :- write(' UNKNOWN TRIGGER: '), print(X), write(' : ').
849
850 print_wf_context(WF) :-
851 (get_wait_flags_context_msg(WF,Msg)
852 -> format('~n### ~w~n ',[Msg]) %format(' : (~w)',[Msg])
853 ; true).
854 :- use_module(translate,[print_bexpr/1]).
855 print_trigger_var_info(b(E,T,I)) :- !, print_bexpr(b(E,T,I)), write(' '), print_span(I).
856 print_trigger_var_info(VarID) :- print(VarID).
857
858 % get variable name from trigger info field
859 get_trigger_info_variable(b(identifier(ID),_,_),VarID) :- !, VarID=ID.
860 get_trigger_info_variable(ID,VarID) :- atom(ID), VarID=ID.
861
862
863 % generate a warning if a large range is enumerated
864 gen_enum_warning_if_large(Var,FDLow,FDUp) :-
865 (FDUp>FDLow+8388608 /* 2**23 ; {x|x:1..2**23 & x mod 2 = x mod 1001} takes about 2 minutes */
866 % however the domain itself could be very small, we also check clpfd_size instead
867 -> fd_size(Var,Size), % no need to call clpfd_size; we know we are in CLP(FD) mode
868 (Size =< 8388608 -> true
869 ; enum_warning_large(Var,'INTEGER',FDLow:FDUp)
870 )
871 ; true).
872 enum_warning_large(_Var,TYPE,RANGE) :-
873 Warning = enumeration_warning(enumerating,TYPE,RANGE,RANGE,non_critical),
874 (add_new_event_in_error_scope(Warning,print_enum_warning_large(TYPE,RANGE))
875 -> true
876 ; true).
877
878 print_enum_warning_large(TYPE,RANGE,THROWING,Span) :-
879 print('### Warning: enumerating large range '),
880 print(TYPE), print(' : '),
881 print(RANGE),nl,
882 print_throwing(THROWING,Span).
883
884 :- block finite_warning(-,?,?,?,?).
885 finite_warning(_,Par,Types,Body,Source) :-
886 add_new_event_in_error_scope(enumeration_warning(checking_finite_closure,Par,Types,finite,critical),
887 print_finite_warning(Par,Types,Body,Source) ),
888 fail. % WITH NEW SEMANTICS OF ENUMERATION WARNING WE SHOULD PROBABLY ALWAYS FAIL HERE !
889 print_finite_warning(Par,Types,Body,Source,THROWING,Span) :-
890 print('### Warning: could not determine set comprehension to be finite: '),
891 translate:print_bvalue(closure(Par,Types,Body)),nl,
892 print('### Source: '), print(Source),nl,
893 print_throwing(THROWING,Span).
894
895 :- block enumerate_natural(-,?,-,?,?).
896 ?enumerate_natural(N,From,_,Span,WF) :- nonvar(N) -> true ; enumerate_natural(N,From,Span,WF).
897 enumerate_natural(N,From,Span,WF) :- preference(use_clpfd_solver,false),!,
898 clpfd_off_domain(N,From,sup,NewLow,NewUp), % try narrow down domain using co-routines
899 (finite_domain(NewLow,NewUp) -> enumerate_int1(N,NewLow,NewUp)
900 ; force_enumerate_with_warning(N,NewLow,NewUp,'NATURAL(1)',trigger_true('NATURAL(1)'),Span,WF)).
901 enumerate_natural(N,From,Span,WF) :- clpfd_domain(N,FDLow,FDUp),
902 fd_max(FDLow,From,Low),
903 (finite_domain(Low,FDUp)
904 ? -> label(N,Low,FDUp)
905 ? ; enumerate_natural_unbounded(N,Low,FDUp,Span,WF)
906 ).
907 enumerate_natural_unbounded(N,FDLow1,FDUp,Span,WF) :-
908 (FDLow1=0
909 -> (N=0 ; /* do a case split */
910 try_post_constraint(N #>0), % this can sometimes make the domain finite
911 ? force_enumerate_int_wo_case_split(N,'NATURAL',trigger_true('NATURAL'),Span,WF)
912 )
913 ? ; force_enumerate_with_warning(N,FDLow1,FDUp,'NATURAL(1)',trigger_true('NATURAL(1)'),Span,WF)
914 ).
915
916
917 % assumes one of FDLow and FDUp is not a number
918 make_domain_finite(FDLow,_FDUp,Min,Max) :- number(FDLow),!,Min=FDLow,
919 preferences:preference(maxint,MaxInt),
920 (MaxInt>=FDLow -> Max=MaxInt ; Max=FDLow). % ensure that we try at least one number
921 make_domain_finite(_FDLow,FDUp,Min,Max) :- number(FDUp),!,Max=FDUp,
922 preferences:preference(minint,MinInt),
923 (MinInt=<FDUp -> Min=MinInt ; Min=FDUp).
924 make_domain_finite(_FDLow,_FDUp,Min,Max) :-
925 ((preferences:preference(maxint,Max),
926 preferences:get_preference(minint,Min))->true). % ensure that we try at least one number
927
928 enumerate_int1(N,Min,Max) :-
929 (Min<0 /* enumerate positive numbers first; many specs only use NAT/NATURAL */
930 -> (enumerate_int2(N,0,Max) ; enumerate_int2(N,Min,-1))
931 ? ; enumerate_int2(N,Min,Max)
932 ).
933 enumerate_int(X,Low,Up) :- get_int_domain(X,Low,Up,RL,RU),
934 %% print(enumerate_int(X,Low,Up, RL,RU)),nl, %%
935 ? enumerate_int2(X,RL,RU).
936
937 get_int_domain(X,Low,Up,RL,RU) :- clpfd_domain(X,FDLow,FDUp),
938 fd_max(FDLow,Low,RL),fd_min(FDUp,Up,RU).
939
940 finite_domain(Low,Up) :- \+ infinite_domain(Low,Up).
941 infinite_domain(inf,_) :- !.
942 infinite_domain(_,sup).
943
944 % second arg should always be a number
945 fd_max(inf,L,R) :- !,R=L.
946 fd_max(FDX,Y,R) :- (nonvar(FDX),nonvar(Y),FDX>Y -> R=FDX ; R=Y).
947 fd_min(sup,L,R) :- !,R=L.
948 fd_min(FDX,Y,R) :- (nonvar(FDX),nonvar(Y),FDX<Y -> R=FDX ; R=Y).
949
950 :- use_module(extension('random_permutations/random_permutations'),
951 [enum_fd_random/3]).
952
953 enumerate_int2(N,X,Y) :-
954 preferences:get_preference(randomise_enumeration_order,true)
955 ? -> enum_fd_random(N,X,Y) ; enumerate_int2_linear(N,X,Y).
956
957 enumerate_int2_linear(N,X,Y) :- X=<Y,
958 ? (N=X ; X1 is X+1, enumerate_int2_linear(N,X1,Y)).
959
960
961 enumerate_basic_type_set(X,Type,Tight,EnumWarning,WF) :- var(X),!,
962 max_cardinality_with_check(Type,Card),
963 ? enumerate_basic_type_set2(X,[],Card,Type,none,Tight,EnumWarning,WF).
964 enumerate_basic_type_set([],_,_,_EnumWarning,_WF) :- !.
965 enumerate_basic_type_set(avl_set(_),_,_,_EnumWarning,_WF) :- !.
966 enumerate_basic_type_set(freetype(_),_,_,_EnumWarning,_WF) :- !.
967 enumerate_basic_type_set(global_set(GS),Type,_Tight,_EnumWarning,_WF) :- !,
968 (Type = global(GT)
969 -> (GS = GT -> true
970 ; nonvar(GS), add_error_and_fail(enumerate_basic_type_set,'Type error in global set: ',GS:GT))
971 ; Type = integer,integer_global_set(GS)
972 ; Type = string, string_global_set(GS)
973 ; Type = real, real_global_set(GS)
974 ).
975 enumerate_basic_type_set(closure(Parameters, PT, Body),_Type,_Tight,_EnumWarning,WF) :- !,
976 (ground(Body) -> true
977 ; add_message_wf(kernel_objects,'Enumerating non-ground closure body: ',closure(Parameters, PT, Body),Body,WF),
978 % this did happen for symbolic total function closures set up for f : NATURAL1 --> ..., see test 2022
979 %term_variables(Body,Vars), print('### Variables: '), print(Vars),nl,
980 ? enumerate_values_inside_expression(Body,WF)
981 ).
982 enumerate_basic_type_set([H|T],Type,Tight,EnumWarning,WF) :- !,
983 % collect bound elements; avoid enumerating initial elements with elements that already appear later
984 collect_bound_elements([H|T], SoFar,Unbound,Closed),
985 (Closed=false -> max_cardinality_with_check(Type,Card)
986 ; Card = Closed),
987 % print(enum(Card,Unbound,SoFar,[H|T],Closed)),nl,
988 ? enumerate_basic_type_set2(Unbound,SoFar,Card,Type,none,Tight,EnumWarning,WF).
989 %enumerate_basic_type_set([H|T],Type,Tight,WF) :- !,
990 % (is_list_skeleton([H|T],Card) -> true
991 % ; max_cardinality_with_check(Type,Card)
992 % ),
993 % enumerate_basic_type_set2([H|T],[],Card,Type,none,Tight,WF).
994 enumerate_basic_type_set(S,Type,Tight,EnumWarning,WF) :-
995 add_internal_error('Illegal set: ',enumerate_basic_type_set(S,Type,Tight,EnumWarning,WF)).
996
997 enumerate_basic_type_set2(HT,ElementsSoFar,_Card,_Type,_Last,_Tight,_EnumWarning,_WF) :- nonvar(HT),
998 is_custom_explicit_set(HT,enumerate_basic_type),!,
999 disjoint_sets(HT,ElementsSoFar). % I am not sure this is necessary; probably other constraints already ensure this holds
1000 enumerate_basic_type_set2(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF) :- var(HT),
1001 preferences:preference(randomise_enumeration_order,true),!,
1002 (random(1,3,1)
1003 ? -> (enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF)
1004 ; HT = [])
1005 ; (HT = [] ;
1006 ? enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF))
1007 ).
1008 enumerate_basic_type_set2([],_,_,_,_,_Tight,_EnumWarning,_WF).
1009 enumerate_basic_type_set2(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF) :-
1010 ? enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF).
1011
1012 enumerate_basic_type_set_cons(HT,ElementsSoFar,Card,Type,Last,Tight,EnumWarning,WF) :- positive_card(Card),
1013 %debug:trace_point(enum(HT,ElementsSoFar,Card,Type,Last,Tight)),
1014 (var(HT) -> HT=[H|T], NewLast=NormH /* the enumerator has completely determined H */
1015 % Note: HT=[H|T] may wake up co-routines and then attach infos to H; but these should hold indpendently for all elements
1016 ; HT=[H|T],
1017 (unbound_value(H)
1018 -> NewLast=NormH /* the enumerator has completely determined H */
1019 ; NewLast=Last) /* H was not freely chosen by the enumerator */
1020 ),
1021 ? not_element_of(H,ElementsSoFar), % this is only needed for elements generated by the enumerator itself
1022 % if we pass WF to not_element_of then test 479 fails due to different enumeration order
1023 ? enumerate_type_wf(H,Type,Tight,EnumWarning,WF),
1024 % TO DO: extract normal form from add_new_element
1025 % Note: if H is_wdguarded_result_variable then H may not be ground !!
1026 (ground_value(H)
1027 -> val_greater_than(H,NormH,Last),
1028 add_new_element(NormH,ElementsSoFar,SoFar2) % TODO : use add_new_element_wf ?
1029 ; add_new_element(H,ElementsSoFar,SoFar2),
1030 NormH=none
1031 ),
1032 C1 is Card-1,
1033 ? enumerate_basic_type_set2(T,SoFar2,C1,Type,NewLast,Tight,EnumWarning,WF).
1034
1035 :- assert_must_succeed((collect_bound_elements([int(1),int(2),int(4),X,int(5)|T],_,U,C),U==[X|T],C==false)).
1036 :- assert_must_succeed((collect_bound_elements([int(1),int(2),int(4),X,int(5)],_,U,C),U==[X],C==1)).
1037 :- assert_must_succeed(exhaustive_kernel_succeed_check(collect_bound_elements([int(1),int(2),int(4),int(5)],_,_,_))).
1038
1039 % collect the bound and unbound elements in a list; also return if the list is closed (then return length) or return false
1040 collect_bound_elements(T, SoFar,Unbound,Closed) :- var(T),!, SoFar=[],Unbound=T,Closed=false.
1041 collect_bound_elements([],[],[],0).
1042 collect_bound_elements(avl_set(A),avl_set(A),[],0).
1043 collect_bound_elements(global_set(GS),SoFar,Unbound,Closed) :- expand_custom_set(global_set(GS),ES),
1044 collect_bound_elements(ES,SoFar,Unbound,Closed).
1045 collect_bound_elements(freetype(FS),SoFar,Unbound,Closed) :- expand_custom_set(freetype(FS),ES),
1046 collect_bound_elements(ES,SoFar,Unbound,Closed).
1047 collect_bound_elements(closure(P,T,B),SoFar,Unbound,Closed) :- expand_custom_set(closure(P,T,B),ES),
1048 collect_bound_elements(ES,SoFar,Unbound,Closed).
1049 collect_bound_elements([H|T],SoFar,Unbound,Closed) :-
1050 collect_bound_elements(T,TSoFar,TUnbound,TClosed),
1051 (ground(H) -> add_new_element(H,TSoFar,SoFar), Unbound=TUnbound, TClosed=Closed
1052 ; SoFar = TSoFar, Unbound = [H|TUnbound],
1053 (TClosed=false -> Closed=false ; Closed is TClosed+1)
1054 ).
1055
1056
1057 % perform order checking on terms, normalising them first
1058 % val_greater_than(A,NormA,NormB)
1059 val_greater_than(A,NormA,NormB) :- !,
1060 (nonvar(A),custom_explicit_sets:convert_to_avl_inside_set(A,NormA)
1061 -> (NormB==none -> true ; NormA @> NormB)
1062 ; add_internal_error('Call failed: ',custom_explicit_sets:convert_to_avl_inside_set(A,NormA)),
1063 NormA = A).
1064
1065 positive_card(inf) :- !, print('$').
1066 positive_card(C) :- (integer(C) -> C>0
1067 ; add_internal_error('Not an integer: ',positive_card(C)),fail).
1068
1069
1070
1071 :- block enumerate_basic_field_types(?,-,?,-,?).
1072 enumerate_basic_field_types([],[],_Tight,_EnumWarning,_).
1073 enumerate_basic_field_types(Fields,[field(Name,VT)|TT],Tight,EnumWarning,WF) :-
1074 ? enumerate_basic_field_types2(Fields,Name,VT,TT,Tight,EnumWarning,WF).
1075
1076 :- block enumerate_basic_field_types2(?,-,?,?,?,?,?).
1077 enumerate_basic_field_types2([field(Name1,V)|T], Name2,VT,TT,Tight,EnumWarning,WF) :-
1078 check_field_name_compatibility(Name1,Name2,enumerate_basic_field_types2),
1079 ? enumerate_type_wf(V,VT,Tight,EnumWarning,WF),
1080 ? enumerate_basic_field_types(T,TT,Tight,EnumWarning,WF).
1081
1082
1083 :- block all_objects_of_type(-,?).
1084 all_objects_of_type(Type,Res) :-
1085 findall(O,enumerate_basic_type(O,Type),Res).
1086
1087 :- use_module(library(avl),[avl_size/2]).
1088 :- use_module(kernel_cardinality_attr,[clpfd_card_domain_for_var/3]).
1089 % obtain info for enumerating sequence lists: length of list skeleton and maximum index inferred to be in the list
1090 % (MaxIndex is not the maximum index that can appear in the full sequence !)
1091 list_length_info(X,LenSoFar,Len,Type,MaxIndex) :- var(X),!,Len=0,
1092 clpfd_card_domain_for_var(X,MinCard,MaxCard),
1093 ( number(MinCard)
1094 -> MaxIndex is MinCard+LenSoFar % we know a valid list must be at least LenSoFar+MinCard long
1095 ; MaxIndex=0),
1096 ( number(MaxCard) -> Max1 is MaxCard+Len, Type = open_bounded(Max1) ; Type = open).
1097 list_length_info([],_,0,closed,0).
1098 list_length_info([H|T],LenSoFar,C1,Type,MaxIndex1) :- Len1 is LenSoFar+1,
1099 list_length_info(T,Len1,C,Type,MaxIndex),
1100 C1 is C+1,
1101 (nonvar(H),H=(I,_),nonvar(I),I=int(Idx),number(Idx),Idx>MaxIndex
1102 -> MaxIndex1 = Idx ; MaxIndex1 = MaxIndex).
1103 list_length_info(avl_set(A),LenSoFar,Size,closed,0) :- % case arises e.g. in private_examples/ClearSy/2019_Dec/well_def
1104 (LenSoFar=0 -> Size=1000000 % then length not used anyway
1105 ; avl_size(A,Size)). % we could check that this is a sequence tail!
1106 list_length_info(closure(_,_,_),_,0,open,0).
1107
1108 :- assert_must_succeed((max_cardinality(set(couple(global('Name'),global('Code'))),64))).
1109 :- assert_must_succeed((max_cardinality(set(set(set(couple(global('Name'),global('Code'))))),_))).
1110 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc4,[case(a,boolean),case(b,couple(boolean,boolean))]),
1111 max_cardinality(freetype(selfc4),6),
1112 kernel_freetypes:reset_freetypes)).
1113 :- assert_must_succeed((kernel_freetypes:add_freetype(selfc6,[case(a,boolean),case(b,freetype(selfc6)),case(c,constant([c]))]),
1114 kernel_freetypes:set_freetype_depth(3),
1115 findall(X,enumerate_tight_type(X,freetype(selfc6)),Solutions),
1116 length(Solutions,NumberOfSolutions),
1117 max_cardinality(freetype(selfc6),NumberOfSolutions),
1118 kernel_freetypes:reset_freetypes)).
1119
1120 :- use_module(tools_printing,[print_error/1]).
1121 max_cardinality_with_check(Set,CCard) :-
1122 (max_cardinality(Set,Card) ->
1123 (Card=inf
1124 -> debug_println(9,very_large_cardinality(Set,Card)),
1125 CCard = 20000000
1126 ; CCard=Card,
1127 (Card>100 -> debug_println(9,large_cardinality(Set,Card)) ; true)
1128 )
1129 ; print_error(failed(max_cardinality(Set,CCard))), CCard = 10
1130 ).
1131 max_cardinality(global(T),Card) :- b_global_set_cardinality(T,Card).
1132 max_cardinality(boolean,2).
1133 max_cardinality(constant([_V]),1).
1134 max_cardinality(any,inf). % :- print_message(dont_know_card_of_any). /* TODO: what should we do here ? */
1135 max_cardinality(string,MC) :- max_cardinality_string(MC). % is inf now
1136 %max_cardinality(abort,1).
1137 max_cardinality(integer,Card) :- Card=inf. %b_global_set_cardinality('INTEGER',Card).
1138 max_cardinality(real,Card) :- Card=inf.
1139 max_cardinality(seq(X),Card) :- % Card=inf, unless a freetype can be of cardinality 0
1140 ? max_cardinality(set(couple(integer,X)),Card).
1141 max_cardinality(couple(X,Y),Card) :-
1142 ? max_cardinality(X,CX), max_cardinality(Y,CY), safe_mul(CX,CY,Card).
1143 max_cardinality(record([]),1).
1144 max_cardinality(record([field(_,T1)|RF]),Card) :-
1145 ? max_cardinality(record(RF),RC),
1146 ? max_cardinality(T1,C1),
1147 safe_mul(C1,RC,Card).
1148 ?max_cardinality(set(X),Card) :- max_cardinality(X,CX),
1149 safe_pow2(CX,Card).
1150 max_cardinality(freetype(Id),Card) :- max_cardinality_freetype(freetype(Id),Card).
1151 max_cardinality(freetype_lim_depth(Id,Depth),Card) :- max_cardinality_freetype(freetype_lim_depth(Id,Depth),Card).
1152
1153 :- assert_must_succeed((safe_pow2(3,R),R==8)).
1154 :- assert_must_succeed((safe_pow2(inf,R),R==inf)).
1155 :- assert_must_succeed((safe_pow2(3072,R),R==inf)).
1156 :- assert_must_succeed((safe_pow2(18446744073709551616,R),R==inf)).
1157 :- assert_must_succeed((safe_pow2(500,X), safe_pow2(501,X2), X2 is 2*X)).
1158 % :- assert_must_succeed((kernel_objects:safe_pow2(1022,X), kernel_objects:safe_pow2(1023,X2), X2 is 2*X)).
1159
1160 safe_pow2(Exp,Res) :- (Exp==inf -> Res=inf
1161 ; Exp>1023 -> Res=inf /* the limit where SICStus 4.2.1 reported inf; 4.2.3 goes further but uses a huge amount of memory */
1162 ; Res is 2^Exp % ^ integer exponentiation operator new in SICStus 4.3
1163 ).
1164 % this seems to be either precise or give inf (at 1023 on 64 bit system)
1165
1166 :- assert_must_succeed((safe_pown(3,2,R),R==9)).
1167 :- assert_must_succeed((safe_pown(2,3072,R),R==inf)).
1168 :- assert_must_succeed((safe_pown(3,647,R),R==inf)).
1169 :- assert_must_succeed((safe_pown(2,500,X), safe_pown(2,501,X2), X2 is 2*X)).
1170 :- assert_must_succeed((safe_pown(2,500,X), safe_pow2(500,X))).
1171 :- assert_must_succeed((kernel_objects:safe_pown(2,1022,X), kernel_objects:safe_pown(2,1023,X2), X2 is 2*X)).
1172 :- assert_must_succeed((kernel_objects:safe_pown(3,500,X), kernel_objects:safe_pown(3,501,X3), X3 is 3*X)).
1173 safe_pown(Base,Exp,Res) :-
1174 (Base=inf -> (Exp=0 -> Res=1 ; Res=inf)
1175 ; Exp=inf -> (Base=0 -> Res=0 ; Base=1 -> Res=1 ; Res=inf)
1176 ; infinite_pown(Base,Exp) -> Res=inf /* SICStus 4.2.1 reported inf; 4.2.3 goes further but uses a huge amount of memory */
1177 ; Res is Base ^ Exp % ^ integer exponentiation operator new in SICStus 4.3
1178 ).
1179
1180 /* SICStus 4.2.1 reported inf; 4.2.3 goes further but uses a huge amount of memory */
1181 infinite_pown(Base,Exp) :- Exp > 1023, !, Base >= 2.
1182 infinite_pown(Base,Exp) :- Exp > 646, !, Base >= 3. % was not really necessary when using overflow_float_pown
1183 infinite_pown(Base,Exp) :- Exp > 511, !, Base >= 4.
1184 infinite_pown(Base,Exp) :- Exp > 441, !, Base >= 5.
1185
1186 :- assert_must_succeed((safe_mul(3,2,R),R==6)).
1187 :- assert_must_succeed((safe_mul(inf,2,R),R==inf)).
1188 :- assert_must_succeed((safe_mul(2,inf,R),R==inf)).
1189 :- assert_must_succeed((safe_mul(0,inf,R),R==0)).
1190 :- assert_must_succeed((safe_mul(inf,0,R),R==0)).
1191 % safe_multiplication for positive numbers
1192 safe_mul(0,_,R) :- !, R=0. % true for cartesian product: card({}*INTEGER)=0
1193 safe_mul(_,0,R) :- !, R=0. % ditto
1194 safe_mul(inf,_,R) :- !, R=inf.
1195 safe_mul(_,inf,R) :- !, R=inf.
1196 safe_mul(X,Y,R) :- is_overflowcheck(R,X*Y).
1197
1198 safe_add(inf,_,R) :- !, R=inf.
1199 safe_add(_,inf,R) :- !, R=inf.
1200 safe_add(X,Y,R) :- is_overflowcheck(R,X+Y).
1201
1202
1203 /* is with overflow check */
1204 is_overflowcheck(Var,Expr) :-
1205 (Expr=inf -> Var=inf
1206 ; catch(Var is Expr, error(_,_), Var=inf)).
1207
1208 %overflow_float_pown(Base,Exp,Res) :-
1209 % catch(
1210 % (R1 is Base**Exp, /* separate into two steps; SICStus 4.2.3 otherwise seems to use integer exponentation */
1211 % Res is truncate(R1)),
1212 % error(_,_),
1213 % Res=inf).
1214
1215 /*
1216 % this code below would sometimes fail in spld generated code:
1217 is_overflowcheck_old(Var,Expr) :- print(is_with_overflow(Var,Expr)),nl,
1218 (Expr=inf -> Var=inf
1219 ; catch(
1220 catch(
1221 Var is Expr,
1222 error(evaluation_error(float_overflow),_),
1223 (print(float_overflow),nl,Var = inf)),
1224 error(type_error(evaluable,inf/0),_),
1225 (print(evaluable_inf),nl,Var=inf))).
1226 % catches any exception (e.g. also representation_error when converting inf to integer)
1227 % could be unsafe with timeout !!
1228 is_errc(Var,Expr) :-
1229 (Expr=inf -> Var=inf
1230 ; safe_on_exception(_E, Var is Expr, Var = inf)).
1231 */
1232
1233 /* ---------------------------- */
1234
1235
1236 /* use a cleverer, better enumeration than enumerate_basic_type */
1237 /* can only be used in certain circumstances: operation preconditions,
1238 properties,... but not for VARIABLES as there is no guarantee that
1239 something declared as a sequence will actually turn out to be a sequence */
1240
1241 :- assert_pre(kernel_objects:enumerate_tight_type(Obj,Type),
1242 (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
1243 :- assert_post(kernel_objects:enumerate_tight_type(Obj,_), (type_check(Obj,bsets_object),ground_check(Obj))).
1244 :- assert_pre(kernel_objects:enumerate_tight_type(Obj,Type,_),
1245 (type_check(Obj,bsets_object),type_check(Type,basic_type_descriptor))).
1246 :- assert_post(kernel_objects:enumerate_tight_type(Obj,_,_), (type_check(Obj,bsets_object),ground_check(Obj))).
1247
1248 :- assert_must_succeed(enumerate_tight_type([(int(1),int(2)),(int(2),int(4))],
1249 seq(integer) )).
1250 :- assert_must_succeed(enumerate_tight_type([(int(1),int(2))],seq(integer) )).
1251 :- assert_must_succeed(enumerate_tight_type([],seq(integer) )).
1252 :- assert_must_succeed((enumerate_tight_type(X,record([field(a,integer),field(b,global('Name'))])),
1253 equal_object(X,rec([field(a,int(1)),field(b,fd(1,'Name'))])) )).
1254 :- assert_must_fail(enumerate_tight_type([(int(1),int(2)),(int(3),int(_))],
1255 seq(integer) )).
1256 :- assert_must_fail(enumerate_tight_type([(int(3),int(_))],seq(integer) )).
1257 :- assert_must_succeed((bsets_clp:is_sequence(X,global_set('Name')),
1258 enumerate_tight_type(X,seq(global('Name')) ),
1259 X = [(int(1),fd(2,'Name'))] )).
1260 :- assert_must_succeed(( enumerate_tight_type(XX, record([field(balance,integer),field(name,global('Name'))])) ,
1261 XX = rec([field(balance,int(1)),field(name,fd(3,'Name'))]) )).
1262 :- assert_must_succeed(( enumerate_tight_type(XX, set(record([field(balance,global('Name')),field(name,global('Name'))]))) , /* STILL TAKES VERY LONG !! */
1263 XX = [rec([field(balance,fd(3,'Name')),field(name,fd(3,'Name'))])] )).
1264 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(balance,global('Name')),field(name,global('Name'))]))) ,S),
1265 length(S,Len), Len = 512 )).
1266 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(name,global('Code'))]))) ,S),
1267 length(S,Len), Len = 4 )).
1268 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(fname,global('Code')),field(name,global('Code'))]))) ,S),
1269 length(S,Len), Len = 16 )).
1270 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(record([field(fname,global('Code')),field(name,global('Name'))]))) ,S),
1271 length(S,Len), Len = 64 )).
1272 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(global('Name'))) ,S),
1273 length(S,Len), Len = 8 )).
1274 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(boolean))) ,S),
1275 length(S,Len), Len = 16 )).
1276 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(global('Name')))) ,S),
1277 length(S,Len), Len = 256 )).
1278 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(global('Code')))) ,S),
1279 length(S,Len), Len = 16 )).
1280 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(set(boolean))) ,S),
1281 length(S,Len), Len = 16 )).
1282 :- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(couple(global('Code'),global('Name')))) ,S),
1283 length(S,Len), Len = 64 )).
1284 %:- assert_must_succeed(( findall(XX,enumerate_tight_type(XX, set(couple(global('Code'),integer))) ,S),
1285 % length(S,Len), Len = 64 )).
1286 :- assert_must_succeed(( enumerate_tight_type(XX, set(record([field(balance,integer)]))) ,
1287 XX = [rec([field(balance,int(1))])] )).
1288 :- assert_must_succeed(( enumerate_tight_type(global_set('Code'),set(global('Code'))) )).
1289
1290 enumerate_tight_type(Obj,Type) :-
1291 enumerate_tight_type_wf(Obj,Type,no_wf_available).
1292
1293 enumerate_tight_type_wf(Obj,Type,WF) :-
1294 ? enumerate_tight_type_wf(Obj,Type,trigger_true(enumerate_tight_type),WF).
1295
1296 enumerate_tight_type(Obj,Type,EnumWarning) :- %enumerate_tight_type2(Type,Obj).
1297 enumerate_tight_type_wf(Obj,Type,EnumWarning,no_wf_available).
1298
1299 :- block enumerate_tight_type_wf(?,-,?,?), enumerate_tight_type_wf(?,?,-,?).
1300 enumerate_tight_type_wf(Obj,Type,EnumWarning,WF) :- %enumerate_tight_type2(Type,Obj).
1301 (ground_value(Obj) -> true ; % print(enumerate_tight_type(Obj,Type)),nl,
1302 ? enumerate_basic_type4(Type,Obj,tight,EnumWarning,WF)
1303 ).
1304
1305 /* TO DO: provide tight enumerators for nat, functions, ... ?? */
1306
1307
1308
1309 :- assert_must_succeed((X=[(int(I1),pred_true /* bool_true */),Y], dif(I1,1),
1310 kernel_objects:enumerate_seq_type(X,boolean,true),I1==2,Y=(int(1),pred_false /* bool_false */))).
1311
1312 enumerate_seq_type(X,Type,EnumWarning) :- enumerate_seq_type_wf(X,Type,EnumWarning,no_wf_available).
1313
1314 enumerate_seq_type_wf(X,Type,EnumWarning,WF) :-
1315 list_length_info(X,0,Len,ListType,MaxIndex), % ListType can be open or closed
1316 % determine MaxIndexForEnum:
1317 (ListType=closed
1318 -> MaxIndexForEnum=Len, EW = no_enum_warning,
1319 MaxIndex =< Len % otherwise this is obviously not a sequence (Index in set which is larger than size)
1320 ; ListType=open_bounded(MaxSize)
1321 -> MaxIndexForEnum=MaxSize, EW = no_enum_warning,
1322 MaxIndex =< MaxSize % otherwise cannot be a sequence
1323 % TO DO: use MinSize?
1324 ; (MaxIndex>Len -> Card = MaxIndex ; Card=Len), % in case we already have an explicit index which is higher than the length we use that as index
1325 b_global_set_cardinality('NAT1',NatCard),
1326 (NatCard<Card -> Max1=Card ; Max1=NatCard),
1327 (Max1<1 -> MaxIndexForEnum = 1 ; MaxIndexForEnum=Max1), % ensure that we generate enumeration warning
1328 EW = EnumWarning
1329 ),
1330 ? enumerate_seq(X,range(1,MaxIndexForEnum),MaxIndexForEnum,Type,EW,WF).
1331
1332 enumerate_seq([],_,_,_,_,_WF).
1333 enumerate_seq(V,_,_,_,_,_WF) :- nonvar(V),V=avl_set(_),!.
1334 enumerate_seq(V,_,_,Type,EnumWarning,WF) :- nonvar(V),V=closure(_,_,_),!,
1335 enumerate_basic_type_set(V,Type,not_tight,EnumWarning,WF).
1336 enumerate_seq(Seq,_,_,_,_,_WF) :- nonvar(Seq),
1337 is_custom_explicit_set(Seq,enumerate_seq),!.
1338 enumerate_seq(Seq,Indexes,Card,Type,EnumWarning,WF) :-
1339 (unbound_variable_for_cons(Seq)
1340 -> positive_card(Card),
1341 get_next_index(Indexes,Index,RemIndexes), % force next index
1342 Seq = [(int(Index),Element)|TSeq], VarEl=true
1343 ; Seq = [El|TSeq],
1344 (unbound_variable(El)
1345 -> VarEl=true, get_next_index(Indexes,Index,RemIndexes) % force next index
1346 ; VarEl=false),
1347 El = (int(Index),Element)
1348 ),
1349 (VarEl=true
1350 -> true % index already forced above
1351 ; number(Index) -> remove_index_ground(Indexes,Index,RemIndexes) % this can fail if Index > MaxIndex found above ! but not first time around, i.e., we will generate enum warning anyway
1352 ? ; remove_index(Indexes,Index,RemIndexes)
1353 ),
1354 (EnumWarning==no_enum_warning -> true
1355 ; gen_enum_warning_wf('seq (length)',inf,Card,EnumWarning,unknown,WF)), % delay enum_warning until we have made the first case-split (sometimes instantiating the sequence to at least one element will trigger an inconsistency)
1356 ? enumerate_tight_type_wf(Element,Type,WF),
1357 C1 is Card-1,
1358 ? enumerate_seq(TSeq,RemIndexes,C1,Type,no_enum_warning,WF).
1359
1360 get_next_index([Index1|RestIndexes],Index1,RestIndexes).
1361 get_next_index(range(I1,I2),I1,Res) :-
1362 I11 is I1+1,
1363 (I11>I2 -> Res=[] ; Res=range(I11,I2)).
1364
1365 remove_index_ground(Indexes,X,Res) :- get_next_index(Indexes,H,T),
1366 (X=H -> Res=T ; Res=[H|R2], remove_index_ground(T,X,R2)).
1367
1368 remove_index(Indexes,X,Res) :- get_next_index(Indexes,H,T),
1369 ? (X=H,Res=T ; X\==H, Res=[H|R2], remove_index(T,X,R2)).
1370
1371
1372
1373 /* a few more unit tests: */
1374
1375 :- assert_must_succeed(( findall(X,enumerate_type(X,set(couple(boolean,boolean)),tight) ,L), length(L,16) )).
1376 :- assert_must_succeed(( findall(X,enumerate_type(X,set(couple(boolean,boolean)),basic) ,L), length(L,16) )).
1377
1378 :- assert_must_succeed(( enumerate_tight_type(
1379 [rec([field(balance,int(0)),field(name,fd(2,'Name'))])],[
1380 rec([field(balance,int(1)),field(name,fd(3,'Name'))]),
1381 rec([field(balance,int(1)),field(name,fd(2,'Name'))]),
1382 rec([field(balance,int(0)),field(name,fd(1,'Name'))]),
1383 rec([field(balance,int(-1)),field(name,fd(1,'Name'))])],
1384 set(record([field(balance,integer),field(name,global('Name'))]))) )).
1385 :- assert_must_succeed(( enumerate_tight_type([
1386 rec([field(balance,int(1)),field(name,fd(2,'Name'))]),
1387 rec([field(balance,int(1)),field(name,fd(1,'Name'))]),
1388 rec([field(balance,int(0)),field(name,fd(1,'Name'))]),
1389 rec([field(balance,int(-1)),field(name,fd(1,'Name'))])|X],
1390 set(record([field(balance,integer),field(name,global('Name'))]))) ,
1391 X = [rec([field(balance,int(1)),field(name,fd(3,'Name'))])] )).
1392
1393 :- assert_must_succeed((not_element_of(X,[(pred_true /* bool_true */,pred_true /* bool_true */),
1394 (pred_true /* bool_true */,pred_false /* bool_false */),(pred_false /* bool_false */,pred_false /* bool_false */)]),
1395 enumerate_tight_type(X,couple(boolean,boolean)))).
1396
1397 :- assert_must_succeed(( not_equal_object(X,(pred_true /* bool_true */,pred_false /* bool_false */)),
1398 not_equal_object(X,(pred_false /* bool_false */,pred_false /* bool_false */)),
1399 not_equal_object(X,(pred_true /* bool_true */,pred_true /* bool_true */)),
1400 enumerate_tight_type(X,couple(boolean,boolean)))).
1401
1402 :- assert_must_succeed(( X = [fd(3,'Name')|T],enumerate_tight_type(X,set(global('Name'))),
1403 T == [fd(1,'Name'),fd(2,'Name')] )).
1404
1405
1406
1407 unbound_value(V) :-
1408 (var(V) -> unbound_variable(V)
1409 ; V = (V1,W1),unbound_value(V1), unbound_value(W1)).
1410
1411 :- use_module(bsyntaxtree,[syntaxtraversion/6]).
1412 enumerate_values_inside_expression(TExpr,WF) :-
1413 syntaxtraversion(TExpr,Expr,Type,_Infos,Subs,_),
1414 nonvar(Expr),!,
1415 ? enumerate_expr(Expr,Type,Subs,WF).
1416 enumerate_values_inside_expression(X,WF) :-
1417 add_internal_error('Unexpected B expression: ',enumerate_values_inside_expression(X,WF)).
1418
1419 %:- block enumerate_expr(-,?,?,?).
1420 enumerate_expr(value(X),Type,Subs,WF) :- !,
1421 ? (ground(Type) -> enumerate_value(X,Type,WF)
1422 ; add_internal_error('Value type not ground: ',enumerate_expr(value(X),Type,Subs,WF))).
1423 ?enumerate_expr(_,_,Subs,WF) :- l_enumerate_values_inside_expression(Subs,WF).
1424
1425 :- use_module(bsyntaxtree,[is_set_type/2]).
1426 % catch a few type errors:
1427 enumerate_value(X,Type,_) :- X==[], !,
1428 (is_set_type(Type,_) -> true ; add_internal_error('Illegal type: ',enumerate_value(X,Type,_))).
1429 ?enumerate_value(X,Type,WF) :- enumerate_basic_type_wf(X,Type,WF).
1430
1431 :- block l_enumerate_values_inside_expression(-,?).
1432 l_enumerate_values_inside_expression([],_WF).
1433 l_enumerate_values_inside_expression([H|T],WF) :-
1434 ? enumerate_values_inside_expression(H,WF),
1435 ? l_enumerate_values_inside_expression(T,WF).
1436
1437
1438 /* --------------- */
1439 /* top_level_dif/2 */
1440 /* --------------- */
1441 /* checks whether two terms have a different top-level functor */
1442
1443 :- assert_must_succeed(top_level_dif(a,b)).
1444 :- assert_must_succeed(top_level_dif(f(_X),g(_Z))).
1445 :- assert_must_fail(top_level_dif(f(a),f(_Z))).
1446 :- assert_must_fail(top_level_dif(f(a),f(b))).
1447
1448 :- block top_level_dif(-,?),top_level_dif(?,-).
1449 top_level_dif(X,Y) :-
1450 functor(X,FX,_),functor(Y,FY,_), FX\=FY. /* check arities ? */
1451
1452
1453 /* ------------------------------------------------------------------- */
1454 /* EQUAL OBJECT */
1455 /* ------------------------------------------------------------------- */
1456
1457 sample_closure(C) :-
1458 construct_closure([xx],[integer],Body,C),
1459 Body = b(conjunct(b(conjunct(
1460 b(member(b(identifier(xx),integer,[]),b(integer_set('NAT'),set(identifier(xx)),[])),pred,[]),
1461 b(greater(b(identifier(xx),integer,[]),b(integer(0),integer,[])),pred,[])),pred,[]),
1462 b(less(b(identifier(xx),integer,[]),b(integer(3),integer,[])),pred,[])),pred,[]).
1463
1464 :- assert_must_succeed(equal_object([int(3),int(1)],
1465 closure([zz],[integer],b(member(b(identifier(zz),integer,[]),b(value([int(1),int(3)]),set(integer),[])),pred,[])))).
1466 :- assert_must_succeed(( equal_object( (fd(1,'Name'),fd(1,'Name')) , (fd(1,'Name'),fd(1,'Name')) ) )).
1467 :- assert_must_succeed(( equal_object( (X,Y) , (fd(2,'Name'),fd(2,'Name')) ) , X = fd(2,'Name'), Y=fd(2,'Name') )).
1468 :- assert_must_fail(equal_object(term(a),term(b))).
1469 :- assert_must_fail(equal_object(int(1),int(2))).
1470 :- assert_must_fail(equal_object([term(a),term(b)],[term(a),term(c)])).
1471 :- assert_must_fail((equal_object([(int(1),[Y])],[(int(X),[Z])]),
1472 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[int(2)])).
1473 :- assert_must_fail(equal_object(rec([field(a,int(1))]),rec([field(a,int(2))]))).
1474 :- assert_must_fail(equal_object(rec([field(a,int(2)),field(b,int(3))]),
1475 rec([field(a,int(2)),field(b,int(4))]))).
1476 :- assert_must_succeed(equal_object(rec([field(a,int(2))]),rec([field(a,int(2))]))).
1477 :- assert_must_succeed(equal_object(rec([field(a,int(2)),field(b,[int(3),int(2)])]),
1478 rec([field(a,int(2)),field(b,[int(2),int(3)])]) )).
1479 :- assert_must_succeed(equal_object([(term(a),[])],[(term(a),[])])).
1480 :- assert_must_succeed(equal_object(_X,[int(1),int(2)])).
1481 :- assert_must_succeed(equal_object([int(1),int(2)],_X)).
1482 :- assert_must_succeed((equal_object([(int(1),[Y])],[(int(X),[Z])]),
1483 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[])).
1484 :- assert_must_succeed(equal_object([int(1),int(2)],[int(2),int(1)])).
1485 :- assert_must_succeed(equal_object(global_set('Name'),[fd(2,'Name'),fd(3,'Name'),fd(1,'Name')])).
1486 :- assert_must_succeed(equal_object(global_set('Name'),[fd(1,'Name'),fd(3,'Name'),fd(2,'Name')])).
1487 :- assert_must_succeed((equal_object([fd(3,'Name'),fd(2,'Name'),fd(1,'Name')],global_set('Name')))).
1488 %:- assert_must_succeed((equal_object([fd(3,'Name'),fd(2,'Name'),fd(1,'Name')],X),X=global_set('Name'))).
1489 :- assert_must_succeed((equal_object(Y,X),X=global_set('Name'),equal_object(Y,[fd(3,'Name'),fd(2,'Name'),fd(1,'Name')]))).
1490 :- assert_must_succeed((equal_object(X,X),X=global_set('Name'))).
1491 :- assert_must_succeed((equal_object(_,X),X=global_set('Name'))).
1492 :- assert_must_succeed((equal_object(X,global_set('Name')),X=global_set('Name'))).
1493 :- assert_must_succeed((equal_object([_A,_B],[int(2),int(1)]))).
1494 :- assert_must_fail((equal_object(X,global_set('Code')),X=global_set('Name'))).
1495 :- assert_must_fail((equal_object(Y,global_set('Name')),Y=[fd(3,'Name'),fd(1,'Name')])).
1496 :- assert_must_fail((equal_object(Y,global_set('Name')),Y=[_,_])).
1497 :- assert_must_succeed((equal_object(X,closure([xx],[integer],b(truth,pred,[]))),X==closure([xx],[integer],b(truth,pred,[])))).
1498 :- assert_must_succeed((sample_closure(C), equal_object([int(1),int(2)],C))).
1499 :- assert_must_succeed((sample_closure(C), equal_object(C,[int(1),int(2)]))).
1500 :- assert_must_fail((sample_closure(C), equal_object(C,[int(1),int(0)]))).
1501 :- assert_must_fail((sample_closure(C), equal_object(C,global_set('NAT')))).
1502 :- assert_must_succeed((equal_object(freeval(selfcx,a,int(5)),freeval(selfcx,a,int(5))))).
1503 :- assert_must_fail((equal_object([int(1),int(2),int(3)],global_set('NATURAL1')))).
1504 :- assert_must_fail((equal_object(X,global_set('NATURAL1')),equal_object(X,[int(1),int(2),int(3)]))).
1505 :- assert_must_fail((equal_object(X,[int(1),int(2),int(3)]),equal_object(X,global_set('NATURAL1')))).
1506 :- assert_must_fail((equal_object(X,global_set('NATURAL')),equal_object(X,global_set('NATURAL1')))).
1507 :- assert_must_succeed((equal_object(X,global_set('NATURAL')),equal_object(X,global_set('NATURAL')))).
1508 % :- assert_must_fail((equal_object(freeval(selfcx,a,int(5)),freeval(selfcy,a,int(5))))). % is a type error
1509 :- assert_must_fail((equal_object(freeval(selfcx,b,int(5)),freeval(selfcx,a,int(5))))).
1510 :- assert_must_fail((equal_object(freeval(selfcx,a,int(5)),freeval(selfcx,a,int(6))))).
1511 :- assert_must_succeed((equal_object(
1512 [[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
1513 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(3,'Name'),fd(2,'Name')]]
1514 ,[[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
1515 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(2,'Name'),fd(3,'Name')]])
1516 )).
1517 :- assert_must_succeed(exhaustive_kernel_check( (equal_object([int(3),int(2),int(1)],[int(2)|T]),
1518 equal_object(T,[int(1),int(3)])))).
1519 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object([int(3),int(1)],[int(1),int(3)]))).
1520 :- assert_must_succeed(exhaustive_kernel_check([commutative],equal_object([int(3),int(4),int(1)],[int(4),int(1),int(3)]))).
1521
1522 %:- assert_must_succeed(exhaustive_kernel_fail_check([commutative],equal_object([int(1),int(2),int(3)],global_set('NATURAL1')))).
1523 :- assert_must_succeed(( equal_object([int(0),int(5)|T],avl_set(node(int(1),true,1,node(int(0),true,0,empty,empty),node(int(3),true,1,empty,node(int(5),true,0,empty,empty))))), nonvar(T),equal_object(T,[int(_A),int(_B)]) )).
1524 % NOTE: had multiple solutions; after solving Ticket #227 it no longer has :-)
1525 :- assert_must_succeed(( equal_object([int(0),int(5)|T],avl_set(node(int(1),true,1,node(int(0),true,0,empty,empty),node(int(3),true,1,empty,node(int(5),true,0,empty,empty))))), nonvar(T),equal_object(T,[_A,_B]) )).
1526
1527 :- assert_must_succeed((equal_object([_X,_Y],[int(1),int(2)]))).
1528 :- assert_must_succeed((equal_object([(int(1),X),(int(2),Y),(int(3),Z),(int(4),A),(int(5),B),(int(6),C),(int(7),D),(int(8),E),(int(9),F),(int(10),G)],avl_set(node((int(5),int(25)),true,0,node((int(2),int(4)),true,1,node((int(1),int(1)),true,0,empty,empty),node((int(3),int(9)),true,1,empty,node((int(4),int(16)),true,0,empty,empty))),node((int(8),int(64)),true,0,node((int(6),int(36)),true,1,empty,node((int(7),int(49)),true,0,empty,empty)),node((int(9),int(81)),true,1,empty,node((int(10),int(100)),true,0,empty,empty)))))),
1529 A == int(16), B == int(25),C == int(36),D == int(49),E == int(64),F == int(81),G == int(100),X == int(1),Y == int(4), Z == int(9))).
1530
1531 :- use_module(bool_pred).
1532
1533 ?equal_object(V1,V2) :- equal_object_wf(V1,V2,no_wf_available).
1534 ?equal_object(V1,V2,Origin) :- equal_object_wf(V1,V2,Origin,no_wf_available).
1535 ?equal_object_optimized(V1,V2,Origin) :- equal_object_optimized_wf(V1,V2,Origin,no_wf_available).
1536 ?equal_object_optimized(V1,V2) :- equal_object_optimized(V1,V2,unknown).
1537
1538 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
1539 :- if(environ(prob_safe_mode,true)).
1540 /* a version of equal_object which will convert lists to avl if possible */
1541 equal_object_optimized_wf(V1,V2,Origin,WF) :-
1542 ( var(V1) -> (var(V2) -> V1=V2 ; equal_object_opt3(V2,V1,WF))
1543 ; equal_object_opt3(V1,V2,WF)),
1544 check_value(V1,Origin), check_value(V2,Origin).
1545 equal_object_wf(V1,V2,Origin,WF) :- ( (var(V1);var(V2)) -> V1=V2
1546 ; nonvar(V1) -> equal_object3(V1,V2,WF)
1547 ; equal_object3(V2,V1,WF)),
1548 check_value(V1,val1(Origin)), check_value(V2,val2(Origin)).
1549 equal_object_wf(V1,V2,WF) :- ( (var(V1);var(V2)) -> V1=V2
1550 ; nonvar(V1) -> equal_object3(V1,V2,WF)
1551 ; equal_object3(V2,V1,WF)),
1552 check_value(V1,equal_object1), check_value(V2,equal_object2).
1553 check_value(X,Origin) :- nonvar(X) -> check_value_aux(X,Origin) ; true.
1554 check_value_aux((A,B),Origin) :- !, check_value(A,pair1(Origin)), check_value(B,pair2(Origin)).
1555 check_value_aux([H|T],Origin) :- !, check_value(H,head(Origin)), check_value(T,tail(Origin)).
1556 check_value_aux(avl_set(X),Origin) :- !,
1557 (var(X) -> add_warning(Origin,'Variable avl_set')
1558 ; X=empty -> add_warning(Origin,'Empty avl_set') ; true).
1559 check_value_aux(closure(P,T,B),Origin) :- !,
1560 (ground(P),ground(T),nonvar(B) -> true
1561 ; add_warning(Origin,illegal_closure(P,T,B))).
1562 check_value_aux(_,_Origin).
1563 :- else.
1564 /* a version of equal_object which will convert lists to avl if possible */
1565 equal_object_optimized_wf(V1,V2,_Origin,WF) :-
1566 ? ( var(V1) -> (var(V2) -> V1=V2 ; equal_object_opt3(V2,V1,WF))
1567 ? ; equal_object_opt3(V1,V2,WF)).
1568
1569 equal_object_wf(V1,V2,_Origin,WF) :- ( (var(V1);var(V2)) -> V1=V2
1570 ? ; nonvar(V1) -> equal_object3(V1,V2,WF)
1571 ; equal_object3(V2,V1,WF)).
1572 equal_object_wf(V1,V2,WF) :- ( (var(V1);var(V2)) -> V1=V2
1573 ? ; nonvar(V1) -> equal_object3(V1,V2,WF)
1574 ; equal_object3(V2,V1,WF)).
1575 :- endif.
1576
1577
1578 equal_object_opt3(int(X),Y,_WF) :- !, Y=int(X).
1579 equal_object_opt3(fd(X,T),Y,_WF) :- !, Y=fd(X,T).
1580 equal_object_opt3(string(X),Y,_WF) :- !, Y=string(X).
1581 equal_object_opt3(pred_false,Y,_WF) :- !, Y=pred_false.
1582 equal_object_opt3(pred_true,Y,_WF) :- !, Y=pred_true.
1583 equal_object_opt3(X,S2,WF) :- var(S2), %unbound_variable(S2), % is it ok to assing an AVL set in one go ?!
1584 should_be_converted_to_avl_from_lists(X), !, % does a ground(X) check
1585 ? construct_avl_from_lists_wf(X,S2,WF).
1586 %equal_object_opt3([H|T],S2) :- var(S2),ground(H),ground(T), !, construct_avl_from_lists([H|T],S2).
1587 ?equal_object_opt3(X,Y,WF) :- equal_object3(X,Y,WF).
1588
1589
1590 %%equal_object3c(X,Y) :- if(equal_object3(X,Y),true,
1591 %% (print_message(equal_object3_failed(X,Y)),equal_object3(X,Y),fail)). %%
1592 :- if(environ(prob_safe_mode,true)).
1593 equal_object3(X,Y,_WF) :- (nonvar(Y) -> type_error(X,Y) ; illegal_value(X)),
1594 add_internal_error('Internal Typing Error (please report as bug !) : ',equal_object(X,Y)),fail.
1595 :- endif.
1596 equal_object3(closure(Par,ParTypes,Clo),Y,WF) :- var(Y),!,
1597 ( closure_occurs_check(Y,Par,ParTypes,Clo)
1598 -> print(occurs_check(Y,Par)),nl,
1599 expand_custom_set_wf(closure(Par,ParTypes,Clo),Expansion,equal_object3,WF),
1600 equal_object_optimized_wf(Y,Expansion,equal_object3,WF)
1601 ; Y = closure(Par,ParTypes,Clo)).
1602 equal_object3(closure(Parameters,PT,Cond),Y,WF) :-
1603 ? equal_object_custom_explicit_set(closure(Parameters,PT,Cond),Y,WF).
1604 %equal_object3(Obj,Y) :- is_custom_explicit_set(Obj,equal_object3_Obj),
1605 % equal_object_custom_explicit_set(Obj,Y,WF). % inlined below for performance
1606 equal_object3(global_set(X),Y,WF) :- equal_object_custom_explicit_set(global_set(X),Y,WF).
1607 equal_object3(freetype(X),Y,WF) :- equal_object_custom_explicit_set(freetype(X),Y,WF).
1608 ?equal_object3(avl_set(X),Y,WF) :- equal_object_custom_explicit_set(avl_set(X),Y,WF).
1609 equal_object3(pred_true /* bool_true */,pred_true /* bool_true */,_WF).
1610 equal_object3(pred_false /* bool_false */,pred_false /* bool_false */,_WF).
1611 equal_object3(term(X),term(X),_WF).
1612 equal_object3(string(X),string(X),_WF).
1613 ?equal_object3(rec(F1),rec(F2),WF) :- equal_fields_wf(F1,F2,WF).
1614 equal_object3(freeval(Id,C,F1),freeval(Id,C,F2),WF) :-
1615 (freetype_with_single_case(Id,Case) -> C=Case ; true),
1616 equal_object_wf(F1,F2,WF).
1617 equal_object3(int(X),int(X),_WF).
1618 ?equal_object3(fd(X,Type),fd(Y,Type),_WF) :- eq_fd(X,Y).
1619 equal_object3((X,Y),(X2,Y2),WF) :-
1620 ? equal_object_wf(X,X2,WF), equal_object_wf(Y,Y2,WF). % initially order was reversed; but this can lead to issues in e.g. g(f("f2")), for f = {"f0"|->0, "f2"|->2} where g gets called for 0 before "f2"="f0" fails
1621 equal_object3([],X,WF) :- empty_set_wf(X,WF).
1622 equal_object3([H|T],S2,WF) :- nonvar(S2), is_custom_explicit_set_nonvar(S2),!,
1623 ? equal_custom_explicit_set_cons_wf(S2,H,T,WF).
1624 %equal_object3([H|T],S2,WF) :- equal_cons_wf(S2,H,T,WF). % leads to time-out for test 1270 : TODO investigate
1625 ?equal_object3([H|T],S2,_WF) :- equal_cons(S2,H,T).
1626
1627
1628 equal_object_custom_explicit_set(Obj,Y,WF) :-
1629 (var(Y) -> Y = Obj
1630 ? ; (is_custom_explicit_set_nonvar(Y) -> equal_explicit_sets_wf(Obj,Y,WF)
1631 ; (Y=[] -> is_empty_explicit_set_wf(Obj,WF)
1632 ? ; Y=[H|T] -> equal_custom_explicit_set_cons_wf(Obj,H,T,WF)
1633 ; add_internal_error('Illegal set: ',equal_object_custom_explicit_set(Obj,Y,WF)),fail
1634 )
1635 )).
1636
1637 equal_custom_explicit_set_cons_wf(CS,H,T,_WF) :- CS \= avl_set(_),
1638 var(H),var(T), % TO DO: should we move this treatment below ? to equal_cons_lwf
1639 % YES, I THINK WE CAN DELETE THIS NOW for avl_sets; but not yet for global_set,...
1640 % print_term_summary(equal_custom_explicit_set_cons(CS,H,T)),nl, (debug_mode(on) -> trace ; true),
1641 unbound_variable(H),
1642 unbound_variable_for_cons(T),
1643 !,
1644 remove_minimum_element_custom_set(CS,Min,NewCS),
1645 (H,T) = (Min,NewCS).
1646 equal_custom_explicit_set_cons_wf(avl_set(AVL),H,T,_WF) :- var(H),
1647 is_unbound_ordered_list_skeleton(H,T),!, % TO DO: provide this also for global_set(_)
1648 % below we check if H can be removed from AVL and remove it
1649 remove_minimal_elements([H|T],avl_set(AVL),SkeletonToUnify),
1650 [H|T] = SkeletonToUnify.
1651 equal_custom_explicit_set_cons_wf(Obj,H,T,WF) :-
1652 ? equal_cons_lwf(Obj,H,T,2,WF).
1653 %equal_cons_wf(Obj,H,T,WF). % equal_cons_wf causes issues to tests 799, (but not anymore 1751, 1642, 1708)
1654
1655
1656 :- block equal_fields_wf(-,-,?).
1657 equal_fields_wf([],[],_).
1658 equal_fields_wf([field(Name1,V1)|T1],[field(Name2,V2)|T2],WF) :-
1659 check_field_name_compatibility(Name1,Name2,equal_fields_wf),
1660 ? equal_object_wf(V1,V2,field,WF),
1661 ? equal_fields_wf(T1,T2,WF).
1662
1663
1664 % is just like equal_cons, but H and T are guaranteed by the caller to be free
1665 % this just gives one next element of the set; can be used to iterate over sets.
1666 get_next_element(R,H,T) :- var(R),!,R=[H|T].
1667 get_next_element([H1|T1],H,T) :- !,(H1,T1)=(H,T).
1668 get_next_element(R,H,T) :- equal_cons(R,H,T).
1669
1670
1671 equal_cons_wf(R,H,T,WF) :- WF == no_wf_available,!, equal_cons_lwf(R,H,T,2,WF).
1672 equal_cons_wf(R,H,T,WF) :-
1673 %get_cardinality_wait_flag(R,equal_cons_wf,WF,LWF),
1674 %get_binary_choice_wait_flag(equal_cons_wf,WF,LWF), %old version
1675 LWF = lwf_card(R,equal_cons_wf,WF), % will be instantiated by instantiate_lwf
1676 ? equal_cons_lwf(R,H,T,LWF,WF).
1677
1678 % a deterministic version; will never instantiate non-deterministically:
1679 % probably better to use equal_cons_wf if possible
1680 %equal_cons_det(R,H,T) :- equal_cons_lwf4(R,H,T,_).
1681
1682 equal_cons(R,H,T) :-
1683 ? equal_cons_lwf(R,H,T,2,no_wf_available). %lwf_first(2)).
1684
1685 :- block blocking_equal_cons_lwf(-,?,?,?,?).
1686 ?blocking_equal_cons_lwf(E,H,T,LWF,WF) :- equal_cons_lwf(E,H,T,LWF,WF).
1687
1688 %equal_cons_lwf4(R,H,T,LWF) :- equal_cons_lwf(R,H,T,LWF,no_wf_available).
1689
1690 ?equal_cons_lwf(R,H,T,_,_) :- var(R),!,add_new_el(T,H,R).
1691 equal_cons_lwf([HR|TR],H,T,_,WF) :- ground_value(H), %print(delete_exact(H,[HR|TR])),nl,
1692 try_quick_delete_exact_member([HR|TR],H,Rest), % try and see if we can find an exact member in the list
1693 % adds quadratic complexity if TR is a list; TODO: maybe do a sort
1694 !,
1695 %equal_object(Rest,T,equal_cons_lwf_1).
1696 ? equal_object_wf(Rest,T,equal_cons_lwf_1,WF).
1697 ?equal_cons_lwf([HR|TR],H,T,LWF,WF) :- !, equal_cons_cons(HR,TR,H,T,LWF,WF).
1698 equal_cons_lwf(avl_set(AVL),H,T,LWF,WF) :- !,
1699 (is_one_element_custom_set(avl_set(AVL),El)
1700 ? -> empty_set(T), % was T=[], but T could be an empty closure !
1701 ? equal_object_wf(El,H,equal_cons_lwf_2,WF)
1702 ; T==[] -> fail % we have a one element set and AVL is not
1703 ; element_can_be_added_or_removed_to_avl(H) ->
1704 remove_element_from_explicit_set(avl_set(AVL),H,AR),
1705 ? equal_object_wf(AR,T,equal_cons_lwf_3,WF)
1706 ; nonvar(T),T=[H2|T2],element_can_be_added_or_removed_to_avl(H2) ->
1707 remove_element_from_explicit_set(avl_set(AVL),H2,AR),
1708 ? equal_object_wf(AR,[H|T2],equal_cons_lwf_4,WF)
1709 % TO DO: move all such H2 to the front ??
1710 % Common pattern for function application patterns f(a) = 1 & f(b) = 2 & f = AVL
1711 % We have f = [(a,1),(b,2)|_] to be unified with an avl_set
1712 ; at_most_one_match_possible(H,AVL,Pairs) -> Pairs=[H2], % unification could fail if no match found
1713 % this optimisation is redundant wrt definitely_not_in_list optimisation below; check test 1716
1714 % but it has better performance for large sets, e.g., when unifying with a large sequence skeleton
1715 % TODO: it could be useful even if there are more than one matches??
1716 ? equal_object_wf(H,H2,WF),
1717 % element_can_be_added_or_removed_to_avl not checked !
1718 % we may need to call another predicate to remove, which only checks index
1719 % or at_most_one_match_possible should remove the element itself
1720 remove_element_from_explicit_set(avl_set(AVL),H2,AR), % print(removed_from_avl_by_equal_cons(H)),nl,
1721 ? equal_object(AR,T,equal_cons_lwf_3)
1722 ; expand_custom_set_wf(avl_set(AVL),ES,equal_cons_lwf,WF), % length(ES,LenES),print(expanded(LenES,T)),nl,
1723 % before attempting unification quickly look if lengths are compatible:
1724 quick_check_length_compatible(ES,[H|T]), % not really sure this is worth it: we have propagate_card in equal_cons_cons below
1725 %we could do the following: (nonvar(LWF),LWF=lwf_card(_,_,WF) -> quick_propagation_element_information(avl_set(AVL),H,WF,NS) ; true) % we could also do it for T, but both H/T can cause issues with free_var detection
1726 equal_cons_perf_message(AVL,H,T,WF),
1727 ? equal_cons_lwf(ES,H,T,LWF,WF) ).
1728 equal_cons_lwf(C,H,T,LWF,WF) :-
1729 is_interval_closure_or_integerset(C,Low,Up),
1730 (T==[] -> true ; finite_bound(Low), finite_bound(Up)),
1731 !,
1732 ? equal_cons_interval(H,T,Low,Up,LWF,WF).
1733 equal_cons_lwf(closure(P,Ty,B),H,T,LWF,WF) :- !,
1734 equal_cons_closure(P,Ty,B,H,T,LWF,WF).
1735 equal_cons_lwf(freetype(ID),H,T,LWF,WF) :- !, expand_custom_set_wf(freetype(ID),ES,equal_cons_lwf,WF),
1736 blocking_equal_cons_lwf(ES,H,T,LWF,WF).
1737 ?equal_cons_lwf(global_set(G),H,T,LWF,WF) :- equal_cons_global_set(G,H,T,LWF,WF).
1738
1739
1740 :- use_module(probsrc(avl_tools),[avl_height_less_than/2]).
1741 :- use_module(performance_messages,[perf_format_wf/3]).
1742 equal_cons_perf_message(AVL,H,T,WF) :- preference(performance_monitoring_on,true),
1743 \+ avl_height_less_than(AVL,5),
1744 \+ is_unbound_ordered_list_skeleton(H,T), % otherwise H will be set to minimum of AVL deterministically
1745 !,
1746 translate:translate_bvalue(avl_set(AVL),AS),
1747 translate:translate_bvalue([H|T],HTS),
1748 perf_format_wf('Expanding avl_set for set-unification ~w = ~w~n',[AS,HTS],WF).
1749 %tools_printing:print_term_summary([H|T]).
1750 equal_cons_perf_message(_,_,_,_).
1751
1752 equal_cons_closure(P,Ty,B,_H,T,_LWF,_WF) :- nonvar(T),
1753 is_definitely_finite(T), % move earlier; is_infinite_closure can perform expansions, e.g., for nested closures
1754 is_infinite_closure(P,Ty,B),
1755 !,
1756 fail. % an infinite set cannot be equal to a finite one.
1757 equal_cons_closure(P,Ty,B,H,T,LWF,WF) :-
1758 expand_custom_set_wf(closure(P,Ty,B),ES,equal_cons_closure,WF),
1759 blocking_equal_cons_lwf(ES,H,T,LWF,WF).
1760
1761 is_definitely_finite(Var) :- var(Var),!,fail.
1762 is_definitely_finite([]).
1763 is_definitely_finite([_|T]) :- is_definitely_finite(T).
1764 is_definitely_finite(avl_set(_)).
1765
1766 %get_wf_from_lwf(LWF,WF) :- % TO DO: a cleaner, less hacky version; passing WF around if possible
1767 % (nonvar(LWF),LWF=lwf_card(_,_,WF1) -> WF=WF1 ; WF = no_wf_available).
1768
1769 finite_bound(I) :- (var(I) -> true /* inf would be created straightaway */ ; number(I)).
1770
1771 % Purpose: treat some specific closures better; e.g., interval closures and constraint a..b = {1,y,5,x,4} or a..b = {x} & x:100..1002
1772 equal_cons_interval(H,T,Low,Up,_LWF,_WF) :- T==[],!, % Low..Up = {H} -> Low=H & Up=H
1773 % unification will fail if Low or Up are not numbers (inf)
1774 (int(Low),int(Up)) = (H,H).
1775 %equal_cons_interval(_H,_T,Low,Up,_LWF,WF) :- (nonvar(Low),\+ number(Low) ; nonvar(Up),\+ number(Up)),!,
1776 % gen_enum_warning_wf('OPEN INTERVAL',Low:Up,'cannot expand',trigger_throw(equal_cons_interval),WF),
1777 % % we could try and instantiate T to an infinite closure
1778 % fail.
1779 equal_cons_interval(H,T,Low,Up,LWF,WF) :-
1780 (number(Low),number(Up) -> true % we can expand interval fully
1781 ; propagate_in_interval([H|T],int(Low),int(Up),0)),
1782 expand_interval_closure_to_avl(Low,Up,ES),
1783 ? blocking_equal_cons_lwf(ES,H,T,LWF,WF).
1784
1785 :- block propagate_in_interval(-,?,?,?).
1786 propagate_in_interval([],Low,Up,Sze) :-
1787 ? (Sze > 0 -> S1 is Sze-1, int_plus(Low,int(S1),Up) ; true). % Test should always be true
1788 propagate_in_interval([H|T],Low,Up,Sze) :-
1789 in_nat_range(H,Low,Up), % without enumeration
1790 S1 is Sze+1,
1791 ? propagate_in_interval(T,Low,Up,S1).
1792 propagate_in_interval(avl_set(_A),_Low,_Up,_). % TO DO: propagate if Low/Up not instantiated
1793 propagate_in_interval(closure(_,_,_),_,_,_).
1794 propagate_in_interval(global_set(_),_,_,_).
1795
1796 quick_check_length_compatible([],R) :- !,
1797 (var(R) -> R=[] % can we force R=[] here ??
1798 ; R \= [_|_]). %(R \= [_|_] -> true ; print(incompatible(R)),fail).
1799 quick_check_length_compatible([_|T],R) :-
1800 (var(R) -> true
1801 ; R = [] -> fail
1802 ; R = [_|RT] -> quick_check_length_compatible(T,RT)
1803 ; true).
1804
1805 :- block equal_cons_global_set(-,?,?,?,?).
1806 ?equal_cons_global_set(G,H,T,LWF,WF) :- is_infinite_global_set(G,_),!,
1807 % for maximal sets we could complement_set([H],global(G),Res),
1808 /* should normally fail, unless T is not a list but contains closure or global set */
1809 test_finite_set_wf(T,Finite,WF), dif(Finite,pred_true),
1810 when((nonvar(Finite);nonvar(LWF)),equal_cons_global_set_warning(LWF,G,H,T,WF)).
1811 % used to be : expand_custom_set(global_set(G),ES), equal_cons_lwf4(ES,H,T,LWF))).
1812 equal_cons_global_set(G,H,T,LWF,WF) :-
1813 %(is_infinite_global_set(G,_) -> test_finite_set_wf(T,Finite,WF), Finite \== pred_true ; true),
1814 expand_custom_set_wf(global_set(G),ES,equal_cons_global_set,WF),
1815 ? equal_cons_lwf(ES,H,T,LWF,WF).
1816
1817
1818 :- block equal_cons_global_set_warning(-,?,?,?,?).
1819 equal_cons_global_set_warning(_,G,H,T,WF) :-
1820 add_new_event_in_error_scope(enumeration_warning(enumerating(G),G,'{}',finite,critical),
1821 print_equal_cons_warning(G,H,T,WF)),
1822 fail. % WITH NEW SEMANTICS OF ENUMERATION WARNING WE SHOULD PROBABLY ALWAYS FAIL HERE !
1823
1824 % THROWING, Span added by add_new_event_in_error_scope
1825 print_equal_cons_warning(G,H,T,WF,THROWING,Span) :-
1826 print('### Enumeration Warning: trying to deconstruct infinite set: '),
1827 translate:print_bvalue(global_set(G)),nl,
1828 print('### Source: '), print(equal_cons_global_set(G,H,T)),nl,
1829 print_throwing_wf(THROWING,unknown_info,Span,WF).
1830
1831 add_new_el(T,H,R) :- var(T),!,R=[H|T].
1832 add_new_el(T,H,R) :- nonvar(T), is_custom_explicit_set_nonvar(T),
1833 add_element_to_explicit_set_wf(T,H,Res,no_wf_available), % will fail for closure/3
1834 !,
1835 Res=R.
1836 add_new_el([HT|TT],H,R) :- !,R=[H,HT|TT].
1837 add_new_el([],H,R) :- !, R=[H].
1838 add_new_el(Set,H,R) :- expand_custom_set_to_list(Set,ESet,_,add_new_el),
1839 add_new_el(ESet,H,R).
1840
1841 %delete_exact_member(V,_,_) :- var(V),!,fail.
1842 %delete_exact_member([H|T],El,Res) :-
1843 % (H==El -> Res=T
1844 % ; Res=[H|TR], delete_exact_member(T,El,TR)).
1845
1846 % a version of delete_exact_member with a cut off
1847 % avoids spending useless time traversing large non-ground lists
1848 % for a list consisting only of non-ground elements delete_exact_member will never succeed !
1849 % this occurs e.g., when a large list skeleton generated by e.g. size_of_sequence is unified with an avl_set
1850 % (e.g., m = READ_PGM_IMAGE_FILE("pgm_files/yuv_1.pgm") & %i.(i:1..550| m(i) /|\ 725))
1851 try_quick_delete_exact_member(List,El,Result) :-
1852 try_quick_delete_exact_member(List,1,El,Result).
1853 try_quick_delete_exact_member(V,_,_,_) :- var(V),!,fail.
1854 try_quick_delete_exact_member([H|T],Sz,El,Res) :-
1855 (H==El -> Res=T
1856 ; Res=[H|TR],
1857 (Sz>50
1858 -> ground_value(H), % after a certain limit we only proceed if there are ground elements
1859 % we could also check: preferences:preference(use_smt_mode,true)
1860 Sz=30 % check again in 20 steps
1861 ; Sz1 is Sz+1),
1862 try_quick_delete_exact_member(T,Sz1,El,TR)).
1863
1864
1865 %unbound_variable(V) :- !, unbound_variable_check(V).
1866 unbound_variable(V) :- free_var(V), frozen(V,Residue),
1867 %unbound_residue(Residue,V).
1868 (unbound_residue(Residue,V) -> true ; %print(bound_var(V,Residue)),nl,trace,unbound_residue(Residue,V),
1869 fail).
1870 unbound_residue((A,B),V) :- !,unbound_residue(A,V), unbound_residue(B,V).
1871 unbound_residue(true,_) :- !.
1872 unbound_residue(Module:Call,Variable) :- unbound_residue_m(Module,Call,Variable).
1873
1874 unbound_residue_m(external_functions,to_string_aux(GrV,_Val,Str),V) :- !, %GrV checks for groundness of _Val
1875 V==GrV,unbound_variable(Str).
1876 unbound_residue_m(external_functions,format_to_string_aux(GrV,_Format,_Val,Str),V) :- !,
1877 %GrV checks for groundness of _Val
1878 V==GrV,unbound_variable(Str).
1879 % TO DO: we need to detect other functions (e.g., B function application,...) which result in values which are not used
1880 %unbound_residue_m(_,ground_value_check(V1,V2),V) :- !, V1==V, unbound_variable(V2). % V1==V not necessary?! cycle check
1881 unbound_residue_m(Module,Residue,Var) :- unbound_basic_residue(Module,Residue,Var).
1882
1883 %unbound_basic_residue(_,true,_).
1884 unbound_basic_residue(_,ground_value_check(V1,V2),Var) :- !, Var==V1, % == check to prevent loops
1885 % in particularly in SWI, where residues also contain calls where Var==V2; e.g., test 639
1886 unbound_variable(V2).
1887 unbound_basic_residue(_,ground_value_check_aux(V1,V2,V3),Var) :- !, (Var==V1 -> true ; Var==V2), unbound_variable(V3).
1888 % we could also treat ground_value_opt_check
1889 unbound_basic_residue(b_interpreter_components,observe_variable_block(_,_,_,_,_),_). % when in -p TRACE_INFO TRUE mode
1890 unbound_basic_residue(b_interpreter_components,observe_variable1_block(_,_,_,_),_). % (provide_trace_information pref)
1891 unbound_basic_residue(kernel_objects,mark_as_to_be_computed(_),_).
1892 unbound_basic_residue(custom_explicit_sets,block_copy_waitflag_store(_,_,_,_,_),_). % this stems from checking the domain predicate of function application check_element_of_function_closure
1893 %unbound_basic_residue(kernel_objects,ordered_value(V,_),_). % <-- TO DO: treat this and then assign minimal value !
1894 %unbound_basic_residue(kernel_ordering,ordered_value2(V,_),_).
1895 % b_tighter_enumerate_sorted_value_and_continue
1896 %unbound_basic_residue(M,U,Var) :- print(bound_basic_residue(M,U,Var)),nl,fail.
1897
1898 % check if we have an unbound list_skeleton with optionally just ordering constraints
1899 % check if it is safe to assign H minimal value
1900 % TO DO: also accept if all elements have the same co-routines constraints attached (e.g., because of +-> check)
1901 is_unbound_ordered_list_skeleton(H,T) :-
1902 is_unbound_ordered_list_skeleton3(H,T,[allow_ordered_values]).
1903 is_unbound_list_skeleton(H,T) :-
1904 ? is_unbound_ordered_list_skeleton3(H,T,[]).
1905
1906 is_unbound_ordered_list_skeleton(H,T,Ordered) :-
1907 is_unbound_ordered_list_skeleton3(H,T,List),
1908 % if List gets instantiated it will become [allow_ordered_values|_]
1909 (var(List) -> Ordered=unordered ; Ordered=ordered).
1910
1911 is_unbound_ordered_list_skeleton3(H,T,Options) :-
1912 free_var(H),
1913 (var(T) -> unbound_variable(H),
1914 ? unbound_ordered_tail(T,Options) % or ? unbound_variable_for_cons(T)
1915 ; T = [H2|T2],
1916 unbound_variable_or_ordered(H,'$$',H2,T,Options),
1917 ? is_unbound_ordered_list_skeleton5(H,H2,T2,[H|T],Options)).
1918 is_unbound_ordered_list_skeleton5(Prev,H,T,All,Options) :-
1919 free_var(H),
1920 (var(T) -> unbound_variable_or_ordered(H,Prev,'$$',All,Options),
1921 ? unbound_ordered_tail(T,Options)
1922 ; T==[] -> unbound_variable_or_ordered(H,Prev,'$$',All,Options)
1923 ; T = [H2|T2],
1924 unbound_variable_or_ordered(H,Prev,H2,All,Options),
1925 ? is_unbound_ordered_list_skeleton5(H,H2,T2,All,Options)).
1926
1927 % utility: if is_unbound_ordered_list_skeleton is true, extract for every element in the list one minimal element from CS
1928 remove_minimal_elements(T,CS,Res) :- var(T),!,Res=CS.
1929 remove_minimal_elements([],CS,Res) :- !, empty_set(CS),Res=[].
1930 remove_minimal_elements([_H|T],CS,[Min|Rest]) :-
1931 remove_minimum_element_custom_set(CS,Min,NewCS), % _H will be unified in one go with Min later
1932 remove_minimal_elements(T,NewCS,Rest).
1933
1934 % it is unbound or can be assigned the minimal value of a set
1935 unbound_variable_or_ordered(Var,Prev,Nxt,All,Options) :-
1936 free_var(Var), frozen(Var,Residue),
1937 unbound_ord_residue_aux(Residue,Prev,Var,Nxt,All,Options).
1938 unbound_ord_residue_aux(true,_Prev,_,_Nxt,_All,_Options).
1939 unbound_ord_residue_aux((A,B),Prev,V,Nxt,All,Options) :- !,
1940 unbound_ord_residue_aux(A,Prev,V,Nxt,All,Options),
1941 unbound_ord_residue_aux(B,Prev,V,Nxt,All,Options).
1942 unbound_ord_residue_aux(Module:Call,Prev,V,Nxt,All,Options) :-
1943 unbound_ord_residue_m(Module,Call,Prev,V,Nxt,All,Options).
1944 unbound_ord_residue_m(Module,Residue,_,Var,_,_,_) :- unbound_basic_residue(Module,Residue,Var),!.
1945 unbound_ord_residue_m(bsets_clp,check_index(V2,_),_,V,_,_,_) :- !,
1946 V2==V. % assumes all index elements in the sequence are being checked; this is the case
1947 unbound_ord_residue_m(kernel_objects,ordered_value(A,B),Prev,V,Nxt,_,Options) :- !,
1948 % there is also a bsets_clp version
1949 ((A,B)==(Prev,V) ; (A,B)==(V,Nxt)),
1950 (member(allow_ordered_values,Options) -> true).
1951 unbound_ord_residue_m(kernel_objects,not_equal_object_wf(A,B,_),_,V,_,All,_) :- !,
1952 % check for all diff constraint; e.g., set up by not_element_of_wf(H,SoFar,WF) in cardinality_as_int2;
1953 % anyway: all elements in a list must be different
1954 (A==V -> exact_member_in_skel(B,All) ; B==V, exact_member_in_skel(A,All)).
1955 unbound_ord_residue_m(kernel_objects,not_element_of_wf1(Set,Val,_),_,V,_,All,_) :- !, Val==V,
1956 open_tail(All,Tail), Tail==Set. % ditto, again just stating that Values are distinct in the list
1957 %unbound_ord_residue_m(A,Prev,V,Nxt,All) :-
1958 % print(unbound_ord_residue_aux(A,Prev,V,Nxt,All)),nl,fail.
1959
1960 % get tail of an open list:
1961 open_tail(X,Res) :- var(X),!,Res=X.
1962 open_tail([_|T],Res) :- open_tail(T,Res).
1963 % exact member in a possibly open list:
1964 exact_member_in_skel(X,List) :- nonvar(List), List=[Y|T],
1965 (X==Y -> true ; exact_member_in_skel(X,T)).
1966
1967
1968 unbound_ordered_tail(T,Options) :- free_var(T), frozen(T,Residue),
1969 ? unbound_ordered_tail_aux(Residue,T,Options).
1970 unbound_ordered_tail_aux(true,_,_).
1971 unbound_ordered_tail_aux(kernel_objects:propagate_card(A,B,_Eq),V,_) :-
1972 (V==A ; V==B). % just specifies A and B have same cardinality
1973 unbound_ordered_tail_aux(prolog:dif(X,Y),V,_) :- (V==X,Y==[] ; V==Y,X==[]).
1974 unbound_ordered_tail_aux(dif(X,Y),V,_) :- (V==X,Y==[] ; V==Y,X==[]).
1975 unbound_ordered_tail_aux(kernel_objects:lazy_ordered_value(W,_),T,Options) :-
1976 W==T, %% difference with just_cardinality_constraints
1977 (member(allow_ordered_values,Options)->true).
1978 unbound_ordered_tail_aux(bsets_clp:propagate_empty_set(_,_),_,_).
1979 unbound_ordered_tail_aux(kernel_objects:prop_non_empty(_,W,_),T,_) :- W==T.
1980 unbound_ordered_tail_aux(kernel_objects:cardinality_as_int2(W,_,_,_,_,_),T,_) :- W==T.
1981 unbound_ordered_tail_aux(kernel_objects:cardinality3(W,_,_),Var,_) :- W==Var.
1982 unbound_ordered_tail_aux((A,B),T,Options) :-
1983 ? (unbound_ordered_tail_aux(A,T,Options) -> true ; unbound_ordered_tail_aux(B,T,Options)).
1984 % TODO: call unbound_basic_residue
1985
1986 % co-routine used to mark certain values as to be computed; avoid instantiating them
1987 :- block mark_as_to_be_computed(-).
1988 mark_as_to_be_computed(_).
1989
1990 is_marked_to_be_computed(X) :- var(X),frozen(X,G), %nl,print(check_frozen(X,G)),nl,
1991 marked_aux(G,X).
1992 marked_aux((A,B),V) :- (marked_aux(A,V) -> true ; marked_aux(B,V)).
1993 marked_aux(kernel_objects:mark_as_to_be_computed(M),V) :- V==M.
1994
1995 :- public unbound_variable_check/1.
1996 % currently not used; but can be useful for debugging
1997 unbound_variable_check(V) :- free_var(V), % check no bool_pred attributes
1998 (frozen(V,Goal), Goal\=true
1999 -> nl,print('### WARNING: goal attached to unbound variable expression'),nl,print(V:Goal),nl, %trace,
2000 fail
2001 ; true).
2002
2003 % check if a variable is unbound or only dif(_,[]) attached; we do not need to check for bool_pred attributes as we have a set
2004 unbound_variable_for_cons(Set) :- var(Set),frozen(Set,F),
2005 \+ contains_problematic_coroutine_for_cons(F,Set). % for equal cons we can allow more co-routines than when we want to freely determine a value in enumeration; the head of the list is unbound
2006
2007 % prolog:dif(X,Y) with Y == [] is ok
2008 contains_problematic_coroutine_for_cons(custom_explicit_sets:element_of_avl_set_wf3(Var,_,_,_,_),V) :- V==Var. % occurs in test 1270
2009 contains_problematic_coroutine_for_cons(kernel_objects:non_free(_),_). % has been marked as non-free
2010 contains_problematic_coroutine_for_cons(kernel_objects:mark_as_to_be_computed(_),_). % has been marked to be computed by closure expansion
2011 contains_problematic_coroutine_for_cons((A,B),Var) :-
2012 ? (contains_problematic_coroutine_for_cons(A,Var) -> true
2013 ; contains_problematic_coroutine_for_cons(B,Var)).
2014
2015
2016 unbound_variable_for_card(Set) :- % when do we allow card to instantiate a list skeleton
2017 preference(data_validation_mode,true),
2018 !,
2019 unbound_variable(Set).
2020 unbound_variable_for_card(Set) :- unbound_variable_for_cons(Set).
2021
2022
2023
2024 % handling equal_object for [HR|TR] = [H|T]
2025
2026 equal_cons_cons(HR,TR,H,T,_LWF,WF) :- TR==[],!,
2027 empty_set_wf(T,WF), % was T=[], but T could be an empty closure
2028 ? equal_object_wf(HR,H,equal_cons_cons_1,WF).
2029 equal_cons_cons(HR,TR,H,T,_LWF,WF) :- T==[],!,
2030 ? empty_set_wf(TR,WF), % was TR=[], but TR could be an empty closure
2031 ? equal_object_wf(HR,H,equal_cons_cons_2,WF).
2032 equal_cons_cons(HR,TR,H,T,_LWF,WF) :-
2033 %(is_unbound_list_skeleton(H,T) -> true ; is_unbound_list_skeleton(HR,TR)),
2034 (is_unbound_ordered_list_skeleton(H,T,Ordered)
2035 -> (Ordered = unordered -> true
2036 ; is_unbound_ordered_list_skeleton(HR,TR))
2037 ? ; is_unbound_list_skeleton(HR,TR)),
2038 % if both are ordered: then the first elements must be equal,
2039 % if one or both are not ordered: the unification HR=H is only ok if the other is unbound
2040 % beware of tests 1078 and 1101 when allowing ordered lists
2041 !,
2042 % HR is variable: no constraints/co-routines attached to it; no other element in TR is constrained either
2043 %(HR,TR)=(H,T). %fails, e.g., if TR=[] and T= empty closure !
2044 % at the moment : unbound_check does not allow ordered set skeletons
2045 HR=H, equal_object_wf(TR,T,equal_cons_cons3,WF).
2046 equal_cons_cons(HR,TR,H,T,LWF,WF) :-
2047 % here we use LWF for the first time
2048 %(number(LWF) -> LWF2=LWF ; true),
2049 equality_objects_lwf(HR,H,EqRes,LWF2,WF),
2050 ? equal_cons1(EqRes,HR,TR,H,T,LWF,LWF2,WF).
2051
2052 equal_cons1(EqRes,_HR,TR,_H,T,_LWF,_LWF2,WF) :- EqRes == pred_true,!,
2053 equal_object_wf(TR,T,equal_cons1,WF).
2054 equal_cons1(EqRes,HR,TR,H,T,_LWF,_LWF2,WF) :- var(EqRes),
2055 (definitely_not_in_list(TR,H)
2056 ; definitely_not_in_list(T,HR) % this can induce a quadratic complexity for large list skeletons
2057 ),
2058 !,
2059 EqRes=pred_true, % H cannot appear in TR; it must match HR
2060 ? equal_object_wf(TR,T,equal_cons1,WF).
2061 equal_cons1(EqRes,HR,TR,H,T,LWF,LWF2,WF) :-
2062 ? instantiate_lwf(LWF,LWF2), % instantiate later to ensure var(EqRes) can hold if LWF already bound
2063 %print(eq_cons_cons_lwf2(HR,H,EqRes,LWF2)),nl,
2064 ? equal_cons2(EqRes,HR,TR,H,T,LWF2,WF),
2065 propagate_card(TR,T,EqRes). % prevents tail recursion; move earlier/remove if EqRes nonvar?
2066 %,instantiate_lwf(LWF,LWF2) % we could instantiate LWF2 later here to give propagate_card a chance to figure out value of EqRes first ? this slows down examples/B/Alstom/CompilatonProject/Regles/Rule_DB_Route_0001ori.his
2067
2068
2069 % this will instantiate LWF if it has not yet been computed
2070 % (Idea: get_cardinality_wait_flag can be expensive; only do it if we really need the wait_flag)
2071 instantiate_lwf(LWF,R) :- var(LWF),!,R=LWF.
2072 instantiate_lwf(lwf_card(Set,Info,WF),LWF) :- !, % TO DO: in prob_data_validation_mode: increase or get_last_waitflag
2073 get_cardinality_wait_flag(Set,Info,WF,LWF).
2074 %% get_cardinality_powset_wait_flag(Set,Info,WF,_,LWF).
2075 %instantiate_lwf(lwf_first(X),R) :- !, R=X.
2076 instantiate_lwf(LWF,LWF).
2077
2078 :- block equal_cons2(-,?,?,?,?,?,?).
2079 ?equal_cons2(pred_true,_HR,TR,_H,T,_,WF) :- equal_object_wf(TR,T,equal_cons2,WF).
2080 equal_cons2(pred_false,HR,TR, H,T,LWF,WF) :-
2081 ? equal_cons_lwf(T,HR,TR2,LWF,WF), % look for HR inside T
2082 T2=TR2,
2083 ? equal_cons_lwf(TR,H,T2,LWF,WF). %, was instead of T2=TR2: equal_object(TR2,T2).
2084
2085 :- use_module(kernel_tools,[cannot_match/2]).
2086 % TO DO: investigate whether we should not use kernel_equality or at least a blocking version
2087 definitely_not_in_list(V,_) :- var(V),!,fail.
2088 definitely_not_in_list([],_).
2089 definitely_not_in_list([H|T],X) :- cannot_match(H,X), definitely_not_in_list(T,X).
2090
2091
2092 :- block propagate_card(-,-,-).
2093 propagate_card(X,Y,EqRes) :-
2094 (nonvar(EqRes) -> true % we no longer need to propagate; equal_cons will traverse
2095 ; nonvar(X) -> propagate_card2(X,Y,EqRes)
2096 ; propagate_card2(Y,X,EqRes)).
2097 propagate_card2([],Y,_) :- !,empty_set(Y).
2098 propagate_card2([_|TX],Y,EqRes) :- !,
2099 (var(Y) -> Y= [_|TY], propagate_card(TX,TY,EqRes)
2100 ; Y=[] -> fail
2101 ; Y=[_|TY] -> propagate_card(TX,TY,EqRes)
2102 ; true
2103 ). % TO DO: add more propagation
2104 propagate_card2(_,_,_).
2105
2106 %same_card_and_expand(A,B,ExpA,ExpB) :- .... + reorder ??
2107
2108 :- if(environ(prob_safe_mode,true)).
2109 % CODE FOR CHECKING FOR TYPE ERRORS AT RUNTIME
2110 :- assert_must_succeed(type_error([],int(1))).
2111 :- assert_must_succeed(type_error((int(1),int(2)),[pred_true])).
2112 :- assert_must_succeed(type_error(string('Name'),global_set('Name'))).
2113 :- assert_must_fail((type_error([],[_]))).
2114 type_error([],Y) :- no_set_type_error(Y).
2115 type_error([_|_],Y) :- no_set_type_error(Y).
2116 %type_error(X,Y) :- is_custom_explicit_set(X,type_error1), no_set_type_error(Y).
2117 type_error(avl_set(A),Y) :- illegal_avl_set(A) -> true ; no_set_type_error(Y).
2118 type_error(global_set(_),Y) :- no_set_type_error(Y).
2119 type_error(freetype(_),Y) :- no_set_type_error(Y).
2120 type_error(closure(P,_,B),Y) :-
2121 (var(P) -> true ; var(B) -> true ; P=[] -> true ; P=[P1|_], var(P1) -> true ; no_set_type_error(Y)).
2122 type_error((_,_),Y) :- Y \= (_,_).
2123 type_error(fd(_,T1),Y) :- (Y= fd(_,T2) -> nonvar(T1),nonvar(T2),T1 \=T2 ; true).
2124 type_error(int(_),Y) :- Y\= int(_).
2125 type_error(term(_),Y) :- Y\= term(_).
2126 type_error(rec(FX),Y) :- (Y = rec(FY) -> type_error_fields(FX,FY,'$') ; true).
2127 type_error(freeval(ID,_,_),Y) :- Y \= freeval(ID,_,_).
2128 type_error(string(_),Y) :- Y \= string(_).
2129 % Should raise type error: kernel_objects:union([int(1)],[[]],R).
2130
2131 type_error_fields(X,Y,_) :- (var(X);var(Y)),!,fail.
2132 type_error_fields([],[_|_],_).
2133 type_error_fields([_|_],[],_).
2134 type_error_fields([F1|T1],[F2|T2],PrevField) :-
2135 nonvar(F1),nonvar(F2),F1=field(Name1,_),F2=field(Name2,_),
2136 nonvar(Name1),
2137 (Name1 @=< PrevField -> true % not sorted
2138 ; Name1 \= Name2 -> true % other record has different field
2139 ; type_error_fields(T1,T2,Name1)).
2140
2141 illegal_value(X) :- var(X),!,fail.
2142 illegal_value(avl_set(A)) :- illegal_avl_set(A).
2143 illegal_value([H|T]) :- illegal_value(H) -> true ; illegal_value(T).
2144 illegal_value(global_set(G)) :- \+ ground(G).
2145 illegal_value(N) :- number(N).
2146 illegal_value((A,B)) :- illegal_value(A) -> true ; illegal_value(B).
2147 % TO DO: complete this
2148
2149 illegal_avl_set(X) :- var(X),!.
2150 illegal_avl_set(empty).
2151 illegal_avl_set(X) :- (X=node(_,_,_,_,_) -> \+ ground(X) ; true).
2152
2153 no_set_type_error(int(_)).
2154 no_set_type_error(fd(_,_)).
2155 no_set_type_error((_,_)).
2156 no_set_type_error(rec(_)).
2157 no_set_type_error(pred_true /* bool_true */).
2158 no_set_type_error(pred_false /* bool_false */).
2159 no_set_type_error(term(_)).
2160 no_set_type_error(string(_)).
2161 no_set_type_error(freeval(_,_,_)).
2162 no_set_type_error(avl_set(A)) :- illegal_avl_set(A).
2163 %% END OF CHECKING CODE
2164 :- endif.
2165
2166
2167 :- assert_must_succeed(not_equal_object(term(a),term(b))).
2168 :- assert_must_succeed(not_equal_object(string('a'),string('b'))).
2169 :- assert_must_succeed(not_equal_object(int(1),int(2))).
2170 :- assert_must_succeed(not_equal_object(rec([field(a,int(1))]),rec([field(a,int(2))]))).
2171 :- assert_must_succeed(not_equal_object(rec([field(a,int(1)),field(b,int(2))]),
2172 rec([field(a,int(1)),field(b,int(3))]))).
2173 :- assert_must_fail(not_equal_object(rec([field(a,int(1))]),rec([field(a,int(1))]))).
2174 :- assert_must_fail(not_equal_object(rec([field(a,int(1)),field(b,int(2))]),
2175 rec([field(a,int(1)),field(b,int(2))]))).
2176 :- assert_must_fail(not_equal_object(term(msg),int(2))).
2177 :- assert_must_fail(not_equal_object(fd(1,a),term(msg))).
2178 :- assert_must_succeed(not_equal_object(global_set(a),global_set(b))).
2179 :- assert_must_succeed(not_equal_object([term(a),term(b)],[term(a),term(c)])).
2180 :- assert_must_succeed((not_equal_object([(int(1),[Y])],[(int(X),[Z])]),
2181 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[int(2)])).
2182 :- assert_must_succeed(not_equal_object((int(1),int(2)),(int(3),int(4)))).
2183 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_equal_object((int(1),int(2)),(int(1),int(4))))).
2184 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_equal_object((int(1),int(4)),(int(3),int(4))))).
2185 :- assert_must_fail(not_equal_object((int(1),int(4)),(int(1),int(4)))).
2186 :- assert_must_succeed(not_equal_object((int(1),string('a')),(int(1),string('b')))).
2187 :- assert_must_fail(not_equal_object((int(1),string('b')),(int(1),string('b')))).
2188 :- assert_must_fail(not_equal_object([(term(a),[])],[(term(a),[])])).
2189 :- assert_must_fail((not_equal_object([(int(1),[Y])],[(int(X),[Z])]),
2190 Y=(term(a),Y2), X=1, Z=(term(a),[]), Y2=[])).
2191 :- assert_must_fail(not_equal_object([int(1),int(2)],[int(2),int(1)])).
2192 :- assert_must_succeed(not_equal_object(term(msg),term(another_msg))).
2193 :- assert_must_succeed(not_equal_object([int(1),int(2)],[int(0),int(4)])).
2194 :- assert_must_fail((sample_closure(C),
2195 not_equal_object(C,[int(1),int(2)]))).
2196 :- assert_must_succeed((sample_closure(C),
2197 not_equal_object(C,[int(1),int(0)]))).
2198 :- assert_must_succeed((sample_closure(C),
2199 not_equal_object(C,global_set('NAT')))).
2200 :- assert_must_fail((not_equal_object(
2201 [[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
2202 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(3,'Name'),fd(2,'Name')]]
2203 ,[[],[fd(1,'Name')],[fd(1,'Name'),fd(2,'Name')],
2204 [fd(1,'Name'),fd(2,'Name'),fd(3,'Name')],[fd(2,'Name')],[fd(2,'Name'),fd(3,'Name')]])
2205 )).
2206 :- assert_must_fail((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,a,int(2))))).
2207 :- assert_must_succeed((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,a,int(3))))).
2208 :- assert_must_succeed((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,b,int(2))))).
2209 :- assert_must_succeed((not_equal_object(freeval(selfcx,a,int(2)),freeval(selfcx,a,int(3))))).
2210
2211 :- assert_must_succeed((not_equal_object(pred_true /* bool_true */,X), X==pred_false /* bool_false */)).
2212 :- assert_must_succeed((not_equal_object([],X),X=[_|_])).
2213 %:- assert_must_succeed((not_equal_object([],X), nonvar(X),X=[_|_])).
2214 :- assert_must_succeed((not_equal_object(X,[]), X=[_|_])).
2215 :- assert_must_succeed((not_equal_object(X,pred_false /* bool_false */), X==pred_true /* bool_true */)).
2216
2217 :- assert_must_succeed(not_equal_object([_X],[int(1),int(3)])). % Inefficiency example of setlog
2218 :- assert_must_succeed_any(not_equal_object([_X],[int(1)])). % Inefficiency example of setlog
2219 :- assert_must_succeed((not_equal_object([X],[pred_true /* bool_true */]),X==pred_false /* bool_false */)).
2220 :- assert_must_succeed((not_equal_object([pred_true /* bool_true */],[X]),X==pred_false /* bool_false */)).
2221 :- assert_must_succeed((not_equal_object([[X]],[[pred_true /* bool_true */]]),X==pred_false /* bool_false */)).
2222 :- assert_must_succeed((not_equal_object([[pred_true /* bool_true */]],[[X]]),X==pred_false /* bool_false */)).
2223 :- assert_must_succeed((custom_explicit_sets:construct_one_element_custom_set(pred_true /* bool_true */, A), kernel_objects:not_equal_object(A,[X]), X==pred_false /* bool_false */)).
2224 :- assert_must_succeed((custom_explicit_sets:construct_one_element_custom_set(pred_true /* bool_true */,A), kernel_objects:not_equal_object([X],A), X==pred_false /* bool_false */)).
2225 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([],[int(3333)]))).
2226 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([],[int(2),int(1),int(3)]))).
2227 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([int(3)],[int(2),int(1),int(3)]))).
2228 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([int(3),int(1),int(4)],[int(2),int(1),int(3)]))).
2229 :- assert_must_succeed(exhaustive_kernel_check([commutative],not_equal_object([int(2),int(1),int(3),int(5)],[int(2),int(1),int(3)]))).
2230 % X in 3..4, kernel_objects:not_equal_object([int(2),int(3)],[int(2),int(X)]), X==4. in clpfd Mode
2231
2232
2233 not_equal_object_wf(X,Y,WF) :-
2234 (var(X)
2235 -> (var(Y)
2236 -> X \== Y,
2237 when((nonvar(X);nonvar(Y);?=(X,Y)), not_equal_object_wf0(X,Y,WF))
2238 ? ; not_equal_object_wf1(Y,X,WF) % invert arguments
2239 )
2240 ? ; not_equal_object_wf1(X,Y,WF)).
2241
2242 %:- block not_equal_object_wf0(-,-,?).
2243 /* TO DO: implement a better _wf version ; use bool_dif if possible */
2244 % block is relevant for tests 1374, 1737
2245 not_equal_object_wf0(X,Y,WF) :-
2246 %(X==Y -> print(not_eq_pruned(X,Y)),nl,fail ; true),
2247 %X\==Y, % could be expensive if X,Y assigned to large term simultaneously (just woken up by when)
2248 ? (var(X) -> X\==Y, not_equal_object_wf1(Y,X,WF)
2249 ? ; not_equal_object_wf1(X,Y,WF)).
2250
2251 ?not_equal_object_wf1([],R,WF) :- !, not_empty_set_wf(R,WF).
2252 not_equal_object_wf1(R,E,WF) :- E==[],!, not_empty_set_wf(R,WF).
2253 ?not_equal_object_wf1(X,Y,WF) :- not_equal_object2_wf(X,Y,WF).
2254
2255 not_equal_object(X,Y) :-
2256 ( nonvar(X) -> not_equal_object2_wf(X,Y,no_wf_available)
2257 ; nonvar(Y) -> not_equal_object2_wf(Y,X,no_wf_available)
2258 ; X\==Y, when((?=(X,Y);nonvar(X);nonvar(Y)), not_equal_object0(X,Y))).
2259
2260 not_equal_object0(X,Y) :- X\==Y,(var(X) -> not_equal_object2_wf(Y,X,no_wf_available)
2261 ; not_equal_object2_wf(X,Y,no_wf_available)).
2262
2263 %not_equal_object2_wf(X,Y,_) :- print(not_equal_object2_wf(X,Y)),nl,fail.
2264 not_equal_object2_wf(pred_true /* bool_true */,R,_) :- !, R=pred_false /* bool_false */.
2265 not_equal_object2_wf(pred_false /* bool_false */,R,_) :- !, R=pred_true /* bool_true */.
2266 ?not_equal_object2_wf(fd(X,Type),R,_) :- !, get_global_type_value(R,Type,Y), % also sets up FD range for Y if R was var
2267 ? neq_fd(X,Y,Type).
2268 ?not_equal_object2_wf(int(X),R,_WF) :- !, R=int(Y), integer_dif(X,Y).
2269 not_equal_object2_wf(string(X),R,_) :- !, R=string(Y), dif(X,Y).
2270 not_equal_object2_wf(term(X),R,WF) :- !, R=term(Y), not_equal_term_wf(X,Y,WF).
2271 not_equal_object2_wf(rec(F1),R,WF) :- !, R=rec(F2),
2272 not_equal_fields_wf(F1,F2,WF).
2273 not_equal_object2_wf([],X,WF) :- !, not_empty_set_wf(X,WF).
2274 not_equal_object2_wf((X1,X2),R,WF) :- !, R=(Y1,Y2),
2275 ? not_equal_couple_wf(X1,Y1,X2,Y2,WF).
2276 not_equal_object2_wf(X,Y,WF) :- is_custom_explicit_set(X,not_equal_object2),!,
2277 ? not_equal_explicit_set_wf(X,Y,WF).
2278 ?not_equal_object2_wf(X,Y,WF) :- not_equal_object3(X,Y,WF).
2279
2280 :- block not_equal_term_wf(-,-,?).
2281 not_equal_term_wf(X,Y,_WF) :- % triggered e.g. in test 1225 or 1227 for nil (freetypes)
2282 dif(X,Y).
2283 % TO DO: should we treat floating/1 in a special way?
2284
2285 :- block not_equal_explicit_set_wf(?,-,?).
2286 not_equal_explicit_set_wf(X,Y,WF) :-
2287 is_custom_explicit_set_nonvar(Y),!,
2288 not_equal_explicit_sets_wf(X,Y,WF).
2289 not_equal_explicit_set_wf(X,[],WF) :- !,
2290 is_non_empty_explicit_set_wf(X,WF).
2291 not_equal_explicit_set_wf(CS,[H|T],WF) :-
2292 ? is_simple_infinite_set(CS), % global_set(.) or open interval
2293 !, % TODO: maybe also detect other infinite sets
2294 test_finite_set_wf(T,Finite,WF),
2295 when(nonvar(Finite),(Finite=pred_true -> true % infinite set cannot be equal finite one
2296 ; not_equal_explicit_set_expand(CS,[H|T],WF))).
2297 not_equal_explicit_set_wf(X,Y,WF) :-
2298 ? not_equal_explicit_set_expand(X,Y,WF).
2299
2300 not_equal_explicit_set_expand(X,Y,WF) :-
2301 expand_custom_set_wf(X,EX,not_equal_explicit_set_wf,WF),
2302 ? not_equal_object3_block(EX,Y,WF).
2303
2304 :- block not_equal_object3_block(-,?,?).
2305 ?not_equal_object3_block(EX,Y,WF) :- not_equal_object3(EX,Y,WF).
2306
2307 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
2308 :- block not_equal_object3(?,-,?).
2309 :- if(environ(prob_safe_mode,true)).
2310 not_equal_object3(X,Y,_) :- nonvar(X),type_error(X,Y),
2311 add_internal_error('Internal Typing Error (please report as bug !) : ',not_equal_object(X,Y)),
2312 fail.
2313 :- endif.
2314 not_equal_object3(X,Y,WF) :- is_custom_explicit_set(Y,not_equal_object2),!,
2315 not_equal_explicit_set_wf(Y,X,WF). % TODO: will uselessly check for X being custom_set or []
2316 not_equal_object3(freeval(ID,Case1,Value1),freeval(ID,Case2,Value2),WF) :-
2317 (freetype_with_single_case(ID,Case) -> (Case,Case)=(Case1,Case2) ; true),
2318 when(?=(Case1,Case2), % we first have to be able to decide the case; if cases are different types of values may be different
2319 not_equal_freeval_wf(Case1,Value1,Case2,Value2,WF)).
2320 not_equal_object3([],X,WF) :- not_empty_set_wf(X,WF).
2321 not_equal_object3([H|T],Set2,WF) :-
2322 (Set2==[] -> true % note second argument is nonvar
2323 ; cardinality_peano_wf([H|T],N1,no_wf_available),
2324 cardinality_peano_wf(Set2,N2,no_wf_available), % TODO(?): pending co-routines if Set2 infinite
2325 ? when(?=(N1,N2), % when we trigger code below, = can be decided:
2326 (N1=N2 -> neq_cons_wf(Set2,H,T,WF) ; true))).
2327 % (dif(N1,N2) ; (N1=N2, neq_cons_wf(Set2,H,T,WF)))). %not_equal_object_sets(Set1,Set2) )) ).
2328
2329 not_equal_freeval_wf(Case1,Value1,Case2,Value2,WF) :-
2330 (Case1=Case2 -> not_equal_object_wf(Value1,Value2,WF) ; true).
2331
2332 :- block not_equal_object_sets_wf(-,?,?), not_equal_object_sets_wf(?,-,?).
2333 not_equal_object_sets_wf([H|T],Set2,WF) :- !,
2334 ( Set2=[H2|_T2]
2335 ? -> not_equal_object_sets2(H,T,H2,Set2,WF)
2336 ; Set2=[] -> true
2337 ; not_equal_object2_wf(Set2,[H|T],WF) % avl_set probably
2338 ).
2339 not_equal_object_sets_wf(Set1,Set2,WF) :- % Note : if Set1 =[] then we can fail, as both sets have same length
2340 % we could have empty set or avl_set can sometimes creep into end of lists
2341 not_equal_object2_wf(Set1,Set2,WF).
2342
2343 :- block not_equal_object_sets2(-,?,?,?,?), not_equal_object_sets2(?,?,-,?,?).
2344 not_equal_object_sets2(H,_T,_H2,Set2,WF) :-
2345 % TO DO: should we not use kernel_equality:membership_test_wf here ??
2346 not_element_of_wf(H,Set2,WF).
2347 not_equal_object_sets2(H,T,_H2,Set2,WF) :-
2348 ? remove_element_wf(H,Set2,Del2,WF), % used to be remove_element(X,Set,Res) :- equal_cons(Set,X,Res).
2349 ? not_equal_object_wf(T,Del2,WF).
2350
2351
2352 :- block neq_cons_wf(-,?,?,?).
2353 neq_cons_wf([],_,_,_) :- !.
2354 neq_cons_wf([H2|T2],H1,T1,WF) :- !,
2355 (T2==[],T1==[]
2356 -> not_equal_object_wf(H1,H2,WF)
2357 ; check_and_remove([H2|T2],H1,NewSet2,RemoveSuccesful),
2358 ? neq_cons2(RemoveSuccesful,T1,NewSet2,WF)
2359 ).
2360 neq_cons_wf(avl_set(A),H1,T1,WF) :- element_can_be_added_or_removed_to_avl(H1),!,
2361 (remove_element_from_explicit_set(avl_set(A),H1,RA)
2362 -> not_equal_object_wf(T1,RA,WF)
2363 ; true ).
2364 neq_cons_wf(ES,H1,T1,WF) :- is_custom_explicit_set(ES,neq_cons),
2365 expand_custom_set_wf(ES,ExpSet,neq_cons_wf,WF),
2366 neq_cons_wf(ExpSet,H1,T1,WF).
2367
2368 :- block neq_cons2(-,?,?,?).
2369 neq_cons2(not_successful,_T1,_NewSet2,_WF). % one element could not be removed: the sets are different
2370 ?neq_cons2(successful,T1,NewSet2,WF) :- not_equal_object_sets_wf(T1,NewSet2,WF).
2371
2372 % kernel_objects:not_equal_couple(int(1),int(Y),B,pred_true).
2373 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(1),int(Y),B,pred_true,no_wf_available),Y=1, B==pred_false)).
2374 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),B,pred_true,no_wf_available),Y=1, B==pred_false)).
2375 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),B,pred_false,no_wf_available),Y=1, B==pred_true)).
2376 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),pred_false,B,no_wf_available),Y=1, B==pred_true)).
2377 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(Y),int(1),B,pred_true,no_wf_available),Y=2, var(B))).
2378 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(B,pred_true,int(Y),int(1),no_wf_available),Y=1, B==pred_false)).
2379 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(B,fd(C,'Code'),fd(Y,'Name'),F,no_wf_available),F=fd(1,'Name'),Y=1,B=fd(1,'Code'),C=2 )).
2380 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(B,pred_true,fd(Y,'Name'),F,no_wf_available),F=fd(1,'Name'),Y=1, B==pred_false)).
2381
2382 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(int(2500),int(50),_,_,no_wf_available))).
2383 :- assert_must_succeed(( kernel_objects:not_equal_couple_wf(_,_,int(2500),int(50),no_wf_available))).
2384
2385
2386 %was too lax (but works): :- block not_equal_couple_wf(-,?,-,?,?),not_equal_couple_wf(?,-,?,-,?).
2387 % but not sure if this new declaration below is worth it, also since X1==Y1 or X2==Y2 is possible
2388 :- block not_equal_couple_wf(-,?,-,?,?), % X1 or X2 must be known
2389 not_equal_couple_wf(?,-,?,-,?), % Y1 or Y2 must be known
2390 not_equal_couple_wf(?,-,-,?,?), % X2 or Y1 must be known
2391 not_equal_couple_wf(-,?,?,-,?). % X1 or Y2 must be known
2392 % (X1,X2) /= (Y1,Y2)
2393
2394 % using CLPFD results in less propagation it seems
2395 % e.g. post_constraint((A1 #\= A2 #\/ B1 #\= B2), dif((A1,B1),(A2,B2))) will not propagate if A1=A2 or B1=B2
2396 % we could do something like
2397 % post_constraint((N*A1 + B1 #\= N*A2 + B2), dif((A1,B1),(A2,B2))). ; but we need to know good value for N
2398 % TO DO: pass typing information when available ?? or not needed because type info extracted ?
2399
2400 not_equal_couple_wf(X1,Y1,X2,Y2,WF) :- var(X1), var(Y1),!,
2401 (X1==Y1 -> not_equal_object_wf(X2,Y2,WF)
2402 ; not_equal_couple_wf_aux(X2,Y2,X1,Y1,WF)). % change order to test
2403 not_equal_couple_wf(X1,Y1,X2,Y2,WF) :-
2404 ? not_equal_couple_wf_aux(X1,Y1,X2,Y2,WF).
2405
2406 not_equal_couple_wf_aux(X1,Y1,X2,Y2,WF) :-
2407 ? equality_objects_wf(X1,Y1,EqRes1,WF),
2408 (var(EqRes1)
2409 -> equality_objects_wf(X2,Y2,EqRes2,WF),
2410 ? not_equal_couple4(EqRes1,X1,Y1,EqRes2,X2,Y2)
2411 ? ; EqRes1=pred_true -> not_equal_object_wf(X2,Y2,WF)
2412 ; true).
2413
2414 :- block not_equal_couple4(-,?,?,-,?,?).
2415 not_equal_couple4(EqRes1,X1,Y1,EqRes2,X2,Y2) :-
2416 (var(EqRes1)
2417 ? -> not_equal_couple5(EqRes2,X1,Y1,EqRes1)
2418 ? ; not_equal_couple5(EqRes1,X2,Y2,EqRes2)).
2419
2420 not_equal_couple5(pred_true,_X2,_Y2,EqResOther) :- EqResOther=pred_false.
2421 not_equal_couple5(pred_false,_,_,_).
2422
2423
2424 /* To do: provide special support for things like
2425 couple of fd's [done], list of fd's, set of fd's */
2426
2427 :- use_module(kernel_records,[check_field_name_compatibility/3]).
2428 :- block not_equal_fields_wf(-,-,?).
2429 not_equal_fields_wf([field(ID1,V1)|T1],[field(ID2,V2)|T2],WF) :-
2430 % should we wait for ID1 or ID2 to become nonvar?
2431 check_field_name_compatibility(ID1,ID2,not_equal_fields_wf),
2432 (T1==[]
2433 -> T2=[], not_equal_object_wf(V1,V2,WF)
2434 ; not_equal_couple_wf(V1,V2,rec(T1),rec(T2),WF) % would be slightly more efficient to have a custom version of not_equal_couple
2435 ).
2436
2437
2438 /* ------------------------------------------- */
2439 /* equality_objects/3 function */
2440 /* ------------------------------------------- */
2441
2442 %% :- ensure_loaded(kernel_equality).
2443
2444 % ----------------------------------------------------------
2445 % ----------------------------------------------------------
2446
2447
2448
2449 :- use_module(kernel_equality).
2450
2451 % ----------------------------------------------------------
2452 % ----------------------------------------------------------
2453
2454 /* ---------------> */
2455 /* This should probably be more systematically applied before every kernel call
2456 + expanded for other symbolic representations !! */
2457
2458
2459
2460 /* underlying assumption: if G is a global set: we get back the
2461 global_set tag immediately: no need to use when to wait;
2462 better: ensure that b_compute_expression always returns a nonvar term */
2463
2464 integer_global_set('NAT').
2465 integer_global_set('NATURAL').
2466 integer_global_set('NAT1').
2467 integer_global_set('NATURAL1').
2468 integer_global_set('INT').
2469 integer_global_set('INTEGER').
2470
2471 string_global_set('STRING'). % TODO : check what happens when we have STRING in Event-B as a set
2472 real_global_set('REAL'). % TODO: ditto
2473 real_global_set('FLOAT'). % TODO: ditto
2474
2475
2476 :- assert_must_succeed(( kernel_objects:element_of_global_set(int(0),'NATURAL'))).
2477 :- assert_must_fail(( kernel_objects:element_of_global_set(int(0),'NATURAL1'))).
2478 :- assert_must_fail(( kernel_objects:element_of_global_set(int(-1),'NATURAL'))).
2479 :- assert_must_succeed(( kernel_objects:element_of_global_set(int(-1),'INTEGER'))).
2480 :- assert_must_succeed(( kernel_objects:element_of_global_set(int(0),'NAT'))).
2481 :- assert_must_fail(( kernel_objects:element_of_global_set(int(0),'NAT1'))).
2482 :- assert_must_succeed(( kernel_objects:element_of_global_set(X,'NAT'),X=int(1))).
2483 :- assert_must_succeed(( kernel_objects:element_of_global_set(X,'NATURAL'),X=int(1))).
2484
2485 element_of_global_set(X,GS) :-
2486 init_wait_flags(WF),element_of_global_set_wf(X,GS,WF),ground_wait_flags(WF).
2487
2488 ?element_of_global_set_wf(El,Set,WF) :- element_of_global_set_wf(El,Set,WF,unknown).
2489
2490 :- use_module(kernel_reals,[is_real/1, is_float_wf/2, is_not_float/1]).
2491 :- block element_of_global_set_wf(?,-,?,?).
2492 ?element_of_global_set_wf(El,Set,WF,_) :- b_global_set(Set),!,
2493 global_type_wf(El,Set,WF).
2494 element_of_global_set_wf(X,'STRING',_WF,_) :- !, X=string(_).
2495 element_of_global_set_wf(X,'REAL',_WF,_) :- !, is_real(X).
2496 element_of_global_set_wf(X,'FLOAT',WF,_) :- !, is_float_wf(X,WF).
2497 element_of_global_set_wf(int(X),GS,WF,Span) :-
2498 ? element_of_global_integer_set_wf(GS,X,WF,Span).
2499
2500 /* what about BOOL ?? */
2501 element_of_global_integer_set_wf('NAT',X,WF,_) :-
2502 preferences:get_preference(maxint,MAXINT),
2503 in_nat_range_wf(int(X),int(0),int(MAXINT),WF).
2504 element_of_global_integer_set_wf('NATURAL',X,WF,Span) :-
2505 (ground(X) -> X>=0
2506 ; is_natural(int(X),WF),
2507 %get_last_wait_flag(element_of_global_set(int(X),'NATURAL'),WF,LWF),
2508 get_integer_enumeration_wait_flag(X,'NATURAL',WF,LWF),
2509 enumerate_natural(X,0,LWF,Span,WF)
2510 ).
2511 element_of_global_integer_set_wf('NAT1',X,WF,_) :-
2512 preferences:get_preference(maxint,MAXINT),
2513 in_nat_range_wf(int(X),int(1),int(MAXINT),WF).
2514 element_of_global_integer_set_wf('NATURAL1',X,WF,Span) :-
2515 (ground(X) -> X>=1
2516 ; is_natural1(int(X),WF),
2517 %get_last_wait_flag(element_of_global_set_wf(int(X),'NATURAL1'),WF,LWF),
2518 get_integer_enumeration_wait_flag(X,'NATURAL1',WF,LWF),
2519 enumerate_natural(X,1,LWF,Span,WF)
2520 ).
2521 element_of_global_integer_set_wf('INT',X,WF,_) :-
2522 preferences:get_preference(minint,MININT),
2523 preferences:get_preference(maxint,MAXINT),
2524 in_nat_range_wf(int(X),int(MININT),int(MAXINT),WF).
2525 element_of_global_integer_set_wf('INTEGER',X,WF,Span) :-
2526 (ground(X) -> true
2527 ; get_integer_enumeration_wait_flag(X,'INTEGER',WF,LWF),
2528 enumerate_int_wf(X,LWF,'INTEGER',WF,Span)
2529 ).
2530
2531
2532 get_integer_enumeration_wait_flag(X,SET,WF,LWF) :-
2533 clpfd_domain(X,FDLow,FDUp), finite_domain(FDLow,FDUp),!,
2534 Size is 1+FDUp-FDLow,
2535 get_wait_flag(Size,element_of_global_set_wf(int(X),SET),WF,LWF).
2536 get_integer_enumeration_wait_flag(X,SET,WF,LWF) :-
2537 get_integer_enumeration_wait_flag(element_of_global_set_wf(int(X),SET),WF,LWF).
2538 % important for e.g., solving r = /*@symbolic*/ {u|#x.(x : NATURAL & u : {x |-> x * x,x |-> x + x})} & 10|->20 : r
2539 % see test 1933, the code was: get_enumeration_starting_wait_flag(element_of_global_set_wf(int(X),SET),WF,LWF), which is a lower number
2540
2541 :- assert_must_succeed((kernel_objects:enumerate_int_wf(X,4,self_check,no_wf_available,unknown),X==2)).
2542 :- block enumerate_int_wf(-,-,?,?,?).
2543 enumerate_int_wf(X,_LWF,Source,WF,Span) :-
2544 (ground(X) -> true
2545 ; add_call_stack_to_span(Span,WF,Span2), % TODO: necessary?
2546 ? enumerate_int_with_span(X,trigger_true(Source),Span2,WF)).
2547
2548 :- assert_must_succeed(not_element_of_global_set(int(-1),'NAT')).
2549 :- assert_must_succeed(not_element_of_global_set(int(-1),'NATURAL')).
2550 :- assert_must_succeed(not_element_of_global_set(int(0),'NAT1')).
2551 :- assert_must_succeed(not_element_of_global_set(int(0),'NATURAL1')).
2552 not_element_of_global_set(_,GS) :- is_maximal_global_set(GS),!, fail. % covers REAL, STRING, INTEGER
2553 not_element_of_global_set(X,'FLOAT') :- !, is_not_float(X).
2554 not_element_of_global_set(int(X),GS) :-
2555 (var(GS) -> add_error(kernel_objects,var_not_element_of_global_set,(int(X),GS)) ; true),
2556 not_element_of_global_set2(GS,X).
2557 not_element_of_global_set2('NAT',X) :-
2558 preferences:get_preference(maxint,MAXINT),
2559 clpfd_not_in_non_empty_range(X,0,MAXINT). %when(nonvar(X), (X<0 ; X>MAXINT)).
2560 not_element_of_global_set2('NATURAL',X) :- is_not_natural(int(X)).
2561 not_element_of_global_set2('NAT1',X) :-
2562 preferences:get_preference(maxint,MAXINT),
2563 clpfd_not_in_non_empty_range(X,1,MAXINT). %when(nonvar(X),(X<1 ; X>MAXINT)).
2564 not_element_of_global_set2('NATURAL1',X) :- is_not_natural1(int(X)).
2565 not_element_of_global_set2('INT',X) :-
2566 preferences:get_preference(minint,MININT),
2567 preferences:get_preference(maxint,MAXINT),
2568 clpfd_not_in_non_empty_range(X,MININT,MAXINT). %when(nonvar(X), (X < MININT ; X > MAXINT)).
2569 %not_element_of_global_set(string(_X),'STRING') :- fail.
2570 %not_element_of_global_set(int(_X),'INTEGER') :- fail.
2571 %not_element_of_global_set(_El,Set) :- b_global_set(Set), fail.
2572
2573
2574
2575 /* ---- */
2576 /* SETS */
2577 /* ---- */
2578
2579 %:- block is_a_set(-).
2580 %is_a_set(X) :- is_a_set2(X).
2581 %is_a_set2([]) :- !.
2582 %is_a_set2([_|_]) :- !.
2583 %is_a_set2(X) :- is_custom_explicit_set(X,is_a_set2).
2584
2585
2586
2587
2588 :- assert_must_succeed(exhaustive_kernel_fail_check(empty_set([int(4),int(3)]))).
2589 :- assert_must_fail((empty_set([int(2),int(1)]))).
2590 :- assert_must_fail((empty_set([int(1)]))).
2591 :- assert_must_fail((empty_set([[]]))).
2592 :- assert_must_fail((empty_set(global_set('Name')))).
2593 :- assert_must_fail((empty_set(X),X=[int(1)])).
2594 :- assert_must_succeed((empty_set([]))).
2595 empty_set(X) :- (var(X) -> X=[]
2596 ; X=[] -> true
2597 % ; X=[_|_] -> fail
2598 ; is_custom_explicit_set_nonvar(X),is_empty_explicit_set(X)).
2599 empty_set_wf(X,WF) :- (var(X) -> X=[]
2600 ; X=[] -> true
2601 % ; X=[_|_] -> fail
2602 ; is_custom_explicit_set_nonvar(X),is_empty_explicit_set_wf(X,WF)).
2603
2604
2605 :- assert_must_succeed(exhaustive_kernel_check(not_empty_set([int(4),int(3)]))).
2606 :- assert_must_succeed((kernel_objects:not_empty_set([int(2),int(1)]))).
2607 :- assert_must_succeed((kernel_objects:not_empty_set([int(1)]))).
2608 :- assert_must_succeed((kernel_objects:not_empty_set([[]]))).
2609 :- assert_must_succeed((kernel_objects:not_empty_set(global_set('Name')))).
2610 :- assert_must_succeed((kernel_objects:not_empty_set_lwf(X,1),nonvar(X),X=[_|_])).
2611 :- assert_must_succeed((kernel_objects:not_empty_set_lwf([int(1)],_))).
2612 :- assert_must_fail((kernel_objects:not_empty_set([]))).
2613
2614 :- use_module(kernel_non_empty_attr,[mark_var_set_as_non_empty/1]).
2615
2616 not_empty_set_wf(S,WF) :- WF==no_wf_available,!, not_empty_set2(S,WF).
2617 not_empty_set_wf(S,WF) :- var(S), !,
2618 (preferences:preference(use_smt_mode,true) -> S=[_|_]
2619 % ; WF=no_wf_available -> not_empty_set(S)
2620 ; get_large_finite_wait_flag(not_empty_set_wf,WF,LWF),
2621 % print(not_empty(S)),nl, % TO DO: set kernel_cardinality attribute if variable
2622 mark_var_set_as_non_empty(S),
2623 not_empty_set_lwf(S,LWF)).
2624 not_empty_set_wf(closure(P,T,B),WF) :- !, is_non_empty_explicit_set_wf(closure(P,T,B),WF).
2625 not_empty_set_wf(S,WF) :- not_empty_set2(S,WF).
2626
2627 :- block not_empty_set_lwf(-,-).
2628 % the instantiation with a list skeleton can easily cause multiple solutions for the same
2629 % set to be found: hence we guard it by a wait flag
2630 not_empty_set_lwf(S,_LWF) :- var(S),!,
2631 S=[_|_].
2632 not_empty_set_lwf(S,_) :- not_empty_set(S).
2633
2634 not_empty_set(Set) :- not_empty_set2(Set,no_wf_available).
2635
2636 :- use_module(error_manager,[add_warning/2]).
2637 :- block not_empty_set2(-,?).
2638 %not_empty_set(S) :- var(S),!,S=[_|_].
2639 % not_empty_set(X) :- not_equal_object([],X).
2640 not_empty_set2([_|_],_).
2641 not_empty_set2(avl_set(A),_) :- (A==empty -> add_warning(not_empty_set,'Empty avl_set'),fail ; true).
2642 not_empty_set2(closure(P,T,B),WF) :- is_non_empty_explicit_set_wf(closure(P,T,B),WF). % TO DO: also use WF
2643 not_empty_set2(global_set(Type),_) :- b_non_empty_global_set(Type).
2644 not_empty_set2(freetype(ID),_) :- kernel_freetypes:is_non_empty_freetype(ID).
2645
2646 % there also exists: eq_empty_set , a reified version, i.e., test_empty_set
2647
2648
2649 :- assert_must_succeed((exact_element_of(int(1),[int(2),int(1)]))).
2650 :- assert_must_succeed((exact_element_of(int(1),[int(2),int(3),int(4),int(1)]))).
2651 :- assert_must_succeed((exact_element_of(int(4),[int(2),int(3),int(4),int(1)]))).
2652 :- assert_must_succeed((exact_element_of(int(1),[int(2),int(3)|T]), T=[int(4),int(1)])).
2653 :- assert_must_fail((exact_element_of(int(5),[int(2),int(3)|T]), T=[int(4),int(1)])).
2654 :- assert_must_succeed((exact_element_of(fd(1,'Name'),global_set('Name')))).
2655 :- assert_must_succeed((exact_element_of([int(2),int(1)],[[],[int(2),int(1)]]))).
2656 :- assert_must_fail((exact_element_of([int(1),int(2)],[[],[int(2),int(1)]]))).
2657 %:- assert_must_succeed((exact_element_of([(int(1),fd(2,'Name'))],
2658 % closure([zzzz],[set(couple(integer,global('Name')))], 'In'('ListExpression'(['Identifier'(zzzz)]),
2659 % 'Seq'(value([fd(1,'Name'),fd(2,'Name')]))))) )).
2660 %:- assert_must_succeed((exact_element_of(XX,
2661 % closure([zzzz],[set(couple(integer,global('Name')))], 'In'('ListExpression'(['Identifier'(zzzz)]),
2662 % 'Seq'(value([fd(1,'Name'),fd(2,'Name')]))))),
2663 % equal_object(XX,[(int(1),fd(1,'Name'))]) )).
2664 %:- assert_must_succeed((
2665 %exact_element_of(XX,closure([zzzz],[set(couple(integer,global('Name')))],
2666 % 'In'('ListExpression'(['Identifier'(zzzz)]),
2667 % 'Perm'(value([fd(1,'Name'),fd(2,'Name')]))))),
2668 % equal_object(XX,[(int(1),fd(2,'Name')),(int(2),fd(1,'Name'))]) )).
2669
2670 %:- assert_must_succeed(( exact_element_of(X,
2671 % closure([zzzz],[set(record([field(balance,integer),field(name,global('Code'))]))],
2672 % 'In'('ListExpression'(['Identifier'(zzzz)]),
2673 % 'PowerSet'(value(closure([zzzz],
2674 % [record([field(balance,integer),field(name,global('Code'))])],'In'('ListExpression'(['Identifier'(zzzz)]),
2675 % 'SetOfRecords'(value(cons_expr(field(balance,global_set('NAT')),
2676 % cons_expr(field(name,global_set('Code')),nil_expr))))))))))),
2677 % X=[rec([field(balance,int(0)),field(name,fd(2,'Code'))])] )).
2678 %:- assert_must_fail(( exact_element_of(X,
2679 % closure([zzzz],[set(record([field(balance,integer),field(name,global('Code'))]))],
2680 % 'In'('ListExpression'(['Identifier'(zzzz)]),
2681 % 'PowerSet'(value(closure([zzzz],
2682 % [record([field(balance,integer),field(name,global('Code'))])],'In'('ListExpression'(['Identifier'(zzzz)]),
2683 % 'SetOfRecords'(value(cons_expr(field(balance,global_set('NAT')),
2684 % cons_expr(field(name,global_set('Code')),nil_expr))))))))))),
2685 % X=[rec([field(balance,int(-1)),field(name,fd(2,'Code'))])] )).
2686
2687
2688 /* use this to compute elements */
2689 exact_element_of(X,Set) :-
2690 dif(Set,[]),
2691 exact_element_of2(Set,X).
2692 :- block exact_element_of2(-,?).
2693 exact_element_of2([H|_],H).
2694 exact_element_of2([_|T],E) :- exact_element_of3(T,E).
2695 exact_element_of2(X,E) :- is_custom_explicit_set_nonvar(X), check_element_of(E,X).
2696 :- block exact_element_of3(-,?).
2697 exact_element_of3([H|_],H).
2698 exact_element_of3([_|T],E) :- exact_element_of3(T,E).
2699
2700
2701 :- assert_must_succeed(exhaustive_kernel_check(check_element_of(int(1),[int(2),int(1)]))).
2702 :- assert_must_succeed(exhaustive_kernel_fail_check(check_element_of(int(3),[int(2),int(1)]))).
2703 :- assert_must_succeed(exhaustive_kernel_fail_check(check_element_of(int(1),[]))).
2704
2705 /* uses equal_object instead of unification */
2706 :- assert_must_succeed((check_element_of(X,
2707 [(int(1),(int(1),(int(1),int(1)))),(int(2),(int(1),(int(1),int(1)))),
2708 (int(1),(int(1),(int(1),int(2)))),(int(2),(int(1),(int(1),int(2))))]),
2709 equal_object(X, (int(2),(int(1),(int(1),int(2))))) )).
2710 :- assert_must_succeed((check_element_of(X,
2711 [ (((int(1),int(1)),int(1)),int(1)), (((int(1),int(1)),int(1)),int(2)),
2712 (((int(1),int(1)),int(1)),int(3)), (((int(1),int(1)),int(1)),int(4)),
2713 (((int(1),int(1)),int(2)),int(1)), (((int(1),int(1)),int(2)),int(2))
2714 ]), equal_object(X, (((int(1),int(1)),int(2)),int(1)))
2715 )).
2716 :- assert_must_succeed((check_element_of(fd(1,'Name'),global_set('Name')))).
2717 %:- assert_must_succeed_multiple(check_element_of(X,[[fd(1,'Name')],[]])).
2718 :- assert_must_succeed((check_element_of((int(1),int(2)),[(int(1),int(2))]))).
2719 :- assert_must_succeed((check_element_of((_X,_Y),[(fd(2,'Code'),fd(2,'Code'))]))).
2720 :- assert_must_succeed((init_wait_flags(WF),
2721 check_element_of_wf((X,Y),[(fd(2,'Code'),fd(2,'Code'))],WF),
2722 ground_det_wait_flag(WF), X= fd(2,'Code'), Y= fd(2,'Code'),
2723 kernel_waitflags:ground_wait_flags(WF) )).
2724 :- assert_must_succeed((init_wait_flags(WF),
2725 check_element_of_wf((Y,X),[(fd(2,'Code'),fd(2,'Code'))],WF),
2726 ground_det_wait_flag(WF), X= fd(2,'Code'), Y= fd(2,'Code'),
2727 kernel_waitflags:ground_wait_flags(WF) )).
2728 :- assert_must_succeed((check_element_of([int(1),int(2)],[[int(2),int(1)]]))).
2729
2730 :- assert_must_succeed((check_element_of([int(1),int(2)],[[],[int(2),int(1)]]))).
2731 :- assert_must_succeed((check_element_of(X,[[],[int(2),int(1)]]), X==[] )).
2732 :- assert_must_succeed((check_element_of_wf(X,[[],[int(2),int(1)]],_WF),
2733 equal_object(X,[int(1),int(2)]) )).
2734 :- assert_must_succeed((check_element_of_wf(XX,global_set('Name'),WF),kernel_waitflags:ground_wait_flags(WF), XX==fd(3,'Name') )).
2735 :- assert_must_fail(check_element_of([fd(2,'Name')],[[fd(1,'Name')],[]])).
2736 :- assert_must_fail((check_element_of([int(2)],[[],[int(2),int(1)]]))).
2737 :- assert_must_succeed((check_element_of(int(1),_X))).
2738 :- assert_must_succeed((check_element_of((int(2),_X),[(int(1),[(int(1),int(22))]),(int(2),[(int(1),int(55))])]))).
2739
2740 check_element_of(X,Set) :- init_wait_flags(WF,[check_element_of]),
2741 check_element_of_wf(X,Set,WF),
2742 ground_wait_flags(WF).
2743
2744 % new test: check_element_of(int(1),X).
2745 % new test: check_element_of(int(1),[int(2)|X]).
2746
2747 check_element_of_wf(X,Set,WF) :- %print(el_of(X,Set)),nl,
2748 dif(Set,[]),
2749 % TO do: mark Set as non-empty not_empty_set_wf from kernel_cardinality_attr
2750 ? check_element_of1(X,Set,WF).
2751
2752 %check_element_of1(X,Set,WF) :- var(X),var(Set),unbound_variable_check(Set),!,
2753 % Set=[_|_], check_element_of2(Set,X,WF).
2754 %:- block check_element_of1(-,-,?). %%
2755
2756
2757 %:- block check_element_of1(-,-,?). % leads to time-out in test 292 for {x,S,S2|x : S & S <: (1 .. 213) & S \/ {x} = S2 & x /: S2} and test 1976 in data_validation mode and CLPFD false
2758 check_element_of1(X,Set,WF) :-
2759 (unbound_variable_for_element_of(Set),
2760 preference(data_validation_mode,false) % TODO: this leads to failure of test 1976 with CLPFD FALSE
2761 % but avoids instantiating Sets to lists early on: can disturb enumeration and efficient computation/unification of large sets
2762 ? -> check_element_of_unbound_set(X,Set,WF)
2763 ? ; check_element_of2(Set,X,WF)
2764 ).
2765
2766 check_element_of_unbound_set(X,Set,_WF) :-
2767 mark_as_non_free(X,check_element_of_unbound_set),
2768 Set=[X|_]. % Note: X needs to be nonvar so that other code knows X is not free anymore
2769 % TO DO: normalise X ?
2770 % TO DO: do this using CHR/attributes rather than by instantiation
2771
2772
2773 unbound_variable_for_element_of(Set) :- unbound_variable_for_cons(Set).
2774
2775 % attach co-routine to mark a given term as not a real variable
2776 mark_as_non_free(X,_Info) :- var(X) -> non_free(X) ; true.
2777 mark_as_non_free(X) :- var(X) -> non_free(X) ; true.
2778 :- block non_free(-).
2779 non_free([H|T]) :- !, mark_as_non_free(H), mark_as_non_free(T).
2780 non_free((A,B)) :- !, mark_as_non_free(A), mark_as_non_free(B).
2781 non_free(rec(Fields)) :- !, mark_as_non_free_fields(Fields).
2782 non_free(_).
2783 :- block mark_as_non_free_fields(-).
2784 mark_as_non_free_fields([]).
2785 mark_as_non_free_fields([field(_,Val)|T]) :- mark_as_non_free(Val),mark_as_non_free_fields(T).
2786
2787 :- use_module(clpfd_lists,[lazy_fd_value_check/4]).
2788
2789 :- block check_element_of2(-,?,?).
2790 check_element_of2(CS,El,WF) :-
2791 ? is_custom_explicit_set_nonvar(CS),!, element_of_custom_set_wf(El,CS,WF).
2792 check_element_of2([],_,_) :- !,fail.
2793 %check_element_of2([H|T],El,WF) :- try_expand_and_convert_to_avl([H|T],AVL),AVL=avl_set(_),!, % much better support exists for AVL trees; should we enable this conversion ?? %nl,print(converted_list_to_AVL([H|T])),nl,nl,
2794 % element_of_custom_set_wf(El,AVL,WF).
2795 check_element_of2([H|T],E,WF) :- !, % print(check_element_of4w(E,H,T,WF)),nl,
2796 % try and transform E : Set into clpfd:element(_,FDVals,EFD) check:
2797 ? lazy_fd_value_check([H|T],E,WF,FullyChecked),
2798 %get_partial_set_priority([H|T],WF,LWF), %%
2799 %get_wait_flag(2,check_element_of2([H|T],E),WF,LWF), %%
2800 (FullyChecked==true,ground(E) -> true % no need to check
2801 ; get_cardinality_wait_flag([H|T],check_element_of2,WF,LWF),
2802 ? check_element_of4w(E,H,T,WF,LWF) % this call is somewhat redundant if FullyChecked=true; but otherwise in_fd_value_list will not enumerate on its own (e.g., self-checks for relation_over will fail)
2803 ).
2804 check_element_of2(freetype(Id),E,WF) :- !, is_a_freetype_wf(E,Id,WF).
2805 check_element_of2(term(Z),_E,_WF) :- Z==undefined,!,
2806 add_error_fail(check_element_of2,'Encountered uninitialised set variable', '').
2807 check_element_of2(Set,E,WF) :-
2808 add_internal_error('Illegal argument: ',check_element_of2(Set,E,WF)),fail.
2809
2810
2811 % call if you already have an explicit waitflag (LWF) setup for the cardinality of the set
2812 :- block check_element_of_wf_lwf(?,-,?,?).
2813 check_element_of_wf_lwf(El,CS,WF,_LWF) :-
2814 ? is_custom_explicit_set_nonvar(CS),!, element_of_custom_set_wf(El,CS,WF).
2815 ?check_element_of_wf_lwf(E,[H|T],WF,LWF) :- check_element_of4w(E,H,T,WF,LWF).
2816 check_element_of_wf_lwf(E,freetype(Id),WF,_) :- !, is_a_freetype_wf(E,Id,WF).
2817
2818 :- block check_element_of4w(-,?,-,?,-).
2819 % check_element_of4w(E,H,T,_WF,_LWF) :- print(check_element_of4w(E,H,T,_WF,_LWF)),nl,fail.
2820 check_element_of4w(E,H,T,_WF,_LWF) :- T==[],!,equal_object(E,H,check_element_of4w).
2821 check_element_of4w(E,H,_T,_WF,_LWF) :- E==H ,!. %,print(eq(E,H)),nl. % added by mal, 17.10 2007
2822 check_element_of4w(E,H,T,WF,LWF) :- T\==[],
2823 ? equality_objects_lwf(E,H,Res,LWF,WF),
2824 ? check_element_of4(Res,E,T,WF,LWF).
2825
2826 :- block check_element_of4(-,?,?,?,-).
2827 check_element_of4(pred_true,_E,_,_WF,_LWF).
2828 check_element_of4(pred_false,E,T,WF,LWF) :-
2829 ? (var(T) -> T = [E|_] ; check_element_of5(E,T,WF,LWF)).
2830
2831 :- block check_element_of5(?,-,?,?).
2832 check_element_of5(E,R,WF,LWF) :-
2833 get_next_element(R,H,T),
2834 ? check_element_of4w(E,H,T,WF,LWF).
2835
2836
2837
2838 :- assert_must_succeed(exhaustive_kernel_check(not_element_of(int(3),[int(2),int(1)]))).
2839 :- assert_must_succeed(exhaustive_kernel_check(not_element_of(int(3),[int(2),int(1),int(4)]))).
2840 :- assert_must_succeed(exhaustive_kernel_fail_check(not_element_of(int(1),[int(2),int(1)]))).
2841 :- assert_must_succeed((kernel_objects:not_element_of(int(3),[int(2),int(1)]))).
2842 :- assert_must_succeed((kernel_objects:not_element_of(fd(1,'Name'),[]))).
2843 :- assert_must_fail((kernel_objects:not_element_of(fd(1,'Name'),global_set('Name')))).
2844 :- assert_must_succeed((kernel_objects:not_element_of(X,[fd(1,'Name')]),X = fd(2,'Name'))).
2845 :- assert_must_fail((kernel_objects:not_element_of(X,[fd(1,'Name')]),X = fd(1,'Name'))).
2846 :- assert_must_succeed(kernel_objects:not_element_of(term(a),[])).
2847 :- assert_must_fail((kernel_objects:not_element_of(int(1),[int(2),int(1)]))).
2848 :- assert_must_succeed((kernel_objects:not_element_of([int(1),int(2)],
2849 [[int(1)],[int(0),int(4)],[int(0),int(3)],[int(0),int(1)],[int(0)],[]]))).
2850 :- assert_must_fail((kernel_objects:not_element_of(term(3),[int(2),int(1)]))).
2851
2852
2853 not_element_of(X,Set) :- init_wait_flags(WF,[not_element_of]),
2854 ? not_element_of_wf(X,Set,WF),
2855 ? ground_wait_flags(WF).
2856
2857 :- use_module(b_global_sets,[b_get_fd_type_bounds/3]).
2858 :- block not_element_of_wf(-,-,?).
2859 not_element_of_wf(_,Set,_) :- Set==[],!.
2860 not_element_of_wf(El,Set,WF) :- nonvar(El),El=fd(X,GS),b_get_fd_type_bounds(GS,N,N),!,
2861 % we have a global set with a single element; Set must be empty
2862 X=N,empty_set_wf(Set,WF).
2863 ?not_element_of_wf(El,Set,WF) :- not_element_of_wf1(Set,El,WF).
2864
2865 :- block not_element_of_wf1(-,?,?).
2866 not_element_of_wf1(X,E,WF) :- is_custom_explicit_set_nonvar(X),!,
2867 ? not_element_of_custom_set_wf(E,X,WF).
2868 not_element_of_wf1([],_E,_WF).
2869 not_element_of_wf1([H|T],E,WF) :-
2870 ? not_equal_object_wf(E,H,WF),
2871 ? not_element_of_wf1(T,E,WF).
2872
2873
2874 :- assert_must_succeed(exhaustive_kernel_check(add_element(int(3),[int(2),int(1)],[int(1),int(3),int(2)]))).
2875 :- assert_must_succeed(exhaustive_kernel_fail_check(add_element(int(2),[int(2),int(1)],[int(1),int(3),int(2)]))).
2876 :- assert_must_succeed(exhaustive_kernel_fail_check(add_element(int(4),[int(2),int(1)],[int(1),int(3),int(2)]))).
2877 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(2),int(1)],R),
2878 kernel_objects:equal_object(R,[int(1),int(2),int(3)]))).
2879 :- assert_must_succeed((kernel_objects:add_element([int(2)],[[int(2),int(1)],[]],R),
2880 kernel_objects:equal_object(R,[[],[int(1),int(2)],[int(2)]]))).
2881 :- assert_must_succeed((kernel_objects:add_element([int(1),int(2)],[[int(2),int(1)],[]],R),
2882 kernel_objects:equal_object(R,[[],[int(1),int(2)]]))).
2883 :- assert_must_succeed((kernel_objects:add_element(X,[int(2),int(1)],R),
2884 kernel_objects:equal_object(R,[int(1),int(2)]), X = int(1))).
2885 :- assert_must_succeed((kernel_objects:add_element([int(1),int(2)],
2886 [[int(1)],[int(0),int(4)],[int(0),int(3)],[int(0),int(1)],[int(0)],[]], _R))).
2887
2888 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(X),int(1)],R,D),
2889 var(D), X=3, R==[int(3),int(1)], D==done)).
2890
2891 :- assert_must_fail((kernel_objects:add_element(term(msg),[int(2),int(1)],_R))).
2892 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(2),int(X)],R),
2893 nonvar(R), R =[H|T], H==int(2), nonvar(T),T=[_HH|TT],var(TT),
2894 X=4, T==[int(4),int(3)])).
2895 :- assert_must_succeed((kernel_objects:add_element(int(3),[int(2),int(X)],R),
2896 nonvar(R), R =[H|T], H==int(2), nonvar(T),T=[_HH|TT],var(TT),
2897 X=3, T==[int(3)])).
2898 :- assert_must_succeed((kernel_objects:add_element(int(3),X,[int(2),int(3)]),
2899 kernel_objects:equal_object(X,[int(2)]) )).
2900 :- assert_must_succeed((kernel_objects:add_element(int(3),X,[int(3)]),
2901 kernel_objects:equal_object(X,[]) )).
2902 :- assert_must_succeed((add_element(X,[int(1)],[int(1)]),X==int(1))).
2903 :- assert_must_succeed((add_element(X,[],[int(1)]),X==int(1))).
2904 % kernel_objects:add_element(E,[H],R,Done), H = int(X), E=int(Y), X in 1..10, Y in 11..20.
2905
2906
2907 add_element(E,Set,NewSet) :- add_element(E,Set,NewSet,_).
2908 add_element(Element,Set,NewSet,Done) :- add_element_wf(Element,Set,NewSet,Done,no_wf_available).
2909 add_element_wf(E,Set,NewSet,WF) :- add_element_wf(E,Set,NewSet,_,WF).
2910
2911 :- block add_element_wf(?,-,?,?,?).
2912 add_element_wf(Element,Set,NewSet,Done,_WF) :- Set==[],!,
2913 % try and convert to AVL if possible:
2914 ? equal_object_optimized(NewSet,[Element]), % we could call equal_object_opt3 directly
2915 Done=done.
2916 ?add_element_wf(E,Set,NewSet,Done,WF) :- add_element1_wf(E,Set,NewSet,Done,WF).
2917
2918 :- block %add_element1(-,?,-,?),
2919 add_element1_wf(?,-,?,?,?).
2920 add_element1_wf(E,Set,NewSet,Done,WF) :- var(E),!, add_element_var(Set,NewSet,E,Done,WF).
2921 add_element1_wf(E,[H|T],NewSet,Done,WF) :- E==H,!, % avoid running [H|T] through expand_custom_set_to_list, in case T is a variable this will create a pending co-routine
2922 ? equal_object_wf(NewSet,[H|T],add_element1_1,WF),Done=done.
2923 add_element1_wf(E,Set,NewSet,Done,WF) :-
2924 nonvar(Set), is_custom_explicit_set_nonvar(Set),
2925 add_element_to_explicit_set_wf(Set,E,R,WF),!,
2926 ? equal_object_wf(R,NewSet,add_element1_2,WF),Done=done.
2927 add_element1_wf(E,Set,NewSet,Done,WF) :-
2928 expand_custom_set_to_list_wf(Set,ESet,_,add_element1,WF), % we could avoid this expansion by treating avl_set,... below in add_element3
2929 ? add_element2_wf(ESet,E,NewSet,Done,WF).
2930
2931
2932 add_element_var([],Res,Element,Done,WF) :- !,
2933 equal_cons_wf(Res,Element,[],WF),Done=done.
2934 add_element_var(Set,Res,Element,Done,WF) :- Set \= [], Set \= closure(_,_,_),
2935 is_one_element_set(Res,ResEl), !,
2936 % the result is a one element set; hence Element *must* be the element in that set
2937 equal_object_wf(Element,ResEl,add_element_var_1,WF),
2938 equal_object_wf(Set,Res,add_element_var_2,WF), Done=done.
2939 add_element_var(Set,Res,Element,Done,WF) :- %when(nonvar(Element), add_element(Element,Set,Res,Done)).
2940 expand_custom_set_to_list_wf(Set,ESet,_,add_element_var,WF),
2941 add_element2_wf(ESet,Element,Res,Done,WF).
2942
2943 is_one_element_set(S,_) :- var(S),!,fail.
2944 is_one_element_set([H|T],H) :- T==[].
2945 is_one_element_set(avl_set(S),El) :- is_one_element_custom_set(avl_set(S),El).
2946
2947 :- block add_element2_wf(-,?,?,?,?).
2948 add_element2_wf([],E,Res,Done,WF) :- var(Res),should_be_converted_to_avl(E),
2949 construct_avl_from_lists_wf([E],R,WF),!,
2950 (R,Done)=(Res,done).
2951 ?add_element2_wf(S,E,Res,Done,WF) :- copy_list_skeleton(S,Res,WF),
2952 ? add_element3_wf(S,E,Res,Done,WF).
2953
2954 % TO DO: use something else, like subset to propagate info that Set1 <: Set1 \/ {New}
2955 :- block copy_list_skeleton(-,?,?).
2956 copy_list_skeleton([],_,_WF) :- !.
2957 copy_list_skeleton([H|T],R,WF) :- !, % H must be in R, but not all elements of R are in [H|T] !; it could be the added element
2958 ((ground_value(H) ; unbound_variable_for_cons(R) ;
2959 custom_explicit_sets:singleton_set(R,_) % if R is a singleton set {EL} then H must be EL and T=[]
2960 )
2961 ? -> equal_cons_wf(R,H,RR,WF),
2962 copy_list_skeleton(T,RR,WF)
2963 ; %nl,print(not_copying([H|T],R)),nl,
2964 true % otherwise equal_cons_wf can backpropagate elements from R into H !! see {x,y| x = {1,2} & x \/ y = {1,2,3} & 1:y } test 1535
2965 ).
2966 copy_list_skeleton(Set,R,WF) :- !,is_custom_explicit_set(Set,copy_list_skeleton),
2967 expand_custom_set_to_list_wf(Set,ESet,_,copy_list_skeleton,WF), copy_list_skeleton(ESet,R,WF).
2968 copy_list_skeleton(Skel,R,WF) :- add_internal_error('Argument not a set: ',copy_list_skeleton(Skel,R,WF)).
2969
2970 :- block add_element3_wf(-,?,?,?,?).
2971 add_element3_wf([],E,Res,Done,WF) :- % Res must be {E}
2972 ? equal_cons_wf(Res,E,[],WF),
2973 Done=done.
2974 add_element3_wf([H|T],E,Res,Done,WF) :-
2975 equality_objects_wf(H,E,EqRes,WF),
2976 equal_cons_wf(Res,H,TailRes,WF), % was: equal_object([H|TailRes],Res), % use WF?
2977 (var(EqRes)
2978 ? -> has_not_to_be_added([H|T],Res,EqRes,0)
2979 ; true),
2980 %(when(nonvar(EqRes),(print(nv(EqRes,H,T,WF)),nl))),
2981 ? add_element4_wf(EqRes,T,E,TailRes,Done,WF).
2982
2983
2984 % check if an element has not to be added to arg1 to obtain arg2
2985 :- block has_not_to_be_added(?,-,?,?),has_not_to_be_added(-,?,?,?).
2986 %has_not_to_be_added(A,B,R,Sz) :- print(has_not_to_be_added(A,B,R,Sz)),nl,fail.
2987 has_not_to_be_added([],[],R,Sz) :- !,(Sz=1 -> R=pred_true % we have 1 element: force equality with first element
2988 ; true).
2989 has_not_to_be_added([],[_H|T],R,_Sz) :- !, %(var(R) -> print(add_f([],[_H|T],R,_Sz)),nl ; true),
2990 empty_set(T),R=pred_false. % R=pred_false means with add an element
2991 has_not_to_be_added([_|_],[],_,_) :- !,fail. % we can either add or not; in both cases we do not obtain []
2992 ?has_not_to_be_added([_|T1],[_|T2],R,Sz) :- !, S1 is Sz+1, has_not_to_be_added(T1,T2,R,S1).
2993 has_not_to_be_added(_,_,_,_). % to do: support custom explicit sets
2994
2995 :- block add_element4_wf(-,?,?,?,?,?).
2996 ?add_element4_wf(pred_true, T,_E,TRes,Done,WF) :- equal_object_wf(T,TRes,add_element4_wf,WF), Done=done.
2997 ?add_element4_wf(pred_false,T, E,TRes,Done,WF) :- add_element3_wf(T,E,TRes,Done,WF).
2998
2999
3000 :- assert_must_succeed((kernel_objects:add_new_element(int(3),[int(2),int(1)],R),
3001 kernel_objects:equal_object(R,[int(1),int(2),int(3)]))).
3002 :- assert_must_succeed((kernel_objects:add_new_element([int(2)],[[int(2),int(1)],[]],R),
3003 kernel_objects:equal_object(R,[[],[int(1),int(2)],[int(2)]]))).
3004
3005 % TO DO : get rid of need for non-WF version in enumeration basic type:
3006 add_new_element(E,Set,NewSet) :- init_wait_flags(WF),
3007 add_new_element_wf(E,Set,NewSet,WF), ground_wait_flags(WF).
3008
3009 % use when you are sure the element to add is not in the set
3010 % to be used for adding elements to an accumulator
3011 :- block add_new_element_wf(?,-,?,?).
3012 %%add_new_element(E,Set,NewSet) :- add_element(E,Set,NewSet). % TO DO : Improve
3013 add_new_element_wf(E,Set,NewSet,WF) :-
3014 is_custom_explicit_set(Set,add_element),
3015 add_element_to_explicit_set_wf(Set,E,R,WF),!,
3016 equal_object_wf(R,NewSet,add_new_element_wf,WF).
3017 add_new_element_wf(E,Set,NewSet,WF) :-
3018 expand_custom_set_to_list_wf(Set,ESet,_,add_new_element_wf,WF),
3019 add_new_element2(ESet,E,NewSet,WF).
3020
3021 :- block add_new_element2(-,?,?,?).
3022 add_new_element2([],E,Res,WF) :- var(Res),should_be_converted_to_avl(E),
3023 construct_avl_from_lists_wf([E],R,WF),!,equal_object_wf(R,Res,add_new_element2,WF).
3024 add_new_element2(S,E,Res,WF) :- equal_cons_wf(Res,E,S,WF).
3025
3026
3027
3028
3029 :- assert_must_succeed(exhaustive_kernel_check(remove_element_wf(int(3),[int(3),int(1)],
3030 [int(1)],_WF))).
3031 :- assert_must_succeed(exhaustive_kernel_check(remove_element_wf(int(1),[int(3),int(1)],
3032 [int(3)],_WF))).
3033 :- assert_must_succeed(exhaustive_kernel_fail_check(remove_element_wf(int(1),[int(3),int(1)],
3034 [int(1)],_WF))).
3035 :- assert_must_succeed(exhaustive_kernel_fail_check(remove_element_wf(int(11),[int(1)],
3036 [int(1)],_WF))).
3037 :- assert_must_succeed(exhaustive_kernel_fail_check(remove_element_wf(int(1),[int(3),int(1)],
3038 [],_WF))).
3039 :- assert_must_succeed((kernel_objects:remove_element_wf(fd(1,'Name'),X,[fd(2,'Name'),fd(3,'Name')],_WF),
3040 kernel_objects:equal_object(X,global_set('Name')))).
3041 :- assert_must_succeed((kernel_objects:remove_element_wf(int(1),X,[int(2)],_WF),
3042 kernel_objects:equal_object(X,[int(2),int(1)]))).
3043 :- assert_must_succeed(( kernel_objects:remove_element_wf(int(1),[int(X),int(2)],R,WF), kernel_waitflags:ground_wait_flags(WF),X==1,R==[int(2)] )).
3044 :- assert_must_succeed(( kernel_objects:remove_element_wf(X,[int(1),int(2)],R,WF), kernel_waitflags:ground_wait_flags(WF),X==int(2),R==[int(1)] )).
3045 :- assert_must_succeed(( kernel_objects:remove_element_wf(X,[pred_true /* bool_true */,pred_false /* bool_false */],R,WF), kernel_waitflags:ground_wait_flags(WF),X==pred_false /* bool_false */,R==[pred_true /* bool_true */] )).
3046
3047 ?remove_element_wf(X,Set,Res,WF) :- remove_element_wf(X,Set,Res,WF,_DONE).
3048
3049 :- block remove_element_wf(?,-, -,?,?).
3050 remove_element_wf(X,Set,Res,WF,_DONE) :- Res==[],!, % we know that X must be the only element in Set
3051 equal_object_wf(Set,[X],remove_element_wf,WF).
3052 remove_element_wf(X,Set,Res,WF,DONE) :-
3053 ? remove_element_wf1(X,Set,Res,WF,DONE).
3054
3055 :- block remove_element_wf1(?,-, ?,?,?).
3056 remove_element_wf1(X,avl_set(A),Res,WF,DONE) :- element_can_be_added_or_removed_to_avl(X),!,
3057 /* TO DO: try and move the check about whether X can be added to later; when either X is known
3058 or LWF is instantiated */
3059 remove_element_from_explicit_set(avl_set(A),X,AR),
3060 equal_object_wf(AR,Res,remove_element_wf1,WF), DONE=done.
3061 remove_element_wf1(X,Set,Res,WF,DONE) :- /* DONE is ground when element actually removed */
3062 expand_custom_set_to_list_wf(Set,ESet,_,remove_element_wf1,WF),
3063 %% nl,print(remove_element_wf1(X,Set,ESet,Res,WF,DONE)),nl,nl, %%
3064 ? remove_element_wf2(X,ESet,Res,LWF,DONE),
3065 %when(nonvar(DONE), print_bt_message(removed(X,ESet,Res,LWF))),
3066 (DONE==done -> true
3067 ; same_card_prop(ESet,[X|Res]), % in case result is instantiated: check compatible with inputs
3068 get_cardinality_wait_flag(ESet,remove_element_wf1(X,ESet,Res),WF,LWF),
3069 ? quick_propagation_element_information(Set,X,WF,_) % use Set rather than ESet; better if still closure or AVL
3070 ).
3071
3072 :- block same_card_prop(-,?), same_card_prop(?,-).
3073 same_card_prop([],[_|_]) :- !, fail.
3074 same_card_prop([_|T],R) :- !,
3075 (R=[] -> fail
3076 ; R=[_|RT] -> same_card_prop(T,RT)
3077 ; true). % just ignore
3078 same_card_prop(_,_).
3079
3080 :- block remove_element_wf2(?,-,?,?,?).
3081 remove_element_wf2(H1,[H2|T],Res,LWF,DONE) :- Res==[],!,
3082 equal_object(H1,H2,remove_element_wf2),
3083 remove_element_wf3(pred_true,H1,H2,T,Res,LWF,DONE).
3084 remove_element_wf2(H1,[H2|T],Res,LWF,DONE) :-
3085 prop_empty_set(T,EqRes),
3086 ? equality_objects_lwf(H1,H2,EqRes,LWF,no_wf_available), % TODO: pass WF
3087 ? remove_element_wf3(EqRes,H1,H2,T,Res,LWF,DONE).
3088 /* important for total_bijection that this has higher priority than other expansions */
3089
3090 :- block prop_empty_set(-,?).
3091 % force second argument to pred_true if first arg is empty set
3092 prop_empty_set([],R) :- !, R=pred_true.
3093 prop_empty_set(_,_).
3094
3095 :- block remove_element_wf3(-,?,?,?,?,-,?).
3096 % remove_element_wf3(EqRes,H1,H2,T,Res,LWF,DONE) :- print(remove_element_wf3(EqRes,H1,H2,T,Res,LWF,DONE)),nl,fail.
3097 remove_element_wf3(pred_true,_H1,_H2,T,Res,_LWF,DONE) :-
3098 ? equal_object(T,Res,remove_element_wf3_1),DONE=done.
3099 remove_element_wf3(pred_false,E,H,T,Res,LWF,DONE) :-
3100 ? equal_object([H|RT],Res,remove_element_wf3_2),
3101 ? remove_element_wf2(E,T,RT,LWF,DONE).
3102
3103 /* the same as above: but do not remove if infinite or closure */
3104
3105 :- block remove_element_wf_if_not_infinite_or_closure(?,-,?,?,?,?).
3106 remove_element_wf_if_not_infinite_or_closure(X,Set, Res,WF,LWF,Done) :-
3107 (dont_expand(Set)
3108 ? -> check_element_of_wf(X,Set,WF),
3109 equal_object_wf(Res,Set,remove_element_wf_if_not_infinite_or_closure,WF),
3110 Done=true % or should we wait until X known ?
3111 %(var(Res)->Res=Set ; equal_object(Res,Set))
3112 ; expand_custom_set_to_list_wf(Set,ESet,_,remove_element_wf_if_not_infinite_or_closure,WF),
3113 ? remove_element_wf2(X,ESet,Res,LWF,Done)
3114 ).
3115
3116 %:- use_module(bmachine_construction,[external_procedure_used/1]).
3117 %dont_expand(global_set('STRING')) :- !. % s: STRING +-> ... will generate new strings !
3118 %(external_procedure_used(_) -> true). % we could check if there is a STRING generating procedure involved
3119 % unless we use external functions, there is *no* way that new strings can be generated from a B machine !
3120 % Hence: we can expand STRING safely and thus avoid infinite enumeration of partial functions, ...
3121 % example: procs : STRING +-> {"waiting"} & card( dom(procs) ) = 6 thus fails quickly
3122 dont_expand(avl_set(_)) :- !,fail.
3123 dont_expand(closure(_,_,_)) :- !. % relevant for tests 283, 1609, 1858
3124 dont_expand(Set) :- is_infinite_or_very_large_explicit_set(Set). % should we use a smaller bound than 20000 ? see test 1609
3125
3126
3127 :- assert_must_succeed((kernel_objects:check_no_duplicates_in_list([int(1),int(2)],[],no_wf_available))).
3128 :- assert_must_fail((kernel_objects:check_no_duplicates_in_list([int(1),int(2),int(1)],[],no_wf_available))).
3129
3130 :- block check_no_duplicates_in_list(-,?,?).
3131 check_no_duplicates_in_list([],_,_) :- !.
3132 check_no_duplicates_in_list([H|T],ElementsSoFar,WF) :- !,
3133 ? not_element_of_wf(H,ElementsSoFar,WF),
3134 add_new_element_wf(H,ElementsSoFar,ElementsSoFar2,WF),
3135 check_no_duplicates_in_list(T,ElementsSoFar2,WF).
3136 check_no_duplicates_in_list(CS,ElementsSoFar,WF) :-
3137 disjoint_sets(CS,ElementsSoFar,WF).
3138
3139 :- public warn_if_duplicates_in_list/3.
3140 % code for debugging / safe mode execution to check for duplicates
3141 warn_if_duplicates_in_list(List,Src,WF) :-
3142 %get_last_wait_flag(warn_if_duplicates_in_list,WF,WFX), % we may wish to use another WF here !?
3143 get_enumeration_finished_wait_flag(WF,WFX),
3144 when(nonvar(WFX),warn_if_duplicates_in_list(List,[],Src,WF)).
3145
3146 :- block warn_if_duplicates_in_list(-,?,?,?).
3147 warn_if_duplicates_in_list([],_,_,_) :- !.
3148 warn_if_duplicates_in_list([H|T],ElementsSoFar,Src,WF) :- !,
3149 membership_test_wf(ElementsSoFar,H,MemRes,WF),
3150 warn_aux(MemRes,H,T,ElementsSoFar,Src,WF).
3151 warn_if_duplicates_in_list(CS,ElementsSoFar,Src,WF) :-
3152 when(ground(CS),
3153 (disjoint_sets(CS,ElementsSoFar,WF)
3154 -> true
3155 ; add_error(Src,'Duplicates in list: ',CS:ElementsSoFar:Src))).
3156
3157 :- block warn_aux(-,?,?,?,?,?).
3158 warn_aux(pred_true,H,_,ElementsSoFar,Src,_WF) :-
3159 add_error(Src,'Duplicate in list: ',H:ElementsSoFar:Src).
3160 warn_aux(pred_false,H,T,ElementsSoFar,Src,WF) :-
3161 add_new_element_wf(H,ElementsSoFar,ElementsSoFar2,WF),
3162 warn_if_duplicates_in_list(T,ElementsSoFar2,Src,WF).
3163
3164
3165 :- assert_must_succeed((kernel_objects:remove_exact_first_element([int(1),int(2)],X,[[]]),
3166 X = [[int(1),int(2)],[]])).
3167 :- assert_must_succeed((kernel_objects:remove_exact_first_element(X,global_set('Name'),T),
3168 X==fd(1,'Name'),T==[fd(2,'Name'),fd(3,'Name')])).
3169 :- assert_must_fail((kernel_objects:remove_exact_first_element([[]],X,_),
3170 X = [[int(1),int(2)],[]])).
3171
3172 :- assert_must_succeed((kernel_objects:remove_exact_first_element(X,C,R),
3173 kernel_objects:gen_test_interval_closure(1,2,C),
3174 X == int(1), R == [int(2)] )).
3175
3176 gen_test_interval_closure(From,To,CL) :-
3177 CL=closure(['_zzzz_unary'],[integer],b(member( b(identifier('_zzzz_unary'),integer,[]),
3178 b(interval(b(value(int(From)),integer,[]),
3179 b(value(int(To)),integer,[])),set(integer),[])),pred,[])).
3180
3181 :- block remove_exact_first_element(?,-,?).
3182 remove_exact_first_element(X,Set,Res) :- remove_exact_first_element1(Set,X,Res).
3183
3184 remove_exact_first_element1([],_,_) :- fail.
3185 remove_exact_first_element1([H|T],H,T).
3186 remove_exact_first_element1(avl_set(A),H,T) :- remove_minimum_element_custom_set(avl_set(A),H,T).
3187 remove_exact_first_element1(global_set(GS),H,T) :-
3188 remove_minimum_element_custom_set(global_set(GS),H,T).
3189 remove_exact_first_element1(freetype(GS),H,T) :-
3190 remove_minimum_element_custom_set(freetype(GS),H,T).
3191 remove_exact_first_element1(closure(P,Types,B),H,T) :-
3192 remove_minimum_element_custom_set(closure(P,Types,B),H,T).
3193
3194
3195 :- assert_must_succeed((kernel_objects:delete_element_wf(fd(1,'Name'),X,[fd(2,'Name'),fd(3,'Name')],_WF),
3196 X = global_set('Name'))).
3197 :- assert_must_succeed((kernel_objects:delete_element_wf(int(1),X,[int(2)],_WF),
3198 X = [int(2),int(1)])).
3199 :- assert_must_succeed((kernel_objects:delete_element_wf([int(1),int(2)],X,[],_WF),
3200 X = [[int(2),int(1)]])).
3201 :- assert_must_succeed((kernel_objects:delete_element_wf(int(3),X,[int(2),int(1)],_WF),
3202 X = [int(2),int(1)])).
3203 :- assert_must_succeed((kernel_objects:delete_element_wf(int(1),X,X,_WF),
3204 X = [])).
3205 :- assert_must_fail((kernel_objects:delete_element_wf(int(X),[int(1)],[int(1)],_WF),
3206 X = 1)).
3207
3208 /* WARNING: only use when R is not instantiated by something else;
3209 (except for R=[]) */
3210
3211
3212 :- block delete_element_wf(?,-,?,?).
3213 delete_element_wf(X,Set,Res,WF) :-
3214 ground(X),
3215 try_expand_and_convert_to_avl_with_check(Set,ESet,delete_element_wf),!,
3216 delete_element0(X,ESet,Res,WF).
3217 delete_element_wf(X,Set,Res,WF) :- delete_element1(X,Set,Res,WF).
3218
3219 :- block delete_element0(?,-,?,?).
3220 delete_element0(X,ESet,Res,WF) :-
3221 ( is_custom_explicit_set(ESet,delete_element),
3222 delete_element_from_explicit_set(ESet,X,DS)
3223 -> equal_object_wf(DS,Res,delete_element0,WF)
3224 ; delete_element1(X,ESet,Res,WF)
3225 ).
3226
3227 delete_element1(X,Set,Res,WF) :- expand_custom_set_to_list_wf(Set,ESet,_,delete_element1,WF),
3228 %check_is_expanded_set(ESet,delete_element2),
3229 delete_element2(ESet,X,Res,WF).
3230
3231 :- block delete_element2(-,?,?,?).
3232 delete_element2([],_,[],_). /* same as above, but allow element to be absent */
3233 delete_element2([H2|T],E,R,WF) :-
3234 equality_objects_wf(H2,E,EqRes,WF),
3235 delete_element3(EqRes,H2,T,E,R,WF).
3236 %when_sufficiently_instantiated(E,H2,delete_element3(H1,[H2|T],R)). /* added by Michael Leuschel, 16/3/06 */
3237
3238 :- block delete_element3(-,?,?,?,?,?).
3239 delete_element3(pred_true,_H2,T,_,R,WF) :- equal_object_wf(R,T,delete_element3,WF).
3240 delete_element3(pred_false,H2,T,E,Res,WF) :- equal_cons_wf(Res,H2,RT,WF),delete_element2(T,E,RT,WF).
3241
3242
3243
3244
3245 :- assert_must_succeed(kernel_objects:check_is_expanded_set([int(1)],test)).
3246
3247 :- public check_is_expanded_set/2.
3248 check_is_expanded_set(X,Source) :-
3249 (nonvar(X),(X=[] ; X= [_|_]) -> true
3250 ; add_internal_error('Is not expanded set: ',check_is_expanded_set(X,Source))
3251 ).
3252
3253
3254 /* union/3 */
3255
3256 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(3)],[int(2),int(1),int(3)],[int(1),int(3),int(2)]))).
3257 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(1)],[int(1),int(2)],[int(1),int(2)]))).
3258 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(3)],[int(2),int(1)],[int(1),int(3),int(2)]))).
3259 :- assert_must_succeed(exhaustive_kernel_check([commutative],union([int(3),int(2)],[int(2),int(1)],[int(1),int(3),int(2)]))).
3260 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],union([int(3),int(4)],[int(2),int(1)],[int(1),int(3),int(2)]))).
3261 :- assert_must_succeed((kernel_objects:union([int(1)],[int(2)],Res),kernel_objects:equal_object(Res,[_,_]))).
3262 :- assert_must_succeed((kernel_objects:union([],[int(2)],Res),
3263 kernel_objects:equal_object(Res,[int(2)]))).
3264 :- assert_must_succeed((kernel_objects:union([int(2)],[],Res),
3265 kernel_objects:equal_object(Res,[int(2)]))).
3266 :- assert_must_succeed((kernel_objects:union([int(2)],[int(2)],Res),
3267 kernel_objects:equal_object(Res,[int(2)]))).
3268 :- assert_must_succeed((kernel_objects:union([int(1)],Res,[int(1),int(2)]),
3269 kernel_objects:equal_object(Res,[int(2)]))).
3270 :- assert_must_succeed((kernel_objects:union([fd(1,'Name')],X,Res),X=global_set('Name'),
3271 kernel_objects:equal_object(Res,X))).
3272 :- assert_must_succeed((kernel_objects:union(X,global_set('Name'),Res),X=[fd(2,'Name'),fd(1,'Name')],
3273 kernel_objects:equal_object(Res,global_set('Name')))).
3274 :- assert_must_succeed((kernel_objects:union([fd(1,'Name')],[fd(3,'Name'),fd(2,'Name')],Res),
3275 kernel_objects:equal_object(Res,global_set('Name')))).
3276 %:- assert_must_succeed((kernel_objects:union([fd(1,'Name')],[fd(3,'Name'),fd(2,'Name')],Res),
3277 % kernel_objects:equal_object(Res,X),X=global_set('Name'))).
3278 :- assert_must_fail((kernel_objects:union([int(1)],[int(2)],Res),
3279 (kernel_objects:equal_object(Res,[_]);kernel_objects:equal_object(Res,[_,_,_|_])))).
3280 :- assert_must_fail((kernel_objects:union([int(1)],[int(1)],Res),(Res=[];kernel_objects:equal_object(Res,[_,_|_])))).
3281 :- assert_must_fail((kernel_objects:union([fd(1,'Name')],[fd(2,'Name')],Res),
3282 kernel_objects:equal_object(Res,global_set('Name')))).
3283 % kernel_objects:union([int(1),int(2)],X,[int(1),int(2),int(3)])
3284
3285 union(S1,S2,Res) :- init_wait_flags(WF,[union]), union_wf(S1,S2,Res,WF), ground_wait_flags(WF).
3286
3287 :- block union_wf(-,-,-,?).
3288 %union_wf(Set1,Set2,Res,_WF) :- print(union_wf(Set1,Set2,Res)),nl,fail.
3289 ?union_wf(Set1,Set2,Res,WF) :- Set1==[],!,equal_object_wf(Set2,Res,union_wf_1,WF).
3290 union_wf(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,union_wf_2,WF).
3291 union_wf(Set1,Set2,Res,WF) :- Res==[],!,empty_set_wf(Set1,WF), empty_set_wf(Set2,WF).
3292 ?union_wf(Set1,Set2,Res,WF) :- union0(Set1,Set2,Res,WF).
3293
3294 :- block union0(-,-,?,?), union0(-,?,-,?), union0(?,-,-,?). % require two arguments to be known
3295 ?union0(Set1,Set2,Res,WF) :- Set1==[],!,equal_object_wf(Set2,Res,union0_1,WF).
3296 ?union0(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,union0_2,WF).
3297 union0(Set1,Set2,Res,WF) :- Res==[],!,empty_set_wf(Set1,WF), empty_set_wf(Set2,WF).
3298 union0(Set1,Set2,Res,WF) :- nonvar(Res), singleton_set(Res,X),!,
3299 (var(Set1) -> union0_to_singleton_set(Set2,Set1,X,WF) ; union0_to_singleton_set(Set1,Set2,X,WF)).
3300 ?union0(Set1,Set2,Res,WF) :- (var(Set1) -> union1(Set2,Set1,Res,WF) ; union1(Set1,Set2,Res,WF)).
3301
3302 % optimized version for Set1 \/ Set2 = {X}
3303 % TO DO: is not triggered when Set1 and Set2 are instantiated first (before result)
3304 % >>> z:11..12 & {x,y} \/ {v} = {z} does not work
3305 union0_to_singleton_set([],Set2,X,WF) :- !, equal_object_wf(Set2,[X],union0_3,WF). % cannot be reached, due to checks above
3306 union0_to_singleton_set([H|T],Set2,X,WF) :- !, empty_set_wf(T,WF), equal_object_wf(H,X,WF),
3307 check_subset_of_wf(Set2,[X],WF).
3308 union0_to_singleton_set(avl_set(A),Set2,X,WF) :- !, singleton_set(avl_set(A),AEl),
3309 equal_object_wf(AEl,X,WF),
3310 check_subset_of_wf(Set2,[X],WF).
3311 union0_to_singleton_set(Set1,Set2,X,WF) :- % closure or global_set; revert to normal treatment
3312 union1(Set1,Set2,[X],WF).
3313
3314 union1(Set1,Set2,Res,WF) :-
3315 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set1,ESet1,WF),
3316 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set2,ESet2,WF),
3317 ? union1e(ESet1,ESet2,Res,WF).
3318
3319 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set,ESet,_) :- (var(Set);Set=closure(_,_,_)),!,ESet=Set.
3320 try_expand_and_convert_to_avl_unless_large_or_closure_wf(Set,ESet,WF) :-
3321 try_expand_and_convert_to_avl_unless_large_wf(Set,ESet,WF).
3322
3323 union1e(Set1,Set2,Res,WF) :-
3324 is_custom_explicit_set(Set1,union1e),
3325 union_of_explicit_set(Set1,Set2,Union), !,
3326 ? equal_object_wf(Union,Res,union1e,WF).
3327 union1e(Set2,Set1,Res,WF) :- % Set2=avl_set(_), nonvar(Set1), Set1 \= avl_set(_),
3328 nonvar(Set1), Set1=avl_set(_), Set2 \= avl_set(_), \+ ground(Set2),
3329 !, % avoid expanding Set2
3330 expand_custom_set_to_list_wf(Set1,ESet1,_,union1e_1,WF),
3331 ? union2(ESet1,Set2,Res,WF), lazy_check_subset_of(Set2,Res,WF).
3332 union1e(Set1,Set2,Res,WF) :-
3333 expand_custom_set_to_list_wf(Set1,ESet1,_,union1e_2,WF), % we could avoid this expansion by treating avl_set,... below in union2
3334 ? union2(ESet1,Set2,Res,WF),
3335 lazy_check_subset_of(Set1,Res,WF), % ADDED to solve {x,y| { x \/ y } <: {{1} \/ {2}}}
3336 lazy_check_subset_of(Set2,Res,WF) % could perform additional constraint checking
3337 % ,try_prop_card_leq(ESet1,Res), try_prop_card_leq(Set2,Res). %%% seems to slow down ProB: investigate
3338 .
3339
3340 /* not yet used:
3341 % lazy_check_in_union(R,Set1,Set2,WF): check if all elements of R appear in at least one of the sets Sets1/2:
3342 :- block lazy_check_in_union(-,?,?,?).
3343 lazy_check_in_union([],_,_,_) :- !.
3344 lazy_check_in_union([H|T],Set1,Set2,WF) :- !,
3345 in_one_of_sets(H,Set1,Set2,WF),
3346 lazy_check_in_union(T,Set1,Set2,WF).
3347 lazy_check_in_union(_,_,_,_).
3348
3349 % check if an element appear in at least one of the two sets:
3350 in_one_of_sets(H,Set1,Set2,WF) :-
3351 membership_test_wf(Set1,H,MemRes1,WF),
3352 (MemRes1==pred_true -> true
3353 ; one_true(MemRes1,MemRes2),
3354 membership_test_wf(Set2,H,MemRes2,WF)
3355 ).
3356
3357 :- block one_true(-,-).
3358 one_true(MemRes1,MemRes2) :- var(MemRes1),!,
3359 (MemRes2=pred_false -> MemRes1=pred_true ; true).
3360 one_true(pred_true,_).
3361 one_true(pred_false,pred_true).
3362 */
3363
3364
3365 :- block lazy_try_check_element_of(?,-,?).
3366 ?lazy_try_check_element_of(H,Set,WF) :- lazy_check_element_of_aux(Set,H,WF).
3367
3368 lazy_check_element_of_aux(closure(P,T,B),H,WF) :- !, check_element_of_wf(H,closure(P,T,B),WF).
3369 lazy_check_element_of_aux(avl_set(A),H,WF) :- !, check_element_of_wf(H,avl_set(A),WF).
3370 ?lazy_check_element_of_aux([X|T],H,WF) :- !, lazy_check_element_of_list(T,X,H,WF).
3371 lazy_check_element_of_aux(_,_,_).
3372
3373 :- block lazy_check_element_of_list(-,?,?,?).
3374 lazy_check_element_of_list([],X,H,WF) :- !, equal_object_wf(X,H,WF).
3375 lazy_check_element_of_list([Y|T],X,H,WF) :- !,
3376 ? quick_propagation_element_information([X,Y|T],H,WF,_). % TO DO: check that we loose no performance due to this
3377 lazy_check_element_of_list(_,_,_,_).
3378
3379 % an incomplete subset check without enumeration
3380 :- block lazy_check_subset_of(-,?,?), lazy_check_subset_of(?,-,?).
3381 lazy_check_subset_of(Set1,Set2,WF) :- nonvar(Set2),
3382 (Set2=closure(_,_,_) ; Set2=avl_set(_)),!, lazy_check_subset_of2(Set1,Set2,WF).
3383 lazy_check_subset_of(_,_,_). % ignore other set representations
3384 :- block lazy_check_subset_of2(-,?,?).
3385 lazy_check_subset_of2([],_,_WF) :- !.
3386 lazy_check_subset_of2([H|T],Set,WF) :- !, check_element_of_wf(H,Set,WF), lazy_check_subset_of2(T,Set,WF).
3387 lazy_check_subset_of2(_,_,_). % ignore other set representations
3388
3389 :- block union2(-,?,?,?).
3390 ?union2([],S,Res,WF) :- equal_object_optimized_wf(S,Res,union2,WF).
3391 union2([H|T],Set2,Res,WF) :-
3392 (T\==[],nonvar(Set2), Set2=[H2|T2], T2==[] % minor optimisation for improved propagation; e.g., for x:S & S<:1..13 & S \/ {x} = S2 & x/: S2
3393 % the constraint is not yet detected straight away: x:S & S<:1..12 & S \/ {x} /= S
3394 ? -> union3(H2,T2,[H|T],Res,WF)
3395 ? ; union3(H,T,Set2,Res,WF)
3396 ).
3397 union3(H,T,Set2,Res,WF) :-
3398 add_element_wf(H,Set2,R,Done,WF),
3399 ? lazy_try_check_element_of(H,Res,WF), % TO DO: propagate constraint that H is in Res
3400 (T==[]
3401 ? -> equal_object_optimized_wf(R,Res,union3,WF) %union2(T,R,Res,WF)
3402 ? ; union4(Done,T,R,Res,WF)).
3403 :- block union4(-,?,?,?,?).
3404 ?union4(_Done,T,R,Res,WF) :- union2(T,R,Res,WF). % if WF not set to 2 there maybe equality_objects pending from add_element_wf ! TO DO: investigate; see test 293
3405
3406
3407 :- assert_must_succeed(exhaustive_kernel_check(union_generalized([[int(3)],[int(2),int(1),int(3)]],[int(1),int(3),int(2)]))).
3408 :- assert_must_succeed(exhaustive_kernel_check(union_generalized([[int(3),int(2)],[],[int(2),int(1),int(3)]],[int(1),int(3),int(2)]))).
3409 :- assert_must_succeed(exhaustive_kernel_fail_check(union_generalized([[int(3)],[int(3),int(4)],[int(2),int(1),int(3)]],[int(1),int(3),int(2)]))).
3410 :- assert_must_succeed((kernel_objects:union_generalized([[]],Res),Res=[])).
3411 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2)]],Res),
3412 kernel_objects:equal_object(Res,[_,_]))).
3413 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2),int(1)]],Res),
3414 kernel_objects:equal_object(Res,[_,_]))).
3415 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2),int(1)],[],[int(2)]],Res),
3416 kernel_objects:equal_object(Res,[_,_]))).
3417 :- assert_must_succeed((kernel_objects:union_generalized([[int(1)],[int(2)],X],Res),
3418 kernel_objects:equal_object(X,Res), X = [int(2),int(1),int(3)])).
3419 :- assert_must_succeed((kernel_objects:union_generalized([global_set('Name'),X,X,X],Res),
3420 kernel_objects:equal_object(global_set('Name'),Res), X = [fd(2,'Name'),fd(1,'Name')])).
3421 :- assert_must_succeed((kernel_objects:union_generalized([X,global_set('Name')],Res),
3422 kernel_objects:equal_object(global_set('Name'),Res), X = [fd(2,'Name'),fd(1,'Name')])).
3423 :- assert_must_fail((kernel_objects:union_generalized([[int(1)],[int(2)]],Res),(Res=[_];
3424 kernel_objects:equal_object(Res,[_,_,_|_])))).
3425 :- assert_must_fail((kernel_objects:union_generalized([[int(1)],[int(1)]],Res),(Res=[];
3426 kernel_objects:equal_object(Res,[_,_|_])))).
3427
3428 % treates the general_union AST node (union(.) in B syntax)
3429 union_generalized(S,Res) :- init_wait_flags(WF), union_generalized_wf(S,Res,WF), ground_wait_flags(WF).
3430
3431 :- block union_generalized_wf(-,-,?).
3432 union_generalized_wf(SetsOfSets,Res,WF) :- var(SetsOfSets), Res==[],!,
3433 expand_custom_set_to_list_wf(SetsOfSets,ESetsOfSets,_,union_generalized_wf,WF),
3434 all_empty_sets_wf(ESetsOfSets,WF).
3435 union_generalized_wf(SetsOfSets,Res,WF) :-
3436 ? union_generalized_wf2(SetsOfSets,Res,WF).
3437
3438 :- block union_generalized_wf2(-,?,?).
3439 union_generalized_wf2(SetsOfSets,Res,WF) :-
3440 custom_explicit_sets:union_generalized_explicit_set(SetsOfSets,ARes,WF),!,
3441 ? equal_object_optimized_wf(ARes,Res,union_generalized_avl_set,WF).
3442 union_generalized_wf2(SetsOfSets,Res,WF) :-
3443 expand_custom_set_to_list_wf(SetsOfSets,ESetsOfSets,_,union_generalized_wf2,WF),
3444 union_generalized2(ESetsOfSets,[],Res,WF).
3445
3446 :- block union_generalized2(-,?,?,?).
3447 union_generalized2([],S,Res,WF) :- equal_object_optimized_wf(S,Res,union_generalized2,WF).
3448 union_generalized2([H|T],UnionSoFar,Res,WF) :-
3449 Res==[],
3450 !,
3451 empty_set_wf(H,WF),
3452 empty_set_wf(UnionSoFar,WF),
3453 all_empty_sets_wf(T,WF).
3454 union_generalized2([H|T],UnionSoFar,Res,WF) :- union_wf(H,UnionSoFar,UnionSoFar2,WF),
3455 ((var(T);var(UnionSoFar2)),
3456 nonvar(Res),is_custom_explicit_set(Res,union_generalized2) % check important for Schneider2_Trees/NewSolver_v3_complex.mch and query CHOOSE_MODULES("bk-phi-H-2013", solution) (0.1 vs 0.9 secs)
3457 -> check_subset_of_wf(H,Res,WF)
3458 % this is only a very weak propagation; example, for union(v) = {4444} & v={{x},{y},{z}} we will instantiate v={{4444},...} and z=4444; see also test 1216
3459 ; true),
3460 union_generalized2(T,UnionSoFar2,Res,WF).
3461
3462 :- block all_empty_sets_wf(-,?).
3463 all_empty_sets_wf([],_).
3464 all_empty_sets_wf([H|T],WF) :- empty_set_wf(H,WF), all_empty_sets_wf(T,WF).
3465
3466 :- assert_must_succeed(exhaustive_kernel_check([commutative],intersection([int(3)],[int(2),int(1),int(3)],[int(3)]))).
3467 :- assert_must_succeed(exhaustive_kernel_check([commutative],intersection([int(4),int(3),int(2)],[int(2),int(1),int(3)],[int(2),int(3)]))).
3468 :- assert_must_succeed(exhaustive_kernel_check([commutative],intersection([int(4),int(3),int(2)],[],[]))).
3469 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],intersection([int(1),int(3)],[int(4),int(3),int(2)],[]))).
3470 :- assert_must_succeed((kernel_objects:intersection(Y,X,Res),X=global_set('Name'),
3471 kernel_objects:equal_object(Res,Y), Y =[fd(1,'Name')])).
3472 :- assert_must_succeed((kernel_objects:intersection([int(1)],[int(2)],Res),Res=[])).
3473 :- assert_must_succeed((kernel_objects:intersection([int(1)],[int(2)],[]))).
3474 :- assert_must_fail((kernel_objects:intersection([int(1),int(4),int(3)],[int(2),int(3)],[]))).
3475 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(1)],_))).
3476 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(1)],[int(2),int(1)]))).
3477 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(1)],[int(1),int(2)]))).
3478 :- assert_must_succeed((kernel_objects:intersection([int(1),int(2)],[int(2),int(3)],Res),
3479 kernel_objects:equal_object(Res,[int(2)]))).
3480 :- assert_must_succeed((kernel_objects:intersection([int(2)],[int(2)],Res),
3481 kernel_objects:equal_object(Res,[int(2)]))).
3482 :- assert_must_succeed((kernel_objects:intersection([int(2),int(3)],[int(3),int(4),int(2)],Res),
3483 kernel_objects:equal_object(Res,[int(2),int(3)]))).
3484 :- assert_must_fail((kernel_objects:intersection([int(1)],[int(2)],Res),(
3485 kernel_objects:equal_object(Res,[_|_])))).
3486 :- assert_must_fail((kernel_objects:intersection([int(1)],[int(1)],Res),(Res=[];
3487 kernel_objects:equal_object(Res,[_,_|_])))).
3488 :- assert_must_fail((kernel_objects:intersection([fd(1,'Name')],X,Res),X=global_set('Name'),
3489 kernel_objects:equal_object(Res,X))).
3490
3491
3492 intersection(S1,S2,Res) :- init_wait_flags(WF,[intersection]), intersection(S1,S2,Res,WF), ground_wait_flags(WF).
3493
3494 :- block intersection(-,-,-,?).
3495 intersection(Set1,Set2,Res,WF) :- (Set1==[] ; Set2==[]),!, empty_set_wf(Res,WF).
3496 intersection(Set1,Set2,Res,WF) :- quick_same_value(Set1,Set2),!,
3497 equal_object_wf(Res,Set1,inter0_equal,WF).
3498 intersection(Set1,Set2,Res,WF) :- Res==[],!,
3499 disjoint_sets(Set1,Set2,WF).
3500 intersection(Set1,Set2,Res,WF) :- % now we need to know at least a bit about both Set1 and Set2; at least given the current code below; TO DO: infer that {x} /\ s = {x} => x:s
3501 ? intersection0(Set1,Set2,Res,WF),
3502 propagate_intersection(Set1,Set2,Res,WF).
3503
3504 :- block propagate_intersection(?,?,-,?). % propagate constraint that result elements must be in both sets
3505 propagate_intersection(Set1,Set2,[H|T],WF) :-
3506 preference(data_validation_mode,false),
3507 !,
3508 ? propagate_intersection_aux(Set1,Set2,H,T,WF).
3509 propagate_intersection(Set1,Set2,avl_set(A),WF) :- !,
3510 ((unknown_set(Set1) ; unknown_set(Set2)) % otherwise intersection0 has already triggered below
3511 -> custom_explicit_sets:avl_approximate_size(A,Size),
3512 (Size<20
3513 -> expand_custom_set_to_list_wf(avl_set(A),ESet,_,propagate_intersection,WF)
3514 ; avl_min(A,Min), avl_max(A,Max), ESet=[Min,Max]
3515 ),
3516 propagate_intersection(Set1,Set2,ESet,WF)
3517 ; true).
3518 % other cases: Set1,2,3 could be interval closure with unknown bounds,...
3519 propagate_intersection(_,_,_,_).
3520
3521 :- block propagate_intersection_aux(-,-,-,?,?).
3522 propagate_intersection_aux(Set1,Set2,H,T,WF) :-
3523 ((unknown_set(Set1) ; unknown_set(Set2)) % otherwise intersection0 has already triggered below
3524 ? -> check_element_of_wf(H,Set1,WF), % should we do this lazily ?
3525 ? check_element_of_wf(H,Set2,WF),
3526 propagate_intersection(Set1,Set2,T,WF)
3527 ; true).
3528
3529 unknown_set(Set) :- var(Set),!.
3530 unknown_set([H|T]) :- (unknown_val(H) -> true ; unknown_set(T)).
3531 unknown_val(Val) :- var(Val),!.
3532 unknown_val(int(X)) :- var(X).
3533 unknown_val(string(X)) :- var(X).
3534 unknown_val(fd(X,_)) :- var(X).
3535 unknown_val((A,B)) :- (unknown_val(A) -> true ; unknown_val(B)).
3536 unknown_val([H|T]) :- (unknown_val(H) -> true ; unknown_set(T)).
3537
3538 :- block intersection0(-,?,?,?), intersection0(?,-,?,?).
3539 intersection0(Set1,Set2,Res,WF) :-
3540 (Set1==[] ; Set2==[]),!, empty_set_wf(Res,WF).
3541 intersection0(Set1,Set2,Res,WF) :- quick_same_value(Set1,Set2),!,
3542 ? equal_object_wf(Res,Set1,inter0_equal,WF).
3543 intersection0(Set1,Set2,Res,WF) :- Res==[],!,
3544 disjoint_sets(Set1,Set2,WF).
3545 intersection0([El1|T1],[El2|T2],Res,WF) :- T1==[],T2==[],
3546 !, % avoid doing intersection_with_interval_closure, especially for nonvar El1,El2 ; see test 2021
3547 equality_objects_wf(El1,El2,EqRes,WF),
3548 kernel_equality:empty_set_test_wf(Res,Empty,WF),
3549 bool_pred:negate(Empty,EqRes),
3550 intersection_pair(EqRes,El1,El2,Res,WF).
3551 intersection0(Set1,Set2,Res,WF) :-
3552 ? intersection_with_interval_closure(Set1,Set2,Inter),!, % avoid expanding intervals at all
3553 equal_object_wf(Inter,Res,intersection0,WF).
3554 intersection0(Set1,Set2,Res,WF) :-
3555 try_expand_and_convert_to_avl_unless_large_wf(Set1,ESet1,WF),
3556 try_expand_and_convert_to_avl_unless_large_wf(Set2,ESet2,WF),
3557 ? intersection1(ESet1,ESet2,Res,WF).
3558
3559 % treat {El1} /\ {El2} = Res
3560 :- block intersection_pair(-,?,?,?,?).
3561 intersection_pair(pred_false,_,_,_,_). % empty_set_test_wf above will set Res to empty_set
3562 ?intersection_pair(pred_true,El1,_El2,Res,WF) :- equal_object_wf(Res,[El1],intersection_pair,WF).
3563
3564 intersection1(Set1,Set2,Res,WF) :- nonvar(Set1),is_custom_explicit_set(Set1,intersection),
3565 intersection_of_explicit_set_wf(Set1,Set2,Inter,WF), !,
3566 equal_object_wf(Inter,Res,intersection1,WF).
3567 intersection1(Set1,Set2,Res,WF) :-
3568 (Res==[] ->
3569 disjoint_sets(Set1,Set2,WF)
3570 ;
3571 ? (swap_set(Set1,Set2) -> intersection2(Set2,Set1,Res,WF)
3572 ? ; intersection2(Set1,Set2,Res,WF))
3573 ).
3574
3575 swap_set(Set1,_Set2) :- var(Set1),!.
3576 swap_set(_Set1,Set2) :- var(Set2),!,fail.
3577 %swap_set(_Set1,Set2) :- is_infinite_explicit_set(Set2),!,fail.
3578 swap_set(avl_set(_),Set2) :- \+ functor(Set2,avl_set,2), %Set2 \= avl_set(_),
3579 Set2 \= [],
3580 \+ functor(Set2,closure,3), %Set2 \= closure(_,_,_),
3581 \+ functor(Set2,global_set,1). %Set2 \= global_set(_). % if it was a small closure, intersection_of_explicit_set should have triggered
3582 swap_set(closure(_P,_T,_B),Set2) :- ok_to_swap(Set2). % TO DO: for two closures: we could try and use the smallest one as first argument to intersection2
3583 swap_set(global_set(_GS),Set2) :- ok_to_swap(Set2).
3584
3585 ok_to_swap(global_set(GS)) :- !, \+ is_infinite_or_very_large_explicit_set(global_set(GS),1000000).
3586 ok_to_swap(closure(P,T,B)) :- !,\+ is_infinite_or_very_large_explicit_set(closure(P,T,B),1000000).
3587 ok_to_swap(_).
3588 % maybe also use is_efficient_custom_set as below ??
3589 % what about freetype ?
3590
3591
3592 intersection2(Set1,Set2,Res,WF) :-
3593 expand_custom_set_to_list_wf(Set1,ESet1,_,intersection2,WF),
3594 ? intersection3(ESet1,Set2,Res,WF).
3595 :- block intersection3(-,?,?,?).
3596 ?intersection3([],_,Res,WF) :- empty_set_wf(Res,WF).
3597 intersection3([H|T],Set,Res,WF) :-
3598 (Res==[]
3599 -> not_element_of_wf(H,Set,WF),intersection3(T,Set,Res,WF)
3600 ; membership_test_wf(Set,H,MemRes,WF),
3601 ? intersection4(MemRes,H,T,Set,Res,WF)
3602 ).
3603
3604 :- block intersection4(-,?,?, ?,?,?).
3605 intersection4(pred_true,H,T,Set,Result,WF) :-
3606 ? equal_object_wf([H|Res],Result,intersection4,WF),
3607 ? intersection3(T,Set,Res,WF).
3608 intersection4(pred_false,_H,T,Set,Res,WF) :-
3609 ? intersection3(T,Set,Res,WF).
3610
3611
3612 :- assert_must_succeed(exhaustive_kernel_check_wfdet(disjoint_sets([int(5)],[int(2),int(1),int(3)],WF),WF)).
3613 :- assert_must_succeed(exhaustive_kernel_check_wfdet(disjoint_sets([int(5)],[],WF),WF)).
3614 :- assert_must_succeed(exhaustive_kernel_check_wfdet(disjoint_sets([int(5),int(2)],[int(6),int(1),int(3)],WF),WF)).
3615
3616 disjoint_sets(S1,S2) :- init_wait_flags(WF,[disjoint_sets]),
3617 disjoint_sets(S1,S2,WF),
3618 ground_wait_flags(WF).
3619
3620 :- block disjoint_sets(-,?,?), disjoint_sets(?,-,?).
3621 disjoint_sets(S1,S2,WF) :-
3622 % TO DO: we could provide faster code for two avl sets / intervals; but probably caught in intersection code above?
3623 ((S1==[];S2==[]) -> true
3624 ; is_interval_closure_or_integerset(S1,Low1,Up1),
3625 nonvar(Low1), nonvar(Up1), % avoid applying it to e.g., {x} /\ 0..2000 = {} from test 1165
3626 is_interval_closure_or_integerset(S2,Low2,Up2), nonvar(Low2), nonvar(Up2) ->
3627 custom_explicit_sets:disjoint_intervals_with_inf(Low1,Up1,Low2,Up2)
3628 ; is_efficient_custom_set(S2) -> expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_1,WF),
3629 % TODO: treat is_infinite_or_symbolic_closure S1
3630 disjoint_sets2(ESet1,S2,WF)
3631 ; is_efficient_custom_set(S1) -> expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_2,WF),
3632 disjoint_sets2(ESet2,S1,WF)
3633 ; expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_3,WF),
3634 %expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_4,WF),
3635 ? disjoint_sets2(ESet1,S2,WF)
3636 ).
3637
3638 % TO DO: we could infer some constraints on the possible max sizes of the sets
3639 % for finite types (sum of size must be <= size of type)
3640 :- block disjoint_sets2(-,?,?).
3641 disjoint_sets2([],_,_WF).
3642 ?disjoint_sets2([H|T],S2,WF) :- not_element_of_wf(H,S2,WF), disjoint_sets2(T,S2,WF).
3643
3644 % NOT YET USED: not_disjoint_sets could be used for S /\ R /= {}
3645 :- assert_must_succeed(exhaustive_kernel_check_wfdet(not_disjoint_sets([int(3)],[int(2),int(1),int(3)],WF),WF)).
3646 :- block not_disjoint_sets(-,?,?), not_disjoint_sets(?,-,?).
3647 not_disjoint_sets(S1,S2,WF) :-
3648 ((S1==[];S2==[]) -> fail
3649 ; is_efficient_custom_set(S2) -> expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_1,WF),
3650 not_disjoint_sets2(ESet1,S2,WF)
3651 ; is_efficient_custom_set(S1) -> expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_2,WF),
3652 not_disjoint_sets2(ESet2,S1,WF)
3653 ; expand_custom_set_to_list_wf(S1,ESet1,_,disjoint_sets_3,WF),
3654 %expand_custom_set_to_list_wf(S2,ESet2,_,disjoint_sets_4,WF),
3655 not_disjoint_sets2(ESet1,S2,WF)
3656 ).
3657
3658 :- block not_disjoint_sets2(-,?,?).
3659 not_disjoint_sets2([],_,_WF).
3660 not_disjoint_sets2([H|T],S2,WF) :- membership_test_wf(S2,H,MemRes,WF), not_disjoint3(MemRes,T,S2,WF).
3661
3662 :- block not_disjoint3(-,?,?,?).
3663 not_disjoint3(pred_true,_,_,_).
3664 not_disjoint3(pred_false,T,S2,WF) :- not_disjoint_sets2(T,S2,WF).
3665
3666 :- assert_must_succeed(exhaustive_kernel_check_wfdet(intersection_generalized_wf([[int(3)],[int(2),int(1),int(3)]],[int(3)],unknown,WF),WF)).
3667 :- assert_must_succeed(exhaustive_kernel_check_wfdet(intersection_generalized_wf([[int(3),int(2)],[int(2),int(1),int(3)],[int(4),int(3)]],[int(3)],unknown,WF),WF)).
3668 :- assert_must_succeed((kernel_objects:intersection_generalized_wf(avl_set(node(avl_set(node(fd(1,'Name'),true,1,empty,node(fd(2,'Name'),true,0,empty,empty))),
3669 true,1,empty,node(avl_set(node(fd(2,'Name'),true,1,empty,node(fd(3,'Name'),true,0,empty,empty))),true,0,empty,empty))),
3670 avl_set(node(fd(2,'Name'),true,0,empty,empty)),unknown,_WF))).
3671 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(1)],[int(2)]],Res,unknown,_WF),Res=[])).
3672 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(1)],[int(2),int(1)]],Res,unknown,_WF),
3673 kernel_objects:equal_object(Res,[int(1)]))).
3674 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(1)],X,[int(2),int(3),int(1)]],Res,unknown,_WF),
3675 X = [int(2),int(1)],
3676 kernel_objects:equal_object(Res,[int(1)]))).
3677 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([X,X,[int(2),int(3),int(1)]],Res,unknown,_WF),
3678 X = [int(2),int(1)], kernel_objects:equal_object(Res,[int(1),int(2)]))).
3679 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([[int(2),int(1),int(3)],X,[int(1),int(2)],X],Res,unknown,_WF),
3680 kernel_objects:equal_object(X,Res), X = [int(2),int(1)])).
3681 :- assert_must_succeed((kernel_objects:intersection_generalized_wf([global_set('Name'),X],Res,unknown,_WF),
3682 kernel_objects:equal_object(X,Res), X = [fd(2,'Name'),fd(1,'Name')])).
3683 :- assert_must_fail((kernel_objects:intersection_generalized_wf([[int(1)],[int(2)]],Res,unknown,_WF),(
3684 kernel_objects:equal_object(Res,[_|_])))).
3685 :- assert_must_fail((kernel_objects:intersection_generalized_wf([[int(1)],[int(1)]],Res,unknown,_WF),(Res=[];
3686 kernel_objects:equal_object(Res,[_,_|_])))).
3687 :- assert_must_abort_wf(kernel_objects:intersection_generalized_wf([],_R,unknown,WF),WF).
3688
3689 % code for general_intersection
3690 :- block intersection_generalized_wf(-,?,?,?).
3691 intersection_generalized_wf(SetsOfSets,Res,Span,WF) :-
3692 expand_custom_set_to_list_wf(SetsOfSets,ESetsOfSets,_,intersection_generalized_wf,WF),
3693 intersection_generalized2(ESetsOfSets,Res,Span,WF).
3694
3695 intersection_generalized2([],Res,Span,WF) :- /* Atelier-B manual requires argument to inter to be non-empty */
3696 add_wd_error_set_result('inter applied to empty set','',Res,[],Span,WF).
3697 intersection_generalized2([H|T],Res,_Span,WF) :- intersection_generalized3(T,H,Res,WF).
3698 :- block intersection_generalized3(-,?,?,?).
3699 intersection_generalized3([],SoFar,Res,WF) :- equal_object_optimized_wf(SoFar,Res,intersection_generalized3,WF).
3700 intersection_generalized3([H|T],InterSoFar,Res,WF) :-
3701 intersection(H,InterSoFar,InterSoFar2,WF),
3702 intersection_generalized3(T,InterSoFar2,Res,WF).
3703
3704 :- assert_must_succeed(exhaustive_kernel_check(difference_set([int(3),int(2)],[int(2),int(1),int(3)],[]))).
3705 :- assert_must_succeed(exhaustive_kernel_check(difference_set([int(3),int(2)],[int(2),int(1),int(4)],[int(3)]))).
3706 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[int(1),int(2)]],[]),
3707 kernel_objects:equal_object(SSS,[[int(2),int(1)]]))).
3708 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[int(1),int(2)]],R), kernel_objects:equal_object(R,[]),
3709 kernel_objects:equal_object(SSS,[[int(2),int(1)]]))).
3710 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[fd(1,'Name'),fd(2,'Name')]],R),
3711 kernel_objects:equal_object(R,[]),
3712 kernel_objects:equal_object(SSS,[[fd(2,'Name'),fd(1,'Name')]]))).
3713 :- assert_must_succeed((kernel_objects:difference_set(SSS,[[int(1),int(2)]],[]),
3714 kernel_objects:equal_object(SSS,[[int(1),int(2)]]))).
3715 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[int(1)],_))).
3716 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[int(2)],_))).
3717 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[int(2)],[int(1)]))).
3718 :- assert_must_succeed((kernel_objects:difference_set([int(1),int(2)],[],[int(2),int(1)]))).
3719 :- assert_must_succeed((kernel_objects:difference_set([],[int(1),int(2)],[]))).
3720 :- assert_must_succeed((kernel_objects:difference_set(Y,X,Res),X=global_set('Name'),
3721 kernel_objects:equal_object(Res,[]), Y =[fd(1,'Name')])).
3722 :- assert_must_succeed((kernel_objects:difference_set(X,Y,Res),X=global_set('Name'),
3723 kernel_objects:equal_object(Res,[fd(3,'Name'),fd(1,'Name')]), Y =[fd(2,'Name')])).
3724 :- assert_must_fail((kernel_objects:difference_set(X,Y,Res),X=global_set('Name'),
3725 kernel_objects:equal_object(Res,[]), Y =[fd(1,'Name'),fd(2,'Name')])).
3726 :- assert_must_fail((kernel_objects:difference_set(Y,X,Res),X=global_set('Name'),
3727 kernel_objects:equal_object(Res,Y), Y =[fd(1,'Name')])).
3728
3729 % deals with set_subtraction AST node
3730 difference_set(Set1,Set2,Res) :- init_wait_flags(WF),
3731 difference_set_wf(Set1,Set2,Res,WF),
3732 ground_wait_flags(WF).
3733
3734 :- block difference_set_wf(-,-,?,?).
3735 difference_set_wf(Set1,_,Res,WF) :- Set1==[],!,empty_set_wf(Res,WF).
3736 difference_set_wf(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,difference_set_wf,WF).
3737 ?difference_set_wf(Set1,Set2,Res,WF) :- difference_set1(Set1,Set2,Res,WF).
3738
3739
3740 :- block difference_set1(?,-,-,?), difference_set1(-,?,-,?).
3741 difference_set1(Set1,Set2,Res,WF) :-
3742 nonvar(Set1),is_custom_explicit_set(Set1,difference_set),
3743 difference_of_explicit_set_wf(Set1,Set2,Diff,WF), !,
3744 ? equal_object_wf(Diff,Res,difference_set1_1,WF).
3745 ?difference_set1(Set1,Set2,Res,WF) :- Set2==[],!,equal_object_wf(Set1,Res,difference_set1_2,WF).
3746 ?difference_set1(Set1,Set2,Res,WF) :- Res==[],!, check_subset_of_wf(Set1,Set2,WF).
3747 difference_set1(Set1,Set2,Res,WF) :-
3748 expand_custom_set_to_list_wf(Set1,ESet1,_,difference_set1,WF),
3749 ? compute_diff(ESet1,Set2,Res,WF),
3750 ? propagate_into2(Res,ESet1,Set2,WF).
3751
3752 :- block compute_diff(-,?,?,?).
3753 ?compute_diff([],_Set2,Res,WF) :- empty_set_wf(Res,WF).
3754 compute_diff([H|T],Set2,Res,WF) :-
3755 ? membership_test_wf(Set2,H,MemRes,WF),compute_diff2(MemRes,H,T,Set2,Res,WF).
3756
3757 :- block compute_diff2(-,?,?,?,?,?).
3758 ?compute_diff2(pred_true,_H,T,Set2,Res,WF) :- compute_diff(T,Set2,Res,WF).
3759 ?compute_diff2(pred_false,H,T,Set2,Res,WF) :- equal_object_wf([H|R2],Res,compute_diff2,WF),
3760 ? compute_diff(T,Set2,R2,WF).
3761
3762 % propagate all elements from one set into another one; do not use for computation; may skip elements ...
3763 /* this version not used at the moment:
3764 :- block propagate_into(-,?,?).
3765 propagate_into(_,Set2,_WF) :- nonvar(Set2),
3766 is_custom_explicit_set(Set2,propagate_into),!. % second set already fully known
3767 propagate_into([],_,_WF) :- !.
3768 propagate_into([H|T],Set,WF) :- !,check_element_of_wf(H,Set,WF), propagate_into(T,Set,WF).
3769 propagate_into(Set1,Set2,WF) :- is_custom_explicit_set(Set1,propagate_into),!,
3770 (is_infinite_explicit_set(Set1) -> true ;
3771 expand_custom_set_to_list(Set1,ESet1), propagate_into(ESet1,Set2,WF)). */
3772
3773 :- block propagate_into2(-,?,?,?).
3774 propagate_into2(_,Set2,_NegSet,_WF) :- nonvar(Set2),
3775 is_custom_explicit_set(Set2,propagate_into),!. % second set already fully known
3776 propagate_into2([],_,_,_WF) :- !.
3777 propagate_into2([H|T],PosSet,NegSet,WF) :- !,
3778 ? check_element_of_wf(H,PosSet,WF),
3779 ? not_element_of_wf(H,NegSet,WF),propagate_into2(T,PosSet,NegSet,WF).
3780 propagate_into2(Set1,PosSet,NegSet,WF) :- is_custom_explicit_set(Set1,propagate_into),!,
3781 (is_infinite_explicit_set(Set1) -> true ;
3782 ? expand_custom_set_to_list_wf(Set1,ESet1,_,propagate_into2,WF), propagate_into2(ESet1,PosSet,NegSet,WF)).
3783
3784 :- assert_must_succeed(exhaustive_kernel_check_wf(in_difference_set_wf(int(33),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3785 :- block in_difference_set_wf(-,-,-,?).
3786 in_difference_set_wf(A,X,Y,WF) :-
3787 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3788 % symbolic treatment would also make sense when A is nonvar and X var to force A to be in X ?!
3789 !,
3790 ? check_element_of_wf(A,X,WF), not_element_of_wf(A,Y,WF).
3791 in_difference_set_wf(A,X,Y,WF) :-
3792 difference_set_wf(X,Y,Diff,WF),
3793 check_element_of_wf(A,Diff,WF).
3794
3795 treat_arg_symbolically(X) :- var(X),!.
3796 treat_arg_symbolically(global_set(_)).
3797 treat_arg_symbolically(freetype(_)).
3798 treat_arg_symbolically(closure(P,T,B)) :- \+ small_interval(P,T,B).
3799
3800 small_interval(P,T,B) :- is_interval_closure(P,T,B,Low,Up),
3801 integer(Low), integer(Up),
3802 Up-Low < 500. % Magic Constant; TO DO: determine good value
3803
3804
3805 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_difference_set_wf(int(2),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3806 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_difference_set_wf(int(111),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3807 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_difference_set_wf(int(1),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3808
3809 :- block not_in_difference_set_wf(-,-,-,?).
3810 not_in_difference_set_wf(A,X,Y,WF) :-
3811 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3812 !,
3813 % A : (X-Y) <=> A:X & not(A:Y)
3814 % A /: (X-Y) <=> A/: X or A:Y
3815 membership_test_wf(X,A,AX_Res,WF),
3816 (AX_Res==pred_false -> true
3817 ; bool_pred:negate(AX_Res,NotAX_Res),
3818 b_interpreter_check:disjoin(NotAX_Res,AY_Res,pred_true,priority(16384),priority(16384),WF), % better: uese a version that does not do a case split ?! or use last wait flag ?
3819 membership_test_wf(Y,A,AY_Res,WF)
3820 ).
3821 not_in_difference_set_wf(A,X,Y,WF) :-
3822 difference_set_wf(X,Y,Diff,WF),
3823 not_element_of_wf(A,Diff,WF).
3824
3825
3826 :- assert_must_succeed(exhaustive_kernel_check_wf(in_intersection_set_wf(int(2),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3827
3828 :- block in_intersection_set_wf(-,-,-,?).
3829 in_intersection_set_wf(A,X,Y,WF) :-
3830 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y)
3831 ; preference(convert_comprehension_sets_into_closures,true)),
3832 (preference(data_validation_mode,true) -> nonvar(X) ; true),
3833 % otherwise we may change enumeration order and enumerate with Y first;
3834 % see private_examples/ClearSy/2019_May/perf_3264/rule_186.mch (but also test 1976);
3835 % we could check if A is ground
3836 !,
3837 Y \== [], % avoid setting up check_element_of for X then
3838 ? check_element_of_wf(A,X,WF), check_element_of_wf(A,Y,WF).
3839 in_intersection_set_wf(A,X,Y,WF) :-
3840 intersection(X,Y,Inter,WF),
3841 check_element_of_wf(A,Inter,WF).
3842
3843 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_intersection_set_wf(int(3),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3844 :- block not_in_intersection_set_wf(-,-,-,?).
3845 not_in_intersection_set_wf(_A,_X,Y,_WF) :- Y == [], !. % intersection will be empty; avoid analysing X
3846 not_in_intersection_set_wf(A,X,Y,WF) :-
3847 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3848 !,
3849 % A : (X /\ Y) <=> A:X & A:Y
3850 % A /: (X /\ Y) <=> A/:X or A/:Y
3851 membership_test_wf(X,A,AX_Res,WF),
3852 (AX_Res==pred_false -> true
3853 ; bool_pred:negate(AX_Res,NotAX_Res), bool_pred:negate(AY_Res,NotAY_Res),
3854 b_interpreter_check:disjoin(NotAX_Res,NotAY_Res,pred_true,priority(16384),priority(16384),WF), % better: uese a version that does not do a case split ?! or use last wait flag ?
3855 membership_test_wf(Y,A,AY_Res,WF)
3856 ).
3857 not_in_intersection_set_wf(A,X,Y,WF) :-
3858 intersection(X,Y,Inter,WF),
3859 not_element_of_wf(A,Inter,WF).
3860
3861 :- assert_must_succeed(exhaustive_kernel_check_wf(in_union_set_wf(int(2),[int(33),int(2)],[int(2),int(1),int(3)],WF),WF)).
3862 :- assert_must_succeed(exhaustive_kernel_check_wf(in_union_set_wf(int(33),[int(32),int(2)],[int(2),int(1),int(33)],WF),WF)).
3863
3864 :- block in_union_set_wf(-,-,-,?).
3865 in_union_set_wf(A,X,Y,WF) :-
3866 (treat_arg_symbolically(X) ; treat_arg_symbolically(Y) ; preference(convert_comprehension_sets_into_closures,true)),
3867 % symbolic treatment would also make sense when A is nonvar and X var to force A to be in X ?!
3868 !,
3869 membership_test_wf(X,A,AX_Res,WF),
3870 (AX_Res==pred_true -> true
3871 ; b_interpreter_check:disjoin(AX_Res,AY_Res,pred_true,priority(16384),priority(16384),WF), % better: use a version that does not do a case split ?! or use last wait flag ?
3872 membership_test_wf(Y,A,AY_Res,WF)
3873 ).
3874 in_union_set_wf(A,X,Y,WF) :-
3875 union_wf(X,Y,Union,WF),
3876 check_element_of_wf(A,Union,WF).
3877
3878 :- assert_must_succeed(exhaustive_kernel_check_wf(not_in_union_set_wf(int(3),[int(32),int(2)],[int(2),int(1),int(33)],WF),WF)).
3879
3880 :- block not_in_union_set_wf(-,-,-,?).
3881 not_in_union_set_wf(A,X,Y,WF) :-
3882 not_element_of_wf(A,X,WF),
3883 not_element_of_wf(A,Y,WF).
3884
3885 % ---------------------
3886
3887
3888 strict_subset_of(X,Y) :-
3889 init_wait_flags(WF,[strict_subset_of]),
3890 strict_subset_of_wf(X,Y,WF),
3891 ground_wait_flags(WF).
3892
3893 :- assert_must_succeed(exhaustive_kernel_check(strict_subset_of_wf([int(3),int(2)],[int(2),int(1),int(3)],_))).
3894 :- assert_must_succeed(exhaustive_kernel_check(strict_subset_of_wf([],[int(2),int(1),int(3)],_))).
3895 :- assert_must_succeed(exhaustive_kernel_check(strict_subset_of_wf([],[ [] ],_))).
3896 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([int(3),int(2),int(1)],[int(2),int(1),int(3)],_))).
3897 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([int(1),int(4)],[int(2),int(1),int(3)],_))).
3898 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([[]],[],_))).
3899 :- assert_must_succeed(exhaustive_kernel_fail_check(strict_subset_of_wf([],[],_))).
3900 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [int(1)], X=[int(2),int(1)])).
3901 :- assert_must_succeed((kernel_objects:strict_subset_of(Y,X), Y = [int(1)], X=[int(2),int(1)])).
3902 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [], X=[int(2),int(1)])).
3903 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [[int(1),int(2)]], X=[[int(2)],[int(2),int(1)]])).
3904 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [fd(1,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
3905 :- assert_must_succeed((kernel_objects:strict_subset_of_wf(Y,X,_WF), Y = [fd(3,'Name'),fd(2,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
3906 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
3907 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [fd(1,'Name'),fd(3,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
3908 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(1)], X=[int(2),int(1)])).
3909 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(1),int(2)], X=[int(2),int(1)])).
3910 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(2)], X=[int(2)])).
3911 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [int(2)], X=[int(1)])).
3912 :- assert_must_fail((kernel_objects:strict_subset_of_wf(X,Y,_WF), Y = [], X=[int(1)])).
3913
3914
3915 :- use_module(chrsrc(chr_set_membership),[chr_subset_strict/2, chr_not_subset_strict/2]).
3916 :- use_module(chrsrc(chr_integer_inequality),[chr_in_interval/4]).
3917
3918 strict_subset_of_wf(Set1,Set2,WF) :-
3919 (preference(use_chr_solver,true) -> chr_subset_strict(Set1,Set2)
3920 ; Set1 \== Set2), % relevant for test 1326
3921 ? strict_subset_of_wf_aux(Set1,Set2,WF).
3922
3923 %:- block strict_subset_of_wf(-,-,?).
3924 strict_subset_of_wf_aux(Set1,Set2,WF) :- Set1==[],!,not_empty_set_wf(Set2,WF).
3925 %strict_subset_of_wf_aux(Set1,Set2,WF) :- var(Set2),nonvar(Set1), print(subs(Set1,Set2)),nl,fail.
3926 strict_subset_of_wf_aux(Set1,Set2,WF) :- nonvar(Set2), singleton_set(Set2,_),!, empty_set_wf(Set1,WF).
3927 strict_subset_of_wf_aux(Set1,Set2,WF) :-
3928 ? not_empty_set_wf(Set2,WF),
3929 get_cardinality_powset_wait_flag(Set2,strict_subset_of_wf,WF,_,LWF),
3930 % we could subtract 1 from priority !? (get_cardinality_pow1set_wait_flag)
3931 ? when(((nonvar(LWF),(nonvar(Set1);ground(Set2))) ; (nonvar(Set1),nonvar(Set2)) ),
3932 strict_subset_of_aux_block(Set1,Set2,WF,LWF)).
3933
3934 strict_subset_of_aux_block(Set1,_Set2,_WF,_LWF) :-
3935 Set1==[],
3936 !. % we have already checked that Set2 is not empty
3937 strict_subset_of_aux_block(Set1,Set2,WF,_LWF) :-
3938 nonvar(Set2), is_definitely_maximal_set(Set2),
3939 !,
3940 not_equal_object_wf(Set1,Set2,WF).
3941 strict_subset_of_aux_block(Set1,Set2,WF,_LWF) :- nonvar(Set2), singleton_set(Set2,_),!, empty_set_wf(Set1,WF).
3942 strict_subset_of_aux_block(Set1,Set2,_WF,_LWF) :-
3943 both_global_sets(Set1,Set2,G1,G2),
3944 !, %(print(check_strict_subset_of_global_sets(G1,G2)),nl,
3945 ? check_strict_subset_of_global_sets(G1,G2).
3946 strict_subset_of_aux_block(Set1,Set2,WF,LWF) :-
3947 var(Set1), nonvar(Set2), Set2=avl_set(_),
3948 check_card_waitflag_less(LWF,4097), % if the number is too big strict_subset_of0 has better chance of working ?!
3949 % without avl_set check test 1003 leads to time out for plavis-TransData_SP_13.prob, with
3950 % memp : seq(STRING) & dom(memp) <<: ( mdp + 1 .. ( mdp + 43 ) )
3951 !,
3952 %non_free(Set1), % as we used to force order, now we use equal_object_wf in gen_strict_subsets and no longer need non_free checking
3953 expand_custom_set_to_list_wf(Set2,ESet2,_,strict_subset_of_wf,WF),
3954 gen_strict_subsets(Set1,ESet2,WF).
3955 strict_subset_of_aux_block(Set1,Set2,WF,LWF) :-
3956 ? strict_subset_of0(Set1,Set2,WF,LWF).
3957 % TO DO (26.10.2014): test 1270 now passes thanks to maximal set check above
3958 % but we should need a better way of ensuring that something like {ssu|ssu<<:POW(elements)} is efficiently computed
3959 % (which it no longer is once the unbound_variable check had been fixed)
3960 % we could also just generally use Set1 <: Set2 & Set1 /= Set2
3961
3962 check_card_waitflag_less(float(Nr),Limit) :- number(Nr), Nr<Limit.
3963
3964 % avoid generating different ordering of the same subset ([1,2] and [2,1] for example), useful for test 642
3965 % Note: remove_element_wf in strict_subset_of2 will create different orders
3966 % for sequence domains gen_strict_subsets uses just the wrong order (deciding to remove 1 first);
3967 % cf test 1003 where not including 1 in domain is bad: memp : seq(STRING) & dom(memp) <<: ( mdp + 1 .. ( mdp + 43 ) )
3968 gen_strict_subsets(T,[H2|T2],WF) :-
3969 not_element_of_wf(H2,T,WF),
3970 gen_subsets(T,T2,WF).
3971 gen_strict_subsets(SubSet,[H2|T2],WF) :-
3972 equal_object_wf([H2|T],SubSet,gen_strict_subsets,WF),
3973 gen_strict_subsets(T,T2,WF).
3974
3975
3976 %:- block strict_subset_of0(-,?,?,?). % required to wait: we know Set2 must be non-empty, but Set1 could be an avl-tree or closure
3977 % TO DO: deal with infinite Set1
3978 strict_subset_of0(Set1,Set2,WF,LWF) :-
3979 expand_custom_set_to_list_wf(Set1,ESet1,_,strict_subset_of0,WF),
3980 (ESet1==[] -> true %not_empty_set(Set2) already checked above
3981 ? ; is_infinite_explicit_set(Set2) ->
3982 % Set1 is expanded to a list ESet1 and thus finite: it is sufficient to check subset relation
3983 check_subset_of_wf(ESet1,Set2,WF)
3984 ; try_expand_custom_set_wf(Set2,ESet2,strict_subset_of0,WF),
3985 %%try_prop_card_lt(ESet1,ESet2), try_prop_card_gt(ESet2,ESet1),
3986 ? strict_subset_of2(ESet1,[],ESet2,WF,LWF)
3987 ).
3988
3989 :- block strict_subset_of2(-,?,?,?,-).
3990 %strict_subset_of2(S,SoFar,Set2,WF) :- print(strict_subset_of2(S,SoFar,Set2,WF)),nl,fail.
3991 ?strict_subset_of2([],_,RemS,WF,_LWF) :- not_empty_set_wf(RemS,WF). /* we know it must be explicit set */
3992 strict_subset_of2([H|T],SoFar,Set2,WF,LWF) :- var(Set2),!,
3993 Set2 = [H|Set2R],
3994 add_new_element_wf(H,SoFar,SoFar2,WF), %was SoFar2 = [H|SoFar],
3995 ? strict_subset_of2(T,SoFar2,Set2R,WF,LWF).
3996 strict_subset_of2([H|T],SoFar,Set2,WF,LWF) :-
3997 % when_sufficiently_for_member(H,Set2,WF,
3998 remove_element_wf(H,Set2,RS2,WF),
3999 ? not_empty_set_wf(RS2,WF),
4000 not_element_of_wf(H,SoFar,WF), /* consistent((H,SoFar)), necessary? */
4001 ? when((nonvar(T) ; (ground(LWF),ground(RS2))),
4002 (add_new_element_wf(H,SoFar,SoFar2,WF), %SoFar2 = [H|SoFar],
4003 strict_subset_of2(T,SoFar2,RS2,WF,LWF) )).
4004
4005
4006
4007
4008 :- assert_must_succeed(exhaustive_kernel_check(partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ],_))).
4009 :- assert_must_succeed(exhaustive_kernel_check(partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)] ],_))).
4010 :- assert_must_succeed(exhaustive_kernel_check(partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5)],[int(1)] ],_))).
4011 :- assert_must_succeed(exhaustive_kernel_fail_check(partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)], [int(3)] ],_))).
4012 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ], _))).
4013 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2)],[ [int(2)], [int(1)], [] ], _))).
4014 :- assert_must_fail((kernel_objects:partition_wf([int(1),int(2)],[ [int(2)], [int(1),int(2)] ], _))).
4015 :- assert_must_fail((kernel_objects:partition_wf([int(1),int(3)],[ [int(1)], [int(2)] ], _))).
4016 :- assert_must_fail((kernel_objects:partition_wf([int(1),int(2),int(3)],[ [int(1)], [int(2)] ], _))).
4017 :- assert_must_succeed((kernel_objects:partition_wf([int(1)],[S1,S2],_WF), S1=[H|T], S2==[],T==[],H==int(1))).
4018 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2)],[S1,S2],_WF), S1=[H|T], S2=[int(1)],(preferences:preference(use_clpfd_solver,true) -> T==[],H==int(2) ; T=[],H=int(2)))).
4019 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2),int(3)],[S1,S2,S3],_WF), S1=[H2|T], S3=[int(3)],T=[H1|TT],H2=int(2),TT==[],S2==[],H1==int(1))).
4020 :- assert_must_succeed((kernel_objects:partition_wf([int(1),int(2),int(3)],[[int(1)],X,[int(2)]],_WF),
4021 X==[int(3)])).
4022
4023 :- use_module(bsets_clp,[disjoint_union_generalized_wf/3]).
4024 :- use_module(kernel_tools,[ground_value/1]).
4025 :- block partition_wf(?,-,?).
4026 partition_wf(Set,ListOfSets,WF) :-
4027 ? partition_disj_union_wf(Set,ListOfSets,WF),
4028 all_disjoint(ListOfSets,WF).
4029
4030 % just check that the disjoint union of all sets is equal to Set
4031 partition_disj_union_wf(Set,ListOfSets,WF) :-
4032 ground_value(Set),find_non_ground_set(ListOfSets,NGS,Rest),!,
4033 disjoint_union_generalized_wf(Rest,RestSet,WF),
4034 check_subset_of_wf(RestSet,Set,WF), % otherwise this is not a partition of Set
4035 difference_set(Set,RestSet,NGS).
4036 partition_disj_union_wf(Set,ListOfSets,WF) :-
4037 ? disjoint_union_generalized_wf(ListOfSets,Set,WF).
4038
4039 :- assert_must_succeed((kernel_objects:find_non_ground_set([int(1),int(2),A,int(5)],B,C), B==A,C==[int(1),int(2),int(5)])).
4040 find_non_ground_set([H|T],NG,Rest) :-
4041 (ground_value(H) -> Rest=[H|TR], find_non_ground_set(T,NG,TR)
4042 ; ground_value(T),NG=H, Rest=T).
4043
4044 :- block all_disjoint(-,?).
4045 % check if a list of sets is all disjoint (Note: this is not a set of sets)
4046 all_disjoint([],_WF) :- !.
4047 all_disjoint([H|T],WF) :- !,
4048 all_disjoint_with(T,H,WF),
4049 all_disjoint(T,WF).
4050 all_disjoint(S,WF) :- add_internal_error('Not a list for partition:',all_disjoint(S,WF)),fail.
4051
4052 :- block all_disjoint_with(-,?,?).
4053 all_disjoint_with([],_,_WF).
4054 all_disjoint_with([H|T],Set1,WF) :- disjoint_sets(Set1,H,WF), all_disjoint_with(T,Set1,WF).
4055
4056
4057 % a utility to check for duplicates in set lists and enter debugger
4058 %:- block check_set_for_repetitions(-,?).
4059 %check_set_for_repetitions([],_) :- !.
4060 %check_set_for_repetitions([H|T],Acc) :- !,
4061 % when(ground(H),(member(H,Acc) -> tools:print_bt_message(duplicate(H,Acc)),trace
4062 % ; check_set_for_repetitions(T,[H|Acc]))).
4063 %check_set_for_repetitions(_,_).
4064
4065 :- assert_must_succeed(exhaustive_kernel_fail_check(not_partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ],_))).
4066 :- assert_must_succeed(exhaustive_kernel_fail_check(not_partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)] ],_))).
4067 :- assert_must_succeed(exhaustive_kernel_fail_check(not_partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5)],[int(1)] ],_))).
4068 :- assert_must_succeed(exhaustive_kernel_check(not_partition_wf([int(1),int(2),int(5)],[ [int(2)], [int(5),int(1)], [int(3)] ],_))).
4069 :- assert_must_fail((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(2)], [int(1)] ], _))).
4070 :- assert_must_fail((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(2)], [int(1)], [] ], _))).
4071 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(2)], [int(1),int(2)] ], _))).
4072 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(3)],[ [int(1)], [int(2)] ], _))).
4073 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(2),int(3)],[ [int(1)], [int(2)] ], _))).
4074 :- assert_must_succeed((kernel_objects:not_partition_wf([int(1),int(2)],[ [int(1),int(2)], [int(1),int(2)] ], _))).
4075
4076 not_partition_wf(FullSet,ListOfSets,WF) :-
4077 test_partition_wf(FullSet,ListOfSets,pred_false,WF).
4078
4079
4080 :- use_module(b_interpreter_check,[imply_true/2]). % TODO: move to another module
4081 :- block test_partition_wf(?,-,?,?).
4082 test_partition_wf(FullSet,ListOfSets,PredRes,WF) :-
4083 bool_pred:negate(PredRes,NotPredRes),
4084 propagate_partition_true(FullSet,ListOfSets,PredRes,WF),
4085 ? test_partition_wf2(ListOfSets,[],FullSet,PredRes,NotPredRes,WF).
4086
4087 :- block propagate_partition_true(?,?,-,?).
4088 propagate_partition_true(FullSet,ListOfSets,pred_true,WF) :-
4089 % ensure we propagate more info; required for tests 1059, 1060
4090 partition_disj_union_wf(FullSet,ListOfSets,WF).
4091 propagate_partition_true(_,_,pred_false,_).
4092
4093 :- block test_partition_wf2(-,?,?, ?,?,?).
4094 %test_partition_wf2(Sets,SoFar,_,Pred,_,_) :- print_term_summary(test_partition_wf2(Sets,SoFar,Pred)),nl,fail.
4095 ?test_partition_wf2([],ElementsSoFar,FullSet,PredRes,_,WF) :- !, equality_objects_wf(ElementsSoFar,FullSet,PredRes,WF).
4096 test_partition_wf2([Set1|Rest],ElementsSoFar,FullSet,PredRes,NotPredRes,WF) :- !,
4097 expand_custom_set_to_list_wf(Set1,ESet1,_,test_partition_wf2,WF), % TODO: requires finite set; choose instantiated sets first
4098 ? test_partition_wf3(ESet1,ElementsSoFar,ElementsSoFar,Rest,FullSet,PredRes,NotPredRes,WF).
4099 test_partition_wf2(A,E,FS,PR,NPR,WF) :-
4100 add_internal_error('Not a list for partition:',test_partition_wf2(A,E,FS,PR,NPR,WF)),fail.
4101
4102 :- block test_partition_wf3(-,?,?,?, ?,?,?,?).
4103 test_partition_wf3([],_,NewElementsSoFar,OtherSets,FullSet,PredRes,NPR,WF) :-
4104 ? test_partition_wf2(OtherSets,NewElementsSoFar,FullSet,PredRes,NPR,WF). % finished treating this set
4105 test_partition_wf3([H|T],ElementsSoFar,NewElementsSoFar,OtherSets,FullSet,PredRes,NotPredRes,WF) :-
4106 imply_true(MemRes,NotPredRes), % if not disjoint (MemRes=pred_true) then we do not have a partition
4107 membership_test_wf(ElementsSoFar,H,MemRes,WF),
4108 ? test_partition_wf4(MemRes,H,T,ElementsSoFar,NewElementsSoFar,OtherSets,FullSet,PredRes,NotPredRes,WF).
4109
4110 :- block test_partition_wf4(-,?,?,?,?, ?,?,?,?,?).
4111 test_partition_wf4(pred_true,_,_,_,_,_,_,pred_false,_,_). % Not disjoint
4112 test_partition_wf4(pred_false,H,T,ElementsSoFar,NewElementsSoFar,OtherSets,FullSet,PredRes,NotPredRes,WF) :-
4113 add_element_wf(H,NewElementsSoFar,NewElementsSoFar2,WF), % we could also already check whether H in FullSet or not
4114 %(PredRes==pred_true -> check_element_of_wf(H,FullSet,WF) ; true),
4115 ? test_partition_wf3(T,ElementsSoFar,NewElementsSoFar2,OtherSets,FullSet,PredRes,NotPredRes,WF).
4116
4117
4118
4119 :- assert_must_succeed(exhaustive_kernel_succeed_check(check_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1),int(3)]))).
4120 :- assert_must_succeed(exhaustive_kernel_succeed_check(check_subset_of([int(1),int(2),int(5)],[int(2),int(5),int(1)]))).
4121 :- assert_must_succeed(exhaustive_kernel_fail_check(check_subset_of([int(1),int(3),int(5)],[int(2),int(5),int(1)]))).
4122 :- assert_must_succeed((kernel_objects:power_set(global_set('Name'),PS),kernel_objects:check_subset_of(X,PS),
4123 kernel_objects:equal_object(X,[[fd(2,'Name'),fd(1,'Name')]]))).
4124 :- assert_must_succeed(findall(X,kernel_objects:check_subset_of(X,[[int(1),int(2)],[]]),[_1,_2,_3,_4])).
4125 :- assert_must_succeed((kernel_objects:check_subset_of(X,[[int(1),int(2)],[]]),
4126 nonvar(X),
4127 kernel_objects:equal_object(X,[[int(2),int(1)]]))).
4128 :- assert_must_succeed((kernel_objects:check_subset_of_wf(Y,X,_WF), Y = [fd(1,'Name')],
4129 nonvar(X),X=[H|T], var(T), H==fd(1,'Name'), X=Y)).
4130 :- assert_must_succeed((kernel_objects:check_subset_of(Y,X), Y = [fd(1,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4131 :- assert_must_succeed((kernel_objects:check_subset_of(Y,X), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4132 :- assert_must_succeed((kernel_objects:check_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4133 :- assert_must_succeed((kernel_objects:sample_closure(C),kernel_objects:check_subset_of(C,global_set('NAT')))).
4134 :- assert_must_succeed((kernel_objects:check_subset_of(global_set('NAT'),global_set('NAT')))).
4135 :- assert_must_succeed((kernel_objects:check_subset_of(global_set('NAT'),global_set('NATURAL')))).
4136 :- assert_must_fail((kernel_objects:check_subset_of(global_set('NAT'),global_set('NATURAL1')))).
4137 :- assert_must_fail((kernel_objects:check_subset_of(global_set('NAT'),global_set('NAT1')))).
4138 :- assert_must_fail((kernel_objects:check_subset_of(X,Y), Y = [fd(1,'Name')], kernel_objects:equal_object(X,global_set('Name')))).
4139 /* TO DO: add special treatment for closures and type checks !! */
4140
4141 check_subset_of(Set1,Set2) :- init_wait_flags(WF),
4142 check_subset_of_wf(Set1,Set2,WF),
4143 ground_wait_flags(WF).
4144
4145 check_finite_subset_of_wf(Set1,Set2,WF) :-
4146 check_subset_of_wf(Set1,Set2,WF),
4147 is_finite_set_wf(Set1,WF).
4148
4149 :- block check_subset_of_wf(-,-,?).
4150 check_subset_of_wf(Set1,Set2,WF) :-
4151 (both_global_sets(Set1,Set2,G1,G2)
4152 -> check_subset_of_global_sets(G1,G2)
4153 ? ; check_subset_of0(Set1,Set2,WF)
4154 ).
4155
4156 both_global_sets(S1,S2,G1,G2) :- nonvar(S1),nonvar(S2),
4157 is_global_set(S1,G1), is_global_set(S2,G2).
4158
4159 % check if we have a global set or interval
4160 % is_global_set([],R) :- !, R=interval(0,-1). % useful ???
4161 is_global_set(global_set(G1),R) :- !,
4162 (custom_explicit_sets:get_integer_set_interval(G1,Low,Up) -> R=interval(Low,Up) ; R=G1).
4163 is_global_set(Closure,R) :-
4164 custom_explicit_sets:is_interval_closure_or_integerset(Closure,Low,Up),!,
4165 R=interval(Low,Up).
4166
4167
4168 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(0,0),interval(minus_inf,inf))).
4169 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(-200,1000),interval(minus_inf,inf))).
4170 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(10,1000),interval(0,inf))).
4171 :- assert_must_fail(kernel_objects:check_subset_of_global_sets(interval(-10,1000),interval(0,inf))).
4172 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(0,inf),interval(0,inf))).
4173 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(0,inf),interval(minus_inf,inf))).
4174 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(1,inf),interval(0,inf))).
4175 :- assert_must_succeed(kernel_objects:check_subset_of_global_sets(interval(1,inf),interval(minus_inf,inf))).
4176
4177 % to do: also extend to allow intervals with inf/minus_inf
4178 check_subset_of_global_sets(X,Y) :- (var(X) ; var(Y)),
4179 add_internal_error('Illegal call: ',check_subset_of_global_sets(X,Y)),fail.
4180 check_subset_of_global_sets(interval(Low1,Up1),interval(Low2,Up2)) :- !,
4181 interval_subset(Low1,Up1,Low2,Up2).
4182 check_subset_of_global_sets(X,X) :- !. % both args must be atomic and ground (global set names)
4183 % BUT WE COULD HAVE {x|x>0} <: NATURAL1 ? interval(0,inf) <: NATURAL1
4184 check_subset_of_global_sets(X,Y) :- check_strict_subset_of_global_sets(X,Y).
4185
4186 % To do: perform some treatment of inf, minus_inf values here <----
4187 interval_subset(Low1,Up1,Low2,Up2) :-
4188 (var(Low1) ; var(Up1)), % otherwise we can use code below
4189 finite_interval(Low1,Up1), finite_interval(Low2,Up2), % inf can appear as term; but only directly not later
4190 !,
4191 % Maybe to do: try to avoid CLPFD overflows if possible; pass WF to force case distinction between empty/non-empty intervals
4192 clpfd_in_interval(Low1,Up1,Low2,Up2).
4193 interval_subset(Low1,Up1,Low2,Up2) :-
4194 interval_subset_aux(Low1,Up1,Low2,Up2).
4195
4196 % check if we have a finite interval (fails for inf/minus_inf terms)
4197 finite_interval(Low1,Up1) :- (var(Low1) -> true ; integer(Low1)), (var(Up1) -> true ; integer(Up1)).
4198 finite_val(LowUp) :- (var(LowUp) -> true ; integer(LowUp)).
4199
4200
4201
4202 % assert Low1..Up1 <: Low2..Up2
4203 clpfd_in_interval(Low1,Up1,Low2,Up2) :-
4204 (preferences:preference(use_chr_solver,true)
4205 -> chr_in_interval(Low1,Up1,Low2,Up2) ; true),
4206 % TO DO: improve detection of Low1 #=< Up1; maybe outside of CHR ?; we could also add a choice point here
4207 % example: p..q <: 0..25 & p<q -> should constrain p,q to p:0..24 & q:1..25
4208 clpfd_interface:post_constraint2((Low1 #=< Up1) #=> ((Low2 #=< Low1) #/\ (Up1 #=< Up2)),Posted),
4209 (Posted==true -> true ; interval_subset_aux(Low1,Up1,Low2,Up2)).
4210
4211 :- block interval_subset_aux(-,?,?,?), interval_subset_aux(?,-,?,?).
4212 interval_subset_aux(Low1,Up1,_,_) :- safe_less_than_with_inf(Up1,Low1). %Set 1 is empty.
4213 interval_subset_aux(Low1,Up1,Low2,Up2) :-
4214 safe_less_than_equal_with_inf(Low1,Up1), % Set 1 is not empty
4215 safe_less_than_equal_with_inf_clpfd(Low2,Low1), safe_less_than_equal_with_inf_clpfd(Up1,Up2). % may call CLPFD
4216
4217 % a version of safe_less_than which allows minus_inf and inf, but only if those terms appear straightaway at the first call
4218 % assumes any variable will only be bound to a number
4219 safe_less_than_with_inf(X,Y) :- (X==Y ; X==inf ; Y==minus_inf), !,fail.
4220 safe_less_than_with_inf(X,Y) :- (X==minus_inf ; Y==inf), !.
4221 safe_less_than_with_inf(X,Y) :- safe_less_than(X,Y).
4222
4223 safe_less_than_with_inf_clpfd(X,Y) :- (X==Y ; X==inf ; Y==minus_inf), !,fail.
4224 safe_less_than_with_inf_clpfd(X,Y) :- (X==minus_inf ; Y==inf), !.
4225 safe_less_than_with_inf_clpfd(X,Y) :- less_than_direct(X,Y). % this can also call CLPFD
4226
4227 % a version of safe_less_than_equal which allows minus_inf and inf, but only if those terms appear straightaway at the first call
4228 safe_less_than_equal_with_inf(X,Y) :- X==Y,!.
4229 safe_less_than_equal_with_inf(X,Y) :- (X==inf ; Y==minus_inf), !,fail.
4230 safe_less_than_equal_with_inf(X,Y) :- (X==minus_inf ; Y==inf), !.
4231 safe_less_than_equal_with_inf(X,Y) :- safe_less_than_equal(X,Y).
4232
4233 safe_less_than_equal_with_inf_clpfd(X,Y) :- X==Y,!.
4234 safe_less_than_equal_with_inf_clpfd(X,Y) :- (X==inf ; Y==minus_inf), !,fail.
4235 safe_less_than_equal_with_inf_clpfd(X,Y) :- (X==minus_inf ; Y==inf), !.
4236 safe_less_than_equal_with_inf_clpfd(X,Y) :- less_than_equal_direct(X,Y). % this can also call CLPFD
4237
4238 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,2),interval(1,3))).
4239 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,1),interval(1,2))).
4240 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,1),interval(0,1))).
4241 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(2,1),interval(33,34))).
4242 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(3,1),interval(4,2))).
4243 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(3,1),interval(2,1))).
4244 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(1,2),interval(1,2))).
4245 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(1,2),interval(2,3))).
4246 :- assert_must_fail(kernel_objects:check_strict_subset_of_global_sets(interval(2,3),interval(1,2))).
4247 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(0,1000),interval(0,inf))).
4248 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(1,1000),interval(1,inf))).
4249 :- assert_must_succeed(kernel_objects:check_strict_subset_of_global_sets(interval(-200,1000),interval(minus_inf,inf))).
4250 % for any other term we have global enumerated or deferred sets: they cannot be a strict subset of each other
4251 check_strict_subset_of_global_sets('FLOAT','REAL').
4252 check_strict_subset_of_global_sets(interval(Low1,Up1),interval(Low2,Up2)) :-
4253 ? check_strict_subset_intervals(Low1,Up1,Low2,Up2).
4254
4255 check_strict_subset_intervals(Low1,Up1,Low2,Up2) :-
4256 safe_less_than_equal_with_inf_clpfd(Low2,Up2), % Low2..Up2 not empty
4257 ? check_strict_subset_intervals1(Low1,Up1,Low2,Up2).
4258
4259 check_strict_subset_intervals1(Low1,Up1,Low2,Up2) :- % we cannot have inf as term (yet) here
4260 %preferences:preference(use_clpfd_solver,true),
4261 (var(Low1) ; var(Up1)),
4262 finite_interval(Low1,Up1), finite_interval(Low2,Up2),
4263 !,
4264 clpfd_interface:post_constraint2((Low1 #=< Up1) #=> ((Low2 #=< Low1) #/\ (Up1 #=< Up2) #/\ (Low1 #\= Low2 #\/ Up1 #\= Up2)),Posted),
4265 (Posted==true -> true ; check_strict_subset_intervals2(Low1,Up1,Low2,Up2)).
4266 ?check_strict_subset_intervals1(Low1,Up1,Low2,Up2) :- check_strict_subset_intervals2(Low1,Up1,Low2,Up2).
4267
4268 :- block check_strict_subset_intervals2(-,?,?,?),check_strict_subset_intervals2(?,-,?,?),
4269 check_strict_subset_intervals2(?,?,-,?).
4270 check_strict_subset_intervals2(Low1,Up1,_,_) :- safe_less_than_with_inf(Up1,Low1). % interval 1 empty
4271 check_strict_subset_intervals2(Low1,Up1,Low2,Up2) :-
4272 safe_less_than_equal_with_inf(Low1,Up1), % interval 1 not empty
4273 ( safe_less_than_with_inf(Low2,Low1), safe_less_than_equal_with_inf_clpfd(Up1,Up2)
4274 ;
4275 Low1=Low2,safe_less_than_with_inf_clpfd(Up1,Up2)
4276 ).
4277
4278 :- use_module(custom_explicit_sets,[is_definitely_maximal_set/1,singleton_set/2]).
4279 :- use_module(kernel_tools,[ground_value_check/2, quick_same_value/2]).
4280
4281 check_subset_of0(Set1,_Set2,_WF) :- Set1==[],!.
4282 check_subset_of0(Set1,Set2,WF) :- Set2==[],
4283 %nonvar(Set2),Set2=[], %var(Set1),
4284 !,
4285 ? empty_set_wf(Set1,WF).
4286 check_subset_of0(_Set1,Set2,_WF) :-
4287 nonvar(Set2),is_definitely_maximal_set(Set2),!.
4288 %singleton
4289 check_subset_of0(Set1,Set2,_) :-
4290 quick_same_value(Set1,Set2), % important for e.g. test 1948 for closures with different info fields
4291 !.
4292 check_subset_of0(Set1,Set2,WF) :- custom_explicit_sets:singleton_set(Set1,El),!,
4293 ? check_element_of_wf(El,Set2,WF).
4294 check_subset_of0(Set1,Set2,WF) :- % Note: two intervals are treated in check_subset_of_global_sets
4295 subset_of_explicit_set(Set1,Set2,Code,WF),!,
4296 ? call(Code).
4297 check_subset_of0(Set1,Set2,WF) :- nonvar(Set1),!,
4298 get_cardinality_powset_wait_flag(Set2,check_subset_of0,WF,_,LWF),
4299 expand_custom_set_to_list_wf(Set1,ESet1,_,check_subset_of1,WF),
4300 try_expand_and_convert_to_avl_unless_large_wf(Set2,ESet2,WF),
4301 % b_interpreter_components:observe_instantiation(ESet1,'ESet1',ESet1),
4302 ? check_subset_of2(ESet1,[],ESet2,WF,LWF,none).
4303 check_subset_of0(Set1,Set2,WF) :-
4304 is_wait_flag_info(WF,wfx_no_enumeration),!,
4305 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_).
4306 check_subset_of0(Set1,Set2,WF) :-
4307 % DO we need LWF if Set1=avl_set(_) ??
4308 get_cardinality_powset_wait_flag(Set2,check_subset_of0,WF,_Card,LWF),
4309 ground_value_check(Set2,GS2),
4310 check_subset_of0_lwf(Set1,Set2,WF,LWF,GS2).
4311
4312 :- use_module(custom_explicit_sets,[is_infinite_or_very_large_explicit_set/2]).
4313
4314 :- block check_subset_of0_lwf(-,?,?,-,?),check_subset_of0_lwf(-,?,?,?,-).
4315 check_subset_of0_lwf(Set1,_Set2,_WF,_LWF,_GS2) :- Set1==[],!.
4316 %check_subset_of0_lwf(Set1,Set2,WF,_LWF) :- Set2==[],!, % can never trigger as Set2 was already nonvar
4317 % empty_set_wf(Set1,WF).
4318 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_GS2) :- custom_explicit_sets:singleton_set(Set1,El),!,
4319 ? check_element_of_wf(El,Set2,WF).
4320 check_subset_of0_lwf(Set1,Set2,_WF,_,_) :-
4321 both_global_sets(Set1,Set2,G1,G2),!, % may now succeed compared to same check above, as Set1/Set2 now instantiated
4322 check_subset_of_global_sets(G1,G2).
4323 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_GS2) :- % Note: two intervals are treated in check_subset_of_global_sets
4324 nonvar(Set1), % otherwise we have already checked this code above
4325 subset_of_explicit_set(Set1,Set2,Code,WF),!,
4326 call(Code).
4327 check_subset_of0_lwf(Set1,Set2,WF,LWF,_GS2) :-
4328 (nonvar(Set1) ; nonvar(Set2),dont_expand_this_explicit_set(Set2)),
4329 !,
4330 expand_custom_set_to_list_wf(Set1,ESet1,_,check_subset_of1,WF),
4331 try_expand_and_convert_to_avl_unless_large_wf(Set2,ESet2,WF),
4332 % b_interpreter_components:observe_instantiation(ESet1,'ESet1',ESet1),
4333 ? check_subset_of2(ESet1,[],ESet2,WF,LWF,none).
4334 check_subset_of0_lwf(Set1,Set2,WF,_LWF,_GS2) :-
4335 expand_custom_set_to_list_wf(Set2,ESet2,_,check_subset_of0_lwf,WF), % Set2 is ground
4336 % THIS WILL ENUMERATE, for something like dom(f) <: SET this is problematic, as information cannot be used
4337 % hence we use wfx_no_enumeration above
4338 %non_free(Set1), % we used to enumerate Set1 in a specific order ESet2; now we use equal_object_wf and we no longer need to mark Set1 as non-free ?
4339 ? gen_subsets(Set1,ESet2,WF).
4340
4341 :- block check_subset_of2(-,?,?,?,-, ?).
4342 check_subset_of2([],_SoFar,_Set2,_WF,_LWF,_Last).
4343 check_subset_of2(HT,SoFar,Set2,WF,LWF,Last) :-
4344 (var(HT),Set2 = avl_set(AVL)
4345 -> % the value is chosen by the enumerator
4346 ? custom_explicit_sets:safe_avl_member(H,AVL),
4347 % this forces H to be ground; if Last /= none then it will be ground
4348 (Last==none -> true ; Last @< H),
4349 % TO DO: we could write a safe_avl_member_greater_than(H,Last,AVL)
4350 not_element_of_wf(H,SoFar,WF),
4351 NewLast=H,
4352 HT = [H|T]
4353 ; % the value may have been chosen by somebody else or will not be enumerated in order below
4354 HT = [H|T],
4355 ? not_element_of_wf(H,SoFar,WF),
4356 ? check_element_of_wf_lwf(H,Set2,WF,LWF),
4357 %check_element_of_wf(H,Set2,WF),
4358
4359 NewLast = Last
4360 ),
4361 ? check_subset_of3(H,T,SoFar,Set2,WF,LWF,NewLast).
4362
4363 % TO DO: write specific subsets code for avl_set(Set2) + try expand when becomes ground; merge with enumerate_tight_set ,...
4364 % TO DO: ensure that it also works with global_set(T) instead of avl_set(_) or with interval closures
4365
4366
4367 :- block check_subset_of3(?,-,-,?,?,-,?), check_subset_of3(?,-,?,-,?,-,?), check_subset_of3(?,-,-,-,?,?,?).
4368 check_subset_of3(_,T,_,_Set2,_WF,_LWF,_) :- T==[],!.
4369 check_subset_of3(H,T,SoFar,Set2,WF,LWF,Last) :- var(T),!,
4370 % Sofar, Set2 and LWF must be set
4371 ? when((nonvar(T);(ground(Set2),ground(H),ground(SoFar))),
4372 (T==[] -> true
4373 ; add_new_element_wf(H,SoFar,SoFar2,WF), %SoFar2 = [H|SoFar],
4374 check_subset_of2(T,SoFar2,Set2,WF,LWF,Last))).
4375 check_subset_of3(H,T,SoFar,Set2,WF,LWF,Last) :-
4376 % T must be set and not equal to []
4377 T = [H2|T2],
4378 add_new_element_wf(H,SoFar,SoFar2,WF), %SoFar2 = [H|SoFar],
4379 %check_subset_of2(T,SoFar2,Set2,WF,LWF))),
4380 ? check_element_of_wf(H2,Set2,WF),
4381 ? not_element_of_wf(H2,SoFar2,WF),
4382 ? check_subset_of3(H2,T2,SoFar2,Set2,WF,LWF,Last).
4383
4384
4385 :- block gen_subsets(?,-,?).
4386 gen_subsets([],_,_).
4387 gen_subsets(SubSet,Set,WF) :-
4388 ? ordered_delete(DH,Set,NewSet),
4389 ? equal_object_wf([DH|T],SubSet,gen_subsets,WF),
4390 ? gen_subsets(T,NewSet,WF).
4391
4392 % note: this is not select/3
4393 ordered_delete(H,[H|T],T).
4394 ?ordered_delete(H,[_|T],R) :- ordered_delete(H,T,R).
4395
4396
4397 :- assert_must_succeed(exhaustive_kernel_check_wf(check_finite_non_empty_subset_of_wf([int(1),int(5)], [int(2),int(5),int(1),int(3)],WF),WF)).
4398 :- assert_must_succeed(exhaustive_kernel_check_wf(check_finite_non_empty_subset_of_wf([int(1),int(5)], [int(5),int(1)],WF),WF)).
4399 check_finite_non_empty_subset_of_wf(Set1,Set2,WF) :-
4400 check_non_empty_subset_of_wf(Set1,Set2,WF),
4401 is_finite_set_wf(Set1,WF).
4402
4403 :- assert_must_succeed(exhaustive_kernel_check_wf(check_non_empty_subset_of_wf([int(1),int(5)], [int(2),int(5),int(1),int(3)],WF),WF)).
4404 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(check_non_empty_subset_of_wf([int(2)], [int(5),int(1)],WF),WF)).
4405 :- assert_must_succeed(exhaustive_kernel_fail_check_wfdet(check_non_empty_subset_of_wf([], [int(1)],WF),WF)).
4406
4407 check_non_empty_subset_of_wf(S1,S2,WF) :- not_empty_set_wf(S1,WF),
4408 check_subset_of_wf(S1,S2,WF).
4409
4410 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_subset_of([int(1),int(2),int(5)], [int(2),int(4),int(1),int(3)]))).
4411 :- assert_must_succeed(exhaustive_kernel_fail_check(not_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1),int(3)]))).
4412 :- assert_must_succeed((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name')], X=global_set('Name'))).
4413 :- assert_must_succeed((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name')], X=[fd(2,'Name')])).
4414 :- assert_must_succeed((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name')], X=[fd(1,'Name'),fd(2,'Name')])).
4415 :- assert_must_fail((kernel_objects:not_subset_of(Y,X), Y = [fd(1,'Name'),fd(3,'Name')], X=global_set('Name'))).
4416 :- assert_must_fail((kernel_objects:not_subset_of(Y,X), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4417 :- assert_must_fail((kernel_objects:not_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4418 :- assert_must_fail((kernel_objects:not_subset_of(global_set('NAT'),global_set('NAT')))).
4419 :- assert_must_succeed((kernel_objects:not_subset_of(global_set('NAT'),global_set('NAT1')))).
4420
4421
4422 not_subset_of(Set1,Set2) :- init_wait_flags(WF),
4423 not_subset_of_wf(Set1,Set2,WF),
4424 ground_wait_flags(WF).
4425
4426 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf([int(1),int(2),int(5)], [int(2),int(4),int(1),int(3)],_WF))).
4427 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf(global_set('NATURAL'), global_set('INTEGER'),_WF))).
4428 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf(global_set('INTEGER'), global_set('INTEGER'),_WF))).
4429 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_finite_subset_of_wf([int(1)], [],_WF))).
4430
4431 :- block not_finite_subset_of_wf(-,?,?).
4432 not_finite_subset_of_wf(Set1,Set2,WF) :- test_finite_set_wf(Set1,Finite,WF),
4433 not_finite_subset_of_wf_aux(Finite,Set1,Set2,WF).
4434 :- block not_finite_subset_of_wf_aux(-,?,?,?).
4435 not_finite_subset_of_wf_aux(pred_false,_Set1,_Set2,_WF).
4436 not_finite_subset_of_wf_aux(pred_true,Set1,Set2,WF) :- not_subset_of_wf(Set1,Set2,WF).
4437
4438 :- block not_subset_of_wf(-,?,?).
4439 not_subset_of_wf([],_,_WF) :- !, fail.
4440 not_subset_of_wf(Set1,Set2,WF) :- Set2==[],!, not_empty_set_wf(Set1,WF).
4441 not_subset_of_wf(Set1,Set2,WF) :-
4442 (both_global_sets(Set1,Set2,G1,G2) % also catches intervals
4443 -> check_not_subset_of_global_sets(G1,G2)
4444 ; not_subset_of_wf1(Set1,Set2,WF)
4445 ).
4446 not_subset_of_wf1(_Set1,Set2,_WF) :-
4447 nonvar(Set2), is_definitely_maximal_set(Set2),!,fail.
4448 not_subset_of_wf1(Set1,Set2,_WF) :- quick_same_value(Set1,Set2),
4449 !, fail.
4450 not_subset_of_wf1(Set1,Set2,WF) :- custom_explicit_sets:singleton_set(Set1,El),!,
4451 not_element_of_wf(El,Set2,WF).
4452 ?not_subset_of_wf1(Set1,Set2,WF) :- not_subset_of_explicit_set(Set1,Set2,Code,WF),!,
4453 call(Code).
4454 not_subset_of_wf1(Set1,Set2,WF) :-
4455 expand_custom_set_to_list_wf(Set1,ESet1,_,not_subset_of_wf1,WF),
4456 not_subset_of2(ESet1,Set2,WF).
4457
4458
4459 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(0,2),interval(1,3))).
4460 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(1,2),interval(0,-1))).
4461 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(1,2),interval(4,3))).
4462 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(1,3))).
4463 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(1,9000),interval(2,9999))).
4464 :- assert_must_succeed((kernel_objects:check_not_subset_of_global_sets(interval(X2,X4),interval(1,3)),
4465 X2=2, X4=4)).
4466 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(1,4))).
4467 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(2,4))).
4468 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(2,4),interval(0,10))).
4469 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(0,2),interval(1,inf))).
4470 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(-1,2),interval(0,inf))).
4471 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,2),interval(1,inf))).
4472 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(0,2),interval(0,inf))).
4473 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(-1,2),interval(minus_inf,inf))).
4474 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(0,inf),interval(1,inf))).
4475 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(minus_inf,inf),interval(1,inf))).
4476 :- assert_must_succeed(kernel_objects:check_not_subset_of_global_sets(interval(minus_inf,inf),interval(0,inf))).
4477 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,inf),interval(minus_inf,inf))).
4478 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,inf),interval(1,inf))).
4479 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(1,inf),interval(0,inf))).
4480 :- assert_must_fail(kernel_objects:check_not_subset_of_global_sets(interval(0,inf),interval(0,inf))).
4481
4482 :- block check_not_subset_of_global_sets(-,?), check_not_subset_of_global_sets(?,-).
4483 check_not_subset_of_global_sets(interval(Low1,Up1),G2) :- !,
4484 safe_less_than_equal_with_inf_clpfd(Low1,Up1), % Set 1 is not empty; otherwise it will always be a subset
4485 not_subset_interval_gs_aux(G2,Low1,Up1).
4486 check_not_subset_of_global_sets(G1,G2) :-
4487 \+ check_subset_of_global_sets(G1,G2).
4488
4489 not_subset_interval_gs_aux(interval(Low2,Up2),Low1,Up1) :-
4490 finite_interval(Low1,Up1), finite_interval(Low2,Up2),
4491 !,
4492 % post_constraint2((Low1 #<Low2 #\/ Up1 #> Up2 #\/ Up2 #< Low1),Posted), %% X #<100 #\/ X#<0. does not constraint X ! but X #<max(100,0) does
4493 post_constraint2((Low1 #<Low2 #\/ Up2 #< max(Up1,Low1)),Posted),
4494 (Posted==true -> true ; not_interval_subset(Low1,Up1,Low2,Up2)).
4495 not_subset_interval_gs_aux(interval(Low2,Up2),Low1,Up1) :- !, not_interval_subset(Low1,Up1,Low2,Up2).
4496 not_subset_interval_gs_aux(GS2,Low1,Up1) :-
4497 when((nonvar(Low1),nonvar(Up1)), \+ check_subset_of_global_sets(interval(Low1,Up1),GS2)).
4498
4499 not_interval_subset(Val1,Up1,Low2,Up2) :- var(Val1), Val1==Up1,
4500 !, % better propagation for singleton set
4501 (Up2==inf -> Low2\==minus_inf, less_than_direct(Val1,Low2)
4502 ; Low2=minus_inf -> less_than_direct(Up2,Val1)
4503 ; not_in_nat_range(int(Val1),int(Low2),int(Up2))).
4504 not_interval_subset(Low1,_,Low2,Up2) :- Up2==inf, finite_val(Low2), finite_val(Low1),
4505 % typical case x..y /<: NATURAL <==> x < 0
4506 !,
4507 less_than_direct(Low1,Low2).
4508 not_interval_subset(_,Up1,Low2,Up2) :- Low2==minus_inf, finite_val(Up2), finite_val(Up1),
4509 % covers x..y /<: {x|x<=0} <==> y > 0
4510 !,
4511 less_than_direct(Up2,Up1).
4512 not_interval_subset(Low1,Up1,Low2,Up2) :- not_interval_subset_block(Low1,Up1,Low2,Up2).
4513 :- block not_interval_subset_block(-,?,?,?), not_interval_subset_block(?,-,?,?),
4514 not_interval_subset_block(?,?,-,?), not_interval_subset_block(?,?,?,-).
4515 not_interval_subset_block(Low1,Up1,Low2,Up2) :- % this could be decided earlier, e.g. 1..n /<: 1..inf is false
4516 \+ interval_subset(Low1,Up1,Low2,Up2).
4517
4518
4519 :- block not_subset_of2(-,?,?).
4520 not_subset_of2([H|T],Set2,WF) :-
4521 (T==[]
4522 -> not_element_of_wf(H,Set2,WF)
4523 ; membership_test_wf(Set2,H,MemRes,WF),
4524 propagate_empty_set_to_pred_false(T,MemRes), % if T becomes empty, we know that H must not be in Set2
4525 not_subset_of3(MemRes,T,Set2,WF)
4526 ).
4527
4528 :- block not_subset_of3(-,?,?,?).
4529 not_subset_of3(pred_false,_T,_Set2,_WF).
4530 not_subset_of3(pred_true,T,Set2,WF) :- not_subset_of2(T,Set2,WF).
4531
4532 :- block propagate_empty_set_to_pred_false(-,-).
4533 propagate_empty_set_to_pred_false(X,PredRes) :- X==[],!,PredRes=pred_false.
4534 propagate_empty_set_to_pred_false(_,_).
4535
4536 :- assert_must_succeed(exhaustive_kernel_check_wf(not_both_subset_of([int(1),int(2),int(5)], []
4537 ,[int(2),int(4),int(1),int(3)],[],WF),WF)).
4538 :- assert_must_succeed(exhaustive_kernel_check_wf(not_both_subset_of([int(1),int(2),int(5)], [int(3)],
4539 [int(2),int(5),int(1),int(3)],[int(1),int(4)],WF),WF)).
4540
4541 not_both_subset_of(Set1A,Set1B, Set2A,Set2B, WF) :-
4542 kernel_equality:subset_test(Set1A,Set2A,Result,WF), % not yet implemented ! % TODO ! -> sub_set,equal,super_set
4543 not_both_subset_of_aux(Result,Set1B,Set2B,WF).
4544
4545 :- block not_both_subset_of_aux(-,?,?,?).
4546 not_both_subset_of_aux(pred_false,_Set1B,_Set2B,_WF).
4547 not_both_subset_of_aux(pred_true,Set1B,Set2B,WF) :-
4548 not_subset_of_wf(Set1B,Set2B,WF).
4549
4550 /***********************************/
4551 /* not_strict_subset_of(Set1,Set2) */
4552 /* Set1 /<<: Set2 */
4553 /**********************************/
4554
4555
4556 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_strict_subset_of([int(1),int(2),int(5)], [int(2),int(4),int(1),int(3)]))).
4557 :- assert_must_succeed(exhaustive_kernel_succeed_check(not_strict_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1)]))).
4558 :- assert_must_succeed(exhaustive_kernel_fail_check(not_strict_subset_of([int(1),int(2),int(5)], [int(2),int(5),int(1),int(3)]))).
4559 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [int(1)], X=[int(2),int(1)])).
4560 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [], X=[int(2),int(1)])).
4561 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [[int(1),int(2)]], X=[[int(2)],[int(2),int(1)]])).
4562 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [fd(1,'Name')], X=global_set('Name'))).
4563 :- assert_must_fail((kernel_objects:not_strict_subset_of(Y,X), Y = [fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4564 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name'),fd(2,'Name')], X=global_set('Name'))).
4565 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [fd(1,'Name'),fd(3,'Name')], X=global_set('Name'))).
4566 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(1)], X=[int(2),int(1)])).
4567 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(1),int(2)], X=[int(2),int(1)])).
4568 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(2)], X=[int(2)])).
4569 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [int(2)], X=[int(1)])).
4570 :- assert_must_succeed((kernel_objects:not_strict_subset_of(X,Y), Y = [], X=[int(1)])).
4571
4572 not_strict_subset_of(Set1,Set2) :-
4573 (preference(use_chr_solver,true) -> chr_not_subset_strict(Set1,Set2) ; true),
4574 init_wait_flags(WF,[not_strict_subset_of]),
4575 not_strict_subset_of_wf(Set1,Set2,WF),
4576 ground_wait_flags(WF).
4577
4578 :- block not_strict_subset_of_wf(-,?,?),not_strict_subset_of_wf(?,-,?).
4579 not_strict_subset_of_wf(Set1,Set2,WF) :-
4580 (both_global_sets(Set1,Set2,G1,G2)
4581 -> not_strict_subset_of_global_sets(G1,G2)
4582 ; not_strict_subset_of_wf1(Set1,Set2,WF)
4583 ).
4584 ?not_strict_subset_of_wf1(Set1,Set2,WF) :- not_subset_of_explicit_set(Set1,Set2,Code,WF),!,
4585 equality_objects_wf(Set1,Set2,EqRes,WF),
4586 not_strict_eq_check(EqRes,Code).
4587 not_strict_subset_of_wf1(Set1,Set2,WF) :-
4588 % OLD VERSION: not_subset_of(Set1,Set2) ; check_equal_object(Set1,Set2).
4589 expand_custom_set_to_list_wf(Set1,ESet1,_,not_strict_subset_of_wf1,WF),
4590 ? (nonvar(Set2),is_infinite_explicit_set(Set2) -> Inf=infinite ; Inf=unknown),
4591 not_strict_subset_of2(ESet1,Set2,Inf,WF).
4592
4593 :- block not_strict_eq_check(-,?).
4594 not_strict_eq_check(pred_true,_). % if equal then not strict subset is true
4595 not_strict_eq_check(pred_false,Code) :- call(Code). % check if not subset
4596
4597 :- block not_strict_subset_of2(-,?,?,?).
4598 not_strict_subset_of2([],R,_,WF) :- empty_set_wf(R,WF).
4599 not_strict_subset_of2([H|T],Set2,Inf,WF) :-
4600 membership_test_wf(Set2,H,MemRes,WF),
4601 not_strict_subset_of3(MemRes,H,T,Set2,Inf,WF).
4602
4603 :- block not_strict_subset_of3(-,?,?,?,?,?).
4604 not_strict_subset_of3(pred_false,_H,_T,_Set2,_,_WF).
4605 not_strict_subset_of3(pred_true,H,T,Set2,Inf,WF) :-
4606 (Inf=infinite
4607 -> RS2=Set2 % Set1 is finite; we just have to check that all elements are in Set2 and we have a strict subset
4608 ; remove_element_wf(H,Set2,RS2,WF)),
4609 not_strict_subset_of2(T,RS2,Inf,WF).
4610
4611
4612 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,2),interval(1,3))).
4613 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,2),interval(0,-1))).
4614 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,2),interval(4,3))).
4615 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(1,3))).
4616 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,9000),interval(2,9999))).
4617 :- assert_must_succeed((kernel_objects:not_strict_subset_of_global_sets(interval(X2,X4),interval(1,3)),
4618 X2=2, X4=4)).
4619 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(1,4))).
4620 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(2,4))).
4621 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(2,4),interval(0,10))).
4622 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,2),interval(1,inf))).
4623 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(-1,2),interval(0,inf))).
4624 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(1,2),interval(1,inf))).
4625 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(0,2),interval(0,inf))).
4626 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(-1,2),interval(minus_inf,inf))).
4627 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,inf),interval(1,inf))).
4628 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(minus_inf,inf),interval(1,inf))).
4629 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(minus_inf,inf),interval(0,inf))).
4630 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(1,inf),interval(minus_inf,inf))).
4631 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(1,inf),interval(1,inf))).
4632 :- assert_must_fail(kernel_objects:not_strict_subset_of_global_sets(interval(1,inf),interval(0,inf))).
4633 :- assert_must_succeed(kernel_objects:not_strict_subset_of_global_sets(interval(0,inf),interval(0,inf))).
4634
4635 :- block not_strict_subset_of_global_sets(-,?), not_strict_subset_of_global_sets(?,-).
4636 not_strict_subset_of_global_sets(interval(Low1,Up1),interval(Low2,Up2)) :- !,
4637 % Note: if Low2>Up2 then nothing is a strict subset of the empty set, i.e., everything is not a strict subset
4638 (finite_interval(Low1,Up1), finite_interval(Low2,Up2)
4639 -> clpfd_interface:post_constraint2(((Low2 #=< Up2) #=> (Low1 #=< Up1 #/\ ((Low2 #> Low1) #\/ (Up1 #> Up2) #\/ ((Low1 #= Low2 #/\ Up1 #= Up2))))),Posted)
4640 ; Posted=false),
4641 (Posted==true -> true ; not_strict_subset_intervals(Low1,Up1,Low2,Up2)).
4642 not_strict_subset_of_global_sets(G1,G2) :-
4643 when((ground(G1),ground(G2)), \+check_strict_subset_of_global_sets(G1,G2)).
4644
4645 :- block not_strict_subset_intervals(?,?,-,?), not_strict_subset_intervals(?,?,?,-).
4646 % Instead of blocking on Low2,Up2 we could post bigger constraint (Low2 <= Up2 => (Low1 <= Up1 /\ ....
4647 not_strict_subset_intervals(_Low1,_Up1,Low2,Up2) :- safe_less_than_with_inf(Up2,Low2),!.
4648 not_strict_subset_intervals(Low1,Up1,Low2,Up2) :-
4649 safe_less_than_equal_with_inf_clpfd(Low1,Up1), % if Low1..Up1 is empty then it would be a strict subset
4650 not_check_strict_subset_intervals2(Low1,Up1,Low2,Up2).
4651 :- block not_check_strict_subset_intervals2(-,?,?,?),not_check_strict_subset_intervals2(?,-,?,?),
4652 not_check_strict_subset_intervals2(?,?,-,?).
4653 ?not_check_strict_subset_intervals2(Low1,Up1,Low2,Up2) :- \+ check_strict_subset_intervals2(Low1,Up1,Low2,Up2).
4654
4655
4656 /* Set1 /: FIN1(Set2) */
4657 :- assert_must_succeed((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(2)])).
4658 :- assert_must_succeed((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X=[int(1)], Y=[int(1),int(2)])).
4659 :- assert_must_succeed((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[])).
4660 :- assert_must_fail((kernel_objects:not_non_empty_finite_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(1)])).
4661
4662 :- block not_non_empty_finite_subset_of_wf(-,?,?).
4663 not_non_empty_finite_subset_of_wf(Set1,Set2,WF) :- test_finite_set_wf(Set1,Finite,WF),
4664 not_non_empty_finite_subset_of_aux(Finite,Set1,Set2,WF).
4665 :- block not_non_empty_finite_subset_of_aux(-,?,?,?).
4666 not_non_empty_finite_subset_of_aux(pred_false,_Set1,_Set2,_WF).
4667 not_non_empty_finite_subset_of_aux(pred_true,Set1,Set2,WF) :- not_non_empty_subset_of_wf(Set1,Set2,WF).
4668
4669 /* Set1 /: POW1(Set2) */
4670 :- assert_must_succeed(exhaustive_kernel_check_wf(not_non_empty_subset_of_wf([int(1)], [int(2),int(3)],WF),WF)).
4671 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(not_non_empty_subset_of_wf([int(2)], [int(2),int(3)],WF),WF)).
4672 :- assert_must_succeed((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(2)])).
4673 :- assert_must_succeed((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X=[int(1)], Y=[int(1),int(2)])).
4674 :- assert_must_succeed((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[])).
4675 :- assert_must_fail((kernel_objects:not_non_empty_subset_of_wf(Y,X,_WF), X = [int(1)], Y=[int(1)])).
4676
4677 % Set1 /: POW1(Set2)
4678 :- block not_non_empty_subset_of_wf(-,?,?).
4679 not_non_empty_subset_of_wf(Set1,_,_WF) :- Set1==[],!.
4680 not_non_empty_subset_of_wf(Set1,Set2,WF) :- % Maybe introduce binary choice point ?
4681 empty_set_wf(Set1,WF) ;
4682 not_subset_of_wf(Set1,Set2,WF).
4683
4684
4685 /* min, max */
4686
4687 :- assert_must_succeed(exhaustive_kernel_check(minimum_of_set([int(1)],int(1),unknown,_WF))).
4688 :- assert_must_succeed(exhaustive_kernel_check(minimum_of_set([int(2),int(3),int(1)],int(1),unknown,_WF))).
4689 :- assert_must_succeed(exhaustive_kernel_fail_check(minimum_of_set([int(2),int(3),int(1)],int(2),unknown,_WF))).
4690 :- assert_must_succeed((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(1)])).
4691 :- assert_must_succeed((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(2),int(1)])).
4692 :- assert_must_succeed((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(1),int(2),int(1),int(3)])).
4693 :- assert_must_fail((kernel_objects:minimum_of_set(Y,X,unknown,_WF), X = int(2), Y=[int(1),int(2),int(1),int(3)])).
4694 :- assert_must_abort_wf(kernel_objects:minimum_of_set([],_R,unknown,WF),WF).
4695 %:- must_succeed(kernel_waitflags:assert_must_abort2_wf(kernel_objects:minimum_of_set([],_R,WF),WF)).
4696
4697 :- block minimum_of_set_extension_list(-,?,?,?).
4698 minimum_of_set_extension_list(ListOfValues,int(Min),Span,WF) :-
4699 minimum_of_set2(ListOfValues,Min,Span,WF).
4700
4701 :- block minimum_of_set(-,?,?,?).
4702 minimum_of_set(Set1,Res,_Span,WF) :- is_custom_explicit_set(Set1,minimum_of_set),
4703 min_of_explicit_set_wf(Set1,Min,WF), !,
4704 equal_object_wf(Min,Res,minimum_of_set,WF).
4705 minimum_of_set(Set1,int(Min),Span,WF) :- expand_custom_set_to_list_wf(Set1,ESet1,_,minimum_of_set,WF),
4706 minimum_of_set2(ESet1,Min,Span,WF).
4707 :- block minimum_of_set2(-,?,?,?).
4708 minimum_of_set2([],Res,Span,WF) :-
4709 add_wd_error_set_result('min applied to empty set','',Res,int(0),Span,WF).
4710 minimum_of_set2([int(N)|T],Min,_,_) :- clpfd_geq2(N,Min,_),minimum_of_set3(T,N,Min,[N]).
4711
4712 :- block minimum_of_set3(-,?,?,?). % with CLPFD: makes sense to also unfold if Min Variable; hence no longer block on : minimum_of_set3(?,-,-).
4713 minimum_of_set3([],MinSoFar,MinSoFar,ListOfValues) :-
4714 (var(MinSoFar) -> clpfd_minimum(MinSoFar,ListOfValues) ; true).
4715 minimum_of_set3([int(M)|T],MinSoFar,Min,ListOfValues) :- clpfd_geq2(M,Min,_),
4716 minimum(M,MinSoFar,NewMinSoFar),
4717 minimum_of_set3(T,NewMinSoFar,Min,[M|ListOfValues]).
4718
4719
4720 :- block minimum(-,?,?), minimum(?,-,?).
4721 minimum(M1,M2,Min) :- M1<M2 -> Min=M1 ; Min=M2.
4722
4723 :- assert_must_succeed(exhaustive_kernel_check(maximum_of_set([int(1)],int(1),unknown,_WF))).
4724 :- assert_must_succeed(exhaustive_kernel_check(maximum_of_set([int(2),int(3),int(1)],int(3),unknown,_WF))).
4725 :- assert_must_succeed(exhaustive_kernel_fail_check(maximum_of_set([int(2),int(3),int(1)],int(2),unknown,_WF))).
4726 :- assert_must_succeed((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(1), Y=[int(1)])).
4727 :- assert_must_succeed((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(2), Y=[int(2),int(1)])).
4728 :- assert_must_succeed((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(3), Y=[int(1),int(2),int(1),int(3)])).
4729 :- assert_must_fail((kernel_objects:maximum_of_set(Y,X,unknown,_WF), X = int(2), Y=[int(1),int(2),int(1),int(3)])).
4730 :- assert_must_fail((preferences:preference(use_clpfd_solver,true),
4731 kernel_objects:maximum_of_set([int(X),int(_Y)],int(3),unknown,_WF), X = 4)). % in CLPFD modus
4732 :- assert_must_fail((preferences:preference(use_clpfd_solver,true),
4733 kernel_objects:maximum_of_set([int(_),int(X)],int(3),unknown,_WF), X = 4)).% in CLPFD modus
4734 :- assert_must_abort_wf(kernel_objects:maximum_of_set([],_R,unknown,WF),WF).
4735
4736 :- block maximum_of_set_extension_list(-,?,?,?).
4737 maximum_of_set_extension_list(ListOfValues,int(Max),Span,WF) :-
4738 maximum_of_set2(ListOfValues,Max,Span,WF).
4739
4740 :- block maximum_of_set(-,?,?,?).
4741 maximum_of_set(Set1,Res,_Span,WF) :-
4742 is_custom_explicit_set(Set1,maximum_of_set),
4743 max_of_explicit_set_wf(Set1,Max,WF), !,
4744 ? equal_object_wf(Max,Res,maximum_of_set,WF).
4745 maximum_of_set(Set1,int(Max),Span,WF) :-
4746 expand_custom_set_to_list_wf(Set1,ESet1,_,maximum_of_set,WF),
4747 maximum_of_set2(ESet1,Max,Span,WF).
4748 :- block maximum_of_set2(-,?,?,?).
4749 maximum_of_set2([],Res,Span,WF) :-
4750 add_wd_error_set_result('max applied to empty set','',Res,int(0),Span,WF). %preferences:get_preference(maxint,R))). %R=abort(maximum_of_empty_set))).
4751 maximum_of_set2([int(N)|T],Max,_Span,_) :- clpfd_geq2(Max,N,_),
4752 maximum_of_set3(T,N,Max,[N]).
4753
4754 :- block maximum_of_set3(-,?,?,?). % with CLPFD: makes sense to also unfold if Max Variable; hence no longer block on : maximum_of_set3(?,-,-).
4755 maximum_of_set3([],MaxSoFar,MaxSoFar,ListOfValues) :-
4756 (var(MaxSoFar) -> clpfd_maximum(MaxSoFar,ListOfValues) ; true).
4757 maximum_of_set3([int(M)|T],MaxSoFar,Max,ListOfValues) :- clpfd_geq2(Max,M,_),
4758 maximum(M,MaxSoFar,NewMaxSoFar),
4759 maximum_of_set3(T,NewMaxSoFar,Max,[M|ListOfValues]).
4760
4761 :- block maximum(-,?,?), maximum(?,-,?).
4762 maximum(M1,M2,Max) :- M1>M2 -> Max=M1 ; Max=M2.
4763
4764 % card(ran(Function)); useful e.g. for q : 1 .. 16 --> 1 .. 16 & card(ran(q))=16
4765 :- block cardinality_of_range(-,?,?).
4766 cardinality_of_range(CS,Card,WF) :-
4767 is_custom_explicit_set(CS,cardinality_of_range),
4768 range_of_explicit_set_wf(CS,Res,WF),!,
4769 cardinality_as_int_wf(Res,Card,WF).
4770 cardinality_of_range(Function,Card,WF) :-
4771 expand_custom_set_to_list_wf(Function,EF1,Done,cardinality_of_range,WF),
4772 project_on_range(EF1,ERange),
4773 % when Done is set: we have a complete list and can compute MaxCard; TODO: maybe provide a version that can trigger earlier
4774 when(nonvar(Done),cardinality_of_set_extension_list(ERange,Card,WF)).
4775
4776 :- block project_on_range(-,?).
4777 project_on_range([],[]).
4778 project_on_range([(_,Ran)|T],[Ran|TR]) :- project_on_range(T,TR).
4779
4780
4781 :- assert_must_succeed((cardinality_of_set_extension_list([fd(1,'Name')],R,_WF), R = int(1))).
4782 :- assert_must_succeed((cardinality_of_set_extension_list([int(X),int(Y)],int(1),_WF), X=22, Y==22)).
4783
4784 cardinality_of_set_extension_list(List,int(Card),WF) :-
4785 length(List,MaxCard), less_than_equal_direct(Card,MaxCard),
4786 cardinality_of_set_extension_list2(List,[],0,MaxCard,Card,WF).
4787
4788 :- block cardinality_of_set_extension_list2(-,?,?,?,?,?).
4789 cardinality_of_set_extension_list2([],_,AccSz,_MaxCard,Res,_WF) :- Res=AccSz.
4790 cardinality_of_set_extension_list2([H|T],Acc,AccSz,MaxCard,Res,WF) :-
4791 membership_test_wf(Acc,H,MemRes,WF),
4792 (MaxCard==Res -> /* only solution is for H to be not in Acc */ MemRes=pred_false
4793 ; AccSz==Res -> /* only solution is for H to be in Acc */ MemRes=pred_true
4794 ; (var(Res),var(MemRes)) -> kernel_equality:equality_int(MaxCard,Res,EqMaxC),prop_if_pred_true(EqMaxC,MemRes,pred_false),
4795 kernel_equality:equality_int(AccSz,Res,EqAccSz),prop_if_pred_true(EqAccSz,MemRes,pred_true)
4796 ; true),
4797 ? cardinality_of_set_extension_list3(MemRes,H,T,Acc,AccSz,MaxCard,Res,WF).
4798
4799 :- block prop_if_pred_true(-,?,?).
4800 prop_if_pred_true(pred_true,X,X).
4801 prop_if_pred_true(pred_false,_,_).
4802
4803 :- block cardinality_of_set_extension_list3(-,?,?,?,?,?,?,?).
4804 cardinality_of_set_extension_list3(pred_true,_,T,Acc,AccSz,MaxCard,Res,WF) :-
4805 % H is a member of Acc, do not increase Acc nor AccSz; however MaxCard now decreases
4806 less_than_direct(Res,MaxCard), M1 is MaxCard-1,
4807 cardinality_of_set_extension_list2(T,Acc,AccSz,M1,Res,WF).
4808 cardinality_of_set_extension_list3(pred_false,H,T,Acc,AccSz,MaxCard,Res,WF) :-
4809 A1 is AccSz+1, less_than_equal_direct(A1,Res),
4810 ? cardinality_of_set_extension_list2(T,[H|Acc],A1,MaxCard,Res,WF).
4811
4812 :- assert_must_succeed(exhaustive_kernel_check(is_finite_set_wf([fd(1,'Name'),fd(2,'Name')],_WF))).
4813 :- assert_must_succeed((is_finite_set_wf(Y,_WF), Y = [])).
4814 :- assert_must_succeed((is_finite_set_wf(Y,_WF), Y = [int(1),int(2)])).
4815 :- use_module(typing_tools,[contains_infinite_type/1]).
4816 :- use_module(custom_explicit_sets,[card_for_specific_custom_set/3]).
4817
4818 is_finite_set_wf(Set,WF) :- test_finite_set_wf(Set,pred_true,WF).
4819
4820 :- assert_must_succeed(exhaustive_kernel_fail_check(is_infinite_set_wf([fd(1,'Name'),fd(2,'Name')],_WF))).
4821 :- assert_must_fail((is_infinite_set_wf(Y,_WF), Y = [int(1),int(2)])).
4822
4823 ?is_infinite_set_wf(Set,WF) :- test_finite_set_wf(Set,pred_false,WF).
4824
4825 %! test_finite_set_wf(+Set,?X,+WF)
4826 :- block test_finite_set_wf(-,?,?).
4827 %test_finite_set_wf(A,B,C) :- print(test_finite_set_wf(A,B,C)),nl,fail.
4828 test_finite_set_wf([],X,_WF) :- !, X=pred_true.
4829 test_finite_set_wf([_|T],X,WF) :- !, test_finite_set_wf(T,X,WF). % what if Tail contains closure ??
4830 test_finite_set_wf(avl_set(_),X,_WF) :- !, X=pred_true.
4831 test_finite_set_wf(closure(_P,T,_B),X,_WF) :- \+ contains_infinite_type(T), !, X=pred_true.
4832 ?test_finite_set_wf(closure(P,T,B),X,WF) :- !, test_finite_closure(P,T,B,X,WF).
4833 test_finite_set_wf(Set,X,WF) :- /* also deals with global_set(_) */
4834 /* explicit_set_cardinality may trigger an enum warning */
4835 explicit_set_cardinality_wf(Set,Card,WF),
4836 set_finite_result(Card,Set,explicit_set,X).
4837
4838 :- use_module(bsyntaxtree,[is_a_disjunct/3]).
4839 % we already check that contains_infinite_type above
4840 test_finite_closure(P,T,B,X,WF) :- is_a_disjunct(B,D1,D2),!,
4841 test_finite_closure(P,T,D1,X1,WF),
4842 ? test_finite_disj2(X1,P,T,D2,X,WF).
4843 % TO DO: add is_closure1_value_closure
4844 test_finite_closure(P,T,B,X,WF) :- when(ground(B), test_finite_closure_ground(P,T,B,X,WF)).
4845
4846 test_finite_disj2(pred_false,_P,_T,_D2,X,_WF) :- X=pred_false.
4847 test_finite_disj2(pred_true,P,T,D2,X,WF) :- test_finite_closure(P,T,D2,X,WF).
4848
4849
4850 % first: we need to check all constructors such as POW, FIN, ... which card_for_specific_custom_set supports
4851 % problem: if card becomes very large it is replaced by inf, which may give wrong results here (for card(.) we just get a spurious WD warning, here we may get wrong results)
4852 test_finite_closure_ground(P,T,B,X,WF) :-
4853 ? is_powerset_closure(closure(P,T,B),_Type,Subset),
4854 % note: whether Type is fin, fin1, pow, or pow1 does not matter
4855 !,
4856 test_finite_set_wf(Subset,X,WF).
4857 test_finite_closure_ground(P,T,B,X,WF) :-
4858 custom_explicit_sets:is_lambda_value_domain_closure(P,T,B, Subset,_Expr), !,
4859 test_finite_set_wf(Subset,X,WF).
4860 test_finite_closure_ground(P,T,B,X,WF) :-
4861 ? custom_explicit_sets:is_cartesian_product_closure(closure(P,T,B), A1,B2), !,
4862 test_finite_set_wf(A1,AX,WF),
4863 test_finite_set_wf(B2,BX,WF),
4864 test_finite_cartesian_product_wf(AX,BX,A1,B2,X,WF).
4865 test_finite_closure_ground(Par,Typ,Body, X,_WF) :-
4866 ? custom_explicit_sets:is_geq_leq_interval_closure(Par,Typ,Body,Low,Up), !,
4867 custom_explicit_sets:card_of_interval_inf(Low,Up,Card),
4868 set_finite_result_no_warn(Card,X).
4869 test_finite_closure_ground(P,T,B,X,WF) :-
4870 custom_explicit_sets:is_member_closure(P,T,B,_,SET), nonvar(SET),
4871 unary_member_closure_for_finite(SET,Check,SET1),
4872 !,
4873 (Check==finite -> test_finite_set_wf(SET1,X,WF)
4874 ; kernel_equality:empty_set_test_wf(SET1,X,WF)).
4875 % TO DO: catch other special cases : relations, struct,...
4876 test_finite_closure_ground(P,T,B,X,_WF) :-
4877 custom_explicit_sets:card_for_specific_closure(closure(P,T,B),ClosureKind,Card,Code),!,
4878 call(Code), % TO DO: catch if we convert large integer due to overflow to inf !
4879 % maybe we can set / transmit a flag for is_overflowcheck ? overflow_float_pown ? factorial ?
4880 set_finite_result(Card,closure(P,T,B),ClosureKind,X).
4881 test_finite_closure_ground(P,T,B,X,WF) :-
4882 on_enumeration_warning(expand_only_custom_closure_global(closure(P,T,B),Result,check,WF),fail),
4883 !,
4884 test_finite_set_wf(Result,X,WF).
4885 test_finite_closure_ground(P,T,B,X,WF) :- X==pred_true, !,
4886 get_enumeration_finished_wait_flag(WF,AWF), % only add warning if indeed we find a solution
4887 finite_warning(AWF,P,T,B,is_finite_set_closure(P)).
4888 test_finite_closure_ground(P,T,B,_X,_WF) :- !,
4889 finite_warning(now,P,T,B,test_finite_closure(P)),
4890 fail. % now we fail; used to be X=pred_true. % we assume set to be finite, but print a warning
4891 % we could set up the closure and do a deterministic phase: if it fails or all variables become bounded, then it is finite
4892
4893 unary_member_closure_for_finite(seq(b(value(SET1),_,_)),empty,SET1). % finite if SET1 is empty
4894 unary_member_closure_for_finite(seq1(b(value(SET1),_,_)),empty,SET1).
4895 unary_member_closure_for_finite(perm(b(value(SET1),_,_)),finite,SET1). % finite if SET1 is finite
4896 unary_member_closure_for_finite(iseq(b(value(SET1),_,_)),finite,SET1).
4897 unary_member_closure_for_finite(iseq1(b(value(SET1),_,_)),finite,SET1).
4898 unary_member_closure_for_finite(identity(b(value(SET1),_,_)),finite,SET1).
4899 % we could deal with POW/POW1... here
4900
4901 :- block test_finite_cartesian_product_wf(-,?,?,?,?,?), test_finite_cartesian_product_wf(?,-,?,?,?,?).
4902 test_finite_cartesian_product_wf(pred_true, pred_true, _,_,X,_) :- !, X=pred_true. % both finite
4903 test_finite_cartesian_product_wf(pred_false,pred_false,_,_,X,_) :- !, X=pred_false. % both infinite
4904 test_finite_cartesian_product_wf(pred_false,pred_true, _,B,X,WF) :- !,
4905 kernel_equality:empty_set_test_wf(B,X,WF). % only finite if B empty
4906 test_finite_cartesian_product_wf(pred_true, pred_false,A,_,X,WF) :- !,
4907 kernel_equality:empty_set_test_wf(A,X,WF). % only finite if B empty
4908
4909
4910 :- block set_finite_result_no_warn(-,?).
4911 set_finite_result_no_warn(inf,X) :- !, X=pred_false.
4912 set_finite_result_no_warn(_,pred_true).
4913
4914 :- block set_finite_result(-,?,?,?).
4915 set_finite_result(inf,Set,ClosureKind,X) :- !,
4916 (Set=closure(P,T,B), %,preferences:preference(disprover_mode,_true))
4917 \+ precise_closure_kind(ClosureKind)
4918 -> finite_warning(now,P,T,B,test_finite_closure(P)) % we sometimes return inf for very large sets % TO DO: fix
4919 ; true),
4920 X=pred_false.
4921 set_finite_result(_,_,_,pred_true).
4922
4923 precise_closure_kind(special_closure). % is_special_infinite_closure is precise, inf is real infinity
4924 precise_closure_kind(interval_closure). % here we also should never produce inf for a finite but large set
4925
4926
4927 :- assert_must_succeed(exhaustive_kernel_check(cardinality_as_int([int(2),int(4),int(1)],int(3)))).
4928 :- assert_must_succeed((cardinality_as_int(Y,int(2)), Y = [fd(1,'Name'),fd(2,'Name')])).
4929 :- assert_must_succeed((cardinality_as_int(Y,int(2)),
4930 nonvar(Y), Y = [H1|YY], nonvar(YY), YY=[H2], H1=int(0), H2=int(3) )).
4931 :- assert_must_succeed((cardinality_as_int([A|Y],int(3)),
4932 nonvar(Y), Y = [B|YY], nonvar(YY), YY=[C], A=int(1),B=int(3),C=int(2) )).
4933 :- assert_must_succeed((cardinality_as_int(Y,int(1)), Y = [fd(1,'Name')])).
4934 :- assert_must_succeed((cardinality_as_int(Y,int(0)), Y = [])).
4935 :- assert_must_succeed((cardinality_as_int(X,int(3)), equal_object(X,global_set('Name')))).
4936 :- assert_must_fail((cardinality_as_int(Y,int(X)), Y = [fd(1,'Name'),fd(2,'Name')],dif(X,2))).
4937 :- assert_must_succeed_any((preferences:preference(use_clpfd_solver,false) ;
4938 cardinality_as_int_wf(S,int(C),WF), clpfd_interface:try_post_constraint('#>='(C,2)), kernel_waitflags:ground_wait_flags(WF), nonvar(S),S=[_|T],nonvar(T))).
4939 :- assert_must_succeed((cardinality_as_int([int(1)|avl_set(node(int(3),true,0,empty,empty))],int(2)))).
4940 :- assert_must_succeed((cardinality_as_int([int(1)|avl_set(node(int(3),true,0,empty,empty))],X),X==int(2))).
4941 % check that we deal with repeated elements, in case no other predicate sets up a list !
4942 :- assert_must_fail((cardinality_as_int([int(1),int(1)],int(2)))).
4943 :- assert_must_fail((cardinality_as_int([int(1),int(1)],_))).
4944 :- assert_must_fail((cardinality_as_int(X,int(2)),X=[int(1),int(1)])).
4945 :- assert_must_fail((cardinality_as_int([int(3)|avl_set(node(int(3),true,0,empty,empty))],_))).
4946 :- assert_must_fail((cardinality_as_int([X|avl_set(node(int(3),true,0,empty,empty))],int(2)),X=int(3))).
4947
4948
4949 cardinality_as_int(S,I) :- cardinality_as_int_wf(S,I,no_wf_available). % TO DO: remove this predicate ?
4950 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
4951 :- if(environ(prob_data_validation_mode,true)).
4952 :- block cardinality_as_int_wf(-,?,?). % avoid instantiating list skeletons; cause backtracking in unifications,...
4953 :- else.
4954 :- block cardinality_as_int_wf(-,-,?).
4955 :- endif.
4956 % can return inf !
4957 cardinality_as_int_wf(Set,int(Card),WF) :-
4958 cardinality_as_int1(Set,Card,Card,WF).
4959
4960 cardinality_as_int1(Set,Card,ResCard,WF) :-
4961 (number(Card)
4962 -> cardinality_as_int1b(Set,Card,ResCard,WF)
4963 ; cardinality_as_int1b(Set,Card,ResCard,WF),
4964 (var(Set) ->
4965 (clpfd_domain(Card,Low,_Up),
4966 number(Low), Low>1,
4967 unbound_variable_for_card(Set)
4968 % TO DO: also use this optimization later in cardinality_as_int2
4969 -> setup_ordered_list_skeleton(Low,Skel,open,WF),
4970 Skel=Set
4971 ; get_wait_flag(1,force_non_empty(Set,Card),WF,LWF),
4972 force_non_empty0(Set,Card,LWF)
4973 )
4974 ; true)
4975 ).
4976 % tests 1418, 1419, 1628, 1776 require that cardinality_as_int1b be triggered quickly
4977 :- block cardinality_as_int1b(-,-,?,?). % with this the self-check with post_constraint('#>='(C,2) fails
4978 % cardinality_as_int1(Set, CardValue, ComputedCardValue) : CardValue should be unified with ComputedCardValue afterwards
4979 cardinality_as_int1b(Set,Card,ResCard,WF) :-
4980 %portray_waitflags(WF),nl,
4981 number(Card), unbound_variable_for_card(Set),
4982 !, % we know the cardinality and the set is not yet bound; this improvement is tested in tests 1417, 1418
4983 setup_ordered_list_skeleton(Card,Skel,closed,WF),
4984 (Card,Set) = (ResCard,Skel). % bypass equal_object: assign variable in one-go
4985 cardinality_as_int1b(Set,Card,ResCard,WF) :- nonvar(Set),!,
4986 cardinality_as_int2(Set,0,Card,ResCard,[],WF).
4987 cardinality_as_int1b(Set,Card,ResCard,WF) :-
4988 % Set is a variable but not unbound_variable_for_cons
4989 % Unifications can be very expensive when we set up long lists
4990 % Idea: multiply Card by a factor and delay instantiating; maybe we get a avl_set; see test 456
4991 Prio is Card*100,
4992 get_wait_flag(Prio,cardinality_as_int1(Set,Card),WF,LWF2),
4993 when((nonvar(Set) ; nonvar(LWF2)),
4994 cardinality_as_int2(Set,0,Card,ResCard,[],WF)).
4995 %force_non_empty0(Set,Card,1).
4996
4997 :- if(environ(prob_data_validation_mode,true)).
4998 :- block cardinality_as_int2(-,?,?,?,?,?). % avoid instantiating list skeletons; cause backtracking in unifications,...
4999 :- else.
5000 :- block cardinality_as_int2(-,?,-,?,?,?).
5001 :- endif.
5002 cardinality_as_int2(X,C,Res,ResultValue,_,WF) :-
5003 C==Res,!,empty_set_wf(X,WF),ResultValue=Res. % avoid choice point below
5004 cardinality_as_int2(X,C,Res,ResultValue,SoFar,WF) :- nonvar(X), X \= [], X\= [_|_],!,
5005 (is_custom_explicit_set(X)
5006 -> explicit_set_cardinality_wf(X,ESC,WF), add_card(C,ESC,ResultValue),
5007 disjoint_sets(X,SoFar,WF)
5008 ; add_error_fail(cardinality_as_int2,'First argument not set: ',cardinality_as_int2(X,C,Res))
5009 ).
5010 cardinality_as_int2([],C,Res,ResultValue,_,_WF) :- C=ResultValue, Res=ResultValue.
5011 cardinality_as_int2([H|T],C,Res,ResultValue,SoFar,WF) :-
5012 C1 is C+1,
5013 not_element_of_wf(H,SoFar,WF), % do we always need to check this ? relevant for test 1828
5014 add_new_element_wf(H,SoFar,SoFar2,WF),
5015 (ground(Res) -> safe_less_than_equal(cardinality_as_int2,C1,Res)
5016 /* check consistency so far if cardinality provided */
5017 ; clpfd_geq(Res,C1,_)
5018 ),
5019 force_non_empty(T,C1,Res,1), % Use WF ?
5020 ? cardinality_as_int2(T,C1,Res,ResultValue,SoFar2,WF).
5021
5022 % setup an list skeleton with ordering constraints to avoid duplicate solutions
5023 setup_ordered_list_skeleton(0,R,Closed,_WF) :- !, (Closed=closed -> R=[] ; true).
5024 setup_ordered_list_skeleton(N,[H|T],Closed,WF) :-
5025 all_different_wf([H|T],WF),
5026 N1 is N-1, setup_list_skel_aux(N1,H,T,Closed).
5027
5028
5029 :- use_module(kernel_ordering,[ordered_value/2]).
5030 %setup_list_skel_aux(0,_,R,Closed) :- !, (Closed=closed -> R=[] ; true). % if open: TO DO: impose ordering on rest using lazy_ordered_value ? done in next clause below
5031 setup_list_skel_aux(0,Prev,R,Closed) :- !, (Closed=closed -> R=[] ; lazy_ordered_value(R,Prev)).
5032 setup_list_skel_aux(N,Prev,[H|T],Closed) :- ordered_value(Prev,H),
5033 N>0, N1 is N-1, setup_list_skel_aux(N1,H,T,Closed).
5034
5035 :- block lazy_ordered_value(-,?).
5036 lazy_ordered_value([H|T],Prev) :- !, ordered_value(Prev,H), lazy_ordered_value(T,H).
5037 lazy_ordered_value(_,_).
5038
5039
5040 % TO DO: use clpfd all_different for integers !?
5041 % get_integer_list(Set,IntList), clpfd_alldifferent(IntList).
5042 % ensure we have all different constraint in case ordered_value does not succeed in enforcing order!
5043 all_different_wf(ListOfValues,WF) :-
5044 all_different2(ListOfValues,[],WF).
5045 :- block all_different2(-,?,?).
5046 all_different2([],_,_) :- !.
5047 all_different2([H|T],SoFar,WF) :- !, all_different3(SoFar,H,WF), all_different2(T,[H|SoFar],WF).
5048 all_different2(CS,SoFar,WF) :- is_custom_explicit_set(CS),
5049 disjoint_sets(CS,SoFar,WF). % already done above by cardinality_as_int2 ?
5050 all_different3([],_,_).
5051 all_different3([H|T],X,WF) :- not_equal_object_wf(H,X,WF), all_different3(T,X,WF).
5052
5053 :- block force_non_empty0(-,-,-).
5054 force_non_empty0(Set,Card,LWF) :- var(Set), var(Card),
5055 clpfd_domain(Card,Low,Up),
5056 (integer(Low) ; integer(Up)), !, % we know we have a finite cardinality
5057 clpfd_interface:try_post_constraint((Card#=0) #<=> EmptyR01),
5058 prop_non_empty(EmptyR01,Set,LWF).
5059 force_non_empty0(_,_,_).
5060
5061 % here we assume that the cardinalities cannot be infinite inf
5062 :- block force_non_empty(-,?,-,-).
5063 force_non_empty(Set,CSoFar,TotalCard,LWF) :-
5064 var(Set), var(TotalCard),
5065 preference(data_validation_mode,false),!,
5066 clpfd_interface:try_post_constraint((TotalCard#=CSoFar) #<=> EmptyR01),
5067 prop_non_empty(EmptyR01,Set,LWF).
5068 force_non_empty(_,_,_,_).
5069 :- block prop_non_empty(-,-,?).
5070 prop_non_empty(_,X,_) :- nonvar(X),!. % do nothing; cardinality_as_int2 will be called anyway
5071 prop_non_empty(0,X,LWF) :- /* X is var; first arg nonvar */ !, not_empty_set_lwf(X,LWF).
5072 %prop_non_empty(1,X,_). % empty_set not really required: TotalCard is now instantiated; cardinality_as_int2 will get called
5073 prop_non_empty(_,_,_).
5074
5075
5076
5077 :- assert_must_succeed(exhaustive_kernel_check(cardinality_as_int_for_wf(global_set('NATURAL'),inf))).
5078 :- assert_must_succeed(exhaustive_kernel_check(cardinality_as_int_for_wf([],0))).
5079 :- assert_must_succeed(exhaustive_kernel_check_opt(cardinality_as_int_for_wf([int(2)],1),
5080 preferences:get_preference(convert_comprehension_sets_into_closures,false))). % in this case inf returned for closures
5081 :- assert_must_succeed(exhaustive_kernel_check_opt(cardinality_as_int_for_wf([int(3),int(1),int(-1),int(100)],4),
5082 preferences:get_preference(convert_comprehension_sets_into_closures,false))).
5083 :- assert_must_succeed(exhaustive_kernel_fail_check_opt(cardinality_as_int_for_wf([int(3),int(1),int(-1),int(100)],1000),
5084 preferences:get_preference(convert_comprehension_sets_into_closures,false))).
5085 :- assert_must_succeed(exhaustive_kernel_fail_check_opt(cardinality_as_int_for_wf(global_set('NATURAL'),1000),
5086 preferences:get_preference(convert_comprehension_sets_into_closures,false))).
5087 % a simpler version without propagation to result; for waitflag priority computation or similar
5088 % it may return inf for closures marked as symbolic !
5089 cardinality_as_int_for_wf(Set,Card) :- cardinality_as_int_for_wf0(Set,0,Card).
5090 :- block cardinality_as_int_for_wf0(-,?,-).
5091 cardinality_as_int_for_wf0(X,C,Res) :-
5092 (nonvar(X) -> cardinality_as_int_for_wf1(X,C,Res)
5093 ; Res==inf -> cardinality_as_int_for_inf(X,C)
5094 ; cardinality_as_int_for_wf2(X,C,Res)).
5095
5096 :- block cardinality_as_int_for_inf(-,?).
5097 cardinality_as_int_for_inf(X,C) :- cardinality_as_int_for_wf1(X,C,inf).
5098
5099 cardinality_as_int_for_wf1([],C,Res) :- !,C=Res.
5100 cardinality_as_int_for_wf1([_H|T],C,Res) :- !,C1 is C+1,
5101 cardinality_as_int_for_wf0(T,C1,Res).
5102 cardinality_as_int_for_wf1(X,C,Res) :- is_custom_explicit_set(X),!,
5103 explicit_set_cardinality_for_wf(X,ESC), add_card(C,ESC,Res).
5104 cardinality_as_int_for_wf1(term(T),C,Res) :- nonvar(T), T=no_value_for(ID),
5105 format_with_colour(user_error,[bold,red],'~nNo value for ~w for cardinality_as_int_for_wf1!~n',[ID]), % can happen with partial_setup_constants
5106 !, C=Res.
5107 cardinality_as_int_for_wf1(X,C,Res) :-
5108 add_internal_error('First arg is not a set: ',cardinality_as_int_for_wf1(X,C,Res)),fail.
5109
5110 % first argument was var, third argument not inf hence third arg must be set
5111 %cardinality_as_int_for_wf2([],C,C).
5112 cardinality_as_int_for_wf2([],C,Res) :- (C==Res -> ! ; C=Res).
5113 cardinality_as_int_for_wf2([_H|T],C,Res) :- C<Res, C1 is C+1,
5114 (var(T) -> cardinality_as_int_for_wf2(T,C1,Res) ; cardinality_as_int_for_wf1(T,C1,Res)).
5115
5116 % add two cardinalities together: can be number or inf
5117 :- block add_card(-,-,?).
5118 add_card(X,Y,R) :- X==0,!,R=Y.
5119 add_card(X,Y,R) :- Y==0,!,R=X.
5120 add_card(X,_,R) :- X==inf,!,R=inf.
5121 add_card(_,Y,R) :- Y==inf,!,R=inf.
5122 add_card(X,Y,R) :- add_card2(X,Y,R).
5123
5124 :- block add_card2(-,?,?), add_card2(?,-,?).
5125 add_card2(inf,_,R) :- !,R=inf.
5126 add_card2(_,inf,R) :- !,R=inf.
5127 add_card2(X,Y,R) :- R is X+Y.
5128
5129
5130 :- assert_must_succeed(exhaustive_kernel_check_wf(same_cardinality_wf(global_set('NATURAL'),global_set('NATURAL'),WF),WF)).
5131 :- assert_must_succeed(exhaustive_kernel_check_wf(same_cardinality_wf(global_set('NATURAL'),global_set('NATURAL1'),WF),WF)).
5132 :- assert_must_succeed(exhaustive_kernel_check_wf(same_cardinality_wf([int(2),int(1)],[int(11),int(22)],WF),WF)).
5133 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(same_cardinality_wf([],[int(11),int(22)],WF),WF)).
5134 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(same_cardinality_wf([int(11),int(22),int(33)],[int(11),int(22)],WF),WF)).
5135 :- assert_must_succeed(exhaustive_kernel_fail_check_wf(same_cardinality_wf(global_set('NATURAL1'),[int(11),int(22)],WF),WF)).
5136
5137 :- block same_cardinality_wf(-,-,?).
5138 same_cardinality_wf(Set1,Set2,WF) :-
5139 (var(Set1) -> same_card_aux(Set2,Set1,WF) ; same_card_aux(Set1,Set2,WF)).
5140
5141 same_card_aux(Set1,Set2,WF) :-
5142 (nonvar(Set1),is_custom_explicit_set(Set1,cardinality)
5143 -> explicit_set_cardinality_wf(Set1,Card,WF),
5144 (Card==inf -> is_infinite_set_wf(Set2,WF)
5145 % assumption: if inf then immediately infinite; TO DO: distinguish between infinite(s) and very large
5146 ; cardinality_as_int_wf(Set2,int(Card),WF)
5147 )
5148 ; cardinality3(Set1,PCard,WF),
5149 cardinality_peano_wf(Set2,PCard,WF)
5150 ).
5151
5152 :- assert_must_succeed(exhaustive_kernel_check(cardinality_peano_wf([],0,no_wf_available))).
5153 :- assert_must_succeed(exhaustive_kernel_check(cardinality_peano_wf([int(11)],s(0),no_wf_available))).
5154 :- assert_must_succeed(exhaustive_kernel_check(cardinality_peano_wf([int(11),int(22)],s(s(0)),no_wf_available))).
5155 % cardinality as peano number
5156 :- block cardinality_peano_wf(-,-,?).
5157 cardinality_peano_wf(Set,PCard,WF) :-
5158 (nonvar(Set),is_custom_explicit_set(Set,cardinality)
5159 -> explicit_set_cardinality_wf(Set,Card,WF),
5160 card_convert_int_to_peano(Card,PCard)
5161 ; cardinality3(Set,PCard,WF)
5162 ).
5163
5164 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(3,s(s(s(0)))))).
5165 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(2,S),S==s(s(0)))).
5166 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(X,s(s(s(0)))),X==3)).
5167 :- assert_must_succeed((kernel_objects:card_convert_int_to_peano(X,s(s(s(Y)))),X=4,Y==s(0))).
5168 :- assert_must_fail((kernel_objects:card_convert_int_to_peano(X,s(s(s(_Y)))),X=2)).
5169
5170 :- block card_convert_int_to_peano(-,-).
5171 card_convert_int_to_peano(X,S0) :- var(X), !,
5172 peel_s(S0,SX,RemS),
5173 (RemS==0 -> X=SX
5174 ; int_plus(int(X1),int(SX),int(X)),
5175 greater_than_equal(int(X1),int(0)),
5176 card_convert_int_to_peano(X1,RemS)).
5177 card_convert_int_to_peano(inf,X) :- !,
5178 infinite_peano(X),
5179 add_message(cardinality,'*** WARNING: Large or infinite Cardinality.').
5180 %convert_int_to_peano(100,X). % used to limit to 100
5181 ?card_convert_int_to_peano(X,P) :- convert_int_to_peano(X,P).
5182
5183 :- block infinite_peano(-).
5184 infinite_peano(inf).
5185 infinite_peano(0) :- fail.
5186 infinite_peano(s(X)) :- infinite_peano(X).
5187
5188 peel_s(0,0,0).
5189 peel_s(s(X),Res,SX) :- (var(X) -> Res=1, SX=X ; peel_s(X,RX,SX), Res is RX+1).
5190
5191 :- block cardinality3(-,?,?). % avoids instantiating set; to do: use kernel_cardinality instead
5192 % relevant, e.g., for "BK-ANT-N-2013" for SlotSolver_v7; but makes 'axm2/WD' fail for test 1448; TO DO: hopefully fixed with kernel_cardinality
5193 % :- block cardinality3(-,-,?).
5194 cardinality3(Set,SC,WF) :- var(Set),!,
5195 (SC=0 -> Set=[] ; SC=s(C),Set=[_|T],cardinality3(T,C,WF)).
5196 cardinality3([],0,_).
5197 ?cardinality3([_|T],s(C),WF) :- cardinality3(T,C,WF).
5198 cardinality3(avl_set(AVL),Res,WF) :- cardinality_peano_wf(avl_set(AVL),Res,WF).
5199 cardinality3(closure(P,T,B),Res,WF) :- cardinality_peano_wf(closure(P,T,B),Res,WF).
5200
5201
5202
5203
5204
5205
5206 :- assert_must_succeed(exhaustive_kernel_check(card_geq([int(2),int(4),int(1)],s(s(s(0)))))).
5207 :- assert_must_succeed((kernel_objects:card_geq(global_set('Name'),s(s(s(0)))))).
5208 :- assert_must_succeed((kernel_objects:card_geq([int(1),int(2)],s(s(0))))).
5209 :- assert_must_succeed((kernel_objects:card_geq([int(1),int(2)],s(0)))).
5210 :- assert_must_fail((kernel_objects:card_geq(global_set('Name'),s(s(s(s(0))))))).
5211 :- assert_must_fail((kernel_objects:card_geq([int(1),int(2)],s(s(s(0)))))).
5212
5213 card_geq(Set,Card) :- card_geq_wf(Set,Card,no_wf_available).
5214
5215 :- block card_geq_wf(-,-,?).
5216 card_geq_wf(Set,Card,WF) :-
5217 (nonvar(Set),is_custom_explicit_set(Set,card_geq)
5218 ? -> explicit_set_cardinality_wf(Set,CCard,WF), geq_int_peano(CCard,Card)
5219 ; card_geq2(Set,Card,WF) ).
5220 % should we call setup_ordered_list_skeleton(Card,Set,open)
5221 :- block card_geq2(?,-,?).
5222 card_geq2(_,C,_) :- C==0,!.
5223 card_geq2(S,C,_) :- S==[],!,C=0.
5224 card_geq2(S,s(C),WF) :- var(S),!,S=[_|T],card_geq2(T,C,WF).
5225 card_geq2([_|T],s(C),WF) :- card_geq2(T,C,WF).
5226 card_geq2(avl_set(A),s(C),WF) :- card_geq_wf(avl_set(A),s(C),WF).
5227 card_geq2(closure(P,T,B),s(C),WF) :- card_geq_wf(closure(P,T,B),s(C),WF).
5228 card_geq2(global_set(G),s(C),WF) :- card_geq_wf(global_set(G),s(C),WF).
5229
5230 :- block geq_int_peano(-,-).
5231 geq_int_peano(_,0).
5232 ?geq_int_peano(X,s(C)) :- geq_int_peano1(X,C).
5233 :- block geq_int_peano1(-,?).
5234 geq_int_peano1(inf,_) :- !.
5235 ?geq_int_peano1(X,C) :- X>0, X1 is X-1, geq_int_peano(X1,C).
5236
5237 :- block convert_int_to_peano(-,?).
5238 ?convert_int_to_peano(X,Y) :- convert_int_to_peano2(X,Y).
5239 convert_int_to_peano2(inf,_).
5240 convert_int_to_peano2(X,R) :- number(X),
5241 (X>100000
5242 -> print('*** Warning: converting large integer to peano: '),print(X),nl,
5243 (X>1000000000 -> print('*** treat like inf'),nl % no hope of ever finishing, do not instantiate just like inf
5244 ; convert_int_to_peano3(X,R))
5245 ? ; convert_int_to_peano3(X,R)
5246 ).
5247 convert_int_to_peano3(0,R) :- !, R=0.
5248 convert_int_to_peano3(X,s(P)) :-
5249 ? (X>0 -> X1 is X-1, convert_int_to_peano3(X1,P)
5250 ; X<0 -> add_error_and_fail(convert_int_to_peano,'Negative nr cannot be converted to peano: ',X)
5251 ).
5252
5253 % not used:
5254 %:- block convert_peano_to_int(-,?).
5255 %convert_peano_to_int(0,0).
5256 %convert_peano_to_int(s(P),X) :- convert_peano_to_int(P,X1), X is X1+1.
5257
5258 :- assert_must_succeed((kernel_objects:cardinality_greater_equal(Set,set(integer),int(X),integer,_WF), X=3,
5259 nonvar(Set),Set=[_|S2],nonvar(S2),S2=[_|S3],nonvar(S3),S3=[_|S4],var(S4), Set=[int(1),int(2),int(3)] )).
5260 :- assert_must_succeed((kernel_objects:cardinality_greater(Set,set(integer),int(X),integer,_WF), X=2,
5261 nonvar(Set),Set=[_|S2],nonvar(S2),S2=[_|S3],nonvar(S3),S3=[_|S4],var(S4), Set=[int(1),int(2),int(3)] )).
5262 /* special predicates called for e.g. card(Set)>X */
5263 cardinality_greater(Set,TypeSet,int(X),_,WF) :-
5264 kernel_objects:max_cardinality(TypeSet,MaxCard),
5265 (number(MaxCard) -> less_than(int(X),int(MaxCard)) ; true),
5266 ? card_greater2(Set,X,WF).
5267 :- block card_greater2(?,-,?).
5268 ?card_greater2(Set,X,WF) :- X1 is X+1, card_greater_equal2(Set,X1,WF).
5269
5270 cardinality_greater_equal(Set,TypeSet,int(X),_,WF) :-
5271 kernel_objects:max_cardinality(TypeSet,MaxCard),
5272 (number(MaxCard) -> less_than_equal(int(X),int(MaxCard)) ; true),
5273 ? card_greater_equal2(Set,X,WF).
5274 :- block card_greater_equal2(?,-,?).
5275 card_greater_equal2(Set,X,WF) :-
5276 (X<1 -> true % potential WD issue, hence this predicates should only be called when no wd issue
5277 ; X=1 -> not_empty_set_wf(Set,WF) % ditto: Set could be infinite
5278 ; var(Set) -> setup_ordered_list_skeleton(X,Set,open,WF)
5279 ; convert_int_to_peano(X,Peano),
5280 ? card_geq_wf(Set,Peano,WF)).
5281
5282
5283
5284 %is_cartesian_pair_or_times(P,X,Y) :- is_cartesian_pair(P,X,Y).
5285 %is_cartesian_pair_or_times(int(Z),int(X),int(Y)) :- times(int(X),int(Y),int(Z)).
5286
5287 is_cartesian_pair_wf((X,Y),XType,YType,WF) :-
5288 ? check_element_of_wf(X,XType,WF), check_element_of_wf(Y,YType,WF).
5289
5290 :- assert_must_succeed(exhaustive_kernel_check_wf(kernel_objects:not_is_cartesian_pair((int(1),int(1)),
5291 [int(1),int(2)],[int(2),int(3)],WF),WF)).
5292 :- assert_must_succeed(exhaustive_kernel_check_wf(kernel_objects:not_is_cartesian_pair((int(3),int(2)),
5293 [int(1),int(2)],[int(2),int(3)],WF),WF)).
5294 :- assert_must_succeed((kernel_objects:not_is_cartesian_pair((int(1),int(1)),
5295 [int(1),int(2)],[int(2),int(3)],_WF))).
5296 :- assert_must_succeed((kernel_objects:not_is_cartesian_pair((int(3),int(1)),
5297 [int(1),int(2)],[int(2),int(3)],_WF))).
5298 :- assert_must_fail((kernel_objects:not_is_cartesian_pair((int(1),int(3)),
5299 [int(1),int(2)],[int(2),int(3)],_WF))).
5300 :- assert_must_succeed((kernel_objects:not_is_cartesian_pair((X,int(3)),
5301 [int(1),int(2)],[int(2),int(3)],_WF),X=int(4))).
5302
5303
5304 not_is_cartesian_pair((X,Y),XType,YType,WF) :-
5305 not_is_cartesian_pair0(X,Y,XType,YType,WF).
5306
5307 :- block not_is_cartesian_pair0(-,-,?,?,?).
5308 not_is_cartesian_pair0(X,Y,XType,YType,WF) :-
5309 (nonvar(X) -> not_is_cartesian_pair1(X,Y,XType,YType,WF)
5310 ; not_is_cartesian_pair1(Y,X,YType,XType,WF)).
5311
5312 not_is_cartesian_pair1(X,Y,XType,YType,WF) :-
5313 membership_test_wf(XType,X,MemResX,WF),
5314 (var(MemResX) -> membership_test_wf(YType,Y,MemResY,WF) ; true),
5315 not_is_cartesian_pair3(MemResX,X,XType,MemResY,Y,YType,WF).
5316
5317 :- block not_is_cartesian_pair3(-,?,?, -,?,?, ?).
5318 not_is_cartesian_pair3(MemResX,X,XType, MemResY,Y,YType, WF) :-
5319 (MemResX==pred_false -> true
5320 ; MemResY==pred_false -> true
5321 ; MemResX==pred_true -> not_element_of_wf(Y,YType,WF)
5322 ; not_element_of_wf(X,XType,WF)
5323 ).
5324
5325
5326
5327 /***************************/
5328 /* power_set(Set,TypeSet) */
5329 /* Set : POW(TypeSet) */
5330 /***************************/
5331
5332 :- assert_must_succeed(exhaustive_kernel_check(power_set([int(2),int(4)],[[int(2)],
5333 [int(4)],[],[int(4),int(2)]]))).
5334 :- assert_must_succeed(power_set([int(1)],[[int(1)],[]])).
5335 :- assert_must_succeed((power_set([int(1),int(2)],R),
5336 equal_object(R,[[],[int(1)],[int(2)],[int(1),int(2)]]))).
5337 :- assert_must_succeed(power_set([],[[]])).
5338
5339 % not used anymore, except for empty set and singleton sets (see do_not_keep_symbolic_unary)
5340 :- block power_set(-,?).
5341 power_set([],Res) :- !,equal_object_optimized([[]],Res,power_set).
5342 power_set(Set1,Res) :- custom_explicit_sets:singleton_set(Set1,El),!,
5343 equal_object_optimized([[],[El]],Res,power_set).
5344 power_set(S,Res) :-
5345 cardinality_peano_wf(S,Card,no_wf_available),
5346 when(ground(Card), /* when all elements are known */
5347 (expand_custom_set_to_list_wf(S,SE,Done,power_set,no_wf_available),
5348 when(nonvar(Done),
5349 (gen_all_subsets(SE,PowerS),
5350 equal_object_optimized(PowerS,Res,power_set) )
5351 )
5352 )).
5353
5354 :- assert_must_succeed((kernel_objects:gen_all_subsets([X],R), R== [[],[X]])).
5355 :- assert_must_succeed((kernel_objects:gen_all_subsets([X,Y],R), R== [[],[Y],[X],[Y,X]])).
5356 % we do not use findall to keep variable links, see test 2103
5357 gen_all_subsets(List,AllSubLists) :- gen_all_subsets(List,[[]],AllSubLists).
5358 add_el(H,T,[H|T]).
5359 gen_all_subsets([],Acc,Acc).
5360 gen_all_subsets([H|T],Acc,Res) :- gen_all_subsets(T,Acc,R1),
5361 append(R1,R2,Res), % DCG would be better; but power_set is not really used anymore for longer lists
5362 maplist(add_el(H),Acc,Acc2), gen_all_subsets(T,Acc2,R2).
5363
5364
5365 :- assert_must_succeed(exhaustive_kernel_check(non_empty_power_set([int(2),int(4)],[[int(2)],
5366 [int(4)],[int(4),int(2)]]))).
5367 :- assert_must_succeed(non_empty_power_set([int(1)],[[int(1)]])).
5368 :- assert_must_succeed((non_empty_power_set([int(1),int(2)],R),
5369 equal_object(R,[[int(1)],[int(2)],[int(1),int(2)]]))).
5370 :- assert_must_succeed(non_empty_power_set([],[])).
5371
5372 :- block non_empty_power_set(-,?).
5373 non_empty_power_set([],Res) :- !,equal_object_optimized([],Res,non_empty_power_set).
5374 non_empty_power_set(Set1,Res) :- custom_explicit_sets:singleton_set(Set1,El),!,
5375 equal_object_optimized([[El]],Res,non_empty_power_set).
5376 non_empty_power_set(S,Res) :-
5377 cardinality_peano_wf(S,Card,no_wf_available),
5378 when(ground(Card), /* when all elements are known */
5379 (expand_custom_set_to_list_wf(S,SE,Done,non_empty_power_set,no_wf_available),
5380 when(nonvar(Done),
5381 (gen_all_subsets(SE,PowerS),
5382 delete(PowerS,[],NE_PowerS),
5383 equal_object_optimized(NE_PowerS,Res,non_empty_power_set) )
5384 )
5385 )).
5386
5387
5388
5389 /* ------- */
5390 /* BOOLEAN */
5391 /* ------- */
5392
5393 % following predicates are not used:
5394 %is_boolean(pred_true /* bool_true */).
5395 %is_boolean(pred_false /* bool_false */).
5396 %is_not_boolean(X) :- dif(X,pred_true /* bool_true */), dif(X,pred_false /* bool_false */).
5397
5398 /* ------- */
5399 /* NUMBERS */
5400 /* ------- */
5401
5402
5403 is_integer(int(X),_WF) :- when(ground(X),integer(X)).
5404 :- block is_not_integer(-).
5405 is_not_integer(X) :- X \= int(_), % will be called for x /: INTEGER; should always fail.
5406 add_internal_error('Wrong type argument: ',is_not_integer(X)),fail.
5407
5408 is_natural(int(X),_WF) :- clpfd_geq2(X,0,Posted), (Posted==true -> true ; number_geq(X,0)).
5409 is_natural1(int(X),_WF) :- clpfd_geq2(X,1,Posted), (Posted==true -> true ; number_geq(X,1)).
5410 :- block number_geq(-,?).
5411 number_geq(X,N) :- X>=N.
5412 :- block number_leq(-,?).
5413 number_leq(X,N) :- X=<N.
5414
5415 :- assert_must_succeed(is_implementable_int(int(0),_WF)).
5416 :- assert_must_fail(is_not_implementable_int(int(0))).
5417
5418
5419 is_implementable_int(int(X),WF) :- element_of_global_integer_set_wf('INT',X,WF,unkmown).
5420 is_implementable_nat(int(X),WF) :- element_of_global_integer_set_wf('NAT',X,WF,unknown).
5421 is_implementable_nat1(int(X),WF) :- element_of_global_integer_set_wf('NAT1',X,WF,unknown).
5422 is_not_implementable_int(X) :- not_element_of_global_set(X,'INT').
5423 is_not_implementable_nat(X) :- not_element_of_global_set(X,'NAT').
5424 is_not_implementable_nat1(X) :- not_element_of_global_set(X,'NAT1').
5425
5426 is_not_natural(int(X)) :- clpfd_geq2(-1,X,Posted), (Posted=true -> true ; number_leq(X,-1)).
5427 is_not_natural1(int(X)) :- clpfd_geq2(0,X,Posted), (Posted==true -> true ; number_leq(X,0)).
5428
5429 :- assert_must_succeed(exhaustive_kernel_check(less_than(int(2),int(3)))).
5430 :- assert_must_succeed(( safe_less_than(A,B),A=3,B=5 )).
5431 :- assert_must_succeed(( safe_less_than(A,B),B=5,A=3 )).
5432 :- assert_must_fail(( safe_less_than(A,B),A=5,B=3 )).
5433 :- assert_must_fail(( safe_less_than(A,B),B=3,A=5 )).
5434 :- assert_must_fail(( safe_less_than(A,B),A=5,B=5 )).
5435 :- assert_must_fail(( safe_less_than(A,B),B=5,A=5 )).
5436
5437 less_than(int(X),int(Y)) :-
5438 (number(X),number(Y) -> X < Y
5439 ; clpfd_lt(X,Y,Posted),
5440 (Posted=true -> true ; safe_less_than(X,Y))).
5441 less_than_direct(X,Y) :-
5442 (number(X),number(Y) -> X < Y
5443 ? ; clpfd_lt(X,Y,Posted),
5444 (Posted=true -> true ; safe_less_than(X,Y))).
5445 :- block safe_less_than(-,?), safe_less_than(?,-).
5446 safe_less_than(X,Y) :-
5447 (number(X),number(Y) -> X<Y
5448 ; add_internal_error('Arguments not numbers: ',safe_less_than(X,Y))).
5449
5450 :- assert_must_succeed(exhaustive_kernel_check(less_than_equal(int(33),int(33)))).
5451 less_than_equal(int(X),int(Y)) :-
5452 (number(X),number(Y) -> X =< Y
5453 ; clpfd_leq(X,Y,Posted),
5454 (Posted=true -> true ; safe_less_than_equal(less_than_equal,X,Y))).
5455 less_than_equal_direct(X,Y) :-
5456 (number(X),number(Y) -> X =< Y
5457 ? ; clpfd_leq(X,Y,Posted),
5458 (Posted=true -> true ; safe_less_than_equal(less_than_equal_direct,X,Y))).
5459
5460 safe_less_than_equal(X,Y) :-
5461 safe_less_than_equal(safe_less_than_equal,X,Y).
5462 :- block safe_less_than_equal(?,-,?), safe_less_than_equal(?,?,-).
5463 safe_less_than_equal(PP,X,Y) :-
5464 (number(X),number(Y) -> X=<Y
5465 ; add_internal_error('Arguments not numbers: ',safe_less_than_equal(PP,X,Y))).
5466
5467 :- assert_must_succeed(exhaustive_kernel_check(greater_than(int(2),int(1)))).
5468 :- assert_must_succeed(exhaustive_kernel_fail_check(greater_than(int(2),int(2)))).
5469 greater_than(int(X),int(Y)) :- less_than_direct(Y,X).
5470 :- assert_must_succeed(exhaustive_kernel_check(greater_than(int(2),int(1)))).
5471 :- assert_must_succeed(exhaustive_kernel_check(greater_than_equal(int(2),int(2)))).
5472 :- assert_must_succeed(exhaustive_kernel_fail_check(greater_than_equal(int(1),int(2)))).
5473 greater_than_equal(int(X),int(Y)) :- less_than_equal_direct(Y,X).
5474
5475
5476
5477
5478
5479 :- assert_must_succeed(exhaustive_kernel_check([commutative],int_plus(int(2),int(3),int(5)))).
5480 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],int_plus(int(2),int(3),int(6)))).
5481
5482 :- assert_must_succeed(int_plus(int(1),int(2),int(3))).
5483 :- assert_must_succeed(( int_plus2(A,B,C),A=3,B=2,C==5 )).
5484 :- assert_must_succeed(( int_plus2(A,B,C),A=3,C=5,B==2 )).
5485 :- assert_must_succeed(( int_plus2(A,B,C),B=2,A=3,C==5 )).
5486 :- assert_must_succeed(( int_plus2(A,B,C),B=2,C=5,A==3 )).
5487 :- assert_must_succeed(( int_plus2(A,B,C),C=5,A=3,B==2 )).
5488 :- assert_must_succeed(( int_plus2(A,B,C),C=5,B=2,A==3 )).
5489 :- assert_must_succeed(( int_plus2(A,B,C),A=0,B==C )).
5490 :- assert_must_succeed(( int_plus2(A,B,C),B=0,A==C )).
5491
5492 int_plus(int(X),int(Y),int(Plus)) :-
5493 ? (two_vars_or_more(X,Y,Plus)
5494 ? -> clpfd_eq(Plus,X+Y) % can have performance problems
5495 ; true % otherwise we can compute the value directly below; we could skip the block declaration
5496 ),
5497 ? int_plus2(X,Y,Plus).
5498 two_vars_or_more(X,Y,Z) :- var(X),!, (var(Y) ; var(Z)).
5499 two_vars_or_more(_X,Y,Z) :- var(Y) , var(Z).
5500
5501 :- block int_plus2(-,-,-).
5502 int_plus2(X,Y,Plus) :-
5503 ? ( ground(X) -> int_plus3(X,Y,Plus)
5504 ; ground(Y) -> int_plus3(Y,X,Plus)
5505 ; int_minus3(Plus,X,Y)).
5506
5507 % int_plus3/3: the first argument must be ground when called
5508 int_plus3(0,Y,Plus) :- !, Y=Plus. % not inferred by CLP(FD): Z #= Y+X, X=0. does not infer Y==Z
5509 int_plus3(X,Y,Plus) :- % integer_dif(Y,Plus), % this generates overflows for test 1353, 1014
5510 ? int_plus4(X,Y,Plus).
5511
5512 % int_plus4/3: the first argument must be ground when called
5513 :- block int_plus4(?,-,-).
5514 int_plus4(X,Y,Plus) :-
5515 ( var(Plus) -> Plus is X+Y
5516 ; Y is Plus-X).
5517
5518 :- assert_must_succeed(exhaustive_kernel_check(int_minus(int(2),int(3),int(-1)))).
5519 :- assert_must_succeed(exhaustive_kernel_fail_check(int_minus(int(2),int(3),int(1)))).
5520 :- assert_must_succeed(int_minus(int(3),int(1),int(2))).
5521 :- assert_must_succeed(( int_minus2(A,B,C),A=3,B=2,C==1 )).
5522 :- assert_must_succeed(( int_minus2(A,B,C),A=3,C=1,B==2 )).
5523 :- assert_must_succeed(( int_minus2(A,B,C),B=2,A=3,C==1 )).
5524 :- assert_must_succeed(( int_minus2(A,B,C),B=2,C=1,A==3 )).
5525 :- assert_must_succeed(( int_minus2(A,B,C),C=1,A=3,B==2 )).
5526 :- assert_must_succeed(( int_minus2(A,B,C),C=1,B=2,A==3 )).
5527 :- assert_must_succeed(( int_minus2(A,B,C),B=0,A==C )).
5528 :- assert_must_succeed(( int_minus2(A,B,C),B=0,C=5,A==5 )).
5529 :- assert_must_succeed(( int_minus2(A,B,5),B=0,A==5 )).
5530
5531 int_minus(int(X),int(Y),int(Minus)) :-
5532 int_minus2(X,Y,Minus),
5533 ? (two_vars_or_more(X,Y,Minus) -> clpfd_eq(Minus,X-Y) % can have performance problems.
5534 % we could also set Minus to 0 if X==Y; this is done in CHR (chr_integer_inequality)
5535 ; true). % we can compute the value directly anyway
5536 :- block int_minus2(-,-,-).
5537 int_minus2(X,Y,Minus) :-
5538 ( ground(Y) ->
5539 ( Y=0 -> X=Minus
5540 ; Y2 is -Y, int_plus3(Y2,X,Minus))
5541 ; ground(X) ->
5542 int_minus3(X,Y,Minus)
5543 ; int_plus3(Minus,Y,X) % will infer that Y=X if Minus=0
5544 ).
5545
5546 % int_minus3/3: the first argument must be ground when called
5547 :- block int_minus3(?,-,-).
5548 int_minus3(X,Y,Minus) :-
5549 ( var(Minus) -> Minus is X-Y
5550 ; Y is X-Minus).
5551
5552 :- assert_must_succeed(exhaustive_kernel_check(division(int(2),int(3),int(0),unknown,_WF))).
5553 :- assert_must_succeed(exhaustive_kernel_check(division(int(7),int(2),int(3),unknown,_WF))).
5554 :- assert_must_succeed(exhaustive_kernel_check(division(int(8),int(2),int(4),unknown,_WF))).
5555 :- assert_must_succeed(exhaustive_kernel_check(division(int(9),int(2),int(4),unknown,_WF))).
5556 :- assert_must_succeed(exhaustive_kernel_check(division(int(2),int(-1),int(-2),unknown,_WF))).
5557 :- assert_must_succeed(exhaustive_kernel_check(division(int(9),int(-2),int(-4),unknown,_WF))).
5558 :- assert_must_succeed(exhaustive_kernel_check(division(int(-9),int(-3),int(3),unknown,_WF))).
5559 :- assert_must_succeed(exhaustive_kernel_check(division(int(-1),int(4),int(0),unknown,_WF))).
5560 :- assert_must_succeed((platform_is_64_bit
5561 -> exhaustive_kernel_check(division(int(4294967296),int(2),int(2147483648),unknown,_WF))
5562 ; exhaustive_kernel_check(division(int(134217728),int(2),int(67108864),unknown,_WF)))).
5563 :- assert_must_succeed((platform_is_64_bit
5564 -> exhaustive_kernel_check(division(int(4294967296),int(2147483648),int(2),unknown,_WF))
5565 ; exhaustive_kernel_check(division(int(134217728),int(67108864),int(2),unknown,_WF)))).
5566 :- assert_must_succeed(exhaustive_kernel_fail_check(division(int(2),int(3),int(1),unknown,_WF))).
5567 :- assert_must_succeed(( division3(A,B,C,unknown,_),A=15,B=4,C==3 )).
5568 :- assert_must_succeed(( division3(A,B,C,unknown,_),B=4,A=15,C==3 )).
5569
5570 division(int(X),int(Y),int(XDY),Span,WF) :- var(Y), (var(X) ; var(XDY)),
5571 preferences:preference(use_clpfd_solver,true),!,
5572 (preferences:preference(disprover_mode,true)
5573 -> clpfd_eq_div(XDY,X,Y) /* we can assume well-definedness */
5574 ; clpfd_eq_guarded_div(XDY,X,Y),
5575 % TO DO: we could set up a choice point just before enumeration of infinite types for Y=0 & Y/=0;
5576 % same for modulo
5577 check_nonzero(X,Y,XDY,Span,WF)
5578 ).
5579 division(int(X),int(Y),int(XDY),Span,WF) :-
5580 %% clpfd_eq_expr(XDY,X/Y), % can have performance problems; could hide division by 0 !
5581 division3(X,Y,XDY,Span,WF).
5582
5583 :- block check_nonzero(?,-,?,?,?).
5584 check_nonzero(X,Y,XDY,Span,WF) :-
5585 (Y=0 -> add_wd_error_set_result('division by zero','/'(X,Y),XDY,0,Span,WF)
5586 ; true).
5587
5588 :- block division3(?,-,?,?,?).
5589 division3(X,Y,XDY,Span,WF) :-
5590 ( Y==0 -> add_wd_error_set_result('division by zero','/'(X,Y),XDY,0,Span,WF)
5591 ; nonvar(X) -> XDY is X // Y
5592 ; Y == 1 -> X=XDY
5593 ; Y == -1,nonvar(XDY) -> X is -XDY
5594 ; clpfd_eq_div(XDY,X,Y)). % we could setup constraint before Y is known; could hide division by 0 ?
5595
5596
5597
5598 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(2),int(3),int(0),unknown,_WF))).
5599 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(7),int(2),int(3),unknown,_WF))).
5600 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(-1),int(4),int(-1),unknown,_WF))).
5601 :- assert_must_succeed(exhaustive_kernel_check(floored_division(int(-9),int(-3),int(3),unknown,_WF))).
5602 floored_division(int(X),int(Y),int(XDY),Span,WF) :- var(Y), (var(X) ; var(XDY)),
5603 preferences:preference(use_clpfd_solver,true),!,
5604 (preferences:preference(disprover_mode,true)
5605 -> clpfd_eq_fdiv(XDY,X,Y) /* we can assume well-definedness */
5606 ; clpfd_eq_guarded_fdiv(XDY,X,Y),
5607 check_nonzero(X,Y,XDY,Span,WF)
5608 ).
5609 floored_division(int(X),int(Y),int(XDY),Span,WF) :-
5610 %% clpfd_eq_expr(XDY,X/Y), % can have performance problems; could hide division by 0 !
5611 floored_division3(X,Y,XDY,Span,WF).
5612 :- block floored_division3(?,-,?,?,?).
5613 floored_division3(X,Y,XDY,Span,WF) :-
5614 ( Y==0 -> add_wd_error_set_result('division by zero','/'(X,Y),XDY,0,Span,WF)
5615 ; nonvar(X) -> XDY is X div Y
5616 ; Y == 1 -> X=XDY
5617 ; (Y == -1,nonvar(XDY)) -> X is -XDY
5618 ; clpfd_eq_guarded_fdiv(XDY,X,Y)). % we could setup constraint before Y is known; could hide division by 0 ?
5619
5620 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(2),int(3),int(2),unknown,WF),WF)).
5621 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(7),int(2),int(1),unknown,WF),WF)).
5622 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(8),int(2),int(0),unknown,WF),WF)).
5623 :- assert_must_succeed(exhaustive_kernel_check_wfdet(modulo(int(9),int(2),int(1),unknown,WF),WF)).
5624 :- assert_must_succeed((platform_is_64_bit
5625 -> exhaustive_kernel_check_wfdet(modulo(int(4294967296),int(2147483648),int(0),unknown,WF),WF)
5626 ; exhaustive_kernel_check_wfdet(modulo(int(134217728),int(67108864),int(0),unknown,WF),WF))).
5627 :- assert_must_succeed((platform_is_64_bit
5628 -> exhaustive_kernel_check_wfdet(modulo(int(4294967299),int(2147483648),int(3),unknown,WF),WF)
5629 ; exhaustive_kernel_check_wfdet(modulo(int(134217731),int(67108864),int(3),unknown,WF),WF))).
5630 :- assert_must_succeed(( modulo2(A,B,C,unknown,_),A=7,B=5,C==2 )).
5631 :- assert_must_fail(( modulo2(A,B,C,unknown,_),A=7,B=5,C==3 )).
5632
5633 modulo(int(X),int(Y),int(Modulo),Span,WF) :-
5634 %% clpfd_eq(Modulo,X mod Y), % can have performance problems; could hide division by 0 !
5635 modulo2(X,Y,Modulo,Span,WF),
5636 % assert that Modulo<Y, Modulo>=0
5637 (nonvar(X),nonvar(Y) -> true % we already have computed Modulo using modulo2
5638 ; nonvar(Modulo), Modulo < 0 -> true % we will generate well-definedness error; see comment next line
5639 ; number(Y),Y =< 0 -> true % in this case we will generate a well-definedness error; it would be more efficient from a constraint solving perspective to assume that there are no well-definedness errors and remove this case !!
5640 ; clpfd_modulo_prop(X,Y,Modulo,WF)
5641 ).
5642 :- use_module(specfile,[z_or_tla_minor_mode/0]).
5643 :- block modulo2(-,?,?,?,?), modulo2(?,-,?,?,?).
5644 modulo2(X,Y,Modulo,Span,WF) :-
5645 ( Y>0 -> (X<0 -> (z_or_tla_minor_mode -> Modulo is X mod Y
5646 ; add_wd_error_set_result('mod not defined for negative numbers in B:',mod(X,Y),Modulo,0,Span,WF))
5647 ; Modulo is X mod Y)
5648 ; Y==0 -> add_wd_error_set_result('mod by zero:',mod(X,Y),Modulo,0,Span,WF)
5649 ; Y<0 -> add_wd_error_set_result('mod not defined for negative numbers:',mod(X,Y),Modulo,0,Span,WF)). % there seems to be a definition in Z ? at least for Z Live ?
5650
5651 % propagate information about Modulo result if part of the information known
5652 clpfd_modulo_prop(X,Y,Modulo,WF) :- %preferences:preference(use_clpfd_solver,true),!,
5653 % in CLP(FD) this is sufficient; for non-CLPFD mode it is better to call in_nat_range to restrict enumeration
5654 less_than_direct(Modulo,Y),
5655 less_than_equal_direct(0,Modulo), % 0 <= Modulo < Y -> by transitivity this forces Y>0 and we no longer detect wd-errors
5656 %less_than_equal_direct(Modulo,X). % by transitivity this imposes X >= 0 and we will never find WD problems with negative X
5657 (preference(use_clpfd_solver,true)
5658 -> get_wait_flag0(WF,WF0),
5659 % avoid propagating complex too early, e.g., for x>2 & x:3..10 & x mod 3 = 1 & x mod 3 = 2 in test 2126
5660 % also see test 1959 which was initially failing due to adding WF0 delay
5661 clpfd_modulo_prop2(X,Y,Modulo,WF0)
5662 ; true).
5663
5664 :- block clpfd_modulo_prop2(?,?,?,-).
5665 clpfd_modulo_prop2(X,Y,Modulo,_WF0) :-
5666 number(Modulo), % this test is required for test 1009, 417 : TO DO : investigate cause
5667 var(X), % or should this be var(X) ; var(Y) ??
5668 fd_min(Y,MinY), number(MinY), MinY>0,
5669 fd_min(X,MinX), number(MinX), MinX>=0, % modulo is well-defined
5670 !,
5671 clpfd_interface:clpfd_leq_expr(Modulo,X),
5672 clpfd_interface:try_post_constraint(Modulo #= X mod Y).
5673 %clpfd_modulo_prop2(X,Y,Modulo,_WF0) :- number(Y),!,
5674 % % also makes tests 1009, 417 fail, but would enable solving x mod 256 = 0 & x>0
5675 % clpfd_interface:try_post_constraint(X#>=0 #=> Modulo #= X mod Y). % will also assert X#>Modulo
5676 clpfd_modulo_prop2(X,_Y,_Modulo,_WF0) :- X==0,!. % no need to propagate, we already assert 0 <= Modulo above
5677 clpfd_modulo_prop2(X,_Y,Modulo,_WF0) :-
5678 clpfd_interface:try_post_constraint(X#>=0 #=> X#>=Modulo). % this would be faster (e.g., {y|y:100000..200000 & y mod 2 = 0}), but would not catch some WD errors: clpfd_interface:try_post_constraint(X#>=Modulo).
5679 % we could reify: Y>0 => Modulo <Y ? Is it worth it ?
5680 % we could also use the CLP(FD) modulo operator X in 3..100, 1 #= X mod 20 infers X in 21..81
5681 % try_post_constraint((X#>=0 #/\ Y#>0) #=> Modulo #= X mod Y)
5682 % what is still missing is that if Y < Modulo => X=Y (CLP(FD) does this X in 0..100 , Y in 2..20 , X #= Y mod 30.)
5683 /* clpfd_modulo_prop(X,Y,Modulo,WF) :- clpfd_modulo_noclp(X,Y,Modulo,WF).
5684 :- block clpfd_modulo_noclp(-,-,-,?).
5685 clpfd_modulo_noclp(X,Y,Modulo,WF) :- print(mod(X,Y,Modulo,WF)),nl,
5686 var(X),var(Modulo),number(Y),!,
5687 Y1 is Y-1,
5688 in_nat_range_wf(int(Modulo),int(0),int(Y1),WF). % problem: could enumerate lambda return variables !!
5689 clpfd_modulo_noclp(_X,_Y,_Modulo,_WF).
5690 */
5691
5692
5693 :- assert_must_succeed(exhaustive_kernel_check(unary_minus_wf(int(2),int(-2),_WF))).
5694 :- assert_must_succeed(exhaustive_kernel_fail_check(unary_minus_wf(int(2),int(2),_WF))).
5695 :- assert_must_succeed(( unary_minus2(A,B),A=7,B== -7 )).
5696 :- assert_must_succeed(( unary_minus2(A,B),A= -7,B==7 )).
5697 :- assert_must_succeed(( unary_minus2(B,A),A=7,B== -7 )).
5698 :- assert_must_succeed(( unary_minus2(B,A),A= -7,B==7 )).
5699 :- assert_must_fail(( unary_minus2(B,A),A= -7,B=6 )).
5700 :- assert_must_fail(( unary_minus2(A,B),A= -7,B=6 )).
5701
5702 unary_minus_wf(int(X),int(MX),_WF) :-
5703 unary_minus2(X,MX),
5704 (var(X),var(MX) -> clpfd_eq(MX,0 - X) % can have performance problems
5705 ; true % we can compute the value without CLPFD
5706 ).
5707 :- block unary_minus2(-,-).
5708 unary_minus2(X,MX) :-
5709 ( ground(X) -> MX is -X
5710 ; X is -MX).
5711
5712 :- assert_must_succeed(first_of_pair((int(1),int(2)),int(1))).
5713 :- assert_must_succeed(second_of_pair((int(1),int(2)),int(2))).
5714
5715 first_of_pair((A,_B),R) :- equal_object(R,A,first_of_pair).
5716 second_of_pair((_A,B),R) :- equal_object(R,B,second_of_pair).
5717
5718
5719 :- assert_must_succeed(exhaustive_kernel_check(cartesian_product([int(2),int(4)],[int(3),int(1)],
5720 [(int(2),int(1)),(int(2),int(3)),(int(4),int(3)),(int(4),int(1))]))).
5721 :- assert_must_succeed(exhaustive_kernel_check(cartesian_product([],[int(3),int(1)],[]))).
5722 :- assert_must_succeed(exhaustive_kernel_check(cartesian_product([int(3)],[],[]))).
5723 :- assert_must_succeed(exhaustive_kernel_fail_check(cartesian_product([int(3)],[int(2)],[]))).
5724 :- assert_must_succeed((cartesian_product(global_set('NAT'),[int(2)],_Res))).
5725 :- assert_must_succeed((cartesian_product([int(1)],[int(2)],Res),
5726 equal_object(Res,[(int(1),int(2))]))).
5727 :- assert_must_succeed((cartesian_product([int(1)],[int(2)],[(int(1),int(2))]))).
5728 :- assert_must_succeed((cartesian_product([],[int(1),int(2)],Res),
5729 equal_object(Res,[]))).
5730 :- assert_must_succeed((cartesian_product([int(1),int(2)],[],Res),
5731 equal_object(Res,[]))).
5732 :- assert_must_succeed((cartesian_product([int(1),int(2)],[int(2),int(3)],Res),
5733 equal_object(Res,[(int(1),int(2)),(int(1),int(3)),(int(2),int(2)),(int(2),int(3))]))).
5734 :- assert_must_succeed((cartesian_product([int(1)|T],[int(2)|T2],Res),
5735 T = [int(2)], T2 = [int(3)],
5736 equal_object(Res,[(int(1),int(2)),(int(1),int(3)),(int(2),int(2)),(int(2),int(3))]))).
5737 :- assert_must_fail((cartesian_product([int(1)],[int(2),int(3)],Res),(Res=[_];
5738 equal_object(Res,[_,_,_|_])))).
5739
5740
5741 cartesian_product(Set1,Set2,Res) :- cartesian_product_wf(Set1,Set2,Res,no_wf_available).
5742
5743 :- block cartesian_product_wf(-,?,?,?), cartesian_product_wf(?,-,?,?).
5744 cartesian_product_wf(Set1,Set2,Res,WF) :-
5745 expand_custom_set_to_list_wf(Set1,ESet1,_,cartesian_product1,WF),
5746 (ESet1==[] -> empty_set_wf(Res,WF)
5747 ; expand_custom_set_to_list_wf(Set2,ESet2,_,cartesian_product2,WF),
5748 (var(Res)
5749 -> cartesian_product2(ESet1,ESet2,CRes,WF),
5750 equal_object_optimized_wf(CRes,Res,cart_product,WF)
5751 ; cartesian_product2(ESet1,ESet2,Res,WF))
5752 ).
5753
5754 :- block cartesian_product2(-,?,?,?).
5755 cartesian_product2([],_,Res,WF) :- empty_set_wf(Res,WF).
5756 cartesian_product2([H|T],Set2,Res,WF) :-
5757 cartesian_el_product(Set2,H,Res,InnerRes,WF),
5758 cartesian_product2(T,Set2,InnerRes,WF).
5759
5760 :- block cartesian_el_product(-,?,?,?,?).
5761 cartesian_el_product([],_El,Res,InnerRes,WF) :- equal_object_optimized_wf(Res,InnerRes,cartesian_el_product_1,WF).
5762 cartesian_el_product([H|T],El,ResSoFar,InnerRes,WF) :-
5763 equal_object_wf(ResSoFar,[(El,H)|NewResSoFar],cartesian_el_product_2,WF),
5764 cartesian_el_product(T,El,NewResSoFar,InnerRes,WF).
5765
5766
5767
5768 :- assert_must_succeed(exhaustive_kernel_check(in_nat_range(int(2),int(2),int(3)))).
5769 :- assert_must_succeed(exhaustive_kernel_check(in_nat_range_wf(int(2),int(2),int(3),_WF))).
5770 :- assert_must_succeed(exhaustive_kernel_fail_check(in_nat_range_wf(int(2),int(3),int(2),_WF))).
5771 :- assert_must_succeed((in_nat_range_wf(X,int(11),int(12),WF),
5772 kernel_waitflags:ground_wait_flags(WF), X==int(12) )).
5773 :- assert_must_fail((in_nat_range_wf(X,int(11),int(12),_WF), X=int(10) )).
5774 :- assert_must_fail((in_nat_range_wf(X,int(11),int(12),_WF), X=int(13) )).
5775 :- assert_must_succeed((in_nat_range_wf(X,int(11),int(12),_WF), X=int(11) )).
5776 :- assert_must_fail((in_nat_range_wf(X,int(11),int(10),_WF), X=int(11) )).
5777 :- assert_must_fail((in_nat_range_wf(X,int(11),int(10),_WF), X=int(10) )).
5778 :- assert_must_fail((in_nat_range_wf(X,int(11),int(10),_WF), X=int(12) )).
5779
5780 in_nat_range(int(X),int(Y),int(Z)) :- % does not enumerate, in contrast to in_nat_range_wf
5781 clpfd_inrange(X,Y,Z,Posted), % better to call inrange rather than leq twice, avoids unecessary propagation
5782 (Posted==true -> true
5783 ; safe_less_than_equal(in_nat_range,Y,X),
5784 safe_less_than_equal(in_nat_range,X,Z)
5785 ).
5786 in_nat_range_wf(int(X),int(Y),int(Z),WF) :-
5787 ? clpfd_inrange(X,Y,Z,Posted), % better to call inrange rather than leq twice, avoids unecessary propagation
5788 (Posted==true ->
5789 /* if the constraint was posted: we do not need to add safe_less_than_equal,...: if overflow happes whole computation will fail anyway */
5790 add_nat_range_fd_variable_for_labeling(X,Y,Z,WF) % do we really need to do this ? maybe add just before enumeration finished ?
5791 ; safe_less_than_equal(in_nat_range_wf,Y,X),
5792 safe_less_than_equal(in_nat_range_wf,X,Z),
5793 (ground(X) -> true
5794 ; get_int_domain(X,Y,Z,RL,RU),get_nat_range_prio(X,RL,RU,WF,LWF),
5795 call_enumerate_int(X,RL,RU,LWF))
5796 ).
5797 % when((ground(X);nonvar(LWF)),(ground(X) -> true ; enumerate_int(X,RL,RU))).
5798
5799 add_nat_range_fd_variable_for_labeling(X,_Low,_Up,_WF) :- nonvar(X),!.
5800 % TO DO: avoid adding useless choice points; not adding makes test 328 fail
5801 %add_nat_range_fd_variable_for_labeling(X,Low,Up,WF) :- !,Size is 100*(Up+1-Low),
5802 % get_wait_flag(Size,add_nat_range_fd(X,Low,Up),WF,LWF), when(nonvar(LWF),add_fd_variable_for_labeling(X,WF)).
5803 add_nat_range_fd_variable_for_labeling(_X,Low,Up,_WF) :-
5804 (var(Low) ; var(Up)),!. % domain is not yet bounded; should we delay/block until Low and Up are known?
5805 add_nat_range_fd_variable_for_labeling(X,_Low,_Up,WF) :- !,add_fd_variable_for_labeling(X,WF).
5806
5807
5808 :- block get_nat_range_prio(?,-,?,?,?), get_nat_range_prio(?,?,-,?,?).
5809 get_nat_range_prio(_Variable,Y,Z,WF,LWF) :- Size is Z+1-Y,
5810 (Size>1 ->
5811 % we do not use add_fd_variable_for_labeling(Variable,Size,WF,LWF) % will use CLP(FD) labeling
5812 % either clpfd is off or we had a time-out or overflow; so labeling may generate instantiation error
5813 get_wait_flag(Size,get_nat_range_prio(Y,Z),WF,LWF)
5814 ; LWF=Size /* Size=0 or 1 -> we can either fail or determine variable */).
5815
5816 :- assert_must_succeed((kernel_objects:call_enumerate_int(X,1,2,g), X==2)).
5817 :- block call_enumerate_int(-,?,?,-).
5818 call_enumerate_int(X,RL,RU,_LWF) :-
5819 (ground(X) -> true
5820 ; % get_int_domain(X,RL,RU,RLL,RUU) : if clp(fd) active then CLP(FD) labeling is used anyway
5821 ? enumerate_int(X,RL,RU)).
5822
5823
5824
5825
5826 :- assert_must_succeed(exhaustive_kernel_check(not_in_nat_range(int(2),int(3),int(2)))).
5827 :- assert_must_succeed(exhaustive_kernel_fail_check(not_in_nat_range(int(2),int(2),int(3)))).
5828 :- assert_must_succeed((not_in_nat_range(X,int(11),int(12)), X=int(10) )).
5829 :- assert_must_succeed((not_in_nat_range(X,int(11),int(12)), X=int(13) )).
5830 :- assert_must_fail((not_in_nat_range(X,int(11),int(12)), X=int(11) )).
5831 :- assert_must_succeed((not_in_nat_range(X,int(11),int(10)), X=int(11) )).
5832 :- assert_must_succeed((not_in_nat_range(X,int(11),int(10)), X=int(10) )).
5833 :- assert_must_succeed((not_in_nat_range(X,int(11),int(10)), X=int(12) )).
5834
5835 ?not_in_nat_range_wf(X,Y,Z,_WF) :- not_in_nat_range(X,Y,Z).
5836 not_in_nat_range(int(X),int(Y),int(Z)) :-
5837 (number(Y),number(Z)
5838 ? -> (Z>=Y -> clpfd_not_in_non_empty_range(X,Y,Z) ; true /* interval empty */)
5839 ; clpfd_not_inrange(X,Y,Z)
5840 ).
5841
5842
5843 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(1),int(0),int(10),pred_true,WF),WF)).
5844 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(10),int(10),int(10),pred_true,WF),WF)).
5845 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(1),int(1),int(10),pred_true,WF),WF)).
5846 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(10),int(0),int(10),pred_true,WF),WF)).
5847 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(11),int(10),int(9),pred_false,WF),WF)).
5848 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(11),int(13),int(12),pred_false,WF),WF)).
5849 :- assert_must_succeed(exhaustive_kernel_check_wf(test_in_nat_range_wf(int(11),int(13),int(15),pred_false,WF),WF)).
5850
5851 % reified version
5852 :- block test_in_nat_range_wf(-,-,?,-,?), test_in_nat_range_wf(-,?,-,-,?), test_in_nat_range_wf(?,-,-,-,?).
5853 test_in_nat_range_wf(X,Y,Z,PredRes,WF) :- PredRes==pred_true,!,
5854 in_nat_range_wf(X,Y,Z,WF).
5855 test_in_nat_range_wf(X,Y,Z,PredRes,WF) :- PredRes==pred_false,!,
5856 not_in_nat_range_wf(X,Y,Z,WF).
5857 test_in_nat_range_wf(int(X),int(Low),int(Up),PredRes,WF) :-
5858 clpfd_interface:post_constraint2(C1 #<=> (X #>= Low #/\ X #=< Up #/\ Low #=< Up),Posted1),
5859 (Posted1 == true -> prop_01(C1,PredRes) ; test_in_nat_range_no_clpfd(X,Low,Up,PredRes,WF)).
5860
5861 % Note: A #<=> (X #>= Low #/\ X#=< Up #/\ Low #=< Up), Low in 11..15, Up in 7..8. -> CLPFD infers A=0
5862 % without the redundant Low #=< Up it does not infer it !
5863 :- block prop_01(-,-).
5864 prop_01(0,pred_false).
5865 prop_01(1,pred_true).
5866
5867 :- block test_in_nat_range_no_clpfd(-,?,?,-,?), test_in_nat_range_no_clpfd(?,-,?,-,?),
5868 test_in_nat_range_no_clpfd(?,?,-,-,?).
5869 test_in_nat_range_no_clpfd(X,Y,Z,PredRes,WF) :- PredRes==pred_true,!,
5870 in_nat_range_wf(int(X),int(Y),int(Z),WF).
5871 test_in_nat_range_no_clpfd(X,Y,Z,PredRes,WF) :- PredRes==pred_false,!,
5872 not_in_nat_range_wf(int(X),int(Y),int(Z),WF).
5873 test_in_nat_range_no_clpfd(X,Y,Z,PredRes,_WF) :- % X,Y,Z must be ground integers
5874 (X >= Y, X =< Z, Y =< Z -> PredRes=pred_true ; PredRes=pred_false).
5875
5876 :- assert_must_succeed(exhaustive_kernel_check_wf(square(int(3),int(9),WF),WF)).
5877 % is now only called when CLPFD is FALSE
5878 square(int(X),int(Sqr),WF) :-
5879 int_square(X,Sqr,WF),
5880 (var(X) -> clpfd_eq(Sqr,X * X)
5881 ; true). % we can compute the value directly
5882
5883 :- block int_square(-,-,?).
5884 int_square(X,Sqr,_) :- ground(X),!, Sqr is X*X.
5885 int_square(X,Sqr,WF) :- get_binary_choice_wait_flag(int_square,WF,WF2), int_square2(X,Sqr,WF2).
5886 :- block int_square2(-,?,-).
5887 int_square2(X,Sqr,_) :- ground(X),!, Sqr is X*X.
5888 int_square2(X,Sqr,_WF2) :-
5889 ? integer_square_root(Sqr,X).
5890
5891 :- assert_must_succeed(( kernel_objects:integer_square_root(0,X),X==0 )).
5892 :- assert_must_succeed(( kernel_objects:integer_square_root(1,X),X==1 )).
5893 :- assert_must_succeed(( kernel_objects:integer_square_root(4,X),X==2 )).
5894 :- assert_must_succeed(( kernel_objects:integer_square_root(49,X),X==7 )).
5895 :- assert_must_succeed(( kernel_objects:integer_square_root(49,X),X==(-7) )).
5896 :- assert_must_fail(( kernel_objects:integer_square_root(5,_) )).
5897 :- assert_must_succeed(( X= 123456789, Y is X*X, kernel_objects:integer_square_root(Y,Z),Z==X)).
5898 :- assert_must_fail(( X= 123456789, Y is 1+X*X, kernel_objects:integer_square_root(Y,_Z))).
5899 :- assert_must_succeed(( X= 12345678900, Y is X*X, kernel_objects:integer_square_root(Y,Z),Z==X)).
5900
5901 integer_square_root(0,Root) :- !, Root = 0.
5902 :- if(current_prolog_flag(dialect, swi)).
5903 % SWI's behavior when converting bigint to float is suboptimal -
5904 % the value is always truncated toward zero instead of rounded to the nearest value,
5905 % which introduces slight inaccuracies that don't happen on SICStus.
5906 % See: https://github.com/SWI-Prolog/swipl-devel/issues/545
5907 % As a workaround, use CLP(FD) to calculate integer square roots.
5908 % On SWI, CLP(FD) works with unlimited size integers and can calculate exact integer n-th roots.
5909 :- use_module(library(clpfd), [(#=)/2, (#>)/2, (#=<)/2]).
5910 integer_square_root(Sqr,Root) :-
5911 Root*Root #= Sqr,
5912 (Root #> 0 ; Root #=< 0).
5913 :- else.
5914 integer_square_root(Sqr,PMRoot) :-
5915 Sqr>0, Root is truncate(sqrt(Sqr)), Sqr is Root*Root,
5916 (PMRoot = Root ; PMRoot is -(Root)).
5917 :- endif.
5918
5919 % integer multiplication
5920 times(int(X),int(Y),int(Times)) :-
5921 int_times2(X,Y,Times),
5922 ? (two_vars_or_more(X,Y,Times) -> clpfd_eq(Times,X * Y) % can have performance problems.
5923 ; true). % we can compute the value directly
5924
5925 :- assert_must_succeed(exhaustive_kernel_check([commutative],times(int(2),int(3),int(6)))).
5926 :- assert_must_succeed(exhaustive_kernel_check([commutative],times(int(2),int(1),int(2)))).
5927 :- assert_must_succeed(exhaustive_kernel_check([commutative],times(int(2),int(0),int(0)))).
5928 :- assert_must_succeed(exhaustive_kernel_check(times(int(0),int(1),int(0)))).
5929 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],times(int(2),int(3),int(5)))).
5930 :- assert_must_succeed(exhaustive_kernel_fail_check([commutative],times(int(1),int(3),int(2)))).
5931 :- assert_must_succeed(( int_times2(A,B,C),A=3,B=2,C==6 )).
5932 :- assert_must_succeed(( int_times2(A,B,C),A=3,C=6,B==2 )).
5933 :- assert_must_succeed(( int_times2(A,B,C),B=2,A=3,C==6 )).
5934 :- assert_must_succeed(( int_times2(A,B,C),B=2,C=6,A==3 )).
5935 :- assert_must_succeed(( int_times2(A,B,C),C=6,A=3,B==2 )).
5936 :- assert_must_succeed(( int_times2(A,B,C),C=6,B=2,A==3 )).
5937 :- assert_must_succeed(( int_times2(A,_,C),A=0,C==0 )).
5938 :- assert_must_succeed(( int_times2(_,B,C),B=0,C==0 )).
5939 :- assert_must_succeed(( int_times2(A,B,C),A=1,B==C )).
5940 :- assert_must_succeed(( int_times2(A,B,C),B=1,A==C )).
5941 :- assert_must_succeed(( int_times2(A,1,C),A=2,C==2 )).
5942 :- assert_must_succeed(( int_times2(_A,0,C),C==0 )).
5943 :- assert_must_succeed(( int_times2(A,_,C),C=0,A=0 )).
5944 :- assert_must_succeed(( int_times2(_,B,C),C=0,B=0 )).
5945 :- assert_must_succeed(( int_times2(A,B,0),A=0,B=2 )).
5946 :- assert_must_succeed(( int_times2(A,B,0),B=2,A=0 )).
5947 :- assert_must_succeed(( int_times2(B,A,0),A=0,B=2 )).
5948 :- assert_must_succeed(( int_times2(B,A,0),B=2,A=0 )).
5949 :- assert_must_fail(( int_times2(A,_,C),A=3,C=7 )).
5950 :- assert_must_fail(( int_times2(A,_,C),C=7,A=3 )).
5951 :- assert_must_fail(( int_times2(_,B,C),B=2,C=7 )).
5952 :- assert_must_fail(( int_times2(_,B,C),C=7,B=2 )).
5953 :- assert_must_fail(( int_times2(A,_,C),C=7,A=0 )).
5954 :- assert_must_fail(( int_times2(_,B,C),C=7,B=0 )).
5955 :- assert_must_fail(( int_times2(B,A,0),B=2,A=1 )).
5956
5957 :- block int_times2(-,-,-).
5958 int_times2(X,Y,Times) :-
5959 ( ground(X) ->
5960 ( X==1 -> Y=Times
5961 ; X==0 -> Times=0
5962 ; int_times3(X,Y,Times))
5963 ; ground(Y) ->
5964 ( Y==1 -> X=Times
5965 ; Y==0 -> Times=0
5966 ; int_times3(Y,X,Times))
5967 ; int_times4(X,Y,Times)).
5968 % int_times3/3: First argument must be ground when called and non-zero
5969 :- block int_times3(?,-,-).
5970 int_times3(X,Y,Times) :-
5971 ( ground(Y) -> Times is X*Y
5972 ; Y is Times // X, Times is X*Y).
5973 % int_times4/3: Third argument must be ground when called
5974 :- block int_times4(-,-,?).
5975 int_times4(X,Y,Times) :-
5976 ( Times==0 ->
5977 ( ground(X) -> (X==0 -> true; Y=0 )
5978 ; /* ground(Y) -> */ (Y==0 -> true; X=0 ))
5979 ; /* Times /== 0 */
5980 ( ground(X) -> X\==0, Y is Times // X, Times is X*Y
5981 ; /* ground(Y) -> */ Y\==0, X is Times // Y, Times is X*Y)).
5982
5983
5984 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(2),int(3),int(8),unknown,_))).
5985 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(2),int(1),int(2),unknown,_))).
5986 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(3),int(0),int(1),unknown,_))).
5987 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(1),int(3),int(1),unknown,_))).
5988 :- assert_must_succeed(exhaustive_kernel_check(int_power(int(0),int(3),int(0),unknown,_))).
5989 :- assert_must_succeed(exhaustive_kernel_fail_check(int_power(int(2),int(3),int(6),unknown,_))).
5990 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=2,B=5,C==32 )).
5991 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A= -2,B=5,C== -32 )).
5992 %:- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=1,B= -5,C==1 )). % now aborts !
5993 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=1,C=1, B= -5 )).
5994 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=1,C= 1,B = -5 )).
5995 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=2,C=32,B==5 )).
5996 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=10,C=1000,B==3 )).
5997 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A= -2,C= -32,B==5 )).
5998 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A= -2,C= 16,B==4 )).
5999 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=2,C=1,B==0 )).
6000 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,B=2,C==0 )).
6001 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,C=0,B=2 )).
6002 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,B=0,C==1 )).
6003 :- assert_must_succeed(( int_power2(A,B,C,unknown,_),A=0,C=1,B==0 )).
6004 :- assert_must_succeed(( int_power2(17,13,C,unknown,_),C==9904578032905937 )).
6005 :- assert_must_succeed((platform_is_64_bit
6006 -> int_power2(A,13,C,unknown,_),C=9904578032905937,A=17
6007 ; int_power2(A,9,C,unknown,_),C=134217728,A=8 )).
6008 :- assert_must_fail((platform_is_64_bit
6009 -> int_power2(A,13,C,unknown,_),C=9904578032905936,A=17
6010 ; int_power2(A,9,C,unknown,_),C=134217727,A=8 )).
6011 :- assert_must_succeed((platform_is_64_bit
6012 -> int_power2(A,10,C,unknown,_),C=576650390625,A=15
6013 ; true)).
6014 :- assert_must_fail((platform_is_64_bit
6015 -> int_power2(A,10,C,unknown,_),C=576650390626,A=15
6016 ; false)).
6017 :- assert_must_succeed(( int_power2(A,100,C,unknown,_),A=2,C==1267650600228229401496703205376 )).
6018 :- assert_must_fail(( int_power2(A,100,C,unknown,_),C=1267650600228229401496703205375,A=2 )).
6019 :- assert_must_fail(( int_power2(A,100,C,unknown,_),C=1267650600228229401496703205377,A=2 )).
6020
6021 :- assert_must_fail(( int_power2(A,B,C,unknown,_),A=2,B=5,C=33 )).
6022 :- assert_must_abort_wf(( int_power2(A,B,_,unknown,WF),A=2,B= -5 ),WF).
6023 :- assert_must_fail(( int_power2(A,_,C,unknown,_),A= -2,C=32 )).
6024 :- assert_must_fail(( int_power2(A,_,C,unknown,_),A= -2,C= -16 )).
6025
6026 :- use_module(specfile,[eventb_mode/0]).
6027 % TODO: calculate X from Y und Pow (i.e., Yth root of Pow); in CLPFD mode this is more or less done
6028 int_power(int(X),int(Y),int(Pow),Span,WF) :- % power_of AST node
6029 ( preferences:preference(use_clpfd_solver,true)
6030 -> int_power2(X,Y,Pow,Span,WF), int_power_clpfd_propagation(X,Y,Pow)
6031 ; int_power1(X,Y,Pow,Span,WF)).
6032 % TO DO ?: if all are variables we can still infer some knowledge
6033 % e.g. if X is positive then Pow must be positive; but it is probably quite rare that we have models with unknown exponent ?
6034 :- block int_power1(-,?,?,?,?). % ensure that Base X is known if CLPFD off
6035 int_power1(X,Y,Pow,Span,WF) :-
6036 int_power2(X,Y,Pow,Span,WF).
6037 :- block int_power2(-,-,?,?,?), int_power2(?,-,-,?,?).
6038 int_power2(X,Y,Pow,Span,WF) :-
6039 ( ground(Y) ->
6040 ( Y>=0 -> (integer(X) -> safe_int_power0(X,Y,PowXY,Span,WF),
6041 ? clpfd_nr_eq(PowXY,Pow) % try and prevent overflow if PowXY is large
6042 ; safe_int_power0(X,Y,Pow,Span,WF))
6043 ; add_wd_error_set_result('power with negative exponent','**'(X,Y),Pow,1,Span,WF))
6044 ; /* X & POW are ground */
6045 ( X==1 -> Pow==1 /* 1**Y = 1 */
6046 ; X==0, Pow==1 -> Y=0
6047 ; X==0 -> Pow==0
6048 ; X>0, Pow>0 ->
6049 checked_precise_log(X,Y,Pow,Span,WF)
6050 % TO DO: X<0 should raise WD error for Event-B ?
6051 ; X<0, eventb_mode -> add_wd_error_set_result('power with negative base','^'(X,Y),Pow,1,Span,WF)
6052 ; X<0, Pow<0 ->
6053 PosPow is -(Pow),
6054 NegX is -(X),
6055 checked_precise_log(NegX,Y,PosPow,Span,WF),
6056 odd(Y)
6057 ; X<0, Pow>0 ->
6058 NegX is -(X),
6059 checked_precise_log(NegX,Y,Pow,Span,WF),
6060 even(Y))).
6061
6062 :- assert_must_succeed(( integer_log(3,59049,Log),Log==10 )).
6063 :- assert_must_succeed(( integer_log(2,1024,Log),Log==10 )).
6064 :- assert_must_succeed(( integer_log(4,1024,Log),Log==5 )).
6065 :- assert_must_succeed(( integer_log(10,1,Log),Log==0 )).
6066 :- assert_must_succeed(( integer_log(10,2,Log),Log==0 )).
6067 :- assert_must_succeed(( integer_log(10,10,Log),Log==1 )).
6068 :- assert_must_succeed(( integer_log(10,11,Log),Log==1 )).
6069 :- assert_must_succeed(( integer_log(10,1000,Log),Log==3 )).
6070 :- use_module(tools_portability, [check_arithmetic_function/1]).
6071 :- if(check_arithmetic_function(log(2, 4))).
6072 % Native log(Base, Power) function is available - use it.
6073 integer_log(Base, Power, Exp) :- ApproximateExp is truncate(log(Base, Power)),
6074 % it is precise for power of 2 it seems, but not for 3
6075 % | ?- X is log(3,59049). X = 9.999999999999998 ? -> truncate gives 9, correct value is 10
6076 correct_integer_log_approximation(Base,Power,ApproximateExp,_,Exp).
6077 :- else.
6078 % No native log(Base, Power) support, so construct it using natural logarithms.
6079 integer_log(Base, Power, Exp) :- ApproximateExp is truncate(log(Power) / log(Base)),
6080 correct_integer_log_approximation(Base,Power,ApproximateExp,_,Exp).
6081 :- endif.
6082
6083 correct_integer_log_approximation(Base,Power,Exp,Correction,Res) :-
6084 BE is Base ^ Exp,
6085 (Correction=decreasing, BE > Power % not sure this case will ever trigger
6086 -> Exp1 is Exp-1, %write(dec(Base,Bower,Exp1)),nl,
6087 correct_integer_log_approximation(Base,Power,Exp1,Correction,Res)
6088 ; Correction=increasing, BE*Base =< Power
6089 -> Exp1 is Exp+1, %write(inc(Base,Bower,Exp1)),nl,
6090 correct_integer_log_approximation(Base,Power,Exp1,Correction,Res)
6091 ; Res=Exp).
6092
6093 % TO DO for checked_precise_log: we should take pre-cautions with try_find_abort
6094 % 2**x + y = 1024 & y:0..100 -> will give x=10, y=0 but not give rise to possible WD error
6095 checked_precise_log(1,Exp,Pow,_,_) :- !, % the SICStus Prolog log function does not work for Base=1
6096 Pow=1, less_than_equal_direct(0,Exp).
6097 checked_precise_log(Base,Exp,Pow,Span,WF) :-
6098 integer_log(Base,Pow,Exp),
6099 safe_int_power(Base,Exp,Pow,Span,WF). % we have the perfect solution
6100 % ; Exp is Try+1, write(inc(Base,Pow,Try)),nl, safe_int_power(Base,Exp,Pow,Span,WF) ,write(pow(Base,Exp,Pow)),nl).
6101
6102 :- block even(-).
6103 even(X) :- 0 is X mod 2.
6104 :- block odd(-).
6105 odd(X) :- 1 is X mod 2.
6106
6107 % propagation rules if only one of the args known
6108 :- block int_power_clpfd_propagation(-,-,-).
6109 int_power_clpfd_propagation(Base,Exp,Pow) :- Exp==0, var(Base),var(Pow),!, % B**0 = 1
6110 Pow = 1.
6111 int_power_clpfd_propagation(Base,Exp,Pow) :- Exp==1, var(Base),var(Pow),!, % B**1 = B
6112 Pow = Base.
6113 int_power_clpfd_propagation(Base,Exp,Pow) :- Base==1, var(Exp),var(Pow),!, % 1**E = 1
6114 Pow = Base.
6115 %int_power_clpfd_propagation(Base,Exp,Pow) :- number(Base), Base>0,var(Exp),var(Pow),!,
6116 % clpfd_leq(1,Pow,_). % causes problem with test 305
6117 int_power_clpfd_propagation(X,Y,Pow) :-
6118 fd_min(X,MinX), number(MinX), MinX>0,
6119 fd_min(Y,MinY), number(MinY), MinY>0, % ensures no WD problem possible
6120 MinPow is MinX^MinY,
6121 \+ integer_too_large_for_clpfd(MinPow),
6122 fd_max(X,MaxX), number(MaxX),
6123 fd_max(Y,MaxY), number(MaxY),
6124 MaxPow is MaxX^MaxY,
6125 \+ integer_too_large_for_clpfd(MaxPow),
6126 % only do propagation if we are sure not to produce a CLPFD overflow
6127 !,
6128 clpfd_inrange(Pow,MinPow,MaxPow),
6129 (number(X), fd_max(Pow,MaxPow2), number(MaxPow2), get_new_upper_bound(X,MaxPow2,NewMaxExp,NewMaxPow)
6130 -> clpfd_leq(Pow,NewMaxPow,_),
6131 clpfd_leq(Y,NewMaxExp,_)
6132 ; true),
6133 (number(X), fd_min(Pow,MinPow2), number(MinPow2), get_new_lower_bound(X,MinPow2,NewMinExp,NewMinPow)
6134 -> clpfd_leq(NewMinPow,Pow,_),
6135 clpfd_leq(NewMinExp,Y,_)
6136 ; true),
6137 true.
6138 %result of this propagation: x = 3**y & y:3..5 & x /= 27 & x /= 243 -> deterministically forces x=81, y=4
6139 int_power_clpfd_propagation(Base,Exp,Pow) :- number(Base), Base>1, var(Exp), var(Pow),
6140 fd_max(Pow,MaxPow), number(MaxPow),!,
6141 (integer_log(Base,MaxPow,Log)
6142 -> clpfd_leq(Exp,Log,_)
6143 ; add_internal_error('Failed:',integer_log(Base,MaxPow,_)),
6144 clpfd_lt(Exp,MaxPow,_Posted)).
6145 int_power_clpfd_propagation(_,_,_).
6146 % TO DO: maybe implement custom CLPFD propagators; above does not trigger for x>0 & y:0..500 & 2**x + y = 1500 or x>0 & x<20 & y:0..500 & 2**x + y = 1500
6147
6148 :- assert_must_succeed((kernel_objects:get_new_lower_bound(2,3,E,P),E==2,P==4)).
6149 :- assert_must_succeed((kernel_objects:get_new_lower_bound(2,11,E,P),E==4,P==16)).
6150 :- assert_must_fail((kernel_objects:get_new_lower_bound(2,16,_,_))).
6151 % given Base and Power, determine if Power is a proper power of Exp, if not determine the next possible power of Base
6152 get_new_lower_bound(Base,Power,MinExp,MinPower) :- Base > 1, Power> 0,
6153 integer_log(Base,Power,Exp),
6154 BE is Base^Exp,
6155 BE < Power,
6156 MinPower is Base*BE,
6157 MinPower>Power,
6158 MinPower < 1125899906842624, % 2^50 \+ integer_too_large_for_clpfd(MinPower),
6159 MinExp is Exp+1.
6160 :- assert_must_succeed((kernel_objects:get_new_upper_bound(2,3,E,P),E==1,P==2)).
6161 :- assert_must_succeed((kernel_objects:get_new_upper_bound(2,11,E,P),E==3,P==8)).
6162 :- assert_must_fail((kernel_objects:get_new_upper_bound(2,16,_,_))).
6163 get_new_upper_bound(Base,Power,MaxExp,MaxPower) :- Base > 1, Power> 0,
6164 integer_log(Base,Power,MaxExp),
6165 MaxPower is Base^MaxExp,
6166 MaxPower < Power,
6167 \+ integer_too_large_for_clpfd(MaxPower),
6168 MaxPower*Base > Power.
6169
6170 % safe exponentiation using the squaring algorithm (CLPFD supports exponentiation only for SICStus 4.9 or later)
6171 % Note: in TLA mode 0^0 is undefined according to TLC; for B/Rodin it is 1
6172 safe_int_power0(Base,Exp,Result,Span,WF) :- var(Base),
6173 Exp>30,!, % Exp>59 % 2**59 no overflow; but everything above that is guaranteed to generate an overflow unless Base is 0 or 1 or -1
6174 % 3**38 generates overflow; 4**30 generates overflow on 64-bit systems
6175 % To do: examine whether we should already delay with a smaller or larger exponent
6176 when(nonvar(Base),safe_int_power(Base,Exp,Result,Span,WF)). % wait until Base is known to avoid CLPFD overflow
6177 safe_int_power0(Base,Exp,Result,Span,WF) :- safe_int_power(Base,Exp,Result,Span,WF).
6178
6179 ?safe_int_power(Base,Exp,Result,Span,WF) :- number(Base), Base<0, eventb_mode,!,
6180 add_wd_error_set_result('power with negative base','^'(Base,Exp),Result,1,Span,WF).
6181 safe_int_power(_Base,0,Result,_,_WF) :- !, Result = 1.
6182 safe_int_power(Base,Exp,Result,_,_) :- number(Base),!,
6183 Result is Base^Exp. % new integer exponentiation operator in SICStus 4.3
6184 safe_int_power(Base,Exp,Result,_,_) :-
6185 Msb is msb(Exp), % most significant bit
6186 ExpMask is 1<<Msb,
6187 safe_int_power_clpfd2(ExpMask,Exp,Base,1,Result).
6188
6189 :- use_module(clpfd_interface,[clpfd_eq_expr/2]).
6190 safe_int_power_clpfd2(0,_,_,Prev,Result) :- !, Prev=Result.
6191 safe_int_power_clpfd2(Mask,Exp,Base,Prev,Result) :-
6192 P is Exp /\ Mask, % P is Exp's highest bit
6193 Mask2 is Mask>>1,
6194 clpfd_eq_expr(Quad,Prev*Prev),
6195 ( P==0 -> Next = Quad
6196 ; clpfd_eq_expr(Next,Quad*Base) ),
6197 safe_int_power_clpfd2(Mask2,Exp,Base,Next,Result).
6198 %% -------------------------------------------------------
6199
6200 :- assert_must_succeed(( singleton_set_element([int(1)],E,unknown,_WF), E==int(1) )).
6201 :- assert_must_succeed(( singleton_set_element([int(X)],int(1),unknown,_WF), X==1 )).
6202 :- assert_must_fail(singleton_set_element([int(1)],int(2),unknown,_WF) ).
6203 :- assert_must_abort_wf(kernel_objects:singleton_set_element([int(1),int(2)],_E,unknown,WF),WF).
6204 % This predicate computes the effect of the MU operator.
6205 % Set should be a singleton set and Elem its only element.
6206 % In case Set is empty or has more than one element, an error
6207 % message is generated.
6208 :- block singleton_set_element(-,?,?,?).
6209 singleton_set_element([],_,Span,WF) :- !,
6210 add_wd_error_span('argument of MU expression must have cardinality 1, but is empty ', '', Span,WF).
6211 singleton_set_element([H|T],Elem,Span,WF) :- !,
6212 empty_set_test_wf(T,Empty,WF),
6213 when(nonvar(Empty),
6214 (Empty=pred_true -> equal_object_wf(Elem,H,singleton_set_element,WF)
6215 ; add_wd_error_span('argument of MU expression has more than one element ',
6216 b(value([H|T]),set(any),[]), Span,WF))).
6217 singleton_set_element(avl_set(A),Elem,Span,WF) :- !,
6218 (is_one_element_avl(A,AEl) -> equal_object_wf(Elem,AEl,singleton_set_element,WF)
6219 ; add_wd_error_span('argument of MU expression has more than one element ',
6220 b(value(avl_set(A)),set(any),[]), Span,WF)).
6221 singleton_set_element(Set,Elem,Span,WF) :-
6222 cardinality_as_int_wf(Set,Card,WF), % we have a comprehension set; could return inf !
6223 singleton_set_element1(Card,Set,Elem,Span,WF).
6224 :- block singleton_set_element1(-,?,?,?,?).
6225 singleton_set_element1(int(Card),Set,Elem,Span,WF) :- !,
6226 % we could check if fd_dom of Card is set up and call equality_objects_lwf(Card,int(1),IsSingleton,LWF,WF) if it is
6227 singleton_set_element2(Card,Set,Elem,Span,WF).
6228 singleton_set_element1(XX,_Set,_Elem,Span,WF) :-
6229 add_wd_error_span('argument of MU expression must have cardinality 1, but has ', XX, Span,WF).
6230
6231 :- block singleton_set_element2(-,?,?,?,?).
6232 singleton_set_element2(1,Set,Elem,_Span,_WF) :- !,
6233 exact_element_of(Elem,Set).
6234 singleton_set_element2(Card,_Set,_Elem,Span,WF) :-
6235 add_wd_error_span('argument of MU expression must have cardinality 1, but has ', Card, Span,WF).
6236
6237 :- assert_must_succeed(( singleton_set_element_wd([int(1)],E,unknown,_WF), E==int(1) )).
6238 :- assert_must_succeed(( singleton_set_element_wd([int(X)],int(1),unknown,_WF), X==1 )).
6239 %:- assert_must_succeed(( singleton_set_element_wd([int(X)|T],int(1),unknown,_WF), X==1, T==[] )).
6240 :- assert_must_fail(singleton_set_element_wd([int(1)],int(2),unknown,_WF) ).
6241 % MU_WD: a version of singleton_set_element which propagates more strongly from result to input
6242 % and thus may not raise WD errors in this case
6243 :- block singleton_set_element_wd(-,-,?,?).
6244 singleton_set_element_wd(Set,Elem,Span,WF) :- nonvar(Set),!, % TODO: first check if Elem is ground
6245 singleton_set_element(Set,Elem,Span,WF).
6246 singleton_set_element_wd(Set,Elem,_,WF) :- % TODO: only propagate if fully known?
6247 %(debug_mode(on) -> add_message_wf('MU_WD','MU_WD result instantiated: ',Elem,Span,WF) ; true),
6248 equal_object_wf(Set,[Elem],singleton_set_element_wd,WF).
6249
6250
6251 %:- print(finished_loading_kernel_objects),nl.