]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic/cicUniv.ml
FIXED bug, added assertion in case a universe inside a term T living at URI u
[helm.git] / helm / software / components / cic / cicUniv.ml
1 (* Copyright (C) 2000, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (*****************************************************************************)
27 (*                                                                           *)
28 (*                               PROJECT HELM                                *)
29 (*                                                                           *)
30 (*                      Enrico Tassi <tassi@cs.unibo.it>                     *)
31 (*                                 23/04/2004                                *)
32 (*                                                                           *)
33 (* This module implements the aciclic graph of universes.                    *)
34 (*                                                                           *)
35 (*****************************************************************************)
36
37 (* $Id$ *)
38
39 (*****************************************************************************)
40 (** switch implementation                                                   **)
41 (*****************************************************************************)
42
43 let fast_implementation = ref true ;;
44
45 (*****************************************************************************)
46 (** open                                                                    **)
47 (*****************************************************************************)
48
49 open Printf
50
51 (*****************************************************************************)
52 (** Types and default values                                                **)
53 (*****************************************************************************)
54
55 type universe = int * UriManager.uri option 
56     
57 module UniverseType = struct
58   type t = universe
59   let compare = Pervasives.compare
60 end
61   
62 module SOF = Set.Make(UniverseType)
63   
64 type entry = {
65   eq_closure : SOF.t;
66   ge_closure : SOF.t;
67   gt_closure : SOF.t;
68   in_gegt_of   : SOF.t;
69   one_s_eq   : SOF.t;
70   one_s_ge   : SOF.t;
71   one_s_gt   : SOF.t;
72 }
73     
74 module MAL = Map.Make(UniverseType)
75   
76 type arc_type = GE | GT | EQ
77     
78 type bag = entry MAL.t 
79     
80 let empty_entry = {
81   eq_closure=SOF.empty;
82   ge_closure=SOF.empty;
83   gt_closure=SOF.empty;
84   in_gegt_of=SOF.empty;
85   one_s_eq=SOF.empty;
86   one_s_ge=SOF.empty;
87   one_s_gt=SOF.empty;
88 }
89 let empty_bag = MAL.empty
90
91 let are_set_eq s1 s2 = 
92   SOF.equal s1 s2
93
94 let are_entry_eq v1 v2 =
95   (are_set_eq v1.gt_closure v2.gt_closure ) &&
96   (are_set_eq v1.ge_closure v2.ge_closure ) &&
97   (are_set_eq v1.eq_closure v2.eq_closure ) &&
98   (*(are_set_eq v1.in_gegt_of v2.in_gegt_of ) &&*)
99   (are_set_eq v1.one_s_ge v2.one_s_ge ) &&
100   (are_set_eq v1.one_s_gt v2.one_s_gt ) &&
101   (are_set_eq v1.one_s_eq v2.one_s_eq )
102
103 let are_ugraph_eq = MAL.equal are_entry_eq
104
105 (*****************************************************************************)
106 (** Pretty printings                                                        **)
107 (*****************************************************************************)
108
109 let string_of_universe (i,u) = 
110   match u with
111       Some u ->
112         "(" ^ ((string_of_int i) ^ "," ^ (UriManager.string_of_uri u) ^ ")")
113     | None -> "(" ^ (string_of_int i) ^ ",None)"
114
115 let string_of_universe_set l = 
116   SOF.fold (fun x s -> s ^ (string_of_universe x) ^ " ") l ""
117
118 let string_of_node n =
119   "{"^
120   "eq_c: " ^ (string_of_universe_set n.eq_closure) ^ "; " ^ 
121   "ge_c: " ^ (string_of_universe_set n.ge_closure) ^ "; " ^ 
122   "gt_c: " ^ (string_of_universe_set n.gt_closure) ^ "; " ^ 
123   "i_gegt: " ^ (string_of_universe_set n.in_gegt_of) ^ "}\n"
124
125 let string_of_arc (a,u,v) = 
126   (string_of_universe u) ^ " " ^ a ^ " " ^ (string_of_universe v)
127   
128 let string_of_mal m =
129   let rc = ref "" in
130   MAL.iter (fun k v ->  
131     rc := !rc ^ sprintf "%s --> %s" (string_of_universe k) 
132               (string_of_node v)) m;
133   !rc
134
135 let string_of_bag b = 
136   string_of_mal b
137
138 (*****************************************************************************)
139 (** Benchmarking                                                            **)
140 (*****************************************************************************)
141 let time_spent = ref 0.0;;
142 let partial = ref 0.0 ;;
143
144 let reset_spent_time () = time_spent := 0.0;;
145 let get_spent_time () = !time_spent ;;
146 let begin_spending () = ()
147   (*assert (!partial = 0.0);*)
148 (*   partial := Unix.gettimeofday () *)
149 ;;
150
151 let end_spending () = ()
152 (*
153   assert (!partial > 0.0);
154   let interval = (Unix.gettimeofday ()) -. !partial in
155     partial := 0.0;
156     time_spent := !time_spent +. interval
157 *)
158 ;;
159
160
161 (*****************************************************************************)
162 (** Helpers                                                                 **)
163 (*****************************************************************************)
164
165 (* find the repr *)
166 let repr u m =
167   try 
168     MAL.find u m
169   with
170     Not_found -> empty_entry
171     
172 (* FIXME: May be faster if we make it by hand *)
173 let merge_closures f nodes m =  
174   SOF.fold (fun x i -> SOF.union (f (repr x m)) i ) nodes SOF.empty
175
176 \f
177 (*****************************************************************************)
178 (** _fats implementation                                                    **)
179 (*****************************************************************************)
180
181 let rec closure_of_fast ru m =
182   let eq_c = closure_eq_fast ru m in
183   let ge_c = closure_ge_fast ru m in
184   let gt_c = closure_gt_fast ru m in
185     {
186       eq_closure = eq_c;
187       ge_closure = ge_c;
188       gt_closure = gt_c;
189       in_gegt_of = ru.in_gegt_of;
190       one_s_eq = ru.one_s_eq;
191       one_s_ge = ru.one_s_ge;
192       one_s_gt = ru.one_s_gt
193     }
194       
195 and closure_eq_fast ru m = 
196   let eq_c =
197     let j = ru.one_s_eq in
198     let _Uj = merge_closures (fun x -> x.eq_closure) j m in
199     let one_step_eq = ru.one_s_eq in
200       (SOF.union one_step_eq _Uj)
201   in
202     eq_c
203       
204 and closure_ge_fast ru m =
205   let ge_c = 
206     let j = SOF.union ru.one_s_ge (SOF.union ru.one_s_gt ru.one_s_eq) in
207     let _Uj = merge_closures (fun x -> x.ge_closure) j m in
208     let _Ux = j in
209       (SOF.union _Uj _Ux)
210   in
211     ge_c
212       
213 and closure_gt_fast ru m =
214   let gt_c =
215     let j = ru.one_s_gt in
216     let k = ru.one_s_ge in
217     let l = ru.one_s_eq in
218     let _Uj = merge_closures (fun x -> x.ge_closure) j m in
219     let _Uk = merge_closures (fun x -> x.gt_closure) k m in
220     let _Ul = merge_closures (fun x -> x.gt_closure) l m in
221     let one_step_gt = ru.one_s_gt in
222       (SOF.union (SOF.union (SOF.union _Ul one_step_gt) _Uk) _Uj)
223   in
224     gt_c
225       
226 and print_rec_status u ru =
227   print_endline ("Aggiusto " ^ (string_of_universe u) ^ 
228                  "e ottengo questa chiusura\n " ^ (string_of_node ru))
229
230 and adjust_fast u m =
231   let ru = repr u m in
232   let gt_c = closure_gt_fast ru m in
233   let ge_c = closure_ge_fast ru m in
234   let eq_c = closure_eq_fast ru m in
235   let changed_eq = not (are_set_eq eq_c ru.eq_closure) in
236   let changed_gegt = 
237     (not (are_set_eq gt_c ru.gt_closure)) || 
238     (not (are_set_eq ge_c ru.ge_closure))
239   in
240     if ((not changed_gegt) &&  (not changed_eq)) then
241       m
242     else
243       begin
244         let ru' = {
245           eq_closure = eq_c;
246           ge_closure = ge_c;
247           gt_closure = gt_c;
248           in_gegt_of = ru.in_gegt_of;
249           one_s_eq = ru.one_s_eq;
250           one_s_ge = ru.one_s_ge;
251           one_s_gt = ru.one_s_gt}
252         in
253         let m = MAL.add u ru' m in
254         let m =
255             SOF.fold (fun x m -> adjust_fast  x m) 
256               (SOF.union ru'.eq_closure ru'.in_gegt_of) m
257               (* TESI: 
258                    ru'.in_gegt_of m 
259               *)
260         in
261           m (*adjust_fast  u m*)
262       end
263         
264 and add_gt_arc_fast u v m =
265   let ru = repr u m in
266   let ru' = {ru with one_s_gt = SOF.add v ru.one_s_gt} in
267   let m' = MAL.add u ru' m in
268   let rv = repr v m' in
269   let rv' = {rv with in_gegt_of = SOF.add u rv.in_gegt_of} in
270   let m'' = MAL.add v rv' m' in
271     adjust_fast u m''
272       
273 and add_ge_arc_fast u v m =
274   let ru = repr u m in
275   let ru' = { ru with one_s_ge = SOF.add v ru.one_s_ge} in
276   let m' = MAL.add u ru' m in
277   let rv = repr v m' in
278   let rv' = {rv with in_gegt_of = SOF.add u rv.in_gegt_of} in
279   let m'' = MAL.add v rv' m' in
280   adjust_fast u m''
281
282 and add_eq_arc_fast u v m =
283   let ru = repr u m in
284   let rv = repr v m in 
285   let ru' = {ru  with one_s_eq = SOF.add v ru.one_s_eq} in
286   (*TESI: let ru' = {ru' with in_gegt_of = SOF.add v ru.in_gegt_of} in *)
287   let m' = MAL.add u ru' m in
288   let rv' = {rv  with one_s_eq = SOF.add u rv.one_s_eq} in
289   (*TESI: let rv' = {rv' with in_gegt_of = SOF.add u rv.in_gegt_of} in *)
290   let m'' = MAL.add v rv' m' in
291     adjust_fast v (*(adjust_fast u*) m'' (* ) *)
292 ;;
293
294 \f
295 (*****************************************************************************)
296 (** safe implementation                                                     **)
297 (*****************************************************************************)
298
299 let closure_of u m =
300   let ru = repr u m in
301   let eq_c =
302     let j = ru.one_s_eq in
303     let _Uj = merge_closures (fun x -> x.eq_closure) j m in
304     let one_step_eq = ru.one_s_eq in
305             (SOF.union one_step_eq _Uj)
306   in
307   let ge_c = 
308     let j = SOF.union ru.one_s_ge (SOF.union ru.one_s_gt ru.one_s_eq) in
309     let _Uj = merge_closures (fun x -> x.ge_closure) j m in
310     let _Ux = j in
311       (SOF.union _Uj _Ux)
312   in
313   let gt_c =
314     let j = ru.one_s_gt in
315     let k = ru.one_s_ge in
316     let l = ru.one_s_eq in
317     let _Uj = merge_closures (fun x -> x.ge_closure) j m in
318     let _Uk = merge_closures (fun x -> x.gt_closure) k m in
319     let _Ul = merge_closures (fun x -> x.gt_closure) l m in
320     let one_step_gt = ru.one_s_gt in
321       (SOF.union (SOF.union (SOF.union _Ul one_step_gt) _Uk) _Uj)
322   in
323     {
324       eq_closure = eq_c;
325       ge_closure = ge_c;
326       gt_closure = gt_c;
327       in_gegt_of = ru.in_gegt_of;
328       one_s_eq = ru.one_s_eq;
329       one_s_ge = ru.one_s_ge;
330       one_s_gt = ru.one_s_gt
331     }
332
333 let rec simple_adjust m =
334   let m' = 
335     MAL.mapi (fun x _ -> closure_of x m) m
336   in
337     if not (are_ugraph_eq m  m') then(
338       simple_adjust m')
339     else
340       m'
341
342 let add_eq_arc u v m =
343   let ru = repr u m in
344   let rv = repr v m in
345   let ru' = {ru with one_s_eq = SOF.add v ru.one_s_eq} in
346   let m' = MAL.add u ru' m in
347   let rv' = {rv with one_s_eq = SOF.add u rv.one_s_eq} in
348   let m'' = MAL.add v rv' m' in
349     simple_adjust m''
350
351 let add_ge_arc u v m =
352   let ru = repr u m in
353   let ru' = { ru with one_s_ge = SOF.add v ru.one_s_ge} in
354   let m' = MAL.add u ru' m in
355     simple_adjust m'
356
357 let add_gt_arc u v m =
358   let ru = repr u m in
359   let ru' = {ru with one_s_gt = SOF.add v ru.one_s_gt} in
360   let m' = MAL.add u ru' m in
361     simple_adjust m'
362
363 \f
364 (*****************************************************************************)
365 (** Outhern interface, that chooses between _fast and safe                  **)
366 (*****************************************************************************)
367
368 (*                                                                            
369     given the 2 nodes plus the current bag, adds the arc, recomputes the 
370     closures and returns the new map
371 *) 
372 let add_eq fast u v b =
373   if fast then
374     add_eq_arc_fast u v b
375   else
376     add_eq_arc u v b
377
378 (*                                                                            
379     given the 2 nodes plus the current bag, adds the arc, recomputes the 
380     closures and returns the new map
381 *) 
382 let add_ge fast u v b =
383   if fast then
384     add_ge_arc_fast u v b
385   else
386     add_ge_arc u v b
387 (*                                                                            
388     given the 2 nodes plus the current bag, adds the arc, recomputes the 
389     closures and returns the new map
390 *)                                                                            
391 let add_gt fast u v b =
392   if fast then
393     add_gt_arc_fast u v b
394   else
395     add_gt_arc u v b
396
397
398 (*****************************************************************************)
399 (** Other real code                                                         **)
400 (*****************************************************************************)
401
402 exception UniverseInconsistency of string Lazy.t
403
404 let error arc node1 closure_type node2 closure =
405   let s =
406    lazy
407     ("\n  ===== Universe Inconsistency detected =====\n\n" ^
408      "   Unable to add\n" ^ 
409      "\t" ^ (string_of_arc arc) ^ "\n" ^
410      "   cause\n" ^ 
411      "\t" ^ (string_of_universe node1) ^ "\n" ^
412      "   is in the " ^ closure_type ^ " closure\n" ^
413      "\t{" ^ (string_of_universe_set closure) ^ "}\n" ^ 
414      "   of\n" ^ 
415      "\t" ^ (string_of_universe node2) ^ "\n\n" ^
416      "  ===== Universe Inconsistency detected =====\n") in
417   prerr_endline (Lazy.force s);
418   raise (UniverseInconsistency s)
419
420
421 let fill_empty_nodes_with_uri (g, already_contained,o) l uri =
422   let fill_empty_universe u =
423     match u with
424         (i,None) -> (i,Some uri)
425       | (i,Some _) as u -> u
426   in
427   let fill_empty_set s =
428     SOF.fold (fun e s -> SOF.add (fill_empty_universe e) s) s SOF.empty 
429   in
430   let fill_empty_entry e = {
431     eq_closure = (fill_empty_set e.eq_closure) ;
432     ge_closure = (fill_empty_set e.ge_closure) ;
433     gt_closure = (fill_empty_set e.gt_closure) ;
434     in_gegt_of = (fill_empty_set e.in_gegt_of) ;
435     one_s_eq = (fill_empty_set e.one_s_eq) ;
436     one_s_ge = (fill_empty_set e.one_s_ge) ;
437     one_s_gt = (fill_empty_set e.one_s_gt) ;
438   } in  
439   let m = g in
440   let m' = MAL.fold (
441     fun k v m -> 
442       MAL.add (fill_empty_universe k) (fill_empty_entry v) m) m MAL.empty
443   in
444   let l' = List.map fill_empty_universe l in
445     (m', already_contained,o),l'
446
447
448 (*****************************************************************************)
449 (** World interface                                                         **)
450 (*****************************************************************************)
451
452 type universe_graph = bag * UriManager.UriSet.t * bool
453 (* the graph , the cache of already merged ugraphs, oblivion? *)
454
455 let empty_ugraph = empty_bag, UriManager.UriSet.empty, false
456 let oblivion_ugraph = empty_bag, UriManager.UriSet.empty, true
457
458 let current_index_anon = ref (-1)
459 let current_index_named = ref (-1)
460
461 let restart_numbering () = current_index_named := (-1) 
462
463 let fresh ?uri ?id () =
464   let i =
465     match uri,id with
466     | None,None -> 
467         current_index_anon := !current_index_anon + 1;
468         !current_index_anon
469     | None, Some _ -> assert false
470     | Some _, None -> 
471         current_index_named := !current_index_named + 1;
472         !current_index_named
473     | Some _, Some id -> id
474   in
475   (i,uri)
476
477 let name_universe u uri =
478   match u with
479   | (i, None) -> (i, Some uri)
480   | (i, Some ouri) -> 
481       (* inside obj living at uri 'uri' should live only
482        * universes with uri None. Call Unshare.unshare ~fresh_univs:true
483        * if you want to reuse a Type in another object *)
484       prerr_endline ("Offending universe: " ^ string_of_universe u^
485         " found inside object " ^ UriManager.string_of_uri  uri);
486       assert false
487 ;;
488   
489 let print_ugraph (g, _, o) = 
490   if o then prerr_endline "oblivion universe" else
491   prerr_endline (string_of_bag g)
492
493 let add_eq ?(fast=(!fast_implementation)) u v b =
494   (* should we check to no add twice the same?? *)
495   let m = b in
496   let ru = repr u m in
497   if SOF.mem v ru.gt_closure then
498     error ("EQ",u,v) v "GT" u ru.gt_closure
499   else
500     begin
501     let rv = repr v m in
502     if SOF.mem u rv.gt_closure then
503       error ("EQ",u,v) u "GT" v rv.gt_closure
504     else
505       add_eq fast u v b
506     end
507
508 let add_ge ?(fast=(!fast_implementation)) u v b =
509   (* should we check to no add twice the same?? *)
510   let m = b in
511   let rv = repr v m in
512   if SOF.mem u rv.gt_closure then
513     error ("GE",u,v) u "GT" v rv.gt_closure
514   else
515     add_ge fast u v b
516   
517 let add_gt ?(fast=(!fast_implementation)) u v b =
518   (* should we check to no add twice the same?? *)
519   (* 
520      FIXME : check the thesis... no need to check GT and EQ closure since the 
521      GE is a superset of both 
522   *)
523   let m = b in
524   let rv = repr v m in
525
526   if u = v then
527     error ("GT",u,v) u "==" v SOF.empty
528   else
529   
530   (*if SOF.mem u rv.gt_closure then
531     error ("GT",u,v) u "GT" v rv.gt_closure
532   else
533     begin*)
534       if SOF.mem u rv.ge_closure then
535         error ("GT",u,v) u "GE" v rv.ge_closure
536       else
537 (*        begin
538           if SOF.mem u rv.eq_closure then
539             error ("GT",u,v) u "EQ" v rv.eq_closure
540           else*)
541             add_gt fast u v b
542 (*        end
543     end*)
544
545 (*****************************************************************************)
546 (** START: Decomment this for performance comparisons                       **)
547 (*****************************************************************************)
548
549 let add_eq ?(fast=(!fast_implementation))  u v (b,already_contained,oblivion) =
550         if oblivion then (b,already_contained,oblivion) else
551   (*prerr_endline "add_eq";*)
552   (begin_spending ();
553   let rc = add_eq ~fast u v b in
554   end_spending ();
555     rc,already_contained,false)
556
557 let add_ge ?(fast=(!fast_implementation)) u v (b,already_contained,oblivion) =
558         if oblivion then (b,already_contained,oblivion) else
559 (*   prerr_endline "add_ge"; *)
560   (begin_spending ();
561   let rc = add_ge ~fast u v b in
562   end_spending ();
563     rc,already_contained,false)
564     
565 let add_gt ?(fast=(!fast_implementation)) u v (b,already_contained,oblivion) =
566         if oblivion then (b,already_contained,oblivion) else
567 (*   prerr_endline "add_gt"; *)
568   (begin_spending ();
569   let rc = add_gt ~fast u v b in
570   end_spending ();
571     rc,already_contained,false)
572     
573 (* profiling code
574 let profiler_eq = HExtlib.profile "CicUniv.add_eq"
575 let profiler_ge = HExtlib.profile "CicUniv.add_ge"
576 let profiler_gt = HExtlib.profile "CicUniv.add_gt"
577 let add_gt ?fast u v b = 
578   profiler_gt.HExtlib.profile (fun _ -> add_gt ?fast u v b) ()
579 let add_ge ?fast u v b = 
580   profiler_ge.HExtlib.profile (fun _ -> add_ge ?fast u v b) ()
581 let add_eq ?fast u v b = 
582   profiler_eq.HExtlib.profile (fun _ -> add_eq ?fast u v b) ()
583 *)
584
585 (* ugly *)
586 let rank = ref MAL.empty;;
587
588 let do_rank (b,_,_) =
589   
590    let keys = MAL.fold (fun k _ acc -> k::acc) b [] in
591    let fall =
592      List.fold_left 
593        (fun acc u ->
594          let rec aux seen = function
595            | [] -> 0, seen
596            | x::tl when SOF.mem x seen -> aux seen tl
597            | x::tl ->
598                let seen = SOF.add x seen in
599                let t1, seen = aux seen (SOF.elements (repr x b).one_s_eq) in
600                let t2, seen = aux seen (SOF.elements (repr x b).one_s_ge) in
601                let t3, seen = aux seen (SOF.elements (repr x b).one_s_gt) in
602                let t4, seen = aux seen tl in
603                max (max t1 t2) 
604                  (max (if SOF.is_empty (repr x b).one_s_gt then 0 else t3+1) t4),
605                seen 
606          in
607          let rank, _ = aux SOF.empty [u] in
608          MAL.add u rank acc) 
609        MAL.empty
610    in
611    rank := fall keys;
612    MAL.iter 
613      (fun k v -> 
614        prerr_endline (string_of_universe k ^ " = " ^ string_of_int v)) !rank
615 ;;
616
617 let get_rank u = 
618   try MAL.find u !rank 
619   with Not_found -> 0 
620   (* if the universe is not in the graph it means there are 
621    * no contraints on it! thus it can be freely set to Type0 *)
622 ;;
623
624 (*****************************************************************************)
625 (** END: Decomment this for performance comparisons                         **)
626 (*****************************************************************************)
627
628 (* TODO: uncomment l to gain a small speedup *)
629 let merge_ugraphs ~base_ugraph ~increment:(increment, uri_of_increment(*,l*)) =
630   let merge_brutal (u,a,_) v = 
631 (*     prerr_endline ("merging graph: "^UriManager.string_of_uri
632  *     uri_of_increment); *)
633     let m1 = u in 
634     let m2 = v in 
635       MAL.fold (
636         fun k v x -> 
637           (SOF.fold (
638              fun u x -> 
639                let m = add_gt k u x in m) 
640                 (SOF.union v.one_s_gt v.gt_closure)
641              (SOF.fold (
642                 fun u x -> 
643                   let m = add_ge k u x in m) 
644                     (SOF.union v.one_s_ge v.ge_closure)
645                 (SOF.fold (
646                    fun u x ->
647                      let m = add_eq k u x in m) 
648                       (SOF.union v.one_s_eq v.eq_closure) x)))
649           ) m1 m2 
650   in
651   let base, already_contained, oblivion = base_ugraph in
652   let inc,_,oblivion2 = increment in
653   if oblivion then
654     base_ugraph      
655   else if oblivion2 then
656     increment
657   else if MAL.is_empty base then
658     increment
659   else if 
660     MAL.is_empty inc || 
661     UriManager.UriSet.mem uri_of_increment already_contained 
662   then
663     base_ugraph
664   else 
665     (fun (x,_,_) -> x) (merge_brutal increment base_ugraph), 
666 (*
667     List.fold_right UriManager.UriSet.add 
668     (List.map (fun (_,x) -> HExtlib.unopt x) l)
669 *)
670     (UriManager.UriSet.add uri_of_increment already_contained), false
671
672 (* profiling code; WARNING: the time spent during profiling can be
673    greater than the profiled time
674 let profiler_merge = HExtlib.profile "CicUniv.merge_ugraphs"
675 let merge_ugraphs ~base_ugraph ~increment =
676   profiler_merge.HExtlib.profile 
677   (fun _ -> merge_ugraphs ~base_ugraph ~increment) ()
678 *)
679
680 (*****************************************************************************)
681 (** Xml sesialization and parsing                                           **)
682 (*****************************************************************************)
683
684 let xml_of_universe name u = 
685   match u with
686   | (i,Some u) -> 
687       Xml.xml_empty name [
688         None,"id",(string_of_int i) ;
689         None,"uri",(UriManager.string_of_uri u)]
690   | (_,None) -> 
691       raise (Failure "we can serialize only universes with uri")
692
693 let xml_of_set s =
694   let l = 
695     List.map (xml_of_universe "node") (SOF.elements s) 
696   in
697     List.fold_left (fun s x -> [< s ; x >] ) [<>] l
698       
699 let xml_of_entry_content e =
700   let stream_of_field f name =
701     let eq_c = xml_of_set f in
702     if eq_c != [<>] then
703       Xml.xml_nempty name [] eq_c
704     else
705       [<>]
706   in
707   [<
708     (stream_of_field e.eq_closure "eq_closure");
709     (stream_of_field e.gt_closure "gt_closure");
710     (stream_of_field e.ge_closure "ge_closure");
711     (stream_of_field e.in_gegt_of "in_gegt_of");
712     (stream_of_field e.one_s_eq "one_s_eq");
713     (stream_of_field e.one_s_gt "one_s_gt");
714     (stream_of_field e.one_s_ge "one_s_ge")
715   >]
716
717 let xml_of_entry u e =
718   let (i,u') = u in
719   let u'' = 
720     match u' with 
721         Some x -> x 
722       | None -> 
723           raise (Failure "we can serialize only universes (entry) with uri")
724   in
725   let ent = Xml.xml_nempty "entry" [
726     None,"id",(string_of_int i) ; 
727     None,"uri",(UriManager.string_of_uri u'')] in
728   let content = xml_of_entry_content e in
729   ent content
730
731 let write_xml_of_ugraph filename (m,_,_) l =
732     let tokens = 
733       [< 
734         Xml.xml_cdata "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
735         Xml.xml_nempty "ugraph" [] 
736           ([< (MAL.fold ( fun k v s -> [< s ; (xml_of_entry k v) >]) m [<>]) ; 
737            (List.fold_left 
738              (fun s u -> [< s ; xml_of_universe "owned_node" u >]) [<>] l) >])>]
739     in
740     Xml.pp ~gzip:true tokens (Some filename)
741
742 let univno = fst
743
744  
745 let rec clean_ugraph m already_contained f =
746   let m' = 
747     MAL.fold (fun k v x -> if (f k) then MAL.add k v x else x ) m MAL.empty in
748   let m'' =  MAL.fold (fun k v x -> 
749     let v' = {
750       eq_closure = SOF.filter f v.eq_closure;
751       ge_closure = SOF.filter f v.ge_closure;
752       gt_closure = SOF.filter f v.gt_closure;
753       in_gegt_of = SOF.filter f v.in_gegt_of;
754       one_s_eq = SOF.filter f v.one_s_eq;
755       one_s_ge = SOF.filter f v.one_s_ge;
756       one_s_gt = SOF.filter f v.one_s_gt
757     } in 
758     MAL.add k v' x ) m' MAL.empty in
759   let e_l = 
760     MAL.fold (fun k v l -> if v = empty_entry && not(f k) then
761       begin
762       k::l end else l) m'' []
763   in
764     if e_l != [] then
765       clean_ugraph 
766         m'' already_contained (fun u -> (f u) && not (List.mem u e_l))
767     else
768       MAL.fold 
769         (fun k v x -> if v <> empty_entry then MAL.add k v x else x) 
770         m'' MAL.empty,
771       already_contained
772
773 let clean_ugraph (m,a,o) l =
774   assert(not o);
775   let m, a = clean_ugraph m a (fun u -> List.mem u l) in
776   m, a, o
777
778 let assigner_of = 
779   function
780     "ge_closure" -> (fun e u->{e with ge_closure=SOF.add u e.ge_closure})
781   | "gt_closure" -> (fun e u->{e with gt_closure=SOF.add u e.gt_closure})
782   | "eq_closure" -> (fun e u->{e with eq_closure=SOF.add u e.eq_closure})
783   | "in_gegt_of"   -> (fun e u->{e with in_gegt_of  =SOF.add u e.in_gegt_of})
784   | "one_s_ge"   -> (fun e u->{e with one_s_ge  =SOF.add u e.one_s_ge})
785   | "one_s_gt"   -> (fun e u->{e with one_s_gt  =SOF.add u e.one_s_gt})
786   | "one_s_eq"   -> (fun e u->{e with one_s_eq  =SOF.add u e.one_s_eq})
787   | s -> raise (Failure ("unsupported tag " ^ s))
788 ;;
789
790 let cb_factory m l = 
791   let module XPP = XmlPushParser in
792   let current_node = ref (0,None) in
793   let current_entry = ref empty_entry in
794   let current_assign = ref (assigner_of "in_gegt_of") in
795   { XPP.default_callbacks with
796     XPP.end_element = Some( fun name ->
797       match name with
798       | "entry" -> 
799           m := MAL.add !current_node !current_entry !m;
800           current_entry := empty_entry
801       | _ -> ()
802     );
803     XPP.start_element = Some( fun name attlist ->
804       match name with
805       | "ugraph" -> ()
806       | "entry" -> 
807           let id = List.assoc "id" attlist in      
808           let uri = List.assoc "uri" attlist in
809           current_node := (int_of_string id,Some (UriManager.uri_of_string uri))
810       | "node" -> 
811           let id = int_of_string (List.assoc "id" attlist) in
812           let uri = List.assoc "uri" attlist in        
813             current_entry := !current_assign !current_entry 
814               (id,Some (UriManager.uri_of_string uri))
815       | "owned_node" -> 
816           let id = int_of_string (List.assoc "id" attlist) in
817           let uri = List.assoc "uri" attlist in        
818           l := (id,Some (UriManager.uri_of_string uri)) :: !l
819       | s -> current_assign := assigner_of s
820     )
821   }
822 ;; 
823
824 let ugraph_and_univlist_of_xml filename =
825   let module XPP = XmlPushParser in
826   let result_map = ref MAL.empty in
827   let result_list = ref [] in
828   let cb = cb_factory result_map result_list in
829   let xml_parser = XPP.create_parser cb in
830   let xml_source = `Gzip_file filename in
831   (try XPP.parse xml_parser xml_source
832    with (XPP.Parse_error err) as exn -> raise exn);
833   (!result_map,UriManager.UriSet.empty,false), !result_list
834
835 \f
836 (*****************************************************************************)
837 (** the main, only for testing                                              **)
838 (*****************************************************************************)
839
840 (* 
841
842 type arc = Ge | Gt | Eq ;;
843
844 let randomize_actionlist n m =
845   let ge_percent = 0.7 in
846   let gt_percent = 0.15 in
847   let random_step () =
848     let node1 = Random.int m in
849     let node2 = Random.int m in
850     let op = 
851       let r = Random.float 1.0 in
852         if r < ge_percent then 
853           Ge 
854         else (if r < (ge_percent +. gt_percent) then 
855           Gt 
856         else 
857           Eq) 
858     in
859       op,node1,node2      
860   in
861   let rec aux n =
862     match n with 
863         0 -> []
864       | n -> (random_step ())::(aux (n-1))
865   in
866     aux n
867
868 let print_action_list l =
869   let string_of_step (op,node1,node2) =
870     (match op with
871          Ge -> "Ge"
872        | Gt -> "Gt"
873        | Eq -> "Eq") ^ 
874     "," ^ (string_of_int node1) ^ ","   ^ (string_of_int node2) 
875   in
876   let rec aux l =
877     match l with 
878         [] -> "]"
879       | a::tl ->
880           ";" ^ (string_of_step a) ^ (aux tl)
881   in
882   let body = aux l in
883   let l_body = (String.length body) - 1 in
884     prerr_endline ("[" ^ (String.sub body 1 l_body))
885   
886 let debug = false
887 let d_print_endline = if debug then print_endline else ignore 
888 let d_print_ugraph = if debug then print_ugraph else ignore
889
890 let _ = 
891   (if Array.length Sys.argv < 2 then
892     prerr_endline ("Usage " ^ Sys.argv.(0) ^ " max_edges max_nodes"));
893   Random.self_init ();
894   let max_edges = int_of_string Sys.argv.(1) in
895   let max_nodes = int_of_string Sys.argv.(2) in
896   let action_listR = randomize_actionlist max_edges max_nodes in
897
898   let action_list = [Ge,1,4;Ge,2,6;Ge,1,1;Eq,6,4;Gt,6,3] in
899   let action_list = action_listR in
900   
901   print_action_list action_list;
902   let prform_step ?(fast=false) (t,u,v) g =
903     let f,str = 
904       match t with
905           Ge -> add_ge,">="
906         | Gt -> add_gt,">"
907         | Eq -> add_eq,"="
908     in
909       d_print_endline (
910         "Aggiungo " ^ 
911         (string_of_int u) ^
912         " " ^ str ^ " " ^ 
913         (string_of_int v));
914       let g' = f ~fast (u,None) (v,None) g in
915         (*print_ugraph g' ;*)
916         g'
917   in
918   let fail = ref false in
919   let time1 = Unix.gettimeofday () in
920   let n_safe = ref 0 in
921   let g_safe =  
922     try 
923       d_print_endline "SAFE";
924       List.fold_left (
925         fun g e -> 
926           n_safe := !n_safe + 1;
927           prform_step e g
928       ) empty_ugraph action_list
929     with
930         UniverseInconsistency s -> fail:=true;empty_bag
931   in
932   let time2 = Unix.gettimeofday () in
933   d_print_ugraph g_safe;
934   let time3 = Unix.gettimeofday () in
935   let n_test = ref 0 in
936   let g_test = 
937     try
938       d_print_endline "FAST";
939       List.fold_left (
940         fun g e ->
941           n_test := !n_test + 1;
942           prform_step ~fast:true e g
943       ) empty_ugraph action_list
944     with
945         UniverseInconsistency s -> empty_bag
946   in
947   let time4 = Unix.gettimeofday () in
948   d_print_ugraph g_test;
949     if are_ugraph_eq g_safe g_test && !n_test = !n_safe then
950       begin
951         let num_eq = 
952           List.fold_left (
953             fun s (e,_,_) -> 
954               if e = Eq then s+1 else s 
955           ) 0 action_list 
956         in
957         let num_gt = 
958           List.fold_left (
959             fun s (e,_,_) ->
960               if e = Gt then s+1 else s
961           ) 0 action_list
962         in
963         let num_ge = max_edges - num_gt - num_eq in
964         let time_fast = (time4 -. time3) in
965         let time_safe = (time2 -. time1) in
966         let gap = ((time_safe -. time_fast) *. 100.0) /. time_safe in
967         let fail = if !fail then 1 else 0 in
968           print_endline 
969             (sprintf 
970                "OK %d safe %1.4f fast %1.4f %% %1.2f #eq %d #gt %d #ge %d %d" 
971                fail time_safe time_fast gap num_eq num_gt num_ge !n_safe);
972           exit 0
973       end
974     else
975       begin
976         print_endline "FAIL";
977         print_ugraph g_safe;
978         print_ugraph g_test;
979         exit 1
980       end
981 ;;
982
983  *)
984
985 let recons_univ u =
986   match u with
987   | i, None -> u
988   | i, Some uri ->
989       i, Some (UriManager.uri_of_string (UriManager.string_of_uri uri))
990
991 let recons_entry entry =
992   let recons_set set =
993     SOF.fold (fun univ set -> SOF.add (recons_univ univ) set) set SOF.empty
994   in
995   {
996     eq_closure = recons_set entry.eq_closure;
997     ge_closure = recons_set entry.ge_closure;
998     gt_closure = recons_set entry.gt_closure;
999     in_gegt_of = recons_set entry.in_gegt_of;
1000     one_s_eq = recons_set entry.one_s_eq;
1001     one_s_ge = recons_set entry.one_s_ge;
1002     one_s_gt = recons_set entry.one_s_gt;
1003   }
1004
1005 let recons_graph (graph,uriset,o) =
1006   MAL.fold
1007     (fun universe entry map ->
1008       MAL.add (recons_univ universe) (recons_entry entry) map)
1009     graph 
1010     MAL.empty,
1011   UriManager.UriSet.fold 
1012     (fun u acc -> 
1013       UriManager.UriSet.add 
1014         (UriManager.uri_of_string (UriManager.string_of_uri u)) acc) 
1015     uriset UriManager.UriSet.empty, o
1016
1017 let assert_univ u =
1018     match u with 
1019     | (_,None) ->
1020        raise (UniverseInconsistency (lazy "This universe graph has a hole"))
1021     | _ -> ()
1022     
1023 let assert_univs_have_uri (graph,_,_) univlist =
1024   let assert_set s =
1025     SOF.iter (fun u -> assert_univ u) s
1026   in
1027   let assert_entry e =
1028     assert_set e.eq_closure;
1029     assert_set e.ge_closure;
1030     assert_set e.gt_closure;
1031     assert_set e.in_gegt_of;
1032     assert_set e.one_s_eq;
1033     assert_set e.one_s_ge;
1034     assert_set e.one_s_gt;
1035   in
1036   MAL.iter (fun k v -> assert_univ k; assert_entry v)graph;
1037   List.iter assert_univ univlist
1038   
1039 let eq u1 u2 = 
1040   match u1,u2 with
1041   | (id1, Some uri1),(id2, Some uri2) -> 
1042       id1 = id2 && UriManager.eq uri1 uri2
1043   | (id1, None),(id2, None) -> id1 = id2
1044   | _ -> false
1045   
1046 let compare (id1, uri1) (id2, uri2) = 
1047   let cmp = id1 - id2 in
1048   if cmp = 0 then
1049     match uri1,uri2 with
1050     | None, None -> 0 
1051     | Some _, None -> 1
1052     | None, Some _ -> ~-1
1053     | Some uri1, Some uri2 -> UriManager.compare uri1 uri2
1054   else
1055     cmp
1056
1057 let is_anon = function (_,None) -> true | _ -> false
1058   
1059 (* EOF *)