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