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