ne.ml 13.4 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: ne.ml
8
** Main author: erwan.jahier@univ-grenoble-alpes.fr
9 10 11 12 13 14
*)


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

(* 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) ->
109 110
	       (acc ^ "   " ^ (Value.num_value_to_string a) ^ "." ^ vn ^
	        " -> " ^ to_string ne ^ "\n")
111 112 113 114
       )
       ""
       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
let (div_hide: t -> t -> t) =
277
  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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
let (div: t -> t -> t) =
  fun ne1 ne2 ->
    if is_a_constant ne2
    then
      let coeff = mfind "" ne2 in
	   if num_eq_zero coeff
	   then (
        let ne_str = "("^(to_string ne1) ^ ") / (" ^ (to_string ne2) ^ ")" in
        print_string ("\n*** Cannot divide by zero: "^ne_str^"\n");
        flush stdout;
        exit 2
      )
	   else
	     ( StringMap.fold
	         (fun vn value acc ->
		        StringMap.add vn (div_num value coeff) acc
	         )
	         ne1
	         StringMap.empty
	     )
    else
      let ne_str = "("^(to_string ne1) ^ ") / (" ^ (to_string ne2) ^ ")" in
      print_string ("\n*** Cannot solve non-linear constraints: "^ne_str^"\n");
      flush stdout;
      exit 2

               
315 316
let (quot: t -> t -> t) = div
      
317 318 319 320
(****************************************************************************)

(* exported *)
let (fold : (string -> Value.num -> 'acc -> 'acc) -> t -> 'acc -> 'acc) =
321
  fun f ne acc0 ->
322 323 324 325
    StringMap.fold f ne acc0

(* exported *)
let (make : string -> Value.num -> t) =
326
  fun vn nval ->
327 328 329
    (StringMap.add vn nval StringMap.empty)

(* exported *)	
330
let (find : string -> t -> Value.num option) =
331
  fun vn ne ->
332
    try Some(mfind vn ne)
333
    with Not_found -> None
334

335 336 337
let (find_constant : t -> Value.num option) =
  find ""

338 339 340 341 342
(****************************************************************************)


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

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
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  -> "???"


362
(* exported *)
363 364 365 366 367 368 369 370

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
371
        | I i1, I i2 -> Num.eq_num (Num.mod_num i2 i1) (Num.Int 0)
372
        | _, _ -> true
373
    in
374
    let cl =  (StringMap.fold (fun v c acc -> (c,v)::acc) ne []) in
375 376 377 378
    let res = 
      match cl with
        | []
        | [_,_] -> 
379
            print_string "The impossible occured!\n"; flush stdout;
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
            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
415 416 417

(* exported *)
let (dimension : t -> int) =
418
  fun ne ->
419
    StringMap.fold (fun vn _ cpt -> if vn = "" then cpt else cpt+1) ne 0
420 421


422
(* exported *)
423 424
let (nexpr_add : (Value.num * string) -> t -> t) =
  fun (nval, vn) ne2 ->
425
    StringMap.add vn nval ne2
426 427


428 429
(* exported *)
let (apply_subst : t -> subst -> t) =
430 431
  fun ne2 ((vn, b), ne1) ->
    if
432 433 434 435 436
      not (StringMap.mem vn ne2)
    then
      ne2
    else
      let _ = assert (not (Value.num_eq_zero b)) in
437
      let a = mfind vn ne2 in
438
      let a_on_b = Value.quot_num a b in
439 440 441 442
      let new_ne1 =
	StringMap.map
	  (fun x -> Value.mult_num x a_on_b)
	  ne1
443
      in
444 445
      let rest_ne2 = (StringMap.remove vn ne2) in
	add new_ne1 rest_ne2
446 447 448 449


(* exported *)
let (apply_substl : subst list -> t -> t) =
450 451 452
  fun sl ne ->
    (*
       Beware that operating rigth-to-left matters.
453 454 455 456 457 458 459 460 461
       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
462 463 464 465 466



(* exported *)
let (apply_simple_subst : t -> string * Value.num -> t) =
467 468
  fun  ne (vn, v) ->
    try
469
      let a = mfind vn ne in
470
      let rest = StringMap.remove vn ne in
471 472
	(
	  try
473
	    let b = mfind "" ne in
474
	      StringMap.add "" (Value.add_num b (Value.mult_num v a)) rest
475 476
	  with
	      Not_found ->
477
		StringMap.add "" (Value.mult_num v a) rest
478
	)
479
    with
480 481 482 483
	Not_found -> ne



484 485 486

(* exported *)
let (get_vars : t -> string list) =
487
  fun ne ->
488 489 490 491 492 493
    (StringMap.fold
       (fun vn _ acc -> vn::acc)
       ne
       []
    )

494 495

(* exported *)
496
let (eval : t -> Var.num_subst list -> Value.num) =
497
  fun ne s ->
498
    let acc0 = match (snd (List.hd s)) with I _ -> I (Num.num_of_int 0) | F _ ->  F 0.0 in
499
      (StringMap.fold
500 501 502 503 504
	 (fun vn v acc ->
	    if
	      vn = ""
	    then
	      Value.add_num acc v
505
	    else
506 507
	        Value.add_num acc (Value.mult_num v (List.assoc vn s))
         )
508 509 510 511
	 ne
	 acc0
      )