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(value_persistance, [set_storage_directory/1,set_storage_directory/2,
6 unset_storage_directory/0,
7 save_constants/1,
8 load_constants/2,
9 cache_is_activated/0, clear_applicable_flag/0,
10 load_partial_constants/3, % load saved constants for sub-machines
11 lookup_cached_transitions/4,
12 add_new_transitions_to_cache/1,
13 add_new_transition_to_cache_from_expanded_state/4, % mainly for execute_modus
14 start_cache_execute_modus/1, stop_cache_execute_modus/0,
15 clear_constant_pre_hash_cache/0, % call when constants may change, e.g., new -execute run
16 tcltk_load_constants/1,
17 delete_cache_files/0,
18 delete_cache_files_for_machine/1,
19 show_cache_file_contents/1, % portray contents of cache files
20 ignore_value_persistance_cache_for/1, % register a machine or machine pattern to ignore
21 print_value_persistance_stats/0,
22 get_value_persistance_stats/1
23 ]).
24
25 :- use_module(module_information).
26 :- module_info(group,interpreter).
27 :- module_info(description,'This module is responsible for caching constants and operations on disk').
28
29 % three types of Cache files
30 % .probcst for solutions to constants
31 % .probops : operations_index file: contains sha OpHash for storable operations (operation/2 facts)
32 % and transition facts trans_index/3 : trans_index(OpName,InputHash,IndexIntoOpDataFile)
33 % .opdata: operations_data
34 % .lock: file created for locking and writing cache (not yet used for writing probcst)
35 % Note: lockfile is necessary, as SICStus allows concurrent write/append on files (on macOS at least)
36 % Thus: we create a lockfile before writing to the cache of a machine using if_exists(error)
37
38 :- use_module(library(lists)).
39 :- use_module(library(file_systems)).
40 :- use_module(library(fastrw)). % fast_read/2
41
42 :- use_module(debug).
43 :- use_module(tools).
44 :- use_module(error_manager, [add_error/2,add_error/3]).
45 :- use_module(state_space, [transition/3,visited_expression/2,
46 time_out_for_node/1,not_all_transitions_added/1,
47 time_out_for_node/3,transition/4,
48 transition_info/2 %,max_reached_for_node/1
49 ]).
50 :- use_module(succeed_max, [max_reached/1]).
51 :- use_module(preferences).
52 :- use_module(b_machine_hierarchy).
53 :- use_module(specfile, [animation_mode/1, classical_b_mode/0,
54 state_corresponds_to_initialised_b_machine/2]).
55 :- use_module(store, [lookup_value/3]).
56 :- use_module(kernel_objects, [equal_object/2]).
57 :- use_module(bmachine, [b_get_machine_refinement_hierarchy/1,
58 b_top_level_operation/1, get_operation_info/2,
59 b_get_machine_constants/1,
60 get_nr_of_machine_constants/1]).
61 :- use_module(bmachine_construction, [used_machine_not_included_anywhere/3]).
62 %:- use_module(bmachine_structure, [get_section/3]).
63 :- use_module(b_global_sets, [is_b_global_constant/3,b_global_set/1,b_get_fd_type_bounds/3]).
64 :- use_module(bsyntaxtree).
65 :- use_module(extension('probhash/probhash'),[raw_sha_hash/2]).
66 :- use_module(tools_printing,[format_with_colour_nl/4, format_with_colour/4]).
67 :- use_module(runtime_profiler,[start_profile/2, stop_profile/4]).
68 :- use_module(memoization,[export_memo_state/1, import_memo_state/1]).
69 :- use_module(state_packing).
70
71
72 :- dynamic storage_directory/1.
73 % storage_directory('/home/plagge/svn/alstomprob/examples/cache/').
74 :- volatile storage_directory/1.
75 :- dynamic is_applicable_internal/1.
76 :- volatile is_applicable_internal/1.
77
78 /**********************************************************************/
79 /* common for loading and saving: */
80 /**********************************************************************/
81
82 cache_is_activated :-
83 storage_directory(_).
84
85 cache_is_applicable_for_constants :-
86 cache_is_applicable, get_preference(cache_constants,true).
87 cache_is_applicable_for_transitions :-
88 cache_is_applicable, get_preference(cache_operations,true).
89
90 cache_is_applicable :-
91 is_applicable_internal(Applicable),!,Applicable=true.
92 cache_is_applicable :-
93 cache_is_activated,
94 % b_mode, % only for B models
95 ? classical_b_mode,
96 b_get_machine_refinement_hierarchy([_]), % only if there is no refinement - we cache no refinements
97 get_preference(symmetry_mode,off), % with symmetry on: you cannot simply patch operation updates
98 formatinfo('cache IS applicable',[]),
99 assert_once( is_applicable_internal(true) ),!.
100 cache_is_applicable :-
101 debug_format(19,'value persistance, cache NOT applicable~n',[]),
102 assert_once( is_applicable_internal(false) ),fail.
103
104 :- use_module(tools,[get_parent_directory_of_directory/2]).
105 set_storage_directory(Dir) :- set_storage_directory(Dir,strict).
106 set_storage_directory(Dir,Create) :-
107 unset_storage_directory,
108 (absolute_file_name(Dir,AbsDir,[file_type(directory),access(exist),fileerrors(fail)])
109 -> assertz(storage_directory(AbsDir))
110 ; Create=create_if_needed,
111 get_parent_directory_of_directory(Dir,ParentDir),
112 directory_exists(ParentDir),
113 % parent directory exists; try to create the directory itself
114 absolute_file_name(Dir,AbsDir,[file_type(directory),access(none),fileerrors(fail)]),
115 formatinfo('Trying to create cache directory: ~w',[AbsDir]),
116 make_directory(AbsDir)
117 -> assertz(storage_directory(AbsDir))
118 ; add_error(cache,'Could not set cache directory, directory does not exist: ',Dir)).
119
120 reset_value_persistance :-
121 retract_all_op_cache_data,
122 retractall(ignore_cache_for_machine(_)),
123 unset_storage_directory,
124 reset_counters.
125 unset_storage_directory :-
126 retractall(storage_directory(_)),
127 clear_applicable_flag.
128
129 % should be called if e.g. animation mode information changes (csp_and_b mode)
130 clear_applicable_flag :-
131 retractall(is_applicable_internal(_)).
132 :- use_module(eventhandling,[register_event_listener/3]).
133 :- register_event_listener(change_of_animation_mode,clear_applicable_flag, 'Clear Cache Info.').
134 :- register_event_listener(reset_prob,reset_value_persistance, 'Reset Cache').
135 :- register_event_listener(stop_prob,reset_operations_index_and_lock_files, 'Close files and delete lock files').
136 :- register_event_listener(specification_initialised,initialise_value_persistance,
137 'Initialise operation and constants persistent caching info.').
138
139 %:- use_module(version, [revision/1]).
140 :- use_module(version,[version/4]).
141 get_revision_info(info(V1,V2,V3,V4,ValuePersistanceRevision)) :-
142 % revision(Revision), % revision not used: it differs between probcli and ProB Tcl/Tk
143 version(V1,V2,V3,V4),
144 ValuePersistanceRevision = '$Rev$'.
145
146 collect_computation_parameters(Name,[machine_name(Name)
147 ,prob_revision(Revision)
148 %,machine_hash(Hash)
149 ,constants_signature(ConstSig)
150 ,SetsSig
151 |Prefs]) :-
152 find_relevant_preferences(Prefs),
153 get_revision_info(Revision),
154 %machine_hash(Name,Hash),
155 compute_constants_signature(Name,ConstSig),
156 compute_sets_signature(Name,SetsSig).
157
158 % signature of the global sets visible in a machine (its own SETS and those of referenced machines):
159 % the stored values of the form fd(Nr,Set) are only valid if the numbering of the set elements and
160 % the set sizes are unchanged (e.g., if a new element is inserted into an enumerated set or the size
161 % of a deferred set changes due to DEFAULT_SETSIZE or properties of another machine)
162 compute_sets_signature(Name,sets_signature(Sig)) :-
163 findall(SetName,visible_global_set(Name,SetName),SetNames),
164 sort(SetNames,SortedSetNames),
165 maplist(global_set_signature,SortedSetNames,Sig).
166
167 visible_global_set(Name,SetName) :-
168 ? machine_or_referenced_machine(Name,M),
169 machine_identifiers(M,_Params,Sets,_AVars,_CVars,_AConsts,_CConsts),
170 ? member(RawSet,Sets),
171 get_raw_set_name(RawSet,SetName).
172
173 machine_or_referenced_machine(Name,Name).
174 machine_or_referenced_machine(Name,M) :-
175 ? referenced_machine(Name,Ref,_,_),
176 ? machine_or_referenced_machine(Ref,M).
177
178 get_raw_set_name(deferred_set(_Pos,Id),Id).
179 get_raw_set_name(enumerated_set(_Pos,Id,_Elements),Id).
180 get_raw_set_name(description(_Pos,_Desc,Raw),Id) :- get_raw_set_name(Raw,Id).
181
182 global_set_signature(SetName,set(SetName,Bounds,Elements)) :-
183 ? (b_global_set(SetName), b_get_fd_type_bounds(SetName,Low,Up) -> Bounds=Low-Up
184 ; Bounds=unknown), % e.g., replaced global set
185 findall(Nr-El,is_b_global_constant(SetName,Nr,El),Els),
186 sort(Els,Elements).
187
188 /* returns a list of Pref/Value pairs for each preference that is regarded
189 a relevant when computing values for constants. See is_relevant_preference/2
190 below */
191 find_relevant_preferences(Prefs) :-
192 findall(preference(Pref,Value), relevant_preference(Pref,Value), Unsorted),
193 sort(Unsorted,Prefs).
194
195 % value_persistance:find_relevant_preferences(L), member(preference(P,_),L), print(P),nl,fail.
196
197 relevant_preference(Pref,Value) :-
198 ? preference_category(Pref,Category),
199 ? ( is_relevant_preference(Pref,Category) -> true; fail), % just to introduce a local cut
200 get_preference(Pref,Value).
201
202 /* is_relevant_preference(+Preference,+Category)
203 is used to specify those preferencees whose values are stored in the constants file.
204 If such a preference changes, the constants have to be recomputed */
205
206 is_relevant_preference(Pref,_) :- nonvar(Pref),
207 ? irrelevant_preference(Pref),!,fail.
208 is_relevant_preference(_Pref,animation).
209 is_relevant_preference(_Pref,hidden).
210 is_relevant_preference(_Pref,advanced).
211
212 % number_animated_abstractions : only relevant for Event-B + if refinement
213 irrelevant_preference(cache_operations_runtime_limit). % only influences what gets stored; re-use always safe
214 irrelevant_preference(cache_constants). % ditto
215 irrelevant_preference(cache_operations). % ditto
216 irrelevant_preference(cache_keep_files_open). % only affects internal working
217 irrelevant_preference(cache_skip_preferences_check). % ditto
218 irrelevant_preference(clash_strict_checks). % no influence on values computed
219 irrelevant_preference(strict_raise_warnings). % no influence on values computed
220 irrelevant_preference(warn_if_definition_hides_variable). % no influence on values computed
221 %irrelevant_preference(strict_raise_enum_warnings). % no sure if it can affect outcome in meaningful; could result in symbolic instead values??
222 irrelevant_preference(jvm_parser_heap_size_mb). % no influence on values computed
223 irrelevant_preference(jvm_parser_additional_args). % ditto
224 irrelevant_preference(use_safety_ltl_model_checker). % ditto
225 irrelevant_preference(store_only_one_incoming_transition). % ditto
226 irrelevant_preference(forget_state_space). % ditto
227 irrelevant_preference(type_check_definitions). % ditto
228 irrelevant_preference(expand_avl_upto). % only affects pretty-printing
229 irrelevant_preference(bool_expression_as_predicate). % only used inside REPL/eval
230 irrelevant_preference(use_large_jvm_for_parser).
231 irrelevant_preference(expand_forall_upto). % only relevant in predicate analysis
232 irrelevant_preference(time_out). % if time_out occurs: no re-use anyway
233 irrelevant_preference(performance_monitoring_on). % just prints messages
234 irrelevant_preference(performance_monitoring_expansion_limit).
235 irrelevant_preference(kodkod_for_components) :- \+ preference(use_solver_on_load,kodkod).
236 irrelevant_preference(do_neginvariant_checking). % just indicates whether invariant evaluated doubly
237 irrelevant_preference(provide_trace_information). % just provides feedback; should not change values
238 irrelevant_preference(prob_profiling_on). % ditto
239 irrelevant_preference(prob_source_profiling_on). % ditto
240 irrelevant_preference(use_closure_expansion_memoization). % only influences performance
241 irrelevant_preference(warn_when_expanding_infinite_closures). % only generates extra warnings
242 irrelevant_preference(use_small_window).
243 irrelevant_preference(tk_show_source_pane).
244 irrelevant_preference(check_prolog_b_ast).
245 irrelevant_preference(use_font_size_for_columns).
246 irrelevant_preference(user_is_an_expert_with_accessto_source_distribution).
247 irrelevant_preference(default_to_runtime_type_checking_on_startup_for_expert).
248 irrelevant_preference(number_of_recent_documents).
249 irrelevant_preference(number_of_searched_patterns).
250 irrelevant_preference(number_of_replaced_patterns).
251 irrelevant_preference(number_of_eval_history_elements).
252 irrelevant_preference(number_of_eval_csp_history_elements).
253 irrelevant_preference(number_of_checked_ltl_formulas).
254 irrelevant_preference(machines_path).
255 irrelevant_preference(tlc_number_of_workers).
256 irrelevant_preference(tlc_use_prob_constant_setup).
257 irrelevant_preference(unsat_core_algorithm).
258
259 irrelevant_preference(deterministic_trace_replay).
260 irrelevant_preference(dot_use_ps_viewer).
261 %irrelevant_preference(double_evaluation_when_analysing).% not used when computing constants or events
262 irrelevant_preference(generate_minimal_nr_of_testcases).
263 irrelevant_preference(ltl_to_ba_tool).
264 irrelevant_preference(path_to_atb_krt).
265 irrelevant_preference(path_to_bcomp).
266 irrelevant_preference(path_to_clingo).
267 irrelevant_preference(path_to_cspm).
268 irrelevant_preference(path_to_csp_typechecker).
269 irrelevant_preference(path_to_dot).
270 irrelevant_preference(path_to_dotty).
271 irrelevant_preference(path_to_fdr).
272 irrelevant_preference(path_to_fuzz). %% ??
273 irrelevant_preference(path_to_latex).
274 irrelevant_preference(path_to_ltsmin).
275 irrelevant_preference(path_to_probe).
276 irrelevant_preference(path_to_ps_viewer).
277 irrelevant_preference(path_to_spin).
278 irrelevant_preference(path_to_text_editor).
279 irrelevant_preference(path_to_text_editor_launch).
280 irrelevant_preference(repl_cache_parsing).
281 irrelevant_preference(show_bvisual_formula_explanations).
282 irrelevant_preference(show_bvisual_formula_functor_from).
283 irrelevant_preference(show_bvisual_proof_info_icons).
284 irrelevant_preference(show_function_tuples_in_property).
285 irrelevant_preference(symbolic_mc_try_other_solvers).
286 irrelevant_preference(use_scope_predicate).
287
288 irrelevant_preference(path_to_java).
289 irrelevant_preference(translate_print_all_sequences).
290 irrelevant_preference(translate_print_cs_style_sequences).
291 irrelevant_preference(view_probcli_errors_using_bbresults).
292 irrelevant_preference(trace_upon_error).
293 irrelevant_preference(error_log_file).
294 irrelevant_preference(tk_custom_state_viewer_padding).
295 irrelevant_preference(tk_custom_state_viewer_str_padding).
296 irrelevant_preference(tk_custom_state_viewer_font_name).
297 irrelevant_preference(tk_custom_state_viewer_font_size).
298 irrelevant_preference(use_tk_custom_state_viewer).
299 irrelevant_preference(translate_suppress_rodin_positions_flag).
300 irrelevant_preference(translate_ids_to_parseable_format).
301 irrelevant_preference(translate_print_frozen_infos).
302 irrelevant_preference(translate_print_typing_infos).
303 irrelevant_preference(translate_force_all_typing_infos).
304 irrelevant_preference(prob_lastchangedate_info).
305 irrelevant_preference(prob_revision_info). % comment in for development mode; to avoid re-computing cache after minor changes
306 irrelevant_preference(expand_becomes_such_into_set). % should not influence values found
307 irrelevant_preference(warn_about_failing_assignments).
308 irrelevant_preference(try_operation_reuse). % should only affect performance, not values computed
309 irrelevant_preference(try_operation_reuse_for_invariants). % only influences invariant checking
310 irrelevant_preference(do_not_print_wd_errors). % only affects printing, set by unsat core
311 irrelevant_preference(pp_propositional_logic_mode). % only affects printing
312 irrelevant_preference(pp_wd_infos). % only affects printing
313 irrelevant_preference(pp_with_terminal_colour). % only affects printing
314 irrelevant_preference(X) :- preference_category(X,Cat), irrelevant_category(Cat).
315
316 irrelevant_category(alloy2b).
317 irrelevant_category(cbc_commands). %cbc_provide_explanations
318 irrelevant_category(distb).
319 irrelevant_category(dot).
320 irrelevant_category(dot_definitions).
321 irrelevant_category(dot_event_hierarchy).
322 irrelevant_category(dot_formula_tree).
323 irrelevant_category(dot_machine_hierarchy).
324 irrelevant_category(dot_graph_generator).
325 irrelevant_category(dot_projection).
326 irrelevant_category(dot_state_graph).
327 irrelevant_category(dot_state_space).
328 irrelevant_category(dot_variable_modification).
329 irrelevant_category(gui_prefs).
330 irrelevant_category(latex).
331 irrelevant_category(mc_dc_commands).
332 irrelevant_category(smtlib2b). % only relevant for .smt2 files
333 irrelevant_category(state_as_graph).
334 irrelevant_category(syntax_highlighting).
335 irrelevant_category(table_commands).
336 irrelevant_category(trace_generator).
337 irrelevant_category(visb).
338 irrelevant_category(wd_commands).
339 % alternate categories already covered by dot category:
340 %irrelevant_category(state_as_graph).
341 %irrelevant_category(dot_graph_generator).
342 %irrelevant_category(dot_state_space).
343
344 % compute signature of PROPERTIES and of PROPERTIES of all referenced machines
345 compute_constants_signature(Name,constsig(Name,PropHash,Sublist)) :-
346 properties_hash(Name,PropHash),
347 findall(Sig,
348 ( referenced_machine_with_constants_or_properties(Name,RefName),
349 compute_constants_signature(RefName,Sig)),
350 SubSigs),
351 sort(SubSigs,Sublist).
352
353 referenced_machine_with_constants_or_properties(OrigName,RefName) :-
354 ? referenced_machine(OrigName,RefName,_,_),
355 machine_has_constants_or_properties_trans(RefName).
356
357 machine_has_constants_or_properties_trans(Name) :-
358 machine_has_constants_or_properties(Name),!.
359 machine_has_constants_or_properties_trans(Name) :-
360 referenced_machine(Name,Ref,_,_),
361 machine_has_constants_or_properties_trans(Ref),!.
362 % the machine or a machine it references (transitively) has constants
363 machine_has_constants_trans(Name) :-
364 machine_has_constants(Name),!.
365 machine_has_constants_trans(Name) :-
366 referenced_machine(Name,Ref,_,_),
367 machine_has_constants_trans(Ref),!.
368
369 machine_has_constants_or_properties(Name) :-
370 machine_identifiers(Name,_Params,Sets,_AVars,_CVars,AConsts,CConsts),
371 ( Sets=[_|_] ; AConsts=[_|_] ; CConsts=[_|_]),!.
372
373 referenced_machine(SrcName,DstName,Type,Prefix) :-
374 machine_references(SrcName,Refs),
375 ? member(ref(Type,DstName,Prefix),Refs).
376
377 /**********************************************************************/
378 /* saving values of constants */
379 /**********************************************************************/
380
381 save_constants(MaxReached) :-
382 cache_is_applicable_for_constants,
383 main_machine_name(Name), % this fails e.g. in Z mode
384 \+ constants_loaded_from_file(Name), % we have just loaded the constants from file; no need to re-write them
385 !,
386 save_constants1(Name,MaxReached).
387 %(machine_name(MName), save_constants1(MName,MaxReached), fail ; true). % this would save all constants; not just the one's from the main machine; but we should probably only save the constants whose value is already deterministic in the original included machine
388 save_constants(_MaxReached).
389
390 save_constants1(Name,MaxReached) :-
391 (save_constants2(Name,MaxReached) -> true ; add_error(value_persistance,'Storing constants failed for:',Name)).
392
393 save_constants2(Name,MaxReached) :-
394 statistics(runtime,[Start,_]),
395 statistics(walltime,[WStart,_]),
396 save_constants_for_machine(Name,MaxReached),
397 statistics(runtime,[Stop,_]), Time is Stop - Start,
398 statistics(walltime,[WStop,_]), WTime is WStop - WStart,
399 %% tools:print_memory_used_wo_gc,
400 formatinfo('storing constants for ~w (max_reached: ~w) (~w [~w] ms).',
401 [Name,MaxReached,Time,WTime]).
402
403
404 save_constants_for_machine(Name,_) :- ignore_cache_for_machine(Name),!.
405 save_constants_for_machine(Name,MaxReached) :-
406 machine_has_constants_trans(Name), % at least one constant exists, check before computing findall !
407 % Note: if machine has params then loading may fail (see check_if_machine_has_no_parameters)
408 find_constants_stores(Stores), % find all concrete_constants(_) nodes in state_space
409 has_usable_constants_data(Name,Stores),!,
410 save_constants_stores(Name,MaxReached,Stores).
411 save_constants_for_machine(Name,_MaxReached) :-
412 formatinfo('no constants stored for ~w',[Name]).
413
414 % called by add_new_transition_to_cache_from_expanded_state:
415 save_constants_from_expanded_state(SingleState) :-
416 cache_is_applicable_for_constants,
417 main_machine_name(Name),
418 \+ constants_loaded_from_file(Name), % we have just loaded the constants from file; no need to re-write them
419 SingleState = concrete_constants(Store),
420 length(Store,Len), formatinfo('saving ~w constants from expanded state',[Len]),
421 !,
422 MaxReached=true, % we do not know if there are more constants states
423 pack_constants(Store,PS),
424 (constants_saved_in_session(Name)
425 -> % keep the solutions saved earlier in this session, e.g., by -execute_all_inits for other initial states
426 % or by save_constants
427 read_saved_packed_constants(Name,OldPackedStores)
428 ; OldPackedStores = []
429 ),
430 (member(OldPS,OldPackedStores), OldPS == PS
431 -> formatinfo('constants already saved for ~w',[Name])
432 ; append(OldPackedStores,[PS],PackedStores),
433 save_packed_constants_stores(Name,MaxReached,PackedStores,1)
434 ).
435 save_constants_from_expanded_state(_) :-
436 (cache_is_applicable,main_machine_name(Name)
437 -> formatinfo('no constants stored for ~w',[Name]) ; true).
438
439 % TODO: at the moment memoisation closures will not work and Memo id info also need to be stored and re-loaded
440 save_constants_stores(MachName,MaxReached,Stores) :-
441 %find_constants(MachName,Constants),maplist(generate_bindings(Constants),Stores,ConstantBindings), % first arg. (Constants) currently not used
442 maplist(pack_constants,Stores,PackedStores),
443 length(Stores,Len),
444 save_packed_constants_stores(MachName,MaxReached,PackedStores,Len).
445
446 % NrNew: number of solutions not yet saved in the file
447 save_packed_constants_stores(MachName,_MaxReached,_PackedStores,_NrNew) :-
448 create_lock_file(MachName),
449 machine_cannot_be_locked_for_writing(MachName,Reason),!,
450 formatdetails('constants cannot be written for ~w (~w)',[MachName,Reason]).
451 save_packed_constants_stores(MachName,MaxReached,PackedStores,NrNew) :-
452 debug_println(9,saving_constants(MachName)),
453 collect_computation_parameters(MachName,CompParams),
454 length(PackedStores,Len),formatinfo('saving ~w constant solutions of machine ~w to file.',[Len,MachName]),
455 export_memo_state(MemoState),
456 bb_inc_by(value_persistance_stored_constants,NrNew),
457 save_constants_values_into_file(MachName,CompParams,PackedStores,MemoState,MaxReached).
458
459 % read the packed constant solutions from the .probcst file, without unpacking or importing the memo state
460 read_saved_packed_constants(MachName,PackedStores) :-
461 storage_file_name(constants,MachName,Filename),
462 my_open(Filename,read,S,[type(binary)]),
463 call_cleanup(read_saved_packed_constants2(S,PackedStores),my_close(S)),!.
464 read_saved_packed_constants(MachName,[]) :-
465 formatwarn('could not read previously saved constants of ~w',[MachName]).
466 read_saved_packed_constants2(S,PackedStores) :-
467 safe_constants_read(S,comp_parameters(_)),
468 safe_constants_read(S,maximum_reached(_)),
469 safe_constants_read(S,memo_state(_)),
470 read_packed_constant_values(S,PackedStores).
471 read_packed_constant_values(S,PackedStores) :-
472 safe_constants_read(S,Term),
473 ( Term = end_of_file -> PackedStores = []
474 ; Term = values(constants,PS) ->
475 PackedStores = [PS|Rest],
476 read_packed_constant_values(S,Rest)).
477
478 % find_main_constants(Constants) :- b_get_machine_constants(C), sort(C,Constants).
479 %find_constants(Name,Constants) :-
480 % get_machine_constants(Name,AbstractConstants,ConcreteConstants),
481 % append(AbstractConstants,ConcreteConstants,RawConstants),
482 % maplist(get_raw_identifier,RawConstants,Unsorted),
483 % sort(Unsorted,Constants).
484
485 get_raw_identifier(identifier(_Pos,Id),Id).
486 get_raw_identifier(description(_Pos,_Desc,Raw),Id) :- get_raw_identifier(Raw,Id).
487
488 %get_machine_constants(Name,AbstractConstants,ConcreteConstants) :-
489 % machine_identifiers(Name,Params,_Sets,_AVars,_CVars,AbstractConstants,ConcreteConstants),
490 % ( Params=[_|_]
491 % -> add_warning(value_persistance,'Parameters not yet supported.'), fail
492 % % ok to just issue warning ?? or should we generate error ?
493 % ; true).
494
495
496 /* Returns the stores of values in the state space that contain values for contants */
497 find_constants_stores(Stores) :-
498 findall(S,
499 ( transition(root,Trans,I),
500 functor(Trans,'$setup_constants',_), % better not save $partial_setup_constants for reuse
501 visited_expression(I,concrete_constants(S))
502 ),
503 Stores).
504
505 /* has_usable_constants_data/2 succeeds if there are constants that are ready to store */
506 has_usable_constants_data(MachName,Stores) :-
507 % at least one state with computed constants was generated
508 Stores = [_|_],
509 % all constants have been computed
510 (not_all_transitions_added(root)
511 -> formatwarn('not storing constants for ~w as not all transitions computed.',[MachName]), fail
512 ; true),
513 % no time-out in the root node
514 (time_out_for_node(root)
515 -> formatwarn('not storing constants for ~w as TIME_OUT occured.',[MachName]), fail
516 ; true).
517
518 % TODO: review if needs to be used
519 %generate_bindings(Constants,Store,ConstantsBinding) :-
520 % maplist(generate_binding2(Store),Constants,ConstantsBinding).
521 %generate_binding2(Store,Constant,bind(Constant,Value)) :-
522 % lookup_value(Constant,Store,Value).
523
524
525 save_constants_values_into_file(MachName,CompParams,PackedStores,MemoState,MaxReached) :-
526 storage_file_name(constants,MachName,Filename),
527 my_open(Filename,write,S,[type(binary)]), % will erase previous contents
528 !,
529 formatdetails('writing constants to (.probcst) cache file: ~w',[Filename]),
530 call_cleanup(save_values_into_file2(S,CompParams,PackedStores,MemoState,MaxReached),
531 my_close(S)),
532 assert_once(constants_saved_in_session(MachName)).
533 save_constants_values_into_file(MachName,_CompParams,_PackedStores,_MemoState,_MaxReached) :-
534 formatwarn('cannot write constants to (.probcst) cache file for: ~w',MachName),
535 assert_machine_cannot_be_locked(MachName,cannot_write_constants_file).
536
537 save_values_into_file2(S,CompParams,PackedStores,MemoState,MaxReached) :-
538 fast_write(S,comp_parameters(CompParams)),
539 fast_write(S,maximum_reached(MaxReached)),
540 fast_write(S,memo_state(MemoState)),
541 maplist(write_packed_bind(S,constants),PackedStores),
542 fast_write(S,end_of_file).
543
544 write_packed_bind(S,Type,PS) :-
545 fast_write(S,values(Type,PS)).
546
547 pack_constants(Store,PS) :-
548 temporary_set_preference(use_state_packing,false,Change),
549 pack_values(Store,PS), % does not seem to bring major performance benefit; but reduces file size
550 % print(packed(Store,PS)),nl,
551 reset_temporary_preference(use_state_packing,Change).
552 % fast_write(S,values(Type)), fast_write_list(PS,S). % should we do something like this to reduce memory consumption ?
553
554 %fast_write_list([],S) :- fast_write(S,end_of_list).
555 %fast_write_list('$bind_var'(Var,Val,T),S) :- fast_write(S,bind(Var,Val)), fast_write_list(T,S).
556
557 /* compute the full file name for the stored constants for the machine
558 the predicate uses the specified directory where constants values
559 should be stored */
560 storage_file_name(Type,MachineName,FullName) :- nonvar(MachineName),
561 cache_file_suffix(Type,Suffix),!,
562 storage_directory(Directory),
563 atom_concat(MachineName,Suffix,Name),
564 atom_concat(Directory,Name,FullName).
565 storage_file_name(Type,MachineName,_) :-
566 add_internal_error('Illegal cache file type: ',storage_file_name(Type,MachineName,_)),fail.
567
568 cache_file_suffix(constants,'.probcst').
569 cache_file_suffix(operations_index,'.probops').
570 cache_file_suffix(machine_lock_file,'.lock').
571 cache_file_suffix(operations_data,'.opdata').
572
573 % following used by show_cache_file_contents_for_machine:
574 cache_file_type(constants,_).
575 cache_file_type(operations_index,_).
576 cache_file_type(operations_data,verbose).
577
578 /**********************************************************************/
579 /* load constants */
580 /**********************************************************************/
581
582 % a predicate to see which constant values have been saved
583 tcltk_load_constants(list(CS)) :-
584 load_constants(ConstantsStores,_),
585 maplist(translate:translate_bstate,ConstantsStores,CS).
586
587
588 /* load_constants/2 returns a list of stores if the constants have been
589 saved before for the same computation parameters.
590 The predicate fails if no constants can be loaded.
591 MaxReached is 'true' if the maximum number of computed solutions was reached
592 or 'false' otherwise.
593 */
594
595 :- dynamic constants_loaded_from_file/1, constants_saved_in_session/1.
596 :- volatile constants_loaded_from_file/1, constants_saved_in_session/1.
597 % load constants for main machine
598 load_constants(ConstantStores,MaxReached) :-
599 cache_is_applicable_for_constants, % check if storing/re-using constants is activated
600 main_machine_name(Name),
601 \+ ignore_cache_for_machine(Name),
602 machine_constants_cache_file_exists(Name,FullName),
603 my_open(FullName,read,S,[type(binary)]),
604 call_cleanup(load_constants2(S,Name,ConstantStores,MaxReached),
605 my_close(S)),!.
606 load_constants2(S,Name,ConstantStores,MaxReached) :-
607 start_profile(Name,T1),
608 load_parameters(S,StoredParameters), % if the relevant computation parameters
609 collect_computation_parameters(Name,CurrentParameters), % are different, we cannot re-use the
610 (compare_computation_parameters(CurrentParameters,StoredParameters,Name) % values stored in the file
611 -> true
612 ; formatwarn('parameters changed; not reusing previously computed constants for main machine ~w.',[Name]),
613 stop_profile(Name,cache_load_constants_failed,unknown,T1),
614 fail
615 ),
616 load_max_reached(S,MaxReached),
617 load_constant_values(S,ConstantStores),
618 bb_inc(value_persistance_constants_loaded),
619 (debug_mode(off)
620 -> formatgood('re-using stored solutions for constants for main machine ~w.', [Name])
621 ; length(ConstantStores,Len),
622 get_ids(ConstantStores,CstNames),
623 length(CstNames,CLen),
624 formatgood('re-using ~w stored solutions for ~w constants ~w for main machine ~w.',
625 [Len,CLen,CstNames,Name])
626 ),
627 assert_once( constants_loaded_from_file(Name) ),
628 stop_profile(Name,cache_load_constants,unknown,T1).
629
630
631 machine_constants_cache_file_exists(Name,FullName) :-
632 cache_file_exists(constants,Name,FullName).
633 cache_file_exists(Type,Name,FullName) :-
634 storage_file_name(Type,Name,FullName),
635 (file_exists(FullName)
636 -> formatdetails('~w cache file ~w exists for ~w.',[Type, FullName, Name])
637 ; get_tail_filename(FullName,Tail),
638 formatinfo('~w cache file ~w does not yet exist for ~w.',[Type, Tail, Name]),
639 fail
640 ).
641
642 load_parameters(S,StoredParameters) :-
643 safe_constants_read(S,comp_parameters(StoredParameters)).
644
645 load_max_reached(S,MR) :-
646 safe_constants_read(S,maximum_reached(MR)).
647
648
649 load_constant_values(S,Stores) :-
650 safe_constants_read(S,memo_state(MS)),
651 import_memo_state(MS),
652 load_constant_values2(S,Stores).
653 load_constant_values2(S,Stores) :-
654 safe_constants_read(S,Term),
655 ( Term = end_of_file ->
656 Stores = []
657 ; Term = values(constants,Store) ->
658 unpack_constants(Store,UPS),
659 Stores = [UPS|Rest],
660 load_constant_values2(S,Rest)).
661
662 unpack_constants(Store,UPS) :-
663 temporary_set_preference(use_state_packing,false,Change),
664 unpack_values(Store,UPS),
665 % print(unpacked(Store,UPS)),nl,
666 reset_temporary_preference(use_state_packing,Change).
667
668 safe_constants_read(S,Term) :-
669 read_syntax_safe(S,T,Error),
670 ( Error==true ->
671 write('Invalid cache file content. File skipped.\n'),
672 fail
673 ;
674 Term = T).
675
676 % load constant solutions from subsidiary referenced machines
677 load_partial_constants(ConstantsBindings,InProperties,OutProperties) :-
678 % TODO: - check if parameters / constraints have been used (what are the implications?)
679 cache_is_applicable_for_constants, % check if storing/re-using constants is activated
680 main_machine_name(Name),
681 start_profile(Name,T1),
682 findall( partial(MName,NewBindings),
683 try_to_reuse_referenced_machine(Name,MName,NewBindings),
684 PSol),
685 (PSol = [_|_] -> true
686 ; stop_profile(Name,cache_load_constants_failed,unknown,T1),fail),
687 !,
688 remove_evaluated_properties(PSol,InProperties,OutProperties),
689 length(PSol,Len),
690 get_number_of_loaded_partial_constants(PSol,0,PLoaded),get_nr_of_machine_constants(Tot),
691 formatgood('partially re-using stored solutions for ~w/~w constants of ~w referenced machines of ~w.',
692 [PLoaded,Tot,Len,Name]),
693 stop_profile(Name,cache_load_constants,unknown,T1),
694 ? select_and_apply_binding(PSol,ConstantsBindings).
695 load_partial_constants(_ConstantsBindings,Properties,Properties).
696
697 % compute number of constants that are partially loaded across all different referenced machines
698 get_number_of_loaded_partial_constants([],A,A).
699 get_number_of_loaded_partial_constants([partial(_RefMachine,Bindings)|T],Acc,Res) :-
700 (Bindings = [Store1|_], length(Store1,Len) -> A1 is Acc+Len ; A1 = Acc),
701 get_number_of_loaded_partial_constants(T,A1,Res).
702
703 /**********************************************************************/
704
705 :- meta_predicate open_cache_file(+,+,-,0).
706 open_cache_file(Type,Name,Stream,Call) :-
707 cache_file_exists(Type,Name,FullName), %print_cache_file_props(Type,Name),
708 my_open(FullName,read,Stream,[type(binary)]),
709 formatdetails('Opened cache file ~w',[FullName]),
710 call_cleanup( (call(Call),!),my_close(Stream)).
711
712 print_cache_file_props(Type,Name) :-
713 cache_file_exists(Type,Name,FullName),
714 file_property(FullName, modify_timestamp, Time),
715 file_property(FullName,size_in_bytes,Size),
716 formatinfo('Modified at: ~w, size: ~w Bytes',[Time,Size]).
717 /**********************************************************************/
718
719 :- dynamic referenced_machine/1.
720
721 :- mode try_to_reuse_referenced_machine(+,-,-).
722 try_to_reuse_referenced_machine(OrigName,Name,Bindings) :-
723 retractall(referenced_machine(_)),
724 try_to_reuse_referenced_machine1(OrigName,Name,Bindings).
725 try_to_reuse_referenced_machine1(OrigName,Name,Bindings) :-
726 ? referenced_machine_with_constants_or_properties(OrigName,RefName),
727 (referenced_machine(RefName) -> fail ; true), % we have already processed it
728 assert(referenced_machine(RefName)),
729 try_to_reuse_referenced_machine2(OrigName,RefName,Name,Bindings).
730 try_to_reuse_referenced_machine2(OrigName,RefName,Name,Bindings) :-
731 \+ ignore_cache_for_machine(RefName), % otherwise try the machines referenced by RefName below
732 % try to re-use values of a machine directly referenced by OrigName that
733 % contains constants
734 open_cache_file(constants,RefName,S,try_load_ref_values2(RefName,OrigName,S,Bindings1)),
735 !,
736 RefName = Name,
737 Bindings1 = Bindings.
738 try_to_reuse_referenced_machine2(_,RefName,Name,Bindings) :-
739 % using the directly referenced machine failed, using a machine
740 % that is referenced by the referenced machine
741 try_to_reuse_referenced_machine1(RefName,Name,Bindings).
742
743 try_load_ref_values2(RefName,OrigName,S,Bindings) :-
744 start_profile(RefName,T1),
745 check_if_machine_has_no_parameters(RefName),
746 load_parameters(S,StoredParameters),
747 check_if_all_constants_computed(RefName,S),
748 collect_computation_parameters(RefName,CurrentParameters),
749 (compare_computation_parameters(CurrentParameters,StoredParameters,RefName)
750 -> true
751 ; formatwarn('not re-using stored solutions for constants for referenced machine ~w.', [RefName]),
752 stop_profile(RefName,cache_load_constants_failed,unknown,T1),
753 fail),
754 load_constant_values(S,Bindings),
755 bb_inc(value_persistance_ref_constants_loaded),
756 (debug_mode(off)
757 -> formatgood('re-using stored solutions for constants for referenced machine ~w.', [RefName])
758 ; length(Bindings,Len),
759 get_ids(Bindings,CstNames),
760 length(CstNames,CLen),
761 formatgood('re-using ~w previously computed solutions for ~w constants ~w of referenced machine ~w within ~w.',[Len,CLen,CstNames,RefName,OrigName])
762 % TODO: show names of constants ...
763 ),
764 stop_profile(RefName,cache_load_constants,unknown,T1).
765
766 get_name(bind(ID,_),ID) :- !.
767 get_name(X,X).
768
769 get_ids([Binding|_],Names) :- maplist(get_name,Binding,Names).
770
771 check_if_machine_has_no_parameters(RefName) :-
772 machine_identifiers(RefName,Params,_Sets,_AVars,_CVars,_AConsts,_CConsts),
773 ( Params=[] -> true
774 ;
775 formatwarn('constants of referenced machine ~w are not used because it uses parameters',[Params]),
776 fail).
777
778 compare_computation_parameters([],[],_) :- !.
779 compare_computation_parameters([CH|CT],[SH|ST],Context) :-
780 !,
781 (SH = preference(Pref,_),
782 irrelevant_preference(Pref) % can happen preference has now become irrelevant and we ignore prob_revision_info
783 -> compare_computation_parameters([CH|CT],ST,Context)
784 ; compare_computation_parameters(CH,SH,Context)
785 -> compare_computation_parameters(CT,ST,Context)
786 ).
787 compare_computation_parameters(op_comp_parameters(C),op_comp_parameters(S),Context) :- !,
788 compare_computation_parameters(C,S,Context).
789 compare_computation_parameters(C,C,_) :- !.
790 compare_computation_parameters(C,S,Context) :-
791 formatwarn('parameter difference:~ncurrent is ~w,~n stored is ~w (context: ~w).',[C,S,Context]),
792 get_preference(cache_skip_preferences_check,true), % proceed if this preference is true
793 formatwarn('still re-using cache for ~w because cache_skip_preferences_check preference is true',[Context]).
794
795 check_if_all_constants_computed(_RefName,S) :-
796 % make sure that all solutions have been generated
797 load_max_reached(S,false),!.
798 check_if_all_constants_computed(RefName,_S) :-
799 formatwarn('constants for referenced machine ~w not used because not all solutions were computed.',[RefName]),
800 fail.
801
802
803 select_and_apply_binding(Solutions,Store) :-
804 ? maplist(select_solutions,Solutions,Bindings),
805 maplist(select_and_apply_binding2(Store),Bindings).
806 select_and_apply_binding2(Store,Binding) :-
807 maplist(apply_binding(Store),Binding).
808 apply_binding(Store,bind(Id,Value)) :-
809 lookup_value(Id,Store,SValue),
810 equal_object(SValue,Value).
811 select_solutions(partial(_Name,Bindings),Binding) :-
812 ? member(Binding,Bindings). % select one of the stored solutions for referenced machine _Name
813
814 :- use_module(bmachine,[get_machine_file_number/4]).
815 machine_file_number(Name,Nr) :-
816 get_machine_file_number(Name,Ext,Nr,_),
817 Ext \= 'def',!.
818 machine_file_number(Name,Nr) :-
819 add_error(value_persistance,'Could not find machine name:',Name),
820 bmachine:portray_filenumbers,
821 Nr = -99.
822
823 :- use_module(tools_positions, [get_position_filenumber/2]).
824 % remove the properties from those machines whose constants have already been set from file
825 remove_evaluated_properties(PSol,InProperties,OutProperties) :-
826 findall(Name,member(partial(Name,_),PSol),UnsortedNames),
827 sort(UnsortedNames,Names),
828 findall(FileNr,(member(NN,Names), get_subsidiary_loaded_filenumber(NN,FileNr)), FileNumbers),
829 sort(FileNumbers,SFileNumbers),
830 debug_println(9,filtering_properties(Names,SFileNumbers)),
831 conjunction_to_list(InProperties,InAsList),
832 % exclude all properties who are in one of the files for which we have restored (all) constant values
833 exclude(belongs_to_file(SFileNumbers),InAsList,OutAsList), % this is exclude/3 from library(lists)
834 length(InAsList,InLen), length(OutAsList,OutLen), length(SFileNumbers,FLen),
835 formatgood('filtered PROPERTIES, keeping ~w out of ~w (#files=~w filtered).',[OutLen,InLen,FLen]),
836 conjunct_predicates(OutAsList,OutProperties).
837 belongs_to_file(SFileNumbers,TPred) :-
838 get_texpr_info(TPred,Info),
839 memberchk(nodeid(Pos),Info),
840 get_position_filenumber(Pos,FilePos),
841 ord_member(FilePos,SFileNumbers).
842 % TODO: check if this is a property coming from a machine included by a file in FileNumbers, without prefix for variables
843
844 %TODO: we could cache the computation or do a topological sorting to avoid re-computing filenumbers
845 get_subsidiary_loaded_filenumber(MachName,FileNr) :-
846 machine_file_number(MachName,FileNr).
847 get_subsidiary_loaded_filenumber(MachName,FileNr) :-
848 machine_references(MachName,References),
849 Prefix='', % we only consider machines included without prefix as loaded;
850 % TODO: for Constants it would be ok with Prefix
851 member(ref(_Type,IncludedMachName,Prefix),References),
852 get_subsidiary_loaded_filenumber(IncludedMachName,FileNr).
853
854
855 /**********************************************************************/
856
857 :- dynamic loadable_operation/5, loadable_short_operation/3, machine_has_relevant_operation/1,
858 storable_operation/5, storable_operation_full_name/3,
859 stored_transition/4, operation_has_stored_transition/1,
860 operations_index_file_opened/2, machine_cannot_be_locked_for_writing/2,
861 machine_lock_file_created/1.
862 :- volatile loadable_operation/5, loadable_short_operation/3, machine_has_relevant_operation/1,
863 storable_operation/5, storable_operation_full_name/3, stored_transition/4, operation_has_stored_transition/1,
864 operations_index_file_opened/2, machine_cannot_be_locked_for_writing/2,
865 machine_lock_file_created/1.
866
867 initialise_value_persistance :-
868 clear_applicable_flag,
869 cache_is_applicable_for_transitions,
870 main_machine_name(MachName), % if we have no machine name, fail silently (for default machine)
871 !,
872 % check wich operations are cachable and prepare information for them
873 formatdetails('initialise_value_persistance for main machine ~w',[MachName]),
874 retract_all_op_cache_data,
875 precompute_machine_has_operations,
876 %initialise_op_cache_for_machine(MachName),
877 find_loadable_machines(LoadableMachines),
878 length(LoadableMachines,LenLoad), formatinfo('number of loadable machines: ~w',[LenLoad]),
879 formatdetails('loadable machines: ~w',[LoadableMachines]),
880 maplist(initialise_op_cache_for_machine,LoadableMachines),
881 formatdetails('initialise_op_cache_for_machine for main machine ~w',[MachName]),
882 maplist(try_to_load_operations_cache,LoadableMachines),
883 maplist(refresh_op_cache_for_machine,LoadableMachines).
884 initialise_value_persistance :-
885 retract_all_op_cache_data.
886
887 initialise_op_cache_for_machine(loadable(_,MachName)) :-
888 bb_inc(value_persistance_op_cache_machines),
889 get_operation_names(MachName,OperationNames),
890 maplist(init_operation_cache(MachName),OperationNames).
891
892 refresh_op_cache_for_machine(loadable(_,MachName)) :-
893 machine_has_relevant_operation(MachName),!, % important that initialise_op_cache_for_machine and try_to_load_operations_cache is done first so that this fact is complete
894 % TODO: should we only do this when there are relevant storeable operations to write?!
895 (operations_index_file_fully_loaded(MachName),
896 \+ new_storable_operation(MachName,_)
897 -> formatgood('operations_index file needs no refresh for ~w',[MachName])
898 ; get_operation_names(MachName,OperationNames),
899 save_operations_index_cache(MachName,OperationNames)
900 ),
901 open_data_file(MachName).
902 refresh_op_cache_for_machine(_).
903
904 % a storable operation without operation/2 entry in the operations_index file (e.g., a newly added operation);
905 % the index file has to be re-written, otherwise its transitions would be ignored when re-loading the file
906 new_storable_operation(MachName,OpName) :-
907 ? storable_operation(_,MachName,OpName,_,_),
908 \+ loadable_short_operation(OpName,MachName,_),
909 formatinfo('operation ~w of ~w not yet in operations_index file',[OpName,MachName]).
910
911
912
913 retract_all_op_cache_data :-
914 retractall(machine_has_operations(_)),
915 retractall(referenced_machine(_)),
916 retractall(constants_loaded_from_file(_)),
917 retractall(constants_saved_in_session(_)),
918 retractall(loadable_operation(_,_,_,_,_)),
919 retractall(loadable_short_operation(_,_,_)),
920 retractall(machine_has_relevant_operation(_)),
921 retractall(storable_operation(_,_,_,_,_)),
922 retractall(storable_operation_full_name(_,_,_)),
923 retractall(stored_transition(_,_,_,_)),
924 retractall(operation_has_stored_transition(_)),
925 retractall(cst_id_to_hash(_,_)),
926 retractall(constant_pre_hash_cache_active),
927 retractall(operations_index_file_fully_loaded(_)),
928 retractall(machine_cannot_be_locked_for_writing(_,_)),
929 % Note: ignore_cache_for_machine is not reset here, as this is called by initialise_value_persistance
930 % after -ignore_cache_for has been processed
931 reset_operations_index_and_lock_files.
932
933 % operations_index_file_opened(Stream) contains a possibly open stream for the operations (probops) file
934 reset_operations_index_and_lock_files :-
935 close_operations_index_files,
936 reset_machine_lock_file_created.
937
938 close_operations_index_files :-
939 ? ( operations_index_file_opened(M,S)
940 -> formatdetails('closing operations index file for ~w',[M]),
941 my_close(S),retractall(operations_index_file_opened(M,_)),
942 close_operations_index_files
943 ; true).
944
945 reset_machine_lock_file_created :-
946 ? retract(machine_lock_file_created(MachName)),
947 delete_cache_file(machine_lock_file,MachName),
948 fail.
949 reset_machine_lock_file_created.
950
951 get_operation_names(MachName,OperationNames) :- % TODO: ['$initialise_machine'|OperationNames]) :-
952 if(machine_operations(MachName,RawOperationNames),
953 maplist(get_raw_identifier,RawOperationNames,OperationNames),
954 add_error_fail(value_persistance,'Cannot find machine:',MachName)).
955
956
957 :- dynamic operations_index_file_fully_loaded/1.
958 :- volatile operations_index_file_fully_loaded/1.
959
960 try_to_load_operations_cache(loadable(Type,MachName)) :- \+ machine_has_operations(MachName),
961 \+ main_machine_name(MachName), !,
962 formatdetails('machine has no operations to load ~w (~w)',[MachName,Type]).
963 try_to_load_operations_cache(loadable(Type,MachName)) :-
964 ignore_cache_for_machine(MachName),!,
965 formatdetails('ignoring machine ~w (~w), not trying to load cached operations',[MachName,Type]).
966 %try_to_load_operations_cache(loadable(Type,MachName)) :-
967 % \+ machine_has_relevant_operation(MachName), % test 2501 fails with this; the computation of that fact is not yet complete, and we may add a loadable operation below in read_cached_operations
968 try_to_load_operations_cache(loadable(Type,MachName)) :- % Type is sub or main
969 formatdetails('try loading cached operations for machine ~w (~w)',[MachName,Type]),
970 start_profile(MachName,T1),
971 get_operations_computation_parameters(MachName,OpParams),
972 (open_cache_file(operations_index,MachName,S,read_cached_operations(S,MachName,OpParams,Error,RequiresRefresh))
973 -> true
974 ; stop_profile(MachName,cache_load_operations_index_failed,unknown,T1), fail
975 ),
976 !,
977 ( Error==true ->
978 formatwarn('corrupted index file for machine ~w, deleting file.',[MachName]),
979 delete_operations_data_cache_file(MachName)
980 ; var(RequiresRefresh) -> assertz(operations_index_file_fully_loaded(MachName))
981 ; true
982 ),
983 stop_profile(MachName,cache_load_operations_index,unknown,T1).
984 try_to_load_operations_cache(loadable(main,MachName)) :-
985 % read_cached_operations has failed, due to general computations parameter change
986 % delete the data file if one exists -- do only for main machine
987 delete_operations_data_cache_file(MachName),!.
988 try_to_load_operations_cache(_Loadable).
989
990 delete_operations_data_cache_file(MachName) :-
991 % the indexes of transitions loaded from the operations_index file refer to the deleted data file:
992 discard_loaded_operations_cache(MachName),
993 (cache_file_exists(operations_data,MachName,Filename)
994 -> formatinfo('deleting opdata cache file of machine ~w: ~w',[MachName,Filename]),
995 delete_file(Filename)
996 ; true
997 ).
998
999 % remove all facts about loadable operations and stored transitions read from the operations_index file
1000 discard_loaded_operations_cache(MachName) :-
1001 ? retract(loadable_short_operation(OpName,MachName,FullOpName)),
1002 bb_dec(value_persistance_loadable_operations), % see also store_loadable_operation
1003 retractall(loadable_operation(FullOpName,OpName,MachName,_,_)),
1004 retractall(stored_transition(_,_,OpName,_)),
1005 retractall(operation_has_stored_transition(OpName)),
1006 formatinfo('discarding cached transitions for operation ~w of machine ~w',[OpName,MachName]),
1007 fail.
1008 discard_loaded_operations_cache(_).
1009
1010 % read cached operations from operations_index file
1011 read_cached_operations(S,MachName,CurrentOpParams,SyntaxError,RequiresRefresh) :-
1012 read_syntax_safe(S,StoredOpParams,SyntaxError),
1013 ( SyntaxError==true -> true
1014 ; compare_computation_parameters(CurrentOpParams,StoredOpParams,MachName) ->
1015 formatgood('parameters unchanged, re-use of stored operations possible for ~w',[MachName]),
1016 read_cached_operations2(S,MachName,SyntaxError,RequiresRefresh)
1017 ;
1018 formatwarn('general computations parameters have changed, no re-use of stored operations for ~w',[MachName]),
1019 debug_params(CurrentOpParams,StoredOpParams),
1020 fail).
1021
1022 % read cached operations from operations_index file if global parameters unchanged:
1023 read_cached_operations2(S,MachName,SyntaxError,RequiresRefresh) :-
1024 read_syntax_safe(S,Term,SyntaxError),
1025 ( SyntaxError==true -> true
1026 ; Term == end_of_file -> true
1027 ; read_cached_operations3(Term,MachName,RequiresRefresh) ->
1028 read_cached_operations2(S,MachName,SyntaxError,RequiresRefresh)
1029 ;
1030 functor(Term,F,A),
1031 formatwarn('unrecognised entry in cache file for ~w: ~w/~w',[MachName,F,A]),
1032 fail
1033 ).
1034 debug_params(op_comp_parameters(A),op_comp_parameters(B)) :- !,
1035 debug_params(A,B).
1036 debug_params(preference(P,A),preference(P,B)) :- !,
1037 (A=B -> true ; print(P), print(':'), print(A/B), print(' ')).
1038 debug_params([],[]) :- !,nl.
1039 debug_params([preference(P1,A)|CT],[preference(P2,B)|ST]) :- !,
1040 (P1=P2 -> (A=B -> true ; format('Difference in preference ~w : current = ~w, stored = ~w~n',[P1,A,B])),
1041 debug_params(CT,ST)
1042 ; P1 @< P2 -> format('New preference ~w = ~w (not stored)~n',[P1,A]), debug_params(CT,[preference(P2,B)|ST])
1043 ; format('Stored preference removed ~w = ~w~n',[P2,B]), debug_params([preference(P1,A)|CT],ST)
1044 ).
1045 debug_params([Cur|CT],[Stored|ST]) :- !,
1046 debug_params(Cur,Stored),
1047 debug_params(CT,ST).
1048 debug_params(A,B) :- (A=B -> true ; print(A/B),nl).
1049
1050 % -----------------
1051
1052 % a way to clean/delete all cache files for current machine; useful for tests
1053 delete_cache_files :-
1054 reset_operations_index_and_lock_files, % to ensure we can delete the files
1055 find_loadable_machines(LoadableMachines),
1056 maplist(delete_cache_files_for_machine(_),LoadableMachines).
1057
1058 % delete a single cache file only
1059 delete_cache_files_for_machine(Machine) :-
1060 reset_operations_index_and_lock_files, % to ensure we can delete the files
1061 delete_cache_files_for_machine(_,loadable(main,Machine)).
1062
1063 delete_cache_files_for_machine(ExpectedType,loadable(_MType,MachName0)) :-
1064 (get_machine_file_number(MachName0,_Ext,_Nr,_) -> MachName=MachName0
1065 ; get_modulename_filename(MachName0,MachName),
1066 get_machine_file_number(MachName,_Ext,_Nr,_)
1067 -> formatinfo('Trying to delete cache for machine: ~w',[MachName]) % TODO: check if file matches?
1068 ; formatwarn('Machine ~w is unknown or does not match filename. Clearing cache may fail.',[MachName0]),
1069 MachName=MachName0
1070 ),
1071 ? cache_file_suffix(Type,_), % backtracks and also matches operations_data
1072 (var(ExpectedType) -> true ; ExpectedType=Type),
1073 delete_cache_file(Type,MachName),
1074 fail.
1075 delete_cache_files_for_machine(_,_).
1076
1077 delete_cache_file(Type,MachName) :-
1078 (cache_file_exists(Type,MachName,FullName)
1079 -> get_tail_filename(FullName,FF),
1080 formatinfo('deleting ~w cache file for machine ~w: ~w',[Type,MachName,FF]),
1081 delete_file(FullName)
1082 ; formatinfo('no need to clear cache, no file of type ~w exists for machine ~w',[Type,MachName])
1083 ).
1084
1085 :- use_module(probsrc(tools_strings), [atom_prefix/2]).
1086 :- dynamic ignore_cache_for_machine/1.
1087 % register a machine name prefix to be ignored
1088 ignore_value_persistance_cache_for(MachNamePat) :-
1089 ? if(ignore_value_persistance_cache_for_prefix(MachNamePat),true,
1090 formatwarn('cannot ignore, no known machine starts with: ~w',[MachNamePat])),
1091 fail.
1092 ignore_value_persistance_cache_for(_).
1093
1094 ignore_value_persistance_cache_for_prefix(MachNamePat) :-
1095 ? machine_name(MachName), % the names from the MACHINE clauses, as used for the cache files
1096 machine_name_prefix(MachNamePat,MachName),
1097 format_with_colour_nl(user_output,[blue],'ignoring cache for machine ~w',[MachName]),
1098 assert(ignore_cache_for_machine(MachName)).
1099
1100 :- use_module(tools,[host_file_name_case_insensitive/0]).
1101 :- use_module(tools_matching,[codes_to_lower_case/2]).
1102 machine_name_prefix(MachNamePat,MachName) :- atom_prefix(MachNamePat,MachName),!.
1103 machine_name_prefix(MachNamePat,MachName) :-
1104 host_file_name_case_insensitive, % e.g., on Windows the file names can differ in case from the machine names
1105 atom_codes(MachNamePat,PC), codes_to_lower_case(PC,LPC),
1106 atom_codes(MachName,MC), codes_to_lower_case(MC,LMC),
1107 append(LPC,_,LMC).
1108
1109
1110 :- meta_predicate show_cache_file_contents_for_machine(-,-,-,0,-,-).
1111 % a small utility to print out the contents of the cache files:
1112
1113 % called by -show_cache and -show_cache_verbose commands of probcli
1114 show_cache_file_contents(Verbose) :-
1115 (storage_directory(Dir) -> true ; Dir='?'),
1116 sep_line,
1117 format_with_colour_nl(user_output,[blue],'Cache contents (directory: ~w)',[Dir]),
1118 close_operations_index_files, % otherwise on Windows we are not able to open the probobs file as it is already open
1119 show_cache_file_operations(Verbose),
1120 sep_line,
1121 (Verbose=verbose -> potray_loadable_operations ; true),
1122 sep_line.
1123
1124
1125 show_cache_file_operations(Verbose) :-
1126 close_operations_index_files, % otherwise on Windows we are not able to open the probobs file as it is already open
1127 find_loadable_machines(LoadableMachines),
1128 maplist(show_cache_file_contents_for_machine(Verbose,Mch,T,show_facts(S,Verbose,Mch,T),S),LoadableMachines),
1129 reset_show_facts.
1130
1131 cache_applicable(operations) :- !, cache_is_applicable_for_transitions.
1132 cache_applicable(constants) :- !, cache_is_applicable_for_constants.
1133 cache_applicable(_) :- cache_is_applicable.
1134
1135 sep_line :- format_with_colour_nl(user_output,[blue],'-----------------',[]).
1136 :- use_module(tools,[get_tail_filename/2, get_modulename_filename/2]).
1137 show_cache_file_contents_for_machine(Verbose,MachName,Type,Call,Stream,loadable(_MType,MachName)) :-
1138 (machine_has_constants(MachName) -> HasC=with ; HasC=no),
1139 (machine_operations(MachName,_) -> HasO=with ; HasO=no),
1140 sep_line,
1141 format_with_colour_nl(user_output,[blue],'Cache for machine ~w (~w constants, ~w operations)',[MachName,HasC,HasO]),
1142 ? cache_file_type(Type,Verbose), % backtracks
1143 (cache_file_exists(Type,MachName,FullName) ->
1144 get_tail_filename(FullName,FF),
1145 format_with_colour_nl(user_output,[blue],'Contents of ~w cache file for machine ~w: ~w',[Type,MachName,FF]),
1146 (cache_applicable(Type)
1147 -> (ignore_cache_for_machine(MachName)
1148 -> format_with_colour_nl(user_output,[blue],' (Cache ignored for ~w)',[MachName]) ; true)
1149 ; format_with_colour_nl(user_output,[blue],' (Cache not applicable for ~w)',[Type])),
1150 (open_cache_file(Type,MachName,Stream,Call)
1151 -> format_with_colour_nl(user_output,[blue],'End of contents (~w)',[FF]),
1152 print_cache_file_props(Type,MachName)
1153 ; format_with_colour_nl(user_error,[red],'Failed to show cache contents of ~w.',[FF])
1154 )
1155 ; \+ cache_applicable(Type) -> true
1156 ; Type=operations_index, machine_operations(MachName,_)
1157 -> format_with_colour_nl(user_output,[blue],'No cache file of type ~w for machine with operations ~w.~n',[Type,MachName])
1158 ; Type=constants, machine_has_constants(MachName)
1159 -> format_with_colour_nl(user_output,[blue],'No cache file of type ~w for machine with constants ~w.~n',[Type,MachName])
1160 ; debug_format(19,'No cache file of type ~w for machine ~w.~n',[Type,MachName]) % TODO: check if MachName has constants,...
1161 ),
1162 fail.
1163 show_cache_file_contents_for_machine(_,_,_,_,_,_).
1164
1165 :- dynamic used_opdata_index/3.
1166 reset_show_facts :- retractall(used_opdata_index(_,_,_)).
1167
1168 show_facts(S,Verbose,Mch,FileType) :-
1169 (FileType=operations_data, stream_position(S,Pos), stream_position_data(byte_count,Pos,BCount)
1170 -> true ; BCount = -1),
1171 read_syntax_safe(S,Term,Error),
1172 (nonvar(Error)
1173 -> add_error(value_persistance,'Error occured reading cache stream: ',S)
1174 ; Term = end_of_file -> reset_and_show_stats % will print # of maximum_reached ...
1175 ; portray_content_fact(Term,Verbose,Mch,BCount),
1176 show_facts(S,Verbose,Mch,FileType)).
1177
1178 :- use_module(tools_strings,[get_hex_bytes/2]).
1179 :- use_module(translate,[print_bstate/1]).
1180 % operations:
1181 portray_content_fact(op_comp_parameters(OpParams),Verbose,_,_) :- OpParams=[H,H2|_], !,
1182 length(OpParams,Len),
1183 format_verbose(Verbose,' op_comp_parameters([~w,~w,...]). % ~w parameters~n',[H,H2,Len]).
1184 portray_content_fact(operation(OpName,Hash),_,_,_) :- get_hex_bytes(Hash,Hex), !,
1185 format(' operation(~w,~s).~n',[OpName,Hex]).
1186 portray_content_fact(trans_index(OpName,Hash,Index),Verbose,Mch,_) :- get_hex_bytes(Hash,Hex), !,
1187 compute_short_hash(Hash,Short),
1188 format_verbose(Verbose,' transition(~w,~s,~w). % short: ~w~n',[OpName,Hex,Index,Short]),
1189 assert(used_opdata_index(Index,Mch,OpName)), % TODO: store machine name
1190 inc_counter(OpName).
1191 % opdata: either trans_info(Infos,Transitions) or a plain list of transitions, see store_transitions_into_cache
1192 portray_content_fact(trans_info(Infos,Transitions),Verbose,Mch,BC) :- !,
1193 get_opdata_entry_op_name(BC,Mch,OpName),
1194 format_verbose(Verbose,' trans_info(~w,~w). % position: ~w ~w~n',[Infos,Transitions,BC, OpName]),
1195 inc_counter(trans_info).
1196 portray_content_fact(Transitions,Verbose,Mch,BC) :- BC >= 0, (Transitions=[] ; Transitions=[_|_]), !,
1197 get_opdata_entry_op_name(BC,Mch,OpName),
1198 format_verbose(Verbose,' ~w. % position: ~w ~w~n',[Transitions,BC, OpName]),
1199 inc_counter(transition_list).
1200 % constants:
1201 portray_content_fact(comp_parameters(OpParams),Verbose,_,_) :- OpParams=[H,H2|_], !,
1202 length(OpParams,Len),
1203 format_verbose(Verbose,' comp_parameters([~w,~w,...]). % ~w parameters~n~n',[H,H2,Len]).
1204 portray_content_fact(maximum_reached(MaxReached),Verbose,_,_) :- !,
1205 format_verbose(Verbose,' maximum_reached(~w).~n',[MaxReached]),
1206 (MaxReached=true -> inc_counter(maximum_reached) ; true).
1207 portray_content_fact(values(constants,Store),_Verbose,_,_) :- !,
1208 unpack_constants(Store,UPS),
1209 print_bstate(UPS),nl.
1210 portray_content_fact(Term,_,_,_) :- write(' '),portray_clause(Term).
1211
1212 % get the operation whose trans_index refers to the opdata entry at position BC
1213 get_opdata_entry_op_name(BC,Mch,OpName) :-
1214 (used_opdata_index(BC,Mch,OpName) -> true ; OpName = '*stale*', inc_counter(stale_opdata_entry)).
1215
1216 format_verbose(verbose,Str,A) :- !, format(Str,A).
1217 format_verbose(_,_,_).
1218
1219
1220 :- dynamic counter/2.
1221 reset_and_show_stats :- retract(counter(C,Nr)), format(' # of ~w : ~w~n',[C,Nr]),fail.
1222 reset_and_show_stats.
1223
1224 inc_counter(C) :- (retract(counter(C,Nr)) -> N1 is Nr+1 ; N1 = 1),
1225 assertz(counter(C,N1)).
1226
1227 :- use_module(error_manager).
1228 % variation of tools_fastread:fastrw_read/3
1229 read_syntax_safe(S,Term,Error) :-
1230 catch( fast_read(S,Term1), % from library fastrw
1231 error(E,_),
1232 ( E=syntax_error(_) -> Error = true
1233 ; E=permission_error(_,_,_) -> Term1 = end_of_file
1234 ; E=consistency_error(_,_,_)
1235 -> add_error(value_persistance,'Consistency error when reading from stream: ',E),
1236 Error = true
1237 ;
1238 add_error(value_persistance,'Unknown error when reading from stream: ',E),
1239 throw(E))
1240 ), %functor(Term1,F,N),write(read_syntax_safe(F/N,E)),nl,
1241 Term1 = Term.
1242
1243
1244 read_cached_operations3(operation(OpName,StoredHash),MachName,RequiresRefresh) :-
1245 ( operation_hash(MachName,OpName,CurrentHash) ->
1246 ( CurrentHash = StoredHash % we can reuse operation; the hash includes DEFINITIONS and called operations
1247 ->
1248 formatgood('operation ~w unchanged for ~w.',[OpName,MachName]),
1249 %TODO: what if the machine has parameters? Can we reuse the transitions from the generic machine?
1250 find_matching_operations(OpName,MachName,PrefixedOpNames), % find includes with renaming, ...
1251 ( PrefixedOpNames = [] ->
1252 formatwarn('no operation found for ~w in ~w', [OpName,MachName]),
1253 RequiresRefresh=refresh
1254 ;
1255 (PrefixedOpNames = [OpName] -> true
1256 ; formatinfo('(composed/renamed) operations ~w found for ~w in ~w',
1257 [PrefixedOpNames,OpName,MachName])
1258 ),
1259 maplist(store_loadable_operation(OpName,MachName),PrefixedOpNames) )
1260 ;
1261 get_hex_bytes(CurrentHash,CH), get_hex_bytes(StoredHash,SH),
1262 formatwarn('operation ~w has changed (~s, was ~s).',[OpName, CH, SH]),
1263 invalidate_loadable_operation(OpName,MachName),
1264 RequiresRefresh=refresh
1265 )
1266 ;
1267 formatwarn('unrecognised operation ~w.',[OpName]),
1268 RequiresRefresh=refresh
1269 ).
1270 read_cached_operations3(trans_index(OpName,Hash,Index),MachName,RequiresRefresh) :-
1271 ( loadable_short_operation(OpName,MachName,_FullOpNameInCurMachine) ->
1272 compute_short_hash(Hash,Short),
1273 debuggood('loading stored_transition ~w (index ~w) : hash ~w',[OpName,Index,Short]),
1274 assert_stored_transition(Short,Hash,OpName,Index)
1275 ;
1276 % ignore
1277 % potray_loadable_operations,
1278 formatwarn('ignoring stored_transition ~w (index ~w) for ~w',[OpName,Index,MachName]),
1279 RequiresRefresh=refresh
1280 ).
1281
1282 % remove any facts marking operation as loadable; should no longer be necessary
1283 invalidate_loadable_operation(OpName,MachName) :-
1284 retract(loadable_short_operation(OpName,MachName,FullOpName)),
1285 bb_dec(value_persistance_loadable_operations), % see also store_loadable_operation
1286 retract(loadable_operation(FullOpName,OpName,MachName,_,_)),
1287 fail.
1288 invalidate_loadable_operation(OpName,_) :-
1289 operation_has_stored_transition(OpName),!,
1290 add_warning(value_persistance,'Already loaded transitions for invalid operation: ',OpName),
1291 retractall( stored_transition(_,_,OpName,_) ),
1292 retractall( operation_has_stored_transition(OpName) ).
1293 invalidate_loadable_operation(_,_).
1294
1295 % mark an operation as loadable, its hash has been checked
1296 store_loadable_operation(_OpName,_MachName,PrefixedOpName) :-
1297 loadable_operation(PrefixedOpName,_,_,_,_),!.
1298 store_loadable_operation(OpName,MachName,PrefixedOpName) :-
1299 (find_operation_input_output(PrefixedOpName,Input,Output) ->
1300 create_output_pattern(Output,OutputPattern),
1301 check_output_pattern_order(OpName,PrefixedOpName,OutputPattern),
1302 compute_lookup_pattern(OpName,PrefixedOpName,Input,InputPattern)),
1303 !,
1304 bb_inc(value_persistance_loadable_operations),
1305 formatinfo('register loadable_operation from cache: ~w in ~w',[OpName,MachName]),
1306 assertz( loadable_operation(PrefixedOpName,OpName,MachName,InputPattern,OutputPattern)),
1307 assertz( loadable_short_operation(OpName,MachName,PrefixedOpName)), % assert with short name as index
1308 store_machine_has_relevant_operation(MachName,OpName,loadable).
1309 store_loadable_operation(_OpName,_MachName,PrefixedOpName) :-
1310 formatwarn('unable to generate input/output pattern for operation ~w.',
1311 [PrefixedOpName]).
1312
1313 % register that the machine has a loadable or storable operation
1314 store_machine_has_relevant_operation(MachName,_,_) :-
1315 machine_has_relevant_operation(MachName),!.
1316 store_machine_has_relevant_operation(MachName,Op,Kind) :-
1317 formatinfo('machine ~w has a relevant (~w) operation ~w',[MachName,Kind,Op]),
1318 bb_inc(value_persistance_op_cache_machines_with_relevant_ops),
1319 assertz( machine_has_relevant_operation(MachName) ).
1320
1321
1322 find_matching_operations(Operation,MachName,FullNames) :-
1323 findall(O, is_matching_operation(Operation,MachName,O), FullNames).
1324
1325 is_matching_operation(Operation,MachName,Operation) :-
1326 % there is an operation with exactly the same name
1327 operation_with_machine(Operation,MachName).
1328 is_matching_operation(Operation,MachName,FullName) :-
1329 atom_concat('.',Operation,DottedOp),
1330 ? operation_with_machine(FullName,MachName),
1331 atom_concat(_,DottedOp,FullName).
1332
1333
1334 :- use_module(tools,[ split_last/4 ]).
1335 decompose_op_name(FullOpName,MachineName,OpName) :-
1336 split_last(FullOpName, '.', MachineName, OpName).
1337
1338
1339 operation_with_machine(OpName,MachName) :-
1340 ? get_operation_info(OpName,Infos),
1341 ( memberchk(origin(Origin),Infos), % for c1.Inc the origin will be the included machine
1342 last(Origin,_/MachName) -> true
1343 ; main_machine_name(MachName)
1344 ).
1345
1346 :- dynamic machine_has_operations/1.
1347 :- volatile machine_has_operations/1.
1348 precompute_machine_has_operations :-
1349 ? operation_with_machine(_Op,MachName), % this will be used to check if an operation from MachName should be loaded
1350 \+ machine_has_operations(MachName),
1351 assert(machine_has_operations(MachName)), % register that it is useful to load cached operations from MachName
1352 fail.
1353 precompute_machine_has_operations.
1354
1355 create_output_pattern(Ids,Values/Bindings) :-
1356 maplist(create_output_pattern2,Ids,Values,Bindings).
1357 create_output_pattern2(Id,Value,bind(Id,Value)).
1358
1359 %b_top_level_operation_or_init('$initialise_machine'). % TODO: comment in once we support caching INITIALISATION
1360 b_top_level_operation_or_init(OpName) :- b_top_level_operation(OpName).
1361
1362 init_operation_cache(MachName,FullOpName) :-
1363 storable_operation(FullOpName,MachName,_,_InputPattern,_Output),!. % ignore, already registered
1364 init_operation_cache(MachName,OpName) :-
1365 b_top_level_operation_or_init(OpName),!,
1366 init_operation_cache2(MachName,OpName,OpName).
1367 init_operation_cache(MachName,OpName) :-
1368 used_machine_not_included_anywhere(MachName,'',_Kind), % we do not support prefixes other than '' at the moment
1369 ajoin([MachName,'.',OpName],FullOpName), % we create_dummy_machine has created a main machine which INCLUDES MachName with prefix MachName
1370 b_top_level_operation(FullOpName),!,
1371 init_operation_cache2(MachName,OpName,FullOpName).
1372 init_operation_cache(MachName,OpName) :-
1373 % only store top-level operations for which we compute all solutions at the moment
1374 % for subsidiary operations we do a call by predicate; much more difficult to cache/store
1375 (used_machine_not_included_anywhere(MachName,Prefix,Kind)
1376 -> formatinfo('Not storing operation ~w from ~w machine (prefix ~w) ~w which is not INCLUDED',[OpName,Kind,Prefix,MachName])
1377 ; formatinfo('Not storing subsidiary operation ~w in machine ~w',[OpName,MachName])
1378 ).
1379
1380 init_operation_cache2(MachName,OpName,FullOpName) :-
1381 ( find_operation_input_output(FullOpName,Input,Output) ->
1382 compute_lookup_pattern(OpName,FullOpName, Input,InputPattern),
1383 debug_println(9,find_operation_input_output(FullOpName,Input,Output)),
1384 formatdetails('storable operation ~w in machine ~w (short name ~w)',[FullOpName,MachName,OpName]),
1385 bb_inc(value_persistance_storeable_operations),
1386 assertz( storable_operation(FullOpName,MachName,OpName,InputPattern,Output) ),
1387 assertz( storable_operation_full_name(OpName,MachName,FullOpName) ),
1388 store_machine_has_relevant_operation(MachName,OpName,storable)
1389 ;
1390 formatwarn('unable to generate input/output pattern for operation ~w.',[FullOpName])
1391 ).
1392
1393
1394
1395
1396 get_operations_computation_parameters(Name,op_comp_parameters(OpParams)) :-
1397 find_relevant_preferences(Prefs),
1398 get_revision_info(Revision),
1399 compute_sets_signature(Name,SetsSig), % values of enumerated and deferred sets are stored as fd(Nr,Set)
1400 OpParams = [machine_name(Name),prob_revision(Revision),SetsSig|Prefs].
1401
1402 % called from b_interpreter inside b_execute_operation2
1403 lookup_cached_transitions(PrefixedOpName,InState,Info,OutputBindings) :- %write(lookup(PrefixedOpName)),nl,
1404 cache_is_applicable_for_transitions,
1405 (loadable_operation(PrefixedOpName,OpName,MachName,InputPattern,OutputPattern)
1406 -> true
1407 % PrefixedOpName can be something like MachName.OpName, and is a local name
1408 % in the cache file we store the short OpName without prefix
1409 ; debugwarn('no loadable_operation found for: ~w',[PrefixedOpName]),
1410 fail
1411 ),
1412 (operation_has_stored_transition(OpName)
1413 -> true % probcli -execute mode checks uses static_disabled_after/static_cannot_enable to avoid computing hash
1414 ; % otherwise no use in computing hash here
1415 debugwarn('no transition stored for: ~w',[OpName]),
1416 fail
1417 ),
1418 sort(InState,SortedInState),
1419 % tools:start_ms_timer(T1),
1420 hash_input_values(OpName,MachName,InputPattern,SortedInState,ShortHash,InputHash),
1421 % tools:stop_ms_walltimer_with_msg(T1,hash_input(OpName)),
1422 formatdetails('computed hash for looking up ~w : ~w',[PrefixedOpName,ShortHash]),
1423 %portray_stored_transitions,
1424 (stored_transition(ShortHash,InputHash,OpName,Index) -> true
1425 ; debugwarn('no cached operation transition found ~w (~w -> ...).',[PrefixedOpName,ShortHash]),
1426 fail
1427 ), !,
1428 formatgood('re-using values for operation ~w (~w -> ~w).',[OpName,ShortHash,Index]),
1429 %formatdetails('state=~w',[SortedInState]),
1430 start_profile(OpName,T1),
1431 ( load_solutions(MachName,Index,Info,Solutions) -> true
1432 %length(Solutions,Sn),
1433 %format('re-using ~w solutions for operation ~w of machine ~w.~n',
1434 % [Sn,OpName,MachName])
1435 ;
1436 formatwarn('re-using values for operation ~w failed.',[OpName]),
1437 fail),
1438 %print(solution(Solutions)),nl, print(pattern(OutputPattern)),nl,
1439 % OutputPattern is of the form [V1,...]/[bind(v1,V1),...]
1440 bb_inc(value_persistance_reused_transitions),
1441 maplist(create_output_binding(OutputPattern),Solutions,OutputBindings),
1442 %tools:stop_ms_walltimer_with_msg(T1,time_caching(OpName)),
1443 stop_profile(OpName,cache_load_transitions,unknown,T1).
1444 load_solutions(MachName,Index,Info,Solutions) :-
1445 storage_file_name(operations_data,MachName,FilenameData),
1446 catch(load_sol_aux(FilenameData,Index,ReadSolutions),
1447 Exc,
1448 (ajoin(['Corrupt opdata cache file for ',MachName,':'],Msg),
1449 add_error_fail(value_persistance,Msg,Exc))
1450 ),
1451 (ReadSolutions = trans_info(II,S) -> Solutions=S, Info=II ; Solutions=ReadSolutions, Info=[]).
1452 load_sol_aux(FilenameData,Index,Solutions) :-
1453 my_open(FilenameData,read,S,[type(binary),reposition(true)]),
1454 call_cleanup((seek(S,Index,bof,_),
1455 fast_read(S,Solutions)), % read list of transition terms
1456 my_close(S)).
1457
1458 create_output_binding(Pattern,trans_cached(Param,Result,New,Info),
1459 trans_cached(Param,Result,Update,Info)) :-
1460 copy_term(Pattern,New/Update).
1461
1462 % check that it is ok not to remove machine prefix in output pattern
1463 % in the cache file we only store the updated values, not the names of the updated variables
1464 check_output_pattern_order(OpName,PrefixOpName,_/OutputBinds) :-
1465 strip_machine_prefix(OpName,PrefixOpName,OutputBinds,StrippedOutput),
1466 sort(StrippedOutput,SIds),
1467 (SIds = StrippedOutput -> true
1468 ; add_internal_error('Output order influenced by machine prefix:',OpName-(OutputBinds,SIds))).
1469
1470 % select updated variables for a cached operation:
1471 select_output_values(Ids,State,Values) :- sort(State,SState),
1472 select_values_sorted(Ids,SState,Values).
1473 % Note: as Identifiers are sorted then we can avoid quadratic complexity here and scan State only once for all Ids
1474 % Note: we do not need to strip_machine_prefix and sort according to local order, as all ids should be prefixed with the same prefix, see check_output_order
1475 select_values_sorted(Ids,SState,Values) :-
1476 (select_values_sorted_aux(Ids,SState,Values) -> true
1477 ; print('Lookup: '),print(Ids), nl,
1478 print('State: '), maplist(get_bind_id,SState,SIds), print(SIds),nl,fail).
1479 select_values_sorted_aux([],_,[]).
1480 select_values_sorted_aux([Id|Irest],State,[Value|Vrest]) :-
1481 ? ( ordered_select(State,Id,StoredValue,RestState) ->
1482 Value=StoredValue,
1483 select_values_sorted_aux(Irest,RestState,Vrest)
1484 ;
1485 ajoin(['Looking up "', Id, '" failed.'], Msg),
1486 (maplist(get_bind_id,State,Ids) -> true ; Ids = '<<cannot print state ids>>'),
1487 add_error(value_persistance,Msg,Ids),
1488 fail
1489 ).
1490 ordered_select([bind(Id,Value)|T],Id,Value,T).
1491 ?ordered_select([_|T],Id,Value,R) :- ordered_select(T,Id,Value,R).
1492 get_bind_id(bind(Id,_),Id).
1493
1494 % compute a hash of all the values a given operation OpName depends upon
1495 % we have a Short hash used for indexing and the full SHA hash for checking if the value is really identical
1496 % we could perform a separate ShortHash based on term_hash with depth-bound; to check if it makes sense to compute the full hash to lookup a transition (which can be expensive)
1497 hash_input_values(OpName,MachName,InputPattern,SortedInState,Short,Long) :-
1498 % tools:start_ms_timer(T1),
1499 ( hash_input_values2(OpName,MachName,InputPattern,SortedInState,Short,Long) ->
1500 true %,write(hash(Short,OpName,MachName,InputPattern,SortedInState)),nl
1501 %,tools:stop_ms_walltimer_with_msg(T1,time_hashing(OpName,MachName))
1502 % tools:print_memory_used_wo_gc,
1503 ; add_failed_call_error(hash_input_values2(OpName,MachName,InputPattern,SortedInState,Short,Long)),
1504 fail).
1505
1506 hash_input_values2(OpName,MachName,InputPattern,SortedInState,Short,Long) :-
1507 start_profile(OpName,T1),
1508 copy_term(InputPattern,lookup_pattern(SortedVars,SortedInputValues,InputVarsAndCsts,InputValues)),
1509 select_values_sorted(SortedVars,SortedInState,SortedInputValues),
1510 l_pre_hash(InputVarsAndCsts,InputValues,PreHashedInputValues),
1511 % terms:term_size(PreHashedInputValues,Sz), write(hash(OpName,SortedVars,Sz)),nl,
1512 % tools_printing:print_term_summary(raw_sha_hash(OpName,PreHashedInputValues)),nl,
1513 raw_sha_hash(OpName/MachName/PreHashedInputValues,Long),
1514 compute_short_hash(Long,Short),
1515 stop_profile(OpName,cache_hashing_input_values,unknown,T1).
1516 compute_short_hash([A,B,C,D|_],Short) :-
1517 Short is A<<24 + B<<16 + C<<8 + D.
1518
1519 % pre-hash certain potentially large values, so that we do not have to send them to raw_sha_hash every time
1520 l_pre_hash([],[],[]).
1521 l_pre_hash([ID|T],[Val|TV],[PreHashVal|PT]) :-
1522 pre_hash(Val,ID,PreHashVal),
1523 l_pre_hash(T,TV,PT).
1524
1525 :- dynamic constant_pre_hash_cache_active/0.
1526
1527 :- dynamic cst_id_to_hash/2.
1528 :- use_module(probsrc(memoization),[is_memoization_closure/2]).
1529 %pre_hash(Val,_ID,PreHashVal) :-
1530 % is_memoization_closure(Val,MemoID),!, %write(memo(ID,MemoID)),nl,
1531 % PreHashVal = '$MEMO'(MemoID).
1532 pre_hash(Val,CstId,PreHashVal) :-
1533 bmachine:b_is_constant(CstId), % TODO: also use for variables, whose values stay constant
1534 value_can_be_large(Val),!,
1535 (constant_pre_hash_cache_active
1536 -> (cst_id_to_hash(CstId,StoredHash)
1537 -> PreHashVal = StoredHash % used stored value
1538 ; pack_and_compute_sha_hash(Val,Hash),
1539 assert(cst_id_to_hash(CstId,Hash)),
1540 debug_println(4,storing_cache_hash_for_constant(CstId)),
1541 PreHashVal = Hash
1542 )
1543 ; pack_and_compute_sha_hash(Val,PreHashVal) % there can be multiple constant values active
1544 ).
1545 pre_hash(V,_,V).
1546
1547 pack_and_compute_sha_hash(Val,PreHashVal) :-
1548 temporary_set_preference(use_state_packing,false,Change),
1549 pack_value(Val,PackedVal), % to be consistent with pack_constants, which packs/unpacks values (and changes interval rep)
1550 reset_temporary_preference(use_state_packing,Change),
1551 raw_sha_hash(PackedVal,PreHashVal).
1552
1553 :- use_module(probsrc(avl_tools),[avl_height_less_than/2]).
1554 value_can_be_large(avl_set(A)) :- \+ avl_height_less_than(A,7).
1555 value_can_be_large(closure(_,_,_)).
1556 value_can_be_large((A,B)) :- value_can_be_large(A) -> true ; value_can_be_large(B).
1557 value_can_be_large(rec(Fields)) :- (member(field(_,V),Fields), value_can_be_large(V) -> true).
1558
1559 % TODO: separate constants from variables? or do full incremental hashing; by hashing all large sets first
1560 % we also could detect memoization closures and just store their id? or pre-compute their hash and store it?
1561
1562 % save operations_index (.probops) file for machine
1563 % contains operation/2 facts and trans_index/3 facts
1564 save_operations_index_cache(MachName,_OperationNames) :-
1565 create_lock_file(MachName),
1566 machine_cannot_be_locked_for_writing(MachName,Reason),!,
1567 formatdetails('cannot save operations index cache for: ~w (~w)',[MachName,Reason]).
1568 save_operations_index_cache(MachName,OperationNames) :-
1569 get_operations_computation_parameters(MachName,OpParams),
1570 storage_file_name(operations_index,MachName,FileName),
1571 my_open(FileName,write,S,[type(binary)]),
1572 !,
1573 formatdetails('saving operations index cache: ~w',[MachName]),
1574 fast_write(S,OpParams),
1575 get_tail_filename(FileName,TailFileName),
1576 save_operation_info(S,TailFileName,MachName,OperationNames),
1577 my_close(S).
1578 save_operations_index_cache(MachName,_OperationNames) :-
1579 formatwarn('cannot save operations index cache for: ~w',MachName),
1580 assert_machine_cannot_be_locked(MachName,cannot_write_operations_index_file).
1581
1582 % is this really required: it seems to re-write already loaded information to the file; at least in some cases
1583 save_operation_info(S,FileName,MachName,OperationNames) :-
1584 ? member(OpName0,OperationNames),
1585 (storable_operation(OpName0,MachName,OpName,_InputPattern,_Output) -> true % FullOpName=OpName0
1586 ; storable_operation_full_name(OpName0,MachName,FullOpName),
1587 storable_operation(FullOpName,MachName,OpName,_InputPattern,_Output) -> true
1588 ; formatwarn('operation ~w in ~w not marked as storable',[OpName0,MachName]),fail
1589 ),
1590 operation_hash(MachName,OpName,OpHash),
1591 fast_write(S,operation(OpName,OpHash)),
1592 formatinfo('storing hash for operation ~w: ~w',[OpName,OpHash]),
1593 ? stored_transition(Short,InputHash,OpName,Index), % stored_transition uses the short name
1594 formatinfo('storing/refreshing transition for ~w (index ~w, hash ~w) from ~w to ~w',[OpName,Index,Short,MachName,FileName]),
1595 fast_write(S,trans_index(OpName,InputHash,Index)),
1596 bb_inc(value_persistance_refresh_transitions),
1597 fail.
1598 save_operation_info(_S,_F,_MachName,_OperationNames).
1599
1600 % TODO: extend for $initialise_machine
1601 find_operation_input_output(OpName,Input,Output) :-
1602 get_operation_info(OpName,Info),
1603 memberchk(reads(Input1),Info),
1604 % remove references to global sets and their elements
1605 get_all_sets_and_enum_ids(SEIds),
1606 remove_all(Input1,SEIds,Input),
1607 memberchk(modifies(Output),Info).
1608
1609 get_all_sets_and_enum_ids(SEIds) :-
1610 findall(Id,
1611 ( is_b_global_constant(_,_,Id)
1612 ; b_global_set(Id)),
1613 SEIds).
1614
1615
1616
1617 % add new transitions from the state space
1618 add_new_transitions_to_cache(InStateId) :-
1619 cache_is_applicable_for_transitions,
1620 visited_expression(InStateId,InState1),
1621 state_corresponds_to_initialised_b_machine(InState1,InState),
1622 !,
1623 add_new_transitions_to_cache1(InStateId,InState).
1624 add_new_transitions_to_cache(_InStateId).
1625
1626 get_all_max_reached_operations(MaxReachedList) :-
1627 findall(OpName, max_reached(OpName), MaxReached),
1628 sort(MaxReached,MaxReachedList).
1629
1630 :- use_module(library(ordsets),[ord_member/2]).
1631
1632 add_new_transitions_to_cache1(InStateId,InState) :-
1633 get_all_max_reached_operations(MaxReachedList),
1634 %main_machine_name(MachName),
1635 ? storable_operation(FullOpName,MachName,OpName,InputPattern,Output),
1636 \+ time_out_for_node(InStateId,FullOpName,_),
1637 (ord_member(FullOpName,MaxReachedList) -> MaxReached=true ; MaxReached=false),
1638 sort(InState,SortedInState),
1639 add_new_transitions_to_cache2(InStateId,SortedInState,FullOpName,OpName,InputPattern,Output,MaxReached,MachName),
1640 fail.
1641 add_new_transitions_to_cache1(_InStateId,_) :-
1642 flush_data.
1643
1644 add_new_transitions_to_cache2(InStateId,SortedInState,FullOpName,OpName,InputPattern,Output,MaxReached,MachName) :-
1645 hash_input_values(OpName,MachName,InputPattern,SortedInState,ShortHash,InputHash),
1646 \+ stored_transition(ShortHash,InputHash,_,_), % Is there already a cache entry?
1647 find_all_transitions(InStateId,FullOpName,Output,Transitions), % state space uses full name, e.g., Ctr.inc
1648 length(Transitions,Length),
1649 %format('storing ~w transitions for operation ~w in state ~w.~n',
1650 % [Length,OpName,InStateId]),
1651 %print(Transitions),nl,
1652 statistics(runtime,[Start,_]),
1653 statistics(walltime,[WStart,_]),
1654 store_transitions_into_cache(OpName,ShortHash,InputHash,Transitions,MaxReached,MachName),
1655 statistics(runtime,[Stop,_]), Time is Stop - Start,
1656 statistics(walltime,[WStop,_]), WTime is WStop - WStart,
1657 %%tools:print_memory_used_wo_gc,
1658 bb_inc_by(value_persistance_stored_transitions,Length),
1659 formatdetails('storing ~w transitions for operation ~w in state ~w (~w, state ~w, [~w] ms).',
1660 [Length,OpName,InStateId,ShortHash,Time,WTime]).
1661
1662 % store transitions for an operation and given hash of input values
1663 store_transitions_into_cache(OpName,ShortHash,Hash,Transitions,MaxReached,MachName) :-
1664 start_profile(OpName,T1),
1665 storage_file_name(operations_data,MachName,FilenameData),
1666 my_open(FilenameData,read,SR,[type(binary),reposition(true)]),
1667 call_cleanup(seek(SR,0,eof,Index), % gets the end of file before writing transitions
1668 my_close(SR)),
1669 % Note: reposition(true) does not seem to work with append, hence we need to open file twice
1670 (MaxReached = true -> Term = trans_info([max_reached],Transitions) ; Term=Transitions),
1671 my_open(FilenameData,append,SW,[type(binary)]),
1672 !,
1673 call_cleanup(fast_write(SW,Term),
1674 my_close(SW)),
1675 formatdetails('stored ~w (~w), EOF index is ~w for file ~w',[OpName,ShortHash,Index,FilenameData]),
1676 assert_stored_transition(ShortHash,Hash,OpName,Index),
1677 formatdetails('storing ~w index ~w in index file for ~w',[OpName,Index,MachName]),
1678 fast_write_to_operations_index_file(MachName,trans_index(OpName,Hash,Index)),
1679 stop_profile(OpName,cache_store_transitions,unknown,T1).
1680 store_transitions_into_cache(OpName,_ShortHash,_Hash,_Transitions,_MaxReached,MachName) :-
1681 formatwarn('cannot open .opdata to store transitions for ~w into cache for machine ~w',[OpName,MachName]).
1682
1683
1684 assert_stored_transition(ShortHash,Hash,OpName,Index) :-
1685 store_operation_has_stored_transition(OpName),
1686 assertz( stored_transition(ShortHash,Hash,OpName,Index) ).
1687
1688 :- public portray_stored_transitions/0.
1689 portray_stored_transitions :-
1690 format(' - ~w : ~w (~w) --> ~w~n',['Operation','ShortHash','Hash','Index']),
1691 stored_transition(ShortHash,Hash,OpName,Index),
1692 format(' - ~w : ~w (~w) --> ~w~n',[OpName,ShortHash,Hash,Index]),
1693 fail.
1694 portray_stored_transitions.
1695
1696 store_operation_has_stored_transition(X) :- operation_has_stored_transition(X),!.
1697 store_operation_has_stored_transition(X) :- formatdetails('Operation now has a stored transition: ~w',[X]),
1698 assertz( operation_has_stored_transition(X) ).
1699
1700 find_all_transitions(InStateId,OpName,Output,Transitions) :-
1701 findall( trans_cached(ParaValues,ResultValues,Updates,TransInfo),
1702 find_transition(InStateId,OpName,Output,ParaValues,ResultValues,Updates,TransInfo),
1703 Transitions).
1704 find_transition(InStateId,OpName,Output,ParaValues,ResultValues,Updates,TransInfo) :-
1705 ? transition(InStateId,Operation,TransId,OutStateId),
1706 operation_name(Operation,OpName,ParaValues,ResultValues),
1707 findall(TI,transition_info(TransId,TI),TransInfo),
1708 visited_expression(OutStateId,OutState1), % we could use packed_visited_expression here ?
1709 state_corresponds_to_initialised_b_machine(OutState1,OutState),
1710 select_output_values(Output,OutState,Updates).
1711 operation_name('-->'(Operation,ResultValues),OpName,ParaValues,ResultValues) :-
1712 !,operation_name(Operation,OpName,ParaValues,_).
1713 operation_name(Operation,OpName,ParaValues,[]) :-
1714 Operation =.. [OpName|ParaValues].
1715
1716
1717 % add a single new transition, found by execute by predicate or -execute
1718 add_new_transition_to_cache_from_expanded_state(root,_OpTerm,OutState,_CacheInfo) :-
1719 OutState = concrete_constants(_),!,
1720 save_constants_from_expanded_state(OutState).
1721 add_new_transition_to_cache_from_expanded_state(InState0,OpTerm,OutState0,CacheInfo) :-
1722 cache_is_applicable_for_transitions,
1723 %main_machine_name(MachName), % removed check: we also want to store operations for INCLUDED/EXTENDED machines
1724 operation_name(OpTerm,FullOpName,ParaValues,ResultValues),
1725 (storable_operation(FullOpName,MachName,OpName,InputPattern,Output)
1726 -> true
1727 ; bb_inc(value_persistance_not_storeable_transitions),
1728 FullOpName \= '$initialise_machine',
1729 (decompose_op_name(FullOpName,MachName,OpName),
1730 machine_cannot_be_locked_for_writing(MachName,Reason)
1731 -> formatwarn('cannot store operation ~w (~w)',[FullOpName,Reason])
1732 ; formatwarn('cannot store (subsidiary or SEEN?) operation ~w',[FullOpName])
1733 ), fail),
1734 ? \+ new_transition_not_worthwhile(CacheInfo,FullOpName),
1735 % the states can be, e.g., expanded_const_and_vars(...) terms in -execute mode; get the full stores:
1736 state_corresponds_to_initialised_b_machine(InState0,InState),
1737 sort(InState,SortedInState),
1738 hash_input_values(OpName,MachName,InputPattern,SortedInState,ShortHash,InputHash), % can be expensive
1739 formatdetails('computed hash for storing ~w : ~w',[FullOpName,ShortHash]),
1740 (stored_transition(ShortHash,InputHash,_,_) % Is there already a cache entry?
1741 -> debugwarn('transition already exists for ~w : ~w',[FullOpName,ShortHash]),
1742 % should normally not happen: if so we would have used the cache!
1743 fail
1744 ; true),
1745 !,
1746 MaxReached=true, % TODO: should we check that MAX_OPERATIONS is set to exactly 1
1747 TransInfo = [], % TODO: preference(eventtrace,true), preference(store_event_transinfo,true)
1748 Transitions = [trans_cached(ParaValues,ResultValues,Updates,TransInfo)],
1749 state_corresponds_to_initialised_b_machine(OutState0,OutState),
1750 select_output_values(Output,OutState,Updates),
1751 bb_inc(value_persistance_stored_transitions),
1752 %formatinfo('storing ~w (~w) --> ~w and updates ~w for ~w', [OpName,ParaValues,ResultValues,Updates,Output]),
1753 store_transitions_into_cache(OpName,ShortHash,InputHash,Transitions,MaxReached,MachName),
1754 formatinfo('storing single transition for operation ~w in execute mode (~w).', [FullOpName,ShortHash]),
1755 flush_data.
1756 add_new_transition_to_cache_from_expanded_state(_,_,_,_).
1757
1758 % add_deadlock_to_cache_from_expanded_state(InState,OpName) % TODO: worthwhile to store failure info
1759
1760 start_cache_execute_modus(cache_info(StartRuntime,Counter)) :-
1761 statistics(runtime,[StartRuntime,_]),
1762 bb_safe_get(value_persistance_reused_transitions,Counter),
1763 (constant_pre_hash_cache_active -> true
1764 ; assert(constant_pre_hash_cache_active)).
1765
1766 stop_cache_execute_modus :-
1767 retractall(constant_pre_hash_cache_active).
1768
1769 % the pre-computed hashes in cst_id_to_hash are only valid as long as the constants do not change
1770 % (e.g., -execute_all_inits executes from initial states with different constant values)
1771 clear_constant_pre_hash_cache :-
1772 retractall(cst_id_to_hash(_,_)).
1773
1774 new_transition_not_worthwhile(cache_info(_,OldCounter),OpName) :-
1775 bb_safe_get(value_persistance_reused_transitions,Counter),
1776 Counter > OldCounter, % we cannot reuse subsidiary operation calls, so this must be the main operation itself
1777 formatdetails('not storing transition for ~w; it has been extracted from cache itself',[OpName]).
1778 new_transition_not_worthwhile(cache_info(StartRuntime,_),OpName) :-
1779 get_preference(cache_operations_runtime_limit,Limit), Limit>0,
1780 statistics(runtime,[CurrentTime,_]), Delta is CurrentTime-StartRuntime,
1781 Delta < Limit,
1782 bb_inc(value_persistance_not_worth_transitions),
1783 formatinfo('not storing transition for ~w, runtime (ms) ~w smaller than limit ~w', [OpName,Delta,Limit]).
1784
1785
1786
1787 % --------------------
1788
1789 :- use_module(version,[version_str/1]).
1790 :- use_module(probsrc(tools_strings),[format_datime_to_codes/2]).
1791 :- use_module(library(process),[process_id/1, process_kill/2]).
1792 :- use_module(tools_platform, [host_platform/1]).
1793 % create a lock file to write to the cache of a machine
1794 create_lock_file(MachName) :- machine_lock_file_created(MachName),!.
1795 create_lock_file(MachName) :-
1796 storage_file_name(machine_lock_file,MachName,FilenameLock),
1797 (try_create_lock_file(MachName,FilenameLock) -> true
1798 ; stale_lock_file(FilenameLock,OldPID),
1799 formatwarn('removing stale lock file of terminated process ~w for ~w: ~w',[OldPID,MachName,FilenameLock]),
1800 catch(delete_file(FilenameLock),_,true),
1801 try_create_lock_file(MachName,FilenameLock) % can fail if another process has created a new lock file in the meantime
1802 ),
1803 !.
1804 create_lock_file(MachName) :-
1805 assert_machine_cannot_be_locked(MachName,cannot_create_lock_file),
1806 storage_file_name(machine_lock_file,MachName,FilenameLock),
1807 (file_exists(FilenameLock),
1808 file_property(FilenameLock, modify_localtime, Time),
1809 format_datime_to_codes(Time,TC)
1810 -> formatwarn('cannot write cache for ~w (locked by other process at ~s); delete ~w if no other process uses the cache',[MachName,TC,FilenameLock])
1811 ; formatwarn('cannot write cache for ~w (unknown problem)',[MachName])
1812 ).
1813
1814 try_create_lock_file(MachName,FilenameLock) :-
1815 process_id(PID),
1816 my_open(FilenameLock,write,FLOCK,[type(text),if_exists(error)]),
1817 assertz(machine_lock_file_created(MachName)),
1818 version_str(VS), format(FLOCK,'process_id(~w).~nversion(~w).~n',[PID,VS]),
1819 close(FLOCK),
1820 formatdetails('machine locked for writing cache: ~w',[MachName]).
1821
1822 % a lock file is stale if the process which created it no longer exists, e.g., because it crashed
1823 % Note: we assume that the process ran on the same computer
1824 stale_lock_file(FilenameLock,PID) :-
1825 \+ host_platform(windows), % on Windows process_kill would terminate the process
1826 file_exists(FilenameLock),
1827 catch(read_lock_file_process_id(FilenameLock,PID),_,fail),
1828 (process_id(PID) -> true % our process did not create it, see create_lock_file; the PID has been re-used
1829 ; \+ process_exists(PID)).
1830
1831 read_lock_file_process_id(FilenameLock,PID) :-
1832 open(FilenameLock,read,S),
1833 call_cleanup(read(S,Term),close(S)),
1834 Term = process_id(PID), integer(PID).
1835
1836 % check if process exists by sending signal 0
1837 process_exists(PID) :-
1838 catch(process_kill(PID,0),E,true),
1839 (var(E) -> true
1840 ? ; E = error(_,system_error(Msg)), atom(Msg), sub_atom(Msg,_,_,_,'NOT_FOUND') -> fail
1841 ; true % e.g., no permission to send signal: process exists
1842 ).
1843
1844 assert_machine_cannot_be_locked(MachName,Reason) :-
1845 assertz(machine_cannot_be_locked_for_writing(MachName,Reason)),
1846 retractall( storable_operation(_,MachName,_,_,_) ), % we cannot store operations
1847 retractall( storable_operation_full_name(_,MachName,_) ).
1848
1849
1850 open_data_file(MachName) :-
1851 operations_index_file_opened(MachName,_),!,
1852 formatdetails('data file already open: ~w',[MachName]).
1853 open_data_file(MachName) :-
1854 create_lock_file(MachName),
1855 ? machine_cannot_be_locked_for_writing(MachName,Reason),!,
1856 formatdetails('data file cannot be opened for ~w (~w)',[MachName,Reason]).
1857 open_data_file(MachName) :-
1858 storage_file_name(operations_index,MachName,FilenameIndex),
1859 my_open(FilenameIndex,append,FI,[type(binary)]),
1860 !,
1861 (get_preference(cache_keep_files_open,true)
1862 -> assertz(operations_index_file_opened(MachName,FI)),
1863 formatgood('operation index file (.probops) opened for ~w',[MachName])
1864 ; my_close(FI)),
1865 create_opdata_file_if_necessary(MachName).
1866 open_data_file(MachName) :-
1867 formatwarn('cannot open index file (.probops) for: ~w (maybe due to concurrent access)',[MachName]),
1868 % TODO: catch permission error due to concurrent access, when multiple ProB instances are running
1869 assert_machine_cannot_be_locked(MachName,cannot_open_operations_index_file).
1870
1871 create_opdata_file_if_necessary(MachName) :-
1872 storage_file_name(operations_data,MachName,FilenameData),
1873 ( file_exists(FilenameData)
1874 -> true
1875 ; formatinfo('creating data file ~w',[FilenameData]), % .opdata
1876 my_open(FilenameData,write,SD,[type(binary)]), % TODO: catch exceptions
1877 my_close(SD)).
1878
1879 flush_data :-
1880 findall(M,(operations_index_file_opened(M,S),flush_output(S)),L),
1881 (L=[],get_preference(cache_keep_files_open,true),
1882 storable_operation(_,_,_,_,_) % otherwise nothing to store, e.g., machine ignored or locked by other process
1883 -> formatwarn('no index file opened for flush_data',[])
1884 ; true).
1885
1886 fast_write_to_operations_index_file(Machine,Term) :-
1887 operations_index_file_opened(Machine,FI),!,
1888 fast_write(FI,Term).
1889 fast_write_to_operations_index_file(Machine,Term) :-
1890 get_preference(cache_keep_files_open,false),
1891 storage_file_name(operations_index,Machine,FilenameIndex),
1892 my_open(FilenameIndex,append,FI,[type(binary)]),!,
1893 call_cleanup(fast_write(FI,Term),my_close(FI)).
1894 fast_write_to_operations_index_file(Machine,_Term) :-
1895 get_preference(cache_keep_files_open,false),
1896 !,
1897 % in this case we have written a transition to .opdata, but cannot store it in the index file
1898 % this is not terrible; but we waste space and cannot reuse the transition
1899 formatwarn('could not store index for operation transition in cache for ~w; later reuse of this transition not possible ',[Machine]).
1900 fast_write_to_operations_index_file(Machine,Term) :-
1901 add_internal_error('No operations_index file open',fast_write_to_operations_index_file(Machine,Term)),fail.
1902
1903 :- use_module(tools_lists,[remove_dups_keep_order/2]).
1904 find_loadable_machines(SortedSolutions) :-
1905 findall(loadable(Type,Machine),
1906 find_loadable_machines2(Type,Machine),
1907 Solutions),
1908 remove_dups_keep_order(Solutions,SortedSolutions).
1909
1910 find_loadable_machines2(Type,Machine) :-
1911 main_machine_name(Main),
1912 ? find_loadable_machines_sees_includes(Main,Type,Machine),
1913 \+ ignore_cache_for_machine(Machine). % Note: this does not prevent machines included from Machine to be loaded
1914 find_loadable_machines_sees_includes(Main,main,Main).
1915 find_loadable_machines_sees_includes(Main,sub,Seen) :-
1916 machine_sees(Main,_Prefix,M),
1917 ? find_loadable_machines_sees_includes(M,_,Seen).
1918 find_loadable_machines_sees_includes(Start,sub,Included) :-
1919 ? machine_includes(Start,_Prefix1,M),
1920 ? find_loadable_machines_sees_includes(M,_,Included).
1921
1922
1923 machine_sees(MachA,Prefix,MachB) :-
1924 machine_references(MachA,References),
1925 ? member(ref(Type,MachB,Prefix),References),
1926 memberchk(Type,[sees,uses]).
1927 machine_includes(MachA,Prefix,MachB) :-
1928 machine_references(MachA,References),
1929 ? member(ref(Type,MachB,Prefix),References),
1930 memberchk(Type,[includes,extends]).
1931
1932 % lookup_pattern/2:
1933 % To enable a fast lookup of values in a state, we have to sort the variables.
1934 % In the past we did not sort the variables when storing them,
1935 % Now we also sort the variables when storing, but according to the local machine order (to enable to re-use SEEN/USED machines with different prefixes)
1936 % This predicate generates a "lookup_pattern" that sorts the variables and their
1937 % corresponding values and enables to map the sorted values to the original order
1938 % by a simple unification.
1939 compute_lookup_pattern(OpName,PrefixOpName,
1940 Variables,lookup_pattern(SortedVariables,SortedValues,VariablesToHash,ValuesToHash)) :-
1941 maplist(variable_value_pair,Variables,VarValues,_),
1942 sort(VarValues,SortedVarValues),
1943 maplist(variable_value_pair,SortedVariables,SortedVarValues,SortedValues),
1944 strip_machine_prefix(OpName,PrefixOpName,VarValues,StrippedVarValues),
1945 sort(StrippedVarValues,SVV),
1946 maplist(variable_value_pair,VariablesToHash,SVV,ValuesToHash),
1947 (append(_,[V,V|_],VariablesToHash) -> add_internal_error('Duplicate id to hash:',OpName:V) ; true).
1948
1949 variable_value_pair(I,I/V,V).
1950
1951 strip_machine_prefix(OpName,OpName,Vars,Res) :- !, Res=Vars.
1952 strip_machine_prefix(OpName,PrefixOpName,VarValues,Res) :-
1953 atom_concat(Prefix,OpName,PrefixOpName),!,
1954 % strip MachName. prefix from variables, so that we sort and store the correct local names
1955 % this is relevant if another main machine uses the cache for this same subsidiary machine
1956 maplist(strip_machine_prefix_aux(Prefix),VarValues,Res).
1957 strip_machine_prefix(OpName,PrefixOpName,Vars,Vars) :-
1958 formatwarn('cannot strip prefix for operation ~w (to ~w), leading to sub-optimal cache re-use',[PrefixOpName,OpName]).
1959
1960 strip_machine_prefix_aux(Prefix,Bind,NewBind) :-
1961 get_bind(Bind,NewBind,VarName,NewVarName),
1962 (atom_concat(Prefix,Suffix,VarName) -> NewVarName = Suffix ; NewVarName = VarName).
1963 get_bind(VarName/V,NewVarName/V,VarName,NewVarName).
1964 get_bind(bind(VarName,V),bind(NewVarName,V),VarName,NewVarName).
1965
1966 % utility for statistics:
1967
1968 reset_counters :-
1969 ? (is_counter(C), bb_reset(C), fail ; true).
1970
1971 print_value_persistance_stats :-
1972 format_with_colour_nl(user_output,[blue],'ProB Value Persistance Caching Statistics',[]),
1973 (storage_directory(Dir)
1974 -> format_with_colour_nl(user_output,[blue],'* Cache storage directory: ~w',[Dir])
1975 ; format_with_colour_nl(user_output,[orange],'* No cache storage directory set!',[])
1976 ),
1977 bb_safe_get(value_persistance_constants_loaded,C),
1978 format_with_colour_nl(user_output,[blue],' * Nr. of main machines for which stored constants were reused: ~w',[C]),
1979 bb_safe_get(value_persistance_ref_constants_loaded,RC),
1980 format_with_colour_nl(user_output,[blue],' * Nr. of referenced machines for which stored constants were reused: ~w',[RC]),
1981 bb_safe_get(value_persistance_stored_constants,StCs),
1982 format_with_colour_nl(user_output,[blue],' * Nr. of solutions for constants stored: ~w',[StCs]),
1983 bb_safe_get(value_persistance_op_cache_machines,OCM),
1984 format_with_colour_nl(user_output,[blue],' * Nr. of machines processed for cache: ~w',[OCM]), % not ignored
1985 bb_safe_get(value_persistance_op_cache_machines_with_relevant_ops,OCMR),
1986 format_with_colour_nl(user_output,[blue],' * Nr. of machines for which operations can be reused/stored: ~w',[OCMR]),
1987 bb_safe_get(value_persistance_loadable_operations,LO),
1988 format_with_colour_nl(user_output,[blue],' * Nr. of stored operations which can be re-used: ~w',[LO]),
1989 bb_safe_get(value_persistance_storeable_operations,SO),
1990 format_with_colour_nl(user_output,[blue],' * Nr. of operations which can be stored: ~w',[SO]),
1991 bb_safe_get(value_persistance_reused_transitions,R),
1992 format_with_colour_nl(user_output,[blue],' * Nr. of stored operation calls reused: ~w',[R]),
1993 bb_safe_get(value_persistance_stored_transitions,S),
1994 format_with_colour_nl(user_output,[blue],' * Nr. of operation calls *not* reused and stored: ~w',[S]),
1995 bb_safe_get(value_persistance_not_worth_transitions,WW),
1996 format_with_colour_nl(user_output,[blue],' * Nr. of operation calls *not* reused and *not* stored due to CACHE_OPERATIONS_RUNTIME_LIMIT: ~w',[WW]),
1997 bb_safe_get(value_persistance_not_storeable_transitions,WW2),
1998 format_with_colour_nl(user_output,[blue],' * Nr. of operation calls *not* reused and *not* storeable: ~w',[WW2]),
1999 bb_safe_get(value_persistance_refresh_transitions,RF),
2000 format_with_colour_nl(user_output,[blue],' * Nr. of operation calls refreshed: ~w',[RF]).
2001
2002 get_value_persistance_stats(List) :-
2003 findall(Counter-Value,(is_counter(Counter),bb_safe_get(Counter,Value)),List).
2004
2005 is_counter(value_persistance_constants_loaded).
2006 is_counter(value_persistance_ref_constants_loaded).
2007 is_counter(value_persistance_stored_constants).
2008 is_counter(value_persistance_loadable_operations).
2009 is_counter(value_persistance_op_cache_machines).
2010 is_counter(value_persistance_op_cache_machines_with_relevant_ops).
2011 is_counter(value_persistance_storeable_operations).
2012 is_counter(value_persistance_reused_transitions).
2013 is_counter(value_persistance_stored_transitions).
2014 is_counter(value_persistance_not_worth_transitions).
2015 is_counter(value_persistance_not_storeable_transitions).
2016 is_counter(value_persistance_refresh_transitions).
2017
2018 bb_reset(Counter) :- bb_put(Counter,0).
2019
2020
2021 % utility for debugging:
2022
2023 debugwarn(_Format,_Args) :- debug_mode(off),!.
2024 debugwarn(Format,Args) :- format_prefix(magenta),
2025 format_with_colour_nl(user_output,[magenta],Format,Args).
2026
2027 debuggood(_,_) :- debug_mode(off),!.
2028 debuggood(Format,Args) :- format_prefix(cyan),
2029 format_with_colour_nl(user_output,[cyan],Format,Args).
2030
2031 formatwarn(Format,Args) :- format_prefix(orange),
2032 format_with_colour_nl(user_output,[orange],Format,Args).
2033
2034 formatinfo(_Format,_Args) :- silent_mode(on),!.
2035 formatinfo(Format,Args) :- format_prefix(grey),
2036 format_with_colour_nl(user_output,[grey],Format,Args).
2037
2038 formatdetails(_Format,_Args) :- (silent_mode(on) ; debug_mode(off)), % or TRACE_INFO ?
2039 !.
2040 formatdetails(Format,Args) :- format_prefix(grey),
2041 format_with_colour_nl(user_output,[grey],Format,Args).
2042
2043 formatgood(_Format,_Args) :- silent_mode(on),!.
2044 formatgood(Format,Args) :- format_prefix(green),
2045 format_with_colour_nl(user_output,[green],Format,Args).
2046
2047 format_prefix(Color) :- silent_mode(off), process_id(PID),!,
2048 format_with_colour(user_output,[Color],'value caching (~w): ',[PID]).
2049 format_prefix(Color) :-
2050 format_with_colour(user_output,[Color],'value caching: ',[]).
2051
2052
2053 my_open(File,Mode,Stream,Opt) :-
2054 catch(open(File,Mode,Stream,Opt),
2055 error(Error,_),
2056 (Error = permission_error(Action,_X,_F) % _X is either source_sink or past_end_of_stream
2057 -> formatwarn('permission error while opening ~w (~w) for action ~w',[File,Mode,Action]),fail
2058 ; ajoin(['Unknown error when opening file ',File,' in mode ',Mode,': '],Msg),
2059 add_error(value_persistance,Msg,Error), fail)),
2060 formatdetails('opened file (~w) ~w -> ~w',[Mode,File,Stream]).
2061
2062 my_close(Stream) :- debug_mode(off), !, close(Stream).
2063 my_close(Stream) :- stream_property(Stream,file_name(F)),
2064 stream_property(Stream,mode(M)),!,
2065 formatinfo('closing ~w (~w) -> ~w',[F, M, Stream]),
2066 close(Stream).
2067 my_close(Stream) :-
2068 formatinfo('closing -> ~w',[Stream]),
2069 close(Stream).
2070
2071 % -------------------
2072
2073 potray_loadable_operations :-
2074 format_with_colour_nl(user_output,[blue],'loadable_operations:',[]),
2075 loadable_operation(PrefixedOpName,OpName,MachName,InputPattern,_OutputPattern),
2076 format_with_colour_nl(user_output,[blue],'* ~w : (~w in ~w)',[PrefixedOpName,OpName,MachName]),
2077 InputPattern=lookup_pattern(SortedVars,_,_,_),
2078 format_with_colour_nl(user_output,[gray],' input: ~w',[SortedVars]),
2079 fail.
2080 potray_loadable_operations.