2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
3 * Copyright (C) 2014 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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 import jalview.bin.Cache;
22 import jalview.datamodel.DBRefEntry;
23 import jalview.datamodel.SequenceFeature;
24 import jalview.datamodel.SequenceI;
25 import jalview.gui.AlignFrame;
26 import jalview.gui.Desktop;
27 import jalview.gui.FeatureSettings;
28 import jalview.util.UrlLink;
29 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
30 import jalview.ws.dbsources.das.api.jalviewSourceI;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Enumeration;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Iterator;
38 import java.util.List;
41 import java.util.StringTokenizer;
42 import java.util.Vector;
44 import javax.swing.JOptionPane;
46 import org.biodas.jdas.client.FeaturesClient;
47 import org.biodas.jdas.client.adapters.features.DasGFFAdapter;
48 import org.biodas.jdas.client.adapters.features.DasGFFAdapter.GFFAdapter;
49 import org.biodas.jdas.client.threads.FeaturesClientMultipleSources;
50 import org.biodas.jdas.schema.features.ERRORSEGMENT;
51 import org.biodas.jdas.schema.features.FEATURE;
52 import org.biodas.jdas.schema.features.LINK;
53 import org.biodas.jdas.schema.features.SEGMENT;
54 import org.biodas.jdas.schema.features.TYPE;
55 import org.biodas.jdas.schema.features.UNKNOWNFEATURE;
56 import org.biodas.jdas.schema.features.UNKNOWNSEGMENT;
57 import org.biodas.jdas.schema.sources.COORDINATES;
65 public class DasSequenceFeatureFetcher
67 SequenceI[] sequences;
71 FeatureSettings fsettings;
73 StringBuffer sbuffer = new StringBuffer();
75 List<jalviewSourceI> selectedSources;
77 boolean cancelled = false;
79 private void debug(String mesg)
84 private void debug(String mesg, Exception e)
86 if (Cache.log != null)
88 Cache.log.debug(mesg, e);
92 System.err.println(mesg);
102 private DasSourceRegistryI sourceRegistry;
104 private boolean useJDASMultiThread = true;
107 * Creates a new SequenceFeatureFetcher object. Uses default
114 public DasSequenceFeatureFetcher(SequenceI[] sequences,
115 FeatureSettings fsettings, Vector selectedSources)
117 this(sequences, fsettings, selectedSources, true, true, true);
120 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
121 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
122 boolean checkDbrefs, boolean promptFetchDbrefs)
124 this(oursequences, fsettings, selectedSources2, checkDbrefs,
125 promptFetchDbrefs, true);
128 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
129 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
130 boolean checkDbrefs, boolean promptFetchDbrefs,
131 boolean useJDasMultiThread)
133 this.useJDASMultiThread = useJDasMultiThread;
134 this.selectedSources = new ArrayList<jalviewSourceI>();
135 // filter both sequences and sources to eliminate duplicates
136 for (jalviewSourceI src : selectedSources2)
138 if (!selectedSources.contains(src))
140 selectedSources.add(src);
144 Vector sqs = new Vector();
145 for (int i = 0; i < oursequences.length; i++)
147 if (!sqs.contains(oursequences[i]))
149 sqs.addElement(oursequences[i]);
152 sequences = new SequenceI[sqs.size()];
153 for (int i = 0; i < sequences.length; i++)
155 sequences[i] = (SequenceI) sqs.elementAt(i);
157 if (fsettings != null)
159 this.fsettings = fsettings;
160 this.af = fsettings.af;
161 af.setShowSeqFeatures(true);
163 int uniprotCount = 0;
164 for (jalviewSourceI source : selectedSources)
166 for (COORDINATES coords : source.getVersion().getCOORDINATES())
168 // TODO: match UniProt coord system canonically (?) - does
169 // UniProt==uniprot==UNIPROT ?
170 if (coords.getAuthority().toLowerCase().equals("uniprot"))
179 for (int i = 0; i < sequences.length; i++)
181 DBRefEntry[] dbref = sequences[i].getDBRef();
184 for (int j = 0; j < dbref.length; j++)
186 if (dbref[j].getSource().equals(
187 jalview.datamodel.DBRefSource.UNIPROT))
196 if (checkDbrefs && refCount < sequences.length && uniprotCount > 0)
199 int reply = JOptionPane.YES_OPTION;
200 if (promptFetchDbrefs)
203 .showInternalConfirmDialog(
205 "Do you want Jalview to find\n"
206 + "Uniprot Accession ids for given sequence names?",
207 "Find Uniprot Accession Ids",
208 JOptionPane.YES_NO_OPTION,
209 JOptionPane.QUESTION_MESSAGE);
212 if (reply == JOptionPane.YES_OPTION)
214 Thread thread = new Thread(new FetchDBRefs());
229 private void _startFetching()
232 new Thread(new FetchSeqFeatures()).start();
235 class FetchSeqFeatures implements Runnable
240 setGuiFetchComplete();
244 class FetchDBRefs implements Runnable
249 new DBRefFetcher(sequences, af).fetchDBRefs(true);
251 setGuiFetchComplete();
256 * Spawns Fetcher threads to add features to sequences in the dataset
262 startTime = System.currentTimeMillis();
265 af.setProgressBar("Fetching DAS Sequence Features", startTime);
267 if (sourceRegistry == null)
269 sourceRegistry = Cache.getDasSourceRegistry();
271 if (selectedSources == null || selectedSources.size() == 0)
275 jalviewSourceI[] sources = sourceRegistry.getSources().toArray(
276 new jalviewSourceI[0]);
277 String active = jalview.bin.Cache.getDefault("DAS_ACTIVE_SOURCE",
279 StringTokenizer st = new StringTokenizer(active, "\t");
280 selectedSources = new Vector();
282 while (st.hasMoreTokens())
284 token = st.nextToken();
285 for (int i = 0; i < sources.length; i++)
287 if (sources[i].getTitle().equals(token))
289 selectedSources.add(sources[i]);
294 } catch (Exception ex)
296 debug("Exception whilst setting default feature sources from registry and local preferences.",
301 if (selectedSources == null || selectedSources.size() == 0)
303 System.out.println("No DAS Sources active");
305 setGuiNoDassourceActive();
309 sourcesRemaining = selectedSources.size();
310 FeaturesClientMultipleSources fc = new FeaturesClientMultipleSources();
311 fc.setConnProps(sourceRegistry.getSessionHandler());
312 // Now sending requests one at a time to each server
313 ArrayList<jalviewSourceI> srcobj = new ArrayList<jalviewSourceI>();
314 ArrayList<String> src = new ArrayList<String>();
315 List<List<String>> ids = new ArrayList<List<String>>();
316 List<List<DBRefEntry>> idobj = new ArrayList<List<DBRefEntry>>();
317 List<Map<String, SequenceI>> sqset = new ArrayList<Map<String, SequenceI>>();
318 for (jalviewSourceI _sr : selectedSources)
321 Map<String, SequenceI> slist = new HashMap<String, SequenceI>();
322 List<DBRefEntry> idob = new ArrayList<DBRefEntry>();
323 List<String> qset = new ArrayList<String>();
325 for (SequenceI seq : sequences)
327 Object[] idset = nextSequence(_sr, seq);
330 List<DBRefEntry> _idob = (List<DBRefEntry>) idset[0];
331 List<String> _qset = (List<String>) idset[1];
332 if (_idob.size() > 0)
334 // add sequence's ref for each id derived from it
335 // (space inefficient, but most unambiguous)
336 // could replace with hash with _qset values as keys.
337 Iterator<DBRefEntry> dbobj = _idob.iterator();
338 for (String q : _qset)
340 SequenceI osq = slist.get(q);
341 DBRefEntry dr = dbobj.next();
342 if (osq != null && osq != seq)
344 // skip - non-canonical query
359 src.add(_sr.getSourceURL());
365 Map<String, Map<List<String>, Exception>> errors = new HashMap<String, Map<List<String>, Exception>>();
366 Map<String, Map<List<String>, DasGFFAdapter>> results = new HashMap<String, Map<List<String>, DasGFFAdapter>>();
367 if (!useJDASMultiThread)
369 Iterator<String> sources = src.iterator();
370 // iterate over each query for each source and do each one individually
371 for (List<String> idl : ids)
373 String source = sources.next();
374 FeaturesClient featuresc = new FeaturesClient(sourceRegistry
375 .getSessionHandler().getConnectionPropertyProviderFor(
377 for (String id : idl)
379 List<String> qid = Arrays.asList(new String[]
383 DasGFFAdapter dga = featuresc.fetchData(source, qid);
384 Map<List<String>, DasGFFAdapter> ers = results.get(source);
388 ers = new HashMap<List<String>, DasGFFAdapter>());
391 } catch (Exception ex)
393 Map<List<String>, Exception> ers = errors.get(source);
397 ers = new HashMap<List<String>, Exception>());
406 // pass them all at once
407 fc.fetchData(src, ids, false, results, errors);
409 while (!fc.isTerminated())
414 } catch (InterruptedException x)
420 Iterator<List<String>> idset = ids.iterator();
421 Iterator<List<DBRefEntry>> idobjset = idobj.iterator();
422 Iterator<Map<String, SequenceI>> seqset = sqset.iterator();
423 for (jalviewSourceI source : srcobj)
425 processResponse(seqset.next(), source, idset.next(), idobjset.next(),
426 results.get(source.getSourceURL()),
427 errors.get(source.getSourceURL()));
431 private void processResponse(Map<String, SequenceI> sequencemap,
432 jalviewSourceI jvsource, List<String> ids,
433 List<DBRefEntry> idobj, Map<List<String>, DasGFFAdapter> results,
434 Map<List<String>, Exception> errors)
436 Set<SequenceI> sequences = new HashSet<SequenceI>();
437 String source = jvsource.getSourceURL();
439 DasGFFAdapter result = (results == null) ? null : results.get(ids);
440 Exception error = (errors == null) ? null : errors.get(ids);
443 debug("das source " + source + " could not be contacted. "
444 + (error == null ? "" : error.toString()));
449 GFFAdapter gff = result.getGFF();
450 List<SEGMENT> segments = gff.getSegments();
451 List<ERRORSEGMENT> errorsegs = gff.getErrorSegments();
452 List<UNKNOWNFEATURE> unkfeats = gff.getUnknownFeatures();
453 List<UNKNOWNSEGMENT> unksegs = gff.getUnknownSegments();
454 debug("das source " + source + " returned " + gff.getTotal()
455 + " responses. " + (errorsegs != null ? errorsegs.size() : 0)
456 + " were incorrect segment queries, "
457 + (unkfeats != null ? unkfeats.size() : 0)
458 + " were unknown features "
459 + (unksegs != null ? unksegs.size() : 0)
460 + " were unknown segments and "
461 + (segments != null ? segments.size() : 0)
462 + " were segment responses.");
463 Iterator<DBRefEntry> dbr = idobj.iterator();
464 if (segments != null)
466 for (SEGMENT seg : segments)
468 String id = seg.getId();
469 if (ids.indexOf(id) == -1)
471 id = id.toUpperCase();
473 DBRefEntry dbref = idobj.get(ids.indexOf(id));
474 SequenceI sequence = sequencemap.get(id);
475 boolean added = false;
476 sequences.add(sequence);
478 for (FEATURE feat : seg.getFEATURE())
480 // standard DAS feature-> jalview sequence feature transformation
481 SequenceFeature f = newSequenceFeature(feat,
482 jvsource.getTitle());
483 if (!parseSeqFeature(sequence, f, feat, jvsource))
485 if (dbref.getMap() != null && f.getBegin() > 0
488 debug("mapping from " + f.getBegin() + " - " + f.getEnd());
489 SequenceFeature vf[] = null;
493 vf = dbref.getMap().locateFeature(f);
494 } catch (Exception ex)
497 .info("Error in 'experimental' mapping of features. Please try to reproduce and then report info to jalview-discuss@jalview.org.");
498 Cache.log.info("Mapping feature from " + f.getBegin()
499 + " to " + f.getEnd() + " in dbref "
500 + dbref.getAccessionId() + " in "
501 + dbref.getSource());
502 Cache.log.info("using das Source " + source);
503 Cache.log.info("Exception", ex);
508 for (int v = 0; v < vf.length; v++)
510 debug("mapping to " + v + ": " + vf[v].getBegin()
511 + " - " + vf[v].getEnd());
512 sequence.addSequenceFeature(vf[v]);
518 sequence.addSequenceFeature(f);
523 featuresAdded(sequences);
527 // System.out.println("No features found for " + seq.getName()
528 // + " from: " + e.getDasSource().getNickname());
533 private void setGuiNoDassourceActive()
538 af.setProgressBar("No DAS Sources Active", startTime);
540 if (getFeatSettings() != null)
542 fsettings.noDasSourceActive();
547 * Update our fsettings dialog reference if we didn't have one when we were
552 private FeatureSettings getFeatSettings()
554 if (fsettings == null)
558 fsettings = af.featureSettings;
568 af.setProgressBar("DAS Feature Fetching Cancelled", startTime);
573 int sourcesRemaining = 0;
575 private boolean running = false;
577 private void setGuiFetchComplete()
580 if (!cancelled && af != null)
582 // only update the progress bar if we've completed the fetch normally
583 af.setProgressBar("DAS Feature Fetching Complete", startTime);
586 if (af != null && af.featureSettings != null)
588 af.featureSettings.setTableData();
591 if (getFeatSettings() != null)
593 fsettings.complete();
597 void featuresAdded(Set<SequenceI> seqs)
601 // no gui to update with features.
604 af.getFeatureRenderer().featuresAdded();
606 int start = af.getViewport().getStartSeq();
607 int end = af.getViewport().getEndSeq();
609 for (index = start; index < end; index++)
611 for (SequenceI seq : seqs)
613 if (seq == af.getViewport().getAlignment().getSequenceAt(index)
614 .getDatasetSequence())
616 af.alignPanel.paintAlignment(true);
624 Object[] nextSequence(jalviewSourceI dasSource, SequenceI seq)
628 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
629 seq.getDBRef(), new String[]
631 // jalview.datamodel.DBRefSource.PDB,
632 jalview.datamodel.DBRefSource.UNIPROT,
633 // jalview.datamodel.DBRefSource.EMBL - not tested on any EMBL coord
636 // TODO: minimal list of DAS queries to make by querying with untyped ID if
637 // distinct from any typed IDs
639 List<DBRefEntry> ids = new ArrayList<DBRefEntry>();
640 List<String> qstring = new ArrayList<String>();
641 boolean dasCoordSysFound = false;
645 // do any of these ids match the source's coordinate system ?
646 for (int j = 0; !dasCoordSysFound && j < uprefs.length; j++)
649 for (COORDINATES csys : dasSource.getVersion().getCOORDINATES())
651 if (jalview.util.DBRefUtils.isDasCoordinateSystem(
652 csys.getAuthority(), uprefs[j]))
654 debug("Launched fetcher for coordinate system "
655 + csys.getAuthority());
656 // Will have to pass any mapping information to the fetcher
657 // - the start/end for the DBRefEntry may not be the same as the
658 // sequence's start/end
660 System.out.println(seq.getName() + " "
661 + (seq.getDatasetSequence() == null) + " "
664 dasCoordSysFound = true; // break's out of the loop
666 qstring.add(uprefs[j].getAccessionId());
669 System.out.println("IGNORE " + csys.getAuthority());
674 if (!dasCoordSysFound)
677 // try and use the name as the sequence id
678 if (seq.getName().indexOf("|") > -1)
680 id = seq.getName().substring(seq.getName().lastIndexOf("|") + 1);
681 if (id.trim().length() < 4)
683 // hack - we regard a significant ID as being at least 4
684 // non-whitespace characters
685 id = seq.getName().substring(0, seq.getName().lastIndexOf("|"));
686 if (id.indexOf("|") > -1)
688 id = id.substring(id.lastIndexOf("|") + 1);
698 DBRefEntry dbre = new DBRefEntry();
699 dbre.setAccessionId(id);
700 // Should try to call a general feature fetcher that
701 // queries many sources with name to discover applicable ID references
703 qstring.add(dbre.getAccessionId());
712 * examine the given sequence feature to determine if it should actually be
713 * turned into sequence annotation or database cross references rather than a
714 * simple sequence feature.
717 * the sequence to annotate
719 * the jalview sequence feature generated from the DAS feature
721 * the sequence feature attributes
723 * the source that emitted the feature
724 * @return true if feature was consumed as another kind of annotation.
726 protected boolean parseSeqFeature(SequenceI seq, SequenceFeature f,
727 FEATURE feature, jalviewSourceI source)
729 SequenceI mseq = seq;
730 while (seq.getDatasetSequence() != null)
732 seq = seq.getDatasetSequence();
734 if (f.getType() != null)
736 String type = f.getType();
737 if (type.equalsIgnoreCase("protein_name"))
739 // parse name onto the alignment sequence or the dataset sequence.
740 if (seq.getDescription() == null
741 || seq.getDescription().trim().length() == 0)
743 // could look at the note series to pick out the first long name, for
744 // the moment just use the whole description string
745 seq.setDescription(f.getDescription());
747 if (mseq.getDescription() == null
748 || mseq.getDescription().trim().length() == 0)
750 // could look at the note series to pick out the first long name, for
751 // the moment just use the whole description string
752 mseq.setDescription(f.getDescription());
756 // check if source has biosapiens or other sequence ontology label
757 if (type.equalsIgnoreCase("DBXREF") || type.equalsIgnoreCase("DBREF"))
759 // try to parse the accession out
761 DBRefEntry dbr = new DBRefEntry();
762 dbr.setVersion(source.getTitle());
763 StringTokenizer st = new StringTokenizer(f.getDescription(), ":");
764 if (st.hasMoreTokens())
766 dbr.setSource(st.nextToken());
768 if (st.hasMoreTokens())
770 dbr.setAccessionId(st.nextToken());
774 if (f.links != null && f.links.size() > 0)
776 // feature is also appended to enable links to be seen.
777 // TODO: consider extending dbrefs to have their own links ?
778 // TODO: new feature: extract dbref links from DAS servers and add the
779 // URL pattern to the list of DB name associated links in the user's
781 // for the moment - just fix up the existing feature so it displays
783 // f.setType(dbr.getSource());
784 // f.setDescription();
785 f.setValue("linkonly", Boolean.TRUE);
786 // f.setDescription("");
787 Vector newlinks = new Vector();
788 Enumeration it = f.links.elements();
789 while (it.hasMoreElements())
792 UrlLink urllink = new UrlLink(elm = (String) it.nextElement());
793 if (urllink.isValid())
795 urllink.setLabel(f.getDescription());
796 newlinks.addElement(urllink.toString());
800 // couldn't parse the link properly. Keep it anyway - just in
802 debug("couldn't parse link string - " + elm);
803 newlinks.addElement(elm);
807 seq.addSequenceFeature(f);
816 * creates a jalview sequence feature from a das feature document
819 * @return sequence feature object created using dasfeature information
821 SequenceFeature newSequenceFeature(FEATURE feat, String nickname)
830 * Different qNames for a DAS Feature - are string keys to the HashMaps in
831 * features "METHOD") || qName.equals("TYPE") || qName.equals("START") ||
832 * qName.equals("END") || qName.equals("NOTE") || qName.equals("LINK") ||
833 * qName.equals("SCORE")
835 String desc = new String();
836 if (feat.getNOTE() != null)
838 for (String note : feat.getNOTE())
840 desc += (String) note;
844 int start = 0, end = 0;
849 start = Integer.parseInt(feat.getSTART().toString());
850 } catch (Exception ex)
855 end = Integer.parseInt(feat.getEND().toString());
856 } catch (Exception ex)
861 Object scr = feat.getSCORE();
864 score = (float) Double.parseDouble(scr.toString());
867 } catch (Exception ex)
871 SequenceFeature f = new SequenceFeature(
872 getTypeString(feat.getTYPE()), desc, start, end, score,
875 if (feat.getLINK() != null)
877 for (LINK link : feat.getLINK())
879 // Do not put feature extent in link text for non-positional features
880 if (f.begin == 0 && f.end == 0)
882 f.addLink(f.getType() + " " + link.getContent() + "|"
887 f.addLink(f.getType() + " " + f.begin + "_" + f.end + " "
888 + link.getContent() + "|" + link.getHref());
894 } catch (Exception e)
896 System.out.println("ERRR " + e);
898 System.out.println("############");
899 debug("Failed to parse " + feat.toString(), e);
904 private String getTypeString(TYPE type)
906 return type.getContent();
909 public boolean isRunning()