.
[tatoo.git] / src / run.ml
1 (***********************************************************************)
2 (*                                                                     *)
3 (*                               TAToo                                 *)
4 (*                                                                     *)
5 (*                     Kim Nguyen, LRI UMR8623                         *)
6 (*                   Université Paris-Sud & CNRS                       *)
7 (*                                                                     *)
8 (*  Copyright 2010-2013 Université Paris-Sud and Centre National de la *)
9 (*  Recherche Scientifique. All rights reserved.  This file is         *)
10 (*  distributed under the terms of the GNU Lesser General Public       *)
11 (*  License, with the special exception on linking described in file   *)
12 (*  ../LICENSE.                                                        *)
13 (*                                                                     *)
14 (***********************************************************************)
15
16 INCLUDE "utils.ml"
17 INCLUDE "debug.ml"
18
19 open Format
20 open Misc
21 open Bigarray
22
23 type stats = { mutable pass : int;
24                auto : Uid.t;
25                tree_size : int;
26                mutable fetch_trans_cache_access : int;
27                mutable fetch_trans_cache_hit : int;
28                mutable eval_trans_cache_access : int;
29                mutable eval_trans_cache_hit : int;
30                mutable nodes_per_run : int list;
31              }
32
33 module NodeSummary =
34 struct
35   (* Pack into an integer the result of the is_* and has_ predicates
36      for a given node *)
37   type t = int
38   let dummy = -1
39   (*
40     ...44443210
41     ...4444 -> kind
42     3 -> has_right
43     2 -> has_left
44     1 -> is_right
45     0 -> is_left
46   *)
47   let is_left (s : t) : bool =
48     s land 1 != 0
49
50   let is_right (s : t) : bool =
51     s land 0b10 != 0
52
53   let has_left (s : t) : bool =
54     s land 0b100 != 0
55
56   let has_right (s : t) : bool =
57     s land 0b1000 != 0
58
59   let kind (s : t) : Tree.NodeKind.t =
60     Obj.magic (s lsr 4)
61
62   let make is_left is_right has_left has_right kind =
63     (int_of_bool is_left) lor
64       ((int_of_bool is_right) lsl 1) lor
65       ((int_of_bool has_left) lsl 2) lor
66       ((int_of_bool has_right) lsl 3) lor
67       ((Obj.magic kind) lsl 4)
68 end
69
70 let dummy_set = StateSet.singleton State.dummy
71
72
73
74   IFDEF HTMLTRACE
75   THEN
76 type sat_array = StateSet.t array list
77   DEFINE IFHTML(a,b) = (a)
78   ELSE
79 type sat_array = StateSet.t array
80   DEFINE IFHTML(a,b) = (b)
81   END
82
83 let unsafe_get a i =
84   if i < 0 then StateSet.empty else
85     Array.unsafe_get (IFHTML(List.hd a, a)) i
86
87 let unsafe_set a i v old_v =
88   if v != old_v then
89     Array.unsafe_set (IFHTML(List.hd a, a)) i v
90
91 type 'a run = {
92   tree : 'a ;
93      (* The argument of the run *)
94   auto : Ata.t;
95      (* The automaton to be run *)
96   mutable sat: sat_array;
97      (* A mapping from node preorders to states satisfied at that node *)
98   mutable pass : int;
99      (* Number of run we have performed *)
100   mutable fetch_trans_cache : Ata.Formula.t Cache.N2.t;
101      (* A cache from states * label to list of transitions *)
102   mutable td_cache : StateSet.t Cache.N6.t;
103   mutable bu_cache : StateSet.t Cache.N6.t;
104      (* Two 6-way caches used during the top-down and bottom-up phase
105         label * self-set * fc-set * ns-set * parent-set * node-shape -> self-set
106      *)
107   node_summaries: (int, int16_unsigned_elt, c_layout) Array1.t;
108   stats : stats;
109 }
110
111 let dummy_form = Ata.Formula.stay State.dummy
112
113 let get_form run tag q =
114   let auto = run.auto in
115   let fetch_trans_cache = run.fetch_trans_cache in
116   let stats = run.stats in
117   let phi =
118     stats.fetch_trans_cache_access <- stats.fetch_trans_cache_access + 1;
119     Cache.N2.find fetch_trans_cache (tag.QName.id :> int) (q :> int)
120   in
121   if phi == dummy_form then
122     let phi = Ata.get_form auto tag q in
123     let () =
124       Cache.N2.add
125         fetch_trans_cache
126         (tag.QName.id :> int)
127         (q :> int) phi
128     in phi
129   else begin
130     stats.fetch_trans_cache_hit <- stats.fetch_trans_cache_hit + 1;
131     phi
132   end
133
134
135 let eval_form phi fcs nss ps ss summary =
136   let open Ata in
137   let rec loop phi =
138     begin match Formula.expr phi with
139     | Boolean.False -> false
140     | Boolean.True -> true
141     | Boolean.Atom (a, b) ->
142       begin
143         let open NodeSummary in
144         match a.Atom.node with
145         | Move (m, q) ->
146           b && StateSet.mem q (
147             match m with
148               `First_child -> fcs
149             | `Next_sibling -> nss
150             | `Parent | `Previous_sibling -> ps
151             | `Stay -> ss
152           )
153         | Is_first_child -> b == is_left summary
154         | Is_next_sibling -> b == is_right summary
155         | Is k -> b == (k == kind summary)
156         | Has_first_child -> b == has_left summary
157         | Has_next_sibling -> b == has_right summary
158       end
159     | Boolean.And(phi1, phi2) -> loop phi1 && loop phi2
160     | Boolean.Or (phi1, phi2) -> loop phi1 || loop phi2
161     end
162   in
163   loop phi
164
165
166 let eval_trans_aux run tag summary fcs nss ps sat todo  =
167   StateSet.fold (fun q (a_sat) ->
168     let phi =
169       get_form run tag q
170     in
171     if eval_form phi fcs nss ps a_sat summary then
172       StateSet.add q a_sat
173     else a_sat
174   ) todo sat
175
176
177 let rec eval_trans_fix run tag summary fcs nss ps sat todo  =
178   let new_sat =
179     eval_trans_aux run tag summary fcs nss ps sat todo
180   in
181   if new_sat == sat then sat else
182     eval_trans_fix run tag summary fcs nss ps new_sat todo
183
184
185 let eval_trans run trans_cache tag summary fcs nss ps ss todo =
186   let stats = run.stats in
187   let fcsid = (fcs.StateSet.id :> int) in
188   let nssid = (nss.StateSet.id :> int) in
189   let psid = (ps.StateSet.id :> int) in
190   let ssid = (ss.StateSet.id :> int) in
191   let tagid = (tag.QName.id :> int) in
192
193   let res = Cache.N6.find trans_cache tagid summary ssid fcsid nssid psid in
194   stats.eval_trans_cache_access <- 1 + stats.eval_trans_cache_access;
195   if res != dummy_set then begin
196     stats.eval_trans_cache_hit <- 1 + stats.eval_trans_cache_hit;
197     res
198   end else let new_sat =
199              eval_trans_fix run tag summary fcs nss ps ss todo
200            in
201            Cache.N6.add trans_cache tagid summary ssid fcsid nssid psid new_sat;
202            new_sat
203
204
205 module Make (T : Tree.S) (L : Node_list.S with type node = T.node) =
206 struct
207
208   let make auto tree =
209     let len = T.size tree in
210     let ba = Array1.create int16_unsigned c_layout len in
211     Array1.fill ba 0;
212     {
213       tree = tree;
214       auto = auto;
215       sat = (let a = Array.create len StateSet.empty in
216              IFHTML([a], a));
217       pass = 0;
218       fetch_trans_cache = Cache.N2.create dummy_form;
219       td_cache = Cache.N6.create dummy_set;
220       bu_cache = Cache.N6.create dummy_set;
221       node_summaries = ba;
222       stats = {
223           pass = 0;
224           auto = Ata.uid auto;
225         tree_size = len;
226         fetch_trans_cache_access = 0;
227         fetch_trans_cache_hit = 0;
228         eval_trans_cache_access = 0;
229         eval_trans_cache_hit = 0;
230         nodes_per_run = [];
231       }
232     }
233
234
235   let top_down run update_res =
236     let num_visited = ref 0 in
237     let i = run.pass in
238     let tree = run.tree in
239     let auto = run.auto in
240     let states_by_rank = Ata.get_states_by_rank auto in
241     let td_todo = states_by_rank.(i) in
242     let bu_todo =
243       if i == Array.length states_by_rank - 1 then StateSet.empty
244       else
245         states_by_rank.(i+1)
246     in
247     let td_only = bu_todo == StateSet.empty in
248     let root = T.root tree in
249     let last_run = i >= Array.length states_by_rank - 2 in
250     let rec loop_td_and_bu node parent parent_sat =
251       if node == T.nil then StateSet.empty
252       else begin
253         incr num_visited;
254         let tag = T.tag tree node in
255         let node_id = T.preorder tree node in
256         let fc = T.first_child tree node in
257         let ns = T.next_sibling tree node in
258          (* We enter the node from its parent *)
259         let summary =
260           let s = Array1.unsafe_get run.node_summaries node_id in
261           if  s != 0 then s else
262             let s =
263               if node == root then
264                 NodeSummary.make false false (fc != T.nil) (ns != T.nil) (T.kind tree node)
265               else
266                 let is_left = node == T.first_child tree parent in
267                 NodeSummary.make
268                   is_left
269                   (not is_left)
270                   (fc != T.nil) (* has_left *)
271                   (ns != T.nil) (* has_right *)
272                   (T.kind tree node) (* kind *)
273             in
274             run.node_summaries.{node_id} <- s; s
275         in
276         let status0 = unsafe_get run.sat node_id in
277         (* get the node_statuses for the first child, next sibling and parent *)
278         (* evaluate the transitions with all this statuses *)
279         let status1 =
280           eval_trans run
281             run.td_cache tag
282             summary
283             (unsafe_get run.sat (T.preorder tree fc))
284             (unsafe_get run.sat (T.preorder tree ns))
285             parent_sat
286             status0 td_todo
287         in
288           (* update the cache if the status of the node changed
289              unsafe_set run.sat node_id status1 status0;*)
290         if td_only then begin
291           unsafe_set run.sat node_id status1 status0; (* write the td_states *)
292           update_res false status1 node;
293           let _ = loop_td_and_bu fc node status1 in
294           loop_td_and_bu ns node status1 (* tail call *)
295         end else
296           let fcs1, nss1 =
297             if last_run then
298               let nss1 = loop_td_and_bu ns node status1 in
299               let fcs1 = loop_td_and_bu fc node status1 in
300               fcs1, nss1
301             else
302               let fcs1 = loop_td_and_bu fc node status1 in
303               let nss1 = loop_td_and_bu ns node status1 in
304               fcs1, nss1
305           in
306           let status2 =
307             eval_trans run run.bu_cache tag
308               summary fcs1
309               nss1
310               parent_sat
311               status1 bu_todo
312           in
313           unsafe_set run.sat node_id status2 status0;
314           if last_run && status2 != StateSet.empty then update_res true status2 node;
315           status2
316       end
317     in
318     let _ = loop_td_and_bu (T.root tree) T.nil dummy_set in
319     run.pass <- run.pass + 2;
320     run.stats.pass <- run.stats.pass + 1;
321     run.stats.nodes_per_run <- !num_visited :: run.stats.nodes_per_run
322
323
324
325   let mk_update_result auto =
326     let sel_states = Ata.get_selecting_states auto in
327     let res = L.create () in
328     (fun prepend sat node ->
329       if StateSet.intersect sel_states sat then begin
330         if prepend then L.push_front node res else
331           L.push_back node res
332       end),
333     (fun () -> res)
334
335
336   let mk_update_full_result auto =
337     let dummy = L.create () in
338     let res_mapper = Cache.N1.create dummy in
339     let () =
340       StateSet.iter
341         (fun q -> Cache.N1.add res_mapper (q :> int) (L.create()))
342         (Ata.get_selecting_states auto)
343     in
344     (fun prepend sat node ->
345       StateSet.iter
346         (fun q ->
347           let res = Cache.N1.find res_mapper (q :> int) in
348           if res != dummy then begin
349             if prepend then L.push_front node res
350             else L.push_back node res
351           end
352         ) sat),
353     (fun () ->
354       StateSet.fold_right
355         (fun q acc -> (q, Cache.N1.find res_mapper (q :> int))::acc)
356         (Ata.get_selecting_states auto) [])
357
358   let prepare_run run list =
359     let tree = run.tree in
360     let auto = run.auto in
361     let sat = IFHTML((List.hd run.sat), run.sat) in
362     let sat0 = Ata.get_starting_states auto in
363     L.iter (fun node ->
364       let node_id = T.preorder tree node in
365       sat.(node_id) <- sat0) list
366
367
368   let compute_run auto tree nodes update_res =
369     let run = make auto tree in
370     prepare_run run nodes;
371     let rank = Ata.get_max_rank auto in
372     while run.pass <= rank do
373       top_down run update_res;
374       IFHTML((run.sat <- (Array.copy (List.hd run.sat)) :: run.sat), ());
375       run.td_cache <- Cache.N6.create dummy_set;
376       run.bu_cache <- Cache.N6.create dummy_set;
377     done;
378     IFHTML((run.sat <- List.tl run.sat), ());
379     IFHTML(Html_trace.gen_trace auto run.sat (module T : Tree.S with type t = T.t) tree ,());
380     run
381
382
383   let last_stats = ref []
384
385   let full_eval auto tree nodes =
386     let update_full,get_full = mk_update_full_result auto in
387     let run = compute_run auto tree nodes update_full in
388     last_stats :=  run.stats :: !last_stats;
389     get_full ()
390
391   let eval auto tree nodes =
392     let update_res,get_res = mk_update_result auto in
393     let run = compute_run auto tree nodes update_res in
394     last_stats :=  run.stats :: !last_stats;
395     get_res ()
396
397   let stats () = match !last_stats with
398       _ :: _ as l -> List.iter (fun s -> s.nodes_per_run <- List.rev s.nodes_per_run) l; List.rev l
399     | [] -> failwith "Missing stats"
400
401 end