JAL-3074 don't scroll up/down on drag out of scale or annotation panel, performance...
[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   /**
721    * DOCUMENT ME!
722    * 
723    * @param gc
724    *          DOCUMENT ME!
725    */
726   @Override
727   public void setGapCharacter(char gc)
728   {
729     gapCharacter = gc;
730     synchronized (sequences)
731     {
732       for (SequenceI seq : sequences)
733       {
734         seq.setSequence(seq.getSequenceAsString().replace('.', gc)
735                 .replace('-', gc).replace(' ', gc));
736       }
737     }
738   }
739
740   /**
741    * DOCUMENT ME!
742    * 
743    * @return DOCUMENT ME!
744    */
745   @Override
746   public char getGapCharacter()
747   {
748     return gapCharacter;
749   }
750
751   /*
752    * (non-Javadoc)
753    * 
754    * @see jalview.datamodel.AlignmentI#isAligned()
755    */
756   @Override
757   public boolean isAligned()
758   {
759     return isAligned(false);
760   }
761
762   /*
763    * (non-Javadoc)
764    * 
765    * @see jalview.datamodel.AlignmentI#isAligned(boolean)
766    */
767   @Override
768   public boolean isAligned(boolean includeHidden)
769   {
770     int width = getWidth();
771     if (hiddenSequences == null || hiddenSequences.getSize() == 0)
772     {
773       includeHidden = true; // no hidden sequences to check against.
774     }
775     for (int i = 0; i < sequences.size(); i++)
776     {
777       if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
778       {
779         if (getSequenceAt(i).getLength() != width)
780         {
781           return false;
782         }
783       }
784     }
785
786     return true;
787   }
788
789   @Override
790   public boolean isHidden(int alignmentIndex)
791   {
792     return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
793   }
794
795   /**
796    * Delete all annotations, including auto-calculated if the flag is set true.
797    * Returns true if at least one annotation was deleted, else false.
798    * 
799    * @param includingAutoCalculated
800    * @return
801    */
802   @Override
803   public boolean deleteAllAnnotations(boolean includingAutoCalculated)
804   {
805     boolean result = false;
806     for (AlignmentAnnotation alan : getAlignmentAnnotation())
807     {
808       if (!alan.autoCalculated || includingAutoCalculated)
809       {
810         deleteAnnotation(alan);
811         result = true;
812       }
813     }
814     return result;
815   }
816
817   /*
818    * (non-Javadoc)
819    * 
820    * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
821    * AlignmentAnnotation)
822    */
823   @Override
824   public boolean deleteAnnotation(AlignmentAnnotation aa)
825   {
826     return deleteAnnotation(aa, true);
827   }
828
829   @Override
830   public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
831   {
832     int aSize = 1;
833
834     if (annotations != null)
835     {
836       aSize = annotations.length;
837     }
838
839     if (aSize < 1)
840     {
841       return false;
842     }
843
844     AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
845
846     boolean swap = false;
847     int tIndex = 0;
848
849     for (int i = 0; i < aSize; i++)
850     {
851       if (annotations[i] == aa)
852       {
853         swap = true;
854         continue;
855       }
856       if (tIndex < temp.length)
857       {
858         temp[tIndex++] = annotations[i];
859       }
860     }
861
862     if (swap)
863     {
864       annotations = temp;
865       if (unhook)
866       {
867         unhookAnnotation(aa);
868       }
869     }
870     return swap;
871   }
872
873   /**
874    * remove any object references associated with this annotation
875    * 
876    * @param aa
877    */
878   private void unhookAnnotation(AlignmentAnnotation aa)
879   {
880     if (aa.sequenceRef != null)
881     {
882       aa.sequenceRef.removeAlignmentAnnotation(aa);
883     }
884     if (aa.groupRef != null)
885     {
886       // probably need to do more here in the future (post 2.5.0)
887       aa.groupRef = null;
888     }
889   }
890
891   /*
892    * (non-Javadoc)
893    * 
894    * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
895    * AlignmentAnnotation)
896    */
897   @Override
898   public void addAnnotation(AlignmentAnnotation aa)
899   {
900     addAnnotation(aa, -1);
901   }
902
903   /*
904    * (non-Javadoc)
905    * 
906    * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
907    * AlignmentAnnotation, int)
908    */
909   @Override
910   public void addAnnotation(AlignmentAnnotation aa, int pos)
911   {
912     if (aa.getRNAStruc() != null)
913     {
914       hasRNAStructure = true;
915     }
916
917     int aSize = 1;
918     if (annotations != null)
919     {
920       aSize = annotations.length + 1;
921     }
922
923     AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
924     int i = 0;
925     if (pos == -1 || pos >= aSize)
926     {
927       temp[aSize - 1] = aa;
928     }
929     else
930     {
931       temp[pos] = aa;
932     }
933     if (aSize > 1)
934     {
935       int p = 0;
936       for (i = 0; i < (aSize - 1); i++, p++)
937       {
938         if (p == pos)
939         {
940           p++;
941         }
942         if (p < temp.length)
943         {
944           temp[p] = annotations[i];
945         }
946       }
947     }
948
949     annotations = temp;
950   }
951
952   @Override
953   public void setAnnotationIndex(AlignmentAnnotation aa, int index)
954   {
955     if (aa == null || annotations == null || annotations.length - 1 < index)
956     {
957       return;
958     }
959
960     int aSize = annotations.length;
961     AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
962
963     temp[index] = aa;
964
965     for (int i = 0; i < aSize; i++)
966     {
967       if (i == index)
968       {
969         continue;
970       }
971
972       if (i < index)
973       {
974         temp[i] = annotations[i];
975       }
976       else
977       {
978         temp[i] = annotations[i - 1];
979       }
980     }
981
982     annotations = temp;
983   }
984
985   @Override
986   /**
987    * returns all annotation on the alignment
988    */
989   public AlignmentAnnotation[] getAlignmentAnnotation()
990   {
991     return annotations;
992   }
993
994   @Override
995   public boolean isNucleotide()
996   {
997     return nucleotide;
998   }
999
1000   @Override
1001   public boolean hasRNAStructure()
1002   {
1003     // TODO can it happen that structure is removed from alignment?
1004     return hasRNAStructure;
1005   }
1006
1007   @Override
1008   public void setDataset(AlignmentI data)
1009   {
1010     if (dataset == null && data == null)
1011     {
1012       createDatasetAlignment();
1013     }
1014     else if (dataset == null && data != null)
1015     {
1016       if (data == this)
1017       {
1018         throw new IllegalArgumentException("Circular dataset reference");
1019       }
1020       if (!(data instanceof Alignment))
1021       {
1022         throw new Error(
1023                 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1024       }
1025       dataset = (Alignment) data;
1026       for (int i = 0; i < getHeight(); i++)
1027       {
1028         SequenceI currentSeq = getSequenceAt(i);
1029         SequenceI dsq = currentSeq.getDatasetSequence();
1030         if (dsq == null)
1031         {
1032           dsq = currentSeq.createDatasetSequence();
1033           dataset.addSequence(dsq);
1034         }
1035         else
1036         {
1037           while (dsq.getDatasetSequence() != null)
1038           {
1039             dsq = dsq.getDatasetSequence();
1040           }
1041           if (dataset.findIndex(dsq) == -1)
1042           {
1043             dataset.addSequence(dsq);
1044           }
1045         }
1046       }
1047     }
1048     dataset.addAlignmentRef();
1049   }
1050
1051   /**
1052    * add dataset sequences to seq for currentSeq and any sequences it references
1053    */
1054   private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1055           Set<SequenceI> seqs, boolean createDatasetSequence)
1056   {
1057     SequenceI alignedSeq = currentSeq;
1058     if (currentSeq.getDatasetSequence() != null)
1059     {
1060       currentSeq = currentSeq.getDatasetSequence();
1061     }
1062     else
1063     {
1064       if (createDatasetSequence)
1065       {
1066         currentSeq = currentSeq.createDatasetSequence();
1067       }
1068     }
1069
1070     List<SequenceI> toProcess = new ArrayList<>();
1071     toProcess.add(currentSeq);
1072     while (toProcess.size() > 0)
1073     {
1074       // use a queue ?
1075       SequenceI curDs = toProcess.remove(0);
1076
1077       if (!seqs.add(curDs))
1078       {
1079         continue;
1080       }
1081       // iterate over database references, making sure we add forward referenced
1082       // sequences
1083       if (curDs.getDBRefs() != null)
1084       {
1085         for (DBRefEntry dbr : curDs.getDBRefs())
1086         {
1087           if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1088           {
1089             if (dbr.getMap().getTo() == alignedSeq)
1090             {
1091               /*
1092                * update mapping to be to the newly created dataset sequence
1093                */
1094               dbr.getMap().setTo(currentSeq);
1095             }
1096             if (dbr.getMap().getTo().getDatasetSequence() != null)
1097             {
1098               throw new Error("Implementation error: Map.getTo() for dbref "
1099                       + dbr + " from " + curDs.getName()
1100                       + " is not a dataset sequence.");
1101             }
1102             // we recurse to add all forward references to dataset sequences via
1103             // DBRefs/etc
1104             toProcess.add(dbr.getMap().getTo());
1105           }
1106         }
1107       }
1108     }
1109   }
1110
1111   /**
1112    * Creates a new dataset for this alignment. Can only be done once - if
1113    * dataset is not null this will not be performed.
1114    */
1115   public void createDatasetAlignment()
1116   {
1117     if (dataset != null)
1118     {
1119       return;
1120     }
1121     // try to avoid using SequenceI.equals at this stage, it will be expensive
1122     Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1123
1124     for (int i = 0; i < getHeight(); i++)
1125     {
1126       SequenceI currentSeq = getSequenceAt(i);
1127       resolveAndAddDatasetSeq(currentSeq, seqs, true);
1128     }
1129
1130     // verify all mappings are in dataset
1131     for (AlignedCodonFrame cf : codonFrameList)
1132     {
1133       for (SequenceToSequenceMapping ssm : cf.getMappings())
1134       {
1135         if (!seqs.contains(ssm.getFromSeq()))
1136         {
1137           resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1138         }
1139         if (!seqs.contains(ssm.getMapping().getTo()))
1140         {
1141           resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1142         }
1143       }
1144     }
1145     // finally construct dataset
1146     dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1147     // move mappings to the dataset alignment
1148     dataset.codonFrameList = this.codonFrameList;
1149     this.codonFrameList = null;
1150   }
1151
1152   /**
1153    * reference count for number of alignments referencing this one.
1154    */
1155   int alignmentRefs = 0;
1156
1157   /**
1158    * increase reference count to this alignment.
1159    */
1160   private void addAlignmentRef()
1161   {
1162     alignmentRefs++;
1163   }
1164
1165   @Override
1166   public Alignment getDataset()
1167   {
1168     return dataset;
1169   }
1170
1171   @Override
1172   public boolean padGaps()
1173   {
1174     boolean modified = false;
1175
1176     // Remove excess gaps from the end of alignment
1177     int maxLength = -1;
1178
1179     SequenceI current;
1180     for (int i = 0; i < sequences.size(); i++)
1181     {
1182       current = getSequenceAt(i);
1183       for (int j = current.getLength(); j > maxLength; j--)
1184       {
1185         if (j > maxLength
1186                 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1187         {
1188           maxLength = j;
1189           break;
1190         }
1191       }
1192     }
1193
1194     maxLength++;
1195
1196     int cLength;
1197     for (int i = 0; i < sequences.size(); i++)
1198     {
1199       current = getSequenceAt(i);
1200       cLength = current.getLength();
1201
1202       if (cLength < maxLength)
1203       {
1204         current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1205         modified = true;
1206       }
1207       else if (current.getLength() > maxLength)
1208       {
1209         current.deleteChars(maxLength, current.getLength());
1210       }
1211     }
1212     return modified;
1213   }
1214
1215   /**
1216    * Justify the sequences to the left or right by deleting and inserting gaps
1217    * before the initial residue or after the terminal residue
1218    * 
1219    * @param right
1220    *          true if alignment padded to right, false to justify to left
1221    * @return true if alignment was changed
1222    */
1223   @Override
1224   public boolean justify(boolean right)
1225   {
1226     boolean modified = false;
1227
1228     // Remove excess gaps from the end of alignment
1229     int maxLength = -1;
1230     int ends[] = new int[sequences.size() * 2];
1231     SequenceI current;
1232     for (int i = 0; i < sequences.size(); i++)
1233     {
1234       current = getSequenceAt(i);
1235       // This should really be a sequence method
1236       ends[i * 2] = current.findIndex(current.getStart());
1237       ends[i * 2 + 1] = current
1238               .findIndex(current.getStart() + current.getLength());
1239       boolean hitres = false;
1240       for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1241       {
1242         if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1243         {
1244           if (!hitres)
1245           {
1246             ends[i * 2] = j;
1247             hitres = true;
1248           }
1249           else
1250           {
1251             ends[i * 2 + 1] = j;
1252             if (j - ends[i * 2] > maxLength)
1253             {
1254               maxLength = j - ends[i * 2];
1255             }
1256           }
1257         }
1258       }
1259     }
1260
1261     maxLength++;
1262     // now edit the flanking gaps to justify to either left or right
1263     int cLength, extent, diff;
1264     for (int i = 0; i < sequences.size(); i++)
1265     {
1266       current = getSequenceAt(i);
1267
1268       cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1269       diff = maxLength - cLength; // number of gaps to indent
1270       extent = current.getLength();
1271       if (right)
1272       {
1273         // right justify
1274         if (extent > ends[i * 2 + 1])
1275         {
1276           current.deleteChars(ends[i * 2 + 1] + 1, extent);
1277           modified = true;
1278         }
1279         if (ends[i * 2] > diff)
1280         {
1281           current.deleteChars(0, ends[i * 2] - diff);
1282           modified = true;
1283         }
1284         else
1285         {
1286           if (ends[i * 2] < diff)
1287           {
1288             current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1289             modified = true;
1290           }
1291         }
1292       }
1293       else
1294       {
1295         // left justify
1296         if (ends[i * 2] > 0)
1297         {
1298           current.deleteChars(0, ends[i * 2]);
1299           modified = true;
1300           ends[i * 2 + 1] -= ends[i * 2];
1301           extent -= ends[i * 2];
1302         }
1303         if (extent > maxLength)
1304         {
1305           current.deleteChars(maxLength + 1, extent);
1306           modified = true;
1307         }
1308         else
1309         {
1310           if (extent < maxLength)
1311           {
1312             current.insertCharAt(extent, maxLength - extent, gapCharacter);
1313             modified = true;
1314           }
1315         }
1316       }
1317     }
1318     return modified;
1319   }
1320
1321   @Override
1322   public HiddenSequences getHiddenSequences()
1323   {
1324     return hiddenSequences;
1325   }
1326
1327   @Override
1328   public HiddenColumns getHiddenColumns()
1329   {
1330     return hiddenCols;
1331   }
1332
1333   @Override
1334   public CigarArray getCompactAlignment()
1335   {
1336     synchronized (sequences)
1337     {
1338       SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1339       int i = 0;
1340       for (SequenceI seq : sequences)
1341       {
1342         alseqs[i++] = new SeqCigar(seq);
1343       }
1344       CigarArray cal = new CigarArray(alseqs);
1345       cal.addOperation(CigarArray.M, getWidth());
1346       return cal;
1347     }
1348   }
1349
1350   @Override
1351   public void setProperty(Object key, Object value)
1352   {
1353     if (alignmentProperties == null)
1354     {
1355       alignmentProperties = new Hashtable();
1356     }
1357
1358     alignmentProperties.put(key, value);
1359   }
1360
1361   @Override
1362   public Object getProperty(Object key)
1363   {
1364     if (alignmentProperties != null)
1365     {
1366       return alignmentProperties.get(key);
1367     }
1368     else
1369     {
1370       return null;
1371     }
1372   }
1373
1374   @Override
1375   public Hashtable getProperties()
1376   {
1377     return alignmentProperties;
1378   }
1379
1380   /**
1381    * Adds the given mapping to the stored set. Note this may be held on the
1382    * dataset alignment.
1383    */
1384   @Override
1385   public void addCodonFrame(AlignedCodonFrame codons)
1386   {
1387     List<AlignedCodonFrame> acfs = getCodonFrames();
1388     if (codons != null && acfs != null && !acfs.contains(codons))
1389     {
1390       acfs.add(codons);
1391     }
1392   }
1393
1394   /*
1395    * (non-Javadoc)
1396    * 
1397    * @see
1398    * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1399    */
1400   @Override
1401   public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1402   {
1403     if (seq == null)
1404     {
1405       return null;
1406     }
1407     List<AlignedCodonFrame> cframes = new ArrayList<>();
1408     for (AlignedCodonFrame acf : getCodonFrames())
1409     {
1410       if (acf.involvesSequence(seq))
1411       {
1412         cframes.add(acf);
1413       }
1414     }
1415     return cframes;
1416   }
1417
1418   /**
1419    * Sets the codon frame mappings (replacing any existing mappings). Note the
1420    * mappings are set on the dataset alignment instead if there is one.
1421    * 
1422    * @see jalview.datamodel.AlignmentI#setCodonFrames()
1423    */
1424   @Override
1425   public void setCodonFrames(List<AlignedCodonFrame> acfs)
1426   {
1427     if (dataset != null)
1428     {
1429       dataset.setCodonFrames(acfs);
1430     }
1431     else
1432     {
1433       this.codonFrameList = acfs;
1434     }
1435   }
1436
1437   /**
1438    * Returns the set of codon frame mappings. Any changes to the returned set
1439    * will affect the alignment. The mappings are held on (and read from) the
1440    * dataset alignment if there is one.
1441    * 
1442    * @see jalview.datamodel.AlignmentI#getCodonFrames()
1443    */
1444   @Override
1445   public List<AlignedCodonFrame> getCodonFrames()
1446   {
1447     // TODO: Fix this method to fix failing AlignedCodonFrame tests
1448     // this behaviour is currently incorrect. method should return codon frames
1449     // for just the alignment,
1450     // selected from dataset
1451     return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1452   }
1453
1454   /**
1455    * Removes the given mapping from the stored set. Note that the mappings are
1456    * held on the dataset alignment if there is one.
1457    */
1458   @Override
1459   public boolean removeCodonFrame(AlignedCodonFrame codons)
1460   {
1461     List<AlignedCodonFrame> acfs = getCodonFrames();
1462     if (codons == null || acfs == null)
1463     {
1464       return false;
1465     }
1466     return acfs.remove(codons);
1467   }
1468
1469   @Override
1470   public void append(AlignmentI toappend)
1471   {
1472     // TODO JAL-1270 needs test coverage
1473     // currently tested for use in jalview.gui.SequenceFetcher
1474     char oldc = toappend.getGapCharacter();
1475     boolean samegap = oldc == getGapCharacter();
1476     boolean hashidden = toappend.getHiddenSequences() != null
1477             && toappend.getHiddenSequences().hiddenSequences != null;
1478     // get all sequences including any hidden ones
1479     List<SequenceI> sqs = (hashidden)
1480             ? toappend.getHiddenSequences().getFullAlignment()
1481                     .getSequences()
1482             : toappend.getSequences();
1483     if (sqs != null)
1484     {
1485       // avoid self append deadlock by
1486       List<SequenceI> toappendsq = new ArrayList<>();
1487       synchronized (sqs)
1488       {
1489         for (SequenceI addedsq : sqs)
1490         {
1491           if (!samegap)
1492           {
1493             addedsq.replace(oldc, gapCharacter);
1494           }
1495           toappendsq.add(addedsq);
1496         }
1497       }
1498       for (SequenceI addedsq : toappendsq)
1499       {
1500         addSequence(addedsq);
1501       }
1502     }
1503     AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1504     for (int a = 0; alan != null && a < alan.length; a++)
1505     {
1506       addAnnotation(alan[a]);
1507     }
1508
1509     // use add method
1510     getCodonFrames().addAll(toappend.getCodonFrames());
1511
1512     List<SequenceGroup> sg = toappend.getGroups();
1513     if (sg != null)
1514     {
1515       for (SequenceGroup _sg : sg)
1516       {
1517         addGroup(_sg);
1518       }
1519     }
1520     if (toappend.getHiddenSequences() != null)
1521     {
1522       HiddenSequences hs = toappend.getHiddenSequences();
1523       if (hiddenSequences == null)
1524       {
1525         hiddenSequences = new HiddenSequences(this);
1526       }
1527       if (hs.hiddenSequences != null)
1528       {
1529         for (int s = 0; s < hs.hiddenSequences.length; s++)
1530         {
1531           // hide the newly appended sequence in the alignment
1532           if (hs.hiddenSequences[s] != null)
1533           {
1534             hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1535           }
1536         }
1537       }
1538     }
1539     if (toappend.getProperties() != null)
1540     {
1541       // we really can't do very much here - just try to concatenate strings
1542       // where property collisions occur.
1543       Enumeration key = toappend.getProperties().keys();
1544       while (key.hasMoreElements())
1545       {
1546         Object k = key.nextElement();
1547         Object ourval = this.getProperty(k);
1548         Object toapprop = toappend.getProperty(k);
1549         if (ourval != null)
1550         {
1551           if (ourval.getClass().equals(toapprop.getClass())
1552                   && !ourval.equals(toapprop))
1553           {
1554             if (ourval instanceof String)
1555             {
1556               // append strings
1557               this.setProperty(k,
1558                       ((String) ourval) + "; " + ((String) toapprop));
1559             }
1560             else
1561             {
1562               if (ourval instanceof Vector)
1563               {
1564                 // append vectors
1565                 Enumeration theirv = ((Vector) toapprop).elements();
1566                 while (theirv.hasMoreElements())
1567                 {
1568                   ((Vector) ourval).addElement(theirv);
1569                 }
1570               }
1571             }
1572           }
1573         }
1574         else
1575         {
1576           // just add new property directly
1577           setProperty(k, toapprop);
1578         }
1579
1580       }
1581     }
1582   }
1583
1584   @Override
1585   public AlignmentAnnotation findOrCreateAnnotation(String name,
1586           String calcId, boolean autoCalc, SequenceI seqRef,
1587           SequenceGroup groupRef)
1588   {
1589     if (annotations != null)
1590     {
1591       for (AlignmentAnnotation annot : getAlignmentAnnotation())
1592       {
1593         if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1594                 && (calcId == null || annot.getCalcId().equals(calcId))
1595                 && annot.sequenceRef == seqRef
1596                 && annot.groupRef == groupRef)
1597         {
1598           return annot;
1599         }
1600       }
1601     }
1602     AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1603             new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1604     annot.hasText = false;
1605     if (calcId != null)
1606     {
1607       annot.setCalcId(new String(calcId));
1608     }
1609     annot.autoCalculated = autoCalc;
1610     if (seqRef != null)
1611     {
1612       annot.setSequenceRef(seqRef);
1613     }
1614     annot.groupRef = groupRef;
1615     addAnnotation(annot);
1616
1617     return annot;
1618   }
1619
1620   @Override
1621   public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1622   {
1623     AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1624     if (alignmentAnnotation != null)
1625     {
1626       return AlignmentAnnotation.findAnnotation(
1627               Arrays.asList(getAlignmentAnnotation()), calcId);
1628     }
1629     return Arrays.asList(new AlignmentAnnotation[] {});
1630   }
1631
1632   @Override
1633   public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1634           String calcId, String label)
1635   {
1636     return AlignmentAnnotation.findAnnotations(
1637             Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1638   }
1639
1640   @Override
1641   public void moveSelectedSequencesByOne(SequenceGroup sg,
1642           Map<SequenceI, SequenceCollectionI> map, boolean up)
1643   {
1644     synchronized (sequences)
1645     {
1646       if (up)
1647       {
1648
1649         for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1650         {
1651           SequenceI seq = sequences.get(i);
1652           if (!sg.getSequences(map).contains(seq))
1653           {
1654             continue;
1655           }
1656
1657           SequenceI temp = sequences.get(i - 1);
1658           if (sg.getSequences(null).contains(temp))
1659           {
1660             continue;
1661           }
1662
1663           sequences.set(i, temp);
1664           sequences.set(i - 1, seq);
1665         }
1666       }
1667       else
1668       {
1669         for (int i = sequences.size() - 2; i > -1; i--)
1670         {
1671           SequenceI seq = sequences.get(i);
1672           if (!sg.getSequences(map).contains(seq))
1673           {
1674             continue;
1675           }
1676
1677           SequenceI temp = sequences.get(i + 1);
1678           if (sg.getSequences(map).contains(temp))
1679           {
1680             continue;
1681           }
1682
1683           sequences.set(i, temp);
1684           sequences.set(i + 1, seq);
1685         }
1686       }
1687
1688     }
1689   }
1690
1691   @Override
1692   public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1693   {
1694     alignmentAnnotation.validateRangeAndDisplay();
1695     if (isNucleotide() && alignmentAnnotation.isValidStruc())
1696     {
1697       hasRNAStructure = true;
1698     }
1699   }
1700
1701   private SequenceI seqrep = null;
1702
1703   /**
1704    * 
1705    * @return the representative sequence for this group
1706    */
1707   @Override
1708   public SequenceI getSeqrep()
1709   {
1710     return seqrep;
1711   }
1712
1713   /**
1714    * set the representative sequence for this group. Note - this affects the
1715    * interpretation of the Hidereps attribute.
1716    * 
1717    * @param seqrep
1718    *          the seqrep to set (null means no sequence representative)
1719    */
1720   @Override
1721   public void setSeqrep(SequenceI seqrep)
1722   {
1723     this.seqrep = seqrep;
1724   }
1725
1726   /**
1727    * 
1728    * @return true if group has a sequence representative
1729    */
1730   @Override
1731   public boolean hasSeqrep()
1732   {
1733     return seqrep != null;
1734   }
1735
1736   @Override
1737   public int getEndRes()
1738   {
1739     return getWidth() - 1;
1740   }
1741
1742   @Override
1743   public int getStartRes()
1744   {
1745     return 0;
1746   }
1747
1748   /*
1749    * In the case of AlignmentI - returns the dataset for the alignment, if set
1750    * (non-Javadoc)
1751    * 
1752    * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1753    */
1754   @Override
1755   public AnnotatedCollectionI getContext()
1756   {
1757     return dataset;
1758   }
1759
1760   /**
1761    * Align this alignment like the given (mapped) one.
1762    */
1763   @Override
1764   public int alignAs(AlignmentI al)
1765   {
1766     /*
1767      * Currently retains unmapped gaps (in introns), regaps mapped regions
1768      * (exons)
1769      */
1770     return alignAs(al, false, true);
1771   }
1772
1773   /**
1774    * Align this alignment 'the same as' the given one. Mapped sequences only are
1775    * realigned. If both of the same type (nucleotide/protein) then align both
1776    * identically. If this is nucleotide and the other is protein, make 3 gaps
1777    * for each gap in the protein sequences. If this is protein and the other is
1778    * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1779    * nucleotide bases. If this is protein and the other is nucleotide, gaps
1780    * protein to match the relative ordering of codons in the nucleotide.
1781    * 
1782    * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1783    * regions are preserved. Gaps that connect introns to exons are treated
1784    * conservatively, i.e. only preserved if both intron and exon gaps are
1785    * preserved. TODO: check caveats below where the implementation fails
1786    * 
1787    * @param al
1788    *          - must have same dataset, and sequences in al must have equivalent
1789    *          dataset sequence and start/end bounds under given mapping
1790    * @param preserveMappedGaps
1791    *          if true, gaps within and between mapped codons are preserved
1792    * @param preserveUnmappedGaps
1793    *          if true, gaps within and between unmapped codons are preserved
1794    */
1795   // @Override
1796   public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1797           boolean preserveUnmappedGaps)
1798   {
1799     // TODO should this method signature be the one in the interface?
1800     // JBPComment - yes - neither flag is used, so should be deleted.
1801     boolean thisIsNucleotide = this.isNucleotide();
1802     boolean thatIsProtein = !al.isNucleotide();
1803     if (!thatIsProtein && !thisIsNucleotide)
1804     {
1805       return AlignmentUtils.alignProteinAsDna(this, al);
1806     }
1807     else if (thatIsProtein && thisIsNucleotide)
1808     {
1809       return AlignmentUtils.alignCdsAsProtein(this, al);
1810     }
1811     return AlignmentUtils.alignAs(this, al);
1812   }
1813
1814   /**
1815    * Returns the alignment in Fasta format. Behaviour of this method is not
1816    * guaranteed between versions.
1817    */
1818   @Override
1819   public String toString()
1820   {
1821     return new FastaFile().print(getSequencesArray(), true);
1822   }
1823
1824   /**
1825    * Returns the set of distinct sequence names. No ordering is guaranteed.
1826    */
1827   @Override
1828   public Set<String> getSequenceNames()
1829   {
1830     Set<String> names = new HashSet<>();
1831     for (SequenceI seq : getSequences())
1832     {
1833       names.add(seq.getName());
1834     }
1835     return names;
1836   }
1837
1838   @Override
1839   public boolean hasValidSequence()
1840   {
1841     boolean hasValidSeq = false;
1842     for (SequenceI seq : getSequences())
1843     {
1844       if ((seq.getEnd() - seq.getStart()) > 0)
1845       {
1846         hasValidSeq = true;
1847         break;
1848       }
1849     }
1850     return hasValidSeq;
1851   }
1852
1853   /**
1854    * Update any mappings to 'virtual' sequences to compatible real ones, if
1855    * present in the added sequences. Returns a count of mappings updated.
1856    * 
1857    * @param seqs
1858    * @return
1859    */
1860   @Override
1861   public int realiseMappings(List<SequenceI> seqs)
1862   {
1863     int count = 0;
1864     for (SequenceI seq : seqs)
1865     {
1866       for (AlignedCodonFrame mapping : getCodonFrames())
1867       {
1868         count += mapping.realiseWith(seq);
1869       }
1870     }
1871     return count;
1872   }
1873
1874   /**
1875    * Returns the first AlignedCodonFrame that has a mapping between the given
1876    * dataset sequences
1877    * 
1878    * @param mapFrom
1879    * @param mapTo
1880    * @return
1881    */
1882   @Override
1883   public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1884   {
1885     for (AlignedCodonFrame acf : getCodonFrames())
1886     {
1887       if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1888       {
1889         return acf;
1890       }
1891     }
1892     return null;
1893   }
1894
1895   @Override
1896   public void setHiddenColumns(HiddenColumns cols)
1897   {
1898     hiddenCols = cols;
1899   }
1900
1901   @Override
1902   public void setupJPredAlignment()
1903   {
1904     SequenceI repseq = getSequenceAt(0);
1905     setSeqrep(repseq);
1906     HiddenColumns cs = new HiddenColumns();
1907     cs.hideList(repseq.getInsertions());
1908     setHiddenColumns(cs);
1909   }
1910
1911   @Override
1912   public HiddenColumns propagateInsertions(SequenceI profileseq,
1913           AlignmentView input)
1914   {
1915     int profsqpos = 0;
1916
1917     char gc = getGapCharacter();
1918     Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1919     HiddenColumns nview = (HiddenColumns) alandhidden[1];
1920     SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1921     return propagateInsertions(profileseq, origseq, nview);
1922   }
1923
1924   /**
1925    * 
1926    * @param profileseq
1927    *          sequence in al which corresponds to origseq
1928    * @param al
1929    *          alignment which is to have gaps inserted into it
1930    * @param origseq
1931    *          sequence corresponding to profileseq which defines gap map for
1932    *          modifying al
1933    */
1934   private HiddenColumns propagateInsertions(SequenceI profileseq,
1935           SequenceI origseq, HiddenColumns hc)
1936   {
1937     // take the set of hidden columns, and the set of gaps in origseq,
1938     // and remove all the hidden gaps from hiddenColumns
1939
1940     // first get the gaps as a Bitset
1941     // then calculate hidden ^ not(gap)
1942     BitSet gaps = origseq.gapBitset();
1943     hc.andNot(gaps);
1944
1945     // for each sequence in the alignment, except the profile sequence,
1946     // insert gaps corresponding to each hidden region but where each hidden
1947     // column region is shifted backwards by the number of preceding visible
1948     // gaps update hidden columns at the same time
1949     HiddenColumns newhidden = new HiddenColumns();
1950
1951     int numGapsBefore = 0;
1952     int gapPosition = 0;
1953     Iterator<int[]> it = hc.iterator();
1954     while (it.hasNext())
1955     {
1956       int[] region = it.next();
1957
1958       // get region coordinates accounting for gaps
1959       // we can rely on gaps not being *in* hidden regions because we already
1960       // removed those
1961       while (gapPosition < region[0])
1962       {
1963         gapPosition++;
1964         if (gaps.get(gapPosition))
1965         {
1966           numGapsBefore++;
1967         }
1968       }
1969
1970       int left = region[0] - numGapsBefore;
1971       int right = region[1] - numGapsBefore;
1972
1973       newhidden.hideColumns(left, right);
1974       padGaps(left, right, profileseq);
1975     }
1976     return newhidden;
1977   }
1978
1979   /**
1980    * Pad gaps in all sequences in alignment except profileseq
1981    * 
1982    * @param left
1983    *          position of first gap to insert
1984    * @param right
1985    *          position of last gap to insert
1986    * @param profileseq
1987    *          sequence not to pad
1988    */
1989   private void padGaps(int left, int right, SequenceI profileseq)
1990   {
1991     char gc = getGapCharacter();
1992
1993     // make a string with number of gaps = length of hidden region
1994     StringBuilder sb = new StringBuilder();
1995     for (int g = 0; g < right - left + 1; g++)
1996     {
1997       sb.append(gc);
1998     }
1999
2000     // loop over the sequences and pad with gaps where required
2001     for (int s = 0, ns = getHeight(); s < ns; s++)
2002     {
2003       SequenceI sqobj = getSequenceAt(s);
2004       if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2005       {
2006         String sq = sqobj.getSequenceAsString();
2007         sqobj.setSequence(
2008                 sq.substring(0, left) + sb.toString() + sq.substring(left));
2009       }
2010     }
2011   }
2012
2013 }