JAL-2154 ENA specific Ensembl canonical db prefixes
[jalview.git] / src / jalview / util / DBRefUtils.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.util;
22
23 import jalview.datamodel.DBRefEntry;
24 import jalview.datamodel.DBRefSource;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Hashtable;
32 import java.util.List;
33 import java.util.Map;
34
35 import com.stevesoft.pat.Regex;
36
37 /**
38  * Utilities for handling DBRef objects and their collections.
39  */
40 public class DBRefUtils
41 {
42   /*
43    * lookup from lower-case form of a name to its canonical (standardised) form
44    */
45   private static Map<String, String> canonicalSourceNameLookup = new HashMap<String, String>();
46
47   private static Map<String, String> dasCoordinateSystemsLookup = new HashMap<String, String>();
48
49   static
50   {
51     // TODO load these from a resource file?
52     canonicalSourceNameLookup.put("uniprotkb/swiss-prot",
53             DBRefSource.UNIPROT);
54     canonicalSourceNameLookup.put("uniprotkb/trembl", DBRefSource.UNIPROT);
55
56     // Ensembl values for dbname in xref REST service:
57     canonicalSourceNameLookup.put("uniprot/sptrembl", DBRefSource.UNIPROT);
58     canonicalSourceNameLookup.put("uniprot/swissprot", DBRefSource.UNIPROT);
59
60     canonicalSourceNameLookup.put("pdb", DBRefSource.PDB);
61     canonicalSourceNameLookup.put("ensembl", DBRefSource.ENSEMBL);
62     // Ensembl Gn and Tr are for Ensembl genomic and transcript IDs as served
63     // from ENA.
64     canonicalSourceNameLookup.put("ensembl-tr", DBRefSource.ENSEMBL);
65     canonicalSourceNameLookup.put("ensembl-gn", DBRefSource.ENSEMBL);
66
67
68     dasCoordinateSystemsLookup.put("pdbresnum", DBRefSource.PDB);
69     dasCoordinateSystemsLookup.put("uniprot", DBRefSource.UNIPROT);
70     dasCoordinateSystemsLookup.put("embl", DBRefSource.EMBL);
71     // dasCoordinateSystemsLookup.put("embl", DBRefSource.EMBLCDS);
72   }
73
74   /**
75    * Returns those DBRefEntry objects whose source identifier (once converted to
76    * Jalview's canonical form) is in the list of sources to search for. Returns
77    * null if no matches found.
78    * 
79    * @param dbrefs
80    *          DBRefEntry objects to search
81    * @param sources
82    *          array of sources to select
83    * @return
84    */
85   public static DBRefEntry[] selectRefs(DBRefEntry[] dbrefs,
86           String[] sources)
87   {
88     if (dbrefs == null || sources == null)
89     {
90       return dbrefs;
91     }
92     HashSet<String> srcs = new HashSet<String>();
93     for (String src : sources)
94     {
95       srcs.add(src);
96     }
97
98     List<DBRefEntry> res = new ArrayList<DBRefEntry>();
99     for (DBRefEntry dbr : dbrefs)
100     {
101       String source = getCanonicalName(dbr.getSource());
102       if (srcs.contains(source))
103       {
104         res.add(dbr);
105       }
106     }
107
108     if (res.size() > 0)
109     {
110       DBRefEntry[] reply = new DBRefEntry[res.size()];
111       return res.toArray(reply);
112     }
113     return null;
114   }
115
116   /**
117    * isDasCoordinateSystem
118    * 
119    * @param string
120    *          String
121    * @param dBRefEntry
122    *          DBRefEntry
123    * @return boolean true if Source DBRefEntry is compatible with DAS
124    *         CoordinateSystem name
125    */
126
127   public static boolean isDasCoordinateSystem(String string,
128           DBRefEntry dBRefEntry)
129   {
130     if (string == null || dBRefEntry == null)
131     {
132       return false;
133     }
134     String coordsys = dasCoordinateSystemsLookup.get(string.toLowerCase());
135     return coordsys == null ? false : coordsys.equals(dBRefEntry
136             .getSource());
137   }
138
139   /**
140    * look up source in an internal list of database reference sources and return
141    * the canonical jalview name for the source, or the original string if it has
142    * no canonical form.
143    * 
144    * @param source
145    * @return canonical jalview source (one of jalview.datamodel.DBRefSource.*)
146    *         or original source
147    */
148   public static String getCanonicalName(String source)
149   {
150     if (source == null)
151     {
152       return null;
153     }
154     String canonical = canonicalSourceNameLookup.get(source.toLowerCase());
155     return canonical == null ? source : canonical;
156   }
157
158   /**
159    * Returns a (possibly empty) list of those references that match the given
160    * entry. Currently uses a comparator which matches if
161    * <ul>
162    * <li>database sources are the same</li>
163    * <li>accession ids are the same</li>
164    * <li>both have no mapping, or the mappings are the same</li>
165    * </ul>
166    * 
167    * @param ref
168    *          Set of references to search
169    * @param entry
170    *          pattern to match
171    * @return
172    */
173   public static List<DBRefEntry> searchRefs(DBRefEntry[] ref,
174           DBRefEntry entry)
175   {
176     return searchRefs(ref, entry,
177             matchDbAndIdAndEitherMapOrEquivalentMapList);
178   }
179
180   /**
181    * Returns a list of those references that match the given accession id
182    * <ul>
183    * <li>database sources are the same</li>
184    * <li>accession ids are the same</li>
185    * <li>both have no mapping, or the mappings are the same</li>
186    * </ul>
187    * 
188    * @param refs
189    *          Set of references to search
190    * @param accId
191    *          accession id to match
192    * @return
193    */
194   public static List<DBRefEntry> searchRefs(DBRefEntry[] refs, String accId)
195   {
196     return searchRefs(refs, new DBRefEntry("", "", accId), matchId);
197   }
198
199   /**
200    * Returns a (possibly empty) list of those references that match the given
201    * entry, according to the given comparator.
202    * 
203    * @param refs
204    *          an array of database references to search
205    * @param entry
206    *          an entry to compare against
207    * @param comparator
208    * @return
209    */
210   static List<DBRefEntry> searchRefs(DBRefEntry[] refs, DBRefEntry entry,
211           DbRefComp comparator)
212   {
213     List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
214     if (refs == null || entry == null)
215     {
216       return rfs;
217     }
218     for (int i = 0; i < refs.length; i++)
219     {
220       if (comparator.matches(entry, refs[i]))
221       {
222         rfs.add(refs[i]);
223       }
224     }
225     return rfs;
226   }
227
228   interface DbRefComp
229   {
230     public boolean matches(DBRefEntry refa, DBRefEntry refb);
231   }
232
233   /**
234    * match on all non-null fields in refa
235    */
236   // TODO unused - remove?
237   public static DbRefComp matchNonNullonA = new DbRefComp()
238   {
239     @Override
240     public boolean matches(DBRefEntry refa, DBRefEntry refb)
241     {
242       if (refa.getSource() == null
243               || refb.getSource().equals(refa.getSource()))
244       {
245         if (refa.getVersion() == null
246                 || refb.getVersion().equals(refa.getVersion()))
247         {
248           if (refa.getAccessionId() == null
249                   || refb.getAccessionId().equals(refa.getAccessionId()))
250           {
251             if (refa.getMap() == null
252                     || (refb.getMap() != null && refb.getMap().equals(
253                             refa.getMap())))
254             {
255               return true;
256             }
257           }
258         }
259       }
260       return false;
261     }
262   };
263
264   /**
265    * either field is null or field matches for all of source, version, accession
266    * id and map.
267    */
268   // TODO unused - remove?
269   public static DbRefComp matchEitherNonNull = new DbRefComp()
270   {
271     @Override
272     public boolean matches(DBRefEntry refa, DBRefEntry refb)
273     {
274       if (nullOrEqual(refa.getSource(), refb.getSource())
275               && nullOrEqual(refa.getVersion(), refb.getVersion())
276               && nullOrEqual(refa.getAccessionId(), refb.getAccessionId())
277               && nullOrEqual(refa.getMap(), refb.getMap()))
278       {
279         return true;
280       }
281       return false;
282     }
283   };
284
285   /**
286    * accession ID and DB must be identical. Version is ignored. Map is either
287    * not defined or is a match (or is compatible?)
288    */
289   // TODO unused - remove?
290   public static DbRefComp matchDbAndIdAndEitherMap = new DbRefComp()
291   {
292     @Override
293     public boolean matches(DBRefEntry refa, DBRefEntry refb)
294     {
295       if (refa.getSource() != null && refb.getSource() != null
296               && refb.getSource().equals(refa.getSource()))
297       {
298         // We dont care about version
299         if (refa.getAccessionId() != null && refb.getAccessionId() != null
300         // FIXME should be && not || here?
301                 || refb.getAccessionId().equals(refa.getAccessionId()))
302         {
303           if ((refa.getMap() == null || refb.getMap() == null)
304                   || (refa.getMap() != null && refb.getMap() != null && refb
305                           .getMap().equals(refa.getMap())))
306           {
307             return true;
308           }
309         }
310       }
311       return false;
312     }
313   };
314
315   /**
316    * accession ID and DB must be identical. Version is ignored. No map on either
317    * or map but no maplist on either or maplist of map on a is the complement of
318    * maplist of map on b.
319    */
320   // TODO unused - remove?
321   public static DbRefComp matchDbAndIdAndComplementaryMapList = new DbRefComp()
322   {
323     @Override
324     public boolean matches(DBRefEntry refa, DBRefEntry refb)
325     {
326       if (refa.getSource() != null && refb.getSource() != null
327               && refb.getSource().equals(refa.getSource()))
328       {
329         // We dont care about version
330         if (refa.getAccessionId() != null && refb.getAccessionId() != null
331                 || refb.getAccessionId().equals(refa.getAccessionId()))
332         {
333           if ((refa.getMap() == null && refb.getMap() == null)
334                   || (refa.getMap() != null && refb.getMap() != null))
335           {
336             if ((refb.getMap().getMap() == null && refa.getMap().getMap() == null)
337                     || (refb.getMap().getMap() != null
338                             && refa.getMap().getMap() != null && refb
339                             .getMap().getMap().getInverse()
340                             .equals(refa.getMap().getMap())))
341             {
342               return true;
343             }
344           }
345         }
346       }
347       return false;
348     }
349   };
350
351   /**
352    * accession ID and DB must be identical. Version is ignored. No map on both
353    * or or map but no maplist on either or maplist of map on a is equivalent to
354    * the maplist of map on b.
355    */
356   // TODO unused - remove?
357   public static DbRefComp matchDbAndIdAndEquivalentMapList = new DbRefComp()
358   {
359     @Override
360     public boolean matches(DBRefEntry refa, DBRefEntry refb)
361     {
362       if (refa.getSource() != null && refb.getSource() != null
363               && refb.getSource().equals(refa.getSource()))
364       {
365         // We dont care about version
366         // if ((refa.getVersion()==null || refb.getVersion()==null)
367         // || refb.getVersion().equals(refa.getVersion()))
368         // {
369         if (refa.getAccessionId() != null && refb.getAccessionId() != null
370                 || refb.getAccessionId().equals(refa.getAccessionId()))
371         {
372           if (refa.getMap() == null && refb.getMap() == null)
373           {
374             return true;
375           }
376           if (refa.getMap() != null
377                   && refb.getMap() != null
378                   && ((refb.getMap().getMap() == null && refa.getMap()
379                           .getMap() == null) || (refb.getMap().getMap() != null
380                           && refa.getMap().getMap() != null && refb
381                           .getMap().getMap().equals(refa.getMap().getMap()))))
382           {
383             return true;
384           }
385         }
386       }
387       return false;
388     }
389   };
390
391   /**
392    * accession ID and DB must be identical, or null on a. Version is ignored. No
393    * map on either or map but no maplist on either or maplist of map on a is
394    * equivalent to the maplist of map on b.
395    */
396   public static DbRefComp matchDbAndIdAndEitherMapOrEquivalentMapList = new DbRefComp()
397   {
398     @Override
399     public boolean matches(DBRefEntry refa, DBRefEntry refb)
400     {
401       if (refa.getSource() != null && refb.getSource() != null
402               && refb.getSource().equals(refa.getSource()))
403       {
404         // We dont care about version
405
406         if (refa.getAccessionId() == null
407                 || refa.getAccessionId().equals(refb.getAccessionId()))
408         {
409           if (refa.getMap() == null || refb.getMap() == null)
410           {
411             return true;
412           }
413           if ((refa.getMap() != null && refb.getMap() != null)
414                   && (refb.getMap().getMap() == null && refa.getMap()
415                           .getMap() == null)
416                   || (refb.getMap().getMap() != null
417                           && refa.getMap().getMap() != null && (refb
418                           .getMap().getMap().equals(refa.getMap().getMap()))))
419           {
420             return true;
421           }
422         }
423       }
424       return false;
425     }
426   };
427
428   /**
429    * accession ID only must be identical.
430    */
431   public static DbRefComp matchId = new DbRefComp()
432   {
433     @Override
434     public boolean matches(DBRefEntry refa, DBRefEntry refb)
435     {
436       if (refa.getAccessionId() != null && refb.getAccessionId() != null
437               && refb.getAccessionId().equals(refa.getAccessionId()))
438       {
439         return true;
440       }
441       return false;
442     }
443   };
444
445   /**
446    * Parses a DBRefEntry and adds it to the sequence, also a PDBEntry if the
447    * database is PDB.
448    * <p>
449    * Used by file parsers to generate DBRefs from annotation within file (eg
450    * Stockholm)
451    * 
452    * @param dbname
453    * @param version
454    * @param acn
455    * @param seq
456    *          where to annotate with reference
457    * @return parsed version of entry that was added to seq (if any)
458    */
459   public static DBRefEntry parseToDbRef(SequenceI seq, String dbname,
460           String version, String acn)
461   {
462     DBRefEntry ref = null;
463     if (dbname != null)
464     {
465       String locsrc = DBRefUtils.getCanonicalName(dbname);
466       if (locsrc.equals(DBRefSource.PDB))
467       {
468         /*
469          * Check for PFAM style stockhom PDB accession id citation e.g.
470          * "1WRI A; 7-80;"
471          */
472         Regex r = new com.stevesoft.pat.Regex(
473                 "([0-9][0-9A-Za-z]{3})\\s*(.?)\\s*;\\s*([0-9]+)-([0-9]+)");
474         if (r.search(acn.trim()))
475         {
476           String pdbid = r.stringMatched(1);
477           String chaincode = r.stringMatched(2);
478           if (chaincode == null)
479           {
480             chaincode = " ";
481           }
482           // String mapstart = r.stringMatched(3);
483           // String mapend = r.stringMatched(4);
484           if (chaincode.equals(" "))
485           {
486             chaincode = "_";
487           }
488           // construct pdb ref.
489           ref = new DBRefEntry(locsrc, version, pdbid + chaincode);
490           PDBEntry pdbr = new PDBEntry();
491           pdbr.setId(pdbid);
492           pdbr.setType(PDBEntry.Type.PDB);
493           pdbr.setProperty(new Hashtable());
494           pdbr.setChainCode(chaincode);
495           // pdbr.getProperty().put("CHAIN", chaincode);
496           seq.addPDBId(pdbr);
497         }
498         else
499         {
500           System.err.println("Malformed PDB DR line:" + acn);
501         }
502       }
503       else
504       {
505         // default:
506         ref = new DBRefEntry(locsrc, version, acn);
507       }
508     }
509     if (ref != null)
510     {
511       seq.addDBRef(ref);
512     }
513     return ref;
514   }
515
516   /**
517    * Returns true if either object is null, or they are equal
518    * 
519    * @param o1
520    * @param o2
521    * @return
522    */
523   public static boolean nullOrEqual(Object o1, Object o2)
524   {
525     if (o1 == null || o2 == null)
526     {
527       return true;
528     }
529     return (o1 == null ? o2.equals(o1) : o1.equals(o2));
530   }
531
532   /**
533    * Selects just the DNA or protein references from a set of references
534    * 
535    * @param selectDna
536    *          if true, select references to 'standard' DNA databases, else to
537    *          'standard' peptide databases
538    * @param refs
539    *          a set of references to select from
540    * @return
541    */
542   public static DBRefEntry[] selectDbRefs(boolean selectDna,
543           DBRefEntry[] refs)
544   {
545     return selectRefs(refs, selectDna ? DBRefSource.DNACODINGDBS
546             : DBRefSource.PROTEINDBS);
547     // could attempt to find other cross
548     // refs here - ie PDB xrefs
549     // (not dna, not protein seq)
550   }
551
552   /**
553    * Returns the (possibly empty) list of those supplied dbrefs which have the
554    * specified source database, with a case-insensitive match of source name
555    * 
556    * @param dbRefs
557    * @param source
558    * @return
559    */
560   public static List<DBRefEntry> searchRefsForSource(DBRefEntry[] dbRefs,
561           String source)
562   {
563     List<DBRefEntry> matches = new ArrayList<DBRefEntry>();
564     if (dbRefs != null && source != null)
565     {
566       for (DBRefEntry dbref : dbRefs)
567       {
568         if (source.equalsIgnoreCase(dbref.getSource()))
569         {
570           matches.add(dbref);
571         }
572       }
573     }
574     return matches;
575   }
576
577 }