JAL-2110 work in progress
[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.Mapping;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.util.Comparison;
32 import jalview.util.DBRefUtils;
33 import jalview.util.MapList;
34 import jalview.ws.SequenceFetcherFactory;
35 import jalview.ws.seqfetcher.ASequenceFetcher;
36
37 import java.util.ArrayList;
38 import java.util.Iterator;
39 import java.util.List;
40
41 /**
42  * Functions for cross-referencing sequence databases.
43  * 
44  * @author JimP
45  * 
46  */
47 public class CrossRef
48 {
49   /*
50    * the dataset of the alignment for which we are searching for 
51    * cross-references; in some cases we may resolve xrefs by 
52    * searching in the dataset
53    */
54   private AlignmentI dataset;
55
56   /*
57    * true if we are searching for cross-references from nucleotide,
58    * i.e. for protein sequences, false if the reverse
59    */
60   private boolean fromDna;
61
62   /*
63    * the sequences for which we are seeking cross-references
64    */
65   private SequenceI[] fromSeqs;
66
67   /**
68    * Constructor
69    * 
70    * @param seqs
71    *          the sequences for which we are seeking cross-references
72    * @param ds
73    *          the containing alignment dataset (may be searched to resolve
74    *          cross-references)
75    */
76   public CrossRef(SequenceI[] seqs, AlignmentI ds)
77   {
78     fromSeqs = seqs;
79     fromDna = ds.isNucleotide();
80     dataset = ds.getDataset() == null ? ds : ds.getDataset();
81   }
82
83   /**
84    * Returns a list of distinct database sources for which sequences have either
85    * <ul>
86    * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
87    * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
88    * reference from another sequence in the dataset which has a cross-reference
89    * to a direct DBRefEntry on the given sequence</li>
90    * </ul>
91    * @return
92    */
93   public List<String> findXrefSourcesForSequences()
94   {
95     List<String> sources = new ArrayList<String>();
96     for (SequenceI seq : fromSeqs)
97     {
98       if (seq != null)
99       {
100         findXrefSourcesForSequence(seq, sources);
101       }
102     }
103     return sources;
104   }
105
106   /**
107    * Returns a list of distinct database sources for which a sequence has either
108    * <ul>
109    * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
110    * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
111    * reference from another sequence in the dataset which has a cross-reference
112    * to a direct DBRefEntry on the given sequence</li>
113    * </ul>
114    * 
115    * @param seq
116    *          the sequence whose dbrefs we are searching against
117    * @param sources
118    *          a list of sources to add matches to
119    */
120   void findXrefSourcesForSequence(SequenceI seq, List<String> sources)
121   {
122     /*
123      * first find seq's xrefs (dna-to-peptide or peptide-to-dna)
124      */
125     DBRefEntry[] rfs = DBRefUtils.selectDbRefs(!fromDna, seq.getDBRefs());
126     addXrefsToSources(rfs, sources);
127     if (dataset != null)
128     {
129       /*
130        * find sequence's direct (dna-to-dna, peptide-to-peptide) xrefs
131        */
132       DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna, seq.getDBRefs());
133       List<SequenceI> rseqs = new ArrayList<SequenceI>();
134
135       /*
136        * find sequences in the alignment which xref one of these DBRefs
137        * i.e. is xref-ed to a common sequence identifier
138        */
139       searchDatasetXrefs(seq, lrfs, rseqs, null);
140
141       /*
142        * add those sequences' (dna-to-peptide or peptide-to-dna) dbref sources
143        */
144       for (SequenceI rs : rseqs)
145       {
146         DBRefEntry[] xrs = DBRefUtils
147                 .selectDbRefs(!fromDna, rs.getDBRefs());
148         addXrefsToSources(xrs, sources);
149       }
150     }
151   }
152
153   /**
154    * Helper method that adds the source identifiers of some cross-references to
155    * a (non-redundant) list of database sources
156    * 
157    * @param xrefs
158    * @param sources
159    */
160   void addXrefsToSources(DBRefEntry[] xrefs, List<String> sources)
161   {
162     if (xrefs != null)
163     {
164       for (DBRefEntry ref : xrefs)
165       {
166         String source = ref.getSource();
167         if (!sources.contains(source))
168         {
169           sources.add(source);
170         }
171       }
172     }
173   }
174
175   /**
176    * 
177    * @param seqs
178    *          sequences whose xrefs are being retrieved
179    * @param dna
180    *          true if sequences are nucleotide
181    * @param source
182    * @param al
183    *          alignment to search for cross-referenced sequences (and possibly
184    *          add to)
185    * @return products (as dataset sequences)
186    */
187   public Alignment findXrefSequences(String source)
188   {
189     List<SequenceI> rseqs = new ArrayList<SequenceI>();
190     AlignedCodonFrame cf = new AlignedCodonFrame();
191     SequenceIdMatcher matcher = new SequenceIdMatcher(
192             dataset.getSequences());
193
194     for (SequenceI seq : fromSeqs)
195     {
196       SequenceI dss = seq;
197       while (dss.getDatasetSequence() != null)
198       {
199         dss = dss.getDatasetSequence();
200       }
201       boolean found = false;
202       DBRefEntry[] xrfs = DBRefUtils
203               .selectDbRefs(!fromDna, dss.getDBRefs());
204       if ((xrfs == null || xrfs.length == 0) && dataset != null)
205       {
206         /*
207          * found no suitable dbrefs on sequence - look for sequences in the
208          * alignment which share a dbref with this one
209          */
210         DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna,
211                 seq.getDBRefs());
212
213         /*
214          * find sequences (except this one!), of complementary type,
215          *  which have a dbref to an accession id for this sequence,
216          *  and add them to the results
217          */
218         found = searchDatasetXrefs(dss, lrfs, rseqs, cf);
219       }
220       if (xrfs == null && !found)
221       {
222         /*
223          * no dbref to source on this sequence or matched
224          * complementary sequence in the dataset 
225          */
226         continue;
227       }
228       List<DBRefEntry> sourceRefs = DBRefUtils.searchRefsForSource(xrfs,
229               source);
230       Iterator<DBRefEntry> refIterator = sourceRefs.iterator();
231       while (refIterator.hasNext())
232       {
233         DBRefEntry xref = refIterator.next();
234         found = false;
235         if (xref.hasMap())
236         {
237           SequenceI mappedTo = xref.getMap().getTo();
238           if (mappedTo != null)
239           {
240             /*
241              * dbref contains the sequence it maps to; add it to the
242              * results unless we have done so already (could happen if 
243              * fetching xrefs for sequences which have xrefs in common)
244              * for example: UNIPROT {P0CE19, P0CE20} -> EMBL {J03321, X06707}
245              */
246             found = true;
247             SequenceI matchInDataset = findInDataset(mappedTo);// matcher.findIdMatch(mappedTo);
248             if (matchInDataset != null)
249             {
250               if (!rseqs.contains(matchInDataset))
251               {
252                 rseqs.add(matchInDataset);
253               }
254               continue;
255             }
256             SequenceI rsq = new Sequence(mappedTo);
257             rseqs.add(rsq);
258             if (xref.getMap().getMap().getFromRatio() != xref.getMap()
259                     .getMap().getToRatio())
260             {
261               // get sense of map correct for adding to product alignment.
262               if (fromDna)
263               {
264                 // map is from dna seq to a protein product
265                 cf.addMap(dss, rsq, xref.getMap().getMap());
266               }
267               else
268               {
269                 // map should be from protein seq to its coding dna
270                 cf.addMap(rsq, dss, xref.getMap().getMap().getInverse());
271               }
272             }
273           }
274         }
275
276         if (!found)
277         {
278           SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
279                   + xref.getAccessionId());
280           if (matchedSeq != null)
281           {
282             if (constructMapping(seq, matchedSeq, xref, cf))
283             {
284               found = true;
285             }
286           }
287         }
288
289         if (!found)
290         {
291           // do a bit more work - search for sequences with references matching
292           // xrefs on this sequence.
293           found = searchDataset(dss, xref, rseqs, cf, false);
294         }
295         if (found)
296         {
297           refIterator.remove();
298         }
299       }
300
301       /*
302        * fetch from source database any dbrefs we haven't resolved up to here
303        */
304       if (!sourceRefs.isEmpty())
305       {
306         ASequenceFetcher sftch = SequenceFetcherFactory
307                 .getSequenceFetcher();
308         SequenceI[] retrieved = null;
309         try
310         {
311           retrieved = sftch.getSequences(sourceRefs, !fromDna);
312         } catch (Exception e)
313         {
314           System.err
315                   .println("Problem whilst retrieving cross references for Sequence : "
316                           + seq.getName());
317           e.printStackTrace();
318         }
319
320         if (retrieved != null)
321         {
322           updateDbrefMappings(seq, xrfs, retrieved, cf);
323           for (SequenceI retrievedSequence : retrieved)
324           {
325             SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
326                     : retrievedSequence.getDatasetSequence();
327             DBRefEntry[] dbr = retrievedSequence.getDBRefs();
328             if (dbr != null)
329             {
330               for (DBRefEntry dbref : dbr)
331               {
332                 // find any entry where we should put in the sequence being
333                 // cross-referenced into the map
334                 Mapping map = dbref.getMap();
335                 if (map != null)
336                 {
337                   if (map.getTo() != null && map.getMap() != null)
338                   {
339                     // TODO findInDataset requires exact sequence match but
340                     // 'congruent' test only for the mapped part
341                     SequenceI matched = findInDataset(map.getTo());// matcher.findIdMatch(map.getTo());
342                     if (matched != null)
343                     {
344                       /*
345                        * already got an xref to this sequence; update this
346                        * map to point to the same sequence, and add
347                        * any new dbrefs to it
348                        */
349                       DBRefEntry[] toRefs = map.getTo().getDBRefs();
350                       if (toRefs != null)
351                       {
352                         for (DBRefEntry ref : toRefs)
353                         {
354                           matched.addDBRef(ref); // add or update mapping
355                         }
356                       }
357                       map.setTo(matched);
358                     }
359                     else
360                     {
361                       matcher.add(map.getTo());
362                     }
363                     try
364                     {
365                       // compare ms with dss and replace with dss in mapping
366                       // if map is congruent
367                       SequenceI ms = map.getTo();
368                       int sf = map.getMap().getToLowest();
369                       int st = map.getMap().getToHighest();
370                       SequenceI mappedrg = ms.getSubSequence(sf, st);
371                       // SequenceI loc = dss.getSubSequence(sf, st);
372                       if (mappedrg.getLength() > 0
373                               && ms.getSequenceAsString().equals(
374                                       dss.getSequenceAsString()))
375                       // && mappedrg.getSequenceAsString().equals(
376                       // loc.getSequenceAsString()))
377                       {
378                         String msg = "Mapping updated from " + ms.getName()
379                                 + " to retrieved crossreference "
380                                 + dss.getName();
381                         System.out.println(msg);
382                         // method to update all refs of existing To on
383                         // retrieved sequence with dss and merge any props
384                         // on To onto dss.
385                         // TODO don't we have to change the mapped to ranges
386                         // if not to the whole sequence?
387                         map.setTo(dss);
388                         /*
389                          * copy sequence features as well, avoiding
390                          * duplication (e.g. same variation from 2 
391                          * transcripts)
392                          */
393                         SequenceFeature[] sfs = ms.getSequenceFeatures();
394                         if (sfs != null)
395                         {
396                           for (SequenceFeature feat : sfs)
397                           {
398                             /*
399                              * make a flyweight feature object which ignores Parent
400                              * attribute in equality test, to avoid creating many
401                              * otherwise duplicate exon features on genomic sequence
402                              */
403                             SequenceFeature newFeature = new SequenceFeature(
404                                     feat)
405                             {
406                               @Override
407                               public boolean equals(Object o)
408                               {
409                                 return super.equals(o, true);
410                               }
411                             };
412                             dss.addSequenceFeature(newFeature);
413                           }
414                         }
415                       }
416                       cf.addMap(retrievedDss, map.getTo(), map.getMap());
417                     } catch (Exception e)
418                     {
419                       System.err
420                               .println("Exception when consolidating Mapped sequence set...");
421                       e.printStackTrace(System.err);
422                     }
423                   }
424                 }
425               }
426             }
427             retrievedSequence.updatePDBIds();
428             rseqs.add(retrievedSequence);
429             dataset.addSequence(retrievedDss);
430             matcher.add(retrievedSequence);
431           }
432         }
433       }
434     }
435
436     Alignment ral = null;
437     if (rseqs.size() > 0)
438     {
439       ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
440       if (cf != null && !cf.isEmpty())
441       {
442         ral.addCodonFrame(cf);
443       }
444     }
445     return ral;
446   }
447
448   /**
449    * Returns the first identical sequence in the dataset if any, else null
450    * 
451    * @param mappedTo
452    * @return
453    */
454   SequenceI findInDataset(SequenceI mappedTo)
455   {
456     if (mappedTo == null)
457     {
458       return null;
459     }
460     SequenceI dss = mappedTo.getDatasetSequence() == null ? mappedTo
461             : mappedTo.getDatasetSequence();
462     for (SequenceI seq : dataset.getSequences())
463     {
464       if (sameSequence(seq, dss))
465       {
466         return seq;
467       }
468     }
469     return null;
470   }
471
472   /**
473    * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
474    * case), else false. This method compares the lengths, then each character in
475    * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
476    * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
477    * 
478    * @param seq1
479    * @param seq2
480    * @return
481    */
482   // TODO move to Sequence / SequenceI
483   static boolean sameSequence(SequenceI seq1, SequenceI seq2)
484   {
485     if (seq1 == seq2)
486     {
487       return true;
488     }
489     if (seq1 == null || seq2 == null)
490     {
491       return false;
492     }
493     char[] c1 = seq1.getSequence();
494     char[] c2 = seq2.getSequence();
495     if (c1.length != c2.length)
496     {
497       return false;
498     }
499     for (int i = 0; i < c1.length; i++)
500     {
501       int diff = c1[i] - c2[i];
502       /*
503        * same char or differ in case only ('a'-'A' == 32)
504        */
505       if (diff != 0 && diff != 32 && diff != -32)
506       {
507         return false;
508       }
509     }
510     return true;
511   }
512
513   /**
514    * Updates any empty mappings in the cross-references with one to a compatible
515    * retrieved sequence if found, and adds any new mappings to the
516    * AlignedCodonFrame
517    * 
518    * @param mapFrom
519    * @param xrefs
520    * @param retrieved
521    * @param acf
522    */
523   void updateDbrefMappings(SequenceI mapFrom,
524           DBRefEntry[] xrefs, SequenceI[] retrieved, AlignedCodonFrame acf)
525   {
526     SequenceIdMatcher matcher = new SequenceIdMatcher(retrieved);
527     for (DBRefEntry xref : xrefs)
528     {
529       if (!xref.hasMap())
530       {
531         String targetSeqName = xref.getSource() + "|"
532                 + xref.getAccessionId();
533         SequenceI[] matches = matcher.findAllIdMatches(targetSeqName);
534         if (matches == null)
535         {
536           return;
537         }
538         for (SequenceI seq : matches)
539         {
540           constructMapping(mapFrom, seq, xref, acf);
541         }
542       }
543     }
544   }
545
546   /**
547    * Tries to make a mapping from dna to protein. If successful, adds the
548    * mapping to the dbref and the mappings collection and answers true,
549    * otherwise answers false.
550    * 
551    * @param mapFrom
552    * @param mapTo
553    * @param xref
554    * @param mappings
555    * @return
556    */
557   boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
558           DBRefEntry xref, AlignedCodonFrame mappings)
559   {
560     MapList mapping = null;
561     if (fromDna)
562     {
563       mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
564     }
565     else
566     {
567       mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
568       if (mapping != null)
569       {
570         mapping = mapping.getInverse();
571       }
572     }
573     if (mapping == null)
574     {
575       return false;
576     }
577     xref.setMap(new Mapping(mapTo, mapping));
578     if (fromDna)
579     {
580       AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
581       mappings.addMap(mapFrom, mapTo, mapping);
582     }
583     else
584     {
585       mappings.addMap(mapTo, mapFrom, mapping.getInverse());
586     }
587
588     return true;
589   }
590
591   /**
592    * find references to lrfs in the cross-reference set of each sequence in
593    * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
594    * based on source and accession string only - Map and Version are nulled.
595    * 
596    * @param sequenceI
597    * @param lrfs
598    * @param rseqs
599    * @return true if matches were found.
600    */
601   private boolean searchDatasetXrefs(SequenceI sequenceI,
602           DBRefEntry[] lrfs, List<SequenceI> rseqs, AlignedCodonFrame cf)
603   {
604     boolean found = false;
605     if (lrfs == null)
606     {
607       return false;
608     }
609     for (int i = 0; i < lrfs.length; i++)
610     {
611       DBRefEntry xref = new DBRefEntry(lrfs[i]);
612       // add in wildcards
613       xref.setVersion(null);
614       xref.setMap(null);
615       found |= searchDataset(sequenceI, xref, rseqs, cf, false);
616     }
617     return found;
618   }
619
620   /**
621    * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
622    * associated sequence to rseqs
623    * 
624    * @param sequenceI
625    *          a sequence to ignore (start point of search)
626    * @param xrf
627    *          a cross-reference to try to match
628    * @param rseqs
629    *          result list to add to
630    * @param cf
631    *          a set of sequence mappings to add to
632    * @param direct
633    *          - search all references or only subset
634    * @return true if relationship found and sequence added.
635    */
636   boolean searchDataset(SequenceI sequenceI, DBRefEntry xrf,
637           List<SequenceI> rseqs, AlignedCodonFrame cf, boolean direct)
638   {
639     boolean found = false;
640     if (dataset == null)
641     {
642       return false;
643     }
644     if (dataset.getSequences() == null)
645     {
646       System.err.println("Empty dataset sequence set - NO VECTOR");
647       return false;
648     }
649     List<SequenceI> ds;
650     synchronized (ds = dataset.getSequences())
651     {
652       for (SequenceI nxt : ds)
653       {
654         if (nxt != null)
655         {
656           if (nxt.getDatasetSequence() != null)
657           {
658             System.err
659                     .println("Implementation warning: getProducts passed a dataset alignment without dataset sequences in it!");
660           }
661           if (nxt == sequenceI || nxt == sequenceI.getDatasetSequence())
662           {
663             continue;
664           }
665           /*
666            * only look at same molecule type if 'direct', or
667            * complementary type if !direct
668            */
669           {
670             boolean isDna = Comparison
671                     .isNucleotide(new SequenceI[] { nxt });
672             if (direct ? (isDna != fromDna) : (isDna == fromDna))
673             {
674               // skip this sequence because it is wrong molecule type
675               continue;
676             }
677           }
678
679           // look for direct or indirect references in common
680           DBRefEntry[] poss = nxt.getDBRefs();
681           List<DBRefEntry> cands = null;
682           /*
683            * TODO does this make any sense?
684            * if 'direct', search the dbrefs for xrf
685            * else, filter the dbrefs by type and then search for xrf
686            * - the result is the same isn't it?
687            */
688           if (direct)
689           {
690             cands = DBRefUtils.searchRefs(poss, xrf);
691           }
692           else
693           {
694             poss = DBRefUtils.selectDbRefs(!fromDna, poss);
695             cands = DBRefUtils.searchRefs(poss, xrf);
696           }
697           if (!cands.isEmpty())
698           {
699             if (!rseqs.contains(nxt))
700             {
701               found = true;
702               rseqs.add(nxt);
703               if (cf != null)
704               {
705                 // don't search if we aren't given a codon map object
706                 for (DBRefEntry candidate : cands)
707                 {
708                   Mapping mapping = candidate.getMap();
709                   if (mapping != null)
710                   {
711                     MapList map = mapping.getMap();
712                     if (mapping.getTo() != null
713                             && map.getFromRatio() != map.getToRatio())
714                     {
715                       // get sense of map correct for adding to product
716                       // alignment.
717                       if (fromDna)
718                       {
719                         // map is from dna seq to a protein product
720                         cf.addMap(sequenceI, nxt, map);
721                       }
722                       else
723                       {
724                         // map should be from protein seq to its coding dna
725                         cf.addMap(nxt, sequenceI, map.getInverse());
726                       }
727                     }
728                   }
729                 }
730               }
731               // TODO: add mapping between sequences if necessary
732             }
733           }
734         }
735       }
736     }
737     return found;
738   }
739 }