2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.ws.sifts;
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;
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;
49 import java.net.URLConnection;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.Collection;
53 import java.util.HashMap;
54 import java.util.HashSet;
55 import java.util.List;
56 import java.util.TreeMap;
57 import java.util.zip.GZIPInputStream;
59 import javax.xml.bind.JAXBContext;
60 import javax.xml.bind.JAXBException;
61 import javax.xml.bind.Unmarshaller;
62 import javax.xml.stream.FactoryConfigurationError;
63 import javax.xml.stream.XMLInputFactory;
64 import javax.xml.stream.XMLStreamException;
65 import javax.xml.stream.XMLStreamReader;
68 import MCview.PDBChain;
69 import MCview.PDBfile;
71 public class SiftsClient implements SiftsClientI
73 private Entry siftsEntry;
79 private String structId;
81 private String segStartEnd;
83 private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
85 private static final int BUFFER_SIZE = 4096;
87 public static final int UNASSIGNED = -1;
89 private static final int PDB_RES_POS = 0;
91 private static final int PDB_ATOM_POS = 1;
93 private static final String NOT_FOUND = "Not_Found";
95 private static final String NOT_OBSERVED = "Not_Observed";
97 private static final String SIFTS_FTP_BASE_URL = "ftp://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/";
99 private final static String NEWLINE = System.lineSeparator();
101 private String curSourceDBRef;
103 private HashSet<String> curDBRefAccessionIdsString;
105 public enum CoordinateSys
107 UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
110 private CoordinateSys(String name)
115 public String getName()
121 public enum ResidueDetailType
123 NAME_SEC_STRUCTURE("nameSecondaryStructure"), CODE_SEC_STRUCTURE(
124 "codeSecondaryStructure"), ANNOTATION("Annotation");
127 private ResidueDetailType(String code)
132 public String getCode()
139 * Fetch SIFTs file for the given PDBfile and construct an instance of
143 * @throws SiftsException
145 public SiftsClient(PDBfile pdb) throws SiftsException
149 File siftsFile = getSiftsFile(pdbId);
150 siftsEntry = parseSIFTs(siftsFile);
154 * Construct an instance of SiftsClient using the supplied SIFTs file. Note:
155 * The SIFTs file should correspond to the PDB Id in PDBfile instance
159 * @throws SiftsException
162 public SiftsClient(PDBfile pdb, File siftsFile) throws SiftsException
166 siftsEntry = parseSIFTs(siftsFile);
170 * Parse the given SIFTs File and return a JAXB POJO of parsed data
173 * - the GZipped SIFTs XML file to parse
176 * if a problem occurs while parsing the SIFTs XML
178 private Entry parseSIFTs(File siftFile) throws SiftsException
180 try (InputStream in = new FileInputStream(siftFile);
181 GZIPInputStream gzis = new GZIPInputStream(in);)
183 System.out.println("File : " + siftFile.getAbsolutePath());
184 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
185 XMLStreamReader streamReader = XMLInputFactory.newInstance()
186 .createXMLStreamReader(gzis);
187 Unmarshaller um = jc.createUnmarshaller();
188 return (Entry) um.unmarshal(streamReader);
189 } catch (JAXBException e)
192 throw new SiftsException(e.getMessage());
193 } catch (FileNotFoundException e)
196 throw new SiftsException(e.getMessage());
197 } catch (XMLStreamException e)
200 throw new SiftsException(e.getMessage());
201 } catch (FactoryConfigurationError e)
204 throw new SiftsException(e.getMessage());
205 } catch (IOException e)
208 throw new SiftsException(e.getMessage());
213 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
214 * repository if not found in cache
217 * @return SIFTs XML file
218 * @throws SiftsException
220 public static File getSiftsFile(String pdbId) throws SiftsException
222 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
223 + pdbId.toLowerCase()
225 if (siftsFile.exists())
227 // TODO it may be worth performing an age check to determine if a
228 // new SIFTs file should be re-downloaded as SIFTs entries are usually
230 System.out.println(">>> SIFTS File already downloaded for " + pdbId);
233 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
238 * Download a SIFTs XML file for a given PDB Id from an FTP repository
241 * @return downloaded SIFTs XML file
242 * @throws SiftsException
244 public static File downloadSiftsFile(String pdbId) throws SiftsException
246 String siftFile = pdbId + ".xml.gz";
247 String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
248 String downloadedSiftsFile = SiftsSettings.getSiftDownloadDirectory()
250 File siftsDownloadDir = new File(
251 SiftsSettings.getSiftDownloadDirectory());
252 if (!siftsDownloadDir.exists())
254 siftsDownloadDir.mkdirs();
258 System.out.println(">> Download ftp url : " + siftsFileFTPURL);
259 URL url = new URL(siftsFileFTPURL);
260 URLConnection conn = url.openConnection();
261 InputStream inputStream = conn.getInputStream();
262 FileOutputStream outputStream = new FileOutputStream(
263 downloadedSiftsFile);
264 byte[] buffer = new byte[BUFFER_SIZE];
266 while ((bytesRead = inputStream.read(buffer)) != -1)
268 outputStream.write(buffer, 0, bytesRead);
270 outputStream.close();
272 System.out.println(">>> File downloaded : " + downloadedSiftsFile);
273 } catch (IOException ex)
275 throw new SiftsException(ex.getMessage());
277 return new File(downloadedSiftsFile);
281 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
285 * @return true if the file was deleted or doesn't exist
287 public static boolean deleteSiftsFileByPDBId(String pdbId)
289 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
290 + pdbId.toLowerCase()
292 if (siftsFile.exists())
294 return siftsFile.delete();
301 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
304 * - the target sequence for the operation
305 * @return a valid DBRefEntry that is SIFTs compatible
307 * if no valid source DBRefEntry was found for the given sequences
309 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
310 throws SiftsException
312 DBRefEntryI sourceDBRef = null;
313 sourceDBRef = seq.getSourceDBRef();
314 if (sourceDBRef != null && isValidDBRefEntry(sourceDBRef))
320 DBRefEntry[] dbRefs = seq.getDBRefs();
321 // if (dbRefs == null || dbRefs.length < 1)
323 // // final SequenceI[] seqs = new SequenceI[] { seq };
324 // // new jalview.ws.DBRefFetcher(seqs, null, null, null, false)
325 // // .fetchDBRefs(true);
326 // dbRefs = seq.getDBRefs();
329 if (dbRefs == null || dbRefs.length < 1)
331 throw new SiftsException("Could not get source DB Ref");
334 for (DBRefEntryI dbRef : dbRefs)
336 if (dbRef == null || dbRef.getAccessionId() == null
337 || dbRef.getSource() == null)
341 if (isFoundInSiftsEntry(dbRef.getAccessionId())
342 && (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT) || dbRef
343 .getSource().equalsIgnoreCase(DBRefSource.PDB)))
349 if (sourceDBRef != null && isValidDBRefEntry(sourceDBRef))
353 throw new SiftsException("Could not get source DB Ref");
358 * Check that the DBRef Entry is properly populated and is available in this
359 * SiftClient instance
362 * - DBRefEntry to validate
363 * @return true validation is successful otherwise false is returned.
365 private boolean isValidDBRefEntry(DBRefEntryI entry)
367 return entry != null && entry.getAccessionId() != null
368 && isFoundInSiftsEntry(entry.getAccessionId());
372 public HashSet<String> getAllMappingAccession()
374 HashSet<String> accessions = new HashSet<String>();
375 List<Entity> entities = siftsEntry.getEntity();
376 for (Entity entity : entities)
378 List<Segment> segments = entity.getSegment();
379 for (Segment segment : segments)
381 List<MapRegion> mapRegions = segment.getListMapRegion()
383 for (MapRegion mapRegion : mapRegions)
385 accessions.add(mapRegion.getDb().getDbAccessionId());
393 public StructureMapping getSiftsStructureMapping(SequenceI seq,
394 String pdbFile, String chain) throws SiftsException
396 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
397 System.out.println("Getting mapping for: " + pdbId + "|" + chain
398 + " : seq- " + seq.getName());
400 final StringBuilder mappingDetails = new StringBuilder(128);
401 PrintStream ps = new PrintStream(System.out)
404 public void print(String x)
406 mappingDetails.append(x);
410 public void println()
412 mappingDetails.append(NEWLINE);
415 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
417 String mappingOutput = mappingDetails.toString();
418 StructureMapping siftsMapping = new StructureMapping(seq, pdbFile,
419 pdbId, chain, mapping,
425 public HashMap<Integer, int[]> getGreedyMapping(String entityId, SequenceI seq,
426 java.io.PrintStream os)
427 throws SiftsException
429 ArrayList<Integer> omitNonObserved = new ArrayList<Integer>();
430 int nonObservedShiftIndex = 0;
431 System.out.println("Generating mappings for : " + entityId);
432 Entity entity = null;
433 entity = getEntityById(entityId);
434 String originalSeq = AlignSeq.extractGaps(
435 jalview.util.Comparison.GapChars,
436 seq.getSequenceAsString());
437 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
438 DBRefEntryI sourceDBRef = seq.getSourceDBRef();
439 if (sourceDBRef == null)
441 sourceDBRef = getValidSourceDBRef(seq);
442 // TODO ensure sequence start/end is in the same coordinate system and
443 // consistent with the choosen sourceDBRef
446 // set sequence coordinate system - default value is UniProt
447 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
449 seqCoordSys = CoordinateSys.PDB;
452 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
453 for (DBRefEntry dbref : seq.getDBRefs())
455 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
457 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
459 curDBRefAccessionIdsString = dbRefAccessionIdsString;
460 curSourceDBRef = sourceDBRef.getAccessionId();
462 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
463 List<Segment> segments = entity.getSegment();
464 for (Segment segment : segments)
466 segStartEnd = segment.getStart() + " - " + segment.getEnd();
467 System.out.println("Mappging segments : " + segment.getSegId() + "\\"
469 List<Residue> residues = segment.getListResidue().getResidue();
470 for (Residue residue : residues)
472 int currSeqIndex = UNASSIGNED;
473 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
474 CrossRefDb pdbRefDb = null;
475 for (CrossRefDb cRefDb : cRefDbs)
477 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
481 if (cRefDb.getDbCoordSys()
482 .equalsIgnoreCase(seqCoordSys.getName())
483 && isAccessionMatched(cRefDb.getDbAccessionId()))
485 String resNumIndexString = cRefDb.getDbResNum()
486 .equalsIgnoreCase("None") ? String.valueOf(UNASSIGNED)
487 : cRefDb.getDbResNum();
488 currSeqIndex = Integer.valueOf(resNumIndexString);
489 if (pdbRefDb != null)
491 break;// exit loop if pdb and uniprot are already found
495 if (currSeqIndex == UNASSIGNED)
499 if (currSeqIndex > seq.getStart() && currSeqIndex <= seq.getEnd())
504 resNum = (pdbRefDb == null) ? Integer.valueOf(residue
505 .getDbResNum()) : Integer.valueOf(pdbRefDb.getDbResNum());
506 } catch (NumberFormatException nfe)
508 resNum = (pdbRefDb == null) ? Integer.valueOf(residue
509 .getDbResNum()) : Integer.valueOf(pdbRefDb
510 .getDbResNum().split("[a-zA-Z]")[0]);
513 if (isResidueObserved(residue)
514 || seqCoordSys == CoordinateSys.UNIPROT)
516 char resCharCode = ResidueProperties
517 .getSingleCharacterCode(residue.getDbResName());
518 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
522 omitNonObserved.add(currSeqIndex);
523 ++nonObservedShiftIndex;
525 mapping.put(currSeqIndex - nonObservedShiftIndex, new int[] {
526 Integer.valueOf(resNum), UNASSIGNED });
532 populateAtomPositions(entityId, mapping);
533 } catch (Exception e)
537 padWithGaps(resNumMap, omitNonObserved);
538 int seqStart = UNASSIGNED;
539 int seqEnd = UNASSIGNED;
540 int pdbStart = UNASSIGNED;
541 int pdbEnd = UNASSIGNED;
543 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
546 seqEnd = keys[keys.length - 1];
548 String matchedSeq = originalSeq;
549 if (seqStart != UNASSIGNED)
551 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
552 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
553 int orignalSeqStart = seq.getStart();
554 if (orignalSeqStart >= 1)
556 int subSeqStart = seqStart - orignalSeqStart;
557 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
558 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
560 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
564 StringBuilder targetStrucSeqs = new StringBuilder();
565 for (String res : resNumMap.values())
567 targetStrucSeqs.append(res);
572 MappingOutputPojo mop = new MappingOutputPojo();
573 mop.setSeqStart(seqStart);
574 mop.setSeqEnd(seqEnd);
575 mop.setSeqName(seq.getName());
576 mop.setSeqResidue(matchedSeq);
578 mop.setStrStart(pdbStart);
579 mop.setStrEnd(pdbEnd);
580 mop.setStrName(structId);
581 mop.setStrResidue(targetStrucSeqs.toString());
584 os.print(getMappingOutput(mop).toString());
590 * Checks if the residue instance is marked 'Not_observed' or not
595 private boolean isResidueObserved(Residue residue)
597 String annotation = getResidueAnnotaiton(residue,
598 ResidueDetailType.ANNOTATION);
599 if (annotation == null)
603 if (!annotation.equalsIgnoreCase(NOT_FOUND)
604 && annotation.equalsIgnoreCase(NOT_OBSERVED))
612 * Get annotation String for a given residue and annotation type
618 private String getResidueAnnotaiton(Residue residue,
619 ResidueDetailType type)
621 List<ResidueDetail> resDetails = residue.getResidueDetail();
622 for (ResidueDetail resDetail : resDetails)
624 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
626 return resDetail.getContent();
633 public boolean isAccessionMatched(String accession)
635 boolean isStrictMatch = true;
636 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
637 : curDBRefAccessionIdsString.contains(accession.toLowerCase());
640 private boolean isFoundInSiftsEntry(String accessionId)
642 return accessionId != null
643 && getAllMappingAccession().contains(accessionId);
647 * Pad omitted residue positions in PDB sequence with gaps
651 void padWithGaps(TreeMap<Integer, String> resNumMap,
652 ArrayList<Integer> omitNonObserved)
654 if (resNumMap == null || resNumMap.isEmpty())
658 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
660 int firstIndex = keys[0];
661 int lastIndex = keys[keys.length - 1];
662 System.out.println("Min value " + firstIndex);
663 System.out.println("Max value " + lastIndex);
664 for (int x = firstIndex; x <= lastIndex; x++)
666 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
668 resNumMap.put(x, "-");
677 * Target chain to populate mapping of its atom positions.
679 * Two dimension array of residue index versus atom position
680 * @throws IllegalArgumentException
681 * Thrown if chainId or mapping is null
683 void populateAtomPositions(String chainId, HashMap<Integer, int[]> mapping)
684 throws IllegalArgumentException
686 PDBChain chain = pdb.findChain(chainId);
687 if (chain == null || mapping == null)
689 throw new IllegalArgumentException(
690 "Chain id or mapping must not be null.");
692 for (int[] map : mapping.values())
694 if (map[PDB_RES_POS] != UNASSIGNED)
696 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
703 * @param residueIndex
704 * The residue index used for the search
706 * A collection of Atom to search
707 * @return atom position for the given residue index
709 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
713 throw new IllegalArgumentException(
714 "atoms collection must not be null!");
716 for (Atom atom : atoms)
718 if (atom.resNumber == residueIndex)
720 return atom.atomIndex;
727 public Entity getEntityById(String id) throws SiftsException
729 List<Entity> entities = siftsEntry.getEntity();
730 for (Entity entity : entities)
732 if (!entity.getEntityId().equalsIgnoreCase(id))
738 throw new SiftsException("Entity " + id + " not found");
742 public String[] getEntryDBs()
744 System.out.println("\nListing DB entries...");
745 List<String> availDbs = new ArrayList<String>();
746 List<Db> dbs = siftsEntry.getListDB().getDb();
749 availDbs.add(db.getDbSource());
750 System.out.println(db.getDbSource() + " | " + db.getDbCoordSys());
752 return availDbs.toArray(new String[0]);
756 public StringBuffer getMappingOutput(MappingOutputPojo mp)
757 throws SiftsException
759 String seqRes = mp.getSeqResidue();
760 String seqName = mp.getSeqName();
761 int sStart = mp.getSeqStart();
762 int sEnd = mp.getSeqEnd();
764 String strRes = mp.getStrResidue();
765 String strName = mp.getStrName();
766 int pdbStart = mp.getStrStart();
767 int pdbEnd = mp.getStrEnd();
769 String type = mp.getType();
771 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
773 int len = 72 - maxid - 1;
775 int nochunks = ((seqRes.length()) / len)
776 + ((seqRes.length()) % len > 0 ? 1 : 0);
778 StringBuffer output = new StringBuffer();
779 output.append(NEWLINE);
780 output.append("Sequence ⟷ Structure mapping details").append(NEWLINE);
781 output.append("Method: SIFTS");
782 output.append(NEWLINE).append(NEWLINE);
784 output.append(new Format("%" + maxid + "s").form(seqName));
785 output.append(" : ");
786 output.append(String.valueOf(sStart));
787 output.append(" - ");
788 output.append(String.valueOf(sEnd));
789 output.append(" Maps to ");
790 output.append(NEWLINE);
791 output.append(new Format("%" + maxid + "s").form(structId));
792 output.append(" : ");
793 output.append(String.valueOf(pdbStart));
794 output.append(" - ");
795 output.append(String.valueOf(pdbEnd));
796 output.append(NEWLINE).append(NEWLINE);
798 int matchedSeqCount = 0;
799 for (int j = 0; j < nochunks; j++)
801 // Print the first aligned sequence
802 output.append(new Format("%" + (maxid) + "s").form(seqName)).append(
805 for (int i = 0; i < len; i++)
807 if ((i + (j * len)) < seqRes.length())
809 output.append(seqRes.charAt(i + (j * len)));
813 output.append(NEWLINE);
814 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
816 // Print out the matching chars
817 for (int i = 0; i < len; i++)
821 if ((i + (j * len)) < seqRes.length())
823 if (seqRes.charAt(i + (j * len)) == strRes.charAt(i + (j * len))
824 && !jalview.util.Comparison.isGap(seqRes.charAt(i
830 else if (type.equals("pep"))
832 if (ResidueProperties.getPAM250(seqRes.charAt(i + (j * len)),
833 strRes.charAt(i + (j * len))) > 0)
847 } catch (IndexOutOfBoundsException e)
852 // Now print the second aligned sequence
853 output = output.append(NEWLINE);
854 output = output.append(new Format("%" + (maxid) + "s").form(strName))
856 for (int i = 0; i < len; i++)
858 if ((i + (j * len)) < strRes.length())
860 output.append(strRes.charAt(i + (j * len)));
863 output.append(NEWLINE).append(NEWLINE);
865 float pid = (float) matchedSeqCount / seqRes.length() * 100;
868 throw new SiftsException("Low PID detected for SIFTs mapping...");
870 output.append("Length of alignment = " + seqRes.length())
872 output.append(new Format("Percentage ID = %2.2f").form(pid));
873 output.append(NEWLINE);
878 public int getEntityCount()
880 return siftsEntry.getEntity().size();
884 public String getDbAccessionId()
886 return siftsEntry.getDbAccessionId();
890 public String getDbCoordSys()
892 return siftsEntry.getDbCoordSys();
896 public String getDbEvidence()
898 return siftsEntry.getDbEvidence();
902 public String getDbSource()
904 return siftsEntry.getDbSource();
908 public String getDbVersion()
910 return siftsEntry.getDbVersion();