JAL-1705 reworked AlignmentUtils.makeCdsAlignment and associated code
[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 jalview.datamodel.AlignedCodon;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.IncompleteCodonException;
30 import jalview.datamodel.Mapping;
31 import jalview.datamodel.Sequence;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.io.gff.SequenceOntologyFactory;
36 import jalview.io.gff.SequenceOntologyI;
37 import jalview.schemes.ResidueProperties;
38 import jalview.util.Comparison;
39 import jalview.util.MapList;
40 import jalview.util.MappingUtils;
41 import jalview.util.StringUtils;
42
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Collection;
46 import java.util.Collections;
47 import java.util.Comparator;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.Iterator;
51 import java.util.LinkedHashMap;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Map.Entry;
55 import java.util.NoSuchElementException;
56 import java.util.Set;
57 import java.util.TreeMap;
58
59 /**
60  * grab bag of useful alignment manipulation operations Expect these to be
61  * refactored elsewhere at some point.
62  * 
63  * @author jimp
64  * 
65  */
66 public class AlignmentUtils
67 {
68
69   /**
70    * given an existing alignment, create a new alignment including all, or up to
71    * flankSize additional symbols from each sequence's dataset sequence
72    * 
73    * @param core
74    * @param flankSize
75    * @return AlignmentI
76    */
77   public static AlignmentI expandContext(AlignmentI core, int flankSize)
78   {
79     List<SequenceI> sq = new ArrayList<SequenceI>();
80     int maxoffset = 0;
81     for (SequenceI s : core.getSequences())
82     {
83       SequenceI newSeq = s.deriveSequence();
84       final int newSeqStart = newSeq.getStart() - 1;
85       if (newSeqStart > maxoffset
86               && newSeq.getDatasetSequence().getStart() < s.getStart())
87       {
88         maxoffset = newSeqStart;
89       }
90       sq.add(newSeq);
91     }
92     if (flankSize > -1)
93     {
94       maxoffset = Math.min(maxoffset, flankSize);
95     }
96
97     /*
98      * now add offset left and right to create an expanded alignment
99      */
100     for (SequenceI s : sq)
101     {
102       SequenceI ds = s;
103       while (ds.getDatasetSequence() != null)
104       {
105         ds = ds.getDatasetSequence();
106       }
107       int s_end = s.findPosition(s.getStart() + s.getLength());
108       // find available flanking residues for sequence
109       int ustream_ds = s.getStart() - ds.getStart();
110       int dstream_ds = ds.getEnd() - s_end;
111
112       // build new flanked sequence
113
114       // compute gap padding to start of flanking sequence
115       int offset = maxoffset - ustream_ds;
116
117       // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
118       if (flankSize >= 0)
119       {
120         if (flankSize < ustream_ds)
121         {
122           // take up to flankSize residues
123           offset = maxoffset - flankSize;
124           ustream_ds = flankSize;
125         }
126         if (flankSize <= dstream_ds)
127         {
128           dstream_ds = flankSize - 1;
129         }
130       }
131       // TODO use Character.toLowerCase to avoid creating String objects?
132       char[] upstream = new String(ds.getSequence(s.getStart() - 1
133               - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
134       char[] downstream = new String(ds.getSequence(s_end - 1, s_end
135               + dstream_ds)).toLowerCase().toCharArray();
136       char[] coreseq = s.getSequence();
137       char[] nseq = new char[offset + upstream.length + downstream.length
138               + coreseq.length];
139       char c = core.getGapCharacter();
140
141       int p = 0;
142       for (; p < offset; p++)
143       {
144         nseq[p] = c;
145       }
146
147       System.arraycopy(upstream, 0, nseq, p, upstream.length);
148       System.arraycopy(coreseq, 0, nseq, p + upstream.length,
149               coreseq.length);
150       System.arraycopy(downstream, 0, nseq, p + coreseq.length
151               + upstream.length, downstream.length);
152       s.setSequence(new String(nseq));
153       s.setStart(s.getStart() - ustream_ds);
154       s.setEnd(s_end + downstream.length);
155     }
156     AlignmentI newAl = new jalview.datamodel.Alignment(
157             sq.toArray(new SequenceI[0]));
158     for (SequenceI s : sq)
159     {
160       if (s.getAnnotation() != null)
161       {
162         for (AlignmentAnnotation aa : s.getAnnotation())
163         {
164           aa.adjustForAlignment(); // JAL-1712 fix
165           newAl.addAnnotation(aa);
166         }
167       }
168     }
169     newAl.setDataset(core.getDataset());
170     return newAl;
171   }
172
173   /**
174    * Returns the index (zero-based position) of a sequence in an alignment, or
175    * -1 if not found.
176    * 
177    * @param al
178    * @param seq
179    * @return
180    */
181   public static int getSequenceIndex(AlignmentI al, SequenceI seq)
182   {
183     int result = -1;
184     int pos = 0;
185     for (SequenceI alSeq : al.getSequences())
186     {
187       if (alSeq == seq)
188       {
189         result = pos;
190         break;
191       }
192       pos++;
193     }
194     return result;
195   }
196
197   /**
198    * Returns a map of lists of sequences in the alignment, keyed by sequence
199    * name. For use in mapping between different alignment views of the same
200    * sequences.
201    * 
202    * @see jalview.datamodel.AlignmentI#getSequencesByName()
203    */
204   public static Map<String, List<SequenceI>> getSequencesByName(
205           AlignmentI al)
206   {
207     Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
208     for (SequenceI seq : al.getSequences())
209     {
210       String name = seq.getName();
211       if (name != null)
212       {
213         List<SequenceI> seqs = theMap.get(name);
214         if (seqs == null)
215         {
216           seqs = new ArrayList<SequenceI>();
217           theMap.put(name, seqs);
218         }
219         seqs.add(seq);
220       }
221     }
222     return theMap;
223   }
224
225   /**
226    * Build mapping of protein to cDNA alignment. Mappings are made between
227    * sequences where the cDNA translates to the protein sequence. Any new
228    * mappings are added to the protein alignment. Returns true if any mappings
229    * either already exist or were added, else false.
230    * 
231    * @param proteinAlignment
232    * @param cdnaAlignment
233    * @return
234    */
235   public static boolean mapProteinAlignmentToCdna(
236           final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
237   {
238     if (proteinAlignment == null || cdnaAlignment == null)
239     {
240       return false;
241     }
242
243     Set<SequenceI> mappedDna = new HashSet<SequenceI>();
244     Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
245
246     /*
247      * First pass - map sequences where cross-references exist. This include
248      * 1-to-many mappings to support, for example, variant cDNA.
249      */
250     boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
251             cdnaAlignment, mappedDna, mappedProtein, true);
252
253     /*
254      * Second pass - map sequences where no cross-references exist. This only
255      * does 1-to-1 mappings and assumes corresponding sequences are in the same
256      * order in the alignments.
257      */
258     mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
259             mappedDna, mappedProtein, false);
260     return mappingPerformed;
261   }
262
263   /**
264    * Make mappings between compatible sequences (where the cDNA translation
265    * matches the protein).
266    * 
267    * @param proteinAlignment
268    * @param cdnaAlignment
269    * @param mappedDna
270    *          a set of mapped DNA sequences (to add to)
271    * @param mappedProtein
272    *          a set of mapped Protein sequences (to add to)
273    * @param xrefsOnly
274    *          if true, only map sequences where xrefs exist
275    * @return
276    */
277   protected static boolean mapProteinToCdna(
278           final AlignmentI proteinAlignment,
279           final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
280           Set<SequenceI> mappedProtein, boolean xrefsOnly)
281   {
282     boolean mappingExistsOrAdded = false;
283     List<SequenceI> thisSeqs = proteinAlignment.getSequences();
284     for (SequenceI aaSeq : thisSeqs)
285     {
286       boolean proteinMapped = false;
287       AlignedCodonFrame acf = new AlignedCodonFrame();
288
289       for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
290       {
291         /*
292          * Always try to map if sequences have xref to each other; this supports
293          * variant cDNA or alternative splicing for a protein sequence.
294          * 
295          * If no xrefs, try to map progressively, assuming that alignments have
296          * mappable sequences in corresponding order. These are not
297          * many-to-many, as that would risk mixing species with similar cDNA
298          * sequences.
299          */
300         if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
301         {
302           continue;
303         }
304
305         /*
306          * Don't map non-xrefd sequences more than once each. This heuristic
307          * allows us to pair up similar sequences in ordered alignments.
308          */
309         if (!xrefsOnly
310                 && (mappedProtein.contains(aaSeq) || mappedDna
311                         .contains(cdnaSeq)))
312         {
313           continue;
314         }
315         if (mappingExists(proteinAlignment.getCodonFrames(),
316                 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
317         {
318           mappingExistsOrAdded = true;
319         }
320         else
321         {
322           MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
323           if (map != null)
324           {
325             acf.addMap(cdnaSeq, aaSeq, map);
326             mappingExistsOrAdded = true;
327             proteinMapped = true;
328             mappedDna.add(cdnaSeq);
329             mappedProtein.add(aaSeq);
330           }
331         }
332       }
333       if (proteinMapped)
334       {
335         proteinAlignment.addCodonFrame(acf);
336       }
337     }
338     return mappingExistsOrAdded;
339   }
340
341   /**
342    * Answers true if the mappings include one between the given (dataset)
343    * sequences.
344    */
345   public static boolean mappingExists(List<AlignedCodonFrame> mappings,
346           SequenceI aaSeq, SequenceI cdnaSeq)
347   {
348     if (mappings != null)
349     {
350       for (AlignedCodonFrame acf : mappings)
351       {
352         if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
353         {
354           return true;
355         }
356       }
357     }
358     return false;
359   }
360
361   /**
362    * Builds a mapping (if possible) of a cDNA to a protein sequence.
363    * <ul>
364    * <li>first checks if the cdna translates exactly to the protein sequence</li>
365    * <li>else checks for translation after removing a STOP codon</li>
366    * <li>else checks for translation after removing a START codon</li>
367    * <li>if that fails, inspect CDS features on the cDNA sequence</li>
368    * </ul>
369    * Returns null if no mapping is determined.
370    * 
371    * @param proteinSeq
372    *          the aligned protein sequence
373    * @param cdnaSeq
374    *          the aligned cdna sequence
375    * @return
376    */
377   public static MapList mapCdnaToProtein(SequenceI proteinSeq,
378           SequenceI cdnaSeq)
379   {
380     /*
381      * Here we handle either dataset sequence set (desktop) or absent (applet).
382      * Use only the char[] form of the sequence to avoid creating possibly large
383      * String objects.
384      */
385     final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
386     char[] aaSeqChars = proteinDataset != null ? proteinDataset
387             .getSequence() : proteinSeq.getSequence();
388     final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
389     char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
390             : cdnaSeq.getSequence();
391     if (aaSeqChars == null || cdnaSeqChars == null)
392     {
393       return null;
394     }
395
396     /*
397      * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
398      */
399     final int mappedLength = 3 * aaSeqChars.length;
400     int cdnaLength = cdnaSeqChars.length;
401     int cdnaStart = cdnaSeq.getStart();
402     int cdnaEnd = cdnaSeq.getEnd();
403     final int proteinStart = proteinSeq.getStart();
404     final int proteinEnd = proteinSeq.getEnd();
405
406     /*
407      * If lengths don't match, try ignoring stop codon (if present)
408      */
409     if (cdnaLength != mappedLength && cdnaLength > 2)
410     {
411       String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
412               .toUpperCase();
413       for (String stop : ResidueProperties.STOP)
414       {
415         if (lastCodon.equals(stop))
416         {
417           cdnaEnd -= 3;
418           cdnaLength -= 3;
419           break;
420         }
421       }
422     }
423
424     /*
425      * If lengths still don't match, try ignoring start codon.
426      */
427     int startOffset = 0;
428     if (cdnaLength != mappedLength
429             && cdnaLength > 2
430             && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
431                     .equals(ResidueProperties.START))
432     {
433       startOffset += 3;
434       cdnaStart += 3;
435       cdnaLength -= 3;
436     }
437
438     if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
439     {
440       /*
441        * protein is translation of dna (+/- start/stop codons)
442        */
443       MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
444       { proteinStart, proteinEnd }, 3, 1);
445       return map;
446     }
447
448     /*
449      * translation failed - try mapping CDS annotated regions of dna
450      */
451     return mapCdsToProtein(cdnaSeq, proteinSeq);
452   }
453
454   /**
455    * Test whether the given cdna sequence, starting at the given offset,
456    * translates to the given amino acid sequence, using the standard translation
457    * table. Designed to fail fast i.e. as soon as a mismatch position is found.
458    * 
459    * @param cdnaSeqChars
460    * @param cdnaStart
461    * @param aaSeqChars
462    * @return
463    */
464   protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
465           char[] aaSeqChars)
466   {
467     if (cdnaSeqChars == null || aaSeqChars == null)
468     {
469       return false;
470     }
471
472     int aaPos = 0;
473     int dnaPos = cdnaStart;
474     for (; dnaPos < cdnaSeqChars.length - 2
475             && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
476     {
477       String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
478       final String translated = ResidueProperties.codonTranslate(codon);
479
480       /*
481        * allow * in protein to match untranslatable in dna
482        */
483       final char aaRes = aaSeqChars[aaPos];
484       if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
485       {
486         continue;
487       }
488       if (translated == null || !(aaRes == translated.charAt(0)))
489       {
490         // debug
491         // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
492         // + codon + "(" + translated + ") != " + aaRes));
493         return false;
494       }
495     }
496
497     /*
498      * check we matched all of the protein sequence
499      */
500     if (aaPos != aaSeqChars.length)
501     {
502       return false;
503     }
504
505     /*
506      * check we matched all of the dna except
507      * for optional trailing STOP codon
508      */
509     if (dnaPos == cdnaSeqChars.length)
510     {
511       return true;
512     }
513     if (dnaPos == cdnaSeqChars.length - 3)
514     {
515       String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
516       if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
517       {
518         return true;
519       }
520     }
521     return false;
522   }
523
524   /**
525    * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
526    * currently assumes that we are aligning cDNA to match protein.
527    * 
528    * @param seq
529    *          the sequence to be realigned
530    * @param al
531    *          the alignment whose sequence alignment is to be 'copied'
532    * @param gap
533    *          character string represent a gap in the realigned sequence
534    * @param preserveUnmappedGaps
535    * @param preserveMappedGaps
536    * @return true if the sequence was realigned, false if it could not be
537    */
538   public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
539           String gap, boolean preserveMappedGaps,
540           boolean preserveUnmappedGaps)
541   {
542     /*
543      * Get any mappings from the source alignment to the target (dataset)
544      * sequence.
545      */
546     // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
547     // all mappings. Would it help to constrain this?
548     List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
549     if (mappings == null || mappings.isEmpty())
550     {
551       return false;
552     }
553
554     /*
555      * Locate the aligned source sequence whose dataset sequence is mapped. We
556      * just take the first match here (as we can't align like more than one
557      * sequence).
558      */
559     SequenceI alignFrom = null;
560     AlignedCodonFrame mapping = null;
561     for (AlignedCodonFrame mp : mappings)
562     {
563       alignFrom = mp.findAlignedSequence(seq, al);
564       if (alignFrom != null)
565       {
566         mapping = mp;
567         break;
568       }
569     }
570
571     if (alignFrom == null)
572     {
573       return false;
574     }
575     alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
576             preserveMappedGaps, preserveUnmappedGaps);
577     return true;
578   }
579
580   /**
581    * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
582    * match residues and codons. Flags control whether existing gaps in unmapped
583    * (intron) and mapped (exon) regions are preserved or not. Gaps between
584    * intron and exon are only retained if both flags are set.
585    * 
586    * @param alignTo
587    * @param alignFrom
588    * @param mapping
589    * @param myGap
590    * @param sourceGap
591    * @param preserveUnmappedGaps
592    * @param preserveMappedGaps
593    */
594   public static void alignSequenceAs(SequenceI alignTo,
595           SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
596           char sourceGap, boolean preserveMappedGaps,
597           boolean preserveUnmappedGaps)
598   {
599     // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
600
601     // aligned and dataset sequence positions, all base zero
602     int thisSeqPos = 0;
603     int sourceDsPos = 0;
604
605     int basesWritten = 0;
606     char myGapChar = myGap.charAt(0);
607     int ratio = myGap.length();
608
609     int fromOffset = alignFrom.getStart() - 1;
610     int toOffset = alignTo.getStart() - 1;
611     int sourceGapMappedLength = 0;
612     boolean inExon = false;
613     final char[] thisSeq = alignTo.getSequence();
614     final char[] thatAligned = alignFrom.getSequence();
615     StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
616
617     /*
618      * Traverse the 'model' aligned sequence
619      */
620     for (char sourceChar : thatAligned)
621     {
622       if (sourceChar == sourceGap)
623       {
624         sourceGapMappedLength += ratio;
625         continue;
626       }
627
628       /*
629        * Found a non-gap character. Locate its mapped region if any.
630        */
631       sourceDsPos++;
632       // Note mapping positions are base 1, our sequence positions base 0
633       int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
634               sourceDsPos + fromOffset);
635       if (mappedPos == null)
636       {
637         /*
638          * unmapped position; treat like a gap
639          */
640         sourceGapMappedLength += ratio;
641         // System.err.println("Can't align: no codon mapping to residue "
642         // + sourceDsPos + "(" + sourceChar + ")");
643         // return;
644         continue;
645       }
646
647       int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
648       int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
649       StringBuilder trailingCopiedGap = new StringBuilder();
650
651       /*
652        * Copy dna sequence up to and including this codon. Optionally, include
653        * gaps before the codon starts (in introns) and/or after the codon starts
654        * (in exons).
655        * 
656        * Note this only works for 'linear' splicing, not reverse or interleaved.
657        * But then 'align dna as protein' doesn't make much sense otherwise.
658        */
659       int intronLength = 0;
660       while (basesWritten + toOffset < mappedCodonEnd
661               && thisSeqPos < thisSeq.length)
662       {
663         final char c = thisSeq[thisSeqPos++];
664         if (c != myGapChar)
665         {
666           basesWritten++;
667           int sourcePosition = basesWritten + toOffset;
668           if (sourcePosition < mappedCodonStart)
669           {
670             /*
671              * Found an unmapped (intron) base. First add in any preceding gaps
672              * (if wanted).
673              */
674             if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
675             {
676               thisAligned.append(trailingCopiedGap.toString());
677               intronLength += trailingCopiedGap.length();
678               trailingCopiedGap = new StringBuilder();
679             }
680             intronLength++;
681             inExon = false;
682           }
683           else
684           {
685             final boolean startOfCodon = sourcePosition == mappedCodonStart;
686             int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
687                     preserveUnmappedGaps, sourceGapMappedLength, inExon,
688                     trailingCopiedGap.length(), intronLength, startOfCodon);
689             for (int i = 0; i < gapsToAdd; i++)
690             {
691               thisAligned.append(myGapChar);
692             }
693             sourceGapMappedLength = 0;
694             inExon = true;
695           }
696           thisAligned.append(c);
697           trailingCopiedGap = new StringBuilder();
698         }
699         else
700         {
701           if (inExon && preserveMappedGaps)
702           {
703             trailingCopiedGap.append(myGapChar);
704           }
705           else if (!inExon && preserveUnmappedGaps)
706           {
707             trailingCopiedGap.append(myGapChar);
708           }
709         }
710       }
711     }
712
713     /*
714      * At end of model aligned sequence. Copy any remaining target sequence, optionally
715      * including (intron) gaps.
716      */
717     while (thisSeqPos < thisSeq.length)
718     {
719       final char c = thisSeq[thisSeqPos++];
720       if (c != myGapChar || preserveUnmappedGaps)
721       {
722         thisAligned.append(c);
723       }
724       sourceGapMappedLength--;
725     }
726
727     /*
728      * finally add gaps to pad for any trailing source gaps or
729      * unmapped characters
730      */
731     if (preserveUnmappedGaps)
732     {
733       while (sourceGapMappedLength > 0)
734       {
735         thisAligned.append(myGapChar);
736         sourceGapMappedLength--;
737       }
738     }
739
740     /*
741      * All done aligning, set the aligned sequence.
742      */
743     alignTo.setSequence(new String(thisAligned));
744   }
745
746   /**
747    * Helper method to work out how many gaps to insert when realigning.
748    * 
749    * @param preserveMappedGaps
750    * @param preserveUnmappedGaps
751    * @param sourceGapMappedLength
752    * @param inExon
753    * @param trailingCopiedGap
754    * @param intronLength
755    * @param startOfCodon
756    * @return
757    */
758   protected static int calculateGapsToInsert(boolean preserveMappedGaps,
759           boolean preserveUnmappedGaps, int sourceGapMappedLength,
760           boolean inExon, int trailingGapLength, int intronLength,
761           final boolean startOfCodon)
762   {
763     int gapsToAdd = 0;
764     if (startOfCodon)
765     {
766       /*
767        * Reached start of codon. Ignore trailing gaps in intron unless we are
768        * preserving gaps in both exon and intron. Ignore them anyway if the
769        * protein alignment introduces a gap at least as large as the intronic
770        * region.
771        */
772       if (inExon && !preserveMappedGaps)
773       {
774         trailingGapLength = 0;
775       }
776       if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
777       {
778         trailingGapLength = 0;
779       }
780       if (inExon)
781       {
782         gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
783       }
784       else
785       {
786         if (intronLength + trailingGapLength <= sourceGapMappedLength)
787         {
788           gapsToAdd = sourceGapMappedLength - intronLength;
789         }
790         else
791         {
792           gapsToAdd = Math.min(intronLength + trailingGapLength
793                   - sourceGapMappedLength, trailingGapLength);
794         }
795       }
796     }
797     else
798     {
799       /*
800        * second or third base of codon; check for any gaps in dna
801        */
802       if (!preserveMappedGaps)
803       {
804         trailingGapLength = 0;
805       }
806       gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
807     }
808     return gapsToAdd;
809   }
810
811   /**
812    * Realigns the given protein to match the alignment of the dna, using codon
813    * mappings to translate aligned codon positions to protein residues.
814    * 
815    * @param protein
816    *          the alignment whose sequences are realigned by this method
817    * @param dna
818    *          the dna alignment whose alignment we are 'copying'
819    * @return the number of sequences that were realigned
820    */
821   public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
822   {
823     List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
824     Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
825             protein, dna, unmappedProtein);
826     return alignProteinAs(protein, alignedCodons, unmappedProtein);
827   }
828
829   /**
830    * Builds a map whose key is an aligned codon position (3 alignment column
831    * numbers base 0), and whose value is a map from protein sequence to each
832    * protein's peptide residue for that codon. The map generates an ordering of
833    * the codons, and allows us to read off the peptides at each position in
834    * order to assemble 'aligned' protein sequences.
835    * 
836    * @param protein
837    *          the protein alignment
838    * @param dna
839    *          the coding dna alignment
840    * @param unmappedProtein
841    *          any unmapped proteins are added to this list
842    * @return
843    */
844   protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
845           AlignmentI protein, AlignmentI dna,
846           List<SequenceI> unmappedProtein)
847   {
848     /*
849      * maintain a list of any proteins with no mappings - these will be
850      * rendered 'as is' in the protein alignment as we can't align them
851      */
852     unmappedProtein.addAll(protein.getSequences());
853
854     List<AlignedCodonFrame> mappings = protein.getCodonFrames();
855
856     /*
857      * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
858      * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
859      * comparator keeps the codon positions ordered.
860      */
861     Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
862             new CodonComparator());
863
864     for (SequenceI dnaSeq : dna.getSequences())
865     {
866       for (AlignedCodonFrame mapping : mappings)
867       {
868         SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
869         if (prot != null)
870         {
871           Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
872           addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
873                   seqMap, alignedCodons);
874           unmappedProtein.remove(prot);
875         }
876       }
877     }
878
879     /*
880      * Finally add any unmapped peptide start residues (e.g. for incomplete
881      * codons) as if at the codon position before the second residue
882      */
883     // TODO resolve JAL-2022 so this fudge can be removed
884     int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
885     addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
886     
887     return alignedCodons;
888   }
889
890   /**
891    * Scans for any protein mapped from position 2 (meaning unmapped start
892    * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
893    * preceding position in the alignment
894    * 
895    * @param alignedCodons
896    *          the codon-to-peptide map
897    * @param mappedSequenceCount
898    *          the number of distinct sequences in the map
899    */
900   protected static void addUnmappedPeptideStarts(
901           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
902           int mappedSequenceCount)
903   {
904     // TODO delete this ugly hack once JAL-2022 is resolved
905     // i.e. we can model startPhase > 0 (incomplete start codon)
906
907     List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
908     AlignedCodon lastCodon = null;
909     Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
910
911     for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
912             .entrySet())
913     {
914       for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
915               .entrySet())
916       {
917         SequenceI seq = sequenceCodon.getKey();
918         if (sequencesChecked.contains(seq))
919         {
920           continue;
921         }
922         sequencesChecked.add(seq);
923         AlignedCodon codon = sequenceCodon.getValue();
924         if (codon.peptideCol > 1)
925         {
926           System.err
927                   .println("Problem mapping protein with >1 unmapped start positions: "
928                           + seq.getName());
929         }
930         else if (codon.peptideCol == 1)
931         {
932           /*
933            * first position (peptideCol == 0) was unmapped - add it
934            */
935           if (lastCodon != null)
936           {
937             AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
938                     lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
939                             .getCharAt(0)), 0);
940             toAdd.put(seq, firstPeptide);
941           }
942           else
943           {
944             /*
945              * unmapped residue at start of alignment (no prior column) -
946              * 'insert' at nominal codon [0, 0, 0]
947              */
948             AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
949                     String.valueOf(seq.getCharAt(0)), 0);
950             toAdd.put(seq, firstPeptide);
951           }
952         }
953         if (sequencesChecked.size() == mappedSequenceCount)
954         {
955           // no need to check past first mapped position in all sequences
956           break;
957         }
958       }
959       lastCodon = entry.getKey();
960     }
961
962     /*
963      * add any new codons safely after iterating over the map
964      */
965     for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
966     {
967       addCodonToMap(alignedCodons, startCodon.getValue(),
968               startCodon.getKey());
969     }
970   }
971
972   /**
973    * Update the aligned protein sequences to match the codon alignments given in
974    * the map.
975    * 
976    * @param protein
977    * @param alignedCodons
978    *          an ordered map of codon positions (columns), with sequence/peptide
979    *          values present in each column
980    * @param unmappedProtein
981    * @return
982    */
983   protected static int alignProteinAs(AlignmentI protein,
984           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
985           List<SequenceI> unmappedProtein)
986   {
987     /*
988      * Prefill aligned sequences with gaps before inserting aligned protein
989      * residues.
990      */
991     int alignedWidth = alignedCodons.size();
992     char[] gaps = new char[alignedWidth];
993     Arrays.fill(gaps, protein.getGapCharacter());
994     String allGaps = String.valueOf(gaps);
995     for (SequenceI seq : protein.getSequences())
996     {
997       if (!unmappedProtein.contains(seq))
998       {
999         seq.setSequence(allGaps);
1000       }
1001     }
1002
1003     int column = 0;
1004     for (AlignedCodon codon : alignedCodons.keySet())
1005     {
1006       final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1007               .get(codon);
1008       for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1009       {
1010         // place translated codon at its column position in sequence
1011         entry.getKey().getSequence()[column] = entry.getValue().product
1012                 .charAt(0);
1013       }
1014       column++;
1015     }
1016     return 0;
1017   }
1018
1019   /**
1020    * Populate the map of aligned codons by traversing the given sequence
1021    * mapping, locating the aligned positions of mapped codons, and adding those
1022    * positions and their translation products to the map.
1023    * 
1024    * @param dna
1025    *          the aligned sequence we are mapping from
1026    * @param protein
1027    *          the sequence to be aligned to the codons
1028    * @param gapChar
1029    *          the gap character in the dna sequence
1030    * @param seqMap
1031    *          a mapping to a sequence translation
1032    * @param alignedCodons
1033    *          the map we are building up
1034    */
1035   static void addCodonPositions(SequenceI dna, SequenceI protein,
1036           char gapChar, Mapping seqMap,
1037           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1038   {
1039     Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1040
1041     /*
1042      * add codon positions, and their peptide translations, to the alignment
1043      * map, while remembering the first codon mapped
1044      */
1045     while (codons.hasNext())
1046     {
1047       try
1048       {
1049         AlignedCodon codon = codons.next();
1050         addCodonToMap(alignedCodons, codon, protein);
1051       } catch (IncompleteCodonException e)
1052       {
1053         // possible incomplete trailing codon - ignore
1054       } catch (NoSuchElementException e)
1055       {
1056         // possibly peptide lacking STOP
1057       }
1058     }
1059   }
1060
1061   /**
1062    * Helper method to add a codon-to-peptide entry to the aligned codons map
1063    * 
1064    * @param alignedCodons
1065    * @param codon
1066    * @param protein
1067    */
1068   protected static void addCodonToMap(
1069           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1070           AlignedCodon codon, SequenceI protein)
1071   {
1072     Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1073     if (seqProduct == null)
1074     {
1075       seqProduct = new HashMap<SequenceI, AlignedCodon>();
1076       alignedCodons.put(codon, seqProduct);
1077     }
1078     seqProduct.put(protein, codon);
1079   }
1080
1081   /**
1082    * Returns true if a cDNA/Protein mapping either exists, or could be made,
1083    * between at least one pair of sequences in the two alignments. Currently,
1084    * the logic is:
1085    * <ul>
1086    * <li>One alignment must be nucleotide, and the other protein</li>
1087    * <li>At least one pair of sequences must be already mapped, or mappable</li>
1088    * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1089    * <li>The translation may ignore start and stop codons if present in the
1090    * nucleotide</li>
1091    * </ul>
1092    * 
1093    * @param al1
1094    * @param al2
1095    * @return
1096    */
1097   public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1098   {
1099     if (al1 == null || al2 == null)
1100     {
1101       return false;
1102     }
1103
1104     /*
1105      * Require one nucleotide and one protein
1106      */
1107     if (al1.isNucleotide() == al2.isNucleotide())
1108     {
1109       return false;
1110     }
1111     AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1112     AlignmentI protein = dna == al1 ? al2 : al1;
1113     List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1114     for (SequenceI dnaSeq : dna.getSequences())
1115     {
1116       for (SequenceI proteinSeq : protein.getSequences())
1117       {
1118         if (isMappable(dnaSeq, proteinSeq, mappings))
1119         {
1120           return true;
1121         }
1122       }
1123     }
1124     return false;
1125   }
1126
1127   /**
1128    * Returns true if the dna sequence is mapped, or could be mapped, to the
1129    * protein sequence.
1130    * 
1131    * @param dnaSeq
1132    * @param proteinSeq
1133    * @param mappings
1134    * @return
1135    */
1136   protected static boolean isMappable(SequenceI dnaSeq,
1137           SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1138   {
1139     if (dnaSeq == null || proteinSeq == null)
1140     {
1141       return false;
1142     }
1143
1144     SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1145             .getDatasetSequence();
1146     SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1147             : proteinSeq.getDatasetSequence();
1148
1149     for (AlignedCodonFrame mapping : mappings)
1150     {
1151       if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1152       {
1153         /*
1154          * already mapped
1155          */
1156         return true;
1157       }
1158     }
1159
1160     /*
1161      * Just try to make a mapping (it is not yet stored), test whether
1162      * successful.
1163      */
1164     return mapCdnaToProtein(proteinDs, dnaDs) != null;
1165   }
1166
1167   /**
1168    * Finds any reference annotations associated with the sequences in
1169    * sequenceScope, that are not already added to the alignment, and adds them
1170    * to the 'candidates' map. Also populates a lookup table of annotation
1171    * labels, keyed by calcId, for use in constructing tooltips or the like.
1172    * 
1173    * @param sequenceScope
1174    *          the sequences to scan for reference annotations
1175    * @param labelForCalcId
1176    *          (optional) map to populate with label for calcId
1177    * @param candidates
1178    *          map to populate with annotations for sequence
1179    * @param al
1180    *          the alignment to check for presence of annotations
1181    */
1182   public static void findAddableReferenceAnnotations(
1183           List<SequenceI> sequenceScope,
1184           Map<String, String> labelForCalcId,
1185           final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1186           AlignmentI al)
1187   {
1188     if (sequenceScope == null)
1189     {
1190       return;
1191     }
1192
1193     /*
1194      * For each sequence in scope, make a list of any annotations on the
1195      * underlying dataset sequence which are not already on the alignment.
1196      * 
1197      * Add to a map of { alignmentSequence, <List of annotations to add> }
1198      */
1199     for (SequenceI seq : sequenceScope)
1200     {
1201       SequenceI dataset = seq.getDatasetSequence();
1202       if (dataset == null)
1203       {
1204         continue;
1205       }
1206       AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1207       if (datasetAnnotations == null)
1208       {
1209         continue;
1210       }
1211       final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1212       for (AlignmentAnnotation dsann : datasetAnnotations)
1213       {
1214         /*
1215          * Find matching annotations on the alignment. If none is found, then
1216          * add this annotation to the list of 'addable' annotations for this
1217          * sequence.
1218          */
1219         final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1220                 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1221         if (!matchedAlignmentAnnotations.iterator().hasNext())
1222         {
1223           result.add(dsann);
1224           if (labelForCalcId != null)
1225           {
1226             labelForCalcId.put(dsann.getCalcId(), dsann.label);
1227           }
1228         }
1229       }
1230       /*
1231        * Save any addable annotations for this sequence
1232        */
1233       if (!result.isEmpty())
1234       {
1235         candidates.put(seq, result);
1236       }
1237     }
1238   }
1239
1240   /**
1241    * Adds annotations to the top of the alignment annotations, in the same order
1242    * as their related sequences.
1243    * 
1244    * @param annotations
1245    *          the annotations to add
1246    * @param alignment
1247    *          the alignment to add them to
1248    * @param selectionGroup
1249    *          current selection group (or null if none)
1250    */
1251   public static void addReferenceAnnotations(
1252           Map<SequenceI, List<AlignmentAnnotation>> annotations,
1253           final AlignmentI alignment, final SequenceGroup selectionGroup)
1254   {
1255     for (SequenceI seq : annotations.keySet())
1256     {
1257       for (AlignmentAnnotation ann : annotations.get(seq))
1258       {
1259         AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1260         int startRes = 0;
1261         int endRes = ann.annotations.length;
1262         if (selectionGroup != null)
1263         {
1264           startRes = selectionGroup.getStartRes();
1265           endRes = selectionGroup.getEndRes();
1266         }
1267         copyAnn.restrict(startRes, endRes);
1268
1269         /*
1270          * Add to the sequence (sets copyAnn.datasetSequence), unless the
1271          * original annotation is already on the sequence.
1272          */
1273         if (!seq.hasAnnotation(ann))
1274         {
1275           seq.addAlignmentAnnotation(copyAnn);
1276         }
1277         // adjust for gaps
1278         copyAnn.adjustForAlignment();
1279         // add to the alignment and set visible
1280         alignment.addAnnotation(copyAnn);
1281         copyAnn.visible = true;
1282       }
1283     }
1284   }
1285
1286   /**
1287    * Set visibility of alignment annotations of specified types (labels), for
1288    * specified sequences. This supports controls like
1289    * "Show all secondary structure", "Hide all Temp factor", etc.
1290    * 
1291    * @al the alignment to scan for annotations
1292    * @param types
1293    *          the types (labels) of annotations to be updated
1294    * @param forSequences
1295    *          if not null, only annotations linked to one of these sequences are
1296    *          in scope for update; if null, acts on all sequence annotations
1297    * @param anyType
1298    *          if this flag is true, 'types' is ignored (label not checked)
1299    * @param doShow
1300    *          if true, set visibility on, else set off
1301    */
1302   public static void showOrHideSequenceAnnotations(AlignmentI al,
1303           Collection<String> types, List<SequenceI> forSequences,
1304           boolean anyType, boolean doShow)
1305   {
1306     for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1307     {
1308       if (anyType || types.contains(aa.label))
1309       {
1310         if ((aa.sequenceRef != null)
1311                 && (forSequences == null || forSequences
1312                         .contains(aa.sequenceRef)))
1313         {
1314           aa.visible = doShow;
1315         }
1316       }
1317     }
1318   }
1319
1320   /**
1321    * Returns true if either sequence has a cross-reference to the other
1322    * 
1323    * @param seq1
1324    * @param seq2
1325    * @return
1326    */
1327   public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1328   {
1329     // Note: moved here from class CrossRef as the latter class has dependencies
1330     // not availability to the applet's classpath
1331     return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1332   }
1333
1334   /**
1335    * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1336    * that sequence name is structured as Source|AccessionId.
1337    * 
1338    * @param seq1
1339    * @param seq2
1340    * @return
1341    */
1342   public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1343   {
1344     if (seq1 == null || seq2 == null)
1345     {
1346       return false;
1347     }
1348     String name = seq2.getName();
1349     final DBRefEntry[] xrefs = seq1.getDBRefs();
1350     if (xrefs != null)
1351     {
1352       for (DBRefEntry xref : xrefs)
1353       {
1354         String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1355         // case-insensitive test, consistent with DBRefEntry.equalRef()
1356         if (xrefName.equalsIgnoreCase(name))
1357         {
1358           return true;
1359         }
1360       }
1361     }
1362     return false;
1363   }
1364
1365   /**
1366    * Constructs an alignment consisting of the mapped (CDS) regions in the given
1367    * nucleotide sequences, and updates mappings to match. The CDS sequences are
1368    * added to the original alignment's dataset, which is shared by the new
1369    * alignment.
1370    * 
1371    * @param dna
1372    *          aligned dna sequences
1373    * @param mappings
1374    *          from dna to protein; these are replaced with new mappings
1375    * @param al
1376    * @return an alignment whose sequences are the cds-only parts of the dna
1377    *         sequences (or null if no mappings are found)
1378    */
1379   public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1380           List<AlignedCodonFrame> mappings, AlignmentI al)
1381   {
1382     List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1383     
1384     for (SequenceI seq : dna)
1385     {
1386       AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
1387       List<AlignedCodonFrame> seqMappings = MappingUtils
1388               .findMappingsForSequence(seq, mappings);
1389       List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
1390       for (AlignedCodonFrame mapping : seqMappings)
1391       {
1392         for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
1393         {
1394           SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
1395                   aMapping);
1396           cdsSeqs.add(cdsSeq);
1397     
1398           /*
1399            * add a mapping from CDS to the (unchanged) mapped to range
1400            */
1401           List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1402               cdsSeq.getLength() });
1403           MapList map = new MapList(cdsRange, aMapping.getMap()
1404                   .getToRanges(), aMapping.getMap().getFromRatio(),
1405                   aMapping.getMap().getToRatio());
1406           cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
1407
1408           /*
1409            * add another mapping from original 'from' range to CDS
1410            */
1411           map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1412                   1);
1413           cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
1414
1415           alignmentMappings.add(cdsMappings);
1416
1417           /*
1418            * transfer any features on dna that overlap the CDS
1419            */
1420           transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1421         }
1422       }
1423     }
1424
1425     /*
1426      * add CDS seqs to shared dataset
1427      */
1428     Alignment dataset = al.getDataset();
1429     for (SequenceI seq : cdsSeqs)
1430     {
1431       if (!dataset.getSequences().contains(seq.getDatasetSequence()))
1432       {
1433         dataset.addSequence(seq.getDatasetSequence());
1434       }
1435     }
1436     AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1437             .size()]));
1438     cds.setDataset(dataset);
1439
1440     return cds;
1441   }
1442
1443   /**
1444    * Helper method that makes a CDS sequence as defined by the mappings from the
1445    * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1446    * forward or reverse strand).
1447    * 
1448    * @param seq
1449    * @param mapping
1450    * @return
1451    */
1452   static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1453   {
1454     char[] seqChars = seq.getSequence();
1455     List<int[]> fromRanges = mapping.getMap().getFromRanges();
1456     int cdsWidth = MappingUtils.getLength(fromRanges);
1457     char[] newSeqChars = new char[cdsWidth];
1458
1459     int newPos = 0;
1460     for (int[] range : fromRanges)
1461     {
1462       if (range[0] <= range[1])
1463       {
1464         // forward strand mapping - just copy the range
1465         int length = range[1] - range[0] + 1;
1466         System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1467                 length);
1468         newPos += length;
1469       }
1470       else
1471       {
1472         // reverse strand mapping - copy and complement one by one
1473         for (int i = range[0]; i >= range[1]; i--)
1474         {
1475           newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1476         }
1477       }
1478     }
1479
1480     SequenceI newSeq = new Sequence(seq.getName() + "|"
1481             + mapping.getTo().getName(), newSeqChars, 1, newPos);
1482     newSeq.createDatasetSequence();
1483     return newSeq;
1484   }
1485
1486   /**
1487    * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1488    * feature start/end ranges, optionally omitting specified feature types.
1489    * Returns the number of features copied.
1490    * 
1491    * @param fromSeq
1492    * @param toSeq
1493    * @param select
1494    *          if not null, only features of this type are copied (including
1495    *          subtypes in the Sequence Ontology)
1496    * @param mapping
1497    *          the mapping from 'fromSeq' to 'toSeq'
1498    * @param omitting
1499    */
1500   public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1501           MapList mapping, String select, String... omitting)
1502   {
1503     SequenceI copyTo = toSeq;
1504     while (copyTo.getDatasetSequence() != null)
1505     {
1506       copyTo = copyTo.getDatasetSequence();
1507     }
1508
1509     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1510     int count = 0;
1511     SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1512     if (sfs != null)
1513     {
1514       for (SequenceFeature sf : sfs)
1515       {
1516         String type = sf.getType();
1517         if (select != null && !so.isA(type, select))
1518         {
1519           continue;
1520         }
1521         boolean omit = false;
1522         for (String toOmit : omitting)
1523         {
1524           if (type.equals(toOmit))
1525           {
1526             omit = true;
1527           }
1528         }
1529         if (omit)
1530         {
1531           continue;
1532         }
1533
1534         /*
1535          * locate the mapped range - null if either start or end is
1536          * not mapped (no partial overlaps are calculated)
1537          */
1538         int start = sf.getBegin();
1539         int end = sf.getEnd();
1540         int[] mappedTo = mapping.locateInTo(start, end);
1541         /*
1542          * if whole exon range doesn't map, try interpreting it
1543          * as 5' or 3' exon overlapping the CDS range
1544          */
1545         if (mappedTo == null)
1546         {
1547           mappedTo = mapping.locateInTo(end, end);
1548           if (mappedTo != null)
1549           {
1550             /*
1551              * end of exon is in CDS range - 5' overlap
1552              * to a range from the start of the peptide
1553              */
1554             mappedTo[0] = 1;
1555           }
1556         }
1557         if (mappedTo == null)
1558         {
1559           mappedTo = mapping.locateInTo(start, start);
1560           if (mappedTo != null)
1561           {
1562             /*
1563              * start of exon is in CDS range - 3' overlap
1564              * to a range up to the end of the peptide
1565              */
1566             mappedTo[1] = toSeq.getLength();
1567           }
1568         }
1569         if (mappedTo != null)
1570         {
1571           SequenceFeature copy = new SequenceFeature(sf);
1572           copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1573           copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1574           copyTo.addSequenceFeature(copy);
1575           count++;
1576         }
1577       }
1578     }
1579     return count;
1580   }
1581
1582   /**
1583    * Returns a mapping from dna to protein by inspecting sequence features of
1584    * type "CDS" on the dna.
1585    * 
1586    * @param dnaSeq
1587    * @param proteinSeq
1588    * @return
1589    */
1590   public static MapList mapCdsToProtein(SequenceI dnaSeq,
1591           SequenceI proteinSeq)
1592   {
1593     List<int[]> ranges = findCdsPositions(dnaSeq);
1594     int mappedDnaLength = MappingUtils.getLength(ranges);
1595
1596     int proteinLength = proteinSeq.getLength();
1597     int proteinStart = proteinSeq.getStart();
1598     int proteinEnd = proteinSeq.getEnd();
1599
1600     /*
1601      * incomplete start codon may mean X at start of peptide
1602      * we ignore both for mapping purposes
1603      */
1604     if (proteinSeq.getCharAt(0) == 'X')
1605     {
1606       // todo JAL-2022 support startPhase > 0
1607       proteinStart++;
1608       proteinLength--;
1609     }
1610     List<int[]> proteinRange = new ArrayList<int[]>();
1611
1612     /*
1613      * dna length should map to protein (or protein plus stop codon)
1614      */
1615     int codesForResidues = mappedDnaLength / 3;
1616     if (codesForResidues == (proteinLength + 1))
1617     {
1618       // assuming extra codon is for STOP and not in peptide
1619       codesForResidues--;
1620     }
1621     if (codesForResidues == proteinLength)
1622     {
1623       proteinRange.add(new int[] { proteinStart, proteinEnd });
1624       return new MapList(ranges, proteinRange, 3, 1);
1625     }
1626     return null;
1627   }
1628
1629   /**
1630    * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1631    * start/end positions of sequence features of type "CDS" (or a sub-type of
1632    * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1633    * position order, so this method is only valid for linear CDS in the same
1634    * sense as the protein product.
1635    * 
1636    * @param dnaSeq
1637    * @return
1638    */
1639   public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1640   {
1641     List<int[]> result = new ArrayList<int[]>();
1642     SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1643     if (sfs == null)
1644     {
1645       return result;
1646     }
1647
1648     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1649     int startPhase = 0;
1650
1651     for (SequenceFeature sf : sfs)
1652     {
1653       /*
1654        * process a CDS feature (or a sub-type of CDS)
1655        */
1656       if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1657       {
1658         int phase = 0;
1659         try
1660         {
1661           phase = Integer.parseInt(sf.getPhase());
1662         } catch (NumberFormatException e)
1663         {
1664           // ignore
1665         }
1666         /*
1667          * phase > 0 on first codon means 5' incomplete - skip to the start
1668          * of the next codon; example ENST00000496384
1669          */
1670         int begin = sf.getBegin();
1671         int end = sf.getEnd();
1672         if (result.isEmpty())
1673         {
1674           begin += phase;
1675           if (begin > end)
1676           {
1677             // shouldn't happen!
1678             System.err
1679                     .println("Error: start phase extends beyond start CDS in "
1680                             + dnaSeq.getName());
1681           }
1682         }
1683         result.add(new int[] { begin, end });
1684       }
1685     }
1686
1687     /*
1688      * remove 'startPhase' positions (usually 0) from the first range 
1689      * so we begin at the start of a complete codon
1690      */
1691     if (!result.isEmpty())
1692     {
1693       // TODO JAL-2022 correctly model start phase > 0
1694       result.get(0)[0] += startPhase;
1695     }
1696
1697     /*
1698      * Finally sort ranges by start position. This avoids a dependency on 
1699      * keeping features in order on the sequence (if they are in order anyway,
1700      * the sort will have almost no work to do). The implicit assumption is CDS
1701      * ranges are assembled in order. Other cases should not use this method,
1702      * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1703      */
1704     Collections.sort(result, new Comparator<int[]>()
1705     {
1706       @Override
1707       public int compare(int[] o1, int[] o2)
1708       {
1709         return Integer.compare(o1[0], o2[0]);
1710       }
1711     });
1712     return result;
1713   }
1714
1715   /**
1716    * Maps exon features from dna to protein, and computes variants in peptide
1717    * product generated by variants in dna, and adds them as sequence_variant
1718    * features on the protein sequence. Returns the number of variant features
1719    * added.
1720    * 
1721    * @param dnaSeq
1722    * @param peptide
1723    * @param dnaToProtein
1724    */
1725   public static int computeProteinFeatures(SequenceI dnaSeq,
1726           SequenceI peptide, MapList dnaToProtein)
1727   {
1728     while (dnaSeq.getDatasetSequence() != null)
1729     {
1730       dnaSeq = dnaSeq.getDatasetSequence();
1731     }
1732     while (peptide.getDatasetSequence() != null)
1733     {
1734       peptide = peptide.getDatasetSequence();
1735     }
1736
1737     transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1738
1739     /*
1740      * compute protein variants from dna variants and codon mappings;
1741      * NB - alternatively we could retrieve this using the REST service e.g.
1742      * http://rest.ensembl.org/overlap/translation
1743      * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1744      * which would be a bit slower but possibly more reliable
1745      */
1746     LinkedHashMap<Integer, String[][]> variants = buildDnaVariantsMap(
1747             dnaSeq, dnaToProtein);
1748
1749     /*
1750      * scan codon variations, compute peptide variants and add to peptide sequence
1751      */
1752     int count = 0;
1753     for (Entry<Integer, String[][]> variant : variants.entrySet())
1754     {
1755       int peptidePos = variant.getKey();
1756       String[][] codonVariants = variant.getValue();
1757       String residue = String.valueOf(peptide.getCharAt(peptidePos - 1)); // 0-based
1758       List<String> peptideVariants = computePeptideVariants(codonVariants,
1759               residue);
1760       if (!peptideVariants.isEmpty())
1761       {
1762         String desc = residue + "," // include canonical residue in description
1763                 + StringUtils.listToDelimitedString(peptideVariants, ", ");
1764         SequenceFeature sf = new SequenceFeature(
1765                 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
1766                 peptidePos, 0f, null);
1767         peptide.addSequenceFeature(sf);
1768         count++;
1769       }
1770     }
1771
1772     /*
1773      * ugly sort to get sequence features in start position order
1774      * - would be better to store in Sequence as a TreeSet instead?
1775      */
1776     Arrays.sort(peptide.getSequenceFeatures(),
1777             new Comparator<SequenceFeature>()
1778             {
1779               @Override
1780               public int compare(SequenceFeature o1, SequenceFeature o2)
1781               {
1782                 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1783                 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1784                         : c;
1785               }
1786             });
1787     return count;
1788   }
1789
1790   /**
1791    * Builds a map whose key is position in the protein sequence, and value is an
1792    * array of all variants for the coding codon positions
1793    * 
1794    * @param dnaSeq
1795    * @param dnaToProtein
1796    * @return
1797    */
1798   static LinkedHashMap<Integer, String[][]> buildDnaVariantsMap(
1799           SequenceI dnaSeq, MapList dnaToProtein)
1800   {
1801     /*
1802      * map from peptide position to all variant features of the codon for it
1803      * LinkedHashMap ensures we add the peptide features in sequence order
1804      */
1805     LinkedHashMap<Integer, String[][]> variants = new LinkedHashMap<Integer, String[][]>();
1806     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1807
1808     SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
1809     if (dnaFeatures == null)
1810     {
1811       return variants;
1812     }
1813
1814     int dnaStart = dnaSeq.getStart();
1815     int[] lastCodon = null;
1816     int lastPeptidePostion = 0;
1817
1818     /*
1819      * build a map of codon variations for peptides
1820      */
1821     for (SequenceFeature sf : dnaFeatures)
1822     {
1823       int dnaCol = sf.getBegin();
1824       if (dnaCol != sf.getEnd())
1825       {
1826         // not handling multi-locus variant features
1827         continue;
1828       }
1829       if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
1830       {
1831         int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
1832         if (mapsTo == null)
1833         {
1834           // feature doesn't lie within coding region
1835           continue;
1836         }
1837         int peptidePosition = mapsTo[0];
1838         String[][] codonVariants = variants.get(peptidePosition);
1839         if (codonVariants == null)
1840         {
1841           codonVariants = new String[3][];
1842           variants.put(peptidePosition, codonVariants);
1843         }
1844
1845         /*
1846          * extract dna variants to a string array
1847          */
1848         String alls = (String) sf.getValue("alleles");
1849         if (alls == null)
1850         {
1851           continue;
1852         }
1853         String[] alleles = alls.toUpperCase().split(",");
1854         int i = 0;
1855         for (String allele : alleles)
1856         {
1857           alleles[i++] = allele.trim(); // lose any space characters "A, G"
1858         }
1859
1860         /*
1861          * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
1862          */
1863         int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
1864                 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
1865                         peptidePosition, peptidePosition));
1866         lastPeptidePostion = peptidePosition;
1867         lastCodon = codon;
1868
1869         /*
1870          * save nucleotide (and this variant) for each codon position
1871          */
1872         for (int codonPos = 0; codonPos < 3; codonPos++)
1873         {
1874           String nucleotide = String.valueOf(
1875                   dnaSeq.getCharAt(codon[codonPos] - dnaStart))
1876                   .toUpperCase();
1877           if (codonVariants[codonPos] == null)
1878           {
1879             /*
1880              * record current dna base
1881              */
1882             codonVariants[codonPos] = new String[] { nucleotide };
1883           }
1884           if (codon[codonPos] == dnaCol)
1885           {
1886             /*
1887              * add alleles to dna base (and any previously found alleles)
1888              */
1889             String[] known = codonVariants[codonPos];
1890             String[] dnaVariants = new String[alleles.length + known.length];
1891             System.arraycopy(known, 0, dnaVariants, 0, known.length);
1892             System.arraycopy(alleles, 0, dnaVariants, known.length,
1893                     alleles.length);
1894             codonVariants[codonPos] = dnaVariants;
1895           }
1896         }
1897       }
1898     }
1899     return variants;
1900   }
1901
1902   /**
1903    * Returns a sorted, non-redundant list of all peptide translations generated
1904    * by the given dna variants, excluding the current residue value
1905    * 
1906    * @param codonVariants
1907    *          an array of base values (acgtACGT) for codon positions 1, 2, 3
1908    * @param residue
1909    *          the current residue translation
1910    * @return
1911    */
1912   static List<String> computePeptideVariants(String[][] codonVariants,
1913           String residue)
1914   {
1915     List<String> result = new ArrayList<String>();
1916     for (String base1 : codonVariants[0])
1917     {
1918       for (String base2 : codonVariants[1])
1919       {
1920         for (String base3 : codonVariants[2])
1921         {
1922           String codon = base1 + base2 + base3;
1923           /*
1924            * get peptide translation of codon e.g. GAT -> D
1925            * note that variants which are not single alleles,
1926            * e.g. multibase variants or HGMD_MUTATION etc
1927            * are ignored here
1928            */
1929           String peptide = codon.contains("-") ? "-"
1930                   : (codon.length() > 3 ? null : ResidueProperties
1931                           .codonTranslate(codon));
1932           if (peptide != null && !result.contains(peptide)
1933                   && !peptide.equalsIgnoreCase(residue))
1934           {
1935             result.add(peptide);
1936           }
1937         }
1938       }
1939     }
1940
1941     /*
1942      * sort alphabetically with STOP at the end
1943      */
1944     Collections.sort(result, new Comparator<String>()
1945     {
1946
1947       @Override
1948       public int compare(String o1, String o2)
1949       {
1950         if ("STOP".equals(o1))
1951         {
1952           return 1;
1953         }
1954         else if ("STOP".equals(o2))
1955         {
1956           return -1;
1957         }
1958         else
1959         {
1960           return o1.compareTo(o2);
1961         }
1962       }
1963     });
1964     return result;
1965   }
1966
1967   /**
1968    * Makes an alignment with a copy of the given sequences, adding in any
1969    * non-redundant sequences which are mapped to by the cross-referenced
1970    * sequences.
1971    * 
1972    * @param seqs
1973    * @param xrefs
1974    * @return
1975    */
1976   public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
1977           SequenceI[] xrefs)
1978   {
1979     AlignmentI copy = new Alignment(new Alignment(seqs));
1980
1981     SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
1982     if (xrefs != null)
1983     {
1984       for (SequenceI xref : xrefs)
1985       {
1986         DBRefEntry[] dbrefs = xref.getDBRefs();
1987         if (dbrefs != null)
1988         {
1989           for (DBRefEntry dbref : dbrefs)
1990           {
1991             if (dbref.getMap() == null || dbref.getMap().getTo() == null)
1992             {
1993               continue;
1994             }
1995             SequenceI mappedTo = dbref.getMap().getTo();
1996             SequenceI match = matcher.findIdMatch(mappedTo);
1997             if (match == null)
1998             {
1999               matcher.add(mappedTo);
2000               copy.addSequence(mappedTo);
2001             }
2002           }
2003         }
2004       }
2005     }
2006     return copy;
2007   }
2008
2009   /**
2010    * Try to align sequences in 'unaligned' to match the alignment of their
2011    * mapped regions in 'aligned'. For example, could use this to align CDS
2012    * sequences which are mapped to their parent cDNA sequences.
2013    * 
2014    * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2015    * dna-to-protein or protein-to-dna use alternative methods.
2016    * 
2017    * @param unaligned
2018    *          sequences to be aligned
2019    * @param aligned
2020    *          holds aligned sequences and their mappings
2021    * @return
2022    */
2023   public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2024   {
2025     List<SequenceI> unmapped = new ArrayList<SequenceI>();
2026     Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2027             unaligned, aligned, unmapped);
2028     int width = columnMap.size();
2029     char gap = unaligned.getGapCharacter();
2030     int realignedCount = 0;
2031
2032     for (SequenceI seq : unaligned.getSequences())
2033     {
2034       if (!unmapped.contains(seq))
2035       {
2036         char[] newSeq = new char[width];
2037         Arrays.fill(newSeq, gap);
2038         int newCol = 0;
2039         int lastCol = 0;
2040
2041         /*
2042          * traverse the map to find columns populated
2043          * by our sequence
2044          */
2045         for (Integer column : columnMap.keySet())
2046         {
2047           Character c = columnMap.get(column).get(seq);
2048           if (c != null)
2049           {
2050             /*
2051              * sequence has a character at this position
2052              * 
2053              */
2054             newSeq[newCol] = c;
2055             lastCol = newCol;
2056           }
2057           newCol++;
2058         }
2059         
2060         /*
2061          * trim trailing gaps
2062          */
2063         if (lastCol < width)
2064         {
2065           char[] tmp = new char[lastCol + 1];
2066           System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2067           newSeq = tmp;
2068         }
2069         seq.setSequence(String.valueOf(newSeq));
2070         realignedCount++;
2071       }
2072     }
2073     return realignedCount;
2074   }
2075
2076   /**
2077    * Returns a map whose key is alignment column number (base 1), and whose
2078    * values are a map of sequence characters in that column.
2079    * 
2080    * @param unaligned
2081    * @param aligned
2082    * @param unmapped
2083    * @return
2084    */
2085   static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2086           AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2087   {
2088     /*
2089      * Map will hold, for each aligned column position, a map of
2090      * {unalignedSequence, sequenceCharacter} at that position.
2091      * TreeMap keeps the entries in ascending column order. 
2092      */
2093     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2094
2095     /*
2096      * report any sequences that have no mapping so can't be realigned
2097      */
2098     unmapped.addAll(unaligned.getSequences());
2099
2100     List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2101
2102     for (SequenceI seq : unaligned.getSequences())
2103     {
2104       for (AlignedCodonFrame mapping : mappings)
2105       {
2106         SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2107         if (fromSeq != null)
2108         {
2109           Mapping seqMap = mapping.getMappingForSequence(seq);
2110           if (addMappedPositions(seq, fromSeq, seqMap, map))
2111           {
2112             unmapped.remove(seq);
2113           }
2114         }
2115       }
2116     }
2117     return map;
2118   }
2119
2120   /**
2121    * Helper method that adds to a map the mapped column positions of a sequence. <br>
2122    * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2123    * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2124    * sequence.
2125    * 
2126    * @param seq
2127    *          the sequence whose column positions we are recording
2128    * @param fromSeq
2129    *          a sequence that is mapped to the first sequence
2130    * @param seqMap
2131    *          the mapping from 'fromSeq' to 'seq'
2132    * @param map
2133    *          a map to add the column positions (in fromSeq) of the mapped
2134    *          positions of seq
2135    * @return
2136    */
2137   static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2138           Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2139   {
2140     char[] fromChars = fromSeq.getSequence();
2141     int toStart = seq.getStart();
2142     char[] toChars = seq.getSequence();
2143
2144     /*
2145      * traverse [start, end, start, end...] ranges in fromSeq
2146      */
2147     for (int[] fromRange : seqMap.getMap().getFromRanges())
2148     {
2149       for (int i = 0; i < fromRange.length - 1; i += 2)
2150       {
2151         boolean forward = fromRange[i + 1] >= fromRange[i];
2152
2153         /*
2154          * find the range mapped to (sequence positions base 1)
2155          */
2156         int[] range = seqMap.locateMappedRange(fromRange[i],
2157                 fromRange[i + 1]);
2158         if (range == null)
2159         {
2160           System.err.println("Error in mapping " + seqMap + " from "
2161                   + fromSeq.getName());
2162           return false;
2163         }
2164         int fromCol = fromSeq.findIndex(fromRange[i]);
2165         int mappedCharPos = range[0];
2166
2167         /*
2168          * walk over the 'from' aligned sequence in forward or reverse
2169          * direction; when a non-gap is found, record the column position
2170          * of the next character of the mapped-to sequence; stop when all
2171          * the characters of the range have been counted
2172          */
2173         while (mappedCharPos <= range[1])
2174         {
2175           if (!Comparison.isGap(fromChars[fromCol - 1]))
2176           {
2177             /*
2178              * mapped from sequence has a character in this column
2179              * record the column position for the mapped to character
2180              */
2181             Map<SequenceI, Character> seqsMap = map.get(fromCol);
2182             if (seqsMap == null)
2183             {
2184               seqsMap = new HashMap<SequenceI, Character>();
2185               map.put(fromCol, seqsMap);
2186             }
2187             seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2188             mappedCharPos++;
2189           }
2190           fromCol += (forward ? 1 : -1);
2191         }
2192       }
2193     }
2194     return true;
2195   }
2196 }