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