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