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