2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
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
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.SequenceFeature;
26 import jalview.datamodel.SequenceI;
27 import jalview.gui.AlignFrame;
28 import jalview.gui.Desktop;
29 import jalview.gui.FeatureSettings;
30 import jalview.util.UrlLink;
31 import jalview.ws.dbsources.das.api.DasSourceRegistryI;
32 import jalview.ws.dbsources.das.api.jalviewSourceI;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Enumeration;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.List;
43 import java.util.StringTokenizer;
44 import java.util.Vector;
46 import javax.swing.JOptionPane;
48 import org.biodas.jdas.client.FeaturesClient;
49 import org.biodas.jdas.client.adapters.features.DasGFFAdapter;
50 import org.biodas.jdas.client.adapters.features.DasGFFAdapter.GFFAdapter;
51 import org.biodas.jdas.client.threads.FeaturesClientMultipleSources;
52 import org.biodas.jdas.schema.features.ERRORSEGMENT;
53 import org.biodas.jdas.schema.features.FEATURE;
54 import org.biodas.jdas.schema.features.LINK;
55 import org.biodas.jdas.schema.features.SEGMENT;
56 import org.biodas.jdas.schema.features.TYPE;
57 import org.biodas.jdas.schema.features.UNKNOWNFEATURE;
58 import org.biodas.jdas.schema.features.UNKNOWNSEGMENT;
59 import org.biodas.jdas.schema.sources.COORDINATES;
67 public class DasSequenceFeatureFetcher
69 SequenceI[] sequences;
73 FeatureSettings fsettings;
75 StringBuffer sbuffer = new StringBuffer();
77 List<jalviewSourceI> selectedSources;
79 boolean cancelled = false;
81 private void debug(String mesg)
86 private void debug(String mesg, Exception e)
88 if (Cache.log != null)
90 Cache.log.debug(mesg, e);
94 System.err.println(mesg);
104 private DasSourceRegistryI sourceRegistry;
106 private boolean useJDASMultiThread = true;
109 * Creates a new SequenceFeatureFetcher object. Uses default
116 public DasSequenceFeatureFetcher(SequenceI[] sequences,
117 FeatureSettings fsettings, Vector selectedSources)
119 this(sequences, fsettings, selectedSources, true, true, true);
122 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
123 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
124 boolean checkDbrefs, boolean promptFetchDbrefs)
126 this(oursequences, fsettings, selectedSources2, checkDbrefs,
127 promptFetchDbrefs, true);
130 public DasSequenceFeatureFetcher(SequenceI[] oursequences,
131 FeatureSettings fsettings, List<jalviewSourceI> selectedSources2,
132 boolean checkDbrefs, boolean promptFetchDbrefs,
133 boolean useJDasMultiThread)
135 this.useJDASMultiThread = useJDasMultiThread;
136 this.selectedSources = new ArrayList<jalviewSourceI>();
137 // filter both sequences and sources to eliminate duplicates
138 for (jalviewSourceI src : selectedSources2)
140 if (!selectedSources.contains(src))
142 selectedSources.add(src);
146 Vector sqs = new Vector();
147 for (int i = 0; i < oursequences.length; i++)
149 if (!sqs.contains(oursequences[i]))
151 sqs.addElement(oursequences[i]);
154 sequences = new SequenceI[sqs.size()];
155 for (int i = 0; i < sequences.length; i++)
157 sequences[i] = (SequenceI) sqs.elementAt(i);
159 if (fsettings != null)
161 this.fsettings = fsettings;
162 this.af = fsettings.af;
163 af.setShowSeqFeatures(true);
165 int uniprotCount = 0;
166 for (jalviewSourceI source : selectedSources)
168 for (COORDINATES coords : source.getVersion().getCOORDINATES())
170 // TODO: match UniProt coord system canonically (?) - does
171 // UniProt==uniprot==UNIPROT ?
172 if (coords.getAuthority().toLowerCase().equals("uniprot"))
181 for (int i = 0; i < sequences.length; i++)
183 DBRefEntry[] dbref = sequences[i].getDBRef();
186 for (int j = 0; j < dbref.length; j++)
188 if (dbref[j].getSource().equals(
189 jalview.datamodel.DBRefSource.UNIPROT))
198 if (checkDbrefs && refCount < sequences.length && uniprotCount > 0)
201 int reply = JOptionPane.YES_OPTION;
202 if (promptFetchDbrefs)
205 .showInternalConfirmDialog(
207 "Do you want Jalview to find\n"
208 + "Uniprot Accession ids for given sequence names?",
209 "Find Uniprot Accession Ids",
210 JOptionPane.YES_NO_OPTION,
211 JOptionPane.QUESTION_MESSAGE);
214 if (reply == JOptionPane.YES_OPTION)
216 Thread thread = new Thread(new FetchDBRefs());
231 private void _startFetching()
234 new Thread(new FetchSeqFeatures()).start();
237 class FetchSeqFeatures implements Runnable
242 setGuiFetchComplete();
246 class FetchDBRefs implements Runnable
251 new DBRefFetcher(sequences, af).fetchDBRefs(true);
253 setGuiFetchComplete();
258 * Spawns Fetcher threads to add features to sequences in the dataset
264 startTime = System.currentTimeMillis();
267 af.setProgressBar("Fetching DAS Sequence Features", startTime);
269 if (sourceRegistry == null)
271 sourceRegistry = Cache.getDasSourceRegistry();
273 if (selectedSources == null || selectedSources.size() == 0)
277 jalviewSourceI[] sources = sourceRegistry.getSources().toArray(
278 new jalviewSourceI[0]);
279 String active = jalview.bin.Cache.getDefault("DAS_ACTIVE_SOURCE",
281 StringTokenizer st = new StringTokenizer(active, "\t");
282 selectedSources = new Vector();
284 while (st.hasMoreTokens())
286 token = st.nextToken();
287 for (int i = 0; i < sources.length; i++)
289 if (sources[i].getTitle().equals(token))
291 selectedSources.add(sources[i]);
296 } catch (Exception ex)
298 debug("Exception whilst setting default feature sources from registry and local preferences.",
303 if (selectedSources == null || selectedSources.size() == 0)
305 System.out.println("No DAS Sources active");
307 setGuiNoDassourceActive();
311 sourcesRemaining = selectedSources.size();
312 FeaturesClientMultipleSources fc = new FeaturesClientMultipleSources();
313 fc.setConnProps(sourceRegistry.getSessionHandler());
314 // Now sending requests one at a time to each server
315 ArrayList<jalviewSourceI> srcobj = new ArrayList<jalviewSourceI>();
316 ArrayList<String> src = new ArrayList<String>();
317 List<List<String>> ids = new ArrayList<List<String>>();
318 List<List<DBRefEntry>> idobj = new ArrayList<List<DBRefEntry>>();
319 List<Map<String, SequenceI>> sqset = new ArrayList<Map<String, SequenceI>>();
320 for (jalviewSourceI _sr : selectedSources)
323 Map<String, SequenceI> slist = new HashMap<String, SequenceI>();
324 List<DBRefEntry> idob = new ArrayList<DBRefEntry>();
325 List<String> qset = new ArrayList<String>();
327 for (SequenceI seq : sequences)
329 Object[] idset = nextSequence(_sr, seq);
332 List<DBRefEntry> _idob = (List<DBRefEntry>) idset[0];
333 List<String> _qset = (List<String>) idset[1];
334 if (_idob.size() > 0)
336 // add sequence's ref for each id derived from it
337 // (space inefficient, but most unambiguous)
338 // could replace with hash with _qset values as keys.
339 Iterator<DBRefEntry> dbobj = _idob.iterator();
340 for (String q : _qset)
342 SequenceI osq = slist.get(q);
343 DBRefEntry dr = dbobj.next();
344 if (osq != null && osq != seq)
346 // skip - non-canonical query
361 src.add(_sr.getSourceURL());
367 Map<String, Map<List<String>, Exception>> errors = new HashMap<String, Map<List<String>, Exception>>();
368 Map<String, Map<List<String>, DasGFFAdapter>> results = new HashMap<String, Map<List<String>, DasGFFAdapter>>();
369 if (!useJDASMultiThread)
371 Iterator<String> sources = src.iterator();
372 // iterate over each query for each source and do each one individually
373 for (List<String> idl : ids)
375 String source = sources.next();
376 FeaturesClient featuresc = new FeaturesClient(sourceRegistry
377 .getSessionHandler().getConnectionPropertyProviderFor(
379 for (String id : idl)
381 List<String> qid = Arrays.asList(new String[]
385 DasGFFAdapter dga = featuresc.fetchData(source, qid);
386 Map<List<String>, DasGFFAdapter> ers = results.get(source);
390 ers = new HashMap<List<String>, DasGFFAdapter>());
393 } catch (Exception ex)
395 Map<List<String>, Exception> ers = errors.get(source);
399 ers = new HashMap<List<String>, Exception>());
408 // pass them all at once
409 fc.fetchData(src, ids, false, results, errors);
411 while (!fc.isTerminated())
416 } catch (InterruptedException x)
422 Iterator<List<String>> idset = ids.iterator();
423 Iterator<List<DBRefEntry>> idobjset = idobj.iterator();
424 Iterator<Map<String, SequenceI>> seqset = sqset.iterator();
425 for (jalviewSourceI source : srcobj)
427 processResponse(seqset.next(), source, idset.next(), idobjset.next(),
428 results.get(source.getSourceURL()),
429 errors.get(source.getSourceURL()));
433 private void processResponse(Map<String, SequenceI> sequencemap,
434 jalviewSourceI jvsource, List<String> ids,
435 List<DBRefEntry> idobj, Map<List<String>, DasGFFAdapter> results,
436 Map<List<String>, Exception> errors)
438 Set<SequenceI> sequences = new HashSet<SequenceI>();
439 String source = jvsource.getSourceURL();
441 DasGFFAdapter result = (results == null) ? null : results.get(ids);
442 Exception error = (errors == null) ? null : errors.get(ids);
445 debug("das source " + source + " could not be contacted. "
446 + (error == null ? "" : error.toString()));
451 GFFAdapter gff = result.getGFF();
452 List<SEGMENT> segments = gff.getSegments();
453 List<ERRORSEGMENT> errorsegs = gff.getErrorSegments();
454 List<UNKNOWNFEATURE> unkfeats = gff.getUnknownFeatures();
455 List<UNKNOWNSEGMENT> unksegs = gff.getUnknownSegments();
456 debug("das source " + source + " returned " + gff.getTotal()
457 + " responses. " + (errorsegs != null ? errorsegs.size() : 0)
458 + " were incorrect segment queries, "
459 + (unkfeats != null ? unkfeats.size() : 0)
460 + " were unknown features "
461 + (unksegs != null ? unksegs.size() : 0)
462 + " were unknown segments and "
463 + (segments != null ? segments.size() : 0)
464 + " were segment responses.");
465 Iterator<DBRefEntry> dbr = idobj.iterator();
466 if (segments != null)
468 for (SEGMENT seg : segments)
470 String id = seg.getId();
471 if (ids.indexOf(id) == -1)
473 id = id.toUpperCase();
475 DBRefEntry dbref = idobj.get(ids.indexOf(id));
476 SequenceI sequence = sequencemap.get(id);
477 boolean added = false;
478 sequences.add(sequence);
480 for (FEATURE feat : seg.getFEATURE())
482 // standard DAS feature-> jalview sequence feature transformation
483 SequenceFeature f = newSequenceFeature(feat,
484 jvsource.getTitle());
485 if (!parseSeqFeature(sequence, f, feat, jvsource))
487 if (dbref.getMap() != null && f.getBegin() > 0
490 debug("mapping from " + f.getBegin() + " - " + f.getEnd());
491 SequenceFeature vf[] = null;
495 vf = dbref.getMap().locateFeature(f);
496 } catch (Exception ex)
499 .info("Error in 'experimental' mapping of features. Please try to reproduce and then report info to jalview-discuss@jalview.org.");
500 Cache.log.info("Mapping feature from " + f.getBegin()
501 + " to " + f.getEnd() + " in dbref "
502 + dbref.getAccessionId() + " in "
503 + dbref.getSource());
504 Cache.log.info("using das Source " + source);
505 Cache.log.info("Exception", ex);
510 for (int v = 0; v < vf.length; v++)
512 debug("mapping to " + v + ": " + vf[v].getBegin()
513 + " - " + vf[v].getEnd());
514 sequence.addSequenceFeature(vf[v]);
520 sequence.addSequenceFeature(f);
525 featuresAdded(sequences);
529 // System.out.println("No features found for " + seq.getName()
530 // + " from: " + e.getDasSource().getNickname());
535 private void setGuiNoDassourceActive()
540 af.setProgressBar("No DAS Sources Active", startTime);
542 if (getFeatSettings() != null)
544 fsettings.noDasSourceActive();
549 * Update our fsettings dialog reference if we didn't have one when we were
554 private FeatureSettings getFeatSettings()
556 if (fsettings == null)
560 fsettings = af.featureSettings;
570 af.setProgressBar("DAS Feature Fetching Cancelled", startTime);
575 int sourcesRemaining = 0;
577 private boolean running = false;
579 private void setGuiFetchComplete()
582 if (!cancelled && af != null)
584 // only update the progress bar if we've completed the fetch normally
585 af.setProgressBar("DAS Feature Fetching Complete", startTime);
588 if (af != null && af.featureSettings != null)
590 af.featureSettings.setTableData();
593 if (getFeatSettings() != null)
595 fsettings.complete();
599 void featuresAdded(Set<SequenceI> seqs)
603 // no gui to update with features.
606 af.getFeatureRenderer().featuresAdded();
608 int start = af.getViewport().getStartSeq();
609 int end = af.getViewport().getEndSeq();
611 for (index = start; index < end; index++)
613 for (SequenceI seq : seqs)
615 if (seq == af.getViewport().getAlignment().getSequenceAt(index)
616 .getDatasetSequence())
618 af.alignPanel.paintAlignment(true);
626 Object[] nextSequence(jalviewSourceI dasSource, SequenceI seq)
630 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
631 seq.getDBRef(), new String[]
633 // jalview.datamodel.DBRefSource.PDB,
634 jalview.datamodel.DBRefSource.UNIPROT,
635 // jalview.datamodel.DBRefSource.EMBL - not tested on any EMBL coord
638 // TODO: minimal list of DAS queries to make by querying with untyped ID if
639 // distinct from any typed IDs
641 List<DBRefEntry> ids = new ArrayList<DBRefEntry>();
642 List<String> qstring = new ArrayList<String>();
643 boolean dasCoordSysFound = false;
647 // do any of these ids match the source's coordinate system ?
648 for (int j = 0; !dasCoordSysFound && j < uprefs.length; j++)
651 for (COORDINATES csys : dasSource.getVersion().getCOORDINATES())
653 if (jalview.util.DBRefUtils.isDasCoordinateSystem(
654 csys.getAuthority(), uprefs[j]))
656 debug("Launched fetcher for coordinate system "
657 + csys.getAuthority());
658 // Will have to pass any mapping information to the fetcher
659 // - the start/end for the DBRefEntry may not be the same as the
660 // sequence's start/end
662 System.out.println(seq.getName() + " "
663 + (seq.getDatasetSequence() == null) + " "
666 dasCoordSysFound = true; // break's out of the loop
668 qstring.add(uprefs[j].getAccessionId());
671 System.out.println("IGNORE " + csys.getAuthority());
676 if (!dasCoordSysFound)
679 // try and use the name as the sequence id
680 if (seq.getName().indexOf("|") > -1)
682 id = seq.getName().substring(seq.getName().lastIndexOf("|") + 1);
683 if (id.trim().length() < 4)
685 // hack - we regard a significant ID as being at least 4
686 // non-whitespace characters
687 id = seq.getName().substring(0, seq.getName().lastIndexOf("|"));
688 if (id.indexOf("|") > -1)
690 id = id.substring(id.lastIndexOf("|") + 1);
700 DBRefEntry dbre = new DBRefEntry();
701 dbre.setAccessionId(id);
702 // Should try to call a general feature fetcher that
703 // queries many sources with name to discover applicable ID references
705 qstring.add(dbre.getAccessionId());
714 * examine the given sequence feature to determine if it should actually be
715 * turned into sequence annotation or database cross references rather than a
716 * simple sequence feature.
719 * the sequence to annotate
721 * the jalview sequence feature generated from the DAS feature
723 * the sequence feature attributes
725 * the source that emitted the feature
726 * @return true if feature was consumed as another kind of annotation.
728 protected boolean parseSeqFeature(SequenceI seq, SequenceFeature f,
729 FEATURE feature, jalviewSourceI source)
731 SequenceI mseq = seq;
732 while (seq.getDatasetSequence() != null)
734 seq = seq.getDatasetSequence();
736 if (f.getType() != null)
738 String type = f.getType();
739 if (type.equalsIgnoreCase("protein_name"))
741 // parse name onto the alignment sequence or the dataset sequence.
742 if (seq.getDescription() == null
743 || seq.getDescription().trim().length() == 0)
745 // could look at the note series to pick out the first long name, for
746 // the moment just use the whole description string
747 seq.setDescription(f.getDescription());
749 if (mseq.getDescription() == null
750 || mseq.getDescription().trim().length() == 0)
752 // could look at the note series to pick out the first long name, for
753 // the moment just use the whole description string
754 mseq.setDescription(f.getDescription());
758 // check if source has biosapiens or other sequence ontology label
759 if (type.equalsIgnoreCase("DBXREF") || type.equalsIgnoreCase("DBREF"))
761 // try to parse the accession out
763 DBRefEntry dbr = new DBRefEntry();
764 dbr.setVersion(source.getTitle());
765 StringTokenizer st = new StringTokenizer(f.getDescription(), ":");
766 if (st.hasMoreTokens())
768 dbr.setSource(st.nextToken());
770 if (st.hasMoreTokens())
772 dbr.setAccessionId(st.nextToken());
776 if (f.links != null && f.links.size() > 0)
778 // feature is also appended to enable links to be seen.
779 // TODO: consider extending dbrefs to have their own links ?
780 // TODO: new feature: extract dbref links from DAS servers and add the
781 // URL pattern to the list of DB name associated links in the user's
783 // for the moment - just fix up the existing feature so it displays
785 // f.setType(dbr.getSource());
786 // f.setDescription();
787 f.setValue("linkonly", Boolean.TRUE);
788 // f.setDescription("");
789 Vector newlinks = new Vector();
790 Enumeration it = f.links.elements();
791 while (it.hasMoreElements())
794 UrlLink urllink = new UrlLink(elm = (String) it.nextElement());
795 if (urllink.isValid())
797 urllink.setLabel(f.getDescription());
798 newlinks.addElement(urllink.toString());
802 // couldn't parse the link properly. Keep it anyway - just in
804 debug("couldn't parse link string - " + elm);
805 newlinks.addElement(elm);
809 seq.addSequenceFeature(f);
818 * creates a jalview sequence feature from a das feature document
821 * @return sequence feature object created using dasfeature information
823 SequenceFeature newSequenceFeature(FEATURE feat, String nickname)
832 * Different qNames for a DAS Feature - are string keys to the HashMaps in
833 * features "METHOD") || qName.equals("TYPE") || qName.equals("START") ||
834 * qName.equals("END") || qName.equals("NOTE") || qName.equals("LINK") ||
835 * qName.equals("SCORE")
837 String desc = new String();
838 if (feat.getNOTE() != null)
840 for (String note : feat.getNOTE())
842 desc += (String) note;
846 int start = 0, end = 0;
851 start = Integer.parseInt(feat.getSTART().toString());
852 } catch (Exception ex)
857 end = Integer.parseInt(feat.getEND().toString());
858 } catch (Exception ex)
863 Object scr = feat.getSCORE();
866 score = (float) Double.parseDouble(scr.toString());
869 } catch (Exception ex)
873 SequenceFeature f = new SequenceFeature(
874 getTypeString(feat.getTYPE()), desc, start, end, score,
877 if (feat.getLINK() != null)
879 for (LINK link : feat.getLINK())
881 // Do not put feature extent in link text for non-positional features
882 if (f.begin == 0 && f.end == 0)
884 f.addLink(f.getType() + " " + link.getContent() + "|"
889 f.addLink(f.getType() + " " + f.begin + "_" + f.end + " "
890 + link.getContent() + "|" + link.getHref());
896 } catch (Exception e)
898 System.out.println("ERRR " + e);
900 System.out.println("############");
901 debug("Failed to parse " + feat.toString(), e);
906 private String getTypeString(TYPE type)
908 return type.getContent();
911 public boolean isRunning()