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