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