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)
205 reply = JvOptionPane.showInternalConfirmDialog(Desktop.desktop,
206 MessageManager.getString(
207 "info.you_want_jalview_to_find_uniprot_accessions"),
209 .getString("label.find_uniprot_accession_ids"),
210 JvOptionPane.YES_NO_OPTION, JvOptionPane.QUESTION_MESSAGE);
213 if (reply == JvOptionPane.YES_OPTION)
215 Thread thread = new Thread(new FetchDBRefs());
230 private void _startFetching()
233 new Thread(new FetchSeqFeatures()).start();
236 class FetchSeqFeatures implements Runnable
242 setGuiFetchComplete();
246 class FetchDBRefs implements Runnable
252 boolean isNucleotide = af.getViewport().getAlignment().isNucleotide();
253 new DBRefFetcher(sequences, af, null, af.featureSettings,
254 isNucleotide).fetchDBRefs(true);
257 setGuiFetchComplete();
262 * Spawns Fetcher threads to add features to sequences in the dataset
268 startTime = System.currentTimeMillis();
271 af.setProgressBar(MessageManager.getString(
272 "status.fetching_das_sequence_features"), startTime);
274 if (sourceRegistry == null)
276 sourceRegistry = Cache.getDasSourceRegistry();
278 if (selectedSources == null || selectedSources.size() == 0)
282 jalviewSourceI[] sources = sourceRegistry.getSources()
283 .toArray(new jalviewSourceI[0]);
284 String active = Cache.getDefault("DAS_ACTIVE_SOURCE", "uniprot");
285 StringTokenizer st = new StringTokenizer(active, "\t");
286 selectedSources = new Vector();
288 while (st.hasMoreTokens())
290 token = st.nextToken();
291 for (int i = 0; i < sources.length; i++)
293 if (sources[i].getTitle().equals(token))
295 selectedSources.add(sources[i]);
300 } catch (Exception ex)
302 debug("Exception whilst setting default feature sources from registry and local preferences.",
307 if (selectedSources == null || selectedSources.size() == 0)
309 System.out.println("No DAS Sources active");
311 setGuiNoDassourceActive();
315 sourcesRemaining = selectedSources.size();
316 FeaturesClientMultipleSources fc = new FeaturesClientMultipleSources();
317 fc.setConnProps(sourceRegistry.getSessionHandler());
318 // Now sending requests one at a time to each server
319 ArrayList<jalviewSourceI> srcobj = new ArrayList<jalviewSourceI>();
320 ArrayList<String> src = new ArrayList<String>();
321 List<List<String>> ids = new ArrayList<List<String>>();
322 List<List<DBRefEntry>> idobj = new ArrayList<List<DBRefEntry>>();
323 List<Map<String, SequenceI>> sqset = new ArrayList<Map<String, SequenceI>>();
324 for (jalviewSourceI _sr : selectedSources)
327 Map<String, SequenceI> slist = new HashMap<String, SequenceI>();
328 List<DBRefEntry> idob = new ArrayList<DBRefEntry>();
329 List<String> qset = new ArrayList<String>();
331 for (SequenceI seq : sequences)
333 Object[] idset = nextSequence(_sr, seq);
336 List<DBRefEntry> _idob = (List<DBRefEntry>) idset[0];
337 List<String> _qset = (List<String>) idset[1];
338 if (_idob.size() > 0)
340 // add sequence's ref for each id derived from it
341 // (space inefficient, but most unambiguous)
342 // could replace with hash with _qset values as keys.
343 Iterator<DBRefEntry> dbobj = _idob.iterator();
344 for (String q : _qset)
346 SequenceI osq = slist.get(q);
347 DBRefEntry dr = dbobj.next();
348 if (osq != null && osq != seq)
350 // skip - non-canonical query
365 src.add(_sr.getSourceURL());
371 Map<String, Map<List<String>, Exception>> errors = new HashMap<String, Map<List<String>, Exception>>();
372 Map<String, Map<List<String>, DasGFFAdapter>> results = new HashMap<String, Map<List<String>, DasGFFAdapter>>();
373 if (!useJDASMultiThread)
375 Iterator<String> sources = src.iterator();
376 // iterate over each query for each source and do each one individually
377 for (List<String> idl : ids)
379 String source = sources.next();
380 FeaturesClient featuresc = new FeaturesClient(
381 sourceRegistry.getSessionHandler()
382 .getConnectionPropertyProviderFor(source));
383 for (String id : idl)
385 List<String> qid = Arrays.asList(new String[] { id });
388 DasGFFAdapter dga = featuresc.fetchData(source, qid);
389 Map<List<String>, DasGFFAdapter> ers = results.get(source);
393 ers = new HashMap<List<String>, DasGFFAdapter>());
396 } catch (Exception ex)
398 Map<List<String>, Exception> ers = errors.get(source);
402 ers = new HashMap<List<String>, Exception>());
411 // pass them all at once
412 fc.fetchData(src, ids, false, results, errors);
414 while (!fc.isTerminated())
419 } catch (InterruptedException x)
425 Iterator<List<String>> idset = ids.iterator();
426 Iterator<List<DBRefEntry>> idobjset = idobj.iterator();
427 Iterator<Map<String, SequenceI>> seqset = sqset.iterator();
428 for (jalviewSourceI source : srcobj)
430 processResponse(seqset.next(), source, idset.next(), idobjset.next(),
431 results.get(source.getSourceURL()),
432 errors.get(source.getSourceURL()));
436 private void processResponse(Map<String, SequenceI> sequencemap,
437 jalviewSourceI jvsource, List<String> ids, List<DBRefEntry> idobj,
438 Map<List<String>, DasGFFAdapter> results,
439 Map<List<String>, Exception> errors)
441 Set<SequenceI> sequences = new HashSet<SequenceI>();
442 String source = jvsource.getSourceURL();
444 DasGFFAdapter result = (results == null) ? null : results.get(ids);
445 Exception error = (errors == null) ? null : errors.get(ids);
448 debug("das source " + source + " could not be contacted. "
449 + (error == null ? "" : error.toString()));
454 GFFAdapter gff = result.getGFF();
455 List<SEGMENT> segments = gff.getSegments();
456 List<ERRORSEGMENT> errorsegs = gff.getErrorSegments();
457 List<UNKNOWNFEATURE> unkfeats = gff.getUnknownFeatures();
458 List<UNKNOWNSEGMENT> unksegs = gff.getUnknownSegments();
459 debug("das source " + source + " returned " + gff.getTotal()
460 + " responses. " + (errorsegs != null ? errorsegs.size() : 0)
461 + " were incorrect segment queries, "
462 + (unkfeats != null ? unkfeats.size() : 0)
463 + " were unknown features "
464 + (unksegs != null ? unksegs.size() : 0)
465 + " were unknown segments and "
466 + (segments != null ? segments.size() : 0)
467 + " were segment responses.");
468 Iterator<DBRefEntry> dbr = idobj.iterator();
469 if (segments != null)
471 for (SEGMENT seg : segments)
473 String id = seg.getId();
474 if (ids.indexOf(id) == -1)
476 id = id.toUpperCase();
478 DBRefEntry dbref = idobj.get(ids.indexOf(id));
479 SequenceI sequence = sequencemap.get(id);
480 boolean added = false;
481 sequences.add(sequence);
483 for (FEATURE feat : seg.getFEATURE())
485 // standard DAS feature-> jalview sequence feature transformation
486 SequenceFeature f = newSequenceFeature(feat,
487 jvsource.getTitle());
488 if (!parseSeqFeature(sequence, f, feat, jvsource))
490 if (dbref.getMap() != null && f.getBegin() > 0
493 debug("mapping from " + f.getBegin() + " - " + f.getEnd());
494 SequenceFeature vf[] = null;
498 vf = dbref.getMap().locateFeature(f);
499 } catch (Exception ex)
502 "Error in 'experimental' mapping of features. Please try to reproduce and then report info to jalview-discuss@jalview.org.");
503 Cache.log.warn("Mapping feature from " + f.getBegin()
504 + " to " + f.getEnd() + " in dbref "
505 + dbref.getAccessionId() + " in "
506 + dbref.getSource());
507 Cache.log.warn("using das Source " + source);
508 Cache.log.warn("Exception", ex);
513 for (int v = 0; v < vf.length; v++)
515 debug("mapping to " + v + ": " + vf[v].getBegin()
516 + " - " + vf[v].getEnd());
517 sequence.addSequenceFeature(vf[v]);
523 sequence.addSequenceFeature(f);
528 featuresAdded(sequences);
532 // System.out.println("No features found for " + seq.getName()
533 // + " from: " + e.getDasSource().getNickname());
538 private void setGuiNoDassourceActive()
544 MessageManager.getString("status.no_das_sources_active"),
547 if (getFeatSettings() != null)
549 fsettings.noDasSourceActive();
554 * Update our fsettings dialog reference if we didn't have one when we were
559 private FeatureSettings getFeatSettings()
561 if (fsettings == null)
565 fsettings = af.featureSettings;
575 af.setProgressBar(MessageManager.getString(
576 "status.das_feature_fetching_cancelled"), startTime);
581 int sourcesRemaining = 0;
583 private boolean running = false;
585 private void setGuiFetchComplete()
588 if (!cancelled && af != null)
590 // only update the progress bar if we've completed the fetch normally
591 af.setProgressBar(MessageManager.getString(
592 "status.das_feature_fetching_complete"), startTime);
595 if (af != null && af.featureSettings != null)
597 af.featureSettings.discoverAllFeatureData();
600 if (getFeatSettings() != null)
602 fsettings.complete();
606 void featuresAdded(Set<SequenceI> seqs)
610 // no gui to update with features.
613 af.getFeatureRenderer().featuresAdded();
615 int start = af.getViewport().getRanges().getStartSeq();
616 int end = af.getViewport().getRanges().getEndSeq();
618 for (index = start; index < end; index++)
620 for (SequenceI seq : seqs)
622 if (seq == af.getViewport().getAlignment().getSequenceAt(index)
623 .getDatasetSequence())
625 af.alignPanel.paintAlignment(true);
633 Object[] nextSequence(jalviewSourceI dasSource, SequenceI seq)
639 DBRefEntry[] uprefs = DBRefUtils.selectRefs(seq.getDBRefs(),
642 // jalview.datamodel.DBRefSource.PDB,
644 // jalview.datamodel.DBRefSource.EMBL - not tested on any EMBL coord
647 // TODO: minimal list of DAS queries to make by querying with untyped ID if
648 // distinct from any typed IDs
650 List<DBRefEntry> ids = new ArrayList<DBRefEntry>();
651 List<String> qstring = new ArrayList<String>();
652 boolean dasCoordSysFound = false;
656 // do any of these ids match the source's coordinate system ?
657 for (int j = 0; !dasCoordSysFound && j < uprefs.length; j++)
660 for (COORDINATES csys : dasSource.getVersion().getCOORDINATES())
662 if (DBRefUtils.isDasCoordinateSystem(csys.getAuthority(),
665 debug("Launched fetcher for coordinate system "
666 + csys.getAuthority());
667 // Will have to pass any mapping information to the fetcher
668 // - the start/end for the DBRefEntry may not be the same as the
669 // sequence's start/end
672 seq.getName() + " " + (seq.getDatasetSequence() == null)
673 + " " + csys.getUri());
675 dasCoordSysFound = true; // break's out of the loop
677 qstring.add(uprefs[j].getAccessionId());
681 System.out.println("IGNORE " + csys.getAuthority());
687 if (!dasCoordSysFound)
690 // try and use the name as the sequence id
691 if (seq.getName().indexOf("|") > -1)
693 id = seq.getName().substring(seq.getName().lastIndexOf("|") + 1);
694 if (id.trim().length() < 4)
696 // hack - we regard a significant ID as being at least 4
697 // non-whitespace characters
698 id = seq.getName().substring(0, seq.getName().lastIndexOf("|"));
699 if (id.indexOf("|") > -1)
701 id = id.substring(id.lastIndexOf("|") + 1);
711 DBRefEntry dbre = new DBRefEntry();
712 dbre.setAccessionId(id);
713 // Should try to call a general feature fetcher that
714 // queries many sources with name to discover applicable ID references
716 qstring.add(dbre.getAccessionId());
720 return new Object[] { ids, qstring };
724 * examine the given sequence feature to determine if it should actually be
725 * turned into sequence annotation or database cross references rather than a
726 * simple sequence feature.
729 * the sequence to annotate
731 * the jalview sequence feature generated from the DAS feature
733 * the sequence feature attributes
735 * the source that emitted the feature
736 * @return true if feature was consumed as another kind of annotation.
738 protected boolean parseSeqFeature(SequenceI seq, SequenceFeature f,
739 FEATURE feature, jalviewSourceI source)
741 SequenceI mseq = seq;
742 while (seq.getDatasetSequence() != null)
744 seq = seq.getDatasetSequence();
746 if (f.getType() != null)
748 String type = f.getType();
749 if (type.equalsIgnoreCase("protein_name"))
751 // parse name onto the alignment sequence or the dataset sequence.
752 if (seq.getDescription() == null
753 || seq.getDescription().trim().length() == 0)
755 // could look at the note series to pick out the first long name, for
756 // the moment just use the whole description string
757 seq.setDescription(f.getDescription());
759 if (mseq.getDescription() == null
760 || mseq.getDescription().trim().length() == 0)
762 // could look at the note series to pick out the first long name, for
763 // the moment just use the whole description string
764 mseq.setDescription(f.getDescription());
768 // check if source has biosapiens or other sequence ontology label
769 if (type.equalsIgnoreCase("DBXREF") || type.equalsIgnoreCase("DBREF"))
771 // try to parse the accession out
773 DBRefEntry dbr = new DBRefEntry();
774 dbr.setVersion(source.getTitle());
775 StringTokenizer st = new StringTokenizer(f.getDescription(), ":");
776 if (st.hasMoreTokens())
778 dbr.setSource(st.nextToken());
780 if (st.hasMoreTokens())
782 dbr.setAccessionId(st.nextToken());
786 if (f.links != null && f.links.size() > 0)
788 // feature is also appended to enable links to be seen.
789 // TODO: consider extending dbrefs to have their own links ?
790 // TODO: new feature: extract dbref links from DAS servers and add the
791 // URL pattern to the list of DB name associated links in the user's
793 // for the moment - just fix up the existing feature so it displays
795 // f.setType(dbr.getSource());
796 // f.setDescription();
797 f.setValue("linkonly", Boolean.TRUE);
798 // f.setDescription("");
799 Vector newlinks = new Vector();
800 Enumeration it = f.links.elements();
801 while (it.hasMoreElements())
804 UrlLink urllink = new UrlLink(elm = (String) it.nextElement());
805 if (urllink.isValid())
807 urllink.setLabel(f.getDescription());
808 newlinks.addElement(urllink.toString());
812 // couldn't parse the link properly. Keep it anyway - just in
814 debug("couldn't parse link string - " + elm);
815 newlinks.addElement(elm);
819 seq.addSequenceFeature(f);
828 * creates a jalview sequence feature from a das feature document
831 * @return sequence feature object created using dasfeature information
833 SequenceFeature newSequenceFeature(FEATURE feat, String nickname)
842 * Different qNames for a DAS Feature - are string keys to the HashMaps in
843 * features "METHOD") || qName.equals("TYPE") || qName.equals("START") ||
844 * qName.equals("END") || qName.equals("NOTE") || qName.equals("LINK") ||
845 * qName.equals("SCORE")
847 String desc = new String();
848 if (feat.getNOTE() != null)
850 for (String note : feat.getNOTE())
856 int start = 0, end = 0;
861 start = Integer.parseInt(feat.getSTART().toString());
862 } catch (Exception ex)
867 end = Integer.parseInt(feat.getEND().toString());
868 } catch (Exception ex)
873 Object scr = feat.getSCORE();
876 score = (float) Double.parseDouble(scr.toString());
879 } catch (Exception ex)
883 SequenceFeature f = new SequenceFeature(getTypeString(feat.getTYPE()),
884 desc, start, end, score, nickname);
886 if (feat.getLINK() != null)
888 for (LINK link : feat.getLINK())
890 // Do not put feature extent in link text for non-positional features
891 if (f.begin == 0 && f.end == 0)
893 f.addLink(f.getType() + " " + link.getContent() + "|"
898 f.addLink(f.getType() + " " + f.begin + "_" + f.end + " "
899 + link.getContent() + "|" + link.getHref());
905 } catch (Exception e)
907 System.out.println("ERRR " + e);
909 System.out.println("############");
910 debug("Failed to parse " + feat.toString(), e);
915 private String getTypeString(TYPE type)
917 return type.getContent();
920 public boolean isRunning()