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].getDBRef();
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(
209 MessageManager.getString("info.you_want_jalview_to_find_uniprot_accessions"),
210 MessageManager.getString("label.find_uniprot_accession_ids"),
211 JOptionPane.YES_NO_OPTION,
212 JOptionPane.QUESTION_MESSAGE);
215 if (reply == JOptionPane.YES_OPTION)
217 Thread thread = new Thread(new FetchDBRefs());
232 private void _startFetching()
235 new Thread(new FetchSeqFeatures()).start();
238 class FetchSeqFeatures implements Runnable
243 setGuiFetchComplete();
247 class FetchDBRefs implements Runnable
252 new DBRefFetcher(sequences, af).fetchDBRefs(true);
254 setGuiFetchComplete();
259 * Spawns Fetcher threads to add features to sequences in the dataset
265 startTime = System.currentTimeMillis();
268 af.setProgressBar(MessageManager.getString("status.fetching_das_sequence_features"), startTime);
270 if (sourceRegistry == null)
272 sourceRegistry = Cache.getDasSourceRegistry();
274 if (selectedSources == null || selectedSources.size() == 0)
278 jalviewSourceI[] sources = sourceRegistry.getSources().toArray(
279 new jalviewSourceI[0]);
280 String active = Cache.getDefault("DAS_ACTIVE_SOURCE",
282 StringTokenizer st = new StringTokenizer(active, "\t");
283 selectedSources = new Vector();
285 while (st.hasMoreTokens())
287 token = st.nextToken();
288 for (int i = 0; i < sources.length; i++)
290 if (sources[i].getTitle().equals(token))
292 selectedSources.add(sources[i]);
297 } catch (Exception ex)
299 debug("Exception whilst setting default feature sources from registry and local preferences.",
304 if (selectedSources == null || selectedSources.size() == 0)
306 System.out.println("No DAS Sources active");
308 setGuiNoDassourceActive();
312 sourcesRemaining = selectedSources.size();
313 FeaturesClientMultipleSources fc = new FeaturesClientMultipleSources();
314 fc.setConnProps(sourceRegistry.getSessionHandler());
315 // Now sending requests one at a time to each server
316 ArrayList<jalviewSourceI> srcobj = new ArrayList<jalviewSourceI>();
317 ArrayList<String> src = new ArrayList<String>();
318 List<List<String>> ids = new ArrayList<List<String>>();
319 List<List<DBRefEntry>> idobj = new ArrayList<List<DBRefEntry>>();
320 List<Map<String, SequenceI>> sqset = new ArrayList<Map<String, SequenceI>>();
321 for (jalviewSourceI _sr : selectedSources)
324 Map<String, SequenceI> slist = new HashMap<String, SequenceI>();
325 List<DBRefEntry> idob = new ArrayList<DBRefEntry>();
326 List<String> qset = new ArrayList<String>();
328 for (SequenceI seq : sequences)
330 Object[] idset = nextSequence(_sr, seq);
333 List<DBRefEntry> _idob = (List<DBRefEntry>) idset[0];
334 List<String> _qset = (List<String>) idset[1];
335 if (_idob.size() > 0)
337 // add sequence's ref for each id derived from it
338 // (space inefficient, but most unambiguous)
339 // could replace with hash with _qset values as keys.
340 Iterator<DBRefEntry> dbobj = _idob.iterator();
341 for (String q : _qset)
343 SequenceI osq = slist.get(q);
344 DBRefEntry dr = dbobj.next();
345 if (osq != null && osq != seq)
347 // skip - non-canonical query
362 src.add(_sr.getSourceURL());
368 Map<String, Map<List<String>, Exception>> errors = new HashMap<String, Map<List<String>, Exception>>();
369 Map<String, Map<List<String>, DasGFFAdapter>> results = new HashMap<String, Map<List<String>, DasGFFAdapter>>();
370 if (!useJDASMultiThread)
372 Iterator<String> sources = src.iterator();
373 // iterate over each query for each source and do each one individually
374 for (List<String> idl : ids)
376 String source = sources.next();
377 FeaturesClient featuresc = new FeaturesClient(sourceRegistry
378 .getSessionHandler().getConnectionPropertyProviderFor(
380 for (String id : idl)
382 List<String> qid = Arrays.asList(new String[]
386 DasGFFAdapter dga = featuresc.fetchData(source, qid);
387 Map<List<String>, DasGFFAdapter> ers = results.get(source);
391 ers = new HashMap<List<String>, DasGFFAdapter>());
394 } catch (Exception ex)
396 Map<List<String>, Exception> ers = errors.get(source);
400 ers = new HashMap<List<String>, Exception>());
409 // pass them all at once
410 fc.fetchData(src, ids, false, results, errors);
412 while (!fc.isTerminated())
417 } catch (InterruptedException x)
423 Iterator<List<String>> idset = ids.iterator();
424 Iterator<List<DBRefEntry>> idobjset = idobj.iterator();
425 Iterator<Map<String, SequenceI>> seqset = sqset.iterator();
426 for (jalviewSourceI source : srcobj)
428 processResponse(seqset.next(), source, idset.next(), idobjset.next(),
429 results.get(source.getSourceURL()),
430 errors.get(source.getSourceURL()));
434 private void processResponse(Map<String, SequenceI> sequencemap,
435 jalviewSourceI jvsource, List<String> ids,
436 List<DBRefEntry> idobj, Map<List<String>, DasGFFAdapter> results,
437 Map<List<String>, Exception> errors)
439 Set<SequenceI> sequences = new HashSet<SequenceI>();
440 String source = jvsource.getSourceURL();
442 DasGFFAdapter result = (results == null) ? null : results.get(ids);
443 Exception error = (errors == null) ? null : errors.get(ids);
446 debug("das source " + source + " could not be contacted. "
447 + (error == null ? "" : error.toString()));
452 GFFAdapter gff = result.getGFF();
453 List<SEGMENT> segments = gff.getSegments();
454 List<ERRORSEGMENT> errorsegs = gff.getErrorSegments();
455 List<UNKNOWNFEATURE> unkfeats = gff.getUnknownFeatures();
456 List<UNKNOWNSEGMENT> unksegs = gff.getUnknownSegments();
457 debug("das source " + source + " returned " + gff.getTotal()
458 + " responses. " + (errorsegs != null ? errorsegs.size() : 0)
459 + " were incorrect segment queries, "
460 + (unkfeats != null ? unkfeats.size() : 0)
461 + " were unknown features "
462 + (unksegs != null ? unksegs.size() : 0)
463 + " were unknown segments and "
464 + (segments != null ? segments.size() : 0)
465 + " were segment responses.");
466 Iterator<DBRefEntry> dbr = idobj.iterator();
467 if (segments != null)
469 for (SEGMENT seg : segments)
471 String id = seg.getId();
472 if (ids.indexOf(id) == -1)
474 id = id.toUpperCase();
476 DBRefEntry dbref = idobj.get(ids.indexOf(id));
477 SequenceI sequence = sequencemap.get(id);
478 boolean added = false;
479 sequences.add(sequence);
481 for (FEATURE feat : seg.getFEATURE())
483 // standard DAS feature-> jalview sequence feature transformation
484 SequenceFeature f = newSequenceFeature(feat,
485 jvsource.getTitle());
486 if (!parseSeqFeature(sequence, f, feat, jvsource))
488 if (dbref.getMap() != null && f.getBegin() > 0
491 debug("mapping from " + f.getBegin() + " - " + f.getEnd());
492 SequenceFeature vf[] = null;
496 vf = dbref.getMap().locateFeature(f);
497 } catch (Exception ex)
500 .warn("Error in 'experimental' mapping of features. Please try to reproduce and then report info to jalview-discuss@jalview.org.");
501 Cache.log.warn("Mapping feature from " + f.getBegin()
502 + " to " + f.getEnd() + " in dbref "
503 + dbref.getAccessionId() + " in "
504 + dbref.getSource());
505 Cache.log.warn("using das Source " + source);
506 Cache.log.warn("Exception", ex);
511 for (int v = 0; v < vf.length; v++)
513 debug("mapping to " + v + ": " + vf[v].getBegin()
514 + " - " + vf[v].getEnd());
515 sequence.addSequenceFeature(vf[v]);
521 sequence.addSequenceFeature(f);
526 featuresAdded(sequences);
530 // System.out.println("No features found for " + seq.getName()
531 // + " from: " + e.getDasSource().getNickname());
536 private void setGuiNoDassourceActive()
541 af.setProgressBar(MessageManager.getString("status.no_das_sources_active"), startTime);
543 if (getFeatSettings() != null)
545 fsettings.noDasSourceActive();
550 * Update our fsettings dialog reference if we didn't have one when we were
555 private FeatureSettings getFeatSettings()
557 if (fsettings == null)
561 fsettings = af.featureSettings;
571 af.setProgressBar(MessageManager.getString("status.das_feature_fetching_cancelled"), startTime);
576 int sourcesRemaining = 0;
578 private boolean running = false;
580 private void setGuiFetchComplete()
583 if (!cancelled && af != null)
585 // only update the progress bar if we've completed the fetch normally
586 af.setProgressBar(MessageManager.getString("status.das_feature_fetching_complete"), startTime);
589 if (af != null && af.featureSettings != null)
591 af.featureSettings.discoverAllFeatureData();
594 if (getFeatSettings() != null)
596 fsettings.complete();
600 void featuresAdded(Set<SequenceI> seqs)
604 // no gui to update with features.
607 af.getFeatureRenderer().featuresAdded();
609 int start = af.getViewport().getStartSeq();
610 int end = af.getViewport().getEndSeq();
612 for (index = start; index < end; index++)
614 for (SequenceI seq : seqs)
616 if (seq == af.getViewport().getAlignment().getSequenceAt(index)
617 .getDatasetSequence())
619 af.alignPanel.paintAlignment(true);
627 Object[] nextSequence(jalviewSourceI dasSource, SequenceI seq)
633 DBRefEntry[] uprefs = DBRefUtils.selectRefs(
634 seq.getDBRef(), new String[]
636 // jalview.datamodel.DBRefSource.PDB,
638 // jalview.datamodel.DBRefSource.EMBL - not tested on any EMBL coord
641 // TODO: minimal list of DAS queries to make by querying with untyped ID if
642 // distinct from any typed IDs
644 List<DBRefEntry> ids = new ArrayList<DBRefEntry>();
645 List<String> qstring = new ArrayList<String>();
646 boolean dasCoordSysFound = false;
650 // do any of these ids match the source's coordinate system ?
651 for (int j = 0; !dasCoordSysFound && j < uprefs.length; j++)
654 for (COORDINATES csys : dasSource.getVersion().getCOORDINATES())
656 if (DBRefUtils.isDasCoordinateSystem(
657 csys.getAuthority(), uprefs[j]))
659 debug("Launched fetcher for coordinate system "
660 + csys.getAuthority());
661 // Will have to pass any mapping information to the fetcher
662 // - the start/end for the DBRefEntry may not be the same as the
663 // sequence's start/end
665 System.out.println(seq.getName() + " "
666 + (seq.getDatasetSequence() == null) + " "
669 dasCoordSysFound = true; // break's out of the loop
671 qstring.add(uprefs[j].getAccessionId());
675 System.out.println("IGNORE " + csys.getAuthority());
681 if (!dasCoordSysFound)
684 // try and use the name as the sequence id
685 if (seq.getName().indexOf("|") > -1)
687 id = seq.getName().substring(seq.getName().lastIndexOf("|") + 1);
688 if (id.trim().length() < 4)
690 // hack - we regard a significant ID as being at least 4
691 // non-whitespace characters
692 id = seq.getName().substring(0, seq.getName().lastIndexOf("|"));
693 if (id.indexOf("|") > -1)
695 id = id.substring(id.lastIndexOf("|") + 1);
705 DBRefEntry dbre = new DBRefEntry();
706 dbre.setAccessionId(id);
707 // Should try to call a general feature fetcher that
708 // queries many sources with name to discover applicable ID references
710 qstring.add(dbre.getAccessionId());
719 * examine the given sequence feature to determine if it should actually be
720 * turned into sequence annotation or database cross references rather than a
721 * simple sequence feature.
724 * the sequence to annotate
726 * the jalview sequence feature generated from the DAS feature
728 * the sequence feature attributes
730 * the source that emitted the feature
731 * @return true if feature was consumed as another kind of annotation.
733 protected boolean parseSeqFeature(SequenceI seq, SequenceFeature f,
734 FEATURE feature, jalviewSourceI source)
736 SequenceI mseq = seq;
737 while (seq.getDatasetSequence() != null)
739 seq = seq.getDatasetSequence();
741 if (f.getType() != null)
743 String type = f.getType();
744 if (type.equalsIgnoreCase("protein_name"))
746 // parse name onto the alignment sequence or the dataset sequence.
747 if (seq.getDescription() == null
748 || seq.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 seq.setDescription(f.getDescription());
754 if (mseq.getDescription() == null
755 || mseq.getDescription().trim().length() == 0)
757 // could look at the note series to pick out the first long name, for
758 // the moment just use the whole description string
759 mseq.setDescription(f.getDescription());
763 // check if source has biosapiens or other sequence ontology label
764 if (type.equalsIgnoreCase("DBXREF") || type.equalsIgnoreCase("DBREF"))
766 // try to parse the accession out
768 DBRefEntry dbr = new DBRefEntry();
769 dbr.setVersion(source.getTitle());
770 StringTokenizer st = new StringTokenizer(f.getDescription(), ":");
771 if (st.hasMoreTokens())
773 dbr.setSource(st.nextToken());
775 if (st.hasMoreTokens())
777 dbr.setAccessionId(st.nextToken());
781 if (f.links != null && f.links.size() > 0)
783 // feature is also appended to enable links to be seen.
784 // TODO: consider extending dbrefs to have their own links ?
785 // TODO: new feature: extract dbref links from DAS servers and add the
786 // URL pattern to the list of DB name associated links in the user's
788 // for the moment - just fix up the existing feature so it displays
790 // f.setType(dbr.getSource());
791 // f.setDescription();
792 f.setValue("linkonly", Boolean.TRUE);
793 // f.setDescription("");
794 Vector newlinks = new Vector();
795 Enumeration it = f.links.elements();
796 while (it.hasMoreElements())
799 UrlLink urllink = new UrlLink(elm = (String) it.nextElement());
800 if (urllink.isValid())
802 urllink.setLabel(f.getDescription());
803 newlinks.addElement(urllink.toString());
807 // couldn't parse the link properly. Keep it anyway - just in
809 debug("couldn't parse link string - " + elm);
810 newlinks.addElement(elm);
814 seq.addSequenceFeature(f);
823 * creates a jalview sequence feature from a das feature document
826 * @return sequence feature object created using dasfeature information
828 SequenceFeature newSequenceFeature(FEATURE feat, String nickname)
837 * Different qNames for a DAS Feature - are string keys to the HashMaps in
838 * features "METHOD") || qName.equals("TYPE") || qName.equals("START") ||
839 * qName.equals("END") || qName.equals("NOTE") || qName.equals("LINK") ||
840 * qName.equals("SCORE")
842 String desc = new String();
843 if (feat.getNOTE() != null)
845 for (String note : feat.getNOTE())
851 int start = 0, end = 0;
856 start = Integer.parseInt(feat.getSTART().toString());
857 } catch (Exception ex)
862 end = Integer.parseInt(feat.getEND().toString());
863 } catch (Exception ex)
868 Object scr = feat.getSCORE();
871 score = (float) Double.parseDouble(scr.toString());
874 } catch (Exception ex)
878 SequenceFeature f = new SequenceFeature(
879 getTypeString(feat.getTYPE()), desc, start, end, score,
882 if (feat.getLINK() != null)
884 for (LINK link : feat.getLINK())
886 // Do not put feature extent in link text for non-positional features
887 if (f.begin == 0 && f.end == 0)
889 f.addLink(f.getType() + " " + link.getContent() + "|"
894 f.addLink(f.getType() + " " + f.begin + "_" + f.end + " "
895 + link.getContent() + "|" + link.getHref());
901 } catch (Exception e)
903 System.out.println("ERRR " + e);
905 System.out.println("############");
906 debug("Failed to parse " + feat.toString(), e);
911 private String getTypeString(TYPE type)
913 return type.getContent();
916 public boolean isRunning()