Debian Codegraph @

plugins/micromega/certificate.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 (* Micromega: A reflexive tactic using the Positivstellensatz *)
12 (* *)
13 (* Frédéric Besson (Irisa/Inria) 2006-2008 *)
14 (* *)
15 (************************************************************************)
16
17 (* We take as input a list of polynomials [p1...pn] and return an unfeasibility
18 certificate polynomial. *)
19
20 let debug = false
21
22 open Polynomial
23 module Mc = Micromega
24 module Ml2C = Mutils.CamlToCoq
25 module C2Ml = Mutils.CoqToCaml
26 open NumCompat
27 open Q.Notations
28 open Mutils
29
30 (* If set to some [file], arithmetic goals are dumped in [file].v *)
31
32 let { Goptions.get = dump_file } =
33 Goptions.declare_stringopt_option_and_ref
34 ~key:["Dump"; "Arith"]
35 ~value:None
36 ()
37
38 type ('prf, 'model) res = Prf of 'prf | Model of 'model | Unknown
39 type zres = (Mc.zArithProof, int * Mc.z list) res
40 type qres = (Mc.q Mc.psatz, int * Mc.q list) res
41
42 type 'a number_spec =
43 { bigint_to_number : Z.t -> 'a
44 ; number_to_num : 'a -> Q.t
45 ; zero : 'a
46 ; unit : 'a
47 ; mult : 'a -> 'a -> 'a
48 ; eqb : 'a -> 'a -> bool }
49
50 let z_spec =
51 { bigint_to_number = Ml2C.bigint
52 ; number_to_num = (fun x -> Q.of_bigint (C2Ml.z_big_int x))
53 ; zero = Mc.Z0
54 ; unit = Mc.Zpos Mc.XH
55 ; mult = Mc.Z.mul
56 ; eqb = Mc.Z.eqb }
57
58 let q_spec =
59 { bigint_to_number = (fun x -> {Mc.qnum = Ml2C.bigint x; Mc.qden = Mc.XH})
60 ; number_to_num = C2Ml.q_to_num
61 ; zero = {Mc.qnum = Mc.Z0; Mc.qden = Mc.XH}
62 ; unit = {Mc.qnum = Mc.Zpos Mc.XH; Mc.qden = Mc.XH}
63 ; mult = Mc.qmult
64 ; eqb = Mc.qeq_bool }
65
66 let dev_form n_spec p =
67 let rec dev_form p =
68 match p with
69 | Mc.PEc z -> Poly.constant (n_spec.number_to_num z)
70 | Mc.PEX v -> Poly.variable (C2Ml.positive v)
71 | Mc.PEmul (p1, p2) ->
72 let p1 = dev_form p1 in
73 let p2 = dev_form p2 in
74 Poly.product p1 p2
75 | Mc.PEadd (p1, p2) -> Poly.addition (dev_form p1) (dev_form p2)
76 | Mc.PEopp p -> Poly.uminus (dev_form p)
77 | Mc.PEsub (p1, p2) ->
78 Poly.addition (dev_form p1) (Poly.uminus (dev_form p2))
79 | Mc.PEpow (p, n) ->
80 let p = dev_form p in
81 let n = C2Ml.n n in
82 let rec pow n =
83 if Int.equal n 0 then Poly.constant (n_spec.number_to_num n_spec.unit)
84 else Poly.product p (pow (n - 1))
85 in
86 pow n
87 in
88 dev_form p
89
90 let rec fixpoint f x =
91 let y' = f x in
92 if y' = x then y' else fixpoint f y'
93
94 let rec_simpl_cone n_spec e =
95 let simpl_cone =
96 Mc.simpl_cone n_spec.zero n_spec.unit n_spec.mult n_spec.eqb
97 in
98 let rec rec_simpl_cone = function
99 | Mc.PsatzMulE (t1, t2) ->
100 simpl_cone (Mc.PsatzMulE (rec_simpl_cone t1, rec_simpl_cone t2))
101 | Mc.PsatzAdd (t1, t2) ->
102 simpl_cone (Mc.PsatzAdd (rec_simpl_cone t1, rec_simpl_cone t2))
103 | x -> simpl_cone x
104 in
105 rec_simpl_cone e
106
107 let simplify_cone n_spec c = fixpoint (rec_simpl_cone n_spec) c
108
109 (* The binding with Fourier might be a bit obsolete
110 -- how does it handle equalities ? *)
111
112 (* Certificates are elements of the cone such that P = 0 *)
113
114 (* To begin with, we search for certificates of the form:
115 a1.p1 + ... an.pn + b1.q1 +... + bn.qn + c = 0
116 where pi >= 0 qi > 0
117 ai >= 0
118 bi >= 0
119 Sum bi + c >= 1
120 This is a linear problem: each monomial is considered as a variable.
121 Hence, we can use fourier.
122
123 The variable c is at index 1
124 *)
125
126 (* fold_left followed by a rev ! *)
127
128 let constrain_variable v l =
129 let coeffs = List.fold_left (fun acc p -> Vect.get v p.coeffs :: acc) [] l in
130 { coeffs =
131 Vect.from_list
132 (Q.of_bigint Z.zero :: Q.of_bigint Z.zero :: List.rev coeffs)
133 ; op = Eq
134 ; cst = Q.of_bigint Z.zero }
135
136 let constrain_constant l =
137 let coeffs = List.fold_left (fun acc p -> Q.neg p.cst :: acc) [] l in
138 { coeffs =
139 Vect.from_list (Q.of_bigint Z.zero :: Q.of_bigint Z.one :: List.rev coeffs)
140 ; op = Eq
141 ; cst = Q.of_bigint Z.zero }
142
143 let positivity l =
144 let rec xpositivity i l =
145 match l with
146 | [] -> []
147 | c :: l -> (
148 match c.op with
149 | Eq -> xpositivity (i + 1) l
150 | _ ->
151 { coeffs = Vect.update (i + 1) (fun _ -> Q.one) Vect.null
152 ; op = Ge
153 ; cst = Q.zero }
154 :: xpositivity (i + 1) l )
155 in
156 xpositivity 1 l
157
158 let cstr_of_poly (p, o) =
159 let c, l = Vect.decomp_cst p in
160 {coeffs = l; op = o; cst = Q.neg c}
161
162 let make_cstr_system sys =
163 let map wp =
164 let ((p, o), prf) = WithProof.repr wp in
165 (cstr_of_poly (p, o), prf)
166 in
167 List.map map sys
168
169 let variables_of_cstr c = Vect.variables c.coeffs
170
171 (* If the certificate includes at least one strict inequality,
172 the obtained polynomial can also be 0 *)
173
174 let build_dual_linear_system l =
175 let variables =
176 List.fold_left
177 (fun acc p -> ISet.union acc (variables_of_cstr p))
178 ISet.empty l
179 in
180 (* For each monomial, compute a constraint *)
181 let s0 =
182 ISet.fold (fun mn res -> constrain_variable mn l :: res) variables []
183 in
184 let c = constrain_constant l in
185 (* I need at least something strictly positive *)
186 let strict =
187 { coeffs =
188 Vect.from_list
189 ( Q.of_bigint Z.zero :: Q.of_bigint Z.one
190 :: List.map
191 (fun c ->
192 if is_strict c then Q.of_bigint Z.one else Q.of_bigint Z.zero)
193 l )
194 ; op = Ge
195 ; cst = Q.of_bigint Z.one }
196 in
197 (* Add the positivity constraint *)
198 { coeffs = Vect.from_list [Q.of_bigint Z.zero; Q.of_bigint Z.one]
199 ; op = Ge
200 ; cst = Q.of_bigint Z.zero }
201 :: ((strict :: positivity l) @ (c :: s0))
202
203
204 let output_cstr_sys o sys =
205 List.iter
206 (fun (c, wp) ->
207 Printf.fprintf o "%a by %a\n" output_cstr c ProofFormat.output_prf_rule wp)
208 sys
209
210 let output_sys o sys =
211 List.iter (fun s -> Printf.fprintf o "%a\n" WithProof.output s) sys
212
213 let tr_sys str f sys =
214 let sys' = f sys in
215 if debug then
216 Printf.fprintf stdout "[%s\n%a=>\n%a]\n" str output_sys sys output_sys sys';
217 sys'
218
219 let tr_cstr_sys str f sys =
220 let sys' = f sys in
221 if debug then
222 Printf.fprintf stdout "[%s\n%a=>\n%a]\n" str output_cstr_sys sys
223 output_cstr_sys sys';
224 sys'
225
226 let dual_raw_certificate l =
227 if debug then begin
228 Printf.printf "dual_raw_certificate\n";
229 List.iter (fun c -> Printf.fprintf stdout "%a\n" output_cstr c) l
230 end;
231 let sys = build_dual_linear_system l in
232 if debug then begin
233 Printf.printf "dual_system\n";
234 List.iter (fun c -> Printf.fprintf stdout "%a\n" output_cstr c) sys
235 end;
236 try
237 match Simplex.find_point sys with
238 | None -> None
239 | Some cert -> (
240 match Vect.choose cert with
241 | None -> failwith "dual_raw_certificate: empty_certificate"
242 | Some _ ->
243 (*Some (rats_to_ints (Vect.to_list (Vect.decr_var 2 (Vect.set 1 Q.zero cert))))*)
244 Some (Vect.normalise (Vect.decr_var 2 (Vect.set 1 Q.zero cert))) )
245 (* should not use rats_to_ints *)
246 with x when CErrors.noncritical x ->
247 if debug then (
248 Printf.printf "dual raw certificate %s" (Printexc.to_string x);
249 flush stdout );
250 None
251
252 let simple_linear_prover l =
253 try Simplex.find_unsat_certificate l
254 with Strict -> dual_raw_certificate l
255
256 let env_of_list l =
257 snd
258 (List.fold_left (fun (i, m) p -> (i + 1, IMap.add i p m)) (0, IMap.empty) l)
259
260 let linear_prover_cstr sys =
261 let sysi, prfi = List.split sys in
262 match simple_linear_prover sysi with
263 | None -> None
264 | Some cert -> Some (ProofFormat.proof_of_farkas (env_of_list prfi) cert)
265
266 let linear_prover_cstr =
267 if debug then ( fun sys ->
268 Printf.printf "<linear_prover";
269 flush stdout;
270 let res = linear_prover_cstr sys in
271 Printf.printf ">"; flush stdout; res )
272 else linear_prover_cstr
273
274 let compute_max_nb_cstr l d =
275 let len = List.length l in
276 max len (max d (len * d))
277
278 let develop_constraint z_spec (e, k) =
279 ( dev_form z_spec e
280 , match k with
281 | Mc.NonStrict -> Ge
282 | Mc.Equal -> Eq
283 | Mc.Strict -> Gt
284 | _ -> assert false )
285
286 (** A single constraint can be unsat for the following reasons:
287 - 0 >= c for c a negative constant
288 - 0 = c for c a non-zero constant
289 - e = c when the coeffs of e are all integers and c is rational
290 *)
291
292 type checksat =
293 | Tauto (* Tautology *)
294 | Unsat of ProofFormat.prf_rule (* Unsatisfiable *)
295 | Cut of cstr * ProofFormat.prf_rule (* Cutting plane *)
296 | Normalise of cstr * ProofFormat.prf_rule
297
298 (* Coefficients may be normalised i.e relatively prime *)
299
300 exception FoundProof of ProofFormat.prf_rule
301
302 (** [check_sat]
303 - detects constraints that are not satisfiable;
304 - normalises constraints and generate cuts.
305 *)
306
307 let check_int_sat (cstr, prf) =
308 let {coeffs; op; cst} = cstr in
309 match Vect.choose coeffs with
310 | None -> if eval_op op Q.zero cst then Tauto else Unsat prf
311 | _ -> (
312 let gcdi = Vect.gcd coeffs in
313 let gcd = Q.of_bigint gcdi in
314 if gcd =/ Q.one then Normalise (cstr, prf)
315 else if Int.equal (Q.sign (Q.mod_ cst gcd)) 0 then begin
316 (* We can really normalise *)
317 assert (Q.sign gcd >= 1);
318 let cstr = {coeffs = Vect.div gcd coeffs; op; cst = cst // gcd} in
319 Normalise (cstr, ProofFormat.Gcd (gcdi, prf))
320 (* Normalise(cstr,CutPrf prf)*)
321 end
322 else
323 match op with
324 | Eq -> Unsat (ProofFormat.CutPrf prf)
325 | Ge ->
326 let cstr =
327 {coeffs = Vect.div gcd coeffs; op; cst = Q.ceiling (cst // gcd)}
328 in
329 Cut (cstr, ProofFormat.CutPrf prf)
330 | Gt -> failwith "check_sat : Unexpected operator" )
331
332 let apply_and_normalise check f psys =
333 List.fold_left
334 (fun acc pc' ->
335 match f pc' with
336 | None -> pc' :: acc
337 | Some pc' -> (
338 match check pc' with
339 | Tauto -> acc
340 | Unsat prf -> raise (FoundProof prf)
341 | Cut (c, p) -> (c, p) :: acc
342 | Normalise (c, p) -> (c, p) :: acc ))
343 [] psys
344
345 let is_linear_for v pc =
346 LinPoly.is_linear (WithProof.polynomial pc) || LinPoly.is_linear_for v (WithProof.polynomial pc)
347
348 (*let non_linear_pivot sys pc v pc' =
349 if LinPoly.is_linear (fst (fst pc'))
350 then None (* There are other ways to deal with those *)
351 else WithProof.linear_pivot sys pc v pc'
352 *)
353
354 let is_linear_substitution sys wp =
355 let (p, o), _ = WithProof.repr wp in
356 let pred v = v =/ Q.one || v =/ Q.minus_one in
357 match o with
358 | Eq -> (
359 match
360 List.filter
361 (fun v -> List.for_all (is_linear_for v) sys)
362 (LinPoly.search_all_linear pred p)
363 with
364 | [] -> None
365 | v :: _ -> Some v (* make a choice *) )
366 | _ -> None
367
368 let elim_simple_linear_equality sys0 =
369 let elim sys =
370 let oeq, sys' = extract (is_linear_substitution sys) sys in
371 match oeq with
372 | None -> None
373 | Some (v, pc) -> simplify (WithProof.linear_pivot sys0 pc v) sys'
374 in
375 iterate_until_stable elim sys0
376
377 let subst sys = tr_sys "subst" WithProof.subst sys
378
379 (** [saturate_linear_equality sys] generate new constraints
380 obtained by eliminating linear equalities by pivoting.
381 For integers, the obtained constraints are sound but not complete.
382 *)
383 let saturate_by_linear_equalities sys0 = WithProof.saturate_subst false sys0
384
385 let saturate_by_linear_equalities sys =
386 tr_sys "saturate_by_linear_equalities" saturate_by_linear_equalities sys
387
388
389 let elim_redundant sys =
390 let module VectMap = Map.Make (Vect) in
391 let elim_eq sys =
392 List.fold_left
393 (fun acc wp ->
394 let (_, o), _ = WithProof.repr wp in
395 match o with
396 | Gt -> assert false
397 | Ge -> wp :: acc
398 | Eq -> wp :: WithProof.neg wp :: acc)
399 [] sys
400 in
401 let of_list l =
402 List.fold_left
403 (fun m wp ->
404 let (v, o), _ = WithProof.repr wp in
405 let q, v' = Vect.decomp_cst v in
406 try
407 let q', wp' = VectMap.find v' m in
408 match Q.compare q q' with
409 | 0 -> if o = Eq then VectMap.add v' (q, wp) m else m
410 | 1 -> m
411 | _ -> VectMap.add v' (q, wp) m
412 with Not_found -> VectMap.add v' (q, wp) m)
413 VectMap.empty l
414 in
415 let to_list m = VectMap.fold (fun _ (_, wp) sys -> wp :: sys) m [] in
416 to_list (of_list (elim_eq sys))
417
418 let elim_redundant sys = tr_sys "elim_redundant" elim_redundant sys
419
420 let bound_monomials (sys : WithProof.t list) =
421 let (all_bounds,_) = extract_all BoundWithProof.make sys in
422 let mon = List.mapi (fun i b ->
423 let v = (BoundWithProof.bound b).Vect.Bound.var in
424 let m = LinPoly.MonT.retrieve v in
425 (i,(v,m,b))) all_bounds in
426
427 let vars = List.fold_left
428 (fun acc wp -> ISet.union (LinPoly.monomials (WithProof.polynomial wp)) acc)
429 ISet.empty sys in
430
431 let rec build_constraints l =
432 match l with
433 |[] -> Linsolve.empty
434 | (i,(_,m',_)) ::l ->
435 let c = build_constraints l in
436 let cm = Monomial.fold (fun x d acc -> Linsolve.make_mon x i d acc) m' Linsolve.empty in
437 Linsolve.merge c cm
438 in
439
440 let eqn = build_constraints mon in
441
442
443 let set_constants_for m e =
444 Monomial.fold (fun x d acc -> Linsolve.set_constant x d e :: acc) m [] in
445
446
447 (* [exp_bound b j] computes the bound at the power j for j >=1.
448 The current algorithm is not complete. It performs iterative multiplications. *)
449 let rec exp_bound b j =
450 if j = 1 then Some b
451 else
452 let b1 = exp_bound b (j/2) in
453 match b1 with
454 | None -> None
455 | Some b1 ->
456 match BoundWithProof.mul_bound b1 b1 with
457 | None -> None
458 | Some b1_b1 ->
459 if j mod 2 = 0
460 then Some b1_b1
461 else BoundWithProof.mul_bound b b1_b1 in
462
463 let rec bound_using_sol sol =
464 match sol with
465 | [] -> None
466 | [x,j] -> let (_,_,b) = List.assoc x mon in
467 exp_bound b j
468 | (x,j)::sol'-> let (_,_,b) = List.assoc x mon in
469 match exp_bound b j with
470 | None -> None
471 | Some b -> match bound_using_sol sol' with
472 |None -> None
473 | Some b' -> BoundWithProof.mul_bound b b' in
474
475 let bound_one_monomial x =
476 let m = LinPoly.MonT.retrieve x in
477 if Monomial.degree m <= 1
478 then []
479 else
480 let eqn = set_constants_for m eqn in
481 if debug then Printf.printf "Equations : %a\n" Linsolve.output_equations eqn ; flush stdout;
482 let sol = Linsolve.solve_and_enum eqn in
483 if debug then Printf.printf "Solutions %i \n %a\n" (List.length sol) Linsolve.output_solutions sol;
484 let l = elim_redundant (CList.map_filter (fun s -> Option.map BoundWithProof.proof (bound_using_sol s)) sol) in
485 if debug then Printf.printf "New bounds %a" output_sys l; l
486 in
487
488 ISet.fold (fun m acc -> List.rev_append (bound_one_monomial m) acc) vars []
489
490
491 let bound_monomials sys= tr_sys "bound_monomials" bound_monomials sys
492
493 let develop_constraints prfdepth n_spec sys =
494 LinPoly.MonT.clear ();
495 max_nb_cstr := compute_max_nb_cstr sys prfdepth;
496 let sys = List.map (develop_constraint n_spec) sys in
497 let sys = List.mapi (fun i (p, o) -> WithProof.mkhyp (LinPoly.linpol_of_pol p) o i) sys in
498 ProofFormat.Env.make (List.length sys), sys
499
500 let square_of_var i =
501 let x = LinPoly.var i in
502 WithProof.square (LinPoly.product x x) x
503
504 (** [nlinear_preprocess sys] augments the system [sys] by performing some limited non-linear reasoning.
505 For instance, it asserts that the x² ≥0 but also that if c₁ ≥ 0 ∈ sys and c₂ ≥ 0 ∈ sys then c₁ × c₂ ≥ 0.
506 The resulting system is linearised.
507 *)
508
509 let nlinear_preprocess (sys : WithProof.t list) =
510 let is_linear = List.for_all (fun wp -> LinPoly.is_linear @@ WithProof.polynomial wp) sys in
511 if is_linear then sys
512 else
513 let collect_square =
514 List.fold_left
515 (fun acc wp ->
516 MonMap.union (fun k e1 e2 -> Some e1) acc (LinPoly.collect_square @@ WithProof.polynomial wp))
517 MonMap.empty sys
518 in
519 let sys =
520 MonMap.fold
521 (fun s m acc ->
522 let s = LinPoly.of_monomial s in
523 let m = LinPoly.of_monomial m in
524 (WithProof.square m s) :: acc)
525 collect_square sys
526 in
527 let collect_vars =
528 List.fold_left
529 (fun acc p -> ISet.union acc (LinPoly.variables (WithProof.polynomial p)))
530 ISet.empty sys
531 in
532 let sys =
533 ISet.fold (fun i acc -> square_of_var i :: acc) collect_vars sys
534 in
535 let sys = sys @ all_pairs WithProof.product sys in
536 List.map (WithProof.annot "P") sys
537
538 let nlinear_preprocess = tr_sys "nlinear_preprocess" nlinear_preprocess
539
540 let nlinear_prover prfdepth sys =
541 let env, sys = develop_constraints prfdepth q_spec sys in
542 let sys1 = elim_simple_linear_equality sys in
543 let sys2 = saturate_by_linear_equalities sys1 in
544 let sys = nlinear_preprocess sys1 @ sys2 in
545 let sys = make_cstr_system sys in
546 match linear_prover_cstr sys with
547 | None -> Unknown
548 | Some cert -> Prf (ProofFormat.cmpl_prf_rule Mc.normQ CamlToCoq.q env cert)
549
550 let linear_prover_with_cert prfdepth sys =
551 let env, sys = develop_constraints prfdepth q_spec sys in
552 (* let sys = nlinear_preprocess sys in *)
553 let sys = make_cstr_system sys in
554 match linear_prover_cstr sys with
555 | None -> Unknown
556 | Some cert ->
557 Prf
558 (ProofFormat.cmpl_prf_rule Mc.normQ CamlToCoq.q
559 env
560 cert)
561
562 (* The prover is (probably) incomplete --
563 only searching for naive cutting planes *)
564
565 open Sos_types
566
567 let rec scale_term t =
568 match t with
569 | Zero -> (Z.one, Zero)
570 | Const n -> (Q.den n, Const (Q.of_bigint (Q.num n)))
571 | Var n -> (Z.one, Var n)
572 | Opp t ->
573 let s, t = scale_term t in
574 (s, Opp t)
575 | Add (t1, t2) ->
576 let s1, y1 = scale_term t1 and s2, y2 = scale_term t2 in
577 let g = Z.gcd s1 s2 in
578 let s1' = Z.div s1 g in
579 let s2' = Z.div s2 g in
580 let e = Z.mul g (Z.mul s1' s2') in
581 if Int.equal (Z.compare e Z.one) 0 then (Z.one, Add (y1, y2))
582 else
583 ( e
584 , Add
585 (Mul (Const (Q.of_bigint s2'), y1), Mul (Const (Q.of_bigint s1'), y2))
586 )
587 | Sub _ -> failwith "scale term: not implemented"
588 | Mul (y, z) ->
589 let s1, y1 = scale_term y and s2, y2 = scale_term z in
590 (Z.mul s1 s2, Mul (y1, y2))
591 | Pow (t, n) ->
592 let s, t = scale_term t in
593 (Z.power_int s n, Pow (t, n))
594
595 let scale_term t =
596 let s, t' = scale_term t in
597 (s, t')
598
599 let rec scale_certificate pos =
600 match pos with
601 | Axiom_eq i -> (Z.one, Axiom_eq i)
602 | Axiom_le i -> (Z.one, Axiom_le i)
603 | Axiom_lt i -> (Z.one, Axiom_lt i)
604 | Monoid l -> (Z.one, Monoid l)
605 | Rational_eq n -> (Q.den n, Rational_eq (Q.of_bigint (Q.num n)))
606 | Rational_le n -> (Q.den n, Rational_le (Q.of_bigint (Q.num n)))
607 | Rational_lt n -> (Q.den n, Rational_lt (Q.of_bigint (Q.num n)))
608 | Square t ->
609 let s, t' = scale_term t in
610 (Z.mul s s, Square t')
611 | Eqmul (t, y) ->
612 let s1, y1 = scale_term t and s2, y2 = scale_certificate y in
613 (Z.mul s1 s2, Eqmul (y1, y2))
614 | Sum (y, z) ->
615 let s1, y1 = scale_certificate y and s2, y2 = scale_certificate z in
616 let g = Z.gcd s1 s2 in
617 let s1' = Z.div s1 g in
618 let s2' = Z.div s2 g in
619 ( Z.mul g (Z.mul s1' s2')
620 , Sum
621 ( Product (Rational_le (Q.of_bigint s2'), y1)
622 , Product (Rational_le (Q.of_bigint s1'), y2) ) )
623 | Product (y, z) ->
624 let s1, y1 = scale_certificate y and s2, y2 = scale_certificate z in
625 (Z.mul s1 s2, Product (y1, y2))
626
627 module Z_ = Z
628 open Micromega
629
630 let rec term_to_q_expr = function
631 | Const n -> PEc (Ml2C.q n)
632 | Zero -> PEc (Ml2C.q Q.zero)
633 | Var s ->
634 PEX (Ml2C.index (int_of_string (String.sub s 1 (String.length s - 1))))
635 | Mul (p1, p2) -> PEmul (term_to_q_expr p1, term_to_q_expr p2)
636 | Add (p1, p2) -> PEadd (term_to_q_expr p1, term_to_q_expr p2)
637 | Opp p -> PEopp (term_to_q_expr p)
638 | Pow (t, n) -> PEpow (term_to_q_expr t, Ml2C.n n)
639 | Sub (t1, t2) -> PEsub (term_to_q_expr t1, term_to_q_expr t2)
640
641 let term_to_q_pol e =
642 Mc.norm_aux (Ml2C.q Q.zero) (Ml2C.q Q.one) Mc.qplus Mc.qmult Mc.qminus Mc.qopp
643 Mc.qeq_bool (term_to_q_expr e)
644
645 let rec product l =
646 match l with
647 | [] -> Mc.PsatzZ
648 | [i] -> Mc.PsatzIn (Ml2C.nat i)
649 | i :: l -> Mc.PsatzMulE (Mc.PsatzIn (Ml2C.nat i), product l)
650
651 let q_cert_of_pos pos =
652 let rec _cert_of_pos = function
653 | Axiom_eq i -> Mc.PsatzIn (Ml2C.nat i)
654 | Axiom_le i -> Mc.PsatzIn (Ml2C.nat i)
655 | Axiom_lt i -> Mc.PsatzIn (Ml2C.nat i)
656 | Monoid l -> product l
657 | Rational_eq n | Rational_le n | Rational_lt n ->
658 if Int.equal (Q.compare n Q.zero) 0 then Mc.PsatzZ
659 else Mc.PsatzC (Ml2C.q n)
660 | Square t -> Mc.PsatzSquare (term_to_q_pol t)
661 | Eqmul (t, y) -> Mc.PsatzMulC (term_to_q_pol t, _cert_of_pos y)
662 | Sum (y, z) -> Mc.PsatzAdd (_cert_of_pos y, _cert_of_pos z)
663 | Product (y, z) -> Mc.PsatzMulE (_cert_of_pos y, _cert_of_pos z)
664 in
665 simplify_cone q_spec (_cert_of_pos pos)
666
667 let rec term_to_z_expr = function
668 | Const n -> PEc (Ml2C.bigint (Q.to_bigint n))
669 | Zero -> PEc Z0
670 | Var s ->
671 PEX (Ml2C.index (int_of_string (String.sub s 1 (String.length s - 1))))
672 | Mul (p1, p2) -> PEmul (term_to_z_expr p1, term_to_z_expr p2)
673 | Add (p1, p2) -> PEadd (term_to_z_expr p1, term_to_z_expr p2)
674 | Opp p -> PEopp (term_to_z_expr p)
675 | Pow (t, n) -> PEpow (term_to_z_expr t, Ml2C.n n)
676 | Sub (t1, t2) -> PEsub (term_to_z_expr t1, term_to_z_expr t2)
677
678 let term_to_z_pol e =
679 Mc.norm_aux (Ml2C.z 0) (Ml2C.z 1) Mc.Z.add Mc.Z.mul Mc.Z.sub Mc.Z.opp
680 Mc.Z.eqb (term_to_z_expr e)
681
682 let z_cert_of_pos pos =
683 let s, pos = scale_certificate pos in
684 let rec _cert_of_pos = function
685 | Axiom_eq i -> Mc.PsatzIn (Ml2C.nat i)
686 | Axiom_le i -> Mc.PsatzIn (Ml2C.nat i)
687 | Axiom_lt i -> Mc.PsatzIn (Ml2C.nat i)
688 | Monoid l -> product l
689 | Rational_eq n | Rational_le n | Rational_lt n ->
690 if Int.equal (Q.compare n Q.zero) 0 then Mc.PsatzZ
691 else Mc.PsatzC (Ml2C.bigint (Q.to_bigint n))
692 | Square t -> Mc.PsatzSquare (term_to_z_pol t)
693 | Eqmul (t, y) ->
694 let is_unit = match t with Const n -> n =/ Q.one | _ -> false in
695 if is_unit then _cert_of_pos y
696 else Mc.PsatzMulC (term_to_z_pol t, _cert_of_pos y)
697 | Sum (y, z) -> Mc.PsatzAdd (_cert_of_pos y, _cert_of_pos z)
698 | Product (y, z) -> Mc.PsatzMulE (_cert_of_pos y, _cert_of_pos z)
699 in
700 simplify_cone z_spec (_cert_of_pos pos)
701
702 (** All constraints (initial or derived) have an index and have a justification i.e., proof.
703 Given a constraint, all the coefficients are always integers.
704 *)
705 open Mutils
706
707 open Polynomial
708
709 (** Proof generating pivoting over variable v.
710 Assumes [a] is the non-zero coefficient for [v] in [c1]. *)
711 let pivot v (a, c1, p1) (c2, p2) =
712 let {coeffs = v1; op = op1; cst = n1} = c1
713 and {coeffs = v2; op = op2; cst = n2} = c2 in
714 let () = assert (op1 == Eq) in
715 (* Could factorise gcd... *)
716 let xpivot cv1 cv2 =
717 ( { coeffs = Vect.add (Vect.mul cv1 v1) (Vect.mul cv2 v2)
718 ; op = opAdd Eq op2
719 ; cst = (n1 */ cv1) +/ (n2 */ cv2) }
720 , ProofFormat.add_proof
721 (ProofFormat.mul_cst_proof cv1 p1)
722 (ProofFormat.mul_cst_proof cv2 p2) )
723 in
724 let b = Vect.get v v2 in
725 if b =/ Q.zero then None
726 else if Int.equal (Q.sign a * Q.sign b) (-1) then
727 let cv1 = Q.abs b and cv2 = Q.abs a in
728 Some (xpivot cv1 cv2)
729 else
730 let cv1 = Q.neg (b */ Q.of_int (Q.sign a)) and cv2 = Q.abs a in
731 Some (xpivot cv1 cv2)
732
733 let pivot v c1 c2 =
734 let res = pivot v c1 c2 in
735 ( match res with
736 | None -> ()
737 | Some (c, _) ->
738 if Vect.get v c.coeffs =/ Q.zero then ()
739 else Printf.printf "pivot error %a\n" output_cstr c );
740 res
741
742
743 (** [ext_gcd a b] is the extended Euclid algorithm.
744 [ext_gcd a b = (x,y,g)] iff [ax+by=g]
745 Source: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
746 *)
747 let rec ext_gcd a b =
748 if Int.equal (Z_.sign b) 0 then (Z_.one, Z_.zero)
749 else
750 let q, r = Z_.quomod a b in
751 let s, t = ext_gcd b r in
752 (t, Z_.sub s (Z_.mul q t))
753
754 let extract_coprime (c1, p1) (c2, p2) =
755 let () = assert (c1.op == Eq) in
756 if c2.op == Eq then
757 Vect.exists2
758 (fun n1 n2 ->
759 Int.equal (Z_.compare (Z_.gcd (Q.num n1) (Q.num n2)) Z_.one) 0)
760 c1.coeffs c2.coeffs
761 else None
762
763 let extract_coprime_equation psys =
764 let rec xextract2 rl l =
765 match l with
766 | [] -> (None, rl) (* Did not find *)
767 | e :: l ->
768 match (fst e).op with
769 | Eq ->
770 begin match extract (extract_coprime e) l with
771 | None, _ -> xextract2 (e :: rl) l
772 | Some (r, e'), l' -> (Some (r, e, e'), List.rev_append rl l')
773 end
774 | Gt | Ge -> xextract2 (e :: rl) l
775 in
776 xextract2 [] psys
777
778 let pivot_sys v (cstr, prf) psys =
779 let a = Vect.get v cstr.coeffs in
780 if a =/ Q.zero then List.rev psys
781 else apply_and_normalise check_int_sat (pivot v (a, cstr, prf)) psys
782
783 let reduce_coprime psys =
784 let oeq, sys = extract_coprime_equation psys in
785 match oeq with
786 | None -> None (* Nothing to do *)
787 | Some ((v, n1, n2), (c1, p1), (c2, p2)) ->
788 let l1, l2 = ext_gcd (Q.num n1) (Q.num n2) in
789 let l1' = Q.of_bigint l1 and l2' = Q.of_bigint l2 in
790 let cstr =
791 { coeffs = Vect.add (Vect.mul l1' c1.coeffs) (Vect.mul l2' c2.coeffs)
792 ; op = Eq
793 ; cst = (l1' */ c1.cst) +/ (l2' */ c2.cst) }
794 in
795 let prf =
796 ProofFormat.add_proof
797 (ProofFormat.mul_cst_proof l1' p1)
798 (ProofFormat.mul_cst_proof l2' p2)
799 in
800 Some (pivot_sys v (cstr, prf) ((c1, p1) :: sys))
801
802 (*let pivot_sys v pc sys = tr_cstr_sys "pivot_sys" (pivot_sys v pc) sys*)
803
804 (** If there is an equation [eq] of the form 1.x + e = c, do a pivot over x with equation [eq] *)
805 let reduce_unary psys =
806 let is_unary_equation (cstr, prf) =
807 if cstr.op == Eq then
808 Vect.find
809 (fun v n -> if n =/ Q.one || n =/ Q.minus_one then Some v else None)
810 cstr.coeffs
811 else None
812 in
813 let oeq, sys = extract is_unary_equation psys in
814 match oeq with
815 | None -> None (* Nothing to do *)
816 | Some (v, (cstr, prf)) ->
817 let () = assert (cstr.op == Eq) in
818 Some (pivot_sys v (cstr, prf) sys)
819
820 let reduce_var_change psys =
821 let rec rel_prime vect =
822 match Vect.choose vect with
823 | None -> None
824 | Some (x, v, vect) -> (
825 let v = Q.num v in
826 match
827 Vect.find
828 (fun x' v' ->
829 let v' = Q.num v' in
830 if Z_.equal (Z_.gcd v v') Z_.one then Some (x', v') else None)
831 vect
832 with
833 | Some (x', v') -> Some ((x, v), (x', v'))
834 | None -> rel_prime vect )
835 in
836 let rel_prime (cstr, prf) =
837 if cstr.op == Eq then rel_prime cstr.coeffs else None
838 in
839 let oeq, sys = extract rel_prime psys in
840 match oeq with
841 | None -> None
842 | Some (((x, v), (x', v')), (c, p)) ->
843 let l1, l2 = ext_gcd v v' in
844 let l1, l2 = (Q.of_bigint l1, Q.of_bigint l2) in
845 let pivot_eq (c', p') =
846 let {coeffs; op; cst} = c' in
847 let vx = Vect.get x coeffs in
848 let vx' = Vect.get x' coeffs in
849 let m = Q.neg ((vx */ l1) +/ (vx' */ l2)) in
850 Some
851 ( { coeffs = Vect.add (Vect.mul m c.coeffs) coeffs
852 ; op
853 ; cst = (m */ c.cst) +/ cst }
854 , ProofFormat.add_proof (ProofFormat.mul_cst_proof m p) p' )
855 in
856 Some (apply_and_normalise check_int_sat pivot_eq sys)
857
858 let reduction_equations psys =
859 iterate_until_stable
860 (app_funs
861 [reduce_unary; reduce_coprime; reduce_var_change (*; reduce_pivot*)])
862 psys
863
864 let reduction_equations = tr_cstr_sys "reduction_equations" reduction_equations
865
866 open ProofFormat
867
868 let xlia env sys =
869 let sys = make_cstr_system sys in
870 match reduction_equations sys with
871 | sys ->
872 let sys = List.map WithProof.of_cstr sys in
873 begin match Simplex.integer_solver sys with
874 | None -> Unknown
875 | Some prf -> Prf (compile_proof env prf)
876 end
877 | exception FoundProof prf ->
878 Prf (compile_proof env (Step (0, prf, Done)))
879
880
881 let gen_bench (tac, prover) prfdepth sys =
882 let res = prover prfdepth sys in
883 ( match dump_file () with
884 | None -> ()
885 | Some file ->
886 let o = open_out (Filename.temp_file ~temp_dir:(Sys.getcwd ()) file ".v") in
887 let _, sys = develop_constraints prfdepth z_spec sys in
888 Printf.fprintf o "Require Import ZArith Lia. Open Scope Z_scope.\n";
889 Printf.fprintf o "Goal %a.\n" (LinPoly.pp_goal "Z") (List.map (fun wp -> fst @@ WithProof.repr wp) sys);
890 begin
891 match res with
892 | Unknown | Model _ ->
893 Printf.fprintf o "Proof.\n intros. Fail %s.\nAbort.\n" tac
894 | Prf res -> Printf.fprintf o "Proof.\n intros. %s.\nQed.\n" tac
895 end;
896 flush o; close_out o );
897 res
898
899 let normalise sys =
900 List.fold_left
901 (fun acc s ->
902 match WithProof.cutting_plane s with
903 | None -> s :: acc
904 | Some s' -> s' :: acc)
905 [] sys
906
907 let normalise = tr_sys "normalise" normalise
908
909
910 (** [fourier_small] performs some variable elimination and keeps the cutting planes.
911 To decide which elimination to perform, the constraints are sorted according to
912 1 - the number of variables
913 2 - the value of the smallest coefficient
914 Given the smallest constraint, we eliminate the variable with the smallest coefficient.
915 The rational is that a constraint with a single variable provides some bound information.
916 When there are several variables, we hope to eliminate all the variables.
917 A necessary condition is to take the variable with the smallest coefficient *)
918
919 let try_pivot qx wp wp' =
920 match WithProof.simple_pivot qx wp wp' with
921 | None -> None
922 | Some wp2 ->
923 match WithProof.cutting_plane wp2 with
924 | Some wp2 -> Some wp2
925 | None -> None
926
927 let fourier_small (sys : WithProof.t list) =
928 let module WPset = Set.Make(WithProof) in
929 let gen_pivot acc qx wp l =
930 let fold acc wp' =
931 match try_pivot qx wp wp' with
932 | None -> acc
933 | Some wp2 -> WPset.add wp2 acc
934 in
935 let acc = WPset.fold (fun wp acc -> fold acc wp) acc acc in
936 List.fold_left (fun acc (_,wp') -> fold acc wp') acc l
937 in
938 let rec all_pivots acc l =
939 match l with
940 | [] -> acc
941 | ((_, qx), wp) :: l' -> all_pivots (gen_pivot acc qx wp l') l'
942 in
943 let sys = WithProof.sort sys in
944 let res = all_pivots WPset.empty sys in
945 WPset.elements res
946
947 let fourier_small = tr_sys "fourier_small" fourier_small
948
949 (** [propagate_bounds sys] generate new constraints by exploiting bounds.
950 A bound is a constraint of the form c + a.x >= 0
951 *)
952
953 let rev_concat l =
954 let rec conc acc l =
955 match l with [] -> acc | l1 :: lr -> conc (List.rev_append l1 acc) lr
956 in
957 conc [] l
958
959 let pre_process sys =
960 let sys = normalise sys in
961 let bnd1 = bound_monomials sys in
962 let sys1 = normalise (subst (List.rev_append sys bnd1)) in
963 let pbnd1 = fourier_small sys1 in
964 let sys2 = elim_redundant (List.rev_append pbnd1 sys1) in
965 let bnd2 = bound_monomials sys2 in
966 (* Should iterate ? *)
967 let sys =
968 rev_concat [bnd2; saturate_by_linear_equalities sys2; sys2]
969 in
970 sys
971
972 let lia (prfdepth : int) sys =
973 let env, sys = develop_constraints prfdepth z_spec sys in
974 if debug then begin
975 Printf.fprintf stdout "Input problem\n";
976 List.iter (fun s -> Printf.fprintf stdout "%a\n" WithProof.output s) sys;
977 Printf.fprintf stdout "Input problem\n";
978 let string_of_op = function Eq -> "=" | Ge -> ">=" | Gt -> ">" in
979 List.iter
980 (fun wp ->
981 let ((p, op), _) = WithProof.repr wp in
982 Printf.fprintf stdout "(assert (%s %a))\n" (string_of_op op) Vect.pp_smt
983 p)
984 sys
985 end;
986 let sys = pre_process sys in
987 xlia env sys
988
989 let nlia prfdepth sys =
990 let env, sys = develop_constraints prfdepth z_spec sys in
991 let is_linear = List.for_all (fun wp -> LinPoly.is_linear @@ WithProof.polynomial wp) sys in
992 if debug then begin
993 Printf.fprintf stdout "Input problem\n";
994 List.iter (fun s -> Printf.fprintf stdout "%a\n" WithProof.output s) sys
995 end;
996 if is_linear then
997 xlia env (pre_process sys)
998 else
999 (*
1000 let sys1 = elim_every_substitution sys in
1001 No: if a wrong equation is chosen, the proof may fail.
1002 It would only be safe if the variable is linear...
1003 *)
1004 let sys1 =
1005 normalise
1006 (elim_simple_linear_equality (WithProof.subst_constant true sys))
1007 in
1008 let bnd1 = bound_monomials sys1 in
1009 let sys2 = saturate_by_linear_equalities sys1 in
1010 let sys3 = nlinear_preprocess (rev_concat [bnd1; sys1; sys2]) in
1011 xlia env sys3
1012
1013 (* For regression testing, if bench = true generate a Rocq goal *)
1014
1015 let lia prfdepth sys = gen_bench ("lia", lia) prfdepth sys
1016 let nlia prfdepth sys = gen_bench ("nia", nlia) prfdepth sys
1017
1018 (* Local Variables: *)
1019 (* coding: utf-8 *)
1020 (* End: *)