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