JAL-4102 update 2.12 from 2.11.2.6 patch release - JAL-3416 JAL-2353 JAL-4104 JAL...
[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 java.util.ArrayList;
24 import java.util.BitSet;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.Map;
30
31 import com.stevesoft.pat.Regex;
32
33 import jalview.datamodel.DBRefEntry;
34 import jalview.datamodel.DBRefSource;
35 import jalview.datamodel.Mapping;
36 import jalview.datamodel.PDBEntry;
37 import jalview.datamodel.SequenceI;
38
39 /**
40  * Utilities for handling DBRef objects and their collections.
41  */
42 public class DBRefUtils
43 {
44   /*
45    * lookup from lower-case form of a name to its canonical (standardised) form
46    */
47   private static Map<String, String> canonicalSourceNameLookup = new HashMap<>();
48
49   public final static int DB_SOURCE = 1;
50
51   public final static int DB_VERSION = 2;
52
53   public final static int DB_ID = 4;
54
55   public final static int DB_MAP = 8;
56
57   public final static int SEARCH_MODE_NO_MAP_NO_VERSION = DB_SOURCE | DB_ID;
58
59   public final static int SEARCH_MODE_FULL = DB_SOURCE | DB_VERSION | DB_ID
60           | DB_MAP;
61
62   static
63   {
64     // TODO load these from a resource file?
65     canonicalSourceNameLookup.put("uniprotkb/swiss-prot",
66             DBRefSource.UNIPROT);
67     canonicalSourceNameLookup.put("uniprotkb/trembl", DBRefSource.UNIPROT);
68
69     // Ensembl values for dbname in xref REST service:
70     canonicalSourceNameLookup.put("uniprot/sptrembl", DBRefSource.UNIPROT);
71     canonicalSourceNameLookup.put("uniprot/swissprot", DBRefSource.UNIPROT);
72
73     canonicalSourceNameLookup.put("pdb", DBRefSource.PDB);
74     canonicalSourceNameLookup.put("ensembl", DBRefSource.ENSEMBL);
75     // Ensembl Gn and Tr are for Ensembl genomic and transcript IDs as served
76     // from ENA.
77     canonicalSourceNameLookup.put("ensembl-tr", DBRefSource.ENSEMBL);
78     canonicalSourceNameLookup.put("ensembl-gn", DBRefSource.ENSEMBL);
79
80     // guarantee we always have lowercase entries for canonical string lookups
81     for (String k : canonicalSourceNameLookup.keySet())
82     {
83       canonicalSourceNameLookup.put(k.toLowerCase(Locale.ROOT),
84               canonicalSourceNameLookup.get(k));
85     }
86   }
87
88   /**
89    * Returns those DBRefEntry objects whose source identifier (once converted to
90    * Jalview's canonical form) is in the list of sources to search for. Returns
91    * null if no matches found.
92    * 
93    * @param dbrefs
94    *          DBRefEntry objects to search
95    * @param sources
96    *          array of sources to select
97    * @return
98    */
99   public static List<DBRefEntry> selectRefs(List<DBRefEntry> dbrefs,
100           String[] sources)
101   {
102     if (dbrefs == null || sources == null)
103     {
104       return dbrefs;
105     }
106
107     // BH TODO (what?)
108     HashSet<String> srcs = new HashSet<String>();
109     for (String src : sources)
110     {
111       srcs.add(src.toUpperCase(Locale.ROOT));
112     }
113
114     int nrefs = dbrefs.size();
115     List<DBRefEntry> res = new ArrayList<DBRefEntry>();
116     for (int ib = 0; ib < nrefs; ib++)
117     {
118       DBRefEntry dbr = dbrefs.get(ib);
119       String source = getCanonicalName(dbr.getSource());
120       if (srcs.contains(source.toUpperCase(Locale.ROOT)))
121       {
122         res.add(dbr);
123       }
124     }
125     if (res.size() > 0)
126     {
127       // List<DBRefEntry> reply = new DBRefEntry[res.size()];
128       return res;// .toArray(reply);
129     }
130     return null;
131   }
132
133   private static boolean selectRefsBS(List<DBRefEntry> dbrefs,
134           int sourceKeys, BitSet bsSelect)
135   {
136     if (dbrefs == null || sourceKeys == 0)
137     {
138       return false;
139     }
140     for (int i = 0, n = dbrefs.size(); i < n; i++)
141     {
142       DBRefEntry dbr = dbrefs.get(i);
143       if ((dbr.getSourceKey() & sourceKeys) != 0)
144       {
145         bsSelect.clear(i);
146       }
147     }
148     return !bsSelect.isEmpty();
149   }
150
151   /**
152    * Returns a (possibly empty) list of those references that match the given
153    * entry, according to the given comparator.
154    * 
155    * @param refs
156    *          an array of database references to search
157    * @param entry
158    *          an entry to compare against
159    * @param comparator
160    * @return
161    */
162   static List<DBRefEntry> searchRefs(DBRefEntry[] refs, DBRefEntry entry,
163           DbRefComp comparator)
164   {
165     List<DBRefEntry> rfs = new ArrayList<>();
166     if (refs == null || entry == null)
167     {
168       return rfs;
169     }
170     for (int i = 0; i < refs.length; i++)
171     {
172       if (comparator.matches(entry, refs[i]))
173       {
174         rfs.add(refs[i]);
175       }
176     }
177     return rfs;
178   }
179
180   /**
181    * look up source in an internal list of database reference sources and return
182    * the canonical jalview name for the source, or the original string if it has
183    * no canonical form.
184    * 
185    * @param source
186    * @return canonical jalview source (one of jalview.datamodel.DBRefSource.*)
187    *         or original source
188    */
189   public static String getCanonicalName(String source)
190   {
191     if (source == null)
192     {
193       return null;
194     }
195     String canonical = canonicalSourceNameLookup
196             .get(source.toLowerCase(Locale.ROOT));
197     return canonical == null ? source : canonical;
198   }
199
200   /**
201    * Returns a (possibly empty) list of those references that match the given
202    * entry. Currently uses a comparator which matches if
203    * <ul>
204    * <li>database sources are the same</li>
205    * <li>accession ids are the same</li>
206    * <li>both have no mapping, or the mappings are the same</li>
207    * </ul>
208    * 
209    * @param ref
210    *          Set of references to search
211    * @param entry
212    *          pattern to match
213    * @param mode
214    *          SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION optional
215    * @return
216    */
217   public static List<DBRefEntry> searchRefs(List<DBRefEntry> ref,
218           DBRefEntry entry, int mode)
219   {
220     return searchRefs(ref, entry,
221             matchDbAndIdAndEitherMapOrEquivalentMapList, mode);
222   }
223
224   /**
225    * Returns a list of those references that match the given accession id
226    * <ul>
227    * <li>database sources are the same</li>
228    * <li>accession ids are the same</li>
229    * <li>both have no mapping, or the mappings are the same</li>
230    * </ul>
231    * 
232    * @param refs
233    *          Set of references to search
234    * @param accId
235    *          accession id to match
236    * @return
237    */
238   public static List<DBRefEntry> searchRefs(List<DBRefEntry> refs,
239           String accId)
240   {
241     List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
242     if (refs == null || accId == null)
243     {
244       return rfs;
245     }
246     for (int i = 0, n = refs.size(); i < n; i++)
247     {
248       DBRefEntry e = refs.get(i);
249       if (accId.equals(e.getAccessionId()))
250       {
251         rfs.add(e);
252       }
253     }
254     return rfs;
255     // return searchRefs(refs, new DBRefEntry("", "", accId), matchId,
256     // SEARCH_MODE_FULL);
257   }
258
259   /**
260    * Returns a (possibly empty) list of those references that match the given
261    * entry, according to the given comparator.
262    * 
263    * @param refs
264    *          an array of database references to search
265    * @param entry
266    *          an entry to compare against
267    * @param comparator
268    * @param mode
269    *          SEARCH_MODE_FULL for all; SEARCH_MODE_NO_MAP_NO_VERSION optional
270    * @return
271    */
272   static List<DBRefEntry> searchRefs(List<DBRefEntry> refs,
273           DBRefEntry entry, DbRefComp comparator, int mode)
274   {
275     List<DBRefEntry> rfs = new ArrayList<DBRefEntry>();
276     if (refs == null || entry == null)
277     {
278       return rfs;
279     }
280     for (int i = 0, n = refs.size(); i < n; i++)
281     {
282       DBRefEntry e = refs.get(i);
283       if (comparator.matches(entry, e, SEARCH_MODE_FULL))
284       {
285         rfs.add(e);
286       }
287     }
288     return rfs;
289   }
290
291   interface DbRefComp
292   {
293     default public boolean matches(DBRefEntry refa, DBRefEntry refb)
294     {
295       return matches(refa, refb, SEARCH_MODE_FULL);
296     };
297
298     public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode);
299   }
300
301   /**
302    * match on all non-null fields in refa
303    */
304   // TODO unused - remove? would be broken by equating "" with null
305   public static DbRefComp matchNonNullonA = new DbRefComp()
306   {
307     @Override
308     public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
309     {
310       if ((mode & DB_SOURCE) != 0 && (refa.getSource() == null
311               || DBRefUtils.getCanonicalName(refb.getSource()).equals(
312                       DBRefUtils.getCanonicalName(refa.getSource()))))
313       {
314         if ((mode & DB_VERSION) != 0 && (refa.getVersion() == null
315                 || refb.getVersion().equals(refa.getVersion())))
316         {
317           if ((mode & DB_ID) != 0 && (refa.getAccessionId() == null
318                   || refb.getAccessionId().equals(refa.getAccessionId())))
319           {
320             if ((mode & DB_MAP) != 0
321                     && (refa.getMap() == null || (refb.getMap() != null
322                             && refb.getMap().equals(refa.getMap()))))
323             {
324               return true;
325             }
326           }
327         }
328       }
329       return false;
330     }
331   };
332
333   /**
334    * either field is null or field matches for all of source, version, accession
335    * id and map.
336    */
337   // TODO unused - remove?
338   public static DbRefComp matchEitherNonNull = new DbRefComp()
339   {
340     @Override
341     public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
342     {
343       if (nullOrEqualSource(refa.getSource(), refb.getSource())
344               && nullOrEqual(refa.getVersion(), refb.getVersion())
345               && nullOrEqual(refa.getAccessionId(), refb.getAccessionId())
346               && nullOrEqual(refa.getMap(), refb.getMap()))
347       {
348         return true;
349       }
350       return false;
351     }
352
353   };
354
355   private static Regex PARSE_REGEX;
356
357   private static Regex getParseRegex()
358   {
359     return (PARSE_REGEX == null ? PARSE_REGEX = Platform.newRegex(
360             "([0-9][0-9A-Za-z]{3})\\s*(.?)\\s*;\\s*([0-9]+)-([0-9]+)")
361             : PARSE_REGEX);
362   }
363
364   /**
365    * Parses a DBRefEntry and adds it to the sequence, also a PDBEntry if the
366    * database is PDB.
367    * <p>
368    * Used by file parsers to generate DBRefs from annotation within file (eg
369    * Stockholm)
370    * 
371    * @param dbname
372    * @param version
373    * @param acn
374    * @param seq
375    *          where to annotate with reference
376    * @return parsed version of entry that was added to seq (if any)
377    */
378   public static DBRefEntry parseToDbRef(SequenceI seq, String dbname,
379           String version, String acn)
380   {
381     DBRefEntry ref = null;
382     if (dbname != null)
383     {
384       String locsrc = DBRefUtils.getCanonicalName(dbname);
385       if (locsrc.equals(DBRefSource.PDB))
386       {
387         /*
388          * Check for PFAM style stockhom PDB accession id citation e.g.
389          * "1WRI A; 7-80;"
390          */
391         Regex r = getParseRegex();
392         if (r.search(acn.trim()))
393         {
394           String pdbid = r.stringMatched(1);
395           String chaincode = r.stringMatched(2);
396           if (chaincode == null)
397           {
398             chaincode = " ";
399           }
400           // String mapstart = r.stringMatched(3);
401           // String mapend = r.stringMatched(4);
402           if (chaincode.equals(" "))
403           {
404             chaincode = "_";
405           }
406           // construct pdb ref.
407           ref = new DBRefEntry(locsrc, version, pdbid + chaincode);
408           PDBEntry pdbr = new PDBEntry();
409           pdbr.setId(pdbid);
410           pdbr.setType(PDBEntry.Type.PDB);
411           pdbr.setChainCode(chaincode);
412           seq.addPDBId(pdbr);
413         }
414         else
415         {
416           System.err.println("Malformed PDB DR line:" + acn);
417         }
418       }
419       else
420       {
421         // default:
422         ref = new DBRefEntry(locsrc, version, acn.trim());
423       }
424     }
425     if (ref != null)
426     {
427       seq.addDBRef(ref);
428     }
429     return ref;
430   }
431
432   /**
433    * accession ID and DB must be identical. Version is ignored. Map is either
434    * not defined or is a match (or is compatible?)
435    */
436   // TODO unused - remove?
437   public static DbRefComp matchDbAndIdAndEitherMap = new DbRefComp()
438   {
439     @Override
440     public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
441     {
442       if (refa.getSource() != null && refb.getSource() != null
443               && DBRefUtils.getCanonicalName(refb.getSource()).equals(
444                       DBRefUtils.getCanonicalName(refa.getSource())))
445       {
446         // We dont care about version
447         if (refa.getAccessionId() != null && refb.getAccessionId() != null
448                 // FIXME should be && not || here?
449                 || refb.getAccessionId().equals(refa.getAccessionId()))
450         {
451           if ((refa.getMap() == null || refb.getMap() == null)
452                   || (refa.getMap() != null && refb.getMap() != null
453                           && refb.getMap().equals(refa.getMap())))
454           {
455             return true;
456           }
457         }
458       }
459       return false;
460     }
461   };
462
463   /**
464    * accession ID and DB must be identical. Version is ignored. No map on either
465    * or map but no maplist on either or maplist of map on a is the complement of
466    * maplist of map on b.
467    */
468   // TODO unused - remove?
469   public static DbRefComp matchDbAndIdAndComplementaryMapList = new DbRefComp()
470   {
471     @Override
472     public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
473     {
474       if (refa.getSource() != null && refb.getSource() != null
475               && DBRefUtils.getCanonicalName(refb.getSource()).equals(
476                       DBRefUtils.getCanonicalName(refa.getSource())))
477       {
478         // We dont care about version
479         if (refa.getAccessionId() != null && refb.getAccessionId() != null
480                 || refb.getAccessionId().equals(refa.getAccessionId()))
481         {
482           if ((refa.getMap() == null && refb.getMap() == null)
483                   || (refa.getMap() != null && refb.getMap() != null))
484           {
485             if ((refb.getMap().getMap() == null
486                     && refa.getMap().getMap() == null)
487                     || (refb.getMap().getMap() != null
488                             && refa.getMap().getMap() != null
489                             && refb.getMap().getMap().getInverse()
490                                     .equals(refa.getMap().getMap())))
491             {
492               return true;
493             }
494           }
495         }
496       }
497       return false;
498     }
499   };
500
501   /**
502    * accession ID and DB must be identical. Version is ignored. No map on both
503    * or or map but no maplist on either or maplist of map on a is equivalent to
504    * the maplist of map on b.
505    */
506   // TODO unused - remove?
507   public static DbRefComp matchDbAndIdAndEquivalentMapList = new DbRefComp()
508   {
509     @Override
510     public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
511     {
512       if (refa.getSource() != null && refb.getSource() != null
513               && DBRefUtils.getCanonicalName(refb.getSource()).equals(
514                       DBRefUtils.getCanonicalName(refa.getSource())))
515       {
516         // We dont care about version
517         // if ((refa.getVersion()==null || refb.getVersion()==null)
518         // || refb.getVersion().equals(refa.getVersion()))
519         // {
520         if (refa.getAccessionId() != null && refb.getAccessionId() != null
521                 || refb.getAccessionId().equals(refa.getAccessionId()))
522         {
523           if (refa.getMap() == null && refb.getMap() == null)
524           {
525             return true;
526           }
527           if (refa.getMap() != null && refb.getMap() != null
528                   && ((refb.getMap().getMap() == null
529                           && refa.getMap().getMap() == null)
530                           || (refb.getMap().getMap() != null
531                                   && refa.getMap().getMap() != null
532                                   && refb.getMap().getMap()
533                                           .equals(refa.getMap().getMap()))))
534           {
535             return true;
536           }
537         }
538       }
539       return false;
540     }
541   };
542
543   /**
544    * accession ID and DB must be identical, or null on a. Version is ignored. No
545    * map on either or map but no maplist on either or maplist of map on a is
546    * equivalent to the maplist of map on b.
547    */
548   public static DbRefComp matchDbAndIdAndEitherMapOrEquivalentMapList = new DbRefComp()
549   {
550     @Override
551     public boolean matches(DBRefEntry refa, DBRefEntry refb, int mode)
552     {
553       if (refa.getSource() != null && refb.getSource() != null
554               && DBRefUtils.getCanonicalName(refb.getSource()).equals(
555                       DBRefUtils.getCanonicalName(refa.getSource())))
556       {
557         // We dont care about version
558         if (refa.getAccessionId() == null
559                 || refa.getAccessionId().equals(refb.getAccessionId()))
560         {
561           if (refa.getMap() == null || refb.getMap() == null)
562           {
563             return true;
564           }
565           if ((refa.getMap() != null && refb.getMap() != null)
566                   && (refb.getMap().getMap() == null
567                           && refa.getMap().getMap() == null)
568                   || (refb.getMap().getMap() != null
569                           && refa.getMap().getMap() != null
570                           && (refb.getMap().getMap()
571                                   .equals(refa.getMap().getMap()))))
572           {
573             return true;
574           }
575         }
576       }
577       return false;
578     }
579   };
580
581   /**
582    * Returns the (possibly empty) list of those supplied dbrefs which have the
583    * specified source database, with a case-insensitive match of source name
584    * 
585    * @param dbRefs
586    * @param source
587    * @return
588    */
589   public static List<DBRefEntry> searchRefsForSource(DBRefEntry[] dbRefs,
590           String source)
591   {
592     List<DBRefEntry> matches = new ArrayList<>();
593     if (dbRefs != null && source != null)
594     {
595       for (DBRefEntry dbref : dbRefs)
596       {
597         if (source.equalsIgnoreCase(dbref.getSource()))
598         {
599           matches.add(dbref);
600         }
601       }
602     }
603     return matches;
604   }
605
606   /**
607    * Returns true if either object is null, or they are equal
608    * 
609    * @param o1
610    * @param o2
611    * @return
612    */
613   public static boolean nullOrEqual(Object o1, Object o2)
614   {
615     if (o1 == null || o2 == null)
616     {
617       return true;
618     }
619     return o1.equals(o2);
620   }
621
622   /**
623    * canonicalise source string before comparing. null is always wildcard
624    * 
625    * @param o1
626    *          - null or source string to compare
627    * @param o2
628    *          - null or source string to compare
629    * @return true if either o1 or o2 are null, or o1 equals o2 under
630    *         DBRefUtils.getCanonicalName
631    *         (o1).equals(DBRefUtils.getCanonicalName(o2))
632    */
633   public static boolean nullOrEqualSource(String o1, String o2)
634   {
635     if (o1 == null || o2 == null)
636     {
637       return true;
638     }
639     return DBRefUtils.getCanonicalName(o1)
640             .equals(DBRefUtils.getCanonicalName(o2));
641   }
642
643   /**
644    * Selects just the DNA or protein references from a set of references
645    * 
646    * @param selectDna
647    *          if true, select references to 'standard' DNA databases, else to
648    *          'standard' peptide databases
649    * @param refs
650    *          a set of references to select from
651    * @return
652    */
653   public static List<DBRefEntry> selectDbRefs(boolean selectDna,
654           List<DBRefEntry> refs)
655   {
656     return selectRefs(refs,
657             selectDna ? DBRefSource.DNACODINGDBS : DBRefSource.PROTEINDBS);
658     // could attempt to find other cross
659     // refs here - ie PDB xrefs
660     // (not dna, not protein seq)
661   }
662
663   /**
664    * Returns the (possibly empty) list of those supplied dbrefs which have the
665    * specified source database, with a case-insensitive match of source name
666    * 
667    * @param dbRefs
668    * @param source
669    * @return
670    */
671   public static List<DBRefEntry> searchRefsForSource(
672           List<DBRefEntry> dbRefs, String source)
673   {
674     List<DBRefEntry> matches = new ArrayList<DBRefEntry>();
675     if (dbRefs != null && source != null)
676     {
677       for (DBRefEntry dbref : dbRefs)
678       {
679         if (source.equalsIgnoreCase(dbref.getSource()))
680         {
681           matches.add(dbref);
682         }
683       }
684     }
685     return matches;
686   }
687
688   /**
689    * promote direct database references to primary for nucleotide or protein
690    * sequences if they have an appropriate primary ref
691    * <table>
692    * <tr>
693    * <th>Seq Type</th>
694    * <th>Primary DB</th>
695    * <th>Direct which will be promoted</th>
696    * </tr>
697    * <tr align=center>
698    * <td>peptides</td>
699    * <td>Ensembl</td>
700    * <td>Uniprot</td>
701    * </tr>
702    * <tr align=center>
703    * <td>peptides</td>
704    * <td>Ensembl</td>
705    * <td>Uniprot</td>
706    * </tr>
707    * <tr align=center>
708    * <td>dna</td>
709    * <td>Ensembl</td>
710    * <td>ENA</td>
711    * </tr>
712    * </table>
713    * 
714    * @param sequence
715    */
716   public static void ensurePrimaries(SequenceI sequence,
717           List<DBRefEntry> pr)
718   {
719     if (pr.size() == 0)
720     {
721       // nothing to do
722       return;
723     }
724     int sstart = sequence.getStart();
725     int send = sequence.getEnd();
726     boolean isProtein = sequence.isProtein();
727     BitSet bsSelect = new BitSet();
728
729     // List<DBRefEntry> selfs = new ArrayList<DBRefEntry>();
730     // {
731
732     // List<DBRefEntry> selddfs = selectDbRefs(!isprot, sequence.getDBRefs());
733     // if (selfs == null || selfs.size() == 0)
734     // {
735     // // nothing to do
736     // return;
737     // }
738
739     List<DBRefEntry> dbrefs = sequence.getDBRefs();
740     bsSelect.set(0, dbrefs.size());
741
742     if (!selectRefsBS(dbrefs, isProtein ? DBRefSource.PROTEIN_MASK
743             : DBRefSource.DNA_CODING_MASK, bsSelect))
744       return;
745
746     // selfs.addAll(selfArray);
747     // }
748
749     // filter non-primary refs
750     for (int ip = pr.size(); --ip >= 0;)
751     {
752       DBRefEntry p = pr.get(ip);
753       for (int i = bsSelect.nextSetBit(0); i >= 0; i = bsSelect
754               .nextSetBit(i + 1))
755       {
756         if (dbrefs.get(i) == p)
757           bsSelect.clear(i);
758       }
759       // while (selfs.contains(p))
760       // {
761       // selfs.remove(p);
762       // }
763     }
764     // List<DBRefEntry> toPromote = new ArrayList<DBRefEntry>();
765
766     for (int ip = pr.size(), keys = 0; --ip >= 0
767             && keys != DBRefSource.PRIMARY_MASK;)
768     {
769       DBRefEntry p = pr.get(ip);
770       if (isProtein)
771       {
772         switch (getCanonicalName(p.getSource()))
773         {
774         case DBRefSource.UNIPROT:
775           keys |= DBRefSource.UNIPROT_MASK;
776           break;
777         case DBRefSource.ENSEMBL:
778           keys |= DBRefSource.ENSEMBL_MASK;
779           break;
780         }
781       }
782       else
783       {
784         // TODO: promote transcript refs ??
785       }
786       if (keys == 0 || !selectRefsBS(dbrefs, keys, bsSelect))
787         return;
788       // if (candidates != null)
789       {
790         for (int ic = bsSelect.nextSetBit(0); ic >= 0; ic = bsSelect
791                 .nextSetBit(ic + 1))
792         // for (int ic = 0, n = candidates.size(); ic < n; ic++)
793         {
794           DBRefEntry cand = dbrefs.get(ic);// candidates.get(ic);
795           if (cand.hasMap())
796           {
797             Mapping map = cand.getMap();
798             SequenceI cto = map.getTo();
799             if (cto != null && cto != sequence)
800             {
801               // can't promote refs with mappings to other sequences
802               continue;
803             }
804             MapList mlist = map.getMap();
805             if (mlist.getFromLowest() != sstart
806                     && mlist.getFromHighest() != send)
807             {
808               // can't promote refs with mappings from a region of this sequence
809               // - eg CDS
810               continue;
811             }
812           }
813           // and promote - not that version must be non-null here,
814           // as p must have passed isPrimaryCandidate()
815           cand.setVersion(cand.getVersion() + " (promoted)");
816           bsSelect.clear(ic);
817           // selfs.remove(cand);
818           // toPromote.add(cand);
819           if (!cand.isPrimaryCandidate())
820           {
821             System.out.println(
822                     "Warning: Couldn't promote dbref " + cand.toString()
823                             + " for sequence " + sequence.toString());
824           }
825         }
826       }
827     }
828   }
829
830 }