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