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