store.ml 40.3 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
(* exported *)
149
let (create : Exp.var list -> t) =
150
  fun var_l ->
151
    let (add_one_var : range_store -> Exp.var -> range_store) =
152
      fun tbl var ->
153 154 155

        let to_num_opt = function 
          | Some(Numer(Ival(min))) -> Some (Ival(min))
156
          | Some(Numer(Uminus(Ival(min)))) -> Some (Ival(Num.minus_num min))
157 158 159 160 161 162 163 164 165
          | Some(Numer(Fval(min))) -> Some (Fval(min))
          | Some(Numer(Uminus(Fval(min)))) -> Some (Fval(-.min))
          | None -> None
          | _  -> 
              output_string stderr "Only immediate constant are allowed in variable ranges.\n";
              flush  stderr;
              assert false
        in
          
166 167 168 169
	     let range = (
	       match (to_num_opt (Var.min var)), (to_num_opt  (Var.max var)) with
	         | Some(Ival(min)), Some(Ival(max)) ->
		          RangeI(min, max)
170

171 172
	         | None, Some(Ival(max)) ->
		          RangeI(default_min_int, max)
173

174 175
	         | Some(Ival(min)), None ->
		          RangeI(min, default_max_int)
176

177 178
	         | Some(Fval(min)), Some(Fval(max)) ->
		          RangeF(min, max)
179

180 181
	         | None, Some(Fval(max)) ->
		          RangeF(default_min_float, max)
182

183 184
	         | Some(Fval(min)), None ->
		          RangeF(min, default_max_float)
185

186 187 188 189 190 191
	         | 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
	           )
192
                
193
	         | _ -> 
194 195
                print_string ((Var.to_string var) ^ "\n");
                flush stdout;
196 197 198 199
	             assert false
	     )
	     in
	       StringMap.add (Var.name var) range tbl;    
200
    in
201
    let tbl = List.fold_left (add_one_var) StringMap.empty var_l in
202
      {
203 204 205 206
	     var = Range(tbl) ;
	     substl = [];
	     delay = [];
	     untouched = var_l
207
      }
208

209 210

(* Normalised atomic constraints *)
211
type nac =
212 213 214 215
  | NSupF   of float (** >  *)
  | NSupEqF of float (** >= *)
  | NInfF   of float (** <  *)
  | NInfEqF of float (** <= *)
216
  | NEqF    of float (** = *)
217

218 219 220
  | NSupEqI of Num.num (** >=  *)
  | NInfEqI of Num.num (** <=  *)
  | NEqI    of Num.num (** = *)
221

222

223 224 225 226 227
(****************************************************************************)
(* Pretty printing   *)


let (range_to_string : range -> string) =
228 229
  fun range ->
    match range with
230
    RangeI(min, max) ->
231
      ("[" ^ (Num.string_of_num min) ^ ", " ^ (Num.string_of_num max) ^ "] ")
232 233 234 235 236
  | RangeF(min, max) ->
      ("[" ^ (string_of_float min) ^ ", " ^ (string_of_float max) ^ "] ")

(* exported *)
let (to_string : t -> string) =
237
  fun s ->
238 239 240 241 242 243 244 245 246 247 248 249 250
    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"
	            )
		)
251 252
    and substl_str = 
      if s.substl = [] then "" else
253
        ("\n*** Substitutions: \n" ^ Ne.substl_to_string s.substl)
254 255
    and delay_str = 
      if s.delay = [] then "" else
256 257 258 259 260
	     ("\n*** Delayed constraints: \n" ^
           List.fold_left
	        (fun acc d -> acc ^ "\n" ^ (Constraint.ineq_to_string d))
	        ""
	        s.delay)
261 262
    in
      (var_str ^ substl_str ^ delay_str)
263
and
264
    (t'_to_string : t' -> string) =
265
  fun s ->
266
    let var_str = (
267
      "\n*** Variable ranges: \n" ^
268 269 270 271 272 273 274
        (StringMap.fold
	        (fun vn range acc ->
	           ("   " ^ vn ^ " in " ^ (range_to_string range) ^ "\n" ^ acc)
	        )
	        s.range
	        "\n"
        )
275 276 277 278 279 280
    )
    and substl_str = ("\n*** Substitutions: \n" ^ Ne.substl_to_string s.substl')
    in
      (var_str ^ substl_str)

let (print_store : t -> unit) =
281
  fun s ->
282
    Format.print_string (to_string s)
283 284 285

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

286
(*
287 288 289 290 291 292 293 294 295 296
   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
297 298
(* exported *)
exception No_polyedral_solution
299

300 301
let (switch_to_polyhedron_representation_do : int -> t -> t' * p) =
  fun verb store ->
302 303
    (* handle delayed constraints using polyhedron *)
    match store.var with
304 305
	     Unsat(_,_) ->
	       print_string ("\nZZZ Dead code reached, oups...\n") ;
306
          flush stdout;
erwan's avatar
erwan committed
307
	       raise No_polyedral_solution (* this ougth to be dead code ... *)
308
      | Range tbl ->
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
	       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 );
erwan's avatar
erwan committed
330 331
		           raise No_polyedral_solution
               )
332 333 334 335 336 337 338 339 340 341
		          )
		          poly_l;

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

343 344 345 346 347
(* tabulate the result as this translation is expensive *)
let poly_table = ref (Hashtbl.create 1)
let poly_table_size = ref 0

(* exported *)
348 349
let (switch_to_polyhedron_representation : int -> t -> t' * p) =
  fun verb store ->
350
    (Util.tabulate_result
351 352
       poly_table poly_table_size 
       100 switch_to_polyhedron_representation_do verb store)
353

354

355

356

357
(****************************************************************************)
358
(****************************************************************************)
359

360
open Poly_draw
361

362 363
let (compute_volume_do : int -> t -> float) =
  fun verb store ->
364 365
    let eps = !(Util.eps) in
    let factor = 1.0 /. eps in
366
      (*
367 368 369
	     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.
370
      *)
371
      match store.var with Unsat(_,_)  ->  0.0 | _ -> 
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
	     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
393
	
394

395
(* tabulate the result of the volume computation *)
396
let store_volume = ref (Hashtbl.create 1)
397
let store_volume_size = ref 0
398

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

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

417
let (div : int -> int -> int) =
418
  fun x y ->
419 420 421 422 423 424
    (* 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
425
    in
426
      int_of_float (floor (xf /.yf))
427

428

429
let (normalise : Constraint.ineq -> Var.name * nac ) =
430
  fun cstr ->
431
    (* Transform atomic formula into a data type that is easier to
432
       process.
433

434 435
       Fails if [cstr] contains more than one variable (in which
       case the constraint should have been delayed).
436
    *)
437
    let (get_vn_and_constant : Ne.t -> ( (* ne = ax+b*)
438 439 440 441 442
	        Value.num  (* The constant b *)
	        * Value.num  (* The coefficient of the variable a *)
	        * Var.name   (* The name of the variable x *)
	      )
	     ) =
443
      fun ne ->
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
	     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
465
    in
466
      match cstr with
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 508 509 510 511 512 513
	       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
	           )
514

515 516 517



518
let (make_subst : Var.name -> Value.num -> Ne.subst) =
519
  fun vn value ->
520
    (* returns a subst from [vn] to [value] *)
521
    match value with
522
	I _ -> ((vn, (I (Num.Int 1))), Ne.make "" value)
523 524 525 526 527 528 529 530 531 532
      | 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. *)

533
(* let (is_ineq_cstr_an_eq : Constraint.t -> t -> (t * Ne.t) option) = *)
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
(*   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 *)
576

577

578
(* exported *)
erwan's avatar
erwan committed
579 580
let rec (add_constraint : t -> Formula_to_bdd.t -> Constraint.t -> t) =
  fun store bddt cstr0 ->
581
    let cstr = Constraint.apply_substl store.substl cstr0 in
582
    let _ =
583
      if debug_store2 then (
584 585 586
	     print_string (
	       "add_constraint (" ^
	         (string_of_int 
erwan's avatar
erwan committed
587
	            (Formula_to_bdd.get_index_from_linear_constraint bddt cstr0)) ^
588 589 590
	         ") " ^
	         (Constraint.to_string cstr) ^ " \n");
	     flush stdout
591
      );
592
      if debug_store then (
593
	     print_string "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n " ;
594
	     print_string ">>>> The store before adding: " ;
595
	     print_string (Constraint.to_string cstr);
596
	     print_string (to_string  store);
597
	     flush stdout
598
      );
599
    in
600
    let eps = !(Util.eps) in
601 602
    let (var, sl, d, uvars) =
      (store.var, store.substl, store.delay, store.untouched)
603
    in
604
    let dim = Constraint.dimension cstr in
605 606
    let res =
      if
607
	     dim = 0
608
      then
609
	     ( match cstr with
erwan's avatar
erwan committed
610
	           EqZ(ne) -> add_eq_to_store store bddt ne
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
	         | 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
		          )
	     )
645
      else if
646
	     dim > 1
647
      then
648 649 650 651 652 653 654 655
	     (*
	       We could also choose not to delay those constraints and
	       switch to the polyhedron representation for the concerned
	       variables there.

	       What is the better solution really ???
	     *)
	     ( match cstr with
erwan's avatar
erwan committed
656
	           EqZ(ne) -> add_eq_to_store store bddt ne
657 658 659 660 661 662 663 664 665 666 667
	         | 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}
	     )
668
      else
669 670 671 672 673 674 675 676 677 678
	     (* dim = 1 *)
	     match store.var with
	         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
erwan's avatar
erwan committed
679
		              EqZ(ne) -> add_eq_to_store store bddt ne
680 681 682 683 684 685 686
		            | Bv _ -> assert false
		            | Ineq ineq ->
		                let (vn, nac) = normalise ineq in
			               ( match
			                   (
			                     nac,
			                     try
687
				                    (mfind vn tbl)
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
			                     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
					                          );
erwan's avatar
erwan committed
760
					                          add_constraint acc bddt (Ineq cstr)
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
				                          )
				                          { 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
					                         );
erwan's avatar
erwan committed
808
					                         add_constraint acc bddt (Ineq cstr))
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
				                         { 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
					                           );
erwan's avatar
erwan committed
857
					                           add_constraint acc bddt (Ineq cstr))
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
				                           { 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
					                         );
erwan's avatar
erwan committed
906
					                         add_constraint acc bddt (Ineq cstr))
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
				                         { 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
					                           );
erwan's avatar
erwan committed
954
					                           add_constraint acc bddt (Ineq cstr))
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
				                           { 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
					                         );
erwan's avatar
erwan committed
1003
					                         add_constraint acc bddt (Ineq cstr)
1004 1005 1006 1007 1008 1009 1010 1011
				                         )
				                         { var=Range(tbl1) ; substl=sl1 ; delay=d1 ;
				                           untouched = rm uvars vn }
				                         da
				                         
			                   | _ -> assert false
			               )
	           )
1012 1013
    in
      if debug_store then (
1014
	     print_string "\n>>>> The Store after:\n";
1015 1016 1017
	     print_string (to_string  res);
	     print_string "\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \n";
	     flush stdout
1018 1019
      );
      res
1020

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

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

1047 1048 1049
	           (*
	             if ne = "a0 + a1x1 + a2x2 + ...", then
	             - vn,coef = ("x1", a1) 
1050 1051
                (or any other indexes except the constant one !!!), 
                - and ne_rest = "a0 + a2x2 + ..."
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
	           *)
	           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 = 
1063
			               try mfind vn tbl
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
			               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
erwan's avatar
erwan committed
1096 1097
		                let storeb = add_constraint storea bddt cstr_min in
		                let storec = add_constraint storeb bddt cstr_max in
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
			               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
		               );
erwan's avatar
erwan committed
1120
		               add_constraint acc bddt (Ineq cstr))
1121 1122 1123 1124 1125 1126 1127 1128 1129
		            { 
		              var = store1.var; 
		              substl = s::(store1.substl); 
		              delay = d3 ;
		              untouched = store1.untouched 
		            }
		            waked
	           in
		          store2
1130 1131
		

1132
(*******************************************************************************)
1133
(* exported *)
1134 1135 1136
let (is_store_satisfiable : int -> t -> bool) =
  fun verb store ->
    match store.var with 
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
	     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
1148
      | _ -> true