Merge develop to Release_2_8_3_Branch
[jalview.git] / src / jalview / analysis / CrossRef.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.analysis;
22
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.DBRefSource;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceI;
30 import jalview.ws.SequenceFetcher;
31 import jalview.ws.seqfetcher.ASequenceFetcher;
32
33 import java.util.Enumeration;
34 import java.util.Hashtable;
35 import java.util.List;
36 import java.util.Vector;
37
38 /**
39  * Functions for cross-referencing sequence databases. user must first specify
40  * if cross-referencing from protein or dna (set dna==true)
41  * 
42  * @author JimP
43  * 
44  */
45 public class CrossRef
46 {
47   /**
48    * get the DNA or protein references for a protein or dna sequence
49    * 
50    * @param dna
51    * @param rfs
52    * @return
53    */
54   public static DBRefEntry[] findXDbRefs(boolean dna, DBRefEntry[] rfs)
55   {
56     if (dna)
57     {
58       rfs = jalview.util.DBRefUtils.selectRefs(rfs, DBRefSource.PROTEINDBS);
59     }
60     else
61     {
62       rfs = jalview.util.DBRefUtils.selectRefs(rfs,
63               DBRefSource.DNACODINGDBS); // could attempt to find other cross
64       // refs and return here - ie PDB xrefs
65       // (not dna, not protein seq)
66     }
67     return rfs;
68   }
69
70   public static Hashtable classifyDbRefs(DBRefEntry[] rfs)
71   {
72     Hashtable classes = new Hashtable();
73     classes.put(DBRefSource.PROTEINDBS,
74             jalview.util.DBRefUtils.selectRefs(rfs, DBRefSource.PROTEINDBS));
75     classes.put(DBRefSource.DNACODINGDBS, jalview.util.DBRefUtils
76             .selectRefs(rfs, DBRefSource.DNACODINGDBS));
77     classes.put(DBRefSource.DOMAINDBS,
78             jalview.util.DBRefUtils.selectRefs(rfs, DBRefSource.DOMAINDBS));
79     // classes.put(OTHER, )
80     return classes;
81   }
82
83   /**
84    * @param dna
85    *          true if seqs are DNA seqs
86    * @param seqs
87    * @return a list of sequence database cross reference source types
88    */
89   public static String[] findSequenceXrefTypes(boolean dna, SequenceI[] seqs)
90   {
91     return findSequenceXrefTypes(dna, seqs, null);
92   }
93
94   /**
95    * Indirect references are references from other sequences from the dataset to
96    * any of the direct DBRefEntrys on the given sequences.
97    * 
98    * @param dna
99    *          true if seqs are DNA seqs
100    * @param seqs
101    * @return a list of sequence database cross reference source types
102    */
103   public static String[] findSequenceXrefTypes(boolean dna,
104           SequenceI[] seqs, AlignmentI dataset)
105   {
106     String[] dbrefs = null;
107     Vector refs = new Vector();
108     for (int s = 0; s < seqs.length; s++)
109     {
110       if (seqs[s] != null)
111       {
112
113         SequenceI dss = seqs[s];
114         while (dss.getDatasetSequence() != null)
115         {
116           dss = dss.getDatasetSequence();
117         }
118         DBRefEntry[] rfs = findXDbRefs(dna, dss.getDBRef());
119         for (int r = 0; rfs != null && r < rfs.length; r++)
120         {
121           if (!refs.contains(rfs[r].getSource()))
122           {
123             refs.addElement(rfs[r].getSource());
124           }
125         }
126         if (dataset != null)
127         {
128           // search for references to this sequence's direct references.
129           DBRefEntry[] lrfs = CrossRef
130                   .findXDbRefs(!dna, seqs[s].getDBRef());
131           Vector rseqs = new Vector();
132           CrossRef.searchDatasetXrefs(seqs[s], !dna, lrfs, dataset, rseqs,
133                   null); // don't need to specify codon frame for mapping here
134           Enumeration lr = rseqs.elements();
135           while (lr.hasMoreElements())
136           {
137             SequenceI rs = (SequenceI) lr.nextElement();
138             DBRefEntry[] xrs = findXDbRefs(dna, rs.getDBRef());
139             for (int r = 0; rfs != null && r < rfs.length; r++)
140             {
141               if (!refs.contains(rfs[r].getSource()))
142               {
143                 refs.addElement(rfs[r].getSource());
144               }
145             }
146           }
147         }
148       }
149     }
150     if (refs.size() > 0)
151     {
152       dbrefs = new String[refs.size()];
153       refs.copyInto(dbrefs);
154     }
155     return dbrefs;
156   }
157
158   /*
159    * if (dna) { if (rfs[r].hasMap()) { // most likely this is a protein cross
160    * reference if (!refs.contains(rfs[r].getSource())) {
161    * refs.addElement(rfs[r].getSource()); } } }
162    */
163   public static boolean hasCdnaMap(SequenceI[] seqs)
164   {
165     String[] reftypes = findSequenceXrefTypes(false, seqs);
166     for (int s = 0; s < reftypes.length; s++)
167     {
168       if (reftypes.equals(DBRefSource.EMBLCDS))
169       {
170         return true;
171         // no map
172       }
173     }
174     return false;
175   }
176
177   public static SequenceI[] getCdnaMap(SequenceI[] seqs)
178   {
179     Vector cseqs = new Vector();
180     for (int s = 0; s < seqs.length; s++)
181     {
182       DBRefEntry[] cdna = findXDbRefs(true, seqs[s].getDBRef());
183       for (int c = 0; c < cdna.length; c++)
184       {
185         if (cdna[c].getSource().equals(DBRefSource.EMBLCDS))
186         {
187           System.err
188                   .println("TODO: unimplemented sequence retrieval for coding region sequence.");
189           // TODO: retrieve CDS dataset sequences
190           // need global dataset sequence retriever/resolver to reuse refs
191           // and construct Mapping entry.
192           // insert gaps in CDS according to peptide gaps.
193           // add gapped sequence to cseqs
194         }
195       }
196     }
197     if (cseqs.size() > 0)
198     {
199       SequenceI[] rsqs = new SequenceI[cseqs.size()];
200       cseqs.copyInto(rsqs);
201       return rsqs;
202     }
203     return null;
204
205   }
206
207   /**
208    * 
209    * @param dna
210    * @param seqs
211    * @return
212    */
213   public static Alignment findXrefSequences(SequenceI[] seqs, boolean dna,
214           String source)
215   {
216     return findXrefSequences(seqs, dna, source, null);
217   }
218
219   /**
220    * 
221    * @param seqs
222    * @param dna
223    * @param source
224    * @param dataset
225    *          alignment to search for product sequences.
226    * @return products (as dataset sequences)
227    */
228   public static Alignment findXrefSequences(SequenceI[] seqs, boolean dna,
229           String source, AlignmentI dataset)
230   {
231     Vector rseqs = new Vector();
232     Alignment ral = null;
233     AlignedCodonFrame cf = new AlignedCodonFrame(); // nominal width
234     for (int s = 0; s < seqs.length; s++)
235     {
236       SequenceI dss = seqs[s];
237       while (dss.getDatasetSequence() != null)
238       {
239         dss = dss.getDatasetSequence();
240       }
241       boolean found = false;
242       DBRefEntry[] xrfs = CrossRef.findXDbRefs(dna, dss.getDBRef());
243       if ((xrfs == null || xrfs.length == 0) && dataset != null)
244       {
245         System.out.println("Attempting to find ds Xrefs refs.");
246         DBRefEntry[] lrfs = CrossRef.findXDbRefs(!dna, seqs[s].getDBRef()); // less
247         // ambiguous
248         // would
249         // be a
250         // 'find
251         // primary
252         // dbRefEntry'
253         // method.
254         // filter for desired source xref here
255         found = CrossRef.searchDatasetXrefs(dss, !dna, lrfs, dataset,
256                 rseqs, cf);
257       }
258       for (int r = 0; xrfs != null && r < xrfs.length; r++)
259       {
260         if (source != null && !source.equals(xrfs[r].getSource()))
261         {
262           continue;
263         }
264         if (xrfs[r].hasMap())
265         {
266           if (xrfs[r].getMap().getTo() != null)
267           {
268             Sequence rsq = new Sequence(xrfs[r].getMap().getTo());
269             rseqs.addElement(rsq);
270             if (xrfs[r].getMap().getMap().getFromRatio() != xrfs[r]
271                     .getMap().getMap().getToRatio())
272             {
273               // get sense of map correct for adding to product alignment.
274               if (dna)
275               {
276                 // map is from dna seq to a protein product
277                 cf.addMap(dss, rsq, xrfs[r].getMap().getMap());
278               }
279               else
280               {
281                 // map should be from protein seq to its coding dna
282                 cf.addMap(rsq, dss, xrfs[r].getMap().getMap().getInverse());
283               }
284             }
285             found = true;
286           }
287         }
288         if (!found)
289         {
290           // do a bit more work - search for sequences with references matching
291           // xrefs on this sequence.
292           if (dataset != null)
293           {
294             found |= searchDataset(dss, xrfs[r], dataset, rseqs, cf); // ,false,!dna);
295             if (found)
296              {
297               xrfs[r] = null; // we've recovered seqs for this one.
298             }
299           }
300         }
301       }
302       if (!found)
303       {
304         if (xrfs != null && xrfs.length > 0)
305         {
306           // Try and get the sequence reference...
307           /*
308            * Ideal world - we ask for a sequence fetcher implementation here if
309            * (jalview.io.RunTimeEnvironment.getSequenceFetcher()) (
310            */
311           ASequenceFetcher sftch = new SequenceFetcher();
312           SequenceI[] retrieved = null;
313           int l = xrfs.length;
314           for (int r = 0; r < xrfs.length; r++)
315           {
316             // filter out any irrelevant or irretrievable references
317             if (xrfs[r] == null
318                     || ((source != null && !source.equals(xrfs[r]
319                             .getSource())) || !sftch.isFetchable(xrfs[r]
320                             .getSource())))
321             {
322               l--;
323               xrfs[r] = null;
324             }
325           }
326           if (l > 0)
327           {
328             System.out
329                     .println("Attempting to retrieve cross referenced sequences.");
330             DBRefEntry[] t = new DBRefEntry[l];
331             l = 0;
332             for (int r = 0; r < xrfs.length; r++)
333             {
334               if (xrfs[r] != null)
335               {
336                 t[l++] = xrfs[r];
337               }
338             }
339             xrfs = t;
340             try
341             {
342               retrieved = sftch.getSequences(xrfs); // problem here is we don't
343               // know which of xrfs
344               // resulted in which
345               // retrieved element
346             } catch (Exception e)
347             {
348               System.err
349                       .println("Problem whilst retrieving cross references for Sequence : "
350                               + seqs[s].getName());
351               e.printStackTrace();
352             }
353             if (retrieved != null)
354             {
355               for (int rs = 0; rs < retrieved.length; rs++)
356               {
357                 // TODO: examine each sequence for 'redundancy'
358                 jalview.datamodel.DBRefEntry[] dbr = retrieved[rs]
359                         .getDBRef();
360                 if (dbr != null && dbr.length > 0)
361                 {
362                   for (int di = 0; di < dbr.length; di++)
363                   {
364                     // find any entry where we should put in the sequence being
365                     // cross-referenced into the map
366                     jalview.datamodel.Mapping map = dbr[di].getMap();
367                     if (map != null)
368                     {
369                       if (map.getTo() != null && map.getMap() != null)
370                       {
371                         // should search the local dataset to find any existing
372                         // candidates for To !
373                         try
374                         {
375                           // compare ms with dss and replace with dss in mapping
376                           // if map is congruent
377                           SequenceI ms = map.getTo();
378                           int sf = map.getMap().getToLowest();
379                           int st = map.getMap().getToHighest();
380                           SequenceI mappedrg = ms.getSubSequence(sf, st);
381                           SequenceI loc = dss.getSubSequence(sf, st);
382                           if (mappedrg.getLength() > 0
383                                   && mappedrg.getSequenceAsString().equals(
384                                           loc.getSequenceAsString()))
385                           {
386                             System.err
387                                     .println("Mapping updated for retrieved crossreference");
388                             // method to update all refs of existing To on
389                             // retrieved sequence with dss and merge any props
390                             // on To onto dss.
391                             map.setTo(dss);
392                           }
393                         } catch (Exception e)
394                         {
395                           System.err
396                                   .println("Exception when consolidating Mapped sequence set...");
397                           e.printStackTrace(System.err);
398                         }
399                       }
400                     }
401                   }
402                 }
403                 retrieved[rs].updatePDBIds();
404                 rseqs.addElement(retrieved[rs]);
405               }
406             }
407           }
408         }
409       }
410     }
411     if (rseqs.size() > 0)
412     {
413       SequenceI[] rsqs = new SequenceI[rseqs.size()];
414       rseqs.copyInto(rsqs);
415       ral = new Alignment(rsqs);
416       if (cf != null && cf.getProtMappings() != null)
417       {
418         ral.addCodonFrame(cf);
419       }
420     }
421     return ral;
422   }
423
424   /**
425    * find references to lrfs in the cross-reference set of each sequence in
426    * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
427    * based on source and accession string only - Map and Version are nulled.
428    * 
429    * @param sequenceI
430    * @param lrfs
431    * @param dataset
432    * @param rseqs
433    * @return true if matches were found.
434    */
435   private static boolean searchDatasetXrefs(SequenceI sequenceI,
436           boolean dna, DBRefEntry[] lrfs, AlignmentI dataset, Vector rseqs,
437           AlignedCodonFrame cf)
438   {
439     boolean found = false;
440     if (lrfs == null)
441     {
442       return false;
443     }
444     for (int i = 0; i < lrfs.length; i++)
445     {
446       DBRefEntry xref = new DBRefEntry(lrfs[i]);
447       // add in wildcards
448       xref.setVersion(null);
449       xref.setMap(null);
450       found = searchDataset(sequenceI, xref, dataset, rseqs, cf, false, dna);
451     }
452     return found;
453   }
454
455   /**
456    * search a given sequence dataset for references matching cross-references to
457    * the given sequence
458    * 
459    * @param sequenceI
460    * @param xrf
461    * @param dataset
462    * @param rseqs
463    *          set of unique sequences
464    * @param cf
465    * @return true if one or more unique sequences were found and added
466    */
467   public static boolean searchDataset(SequenceI sequenceI, DBRefEntry xrf,
468           AlignmentI dataset, Vector rseqs, AlignedCodonFrame cf)
469   {
470     return searchDataset(sequenceI, xrf, dataset, rseqs, cf, true, false);
471   }
472
473   /**
474    * TODO: generalise to different protein classifications Search dataset for
475    * DBRefEntrys matching the given one (xrf) and add the associated sequence to
476    * rseq.
477    * 
478    * @param sequenceI
479    * @param xrf
480    * @param dataset
481    * @param rseqs
482    * @param direct
483    *          - search all references or only subset
484    * @param dna
485    *          search dna or protein xrefs (if direct=false)
486    * @return true if relationship found and sequence added.
487    */
488   public static boolean searchDataset(SequenceI sequenceI, DBRefEntry xrf,
489           AlignmentI dataset, Vector rseqs, AlignedCodonFrame cf,
490           boolean direct, boolean dna)
491   {
492     boolean found = false;
493     SequenceI[] typer = new SequenceI[1];
494     if (dataset == null)
495     {
496       return false;
497     }
498     if (dataset.getSequences() == null)
499     {
500       System.err.println("Empty dataset sequence set - NO VECTOR");
501       return false;
502     }
503     List<SequenceI> ds;
504     synchronized (ds = dataset.getSequences())
505     {
506       for (SequenceI nxt : ds)
507       {
508         if (nxt != null)
509         {
510           if (nxt.getDatasetSequence() != null)
511           {
512             System.err
513                     .println("Implementation warning: getProducts passed a dataset alignment without dataset sequences in it!");
514           }
515           if (nxt != sequenceI && nxt != sequenceI.getDatasetSequence())
516           {
517             // check if this is the correct sequence type
518             {
519               typer[0] = nxt;
520               boolean isDna = jalview.util.Comparison.isNucleotide(typer);
521               if ((direct && isDna == dna) || (!direct && isDna != dna))
522               {
523                 // skip this sequence because it is same molecule type
524                 continue;
525               }
526             }
527
528             // look for direct or indirect references in common
529             DBRefEntry[] poss = nxt.getDBRef(), cands = null;
530             if (direct)
531             {
532               cands = jalview.util.DBRefUtils.searchRefs(poss, xrf);
533             }
534             else
535             {
536               poss = CrossRef.findXDbRefs(dna, poss); //
537               cands = jalview.util.DBRefUtils.searchRefs(poss, xrf);
538             }
539             if (cands != null)
540             {
541               if (!rseqs.contains(nxt))
542               {
543                 rseqs.addElement(nxt);
544                 boolean foundmap = cf != null; // don't search if we aren't
545                                                // given
546                 // a codon map object
547                 for (int r = 0; foundmap && r < cands.length; r++)
548                 {
549                   if (cands[r].hasMap())
550                   {
551                     if (cands[r].getMap().getTo() != null
552                             && cands[r].getMap().getMap().getFromRatio() != cands[r]
553                                     .getMap().getMap().getToRatio())
554                     {
555                       foundmap = true;
556                       // get sense of map correct for adding to product
557                       // alignment.
558                       if (dna)
559                       {
560                         // map is from dna seq to a protein product
561                         cf.addMap(sequenceI, nxt, cands[r].getMap()
562                                 .getMap());
563                       }
564                       else
565                       {
566                         // map should be from protein seq to its coding dna
567                         cf.addMap(nxt, sequenceI, cands[r].getMap()
568                                 .getMap().getInverse());
569                       }
570                     }
571                   }
572                 }
573                 // TODO: add mapping between sequences if necessary
574                 found = true;
575               }
576             }
577
578           }
579         }
580       }
581     }
582     return found;
583   }
584
585   /**
586    * Returns true if either sequence has a cross-reference to the other
587    * 
588    * @param seq1
589    * @param seq2
590    * @return
591    */
592   public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
593   {
594     return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
595   }
596
597   /**
598    * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
599    * that sequence name is structured as Source|AccessId.
600    * 
601    * @param seq1
602    * @param seq2
603    * @return
604    */
605   public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
606   {
607     if (seq1 == null || seq2 == null)
608     {
609       return false;
610     }
611     String name = seq2.getName();
612     final DBRefEntry[] xrefs = seq1.getDBRef();
613     if (xrefs != null)
614     {
615       for (DBRefEntry xref : xrefs)
616       {
617         String xrefName = xref.getSource() + "|" + xref.getAccessionId();
618         // case-insensitive test, consistent with DBRefEntry.equalRef()
619         if (xrefName.equalsIgnoreCase(name))
620         {
621           return true;
622         }
623       }
624     }
625     return false;
626   }
627
628   /**
629    * precalculate different products that can be found for seqs in dataset and
630    * return them.
631    * 
632    * @param dna
633    * @param seqs
634    * @param dataset
635    * @param fake
636    *          - don't actually build lists - just get types
637    * @return public static Object[] buildXProductsList(boolean dna, SequenceI[]
638    *         seqs, AlignmentI dataset, boolean fake) { String types[] =
639    *         jalview.analysis.CrossRef.findSequenceXrefTypes( dna, seqs,
640    *         dataset); if (types != null) { System.out.println("Xref Types for:
641    *         "+(dna ? "dna" : "prot")); for (int t = 0; t < types.length; t++) {
642    *         System.out.println("Type: " + types[t]); SequenceI[] prod =
643    *         jalview.analysis.CrossRef.findXrefSequences(seqs, dna, types[t]);
644    *         System.out.println("Found " + ((prod == null) ? "no" : "" +
645    *         prod.length) + " products"); if (prod!=null) { for (int p=0;
646    *         p<prod.length; p++) { System.out.println("Prod "+p+":
647    *         "+prod[p].getDisplayId(true)); } } } } else {
648    *         System.out.println("Trying getProducts for
649    *         "+al.getSequenceAt(0).getDisplayId(true));
650    *         System.out.println("Search DS Xref for: "+(dna ? "dna" : "prot"));
651    *         // have a bash at finding the products amongst all the retrieved
652    *         sequences. SequenceI[] prod =
653    *         jalview.analysis.CrossRef.findXrefSequences(al
654    *         .getSequencesArray(), dna, null, ds); System.out.println("Found " +
655    *         ((prod == null) ? "no" : "" + prod.length) + " products"); if
656    *         (prod!=null) { // select non-equivalent sequences from dataset list
657    *         for (int p=0; p<prod.length; p++) { System.out.println("Prod "+p+":
658    *         "+prod[p].getDisplayId(true)); } } } }
659    */
660 }