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