Merge branch 'develop' into update_212_Dec_merge_with_21125_chamges
[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 (Platform.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.add(mapRegion.getDb().getDbAccessionId()
430                   .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
501               .add(dbref.getAccessionId().toLowerCase(Locale.ROOT));
502     }
503     dbRefAccessionIdsString
504             .add(sourceDBRef.getAccessionId().toLowerCase(Locale.ROOT));
505
506     curDBRefAccessionIdsString = dbRefAccessionIdsString;
507     curSourceDBRef = sourceDBRef.getAccessionId();
508
509     TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
510     List<Segment> segments = entity.getSegment();
511     SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
512             omitNonObserved, nonObservedShiftIndex,pdbeNonObserved);
513     processSegments(segments, shp);
514     try
515     {
516       populateAtomPositions(entityId, mapping);
517     } catch (Exception e)
518     {
519       e.printStackTrace();
520     }
521     if (seqCoordSys == CoordinateSys.UNIPROT)
522     {
523       padWithGaps(resNumMap, omitNonObserved);
524     }
525     int seqStart = UNASSIGNED;
526     int seqEnd = UNASSIGNED;
527     int pdbStart = UNASSIGNED;
528     int pdbEnd = UNASSIGNED;
529
530     if (mapping.isEmpty())
531     {
532       throw new SiftsException("SIFTS mapping failed");
533     }
534     // also construct a mapping object between the seq-coord sys and the PDB seq's coord sys
535
536     Integer[] keys = mapping.keySet().toArray(new Integer[0]);
537     Arrays.sort(keys);
538     seqStart = keys[0];
539     seqEnd = keys[keys.length - 1];
540     List<int[]> from=new ArrayList<>(),to=new ArrayList<>();
541     int[]_cfrom=null,_cto=null;
542     String matchedSeq = originalSeq;
543     if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb sequence that starts <-1
544     {
545       for (int seqps:keys)
546       {
547         int pdbpos = mapping.get(seqps)[PDBE_POS];
548         if (pdbpos == UNASSIGNED)
549         {
550           // not correct - pdbpos might be -1, but leave it for now
551           continue;
552         }
553         if (_cfrom==null || seqps!=_cfrom[1]+1)
554         {
555           _cfrom = new int[] { seqps,seqps};
556           from.add(_cfrom);
557           _cto = null; // discontinuity
558         } else {
559           _cfrom[1]= seqps;
560         }
561         if (_cto==null || pdbpos!=1+_cto[1])
562         {
563           _cto = new int[] { pdbpos,pdbpos};
564           to.add(_cto);
565         } else {
566           _cto[1] = pdbpos;
567         }
568       }
569       _cfrom = new int[from.size() * 2];
570       _cto = new int[to.size() * 2];
571       int p = 0;
572       for (int[] range : from)
573       {
574         _cfrom[p++] = range[0];
575         _cfrom[p++] = range[1];
576       }
577       ;
578       p = 0;
579       for (int[] range : to)
580       {
581         _cto[p++] = range[0];
582         _cto[p++] = range[1];
583       }
584       ;
585
586       seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
587               1,
588               1);
589       pdbStart = mapping.get(seqStart)[PDB_RES_POS];
590       pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
591       int orignalSeqStart = seq.getStart();
592       if (orignalSeqStart >= 1)
593       {
594         int subSeqStart = (seqStart >= orignalSeqStart)
595                 ? seqStart - orignalSeqStart
596                 : 0;
597         int subSeqEnd = seqEnd - (orignalSeqStart - 1);
598         subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
599                 : subSeqEnd;
600         matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
601       }
602       else
603       {
604         matchedSeq = originalSeq.substring(1, originalSeq.length());
605       }
606     }
607
608     StringBuilder targetStrucSeqs = new StringBuilder();
609     for (String res : resNumMap.values())
610     {
611       targetStrucSeqs.append(res);
612     }
613
614     if (os != null)
615     {
616       MappingOutputPojo mop = new MappingOutputPojo();
617       mop.setSeqStart(seqStart);
618       mop.setSeqEnd(seqEnd);
619       mop.setSeqName(seq.getName());
620       mop.setSeqResidue(matchedSeq);
621
622       mop.setStrStart(pdbStart);
623       mop.setStrEnd(pdbEnd);
624       mop.setStrName(structId);
625       mop.setStrResidue(targetStrucSeqs.toString());
626
627       mop.setType("pep");
628       os.print(getMappingOutput(mop).toString());
629       os.println();
630     }
631     return mapping;
632   }
633
634   void processSegments(List<Segment> segments, SegmentHelperPojo shp)
635   {
636     SequenceI seq = shp.getSeq();
637     HashMap<Integer, int[]> mapping = shp.getMapping();
638     TreeMap<Integer, String> resNumMap = shp.getResNumMap();
639     List<Integer> omitNonObserved = shp.getOmitNonObserved();
640     int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
641     int pdbeNonObservedCount = shp.getPdbeNonObserved();
642     int firstPDBResNum = UNASSIGNED;
643     for (Segment segment : segments)
644     {
645       // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
646       // + segStartEnd);
647       List<Residue> residues = segment.getListResidue().getResidue();
648       for (Residue residue : residues)
649       {
650         boolean isObserved = isResidueObserved(residue);
651         int pdbeIndex = Platform.getLeadingIntegerValue(residue.getDbResNum(),
652                 UNASSIGNED);
653         int currSeqIndex = UNASSIGNED;
654         List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
655         CrossRefDb pdbRefDb = null;
656         for (CrossRefDb cRefDb : cRefDbs)
657         {
658           if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
659           {
660             pdbRefDb = cRefDb;
661             if (firstPDBResNum == UNASSIGNED)
662             {
663               firstPDBResNum = Platform.getLeadingIntegerValue(cRefDb.getDbResNum(),
664                       UNASSIGNED);
665             }
666             else
667             {
668               if (isObserved)
669               {
670                 // after we find the first observed residue we just increment
671                 firstPDBResNum++;
672               }
673             }
674           }
675           if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
676                   && isAccessionMatched(cRefDb.getDbAccessionId()))
677           {
678             currSeqIndex = Platform.getLeadingIntegerValue(cRefDb.getDbResNum(),
679                     UNASSIGNED);
680             if (pdbRefDb != null)
681             {
682               break;// exit loop if pdb and uniprot are already found
683             }
684           }
685         }
686         if (!isObserved)
687         {
688           ++pdbeNonObservedCount;
689         }
690         if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
691                                             // ???
692         {
693           // if the sequence has a primary reference to the PDB, then we are
694           // dealing with a sequence extracted directly from the PDB. In that
695           // case, numbering is PDBe - non-observed residues
696           currSeqIndex = seq.getStart() - 1 + pdbeIndex;
697         }
698         if (!isObserved)
699         {
700           if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
701                                                     // here
702           {
703             // mapping to PDB or PDBe so we need to bookkeep for the
704             // non-observed
705             // SEQRES positions
706             omitNonObserved.add(currSeqIndex);
707             ++nonObservedShiftIndex;
708           }
709         }
710         if (currSeqIndex == UNASSIGNED)
711         {
712           // change in logic - unobserved residues with no currSeqIndex
713           // corresponding are still counted in both nonObservedShiftIndex and
714           // pdbeIndex...
715           continue;
716         }
717         // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
718         // true
719                                                                          // numbering
720                                                                          // is
721                                                                          // not
722                                                                          // up
723                                                                          // to
724                                                                          // seq.getEnd()
725         {
726
727           int resNum = (pdbRefDb == null)
728                   ? Platform.getLeadingIntegerValue(residue.getDbResNum(),
729                           UNASSIGNED)
730                   : Platform.getLeadingIntegerValue(pdbRefDb.getDbResNum(),
731                           UNASSIGNED);
732
733           if (isObserved)
734           {
735             char resCharCode = ResidueProperties
736                     .getSingleCharacterCode(ResidueProperties
737                             .getCanonicalAminoAcid(residue.getDbResName()));
738             resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
739
740             int[] mappingcols = new int[] { Integer.valueOf(resNum),
741                 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
742
743             mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
744           }
745         }
746       }
747     }
748   }
749
750   /**
751    * 
752    * @param chainId
753    *          Target chain to populate mapping of its atom positions.
754    * @param mapping
755    *          Two dimension array of residue index versus atom position
756    * @throws IllegalArgumentException
757    *           Thrown if chainId or mapping is null
758    * @throws SiftsException
759    */
760   void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
761           throws IllegalArgumentException, SiftsException
762   {
763     try
764     {
765       PDBChain chain = pdb.findChain(chainId);
766
767       if (chain == null || mapping == null)
768       {
769         throw new IllegalArgumentException(
770                 "Chain id or mapping must not be null.");
771       }
772       for (int[] map : mapping.values())
773       {
774         if (map[PDB_RES_POS] != UNASSIGNED)
775         {
776           map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
777         }
778       }
779     } catch (NullPointerException e)
780     {
781       throw new SiftsException(e.getMessage());
782     } catch (Exception e)
783     {
784       throw new SiftsException(e.getMessage());
785     }
786   }
787
788   /**
789    * 
790    * @param residueIndex
791    *          The residue index used for the search
792    * @param atoms
793    *          A collection of Atom to search
794    * @return atom position for the given residue index
795    */
796   int getAtomIndex(int residueIndex, Collection<Atom> atoms)
797   {
798     if (atoms == null)
799     {
800       throw new IllegalArgumentException(
801               "atoms collection must not be null!");
802     }
803     for (Atom atom : atoms)
804     {
805       if (atom.resNumber == residueIndex)
806       {
807         return atom.atomIndex;
808       }
809     }
810     return UNASSIGNED;
811   }
812
813   /**
814    * Checks if the residue instance is marked 'Not_observed' or not
815    * 
816    * @param residue
817    * @return
818    */
819   private boolean isResidueObserved(Residue residue)
820   {
821     Set<String> annotations = getResidueAnnotaitons(residue,
822             ResidueDetailType.ANNOTATION);
823     if (annotations == null || annotations.isEmpty())
824     {
825       return true;
826     }
827     for (String annotation : annotations)
828     {
829       if (annotation.equalsIgnoreCase(NOT_OBSERVED))
830       {
831         return false;
832       }
833     }
834     return true;
835   }
836
837   /**
838    * Get annotation String for a given residue and annotation type
839    * 
840    * @param residue
841    * @param type
842    * @return
843    */
844   private Set<String> getResidueAnnotaitons(Residue residue,
845           ResidueDetailType type)
846   {
847     HashSet<String> foundAnnotations = new HashSet<String>();
848     List<ResidueDetail> resDetails = residue.getResidueDetail();
849     for (ResidueDetail resDetail : resDetails)
850     {
851       if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
852       {
853         foundAnnotations.add(resDetail.getContent());
854       }
855     }
856     return foundAnnotations;
857   }
858
859   @Override
860   public boolean isAccessionMatched(String accession)
861   {
862     boolean isStrictMatch = true;
863     return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
864             : curDBRefAccessionIdsString
865                     .contains(accession.toLowerCase(Locale.ROOT));
866   }
867
868   private boolean isFoundInSiftsEntry(String accessionId)
869   {
870     Set<String> siftsDBRefs = getAllMappingAccession();
871     return accessionId != null
872             && siftsDBRefs.contains(accessionId.toLowerCase(Locale.ROOT));
873   }
874
875   /**
876    * Pad omitted residue positions in PDB sequence with gaps
877    * 
878    * @param resNumMap
879    */
880   void padWithGaps(Map<Integer, String> resNumMap,
881           List<Integer> omitNonObserved)
882   {
883     if (resNumMap == null || resNumMap.isEmpty())
884     {
885       return;
886     }
887     Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
888     // Arrays.sort(keys);
889     int firstIndex = keys[0];
890     int lastIndex = keys[keys.length - 1];
891     // System.out.println("Min value " + firstIndex);
892     // System.out.println("Max value " + lastIndex);
893     for (int x = firstIndex; x <= lastIndex; x++)
894     {
895       if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
896       {
897         resNumMap.put(x, "-");
898       }
899     }
900   }
901
902   @Override
903   public Entity getEntityById(String id) throws SiftsException
904   {
905     // Determines an entity to process by performing a heuristic matching of all
906     // Entities with the given chainId and choosing the best matching Entity
907     Entity entity = getEntityByMostOptimalMatchedId(id);
908     if (entity != null)
909     {
910       return entity;
911     }
912     throw new SiftsException("Entity " + id + " not found");
913   }
914
915   /**
916    * This method was added because EntityId is NOT always equal to ChainId.
917    * Hence, it provides the logic to greedily detect the "true" Entity for a
918    * given chainId where discrepancies exist.
919    * 
920    * @param chainId
921    * @return
922    */
923   public Entity getEntityByMostOptimalMatchedId(String chainId)
924   {
925     // System.out.println("---> advanced greedy entityId matching block
926     // entered..");
927     List<Entity> entities = siftsEntry.getEntity();
928     SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
929     int count = 0;
930     for (Entity entity : entities)
931     {
932       sPojo[count] = new SiftsEntitySortPojo();
933       sPojo[count].entityId = entity.getEntityId();
934
935       List<Segment> segments = entity.getSegment();
936       for (Segment segment : segments)
937       {
938         List<Residue> residues = segment.getListResidue().getResidue();
939         for (Residue residue : residues)
940         {
941           List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
942           for (CrossRefDb cRefDb : cRefDbs)
943           {
944             if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
945             {
946               continue;
947             }
948             ++sPojo[count].resCount;
949             if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
950             {
951               ++sPojo[count].chainIdFreq;
952             }
953           }
954         }
955       }
956       sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
957               / sPojo[count].resCount;
958       ++count;
959     }
960     Arrays.sort(sPojo, Collections.reverseOrder());
961     // System.out.println("highest matched entity : " + sPojo[0].entityId);
962     // System.out.println("highest matched pid : " + sPojo[0].pid);
963
964     if (sPojo[0].entityId != null)
965     {
966       if (sPojo[0].pid < 1)
967       {
968         return null;
969       }
970       for (Entity entity : entities)
971       {
972         if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
973         {
974           continue;
975         }
976         return entity;
977       }
978     }
979     return null;
980   }
981
982   private class SiftsEntitySortPojo
983           implements Comparable<SiftsEntitySortPojo>
984   {
985     public String entityId;
986
987     public int chainIdFreq;
988
989     public int pid;
990
991     public int resCount;
992
993     @Override
994     public int compareTo(SiftsEntitySortPojo o)
995     {
996       return this.pid - o.pid;
997     }
998   }
999
1000   private class SegmentHelperPojo
1001   {
1002     private SequenceI seq;
1003
1004     private HashMap<Integer, int[]> mapping;
1005
1006     private TreeMap<Integer, String> resNumMap;
1007
1008     private List<Integer> omitNonObserved;
1009
1010     private int nonObservedShiftIndex;
1011
1012     /**
1013      * count of number of 'not observed' positions in the PDB record's SEQRES
1014      * (total number of residues with coordinates == length(SEQRES) -
1015      * pdbeNonObserved
1016      */
1017     private int pdbeNonObserved;
1018
1019     public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1020             TreeMap<Integer, String> resNumMap,
1021             List<Integer> omitNonObserved, int nonObservedShiftIndex,
1022             int pdbeNonObserved)
1023     {
1024       setSeq(seq);
1025       setMapping(mapping);
1026       setResNumMap(resNumMap);
1027       setOmitNonObserved(omitNonObserved);
1028       setNonObservedShiftIndex(nonObservedShiftIndex);
1029       setPdbeNonObserved(pdbeNonObserved);
1030
1031     }
1032
1033     public void setPdbeNonObserved(int pdbeNonObserved2)
1034     {
1035       this.pdbeNonObserved = pdbeNonObserved2;
1036     }
1037
1038     public int getPdbeNonObserved()
1039     {
1040       return pdbeNonObserved;
1041     }
1042     public SequenceI getSeq()
1043     {
1044       return seq;
1045     }
1046
1047     public void setSeq(SequenceI seq)
1048     {
1049       this.seq = seq;
1050     }
1051
1052     public HashMap<Integer, int[]> getMapping()
1053     {
1054       return mapping;
1055     }
1056
1057     public void setMapping(HashMap<Integer, int[]> mapping)
1058     {
1059       this.mapping = mapping;
1060     }
1061
1062     public TreeMap<Integer, String> getResNumMap()
1063     {
1064       return resNumMap;
1065     }
1066
1067     public void setResNumMap(TreeMap<Integer, String> resNumMap)
1068     {
1069       this.resNumMap = resNumMap;
1070     }
1071
1072     public List<Integer> getOmitNonObserved()
1073     {
1074       return omitNonObserved;
1075     }
1076
1077     public void setOmitNonObserved(List<Integer> omitNonObserved)
1078     {
1079       this.omitNonObserved = omitNonObserved;
1080     }
1081
1082     public int getNonObservedShiftIndex()
1083     {
1084       return nonObservedShiftIndex;
1085     }
1086
1087     public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1088     {
1089       this.nonObservedShiftIndex = nonObservedShiftIndex;
1090     }
1091
1092   }
1093
1094   @Override
1095   public StringBuilder getMappingOutput(MappingOutputPojo mp)
1096           throws SiftsException
1097   {
1098     String seqRes = mp.getSeqResidue();
1099     String seqName = mp.getSeqName();
1100     int sStart = mp.getSeqStart();
1101     int sEnd = mp.getSeqEnd();
1102
1103     String strRes = mp.getStrResidue();
1104     String strName = mp.getStrName();
1105     int pdbStart = mp.getStrStart();
1106     int pdbEnd = mp.getStrEnd();
1107
1108     String type = mp.getType();
1109
1110     int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1111             : strName.length();
1112     int len = 72 - maxid - 1;
1113
1114     int nochunks = ((seqRes.length()) / len)
1115             + ((seqRes.length()) % len > 0 ? 1 : 0);
1116     // output mappings
1117     StringBuilder output = new StringBuilder(512);
1118     output.append(NEWLINE);
1119     output.append("Sequence \u27f7 Structure mapping details")
1120             .append(NEWLINE);
1121     output.append("Method: SIFTS");
1122     output.append(NEWLINE).append(NEWLINE);
1123
1124     output.append(new Format("%" + maxid + "s").form(seqName));
1125     output.append(" :  ");
1126     output.append(String.valueOf(sStart));
1127     output.append(" - ");
1128     output.append(String.valueOf(sEnd));
1129     output.append(" Maps to ");
1130     output.append(NEWLINE);
1131     output.append(new Format("%" + maxid + "s").form(structId));
1132     output.append(" :  ");
1133     output.append(String.valueOf(pdbStart));
1134     output.append(" - ");
1135     output.append(String.valueOf(pdbEnd));
1136     output.append(NEWLINE).append(NEWLINE);
1137
1138     ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1139     int matchedSeqCount = 0;
1140     for (int j = 0; j < nochunks; j++)
1141     {
1142       // Print the first aligned sequence
1143       output.append(new Format("%" + (maxid) + "s").form(seqName))
1144               .append(" ");
1145
1146       for (int i = 0; i < len; i++)
1147       {
1148         if ((i + (j * len)) < seqRes.length())
1149         {
1150           output.append(seqRes.charAt(i + (j * len)));
1151         }
1152       }
1153
1154       output.append(NEWLINE);
1155       output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1156
1157       /*
1158        * Print out the match symbols:
1159        * | for exact match (ignoring case)
1160        * . if PAM250 score is positive
1161        * else a space
1162        */
1163       for (int i = 0; i < len; i++)
1164       {
1165         try
1166         {
1167           if ((i + (j * len)) < seqRes.length())
1168           {
1169             char c1 = seqRes.charAt(i + (j * len));
1170             char c2 = strRes.charAt(i + (j * len));
1171             boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1172             if (sameChar && !Comparison.isGap(c1))
1173             {
1174               matchedSeqCount++;
1175               output.append("|");
1176             }
1177             else if (type.equals("pep"))
1178             {
1179               if (pam250.getPairwiseScore(c1, c2) > 0)
1180               {
1181                 output.append(".");
1182               }
1183               else
1184               {
1185                 output.append(" ");
1186               }
1187             }
1188             else
1189             {
1190               output.append(" ");
1191             }
1192           }
1193         } catch (IndexOutOfBoundsException e)
1194         {
1195           continue;
1196         }
1197       }
1198       // Now print the second aligned sequence
1199       output = output.append(NEWLINE);
1200       output = output.append(new Format("%" + (maxid) + "s").form(strName))
1201               .append(" ");
1202       for (int i = 0; i < len; i++)
1203       {
1204         if ((i + (j * len)) < strRes.length())
1205         {
1206           output.append(strRes.charAt(i + (j * len)));
1207         }
1208       }
1209       output.append(NEWLINE).append(NEWLINE);
1210     }
1211     float pid = (float) matchedSeqCount / seqRes.length() * 100;
1212     if (pid < SiftsSettings.getFailSafePIDThreshold())
1213     {
1214       throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1215     }
1216     output.append("Length of alignment = " + seqRes.length())
1217             .append(NEWLINE);
1218     output.append(new Format("Percentage ID = %2.2f").form(pid));
1219     return output;
1220   }
1221
1222   @Override
1223   public int getEntityCount()
1224   {
1225     return siftsEntry.getEntity().size();
1226   }
1227
1228   @Override
1229   public String getDbAccessionId()
1230   {
1231     return siftsEntry.getDbAccessionId();
1232   }
1233
1234   @Override
1235   public String getDbCoordSys()
1236   {
1237     return siftsEntry.getDbCoordSys();
1238   }
1239
1240   @Override
1241   public String getDbSource()
1242   {
1243     return siftsEntry.getDbSource();
1244   }
1245
1246   @Override
1247   public String getDbVersion()
1248   {
1249     return siftsEntry.getDbVersion();
1250   }
1251
1252   public static void setMockSiftsFile(File file)
1253   {
1254     mockSiftsFile = file;
1255   }
1256
1257 }