JAL-1926 JAL-2106 source DB refs come from SequenceI.getPrimaryDBRefs()
[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       if (isValidDBRefEntry(dbRef)
342               && dbRef.isPrimary()
343               && (DBRefUtils.getCanonicalName(dbRef.getSource())
344                       .equalsIgnoreCase(DBRefSource.UNIPROT) || DBRefUtils
345                       .getCanonicalName(dbRef.getSource())
346                       .equalsIgnoreCase(DBRefSource.PDB)))
347       {
348         return dbRef;
349       }
350     }
351     throw new SiftsException("Could not get source DB Ref");
352   }
353
354   /**
355    * Check that the DBRef Entry is properly populated and is available in this
356    * SiftClient instance
357    * 
358    * @param entry
359    *          - DBRefEntry to validate
360    * @return true validation is successful otherwise false is returned.
361    */
362   boolean isValidDBRefEntry(DBRefEntryI entry)
363   {
364     return entry != null && entry.getAccessionId() != null
365             && isFoundInSiftsEntry(entry.getAccessionId());
366   }
367
368   @Override
369   public HashSet<String> getAllMappingAccession()
370   {
371     HashSet<String> accessions = new HashSet<String>();
372     List<Entity> entities = siftsEntry.getEntity();
373     for (Entity entity : entities)
374     {
375       List<Segment> segments = entity.getSegment();
376       for (Segment segment : segments)
377       {
378         List<MapRegion> mapRegions = segment.getListMapRegion()
379                 .getMapRegion();
380         for (MapRegion mapRegion : mapRegions)
381         {
382           accessions
383                   .add(mapRegion.getDb().getDbAccessionId().toLowerCase());
384         }
385       }
386     }
387     return accessions;
388   }
389
390   @Override
391   public StructureMapping getSiftsStructureMapping(SequenceI seq,
392           String pdbFile, String chain) throws SiftsException
393   {
394     structId = (chain == null) ? pdbId : pdbId + "|" + chain;
395     System.out.println("Getting mapping for: " + pdbId + "|" + chain
396             + " : seq- " + seq.getName());
397
398     final StringBuilder mappingDetails = new StringBuilder(128);
399     PrintStream ps = new PrintStream(System.out)
400     {
401       @Override
402       public void print(String x)
403       {
404         mappingDetails.append(x);
405       }
406
407       @Override
408       public void println()
409       {
410         mappingDetails.append(NEWLINE);
411       }
412     };
413     HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
414
415     String mappingOutput = mappingDetails.toString();
416     StructureMapping siftsMapping = new StructureMapping(seq, pdbFile,
417             pdbId, chain, mapping, mappingOutput);
418     return siftsMapping;
419   }
420
421   @Override
422   public HashMap<Integer, int[]> getGreedyMapping(String entityId,
423           SequenceI seq, java.io.PrintStream os) throws SiftsException
424   {
425     List<Integer> omitNonObserved = new ArrayList<Integer>();
426     int nonObservedShiftIndex = 0;
427     // System.out.println("Generating mappings for : " + entityId);
428     Entity entity = null;
429     entity = getEntityById(entityId);
430     String originalSeq = AlignSeq.extractGaps(
431             jalview.util.Comparison.GapChars, seq.getSequenceAsString());
432     HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
433     DBRefEntryI sourceDBRef;
434     sourceDBRef = getValidSourceDBRef(seq);
435     // TODO ensure sequence start/end is in the same coordinate system and
436     // consistent with the choosen sourceDBRef
437
438     // set sequence coordinate system - default value is UniProt
439     if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
440     {
441       seqCoordSys = CoordinateSys.PDB;
442     }
443
444     HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
445     for (DBRefEntry dbref : seq.getDBRefs())
446     {
447       dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
448     }
449     dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
450
451     curDBRefAccessionIdsString = dbRefAccessionIdsString;
452     curSourceDBRef = sourceDBRef.getAccessionId();
453
454     TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
455     List<Segment> segments = entity.getSegment();
456     SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
457             omitNonObserved, nonObservedShiftIndex);
458     processSegments(segments, shp);
459     try
460     {
461       populateAtomPositions(entityId, mapping);
462     } catch (Exception e)
463     {
464       e.printStackTrace();
465     }
466     if (seqCoordSys == CoordinateSys.UNIPROT)
467     {
468       padWithGaps(resNumMap, omitNonObserved);
469     }
470     int seqStart = UNASSIGNED;
471     int seqEnd = UNASSIGNED;
472     int pdbStart = UNASSIGNED;
473     int pdbEnd = UNASSIGNED;
474
475     Integer[] keys = mapping.keySet().toArray(new Integer[0]);
476     Arrays.sort(keys);
477     if (keys.length < 1)
478     {
479       throw new SiftsException(">>> Empty SIFTS mapping generated!!");
480     }
481     seqStart = keys[0];
482     seqEnd = keys[keys.length - 1];
483
484     String matchedSeq = originalSeq;
485     if (seqStart != UNASSIGNED)
486     {
487       pdbStart = mapping.get(seqStart)[PDB_RES_POS];
488       pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
489       int orignalSeqStart = seq.getStart();
490       if (orignalSeqStart >= 1)
491       {
492         int subSeqStart = (seqStart >= orignalSeqStart) ? seqStart
493                 - orignalSeqStart : 0;
494         int subSeqEnd = seqEnd - (orignalSeqStart - 1);
495         subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
496                 : subSeqEnd;
497         matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
498       }
499       else
500       {
501         matchedSeq = originalSeq.substring(1, originalSeq.length());
502       }
503     }
504
505     StringBuilder targetStrucSeqs = new StringBuilder();
506     for (String res : resNumMap.values())
507     {
508       targetStrucSeqs.append(res);
509     }
510
511     if (os != null)
512     {
513       MappingOutputPojo mop = new MappingOutputPojo();
514       mop.setSeqStart(pdbStart);
515       mop.setSeqEnd(pdbEnd);
516       mop.setSeqName(seq.getName());
517       mop.setSeqResidue(matchedSeq);
518
519       mop.setStrStart(seqStart);
520       mop.setStrEnd(seqEnd);
521       mop.setStrName(structId);
522       mop.setStrResidue(targetStrucSeqs.toString());
523
524       mop.setType("pep");
525       os.print(getMappingOutput(mop).toString());
526       os.println();
527     }
528     return mapping;
529   }
530
531   void processSegments(List<Segment> segments, SegmentHelperPojo shp)
532   {
533     SequenceI seq = shp.getSeq();
534     HashMap<Integer, int[]> mapping = shp.getMapping();
535     TreeMap<Integer, String> resNumMap = shp.getResNumMap();
536     List<Integer> omitNonObserved = shp.getOmitNonObserved();
537     int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
538     for (Segment segment : segments)
539     {
540       // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
541       // + segStartEnd);
542       List<Residue> residues = segment.getListResidue().getResidue();
543       for (Residue residue : residues)
544       {
545         int currSeqIndex = UNASSIGNED;
546         List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
547         CrossRefDb pdbRefDb = null;
548         for (CrossRefDb cRefDb : cRefDbs)
549         {
550           if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
551           {
552             pdbRefDb = cRefDb;
553           }
554           if (cRefDb.getDbCoordSys()
555                   .equalsIgnoreCase(seqCoordSys.getName())
556                   && isAccessionMatched(cRefDb.getDbAccessionId()))
557           {
558             String resNumIndexString = cRefDb.getDbResNum()
559                     .equalsIgnoreCase("None") ? String.valueOf(UNASSIGNED)
560                     : cRefDb.getDbResNum();
561             try
562             {
563               currSeqIndex = Integer.valueOf(resNumIndexString);
564             } catch (NumberFormatException nfe)
565             {
566               currSeqIndex = Integer.valueOf(resNumIndexString
567                       .split("[a-zA-Z]")[0]);
568               continue;
569             }
570             if (pdbRefDb != null)
571             {
572               break;// exit loop if pdb and uniprot are already found
573             }
574           }
575         }
576         if (currSeqIndex == UNASSIGNED)
577         {
578           continue;
579         }
580         if (currSeqIndex >= seq.getStart() && currSeqIndex <= seq.getEnd())
581         {
582           int resNum;
583           try
584           {
585             resNum = (pdbRefDb == null) ? Integer.valueOf(residue
586                     .getDbResNum()) : Integer.valueOf(pdbRefDb
587                     .getDbResNum());
588           } catch (NumberFormatException nfe)
589           {
590             resNum = (pdbRefDb == null) ? Integer.valueOf(residue
591                     .getDbResNum()) : Integer.valueOf(pdbRefDb
592                     .getDbResNum().split("[a-zA-Z]")[0]);
593             continue;
594           }
595
596           if (isResidueObserved(residue)
597                   || seqCoordSys == CoordinateSys.UNIPROT)
598           {
599             char resCharCode = ResidueProperties
600                     .getSingleCharacterCode(ResidueProperties
601                             .getCanonicalAminoAcid(residue.getDbResName()));
602             resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
603           }
604           else
605           {
606             omitNonObserved.add(currSeqIndex);
607             ++nonObservedShiftIndex;
608           }
609           mapping.put(currSeqIndex - nonObservedShiftIndex, new int[] {
610               Integer.valueOf(resNum), UNASSIGNED });
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
767
768   @Override
769   public Entity getEntityById(String id) throws SiftsException
770   {
771     // Determines an entity to process by performing a heuristic matching of all
772     // Entities with the given chainId and choosing the best matching Entity
773     Entity entity = getEntityByMostOptimalMatchedId(id);
774     if (entity != null)
775     {
776       return entity;
777     }
778     throw new SiftsException("Entity " + id + " not found");
779   }
780
781   /**
782    * This method was added because EntityId is NOT always equal to ChainId.
783    * Hence, it provides the logic to greedily detect the "true" Entity for a
784    * given chainId where discrepancies exist.
785    * 
786    * @param chainId
787    * @return
788    */
789   public Entity getEntityByMostOptimalMatchedId(String chainId)
790   {
791     // System.out.println("---> advanced greedy entityId matching block entered..");
792     List<Entity> entities = siftsEntry.getEntity();
793     SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
794     int count = 0;
795     for (Entity entity : entities)
796     {
797       sPojo[count] = new SiftsEntitySortPojo();
798       sPojo[count].entityId = entity.getEntityId();
799
800       List<Segment> segments = entity.getSegment();
801       for (Segment segment : segments)
802       {
803         List<Residue> residues = segment.getListResidue().getResidue();
804         for (Residue residue : residues)
805         {
806           List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
807           for (CrossRefDb cRefDb : cRefDbs)
808           {
809             if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
810             {
811               continue;
812             }
813             ++sPojo[count].resCount;
814             if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
815             {
816               ++sPojo[count].chainIdFreq;
817             }
818           }
819         }
820       }
821       sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
822               / sPojo[count].resCount;
823       ++count;
824     }
825     Arrays.sort(sPojo, Collections.reverseOrder());
826     // System.out.println("highest matched entity : " + sPojo[0].entityId);
827     // System.out.println("highest matched pid : " + sPojo[0].pid);
828
829     if (sPojo[0].entityId != null)
830     {
831       for (Entity entity : entities)
832       {
833         if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
834         {
835           continue;
836         }
837         return entity;
838       }
839     }
840     return null;
841   }
842
843   private class SiftsEntitySortPojo implements
844           Comparable<SiftsEntitySortPojo>
845   {
846     public String entityId;
847
848     public int chainIdFreq;
849
850     public int pid;
851
852     public int resCount;
853
854     @Override
855     public int compareTo(SiftsEntitySortPojo o)
856     {
857       return this.pid - o.pid;
858     }
859   }
860
861   private class SegmentHelperPojo
862   {
863     private SequenceI seq;
864
865     private HashMap<Integer, int[]> mapping;
866
867     private TreeMap<Integer, String> resNumMap;
868
869     private List<Integer> omitNonObserved;
870
871     private int nonObservedShiftIndex;
872
873     public SegmentHelperPojo(SequenceI seq,
874             HashMap<Integer, int[]> mapping,
875             TreeMap<Integer, String> resNumMap,
876             List<Integer> omitNonObserved, int nonObservedShiftIndex)
877     {
878       setSeq(seq);
879       setMapping(mapping);
880       setResNumMap(resNumMap);
881       setOmitNonObserved(omitNonObserved);
882       setNonObservedShiftIndex(nonObservedShiftIndex);
883     }
884
885     public SequenceI getSeq()
886     {
887       return seq;
888     }
889
890     public void setSeq(SequenceI seq)
891     {
892       this.seq = seq;
893     }
894
895     public HashMap<Integer, int[]> getMapping()
896     {
897       return mapping;
898     }
899
900     public void setMapping(HashMap<Integer, int[]> mapping)
901     {
902       this.mapping = mapping;
903     }
904
905     public TreeMap<Integer, String> getResNumMap()
906     {
907       return resNumMap;
908     }
909
910     public void setResNumMap(TreeMap<Integer, String> resNumMap)
911     {
912       this.resNumMap = resNumMap;
913     }
914
915     public List<Integer> getOmitNonObserved()
916     {
917       return omitNonObserved;
918     }
919
920     public void setOmitNonObserved(List<Integer> omitNonObserved)
921     {
922       this.omitNonObserved = omitNonObserved;
923     }
924
925     public int getNonObservedShiftIndex()
926     {
927       return nonObservedShiftIndex;
928     }
929
930     public void setNonObservedShiftIndex(int nonObservedShiftIndex)
931     {
932       this.nonObservedShiftIndex = nonObservedShiftIndex;
933     }
934   }
935
936   @Override
937   public StringBuffer getMappingOutput(MappingOutputPojo mp)
938           throws SiftsException
939   {
940     String seqRes = mp.getSeqResidue();
941     String seqName = mp.getSeqName();
942     int sStart = mp.getSeqStart();
943     int sEnd = mp.getSeqEnd();
944
945     String strRes = mp.getStrResidue();
946     String strName = mp.getStrName();
947     int pdbStart = mp.getStrStart();
948     int pdbEnd = mp.getStrEnd();
949
950     String type = mp.getType();
951
952     int maxid = (seqName.length() >= strName.length()) ? seqName.length()
953             : strName.length();
954     int len = 72 - maxid - 1;
955
956     int nochunks = ((seqRes.length()) / len)
957             + ((seqRes.length()) % len > 0 ? 1 : 0);
958     // output mappings
959     StringBuffer output = new StringBuffer();
960     output.append(NEWLINE);
961     output.append("Sequence \u27f7 Structure mapping details").append(
962             NEWLINE);
963     output.append("Method: SIFTS");
964     output.append(NEWLINE).append(NEWLINE);
965
966     output.append(new Format("%" + maxid + "s").form(seqName));
967     output.append(" :  ");
968     output.append(String.valueOf(sStart));
969     output.append(" - ");
970     output.append(String.valueOf(sEnd));
971     output.append(" Maps to ");
972     output.append(NEWLINE);
973     output.append(new Format("%" + maxid + "s").form(structId));
974     output.append(" :  ");
975     output.append(String.valueOf(pdbStart));
976     output.append(" - ");
977     output.append(String.valueOf(pdbEnd));
978     output.append(NEWLINE).append(NEWLINE);
979
980     int matchedSeqCount = 0;
981     for (int j = 0; j < nochunks; j++)
982     {
983       // Print the first aligned sequence
984       output.append(new Format("%" + (maxid) + "s").form(seqName)).append(
985               " ");
986
987       for (int i = 0; i < len; i++)
988       {
989         if ((i + (j * len)) < seqRes.length())
990         {
991           output.append(seqRes.charAt(i + (j * len)));
992         }
993       }
994
995       output.append(NEWLINE);
996       output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
997
998       // Print out the matching chars
999       for (int i = 0; i < len; i++)
1000       {
1001         try
1002         {
1003           if ((i + (j * len)) < seqRes.length())
1004           {
1005             if (seqRes.charAt(i + (j * len)) == strRes
1006                     .charAt(i + (j * len))
1007                     && !jalview.util.Comparison.isGap(seqRes.charAt(i
1008                             + (j * len))))
1009             {
1010               matchedSeqCount++;
1011               output.append("|");
1012             }
1013             else if (type.equals("pep"))
1014             {
1015               if (ResidueProperties.getPAM250(seqRes.charAt(i + (j * len)),
1016                       strRes.charAt(i + (j * len))) > 0)
1017               {
1018                 output.append(".");
1019               }
1020               else
1021               {
1022                 output.append(" ");
1023               }
1024             }
1025             else
1026             {
1027               output.append(" ");
1028             }
1029           }
1030         } catch (IndexOutOfBoundsException e)
1031         {
1032           continue;
1033         }
1034       }
1035       // Now print the second aligned sequence
1036       output = output.append(NEWLINE);
1037       output = output.append(new Format("%" + (maxid) + "s").form(strName))
1038               .append(" ");
1039       for (int i = 0; i < len; i++)
1040       {
1041         if ((i + (j * len)) < strRes.length())
1042         {
1043           output.append(strRes.charAt(i + (j * len)));
1044         }
1045       }
1046       output.append(NEWLINE).append(NEWLINE);
1047     }
1048     float pid = (float) matchedSeqCount / seqRes.length() * 100;
1049     if (pid < SiftsSettings.getFailSafePIDThreshold())
1050     {
1051       throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1052     }
1053     output.append("Length of alignment = " + seqRes.length()).append(
1054             NEWLINE);
1055     output.append(new Format("Percentage ID = %2.2f").form(pid));
1056     return output;
1057   }
1058
1059   @Override
1060   public int getEntityCount()
1061   {
1062     return siftsEntry.getEntity().size();
1063   }
1064
1065   @Override
1066   public String getDbAccessionId()
1067   {
1068     return siftsEntry.getDbAccessionId();
1069   }
1070
1071   @Override
1072   public String getDbCoordSys()
1073   {
1074     return siftsEntry.getDbCoordSys();
1075   }
1076
1077   @Override
1078   public String getDbSource()
1079   {
1080     return siftsEntry.getDbSource();
1081   }
1082
1083   @Override
1084   public String getDbVersion()
1085   {
1086     return siftsEntry.getDbVersion();
1087   }
1088
1089 }