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