1 package jalview.datamodel.features;
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
9 * An adapted implementation of NCList as described in the paper
12 * Nested Containment List (NCList): a new algorithm for accelerating
13 * interval query of genome alignment and interval databases
14 * - Alexander V. Alekseyenko, Christopher J. Lee
15 * https://doi.org/10.1093/bioinformatics/btl647
18 public class NCList<T extends ContiguousI>
21 * the number of ranges represented
26 * a list, in start position order, of sublists of ranges ordered so
27 * that each contains (or is the same as) the one that follows it
29 private List<NCNode<T>> subranges;
32 * a comparator to sort intervals by start position ascending, with
33 * longer (enclosing) intervals preceding those they enclose
35 Comparator<ContiguousI> intervalSorter = new RangeComparator(true);
38 * Constructor given a list of things that are each located on a contiguous
39 * interval. Note that the constructor may reorder the list.
41 * We assume here that for each range, start <= end. Behaviour for reverse
42 * ordered ranges is undefined.
46 public NCList(List<T> ranges)
53 * Sort and group ranges into sublists where each sublist represents a region
54 * and its contained subregions
58 protected void build(List<T> ranges)
61 * sort by start ascending so that contained intervals
62 * follow their containing interval
64 Collections.sort(ranges, intervalSorter);
66 List<Range> sublists = buildSubranges(ranges);
69 * convert each subrange to an NCNode consisting of a range and
70 * (possibly) its contained NCList
72 for (Range sublist : sublists)
74 subranges.add(new NCNode<T>(ranges.subList(sublist.start,
81 public NCList(T entry)
84 subranges.add(new NCNode<T>(entry));
90 subranges = new ArrayList<NCNode<T>>();
94 * Traverses the sorted ranges to identify sublists, within which each
95 * interval contains the one that follows it
100 protected List<Range> buildSubranges(List<T> ranges)
102 List<Range> sublists = new ArrayList<Range>();
104 if (ranges.isEmpty())
109 int listStartIndex = 0;
110 long lastEndPos = Long.MAX_VALUE;
112 for (int i = 0; i < ranges.size(); i++)
114 ContiguousI nextInterval = ranges.get(i);
115 long nextStart = nextInterval.getBegin();
116 long nextEnd = nextInterval.getEnd();
117 if (nextStart > lastEndPos || nextEnd > lastEndPos)
120 * this interval is not contained in the preceding one
121 * close off the last sublist
123 sublists.add(new Range(listStartIndex, i - 1));
126 lastEndPos = nextEnd;
129 sublists.add(new Range(listStartIndex, ranges.size() - 1));
134 * Adds one entry to the stored set (with duplicates allowed)
138 public void add(T entry)
144 * Adds one entry to the stored set, and returns true, unless allowDuplicates
145 * is set to false and it is already contained (by object equality test), in
146 * which case it is not added and this method returns false.
149 * @param allowDuplicates
152 public synchronized boolean add(T entry, boolean allowDuplicates)
154 if (!allowDuplicates && contains(entry))
160 long start = entry.getBegin();
161 long end = entry.getEnd();
165 * - precedes all subranges: add as NCNode on front of list
166 * - follows all subranges: add as NCNode on end of list
167 * - enclosed by a subrange - add recursively to subrange
168 * - encloses one or more subranges - push them inside it
169 * - none of the above - add as a new node and resort nodes list (?)
173 * find the first subrange whose end does not precede entry's start
175 int candidateIndex = findFirstOverlap(start);
176 if (candidateIndex == -1)
179 * all subranges precede this one - add it on the end
181 subranges.add(new NCNode<T>(entry));
186 * search for maximal span of subranges i-k that the new entry
187 * encloses; or a subrange that encloses the new entry
189 boolean enclosing = false;
190 int firstEnclosed = 0;
191 int lastEnclosed = 0;
192 boolean overlapping = false;
194 for (int j = candidateIndex; j < subranges.size(); j++)
196 NCNode<T> subrange = subranges.get(j);
198 if (end < subrange.getBegin() && !overlapping && !enclosing)
201 * new entry lies between subranges j-1 j
203 subranges.add(j, new NCNode<T>(entry));
207 if (subrange.getBegin() <= start && subrange.getEnd() >= end)
210 * push new entry inside this subrange as it encloses it
216 if (start <= subrange.getBegin())
218 if (end >= subrange.getEnd())
221 * new entry encloses this subrange (and possibly preceding ones);
222 * continue to find the maximal list it encloses
235 * entry spans from before this subrange to inside it
240 * entry encloses one or more preceding subranges
242 addEnclosingRange(entry, firstEnclosed, lastEnclosed);
248 * entry spans two subranges but doesn't enclose any
251 subranges.add(j, new NCNode<T>(entry));
263 * drops through to here if new range encloses all others
264 * or overlaps the last one
268 addEnclosingRange(entry, firstEnclosed, lastEnclosed);
272 subranges.add(new NCNode<T>(entry));
279 * Answers true if this NCList contains the given entry (by object equality
285 public boolean contains(T entry)
288 * find the first sublist that might overlap, i.e.
289 * the first whose end position is >= from
291 int candidateIndex = findFirstOverlap(entry.getBegin());
293 if (candidateIndex == -1)
298 int to = entry.getEnd();
300 for (int i = candidateIndex; i < subranges.size(); i++)
302 NCNode<T> candidate = subranges.get(i);
303 if (candidate.getBegin() > to)
306 * we are past the end of our target range
310 if (candidate.contains(entry))
319 * Update the tree so that the range of the new entry encloses subranges i to
320 * j (inclusive). That is, replace subranges i-j (inclusive) with a new
321 * subrange that contains them.
327 protected synchronized void addEnclosingRange(T entry, final int i,
330 NCList<T> newNCList = new NCList<T>();
331 newNCList.addNodes(subranges.subList(i, j + 1));
332 NCNode<T> newNode = new NCNode<T>(entry, newNCList);
333 for (int k = j; k >= i; k--)
337 subranges.add(i, newNode);
340 protected void addNodes(List<NCNode<T>> nodes)
342 for (NCNode<T> node : nodes)
350 * Returns a (possibly empty) list of items whose extent overlaps the given
354 * start of overlap range (inclusive)
356 * end of overlap range (inclusive)
359 public List<T> findOverlaps(long from, long to)
361 List<T> result = new ArrayList<T>();
363 findOverlaps(from, to, result);
369 * Recursively searches the NCList adding any items that overlap the from-to
370 * range to the result list
376 protected void findOverlaps(long from, long to, List<T> result)
379 * find the first sublist that might overlap, i.e.
380 * the first whose end position is >= from
382 int candidateIndex = findFirstOverlap(from);
384 if (candidateIndex == -1)
389 for (int i = candidateIndex; i < subranges.size(); i++)
391 NCNode<T> candidate = subranges.get(i);
392 if (candidate.getBegin() > to)
395 * we are past the end of our target range
399 candidate.findOverlaps(from, to, result);
405 * Search subranges for the first one whose end position is not before the
406 * target range's start position, i.e. the first one that may overlap the
407 * target range. Returns the index in the list of the first such range found,
408 * or -1 if none found.
413 protected int findFirstOverlap(long from)
416 * The NCList paper describes binary search for this step,
417 * but this not implemented here as (a) I haven't understood it yet
418 * and (b) it seems to imply complications for adding to an NCList
422 if (subranges != null)
424 for (NCNode<T> subrange : subranges)
426 if (subrange.getEnd() >= from)
437 * Formats the tree as a bracketed list e.g.
440 * [1-100 [10-30 [10-20]], 15-30 [20-20]]
444 public String toString()
446 return subranges.toString();
450 * Returns a string representation of the data where containment is shown by
451 * indentation on new lines
455 public String prettyPrint()
457 StringBuilder sb = new StringBuilder(512);
460 prettyPrint(sb, offset, indent);
461 sb.append(System.lineSeparator());
462 return sb.toString();
470 void prettyPrint(StringBuilder sb, int offset, int indent)
472 boolean first = true;
473 for (NCNode<T> subrange : subranges)
477 sb.append(System.lineSeparator());
480 subrange.prettyPrint(sb, offset, indent);
485 * Answers true if the data held satisfy the rules of construction of an
486 * NCList, else false.
490 public boolean isValid()
492 return isValid(Integer.MIN_VALUE, Integer.MAX_VALUE);
496 * Answers true if the data held satisfy the rules of construction of an
497 * NCList bounded within the given start-end range, else false.
499 * Each subrange must lie within start-end (inclusive). Subranges must be
500 * ordered by start position ascending.
507 boolean isValid(final int start, final int end)
509 int lastStart = start;
510 for (NCNode<T> subrange : subranges)
512 if (subrange.getBegin() < lastStart)
514 System.err.println("error in NCList: range " + subrange.toString()
515 + " starts before " + lastStart);
518 if (subrange.getEnd() > end)
520 System.err.println("error in NCList: range " + subrange.toString()
521 + " ends after " + end);
524 lastStart = subrange.getBegin();
526 if (!subrange.isValid())
535 * Answers the lowest start position enclosed by the ranges
539 public int getStart()
541 return subranges.isEmpty() ? 0 : subranges.get(0).getBegin();
545 * Returns the number of ranges held (deep count)
555 * Returns a list of all entries stored
559 public List<T> getEntries()
561 List<T> result = new ArrayList<T>();
567 * Adds all contained entries to the given list
571 void getEntries(List<T> result)
573 for (NCNode<T> subrange : subranges)
575 subrange.getEntries(result);
580 * Deletes the given entry from the store, returning true if it was found (and
581 * deleted), else false. This method makes no assumption that the entry is in
582 * the 'expected' place in the store, in case it has been modified since it
583 * was added. Only the first 'same object' match is deleted, not 'equal' or
588 public synchronized boolean delete(T entry)
594 for (int i = 0; i < subranges.size(); i++)
596 NCNode<T> subrange = subranges.get(i);
597 NCList<T> subRegions = subrange.getSubRegions();
599 if (subrange.getRegion() == entry)
602 * if the subrange is rooted on this entry, promote its
603 * subregions (if any) to replace the subrange here;
604 * NB have to resort subranges after doing this since e.g.
605 * [10-30 [12-20 [16-18], 13-19]]
606 * after deleting 12-20, 16-18 is promoted to sibling of 13-19
607 * but should follow it in the list of subranges of 10-30
610 if (subRegions != null)
612 subranges.addAll(subRegions.subranges);
613 Collections.sort(subranges, intervalSorter);
620 if (subRegions != null && subRegions.delete(entry))
623 subrange.deleteSubRegionsIfEmpty();