2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.bin.Cache;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.AlignFrame;
29 import jalview.gui.Desktop;
30 import jalview.gui.FeatureSettings;
31 import jalview.gui.JvOptionPane;
32 import jalview.util.DBRefUtils;
33 import jalview.util.MessageManager;
34 import jalview.util.UrlLink;
35 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
36 import jalview.ws.dbsources.das.api.jalviewSourceI;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Enumeration;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.List;
47 import java.util.StringTokenizer;
48 import java.util.Vector;
50 import org.biodas.jdas.client.FeaturesClient;
51 import org.biodas.jdas.client.adapters.features.DasGFFAdapter;
52 import org.biodas.jdas.client.adapters.features.DasGFFAdapter.GFFAdapter;
53 import org.biodas.jdas.client.threads.FeaturesClientMultipleSources;
54 import org.biodas.jdas.schema.features.ERRORSEGMENT;
55 import org.biodas.jdas.schema.features.FEATURE;
56 import org.biodas.jdas.schema.features.LINK;
57 import org.biodas.jdas.schema.features.SEGMENT;
58 import org.biodas.jdas.schema.features.TYPE;
59 import org.biodas.jdas.schema.features.UNKNOWNFEATURE;
60 import org.biodas.jdas.schema.features.UNKNOWNSEGMENT;
61 import org.biodas.jdas.schema.sources.COORDINATES;
69 public class DasSequenceFeatureFetcher
71 SequenceI[] sequences;
75 FeatureSettings fsettings;
77 StringBuffer sbuffer = new StringBuffer();
79 List<jalviewSourceI> selectedSources;
81 boolean cancelled = false;
83 private void debug(String mesg)
88 private void debug(String mesg, Exception e)
90 if (Cache.log != null)
92 Cache.log.debug(mesg, e);
96 System.err.println(mesg);
106 private DasSourceRegistryI sourceRegistry;
108 private boolean useJDASMultiThread = true;
111 * Creates a new SequenceFeatureFetcher object. Uses default
118 public DasSequenceFeatureFetcher(SequenceI[] sequences,
119 FeatureSettings fsettings, Vector selectedSources)
121 this(sequences, fsettings, selectedSources, true, true, true);
124 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
125 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
126 boolean checkDbrefs, boolean promptFetchDbrefs)
128 this(oursequences, fsettings, selectedSources2, checkDbrefs,
129 promptFetchDbrefs, true);
132 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
133 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
134 boolean checkDbrefs, boolean promptFetchDbrefs,
135 boolean useJDasMultiThread)
137 this.useJDASMultiThread = useJDasMultiThread;
138 this.selectedSources = new ArrayList<jalviewSourceI>();
139 // filter both sequences and sources to eliminate duplicates
140 for (jalviewSourceI src : selectedSources2)
142 if (!selectedSources.contains(src))
144 selectedSources.add(src);
148 Vector sqs = new Vector();
149 for (int i = 0; i < oursequences.length; i++)
151 if (!sqs.contains(oursequences[i]))
153 sqs.addElement(oursequences[i]);
156 sequences = new SequenceI[sqs.size()];
157 for (int i = 0; i < sequences.length; i++)
159 sequences[i] = (SequenceI) sqs.elementAt(i);
161 if (fsettings != null)
163 this.fsettings = fsettings;
164 this.af = fsettings.af;
165 af.setShowSeqFeatures(true);
167 int uniprotCount = 0;
168 for (jalviewSourceI source : selectedSources)
170 for (COORDINATES coords : source.getVersion().getCOORDINATES())
172 // TODO: match UniProt coord system canonically (?) - does
173 // UniProt==uniprot==UNIPROT ?
174 if (coords.getAuthority().toLowerCase().equals("uniprot"))
183 for (int i = 0; i < sequences.length; i++)
185 DBRefEntry[] dbref = sequences[i].getDBRefs();
188 for (int j = 0; j < dbref.length; j++)
190 if (dbref[j].getSource().equals(DBRefSource.UNIPROT))
199 if (checkDbrefs && refCount < sequences.length && uniprotCount > 0)
202 int reply = JvOptionPane.YES_OPTION;
203 if (promptFetchDbrefs)
206 .showInternalConfirmDialog(
209 .getString("info.you_want_jalview_to_find_uniprot_accessions"),
211 .getString("label.find_uniprot_accession_ids"),
212 JvOptionPane.YES_NO_OPTION,
213 JvOptionPane.QUESTION_MESSAGE);
216 if (reply == JvOptionPane.YES_OPTION)
218 Thread thread = new Thread(new FetchDBRefs());
233 private void _startFetching()
236 new Thread(new FetchSeqFeatures()).start();
239 class FetchSeqFeatures implements Runnable
245 setGuiFetchComplete();
249 class FetchDBRefs implements Runnable
255 boolean isNucleotide = af.getViewport().getAlignment().isNucleotide();
256 new DBRefFetcher(sequences, af, null, af.featureSettings,
257 isNucleotide).fetchDBRefs(true);
260 setGuiFetchComplete();
265 * Spawns Fetcher threads to add features to sequences in the dataset
271 startTime = System.currentTimeMillis();
274 af.setProgressBar(MessageManager
275 .getString("status.fetching_das_sequence_features"),
278 if (sourceRegistry == null)
280 sourceRegistry = Cache.getDasSourceRegistry();
282 if (selectedSources == null || selectedSources.size() == 0)
286 jalviewSourceI[] sources = sourceRegistry.getSources().toArray(
287 new jalviewSourceI[0]);
288 String active = Cache.getDefault("DAS_ACTIVE_SOURCE", "uniprot");
289 StringTokenizer st = new StringTokenizer(active, "\t");
290 selectedSources = new Vector();
292 while (st.hasMoreTokens())
294 token = st.nextToken();
295 for (int i = 0; i < sources.length; i++)
297 if (sources[i].getTitle().equals(token))
299 selectedSources.add(sources[i]);
304 } catch (Exception ex)
306 debug("Exception whilst setting default feature sources from registry and local preferences.",
311 if (selectedSources == null || selectedSources.size() == 0)
313 System.out.println("No DAS Sources active");
315 setGuiNoDassourceActive();
319 sourcesRemaining = selectedSources.size();
320 FeaturesClientMultipleSources fc = new FeaturesClientMultipleSources();
321 fc.setConnProps(sourceRegistry.getSessionHandler());
322 // Now sending requests one at a time to each server
323 ArrayList<jalviewSourceI> srcobj = new ArrayList<jalviewSourceI>();
324 ArrayList<String> src = new ArrayList<String>();
325 List<List<String>> ids = new ArrayList<List<String>>();
326 List<List<DBRefEntry>> idobj = new ArrayList<List<DBRefEntry>>();
327 List<Map<String, SequenceI>> sqset = new ArrayList<Map<String, SequenceI>>();
328 for (jalviewSourceI _sr : selectedSources)
331 Map<String, SequenceI> slist = new HashMap<String, SequenceI>();
332 List<DBRefEntry> idob = new ArrayList<DBRefEntry>();
333 List<String> qset = new ArrayList<String>();
335 for (SequenceI seq : sequences)
337 Object[] idset = nextSequence(_sr, seq);
340 List<DBRefEntry> _idob = (List<DBRefEntry>) idset[0];
341 List<String> _qset = (List<String>) idset[1];
342 if (_idob.size() > 0)
344 // add sequence's ref for each id derived from it
345 // (space inefficient, but most unambiguous)
346 // could replace with hash with _qset values as keys.
347 Iterator<DBRefEntry> dbobj = _idob.iterator();
348 for (String q : _qset)
350 SequenceI osq = slist.get(q);
351 DBRefEntry dr = dbobj.next();
352 if (osq != null && osq != seq)
354 // skip - non-canonical query
369 src.add(_sr.getSourceURL());
375 Map<String, Map<List<String>, Exception>> errors = new HashMap<String, Map<List<String>, Exception>>();
376 Map<String, Map<List<String>, DasGFFAdapter>> results = new HashMap<String, Map<List<String>, DasGFFAdapter>>();
377 if (!useJDASMultiThread)
379 Iterator<String> sources = src.iterator();
380 // iterate over each query for each source and do each one individually
381 for (List<String> idl : ids)
383 String source = sources.next();
384 FeaturesClient featuresc = new FeaturesClient(sourceRegistry
385 .getSessionHandler().getConnectionPropertyProviderFor(
387 for (String id : idl)
389 List<String> qid = Arrays.asList(new String[] { id });
392 DasGFFAdapter dga = featuresc.fetchData(source, qid);
393 Map<List<String>, DasGFFAdapter> ers = results.get(source);
397 ers = new HashMap<List<String>, DasGFFAdapter>());
400 } catch (Exception ex)
402 Map<List<String>, Exception> ers = errors.get(source);
406 ers = new HashMap<List<String>, Exception>());
415 // pass them all at once
416 fc.fetchData(src, ids, false, results, errors);
418 while (!fc.isTerminated())
423 } catch (InterruptedException x)
429 Iterator<List<String>> idset = ids.iterator();
430 Iterator<List<DBRefEntry>> idobjset = idobj.iterator();
431 Iterator<Map<String, SequenceI>> seqset = sqset.iterator();
432 for (jalviewSourceI source : srcobj)
434 processResponse(seqset.next(), source, idset.next(), idobjset.next(),
435 results.get(source.getSourceURL()),
436 errors.get(source.getSourceURL()));
440 private void processResponse(Map<String, SequenceI> sequencemap,
441 jalviewSourceI jvsource, List<String> ids,
442 List<DBRefEntry> idobj, Map<List<String>, DasGFFAdapter> results,
443 Map<List<String>, Exception> errors)
445 Set<SequenceI> sequences = new HashSet<SequenceI>();
446 String source = jvsource.getSourceURL();
448 DasGFFAdapter result = (results == null) ? null : results.get(ids);
449 Exception error = (errors == null) ? null : errors.get(ids);
452 debug("das source " + source + " could not be contacted. "
453 + (error == null ? "" : error.toString()));
458 GFFAdapter gff = result.getGFF();
459 List<SEGMENT> segments = gff.getSegments();
460 List<ERRORSEGMENT> errorsegs = gff.getErrorSegments();
461 List<UNKNOWNFEATURE> unkfeats = gff.getUnknownFeatures();
462 List<UNKNOWNSEGMENT> unksegs = gff.getUnknownSegments();
463 debug("das source " + source + " returned " + gff.getTotal()
464 + " responses. " + (errorsegs != null ? errorsegs.size() : 0)
465 + " were incorrect segment queries, "
466 + (unkfeats != null ? unkfeats.size() : 0)
467 + " were unknown features "
468 + (unksegs != null ? unksegs.size() : 0)
469 + " were unknown segments and "
470 + (segments != null ? segments.size() : 0)
471 + " were segment responses.");
472 Iterator<DBRefEntry> dbr = idobj.iterator();
473 if (segments != null)
475 for (SEGMENT seg : segments)
477 String id = seg.getId();
478 if (ids.indexOf(id) == -1)
480 id = id.toUpperCase();
482 DBRefEntry dbref = idobj.get(ids.indexOf(id));
483 SequenceI sequence = sequencemap.get(id);
484 boolean added = false;
485 sequences.add(sequence);
487 for (FEATURE feat : seg.getFEATURE())
489 // standard DAS feature-> jalview sequence feature transformation
490 SequenceFeature f = newSequenceFeature(feat,
491 jvsource.getTitle());
492 if (!parseSeqFeature(sequence, f, feat, jvsource))
494 if (dbref.getMap() != null && f.getBegin() > 0
497 debug("mapping from " + f.getBegin() + " - " + f.getEnd());
498 SequenceFeature vf[] = null;
502 vf = dbref.getMap().locateFeature(f);
503 } catch (Exception ex)
506 .warn("Error in 'experimental' mapping of features. Please try to reproduce and then report info to jalview-discuss@jalview.org.");
507 Cache.log.warn("Mapping feature from " + f.getBegin()
508 + " to " + f.getEnd() + " in dbref "
509 + dbref.getAccessionId() + " in "
510 + dbref.getSource());
511 Cache.log.warn("using das Source " + source);
512 Cache.log.warn("Exception", ex);
517 for (int v = 0; v < vf.length; v++)
519 debug("mapping to " + v + ": " + vf[v].getBegin()
520 + " - " + vf[v].getEnd());
521 sequence.addSequenceFeature(vf[v]);
527 sequence.addSequenceFeature(f);
532 featuresAdded(sequences);
536 // System.out.println("No features found for " + seq.getName()
537 // + " from: " + e.getDasSource().getNickname());
542 private void setGuiNoDassourceActive()
548 MessageManager.getString("status.no_das_sources_active"),
551 if (getFeatSettings() != null)
553 fsettings.noDasSourceActive();
558 * Update our fsettings dialog reference if we didn't have one when we were
563 private FeatureSettings getFeatSettings()
565 if (fsettings == null)
569 fsettings = af.featureSettings;
579 af.setProgressBar(MessageManager
580 .getString("status.das_feature_fetching_cancelled"),
586 int sourcesRemaining = 0;
588 private boolean running = false;
590 private void setGuiFetchComplete()
593 if (!cancelled && af != null)
595 // only update the progress bar if we've completed the fetch normally
596 af.setProgressBar(MessageManager
597 .getString("status.das_feature_fetching_complete"), startTime);
600 if (af != null && af.featureSettings != null)
602 af.featureSettings.discoverAllFeatureData();
605 if (getFeatSettings() != null)
607 fsettings.complete();
611 void featuresAdded(Set<SequenceI> seqs)
615 // no gui to update with features.
618 af.getFeatureRenderer().featuresAdded();
620 int start = af.getViewport().getStartSeq();
621 int end = af.getViewport().getEndSeq();
623 for (index = start; index < end; index++)
625 for (SequenceI seq : seqs)
627 if (seq == af.getViewport().getAlignment().getSequenceAt(index)
628 .getDatasetSequence())
630 af.alignPanel.paintAlignment(true);
638 Object[] nextSequence(jalviewSourceI dasSource, SequenceI seq)
644 DBRefEntry[] uprefs = DBRefUtils.selectRefs(seq.getDBRefs(),
646 // jalview.datamodel.DBRefSource.PDB,
648 // jalview.datamodel.DBRefSource.EMBL - not tested on any EMBL coord
651 // TODO: minimal list of DAS queries to make by querying with untyped ID if
652 // distinct from any typed IDs
654 List<DBRefEntry> ids = new ArrayList<DBRefEntry>();
655 List<String> qstring = new ArrayList<String>();
656 boolean dasCoordSysFound = false;
660 // do any of these ids match the source's coordinate system ?
661 for (int j = 0; !dasCoordSysFound && j < uprefs.length; j++)
664 for (COORDINATES csys : dasSource.getVersion().getCOORDINATES())
666 if (DBRefUtils.isDasCoordinateSystem(csys.getAuthority(),
669 debug("Launched fetcher for coordinate system "
670 + csys.getAuthority());
671 // Will have to pass any mapping information to the fetcher
672 // - the start/end for the DBRefEntry may not be the same as the
673 // sequence's start/end
675 System.out.println(seq.getName() + " "
676 + (seq.getDatasetSequence() == null) + " "
679 dasCoordSysFound = true; // break's out of the loop
681 qstring.add(uprefs[j].getAccessionId());
685 System.out.println("IGNORE " + csys.getAuthority());
691 if (!dasCoordSysFound)
694 // try and use the name as the sequence id
695 if (seq.getName().indexOf("|") > -1)
697 id = seq.getName().substring(seq.getName().lastIndexOf("|") + 1);
698 if (id.trim().length() < 4)
700 // hack - we regard a significant ID as being at least 4
701 // non-whitespace characters
702 id = seq.getName().substring(0, seq.getName().lastIndexOf("|"));
703 if (id.indexOf("|") > -1)
705 id = id.substring(id.lastIndexOf("|") + 1);
715 DBRefEntry dbre = new DBRefEntry();
716 dbre.setAccessionId(id);
717 // Should try to call a general feature fetcher that
718 // queries many sources with name to discover applicable ID references
720 qstring.add(dbre.getAccessionId());
724 return new Object[] { ids, qstring };
728 * examine the given sequence feature to determine if it should actually be
729 * turned into sequence annotation or database cross references rather than a
730 * simple sequence feature.
733 * the sequence to annotate
735 * the jalview sequence feature generated from the DAS feature
737 * the sequence feature attributes
739 * the source that emitted the feature
740 * @return true if feature was consumed as another kind of annotation.
742 protected boolean parseSeqFeature(SequenceI seq, SequenceFeature f,
743 FEATURE feature, jalviewSourceI source)
745 SequenceI mseq = seq;
746 while (seq.getDatasetSequence() != null)
748 seq = seq.getDatasetSequence();
750 if (f.getType() != null)
752 String type = f.getType();
753 if (type.equalsIgnoreCase("protein_name"))
755 // parse name onto the alignment sequence or the dataset sequence.
756 if (seq.getDescription() == null
757 || seq.getDescription().trim().length() == 0)
759 // could look at the note series to pick out the first long name, for
760 // the moment just use the whole description string
761 seq.setDescription(f.getDescription());
763 if (mseq.getDescription() == null
764 || mseq.getDescription().trim().length() == 0)
766 // could look at the note series to pick out the first long name, for
767 // the moment just use the whole description string
768 mseq.setDescription(f.getDescription());
772 // check if source has biosapiens or other sequence ontology label
773 if (type.equalsIgnoreCase("DBXREF") || type.equalsIgnoreCase("DBREF"))
775 // try to parse the accession out
777 DBRefEntry dbr = new DBRefEntry();
778 dbr.setVersion(source.getTitle());
779 StringTokenizer st = new StringTokenizer(f.getDescription(), ":");
780 if (st.hasMoreTokens())
782 dbr.setSource(st.nextToken());
784 if (st.hasMoreTokens())
786 dbr.setAccessionId(st.nextToken());
790 if (f.links != null && f.links.size() > 0)
792 // feature is also appended to enable links to be seen.
793 // TODO: consider extending dbrefs to have their own links ?
794 // TODO: new feature: extract dbref links from DAS servers and add the
795 // URL pattern to the list of DB name associated links in the user's
797 // for the moment - just fix up the existing feature so it displays
799 // f.setType(dbr.getSource());
800 // f.setDescription();
801 f.setValue("linkonly", Boolean.TRUE);
802 // f.setDescription("");
803 Vector newlinks = new Vector();
804 Enumeration it = f.links.elements();
805 while (it.hasMoreElements())
808 UrlLink urllink = new UrlLink(elm = (String) it.nextElement());
809 if (urllink.isValid())
811 urllink.setLabel(f.getDescription());
812 newlinks.addElement(urllink.toString());
816 // couldn't parse the link properly. Keep it anyway - just in
818 debug("couldn't parse link string - " + elm);
819 newlinks.addElement(elm);
823 seq.addSequenceFeature(f);
832 * creates a jalview sequence feature from a das feature document
835 * @return sequence feature object created using dasfeature information
837 SequenceFeature newSequenceFeature(FEATURE feat, String nickname)
846 * Different qNames for a DAS Feature - are string keys to the HashMaps in
847 * features "METHOD") || qName.equals("TYPE") || qName.equals("START") ||
848 * qName.equals("END") || qName.equals("NOTE") || qName.equals("LINK") ||
849 * qName.equals("SCORE")
851 String desc = new String();
852 if (feat.getNOTE() != null)
854 for (String note : feat.getNOTE())
860 int start = 0, end = 0;
865 start = Integer.parseInt(feat.getSTART().toString());
866 } catch (Exception ex)
871 end = Integer.parseInt(feat.getEND().toString());
872 } catch (Exception ex)
877 Object scr = feat.getSCORE();
880 score = (float) Double.parseDouble(scr.toString());
883 } catch (Exception ex)
887 SequenceFeature f = new SequenceFeature(
888 getTypeString(feat.getTYPE()), desc, start, end, score,
891 if (feat.getLINK() != null)
893 for (LINK link : feat.getLINK())
895 // Do not put feature extent in link text for non-positional features
896 if (f.begin == 0 && f.end == 0)
898 f.addLink(f.getType() + " " + link.getContent() + "|"
903 f.addLink(f.getType() + " " + f.begin + "_" + f.end + " "
904 + link.getContent() + "|" + link.getHref());
910 } catch (Exception e)
912 System.out.println("ERRR " + e);
914 System.out.println("############");
915 debug("Failed to parse " + feat.toString(), e);
920 private String getTypeString(TYPE type)
922 return type.getContent();
925 public boolean isRunning()