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