cdfe95296d6e4310ac04356d18e374af0688600d
[SXSI/XMLTree.git] / XMLTree.cpp
1 #include "XMLTree.h"\r
2 #include <cstring>\r
3 \r
4 // functions to convert tag positions to the corresponding tree node and viceversa. \r
5 // These are implemented in order to be able to change the tree and Tags representations, \r
6 // without affecting the code so much.\r
7 // Current implementation corresponds to balanced-parentheses representation for\r
8 // the tree, and storing 2 tags per tree node (opening and closing tags).\r
9 \r
10 // tag position -> tree node\r
11 inline treeNode tagpos2node(int t) {\r
12    return (treeNode)t;\r
13 }\r
14 \r
15 // tree node -> tag position\r
16 inline int node2tagpos(treeNode x) {\r
17    return (int)x;\r
18 }\r
19 \r
20 \r
21 //KIM OJO to prevent suprious "unused result" warnings\r
22 \r
23 inline void ufread(void *ptr, size_t size, size_t nmemb, FILE *stream){\r
24   size_t res;\r
25   res = fread(ptr,size,nmemb,stream);\r
26   if (res < nmemb)\r
27     throw "ufread I/O error";\r
28 \r
29   return;\r
30 }\r
31 \r
32 inline void ufwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream){\r
33   size_t res;\r
34   res = fwrite(ptr,size,nmemb,stream);\r
35   if (res < nmemb)\r
36     throw "ufwrite I/O error";\r
37   return;\r
38 }\r
39 \r
40 // OJO to fail cleanly while doing a realloc\r
41 // if we can't realloc we are pretty much screwed anyway but\r
42 // it makes the code clearer to not have a bunch of if (!ptr) { printf("..."); exit(1); };\r
43 inline void * urealloc(void *ptr, size_t size){\r
44 \r
45   void * dest = realloc(ptr,size);\r
46   //don't fail if we requested size 0\r
47   if (dest == NULL && size > 0 )\r
48     throw std::bad_alloc();\r
49   return dest;\r
50 \r
51 }\r
52 \r
53 inline void * ucalloc(size_t nmemb, size_t size){\r
54 \r
55   void * dest = calloc(nmemb,size);\r
56   //don't fail if we requested size 0\r
57   if (dest == NULL && nmemb > 0 && size > 0 )\r
58     throw std::bad_alloc();\r
59   return dest;\r
60 \r
61 }\r
62 \r
63 inline void * umalloc(size_t size){\r
64   void * dest = malloc(size);\r
65   if (dest == NULL && size > 0)\r
66     throw std::bad_alloc();\r
67   return dest;\r
68 }\r
69 \r
70 // Save: saves XML tree data structure to file. \r
71 void XMLTree::Save(unsigned char *filename) \r
72  {\r
73 \r
74     FILE *fp;\r
75     char filenameaux[1024];\r
76     int i;\r
77    \r
78     sprintf(filenameaux, "%s.srx", filename);\r
79     fp = fopen(filenameaux, "w");\r
80     if (fp == NULL) {\r
81        printf("Error: cannot create file %s to store the tree structure of XML collection\n", filenameaux);\r
82        exit(1);\r
83     } \r
84     \r
85     // first stores the tree topology\r
86     saveTree(Par, fp);\r
87  \r
88     // stores the table with tag names\r
89     ufwrite(&ntagnames, sizeof(int), 1, fp);\r
90     for (i=0; i<ntagnames;i++)\r
91       fprintf(fp, "%s\n",TagName[i]);\r
92     \r
93     \r
94     // stores the flags\r
95     ufwrite(&indexing_empty_texts, sizeof(bool), 1, fp);\r
96     ufwrite(&initialized, sizeof(bool), 1, fp);\r
97     ufwrite(&finished, sizeof(bool), 1, fp);\r
98     ufwrite(&disable_tc, sizeof(bool),1,fp);\r
99     \r
100     if (!indexing_empty_texts) EBVector->save(fp);\r
101     \r
102     // stores the tags\r
103     Tags->save(fp);\r
104 \r
105     // stores the texts   \r
106     if (!disable_tc)\r
107       Text->Save(fp);\r
108     if (!disable_tc){\r
109     int st = CachedText.size();\r
110     ufwrite(&st, sizeof(int),1,fp);\r
111     for (int i = 0; i< CachedText.size(); ++i){\r
112       st = CachedText.at(i).size();\r
113       ufwrite(&st, sizeof(int),1,fp);\r
114       ufwrite(CachedText.at(i).c_str(),sizeof(char),(1+strlen(CachedText.at(i).c_str())),fp);\r
115     };\r
116     };\r
117     fclose(fp);\r
118 \r
119  }\r
120 \r
121 \r
122 // Load: loads XML tree data structure from file. Returns\r
123 // a pointer to the loaded data structure\r
124 XMLTree *XMLTree::Load(unsigned char *filename, int sample_rate_text) \r
125  {\r
126 \r
127     FILE *fp;\r
128     char buffer[1024];\r
129     XMLTree *XML_Tree;\r
130     int i;\r
131     size_t s_tree = 0;\r
132     long s_text = 0;\r
133     size_t s_tags = 0;\r
134 \r
135     // first load the tree topology\r
136     sprintf(buffer, "%s.srx", filename);\r
137     fp = fopen(buffer, "r");\r
138     if (fp == NULL) {\r
139        printf("Error: cannot open file %s to load the tree structure of XML collection\n", buffer);\r
140        exit(1);\r
141     } \r
142 \r
143     XML_Tree = new XMLTree();\r
144 \r
145     XML_Tree->Par = (bp *)umalloc(sizeof(bp));\r
146 \r
147     loadTree(XML_Tree->Par, fp); \r
148 \r
149     s_tree += sizeof(bp);\r
150 \r
151     // stores the table with tag names\r
152     ufread(&XML_Tree->ntagnames, sizeof(int), 1, fp);\r
153     \r
154     s_tree += sizeof(int);\r
155 \r
156     XML_Tree->TagName = (unsigned char **)umalloc(XML_Tree->ntagnames*sizeof(unsigned char *));\r
157     \r
158     s_tags += sizeof(unsigned char*)*XML_Tree->ntagnames;\r
159 \r
160 \r
161     for (i=0; i<XML_Tree->ntagnames;i++) {\r
162       \r
163       // OJO Kim is it needed ?\r
164       int k = feof(fp);\r
165 \r
166       \r
167        // fscanf chokes on "\n" which is the case for the root element\r
168        char * r = fgets(buffer,1023,fp);\r
169        //       int r = fscanf(fp, "%s\n",buffer);\r
170        if (r==NULL)\r
171          throw "Cannot read tag list";\r
172 \r
173        // strlen is actually the right size, since there is a trailing '\n'\r
174        int len = strlen((const char*)buffer);\r
175        XML_Tree->TagName[i] = (unsigned char *)ucalloc(len,sizeof(char));\r
176        strncpy((char *)XML_Tree->TagName[i], (const char *)buffer,len - 1);\r
177        s_tags+= len*sizeof(char);\r
178     }\r
179         \r
180     // loads the flags\r
181 \r
182     ufread(&(XML_Tree->indexing_empty_texts), sizeof(bool), 1, fp);\r
183     ufread(&(XML_Tree->initialized), sizeof(bool), 1, fp);\r
184     ufread(&(XML_Tree->finished), sizeof(bool), 1, fp);\r
185     ufread(&(XML_Tree->disable_tc), sizeof(bool), 1, fp);\r
186     \r
187     s_tree+=sizeof(bool)*4;\r
188 \r
189     if (!(XML_Tree->indexing_empty_texts)) XML_Tree->EBVector = static_bitsequence_rrr02::load(fp);\r
190     \r
191     s_tree+= XML_Tree->EBVector->size();\r
192     \r
193     // loads the tags\r
194     XML_Tree->Tags = static_sequence::load(fp);\r
195     s_tree+= XML_Tree->Tags->size();\r
196 \r
197     s_text = ftell(fp);\r
198 \r
199     // loads the texts\r
200     if (!XML_Tree->disable_tc){\r
201       XML_Tree->Text = TextCollection::InitTextCollection(sample_rate_text);\r
202       XML_Tree->Text->Load(fp,sample_rate_text);\r
203       int sst;\r
204       int st;\r
205       ufread(&sst, sizeof(int),1,fp);\r
206       for (int i=0;i<sst;i++){\r
207         ufread(&st, sizeof(int),1,fp);\r
208         char* str = (char*) malloc(sizeof(char)*st+1);\r
209         ufread(str,sizeof(char),st+1,fp);\r
210         string cppstr = str;\r
211         XML_Tree->CachedText.push_back(cppstr);\r
212         free(str);\r
213       };\r
214 \r
215     }\r
216     else\r
217       XML_Tree->Text = NULL;\r
218 \r
219     s_text = ftell(fp) - s_text;\r
220 \r
221     \r
222 \r
223 \r
224     fclose(fp);\r
225 \r
226     std::cerr << "Tree part is " << s_tree/1024 << " Kbytes,\n"\r
227               << "with node->tagid part " << XML_Tree->Tags->size()/1024 << "Kbytes \n"\r
228               << "size of Tag part : " << XML_Tree->Tags->length () << " elements\n"\r
229               << "sizof(unsigned int)* " <<  XML_Tree->Tags->length () << " = " << \r
230       sizeof(unsigned int) * XML_Tree->Tags->length () / 1024 << " Kbytes\n"\r
231               << "Tag part is " << s_tags/1024 << " Kbytes,\n"\r
232               << "Text collection is " << s_text/1024 << " Kbytes \n";\r
233     return XML_Tree;\r
234  }\r
235 \r
236 \r
237 // ~XMLTree: frees memory of XML tree.\r
238 XMLTree::~XMLTree() \r
239  { \r
240     int i;\r
241 \r
242     destroyTree(Par);\r
243     free(Par); // frees the memory of struct Par\r
244    \r
245     for (i=0; i<ntagnames;i++) \r
246        free(TagName[i]);\r
247     \r
248     free(TagName);\r
249 \r
250     if (!indexing_empty_texts) {\r
251        //EBVector->~static_bitsequence_rrr02();\r
252        delete EBVector;\r
253        EBVector = NULL;\r
254     }\r
255 \r
256     //Tags->~static_sequence_wvtree();\r
257     delete Tags;\r
258     Tags = NULL;\r
259 \r
260     //Text->~TextCollection();\r
261     delete Text;\r
262     Text = NULL;\r
263 \r
264     initialized = false;\r
265     finished = false;\r
266  }\r
267 \r
268 // root(): returns the tree root.\r
269 treeNode XMLTree::Root() \r
270  {\r
271     if (!finished) {\r
272        fprintf(stderr, "Root() : Error: data structure has not been constructed properly\n");\r
273        exit(1);\r
274     }\r
275     return root_node(Par);\r
276  }\r
277 \r
278 // SubtreeSize(x): the number of nodes (and attributes) in the subtree of node x.\r
279 int XMLTree::SubtreeSize(treeNode x) \r
280  {\r
281     if (!finished) {\r
282        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
283        exit(1);\r
284     }\r
285     return subtree_size(Par, x);\r
286  }\r
287 \r
288 // SubtreeTags(x,tag): the number of occurrences of tag within the subtree of node x.\r
289 int XMLTree::SubtreeTags(treeNode x, TagType tag) \r
290  {\r
291     if (!finished) {\r
292        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
293        exit(1);\r
294     }\r
295     if (x == Root())\r
296       x = first_child(Par,x);\r
297     \r
298 \r
299     int s = x + 2*subtree_size(Par, x) - 1;\r
300  \r
301     return Tags->rank(tag, s) - Tags->rank(tag, node2tagpos(x)-1);\r
302  }\r
303 \r
304 // IsLeaf(x): returns whether node x is leaf or not. In the succinct representation\r
305 // this is just a bit inspection.\r
306 bool XMLTree::IsLeaf(treeNode x) \r
307  {\r
308     return isleaf(Par, x);\r
309  } \r
310 \r
311 // IsAncestor(x,y): returns whether node x is ancestor of node y.\r
312 bool XMLTree::IsAncestor(treeNode x, treeNode y) \r
313  {\r
314     if (!finished) {\r
315        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
316        exit(1);\r
317     }\r
318 \r
319     return is_ancestor(Par, x, y);\r
320  }\r
321 \r
322 // IsChild(x,y): returns whether node x is parent of node y.\r
323 bool XMLTree::IsChild(treeNode x, treeNode y) \r
324  {\r
325     if (!finished) {\r
326        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
327        exit(1);\r
328     }\r
329 \r
330     if (!is_ancestor(Par, x, y)) return false;\r
331     return depth(Par, x) == (depth(Par, y) + 1);\r
332  }\r
333 \r
334 // NumChildren(x): number of children of node x. Constant time with the data structure\r
335 // of Sadakane.\r
336 int XMLTree::NumChildren(treeNode x) \r
337  {\r
338     if (!finished) {\r
339        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
340        exit(1);\r
341     }\r
342 \r
343     return degree(Par, x);\r
344  }\r
345 \r
346 // ChildNumber(x): returns i if node x is the i-th children of its parent.\r
347 int XMLTree::ChildNumber(treeNode x) \r
348  {\r
349     if (!finished) {\r
350        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
351        exit(1);\r
352     }\r
353 \r
354     return child_rank(Par, x);\r
355  }\r
356 \r
357 // Depth(x): depth of node x, a simple binary rank on the parentheses sequence.\r
358 int XMLTree::Depth(treeNode x) \r
359  {\r
360     if (!finished) {\r
361        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
362        exit(1);\r
363     }\r
364 \r
365     return depth(Par, x);\r
366  }\r
367 \r
368 // Preorder(x): returns the preorder number of node x, just counting the tree\r
369 // nodes (i.e., tags, it disregards the texts in the tree).\r
370 int XMLTree::Preorder(treeNode x) \r
371  {\r
372     if (!finished) {\r
373        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
374        exit(1);\r
375     }\r
376 \r
377     return preorder_rank(Par, x);\r
378  }\r
379 \r
380 // Postorder(x): returns the postorder number of node x, just counting the tree\r
381 // nodes (i.e., tags, it disregards the texts in the tree).\r
382 int XMLTree::Postorder(treeNode x) \r
383  {\r
384     if (!finished) {\r
385        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
386        exit(1);\r
387     }\r
388     return postorder_rank(Par, x);\r
389  }\r
390 \r
391 // Tag(x): returns the tag identifier of node x.\r
392 TagType XMLTree::Tag(treeNode x) \r
393  {\r
394     if (!finished) {\r
395        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
396        exit(1);\r
397     }\r
398     \r
399     return Tags->access(node2tagpos(x));\r
400  }\r
401 \r
402 // DocIds(x): returns the range of text identifiers that descend from node x.\r
403 // returns {NULLT, NULLT} when there are no texts descending from x.\r
404 range XMLTree::DocIds(treeNode x) \r
405  {\r
406     if (!finished) {\r
407        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
408        exit(1);\r
409     }\r
410 \r
411     range r;\r
412     if (indexing_empty_texts) { // faster, no rank needed\r
413        r.min = x;\r
414        r.max = x+2*subtree_size(Par, x)-2;\r
415     }\r
416     else { // we are not indexing empty texts, we need rank\r
417        int min = EBVector->rank1(x-1);                          \r
418        int max = EBVector->rank1(x+2*subtree_size(Par, x)-2); \r
419        if (min==max) { // range is empty, no texts within the subtree of x\r
420           r.min = NULLT;\r
421           r.max = NULLT;\r
422        }\r
423        else { // the range is non-empty, there are texts within the subtree of x\r
424           r.min = min+1;\r
425           r.max = max;\r
426        }\r
427     }\r
428     return r;\r
429  }\r
430 \r
431 // Parent(x): returns the parent node of node x.\r
432 treeNode XMLTree::Parent(treeNode x) \r
433  {\r
434     if (!finished) {\r
435        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
436        exit(1);\r
437     }\r
438     if (x == Root())\r
439       return NULLT;\r
440     else\r
441       return parent(Par, x);\r
442  }\r
443 \r
444 // Child(x,i): returns the i-th child of node x, assuming it exists.\r
445 treeNode XMLTree::Child(treeNode x, int i) \r
446 {\r
447     if (!finished) {\r
448        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
449        exit(1);\r
450     }\r
451 \r
452     if (i <= OPTD) return naive_child(Par, x, i);\r
453     else return child(Par, x, i);\r
454  }\r
455 \r
456 // FirstChild(x): returns the first child of node x, assuming it exists. Very fast in BP.\r
457 treeNode XMLTree::FirstChild(treeNode x) \r
458  {\r
459     if (!finished) {\r
460        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
461        exit(1);\r
462     }\r
463 \r
464     return first_child(Par, x);\r
465  }\r
466 \r
467 // NextSibling(x): returns the next sibling of node x, assuming it exists.\r
468 treeNode XMLTree::NextSibling(treeNode x) \r
469  {\r
470     if (!finished) {\r
471        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
472        exit(1);\r
473     }\r
474     if (x == Root())\r
475       return NULLT;\r
476  \r
477     return next_sibling(Par, x);\r
478  }\r
479 \r
480 // PrevSibling(x): returns the previous sibling of node x, assuming it exists.\r
481 treeNode XMLTree::PrevSibling(treeNode x) \r
482  {\r
483     if (!finished) {\r
484        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
485        exit(1);\r
486     }\r
487 \r
488     return prev_sibling(Par, x);\r
489  }\r
490 \r
491 // TaggedChild(x,i,tag): returns the i-th child of node x tagged tag, or NULLT if there is none.\r
492 // Because of the balanced-parentheses representation of the tree, this operation is not supported\r
493 // efficiently, just iterating among the children of node x until finding the desired child.\r
494 treeNode XMLTree::TaggedChild(treeNode x, int i, TagType tag) \r
495  {\r
496     if (!finished) {\r
497        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
498        exit(1);\r
499     }\r
500 \r
501     treeNode child;\r
502    \r
503     child = first_child(Par, x); // starts at first child of node x\r
504     if (child==(treeNode)-1) return NULLT; // node x is a leaf, there is no such child\r
505     while (child!=(treeNode)-1) {\r
506        if (Tags->access(node2tagpos(child)) == tag) { // current child is labeled with tag of interest\r
507           i--;\r
508           if (i==0) return child; // we have seen i children of x tagged tag, this is the one we are looking for\r
509        }\r
510        child = next_sibling(Par, x); // OK, let's try with the next child\r
511     }\r
512     return NULLT; // no such child was found  \r
513  }\r
514 \r
515 // TaggedDesc(x,tag): returns the first node tagged tag with larger preorder than x and within\r
516 // the subtree of x. Returns NULLT if there is none.\r
517 treeNode XMLTree::TaggedDesc(treeNode x, TagType tag) \r
518  {\r
519     if (!finished) {\r
520        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
521        exit(1);\r
522     }\r
523 \r
524     int r, s;\r
525     treeNode y;\r
526     if (isleaf(Par,x))\r
527       return NULLT;\r
528 \r
529     r = (int) Tags->rank(tag, node2tagpos(x));\r
530     s = (int) Tags->select(tag, r+1);\r
531     if (s == -1) return NULLT; // there is no such node\r
532     y = tagpos2node(s); // transforms the tag position into a node position\r
533     if (!is_ancestor(Par, x, y)) return NULLT; // the next node tagged tag (in preorder) is not within the subtree of x.\r
534     else return y;\r
535  }\r
536 \r
537 // TaggedNext(x,tag): returns the first node tagged tag with larger preorder than x \r
538 // Returns NULLT if there is none.\r
539 treeNode XMLTree::TaggedNext(treeNode x, TagType tag) \r
540  {\r
541     if (!finished) {\r
542        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
543        exit(1);\r
544     }\r
545 \r
546     int r, s;\r
547     treeNode y;\r
548     if (x==NULLT)\r
549       return NULLT;\r
550 \r
551     r = (int) Tags->rank(tag, node2tagpos(x));\r
552     s = (int) Tags->select(tag, r+1);\r
553     if (s == -1) return NULLT; // there is no such node\r
554     y = tagpos2node(s); // transforms the tag position into a node position  \r
555     return (y<=x ? NULLT : y);\r
556  }\r
557 \r
558 \r
559 // TaggedPrec(x,tag): returns the first node tagged tag with smaller preorder than x and not an\r
560 // ancestor of x. Returns NULLT if there is none.\r
561 treeNode XMLTree::TaggedPrec(treeNode x, TagType tag) \r
562  {\r
563     if (!finished) {\r
564        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
565        exit(1);\r
566     }\r
567     \r
568     int r, s;\r
569     treeNode node_s, root;\r
570     r = (int)Tags->rank(tag, node2tagpos(x)-1);\r
571     if (r==0) return NULLT; // there is no such node.\r
572     s = (int)Tags->select(tag, r);\r
573     root = root_node(Par);\r
574     node_s = tagpos2node(s);\r
575     while (is_ancestor(Par, node_s, x) && (node_s!=root)) { // the one that we found is an ancestor of x\r
576        r--;\r
577        if (r==0) return NULLT; // there is no such node\r
578        s = (int)Tags->select(tag, r);  // we should use select_prev instead when provided\r
579        node_s = tagpos2node(s);\r
580     }\r
581     return NULLT; // there is no such node \r
582  }\r
583 \r
584 // TaggedFoll(x,tag): returns the first node tagged tag with larger preorder than x and not in\r
585 // the subtree of x. Returns NULLT if there is none.\r
586 treeNode XMLTree::TaggedFoll(treeNode x, TagType tag) \r
587  {\r
588     if (!finished) {\r
589        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
590        exit(1);\r
591     }\r
592 \r
593     int r, s;\r
594     if (x ==NULLT || x == Root()|| (next_sibling(Par,x) == -1 ))\r
595       return NULLT;\r
596 \r
597     r = (int) Tags->rank(tag, node2tagpos(next_sibling(Par, x))-1);\r
598     s = (int) Tags->select(tag, r+1);  // select returns -1 in case that there is no r+1-th tag.\r
599     if (s==-1) return NULLT;\r
600     else return tagpos2node(s);\r
601  }\r
602 \r
603 // PrevText(x): returns the document identifier of the text to the left \r
604 // of node x, or NULLT if x is the root node or the text is empty.\r
605 // Assumes Doc ids start from 0.\r
606 DocID XMLTree::PrevText(treeNode x) \r
607  {\r
608     if (!finished) {\r
609        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
610        exit(1);\r
611     }\r
612 \r
613     if (x == Root()) return NULLT;\r
614     if (indexing_empty_texts)  // faster, no rank needed\r
615        return (DocID)x-1;\r
616     else { // we are not indexing empty texts, rank is needed\r
617        if (EBVector->access(x-1) == 0) \r
618           return (DocID)NULLT;  // there is no text to the left of node (text is empty)\r
619        else\r
620           return (DocID)EBVector->rank1(x-1)-1;  //-1 because document ids start from 0\r
621     }\r
622  }\r
623 \r
624 // NextText(x): returns the document identifier of the text to the right\r
625 // of node x, or NULLT if x is the root node. Assumes Doc ids start from 0.\r
626 DocID XMLTree::NextText(treeNode x) \r
627  {\r
628     if (!finished) {\r
629        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
630        exit(1);\r
631     }\r
632 \r
633     if (x == Root()) return NULLT;\r
634     if (indexing_empty_texts)  // faster, no rank needed\r
635        return (DocID)x+2*subtree_size(Par, x)-1;\r
636     else { // we are not indexing empty texts, rank is needed\r
637        int p = x+2*subtree_size(Par, x)-1;\r
638        if (EBVector->access(p) == 0) // there is no text to the right of node\r
639           return (DocID)NULLT;\r
640        else\r
641           return (DocID)EBVector->rank1(p)-1; //-1 because document ids start from 0\r
642     }\r
643  }\r
644 \r
645 // MyText(x): returns the document identifier of the text below node x, \r
646 // or NULLT if x is not a leaf node or the text is empty. Assumes Doc \r
647 // ids start from 0.\r
648 DocID XMLTree::MyText(treeNode x) \r
649  {\r
650     if (!finished) {\r
651        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
652        exit(1);\r
653     }\r
654 \r
655     if (!IsLeaf(x)) return NULLT;\r
656     if (indexing_empty_texts) // faster, no rank needed\r
657        return (DocID)x;\r
658     else { // we are not indexing empty texts, rank is needed\r
659        if (EBVector->access(x) == 0)  // there is no text below node x\r
660           return (DocID)NULLT;\r
661        else\r
662           return (DocID)EBVector->rank1(x)-1; //-1 because document ids start from 0\r
663     } \r
664  }\r
665 \r
666 // TextXMLId(d): returns the preorder of document with identifier d in the tree consisting of\r
667 // all tree nodes and all text nodes. Assumes that the tree root has preorder 1.\r
668 int XMLTree::TextXMLId(DocID d) \r
669  {\r
670     if (!finished) {\r
671        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
672        exit(1);\r
673     }\r
674 \r
675     if (indexing_empty_texts) \r
676        return d + rank_open(Par, d)+1; // +1 because root has preorder 1\r
677     else { // slower, needs rank and select\r
678        int s = EBVector->select1(d+1);\r
679        return rank_open(Par, s) + d + 1; // +1 because root has preorder 1\r
680     }\r
681  }\r
682 \r
683 // NodeXMLId(x): returns the preorder of node x in the tree consisting \r
684 // of all tree nodes and all text nodes. Assumes that the tree root has\r
685 // preorder 0;\r
686 int XMLTree::NodeXMLId(treeNode x) \r
687  {\r
688     if (!finished) {\r
689        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
690        exit(1);\r
691     }\r
692 \r
693     if (indexing_empty_texts)\r
694        return x - 1 + rank_open(Par, x);\r
695     else {\r
696        if (x == Root()) return 1; // root node has preorder 1\r
697        else\r
698           return rank_open(Par, x) + EBVector->rank1(x-1);\r
699     }\r
700  }\r
701 \r
702 // ParentNode(d): returns the parent node of document identifier d.\r
703 treeNode XMLTree::ParentNode(DocID d) \r
704  {\r
705     if (!finished) {\r
706        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
707        exit(1);\r
708     }\r
709     \r
710     if (d == NULLT)\r
711       return NULLT;\r
712     \r
713     int s;\r
714     // OJO : Kim : I added the d+1. before that, else branch was \r
715     // EBVector->select1(d)\r
716     // and gave wrong results (I'm really poking a bear with a stick here).\r
717     if (indexing_empty_texts) s = d;\r
718     else s = EBVector->select1(d+1);\r
719     \r
720     if (inspect(Par,s) == CP) // is a closing parenthesis\r
721        return parent(Par, find_open(Par, s));\r
722     else // is an opening parenthesis\r
723        return (treeNode)s;\r
724      \r
725  }\r
726 \r
727 \r
728 // OpenDocument(empty_texts): it starts the construction of the data structure for\r
729 // the XML document. Parameter empty_texts indicates whether we index empty texts\r
730 // in document or not. Returns a non-zero value upon success, NULLT in case of error.\r
731 int XMLTree::OpenDocument(bool empty_texts, int sample_rate_text,bool dtc)\r
732  {\r
733     initialized = true;\r
734     finished = false;\r
735     found_attributes = false;\r
736     npar = 0;\r
737     parArraySize = 1;\r
738     ntagnames = 2;    \r
739     disable_tc = dtc;\r
740     \r
741     indexing_empty_texts = empty_texts;\r
742     \r
743     par_aux = (pb *)umalloc(sizeof(pb)*parArraySize);\r
744     \r
745     tags_aux = (TagType *) umalloc(sizeof(TagType));\r
746     \r
747     TagName = (unsigned char **) umalloc(2*sizeof(unsigned char*));\r
748 \r
749     TagName[0] = (unsigned char *) umalloc(4*sizeof(unsigned char));\r
750 \r
751     strcpy((char *) TagName[0], "<@>");\r
752 \r
753     TagName[1] = (unsigned char *) umalloc(4*sizeof(unsigned char));\r
754 \r
755     strcpy((char *) TagName[1], "<$>");\r
756 \r
757 \r
758     if (!indexing_empty_texts) \r
759       empty_texts_aux = (unsigned int *)umalloc(sizeof(unsigned int));\r
760        \r
761     \r
762     \r
763     Text = TextCollection::InitTextCollection((unsigned)sample_rate_text);\r
764     \r
765     return 1;  // indicates success in the initialization of the data structure\r
766  }\r
767 \r
768 // CloseDocument(): it finishes the construction of the data structure for the XML\r
769 // document. Tree and tags are represented in the final form, dynamic data \r
770 // structures are made static, and the flag "finished" is set to true. After that, \r
771 // the data structure can be queried.\r
772 int XMLTree::CloseDocument()\r
773  {\r
774     if (!initialized) {  // data structure has not been initialized properly\r
775        fprintf(stderr, "Error: data structure has not been initialized properly (by calling method OpenDocument)\n");\r
776        return NULLT;\r
777     }\r
778     \r
779     // closing parenthesis for the tree root\r
780     par_aux = (pb *)urealloc(par_aux, sizeof(pb)*(1+npar/(8*sizeof(pb))));\r
781     \r
782     // creates the data structure for the tree topology\r
783     Par = (bp *)umalloc(sizeof(bp));\r
784     bp_construct(Par, npar, par_aux, OPT_DEGREE|0);    \r
785     // creates structure for tags\r
786     static_bitsequence_builder * bmb = new static_bitsequence_builder_brw32(20);\r
787     static_permutation_builder * pmb = new static_permutation_builder_mrrr(PERM_SAMPLE, bmb);\r
788     static_sequence_builder * ssb = new static_sequence_builder_gmr_chunk(bmb, pmb);\r
789 \r
790 \r
791     // If we found an attribute then "<@>" is present in the tree\r
792     // if we didn't then it is not. "<$>" is never present in the tree\r
793     int ntagsize = found_attributes ? 2*ntagnames-1 : 2*ntagnames - 2;\r
794 \r
795     Tags = new static_sequence_gmr((uint *) tags_aux, (uint) npar-1,ntagsize, bmb, ssb);\r
796     \r
797     delete bmb;\r
798     delete pmb;\r
799     delete ssb;\r
800     // makes the text collection static\r
801     if (!disable_tc)\r
802       Text->MakeStatic();\r
803     \r
804     // creates the data structure marking the non-empty texts (just in the case it is necessary)\r
805     if (!indexing_empty_texts)  {\r
806        EBVector = new static_bitsequence_rrr02((uint *)empty_texts_aux,(ulong)npar,(uint)32);\r
807        free (empty_texts_aux);\r
808        empty_texts_aux = NULL;\r
809     }\r
810    \r
811     // OJO was leaked before, found by valgrind\r
812     free(tags_aux);\r
813 \r
814     tags_aux = NULL;\r
815 \r
816     finished = true;\r
817 \r
818     return 1; // indicates success in the inicialization\r
819  }\r
820 \r
821 \r
822 // NewOpenTag(tagname): indicates the event of finding a new opening tag in the document.\r
823 // Tag name is given. Returns a non-zero value upon success, and returns NULLT\r
824 // in case of failing when trying to insert the new tag.\r
825 int XMLTree::NewOpenTag(unsigned char *tagname)\r
826  {\r
827     int i;\r
828 \r
829     if (!initialized) {  // data structure has not been initialized properly\r
830        fprintf(stderr, "Error: you cannot insert a new opening tag without first calling method OpenDocument first\n");\r
831        return NULLT;\r
832     }\r
833     \r
834     // inserts a new opening parentheses in the bit sequence\r
835     if (sizeof(pb)*8*parArraySize == npar) { // no space left for the new parenthesis\r
836        par_aux = (pb *)urealloc(par_aux, sizeof(pb)*2*parArraySize);\r
837        parArraySize *= 2;\r
838     }\r
839     \r
840     setbit(par_aux,npar,OP);  // marks a new opening parenthesis\r
841 \r
842     // transforms the tagname into a tag identifier. If the tag is new, we insert\r
843     // it in the table.\r
844     for (i=0; i<ntagnames; i++)\r
845       if (strcmp((const char *)tagname,(const char *)TagName[i])==0) break;\r
846  \r
847 \r
848     // NewOpenTag("<@>") was called\r
849     if (i==0) \r
850       found_attributes=true;\r
851 \r
852     if (i==ntagnames) { // the tag is a new one, then we insert it\r
853        TagName = (unsigned char **)urealloc(TagName, sizeof(char *)*(ntagnames+1));\r
854        \r
855        if (!TagName) {\r
856           fprintf(stderr, "Error: not enough memory\n");\r
857           return NULLT;\r
858        }\r
859        \r
860        ntagnames++;\r
861        TagName[i] = (unsigned char *)umalloc(sizeof(unsigned char)*(strlen((const char *)tagname)+1));\r
862        strcpy((char *)TagName[i], (const char *)tagname);\r
863     } \r
864     tags_aux = (TagType *) urealloc(tags_aux, sizeof(TagType)*(npar + 1));\r
865 \r
866     tags_aux[npar] = i; // inserts the new tag id within the preorder sequence of tags\r
867     \r
868     npar++;\r
869     \r
870     return 1;\r
871     \r
872  }\r
873 \r
874 \r
875 // NewClosingTag(tagname): indicates the event of finding a new closing tag in the document.\r
876 // Tag name is given. Returns a non-zero value upon success, and returns NULLT\r
877 // in case of failing when trying to insert the new tag.\r
878 int XMLTree::NewClosingTag(unsigned char *tagname)\r
879  {\r
880     int i;\r
881 \r
882     if (!initialized) {  // data structure has not been initialized properly\r
883        fprintf(stderr, "Error: you cannot insert a new closing tag without first calling method OpenDocument first\n");\r
884        return NULLT;\r
885     }\r
886     \r
887     // inserts a new closing parentheses in the bit sequence\r
888     if (sizeof(pb)*8*parArraySize == npar) { // no space left for the new parenthesis\r
889        par_aux = (pb *)urealloc(par_aux, sizeof(pb)*2*parArraySize);\r
890        parArraySize *= 2;\r
891     }\r
892     \r
893     setbit(par_aux,npar,CP);  // marks a new closing opening parenthesis\r
894 \r
895     // transforms the tagname into a tag identifier. If the tag is new, we insert\r
896     // it in the table.\r
897     for (i=0; i<ntagnames; i++)\r
898        if (strcmp((const char *)tagname,(const char *)TagName[i])==0) break;\r
899  \r
900     if (i==ntagnames) { // the tag is a new one, then we insert it\r
901        TagName = (unsigned char **)urealloc(TagName, sizeof(char *)*(ntagnames+1));\r
902        \r
903        \r
904        ntagnames++;\r
905        TagName[i] = (unsigned char *)umalloc(sizeof(char)*(strlen((const char *)tagname)+2));\r
906        TagName[i][0] = '/';\r
907        strcpy((char *)&(TagName[i][1]), (const char *)tagname);\r
908     } \r
909 \r
910     tags_aux = (TagType *)urealloc(tags_aux, sizeof(TagType)*(npar + 1));\r
911 \r
912     tags_aux[npar] = i; // inserts the new tag id within the preorder sequence of tags\r
913     \r
914     npar++;\r
915 \r
916     return 1; // success\r
917     \r
918  }\r
919 \r
920 \r
921 // NewText(s): indicates the event of finding a new (non-empty) text s in the document.\r
922 // The new text is inserted within the text collection. Returns a non-zero value upon\r
923 // success, NULLT in case of error.\r
924 int XMLTree::NewText(unsigned char *s)\r
925  {\r
926     if (!initialized) {  // data structure has not been initialized properly\r
927        fprintf(stderr, "Error: you cannot insert a new text without first calling method OpenDocument first\n");\r
928        return NULLT;\r
929     }\r
930 \r
931     if (disable_tc) {\r
932       XMLTree::NewEmptyText();\r
933       return 1;\r
934     };\r
935 \r
936     if (!indexing_empty_texts) {\r
937        empty_texts_aux = (unsigned int *)urealloc(empty_texts_aux, sizeof(pb)*(1+(npar-1)/(8*sizeof(pb))));\r
938               bitset(empty_texts_aux, npar-1);  // marks the non-empty text with a 1 in the bit vector\r
939     }\r
940     \r
941     Text->InsertText(s);\r
942     string cpps = (char*) s;\r
943     CachedText.push_back(cpps); \r
944     \r
945     return 1; // success\r
946  }\r
947 \r
948 // NewEmptyText(): indicates the event of finding a new empty text in the document.\r
949 // In case of indexing empty and non-empty texts, we insert the empty texts into the\r
950 // text collection. In case of indexing only non-empty texts, it just indicates an\r
951 // empty text in the bit vector of empty texts. Returns a non-zero value upon\r
952 // success, NULLT in case of error.\r
953 int XMLTree::NewEmptyText() \r
954  {\r
955     unsigned char c = 0;\r
956     if (!initialized) {  // data structure has not been initialized properly\r
957        fprintf(stderr, "Error: you cannot insert a new empty text without first calling method OpenDocument first\n");\r
958        return NULLT;\r
959     }\r
960 \r
961     if (!indexing_empty_texts) {\r
962        empty_texts_aux = (unsigned int *)urealloc(empty_texts_aux, sizeof(pb)*(1+(npar-1)/(8*sizeof(pb))));\r
963        \r
964        bitclean(empty_texts_aux, npar-1);  // marks the empty text with a 0 in the bit vector\r
965     }\r
966     else Text->InsertText(&c); // we insert the empty text just in case we index all the texts\r
967     \r
968     return 1; // success    \r
969  }\r
970 \r
971 \r
972 // GetTagId: returns the tag identifier corresponding to a given tag name.\r
973 // Returns NULLT in case that the tag name does not exists.\r
974 TagType XMLTree::GetTagId(unsigned char *tagname)\r
975  {\r
976     int i;\r
977     // this should be changed for more efficient processing\r
978     for (i=0; i<ntagnames; i++)\r
979        if (strcmp((const char *)tagname,(const char *)TagName[i])==0) break; \r
980     if (i==ntagnames) return (TagType)NULLT; // tagname does not exists in the table\r
981     else return i;\r
982  }\r
983 \r
984 \r
985 // GetTagName(tagid): returns the tag name of a given tag identifier.\r
986 // Returns NULL in case that the tag identifier is not valid.\r
987 unsigned char *XMLTree::GetTagName(TagType tagid)\r
988  {\r
989     unsigned char *s;\r
990 \r
991     if (tagid >= ntagnames) return NULL; // invalid tag identifier\r
992     s = (unsigned char *)umalloc((strlen((const char *)TagName[tagid])+1)*sizeof(unsigned char));\r
993     strcpy((char *)s, (const char *)TagName[tagid]);\r
994     return s;\r
995  }\r
996 \r
997 \r
998 //KIM : OJO need the two following methods\r
999 \r
1000 const unsigned char *XMLTree::GetTagNameByRef(TagType tagid)\r
1001  {\r
1002     if (tagid >= ntagnames) return NULL; // invalid tag identifier\r
1003     return ((const unsigned char*)  TagName[tagid]);\r
1004  }\r
1005 \r
1006 \r
1007 \r
1008 TagType XMLTree::RegisterTag(unsigned char *tagname)\r
1009 {\r
1010   if (!finished)\r
1011     return NULLT;\r
1012   \r
1013   TagType id = XMLTree::GetTagId(tagname);\r
1014   if (id == NULLT){\r
1015     id = ntagnames;\r
1016     ntagnames = ntagnames + 1;    \r
1017     TagName = (unsigned char **) urealloc(TagName,ntagnames*(sizeof(unsigned char*)));\r
1018     TagName[id] = (unsigned char *) umalloc(sizeof(unsigned char)*strlen( (const char*) tagname)+1);\r
1019     strcpy((char*)TagName[id], (const char *)tagname);  \r
1020   };\r
1021 \r
1022   return id;\r
1023 }\r