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