Merge branch 'features/JAL-2885UniprotHttps' into releases/Release_2_10_4_Branch
[jalview.git] / src / jalview / datamodel / Alignment.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.datamodel;
22
23 import jalview.analysis.AlignmentUtils;
24 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
25 import jalview.io.FastaFile;
26 import jalview.util.Comparison;
27 import jalview.util.LinkedIdentityHashSet;
28 import jalview.util.MessageManager;
29
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collections;
33 import java.util.Enumeration;
34 import java.util.HashSet;
35 import java.util.Hashtable;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.Vector;
40
41 /**
42  * Data structure to hold and manipulate a multiple sequence alignment
43  */
44 /**
45  * @author JimP
46  * 
47  */
48 public class Alignment implements AlignmentI
49 {
50   private Alignment dataset;
51
52   private List<SequenceI> sequences;
53
54   protected List<SequenceGroup> groups;
55
56   protected char gapCharacter = '-';
57
58   private boolean nucleotide = true;
59
60   public boolean hasRNAStructure = false;
61
62   public AlignmentAnnotation[] annotations;
63
64   HiddenSequences hiddenSequences;
65
66   HiddenColumns hiddenCols;
67
68   public Hashtable alignmentProperties;
69
70   private List<AlignedCodonFrame> codonFrameList;
71
72   private void initAlignment(SequenceI[] seqs)
73   {
74     groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
75     hiddenSequences = new HiddenSequences(this);
76     hiddenCols = new HiddenColumns();
77     codonFrameList = new ArrayList<>();
78
79     nucleotide = Comparison.isNucleotide(seqs);
80
81     sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
82
83     for (int i = 0; i < seqs.length; i++)
84     {
85       sequences.add(seqs[i]);
86     }
87
88   }
89
90   /**
91    * Make a 'copy' alignment - sequences have new copies of features and
92    * annotations, but share the original dataset sequences.
93    */
94   public Alignment(AlignmentI al)
95   {
96     SequenceI[] seqs = al.getSequencesArray();
97     for (int i = 0; i < seqs.length; i++)
98     {
99       seqs[i] = new Sequence(seqs[i]);
100     }
101
102     initAlignment(seqs);
103
104     /*
105      * Share the same dataset sequence mappings (if any). 
106      */
107     if (dataset == null && al.getDataset() == null)
108     {
109       this.setCodonFrames(al.getCodonFrames());
110     }
111   }
112
113   /**
114    * Make an alignment from an array of Sequences.
115    * 
116    * @param sequences
117    */
118   public Alignment(SequenceI[] seqs)
119   {
120     initAlignment(seqs);
121   }
122
123   /**
124    * Make a new alignment from an array of SeqCigars
125    * 
126    * @param seqs
127    *          SeqCigar[]
128    */
129   public Alignment(SeqCigar[] alseqs)
130   {
131     SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
132             gapCharacter, new HiddenColumns(), null);
133     initAlignment(seqs);
134   }
135
136   /**
137    * Make a new alignment from an CigarArray JBPNote - can only do this when
138    * compactAlignment does not contain hidden regions. JBPNote - must also check
139    * that compactAlignment resolves to a set of SeqCigars - or construct them
140    * appropriately.
141    * 
142    * @param compactAlignment
143    *          CigarArray
144    */
145   public static AlignmentI createAlignment(CigarArray compactAlignment)
146   {
147     throw new Error(MessageManager
148             .getString("error.alignment_cigararray_not_implemented"));
149     // this(compactAlignment.refCigars);
150   }
151
152   @Override
153   public List<SequenceI> getSequences()
154   {
155     return sequences;
156   }
157
158   @Override
159   public List<SequenceI> getSequences(
160           Map<SequenceI, SequenceCollectionI> hiddenReps)
161   {
162     // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
163     // work on this.
164     return sequences;
165   }
166
167   @Override
168   public SequenceI[] getSequencesArray()
169   {
170     if (sequences == null)
171     {
172       return null;
173     }
174     synchronized (sequences)
175     {
176       return sequences.toArray(new SequenceI[sequences.size()]);
177     }
178   }
179
180   /**
181    * Returns a map of lists of sequences keyed by sequence name.
182    * 
183    * @return
184    */
185   @Override
186   public Map<String, List<SequenceI>> getSequencesByName()
187   {
188     return AlignmentUtils.getSequencesByName(this);
189   }
190
191   @Override
192   public SequenceI getSequenceAt(int i)
193   {
194     synchronized (sequences)
195     {
196       if (i > -1 && i < sequences.size())
197       {
198         return sequences.get(i);
199       }
200     }
201
202     return null;
203   }
204
205   @Override
206   public SequenceI getSequenceAtAbsoluteIndex(int i)
207   {
208     SequenceI seq = null;
209     if (getHiddenSequences().getSize() > 0)
210     {
211       seq = getHiddenSequences().getHiddenSequence(i);
212       if (seq == null)
213       {
214         // didn't find the sequence in the hidden sequences, get it from the
215         // alignment
216         int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
217         seq = getSequenceAt(index);
218       }
219     }
220     else
221     {
222       seq = getSequenceAt(i);
223     }
224     return seq;
225   }
226
227   /**
228    * Adds a sequence to the alignment. Recalculates maxLength and size. Note
229    * this currently does not recalculate whether or not the alignment is
230    * nucleotide, so mixed alignments may have undefined behaviour.
231    * 
232    * @param snew
233    */
234   @Override
235   public void addSequence(SequenceI snew)
236   {
237     if (dataset != null)
238     {
239
240       // maintain dataset integrity
241       SequenceI dsseq = snew.getDatasetSequence();
242       if (dsseq == null)
243       {
244         // derive new sequence
245         SequenceI adding = snew.deriveSequence();
246         snew = adding;
247         dsseq = snew.getDatasetSequence();
248       }
249       if (getDataset().findIndex(dsseq) == -1)
250       {
251         getDataset().addSequence(dsseq);
252       }
253
254     }
255     if (sequences == null)
256     {
257       initAlignment(new SequenceI[] { snew });
258     }
259     else
260     {
261       synchronized (sequences)
262       {
263         sequences.add(snew);
264       }
265     }
266     if (hiddenSequences != null)
267     {
268       hiddenSequences.adjustHeightSequenceAdded();
269     }
270   }
271
272   @Override
273   public SequenceI replaceSequenceAt(int i, SequenceI snew)
274   {
275     synchronized (sequences)
276     {
277       if (sequences.size() > i)
278       {
279         return sequences.set(i, snew);
280
281       }
282       else
283       {
284         sequences.add(snew);
285         hiddenSequences.adjustHeightSequenceAdded();
286       }
287       return null;
288     }
289   }
290
291   /**
292    * DOCUMENT ME!
293    * 
294    * @return DOCUMENT ME!
295    */
296   @Override
297   public List<SequenceGroup> getGroups()
298   {
299     return groups;
300   }
301
302   @Override
303   public void finalize() throws Throwable
304   {
305     if (getDataset() != null)
306     {
307       getDataset().removeAlignmentRef();
308     }
309
310     nullReferences();
311     super.finalize();
312   }
313
314   /**
315    * Defensively nulls out references in case this object is not garbage
316    * collected
317    */
318   void nullReferences()
319   {
320     dataset = null;
321     sequences = null;
322     groups = null;
323     annotations = null;
324     hiddenSequences = null;
325   }
326
327   /**
328    * decrement the alignmentRefs counter by one and null references if it goes
329    * to zero.
330    * 
331    * @throws Throwable
332    */
333   private void removeAlignmentRef() throws Throwable
334   {
335     if (--alignmentRefs == 0)
336     {
337       nullReferences();
338     }
339   }
340
341   @Override
342   public void deleteSequence(SequenceI s)
343   {
344     synchronized (sequences)
345     {
346       deleteSequence(findIndex(s));
347     }
348   }
349
350   @Override
351   public void deleteSequence(int i)
352   {
353     synchronized (sequences)
354     {
355       if (i > -1 && i < getHeight())
356       {
357         sequences.remove(i);
358         hiddenSequences.adjustHeightSequenceDeleted(i);
359       }
360     }
361   }
362
363   @Override
364   public void deleteHiddenSequence(int i)
365   {
366     synchronized (sequences)
367     {
368       if (i > -1 && i < getHeight())
369       {
370         sequences.remove(i);
371       }
372     }
373   }
374
375   /*
376    * (non-Javadoc)
377    * 
378    * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
379    */
380   @Override
381   public SequenceGroup findGroup(SequenceI seq, int position)
382   {
383     synchronized (groups)
384     {
385       for (SequenceGroup sg : groups)
386       {
387         if (sg.getSequences(null).contains(seq))
388         {
389           if (position >= sg.getStartRes() && position <= sg.getEndRes())
390           {
391             return sg;
392           }
393         }
394       }
395     }
396     return null;
397   }
398
399   /*
400    * (non-Javadoc)
401    * 
402    * @see
403    * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
404    */
405   @Override
406   public SequenceGroup[] findAllGroups(SequenceI s)
407   {
408     ArrayList<SequenceGroup> temp = new ArrayList<>();
409
410     synchronized (groups)
411     {
412       int gSize = groups.size();
413       for (int i = 0; i < gSize; i++)
414       {
415         SequenceGroup sg = groups.get(i);
416         if (sg == null || sg.getSequences() == null)
417         {
418           this.deleteGroup(sg);
419           gSize--;
420           continue;
421         }
422
423         if (sg.getSequences().contains(s))
424         {
425           temp.add(sg);
426         }
427       }
428     }
429     SequenceGroup[] ret = new SequenceGroup[temp.size()];
430     return temp.toArray(ret);
431   }
432
433   /**    */
434   @Override
435   public void addGroup(SequenceGroup sg)
436   {
437     synchronized (groups)
438     {
439       if (!groups.contains(sg))
440       {
441         if (hiddenSequences.getSize() > 0)
442         {
443           int i, iSize = sg.getSize();
444           for (i = 0; i < iSize; i++)
445           {
446             if (!sequences.contains(sg.getSequenceAt(i)))
447             {
448               sg.deleteSequence(sg.getSequenceAt(i), false);
449               iSize--;
450               i--;
451             }
452           }
453
454           if (sg.getSize() < 1)
455           {
456             return;
457           }
458         }
459         sg.setContext(this, true);
460         groups.add(sg);
461       }
462     }
463   }
464
465   /**
466    * remove any annotation that references gp
467    * 
468    * @param gp
469    *          (if null, removes all group associated annotation)
470    */
471   private void removeAnnotationForGroup(SequenceGroup gp)
472   {
473     if (annotations == null || annotations.length == 0)
474     {
475       return;
476     }
477     // remove annotation very quickly
478     AlignmentAnnotation[] t,
479             todelete = new AlignmentAnnotation[annotations.length],
480             tokeep = new AlignmentAnnotation[annotations.length];
481     int i, p, k;
482     if (gp == null)
483     {
484       for (i = 0, p = 0, k = 0; i < annotations.length; i++)
485       {
486         if (annotations[i].groupRef != null)
487         {
488           todelete[p++] = annotations[i];
489         }
490         else
491         {
492           tokeep[k++] = annotations[i];
493         }
494       }
495     }
496     else
497     {
498       for (i = 0, p = 0, k = 0; i < annotations.length; i++)
499       {
500         if (annotations[i].groupRef == gp)
501         {
502           todelete[p++] = annotations[i];
503         }
504         else
505         {
506           tokeep[k++] = annotations[i];
507         }
508       }
509     }
510     if (p > 0)
511     {
512       // clear out the group associated annotation.
513       for (i = 0; i < p; i++)
514       {
515         unhookAnnotation(todelete[i]);
516         todelete[i] = null;
517       }
518       t = new AlignmentAnnotation[k];
519       for (i = 0; i < k; i++)
520       {
521         t[i] = tokeep[i];
522       }
523       annotations = t;
524     }
525   }
526
527   @Override
528   public void deleteAllGroups()
529   {
530     synchronized (groups)
531     {
532       if (annotations != null)
533       {
534         removeAnnotationForGroup(null);
535       }
536       for (SequenceGroup sg : groups)
537       {
538         sg.setContext(null, false);
539       }
540       groups.clear();
541     }
542   }
543
544   /**    */
545   @Override
546   public void deleteGroup(SequenceGroup g)
547   {
548     synchronized (groups)
549     {
550       if (groups.contains(g))
551       {
552         removeAnnotationForGroup(g);
553         groups.remove(g);
554         g.setContext(null, false);
555       }
556     }
557   }
558
559   /**    */
560   @Override
561   public SequenceI findName(String name)
562   {
563     return findName(name, false);
564   }
565
566   /*
567    * (non-Javadoc)
568    * 
569    * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
570    */
571   @Override
572   public SequenceI findName(String token, boolean b)
573   {
574     return findName(null, token, b);
575   }
576
577   /*
578    * (non-Javadoc)
579    * 
580    * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
581    * boolean)
582    */
583   @Override
584   public SequenceI findName(SequenceI startAfter, String token, boolean b)
585   {
586
587     int i = 0;
588     SequenceI sq = null;
589     String sqname = null;
590     if (startAfter != null)
591     {
592       // try to find the sequence in the alignment
593       boolean matched = false;
594       while (i < sequences.size())
595       {
596         if (getSequenceAt(i++) == startAfter)
597         {
598           matched = true;
599           break;
600         }
601       }
602       if (!matched)
603       {
604         i = 0;
605       }
606     }
607     while (i < sequences.size())
608     {
609       sq = getSequenceAt(i);
610       sqname = sq.getName();
611       if (sqname.equals(token) // exact match
612               || (b && // allow imperfect matches - case varies
613                       (sqname.equalsIgnoreCase(token))))
614       {
615         return getSequenceAt(i);
616       }
617
618       i++;
619     }
620
621     return null;
622   }
623
624   @Override
625   public SequenceI[] findSequenceMatch(String name)
626   {
627     Vector matches = new Vector();
628     int i = 0;
629
630     while (i < sequences.size())
631     {
632       if (getSequenceAt(i).getName().equals(name))
633       {
634         matches.addElement(getSequenceAt(i));
635       }
636       i++;
637     }
638
639     SequenceI[] result = new SequenceI[matches.size()];
640     for (i = 0; i < result.length; i++)
641     {
642       result[i] = (SequenceI) matches.elementAt(i);
643     }
644
645     return result;
646
647   }
648
649   /*
650    * (non-Javadoc)
651    * 
652    * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
653    */
654   @Override
655   public int findIndex(SequenceI s)
656   {
657     int i = 0;
658
659     while (i < sequences.size())
660     {
661       if (s == getSequenceAt(i))
662       {
663         return i;
664       }
665
666       i++;
667     }
668
669     return -1;
670   }
671
672   /*
673    * (non-Javadoc)
674    * 
675    * @see
676    * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
677    */
678   @Override
679   public int findIndex(SearchResultsI results)
680   {
681     int i = 0;
682
683     while (i < sequences.size())
684     {
685       if (results.involvesSequence(getSequenceAt(i)))
686       {
687         return i;
688       }
689       i++;
690     }
691     return -1;
692   }
693
694   @Override
695   public int getHeight()
696   {
697     return sequences.size();
698   }
699
700   @Override
701   public int getAbsoluteHeight()
702   {
703     return sequences.size() + getHiddenSequences().getSize();
704   }
705
706   @Override
707   public int getWidth()
708   {
709     int maxLength = -1;
710   
711     for (int i = 0; i < sequences.size(); i++)
712     {
713       if (getSequenceAt(i).getLength() > maxLength)
714       {
715         maxLength = getSequenceAt(i).getLength();
716       }
717     }
718   
719     return maxLength;
720   }
721   /*
722   @Override
723   public int getWidth()
724   {
725     final Wrapper temp = new Wrapper();
726   
727     forEachSequence(new Consumer<SequenceI>()
728     {
729       @Override
730       public void accept(SequenceI s)
731       {
732         if (s.getLength() > temp.inner)
733         {
734           temp.inner = s.getLength();
735         }
736       }
737     }, 0, sequences.size() - 1);
738   
739     return temp.inner;
740   }
741   
742   public static class Wrapper
743   {
744     public int inner;
745   }*/
746
747   /**
748    * DOCUMENT ME!
749    * 
750    * @param gc
751    *          DOCUMENT ME!
752    */
753   @Override
754   public void setGapCharacter(char gc)
755   {
756     gapCharacter = gc;
757     synchronized (sequences)
758     {
759       for (SequenceI seq : sequences)
760       {
761         seq.setSequence(seq.getSequenceAsString().replace('.', gc)
762                 .replace('-', gc).replace(' ', gc));
763       }
764     }
765   }
766
767   /**
768    * DOCUMENT ME!
769    * 
770    * @return DOCUMENT ME!
771    */
772   @Override
773   public char getGapCharacter()
774   {
775     return gapCharacter;
776   }
777
778   /*
779    * (non-Javadoc)
780    * 
781    * @see jalview.datamodel.AlignmentI#isAligned()
782    */
783   @Override
784   public boolean isAligned()
785   {
786     return isAligned(false);
787   }
788
789   /*
790    * (non-Javadoc)
791    * 
792    * @see jalview.datamodel.AlignmentI#isAligned(boolean)
793    */
794   @Override
795   public boolean isAligned(boolean includeHidden)
796   {
797     int width = getWidth();
798     if (hiddenSequences == null || hiddenSequences.getSize() == 0)
799     {
800       includeHidden = true; // no hidden sequences to check against.
801     }
802     for (int i = 0; i < sequences.size(); i++)
803     {
804       if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
805       {
806         if (getSequenceAt(i).getLength() != width)
807         {
808           return false;
809         }
810       }
811     }
812
813     return true;
814   }
815
816   @Override
817   public boolean isHidden(int alignmentIndex)
818   {
819     return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
820   }
821
822   /**
823    * Delete all annotations, including auto-calculated if the flag is set true.
824    * Returns true if at least one annotation was deleted, else false.
825    * 
826    * @param includingAutoCalculated
827    * @return
828    */
829   @Override
830   public boolean deleteAllAnnotations(boolean includingAutoCalculated)
831   {
832     boolean result = false;
833     for (AlignmentAnnotation alan : getAlignmentAnnotation())
834     {
835       if (!alan.autoCalculated || includingAutoCalculated)
836       {
837         deleteAnnotation(alan);
838         result = true;
839       }
840     }
841     return result;
842   }
843
844   /*
845    * (non-Javadoc)
846    * 
847    * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
848    * AlignmentAnnotation)
849    */
850   @Override
851   public boolean deleteAnnotation(AlignmentAnnotation aa)
852   {
853     return deleteAnnotation(aa, true);
854   }
855
856   @Override
857   public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
858   {
859     int aSize = 1;
860
861     if (annotations != null)
862     {
863       aSize = annotations.length;
864     }
865
866     if (aSize < 1)
867     {
868       return false;
869     }
870
871     AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
872
873     boolean swap = false;
874     int tIndex = 0;
875
876     for (int i = 0; i < aSize; i++)
877     {
878       if (annotations[i] == aa)
879       {
880         swap = true;
881         continue;
882       }
883       if (tIndex < temp.length)
884       {
885         temp[tIndex++] = annotations[i];
886       }
887     }
888
889     if (swap)
890     {
891       annotations = temp;
892       if (unhook)
893       {
894         unhookAnnotation(aa);
895       }
896     }
897     return swap;
898   }
899
900   /**
901    * remove any object references associated with this annotation
902    * 
903    * @param aa
904    */
905   private void unhookAnnotation(AlignmentAnnotation aa)
906   {
907     if (aa.sequenceRef != null)
908     {
909       aa.sequenceRef.removeAlignmentAnnotation(aa);
910     }
911     if (aa.groupRef != null)
912     {
913       // probably need to do more here in the future (post 2.5.0)
914       aa.groupRef = null;
915     }
916   }
917
918   /*
919    * (non-Javadoc)
920    * 
921    * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
922    * AlignmentAnnotation)
923    */
924   @Override
925   public void addAnnotation(AlignmentAnnotation aa)
926   {
927     addAnnotation(aa, -1);
928   }
929
930   /*
931    * (non-Javadoc)
932    * 
933    * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
934    * AlignmentAnnotation, int)
935    */
936   @Override
937   public void addAnnotation(AlignmentAnnotation aa, int pos)
938   {
939     if (aa.getRNAStruc() != null)
940     {
941       hasRNAStructure = true;
942     }
943
944     int aSize = 1;
945     if (annotations != null)
946     {
947       aSize = annotations.length + 1;
948     }
949
950     AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
951     int i = 0;
952     if (pos == -1 || pos >= aSize)
953     {
954       temp[aSize - 1] = aa;
955     }
956     else
957     {
958       temp[pos] = aa;
959     }
960     if (aSize > 1)
961     {
962       int p = 0;
963       for (i = 0; i < (aSize - 1); i++, p++)
964       {
965         if (p == pos)
966         {
967           p++;
968         }
969         if (p < temp.length)
970         {
971           temp[p] = annotations[i];
972         }
973       }
974     }
975
976     annotations = temp;
977   }
978
979   @Override
980   public void setAnnotationIndex(AlignmentAnnotation aa, int index)
981   {
982     if (aa == null || annotations == null || annotations.length - 1 < index)
983     {
984       return;
985     }
986
987     int aSize = annotations.length;
988     AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
989
990     temp[index] = aa;
991
992     for (int i = 0; i < aSize; i++)
993     {
994       if (i == index)
995       {
996         continue;
997       }
998
999       if (i < index)
1000       {
1001         temp[i] = annotations[i];
1002       }
1003       else
1004       {
1005         temp[i] = annotations[i - 1];
1006       }
1007     }
1008
1009     annotations = temp;
1010   }
1011
1012   @Override
1013   /**
1014    * returns all annotation on the alignment
1015    */
1016   public AlignmentAnnotation[] getAlignmentAnnotation()
1017   {
1018     return annotations;
1019   }
1020
1021   @Override
1022   public boolean isNucleotide()
1023   {
1024     return nucleotide;
1025   }
1026
1027   @Override
1028   public boolean hasRNAStructure()
1029   {
1030     // TODO can it happen that structure is removed from alignment?
1031     return hasRNAStructure;
1032   }
1033
1034   @Override
1035   public void setDataset(AlignmentI data)
1036   {
1037     if (dataset == null && data == null)
1038     {
1039       createDatasetAlignment();
1040     }
1041     else if (dataset == null && data != null)
1042     {
1043       if (data == this)
1044       {
1045         throw new IllegalArgumentException("Circular dataset reference");
1046       }
1047       if (!(data instanceof Alignment))
1048       {
1049         throw new Error(
1050                 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1051       }
1052       dataset = (Alignment) data;
1053       for (int i = 0; i < getHeight(); i++)
1054       {
1055         SequenceI currentSeq = getSequenceAt(i);
1056         SequenceI dsq = currentSeq.getDatasetSequence();
1057         if (dsq == null)
1058         {
1059           dsq = currentSeq.createDatasetSequence();
1060           dataset.addSequence(dsq);
1061         }
1062         else
1063         {
1064           while (dsq.getDatasetSequence() != null)
1065           {
1066             dsq = dsq.getDatasetSequence();
1067           }
1068           if (dataset.findIndex(dsq) == -1)
1069           {
1070             dataset.addSequence(dsq);
1071           }
1072         }
1073       }
1074     }
1075     dataset.addAlignmentRef();
1076   }
1077
1078   /**
1079    * add dataset sequences to seq for currentSeq and any sequences it references
1080    */
1081   private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1082           Set<SequenceI> seqs, boolean createDatasetSequence)
1083   {
1084     SequenceI alignedSeq = currentSeq;
1085     if (currentSeq.getDatasetSequence() != null)
1086     {
1087       currentSeq = currentSeq.getDatasetSequence();
1088     }
1089     else
1090     {
1091       if (createDatasetSequence)
1092       {
1093         currentSeq = currentSeq.createDatasetSequence();
1094       }
1095     }
1096
1097     List<SequenceI> toProcess = new ArrayList<>();
1098     toProcess.add(currentSeq);
1099     while (toProcess.size() > 0)
1100     {
1101       // use a queue ?
1102       SequenceI curDs = toProcess.remove(0);
1103
1104       if (!seqs.add(curDs))
1105       {
1106         continue;
1107       }
1108       // iterate over database references, making sure we add forward referenced
1109       // sequences
1110       if (curDs.getDBRefs() != null)
1111       {
1112         for (DBRefEntry dbr : curDs.getDBRefs())
1113         {
1114           if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1115           {
1116             if (dbr.getMap().getTo() == alignedSeq)
1117             {
1118               /*
1119                * update mapping to be to the newly created dataset sequence
1120                */
1121               dbr.getMap().setTo(currentSeq);
1122             }
1123             if (dbr.getMap().getTo().getDatasetSequence() != null)
1124             {
1125               throw new Error("Implementation error: Map.getTo() for dbref "
1126                       + dbr + " from " + curDs.getName()
1127                       + " is not a dataset sequence.");
1128             }
1129             // we recurse to add all forward references to dataset sequences via
1130             // DBRefs/etc
1131             toProcess.add(dbr.getMap().getTo());
1132           }
1133         }
1134       }
1135     }
1136   }
1137
1138   /**
1139    * Creates a new dataset for this alignment. Can only be done once - if
1140    * dataset is not null this will not be performed.
1141    */
1142   public void createDatasetAlignment()
1143   {
1144     if (dataset != null)
1145     {
1146       return;
1147     }
1148     // try to avoid using SequenceI.equals at this stage, it will be expensive
1149     Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1150
1151     for (int i = 0; i < getHeight(); i++)
1152     {
1153       SequenceI currentSeq = getSequenceAt(i);
1154       resolveAndAddDatasetSeq(currentSeq, seqs, true);
1155     }
1156
1157     // verify all mappings are in dataset
1158     for (AlignedCodonFrame cf : codonFrameList)
1159     {
1160       for (SequenceToSequenceMapping ssm : cf.getMappings())
1161       {
1162         if (!seqs.contains(ssm.getFromSeq()))
1163         {
1164           resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1165         }
1166         if (!seqs.contains(ssm.getMapping().getTo()))
1167         {
1168           resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1169         }
1170       }
1171     }
1172     // finally construct dataset
1173     dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1174     // move mappings to the dataset alignment
1175     dataset.codonFrameList = this.codonFrameList;
1176     this.codonFrameList = null;
1177   }
1178
1179   /**
1180    * reference count for number of alignments referencing this one.
1181    */
1182   int alignmentRefs = 0;
1183
1184   /**
1185    * increase reference count to this alignment.
1186    */
1187   private void addAlignmentRef()
1188   {
1189     alignmentRefs++;
1190   }
1191
1192   @Override
1193   public Alignment getDataset()
1194   {
1195     return dataset;
1196   }
1197
1198   @Override
1199   public boolean padGaps()
1200   {
1201     boolean modified = false;
1202
1203     // Remove excess gaps from the end of alignment
1204     int maxLength = -1;
1205
1206     SequenceI current;
1207     for (int i = 0; i < sequences.size(); i++)
1208     {
1209       current = getSequenceAt(i);
1210       for (int j = current.getLength(); j > maxLength; j--)
1211       {
1212         if (j > maxLength
1213                 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1214         {
1215           maxLength = j;
1216           break;
1217         }
1218       }
1219     }
1220
1221     maxLength++;
1222
1223     int cLength;
1224     for (int i = 0; i < sequences.size(); i++)
1225     {
1226       current = getSequenceAt(i);
1227       cLength = current.getLength();
1228
1229       if (cLength < maxLength)
1230       {
1231         current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1232         modified = true;
1233       }
1234       else if (current.getLength() > maxLength)
1235       {
1236         current.deleteChars(maxLength, current.getLength());
1237       }
1238     }
1239     return modified;
1240   }
1241
1242   /**
1243    * Justify the sequences to the left or right by deleting and inserting gaps
1244    * before the initial residue or after the terminal residue
1245    * 
1246    * @param right
1247    *          true if alignment padded to right, false to justify to left
1248    * @return true if alignment was changed
1249    */
1250   @Override
1251   public boolean justify(boolean right)
1252   {
1253     boolean modified = false;
1254
1255     // Remove excess gaps from the end of alignment
1256     int maxLength = -1;
1257     int ends[] = new int[sequences.size() * 2];
1258     SequenceI current;
1259     for (int i = 0; i < sequences.size(); i++)
1260     {
1261       current = getSequenceAt(i);
1262       // This should really be a sequence method
1263       ends[i * 2] = current.findIndex(current.getStart());
1264       ends[i * 2 + 1] = current
1265               .findIndex(current.getStart() + current.getLength());
1266       boolean hitres = false;
1267       for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1268       {
1269         if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1270         {
1271           if (!hitres)
1272           {
1273             ends[i * 2] = j;
1274             hitres = true;
1275           }
1276           else
1277           {
1278             ends[i * 2 + 1] = j;
1279             if (j - ends[i * 2] > maxLength)
1280             {
1281               maxLength = j - ends[i * 2];
1282             }
1283           }
1284         }
1285       }
1286     }
1287
1288     maxLength++;
1289     // now edit the flanking gaps to justify to either left or right
1290     int cLength, extent, diff;
1291     for (int i = 0; i < sequences.size(); i++)
1292     {
1293       current = getSequenceAt(i);
1294
1295       cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1296       diff = maxLength - cLength; // number of gaps to indent
1297       extent = current.getLength();
1298       if (right)
1299       {
1300         // right justify
1301         if (extent > ends[i * 2 + 1])
1302         {
1303           current.deleteChars(ends[i * 2 + 1] + 1, extent);
1304           modified = true;
1305         }
1306         if (ends[i * 2] > diff)
1307         {
1308           current.deleteChars(0, ends[i * 2] - diff);
1309           modified = true;
1310         }
1311         else
1312         {
1313           if (ends[i * 2] < diff)
1314           {
1315             current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1316             modified = true;
1317           }
1318         }
1319       }
1320       else
1321       {
1322         // left justify
1323         if (ends[i * 2] > 0)
1324         {
1325           current.deleteChars(0, ends[i * 2]);
1326           modified = true;
1327           ends[i * 2 + 1] -= ends[i * 2];
1328           extent -= ends[i * 2];
1329         }
1330         if (extent > maxLength)
1331         {
1332           current.deleteChars(maxLength + 1, extent);
1333           modified = true;
1334         }
1335         else
1336         {
1337           if (extent < maxLength)
1338           {
1339             current.insertCharAt(extent, maxLength - extent, gapCharacter);
1340             modified = true;
1341           }
1342         }
1343       }
1344     }
1345     return modified;
1346   }
1347
1348   @Override
1349   public HiddenSequences getHiddenSequences()
1350   {
1351     return hiddenSequences;
1352   }
1353
1354   @Override
1355   public HiddenColumns getHiddenColumns()
1356   {
1357     return hiddenCols;
1358   }
1359
1360   @Override
1361   public CigarArray getCompactAlignment()
1362   {
1363     synchronized (sequences)
1364     {
1365       SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1366       int i = 0;
1367       for (SequenceI seq : sequences)
1368       {
1369         alseqs[i++] = new SeqCigar(seq);
1370       }
1371       CigarArray cal = new CigarArray(alseqs);
1372       cal.addOperation(CigarArray.M, getWidth());
1373       return cal;
1374     }
1375   }
1376
1377   @Override
1378   public void setProperty(Object key, Object value)
1379   {
1380     if (alignmentProperties == null)
1381     {
1382       alignmentProperties = new Hashtable();
1383     }
1384
1385     alignmentProperties.put(key, value);
1386   }
1387
1388   @Override
1389   public Object getProperty(Object key)
1390   {
1391     if (alignmentProperties != null)
1392     {
1393       return alignmentProperties.get(key);
1394     }
1395     else
1396     {
1397       return null;
1398     }
1399   }
1400
1401   @Override
1402   public Hashtable getProperties()
1403   {
1404     return alignmentProperties;
1405   }
1406
1407   /**
1408    * Adds the given mapping to the stored set. Note this may be held on the
1409    * dataset alignment.
1410    */
1411   @Override
1412   public void addCodonFrame(AlignedCodonFrame codons)
1413   {
1414     List<AlignedCodonFrame> acfs = getCodonFrames();
1415     if (codons != null && acfs != null && !acfs.contains(codons))
1416     {
1417       acfs.add(codons);
1418     }
1419   }
1420
1421   /*
1422    * (non-Javadoc)
1423    * 
1424    * @see
1425    * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1426    */
1427   @Override
1428   public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1429   {
1430     if (seq == null)
1431     {
1432       return null;
1433     }
1434     List<AlignedCodonFrame> cframes = new ArrayList<>();
1435     for (AlignedCodonFrame acf : getCodonFrames())
1436     {
1437       if (acf.involvesSequence(seq))
1438       {
1439         cframes.add(acf);
1440       }
1441     }
1442     return cframes;
1443   }
1444
1445   /**
1446    * Sets the codon frame mappings (replacing any existing mappings). Note the
1447    * mappings are set on the dataset alignment instead if there is one.
1448    * 
1449    * @see jalview.datamodel.AlignmentI#setCodonFrames()
1450    */
1451   @Override
1452   public void setCodonFrames(List<AlignedCodonFrame> acfs)
1453   {
1454     if (dataset != null)
1455     {
1456       dataset.setCodonFrames(acfs);
1457     }
1458     else
1459     {
1460       this.codonFrameList = acfs;
1461     }
1462   }
1463
1464   /**
1465    * Returns the set of codon frame mappings. Any changes to the returned set
1466    * will affect the alignment. The mappings are held on (and read from) the
1467    * dataset alignment if there is one.
1468    * 
1469    * @see jalview.datamodel.AlignmentI#getCodonFrames()
1470    */
1471   @Override
1472   public List<AlignedCodonFrame> getCodonFrames()
1473   {
1474     // TODO: Fix this method to fix failing AlignedCodonFrame tests
1475     // this behaviour is currently incorrect. method should return codon frames
1476     // for just the alignment,
1477     // selected from dataset
1478     return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1479   }
1480
1481   /**
1482    * Removes the given mapping from the stored set. Note that the mappings are
1483    * held on the dataset alignment if there is one.
1484    */
1485   @Override
1486   public boolean removeCodonFrame(AlignedCodonFrame codons)
1487   {
1488     List<AlignedCodonFrame> acfs = getCodonFrames();
1489     if (codons == null || acfs == null)
1490     {
1491       return false;
1492     }
1493     return acfs.remove(codons);
1494   }
1495
1496   @Override
1497   public void append(AlignmentI toappend)
1498   {
1499     // TODO JAL-1270 needs test coverage
1500     // currently tested for use in jalview.gui.SequenceFetcher
1501     char oldc = toappend.getGapCharacter();
1502     boolean samegap = oldc == getGapCharacter();
1503     boolean hashidden = toappend.getHiddenSequences() != null
1504             && toappend.getHiddenSequences().hiddenSequences != null;
1505     // get all sequences including any hidden ones
1506     List<SequenceI> sqs = (hashidden)
1507             ? toappend.getHiddenSequences().getFullAlignment()
1508                     .getSequences()
1509             : toappend.getSequences();
1510     if (sqs != null)
1511     {
1512       // avoid self append deadlock by
1513       List<SequenceI> toappendsq = new ArrayList<>();
1514       synchronized (sqs)
1515       {
1516         for (SequenceI addedsq : sqs)
1517         {
1518           if (!samegap)
1519           {
1520             addedsq.replace(oldc, gapCharacter);
1521           }
1522           toappendsq.add(addedsq);
1523         }
1524       }
1525       for (SequenceI addedsq : toappendsq)
1526       {
1527         addSequence(addedsq);
1528       }
1529     }
1530     AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1531     for (int a = 0; alan != null && a < alan.length; a++)
1532     {
1533       addAnnotation(alan[a]);
1534     }
1535
1536     // use add method
1537     getCodonFrames().addAll(toappend.getCodonFrames());
1538
1539     List<SequenceGroup> sg = toappend.getGroups();
1540     if (sg != null)
1541     {
1542       for (SequenceGroup _sg : sg)
1543       {
1544         addGroup(_sg);
1545       }
1546     }
1547     if (toappend.getHiddenSequences() != null)
1548     {
1549       HiddenSequences hs = toappend.getHiddenSequences();
1550       if (hiddenSequences == null)
1551       {
1552         hiddenSequences = new HiddenSequences(this);
1553       }
1554       if (hs.hiddenSequences != null)
1555       {
1556         for (int s = 0; s < hs.hiddenSequences.length; s++)
1557         {
1558           // hide the newly appended sequence in the alignment
1559           if (hs.hiddenSequences[s] != null)
1560           {
1561             hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1562           }
1563         }
1564       }
1565     }
1566     if (toappend.getProperties() != null)
1567     {
1568       // we really can't do very much here - just try to concatenate strings
1569       // where property collisions occur.
1570       Enumeration key = toappend.getProperties().keys();
1571       while (key.hasMoreElements())
1572       {
1573         Object k = key.nextElement();
1574         Object ourval = this.getProperty(k);
1575         Object toapprop = toappend.getProperty(k);
1576         if (ourval != null)
1577         {
1578           if (ourval.getClass().equals(toapprop.getClass())
1579                   && !ourval.equals(toapprop))
1580           {
1581             if (ourval instanceof String)
1582             {
1583               // append strings
1584               this.setProperty(k,
1585                       ((String) ourval) + "; " + ((String) toapprop));
1586             }
1587             else
1588             {
1589               if (ourval instanceof Vector)
1590               {
1591                 // append vectors
1592                 Enumeration theirv = ((Vector) toapprop).elements();
1593                 while (theirv.hasMoreElements())
1594                 {
1595                   ((Vector) ourval).addElement(theirv);
1596                 }
1597               }
1598             }
1599           }
1600         }
1601         else
1602         {
1603           // just add new property directly
1604           setProperty(k, toapprop);
1605         }
1606
1607       }
1608     }
1609   }
1610
1611   @Override
1612   public AlignmentAnnotation findOrCreateAnnotation(String name,
1613           String calcId, boolean autoCalc, SequenceI seqRef,
1614           SequenceGroup groupRef)
1615   {
1616     if (annotations != null)
1617     {
1618       for (AlignmentAnnotation annot : getAlignmentAnnotation())
1619       {
1620         if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1621                 && (calcId == null || annot.getCalcId().equals(calcId))
1622                 && annot.sequenceRef == seqRef
1623                 && annot.groupRef == groupRef)
1624         {
1625           return annot;
1626         }
1627       }
1628     }
1629     AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1630             new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1631     annot.hasText = false;
1632     if (calcId != null)
1633     {
1634       annot.setCalcId(new String(calcId));
1635     }
1636     annot.autoCalculated = autoCalc;
1637     if (seqRef != null)
1638     {
1639       annot.setSequenceRef(seqRef);
1640     }
1641     annot.groupRef = groupRef;
1642     addAnnotation(annot);
1643
1644     return annot;
1645   }
1646
1647   @Override
1648   public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1649   {
1650     AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1651     if (alignmentAnnotation != null)
1652     {
1653       return AlignmentAnnotation.findAnnotation(
1654               Arrays.asList(getAlignmentAnnotation()), calcId);
1655     }
1656     return Arrays.asList(new AlignmentAnnotation[] {});
1657   }
1658
1659   @Override
1660   public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1661           String calcId, String label)
1662   {
1663     return AlignmentAnnotation.findAnnotations(
1664             Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1665   }
1666
1667   @Override
1668   public void moveSelectedSequencesByOne(SequenceGroup sg,
1669           Map<SequenceI, SequenceCollectionI> map, boolean up)
1670   {
1671     synchronized (sequences)
1672     {
1673       if (up)
1674       {
1675
1676         for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1677         {
1678           SequenceI seq = sequences.get(i);
1679           if (!sg.getSequences(map).contains(seq))
1680           {
1681             continue;
1682           }
1683
1684           SequenceI temp = sequences.get(i - 1);
1685           if (sg.getSequences(null).contains(temp))
1686           {
1687             continue;
1688           }
1689
1690           sequences.set(i, temp);
1691           sequences.set(i - 1, seq);
1692         }
1693       }
1694       else
1695       {
1696         for (int i = sequences.size() - 2; i > -1; i--)
1697         {
1698           SequenceI seq = sequences.get(i);
1699           if (!sg.getSequences(map).contains(seq))
1700           {
1701             continue;
1702           }
1703
1704           SequenceI temp = sequences.get(i + 1);
1705           if (sg.getSequences(map).contains(temp))
1706           {
1707             continue;
1708           }
1709
1710           sequences.set(i, temp);
1711           sequences.set(i + 1, seq);
1712         }
1713       }
1714
1715     }
1716   }
1717
1718   @Override
1719   public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1720   {
1721     alignmentAnnotation.validateRangeAndDisplay();
1722     if (isNucleotide() && alignmentAnnotation.isValidStruc())
1723     {
1724       hasRNAStructure = true;
1725     }
1726   }
1727
1728   private SequenceI seqrep = null;
1729
1730   /**
1731    * 
1732    * @return the representative sequence for this group
1733    */
1734   @Override
1735   public SequenceI getSeqrep()
1736   {
1737     return seqrep;
1738   }
1739
1740   /**
1741    * set the representative sequence for this group. Note - this affects the
1742    * interpretation of the Hidereps attribute.
1743    * 
1744    * @param seqrep
1745    *          the seqrep to set (null means no sequence representative)
1746    */
1747   @Override
1748   public void setSeqrep(SequenceI seqrep)
1749   {
1750     this.seqrep = seqrep;
1751   }
1752
1753   /**
1754    * 
1755    * @return true if group has a sequence representative
1756    */
1757   @Override
1758   public boolean hasSeqrep()
1759   {
1760     return seqrep != null;
1761   }
1762
1763   @Override
1764   public int getEndRes()
1765   {
1766     return getWidth() - 1;
1767   }
1768
1769   @Override
1770   public int getStartRes()
1771   {
1772     return 0;
1773   }
1774
1775   /*
1776    * In the case of AlignmentI - returns the dataset for the alignment, if set
1777    * (non-Javadoc)
1778    * 
1779    * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1780    */
1781   @Override
1782   public AnnotatedCollectionI getContext()
1783   {
1784     return dataset;
1785   }
1786
1787   /**
1788    * Align this alignment like the given (mapped) one.
1789    */
1790   @Override
1791   public int alignAs(AlignmentI al)
1792   {
1793     /*
1794      * Currently retains unmapped gaps (in introns), regaps mapped regions
1795      * (exons)
1796      */
1797     return alignAs(al, false, true);
1798   }
1799
1800   /**
1801    * Align this alignment 'the same as' the given one. Mapped sequences only are
1802    * realigned. If both of the same type (nucleotide/protein) then align both
1803    * identically. If this is nucleotide and the other is protein, make 3 gaps
1804    * for each gap in the protein sequences. If this is protein and the other is
1805    * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1806    * nucleotide bases. If this is protein and the other is nucleotide, gaps
1807    * protein to match the relative ordering of codons in the nucleotide.
1808    * 
1809    * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1810    * regions are preserved. Gaps that connect introns to exons are treated
1811    * conservatively, i.e. only preserved if both intron and exon gaps are
1812    * preserved. TODO: check caveats below where the implementation fails
1813    * 
1814    * @param al
1815    *          - must have same dataset, and sequences in al must have equivalent
1816    *          dataset sequence and start/end bounds under given mapping
1817    * @param preserveMappedGaps
1818    *          if true, gaps within and between mapped codons are preserved
1819    * @param preserveUnmappedGaps
1820    *          if true, gaps within and between unmapped codons are preserved
1821    */
1822   // @Override
1823   public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1824           boolean preserveUnmappedGaps)
1825   {
1826     // TODO should this method signature be the one in the interface?
1827     // JBPComment - yes - neither flag is used, so should be deleted.
1828     boolean thisIsNucleotide = this.isNucleotide();
1829     boolean thatIsProtein = !al.isNucleotide();
1830     if (!thatIsProtein && !thisIsNucleotide)
1831     {
1832       return AlignmentUtils.alignProteinAsDna(this, al);
1833     }
1834     else if (thatIsProtein && thisIsNucleotide)
1835     {
1836       return AlignmentUtils.alignCdsAsProtein(this, al);
1837     }
1838     return AlignmentUtils.alignAs(this, al);
1839   }
1840
1841   /**
1842    * Returns the alignment in Fasta format. Behaviour of this method is not
1843    * guaranteed between versions.
1844    */
1845   @Override
1846   public String toString()
1847   {
1848     return new FastaFile().print(getSequencesArray(), true);
1849   }
1850
1851   /**
1852    * Returns the set of distinct sequence names. No ordering is guaranteed.
1853    */
1854   @Override
1855   public Set<String> getSequenceNames()
1856   {
1857     Set<String> names = new HashSet<>();
1858     for (SequenceI seq : getSequences())
1859     {
1860       names.add(seq.getName());
1861     }
1862     return names;
1863   }
1864
1865   @Override
1866   public boolean hasValidSequence()
1867   {
1868     boolean hasValidSeq = false;
1869     for (SequenceI seq : getSequences())
1870     {
1871       if ((seq.getEnd() - seq.getStart()) > 0)
1872       {
1873         hasValidSeq = true;
1874         break;
1875       }
1876     }
1877     return hasValidSeq;
1878   }
1879
1880   /**
1881    * Update any mappings to 'virtual' sequences to compatible real ones, if
1882    * present in the added sequences. Returns a count of mappings updated.
1883    * 
1884    * @param seqs
1885    * @return
1886    */
1887   @Override
1888   public int realiseMappings(List<SequenceI> seqs)
1889   {
1890     int count = 0;
1891     for (SequenceI seq : seqs)
1892     {
1893       for (AlignedCodonFrame mapping : getCodonFrames())
1894       {
1895         count += mapping.realiseWith(seq);
1896       }
1897     }
1898     return count;
1899   }
1900
1901   /**
1902    * Returns the first AlignedCodonFrame that has a mapping between the given
1903    * dataset sequences
1904    * 
1905    * @param mapFrom
1906    * @param mapTo
1907    * @return
1908    */
1909   @Override
1910   public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1911   {
1912     for (AlignedCodonFrame acf : getCodonFrames())
1913     {
1914       if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1915       {
1916         return acf;
1917       }
1918     }
1919     return null;
1920   }
1921
1922   @Override
1923   public void setHiddenColumns(HiddenColumns cols)
1924   {
1925     hiddenCols = cols;
1926   }
1927 }