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