1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(state_packing,[reset_stored_values/0, recompute_state_packing_preference/0,
6 precompile_state_packing/0, % to be called after b_global_sets precompiled
7 pack_state/2, unpack_state/2,
8 unpack_state_top_level/2,
9 incremental_pack_state/4,
10 pack_values/2, unpack_values/2,
11 pack_value/2, unpack_value/2,
12
13 pack_bind_list/3, % pack a list of bind/2 terms and skeleton returning list of values
14 unpack_bind_list/3,
15
16 get_packed_b_state_with_uncompressed_lists/2,
17 print_stored_values/1, set_next_value_id/1,
18 retract_stored_values_with_statistics/0,
19 print_state_packing_profile/0]).
20
21 % a module to pack/compress states before asserting them in state_space
22 :- use_module(specfile,[ csp_mode/0]). % b_or_z_mode/0,
23 :- use_module(tools).
24 :- use_module(b_global_sets).
25 :- use_module(error_manager).
26 :- use_module(debug,[debug_mode/1]).
27 :- use_module(library(avl)).
28 :- use_module(preferences,[preference/2, get_preference/2, set_preference/2]).
29 :- use_module(custom_explicit_sets,[is_interval_closure/5, construct_interval_closure/3]).
30 :- use_module(performance_messages,[perfmessage/2]).
31
32 :- use_module(module_information).
33 :- module_info(group,state_space).
34 :- module_info(description,'This module packs and unpacks states and values.').
35
36 :- dynamic bind_skeleton/2. % stores the list of variable names
37 % we assume they are always in the same order; otherwise there is a problem
38 % there is a separate skeleton for const_and_vars list of variables only and for full states with constants/variables (as generated by CBC checking)
39
40 %pack_state(S,R) :- print('pack '), tools_printing:print_term_summary(S),nl,fail.
41 pack_state(root,R) :- !, R=root.
42 pack_state(const_and_vars(ID,S),R) :- % b_or_z_mode, % here for efficiency we assume that we are in B mode; any plug-in should not use this state constructor !!
43 !,
44 R='$cst_vars'(ID,PCS),
45 % debug:time(state_packing:pack_bind_list(S,PS)).
46 (bind_skeleton(const_and_vars,Skel) -> pack_bind_list(S,Skel,PS)
47 ; pack_bind_list(S,Skel,PS), %print(vskel(Skel)),nl,
48 (bind_skeleton(const_and_vars,OtherList)
49 -> add_internal_error('Multiple bind skeletons for const_and_vars:',OtherList:Skel) ; true),
50 assertz(bind_skeleton(const_and_vars,Skel))),
51 compress_list(PS,PCS).
52 pack_state(concrete_constants(S),R) :-
53 !,
54 (preference(use_state_packing,full) % leads to further reduction in memory consumption, but to a slowdown
55 -> R = '$cst'(PCS),
56 (bind_skeleton(concrete_constants,Skel) -> pack_bind_list(S,Skel,PS)
57 ; pack_bind_list(S,Skel,PS), %print(vskel(Skel)),nl,
58 assertz(bind_skeleton(concrete_constants,Skel))),
59 compress_list(PS,PCS)
60 ; R = concrete_constants(S)).
61 pack_state([bind(V,Val)|T],R) :- % b_or_z_mode, % again, for effiency we do not check whether we are in B mode here
62 !,
63 R='$bind_lst'(PV1,PCT),
64 pack_value(Val,PV),
65 (bind_skeleton(list,[V|Skel])
66 -> PV1=PV,pack_bind_list(T,Skel,PT1)
67 ; pack_bind_list(T,Skel,PT),
68 (bind_skeleton(list,OtherList)
69 -> add_warning(pack_state,'Multiple bind skeletons:',OtherList:[V|Skel]),
70 reorder(OtherList,[V|Skel],[PV|PT],[PV1|PT1]) %,print(reordered(PT1)),nl
71 ; assertz(bind_skeleton(list,[V|Skel])), PT=PT1,PV=PV1
72 )
73 ),
74 compress_list(PT1,PCT).
75 pack_state([],R) :- !, R=[].
76 pack_state(csp_and_b(CSP,B),R) :- !, R=csp_and_b(PCSP,PB),
77 pack_state(CSP,PCSP),
78 pack_state(B,PB).
79 pack_state(expanded_const_and_vars(C,V,_,_),R) :- !,
80 pack_state(const_and_vars(C,V),R).
81 pack_state(expanded_vars(V,_),R) :- !,
82 pack_state(V,R).
83 pack_state(CSP,R) :-
84 \+ preference(use_state_packing,false),csp_mode,!,
85 R='$csp'(PCSP), % tag packed CSP states, so that unpacking does not depend on the preference/mode at unpack time
86 pack_csp_expression(CSP,PCSP).
87 pack_state(V,V).
88
89 :- use_module(library(lists),[nth1/3]).
90 reorder([],_,_,[]).
91 reorder([ID|T1],Skel,Vals,[V2|T2]) :- nth1(Nr,Skel,ID), nth1(Nr,Vals,V2),!,
92 reorder(T1,Skel,Vals,T2).
93 reorder([ID|T1],Skel,Vals,Res) :- add_internal_error('Cannot find identifier:',ID),
94 reorder(T1,Skel,Vals,Res).
95
96 %compress_list([A,B,C,D|T],l4(A,B,C,D,CT)) :- !, compress_list(T,CT).
97 %compress_list(List,'$bitvector'(Val,Len,CT)) :- compress_bv(List,Val,Len,T), !, compress_list(T,CT).
98 compress_list([A,B,C|T],l3(A,B,C,CT)) :- !, compress_list(T,CT).
99 %compress_list([A,B,C|T],l3c(ID,CT)) :- !, store_value((A,B,C),ID),compress_list(T,CT). % TO DO: use this when preferences:preference(use_state_packing,true) ?
100 compress_list(T,T).
101
102 %uncompress_list(l2(A,B,CT),[A,B|T]) :- uncompress_list(CT,T).
103 uncompress_list(l3(A,B,C,CT),[A,B,C|T]) :- !, uncompress_list(CT,T).
104 %uncompress_list('$bitvector'(Val,Len,CT),Res) :- !, uncompress_bv(Val,Len,T,Res), uncompress_list(CT,T).
105 %uncompress_list(l3c(ID,CT),[A,B,C|T]) :- stored_value(ID,(A,B,C)),!,uncompress_list(CT,T).
106 %uncompress_list(l4(A,B,C,D,CT),[A,B,C,D|T]) :- uncompress_list(CT,T).
107 uncompress_list(T,T).
108
109
110 %pack_bind_list(Store,ValueList) :- pack_bind_list(Store,_,ValueList).
111
112 pack_bind_list([],[],R) :- !,R=[].
113 pack_bind_list([bind(V,Val)|T],[V|VT],R) :- !,R=[PV|PT],
114 %atom_concat(pack_,V,PackV),runtime_profiler:profile_single_call(PackV,state_packing:pack_value(Val,PV)),
115 pack_value(Val,PV),
116 pack_bind_list(T,VT,PT).
117 pack_bind_list(V,VT,R) :-
118 add_internal_error('Illegal call, probably illegal order of variables: ',pack_bind_list(V,VT,R)),
119 R=V.
120
121
122 % just unpack top-level constructor for matching against
123 % WARNING: do not use state for any processing apart from checking top-level constructor and constants id
124 % it can be used for something like state_corresponds_to_initialised_b_machine, state_corresponds_to_set_up_constants
125 unpack_state_top_level(root,State) :- !, State=root.
126 unpack_state_top_level(concrete_constants(C),State) :- !, State=concrete_constants(C).
127 unpack_state_top_level(const_and_vars(ID,CS),R) :- !, R=const_and_vars(ID,CS).
128 unpack_state_top_level('$cst'(CS),R) :- !, R=concrete_constants(CS).
129 unpack_state_top_level('$cst_vars'(ID,CS),R) :- !, R=const_and_vars(ID,CS).
130 unpack_state_top_level('$bind_lst'(Val,_),R) :- !, R=[bind(unknown,Val)].
131 unpack_state_top_level(csp_and_b(CSP,B),csp_and_b(UPCSP,UPB)) :- !, unpack_state_top_level(CSP,UPCSP),
132 unpack_state_top_level(B,UPB).
133 unpack_state_top_level(X,X).
134
135
136 unpack_state(root,State) :- !, State=root.
137 unpack_state(concrete_constants(C),State) :- !, State=concrete_constants(C). % comment out in case concrete_constants are packed after all
138 unpack_state(PackedState,State) :- %empty_avl(E), %tools_printing:print_term_summary(unpack(PackedState,State)),nl,
139 %tools_printing:print_term_summary(unpack_state(PackedState)),
140 unpack_state2(PackedState,State).
141
142 %unpack_state(concrete_constants(S),R) --> {b_or_z_mode},!, {R=concrete_constants(UPS)}, unpack_state(S,UPS). % leads to further reduction
143 unpack_state2(const_and_vars(ID,CS),R) :- !,
144 R=const_and_vars(ID,UPS),
145 unpack_state2(CS,UPS).
146 unpack_state2('$cst'(CS),R) :- !,
147 R=concrete_constants(UPS),
148 uncompress_list(CS,S),get_bind_skeleton(concrete_constants,Skel),
149 unpack_bind_list(S,Skel,UPS).
150 unpack_state2('$cst_vars'(ID,CS),R) :- % {b_or_z_mode}, we assume const_and_vars is only used in B or Z mode or is compatible
151 !,
152 R=const_and_vars(ID,UPS),
153 uncompress_list(CS,S),get_bind_skeleton(const_and_vars,Skel),
154 unpack_bind_list(S,Skel,UPS).
155 unpack_state2('$bind_lst'(Val,CT),R) :- % {b_or_z_mode}, we assume $bind_lst not used by any plug-in
156 !,
157 uncompress_list(CT,T),get_bind_skeleton(list,[Var|Skel]),R=[bind(Var,UPV)|RT],
158 %atom_concat(unpack_,Var,PackV),runtime_profiler:profile_single_call(PackV,state_packing:unpack_value(Val,UPV)),
159 unpack_value(Val,UPV), %!,
160 unpack_bind_list(T,Skel,RT).
161 unpack_state2([],R) :- !, R=[].
162 unpack_state2(csp_and_b(CSP,B),csp_and_b(UPCSP,UPB)) :- !, unpack_state2(CSP,UPCSP),
163 unpack_state2(B,UPB).
164 unpack_state2('$csp'(PCSP),R) :- !,
165 unpack_csp_expression(PCSP,R).
166 unpack_state2(R,R).
167
168 unpack_bind_list([],[],[]).
169 unpack_bind_list([Val|T],[Var|VT],R) :- R=[bind(Var,UPV)|UPT],
170 %atom_concat(unpack_,Var,PackV),runtime_profiler:profile_single_call(PackV,state_packing:unpack_value(Val,UPV)),
171 unpack_value(Val,UPV), %!,
172 unpack_bind_list(T,VT,UPT).
173 unpack_bind_list([],[Var|VT],_) :-
174 add_internal_error('Packed state has fewer values than bind skeleton, missing: ',[Var|VT]), fail.
175 unpack_bind_list([Val|T],[],_) :-
176 add_internal_error('Packed state has more values than bind skeleton, extra: ',[Val|T]), fail.
177 %unpack_bind_list('$bind_lst'(Var,Val,_),_) --> {add_internal_error('Unpacking value failed: ',Var/Val),fail}.
178
179
180 get_bind_skeleton(Category,X) :-
181 (bind_skeleton(Category,X) -> true
182 ; add_internal_error('No bind skeleton stored for: ',get_bind_skeleton(Category,X)),fail).
183
184 % a simpler version for list of bind-pairs; does not require bind_skeleton to be set up / stored
185 pack_values([],[]) :- !.
186 pack_values([bind(V,Val)|T],R) :- !,R=[Bind|PT],
187 pack_bind(Val,V,Bind),
188 pack_values(T,PT).
189 pack_values(V,R) :- add_internal_error('Illegal value, not a list of bindings: ',pack_values(V,R)),R=V.
190
191 pack_bind([],V,R) :- !, R='$bind_empty_set'(V).
192 pack_bind(pred_false,V,R) :- !, R='$bind_false'(V). % bind boolean values
193 pack_bind(pred_true,V,R) :- !, R='$bind_true'(V).
194 pack_bind(Val,V,'$bind'(V,PV)) :- pack_value(Val,PV).
195
196 unpack_bind('$bind_empty_set'(V),V,[]).
197 unpack_bind('$bind_false'(V),V,pred_false).
198 unpack_bind('$bind_true'(V),V,pred_true).
199 unpack_bind('$bind'(V,PV),V,Val) :- unpack_value(PV,Val).
200
201 unpack_values([],[]) :- !.
202 unpack_values([PBind|T],R) :- unpack_bind(PBind,V,Val),!,
203 R=[bind(V,Val)|UPT],
204 unpack_values(T,UPT).
205 unpack_values(V,R) :-
206 add_internal_error('Illegal value: ',unpack_values(V,R)),R=V.
207
208
209
210 pack_value(Var,R) :- var(Var),!,
211 add_internal_error('Illegal variable value: ', pack_value(Var,R)),
212 R='$variable'(Var).
213 pack_value(avl_set(A),R) :- !, pack_avl_set(A,R).
214 pack_value((A,B),(PA,PB)) :- !, pack_value(A,PA), pack_value(B,PB).
215 pack_value(fd(Nr,T),R) :- pack_basic_fd_value(T,Nr,Atom),!,Atom=R.
216 pack_value(int(Nr),R) :- !, R=Nr.
217 pack_value(closure(P,T,Body),R) :- pack_closure(P,T,Body,PC),!, R=PC.
218 pack_value(rec(Fields),PFields) :- !, pack_fields(Fields,PFields).
219 pack_value(freeval(ID,Case,Val),freeval(ID,Case,PVal)) :- !, pack_value(Val,PVal).
220 pack_value(term(floating(Nr)),R) :- !, R=Nr.
221 %pack_value(V,_) :- V \= [], V \= pred_true, V \= pred_false, V \= string(_), functor(V,F,N), write(cannot_pack(F,N)),nl,fail.
222 pack_value(V,V).
223
224 /* not worth it : compute avl_domain and apply pack_value in one go:
225 avl_packed_domain(empty, Domain, Domain).
226 avl_packed_domain(node(Key,_,_,L,R), Domain0, Domain) :-
227 pack_value(Key,PKey), avl_packed_domain(L, Domain0, [PKey|Domain1]),
228 avl_packed_domain(R, Domain1, Domain).
229 */
230
231 :- use_module(bsyntaxtree,[transform_bexpr/3]).
232
233 pack_closure(P,T,Body,R) :- is_interval_closure(P,T,Body,Low,Up),!,
234 %print(pack_interval(Low,Up,B)),nl,
235 R='$interval'(Low,Up).
236 %pack_value(closure(P,T,B),R) :- is_cartesian_product_closure(CPA,A1,A2),!,
237 % R='$cartesian_product'(PA1,PA2),
238 % pack_value(A1,PA1), pack_value(A2,PA2).
239 pack_closure(P,T,Body,R) :-
240 (preference(use_state_packing,full) -> true ; preference(force_state_packing_for_closures,true)),
241 R = '$closure'(P,T,PBody),
242 %add_message(state_packing,'Packing closure: ',Body,Body),
243 transform_bexpr(state_packing:pack_bexpr,Body,PBody).
244
245 pack_fields([],[]).
246 pack_fields([field(F,H)|T],'$field'(F,PH,PT)) :- pack_value(H,PH), pack_fields(T,PT).
247
248 l_pack_value([],[]).
249 l_pack_value([H|T],[PH|PT]) :- pack_value(H,PH), l_pack_value(T,PT).
250
251 pack_bexpr(b(value(Val),T,I),b(value(PVal),T,I)) :-
252 pack_value(Val,PVal).
253
254 % --------------------
255
256
257 pack_avl_set(Avl,R) :- preference(use_state_packing,Pref), pack_avl_set_aux(Avl,Pref,R).
258
259 pack_avl_set_aux(A,full,R) :-
260 avl_top_val2(A,(_,Bool)), (Bool=pred_false ; Bool=pred_true), % we have a relation/function to BOOL
261 !,
262 pack_relation(A,DomSkel,RangeVals),
263 compress_bv(RangeVals,BVVal,BVLen,[]), !, % Store function/relation skeleton separately and compress bv
264 %print(rel_packed(Val,Len,Rest)),nl,
265 R='$stored_avl_rel_bv_packed'(ID1,BVVal),
266 store_value((BVLen,DomSkel),ID1).
267 pack_avl_set_aux(A,full,R) :- %R\==[],
268 avl_domain(A,AD),
269 (pack_fd_set(AD,Type,PackedInteger)
270 -> !,
271 R = '$avl_bv'(PackedInteger,Type) % avl bit vector
272 ; AD = [_,_|_], % at least two elements
273 !,
274 l_pack_value(AD,ADL),
275 R='$stored_avl_exp'(ID),
276 store_value(ADL,ID)
277 ).
278 pack_avl_set_aux(A,_Pref,R) :- A = node(fd(_,Type),_,_,_,_),
279 % maybe we want to disable this for Pref=false ? TODO: benchmark (for nota.mch pack_fd_set seems slightly better)
280 fd_type_can_be_packed_to_bv(Type),
281 avl_domain(A,AD),
282 pack_fd_set(AD,Type,PackedInteger),!,
283 R = '$avl_bv'(PackedInteger,Type).
284 pack_avl_set_aux(A,Pref,R) :- !,
285 %avl_height(A,Height), format('Packing avl with height ~w (pref: ~w)~n',[Height,Pref]),
286 pack_avl(A,PA),
287 (try_store_avl(Pref,A,PA)
288 -> R='$stored_avl_packed'(ID), store_value(PA,ID)
289 ; PA = packed_leaf(AP) -> R='$avl_singleton'(AP)
290 ; R='$avl_packed'(PA)
291 ).
292
293 :- use_module(probsrc(avl_tools),[avl_height_less_than/2]).
294 try_store_avl(true,_A,PA) :-
295 %\+ avl_height_less_than(A,5), % if the set is large enough, store it separately; TODO: provide preference?
296 store_packed_avl(PA).
297
298 store_packed_avl(packed_leaf(Val)) :-
299 compound(Val). % no use storing simple singleton sets; maybe singleton sets in general?
300 store_packed_avl(packed_node(_,_,_,_)).
301
302 %avl_top_val(node(Val,_,_,_,_),Val).
303 avl_top_val2(node(Val,_,_,L,R),Val) :- L \= empty, R\=empty.
304
305 unpack_avl_expanded(AD,R) :-
306 l_unpack_value(AD,ADT),
307 custom_explicit_sets:ord_list_to_avlset_direct(ADT,R,unpack_value).
308
309 % try to pack an AVL tree in-place without expanding to list first:
310 pack_avl(empty, empty).
311 pack_avl(node(Val,_,0,empty,empty), R) :- !,
312 R= packed_leaf(PackedVal),
313 pack_value(Val,PackedVal).
314 pack_avl(node(Val,true,B,L0,R0), packed_node(PackedVal,B,L1,R1)) :-
315 pack_value(Val,PackedVal),
316 pack_avl(L0, L1), % TODO: we could store L, R separately
317 pack_avl(R0, R1).
318
319 unpack_avl(empty,empty).
320 unpack_avl(packed_leaf(PackedVal), node(Val,true,0,empty,empty)) :- unpack_value(PackedVal,Val).
321 unpack_avl(packed_node(PackedVal,B,L0,R0), node(Val,true,B,L1,R1)) :-
322 unpack_value(PackedVal,Val),
323 unpack_avl(L0, L1),
324 unpack_avl(R0, R1).
325
326 % pack relation: skeleton of relation and range values separately
327 pack_relation(AVL,DomSkeleton,RangeValueList) :- pack_relation(AVL,DomSkeleton,RangeValueList,[]).
328 pack_relation(empty, empty) --> [].
329 pack_relation(node((DomVal,RanVal),true,B,L0,R0), packed_rel_node(PackedVal,B,L1,R1)) -->
330 {pack_value(DomVal,PackedVal),
331 RanVal=RanPackedVal %pack_value(RanVal,RanPackedVal)
332 }, % enable compress_bv
333 [RanPackedVal],
334 pack_relation(L0, L1),
335 pack_relation(R0, R1).
336
337 unpack_relation(DomSkeleton,RangeValueList,AVL) :- unpack_relation(DomSkeleton,AVL,RangeValueList,[]).
338 unpack_relation(empty, empty) --> [].
339 unpack_relation(packed_rel_node(PackedVal,B,L1,R1), node((DomVal,RanVal),true,B,L0,R0)) -->
340 {unpack_value(PackedVal,DomVal)},
341 [RanPackedVal],
342 {RanPackedVal=RanVal}, %{unpack_value(RanPackedVal,RanVal)},
343 unpack_relation(L1, L0),
344 unpack_relation(R1, R0).
345
346 % avl_height but for packed AVLs
347 packed_avl_height(AVL, Height) :-
348 packed_avl_height(AVL, 0, Height).
349
350 packed_avl_height(empty, H, H).
351 packed_avl_height(packed_leaf(_), H0, H1) :- H1 is H0+1.
352 packed_avl_height(packed_node(_,B,L,R), H0, H) :-
353 H1 is H0+1,
354 ( B >= 0 -> packed_avl_height(R, H1, H)
355 ; packed_avl_height(L, H1, H)
356 ).
357 packed_avl_height(packed_rel_node(_,B,L,R), H0, H) :-
358 H1 is H0+1,
359 ( B >= 0 -> packed_avl_height(R, H1, H)
360 ; packed_avl_height(L, H1, H)
361 ).
362
363 % --------------------
364
365 % TO DO or [(fd,fd) as bit-vectors if <xx bits
366
367 % Pack set of FD values as bit-vector representation
368 pack_fd_set([fd(X,Type)|T],Type,Result) :-
369 fd_type_can_be_packed_to_bv(Type),
370 Acc is 1<<X,
371 pack_fd_set_aux(T,Acc,Result).
372
373 %:- use_module(tools_platform, [max_tagged_pow2/1]).
374 fd_type_can_be_packed_to_bv(Type) :-
375 b_get_fd_type_bounds(Type,1,UpBound), integer(UpBound).
376 % max_tagged_pow2(MaxBound),UpBound < MaxBound
377 % we no longer check that we can fit the bitvector in a single integer
378 % experiments seem to show that using multi-precision integers results in better compression
379 % and better performance (with and without operation_reuse)
380 % see public_examples/B/PerformanceTests/Compression/LargeDefSet.mch and LargeDefSet2.mch
381
382 pack_fd_set_aux([],A,A).
383 pack_fd_set_aux([fd(X,_)|T],Acc,Res) :-
384 NewAcc is Acc \/ (1<<X),
385 pack_fd_set_aux(T,NewAcc,Res).
386
387 % unpack a bit-vector set representation
388 unpack_fd_set(PackedInteger,Type,Value) :-
389 unpack_fd_set_aux(PackedInteger,0,Type,ResList), %print(unpacked(PackedInteger,ResList)),nl,
390 custom_explicit_sets:ord_list_to_avlset_direct(ResList,Value,unpack_fd_set).
391
392 unpack_fd_set_aux(0,_,_,Res) :- !, Res=[].
393 unpack_fd_set_aux(Nr,X,Type,Res) :-
394 (Nr mod 2 =:= 1 -> Res = [fd(X,Type)-true|T] ; Res=T),
395 X1 is X+1, Nr1 is (Nr>>1),
396 unpack_fd_set_aux(Nr1,X1,Type,T).
397
398 % first rough attempt at packing CSP expressions
399 pack_csp_expression(esharing(Set,B,C,Span),'$esharing'(PSet,PB,PC,PSpan)) :- !,
400 pack_csp_expression(Set,PSet), pack_csp_expression(B,PB),
401 pack_csp_expression(C,PC), pack_csp_expression(Span,PSpan).
402 pack_csp_expression('|||'(A,B,Span),'|||'(PA,PB,PSpan)) :- !,
403 pack_csp_expression(A,PA), pack_csp_expression(B,PB), pack_csp_expression(Span,PSpan).
404 %pack_csp_expression('&'(A,B),'&'(PA,PB)) :- !,
405 % pack_csp_expression(A,PA), pack_csp_expression(B,PB).
406 pack_csp_expression('[]'(A,B,Span),'[]'(PA,PB,PSpan)) :- !,
407 pack_csp_expression(A,PA), pack_csp_expression(B,PB), pack_csp_expression(Span,PSpan).
408 pack_csp_expression(eaParallel(C,A,D,B,Span),eaParallel(PC,PA,PD,PB,PSpan)) :- !,
409 pack_csp_expression(A,PA), pack_csp_expression(B,PB), pack_csp_expression(C,PC),
410 pack_csp_expression(D,PD), pack_csp_expression(Span,PSpan).
411 %pack_csp_expression(prefix(C,A,D,B,Span),prefix(PC,PA,PD,PB,PSpan)) :- !,
412 % pack_csp_expression(A,PA), pack_csp_expression(B,PB), pack_csp_expression(C,PC),
413 % pack_csp_expression(D,PD), pack_csp_expression(Span,PSpan).
414 %pack_csp_expression(ifte(C,A,D,B,Span,S3),ifte(PC,PA,PD,PB,PSpan,S3)) :- !,
415 % pack_csp_expression(A,PA), pack_csp_expression(B,PB), pack_csp_expression(C,PC),
416 % pack_csp_expression(D,PD), pack_csp_expression(Span,PSpan).
417 %pack_csp_expression(V,'$stored_csp'(ID)) :- store_value(V,ID).
418 pack_csp_expression(V,ID) :- store_value(V,ID).
419
420 unpack_csp_expression('$esharing'(PSet,PB,PC,PSpan),esharing(Set,B,C,Span)) :- !,
421 unpack_csp_expression(PSet,Set), unpack_csp_expression(PB,B),
422 unpack_csp_expression(PC,C), unpack_csp_expression(PSpan,Span).
423 unpack_csp_expression('|||'(A,B,Span),'|||'(PA,PB,PSpan)) :- !,
424 unpack_csp_expression(A,PA), unpack_csp_expression(B,PB), unpack_csp_expression(Span,PSpan).
425 %unpack_csp_expression('&'(A,B),'&'(PA,PB)) :- !,
426 % unpack_csp_expression(A,PA), unpack_csp_expression(B,PB).
427 unpack_csp_expression('[]'(A,B,Span),'[]'(PA,PB,PSpan)) :- !,
428 unpack_csp_expression(A,PA), unpack_csp_expression(B,PB), unpack_csp_expression(Span,PSpan).
429 unpack_csp_expression(eaParallel(C,A,D,B,Span),eaParallel(PC,PA,PD,PB,PSpan)) :- !,
430 unpack_csp_expression(A,PA), unpack_csp_expression(B,PB), unpack_csp_expression(C,PC),
431 unpack_csp_expression(D,PD), unpack_csp_expression(Span,PSpan).
432 %unpack_csp_expression(prefix(C,A,D,B,Span),prefix(PC,PA,PD,PB,PSpan)) :- !,
433 % unpack_csp_expression(A,PA), unpack_csp_expression(B,PB), unpack_csp_expression(C,PC),
434 % unpack_csp_expression(D,PD), unpack_csp_expression(Span,PSpan).
435 %unpack_csp_expression(ifte(C,A,D,B,Span,S3),ifte(PC,PA,PD,PB,PSpan,S3)) :- !,
436 % unpack_csp_expression(A,PA), unpack_csp_expression(B,PB), unpack_csp_expression(C,PC),
437 % unpack_csp_expression(D,PD), unpack_csp_expression(Span,PSpan).
438 %unpack_csp_expression('$stored_csp'(ID),V) :- !, stored_value(ID,V).
439 unpack_csp_expression(ID,V) :- % all other sub-expressions were stored by pack_csp_expression
440 (stored_value(ID,V) -> true
441 ; add_internal_error('Unknown stored CSP expression: ',ID), fail).
442
443 %unpack_value(Val,UPVal) :- unpack_value(Val,UPVal,empty,_).
444
445 unpack_value(V,R) :- var(V),!,
446 add_internal_error('Illegal variable value: ', unpack_value(V,R)), R=V.
447 unpack_value('$avl_packed'(AP),R) :- !, R=avl_set(A),unpack_avl(AP,A).
448 unpack_value('$avl_singleton'(AP),R) :- !, R=avl_set(node(A,true,0,empty,empty)),unpack_value(AP,A).
449 unpack_value('$avl_exp'(AD),R) :- !, unpack_avl_expanded(AD,R).
450 unpack_value('$stored_avl_packed'(ID),R) :- !,
451 (stored_value(ID,Val) -> R = avl_set(A), unpack_avl(Val,A)
452 ; add_internal_error('No stored AVL: ',ID),fail).
453 unpack_value('$stored_avl_exp'(ID),R) :- !,
454 (stored_value(ID,Val) -> unpack_avl_expanded(Val,R)
455 ; add_internal_error('No stored AVL: ',ID),fail).
456 unpack_value('$stored_avl_rel_bv_packed'(ID1,Val),R) :- !,
457 (stored_value(ID1,(Len,DomVal))
458 -> R = avl_set(A),
459 uncompress_bv(Val,Len,[],RanVals),
460 unpack_relation(DomVal,RanVals,A)
461 ; add_internal_error('No stored length and Domain AVL / Range Value: ',ID1),fail).
462 unpack_value('$avl_bv'(PackedInteger,Type),R) :- !, unpack_fd_set(PackedInteger,Type,R).
463 /* comment in and re-add DCG to try and re-construct sharing; does seem to increase memory usage for vital_gradient_values
464 unpack_value('$stored_avl'(ID),R,InEnv,OutEnv) :- !,
465 (avl_fetch(ID,InEnv,ER) %(expanded(ID,ER),InEnv)
466 -> R = ER, OutEnv=InEnv % reuse the already expanded value: will also decrease memory consumption due to sharing
467 ; stored_value(ID,Val),
468 avl_store(ID,InEnv,R,InEnv2), % OutEnv=[expanded(ID,R)|OutEnv2], % note: ID cannot occur inside Val
469 unpack_avl_expanded(Val,R,InEnv2,OutEnv)).
470 */
471 %unpack_value('$cartesian_product'(A,B),R) :- unpack_value(A,PA), unpack_value(B,PB),
472 % construct_cartesian_product_closure(PA,PB,R).
473 unpack_value((A,B),(PA,PB)) :- !, unpack_value(A,PA), unpack_value(B,PB).
474 unpack_value('$interval'(A,B),R) :- !, construct_interval_closure(A,B,R).
475 unpack_value('$closure'(P,T,PB),closure(P,T,B)) :- !, transform_bexpr(state_packing:unpack_bexpr,PB,B).
476 unpack_value('$field'(Field,PH,PT),rec(F)) :- !,
477 unpack_fields('$field'(Field,PH,PT),F).
478 unpack_value(freeval(ID,Case,PVal),freeval(ID,Case,Val)) :- !, unpack_value(PVal,Val).
479 unpack_value(Nr,R) :- integer(Nr),!, R=int(Nr).
480 unpack_value(Nr,R) :- float(Nr),!, R=term(floating(Nr)).
481 unpack_value(V,UPV) :- unpack_basic_fd_value(V,FD),!,UPV=FD.
482 unpack_value(V,V).
483
484 unpack_fields([],[]).
485 unpack_fields('$field'(F,PH,PT),[field(F,H)|T]) :- unpack_value(PH,H), unpack_fields(PT,T).
486
487 l_unpack_value([],[]).
488 l_unpack_value([H|T],[PH-true|PT]) :- unpack_value(H,PH), l_unpack_value(T,PT).
489
490 unpack_bexpr(b(value(PVal),T,I),b(value(Val),T,I)) :-
491 unpack_value(PVal,Val).
492
493 % -------------------------
494
495 % a version of pack_state which makes use of a previously packed state and a ordered list of Unchanged variables
496 % incremental_pack_state(State,PrevPackedState,UnchangedVariables,PackedState)
497 % The idea is to re-use the packed values from the previous state if possible
498
499 % the packed state needs to be processed by get_packed_b_state_with_uncompressed_lists first
500
501 % Note: bind_skeleton does not need to be stored as these clauses only apply when previous state of same type exists
502 incremental_pack_state(const_and_vars(ID,T),const_and_vars(ID,PrevCT),Unchanged,'$cst_vars'(ID,PCT)) :- !,
503 uncompress_list(PrevCT,PrevT),
504 incr_pack_bind_list(T,PrevT,Unchanged,PT),
505 compress_list(PT,PCT).
506 incremental_pack_state([bind(V,Val)|T],[bind(V,PrevV)|PrevCT],Unchanged,'$bind_lst'(PV,PCT)) :- !,
507 uncompress_list(PrevCT,PrevT),
508 incremental_pack_value(Val,V,PrevV,Unchanged,PV,U2),
509 incr_pack_bind_list(T,PrevT,U2,PT),
510 compress_list(PT,PCT).
511 incremental_pack_state(State,_Prev,_UC,PackedState) :-
512 % previous state has a different shape (e.g., different constants ID or not a B state): pack from scratch
513 perfmessage(state_packing,'Non-incremental state packing'),
514 pack_state(State,PackedState).
515
516 %ord_delete_existing_element(List,El,ResList) :- % ord_del_element also succeeds if El is not in the list !
517 % ord_intersection([El],List,[El],ResList).
518 %:- use_module(library(ordsets),[ord_intersection/4]).
519
520 incremental_pack_value(_,Var,PrevPackVal,[Var|U2],PackedValue,U2) :- % copy previously packed value
521 !, PackedValue=PrevPackVal.
522 incremental_pack_value(Val,_Var,_Prev,Unchanged,PackedValue,Unchanged) :-
523 pack_value(Val,PackedValue).
524
525 %not_packed(pred_false).
526 %not_packed(pred_true).
527 %not_packed(string(_)).
528
529 incr_pack_bind_list([],_,Unchanged,[]) :-
530 (Unchanged=[] -> true ; add_internal_error('Did not encounter these unchanged vars:',Unchanged)).
531 incr_pack_bind_list([bind(V,Val)|T],[bind(V,PrevV)|PrevT],Unchanged,[PackedValue|PT]) :-
532 incremental_pack_value(Val,V,PrevV,Unchanged,PackedValue,U2),
533 incr_pack_bind_list(T,PrevT,U2,PT).
534
535 % -------------------------
536
537 :- use_module(library(terms),[term_hash/2]).
538 :- use_module(debug,[debug_format/3]).
539 :- dynamic pack_basic_fd_value4/4, unpack_basic_fd_value/2.
540 % associate precompiled atoms with all enumerated & deferred set elements; TO DO: only do for "smaller" SETS
541 precompile_state_packing :-
542 retractall(pack_basic_fd_value4(_,_,_,_)),
543 retractall(unpack_basic_fd_value(_,_)),
544 ? b_global_set(T),
545 b_fd_card(T,Card),
546 (integer(Card), Card < 1000 -> true
547 ; debug_format(19,'Not precompiling state packing for ~w (size ~w)~n',[T,Card]),fail),
548 ? enum_global_type_limited(fd(Nr,T),_), % limits infinite deferred sets, which we don't precompile anyway
549 gen_fd_atom(Nr,T,NewAtom),
550 term_hash((T,Nr),Hash), % we could number the Types and use something like TypeNr*MaxSize + Nr
551 assertz(pack_basic_fd_value4(Hash,T,Nr,NewAtom)),
552 assertz(unpack_basic_fd_value(NewAtom,fd(Nr,T))),fail.
553 precompile_state_packing.
554
555 gen_fd_atom(Nr,T,NewAtom) :-
556 atom_codes(T,TC),
557 number_codes(Nr,NrC),
558 append(TC,NrC,TNrC),
559 atom_codes(NewAtom,[36,102,100,95|TNrC]). % generates '$fd_TNr atom
560
561 % use term_hash in case we have very large enumerated/deferred sets
562 pack_basic_fd_value(T,Nr,NewAtom) :- term_hash((T,Nr),Hash),
563 pack_basic_fd_value4(Hash,T,Nr,NewAtom).
564
565 % ------------------------
566
567 :- dynamic stored_value/2, stored_value_hash_to_id/2.
568
569 reset_stored_values :-
570 %(retract(stored_value(ID,_)), print(remove_stored_value(ID)),nl,fail ; true),
571 retractall(bind_skeleton(_,_)),
572 retractall(stored_value(_,_)),
573 retractall(stored_value_hash_to_id(_,_)),
574 bb_put(next_value_id,0),
575 recompute_state_packing_preference.
576
577 % the next is also called by auto_set_b_operation_cache after specification_initialised event
578 % i.e., it will also work if SET_PREF_COMPRESSION is used in loaded B machine
579 recompute_state_packing_preference :-
580 get_preference(try_use_state_packing,X),
581 compute_state_pack_setting(X,Setting),
582 set_preference(use_state_packing,Setting).
583
584 compute_state_pack_setting(auto,Setting) :- !,
585 (state_packing_definitely_useful
586 -> Setting=true
587 ; Setting = false),
588 debug_format(19,'Setting COMPRESSION to ~w~n',[Setting]).
589 compute_state_pack_setting(X,X).
590
591 state_packing_definitely_useful :-
592 get_preference(operation_reuse_setting,X), X \= false. % for operation reuse COMPRESSION is often essential
593
594
595 :- use_module(probsrc(hashing),[sdbm_term_hash/2]).
596 store_value(Value,ID) :-
597 sdbm_term_hash(Value,Hash), %[range(smallint),algorithm(sdbm), depth(infinite),if_var(ignore)],Hash),
598 % instead of infinite we could use a lower bound, collisions are taken care of below
599 store_value_aux(Value,Hash,ID).
600
601 store_value_aux(Value,Hash,ID) :-
602 stored_value_hash_to_id(Hash,ID),
603 stored_value(ID,Stored_Value),
604 Value=Stored_Value, % check that we have the exact value, could be expensive but collisions are possible
605 !. % we have already stored the value
606 store_value_aux(Value,Hash,ID) :-
607 (bb_get(next_value_id,NID) -> true ; NID=0),
608 NID1 is NID+1,
609 bb_put(next_value_id,NID1),
610 assertz(stored_value(NID,Value)),
611 assertz(stored_value_hash_to_id(Hash,NID)),
612 ID=NID.
613
614 :- use_module(tools_printing, [print_dynamic_pred/4]).
615 % state_packing:print_stored_values(user_output)
616 print_stored_values(Stream) :- % for saving state_space to file
617 print_dynamic_pred(Stream,state_packing,bind_skeleton,2),
618 print_dynamic_pred(Stream,state_packing,stored_value,2),
619 print_dynamic_pred(Stream,state_packing,stored_value_hash_to_id,2),
620 (bb_get(next_value_id,NID) -> true ; NID=0), format(Stream,'~n:- dynamic next_value_id/1.~nnext_value_id(~w).~n~n',[NID]).
621
622 % when loading state space from file
623 set_next_value_id(ID) :- bb_put(next_value_id,ID).
624
625 retract_stored_values_with_statistics :-
626 retract_with_statistics(state_packing,[stored_value(_,_),
627 stored_value_hash_to_id(_,_)]),
628 reset_stored_values.
629
630 % portray state packing infos
631 print_state_packing_profile :-
632 (bb_get(next_value_id,Nr) -> true ; Nr=0),
633 format('Stored ~w AVL sets for state compression~n',[Nr]),
634 (debug_mode(on) -> portray_stored_values ; true).
635
636 portray_stored_values :- bind_skeleton(Kind,Skel),
637 format('Binding skeleton for ~w:~n ~w~n',[Kind,Skel]),
638 fail.
639 portray_stored_values :-
640 stored_value(NID,Value), functor(Value,F,N),
641 (packed_avl_height(Value,Size) -> true
642 ; Value = (_BVLen,DomSkel), packed_avl_height(DomSkel,Size) -> true % relation skeleton, see pack_avl_set_aux
643 ; length(Value,Size) -> true ; Size='?'),
644 format('Value ~w : ~w/~w : size: ~w~n',[NID,F,N,Size]),
645 fail.
646 portray_stored_values.
647
648 % -------------------------------------
649
650 % utility to translate boolean variables into bit-vector integers (not used yet; degrades performance)
651
652 :- use_module(self_check).
653 :- assert_must_succeed((Input=[pred_false,pred_true,pred_false,1],state_packing:compress_bv(Input,Val,Len,Rest), state_packing:uncompress_bv(Val,Len,Rest,Res), Res=Input)).
654 :- assert_must_succeed((Input=[pred_false,pred_false],state_packing:compress_bv(Input,Val,Len,Rest), state_packing:uncompress_bv(Val,Len,Rest,Res), Res=Input)).
655 :- assert_must_succeed((Input=[pred_true,pred_true],state_packing:compress_bv(Input,Val,Len,Rest), state_packing:uncompress_bv(Val,Len,Rest,Res), Res=Input)).
656
657 % compress successive boolean values (at least 2)
658 compress_bv([P|T],Val,Len,Rest) :- get_bool_bv(P,Acc), compress_bv2(T,Acc,Val,Len,Rest).
659 get_bool_bv(pred_true,1).
660 get_bool_bv(pred_false,0).
661 compress_bv2([P|T],Acc,Val,Len,Rest) :- get_bool_bv(P,BoolVal),!,
662 Acc2 is Acc + BoolVal*2, % BoolVal+(Acc << 1),
663 compress_bv3(T,Acc2,Val,2,Len,Rest).
664 compress_bv3([P|T],Acc,Val,AccLen,Len,Rest) :- %get_bool_bv(P,BoolVal),!,
665 (P=pred_true -> Acc2 is Acc + (1 << AccLen) ; P=pred_false -> Acc2 = Acc), !,
666 %Acc2 is Acc + BoolVal*(2^AccLen),
667 AccLen2 is AccLen+1, compress_bv3(T,Acc2,Val,AccLen2,Len,Rest).
668 compress_bv3(Rest,Acc,Acc,AccLen,AccLen,Rest). % we have a non BOOL value
669
670 % uncompress bitvector Val of Len bits into list of pred_true, pred_false elements
671 uncompress_bv(_,Len,Rest,Res) :- Len =< 0, !, Res=Rest.
672 uncompress_bv(Val,Len,Rest,[BV|TRes]) :-
673 (Val mod 2 =:= 1 -> BV = pred_true ; BV=pred_false),
674 Val2 is Val >> 1, Len1 is Len-1,
675 uncompress_bv(Val2,Len1,Rest,TRes).
676
677 % -------------------------------------
678
679 % a utility to get a state as List or const_and_vars(ID,List) with list of packed values with bind/2 terms
680
681 get_packed_b_state_with_uncompressed_lists(csp_and_b(_,B),Res) :- !,
682 get_packed_b_state_with_uncompressed_lists(B,Res).
683 get_packed_b_state_with_uncompressed_lists('$cst_vars'(ID,CS),const_and_vars(ID,Res)) :-
684 uncompress_list(CS,List),
685 get_bind_skeleton(const_and_vars,Skel),
686 gen_packed_bind_list(List,Skel,Res).
687 get_packed_b_state_with_uncompressed_lists('$bind_lst'(Val,CT),[bind(Var1,Val)|Res]) :- uncompress_list(CT,List),
688 get_bind_skeleton(list,[Var1|Skel]),
689 gen_packed_bind_list(List,Skel,Res).
690
691
692 gen_packed_bind_list([],[],[]).
693 gen_packed_bind_list([Val|T],[Var|VT],R) :- R=[bind(Var,Val)|UPT],
694 gen_packed_bind_list(T,VT,UPT).
695
696
697 % -------------------------------------
698
699
700