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