store.ml 34.8 KB
Newer Older
1
(*-----------------------------------------------------------------------
2
** Copyright (C) - Verimag.
3
** This file may only be copied under the terms of the CeCill
4
** Public License
5 6
**-----------------------------------------------------------------------
**
7
** File: store.ml
8
** Main author: erwan.jahier@univ-grenoble-alpes.fr
9 10
*)

11
open Exp
12
open Value
13
open Constraint
14
open Polyhedron
15 16
open Util
open List
17

18

19
let debug_store = false
20
let debug_store2 = false
21

erwan's avatar
erwan committed
22 23
(*  let debug_store = true  *)
(*  let debug_store2 = true   *)
24

25
type p = (Var.vnt list * Poly.t * (int -> string) * Constraint.ineq list) list
26

27
type range_store =  Polyhedron.range Util.StringMap.t
28

29

30

31
type t = {
32
  (**
33 34 35 36 37 38 39 40 41
    This field is used to store where each variable ranges.  It is
    set to [Unsat] when the system becomes unsatisfiable, namely,
    when the range for one of the variable becomes empty.

    Some variables are represented by Ranges (polyhedron of dimension
    one). Some others by plain Polyhedron. The idea is that, at bdd
    leaves, if it remains some delayed constraints, we switch to a
    polyhedron representation.  *)
  var : vars_domain ;
42

43
  (**
44 45 46 47 48
    This field is used to substitute a variable by an expression. This
    is to deal with equalities: when an equality is encountered,
    we can remove one dimension by putting the equality into a
    such a substitution.

49
    Then we apply it to all the other relations. the value of the
50
    substituted variable is then obtained once the other var have
51
    been drawn.
52

53
    We add an element to this list if
54
    - an equality is encountered during the drawing/bdd-traversal
55
    - whenever a variable become bounded (1) after a constraint is
56
      added to the store
57

58
    (1) i.e., when the interval is reduced to one single point
59
  *)
60
  substl : Ne.subst list;
61 62

  (**
63 64 65 66 67 68 69
    When the dimension of an atomic formula is greater than 1, we
    delay its addition to the store until an equality makes it a
    constraint of dimension 1 (i.e., it contains only 1 var). At bdd
    leaves, if this list is not empty, it means that the current
    formula cannot be solved with an interval based solver.
    In that case, we use a polyhedron solver.
  *)
70 71 72
  delay : Constraint.ineq list ;

  (** Variables that have been constrained. If a formula has not been
73
    constraint when the draw is done, we give it its default value if any.
74
  *)
75
  untouched : Exp.var list
76
}
77 78 79 80 81
and 
  vars_domain =
    Unsat of Constraint.t * t
  | Range of range_store
      
82

83
(** contains basically the same info as [t] with a few fields removed *)
84 85
type t' = {
  range : range_store ;
86
  substl' : Ne.subst list;
87
  untouched' : Exp.var list
88 89
}

90

91 92 93
let unsat_store cstr store= 
  { var = Unsat(cstr,store) ; substl = [] ; delay = [] ; untouched = [] }

94
let (rm :  Exp.var list -> Var.name -> Exp.var list) =
95
  fun varl vn ->
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    (* Removes in [varl] all the vars which names begins with [vn].

       Indeed, when a structured variable "s" is touched, then
       so do the variables "s.f1", "s.f2[1]", ... 
    *)
    let is_not_a_prefix_of vn v =
      let res = 
	let l_vn = String.length vn in
	let l = String.length v in
	  if l_vn > l then true else (String.sub v 0 l_vn) <> vn 
      in
	 res
    in
      (List.filter (fun v -> is_not_a_prefix_of vn (Var.name v)) varl)

111

112
let (remove_var_from_range_store : t' -> Exp.var -> t') =
113
  fun st var ->
114
    {
115
      range = StringMap.remove (Var.name var) st.range;
116 117 118 119
      substl' = st.substl';
      untouched' = st.untouched'
    }

120

121
let (get_untouched_var : t' -> Exp.var list) =
122
  fun st ->
123
    st.untouched'
124 125


126
(*
127 128 129
   XXX ougth to be modifiable from the outside.
   nb : if those values are too big, sim2chro crashes ....
*)
130 131 132 133
(* let default_min_float = -10000. *)
(* let default_max_float = 10000. *)
(* let default_max_int = 10000 *)
(* let default_min_int = -10000 *)
134 135
(*
   XXX What should be the default values ???
136 137
   Too big values migth break other tools (e.g., sim2chro...)
*)
138 139 140
let lucky_max_int = (max_int / 4)

let default_max_float = (float_of_int lucky_max_int)
141
(*   (float_of_int max_int) /. 2.**(float_of_int (!Util.precision + 1)) *)
142 143 144 145
let default_min_float = (-. default_max_float)
let default_max_int = (Num.Int lucky_max_int)
let default_min_int = (Num.Int (-lucky_max_int))
let zero  = Num.Int 0
146

147 148 149
let one_of_num = function
  | I _ -> I (Num.Int 1)
  | F _ -> F 1.0
150

151
(* exported *)
152
let (create : Exp.var list -> t) =
153
  fun var_l ->
154 155 156
    let (add_one_var : range_store * Ne.subst list -> Exp.var ->
         range_store * Ne.subst list) =
      fun (tbl,sl) var ->
157 158
        let to_num_opt = function 
          | Some(Numer(Ival(min))) -> Some (Ival(min))
159
          | Some(Numer(Uminus(Ival(min)))) -> Some (Ival(Num.minus_num min))
160 161 162
          | Some(Numer(Fval(min))) -> Some (Fval(min))
          | Some(Numer(Uminus(Fval(min)))) -> Some (Fval(-.min))
          | None -> None
163 164 165 166
          | _  -> output_string stderr
                    "Only immediate constant are allowed in variable ranges.\n";
            flush  stderr;
            assert false
167
        in
168
	     let range =
169
	       match (to_num_opt (Var.min var)), (to_num_opt  (Var.max var)) with
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	       | Some(Ival(min)), Some(Ival(max)) -> RangeI(min, max)
	       | None,            Some(Ival(max)) -> RangeI(default_min_int, max)
	       | Some(Ival(min)), None            -> RangeI(min, default_max_int)
	       | Some(Fval(min)), Some(Fval(max)) -> RangeF(min, max)
	       | None,            Some(Fval(max)) -> RangeF(default_min_float, max)
	       | Some(Fval(min)), None            -> RangeF(min, default_max_float)
	       | None, None -> (
		        match Var.typ var with
		          Type.IntT -> RangeI(default_min_int, default_max_int)
		        | Type.FloatT -> RangeF(default_min_float, default_max_float)
		        | _ -> assert false
	         )
	       | _ -> 
            print_string ((Var.to_string var) ^ "\n"); flush stdout;
	         assert false
185
	     in
186 187 188 189 190 191 192 193
        let subst_opt = (* sometimes, range are actually subst ! *)
          match range with
          | RangeI (n1,n2) -> if n1=n2 then Some (I n1) else None
          | RangeF (n1,n2) -> if n1=n2 then Some (F n1) else None
        in
        match subst_opt with
        | Some v -> tbl, ((Var.name var, one_of_num v), Ne.make "" v)::sl
        | None  ->  StringMap.add (Var.name var) range tbl, sl 
194
    in
195 196 197 198 199 200 201
    let tbl,sl = List.fold_left (add_one_var) (StringMap.empty,[]) var_l in
    {
      var = Range(tbl) ;
      substl = sl;
      delay = [];
      untouched = var_l
    }
202

203 204

(* Normalised atomic constraints *)
205
type nac =
206 207 208 209
  | NSupF   of float (** >  *)
  | NSupEqF of float (** >= *)
  | NInfF   of float (** <  *)
  | NInfEqF of float (** <= *)
210
  | NEqF    of float (** = *)
211

212 213 214
  | NSupEqI of Num.num (** >=  *)
  | NInfEqI of Num.num (** <=  *)
  | NEqI    of Num.num (** = *)
215

216

217 218 219 220 221
(****************************************************************************)
(* Pretty printing   *)


let (range_to_string : range -> string) =
222 223
  fun range ->
    match range with
224
    RangeI(min, max) ->
225
      ("[" ^ (Num.string_of_num min) ^ ", " ^ (Num.string_of_num max) ^ "] ")
226 227 228 229 230
  | RangeF(min, max) ->
      ("[" ^ (string_of_float min) ^ ", " ^ (string_of_float max) ^ "] ")

(* exported *)
let (to_string : t -> string) =
231
  fun s ->
232 233 234 235 236 237 238 239 240 241 242 243 244
    let var_str =
      ("\n*** Variable ranges: \n" ^
         match s.var with
	          Unsat(_,_) -> "Empty store"
	        | Range(tbl) ->
	            (StringMap.fold
	               (fun vn range acc ->
		               ("   " ^ vn ^ " in " ^ (range_to_string range) ^ "\n" ^ acc)
	               )
	               tbl
	               "\n"
	            )
		)
245 246
    and substl_str = 
      if s.substl = [] then "" else
247
        ("\n*** Substitutions: \n" ^ Ne.substl_to_string s.substl)
248 249
    and delay_str = 
      if s.delay = [] then "" else
250 251 252 253 254
	     ("\n*** Delayed constraints: \n" ^
           List.fold_left
	        (fun acc d -> acc ^ "\n" ^ (Constraint.ineq_to_string d))
	        ""
	        s.delay)
255 256
    in
      (var_str ^ substl_str ^ delay_str)
257
and
258
    (t'_to_string : t' -> string) =
259
  fun s ->
260
    let var_str = (
261
      "\n*** Variable ranges: \n" ^
262 263 264 265 266 267 268
        (StringMap.fold
	        (fun vn range acc ->
	           ("   " ^ vn ^ " in " ^ (range_to_string range) ^ "\n" ^ acc)
	        )
	        s.range
	        "\n"
        )
269 270 271 272 273 274
    )
    and substl_str = ("\n*** Substitutions: \n" ^ Ne.substl_to_string s.substl')
    in
      (var_str ^ substl_str)

let (print_store : t -> unit) =
275
  fun s ->
276
    Format.print_string (to_string s)
277 278 279

(****************************************************************************)

280
(*
281 282 283 284 285 286 287 288 289 290
   Note that we check the satisfiability of constraints over
   polyhedra at bdd leaves, which, in some circumstances, migth be
   inefficient. The point is that, if we chose to check the formula
   satisfiability during the bdd traversal, we take the risk that a
   very big polyhedron is created whereas it was not necessary (because
   of forthcoming equalities that would reduce its dimension). And
   creating polyhedron with too big (>15) dimensions simply runs
   forever, which is really bad.
*)

erwan's avatar
erwan committed
291 292
(* exported *)
exception No_polyedral_solution
293

294 295
let (switch_to_polyhedron_representation_do : int -> t -> t' * p) =
  fun verb store ->
296 297
    (* handle delayed constraints using polyhedron *)
    match store.var with
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
	   Unsat(_,_) ->
	   print_string ("\nZZZ Dead code reached, oups...\n") ;
      flush stdout;
	   raise No_polyedral_solution (* this ougth to be dead code ... *)
    | Range tbl ->
	   if
	     store.delay = []
	   then
	     (
	       { range = tbl; substl' = store.substl; untouched' = store.untouched }
	       ,
	       []
	     )
	   else
	     let (tbl2, touched_vars, poly_l) =
	       (* side effect: this function also removes from [store] variables
		       that are put into the polyhedron store *)
	       Polyhedron.build_poly_list_from_delayed_cstr verb tbl store.delay
	     in
	     List.iter
		    (fun (_, poly, _, _) ->
		       if Poly.is_empty poly then (
		         if debug_store then (
		           print_string (to_string  store);
		           print_string "\n The polyhedron is empty .\n";
		           flush stdout );
		         raise No_polyedral_solution
             )
		    )
		    poly_l;

	     (
		    { range = tbl2; substl' = store.substl ;
		      untouched' = List.fold_left (rm) store.untouched touched_vars
		    }
		    ,
		    poly_l
	     )
336

337 338 339 340 341
(* tabulate the result as this translation is expensive *)
let poly_table = ref (Hashtbl.create 1)
let poly_table_size = ref 0

(* exported *)
342 343
let (switch_to_polyhedron_representation : int -> t -> t' * p) =
  fun verb store ->
344
    (Util.tabulate_result
345 346
       poly_table poly_table_size 
       100 switch_to_polyhedron_representation_do verb store)
347

348

349

350

351
(****************************************************************************)
352
(****************************************************************************)
353

354
open Poly_draw
355

356 357
let (compute_volume_do : int -> t -> float) =
  fun verb store ->
358 359
    let eps = !(Util.eps) in
    let factor = 1.0 /. eps in
360
      (*
361 362 363
	     In order to compare the number of solutions in a integer polyhedron
	     and in a float one, we multiply the volume of the float polyhedron by
	     2 ^ precision.
364
      *)
365
      match store.var with Unsat(_,_)  ->  0.0 | _ -> 
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	     let (store', poly_l) = switch_to_polyhedron_representation verb store in
	     let range_vol =
	       Util.StringMap.fold
	         (fun vn r acc ->
	            match r with
		           | RangeI(min, max) ->
		               acc *. (Num.float_of_num (Num.succ_num (Num.sub_num max min)))
		                 
		           | RangeF(min, max) ->
		               acc *.  (max -. min +. eps) *. factor
	         )
	         store'.range
	         1.0
	     in
	     let poly_vol =
	       List.fold_left
	         (fun acc (_,p,r2n,_) -> acc *. factor *. (Polyhedron.volume p r2n))
	         1.0
	         poly_l
	     in
	       range_vol *. poly_vol
387
	
388

389
(* tabulate the result of the volume computation *)
390
let store_volume = ref (Hashtbl.create 1)
391
let store_volume_size = ref 0
392

393 394
let (compute_volume : int -> t -> float) =
  fun verb store ->
395
    let volume =
396
      (Util.tabulate_result
397
	      store_volume store_volume_size 100 compute_volume_do verb store)
398 399
    in
      if debug_store then
400 401 402 403 404 405
	     (
	       print_string ( 
	         " ******* The store \n" ^
	           (to_string store) ^ " has volume " ^ (string_of_float volume) ^ "\n");
	       flush stdout;
	     );
406
      volume
407 408 409 410
		

(****************************************************************************)

411
let (div : int -> int -> int) =
412
  fun x y ->
413 414 415 416 417 418
    (* I define my own integer division as the division of Pervasives
       does not consistently rounds its result (ie, the result is
       round to the least integer if it is positive, and to the
       greatest integer if it is negative). *)
    let xf = float_of_int x
    and yf = float_of_int y
419
    in
420
      int_of_float (floor (xf /.yf))
421

422

423
let (normalise : Constraint.ineq -> Var.name * nac ) =
424
  fun cstr ->
425
    (* Transform atomic formula into a data type that is easier to
426
       process.
427

428 429
       Fails if [cstr] contains more than one variable (in which
       case the constraint should have been delayed).
430
    *)
431
    let (get_vn_and_constant : Ne.t -> ( (* ne = ax+b*)
432 433 434 435 436
	        Value.num  (* The constant b *)
	        * Value.num  (* The coefficient of the variable a *)
	        * Var.name   (* The name of the variable x *)
	      )
	     ) =
437
      fun ne ->
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	     let list = Ne.fold (fun vn num acc -> (vn,num)::acc) ne [] in
	       match list with
	           (* 0 var *)
	           [("", cst)] ->
		          ( match cst with
		                I(_) -> (cst, I(Num.Int 0) , "")
		              | F(_) -> (cst, F(0.), "")
		          )

	         (* 1 var *)
	         | [("", cst); (vn, coeff)] -> (cst, coeff, vn)
	         | [(vn, coeff); ("", cst)] -> (cst, coeff, vn)
	         | [(vn, coeff)] ->
		          ( match coeff with
		                I(_) -> (I(Num.Int 0), coeff, vn)
		              | F(_) -> (F(0.), coeff, vn)
		          )

	         (* more than 1 var *)
	         | _ ->
		          assert false
459
    in
460
      match cstr with
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 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
	       GZ(ne) -> (* coeff.x + cst > 0 *)
	         let (cst, coeff, vn) = get_vn_and_constant ne in
	           ( match (cst, coeff) with
		              (I(i_cst), I(i_coeff)) ->  
		                let i = Num.quo_num (Num.minus_num i_cst)  i_coeff in
			               if Num.gt_num i_coeff zero then (vn, NSupEqI(Num.succ_num i))
			               else
			                 if Num.eq_num (Num.mod_num i_cst i_coeff)  zero
			                 then (vn, NInfEqI(Num.pred_num i))
			                 else (vn, NInfEqI(i))

		            | (F(f_cst), F(f_coeff)) ->
		                if f_coeff > 0.
		                then (vn, NSupF(-.f_cst /. f_coeff))
		                else (vn, NInfF(-.f_cst /. f_coeff))

		            | (I(i), F(f)) ->
		                failwith ("*** Error: " ^ (Num.string_of_num i)
				                    ^ " is an integer and "
				                    ^ (string_of_float f) ^ " is a float.\n")
		            | (F(f), I(i)) ->
		                failwith ("*** Error: " ^ (Num.string_of_num i)
				                    ^ " is an integer and "
				                    ^ (string_of_float f) ^ " is a float.\n")
	           )

	     | GeqZ(ne) ->
	         let (cst, coeff, vn) = get_vn_and_constant ne in
	           ( match (cst, coeff) with
		              (I(i_cst), I(i_coeff)) ->
		                let i =  Num.quo_num (Num.minus_num i_cst)  i_coeff in
			               if Num.gt_num i_coeff  zero
			               then
			                 if Num.eq_num (Num.mod_num i_cst i_coeff)  zero
			                 then (vn, NSupEqI(i))
			                 else (vn, NSupEqI(Num.succ_num i))
			               else
			                 if Num.eq_num (Num.mod_num i_cst i_coeff) zero
			                 then (vn, NInfEqI(i))
			                 else (vn, NInfEqI(i))
		            | (F(f_cst), F(f_coeff)) ->
		                if f_coeff > 0.
		                then (vn, NSupEqF(-.f_cst /. f_coeff))
		                else (vn, NInfEqF(-.f_cst /. f_coeff))
		            | (I(_), F(_)) -> assert false
		            | (F(_), I(_)) -> assert false
	           )
508

509 510 511



512
let (make_subst : Var.name -> Value.num -> Ne.subst) =
513
  fun vn value ->
514
    (* returns a subst from [vn] to [value] *)
515
    match value with
516
	I _ -> ((vn, (I (Num.Int 1))), Ne.make "" value)
517 518 519 520 521 522 523 524 525 526
      | F _ -> ((vn, (F 1.)), Ne.make "" value)



(** if a constraint [cstr] = [GeqZ(ne)] is such that the store
  contains the constraint [eqZ(-ne)] among its delayed variables,
  then [cstr] turns out to be an equality. In that case, this
  function returns [ne] as well as the store with the delayed
  constraint [eqZ(-ne)] removed. *)

527
(* let (is_ineq_cstr_an_eq : Constraint.t -> t -> (t * Ne.t) option) = *)
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
(*   fun cstr store -> *)
(*     let ne = *)
(*       match cstr with *)
(* 	  GZ(ne) -> ne *)
(* 	| GeqZ(ne) -> ne *)
(* 	| _ -> assert false *)
(*     in *)
(*     let rec get_cstr ne d acc = *)
(*       match d with *)
(* 	  [] -> raise Not_found *)
(* 	| GZ(ne2)::dtail ->  *)
(* 	    if ne = ne2 *)
(* 	    then GZ(ne2), List.rev_append acc dtail *)
(* 	    else get_cstr ne dtail (GZ(ne2)::acc) *)
(* 	| GeqZ(ne2)::dtail -> *)
(* 	    if ne = ne2 *)
(* 	    then GeqZ(ne2), List.rev_append acc dtail *)
(* 	    else get_cstr ne dtail (GeqZ(ne2)::acc) *)
(* 	| _ -> assert false *)
(*     in *)
(*     let d2 = *)
(*       try  *)
(* 	match  cstr, (get_cstr ne d []) with *)
(* 	  | GeqZ(ne), (GZ(_),  d2) -> GZ(ne)::d2 *)
(* 	      (* Indeed, GeqZ(ne) => GZ(ne) *) *)
(* 	  | _ -> d *)
(* 	with  *)
(* 	    Not_found -> d *)
(* 	in *)
(* 	let new_d = *)
(* 	  try  *)
(* 	    if *)
(* 	      match cstr, (get_cstr (Ne.neg ne) d []) with *)
(* 		  GeqZ(ne), (GeqZ(_), d2) -> true *)
(* 		| _ -> false *)
(* 	    then *)
(* 	       *)
(* 	    else *)
(* 	       *)
(* 	  with  *)
(* 	      Not_found -> d *)
(* 	in *)
570

571

572
(* exported *)
erwan's avatar
erwan committed
573 574
let rec (add_constraint : t -> Formula_to_bdd.t -> Constraint.t -> t) =
  fun store bddt cstr0 ->
575
    let cstr = Constraint.apply_substl store.substl cstr0 in
576
    let _ =
577
      if debug_store2 then (
578 579
	     print_string (
	       "add_constraint (" ^
580 581 582 583
	       (string_of_int 
	          (Formula_to_bdd.get_index_from_linear_constraint bddt cstr0)) ^
	       ") " ^
	       (Constraint.to_string cstr) ^ " \n");
584
	     flush stdout
585
      );
586
      if debug_store then (
587
	     print_string "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n " ;
588
	     print_string ">>>> The store before adding: " ;
589
	     print_string (Constraint.to_string cstr);
590
	     print_string (to_string  store);
591
	     flush stdout
592
      );
593
    in
594
    let eps = !(Util.eps) in
595 596
    let (var, sl, d, uvars) =
      (store.var, store.substl, store.delay, store.untouched)
597
    in
598
    let dim = Constraint.dimension cstr in
599 600
    let res =
      if
601
	     dim = 0
602
      then
603
	     ( match cstr with
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
	         EqZ(ne) -> add_eq_to_store store bddt ne
	       | Bv _ -> assert false
	       | Ineq(GZ(ne)) ->
		      if
		        ( match (Ne.find "" ne) with
			         Some v -> Value.num_sup_zero v
		          | None -> false
		        )
		      then
		        store
		      else (
		        if debug_store2 then (
		          print_string ( 
		            "\nAdding constraint " ^ (Constraint.to_string cstr) ^ 
		            " leads to an empty store.\n") ;
		          flush stdout);
		        unsat_store (Ineq(GZ(ne))) store
		      )
	       | Ineq(GeqZ(ne)) ->
		      if
		        ( match (Ne.find "" ne) with
			         Some v -> Value.num_supeq_zero v
		          | None -> true
		        )
		      then
		        store
		      else (
		        if debug_store2 then (
		          print_string (
		            "\nAdding constraint " ^ (Constraint.to_string cstr) ^ 
		            " leads to an empty store.\n") ;
		          flush stdout);
		        unsat_store (Ineq(GeqZ(ne))) store
		      )
638
	     )
639
      else if
640
	     dim > 1
641
      then
642 643 644 645
  (*
We could also choose not to delay those constraints and
switch to the polyhedron representation for the concerned
variables there.
646

647 648
What is the better solution really ???
*)
649
	     ( match cstr with
650 651 652 653 654 655 656 657 658 659 660
	         EqZ(ne) -> add_eq_to_store store bddt ne
	       | Bv _ -> assert false
	       | Ineq ineq ->
		      if debug_store then (
		        let cstr_str = (Constraint.to_string cstr) in
		        print_string "\n ==> delay  " ;
		        print_string cstr_str;
		        flush stdout
		      );
		      { var=var ; substl=sl ; delay = ineq::d  ;
		        untouched = uvars}
661
	     )
662
      else
663 664
	     (* dim = 1 *)
	     match store.var with
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
	       Unsat(cstr, store) ->
	       if debug_store2 then 
		      print_string (
		        "\nAdding constraint " ^ (Constraint.to_string cstr) ^ 
		        " leads to an empty store.\n") ;
	       unsat_store cstr store
	     | Range(tbl) ->
	       ( match cstr with
		        EqZ(ne) -> add_eq_to_store store bddt ne
		      | Bv _ -> assert false
		      | Ineq ineq ->
		        let (vn, nac) = normalise ineq in
			     ( match
			         (
			           nac,
			           try
				          (mfind vn tbl)
			           with Not_found ->
				          print_string ("\n" ^ vn ^ 
					                     " not found in the table!\n");
				          StringMap.iter
				            (fun key range ->
				               print_string (
				                 "\n\t" ^ key ^ " " ^
				                 (Polyhedron.range_to_string range)
				               );
				            )
				            tbl;
				          flush stdout;
				          assert false
			         )
			       with
			         (NSupEqI(i), RangeI(min, max)) ->
				      if
				        Num.le_num i min
				      then
				        {var=Range(tbl) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn}
				      else if
				        Num.gt_num i max
				      then
				        {var=Unsat(cstr, store) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn}
				      else (* min < i <= max *)
				        let tbl1, sl1, d1, da =
				          if
				            Num.eq_num i max
				          then
				  (*
Whenever, a variable becomes bounded, we:
- add it to the list of substitutions
- remove it from the store.
- check if delayed cstr should be awaked
once this new subst has been applied
*)
				            let s = make_subst vn (I max) in
				            let d' =
					           (List.map
					              (Constraint.apply_subst_ineq s)
					              d
					           )
				            in
				            let (d_awake, d_delay) =
					           List.partition
					             (fun ineq ->
					                Constraint.dimension_ineq ineq <= 1)
					             d'
				            in
					         (StringMap.remove vn tbl,
					          s::sl,
					          d_delay,
					          d_awake)
				          else
				            (
					           StringMap.add vn (RangeI(i, max)) tbl,
					           sl,
					           d,
					           []
				            )
				        in
				        (* Applying the waked constraints *)
				        List.fold_left
				          (fun acc cstr ->
					          if debug_store2 then (
					            print_string "\n <== awake ";
					            print_string
					              (Constraint.ineq_to_string cstr);
					            flush stdout
					          );
					          add_constraint acc bddt (Ineq cstr)
				          )
				          { var=Range(tbl1) ; substl=sl1 ; delay=d1 ;
					         untouched = rm uvars vn}
				          da
			       |
			         (NInfEqI(i), RangeI(min, max)) ->
			         if
				        Num.lt_num i min
			         then
				        { var=Unsat(cstr, store) ; substl=sl ; delay=d;
				          untouched = rm uvars vn }
			         else if
				        Num.ge_num i max
			         then
				        { var=Range(tbl) ; substl=sl ; delay=d;
				          untouched = rm uvars vn  }
			         else (* min <= i < max *)
				        let tbl1, sl1, d1, da =
				          if
				            Num.eq_num i min
				          then
				            let s = make_subst vn (I min) in
				            let (d_awake, d_delay) =
				              List.partition
					             (fun ineq ->
					                Constraint.dimension_ineq ineq <= 1)
					             (List.map
					                (Constraint.apply_subst_ineq s)
					                d)
				            in
				            (StringMap.remove vn tbl,
					          s::sl, d_delay, d_awake)
				          else
				            (
				              StringMap.add vn (RangeI(min,i)) tbl, sl,
				              d,
				              []
				            )
				        in
				        (* Applying the waked constraints *)
				        List.fold_left
				          (fun acc cstr ->
					          if debug_store2 then (
					            print_string "\n <== awake ";
					            print_string (Constraint.ineq_to_string cstr);
					            flush stdout
					          );
					          add_constraint acc bddt (Ineq cstr))
				          { var=Range(tbl1) ; substl=sl1 ; delay=d1;
				            untouched = rm uvars vn  }
				          da

			       (** **)
			       |  (NSupEqF(f), RangeF(min, max)) ->
				      if
				        f <= min
				      then
				        {var=Range(tbl) ; substl=sl ; delay=d;
				         untouched = rm uvars vn  }
				      else if
				        f > max
				      then
				        {var=Unsat(cstr, store) ; substl=sl ; delay=d;
				         untouched = rm uvars vn  }
				      else (* min < f <= max *)
				        let tbl1, sl1, d1, da =
				          if
				            f = max
				          then
				            let s = make_subst vn (F max) in
				            let (d_awake, d_delay) =
					           List.partition
					             (fun ineq ->
					                Constraint.dimension_ineq ineq <= 1)
					             (List.map
					                (Constraint.apply_subst_ineq s)
					                d)
				            in
					         (StringMap.remove vn tbl,
					          s::sl, d_delay, d_awake)
				          else
				            (
					           StringMap.add vn (RangeF(f, max)) tbl,
					           sl,
					           d,
					           []
				            )
				        in
				        (* Applying the waked constraints *)
				        List.fold_left
				          (fun acc cstr ->
					          if debug_store2 then (
					            print_string "\n <== awake ";
					            print_string (Constraint.ineq_to_string cstr);
					            flush stdout
					          );
					          add_constraint acc bddt (Ineq cstr))
				          { var=Range(tbl1) ; substl=sl1 ; delay=d1;
					         untouched = rm uvars vn  }
				          da

			       |
			         (NInfEqF(f), RangeF(min, max)) ->
			         if
				        f < min
			         then
				        {var=Unsat(cstr, store) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn }
			         else if
				        f >= max
			         then
				        {var=Range(tbl) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn }
			         else (* min <= f < max *)
				        let tbl1, sl1, d1, da =
				          if
				            f = min
				          then
				            let s = make_subst vn (F min) in
				            let (d_awake, d_delay) =
				              List.partition
					             (fun ineq ->
					                Constraint.dimension_ineq ineq <= 1)
					             (List.map
					                (Constraint.apply_subst_ineq s)
					                d)
				            in
				            (StringMap.remove vn tbl,
					          s::sl, d_delay, d_awake)
				          else
				            (
				              StringMap.add vn (RangeF(min, f)) tbl,
				              sl,
				              d,
				              []
				            )
				        in
				        (* Applying the waked constraints *)
				        List.fold_left
				          (fun acc cstr ->
					          if debug_store2 then (
					            print_string "\n <== awake ";
					            print_string (Constraint.ineq_to_string cstr);
					            flush stdout
					          );
					          add_constraint acc bddt (Ineq cstr))
				          { var=Range(tbl1) ; substl=sl1 ; delay=d1;
				            untouched = rm uvars vn  }
				          da

			       |  (NSupF(f), RangeF(min, max)) ->
				      if
				        f < min
				      then
				        {var=Range(tbl) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn }
				      else if
				        f >= max
				      then
				        {var=Unsat(cstr, store) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn }
				      else (* min <= f < max *)
				        let (tbl1, sl1, d1, da) =
				          if
				            (f +. eps) = max
				          then
				            let s = make_subst vn (F max) in
				            let (d_awake, d_delay) =
					           List.partition
					             (fun ineq ->
					                Constraint.dimension_ineq ineq <= 1)
					             (List.map
					                (Constraint.apply_subst_ineq s)
					                d)
				            in
					         (StringMap.remove vn tbl,
					          s::sl, d_delay, d_awake)
				          else
				            (
					           StringMap.add vn (RangeF(f+.eps, max)) tbl,
					           sl,
					           d,
					           []
				            )
				        in
				        (* Applying the waked constraints *)
				        List.fold_left
				          (fun acc cstr ->
					          if debug_store2 then (
					            print_string "\n <== awake ";
					            print_string (Constraint.ineq_to_string cstr);
					            flush stdout
					          );
					          add_constraint acc bddt (Ineq cstr))
				          { var=Range(tbl1) ; substl=sl1 ; delay=d1 ;
					         untouched = rm uvars vn }
				          da

			       |
			         (NInfF(f), RangeF(min, max)) ->
			         if
				        f <= min
			         then
				        {var=Unsat(cstr, store) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn }
			         else if
				        f > max
			         then
				        {var=Range(tbl) ; substl=sl ; delay=d ;
				         untouched = rm uvars vn }
			         else (* min < f <= max *)
				        let tbl1, sl1, d1, da =
				          if
				            (f -. eps) = min
				          then
				            let s = make_subst vn (F min) in
				            let (d_awake, d_delay) =
				              List.partition
					             (fun ineq ->
					                Constraint.dimension_ineq ineq <= 1)
					             (List.map
					                (Constraint.apply_subst_ineq s)
					                d)
				            in
				            (StringMap.remove vn tbl,
					          s::sl, d_delay, d_awake)
				          else
				            (
				              StringMap.add vn (RangeF(min, f-.eps)) tbl,
				              sl,
				              d,
				              []
				            )
				        in
				        (* Applying the waked constraints *)
				        List.fold_left
				          (fun acc cstr ->
					          if debug_store2 then (
					            print_string "\n <== awake ";
					            print_string (Constraint.ineq_to_string cstr);
					            flush stdout
					          );
					          add_constraint acc bddt (Ineq cstr)
				          )
				          { var=Range(tbl1) ; substl=sl1 ; delay=d1 ;
				            untouched = rm uvars vn }
				          da

			       | _ -> assert false
			     )
	       )
1006
    in
1007 1008 1009 1010 1011 1012 1013
    if debug_store then (
	   print_string "\n>>>> The Store after:\n";
	   print_string (to_string  res);
	   print_string "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \n";
	   flush stdout
    );
    res
1014

erwan's avatar
erwan committed
1015 1016
and (add_eq_to_store : t -> Formula_to_bdd.t ->  Ne.t -> t) =
  fun store bddt ne ->
1017
    (** [add_eq_to_store s e] returns the store [s] with the numeric
1018
        constraint [EqZ(e)] added.
1019
    *)
1020 1021
    if debug_store2 then (
      print_string ("add_eq_to_store " ^ (Ne.to_string ne) ^ " \n");
1022
      print_string (to_string  store);
1023
      flush stdout;
1024
    );
1025
    let dim = Ne.dimension ne in
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    if
	   dim = 0
    then
	   match (Ne.find "" ne) with
	   | Some x -> if Value.num_eq_zero x then store else 
	       unsat_store (EqZ ne) store
	   | None -> store
    else
	   (* dim > 0 *)

      match Ne.split ne with 
      | Ne.No_solution -> unsat_store (EqZ ne) store
      | Ne.Dont_know -> store
      | Ne.Split(vn, coef, ne_rest) -> 
1040

1041 1042 1043
	     (*
if ne = "a0 + a1x1 + a2x2 + ...", then
- vn,coef = ("x1", a1) 
1044 1045
                (or any other indexes except the constant one !!!), 
                - and ne_rest = "a0 + a2x2 + ..."
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 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
*)
	     let coef_neg = Value.neg coef in
	     let store1 = 
	 (*
 Propagates the bounds of vn (min and max) to what 
 (-a0).vn will be substituted to. 
*)
		    match store.var with
		      Unsat(_,_) -> assert false
		    | Range(tbl) ->
		      let range_vn = 
			     try mfind vn tbl
			     with Not_found -> 
			       print_string (vn ^ " not found\n store= ");
			       print_string (to_string store);
			       assert false
		      in
		      let (vn_min, vn_max) =
			     match range_vn with
			     | RangeI(min, max) -> I min, I max
			     | RangeF(min, max) -> F min, F max
		      in
		      let (vn_min1, vn_max1) = 
			     if Value.num_supeq_zero coef_neg then
			       (Value.mult_num coef_neg vn_min,
			        Value.mult_num coef_neg vn_max)
			     else
			       (Value.mult_num coef_neg vn_max,
			        Value.mult_num coef_neg vn_min)
		      in
		      let cstr_min = Ineq (GeqZ(Ne.diff ne_rest (Ne.make "" vn_min1)))
		      and cstr_max = Ineq (GeqZ(Ne.diff (Ne.make "" vn_max1) ne_rest)) in
		      let new_store_var =
			     (* We do not need the bounds of [vn] anymore *)
			     Range(StringMap.remove vn tbl)
		      in
		      let storea =
			     {
			       var = new_store_var;
			       substl = store.substl;
			       delay = store.delay ;
			       untouched = rm store.untouched vn
			     }
		      in
		      let storeb = add_constraint storea bddt cstr_min in
		      let storec = add_constraint storeb bddt cstr_max in
			   storec
	     in

	     (* The new substitution *)
	     let s = ((vn, coef_neg), ne_rest) in

	     (*  [vn] elimination in the delayed constraints *)
	     let d = store1.delay in
	     let d2 = List.map (Constraint.apply_subst_ineq s) d in
		  (* Some delayed constraints may have been awaken by this
		     substitution (awake = become of dim 1). *)
	     let (waked, d3) = List.partition 
		      (fun cstr -> Constraint.dimension_ineq cstr <= 1) d2
	     in
	     let store2 =
		    List.fold_left
		      (fun acc cstr ->
		         if debug_store2 then (
		           print_string (
			          "\n <== awake "^ (Constraint.ineq_to_string cstr));
		           flush stdout
		         );
		         add_constraint acc bddt (Ineq cstr))
		      { 
		        var = store1.var; 
		        substl = s::(store1.substl); 
		        delay = d3 ;
		        untouched = store1.untouched 
		      }
		      waked
	     in
		  store2
1124 1125
		

1126
(*******************************************************************************)
1127
(* exported *)
1128 1129 1130
let (is_store_satisfiable : int -> t -> bool) =
  fun verb store ->
    match store.var with 
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
	     Unsat(cstr,store) -> 
	       if verb >= 2 then
	         (
	           print_string (
		          "# adding the constraint " ^ (Constraint.to_string cstr) ^
		            " led to an empty set of solution");
		        print_string (" when added to the store " ^ (to_string store));
	           print_string "\n";
	           flush stdout
	         ); 
	       false
1142
      | _ -> true