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