JAL-2738 tidy Javadoc, remove debug logging
[jalview.git] / src / jalview / gui / CrossRefAction.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.AlignmentUtils;
24 import jalview.analysis.CrossRef;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.api.FeatureSettingsModelI;
27 import jalview.bin.Cache;
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.DBRefSource;
32 import jalview.datamodel.GeneLociI;
33 import jalview.datamodel.SequenceI;
34 import jalview.ext.ensembl.EnsemblInfo;
35 import jalview.ext.ensembl.EnsemblMap;
36 import jalview.io.gff.SequenceOntologyI;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.DBRefUtils;
39 import jalview.util.MapList;
40 import jalview.util.MappingUtils;
41 import jalview.util.MessageManager;
42 import jalview.ws.SequenceFetcher;
43
44 import java.util.ArrayList;
45 import java.util.HashMap;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49
50 /**
51  * Factory constructor and runnable for discovering and displaying
52  * cross-references for a set of aligned sequences
53  * 
54  * @author jprocter
55  *
56  */
57 public class CrossRefAction implements Runnable
58 {
59   private AlignFrame alignFrame;
60
61   private SequenceI[] sel;
62
63   private final boolean _odna;
64
65   private String source;
66
67   List<AlignmentViewPanel> xrefViews = new ArrayList<>();
68
69   List<AlignmentViewPanel> getXrefViews()
70   {
71     return xrefViews;
72   }
73
74   @Override
75   public void run()
76   {
77     final long sttime = System.currentTimeMillis();
78     alignFrame.setProgressBar(MessageManager.formatMessage(
79             "status.searching_for_sequences_from", new Object[]
80             { source }), sttime);
81     try
82     {
83       AlignmentI alignment = alignFrame.getViewport().getAlignment();
84       AlignmentI dataset = alignment.getDataset() == null ? alignment
85               : alignment.getDataset();
86       boolean dna = alignment.isNucleotide();
87       if (_odna != dna)
88       {
89         System.err
90                 .println("Conflict: showProducts for alignment originally "
91                         + "thought to be " + (_odna ? "DNA" : "Protein")
92                         + " now searching for " + (dna ? "DNA" : "Protein")
93                         + " Context.");
94       }
95       AlignmentI xrefs = new CrossRef(sel, dataset)
96               .findXrefSequences(source, dna);
97       if (xrefs == null)
98       {
99         return;
100       }
101
102       /*
103        * try to look up chromosomal coordinates for nucleotide
104        * sequences (if not already retrieved)
105        */
106       findGeneLoci(xrefs.getSequences());
107
108       /*
109        * get display scheme (if any) to apply to features
110        */
111       FeatureSettingsModelI featureColourScheme = new SequenceFetcher()
112               .getFeatureColourScheme(source);
113
114       AlignmentI xrefsAlignment = makeCrossReferencesAlignment(dataset,
115               xrefs);
116       if (!dna)
117       {
118         xrefsAlignment = AlignmentUtils.makeCdsAlignment(
119                 xrefsAlignment.getSequencesArray(), dataset, sel);
120         xrefsAlignment.alignAs(alignment);
121       }
122
123       /*
124        * If we are opening a splitframe, make a copy of this alignment (sharing the same dataset
125        * sequences). If we are DNA, drop introns and update mappings
126        */
127       AlignmentI copyAlignment = null;
128
129       if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
130       {
131         copyAlignment = copyAlignmentForSplitFrame(alignment, dataset, dna,
132                 xrefs, xrefsAlignment);
133         if (copyAlignment == null)
134         {
135           return; // failed
136         }
137       }
138
139       /*
140        * build AlignFrame(s) according to available alignment data
141        */
142       AlignFrame newFrame = new AlignFrame(xrefsAlignment,
143               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
144       if (Cache.getDefault("HIDE_INTRONS", true))
145       {
146         newFrame.hideFeatureColumns(SequenceOntologyI.EXON, false);
147       }
148       String newtitle = String.format("%s %s %s",
149               dna ? MessageManager.getString("label.proteins")
150                       : MessageManager.getString("label.nucleotides"),
151               MessageManager.getString("label.for"), alignFrame.getTitle());
152       newFrame.setTitle(newtitle);
153
154       if (copyAlignment == null)
155       {
156         /*
157          * split frame display is turned off in preferences file
158          */
159         Desktop.addInternalFrame(newFrame, newtitle,
160                 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
161         xrefViews.add(newFrame.alignPanel);
162         return; // via finally clause
163       }
164
165       AlignFrame copyThis = new AlignFrame(copyAlignment,
166               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
167       copyThis.setTitle(alignFrame.getTitle());
168
169       boolean showSequenceFeatures = alignFrame.getViewport()
170               .isShowSequenceFeatures();
171       newFrame.setShowSeqFeatures(showSequenceFeatures);
172       copyThis.setShowSeqFeatures(showSequenceFeatures);
173       FeatureRenderer myFeatureStyling = alignFrame.alignPanel
174               .getSeqPanel().seqCanvas.getFeatureRenderer();
175
176       /*
177        * copy feature rendering settings to split frame
178        */
179       newFrame.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
180               .transferSettings(myFeatureStyling);
181       copyThis.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
182               .transferSettings(myFeatureStyling);
183
184       /*
185        * apply 'database source' feature configuration
186        * if any was found
187        */
188       // TODO is this the feature colouring for the original
189       // alignment or the fetched xrefs? either could be Ensembl
190       newFrame.getViewport().applyFeaturesStyle(featureColourScheme);
191       copyThis.getViewport().applyFeaturesStyle(featureColourScheme);
192
193       SplitFrame sf = new SplitFrame(dna ? copyThis : newFrame,
194               dna ? newFrame : copyThis);
195       newFrame.setVisible(true);
196       copyThis.setVisible(true);
197       String linkedTitle = MessageManager
198               .getString("label.linked_view_title");
199       Desktop.addInternalFrame(sf, linkedTitle, -1, -1);
200       sf.adjustInitialLayout();
201
202       // finally add the top, then bottom frame to the view list
203       xrefViews.add(dna ? copyThis.alignPanel : newFrame.alignPanel);
204       xrefViews.add(!dna ? copyThis.alignPanel : newFrame.alignPanel);
205
206     } catch (OutOfMemoryError e)
207     {
208       new OOMWarning("whilst fetching crossreferences", e);
209     } catch (Throwable e)
210     {
211       Cache.log.error("Error when finding crossreferences", e);
212     } finally
213     {
214       alignFrame.setProgressBar(MessageManager.formatMessage(
215               "status.finished_searching_for_sequences_from", new Object[]
216               { source }), sttime);
217     }
218   }
219
220   /**
221    * Tries to add chromosomal coordinates to any nucleotide sequence which does
222    * not already have them. Coordinates are retrieved from Ensembl given an
223    * Ensembl identifier, either on the sequence itself or on a peptide sequence
224    * it has a reference to.
225    * 
226    * <pre>
227    * Example (human):
228    * - fetch EMBLCDS cross-references for Uniprot entry P30419
229    * - the EMBL sequences do not have xrefs to Ensembl
230    * - the Uniprot entry has xrefs to 
231    *    ENSP00000258960, ENSP00000468424, ENST00000258960, ENST00000592782
232    * - either of the transcript ids can be used to retrieve gene loci e.g.
233    *    http://rest.ensembl.org/map/cds/ENST00000592782/1..100000
234    * Example (invertebrate):
235    * - fetch EMBLCDS cross-references for Uniprot entry Q43517 (FER1_SOLLC)
236    * - the Uniprot entry has an xref to ENSEMBLPLANTS Solyc10g044520.1.1
237    * - can retrieve gene loci with
238    *    http://rest.ensemblgenomes.org/map/cds/Solyc10g044520.1.1/1..100000
239    * </pre>
240    * 
241    * @param sequences
242    */
243   public static void findGeneLoci(List<SequenceI> sequences)
244   {
245     Map<DBRefEntry, GeneLociI> retrievedLoci = new HashMap<>();
246     for (SequenceI seq : sequences)
247     {
248       findGeneLoci(seq, retrievedLoci);
249     }
250   }
251
252   /**
253    * Tres to find chromosomal coordinates for the sequence, by searching its
254    * direct and indirect cross-references for Ensembl. If the loci have already
255    * been retrieved, just reads them out of the map of retrievedLoci; this is
256    * the case of an alternative transcript for the same protein. Otherwise calls
257    * a REST service to retrieve the loci, and if successful, adds them to the
258    * sequence and to the retrievedLoci.
259    * 
260    * @param seq
261    * @param retrievedLoci
262    */
263   static void findGeneLoci(SequenceI seq,
264           Map<DBRefEntry, GeneLociI> retrievedLoci)
265   {
266     /*
267      * don't replace any existing chromosomal coordinates
268      */
269     if (seq == null || seq.isProtein() || seq.getGeneLoci() != null
270             || seq.getDBRefs() == null)
271     {
272       return;
273     }
274     
275     Set<String> ensemblDivisions = new EnsemblInfo().getDivisions();
276     
277     /*
278      * first look for direct dbrefs from sequence to Ensembl
279      */
280     String[] divisionsArray = ensemblDivisions
281             .toArray(new String[ensemblDivisions.size()]);
282     DBRefEntry[] seqRefs = seq.getDBRefs();
283     DBRefEntry[] directEnsemblRefs = DBRefUtils.selectRefs(seqRefs,
284             divisionsArray);
285     if (directEnsemblRefs != null)
286     {
287       for (DBRefEntry ensemblRef : directEnsemblRefs)
288       {
289         if (fetchGeneLoci(seq, ensemblRef, retrievedLoci))
290         {
291           return;
292         }
293       }
294     }
295
296     /*
297      * else look for indirect dbrefs from sequence to Ensembl
298      */
299     for (DBRefEntry dbref : seq.getDBRefs())
300     {
301       if (dbref.getMap() != null && dbref.getMap().getTo() != null)
302       {
303         DBRefEntry[] dbrefs = dbref.getMap().getTo().getDBRefs();
304         DBRefEntry[] indirectEnsemblRefs = DBRefUtils.selectRefs(dbrefs,
305                 divisionsArray);
306         if (indirectEnsemblRefs != null)
307         {
308           for (DBRefEntry ensemblRef : indirectEnsemblRefs)
309           {
310             if (fetchGeneLoci(seq, ensemblRef, retrievedLoci))
311             {
312               return;
313             }
314           }
315         }
316       }
317     }
318   }
319
320   /**
321    * Retrieves chromosomal coordinates for the Ensembl (or EnsemblGenomes)
322    * identifier in dbref. If successful, and the sequence length matches gene
323    * loci length, then add it to the sequence, and to the retrievedLoci map.
324    * Answers true if successful, else false.
325    * 
326    * @param seq
327    * @param dbref
328    * @param retrievedLoci
329    * @return
330    */
331   static boolean fetchGeneLoci(SequenceI seq, DBRefEntry dbref,
332           Map<DBRefEntry, GeneLociI> retrievedLoci)
333   {
334     String accession = dbref.getAccessionId();
335     String division = dbref.getSource();
336
337     /*
338      * hack: ignore cross-references to Ensembl protein ids
339      * (or use map/translation perhaps?)
340      * todo: is there an equivalent in EnsemblGenomes?
341      */
342     if (accession.startsWith("ENSP"))
343     {
344       return false;
345     }
346     EnsemblMap mapper = new EnsemblMap();
347
348     /*
349      * try CDS mapping first
350      */
351     GeneLociI geneLoci = mapper.getCdsMapping(division, accession, 1,
352             seq.getLength());
353     if (geneLoci != null)
354     {
355       MapList map = geneLoci.getMap();
356       int mappedFromLength = MappingUtils.getLength(map.getFromRanges());
357       if (mappedFromLength == seq.getLength())
358       {
359         seq.setGeneLoci(geneLoci.getSpeciesId(), geneLoci.getAssemblyId(),
360                 geneLoci.getChromosomeId(), geneLoci.getMap());
361         retrievedLoci.put(dbref, geneLoci);
362         return true;
363       }
364     }
365
366     /*
367      * else try CDNA mapping
368      */
369     geneLoci = mapper.getCdnaMapping(division, accession, 1,
370             seq.getLength());
371     if (geneLoci != null)
372     {
373       MapList map = geneLoci.getMap();
374       int mappedFromLength = MappingUtils.getLength(map.getFromRanges());
375       if (mappedFromLength == seq.getLength())
376       {
377         seq.setGeneLoci(geneLoci.getSpeciesId(), geneLoci.getAssemblyId(),
378                 geneLoci.getChromosomeId(), geneLoci.getMap());
379         retrievedLoci.put(dbref, geneLoci);
380         return true;
381       }
382     }
383
384     return false;
385   }
386
387   /**
388    * @param alignment
389    * @param dataset
390    * @param dna
391    * @param xrefs
392    * @param xrefsAlignment
393    * @return
394    */
395   protected AlignmentI copyAlignmentForSplitFrame(AlignmentI alignment,
396           AlignmentI dataset, boolean dna, AlignmentI xrefs,
397           AlignmentI xrefsAlignment)
398   {
399     AlignmentI copyAlignment;
400     boolean copyAlignmentIsAligned = false;
401     if (dna)
402     {
403       copyAlignment = AlignmentUtils.makeCdsAlignment(sel, dataset,
404               xrefsAlignment.getSequencesArray());
405       if (copyAlignment.getHeight() == 0)
406       {
407         JvOptionPane.showMessageDialog(alignFrame,
408                 MessageManager.getString("label.cant_map_cds"),
409                 MessageManager.getString("label.operation_failed"),
410                 JvOptionPane.OK_OPTION);
411         System.err.println("Failed to make CDS alignment");
412         return null;
413       }
414
415       /*
416        * pending getting Embl transcripts to 'align', 
417        * we are only doing this for Ensembl
418        */
419       // TODO proper criteria for 'can align as cdna'
420       if (DBRefSource.ENSEMBL.equalsIgnoreCase(source)
421               || AlignmentUtils.looksLikeEnsembl(alignment))
422       {
423         copyAlignment.alignAs(alignment);
424         copyAlignmentIsAligned = true;
425       }
426     }
427     else
428     {
429       copyAlignment = AlignmentUtils.makeCopyAlignment(sel,
430               xrefs.getSequencesArray(), dataset);
431     }
432     copyAlignment
433             .setGapCharacter(alignFrame.viewport.getGapCharacter());
434
435     StructureSelectionManager ssm = StructureSelectionManager
436             .getStructureSelectionManager(Desktop.instance);
437
438     /*
439      * register any new mappings for sequence mouseover etc
440      * (will not duplicate any previously registered mappings)
441      */
442     ssm.registerMappings(dataset.getCodonFrames());
443
444     if (copyAlignment.getHeight() <= 0)
445     {
446       System.err.println(
447               "No Sequences generated for xRef type " + source);
448       return null;
449     }
450
451     /*
452      * align protein to dna
453      */
454     if (dna && copyAlignmentIsAligned)
455     {
456       xrefsAlignment.alignAs(copyAlignment);
457     }
458     else
459     {
460       /*
461        * align cdna to protein - currently only if 
462        * fetching and aligning Ensembl transcripts!
463        */
464       // TODO: generalise for other sources of locus/transcript/cds data
465       if (dna && DBRefSource.ENSEMBL.equalsIgnoreCase(source))
466       {
467         copyAlignment.alignAs(xrefsAlignment);
468       }
469     }
470
471     return copyAlignment;
472   }
473
474   /**
475    * Makes an alignment containing the given sequences, and adds them to the
476    * given dataset, which is also set as the dataset for the new alignment
477    * 
478    * TODO: refactor to DatasetI method
479    * 
480    * @param dataset
481    * @param seqs
482    * @return
483    */
484   protected AlignmentI makeCrossReferencesAlignment(AlignmentI dataset,
485           AlignmentI seqs)
486   {
487     SequenceI[] sprods = new SequenceI[seqs.getHeight()];
488     for (int s = 0; s < sprods.length; s++)
489     {
490       sprods[s] = (seqs.getSequenceAt(s)).deriveSequence();
491       if (dataset.getSequences() == null || !dataset.getSequences()
492               .contains(sprods[s].getDatasetSequence()))
493       {
494         dataset.addSequence(sprods[s].getDatasetSequence());
495       }
496       sprods[s].updatePDBIds();
497     }
498     Alignment al = new Alignment(sprods);
499     al.setDataset(dataset);
500     return al;
501   }
502
503   /**
504    * Constructor
505    * 
506    * @param af
507    * @param seqs
508    * @param fromDna
509    * @param dbSource
510    */
511   CrossRefAction(AlignFrame af, SequenceI[] seqs, boolean fromDna,
512           String dbSource)
513   {
514     this.alignFrame = af;
515     this.sel = seqs;
516     this._odna = fromDna;
517     this.source = dbSource;
518   }
519
520   public static CrossRefAction getHandlerFor(final SequenceI[] sel,
521           final boolean fromDna, final String source,
522           final AlignFrame alignFrame)
523   {
524     return new CrossRefAction(alignFrame, sel, fromDna, source);
525   }
526
527 }