JAL-2312 Bug fix for repeated mapping generation from SIFTS when heuristic identifica...
[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    * Parse the given SIFTs File and return a JAXB POJO of parsed data
154    * 
155    * @param siftFile
156    *          - the GZipped SIFTs XML file to parse
157    * @return
158    * @throws Exception
159    *           if a problem occurs while parsing the SIFTs XML
160    */
161   private Entry parseSIFTs(File siftFile) throws SiftsException
162   {
163     try (InputStream in = new FileInputStream(siftFile);
164             GZIPInputStream gzis = new GZIPInputStream(in);)
165     {
166       // System.out.println("File : " + siftFile.getAbsolutePath());
167       JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
168       XMLStreamReader streamReader = XMLInputFactory.newInstance()
169               .createXMLStreamReader(gzis);
170       Unmarshaller um = jc.createUnmarshaller();
171       return (Entry) um.unmarshal(streamReader);
172     } catch (Exception e)
173     {
174       e.printStackTrace();
175       throw new SiftsException(e.getMessage());
176     }
177   }
178
179   /**
180    * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
181    * repository if not found in cache
182    * 
183    * @param pdbId
184    * @return SIFTs XML file
185    * @throws SiftsException
186    */
187   public static File getSiftsFile(String pdbId) throws SiftsException
188   {
189     String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
190             + pdbId.toLowerCase() + ".xml.gz";
191     File siftsFile = new File(siftsFileName);
192     if (siftsFile.exists())
193     {
194       // The line below is required for unit testing... don't comment it out!!!
195       System.out.println(">>> SIFTS File already downloaded for " + pdbId);
196
197       if (isFileOlderThanThreshold(siftsFile,
198               SiftsSettings.getCacheThresholdInDays()))
199       {
200         File oldSiftsFile = new File(siftsFileName + "_old");
201         siftsFile.renameTo(oldSiftsFile);
202         try
203         {
204           siftsFile = downloadSiftsFile(pdbId.toLowerCase());
205           oldSiftsFile.delete();
206           return siftsFile;
207         } catch (IOException e)
208         {
209           e.printStackTrace();
210           oldSiftsFile.renameTo(siftsFile);
211           return new File(siftsFileName);
212         }
213       }
214     }
215     try
216     {
217       siftsFile = downloadSiftsFile(pdbId.toLowerCase());
218     } catch (IOException e)
219     {
220       throw new SiftsException(e.getMessage());
221     }
222     return siftsFile;
223   }
224
225   /**
226    * This method enables checking if a cached file has exceeded a certain
227    * threshold(in days)
228    * 
229    * @param file
230    *          the cached file
231    * @param noOfDays
232    *          the threshold in days
233    * @return
234    */
235   public static boolean isFileOlderThanThreshold(File file, int noOfDays)
236   {
237     Path filePath = file.toPath();
238     BasicFileAttributes attr;
239     int diffInDays = 0;
240     try
241     {
242       attr = Files.readAttributes(filePath, BasicFileAttributes.class);
243       diffInDays = (int) ((new Date().getTime() - attr.lastModifiedTime()
244               .toMillis()) / (1000 * 60 * 60 * 24));
245       // System.out.println("Diff in days : " + diffInDays);
246     } catch (IOException e)
247     {
248       e.printStackTrace();
249     }
250     return noOfDays <= diffInDays;
251   }
252
253   /**
254    * Download a SIFTs XML file for a given PDB Id from an FTP repository
255    * 
256    * @param pdbId
257    * @return downloaded SIFTs XML file
258    * @throws SiftsException
259    * @throws IOException
260    */
261   public static File downloadSiftsFile(String pdbId) throws SiftsException,
262           IOException
263   {
264     if (pdbId.contains(".cif"))
265     {
266       pdbId = pdbId.replace(".cif", "");
267     }
268     String siftFile = pdbId + ".xml.gz";
269     String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
270     String downloadedSiftsFile = SiftsSettings.getSiftDownloadDirectory()
271             + siftFile;
272     File siftsDownloadDir = new File(
273             SiftsSettings.getSiftDownloadDirectory());
274     if (!siftsDownloadDir.exists())
275     {
276       siftsDownloadDir.mkdirs();
277     }
278     // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
279     URL url = new URL(siftsFileFTPURL);
280     URLConnection conn = url.openConnection();
281     InputStream inputStream = conn.getInputStream();
282     FileOutputStream outputStream = new FileOutputStream(
283             downloadedSiftsFile);
284     byte[] buffer = new byte[BUFFER_SIZE];
285     int bytesRead = -1;
286     while ((bytesRead = inputStream.read(buffer)) != -1)
287     {
288       outputStream.write(buffer, 0, bytesRead);
289     }
290     outputStream.close();
291     inputStream.close();
292     // System.out.println(">>> File downloaded : " + downloadedSiftsFile);
293     return new File(downloadedSiftsFile);
294   }
295
296   /**
297    * Delete the SIFTs file for the given PDB Id in the local SIFTs download
298    * directory
299    * 
300    * @param pdbId
301    * @return true if the file was deleted or doesn't exist
302    */
303   public static boolean deleteSiftsFileByPDBId(String pdbId)
304   {
305     File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
306             + pdbId.toLowerCase() + ".xml.gz");
307     if (siftsFile.exists())
308     {
309       return siftsFile.delete();
310     }
311     return true;
312   }
313
314   /**
315    * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
316    * 
317    * @param seq
318    *          - the target sequence for the operation
319    * @return a valid DBRefEntry that is SIFTs compatible
320    * @throws Exception
321    *           if no valid source DBRefEntry was found for the given sequences
322    */
323   public DBRefEntryI getValidSourceDBRef(SequenceI seq)
324           throws SiftsException
325   {
326     List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
327     if (dbRefs == null || dbRefs.size() < 1)
328     {
329       throw new SiftsException(
330               "Source DBRef could not be determined. DBRefs might not have been retrieved.");
331     }
332
333     for (DBRefEntry dbRef : dbRefs)
334     {
335       if (dbRef == null || dbRef.getAccessionId() == null
336               || dbRef.getSource() == null)
337       {
338         continue;
339       }
340       String canonicalSource = DBRefUtils.getCanonicalName(dbRef
341               .getSource());
342       if (isValidDBRefEntry(dbRef)
343               && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT) || canonicalSource
344                       .equalsIgnoreCase(DBRefSource.PDB)))
345       {
346         return dbRef;
347       }
348     }
349     throw new SiftsException("Could not get source DB Ref");
350   }
351
352   /**
353    * Check that the DBRef Entry is properly populated and is available in this
354    * SiftClient instance
355    * 
356    * @param entry
357    *          - DBRefEntry to validate
358    * @return true validation is successful otherwise false is returned.
359    */
360   boolean isValidDBRefEntry(DBRefEntryI entry)
361   {
362     return entry != null && entry.getAccessionId() != null
363             && isFoundInSiftsEntry(entry.getAccessionId());
364   }
365
366   @Override
367   public HashSet<String> getAllMappingAccession()
368   {
369     HashSet<String> accessions = new HashSet<String>();
370     List<Entity> entities = siftsEntry.getEntity();
371     for (Entity entity : entities)
372     {
373       List<Segment> segments = entity.getSegment();
374       for (Segment segment : segments)
375       {
376         List<MapRegion> mapRegions = segment.getListMapRegion()
377                 .getMapRegion();
378         for (MapRegion mapRegion : mapRegions)
379         {
380           accessions
381                   .add(mapRegion.getDb().getDbAccessionId().toLowerCase());
382         }
383       }
384     }
385     return accessions;
386   }
387
388   @Override
389   public StructureMapping getSiftsStructureMapping(SequenceI seq,
390           String pdbFile, String chain) throws SiftsException
391   {
392     structId = (chain == null) ? pdbId : pdbId + "|" + chain;
393     System.out.println("Getting SIFTS mapping for " + structId + ": seq "
394             + seq.getName());
395
396     final StringBuilder mappingDetails = new StringBuilder(128);
397     PrintStream ps = new PrintStream(System.out)
398     {
399       @Override
400       public void print(String x)
401       {
402         mappingDetails.append(x);
403       }
404
405       @Override
406       public void println()
407       {
408         mappingDetails.append(NEWLINE);
409       }
410     };
411     HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
412
413     String mappingOutput = mappingDetails.toString();
414     StructureMapping siftsMapping = new StructureMapping(seq, pdbFile,
415             pdbId, chain, mapping, mappingOutput);
416     return siftsMapping;
417   }
418
419   @Override
420   public HashMap<Integer, int[]> getGreedyMapping(String entityId,
421           SequenceI seq, java.io.PrintStream os) throws SiftsException
422   {
423     List<Integer> omitNonObserved = new ArrayList<Integer>();
424     int nonObservedShiftIndex = 0;
425     // System.out.println("Generating mappings for : " + entityId);
426     Entity entity = null;
427     entity = getEntityById(entityId);
428     String originalSeq = AlignSeq.extractGaps(
429             jalview.util.Comparison.GapChars, seq.getSequenceAsString());
430     HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
431     DBRefEntryI sourceDBRef;
432     sourceDBRef = getValidSourceDBRef(seq);
433     // TODO ensure sequence start/end is in the same coordinate system and
434     // consistent with the choosen sourceDBRef
435
436     // set sequence coordinate system - default value is UniProt
437     if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
438     {
439       seqCoordSys = CoordinateSys.PDB;
440     }
441
442     HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
443     for (DBRefEntry dbref : seq.getDBRefs())
444     {
445       dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
446     }
447     dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
448
449     curDBRefAccessionIdsString = dbRefAccessionIdsString;
450     curSourceDBRef = sourceDBRef.getAccessionId();
451
452     TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
453     List<Segment> segments = entity.getSegment();
454     SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
455             omitNonObserved, nonObservedShiftIndex);
456     processSegments(segments, shp);
457     try
458     {
459       populateAtomPositions(entityId, mapping);
460     } catch (Exception e)
461     {
462       e.printStackTrace();
463     }
464     if (seqCoordSys == CoordinateSys.UNIPROT)
465     {
466       padWithGaps(resNumMap, omitNonObserved);
467     }
468     int seqStart = UNASSIGNED;
469     int seqEnd = UNASSIGNED;
470     int pdbStart = UNASSIGNED;
471     int pdbEnd = UNASSIGNED;
472
473     if (mapping.isEmpty())
474     {
475       throw new SiftsException("SIFTS mapping failed");
476     }
477
478     Integer[] keys = mapping.keySet().toArray(new Integer[0]);
479     Arrays.sort(keys);
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    * 
617    * @param chainId
618    *          Target chain to populate mapping of its atom positions.
619    * @param mapping
620    *          Two dimension array of residue index versus atom position
621    * @throws IllegalArgumentException
622    *           Thrown if chainId or mapping is null
623    * @throws SiftsException
624    */
625   void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
626           throws IllegalArgumentException, SiftsException
627   {
628     try
629     {
630       PDBChain chain = pdb.findChain(chainId);
631
632       if (chain == null || mapping == null)
633       {
634         throw new IllegalArgumentException(
635                 "Chain id or mapping must not be null.");
636       }
637       for (int[] map : mapping.values())
638       {
639         if (map[PDB_RES_POS] != UNASSIGNED)
640         {
641           map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
642         }
643       }
644     } catch (NullPointerException e)
645     {
646       throw new SiftsException(e.getMessage());
647     } catch (Exception e)
648     {
649       throw new SiftsException(e.getMessage());
650     }
651   }
652
653   /**
654    * 
655    * @param residueIndex
656    *          The residue index used for the search
657    * @param atoms
658    *          A collection of Atom to search
659    * @return atom position for the given residue index
660    */
661   int getAtomIndex(int residueIndex, Collection<Atom> atoms)
662   {
663     if (atoms == null)
664     {
665       throw new IllegalArgumentException(
666               "atoms collection must not be null!");
667     }
668     for (Atom atom : atoms)
669     {
670       if (atom.resNumber == residueIndex)
671       {
672         return atom.atomIndex;
673       }
674     }
675     return UNASSIGNED;
676   }
677
678   /**
679    * Checks if the residue instance is marked 'Not_observed' or not
680    * 
681    * @param residue
682    * @return
683    */
684   private boolean isResidueObserved(Residue residue)
685   {
686     Set<String> annotations = getResidueAnnotaitons(residue,
687             ResidueDetailType.ANNOTATION);
688     if (annotations == null || annotations.isEmpty())
689     {
690       return true;
691     }
692     for (String annotation : annotations)
693     {
694       if (annotation.equalsIgnoreCase(NOT_OBSERVED))
695       {
696         return false;
697       }
698     }
699     return true;
700   }
701
702   /**
703    * Get annotation String for a given residue and annotation type
704    * 
705    * @param residue
706    * @param type
707    * @return
708    */
709   private Set<String> getResidueAnnotaitons(Residue residue,
710           ResidueDetailType type)
711   {
712     HashSet<String> foundAnnotations = new HashSet<String>();
713     List<ResidueDetail> resDetails = residue.getResidueDetail();
714     for (ResidueDetail resDetail : resDetails)
715     {
716       if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
717       {
718         foundAnnotations.add(resDetail.getContent());
719       }
720     }
721     return foundAnnotations;
722   }
723
724   @Override
725   public boolean isAccessionMatched(String accession)
726   {
727     boolean isStrictMatch = true;
728     return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
729             : curDBRefAccessionIdsString.contains(accession.toLowerCase());
730   }
731
732   private boolean isFoundInSiftsEntry(String accessionId)
733   {
734     Set<String> siftsDBRefs = getAllMappingAccession();
735     return accessionId != null
736             && siftsDBRefs.contains(accessionId.toLowerCase());
737   }
738
739   /**
740    * Pad omitted residue positions in PDB sequence with gaps
741    * 
742    * @param resNumMap
743    */
744   void padWithGaps(Map<Integer, String> resNumMap,
745           List<Integer> omitNonObserved)
746   {
747     if (resNumMap == null || resNumMap.isEmpty())
748     {
749       return;
750     }
751     Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
752     // Arrays.sort(keys);
753     int firstIndex = keys[0];
754     int lastIndex = keys[keys.length - 1];
755     // System.out.println("Min value " + firstIndex);
756     // System.out.println("Max value " + lastIndex);
757     for (int x = firstIndex; x <= lastIndex; x++)
758     {
759       if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
760       {
761         resNumMap.put(x, "-");
762       }
763     }
764   }
765
766   @Override
767   public Entity getEntityById(String id) throws SiftsException
768   {
769     // Determines an entity to process by performing a heuristic matching of all
770     // Entities with the given chainId and choosing the best matching Entity
771     Entity entity = getEntityByMostOptimalMatchedId(id);
772     if (entity != null)
773     {
774       return entity;
775     }
776     throw new SiftsException("Entity " + id + " not found");
777   }
778
779   /**
780    * This method was added because EntityId is NOT always equal to ChainId.
781    * Hence, it provides the logic to greedily detect the "true" Entity for a
782    * given chainId where discrepancies exist.
783    * 
784    * @param chainId
785    * @return
786    */
787   public Entity getEntityByMostOptimalMatchedId(String chainId)
788   {
789     // System.out.println("---> advanced greedy entityId matching block entered..");
790     List<Entity> entities = siftsEntry.getEntity();
791     SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
792     int count = 0;
793     for (Entity entity : entities)
794     {
795       sPojo[count] = new SiftsEntitySortPojo();
796       sPojo[count].entityId = entity.getEntityId();
797
798       List<Segment> segments = entity.getSegment();
799       for (Segment segment : segments)
800       {
801         List<Residue> residues = segment.getListResidue().getResidue();
802         for (Residue residue : residues)
803         {
804           List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
805           for (CrossRefDb cRefDb : cRefDbs)
806           {
807             if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
808             {
809               continue;
810             }
811             ++sPojo[count].resCount;
812             if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
813             {
814               ++sPojo[count].chainIdFreq;
815             }
816           }
817         }
818       }
819       sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
820               / sPojo[count].resCount;
821       ++count;
822     }
823     Arrays.sort(sPojo, Collections.reverseOrder());
824     // System.out.println("highest matched entity : " + sPojo[0].entityId);
825     // System.out.println("highest matched pid : " + sPojo[0].pid);
826
827     if (sPojo[0].entityId != null)
828     {
829       if (sPojo[0].pid < 1)
830       {
831         return null;
832       }
833       for (Entity entity : entities)
834       {
835         if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
836         {
837           continue;
838         }
839         return entity;
840       }
841     }
842     return null;
843   }
844
845   private class SiftsEntitySortPojo implements
846           Comparable<SiftsEntitySortPojo>
847   {
848     public String entityId;
849
850     public int chainIdFreq;
851
852     public int pid;
853
854     public int resCount;
855
856     @Override
857     public int compareTo(SiftsEntitySortPojo o)
858     {
859       return this.pid - o.pid;
860     }
861   }
862
863   private class SegmentHelperPojo
864   {
865     private SequenceI seq;
866
867     private HashMap<Integer, int[]> mapping;
868
869     private TreeMap<Integer, String> resNumMap;
870
871     private List<Integer> omitNonObserved;
872
873     private int nonObservedShiftIndex;
874
875     public SegmentHelperPojo(SequenceI seq,
876             HashMap<Integer, int[]> mapping,
877             TreeMap<Integer, String> resNumMap,
878             List<Integer> omitNonObserved, int nonObservedShiftIndex)
879     {
880       setSeq(seq);
881       setMapping(mapping);
882       setResNumMap(resNumMap);
883       setOmitNonObserved(omitNonObserved);
884       setNonObservedShiftIndex(nonObservedShiftIndex);
885     }
886
887     public SequenceI getSeq()
888     {
889       return seq;
890     }
891
892     public void setSeq(SequenceI seq)
893     {
894       this.seq = seq;
895     }
896
897     public HashMap<Integer, int[]> getMapping()
898     {
899       return mapping;
900     }
901
902     public void setMapping(HashMap<Integer, int[]> mapping)
903     {
904       this.mapping = mapping;
905     }
906
907     public TreeMap<Integer, String> getResNumMap()
908     {
909       return resNumMap;
910     }
911
912     public void setResNumMap(TreeMap<Integer, String> resNumMap)
913     {
914       this.resNumMap = resNumMap;
915     }
916
917     public List<Integer> getOmitNonObserved()
918     {
919       return omitNonObserved;
920     }
921
922     public void setOmitNonObserved(List<Integer> omitNonObserved)
923     {
924       this.omitNonObserved = omitNonObserved;
925     }
926
927     public int getNonObservedShiftIndex()
928     {
929       return nonObservedShiftIndex;
930     }
931
932     public void setNonObservedShiftIndex(int nonObservedShiftIndex)
933     {
934       this.nonObservedShiftIndex = nonObservedShiftIndex;
935     }
936   }
937
938   @Override
939   public StringBuffer getMappingOutput(MappingOutputPojo mp)
940           throws SiftsException
941   {
942     String seqRes = mp.getSeqResidue();
943     String seqName = mp.getSeqName();
944     int sStart = mp.getSeqStart();
945     int sEnd = mp.getSeqEnd();
946
947     String strRes = mp.getStrResidue();
948     String strName = mp.getStrName();
949     int pdbStart = mp.getStrStart();
950     int pdbEnd = mp.getStrEnd();
951
952     String type = mp.getType();
953
954     int maxid = (seqName.length() >= strName.length()) ? seqName.length()
955             : strName.length();
956     int len = 72 - maxid - 1;
957
958     int nochunks = ((seqRes.length()) / len)
959             + ((seqRes.length()) % len > 0 ? 1 : 0);
960     // output mappings
961     StringBuffer output = new StringBuffer();
962     output.append(NEWLINE);
963     output.append("Sequence \u27f7 Structure mapping details").append(
964             NEWLINE);
965     output.append("Method: SIFTS");
966     output.append(NEWLINE).append(NEWLINE);
967
968     output.append(new Format("%" + maxid + "s").form(seqName));
969     output.append(" :  ");
970     output.append(String.valueOf(sStart));
971     output.append(" - ");
972     output.append(String.valueOf(sEnd));
973     output.append(" Maps to ");
974     output.append(NEWLINE);
975     output.append(new Format("%" + maxid + "s").form(structId));
976     output.append(" :  ");
977     output.append(String.valueOf(pdbStart));
978     output.append(" - ");
979     output.append(String.valueOf(pdbEnd));
980     output.append(NEWLINE).append(NEWLINE);
981
982     int matchedSeqCount = 0;
983     for (int j = 0; j < nochunks; j++)
984     {
985       // Print the first aligned sequence
986       output.append(new Format("%" + (maxid) + "s").form(seqName)).append(
987               " ");
988
989       for (int i = 0; i < len; i++)
990       {
991         if ((i + (j * len)) < seqRes.length())
992         {
993           output.append(seqRes.charAt(i + (j * len)));
994         }
995       }
996
997       output.append(NEWLINE);
998       output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
999
1000       // Print out the matching chars
1001       for (int i = 0; i < len; i++)
1002       {
1003         try
1004         {
1005           if ((i + (j * len)) < seqRes.length())
1006           {
1007             if (seqRes.charAt(i + (j * len)) == strRes
1008                     .charAt(i + (j * len))
1009                     && !jalview.util.Comparison.isGap(seqRes.charAt(i
1010                             + (j * len))))
1011             {
1012               matchedSeqCount++;
1013               output.append("|");
1014             }
1015             else if (type.equals("pep"))
1016             {
1017               if (ResidueProperties.getPAM250(seqRes.charAt(i + (j * len)),
1018                       strRes.charAt(i + (j * len))) > 0)
1019               {
1020                 output.append(".");
1021               }
1022               else
1023               {
1024                 output.append(" ");
1025               }
1026             }
1027             else
1028             {
1029               output.append(" ");
1030             }
1031           }
1032         } catch (IndexOutOfBoundsException e)
1033         {
1034           continue;
1035         }
1036       }
1037       // Now print the second aligned sequence
1038       output = output.append(NEWLINE);
1039       output = output.append(new Format("%" + (maxid) + "s").form(strName))
1040               .append(" ");
1041       for (int i = 0; i < len; i++)
1042       {
1043         if ((i + (j * len)) < strRes.length())
1044         {
1045           output.append(strRes.charAt(i + (j * len)));
1046         }
1047       }
1048       output.append(NEWLINE).append(NEWLINE);
1049     }
1050     float pid = (float) matchedSeqCount / seqRes.length() * 100;
1051     if (pid < SiftsSettings.getFailSafePIDThreshold())
1052     {
1053       throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1054     }
1055     output.append("Length of alignment = " + seqRes.length()).append(
1056             NEWLINE);
1057     output.append(new Format("Percentage ID = %2.2f").form(pid));
1058     return output;
1059   }
1060
1061   @Override
1062   public int getEntityCount()
1063   {
1064     return siftsEntry.getEntity().size();
1065   }
1066
1067   @Override
1068   public String getDbAccessionId()
1069   {
1070     return siftsEntry.getDbAccessionId();
1071   }
1072
1073   @Override
1074   public String getDbCoordSys()
1075   {
1076     return siftsEntry.getDbCoordSys();
1077   }
1078
1079   @Override
1080   public String getDbSource()
1081   {
1082     return siftsEntry.getDbSource();
1083   }
1084
1085   @Override
1086   public String getDbVersion()
1087   {
1088     return siftsEntry.getDbVersion();
1089   }
1090
1091 }