]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/paramodulation/saturation.ml
removed first Cic.term from type equality, added an int (weight of the equality)
[helm.git] / helm / ocaml / paramodulation / saturation.ml
1 open Inference;;
2 open Utils;;
3
4
5 (* profiling statistics... *)
6 let infer_time = ref 0.;;
7 let forward_simpl_time = ref 0.;;
8 let forward_simpl_new_time = ref 0.;;
9 let backward_simpl_time = ref 0.;;
10 let passive_maintainance_time = ref 0.;;
11
12 (* limited-resource-strategy related globals *)
13 let processed_clauses = ref 0;; (* number of equalities selected so far... *)
14 let time_limit = ref 0.;; (* in seconds, settable by the user... *)
15 let start_time = ref 0.;; (* time at which the execution started *)
16 let elapsed_time = ref 0.;;
17 (* let maximal_weight = ref None;; *)
18 let maximal_retained_equality = ref None;;
19
20 (* equality-selection related globals *)
21 let use_fullred = ref false;;
22 let weight_age_ratio = ref 0;; (* settable by the user from the command line *)
23 let weight_age_counter = ref !weight_age_ratio;;
24 let symbols_ratio = ref 0;;
25 let symbols_counter = ref 0;;
26
27 (* statistics... *)
28 let derived_clauses = ref 0;;
29 let kept_clauses = ref 0;;
30
31 (* index of the greatest Cic.Meta created - TODO: find a better way! *)
32 let maxmeta = ref 0;;
33
34
35 type result =
36   | Failure
37   | Success of Inference.equality option * environment
38 ;;
39
40
41 (*
42 let symbols_of_equality (_, (_, left, right), _, _) =
43   TermSet.union (symbols_of_term left) (symbols_of_term right)
44 ;;
45 *)
46
47 let symbols_of_equality ((_, (_, left, right, _), _, _) as equality) =
48   let m1 = symbols_of_term left in
49   let m = 
50     TermMap.fold
51       (fun k v res ->
52          try
53            let c = TermMap.find k res in
54            TermMap.add k (c+v) res
55          with Not_found ->
56            TermMap.add k v res)
57       (symbols_of_term right) m1
58   in
59 (*   Printf.printf "symbols_of_equality %s:\n" *)
60 (*     (string_of_equality equality); *)
61 (*   TermMap.iter (fun k v -> Printf.printf "%s: %d\n" (CicPp.ppterm k) v) m; *)
62 (*   print_newline (); *)
63   m
64 ;;
65
66
67 module OrderedEquality = struct
68   type t = Inference.equality
69
70   let compare eq1 eq2 =
71     match meta_convertibility_eq eq1 eq2 with
72     | true -> 0
73     | false ->
74         let w1, (ty, left, right, _), _, a = eq1
75         and w2, (ty', left', right', _), _, a' = eq2 in
76 (*         let weight_of t = fst (weight_of_term ~consider_metas:false t) in *)
77 (*         let w1 = (weight_of ty) + (weight_of left) + (weight_of right) *)
78 (*         and w2 = (weight_of ty') + (weight_of left') + (weight_of right') in *)
79         match Pervasives.compare w1 w2 with
80         | 0 ->
81             let res = (List.length a) - (List.length a') in
82             if res <> 0 then res else (
83               try
84                 let res = Pervasives.compare (List.hd a) (List.hd a') in
85                 if res <> 0 then res else Pervasives.compare eq1 eq2
86               with _ -> Pervasives.compare eq1 eq2
87 (*               match a, a' with *)
88 (*               | (Cic.Meta (i, _)::_), (Cic.Meta (j, _)::_) -> *)
89 (*                   let res = Pervasives.compare i j in *)
90 (*                   if res <> 0 then res else Pervasives.compare eq1 eq2 *)
91 (*               | _, _ -> Pervasives.compare eq1 eq2 *)
92             )
93         | res -> res
94 end
95
96 module EqualitySet = Set.Make(OrderedEquality);;
97
98
99 let select env passive (active, _) =
100   processed_clauses := !processed_clauses + 1;
101   
102   let (neg_list, neg_set), (pos_list, pos_set), passive_table = passive in
103   let remove eq l =
104     List.filter (fun e -> e <> eq) l
105   in
106   if !weight_age_ratio > 0 then
107     weight_age_counter := !weight_age_counter - 1;
108   match !weight_age_counter with
109   | 0 -> (
110       weight_age_counter := !weight_age_ratio;
111       match neg_list, pos_list with
112       | hd::tl, pos ->
113           (* Negatives aren't indexed, no need to remove them... *)
114           (Negative, hd),
115           ((tl, EqualitySet.remove hd neg_set), (pos, pos_set), passive_table)
116       | [], hd::tl ->
117           let passive_table =
118             Indexing.remove_index passive_table hd
119 (*             if !use_fullred then Indexing.remove_index passive_table hd *)
120 (*             else passive_table *)
121           in
122           (Positive, hd),
123           (([], neg_set), (tl, EqualitySet.remove hd pos_set), passive_table)
124       | _, _ -> assert false
125     )
126   | _ when (!symbols_counter > 0) && (EqualitySet.is_empty neg_set) -> (
127       symbols_counter := !symbols_counter - 1;
128       let cardinality map =
129         TermMap.fold (fun k v res -> res + v) map 0
130       in
131       match active with
132       | (Negative, e)::_ ->
133           let symbols = symbols_of_equality e in
134           let card = cardinality symbols in
135           let foldfun k v (r1, r2) = 
136             if TermMap.mem k symbols then
137               let c = TermMap.find k symbols in
138               let c1 = abs (c - v) in
139               let c2 = v - c1 in
140               r1 + c2, r2 + c1
141             else
142               r1, r2 + v
143           in
144           let f equality (i, e) =
145             let common, others =
146               TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
147             in
148             let c = others + (abs (common - card)) in
149             if c < i then (c, equality)
150 (*             else if c = i then *)
151 (*               match OrderedEquality.compare equality e with *)
152 (*               | -1 -> (c, equality) *)
153 (*               | res -> (i, e) *)
154             else (i, e)
155           in
156           let e1 = EqualitySet.min_elt pos_set in
157           let initial =
158             let common, others = 
159               TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
160             in
161             (others + (abs (common - card))), e1
162           in
163           let _, current = EqualitySet.fold f pos_set initial in
164 (*           Printf.printf "\nsymbols-based selection: %s\n\n" *)
165 (*             (string_of_equality ~env current); *)
166           let passive_table =
167             Indexing.remove_index passive_table current
168 (*             if !use_fullred then Indexing.remove_index passive_table current *)
169 (*             else passive_table *)
170           in
171           (Positive, current),
172           (([], neg_set),
173            (remove current pos_list, EqualitySet.remove current pos_set),
174            passive_table)
175       | _ ->
176           let current = EqualitySet.min_elt pos_set in
177           let passive_table =
178             Indexing.remove_index passive_table current
179 (*             if !use_fullred then Indexing.remove_index passive_table current *)
180 (*             else passive_table *)
181           in
182           let passive =
183             (neg_list, neg_set),
184             (remove current pos_list, EqualitySet.remove current pos_set),
185             passive_table
186           in
187           (Positive, current), passive
188     )
189   | _ ->
190       symbols_counter := !symbols_ratio;
191       let set_selection set = EqualitySet.min_elt set in
192       if EqualitySet.is_empty neg_set then
193         let current = set_selection pos_set in
194         let passive =
195           (neg_list, neg_set),
196           (remove current pos_list, EqualitySet.remove current pos_set),
197           Indexing.remove_index passive_table current
198 (*           if !use_fullred then Indexing.remove_index passive_table current *)
199 (*           else passive_table *)
200         in
201         (Positive, current), passive
202       else
203         let current = set_selection neg_set in
204         let passive =
205           (remove current neg_list, EqualitySet.remove current neg_set),
206           (pos_list, pos_set),
207           passive_table
208         in
209         (Negative, current), passive
210 ;;
211
212
213 let make_passive neg pos =
214   let set_of equalities =
215     List.fold_left (fun s e -> EqualitySet.add e s) EqualitySet.empty equalities
216   in
217   let table =
218       List.fold_left (fun tbl e -> Indexing.index tbl e)
219         (Indexing.empty_table ()) pos
220 (*     if !use_fullred then *)
221 (*       List.fold_left (fun tbl e -> Indexing.index tbl e) *)
222 (*         (Indexing.empty_table ()) pos *)
223 (*     else *)
224 (*       Indexing.empty_table () *)
225   in
226   (neg, set_of neg),
227   (pos, set_of pos),
228   table
229 ;;
230
231
232 let make_active () =
233   [], Indexing.empty_table () 
234 ;;
235
236
237 let add_to_passive passive (new_neg, new_pos) =
238   let (neg_list, neg_set), (pos_list, pos_set), table = passive in
239   let ok set equality = not (EqualitySet.mem equality set) in
240   let neg = List.filter (ok neg_set) new_neg
241   and pos = List.filter (ok pos_set) new_pos in
242   let table =
243       List.fold_left (fun tbl e -> Indexing.index tbl e) table pos
244 (*     if !use_fullred then *)
245 (*       List.fold_left (fun tbl e -> Indexing.index tbl e) table pos *)
246 (*     else *)
247 (*       table *)
248   in
249   let add set equalities =
250     List.fold_left (fun s e -> EqualitySet.add e s) set equalities
251   in
252   (neg @ neg_list, add neg_set neg),
253   (pos_list @ pos, add pos_set pos),
254   table
255 ;;
256
257
258 let passive_is_empty = function
259   | ([], _), ([], _), _ -> true
260   | _ -> false
261 ;;
262
263
264 let size_of_passive ((_, ns), (_, ps), _) =
265   (EqualitySet.cardinal ns) + (EqualitySet.cardinal ps)
266 ;;
267
268
269 let size_of_active (active_list, _) =
270   List.length active_list
271 ;;
272
273
274 let prune_passive howmany (active, _) passive =
275   let (nl, ns), (pl, ps), tbl = passive in
276   let howmany = float_of_int howmany
277   and ratio = float_of_int !weight_age_ratio in
278   let in_weight = int_of_float (howmany *. ratio /. (ratio +. 1.))
279   and in_age = int_of_float (howmany /. (ratio +. 1.)) in 
280   Printf.printf "in_weight: %d, in_age: %d\n" in_weight in_age;
281   let symbols, card =
282     match active with
283     | (Negative, e)::_ ->
284         let symbols = symbols_of_equality e in
285         let card = TermMap.fold (fun k v res -> res + v) symbols 0 in
286         Some symbols, card
287     | _ -> None, 0
288   in
289   let counter = ref !symbols_ratio in
290   let rec pickw w ns ps =
291     if w > 0 then
292       if not (EqualitySet.is_empty ns) then
293         let e = EqualitySet.min_elt ns in
294         let ns', ps = pickw (w-1) (EqualitySet.remove e ns) ps in
295         EqualitySet.add e ns', ps
296       else if !counter > 0 then
297         let _ =
298           counter := !counter - 1;
299           if !counter = 0 then counter := !symbols_ratio
300         in
301         match symbols with
302         | None ->
303             let e = EqualitySet.min_elt ps in
304             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
305             ns, EqualitySet.add e ps'
306         | Some symbols ->
307             let foldfun k v (r1, r2) =
308               if TermMap.mem k symbols then
309                 let c = TermMap.find k symbols in
310                 let c1 = abs (c - v) in
311                 let c2 = v - c1 in
312                 r1 + c2, r2 + c1
313               else
314                 r1, r2 + v
315             in
316             let f equality (i, e) =
317               let common, others =
318                 TermMap.fold foldfun (symbols_of_equality equality) (0, 0)
319               in
320               let c = others + (abs (common - card)) in
321               if c < i then (c, equality)
322               else (i, e)
323             in
324             let e1 = EqualitySet.min_elt ps in
325             let initial =
326               let common, others = 
327                 TermMap.fold foldfun (symbols_of_equality e1) (0, 0)
328               in
329               (others + (abs (common - card))), e1
330             in
331             let _, e = EqualitySet.fold f ps initial in
332             let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
333             ns, EqualitySet.add e ps'
334       else
335         let e = EqualitySet.min_elt ps in
336         let ns, ps' = pickw (w-1) ns (EqualitySet.remove e ps) in
337         ns, EqualitySet.add e ps'        
338     else
339       EqualitySet.empty, EqualitySet.empty
340   in
341 (*   let in_weight, ns = pickw in_weight ns in *)
342 (*   let _, ps = pickw in_weight ps in *)
343   let ns, ps = pickw in_weight ns ps in
344   let rec picka w s l =
345     if w > 0 then
346       match l with
347       | [] -> w, s, []
348       | hd::tl when not (EqualitySet.mem hd s) ->
349           let w, s, l = picka (w-1) s tl in
350           w, EqualitySet.add hd s, hd::l
351       | hd::tl ->
352           let w, s, l = picka w s tl in
353           w, s, hd::l
354     else
355       0, s, l
356   in
357   let in_age, ns, nl = picka in_age ns nl in
358   let _, ps, pl = picka in_age ps pl in
359   if not (EqualitySet.is_empty ps) then
360 (*     maximal_weight := Some (weight_of_equality (EqualitySet.max_elt ps)); *)
361     maximal_retained_equality := Some (EqualitySet.max_elt ps);
362   let tbl =
363     EqualitySet.fold
364       (fun e tbl -> Indexing.index tbl e) ps (Indexing.empty_table ())
365 (*     if !use_fullred then *)
366 (*       EqualitySet.fold *)
367 (*         (fun e tbl -> Indexing.index tbl e) ps (Indexing.empty_table ()) *)
368 (*     else *)
369 (*       tbl *)
370   in
371   (nl, ns), (pl, ps), tbl  
372 ;;
373
374
375 let infer env sign current (active_list, active_table) =
376   let new_neg, new_pos = 
377     match sign with
378     | Negative ->
379         Indexing.superposition_left env active_table current, []
380     | Positive ->
381         let maxm, res =
382           Indexing.superposition_right !maxmeta env active_table current in
383         maxmeta := maxm;
384         let rec infer_positive table = function
385           | [] -> [], []
386           | (Negative, equality)::tl ->
387               let res = Indexing.superposition_left env table equality in
388               let neg, pos = infer_positive table tl in
389               res @ neg, pos
390           | (Positive, equality)::tl ->
391               let maxm, res =
392                 Indexing.superposition_right !maxmeta env table equality in
393               maxmeta := maxm;
394               let neg, pos = infer_positive table tl in
395               neg, res @ pos
396         in
397         let curr_table = Indexing.index (Indexing.empty_table ()) current in
398         let neg, pos = infer_positive curr_table active_list in
399         neg, res @ pos
400   in
401   derived_clauses := !derived_clauses + (List.length new_neg) +
402     (List.length new_pos);
403   match (* !maximal_weight *)!maximal_retained_equality with
404   | None -> new_neg, new_pos
405   | Some (* w *) eq ->
406       let new_pos =
407         List.filter (fun e -> (* (weight_of_equality e) <= w *) OrderedEquality.compare e eq <= 0) new_pos in
408       new_neg, new_pos
409 ;;
410
411
412 let contains_empty env (negative, positive) =
413   let metasenv, context, ugraph = env in
414   try
415     let found =
416       List.find
417         (fun (proof, (ty, left, right, ordering), m, a) ->
418            fst (CicReduction.are_convertible context left right ugraph))
419         negative
420     in
421     true, Some found
422   with Not_found ->
423     false, None
424 ;;
425
426
427 let forward_simplify env (sign, current) ?passive (active_list, active_table) =
428   let pl, passive_table =
429     match passive with
430     | None -> [], None
431     | Some ((pn, _), (pp, _), pt) ->
432         let pn = List.map (fun e -> (Negative, e)) pn
433         and pp = List.map (fun e -> (Positive, e)) pp in
434         pn @ pp, Some pt
435   in
436   let all = if pl = [] then active_list else active_list @ pl in
437
438 (*   let rec find_duplicate sign current = function *)
439 (*     | [] -> false *)
440 (*     | (s, eq)::tl when s = sign -> *)
441 (*         if meta_convertibility_eq current eq then true *)
442 (*         else find_duplicate sign current tl *)
443 (*     | _::tl -> find_duplicate sign current tl *)
444 (*   in *)
445
446 (*   let res =  *)
447 (*     if sign = Positive then *)
448 (*       Indexing.subsumption env active_table current *)
449 (*     else *)
450 (*       false *)
451 (*   in *)
452 (*   if res then *)
453 (*     None *)
454 (*   else *)
455   
456   let demodulate table current = 
457     let newmeta, newcurrent =
458       Indexing.demodulation !maxmeta env table current in
459     maxmeta := newmeta;
460     if is_identity env newcurrent then
461       if sign = Negative then Some (sign, newcurrent)
462       else (Inference.delete_proof newcurrent; None)
463     else
464       Some (sign, newcurrent)
465   in
466   let res =
467     let res = demodulate active_table current in
468     match res with
469     | None -> None
470     | Some (sign, newcurrent) ->
471         match passive_table with
472         | None -> res
473         | Some passive_table -> demodulate passive_table newcurrent
474   in
475   match res with
476   | None -> None
477   | Some (Negative, c) ->
478       let ok = not (
479         List.exists
480           (fun (s, eq) -> s = Negative && meta_convertibility_eq eq c)
481           all)
482       in
483       if ok then res else None
484   | Some (Positive, c) ->
485       if Indexing.in_index active_table c then
486         (Inference.delete_proof c; None)
487       else
488         match passive_table with
489         | None -> res
490         | Some passive_table ->
491             if Indexing.in_index passive_table c then
492               (Inference.delete_proof c; None)
493             else res
494
495 (*   | Some (s, c) -> if find_duplicate s c all then None else res *)
496
497 (*         if s = Utils.Negative then *)
498 (*           res *)
499 (*         else *)
500 (*           if Indexing.subsumption env active_table c then *)
501 (*             None *)
502 (*           else ( *)
503 (*             match passive_table with *)
504 (*             | None -> res *)
505 (*             | Some passive_table -> *)
506 (*                 if Indexing.subsumption env passive_table c then *)
507 (*                   None *)
508 (*                 else *)
509 (*                   res *)
510 (*           ) *)
511
512 (*         let pred (sign, eq) = *)
513 (*           if sign <> s then false *)
514 (*           else subsumption env c eq *)
515 (*         in *)
516 (*         if List.exists pred all then None *)
517 (*         else res *)
518 ;;
519
520 type fs_time_info_t = {
521   mutable build_all: float;
522   mutable demodulate: float;
523   mutable subsumption: float;
524 };;
525
526 let fs_time_info = { build_all = 0.; demodulate = 0.; subsumption = 0. };;
527
528
529 let forward_simplify_new env (new_neg, new_pos) ?passive active =
530   let t1 = Unix.gettimeofday () in
531
532   let active_list, active_table = active in
533   let pl, passive_table =
534     match passive with
535     | None -> [], None
536     | Some ((pn, _), (pp, _), pt) ->
537         let pn = List.map (fun e -> (Negative, e)) pn
538         and pp = List.map (fun e -> (Positive, e)) pp in
539         pn @ pp, Some pt
540   in
541   let all = active_list @ pl in
542   
543   let t2 = Unix.gettimeofday () in
544   fs_time_info.build_all <- fs_time_info.build_all +. (t2 -. t1);
545   
546   let demodulate table target =
547     let newmeta, newtarget = Indexing.demodulation !maxmeta env table target in
548     maxmeta := newmeta;
549     newtarget
550   in
551 (*   let f sign' target (sign, eq) = *)
552 (*     if sign <> sign' then false *)
553 (*     else subsumption env target eq  *)
554 (*   in *)
555
556   let t1 = Unix.gettimeofday () in
557
558   let new_neg, new_pos =
559     let new_neg = List.map (demodulate active_table) new_neg
560     and new_pos = List.map (demodulate active_table) new_pos in
561     match passive_table with
562     | None -> new_neg, new_pos
563     | Some passive_table ->
564         List.map (demodulate passive_table) new_neg,
565         List.map (demodulate passive_table) new_pos
566   in
567
568   let t2 = Unix.gettimeofday () in
569   fs_time_info.demodulate <- fs_time_info.demodulate +. (t2 -. t1);
570
571   let new_pos_set =
572     List.fold_left
573       (fun s e ->
574          if not (Inference.is_identity env e) then
575            if EqualitySet.mem e s then
576              (Inference.delete_proof e; s)
577            else
578              EqualitySet.add e s
579          else
580            (Inference.delete_proof e; s))
581       EqualitySet.empty new_pos
582   in
583   let new_pos = EqualitySet.elements new_pos_set in
584
585   let subs =
586     match passive_table with
587     | None ->
588         (fun e -> not (Indexing.subsumption env active_table e))
589     | Some passive_table ->
590         (fun e -> not ((Indexing.subsumption env active_table e) ||
591                          (Indexing.subsumption env passive_table e)))
592   in
593
594   let t1 = Unix.gettimeofday () in
595
596 (*   let new_neg, new_pos = *)
597 (*     List.filter subs new_neg, *)
598 (*     List.filter subs new_pos *)
599 (*   in *)
600
601 (*   let new_neg, new_pos =  *)
602 (*     (List.filter (fun e -> not (List.exists (f Negative e) all)) new_neg, *)
603 (*      List.filter (fun e -> not (List.exists (f Positive e) all)) new_pos) *)
604 (*   in *)
605
606   let t2 = Unix.gettimeofday () in
607   fs_time_info.subsumption <- fs_time_info.subsumption +. (t2 -. t1);
608
609   let is_duplicate =
610     match passive_table with
611     | None ->
612         (fun e ->
613            let ok = not (Indexing.in_index active_table e) in
614            if not ok then Inference.delete_proof e;
615            ok)
616     | Some passive_table ->
617         (fun e ->
618            let ok = not ((Indexing.in_index active_table e) ||
619                            (Indexing.in_index passive_table e)) in
620            if not ok then Inference.delete_proof e;
621            ok)
622   in
623   new_neg, List.filter is_duplicate new_pos
624
625 (*   new_neg, new_pos *)
626
627 (*   let res = *)
628 (*     (List.filter (fun e -> not (List.exists (f Negative e) all)) new_neg, *)
629 (*      List.filter (fun e -> not (List.exists (f Positive e) all)) new_pos) *)
630 (*   in *)
631 (*   res *)
632 ;;
633
634
635 let backward_simplify_active env new_pos new_table active =
636   let active_list, active_table = active in
637   let active_list, newa = 
638     List.fold_right
639       (fun (s, equality) (res, newn) ->
640          match forward_simplify env (s, equality) (new_pos, new_table) with
641          | None -> res, newn
642          | Some (s, e) ->
643              if equality = e then
644                (s, e)::res, newn
645              else 
646                res, (s, e)::newn)
647       active_list ([], [])
648   in
649   let find eq1 where =
650     List.exists (fun (s, e) -> meta_convertibility_eq eq1 e) where
651   in
652   let active, newa =
653     List.fold_right
654       (fun (s, eq) (res, tbl) ->
655          if List.mem (s, eq) res then
656            res, tbl
657          else if (is_identity env eq) || (find eq res) then (
658            Inference.delete_proof eq;
659            res, tbl
660          ) (* else if (find eq res) then *)
661 (*            res, tbl *)
662          else
663            (s, eq)::res, if s = Negative then tbl else Indexing.index tbl eq)
664       active_list ([], Indexing.empty_table ()),
665     List.fold_right
666       (fun (s, eq) (n, p) ->
667          if (s <> Negative) && (is_identity env eq) then (
668            Inference.delete_proof eq;
669            (n, p)
670          ) else
671            if s = Negative then eq::n, p
672            else n, eq::p)
673       newa ([], [])
674   in
675   match newa with
676   | [], [] -> active, None
677   | _ -> active, Some newa
678 ;;
679
680
681 let backward_simplify_passive env new_pos new_table passive =
682   let (nl, ns), (pl, ps), passive_table = passive in
683   let f sign equality (resl, ress, newn) =
684     match forward_simplify env (sign, equality) (new_pos, new_table) with
685     | None -> resl, EqualitySet.remove equality ress, newn
686     | Some (s, e) ->
687         if equality = e then
688           equality::resl, ress, newn
689         else
690           let ress = EqualitySet.remove equality ress in
691           resl, ress, e::newn
692   in
693   let nl, ns, newn = List.fold_right (f Negative) nl ([], ns, [])
694   and pl, ps, newp = List.fold_right (f Positive) pl ([], ps, []) in
695   let passive_table =
696     List.fold_left
697       (fun tbl e -> Indexing.index tbl e) (Indexing.empty_table ()) pl
698   in
699   match newn, newp with
700   | [], [] -> ((nl, ns), (pl, ps), passive_table), None
701   | _, _ -> ((nl, ns), (pl, ps), passive_table), Some (newn, newp)
702 ;;
703
704
705 let backward_simplify env new' ?passive active =
706   let new_pos, new_table =
707     List.fold_left
708       (fun (l, t) e -> (Positive, e)::l, Indexing.index t e)
709       ([], Indexing.empty_table ()) (snd new')
710   in    
711   let active, newa = backward_simplify_active env new_pos new_table active in
712   match passive with
713   | None ->
714       active, (make_passive [] []), newa, None
715   | Some passive ->
716       let passive, newp =
717         backward_simplify_passive env new_pos new_table passive in
718       active, passive, newa, newp
719 ;;
720
721
722 let get_selection_estimate () =
723   elapsed_time := (Unix.gettimeofday ()) -. !start_time;
724 (*   !processed_clauses * (int_of_float (!time_limit /. !elapsed_time)) *)
725   int_of_float (
726     ceil ((float_of_int !processed_clauses) *.
727             ((!time_limit (* *. 2. *)) /. !elapsed_time -. 1.)))
728 ;;
729
730   
731 let rec given_clause env passive active =
732   let time1 = Unix.gettimeofday () in
733
734   let selection_estimate = get_selection_estimate () in
735   let kept = size_of_passive passive in
736   let passive =
737     if !time_limit = 0. || !processed_clauses = 0 then
738       passive
739     else if !elapsed_time > !time_limit then (
740       Printf.printf "Time limit (%.2f) reached: %.2f\n"
741         !time_limit !elapsed_time;
742       make_passive [] []
743     ) else if kept > selection_estimate then (
744       Printf.printf ("Too many passive equalities: pruning... (kept: %d, " ^^
745                        "selection_estimate: %d)\n") kept selection_estimate;
746       prune_passive selection_estimate active passive
747     ) else
748       passive
749   in
750
751   let time2 = Unix.gettimeofday () in
752   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
753
754   kept_clauses := (size_of_passive passive) + (size_of_active active);
755     
756   match passive_is_empty passive with
757   | true -> Failure
758   | false ->
759       let (sign, current), passive = select env passive active in
760       let time1 = Unix.gettimeofday () in
761       let res = forward_simplify env (sign, current) ~passive active in
762       let time2 = Unix.gettimeofday () in
763       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
764       match res with
765       | None ->
766           given_clause env passive active
767       | Some (sign, current) ->
768           if (sign = Negative) && (is_identity env current) then (
769             Printf.printf "OK!!! %s %s" (string_of_sign sign)
770               (string_of_equality ~env current);
771             print_newline ();
772             Success (Some current, env)
773           ) else (            
774             print_endline "\n================================================";
775             Printf.printf "selected: %s %s"
776               (string_of_sign sign) (string_of_equality ~env current);
777             print_newline ();
778
779             let t1 = Unix.gettimeofday () in
780             let new' = infer env sign current active in
781             let t2 = Unix.gettimeofday () in
782             infer_time := !infer_time +. (t2 -. t1);
783             
784             let res, goal = contains_empty env new' in
785             if res then
786               Success (goal, env)
787             else 
788               let t1 = Unix.gettimeofday () in
789               let new' = forward_simplify_new env new' (* ~passive *) active in
790               let t2 = Unix.gettimeofday () in
791               let _ =
792                 forward_simpl_new_time := !forward_simpl_new_time +. (t2 -. t1)
793               in
794               let active =
795                 match sign with
796                 | Negative -> active
797                 | Positive ->
798                     let t1 = Unix.gettimeofday () in
799                     let active, _, newa, _ =
800                       backward_simplify env ([], [current]) active
801                     in
802                     let t2 = Unix.gettimeofday () in
803                     backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
804                     match newa with
805                     | None -> active
806                     | Some (n, p) ->
807                         let al, tbl = active in
808                         let nn = List.map (fun e -> Negative, e) n in
809                         let pp, tbl =
810                           List.fold_right
811                             (fun e (l, t) ->
812                                (Positive, e)::l,
813                                Indexing.index tbl e)
814                             p ([], tbl)
815                         in
816                         nn @ al @ pp, tbl
817               in
818 (*               let _ = *)
819 (*                 Printf.printf "active:\n%s\n" *)
820 (*                   (String.concat "\n" *)
821 (*                      ((List.map *)
822 (*                          (fun (s, e) -> (string_of_sign s) ^ " " ^ *)
823 (*                             (string_of_equality ~env e)) (fst active)))); *)
824 (*                 print_newline (); *)
825 (*               in *)
826 (*               let _ = *)
827 (*                 match new' with *)
828 (*                 | neg, pos -> *)
829 (*                     Printf.printf "new':\n%s\n" *)
830 (*                       (String.concat "\n" *)
831 (*                          ((List.map *)
832 (*                              (fun e -> "Negative " ^ *)
833 (*                                 (string_of_equality ~env e)) neg) @ *)
834 (*                             (List.map *)
835 (*                                (fun e -> "Positive " ^ *)
836 (*                                   (string_of_equality ~env e)) pos))); *)
837 (*                     print_newline (); *)
838 (*               in *)
839               match contains_empty env new' with
840               | false, _ -> 
841                   let active =
842                     let al, tbl = active in
843                     match sign with
844                     | Negative -> (sign, current)::al, tbl
845                     | Positive ->
846                         al @ [(sign, current)], Indexing.index tbl current
847                   in
848                   let passive = add_to_passive passive new' in
849 (*                   let (_, ns), (_, ps), _ = passive in *)
850 (*                   Printf.printf "passive:\n%s\n" *)
851 (*                     (String.concat "\n" *)
852 (*                        ((List.map (fun e -> "Negative " ^ *)
853 (*                                      (string_of_equality ~env e)) *)
854 (*                            (EqualitySet.elements ns)) @ *)
855 (*                           (List.map (fun e -> "Positive " ^ *)
856 (*                                        (string_of_equality ~env e)) *)
857 (*                              (EqualitySet.elements ps)))); *)
858 (*                   print_newline (); *)
859                   given_clause env passive active
860               | true, goal ->
861                   Success (goal, env)
862           )
863 ;;
864
865
866 let rec given_clause_fullred env passive active =
867   let time1 = Unix.gettimeofday () in
868   
869   let selection_estimate = get_selection_estimate () in
870   let kept = size_of_passive passive in
871   let passive =
872     if !time_limit = 0. || !processed_clauses = 0 then
873       passive
874     else if !elapsed_time > !time_limit then (
875       Printf.printf "Time limit (%.2f) reached: %.2f\n"
876         !time_limit !elapsed_time;
877       make_passive [] []
878     ) else if kept > selection_estimate then (
879       Printf.printf ("Too many passive equalities: pruning... (kept: %d, " ^^
880                        "selection_estimate: %d)\n") kept selection_estimate;
881       prune_passive selection_estimate active passive
882     ) else
883       passive
884   in
885
886   let time2 = Unix.gettimeofday () in
887   passive_maintainance_time := !passive_maintainance_time +. (time2 -. time1);
888     
889   kept_clauses := (size_of_passive passive) + (size_of_active active);
890
891   match passive_is_empty passive with
892   | true -> Failure
893   | false ->
894       let (sign, current), passive = select env passive active in
895       let time1 = Unix.gettimeofday () in
896       let res = forward_simplify env (sign, current) ~passive active in
897       let time2 = Unix.gettimeofday () in
898       forward_simpl_time := !forward_simpl_time +. (time2 -. time1);
899       match res with
900       | None ->
901           given_clause_fullred env passive active
902       | Some (sign, current) ->
903           if (sign = Negative) && (is_identity env current) then (
904             Printf.printf "OK!!! %s %s" (string_of_sign sign)
905               (string_of_equality ~env current);
906             print_newline ();
907             Success (Some current, env)
908           ) else (
909             print_endline "\n================================================";
910             Printf.printf "selected: %s %s"
911               (string_of_sign sign) (string_of_equality ~env current);
912             print_newline ();
913
914             let t1 = Unix.gettimeofday () in
915             let new' = infer env sign current active in
916             let t2 = Unix.gettimeofday () in
917             infer_time := !infer_time +. (t2 -. t1);
918
919             let active =
920               if is_identity env current then active
921               else
922                 let al, tbl = active in
923                 match sign with
924                 | Negative -> (sign, current)::al, tbl
925                 | Positive -> al @ [(sign, current)], Indexing.index tbl current
926             in
927             let rec simplify new' active passive =
928               let t1 = Unix.gettimeofday () in
929               let new' = forward_simplify_new env new' ~passive active in
930               let t2 = Unix.gettimeofday () in
931               forward_simpl_new_time := !forward_simpl_new_time +. (t2 -. t1);
932               let t1 = Unix.gettimeofday () in
933               let active, passive, newa, retained =
934                 backward_simplify env new' ~passive active in
935               let t2 = Unix.gettimeofday () in
936               backward_simpl_time := !backward_simpl_time +. (t2 -. t1);
937               match newa, retained with
938               | None, None -> active, passive, new'
939               | Some (n, p), None
940               | None, Some (n, p) ->
941                   let nn, np = new' in
942                   simplify (nn @ n, np @ p) active passive
943               | Some (n, p), Some (rn, rp) ->
944                   let nn, np = new' in
945                   simplify (nn @ n @ rn, np @ p @ rp) active passive
946             in
947             let active, passive, new' = simplify new' active passive in
948
949             let k = size_of_passive passive in
950             if k < (kept - 1) then
951               processed_clauses := !processed_clauses + (kept - 1 - k);
952             
953 (*             let _ = *)
954 (*               Printf.printf "active:\n%s\n" *)
955 (*                 (String.concat "\n" *)
956 (*                    ((List.map *)
957 (*                        (fun (s, e) -> (string_of_sign s) ^ " " ^ *)
958 (*                           (string_of_equality ~env e)) (fst active)))); *)
959 (*               print_newline (); *)
960 (*             in *)
961 (*             let _ = *)
962 (*               match new' with *)
963 (*               | neg, pos -> *)
964 (*                   Printf.printf "new':\n%s\n" *)
965 (*                     (String.concat "\n" *)
966 (*                        ((List.map *)
967 (*                            (fun e -> "Negative " ^ *)
968 (*                               (string_of_equality ~env e)) neg) @ *)
969 (*                           (List.map *)
970 (*                              (fun e -> "Positive " ^ *)
971 (*                                 (string_of_equality ~env e)) pos))); *)
972 (*                   print_newline (); *)
973 (*             in *)
974             match contains_empty env new' with
975             | false, _ -> 
976                 let passive = add_to_passive passive new' in
977                 given_clause_fullred env passive active
978             | true, goal ->
979                 Success (goal, env)
980           )
981 ;;
982
983
984 let get_from_user () =
985   let dbd = Mysql.quick_connect
986     ~host:"localhost" ~user:"helm" ~database:"mowgli" () in
987   let rec get () =
988     match read_line () with
989     | "" -> []
990     | t -> t::(get ())
991   in
992   let term_string = String.concat "\n" (get ()) in
993   let env, metasenv, term, ugraph =
994     List.nth (Disambiguate.Trivial.disambiguate_string dbd term_string) 0
995   in
996   term, metasenv, ugraph
997 ;;
998
999
1000 let given_clause_ref = ref given_clause;;
1001
1002
1003 let main () =
1004   let module C = Cic in
1005   let module T = CicTypeChecker in
1006   let module PET = ProofEngineTypes in
1007   let module PP = CicPp in
1008   let term, metasenv, ugraph = get_from_user () in
1009   let proof = None, (1, [], term)::metasenv, C.Meta (1, []), term in
1010   let proof, goals =
1011     PET.apply_tactic (PrimitiveTactics.intros_tac ()) (proof, 1) in
1012   let goal = List.nth goals 0 in
1013   let _, metasenv, meta_proof, _ = proof in
1014   let _, context, goal = CicUtil.lookup_meta goal metasenv in
1015   let equalities, maxm = find_equalities context proof in
1016   maxmeta := maxm; (* TODO ugly!! *)
1017   let env = (metasenv, context, ugraph) in
1018   try
1019     let term_equality = equality_of_term meta_proof goal in
1020     let meta_proof, (eq_ty, left, right, ordering), _, _ = term_equality in
1021     let active = make_active () in
1022     let passive = make_passive [term_equality] equalities in
1023     Printf.printf "\ncurrent goal: %s\n"
1024       (string_of_equality ~env term_equality);
1025     Printf.printf "\ncontext:\n%s\n" (PP.ppcontext context);
1026     Printf.printf "\nmetasenv:\n%s\n" (print_metasenv metasenv);
1027     Printf.printf "\nequalities:\n%s\n"
1028       (String.concat "\n"
1029          (List.map
1030             (string_of_equality ~env)
1031             equalities));
1032     print_endline "--------------------------------------------------";
1033     let start = Unix.gettimeofday () in
1034     print_endline "GO!";
1035     start_time := Unix.gettimeofday ();
1036     let res =
1037       (if !use_fullred then given_clause_fullred else given_clause)
1038         env passive active
1039     in
1040     let finish = Unix.gettimeofday () in
1041     let _ =
1042       match res with
1043       | Failure ->
1044           Printf.printf "NO proof found! :-(\n\n"
1045       | Success (Some goal, env) ->
1046           Printf.printf "OK, found a proof!\n";
1047           let proof = Inference.build_term_proof goal in
1048           print_endline (PP.pp proof (names_of_context context));
1049           print_endline (string_of_float (finish -. start));
1050       | Success (None, env) ->
1051           Printf.printf "Success, but no proof?!?\n\n"
1052     in
1053     Printf.printf ("infer_time: %.9f\nforward_simpl_time: %.9f\n" ^^
1054                      "forward_simpl_new_time: %.9f\n" ^^
1055                      "backward_simpl_time: %.9f\n")
1056       !infer_time !forward_simpl_time !forward_simpl_new_time
1057       !backward_simpl_time;
1058     Printf.printf "passive_maintainance_time: %.9f\n"
1059       !passive_maintainance_time;
1060     Printf.printf "    successful unification/matching time: %.9f\n"
1061       !Indexing.match_unif_time_ok;
1062     Printf.printf "    failed unification/matching time: %.9f\n"
1063       !Indexing.match_unif_time_no;
1064     Printf.printf "    indexing retrieval time: %.9f\n"
1065       !Indexing.indexing_retrieval_time;
1066     Printf.printf "    demodulate_term.build_newtarget_time: %.9f\n"
1067       !Indexing.build_newtarget_time;
1068     Printf.printf "derived %d clauses, kept %d clauses.\n"
1069       !derived_clauses !kept_clauses;
1070   with exc ->
1071     print_endline ("EXCEPTION: " ^ (Printexc.to_string exc));
1072     raise exc
1073 ;;
1074
1075
1076 let configuration_file = ref "../../gTopLevel/gTopLevel.conf.xml";;
1077
1078 let _ =
1079   let set_ratio v = weight_age_ratio := (v+1); weight_age_counter := (v+1)
1080   and set_sel v = symbols_ratio := v; symbols_counter := v;
1081   and set_conf f = configuration_file := f
1082   and set_lpo () = Utils.compare_terms := lpo
1083   and set_kbo () = Utils.compare_terms := nonrec_kbo
1084   and set_fullred () = use_fullred := true
1085   and set_time_limit v = time_limit := float_of_int v
1086   in
1087   Arg.parse [
1088     "-f", Arg.Unit set_fullred, "Use full-reduction strategy";
1089     
1090     "-r", Arg.Int set_ratio, "Weight-Age equality selection ratio (default: 0)";
1091
1092     "-s", Arg.Int set_sel,
1093     "symbols-based selection ratio (relative to the weight ratio)";
1094
1095     "-c", Arg.String set_conf, "Configuration file (for the db connection)";
1096
1097     "-lpo", Arg.Unit set_lpo, "Use lpo term ordering";
1098
1099     "-kbo", Arg.Unit set_kbo, "Use (non-recursive) kbo term ordering (default)";
1100
1101     "-l", Arg.Int set_time_limit, "Time limit (in seconds)";
1102   ] (fun a -> ()) "Usage:"
1103 in
1104 Helm_registry.load_from !configuration_file;
1105 main ()