]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic/cicUniv.ml
added little optimization to not add twice the same arc
[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_aux 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_aux  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 (*
265 and profiler_adj = HExtlib.profile "CicUniv.adjust_fast"
266 and adjust_fast x y = profiler_adj.HExtlib.profile (adjust_fast_aux x) y
267 *)
268 and adjust_fast x y = adjust_fast_aux x y
269         
270 and add_gt_arc_fast u v m =
271   let ru = repr u m in
272   if SOF.mem v ru.gt_closure then m else
273   let ru' = {ru with one_s_gt = SOF.add v ru.one_s_gt} in
274   let m' = MAL.add u ru' m in
275   let rv = repr v m' in
276   let rv' = {rv with in_gegt_of = SOF.add u rv.in_gegt_of} in
277   let m'' = MAL.add v rv' m' in
278     adjust_fast u m''
279       
280 and add_ge_arc_fast u v m =
281   let ru = repr u m in
282   if SOF.mem v ru.ge_closure then m else
283   let ru' = { ru with one_s_ge = SOF.add v ru.one_s_ge} in
284   let m' = MAL.add u ru' m in
285   let rv = repr v m' in
286   let rv' = {rv with in_gegt_of = SOF.add u rv.in_gegt_of} in
287   let m'' = MAL.add v rv' m' in
288   adjust_fast u m''
289
290 and add_eq_arc_fast u v m =
291   let ru = repr u m in
292   if SOF.mem v ru.eq_closure then m else
293   let rv = repr v m in 
294   let ru' = {ru  with one_s_eq = SOF.add v ru.one_s_eq} in
295   (*TESI: let ru' = {ru' with in_gegt_of = SOF.add v ru.in_gegt_of} in *)
296   let m' = MAL.add u ru' m in
297   let rv' = {rv  with one_s_eq = SOF.add u rv.one_s_eq} in
298   (*TESI: let rv' = {rv' with in_gegt_of = SOF.add u rv.in_gegt_of} in *)
299   let m'' = MAL.add v rv' m' in
300     adjust_fast v (*(adjust_fast u*) m'' (* ) *)
301 ;;
302
303 \f
304 (*****************************************************************************)
305 (** safe implementation                                                     **)
306 (*****************************************************************************)
307
308 let closure_of u m =
309   let ru = repr u m in
310   let eq_c =
311     let j = ru.one_s_eq in
312     let _Uj = merge_closures (fun x -> x.eq_closure) j m in
313     let one_step_eq = ru.one_s_eq in
314             (SOF.union one_step_eq _Uj)
315   in
316   let ge_c = 
317     let j = SOF.union ru.one_s_ge (SOF.union ru.one_s_gt ru.one_s_eq) in
318     let _Uj = merge_closures (fun x -> x.ge_closure) j m in
319     let _Ux = j in
320       (SOF.union _Uj _Ux)
321   in
322   let gt_c =
323     let j = ru.one_s_gt in
324     let k = ru.one_s_ge in
325     let l = ru.one_s_eq in
326     let _Uj = merge_closures (fun x -> x.ge_closure) j m in
327     let _Uk = merge_closures (fun x -> x.gt_closure) k m in
328     let _Ul = merge_closures (fun x -> x.gt_closure) l m in
329     let one_step_gt = ru.one_s_gt in
330       (SOF.union (SOF.union (SOF.union _Ul one_step_gt) _Uk) _Uj)
331   in
332     {
333       eq_closure = eq_c;
334       ge_closure = ge_c;
335       gt_closure = gt_c;
336       in_gegt_of = ru.in_gegt_of;
337       one_s_eq = ru.one_s_eq;
338       one_s_ge = ru.one_s_ge;
339       one_s_gt = ru.one_s_gt
340     }
341
342 let rec simple_adjust m =
343   let m' = 
344     MAL.mapi (fun x _ -> closure_of x m) m
345   in
346     if not (are_ugraph_eq m  m') then(
347       simple_adjust m')
348     else
349       m'
350
351 let add_eq_arc u v m =
352   let ru = repr u m in
353   let rv = repr v m in
354   let ru' = {ru with one_s_eq = SOF.add v ru.one_s_eq} in
355   let m' = MAL.add u ru' m in
356   let rv' = {rv with one_s_eq = SOF.add u rv.one_s_eq} in
357   let m'' = MAL.add v rv' m' in
358     simple_adjust m''
359
360 let add_ge_arc u v m =
361   let ru = repr u m in
362   let ru' = { ru with one_s_ge = SOF.add v ru.one_s_ge} in
363   let m' = MAL.add u ru' m in
364     simple_adjust m'
365
366 let add_gt_arc u v m =
367   let ru = repr u m in
368   let ru' = {ru with one_s_gt = SOF.add v ru.one_s_gt} in
369   let m' = MAL.add u ru' m in
370     simple_adjust m'
371
372 \f
373 (*****************************************************************************)
374 (** Outhern interface, that chooses between _fast and safe                  **)
375 (*****************************************************************************)
376
377 (*                                                                            
378     given the 2 nodes plus the current bag, adds the arc, recomputes the 
379     closures and returns the new map
380 *) 
381 let add_eq fast u v b =
382   if fast then
383     add_eq_arc_fast u v b
384   else
385     add_eq_arc u v b
386
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_ge fast u v b =
392   if fast then
393     add_ge_arc_fast u v b
394   else
395     add_ge_arc u v b
396 (*                                                                            
397     given the 2 nodes plus the current bag, adds the arc, recomputes the 
398     closures and returns the new map
399 *)                                                                            
400 let add_gt fast u v b =
401   if fast then
402     add_gt_arc_fast u v b
403   else
404     add_gt_arc u v b
405
406
407 (*****************************************************************************)
408 (** Other real code                                                         **)
409 (*****************************************************************************)
410
411 exception UniverseInconsistency of string Lazy.t
412
413 let error arc node1 closure_type node2 closure =
414   let s =
415    lazy
416     ("\n  ===== Universe Inconsistency detected =====\n\n" ^
417      "   Unable to add\n" ^ 
418      "\t" ^ (string_of_arc arc) ^ "\n" ^
419      "   cause\n" ^ 
420      "\t" ^ (string_of_universe node1) ^ "\n" ^
421      "   is in the " ^ closure_type ^ " closure\n" ^
422      "\t{" ^ (string_of_universe_set closure) ^ "}\n" ^ 
423      "   of\n" ^ 
424      "\t" ^ (string_of_universe node2) ^ "\n\n" ^
425      "  ===== Universe Inconsistency detected =====\n") in
426   prerr_endline (Lazy.force s);
427   raise (UniverseInconsistency s)
428
429
430 let fill_empty_nodes_with_uri (g, already_contained,o) l uri =
431   let fill_empty_universe u =
432     match u with
433         (i,None) -> (i,Some uri)
434       | (i,Some _) as u -> u
435   in
436   let fill_empty_set s =
437     SOF.fold (fun e s -> SOF.add (fill_empty_universe e) s) s SOF.empty 
438   in
439   let fill_empty_entry e = {
440     eq_closure = (fill_empty_set e.eq_closure) ;
441     ge_closure = (fill_empty_set e.ge_closure) ;
442     gt_closure = (fill_empty_set e.gt_closure) ;
443     in_gegt_of = (fill_empty_set e.in_gegt_of) ;
444     one_s_eq = (fill_empty_set e.one_s_eq) ;
445     one_s_ge = (fill_empty_set e.one_s_ge) ;
446     one_s_gt = (fill_empty_set e.one_s_gt) ;
447   } in  
448   let m = g in
449   let m' = MAL.fold (
450     fun k v m -> 
451       MAL.add (fill_empty_universe k) (fill_empty_entry v) m) m MAL.empty
452   in
453   let l' = List.map fill_empty_universe l in
454     (m', already_contained,o),l'
455
456
457 (*****************************************************************************)
458 (** World interface                                                         **)
459 (*****************************************************************************)
460
461 type universe_graph = bag * UriManager.UriSet.t * bool
462 (* the graph , the cache of already merged ugraphs, oblivion? *)
463
464 let empty_ugraph = empty_bag, UriManager.UriSet.empty, false
465 let oblivion_ugraph = empty_bag, UriManager.UriSet.empty, true
466
467 let current_index_anon = ref (-1)
468 let current_index_named = ref (-1)
469
470 let restart_numbering () = current_index_named := (-1) 
471
472 let fresh ?uri ?id () =
473   let i =
474     match uri,id with
475     | None,None -> 
476         current_index_anon := !current_index_anon + 1;
477         !current_index_anon
478     | None, Some _ -> assert false
479     | Some _, None -> 
480         current_index_named := !current_index_named + 1;
481         !current_index_named
482     | Some _, Some id -> id
483   in
484   (i,uri)
485
486 let name_universe u uri =
487   match u with
488   | (i, None) -> (i, Some uri)
489   | (i, Some ouri) -> 
490       (* inside obj living at uri 'uri' should live only
491        * universes with uri None. Call Unshare.unshare ~fresh_univs:true
492        * if you want to reuse a Type in another object *)
493       prerr_endline ("Offending universe: " ^ string_of_universe u^
494         " found inside object " ^ UriManager.string_of_uri  uri);
495       assert false
496 ;;
497   
498 let print_ugraph (g, _, o) = 
499   if o then prerr_endline "oblivion universe" else
500   prerr_endline (string_of_bag g)
501
502 let add_eq ?(fast=(!fast_implementation)) u v b =
503   (* should we check to no add twice the same?? *)
504   let m = b in
505   let ru = repr u m in
506   if SOF.mem v ru.gt_closure then
507     error ("EQ",u,v) v "GT" u ru.gt_closure
508   else
509     begin
510     let rv = repr v m in
511     if SOF.mem u rv.gt_closure then
512       error ("EQ",u,v) u "GT" v rv.gt_closure
513     else
514       add_eq fast u v b
515     end
516
517 let add_ge ?(fast=(!fast_implementation)) u v b =
518   (* should we check to no add twice the same?? *)
519   let m = b in
520   let rv = repr v m in
521   if SOF.mem u rv.gt_closure then
522     error ("GE",u,v) u "GT" v rv.gt_closure
523   else
524     add_ge fast u v b
525   
526 let add_gt ?(fast=(!fast_implementation)) u v b =
527   (* should we check to no add twice the same?? *)
528   (* 
529      FIXME : check the thesis... no need to check GT and EQ closure since the 
530      GE is a superset of both 
531   *)
532   let m = b in
533   let rv = repr v m in
534
535   if u = v then
536     error ("GT",u,v) u "==" v SOF.empty
537   else
538   
539   (*if SOF.mem u rv.gt_closure then
540     error ("GT",u,v) u "GT" v rv.gt_closure
541   else
542     begin*)
543       if SOF.mem u rv.ge_closure then
544         error ("GT",u,v) u "GE" v rv.ge_closure
545       else
546 (*        begin
547           if SOF.mem u rv.eq_closure then
548             error ("GT",u,v) u "EQ" v rv.eq_closure
549           else*)
550             add_gt fast u v b
551 (*        end
552     end*)
553
554 (*****************************************************************************)
555 (** START: Decomment this for performance comparisons                       **)
556 (*****************************************************************************)
557
558 let add_eq ?(fast=(!fast_implementation))  u v (b,already_contained,oblivion) =
559         if oblivion then (b,already_contained,oblivion) else
560   (*prerr_endline "add_eq";*)
561   (begin_spending ();
562   let rc = add_eq ~fast u v b in
563   end_spending ();
564     rc,already_contained,false)
565
566 let add_ge ?(fast=(!fast_implementation)) u v (b,already_contained,oblivion) =
567         if oblivion then (b,already_contained,oblivion) else
568 (*   prerr_endline "add_ge"; *)
569   (begin_spending ();
570   let rc = add_ge ~fast u v b in
571   end_spending ();
572     rc,already_contained,false)
573     
574 let add_gt ?(fast=(!fast_implementation)) u v (b,already_contained,oblivion) =
575         if oblivion then (b,already_contained,oblivion) else
576 (*   prerr_endline "add_gt"; *)
577   (begin_spending ();
578   let rc = add_gt ~fast u v b in
579   end_spending ();
580     rc,already_contained,false)
581     
582 (* profiling code 
583 let profiler_eq = HExtlib.profile "CicUniv.add_eq"
584 let profiler_ge = HExtlib.profile "CicUniv.add_ge"
585 let profiler_gt = HExtlib.profile "CicUniv.add_gt"
586 let add_gt ?fast u v b = 
587   profiler_gt.HExtlib.profile (fun _ -> add_gt ?fast u v b) ()
588 let add_ge ?fast u v b = 
589   profiler_ge.HExtlib.profile (fun _ -> add_ge ?fast u v b) ()
590 let add_eq ?fast u v b = 
591   profiler_eq.HExtlib.profile (fun _ -> add_eq ?fast u v b) ()
592 *)
593
594 (* ugly *)
595 let rank = ref MAL.empty;;
596
597 let do_rank (b,_,_) =
598   
599    let keys = MAL.fold (fun k _ acc -> k::acc) b [] in
600    let fall =
601      List.fold_left 
602        (fun acc u ->
603          let rec aux seen = function
604            | [] -> 0, seen
605            | x::tl when SOF.mem x seen -> aux seen tl
606            | x::tl ->
607                let seen = SOF.add x seen in
608                let t1, seen = aux seen (SOF.elements (repr x b).one_s_eq) in
609                let t2, seen = aux seen (SOF.elements (repr x b).one_s_ge) in
610                let t3, seen = aux seen (SOF.elements (repr x b).one_s_gt) in
611                let t4, seen = aux seen tl in
612                max (max t1 t2) 
613                  (max (if SOF.is_empty (repr x b).one_s_gt then 0 else t3+1) t4),
614                seen 
615          in
616          let rank, _ = aux SOF.empty [u] in
617          MAL.add u rank acc) 
618        MAL.empty
619    in
620    rank := fall keys;
621    MAL.iter 
622      (fun k v -> 
623        prerr_endline (string_of_universe k ^ " = " ^ string_of_int v)) !rank
624 ;;
625
626 let get_rank u = 
627   try MAL.find u !rank 
628   with Not_found -> 0 
629   (* if the universe is not in the graph it means there are 
630    * no contraints on it! thus it can be freely set to Type0 *)
631 ;;
632
633 (*****************************************************************************)
634 (** END: Decomment this for performance comparisons                         **)
635 (*****************************************************************************)
636
637 (* TODO: uncomment l to gain a small speedup *)
638 let merge_ugraphs ~base_ugraph ~increment:(increment, uri_of_increment(*,l*)) =
639   let merge_brutal (u,a,_) v = 
640 (*     prerr_endline ("merging graph: "^UriManager.string_of_uri
641  *     uri_of_increment); *)
642     let m1 = u in 
643     let m2 = v in 
644       MAL.fold (
645         fun k v x -> 
646           (SOF.fold (
647              fun u x -> 
648                let m = add_gt k u x in m) 
649                 (SOF.union v.one_s_gt v.gt_closure)
650              (SOF.fold (
651                 fun u x -> 
652                   let m = add_ge k u x in m) 
653                     (SOF.union v.one_s_ge v.ge_closure)
654                 (SOF.fold (
655                    fun u x ->
656                      let m = add_eq k u x in m) 
657                       (SOF.union v.one_s_eq v.eq_closure) x)))
658           ) m1 m2 
659   in
660   let base, already_contained, oblivion = base_ugraph in
661   let inc,_,oblivion2 = increment in
662   if oblivion then
663     base_ugraph      
664   else if oblivion2 then
665     increment
666   else if MAL.is_empty base then
667     increment
668   else if 
669     MAL.is_empty inc || 
670     UriManager.UriSet.mem uri_of_increment already_contained 
671   then
672     base_ugraph
673   else 
674     (fun (x,_,_) -> x) (merge_brutal increment base_ugraph), 
675 (*
676     List.fold_right UriManager.UriSet.add 
677     (List.map (fun (_,x) -> HExtlib.unopt x) l)
678 *)
679     (UriManager.UriSet.add uri_of_increment already_contained), false
680
681 (* profiling code; WARNING: the time spent during profiling can be
682    greater than the profiled time 
683 let profiler_merge = HExtlib.profile "CicUniv.merge_ugraphs"
684 let merge_ugraphs ~base_ugraph ~increment =
685   profiler_merge.HExtlib.profile 
686   (fun _ -> merge_ugraphs ~base_ugraph ~increment) ()
687 *)
688
689 (*****************************************************************************)
690 (** Xml sesialization and parsing                                           **)
691 (*****************************************************************************)
692
693 let xml_of_universe name u = 
694   match u with
695   | (i,Some u) -> 
696       Xml.xml_empty name [
697         None,"id",(string_of_int i) ;
698         None,"uri",(UriManager.string_of_uri u)]
699   | (_,None) -> 
700       raise (Failure "we can serialize only universes with uri")
701
702 let xml_of_set s =
703   let l = 
704     List.map (xml_of_universe "node") (SOF.elements s) 
705   in
706     List.fold_left (fun s x -> [< s ; x >] ) [<>] l
707       
708 let xml_of_entry_content e =
709   let stream_of_field f name =
710     let eq_c = xml_of_set f in
711     if eq_c != [<>] then
712       Xml.xml_nempty name [] eq_c
713     else
714       [<>]
715   in
716   [<
717     (stream_of_field e.eq_closure "eq_closure");
718     (stream_of_field e.gt_closure "gt_closure");
719     (stream_of_field e.ge_closure "ge_closure");
720     (stream_of_field e.in_gegt_of "in_gegt_of");
721     (stream_of_field e.one_s_eq "one_s_eq");
722     (stream_of_field e.one_s_gt "one_s_gt");
723     (stream_of_field e.one_s_ge "one_s_ge")
724   >]
725
726 let xml_of_entry u e =
727   let (i,u') = u in
728   let u'' = 
729     match u' with 
730         Some x -> x 
731       | None -> 
732           raise (Failure "we can serialize only universes (entry) with uri")
733   in
734   let ent = Xml.xml_nempty "entry" [
735     None,"id",(string_of_int i) ; 
736     None,"uri",(UriManager.string_of_uri u'')] in
737   let content = xml_of_entry_content e in
738   ent content
739
740 let write_xml_of_ugraph filename (m,_,_) l =
741     let tokens = 
742       [< 
743         Xml.xml_cdata "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
744         Xml.xml_nempty "ugraph" [] 
745           ([< (MAL.fold ( fun k v s -> [< s ; (xml_of_entry k v) >]) m [<>]) ; 
746            (List.fold_left 
747              (fun s u -> [< s ; xml_of_universe "owned_node" u >]) [<>] l) >])>]
748     in
749     Xml.pp ~gzip:true tokens (Some filename)
750
751 let univno = fst
752
753  
754 let rec clean_ugraph m already_contained f =
755   let m' = 
756     MAL.fold (fun k v x -> if (f k) then MAL.add k v x else x ) m MAL.empty in
757   let m'' =  MAL.fold (fun k v x -> 
758     let v' = {
759       eq_closure = SOF.filter f v.eq_closure;
760       ge_closure = SOF.filter f v.ge_closure;
761       gt_closure = SOF.filter f v.gt_closure;
762       in_gegt_of = SOF.filter f v.in_gegt_of;
763       one_s_eq = SOF.filter f v.one_s_eq;
764       one_s_ge = SOF.filter f v.one_s_ge;
765       one_s_gt = SOF.filter f v.one_s_gt
766     } in 
767     MAL.add k v' x ) m' MAL.empty in
768   let e_l = 
769     MAL.fold (fun k v l -> if v = empty_entry && not(f k) then
770       begin
771       k::l end else l) m'' []
772   in
773     if e_l != [] then
774       clean_ugraph 
775         m'' already_contained (fun u -> (f u) && not (List.mem u e_l))
776     else
777       MAL.fold 
778         (fun k v x -> if v <> empty_entry then MAL.add k v x else x) 
779         m'' MAL.empty,
780       already_contained
781
782 let clean_ugraph (m,a,o) l =
783   assert(not o);
784   let m, a = clean_ugraph m a (fun u -> List.mem u l) in
785   m, a, o
786
787 let assigner_of = 
788   function
789     "ge_closure" -> (fun e u->{e with ge_closure=SOF.add u e.ge_closure})
790   | "gt_closure" -> (fun e u->{e with gt_closure=SOF.add u e.gt_closure})
791   | "eq_closure" -> (fun e u->{e with eq_closure=SOF.add u e.eq_closure})
792   | "in_gegt_of"   -> (fun e u->{e with in_gegt_of  =SOF.add u e.in_gegt_of})
793   | "one_s_ge"   -> (fun e u->{e with one_s_ge  =SOF.add u e.one_s_ge})
794   | "one_s_gt"   -> (fun e u->{e with one_s_gt  =SOF.add u e.one_s_gt})
795   | "one_s_eq"   -> (fun e u->{e with one_s_eq  =SOF.add u e.one_s_eq})
796   | s -> raise (Failure ("unsupported tag " ^ s))
797 ;;
798
799 let cb_factory m l = 
800   let module XPP = XmlPushParser in
801   let current_node = ref (0,None) in
802   let current_entry = ref empty_entry in
803   let current_assign = ref (assigner_of "in_gegt_of") in
804   { XPP.default_callbacks with
805     XPP.end_element = Some( fun name ->
806       match name with
807       | "entry" -> 
808           m := MAL.add !current_node !current_entry !m;
809           current_entry := empty_entry
810       | _ -> ()
811     );
812     XPP.start_element = Some( fun name attlist ->
813       match name with
814       | "ugraph" -> ()
815       | "entry" -> 
816           let id = List.assoc "id" attlist in      
817           let uri = List.assoc "uri" attlist in
818           current_node := (int_of_string id,Some (UriManager.uri_of_string uri))
819       | "node" -> 
820           let id = int_of_string (List.assoc "id" attlist) in
821           let uri = List.assoc "uri" attlist in        
822             current_entry := !current_assign !current_entry 
823               (id,Some (UriManager.uri_of_string uri))
824       | "owned_node" -> 
825           let id = int_of_string (List.assoc "id" attlist) in
826           let uri = List.assoc "uri" attlist in        
827           l := (id,Some (UriManager.uri_of_string uri)) :: !l
828       | s -> current_assign := assigner_of s
829     )
830   }
831 ;; 
832
833 let ugraph_and_univlist_of_xml filename =
834   let module XPP = XmlPushParser in
835   let result_map = ref MAL.empty in
836   let result_list = ref [] in
837   let cb = cb_factory result_map result_list in
838   let xml_parser = XPP.create_parser cb in
839   let xml_source = `Gzip_file filename in
840   (try XPP.parse xml_parser xml_source
841    with (XPP.Parse_error err) as exn -> raise exn);
842   (!result_map,UriManager.UriSet.empty,false), !result_list
843
844 \f
845 (*****************************************************************************)
846 (** the main, only for testing                                              **)
847 (*****************************************************************************)
848
849 (* 
850
851 type arc = Ge | Gt | Eq ;;
852
853 let randomize_actionlist n m =
854   let ge_percent = 0.7 in
855   let gt_percent = 0.15 in
856   let random_step () =
857     let node1 = Random.int m in
858     let node2 = Random.int m in
859     let op = 
860       let r = Random.float 1.0 in
861         if r < ge_percent then 
862           Ge 
863         else (if r < (ge_percent +. gt_percent) then 
864           Gt 
865         else 
866           Eq) 
867     in
868       op,node1,node2      
869   in
870   let rec aux n =
871     match n with 
872         0 -> []
873       | n -> (random_step ())::(aux (n-1))
874   in
875     aux n
876
877 let print_action_list l =
878   let string_of_step (op,node1,node2) =
879     (match op with
880          Ge -> "Ge"
881        | Gt -> "Gt"
882        | Eq -> "Eq") ^ 
883     "," ^ (string_of_int node1) ^ ","   ^ (string_of_int node2) 
884   in
885   let rec aux l =
886     match l with 
887         [] -> "]"
888       | a::tl ->
889           ";" ^ (string_of_step a) ^ (aux tl)
890   in
891   let body = aux l in
892   let l_body = (String.length body) - 1 in
893     prerr_endline ("[" ^ (String.sub body 1 l_body))
894   
895 let debug = false
896 let d_print_endline = if debug then print_endline else ignore 
897 let d_print_ugraph = if debug then print_ugraph else ignore
898
899 let _ = 
900   (if Array.length Sys.argv < 2 then
901     prerr_endline ("Usage " ^ Sys.argv.(0) ^ " max_edges max_nodes"));
902   Random.self_init ();
903   let max_edges = int_of_string Sys.argv.(1) in
904   let max_nodes = int_of_string Sys.argv.(2) in
905   let action_listR = randomize_actionlist max_edges max_nodes in
906
907   let action_list = [Ge,1,4;Ge,2,6;Ge,1,1;Eq,6,4;Gt,6,3] in
908   let action_list = action_listR in
909   
910   print_action_list action_list;
911   let prform_step ?(fast=false) (t,u,v) g =
912     let f,str = 
913       match t with
914           Ge -> add_ge,">="
915         | Gt -> add_gt,">"
916         | Eq -> add_eq,"="
917     in
918       d_print_endline (
919         "Aggiungo " ^ 
920         (string_of_int u) ^
921         " " ^ str ^ " " ^ 
922         (string_of_int v));
923       let g' = f ~fast (u,None) (v,None) g in
924         (*print_ugraph g' ;*)
925         g'
926   in
927   let fail = ref false in
928   let time1 = Unix.gettimeofday () in
929   let n_safe = ref 0 in
930   let g_safe =  
931     try 
932       d_print_endline "SAFE";
933       List.fold_left (
934         fun g e -> 
935           n_safe := !n_safe + 1;
936           prform_step e g
937       ) empty_ugraph action_list
938     with
939         UniverseInconsistency s -> fail:=true;empty_bag
940   in
941   let time2 = Unix.gettimeofday () in
942   d_print_ugraph g_safe;
943   let time3 = Unix.gettimeofday () in
944   let n_test = ref 0 in
945   let g_test = 
946     try
947       d_print_endline "FAST";
948       List.fold_left (
949         fun g e ->
950           n_test := !n_test + 1;
951           prform_step ~fast:true e g
952       ) empty_ugraph action_list
953     with
954         UniverseInconsistency s -> empty_bag
955   in
956   let time4 = Unix.gettimeofday () in
957   d_print_ugraph g_test;
958     if are_ugraph_eq g_safe g_test && !n_test = !n_safe then
959       begin
960         let num_eq = 
961           List.fold_left (
962             fun s (e,_,_) -> 
963               if e = Eq then s+1 else s 
964           ) 0 action_list 
965         in
966         let num_gt = 
967           List.fold_left (
968             fun s (e,_,_) ->
969               if e = Gt then s+1 else s
970           ) 0 action_list
971         in
972         let num_ge = max_edges - num_gt - num_eq in
973         let time_fast = (time4 -. time3) in
974         let time_safe = (time2 -. time1) in
975         let gap = ((time_safe -. time_fast) *. 100.0) /. time_safe in
976         let fail = if !fail then 1 else 0 in
977           print_endline 
978             (sprintf 
979                "OK %d safe %1.4f fast %1.4f %% %1.2f #eq %d #gt %d #ge %d %d" 
980                fail time_safe time_fast gap num_eq num_gt num_ge !n_safe);
981           exit 0
982       end
983     else
984       begin
985         print_endline "FAIL";
986         print_ugraph g_safe;
987         print_ugraph g_test;
988         exit 1
989       end
990 ;;
991
992  *)
993
994 let recons_univ u =
995   match u with
996   | i, None -> u
997   | i, Some uri ->
998       i, Some (UriManager.uri_of_string (UriManager.string_of_uri uri))
999
1000 let recons_entry entry =
1001   let recons_set set =
1002     SOF.fold (fun univ set -> SOF.add (recons_univ univ) set) set SOF.empty
1003   in
1004   {
1005     eq_closure = recons_set entry.eq_closure;
1006     ge_closure = recons_set entry.ge_closure;
1007     gt_closure = recons_set entry.gt_closure;
1008     in_gegt_of = recons_set entry.in_gegt_of;
1009     one_s_eq = recons_set entry.one_s_eq;
1010     one_s_ge = recons_set entry.one_s_ge;
1011     one_s_gt = recons_set entry.one_s_gt;
1012   }
1013
1014 let recons_graph (graph,uriset,o) =
1015   MAL.fold
1016     (fun universe entry map ->
1017       MAL.add (recons_univ universe) (recons_entry entry) map)
1018     graph 
1019     MAL.empty,
1020   UriManager.UriSet.fold 
1021     (fun u acc -> 
1022       UriManager.UriSet.add 
1023         (UriManager.uri_of_string (UriManager.string_of_uri u)) acc) 
1024     uriset UriManager.UriSet.empty, o
1025
1026 let assert_univ u =
1027     match u with 
1028     | (_,None) ->
1029        raise (UniverseInconsistency (lazy "This universe graph has a hole"))
1030     | _ -> ()
1031     
1032 let assert_univs_have_uri (graph,_,_) univlist =
1033   let assert_set s =
1034     SOF.iter (fun u -> assert_univ u) s
1035   in
1036   let assert_entry e =
1037     assert_set e.eq_closure;
1038     assert_set e.ge_closure;
1039     assert_set e.gt_closure;
1040     assert_set e.in_gegt_of;
1041     assert_set e.one_s_eq;
1042     assert_set e.one_s_ge;
1043     assert_set e.one_s_gt;
1044   in
1045   MAL.iter (fun k v -> assert_univ k; assert_entry v)graph;
1046   List.iter assert_univ univlist
1047   
1048 let eq u1 u2 = 
1049   match u1,u2 with
1050   | (id1, Some uri1),(id2, Some uri2) -> 
1051       id1 = id2 && UriManager.eq uri1 uri2
1052   | (id1, None),(id2, None) -> id1 = id2
1053   | _ -> false
1054   
1055 let compare (id1, uri1) (id2, uri2) = 
1056   let cmp = id1 - id2 in
1057   if cmp = 0 then
1058     match uri1,uri2 with
1059     | None, None -> 0 
1060     | Some _, None -> 1
1061     | None, Some _ -> ~-1
1062     | Some uri1, Some uri2 -> UriManager.compare uri1 uri2
1063   else
1064     cmp
1065
1066 let is_anon = function (_,None) -> true | _ -> false
1067   
1068 (* EOF *)