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