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