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 throw new SiftsException("Could not get source DB Ref");
326 for (DBRefEntryI dbRef : dbRefs)
328 if (dbRef == null || dbRef.getAccessionId() == null
329 || dbRef.getSource() == null)
333 if (isFoundInSiftsEntry(dbRef.getAccessionId())
334 && (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT) || dbRef
335 .getSource().equalsIgnoreCase(DBRefSource.PDB)))
341 if (sourceDBRef != null && isValidDBRefEntry(sourceDBRef))
345 throw new SiftsException("Could not get source DB Ref");
350 * Check that the DBRef Entry is properly populated and is available in this
351 * SiftClient instance
354 * - DBRefEntry to validate
355 * @return true validation is successful otherwise false is returned.
357 private boolean isValidDBRefEntry(DBRefEntryI entry)
359 return entry != null && entry.getAccessionId() != null
360 && isFoundInSiftsEntry(entry.getAccessionId());
364 public HashSet<String> getAllMappingAccession()
366 HashSet<String> accessions = new HashSet<String>();
367 List<Entity> entities = siftsEntry.getEntity();
368 for (Entity entity : entities)
370 List<Segment> segments = entity.getSegment();
371 for (Segment segment : segments)
373 List<MapRegion> mapRegions = segment.getListMapRegion()
375 for (MapRegion mapRegion : mapRegions)
377 accessions.add(mapRegion.getDb().getDbAccessionId());
385 public StructureMapping getSiftsStructureMapping(SequenceI seq,
386 String pdbFile, String chain) throws SiftsException
388 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
389 System.out.println("Getting mapping for: " + pdbId + "|" + chain
390 + " : seq- " + seq.getName());
392 final StringBuilder mappingDetails = new StringBuilder(128);
393 PrintStream ps = new PrintStream(System.out)
396 public void print(String x)
398 mappingDetails.append(x);
402 public void println()
404 mappingDetails.append(NEWLINE);
407 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
409 String mappingOutput = mappingDetails.toString();
410 StructureMapping siftsMapping = new StructureMapping(seq, pdbFile,
411 pdbId, chain, mapping,
417 public HashMap<Integer, int[]> getGreedyMapping(String entityId, SequenceI seq,
418 java.io.PrintStream os)
419 throws SiftsException
421 ArrayList<Integer> omitNonObserved = new ArrayList<Integer>();
422 int nonObservedShiftIndex = 0;
423 System.out.println("Generating mappings for : " + entityId);
424 Entity entity = null;
425 entity = getEntityById(entityId);
426 String originalSeq = AlignSeq.extractGaps(
427 jalview.util.Comparison.GapChars,
428 seq.getSequenceAsString());
429 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
430 DBRefEntryI sourceDBRef = seq.getSourceDBRef();
431 if (sourceDBRef == null)
433 sourceDBRef = getValidSourceDBRef(seq);
434 // TODO ensure sequence start/end is in the same coordinate system and
435 // consistent with the choosen sourceDBRef
438 // set sequence coordinate system - default value is UniProt
439 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
441 seqCoordSys = CoordinateSys.PDB;
444 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
445 for (DBRefEntry dbref : seq.getDBRefs())
447 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
449 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
451 curDBRefAccessionIdsString = dbRefAccessionIdsString;
452 curSourceDBRef = sourceDBRef.getAccessionId();
454 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
455 List<Segment> segments = entity.getSegment();
456 for (Segment segment : segments)
458 segStartEnd = segment.getStart() + " - " + segment.getEnd();
459 System.out.println("Mappging segments : " + segment.getSegId() + "\\"
461 List<Residue> residues = segment.getListResidue().getResidue();
462 for (Residue residue : residues)
464 int currSeqIndex = UNASSIGNED;
465 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
466 CrossRefDb pdbRefDb = null;
467 for (CrossRefDb cRefDb : cRefDbs)
469 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
473 if (cRefDb.getDbCoordSys()
474 .equalsIgnoreCase(seqCoordSys.getName())
475 && isAccessionMatched(cRefDb.getDbAccessionId()))
477 String resNumIndexString = cRefDb.getDbResNum()
478 .equalsIgnoreCase("None") ? String.valueOf(UNASSIGNED)
479 : cRefDb.getDbResNum();
480 currSeqIndex = Integer.valueOf(resNumIndexString);
481 if (pdbRefDb != null)
483 break;// exit loop if pdb and uniprot are already found
487 if (currSeqIndex == UNASSIGNED)
491 if (currSeqIndex > seq.getStart() && currSeqIndex <= seq.getEnd())
496 resNum = (pdbRefDb == null) ? Integer.valueOf(residue
497 .getDbResNum()) : Integer.valueOf(pdbRefDb.getDbResNum());
498 } catch (NumberFormatException nfe)
500 resNum = (pdbRefDb == null) ? Integer.valueOf(residue
501 .getDbResNum()) : Integer.valueOf(pdbRefDb
502 .getDbResNum().split("[a-zA-Z]")[0]);
505 if (isResidueObserved(residue)
506 || seqCoordSys == CoordinateSys.UNIPROT)
508 char resCharCode = ResidueProperties
509 .getSingleCharacterCode(residue.getDbResName());
510 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
514 omitNonObserved.add(currSeqIndex);
515 ++nonObservedShiftIndex;
517 mapping.put(currSeqIndex - nonObservedShiftIndex, new int[] {
518 Integer.valueOf(resNum), UNASSIGNED });
524 populateAtomPositions(entityId, mapping);
525 } catch (Exception e)
529 padWithGaps(resNumMap, omitNonObserved);
530 int seqStart = UNASSIGNED;
531 int seqEnd = UNASSIGNED;
532 int pdbStart = UNASSIGNED;
533 int pdbEnd = UNASSIGNED;
535 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
538 seqEnd = keys[keys.length - 1];
540 String matchedSeq = originalSeq;
541 if (seqStart != UNASSIGNED)
543 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
544 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
545 int orignalSeqStart = seq.getStart();
546 if (orignalSeqStart >= 1)
548 int subSeqStart = seqStart - orignalSeqStart;
549 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
550 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
552 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
556 StringBuilder targetStrucSeqs = new StringBuilder();
557 for (String res : resNumMap.values())
559 targetStrucSeqs.append(res);
564 MappingOutputPojo mop = new MappingOutputPojo();
565 mop.setSeqStart(seqStart);
566 mop.setSeqEnd(seqEnd);
567 mop.setSeqName(seq.getName());
568 mop.setSeqResidue(matchedSeq);
570 mop.setStrStart(pdbStart);
571 mop.setStrEnd(pdbEnd);
572 mop.setStrName(structId);
573 mop.setStrResidue(targetStrucSeqs.toString());
576 os.print(getMappingOutput(mop).toString());
582 * Checks if the residue instance is marked 'Not_observed' or not
587 private boolean isResidueObserved(Residue residue)
589 String annotation = getResidueAnnotaiton(residue,
590 ResidueDetailType.ANNOTATION);
591 if (annotation == null)
595 if (!annotation.equalsIgnoreCase(NOT_FOUND)
596 && annotation.equalsIgnoreCase(NOT_OBSERVED))
604 * Get annotation String for a given residue and annotation type
610 private String getResidueAnnotaiton(Residue residue,
611 ResidueDetailType type)
613 List<ResidueDetail> resDetails = residue.getResidueDetail();
614 for (ResidueDetail resDetail : resDetails)
616 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
618 return resDetail.getContent();
625 public boolean isAccessionMatched(String accession)
627 boolean isStrictMatch = true;
628 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
629 : curDBRefAccessionIdsString.contains(accession.toLowerCase());
632 private boolean isFoundInSiftsEntry(String accessionId)
634 return accessionId != null
635 && getAllMappingAccession().contains(accessionId);
639 * Pad omitted residue positions in PDB sequence with gaps
643 void padWithGaps(TreeMap<Integer, String> resNumMap,
644 ArrayList<Integer> omitNonObserved)
646 if (resNumMap == null || resNumMap.isEmpty())
650 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
652 int firstIndex = keys[0];
653 int lastIndex = keys[keys.length - 1];
654 System.out.println("Min value " + firstIndex);
655 System.out.println("Max value " + lastIndex);
656 for (int x = firstIndex; x <= lastIndex; x++)
658 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
660 resNumMap.put(x, "-");
669 * Target chain to populate mapping of its atom positions.
671 * Two dimension array of residue index versus atom position
672 * @throws IllegalArgumentException
673 * Thrown if chainId or mapping is null
675 void populateAtomPositions(String chainId, HashMap<Integer, int[]> mapping)
676 throws IllegalArgumentException
678 PDBChain chain = pdb.findChain(chainId);
679 if (chain == null || mapping == null)
681 throw new IllegalArgumentException(
682 "Chain id or mapping must not be null.");
684 for (int[] map : mapping.values())
686 if (map[PDB_RES_POS] != UNASSIGNED)
688 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
695 * @param residueIndex
696 * The residue index used for the search
698 * A collection of Atom to search
699 * @return atom position for the given residue index
701 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
705 throw new IllegalArgumentException(
706 "atoms collection must not be null!");
708 for (Atom atom : atoms)
710 if (atom.resNumber == residueIndex)
712 return atom.atomIndex;
719 public Entity getEntityById(String id) throws SiftsException
721 List<Entity> entities = siftsEntry.getEntity();
722 for (Entity entity : entities)
724 if (!entity.getEntityId().equalsIgnoreCase(id))
730 throw new SiftsException("Entity " + id + " not found");
734 public String[] getEntryDBs()
736 System.out.println("\nListing DB entries...");
737 List<String> availDbs = new ArrayList<String>();
738 List<Db> dbs = siftsEntry.getListDB().getDb();
741 availDbs.add(db.getDbSource());
742 System.out.println(db.getDbSource() + " | " + db.getDbCoordSys());
744 return availDbs.toArray(new String[0]);
748 public StringBuffer getMappingOutput(MappingOutputPojo mp)
749 throws SiftsException
751 String seqRes = mp.getSeqResidue();
752 String seqName = mp.getSeqName();
753 int sStart = mp.getSeqStart();
754 int sEnd = mp.getSeqEnd();
756 String strRes = mp.getStrResidue();
757 String strName = mp.getStrName();
758 int pdbStart = mp.getStrStart();
759 int pdbEnd = mp.getStrEnd();
761 String type = mp.getType();
763 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
765 int len = 72 - maxid - 1;
767 int nochunks = ((seqRes.length()) / len)
768 + ((seqRes.length()) % len > 0 ? 1 : 0);
770 StringBuffer output = new StringBuffer();
771 output.append(NEWLINE);
772 output.append("Sequence ⟷ Structure mapping details").append(NEWLINE);
773 output.append("Method: SIFTS");
774 output.append(NEWLINE).append(NEWLINE);
776 output.append(new Format("%" + maxid + "s").form(seqName));
777 output.append(" : ");
778 output.append(String.valueOf(sStart));
779 output.append(" - ");
780 output.append(String.valueOf(sEnd));
781 output.append(" Maps to ");
782 output.append(NEWLINE);
783 output.append(new Format("%" + maxid + "s").form(structId));
784 output.append(" : ");
785 output.append(String.valueOf(pdbStart));
786 output.append(" - ");
787 output.append(String.valueOf(pdbEnd));
788 output.append(NEWLINE).append(NEWLINE);
790 int matchedSeqCount = 0;
791 for (int j = 0; j < nochunks; j++)
793 // Print the first aligned sequence
794 output.append(new Format("%" + (maxid) + "s").form(seqName)).append(
797 for (int i = 0; i < len; i++)
799 if ((i + (j * len)) < seqRes.length())
801 output.append(seqRes.charAt(i + (j * len)));
805 output.append(NEWLINE);
806 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
808 // Print out the matching chars
809 for (int i = 0; i < len; i++)
813 if ((i + (j * len)) < seqRes.length())
815 if (seqRes.charAt(i + (j * len)) == strRes.charAt(i + (j * len))
816 && !jalview.util.Comparison.isGap(seqRes.charAt(i
822 else if (type.equals("pep"))
824 if (ResidueProperties.getPAM250(seqRes.charAt(i + (j * len)),
825 strRes.charAt(i + (j * len))) > 0)
839 } catch (IndexOutOfBoundsException e)
844 // Now print the second aligned sequence
845 output = output.append(NEWLINE);
846 output = output.append(new Format("%" + (maxid) + "s").form(strName))
848 for (int i = 0; i < len; i++)
850 if ((i + (j * len)) < strRes.length())
852 output.append(strRes.charAt(i + (j * len)));
855 output.append(NEWLINE).append(NEWLINE);
857 float pid = (float) matchedSeqCount / seqRes.length() * 100;
860 throw new SiftsException("Low PID detected for SIFTs mapping...");
862 output.append("Length of alignment = " + seqRes.length())
864 output.append(new Format("Percentage ID = %2.2f").form(pid));
865 output.append(NEWLINE);
870 public int getEntityCount()
872 return siftsEntry.getEntity().size();
876 public String getDbAccessionId()
878 return siftsEntry.getDbAccessionId();
882 public String getDbCoordSys()
884 return siftsEntry.getDbCoordSys();
888 public String getDbEvidence()
890 return siftsEntry.getDbEvidence();
894 public String getDbSource()
896 return siftsEntry.getDbSource();
900 public String getDbVersion()
902 return siftsEntry.getDbVersion();