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