JAL-3725 helper methods for computing mapped feature range overlap
[jalview.git] / src / jalview / util / MappingUtils.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.util;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29
30 import jalview.analysis.AlignmentSorter;
31 import jalview.api.AlignViewportI;
32 import jalview.bin.Cache;
33 import jalview.commands.CommandI;
34 import jalview.commands.EditCommand;
35 import jalview.commands.EditCommand.Action;
36 import jalview.commands.EditCommand.Edit;
37 import jalview.commands.OrderCommand;
38 import jalview.datamodel.AlignedCodonFrame;
39 import jalview.datamodel.AlignmentI;
40 import jalview.datamodel.AlignmentOrder;
41 import jalview.datamodel.ColumnSelection;
42 import jalview.datamodel.HiddenColumns;
43 import jalview.datamodel.SearchResultMatchI;
44 import jalview.datamodel.SearchResults;
45 import jalview.datamodel.SearchResultsI;
46 import jalview.datamodel.Sequence;
47 import jalview.datamodel.SequenceGroup;
48 import jalview.datamodel.SequenceI;
49
50 /**
51  * Helper methods for manipulations involving sequence mappings.
52  * 
53  * @author gmcarstairs
54  *
55  */
56 public final class MappingUtils
57 {
58
59   /**
60    * Helper method to map a CUT or PASTE command.
61    * 
62    * @param edit
63    *          the original command
64    * @param undo
65    *          if true, the command is to be undone
66    * @param targetSeqs
67    *          the mapped sequences to apply the mapped command to
68    * @param result
69    *          the mapped EditCommand to add to
70    * @param mappings
71    */
72   protected static void mapCutOrPaste(Edit edit, boolean undo,
73           List<SequenceI> targetSeqs, EditCommand result,
74           List<AlignedCodonFrame> mappings)
75   {
76     Action action = edit.getAction();
77     if (undo)
78     {
79       action = action.getUndoAction();
80     }
81     // TODO write this
82     Cache.log.error("MappingUtils.mapCutOrPaste not yet implemented");
83   }
84
85   /**
86    * Returns a new EditCommand representing the given command as mapped to the
87    * given sequences. If there is no mapping, returns null.
88    * 
89    * @param command
90    * @param undo
91    * @param mapTo
92    * @param gapChar
93    * @param mappings
94    * @return
95    */
96   public static EditCommand mapEditCommand(EditCommand command,
97           boolean undo, final AlignmentI mapTo, char gapChar,
98           List<AlignedCodonFrame> mappings)
99   {
100     /*
101      * For now, only support mapping from protein edits to cDna
102      */
103     if (!mapTo.isNucleotide())
104     {
105       return null;
106     }
107
108     /*
109      * Cache a copy of the target sequences so we can mimic successive edits on
110      * them. This lets us compute mappings for all edits in the set.
111      */
112     Map<SequenceI, SequenceI> targetCopies = new HashMap<>();
113     for (SequenceI seq : mapTo.getSequences())
114     {
115       SequenceI ds = seq.getDatasetSequence();
116       if (ds != null)
117       {
118         final SequenceI copy = new Sequence(seq);
119         copy.setDatasetSequence(ds);
120         targetCopies.put(ds, copy);
121       }
122     }
123
124     /*
125      * Compute 'source' sequences as they were before applying edits:
126      */
127     Map<SequenceI, SequenceI> originalSequences = command.priorState(undo);
128
129     EditCommand result = new EditCommand();
130     Iterator<Edit> edits = command.getEditIterator(!undo);
131     while (edits.hasNext())
132     {
133       Edit edit = edits.next();
134       if (edit.getAction() == Action.CUT
135               || edit.getAction() == Action.PASTE)
136       {
137         mapCutOrPaste(edit, undo, mapTo.getSequences(), result, mappings);
138       }
139       else if (edit.getAction() == Action.INSERT_GAP
140               || edit.getAction() == Action.DELETE_GAP)
141       {
142         mapInsertOrDelete(edit, undo, originalSequences,
143                 mapTo.getSequences(), targetCopies, gapChar, result,
144                 mappings);
145       }
146     }
147     return result.getSize() > 0 ? result : null;
148   }
149
150   /**
151    * Helper method to map an edit command to insert or delete gaps.
152    * 
153    * @param edit
154    *          the original command
155    * @param undo
156    *          if true, the action is to undo the command
157    * @param originalSequences
158    *          the sequences the command acted on
159    * @param targetSeqs
160    * @param targetCopies
161    * @param gapChar
162    * @param result
163    *          the new EditCommand to add mapped commands to
164    * @param mappings
165    */
166   protected static void mapInsertOrDelete(Edit edit, boolean undo,
167           Map<SequenceI, SequenceI> originalSequences,
168           final List<SequenceI> targetSeqs,
169           Map<SequenceI, SequenceI> targetCopies, char gapChar,
170           EditCommand result, List<AlignedCodonFrame> mappings)
171   {
172     Action action = edit.getAction();
173
174     /*
175      * Invert sense of action if an Undo.
176      */
177     if (undo)
178     {
179       action = action.getUndoAction();
180     }
181     final int count = edit.getNumber();
182     final int editPos = edit.getPosition();
183     for (SequenceI seq : edit.getSequences())
184     {
185       /*
186        * Get residue position at (or to right of) edit location. Note we use our
187        * 'copy' of the sequence before editing for this.
188        */
189       SequenceI ds = seq.getDatasetSequence();
190       if (ds == null)
191       {
192         continue;
193       }
194       final SequenceI actedOn = originalSequences.get(ds);
195       final int seqpos = actedOn.findPosition(editPos);
196
197       /*
198        * Determine all mappings from this position to mapped sequences.
199        */
200       SearchResultsI sr = buildSearchResults(seq, seqpos, mappings);
201
202       if (!sr.isEmpty())
203       {
204         for (SequenceI targetSeq : targetSeqs)
205         {
206           ds = targetSeq.getDatasetSequence();
207           if (ds == null)
208           {
209             continue;
210           }
211           SequenceI copyTarget = targetCopies.get(ds);
212           final int[] match = sr.getResults(copyTarget, 0,
213                   copyTarget.getLength());
214           if (match != null)
215           {
216             final int ratio = 3; // TODO: compute this - how?
217             final int mappedCount = count * ratio;
218
219             /*
220              * Shift Delete start position left, as it acts on positions to its
221              * right.
222              */
223             int mappedEditPos = action == Action.DELETE_GAP
224                     ? match[0] - mappedCount
225                     : match[0];
226             Edit e = result.new Edit(action, new SequenceI[] { targetSeq },
227                     mappedEditPos, mappedCount, gapChar);
228             result.addEdit(e);
229
230             /*
231              * and 'apply' the edit to our copy of its target sequence
232              */
233             if (action == Action.INSERT_GAP)
234             {
235               copyTarget.setSequence(new String(
236                       StringUtils.insertCharAt(copyTarget.getSequence(),
237                               mappedEditPos, mappedCount, gapChar)));
238             }
239             else if (action == Action.DELETE_GAP)
240             {
241               copyTarget.setSequence(new String(
242                       StringUtils.deleteChars(copyTarget.getSequence(),
243                               mappedEditPos, mappedEditPos + mappedCount)));
244             }
245           }
246         }
247       }
248       /*
249        * and 'apply' the edit to our copy of its source sequence
250        */
251       if (action == Action.INSERT_GAP)
252       {
253         actedOn.setSequence(new String(StringUtils.insertCharAt(
254                 actedOn.getSequence(), editPos, count, gapChar)));
255       }
256       else if (action == Action.DELETE_GAP)
257       {
258         actedOn.setSequence(new String(StringUtils.deleteChars(
259                 actedOn.getSequence(), editPos, editPos + count)));
260       }
261     }
262   }
263
264   /**
265    * Returns a SearchResults object describing the mapped region corresponding
266    * to the specified sequence position.
267    * 
268    * @param seq
269    * @param index
270    * @param seqmappings
271    * @return
272    */
273   public static SearchResultsI buildSearchResults(SequenceI seq, int index,
274           List<AlignedCodonFrame> seqmappings)
275   {
276     SearchResultsI results = new SearchResults();
277     addSearchResults(results, seq, index, seqmappings);
278     return results;
279   }
280
281   /**
282    * Adds entries to a SearchResults object describing the mapped region
283    * corresponding to the specified sequence position.
284    * 
285    * @param results
286    * @param seq
287    * @param index
288    * @param seqmappings
289    */
290   public static void addSearchResults(SearchResultsI results, SequenceI seq,
291           int index, List<AlignedCodonFrame> seqmappings)
292   {
293     if (index >= seq.getStart() && index <= seq.getEnd())
294     {
295       for (AlignedCodonFrame acf : seqmappings)
296       {
297         acf.markMappedRegion(seq, index, results);
298       }
299     }
300   }
301
302   /**
303    * Returns a (possibly empty) SequenceGroup containing any sequences in the
304    * mapped viewport corresponding to the given group in the source viewport.
305    * 
306    * @param sg
307    * @param mapFrom
308    * @param mapTo
309    * @return
310    */
311   public static SequenceGroup mapSequenceGroup(final SequenceGroup sg,
312           final AlignViewportI mapFrom, final AlignViewportI mapTo)
313   {
314     /*
315      * Note the SequenceGroup holds aligned sequences, the mappings hold dataset
316      * sequences.
317      */
318     boolean targetIsNucleotide = mapTo.isNucleotide();
319     AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
320     List<AlignedCodonFrame> codonFrames = protein.getAlignment()
321             .getCodonFrames();
322     /*
323      * Copy group name, colours etc, but not sequences or sequence colour scheme
324      */
325     SequenceGroup mappedGroup = new SequenceGroup(sg);
326     mappedGroup.setColourScheme(mapTo.getGlobalColourScheme());
327     mappedGroup.clear();
328
329     int minStartCol = -1;
330     int maxEndCol = -1;
331     final int selectionStartRes = sg.getStartRes();
332     final int selectionEndRes = sg.getEndRes();
333     for (SequenceI selected : sg.getSequences())
334     {
335       /*
336        * Find the widest range of non-gapped positions in the selection range
337        */
338       int firstUngappedPos = selectionStartRes;
339       while (firstUngappedPos <= selectionEndRes
340               && Comparison.isGap(selected.getCharAt(firstUngappedPos)))
341       {
342         firstUngappedPos++;
343       }
344
345       /*
346        * If this sequence is only gaps in the selected range, skip it
347        */
348       if (firstUngappedPos > selectionEndRes)
349       {
350         continue;
351       }
352
353       int lastUngappedPos = selectionEndRes;
354       while (lastUngappedPos >= selectionStartRes
355               && Comparison.isGap(selected.getCharAt(lastUngappedPos)))
356       {
357         lastUngappedPos--;
358       }
359
360       /*
361        * Find the selected start/end residue positions in sequence
362        */
363       int startResiduePos = selected.findPosition(firstUngappedPos);
364       int endResiduePos = selected.findPosition(lastUngappedPos);
365
366       for (AlignedCodonFrame acf : codonFrames)
367       {
368         SequenceI mappedSequence = targetIsNucleotide
369                 ? acf.getDnaForAaSeq(selected)
370                 : acf.getAaForDnaSeq(selected);
371         if (mappedSequence != null)
372         {
373           for (SequenceI seq : mapTo.getAlignment().getSequences())
374           {
375             int mappedStartResidue = 0;
376             int mappedEndResidue = 0;
377             if (seq.getDatasetSequence() == mappedSequence)
378             {
379               /*
380                * Found a sequence mapping. Locate the start/end mapped residues.
381                */
382               List<AlignedCodonFrame> mapping = Arrays
383                       .asList(new AlignedCodonFrame[]
384                       { acf });
385               SearchResultsI sr = buildSearchResults(selected,
386                       startResiduePos, mapping);
387               for (SearchResultMatchI m : sr.getResults())
388               {
389                 mappedStartResidue = m.getStart();
390                 mappedEndResidue = m.getEnd();
391               }
392               sr = buildSearchResults(selected, endResiduePos, mapping);
393               for (SearchResultMatchI m : sr.getResults())
394               {
395                 mappedStartResidue = Math.min(mappedStartResidue,
396                         m.getStart());
397                 mappedEndResidue = Math.max(mappedEndResidue, m.getEnd());
398               }
399
400               /*
401                * Find the mapped aligned columns, save the range. Note findIndex
402                * returns a base 1 position, SequenceGroup uses base 0
403                */
404               int mappedStartCol = seq.findIndex(mappedStartResidue) - 1;
405               minStartCol = minStartCol == -1 ? mappedStartCol
406                       : Math.min(minStartCol, mappedStartCol);
407               int mappedEndCol = seq.findIndex(mappedEndResidue) - 1;
408               maxEndCol = maxEndCol == -1 ? mappedEndCol
409                       : Math.max(maxEndCol, mappedEndCol);
410               mappedGroup.addSequence(seq, false);
411               break;
412             }
413           }
414         }
415       }
416     }
417     mappedGroup.setStartRes(minStartCol < 0 ? 0 : minStartCol);
418     mappedGroup.setEndRes(maxEndCol < 0 ? 0 : maxEndCol);
419     return mappedGroup;
420   }
421
422   /**
423    * Returns an OrderCommand equivalent to the given one, but acting on mapped
424    * sequences as described by the mappings, or null if no mapping can be made.
425    * 
426    * @param command
427    *          the original order command
428    * @param undo
429    *          if true, the action is to undo the sort
430    * @param mapTo
431    *          the alignment we are mapping to
432    * @param mappings
433    *          the mappings available
434    * @return
435    */
436   public static CommandI mapOrderCommand(OrderCommand command, boolean undo,
437           AlignmentI mapTo, List<AlignedCodonFrame> mappings)
438   {
439     SequenceI[] sortOrder = command.getSequenceOrder(undo);
440     List<SequenceI> mappedOrder = new ArrayList<>();
441     int j = 0;
442
443     /*
444      * Assumption: we are only interested in a cDNA/protein mapping; refactor in
445      * future if we want to support sorting (c)dna as (c)dna or protein as
446      * protein
447      */
448     boolean mappingToNucleotide = mapTo.isNucleotide();
449     for (SequenceI seq : sortOrder)
450     {
451       for (AlignedCodonFrame acf : mappings)
452       {
453         SequenceI mappedSeq = mappingToNucleotide ? acf.getDnaForAaSeq(seq)
454                 : acf.getAaForDnaSeq(seq);
455         if (mappedSeq != null)
456         {
457           for (SequenceI seq2 : mapTo.getSequences())
458           {
459             if (seq2.getDatasetSequence() == mappedSeq)
460             {
461               mappedOrder.add(seq2);
462               j++;
463               break;
464             }
465           }
466         }
467       }
468     }
469
470     /*
471      * Return null if no mappings made.
472      */
473     if (j == 0)
474     {
475       return null;
476     }
477
478     /*
479      * Add any unmapped sequences on the end of the sort in their original
480      * ordering.
481      */
482     if (j < mapTo.getHeight())
483     {
484       for (SequenceI seq : mapTo.getSequences())
485       {
486         if (!mappedOrder.contains(seq))
487         {
488           mappedOrder.add(seq);
489         }
490       }
491     }
492
493     /*
494      * Have to sort the sequences before constructing the OrderCommand - which
495      * then resorts them?!?
496      */
497     final SequenceI[] mappedOrderArray = mappedOrder
498             .toArray(new SequenceI[mappedOrder.size()]);
499     SequenceI[] oldOrder = mapTo.getSequencesArray();
500     AlignmentSorter.sortBy(mapTo, new AlignmentOrder(mappedOrderArray));
501     final OrderCommand result = new OrderCommand(command.getDescription(),
502             oldOrder, mapTo);
503     return result;
504   }
505
506   /**
507    * Returns a ColumnSelection in the 'mapTo' view which corresponds to the
508    * given selection in the 'mapFrom' view. We assume one is nucleotide, the
509    * other is protein (and holds the mappings from codons to protein residues).
510    * 
511    * @param colsel
512    * @param mapFrom
513    * @param mapTo
514    * @return
515    */
516   public static void mapColumnSelection(ColumnSelection colsel,
517           HiddenColumns hiddencols, AlignViewportI mapFrom,
518           AlignViewportI mapTo, ColumnSelection newColSel,
519           HiddenColumns newHidden)
520   {
521     boolean targetIsNucleotide = mapTo.isNucleotide();
522     AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
523     List<AlignedCodonFrame> codonFrames = protein.getAlignment()
524             .getCodonFrames();
525
526     if (colsel == null)
527     {
528       return; // mappedColumns;
529     }
530
531     char fromGapChar = mapFrom.getAlignment().getGapCharacter();
532
533     /*
534      * For each mapped column, find the range of columns that residues in that
535      * column map to.
536      */
537     List<SequenceI> fromSequences = mapFrom.getAlignment().getSequences();
538     List<SequenceI> toSequences = mapTo.getAlignment().getSequences();
539
540     for (Integer sel : colsel.getSelected())
541     {
542       mapColumn(sel.intValue(), codonFrames, newColSel, fromSequences,
543               toSequences, fromGapChar);
544     }
545
546     Iterator<int[]> regions = hiddencols.iterator();
547     while (regions.hasNext())
548     {
549       mapHiddenColumns(regions.next(), codonFrames, newHidden,
550               fromSequences, toSequences, fromGapChar);
551     }
552     return; // mappedColumns;
553   }
554
555   /**
556    * Helper method that maps a [start, end] hidden column range to its mapped
557    * equivalent
558    * 
559    * @param hidden
560    * @param mappings
561    * @param mappedColumns
562    * @param fromSequences
563    * @param toSequences
564    * @param fromGapChar
565    */
566   protected static void mapHiddenColumns(int[] hidden,
567           List<AlignedCodonFrame> mappings, HiddenColumns mappedColumns,
568           List<SequenceI> fromSequences, List<SequenceI> toSequences,
569           char fromGapChar)
570   {
571     for (int col = hidden[0]; col <= hidden[1]; col++)
572     {
573       int[] mappedTo = findMappedColumns(col, mappings, fromSequences,
574               toSequences, fromGapChar);
575
576       /*
577        * Add the range of hidden columns to the mapped selection (converting
578        * base 1 to base 0).
579        */
580       if (mappedTo != null)
581       {
582         mappedColumns.hideColumns(mappedTo[0] - 1, mappedTo[1] - 1);
583       }
584     }
585   }
586
587   /**
588    * Helper method to map one column selection
589    * 
590    * @param col
591    *          the column number (base 0)
592    * @param mappings
593    *          the sequence mappings
594    * @param mappedColumns
595    *          the mapped column selections to add to
596    * @param fromSequences
597    * @param toSequences
598    * @param fromGapChar
599    */
600   protected static void mapColumn(int col, List<AlignedCodonFrame> mappings,
601           ColumnSelection mappedColumns, List<SequenceI> fromSequences,
602           List<SequenceI> toSequences, char fromGapChar)
603   {
604     int[] mappedTo = findMappedColumns(col, mappings, fromSequences,
605             toSequences, fromGapChar);
606
607     /*
608      * Add the range of mapped columns to the mapped selection (converting
609      * base 1 to base 0). Note that this may include intron-only regions which
610      * lie between the start and end ranges of the selection.
611      */
612     if (mappedTo != null)
613     {
614       for (int i = mappedTo[0]; i <= mappedTo[1]; i++)
615       {
616         mappedColumns.addElement(i - 1);
617       }
618     }
619   }
620
621   /**
622    * Helper method to find the range of columns mapped to from one column.
623    * Returns the maximal range of columns mapped to from all sequences in the
624    * source column, or null if no mappings were found.
625    * 
626    * @param col
627    * @param mappings
628    * @param fromSequences
629    * @param toSequences
630    * @param fromGapChar
631    * @return
632    */
633   protected static int[] findMappedColumns(int col,
634           List<AlignedCodonFrame> mappings, List<SequenceI> fromSequences,
635           List<SequenceI> toSequences, char fromGapChar)
636   {
637     int[] mappedTo = new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE };
638     boolean found = false;
639
640     /*
641      * For each sequence in the 'from' alignment
642      */
643     for (SequenceI fromSeq : fromSequences)
644     {
645       /*
646        * Ignore gaps (unmapped anyway)
647        */
648       if (fromSeq.getCharAt(col) == fromGapChar)
649       {
650         continue;
651       }
652
653       /*
654        * Get the residue position and find the mapped position.
655        */
656       int residuePos = fromSeq.findPosition(col);
657       SearchResultsI sr = buildSearchResults(fromSeq, residuePos, mappings);
658       for (SearchResultMatchI m : sr.getResults())
659       {
660         int mappedStartResidue = m.getStart();
661         int mappedEndResidue = m.getEnd();
662         SequenceI mappedSeq = m.getSequence();
663
664         /*
665          * Locate the aligned sequence whose dataset is mappedSeq. TODO a
666          * datamodel that can do this efficiently.
667          */
668         for (SequenceI toSeq : toSequences)
669         {
670           if (toSeq.getDatasetSequence() == mappedSeq)
671           {
672             int mappedStartCol = toSeq.findIndex(mappedStartResidue);
673             int mappedEndCol = toSeq.findIndex(mappedEndResidue);
674             mappedTo[0] = Math.min(mappedTo[0], mappedStartCol);
675             mappedTo[1] = Math.max(mappedTo[1], mappedEndCol);
676             found = true;
677             break;
678             // note: remove break if we ever want to map one to many sequences
679           }
680         }
681       }
682     }
683     return found ? mappedTo : null;
684   }
685
686   /**
687    * Returns the mapped codon or codons for a given aligned sequence column
688    * position (base 0).
689    * 
690    * @param seq
691    *          an aligned peptide sequence
692    * @param col
693    *          an aligned column position (base 0)
694    * @param mappings
695    *          a set of codon mappings
696    * @return the bases of the mapped codon(s) in the cDNA dataset sequence(s),
697    *         or an empty list if none found
698    */
699   public static List<char[]> findCodonsFor(SequenceI seq, int col,
700           List<AlignedCodonFrame> mappings)
701   {
702     List<char[]> result = new ArrayList<>();
703     int dsPos = seq.findPosition(col);
704     for (AlignedCodonFrame mapping : mappings)
705     {
706       if (mapping.involvesSequence(seq))
707       {
708         List<char[]> codons = mapping
709                 .getMappedCodons(seq.getDatasetSequence(), dsPos);
710         if (codons != null)
711         {
712           result.addAll(codons);
713         }
714       }
715     }
716     return result;
717   }
718
719   /**
720    * Converts a series of [start, end] range pairs into an array of individual
721    * positions. This also caters for 'reverse strand' (start > end) cases.
722    * 
723    * @param ranges
724    * @return
725    */
726   public static int[] flattenRanges(int[] ranges)
727   {
728     /*
729      * Count how many positions altogether
730      */
731     int count = 0;
732     for (int i = 0; i < ranges.length - 1; i += 2)
733     {
734       count += Math.abs(ranges[i + 1] - ranges[i]) + 1;
735     }
736
737     int[] result = new int[count];
738     int k = 0;
739     for (int i = 0; i < ranges.length - 1; i += 2)
740     {
741       int from = ranges[i];
742       final int to = ranges[i + 1];
743       int step = from <= to ? 1 : -1;
744       do
745       {
746         result[k++] = from;
747         from += step;
748       } while (from != to + step);
749     }
750     return result;
751   }
752
753   /**
754    * Returns a list of any mappings that are from or to the given (aligned or
755    * dataset) sequence.
756    * 
757    * @param sequence
758    * @param mappings
759    * @return
760    */
761   public static List<AlignedCodonFrame> findMappingsForSequence(
762           SequenceI sequence, List<AlignedCodonFrame> mappings)
763   {
764     return findMappingsForSequenceAndOthers(sequence, mappings, null);
765   }
766
767   /**
768    * Returns a list of any mappings that are from or to the given (aligned or
769    * dataset) sequence, optionally limited to mappings involving one of a given
770    * list of sequences.
771    * 
772    * @param sequence
773    * @param mappings
774    * @param filterList
775    * @return
776    */
777   public static List<AlignedCodonFrame> findMappingsForSequenceAndOthers(
778           SequenceI sequence, List<AlignedCodonFrame> mappings,
779           List<SequenceI> filterList)
780   {
781     List<AlignedCodonFrame> result = new ArrayList<>();
782     if (sequence == null || mappings == null)
783     {
784       return result;
785     }
786     for (AlignedCodonFrame mapping : mappings)
787     {
788       if (mapping.involvesSequence(sequence))
789       {
790         if (filterList != null)
791         {
792           for (SequenceI otherseq : filterList)
793           {
794             SequenceI otherDataset = otherseq.getDatasetSequence();
795             if (otherseq == sequence
796                     || otherseq == sequence.getDatasetSequence()
797                     || (otherDataset != null && (otherDataset == sequence
798                             || otherDataset == sequence
799                                     .getDatasetSequence())))
800             {
801               // skip sequences in subset which directly relate to sequence
802               continue;
803             }
804             if (mapping.involvesSequence(otherseq))
805             {
806               // selected a mapping contained in subselect alignment
807               result.add(mapping);
808               break;
809             }
810           }
811         }
812         else
813         {
814           result.add(mapping);
815         }
816       }
817     }
818     return result;
819   }
820
821   /**
822    * Returns the total length of the supplied ranges, which may be as single
823    * [start, end] or multiple [start, end, start, end ...]
824    * 
825    * @param ranges
826    * @return
827    */
828   public static int getLength(List<int[]> ranges)
829   {
830     if (ranges == null)
831     {
832       return 0;
833     }
834     int length = 0;
835     for (int[] range : ranges)
836     {
837       if (range.length % 2 != 0)
838       {
839         Cache.log.error(
840                 "Error unbalance start/end ranges: " + ranges.toString());
841         return 0;
842       }
843       for (int i = 0; i < range.length - 1; i += 2)
844       {
845         length += Math.abs(range[i + 1] - range[i]) + 1;
846       }
847     }
848     return length;
849   }
850
851   /**
852    * Answers true if any range includes the given value
853    * 
854    * @param ranges
855    * @param value
856    * @return
857    */
858   public static boolean contains(List<int[]> ranges, int value)
859   {
860     if (ranges == null)
861     {
862       return false;
863     }
864     for (int[] range : ranges)
865     {
866       if (range[1] >= range[0] && value >= range[0] && value <= range[1])
867       {
868         /*
869          * value within ascending range
870          */
871         return true;
872       }
873       if (range[1] < range[0] && value <= range[0] && value >= range[1])
874       {
875         /*
876          * value within descending range
877          */
878         return true;
879       }
880     }
881     return false;
882   }
883
884   /**
885    * Removes a specified number of positions from the start of a ranges list.
886    * For example, could be used to adjust cds ranges to allow for an incomplete
887    * start codon. Subranges are removed completely, or their start positions
888    * adjusted, until the required number of positions has been removed from the
889    * range. Reverse strand ranges are supported. The input array is not
890    * modified.
891    * 
892    * @param removeCount
893    * @param ranges
894    *          an array of [start, end, start, end...] positions
895    * @return a new array with the first removeCount positions removed
896    */
897   public static int[] removeStartPositions(int removeCount,
898           final int[] ranges)
899   {
900     if (removeCount <= 0)
901     {
902       return ranges;
903     }
904
905     int[] copy = Arrays.copyOf(ranges, ranges.length);
906     int sxpos = -1;
907     int cdspos = 0;
908     for (int x = 0; x < copy.length && sxpos == -1; x += 2)
909     {
910       cdspos += Math.abs(copy[x + 1] - copy[x]) + 1;
911       if (removeCount < cdspos)
912       {
913         /*
914          * we have removed enough, time to finish
915          */
916         sxpos = x;
917
918         /*
919          * increment start of first exon, or decrement if reverse strand
920          */
921         if (copy[x] <= copy[x + 1])
922         {
923           copy[x] = copy[x + 1] - cdspos + removeCount + 1;
924         }
925         else
926         {
927           copy[x] = copy[x + 1] + cdspos - removeCount - 1;
928         }
929         break;
930       }
931     }
932
933     if (sxpos > 0)
934     {
935       /*
936        * we dropped at least one entire sub-range - compact the array
937        */
938       int[] nxon = new int[copy.length - sxpos];
939       System.arraycopy(copy, sxpos, nxon, 0, copy.length - sxpos);
940       return nxon;
941     }
942     return copy;
943   }
944
945   /**
946    * Answers true if range's start-end positions include those of queryRange,
947    * where either range might be in reverse direction, else false
948    * 
949    * @param range
950    *          a start-end range
951    * @param queryRange
952    *          a candidate subrange of range (start2-end2)
953    * @return
954    */
955   public static boolean rangeContains(int[] range, int[] queryRange)
956   {
957     if (range == null || queryRange == null || range.length != 2
958             || queryRange.length != 2)
959     {
960       /*
961        * invalid arguments
962        */
963       return false;
964     }
965
966     int min = Math.min(range[0], range[1]);
967     int max = Math.max(range[0], range[1]);
968
969     return (min <= queryRange[0] && max >= queryRange[0]
970             && min <= queryRange[1] && max >= queryRange[1]);
971   }
972
973   /**
974    * Removes the specified number of positions from the given ranges. Provided
975    * to allow a stop codon to be stripped from a CDS sequence so that it matches
976    * the peptide translation length.
977    * 
978    * @param positions
979    * @param ranges
980    *          a list of (single) [start, end] ranges
981    * @return
982    */
983   public static void removeEndPositions(int positions, List<int[]> ranges)
984   {
985     int toRemove = positions;
986     Iterator<int[]> it = new ReverseListIterator<>(ranges);
987     while (toRemove > 0)
988     {
989       int[] endRange = it.next();
990       if (endRange.length != 2)
991       {
992         /*
993          * not coded for [start1, end1, start2, end2, ...]
994          */
995         Cache.log.error(
996                 "MappingUtils.removeEndPositions doesn't handle multiple  ranges");
997         return;
998       }
999
1000       int length = endRange[1] - endRange[0] + 1;
1001       if (length <= 0)
1002       {
1003         /*
1004          * not coded for a reverse strand range (end < start)
1005          */
1006         Cache.log.error(
1007                 "MappingUtils.removeEndPositions doesn't handle reverse strand");
1008         return;
1009       }
1010       if (length > toRemove)
1011       {
1012         endRange[1] -= toRemove;
1013         toRemove = 0;
1014       }
1015       else
1016       {
1017         toRemove -= length;
1018         it.remove();
1019       }
1020     }
1021   }
1022
1023   /**
1024    * Converts a list of {@code start-end} ranges to a single array of
1025    * {@code start1, end1, start2, ... } ranges
1026    * 
1027    * @param ranges
1028    * @return
1029    */
1030   public static int[] rangeListToArray(List<int[]> ranges)
1031   {
1032     int rangeCount = ranges.size();
1033     int[] result = new int[rangeCount * 2];
1034     int j = 0;
1035     for (int i = 0; i < rangeCount; i++)
1036     {
1037       int[] range = ranges.get(i);
1038       result[j++] = range[0];
1039       result[j++] = range[1];
1040     }
1041     return result;
1042   }
1043
1044   /*
1045    * Returns the maximal start-end positions in the given (ordered) list of
1046    * ranges which is overlapped by the given begin-end range, or null if there
1047    * is no overlap.
1048    * 
1049    * <pre>
1050    * Examples:
1051    *   if ranges is {[4, 8], [10, 12], [16, 19]}
1052    * then
1053    *   findOverlap(ranges, 1, 20) == [4, 19]
1054    *   findOverlap(ranges, 6, 11) == [6, 11]
1055    *   findOverlap(ranges, 9, 15) == [10, 12]
1056    *   findOverlap(ranges, 13, 15) == null
1057    * </pre>
1058    * 
1059    * @param ranges
1060    * @param begin
1061    * @param end
1062    * @return
1063    */
1064   protected static int[] findOverlap(List<int[]> ranges, final int begin,
1065           final int end)
1066   {
1067     boolean foundStart = false;
1068     int from = 0;
1069     int to = 0;
1070
1071     /*
1072      * traverse the ranges to find the first position (if any) >= begin,
1073      * and the last position (if any) <= end
1074      */
1075     for (int[] range : ranges)
1076     {
1077       if (!foundStart)
1078       {
1079         if (range[0] >= begin)
1080         {
1081           /*
1082            * first range that starts with, or follows, begin
1083            */
1084           foundStart = true;
1085           from = Math.max(range[0], begin);
1086         }
1087         else if (range[1] >= begin)
1088         {
1089           /*
1090            * first range that contains begin
1091            */
1092           foundStart = true;
1093           from = begin;
1094         }
1095       }
1096
1097       if (range[0] <= end)
1098       {
1099         to = Math.min(end, range[1]);
1100       }
1101     }
1102
1103     return foundStart && to >= from ? new int[] { from, to } : null;
1104   }
1105 }