1 package jalview.datamodel.features;
3 import java.util.ArrayList;
4 import java.util.Collections;
8 * An adapted implementation of NCList as described in the paper
11 * Nested Containment List (NCList): a new algorithm for accelerating
12 * interval query of genome alignment and interval databases
13 * - Alexander V. Alekseyenko, Christopher J. Lee
14 * https://doi.org/10.1093/bioinformatics/btl647
17 public class NCList<T extends ContiguousI>
20 * the number of ranges represented
25 * a list, in start position order, of sublists of ranges ordered so
26 * that each contains (or is the same as) the one that follows it
28 private List<NCNode<T>> subranges;
31 * Constructor given a list of things that are each located on a contiguous
32 * interval. Note that the constructor may reorder the list.
34 * We assume here that for each range, start <= end. Behaviour for reverse
35 * ordered ranges is undefined.
39 public NCList(List<T> ranges)
46 * Sort and group ranges into sublists where each sublist represents a region
47 * and its contained subregions
51 protected void build(List<T> ranges)
54 * sort by start ascending so that contained intervals
55 * follow their containing interval
57 Collections.sort(ranges, RangeComparator.BY_START_POSITION);
59 List<Range> sublists = buildSubranges(ranges);
62 * convert each subrange to an NCNode consisting of a range and
63 * (possibly) its contained NCList
65 for (Range sublist : sublists)
67 subranges.add(new NCNode<T>(ranges.subList(sublist.start,
74 public NCList(T entry)
77 subranges.add(new NCNode<T>(entry));
83 subranges = new ArrayList<NCNode<T>>();
87 * Traverses the sorted ranges to identify sublists, within which each
88 * interval contains the one that follows it
93 protected List<Range> buildSubranges(List<T> ranges)
95 List<Range> sublists = new ArrayList<Range>();
102 int listStartIndex = 0;
103 long lastEndPos = Long.MAX_VALUE;
105 for (int i = 0; i < ranges.size(); i++)
107 ContiguousI nextInterval = ranges.get(i);
108 long nextStart = nextInterval.getBegin();
109 long nextEnd = nextInterval.getEnd();
110 if (nextStart > lastEndPos || nextEnd > lastEndPos)
113 * this interval is not contained in the preceding one
114 * close off the last sublist
116 sublists.add(new Range(listStartIndex, i - 1));
119 lastEndPos = nextEnd;
122 sublists.add(new Range(listStartIndex, ranges.size() - 1));
127 * Adds one entry to the stored set (with duplicates allowed)
131 public void add(T entry)
137 * Adds one entry to the stored set, and returns true, unless allowDuplicates
138 * is set to false and it is already contained (by object equality test), in
139 * which case it is not added and this method returns false.
142 * @param allowDuplicates
145 public synchronized boolean add(T entry, boolean allowDuplicates)
147 if (!allowDuplicates && contains(entry))
153 long start = entry.getBegin();
154 long end = entry.getEnd();
158 * - precedes all subranges: add as NCNode on front of list
159 * - follows all subranges: add as NCNode on end of list
160 * - enclosed by a subrange - add recursively to subrange
161 * - encloses one or more subranges - push them inside it
162 * - none of the above - add as a new node and resort nodes list (?)
166 * find the first subrange whose end does not precede entry's start
168 int candidateIndex = findFirstOverlap(start);
169 if (candidateIndex == -1)
172 * all subranges precede this one - add it on the end
174 subranges.add(new NCNode<T>(entry));
179 * search for maximal span of subranges i-k that the new entry
180 * encloses; or a subrange that encloses the new entry
182 boolean enclosing = false;
183 int firstEnclosed = 0;
184 int lastEnclosed = 0;
185 boolean overlapping = false;
187 for (int j = candidateIndex; j < subranges.size(); j++)
189 NCNode<T> subrange = subranges.get(j);
191 if (end < subrange.getBegin() && !overlapping && !enclosing)
194 * new entry lies between subranges j-1 j
196 subranges.add(j, new NCNode<T>(entry));
200 if (subrange.getBegin() <= start && subrange.getEnd() >= end)
203 * push new entry inside this subrange as it encloses it
209 if (start <= subrange.getBegin())
211 if (end >= subrange.getEnd())
214 * new entry encloses this subrange (and possibly preceding ones);
215 * continue to find the maximal list it encloses
228 * entry spans from before this subrange to inside it
233 * entry encloses one or more preceding subranges
235 addEnclosingRange(entry, firstEnclosed, lastEnclosed);
241 * entry spans two subranges but doesn't enclose any
244 subranges.add(j, new NCNode<T>(entry));
256 * drops through to here if new range encloses all others
257 * or overlaps the last one
261 addEnclosingRange(entry, firstEnclosed, lastEnclosed);
265 subranges.add(new NCNode<T>(entry));
272 * Answers true if this NCList contains the given entry (by object equality
278 public boolean contains(T entry)
281 * find the first sublist that might overlap, i.e.
282 * the first whose end position is >= from
284 int candidateIndex = findFirstOverlap(entry.getBegin());
286 if (candidateIndex == -1)
291 int to = entry.getEnd();
293 for (int i = candidateIndex; i < subranges.size(); i++)
295 NCNode<T> candidate = subranges.get(i);
296 if (candidate.getBegin() > to)
299 * we are past the end of our target range
303 if (candidate.contains(entry))
312 * Update the tree so that the range of the new entry encloses subranges i to
313 * j (inclusive). That is, replace subranges i-j (inclusive) with a new
314 * subrange that contains them.
320 protected synchronized void addEnclosingRange(T entry, final int i,
323 NCList<T> newNCList = new NCList<T>();
324 newNCList.addNodes(subranges.subList(i, j + 1));
325 NCNode<T> newNode = new NCNode<T>(entry, newNCList);
326 for (int k = j; k >= i; k--)
330 subranges.add(i, newNode);
333 protected void addNodes(List<NCNode<T>> nodes)
335 for (NCNode<T> node : nodes)
343 * Returns a (possibly empty) list of items whose extent overlaps the given
347 * start of overlap range (inclusive)
349 * end of overlap range (inclusive)
352 public List<T> findOverlaps(long from, long to)
354 List<T> result = new ArrayList<T>();
356 findOverlaps(from, to, result);
362 * Recursively searches the NCList adding any items that overlap the from-to
363 * range to the result list
369 protected void findOverlaps(long from, long to, List<T> result)
372 * find the first sublist that might overlap, i.e.
373 * the first whose end position is >= from
375 int candidateIndex = findFirstOverlap(from);
377 if (candidateIndex == -1)
382 for (int i = candidateIndex; i < subranges.size(); i++)
384 NCNode<T> candidate = subranges.get(i);
385 if (candidate.getBegin() > to)
388 * we are past the end of our target range
392 candidate.findOverlaps(from, to, result);
398 * Search subranges for the first one whose end position is not before the
399 * target range's start position, i.e. the first one that may overlap the
400 * target range. Returns the index in the list of the first such range found,
401 * or -1 if none found.
406 protected int findFirstOverlap(long from)
409 * The NCList paper describes binary search for this step,
410 * but this not implemented here as (a) I haven't understood it yet
411 * and (b) it seems to imply complications for adding to an NCList
415 if (subranges != null)
417 for (NCNode<T> subrange : subranges)
419 if (subrange.getEnd() >= from)
430 * Formats the tree as a bracketed list e.g.
433 * [1-100 [10-30 [10-20]], 15-30 [20-20]]
437 public String toString()
439 return subranges.toString();
443 * Returns a string representation of the data where containment is shown by
444 * indentation on new lines
448 public String prettyPrint()
450 StringBuilder sb = new StringBuilder(512);
453 prettyPrint(sb, offset, indent);
454 sb.append(System.lineSeparator());
455 return sb.toString();
463 void prettyPrint(StringBuilder sb, int offset, int indent)
465 boolean first = true;
466 for (NCNode<T> subrange : subranges)
470 sb.append(System.lineSeparator());
473 subrange.prettyPrint(sb, offset, indent);
478 * Answers true if the data held satisfy the rules of construction of an
479 * NCList, else false.
483 public boolean isValid()
485 return isValid(Integer.MIN_VALUE, Integer.MAX_VALUE);
489 * Answers true if the data held satisfy the rules of construction of an
490 * NCList bounded within the given start-end range, else false.
492 * Each subrange must lie within start-end (inclusive). Subranges must be
493 * ordered by start position ascending.
500 boolean isValid(final int start, final int end)
502 int lastStart = start;
503 for (NCNode<T> subrange : subranges)
505 if (subrange.getBegin() < lastStart)
507 System.err.println("error in NCList: range " + subrange.toString()
508 + " starts before " + lastStart);
511 if (subrange.getEnd() > end)
513 System.err.println("error in NCList: range " + subrange.toString()
514 + " ends after " + end);
517 lastStart = subrange.getBegin();
519 if (!subrange.isValid())
528 * Answers the lowest start position enclosed by the ranges
532 public int getStart()
534 return subranges.isEmpty() ? 0 : subranges.get(0).getBegin();
538 * Returns the number of ranges held (deep count)
548 * Returns a list of all entries stored
552 public List<T> getEntries()
554 List<T> result = new ArrayList<T>();
560 * Adds all contained entries to the given list
564 void getEntries(List<T> result)
566 for (NCNode<T> subrange : subranges)
568 subrange.getEntries(result);
573 * Deletes the given entry from the store, returning true if it was found (and
574 * deleted), else false. This method makes no assumption that the entry is in
575 * the 'expected' place in the store, in case it has been modified since it
576 * was added. Only the first 'same object' match is deleted, not 'equal' or
581 public synchronized boolean delete(T entry)
587 for (int i = 0; i < subranges.size(); i++)
589 NCNode<T> subrange = subranges.get(i);
590 NCList<T> subRegions = subrange.getSubRegions();
592 if (subrange.getRegion() == entry)
595 * if the subrange is rooted on this entry, promote its
596 * subregions (if any) to replace the subrange here;
597 * NB have to resort subranges after doing this since e.g.
598 * [10-30 [12-20 [16-18], 13-19]]
599 * after deleting 12-20, 16-18 is promoted to sibling of 13-19
600 * but should follow it in the list of subranges of 10-30
603 if (subRegions != null)
605 subranges.addAll(subRegions.subranges);
606 Collections.sort(subranges, RangeComparator.BY_START_POSITION);
613 if (subRegions != null && subRegions.delete(entry))
616 subrange.deleteSubRegionsIfEmpty();