cb2ea3b548b4fa879733285788de5c7544765e71
[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
225    let eval_trans_aux cache4 fcs nss ps ss old_config =
226      let { sat = old_sat;
227            unsat = old_unsat;
228            todo = old_todo;
229            summary = old_summary } = old_config.NodeStatus.node
230      in
231      let sat, unsat, removed, kept, todo =
232        Ata.TransList.fold
233          (fun trs acc ->
234            let q, lab, phi = Ata.Transition.node trs in
235            let a_sat, a_unsat, a_rem, a_kept, a_todo = acc in
236            if StateSet.mem q a_sat || StateSet.mem q a_unsat then acc else
237              let new_phi =
238                eval_form phi fcs nss ps old_config old_summary
239              in
240              if Ata.Formula.is_true new_phi then
241                StateSet.add q a_sat, a_unsat, StateSet.add q a_rem, a_kept, a_todo
242              else if Ata.Formula.is_false new_phi then
243                a_sat, StateSet.add q a_unsat, StateSet.add q a_rem, a_kept, a_todo
244              else
245                let new_tr = Ata.Transition.make (q, lab, new_phi) in
246                (a_sat, a_unsat, a_rem, StateSet.add q a_kept, (Ata.TransList.cons new_tr a_todo))
247          ) old_todo (old_sat, old_unsat, StateSet.empty, StateSet.empty, Ata.TransList.nil)
248      in
249            (* States that have been removed from the todo list and not kept are now
250               unsatisfiable *)
251      let unsat = StateSet.union unsat (StateSet.diff removed kept) in
252            (* States that were found once to be satisfiable remain so *)
253      let unsat = StateSet.diff unsat sat in
254      let new_config = NodeStatus.make { old_config.NodeStatus.node with sat; unsat; todo; } in
255      new_config
256
257
258    let eval_trans cache4 fcs nss ps ss =
259      let fcsid = (fcs.NodeStatus.id :> int) in
260      let nssid = (nss.NodeStatus.id :> int) in
261      let psid = (ps.NodeStatus.id :> int) in
262      let rec loop old_config =
263        let oid = (old_config.NodeStatus.id :> int) in
264        let res =
265          let res = Cache.N4.find cache4 oid fcsid nssid psid in
266          if res != dummy_status then res
267          else
268            let new_config = 
269              eval_trans_aux cache4 fcs nss ps ss old_config
270            in
271            Cache.N4.add cache4 oid fcsid nssid psid new_config;
272            new_config
273        in
274        if res == old_config then res else loop res
275      in
276      loop ss
277
278
279
280
281   let top_down run =
282     let tree = run.tree in
283     let auto = run.auto in
284     let status = run.status in
285     let cache2 = run.cache2 in
286     let cache4 = run.cache4 in
287     let unstable = run.unstable in
288     let rec loop node =
289       let node_id = T.preorder tree node in
290       if node == T.nil || not (Bitvector.get unstable node_id) then false else begin
291         let parent = T.parent tree node in
292         let fc = T.first_child tree node in
293         let fc_id = T.preorder tree fc in
294         let ns = T.next_sibling tree node in
295         let ns_id = T.preorder tree ns in
296         let tag = T.tag tree node in
297         (* We enter the node from its parent *)
298
299         let status0 =
300           let c = unsafe_get_status status node_id in
301           if c == dummy_status then
302             (* first time we visit the node *)
303             let ltrs = get_trans cache2 auto tag (Ata.get_states auto) in
304             NodeStatus.make
305               { sat = StateSet.empty;
306                 unsat = Ata.get_starting_states auto;
307                 todo = ltrs;
308                 summary = NodeSummary.make
309                   (node == T.first_child tree parent) (* is_left *)
310                   (node == T.next_sibling tree parent) (* is_right *)
311                   (fc != T.nil) (* has_left *)
312                   (ns != T.nil) (* has_right *)
313                   (T.kind tree node) (* kind *)
314               }
315           else c
316         in
317
318         TRACE(html tree node _i config0 "Entering node");
319
320         (* get the node_statuses for the first child, next sibling and parent *)
321         let ps = unsafe_get_status status (T.preorder tree parent) in
322         let fcs = unsafe_get_status status fc_id in
323         let nss = unsafe_get_status status ns_id in
324         (* evaluate the transitions with all this statuses *)
325         let status1 = eval_trans cache4 fcs nss ps status0 in
326
327         TRACE(html tree node _i config1 "Updating transitions");
328
329         (* update the cache if the status of the node changed *)
330
331         if status1 != status0 then status.(node_id) <- status1;
332         (* recursively traverse the first child *)
333         let unstable_left = loop fc in
334         (* here we re-enter the node from its first child,
335            get the new status of the first child *)
336         let fcs1 = unsafe_get_status status fc_id in
337         (* update the status *)
338         let status2 = eval_trans cache4 fcs1 nss ps status1 in
339
340         TRACE(html tree node _i config2 "Updating transitions (after first-child)");
341
342         if status2 != status1 then status.(node_id) <- status2;
343         let unstable_right = loop ns in
344         let nss1 = unsafe_get_status status ns_id in
345         let status3 = eval_trans cache4 fcs1 nss1 ps status2 in
346
347         TRACE(html tree node _i config3 "Updating transitions (after next-sibling)");
348
349         if status3 != status2 then status.(node_id) <- status3;
350
351         let unstable_self =
352           (* if either our left or right child is unstable or if we still have transitions
353              pending, the current node is unstable *)
354           unstable_left
355           || unstable_right
356           || Ata.TransList.nil != status3.NodeStatus.node.todo
357         in
358         Bitvector.unsafe_set unstable node_id unstable_self;
359         TRACE((if not unstable_self then
360             Html.finalize_node
361               node_id
362               _i
363               Ata.(StateSet.intersect config3.Config.node.sat auto.selection_states)));
364         unstable_self
365       end
366     in
367     run.redo <- loop (T.root tree);
368     run.pass <- run.pass + 1
369
370 (*
371   let stats run =
372     let count = ref 0 in
373     let len = Bitvector.length run.unstable in
374     for i = 0 to len - 1 do
375       if not (Bitvector.unsafe_get run.unstable i) then
376         incr count
377     done;
378     Logger.msg `STATS
379       "%i nodes over %i were skipped in iteration %i (%.2f %%), redo is: %b"
380       !count len run.pass (100. *. (float !count /. float len))
381       run.redo
382
383
384   let eval auto tree node =
385     let len = T.size tree in
386     let run = { config = Array.create len Ata.dummy_config;
387                 unstable = Bitvector.create ~init:true len;
388                 redo = true;
389                 pass = 0
390               }
391     in
392     while run.redo do
393       run.redo <- false;
394       Ata.reset auto; (* prevents the .cache2 and .cache4 memoization tables from growing too much *)
395       run.redo <- top_down_run auto tree node run;
396       stats run;
397       run.pass <- run.pass + 1;
398     done;
399     at_exit (fun () -> Logger.msg `STATS "%i iterations" run.pass);
400     at_exit (fun () -> stats run);
401     let r = get_results auto tree node run.config in
402
403     TRACE(Html.gen_trace (module T : Tree.S with type t = T.t) (tree));
404
405     r
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 rec loop node =
438       if node != T.nil then
439         let () = loop (T.next_sibling tree node) in
440         let () = loop (T.first_child tree node) in
441         StateSet.iter
442           (fun q ->
443             try
444               let acc = Hashtbl.find res_mapper q in
445               Hashtbl.replace res_mapper q (node::acc)
446             with
447               Not_found -> ())
448           cache.(T.preorder tree node).NodeStatus.node.sat
449     in
450     loop (T.root tree);
451     StateSet.fold
452       (fun q acc -> (q, Hashtbl.find res_mapper q)::acc)
453       (Ata.get_selecting_states auto) []
454
455   let prepare_run run list =
456     let tree = run.tree in
457     let auto = run.auto in
458     let status = run.status in
459     let cache2 = run.cache2 in
460     List.iter (fun node ->
461       let parent = T.parent tree node in
462       let fc = T.first_child tree node in
463       let ns = T.next_sibling tree node in
464       let tag = T.tag tree node in
465
466       let status0 =
467         NodeStatus.make
468           { sat = Ata.get_starting_states auto;
469             unsat = StateSet.empty;
470             todo = get_trans cache2 auto tag (Ata.get_states auto);
471             summary = NodeSummary.make
472               (node == T.first_child tree parent) (* is_left *)
473               (node == T.next_sibling tree parent) (* is_right *)
474               (fc != T.nil) (* has_left *)
475               (ns != T.nil) (* has_right *)
476               (T.kind tree node) (* kind *)
477           }
478       in
479       let node_id = T.preorder tree node in
480       status.(node_id) <- status0) list
481
482
483   let eval full auto tree nodes =
484     let run = make auto tree in
485     prepare_run run nodes;
486     while run.redo do
487       top_down run
488     done;
489     if full then `Full (get_full_results run)
490     else `Normal (get_results run)
491
492
493   let full_eval auto tree nodes =
494     match eval true auto tree nodes with
495       `Full l -> l
496     | _ -> assert false
497
498   let eval auto tree nodes =
499     match eval false auto tree nodes with
500       `Normal l -> l
501     | _ -> assert false
502
503 end