JAL-2349 JAL-3855 Integrate pAE retrieval in StructureFile so it can be transferred...
[jalview.git] / src / jalview / analysis / AlignmentUtils.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.analysis;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.NoSuchElementException;
36 import java.util.Set;
37 import java.util.SortedMap;
38 import java.util.TreeMap;
39
40 import jalview.bin.Console;
41 import jalview.commands.RemoveGapColCommand;
42 import jalview.datamodel.AlignedCodon;
43 import jalview.datamodel.AlignedCodonFrame;
44 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
45 import jalview.datamodel.Alignment;
46 import jalview.datamodel.AlignmentAnnotation;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.ContactMatrixI;
49 import jalview.datamodel.DBRefEntry;
50 import jalview.datamodel.GeneLociI;
51 import jalview.datamodel.IncompleteCodonException;
52 import jalview.datamodel.Mapping;
53 import jalview.datamodel.Sequence;
54 import jalview.datamodel.SequenceFeature;
55 import jalview.datamodel.SequenceGroup;
56 import jalview.datamodel.SequenceI;
57 import jalview.datamodel.features.SequenceFeatures;
58 import jalview.io.gff.SequenceOntologyI;
59 import jalview.schemes.ResidueProperties;
60 import jalview.util.Comparison;
61 import jalview.util.DBRefUtils;
62 import jalview.util.IntRangeComparator;
63 import jalview.util.MapList;
64 import jalview.util.MappingUtils;
65
66 /**
67  * grab bag of useful alignment manipulation operations Expect these to be
68  * refactored elsewhere at some point.
69  * 
70  * @author jimp
71  * 
72  */
73 public class AlignmentUtils
74 {
75   private static final int CODON_LENGTH = 3;
76
77   private static final String SEQUENCE_VARIANT = "sequence_variant:";
78
79   /*
80    * the 'id' attribute is provided for variant features fetched from
81    * Ensembl using its REST service with JSON format 
82    */
83   public static final String VARIANT_ID = "id";
84
85   /**
86    * A data model to hold the 'normal' base value at a position, and an optional
87    * sequence variant feature
88    */
89   static final class DnaVariant
90   {
91     final String base;
92
93     SequenceFeature variant;
94
95     DnaVariant(String nuc)
96     {
97       base = nuc;
98       variant = null;
99     }
100
101     DnaVariant(String nuc, SequenceFeature var)
102     {
103       base = nuc;
104       variant = var;
105     }
106
107     public String getSource()
108     {
109       return variant == null ? null : variant.getFeatureGroup();
110     }
111
112     /**
113      * toString for aid in the debugger only
114      */
115     @Override
116     public String toString()
117     {
118       return base + ":" + (variant == null ? "" : variant.getDescription());
119     }
120   }
121
122   /**
123    * given an existing alignment, create a new alignment including all, or up to
124    * flankSize additional symbols from each sequence's dataset sequence
125    * 
126    * @param core
127    * @param flankSize
128    * @return AlignmentI
129    */
130   public static AlignmentI expandContext(AlignmentI core, int flankSize)
131   {
132     List<SequenceI> sq = new ArrayList<>();
133     int maxoffset = 0;
134     for (SequenceI s : core.getSequences())
135     {
136       SequenceI newSeq = s.deriveSequence();
137       final int newSeqStart = newSeq.getStart() - 1;
138       if (newSeqStart > maxoffset
139               && newSeq.getDatasetSequence().getStart() < s.getStart())
140       {
141         maxoffset = newSeqStart;
142       }
143       sq.add(newSeq);
144     }
145     if (flankSize > -1)
146     {
147       maxoffset = Math.min(maxoffset, flankSize);
148     }
149
150     /*
151      * now add offset left and right to create an expanded alignment
152      */
153     for (SequenceI s : sq)
154     {
155       SequenceI ds = s;
156       while (ds.getDatasetSequence() != null)
157       {
158         ds = ds.getDatasetSequence();
159       }
160       int s_end = s.findPosition(s.getStart() + s.getLength());
161       // find available flanking residues for sequence
162       int ustream_ds = s.getStart() - ds.getStart();
163       int dstream_ds = ds.getEnd() - s_end;
164
165       // build new flanked sequence
166
167       // compute gap padding to start of flanking sequence
168       int offset = maxoffset - ustream_ds;
169
170       // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
171       if (flankSize >= 0)
172       {
173         if (flankSize < ustream_ds)
174         {
175           // take up to flankSize residues
176           offset = maxoffset - flankSize;
177           ustream_ds = flankSize;
178         }
179         if (flankSize <= dstream_ds)
180         {
181           dstream_ds = flankSize - 1;
182         }
183       }
184       // TODO use Character.toLowerCase to avoid creating String objects?
185       char[] upstream = new String(ds
186               .getSequence(s.getStart() - 1 - ustream_ds, s.getStart() - 1))
187                       .toLowerCase(Locale.ROOT).toCharArray();
188       char[] downstream = new String(
189               ds.getSequence(s_end - 1, s_end + dstream_ds))
190                       .toLowerCase(Locale.ROOT).toCharArray();
191       char[] coreseq = s.getSequence();
192       char[] nseq = new char[offset + upstream.length + downstream.length
193               + coreseq.length];
194       char c = core.getGapCharacter();
195
196       int p = 0;
197       for (; p < offset; p++)
198       {
199         nseq[p] = c;
200       }
201
202       System.arraycopy(upstream, 0, nseq, p, upstream.length);
203       System.arraycopy(coreseq, 0, nseq, p + upstream.length,
204               coreseq.length);
205       System.arraycopy(downstream, 0, nseq,
206               p + coreseq.length + upstream.length, downstream.length);
207       s.setSequence(new String(nseq));
208       s.setStart(s.getStart() - ustream_ds);
209       s.setEnd(s_end + downstream.length);
210     }
211     AlignmentI newAl = new jalview.datamodel.Alignment(
212             sq.toArray(new SequenceI[0]));
213     for (SequenceI s : sq)
214     {
215       if (s.getAnnotation() != null)
216       {
217         for (AlignmentAnnotation aa : s.getAnnotation())
218         {
219           aa.adjustForAlignment(); // JAL-1712 fix
220           newAl.addAnnotation(aa);
221         }
222       }
223     }
224     newAl.setDataset(core.getDataset());
225     return newAl;
226   }
227
228   /**
229    * Returns the index (zero-based position) of a sequence in an alignment, or
230    * -1 if not found.
231    * 
232    * @param al
233    * @param seq
234    * @return
235    */
236   public static int getSequenceIndex(AlignmentI al, SequenceI seq)
237   {
238     int result = -1;
239     int pos = 0;
240     for (SequenceI alSeq : al.getSequences())
241     {
242       if (alSeq == seq)
243       {
244         result = pos;
245         break;
246       }
247       pos++;
248     }
249     return result;
250   }
251
252   /**
253    * Returns a map of lists of sequences in the alignment, keyed by sequence
254    * name. For use in mapping between different alignment views of the same
255    * sequences.
256    * 
257    * @see jalview.datamodel.AlignmentI#getSequencesByName()
258    */
259   public static Map<String, List<SequenceI>> getSequencesByName(
260           AlignmentI al)
261   {
262     Map<String, List<SequenceI>> theMap = new LinkedHashMap<>();
263     for (SequenceI seq : al.getSequences())
264     {
265       String name = seq.getName();
266       if (name != null)
267       {
268         List<SequenceI> seqs = theMap.get(name);
269         if (seqs == null)
270         {
271           seqs = new ArrayList<>();
272           theMap.put(name, seqs);
273         }
274         seqs.add(seq);
275       }
276     }
277     return theMap;
278   }
279
280   /**
281    * Build mapping of protein to cDNA alignment. Mappings are made between
282    * sequences where the cDNA translates to the protein sequence. Any new
283    * mappings are added to the protein alignment. Returns true if any mappings
284    * either already exist or were added, else false.
285    * 
286    * @param proteinAlignment
287    * @param cdnaAlignment
288    * @return
289    */
290   public static boolean mapProteinAlignmentToCdna(
291           final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
292   {
293     if (proteinAlignment == null || cdnaAlignment == null)
294     {
295       return false;
296     }
297
298     Set<SequenceI> mappedDna = new HashSet<>();
299     Set<SequenceI> mappedProtein = new HashSet<>();
300
301     /*
302      * First pass - map sequences where cross-references exist. This include
303      * 1-to-many mappings to support, for example, variant cDNA.
304      */
305     boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
306             cdnaAlignment, mappedDna, mappedProtein, true);
307
308     /*
309      * Second pass - map sequences where no cross-references exist. This only
310      * does 1-to-1 mappings and assumes corresponding sequences are in the same
311      * order in the alignments.
312      */
313     mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
314             mappedDna, mappedProtein, false);
315     return mappingPerformed;
316   }
317
318   /**
319    * Make mappings between compatible sequences (where the cDNA translation
320    * matches the protein).
321    * 
322    * @param proteinAlignment
323    * @param cdnaAlignment
324    * @param mappedDna
325    *          a set of mapped DNA sequences (to add to)
326    * @param mappedProtein
327    *          a set of mapped Protein sequences (to add to)
328    * @param xrefsOnly
329    *          if true, only map sequences where xrefs exist
330    * @return
331    */
332   protected static boolean mapProteinToCdna(
333           final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment,
334           Set<SequenceI> mappedDna, Set<SequenceI> mappedProtein,
335           boolean xrefsOnly)
336   {
337     boolean mappingExistsOrAdded = false;
338     List<SequenceI> thisSeqs = proteinAlignment.getSequences();
339     for (SequenceI aaSeq : thisSeqs)
340     {
341       boolean proteinMapped = false;
342       AlignedCodonFrame acf = new AlignedCodonFrame();
343
344       for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
345       {
346         /*
347          * Always try to map if sequences have xref to each other; this supports
348          * variant cDNA or alternative splicing for a protein sequence.
349          * 
350          * If no xrefs, try to map progressively, assuming that alignments have
351          * mappable sequences in corresponding order. These are not
352          * many-to-many, as that would risk mixing species with similar cDNA
353          * sequences.
354          */
355         if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
356         {
357           continue;
358         }
359
360         /*
361          * Don't map non-xrefd sequences more than once each. This heuristic
362          * allows us to pair up similar sequences in ordered alignments.
363          */
364         if (!xrefsOnly && (mappedProtein.contains(aaSeq)
365                 || mappedDna.contains(cdnaSeq)))
366         {
367           continue;
368         }
369         if (mappingExists(proteinAlignment.getCodonFrames(),
370                 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
371         {
372           mappingExistsOrAdded = true;
373         }
374         else
375         {
376           MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
377           if (map != null)
378           {
379             acf.addMap(cdnaSeq, aaSeq, map);
380             mappingExistsOrAdded = true;
381             proteinMapped = true;
382             mappedDna.add(cdnaSeq);
383             mappedProtein.add(aaSeq);
384           }
385         }
386       }
387       if (proteinMapped)
388       {
389         proteinAlignment.addCodonFrame(acf);
390       }
391     }
392     return mappingExistsOrAdded;
393   }
394
395   /**
396    * Answers true if the mappings include one between the given (dataset)
397    * sequences.
398    */
399   protected static boolean mappingExists(List<AlignedCodonFrame> mappings,
400           SequenceI aaSeq, SequenceI cdnaSeq)
401   {
402     if (mappings != null)
403     {
404       for (AlignedCodonFrame acf : mappings)
405       {
406         if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
407         {
408           return true;
409         }
410       }
411     }
412     return false;
413   }
414
415   /**
416    * Builds a mapping (if possible) of a cDNA to a protein sequence.
417    * <ul>
418    * <li>first checks if the cdna translates exactly to the protein
419    * sequence</li>
420    * <li>else checks for translation after removing a STOP codon</li>
421    * <li>else checks for translation after removing a START codon</li>
422    * <li>if that fails, inspect CDS features on the cDNA sequence</li>
423    * </ul>
424    * Returns null if no mapping is determined.
425    * 
426    * @param proteinSeq
427    *          the aligned protein sequence
428    * @param cdnaSeq
429    *          the aligned cdna sequence
430    * @return
431    */
432   public static MapList mapCdnaToProtein(SequenceI proteinSeq,
433           SequenceI cdnaSeq)
434   {
435     /*
436      * Here we handle either dataset sequence set (desktop) or absent (applet).
437      * Use only the char[] form of the sequence to avoid creating possibly large
438      * String objects.
439      */
440     final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
441     char[] aaSeqChars = proteinDataset != null
442             ? proteinDataset.getSequence()
443             : proteinSeq.getSequence();
444     final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
445     char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
446             : cdnaSeq.getSequence();
447     if (aaSeqChars == null || cdnaSeqChars == null)
448     {
449       return null;
450     }
451
452     /*
453      * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
454      */
455     final int mappedLength = CODON_LENGTH * aaSeqChars.length;
456     int cdnaLength = cdnaSeqChars.length;
457     int cdnaStart = cdnaSeq.getStart();
458     int cdnaEnd = cdnaSeq.getEnd();
459     final int proteinStart = proteinSeq.getStart();
460     final int proteinEnd = proteinSeq.getEnd();
461
462     /*
463      * If lengths don't match, try ignoring stop codon (if present)
464      */
465     if (cdnaLength != mappedLength && cdnaLength > 2)
466     {
467       String lastCodon = String.valueOf(cdnaSeqChars,
468               cdnaLength - CODON_LENGTH, CODON_LENGTH)
469               .toUpperCase(Locale.ROOT);
470       for (String stop : ResidueProperties.STOP_CODONS)
471       {
472         if (lastCodon.equals(stop))
473         {
474           cdnaEnd -= CODON_LENGTH;
475           cdnaLength -= CODON_LENGTH;
476           break;
477         }
478       }
479     }
480
481     /*
482      * If lengths still don't match, try ignoring start codon.
483      */
484     int startOffset = 0;
485     if (cdnaLength != mappedLength && cdnaLength > 2
486             && String.valueOf(cdnaSeqChars, 0, CODON_LENGTH)
487                     .toUpperCase(Locale.ROOT)
488                     .equals(ResidueProperties.START))
489     {
490       startOffset += CODON_LENGTH;
491       cdnaStart += CODON_LENGTH;
492       cdnaLength -= CODON_LENGTH;
493     }
494
495     if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
496     {
497       /*
498        * protein is translation of dna (+/- start/stop codons)
499        */
500       MapList map = new MapList(new int[] { cdnaStart, cdnaEnd },
501               new int[]
502               { proteinStart, proteinEnd }, CODON_LENGTH, 1);
503       return map;
504     }
505
506     /*
507      * translation failed - try mapping CDS annotated regions of dna
508      */
509     return mapCdsToProtein(cdnaSeq, proteinSeq);
510   }
511
512   /**
513    * Test whether the given cdna sequence, starting at the given offset,
514    * translates to the given amino acid sequence, using the standard translation
515    * table. Designed to fail fast i.e. as soon as a mismatch position is found.
516    * 
517    * @param cdnaSeqChars
518    * @param cdnaStart
519    * @param aaSeqChars
520    * @return
521    */
522   protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
523           char[] aaSeqChars)
524   {
525     if (cdnaSeqChars == null || aaSeqChars == null)
526     {
527       return false;
528     }
529
530     int aaPos = 0;
531     int dnaPos = cdnaStart;
532     for (; dnaPos < cdnaSeqChars.length - 2
533             && aaPos < aaSeqChars.length; dnaPos += CODON_LENGTH, aaPos++)
534     {
535       String codon = String.valueOf(cdnaSeqChars, dnaPos, CODON_LENGTH);
536       final String translated = ResidueProperties.codonTranslate(codon);
537
538       /*
539        * allow * in protein to match untranslatable in dna
540        */
541       final char aaRes = aaSeqChars[aaPos];
542       if ((translated == null || ResidueProperties.STOP.equals(translated))
543               && aaRes == '*')
544       {
545         continue;
546       }
547       if (translated == null || !(aaRes == translated.charAt(0)))
548       {
549         // debug
550         // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
551         // + codon + "(" + translated + ") != " + aaRes));
552         return false;
553       }
554     }
555
556     /*
557      * check we matched all of the protein sequence
558      */
559     if (aaPos != aaSeqChars.length)
560     {
561       return false;
562     }
563
564     /*
565      * check we matched all of the dna except
566      * for optional trailing STOP codon
567      */
568     if (dnaPos == cdnaSeqChars.length)
569     {
570       return true;
571     }
572     if (dnaPos == cdnaSeqChars.length - CODON_LENGTH)
573     {
574       String codon = String.valueOf(cdnaSeqChars, dnaPos, CODON_LENGTH);
575       if (ResidueProperties.STOP
576               .equals(ResidueProperties.codonTranslate(codon)))
577       {
578         return true;
579       }
580     }
581     return false;
582   }
583
584   /**
585    * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
586    * currently assumes that we are aligning cDNA to match protein.
587    * 
588    * @param seq
589    *          the sequence to be realigned
590    * @param al
591    *          the alignment whose sequence alignment is to be 'copied'
592    * @param gap
593    *          character string represent a gap in the realigned sequence
594    * @param preserveUnmappedGaps
595    * @param preserveMappedGaps
596    * @return true if the sequence was realigned, false if it could not be
597    */
598   public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
599           String gap, boolean preserveMappedGaps,
600           boolean preserveUnmappedGaps)
601   {
602     /*
603      * Get any mappings from the source alignment to the target (dataset)
604      * sequence.
605      */
606     // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
607     // all mappings. Would it help to constrain this?
608     List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
609     if (mappings == null || mappings.isEmpty())
610     {
611       return false;
612     }
613
614     /*
615      * Locate the aligned source sequence whose dataset sequence is mapped. We
616      * just take the first match here (as we can't align like more than one
617      * sequence).
618      */
619     SequenceI alignFrom = null;
620     AlignedCodonFrame mapping = null;
621     for (AlignedCodonFrame mp : mappings)
622     {
623       alignFrom = mp.findAlignedSequence(seq, al);
624       if (alignFrom != null)
625       {
626         mapping = mp;
627         break;
628       }
629     }
630
631     if (alignFrom == null)
632     {
633       return false;
634     }
635     alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
636             preserveMappedGaps, preserveUnmappedGaps);
637     return true;
638   }
639
640   /**
641    * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
642    * match residues and codons. Flags control whether existing gaps in unmapped
643    * (intron) and mapped (exon) regions are preserved or not. Gaps between
644    * intron and exon are only retained if both flags are set.
645    * 
646    * @param alignTo
647    * @param alignFrom
648    * @param mapping
649    * @param myGap
650    * @param sourceGap
651    * @param preserveUnmappedGaps
652    * @param preserveMappedGaps
653    */
654   public static void alignSequenceAs(SequenceI alignTo, SequenceI alignFrom,
655           AlignedCodonFrame mapping, String myGap, char sourceGap,
656           boolean preserveMappedGaps, boolean preserveUnmappedGaps)
657   {
658     // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
659
660     // aligned and dataset sequence positions, all base zero
661     int thisSeqPos = 0;
662     int sourceDsPos = 0;
663
664     int basesWritten = 0;
665     char myGapChar = myGap.charAt(0);
666     int ratio = myGap.length();
667
668     int fromOffset = alignFrom.getStart() - 1;
669     int toOffset = alignTo.getStart() - 1;
670     int sourceGapMappedLength = 0;
671     boolean inExon = false;
672     final int toLength = alignTo.getLength();
673     final int fromLength = alignFrom.getLength();
674     StringBuilder thisAligned = new StringBuilder(2 * toLength);
675
676     /*
677      * Traverse the 'model' aligned sequence
678      */
679     for (int i = 0; i < fromLength; i++)
680     {
681       char sourceChar = alignFrom.getCharAt(i);
682       if (sourceChar == sourceGap)
683       {
684         sourceGapMappedLength += ratio;
685         continue;
686       }
687
688       /*
689        * Found a non-gap character. Locate its mapped region if any.
690        */
691       sourceDsPos++;
692       // Note mapping positions are base 1, our sequence positions base 0
693       int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
694               sourceDsPos + fromOffset);
695       if (mappedPos == null)
696       {
697         /*
698          * unmapped position; treat like a gap
699          */
700         sourceGapMappedLength += ratio;
701         // System.err.println("Can't align: no codon mapping to residue "
702         // + sourceDsPos + "(" + sourceChar + ")");
703         // return;
704         continue;
705       }
706
707       int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
708       int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
709       StringBuilder trailingCopiedGap = new StringBuilder();
710
711       /*
712        * Copy dna sequence up to and including this codon. Optionally, include
713        * gaps before the codon starts (in introns) and/or after the codon starts
714        * (in exons).
715        * 
716        * Note this only works for 'linear' splicing, not reverse or interleaved.
717        * But then 'align dna as protein' doesn't make much sense otherwise.
718        */
719       int intronLength = 0;
720       while (basesWritten + toOffset < mappedCodonEnd
721               && thisSeqPos < toLength)
722       {
723         final char c = alignTo.getCharAt(thisSeqPos++);
724         if (c != myGapChar)
725         {
726           basesWritten++;
727           int sourcePosition = basesWritten + toOffset;
728           if (sourcePosition < mappedCodonStart)
729           {
730             /*
731              * Found an unmapped (intron) base. First add in any preceding gaps
732              * (if wanted).
733              */
734             if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
735             {
736               thisAligned.append(trailingCopiedGap.toString());
737               intronLength += trailingCopiedGap.length();
738               trailingCopiedGap = new StringBuilder();
739             }
740             intronLength++;
741             inExon = false;
742           }
743           else
744           {
745             final boolean startOfCodon = sourcePosition == mappedCodonStart;
746             int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
747                     preserveUnmappedGaps, sourceGapMappedLength, inExon,
748                     trailingCopiedGap.length(), intronLength, startOfCodon);
749             for (int k = 0; k < gapsToAdd; k++)
750             {
751               thisAligned.append(myGapChar);
752             }
753             sourceGapMappedLength = 0;
754             inExon = true;
755           }
756           thisAligned.append(c);
757           trailingCopiedGap = new StringBuilder();
758         }
759         else
760         {
761           if (inExon && preserveMappedGaps)
762           {
763             trailingCopiedGap.append(myGapChar);
764           }
765           else if (!inExon && preserveUnmappedGaps)
766           {
767             trailingCopiedGap.append(myGapChar);
768           }
769         }
770       }
771     }
772
773     /*
774      * At end of model aligned sequence. Copy any remaining target sequence, optionally
775      * including (intron) gaps.
776      */
777     while (thisSeqPos < toLength)
778     {
779       final char c = alignTo.getCharAt(thisSeqPos++);
780       if (c != myGapChar || preserveUnmappedGaps)
781       {
782         thisAligned.append(c);
783       }
784       sourceGapMappedLength--;
785     }
786
787     /*
788      * finally add gaps to pad for any trailing source gaps or
789      * unmapped characters
790      */
791     if (preserveUnmappedGaps)
792     {
793       while (sourceGapMappedLength > 0)
794       {
795         thisAligned.append(myGapChar);
796         sourceGapMappedLength--;
797       }
798     }
799
800     /*
801      * All done aligning, set the aligned sequence.
802      */
803     alignTo.setSequence(new String(thisAligned));
804   }
805
806   /**
807    * Helper method to work out how many gaps to insert when realigning.
808    * 
809    * @param preserveMappedGaps
810    * @param preserveUnmappedGaps
811    * @param sourceGapMappedLength
812    * @param inExon
813    * @param trailingCopiedGap
814    * @param intronLength
815    * @param startOfCodon
816    * @return
817    */
818   protected static int calculateGapsToInsert(boolean preserveMappedGaps,
819           boolean preserveUnmappedGaps, int sourceGapMappedLength,
820           boolean inExon, int trailingGapLength, int intronLength,
821           final boolean startOfCodon)
822   {
823     int gapsToAdd = 0;
824     if (startOfCodon)
825     {
826       /*
827        * Reached start of codon. Ignore trailing gaps in intron unless we are
828        * preserving gaps in both exon and intron. Ignore them anyway if the
829        * protein alignment introduces a gap at least as large as the intronic
830        * region.
831        */
832       if (inExon && !preserveMappedGaps)
833       {
834         trailingGapLength = 0;
835       }
836       if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
837       {
838         trailingGapLength = 0;
839       }
840       if (inExon)
841       {
842         gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
843       }
844       else
845       {
846         if (intronLength + trailingGapLength <= sourceGapMappedLength)
847         {
848           gapsToAdd = sourceGapMappedLength - intronLength;
849         }
850         else
851         {
852           gapsToAdd = Math.min(
853                   intronLength + trailingGapLength - sourceGapMappedLength,
854                   trailingGapLength);
855         }
856       }
857     }
858     else
859     {
860       /*
861        * second or third base of codon; check for any gaps in dna
862        */
863       if (!preserveMappedGaps)
864       {
865         trailingGapLength = 0;
866       }
867       gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
868     }
869     return gapsToAdd;
870   }
871
872   /**
873    * Realigns the given protein to match the alignment of the dna, using codon
874    * mappings to translate aligned codon positions to protein residues.
875    * 
876    * @param protein
877    *          the alignment whose sequences are realigned by this method
878    * @param dna
879    *          the dna alignment whose alignment we are 'copying'
880    * @return the number of sequences that were realigned
881    */
882   public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
883   {
884     if (protein.isNucleotide() || !dna.isNucleotide())
885     {
886       System.err.println("Wrong alignment type in alignProteinAsDna");
887       return 0;
888     }
889     List<SequenceI> unmappedProtein = new ArrayList<>();
890     Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
891             protein, dna, unmappedProtein);
892     return alignProteinAs(protein, alignedCodons, unmappedProtein);
893   }
894
895   /**
896    * Realigns the given dna to match the alignment of the protein, using codon
897    * mappings to translate aligned peptide positions to codons.
898    * 
899    * Always produces a padded CDS alignment.
900    * 
901    * @param dna
902    *          the alignment whose sequences are realigned by this method
903    * @param protein
904    *          the protein alignment whose alignment we are 'copying'
905    * @return the number of sequences that were realigned
906    */
907   public static int alignCdsAsProtein(AlignmentI dna, AlignmentI protein)
908   {
909     if (protein.isNucleotide() || !dna.isNucleotide())
910     {
911       System.err.println("Wrong alignment type in alignProteinAsDna");
912       return 0;
913     }
914     // todo: implement this
915     List<AlignedCodonFrame> mappings = protein.getCodonFrames();
916     int alignedCount = 0;
917     int width = 0; // alignment width for padding CDS
918     for (SequenceI dnaSeq : dna.getSequences())
919     {
920       if (alignCdsSequenceAsProtein(dnaSeq, protein, mappings,
921               dna.getGapCharacter()))
922       {
923         alignedCount++;
924       }
925       width = Math.max(dnaSeq.getLength(), width);
926     }
927     int oldwidth;
928     int diff;
929     for (SequenceI dnaSeq : dna.getSequences())
930     {
931       oldwidth = dnaSeq.getLength();
932       diff = width - oldwidth;
933       if (diff > 0)
934       {
935         dnaSeq.insertCharAt(oldwidth, diff, dna.getGapCharacter());
936       }
937     }
938     return alignedCount;
939   }
940
941   /**
942    * Helper method to align (if possible) the dna sequence to match the
943    * alignment of a mapped protein sequence. This is currently limited to
944    * handling coding sequence only.
945    * 
946    * @param cdsSeq
947    * @param protein
948    * @param mappings
949    * @param gapChar
950    * @return
951    */
952   static boolean alignCdsSequenceAsProtein(SequenceI cdsSeq,
953           AlignmentI protein, List<AlignedCodonFrame> mappings,
954           char gapChar)
955   {
956     SequenceI cdsDss = cdsSeq.getDatasetSequence();
957     if (cdsDss == null)
958     {
959       System.err
960               .println("alignCdsSequenceAsProtein needs aligned sequence!");
961       return false;
962     }
963
964     List<AlignedCodonFrame> dnaMappings = MappingUtils
965             .findMappingsForSequence(cdsSeq, mappings);
966     for (AlignedCodonFrame mapping : dnaMappings)
967     {
968       SequenceI peptide = mapping.findAlignedSequence(cdsSeq, protein);
969       if (peptide != null)
970       {
971         final int peptideLength = peptide.getLength();
972         Mapping map = mapping.getMappingBetween(cdsSeq, peptide);
973         if (map != null)
974         {
975           MapList mapList = map.getMap();
976           if (map.getTo() == peptide.getDatasetSequence())
977           {
978             mapList = mapList.getInverse();
979           }
980           final int cdsLength = cdsDss.getLength();
981           int mappedFromLength = MappingUtils
982                   .getLength(mapList.getFromRanges());
983           int mappedToLength = MappingUtils
984                   .getLength(mapList.getToRanges());
985           boolean addStopCodon = (cdsLength == mappedFromLength
986                   * CODON_LENGTH + CODON_LENGTH)
987                   || (peptide.getDatasetSequence()
988                           .getLength() == mappedFromLength - 1);
989           if (cdsLength != mappedToLength && !addStopCodon)
990           {
991             System.err.println(String.format(
992                     "Can't align cds as protein (length mismatch %d/%d): %s",
993                     cdsLength, mappedToLength, cdsSeq.getName()));
994           }
995
996           /*
997            * pre-fill the aligned cds sequence with gaps
998            */
999           char[] alignedCds = new char[peptideLength * CODON_LENGTH
1000                   + (addStopCodon ? CODON_LENGTH : 0)];
1001           Arrays.fill(alignedCds, gapChar);
1002
1003           /*
1004            * walk over the aligned peptide sequence and insert mapped 
1005            * codons for residues in the aligned cds sequence 
1006            */
1007           int copiedBases = 0;
1008           int cdsStart = cdsDss.getStart();
1009           int proteinPos = peptide.getStart() - 1;
1010           int cdsCol = 0;
1011
1012           for (int col = 0; col < peptideLength; col++)
1013           {
1014             char residue = peptide.getCharAt(col);
1015
1016             if (Comparison.isGap(residue))
1017             {
1018               cdsCol += CODON_LENGTH;
1019             }
1020             else
1021             {
1022               proteinPos++;
1023               int[] codon = mapList.locateInTo(proteinPos, proteinPos);
1024               if (codon == null)
1025               {
1026                 // e.g. incomplete start codon, X in peptide
1027                 cdsCol += CODON_LENGTH;
1028               }
1029               else
1030               {
1031                 for (int j = codon[0]; j <= codon[1]; j++)
1032                 {
1033                   char mappedBase = cdsDss.getCharAt(j - cdsStart);
1034                   alignedCds[cdsCol++] = mappedBase;
1035                   copiedBases++;
1036                 }
1037               }
1038             }
1039           }
1040
1041           /*
1042            * append stop codon if not mapped from protein,
1043            * closing it up to the end of the mapped sequence
1044            */
1045           if (copiedBases == cdsLength - CODON_LENGTH)
1046           {
1047             for (int i = alignedCds.length - 1; i >= 0; i--)
1048             {
1049               if (!Comparison.isGap(alignedCds[i]))
1050               {
1051                 cdsCol = i + 1; // gap just after end of sequence
1052                 break;
1053               }
1054             }
1055             for (int i = cdsLength - CODON_LENGTH; i < cdsLength; i++)
1056             {
1057               alignedCds[cdsCol++] = cdsDss.getCharAt(i);
1058             }
1059           }
1060           cdsSeq.setSequence(new String(alignedCds));
1061           return true;
1062         }
1063       }
1064     }
1065     return false;
1066   }
1067
1068   /**
1069    * Builds a map whose key is an aligned codon position (3 alignment column
1070    * numbers base 0), and whose value is a map from protein sequence to each
1071    * protein's peptide residue for that codon. The map generates an ordering of
1072    * the codons, and allows us to read off the peptides at each position in
1073    * order to assemble 'aligned' protein sequences.
1074    * 
1075    * @param protein
1076    *          the protein alignment
1077    * @param dna
1078    *          the coding dna alignment
1079    * @param unmappedProtein
1080    *          any unmapped proteins are added to this list
1081    * @return
1082    */
1083   protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
1084           AlignmentI protein, AlignmentI dna,
1085           List<SequenceI> unmappedProtein)
1086   {
1087     /*
1088      * maintain a list of any proteins with no mappings - these will be
1089      * rendered 'as is' in the protein alignment as we can't align them
1090      */
1091     unmappedProtein.addAll(protein.getSequences());
1092
1093     List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1094
1095     /*
1096      * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
1097      * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
1098      * comparator keeps the codon positions ordered.
1099      */
1100     Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<>(
1101             new CodonComparator());
1102
1103     for (SequenceI dnaSeq : dna.getSequences())
1104     {
1105       for (AlignedCodonFrame mapping : mappings)
1106       {
1107         SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
1108         if (prot != null)
1109         {
1110           Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
1111           addCodonPositions(dnaSeq, prot, protein.getGapCharacter(), seqMap,
1112                   alignedCodons);
1113           unmappedProtein.remove(prot);
1114         }
1115       }
1116     }
1117
1118     /*
1119      * Finally add any unmapped peptide start residues (e.g. for incomplete
1120      * codons) as if at the codon position before the second residue
1121      */
1122     // TODO resolve JAL-2022 so this fudge can be removed
1123     int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
1124     addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
1125
1126     return alignedCodons;
1127   }
1128
1129   /**
1130    * Scans for any protein mapped from position 2 (meaning unmapped start
1131    * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
1132    * preceding position in the alignment
1133    * 
1134    * @param alignedCodons
1135    *          the codon-to-peptide map
1136    * @param mappedSequenceCount
1137    *          the number of distinct sequences in the map
1138    */
1139   protected static void addUnmappedPeptideStarts(
1140           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1141           int mappedSequenceCount)
1142   {
1143     // TODO delete this ugly hack once JAL-2022 is resolved
1144     // i.e. we can model startPhase > 0 (incomplete start codon)
1145
1146     List<SequenceI> sequencesChecked = new ArrayList<>();
1147     AlignedCodon lastCodon = null;
1148     Map<SequenceI, AlignedCodon> toAdd = new HashMap<>();
1149
1150     for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
1151             .entrySet())
1152     {
1153       for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
1154               .entrySet())
1155       {
1156         SequenceI seq = sequenceCodon.getKey();
1157         if (sequencesChecked.contains(seq))
1158         {
1159           continue;
1160         }
1161         sequencesChecked.add(seq);
1162         AlignedCodon codon = sequenceCodon.getValue();
1163         if (codon.peptideCol > 1)
1164         {
1165           System.err.println(
1166                   "Problem mapping protein with >1 unmapped start positions: "
1167                           + seq.getName());
1168         }
1169         else if (codon.peptideCol == 1)
1170         {
1171           /*
1172            * first position (peptideCol == 0) was unmapped - add it
1173            */
1174           if (lastCodon != null)
1175           {
1176             AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
1177                     lastCodon.pos2, lastCodon.pos3,
1178                     String.valueOf(seq.getCharAt(0)), 0);
1179             toAdd.put(seq, firstPeptide);
1180           }
1181           else
1182           {
1183             /*
1184              * unmapped residue at start of alignment (no prior column) -
1185              * 'insert' at nominal codon [0, 0, 0]
1186              */
1187             AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
1188                     String.valueOf(seq.getCharAt(0)), 0);
1189             toAdd.put(seq, firstPeptide);
1190           }
1191         }
1192         if (sequencesChecked.size() == mappedSequenceCount)
1193         {
1194           // no need to check past first mapped position in all sequences
1195           break;
1196         }
1197       }
1198       lastCodon = entry.getKey();
1199     }
1200
1201     /*
1202      * add any new codons safely after iterating over the map
1203      */
1204     for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
1205     {
1206       addCodonToMap(alignedCodons, startCodon.getValue(),
1207               startCodon.getKey());
1208     }
1209   }
1210
1211   /**
1212    * Update the aligned protein sequences to match the codon alignments given in
1213    * the map.
1214    * 
1215    * @param protein
1216    * @param alignedCodons
1217    *          an ordered map of codon positions (columns), with sequence/peptide
1218    *          values present in each column
1219    * @param unmappedProtein
1220    * @return
1221    */
1222   protected static int alignProteinAs(AlignmentI protein,
1223           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1224           List<SequenceI> unmappedProtein)
1225   {
1226     /*
1227      * prefill peptide sequences with gaps 
1228      */
1229     int alignedWidth = alignedCodons.size();
1230     char[] gaps = new char[alignedWidth];
1231     Arrays.fill(gaps, protein.getGapCharacter());
1232     Map<SequenceI, char[]> peptides = new HashMap<>();
1233     for (SequenceI seq : protein.getSequences())
1234     {
1235       if (!unmappedProtein.contains(seq))
1236       {
1237         peptides.put(seq, Arrays.copyOf(gaps, gaps.length));
1238       }
1239     }
1240
1241     /*
1242      * Traverse the codons left to right (as defined by CodonComparator)
1243      * and insert peptides in each column where the sequence is mapped.
1244      * This gives a peptide 'alignment' where residues are aligned if their
1245      * corresponding codons occupy the same columns in the cdna alignment.
1246      */
1247     int column = 0;
1248     for (AlignedCodon codon : alignedCodons.keySet())
1249     {
1250       final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1251               .get(codon);
1252       for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1253       {
1254         char residue = entry.getValue().product.charAt(0);
1255         peptides.get(entry.getKey())[column] = residue;
1256       }
1257       column++;
1258     }
1259
1260     /*
1261      * and finally set the constructed sequences
1262      */
1263     for (Entry<SequenceI, char[]> entry : peptides.entrySet())
1264     {
1265       entry.getKey().setSequence(new String(entry.getValue()));
1266     }
1267
1268     return 0;
1269   }
1270
1271   /**
1272    * Populate the map of aligned codons by traversing the given sequence
1273    * mapping, locating the aligned positions of mapped codons, and adding those
1274    * positions and their translation products to the map.
1275    * 
1276    * @param dna
1277    *          the aligned sequence we are mapping from
1278    * @param protein
1279    *          the sequence to be aligned to the codons
1280    * @param gapChar
1281    *          the gap character in the dna sequence
1282    * @param seqMap
1283    *          a mapping to a sequence translation
1284    * @param alignedCodons
1285    *          the map we are building up
1286    */
1287   static void addCodonPositions(SequenceI dna, SequenceI protein,
1288           char gapChar, Mapping seqMap,
1289           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1290   {
1291     Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1292
1293     /*
1294      * add codon positions, and their peptide translations, to the alignment
1295      * map, while remembering the first codon mapped
1296      */
1297     while (codons.hasNext())
1298     {
1299       try
1300       {
1301         AlignedCodon codon = codons.next();
1302         addCodonToMap(alignedCodons, codon, protein);
1303       } catch (IncompleteCodonException e)
1304       {
1305         // possible incomplete trailing codon - ignore
1306       } catch (NoSuchElementException e)
1307       {
1308         // possibly peptide lacking STOP
1309       }
1310     }
1311   }
1312
1313   /**
1314    * Helper method to add a codon-to-peptide entry to the aligned codons map
1315    * 
1316    * @param alignedCodons
1317    * @param codon
1318    * @param protein
1319    */
1320   protected static void addCodonToMap(
1321           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1322           AlignedCodon codon, SequenceI protein)
1323   {
1324     Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1325     if (seqProduct == null)
1326     {
1327       seqProduct = new HashMap<>();
1328       alignedCodons.put(codon, seqProduct);
1329     }
1330     seqProduct.put(protein, codon);
1331   }
1332
1333   /**
1334    * Returns true if a cDNA/Protein mapping either exists, or could be made,
1335    * between at least one pair of sequences in the two alignments. Currently,
1336    * the logic is:
1337    * <ul>
1338    * <li>One alignment must be nucleotide, and the other protein</li>
1339    * <li>At least one pair of sequences must be already mapped, or mappable</li>
1340    * <li>Mappable means the nucleotide translation matches the protein
1341    * sequence</li>
1342    * <li>The translation may ignore start and stop codons if present in the
1343    * nucleotide</li>
1344    * </ul>
1345    * 
1346    * @param al1
1347    * @param al2
1348    * @return
1349    */
1350   public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1351   {
1352     if (al1 == null || al2 == null)
1353     {
1354       return false;
1355     }
1356
1357     /*
1358      * Require one nucleotide and one protein
1359      */
1360     if (al1.isNucleotide() == al2.isNucleotide())
1361     {
1362       return false;
1363     }
1364     AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1365     AlignmentI protein = dna == al1 ? al2 : al1;
1366     List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1367     for (SequenceI dnaSeq : dna.getSequences())
1368     {
1369       for (SequenceI proteinSeq : protein.getSequences())
1370       {
1371         if (isMappable(dnaSeq, proteinSeq, mappings))
1372         {
1373           return true;
1374         }
1375       }
1376     }
1377     return false;
1378   }
1379
1380   /**
1381    * Returns true if the dna sequence is mapped, or could be mapped, to the
1382    * protein sequence.
1383    * 
1384    * @param dnaSeq
1385    * @param proteinSeq
1386    * @param mappings
1387    * @return
1388    */
1389   protected static boolean isMappable(SequenceI dnaSeq,
1390           SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1391   {
1392     if (dnaSeq == null || proteinSeq == null)
1393     {
1394       return false;
1395     }
1396
1397     SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq
1398             : dnaSeq.getDatasetSequence();
1399     SequenceI proteinDs = proteinSeq.getDatasetSequence() == null
1400             ? proteinSeq
1401             : proteinSeq.getDatasetSequence();
1402
1403     for (AlignedCodonFrame mapping : mappings)
1404     {
1405       if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1406       {
1407         /*
1408          * already mapped
1409          */
1410         return true;
1411       }
1412     }
1413
1414     /*
1415      * Just try to make a mapping (it is not yet stored), test whether
1416      * successful.
1417      */
1418     return mapCdnaToProtein(proteinDs, dnaDs) != null;
1419   }
1420
1421   /**
1422    * Finds any reference annotations associated with the sequences in
1423    * sequenceScope, that are not already added to the alignment, and adds them
1424    * to the 'candidates' map. Also populates a lookup table of annotation
1425    * labels, keyed by calcId, for use in constructing tooltips or the like.
1426    * 
1427    * @param sequenceScope
1428    *          the sequences to scan for reference annotations
1429    * @param labelForCalcId
1430    *          (optional) map to populate with label for calcId
1431    * @param candidates
1432    *          map to populate with annotations for sequence
1433    * @param al
1434    *          the alignment to check for presence of annotations
1435    */
1436   public static void findAddableReferenceAnnotations(
1437           List<SequenceI> sequenceScope, Map<String, String> labelForCalcId,
1438           final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1439           AlignmentI al)
1440   {
1441     if (sequenceScope == null)
1442     {
1443       return;
1444     }
1445
1446     /*
1447      * For each sequence in scope, make a list of any annotations on the
1448      * underlying dataset sequence which are not already on the alignment.
1449      * 
1450      * Add to a map of { alignmentSequence, <List of annotations to add> }
1451      */
1452     for (SequenceI seq : sequenceScope)
1453     {
1454       SequenceI dataset = seq.getDatasetSequence();
1455       if (dataset == null)
1456       {
1457         continue;
1458       }
1459       AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1460       if (datasetAnnotations == null)
1461       {
1462         continue;
1463       }
1464       final List<AlignmentAnnotation> result = new ArrayList<>();
1465       for (AlignmentAnnotation dsann : datasetAnnotations)
1466       {
1467         /*
1468          * Find matching annotations on the alignment. If none is found, then
1469          * add this annotation to the list of 'addable' annotations for this
1470          * sequence.
1471          */
1472         final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1473                 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1474         if (matchedAlignmentAnnotations == null
1475                 || !matchedAlignmentAnnotations.iterator().hasNext())
1476         {
1477           result.add(dsann);
1478           if (labelForCalcId != null)
1479           {
1480             labelForCalcId.put(dsann.getCalcId(), dsann.label);
1481           }
1482         }
1483       }
1484       /*
1485        * Save any addable annotations for this sequence
1486        */
1487       if (!result.isEmpty())
1488       {
1489         candidates.put(seq, result);
1490       }
1491     }
1492   }
1493
1494   /**
1495    * Adds annotations to the top of the alignment annotations, in the same order
1496    * as their related sequences.
1497    * 
1498    * @param annotations
1499    *          the annotations to add
1500    * @param alignment
1501    *          the alignment to add them to
1502    * @param selectionGroup
1503    *          current selection group (or null if none)
1504    */
1505   public static void addReferenceAnnotations(
1506           Map<SequenceI, List<AlignmentAnnotation>> annotations,
1507           final AlignmentI alignment, final SequenceGroup selectionGroup)
1508   {
1509     for (SequenceI seq : annotations.keySet())
1510     {
1511       for (AlignmentAnnotation ann : annotations.get(seq))
1512       {
1513         AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1514         int startRes = 0;
1515         int endRes = ann.annotations.length;
1516         if (selectionGroup != null)
1517         {
1518           startRes = selectionGroup.getStartRes();
1519           endRes = selectionGroup.getEndRes();
1520         }
1521         copyAnn.restrict(startRes, endRes + 0);
1522
1523         /*
1524          * Add to the sequence (sets copyAnn.datasetSequence), unless the
1525          * original annotation is already on the sequence.
1526          */
1527         if (!seq.hasAnnotation(ann))
1528         {
1529           ContactMatrixI cm = seq.getDatasetSequence()
1530                   .getContactMatrixFor(ann);
1531           if (cm != null)
1532           {
1533             seq.addContactListFor(copyAnn, cm);
1534           }
1535           seq.addAlignmentAnnotation(copyAnn);
1536         }
1537         // adjust for gaps
1538         copyAnn.adjustForAlignment();
1539         // add to the alignment and set visible
1540         alignment.addAnnotation(copyAnn);
1541         copyAnn.visible = true;
1542       }
1543     }
1544
1545   }
1546
1547   /**
1548    * Set visibility of alignment annotations of specified types (labels), for
1549    * specified sequences. This supports controls like "Show all secondary
1550    * structure", "Hide all Temp factor", etc.
1551    * 
1552    * @al the alignment to scan for annotations
1553    * @param types
1554    *          the types (labels) of annotations to be updated
1555    * @param forSequences
1556    *          if not null, only annotations linked to one of these sequences are
1557    *          in scope for update; if null, acts on all sequence annotations
1558    * @param anyType
1559    *          if this flag is true, 'types' is ignored (label not checked)
1560    * @param doShow
1561    *          if true, set visibility on, else set off
1562    */
1563   public static void showOrHideSequenceAnnotations(AlignmentI al,
1564           Collection<String> types, List<SequenceI> forSequences,
1565           boolean anyType, boolean doShow)
1566   {
1567     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
1568     if (anns != null)
1569     {
1570       for (AlignmentAnnotation aa : anns)
1571       {
1572         if (anyType || types.contains(aa.label))
1573         {
1574           if ((aa.sequenceRef != null) && (forSequences == null
1575                   || forSequences.contains(aa.sequenceRef)))
1576           {
1577             aa.visible = doShow;
1578           }
1579         }
1580       }
1581     }
1582   }
1583
1584   /**
1585    * Returns true if either sequence has a cross-reference to the other
1586    * 
1587    * @param seq1
1588    * @param seq2
1589    * @return
1590    */
1591   public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1592   {
1593     // Note: moved here from class CrossRef as the latter class has dependencies
1594     // not availability to the applet's classpath
1595     return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1596   }
1597
1598   /**
1599    * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1600    * that sequence name is structured as Source|AccessionId.
1601    * 
1602    * @param seq1
1603    * @param seq2
1604    * @return
1605    */
1606   public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1607   {
1608     if (seq1 == null || seq2 == null)
1609     {
1610       return false;
1611     }
1612     String name = seq2.getName();
1613     final List<DBRefEntry> xrefs = seq1.getDBRefs();
1614     if (xrefs != null)
1615     {
1616       for (int ix = 0, nx = xrefs.size(); ix < nx; ix++)
1617       {
1618         DBRefEntry xref = xrefs.get(ix);
1619         String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1620         // case-insensitive test, consistent with DBRefEntry.equalRef()
1621         if (xrefName.equalsIgnoreCase(name))
1622         {
1623           return true;
1624         }
1625       }
1626     }
1627     return false;
1628   }
1629
1630   /**
1631    * Constructs an alignment consisting of the mapped (CDS) regions in the given
1632    * nucleotide sequences, and updates mappings to match. The CDS sequences are
1633    * added to the original alignment's dataset, which is shared by the new
1634    * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1635    * added to the alignment dataset.
1636    * 
1637    * @param dna
1638    *          aligned nucleotide (dna or cds) sequences
1639    * @param dataset
1640    *          the alignment dataset the sequences belong to
1641    * @param products
1642    *          (optional) to restrict results to CDS that map to specified
1643    *          protein products
1644    * @return an alignment whose sequences are the cds-only parts of the dna
1645    *         sequences (or null if no mappings are found)
1646    */
1647   public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1648           AlignmentI dataset, SequenceI[] products)
1649   {
1650     if (dataset == null || dataset.getDataset() != null)
1651     {
1652       throw new IllegalArgumentException(
1653               "IMPLEMENTATION ERROR: dataset.getDataset() must be null!");
1654     }
1655     List<SequenceI> foundSeqs = new ArrayList<>();
1656     List<SequenceI> cdsSeqs = new ArrayList<>();
1657     List<AlignedCodonFrame> mappings = dataset.getCodonFrames();
1658     HashSet<SequenceI> productSeqs = null;
1659     if (products != null)
1660     {
1661       productSeqs = new HashSet<>();
1662       for (SequenceI seq : products)
1663       {
1664         productSeqs.add(seq.getDatasetSequence() == null ? seq
1665                 : seq.getDatasetSequence());
1666       }
1667     }
1668
1669     /*
1670      * Construct CDS sequences from mappings on the alignment dataset.
1671      * The logic is:
1672      * - find the protein product(s) mapped to from each dna sequence
1673      * - if the mapping covers the whole dna sequence (give or take start/stop
1674      *   codon), take the dna as the CDS sequence
1675      * - else search dataset mappings for a suitable dna sequence, i.e. one
1676      *   whose whole sequence is mapped to the protein 
1677      * - if no sequence found, construct one from the dna sequence and mapping
1678      *   (and add it to dataset so it is found if this is repeated)
1679      */
1680     for (SequenceI dnaSeq : dna)
1681     {
1682       SequenceI dnaDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
1683               : dnaSeq.getDatasetSequence();
1684
1685       List<AlignedCodonFrame> seqMappings = MappingUtils
1686               .findMappingsForSequence(dnaSeq, mappings);
1687       for (AlignedCodonFrame mapping : seqMappings)
1688       {
1689         List<Mapping> mappingsFromSequence = mapping
1690                 .getMappingsFromSequence(dnaSeq);
1691
1692         for (Mapping aMapping : mappingsFromSequence)
1693         {
1694           MapList mapList = aMapping.getMap();
1695           if (mapList.getFromRatio() == 1)
1696           {
1697             /*
1698              * not a dna-to-protein mapping (likely dna-to-cds)
1699              */
1700             continue;
1701           }
1702
1703           /*
1704            * skip if mapping is not to one of the target set of proteins
1705            */
1706           SequenceI proteinProduct = aMapping.getTo();
1707           if (productSeqs != null && !productSeqs.contains(proteinProduct))
1708           {
1709             continue;
1710           }
1711
1712           /*
1713            * try to locate the CDS from the dataset mappings;
1714            * guard against duplicate results (for the case that protein has
1715            * dbrefs to both dna and cds sequences)
1716            */
1717           SequenceI cdsSeq = findCdsForProtein(mappings, dnaSeq,
1718                   seqMappings, aMapping);
1719           if (cdsSeq != null)
1720           {
1721             if (!foundSeqs.contains(cdsSeq))
1722             {
1723               foundSeqs.add(cdsSeq);
1724               SequenceI derivedSequence = cdsSeq.deriveSequence();
1725               cdsSeqs.add(derivedSequence);
1726               if (!dataset.getSequences().contains(cdsSeq))
1727               {
1728                 dataset.addSequence(cdsSeq);
1729               }
1730             }
1731             continue;
1732           }
1733
1734           /*
1735            * didn't find mapped CDS sequence - construct it and add
1736            * its dataset sequence to the dataset
1737            */
1738           cdsSeq = makeCdsSequence(dnaSeq.getDatasetSequence(), aMapping,
1739                   dataset).deriveSequence();
1740           // cdsSeq has a name constructed as CDS|<dbref>
1741           // <dbref> will be either the accession for the coding sequence,
1742           // marked in the /via/ dbref to the protein product accession
1743           // or it will be the original nucleotide accession.
1744           SequenceI cdsSeqDss = cdsSeq.getDatasetSequence();
1745
1746           cdsSeqs.add(cdsSeq);
1747
1748           /*
1749            * build the mapping from CDS to protein
1750            */
1751           List<int[]> cdsRange = Collections
1752                   .singletonList(new int[]
1753                   { cdsSeq.getStart(),
1754                       cdsSeq.getLength() + cdsSeq.getStart() - 1 });
1755           MapList cdsToProteinMap = new MapList(cdsRange,
1756                   mapList.getToRanges(), mapList.getFromRatio(),
1757                   mapList.getToRatio());
1758
1759           if (!dataset.getSequences().contains(cdsSeqDss))
1760           {
1761             /*
1762              * if this sequence is a newly created one, add it to the dataset
1763              * and made a CDS to protein mapping (if sequence already exists,
1764              * CDS-to-protein mapping _is_ the transcript-to-protein mapping)
1765              */
1766             dataset.addSequence(cdsSeqDss);
1767             AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
1768             cdsToProteinMapping.addMap(cdsSeqDss, proteinProduct,
1769                     cdsToProteinMap);
1770
1771             /*
1772              * guard against duplicating the mapping if repeating this action
1773              */
1774             if (!mappings.contains(cdsToProteinMapping))
1775             {
1776               mappings.add(cdsToProteinMapping);
1777             }
1778           }
1779
1780           propagateDBRefsToCDS(cdsSeqDss, dnaSeq.getDatasetSequence(),
1781                   proteinProduct, aMapping);
1782           /*
1783            * add another mapping from original 'from' range to CDS
1784            */
1785           AlignedCodonFrame dnaToCdsMapping = new AlignedCodonFrame();
1786           final MapList dnaToCdsMap = new MapList(mapList.getFromRanges(),
1787                   cdsRange, 1, 1);
1788           dnaToCdsMapping.addMap(dnaSeq.getDatasetSequence(), cdsSeqDss,
1789                   dnaToCdsMap);
1790           if (!mappings.contains(dnaToCdsMapping))
1791           {
1792             mappings.add(dnaToCdsMapping);
1793           }
1794
1795           /*
1796            * transfer dna chromosomal loci (if known) to the CDS
1797            * sequence (via the mapping)
1798            */
1799           final MapList cdsToDnaMap = dnaToCdsMap.getInverse();
1800           transferGeneLoci(dnaSeq, cdsToDnaMap, cdsSeq);
1801
1802           /*
1803            * add DBRef with mapping from protein to CDS
1804            * (this enables Get Cross-References from protein alignment)
1805            * This is tricky because we can't have two DBRefs with the
1806            * same source and accession, so need a different accession for
1807            * the CDS from the dna sequence
1808            */
1809
1810           // specific use case:
1811           // Genomic contig ENSCHR:1, contains coding regions for ENSG01,
1812           // ENSG02, ENSG03, with transcripts and products similarly named.
1813           // cannot add distinct dbrefs mapping location on ENSCHR:1 to ENSG01
1814
1815           // JBPNote: ?? can't actually create an example that demonstrates we
1816           // need to
1817           // synthesize an xref.
1818
1819           List<DBRefEntry> primrefs = dnaDss.getPrimaryDBRefs();
1820           for (int ip = 0, np = primrefs.size(); ip < np; ip++)
1821           {
1822             DBRefEntry primRef = primrefs.get(ip);
1823             /*
1824              * create a cross-reference from CDS to the source sequence's
1825              * primary reference and vice versa
1826              */
1827             String source = primRef.getSource();
1828             String version = primRef.getVersion();
1829             DBRefEntry cdsCrossRef = new DBRefEntry(source,
1830                     source + ":" + version, primRef.getAccessionId());
1831             cdsCrossRef
1832                     .setMap(new Mapping(dnaDss, new MapList(cdsToDnaMap)));
1833             cdsSeqDss.addDBRef(cdsCrossRef);
1834
1835             dnaSeq.addDBRef(new DBRefEntry(source, version,
1836                     cdsSeq.getName(), new Mapping(cdsSeqDss, dnaToCdsMap)));
1837             // problem here is that the cross-reference is synthesized -
1838             // cdsSeq.getName() may be like 'CDS|dnaaccession' or
1839             // 'CDS|emblcdsacc'
1840             // assuming cds version same as dna ?!?
1841
1842             DBRefEntry proteinToCdsRef = new DBRefEntry(source, version,
1843                     cdsSeq.getName());
1844             //
1845             proteinToCdsRef.setMap(
1846                     new Mapping(cdsSeqDss, cdsToProteinMap.getInverse()));
1847             proteinProduct.addDBRef(proteinToCdsRef);
1848           }
1849           /*
1850            * transfer any features on dna that overlap the CDS
1851            */
1852           transferFeatures(dnaSeq, cdsSeq, dnaToCdsMap, null,
1853                   SequenceOntologyI.CDS);
1854         }
1855       }
1856     }
1857
1858     AlignmentI cds = new Alignment(
1859             cdsSeqs.toArray(new SequenceI[cdsSeqs.size()]));
1860     cds.setDataset(dataset);
1861
1862     return cds;
1863   }
1864
1865   /**
1866    * Tries to transfer gene loci (dbref to chromosome positions) from fromSeq to
1867    * toSeq, mediated by the given mapping between the sequences
1868    * 
1869    * @param fromSeq
1870    * @param targetToFrom
1871    *          Map
1872    * @param targetSeq
1873    */
1874   protected static void transferGeneLoci(SequenceI fromSeq,
1875           MapList targetToFrom, SequenceI targetSeq)
1876   {
1877     if (targetSeq.getGeneLoci() != null)
1878     {
1879       // already have - don't override
1880       return;
1881     }
1882     GeneLociI fromLoci = fromSeq.getGeneLoci();
1883     if (fromLoci == null)
1884     {
1885       return;
1886     }
1887
1888     MapList newMap = targetToFrom.traverse(fromLoci.getMapping());
1889
1890     if (newMap != null)
1891     {
1892       targetSeq.setGeneLoci(fromLoci.getSpeciesId(),
1893               fromLoci.getAssemblyId(), fromLoci.getChromosomeId(), newMap);
1894     }
1895   }
1896
1897   /**
1898    * A helper method that finds a CDS sequence in the alignment dataset that is
1899    * mapped to the given protein sequence, and either is, or has a mapping from,
1900    * the given dna sequence.
1901    * 
1902    * @param mappings
1903    *          set of all mappings on the dataset
1904    * @param dnaSeq
1905    *          a dna (or cds) sequence we are searching from
1906    * @param seqMappings
1907    *          the set of mappings involving dnaSeq
1908    * @param aMapping
1909    *          a transcript-to-peptide mapping
1910    * @return
1911    */
1912   static SequenceI findCdsForProtein(List<AlignedCodonFrame> mappings,
1913           SequenceI dnaSeq, List<AlignedCodonFrame> seqMappings,
1914           Mapping aMapping)
1915   {
1916     /*
1917      * TODO a better dna-cds-protein mapping data representation to allow easy
1918      * navigation; until then this clunky looping around lists of mappings
1919      */
1920     SequenceI seqDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
1921             : dnaSeq.getDatasetSequence();
1922     SequenceI proteinProduct = aMapping.getTo();
1923
1924     /*
1925      * is this mapping from the whole dna sequence (i.e. CDS)?
1926      * allowing for possible stop codon on dna but not peptide
1927      */
1928     int mappedFromLength = MappingUtils
1929             .getLength(aMapping.getMap().getFromRanges());
1930     int dnaLength = seqDss.getLength();
1931     if (mappedFromLength == dnaLength
1932             || mappedFromLength == dnaLength - CODON_LENGTH)
1933     {
1934       /*
1935        * if sequence has CDS features, this is a transcript with no UTR
1936        * - do not take this as the CDS sequence! (JAL-2789)
1937        */
1938       if (seqDss.getFeatures().getFeaturesByOntology(SequenceOntologyI.CDS)
1939               .isEmpty())
1940       {
1941         return seqDss;
1942       }
1943     }
1944
1945     /*
1946      * looks like we found the dna-to-protein mapping; search for the
1947      * corresponding cds-to-protein mapping
1948      */
1949     List<AlignedCodonFrame> mappingsToPeptide = MappingUtils
1950             .findMappingsForSequence(proteinProduct, mappings);
1951     for (AlignedCodonFrame acf : mappingsToPeptide)
1952     {
1953       for (SequenceToSequenceMapping map : acf.getMappings())
1954       {
1955         Mapping mapping = map.getMapping();
1956         if (mapping != aMapping
1957                 && mapping.getMap().getFromRatio() == CODON_LENGTH
1958                 && proteinProduct == mapping.getTo()
1959                 && seqDss != map.getFromSeq())
1960         {
1961           mappedFromLength = MappingUtils
1962                   .getLength(mapping.getMap().getFromRanges());
1963           if (mappedFromLength == map.getFromSeq().getLength())
1964           {
1965             /*
1966             * found a 3:1 mapping to the protein product which covers
1967             * the whole dna sequence i.e. is from CDS; finally check the CDS
1968             * is mapped from the given dna start sequence
1969             */
1970             SequenceI cdsSeq = map.getFromSeq();
1971             // todo this test is weak if seqMappings contains multiple mappings;
1972             // we get away with it if transcript:cds relationship is 1:1
1973             List<AlignedCodonFrame> dnaToCdsMaps = MappingUtils
1974                     .findMappingsForSequence(cdsSeq, seqMappings);
1975             if (!dnaToCdsMaps.isEmpty())
1976             {
1977               return cdsSeq;
1978             }
1979           }
1980         }
1981       }
1982     }
1983     return null;
1984   }
1985
1986   /**
1987    * Helper method that makes a CDS sequence as defined by the mappings from the
1988    * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1989    * forward or reverse strand).
1990    * 
1991    * @param seq
1992    * @param mapping
1993    * @param dataset
1994    *          - existing dataset. We check for sequences that look like the CDS
1995    *          we are about to construct, if one exists already, then we will
1996    *          just return that one.
1997    * @return CDS sequence (as a dataset sequence)
1998    */
1999   static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping,
2000           AlignmentI dataset)
2001   {
2002     /*
2003      * construct CDS sequence name as "CDS|" with 'from id' held in the mapping
2004      * if set (e.g. EMBL protein_id), else sequence name appended
2005      */
2006     String mapFromId = mapping.getMappedFromId();
2007     final String seqId = "CDS|"
2008             + (mapFromId != null ? mapFromId : seq.getName());
2009
2010     SequenceI newSeq = null;
2011
2012     /*
2013      * construct CDS sequence by splicing mapped from ranges
2014      */
2015     char[] seqChars = seq.getSequence();
2016     List<int[]> fromRanges = mapping.getMap().getFromRanges();
2017     int cdsWidth = MappingUtils.getLength(fromRanges);
2018     char[] newSeqChars = new char[cdsWidth];
2019
2020     int newPos = 0;
2021     for (int[] range : fromRanges)
2022     {
2023       if (range[0] <= range[1])
2024       {
2025         // forward strand mapping - just copy the range
2026         int length = range[1] - range[0] + 1;
2027         System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
2028                 length);
2029         newPos += length;
2030       }
2031       else
2032       {
2033         // reverse strand mapping - copy and complement one by one
2034         for (int i = range[0]; i >= range[1]; i--)
2035         {
2036           newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
2037         }
2038       }
2039
2040       newSeq = new Sequence(seqId, newSeqChars, 1, newPos);
2041     }
2042
2043     if (dataset != null)
2044     {
2045       SequenceI[] matches = dataset.findSequenceMatch(newSeq.getName());
2046       if (matches != null)
2047       {
2048         boolean matched = false;
2049         for (SequenceI mtch : matches)
2050         {
2051           if (mtch.getStart() != newSeq.getStart())
2052           {
2053             continue;
2054           }
2055           if (mtch.getEnd() != newSeq.getEnd())
2056           {
2057             continue;
2058           }
2059           if (!Arrays.equals(mtch.getSequence(), newSeq.getSequence()))
2060           {
2061             continue;
2062           }
2063           if (!matched)
2064           {
2065             matched = true;
2066             newSeq = mtch;
2067           }
2068           else
2069           {
2070             Console.error(
2071                     "JAL-2154 regression: warning - found (and ignored) a duplicate CDS sequence:"
2072                             + mtch.toString());
2073           }
2074         }
2075       }
2076     }
2077     // newSeq.setDescription(mapFromId);
2078
2079     return newSeq;
2080   }
2081
2082   /**
2083    * Adds any DBRefEntrys to cdsSeq from contig that have a Mapping congruent to
2084    * the given mapping.
2085    * 
2086    * @param cdsSeq
2087    * @param contig
2088    * @param proteinProduct
2089    * @param mapping
2090    * @return list of DBRefEntrys added
2091    */
2092   protected static List<DBRefEntry> propagateDBRefsToCDS(SequenceI cdsSeq,
2093           SequenceI contig, SequenceI proteinProduct, Mapping mapping)
2094   {
2095
2096     // gather direct refs from contig congruent with mapping
2097     List<DBRefEntry> direct = new ArrayList<>();
2098     HashSet<String> directSources = new HashSet<>();
2099
2100     List<DBRefEntry> refs = contig.getDBRefs();
2101     if (refs != null)
2102     {
2103       for (int ib = 0, nb = refs.size(); ib < nb; ib++)
2104       {
2105         DBRefEntry dbr = refs.get(ib);
2106         MapList map;
2107         if (dbr.hasMap() && (map = dbr.getMap().getMap()).isTripletMap())
2108         {
2109           // check if map is the CDS mapping
2110           if (mapping.getMap().equals(map))
2111           {
2112             direct.add(dbr);
2113             directSources.add(dbr.getSource());
2114           }
2115         }
2116       }
2117     }
2118     List<DBRefEntry> onSource = DBRefUtils.selectRefs(
2119             proteinProduct.getDBRefs(),
2120             directSources.toArray(new String[0]));
2121     List<DBRefEntry> propagated = new ArrayList<>();
2122
2123     // and generate appropriate mappings
2124     for (int ic = 0, nc = direct.size(); ic < nc; ic++)
2125     {
2126       DBRefEntry cdsref = direct.get(ic);
2127       Mapping m = cdsref.getMap();
2128       // clone maplist and mapping
2129       MapList cdsposmap = new MapList(
2130               Arrays.asList(new int[][]
2131               { new int[] { cdsSeq.getStart(), cdsSeq.getEnd() } }),
2132               m.getMap().getToRanges(), 3, 1);
2133       Mapping cdsmap = new Mapping(m.getTo(), m.getMap());
2134
2135       // create dbref
2136       DBRefEntry newref = new DBRefEntry(cdsref.getSource(),
2137               cdsref.getVersion(), cdsref.getAccessionId(),
2138               new Mapping(cdsmap.getTo(), cdsposmap));
2139
2140       // and see if we can map to the protein product for this mapping.
2141       // onSource is the filtered set of accessions on protein that we are
2142       // tranferring, so we assume accession is the same.
2143       if (cdsmap.getTo() == null && onSource != null)
2144       {
2145         List<DBRefEntry> sourceRefs = DBRefUtils.searchRefs(onSource,
2146                 cdsref.getAccessionId());
2147         if (sourceRefs != null)
2148         {
2149           for (DBRefEntry srcref : sourceRefs)
2150           {
2151             if (srcref.getSource().equalsIgnoreCase(cdsref.getSource()))
2152             {
2153               // we have found a complementary dbref on the protein product, so
2154               // update mapping's getTo
2155               newref.getMap().setTo(proteinProduct);
2156             }
2157           }
2158         }
2159       }
2160       cdsSeq.addDBRef(newref);
2161       propagated.add(newref);
2162     }
2163     return propagated;
2164   }
2165
2166   /**
2167    * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
2168    * feature start/end ranges, optionally omitting specified feature types.
2169    * Returns the number of features copied.
2170    * 
2171    * @param fromSeq
2172    * @param toSeq
2173    * @param mapping
2174    *          the mapping from 'fromSeq' to 'toSeq'
2175    * @param select
2176    *          if not null, only features of this type are copied (including
2177    *          subtypes in the Sequence Ontology)
2178    * @param omitting
2179    */
2180   protected static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
2181           MapList mapping, String select, String... omitting)
2182   {
2183     SequenceI copyTo = toSeq;
2184     while (copyTo.getDatasetSequence() != null)
2185     {
2186       copyTo = copyTo.getDatasetSequence();
2187     }
2188     if (fromSeq == copyTo || fromSeq.getDatasetSequence() == copyTo)
2189     {
2190       return 0; // shared dataset sequence
2191     }
2192
2193     /*
2194      * get features, optionally restricted by an ontology term
2195      */
2196     List<SequenceFeature> sfs = select == null
2197             ? fromSeq.getFeatures().getPositionalFeatures()
2198             : fromSeq.getFeatures().getFeaturesByOntology(select);
2199
2200     int count = 0;
2201     for (SequenceFeature sf : sfs)
2202     {
2203       String type = sf.getType();
2204       boolean omit = false;
2205       for (String toOmit : omitting)
2206       {
2207         if (type.equals(toOmit))
2208         {
2209           omit = true;
2210         }
2211       }
2212       if (omit)
2213       {
2214         continue;
2215       }
2216
2217       /*
2218        * locate the mapped range - null if either start or end is
2219        * not mapped (no partial overlaps are calculated)
2220        */
2221       int start = sf.getBegin();
2222       int end = sf.getEnd();
2223       int[] mappedTo = mapping.locateInTo(start, end);
2224       /*
2225        * if whole exon range doesn't map, try interpreting it
2226        * as 5' or 3' exon overlapping the CDS range
2227        */
2228       if (mappedTo == null)
2229       {
2230         mappedTo = mapping.locateInTo(end, end);
2231         if (mappedTo != null)
2232         {
2233           /*
2234            * end of exon is in CDS range - 5' overlap
2235            * to a range from the start of the peptide
2236            */
2237           mappedTo[0] = 1;
2238         }
2239       }
2240       if (mappedTo == null)
2241       {
2242         mappedTo = mapping.locateInTo(start, start);
2243         if (mappedTo != null)
2244         {
2245           /*
2246            * start of exon is in CDS range - 3' overlap
2247            * to a range up to the end of the peptide
2248            */
2249           mappedTo[1] = toSeq.getLength();
2250         }
2251       }
2252       if (mappedTo != null)
2253       {
2254         int newBegin = Math.min(mappedTo[0], mappedTo[1]);
2255         int newEnd = Math.max(mappedTo[0], mappedTo[1]);
2256         SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
2257                 sf.getFeatureGroup(), sf.getScore());
2258         copyTo.addSequenceFeature(copy);
2259         count++;
2260       }
2261     }
2262     return count;
2263   }
2264
2265   /**
2266    * Returns a mapping from dna to protein by inspecting sequence features of
2267    * type "CDS" on the dna. A mapping is constructed if the total CDS feature
2268    * length is 3 times the peptide length (optionally after dropping a trailing
2269    * stop codon). This method does not check whether the CDS nucleotide sequence
2270    * translates to the peptide sequence.
2271    * 
2272    * @param dnaSeq
2273    * @param proteinSeq
2274    * @return
2275    */
2276   public static MapList mapCdsToProtein(SequenceI dnaSeq,
2277           SequenceI proteinSeq)
2278   {
2279     List<int[]> ranges = findCdsPositions(dnaSeq);
2280     int mappedDnaLength = MappingUtils.getLength(ranges);
2281
2282     /*
2283      * if not a whole number of codons, truncate mapping
2284      */
2285     int codonRemainder = mappedDnaLength % CODON_LENGTH;
2286     if (codonRemainder > 0)
2287     {
2288       mappedDnaLength -= codonRemainder;
2289       MappingUtils.removeEndPositions(codonRemainder, ranges);
2290     }
2291
2292     int proteinLength = proteinSeq.getLength();
2293     int proteinStart = proteinSeq.getStart();
2294     int proteinEnd = proteinSeq.getEnd();
2295
2296     /*
2297      * incomplete start codon may mean X at start of peptide
2298      * we ignore both for mapping purposes
2299      */
2300     if (proteinSeq.getCharAt(0) == 'X')
2301     {
2302       // todo JAL-2022 support startPhase > 0
2303       proteinStart++;
2304       proteinLength--;
2305     }
2306     List<int[]> proteinRange = new ArrayList<>();
2307
2308     /*
2309      * dna length should map to protein (or protein plus stop codon)
2310      */
2311     int codesForResidues = mappedDnaLength / CODON_LENGTH;
2312     if (codesForResidues == (proteinLength + 1))
2313     {
2314       // assuming extra codon is for STOP and not in peptide
2315       // todo: check trailing codon is indeed a STOP codon
2316       codesForResidues--;
2317       mappedDnaLength -= CODON_LENGTH;
2318       MappingUtils.removeEndPositions(CODON_LENGTH, ranges);
2319     }
2320
2321     if (codesForResidues == proteinLength)
2322     {
2323       proteinRange.add(new int[] { proteinStart, proteinEnd });
2324       return new MapList(ranges, proteinRange, CODON_LENGTH, 1);
2325     }
2326     return null;
2327   }
2328
2329   /**
2330    * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
2331    * [start, end] positions of sequence features of type "CDS" (or a sub-type of
2332    * CDS in the Sequence Ontology). The ranges are sorted into ascending start
2333    * position order, so this method is only valid for linear CDS in the same
2334    * sense as the protein product.
2335    * 
2336    * @param dnaSeq
2337    * @return
2338    */
2339   protected static List<int[]> findCdsPositions(SequenceI dnaSeq)
2340   {
2341     List<int[]> result = new ArrayList<>();
2342
2343     List<SequenceFeature> sfs = dnaSeq.getFeatures()
2344             .getFeaturesByOntology(SequenceOntologyI.CDS);
2345     if (sfs.isEmpty())
2346     {
2347       return result;
2348     }
2349     SequenceFeatures.sortFeatures(sfs, true);
2350
2351     for (SequenceFeature sf : sfs)
2352     {
2353       int phase = 0;
2354       try
2355       {
2356         String s = sf.getPhase();
2357         if (s != null)
2358         {
2359           phase = Integer.parseInt(s);
2360         }
2361       } catch (NumberFormatException e)
2362       {
2363         // leave as zero
2364       }
2365       /*
2366        * phase > 0 on first codon means 5' incomplete - skip to the start
2367        * of the next codon; example ENST00000496384
2368        */
2369       int begin = sf.getBegin();
2370       int end = sf.getEnd();
2371       if (result.isEmpty() && phase > 0)
2372       {
2373         begin += phase;
2374         if (begin > end)
2375         {
2376           // shouldn't happen!
2377           System.err
2378                   .println("Error: start phase extends beyond start CDS in "
2379                           + dnaSeq.getName());
2380         }
2381       }
2382       result.add(new int[] { begin, end });
2383     }
2384
2385     /*
2386      * Finally sort ranges by start position. This avoids a dependency on 
2387      * keeping features in order on the sequence (if they are in order anyway,
2388      * the sort will have almost no work to do). The implicit assumption is CDS
2389      * ranges are assembled in order. Other cases should not use this method,
2390      * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
2391      */
2392     Collections.sort(result, IntRangeComparator.ASCENDING);
2393     return result;
2394   }
2395
2396   /**
2397    * Makes an alignment with a copy of the given sequences, adding in any
2398    * non-redundant sequences which are mapped to by the cross-referenced
2399    * sequences.
2400    * 
2401    * @param seqs
2402    * @param xrefs
2403    * @param dataset
2404    *          the alignment dataset shared by the new copy
2405    * @return
2406    */
2407   public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2408           SequenceI[] xrefs, AlignmentI dataset)
2409   {
2410     AlignmentI copy = new Alignment(new Alignment(seqs));
2411     copy.setDataset(dataset);
2412     boolean isProtein = !copy.isNucleotide();
2413     SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2414     if (xrefs != null)
2415     {
2416       // BH 2019.01.25 recoded to remove iterators
2417
2418       for (int ix = 0, nx = xrefs.length; ix < nx; ix++)
2419       {
2420         SequenceI xref = xrefs[ix];
2421         List<DBRefEntry> dbrefs = xref.getDBRefs();
2422         if (dbrefs != null)
2423         {
2424           for (int ir = 0, nir = dbrefs.size(); ir < nir; ir++)
2425           {
2426             DBRefEntry dbref = dbrefs.get(ir);
2427             Mapping map = dbref.getMap();
2428             SequenceI mto;
2429             if (map == null || (mto = map.getTo()) == null
2430                     || mto.isProtein() != isProtein)
2431             {
2432               continue;
2433             }
2434             SequenceI mappedTo = mto;
2435             SequenceI match = matcher.findIdMatch(mappedTo);
2436             if (match == null)
2437             {
2438               matcher.add(mappedTo);
2439               copy.addSequence(mappedTo);
2440             }
2441           }
2442         }
2443       }
2444     }
2445     return copy;
2446   }
2447
2448   /**
2449    * Try to align sequences in 'unaligned' to match the alignment of their
2450    * mapped regions in 'aligned'. For example, could use this to align CDS
2451    * sequences which are mapped to their parent cDNA sequences.
2452    * 
2453    * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2454    * dna-to-protein or protein-to-dna use alternative methods.
2455    * 
2456    * @param unaligned
2457    *          sequences to be aligned
2458    * @param aligned
2459    *          holds aligned sequences and their mappings
2460    * @return
2461    */
2462   public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2463   {
2464     /*
2465      * easy case - aligning a copy of aligned sequences
2466      */
2467     if (alignAsSameSequences(unaligned, aligned))
2468     {
2469       return unaligned.getHeight();
2470     }
2471
2472     /*
2473      * fancy case - aligning via mappings between sequences
2474      */
2475     List<SequenceI> unmapped = new ArrayList<>();
2476     Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2477             unaligned, aligned, unmapped);
2478     int width = columnMap.size();
2479     char gap = unaligned.getGapCharacter();
2480     int realignedCount = 0;
2481     // TODO: verify this loop scales sensibly for very wide/high alignments
2482
2483     for (SequenceI seq : unaligned.getSequences())
2484     {
2485       if (!unmapped.contains(seq))
2486       {
2487         char[] newSeq = new char[width];
2488         Arrays.fill(newSeq, gap); // JBPComment - doubt this is faster than the
2489                                   // Integer iteration below
2490         int newCol = 0;
2491         int lastCol = 0;
2492
2493         /*
2494          * traverse the map to find columns populated
2495          * by our sequence
2496          */
2497         for (Integer column : columnMap.keySet())
2498         {
2499           Character c = columnMap.get(column).get(seq);
2500           if (c != null)
2501           {
2502             /*
2503              * sequence has a character at this position
2504              * 
2505              */
2506             newSeq[newCol] = c;
2507             lastCol = newCol;
2508           }
2509           newCol++;
2510         }
2511
2512         /*
2513          * trim trailing gaps
2514          */
2515         if (lastCol < width)
2516         {
2517           char[] tmp = new char[lastCol + 1];
2518           System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2519           newSeq = tmp;
2520         }
2521         // TODO: optimise SequenceI to avoid char[]->String->char[]
2522         seq.setSequence(String.valueOf(newSeq));
2523         realignedCount++;
2524       }
2525     }
2526     return realignedCount;
2527   }
2528
2529   /**
2530    * If unaligned and aligned sequences share the same dataset sequences, then
2531    * simply copies the aligned sequences to the unaligned sequences and returns
2532    * true; else returns false
2533    * 
2534    * @param unaligned
2535    *          - sequences to be aligned based on aligned
2536    * @param aligned
2537    *          - 'guide' alignment containing sequences derived from same dataset
2538    *          as unaligned
2539    * @return
2540    */
2541   static boolean alignAsSameSequences(AlignmentI unaligned,
2542           AlignmentI aligned)
2543   {
2544     if (aligned.getDataset() == null || unaligned.getDataset() == null)
2545     {
2546       return false; // should only pass alignments with datasets here
2547     }
2548
2549     // map from dataset sequence to alignment sequence(s)
2550     Map<SequenceI, List<SequenceI>> alignedDatasets = new HashMap<>();
2551     for (SequenceI seq : aligned.getSequences())
2552     {
2553       SequenceI ds = seq.getDatasetSequence();
2554       if (alignedDatasets.get(ds) == null)
2555       {
2556         alignedDatasets.put(ds, new ArrayList<SequenceI>());
2557       }
2558       alignedDatasets.get(ds).add(seq);
2559     }
2560
2561     /*
2562      * first pass - check whether all sequences to be aligned share a 
2563      * dataset sequence with an aligned sequence; also note the leftmost
2564      * ungapped column from which to copy
2565      */
2566     int leftmost = Integer.MAX_VALUE;
2567     for (SequenceI seq : unaligned.getSequences())
2568     {
2569       final SequenceI ds = seq.getDatasetSequence();
2570       if (!alignedDatasets.containsKey(ds))
2571       {
2572         return false;
2573       }
2574       SequenceI alignedSeq = alignedDatasets.get(ds).get(0);
2575       int startCol = alignedSeq.findIndex(seq.getStart()); // 1..
2576       leftmost = Math.min(leftmost, startCol);
2577     }
2578
2579     /*
2580      * second pass - copy aligned sequences;
2581      * heuristic rule: pair off sequences in order for the case where 
2582      * more than one shares the same dataset sequence 
2583      */
2584     final char gapCharacter = aligned.getGapCharacter();
2585     for (SequenceI seq : unaligned.getSequences())
2586     {
2587       List<SequenceI> alignedSequences = alignedDatasets
2588               .get(seq.getDatasetSequence());
2589       if (alignedSequences.isEmpty())
2590       {
2591         /*
2592          * defensive check - shouldn't happen! (JAL-3536)
2593          */
2594         continue;
2595       }
2596       SequenceI alignedSeq = alignedSequences.get(0);
2597
2598       /*
2599        * gap fill for leading (5') UTR if any
2600        */
2601       // TODO this copies intron columns - wrong!
2602       int startCol = alignedSeq.findIndex(seq.getStart()); // 1..
2603       int endCol = alignedSeq.findIndex(seq.getEnd());
2604       char[] seqchars = new char[endCol - leftmost + 1];
2605       Arrays.fill(seqchars, gapCharacter);
2606       char[] toCopy = alignedSeq.getSequence(startCol - 1, endCol);
2607       System.arraycopy(toCopy, 0, seqchars, startCol - leftmost,
2608               toCopy.length);
2609       seq.setSequence(String.valueOf(seqchars));
2610       if (alignedSequences.size() > 0)
2611       {
2612         // pop off aligned sequences (except the last one)
2613         alignedSequences.remove(0);
2614       }
2615     }
2616
2617     /*
2618      * finally remove gapped columns (e.g. introns)
2619      */
2620     new RemoveGapColCommand("", unaligned.getSequencesArray(), 0,
2621             unaligned.getWidth() - 1, unaligned);
2622
2623     return true;
2624   }
2625
2626   /**
2627    * Returns a map whose key is alignment column number (base 1), and whose
2628    * values are a map of sequence characters in that column.
2629    * 
2630    * @param unaligned
2631    * @param aligned
2632    * @param unmapped
2633    * @return
2634    */
2635   static SortedMap<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2636           AlignmentI unaligned, AlignmentI aligned,
2637           List<SequenceI> unmapped)
2638   {
2639     /*
2640      * Map will hold, for each aligned column position, a map of
2641      * {unalignedSequence, characterPerSequence} at that position.
2642      * TreeMap keeps the entries in ascending column order. 
2643      */
2644     SortedMap<Integer, Map<SequenceI, Character>> map = new TreeMap<>();
2645
2646     /*
2647      * record any sequences that have no mapping so can't be realigned
2648      */
2649     unmapped.addAll(unaligned.getSequences());
2650
2651     List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2652
2653     for (SequenceI seq : unaligned.getSequences())
2654     {
2655       for (AlignedCodonFrame mapping : mappings)
2656       {
2657         SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2658         if (fromSeq != null)
2659         {
2660           Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2661           if (addMappedPositions(seq, fromSeq, seqMap, map))
2662           {
2663             unmapped.remove(seq);
2664           }
2665         }
2666       }
2667     }
2668     return map;
2669   }
2670
2671   /**
2672    * Helper method that adds to a map the mapped column positions of a sequence.
2673    * <br>
2674    * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2675    * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2676    * sequence.
2677    * 
2678    * @param seq
2679    *          the sequence whose column positions we are recording
2680    * @param fromSeq
2681    *          a sequence that is mapped to the first sequence
2682    * @param seqMap
2683    *          the mapping from 'fromSeq' to 'seq'
2684    * @param map
2685    *          a map to add the column positions (in fromSeq) of the mapped
2686    *          positions of seq
2687    * @return
2688    */
2689   static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2690           Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2691   {
2692     if (seqMap == null)
2693     {
2694       return false;
2695     }
2696
2697     /*
2698      * invert mapping if it is from unaligned to aligned sequence
2699      */
2700     if (seqMap.getTo() == fromSeq.getDatasetSequence())
2701     {
2702       seqMap = new Mapping(seq.getDatasetSequence(),
2703               seqMap.getMap().getInverse());
2704     }
2705
2706     int toStart = seq.getStart();
2707
2708     /*
2709      * traverse [start, end, start, end...] ranges in fromSeq
2710      */
2711     for (int[] fromRange : seqMap.getMap().getFromRanges())
2712     {
2713       for (int i = 0; i < fromRange.length - 1; i += 2)
2714       {
2715         boolean forward = fromRange[i + 1] >= fromRange[i];
2716
2717         /*
2718          * find the range mapped to (sequence positions base 1)
2719          */
2720         int[] range = seqMap.locateMappedRange(fromRange[i],
2721                 fromRange[i + 1]);
2722         if (range == null)
2723         {
2724           System.err.println("Error in mapping " + seqMap + " from "
2725                   + fromSeq.getName());
2726           return false;
2727         }
2728         int fromCol = fromSeq.findIndex(fromRange[i]);
2729         int mappedCharPos = range[0];
2730
2731         /*
2732          * walk over the 'from' aligned sequence in forward or reverse
2733          * direction; when a non-gap is found, record the column position
2734          * of the next character of the mapped-to sequence; stop when all
2735          * the characters of the range have been counted
2736          */
2737         while (mappedCharPos <= range[1] && fromCol <= fromSeq.getLength()
2738                 && fromCol >= 0)
2739         {
2740           if (!Comparison.isGap(fromSeq.getCharAt(fromCol - 1)))
2741           {
2742             /*
2743              * mapped from sequence has a character in this column
2744              * record the column position for the mapped to character
2745              */
2746             Map<SequenceI, Character> seqsMap = map.get(fromCol);
2747             if (seqsMap == null)
2748             {
2749               seqsMap = new HashMap<>();
2750               map.put(fromCol, seqsMap);
2751             }
2752             seqsMap.put(seq, seq.getCharAt(mappedCharPos - toStart));
2753             mappedCharPos++;
2754           }
2755           fromCol += (forward ? 1 : -1);
2756         }
2757       }
2758     }
2759     return true;
2760   }
2761
2762   // strictly temporary hack until proper criteria for aligning protein to cds
2763   // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2764   public static boolean looksLikeEnsembl(AlignmentI alignment)
2765   {
2766     for (SequenceI seq : alignment.getSequences())
2767     {
2768       String name = seq.getName();
2769       if (!name.startsWith("ENSG") && !name.startsWith("ENST"))
2770       {
2771         return false;
2772       }
2773     }
2774     return true;
2775   }
2776 }