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