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