0349ff260c7388ca70f2050e8cc9f705a0a845df
[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.Hashtable;
31 import java.util.List;
32 import java.util.Map;
33
34 import com.stevesoft.pat.Regex;
35
36 public class DBRefUtils
37 {
38   private static Map<String, String> canonicalSourceNameLookup = new HashMap<String, String>();
39
40   private static Map<String, String> dasCoordinateSystemsLookup = new HashMap<String, String>();
41
42   static
43   {
44     // TODO load these from a resource file?
45     canonicalSourceNameLookup.put("uniprotkb/swiss-prot",
46             DBRefSource.UNIPROT);
47     canonicalSourceNameLookup.put("uniprotkb/trembl", DBRefSource.UNIPROT);
48     canonicalSourceNameLookup.put("pdb", DBRefSource.PDB);
49
50     dasCoordinateSystemsLookup.put("pdbresnum", DBRefSource.PDB);
51     dasCoordinateSystemsLookup.put("uniprot", DBRefSource.UNIPROT);
52     dasCoordinateSystemsLookup.put("embl", DBRefSource.EMBL);
53     // dasCoordinateSystemsLookup.put("embl", DBRefSource.EMBLCDS);
54   }
55
56   /**
57    * Utilities for handling DBRef objects and their collections.
58    */
59   /**
60    * 
61    * @param dbrefs
62    *          Vector of DBRef objects to search
63    * @param sources
64    *          String[] array of source DBRef IDs to retrieve
65    * @return Vector
66    */
67   public static DBRefEntry[] selectRefs(DBRefEntry[] dbrefs,
68           String[] sources)
69   {
70     if (dbrefs == null)
71     {
72       return null;
73     }
74     if (sources == null)
75     {
76       return dbrefs;
77     }
78     Map<String, Integer> srcs = new HashMap<String, Integer>();
79     ArrayList<DBRefEntry> res = new ArrayList<DBRefEntry>();
80
81     for (int i = 0; i < sources.length; i++)
82     {
83       srcs.put(new String(sources[i]), new Integer(i));
84     }
85     for (int i = 0, j = dbrefs.length; i < j; i++)
86     {
87       if (srcs.containsKey(dbrefs[i].getSource()))
88       {
89         res.add(dbrefs[i]);
90       }
91     }
92
93     if (res.size() > 0)
94     {
95       DBRefEntry[] reply = new DBRefEntry[res.size()];
96       return res.toArray(reply);
97     }
98     res = null;
99     // there are probable memory leaks in the hashtable!
100     return null;
101   }
102
103   /**
104    * isDasCoordinateSystem
105    * 
106    * @param string
107    *          String
108    * @param dBRefEntry
109    *          DBRefEntry
110    * @return boolean true if Source DBRefEntry is compatible with DAS
111    *         CoordinateSystem name
112    */
113
114   public static boolean isDasCoordinateSystem(String string,
115           DBRefEntry dBRefEntry)
116   {
117     if (string == null || dBRefEntry == null)
118     {
119       return false;
120     }
121     String coordsys = dasCoordinateSystemsLookup.get(string
122             .toLowerCase());
123     return coordsys == null ? false : coordsys.equals(dBRefEntry
124             .getSource());
125   }
126
127   /**
128    * look up source in an internal list of database reference sources and return
129    * the canonical jalview name for the source, or the original string if it has
130    * no canonical form.
131    * 
132    * @param source
133    * @return canonical jalview source (one of jalview.datamodel.DBRefSource.*)
134    *         or original source
135    */
136   public static String getCanonicalName(String source)
137   {
138     if (source == null)
139     {
140       return null;
141     }
142     String canonical = canonicalSourceNameLookup.get(source
143             .toLowerCase());
144     return canonical == null ? source : canonical;
145   }
146
147   /**
148    * Returns an array of those references that match the given entry, or null if
149    * no matches. Currently uses a comparator which matches if
150    * <ul>
151    * <li>database sources are the same</li>
152    * <li>accession ids are the same</li>
153    * <li>both have no mapping, or the mappings are the same</li>
154    * </ul>
155    * 
156    * @param ref
157    *          Set of references to search
158    * @param entry
159    *          pattern to match
160    * @return
161    */
162   public static DBRefEntry[] searchRefs(DBRefEntry[] ref, DBRefEntry entry)
163   {
164     return searchRefs(ref, entry,
165             matchDbAndIdAndEitherMapOrEquivalentMapList);
166   }
167
168   /**
169    * Returns an array of those references that match the given entry, according
170    * to the given comparator. Returns null if no matches.
171    * 
172    * @param refs
173    *          an array of database references to search
174    * @param entry
175    *          an entry to compare against
176    * @param comparator
177    * @return
178    */
179   static DBRefEntry[] searchRefs(DBRefEntry[] refs, DBRefEntry entry,
180           DbRefComp comparator)
181   {
182     if (refs == null || entry == null)
183     {
184       return null;
185     }
186     List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
187     for (int i = 0; i < refs.length; i++)
188     {
189       if (comparator.matches(entry, refs[i]))
190       {
191         rfs.add(refs[i]);
192       }
193     }
194     return rfs.size() == 0 ? null : rfs.toArray(new DBRefEntry[rfs.size()]);
195   }
196
197   interface DbRefComp
198   {
199     public boolean matches(DBRefEntry refa, DBRefEntry refb);
200   }
201
202   /**
203    * match on all non-null fields in refa
204    */
205   public static DbRefComp matchNonNullonA = new DbRefComp()
206   {
207     public boolean matches(DBRefEntry refa, DBRefEntry refb)
208     {
209       if (refa.getSource() == null
210               || refb.getSource().equals(refa.getSource()))
211       {
212         if (refa.getVersion() == null
213                 || refb.getVersion().equals(refa.getVersion()))
214         {
215           if (refa.getAccessionId() == null
216                   || refb.getAccessionId().equals(refa.getAccessionId()))
217           {
218             if (refa.getMap() == null
219                     || (refb.getMap() != null && refb.getMap().equals(
220                             refa.getMap())))
221             {
222               return true;
223             }
224           }
225         }
226       }
227       return false;
228     }
229   };
230
231   /**
232    * either field is null or field matches for all of source, version, accession
233    * id and map.
234    */
235   public static DbRefComp matchEitherNonNull = new DbRefComp()
236   {
237     public boolean matches(DBRefEntry refa, DBRefEntry refb)
238     {
239       if ((refa.getSource() == null || refb.getSource() == null)
240               || refb.getSource().equals(refa.getSource()))
241       {
242         if ((refa.getVersion() == null || refb.getVersion() == null)
243                 || refb.getVersion().equals(refa.getVersion()))
244         {
245           if ((refa.getAccessionId() == null || refb.getAccessionId() == null)
246                   || refb.getAccessionId().equals(refa.getAccessionId()))
247           {
248             if ((refa.getMap() == null || refb.getMap() == null)
249                     || (refb.getMap() != null && refb.getMap().equals(
250                             refa.getMap())))
251             {
252               return true;
253             }
254           }
255         }
256       }
257       return false;
258     }
259   };
260
261   /**
262    * accession ID and DB must be identical. Version is ignored. Map is either
263    * not defined or is a match (or is compatible?)
264    */
265   public static DbRefComp matchDbAndIdAndEitherMap = new DbRefComp()
266   {
267     public boolean matches(DBRefEntry refa, DBRefEntry refb)
268     {
269       if (refa.getSource() != null && refb.getSource() != null
270               && refb.getSource().equals(refa.getSource()))
271       {
272         // We dont care about version
273         // if ((refa.getVersion()==null || refb.getVersion()==null)
274         // || refb.getVersion().equals(refa.getVersion()))
275         // {
276         if (refa.getAccessionId() != null && refb.getAccessionId() != null
277                 || refb.getAccessionId().equals(refa.getAccessionId()))
278         {
279           if ((refa.getMap() == null || refb.getMap() == null)
280                   || (refa.getMap() != null && refb.getMap() != null && refb
281                           .getMap().equals(refa.getMap())))
282           {
283             return true;
284           }
285         }
286       }
287       return false;
288     }
289   };
290
291   /**
292    * accession ID and DB must be identical. Version is ignored. No map on either
293    * or map but no maplist on either or maplist of map on a is the complement of
294    * maplist of map on b.
295    */
296   public static DbRefComp matchDbAndIdAndComplementaryMapList = new DbRefComp()
297   {
298     public boolean matches(DBRefEntry refa, DBRefEntry refb)
299     {
300       if (refa.getSource() != null && refb.getSource() != null
301               && refb.getSource().equals(refa.getSource()))
302       {
303         // We dont care about version
304         // if ((refa.getVersion()==null || refb.getVersion()==null)
305         // || refb.getVersion().equals(refa.getVersion()))
306         // {
307         if (refa.getAccessionId() != null && refb.getAccessionId() != null
308                 || refb.getAccessionId().equals(refa.getAccessionId()))
309         {
310           if ((refa.getMap() == null && refb.getMap() == null)
311                   || (refa.getMap() != null && refb.getMap() != null))
312           {
313             if ((refb.getMap().getMap() == null && refa.getMap().getMap() == null)
314                     || (refb.getMap().getMap() != null
315                             && refa.getMap().getMap() != null && refb
316                             .getMap().getMap().getInverse()
317                             .equals(refa.getMap().getMap())))
318             {
319               return true;
320             }
321           }
322         }
323       }
324       return false;
325     }
326   };
327
328   /**
329    * accession ID and DB must be identical. Version is ignored. No map on both
330    * or or map but no maplist on either or maplist of map on a is equivalent to
331    * the maplist of map on b.
332    */
333   public static DbRefComp matchDbAndIdAndEquivalentMapList = new DbRefComp()
334   {
335     public boolean matches(DBRefEntry refa, DBRefEntry refb)
336     {
337       if (refa.getSource() != null && refb.getSource() != null
338               && refb.getSource().equals(refa.getSource()))
339       {
340         // We dont care about version
341         // if ((refa.getVersion()==null || refb.getVersion()==null)
342         // || refb.getVersion().equals(refa.getVersion()))
343         // {
344         if (refa.getAccessionId() != null && refb.getAccessionId() != null
345                 || refb.getAccessionId().equals(refa.getAccessionId()))
346         {
347           if (refa.getMap() == null && refb.getMap() == null)
348           {
349             return true;
350           }
351           if (refa.getMap() != null
352                   && refb.getMap() != null
353                   && ((refb.getMap().getMap() == null && refa.getMap()
354                           .getMap() == null) || (refb.getMap().getMap() != null
355                           && refa.getMap().getMap() != null && refb
356                           .getMap().getMap().equals(refa.getMap().getMap()))))
357           {
358             return true;
359           }
360         }
361       }
362       return false;
363     }
364   };
365
366   /**
367    * accession ID and DB must be identical. Version is ignored. No map on either
368    * or map but no maplist on either or maplist of map on a is equivalent to the
369    * maplist of map on b.
370    */
371   public static DbRefComp matchDbAndIdAndEitherMapOrEquivalentMapList = new DbRefComp()
372   {
373     public boolean matches(DBRefEntry refa, DBRefEntry refb)
374     {
375       // System.err.println("Comparing A: "+refa.getSrcAccString()+(refa.hasMap()?" has map.":"."));
376       // System.err.println("Comparing B: "+refb.getSrcAccString()+(refb.hasMap()?" has map.":"."));
377       if (refa.getSource() != null && refb.getSource() != null
378               && refb.getSource().equals(refa.getSource()))
379       {
380         // We dont care about version
381         // if ((refa.getVersion()==null || refb.getVersion()==null)
382         // || refb.getVersion().equals(refa.getVersion()))
383         // {
384         if (refa.getAccessionId() != null && refb.getAccessionId() != null
385                 && refb.getAccessionId().equals(refa.getAccessionId()))
386         {
387           if (refa.getMap() == null || refb.getMap() == null)
388           {
389             return true;
390           }
391           if ((refa.getMap() != null && refb.getMap() != null)
392                   && (refb.getMap().getMap() == null && refa.getMap()
393                           .getMap() == null)
394                   || (refb.getMap().getMap() != null
395                           && refa.getMap().getMap() != null && (refb
396                           .getMap().getMap().equals(refa.getMap().getMap()))))
397           { // getMap().getMap().containsEither(false,refa.getMap().getMap())
398             return true;
399           }
400         }
401       }
402       return false;
403     }
404   };
405
406   /**
407    * Parses a DBRefEntry and adds it to the sequence, also a PDBEntry if the
408    * database is PDB.
409    * <p>
410    * Used by file parsers to generate DBRefs from annotation within file (eg
411    * Stockholm)
412    * 
413    * @param dbname
414    * @param version
415    * @param acn
416    * @param seq
417    *          where to annotate with reference
418    * @return parsed version of entry that was added to seq (if any)
419    */
420   public static DBRefEntry parseToDbRef(SequenceI seq, String dbname,
421           String version, String acn)
422   {
423     DBRefEntry ref = null;
424     if (dbname != null)
425     {
426       String locsrc = DBRefUtils.getCanonicalName(dbname);
427       if (locsrc.equals(DBRefSource.PDB))
428       {
429         /*
430          * Check for PFAM style stockhom PDB accession id citation e.g.
431          * "1WRI A; 7-80;"
432          */
433         Regex r = new Regex(
434                 "([0-9][0-9A-Za-z]{3})\\s*(.?)\\s*;\\s*([0-9]+)-([0-9]+)");
435         if (r.search(acn.trim()))
436         {
437           String pdbid = r.stringMatched(1);
438           String chaincode = r.stringMatched(2);
439           if (chaincode==null)
440           {
441             chaincode = " ";
442           }
443           // String mapstart = r.stringMatched(3);
444           // String mapend = r.stringMatched(4);
445           if (chaincode.equals(" "))
446           {
447             chaincode = "_";
448           }
449           // construct pdb ref.
450           ref = new DBRefEntry(locsrc, version, pdbid + chaincode);
451           PDBEntry pdbr = new PDBEntry();
452           pdbr.setId(pdbid);
453           pdbr.setType(PDBEntry.Type.PDB);
454           pdbr.setProperty(new Hashtable());
455           pdbr.setChainCode(chaincode);
456           // pdbr.getProperty().put("CHAIN", chaincode);
457           seq.addPDBId(pdbr);
458         } else {
459           System.err.println("Malformed PDB DR line:"+acn);
460         }
461       }
462       else
463       {
464         // default:
465         ref = new DBRefEntry(locsrc, version, acn);
466       }
467     }
468     if (ref != null)
469     {
470       seq.addDBRef(ref);
471     }
472     return ref;
473   }
474
475 }