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