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)
55 protected void build(List<T> ranges)
58 * sort by start ascending so that contained intervals
59 * follow their containing interval
61 Collections.sort(ranges, intervalSorter);
63 List<SubList> sublists = buildSubranges(ranges);
66 * convert each subrange to an NCNode consisting of a range and
67 * (possibly) its contained NCList
69 for (SubList sublist : sublists)
71 subranges.add(new NCNode<T>(ranges.subList(sublist.startIndex,
72 sublist.endIndex + 1)));
78 public NCList(T entry)
81 List<T> ranges = new ArrayList<T>();
88 subranges = new ArrayList<NCNode<T>>();
92 * Traverses the sorted ranges to identify sublists, within which each
93 * interval contains the one that follows it
98 protected List<SubList> buildSubranges(List<T> ranges)
100 List<SubList> sublists = new ArrayList<SubList>();
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 SubList(listStartIndex, i - 1));
119 lastEndPos = nextEnd;
122 sublists.add(new SubList(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.getStart() && !overlapping && !enclosing)
194 * new entry lies between subranges j-1 j
196 subranges.add(j, new NCNode<T>(entry));
200 if (subrange.getStart() <= start && subrange.getEnd() >= end)
203 * push new entry inside this subrange as it encloses it
209 if (start <= subrange.getStart())
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.getStart() > 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.subranges.addAll(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);
334 * Returns a (possibly empty) list of items whose extent overlaps the given
338 * start of overlap range (inclusive)
340 * end of overlap range (inclusive)
343 public List<T> findOverlaps(long from, long to)
345 List<T> result = new ArrayList<T>();
347 findOverlaps(from, to, result);
353 * Recursively searches the NCList adding any items that overlap the from-to
354 * range to the result list
360 protected void findOverlaps(long from, long to, List<T> result)
363 * find the first sublist that might overlap, i.e.
364 * the first whose end position is >= from
366 int candidateIndex = findFirstOverlap(from);
368 if (candidateIndex == -1)
373 for (int i = candidateIndex; i < subranges.size(); i++)
375 NCNode<T> candidate = subranges.get(i);
376 if (candidate.getStart() > to)
379 * we are past the end of our target range
383 candidate.findOverlaps(from, to, result);
389 * Search subranges for the first one whose end position is not before the
390 * target range's start position, i.e. the first one that may overlap the
391 * target range. Returns the index in the list of the first such range found,
392 * or -1 if none found.
397 protected int findFirstOverlap(long from)
399 // TODO binary search
400 // for now quick cheat linear search
402 if (subranges != null)
404 for (NCNode<T> subrange : subranges)
406 if (subrange.getEnd() >= from)
417 * Formats the tree as a bracketed list e.g.
420 * [1-100 [10-30 [10-20]], 15-30 [20-20]]
424 public String toString()
426 return subranges.toString();
430 * Returns a string representation of the data where containment is shown bgy
431 * indentation on new lines
435 public String prettyPrint()
437 StringBuilder sb = new StringBuilder(512);
440 prettyPrint(sb, offset, indent);
441 return sb.toString();
449 void prettyPrint(StringBuilder sb, int offset, int indent)
451 boolean first = true;
452 for (NCNode<T> subrange : subranges)
456 sb.append(System.lineSeparator());
459 subrange.prettyPrint(sb, offset, indent);
464 * Answers true if the data held satisfy the rules of construction of an
465 * NCList, else false.
469 public boolean isValid()
471 return isValid(Integer.MIN_VALUE, Integer.MAX_VALUE);
475 * Answers true if the data held satisfy the rules of construction of an
476 * NCList bounded within the given start-end range, else false.
478 * Each subrange must lie within start-end (inclusive). Subranges must be
479 * ordered by start position ascending.
486 boolean isValid(final int start, final int end)
488 int lastStart = start;
489 for (NCNode<T> subrange : subranges)
491 if (subrange.getStart() < lastStart)
493 System.err.println("error in NCList: range " + subrange.toString()
494 + " starts before " + lastStart);
497 if (subrange.getEnd() > end)
499 System.err.println("error in NCList: range " + subrange.toString()
500 + " ends after " + end);
503 lastStart = subrange.getStart();
505 if (!subrange.isValid())
514 * Answers the lowest start position enclosed by the ranges
518 public int getStart()
520 return subranges.isEmpty() ? 0 : subranges.get(0).getStart();
524 * Returns the number of ranges held (deep count)
534 * Returns a list of all entries stored
538 public List<T> getEntries()
540 List<T> result = new ArrayList<T>();
546 * Adds all contained entries to the given list
550 void getEntries(List<T> result)
552 for (NCNode<T> subrange : subranges)
554 subrange.getEntries(result);
559 * Deletes the given entry from the store, returning true if it was found (and
560 * deleted), else false. This method makes no assumption that the entry is in
561 * the 'expected' place in the store, in case it has been modified since it
562 * was added. Only the first 'same object' match is deleted, not 'equal' or
567 public synchronized boolean delete(T entry)
573 for (int i = 0; i < subranges.size(); i++)
575 NCNode<T> subrange = subranges.get(i);
576 NCList<T> subRegions = subrange.getSubRegions();
578 if (subrange.getRegion() == entry)
581 * if the subrange is rooted on this entry, promote its
582 * subregions (if any) to replace the subrange here
585 if (subRegions != null)
587 subranges.addAll(i, subRegions.subranges);
594 if (subRegions != null && subRegions.delete(entry))
605 * Answers true if this contains no ranges
609 public boolean isEmpty()
611 return getSize() == 0;
615 * Answer the list of subranges held in this NCList
619 List<NCNode<T>> getSubregions()