1 /******************************************************************************
2 * Copyright (C) 2006-2008 by Veli Mäkinen and Niko Välimäki *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU Lesser General Public License as published *
7 * by the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU Lesser General Public License for more details. *
15 * You should have received a copy of the GNU Lesser General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 *****************************************************************************/
21 #include "TextCollection.h"
30 #include <cstring> // For strlen()
36 using SXSI::TextCollection;
38 // Save file version info
39 const uchar CSA::versionFlag = 2;
41 ////////////////////////////////////////////////////////////////////////////
42 // Class CSA::THuffAlphabetRank
44 CSA::THuffAlphabetRank::THuffAlphabetRank(uchar *s, TextPosition n, TCodeEntry *codetable, unsigned level) {
50 this->codetable = codetable;
52 bool *B = new bool[n];
55 for (i=0; i< n; i++) {
56 printf("%c:", (char)((int)s[i]-128));
57 for (r=0;r<codetable[(int)s[i]].bits;r++)
58 if (codetable[(int)s[i]].code & (1u <<r))
64 if (level > 100) return;*/
66 if (codetable[(int)s[i]].code & (1u << level)) {
71 if (sum==0 || sum==n) {
76 uchar *sfirst, *ssecond;
78 sfirst = new uchar[n-sum];
80 ssecond = new uchar[sum];
83 if (B[i]) ssecond[k++] = s[i];
84 else sfirst[j++] = s[i];
85 ulong *Binbits = new ulong[n/W+1];
87 Tools::SetField(Binbits,1,i,B[i]);
89 bitrank = new BitRank(Binbits,n,true);
91 left = new THuffAlphabetRank(sfirst,j,codetable,level+1);
95 right = new THuffAlphabetRank(ssecond,k,codetable,level+1);
101 bool CSA::THuffAlphabetRank::Test(uchar *s, ulong n) {
102 // testing that the code works correctly
110 if (C[(int)s[i]] != (int)rank((int)s[i],i)) {
112 printf("%d (%c): %d<>%d\n",i,(int)s[i]-128,C[(int)s[i]],(int)rank((int)s[i],i));
118 CSA::THuffAlphabetRank::~THuffAlphabetRank() {
119 if (left!=NULL) delete left;
120 if (right!=NULL) delete right;
126 * Saving data fields:
133 void CSA::THuffAlphabetRank::Save(FILE *file)
138 CSA::THuffAlphabetRank::THuffAlphabetRank(FILE *file)
144 /////////////////////////////////////////////f///////////////////////////////
148 * Constructor inits an empty dynamic FM-index.
149 * Samplerate defaults to TEXTCOLLECTION_DEFAULT_SAMPLERATE.
151 CSA::CSA(unsigned samplerate)
152 : n(0), samplerate(0), alphabetrank(0), sampled(0), suffixes(0), suffixDocId(0), positions(0),
153 codetable(0), dynFMI(0), numberOfTexts(0), numberOfAllTexts(0), maxTextLength(0), endmarkerDocId(0),
154 textLength(0), textStartPos(0), emptyTextRank(0)
156 this->samplerate = samplerate;
158 // FIXME TODO : DynFMI needs distribution of characters before hand
159 // This will create fully balanced wavelet tree for all chars [0, 255].
161 for (unsigned i = 0; i < 255; ++i)
164 dynFMI = new DynFMI(temp, 1, 255, false);
166 /* Debug code: take char distribution from data.txt.
167 uchar *temp = Tools::GetFileContents("data.txt", 0);
168 dynFMI = new DynFMI(temp,1790000, strlen((char *)temp), false);
175 * Given text must include end-marker.
176 * Text identifiers are numbered starting from 0.
178 void CSA::InsertText(uchar const * text)
183 TextPosition m = std::strlen((char *)text) + 1;
184 if (m > maxTextLength)
185 maxTextLength = m; // Store length of the longest text seen so far.
190 this->numberOfTexts ++;
191 this->numberOfAllTexts ++;
192 dynFMI->addText(text, m);
196 emptyTextId.insert(numberOfAllTexts); // FIXME Using too much space here
197 this->numberOfAllTexts ++; // Replace with dynamic bitvector
201 void CSA::MakeStatic()
205 throw std::runtime_error("CSA::MakeStatic(): Data structure is already static (dynFMI == 0).");
207 // Bitvector of empty texts
209 //std::cout << std::endl << "texts: " << numberOfTexts << ", all texts " << numberOfAllTexts << ", size : " << emptyTextId.size() <<std::endl;
210 ulong *tempB = new ulong[numberOfAllTexts/W + 1];
211 for (ulong i = 0; i < numberOfAllTexts/W + 1; ++i)
213 for (std::set<unsigned>::const_iterator it = emptyTextId.begin(); it != emptyTextId.end(); ++it)
214 Tools::SetField(tempB, 1, (*it), 1);
216 emptyTextRank = new BSGAP(tempB, numberOfAllTexts, true);
219 uchar *bwt = dynFMI->getBWT();
220 /*printf("123456789012345678901234567890123456789\n");
221 for (TextPosition i = 0; i < n; i ++)
223 printf("%d", (int)bwt[i]);
225 printf("%c", bwt[i]);
229 /* for (TextPosition i = 1; i <= n; i ++)
231 printf("LF[%lu, %c] = %lu\n", i, (*dynFMI)[i], dynFMI->LFmapping(i));
235 assert(numberOfTexts == dynFMI->getCollectionSize());
240 makewavelet(bwt); // Deletes bwt!
243 // Calculate BWT end-marker position (of last inserted text)
244 // and the length of the first text (counter l):
248 uchar c = alphabetrank->access(i);
251 i = C[c]+alphabetrank->rank(c, i)-1;
253 c = alphabetrank->access(i);
256 assert(bwtEndPos < n);
257 //printf("bwtEndPos = %lu\n", bwtEndPos);
259 // Build up arrays for text length and starting positions
260 // FIXME Remove, temp data
261 textLength = new BlockArray(numberOfTexts, Tools::CeilLog2(maxTextLength));
262 textStartPos = new BlockArray(numberOfTexts, Tools::CeilLog2(this->n));
263 (*textLength)[0] = l;
264 (*textStartPos)[0] = 0; // Rest of the values are updated in CSA::maketables().
266 // Make sampling tables
270 bool CSA::EmptyText(DocId k) const
272 assert(k < (DocId)numberOfTexts);
273 if (emptyTextRank->IsBitSet(k))
278 uchar* CSA::GetText(DocId k) const
280 assert(k < (DocId)numberOfTexts);
283 if (emptyTextRank->IsBitSet(k, &textRank))
285 uchar* result = new uchar[1];
289 // Map to non-empty text
290 k -= textRank; //emptyTextRank->rank(k);
294 string result; //TextPosition j = (*textLength)[k] - 1;
296 uchar c = alphabetrank->access(i);
300 i = C[c]+alphabetrank->rank(c,i)-1;
302 c = alphabetrank->access(i); // "next" char.
305 // Convert to uchar (FIXME return string?)
307 uchar* res = new uchar[i+1];
309 for (ulong j = 0; j < i; ++j)
310 res[i-j-1] = result[j];
315 uchar* CSA::GetText(DocId k, TextPosition i, TextPosition j) const
317 assert(k < (DocId)numberOfTexts);
318 assert(j < (*textLength)[k]);
322 if (emptyTextRank->IsBitSet(k, &textRank))
324 uchar* result = new uchar[1];
329 // Map to non-empty text
330 k -= textRank; // emptyTextRank->rank(k);
332 // Start position of k'th text
333 ulong start = (*textStartPos)[k];
335 return Substring(i + start, j-i+1);
338 /******************************************************************
339 * Existential queries
341 bool CSA::IsPrefix(uchar const * pattern) const
343 TextPosition m = strlen((char *)pattern);
347 TextPosition sp = 0, ep = 0;
348 Search(pattern, m, &sp, &ep);
350 // Check for end-marker(s) in result interval
351 if (CountEndmarkers(sp, ep))
356 bool CSA::IsSuffix(uchar const *pattern) const
358 // Here counting is as fast as IsSuffix():
359 if (CountSuffix(pattern) > 0)
364 bool CSA::IsEqual(uchar const *pattern) const
366 TextPosition m = std::strlen((char *)pattern);
369 if (numberOfAllTexts - numberOfTexts > 0u)
370 return true; // Empty texts exists
371 return false; // No empty texts exists
374 TextPosition sp = 0, ep = 0;
375 // Match including end-marker
376 Search(pattern, m+1, &sp, &ep);
378 // Check for end-marker(s) in result interval
379 if (CountEndmarkers(sp, ep))
384 bool CSA::IsContains(uchar const * pattern) const
386 TextPosition m = strlen((char *)pattern);
390 TextPosition sp = 0, ep = 0;
391 // Just check if pattern exists somewhere
392 ulong count = Search(pattern, m, &sp, &ep);
399 bool CSA::IsLessThan(uchar const*) const
406 /******************************************************************
409 unsigned CSA::CountPrefix(uchar const * pattern) const
411 TextPosition m = strlen((char *)pattern);
413 return numberOfAllTexts;
415 TextPosition sp = 0, ep = 0;
416 Search(pattern, m, &sp, &ep);
418 // Count end-markers in result interval
419 return CountEndmarkers(sp, ep);
422 unsigned CSA::CountSuffix(uchar const * pattern) const
424 TextPosition m = strlen((char *)pattern);
426 return numberOfAllTexts;
428 TextPosition sp = 0, ep = 0;
429 // Search with end-marker
430 unsigned count = (unsigned) Search(pattern, m+1, &sp, &ep);
435 unsigned CSA::CountEqual(uchar const *pattern) const
437 TextPosition m = strlen((char const *)pattern);
439 return numberOfAllTexts - numberOfTexts; // Empty texts.
441 TextPosition sp = 0, ep = 0;
442 // Match including end-marker
443 Search(pattern, m+1, &sp, &ep);
445 // Count end-markers in result interval
446 return CountEndmarkers(sp, ep);
449 unsigned CSA::CountContains(uchar const * pattern) const
451 TextPosition m = strlen((char const *)pattern);
453 return numberOfAllTexts; // Total number of texts.
455 // Here counting is as slow as fetching the result set
456 // because we would have to filter out occ's that fall within same document.
457 TextCollection::document_result result = Contains(pattern);
458 return result.size();
461 unsigned CSA::CountLessThan(uchar const * pattern) const
469 * Document reporting queries
471 TextCollection::document_result CSA::Prefix(uchar const * pattern) const
473 TextPosition m = strlen((char *)pattern);
475 return TextCollection::document_result(); // FIXME Should return all 1...k
477 TextPosition sp = 0, ep = 0;
478 Search(pattern, m, &sp, &ep);
480 TextCollection::document_result result;
482 // Report end-markers in result interval
483 unsigned resultSize = CountEndmarkers(sp, ep);
487 result.reserve(resultSize); // Try to avoid reallocation.
489 // Iterate through end-markers in [sp,ep]:
492 i = alphabetrank->rank(0, sp - 1);
495 // End-marker we found belongs to the "preceeding" doc in the collection
496 DocId docId = ((*endmarkerDocId)[i] + 1) % numberOfTexts;
498 docId = emptyTextRank->select0(docId+1);
499 result.push_back(docId);
508 TextCollection::document_result CSA::Suffix(uchar const * pattern) const
510 TextPosition m = strlen((char *)pattern);
512 return TextCollection::document_result(); // FIXME Should return all 1...k
514 TextPosition sp = 0, ep = 0;
515 // Search with end-marker
516 Search(pattern, m+1, &sp, &ep);
518 TextCollection::document_result result;
519 result.reserve(ep-sp+1); // Try to avoid reallocation.
521 ulong sampled_rank_i = 0;
522 // Check each occurrence
523 for (; sp <= ep; ++sp)
527 uchar c = alphabetrank->access(i);
528 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
530 i = C[c]+alphabetrank->rank(c,i)-1;
531 c = alphabetrank->access(i);
533 // Assert: c == '\0' OR sampled->IsBitSet(i)
537 // Rank among the end-markers in BWT
538 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
540 // End-marker that we found belongs to the "preceeding" doc in collection:
541 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
543 docId = emptyTextRank->select0(docId+1);
544 result.push_back(docId);
546 else // Sampled position
548 DocId docId = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
550 docId = emptyTextRank->select0(docId+1);
551 result.push_back(docId);
558 TextCollection::document_result CSA::Equal(uchar const *pattern) const
560 TextPosition m = strlen((char const *)pattern);
562 return TextCollection::document_result(); // FIXME Should return all empty texts
564 TextPosition sp = 0, ep = 0;
565 // Match including end-marker
566 Search(pattern, m+1, &sp, &ep);
568 TextCollection::document_result result;
570 // Report end-markers in result interval
571 unsigned resultSize = CountEndmarkers(sp, ep);
575 result.reserve(resultSize); // Try to avoid reallocation.
579 i = alphabetrank->rank(0, sp - 1);
582 // End-marker we found belongs to the "previous" doc in the collection
583 DocId docId = ((*endmarkerDocId)[i] + 1) % numberOfTexts;
585 docId = emptyTextRank->select0(docId+1);
586 result.push_back(docId);
596 TextCollection::document_result CSA::Contains(uchar const * pattern) const
598 TextPosition m = strlen((char *)pattern);
600 return TextCollection::document_result();
602 TextPosition sp = 0, ep = 0;
603 // Search all occurrences
604 Search(pattern, m, &sp, &ep);
606 // We want unique document indentifiers, using std::set to collect them
607 std::set<DocId> resultSet;
609 ulong sampled_rank_i = 0;
610 // Check each occurrence
611 for (; sp <= ep; ++sp)
614 uchar c = alphabetrank->access(i);
615 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
617 i = C[c]+alphabetrank->rank(c,i)-1; // LF-mapping
618 c = alphabetrank->access(i);
622 // Rank among the end-markers in BWT
623 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
625 // End-marker that we found belongs to the "preceeding" doc in collection:
626 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
627 resultSet.insert(docId);
631 DocId di = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
632 assert((unsigned)di < numberOfTexts);
633 resultSet.insert(di);
637 // Convert std::set to std::vector
638 TextCollection::document_result result(resultSet.begin(), resultSet.end());
640 for (document_result::iterator it = result.begin(); it != result.end(); ++it)
641 *it = emptyTextRank->select0(*it+1);
645 TextCollection::document_result CSA::LessThan(uchar const * pattern) const
649 return document_result();
653 * Full result set queries
655 TextCollection::full_result CSA::FullContains(uchar const * pattern) const
657 TextPosition m = strlen((char *)pattern);
659 return full_result(); // FIXME Throw exception?
661 TextPosition sp = 0, ep = 0;
662 // Search all occurrences
663 Search(pattern, m, &sp, &ep);
666 result.reserve(ep-sp+1); // Try to avoid reallocation.
668 ulong sampled_rank_i = 0;
669 // Report each occurrence
670 for (; sp <= ep; ++sp)
673 TextPosition dist = 0;
674 uchar c = alphabetrank->access(i);
675 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
677 i = C[c]+alphabetrank->rank(c,i)-1;
678 c = alphabetrank->access(i);
683 // Rank among the end-markers in BWT
684 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
686 // End-marker that we found belongs to the "preceeding" doc in collection:
687 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
689 docId = emptyTextRank->select0(docId+1);
690 result.push_back(make_pair(docId, dist));
694 TextPosition textPos = (*suffixes)[sampled_rank_i-1]+dist; //sampled->rank(i)-1] + dist;
695 DocId docId = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
696 // textPos = textPos - (*textStartPos)[docId]; // Offset inside the text
699 docId = emptyTextRank->select0(docId+1);
700 result.push_back(make_pair(docId, textPos));
709 * Save index to a file handle
711 * Throws a std::runtime_error exception on i/o error.
712 * First byte that is saved represents the version number of the save file.
713 * In version 2 files, the data fields are:
718 TextPosition bwtEndPos;
719 static_sequence * alphabetrank;
721 BlockArray *suffixes;
722 BlockArray *suffixDocId;
723 unsigned numberOfTexts;
724 unsigned numberOfAllTexts;
726 BlockArray *endmarkerDocId;
727 BSGAP *emptyTextRank;
729 void CSA::Save(FILE *file) const
731 // Saving version info:
732 if (std::fwrite(&versionFlag, 1, 1, file) != 1)
733 throw std::runtime_error("CSA::Save(): file write error (version flag).");
735 if (std::fwrite(&(this->n), sizeof(TextPosition), 1, file) != 1)
736 throw std::runtime_error("CSA::Save(): file write error (n).");
737 if (std::fwrite(&(this->samplerate), sizeof(unsigned), 1, file) != 1)
738 throw std::runtime_error("CSA::Save(): file write error (samplerate).");
740 for(ulong i = 0; i < 256; ++i)
741 if (std::fwrite(this->C + i, sizeof(unsigned), 1, file) != 1)
742 throw std::runtime_error("CSA::Save(): file write error (C table).");
744 if (std::fwrite(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
745 throw std::runtime_error("CSA::Save(): file write error (bwt end position).");
747 alphabetrank->save(file);
749 suffixes->Save(file);
750 suffixDocId->Save(file);
752 if (std::fwrite(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
753 throw std::runtime_error("CSA::Save(): file write error (numberOfTexts).");
754 if (std::fwrite(&(this->numberOfAllTexts), sizeof(unsigned), 1, file) != 1)
755 throw std::runtime_error("CSA::Save(): file write error (numberOfAllTexts).");
756 if (std::fwrite(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
757 throw std::runtime_error("CSA::Save(): file write error (maxTextLength).");
759 endmarkerDocId->Save(file);
760 emptyTextRank->Save(file);
765 * Load index from a file handle
767 * Throws a std::runtime_error exception on i/o error.
768 * For more info, see CSA::Save().
770 void CSA::Load(FILE *file, unsigned samplerate)
773 delete dynFMI; dynFMI = 0;
774 delete alphabetrank; alphabetrank = 0;
775 delete sampled; sampled = 0;
776 delete suffixes; suffixes = 0;
777 delete suffixDocId; suffixDocId = 0;
778 delete positions; positions = 0;
779 delete [] codetable; codetable = 0;
781 delete endmarkerDocId; endmarkerDocId = 0;
782 delete emptyTextRank; emptyTextRank = 0;
783 // FIXME Remove following:
784 delete textLength; textLength = 0;
785 delete textStartPos; textStartPos = 0;
787 this->maxTextLength = 0;
788 this->numberOfTexts = 0;
789 this->numberOfAllTexts = 0;
790 this->samplerate = samplerate;
794 if (std::fread(&verFlag, 1, 1, file) != 1)
795 throw std::runtime_error("CSA::Load(): file read error (version flag).");
796 if (verFlag != CSA::versionFlag)
797 throw std::runtime_error("CSA::Load(): invalid save file version.");
799 if (std::fread(&(this->n), sizeof(TextPosition), 1, file) != 1)
800 throw std::runtime_error("CSA::Load(): file read error (n).");
801 if (std::fread(&samplerate, sizeof(unsigned), 1, file) != 1)
802 throw std::runtime_error("CSA::Load(): file read error (samplerate).");
803 // FIXME samplerate can not be changed during load.
804 // if (this->samplerate == 0)
805 // this->samplerate = samplerate;
807 for(ulong i = 0; i < 256; ++i)
808 if (std::fread(this->C + i, sizeof(unsigned), 1, file) != 1)
809 throw std::runtime_error("CSA::Load(): file read error (C table).");
811 if (std::fread(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
812 throw std::runtime_error("CSA::Load(): file read error (bwt end position).");
814 alphabetrank = static_sequence::load(file);
815 sampled = new BSGAP(file);
816 suffixes = new BlockArray(file);
817 suffixDocId = new BlockArray(file);
819 if (std::fread(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
820 throw std::runtime_error("CSA::Load(): file read error (numberOfTexts).");
821 if (std::fread(&(this->numberOfAllTexts), sizeof(unsigned), 1, file) != 1)
822 throw std::runtime_error("CSA::Load(): file read error (numberOfAllTexts).");
823 if (std::fread(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
824 throw std::runtime_error("CSA::Load(): file read error (maxTextLength).");
826 endmarkerDocId = new BlockArray(file);
827 emptyTextRank = new BSGAP(file);
829 // FIXME Construct data structures with new samplerate
830 //maketables(); // FIXME: this will redo text length tables
836 * Rest of the functions follow...
841 uchar * CSA::Substring(TextPosition i, TextPosition l) const
843 uchar *result = new uchar[l + 1];
851 TextPosition k = i + l - 1;
852 // Check for end of the string
859 TextPosition skip = samplerate - k % samplerate - 1;
861 if (k / samplerate + 1 >= n / samplerate)
868 j = (*positions)[k/samplerate+1];
869 //cout << samplerate << ' ' << j << '\n';
872 for (dist = 0; dist < skip + l; dist++)
874 int c = alphabetrank->access(j); //charAtPos(j, &alphabetrank_tmp);
877 // Rank among the end-markers in BWT
878 unsigned endmarkerRank = alphabetrank->rank(0, j) - 1;
879 j = (*endmarkerDocId)[endmarkerRank]; // LF-mapping for end-marker
882 j = C[c]+alphabetrank->rank(c,j)-1; // LF-mapping
884 result[l + skip - dist - 1] = c;
890 /*TextPosition CSA::inverse(TextPosition i)
892 TextPosition skip = samplerate - i % samplerate;
894 if (i / samplerate + 1 >= n / samplerate)
901 j = (*positions)[i/samplerate+1];
902 //cout << samplerate << ' ' << j << '\n';
907 int c = alphabetrank->charAtPos(j);
908 j = C[c]+alphabetrank->rank(c,j)-1; // LF-mapping
914 ulong CSA::Search(uchar const * pattern, TextPosition m, TextPosition *spResult, TextPosition *epResult) const
916 // use the FM-search replacing function Occ(c,1,i) with alphabetrank->rank(c,i)
917 int c = (int)pattern[m-1];
919 TextPosition sp = C[c];
920 TextPosition ep = C[c+1]-1;
921 while (sp<=ep && i>=1)
923 // printf("i = %lu, c = %c, sp = %lu, ep = %lu\n", i, pattern[i], sp, ep);
924 c = (int)pattern[--i];
925 sp = C[c]+alphabetrank->rank(c,sp-1);
926 ep = C[c]+alphabetrank->rank(c,ep)-1;
936 /*TextPosition CSA::LF(uchar c, TextPosition &sp, TextPosition &ep)
938 sp = C[(int)c]+alphabetrank->rank(c,sp-1);
939 ep = C[(int)c]+alphabetrank->rank(c,ep)-1;
947 CSA::TextPosition CSA::Lookup(TextPosition i) const
950 while (!sampled->IsBitSet(i))
953 int c = alphabetrank->access(i);
956 // End-markers are sampled
957 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
958 DocId docId = (*endmarkerDocId)[endmarkerRank];
959 return (*textStartPos)[docId] + dist;
961 i = C[c]+alphabetrank->rank(c,i)-1;
965 return (*suffixes)[sampled->rank(i)-1]+dist;
977 delete endmarkerDocId;
980 delete emptyTextRank;
983 void CSA::makewavelet(uchar *bwt)
992 if (C[i]>0) {min = i; break;}
993 for (i=255;i>=min;--i)
994 if (C[i]>0) {max = i; break;}
997 /*for(i = 0; i < 256; i++)
998 if (C[i]>0) printf("C[%lu] = %lu\n", i, C[i]);
1001 ulong prev=C[0], temp;
1003 for (i=1;i<256;i++) {
1008 // this->codetable = node::makecodetable(bwt,n);
1009 // alphabetrank = new THuffAlphabetRank(bwt,n, this->codetable,0);
1011 //alphabetrank = new RLWaveletTree(bwt, n); // Deletes bwt!
1013 uint *text = new uint[n];
1014 for (i = 0; i < n; ++i) // Silly
1019 alphabet_mapper * am = new alphabet_mapper_none();
1020 static_bitsequence_builder * bmb = new static_bitsequence_builder_rrr02(16); // FIXME samplerate?
1022 //cout << "Building Huffman table..."; cout.flush();
1024 wt_coder * wtc = new wt_coder_huff(text,n,am);
1026 //cout << "done" << endl; cout.flush();
1027 //cout << "Building static_sequence..."; cout.flush();
1029 alphabetrank = new static_sequence_wvtree(text,n,wtc,bmb,am);
1033 /* for (i = 0; i < n; ++i)
1035 uchar c = alphabetrank->charAtPos(i);
1036 TextPosition j = C[c]+alphabetrank->rank(c, i)-1;
1037 printf("LF[%lu] = %lu\n", i, j);
1041 void CSA::maketables()
1043 ulong sampleLength = (n%samplerate==0) ? n/samplerate : n/samplerate+1;
1045 ulong *sampledpositions = new ulong[n/W+1];
1046 unsigned ceilLog2n = Tools::CeilLog2(n);
1047 positions = new BlockArray(sampleLength, ceilLog2n);
1048 BlockArray* tmpSuffix = new BlockArray(sampleLength, ceilLog2n);
1050 // Mapping from end-markers to doc ID's:
1051 endmarkerDocId = new BlockArray(numberOfTexts, Tools::CeilLog2(numberOfTexts));
1054 for (i=0;i<n/W+1;i++)
1055 sampledpositions[i]=0lu;
1057 ulong x,p=bwtEndPos;
1058 ulong sampleCount = 0;
1059 // Keeping track of text position of end-markers seen
1060 ulong posOfSuccEndmarker = n;
1061 DocId textId = numberOfTexts;
1066 for (i=n-1;i<ulongmax;i--) { // TODO bad solution with ulongmax?
1067 // i substitutes SA->GetPos(i)
1070 if (x % samplerate == 0 && posOfSuccEndmarker - x > samplerate) {
1071 Tools::SetField(sampledpositions,1,p,1);
1072 (*positions)[sampleCount] = p;
1073 (*tmpSuffix)[sampleCount] = x; // FIXME remove
1077 uchar c = alphabetrank->access(p);
1082 // Record the order of end-markers in BWT:
1083 ulong endmarkerRank = alphabetrank->rank(0, p) - 1;
1084 (*endmarkerDocId)[endmarkerRank] = textId;
1086 // Store text length and text start position:
1087 if (textId < (DocId)numberOfTexts - 1)
1089 (*textLength)[textId + 1] = posOfSuccEndmarker - x;
1090 (*textStartPos)[textId + 1] = x; // x is the position of end-marker.
1091 posOfSuccEndmarker = x;
1094 // LF-mapping from '\0' does not work with this (pseudo) BWT (see details from Wolfgang's thesis).
1095 p = textId; // Correct LF-mapping to the last char of the previous text.
1098 p = C[c]+alphabetrank->rank(c, p)-1;
1100 assert(textId == 0);
1103 for (map<ulong, pair<DocId, ulong> >::iterator it = endmarkers.begin(); it != endmarkers.end(); ++it, ++i)
1105 int docc = (*endmarkerDocId)[i];
1106 ulong poss = (*endmarkerPos)[i];
1107 printf("endm[%u] = %lu (text pos: %lu) (recorded: %d, %lu)\n", (it->second).first, it->first, (it->second).second, docc, poss);
1110 for (i = 0; i < numberOfTexts; ++ i)
1112 //std::cout << "textlength = " << dynTextLength[i].first << " vs " << (*textLength)[i] << ", textStartPos = " << dynTextLength[i].second << " vs " << (*textStartPos)[i] << std::endl;
1113 assert(dynTextLength[i].first == (*textLength)[i]);
1114 assert(dynTextLength[i].second == (*textStartPos)[i]);
1117 sampled = new BSGAP(sampledpositions,n,true);
1118 sampleLength = sampled->rank(n-1);
1119 assert(sampleCount == sampleLength);
1120 // std::cout << ";sampleLength;" << sampleLength << std::endl;
1121 // Suffixes == offset from text start position
1122 suffixes = new BlockArray(sampleLength, Tools::CeilLog2(maxTextLength));
1123 suffixDocId = new BlockArray(sampleLength, Tools::CeilLog2(numberOfTexts));
1126 for(i=0; i<sampleLength; i++) {
1127 assert((*positions)[i] < n);
1128 j = sampled->rank((*positions)[i]);
1129 if (j==0) j=sampleLength;
1130 TextPosition textPos = (*tmpSuffix)[i]; //(i*samplerate==n)?0:i*samplerate;
1131 (*suffixDocId)[j-1] = DocIdAtTextPos(textPos); // (*suffixes)[j-1]);
1133 assert((unsigned)DocIdAtTextPos(textPos) < numberOfTexts);
1134 assert((*suffixDocId)[j-1] < numberOfTexts);
1135 // calculate offset from text start:
1136 (*suffixes)[j-1] = textPos - (*textStartPos)[(*suffixDocId)[j-1]];
1138 // FIXME Temp, remove
1145 delete textStartPos;
1151 * Finds document identifier for given text position
1153 * Starting text position of the document is stored into second parameter.
1154 * Binary searching on text starting positions.
1156 TextCollection::DocId CSA::DocIdAtTextPos(TextPosition i) const
1161 DocId b = numberOfTexts - 1;
1164 DocId c = a + (b - a)/2;
1165 if ((*textStartPos)[c] > i)
1167 else if ((*textStartPos)[c+1] > i)
1173 assert(a < (DocId)numberOfTexts);
1174 assert(i >= (*textStartPos)[a]);
1175 assert(i < (a == (DocId)numberOfTexts - 1 ? n : (*textStartPos)[a+1]));
1179 CSA::TCodeEntry * CSA::node::makecodetable(uchar *text, TextPosition n)
1181 TCodeEntry *result = new TCodeEntry[ 256 ];
1183 count_chars( text, n, result );
1184 std::priority_queue< node, std::vector< node >, std::greater<node> > q;
1186 // First I push all the leaf nodes into the queue
1188 for ( unsigned int i = 0 ; i < 256 ; i++ )
1189 if ( result[ i ].count )
1190 q.push(node( i, result[ i ].count ) );
1192 // This loop removes the two smallest nodes from the
1193 // queue. It creates a new internal node that has
1194 // those two nodes as children. The new internal node
1195 // is then inserted into the priority queue. When there
1196 // is only one node in the priority queue, the tree
1200 while ( q.size() > 1 ) {
1201 node *child0 = new node( q.top() );
1203 node *child1 = new node( q.top() );
1205 q.push( node( child0, child1 ) );
1208 // Now I compute and return the codetable
1210 q.top().maketable(0u,0u, result);
1216 void CSA::node::maketable(unsigned code, unsigned bits, TCodeEntry *codetable) const
1220 child0->maketable( SetBit(code,bits,0), bits+1, codetable );
1221 child1->maketable( SetBit(code,bits,1), bits+1, codetable );
1227 codetable[value].code = code;
1228 codetable[value].bits = bits;
1232 void CSA::node::count_chars(uchar *text, TextPosition n, TCodeEntry *counts )
1235 for (i = 0 ; i < 256 ; i++ )
1236 counts[ i ].count = 0;
1238 counts[(int)text[i]].count++;
1241 unsigned CSA::node::SetBit(unsigned x, unsigned pos, unsigned bit) {
1242 return x | (bit << pos);