f9222f1bff3a3267afb60e9cb3d7f7ea2907ef60
[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
120    let dummy_form = Ata.Formula.stay State.dummy
121
122    let get_form fetch_trans_cache auto tag q =
123      let phi =
124        incr fetch_trans_cache_access;
125        Cache.N2.find fetch_trans_cache (tag.QName.id :> int) (q :> int)
126      in
127      if phi == dummy_form then
128        let phi = Ata.get_form auto tag q in
129        let () =
130          Cache.N2.add
131            fetch_trans_cache
132            (tag.QName.id :> int)
133            (q :> int) phi
134        in phi
135      else begin
136        incr fetch_trans_cache_hit;
137        phi
138      end
139
140
141    let eval_form phi fcs nss ps ss summary =
142      let open Ata in
143          let rec loop phi =
144            begin match Formula.expr phi with
145            | Boolean.False -> false
146            | Boolean.True -> true
147            | Boolean.Atom (a, b) ->
148                begin
149                  let open NodeSummary in
150                      match a.Atom.node with
151                      | Move (m, q) ->
152                        b && StateSet.mem q (
153                            match m with
154                              `First_child -> fcs
155                            | `Next_sibling -> nss
156                            | `Parent | `Previous_sibling ->  ps
157                            | `Stay ->  ss
158                        )
159                      | Is_first_child -> b == is_left summary
160                      | Is_next_sibling -> b == is_right summary
161                      | Is k -> b == (k == kind summary)
162                      | Has_first_child -> b == has_left summary
163                      | Has_next_sibling -> b == has_right summary
164                end
165            | Boolean.And(phi1, phi2) -> loop phi1 && loop phi2
166            | Boolean.Or (phi1, phi2) -> loop phi1 || loop phi2
167            end
168          in
169          loop phi
170
171
172    let eval_trans_aux auto trans_cache tag summary fcs nss ps sat todo  =
173      StateSet.fold (fun q (a_sat) ->
174        let phi =
175          get_form trans_cache auto tag q
176        in
177        if eval_form phi fcs nss ps a_sat summary then
178          StateSet.add q a_sat
179        else a_sat
180      ) todo sat
181
182
183    let rec eval_trans_fix auto trans_cache tag summary fcs nss ps sat todo  =
184      let new_sat =
185        eval_trans_aux auto trans_cache tag summary fcs nss ps sat todo
186      in
187      if new_sat == sat then sat else
188        eval_trans_fix auto trans_cache tag summary fcs nss ps new_sat todo
189
190
191    let eval_trans auto fetch_trans_cache eval_cache tag summary fcs nss ps ss todo =
192      let fcsid = (fcs.StateSet.id :> int) in
193      let nssid = (nss.StateSet.id :> int) in
194      let psid = (ps.StateSet.id :> int) in
195      let ssid = (ss.StateSet.id :> int) in
196      let tagid = (tag.QName.id :> int) in
197      let res = Cache.N6.find eval_cache tagid summary ssid fcsid nssid psid in
198      incr eval_trans_cache_access;
199      if res != dummy_set then begin incr eval_trans_cache_hit; res end
200      else let new_sat =
201             eval_trans_fix auto fetch_trans_cache tag summary fcs nss ps ss todo
202           in
203           Cache.N6.add eval_cache tagid summary ssid fcsid nssid psid new_sat;
204           new_sat
205
206
207 module Make (T : Tree.S) (L : Node_list.S with type node = T.node) =
208  struct
209
210    let make auto tree =
211      let len = T.size tree in
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 = let ba = Array1.create int16_unsigned c_layout len in
222                         Array1.fill ba 0; ba
223      }
224
225
226    let top_down run update_res =
227     let i = run.pass in
228     let tree = run.tree in
229     let auto = run.auto in
230     let states_by_rank = Ata.get_states_by_rank auto in
231     let td_todo = states_by_rank.(i) in
232     let bu_todo =
233       if i == Array.length states_by_rank - 1 then StateSet.empty
234       else
235         states_by_rank.(i+1)
236     in
237     let last_run = i >= Array.length states_by_rank - 2 in
238     let rec loop_td_and_bu node parent parent_sat =
239       if node == T.nil then StateSet.empty
240       else begin
241         let node_id = T.preorder tree node in
242         let fc = T.first_child tree node in
243         let ns = T.next_sibling tree node in
244         (* We enter the node from its parent *)
245         let summary =
246           let s = Array1.unsafe_get run.node_summaries node_id in
247           if  s != 0 then s else
248             let s =
249               NodeSummary.make
250                 (node_id == T.preorder tree (T.first_child tree parent)) (*is_left *)
251                 (node_id ==  T.preorder tree (T.next_sibling tree parent))(*is_right *)
252                 (fc != T.nil) (* has_left *)
253                 (ns != T.nil) (* has_right *)
254                 (T.kind tree node) (* kind *)
255             in
256             run.node_summaries.{node_id} <- s; s
257         in
258         let status0 = unsafe_get run.sat node_id in
259         (* get the node_statuses for the first child, next sibling and parent *)
260         (* evaluate the transitions with all this statuses *)
261         let tag = T.tag tree node in
262         let status1 =
263           eval_trans
264             auto run.fetch_trans_cache run.td_cache tag
265             summary
266             (unsafe_get run.sat (T.preorder tree fc))
267             (unsafe_get run.sat (T.preorder tree ns))
268             parent_sat
269             status0 td_todo
270         in
271
272         (* update the cache if the status of the node changed
273            unsafe_set run.sat node_id status1 status0;*)
274           if bu_todo == StateSet.empty then begin
275             unsafe_set run.sat node_id status1 status0; (* write the td_states *)
276             update_res false status1 node;
277             let _ = loop_td_and_bu fc node status1 in
278             loop_td_and_bu ns node status1 (* tail call *)
279           end else
280             let fcs1, nss1 =
281               if last_run then
282                 let nss1 = loop_td_and_bu ns node status1 in
283                 let fcs1 = loop_td_and_bu fc node status1 in
284                 fcs1, nss1
285               else
286                 let fcs1 = loop_td_and_bu fc node status1 in
287                 let nss1 = loop_td_and_bu ns node status1 in
288                 fcs1, nss1
289             in
290             let status2 =
291               eval_trans auto run.fetch_trans_cache run.bu_cache tag
292                 summary fcs1
293                 nss1
294                 parent_sat
295                 status1 bu_todo
296             in
297             unsafe_set run.sat node_id status2 status0;
298             if last_run then update_res true status2 node;
299             status2
300         end
301     in
302     let _ = loop_td_and_bu (T.root tree) T.nil dummy_set in
303     run.pass <- run.pass + 2
304
305
306    let mk_update_result auto =
307      let sel_states = Ata.get_selecting_states auto in
308      let res = L.create () in
309      (fun prepend sat node ->
310        if StateSet.intersect sel_states sat then begin
311          if prepend then L.push_front node res else
312            L.push_back node res
313        end),
314      (fun () -> res)
315
316
317    let mk_update_full_result auto =
318      let dummy = L.create () in
319      let res_mapper = Cache.N1.create dummy in
320      let () =
321        StateSet.iter
322          (fun q -> Cache.N1.add res_mapper (q :> int) (L.create()))
323          (Ata.get_selecting_states auto)
324      in
325      (fun prepend sat node ->
326        StateSet.iter
327          (fun q ->
328            let res = Cache.N1.find res_mapper (q :> int) in
329            if res != dummy then begin
330              if prepend then L.push_front node res
331              else L.push_back node res
332            end
333          ) sat),
334      (fun () ->
335        StateSet.fold_right
336          (fun q acc -> (q, Cache.N1.find res_mapper (q :> int))::acc)
337          (Ata.get_selecting_states auto) [])
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     L.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
351   let compute_run auto tree nodes update_res =
352     pass := 0;
353     tree_size := T.size tree;
354     let run = make auto tree in
355     prepare_run run nodes;
356     let rank = Ata.get_max_rank auto in
357     while run.pass <= rank do
358       top_down run update_res;
359       IFHTML((run.sat <- (Array.copy (List.hd run.sat)) :: run.sat), ());
360       run.td_cache <- Cache.N6.create dummy_set;
361       run.bu_cache <- Cache.N6.create dummy_set;
362     done;
363     IFHTML((run.sat <- List.tl run.sat), ());
364     pass := Ata.get_max_rank auto + 1;
365     IFHTML(Html_trace.gen_trace auto run.sat (module T : Tree.S with type t = T.t) tree ,());
366     run
367
368
369
370   let full_eval auto tree nodes =
371     let update_full,get_full = mk_update_full_result auto in
372     let _ = compute_run auto tree nodes update_full in
373     get_full ()
374
375   let eval auto tree nodes =
376     let update_res,get_res = mk_update_result auto in
377     let _ = compute_run auto tree nodes update_res in
378     get_res ()
379
380   let stats () = {
381     tree_size = !tree_size;
382     run = !pass;
383     fetch_trans_cache_access = !fetch_trans_cache_access;
384     fetch_trans_cache_hit = !fetch_trans_cache_hit;
385     eval_trans_cache_access = !eval_trans_cache_access;
386     eval_trans_cache_hit = !eval_trans_cache_hit;
387   }
388
389 end