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.util.DBRefUtils;
32 import jalview.util.MessageManager;
33 import jalview.util.UrlLink;
34 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
35 import jalview.ws.dbsources.das.api.jalviewSourceI;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Enumeration;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
49 import javax.swing.JOptionPane;
51 import org.biodas.jdas.client.FeaturesClient;
52 import org.biodas.jdas.client.adapters.features.DasGFFAdapter;
53 import org.biodas.jdas.client.adapters.features.DasGFFAdapter.GFFAdapter;
54 import org.biodas.jdas.client.threads.FeaturesClientMultipleSources;
55 import org.biodas.jdas.schema.features.ERRORSEGMENT;
56 import org.biodas.jdas.schema.features.FEATURE;
57 import org.biodas.jdas.schema.features.LINK;
58 import org.biodas.jdas.schema.features.SEGMENT;
59 import org.biodas.jdas.schema.features.TYPE;
60 import org.biodas.jdas.schema.features.UNKNOWNFEATURE;
61 import org.biodas.jdas.schema.features.UNKNOWNSEGMENT;
62 import org.biodas.jdas.schema.sources.COORDINATES;
70 public class DasSequenceFeatureFetcher
72 SequenceI[] sequences;
76 FeatureSettings fsettings;
78 StringBuffer sbuffer = new StringBuffer();
80 List<jalviewSourceI> selectedSources;
82 boolean cancelled = false;
84 private void debug(String mesg)
89 private void debug(String mesg, Exception e)
91 if (Cache.log != null)
93 Cache.log.debug(mesg, e);
97 System.err.println(mesg);
107 private DasSourceRegistryI sourceRegistry;
109 private boolean useJDASMultiThread = true;
112 * Creates a new SequenceFeatureFetcher object. Uses default
119 public DasSequenceFeatureFetcher(SequenceI[] sequences,
120 FeatureSettings fsettings, Vector selectedSources)
122 this(sequences, fsettings, selectedSources, true, true, true);
125 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
126 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
127 boolean checkDbrefs, boolean promptFetchDbrefs)
129 this(oursequences, fsettings, selectedSources2, checkDbrefs,
130 promptFetchDbrefs, true);
133 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
134 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
135 boolean checkDbrefs, boolean promptFetchDbrefs,
136 boolean useJDasMultiThread)
138 this.useJDASMultiThread = useJDasMultiThread;
139 this.selectedSources = new ArrayList<jalviewSourceI>();
140 // filter both sequences and sources to eliminate duplicates
141 for (jalviewSourceI src : selectedSources2)
143 if (!selectedSources.contains(src))
145 selectedSources.add(src);
149 Vector sqs = new Vector();
150 for (int i = 0; i < oursequences.length; i++)
152 if (!sqs.contains(oursequences[i]))
154 sqs.addElement(oursequences[i]);
157 sequences = new SequenceI[sqs.size()];
158 for (int i = 0; i < sequences.length; i++)
160 sequences[i] = (SequenceI) sqs.elementAt(i);
162 if (fsettings != null)
164 this.fsettings = fsettings;
165 this.af = fsettings.af;
166 af.setShowSeqFeatures(true);
168 int uniprotCount = 0;
169 for (jalviewSourceI source : selectedSources)
171 for (COORDINATES coords : source.getVersion().getCOORDINATES())
173 // TODO: match UniProt coord system canonically (?) - does
174 // UniProt==uniprot==UNIPROT ?
175 if (coords.getAuthority().toLowerCase().equals("uniprot"))
184 for (int i = 0; i < sequences.length; i++)
186 DBRefEntry[] dbref = sequences[i].getDBRefs();
189 for (int j = 0; j < dbref.length; j++)
191 if (dbref[j].getSource().equals(DBRefSource.UNIPROT))
200 if (checkDbrefs && refCount < sequences.length && uniprotCount > 0)
203 int reply = JOptionPane.YES_OPTION;
204 if (promptFetchDbrefs)
207 .showInternalConfirmDialog(
210 .getString("info.you_want_jalview_to_find_uniprot_accessions"),
212 .getString("label.find_uniprot_accession_ids"),
213 JOptionPane.YES_NO_OPTION,
214 JOptionPane.QUESTION_MESSAGE);
217 if (reply == JOptionPane.YES_OPTION)
219 Thread thread = new Thread(new FetchDBRefs());
234 private void _startFetching()
237 new Thread(new FetchSeqFeatures()).start();
240 class FetchSeqFeatures implements Runnable
246 setGuiFetchComplete();
250 class FetchDBRefs implements Runnable
256 boolean isNucleotide = af.getViewport().getAlignment().isNucleotide();
257 new DBRefFetcher(sequences, af, null, af.featureSettings,
258 isNucleotide).fetchDBRefs(true);
261 setGuiFetchComplete();
266 * Spawns Fetcher threads to add features to sequences in the dataset
272 startTime = System.currentTimeMillis();
275 af.setProgressBar(MessageManager
276 .getString("status.fetching_das_sequence_features"),
279 if (sourceRegistry == null)
281 sourceRegistry = Cache.getDasSourceRegistry();
283 if (selectedSources == null || selectedSources.size() == 0)
287 jalviewSourceI[] sources = sourceRegistry.getSources().toArray(
288 new jalviewSourceI[0]);
289 String active = Cache.getDefault("DAS_ACTIVE_SOURCE", "uniprot");
290 StringTokenizer st = new StringTokenizer(active, "\t");
291 selectedSources = new Vector();
293 while (st.hasMoreTokens())
295 token = st.nextToken();
296 for (int i = 0; i < sources.length; i++)
298 if (sources[i].getTitle().equals(token))
300 selectedSources.add(sources[i]);
305 } catch (Exception ex)
307 debug("Exception whilst setting default feature sources from registry and local preferences.",
312 if (selectedSources == null || selectedSources.size() == 0)
314 System.out.println("No DAS Sources active");
316 setGuiNoDassourceActive();
320 sourcesRemaining = selectedSources.size();
321 FeaturesClientMultipleSources fc = new FeaturesClientMultipleSources();
322 fc.setConnProps(sourceRegistry.getSessionHandler());
323 // Now sending requests one at a time to each server
324 ArrayList<jalviewSourceI> srcobj = new ArrayList<jalviewSourceI>();
325 ArrayList<String> src = new ArrayList<String>();
326 List<List<String>> ids = new ArrayList<List<String>>();
327 List<List<DBRefEntry>> idobj = new ArrayList<List<DBRefEntry>>();
328 List<Map<String, SequenceI>> sqset = new ArrayList<Map<String, SequenceI>>();
329 for (jalviewSourceI _sr : selectedSources)
332 Map<String, SequenceI> slist = new HashMap<String, SequenceI>();
333 List<DBRefEntry> idob = new ArrayList<DBRefEntry>();
334 List<String> qset = new ArrayList<String>();
336 for (SequenceI seq : sequences)
338 Object[] idset = nextSequence(_sr, seq);
341 List<DBRefEntry> _idob = (List<DBRefEntry>) idset[0];
342 List<String> _qset = (List<String>) idset[1];
343 if (_idob.size() > 0)
345 // add sequence's ref for each id derived from it
346 // (space inefficient, but most unambiguous)
347 // could replace with hash with _qset values as keys.
348 Iterator<DBRefEntry> dbobj = _idob.iterator();
349 for (String q : _qset)
351 SequenceI osq = slist.get(q);
352 DBRefEntry dr = dbobj.next();
353 if (osq != null && osq != seq)
355 // skip - non-canonical query
370 src.add(_sr.getSourceURL());
376 Map<String, Map<List<String>, Exception>> errors = new HashMap<String, Map<List<String>, Exception>>();
377 Map<String, Map<List<String>, DasGFFAdapter>> results = new HashMap<String, Map<List<String>, DasGFFAdapter>>();
378 if (!useJDASMultiThread)
380 Iterator<String> sources = src.iterator();
381 // iterate over each query for each source and do each one individually
382 for (List<String> idl : ids)
384 String source = sources.next();
385 FeaturesClient featuresc = new FeaturesClient(sourceRegistry
386 .getSessionHandler().getConnectionPropertyProviderFor(
388 for (String id : idl)
390 List<String> qid = Arrays.asList(new String[] { id });
393 DasGFFAdapter dga = featuresc.fetchData(source, qid);
394 Map<List<String>, DasGFFAdapter> ers = results.get(source);
398 ers = new HashMap<List<String>, DasGFFAdapter>());
401 } catch (Exception ex)
403 Map<List<String>, Exception> ers = errors.get(source);
407 ers = new HashMap<List<String>, Exception>());
416 // pass them all at once
417 fc.fetchData(src, ids, false, results, errors);
419 while (!fc.isTerminated())
424 } catch (InterruptedException x)
430 Iterator<List<String>> idset = ids.iterator();
431 Iterator<List<DBRefEntry>> idobjset = idobj.iterator();
432 Iterator<Map<String, SequenceI>> seqset = sqset.iterator();
433 for (jalviewSourceI source : srcobj)
435 processResponse(seqset.next(), source, idset.next(), idobjset.next(),
436 results.get(source.getSourceURL()),
437 errors.get(source.getSourceURL()));
441 private void processResponse(Map<String, SequenceI> sequencemap,
442 jalviewSourceI jvsource, List<String> ids,
443 List<DBRefEntry> idobj, Map<List<String>, DasGFFAdapter> results,
444 Map<List<String>, Exception> errors)
446 Set<SequenceI> sequences = new HashSet<SequenceI>();
447 String source = jvsource.getSourceURL();
449 DasGFFAdapter result = (results == null) ? null : results.get(ids);
450 Exception error = (errors == null) ? null : errors.get(ids);
453 debug("das source " + source + " could not be contacted. "
454 + (error == null ? "" : error.toString()));
459 GFFAdapter gff = result.getGFF();
460 List<SEGMENT> segments = gff.getSegments();
461 List<ERRORSEGMENT> errorsegs = gff.getErrorSegments();
462 List<UNKNOWNFEATURE> unkfeats = gff.getUnknownFeatures();
463 List<UNKNOWNSEGMENT> unksegs = gff.getUnknownSegments();
464 debug("das source " + source + " returned " + gff.getTotal()
465 + " responses. " + (errorsegs != null ? errorsegs.size() : 0)
466 + " were incorrect segment queries, "
467 + (unkfeats != null ? unkfeats.size() : 0)
468 + " were unknown features "
469 + (unksegs != null ? unksegs.size() : 0)
470 + " were unknown segments and "
471 + (segments != null ? segments.size() : 0)
472 + " were segment responses.");
473 Iterator<DBRefEntry> dbr = idobj.iterator();
474 if (segments != null)
476 for (SEGMENT seg : segments)
478 String id = seg.getId();
479 if (ids.indexOf(id) == -1)
481 id = id.toUpperCase();
483 DBRefEntry dbref = idobj.get(ids.indexOf(id));
484 SequenceI sequence = sequencemap.get(id);
485 boolean added = false;
486 sequences.add(sequence);
488 for (FEATURE feat : seg.getFEATURE())
490 // standard DAS feature-> jalview sequence feature transformation
491 SequenceFeature f = newSequenceFeature(feat,
492 jvsource.getTitle());
493 if (!parseSeqFeature(sequence, f, feat, jvsource))
495 if (dbref.getMap() != null && f.getBegin() > 0
498 debug("mapping from " + f.getBegin() + " - " + f.getEnd());
499 SequenceFeature vf[] = null;
503 vf = dbref.getMap().locateFeature(f);
504 } catch (Exception ex)
507 .warn("Error in 'experimental' mapping of features. Please try to reproduce and then report info to jalview-discuss@jalview.org.");
508 Cache.log.warn("Mapping feature from " + f.getBegin()
509 + " to " + f.getEnd() + " in dbref "
510 + dbref.getAccessionId() + " in "
511 + dbref.getSource());
512 Cache.log.warn("using das Source " + source);
513 Cache.log.warn("Exception", ex);
518 for (int v = 0; v < vf.length; v++)
520 debug("mapping to " + v + ": " + vf[v].getBegin()
521 + " - " + vf[v].getEnd());
522 sequence.addSequenceFeature(vf[v]);
528 sequence.addSequenceFeature(f);
533 featuresAdded(sequences);
537 // System.out.println("No features found for " + seq.getName()
538 // + " from: " + e.getDasSource().getNickname());
543 private void setGuiNoDassourceActive()
549 MessageManager.getString("status.no_das_sources_active"),
552 if (getFeatSettings() != null)
554 fsettings.noDasSourceActive();
559 * Update our fsettings dialog reference if we didn't have one when we were
564 private FeatureSettings getFeatSettings()
566 if (fsettings == null)
570 fsettings = af.featureSettings;
580 af.setProgressBar(MessageManager
581 .getString("status.das_feature_fetching_cancelled"),
587 int sourcesRemaining = 0;
589 private boolean running = false;
591 private void setGuiFetchComplete()
594 if (!cancelled && af != null)
596 // only update the progress bar if we've completed the fetch normally
597 af.setProgressBar(MessageManager
598 .getString("status.das_feature_fetching_complete"), startTime);
601 if (af != null && af.featureSettings != null)
603 af.featureSettings.discoverAllFeatureData();
606 if (getFeatSettings() != null)
608 fsettings.complete();
612 void featuresAdded(Set<SequenceI> seqs)
616 // no gui to update with features.
619 af.getFeatureRenderer().featuresAdded();
621 int start = af.getViewport().getStartSeq();
622 int end = af.getViewport().getEndSeq();
624 for (index = start; index < end; index++)
626 for (SequenceI seq : seqs)
628 if (seq == af.getViewport().getAlignment().getSequenceAt(index)
629 .getDatasetSequence())
631 af.alignPanel.paintAlignment(true);
639 Object[] nextSequence(jalviewSourceI dasSource, SequenceI seq)
645 DBRefEntry[] uprefs = DBRefUtils.selectRefs(seq.getDBRefs(),
647 // jalview.datamodel.DBRefSource.PDB,
649 // jalview.datamodel.DBRefSource.EMBL - not tested on any EMBL coord
652 // TODO: minimal list of DAS queries to make by querying with untyped ID if
653 // distinct from any typed IDs
655 List<DBRefEntry> ids = new ArrayList<DBRefEntry>();
656 List<String> qstring = new ArrayList<String>();
657 boolean dasCoordSysFound = false;
661 // do any of these ids match the source's coordinate system ?
662 for (int j = 0; !dasCoordSysFound && j < uprefs.length; j++)
665 for (COORDINATES csys : dasSource.getVersion().getCOORDINATES())
667 if (DBRefUtils.isDasCoordinateSystem(csys.getAuthority(),
670 debug("Launched fetcher for coordinate system "
671 + csys.getAuthority());
672 // Will have to pass any mapping information to the fetcher
673 // - the start/end for the DBRefEntry may not be the same as the
674 // sequence's start/end
676 System.out.println(seq.getName() + " "
677 + (seq.getDatasetSequence() == null) + " "
680 dasCoordSysFound = true; // break's out of the loop
682 qstring.add(uprefs[j].getAccessionId());
686 System.out.println("IGNORE " + csys.getAuthority());
692 if (!dasCoordSysFound)
695 // try and use the name as the sequence id
696 if (seq.getName().indexOf("|") > -1)
698 id = seq.getName().substring(seq.getName().lastIndexOf("|") + 1);
699 if (id.trim().length() < 4)
701 // hack - we regard a significant ID as being at least 4
702 // non-whitespace characters
703 id = seq.getName().substring(0, seq.getName().lastIndexOf("|"));
704 if (id.indexOf("|") > -1)
706 id = id.substring(id.lastIndexOf("|") + 1);
716 DBRefEntry dbre = new DBRefEntry();
717 dbre.setAccessionId(id);
718 // Should try to call a general feature fetcher that
719 // queries many sources with name to discover applicable ID references
721 qstring.add(dbre.getAccessionId());
725 return new Object[] { ids, qstring };
729 * examine the given sequence feature to determine if it should actually be
730 * turned into sequence annotation or database cross references rather than a
731 * simple sequence feature.
734 * the sequence to annotate
736 * the jalview sequence feature generated from the DAS feature
738 * the sequence feature attributes
740 * the source that emitted the feature
741 * @return true if feature was consumed as another kind of annotation.
743 protected boolean parseSeqFeature(SequenceI seq, SequenceFeature f,
744 FEATURE feature, jalviewSourceI source)
746 SequenceI mseq = seq;
747 while (seq.getDatasetSequence() != null)
749 seq = seq.getDatasetSequence();
751 if (f.getType() != null)
753 String type = f.getType();
754 if (type.equalsIgnoreCase("protein_name"))
756 // parse name onto the alignment sequence or the dataset sequence.
757 if (seq.getDescription() == null
758 || seq.getDescription().trim().length() == 0)
760 // could look at the note series to pick out the first long name, for
761 // the moment just use the whole description string
762 seq.setDescription(f.getDescription());
764 if (mseq.getDescription() == null
765 || mseq.getDescription().trim().length() == 0)
767 // could look at the note series to pick out the first long name, for
768 // the moment just use the whole description string
769 mseq.setDescription(f.getDescription());
773 // check if source has biosapiens or other sequence ontology label
774 if (type.equalsIgnoreCase("DBXREF") || type.equalsIgnoreCase("DBREF"))
776 // try to parse the accession out
778 DBRefEntry dbr = new DBRefEntry();
779 dbr.setVersion(source.getTitle());
780 StringTokenizer st = new StringTokenizer(f.getDescription(), ":");
781 if (st.hasMoreTokens())
783 dbr.setSource(st.nextToken());
785 if (st.hasMoreTokens())
787 dbr.setAccessionId(st.nextToken());
791 if (f.links != null && f.links.size() > 0)
793 // feature is also appended to enable links to be seen.
794 // TODO: consider extending dbrefs to have their own links ?
795 // TODO: new feature: extract dbref links from DAS servers and add the
796 // URL pattern to the list of DB name associated links in the user's
798 // for the moment - just fix up the existing feature so it displays
800 // f.setType(dbr.getSource());
801 // f.setDescription();
802 f.setValue("linkonly", Boolean.TRUE);
803 // f.setDescription("");
804 Vector newlinks = new Vector();
805 Enumeration it = f.links.elements();
806 while (it.hasMoreElements())
809 UrlLink urllink = new UrlLink(elm = (String) it.nextElement());
810 if (urllink.isValid())
812 urllink.setLabel(f.getDescription());
813 newlinks.addElement(urllink.toString());
817 // couldn't parse the link properly. Keep it anyway - just in
819 debug("couldn't parse link string - " + elm);
820 newlinks.addElement(elm);
824 seq.addSequenceFeature(f);
833 * creates a jalview sequence feature from a das feature document
836 * @return sequence feature object created using dasfeature information
838 SequenceFeature newSequenceFeature(FEATURE feat, String nickname)
847 * Different qNames for a DAS Feature - are string keys to the HashMaps in
848 * features "METHOD") || qName.equals("TYPE") || qName.equals("START") ||
849 * qName.equals("END") || qName.equals("NOTE") || qName.equals("LINK") ||
850 * qName.equals("SCORE")
852 String desc = new String();
853 if (feat.getNOTE() != null)
855 for (String note : feat.getNOTE())
861 int start = 0, end = 0;
866 start = Integer.parseInt(feat.getSTART().toString());
867 } catch (Exception ex)
872 end = Integer.parseInt(feat.getEND().toString());
873 } catch (Exception ex)
878 Object scr = feat.getSCORE();
881 score = (float) Double.parseDouble(scr.toString());
884 } catch (Exception ex)
888 SequenceFeature f = new SequenceFeature(
889 getTypeString(feat.getTYPE()), desc, start, end, score,
892 if (feat.getLINK() != null)
894 for (LINK link : feat.getLINK())
896 // Do not put feature extent in link text for non-positional features
897 if (f.begin == 0 && f.end == 0)
899 f.addLink(f.getType() + " " + link.getContent() + "|"
904 f.addLink(f.getType() + " " + f.begin + "_" + f.end + " "
905 + link.getContent() + "|" + link.getHref());
911 } catch (Exception e)
913 System.out.println("ERRR " + e);
915 System.out.println("############");
916 debug("Failed to parse " + feat.toString(), e);
921 private String getTypeString(TYPE type)
923 return type.getContent();
926 public boolean isRunning()