1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(state_space_reduction,
6 [
7 % a generic state space reduction predicate:
8 reduce_state_space/2,
9
10 % these are the facts generated by reduce_state_space:
11 get_reduced_node/4, reduced_trans/5,
12 equivalence_class/2,
13
14 % makes use of reduce_state_space to compute the signature-merge:
15 compute_signature_merge/0,
16 write_signature_merge_to_dotfile/1, write_signature_merge_to_dotfile/2,
17 tcltk_write_signature_merge_to_dotfile/2,
18 write_covered_values_for_expression_to_csvfile/2,
19 initialised_b_state_exists/0,
20 compute_covered_values_for_expression/4, compute_covered_values_for_expression/5,
21 compute_set_of_covered_values_for_typed_expression/2,
22 tcltk_compute_nr_covered_values_for_all_variables/1,
23 tcltk_compute_nr_covered_values_for_all_constants/1,
24
25 % makes use of reduce_state_space to compute the transition diagram for an expression:
26 compute_transition_diagram/1,
27 write_transition_diagram_for_expr_to_dotfile/2,
28 generate_node_color/5,
29 generate_node_labels/3,
30 generate_transition_label/3,
31 generate_transition_color_and_style/6,
32 reset_ignored_events/0,
33 set_ignored_events/1
34 ]).
35
36 :- use_module(probsrc(module_information)).
37 :- module_info(group,dot).
38 :- module_info(description,'This module computes state space projections for dot visualizations.').
39
40
41 :- meta_predicate reduce_state_space(3,5).
42 :- meta_predicate reduce_selected_states(1,3,-).
43 :- meta_predicate reduce_states(3,-).
44 :- meta_predicate sm_node_pred(2,-,-,-,-,-,-).
45
46
47 :- use_module(probsrc(state_space)).
48 :- use_module(probsrc(error_manager)).
49
50 :- use_module(probsrc(b_interpreter),[b_compute_expression_nowf/6]).
51 :- use_module(probsrc(debug),[debug_mode/1,time/1,formatsilent/2]).
52 :- use_module(probsrc(hashing),[my_term_hash/2]).
53 %:- use_module(probltlsrc(ltl_tools),[check_atomic_property_formula/2,preprocess_formula/2]).
54 %:- use_module(probltlsrc(ltl_tools),[temporal_parser/3]).
55
56 :- use_module(extension('counter/counter'),
57 [counter_init/0, new_counter/1, get_counter/2, inc_counter/2]).
58
59 :- dynamic reduced_node/5, equivalence_class/2,
60 equivalence_class_contains_current_node/1, equivalence_class_contains_open_node/1.
61 :- dynamic reduced_trans/5.
62 reset :- retractall(reduced_node(_,_,_,_,_)), retractall(equivalence_class(_,_)),
63 retractall(equivalence_class_contains_current_node(_)),
64 retractall(equivalence_class_contains_open_node(_)),
65 retractall(reduced_trans(_,_,_,_,_)),
66 counter_init,
67 new_counter(transition_id), new_counter(equiv_class_id).
68 % ---------------------------
69
70 % An implementation of signature merge algorithm:
71
72 :- dynamic ignore_event/1.
73 reset_ignored_events :- %print(reseting_ignore_event),nl,
74 retractall(ignore_event(_)).
75 set_ignored_events([]).
76 set_ignored_events([H|T]) :- assertz(ignore_event(H)),
77 format('Ignoring: ~w~n',[H]),
78 set_ignored_events(T).
79 signature_and_inv(ID,S,AbsState) :-
80 (invariant_violated(ID) -> AbsState = [invariant_violated|Sig] ; AbsState = Sig),
81 signature(ID,S,Sig).
82 signature(ID,_,AbsState) :-
83 findall(Name,(transition(ID,Action,_,_),specfile:get_operation_name(Action,Name),
84 \+ ignore_event(Name)), L),
85 (L=[] ->
86 (not_all_transitions_added(ID) -> AbsState = ['NOT YET EXPLORED']
87 ; transition(ID,_,_,_) -> AbsState = ['NO SELECTED EVENTS']
88 ; AbsState = ['DEADLOCK'])
89 ; sort(L,AbsState)
90 ).
91
92 transition_name(_,Action,_,_,Name) :- specfile:get_operation_name(Action,Name),
93 \+ ignore_event(Name).
94
95 compute_signature_merge :-
96 % we could provide options: not consider invariant, ignore certain transitions, ...
97 reduce_state_space(signature_and_inv,transition_name).
98
99 :- use_module(cbcsrc(sap),[tcl_convert_event_numbers_to_names/2]).
100 tcltk_write_signature_merge_to_dotfile(IgnoredEventNrs,File) :-
101 tcl_convert_event_numbers_to_names(list(IgnoredEventNrs),list(IgnoredEvents)),
102 %print(tcl_convert_event_numbers_to_names(list(IgnoredEventNrs),list(IgnoredEvents))),nl,
103 write_signature_merge_to_dotfile(IgnoredEvents,File).
104
105 :- use_module(dotsrc(dot_graph_generator), [gen_dot_graph/3, gen_dot_graph/6, use_new_dot_attr_pred/7, dot_no_same_rank/1, dot_no_subgraph/3]).
106 write_signature_merge_to_dotfile(IgnoredEvents,File) :-
107 reset_ignored_events,
108 set_ignored_events(IgnoredEvents),
109 time(state_space_reduction:compute_signature_merge), % from debug module
110 (IgnoredEvents=[] -> Title='Signature merge'
111 ; ajoin_with_sep(IgnoredEvents,', ',IEs), ajoin(['Signature merge (ignoring ',IEs,')'],Title)),
112 get_preference(dot_print_self_loops,SELF),
113 sm_graph_attrs(signature_merge,Title,GraphAttrs),
114 gen_dot_graph(File,GraphAttrs,
115 use_new_dot_attr_pred(state_space_reduction:sm_dot_node(simple_list)),
116 use_new_dot_attr_pred(state_space_reduction:sm_dot_edge(SELF)),
117 dot_no_same_rank,dot_no_subgraph),
118 reset_ignored_events.
119 write_signature_merge_to_dotfile(File) :-
120 write_signature_merge_to_dotfile([],File).
121
122 :- use_module(library(lists),[maplist/3]).
123 :- use_module(probsrc(tools),[ajoin/2, string_escape/2]).
124 % node predicate for gen_dot_graph:
125 :- public sm_node_pred/7.
126 sm_node_pred(GenLabels,EqNodeID,SubGraph,NodeDesc,Shape,Style,Color) :- SubGraph=none,
127 Shape=record,
128 get_reduced_node(AbsState,C1,Witness,EqNodeID),
129 (equivalence_class_contains_current_node(EqNodeID) -> Style = bold % bold, diagonals, rounded
130 % we could optionally turn this off in case the UI wants to do this itself and update when the animator changes state
131 ; Style = none), % or rounded
132 %insert_commas(AbsState,0,CL),
133 (AbsState = [invariant_violated|Signature]
134 -> Labels = ['INVARIANT VIOLATED\\n|'|EscCL]
135 ; Labels = EscCL, Signature = AbsState
136 ),
137 call(GenLabels,Signature,CL),
138 maplist(string_escape,CL,EscCL),
139 %maplist : tools:wrap_and_truncate_atom(EscCL,30,121,EscCLW),
140 insert_newlines(Labels,0,100,LabelsNL),
141 append(['|{' | LabelsNL],['\\n|# states: ',C1,'}|'],Atoms),
142 ajoin(Atoms,NodeDesc),
143 generate_node_color(EqNodeID,Witness,AbsState,C1,Color).
144
145 % insert newline if line become too long
146 insert_newlines([],_,_,[]).
147 insert_newlines([H|T],CurCodes,Limit,Res) :-
148 atom_length(H,Len),
149 C1 is CurCodes+Len,
150 ((C1 > Limit, CurCodes>0)
151 -> Res = ['\\n',H|TR], insert_newlines(T,Len,Limit,TR)
152 ; Res = [H|TR], insert_newlines(T,C1,Limit,TR)).
153
154
155 generate_node_color(EquivClassNodeID,_Witness,AbsState,Count,Color) :-
156 (AbsState=['NOT YET EXPLORED'] -> Color=orange
157 ; AbsState = [invariant_violated|_] -> Color=red
158 ; AbsState = ['DEADLOCK'] -> Color=red
159 ; equivalence_class_contains_open_node(EquivClassNodeID) -> Color=orange
160 ; Count>1 -> Color=blue
161 ; Color=green).
162
163 generate_node_labels(GenLabels,AbsState,Labels) :-
164 (AbsState = [invariant_violated|Signature]
165 -> Labels = ['INVARIANT VIOLATED'|CL]
166 ; Labels = CL, Signature = AbsState
167 ),
168 call(GenLabels,Signature,CL).
169
170 generate_transition_label(AbsAction,Count,Label) :-
171 (Count>1
172 -> ajoin([AbsAction,' : ',Count],Label)
173 ; Label=AbsAction
174 ).
175
176 :- use_module(probsrc(preferences),[get_preference/2]).
177 generate_transition_color_and_style(ShowSelfLoops,NodeID,AbsAction,SuccID,Color,Style) :-
178 %format(user_output,'~w~n',[p(ShowSelfLoops,NodeID,AbsAction,SuccID)]),
179 (reduced_trans(NodeID,AbsAction,_,Other,_),
180 Other \= SuccID
181 -> % there exists another transition of the same abstract action leading to another equivalence class
182 % Note: here we always show self-loops
183 get_preference(dot_projection_non_det_edge_colour,Color),
184 get_transition_style(NodeID,AbsAction,SuccID,Style)
185 ; self_loop_check(NodeID,SuccID,ShowSelfLoops), % here we only show self-loops if requested by user
186 get_preference(dot_projection_det_edge_colour,Color),
187 get_transition_style(NodeID,AbsAction,SuccID,Style)
188 ).
189
190 non_definite_edge(NodeID,AbsAction,SuccID) :-
191 abs_signature(NodeID,AlwaysEnabled),
192 nonmember(AbsAction/SuccID,AlwaysEnabled).
193
194 get_transition_style(NodeID,AbsAction,SuccID,Style) :-
195 non_definite_edge(NodeID,AbsAction,SuccID),
196 !, % the edge is not always possible
197 get_preference(dot_projection_non_definite_edge_style,Style).
198 get_transition_style(_,_,_,Style) :-
199 get_preference(dot_projection_definite_edge_style,Style).
200
201 self_loop_check(NodeID,SuccID,ShowSelfLoops) :-
202 (NodeID==SuccID -> ShowSelfLoops=true % if we have a single self-loop then only show it if preference set
203 ; true).
204
205
206 :- public insert_commas/2.
207 % this should probably be outsourced to another module:
208 insert_commas(L,R) :- insert_commas(L,0,R).
209 insert_commas([],_,[]).
210 insert_commas([H],_,R) :- !, R=[H].
211 insert_commas([H|T],N,[H,Sep|IT]) :-
212 (N>5 -> N1=0, Sep=',\\n' ; N1 is N+1, Sep=', '),
213 insert_commas(T,N1,IT).
214
215 % transition predicate for gen_dot_graph:
216 sm_trans_predicate(ShowSelfLoops,NodeID,Label,SuccID,Color,Style) :-
217 sm_trans_predicate(ShowSelfLoops,NodeID,_AbsAction,Label,SuccID,Color,Style).
218 sm_trans_predicate(ShowSelfLoops,NodeID,AbsAction,Label,SuccID,Color,Style) :-
219 reduced_trans(NodeID,AbsAction,Count,SuccID,_TID),
220 % TO DO: maybe merge all AbsAction with the same Origin & Destination into single transition
221 generate_transition_label(AbsAction,Count,Label),
222 generate_transition_color_and_style(ShowSelfLoops,NodeID,AbsAction,SuccID,Color,Style).
223
224 % ---------------------------
225 % new-style (attribute list) dot node and edge predicates for signature merge and transition diagram
226
227 :- use_module(probsrc(tools),[html_escape/2]).
228 :- use_module(probsrc(tools_strings),[ajoin_with_sep/3]).
229
230 sm_graph_attrs(GraphName,Title,[graph_name/GraphName, no_page_size, deals_with_pref/dot_print_self_loops,
231 fontname/'Helvetica', nodesep/0.3, ranksep/0.5,
232 node_defaults/[fontname/'Helvetica', fontsize/11, shape/box, style/'rounded,filled', margin/'0.12,0.06'],
233 edge_defaults/[fontname/'Helvetica', fontsize/9, arrowsize/0.8]
234 | TitleAttrs]) :-
235 (get_preference(dot_print_graph_title,true)
236 -> get_counter(equiv_class_id,NrClasses),
237 state_space:get_state_space_stats(NrStates,_,_),
238 ajoin([Title,'\\n',NrClasses,' classes for ',NrStates,' states'],FullTitle),
239 get_preference(dot_title_font_size,TFS), TitleAttrs = [label/FullTitle, labelloc/t, fontsize/TFS]
240 ; TitleAttrs = []).
241
242 :- public sm_dot_node/4.
243 :- meta_predicate sm_dot_node(2,-,-,-).
244 % one node per equivalence class
245 sm_dot_node(GenLabels,EqNodeID,none,[label/htmllabel(Label), tooltip/Tooltip, fillcolor/Fill, color/Col | Attrs]) :-
246 get_reduced_node(AbsState,Count,Witness,EqNodeID),
247 sm_node_class(EqNodeID,Witness,AbsState,Count,Class),
248 sm_class_colours(Class,Fill,Col,LegendText,Order),
249 (AbsState = [invariant_violated|Signature]
250 -> Header='<font point-size="9" color="#C62828"><b>INVARIANT VIOLATED</b></font><br/>'
251 ; Signature = AbsState,
252 (Class=root -> Header='<font point-size="9" color="#707070">root</font><br/>' ; Header='')),
253 call(GenLabels,Signature,Items),
254 maplist(html_escape,Items,EItems),
255 sm_wrap_items(EItems,0,50,ItemsHtml),
256 (Class=root -> CountHtml=''
257 ; Count=1 -> CountHtml='<br/><font point-size="9" color="#707070">1 state</font>'
258 ; ajoin(['<br/><font point-size="9" color="#707070">',Count,' states</font>'],CountHtml)),
259 ajoin(['<',Header,ItemsHtml,CountHtml,'>'],Label),
260 (equivalence_class_contains_current_node(EqNodeID)
261 -> Attrs = [penwidth/3 | LAttrs], CurTxt=', contains current state' ; Attrs=LAttrs, CurTxt=''),
262 (Witness = root -> ajoin(['root',CurTxt],Tooltip)
263 ; ajoin([Count,' state(s), e.g. state ',Witness,CurTxt],Tooltip)),
264 (get_preference(dot_print_legend,true) -> LAttrs=[legend/LegendText, legend_order/Order] ; LAttrs=[]).
265
266 sm_node_class(_,Witness,_,_,Class) :- Witness==root, !, Class=root.
267 sm_node_class(_,_,AbsState,_,unexplored) :- (AbsState=['NOT YET EXPLORED'] ; AbsState=not_yet_explored), !.
268 sm_node_class(_,_,[invariant_violated|_],_,invariant_violated) :- !.
269 sm_node_class(_,_,['DEADLOCK'],_,deadlock) :- !.
270 sm_node_class(EqNodeID,_,_,_,unexplored) :- equivalence_class_contains_open_node(EqNodeID), !.
271 sm_node_class(_,_,_,Count,merged) :- Count>1, !.
272 sm_node_class(_,_,_,_,single).
273
274 sm_class_colours(root,white,'#616161','root (before initialisation)',10).
275 sm_class_colours(single,'#E4F2E5','#2E7D32','single state',20).
276 sm_class_colours(merged,'#E3EDF7','#1F5F99','several states',30).
277 sm_class_colours(unexplored,'#FFF3E0','#C77700','contains unexplored states',40).
278 sm_class_colours(deadlock,'#F3E5F5','#6A1B9A','deadlock',50).
279 sm_class_colours(invariant_violated,'#FDECEA','#C62828','invariant violated',60).
280
281 % join items with ", " and break lines after Limit characters
282 sm_wrap_items([],_,_,'').
283 sm_wrap_items([H],_,_,H) :- !.
284 sm_wrap_items([H|T],Cur,Limit,Res) :-
285 atom_length(H,Len), C1 is Cur+Len+2,
286 (C1 > Limit -> Sep=',<br/>', C2=0 ; Sep=', ', C2=C1),
287 sm_wrap_items(T,C2,Limit,TRes),
288 ajoin([H,Sep,TRes],Res).
289
290 :- public sm_dot_edge/4.
291 % one edge per pair of classes, colour and style; labels of the merged transitions are joined
292 sm_dot_edge(ShowSelfLoops,NodeID,SuccID,[label/Label, color/Color, fontcolor/Color, style/Style, tooltip/Tooltip | LAttrs]) :-
293 findall(edge(NodeID1,SuccID1,Color1,Style1)-(Lbl/Act),
294 sm_trans_predicate(ShowSelfLoops,NodeID1,Act,Lbl,SuccID1,Color1,Style1),Edges),
295 sort(Edges,SEdges),
296 findall(E,member(E-_,SEdges),Keys), sort(Keys,SKeys),
297 member(edge(NodeID,SuccID,Color,Style),SKeys),
298 findall(L,member(edge(NodeID,SuccID,Color,Style)-(L/_),SEdges),Labels),
299 findall(A,member(edge(NodeID,SuccID,Color,Style)-(_/A),SEdges),Actions),
300 ajoin_with_sep(Labels,', ',Tooltip),
301 sm_edge_label(Actions,Labels,Label),
302 (get_preference(dot_print_legend,true), sm_edge_legend(Color,Style,LegendText,Order)
303 -> LAttrs = [legend/LegendText, legend_order/Order] ; LAttrs = []).
304
305 % compact label for an edge with many events:
306 % 1. if the edge covers all operations (or all but a few): all events / all events except ...
307 % 2. otherwise wrap the event names over several lines and cut off after a maximum number of events
308 sm_edge_label(Actions,_Labels,Label) :-
309 sm_all_operations(AllOps),
310 sort(Actions,SActions),
311 length(SActions,NrActions), NrActions>2,
312 ord_subset(SActions,AllOps),
313 ord_subtract(AllOps,SActions,Missing),
314 length(Missing,NrMissing),
315 NrMissing*2 < NrActions, % only use the complement when it is much shorter than the list itself
316 !,
317 (eventb_mode -> All='all events' ; All='all operations'),
318 (Missing=[] -> Label=All
319 ; sm_wrap_label(Missing,Rest),
320 ajoin([All,' except\\n',Rest],Label)).
321 sm_edge_label(_,Labels,Label) :- sm_wrap_label(Labels,Label).
322
323 sm_wrap_label(Labels,Label) :-
324 get_preference(dot_projection_max_edge_label_events,Max),
325 length(Labels,Len),
326 (Len > Max, Max>0
327 -> length(Shown,Max), append(Shown,_,Labels),
328 NrMore is Len-Max,
329 ajoin(['\x2026\ +',NrMore,' more'],More),
330 append(Shown,[More],Items)
331 ; Items=Labels),
332 sm_wrap_plain(Items,0,40,Label).
333
334 % join items with ", " and break lines (using dot's \\n) before a line would exceed Limit characters
335 sm_wrap_plain([],_,_,'').
336 sm_wrap_plain([H|T],_,Limit,Res) :- atom_length(H,Len), sm_wrap_plain2(T,Len,Limit,H,Res).
337 sm_wrap_plain2([],_,_,Acc,Acc).
338 sm_wrap_plain2([H|T],Cur,Limit,Acc,Res) :-
339 atom_length(H,Len), C1 is Cur+Len+2,
340 (C1 > Limit -> ajoin([Acc,',\\n',H],Acc2), C2=Len ; ajoin([Acc,', ',H],Acc2), C2=C1),
341 sm_wrap_plain2(T,C2,Limit,Acc2,Res).
342
343 :- use_module(probsrc(specfile),[b_or_z_mode/0, eventb_mode/0]).
344 :- use_module(probsrc(bmachine),[b_top_level_operation/1]).
345 :- use_module(library(ordsets),[ord_subset/2, ord_subtract/3]).
346 % the names of all operations/events of the machine, sorted
347 sm_all_operations(AllOps) :- b_or_z_mode,
348 findall(Op,b_top_level_operation(Op),Ops),
349 sort(Ops,AllOps), AllOps \= [].
350
351 sm_edge_legend(Color,Style,Text,Order) :-
352 (get_preference(dot_projection_non_det_edge_colour,Color)
353 -> D='non-deterministic', O1=2 ; D='deterministic', O1=0),
354 (get_preference(dot_projection_non_definite_edge_style,Style), \+ get_preference(dot_projection_definite_edge_style,Style)
355 -> E='not enabled in all states', O2=1 ; E='enabled in all states', O2=0),
356 ajoin([D,', ',E],Text),
357 Order is 100+O1+O2.
358
359 % ---------------------------
360
361 % Implementation of the Transition Diagram for Expression
362 % evaluate an expression for every state; merge those states that have the same value
363 % show in the diagram how the value can be changed by various operations
364 :- use_module(probsrc(store),[normalise_value_for_var/4]).
365 :- use_module(probsrc(specfile),[ state_corresponds_to_initialised_b_machine/2]).
366 state_value_for_expr(Expr,_ID,root,AbsState) :- !, AbsState=expr(Expr).
367 state_value_for_expr(_Expr,ID,_State,AbsState) :-
368 get_preference(dot_projection_process_only_explored,true),
369 (invariant_still_to_be_checked(ID) -> A=not_yet_explored
370 ; not_interesting(ID) -> A=not_interesting), % SCOPE predicate false
371 !, AbsState=A.
372 state_value_for_expr(Expr,ID,State,AbsState) :-
373 state_corresponds_to_initialised_b_machine(State,BState),
374 b_compute_expression_nowf(Expr,[],BState,Val,'state space reduction',ID),!,
375 Expand=false,
376 normalise_value_for_var(Expr,Expand,Val,AbsState). % not necessary if Expr is a simple ID, but then we use state_value_for_variable
377 state_value_for_expr(_Expr,_ID,_State,undefined).
378
379 :- use_module(probsrc(specfile),[ state_corresponds_to_initialised_b_machine/1]).
380 % check if at least one initialised state exists; otherwise transition diagram makes no sense
381 initialised_b_state_exists :-
382 visited_expression(_,S),
383 state_corresponds_to_initialised_b_machine(S).
384
385 :- public guard_reduce/5.
386 % a valid argument for reduce_states: combines GuardPredicate with AbstractAndFilterStates predicate
387 guard_reduce(GuardPredicate,AbstractAndFilterStates,ID,State,Value) :-
388 call(GuardPredicate,ID,State),
389 call(AbstractAndFilterStates,ID,State,Value).
390
391 :- use_module(probltlsrc(ltl_tools),[temporal_parser/3]).
392 :- use_module(probltlsrc(ltl),[preprocess_formula/2]).
393 add_ltl_ap_guard('',Pred,Res) :- !,Res=Pred.
394 add_ltl_ap_guard(LTLAP,Pred,guard_reduce(check_ltl_ap(PF),Pred)) :-
395 temporal_parser(LTLAP,ltl,Result),
396 preprocess_formula(Result,PF).
397
398 :- use_module(probltlsrc(ltl_propositions),[check_atomic_property_formula/2]).
399 :- public check_ltl_ap/3.
400 % a valid argument for guard_reduce
401 check_ltl_ap(AtomicLTLProperty,ID,_State) :-
402 check_atomic_property_formula(AtomicLTLProperty,ID).
403
404 % a valid argument for reduce_states
405 state_value_for_variable(Variable,_ID,State,Value) :- get_variable_value(State,Variable,Value).
406 % comment in lines below if you want to use it for transition diagram; however then we need to adapt tcltk_compute_nr_covered_values_for_all_variables
407 %get_variable_value(root,Variable,Value) :- !, Value = Variable.
408 get_variable_value(const_and_vars(_ID,S),Variable,Value) :- !, member(bind(Variable,Value),S).
409 %get_variable_value(concrete_constants(_),_Variable,Value) :- !, Value=undefined.
410 get_variable_value(csp_and_b(_CSP,BState),Variable,Value) :- !,
411 get_variable_value(BState,Variable,Value).
412 get_variable_value(S,Variable,Value) :- !, member(bind(Variable,Value),S).
413
414 % as above but also check invariant status
415 state_value_for_expr_and_inv(Expr,ID,State,ResAbsState) :-
416 state_value_for_expr(Expr,ID,State,AbsState),
417 (invariant_violated(ID) -> ResAbsState = [invariant_violated|AbsState]
418 % TO DO: also look if invariant_not_yet_checked ?, ... not_all_transitions_added ?
419 ; ResAbsState = AbsState).
420
421 compute_transition_diagram(Expr) :-
422 reduce_state_space(state_value_for_expr_and_inv(Expr),transition_name).
423
424 :- use_module(probsrc(bmachine), [parse_expression_raw_or_atom_with_prob_ids/2,
425 parse_expression_or_predicate_raw_or_atom_with_prob_ids/2]).
426 :- use_module(dotsrc(dot_graph_generator), [gen_dot_graph/6,dot_no_same_rank/1, dot_no_subgraph/3]).
427
428 % VorE can also be a predicate P: the state space is then projected onto bool(P)
429
430 write_transition_diagram_for_expr_to_dotfile(VorE,File) :-
431 %print(expr(VorE)),
432 parse_expression_or_predicate_raw_or_atom_with_prob_ids(VorE,TypedExpr),
433 statistics(walltime,[W1,_]),
434 compute_transition_diagram(TypedExpr),
435 statistics(walltime,[W2,_]),
436 (get_preference(dot_use_unicode,true) -> translate:set_unicode_mode ; true),
437 get_preference(dot_print_self_loops,SELF),
438 translate:translate_bexpression_with_limit(TypedExpr,60,ExprStr),
439 ajoin(['Transition diagram for ',ExprStr],Title),
440 sm_graph_attrs(transition_diagram,Title,GraphAttrs),
441 call_cleanup(
442 gen_dot_graph(File,GraphAttrs,
443 use_new_dot_attr_pred(state_space_reduction:sm_dot_node(gen_label)),
444 use_new_dot_attr_pred(state_space_reduction:sm_dot_edge(SELF)),
445 dot_no_same_rank,dot_no_subgraph),
446 (get_preference(dot_use_unicode,true) -> translate:unset_unicode_mode ; true)),
447 statistics(walltime,[W3,_]),
448 (debug_mode(on)
449 -> W is W3-W1, W12 is W2-W1,
450 format('Time to compute transition diagram projection and write to file: ~w ms (~w ms for projection)~n',[W,W12])
451 ; true).
452 % the original version only kept those transitions that actually change an expression
453 % we could easily do this here by adapting sm_trans_predicate
454
455
456
457 :- public gen_label/2.
458 gen_label(expr(Expr),[Str]) :- !,
459 get_preference(dot_projection_label_limit,Lim), L2 is Lim*2,
460 translate:translate_bexpression_with_limit(Expr,L2,Str).
461 gen_label(Value,[Str]) :-
462 get_preference(dot_projection_label_limit,Lim),
463 (translate:translate_bvalue_with_limit(Value,Lim,Str)
464 -> true; Str = 'fail').
465
466 :- public simple_list/2.
467 % used by get_signature_merge_state_space
468 simple_list(List,List).
469
470 :- use_module(probsrc(bsyntaxtree), [get_texpr_type/2]).
471 :- use_module(probsrc(kernel_objects),[max_cardinality/2]).
472 :- use_module(probsrc(translate), [get_bexpression_column_template/4]).
473 % compute which values are present in the state space for a give Expression
474 compute_covered_values_for_expression(ExprToEvaluate,MaxTypeCard,TotalNrOfValuesFound,Res) :-
475 LTLGuard='',
476 compute_covered_values_for_expression(ExprToEvaluate,LTLGuard,MaxTypeCard,TotalNrOfValuesFound,Res).
477 compute_covered_values_for_expression(ExprToEvaluate,LTLGuard,MaxTypeCard,TotalNrOfValuesFound,
478 list([list(['Nr'|AllColHeaders])|LResult])) :-
479 parse_expression_raw_or_atom_with_prob_ids(ExprToEvaluate,TypedExpr),
480 translate:translate_bexpression_with_limit(TypedExpr,100,Str),
481 get_bexpression_column_template(TypedExpr,Values,ColHeaders,Columns),
482 append(ColHeaders,['Occurences',
483 'State ID' % used instead of 'Witness ID' so that ProB2-UI proposes popup menu
484 ],AllColHeaders),
485 get_texpr_type(TypedExpr,ExprType),
486 (max_cardinality(ExprType,MaxTypeCard) -> true ; MaxTypeCard='??'),
487 state_space:get_state_space_stats(NrNodes,_,_),
488 format('Computing all values in initialised states (of ~w states in total) for expression: ~w [Max.Card=~w]~n',[NrNodes,Str,MaxTypeCard]),
489 construct_projection_pred_for_typed_expr(TypedExpr,ProjPred),
490 add_ltl_ap_guard(LTLGuard,ProjPred,FullProjPred),
491 reduce_states(FullProjPred,false),
492 format('Collecting values~n',[]),
493 findall(list(StrVals),covered_values(StrVals,Values,Columns),Result),
494 sort(Result,SResult),
495 add_line_numbers(SResult,LResult,TotalNrOfValuesFound).
496
497 % a version which computes a list/set of values for an already typed expression
498 compute_set_of_covered_values_for_typed_expression(TypedExpr,SetOfValues) :-
499 construct_projection_pred_for_typed_expr(TypedExpr,ProjPred),
500 %add_ltl_ap_guard(LTLGuard,ProjPred,FullProjPred),
501 reduce_states(ProjPred,false),
502 state_space:get_state_space_stats(NrNodes,_,_),
503 format('Collecting (Count, WitnessID, Value) triples for all ~w states in state space~n',[NrNodes]),
504 findall( ((int(Count),int(Witness)),Val),
505 (get_reduced_node(Val,Count,Witness,_EquivClassID),Witness\=root),SetOfValues).
506
507
508 % ---------------
509
510 tcltk_compute_nr_covered_values_for_all_variables(list([list(['Variable', 'Number of Values'])|VL])) :-
511 state_space:get_state_space_stats(NrNodes,_,_),
512 format('Computing all values in ~w states for all variables~n',[NrNodes]),
513 findall(list([ID,Count]),number_of_values_for_variable(ID,Count),VL),
514 format('Finished computing all values for all variables~n',[]).
515
516 number_of_values_for_variable(ID,Count) :-
517 bmachine:b_is_variable(ID),
518 reduce_states(state_value_for_variable(ID),false),
519 get_counter(equiv_class_id,Count),
520 format('~w : ~w~n',[ID,Count]).
521
522
523 tcltk_compute_nr_covered_values_for_all_constants(list([list(['Constant', 'Number of Values'])|VL])) :-
524 state_space:get_state_space_stats(NrNodes,_,_),
525 format('Computing all values in ~w states for all constants~n',[NrNodes]),
526 findall(list([ID,Count]),number_of_values_for_constant(ID,Count),VL),
527 format('Finished computing all values for all constants~n',[]).
528
529 number_of_values_for_constant(ID,Count) :-
530 bmachine:b_is_constant(ID),
531 reduce_selected_states(is_concrete_constants_state_id,get_constant_value(ID),false),
532 get_counter(equiv_class_id,Count),
533 format('~w : ~w~n',[ID,Count]).
534
535 get_constant_value(VariableID,_,concrete_constants(S),Value) :- !, member(bind(VariableID,Value),S).
536
537 % ---------------
538
539
540 :- use_module(probsrc(bsyntaxtree),[get_texpr_id/2]).
541 construct_projection_pred_for_typed_expr(TypedExpr,Predicate) :-
542 get_texpr_id(TypedExpr,ID),
543 bmachine:b_is_variable(ID),!,
544 % use optimized, faster state_value_for_variable predicate
545 Predicate = state_value_for_variable(ID).
546 construct_projection_pred_for_typed_expr(TypedExpr,Predicate) :-
547 Predicate = state_value_for_expr(TypedExpr).
548
549
550 add_line_numbers(T,LT,Total) :- add_line_numbers_aux(T,0,LT,Total).
551 add_line_numbers_aux([],Nr,[],Nr) :- format('Found ~w different values.~n',[Nr]).
552 add_line_numbers_aux([list(H)|T],Nr,[list([N1|H])|LT],Total) :-
553 N1 is Nr+1,
554 add_line_numbers_aux(T,N1,LT,Total).
555
556 covered_values(AllColumns,Values,Columns) :-
557 get_reduced_node(AbsState,Count,Witness,_EquivClassID),
558 Witness \= root,
559 Witness \= concrete_constants(_),
560 AbsState \= undefined,
561 % TO DO: maybe add further info: card for sets, dom, ran for relations ?
562 translate_abs_value(AbsState,Values,Columns,StrVals),
563 append(StrVals,[Count,Witness],AllColumns).
564
565 translate_abs_value(AbsState,Values,Columns,StrVals) :-
566 AbsState=Values, !,
567 maplist(mytranslate,Columns,StrVals).
568 translate_abs_value(undefined,_Values,Columns,StrVals) :- !,
569 maplist(myundefined,Columns,StrVals).
570 translate_abs_value(AbsState,_Values,_Columns,[StrVal]) :-
571 mytranslate(AbsState,StrVal).
572
573 myundefined(_,undefined).
574 mytranslate(Value,StrVal) :-
575 translate:translate_bvalue_with_limit(Value,100,StrVal).
576
577
578 write_covered_values_for_expression_to_csvfile(VorE,File) :-
579 print('Parsing and type checking'),nl,
580 parse_expression_raw_or_atom_with_prob_ids(VorE,TypedExpr),
581 translate:translate_bexpression_with_limit(TypedExpr,100,Str),
582 format('Computing all values for expression: ~w~n',[Str]),
583 reduce_states(state_value_for_expr(TypedExpr),false),
584 format('Writing values to CSV file: ~w~n',[File]),
585 open(File,write,Stream,[encoding(utf8)]),
586 format(Stream,'"~w",~w,~w,~n',[Str,'Occurences','WitnessStateID']),
587 call_cleanup(write_covered_values_for_expression_to_csvfile_aux(Stream), close(Stream)),
588 format('Finished writing values to CSV file: ~w~n',[File]).
589 write_covered_values_for_expression_to_csvfile(_VorECodes,File) :-
590 add_error(state_space_reduction,'Computing Value Coverage Failed',File).
591
592 write_covered_values_for_expression_to_csvfile_aux(S) :-
593 get_reduced_node(AbsState,Count,Witness,_EquivClassID),
594 (Witness=root -> StrVal = '?'
595 ; translate:translate_bvalue_with_limit(AbsState,100,StrVal)),
596 format(S,'"~w",~w,~w~n',[StrVal,Count,Witness]),
597 fail.
598 write_covered_values_for_expression_to_csvfile_aux(_).
599
600
601 % ---------------------------
602 % the generic state space reduction Algorithm:
603 % it takes two predicates:
604 % AbstracAndFilterStates: it should succeed for those states that we want to process
605 % and then generate an abstract representation of it
606 % AbstractAndFilterTransitions: it should succeed for all transtitions to be processed
607 % and also generate an abstract representation
608 % Note: all states with the same abstract representation will be merged;
609 % the same is true for transitions
610
611
612 reduce_state_space(AbstracAndFilterStates,
613 AbstractAndFilterTransitions) :-
614 retractall(abs_signature(_,_)),
615 % first compute equivalence class for every state
616 statistics(walltime,[W1,_]),
617 reduce_states(AbstracAndFilterStates,true),
618 statistics(walltime,[W2,_]),
619 (debug_mode(on)
620 -> W12 is W2-W1, format('Time to abstract and filter states: ~w ms~n',[W12]) ; true),
621 %set_prolog_flag(profiling,on),
622 % now inspect every transition for every node (that has been retained)
623 equivalence_class(ID,EquivClassID), %print(id_class(ID,EquivClassID)),nl,
624 findall(AbsAction/DestEquivClassID,
625 get_and_add_abstract_transition(ID,AbstractAndFilterTransitions,EquivClassID,
626 AbsAction,DestEquivClassID),
627 UnsortedSignature),
628 sort(UnsortedSignature,Signature), %print(sig(Signature)),nl,
629 update_signature(EquivClassID,Signature),
630 fail.
631 reduce_state_space(_,_). % :- set_prolog_flag(profiling,off),print_profile.
632
633 :- use_module(library(ordsets),[ord_intersection/3]).
634 % store those abstract transitions which are always enabled
635 :- dynamic abs_signature/2.
636 update_signature(EquivClassID,Signature) :-
637 (abs_signature(EquivClassID,OldSignature)
638 -> (Signature=OldSignature -> true
639 % ; OldSignature = [] -> true % already minimal
640 ; ord_intersection(OldSignature,Signature,NewSignature),
641 %print(updated_signature(NewSignature)),nl,
642 (NewSignature=OldSignature -> true
643 ; retract(abs_signature(EquivClassID,OldSignature)),
644 assertz(abs_signature(EquivClassID,NewSignature))
645 )
646 )
647 ; assertz(abs_signature(EquivClassID,Signature))).
648 % examine every outgoing transition, compute the abstract action and destination equivalence class
649 % and add a new transition in the reduced state space if necessary
650 get_and_add_abstract_transition(ID,AbstractAndFilterTransitions,EquivClassID,AbsAction,DestEquivClassID) :-
651 transition(ID,Action,TransId,Destination),
652 equivalence_class(Destination,DestEquivClassID),
653 call(AbstractAndFilterTransitions,ID,Action,TransId,Destination,AbsAction),
654 %print(trans(EquivClassID,DestEquivClassID,AbsAction)),nl,
655 add_new_abstract_transition(EquivClassID,DestEquivClassID,ID,Action,TransId,Destination,AbsAction).
656
657 all_states(_).
658 reduce_states(AbstractAndFilterStates,AssertEquivClass) :-
659 reduce_selected_states(all_states,AbstractAndFilterStates,AssertEquivClass).
660 reduce_selected_states(SelectionPred,AbstractAndFilterStatesPred,AssertEquivClass) :-
661 reset,
662 call(SelectionPred,ID),
663 % compute equivalence class for every state selected by SelectionPred
664 visited_expression(ID,State),
665 call(AbstractAndFilterStatesPred,ID,State,AbsState),
666 % should succeed if state to be shown
667 %print(state(ID,AbsState)),nl,
668 add_new_abstract_node(ID,State,AbsState,AssertEquivClass,_EquivClassID),
669 fail.
670 reduce_selected_states(_,_,_).
671
672 get_reduced_node(AbsState,Count,Witness,EquivClassID) :-
673 reduced_node(_Hash,AbsState,Count,Witness,EquivClassID).
674 add_new_abstract_node(ID,_State,AbsState,AssertEquivClass,EquivClassID) :-
675 % TO DO: use hashing to improve lookup ! hashing:my_term_hash
676 my_term_hash(AbsState,Hash),
677 (retract(reduced_node(Hash,AbsState,Count,Witness,EquivClassID))
678 -> C1 is Count+1,
679 assertz(reduced_node(Hash,AbsState,C1,Witness,EquivClassID))
680 ; inc_counter(equiv_class_id,EquivClassID),
681 (print_progress(EquivClassID,ID)
682 -> formatsilent('% Number of equivalence classes: ~w. Treated ~w states so far.~n',[EquivClassID,ID])
683 ; true),
684 assertz(reduced_node(Hash,AbsState,1,ID,EquivClassID))
685 ),
686 (AssertEquivClass==false % we compute ohter stuff; e.g., just coverage,....
687 -> true
688 ; assertz(equivalence_class(ID,EquivClassID)),
689 (current_expression(ID,_) -> assertz(equivalence_class_contains_current_node(EquivClassID)) ; true),
690 ((not_all_transitions_added(ID), \+equivalence_class_contains_open_node(EquivClassID))
691 -> assertz(equivalence_class_contains_open_node(EquivClassID)) ; true)
692 ).
693 print_progress(EquivClassID,_ID) :- EquivClassID mod 10 =:= 0 ;EquivClassID = 5.
694
695 % this version does not count (for efficiency reasons):
696 add_new_abstract_transition(EquivClassID,DestEquivClassID,_ID,_Action,_TransId,_Destination,AbsAction) :-
697 (reduced_trans(EquivClassID,AbsAction,_Count,DestEquivClassID,_TransitionID)
698 -> true
699 ; inc_counter(transition_id,TransitionID),
700 assertz(reduced_trans(EquivClassID,AbsAction,1,DestEquivClassID,TransitionID))
701 ).
702 % TO DO: make more efficient version by using C counters
703 /*
704 add_new_abstract_transition(EquivClassID,DestEquivClassID,_ID,_Action,_TransId,_Destination,AbsAction) :-
705 (retract(reduced_trans(EquivClassID,AbsAction,Count,DestEquivClassID,TransitionID))
706 -> C1 is Count+1,
707 assertz(reduced_trans(EquivClassID,AbsAction,C1,DestEquivClassID,TransitionID))
708 ; inc_counter(1,TransitionID),
709 assertz(reduced_trans(EquivClassID,AbsAction,1,DestEquivClassID,TransitionID))
710 ).
711 */