Add functions to normalize an automaton:
[tatoo.git] / src / auto / ata.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 (*
17   Time-stamp: <Last modified on 2013-02-08 18:43:08 CET by Kim Nguyen>
18 *)
19
20 INCLUDE "utils.ml"
21 open Format
22 open Utils
23
24 type move = [ `Left | `Right | `Up1 | `Up2 | `Epsilon ]
25 type state_ctx = { mutable left : StateSet.t;
26              mutable right : StateSet.t;
27              mutable up1 : StateSet.t;
28              mutable up2 : StateSet.t;
29              mutable epsilon : StateSet.t}
30
31 type pred_ = move * bool * State.t
32
33 module Move : (Formula.PREDICATE with type data = pred_ and type ctx = state_ctx ) =
34 struct
35
36   module Node =
37   struct
38     type t = move * bool * State.t
39     let equal n1 n2 = n1 = n2
40     let hash n = Hashtbl.hash n
41   end
42
43   type ctx = state_ctx
44
45   let make_ctx a b c d e =
46     { left = a; right = b; up1 = c; up2 = d; epsilon = e }
47
48   include Hcons.Make(Node) 
49
50   let print ppf a =
51     let _ = flush_str_formatter() in
52     let fmt = str_formatter in
53
54     let m, b, s = a.node in
55     let dir,num =
56       match  m with
57       | `Left ->  Pretty.down_arrow, Pretty.subscript 1
58       | `Right -> Pretty.down_arrow, Pretty.subscript 2
59       | `Epsilon -> Pretty.epsilon, ""
60       | `Up1 -> Pretty.up_arrow, Pretty.subscript 1
61       | `Up2 -> Pretty.up_arrow, Pretty.subscript 2
62     in
63     fprintf fmt "%s%s" dir num;
64     State.print fmt s;
65     let str = flush_str_formatter() in
66     if b then fprintf ppf "%s" str
67     else Pretty.pp_overline ppf str
68
69   let neg p =
70     let l, b, s = p.node in
71     make (l, not b, s)
72   exception NegativeAtom of (move*State.t)
73   let eval ctx p =
74     let l, b, s = p.node in
75     if b then raise (NegativeAtom(l,s));
76     StateSet.mem s begin
77       match l with
78         `Left -> ctx.left
79       | `Right -> ctx.right
80       | `Up1 -> ctx.up1
81       | `Up2 -> ctx.up2
82       | `Epsilon -> ctx.epsilon
83     end
84 end
85
86 module SFormula = Formula.Make(Move)
87 type 'a t = {
88   id : Uid.t;
89   mutable states : StateSet.t;
90   mutable top_states : StateSet.t;
91   mutable bottom_states: StateSet.t;
92   mutable selection_states: StateSet.t;
93   transitions: (State.t, (QNameSet.t*SFormula.t) list) Hashtbl.t;
94 }
95
96 let next = Uid.make_maker ()
97
98 let create () = { id = next ();
99                   states = StateSet.empty;
100                   top_states = StateSet.empty;
101                   bottom_states = StateSet.empty;
102                   selection_states = StateSet.empty;
103                   transitions = Hashtbl.create 17;
104  }
105
106
107 (*
108   [add_trans a q labels f] adds a transition [(q,labels) -> f] to the
109   automaton [a] but ensures that transitions remains pairwise disjoint
110 *)
111
112 let add_trans a q s f =
113   let trs = try Hashtbl.find a.transitions q with Not_found -> [] in
114   let cup, ntrs =
115     List.fold_left (fun (acup, atrs) (labs, phi) ->
116       let lab1 = QNameSet.inter labs s in
117       let lab2 = QNameSet.diff labs s in
118       let tr1 =
119         if QNameSet.is_empty lab1 then []
120         else [ (lab1, SFormula.or_ phi f) ]
121       in
122       let tr2 =
123         if QNameSet.is_empty lab2 then []
124         else [ (lab2, SFormula.or_ phi f) ]
125       in
126       (QNameSet.union acup labs, tr1@ tr2 @ atrs)
127     ) (QNameSet.empty, []) trs
128   in
129   let rem = QNameSet.diff s cup in
130   let ntrs = if QNameSet.is_empty rem then ntrs
131     else (rem, f) :: ntrs
132   in
133   Hashtbl.replace a.transitions q ntrs
134
135
136 let print fmt a =
137   fprintf fmt
138     "Unique ID: %i@\n\
139      States %a@\n\
140      Top states: %a@\n\
141      Bottom states: %a@\n\
142      Selection states: %a@\n\
143      Alternating transitions:@\n"
144     (a.id :> int)
145     StateSet.print a.states
146     StateSet.print a.top_states
147     StateSet.print a.bottom_states
148     StateSet.print a.selection_states;
149   let trs =
150     Hashtbl.fold
151       (fun q t acc -> List.fold_left (fun acc (s , f) -> (q,s,f)::acc) acc t)
152       a.transitions
153       []
154   in
155   let sorted_trs = List.stable_sort (fun (q1, s1, phi1) (q2, s2, phi2) ->
156     let c = State.compare q1 q2 in - (if c == 0 then QNameSet.compare s1 s2 else c))
157     trs
158   in
159   let sfmt = str_formatter in
160   let _ = flush_str_formatter () in
161   let strs_strings, maxs = List.fold_left (fun (accl, accm) (q, s, f) ->
162     let s1 = State.print sfmt q; flush_str_formatter () in
163     let s2 = QNameSet.print sfmt s; flush_str_formatter () in
164     let s3 = SFormula.print sfmt f; flush_str_formatter () in
165     ( (s1, s2, s3) :: accl,
166       max
167         accm (2 + String.length s1 + String.length s2))
168   ) ([], 0) sorted_trs
169   in
170   List.iter (fun (s1, s2, s3) ->
171     fprintf fmt "%s, %s" s1 s2;
172     fprintf fmt "%s" (Pretty.padding (maxs - String.length s1 - String.length s2 - 2));
173     fprintf fmt "%s  %s@\n" Pretty.right_arrow s3) strs_strings
174
175 (*
176   [complete transitions a] ensures that for each state q
177   and each symbols s in the alphabet, a transition q, s exists.
178   (adding q, s -> F when necessary).
179 *)
180
181 let complete_transitions a =
182   StateSet.iter (fun q ->
183     let qtrans = Hashtbl.find a.transitions q in
184     let rem =
185       List.fold_left (fun rem (labels, _) ->
186         QNameSet.diff rem labels) QNameSet.any qtrans
187     in
188     let nqtrans =
189       if QNameSet.is_empty rem then qtrans
190       else
191         (rem, SFormula.false_) :: qtrans
192     in
193     Hashtbl.replace a.transitions q nqtrans
194   ) a.states
195
196 (* [normalize_negations a] removes negative atoms in the formula
197    complementing the sub-automaton in the negative states.
198    [TODO check the meaning of negative upward arrows]
199 *)
200 let normalize_negations a =
201   let memo_state = Hashtbl.create 17 in
202   let todo = Queue.create () in
203   let rec flip b f =
204     match SFormula.expr f with
205       Formula.True | Formula.False -> if b then f else SFormula.not_ f
206     | Formula.Or(f1, f2) -> (if b then SFormula.or_ else SFormula.and_)(flip b f1) (flip b f2)
207     | Formula.And(f1, f2) -> (if b then SFormula.and_ else SFormula.or_)(flip b f1) (flip b f2)
208     | Formula.Atom(a) -> begin
209       let l, b', q = Move.node a in
210       if b == b' then begin
211         (* a appears positively, either no negation or double negation *)
212         if not (Hashtbl.mem memo_state (q,b)) then Queue.add (q,true) todo;
213         SFormula.atom_ (Move.make (l, true, q))
214       end else begin
215         (* need to reverse the atom
216            either we have a positive state deep below a negation
217            or we have a negative state in a positive formula
218            b' = sign of the state
219            b = sign of the containing formula
220         *)
221         let not_q =
222           try
223             (* does the inverted state of q exist ? *)
224             Hashtbl.find memo_state (q, false)
225           with
226             Not_found ->
227               (* create a new state and add it to the todo queue *)
228               let nq = State.make () in
229               Hashtbl.add memo_state (q, false) nq;
230               Queue.add (q, false) todo; nq
231         in
232         SFormula.atom_ (Move.make (l, true, not_q))
233       end
234     end
235   in
236   StateSet.iter (fun q -> Queue.add (q, true) todo) a.top_states;
237   while not (Queue.is_empty todo) do
238     let (q, b) as key = Queue.pop todo in
239     let q' =
240       try
241         Hashtbl.find memo_state key
242       with
243         Not_found ->
244           let nq = if b then q else State.make () in
245           Hashtbl.add memo_state key nq; nq
246     in
247     let trans = Hashtbl.find a.transitions q in
248     let trans' = List.map (fun (lab, f) -> lab, flip b f) trans in
249     Hashtbl.replace a.transitions q' trans'
250   done;
251   Hashtbl.iter (fun (q, b) q' ->
252     if not (b || StateSet.mem q a.bottom_states) then
253       a.bottom_states <- StateSet.add q' a.bottom_states
254   ) memo_state
255