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 *****************************************************************************/
20 #include "TCImplementation.h"
22 //#define DEBUG_MEMUSAGE
24 #include "HeapProfiler.h" // FIXME remove
34 #include <cstring> // For strlen()
43 // Save file version info
44 const uchar TCImplementation::versionFlag = 6;
47 * Constructor inits an empty dynamic FM-index.
48 * Samplerate defaults to TEXTCOLLECTION_DEFAULT_SAMPLERATE.
50 TCImplementation::TCImplementation(uchar * bwt, ulong length, unsigned samplerate_,
51 unsigned numberOfTexts_, ulong maxTextLength_, ulong numberOfSamples_, char tsType)
52 : n(length), samplerate(samplerate_), alphabetrank(0), sampled(0), suffixes(0),
53 suffixDocId(0), numberOfTexts(numberOfTexts_), maxTextLength(maxTextLength_), Doc(0)
55 makewavelet(bwt); // Deletes bwt!
58 // Make sampling tables
59 maketables(numberOfSamples_, tsType);
62 bool TCImplementation::EmptyText(DocId k) const
64 assert(k < (DocId)numberOfTexts);
65 return false; // Empty texts are not indexed
68 uchar * TCImplementation::GetText(DocId k) const
70 assert(k < (DocId)numberOfTexts);
72 return textStorage->GetText(k);
73 /* TextPosition i = k;
76 // Reserve average string length to avoid reallocs
77 result.reserve(n/numberOfTexts);
79 uchar c = alphabetrank->access(i);
83 i = C[c]+alphabetrank->rank(c,i)-1;
85 c = alphabetrank->access(i); // "next" char.
88 // Convert to uchar (FIXME return string?)
90 uchar* res = new uchar[i+1];
92 for (ulong j = 0; j < i; ++j)
93 res[i-j-1] = result[j];
98 uchar* TCImplementation::GetText(DocId k, TextPosition i, TextPosition j) const
100 assert(k < (DocId)numberOfTexts);
101 assert(j < (*textLength)[k]);
106 // Start position of k'th text
107 ulong start = (*textStartPos)[k];
109 return Substring(i + start, j-i+1);
112 /******************************************************************
113 * Existential queries
115 bool TCImplementation::IsPrefix(uchar const * pattern) const
117 TextPosition m = strlen((char *)pattern);
121 TextPosition sp = 0, ep = 0;
122 Search(pattern, m, &sp, &ep);
124 // Check for end-marker(s) in result interval
125 if (CountEndmarkers(sp, ep))
130 bool TCImplementation::IsPrefix(uchar const * pattern, DocId begin, DocId end) const
132 TextPosition m = strlen((char *)pattern);
136 TextPosition sp = 0, ep = 0;
137 Search(pattern, m, &sp, &ep);
139 // Check for end-marker(s) in result interval
140 if (CountEndmarkers(sp, ep, begin, end))
146 bool TCImplementation::IsSuffix(uchar const *pattern) const
148 // Here counting is as fast as IsSuffix():
149 if (CountSuffix(pattern) > 0)
154 bool TCImplementation::IsSuffix(uchar const *pattern, DocId begin, DocId end) const
156 // Here counting is as fast as IsSuffix():
157 if (CountSuffix(pattern, begin, end) > 0)
162 bool TCImplementation::IsEqual(uchar const *pattern) const
164 TextPosition m = std::strlen((char *)pattern);
166 return false; // No empty texts exists
168 TextPosition sp = 0, ep = 0;
169 // Match including end-marker
170 Search(pattern, m+1, &sp, &ep);
172 // Check for end-marker(s) in result interval
173 if (CountEndmarkers(sp, ep))
178 bool TCImplementation::IsEqual(uchar const *pattern, DocId begin, DocId end) const
180 TextPosition m = std::strlen((char *)pattern);
182 return false; // No empty texts exists
184 TextPosition sp = 0, ep = 0;
185 // Match including end-marker
186 Search(pattern, m+1, &sp, &ep, begin, end);
188 // Check for end-marker(s) in result interval
189 if (CountEndmarkers(sp, ep))
194 bool TCImplementation::IsContains(uchar const * pattern) const
196 TextPosition m = strlen((char *)pattern);
200 TextPosition sp = 0, ep = 0;
201 // Just check if pattern exists somewhere
202 ulong count = Search(pattern, m, &sp, &ep);
209 bool TCImplementation::IsContains(uchar const * pattern, DocId begin, DocId end) const
211 // Here counting is as fast as existential querying
212 if (CountContains(pattern, begin, end) > 0)
213 return true; // FIXME No need to filter result set
217 bool TCImplementation::IsLessThan(uchar const * pattern) const
219 if (CountLessThan(pattern) > 0)
224 bool TCImplementation::IsLessThan(uchar const * pattern, DocId begin, DocId end) const
226 if (CountLessThan(pattern, begin, end) > 0)
231 /******************************************************************
234 ulong TCImplementation::Count(uchar const * pattern) const
236 TextPosition m = strlen((char *)pattern);
240 TextPosition sp = 0, ep = 0;
241 unsigned count = (unsigned) Search(pattern, m, &sp, &ep);
245 unsigned TCImplementation::CountPrefix(uchar const * pattern) const
247 TextPosition m = strlen((char *)pattern);
249 return numberOfTexts;
251 TextPosition sp = 0, ep = 0;
252 Search(pattern, m, &sp, &ep);
254 // Count end-markers in result interval
255 return CountEndmarkers(sp, ep);
258 unsigned TCImplementation::CountPrefix(uchar const * pattern, DocId begin, DocId end) const
260 TextPosition m = strlen((char *)pattern);
262 return numberOfTexts;
264 TextPosition sp = 0, ep = 0;
265 Search(pattern, m, &sp, &ep);
267 // Count end-markers in result interval
268 return CountEndmarkers(sp, ep, begin, end);
271 unsigned TCImplementation::CountSuffix(uchar const * pattern) const
273 TextPosition m = strlen((char *)pattern);
275 return numberOfTexts;
277 TextPosition sp = 0, ep = 0;
278 // Search with end-marker
279 unsigned count = (unsigned) Search(pattern, m+1, &sp, &ep);
284 unsigned TCImplementation::CountSuffix(uchar const * pattern, DocId begin, DocId end) const
286 TextPosition m = strlen((char *)pattern);
288 return numberOfTexts;
290 TextPosition sp = 0, ep = 0;
291 // Search with end-marker
292 unsigned count = (unsigned) Search(pattern, m+1, &sp, &ep, begin, end);
297 unsigned TCImplementation::CountEqual(uchar const *pattern) const
299 TextPosition m = strlen((char const *)pattern);
301 return 0; // No empty texts.
303 TextPosition sp = 0, ep = 0;
304 // Match including end-marker
305 Search(pattern, m+1, &sp, &ep);
307 // Count end-markers in result interval
308 return CountEndmarkers(sp, ep);
311 unsigned TCImplementation::CountEqual(uchar const *pattern, DocId begin, DocId end) const
313 TextPosition m = strlen((char const *)pattern);
315 return 0; // No empty texts.
317 TextPosition sp = 0, ep = 0;
318 // Match including end-marker
319 Search(pattern, m+1, &sp, &ep, begin, end);
321 // Count end-markers in result interval
322 return CountEndmarkers(sp, ep); // Already within [begin, end]
325 unsigned TCImplementation::CountContains(uchar const * pattern) const
327 TextPosition m = strlen((char const *)pattern);
329 return numberOfTexts; // Total number of texts.
331 // Here counting is as slow as fetching the result set
332 // because we have to filter out occ's that fall within same document.
333 TextCollection::document_result result = Contains(pattern);
334 return result.size();
337 unsigned TCImplementation::CountContains(uchar const * pattern, DocId begin, DocId end) const
339 TextPosition m = strlen((char const *)pattern);
341 return numberOfTexts; // Total number of texts.
343 // Here counting is as slow as fetching the result set
344 // because we have to filter out occ's that fall within same document.
345 TextCollection::document_result result = Contains(pattern, begin, end);
346 return result.size();
349 // Less than or equal
350 unsigned TCImplementation::CountLessThan(uchar const * pattern) const
352 TextPosition m = strlen((char const *)pattern);
354 return 0; // No empty texts.
356 TextPosition sp = 0, ep = 0;
357 SearchLessThan(pattern, m, &sp, &ep);
359 // Count end-markers in result interval
360 return CountEndmarkers(sp, ep);
363 unsigned TCImplementation::CountLessThan(uchar const * pattern, DocId begin, DocId end) const
365 TextPosition m = strlen((char const *)pattern);
367 return 0; // No empty texts.
369 TextPosition sp = 0, ep = 0;
370 SearchLessThan(pattern, m, &sp, &ep);
372 // Count end-markers in result interval
373 return CountEndmarkers(sp, ep, begin, end);
377 * Document reporting queries
379 TextCollection::document_result TCImplementation::Prefix(uchar const * pattern) const
381 TextPosition m = strlen((char *)pattern);
383 return TextCollection::document_result(); // FIXME Should return all 1...k
385 TextPosition sp = 0, ep = 0;
386 Search(pattern, m, &sp, &ep);
388 // Iterate through end-markers in [sp,ep]:
389 return EnumerateEndmarkers(sp, ep);
392 TextCollection::document_result TCImplementation::Prefix(uchar const * pattern, DocId begin, DocId end) const
394 TextPosition m = strlen((char *)pattern);
396 return TextCollection::document_result(); // FIXME Should return all 1...k
398 TextPosition sp = 0, ep = 0;
399 Search(pattern, m, &sp, &ep);
401 // Return end-markers in [sp,ep] and [begin, end]:
402 return EnumerateEndmarkers(sp, ep, begin, end);
405 TextCollection::document_result TCImplementation::Suffix(uchar const * pattern) const
407 TextPosition m = strlen((char *)pattern);
409 return TextCollection::document_result(); // FIXME Should return all 1...k
411 TextPosition sp = 0, ep = 0;
412 // Search with end-marker
413 Search(pattern, m+1, &sp, &ep);
415 TextCollection::document_result result;
416 result.reserve(ep-sp+1); // Try to avoid reallocation.
418 // Check each occurrence
419 for (; sp <= ep; ++sp)
423 uchar c = alphabetrank->access(i);
424 while (c != '\0' && !sampled->access(i))
426 i = C[c]+alphabetrank->rank(c,i)-1;
427 c = alphabetrank->access(i);
429 // Assert: c == '\0' OR sampled->IsBitSet(i)
433 // Rank among the end-markers in BWT
434 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
435 result.push_back(Doc->access(endmarkerRank));
437 else // Sampled position
439 DocId docId = (*suffixDocId)[sampled->rank1(i)-1];
440 result.push_back(docId);
447 TextCollection::document_result TCImplementation::Suffix(uchar const * pattern, DocId begin, DocId end) const
449 TextPosition m = strlen((char *)pattern);
451 return TextCollection::document_result(); // FIXME Should return all 1...k
453 TextPosition sp = 0, ep = 0;
454 // Search with end-marker
455 Search(pattern, m+1, &sp, &ep, begin, end);
457 TextCollection::document_result result;
458 result.reserve(ep-sp+1); // Try to avoid reallocation.
460 // Check each occurrence, already within [begin, end]
461 for (; sp <= ep; ++sp)
465 uchar c = alphabetrank->access(i);
466 while (c != '\0' && !sampled->access(i))
468 i = C[c]+alphabetrank->rank(c,i)-1;
469 c = alphabetrank->access(i);
471 // Assert: c == '\0' OR sampled->IsBitSet(i)
475 // Rank among the end-markers in BWT
476 unsigned endmarkerRank = alphabetrank->rank(0, i) - 1;
477 result.push_back(Doc->access(endmarkerRank));
479 else // Sampled position
481 DocId docId = (*suffixDocId)[sampled->rank1(i)-1];
482 result.push_back(docId);
490 TextCollection::document_result TCImplementation::Equal(uchar const *pattern) const
492 TextPosition m = strlen((char const *)pattern);
494 return TextCollection::document_result(); // FIXME Should return all empty texts
496 TextPosition sp = 0, ep = 0;
497 // Match including end-marker
498 Search(pattern, m+1, &sp, &ep);
500 // Report end-markers in result interval
501 return EnumerateEndmarkers(sp, ep);
504 TextCollection::document_result TCImplementation::Equal(uchar const *pattern, DocId begin, DocId end) const
506 TextPosition m = strlen((char const *)pattern);
508 return TextCollection::document_result(); // FIXME Should return all empty texts
510 TextPosition sp = 0, ep = 0;
511 // Match including end-marker
512 Search(pattern, m+1, &sp, &ep, begin, end);
514 // Report end-markers in result interval
515 return EnumerateEndmarkers(sp, ep, begin, end);
519 TextCollection::document_result TCImplementation::Contains(uchar const * pattern) const
521 TextPosition m = strlen((char *)pattern);
523 return TextCollection::document_result();
525 TextPosition sp = 0, ep = 0;
526 // Search all occurrences
527 Search(pattern, m, &sp, &ep);
529 // We want unique document indentifiers, using std::set to collect them
530 std::set<DocId> resultSet;
531 EnumerateDocuments(resultSet, sp, ep);
533 // Convert std::set to std::vector
534 TextCollection::document_result result(resultSet.begin(), resultSet.end());
538 TextCollection::document_result TCImplementation::Contains(uchar const * pattern, DocId begin, DocId end) const
540 TextPosition m = strlen((char *)pattern);
542 return TextCollection::document_result();
544 TextPosition sp = 0, ep = 0;
545 // Search all occurrences
546 Search(pattern, m, &sp, &ep);
548 // We want unique document indentifiers, using std::set to collect them
549 std::set<DocId> resultSet;
550 EnumerateDocuments(resultSet, sp, ep, begin, end);
552 // Convert std::set to std::vector
553 TextCollection::document_result result(resultSet.begin(), resultSet.end());
557 TextCollection::document_result TCImplementation::LessThan(uchar const * pattern) const
559 TextPosition m = strlen((char *)pattern);
561 return TextCollection::document_result(); // empty result set
563 TextPosition sp = 0, ep = 0;
564 SearchLessThan(pattern, m, &sp, &ep);
566 // Report end-markers in result interval
567 return EnumerateEndmarkers(sp, ep);
570 TextCollection::document_result TCImplementation::LessThan(uchar const * pattern, DocId begin, DocId end) const
572 TextPosition m = strlen((char *)pattern);
574 return TextCollection::document_result(); // empty result set
576 TextPosition sp = 0, ep = 0;
577 SearchLessThan(pattern, m, &sp, &ep);
579 // Iterate through end-markers in [sp,ep] and [begin, end]:
580 return EnumerateEndmarkers(sp, ep, begin, end);
584 TextCollection::document_result TCImplementation::KMismaches(uchar const * pattern, unsigned k) const
586 TextPosition m = strlen((char *)pattern);
588 return TextCollection::document_result(); // empty result set
590 suffix_range_vector ranges;
591 kmismatches(ranges, pattern, 0, n-1, m, k);
592 std::set<DocId> resultSet;
594 for (suffix_range_vector::iterator it = ranges.begin(); it != ranges.end(); ++it)
595 // Iterate through docs in [sp,ep]:
596 EnumerateDocuments(resultSet, (*it).first, (*it).second);
598 // Convert std::set to std::vector
599 TextCollection::document_result result(resultSet.begin(), resultSet.end());
603 TextCollection::document_result TCImplementation::KErrors(uchar const * pattern, unsigned k) const
605 TextPosition m = strlen((char *)pattern);
607 return TextCollection::document_result(); // empty result set
609 suffix_range_vector ranges;
610 ulong *dd = new ulong[m+1];
611 for (ulong i=0;i<m+1;i++)
613 kerrors(ranges, pattern, 0, n-1, m+k, k, dd, m);
616 std::set<DocId> resultSet;
617 for (suffix_range_vector::iterator it = ranges.begin(); it != ranges.end(); ++it)
618 // Iterate through docs in [sp,ep]:
619 EnumerateDocuments(resultSet, (*it).first, (*it).second);
621 // Convert std::set to std::vector
622 TextCollection::document_result result(resultSet.begin(), resultSet.end());
628 * Full result set queries
630 TextCollection::full_result TCImplementation::FullContains(uchar const * pattern) const
632 TextPosition m = strlen((char *)pattern);
634 return full_result(); // FIXME Throw exception?
636 TextPosition sp = 0, ep = 0;
637 // Search all occurrences
638 Search(pattern, m, &sp, &ep);
641 result.reserve(ep-sp+1); // Try to avoid reallocation.
642 EnumeratePositions(result, sp, ep);
647 TextCollection::full_result TCImplementation::FullContains(uchar const * pattern, DocId begin, DocId end) const
649 TextPosition m = strlen((char *)pattern);
651 return full_result(); // FIXME Throw exception?
653 TextPosition sp = 0, ep = 0;
654 // Search all occurrences
655 Search(pattern, m, &sp, &ep);
658 result.reserve(ep-sp+1); // Try to avoid reallocation.
659 EnumeratePositions(result, sp, ep, begin, end);
664 TextCollection::full_result TCImplementation::FullKMismatches(uchar const * pattern, unsigned k) const
666 TextPosition m = strlen((char *)pattern);
668 return TextCollection::full_result(); // empty result set
670 suffix_range_vector ranges;
671 ulong count = kmismatches(ranges, pattern, 0, n-1, m, k);
673 TextCollection::full_result result;
674 result.reserve(count); // avoid reallocation.
675 for (suffix_range_vector::iterator it = ranges.begin(); it != ranges.end(); ++it)
676 // Iterate through docs in [sp,ep]:
677 EnumeratePositions(result, (*it).first, (*it).second);
681 TextCollection::full_result TCImplementation::FullKErrors(uchar const * pattern, unsigned k) const
683 TextPosition m = strlen((char *)pattern);
685 return TextCollection::full_result(); // empty result set
687 suffix_range_vector ranges;
688 ulong *dd = new ulong[m+1];
689 for (unsigned i=0;i<m+1;i++)
691 ulong count = kerrors(ranges, pattern, 0, n-1, m+k, k, dd, m);
694 TextCollection::full_result result;
695 result.reserve(count); // avoid reallocation.
696 for (suffix_range_vector::iterator it = ranges.begin(); it != ranges.end(); ++it)
697 // Iterate through docs in [sp,ep]:
698 EnumeratePositions(result, (*it).first, (*it).second);
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;
720 static_sequence *docId;
722 void TCImplementation::Save(FILE *file) const
724 // Saving version info:
725 if (std::fwrite(&versionFlag, 1, 1, file) != 1)
726 throw std::runtime_error("TCImplementation::Save(): file write error (version flag).");
728 if (std::fwrite(&(this->n), sizeof(TextPosition), 1, file) != 1)
729 throw std::runtime_error("TCImplementation::Save(): file write error (n).");
730 if (std::fwrite(&(this->samplerate), sizeof(unsigned), 1, file) != 1)
731 throw std::runtime_error("TCImplementation::Save(): file write error (samplerate).");
733 for(ulong i = 0; i < 256; ++i)
734 if (std::fwrite(this->C + i, sizeof(unsigned), 1, file) != 1)
735 throw std::runtime_error("TCImplementation::Save(): file write error (C table).");
737 if (std::fwrite(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
738 throw std::runtime_error("TCImplementation::Save(): file write error (bwt end position).");
740 alphabetrank->save(file);
742 suffixes->Save(file);
743 suffixDocId->Save(file);
745 if (std::fwrite(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
746 throw std::runtime_error("TCImplementation::Save(): file write error (numberOfTexts).");
747 if (std::fwrite(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
748 throw std::runtime_error("TCImplementation::Save(): file write error (maxTextLength).");
751 textStorage->Save(file);
757 * Load index from a file handle
759 * Throws a std::runtime_error exception on i/o error.
760 * For more info, see TCImplementation::Save().
762 TCImplementation::TCImplementation(FILE *file, unsigned samplerate_)
763 : n(0), samplerate(samplerate_), alphabetrank(0), sampled(0), suffixes(0),
764 suffixDocId(0), numberOfTexts(0), maxTextLength(0), Doc(0)
767 if (std::fread(&verFlag, 1, 1, file) != 1)
768 throw std::runtime_error("TCImplementation::Load(): file read error (version flag).");
769 if (verFlag != TCImplementation::versionFlag)
770 throw std::runtime_error("TCImplementation::Load(): invalid save file version.");
772 if (std::fread(&(this->n), sizeof(TextPosition), 1, file) != 1)
773 throw std::runtime_error("TCImplementation::Load(): file read error (n).");
774 if (std::fread(&samplerate, sizeof(unsigned), 1, file) != 1)
775 throw std::runtime_error("TCImplementation::Load(): file read error (samplerate).");
776 // FIXME samplerate can not be changed during load.
777 // if (this->samplerate == 0)
778 // this->samplerate = samplerate;
780 for(ulong i = 0; i < 256; ++i)
781 if (std::fread(this->C + i, sizeof(unsigned), 1, file) != 1)
782 throw std::runtime_error("TCImplementation::Load(): file read error (C table).");
784 if (std::fread(&(this->bwtEndPos), sizeof(TextPosition), 1, file) != 1)
785 throw std::runtime_error("TCImplementation::Load(): file read error (bwt end position).");
787 alphabetrank = static_sequence::load(file);
788 sampled = static_bitsequence::load(file);
789 suffixes = new BlockArray(file);
790 suffixDocId = new BlockArray(file);
792 if (std::fread(&(this->numberOfTexts), sizeof(unsigned), 1, file) != 1)
793 throw std::runtime_error("TCImplementation::Load(): file read error (numberOfTexts).");
794 if (std::fread(&(this->maxTextLength), sizeof(ulong), 1, file) != 1)
795 throw std::runtime_error("TCImplementation::Load(): file read error (maxTextLength).");
797 Doc = static_sequence::load(file);
798 textStorage = TextStorage::Load(file);
800 // FIXME Construct data structures with new samplerate
807 * Rest of the functions follow...
809 ulong TCImplementation::searchPrefix(uchar const *pattern, ulong i, ulong *sp, ulong *ep) const
812 while (*sp<=*ep && i>=1)
814 c = (int)pattern[--i];
815 *sp = C[c]+alphabetrank->rank(c,*sp-1);
816 *ep = C[c]+alphabetrank->rank(c,*ep)-1;
819 return *ep - *sp + 1;
825 ulong TCImplementation::kmismatches(suffix_range_vector &result, uchar const *pattern, ulong sp, ulong ep, ulong j, unsigned k) const
830 result.push_back(std::make_pair(sp,ep));
840 sum = searchPrefix(pattern, j, &sp, &ep);
842 result.push_back(std::make_pair(sp, ep));
845 vector<int> chars = alphabetrank->accessAll(sp, ep);
846 for (vector<int>::iterator it = chars.begin(); it != chars.end(); ++it)
849 continue; // skip '\0'
851 spnew = C[c]+alphabetrank->rank(c,sp-1);
852 epnew = C[c]+alphabetrank->rank(c,ep)-1;
853 if (c!=pattern[j-1]) knew = (int)k-1; else knew = k;
854 if (knew>=0) sum += kmismatches(result, pattern, spnew, epnew, j-1, knew);
859 //first call kerrors(pattern,1,n,m+k,k,d,m), where d[i]=i
860 ulong TCImplementation::kerrors(suffix_range_vector &result, uchar const *pattern, ulong sp, ulong ep, ulong j, unsigned k, ulong const *d, ulong m) const
863 if (d[m]<=k) // range of suffixes with at most k-errors found
866 result.push_back(std::make_pair(sp, ep));
867 sum += (sp<=ep)?ep-sp+1:0ul;
871 ulong *dnew = new ulong[m+1];
876 vector<int> chars = alphabetrank->accessAll(sp, ep);
877 for (vector<int>::iterator it = chars.begin(); it != chars.end(); ++it)
880 continue; // skip '\0'
882 spnew = C[c]+alphabetrank->rank(c,sp-1);
883 epnew = C[c]+alphabetrank->rank(c,ep)-1;
884 if (spnew>epnew) continue;
887 for (p=1; p<=m; p++) {
888 dnew[p]=myminofthree(d[p]+1,dnew[p-1]+1,(c==pattern[m-p])?d[p-1]:(d[p-1]+1));
889 if (dnew[p]<lowerbound)
890 lowerbound = dnew[p];
893 sum += kerrors(result, pattern, spnew, epnew, j-1, k,dnew,m);
900 ulong TCImplementation::Search(uchar const * pattern, TextPosition m, TextPosition *spResult, TextPosition *epResult) const
902 // use the FM-search replacing function Occ(c,1,i) with alphabetrank->rank(c,i)
903 int c = (int)pattern[m-1];
905 TextPosition sp = C[c];
906 TextPosition ep = C[c+1]-1;
907 while (sp<=ep && i>=1)
909 // printf("i = %lu, c = %c, sp = %lu, ep = %lu\n", i, pattern[i], sp, ep);
910 c = (int)pattern[--i];
911 sp = C[c]+alphabetrank->rank(c,sp-1);
912 ep = C[c]+alphabetrank->rank(c,ep)-1;
922 ulong TCImplementation::Search(uchar const * pattern, TextPosition m, TextPosition *spResult, TextPosition *epResult, DocId begin, DocId end) const
924 // use the FM-search replacing function Occ(c,1,i) with alphabetrank->rank(c,i)
925 int c = (int)pattern[m-1];
926 assert(c == 0); // Start from endmarkers
928 TextPosition sp = begin;
929 TextPosition ep = end;
930 while (sp<=ep && i>=1)
932 // printf("i = %lu, c = %c, sp = %lu, ep = %lu\n", i, pattern[i], sp, ep);
933 c = (int)pattern[--i];
934 sp = C[c]+alphabetrank->rank(c,sp-1);
935 ep = C[c]+alphabetrank->rank(c,ep)-1;
946 ulong TCImplementation::SearchLessThan(uchar const * pattern, TextPosition m, TextPosition *spResult, TextPosition *epResult) const
948 // use the FM-search replacing function Occ(c,1,i) with alphabetrank->rank(c,i)
949 uint c = (int)pattern[m-1];
952 TextPosition ep = C[c+1]-1;
953 while (sp<=ep && i>=1)
955 // printf("i = %lu, c = %c, sp = %lu, ep = %lu\n", i, pattern[i], sp, ep);
956 c = (int)pattern[--i];
957 uint result = alphabetrank->rankLessThan(c,ep);
972 TCImplementation::~TCImplementation() {
981 void TCImplementation::makewavelet(uchar *bwt)
990 if (C[i]>0) {min = i; break;}
991 for (i=255;i>=min;--i)
992 if (C[i]>0) {max = i; break;}
994 ulong prev=C[0], temp;
996 for (i=1;i<256;i++) {
1001 // this->codetable = node::makecodetable(bwt,n);
1002 // alphabetrank = new THuffAlphabetRank(bwt,n, this->codetable,0);
1004 //alphabetrank = new RLWaveletTree(bwt, n); // Deletes bwt!
1005 // std::cerr << "heap usage: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1007 #ifdef DEBUG_MEMUSAGE
1008 std::cerr << "max heap usage before WT: " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1009 HeapProfiler::ResetMaxHeapConsumption();
1012 alphabet_mapper * am = new alphabet_mapper_none();
1013 static_bitsequence_builder * bmb = new static_bitsequence_builder_rrr02(8); // FIXME samplerate?
1014 wt_coder * wtc = new wt_coder_binary(bwt,n,am);
1015 alphabetrank = new static_sequence_wvtree(bwt,n,wtc,bmb,am);
1017 bwt = 0; // already deleted
1019 #ifdef DEBUG_MEMUSAGE
1020 std::cerr << "heap usage after WT: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1021 std::cerr << "max heap usage after WT: " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1025 void TCImplementation::maketables(ulong sampleLength, char tsType)
1027 // Calculate BWT end-marker position (of last inserted text)
1030 uint alphabetrank_i_tmp = 0;
1031 uchar c = alphabetrank->access(i, alphabetrank_i_tmp);
1034 i = C[c]+alphabetrank_i_tmp-1;
1035 c = alphabetrank->access(i, alphabetrank_i_tmp);
1038 this->bwtEndPos = i;
1041 #ifdef DEBUG_MEMUSAGE
1042 std::cerr << "heap usage before BWT traverse: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " / " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes, " << HeapProfiler::GetHeapConsumption() << " / " << HeapProfiler::GetMaxHeapConsumption() << std::endl;
1043 HeapProfiler::ResetMaxHeapConsumption();
1046 // Build up array for text starting positions
1047 // BlockArray* textStartPos = new BlockArray(numberOfTexts, Tools::CeilLog2(this->n));
1048 // (*textStartPos)[0] = 0;
1050 // Mapping from end-markers to doc ID's:
1051 unsigned logNumberOfTexts = Tools::CeilLog2(numberOfTexts);
1052 uint *endmarkerDocId = new uint[(numberOfTexts * logNumberOfTexts)/(8*sizeof(uint)) + 1];
1054 BlockArray* positions = new BlockArray(sampleLength, Tools::CeilLog2(this->n));
1055 uint *sampledpositions = new uint[n/(sizeof(uint)*8)+1];
1056 for (ulong i = 0; i < n / (sizeof(uint)*8) + 1; i++)
1057 sampledpositions[i] = 0;
1059 ulong x,p=bwtEndPos;
1060 ulong sampleCount = 0;
1061 // Keeping track of text position of prev. end-marker seen
1062 ulong posOfSuccEndmarker = n-1;
1063 DocId textId = numberOfTexts;
1066 uint alphabetrank_i_tmp =0;
1068 TextStorageBuilder tsbuilder(n);
1069 Tools::StartTimer();
1071 for (ulong i=n-1;i<ulongmax;i--) {
1072 // i substitutes SA->GetPos(i)
1075 uchar c = alphabetrank->access(p, alphabetrank_i_tmp);
1078 if ((posOfSuccEndmarker - i) % samplerate == 0 && c != '\0')
1080 set_field(sampledpositions,1,p,1);
1081 (*positions)[sampleCount] = p;
1089 // Record the order of end-markers in BWT:
1090 ulong endmarkerRank = alphabetrank_i_tmp - 1;
1091 set_field(endmarkerDocId, logNumberOfTexts, endmarkerRank, (textId + 1) % numberOfTexts);
1093 // Store text length and text start position:
1094 if (textId < (DocId)numberOfTexts - 1)
1096 // (*textStartPos)[textId + 1] = x; // x-1 is text position of end-marker.
1097 posOfSuccEndmarker = i;
1100 // LF-mapping from '\0' does not work with this (pseudo) BWT (see details from Wolfgang's thesis).
1101 p = textId; // Correct LF-mapping to the last char of the previous text.
1103 else // Now c != '\0', do LF-mapping:
1104 p = C[c]+alphabetrank_i_tmp-1;
1106 assert(textId == 0);
1108 #ifdef DEBUG_MEMUSAGE
1109 std::cerr << "heap usage before tsbuilder init: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " / " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes, " << HeapProfiler::GetHeapConsumption() << " / " << HeapProfiler::GetMaxHeapConsumption() << std::endl;
1110 HeapProfiler::ResetMaxHeapConsumption();
1113 textStorage = tsbuilder.InitTextStorage(tsType);
1115 #ifdef DEBUG_MEMUSAGE
1116 std::cerr << "heap usage after tsbuilder init: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " / " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes, " << HeapProfiler::GetHeapConsumption() << " / " << HeapProfiler::GetMaxHeapConsumption() << std::endl;
1117 HeapProfiler::ResetMaxHeapConsumption();
1120 sampled = new static_bitsequence_rrr02(sampledpositions, n, 16);
1121 delete [] sampledpositions;
1122 assert(sampleCount == sampleLength);
1123 assert(sampled->rank1(n-1) == sampleLength);
1125 #ifdef DEBUG_MEMUSAGE
1126 std::cerr << "heap usage after sampled bit vector: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " / " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes, " << HeapProfiler::GetHeapConsumption() << " / " << HeapProfiler::GetMaxHeapConsumption() << std::endl;
1127 HeapProfiler::ResetMaxHeapConsumption();
1130 // Suffixes store an offset from the text start position
1131 suffixes = new BlockArray(sampleLength, Tools::CeilLog2(maxTextLength));
1132 suffixDocId = new BlockArray(sampleLength, Tools::CeilLog2(numberOfTexts));
1135 posOfSuccEndmarker = n-1;
1136 for(ulong i=0; i<sampleLength; i++) {
1137 // Find next sampled text position
1138 while ((posOfSuccEndmarker - x) % samplerate != 0)
1142 if (textStorage->IsEndmarker(x))
1143 posOfSuccEndmarker = x--;
1145 assert((*positions)[i] < n);
1146 ulong j = sampled->rank1((*positions)[i]);
1148 assert(j != 0); // if (j==0) j=sampleLength;
1150 TextPosition textPos = (x==n-1)?0:x+1;
1151 (*suffixDocId)[j-1] = textStorage->DocIdAtTextPos(textPos);
1153 assert((*suffixDocId)[j-1] < numberOfTexts);
1154 // calculate offset from text start:
1155 (*suffixes)[j-1] = textPos - textStorage->TextStartPos((*suffixDocId)[j-1]);
1157 if (x != ~0lu && textStorage->IsEndmarker(x))
1158 posOfSuccEndmarker = x--;
1163 #ifdef DEBUG_MEMUSAGE
1164 std::cerr << "heap usage after sampled arrays: " << HeapProfiler::GetHeapConsumption()/(1024*1024) << " / " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes, " << HeapProfiler::GetHeapConsumption() << " / " << HeapProfiler::GetMaxHeapConsumption() << std::endl;
1165 HeapProfiler::ResetMaxHeapConsumption();
1169 * Second pass: check tables
1172 textId = numberOfTexts;
1173 for (ulong i=n-1;i<ulongmax;i--) {
1176 if (sampled->access(p)) {
1177 ulong j = sampled->rank1(p)-1;
1178 assert((*suffixDocId)[j] == DocIdAtTextPos(textStartPos, x));
1180 // calculate offset from text start:
1181 assert((*suffixes)[j] == x - (*textStartPos)[(*suffixDocId)[j]]);
1184 uchar c = alphabetrank->access(p, alphabetrank_i_tmp);
1189 // LF-mapping from '\0' does not work with this (pseudo) BWT (see details from Wolfgang's thesis).
1190 p = textId; // Correct LF-mapping to the last char of the previous text.
1192 else // Now c != '\0', do LF-mapping:
1193 p = C[c]+alphabetrank_i_tmp-1;
1195 assert(textId == 0);
1199 #ifdef DEBUG_MEMUSAGE
1200 std::cerr << "max heap usage before Doc: " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1201 HeapProfiler::ResetMaxHeapConsumption();
1204 alphabet_mapper * am = new alphabet_mapper_none();
1205 static_bitsequence_builder * bmb = new static_bitsequence_builder_rrr02(32); // FIXME samplerate?
1206 Doc = new static_sequence_wvtree_noptrs(endmarkerDocId, numberOfTexts, logNumberOfTexts, bmb, am, true);
1208 // delete [] endmarkerDocId; // already deleted in static_sequence_wvtree_noptrs!
1210 #ifdef DEBUG_MEMUSAGE
1211 std::cerr << "max heap usage after Doc: " << HeapProfiler::GetMaxHeapConsumption()/(1024*1024) << " Mbytes" << std::endl;
1217 * Finds document identifier for given text position
1219 * Starting text position of the document is stored into second parameter.
1220 * Binary searching on text starting positions.
1222 TextCollection::DocId TCImplementation::DocIdAtTextPos(BlockArray* textStartPos, TextPosition i) const
1227 DocId b = numberOfTexts - 1;
1230 DocId c = a + (b - a)/2;
1231 if ((*textStartPos)[c] > i)
1233 else if ((*textStartPos)[c+1] > i)
1239 assert(a < (DocId)numberOfTexts);
1240 assert(i >= (*textStartPos)[a]);
1241 assert(i < (a == (DocId)numberOfTexts - 1 ? n : (*textStartPos)[a+1]));