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