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 ////////////////////////////////////////////////////////////////////////////
130 * Constructor inits an empty dynamic FM-index.
131 * Samplerate defaults to TEXTCOLLECTION_DEFAULT_SAMPLERATE.
133 CSA::CSA(unsigned samplerate)
134 : n(0), samplerate(0), alphabetrank(0), sampled(0), suffixes(0), suffixDocId(0), positions(0),
135 codetable(0), dynFMI(0), numberOfTexts(0), numberOfAllTexts(0), maxTextLength(0), endmarkerDocId(0),
136 textLength(0), textStartPos(0), emptyTextRank(0)
138 this->samplerate = samplerate;
140 // FIXME TODO : DynFMI needs distribution of characters before hand
141 // This will create fully balanced wavelet tree for all chars [0, 255].
143 for (unsigned i = 0; i < 255; ++i)
146 dynFMI = new DynFMI(temp, 1, 255, false);
148 /* Debug code: take char distribution from data.txt.
149 uchar *temp = Tools::GetFileContents("data.txt", 0);
150 dynFMI = new DynFMI(temp,1790000, strlen((char *)temp), false);
157 * Given text must include end-marker.
158 * Text identifiers are numbered starting from 0.
160 void CSA::InsertText(uchar const * text)
165 TextPosition m = std::strlen((char *)text) + 1;
166 if (m > maxTextLength)
167 maxTextLength = m; // Store length of the longest text seen so far.
172 this->numberOfTexts ++;
173 this->numberOfAllTexts ++;
174 dynFMI->addText(text, m);
178 emptyTextId.insert(numberOfAllTexts); // FIXME Using too much space here
179 this->numberOfAllTexts ++; // Replace with dynamic bitvector
183 void CSA::MakeStatic()
187 throw std::runtime_error("CSA::MakeStatic(): Data structure is already static (dynFMI == 0).");
189 // Bitvector of empty texts
191 //std::cout << std::endl << "texts: " << numberOfTexts << ", all texts " << numberOfAllTexts << ", size : " << emptyTextId.size() <<std::endl;
192 ulong *tempB = new ulong[numberOfAllTexts/W + 1];
193 for (ulong i = 0; i < numberOfAllTexts/W + 1; ++i)
195 for (std::set<unsigned>::const_iterator it = emptyTextId.begin(); it != emptyTextId.end(); ++it)
196 Tools::SetField(tempB, 1, (*it), 1);
198 emptyTextRank = new BSGAP(tempB, numberOfAllTexts, true);
201 uchar *bwt = dynFMI->getBWT();
202 /*printf("123456789012345678901234567890123456789\n");
203 for (TextPosition i = 0; i < n; i ++)
205 printf("%d", (int)bwt[i]);
207 printf("%c", bwt[i]);
211 /* for (TextPosition i = 1; i <= n; i ++)
213 printf("LF[%lu, %c] = %lu\n", i, (*dynFMI)[i], dynFMI->LFmapping(i));
217 assert(numberOfTexts == dynFMI->getCollectionSize());
222 makewavelet(bwt); // Deletes bwt!
225 // Calculate BWT end-marker position (of last inserted text)
226 // and the length of the first text (counter l):
230 uchar c = alphabetrank->access(i);
233 i = C[c]+alphabetrank->rank(c, i)-1;
235 c = alphabetrank->access(i);
238 assert(bwtEndPos < n);
239 //printf("bwtEndPos = %lu\n", bwtEndPos);
241 // Build up arrays for text length and starting positions
242 // FIXME Remove, temp data
243 textLength = new BlockArray(numberOfTexts, Tools::CeilLog2(maxTextLength));
244 textStartPos = new BlockArray(numberOfTexts, Tools::CeilLog2(this->n));
245 (*textLength)[0] = l;
246 (*textStartPos)[0] = 0; // Rest of the values are updated in CSA::maketables().
248 // Make sampling tables
252 bool CSA::EmptyText(DocId k) const
254 assert(k < (DocId)numberOfTexts);
255 if (emptyTextRank->IsBitSet(k))
260 uchar* CSA::GetText(DocId k) const
262 assert(k < (DocId)numberOfTexts);
265 if (emptyTextRank->IsBitSet(k, &textRank))
267 uchar* result = new uchar[1];
271 // Map to non-empty text
272 k -= textRank; //emptyTextRank->rank(k);
277 // Reserve average string length to avoid reallocs
278 result.reserve(n/numberOfTexts);
280 uchar c = alphabetrank->access(i);
284 i = C[c]+alphabetrank->rank(c,i)-1;
286 c = alphabetrank->access(i); // "next" char.
289 // Convert to uchar (FIXME return string?)
291 uchar* res = new uchar[i+1];
293 for (ulong j = 0; j < i; ++j)
294 res[i-j-1] = result[j];
299 uchar* CSA::GetText(DocId k, TextPosition i, TextPosition j) const
301 assert(k < (DocId)numberOfTexts);
302 assert(j < (*textLength)[k]);
306 if (emptyTextRank->IsBitSet(k, &textRank))
308 uchar* result = new uchar[1];
313 // Map to non-empty text
314 k -= textRank; // emptyTextRank->rank(k);
316 // Start position of k'th text
317 ulong start = (*textStartPos)[k];
319 return Substring(i + start, j-i+1);
322 /******************************************************************
323 * Existential queries
325 bool CSA::IsPrefix(uchar const * pattern) const
327 TextPosition m = strlen((char *)pattern);
331 TextPosition sp = 0, ep = 0;
332 Search(pattern, m, &sp, &ep);
334 // Check for end-marker(s) in result interval
335 if (CountEndmarkers(sp, ep))
340 bool CSA::IsSuffix(uchar const *pattern) const
342 // Here counting is as fast as IsSuffix():
343 if (CountSuffix(pattern) > 0)
348 bool CSA::IsEqual(uchar const *pattern) const
350 TextPosition m = std::strlen((char *)pattern);
353 if (numberOfAllTexts - numberOfTexts > 0u)
354 return true; // Empty texts exists
355 return false; // No empty texts exists
358 TextPosition sp = 0, ep = 0;
359 // Match including end-marker
360 Search(pattern, m+1, &sp, &ep);
362 // Check for end-marker(s) in result interval
363 if (CountEndmarkers(sp, ep))
368 bool CSA::IsContains(uchar const * pattern) const
370 TextPosition m = strlen((char *)pattern);
374 TextPosition sp = 0, ep = 0;
375 // Just check if pattern exists somewhere
376 ulong count = Search(pattern, m, &sp, &ep);
383 bool CSA::IsLessThan(uchar const*) const
390 /******************************************************************
393 ulong CSA::Count(uchar const * pattern) const
395 TextPosition m = strlen((char *)pattern);
399 TextPosition sp = 0, ep = 0;
400 unsigned count = (unsigned) Search(pattern, m, &sp, &ep);
404 unsigned CSA::CountPrefix(uchar const * pattern) const
406 TextPosition m = strlen((char *)pattern);
408 return numberOfAllTexts;
410 TextPosition sp = 0, ep = 0;
411 Search(pattern, m, &sp, &ep);
413 // Count end-markers in result interval
414 return CountEndmarkers(sp, ep);
417 unsigned CSA::CountSuffix(uchar const * pattern) const
419 TextPosition m = strlen((char *)pattern);
421 return numberOfAllTexts;
423 TextPosition sp = 0, ep = 0;
424 // Search with end-marker
425 unsigned count = (unsigned) Search(pattern, m+1, &sp, &ep);
430 unsigned CSA::CountEqual(uchar const *pattern) const
432 TextPosition m = strlen((char const *)pattern);
434 return numberOfAllTexts - numberOfTexts; // Empty texts.
436 TextPosition sp = 0, ep = 0;
437 // Match including end-marker
438 Search(pattern, m+1, &sp, &ep);
440 // Count end-markers in result interval
441 return CountEndmarkers(sp, ep);
444 unsigned CSA::CountContains(uchar const * pattern) const
446 TextPosition m = strlen((char const *)pattern);
448 return numberOfAllTexts; // Total number of texts.
450 // Here counting is as slow as fetching the result set
451 // because we would have to filter out occ's that fall within same document.
452 TextCollection::document_result result = Contains(pattern);
453 return result.size();
456 unsigned CSA::CountLessThan(uchar const * pattern) const
464 * Document reporting queries
466 TextCollection::document_result CSA::Prefix(uchar const * pattern) const
468 TextPosition m = strlen((char *)pattern);
470 return TextCollection::document_result(); // FIXME Should return all 1...k
472 TextPosition sp = 0, ep = 0;
473 Search(pattern, m, &sp, &ep);
475 TextCollection::document_result result;
477 // Report end-markers in result interval
478 unsigned resultSize = CountEndmarkers(sp, ep);
482 result.reserve(resultSize); // Try to avoid reallocation.
484 // Iterate through end-markers in [sp,ep]:
487 i = alphabetrank->rank(0, sp - 1);
490 // End-marker we found belongs to the "preceeding" doc in the collection
491 DocId docId = ((*endmarkerDocId)[i] + 1) % numberOfTexts;
493 docId = emptyTextRank->select0(docId+1);
494 result.push_back(docId);
503 TextCollection::document_result CSA::Suffix(uchar const * pattern) const
505 TextPosition m = strlen((char *)pattern);
507 return TextCollection::document_result(); // FIXME Should return all 1...k
509 TextPosition sp = 0, ep = 0;
510 // Search with end-marker
511 Search(pattern, m+1, &sp, &ep);
513 TextCollection::document_result result;
514 result.reserve(ep-sp+1); // Try to avoid reallocation.
516 ulong sampled_rank_i = 0;
517 // Check each occurrence
518 for (; sp <= ep; ++sp)
522 uchar c = alphabetrank->access(i);
523 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
525 i = C[c]+alphabetrank->rank(c,i)-1;
526 c = alphabetrank->access(i);
528 // Assert: c == '\0' OR sampled->IsBitSet(i)
532 // Rank among the end-markers in BWT
533 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
535 // End-marker that we found belongs to the "preceeding" doc in collection:
536 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
538 docId = emptyTextRank->select0(docId+1);
539 result.push_back(docId);
541 else // Sampled position
543 DocId docId = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
545 docId = emptyTextRank->select0(docId+1);
546 result.push_back(docId);
553 TextCollection::document_result CSA::Equal(uchar const *pattern) const
555 TextPosition m = strlen((char const *)pattern);
557 return TextCollection::document_result(); // FIXME Should return all empty texts
559 TextPosition sp = 0, ep = 0;
560 // Match including end-marker
561 Search(pattern, m+1, &sp, &ep);
563 TextCollection::document_result result;
565 // Report end-markers in result interval
566 unsigned resultSize = CountEndmarkers(sp, ep);
570 result.reserve(resultSize); // Try to avoid reallocation.
574 i = alphabetrank->rank(0, sp - 1);
577 // End-marker we found belongs to the "previous" doc in the collection
578 DocId docId = ((*endmarkerDocId)[i] + 1) % numberOfTexts;
580 docId = emptyTextRank->select0(docId+1);
581 result.push_back(docId);
591 TextCollection::document_result CSA::Contains(uchar const * pattern) const
593 TextPosition m = strlen((char *)pattern);
595 return TextCollection::document_result();
597 TextPosition sp = 0, ep = 0;
598 // Search all occurrences
599 Search(pattern, m, &sp, &ep);
601 // We want unique document indentifiers, using std::set to collect them
602 std::set<DocId> resultSet;
604 ulong sampled_rank_i = 0;
605 // Check each occurrence
606 for (; sp <= ep; ++sp)
609 uchar c = alphabetrank->access(i);
610 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
612 i = C[c]+alphabetrank->rank(c,i)-1; // LF-mapping
613 c = alphabetrank->access(i);
617 // Rank among the end-markers in BWT
618 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
620 // End-marker that we found belongs to the "preceeding" doc in collection:
621 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
622 resultSet.insert(docId);
626 DocId di = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
627 assert((unsigned)di < numberOfTexts);
628 resultSet.insert(di);
632 // Convert std::set to std::vector
633 TextCollection::document_result result(resultSet.begin(), resultSet.end());
635 for (document_result::iterator it = result.begin(); it != result.end(); ++it)
636 *it = emptyTextRank->select0(*it+1);
640 TextCollection::document_result CSA::LessThan(uchar const * pattern) const
644 return document_result();
648 * Full result set queries
650 TextCollection::full_result CSA::FullContains(uchar const * pattern) const
652 TextPosition m = strlen((char *)pattern);
654 return full_result(); // FIXME Throw exception?
656 TextPosition sp = 0, ep = 0;
657 // Search all occurrences
658 Search(pattern, m, &sp, &ep);
661 result.reserve(ep-sp+1); // Try to avoid reallocation.
663 ulong sampled_rank_i = 0;
664 // Report each occurrence
665 for (; sp <= ep; ++sp)
668 TextPosition dist = 0;
669 uchar c = alphabetrank->access(i);
670 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
672 i = C[c]+alphabetrank->rank(c,i)-1;
673 c = alphabetrank->access(i);
678 // Rank among the end-markers in BWT
679 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
681 // End-marker that we found belongs to the "preceeding" doc in collection:
682 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
684 docId = emptyTextRank->select0(docId+1);
685 result.push_back(make_pair(docId, dist));
689 TextPosition textPos = (*suffixes)[sampled_rank_i-1]+dist; //sampled->rank(i)-1] + dist;
690 DocId docId = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
691 // textPos = textPos - (*textStartPos)[docId]; // Offset inside the text
694 docId = emptyTextRank->select0(docId+1);
695 result.push_back(make_pair(docId, textPos));
704 * Save index to a file handle
706 * Throws a std::runtime_error exception on i/o error.
707 * First byte that is saved represents the version number of the save file.
708 * In version 2 files, the data fields are:
713 TextPosition bwtEndPos;
714 static_sequence * alphabetrank;
716 BlockArray *suffixes;
717 BlockArray *suffixDocId;
718 unsigned numberOfTexts;
719 unsigned numberOfAllTexts;
721 BlockArray *endmarkerDocId;
722 BSGAP *emptyTextRank;
724 void CSA::Save(FILE *file) const
726 // Saving version info:
727 if (std::fwrite(&versionFlag, 1, 1, file) != 1)
728 throw std::runtime_error("CSA::Save(): file write error (version flag).");
730 if (std::fwrite(&(this->n), sizeof(TextPosition), 1, file) != 1)
731 throw std::runtime_error("CSA::Save(): file write error (n).");
732 if (std::fwrite(&(this->samplerate), sizeof(unsigned), 1, file) != 1)
733 throw std::runtime_error("CSA::Save(): file write error (samplerate).");
735 for(ulong i = 0; i < 256; ++i)
736 if (std::fwrite(this->C + i, sizeof(unsigned), 1, file) != 1)
737 throw std::runtime_error("CSA::Save(): file write error (C table).");
739 if (std::fwrite(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
740 throw std::runtime_error("CSA::Save(): file write error (bwt end position).");
742 alphabetrank->save(file);
744 suffixes->Save(file);
745 suffixDocId->Save(file);
747 if (std::fwrite(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
748 throw std::runtime_error("CSA::Save(): file write error (numberOfTexts).");
749 if (std::fwrite(&(this->numberOfAllTexts), sizeof(unsigned), 1, file) != 1)
750 throw std::runtime_error("CSA::Save(): file write error (numberOfAllTexts).");
751 if (std::fwrite(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
752 throw std::runtime_error("CSA::Save(): file write error (maxTextLength).");
754 endmarkerDocId->Save(file);
755 emptyTextRank->Save(file);
761 * Load index from a file handle
763 * Throws a std::runtime_error exception on i/o error.
764 * For more info, see CSA::Save().
766 void CSA::Load(FILE *file, unsigned samplerate)
769 delete dynFMI; dynFMI = 0;
770 delete alphabetrank; alphabetrank = 0;
771 delete sampled; sampled = 0;
772 delete suffixes; suffixes = 0;
773 delete suffixDocId; suffixDocId = 0;
774 delete positions; positions = 0;
775 delete [] codetable; codetable = 0;
777 delete endmarkerDocId; endmarkerDocId = 0;
778 delete emptyTextRank; emptyTextRank = 0;
779 // FIXME Remove following:
780 delete textLength; textLength = 0;
781 delete textStartPos; textStartPos = 0;
783 this->maxTextLength = 0;
784 this->numberOfTexts = 0;
785 this->numberOfAllTexts = 0;
786 this->samplerate = samplerate;
790 if (std::fread(&verFlag, 1, 1, file) != 1)
791 throw std::runtime_error("CSA::Load(): file read error (version flag).");
792 if (verFlag != CSA::versionFlag)
793 throw std::runtime_error("CSA::Load(): invalid save file version.");
795 if (std::fread(&(this->n), sizeof(TextPosition), 1, file) != 1)
796 throw std::runtime_error("CSA::Load(): file read error (n).");
797 if (std::fread(&samplerate, sizeof(unsigned), 1, file) != 1)
798 throw std::runtime_error("CSA::Load(): file read error (samplerate).");
799 // FIXME samplerate can not be changed during load.
800 // if (this->samplerate == 0)
801 // this->samplerate = samplerate;
803 for(ulong i = 0; i < 256; ++i)
804 if (std::fread(this->C + i, sizeof(unsigned), 1, file) != 1)
805 throw std::runtime_error("CSA::Load(): file read error (C table).");
807 if (std::fread(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
808 throw std::runtime_error("CSA::Load(): file read error (bwt end position).");
810 alphabetrank = static_sequence::load(file);
811 sampled = new BSGAP(file);
812 suffixes = new BlockArray(file);
813 suffixDocId = new BlockArray(file);
815 if (std::fread(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
816 throw std::runtime_error("CSA::Load(): file read error (numberOfTexts).");
817 if (std::fread(&(this->numberOfAllTexts), sizeof(unsigned), 1, file) != 1)
818 throw std::runtime_error("CSA::Load(): file read error (numberOfAllTexts).");
819 if (std::fread(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
820 throw std::runtime_error("CSA::Load(): file read error (maxTextLength).");
822 endmarkerDocId = new BlockArray(file);
823 emptyTextRank = new BSGAP(file);
825 // FIXME Construct data structures with new samplerate
826 //maketables(); // FIXME: this will redo text length tables
832 * Rest of the functions follow...
837 uchar * CSA::Substring(TextPosition i, TextPosition l) const
839 uchar *result = new uchar[l + 1];
847 TextPosition k = i + l - 1;
848 // Check for end of the string
855 TextPosition skip = samplerate - k % samplerate - 1;
857 if (k / samplerate + 1 >= n / samplerate)
864 j = (*positions)[k/samplerate+1];
865 //cout << samplerate << ' ' << j << '\n';
868 for (dist = 0; dist < skip + l; dist++)
870 int c = alphabetrank->access(j); //charAtPos(j, &alphabetrank_tmp);
873 // Rank among the end-markers in BWT
874 unsigned endmarkerRank = alphabetrank->rank(0, j) - 1;
875 j = (*endmarkerDocId)[endmarkerRank]; // LF-mapping for end-marker
878 j = C[c]+alphabetrank->rank(c,j)-1; // LF-mapping
880 result[l + skip - dist - 1] = c;
886 /*TextPosition CSA::inverse(TextPosition i)
888 TextPosition skip = samplerate - i % samplerate;
890 if (i / samplerate + 1 >= n / samplerate)
897 j = (*positions)[i/samplerate+1];
898 //cout << samplerate << ' ' << j << '\n';
903 int c = alphabetrank->charAtPos(j);
904 j = C[c]+alphabetrank->rank(c,j)-1; // LF-mapping
910 ulong CSA::Search(uchar const * pattern, TextPosition m, TextPosition *spResult, TextPosition *epResult) const
912 // use the FM-search replacing function Occ(c,1,i) with alphabetrank->rank(c,i)
913 int c = (int)pattern[m-1];
915 TextPosition sp = C[c];
916 TextPosition ep = C[c+1]-1;
917 while (sp<=ep && i>=1)
919 // printf("i = %lu, c = %c, sp = %lu, ep = %lu\n", i, pattern[i], sp, ep);
920 c = (int)pattern[--i];
921 sp = C[c]+alphabetrank->rank(c,sp-1);
922 ep = C[c]+alphabetrank->rank(c,ep)-1;
932 /*TextPosition CSA::LF(uchar c, TextPosition &sp, TextPosition &ep)
934 sp = C[(int)c]+alphabetrank->rank(c,sp-1);
935 ep = C[(int)c]+alphabetrank->rank(c,ep)-1;
943 CSA::TextPosition CSA::Lookup(TextPosition i) const
946 while (!sampled->IsBitSet(i))
949 int c = alphabetrank->access(i);
952 // End-markers are sampled
953 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
954 DocId docId = (*endmarkerDocId)[endmarkerRank];
955 return (*textStartPos)[docId] + dist;
957 i = C[c]+alphabetrank->rank(c,i)-1;
961 return (*suffixes)[sampled->rank(i)-1]+dist;
973 delete endmarkerDocId;
976 delete emptyTextRank;
979 void CSA::makewavelet(uchar *bwt)
988 if (C[i]>0) {min = i; break;}
989 for (i=255;i>=min;--i)
990 if (C[i]>0) {max = i; break;}
993 /*for(i = 0; i < 256; i++)
994 if (C[i]>0) printf("C[%lu] = %lu\n", i, C[i]);
997 ulong prev=C[0], temp;
999 for (i=1;i<256;i++) {
1004 // this->codetable = node::makecodetable(bwt,n);
1005 // alphabetrank = new THuffAlphabetRank(bwt,n, this->codetable,0);
1007 //alphabetrank = new RLWaveletTree(bwt, n); // Deletes bwt!
1009 uint *text = new uint[n];
1010 for (i = 0; i < n; ++i) // Silly
1015 alphabet_mapper * am = new alphabet_mapper_none();
1016 static_bitsequence_builder * bmb = new static_bitsequence_builder_brw32(16); // FIXME samplerate?
1018 //cout << "Building Huffman table..."; cout.flush();
1020 wt_coder * wtc = new wt_coder_huff(text,n,am);
1022 //cout << "done" << endl; cout.flush();
1023 //cout << "Building static_sequence..."; cout.flush();
1025 alphabetrank = new static_sequence_wvtree(text,n,wtc,bmb,am);
1029 /* for (i = 0; i < n; ++i)
1031 uchar c = alphabetrank->charAtPos(i);
1032 TextPosition j = C[c]+alphabetrank->rank(c, i)-1;
1033 printf("LF[%lu] = %lu\n", i, j);
1037 void CSA::maketables()
1039 ulong sampleLength = (n%samplerate==0) ? n/samplerate : n/samplerate+1;
1041 ulong *sampledpositions = new ulong[n/W+1];
1042 unsigned ceilLog2n = Tools::CeilLog2(n);
1043 positions = new BlockArray(sampleLength, ceilLog2n);
1044 BlockArray* tmpSuffix = new BlockArray(sampleLength, ceilLog2n);
1046 // Mapping from end-markers to doc ID's:
1047 endmarkerDocId = new BlockArray(numberOfTexts, Tools::CeilLog2(numberOfTexts));
1050 for (i=0;i<n/W+1;i++)
1051 sampledpositions[i]=0lu;
1053 ulong x,p=bwtEndPos;
1054 ulong sampleCount = 0;
1055 // Keeping track of text position of end-markers seen
1056 ulong posOfSuccEndmarker = n;
1057 DocId textId = numberOfTexts;
1062 for (i=n-1;i<ulongmax;i--) { // TODO bad solution with ulongmax?
1063 // i substitutes SA->GetPos(i)
1066 if (x % samplerate == 0 && posOfSuccEndmarker - x > samplerate) {
1067 Tools::SetField(sampledpositions,1,p,1);
1068 (*positions)[sampleCount] = p;
1069 (*tmpSuffix)[sampleCount] = x; // FIXME remove
1073 uchar c = alphabetrank->access(p);
1078 // Record the order of end-markers in BWT:
1079 ulong endmarkerRank = alphabetrank->rank(0, p) - 1;
1080 (*endmarkerDocId)[endmarkerRank] = textId;
1082 // Store text length and text start position:
1083 if (textId < (DocId)numberOfTexts - 1)
1085 (*textLength)[textId + 1] = posOfSuccEndmarker - x;
1086 (*textStartPos)[textId + 1] = x; // x is the position of end-marker.
1087 posOfSuccEndmarker = x;
1090 // LF-mapping from '\0' does not work with this (pseudo) BWT (see details from Wolfgang's thesis).
1091 p = textId; // Correct LF-mapping to the last char of the previous text.
1094 p = C[c]+alphabetrank->rank(c, p)-1;
1096 assert(textId == 0);
1099 for (map<ulong, pair<DocId, ulong> >::iterator it = endmarkers.begin(); it != endmarkers.end(); ++it, ++i)
1101 int docc = (*endmarkerDocId)[i];
1102 ulong poss = (*endmarkerPos)[i];
1103 printf("endm[%u] = %lu (text pos: %lu) (recorded: %d, %lu)\n", (it->second).first, it->first, (it->second).second, docc, poss);
1106 for (i = 0; i < numberOfTexts; ++ i)
1108 //std::cout << "textlength = " << dynTextLength[i].first << " vs " << (*textLength)[i] << ", textStartPos = " << dynTextLength[i].second << " vs " << (*textStartPos)[i] << std::endl;
1109 assert(dynTextLength[i].first == (*textLength)[i]);
1110 assert(dynTextLength[i].second == (*textStartPos)[i]);
1113 sampled = new BSGAP(sampledpositions,n,true);
1114 sampleLength = sampled->rank(n-1);
1115 assert(sampleCount == sampleLength);
1116 // std::cout << ";sampleLength;" << sampleLength << std::endl;
1117 // Suffixes == offset from text start position
1118 suffixes = new BlockArray(sampleLength, Tools::CeilLog2(maxTextLength));
1119 suffixDocId = new BlockArray(sampleLength, Tools::CeilLog2(numberOfTexts));
1122 for(i=0; i<sampleLength; i++) {
1123 assert((*positions)[i] < n);
1124 j = sampled->rank((*positions)[i]);
1125 if (j==0) j=sampleLength;
1126 TextPosition textPos = (*tmpSuffix)[i]; //(i*samplerate==n)?0:i*samplerate;
1127 (*suffixDocId)[j-1] = DocIdAtTextPos(textPos); // (*suffixes)[j-1]);
1129 assert((unsigned)DocIdAtTextPos(textPos) < numberOfTexts);
1130 assert((*suffixDocId)[j-1] < numberOfTexts);
1131 // calculate offset from text start:
1132 (*suffixes)[j-1] = textPos - (*textStartPos)[(*suffixDocId)[j-1]];
1134 // FIXME Temp, remove
1141 delete textStartPos;
1147 * Finds document identifier for given text position
1149 * Starting text position of the document is stored into second parameter.
1150 * Binary searching on text starting positions.
1152 TextCollection::DocId CSA::DocIdAtTextPos(TextPosition i) const
1157 DocId b = numberOfTexts - 1;
1160 DocId c = a + (b - a)/2;
1161 if ((*textStartPos)[c] > i)
1163 else if ((*textStartPos)[c+1] > i)
1169 assert(a < (DocId)numberOfTexts);
1170 assert(i >= (*textStartPos)[a]);
1171 assert(i < (a == (DocId)numberOfTexts - 1 ? n : (*textStartPos)[a+1]));
1175 CSA::TCodeEntry * CSA::node::makecodetable(uchar *text, TextPosition n)
1177 TCodeEntry *result = new TCodeEntry[ 256 ];
1179 count_chars( text, n, result );
1180 std::priority_queue< node, std::vector< node >, std::greater<node> > q;
1182 // First I push all the leaf nodes into the queue
1184 for ( unsigned int i = 0 ; i < 256 ; i++ )
1185 if ( result[ i ].count )
1186 q.push(node( i, result[ i ].count ) );
1188 // This loop removes the two smallest nodes from the
1189 // queue. It creates a new internal node that has
1190 // those two nodes as children. The new internal node
1191 // is then inserted into the priority queue. When there
1192 // is only one node in the priority queue, the tree
1196 while ( q.size() > 1 ) {
1197 node *child0 = new node( q.top() );
1199 node *child1 = new node( q.top() );
1201 q.push( node( child0, child1 ) );
1204 // Now I compute and return the codetable
1206 q.top().maketable(0u,0u, result);
1212 void CSA::node::maketable(unsigned code, unsigned bits, TCodeEntry *codetable) const
1216 child0->maketable( SetBit(code,bits,0), bits+1, codetable );
1217 child1->maketable( SetBit(code,bits,1), bits+1, codetable );
1223 codetable[value].code = code;
1224 codetable[value].bits = bits;
1228 void CSA::node::count_chars(uchar *text, TextPosition n, TCodeEntry *counts )
1231 for (i = 0 ; i < 256 ; i++ )
1232 counts[ i ].count = 0;
1234 counts[(int)text[i]].count++;
1237 unsigned CSA::node::SetBit(unsigned x, unsigned pos, unsigned bit) {
1238 return x | (bit << pos);