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