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