Debian Codegraph @

src/iitii.h

raw symbols SCIP
1 /*
2 Implicit Interval Tree with Interpolation Index (iitii)
3
4 This file provides two template classes,
5 iit: implicit interval tree, a reimplementation of cgranges by Heng Li
6 iitii: iit + interpolation index, experimental extension to speed up queries on very large
7 datasets
8
9 Both classes take the folllowing four template parameters:
10 Pos : numeric position type (e.g. uint32_t, double)
11 Item : arbitrary type of the items to be indexed
12 get_beg : a function (const Item& -> Pos) which accesses the interval begin position of item
13 get_end : " " " end "
14 For good performance, get_beg and get_end should just access members of Item (cache-local fetch).
15
16 Example:
17
18 using intpair = std::pair<int,int>;
19 int p_get_beg(const intpair& p) { return p.first; }
20 int p_get_end(const intpair& p) { return p.second; }
21 using p_iit = iit<int, intpair, p_get_beg, p_get_end>; // first arg is position type
22
23 p_iit::builder br;
24 br.add(intpair(12,34));
25 br.add(intpair(0,23));
26 br.add(intpair(34,56));
27 p_iit db = br.build();
28 // alternative: p_iit db = p_iit::builder(container.begin(), container.end()).build();
29
30 std::vector<intpair> results = db.overlap(22, 25);
31 // alternative: db.overlap(22, 25, results);
32
33 Building iitii works the same way, except build() takes a size_t argument giving the number of
34 model domains.
35
36 This header file has other helper template classes that allow most code to be shared between iit
37 and iitii (without burdening the former with baggage from the latter -- important for fair
38 comparative benchmarking). The template structure has gotten a little out of hand, which always
39 seems to happen.
40 */
41
42 #include <vector>
43 #include <limits>
44 #include <algorithm>
45 #include <cmath>
46 #include <iostream>
47 #include <fstream>
48 #include <sstream>
49 #include <fcntl.h>
50 #include <cstdio>
51 #include <cstdlib>
52 #include <cstring>
53 #include <cassert>
54 #include <sys/mman.h>
55 #include <sys/stat.h>
56 #include <sys/types.h>
57 #include <unistd.h>
58 #include "ips4o.hpp"
59 #include "mmappable_vector.h"
60
61 namespace iitii {
62
63 using namespace mmap_allocator_namespace;
64
65 // Base template for the internal representation of a node within an implicit interval tree
66 // User should not care about this; subclass instantiations may add more members for more-
67 // exotically augmented classes of implicit interval trees
68 template<typename Pos, typename Item, Pos get_beg(const Item&), Pos get_end(const Item&)>
69 struct iit_node_base {
70 static const Pos npos = std::numeric_limits<Pos>::max(); // reserved constant for invalid Pos
71
72 Item item;
73 Pos inside_max_end; // max end of this & subtree (as in textbook augmented interval tree)
74
75 iit_node_base(const Item& item_)
76 : item(item_)
77 , inside_max_end(get_end(item))
78 {}
79 inline Pos beg() const {
80 return get_beg(item);
81 }
82 inline Pos end() const {
83 return get_end(item);
84 }
85 bool operator<(const iit_node_base<Pos, Item, get_beg, get_end>& rhs) const {
86 auto lbeg = beg(), rbeg = rhs.beg();
87 if (lbeg == rbeg) {
88 return end() < rhs.end();
89 }
90 return lbeg < rbeg;
91 }
92 };
93
94 // Base template for an implicit interval tree, with internal repr
95 // Node<Pos, Item, ...> : iit_node_base<Pos, Item, ...>
96 // User should not deal with this directly, but instantiate sub-templates iit or iiitii (below)
97 template<typename Pos, typename Item, typename Node>
98 class iit_base {
99 protected:
100 // aliases to help keep the Pos, Rank, and Level concepts straight
101 typedef std::size_t Rank; // rank of a node, its index in the sorted array (or beyond, if
102 // imaginary)
103 typedef std::size_t Level; // level in tree
104
105 static const Rank nrank = std::numeric_limits<Rank>::max(); // invalid Rank
106
107 mmappable_vector<Node> nodes; // array of Nodes sorted by beginning position
108 std::string backing_filename; // the filename backing this mmappable_vector
109 size_t full_size; // size of the full binary tree containing the nodes; liable to be
110 // as large as 2*nodes.size()-1, including imaginary nodes.
111
112 Rank root;
113 Level root_level; // = K in cgranges
114
115 // compute a node's level, the # of 1 bits below the lowest 0 bit
116 inline Level level(Rank node) const {
117 assert(node < full_size);
118 Level ans = __builtin_ctzll(~node); // bitwise-negate & count trailing zeroes
119 #ifndef NDEBUG
120 Level chk;
121 for (chk=0; node&1; chk++, node>>=1);
122 assert(ans == chk);
123 #endif
124 return ans;
125 }
126
127 // get node's parent, or nrank if called on the root
128 inline Rank parent(Rank node) const {
129 assert(node < full_size);
130 if (node == root) {
131 return nrank;
132 }
133 Level lv = level(node);
134 Rank ofs = Rank(1) << lv;
135 assert(node >= ofs-1);
136 if (((node>>(lv+1)) & 1)) { // node is right child
137 assert(node >= ofs);
138 return node-ofs;
139 }
140 // node is left child
141 return node+ofs;
142 }
143
144 // get node's left child, or nrank if called on a leaf
145 inline Rank left(Rank node) const {
146 Level lv = level(node);
147 return lv > 0 ? node - (Rank(1) << (lv-1)) : nrank;
148 }
149
150 // get node's right child, or nrank if called on a leaf
151 inline Rank right(Rank node) const {
152 Level lv = level(node);
153 return lv > 0 ? node + (Rank(1) << (lv-1)) : nrank;
154 }
155
156 // top-down overlap scan for [qbeg,qend). return # of nodes visited
157 // recursion depth limited to tree height
158 // TODO: nip&tuck optimizations (eliminate recursion, unroll traversal of low levels, etc.)
159 size_t scan(Rank subtree, Pos qbeg, Pos qend, std::vector<Item>& ans) const {
160 if (subtree == nrank) {
161 return 0;
162 }
163 assert(subtree < full_size);
164 if (subtree >= nodes.size()) {
165 // When we arrive at an imaginary node, its right subtree must be all imaginary, so we
166 // only need to descend left.
167 // TODO: should be able to work out a closed formula for the next real node we'll find,
168 // given subtree, n.size(), and full_size.
169 return 1 + scan(left(subtree), qbeg, qend, ans);
170 }
171
172 size_t cost = 1;
173 const Node& n = nodes[subtree];
174 if (n.inside_max_end > qbeg) { // something in current subtree extends into/over query
175 cost += scan(left(subtree), qbeg, qend, ans);
176 Pos nbeg = n.beg();
177 if (nbeg < qend) { // this node isn't already past query
178 if (n.end() > qbeg) { // this node overlaps query
179 ans.push_back(n.item);
180 }
181 cost += scan(right(subtree), qbeg, qend, ans);
182 }
183 }
184 return cost;
185 }
186
187 public:
188 iit_base(mmappable_vector<Node>& nodes_, const std::string& filename)
189 : nodes(std::move(nodes_))
190 , backing_filename(filename)
191 , root_level(0)
192 , root(std::numeric_limits<Rank>::max())
193 {
194 // compute the implied tree geometry
195 for (root_level = 0, full_size = 0; full_size < nodes.size();
196 ++root_level, full_size = (size_t(1)<<(root_level+1)) - 1);
197 root = (Rank(1) << root_level) - 1;
198
199 if (nodes.size()) {
200 // sort the nodes by interval beg (then end)
201 ips4o::parallel::sort(nodes.begin(), nodes.end());
202 // Memoize the path from the rightmost leaf up to the root. This will trace the border
203 // between the real and imaginary nodes (if any), which we'll refer to in indexing
204 // below. Some of these border nodes may be imaginary.
205 std::vector<Rank> right_border_nodes({
206 nodes.size() - (2 - nodes.size() % 2) // rightmost real leaf
207 });
208 while (right_border_nodes.back() != root) {
209 right_border_nodes.push_back(parent(right_border_nodes.back()));
210 }
211
212 // bottom-up indexing
213 Pos right_border_ime = nodes[right_border_nodes[0]].inside_max_end;
214 for (Level lv=1; lv <= root_level; ++lv) {
215 // for each in nodes on this level
216 size_t x = size_t(1)<<(lv-1), step = x<<2;
217 for (Rank n = (x<<1)-1; n < nodes.size(); n += step) {
218 // figure inside_max_end
219 Pos ime = nodes[n].end();
220 ime = std::max(ime, nodes[left(n)].inside_max_end);
221 if (right(n) < nodes.size()) {
222 ime = std::max(ime, nodes[right(n)].inside_max_end);
223 } else {
224 // right child is imaginary; take the last border observation
225 ime = std::max(ime, right_border_ime);
226 }
227 assert(ime != Node::npos);
228 nodes[n].inside_max_end = ime;
229
230 if (n == right_border_nodes[lv]) {
231 // track inside_max_end of the real nodes on the border
232 right_border_ime = ime;
233 }
234 }
235 }
236 }
237 }
238
239 ~iit_base(void) {
240 nodes.munmap_file();
241 std::remove(backing_filename.c_str());
242 }
243
244 // overlap query; fill ans and return query cost (number of tree nodes visited)
245 virtual size_t overlap(Pos qbeg, Pos qend, std::vector<Item>& ans) const {
246 ans.clear();
247 return scan(root, qbeg, qend, ans);
248 }
249
250 // overlap query, return vector of results
251 std::vector<Item> overlap(Pos qbeg, Pos qend) const {
252 std::vector<Item> ans;
253 overlap(qbeg, qend, ans);
254 return ans;
255 }
256 };
257
258 // template for the builder class exposed by each user-facing class, which takes in items either
259 // all at once from InputIterator, or streaming one-by-one
260 template<class iitT, typename Item, typename Node>
261 class iit_builder_base {
262 mmappable_vector<Node> nodes_;
263
264 public:
265 iit_builder_base() = default;
266 template<typename InputIterator>
267 iit_builder_base(InputIterator begin, InputIterator end) {
268 add(begin, end);
269 }
270
271 void add(const Item& it) {
272 nodes_.push_back(Node(it));
273 }
274
275 template<typename InputIterator>
276 void add(InputIterator begin, InputIterator end) {
277 std::for_each(begin, end, [&](const Item& it) { add(it); });
278 }
279
280 template<typename... Args>
281 iitT build(Args&&... args) {
282 return iitT(nodes_, std::forward<Args>(args)...);
283 }
284 };
285
286 // template for the memory-mapped builder class exposed by each user-facing class, which takes in items either
287 // all at once from InputIterator, or streaming one-by-one
288 template<class iitT, typename Item, typename Node>
289 class iit_mm_builder_base {
290 //mmappable_vector<Node> nodes_;
291
292 int get_thread_count(void) {
293 int thread_count = 1;
294 #pragma omp parallel
295 {
296 #pragma omp master
297 thread_count = omp_get_num_threads();
298 }
299 return thread_count;
300 }
301
302 std::ofstream writer;
303 std::vector<std::ofstream> writers;
304 char* reader = nullptr;
305 int reader_fd = 0;
306 std::string filename;
307 std::string index_filename;
308 bool sorted = false;
309 // key information
310 uint64_t n_records = 0;
311 bool indexed = false;
312 uint32_t OUTPUT_VERSION = 1; // update as we change our format
313
314 public:
315 iit_mm_builder_base() = default;
316 template<typename InputIterator>
317 iit_mm_builder_base(const std::string& f, InputIterator begin, InputIterator end)
318 : filename(f) {
319 open_writers(f);
320 add(begin, end);
321 }
322
323 iit_mm_builder_base(const std::string& f) : filename(f) { open_writers(f); }
324
325 //~iit_mm_builder_base(void) { close_writers(); }
326
327 void set_base_filename(const std::string& f) {
328 filename = f;
329 }
330
331 // close/open backing file
332 void open_main_writer(void) {
333 if (writer.is_open()) {
334 writer.seekp(0, std::ios_base::end); // seek to the end for appending
335 return;
336 }
337 assert(!filename.empty());
338 writer.open(filename.c_str(), std::ios::binary | std::ios::trunc);
339 if (writer.fail()) {
340 throw std::ios_base::failure(std::strerror(errno));
341 }
342 }
343
344 // per-thread writers
345 void open_writers(const std::string& f) {
346 set_base_filename(f);
347 open_writers();
348 }
349
350 void open_writers(void) {
351 assert(!filename.empty());
352 writers.clear();
353 writers.resize(get_thread_count());
354 for (size_t i = 0; i < writers.size(); ++i) {
355 auto& writer = writers[i];
356 writer.open(writer_filename(i), std::ios::binary | std::ios::app);
357 if (writer.fail()) {
358 throw std::ios_base::failure(std::strerror(errno));
359 }
360 }
361 }
362
363 std::string writer_filename(size_t i) {
364 std::stringstream wf;
365 wf << filename << ".tmp_write" << "." << i;
366 return wf.str();
367 }
368
369 std::ofstream& get_writer(void) {
370 return writers[omp_get_thread_num()];
371 }
372
373 void sync_and_close_parallel_writers(void) {
374 // check to see if we ran single-threaded
375 uint64_t used_writers = 0;
376 uint64_t writer_that_wrote = 0;
377 for (size_t i = 0; i < writers.size(); ++i) {
378 writers[i].close();
379 if (filesize(writer_filename(i).c_str())) {
380 ++used_writers;
381 writer_that_wrote = i;
382 }
383 }
384 bool single_threaded = used_writers == 1;
385 // close the temp writers and cat them onto the end of the main file
386 if (single_threaded) {
387 std::rename(writer_filename(writer_that_wrote).c_str(), filename.c_str());
388 for (size_t i = 0; i < writers.size(); ++i) {
389 if (i != writer_that_wrote) {
390 std::remove(writer_filename(i).c_str());
391 }
392 }
393 } else {
394 open_main_writer();
395 for (size_t i = 0; i < writers.size(); ++i) {
396 std::ifstream if_w(writer_filename(i), std::ios_base::binary);
397 writer << if_w.rdbuf();
398 if_w.close();
399 std::remove(writer_filename(i).c_str());
400 }
401 }
402 writers.clear();
403 writer.close();
404 for (size_t i = 0; i < writers.size(); ++i) {
405 std::remove(writer_filename(i).c_str());
406 }
407 }
408
409 /// return the number of records, which will only work after indexing
410 size_t size(void) const {
411 return n_records;
412 }
413
414 /// return the backing buffer
415 char* get_buffer(void) const {
416 return reader;
417 }
418
419 /// get the record count
420 size_t record_count(void) {
421 int fd = open(filename.c_str(), O_RDWR);
422 if (fd == -1) {
423 assert(false);
424 }
425 struct stat stats;
426 if (-1 == fstat(fd, &stats)) {
427 assert(false);
428 }
429 assert(stats.st_size % sizeof(Node) == 0); // must be even records
430 size_t count = stats.st_size / sizeof(Node);
431 close(fd);
432 return count;
433 }
434
435 std::ifstream::pos_type filesize(const char* filename) {
436 std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
437 return in.tellg();
438 }
439
440 void add(const Item& it) {
441 auto v = Node(it);
442 auto& writer = get_writer();
443 writer.write((char*)&v, sizeof(Node));
444 }
445
446 template<typename InputIterator>
447 void add(InputIterator begin, InputIterator end) {
448 std::for_each(begin, end, [&](const Item& it) { add(it); });
449 }
450
451 template<typename... Args>
452 iitT build(Args&&... args) {
453 sync_and_close_parallel_writers();
454 mmappable_vector<Node> nodes_;
455 nodes_.mmap_file(filename.c_str(), READ_WRITE_SHARED, 0, record_count());
456 return iitT(nodes_, filename, std::forward<Args>(args)...);
457 }
458 };
459
460 // Basic implicit interval tree (a reimplementation of cgranges)
461 template<typename Pos, typename Item, Pos get_beg(const Item&), Pos get_end(const Item&)>
462 class iit : public iit_base<Pos, Item, iit_node_base<Pos, Item, get_beg, get_end>> {
463 using Node = iit_node_base<Pos, Item, get_beg, get_end>;
464
465 iit(mmappable_vector<Node>& nodes_, const std::string& file)
466 : iit_base<Pos, Item, Node>(nodes_, file)
467 {}
468
469 public:
470 using builder = iit_mm_builder_base<iit<Pos, Item, get_beg, get_end>, Item, Node>;
471 friend builder;
472 };
473
474
475 // iitii-specialized node type
476 template<typename Pos, typename Item, Pos get_beg(const Item&), Pos get_end(const Item&)>
477 struct iitii_node : public iit_node_base<Pos, Item, get_beg, get_end> {
478 // Additional augment values for iitii nodes, which help us know when we can stop climbing in
479 // the bottom-up search starting from a leaf to an ancestor node which must contain all query
480 // results beneath it.
481 //
482 // outside_max_end of node n is the maximum m.end() of all nodes m outside of n & its subtree
483 // with m.beg() < n.beg(); -infinity if there are no such nodes.
484 // outside_min_beg of node n is the minimum m.beg() of all nodes m outside of n & its subtree
485 // with m.beg() >= n.beg(); infinity if there are no such nodes.
486 //
487 // Suppose during a query for [qbeg, qend) we climb up to a node n with,
488 // (i) n.outside_max_end <= qbeg; AND
489 // (ii) qend <= n.outside_min_beg
490 // By (i), any node outside n & subtree with beg < n's cannot overlap the query. By (ii), any
491 // node outside n & subtree with beg >= n's cannot overlap the query. This exhausts all nodes
492 // outside of n & subtree, so we need not climb past n.
493 Pos outside_max_end;
494 Pos outside_min_beg;
495
496 iitii_node(const Item& item_)
497 : iit_node_base<Pos, Item, get_beg, get_end>(item_)
498 , outside_max_end(std::numeric_limits<Pos>::min())
499 , outside_min_beg(std::numeric_limits<Pos>::max())
500 {}
501 };
502
503 // simple linear regression of y ~ x given points [(x,y)], returning (intercept, slope)
504 template<typename XT, typename YT>
505 std::pair<double,double> regress(const std::vector<std::pair<XT,YT>>& points) {
506 if (points.empty()) {
507 return std::make_pair(std::numeric_limits<double>::quiet_NaN(),
508 std::numeric_limits<double>::quiet_NaN());
509 }
510 double sum_x, sum_y, cov, var;
511 sum_x = sum_y = cov = var = 0.0;
512 for (const auto& pt : points) {
513 sum_x += double(pt.first);
514 sum_y += double(pt.second);
515 }
516 const double mean_x = sum_x/points.size(), mean_y = sum_y/points.size();
517 for (const auto& pt : points) {
518 const double x_err = pt.first - mean_x;
519 cov += x_err*(pt.second - mean_y);
520 var += x_err*x_err;
521 }
522 if (var == 0.0) {
523 return std::make_pair(0.0, 0.0);
524 }
525 const double m = cov / var;
526 return std::make_pair(mean_y - m*mean_x, m);
527 }
528
529 template<typename XT, typename YT>
530 double mean_absolute_residual(const std::vector<std::pair<XT,YT>>& points, double b, double m) {
531 if (points.empty()) {
532 return std::numeric_limits<double>::quiet_NaN();
533 }
534 double sr = 0.0;
535 for (const auto& pt : points) {
536 double y = double(pt.second), fx = (m*double(pt.first)+b);
537 sr += y >= fx ? y-fx : fx-y;
538 }
539 return sr/points.size();
540 }
541
542 // here it is
543 template<typename Pos, typename Item, Pos get_beg(const Item&), Pos get_end(const Item&)>
544 class iitii : public iit_base<Pos, Item, iitii_node<Pos, Item, get_beg, get_end>> {
545 using Node = iitii_node<Pos, Item, get_beg, get_end>;
546 using super = iit_base<Pos, Item, Node>;
547 using typename super::Rank;
548 using typename super::Level;
549 using super::left;
550 using super::right;
551 using super::parent;
552 using super::nodes;
553 using super::full_size;
554 using super::nrank;
555 using super::level;
556 using super::root;
557 using super::root_level;
558
559
560 // Leaf prediction model: the (max_beg-min_beg) range is partitioned into a number of domains,
561 // each domain covering an equal-sized portion of that range. For each domain d we keep a
562 // linear model of leaf rank on beg position, rank ~ w[d,0] + w[d,1]*beg.
563 // Given query qbeg, selecting the domain and predicting the rank should take constant time.
564 // As a detail, the leaves are the even-ranked nodes, so we have the models predict rank/2 and
565 // then double the floored prediction.
566 // TODO: think about predicting internal nodes instead of leaves
567 unsigned domains;
568 Pos domain_size = Node::npos;
569 std::vector<float> weights; // domains*2
570 Pos min_beg = std::numeric_limits<Pos>::max();
571
572 inline unsigned which_domain(Pos beg) const {
573 if (beg < min_beg) {
574 return 0;
575 }
576 return std::min(domains-1, unsigned((beg-min_beg)/domain_size));
577 }
578
579 // Given qbeg, select domain and predict rank from the respective model
580 // TODO: try using middle of qbeg & qend, or generally "learn" the best offset
581 Rank predict_leaf(Pos qbeg) const {
582 auto which = which_domain(qbeg);
583 assert(which < domains);
584
585 float halfrank = weights[2*which] + weights[2*which+1]*float(qbeg);
586 if (!std::isfinite(halfrank)) {
587 return nrank;
588 }
589
590 Rank r = 2*Rank(std::max(0.0f,halfrank));
591 const auto nsz = nodes.size();
592 return r < nsz ? r : (nsz - (2 - nsz%2));
593 }
594
595 void train() {
596 std::vector<std::vector<std::pair<Pos,Rank>>> points;
597 points.resize(domains);
598 // partition all the nodes into their respective domains & record training points
599 for (Rank r = 0; r < nodes.size(); r+=2) {
600 points.at(which_domain(nodes[r].beg()))
601 .push_back(std::make_pair(nodes[r].beg(), r/2));
602 }
603 // train each domain-specific model
604 for (unsigned which = 0; which < domains; ++which) {
605 auto w = regress<Pos,Rank>(points[which]);
606 // Keep the model if the regression succeeded and the mean absolute residual from the
607 // training points is <= 2^(half of tree height). Otherwise we consider the bottom-up
608 // search counterproductive; leaving the respective weights at nan will cause overlap()
609 // to fall back to top-down search from the root.
610 if (std::isfinite(w.first) && std::isfinite(w.second) &&
611 mean_absolute_residual(points[which], w.first, w.second) <= double(1 << (root_level/2))) {
612 weights[2*which] = float(w.first);
613 weights[2*which+1] = float(w.second);
614 }
615 // std::cout << "which = " << which << " points = " << points[which].size()
616 // << " b = " << w.first << " m = " << w.second << std::endl;
617 }
618 }
619
620 inline Rank leftmost_child(Rank subtree) const {
621 Level k = level(subtree);
622 auto ofs = (Rank(1)<<k) - 1;
623 assert(subtree >= ofs);
624 return subtree - ofs;
625 }
626
627 inline Rank rightmost_child(Rank subtree) const {
628 Level k = level(subtree);
629 auto ofs = (Rank(1)<<k) - 1;
630 assert(subtree + ofs < full_size);
631 return subtree + ofs;
632 }
633
634 iitii(mmappable_vector<Node>& nodes_, const std::string& filename, unsigned domains_)
635 : super(nodes_, filename)
636 , domains(std::max(1U,domains_))
637 , domain_size(std::numeric_limits<Pos>::max())
638 {
639 weights.resize(domains*2, std::numeric_limits<float>::quiet_NaN());
640
641 if (nodes.size()) {
642 // equal size (in Pos units) of each domain
643 min_beg = nodes[0].beg();
644 domain_size = 1 + (nodes.back().beg()-min_beg)/domains;
645
646 // compute running max_end along the sorted array, which we'll look up while computing
647 // outside_max_end below
648 std::vector<Pos> running_max_end { nodes[0].end() };
649 for (Rank n = 1; n < nodes.size(); ++n) {
650 running_max_end.push_back(std::max(running_max_end[n-1], nodes[n].end()));
651 }
652
653 // Fill outside_min_beg and outside_max_end. Neatly, with the cgranges beg-sorted array
654 // and running_max_end, we can find each value independently in ~constant time.
655 // Precomputing them is still worthwhile for cache locality and dealing with corner
656 // cases arising from beg position collisions.
657 for (Rank n = 0; n < nodes.size(); ++n) {
658 Node& node = nodes[n];
659 Rank l = leftmost_child(n), r = rightmost_child(n);
660
661 // outside_min_beg is beg() of the node ranked one higher than n's rightmost child
662 node.outside_min_beg = r < nodes.size()-1 ? nodes[r+1].beg() : Node::npos;
663 if (l>0) {
664 if (nodes[l-1].beg() == node.beg()) {
665 // corner case: nodes to the left of n's subtree can have the same beg as n
666 // and outside_min_beg is defined on nodes with beg >= n's.
667 node.outside_min_beg = node.beg();
668 }
669
670 // outside_max_end is the running_max_end of the highest-ranked node ranked
671 // below n's leftmost child & has beg strictly below n's
672 Rank leq = l-1;
673 while (nodes[leq].beg() == node.beg()) {
674 if (leq == 0) {
675 break;
676 }
677 --leq;
678 }
679 assert(nodes[leq].beg() <= node.beg());
680 node.outside_max_end = nodes[leq].beg() < node.beg()
681 ? running_max_end[leq]
682 : std::numeric_limits<Pos>::min();
683 }
684
685 assert(node.outside_min_beg >= node.beg());
686 }
687
688 // train the rank prediction models
689 train();
690 }
691 }
692
693 public:
694 // iitii::builder::build() takes a size_t argument giving the number of domains to model
695 using builder = iit_mm_builder_base<iitii<Pos, Item, get_beg, get_end>, Item, Node>;
696 friend builder;
697
698 size_t overlap(Pos qbeg, Pos qend, std::vector<Item>& ans) const override {
699 // ask model which leaf we should begin our bottom-up climb at
700 Rank prediction = predict_leaf(qbeg);
701 if (prediction == nrank) {
702 // the model did not make a prediction for some reason, so just go to the root
703 return super::overlap(qbeg, qend, ans);
704 }
705 assert(level(prediction) == 0);
706
707 // climb until our necessary & sufficient criteria are met, or the root
708 size_t climb_cost = 0;
709 Rank subtree = prediction;
710 while (subtree != root && // stop at root
711 (subtree >= nodes.size() || // continue climb through imaginary
712 qbeg < nodes[subtree].outside_max_end || // possible outside overlap from left
713 nodes[subtree].outside_min_beg < qend)) { // possible outside overlap from right
714 subtree = parent(subtree);
715 // TODO: scheme to skip through chains of imaginary nodes along the border
716 ++climb_cost;
717 }
718
719 auto self = const_cast<iitii<Pos, Item, get_beg, get_end>*>(this); // getting around const
720 self->queries++;
721 self->total_climb_cost += climb_cost;
722
723 // scan the subtree for query results
724 ans.clear();
725 return super::scan(subtree, qbeg, qend, ans) + climb_cost;
726 }
727
728 size_t queries = 0;
729 size_t total_climb_cost = 0;
730
731 using super::overlap;
732 };
733
734 }