Debian Codegraph @

plugins/micromega/simplex.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open NumCompat
12 open Q.Notations
13 open Polynomial
14 open Mutils
15
16 type ('a, 'b) sum = Inl of 'a | Inr of 'b
17
18 let debug = false
19
20 (** Exploiting profiling information *)
21
22 let profile_info = ref []
23 let nb_pivot = ref 0
24
25 type profile_info =
26 { number_of_successes : int
27 ; number_of_failures : int
28 ; success_pivots : int
29 ; failure_pivots : int
30 ; average_pivots : int
31 ; maximum_pivots : int }
32
33 let init_profile =
34 { number_of_successes = 0
35 ; number_of_failures = 0
36 ; success_pivots = 0
37 ; failure_pivots = 0
38 ; average_pivots = 0
39 ; maximum_pivots = 0 }
40
41 let get_profile_info () =
42 let update_profile
43 { number_of_successes
44 ; number_of_failures
45 ; success_pivots
46 ; failure_pivots
47 ; average_pivots
48 ; maximum_pivots } (b, i) =
49 { number_of_successes = (number_of_successes + if b then 1 else 0)
50 ; number_of_failures = (number_of_failures + if b then 0 else 1)
51 ; success_pivots = (success_pivots + if b then i else 0)
52 ; failure_pivots = (failure_pivots + if b then 0 else i)
53 ; average_pivots = average_pivots + 1 (* number of proofs *)
54 ; maximum_pivots = max maximum_pivots i }
55 in
56 let p = List.fold_left update_profile init_profile !profile_info in
57 profile_info := [];
58 { p with
59 average_pivots =
60 ( try (p.success_pivots + p.failure_pivots) / p.average_pivots
61 with Division_by_zero -> 0 ) }
62
63 (* SMT output for debugging *)
64
65 (*
66 let pp_smt_row o (k, v) =
67 Printf.fprintf o "(assert (= x%i %a))\n" k Vect.pp_smt v
68
69 let pp_smt_assert_tbl o tbl = IMap.iter (fun k v -> pp_smt_row o (k, v)) tbl
70
71 let pp_smt_goal_tbl o tbl =
72 let pp_rows o tbl =
73 IMap.iter (fun k v -> Printf.fprintf o "(= x%i %a)" k Vect.pp_smt v) tbl
74 in
75 Printf.fprintf o "(assert (not (and %a)))\n" pp_rows tbl
76
77 let pp_smt_vars s o var =
78 ISet.iter
79 (fun i ->
80 Printf.fprintf o "(declare-const x%i %s);%a\n" i s LinPoly.pp_var i)
81 (ISet.remove 0 var)
82
83 let pp_smt_goal s o tbl1 tbl2 =
84 let set_of_row vr v = ISet.add vr (Vect.variables v) in
85 let var =
86 IMap.fold (fun k v acc -> ISet.union (set_of_row k v) acc) tbl1 ISet.empty
87 in
88 Printf.fprintf o "(echo \"%s\")\n(push) %a %a %a (check-sat) (pop)\n" s
89 (pp_smt_vars "Real") var pp_smt_assert_tbl tbl1 pp_smt_goal_tbl tbl2;
90 flush stdout
91
92 let pp_smt_cut o lp c =
93 let var =
94 ISet.remove 0
95 (List.fold_left
96 (fun acc ((c, o), _) -> ISet.union (Vect.variables c) acc)
97 ISet.empty lp)
98 in
99 let pp_list o l =
100 List.iter
101 (fun ((c, _), _) -> Printf.fprintf o "(assert (>= %a 0))\n" Vect.pp_smt c)
102 l
103 in
104 Printf.fprintf o
105 "(push) \n\
106 (echo \"new cut\")\n\
107 %a %a (assert (not (>= %a 0)))\n\
108 (check-sat) (pop)\n"
109 (pp_smt_vars "Int") var pp_list lp Vect.pp_smt c
110
111 let pp_smt_sat o lp sol =
112 let var =
113 ISet.remove 0
114 (List.fold_left
115 (fun acc ((c, o), _) -> ISet.union (Vect.variables c) acc)
116 ISet.empty lp)
117 in
118 let pp_list o l =
119 List.iter
120 (fun ((c, _), _) -> Printf.fprintf o "(assert (>= %a 0))\n" Vect.pp_smt c)
121 l
122 in
123 let pp_model o v =
124 Vect.fold
125 (fun () v x ->
126 Printf.fprintf o "(assert (= x%i %a))\n" v Vect.pp_smt (Vect.cst x))
127 () v
128 in
129 Printf.fprintf o
130 "(push) \n(echo \"check base\")\n%a %a %a\n(check-sat) (pop)\n"
131 (pp_smt_vars "Real") var pp_list lp pp_model sol
132 *)
133
134 type iset = unit IMap.t
135
136 (** Mapping basic variables to their equation.
137 All variables >= than a threshold rst are restricted.*)
138 type tableau = Vect.t IMap.t
139
140 module Restricted = struct
141 type t =
142 { base : int (** All variables above [base] are restricted *)
143 ; exc : int option (** Except [exc] which is currently optimised *) }
144
145 let pp o {base; exc} =
146 Printf.fprintf o ">= %a " LinPoly.pp_var base;
147 match exc with
148 | None -> Printf.fprintf o "-"
149 | Some x -> Printf.fprintf o "-%a" LinPoly.pp_var base
150
151 let is_exception (x : var) (r : t) =
152 match r.exc with None -> false | Some x' -> x = x'
153
154 let restrict x rst =
155 if is_exception x rst then {base = rst.base; exc = None}
156 else failwith (Printf.sprintf "Cannot restrict %i" x)
157
158 let is_restricted x r0 = x >= r0.base && not (is_exception x r0)
159 let make x = {base = x; exc = None}
160 let set_exc x rst = {base = rst.base; exc = Some x}
161
162 let fold rst f m acc =
163 IMap.fold
164 (fun k v acc -> if is_exception k rst then acc else f k v acc)
165 (IMap.from rst.base m) acc
166 end
167
168 let pp_row o v = LinPoly.pp o v
169
170 let output_tableau o t =
171 IMap.iter
172 (fun k v -> Printf.fprintf o "%a = %a\n" LinPoly.pp_var k pp_row v)
173 t
174
175 let output_env o t =
176 IMap.iter (fun k v -> Printf.fprintf o "%i : %a\n" k WithProof.output v) t
177
178 let output_vars o m =
179 IMap.iter (fun k _ -> Printf.fprintf o "%a " LinPoly.pp_var k) m
180
181 (** A tableau is feasible iff for every basic restricted variable xi,
182 we have ci>=0.
183
184 When all the non-basic variables are set to 0, the value of a basic
185 variable xi is necessarily ci. If xi is restricted, it is feasible
186 if ci>=0.
187 *)
188
189 let unfeasible (rst : Restricted.t) tbl =
190 Restricted.fold rst
191 (fun k v m -> if Vect.get_cst v >=/ Q.zero then m else IMap.add k () m)
192 tbl IMap.empty
193
194 let is_feasible rst tb = IMap.is_empty (unfeasible rst tb)
195
196 (** Let a1.x1+...+an.xn be a vector of non-basic variables.
197 It is maximised if all the xi are restricted
198 and the ai are negative.
199
200 If xi>= 0 (restricted) and ai is negative,
201 the maximum for ai.xi is obtained for xi = 0
202
203 Otherwise, it is possible to make ai.xi arbitrarily big:
204 - if xi is not restricted, take +/- oo depending on the sign of ai
205 - if ai is positive, take +oo
206 *)
207
208 let is_maximised_vect rst v =
209 Vect.for_all
210 (fun xi ai ->
211 if ai >/ Q.zero then false else Restricted.is_restricted xi rst)
212 v
213
214 (** [is_maximised rst v]
215 @return None if the variable is not maximised
216 @return Some v where v is the maximal value
217 *)
218 let is_maximised rst v =
219 try
220 let vl, v = Vect.decomp_cst v in
221 if is_maximised_vect rst v then Some vl else None
222 with Not_found -> None
223
224 (** A variable xi is unbounded if for every
225 equation xj= ...ai.xi ...
226 if ai < 0 then xj is not restricted.
227 As a result, even if we
228 increase the value of xi, it is always
229 possible to adjust the value of xj without
230 violating a restriction.
231 *)
232
233 type result =
234 | Max of Q.t (** Maximum is reached *)
235 | Ubnd of var (** Problem is unbounded *)
236 | Feas (** Problem is feasible *)
237
238 type pivot = Done of result | Pivot of int * int * Q.t
239 type simplex = Opt of tableau * result
240
241 (** For a row, x = ao.xo+...+ai.xi
242 a valid pivot variable is such that it can improve the value of xi.
243 it is the case, if xi is unrestricted (increase if ai> 0, decrease if ai < 0)
244 xi is restricted but ai > 0
245
246 This is the entering variable.
247 *)
248
249 let rec find_pivot_column (rst : Restricted.t) (r : Vect.t) =
250 match Vect.choose r with
251 | None -> failwith "find_pivot_column"
252 | Some (xi, ai, r') ->
253 if ai </ Q.zero then
254 if Restricted.is_restricted xi rst then find_pivot_column rst r'
255 (* ai.xi cannot be improved *)
256 else (xi, -1) (* r is not restricted, sign of ai does not matter *)
257 else (* ai is positive, xi can be increased *)
258 (xi, 1)
259
260 (** Finding the variable leaving the basis is more subtle because we need to:
261 - increase the objective function
262 - make sure that the entering variable has a feasible value
263 - but also that after pivoting all the other basic variables are still feasible.
264 This explains why we choose the pivot with the smallest score
265 *)
266
267 let min_score s (i1, sc1) =
268 match s with
269 | None -> Some (i1, sc1)
270 | Some (i0, sc0) ->
271 if sc0 </ sc1 then s
272 else if sc1 </ sc0 then Some (i1, sc1)
273 else if i0 < i1 then s
274 else Some (i1, sc1)
275
276 let find_pivot_row rst tbl j sgn =
277 Restricted.fold rst
278 (fun i' v res ->
279 let aij = Vect.get j v in
280 if Q.of_int sgn */ aij </ Q.zero then
281 (* This would improve *)
282 let score' = Q.abs (Vect.get_cst v // aij) in
283 min_score res (i', score')
284 else res)
285 tbl None
286
287 let safe_find err x t =
288 try IMap.find x t
289 with Not_found ->
290 if debug then
291 Printf.fprintf stdout "safe_find %s x%i %a\n" err x output_tableau t;
292 failwith err
293
294 (** [find_pivot vr t] aims at improving the objective function of the basic variable vr *)
295 let find_pivot vr (rst : Restricted.t) tbl =
296 (* Get the objective of the basic variable vr *)
297 let v = safe_find "find_pivot" vr tbl in
298 match is_maximised rst v with
299 | Some mx -> Done (Max mx) (* Maximum is reached; we are done *)
300 | None -> (
301 (* Extract the vector *)
302 let _, v = Vect.decomp_cst v in
303 let j', sgn = find_pivot_column rst v in
304 match find_pivot_row rst (IMap.remove vr tbl) j' sgn with
305 | None -> Done (Ubnd j')
306 | Some (i', sc) -> Pivot (i', j', sc) )
307
308 (** [solve_column c r e]
309 @param c is a non-basic variable
310 @param r is a basic variable
311 @param e is a vector such that r = e
312 and e is of the form ai.c+e'
313 @return the vector (-r + e').-1/ai i.e
314 c = (r - e')/ai
315 *)
316
317 let solve_column (c : var) (r : var) (e : Vect.t) : Vect.t =
318 let a = Vect.get c e in
319 if a =/ Q.zero then failwith "Cannot solve column"
320 else
321 let a' = Q.minus_one // a in
322 Vect.mul a' (Vect.set r Q.minus_one (Vect.set c Q.zero e))
323
324 (** [pivot_row r c e]
325 @param c is such that c = e
326 @param r is a vector r = g.c + r'
327 @return g.e+r' *)
328
329 let pivot_row (row : Vect.t) (c : var) (e : Vect.t) : Vect.t =
330 let g = Vect.get c row in
331 if g =/ Q.zero then row else Vect.mul_add g e Q.one (Vect.set c Q.zero row)
332
333 let pivot_with (m : tableau) (v : var) (p : Vect.t) =
334 IMap.map (fun (r : Vect.t) -> pivot_row r v p) m
335
336 let pivot (m : tableau) (r : var) (c : var) =
337 incr nb_pivot;
338 let row = safe_find "pivot" r m in
339 let piv = solve_column c r row in
340 IMap.add c piv (pivot_with (IMap.remove r m) c piv)
341
342 let adapt_unbounded vr x rst tbl =
343 if Vect.get_cst (IMap.find vr tbl) >=/ Q.zero then tbl else pivot tbl vr x
344
345 module BaseSet = Set.Make (struct
346 type t = iset
347
348 let compare = IMap.compare (fun x y -> 0)
349 end)
350
351 let get_base tbl = IMap.mapi (fun k _ -> ()) tbl
352
353 let simplex opt vr rst tbl =
354 let b = ref BaseSet.empty in
355 let rec simplex opt vr rst tbl =
356 ( if debug then
357 let base = get_base tbl in
358 if BaseSet.mem base !b then Printf.fprintf stdout "Cycling detected\n"
359 else b := BaseSet.add base !b );
360 if debug && not (is_feasible rst tbl) then begin
361 let m = unfeasible rst tbl in
362 Printf.fprintf stdout "Simplex error\n";
363 Printf.fprintf stdout "The current tableau is not feasible\n";
364 Printf.fprintf stdout "Restricted >= %a\n" Restricted.pp rst;
365 output_tableau stdout tbl;
366 Printf.fprintf stdout "Error for variables %a\n" output_vars m
367 end;
368 if (not opt) && Vect.get_cst (IMap.find vr tbl) >=/ Q.zero then
369 Opt (tbl, Feas)
370 else
371 match find_pivot vr rst tbl with
372 | Done r -> (
373 match r with
374 | Max _ -> Opt (tbl, r)
375 | Ubnd x ->
376 let t' = adapt_unbounded vr x rst tbl in
377 Opt (t', r)
378 | Feas -> raise (Invalid_argument "find_pivot") )
379 | Pivot (i, j, s) ->
380 if debug then begin
381 Printf.fprintf stdout "Find pivot for x%i(%s)\n" vr (Q.to_string s);
382 Printf.fprintf stdout "Leaving variable x%i\n" i;
383 Printf.fprintf stdout "Entering variable x%i\n" j
384 end;
385 let m' = pivot tbl i j in
386 simplex opt vr rst m'
387 in
388 simplex opt vr rst tbl
389
390 type certificate = Unsat of Vect.t | Sat of tableau * var option
391
392 (** [normalise_row t v]
393 @return a row obtained by pivoting the basic variables of the vector v
394 *)
395
396 let normalise_row (t : tableau) (v : Vect.t) =
397 Vect.fold
398 (fun acc vr ai ->
399 try
400 let e = IMap.find vr t in
401 Vect.add (Vect.mul ai e) acc
402 with Not_found -> Vect.add (Vect.set vr ai Vect.null) acc)
403 Vect.null v
404
405 let normalise_row (t : tableau) (v : Vect.t) =
406 let v' = normalise_row t v in
407 if debug then Printf.fprintf stdout "Normalised Optimising %a\n" LinPoly.pp v';
408 v'
409
410 let add_row (nw : var) (t : tableau) (v : Vect.t) : tableau =
411 IMap.add nw (normalise_row t v) t
412
413 (** [push_real] performs reasoning over the rationals *)
414 let push_real (opt : bool) (nw : var) (v : Vect.t) (rst : Restricted.t)
415 (t : tableau) : certificate =
416 if debug then begin
417 Printf.fprintf stdout "Current Tableau\n%a\n" output_tableau t;
418 Printf.fprintf stdout "Optimising %a=%a\n" LinPoly.pp_var nw LinPoly.pp v
419 end;
420 match simplex opt nw rst (add_row nw t v) with
421 | Opt (t', r) -> (
422 (* Look at the optimal *)
423 match r with
424 | Ubnd x ->
425 if debug then
426 Printf.printf "The objective is unbounded (variable %a)\n"
427 LinPoly.pp_var x;
428 Sat (t', Some x) (* This is sat and we can extract a value *)
429 | Feas -> Sat (t', None)
430 | Max n ->
431 if debug then begin
432 Printf.printf "The objective is maximised %s\n" (Q.to_string n);
433 Printf.printf "%a = %a\n" LinPoly.pp_var nw pp_row (IMap.find nw t')
434 end;
435 if n >=/ Q.zero then Sat (t', None)
436 else
437 let v' = safe_find "push_real" nw t' in
438 Unsat (Vect.set nw Q.one (Vect.set 0 Q.zero (Vect.mul Q.minus_one v')))
439 )
440
441 (** One complication is that equalities needs some pre-processing.
442 *)
443 open Mutils
444
445 open Polynomial
446
447 (*type varmap = (int * bool) IMap.t*)
448
449 let find_solution rst tbl =
450 IMap.fold
451 (fun vr v res ->
452 if Restricted.is_restricted vr rst then res
453 else Vect.set vr (Vect.get_cst v) res)
454 tbl Vect.null
455
456 let find_full_solution rst tbl =
457 IMap.fold (fun vr v res -> Vect.set vr (Vect.get_cst v) res) tbl Vect.null
458
459 let choose_conflict (sol : Vect.t) (l : (var * Vect.t) list) =
460 let esol = Vect.set 0 Q.one sol in
461 let rec most_violating l e (x, v) rst =
462 match l with
463 | [] -> Some ((x, v), rst)
464 | (x', v') :: l ->
465 let e' = Vect.dotproduct esol v' in
466 if e' <=/ e then most_violating l e' (x', v') ((x, v) :: rst)
467 else most_violating l e (x, v) ((x', v') :: rst)
468 in
469 match l with
470 | [] -> None
471 | (x, v) :: l ->
472 let e = Vect.dotproduct esol v in
473 most_violating l e (x, v) []
474
475 let rec solve opt l (rst : Restricted.t) (t : tableau) =
476 let sol = find_solution rst t in
477 match choose_conflict sol l with
478 | None -> Inl (rst, t, None)
479 | Some ((vr, v), l) -> (
480 match push_real opt vr v (Restricted.set_exc vr rst) t with
481 | Sat (t', x) -> (
482 match l with [] -> Inl (rst, t', x) | _ -> solve opt l rst t' )
483 | Unsat c -> Inr c )
484
485 let fresh_var l =
486 1
487 +
488 try
489 ISet.max_elt
490 (List.fold_left
491 (fun acc c -> ISet.union acc (Vect.variables c.coeffs))
492 ISet.empty l)
493 with Not_found -> 0
494
495 module PrfEnv = struct
496 type t = WithProof.t IMap.t
497
498 let empty = IMap.empty
499
500 let register prf env =
501 let fr = LinPoly.MonT.get_fresh () in
502 (fr, IMap.add fr prf env)
503
504 (* let register_def (v, op) {fresh; env} =
505 LinPoly.MonT.reserve fresh;
506 (fresh, {fresh = fresh + 1; env = IMap.add fresh ((v, op), Def fresh) env}) *)
507
508 let set_prf i prf env = IMap.add i prf env
509 let find idx env = IMap.find idx env
510
511 let rec of_list acc env l =
512 match l with
513 | [] -> (acc, env)
514 | wp :: l -> (
515 let ((lp, op), prf) = WithProof.repr wp in
516 match op with
517 | Gt -> raise Strict (* Should be eliminated earlier *)
518 | Ge ->
519 (* Simply register *)
520 let f, env' = register wp env in
521 of_list ((f, lp) :: acc) env' l
522 | Eq ->
523 (* Generate two constraints *)
524 let f1, env = register wp env in
525 let wp' = WithProof.neg wp in
526 let f2, env = register wp' env in
527 let (lp', _), _ = WithProof.repr wp' in
528 of_list ((f1, lp) :: (f2, lp') :: acc) env l )
529
530 let map f env = IMap.map f env
531 end
532
533 let make_env (l : Polynomial.cstr list) =
534 PrfEnv.of_list [] PrfEnv.empty
535 (List.rev_map WithProof.of_cstr
536 (List.mapi (fun i x -> (x, ProofFormat.Hyp i)) l))
537
538 let find_point (l : Polynomial.cstr list) =
539 let vr = fresh_var l in
540 LinPoly.MonT.safe_reserve vr;
541 let l', _ = make_env l in
542 match solve false l' (Restricted.make vr) IMap.empty with
543 | Inl (rst, t, _) -> Some (find_solution rst t)
544 | _ -> None
545
546 (** [make_certificate env l] makes very strong assumptions
547 about the form of the environment.
548 Each proof is assumed to be either:
549 - an hypothesis Hyp i
550 - or, the negation of an hypothesis (MulC(-1,Hyp i))
551 *)
552
553 let make_certificate env l =
554 Vect.normalise
555 (Vect.fold
556 (fun acc x n ->
557 let wp = PrfEnv.find x env in
558 ProofFormat.(
559 match WithProof.proof wp with
560 | Hyp i -> Vect.set i n acc
561 | MulC (_, Hyp i) -> Vect.set i (Q.neg n) acc
562 | _ -> failwith "make_certificate: invalid proof"))
563 Vect.null l)
564
565 let find_unsat_certificate (l : Polynomial.cstr list) =
566 let l', env = make_env l in
567 let vr = fresh_var l in
568 match solve false l' (Restricted.make vr) IMap.empty with
569 | Inr c -> Some (make_certificate env c)
570 | Inl _ -> None
571
572 open Polynomial
573 open ProofFormat
574
575 let make_farkas_certificate (env : PrfEnv.t) v =
576 let fold acc x n =
577 let wp = PrfEnv.find x env in
578 add_proof acc (mul_cst_proof n (WithProof.proof wp))
579 in
580 Vect.fold fold Zero v
581
582 let make_farkas_proof (env : PrfEnv.t) v =
583 Vect.fold
584 (fun wp x n ->
585 WithProof.addition wp (WithProof.mul_cst n (PrfEnv.find x env)))
586 WithProof.zero v
587
588 let frac_num n = n -/ Q.floor n
589
590 type ('a, 'b) hitkind =
591 | Forget
592 (* Not interesting *)
593 | Hit of 'a
594 (* Yes, we have a positive result *)
595 | Keep of 'b
596
597 let violation sol vect =
598 let sol = Vect.set 0 Q.one sol in
599 let c = Vect.get 0 vect in
600 if Q.zero =/ c then Vect.dotproduct sol vect
601 else Q.abs (Vect.dotproduct sol vect // c)
602
603 let cut env rmin sol (rst : Restricted.t) tbl (x, v) =
604 let n, r = Vect.decomp_cst v in
605 let fn = frac_num (Q.abs n) in
606 if fn =/ Q.zero then Forget (* The solution is integral *)
607 else
608 (* The cut construction is from:
609 Letchford and Lodi. Strengthening Chvatal-Gomory cuts and Gomory fractional cuts.
610
611 We implement the classic Proposition 2 from the "known results"
612 *)
613
614 (* Proposition 3 requires all the variables to be restricted and is
615 therefore not always applicable. *)
616 (* let ccoeff_prop1 v = frac_num v in
617 let ccoeff_prop3 v =
618 (* mixed integer cut *)
619 let fv = frac_num v in
620 Num.min_num fv (fn */ (Q.one -/ fv) // (Q.one -/ fn))
621 in
622 let ccoeff_prop3 =
623 if Restricted.is_restricted x rst then ("Prop3", ccoeff_prop3)
624 else ("Prop1", ccoeff_prop1)
625 in *)
626 let n0_5 = Q.one // Q.two in
627 (* If the fractional part [fn] is small, we construct the t-cut.
628 If the fractional part [fn] is big, we construct the t-cut of the negated row.
629 (This is only a cut if all the fractional variables are restricted.)
630 *)
631 let ccoeff_prop2 =
632 let tmin =
633 if fn </ n0_5 then (* t-cut *)
634 Q.ceiling (n0_5 // fn)
635 else
636 (* multiply by -1 & t-cut *)
637 Q.neg (Q.ceiling (n0_5 // (Q.one -/ fn)))
638 in
639 ("Prop2", fun v -> frac_num (v */ tmin))
640 in
641 let ccoeff = ccoeff_prop2 in
642 let cut_vector ccoeff =
643 Vect.fold
644 (fun acc x n ->
645 if Restricted.is_restricted x rst then Vect.set x (ccoeff n) acc
646 else acc)
647 Vect.null r
648 in
649 let lcut =
650 ( fst ccoeff
651 , make_farkas_proof env (Vect.normalise (cut_vector (snd ccoeff))) )
652 in
653 let check_cutting_plane (p, c) =
654 match WithProof.cutting_plane c with
655 | None ->
656 if debug then
657 Printf.printf "%s: This is not a cutting plane for %a\n%a:" p
658 LinPoly.pp_var x WithProof.output c;
659 None
660 | Some wp ->
661 if debug then (
662 Printf.printf "%s: This is a cutting plane for %a:" p LinPoly.pp_var x;
663 Printf.printf "(viol %f) %a\n"
664 (Q.to_float (violation sol (WithProof.polynomial wp)))
665 WithProof.output wp);
666 Some (x, wp)
667 in
668 match check_cutting_plane lcut with
669 | Some r -> Hit r
670 | None ->
671 let has_unrestricted =
672 Vect.fold
673 (fun acc v vl -> acc || not (Restricted.is_restricted v rst))
674 false r
675 in
676 if has_unrestricted then Keep (x, v) else Forget
677
678 let merge_result_old oldr f x =
679 match oldr with
680 | Hit v -> Hit v
681 | Forget -> (
682 match f x with Forget -> Forget | Hit v -> Hit v | Keep v -> Keep v )
683 | Keep v -> (
684 match f x with Forget -> Keep v | Keep v' -> Keep v | Hit v -> Hit v )
685
686 let merge_best lt oldr newr =
687 match (oldr, newr) with
688 | x, Forget -> x
689 | Hit v, Hit v' -> if lt v v' then Hit v else Hit v'
690 | _, Hit v | Hit v, _ -> Hit v
691 | Forget, Keep v -> Keep v
692 | Keep v, Keep v' -> Keep v'
693
694 (*let size_vect v =
695 let abs z = if Z.compare z Z.zero < 0 then Z.neg z else z in
696 Vect.fold
697 (fun acc _ q -> Z.add (abs (Q.num q)) (Z.add (Q.den q) acc))
698 Z.zero v
699 *)
700
701 let find_cut nb env u sol rst tbl =
702 if nb = 0 then
703 IMap.fold
704 (fun x v acc -> merge_result_old acc (cut env u sol rst tbl) (x, v))
705 tbl Forget
706 else
707 let lt (_, wp1) (_, wp2) =
708 (*violation sol v1 >/ violation sol v2*)
709 ProofFormat.pr_size (WithProof.proof wp1) </ ProofFormat.pr_size (WithProof.proof wp2)
710 in
711 IMap.fold
712 (fun x v acc -> merge_best lt acc (cut env u sol rst tbl (x, v)))
713 tbl Forget
714
715 let find_split env tbl rst =
716 let is_split x v =
717 let v, n =
718 let n, _ = Vect.decomp_cst v in
719 if Restricted.is_restricted x rst then
720 let n', v = Vect.decomp_cst @@ WithProof.polynomial @@ PrfEnv.find x env in
721 (v, n -/ n')
722 else (Vect.set x Q.one Vect.null, n)
723 in
724 if Restricted.is_restricted x rst then None
725 else
726 let fn = frac_num n in
727 if fn =/ Q.zero then None
728 else
729 let fn = Q.abs fn in
730 let score = Q.min fn (Q.one -/ fn) in
731 let vect = Vect.add (Vect.cst (Q.neg n)) v in
732 Some (Vect.normalise vect, score)
733 in
734 IMap.fold
735 (fun x v acc ->
736 match is_split x v with
737 | None -> acc
738 | Some (v, s) -> (
739 match acc with
740 | None -> Some (v, s)
741 | Some (v', s') -> if s' >/ s then acc else Some (v, s) ))
742 tbl None
743
744 let var_of_vect v = fst (fst (Vect.decomp_fst v))
745
746 let eliminate_variable (bounded, env, tbl) x =
747 if debug then
748 Printf.printf "Eliminating variable %a from tableau\n%a\n" LinPoly.pp_var x
749 output_tableau tbl;
750 (* We identify the new variables with the constraint. *)
751 let vr = LinPoly.MonT.get_fresh () in
752 let vr1 = LinPoly.MonT.get_fresh () in
753 let vr2 = LinPoly.MonT.get_fresh () in
754 let z = LinPoly.var vr1 in
755 let zv = var_of_vect z in
756 let t = LinPoly.var vr2 in
757 let tv = var_of_vect t in
758 (* x = z - t *)
759 let xdef = Vect.add z (Vect.uminus t) in
760 let xp = WithProof.def (Vect.set x Q.one (Vect.uminus xdef)) Eq vr in
761 let zp = WithProof.def z Ge zv in
762 let tp = WithProof.def t Ge tv in
763 (* Pivot the current tableau using xdef *)
764 let tbl = IMap.map (fun v -> Vect.subst x xdef v) tbl in
765 (* Pivot the proof environment *)
766 let env =
767 PrfEnv.map
768 (fun lp ->
769 let ai = Vect.get x (WithProof.polynomial lp) in
770 if ai =/ Q.zero then lp
771 else WithProof.addition (WithProof.mul_cst (Q.neg ai) xp) lp)
772 env
773 in
774 (* Add the variables to the environment *)
775 let env =
776 PrfEnv.set_prf vr xp (PrfEnv.set_prf zv zp (PrfEnv.set_prf tv tp env))
777 in
778 (* Remember the mapping *)
779 let bounded = IMap.add x (vr, zv, tv) bounded in
780 if debug then (
781 Printf.printf "Tableau without\n %a\n" output_tableau tbl;
782 Printf.printf "Environment\n %a\n" output_env env );
783 (bounded, env, tbl)
784
785 let integer_solver lp =
786 let insert_row vr v rst tbl =
787 match push_real true vr v rst tbl with
788 | Sat (t', x) ->
789 (*pp_smt_goal stdout tbl vr v t';*)
790 Inl (Restricted.restrict vr rst, t', x)
791 | Unsat c -> Inr c
792 in
793 let vr0 = LinPoly.MonT.get_fresh () in
794 (* Initialise the proof environment mapping variables of the simplex to their proof. *)
795 let l', env =
796 PrfEnv.of_list [] PrfEnv.empty (List.rev lp)
797 in
798 let nb = ref 0 in
799 let rec isolve env cr res =
800 incr nb;
801 match res with
802 | Inr c ->
803 Some
804 (Step
805 ( LinPoly.MonT.get_fresh ()
806 , make_farkas_certificate env (Vect.normalise c)
807 , Done ))
808 | Inl (rst, tbl, x) -> (
809 if debug then begin
810 Printf.fprintf stdout "Looking for a cut\n";
811 Printf.fprintf stdout "Restricted %a ...\n" Restricted.pp rst;
812 Printf.fprintf stdout "Current Tableau\n%a\n" output_tableau tbl;
813 flush stdout
814 end;
815 if !nb mod 3 = 0 then
816 match find_split env tbl rst with
817 | None ->
818 None (* There is no hope, there should be an integer solution *)
819 | Some (v, s) -> (
820 let vr = LinPoly.MonT.get_fresh () in
821 let wp1 = WithProof.def v Ge vr in
822 let wp2 = WithProof.def (Vect.mul Q.minus_one v) Ge vr in
823 match (WithProof.cutting_plane wp1, WithProof.cutting_plane wp2) with
824 | None, _ | _, None ->
825 failwith "Error: splitting over an integer variable"
826 | Some wp1, Some wp2 -> (
827 if debug then
828 Printf.fprintf stdout "Splitting over (%s) %a:%a or %a \n"
829 (Q.to_string s) LinPoly.pp_var vr WithProof.output wp1
830 WithProof.output wp2;
831 let v1', v2' = (WithProof.polynomial wp1, WithProof.polynomial wp2) in
832 if debug then
833 Printf.fprintf stdout "Solving with %a\n" LinPoly.pp v1';
834 let res1 = insert_row vr v1' (Restricted.set_exc vr rst) tbl in
835 let prf1 = isolve (IMap.add vr (WithProof.def v1' Ge vr) env) cr res1 in
836 match prf1 with
837 | None -> None
838 | Some prf1 ->
839 let prf', hyps = ProofFormat.simplify_proof prf1 in
840 if not (ISet.mem vr hyps) then Some prf'
841 else (
842 if debug then
843 Printf.fprintf stdout "Solving with %a\n" Vect.pp v2';
844 let res2 = insert_row vr v2' (Restricted.set_exc vr rst) tbl in
845 let prf2 =
846 isolve (IMap.add vr (WithProof.def v2' Ge vr) env) cr res2
847 in
848 match prf2 with
849 | None -> None
850 | Some prf2 -> Some (Split (vr, v, prf1, prf2)) ) ) )
851 else
852 let sol = find_full_solution rst tbl in
853 match find_cut (!nb mod 2) env cr (*x*) sol rst tbl with
854 | Forget ->
855 None (* There is no hope, there should be an integer solution *)
856 | Hit (cr, wp) -> (
857 let (v, op), cut = WithProof.repr wp in
858 let vr = LinPoly.MonT.get_fresh () in
859 if op = Eq then
860 (* This is a contradiction *)
861 Some (Step (vr, CutPrf cut, Done))
862 else
863 let res = insert_row vr v (Restricted.set_exc vr rst) tbl in
864 let prf =
865 isolve (IMap.add vr (WithProof.def v op vr) env) (Some cr) res
866 in
867 match prf with
868 | None -> None
869 | Some p -> Some (Step (vr, CutPrf cut, p)) )
870 | Keep (x, v) -> (
871 if debug then
872 Printf.fprintf stdout "Remove %a from Tableau\n" LinPoly.pp_var x;
873 let bounded, env, tbl =
874 Vect.fold
875 (fun acc x n ->
876 if x <> 0 && not (Restricted.is_restricted x rst) then
877 eliminate_variable acc x
878 else acc)
879 (IMap.empty, env, tbl) v
880 in
881 let prf = isolve env cr (Inl (rst, tbl, None)) in
882 match prf with
883 | None -> None
884 | Some pf ->
885 Some
886 (IMap.fold
887 (fun x (vr, zv, tv) acc ->
888 ExProof (vr, zv, tv, x, zv, tv, acc))
889 bounded pf) ) )
890 in
891 let res = solve true l' (Restricted.make vr0) IMap.empty in
892 isolve env None res
893
894 let integer_solver lp =
895 nb_pivot := 0;
896 if debug then
897 Printf.printf "Input integer solver\n%a\n" WithProof.output_sys lp;
898 match integer_solver lp with
899 | None ->
900 profile_info := (false, !nb_pivot) :: !profile_info;
901 None
902 | Some prf ->
903 profile_info := (true, !nb_pivot) :: !profile_info;
904 if debug then
905 Printf.fprintf stdout "Proof %a\n" ProofFormat.output_proof prf;
906 Some prf