f25c1cf7d551363c58f4f9198fad065f38c433ff
[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             continue;
547           }
548
549           if (isResidueObserved(residue)
550                   || seqCoordSys == CoordinateSys.UNIPROT)
551           {
552             char resCharCode = ResidueProperties
553                     .getSingleCharacterCode(ResidueProperties
554                             .getCanonicalAminoAcid(residue.getDbResName()));
555             resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
556           }
557           else
558           {
559             omitNonObserved.add(currSeqIndex);
560             ++nonObservedShiftIndex;
561           }
562           mapping.put(currSeqIndex - nonObservedShiftIndex, new int[] {
563               Integer.valueOf(resNum), UNASSIGNED });
564         }
565       }
566     }
567     try
568     {
569       populateAtomPositions(entityId, mapping);
570     } catch (Exception e)
571     {
572       e.printStackTrace();
573     }
574     if (seqCoordSys == CoordinateSys.UNIPROT)
575     {
576       padWithGaps(resNumMap, omitNonObserved);
577     }
578     int seqStart = UNASSIGNED;
579     int seqEnd = UNASSIGNED;
580     int pdbStart = UNASSIGNED;
581     int pdbEnd = UNASSIGNED;
582
583     Integer[] keys = mapping.keySet().toArray(new Integer[0]);
584     Arrays.sort(keys);
585     if (keys.length < 1)
586     {
587       throw new SiftsException(">>> Empty SIFTS mapping generated!!");
588     }
589     seqStart = keys[0];
590     seqEnd = keys[keys.length - 1];
591
592     String matchedSeq = originalSeq;
593     if (seqStart != UNASSIGNED)
594     {
595       pdbStart = mapping.get(seqStart)[PDB_RES_POS];
596       pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
597       int orignalSeqStart = seq.getStart();
598       if (orignalSeqStart >= 1)
599       {
600         int subSeqStart = (seqStart >= orignalSeqStart) ? seqStart
601                 - orignalSeqStart : 0;
602         int subSeqEnd = seqEnd - (orignalSeqStart - 1);
603         subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
604                 : subSeqEnd;
605         matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
606       }
607       else
608       {
609         matchedSeq = originalSeq.substring(1, originalSeq.length());
610       }
611     }
612
613     StringBuilder targetStrucSeqs = new StringBuilder();
614     for (String res : resNumMap.values())
615     {
616       targetStrucSeqs.append(res);
617     }
618
619     if (os != null)
620     {
621       MappingOutputPojo mop = new MappingOutputPojo();
622       mop.setSeqStart(pdbStart);
623       mop.setSeqEnd(pdbEnd);
624       mop.setSeqName(seq.getName());
625       mop.setSeqResidue(matchedSeq);
626
627       mop.setStrStart(seqStart);
628       mop.setStrEnd(seqEnd);
629       mop.setStrName(structId);
630       mop.setStrResidue(targetStrucSeqs.toString());
631
632       mop.setType("pep");
633       os.print(getMappingOutput(mop).toString());
634     }
635     return mapping;
636   }
637
638   /**
639    * 
640    * @param chainId
641    *          Target chain to populate mapping of its atom positions.
642    * @param mapping
643    *          Two dimension array of residue index versus atom position
644    * @throws IllegalArgumentException
645    *           Thrown if chainId or mapping is null
646    */
647   void populateAtomPositions(String chainId,
648           HashMap<Integer, int[]> mapping) throws IllegalArgumentException
649   {
650     PDBChain chain = pdb.findChain(chainId);
651     if (chain == null || mapping == null)
652     {
653       throw new IllegalArgumentException(
654               "Chain id or mapping must not be null.");
655     }
656     for (int[] map : mapping.values())
657     {
658       if (map[PDB_RES_POS] != UNASSIGNED)
659       {
660         map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
661       }
662     }
663   }
664
665   /**
666    * 
667    * @param residueIndex
668    *          The residue index used for the search
669    * @param atoms
670    *          A collection of Atom to search
671    * @return atom position for the given residue index
672    */
673   int getAtomIndex(int residueIndex, Collection<Atom> atoms)
674   {
675     if (atoms == null)
676     {
677       throw new IllegalArgumentException(
678               "atoms collection must not be null!");
679     }
680     for (Atom atom : atoms)
681     {
682       if (atom.resNumber == residueIndex)
683       {
684         return atom.atomIndex;
685       }
686     }
687     return UNASSIGNED;
688   }
689
690   /**
691    * Checks if the residue instance is marked 'Not_observed' or not
692    * 
693    * @param residue
694    * @return
695    */
696   private boolean isResidueObserved(Residue residue)
697   {
698     HashSet<String> annotations = getResidueAnnotaitons(residue,
699             ResidueDetailType.ANNOTATION);
700     if (annotations == null || annotations.isEmpty())
701     {
702       return true;
703     }
704     for (String annotation : annotations)
705     {
706       if (annotation.equalsIgnoreCase(NOT_OBSERVED))
707       {
708         return false;
709       }
710     }
711     return true;
712   }
713
714   /**
715    * Get annotation String for a given residue and annotation type
716    * 
717    * @param residue
718    * @param type
719    * @return
720    */
721   private HashSet<String> getResidueAnnotaitons(Residue residue,
722           ResidueDetailType type)
723   {
724     HashSet<String> foundAnnotations = new HashSet<String>();
725     List<ResidueDetail> resDetails = residue.getResidueDetail();
726     for (ResidueDetail resDetail : resDetails)
727     {
728       if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
729       {
730         foundAnnotations.add(resDetail.getContent());
731       }
732     }
733     return foundAnnotations;
734   }
735
736   @Override
737   public boolean isAccessionMatched(String accession)
738   {
739     boolean isStrictMatch = true;
740     return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
741             : curDBRefAccessionIdsString.contains(accession.toLowerCase());
742   }
743
744   private boolean isFoundInSiftsEntry(String accessionId)
745   {
746     return accessionId != null
747             && getAllMappingAccession().contains(accessionId);
748   }
749
750   /**
751    * Pad omitted residue positions in PDB sequence with gaps
752    * 
753    * @param resNumMap
754    */
755   void padWithGaps(TreeMap<Integer, String> resNumMap,
756           ArrayList<Integer> omitNonObserved)
757   {
758     if (resNumMap == null || resNumMap.isEmpty())
759     {
760       return;
761     }
762     Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
763     Arrays.sort(keys);
764     int firstIndex = keys[0];
765     int lastIndex = keys[keys.length - 1];
766     System.out.println("Min value " + firstIndex);
767     System.out.println("Max value " + lastIndex);
768     for (int x = firstIndex; x <= lastIndex; x++)
769     {
770       if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
771       {
772         resNumMap.put(x, "-");
773       }
774     }
775   }
776
777
778
779   @Override
780   public Entity getEntityById(String id) throws SiftsException
781   {
782     // Sometimes SIFTS mappings are wrongly swapped between different chains of
783     // a PDB entry. This results to wrong mappings being generated. The boolean
784     // flag 'isGetEntityIdDirectly, determines whether an entity to process is
785     // determined by a greedy heuristic search or by just matching the Chain Id
786     // directly against the entity Id tag. Setting the default value to 'false'
787     // utilise the heuristic search which always produces correct mappings but
788     // less optimised processing, where as changing the value to 'true'
789     // optimises performance but might result to incorrect mapping in some cases
790     // where SIFTS mappings are wrongly swapped between different chains.
791     boolean isGetEntityIdDirectly = false;
792     if (isGetEntityIdDirectly)
793     {
794       List<Entity> entities = siftsEntry.getEntity();
795       for (Entity entity : entities)
796       {
797         if (!entity.getEntityId().equalsIgnoreCase(id))
798         {
799           continue;
800         }
801         return entity;
802       }
803     }
804     Entity entity = getEntityByMostOptimalMatchedId(id);
805     if (entity != null)
806     {
807       return entity;
808     }
809     throw new SiftsException("Entity " + id + " not found");
810   }
811
812   /**
813    * This method was added because EntityId is NOT always equal to ChainId.
814    * Hence, it provides the logic to greedily detect the "true" Entity for a
815    * given chainId where discrepancies exist.
816    * 
817    * @param chainId
818    * @return
819    */
820   public Entity getEntityByMostOptimalMatchedId(String chainId)
821   {
822     // System.out.println("---> advanced greedy entityId matching block entered..");
823     List<Entity> entities = siftsEntry.getEntity();
824     SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
825     int count = 0;
826     for (Entity entity : entities)
827     {
828       sPojo[count] = new SiftsEntitySortPojo();
829       sPojo[count].entityId = entity.getEntityId();
830
831       List<Segment> segments = entity.getSegment();
832       for (Segment segment : segments)
833       {
834         List<Residue> residues = segment.getListResidue().getResidue();
835         for (Residue residue : residues)
836         {
837           List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
838           for (CrossRefDb cRefDb : cRefDbs)
839           {
840             if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
841             {
842               continue;
843             }
844             ++sPojo[count].resCount;
845             if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
846             {
847               ++sPojo[count].chainIdFreq;
848             }
849           }
850         }
851       }
852       sPojo[count].pid = 100 * (sPojo[count].chainIdFreq / sPojo[count].resCount);
853       ++count;
854     }
855     Arrays.sort(sPojo, Collections.reverseOrder());
856     System.out.println("highest matched entity : " + sPojo[0].entityId);
857     System.out.println("highest matched pid : " + sPojo[0].pid);
858
859     if (sPojo[0].entityId != null)
860     {
861       for (Entity entity : entities)
862       {
863         if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
864         {
865           continue;
866         }
867         return entity;
868       }
869     }
870     return null;
871   }
872
873   public class SiftsEntitySortPojo implements
874           Comparable<SiftsEntitySortPojo>
875   {
876     public String entityId;
877
878     public int chainIdFreq;
879
880     public int pid;
881
882     public int resCount;
883
884     @Override
885     public int compareTo(SiftsEntitySortPojo o)
886     {
887       return this.pid - o.pid;
888     }
889   }
890
891   @Override
892   public String[] getEntryDBs()
893   {
894     System.out.println("\nListing DB entries...");
895     List<String> availDbs = new ArrayList<String>();
896     List<Db> dbs = siftsEntry.getListDB().getDb();
897     for (Db db : dbs)
898     {
899       availDbs.add(db.getDbSource());
900       System.out.println(db.getDbSource() + " | " + db.getDbCoordSys());
901     }
902     return availDbs.toArray(new String[0]);
903   }
904
905   @Override
906   public StringBuffer getMappingOutput(MappingOutputPojo mp)
907           throws SiftsException
908   {
909     String seqRes = mp.getSeqResidue();
910     String seqName = mp.getSeqName();
911     int sStart = mp.getSeqStart();
912     int sEnd = mp.getSeqEnd();
913
914     String strRes = mp.getStrResidue();
915     String strName = mp.getStrName();
916     int pdbStart = mp.getStrStart();
917     int pdbEnd = mp.getStrEnd();
918
919     String type = mp.getType();
920
921     int maxid = (seqName.length() >= strName.length()) ? seqName.length()
922             : strName.length();
923     int len = 72 - maxid - 1;
924
925     int nochunks = ((seqRes.length()) / len)
926             + ((seqRes.length()) % len > 0 ? 1 : 0);
927     // output mappings
928     StringBuffer output = new StringBuffer();
929     output.append(NEWLINE);
930     output.append("Sequence ⟷ Structure mapping details").append(NEWLINE);
931     output.append("Method: SIFTS");
932     output.append(NEWLINE).append(NEWLINE);
933
934     output.append(new Format("%" + maxid + "s").form(seqName));
935     output.append(" :  ");
936     output.append(String.valueOf(sStart));
937     output.append(" - ");
938     output.append(String.valueOf(sEnd));
939     output.append(" Maps to ");
940     output.append(NEWLINE);
941     output.append(new Format("%" + maxid + "s").form(structId));
942     output.append(" :  ");
943     output.append(String.valueOf(pdbStart));
944     output.append(" - ");
945     output.append(String.valueOf(pdbEnd));
946     output.append(NEWLINE).append(NEWLINE);
947
948     int matchedSeqCount = 0;
949     for (int j = 0; j < nochunks; j++)
950     {
951       // Print the first aligned sequence
952       output.append(new Format("%" + (maxid) + "s").form(seqName)).append(
953               " ");
954
955       for (int i = 0; i < len; i++)
956       {
957         if ((i + (j * len)) < seqRes.length())
958         {
959           output.append(seqRes.charAt(i + (j * len)));
960         }
961       }
962
963       output.append(NEWLINE);
964       output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
965
966       // Print out the matching chars
967       for (int i = 0; i < len; i++)
968       {
969         try
970         {
971           if ((i + (j * len)) < seqRes.length())
972           {
973             if (seqRes.charAt(i + (j * len)) == strRes
974                     .charAt(i + (j * len))
975                     && !jalview.util.Comparison.isGap(seqRes.charAt(i
976                             + (j * len))))
977             {
978               matchedSeqCount++;
979               output.append("|");
980             }
981             else if (type.equals("pep"))
982             {
983               if (ResidueProperties.getPAM250(seqRes.charAt(i + (j * len)),
984                       strRes.charAt(i + (j * len))) > 0)
985               {
986                 output.append(".");
987               }
988               else
989               {
990                 output.append(" ");
991               }
992             }
993             else
994             {
995               output.append(" ");
996             }
997           }
998         } catch (IndexOutOfBoundsException e)
999         {
1000           continue;
1001         }
1002       }
1003       // Now print the second aligned sequence
1004       output = output.append(NEWLINE);
1005       output = output.append(new Format("%" + (maxid) + "s").form(strName))
1006               .append(" ");
1007       for (int i = 0; i < len; i++)
1008       {
1009         if ((i + (j * len)) < strRes.length())
1010         {
1011           output.append(strRes.charAt(i + (j * len)));
1012         }
1013       }
1014       output.append(NEWLINE).append(NEWLINE);
1015     }
1016     float pid = (float) matchedSeqCount / seqRes.length() * 100;
1017     if (pid < SiftsSettings.getFailSafePIDThreshold())
1018     {
1019       throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1020     }
1021     output.append("Length of alignment = " + seqRes.length()).append(
1022             NEWLINE);
1023     output.append(new Format("Percentage ID = %2.2f").form(pid));
1024     output.append(NEWLINE);
1025     return output;
1026   }
1027
1028   @Override
1029   public int getEntityCount()
1030   {
1031     return siftsEntry.getEntity().size();
1032   }
1033
1034   @Override
1035   public String getDbAccessionId()
1036   {
1037     return siftsEntry.getDbAccessionId();
1038   }
1039
1040   @Override
1041   public String getDbCoordSys()
1042   {
1043     return siftsEntry.getDbCoordSys();
1044   }
1045
1046   @Override
1047   public String getDbEvidence()
1048   {
1049     return siftsEntry.getDbEvidence();
1050   }
1051
1052   @Override
1053   public String getDbSource()
1054   {
1055     return siftsEntry.getDbSource();
1056   }
1057
1058   @Override
1059   public String getDbVersion()
1060   {
1061     return siftsEntry.getDbVersion();
1062   }
1063
1064 }