ne.ml 12.7 KB
Newer Older
1
(*-----------------------------------------------------------------------
2
** Copyright (C) - Verimag.
3
** This file may only be copied under the terms of the GNU Library General
4
** Public License
5 6 7 8 9 10 11 12 13 14
**-----------------------------------------------------------------------
**
** File: ne.ml
** Main author: jahier@imag.fr
*)


open Value

module StringMap = struct
15
  include Map.Make(
16 17 18
    struct
      type t = string
      let compare = compare
19 20
    end
  )
21 22
end

23
let mfind = StringMap.find
24 25 26 27 28 29 30 31 32 33 34 35

(* exported *)
(** Normal expressions.

  Keys are var names, and the content is the coefficient of the
  monomial. By convention, "" maps the constant value. For instance,
  [("a" -> I(3) ; "b" -> I(-2) ; "" -> I(11))] represents the
  expression [3*a - 2*b + 11].
*)
type t = Value.num StringMap.t

type subst = (string * Value.num) * t
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
(****************************************************************************)
(* exported *)

let (to_expr: t -> Expr.t) =
  fun ne ->
    let l =
    StringMap.fold
      (fun var c acc ->
        let c = match c with I i -> Expr.Ival i | F f -> Expr.Fval f in
        if var = "" then c::acc else (Expr.Op (Expr.Prod, [c; Expr.Var var]))::acc
      )
      ne
      []
    in
    Expr.Op (Expr.Sum, l)

52 53 54 55 56 57 58 59 60
exception Choose_elt of Value.num
let (mapchoose:t -> Value.num) = 
  fun ne -> 
    (* only available since ocaml 3.12.0... *)
    (*   StringMap.choose ne *)
  try ignore (StringMap.fold (fun k a acc -> raise (Choose_elt a)) ne 0); (F 0.0) (* dummy *)
  with Choose_elt x -> x
    

61 62 63
let (is_int: t -> bool) =
  fun ne ->
    assert(ne <> StringMap.empty);
64
    match (mapchoose ne) with
65 66
      | I _ -> true
      | F _ -> false
67

68 69 70 71 72 73
(****************************************************************************)
(* exported *)
let (to_string_gen : (Value.num -> string) -> string -> t -> string) =
  fun nv_to_string plus ne ->
    let str =
      (StringMap.fold
74 75 76 77 78 79 80 81 82 83 84 85
	      (fun vn v acc ->
	         if vn = "" then
	           let v_str = nv_to_string v in
		          match v_str with
		              ""  -> "+1" ^ acc
		            | "-" -> "-1" ^ acc
		            | _ -> (v_str ^ acc)
	         else
	           (acc^plus ^ (nv_to_string v ) ^ "" ^ ((Prevar.format vn)))
	      )
	      ne
	      ""
86 87
      )
    in
88 89 90 91 92
    let str = Str.global_replace (Str.regexp "+ -") "-" str in
    let str = Str.global_replace (Str.regexp "+-") "-" str in
    let str = Str.global_replace (Str.regexp "+ +") "+" str in
    let str = Str.global_replace (Str.regexp "++") "+" str in
      str
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

(* exported *)
let (to_string : t -> string) =
  fun ne ->
    to_string_gen (num_value_to_string) " + " ne

(* exported *)
let (print : t -> unit) =
  fun ne ->
    print_string (to_string ne)

(* exported *)
let (substl_to_string : subst list -> string) =
  fun sl ->
    (List.fold_left
       (fun acc ((vn, a), ne) ->
	  (acc ^ "   " ^ (Value.num_value_to_string a) ^ "." ^ vn ^
	   " -> " ^ to_string ne ^ "\n")
       )
       ""
       sl
    )
115

116

117 118 119
(****************************************************************************)
(* exported *)
let (is_a_constant : t -> bool) =
120
  fun ne ->
121 122 123 124 125 126
    (StringMap.remove "" ne) = StringMap.empty



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

127 128 129
(* exported *)
let (opposite: t -> t) =
  fun ne ->
130
    StringMap.map (fun num -> match num with I(i) -> I(Num.minus_num i) | F(f) -> F(-.f)) ne
131

132 133 134 135

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

(* exported *)
136 137 138
let (add: t -> t -> t) =
  fun ne1 ne2 ->
    ( StringMap.fold
139
	(fun vn1 val1 acc ->
140
	   try
141
	     let val2 = mfind vn1 acc in
142 143 144 145
	     let valr = (add_num val1 val2) in
	       if ((not (num_eq_zero valr)) || (vn1 = "") )
	       then StringMap.add vn1 valr acc
	       else StringMap.remove vn1 acc
146
	   with Not_found ->
147 148 149 150 151 152 153
	     StringMap.add vn1 val1 acc
	)
	ne1
	ne2
    )

let _ = assert (
154 155 156 157 158 159
  let ne1 = StringMap.add "" (I(Num.num_of_int 1)) 
    (StringMap.add "toto" (I(Num.num_of_int 2))  StringMap.empty)
  and ne2 = StringMap.add "" (I(Num.num_of_int 2)) 
    (StringMap.add "toto" (I(Num.num_of_int (-3))) StringMap.empty)
  and ne_res = StringMap.add "" (I(Num.num_of_int 3)) 
    (StringMap.add "toto" (I(Num.num_of_int (-1))) StringMap.empty)
160 161 162
  in
  let ne_cal = add ne1 ne2 in

163
    ((mfind "toto" ne_res) = (mfind "toto" ne_cal))
164
    &&
165
    ((mfind "" ne_res) = (mfind "" ne_cal))
166
)
167

168 169 170 171
(****************************************************************************)
let (diff: t -> t -> t) =
  fun ne1 ne2 ->
    ( StringMap.fold
172
	(fun vn2 val2 acc ->
173
	   try
174
	     let val1 = mfind vn2 acc in
175 176 177 178
	     let valr = (diff_num val1 val2) in
	       if (not (num_eq_zero valr) || vn2 = "" )
	       then StringMap.add vn2 valr acc
	       else StringMap.remove vn2 acc
179 180
	   with Not_found ->
	     let minus_val2 =
181
	       match val2 with
182
		   I(i) -> I(Num.minus_num i)
183 184 185 186 187 188 189 190 191
		 | F(f) -> F(-. f)
	     in
	       StringMap.add vn2 minus_val2 acc
	)
	ne2
	ne1
    )

let _ = assert (
192 193 194 195 196 197 198 199
  let ne1 = StringMap.add "" (I(Num.num_of_int 1)) 
    (StringMap.add "toto" (I(Num.num_of_int 2)) StringMap.empty)
  and ne2 = StringMap.add "" (I(Num.num_of_int 2)) 
    (StringMap.add "titi" (I(Num.num_of_int 3))
				   (StringMap.add "toto" (I(Num.num_of_int 3)) StringMap.empty))
  and ne_res = StringMap.add "" (I(Num.num_of_int (-1))) 
    (StringMap.add "toto" (I(Num.num_of_int (-1)))
				       (StringMap.add "titi" (I(Num.num_of_int 3)) StringMap.empty))
200
  in
201
  let ne_cal = diff ne1 ne2
202
  in
203
    ((mfind "toto" ne_res) = (mfind "toto" ne_cal))
204
    &&
205
    ((mfind "" ne_res) = (mfind "" ne_cal))
206 207 208 209 210 211 212
)

(****************************************************************************)
let (mult: t -> t -> t) =
  fun ne1 ne2 ->
    if is_a_constant ne1
    then
213 214 215 216 217 218 219 220 221 222 223
      let coeff = mfind "" ne1 in
	   if num_eq_zero coeff
	   then ne1
	   else
	     ( StringMap.fold
	         (fun vn value acc ->
		        StringMap.add vn (mult_num coeff value) acc
	         )
	         ne2
	         StringMap.empty
	     )
224 225
    else if is_a_constant ne2
    then
226 227 228 229 230 231 232 233 234 235 236
      let coeff = mfind "" ne2 in
	   if num_eq_zero coeff
	   then ne2
	   else
	     ( StringMap.fold
	         (fun vn value acc ->
		        StringMap.add vn (mult_num coeff value) acc
	         )
	         ne1
	         StringMap.empty
	     )
237
    else
238
      let ne_str = "("^(to_string ne1) ^ ") x (" ^ (to_string ne2) ^ ")" in
239 240 241
      print_string ("\n*** Cannot solve non-linear constraints: "^ne_str^"\n");
      flush stdout;
      exit 2
242 243

let _ = assert (
244 245 246
  let ne1 = StringMap.add "" (I(Num.num_of_int 1)) 
    (StringMap.add "toto" (I(Num.num_of_int 2)) StringMap.empty) in
  let ne2 = StringMap.add "" (I(Num.num_of_int 2)) StringMap.empty in
247

248
  let ne_res = 
249 250
    StringMap.add "" (I(Num.num_of_int 2))
      (StringMap.add "toto" (I(Num.num_of_int 4)) StringMap.empty) 
251
  in
252 253
  let ne_cal = mult ne1 ne2 in

254
    ((mfind "toto" ne_res) = (mfind "toto" ne_cal))
255
    &&
256
    ((mfind "" ne_res) = (mfind "" ne_cal))
257 258 259
)

(****************************************************************************)
260
let (modulo: t -> t -> t) =
261
  fun ne1 ne2 ->
262
    if
263
      is_a_constant ne1 && is_a_constant ne2 
264
    then
265 266 267 268
      (* dead code ? (simplified before) *)
      let c1 = mfind "" ne1 in
      let c2 = mfind "" ne2 in
      StringMap.add "" (Value.modulo_num c1 c2) StringMap.empty
269
    else
270
      failwith "*** arguments of 'mod' should be known. \n"
271 272 273
	(* indeed, x mod y <=> 0 <= x < y and x = k * y  where is a 
	   (uncontrollable) local variable*)

274 275

(****************************************************************************)
276 277
let (div: t -> t -> t) =
  fun ne1 ne2 ->
278
    if
279
      is_a_constant ne1 && is_a_constant ne2
280
    then
281 282 283 284
      (* dead code ? (simplified before) *)
      let c1 = mfind "" ne1 in
      let c2 = mfind "" ne2 in
      StringMap.add "" (Value.div_num c1 c2) StringMap.empty
285
    else
286
      failwith ("*** arguments of 'div' should be known \n")
287

288 289
let (quot: t -> t -> t) = div
      
290 291 292 293
(****************************************************************************)

(* exported *)
let (fold : (string -> Value.num -> 'acc -> 'acc) -> t -> 'acc -> 'acc) =
294
  fun f ne acc0 ->
295 296 297 298
    StringMap.fold f ne acc0

(* exported *)
let (make : string -> Value.num -> t) =
299
  fun vn nval ->
300 301 302
    (StringMap.add vn nval StringMap.empty)

(* exported *)	
303
let (find : string -> t -> Value.num option) =
304
  fun vn ne ->
305
    try Some(mfind vn ne)
306
    with Not_found -> None
307

308 309 310
let (find_constant : t -> Value.num option) =
  find ""

311 312 313 314 315
(****************************************************************************)


(* exported *)
let (neg_nexpr : t -> t) =
316
  fun ne ->
317
    StringMap.map (fun x -> match x with I(i) -> I(Num.minus_num i) | F(f) -> F(-.f)) ne
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
type split_res =
  | Split of string * Value.num * t
      (* i.e., for expressions over floats, or for simple integer expressions *)
  | No_solution (* e.g., "2.x + 3 = 0" have no solution for integers *)
  | Dont_know   (* e.g., "a.x + b.y = 0", for which it is difficult to 
                   find a substition for integers *)



let split_res_to_string = function 
  | Split(str,v,ne) ->
      "(" ^ str ^ ", " ^  (Value.num_value_to_string v)^ ", " ^ (to_string ne) ^ ")"  
  | No_solution  -> "no solution"
  | Dont_know  -> "???"


335
(* exported *)
336 337 338 339 340 341 342 343

let (split : t -> split_res) =
  fun ne ->
    let list_to_ne = 
      List.fold_left (fun acc (c,v) -> StringMap.add v c acc) StringMap.empty 
    in
    let divide c1 c2 = 
      match (c1,c2) with
344
        | I i1, I i2 -> Num.eq_num (Num.mod_num i2 i1) (Num.Int 0)
345 346
        | _ ,_ -> true
    in
347
    let cl =  (StringMap.fold (fun v c acc -> (c,v)::acc) ne []) in
348 349 350 351
    let res = 
      match cl with
        | []
        | [_,_] -> 
352
            print_string "The impossible occured!\n"; flush stdout;
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
            assert false (* dim > 0 *)
        | (F f_cst,"")::(F f, v)::rest 
        | (F f, v)::(F f_cst,"")::rest 
          -> (* for floats, no soucis... *)
            (* a.x+b*)
            let ne_rest = list_to_ne ((F f_cst, "")::rest) in
              Split(v, F f, ne_rest)

        (* For integers, let's be careful *)
        | (c,v)::(c0, "")::[] 
        | (c0, "")::(c,v)::[] -> 
            (* c.v = 0  =>  c = 0 *)
            let ne_rest = list_to_ne [(c0, "")] in
            if divide c c0 then Split (v, c, ne_rest) else No_solution
              
        | _ -> (
            try (* we search if one of the coef divide all the others *)
              let (c,v) = 
                List.find 
                  (fun (c,v) ->
                     v<>"" && List.for_all (fun (c',v') -> divide c c') cl
                  ) 
                  cl
              in
              let _, rest = List.partition (fun x -> x=(c,v)) cl in
              let ne_rest = list_to_ne rest in
                Split(v,c, ne_rest)
            with 
                (* if no coef divide all the other, we dont know what to do.
                   That will be handled later by polka.
                *) 
                Not_found -> Dont_know
          )
    in
        res
388 389 390

(* exported *)
let (dimension : t -> int) =
391
  fun ne ->
392
    StringMap.fold (fun vn _ cpt -> if vn = "" then cpt else cpt+1) ne 0
393 394


395
(* exported *)
396 397
let (nexpr_add : (Value.num * string) -> t -> t) =
  fun (nval, vn) ne2 ->
398
    StringMap.add vn nval ne2
399 400


401 402
(* exported *)
let (apply_subst : t -> subst -> t) =
403 404
  fun ne2 ((vn, b), ne1) ->
    if
405 406 407 408 409
      not (StringMap.mem vn ne2)
    then
      ne2
    else
      let _ = assert (not (Value.num_eq_zero b)) in
410
      let a = mfind vn ne2 in
411
      let a_on_b = Value.quot_num a b in
412 413 414 415
      let new_ne1 =
	StringMap.map
	  (fun x -> Value.mult_num x a_on_b)
	  ne1
416
      in
417 418
      let rest_ne2 = (StringMap.remove vn ne2) in
	add new_ne1 rest_ne2
419 420 421 422


(* exported *)
let (apply_substl : subst list -> t -> t) =
423 424 425
  fun sl ne ->
    (*
       Beware that operating rigth-to-left matters.
426 427 428 429 430 431 432 433 434
       Typically, sl is of the form :
       [
          N -> 1;
          N' -> N+1
       ]
       Therefore, if we apply the substitution left-to-rigth,
       a N would remain in the expression.
    *)
    List.fold_right (fun x y -> apply_subst y x) sl ne
435 436 437 438 439



(* exported *)
let (apply_simple_subst : t -> string * Value.num -> t) =
440 441
  fun  ne (vn, v) ->
    try
442
      let a = mfind vn ne in
443
      let rest = StringMap.remove vn ne in
444 445
	(
	  try
446
	    let b = mfind "" ne in
447
	      StringMap.add "" (Value.add_num b (Value.mult_num v a)) rest
448 449
	  with
	      Not_found ->
450
		StringMap.add "" (Value.mult_num v a) rest
451
	)
452
    with
453 454 455 456
	Not_found -> ne



457 458 459

(* exported *)
let (get_vars : t -> string list) =
460
  fun ne ->
461 462 463 464 465 466
    (StringMap.fold
       (fun vn _ acc -> vn::acc)
       ne
       []
    )

467 468

(* exported *)
469
let (eval : t -> Var.num_subst list -> Value.num) =
470
  fun ne s ->
471
    let acc0 = match (snd (List.hd s)) with I _ -> I (Num.num_of_int 0) | F _ ->  F 0.0 in
472
      (StringMap.fold
473 474 475 476 477
	 (fun vn v acc ->
	    if
	      vn = ""
	    then
	      Value.add_num acc v
478
	    else
479 480
	        Value.add_num acc (Value.mult_num v (List.assoc vn s))
         )
481 482 483 484
	 ne
	 acc0
      )