]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/metadata/metadataDeps.ml
added alternative implementation for hMysql relying
[helm.git] / helm / software / components / metadata / metadataDeps.ml
1 (* Copyright (C) 2006, 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://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 open MetadataTypes
29
30 module Pp = GraphvizPp.Dot
31 module UriSet = UriManager.UriSet
32
33 let strip_prefix s =
34   let prefix_len = String.length position_prefix in
35   String.sub s prefix_len (String.length s - prefix_len)
36
37 let parse_pos =
38   function
39     | Some s, Some d ->
40         (match strip_prefix s with
41         | "MainConclusion" -> `MainConclusion (Some (Eq (int_of_string d)))
42         | "MainHypothesis" -> `MainHypothesis (Some (Eq (int_of_string d)))
43         | s ->
44             prerr_endline ("Invalid main position: " ^ s);
45             assert false)
46     | Some s, None ->
47         (match strip_prefix s with
48         | "InConclusion" -> `InConclusion
49         | "InHypothesis" -> `InHypothesis
50         | "InBody" -> `InBody
51         | s ->
52             prerr_endline ("Invalid position: " ^ s);
53             assert false)
54     | _ -> assert false
55
56 let unbox_row = function `Obj (uri, pos) -> (uri, pos)
57
58 let direct_deps ~dbd uri =
59   let obj_metadata_of_row =
60     function
61       | [| Some _; Some occurrence; pos; depth |] ->
62           `Obj (UriManager.uri_of_string occurrence, parse_pos (pos, depth))
63       | _ ->
64           prerr_endline "invalid (direct) refObj metadata row";
65           assert false 
66   in
67   let do_query tbl =
68     let res = HSql.exec dbd (SqlStatements.direct_deps tbl uri) in
69     let deps =
70       HSql.map res (fun row -> unbox_row (obj_metadata_of_row row)) in
71     deps
72   in
73   do_query (MetadataTypes.obj_tbl ())
74     @ do_query MetadataTypes.library_obj_tbl
75
76 let inverse_deps ~dbd uri =
77   let inv_obj_metadata_of_row =
78     function
79       | [| Some src; Some _; pos; depth |] ->
80           `Obj (UriManager.uri_of_string src, parse_pos (pos, depth))
81       | _ ->
82           prerr_endline "invalid (inverse) refObj metadata row";
83           assert false 
84   in
85   let do_query tbl =
86     let res = HSql.exec dbd (SqlStatements.inverse_deps tbl uri) in
87     let deps =
88       HSql.map res (fun row -> unbox_row (inv_obj_metadata_of_row row)) in
89     deps
90   in
91   do_query (MetadataTypes.obj_tbl ())
92     @ do_query MetadataTypes.library_obj_tbl
93
94 let topological_sort ~dbd uris =
95  let module OrderedUri =
96   struct
97    type t = UriManager.uri
98    let compare = UriManager.compare
99   end in
100  let module Topo = HTopoSort.Make(OrderedUri) in
101   Topo.topological_sort uris
102    (fun uri -> fst (List.split (direct_deps ~dbd uri)))
103
104 let sorted_uris_of_baseuri ~dbd baseuri =
105    let sql_pat = 
106       Pcre.replace ~rex:(Pcre.regexp "_") ~templ:"\\_" baseuri ^ "%" 
107    in
108    let query =
109       Printf.sprintf
110          ("SELECT source FROM %s WHERE source LIKE \"%s\" UNION "^^
111           "SELECT source FROM %s WHERE source LIKE \"%s\"")
112          (MetadataTypes.name_tbl ()) sql_pat
113          MetadataTypes.library_name_tbl sql_pat
114    in
115    let result = HSql.exec dbd query in
116    let map cols = match cols.(0) with
117       | Some s -> UriManager.uri_of_string s
118       | _ -> assert false
119    in
120    let uris = HSql.map result map in
121    let sorted_uris = topological_sort ~dbd uris in
122    let filter_map uri =
123       let s =
124          Pcre.replace ~rex:(Pcre.regexp "#xpointer\\(1/1\\)") ~templ:""
125                       (UriManager.string_of_uri uri)
126       in
127       try ignore (Pcre.exec ~rex:(Pcre.regexp"#xpointer") s); None
128       with Not_found -> Some (UriManager.uri_of_string s)
129    in
130    HExtlib.filter_map filter_map sorted_uris
131
132 module DepGraph =
133 struct
134   module UriTbl = UriManager.UriHashtbl
135
136   let fat_value = 20
137   let fat_increment = fat_value
138   let incomplete_attrs = ["style", "dashed"]
139   let global_node_attrs = ["fontsize", "12"; "width", ".4"; "height", ".4"]
140
141   let label_of_uri uri = UriManager.name_of_uri uri
142   (*let label_of_uri uri = UriManager.string_of_uri uri*)
143
144   type neighborhood =
145     { adjacency: UriManager.uri list lazy_t;  (* all outgoing edges *)
146       mutable shown: int                      (* amount of edges to show *)
147     }
148
149     (** <adjacency list of the dependency graph,
150      *   root,
151      *   generator function,
152      *   invert edges on render?>
153      * All dependency graph have a single root, it is kept here to have a
154      * starting point for graph traversals *)
155   type t =
156     neighborhood UriTbl.t * UriManager.uri
157       * (UriManager.uri -> UriManager.uri list) * bool
158
159   let dummy =
160     UriTbl.create 0, UriManager.uri_of_string "cic:/a.con",
161       (fun _ -> []), false
162
163   let render fmt (adjlist, root, _f, invert) =
164     let is_complete uri =
165       try
166         let neighbs = UriTbl.find adjlist uri in
167         Lazy.lazy_is_val neighbs.adjacency
168           && neighbs.shown >= List.length (Lazy.force neighbs.adjacency)
169       with Not_found ->
170         (*eprintf "Node '%s' not found.\n" (UriManager.string_of_uri uri);*)
171         assert false
172     in
173     Pp.header ~graph_type:"strict digraph" ~graph_attrs:["rankdir", "LR"] ~node_attrs:global_node_attrs fmt;
174     let rec aux =
175       function
176         | [] -> ()
177         | uri :: tl ->
178             let suri = UriManager.string_of_uri uri in
179             Pp.node suri
180               ~attrs:([ "href", UriManager.string_of_uri uri;
181                         "label", label_of_uri uri
182                 ] @ (if is_complete uri then [] else incomplete_attrs))
183               fmt;
184             let new_nodes = ref [] in
185             (try
186               let neighbs = UriTbl.find adjlist uri in
187               if Lazy.lazy_is_val neighbs.adjacency then begin
188                 let adjacency, _ =
189                   HExtlib.split_nth neighbs.shown (Lazy.force neighbs.adjacency)
190                 in
191                 List.iter
192                   (fun dest ->
193                     let uri1, uri2 = if invert then dest, uri else uri, dest in
194                     Pp.edge (UriManager.string_of_uri uri1)
195                       (UriManager.string_of_uri uri2) fmt)
196                   adjacency;
197                 new_nodes := adjacency
198               end;
199             with Not_found -> ());
200             aux (!new_nodes @ tl)
201     in
202     aux [root];
203     Pp.trailer fmt
204
205   let expand uri (adjlist, _root, f, _invert) =
206     (*eprintf "expanding uri %s\n%!" (UriManager.string_of_uri uri);*)
207     try
208       let neighbs = UriTbl.find adjlist uri in
209       if not (Lazy.lazy_is_val neighbs.adjacency) then
210           (* node has never been expanded *)
211         let adjacency = Lazy.force neighbs.adjacency in
212         let weight = min (List.length adjacency) fat_value in
213         List.iter
214           (fun dest ->
215             (* perform look ahead of 1 edge to avoid making as expandable nodes
216              * which have no outgoing edges *)
217             let next_level = f dest in
218             let neighborhood =
219               if List.length next_level = 0 then begin
220                 (* no further outgoing edges, "expand" the node right now *)
221                 let lazy_val = lazy next_level in
222                 ignore (Lazy.force lazy_val);
223                 { adjacency = lazy_val; shown = 0 }
224               end else
225                 { adjacency = lazy next_level; shown = 0 }
226             in
227             (*UriTbl.add adjlist dest { adjacency = lazy (f dest); shown = 0 }*)
228             UriTbl.add adjlist dest neighborhood)
229           adjacency;
230         neighbs.shown <- weight;
231         fst (HExtlib.split_nth weight adjacency), weight
232       else begin  (* nodes has been expanded at least once *)
233         let adjacency = Lazy.force neighbs.adjacency in
234         let total_nodes = List.length adjacency in
235         if neighbs.shown < total_nodes then begin
236           (* some more children to show ... *)
237           let shown_before = neighbs.shown in
238           neighbs.shown <- min (neighbs.shown + fat_increment) total_nodes;
239           let new_shown = neighbs.shown - shown_before in
240           (fst (HExtlib.split_nth new_shown (List.rev adjacency))), new_shown
241         end else
242           [], 0 (* all children are already shown *)
243       end
244     with Not_found ->
245       (*eprintf "uri not found: %s\n%!" (UriManager.string_of_uri uri);*)
246       [], 0
247
248   let collapse uri (adjlist, _root, f, _invert) =
249     try
250       let neighbs = UriTbl.find adjlist uri in
251       if Lazy.lazy_is_val neighbs.adjacency then
252         (* do not collapse already collapsed nodes *)
253         if Lazy.force neighbs.adjacency <> [] then
254           (* do not collapse nodes with no outgoing edges *)
255           UriTbl.replace adjlist uri { adjacency = lazy (f uri); shown = 0 }
256     with Not_found ->
257       (* do not add a collapsed node if it was not part of the graph *)
258       ()
259
260   let graph_of_fun ?(invert = false) f ~dbd uri =
261     let f ~dbd uri =
262       (*eprintf "invoking graph fun on %s...\n%!" (UriManager.string_of_uri uri);*)
263       let uris = fst (List.split (f ~dbd uri)) in
264       let uriset = List.fold_right UriSet.add uris UriSet.empty in
265       let res = UriSet.elements uriset in
266       (*eprintf "returned uris: %s\n%!"*)
267         (*(String.concat " " (List.map UriManager.string_of_uri res));*)
268       res
269     in
270     let adjlist = UriTbl.create 17 in
271     let gen_f = f ~dbd in
272     UriTbl.add adjlist uri { adjacency = lazy (gen_f uri); shown = 0 };
273     let dep_graph = adjlist, uri, gen_f, invert in
274     let rec rec_expand weight =
275       function
276         | [] -> ()
277         | uri :: tl when weight >= fat_value -> ()
278         | uri :: tl ->
279             let new_nodes, increase = expand uri dep_graph in
280             rec_expand (weight + increase) (new_nodes @ tl) in
281     rec_expand 1 [uri];
282     dep_graph
283
284   let direct_deps = graph_of_fun direct_deps
285   let inverse_deps = graph_of_fun ~invert:true inverse_deps
286
287   let expand uri graph =
288     try
289       ignore (expand uri graph)
290     with Not_found -> ()
291 end
292