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