JAL-2106 removed setSourceDBRef, refactor getSourceDBRef to getPrimaryDBRefs
[jalview.git] / src / jalview / ws / sifts / SiftsClient.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.ws.sifts;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.api.DBRefEntryI;
25 import jalview.api.SiftsClientI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.DBRefSource;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.StructureFile;
30 import jalview.schemes.ResidueProperties;
31 import jalview.structure.StructureMapping;
32 import jalview.util.Format;
33 import jalview.xml.binding.sifts.Entry;
34 import jalview.xml.binding.sifts.Entry.Entity;
35 import jalview.xml.binding.sifts.Entry.Entity.Segment;
36 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListMapRegion.MapRegion;
37 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue;
38 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.CrossRefDb;
39 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.ResidueDetail;
40
41 import java.io.File;
42 import java.io.FileInputStream;
43 import java.io.FileOutputStream;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.io.PrintStream;
47 import java.net.URL;
48 import java.net.URLConnection;
49 import java.nio.file.Files;
50 import java.nio.file.Path;
51 import java.nio.file.attribute.BasicFileAttributes;
52 import java.util.ArrayList;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.Collections;
56 import java.util.Date;
57 import java.util.HashMap;
58 import java.util.HashSet;
59 import java.util.List;
60 import java.util.Map;
61 import java.util.Set;
62 import java.util.TreeMap;
63 import java.util.zip.GZIPInputStream;
64
65 import javax.xml.bind.JAXBContext;
66 import javax.xml.bind.Unmarshaller;
67 import javax.xml.stream.XMLInputFactory;
68 import javax.xml.stream.XMLStreamReader;
69
70 import MCview.Atom;
71 import MCview.PDBChain;
72
73 public class SiftsClient implements SiftsClientI
74 {
75   private Entry siftsEntry;
76
77   private StructureFile pdb;
78
79   private String pdbId;
80
81   private String structId;
82
83   private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
84
85   private static final int BUFFER_SIZE = 4096;
86
87   public static final int UNASSIGNED = -1;
88
89   private static final int PDB_RES_POS = 0;
90
91   private static final int PDB_ATOM_POS = 1;
92
93   private static final String NOT_OBSERVED = "Not_Observed";
94
95   private static final String SIFTS_FTP_BASE_URL = "http://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/";
96
97   private final static String NEWLINE = System.lineSeparator();
98
99   private String curSourceDBRef;
100
101   private HashSet<String> curDBRefAccessionIdsString;
102
103   private enum CoordinateSys
104   {
105     UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
106     private String name;
107
108     private CoordinateSys(String name)
109     {
110       this.name = name;
111     }
112
113     public String getName()
114     {
115       return name;
116     }
117   };
118
119   private enum ResidueDetailType
120   {
121     NAME_SEC_STRUCTURE("nameSecondaryStructure"), CODE_SEC_STRUCTURE(
122             "codeSecondaryStructure"), ANNOTATION("Annotation");
123     private String code;
124
125     private ResidueDetailType(String code)
126     {
127       this.code = code;
128     }
129
130     public String getCode()
131     {
132       return code;
133     }
134   };
135
136   /**
137    * Fetch SIFTs file for the given PDBfile and construct an instance of
138    * SiftsClient
139    * 
140    * @param pdbId
141    * @throws SiftsException
142    */
143   public SiftsClient(StructureFile pdb) throws SiftsException
144   {
145     this.pdb = pdb;
146     this.pdbId = pdb.getId();
147     File siftsFile = getSiftsFile(pdbId);
148     siftsEntry = parseSIFTs(siftsFile);
149   }
150
151
152   /**
153    * Parse the given SIFTs File and return a JAXB POJO of parsed data
154    * 
155    * @param siftFile
156    *          - the GZipped SIFTs XML file to parse
157    * @return
158    * @throws Exception
159    *           if a problem occurs while parsing the SIFTs XML
160    */
161   private Entry parseSIFTs(File siftFile) throws SiftsException
162   {
163     try (InputStream in = new FileInputStream(siftFile);
164             GZIPInputStream gzis = new GZIPInputStream(in);)
165     {
166       // System.out.println("File : " + siftFile.getAbsolutePath());
167       JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
168       XMLStreamReader streamReader = XMLInputFactory.newInstance()
169               .createXMLStreamReader(gzis);
170       Unmarshaller um = jc.createUnmarshaller();
171       return (Entry) um.unmarshal(streamReader);
172     } catch (Exception e)
173     {
174       e.printStackTrace();
175       throw new SiftsException(e.getMessage());
176     }
177   }
178
179   /**
180    * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
181    * repository if not found in cache
182    * 
183    * @param pdbId
184    * @return SIFTs XML file
185    * @throws SiftsException
186    */
187   public static File getSiftsFile(String pdbId) throws SiftsException
188   {
189     String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
190             + pdbId.toLowerCase() + ".xml.gz";
191     File siftsFile = new File(siftsFileName);
192     if (siftsFile.exists())
193     {
194       // The line below is required for unit testing... don't comment it out!!!
195       System.out.println(">>> SIFTS File already downloaded for " + pdbId);
196
197       if (isFileOlderThanThreshold(siftsFile,
198               SiftsSettings.getCacheThresholdInDays()))
199       {
200         File oldSiftsFile = new File(siftsFileName + "_old");
201         siftsFile.renameTo(oldSiftsFile);
202         try
203         {
204           siftsFile = downloadSiftsFile(pdbId.toLowerCase());
205           oldSiftsFile.delete();
206           return siftsFile;
207         } catch (IOException e)
208         {
209           e.printStackTrace();
210           oldSiftsFile.renameTo(siftsFile);
211           return new File(siftsFileName);
212         }
213       }
214     }
215     try
216     {
217       siftsFile = downloadSiftsFile(pdbId.toLowerCase());
218     } catch (IOException e)
219     {
220       throw new SiftsException(e.getMessage());
221     }
222     return siftsFile;
223   }
224
225   /**
226    * This method enables checking if a cached file has exceeded a certain
227    * threshold(in days)
228    * 
229    * @param file
230    *          the cached file
231    * @param noOfDays
232    *          the threshold in days
233    * @return
234    */
235   public static boolean isFileOlderThanThreshold(File file, int noOfDays)
236   {
237     Path filePath = file.toPath();
238     BasicFileAttributes attr;
239     int diffInDays = 0;
240     try
241     {
242       attr = Files.readAttributes(filePath, BasicFileAttributes.class);
243       diffInDays = (int) ((new Date().getTime() - attr.lastModifiedTime()
244               .toMillis()) / (1000 * 60 * 60 * 24));
245       // System.out.println("Diff in days : " + diffInDays);
246     } catch (IOException e)
247     {
248       e.printStackTrace();
249     }
250     return noOfDays <= diffInDays;
251   }
252
253   /**
254    * Download a SIFTs XML file for a given PDB Id from an FTP repository
255    * 
256    * @param pdbId
257    * @return downloaded SIFTs XML file
258    * @throws SiftsException
259    * @throws IOException
260    */
261   public static File downloadSiftsFile(String pdbId) throws SiftsException,
262           IOException
263   {
264     if (pdbId.contains(".cif"))
265     {
266       pdbId = pdbId.replace(".cif", "");
267     }
268     String siftFile = pdbId + ".xml.gz";
269     String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
270     String downloadedSiftsFile = SiftsSettings.getSiftDownloadDirectory()
271             + siftFile;
272     File siftsDownloadDir = new File(
273             SiftsSettings.getSiftDownloadDirectory());
274     if (!siftsDownloadDir.exists())
275     {
276       siftsDownloadDir.mkdirs();
277     }
278       // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
279       URL url = new URL(siftsFileFTPURL);
280       URLConnection conn = url.openConnection();
281       InputStream inputStream = conn.getInputStream();
282       FileOutputStream outputStream = new FileOutputStream(
283               downloadedSiftsFile);
284       byte[] buffer = new byte[BUFFER_SIZE];
285       int bytesRead = -1;
286       while ((bytesRead = inputStream.read(buffer)) != -1)
287       {
288         outputStream.write(buffer, 0, bytesRead);
289       }
290       outputStream.close();
291       inputStream.close();
292       // System.out.println(">>> File downloaded : " + downloadedSiftsFile);
293     return new File(downloadedSiftsFile);
294   }
295
296   /**
297    * Delete the SIFTs file for the given PDB Id in the local SIFTs download
298    * directory
299    * 
300    * @param pdbId
301    * @return true if the file was deleted or doesn't exist
302    */
303   public static boolean deleteSiftsFileByPDBId(String pdbId)
304   {
305     File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
306             + pdbId.toLowerCase() + ".xml.gz");
307     if (siftsFile.exists())
308     {
309       return siftsFile.delete();
310     }
311     return true;
312   }
313
314   /**
315    * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
316    * 
317    * @param seq
318    *          - the target sequence for the operation
319    * @return a valid DBRefEntry that is SIFTs compatible
320    * @throws Exception
321    *           if no valid source DBRefEntry was found for the given sequences
322    */
323   public DBRefEntryI getValidSourceDBRef(SequenceI seq)
324           throws SiftsException
325   {
326     DBRefEntry[] dbRefs = seq.getDBRefs();
327     if (dbRefs == null || dbRefs.length < 1)
328     {
329       throw new SiftsException(
330               "Source DBRef could not be determined. DBRefs might not have been retrieved.");
331     }
332
333     for (DBRefEntryI dbRef : dbRefs)
334     {
335       if (dbRef == null || dbRef.getAccessionId() == null
336               || dbRef.getSource() == null)
337       {
338         continue;
339       }
340       if (isValidDBRefEntry(dbRef)
341               && dbRef.isPrimary()
342               && (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT) || dbRef
343                       .getSource().equalsIgnoreCase(DBRefSource.PDB)))
344       {
345         return dbRef;
346       }
347     }
348     throw new SiftsException("Could not get source DB Ref");
349   }
350
351   /**
352    * Check that the DBRef Entry is properly populated and is available in this
353    * SiftClient instance
354    * 
355    * @param entry
356    *          - DBRefEntry to validate
357    * @return true validation is successful otherwise false is returned.
358    */
359   boolean isValidDBRefEntry(DBRefEntryI entry)
360   {
361     return entry != null && entry.getAccessionId() != null
362             && isFoundInSiftsEntry(entry.getAccessionId());
363   }
364
365   @Override
366   public HashSet<String> getAllMappingAccession()
367   {
368     HashSet<String> accessions = new HashSet<String>();
369     List<Entity> entities = siftsEntry.getEntity();
370     for (Entity entity : entities)
371     {
372       List<Segment> segments = entity.getSegment();
373       for (Segment segment : segments)
374       {
375         List<MapRegion> mapRegions = segment.getListMapRegion()
376                 .getMapRegion();
377         for (MapRegion mapRegion : mapRegions)
378         {
379           accessions
380                   .add(mapRegion.getDb().getDbAccessionId().toLowerCase());
381         }
382       }
383     }
384     return accessions;
385   }
386
387   @Override
388   public StructureMapping getSiftsStructureMapping(SequenceI seq,
389           String pdbFile, String chain) throws SiftsException
390   {
391     structId = (chain == null) ? pdbId : pdbId + "|" + chain;
392     System.out.println("Getting mapping for: " + pdbId + "|" + chain
393             + " : seq- " + seq.getName());
394
395     final StringBuilder mappingDetails = new StringBuilder(128);
396     PrintStream ps = new PrintStream(System.out)
397     {
398       @Override
399       public void print(String x)
400       {
401         mappingDetails.append(x);
402       }
403
404       @Override
405       public void println()
406       {
407         mappingDetails.append(NEWLINE);
408       }
409     };
410     HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
411
412     String mappingOutput = mappingDetails.toString();
413     StructureMapping siftsMapping = new StructureMapping(seq, pdbFile,
414             pdbId, chain, mapping, mappingOutput);
415     return siftsMapping;
416   }
417
418   @Override
419   public HashMap<Integer, int[]> getGreedyMapping(String entityId,
420           SequenceI seq, java.io.PrintStream os) throws SiftsException
421   {
422     List<Integer> omitNonObserved = new ArrayList<Integer>();
423     int nonObservedShiftIndex = 0;
424     // System.out.println("Generating mappings for : " + entityId);
425     Entity entity = null;
426     entity = getEntityById(entityId);
427     String originalSeq = AlignSeq.extractGaps(
428             jalview.util.Comparison.GapChars, seq.getSequenceAsString());
429     HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
430     DBRefEntryI sourceDBRef;
431     sourceDBRef = getValidSourceDBRef(seq);
432     // TODO ensure sequence start/end is in the same coordinate system and
433     // consistent with the choosen sourceDBRef
434
435     // set sequence coordinate system - default value is UniProt
436     if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
437     {
438       seqCoordSys = CoordinateSys.PDB;
439     }
440
441     HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
442     for (DBRefEntry dbref : seq.getDBRefs())
443     {
444       dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
445     }
446     dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
447
448     curDBRefAccessionIdsString = dbRefAccessionIdsString;
449     curSourceDBRef = sourceDBRef.getAccessionId();
450
451     TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
452     List<Segment> segments = entity.getSegment();
453     SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
454             omitNonObserved, nonObservedShiftIndex);
455     processSegments(segments, shp);
456     try
457     {
458       populateAtomPositions(entityId, mapping);
459     } catch (Exception e)
460     {
461       e.printStackTrace();
462     }
463     if (seqCoordSys == CoordinateSys.UNIPROT)
464     {
465       padWithGaps(resNumMap, omitNonObserved);
466     }
467     int seqStart = UNASSIGNED;
468     int seqEnd = UNASSIGNED;
469     int pdbStart = UNASSIGNED;
470     int pdbEnd = UNASSIGNED;
471
472     Integer[] keys = mapping.keySet().toArray(new Integer[0]);
473     Arrays.sort(keys);
474     if (keys.length < 1)
475     {
476       throw new SiftsException(">>> Empty SIFTS mapping generated!!");
477     }
478     seqStart = keys[0];
479     seqEnd = keys[keys.length - 1];
480
481     String matchedSeq = originalSeq;
482     if (seqStart != UNASSIGNED)
483     {
484       pdbStart = mapping.get(seqStart)[PDB_RES_POS];
485       pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
486       int orignalSeqStart = seq.getStart();
487       if (orignalSeqStart >= 1)
488       {
489         int subSeqStart = (seqStart >= orignalSeqStart) ? seqStart
490                 - orignalSeqStart : 0;
491         int subSeqEnd = seqEnd - (orignalSeqStart - 1);
492         subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
493                 : subSeqEnd;
494         matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
495       }
496       else
497       {
498         matchedSeq = originalSeq.substring(1, originalSeq.length());
499       }
500     }
501
502     StringBuilder targetStrucSeqs = new StringBuilder();
503     for (String res : resNumMap.values())
504     {
505       targetStrucSeqs.append(res);
506     }
507
508     if (os != null)
509     {
510       MappingOutputPojo mop = new MappingOutputPojo();
511       mop.setSeqStart(pdbStart);
512       mop.setSeqEnd(pdbEnd);
513       mop.setSeqName(seq.getName());
514       mop.setSeqResidue(matchedSeq);
515
516       mop.setStrStart(seqStart);
517       mop.setStrEnd(seqEnd);
518       mop.setStrName(structId);
519       mop.setStrResidue(targetStrucSeqs.toString());
520
521       mop.setType("pep");
522       os.print(getMappingOutput(mop).toString());
523       os.println();
524     }
525     return mapping;
526   }
527
528   void processSegments(List<Segment> segments, SegmentHelperPojo shp)
529   {
530     SequenceI seq = shp.getSeq();
531     HashMap<Integer, int[]> mapping = shp.getMapping();
532     TreeMap<Integer, String> resNumMap = shp.getResNumMap();
533     List<Integer> omitNonObserved = shp.getOmitNonObserved();
534     int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
535     for (Segment segment : segments)
536     {
537       // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
538       // + segStartEnd);
539       List<Residue> residues = segment.getListResidue().getResidue();
540       for (Residue residue : residues)
541       {
542         int currSeqIndex = UNASSIGNED;
543         List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
544         CrossRefDb pdbRefDb = null;
545         for (CrossRefDb cRefDb : cRefDbs)
546         {
547           if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
548           {
549             pdbRefDb = cRefDb;
550           }
551           if (cRefDb.getDbCoordSys()
552                   .equalsIgnoreCase(seqCoordSys.getName())
553                   && isAccessionMatched(cRefDb.getDbAccessionId()))
554           {
555             String resNumIndexString = cRefDb.getDbResNum()
556                     .equalsIgnoreCase("None") ? String.valueOf(UNASSIGNED)
557                     : cRefDb.getDbResNum();
558             try
559             {
560               currSeqIndex = Integer.valueOf(resNumIndexString);
561             } catch (NumberFormatException nfe)
562             {
563               currSeqIndex = Integer.valueOf(resNumIndexString
564                       .split("[a-zA-Z]")[0]);
565               continue;
566             }
567             if (pdbRefDb != null)
568             {
569               break;// exit loop if pdb and uniprot are already found
570             }
571           }
572         }
573         if (currSeqIndex == UNASSIGNED)
574         {
575           continue;
576         }
577         if (currSeqIndex >= seq.getStart() && currSeqIndex <= seq.getEnd())
578         {
579           int resNum;
580           try
581           {
582             resNum = (pdbRefDb == null) ? Integer.valueOf(residue
583                     .getDbResNum()) : Integer.valueOf(pdbRefDb
584                     .getDbResNum());
585           } catch (NumberFormatException nfe)
586           {
587             resNum = (pdbRefDb == null) ? Integer.valueOf(residue
588                     .getDbResNum()) : Integer.valueOf(pdbRefDb
589                     .getDbResNum().split("[a-zA-Z]")[0]);
590             continue;
591           }
592
593           if (isResidueObserved(residue)
594                   || seqCoordSys == CoordinateSys.UNIPROT)
595           {
596             char resCharCode = ResidueProperties
597                     .getSingleCharacterCode(ResidueProperties
598                             .getCanonicalAminoAcid(residue.getDbResName()));
599             resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
600           }
601           else
602           {
603             omitNonObserved.add(currSeqIndex);
604             ++nonObservedShiftIndex;
605           }
606           mapping.put(currSeqIndex - nonObservedShiftIndex, new int[] {
607               Integer.valueOf(resNum), UNASSIGNED });
608         }
609       }
610     }
611   }
612   /**
613    * 
614    * @param chainId
615    *          Target chain to populate mapping of its atom positions.
616    * @param mapping
617    *          Two dimension array of residue index versus atom position
618    * @throws IllegalArgumentException
619    *           Thrown if chainId or mapping is null
620    * @throws SiftsException
621    */
622   void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
623           throws IllegalArgumentException, SiftsException
624   {
625     try
626     {
627       PDBChain chain = pdb.findChain(chainId);
628
629       if (chain == null || mapping == null)
630       {
631         throw new IllegalArgumentException(
632                 "Chain id or mapping must not be null.");
633       }
634       for (int[] map : mapping.values())
635       {
636         if (map[PDB_RES_POS] != UNASSIGNED)
637         {
638           map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
639         }
640       }
641     } catch (NullPointerException e)
642     {
643       throw new SiftsException(e.getMessage());
644     } catch (Exception e)
645     {
646       throw new SiftsException(e.getMessage());
647     }
648   }
649
650   /**
651    * 
652    * @param residueIndex
653    *          The residue index used for the search
654    * @param atoms
655    *          A collection of Atom to search
656    * @return atom position for the given residue index
657    */
658   int getAtomIndex(int residueIndex, Collection<Atom> atoms)
659   {
660     if (atoms == null)
661     {
662       throw new IllegalArgumentException(
663               "atoms collection must not be null!");
664     }
665     for (Atom atom : atoms)
666     {
667       if (atom.resNumber == residueIndex)
668       {
669         return atom.atomIndex;
670       }
671     }
672     return UNASSIGNED;
673   }
674
675   /**
676    * Checks if the residue instance is marked 'Not_observed' or not
677    * 
678    * @param residue
679    * @return
680    */
681   private boolean isResidueObserved(Residue residue)
682   {
683     Set<String> annotations = getResidueAnnotaitons(residue,
684             ResidueDetailType.ANNOTATION);
685     if (annotations == null || annotations.isEmpty())
686     {
687       return true;
688     }
689     for (String annotation : annotations)
690     {
691       if (annotation.equalsIgnoreCase(NOT_OBSERVED))
692       {
693         return false;
694       }
695     }
696     return true;
697   }
698
699   /**
700    * Get annotation String for a given residue and annotation type
701    * 
702    * @param residue
703    * @param type
704    * @return
705    */
706   private Set<String> getResidueAnnotaitons(Residue residue,
707           ResidueDetailType type)
708   {
709     HashSet<String> foundAnnotations = new HashSet<String>();
710     List<ResidueDetail> resDetails = residue.getResidueDetail();
711     for (ResidueDetail resDetail : resDetails)
712     {
713       if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
714       {
715         foundAnnotations.add(resDetail.getContent());
716       }
717     }
718     return foundAnnotations;
719   }
720
721   @Override
722   public boolean isAccessionMatched(String accession)
723   {
724     boolean isStrictMatch = true;
725     return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
726             : curDBRefAccessionIdsString.contains(accession.toLowerCase());
727   }
728
729   private boolean isFoundInSiftsEntry(String accessionId)
730   {
731     Set<String> siftsDBRefs = getAllMappingAccession();
732     return accessionId != null
733             && siftsDBRefs.contains(accessionId.toLowerCase());
734   }
735
736   /**
737    * Pad omitted residue positions in PDB sequence with gaps
738    * 
739    * @param resNumMap
740    */
741   void padWithGaps(Map<Integer, String> resNumMap,
742           List<Integer> omitNonObserved)
743   {
744     if (resNumMap == null || resNumMap.isEmpty())
745     {
746       return;
747     }
748     Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
749     // Arrays.sort(keys);
750     int firstIndex = keys[0];
751     int lastIndex = keys[keys.length - 1];
752     // System.out.println("Min value " + firstIndex);
753     // System.out.println("Max value " + lastIndex);
754     for (int x = firstIndex; x <= lastIndex; x++)
755     {
756       if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
757       {
758         resNumMap.put(x, "-");
759       }
760     }
761   }
762
763
764
765   @Override
766   public Entity getEntityById(String id) throws SiftsException
767   {
768     // Determines an entity to process by performing a heuristic matching of all
769     // Entities with the given chainId and choosing the best matching Entity
770     Entity entity = getEntityByMostOptimalMatchedId(id);
771     if (entity != null)
772     {
773       return entity;
774     }
775     throw new SiftsException("Entity " + id + " not found");
776   }
777
778   /**
779    * This method was added because EntityId is NOT always equal to ChainId.
780    * Hence, it provides the logic to greedily detect the "true" Entity for a
781    * given chainId where discrepancies exist.
782    * 
783    * @param chainId
784    * @return
785    */
786   public Entity getEntityByMostOptimalMatchedId(String chainId)
787   {
788     // System.out.println("---> advanced greedy entityId matching block entered..");
789     List<Entity> entities = siftsEntry.getEntity();
790     SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
791     int count = 0;
792     for (Entity entity : entities)
793     {
794       sPojo[count] = new SiftsEntitySortPojo();
795       sPojo[count].entityId = entity.getEntityId();
796
797       List<Segment> segments = entity.getSegment();
798       for (Segment segment : segments)
799       {
800         List<Residue> residues = segment.getListResidue().getResidue();
801         for (Residue residue : residues)
802         {
803           List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
804           for (CrossRefDb cRefDb : cRefDbs)
805           {
806             if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
807             {
808               continue;
809             }
810             ++sPojo[count].resCount;
811             if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
812             {
813               ++sPojo[count].chainIdFreq;
814             }
815           }
816         }
817       }
818       sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
819               / sPojo[count].resCount;
820       ++count;
821     }
822     Arrays.sort(sPojo, Collections.reverseOrder());
823     // System.out.println("highest matched entity : " + sPojo[0].entityId);
824     // System.out.println("highest matched pid : " + sPojo[0].pid);
825
826     if (sPojo[0].entityId != null)
827     {
828       for (Entity entity : entities)
829       {
830         if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
831         {
832           continue;
833         }
834         return entity;
835       }
836     }
837     return null;
838   }
839
840   private class SiftsEntitySortPojo implements
841           Comparable<SiftsEntitySortPojo>
842   {
843     public String entityId;
844
845     public int chainIdFreq;
846
847     public int pid;
848
849     public int resCount;
850
851     @Override
852     public int compareTo(SiftsEntitySortPojo o)
853     {
854       return this.pid - o.pid;
855     }
856   }
857
858   private class SegmentHelperPojo
859   {
860     private SequenceI seq;
861
862     private HashMap<Integer, int[]> mapping;
863
864     private TreeMap<Integer, String> resNumMap;
865
866     private List<Integer> omitNonObserved;
867
868     private int nonObservedShiftIndex;
869
870     public SegmentHelperPojo(SequenceI seq,
871             HashMap<Integer, int[]> mapping,
872             TreeMap<Integer, String> resNumMap,
873             List<Integer> omitNonObserved, int nonObservedShiftIndex)
874     {
875       setSeq(seq);
876       setMapping(mapping);
877       setResNumMap(resNumMap);
878       setOmitNonObserved(omitNonObserved);
879       setNonObservedShiftIndex(nonObservedShiftIndex);
880     }
881
882     public SequenceI getSeq()
883     {
884       return seq;
885     }
886
887     public void setSeq(SequenceI seq)
888     {
889       this.seq = seq;
890     }
891
892     public HashMap<Integer, int[]> getMapping()
893     {
894       return mapping;
895     }
896
897     public void setMapping(HashMap<Integer, int[]> mapping)
898     {
899       this.mapping = mapping;
900     }
901
902     public TreeMap<Integer, String> getResNumMap()
903     {
904       return resNumMap;
905     }
906
907     public void setResNumMap(TreeMap<Integer, String> resNumMap)
908     {
909       this.resNumMap = resNumMap;
910     }
911
912     public List<Integer> getOmitNonObserved()
913     {
914       return omitNonObserved;
915     }
916
917     public void setOmitNonObserved(List<Integer> omitNonObserved)
918     {
919       this.omitNonObserved = omitNonObserved;
920     }
921
922     public int getNonObservedShiftIndex()
923     {
924       return nonObservedShiftIndex;
925     }
926
927     public void setNonObservedShiftIndex(int nonObservedShiftIndex)
928     {
929       this.nonObservedShiftIndex = nonObservedShiftIndex;
930     }
931   }
932
933   @Override
934   public StringBuffer getMappingOutput(MappingOutputPojo mp)
935           throws SiftsException
936   {
937     String seqRes = mp.getSeqResidue();
938     String seqName = mp.getSeqName();
939     int sStart = mp.getSeqStart();
940     int sEnd = mp.getSeqEnd();
941
942     String strRes = mp.getStrResidue();
943     String strName = mp.getStrName();
944     int pdbStart = mp.getStrStart();
945     int pdbEnd = mp.getStrEnd();
946
947     String type = mp.getType();
948
949     int maxid = (seqName.length() >= strName.length()) ? seqName.length()
950             : strName.length();
951     int len = 72 - maxid - 1;
952
953     int nochunks = ((seqRes.length()) / len)
954             + ((seqRes.length()) % len > 0 ? 1 : 0);
955     // output mappings
956     StringBuffer output = new StringBuffer();
957     output.append(NEWLINE);
958     output.append("Sequence \u27f7 Structure mapping details").append(
959             NEWLINE);
960     output.append("Method: SIFTS");
961     output.append(NEWLINE).append(NEWLINE);
962
963     output.append(new Format("%" + maxid + "s").form(seqName));
964     output.append(" :  ");
965     output.append(String.valueOf(sStart));
966     output.append(" - ");
967     output.append(String.valueOf(sEnd));
968     output.append(" Maps to ");
969     output.append(NEWLINE);
970     output.append(new Format("%" + maxid + "s").form(structId));
971     output.append(" :  ");
972     output.append(String.valueOf(pdbStart));
973     output.append(" - ");
974     output.append(String.valueOf(pdbEnd));
975     output.append(NEWLINE).append(NEWLINE);
976
977     int matchedSeqCount = 0;
978     for (int j = 0; j < nochunks; j++)
979     {
980       // Print the first aligned sequence
981       output.append(new Format("%" + (maxid) + "s").form(seqName)).append(
982               " ");
983
984       for (int i = 0; i < len; i++)
985       {
986         if ((i + (j * len)) < seqRes.length())
987         {
988           output.append(seqRes.charAt(i + (j * len)));
989         }
990       }
991
992       output.append(NEWLINE);
993       output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
994
995       // Print out the matching chars
996       for (int i = 0; i < len; i++)
997       {
998         try
999         {
1000           if ((i + (j * len)) < seqRes.length())
1001           {
1002             if (seqRes.charAt(i + (j * len)) == strRes
1003                     .charAt(i + (j * len))
1004                     && !jalview.util.Comparison.isGap(seqRes.charAt(i
1005                             + (j * len))))
1006             {
1007               matchedSeqCount++;
1008               output.append("|");
1009             }
1010             else if (type.equals("pep"))
1011             {
1012               if (ResidueProperties.getPAM250(seqRes.charAt(i + (j * len)),
1013                       strRes.charAt(i + (j * len))) > 0)
1014               {
1015                 output.append(".");
1016               }
1017               else
1018               {
1019                 output.append(" ");
1020               }
1021             }
1022             else
1023             {
1024               output.append(" ");
1025             }
1026           }
1027         } catch (IndexOutOfBoundsException e)
1028         {
1029           continue;
1030         }
1031       }
1032       // Now print the second aligned sequence
1033       output = output.append(NEWLINE);
1034       output = output.append(new Format("%" + (maxid) + "s").form(strName))
1035               .append(" ");
1036       for (int i = 0; i < len; i++)
1037       {
1038         if ((i + (j * len)) < strRes.length())
1039         {
1040           output.append(strRes.charAt(i + (j * len)));
1041         }
1042       }
1043       output.append(NEWLINE).append(NEWLINE);
1044     }
1045     float pid = (float) matchedSeqCount / seqRes.length() * 100;
1046     if (pid < SiftsSettings.getFailSafePIDThreshold())
1047     {
1048       throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1049     }
1050     output.append("Length of alignment = " + seqRes.length()).append(
1051             NEWLINE);
1052     output.append(new Format("Percentage ID = %2.2f").form(pid));
1053     return output;
1054   }
1055
1056   @Override
1057   public int getEntityCount()
1058   {
1059     return siftsEntry.getEntity().size();
1060   }
1061
1062   @Override
1063   public String getDbAccessionId()
1064   {
1065     return siftsEntry.getDbAccessionId();
1066   }
1067
1068   @Override
1069   public String getDbCoordSys()
1070   {
1071     return siftsEntry.getDbCoordSys();
1072   }
1073
1074   @Override
1075   public String getDbSource()
1076   {
1077     return siftsEntry.getDbSource();
1078   }
1079
1080   @Override
1081   public String getDbVersion()
1082   {
1083     return siftsEntry.getDbVersion();
1084   }
1085
1086 }