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"
23 // Conflicts with std::min and std::max
26 #include "dcover/bwt.hpp"
28 #include "HeapProfiler.h" // FIXME remove
37 #include <cstring> // For strlen()
46 // Save file version info
47 const uchar CSA::versionFlag = 2;
49 ////////////////////////////////////////////////////////////////////////////
50 // Class CSA::THuffAlphabetRank
52 CSA::THuffAlphabetRank::THuffAlphabetRank(uchar *s, TextPosition n, TCodeEntry *codetable, unsigned level) {
58 this->codetable = codetable;
60 bool *B = new bool[n];
63 for (i=0; i< n; i++) {
64 printf("%c:", (char)((int)s[i]-128));
65 for (r=0;r<codetable[(int)s[i]].bits;r++)
66 if (codetable[(int)s[i]].code & (1u <<r))
72 if (level > 100) return;*/
74 if (codetable[(int)s[i]].code & (1u << level)) {
79 if (sum==0 || sum==n) {
84 uchar *sfirst, *ssecond;
86 sfirst = new uchar[n-sum];
88 ssecond = new uchar[sum];
91 if (B[i]) ssecond[k++] = s[i];
92 else sfirst[j++] = s[i];
93 ulong *Binbits = new ulong[n/W+1];
95 Tools::SetField(Binbits,1,i,B[i]);
97 bitrank = new BitRank(Binbits,n,true);
99 left = new THuffAlphabetRank(sfirst,j,codetable,level+1);
103 right = new THuffAlphabetRank(ssecond,k,codetable,level+1);
109 bool CSA::THuffAlphabetRank::Test(uchar *s, ulong n) {
110 // testing that the code works correctly
118 if (C[(int)s[i]] != (int)rank((int)s[i],i)) {
120 printf("%d (%c): %d<>%d\n",i,(int)s[i]-128,C[(int)s[i]],(int)rank((int)s[i],i));
126 CSA::THuffAlphabetRank::~THuffAlphabetRank() {
127 if (left!=NULL) delete left;
128 if (right!=NULL) delete right;
134 ////////////////////////////////////////////////////////////////////////////
138 * Constructor inits an empty dynamic FM-index.
139 * Samplerate defaults to TEXTCOLLECTION_DEFAULT_SAMPLERATE.
141 CSA::CSA(unsigned samplerate)
142 : n(0), samplerate(0), alphabetrank(0), codetable(0), sampled(0), suffixes(0),
143 suffixDocId(0), numberOfTexts(0), numberOfAllTexts(0), maxTextLength(0), endmarkerDocId(0),
146 this->samplerate = samplerate;
149 // FIXME TODO : DynFMI needs distribution of characters before hand
150 // This will create fully balanced wavelet tree for all chars [0, 255].
152 for (unsigned i = 0; i < 255; ++i)
155 dynFMI = new DynFMI(temp, 1, 255, false);
157 /* Debug code: take char distribution from data.txt.
158 uchar *temp = Tools::GetFileContents("data.txt", 0);
159 dynFMI = new DynFMI(temp,1790000, strlen((char *)temp), false);
167 * Given text must include end-marker.
168 * Text identifiers are numbered starting from 0.
170 void CSA::InsertText(uchar const * text)
177 TextPosition m = std::strlen((char *)text) + 1;
178 if (m > maxTextLength)
179 maxTextLength = m; // Store length of the longest text seen so far.
184 this->numberOfTexts ++;
185 this->numberOfAllTexts ++;
187 dynFMI->addText(text, m);
190 texts.append((char *) text);
191 texts.append(1, '\0');
195 emptyTextId.insert(numberOfAllTexts); // FIXME Using too much space here
196 this->numberOfAllTexts ++;
200 void CSA::MakeStatic()
205 throw std::runtime_error("CSA::MakeStatic(): Data structure is already static (dynFMI == 0).");
208 if (texts.size() == 0) // Empty collection
211 texts.append(1, '\0');
214 // Bitvector of empty texts, FIXME Remove?
216 //std::cout << std::endl << "texts: " << numberOfTexts << ", all texts " << numberOfAllTexts << ", size : " << emptyTextId.size() <<std::endl;
217 ulong *tempB = new ulong[numberOfAllTexts/W + 1];
218 for (ulong i = 0; i < numberOfAllTexts/W + 1; ++i)
220 for (std::set<unsigned>::const_iterator it = emptyTextId.begin(); it != emptyTextId.end(); ++it)
221 Tools::SetField(tempB, 1, (*it), 1);
223 emptyTextRank = new BSGAP(tempB, numberOfAllTexts, true);
226 texts.reserve(0); // Release extra capacity
228 /* FILE *fp = fopen("texts.txt", "wb");
229 std::cout << "Wrote " << fwrite(texts.c_str(), 1, n, fp) << " bytes into texts.txt." << std::endl;
232 uchar *bwt = new uchar[n];
234 // More succinct solution via StringIterator, see below.
235 /* unsigned* maptexts = new unsigned[n+1];
236 // Map text chars to [0..255+numberOfTexts]
238 for (ulong i = 0; i < n; ++i)
240 maptexts[i] = ++count; // endmarkers \in [1..numberOfTexts]
242 uchar c = (uchar)texts[i];
243 maptexts[i] = (unsigned)c + numberOfTexts;
246 assert(count == numberOfTexts);
248 std::cout << "maptext: ";
249 for (ulong i = 0; i <= n; ++i)
250 std::cout << maptexts[i] << ", ";
251 std::cout << std::endl;*/
253 // Mark endmarker positions into bitvector
254 ulong * endmarkers = new ulong[n/W+1];
255 for (ulong i = 0; i < n/W+1; ++i)
257 for (ulong i = 0; i < n; ++i)
259 Tools::SetField(endmarkers, 1, i, 1);
260 BitRank* br = new BitRank(endmarkers, n, true);
261 assert(numberOfTexts == br->rank(n-1));
263 // Build iterators, FIXME clean up iterator construction.
264 StringIterator itBegin((uchar const *)texts.c_str(), (uchar const *)texts.c_str(), n, numberOfTexts, br);
265 StringIterator itEnd((uchar const *)texts.c_str() + n,(uchar const *)texts.c_str(), n, numberOfTexts, br);
267 bwtEndPos = (ulong)compute_bwt(itBegin, itEnd, //&maptexts[0], &maptexts[n],
268 &bwt[0], numberOfTexts);
270 bwt[--bwtEndPos] = '\0';
272 texts.reserve(0); // Release capacity
273 delete br; // bitvector of endmarkers
274 } // End of bw transform
275 // std::cerr << "Time after BWT: " << Tools::GetTime() << std::endl;
277 /* fp = fopen("bwt.txt", "wb");
278 std::cout << "Wrote " << fwrite(bwt, 1, n, fp) << " bytes into bwt.txt." << std::endl;
284 uchar *bwtTest = dynFMI->getBWT();
285 printf("123456789012345678901234567890123456789\n");
286 for (TextPosition i = 0; i < n && i < 100; i ++)
288 printf("%d", (int)bwt[i]);
290 printf("%c", bwt[i]);
292 for (TextPosition i = 0; i < n && i < 100; i ++)
294 printf("%d", (int)bwtTest[i]);
296 printf("%c", bwtTest[i]);
300 assert(numberOfTexts == dynFMI->getCollectionSize());
304 for (ulong i = 0; i < n; ++i)
305 if (bwt[i] != bwtTest[i])
307 std::cout << "i = " << i << ", bwt = " << (unsigned)bwt[i] << ", " << (unsigned)bwtTest[i] << std::endl;
312 #endif // CSA_TEST_BWT
314 makewavelet(bwt); // Deletes bwt!
317 // Make sampling tables
321 bool CSA::EmptyText(DocId k) const
323 assert(k < (DocId)numberOfTexts);
324 if (emptyTextRank->IsBitSet(k))
329 uchar* CSA::GetText(DocId k) const
331 assert(k < (DocId)numberOfTexts);
334 if (emptyTextRank->IsBitSet(k, &textRank))
336 uchar* result = new uchar[1];
340 // Map to non-empty text
341 k -= textRank; //emptyTextRank->rank(k);
346 // Reserve average string length to avoid reallocs
347 result.reserve(n/numberOfTexts);
349 uchar c = alphabetrank->access(i);
353 i = C[c]+alphabetrank->rank(c,i)-1;
355 c = alphabetrank->access(i); // "next" char.
358 // Convert to uchar (FIXME return string?)
360 uchar* res = new uchar[i+1];
362 for (ulong j = 0; j < i; ++j)
363 res[i-j-1] = result[j];
368 uchar* CSA::GetText(DocId k, TextPosition i, TextPosition j) const
370 assert(k < (DocId)numberOfTexts);
371 assert(j < (*textLength)[k]);
375 if (emptyTextRank->IsBitSet(k, &textRank))
377 uchar* result = new uchar[1];
382 // Map to non-empty text
383 k -= textRank; // emptyTextRank->rank(k);
385 // Start position of k'th text
386 ulong start = (*textStartPos)[k];
388 return Substring(i + start, j-i+1);
391 /******************************************************************
392 * Existential queries
394 bool CSA::IsPrefix(uchar const * pattern) const
396 TextPosition m = strlen((char *)pattern);
400 TextPosition sp = 0, ep = 0;
401 Search(pattern, m, &sp, &ep);
403 // Check for end-marker(s) in result interval
404 if (CountEndmarkers(sp, ep))
409 bool CSA::IsSuffix(uchar const *pattern) const
411 // Here counting is as fast as IsSuffix():
412 if (CountSuffix(pattern) > 0)
417 bool CSA::IsEqual(uchar const *pattern) const
419 TextPosition m = std::strlen((char *)pattern);
422 if (numberOfAllTexts - numberOfTexts > 0u)
423 return true; // Empty texts exists
424 return false; // No empty texts exists
427 TextPosition sp = 0, ep = 0;
428 // Match including end-marker
429 Search(pattern, m+1, &sp, &ep);
431 // Check for end-marker(s) in result interval
432 if (CountEndmarkers(sp, ep))
437 bool CSA::IsContains(uchar const * pattern) const
439 TextPosition m = strlen((char *)pattern);
443 TextPosition sp = 0, ep = 0;
444 // Just check if pattern exists somewhere
445 ulong count = Search(pattern, m, &sp, &ep);
452 bool CSA::IsLessThan(uchar const * pattern) const
454 if (CountLessThan(pattern) > 0)
459 /******************************************************************
462 ulong CSA::Count(uchar const * pattern) const
464 TextPosition m = strlen((char *)pattern);
468 TextPosition sp = 0, ep = 0;
469 unsigned count = (unsigned) Search(pattern, m, &sp, &ep);
473 unsigned CSA::CountPrefix(uchar const * pattern) const
475 TextPosition m = strlen((char *)pattern);
477 return numberOfAllTexts;
479 TextPosition sp = 0, ep = 0;
480 Search(pattern, m, &sp, &ep);
482 // Count end-markers in result interval
483 return CountEndmarkers(sp, ep);
486 unsigned CSA::CountSuffix(uchar const * pattern) const
488 TextPosition m = strlen((char *)pattern);
490 return numberOfAllTexts;
492 TextPosition sp = 0, ep = 0;
493 // Search with end-marker
494 unsigned count = (unsigned) Search(pattern, m+1, &sp, &ep);
499 unsigned CSA::CountEqual(uchar const *pattern) const
501 TextPosition m = strlen((char const *)pattern);
503 return numberOfAllTexts - numberOfTexts; // Empty texts.
505 TextPosition sp = 0, ep = 0;
506 // Match including end-marker
507 Search(pattern, m+1, &sp, &ep);
509 // Count end-markers in result interval
510 return CountEndmarkers(sp, ep);
513 unsigned CSA::CountContains(uchar const * pattern) const
515 TextPosition m = strlen((char const *)pattern);
517 return numberOfAllTexts; // Total number of texts.
519 // Here counting is as slow as fetching the result set
520 // because we would have to filter out occ's that fall within same document.
521 TextCollection::document_result result = Contains(pattern);
522 return result.size();
525 // Less than or equal
526 unsigned CSA::CountLessThan(uchar const * pattern) const
528 TextPosition m = strlen((char const *)pattern);
530 return numberOfAllTexts - numberOfTexts; // Empty texts.
532 TextPosition sp = 0, ep = 0;
533 SearchLessThan(pattern, m, &sp, &ep);
535 // Count end-markers in result interval
536 return CountEndmarkers(sp, ep);
540 * Document reporting queries
542 TextCollection::document_result CSA::Prefix(uchar const * pattern) const
544 TextPosition m = strlen((char *)pattern);
546 return TextCollection::document_result(); // FIXME Should return all 1...k
548 TextPosition sp = 0, ep = 0;
549 Search(pattern, m, &sp, &ep);
551 TextCollection::document_result result;
553 // Report end-markers in result interval
554 unsigned resultSize = CountEndmarkers(sp, ep);
558 result.reserve(resultSize); // Try to avoid reallocation.
560 // Iterate through end-markers in [sp,ep]:
563 i = alphabetrank->rank(0, sp - 1);
566 // End-marker we found belongs to the "preceeding" doc in the collection
567 DocId docId = ((*endmarkerDocId)[i] + 1) % numberOfTexts;
569 docId = emptyTextRank->select0(docId+1);
570 result.push_back(docId);
579 TextCollection::document_result CSA::Suffix(uchar const * pattern) const
581 TextPosition m = strlen((char *)pattern);
583 return TextCollection::document_result(); // FIXME Should return all 1...k
585 TextPosition sp = 0, ep = 0;
586 // Search with end-marker
587 Search(pattern, m+1, &sp, &ep);
589 TextCollection::document_result result;
590 result.reserve(ep-sp+1); // Try to avoid reallocation.
592 ulong sampled_rank_i = 0;
593 // Check each occurrence
594 for (; sp <= ep; ++sp)
598 uchar c = alphabetrank->access(i);
599 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
601 i = C[c]+alphabetrank->rank(c,i)-1;
602 c = alphabetrank->access(i);
604 // Assert: c == '\0' OR sampled->IsBitSet(i)
608 // Rank among the end-markers in BWT
609 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
611 // End-marker that we found belongs to the "preceeding" doc in collection:
612 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
614 docId = emptyTextRank->select0(docId+1);
615 result.push_back(docId);
617 else // Sampled position
619 DocId docId = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
621 docId = emptyTextRank->select0(docId+1);
622 result.push_back(docId);
629 TextCollection::document_result CSA::Equal(uchar const *pattern) const
631 TextPosition m = strlen((char const *)pattern);
633 return TextCollection::document_result(); // FIXME Should return all empty texts
635 TextPosition sp = 0, ep = 0;
636 // Match including end-marker
637 Search(pattern, m+1, &sp, &ep);
639 TextCollection::document_result result;
641 // Report end-markers in result interval
642 unsigned resultSize = CountEndmarkers(sp, ep);
646 result.reserve(resultSize); // Try to avoid reallocation.
650 i = alphabetrank->rank(0, sp - 1);
653 // End-marker we found belongs to the "previous" doc in the collection
654 DocId docId = ((*endmarkerDocId)[i] + 1) % numberOfTexts;
656 docId = emptyTextRank->select0(docId+1);
657 result.push_back(docId);
667 TextCollection::document_result CSA::Contains(uchar const * pattern) const
669 TextPosition m = strlen((char *)pattern);
671 return TextCollection::document_result();
673 TextPosition sp = 0, ep = 0;
674 // Search all occurrences
675 Search(pattern, m, &sp, &ep);
677 // We want unique document indentifiers, using std::set to collect them
678 std::set<DocId> resultSet;
680 ulong sampled_rank_i = 0;
681 // Check each occurrence
682 for (; sp <= ep; ++sp)
685 uchar c = alphabetrank->access(i);
686 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
688 i = C[c]+alphabetrank->rank(c,i)-1; // LF-mapping
689 c = alphabetrank->access(i);
693 // Rank among the end-markers in BWT
694 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
696 // End-marker that we found belongs to the "preceeding" doc in collection:
697 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
698 resultSet.insert(docId);
702 DocId di = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
703 assert((unsigned)di < numberOfTexts);
704 resultSet.insert(di);
708 // Convert std::set to std::vector
709 TextCollection::document_result result(resultSet.begin(), resultSet.end());
711 for (document_result::iterator it = result.begin(); it != result.end(); ++it)
712 *it = emptyTextRank->select0(*it+1);
716 TextCollection::document_result CSA::LessThan(uchar const * pattern) const
718 TextPosition m = strlen((char *)pattern);
720 return TextCollection::document_result(); // empty result set
722 TextPosition sp = 0, ep = 0;
723 SearchLessThan(pattern, m, &sp, &ep);
725 TextCollection::document_result result;
727 // Report end-markers in result interval
728 unsigned resultSize = CountEndmarkers(sp, ep);
732 result.reserve(resultSize); // Try to avoid reallocation.
734 // Iterate through end-markers in [sp,ep]:
737 i = alphabetrank->rank(0, sp - 1);
740 // End-marker we found belongs to the "preceeding" doc in the collection
741 DocId docId = ((*endmarkerDocId)[i] + 1) % numberOfTexts;
743 docId = emptyTextRank->select0(docId+1);
744 result.push_back(docId);
754 * Full result set queries
756 TextCollection::full_result CSA::FullContains(uchar const * pattern) const
758 TextPosition m = strlen((char *)pattern);
760 return full_result(); // FIXME Throw exception?
762 TextPosition sp = 0, ep = 0;
763 // Search all occurrences
764 Search(pattern, m, &sp, &ep);
767 result.reserve(ep-sp+1); // Try to avoid reallocation.
769 ulong sampled_rank_i = 0;
770 // Report each occurrence
771 for (; sp <= ep; ++sp)
774 TextPosition dist = 0;
775 uchar c = alphabetrank->access(i);
776 while (c != '\0' && !sampled->IsBitSet(i, &sampled_rank_i))
778 i = C[c]+alphabetrank->rank(c,i)-1;
779 c = alphabetrank->access(i);
784 // Rank among the end-markers in BWT
785 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
787 // End-marker that we found belongs to the "preceeding" doc in collection:
788 DocId docId = ((*endmarkerDocId)[endmarkerRank] + 1) % numberOfTexts;
790 docId = emptyTextRank->select0(docId+1);
791 result.push_back(make_pair(docId, dist));
795 TextPosition textPos = (*suffixes)[sampled_rank_i-1]+dist; //sampled->rank(i)-1] + dist;
796 DocId docId = (*suffixDocId)[sampled_rank_i-1]; //sampled->rank(i)-1];
797 // textPos = textPos - (*textStartPos)[docId]; // Offset inside the text
800 docId = emptyTextRank->select0(docId+1);
801 result.push_back(make_pair(docId, textPos));
810 * Save index to a file handle
812 * Throws a std::runtime_error exception on i/o error.
813 * First byte that is saved represents the version number of the save file.
814 * In version 2 files, the data fields are:
819 TextPosition bwtEndPos;
820 static_sequence * alphabetrank;
822 BlockArray *suffixes;
823 BlockArray *suffixDocId;
824 unsigned numberOfTexts;
825 unsigned numberOfAllTexts;
827 BlockArray *endmarkerDocId;
828 BSGAP *emptyTextRank;
830 void CSA::Save(FILE *file) const
832 // Saving version info:
833 if (std::fwrite(&versionFlag, 1, 1, file) != 1)
834 throw std::runtime_error("CSA::Save(): file write error (version flag).");
836 if (std::fwrite(&(this->n), sizeof(TextPosition), 1, file) != 1)
837 throw std::runtime_error("CSA::Save(): file write error (n).");
838 if (std::fwrite(&(this->samplerate), sizeof(unsigned), 1, file) != 1)
839 throw std::runtime_error("CSA::Save(): file write error (samplerate).");
841 for(ulong i = 0; i < 256; ++i)
842 if (std::fwrite(this->C + i, sizeof(unsigned), 1, file) != 1)
843 throw std::runtime_error("CSA::Save(): file write error (C table).");
845 if (std::fwrite(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
846 throw std::runtime_error("CSA::Save(): file write error (bwt end position).");
848 alphabetrank->save(file);
850 suffixes->Save(file);
851 suffixDocId->Save(file);
853 if (std::fwrite(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
854 throw std::runtime_error("CSA::Save(): file write error (numberOfTexts).");
855 if (std::fwrite(&(this->numberOfAllTexts), sizeof(unsigned), 1, file) != 1)
856 throw std::runtime_error("CSA::Save(): file write error (numberOfAllTexts).");
857 if (std::fwrite(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
858 throw std::runtime_error("CSA::Save(): file write error (maxTextLength).");
860 endmarkerDocId->Save(file);
861 emptyTextRank->Save(file);
867 * Load index from a file handle
869 * Throws a std::runtime_error exception on i/o error.
870 * For more info, see CSA::Save().
872 void CSA::Load(FILE *file, unsigned samplerate)
876 delete dynFMI; dynFMI = 0;
878 delete alphabetrank; alphabetrank = 0;
879 delete sampled; sampled = 0;
880 delete suffixes; suffixes = 0;
881 delete suffixDocId; suffixDocId = 0;
882 delete [] codetable; codetable = 0;
884 delete endmarkerDocId; endmarkerDocId = 0;
885 delete emptyTextRank; emptyTextRank = 0;
887 this->maxTextLength = 0;
888 this->numberOfTexts = 0;
889 this->numberOfAllTexts = 0;
890 this->samplerate = samplerate;
894 if (std::fread(&verFlag, 1, 1, file) != 1)
895 throw std::runtime_error("CSA::Load(): file read error (version flag).");
896 if (verFlag != CSA::versionFlag)
897 throw std::runtime_error("CSA::Load(): invalid save file version.");
899 if (std::fread(&(this->n), sizeof(TextPosition), 1, file) != 1)
900 throw std::runtime_error("CSA::Load(): file read error (n).");
901 if (std::fread(&samplerate, sizeof(unsigned), 1, file) != 1)
902 throw std::runtime_error("CSA::Load(): file read error (samplerate).");
903 // FIXME samplerate can not be changed during load.
904 // if (this->samplerate == 0)
905 // this->samplerate = samplerate;
907 for(ulong i = 0; i < 256; ++i)
908 if (std::fread(this->C + i, sizeof(unsigned), 1, file) != 1)
909 throw std::runtime_error("CSA::Load(): file read error (C table).");
911 if (std::fread(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
912 throw std::runtime_error("CSA::Load(): file read error (bwt end position).");
914 alphabetrank = static_sequence::load(file);
915 sampled = new BSGAP(file);
916 suffixes = new BlockArray(file);
917 suffixDocId = new BlockArray(file);
919 if (std::fread(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
920 throw std::runtime_error("CSA::Load(): file read error (numberOfTexts).");
921 if (std::fread(&(this->numberOfAllTexts), sizeof(unsigned), 1, file) != 1)
922 throw std::runtime_error("CSA::Load(): file read error (numberOfAllTexts).");
923 if (std::fread(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
924 throw std::runtime_error("CSA::Load(): file read error (maxTextLength).");
926 endmarkerDocId = new BlockArray(file);
927 emptyTextRank = new BSGAP(file);
929 // FIXME Construct data structures with new samplerate
936 * Rest of the functions follow...
940 ulong CSA::Search(uchar const * pattern, TextPosition m, TextPosition *spResult, TextPosition *epResult) const
942 // use the FM-search replacing function Occ(c,1,i) with alphabetrank->rank(c,i)
943 int c = (int)pattern[m-1];
945 TextPosition sp = C[c];
946 TextPosition ep = C[c+1]-1;
947 while (sp<=ep && i>=1)
949 // printf("i = %lu, c = %c, sp = %lu, ep = %lu\n", i, pattern[i], sp, ep);
950 c = (int)pattern[--i];
951 sp = C[c]+alphabetrank->rank(c,sp-1);
952 ep = C[c]+alphabetrank->rank(c,ep)-1;
963 ulong CSA::SearchLessThan(uchar const * pattern, TextPosition m, TextPosition *spResult, TextPosition *epResult) const
965 // use the FM-search replacing function Occ(c,1,i) with alphabetrank->rank(c,i)
966 uint c = (int)pattern[m-1];
969 TextPosition ep = C[c+1]-1;
970 while (sp<=ep && i>=1)
972 // printf("i = %lu, c = %c, sp = %lu, ep = %lu\n", i, pattern[i], sp, ep);
973 c = (int)pattern[--i];
974 uint result = alphabetrank->rank(c,ep);
997 delete [] codetable; // FIXME remove
999 delete endmarkerDocId;
1000 delete emptyTextRank;
1003 void CSA::makewavelet(uchar *bwt)
1012 if (C[i]>0) {min = i; break;}
1013 for (i=255;i>=min;--i)
1014 if (C[i]>0) {max = i; break;}
1016 ulong prev=C[0], temp;
1018 for (i=1;i<256;i++) {
1023 // this->codetable = node::makecodetable(bwt,n);
1024 // alphabetrank = new THuffAlphabetRank(bwt,n, this->codetable,0);
1026 //alphabetrank = new RLWaveletTree(bwt, n); // Deletes bwt!
1027 std::cerr << "heap usage: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1028 std::cerr << "max heap usage before WT: " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1030 HeapProfiler::ResetMaxHeapConsumption(); // FIXME remove
1032 alphabet_mapper * am = new alphabet_mapper_none();
1033 static_bitsequence_builder * bmb = new static_bitsequence_builder_rrr02(8); // FIXME samplerate?
1034 // static_bitsequence_builder * bmb = new static_bitsequence_builder_brw32(16); // FIXME samplerate?
1035 wt_coder * wtc = new wt_coder_binary(bwt,n,am);
1036 alphabetrank = new static_sequence_wvtree(bwt,n,wtc,bmb,am);
1038 bwt = 0; // already deleted
1040 std::cerr << "heap usage: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1041 std::cerr << "max heap usage after WT: " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1044 void CSA::maketables()
1046 // Calculate BWT end-marker position (of last inserted text)
1047 // Note: bwtEndPos already set!
1048 // and the length of the first text (counter l):
1053 uint alphabetrank_i_tmp = 0;
1054 uchar c = alphabetrank->access(i, alphabetrank_i_tmp);
1057 i = C[c]+alphabetrank_i_tmp-1;
1059 c = alphabetrank->access(i, alphabetrank_i_tmp);
1062 if (i != bwtEndPos) // compare result
1064 std::cout << "i = " << i << ", bwtendpos = " << bwtEndPos << std::endl;
1070 // Build up arrays for text length and starting positions
1071 // FIXME Temp, remove
1072 //BlockArray* textLength = new BlockArray(numberOfTexts, Tools::CeilLog2(maxTextLength));
1073 BlockArray* textStartPos = new BlockArray(numberOfTexts, Tools::CeilLog2(this->n));
1074 //(*textLength)[0] = l;
1075 (*textStartPos)[0] = 0;
1077 // Construct samples
1078 ulong sampleLength = (n%samplerate==0) ? n/samplerate : n/samplerate+1;
1079 unsigned ceilLog2n = Tools::CeilLog2(n);
1080 BlockArray* positions = new BlockArray(sampleLength, ceilLog2n);
1081 BlockArray* tmpSuffix = new BlockArray(sampleLength, ceilLog2n);
1083 // Mapping from end-markers to doc ID's:
1084 endmarkerDocId = new BlockArray(numberOfTexts, Tools::CeilLog2(numberOfTexts));
1086 ulong *sampledpositions = new ulong[n/W+1];
1087 for (ulong i=0;i<n/W+1;i++)
1088 sampledpositions[i]=0lu;
1090 ulong x,p=bwtEndPos;
1091 ulong sampleCount = 0;
1092 // Keeping track of text position of prev. end-marker seen
1093 ulong posOfSuccEndmarker = n;
1094 DocId textId = numberOfTexts;
1097 uint alphabetrank_i_tmp =0;
1100 for (ulong i=n-1;i<ulongmax;i--) { // TODO bad solution with ulongmax?
1101 // i substitutes SA->GetPos(i)
1104 if (x % samplerate == 0 && posOfSuccEndmarker - x > samplerate) {
1105 Tools::SetField(sampledpositions,1,p,1);
1106 (*positions)[sampleCount] = p;
1107 (*tmpSuffix)[sampleCount] = x; // FIXME remove
1111 uchar c = alphabetrank->access(p, alphabetrank_i_tmp);
1116 // Record the order of end-markers in BWT:
1117 ulong endmarkerRank = alphabetrank_i_tmp - 1;
1118 (*endmarkerDocId)[endmarkerRank] = textId;
1120 // Store text length and text start position:
1121 if (textId < (DocId)numberOfTexts - 1)
1123 //(*textLength)[textId + 1] = posOfSuccEndmarker - x;
1124 (*textStartPos)[textId + 1] = x; // x is the position of end-marker.
1125 posOfSuccEndmarker = x;
1128 // LF-mapping from '\0' does not work with this (pseudo) BWT (see details from Wolfgang's thesis).
1129 p = textId; // Correct LF-mapping to the last char of the previous text.
1132 p = C[c]+alphabetrank_i_tmp-1;
1134 assert(textId == 0);
1136 sampled = new BSGAP(sampledpositions,n,true);
1137 sampleLength = sampled->rank(n-1);
1138 assert(sampleCount == sampleLength);
1140 // Suffixes store an offset from the text start position
1141 suffixes = new BlockArray(sampleLength, Tools::CeilLog2(maxTextLength));
1142 suffixDocId = new BlockArray(sampleLength, Tools::CeilLog2(numberOfTexts));
1144 for(ulong i=0; i<sampleLength; i++) {
1145 assert((*positions)[i] < n);
1146 ulong j = sampled->rank((*positions)[i]);
1147 if (j==0) j=sampleLength;
1148 TextPosition textPos = (*tmpSuffix)[i];
1149 (*suffixDocId)[j-1] = DocIdAtTextPos(textStartPos, textPos);
1151 assert((unsigned)DocIdAtTextPos(textStartPos, textPos) < numberOfTexts);
1152 assert((*suffixDocId)[j-1] < numberOfTexts);
1153 // calculate offset from text start:
1154 (*suffixes)[j-1] = textPos - (*textStartPos)[(*suffixDocId)[j-1]];
1156 // FIXME Temp, remove
1159 // delete textLength;
1160 delete textStartPos;
1165 * Finds document identifier for given text position
1167 * Starting text position of the document is stored into second parameter.
1168 * Binary searching on text starting positions.
1170 TextCollection::DocId CSA::DocIdAtTextPos(BlockArray* textStartPos, TextPosition i) const
1175 DocId b = numberOfTexts - 1;
1178 DocId c = a + (b - a)/2;
1179 if ((*textStartPos)[c] > i)
1181 else if ((*textStartPos)[c+1] > i)
1187 assert(a < (DocId)numberOfTexts);
1188 assert(i >= (*textStartPos)[a]);
1189 assert(i < (a == (DocId)numberOfTexts - 1 ? n : (*textStartPos)[a+1]));
1193 CSA::TCodeEntry * CSA::node::makecodetable(uchar *text, TextPosition n)
1195 TCodeEntry *result = new TCodeEntry[ 256 ];
1197 count_chars( text, n, result );
1198 std::priority_queue< node, std::vector< node >, std::greater<node> > q;
1200 // First I push all the leaf nodes into the queue
1202 for ( unsigned int i = 0 ; i < 256 ; i++ )
1203 if ( result[ i ].count )
1204 q.push(node( i, result[ i ].count ) );
1206 // This loop removes the two smallest nodes from the
1207 // queue. It creates a new internal node that has
1208 // those two nodes as children. The new internal node
1209 // is then inserted into the priority queue. When there
1210 // is only one node in the priority queue, the tree
1214 while ( q.size() > 1 ) {
1215 node *child0 = new node( q.top() );
1217 node *child1 = new node( q.top() );
1219 q.push( node( child0, child1 ) );
1222 // Now I compute and return the codetable
1224 q.top().maketable(0u,0u, result);
1230 void CSA::node::maketable(unsigned code, unsigned bits, TCodeEntry *codetable) const
1234 child0->maketable( SetBit(code,bits,0), bits+1, codetable );
1235 child1->maketable( SetBit(code,bits,1), bits+1, codetable );
1241 codetable[value].code = code;
1242 codetable[value].bits = bits;
1246 void CSA::node::count_chars(uchar *text, TextPosition n, TCodeEntry *counts )
1249 for (i = 0 ; i < 256 ; i++ )
1250 counts[ i ].count = 0;
1252 counts[(int)text[i]].count++;
1255 unsigned CSA::node::SetBit(unsigned x, unsigned pos, unsigned bit) {
1256 return x | (bit << pos);