timedAutomaton.ml 37.9 KB
Newer Older
mcolange's avatar
mcolange committed
1 2 3
open Batteries
open Common
open Printf
mcolange's avatar
mcolange committed
4
open Dbm
mcolange's avatar
mcolange committed
5 6 7 8
open Uta

module type TIMED_AUTOMATON =
sig
mcolange's avatar
mcolange committed
9
  module Dbm : IDBM
10

mcolange's avatar
mcolange committed
11 12 13 14 15
  type timed_automaton
  type discrete_state
  type transition

  val clocks : timed_automaton -> string VarContext.t
16 17
  val is_state_equal : discrete_state -> discrete_state -> bool
  val hash_discrete_state : discrete_state -> int
mcolange's avatar
mcolange committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
  val initial_discrete_state : timed_automaton -> discrete_state
  (* does it belong here? If so, so does type for extended_state... *)
  val initial_extended_state : timed_automaton -> discrete_state * Dbm.t
  val transitions_from : timed_automaton -> discrete_state -> transition list
  val transition_fields : timed_automaton -> transition ->
    (discrete_state * Dbm.t * ClockSet.t * discrete_state)
  val guard_of_transition : timed_automaton -> transition -> Dbm.t
  val invariant_of_discrete_state : timed_automaton -> discrete_state -> Dbm.t
  val is_urgent_or_committed : timed_automaton -> discrete_state -> bool
  val is_target : timed_automaton -> discrete_state -> bool
  val lu_bounds : timed_automaton -> discrete_state -> int array -> int array -> unit
  (** print functions *)
  val print_discrete_state  : 'b BatIO.output -> timed_automaton -> discrete_state -> unit
  val print_transition : 'b BatIO.output -> timed_automaton -> transition -> unit
  val print_timed_automaton : 'b BatIO.output -> timed_automaton -> unit
  val print_extended_state : 'b BatIO.output -> timed_automaton -> (discrete_state * Dbm.t) -> unit
end

module type TIMED_GAME = 
sig
  include TIMED_AUTOMATON
  
  (* I am not convinced it is the better interface *)
  val is_controllable : timed_automaton -> edge -> bool
end

mcolange's avatar
mcolange committed
44
module GenericUAutomaton (BDbm : BIG_IDBM) =
mcolange's avatar
mcolange committed
45
struct
46

mcolange's avatar
mcolange committed
47
  module Dbm = BDbm.Dbm
48

mcolange's avatar
mcolange committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  (** In contrast with Uta.expression used in the parser, the variables here are indexed
   *  by unique integer identifiers.
   *)
  type expression =
    | Constant of int
    | Variable of int
    | Clock of int
    | Sum of expression * expression
    | Product of expression * expression
    | Substraction of expression * expression
    | Division of expression * expression

  type atomic_guard = 
    | GuardLeq of expression * expression
    | GuardLess of expression * expression
    | GuardGeq of expression * expression
    | GuardGreater of expression * expression
    | GuardEqual of expression * expression

  (** A guard is a conjunction of atomic guards *)
  type guard = atomic_guard list

  (** clocks updates *)
  type update = (int * expression) list

  type edge = {
    edgeSource : int;
    edgeGuard : guard;
    edgeDiscGuard : guard;
    edgeReset : ClockSet.t;
    edgeDiscUpdate : update;
    edgeTarget : int;
    edgeSync : chan option;
    mutable edgeProc : process option;
    edgeControllable : bool
  }
  and location = {
    locId : int;
    mutable locName : string;
    locCommitted : bool;
    locUrgent : bool;
    locInvar : guard;
    locEdges : edge list;
    mutable locProc : process option;
  }
  and process = {
    procName : string;
    procId : int;
    procLocations : location array;
    procInitLoc : int;
  }
  type discrete_state = {
    stateLocs : location array;
    stateVars : int array;
  }

  type transition = InternalTrans of discrete_state * edge
                  | SyncTrans of discrete_state * edge * edge

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

  module LocHashtbl = Hashtbl.Make(
    struct
      type t = location array

      exception NotEqual

      let equal a1 a2 =
        let dim = Array.length a1 in
        assert(dim = (Array.length a2));
        try
        for x = 0 to dim-1 do
          if (a1.(x).locId <> a2.(x).locId) then
            raise NotEqual
        done;
        true
        with NotEqual -> false

      let hash a =
        Hashtbl.hash (Array.map (fun x -> x.locId) a)

    end
  )

mcolange's avatar
mcolange committed
132 133 134 135 136 137 138 139 140 141 142 143 144
  (** A succinct version of the above to be used in hash tables; we just don't need the variable valuations *)
  type _succinct_transition = Suc_InternalTrans of edge
                            | Suc_SyncTrans of edge * edge

  type timed_automaton = { 
    procs : process array;
    clocks : string VarContext.t;
    vars : string VarContext.t;
    init : discrete_state;
    mutable query : query;
    mutable lowerLU : int array array array;
    mutable upperLU : int array array array;
    guards_tbl : (_succinct_transition,Dbm.t) Hashtbl.t;
145
    invars_tbl : Dbm.t LocHashtbl.t;
mcolange's avatar
mcolange committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
  }
  

  (********** PRINTING AUXILIARY FUNCTIONS **********)
  let rec string_of_exp ta e = 
    let string_of_exp = string_of_exp ta in
    (function
      | Constant c -> sprintf "%d" c 
      | Variable(id) -> VarContext.var_of_index ta.vars id
      | Clock(id) ->  VarContext.var_of_index ta.clocks id
      | Product(e1,e2) ->
        sprintf "%s * %s" (string_of_exp e1)
          (string_of_exp e2)
      | Sum(e1,e2) ->
        sprintf "(%s + %s)" (string_of_exp e1)
          (string_of_exp e2)
      | Division(e1,e2) ->
        sprintf "%s / %s" (string_of_exp e1)
          (string_of_exp e2)
      | Substraction(e1,e2) ->
        sprintf "(%s - %s)" (string_of_exp e1)
          (string_of_exp e2)
    ) e


  let string_of_atomic_guard ta = 
    let string_of_exp = string_of_exp ta in
    function
    |  GuardLeq(v,exp) ->
      sprintf "%s <= %s" (string_of_exp v)(string_of_exp exp)
    | GuardLess(v,exp) ->
      sprintf "%s < %s" (string_of_exp v)(string_of_exp exp)
    | GuardGeq(v,exp)->
      sprintf "%s >= %s" (string_of_exp v)(string_of_exp exp)
    | GuardGreater(v,exp)->
      sprintf "%s > %s" (string_of_exp v) (string_of_exp exp)
    | GuardEqual(v,exp)->
      sprintf "%s == %s" (string_of_exp v) (string_of_exp exp)


  let xml_string_of_atomic_guard ta = 
    let string_of_exp = string_of_exp ta in       
    function
    |  GuardLeq(v,exp) ->
      sprintf "%s &lt;= %s" (string_of_exp v)(string_of_exp exp)
    | GuardLess(v,exp) ->
      sprintf "%s &lt; %s" (string_of_exp v)(string_of_exp exp)
    | GuardGeq(v,exp)->
      sprintf "%s &gt;= %s" (string_of_exp v)(string_of_exp exp)
    | GuardGreater(v,exp)->
      sprintf "%s &gt; %s" (string_of_exp v) (string_of_exp exp)
    | GuardEqual(v,exp)->
      sprintf "%s == %s" (string_of_exp v) (string_of_exp exp)


  let rec string_of_guard ta = 
    function
    | [] -> ""
    | [x] -> string_of_atomic_guard ta x
    | x :: y :: l -> 
      ((string_of_atomic_guard ta x) ^ " && ")
      ^ (string_of_guard ta (y::l))


  let rec xml_string_of_guard ta =
    function
    | [] -> ""
    | [x] -> xml_string_of_atomic_guard ta x
    | x :: y :: l -> 
      ((xml_string_of_atomic_guard ta x) ^ " &amp;&amp; ")
      ^ (xml_string_of_guard ta (y::l))


  let string_of_updates ta ups = 
    let ups_str = 
      List.map (fun (var,exp) -> sprintf "%s = %s" (VarContext.var_of_index ta.vars var) (string_of_exp ta exp)) ups in
    String.concat ", " ups_str

    
  let string_of_state ta state =
    let out = Buffer.create 50 in 
    Array.iter (fun loc -> Buffer.add_string out loc.locName;
                 Buffer.add_string out " ") state.stateLocs;
    if (Array.length state.stateVars > 0 ) then (
      Buffer.add_string out "\n";
      Array.iteri (fun i v ->
          let name = VarContext.index2var ta.vars i in
          Buffer.add_string out (sprintf "%s = %d, " name v)) state.stateVars;
    );
    (*    Buffer.add_string out "\n";*)
    Buffer.contents out

    
  let string_of_edge ta edge = 
    let proc = match edge.edgeProc with
        None -> failwith "Edge with no proc"
      | Some proc -> proc
    in
    let resetnames = 
      let out = Buffer.create 100 in
      ClockSet.iter 
        (fun ind -> 
           let name = VarContext.index2var ta.clocks ind in
           Buffer.add_string out name; 
           Buffer.add_string out " ") 
        edge.edgeReset;
      Buffer.contents out
    in
    let sync = match edge.edgeSync with 
      |None -> ""
      |Some(SendChan(c)) -> c^"!"
      |Some(RecvChan(c)) -> c^"?"
    in
    let discguardstr = string_of_guard ta edge.edgeDiscGuard in
    let guardstr = string_of_guard ta edge.edgeGuard in
    sprintf "%s%s -> %s \tDiscGuard: %s \tDiscUpdate: %s \tGuard: %s \tResets:%s \tSync:%s" 
      (if (edge.edgeControllable) then "" else "[E]")
      (proc.procLocations.(edge.edgeSource).locName)
      (proc.procLocations.(edge.edgeTarget).locName)
      discguardstr
      (string_of_updates ta edge.edgeDiscUpdate)
      guardstr
      resetnames
      sync
  (*
    sprintf "Edge:\n Target: %s.%s\n\tDiscGuard: %s\n\tDiscUpdate: %s\n\tGuard: %s\n\tResets:%s\n\tSync:%s\n" 
            proc.procName
            (proc.procLocations.(edge.edgeTarget).locName)
            discguardstr
            (string_of_updates ta edge.edgeDiscUpdate)
            guardstr
            resetnames
            sync
     *)

  
  let string_of_location ta loc =
    let out = Buffer.create 128 in
    let utter = Buffer.add_string out in
    utter (sprintf "Location %d: %s "loc.locId loc.locName);
    if (loc.locCommitted) then
      utter "committed ";
    utter (string_of_guard ta loc.locInvar);
    utter "\n";
    utter (sprintf "Has %d edges:\n" (List.length loc.locEdges));
    let edgestrlist = (List.map (string_of_edge ta) loc.locEdges) in
    utter (String.concat "\n" edgestrlist);
    utter "\n";
    Buffer.contents out


  let string_of_process ta proc = 
    let out = Buffer.create 1000 in
    let utter = Buffer.add_string out in
    utter (sprintf "Process(%d): %s\n"  proc.procId proc.procName);
    Array.iter (fun loc -> utter (string_of_location ta loc)) proc.procLocations;
    utter (sprintf "Initial location id: %d\n" proc.procInitLoc);
    Buffer.contents out


  let string_of_transition ta tr =
    let buf = Buffer.create 128 in
    let out = Buffer.add_string buf in
    let proc_name e = match e.edgeProc with
      |None -> ""
      |Some p -> p.procName
    in
    match tr with 
      InternalTrans(state,e) ->
      out (sprintf "From global state: %s\n" (string_of_state ta state));
      out (string_of_edge ta e);
      Buffer.contents buf
    | SyncTrans(state,e1,e2) ->
      out (sprintf "Synchronized Transition btw Processes: %s - %s\n Source: %s\n" (proc_name e1) (proc_name e2)
             (string_of_state ta state));
      out "Sync:\n";
      out (string_of_edge ta e1);
      out "\n";
      out (string_of_edge ta e2);
      Buffer.contents buf


  (********** OTHER AUXILIARY FUNCTIONS **********)
    
  let rec eval_disc_exp ta vars exp =
    try
      let k = 
        (match exp with
         | Constant c -> c
         | Variable(id) -> 
           if ( id < 0 || id >= Array.length vars ) then
             failwith (sprintf "Var index %d out of bounds (%d)" id (Array.length vars));
           vars.(id)
         | Clock(id) ->raise Found
         | Product(e1,e2) -> (eval_disc_exp ta vars e1) * (eval_disc_exp ta vars e2)
         | Sum(e1,e2) -> (eval_disc_exp ta vars e1) + (eval_disc_exp ta vars e2)
         | Division(e1,e2) -> (eval_disc_exp ta vars e1) / (eval_disc_exp ta vars e2)
         | Substraction(e1,e2) -> (eval_disc_exp ta vars e1) - (eval_disc_exp ta vars e2)
        ) in
      (*
      eprintf "%s -----> %d\n" (string_of_exp ta exp) k;
       *)
      k
    with Found ->
      failwith ("Discrete expression contains clock: " ^ (string_of_exp ta exp)); 
       | e -> raise e

       
  let source_location_of_edge ta edge =
    let proc = match edge.edgeProc with
      |None -> failwith "Edge has no process"
      |Some(proc)-> proc
    in
    proc.procLocations.(edge.edgeSource)


  let eval_disc_guard ta state guard =
    let eval =
      eval_disc_exp ta state.stateVars
    in
    let atomic = function
      | GuardLeq(e1,e2) ->
        (eval e1) <= (eval e2)
      | GuardLess(e1,e2) ->
        (eval e1) < (eval e2)
      | GuardGeq(e1,e2) ->
        (eval e1) >= (eval e2)
      | GuardGreater(e1,e2) ->
        (eval e1) > (eval e2)
      | GuardEqual(e1,e2) ->
        (eval e1) = (eval e2)
    in
    List.fold_left (fun b ag -> b && (atomic ag)) true guard


  let _guard_to_dbm ta state g =
    let nclocks = VarContext.size ta.clocks in
    let dbm = Dbm.create nclocks in
    Dbm.set_init dbm;
    let aux = function
      | GuardLeq(Clock(c), e) ->
          let k = eval_disc_exp ta state e in
mcolange's avatar
mcolange committed
388
          Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_WEAK))
mcolange's avatar
mcolange committed
389 390
      | GuardLess(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
mcolange's avatar
mcolange committed
391
        Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_STRICT))
mcolange's avatar
mcolange committed
392 393
      | GuardGeq(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
mcolange's avatar
mcolange committed
394
        Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_WEAK))
mcolange's avatar
mcolange committed
395 396
      | GuardGreater(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
mcolange's avatar
mcolange committed
397
        Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_STRICT))
mcolange's avatar
mcolange committed
398 399
      | GuardEqual(Clock(c), e) ->
        let k = eval_disc_exp ta state e in
mcolange's avatar
mcolange committed
400 401
        Dbm.constrain dbm (0, c, (-k, Udbml.Basic_types.DBM_WEAK));
        Dbm.constrain dbm (c, 0, (k, Udbml.Basic_types.DBM_WEAK))
mcolange's avatar
mcolange committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
      | _ as e -> failwith (sprintf "Bad Guard: %s" (string_of_guard ta [e]))
    in
    List.iter aux g;
    dbm


  let is_committed state =
    Array.exists (fun loc -> loc.locCommitted) state.stateLocs

  
  let _copy_state state = 
    { stateVars = Array.copy state.stateVars;
      stateLocs = Array.copy state.stateLocs}


  (** Apply discrete update of edge to state, result written in state' *)
  let _apply_edge ta state edge state' =
    let aux = fun (id,e) -> 
      state'.stateVars.(id) <- eval_disc_exp ta state.stateVars e
    in
    let tproc = match edge.edgeProc with
      | None -> failwith "Edge without process"
      | Some(proc) -> proc
    in
    state'.stateLocs.(tproc.procId) <- tproc.procLocations.(edge.edgeTarget);
    List.iter aux edge.edgeDiscUpdate



  (********** TIMED_AUTOMATON interface **********)
  let clocks ta = ta.clocks

434
  let hash_discrete_state s =
435 436 437 438 439 440
    let tmp = Array.fold_right
      (fun x r -> r + x.locId + 0x9e3779b9 + (r lsl 6) + (r lsr 2))
      s.stateLocs 0
    in Array.fold_right
      (fun x r -> r + x + 0x9e3779b9 + (r lsl 6) + (r lsr 2))
      s.stateVars tmp
441 442

  let is_state_equal s t =
mcolange's avatar
mcolange committed
443 444 445 446 447 448 449 450 451 452
    not(
      (Array.exists2 (fun l1 l2 -> not (l1.locId = l2.locId)) s.stateLocs t.stateLocs)
      ||
      (Array.exists2 (fun v1 v2 -> not (v1 = v2)) s.stateVars t.stateVars)
    )

  let initial_discrete_state ta = ta.init

  let invariant_of_discrete_state ta state =
    try
453
      LocHashtbl.find ta.invars_tbl state.stateLocs
mcolange's avatar
mcolange committed
454 455 456 457
    with Not_found ->
      let glob_inv =
        Array.fold_left (fun acc loc -> loc.locInvar @ acc ) [] state.stateLocs in
      let inv = _guard_to_dbm ta state.stateVars glob_inv in
458
      LocHashtbl.add ta.invars_tbl state.stateLocs inv;
mcolange's avatar
mcolange committed
459 460 461 462 463 464 465 466 467
      inv
       | _ as e -> raise e

  let initial_extended_state ta =
    let dim = (VarContext.size (clocks ta)) in
    let z = Dbm.create dim in
    Dbm.set_init z;
    (try
      for i = 0 to dim - 1 do
mcolange's avatar
mcolange committed
468 469
        Dbm.constrain z (i, 0, (0, Udbml.Basic_types.DBM_WEAK));
        Dbm.constrain z (0, i, (0, Udbml.Basic_types.DBM_WEAK));
mcolange's avatar
mcolange committed
470
      done;
mcolange's avatar
mcolange committed
471 472 473 474 475 476 477 478
      let lz = BDbm.Fed.to_dbm (Dbm.up z) in
      match lz with
      | [upz] ->
          let inv = (invariant_of_discrete_state ta ta.init) in
          Dbm.intersect upz inv;
          assert(not (Dbm.is_empty upz));
          (ta.init, upz)
      | _ -> failwith "cannot happen"
mcolange's avatar
mcolange committed
479
    with _ as e -> raise e
mcolange's avatar
mcolange committed
480
    )
mcolange's avatar
mcolange committed
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    
  let transitions_from ta state = 
    let committed = is_committed state in
    let transq = Queue.create () in
    (* Queue of synchronizing edges *)
    let rchan = Queue.create () in
    let schan = Queue.create () in
    let nproc = Array.length ta.procs in
    for i = 0 to nproc - 1 do
      let loc = state.stateLocs.(i) in
      let add_single = not committed || loc.locCommitted in
      List.iter
        (fun edge ->
          if (eval_disc_guard ta state edge.edgeDiscGuard) then
            (match edge.edgeSync with
              | Some (SendChan(c)) ->
                  Queue.add (c, edge) schan
              | Some (RecvChan(c)) ->
                  Queue.add (c, edge) rchan
              | None ->
                  if (add_single) then
                    Queue.add (InternalTrans (state, edge)) transq
            )
        ) loc.locEdges
    done;
    Queue.iter
      (fun (rname, redge) ->
        Queue.iter
          (fun (sname, sedge) ->
            (* Sync if same channels are used by different processes *)
            if (rname = sname && redge.edgeProc <> sedge.edgeProc) then (
              (* and if state not committed or one of the participating states is *)
              let sloc = source_location_of_edge ta sedge in
              let rloc = source_location_of_edge ta redge in
              if (not committed || sloc.locCommitted || rloc.locCommitted) then
                Queue.add (SyncTrans (state, redge, sedge)) transq
            )
          ) schan
      ) rchan;
    Queue.fold (fun l tr -> tr :: l) [] transq

  let transition_fields ta = function
    | InternalTrans(state, e) ->
        let state' = _copy_state state in
        _apply_edge ta state e state';
        (state,
         _guard_to_dbm ta state.stateVars e.edgeGuard,
         e.edgeReset,
         state')
    | SyncTrans(state, e1, e2) ->
        let state' = _copy_state state in
        _apply_edge ta state e1 state';       
        _apply_edge ta state e2 state';
        let g1 = _guard_to_dbm ta state.stateVars e1.edgeGuard in
        let g2 = _guard_to_dbm ta state.stateVars e2.edgeGuard in
        Dbm.intersect g1 g2;
        (state, g1, (ClockSet.union e1.edgeReset e2.edgeReset), state')

  let guard_of_transition ta tr = 
    let to_succinct = function
      |InternalTrans(_,e) -> Suc_InternalTrans(e)
      |SyncTrans(_,e1,e2) -> Suc_SyncTrans(e1,e2)
    in
    let str = to_succinct tr in
    try 
      Hashtbl.find ta.guards_tbl str
    with Not_found ->
      (match tr with
       | InternalTrans(state,e) ->
         let g =_guard_to_dbm ta state.stateVars e.edgeGuard in
         Hashtbl.add ta.guards_tbl str g;
         g
       | SyncTrans(state,e1,e2) -> 
         let g1 = _guard_to_dbm ta state.stateVars e1.edgeGuard in
         let g2 = _guard_to_dbm ta state.stateVars e2.edgeGuard in
         Dbm.intersect g1 g2;
         Hashtbl.add ta.guards_tbl str g1;
         g1
      ) 
       |_ as e -> raise e

  let is_urgent_or_committed ta state =
    Array.exists (fun loc -> loc.locCommitted || loc.locUrgent) state.stateLocs

  let is_target ta state =
    let rec eval = function
      | AtomicQuery(s) -> 
        Array.exists (fun loc -> loc.locName = s) state.stateLocs
      | OrQuery(p1,p2) -> (eval p1) || (eval p2)
      | AndQuery(p1,p2) -> (eval p1) && (eval p2)
      | NotQuery(p) -> not (eval p)
    in
    match ta.query with
      EmptyQuery -> true
    | ReachQuery(pq) -> eval pq

  let lu_bounds ta state lbounds ubounds =
    Array.iteri (fun i _ -> 
        lbounds.(i) <- -Dbm.infty;
        ubounds.(i) <- -Dbm.infty
      ) lbounds;
    lbounds.(0) <- 0;
    ubounds.(0) <- 0;
    let nprocs = Array.length state.stateLocs in
    let nclocks = VarContext.size ta.clocks in 
    for iproc = 0 to nprocs - 1 do
      let iloc = state.stateLocs.(iproc).locId in
      for cl = 0 to nclocks - 1 do
589 590 591 592 593
        let mymax (x:int) (y:int) = 
          if (x < y) then y else x
        in
        lbounds.(cl) <- mymax lbounds.(cl) ta.lowerLU.(iproc).(iloc).(cl);
        ubounds.(cl) <- mymax ubounds.(cl) ta.upperLU.(iproc).(iloc).(cl);
mcolange's avatar
mcolange committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
      done;
    done

  (** print functions *)
  let print_discrete_state chan ta state =
    fprintf chan "%s\n" (string_of_state ta state)
  
  let print_transition chan ta trans = 
    fprintf chan "%s\n" (string_of_transition ta trans)

  let print_timed_automaton chan ta =
    fprintf chan "Timed automaton with %d clocks and %d processes\n"
      (VarContext.size ta.clocks) (Array.length ta.procs);
    Array.iter (fun proc -> fprintf chan "%s\n-----\n" (string_of_process ta proc)) ta.procs
 
  let print_extended_state chan ta (state,dbm) =
    fprintf chan "%s " (string_of_state ta state);
    fprintf chan "%s " (Dbm.to_string dbm)

  (********** LOADING FUNCTIONS **********)
  
  (** This is pretty much a direct translation from LocalLUNormalizer class of Verifix.
      @return a pair (lower,upper) corresponding to L and U values, three-dimensional arrays indexed by  process, location, and clock
      *)
  let _make_lu_table ta = 
    let nclocks = VarContext.size ta.clocks in
    let maketable () = 
      Array.map (fun proc -> 
          Array.map (fun loc ->
              Array.init nclocks (fun c -> -Dbm.infty)
            ) proc.procLocations
        ) ta.procs
    in
    let upper = maketable () in
    let lower = maketable () in
    let process iproc iloc g = 
      let aux = function
        | GuardLeq(Clock(l),Constant(r)) ->
          upper.(iproc).(iloc).(l) <- max upper.(iproc).(iloc).(l) r
        | GuardLess(Clock(l),Constant(r)) ->
          upper.(iproc).(iloc).(l) <- max upper.(iproc).(iloc).(l) r
        | GuardEqual(Clock(l),Constant(r)) ->
          upper.(iproc).(iloc).(l) <- max upper.(iproc).(iloc).(l) r;
          lower.(iproc).(iloc).(l) <- max lower.(iproc).(iloc).(l) r
        | GuardGreater(Clock(l),Constant(r)) ->
          lower.(iproc).(iloc).(l) <- max lower.(iproc).(iloc).(l) r
        | GuardGeq(Clock(l),Constant(r)) ->
          lower.(iproc).(iloc).(l) <- max lower.(iproc).(iloc).(l) r
        | _ -> failwith "Cannot compute lu bounds: Guards not in normal form."
      in
      List.iter aux g
    in
    let close bounds iproc proc = 
      let stable = ref false in
      while (not !stable) do
        stable := true;
        Array.iter (fun loc -> 
            List.iter (fun edge ->
                let source = edge.edgeSource in
                let target = edge.edgeTarget in
                let sourceBnd = bounds.(iproc).(source) in
                let targetBnd = bounds.(iproc).(target) in
mcolange's avatar
mcolange committed
656
                for j = 1 to nclocks - 1 do
mcolange's avatar
mcolange committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
                  if (not (ClockSet.mem j edge.edgeReset)) then (
                    if (targetBnd.(j) > sourceBnd.(j) ) then(
                      sourceBnd.(j) <- targetBnd.(j);
                      stable := false
                    )                                     
                  )
                done
              ) loc.locEdges
          ) proc.procLocations
      done;
    in
    Array.iteri (fun iproc proc -> 
        (* Initialize *)
        Array.iteri (fun iloc loc ->
            List.iter (fun edge ->
                process iproc iloc edge.edgeGuard) 
              loc.locEdges;
            process iproc iloc loc.locInvar
          ) proc.procLocations;
        (* Close *)
        close lower iproc proc;
        close upper iproc proc;
      ) ta.procs;
    (lower,upper)


  (** Constructs a timed_automaton. The constructor function is parameterized
   *  by guard_of_transition and invariant_of_discrete_state so that we can 
   *  instantiate it for other kinds of automata (enlarged automata below)
   *  in modules extending the current one.
       @param sys parsed system (Uta.system)
       @param scale scales all constants by scale
       @param enlarge enlarges all constants by enlarge (after having scaled)
       @param (guard_of_transition,invariant_of_discrete_state)
      *)
  let make_ta (guard_of_transition, invariant_of_discrete_state) sys scale enlarge = 
    let templates = sys.sysTemplates in 
    (** Variable and clock contexts have initially keys of type (p,name)
     * where p is process option (None for global variables),
     * and name the name of the variable. *)
    let varcont = VarContext.create () in
    let var_init_values = Hashtbl.create 10 in
    let const_values = Hashtbl.create 10 in
    let clockcont = VarContext.create () in
    VarContext.add clockcont (None,"0");
    let constcont = VarContext.create () in
    (* Function to register global clocks and variables *)
    let register_vars tmp (clocks,vars) = 
      List.iter (fun cl -> 
          try VarContext.add clockcont (tmp,cl) 
          with Var_already_defined -> 
            eprintf "Variable %s is already defined\n" cl;
            failwith "Error"
             | _ as e ->
               raise e
        ) clocks;
      List.iter (fun var -> 
          try 
            match var with
              Var(id,v) ->
              VarContext.add varcont (tmp,id);
              let index = VarContext.index_of_var varcont (tmp,id) in
              Hashtbl.add var_init_values index v
            | ConstVar(id,v) ->
              VarContext.add constcont (tmp,id);
              let index = VarContext.index_of_var constcont (tmp,id) in                     
              Hashtbl.add const_values index v
          with Var_already_defined ->
            eprintf "Variable %s is already defined\n" (name_of_var var);
            failwith "Error"
             | _ as e ->
               raise e
        ) vars
    in
    (* Register variables: first global ones then local ones *)
    register_vars None (sys.sysClocks, sys.sysVars);
    List.iter (fun tmp -> register_vars (Some tmp) (tmp.tempClocks, tmp.tempVars) ) templates;
    let nvars = (VarContext.size varcont) in
    let is_clock tmp var = 
      if (VarContext.mem clockcont (Some tmp,var)) then
        true
      else if (VarContext.mem clockcont (None,var)) then
        true
      else 
        false
    in
    let get_clock_id tmp var = 
      if (VarContext.mem clockcont (Some tmp,var) ) then
        VarContext.index_of_var clockcont (Some tmp,var)
      else
        VarContext.index_of_var clockcont (None,var)
    in
    (* Convert the given Uta.expression inside the template tmp to the local exp type
       by replacing variable names by their integer identifiers. Also instantiates constants
       and partially evaluates the arithmetic operations  *)
    let convert_exp tmp exp = 
      let rec eval = function
        | Uta.Constant(c) -> Constant(c)
        | Uta.Variable(name) -> 
          (* We first check if the variable is a constant *)
          if (VarContext.mem constcont (Some tmp,name) ) then
            (* Is it a local constant? *)
            let varid = VarContext.index_of_var constcont (Some tmp,name) in
            Constant(Hashtbl.find const_values varid)
          else if (VarContext.mem constcont (None,name)) then
            (* Is it a global constant ? *)
            let varid = VarContext.index_of_var constcont (None,name) in
            Constant(Hashtbl.find const_values varid)
          else if (VarContext.mem varcont (Some tmp,name)) then
            (* Is it a local variable? *)
            let varid = VarContext.index_of_var varcont (Some tmp,name) in
            Variable(varid)
          else if (VarContext.mem varcont (None,name)) then
            (* Is it a global variable? *)
            let varid = VarContext.index_of_var varcont (None,name) in
            Variable(varid)
          else if (VarContext.mem clockcont (Some tmp, name) ) then
            (* Local clock *)
            let varid = VarContext.index_of_var clockcont (Some tmp,name) in
            Clock(varid)            
          else if (VarContext.mem clockcont (None, name) ) then
            (* Global clock *)
            let varid = VarContext.index_of_var clockcont (None,name) in
            Clock(varid)    
          else (
            eprintf "Printing final VarContext\n";
            VarContext.iter 
              (fun (t,name) ind ->
                 let scope = match t with None -> "None" | Some tmp -> tmp.tempName
                 in
                 eprintf "\t%d <%s> : %s\n" ind  name scope
              ) varcont;
            printf "%b\n" (VarContext.mem varcont (Some tmp, name));
            failwith (sprintf "Undefined variable <%s>" name)
          )
        | Uta.Sum(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 + v2)
           | _ -> Sum(ne1,ne2)
          )
        | Uta.Subtraction(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 - v2)
           | _ -> Substraction(ne1,ne2)
          )
        | Uta.Product(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 * v2)
           | _ -> Product(ne1,ne2)
          )
        | Uta.Division(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 / v2)
           | _ -> Division(ne1,ne2)
          )
      in
      eval exp
    in
    let convert_guard tmp g  =
      let convert_atomic_guard = function
        | Uta.GuardLeq(e1,e2) -> GuardLeq(convert_exp tmp e1, convert_exp tmp e2)
        | Uta.GuardLess(e1,e2) -> GuardLess(convert_exp tmp e1, convert_exp tmp e2)
        | Uta.GuardGeq(e1,e2) -> GuardGeq(convert_exp tmp e1, convert_exp tmp e2)
        | Uta.GuardGreater(e1,e2) -> GuardGreater(convert_exp tmp e1, convert_exp tmp e2)
        | Uta.GuardEqual(e1,e2) -> GuardEqual(convert_exp tmp e1, convert_exp tmp e2)
      in
      (* Make sure clock guards have the form Guard*(Clock(cl),Constant(r)) *)
      let normalize_atomic_guard = function
        | GuardLeq(_ as k,Clock(cl)) ->
          GuardGeq(Clock(cl),k)
        | GuardLess(_ as k,Clock(cl)) ->
          GuardGreater(Clock(cl),k)
        | GuardGeq(_ as k,Clock(cl)) ->
          GuardLeq(Clock(cl),k)
        | GuardGreater(_ as k,Clock(cl)) ->
          GuardLess(Clock(cl),k)
        | GuardEqual(_ as k,Clock(cl)) ->
          GuardEqual(Clock(cl),k)
        | e -> e
      in
      let aux ag = 
        normalize_atomic_guard (convert_atomic_guard ag)
      in
      let g = List.map aux g in
      g
    in
    (** Instantiate constants inside updates *)
    let convert_update tmp up = 
      List.map (fun (var,exp) -> 
          let varid = 
            if (VarContext.mem varcont (Some tmp,var)) then
              VarContext.index_of_var varcont (Some tmp,var)
            else                   
              VarContext.index_of_var varcont (None,var) 
          in
          (varid,convert_exp tmp exp)
        ) up
    in
    (** Get discrete guard from mixed guard *)
    let filter_disc_guard tmp g = 
      let filt_ag ag = 
        List.for_all (fun name -> not (is_clock tmp name)) (vars_of_atomic_guard ag)
      in
      List.filter filt_ag g
    in
    (** Get clock guard from mixed guard *)
    (* TODO Also check that there is no variable *)
    let filter_clock_guard tmp g = 
      let filt_ag ag = 
        List.exists (fun name -> (is_clock tmp name)) (vars_of_atomic_guard ag)
      in
      List.filter filt_ag g
    in
    (** Make clock reset set *)
    let clock_update tmp up =
      let reset = 
        (List.map (fun (name,_) -> get_clock_id tmp name)
           (List.filter (fun (var,_) -> is_clock tmp var) up))
        |>
        (List.fold_left (fun set cl -> ClockSet.add cl set) ClockSet.empty)
      in
      reset
    in
    (** scale all constants by scale and enlarge by enlarge*)
    let scale_and_enlarge_cguard g =
      let rec eval = function
        | Sum(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 + v2)
           | _ -> Sum(ne1,ne2)
          )
        | Substraction(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 - v2)
           | _ -> Substraction(ne1,ne2)
          )
        | Product(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 * v2)
           | _ -> Product(ne1,ne2)
          )
        | Division(e1,e2)  ->
          let ne1 = eval e1 in
          let ne2 = eval e2 in
          (match (ne1,ne2) with
             Constant(v1), Constant(v2) -> Constant(v1 / v2)
           | _ -> Division(ne1,ne2)
          )
        | e -> e
      in
      let s = Constant(scale) in
      let d = Constant(enlarge) in
      let scale_and_enlarge = function
        | GuardLeq(Clock(_) as e1,e2) -> [GuardLeq(e1,eval (Sum(Product(e2,s),d)))]
        | GuardLess(Clock(_) as e1,e2) -> [GuardLess(e1,eval (Sum(Product(e2,s),d)))]
        | GuardGreater(Clock(_) as e1,e2) -> [GuardGreater(e1,eval (Substraction(Product(e2,s),d)))]
        | GuardGeq(Clock(_) as e1,e2) -> [GuardGeq(e1,eval (Substraction(Product(e2,s),d)))]
        | GuardEqual(Clock(_) as e1,e2) ->
          let se2 = Product(e2,s) in
          [GuardGeq(e1,eval (Substraction(se2,d)));
           GuardLeq(e1,eval (Sum(se2,d)))
          ]
        | other ->
          failwith "Cannot enlarge non-normalized clock guard"
      in
      List.fold_left (fun acc ag -> (scale_and_enlarge ag)@acc) [] g
    in
    (* Convert the (template,string) VarContext.t  to string VarContext.t
       by prepending the process names to variables and clocks. 
       We will just extract these elements from the hash tables, along with their indices,
       so as to reinsert them in the same order in the new VarContext.
       These contexts are only for pretty printing and have no role in simulation
    *)
    let get_vc_elements vc = 
      Hashtbl.fold 
        (fun (tmp,name) index acc ->
           let prefix = match tmp with
               None -> ""
             | Some tmp -> tmp.tempName ^"."
           in
           let name = sprintf "%s%s" prefix name in
           (index,name) :: acc
        ) (VarContext.get_var2index vc) [] 
    in    
    let clist = List.sort compare (get_vc_elements clockcont) in
    let vlist = List.sort compare (get_vc_elements varcont) in
    let clocks = VarContext.create () in
    let vars = VarContext.create () in
    List.iter (fun (_,name) -> VarContext.add clocks name) clist;
    List.iter (fun (_,name) -> VarContext.add vars name) vlist;
    let disc_update tmp up =
      List.filter (fun (var,_) -> not (is_clock tmp var)) up
    in
    (** Now we start making the timed automaton *)
    let make_proc id tmp = 
      (* Assign integer identifiers to locations by their locId's.
         We assign id i to the i-th location in the list (see below)
      *)
      let locids = Hashtbl.create 50 in
      List.iteri (fun i loc -> Hashtbl.add locids loc.Uta.locId i) tmp.tempLocations;
      let make_edge edge = 
        {
          edgeSource = Hashtbl.find locids edge.Uta.edgeSource;
          edgeTarget = Hashtbl.find locids edge.Uta.edgeTarget;
          edgeDiscGuard = convert_guard tmp (filter_disc_guard tmp edge.Uta.edgeGuard);
          edgeGuard = scale_and_enlarge_cguard
              (convert_guard tmp (filter_clock_guard tmp edge.Uta.edgeGuard));
          edgeReset = clock_update tmp edge.edgeUpdates;
          edgeDiscUpdate = convert_update tmp (disc_update tmp edge.edgeUpdates);
          edgeSync = edge.Uta.edgeSync;
          edgeProc = None;
          edgeControllable = true;
        }
      in
      let make_loc loc = 
        let edges = 
          let e = List.filter
              (fun edge -> edge.Uta.edgeSource = loc.Uta.locId) tmp.tempEdges in
          List.map make_edge e                   
        in
        {
          locId = Hashtbl.find locids loc.Uta.locId;
          locName = if (loc.Uta.locName <> "") then loc.Uta.locName else loc.Uta.locId;
          locCommitted = loc.Uta.locCommitted;
          locUrgent = loc.Uta.locUrgent;
          locInvar = scale_and_enlarge_cguard (convert_guard tmp loc.Uta.locInvar);
          locEdges = List.rev edges;
          locProc = None;
        }
      in
      let locslist = List.map make_loc tmp.tempLocations in
      let locs = Array.of_list locslist in
      {
        procName = tmp.Uta.tempName;
        procId = id;
        procLocations = locs;
        procInitLoc = Hashtbl.find locids tmp.tempInitialLocation.locId;
      } 
    in
    let procs = Array.of_list (List.mapi make_proc templates) in
    (* Fill in the edgeProc and locProc fields in all locations and edges *)
    Array.iter (fun proc -> 
        Array.iter (fun loc -> 
            loc.locName <- proc.procName ^ "." ^ loc.locName;
            loc.locProc <- Some proc;
            loc.locEdges |>
            List.iter (fun edge -> edge.edgeProc <- Some proc)
          ) proc.procLocations
      )
      procs;
    let initLocs = Array.map (fun proc -> proc.procLocations.(proc.procInitLoc)) procs in
    let initVars = Array.create nvars 0 in
    for i = 0 to nvars-1 do
      initVars.(i) <- Hashtbl.find var_init_values i;
    done;
    let ta = {
      procs = procs;
      clocks = clocks;
      vars = vars;
      init = {stateLocs = initLocs; stateVars = initVars};
      query = EmptyQuery;
      lowerLU = [||];
      upperLU = [||];
      guards_tbl = Hashtbl.create 1024;
1035
      invars_tbl = LocHashtbl.create 1024
mcolange's avatar
mcolange committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    }
    in 
    let (lower,upper) = _make_lu_table ta in
    ta.lowerLU <- lower;
    ta.upperLU <- upper;
    (** Check restrictions:
     * 1) No discrete variables in clock guards
     *    ( This restriction could actually be lifted
     *      by redefining the hash tables as a function
     *      from state = stateLocs * stateVars)
     *)
    let check_ta ta =
      let check_guard_no_discrete g = 
        let aux = function 
          |Variable(_) -> raise Found
          | _ -> ()
        in
        let atomic = function       
          | GuardLess(e1,e2) -> aux e1; aux e2
          | GuardLeq(e1,e2) -> aux e1; aux e2
          | GuardGeq(e1,e2) -> aux e1; aux e2
          | GuardGreater(e1,e2) -> aux e1; aux e2
          | GuardEqual(e1,e2) -> aux e1; aux e2
        in
        List.iter atomic g
      in
      (try
         ta.procs |> Array.iter (fun proc ->
             proc.procLocations |> 
             Array.iter (fun loc ->
                 check_guard_no_discrete loc.locInvar;
                 loc.locEdges |> List.iter (fun edge -> check_guard_no_discrete edge.edgeGuard)
               )
           ) 
       with Found -> failwith "We do not support discrete variables in clock guards"
          | _ as e -> raise e
      )
    in
    check_ta ta;
    ta


  let from_file tafile qfile ?scale:(scale=1) ?enlarge:(enlarge=0) () = 
    let pta  = UtaReader.nta_from_file (tafile) in
    let query = UtaReader.query_from_file qfile in
    let ta = make_ta (guard_of_transition, invariant_of_discrete_state) pta scale enlarge in
    ta.query <- query;
    ta
  
end