Don't needlessly run the last bottom-up phase, when the top-down is sufficient.
[tatoo.git] / src / run.ml
index 291faa4..5377690 100644 (file)
 INCLUDE "utils.ml"
 INCLUDE "debug.ml"
 
-open Format
-open Misc
-
-type stats = { run : int;
-               tree_size : int;
-               fetch_trans_cache_access : int;
-               fetch_trans_cache_hit : int;
-               eval_trans_cache_access : int;
-               eval_trans_cache_hit : int;
-             }
-
-let fetch_trans_cache_hit = ref 0
-let fetch_trans_cache_access = ref 0
-let eval_trans_cache_hit = ref 0
-let eval_trans_cache_access = ref 0
-let reset_stat_counters () =
-  fetch_trans_cache_hit := 0;
-  fetch_trans_cache_access := 0;
-  eval_trans_cache_hit := 0;
-  eval_trans_cache_access := 0
-
 
 module Make (T : Tree.S) =
- struct
-
-   module NodeSummary =
-   struct
-     (* Pack into an integer the result of the is_* and has_ predicates
-        for a given node *)
-     type t = int
-     let dummy = -1
-    (*
-      ...44443210
-      ...4444 -> kind
-      3 -> has_right
-      2 -> has_left
-      1 -> is_right
-      0 -> is_left
-    *)
-     let is_left (s : t) : bool =
-       s land 1 != 0
-
-     let is_right (s : t) : bool =
-       s land 0b10 != 0
-
-     let has_left (s : t) : bool =
-       s land 0b100 != 0
-
-     let has_right (s : t) : bool =
-       s land 0b1000 != 0
-
-     let kind (s : t) : Tree.NodeKind.t =
-       Obj.magic (s lsr 4)
-
-     let make is_left is_right has_left has_right kind =
-       (int_of_bool is_left) lor
-         ((int_of_bool is_right) lsl 1) lor
-         ((int_of_bool has_left) lsl 2) lor
-         ((int_of_bool has_right) lsl 3) lor
-         ((Obj.magic kind) lsl 4)
-   end
-
-   let dummy_set = StateSet.singleton State.dummy
-   open Bigarray
-
-IFDEF HTMLTRACE
-THEN
-   type sat_array = StateSet.t array list
-   DEFINE IFHTML(a,b) = (a)
-ELSE
-   type sat_array = StateSet.t array
-   DEFINE IFHTML(a,b) = (b)
-END
-   let unsafe_get a i =
-     if i < 0 then StateSet.empty else
-       Array.unsafe_get (IFHTML(List.hd a, a)) i
-   let unsafe_set a i v old_v =
-     if v != old_v then
-       Array.unsafe_set (IFHTML(List.hd a, a)) i v
-
-   type run = {
-     tree : T.t ;
-     (* The argument of the run *)
-     auto : Ata.t;
-     (* The automaton to be run *)
-     mutable sat: sat_array;
-     (* A mapping from node preorders to states satisfied at that node *)
-     mutable pass : int;
-     (* Number of run we have performed *)
-     mutable fetch_trans_cache : Ata.Formula.t Cache.N2.t;
-     (* A cache from states * label to list of transitions *)
-     mutable td_cache : StateSet.t Cache.N6.t;
-     mutable bu_cache : StateSet.t Cache.N6.t;
-     (* Two 6-way caches used during the top-down and bottom-up phase
-        label * self-set * fc-set * ns-set * parent-set * node-shape -> self-set
-     *)
-     node_summaries: (int, int16_unsigned_elt, c_layout) Array1.t;
-   }
-
-
-   let dummy_form = Ata.Formula.stay State.dummy
-
-   let make auto tree =
-     let len = T.size tree in
-     {
-       tree = tree;
-       auto = auto;
-       sat = (let a = Array.create len StateSet.empty in
-             IFHTML([a], a));
-       pass = 0;
-       fetch_trans_cache = Cache.N2.create dummy_form;
-       td_cache = Cache.N6.create dummy_set;
-       bu_cache = Cache.N6.create dummy_set;
-       node_summaries = let ba = Array1.create int16_unsigned c_layout len in
-                        Array1.fill ba 0; ba
-     }
-
-   let get_form fetch_trans_cache auto tag q =
-     let phi =
-       incr fetch_trans_cache_access;
-       Cache.N2.find fetch_trans_cache (tag.QName.id :> int) (q :> int)
-     in
-     if phi == dummy_form then
-       let phi = Ata.get_form auto tag q in
-       let () =
-         Cache.N2.add
-           fetch_trans_cache
-           (tag.QName.id :> int)
-           (q :> int) phi
-       in phi
-     else begin
-       incr fetch_trans_cache_hit;
-       phi
-     end
-
-
-   let eval_form phi fcs nss ps ss summary =
-     let open Ata in
-         let rec loop phi =
-           begin match Formula.expr phi with
-           | Boolean.False -> false
-           | Boolean.True -> true
-           | Boolean.Atom (a, b) ->
-               begin
-                 let open NodeSummary in
-                     match a.Atom.node with
-                     | Move (m, q) ->
-                       b && StateSet.mem q (
-                           match m with
-                             `First_child -> fcs
-                           | `Next_sibling -> nss
-                           | `Parent | `Previous_sibling ->  ps
-                           | `Stay ->  ss
-                       )
-                     | Is_first_child -> b == is_left summary
-                     | Is_next_sibling -> b == is_right summary
-                     | Is k -> b == (k == kind summary)
-                     | Has_first_child -> b == has_left summary
-                     | Has_next_sibling -> b == has_right summary
-               end
-           | Boolean.And(phi1, phi2) -> loop phi1 && loop phi2
-           | Boolean.Or (phi1, phi2) -> loop phi1 || loop phi2
-           end
-         in
-         loop phi
-
-
-   let eval_trans_aux auto fetch_trans_cache tag fcs nss ps sat todo summary =
-     StateSet.fold (fun q (a_sat) ->
-       let phi =
-         get_form fetch_trans_cache auto tag q
-       in
-       if eval_form phi fcs nss ps a_sat summary then
-         StateSet.add q a_sat
-       else a_sat
-     ) todo sat
-
-
-   let rec eval_trans_fix auto fetch_trans_cache tag fcs nss ps sat todo summary =
-     let new_sat =
-       eval_trans_aux auto fetch_trans_cache tag fcs nss ps sat todo summary
-     in
-     if new_sat == sat then sat else
-       eval_trans_fix auto fetch_trans_cache tag fcs nss ps new_sat todo summary
-
-
-   let eval_trans auto fetch_trans_cache eval_cache tag fcs nss ps ss todo summary =
-     let fcsid = (fcs.StateSet.id :> int) in
-     let nssid = (nss.StateSet.id :> int) in
-     let psid = (ps.StateSet.id :> int) in
-     let ssid = (ss.StateSet.id :> int) in
-     let tagid = (tag.QName.id :> int) in
-     let res = Cache.N6.find eval_cache tagid summary ssid fcsid nssid psid in
-     incr eval_trans_cache_access;
-     if res != dummy_set then begin incr eval_trans_cache_hit; res end
-     else let new_sat =
-            eval_trans_fix auto fetch_trans_cache tag fcs  nss ps ss todo summary
+struct
+
+  let int (x : bool) : int = Obj.magic x
+  let kint (x : Tree.NodeKind.t) : int = Obj.magic x
+  let summary tree node is_first is_next fc ns =
+    (int (ns != T.nil)) lor
+      ((int (fc != T.nil)) lsl 1) lor
+      ((int is_next) lsl 2) lor
+      ((int is_first) lsl 3) lor
+      ((kint (T.kind tree node)) lsl 4)
+
+  let has_next_sibling summary : bool = Obj.magic (summary land 1)
+  let has_first_child summary : bool = Obj.magic ((summary lsr 1) land 1)
+  let is_next_sibling summary : bool = Obj.magic ((summary lsr 2) land 1)
+  let is_first_child summary : bool = Obj.magic ((summary lsr 3) land 1)
+  let kind summary : Tree.NodeKind.t  = Obj.magic (summary lsr 4)
+
+  let dummy_set = StateSet.singleton State.dummy
+  let dummy_trans_list =
+    Ata.(TransList.cons
+      (Transition.make (State.dummy, QNameSet.empty, Formula.false_))
+      TransList.nil)
+
+  module Run =
+    struct
+      open Bigarray
+      type t = {
+        mutable pass : int;
+        auto : Ata.t;
+        trans_cache : Ata.TransList.t Cache.N2.t;
+        td_cache : StateSet.t Cache.N6.t;
+        bu_cache : StateSet.t Cache.N6.t;
+        mark_cache : (StateSet.t*StateSet.t*StateSet.t) Cache.N4.t;
+      }
+
+      let create a =
+        {
+          pass = 0;
+          auto = a;
+          trans_cache = Cache.N2.create dummy_trans_list;
+          td_cache = Cache.N6.create dummy_set;
+          bu_cache = Cache.N6.create dummy_set;
+          mark_cache = Cache.N4.create (dummy_set,dummy_set,dummy_set);
+        }
+    end
+
+
+  let eval_form phi node_summary f_set n_set p_set s_set =
+    let rec loop phi =
+      let open Boolean in
+      match Ata.Formula.expr phi with
+        False -> false
+      | True -> true
+      | Or (phi1, phi2) -> loop phi1 || loop phi2
+      | And (phi1, phi2) -> loop phi1 && loop phi2
+      | Atom (a, b) -> b == Ata.(
+        match Atom.node a with
+          Is_first_child -> is_first_child node_summary
+        | Is_next_sibling -> is_next_sibling node_summary
+        | Is k -> k == kind node_summary
+        | Has_first_child -> has_first_child node_summary
+        | Has_next_sibling -> has_next_sibling node_summary
+        | Move (m, q) ->
+          let set =
+            match m with
+              `First_child -> f_set
+            | `Next_sibling -> n_set
+            | `Parent
+            | `Previous_sibling -> p_set
+            | `Stay -> s_set
           in
-          Cache.N6.add eval_cache tagid summary ssid fcsid nssid psid new_sat;
-          new_sat
-
+          StateSet.mem q set
+      )
+    in
+    loop phi
 
 
-   let top_down run =
-    let i = run.pass in
-    let tree = run.tree in
-    let auto = run.auto in
-    let states_by_rank = Ata.get_states_by_rank auto in
-    let td_todo = states_by_rank.(i) in
-    let bu_todo = if i + 1 = Array.length states_by_rank then StateSet.empty
+  let eval_trans_aux trans_list node_summary f_set n_set p_set s_set =
+    let open Ata in
+    TransList.fold (fun trs acc ->
+      let q, _ , phi = Transition.node trs in
+      if eval_form phi node_summary f_set n_set p_set s_set then
+        StateSet.add q acc
       else
-        states_by_rank.(i+1)
+        acc) trans_list s_set
+
+  let eval_trans trans_list node_summary f_set n_set p_set s_set =
+    let rec loop old_s =
+
+      let new_s =
+        eval_trans_aux trans_list node_summary f_set n_set p_set old_s
+      in
+      if new_s == old_s then old_s else loop new_s
     in
-    let rec loop_td_and_bu node parent parent_sat =
-      if node == T.nil
-      then StateSet.empty
-      else begin
-        let node_id = T.preorder tree node in
-        let fc = T.first_child tree node in
-        let ns = T.next_sibling tree node in
+    loop s_set
+
+  let get_trans run tag set =
+    let i = (tag.QName.id :> int) in
+    let j = (set.StateSet.id :> int) in
+    let res = Cache.N2.find run.Run.trans_cache i j in
+    if res == dummy_trans_list then begin
+      let res = Ata.get_trans run.Run.auto tag set in
+      Cache.N2.add run.Run.trans_cache i j res;
+      res
+    end
+    else
+      res
+
+  let eval_trans run cache set tag node_summary f_set n_set p_set s_set =
+    let i = node_summary in
+    let j = (tag.QName.id :> int) in
+    let k = (f_set.StateSet.id :> int) in
+    let l = (n_set.StateSet.id :> int) in
+    let m = (p_set.StateSet.id :> int) in
+    let n = (s_set.StateSet.id :> int) in
+    let res = Cache.N6.find cache i j k l m n in
+    if res == dummy_set then begin
+      let trans_list = get_trans run tag set in
+      let res = eval_trans trans_list node_summary f_set n_set p_set s_set in
+      Cache.N6.add cache i j k l m n res;
+      res
+    end
+    else res
+
+  let auto_run run tree prev_nodes td_states bu_states exit_states _i =
+    let exit_id = (exit_states.StateSet.id :> int) in
+    let empty_sets = StateSet.(empty,empty,empty) in
+
+    let mark_node front res node set f_set n_set =
+      let i = (set.StateSet.id :> int) in
+      let j = (f_set.StateSet.id :> int) in
+      let k = (n_set.StateSet.id :> int) in
+      let (mstates, _, _) as block =
+        Cache.N4.find run.Run.mark_cache exit_id i j k
+      in
+
+      let mstates, ll, rr =
+        if mstates == dummy_set then begin
+        let r1 = StateSet.inter set exit_states in
+        let r2 = StateSet.inter f_set exit_states in
+        let r3 = StateSet.inter n_set exit_states in
+        let r = r1,r2,r3 in
+        Cache.N4.add run.Run.mark_cache exit_id i j k r;
+        r
+        end
+        else block
+      in
+      if mstates != StateSet.empty then
+        let block = mstates, ll, rr, node in
+        if front then Sequence.push_front block res
+        else Sequence.push_back block res
+    in
+    let rec loop res node is_first is_next parent_set =
+      if node == T.nil then StateSet.empty else begin
+        let set,lset,rset =
+        if Sequence.is_empty prev_nodes then
+          empty_sets
+        else
+          let set,lset,rset, node' = Sequence.peek prev_nodes in
+          if node == node' then begin
+            ignore (Sequence.pop prev_nodes);
+            set,lset,rset
+          end
+          else
+            empty_sets
+        in
         let tag = T.tag tree node in
-        (* We enter the node from its parent *)
-        let summary =
-          let s = Array1.unsafe_get run.node_summaries node_id in
-          if  s != 0 then s else
-            let s =
-              NodeSummary.make
-                (node == T.first_child tree parent) (*is_left *)
-                (node == T.next_sibling tree parent)(*is_right *)
-                (fc != T.nil) (* has_left *)
-                (ns != T.nil) (* has_right *)
-                (T.kind tree node) (* kind *)
-            in
-            run.node_summaries.{node_id} <- s; s
+        let first_child = T.first_child tree node in
+        let next_sibling = T.next_sibling tree node in
+        let node_summary =
+          summary tree node is_first is_next first_child next_sibling
         in
-        let status0 = unsafe_get run.sat node_id in
-        (* get the node_statuses for the first child, next sibling and parent *)
-        let fcs = unsafe_get run.sat (T.preorder tree fc) in
-        let nss = unsafe_get run.sat (T.preorder tree ns) in
-        (* evaluate the transitions with all this statuses *)
         let status1 =
-          eval_trans auto run.fetch_trans_cache run.td_cache tag fcs nss
-            parent_sat
-            status0 td_todo summary
+          eval_trans run run.Run.td_cache td_states tag node_summary lset rset parent_set set
         in
-        (* update the cache if the status of the node changed
-        unsafe_set run.sat node_id status1 status0;*)
-        let fcs1 = loop_td_and_bu fc node status1 in
-        if bu_todo == StateSet.empty then begin
-          unsafe_set run.sat node_id status1 status0; (* write the td_states *)
-          loop_td_and_bu ns node status1 (* tail call *)
-        end else
-          let nss1 = loop_td_and_bu ns node status1 in
+        let fcs = loop res first_child true false status1 in
+        let rres = Sequence.create () in
+        let nss = loop rres next_sibling false true status1 in
+        if bu_states == StateSet.empty then (* tail call *) begin
+          mark_node true res node status1 fcs StateSet.empty;
+          Sequence.append res rres;
+          status1
+        end else begin
+
           let status2 =
-            eval_trans auto run.fetch_trans_cache run.bu_cache tag fcs1 nss1
-              parent_sat
-              status1 bu_todo summary
+            eval_trans run run.Run.bu_cache bu_states tag node_summary fcs nss parent_set status1
           in
-          unsafe_set run.sat node_id status2 status0;
+          if status2 != StateSet.empty then
+            mark_node true res node status2 fcs nss;
+          Sequence.append res rres;
           status2
+        end;
       end
     in
-    let _ = loop_td_and_bu (T.root tree) T.nil StateSet.empty in
-    run.pass <- run.pass + 2
-
-
-  let get_results run =
-    let cache = IFHTML((List.hd run.sat), run.sat) in
-    let auto = run.auto in
-    let tree = run.tree in
-    let sel_states = Ata.get_selecting_states auto in
-    let rec loop node acc =
-      if node == T.nil then acc
-      else
-        let acc0 = loop (T.next_sibling tree node) acc in
-        let acc1 = loop (T.first_child tree node) acc0 in
-
-        if StateSet.intersect
-          cache.(T.preorder tree node)(* NodeStatus.node.sat *)
-          sel_states then node::acc1
-        else acc1
-    in
-    loop (T.root tree) []
-
-
-  let get_full_results run =
-    let cache = IFHTML((List.hd run.sat), run.sat) in
-    let auto = run.auto in
-    let tree = run.tree in
-    let res_mapper = Hashtbl.create MED_H_SIZE in
-    let () =
-      StateSet.iter
-        (fun q -> Hashtbl.add res_mapper q [])
-        (Ata.get_selecting_states auto)
-    in
-    let dummy = [ T.nil ] in
-    let res_mapper = Cache.N1.create dummy in
-    let () =
-      StateSet.iter
-        (fun q -> Cache.N1.add res_mapper (q :> int) [])
-        (Ata.get_selecting_states auto)
-    in
-    let rec loop node =
-      if node != T.nil then
-        let () = loop (T.next_sibling tree node) in
-        let () = loop (T.first_child tree node) in
-        StateSet.iter
-          (fun q ->
-            let res = Cache.N1.find res_mapper (q :> int) in
-            if res != dummy then
-              Cache.N1.add res_mapper (q :> int) (node::res)
-          )
-          cache.(T.preorder tree node)(* NodeStatus.node.sat *)
-    in
-    loop (T.root tree);
-    (StateSet.fold_right
-       (fun q acc -> (q, Cache.N1.find res_mapper (q :> int))::acc)
-       (Ata.get_selecting_states auto) [])
-
-
-  let prepare_run run list =
-    let tree = run.tree in
-    let auto = run.auto in
-    let sat = IFHTML((List.hd run.sat), run.sat) in
-    let sat0 = Ata.get_starting_states auto in
-    List.iter (fun node ->
-      let node_id = T.preorder tree node in
-      sat.(node_id) <- sat0) list
-
-  let tree_size = ref 0
-  let pass = ref 0
-  let compute_run auto tree nodes =
-    pass := 0;
-    tree_size := T.size tree;
-    let run = make auto tree in
-    prepare_run run nodes;
-    let rank = Ata.get_max_rank auto in
-    while run.pass <= rank do
-      top_down run;
-      IFHTML((run.sat <- (Array.copy (List.hd run.sat)) :: run.sat), ());
-      run.td_cache <- Cache.N6.create dummy_set;
-      run.bu_cache <- Cache.N6.create dummy_set;
+    let res = Sequence.create () in
+    ignore (loop res (T.root tree) false false StateSet.empty);
+    res
+
+
+
+  let prepare_run auto l =
+    let res = Sequence.create () in
+    let start = Ata.get_starting_states auto in
+    Sequence.iter (fun n -> Sequence.push_back (start, StateSet.empty, StateSet.empty, n) res) l;
+    res
+
+let time f arg msg =
+  let t1 = Unix.gettimeofday () in
+  let r = f arg in
+  let t2 = Unix.gettimeofday () in
+  let time = (t2 -. t1) *. 1000. in
+  Logger.msg `STATS "%s: %fms" msg time;
+  r
+
+
+  let main_eval auto tree nodes =
+    let s_nodes = prepare_run auto nodes in
+    let ranked_states = Ata.get_states_by_rank auto in
+    let acc = ref s_nodes in
+    let max_rank = Ata.get_max_rank auto in
+    let run = Run.create auto in
+    for i = 0 to max_rank do
+      let open Ata in
+      let { td; bu; exit } = ranked_states.(i) in
+      run.Run.pass <- i;
+      acc := auto_run run tree !acc td bu exit i;
     done;
-    pass := Ata.get_max_rank auto + 1;
-    IFHTML(Html.gen_trace auto run.sat (module T : Tree.S with type t = T.t) tree ,());
-    run
+    !acc
 
-  let full_eval auto tree nodes =
-    let r = compute_run auto tree nodes in
-    get_full_results r
 
   let eval auto tree nodes =
-    let r = compute_run auto tree nodes in
-    get_results r
+    let res = main_eval auto tree nodes in
+    let r = Sequence.create () in
+    Sequence.iter (fun (_,_,_, n) -> Sequence.push_back n r) res;
+    r
+
 
-  let stats () = {
-    tree_size = !tree_size;
-    run = !pass;
-    fetch_trans_cache_access = !fetch_trans_cache_access;
-    fetch_trans_cache_hit = !fetch_trans_cache_hit;
-    eval_trans_cache_access = !eval_trans_cache_access;
-    eval_trans_cache_hit = !eval_trans_cache_hit;
-  }
+  let full_eval auto tree nodes =
+    let res = main_eval auto tree nodes in
+    let dummy = Sequence.create () in
+    let cache = Cache.N1.create dummy in
+    Sequence.iter (fun (set, _, _, n) ->
+      StateSet.iter (fun q ->
+        let qres = Cache.N1.find cache q in
+        let qres =
+          if qres == dummy then begin
+            let s = Sequence.create () in
+            Cache.N1.add cache q s;
+            s
+          end
+          else qres
+        in
+        Sequence.push_back n qres) set )
+      res;
+    let l = StateSet.fold (fun q acc ->
+      let res = Cache.N1.find cache q in
+      (q, res) :: acc) (Ata.get_selecting_states auto) []
+    in
+    List.rev l
 
 end