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