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