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()
258 new DBRefFetcher(sequences, af, null, af.featureSettings,
259 isNucleotide).fetchDBRefs(true);
262 setGuiFetchComplete();
267 * Spawns Fetcher threads to add features to sequences in the dataset
273 startTime = System.currentTimeMillis();
276 af.setProgressBar(MessageManager
277 .getString("status.fetching_das_sequence_features"),
280 if (sourceRegistry == null)
282 sourceRegistry = Cache.getDasSourceRegistry();
284 if (selectedSources == null || selectedSources.size() == 0)
288 jalviewSourceI[] sources = sourceRegistry.getSources().toArray(
289 new jalviewSourceI[0]);
290 String active = Cache.getDefault("DAS_ACTIVE_SOURCE",
292 StringTokenizer st = new StringTokenizer(active, "\t");
293 selectedSources = new Vector();
295 while (st.hasMoreTokens())
297 token = st.nextToken();
298 for (int i = 0; i < sources.length; i++)
300 if (sources[i].getTitle().equals(token))
302 selectedSources.add(sources[i]);
307 } catch (Exception ex)
309 debug("Exception whilst setting default feature sources from registry and local preferences.",
314 if (selectedSources == null || selectedSources.size() == 0)
316 System.out.println("No DAS Sources active");
318 setGuiNoDassourceActive();
322 sourcesRemaining = selectedSources.size();
323 FeaturesClientMultipleSources fc = new FeaturesClientMultipleSources();
324 fc.setConnProps(sourceRegistry.getSessionHandler());
325 // Now sending requests one at a time to each server
326 ArrayList<jalviewSourceI> srcobj = new ArrayList<jalviewSourceI>();
327 ArrayList<String> src = new ArrayList<String>();
328 List<List<String>> ids = new ArrayList<List<String>>();
329 List<List<DBRefEntry>> idobj = new ArrayList<List<DBRefEntry>>();
330 List<Map<String, SequenceI>> sqset = new ArrayList<Map<String, SequenceI>>();
331 for (jalviewSourceI _sr : selectedSources)
334 Map<String, SequenceI> slist = new HashMap<String, SequenceI>();
335 List<DBRefEntry> idob = new ArrayList<DBRefEntry>();
336 List<String> qset = new ArrayList<String>();
338 for (SequenceI seq : sequences)
340 Object[] idset = nextSequence(_sr, seq);
343 List<DBRefEntry> _idob = (List<DBRefEntry>) idset[0];
344 List<String> _qset = (List<String>) idset[1];
345 if (_idob.size() > 0)
347 // add sequence's ref for each id derived from it
348 // (space inefficient, but most unambiguous)
349 // could replace with hash with _qset values as keys.
350 Iterator<DBRefEntry> dbobj = _idob.iterator();
351 for (String q : _qset)
353 SequenceI osq = slist.get(q);
354 DBRefEntry dr = dbobj.next();
355 if (osq != null && osq != seq)
357 // skip - non-canonical query
372 src.add(_sr.getSourceURL());
378 Map<String, Map<List<String>, Exception>> errors = new HashMap<String, Map<List<String>, Exception>>();
379 Map<String, Map<List<String>, DasGFFAdapter>> results = new HashMap<String, Map<List<String>, DasGFFAdapter>>();
380 if (!useJDASMultiThread)
382 Iterator<String> sources = src.iterator();
383 // iterate over each query for each source and do each one individually
384 for (List<String> idl : ids)
386 String source = sources.next();
387 FeaturesClient featuresc = new FeaturesClient(sourceRegistry
388 .getSessionHandler().getConnectionPropertyProviderFor(
390 for (String id : idl)
392 List<String> qid = Arrays.asList(new String[] { id });
395 DasGFFAdapter dga = featuresc.fetchData(source, qid);
396 Map<List<String>, DasGFFAdapter> ers = results.get(source);
400 ers = new HashMap<List<String>, DasGFFAdapter>());
403 } catch (Exception ex)
405 Map<List<String>, Exception> ers = errors.get(source);
409 ers = new HashMap<List<String>, Exception>());
418 // pass them all at once
419 fc.fetchData(src, ids, false, results, errors);
421 while (!fc.isTerminated())
426 } catch (InterruptedException x)
432 Iterator<List<String>> idset = ids.iterator();
433 Iterator<List<DBRefEntry>> idobjset = idobj.iterator();
434 Iterator<Map<String, SequenceI>> seqset = sqset.iterator();
435 for (jalviewSourceI source : srcobj)
437 processResponse(seqset.next(), source, idset.next(), idobjset.next(),
438 results.get(source.getSourceURL()),
439 errors.get(source.getSourceURL()));
443 private void processResponse(Map<String, SequenceI> sequencemap,
444 jalviewSourceI jvsource, List<String> ids,
445 List<DBRefEntry> idobj, Map<List<String>, DasGFFAdapter> results,
446 Map<List<String>, Exception> errors)
448 Set<SequenceI> sequences = new HashSet<SequenceI>();
449 String source = jvsource.getSourceURL();
451 DasGFFAdapter result = (results == null) ? null : results.get(ids);
452 Exception error = (errors == null) ? null : errors.get(ids);
455 debug("das source " + source + " could not be contacted. "
456 + (error == null ? "" : error.toString()));
461 GFFAdapter gff = result.getGFF();
462 List<SEGMENT> segments = gff.getSegments();
463 List<ERRORSEGMENT> errorsegs = gff.getErrorSegments();
464 List<UNKNOWNFEATURE> unkfeats = gff.getUnknownFeatures();
465 List<UNKNOWNSEGMENT> unksegs = gff.getUnknownSegments();
466 debug("das source " + source + " returned " + gff.getTotal()
467 + " responses. " + (errorsegs != null ? errorsegs.size() : 0)
468 + " were incorrect segment queries, "
469 + (unkfeats != null ? unkfeats.size() : 0)
470 + " were unknown features "
471 + (unksegs != null ? unksegs.size() : 0)
472 + " were unknown segments and "
473 + (segments != null ? segments.size() : 0)
474 + " were segment responses.");
475 Iterator<DBRefEntry> dbr = idobj.iterator();
476 if (segments != null)
478 for (SEGMENT seg : segments)
480 String id = seg.getId();
481 if (ids.indexOf(id) == -1)
483 id = id.toUpperCase();
485 DBRefEntry dbref = idobj.get(ids.indexOf(id));
486 SequenceI sequence = sequencemap.get(id);
487 boolean added = false;
488 sequences.add(sequence);
490 for (FEATURE feat : seg.getFEATURE())
492 // standard DAS feature-> jalview sequence feature transformation
493 SequenceFeature f = newSequenceFeature(feat,
494 jvsource.getTitle());
495 if (!parseSeqFeature(sequence, f, feat, jvsource))
497 if (dbref.getMap() != null && f.getBegin() > 0
500 debug("mapping from " + f.getBegin() + " - " + f.getEnd());
501 SequenceFeature vf[] = null;
505 vf = dbref.getMap().locateFeature(f);
506 } catch (Exception ex)
509 .warn("Error in 'experimental' mapping of features. Please try to reproduce and then report info to jalview-discuss@jalview.org.");
510 Cache.log.warn("Mapping feature from " + f.getBegin()
511 + " to " + f.getEnd() + " in dbref "
512 + dbref.getAccessionId() + " in "
513 + dbref.getSource());
514 Cache.log.warn("using das Source " + source);
515 Cache.log.warn("Exception", ex);
520 for (int v = 0; v < vf.length; v++)
522 debug("mapping to " + v + ": " + vf[v].getBegin()
523 + " - " + vf[v].getEnd());
524 sequence.addSequenceFeature(vf[v]);
530 sequence.addSequenceFeature(f);
535 featuresAdded(sequences);
539 // System.out.println("No features found for " + seq.getName()
540 // + " from: " + e.getDasSource().getNickname());
545 private void setGuiNoDassourceActive()
551 MessageManager.getString("status.no_das_sources_active"),
554 if (getFeatSettings() != null)
556 fsettings.noDasSourceActive();
561 * Update our fsettings dialog reference if we didn't have one when we were
566 private FeatureSettings getFeatSettings()
568 if (fsettings == null)
572 fsettings = af.featureSettings;
582 af.setProgressBar(MessageManager
583 .getString("status.das_feature_fetching_cancelled"),
589 int sourcesRemaining = 0;
591 private boolean running = false;
593 private void setGuiFetchComplete()
596 if (!cancelled && af != null)
598 // only update the progress bar if we've completed the fetch normally
599 af.setProgressBar(MessageManager
600 .getString("status.das_feature_fetching_complete"), startTime);
603 if (af != null && af.featureSettings != null)
605 af.featureSettings.discoverAllFeatureData();
608 if (getFeatSettings() != null)
610 fsettings.complete();
614 void featuresAdded(Set<SequenceI> seqs)
618 // no gui to update with features.
621 af.getFeatureRenderer().featuresAdded();
623 int start = af.getViewport().getStartSeq();
624 int end = af.getViewport().getEndSeq();
626 for (index = start; index < end; index++)
628 for (SequenceI seq : seqs)
630 if (seq == af.getViewport().getAlignment().getSequenceAt(index)
631 .getDatasetSequence())
633 af.alignPanel.paintAlignment(true);
641 Object[] nextSequence(jalviewSourceI dasSource, SequenceI seq)
647 DBRefEntry[] uprefs = DBRefUtils.selectRefs(
648 seq.getDBRefs(), new String[] {
649 // jalview.datamodel.DBRefSource.PDB,
651 // jalview.datamodel.DBRefSource.EMBL - not tested on any EMBL coord
654 // TODO: minimal list of DAS queries to make by querying with untyped ID if
655 // distinct from any typed IDs
657 List<DBRefEntry> ids = new ArrayList<DBRefEntry>();
658 List<String> qstring = new ArrayList<String>();
659 boolean dasCoordSysFound = false;
663 // do any of these ids match the source's coordinate system ?
664 for (int j = 0; !dasCoordSysFound && j < uprefs.length; j++)
667 for (COORDINATES csys : dasSource.getVersion().getCOORDINATES())
669 if (DBRefUtils.isDasCoordinateSystem(
670 csys.getAuthority(), uprefs[j]))
672 debug("Launched fetcher for coordinate system "
673 + csys.getAuthority());
674 // Will have to pass any mapping information to the fetcher
675 // - the start/end for the DBRefEntry may not be the same as the
676 // sequence's start/end
678 System.out.println(seq.getName() + " "
679 + (seq.getDatasetSequence() == null) + " "
682 dasCoordSysFound = true; // break's out of the loop
684 qstring.add(uprefs[j].getAccessionId());
688 System.out.println("IGNORE " + csys.getAuthority());
694 if (!dasCoordSysFound)
697 // try and use the name as the sequence id
698 if (seq.getName().indexOf("|") > -1)
700 id = seq.getName().substring(seq.getName().lastIndexOf("|") + 1);
701 if (id.trim().length() < 4)
703 // hack - we regard a significant ID as being at least 4
704 // non-whitespace characters
705 id = seq.getName().substring(0, seq.getName().lastIndexOf("|"));
706 if (id.indexOf("|") > -1)
708 id = id.substring(id.lastIndexOf("|") + 1);
718 DBRefEntry dbre = new DBRefEntry();
719 dbre.setAccessionId(id);
720 // Should try to call a general feature fetcher that
721 // queries many sources with name to discover applicable ID references
723 qstring.add(dbre.getAccessionId());
727 return new Object[] { ids, qstring };
731 * examine the given sequence feature to determine if it should actually be
732 * turned into sequence annotation or database cross references rather than a
733 * simple sequence feature.
736 * the sequence to annotate
738 * the jalview sequence feature generated from the DAS feature
740 * the sequence feature attributes
742 * the source that emitted the feature
743 * @return true if feature was consumed as another kind of annotation.
745 protected boolean parseSeqFeature(SequenceI seq, SequenceFeature f,
746 FEATURE feature, jalviewSourceI source)
748 SequenceI mseq = seq;
749 while (seq.getDatasetSequence() != null)
751 seq = seq.getDatasetSequence();
753 if (f.getType() != null)
755 String type = f.getType();
756 if (type.equalsIgnoreCase("protein_name"))
758 // parse name onto the alignment sequence or the dataset sequence.
759 if (seq.getDescription() == null
760 || seq.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 seq.setDescription(f.getDescription());
766 if (mseq.getDescription() == null
767 || mseq.getDescription().trim().length() == 0)
769 // could look at the note series to pick out the first long name, for
770 // the moment just use the whole description string
771 mseq.setDescription(f.getDescription());
775 // check if source has biosapiens or other sequence ontology label
776 if (type.equalsIgnoreCase("DBXREF") || type.equalsIgnoreCase("DBREF"))
778 // try to parse the accession out
780 DBRefEntry dbr = new DBRefEntry();
781 dbr.setVersion(source.getTitle());
782 StringTokenizer st = new StringTokenizer(f.getDescription(), ":");
783 if (st.hasMoreTokens())
785 dbr.setSource(st.nextToken());
787 if (st.hasMoreTokens())
789 dbr.setAccessionId(st.nextToken());
793 if (f.links != null && f.links.size() > 0)
795 // feature is also appended to enable links to be seen.
796 // TODO: consider extending dbrefs to have their own links ?
797 // TODO: new feature: extract dbref links from DAS servers and add the
798 // URL pattern to the list of DB name associated links in the user's
800 // for the moment - just fix up the existing feature so it displays
802 // f.setType(dbr.getSource());
803 // f.setDescription();
804 f.setValue("linkonly", Boolean.TRUE);
805 // f.setDescription("");
806 Vector newlinks = new Vector();
807 Enumeration it = f.links.elements();
808 while (it.hasMoreElements())
811 UrlLink urllink = new UrlLink(elm = (String) it.nextElement());
812 if (urllink.isValid())
814 urllink.setLabel(f.getDescription());
815 newlinks.addElement(urllink.toString());
819 // couldn't parse the link properly. Keep it anyway - just in
821 debug("couldn't parse link string - " + elm);
822 newlinks.addElement(elm);
826 seq.addSequenceFeature(f);
835 * creates a jalview sequence feature from a das feature document
838 * @return sequence feature object created using dasfeature information
840 SequenceFeature newSequenceFeature(FEATURE feat, String nickname)
849 * Different qNames for a DAS Feature - are string keys to the HashMaps in
850 * features "METHOD") || qName.equals("TYPE") || qName.equals("START") ||
851 * qName.equals("END") || qName.equals("NOTE") || qName.equals("LINK") ||
852 * qName.equals("SCORE")
854 String desc = new String();
855 if (feat.getNOTE() != null)
857 for (String note : feat.getNOTE())
863 int start = 0, end = 0;
868 start = Integer.parseInt(feat.getSTART().toString());
869 } catch (Exception ex)
874 end = Integer.parseInt(feat.getEND().toString());
875 } catch (Exception ex)
880 Object scr = feat.getSCORE();
883 score = (float) Double.parseDouble(scr.toString());
886 } catch (Exception ex)
890 SequenceFeature f = new SequenceFeature(
891 getTypeString(feat.getTYPE()), desc, start, end, score,
894 if (feat.getLINK() != null)
896 for (LINK link : feat.getLINK())
898 // Do not put feature extent in link text for non-positional features
899 if (f.begin == 0 && f.end == 0)
901 f.addLink(f.getType() + " " + link.getContent() + "|"
906 f.addLink(f.getType() + " " + f.begin + "_" + f.end + " "
907 + link.getContent() + "|" + link.getHref());
913 } catch (Exception e)
915 System.out.println("ERRR " + e);
917 System.out.println("############");
918 debug("Failed to parse " + feat.toString(), e);
923 private String getTypeString(TYPE type)
925 return type.getContent();
928 public boolean isRunning()