1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5
6 :- module(state_custom_dot_graph,[tcltk_generate_state_custom_dot_graph/1,
7 state_custom_dot_graph_available/0,
8 tcltk_generate_state_custom_dot_graph_for_expr/2,
9 is_valid_custom_dot_graph_record/1]).
10
11 :- use_module(probsrc(module_information)).
12 :- module_info(group,dot).
13 :- module_info(description,'This module provides a way to generate custom state graphs (using info from DEFINITIONS).').
14
15 % The best way to use this feature is to describe nodes and edges by records
16 % Nodes should be records with a
17 % - value field, used to compute the internal id and used by the edges
18 % - label field: the text shown in dot for the node
19 % Here is an example:
20 % CUSTOM_GRAPH_NODES == {p•p∈Pairs|rec(`value`:p, label:```${p}\nu=${u(p)}```,
21 % style: IF prj2(p)=certain THEN "solid" ELSE "dashed" END,
22 % color: IF prj1(p)=fair THEN "green" ELSE "red" END, shape:"rect")};
23 % Edges should be records with
24 % - from and to fields which should match the value field of some node
25 % - label field: the text associated with the edge
26 % Here is an example:
27 % CUSTOM_GRAPH_EDGES == {a,b• a∈Pairs ∧ b∈Pairs ∧ u(a) > u(b) | rec(from:a,to:b,label:">")}
28 % You can also merge everything into a single CUSTOM_GRAPH definition
29 % CUSTOM_GRAPH == rec(layout:"circo", nodes:mynodes, edges:myedges)
30
31 :- use_module(dotsrc(dot_graph_generator)).
32
33 %:- use_module(self_check).
34 :- use_module(probsrc(error_manager)).
35
36 :- use_module(probsrc(state_space),[current_expression/2]).
37 :- use_module(probsrc(bsyntaxtree), [get_texpr_id/2]).
38 :- use_module(probsrc(specfile), [state_corresponds_to_fully_setup_b_machine/2]).
39 :- use_module(probsrc(debug), [debug_println/2, debug_format/3]).
40 :- use_module(probsrc(bmachine), [b_get_machine_custom_nodes_function/2,b_get_machine_custom_edges_function/2,
41 b_get_machine_custom_graph_function/2]).
42 :- use_module(probsrc(preferences),[valid_rgb_color/1, valid_dot_shape/1,
43 valid_dot_line_style/1, valid_dot_node_style/1]).
44 :- use_module(probsrc(tools),[start_ms_timer/1, stop_ms_timer_with_msg/2]).
45 :- use_module(library(lists),[exclude/3]).
46
47 :- set_prolog_flag(double_quotes, codes).
48
49
50 state_custom_dot_graph_available :-
51 b_get_machine_custom_graph_function(_,_) ;
52 % b_get_machine_custom_nodes_function(_,_) ;
53 ? b_get_machine_custom_edges_function(_,_).
54
55 reset_custom_defs :-
56 retractall(custom_nodes(_,_,_,_)),
57 retractall(custom_edges(_,_,_,_)),
58 retractall(custom_graph(_,_)),
59 retractall(custom_node_id(_,_)), retractall(nodectr(_)),
60 retractall(custom_trans_label(_,_)), retractall(trans_ctr(_)), assertz(trans_ctr(1)).
61
62 tcltk_generate_state_custom_dot_graph(File) :-
63 get_state_for_graph(BState),
64 ? (state_custom_dot_graph_available
65 -> true
66 ; add_error_and_fail(tcltk_generate_state_custom_dot_graph,
67 'No CUSTOM_GRAPH_EDGES or CUSTOM_GRAPH Function in DEFINITIONS')),
68 reset_custom_defs,
69 start_ms_timer(Timer),
70 eval_defs(BState),
71 gen_graph(File),
72 stop_ms_timer_with_msg(Timer,'custom graph: ').
73
74 :- use_module(probsrc(eval_let_store),[extend_state_with_probids_and_lets/2]).
75 :- use_module(probsrc(specfile), [get_current_state_for_b_formula/2]).
76 % provide a way to create a custom graph from an expression
77 % this expression should be a record with nodes, nedges fields, like a CUSTOM_GRAPH definition
78 tcltk_generate_state_custom_dot_graph_for_expr(GraphFunction,File) :-
79 get_current_state_for_b_formula(GraphFunction,BState),
80 extend_state_with_probids_and_lets(BState,BState1),
81 reset_custom_defs,
82 eval_custom_graph_function(GraphFunction,0,BState1),
83 gen_graph(File).
84
85 :- use_module(probsrc(preferences),[temporary_set_preference/3, reset_temporary_preference/2]).
86 gen_graph(File) :-
87 (custom_graph(_,UserGraphAttrs) -> true ; UserGraphAttrs=[]),
88 add_custom_graph_defaults(UserGraphAttrs,GraphAttrs),
89 temporary_set_preference(dot_print_self_loops,true,Chng), % the user provides the edges function explicitly, show all edges
90 call_cleanup(gen_dot_graph(File,GraphAttrs,
91 use_new_dot_attr_pred(state_custom_dot_graph:cg_node_predicate),
92 use_new_dot_attr_pred(state_custom_dot_graph:cg_trans_predicate),
93 dot_no_same_rank,
94 cg_subgraph_predicate), %dot_no_subgraph),
95 reset_temporary_preference(dot_print_self_loops,Chng)).
96
97 % default graph, node and edge attributes; attributes provided by the user in CUSTOM_GRAPH
98 % (or for individual nodes and edges) take precedence, as dot uses the last value given
99 add_custom_graph_defaults(UserAttrs,Attrs) :-
100 Defaults = [graph_name/custom_graph, fontname/'Helvetica',
101 node_defaults/[fontname/'Helvetica', fontsize/11],
102 edge_defaults/[fontname/'Helvetica', fontsize/10, arrowsize/0.8]],
103 exclude(user_overrides_attr(UserAttrs),Defaults,Defaults1),
104 ((member(page/_,UserAttrs) ; member(size/_,UserAttrs) ; member(ratio/_,UserAttrs))
105 -> Attrs1 = Defaults1 % keep page layout of user
106 ; Attrs1 = [no_page_size|Defaults1]),
107 append(Attrs1,UserAttrs,Attrs).
108 user_overrides_attr(UserAttrs,Attr/_) :- member(Attr/_,UserAttrs).
109
110 get_state_for_graph(BState) :-
111 current_expression(_CurID,State),
112 state_corresponds_to_fully_setup_b_machine(State,BState),!.
113 get_state_for_graph(_) :- % we could look at type of definitions and use get_current_state_for_b_formula
114 add_error_and_fail(state_custom_dot_graph,'Only possible for initialised B machine.').
115
116 % check if something is a valid record for CUSTOM_GRAPH
117 % it must have a nodes and edges field
118 is_valid_custom_dot_graph_record(b(rec(Fields),_,_)) :-
119 member(field(NodesField,_),Fields), is_nodes_field(NodesField,_),!,
120 member(field(EdgesField,_),Fields), is_edges_field(EdgesField,_),!.
121
122 :- use_module(library(lists),[select/3]).
123 eval_defs(BState) :-
124 ? b_get_machine_custom_nodes_function(NodesFunction,Nr),
125 ? eval_definition_fun(NodesFunction, Nr, nodes, BState, Infos, NodesRes),
126 debug_println(19,custom_nodes(Nr,NodesRes)),
127 (select(id/EFID,Infos,RestInfos) % id has priority of label
128 -> assertz(custom_nodes(EFID,Nr,RestInfos,NodesRes))
129 ; select(label/EFID,Infos,RestInfos)
130 -> assertz(custom_nodes(EFID,Nr,RestInfos,NodesRes))
131 ; get_texpr_id(NodesFunction,EFID)
132 -> assertz(custom_nodes(EFID,Nr,Infos,NodesRes))
133 ; % we cannot derive name, then generate one
134 number_codes(Nr,NC), append("custom",NC,CC), atom_codes(Custom,CC),
135 assertz(custom_nodes(Custom,Nr,Infos,NodesRes))),
136 fail.
137 eval_defs(BState) :-
138 ? b_get_machine_custom_edges_function(EdgesFunction,Nr),
139 ? eval_definition_fun(EdgesFunction, Nr, edges, BState, Infos, EdgesRes),
140 debug_println(19,custom_edges(Nr,EdgesRes)),
141 ? (select(label/Label,Infos,RestInfos) -> true
142 ; get_texpr_id(EdgesFunction,Label) -> RestInfos=Infos
143 ? ; b_get_machine_custom_edges_function(_,Nr2), Nr2 \= Nr % other relation exists; makes sense to use label
144 -> number_codes(Nr,NC), append("custom",NC,CC),
145 atom_codes(Label,CC),RestInfos=Infos
146 ; Label='',RestInfos=Infos
147 ),
148 assertz(custom_edges(Label,Nr,RestInfos,EdgesRes)),
149 % print(edges(Label,Nr,RestInfos)),nl, translate:print_bvalue(EdgesRes),nl,nl,
150 fail.
151 eval_defs(BState) :-
152 b_get_machine_custom_graph_function(GraphFunction,Nr),
153 format('Detected single CUSTOM_GRAPH DEFINITION ~w~n',[Nr]),
154 eval_custom_graph_function(GraphFunction,Nr,BState),
155 fail.
156 eval_defs(_).
157
158 % Process a single CUSTOM_GRAPH record
159 % Example:
160 % rec(layout:"fdp",directed:TRUE,
161 % edges:rec(colorscheme:"purples9",
162 % edges:{x,y•x:2..50 & y:2..(x-1) & x mod y =0|
163 % rec(edge:y|->x, label:"div", color:1 + x mod 9)} ),
164 % nodes:rec(colorscheme:"set312", style:"filled",
165 % nodes:{x•x:2..50|rec(label:x,
166 % fillcolor: 1 + x mod 11) } ) );
167 eval_custom_graph_function(GraphFunction,Nr,BState) :-
168 eval_definition_fun(GraphFunction, Nr, graph, BState, GraphAttrs, rec(OtherFields)),
169 exclude(process_nodes_field([],GraphFunction),OtherFields,Infos1),
170 exclude(process_edges_field([],GraphFunction),Infos1,Infos2),
171 % instead of passing [] above, we could auto-detect GraphAttrs which are node or edge attributes
172 (Infos2 = [] ->
173 (Infos1=[]
174 -> add_message(state_custom_dot_graph,'No edges detected in CUSTOM_GRAPH: ',OtherFields,GraphFunction)
175 ; true)
176 ; add_warning(state_custom_dot_graph,'Unrecognized CUSTOM_GRAPH fields: ',Infos2,GraphFunction)),
177 (custom_graph(_,_)
178 -> add_warning(state_custom_dot_graph,'Duplicate CUSTOM_GRAPH definition: ',Nr,GraphFunction)
179 ; assertz(custom_graph(Nr,GraphAttrs))
180 ).
181
182 % process a single nodes:Nodes field and assert custom_nodes facts
183 process_nodes_field(DefaultAttrs,Span,field(NodeField,Nodes)) :-
184 is_nodes_field(NodeField,Nr),
185 assert_custom_nodes2(Nodes,DefaultAttrs,Span,Nr).
186
187 assert_custom_nodes2(Nodes,DefaultAttrs,Span,_Nr) :- Nodes = rec(_),
188 extract_record_fields(Nodes,_,DotAttributes,OtherFields),!,
189 % we have a nested record with default Attributes for the nodes
190 add_default_attrs(DefaultAttrs,DotAttributes,NewDefaultAttrs),
191 exclude(process_nodes_field(NewDefaultAttrs,Span),OtherFields,Infos1),
192 (Infos1 = [] -> true
193 ; add_warning(state_custom_dot_graph,'Unrecognized CUSTOM_GRAPH nodes fields: ',Infos1,Span)).
194 assert_custom_nodes2(Nodes,DefaultAttrs,_,Nr) :-
195 try_expand_custom_set_with_catch(Nodes, NodesRes,extract_dot_function),
196 assertz(custom_nodes('custom',Nr,DefaultAttrs,NodesRes)). %translate:print_bvalue(NodesRes),nl
197
198 is_nodes_field(nodes,0).
199 is_nodes_field(nodes0,0).
200 is_nodes_field(nodes1,1).
201 is_nodes_field(nodes2,2).
202 is_nodes_field(nodes3,3).
203 is_nodes_field(nodes4,4).
204 is_nodes_field(nodes5,5).
205 is_nodes_field(nodes6,6).
206 is_nodes_field(nodes7,7).
207 is_nodes_field(nodes8,8).
208 is_nodes_field(nodes9,9).
209
210 % process a single edges:Nodes field and assert custom_edges facts
211 process_edges_field(DefaultAttrs,Span,field(EdgesField,Edges)) :-
212 is_edges_field(EdgesField,Nr),
213 assert_custom_edges2(Edges,DefaultAttrs,Span,Nr).
214
215 assert_custom_edges2(Edges,DefaultAttrs,Span,_Nr) :- Edges = rec(_),
216 extract_record_fields(Edges,_,DotAttributes,OtherFields),!,
217 % we have a nested record with default Attributes for the edges
218 add_default_attrs(DefaultAttrs,DotAttributes,NewDefaultAttrs),
219 exclude(process_edges_field(NewDefaultAttrs,Span),OtherFields,Infos1),
220 (Infos1 = [] -> true
221 ; add_warning(state_custom_dot_graph,'Unrecognized CUSTOM_GRAPH edges fields: ',Infos1,Span)).
222 assert_custom_edges2(Edges,DefaultAttrs,_,Nr) :-
223 try_expand_custom_set_with_catch(Edges, EdgesRes,extract_dot_function),
224 (select(label/Label,DefaultAttrs,DA) -> true
225 ; Label='edge', DA=DefaultAttrs),
226 assertz(custom_edges(Label,Nr,DA,EdgesRes)).
227
228
229 is_edges_field(edges,0).
230 is_edges_field(edges0,0).
231 is_edges_field(edges1,1).
232 is_edges_field(edges2,2).
233 is_edges_field(edges3,3).
234 is_edges_field(edges4,4).
235 is_edges_field(edges5,5).
236 is_edges_field(edges6,6).
237 is_edges_field(edges7,7).
238 is_edges_field(edges8,8).
239 is_edges_field(edges9,9).
240
241 :- dynamic custom_nodes/4, custom_edges/4, custom_graph/2.
242
243 % TODO: use dot_no_subgraph if no subgraph field used anywhere; allow setting style, color and other attributes
244 cg_subgraph_predicate(ID,Style,Color) :-
245 Style=rounded, Color=gray50,
246 findall(SubGraphID,
247 (custom_nodes(_CustomID,_Nr,DefaultAttrs,Nodes),nonvar(Nodes),
248 get_node_attributes(Nodes,DefaultAttrs,_,Attributes),
249 member(subgraph/SubGraphID,Attributes)),List),
250 sort(List,SList),
251 member(ID,SList).
252
253 :- public cg_node_predicate/3.
254 :- use_module(probsrc(tools),[string_escape/2]).
255 % Custom Graph node predicate for dot_graph_generator.pl
256 cg_node_predicate(NodeID,SubGraph,Attributes) :-
257 ? custom_nodes(CustomID,_Nr,DefaultAttrs,Nodes),
258 debug_format(19,'Processing CUSTOM_GRAPH_NODES ~w~n',[CustomID]),
259 (var(Nodes) -> add_error(cg_node_predicate,'Variable custom_nodes: ',Nodes),fail ; true),
260 ? get_node_attributes(Nodes,DefaultAttrs,NodeVal,Attributes0),
261 %tools:print_message(node(NodeVal,ColVal,Color,NodeID)),
262 (select(subgraph/Sub,Attributes0,Attributes) -> SubGraph=Sub
263 ; SubGraph=none, Attributes=Attributes0),
264 gen_id(NodeVal,NodeID). %tools:print_message(nodeid(NodeID)).
265
266 get_node_attributes(CustomNodes,DefaultAttrs,NodeVal,[label/NodeDesc|Attrs]) :-
267 %(member(style/DefStyle,DefaultAttrs) -> true ; DefStyle=filled), % to do: extract multiple styles
268 %(member(shape/DefShape,DefaultAttrs) -> true ; DefShape=box),
269 ? member(Node,CustomNodes),
270 deconstruct_node(Node,DefaultAttrs,NodeVal,Attrs,Label),
271 (Label\='$default_no_label' -> NodeDesc=Label
272 ; translate_value_and_escape(NodeVal,NodeDesc) -> true
273 ; NodeDesc = '???').
274
275
276 deconstruct_node(((NodeVal,string(Shape)),ColVal),DefaultAttrs,ResNodeVal,Attrs,'$default_no_label') :-
277 valid_dot_shape(Shape),
278 !, % we have a triple (Node,"box","colour") = ((Node,"box"),"colour")
279 ResNodeVal=NodeVal,
280 translate_bvalue_to_colour(ColVal,ResColVal),
281 add_default_attrs(DefaultAttrs,[color/ResColVal,shape/Shape],Attrs).
282 deconstruct_node((NodeVal,string(ColVal)),DefaultAttrs,ResNodeVal,Attrs,'$default_no_label') :-
283 valid_rgb_color(ColVal),
284 !, % we have a pair (Node,"colour")
285 ResNodeVal=NodeVal,
286 add_default_attrs(DefaultAttrs,[color/ColVal],Attrs).
287 deconstruct_node((NodeVal,string(Shape)),DefaultAttrs,ResNodeVal, Attrs,'$default_no_label') :-
288 valid_dot_shape(Shape),
289 !, % we have a pair (Node,"shape")
290 ResNodeVal=NodeVal,
291 add_default_attrs(DefaultAttrs,[shape/Shape],Attrs).
292 deconstruct_node(Record,DefaultAttrs,NodeVal,
293 Attrs,Label) :-
294 % New record style: this should probably be the default now
295 extract_record_fields(Record,AllFields,DotAttributes,RemainingVals),
296 DotAttributes = [_|_], % at least one field recognised
297 ( RemainingVals = [field(_,NodeVal)] -> true
298 ; member(field(value,NodeVal),RemainingVals) -> true
299 ? ; member(id/_,DotAttributes),
300 ? member(field(id,NodeVal),AllFields) -> true % like in VisB / SVG; note is also a valid dot_attribute_field
301 ; member(label/_,DotAttributes)
302 -> member(field(label,NodeVal),AllFields), % get original value before translation to string
303 % but using label as node value may not be ideal for linking edges, better use separate value/id field
304 (RemainingVals = [] -> true
305 ; add_warning(state_custom_dot_graph,'Node has unrecognised fields:',RemainingVals,Record))
306 ; RemainingVals \= [] -> add_warning(state_custom_dot_graph,'Node has no label or value field:',Record,Record),
307 NodeVal = rec(RemainingVals)
308 ),
309 !,
310 % add default values if not specified:
311 ? ( select(label/LB,DotAttributes,Attrs0) -> Label=LB
312 ; select(description/LB,DotAttributes,Attrs0) -> Label=LB
313 ; Label = '$default_no_label', Attrs0=DotAttributes),
314 add_default_attrs(DefaultAttrs,Attrs0,Attrs).
315 deconstruct_node(NodeVal,DefaultAttrs,NodeVal,Attrs,'$default_no_label') :-
316 (DefaultAttrs=[]
317 -> format('CUSTOM_GRAPH_NODES value not recognised:~w~nUse rec(label:L,shape:"rect",...)~n',[NodeVal])
318 ; true % user has provided attributes in outer rec(...) construct
319 ),
320 add_default_attrs(DefaultAttrs,[],Attrs). % will remove none attributes
321 % shapes: triangle,ellipse,box,diamond,hexagon,octagon,house,invtriangle,invhouse,invtrapez,doubleoctagon,egg,parallelogram,pentagon,trapezium...
322
323 add_default_attrs([],Attrs,Attrs).
324 add_default_attrs([Attr/Val|T],Attrs,ResAttrs) :-
325 ? (member(Attr/_,Attrs) -> add_default_attrs(T,Attrs,ResAttrs)
326 ; Val=none, \+ none_valid(Attr) -> add_default_attrs(T,Attrs,ResAttrs) % Should we completely remove this line?
327 ; ResAttrs = [Attr/Val|RT],
328 add_default_attrs(T,Attrs,RT)).
329
330 % none is valid for arrowhead, arrowtail, ... and is different from default:
331 none_valid(arrowhead).
332 none_valid(arrowtail).
333
334 :- dynamic custom_node_id/2, nodectr/1.
335 nodectr(0).
336
337 get_ctr(Res) :- retract(nodectr(C)),!, C1 is C+1, assertz(nodectr(C1)), Res=C.
338 get_ctr(0) :- assertz(nodectr(1)).
339
340 % generate or lookup ID for node
341 gen_id(NodeVal,ID) :-
342 ? (custom_node_id(NodeVal,ID) -> true
343 ; NodeVal = int(IID)
344 -> assert(custom_node_id(NodeVal,IID)), % store for looking up
345 (nodectr(X),X =< IID -> N1 is IID+1, retract(nodectr(_)),assert(nodectr(N1)) ; true),
346 ID=IID % allow user to specify id's explicitly via id attribute
347 ; get_ctr(C),
348 assertz(custom_node_id(NodeVal,C)),ID=C).
349
350 % TODO: hash NodeVal to improve performance for large graphs
351
352 % lookup ID and generate message if it does not exist
353 lookup_id(NodeVal,Kind,ID) :-
354 ? (custom_node_id(NodeVal,ID)
355 -> true
356 ; get_as_string(NodeVal,VS),
357 format(user_error,'The ~w node does not exist in CUSTOM_GRAPH_NODES: ~w~n',[Kind,VS]),
358 %format('Internal value: ~w~n',[NodeVal]), portray_nodes,
359 string_escape(VS,VSC),
360 assertz(custom_node_id(NodeVal,VSC)),
361 ID=VSC
362 ).
363
364 :- public portray_nodes/0.
365 portray_nodes :- format(user_output,' ~w : ~w (~w)~n',['ID','Value','internal value']),
366 custom_node_id(NodeVal,ID),
367 translate_bvalue(NodeVal,NS),
368 format(user_output,' ~w : ~w (~w)~n',[ID,NS,NodeVal]),fail.
369 portray_nodes.
370
371 :- dynamic custom_trans_label/2, trans_ctr/1.
372 trans_ctr(1).
373 gen_trans_color(Label,Col,_,IsColor) :- custom_trans_label(Label,C),!,Col=C,IsColor=false.
374 gen_trans_color(_Label,Col,Infos,IsColor) :- member(color/C,Infos),!,Col=C,IsColor=false.
375 gen_trans_color(Label,Col,_,IsColor) :- try_translate_bvalue_to_colour(Label,C),!,Col=C,IsColor=true.
376 gen_trans_color(Label,Col,_,IsColor) :- retract(trans_ctr(Ctr)), C1 is Ctr+1, assertz(trans_ctr(C1)),
377 translate_bvalue_to_colour(int(Ctr),C),
378 assertz(custom_trans_label(Label,C)), Col=C,IsColor=false.
379
380 :- public cg_trans_predicate/3.
381 % Custom graph transition predicate for dot_graph_generator.pl
382 cg_trans_predicate(NodeID,SuccID,DotAttributes) :-
383 ? custom_edges(DefaultLabel,_,Infos,Edges),
384 (member(color/DefaultCol,Infos) -> true ; DefaultCol=blue),
385 (var(Edges) -> add_error(trans_predicate,'Variable custom_edges: ',Edges),fail ; true),
386 ? member(Edge,Edges),
387 cg_trans_aux(Edge,(DefaultLabel,DefaultCol),Infos,FromNode,ToNode,Attrs),
388 add_default_attrs(Infos,Attrs,DotAttributes),
389 lookup_id(FromNode,source,NodeID),
390 lookup_id(ToNode,target,SuccID).
391
392 cg_trans_aux(Pair,DefaultLabelCol,Infos, FromNode,ToNode,[label/Label, color/Colour]) :-
393 ? get_pair(Pair,From1,To2),!,
394 trans_pred_aux(From1,DefaultLabelCol,Infos,To2,FromNode,ToNode,Label,Colour).
395 cg_trans_aux(Record,(DefaultLabel,DefaultCol),_Infos, FromNode,ToNode,Attrs) :-
396 extract_record_fields(Record,_,DotAttrs,Vals),
397 get_from_to(Vals,FromNode,ToNode),
398 add_default_attrs([color/DefaultCol,label/DefaultLabel],DotAttrs,Attrs).
399
400 :- use_module(probsrc(specfile), [animation_minor_mode/1]).
401 :- use_module(probsrc(custom_explicit_sets),[singleton_set/2]).
402 get_pair((From,To),From,To).
403 get_pair(Set,From,To) :- % process optional values, e.g., in Alloy
404 singleton_set(Set,El), !, El = (From,To).
405 get_pair(avl_set(A),From,To) :- % process TLA+ tuples <<from,to>> translated to -> {(1,From),(2,To)}
406 animation_minor_mode(tla),
407 try_expand_custom_set_with_catch(avl_set(A), FunctionRes,get_pair),
408 FunctionRes = [(int(1),From),(int(2),To)].
409
410
411 get_from_to(Vals,FromNode,ToNode) :- % either two field from:Fromnode, to:ToNode
412 ? member(field(from,FromNode),Vals),!,
413 member(field(to,ToNode),Vals).
414 get_from_to(Vals,FromNode,ToNode) :- % or a single edge field which is a pair
415 member(field(edge,(FromNode,ToNode)),Vals),!.
416
417
418 % we have a transition where the colour is specified (e.g., CUSTOM_GRAPH_EDGES == {n1,col,n2 | ... }
419 % we assume trans_predicate has been called first
420 trans_pred_aux((From,To),(Label,_Col),_Infos,string(Colour),From,To,Label,Colour) :-
421 To \= string(_), % we are not in one of the cases below where To is a label
422 valid_rgb_color(Colour),!.
423 % stems from something like CUSTOM_GRAPH_EDGES1 == graph*{"red"};
424 trans_pred_aux(FromValue,_Defaults,Infos,To,From,To,ELabel,Color) :-
425 % format(user_output,'from: ~w~nto: ~w~n~n',[FromValue,To]),
426 % ((From,LabelCol) |-> To) case
427 get_trans_label_and_color(FromValue,Infos,From,Color,ELabel), % the From Value contains color and label
428 !.
429 trans_pred_aux(From,_Defaults,Infos,(LabelVal,ToVal),From,To,ELabel,Color) :-
430 % (From |-> (LabelCol,To)) case
431 get_trans_label_and_color((ToVal,LabelVal),Infos,To,Color,ELabel), % the To Value contains color and label
432 !.
433 trans_pred_aux(From,(Label,Col),_Infos,To,From,To,Label,Col).
434 % no label or color specified in transition pair
435
436
437 % try and decompose a from value, detecting color and label string ((From,"label"),"color")
438 get_trans_label_and_color((FromVal,LabelVal),Infos,From,Color,ELabel) :-
439 gen_trans_color(LabelVal,Color,Infos,IsColor),
440 (IsColor
441 -> get_trans_label(FromVal,From,ELabel)
442 ; translate_value_and_escape(LabelVal,ELabel),
443 From=FromVal
444 ).
445
446 get_trans_label((From,string(LabelVal)),From,ELabel) :- string_escape(LabelVal,ELabel).
447 get_trans_label(From,From,''). % or should we use DefaultLabel
448
449 translate_value_and_escape(string(S),ELabel) :- !, string_escape(S,ELabel).
450 translate_value_and_escape(LabelVal,ELabel) :-
451 translate:translate_bvalue(LabelVal,Label),string_escape(Label,ELabel).
452
453 :- use_module(probsrc(b_interpreter),[b_compute_explicit_epression_no_wf/6]).
454 :- use_module(probsrc(custom_explicit_sets),[try_expand_custom_set_with_catch/3]).
455 :- use_module(probsrc(bsyntaxtree),[get_texpr_info/2]).
456
457 % Kind = edges, nodes, graph
458 eval_definition_fun(AnimFunction, Nr, Kind, BState, SInfos, FunctionRes) :-
459 ? b_compute_explicit_epression_no_wf(AnimFunction,[],BState,FunctionResCl,'custom state graph',Nr),
460 %nl, print('FunctionResult'(FunctionResCl)),nl,
461 get_texpr_info(AnimFunction,Pos),
462 extract_dot_function(FunctionResCl, Kind, Infos, FunctionRes,Pos),
463 sort(Infos,SInfos).
464
465 extract_dot_function(Value,graph,Attributes,FunctionRes,Pos) :- !, % for CUSTOM_GRAPH
466 extract_dot_graph_function(Value,Attributes,OtherFields,Pos),
467 FunctionRes=rec(OtherFields). % list of fields
468 extract_dot_function((Label,Value),Kind,Info,FunctionRes,Pos) :- % treat e.g. == ("red","F",F)
469 extract_dot_info(Label,Info,Info2),!,
470 extract_dot_function(Value,Kind,Info2,FunctionRes,Pos).
471 extract_dot_function((Value,Label),Kind,Info,FunctionRes,Pos) :-
472 extract_dot_info(Label,Info,Info2),!,
473 extract_dot_function(Value,Kind,Info2,FunctionRes,Pos).
474 extract_dot_function([],Kind,_DefaultDotAttributes,_FunctionRes,Pos) :- !,
475 add_message(state_custom_graph,'CUSTOM_GRAPH definition is empty: ',Kind,Pos),
476 % can be intentional, e.g., if we have multiple ones and we comment some of them out
477 fail.
478 extract_dot_function(Record,Kind,DefaultDotAttributes,FunctionRes,Pos) :-
479 % treat e.g. CUSTOM_GRAPH_NODES == rec(color:"blue", shape:"rect", nodes:e);
480 % or CUSTOM_GRAPH_EDGES == rec(color:"red", style:"dotted", edges:e);
481 % or CUSTOM_GRAPH_NODES == rec(color:"blue", label:"root", shape:"")
482 extract_record_fields(Record,_,DotAttributes,Vals),
483 !,
484 ? ( select(field(ValAttr,Value),Vals,RestVals),
485 ? member(ValAttr,[value, Kind]) % there is a value, edge, nodes field
486 % this a record setting attributes for a set of nodes/edges
487 -> DefaultDotAttributes = DotAttributes,
488 try_expand_custom_set_with_catch(Value, FunctionRes,extract_dot_function),
489 (RestVals=[] -> true ; add_message(state_custom_dot_graph,'Unrecognised DOT attributes: ',RestVals,Pos))
490 ; member(label/_,DotAttributes) % in case we have a label this represents a single record
491 -> FunctionRes = [Record], DefaultDotAttributes=[]
492 ; add_message(state_custom_graph,'CUSTOM_GRAPH record not ok (use fields color,shape,style,description and either label, edges or nodes): ',Vals,Pos),
493 fail
494 ).
495 extract_dot_function(Value,_Kind,[],FunctionRes,_) :-
496 % we try to see if it is a set of nodes (ideally as records) or edges
497 try_expand_custom_set_with_catch(Value,FunctionRes,extract_dot_function),!.
498 extract_dot_function(Value,_Kind,_,_,Pos) :-
499 add_warning(state_custom_dot_graph,'Illegal CUSTOM_GRAPH value (use rec(label:L,shape:,...) record or set of records): ',Value,Pos),
500 fail.
501
502 % treat single CUSTOM_GRAPH record:
503 extract_dot_graph_function(Record,Attributes,OtherFields,_) :-
504 extract_record_fields(Record,_,Attributes,OtherFields),!.
505 extract_dot_graph_function(Value,_,_,Pos) :-
506 add_warning(state_custom_dot_graph,'Illegal CUSTOM_GRAPH value, use record',Value,Pos),
507 fail.
508
509 :- use_module(probsrc(translate), [translate_bvalue/2]).
510 % extract dot information from a B value, if it looks like a color, shape, style or label
511 extract_dot_info((A,B),I0,I2) :- !, extract_dot_info(A,I0,I1), extract_dot_info(B,I1,I2).
512 extract_dot_info(string(Str),[Type/Str|T],T) :-
513 (infer_string_type(Str,Type) -> true ; Type=label).
514 extract_dot_info(Value,[label/Str|T],T) :- simple_label_value(Value),
515 translate_bvalue(Value,Str).
516 simple_label_value(fd(_,_)).
517
518 ?infer_string_type(Str,color) :- valid_rgb_color(Str).
519 infer_string_type(Str,shape) :- valid_dot_shape(Str).
520 infer_string_type(Str,style) :- valid_dot_line_style(Str).
521 infer_string_type(Str,style) :- valid_dot_node_style(Str).
522
523 % get record fields from record or partial function STRING +-> STRING
524 % and select dot attributes
525
526 extract_record_fields(Record,Fields,DotAttributes,OtherFields) :-
527 flexible_get_record_fields(Record,Fields),
528 extract_info_from_fields(Fields,DotAttributes,OtherFields).
529
530 :- use_module(library(lists),[maplist/3]).
531 :- use_module(probsrc(custom_explicit_sets),[try_expand_custom_set_with_catch/3, is_set_value/2]).
532 % similar to get_VISB_record_fields
533 flexible_get_record_fields(rec(Fields),Res) :- !, Res=Fields.
534 flexible_get_record_fields(StringFunction,Fields) :-
535 is_set_value(StringFunction,flexible_get_record_fields),
536 try_expand_custom_set_with_catch(StringFunction,Expanded,get_visb_DEFINITION_svg_object),
537 % TODO: check we have no duplicates
538 maplist(convert_to_field,Expanded,Fields).
539 convert_to_field((string(FieldName),Value),field(FieldName,Value)).
540
541 extract_info_from_fields([],[],[]).
542 extract_info_from_fields([field(FName,FVAL)|TF],[Type/Str|TI],Val) :-
543 dot_attribute_field(FName,Type),!,
544 ( \+ checked_attribute(Type) -> get_as_string_for_attr(Type,FVAL,Str)
545 ? ; get_label_value(Type,FVAL,Str) -> true
546 ; add_message(state_custom_dot_graph,'Unexpected value for dot attribute: ',Type/FVAL),
547 get_as_string(FVAL,Str)
548 ),
549 extract_info_from_fields(TF,TI,Val).
550 extract_info_from_fields([field(FName,FVAL)|TF],[FName/EStr|TI],Val) :-
551 ? \+ definitely_not_dot_attribute(FName),
552 get_as_string(FVAL,Str),
553 !,
554 add_message(state_custom_dot_graph,'Assuming this is a dot attribute: ',FName/Str),
555 string_escape(Str,EStr),
556 extract_info_from_fields(TF,TI,Val).
557 extract_info_from_fields([F|TF],Info,[F|TVal]) :-
558 extract_info_from_fields(TF,Info,TVal).
559
560 get_label_value(label,Val,Str) :- !, get_as_string(Val,Str).
561 get_label_value(description,string(Str),Str).
562 ?get_label_value(Type,string(Str),Str) :- infer_string_type(Str,Type).
563 get_label_value(color,Val,Str) :- get_color(Val,Str).
564
565 get_color(string(Str),Val) :- !, Val=Str.
566 get_color(int(Nr),Val) :- !, Val=Nr. % numbers can be valid DOT colors when colorscheme provided
567 get_color(Val,Col) :-
568 try_translate_bvalue_to_colour(Val,Col). % from dot_graph_generator
569
570 checked_attribute(description).
571 checked_attribute(color).
572 checked_attribute(shape).
573 checked_attribute(style).
574
575 definitely_not_dot_attribute(edge).
576 definitely_not_dot_attribute(from).
577 definitely_not_dot_attribute(nodes).
578 definitely_not_dot_attribute(to).
579 definitely_not_dot_attribute(value).
580 definitely_not_dot_attribute(E) :- is_edges_field(E,_).
581 definitely_not_dot_attribute(N) :- is_nodes_field(N,_).
582
583 :- use_module(probsrc(kernel_strings),[to_b_string/2]).
584 get_as_string(BValue,Str) :- to_b_string(BValue,string(Str)).
585
586 % cf b_value_to_id_string in VisB; allow to use pairs to concatenate strings
587 get_as_id_string_or_number(int(I),Res) :- !, Res=I. % if we have an integer: use this as id of Dot node
588 get_as_id_string_or_number(BVal,Atom) :- get_as_id_string(BVal,Atom).
589
590 get_as_id_string(string(SValue),Res) :- !, Res=SValue.
591 get_as_id_string((A,B),Res) :- !,
592 get_as_id_string(A,VA), get_as_id_string(B,VB), atom_concat(VA,VB,Res).
593 % TODO: maybe convert sequence of values using conc
594 get_as_id_string(FValue,Res) :- get_as_string(FValue,Res).
595
596 get_as_string_for_attr(id,Val,Str) :- !, get_as_id_string_or_number(Val,Str). % like SVG ids in VisB
597 get_as_string_for_attr(_,Val,Str) :- !, get_as_string(Val,Str).
598
599 :- use_module(probsrc(tools_matching),[is_dot_attribute/1]).
600 dot_attribute_field(colour,color).
601 dot_attribute_field(fontcolour,fontcolor).
602 dot_attribute_field(description,description). % virtual attribute
603 dot_attribute_field(subgraph,subgraph). % virtual attribute
604 dot_attribute_field(stroke,style). % used in SVG
605 dot_attribute_field(Name,Name) :- is_dot_attribute(Name).
606
607