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;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.PrintStream;
30 import java.net.URLConnection;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.attribute.BasicFileAttributes;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Date;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
44 import java.util.TreeMap;
45 import java.util.zip.GZIPInputStream;
47 import javax.xml.bind.JAXBContext;
48 import javax.xml.bind.Unmarshaller;
49 import javax.xml.stream.XMLInputFactory;
50 import javax.xml.stream.XMLStreamReader;
53 import MCview.PDBChain;
54 import jalview.analysis.AlignSeq;
55 import jalview.analysis.scoremodels.ScoreMatrix;
56 import jalview.analysis.scoremodels.ScoreModels;
57 import jalview.api.DBRefEntryI;
58 import jalview.api.SiftsClientI;
59 import jalview.datamodel.DBRefEntry;
60 import jalview.datamodel.DBRefSource;
61 import jalview.datamodel.SequenceI;
62 import jalview.io.BackupFiles;
63 import jalview.io.StructureFile;
64 import jalview.schemes.ResidueProperties;
65 import jalview.structure.StructureMapping;
66 import jalview.util.Comparison;
67 import jalview.util.DBRefUtils;
68 import jalview.util.Format;
69 import jalview.xml.binding.sifts.Entry;
70 import jalview.xml.binding.sifts.Entry.Entity;
71 import jalview.xml.binding.sifts.Entry.Entity.Segment;
72 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListMapRegion.MapRegion;
73 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue;
74 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.CrossRefDb;
75 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.ResidueDetail;
77 public class SiftsClient implements SiftsClientI
80 * for use in mocking out file fetch for tests only
81 * - reset to null after testing!
83 private static File mockSiftsFile;
85 private Entry siftsEntry;
87 private StructureFile pdb;
91 private String structId;
93 private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
96 * PDB sequence position to sequence coordinate mapping as derived from SIFTS
97 * record for the identified SeqCoordSys Used for lift-over from sequence
98 * derived from PDB (with first extracted PDBRESNUM as 'start' to the sequence
99 * being annotated with PDB data
101 private jalview.datamodel.Mapping seqFromPdbMapping;
103 private static final int BUFFER_SIZE = 4096;
105 public static final int UNASSIGNED = Integer.MIN_VALUE;
107 private static final int PDB_RES_POS = 0;
109 private static final int PDB_ATOM_POS = 1;
111 private static final int PDBE_POS = 2;
113 private static final String NOT_OBSERVED = "Not_Observed";
115 private static final String SIFTS_FTP_BASE_URL = "http://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/";
117 private final static String NEWLINE = System.lineSeparator();
119 private String curSourceDBRef;
121 private HashSet<String> curDBRefAccessionIdsString;
123 private enum CoordinateSys
125 UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
129 private CoordinateSys(String name)
134 public String getName()
140 private enum ResidueDetailType
142 NAME_SEC_STRUCTURE("nameSecondaryStructure"),
143 CODE_SEC_STRUCTURE("codeSecondaryStructure"), ANNOTATION("Annotation");
147 private ResidueDetailType(String code)
152 public String getCode()
159 * Fetch SIFTs file for the given PDBfile and construct an instance of
163 * @throws SiftsException
165 public SiftsClient(StructureFile pdb) throws SiftsException
168 this.pdbId = pdb.getId();
169 File siftsFile = getSiftsFile(pdbId);
170 siftsEntry = parseSIFTs(siftsFile);
174 * Parse the given SIFTs File and return a JAXB POJO of parsed data
177 * - the GZipped SIFTs XML file to parse
180 * if a problem occurs while parsing the SIFTs XML
182 private Entry parseSIFTs(File siftFile) throws SiftsException
184 try (InputStream in = new FileInputStream(siftFile);
185 GZIPInputStream gzis = new GZIPInputStream(in);)
187 // System.out.println("File : " + siftFile.getAbsolutePath());
188 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
189 XMLStreamReader streamReader = XMLInputFactory.newInstance()
190 .createXMLStreamReader(gzis);
191 Unmarshaller um = jc.createUnmarshaller();
192 return (Entry) um.unmarshal(streamReader);
193 } catch (Exception e)
196 throw new SiftsException(e.getMessage());
201 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
202 * repository if not found in cache
205 * @return SIFTs XML file
206 * @throws SiftsException
208 public static File getSiftsFile(String pdbId) throws SiftsException
211 * return mocked file if it has been set
213 if (mockSiftsFile != null)
215 return mockSiftsFile;
218 String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
219 + pdbId.toLowerCase() + ".xml.gz";
220 File siftsFile = new File(siftsFileName);
221 if (siftsFile.exists())
223 // The line below is required for unit testing... don't comment it out!!!
224 System.out.println(">>> SIFTS File already downloaded for " + pdbId);
226 if (isFileOlderThanThreshold(siftsFile,
227 SiftsSettings.getCacheThresholdInDays()))
229 File oldSiftsFile = new File(siftsFileName + "_old");
230 BackupFiles.moveFileToFile(siftsFile, oldSiftsFile);
233 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
234 oldSiftsFile.delete();
236 } catch (IOException e)
239 BackupFiles.moveFileToFile(oldSiftsFile, siftsFile);
240 return new File(siftsFileName);
250 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
251 } catch (IOException e)
253 throw new SiftsException(e.getMessage());
259 * This method enables checking if a cached file has exceeded a certain
265 * the threshold in days
268 public static boolean isFileOlderThanThreshold(File file, int noOfDays)
270 Path filePath = file.toPath();
271 BasicFileAttributes attr;
275 attr = Files.readAttributes(filePath, BasicFileAttributes.class);
276 diffInDays = (int) ((new Date().getTime()
277 - attr.lastModifiedTime().toMillis())
278 / (1000 * 60 * 60 * 24));
279 // System.out.println("Diff in days : " + diffInDays);
280 } catch (IOException e)
284 return noOfDays <= diffInDays;
288 * Download a SIFTs XML file for a given PDB Id from an FTP repository
291 * @return downloaded SIFTs XML file
292 * @throws SiftsException
293 * @throws IOException
295 public static File downloadSiftsFile(String pdbId)
296 throws SiftsException, IOException
298 if (pdbId.contains(".cif"))
300 pdbId = pdbId.replace(".cif", "");
302 String siftFile = pdbId + ".xml.gz";
303 String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
304 String downloadedSiftsFile = SiftsSettings.getSiftDownloadDirectory()
306 File siftsDownloadDir = new File(
307 SiftsSettings.getSiftDownloadDirectory());
308 if (!siftsDownloadDir.exists())
310 siftsDownloadDir.mkdirs();
312 // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
313 // long now = System.currentTimeMillis();
314 URL url = new URL(siftsFileFTPURL);
315 URLConnection conn = url.openConnection();
316 InputStream inputStream = conn.getInputStream();
317 FileOutputStream outputStream = new FileOutputStream(
318 downloadedSiftsFile);
319 byte[] buffer = new byte[BUFFER_SIZE];
321 while ((bytesRead = inputStream.read(buffer)) != -1)
323 outputStream.write(buffer, 0, bytesRead);
325 outputStream.close();
327 // System.out.println(">>> File downloaded : " + downloadedSiftsFile
328 // + " took " + (System.currentTimeMillis() - now) + "ms");
329 return new File(downloadedSiftsFile);
333 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
337 * @return true if the file was deleted or doesn't exist
339 public static boolean deleteSiftsFileByPDBId(String pdbId)
341 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
342 + pdbId.toLowerCase() + ".xml.gz");
343 if (siftsFile.exists())
345 return siftsFile.delete();
351 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
354 * - the target sequence for the operation
355 * @return a valid DBRefEntry that is SIFTs compatible
357 * if no valid source DBRefEntry was found for the given sequences
359 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
360 throws SiftsException
362 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
363 if (dbRefs == null || dbRefs.size() < 1)
365 throw new SiftsException(
366 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
369 for (DBRefEntry dbRef : dbRefs)
371 if (dbRef == null || dbRef.getAccessionId() == null
372 || dbRef.getSource() == null)
376 String canonicalSource = DBRefUtils
377 .getCanonicalName(dbRef.getSource());
378 if (isValidDBRefEntry(dbRef)
379 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
380 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
385 throw new SiftsException("Could not get source DB Ref");
389 * Check that the DBRef Entry is properly populated and is available in this
390 * SiftClient instance
393 * - DBRefEntry to validate
394 * @return true validation is successful otherwise false is returned.
396 boolean isValidDBRefEntry(DBRefEntryI entry)
398 return entry != null && entry.getAccessionId() != null
399 && isFoundInSiftsEntry(entry.getAccessionId());
403 public HashSet<String> getAllMappingAccession()
405 HashSet<String> accessions = new HashSet<String>();
406 List<Entity> entities = siftsEntry.getEntity();
407 for (Entity entity : entities)
409 List<Segment> segments = entity.getSegment();
410 for (Segment segment : segments)
412 List<MapRegion> mapRegions = segment.getListMapRegion()
414 for (MapRegion mapRegion : mapRegions)
417 .add(mapRegion.getDb().getDbAccessionId().toLowerCase());
425 public StructureMapping getSiftsStructureMapping(SequenceI seq,
426 String pdbFile, String chain) throws SiftsException
428 SequenceI aseq = seq;
429 while (seq.getDatasetSequence() != null)
431 seq = seq.getDatasetSequence();
433 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
434 System.out.println("Getting SIFTS mapping for " + structId + ": seq "
437 final StringBuilder mappingDetails = new StringBuilder(128);
438 PrintStream ps = new PrintStream(System.out)
441 public void print(String x)
443 mappingDetails.append(x);
447 public void println()
449 mappingDetails.append(NEWLINE);
452 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
454 String mappingOutput = mappingDetails.toString();
455 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
456 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
462 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
463 SequenceI seq, java.io.PrintStream os) throws SiftsException
465 List<Integer> omitNonObserved = new ArrayList<>();
466 int nonObservedShiftIndex = 0, pdbeNonObserved = 0;
467 // System.out.println("Generating mappings for : " + entityId);
468 Entity entity = null;
469 entity = getEntityById(entityId);
470 String originalSeq = AlignSeq.extractGaps(
471 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
472 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
473 DBRefEntryI sourceDBRef;
474 sourceDBRef = getValidSourceDBRef(seq);
475 // TODO ensure sequence start/end is in the same coordinate system and
476 // consistent with the choosen sourceDBRef
478 // set sequence coordinate system - default value is UniProt
479 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
481 seqCoordSys = CoordinateSys.PDB;
484 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
485 for (DBRefEntry dbref : seq.getDBRefs())
487 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
489 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
491 curDBRefAccessionIdsString = dbRefAccessionIdsString;
492 curSourceDBRef = sourceDBRef.getAccessionId();
494 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
495 List<Segment> segments = entity.getSegment();
496 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
497 omitNonObserved, nonObservedShiftIndex, pdbeNonObserved);
498 processSegments(segments, shp);
501 populateAtomPositions(entityId, mapping);
502 } catch (Exception e)
506 if (seqCoordSys == CoordinateSys.UNIPROT)
508 padWithGaps(resNumMap, omitNonObserved);
510 int seqStart = UNASSIGNED;
511 int seqEnd = UNASSIGNED;
512 int pdbStart = UNASSIGNED;
513 int pdbEnd = UNASSIGNED;
515 if (mapping.isEmpty())
517 throw new SiftsException("SIFTS mapping failed");
519 // also construct a mapping object between the seq-coord sys and the PDB
522 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
525 seqEnd = keys[keys.length - 1];
526 List<int[]> from = new ArrayList<>(), to = new ArrayList<>();
527 int[] _cfrom = null, _cto = null;
528 String matchedSeq = originalSeq;
529 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb
530 // sequence that starts <-1
532 for (int seqps : keys)
534 int pdbpos = mapping.get(seqps)[PDBE_POS];
535 if (pdbpos == UNASSIGNED)
537 // not correct - pdbpos might be -1, but leave it for now
540 if (_cfrom == null || seqps != _cfrom[1] + 1)
542 _cfrom = new int[] { seqps, seqps };
544 _cto = null; // discontinuity
550 if (_cto == null || pdbpos != 1 + _cto[1])
552 _cto = new int[] { pdbpos, pdbpos };
560 _cfrom = new int[from.size() * 2];
561 _cto = new int[to.size() * 2];
563 for (int[] range : from)
565 _cfrom[p++] = range[0];
566 _cfrom[p++] = range[1];
570 for (int[] range : to)
572 _cto[p++] = range[0];
573 _cto[p++] = range[1];
577 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
579 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
580 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
581 int orignalSeqStart = seq.getStart();
582 if (orignalSeqStart >= 1)
584 int subSeqStart = (seqStart >= orignalSeqStart)
585 ? seqStart - orignalSeqStart
587 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
588 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
590 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
594 matchedSeq = originalSeq.substring(1, originalSeq.length());
598 StringBuilder targetStrucSeqs = new StringBuilder();
599 for (String res : resNumMap.values())
601 targetStrucSeqs.append(res);
606 MappingOutputPojo mop = new MappingOutputPojo();
607 mop.setSeqStart(seqStart);
608 mop.setSeqEnd(seqEnd);
609 mop.setSeqName(seq.getName());
610 mop.setSeqResidue(matchedSeq);
612 mop.setStrStart(pdbStart);
613 mop.setStrEnd(pdbEnd);
614 mop.setStrName(structId);
615 mop.setStrResidue(targetStrucSeqs.toString());
618 os.print(getMappingOutput(mop).toString());
624 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
626 SequenceI seq = shp.getSeq();
627 HashMap<Integer, int[]> mapping = shp.getMapping();
628 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
629 List<Integer> omitNonObserved = shp.getOmitNonObserved();
630 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
631 int pdbeNonObservedCount = shp.getPdbeNonObserved();
632 int firstPDBResNum = UNASSIGNED;
633 for (Segment segment : segments)
635 // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
637 List<Residue> residues = segment.getListResidue().getResidue();
638 for (Residue residue : residues)
640 boolean isObserved = isResidueObserved(residue);
641 int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
643 int currSeqIndex = UNASSIGNED;
644 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
645 CrossRefDb pdbRefDb = null;
646 for (CrossRefDb cRefDb : cRefDbs)
648 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
651 if (firstPDBResNum == UNASSIGNED)
653 firstPDBResNum = getLeadingIntegerValue(cRefDb.getDbResNum(),
660 // after we find the first observed residue we just increment
665 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
666 && isAccessionMatched(cRefDb.getDbAccessionId()))
668 currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
670 if (pdbRefDb != null)
672 break;// exit loop if pdb and uniprot are already found
678 ++pdbeNonObservedCount;
680 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
683 // if the sequence has a primary reference to the PDB, then we are
684 // dealing with a sequence extracted directly from the PDB. In that
685 // case, numbering is PDBe - non-observed residues
686 currSeqIndex = seq.getStart() - 1 + pdbeIndex;
690 if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
693 // mapping to PDB or PDBe so we need to bookkeep for the
696 omitNonObserved.add(currSeqIndex);
697 ++nonObservedShiftIndex;
700 if (currSeqIndex == UNASSIGNED)
702 // change in logic - unobserved residues with no currSeqIndex
703 // corresponding are still counted in both nonObservedShiftIndex and
707 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
717 int resNum = (pdbRefDb == null)
718 ? getLeadingIntegerValue(residue.getDbResNum(),
720 : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
725 char resCharCode = ResidueProperties
726 .getSingleCharacterCode(ResidueProperties
727 .getCanonicalAminoAcid(residue.getDbResName()));
728 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
730 int[] mappingcols = new int[] { Integer.valueOf(resNum),
731 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
733 mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
741 * Get the leading integer part of a string that begins with an integer.
744 * - the string input to process
746 * - value returned if unsuccessful
749 static int getLeadingIntegerValue(String input, int failValue)
755 String[] parts = input.split("(?=\\D)(?<=\\d)");
756 if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
758 return Integer.valueOf(parts[0]);
766 * Target chain to populate mapping of its atom positions.
768 * Two dimension array of residue index versus atom position
769 * @throws IllegalArgumentException
770 * Thrown if chainId or mapping is null
771 * @throws SiftsException
773 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
774 throws IllegalArgumentException, SiftsException
778 PDBChain chain = pdb.findChain(chainId);
780 if (chain == null || mapping == null)
782 throw new IllegalArgumentException(
783 "Chain id or mapping must not be null.");
785 for (int[] map : mapping.values())
787 if (map[PDB_RES_POS] != UNASSIGNED)
789 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
792 } catch (NullPointerException e)
794 throw new SiftsException(e.getMessage());
795 } catch (Exception e)
797 throw new SiftsException(e.getMessage());
803 * @param residueIndex
804 * The residue index used for the search
806 * A collection of Atom to search
807 * @return atom position for the given residue index
809 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
813 throw new IllegalArgumentException(
814 "atoms collection must not be null!");
816 for (Atom atom : atoms)
818 if (atom.resNumber == residueIndex)
820 return atom.atomIndex;
827 * Checks if the residue instance is marked 'Not_observed' or not
832 private boolean isResidueObserved(Residue residue)
834 Set<String> annotations = getResidueAnnotaitons(residue,
835 ResidueDetailType.ANNOTATION);
836 if (annotations == null || annotations.isEmpty())
840 for (String annotation : annotations)
842 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
851 * Get annotation String for a given residue and annotation type
857 private Set<String> getResidueAnnotaitons(Residue residue,
858 ResidueDetailType type)
860 HashSet<String> foundAnnotations = new HashSet<String>();
861 List<ResidueDetail> resDetails = residue.getResidueDetail();
862 for (ResidueDetail resDetail : resDetails)
864 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
866 foundAnnotations.add(resDetail.getContent());
869 return foundAnnotations;
873 public boolean isAccessionMatched(String accession)
875 boolean isStrictMatch = true;
876 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
877 : curDBRefAccessionIdsString.contains(accession.toLowerCase());
880 private boolean isFoundInSiftsEntry(String accessionId)
882 Set<String> siftsDBRefs = getAllMappingAccession();
883 return accessionId != null
884 && siftsDBRefs.contains(accessionId.toLowerCase());
888 * Pad omitted residue positions in PDB sequence with gaps
892 void padWithGaps(Map<Integer, String> resNumMap,
893 List<Integer> omitNonObserved)
895 if (resNumMap == null || resNumMap.isEmpty())
899 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
900 // Arrays.sort(keys);
901 int firstIndex = keys[0];
902 int lastIndex = keys[keys.length - 1];
903 // System.out.println("Min value " + firstIndex);
904 // System.out.println("Max value " + lastIndex);
905 for (int x = firstIndex; x <= lastIndex; x++)
907 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
909 resNumMap.put(x, "-");
915 public Entity getEntityById(String id) throws SiftsException
917 // Determines an entity to process by performing a heuristic matching of all
918 // Entities with the given chainId and choosing the best matching Entity
919 Entity entity = getEntityByMostOptimalMatchedId(id);
924 throw new SiftsException("Entity " + id + " not found");
928 * This method was added because EntityId is NOT always equal to ChainId.
929 * Hence, it provides the logic to greedily detect the "true" Entity for a
930 * given chainId where discrepancies exist.
935 public Entity getEntityByMostOptimalMatchedId(String chainId)
937 // System.out.println("---> advanced greedy entityId matching block
939 List<Entity> entities = siftsEntry.getEntity();
940 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
942 for (Entity entity : entities)
944 sPojo[count] = new SiftsEntitySortPojo();
945 sPojo[count].entityId = entity.getEntityId();
947 List<Segment> segments = entity.getSegment();
948 for (Segment segment : segments)
950 List<Residue> residues = segment.getListResidue().getResidue();
951 for (Residue residue : residues)
953 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
954 for (CrossRefDb cRefDb : cRefDbs)
956 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
960 ++sPojo[count].resCount;
961 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
963 ++sPojo[count].chainIdFreq;
968 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
969 / sPojo[count].resCount;
972 Arrays.sort(sPojo, Collections.reverseOrder());
973 // System.out.println("highest matched entity : " + sPojo[0].entityId);
974 // System.out.println("highest matched pid : " + sPojo[0].pid);
976 if (sPojo[0].entityId != null)
978 if (sPojo[0].pid < 1)
982 for (Entity entity : entities)
984 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
994 private class SiftsEntitySortPojo
995 implements Comparable<SiftsEntitySortPojo>
997 public String entityId;
999 public int chainIdFreq;
1003 public int resCount;
1006 public int compareTo(SiftsEntitySortPojo o)
1008 return this.pid - o.pid;
1012 private class SegmentHelperPojo
1014 private SequenceI seq;
1016 private HashMap<Integer, int[]> mapping;
1018 private TreeMap<Integer, String> resNumMap;
1020 private List<Integer> omitNonObserved;
1022 private int nonObservedShiftIndex;
1025 * count of number of 'not observed' positions in the PDB record's SEQRES
1026 * (total number of residues with coordinates == length(SEQRES) -
1029 private int pdbeNonObserved;
1031 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1032 TreeMap<Integer, String> resNumMap,
1033 List<Integer> omitNonObserved, int nonObservedShiftIndex,
1034 int pdbeNonObserved)
1037 setMapping(mapping);
1038 setResNumMap(resNumMap);
1039 setOmitNonObserved(omitNonObserved);
1040 setNonObservedShiftIndex(nonObservedShiftIndex);
1041 setPdbeNonObserved(pdbeNonObserved);
1045 public void setPdbeNonObserved(int pdbeNonObserved2)
1047 this.pdbeNonObserved = pdbeNonObserved2;
1050 public int getPdbeNonObserved()
1052 return pdbeNonObserved;
1055 public SequenceI getSeq()
1060 public void setSeq(SequenceI seq)
1065 public HashMap<Integer, int[]> getMapping()
1070 public void setMapping(HashMap<Integer, int[]> mapping)
1072 this.mapping = mapping;
1075 public TreeMap<Integer, String> getResNumMap()
1080 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1082 this.resNumMap = resNumMap;
1085 public List<Integer> getOmitNonObserved()
1087 return omitNonObserved;
1090 public void setOmitNonObserved(List<Integer> omitNonObserved)
1092 this.omitNonObserved = omitNonObserved;
1095 public int getNonObservedShiftIndex()
1097 return nonObservedShiftIndex;
1100 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1102 this.nonObservedShiftIndex = nonObservedShiftIndex;
1108 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1109 throws SiftsException
1111 String seqRes = mp.getSeqResidue();
1112 String seqName = mp.getSeqName();
1113 int sStart = mp.getSeqStart();
1114 int sEnd = mp.getSeqEnd();
1116 String strRes = mp.getStrResidue();
1117 String strName = mp.getStrName();
1118 int pdbStart = mp.getStrStart();
1119 int pdbEnd = mp.getStrEnd();
1121 String type = mp.getType();
1123 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1125 int len = 72 - maxid - 1;
1127 int nochunks = ((seqRes.length()) / len)
1128 + ((seqRes.length()) % len > 0 ? 1 : 0);
1130 StringBuilder output = new StringBuilder(512);
1131 output.append(NEWLINE);
1132 output.append("Sequence \u27f7 Structure mapping details")
1134 output.append("Method: SIFTS");
1135 output.append(NEWLINE).append(NEWLINE);
1137 output.append(new Format("%" + maxid + "s").form(seqName));
1138 output.append(" : ");
1139 output.append(String.valueOf(sStart));
1140 output.append(" - ");
1141 output.append(String.valueOf(sEnd));
1142 output.append(" Maps to ");
1143 output.append(NEWLINE);
1144 output.append(new Format("%" + maxid + "s").form(structId));
1145 output.append(" : ");
1146 output.append(String.valueOf(pdbStart));
1147 output.append(" - ");
1148 output.append(String.valueOf(pdbEnd));
1149 output.append(NEWLINE).append(NEWLINE);
1151 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1152 int matchedSeqCount = 0;
1153 for (int j = 0; j < nochunks; j++)
1155 // Print the first aligned sequence
1156 output.append(new Format("%" + (maxid) + "s").form(seqName))
1159 for (int i = 0; i < len; i++)
1161 if ((i + (j * len)) < seqRes.length())
1163 output.append(seqRes.charAt(i + (j * len)));
1167 output.append(NEWLINE);
1168 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1171 * Print out the match symbols:
1172 * | for exact match (ignoring case)
1173 * . if PAM250 score is positive
1176 for (int i = 0; i < len; i++)
1180 if ((i + (j * len)) < seqRes.length())
1182 char c1 = seqRes.charAt(i + (j * len));
1183 char c2 = strRes.charAt(i + (j * len));
1184 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1185 if (sameChar && !Comparison.isGap(c1))
1190 else if (type.equals("pep"))
1192 if (pam250.getPairwiseScore(c1, c2) > 0)
1206 } catch (IndexOutOfBoundsException e)
1211 // Now print the second aligned sequence
1212 output = output.append(NEWLINE);
1213 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1215 for (int i = 0; i < len; i++)
1217 if ((i + (j * len)) < strRes.length())
1219 output.append(strRes.charAt(i + (j * len)));
1222 output.append(NEWLINE).append(NEWLINE);
1224 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1225 if (pid < SiftsSettings.getFailSafePIDThreshold())
1227 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1229 output.append("Length of alignment = " + seqRes.length())
1231 output.append(new Format("Percentage ID = %2.2f").form(pid));
1236 public int getEntityCount()
1238 return siftsEntry.getEntity().size();
1242 public String getDbAccessionId()
1244 return siftsEntry.getDbAccessionId();
1248 public String getDbCoordSys()
1250 return siftsEntry.getDbCoordSys();
1254 public String getDbSource()
1256 return siftsEntry.getDbSource();
1260 public String getDbVersion()
1262 return siftsEntry.getDbVersion();
1265 public static void setMockSiftsFile(File file)
1267 mockSiftsFile = file;