2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 import jalview.bin.Cache;
22 import jalview.datamodel.AlignedCodonFrame;
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.AlignmentView;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.GraphLine;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceI;
30 import jalview.gui.AlignFrame;
31 import jalview.gui.AlignViewport;
32 import jalview.gui.Desktop;
33 import jalview.gui.TreePanel;
34 import jalview.io.vamsas.Datasetsequence;
35 import jalview.io.vamsas.DatastoreItem;
36 import jalview.io.vamsas.Rangetype;
37 import jalview.util.UrlLink;
39 import java.io.IOException;
40 import java.util.Enumeration;
41 import java.util.HashMap;
42 import java.util.Hashtable;
43 import java.util.IdentityHashMap;
44 import java.util.Iterator;
45 import java.util.Vector;
46 import java.util.jar.JarInputStream;
47 import java.util.jar.JarOutputStream;
49 import uk.ac.vamsas.client.*;
50 import uk.ac.vamsas.objects.core.*;
51 import uk.ac.vamsas.objects.utils.Properties;
56 * org.exolab.castor.util.LocalConfiguration.getInstance().getProperties().setProperty(
57 * "org.exolab.castor.serializer", "org.apache.xml.serialize.XMLSerilazizer"); }
61 public class VamsasAppDatastore
64 * Type used for general jalview generated annotation added to vamsas document
66 public static final String JALVIEW_ANNOTATION_ROW = "JalviewAnnotation";
69 * AlignmentAnnotation property to indicate that values should not be
72 public static final String DISCRETE_ANNOTATION = "discrete";
75 * continuous property - optional to specify that annotation should be
76 * represented as a continous graph line
78 private static final String CONTINUOUS_ANNOTATION = "continuous";
80 private static final String THRESHOLD = "threshold";
83 * template for provenance entries written to vamsas session document
85 Entry provEntry = null;
88 * Instance of the session document being synchronized with
93 * map Vorba (vamsas object xml ref) IDs to live jalview object references
98 * map live jalview object references to Vorba IDs
100 IdentityHashMap jv2vobj;
103 * map jalview sequence set ID (which is vorba ID for alignment) to last
104 * recorded hash value for the alignment viewport (the undo/redo hash value)
106 Hashtable alignRDHash;
108 public VamsasAppDatastore(IClientDocument cdoc, Hashtable vobj2jv,
109 IdentityHashMap jv2vobj, Entry provEntry, Hashtable alignRDHash)
112 this.vobj2jv = vobj2jv;
113 this.jv2vobj = jv2vobj;
114 this.provEntry = provEntry;
115 this.alignRDHash = alignRDHash;
120 * the skipList used to skip over views from Jalview Appdata's that we've
121 * already syncrhonized
125 private void buildSkipList()
127 skipList = new Hashtable();
128 AlignFrame[] al = Desktop.getAlignframes();
129 for (int f = 0; al != null && f < al.length; f++)
131 skipList.put(al[f].getViewport().getSequenceSetId(), al[f]);
136 * @return the Vobject bound to Jalview datamodel object
138 protected Vobject getjv2vObj(Object jvobj)
140 if (jv2vobj.containsKey(jvobj))
142 return cdoc.getObject((VorbaId) jv2vobj.get(jvobj));
144 // check if we're working with a string - then workaround
145 // the use of IdentityHashTable because different strings
146 // have different object IDs.
147 if (jvobj instanceof String)
149 Object seqsetidobj = null;
150 seqsetidobj = getVamsasObjectBinding().get(jvobj);
151 if (seqsetidobj != null)
153 if (seqsetidobj instanceof String)
155 // what is expected. object returned by av.getSequenceSetId() -
156 // reverse lookup to get the 'registered' instance of this string
157 Vobject obj = getjv2vObj(seqsetidobj);
158 if (obj!=null && !(obj instanceof Alignment))
160 Cache.log.warn("IMPLEMENTATION ERROR?: Unexpected mapping for unmapped jalview string object content:"
161 + seqsetidobj + " to object " + obj);
167 Cache.log.warn("Unexpected mapping for Jalview String Object ID "
169 + " to another jalview dataset object " + seqsetidobj);
174 if (Cache.log.isDebugEnabled())
176 Cache.log.debug("Returning null VorbaID binding for jalview object "
185 * @return Jalview datamodel object bound to the vamsas document object
187 protected Object getvObj2jv(uk.ac.vamsas.client.Vobject vobj)
189 VorbaId id = vobj.getVorbaId();
192 id = cdoc.registerObject(vobj);
194 .debug("Registering new object and returning null for getvObj2jv");
197 if (vobj2jv.containsKey(vobj.getVorbaId()))
199 return vobj2jv.get(vobj.getVorbaId());
204 protected void bindjvvobj(Object jvobj, uk.ac.vamsas.client.Vobject vobj)
206 VorbaId id = vobj.getVorbaId();
209 id = cdoc.registerObject(vobj);
210 if (id == null || vobj.getVorbaId() == null
211 || cdoc.getObject(id) != vobj)
213 Cache.log.error("Failed to get id for "
214 + (vobj.isRegisterable() ? "registerable"
215 : "unregisterable") + " object " + vobj);
219 if (vobj2jv.containsKey(vobj.getVorbaId())
220 && !((VorbaId) vobj2jv.get(vobj.getVorbaId())).equals(jvobj))
223 "Warning? Overwriting existing vamsas id binding for "
224 + vobj.getVorbaId(), new Exception(
225 "Overwriting vamsas id binding."));
227 else if (jv2vobj.containsKey(jvobj)
228 && !((VorbaId) jv2vobj.get(jvobj)).equals(vobj.getVorbaId()))
231 "Warning? Overwriting existing jalview object binding for "
232 + jvobj, new Exception(
233 "Overwriting jalview object binding."));
236 * Cache.log.error("Attempt to make conflicting object binding! "+vobj+" id "
237 * +vobj.getVorbaId()+" already bound to "+getvObj2jv(vobj)+" and "+jvobj+"
238 * already bound to "+getjv2vObj(jvobj),new Exception("Excessive call to
241 // we just update the hash's regardless!
242 Cache.log.debug("Binding " + vobj.getVorbaId() + " to " + jvobj);
243 vobj2jv.put(vobj.getVorbaId(), jvobj);
244 // JBPNote - better implementing a hybrid invertible hash.
245 jv2vobj.put(jvobj, vobj.getVorbaId());
249 * put the alignment viewed by AlignViewport into cdoc.
252 * alignViewport to be stored
254 * title for alignment
255 * @return true if alignment associated with viewport was stored/synchronized to document
257 public boolean storeVAMSAS(AlignViewport av, String aFtitle)
261 jalview.datamodel.AlignmentI jal = av.getAlignment();
263 VAMSAS root = null; // will be resolved based on Dataset Parent.
264 // /////////////////////////////////////////
266 DataSet dataset = null;
267 if (jal.getDataset() == null)
269 Cache.log.warn("Creating new dataset for an alignment.");
270 jal.setDataset(null);
272 // try and get alignment and association for sequence set id
274 Alignment alignment = (Alignment) getjv2vObj(av.getSequenceSetId());
277 dataset = (DataSet) alignment.getV_parent();
279 // is the dataset already registered
280 dataset = (DataSet) getjv2vObj(jal.getDataset());
285 // it might be that one of the dataset sequences does actually have a
286 // binding, so search for it indirectly. If it does, then the local jalview dataset
287 // must be merged with the existing vamsas dataset.
288 jalview.datamodel.SequenceI[] jdatset = jal.getDataset()
289 .getSequencesArray();
290 for (int i = 0; i < jdatset.length; i++)
292 Vobject vbound = getjv2vObj(jdatset[i]);
295 if (vbound instanceof uk.ac.vamsas.objects.core.Sequence)
299 dataset = (DataSet) vbound.getV_parent();
303 if (vbound.getV_parent()!=null && dataset != vbound.getV_parent())
306 "IMPLEMENTATION ERROR: Cannot map an alignment of sequences from different datasets into a single alignment in the vamsas document.");
307 // This occurs because the dataset for the alignment we are
318 Cache.log.warn("Creating new vamsas dataset for alignment view "
319 + av.getSequenceSetId());
320 // we create a new dataset on the default vamsas root.
321 root = cdoc.getVamsasRoots()[0]; // default vamsas root for modifying.
322 dataset = new DataSet();
323 root.addDataSet(dataset);
324 bindjvvobj(jal.getDataset(), dataset);
325 dataset.setProvenance(dummyProvenance());
326 // dataset.getProvenance().addEntry(provEntry);
331 root = (VAMSAS) dataset.getV_parent();
336 // set new dataset and alignment sequences based on alignment Nucleotide
338 // this *will* break when alignment contains both nucleotide and amino
340 String dict = jal.isNucleotide() ? uk.ac.vamsas.objects.utils.SymbolDictionary.STANDARD_NA
341 : uk.ac.vamsas.objects.utils.SymbolDictionary.STANDARD_AA;
342 Vector dssmods = new Vector();
343 for (int i = 0; i < jal.getHeight(); i++)
345 SequenceI sq = jal.getSequenceAt(i).getDatasetSequence(); // only insert
349 Datasetsequence dssync = new jalview.io.vamsas.Datasetsequence(this, sq, dict, dataset);
350 sequence = (Sequence) dssync.getVobj();
351 if (dssync.getModified()) {
352 dssmods.addElement(sequence);
355 if (dssmods.size() > 0)
359 Entry pentry = this.addProvenance(dataset.getProvenance(),
360 "updated sequences");
361 // pentry.addInput(vInput); could write in which sequences were
363 dssmods.removeAllElements();
366 // dataset.setProvenance(getVamsasProvenance(jal.getDataset().getProvenance()));
367 // ////////////////////////////////////////////
368 if (!av.getAlignment().isAligned())
370 // TODO: trees could be written - but for the moment we just
372 // add to the JalviewXML skipList and ..
376 if (alignment == null)
378 alignment = new Alignment();
379 bindjvvobj(av.getSequenceSetId(), alignment);
380 if (alignment.getProvenance() == null)
382 alignment.setProvenance(new Provenance());
384 addProvenance(alignment.getProvenance(), "added"); // TODO: insert some
387 dataset.addAlignment(alignment);
389 Property title = new Property();
390 title.setName("title");
391 title.setType("string");
392 title.setContent(aFtitle);
393 alignment.addProperty(title);
395 alignment.setGapChar(String.valueOf(av.getGapCharacter()));
396 for (int i = 0; i < jal.getHeight(); i++)
398 syncToAlignmentSequence(jal.getSequenceAt(i), alignment, null);
400 alignRDHash.put(av.getSequenceSetId(), av.getUndoRedoHash());
404 // always prepare to clone the alignment
405 boolean alismod = av.isUndoRedoHashModified((long[]) alignRDHash
406 .get(av.getSequenceSetId()));
407 // todo: verify and update mutable alignment props.
408 // TODO: Use isLocked methods
409 if (alignment.getModifiable() == null
410 || alignment.getModifiable().length() == 0)
411 // && !alignment.isDependedOn())
413 boolean modified = false;
414 // check existing sequences in local and in document.
415 Vector docseqs = new Vector(alignment
416 .getAlignmentSequenceAsReference());
417 for (int i = 0; i < jal.getHeight(); i++)
419 modified |= syncToAlignmentSequence(jal.getSequenceAt(i),
422 if (docseqs.size() > 0)
424 // removeValignmentSequences(alignment, docseqs);
425 docseqs.removeAllElements();
427 .println("Sequence deletion from alignment is not implemented.");
435 addProvenance(alignment.getProvenance(), "Edited"); // TODO:
444 addProvenance(alignment.getProvenance(), "Attributes Edited"); // TODO:
454 System.out.println("update alignment in document.");
458 System.out.println("alignment in document left unchanged.");
463 // unbind alignment from view.
464 // create new binding and new alignment.
465 // mark trail on new alignment as being derived from old ?
467 .println("update edited alignment to new alignment in document.");
470 // ////////////////////////////////////////////
471 // SAVE Alignment Sequence Features
472 for (int i = 0, iSize = alignment.getAlignmentSequenceCount(); i < iSize; i++)
474 AlignmentSequence valseq;
475 SequenceI alseq = (SequenceI) getvObj2jv(valseq = alignment
476 .getAlignmentSequence(i));
477 if (alseq != null && alseq.getSequenceFeatures() != null)
480 * We do not put local Alignment Sequence Features into the vamsas
484 * jalview.datamodel.SequenceFeature[] features = alseq
485 * .getSequenceFeatures(); for (int f = 0; f < features.length; f++) {
486 * if (features[f] != null) { AlignmentSequenceAnnotation valseqf = (
487 * AlignmentSequenceAnnotation) getjv2vObj(features[i]); if (valseqf ==
490 * valseqf = (AlignmentSequenceAnnotation) getDSAnnotationFromJalview(
491 * new AlignmentSequenceAnnotation(), features[i]);
492 * valseqf.setGraph(false);
493 * valseqf.addProperty(newProperty("jalview:feature","boolean","true"));
494 * if (valseqf.getProvenance() == null) { valseqf.setProvenance(new
495 * Provenance()); } addProvenance(valseqf.getProvenance(), "created"); //
496 * JBPNote - // need to // update bindjvvobj(features[i], valseqf);
497 * valseq.addAlignmentSequenceAnnotation(valseqf); } } }
502 // ////////////////////////////////////////////
504 if (jal.getAlignmentAnnotation() != null)
506 jalview.datamodel.AlignmentAnnotation[] aa = jal
507 .getAlignmentAnnotation();
508 java.util.HashMap AlSeqMaps = new HashMap(); // stores int maps from
509 // alignment columns to
510 // sequence positions.
511 for (int i = 0; i < aa.length; i++)
513 if (aa[i] == null || isJalviewOnly(aa[i]))
517 if (aa[i].sequenceRef != null)
519 // Deal with sequence associated annotation
520 Vobject sref = getjv2vObj(aa[i].sequenceRef);
521 if (sref instanceof uk.ac.vamsas.objects.core.AlignmentSequence)
523 saveAlignmentSequenceAnnotation(AlSeqMaps,
524 (AlignmentSequence) sref, aa[i]);
528 // first find the alignment sequence to associate this with.
529 SequenceI jvalsq = null;
530 Enumeration jval = av.getAlignment().getSequences()
532 while (jval.hasMoreElements())
534 jvalsq = (SequenceI) jval.nextElement();
535 // saveDatasetSequenceAnnotation(AlSeqMaps,(uk.ac.vamsas.objects.core.Sequence)
537 if (jvalsq.getDatasetSequence() == aa[i].sequenceRef)
539 Vobject alsref = getjv2vObj(jvalsq);
540 saveAlignmentSequenceAnnotation(AlSeqMaps,
541 (AlignmentSequence) alsref, aa[i]);
550 // add Alignment Annotation
551 uk.ac.vamsas.objects.core.AlignmentAnnotation an = (uk.ac.vamsas.objects.core.AlignmentAnnotation) getjv2vObj(aa[i]);
554 an = new uk.ac.vamsas.objects.core.AlignmentAnnotation();
555 an.setType(JALVIEW_ANNOTATION_ROW);
556 an.setDescription(aa[i].description);
557 alignment.addAlignmentAnnotation(an);
558 Seg vSeg = new Seg(); // TODO: refactor to have a default
559 // rangeAnnotationType initer/updater that
560 // takes a set of int ranges.
562 vSeg.setInclusive(true);
563 vSeg.setEnd(jal.getWidth());
567 an.setGraph(true); // aa[i].graph);
569 an.setLabel(aa[i].label);
570 an.setProvenance(dummyProvenance());
571 if (aa[i].graph != AlignmentAnnotation.NO_GRAPH)
573 an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote
588 AnnotationElement ae;
590 for (int a = 0; a < aa[i].annotations.length; a++)
592 if ((aa[i] == null) || (aa[i].annotations[a] == null))
597 ae = new AnnotationElement();
598 ae.setDescription(aa[i].annotations[a].description);
599 ae.addGlyph(new Glyph());
600 ae.getGlyph(0).setContent(
601 aa[i].annotations[a].displayCharacter); // assume
610 ae.addValue(aa[i].annotations[a].value);
612 ae.setPosition(a + 1);
613 if (aa[i].annotations[a].secondaryStructure != ' ')
615 Glyph ss = new Glyph();
617 .setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
620 .valueOf(aa[i].annotations[a].secondaryStructure));
623 an.addAnnotationElement(ae);
627 // an.addProperty(newProperty("jalview:editable", null,
629 // an.setModifiable(""); // TODO: This is not the way the
630 // modifiable flag is supposed to be used.
632 setAnnotationType(an, aa[i]);
634 if (aa[i].graph != jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
637 an.setGroup(Integer.toString(aa[i].graphGroup));
638 if (aa[i].threshold != null && aa[i].threshold.displayed)
640 an.addProperty(Properties.newProperty(THRESHOLD, Properties.FLOATTYPE, ""
641 + aa[i].threshold.value));
642 if (aa[i].threshold.label != null)
644 an.addProperty(Properties.newProperty(THRESHOLD + "Name", Properties.STRINGTYPE,
645 "" + aa[i].threshold.label));
654 if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT
657 // verify annotation - update (perhaps)
659 .info("update alignment sequence annotation. not yet implemented.");
663 // verify annotation - update (perhaps)
665 .info("updated alignment sequence annotation added.");
671 // /////////////////////////////////////////////////////
673 // //////////////////////////////////////////////
675 // /////////////////////////////////
676 // FIND ANY ASSOCIATED TREES
677 if (Desktop.desktop != null)
679 javax.swing.JInternalFrame[] frames = Desktop.instance
682 for (int t = 0; t < frames.length; t++)
684 if (frames[t] instanceof TreePanel)
686 TreePanel tp = (TreePanel) frames[t];
688 if (tp.getAlignment() == jal)
690 DatastoreItem vtree = new jalview.io.vamsas.Tree(this, tp,
696 // Store Jalview specific stuff in the Jalview appData
697 // not implemented in the SimpleDoc interface.
702 ex.printStackTrace();
708 private void addToSkipList(AlignViewport av)
710 if (skipList == null)
712 skipList = new Hashtable();
714 skipList.put(av.getSequenceSetId(), av);
718 * remove docseqs from the given alignment marking provenance appropriately
719 * and removing any references to the sequences.
724 private void removeValignmentSequences(Alignment alignment, Vector docseqs)
726 // delete these from document. This really needs to be a generic document
727 // API function derived by CASTOR.
728 Enumeration en = docseqs.elements();
729 while (en.hasMoreElements())
731 alignment.removeAlignmentSequence((AlignmentSequence) en
734 Entry pe = addProvenance(alignment.getProvenance(), "Removed "
735 + docseqs.size() + " sequences");
736 en = alignment.enumerateAlignmentAnnotation();
737 Vector toremove = new Vector();
738 while (en.hasMoreElements())
740 uk.ac.vamsas.objects.core.AlignmentAnnotation alan = (uk.ac.vamsas.objects.core.AlignmentAnnotation) en
742 if (alan.getSeqrefsCount() > 0)
745 Vector storem = new Vector();
746 Enumeration sr = alan.enumerateSeqrefs();
747 while (sr.hasMoreElements())
749 Object alsr = sr.nextElement();
750 if (docseqs.contains(alsr))
752 storem.addElement(alsr);
755 // remove references to the deleted sequences
756 sr = storem.elements();
757 while (sr.hasMoreElements())
759 alan.removeSeqrefs(sr.nextElement());
762 if (alan.getSeqrefsCount() == 0)
764 // should then delete alan from dataset
765 toremove.addElement(alan);
769 // remove any annotation that used to be associated to a specific bunch of
771 en = toremove.elements();
772 while (en.hasMoreElements())
775 .removeAlignmentAnnotation((uk.ac.vamsas.objects.core.AlignmentAnnotation) en
778 // TODO: search through alignment annotations to remove any references to
779 // this alignment sequence
783 * sync a jalview alignment seuqence into a vamsas alignment assumes all lock
784 * transformation/bindings have been sorted out before hand. creates/syncs the
785 * vamsas alignment sequence for jvalsq and adds it to the alignment if
786 * necessary. unbounddocseq is a duplicate of the vamsas alignment sequences
787 * and these are removed after being processed w.r.t a bound jvalsq
790 private boolean syncToAlignmentSequence(SequenceI jvalsq,
791 Alignment alignment, Vector unbounddocseq)
793 boolean modal = false;
794 // todo: islocked method here
795 boolean up2doc = false;
796 AlignmentSequence alseq = (AlignmentSequence) getjv2vObj(jvalsq);
799 alseq = new AlignmentSequence();
804 if (unbounddocseq != null)
806 unbounddocseq.removeElement(alseq);
809 // boolean locked = (alignment.getModifiable()==null ||
810 // alignment.getModifiable().length()>0);
811 // TODO: VAMSAS: translate lowercase symbols to annotation ?
812 if (up2doc || !alseq.getSequence().equals(jvalsq.getSequenceAsString()))
814 alseq.setSequence(jvalsq.getSequenceAsString());
815 alseq.setStart(jvalsq.getStart());
816 alseq.setEnd(jvalsq.getEnd());
819 if (up2doc || !alseq.getName().equals(jvalsq.getName()))
822 alseq.setName(jvalsq.getName());
824 if (jvalsq.getDescription() != null
825 && (alseq.getDescription() == null || !jvalsq.getDescription()
826 .equals(alseq.getDescription())))
829 alseq.setDescription(jvalsq.getDescription());
831 if (getjv2vObj(jvalsq.getDatasetSequence()) == null)
834 .warn("Serious Implementation error - Unbound dataset sequence in alignment: "
835 + jvalsq.getDatasetSequence());
837 alseq.setRefid(getjv2vObj(jvalsq.getDatasetSequence()));
841 alignment.addAlignmentSequence(alseq);
842 bindjvvobj(jvalsq, alseq);
844 return up2doc || modal;
848 * locally sync a jalview alignment seuqence from a vamsas alignment assumes
849 * all lock transformation/bindings have been sorted out before hand.
850 * creates/syncs the jvalsq from the alignment sequence
852 private boolean syncFromAlignmentSequence(AlignmentSequence valseq,
853 char valGapchar, char gapChar, Vector dsseqs)
856 boolean modal = false;
857 // todo: islocked method here
858 boolean upFromdoc = false;
859 jalview.datamodel.SequenceI alseq = (SequenceI) getvObj2jv(valseq);
867 // boolean locked = (alignment.getModifiable()==null ||
868 // alignment.getModifiable().length()>0);
869 // TODO: VAMSAS: translate lowercase symbols to annotation ?
871 || !valseq.getSequence().equals(alseq.getSequenceAsString()))
873 // this might go *horribly* wrong
874 alseq.setSequence(new String(valseq.getSequence()).replace(
875 valGapchar, gapChar));
876 alseq.setStart((int) valseq.getStart());
877 alseq.setEnd((int) valseq.getEnd());
880 if (!valseq.getName().equals(alseq.getName()))
883 alseq.setName(valseq.getName());
885 if (alseq.getDescription()==null || (valseq.getDescription() != null && !alseq.getDescription()
886 .equals(valseq.getDescription())))
888 alseq.setDescription(valseq.getDescription());
891 if (modal && Cache.log.isDebugEnabled())
893 Cache.log.debug("Updating apparently edited sequence "
899 alseq = new jalview.datamodel.Sequence(valseq.getName(), valseq
900 .getSequence().replace(valGapchar, gapChar), (int) valseq
901 .getStart(), (int) valseq.getEnd());
903 Vobject datsetseq = (Vobject) valseq.getRefid();
904 if (datsetseq != null)
906 alseq.setDatasetSequence((SequenceI) getvObj2jv(datsetseq)); // exceptions
907 if (valseq.getDescription()!=null)
909 alseq.setDescription(valseq.getDescription());
911 // inherit description line from dataset.
912 if (alseq.getDatasetSequence().getDescription()!=null)
914 alseq.setDescription(alseq.getDatasetSequence().getDescription());
928 .error("Invalid dataset sequence id (null) for alignment sequence "
929 + valseq.getVorbaId());
931 bindjvvobj(alseq, valseq);
932 alseq.setVamsasId(valseq.getVorbaId().getId());
935 Vobject datsetseq = (Vobject) valseq.getRefid();
936 if (datsetseq != null)
938 if (datsetseq != alseq.getDatasetSequence())
942 alseq.setDatasetSequence((SequenceI) getvObj2jv(datsetseq)); // exceptions
944 return upFromdoc || modal;
947 private void initRangeAnnotationType(RangeAnnotation an,
948 AlignmentAnnotation alan, int[] gapMap)
950 Seg vSeg = new Seg();
952 vSeg.setInclusive(true);
953 vSeg.setEnd(gapMap.length);
956 // LATER: much of this is verbatim from the alignmentAnnotation
957 // method below. suggests refactoring to make rangeAnnotation the
959 an.setDescription(alan.description);
960 an.setLabel(alan.label);
961 an.setGroup(Integer.toString(alan.graphGroup));
970 AnnotationElement ae;
971 for (int a = 0; a < alan.annotations.length; a++)
973 if (alan.annotations[a] == null)
978 ae = new AnnotationElement();
979 ae.setDescription(alan.annotations[a].description);
980 ae.addGlyph(new Glyph());
981 ae.getGlyph(0).setContent(alan.annotations[a].displayCharacter); // assume
988 if (alan.graph != jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
990 ae.addValue(alan.annotations[a].value);
992 ae.setPosition(gapMap[a] + 1); // position w.r.t. AlignmentSequence
994 if (alan.annotations[a].secondaryStructure != ' ')
996 // we only write an annotation where it really exists.
997 Glyph ss = new Glyph();
999 .setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
1000 ss.setContent(String
1001 .valueOf(alan.annotations[a].secondaryStructure));
1004 an.addAnnotationElement(ae);
1009 private void saveDatasetSequenceAnnotation(HashMap AlSeqMaps,
1010 uk.ac.vamsas.objects.core.Sequence sref, AlignmentAnnotation alan)
1014 // objects.core.AlignmentSequence alsref = (uk.ac.vamsas.
1015 // objects.core.AlignmentSequence) sref;
1016 uk.ac.vamsas.objects.core.DataSetAnnotations an = (uk.ac.vamsas.objects.core.DataSetAnnotations) getjv2vObj(alan);
1017 int[] gapMap = getGapMap(AlSeqMaps, alan);
1020 an = new uk.ac.vamsas.objects.core.DataSetAnnotations();
1021 initRangeAnnotationType(an, alan, gapMap);
1023 an.setProvenance(dummyProvenance()); // get provenance as user
1024 // created, or jnet, or
1026 setAnnotationType(an, alan);
1027 an.setGroup(Integer.toString(alan.graphGroup)); // // JBPNote -
1035 if (alan.getThreshold() != null && alan.getThreshold().displayed)
1037 an.addProperty(Properties.newProperty(THRESHOLD, Properties.FLOATTYPE,
1039 + alan.getThreshold().value));
1040 if (alan.getThreshold().label != null)
1041 an.addProperty(Properties.newProperty(THRESHOLD + "Name", Properties.STRINGTYPE, ""
1042 + alan.getThreshold().label));
1044 ((DataSet) sref.getV_parent()).addDataSetAnnotations(an);
1045 bindjvvobj(alan, an);
1049 // update reference sequence Annotation
1050 if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK
1053 // verify existing alignment sequence annotation is up to date
1054 System.out.println("update dataset sequence annotation.");
1058 // verify existing alignment sequence annotation is up to date
1060 .println("make new alignment dataset sequence annotation if modification has happened.");
1066 private int[] getGapMap(HashMap AlSeqMaps, AlignmentAnnotation alan)
1069 if (AlSeqMaps.containsKey(alan.sequenceRef))
1071 gapMap = (int[]) AlSeqMaps.get(alan.sequenceRef);
1075 gapMap = new int[alan.sequenceRef.getLength()];
1076 // map from alignment position to sequence position.
1077 int[] sgapMap = alan.sequenceRef.gapMap();
1078 for (int a = 0; a < sgapMap.length; a++)
1080 gapMap[sgapMap[a]] = a;
1086 private void saveAlignmentSequenceAnnotation(HashMap AlSeqMaps,
1087 AlignmentSequence alsref, AlignmentAnnotation alan)
1091 // objects.core.AlignmentSequence alsref = (uk.ac.vamsas.
1092 // objects.core.AlignmentSequence) sref;
1093 uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation an = (uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation) getjv2vObj(alan);
1094 int[] gapMap = getGapMap(AlSeqMaps, alan);
1097 an = new uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation();
1098 initRangeAnnotationType(an, alan, gapMap);
1100 * I mean here that we don't actually have a semantic 'type' for the
1101 * annotation (this might be - score, intrinsic property, measurement,
1102 * something extracted from another program, etc)
1104 an.setType(JALVIEW_ANNOTATION_ROW); // TODO: better fix
1105 // this rough guess ;)
1106 alsref.addAlignmentSequenceAnnotation(an);
1107 bindjvvobj(alan, an);
1108 // These properties are directly supported by the
1109 // AlignmentSequenceAnnotation type.
1110 setAnnotationType(an, alan);
1111 an.setProvenance(dummyProvenance()); // get provenance as user
1112 // created, or jnet, or
1117 // update reference sequence Annotation
1118 if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK
1121 // verify existing alignment sequence annotation is up to date
1122 System.out.println("update alignment sequence annotation.");
1126 // verify existing alignment sequence annotation is up to date
1128 .println("make new alignment sequence annotation if modification has happened.");
1134 * set vamsas annotation object type from jalview annotation
1139 private void setAnnotationType(RangeAnnotation an,
1140 AlignmentAnnotation alan)
1142 if (an instanceof AlignmentSequenceAnnotation)
1144 if (alan.graph != AlignmentAnnotation.NO_GRAPH)
1146 ((AlignmentSequenceAnnotation) an).setGraph(true);
1150 ((AlignmentSequenceAnnotation) an).setGraph(false);
1153 if (an instanceof uk.ac.vamsas.objects.core.AlignmentAnnotation)
1155 if (alan.graph != AlignmentAnnotation.NO_GRAPH)
1157 ((uk.ac.vamsas.objects.core.AlignmentAnnotation) an).setGraph(true);
1161 ((uk.ac.vamsas.objects.core.AlignmentAnnotation) an)
1167 case AlignmentAnnotation.BAR_GRAPH:
1168 an.addProperty(Properties.newProperty(DISCRETE_ANNOTATION, Properties.BOOLEANTYPE, "true"));
1170 case AlignmentAnnotation.LINE_GRAPH:
1171 an.addProperty(Properties.newProperty(CONTINUOUS_ANNOTATION, Properties.BOOLEANTYPE, "true"));
1174 // don't add any kind of discrete or continous property info.
1180 * get start<end range of segment, adjusting for inclusivity flag and
1184 * @param ensureDirection
1185 * when true - always ensure start is less than end.
1186 * @return int[] { start, end, direction} where direction==1 for range running
1187 * from end to start.
1189 private int[] getSegRange(Seg visSeg, boolean ensureDirection)
1191 boolean incl = visSeg.getInclusive();
1192 // adjust for inclusive flag.
1193 int pol = (visSeg.getStart() <= visSeg.getEnd()) ? 1 : -1; // polarity of
1195 int start = visSeg.getStart() + (incl ? 0 : pol);
1196 int end = visSeg.getEnd() + (incl ? 0 : -pol);
1197 if (ensureDirection && pol == -1)
1199 // jalview doesn't deal with inverted ranges, yet.
1205 { start, end, pol < 0 ? 1 : 0 };
1211 * @return true if annotation is not to be stored in document
1213 private boolean isJalviewOnly(AlignmentAnnotation annotation)
1215 return annotation.autoCalculated || annotation.label.equals("Quality")
1216 || annotation.label.equals("Conservation")
1217 || annotation.label.equals("Consensus");
1220 boolean dojvsync = true;
1222 // boolean dojvsync = false; // disables Jalview AppData IO
1224 * list of alignment views created when updating Jalview from document.
1226 private Vector newAlignmentViews = new Vector();
1229 * update local jalview view settings from the stored appdata (if any)
1231 public void updateJalviewFromAppdata()
1233 // recover any existing Jalview data from appdata
1234 // TODO: recover any PDB files stored as attachments in the vamsas session
1235 // and initialise the Jalview2XML.alreadyLoadedPDB hashtable with mappings
1238 final IClientAppdata cappdata = cdoc.getClientAppdata();
1239 if (cappdata != null)
1241 if (cappdata.hasClientAppdata())
1243 // TODO: how to check version of Jalview client app data and whether
1244 // it has been modified
1245 // client data is shared over all app clients
1248 jalview.gui.Jalview2XML fromxml = new jalview.gui.Jalview2XML();
1249 fromxml.attemptversion1parse = false;
1250 fromxml.setUniqueSetSuffix("");
1251 fromxml.setObjectMappingTables(vobj2jv, jv2vobj); // mapKeysToString
1253 // mapValuesToString
1254 fromxml.setSkipList(skipList);
1255 jalview.util.jarInputStreamProvider jprovider = new jalview.util.jarInputStreamProvider()
1258 public String getFilename()
1261 // TODO Get the vamsas session ID here
1262 return "Jalview Vamsas Document Client Data";
1265 public JarInputStream getJarInputStream() throws IOException
1267 jalview.bin.Cache.log
1268 .debug("Returning client input stream for Jalview from Vamsas Document.");
1269 return new JarInputStream(cappdata.getClientInputStream());
1274 fromxml.LoadJalviewAlign(jprovider);
1276 } catch (Exception e)
1279 } catch (OutOfMemoryError e)
1288 if (cappdata.hasUserAppdata())
1290 // TODO: how to check version of Jalview user app data and whether it
1291 // has been modified
1292 // user data overrides data shared over all app clients ?
1295 jalview.gui.Jalview2XML fromxml = new jalview.gui.Jalview2XML();
1296 fromxml.attemptversion1parse = false;
1297 fromxml.setUniqueSetSuffix("");
1298 fromxml.setSkipList(skipList);
1299 fromxml.setObjectMappingTables(mapKeysToString(vobj2jv),
1300 mapValuesToString(jv2vobj));
1301 jalview.util.jarInputStreamProvider jarstream = new jalview.util.jarInputStreamProvider()
1304 public String getFilename()
1307 // TODO Get the vamsas session ID here
1308 return "Jalview Vamsas Document User Data";
1311 public JarInputStream getJarInputStream() throws IOException
1313 jalview.bin.Cache.log
1314 .debug("Returning user input stream for Jalview from Vamsas Document.");
1315 return new JarInputStream(cappdata.getUserInputStream());
1320 fromxml.LoadJalviewAlign(jarstream);
1322 } catch (Exception e)
1325 } catch (OutOfMemoryError e)
1335 flushAlignViewports();
1339 * remove any spurious views generated by document synchronization
1341 private void flushAlignViewports()
1343 // remove any additional viewports originally recovered from the vamsas
1345 // search for all alignframes containing viewports generated from document
1347 // and if any contain more than one view, then remove the one generated by
1349 AlignViewport views[], av = null;
1350 AlignFrame af = null;
1351 Iterator newviews = newAlignmentViews.iterator();
1352 while (newviews.hasNext())
1354 av = (AlignViewport) newviews.next();
1355 af = Desktop.getAlignFrameFor(av);
1356 // TODO implement this : af.getNumberOfViews
1357 String seqsetidobj = av.getSequenceSetId();
1358 views = Desktop.getViewports(seqsetidobj);
1359 Cache.log.debug("Found "
1360 + (views == null ? " no " : "" + views.length)
1361 + " views for '" + av.getSequenceSetId() + "'");
1362 if (views.length > 1)
1364 // we need to close the original document view.
1366 // work out how to do this by seeing if the views are gathered.
1367 // pretty clunky but the only way to do this without adding more flags
1368 // to the align frames.
1369 boolean gathered = false;
1370 String newviewid = null;
1371 AlignedCodonFrame[] mappings = av.getAlignment().getCodonFrames();
1372 for (int i = 0; i < views.length; i++)
1376 AlignFrame viewframe = Desktop.getAlignFrameFor(views[i]);
1377 if (viewframe == af)
1381 newviewid = views[i].getSequenceSetId();
1385 // lose the reference to the vamsas document created view
1389 // close the view generated by the vamsas document synchronization
1396 af.closeMenuItem_actionPerformed(false);
1398 replaceJvObjMapping(seqsetidobj, newviewid);
1399 seqsetidobj = newviewid;
1400 // not sure if we need to do this:
1402 if (false) // mappings != null)
1404 // ensure sequence mappings from vamsas document view still
1406 if (mappings != null && mappings.length > 0)
1408 jalview.structure.StructureSelectionManager
1409 .getStructureSelectionManager().addMappings(mappings);
1413 // ensure vamsas object binds to the stored views retrieved from
1415 //jalview.structure.StructureSelectionManager
1416 // .getStructureSelectionManager()
1417 // .addStructureViewerListener(viewframe.alignPanel);
1422 newAlignmentViews.clear();
1426 * replaces oldjvobject with newjvobject in the Jalview Object <> VorbaID
1429 * @param oldjvobject
1430 * @param newjvobject (may be null)
1432 private void replaceJvObjMapping(Object oldjvobject, Object newjvobject)
1434 Object vobject = jv2vobj.remove(oldjvobject);
1435 if (vobject == null)
1438 "IMPLEMENTATION ERROR: old jalview object is not bound ! ("
1439 + oldjvobject + ")");
1441 if (newjvobject!=null)
1443 jv2vobj.put(newjvobject, vobject);
1444 vobj2jv.put(vobject, newjvobject);
1449 * Update the jalview client and user appdata from the local jalview settings
1451 public void updateJalviewClientAppdata()
1453 final IClientAppdata cappdata = cdoc.getClientAppdata();
1454 if (cappdata != null)
1458 jalview.gui.Jalview2XML jxml = new jalview.gui.Jalview2XML();
1459 jxml.setObjectMappingTables(mapKeysToString(vobj2jv),
1460 mapValuesToString(jv2vobj));
1461 jxml.setSkipList(skipList);
1464 jxml.SaveState(new JarOutputStream(cappdata
1465 .getClientOutputStream()));
1468 } catch (Exception e)
1470 // TODO raise GUI warning if user requests it.
1471 jalview.bin.Cache.log
1473 "Couldn't update jalview client application data. Giving up - local settings probably lost.",
1479 jalview.bin.Cache.log
1480 .error("Couldn't access client application data for vamsas session. This is probably a vamsas client bug.");
1485 * translate the Vobject keys to strings for use in Jalview2XML
1490 private IdentityHashMap mapValuesToString(IdentityHashMap jv2vobj2)
1492 IdentityHashMap mapped = new IdentityHashMap();
1493 Iterator keys = jv2vobj2.keySet().iterator();
1494 while (keys.hasNext())
1496 Object key = keys.next();
1497 mapped.put(key, jv2vobj2.get(key).toString());
1503 * translate the Vobject values to strings for use in Jalview2XML
1506 * @return hashtable with string values
1508 private Hashtable mapKeysToString(Hashtable vobj2jv2)
1510 Hashtable mapped = new Hashtable();
1511 Iterator keys = vobj2jv2.keySet().iterator();
1512 while (keys.hasNext())
1514 Object key = keys.next();
1515 mapped.put(key.toString(), vobj2jv2.get(key));
1520 * synchronize Jalview from the vamsas document
1522 public void updateToJalview()
1524 VAMSAS _roots[] = cdoc.getVamsasRoots();
1526 for (int _root = 0; _root < _roots.length; _root++)
1528 VAMSAS root = _roots[_root];
1529 boolean newds = false;
1530 for (int _ds = 0, _nds = root.getDataSetCount(); _ds < _nds; _ds++)
1532 // ///////////////////////////////////
1534 DataSet dataset = root.getDataSet(_ds);
1535 int i, iSize = dataset.getSequenceCount();
1537 jalview.datamodel.Alignment jdataset = (jalview.datamodel.Alignment) getvObj2jv(dataset);
1539 if (jdataset == null)
1541 Cache.log.debug("Initialising new jalview dataset fields");
1543 dsseqs = new Vector();
1547 Cache.log.debug("Update jalview dataset from vamsas.");
1548 jremain = jdataset.getHeight();
1549 dsseqs = jdataset.getSequences();
1552 // TODO: test sequence merging - we preserve existing non vamsas
1553 // sequences but add in any new vamsas ones, and don't yet update any
1554 // sequence attributes
1555 for (i = 0; i < iSize
1558 Sequence vdseq = dataset.getSequence(i);
1559 jalview.io.vamsas.Datasetsequence dssync = new Datasetsequence(this, vdseq);
1561 jalview.datamodel.SequenceI dsseq = (SequenceI) dssync.getJvobj();
1562 if (dssync.isAddfromdoc())
1566 if (vdseq.getDbRefCount() > 0)
1568 DbRef[] dbref = vdseq.getDbRef();
1569 for (int db = 0; db < dbref.length; db++)
1571 new jalview.io.vamsas.Dbref(this, dbref[db], vdseq, dsseq);
1574 dsseq.updatePDBIds();
1580 SequenceI[] seqs = new SequenceI[dsseqs.size()];
1581 for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1583 seqs[i] = (SequenceI) dsseqs.elementAt(i);
1584 dsseqs.setElementAt(null, i);
1586 jdataset = new jalview.datamodel.Alignment(seqs);
1587 Cache.log.debug("New vamsas dataset imported into jalview.");
1588 bindjvvobj(jdataset, dataset);
1591 // add any new dataset sequence feature annotations
1592 if (dataset.getDataSetAnnotations() != null)
1594 for (int dsa = 0; dsa < dataset.getDataSetAnnotationsCount(); dsa++)
1596 DataSetAnnotations dseta = dataset.getDataSetAnnotations(dsa);
1597 // TODO: deal with group annotation on datset sequences.
1598 if (dseta.getSeqRefCount() == 1)
1600 SequenceI dsSeq = (SequenceI) getvObj2jv((Vobject) dseta
1601 .getSeqRef(0)); // TODO: deal with group dataset
1605 jalview.bin.Cache.log
1606 .warn("Couldn't resolve jalview sequenceI for dataset object reference "
1607 + ((Vobject) dataset.getDataSetAnnotations(
1608 dsa).getSeqRef(0)).getVorbaId()
1613 if (dseta.getAnnotationElementCount() == 0)
1615 new jalview.io.vamsas.Sequencefeature(this, dseta, dsSeq);
1620 // TODO: deal with alignmentAnnotation style annotation
1621 // appearing on dataset sequences.
1622 // JBPNote: we could just add them to all alignments but
1623 // that may complicate cross references in the jalview
1626 .warn("Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
1630 Cache.log.warn("Ignoring multiply referenced dataset sequence annotation for binding to datsaet sequence features.");
1634 if (dataset.getAlignmentCount() > 0)
1636 // LOAD ALIGNMENTS from DATASET
1638 for (int al = 0, nal = dataset.getAlignmentCount(); al < nal; al++)
1640 uk.ac.vamsas.objects.core.Alignment alignment = dataset
1642 // TODO check this handles multiple views properly
1643 AlignViewport av = findViewport(alignment);
1645 jalview.datamodel.AlignmentI jal = null;
1648 // TODO check that correct alignment object is retrieved when
1649 // hidden seqs exist.
1650 jal = (av.hasHiddenRows()) ? av.getAlignment()
1651 .getHiddenSequences().getFullAlignment() : av
1654 iSize = alignment.getAlignmentSequenceCount();
1655 boolean newal = (jal == null) ? true : false;
1656 boolean refreshal = false;
1657 Vector newasAnnots = new Vector();
1658 char gapChar = ' '; // default for new alignments read in from the
1662 dsseqs = jal.getSequences(); // for merge/update
1663 gapChar = jal.getGapCharacter();
1667 dsseqs = new Vector();
1669 char valGapchar = alignment.getGapChar().charAt(0);
1670 for (i = 0; i < iSize; i++)
1672 AlignmentSequence valseq = alignment.getAlignmentSequence(i);
1673 jalview.datamodel.Sequence alseq = (jalview.datamodel.Sequence) getvObj2jv(valseq);
1674 if (syncFromAlignmentSequence(valseq, valGapchar, gapChar,
1679 // updated to sequence from the document
1683 if (valseq.getAlignmentSequenceAnnotationCount() > 0)
1685 AlignmentSequenceAnnotation[] vasannot = valseq
1686 .getAlignmentSequenceAnnotation();
1687 for (int a = 0; a < vasannot.length; a++)
1689 jalview.datamodel.AlignmentAnnotation asa = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(vasannot[a]); // TODO:
1697 int se[] = getBounds(vasannot[a]);
1698 asa = getjAlignmentAnnotation(jal, vasannot[a]);
1699 asa.setSequenceRef(alseq);
1700 asa.createSequenceMapping(alseq, se[0], false); // TODO:
1711 alseq.addAlignmentAnnotation(asa);
1712 bindjvvobj(asa, vasannot[a]);
1713 newasAnnots.add(asa);
1717 // update existing annotation - can do this in place
1718 if (vasannot[a].getModifiable() == null) // TODO: USE
1724 .info("UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");
1725 // TODO: should at least replace with new one - otherwise
1726 // things will break
1727 // basically do this:
1728 // int se[] = getBounds(vasannot[a]);
1729 // asa.update(getjAlignmentAnnotation(jal, vasannot[a]));
1730 // // update from another annotation object in place.
1731 // asa.createSequenceMapping(alseq, se[0], false);
1740 SequenceI[] seqs = new SequenceI[dsseqs.size()];
1741 for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1743 seqs[i] = (SequenceI) dsseqs.elementAt(i);
1744 dsseqs.setElementAt(null, i);
1746 jal = new jalview.datamodel.Alignment(seqs);
1747 Cache.log.debug("New vamsas alignment imported into jalview "
1748 + alignment.getVorbaId().getId());
1749 jal.setDataset(jdataset);
1751 if (newasAnnots != null && newasAnnots.size() > 0)
1753 // Add the new sequence annotations in to the alignment.
1754 for (int an = 0, anSize = newasAnnots.size(); an < anSize; an++)
1756 jal.addAnnotation((AlignmentAnnotation) newasAnnots
1758 // TODO: check if anything has to be done - like calling
1759 // adjustForAlignment or something.
1760 newasAnnots.setElementAt(null, an);
1764 // //////////////////////////////////////////
1765 // //LOAD ANNOTATIONS FOR THE ALIGNMENT
1766 // ////////////////////////////////////
1767 if (alignment.getAlignmentAnnotationCount() > 0)
1769 uk.ac.vamsas.objects.core.AlignmentAnnotation[] an = alignment
1770 .getAlignmentAnnotation();
1772 for (int j = 0; j < an.length; j++)
1774 jalview.datamodel.AlignmentAnnotation jan = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(an[j]);
1777 // update or stay the same.
1778 // TODO: should at least replace with a new one - otherwise
1779 // things will break
1780 // basically do this:
1781 // jan.update(getjAlignmentAnnotation(jal, an[a])); // update
1782 // from another annotation object in place.
1785 .debug("update from vamsas alignment annotation to existing jalview alignment annotation.");
1786 if (an[j].getModifiable() == null) // TODO: USE VAMSAS
1787 // LIBRARY OBJECT LOCK
1790 // TODO: user defined annotation is totally mutable... - so
1791 // load it up or throw away if locally edited.
1793 .info("NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");
1795 // TODO: compare annotation element rows
1796 // TODO: compare props.
1800 jan = getjAlignmentAnnotation(jal, an[j]);
1801 jal.addAnnotation(jan);
1802 bindjvvobj(jan, an[j]);
1806 AlignFrame alignFrame;
1809 Cache.log.debug("New alignframe for alignment "
1810 + alignment.getVorbaId());
1811 // ///////////////////////////////
1812 // construct alignment view
1813 alignFrame = new AlignFrame(jal, AlignFrame.DEFAULT_WIDTH,
1814 AlignFrame.DEFAULT_HEIGHT, alignment.getVorbaId()
1816 av = alignFrame.getViewport();
1817 newAlignmentViews.addElement(av);
1818 String title = alignment.getProvenance().getEntry(
1819 alignment.getProvenance().getEntryCount() - 1)
1821 if (alignment.getPropertyCount() > 0)
1823 for (int p = 0, pe = alignment.getPropertyCount(); p < pe; p++)
1825 if (alignment.getProperty(p).getName().equals("title"))
1827 title = alignment.getProperty(p).getContent();
1831 // TODO: automatically create meaningful title for a vamsas
1832 // alignment using its provenance.
1833 if (Cache.log.isDebugEnabled())
1835 title = title + "(" + alignment.getVorbaId() + ")";
1838 jalview.gui.Desktop.addInternalFrame(alignFrame, title,
1839 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1840 bindjvvobj(av.getSequenceSetId(), alignment);
1844 // find the alignFrame for jal.
1845 // TODO: fix this so we retrieve the alignFrame handing av
1846 // *directly* (JBPNote - don't understand this now)
1847 // TODO: make sure all associated views are refreshed
1848 alignFrame = Desktop.getAlignFrameFor(av);
1851 av.alignmentChanged(alignFrame.alignPanel);
1855 // /////////////////////////////////////
1856 if (alignment.getTreeCount() > 0)
1859 for (int t = 0; t < alignment.getTreeCount(); t++)
1861 jalview.io.vamsas.Tree vstree = new jalview.io.vamsas.Tree(
1862 this, alignFrame, alignment.getTree(t));
1863 TreePanel tp = null;
1864 if (vstree.isValidTree())
1866 tp = alignFrame.ShowNewickTree(vstree.getNewickTree(),
1867 vstree.getTitle(), vstree.getInputData(), 600,
1868 500, t * 20 + 50, t * 20 + 50);
1873 bindjvvobj(tp, alignment.getTree(t));
1876 vstree.UpdateSequenceTreeMap(tp);
1877 } catch (RuntimeException e)
1879 Cache.log.warn("update of labels failed.", e);
1884 Cache.log.warn("Cannot create tree for tree " + t
1886 + alignment.getTree(t).getVorbaId());
1894 // we do sequenceMappings last because they span all datasets in a vamsas
1896 for (int _ds = 0, _nds = root.getDataSetCount(); _ds < _nds; _ds++)
1898 DataSet dataset = root.getDataSet(_ds);
1899 if (dataset.getSequenceMappingCount() > 0)
1901 for (int sm = 0, smCount = dataset.getSequenceMappingCount(); sm < smCount; sm++)
1903 Rangetype seqmap = new jalview.io.vamsas.Sequencemapping(this,
1904 dataset.getSequenceMapping(sm));
1911 public AlignViewport findViewport(Alignment alignment)
1913 AlignViewport av = null;
1914 AlignViewport[] avs = Desktop
1915 .getViewports((String) getvObj2jv(alignment));
1923 // bitfields - should be a template in j1.5
1924 private static int HASSECSTR = 0;
1926 private static int HASVALS = 1;
1928 private static int HASHPHOB = 2;
1930 private static int HASDC = 3;
1932 private static int HASDESCSTR = 4;
1934 private static int HASTWOSTATE = 5; // not used yet.
1937 * parses the AnnotationElements - if they exist - into
1938 * jalview.datamodel.Annotation[] rows Two annotation rows are made if there
1939 * are distinct annotation for both at 'pos' and 'after pos' at any particular
1943 * @return { boolean[static int constants ], int[ae.length] - map to annotated
1944 * object frame, jalview.datamodel.Annotation[],
1945 * jalview.datamodel.Annotation[] (after)}
1947 private Object[] parseRangeAnnotation(
1948 uk.ac.vamsas.objects.core.RangeAnnotation annotation)
1950 // set these attributes by looking in the annotation to decide what kind of
1951 // alignment annotation rows will be made
1952 // TODO: potentially we might make several annotation rows from one vamsas
1953 // alignment annotation. the jv2Vobj binding mechanism
1954 // may not quite cope with this (without binding an array of annotations to
1955 // a vamsas alignment annotation)
1956 // summary flags saying what we found over the set of annotation rows.
1957 boolean[] AeContent = new boolean[]
1958 { false, false, false, false, false };
1959 int[] rangeMap = getMapping(annotation);
1960 jalview.datamodel.Annotation[][] anot = new jalview.datamodel.Annotation[][]
1961 { new jalview.datamodel.Annotation[rangeMap.length],
1962 new jalview.datamodel.Annotation[rangeMap.length] };
1963 boolean mergeable = true; // false if 'after positions cant be placed on
1964 // same annotation row as positions.
1966 if (annotation.getAnnotationElementCount() > 0)
1968 AnnotationElement ae[] = annotation.getAnnotationElement();
1969 for (int aa = 0; aa < ae.length; aa++)
1971 int pos = (int) ae[aa].getPosition() - 1; // pos counts from 1 to
1972 // (|seg.start-seg.end|+1)
1973 if (pos >= 0 && pos < rangeMap.length)
1975 int row = ae[aa].getAfter() ? 1 : 0;
1976 if (anot[row][pos] != null)
1978 // only time this should happen is if the After flag is set.
1979 Cache.log.debug("Ignoring duplicate annotation site at " + pos);
1982 if (anot[1 - row][pos] != null)
1987 if (ae[aa].getDescription() != null)
1989 desc = ae[aa].getDescription();
1990 if (desc.length() > 0)
1992 // have imported valid description string
1993 AeContent[HASDESCSTR] = true;
1996 String dc = null; // ae[aa].getDisplayCharacter()==null ? "dc" :
1997 // ae[aa].getDisplayCharacter();
1998 String ss = null; // ae[aa].getSecondaryStructure()==null ? "ss" :
1999 // ae[aa].getSecondaryStructure();
2000 java.awt.Color colour = null;
2001 if (ae[aa].getGlyphCount() > 0)
2003 Glyph[] glyphs = ae[aa].getGlyph();
2004 for (int g = 0; g < glyphs.length; g++)
2009 uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE))
2011 ss = glyphs[g].getContent();
2012 AeContent[HASSECSTR] = true;
2017 uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO))
2019 Cache.log.debug("ignoring hydrophobicity glyph marker.");
2020 AeContent[HASHPHOB] = true;
2021 char c = (dc = glyphs[g].getContent()).charAt(0);
2022 // dc may get overwritten - but we still set the colour.
2023 colour = new java.awt.Color(c == '+' ? 255 : 0,
2024 c == '.' ? 255 : 0, c == '-' ? 255 : 0);
2027 else if (glyphs[g].getDict().equals(
2028 uk.ac.vamsas.objects.utils.GlyphDictionary.DEFAULT))
2030 dc = glyphs[g].getContent();
2031 AeContent[HASDC] = true;
2036 .debug("IMPLEMENTATION TODO: Ignoring unknown glyph type "
2037 + glyphs[g].getDict());
2042 if (ae[aa].getValueCount() > 0)
2044 AeContent[HASVALS] = true;
2045 if (ae[aa].getValueCount() > 1)
2047 Cache.log.warn("ignoring additional "
2048 + (ae[aa].getValueCount() - 1)
2049 + "values in annotation element.");
2051 val = ae[aa].getValue(0);
2055 anot[row][pos] = new jalview.datamodel.Annotation(
2056 (dc != null) ? dc : "", desc, (ss != null) ? ss
2057 .charAt(0) : ' ', val);
2061 anot[row][pos] = new jalview.datamodel.Annotation(
2062 (dc != null) ? dc : "", desc, (ss != null) ? ss
2063 .charAt(0) : ' ', val, colour);
2068 Cache.log.warn("Ignoring out of bound annotation element " + aa
2069 + " in " + annotation.getVorbaId().getId());
2072 // decide on how many annotation rows are needed.
2075 for (int i = 0; i < anot[0].length; i++)
2077 if (anot[1][i] != null)
2079 anot[0][i] = anot[1][i];
2080 anot[0][i].description = anot[0][i].description + " (after)";
2081 AeContent[HASDESCSTR] = true; // we have valid description string
2090 for (int i = 0; i < anot[0].length; i++)
2092 anot[1][i].description = anot[1][i].description + " (after)";
2096 { AeContent, rangeMap, anot[0], anot[1] };
2100 // no annotations to parse. Just return an empty annotationElement[]
2103 { AeContent, rangeMap, anot[0], anot[1] };
2110 * the jalview alignment to which the annotation will be
2111 * attached (ideally - freshly updated from corresponding
2114 * @return unbound jalview alignment annotation object.
2116 private jalview.datamodel.AlignmentAnnotation getjAlignmentAnnotation(
2117 jalview.datamodel.AlignmentI jal,
2118 uk.ac.vamsas.objects.core.RangeAnnotation annotation)
2120 if (annotation == null)
2125 // hasSequenceRef=annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation.class);
2126 // boolean hasProvenance=hasSequenceRef ||
2127 // (annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentAnnotation.class));
2129 * int se[] = getBounds(annotation); if (se==null) se=new int[]
2130 * {0,jal.getWidth()-1};
2132 Object[] parsedRangeAnnotation = parseRangeAnnotation(annotation);
2133 String a_label = annotation.getLabel();
2134 String a_descr = annotation.getDescription();
2135 GraphLine gl = null;
2137 boolean interp = true; // cleared if annotation is DISCRETE
2138 // set type and other attributes from properties
2139 if (annotation.getPropertyCount() > 0)
2141 // look for special jalview properties
2142 uk.ac.vamsas.objects.core.Property[] props = annotation.getProperty();
2143 for (int p = 0; p < props.length; p++)
2145 if (props[p].getName().equalsIgnoreCase(DISCRETE_ANNOTATION))
2147 type = AlignmentAnnotation.BAR_GRAPH;
2150 else if (props[p].getName().equalsIgnoreCase(CONTINUOUS_ANNOTATION))
2152 type = AlignmentAnnotation.LINE_GRAPH;
2154 else if (props[p].getName().equalsIgnoreCase(THRESHOLD))
2159 val = new Float(props[p].getContent());
2160 } catch (Exception e)
2162 Cache.log.warn("Failed to parse threshold property");
2167 gl = new GraphLine(val.floatValue(), "", java.awt.Color.black);
2171 gl.value = val.floatValue();
2174 else if (props[p].getName().equalsIgnoreCase(THRESHOLD + "Name"))
2177 gl = new GraphLine(0, "", java.awt.Color.black);
2178 gl.label = props[p].getContent();
2182 jalview.datamodel.AlignmentAnnotation jan = null;
2183 if (a_label == null || a_label.length() == 0)
2185 a_label = annotation.getType();
2186 if (a_label.length() == 0)
2188 a_label = "Unamed annotation";
2191 if (a_descr == null || a_descr.length() == 0)
2193 a_descr = "Annotation of type '" + annotation.getType() + "'";
2195 if (parsedRangeAnnotation == null)
2198 .debug("Inserting empty annotation row elements for a whole-alignment annotation.");
2202 if (parsedRangeAnnotation[3] != null)
2204 Cache.log.warn("Ignoring 'After' annotation row in "
2205 + annotation.getVorbaId());
2207 jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2];
2208 boolean[] has = (boolean[]) parsedRangeAnnotation[0];
2209 // VAMSAS: getGraph is only on derived annotation for alignments - in this
2210 // way its 'odd' - there is already an existing TODO about removing this
2211 // flag as being redundant
2214 * ((annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentAnnotation.class) &&
2215 * ((uk.ac.vamsas.objects.core.AlignmentAnnotation)annotation).getGraph()) ||
2216 * (hasSequenceRef=true &&
2217 * ((uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation)annotation).getGraph())) {
2223 type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH; // default
2229 // no hints - so we ensure HPHOB display is like this.
2230 type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH;
2233 // make bounds and automatic description strings for jalview user's
2234 // benefit (these shouldn't be written back to vamsas document)
2235 boolean first = true;
2236 float min = 0, max = 1;
2238 for (int i = 0; i < arow.length; i++)
2240 if (arow[i] != null)
2242 if (i - lastval > 1 && interp)
2244 // do some interpolation *between* points
2245 if (arow[lastval] != null)
2247 float interval = arow[i].value - arow[lastval].value;
2248 interval /= i - lastval;
2249 float base = arow[lastval].value;
2250 for (int ip = lastval + 1, np = 0; ip < i; np++, ip++)
2252 arow[ip] = new jalview.datamodel.Annotation("", "", ' ',
2253 interval * np + base);
2254 // NB - Interpolated points don't get a tooltip and
2260 // check range - shouldn't we have a min and max property in the
2261 // annotation object ?
2264 min = max = arow[i].value;
2269 if (arow[i].value < min)
2271 min = arow[i].value;
2273 else if (arow[i].value > max)
2275 max = arow[i].value;
2278 // make tooltip and display char value
2279 if (!has[HASDESCSTR])
2281 arow[i].description = arow[i].value + "";
2287 if (arow[i].description != null
2288 && arow[i].description.length() < 3)
2290 // copy over the description as the display char.
2291 arow[i].displayCharacter = new String(arow[i].description);
2296 // mark the position as a point used for the interpolation.
2297 arow[i].displayCharacter = arow[i].value + "";
2302 jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr,
2303 arow, min, max, type);
2307 if (annotation.getAnnotationElementCount() == 0)
2309 // empty annotation array
2310 // TODO: alignment 'features' compare rangeType spec to alignment
2311 // width - if it is not complete, then mark regions on the annotation
2314 jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr,
2316 jan.setThreshold(null);
2317 jan.annotationId = annotation.getVorbaId().toString(); // keep all the
2320 if (annotation.getLinkCount() > 0)
2322 Cache.log.warn("Ignoring " + annotation.getLinkCount()
2323 + "links added to AlignmentAnnotation.");
2325 if (annotation.getModifiable() == null
2326 || annotation.getModifiable().length() == 0) // TODO: USE VAMSAS
2330 jan.editable = true;
2334 if (annotation.getGroup() != null
2335 && annotation.getGroup().length() > 0)
2337 jan.graphGroup = Integer.parseInt(annotation.getGroup()); // TODO:
2345 } catch (Exception e)
2348 .info("UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");
2359 * get real bounds of a RangeType's specification. start and end are an
2360 * inclusive range within which all segments and positions lie. TODO: refactor
2364 * @return int[] { start, end}
2366 private int[] getBounds(RangeType dseta)
2371 if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
2374 "Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
2376 if (dseta.getSegCount() > 0)
2378 se = getSegRange(dseta.getSeg(0), true);
2379 for (int s = 1, sSize = dseta.getSegCount(); s < sSize; s++)
2381 int nse[] = getSegRange(dseta.getSeg(s), true);
2392 if (dseta.getPosCount() > 0)
2394 // could do a polarity for pos range too. and pass back indication of
2396 int pos = dseta.getPos(0).getI();
2399 for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
2401 pos = dseta.getPos(p).getI();
2418 * map from a rangeType's internal frame to the referenced object's coordinate
2422 * @return int [] { ref(pos)...} for all pos in rangeType's frame.
2424 private int[] getMapping(RangeType dseta)
2426 Vector posList = new Vector();
2430 if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
2433 "Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
2435 if (dseta.getSegCount() > 0)
2437 for (int s = 0, sSize = dseta.getSegCount(); s < sSize; s++)
2439 se = getSegRange(dseta.getSeg(s), false);
2440 int se_end = se[1 - se[2]] + (se[2] == 0 ? 1 : -1);
2441 for (int p = se[se[2]]; p != se_end; p += se[2] == 0 ? 1 : -1)
2443 posList.add(new Integer(p));
2447 else if (dseta.getPosCount() > 0)
2449 int pos = dseta.getPos(0).getI();
2451 for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
2453 pos = dseta.getPos(p).getI();
2454 posList.add(new Integer(pos));
2458 if (posList != null && posList.size() > 0)
2460 int[] range = new int[posList.size()];
2461 for (int i = 0; i < range.length; i++)
2463 range[i] = ((Integer) posList.elementAt(i)).intValue();
2474 * where the from range is the local mapped range, and the to
2475 * range is the 'mapped' range in the MapRangeType
2482 private jalview.util.MapList parsemapType(MapType maprange, int localu,
2485 jalview.util.MapList ml = null;
2486 int[] localRange = getMapping(maprange.getLocal());
2487 int[] mappedRange = getMapping(maprange.getMapped());
2488 long lu = maprange.getLocal().hasUnit() ? maprange.getLocal().getUnit()
2490 long mu = maprange.getMapped().hasUnit() ? maprange.getMapped()
2491 .getUnit() : mappedu;
2492 ml = new jalview.util.MapList(localRange, mappedRange, (int) lu,
2498 * initialise a range type object from a set of start/end inclusive intervals
2503 private void initRangeType(RangeType mrt, int[] range)
2505 for (int i = 0; i < range.length; i += 2)
2507 Seg vSeg = new Seg();
2508 vSeg.setStart(range[i]);
2509 vSeg.setEnd(range[i + 1]);
2515 * initialise a MapType object from a MapList object.
2521 private void initMapType(MapType maprange, jalview.util.MapList ml,
2524 maprange.setLocal(new Local());
2525 maprange.setMapped(new Mapped());
2526 initRangeType(maprange.getLocal(), ml.getFromRanges());
2527 initRangeType(maprange.getMapped(), ml.getToRanges());
2530 maprange.getLocal().setUnit(ml.getFromRatio());
2531 maprange.getLocal().setUnit(ml.getToRatio());
2536 * not needed now. Provenance getVamsasProvenance(jalview.datamodel.Provenance
2537 * jprov) { jalview.datamodel.ProvenanceEntry[] entries = null; // TODO: fix
2538 * App and Action here. Provenance prov = new Provenance();
2539 * org.exolab.castor.types.Date date = new org.exolab.castor.types.Date( new
2540 * java.util.Date()); Entry provEntry;
2542 * if (jprov != null) { entries = jprov.getEntries(); for (int i = 0; i <
2543 * entries.length; i++) { provEntry = new Entry(); try { date = new
2544 * org.exolab.castor.types.Date(entries[i].getDate()); } catch (Exception ex) {
2545 * ex.printStackTrace();
2547 * date = new org.exolab.castor.types.Date(entries[i].getDate()); }
2548 * provEntry.setDate(date); provEntry.setUser(entries[i].getUser());
2549 * provEntry.setAction(entries[i].getAction()); prov.addEntry(provEntry); } }
2550 * else { provEntry = new Entry(); provEntry.setDate(date);
2551 * provEntry.setUser(System.getProperty("user.name")); // TODO: ext string
2552 * provEntry.setApp("JVAPP"); // TODO: ext string provEntry.setAction(action);
2553 * prov.addEntry(provEntry); }
2557 jalview.datamodel.Provenance getJalviewProvenance(Provenance prov)
2559 // TODO: fix App and Action entries and check use of provenance in jalview.
2560 jalview.datamodel.Provenance jprov = new jalview.datamodel.Provenance();
2561 for (int i = 0; i < prov.getEntryCount(); i++)
2563 jprov.addEntry(prov.getEntry(i).getUser(), prov.getEntry(i)
2564 .getAction(), prov.getEntry(i).getDate(), prov.getEntry(i)
2573 * @return default initial provenance list for a Jalview created vamsas
2576 Provenance dummyProvenance()
2578 return dummyProvenance(null);
2581 Entry dummyPEntry(String action)
2583 Entry entry = new Entry();
2584 entry.setApp(this.provEntry.getApp());
2587 entry.setAction(action);
2591 entry.setAction("created.");
2593 entry.setDate(new java.util.Date());
2594 entry.setUser(this.provEntry.getUser());
2598 Provenance dummyProvenance(String action)
2600 Provenance prov = new Provenance();
2601 prov.addEntry(dummyPEntry(action));
2605 Entry addProvenance(Provenance p, String action)
2607 Entry dentry = dummyPEntry(action);
2612 public Entry getProvEntry()
2617 public IClientDocument getClientDocument()
2622 public IdentityHashMap getJvObjectBinding()
2627 public Hashtable getVamsasObjectBinding()
2632 public void storeSequenceMappings(AlignViewport viewport, String title)
2635 AlignViewport av = viewport;
2638 jalview.datamodel.AlignmentI jal = av.getAlignment();
2639 // /////////////////////////////////////////
2641 DataSet dataset = null;
2642 if (jal.getDataset() == null)
2644 Cache.log.warn("Creating new dataset for an alignment.");
2645 jal.setDataset(null);
2647 dataset = (DataSet) getjv2vObj(jal.getDataset());
2648 // Store any sequence mappings.
2649 if (av.getAlignment().getCodonFrames() != null
2650 && av.getAlignment().getCodonFrames().length > 0)
2652 jalview.datamodel.AlignedCodonFrame[] cframes = av.getAlignment()
2654 for (int cf = 0; cf < cframes.length; cf++)
2656 if (cframes[cf].getdnaSeqs().length > 0)
2658 jalview.datamodel.SequenceI[] dmps = cframes[cf].getdnaSeqs();
2659 jalview.datamodel.Mapping[] mps = cframes[cf].getProtMappings();
2660 for (int smp = 0; smp < mps.length; smp++)
2662 uk.ac.vamsas.objects.core.SequenceType mfrom = (SequenceType) getjv2vObj(dmps[smp]);
2665 new jalview.io.vamsas.Sequencemapping(this, mps[smp],
2671 .warn("NO Vamsas Binding for local sequence! NOT CREATING MAPPING FOR "
2672 + dmps[smp].getDisplayId(true)
2674 + mps[smp].getTo().getName());
2680 } catch (Exception e)
2682 throw new Exception("Couldn't store sequence mappings for " + title,
2687 public void clearSkipList()
2689 if (skipList != null)
2696 * @return the skipList
2698 public Hashtable getSkipList()
2704 * @param skipList the skipList to set
2706 public void setSkipList(Hashtable skipList)
2708 this.skipList = skipList;