Tentative optimization
[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 open Format
18 open Misc
19
20 module Make (T : Tree.S) =
21  struct
22
23    module NodeSummary =
24    struct
25      (* Pack into an integer the result of the is_* and has_ predicates
26         for a given node *)
27      type t = int
28      let dummy = -1
29     (*
30       4444444444443210
31       4 -> kind
32       3 -> is_left
33       2 -> is_right
34       1 -> has_left
35       0 -> has_right
36     *)
37
38      let has_right (s : t) : bool =
39        Obj.magic (s land 1)
40
41      let has_left (s : t) : bool =
42        Obj.magic ((s lsr 1) land 1)
43
44      let is_right (s : t) : bool =
45        Obj.magic ((s lsr 2) land 1)
46
47      let is_left (s : t) : bool =
48        Obj.magic ((s lsr 3) land 1)
49
50      let kind (s : t) : Tree.NodeKind.t =
51        Obj.magic (s lsr 4)
52
53      let make is_left is_right has_left has_right kind =
54        ((Obj.magic kind) lsl 4) lor
55          ((int_of_bool is_left) lsl 3) lor
56          ((int_of_bool is_right) lsl 2) lor
57          ((int_of_bool has_left) lsl 1) lor
58          (int_of_bool has_right)
59
60    end
61
62    type node_status = {
63      sat : StateSet.t;
64      unsat : StateSet.t;
65      todo : Ata.TransList.t;
66      summary : NodeSummary.t;
67    }
68 (* Describe what is kept at each node for a run *)
69
70    module NodeStatus = Hcons.Make(struct
71      type t = node_status
72      let equal c d =
73        c == d ||
74          c.sat == d.sat &&
75          c.unsat == d.unsat &&
76          c.todo == d.todo &&
77          c.summary == d.summary
78
79      let hash c =
80        HASHINT4((c.sat.StateSet.id :> int),
81                 (c.unsat.StateSet.id :> int),
82                 (c.todo.Ata.TransList.id :> int),
83                 c.summary)
84    end
85    )
86
87    let dummy_status =
88      NodeStatus.make { sat = StateSet.empty;
89                        unsat = StateSet.empty;
90                        todo = Ata.TransList.nil;
91                        summary = NodeSummary.dummy;
92                      }
93
94
95    type run = {
96      tree : T.t ;
97      (* The argument of the run *)
98      auto : Ata.t;
99      (* The automaton to be run *)
100      status : NodeStatus.t array;
101      (* A mapping from node preorders to NodeStatus *)
102      unstable : Bitvector.t;
103      (* A bitvector remembering whether a subtree is stable *)
104      mutable redo : bool;
105      (* A boolean indicating whether the run is incomplete *)
106      mutable pass : int;
107      (* The number of times this run was updated *)
108      mutable cache2 : Ata.TransList.t Cache.N2.t;
109      (* A cache from states * label to list of transitions *)
110      mutable cache4 : NodeStatus.t Cache.N4.t;
111    }
112
113    let pass r = r.pass
114    let stable r = not r.redo
115    let auto r = r.auto
116    let tree r = r.tree
117
118
119    let dummy_trl =
120      Ata.(TransList.cons
121             (Transition.make
122                (State.dummy,QNameSet.empty, Formula.false_))
123             TransList.nil)
124
125    let make auto tree =
126      let len = T.size tree in
127      {
128        tree = tree;
129        auto = auto;
130        status = Array.create len dummy_status;
131        unstable = Bitvector.create ~init:true len;
132        redo = true;
133        pass = 0;
134        cache2 = Cache.N2.create dummy_trl;
135        cache4 = Cache.N4.create dummy_status;
136      }
137
138    let get_status a i =
139      if i < 0 then dummy_status else Array.get a i
140
141    let unsafe_get_status a i =
142      if i < 0 then dummy_status else Array.unsafe_get a i
143
144 IFDEF HTMLTRACE
145   THEN
146 DEFINE TRACE(e) = (e)
147   ELSE
148 DEFINE TRACE(e) = ()
149 END
150
151    let html tree node i config msg =
152      let config = config.NodeStatus.node in
153      Html.trace (T.preorder tree node) i
154        "node: %i<br/>%s<br/>sat: %a<br/>unsat: %a<br/>todo: %around: %i<br/>"
155        (T.preorder tree node)
156        msg
157        StateSet.print config.sat
158        StateSet.print config.unsat
159        (Ata.TransList.print ~sep:"<br/>") config.todo i
160
161
162    let debug msg tree node i config =
163      let config = config.NodeStatus.node in
164      eprintf
165        "DEBUG:%s node: %i\nsat: %a\nunsat: %a\ntodo: %around: %i\n"
166        msg
167        (T.preorder tree node)
168        StateSet.print config.sat
169        StateSet.print config.unsat
170        (Ata.TransList.print ~sep:"\n") config.todo i
171
172
173    let get_trans cache2 auto tag states =
174      let trs =
175        Cache.N2.find cache2
176          (tag.QName.id :> int) (states.StateSet.id :> int)
177      in
178      if trs == dummy_trl then
179        let trs = Ata.get_trans auto tag states in
180        (Cache.N2.add
181           cache2
182           (tag.QName.id :> int)
183           (states.StateSet.id :> int) trs; trs)
184      else trs
185
186
187
188    let simplify_atom atom pos q { NodeStatus.node = status; _ } =
189      if (pos && StateSet.mem q status.sat)
190        || ((not pos) && StateSet.mem q status.unsat) then Ata.Formula.true_
191      else if (pos && StateSet.mem q status.unsat)
192          || ((not pos) && StateSet.mem q status.sat) then Ata.Formula.false_
193      else atom
194
195
196    let eval_form phi fcs nss ps ss summary =
197      let open Ata in
198          let rec loop phi =
199            begin match Formula.expr phi with
200              Boolean.True | Boolean.False -> phi
201            | Boolean.Atom (a, b) ->
202                begin
203                  let open NodeSummary in
204                      match a.Atom.node with
205                      | Move (m, q) ->
206                          let states = match m with
207                            `First_child -> fcs
208                          | `Next_sibling -> nss
209                          | `Parent | `Previous_sibling -> ps
210                          | `Stay -> ss
211                          in simplify_atom phi b q states
212                      | Is_first_child -> Formula.of_bool (b == is_left summary)
213                      | Is_next_sibling -> Formula.of_bool (b == is_right summary)
214                      | Is k -> Formula.of_bool (b == (k == kind summary))
215                      | Has_first_child -> Formula.of_bool (b == has_left summary)
216                      | Has_next_sibling -> Formula.of_bool (b == has_right summary)
217                end
218            | Boolean.And(phi1, phi2) -> Formula.and_ (loop phi1) (loop phi2)
219            | Boolean.Or (phi1, phi2) -> Formula.or_  (loop phi1) (loop phi2)
220            end
221          in
222          loop phi
223
224    type trivalent = False | True | Unknown
225
226    let or_ t1 t2 = match t1 with
227      False -> t2
228    | True -> True
229    | Unknown -> if t2 == True then True else Unknown
230
231    let and_ t1 t2 = match t1 with
232      False -> False
233    | True -> t2
234    | Unknown -> if t2 == False then False else Unknown
235    let of_bool = function false -> False | true -> True
236
237    let eval_form phi fcs nss ps ss summary =
238      let open Ata in
239          let rec loop phi =
240            begin match Formula.expr phi with
241            | Boolean.False -> False
242            | Boolean.True -> True
243            | Boolean.Atom (a, b) ->
244                begin
245                  let open NodeSummary in
246                      match a.Atom.node with
247                      | Move (m, q) ->
248                          let sum = match m with
249                            `First_child -> fcs
250                          | `Next_sibling -> nss
251                          | `Parent | `Previous_sibling -> ps
252                          | `Stay -> ss
253                          in
254                          if StateSet.mem q sum.NodeStatus.node.sat then of_bool b
255                          else if StateSet.mem q sum.NodeStatus.node.unsat then of_bool (not b)
256                          else Unknown
257                      | Is_first_child -> of_bool (b == is_left summary)
258                      | Is_next_sibling -> of_bool (b == is_right summary)
259                      | Is k -> of_bool (b == (k == kind summary))
260                      | Has_first_child -> of_bool (b == has_left summary)
261                      | Has_next_sibling -> of_bool (b == has_right summary)
262                end
263            | Boolean.And(phi1, phi2) -> and_ (loop phi1) (loop phi2)
264            | Boolean.Or (phi1, phi2) -> or_  (loop phi1) (loop phi2)
265            end
266          in
267          loop phi
268
269
270    let eval_trans_aux cache4 fcs nss ps ss old_config =
271      let { sat = old_sat;
272            unsat = old_unsat;
273            todo = old_todo;
274            summary = old_summary } = old_config.NodeStatus.node
275      in
276      let sat, unsat, removed, kept, todo =
277        Ata.TransList.fold
278          (fun trs acc ->
279            let q, lab, phi = Ata.Transition.node trs in
280            let a_sat, a_unsat, a_rem, a_kept, a_todo = acc in
281            if StateSet.mem q a_sat || StateSet.mem q a_unsat then acc else
282              let phi_val =
283                eval_form phi fcs nss ps old_config old_summary
284              in
285              match phi_val with
286              | False -> a_sat, StateSet.add q a_unsat, StateSet.add q a_rem, a_kept, a_todo
287              | True ->  StateSet.add q a_sat, a_unsat, StateSet.add q a_rem, a_kept, a_todo
288              | Unknown ->
289                  (a_sat, a_unsat, a_rem, StateSet.add q a_kept, (Ata.TransList.cons trs a_todo))
290          ) old_todo (old_sat, old_unsat, StateSet.empty, StateSet.empty, Ata.TransList.nil)
291      in
292            (* States that have been removed from the todo list and not kept are now
293               unsatisfiable *)
294      let unsat = StateSet.union unsat (StateSet.diff removed kept) in
295            (* States that were found once to be satisfiable remain so *)
296      let unsat = StateSet.diff unsat sat in
297      let new_config = NodeStatus.make { old_config.NodeStatus.node with sat; unsat; todo; } in
298      new_config
299
300
301    let eval_trans cache4 fcs nss ps ss =
302      let fcsid = (fcs.NodeStatus.id :> int) in
303      let nssid = (nss.NodeStatus.id :> int) in
304      let psid = (ps.NodeStatus.id :> int) in
305      let rec loop old_config =
306        let oid = (old_config.NodeStatus.id :> int) in
307        let res =
308          let res = Cache.N4.find cache4 oid fcsid nssid psid in
309          if res != dummy_status then res
310          else
311            let new_config = 
312              eval_trans_aux cache4 fcs nss ps ss old_config
313            in
314            Cache.N4.add cache4 oid fcsid nssid psid new_config;
315            new_config
316        in
317        if res == old_config then res else loop res
318      in
319      loop ss
320
321
322
323
324   let top_down run =
325     let tree = run.tree in
326     let auto = run.auto in
327     let status = run.status in
328     let cache2 = run.cache2 in
329     let cache4 = run.cache4 in
330     let unstable = run.unstable in
331     let rec loop node =
332       let node_id = T.preorder tree node in
333       if node == T.nil || not (Bitvector.get unstable node_id) then false else begin
334         let parent = T.parent tree node in
335         let fc = T.first_child tree node in
336         let fc_id = T.preorder tree fc in
337         let ns = T.next_sibling tree node in
338         let ns_id = T.preorder tree ns in
339         let tag = T.tag tree node in
340         (* We enter the node from its parent *)
341
342         let status0 =
343           let c = unsafe_get_status status node_id in
344           if c == dummy_status then
345             (* first time we visit the node *)
346             let ltrs = get_trans cache2 auto tag (Ata.get_states auto) in
347             NodeStatus.make
348               { sat = StateSet.empty;
349                 unsat = Ata.get_starting_states auto;
350                 todo = ltrs;
351                 summary = NodeSummary.make
352                   (node == T.first_child tree parent) (* is_left *)
353                   (node == T.next_sibling tree parent) (* is_right *)
354                   (fc != T.nil) (* has_left *)
355                   (ns != T.nil) (* has_right *)
356                   (T.kind tree node) (* kind *)
357               }
358           else c
359         in
360
361         TRACE(html tree node _i config0 "Entering node");
362
363         (* get the node_statuses for the first child, next sibling and parent *)
364         let ps = unsafe_get_status status (T.preorder tree parent) in
365         let fcs = unsafe_get_status status fc_id in
366         let nss = unsafe_get_status status ns_id in
367         (* evaluate the transitions with all this statuses *)
368         let status1 = eval_trans cache4 fcs nss ps status0 in
369
370         TRACE(html tree node _i config1 "Updating transitions");
371
372         (* update the cache if the status of the node changed *)
373
374         if status1 != status0 then status.(node_id) <- status1;
375         (* recursively traverse the first child *)
376         let unstable_left = loop fc in
377         (* here we re-enter the node from its first child,
378            get the new status of the first child *)
379         let fcs1 = unsafe_get_status status fc_id in
380         (* update the status *)
381         let status2 = eval_trans cache4 fcs1 nss ps status1 in
382
383         TRACE(html tree node _i config2 "Updating transitions (after first-child)");
384
385         if status2 != status1 then status.(node_id) <- status2;
386         let unstable_right = loop ns in
387         let nss1 = unsafe_get_status status ns_id in
388         let status3 = eval_trans cache4 fcs1 nss1 ps status2 in
389
390         TRACE(html tree node _i config3 "Updating transitions (after next-sibling)");
391
392         if status3 != status2 then status.(node_id) <- status3;
393
394         let unstable_self =
395           (* if either our left or right child is unstable or if we still have transitions
396              pending, the current node is unstable *)
397           unstable_left
398           || unstable_right
399           || Ata.TransList.nil != status3.NodeStatus.node.todo
400         in
401         Bitvector.unsafe_set unstable node_id unstable_self;
402         TRACE((if not unstable_self then
403             Html.finalize_node
404               node_id
405               _i
406               Ata.(StateSet.intersect config3.Config.node.sat auto.selection_states)));
407         unstable_self
408       end
409     in
410     run.redo <- loop (T.root tree);
411     run.pass <- run.pass + 1
412
413 (*
414   let stats run =
415     let count = ref 0 in
416     let len = Bitvector.length run.unstable in
417     for i = 0 to len - 1 do
418       if not (Bitvector.unsafe_get run.unstable i) then
419         incr count
420     done;
421     Logger.msg `STATS
422       "%i nodes over %i were skipped in iteration %i (%.2f %%), redo is: %b"
423       !count len run.pass (100. *. (float !count /. float len))
424       run.redo
425
426
427   let eval auto tree node =
428     let len = T.size tree in
429     let run = { config = Array.create len Ata.dummy_config;
430                 unstable = Bitvector.create ~init:true len;
431                 redo = true;
432                 pass = 0
433               }
434     in
435     while run.redo do
436       run.redo <- false;
437       Ata.reset auto; (* prevents the .cache2 and .cache4 memoization tables from growing too much *)
438       run.redo <- top_down_run auto tree node run;
439       stats run;
440       run.pass <- run.pass + 1;
441     done;
442     at_exit (fun () -> Logger.msg `STATS "%i iterations" run.pass);
443     at_exit (fun () -> stats run);
444     let r = get_results auto tree node run.config in
445
446     TRACE(Html.gen_trace (module T : Tree.S with type t = T.t) (tree));
447
448     r
449 *)
450
451   let get_results run =
452     let cache = run.status in
453     let auto = run.auto in
454     let tree = run.tree in
455     let rec loop node acc =
456       if node == T.nil then acc
457       else
458         let acc0 = loop (T.next_sibling tree node) acc in
459         let acc1 = loop (T.first_child tree node) acc0 in
460
461         if Ata.(
462           StateSet.intersect
463             cache.(T.preorder tree node).NodeStatus.node.sat
464             (get_selecting_states auto)) then node::acc1
465         else acc1
466     in
467     loop (T.root tree) []
468
469
470   let get_full_results run =
471     let cache = run.status in
472     let auto = run.auto in
473     let tree = run.tree in
474     let res_mapper = Hashtbl.create MED_H_SIZE in
475     let () =
476       StateSet.iter
477         (fun q -> Hashtbl.add res_mapper q [])
478         (Ata.get_selecting_states auto)
479     in
480     let rec loop node =
481       if node != T.nil then
482         let () = loop (T.next_sibling tree node) in
483         let () = loop (T.first_child tree node) in
484         StateSet.iter
485           (fun q ->
486             try
487               let acc = Hashtbl.find res_mapper q in
488               Hashtbl.replace res_mapper q (node::acc)
489             with
490               Not_found -> ())
491           cache.(T.preorder tree node).NodeStatus.node.sat
492     in
493     loop (T.root tree);
494     StateSet.fold
495       (fun q acc -> (q, Hashtbl.find res_mapper q)::acc)
496       (Ata.get_selecting_states auto) []
497
498   let prepare_run run list =
499     let tree = run.tree in
500     let auto = run.auto in
501     let status = run.status in
502     let cache2 = run.cache2 in
503     List.iter (fun node ->
504       let parent = T.parent tree node in
505       let fc = T.first_child tree node in
506       let ns = T.next_sibling tree node in
507       let tag = T.tag tree node in
508
509       let status0 =
510         NodeStatus.make
511           { sat = Ata.get_starting_states auto;
512             unsat = StateSet.empty;
513             todo = get_trans cache2 auto tag (Ata.get_states auto);
514             summary = NodeSummary.make
515               (node == T.first_child tree parent) (* is_left *)
516               (node == T.next_sibling tree parent) (* is_right *)
517               (fc != T.nil) (* has_left *)
518               (ns != T.nil) (* has_right *)
519               (T.kind tree node) (* kind *)
520           }
521       in
522       let node_id = T.preorder tree node in
523       status.(node_id) <- status0) list
524
525
526   let eval full auto tree nodes =
527     let run = make auto tree in
528     prepare_run run nodes;
529     while run.redo do
530       top_down run
531     done;
532     if full then `Full (get_full_results run)
533     else `Normal (get_results run)
534
535
536   let full_eval auto tree nodes =
537     match eval true auto tree nodes with
538       `Full l -> l
539     | _ -> assert false
540
541   let eval auto tree nodes =
542     match eval false auto tree nodes with
543       `Normal l -> l
544     | _ -> assert false
545
546 end