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 java.util.Locale;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.PrintStream;
32 import java.net.URLConnection;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.attribute.BasicFileAttributes;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
46 import java.util.TreeMap;
47 import java.util.zip.GZIPInputStream;
49 import javax.xml.bind.JAXBContext;
50 import javax.xml.bind.JAXBElement;
51 import javax.xml.bind.Unmarshaller;
52 import javax.xml.stream.XMLInputFactory;
53 import javax.xml.stream.XMLStreamReader;
55 import jalview.analysis.AlignSeq;
56 import jalview.analysis.scoremodels.ScoreMatrix;
57 import jalview.analysis.scoremodels.ScoreModels;
58 import jalview.api.DBRefEntryI;
59 import jalview.api.SiftsClientI;
60 import jalview.datamodel.DBRefEntry;
61 import jalview.datamodel.DBRefSource;
62 import jalview.datamodel.SequenceI;
63 import jalview.io.BackupFiles;
64 import jalview.io.StructureFile;
65 import jalview.schemes.ResidueProperties;
66 import jalview.structure.StructureMapping;
67 import jalview.util.Comparison;
68 import jalview.util.DBRefUtils;
69 import jalview.util.Format;
70 import jalview.util.Platform;
71 import jalview.xml.binding.sifts.Entry;
72 import jalview.xml.binding.sifts.Entry.Entity;
73 import jalview.xml.binding.sifts.Entry.Entity.Segment;
74 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListMapRegion.MapRegion;
75 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue;
76 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.CrossRefDb;
77 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.ResidueDetail;
79 import mc_view.PDBChain;
81 public class SiftsClient implements SiftsClientI
84 * for use in mocking out file fetch for tests only
85 * - reset to null after testing!
87 private static File mockSiftsFile;
89 private Entry siftsEntry;
91 private StructureFile pdb;
95 private String structId;
97 private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
100 * PDB sequence position to sequence coordinate mapping as derived from SIFTS
101 * record for the identified SeqCoordSys Used for lift-over from sequence
102 * derived from PDB (with first extracted PDBRESNUM as 'start' to the sequence
103 * being annotated with PDB data
105 private jalview.datamodel.Mapping seqFromPdbMapping;
107 private static final int BUFFER_SIZE = 4096;
109 public static final int UNASSIGNED = Integer.MIN_VALUE;
111 private static final int PDB_RES_POS = 0;
113 private static final int PDB_ATOM_POS = 1;
115 private static final int PDBE_POS = 2;
117 private static final String NOT_OBSERVED = "Not_Observed";
119 private static final String SIFTS_SPLIT_FTP_BASE_URL = "https://ftp.ebi.ac.uk/pub/databases/msd/sifts/split_xml/";
121 private final static String NEWLINE = System.lineSeparator();
123 private String curSourceDBRef;
125 private HashSet<String> curDBRefAccessionIdsString;
127 private enum CoordinateSys
129 UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
133 private CoordinateSys(String name)
138 public String getName()
144 private enum ResidueDetailType
146 NAME_SEC_STRUCTURE("nameSecondaryStructure"),
147 CODE_SEC_STRUCTURE("codeSecondaryStructure"), ANNOTATION("Annotation");
151 private ResidueDetailType(String code)
156 public String getCode()
163 * Fetch SIFTs file for the given PDBfile and construct an instance of
167 * @throws SiftsException
169 public SiftsClient(StructureFile pdb) throws SiftsException
172 this.pdbId = pdb.getId();
173 File siftsFile = getSiftsFile(pdbId);
174 siftsEntry = parseSIFTs(siftsFile);
178 * Parse the given SIFTs File and return a JAXB POJO of parsed data
181 * - the GZipped SIFTs XML file to parse
184 * if a problem occurs while parsing the SIFTs XML
186 private Entry parseSIFTs(File siftFile) throws SiftsException
188 try (InputStream in = new FileInputStream(siftFile);
189 GZIPInputStream gzis = new GZIPInputStream(in);)
191 // System.out.println("File : " + siftFile.getAbsolutePath());
192 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
193 XMLStreamReader streamReader = XMLInputFactory.newInstance()
194 .createXMLStreamReader(gzis);
195 Unmarshaller um = jc.createUnmarshaller();
196 JAXBElement<Entry> jbe = um.unmarshal(streamReader, Entry.class);
197 return jbe.getValue();
198 } catch (Exception e)
201 throw new SiftsException(e.getMessage());
206 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
207 * repository if not found in cache
210 * @return SIFTs XML file
211 * @throws SiftsException
213 public static File getSiftsFile(String pdbId) throws SiftsException
216 * return mocked file if it has been set
218 if (mockSiftsFile != null)
220 return mockSiftsFile;
223 String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
224 + pdbId.toLowerCase(Locale.ROOT) + ".xml.gz";
225 File siftsFile = new File(siftsFileName);
226 if (siftsFile.exists())
228 // The line below is required for unit testing... don't comment it out!!!
229 System.out.println(">>> SIFTS File already downloaded for " + pdbId);
231 if (isFileOlderThanThreshold(siftsFile,
232 SiftsSettings.getCacheThresholdInDays()))
234 File oldSiftsFile = new File(siftsFileName + "_old");
235 BackupFiles.moveFileToFile(siftsFile, oldSiftsFile);
238 siftsFile = downloadSiftsFile(pdbId.toLowerCase(Locale.ROOT));
239 oldSiftsFile.delete();
241 } catch (IOException e)
244 BackupFiles.moveFileToFile(oldSiftsFile, siftsFile);
245 return new File(siftsFileName);
255 siftsFile = downloadSiftsFile(pdbId.toLowerCase(Locale.ROOT));
256 } catch (IOException e)
258 throw new SiftsException(e.getMessage());
264 * This method enables checking if a cached file has exceeded a certain
270 * the threshold in days
273 public static boolean isFileOlderThanThreshold(File file, int noOfDays)
275 Path filePath = file.toPath();
276 BasicFileAttributes attr;
280 attr = Files.readAttributes(filePath, BasicFileAttributes.class);
281 diffInDays = (int) ((new Date().getTime()
282 - attr.lastModifiedTime().toMillis())
283 / (1000 * 60 * 60 * 24));
284 // System.out.println("Diff in days : " + diffInDays);
285 } catch (IOException e)
289 return noOfDays <= diffInDays;
293 * Download a SIFTs XML file for a given PDB Id from an FTP repository
296 * @return downloaded SIFTs XML file
297 * @throws SiftsException
298 * @throws IOException
300 public static File downloadSiftsFile(String pdbId)
301 throws SiftsException, IOException
303 if (pdbId.contains(".cif"))
305 pdbId = pdbId.replace(".cif", "");
307 String siftFile = pdbId + ".xml.gz";
308 String siftsFileFTPURL = getDownloadUrlFor(siftFile);
311 * Download the file from URL to either
312 * Java: directory of cached downloaded SIFTS files
313 * Javascript: temporary 'file' (in-memory cache)
315 File downloadTo = null;
318 downloadTo = File.createTempFile(siftFile, ".xml.gz");
322 downloadTo = new File(
323 SiftsSettings.getSiftDownloadDirectory() + siftFile);
324 File siftsDownloadDir = new File(
325 SiftsSettings.getSiftDownloadDirectory());
326 if (!siftsDownloadDir.exists())
328 siftsDownloadDir.mkdirs();
332 // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
333 // long now = System.currentTimeMillis();
334 URL url = new URL(siftsFileFTPURL);
335 URLConnection conn = url.openConnection();
336 InputStream inputStream = conn.getInputStream();
337 FileOutputStream outputStream = new FileOutputStream(downloadTo);
338 byte[] buffer = new byte[BUFFER_SIZE];
340 while ((bytesRead = inputStream.read(buffer)) != -1)
342 outputStream.write(buffer, 0, bytesRead);
344 outputStream.close();
346 // System.out.println(">>> File downloaded : " + downloadedSiftsFile
347 // + " took " + (System.currentTimeMillis() - now) + "ms");
351 public static String getDownloadUrlFor(String siftFile)
353 return SIFTS_SPLIT_FTP_BASE_URL +siftFile.substring(1, 3)+"/"+siftFile;
357 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
361 * @return true if the file was deleted or doesn't exist
363 public static boolean deleteSiftsFileByPDBId(String pdbId)
365 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
366 + pdbId.toLowerCase(Locale.ROOT) + ".xml.gz");
367 if (siftsFile.exists())
369 return siftsFile.delete();
375 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
378 * - the target sequence for the operation
379 * @return a valid DBRefEntry that is SIFTs compatible
381 * if no valid source DBRefEntry was found for the given sequences
383 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
384 throws SiftsException
386 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
387 if (dbRefs == null || dbRefs.size() < 1)
389 throw new SiftsException(
390 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
393 for (DBRefEntry dbRef : dbRefs)
395 if (dbRef == null || dbRef.getAccessionId() == null
396 || dbRef.getSource() == null)
400 String canonicalSource = DBRefUtils
401 .getCanonicalName(dbRef.getSource());
402 if (isValidDBRefEntry(dbRef)
403 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
404 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
409 throw new SiftsException("Could not get source DB Ref");
413 * Check that the DBRef Entry is properly populated and is available in this
414 * SiftClient instance
417 * - DBRefEntry to validate
418 * @return true validation is successful otherwise false is returned.
420 boolean isValidDBRefEntry(DBRefEntryI entry)
422 return entry != null && entry.getAccessionId() != null
423 && isFoundInSiftsEntry(entry.getAccessionId());
427 public HashSet<String> getAllMappingAccession()
429 HashSet<String> accessions = new HashSet<String>();
430 List<Entity> entities = siftsEntry.getEntity();
431 for (Entity entity : entities)
433 List<Segment> segments = entity.getSegment();
434 for (Segment segment : segments)
436 List<MapRegion> mapRegions = segment.getListMapRegion()
438 for (MapRegion mapRegion : mapRegions)
440 accessions.add(mapRegion.getDb().getDbAccessionId()
441 .toLowerCase(Locale.ROOT));
449 public StructureMapping getSiftsStructureMapping(SequenceI seq,
450 String pdbFile, String chain) throws SiftsException
452 SequenceI aseq = seq;
453 while (seq.getDatasetSequence() != null)
455 seq = seq.getDatasetSequence();
457 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
458 System.out.println("Getting SIFTS mapping for " + structId + ": seq "
461 final StringBuilder mappingDetails = new StringBuilder(128);
462 PrintStream ps = new PrintStream(System.out)
465 public void print(String x)
467 mappingDetails.append(x);
471 public void println()
473 mappingDetails.append(NEWLINE);
476 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
478 String mappingOutput = mappingDetails.toString();
479 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
480 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
486 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
487 SequenceI seq, java.io.PrintStream os) throws SiftsException
489 List<Integer> omitNonObserved = new ArrayList<>();
490 int nonObservedShiftIndex = 0, pdbeNonObserved = 0;
491 // System.out.println("Generating mappings for : " + entityId);
492 Entity entity = null;
493 entity = getEntityById(entityId);
494 String originalSeq = AlignSeq.extractGaps(
495 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
496 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
497 DBRefEntryI sourceDBRef;
498 sourceDBRef = getValidSourceDBRef(seq);
499 // TODO ensure sequence start/end is in the same coordinate system and
500 // consistent with the choosen sourceDBRef
502 // set sequence coordinate system - default value is UniProt
503 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
505 seqCoordSys = CoordinateSys.PDB;
508 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
509 for (DBRefEntry dbref : seq.getDBRefs())
511 dbRefAccessionIdsString
512 .add(dbref.getAccessionId().toLowerCase(Locale.ROOT));
514 dbRefAccessionIdsString
515 .add(sourceDBRef.getAccessionId().toLowerCase(Locale.ROOT));
517 curDBRefAccessionIdsString = dbRefAccessionIdsString;
518 curSourceDBRef = sourceDBRef.getAccessionId();
520 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
521 List<Segment> segments = entity.getSegment();
522 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
523 omitNonObserved, nonObservedShiftIndex, pdbeNonObserved);
524 processSegments(segments, shp);
527 populateAtomPositions(entityId, mapping);
528 } catch (Exception e)
532 if (seqCoordSys == CoordinateSys.UNIPROT)
534 padWithGaps(resNumMap, omitNonObserved);
536 int seqStart = UNASSIGNED;
537 int seqEnd = UNASSIGNED;
538 int pdbStart = UNASSIGNED;
539 int pdbEnd = UNASSIGNED;
541 if (mapping.isEmpty())
543 throw new SiftsException("SIFTS mapping failed");
545 // also construct a mapping object between the seq-coord sys and the PDB
548 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
551 seqEnd = keys[keys.length - 1];
552 List<int[]> from = new ArrayList<>(), to = new ArrayList<>();
553 int[] _cfrom = null, _cto = null;
554 String matchedSeq = originalSeq;
555 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb
556 // sequence that starts <-1
558 for (int seqps : keys)
560 int pdbpos = mapping.get(seqps)[PDBE_POS];
561 if (pdbpos == UNASSIGNED)
563 // not correct - pdbpos might be -1, but leave it for now
566 if (_cfrom == null || seqps != _cfrom[1] + 1)
568 _cfrom = new int[] { seqps, seqps };
570 _cto = null; // discontinuity
576 if (_cto == null || pdbpos != 1 + _cto[1])
578 _cto = new int[] { pdbpos, pdbpos };
586 _cfrom = new int[from.size() * 2];
587 _cto = new int[to.size() * 2];
589 for (int[] range : from)
591 _cfrom[p++] = range[0];
592 _cfrom[p++] = range[1];
596 for (int[] range : to)
598 _cto[p++] = range[0];
599 _cto[p++] = range[1];
603 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
605 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
606 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
607 int orignalSeqStart = seq.getStart();
608 if (orignalSeqStart >= 1)
610 int subSeqStart = (seqStart >= orignalSeqStart)
611 ? seqStart - orignalSeqStart
613 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
614 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
616 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
620 matchedSeq = originalSeq.substring(1, originalSeq.length());
624 StringBuilder targetStrucSeqs = new StringBuilder();
625 for (String res : resNumMap.values())
627 targetStrucSeqs.append(res);
632 MappingOutputPojo mop = new MappingOutputPojo();
633 mop.setSeqStart(seqStart);
634 mop.setSeqEnd(seqEnd);
635 mop.setSeqName(seq.getName());
636 mop.setSeqResidue(matchedSeq);
638 mop.setStrStart(pdbStart);
639 mop.setStrEnd(pdbEnd);
640 mop.setStrName(structId);
641 mop.setStrResidue(targetStrucSeqs.toString());
644 os.print(getMappingOutput(mop).toString());
650 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
652 SequenceI seq = shp.getSeq();
653 HashMap<Integer, int[]> mapping = shp.getMapping();
654 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
655 List<Integer> omitNonObserved = shp.getOmitNonObserved();
656 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
657 int pdbeNonObservedCount = shp.getPdbeNonObserved();
658 int firstPDBResNum = UNASSIGNED;
659 for (Segment segment : segments)
661 // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
663 List<Residue> residues = segment.getListResidue().getResidue();
664 for (Residue residue : residues)
666 boolean isObserved = isResidueObserved(residue);
667 int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
669 int currSeqIndex = UNASSIGNED;
670 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
671 CrossRefDb pdbRefDb = null;
672 for (CrossRefDb cRefDb : cRefDbs)
674 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
677 if (firstPDBResNum == UNASSIGNED)
679 firstPDBResNum = getLeadingIntegerValue(cRefDb.getDbResNum(),
686 // after we find the first observed residue we just increment
691 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
692 && isAccessionMatched(cRefDb.getDbAccessionId()))
694 currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
696 if (pdbRefDb != null)
698 break;// exit loop if pdb and uniprot are already found
704 ++pdbeNonObservedCount;
706 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
709 // if the sequence has a primary reference to the PDB, then we are
710 // dealing with a sequence extracted directly from the PDB. In that
711 // case, numbering is PDBe - non-observed residues
712 currSeqIndex = seq.getStart() - 1 + pdbeIndex;
716 if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
719 // mapping to PDB or PDBe so we need to bookkeep for the
722 omitNonObserved.add(currSeqIndex);
723 ++nonObservedShiftIndex;
726 if (currSeqIndex == UNASSIGNED)
728 // change in logic - unobserved residues with no currSeqIndex
729 // corresponding are still counted in both nonObservedShiftIndex and
733 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
743 int resNum = (pdbRefDb == null)
744 ? getLeadingIntegerValue(residue.getDbResNum(),
746 : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
751 char resCharCode = ResidueProperties
752 .getSingleCharacterCode(ResidueProperties
753 .getCanonicalAminoAcid(residue.getDbResName()));
754 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
756 int[] mappingcols = new int[] { Integer.valueOf(resNum),
757 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
759 mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
767 * Get the leading integer part of a string that begins with an integer.
770 * - the string input to process
772 * - value returned if unsuccessful
775 static int getLeadingIntegerValue(String input, int failValue)
781 String[] parts = input.split("(?=\\D)(?<=\\d)");
782 if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
784 return Integer.valueOf(parts[0]);
792 * Target chain to populate mapping of its atom positions.
794 * Two dimension array of residue index versus atom position
795 * @throws IllegalArgumentException
796 * Thrown if chainId or mapping is null
797 * @throws SiftsException
799 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
800 throws IllegalArgumentException, SiftsException
804 PDBChain chain = pdb.findChain(chainId);
806 if (chain == null || mapping == null)
808 throw new IllegalArgumentException(
809 "Chain id or mapping must not be null.");
811 for (int[] map : mapping.values())
813 if (map[PDB_RES_POS] != UNASSIGNED)
815 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
818 } catch (NullPointerException e)
820 throw new SiftsException(e.getMessage());
821 } catch (Exception e)
823 throw new SiftsException(e.getMessage());
829 * @param residueIndex
830 * The residue index used for the search
832 * A collection of Atom to search
833 * @return atom position for the given residue index
835 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
839 throw new IllegalArgumentException(
840 "atoms collection must not be null!");
842 for (Atom atom : atoms)
844 if (atom.resNumber == residueIndex)
846 return atom.atomIndex;
853 * Checks if the residue instance is marked 'Not_observed' or not
858 private boolean isResidueObserved(Residue residue)
860 Set<String> annotations = getResidueAnnotaitons(residue,
861 ResidueDetailType.ANNOTATION);
862 if (annotations == null || annotations.isEmpty())
866 for (String annotation : annotations)
868 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
877 * Get annotation String for a given residue and annotation type
883 private Set<String> getResidueAnnotaitons(Residue residue,
884 ResidueDetailType type)
886 HashSet<String> foundAnnotations = new HashSet<String>();
887 List<ResidueDetail> resDetails = residue.getResidueDetail();
888 for (ResidueDetail resDetail : resDetails)
890 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
892 foundAnnotations.add(resDetail.getContent());
895 return foundAnnotations;
899 public boolean isAccessionMatched(String accession)
901 boolean isStrictMatch = true;
902 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
903 : curDBRefAccessionIdsString
904 .contains(accession.toLowerCase(Locale.ROOT));
907 private boolean isFoundInSiftsEntry(String accessionId)
909 Set<String> siftsDBRefs = getAllMappingAccession();
910 return accessionId != null
911 && siftsDBRefs.contains(accessionId.toLowerCase(Locale.ROOT));
915 * Pad omitted residue positions in PDB sequence with gaps
919 void padWithGaps(Map<Integer, String> resNumMap,
920 List<Integer> omitNonObserved)
922 if (resNumMap == null || resNumMap.isEmpty())
926 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
927 // Arrays.sort(keys);
928 int firstIndex = keys[0];
929 int lastIndex = keys[keys.length - 1];
930 // System.out.println("Min value " + firstIndex);
931 // System.out.println("Max value " + lastIndex);
932 for (int x = firstIndex; x <= lastIndex; x++)
934 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
936 resNumMap.put(x, "-");
942 public Entity getEntityById(String id) throws SiftsException
944 // Determines an entity to process by performing a heuristic matching of all
945 // Entities with the given chainId and choosing the best matching Entity
946 Entity entity = getEntityByMostOptimalMatchedId(id);
951 throw new SiftsException("Entity " + id + " not found");
955 * This method was added because EntityId is NOT always equal to ChainId.
956 * Hence, it provides the logic to greedily detect the "true" Entity for a
957 * given chainId where discrepancies exist.
962 public Entity getEntityByMostOptimalMatchedId(String chainId)
964 // System.out.println("---> advanced greedy entityId matching block
966 List<Entity> entities = siftsEntry.getEntity();
967 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
969 for (Entity entity : entities)
971 sPojo[count] = new SiftsEntitySortPojo();
972 sPojo[count].entityId = entity.getEntityId();
974 List<Segment> segments = entity.getSegment();
975 for (Segment segment : segments)
977 List<Residue> residues = segment.getListResidue().getResidue();
978 for (Residue residue : residues)
980 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
981 for (CrossRefDb cRefDb : cRefDbs)
983 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
987 ++sPojo[count].resCount;
988 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
990 ++sPojo[count].chainIdFreq;
995 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
996 / sPojo[count].resCount;
999 Arrays.sort(sPojo, Collections.reverseOrder());
1000 // System.out.println("highest matched entity : " + sPojo[0].entityId);
1001 // System.out.println("highest matched pid : " + sPojo[0].pid);
1003 if (sPojo[0].entityId != null)
1005 if (sPojo[0].pid < 1)
1009 for (Entity entity : entities)
1011 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
1021 private class SiftsEntitySortPojo
1022 implements Comparable<SiftsEntitySortPojo>
1024 public String entityId;
1026 public int chainIdFreq;
1030 public int resCount;
1033 public int compareTo(SiftsEntitySortPojo o)
1035 return this.pid - o.pid;
1039 private class SegmentHelperPojo
1041 private SequenceI seq;
1043 private HashMap<Integer, int[]> mapping;
1045 private TreeMap<Integer, String> resNumMap;
1047 private List<Integer> omitNonObserved;
1049 private int nonObservedShiftIndex;
1052 * count of number of 'not observed' positions in the PDB record's SEQRES
1053 * (total number of residues with coordinates == length(SEQRES) -
1056 private int pdbeNonObserved;
1058 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1059 TreeMap<Integer, String> resNumMap,
1060 List<Integer> omitNonObserved, int nonObservedShiftIndex,
1061 int pdbeNonObserved)
1064 setMapping(mapping);
1065 setResNumMap(resNumMap);
1066 setOmitNonObserved(omitNonObserved);
1067 setNonObservedShiftIndex(nonObservedShiftIndex);
1068 setPdbeNonObserved(pdbeNonObserved);
1072 public void setPdbeNonObserved(int pdbeNonObserved2)
1074 this.pdbeNonObserved = pdbeNonObserved2;
1077 public int getPdbeNonObserved()
1079 return pdbeNonObserved;
1082 public SequenceI getSeq()
1087 public void setSeq(SequenceI seq)
1092 public HashMap<Integer, int[]> getMapping()
1097 public void setMapping(HashMap<Integer, int[]> mapping)
1099 this.mapping = mapping;
1102 public TreeMap<Integer, String> getResNumMap()
1107 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1109 this.resNumMap = resNumMap;
1112 public List<Integer> getOmitNonObserved()
1114 return omitNonObserved;
1117 public void setOmitNonObserved(List<Integer> omitNonObserved)
1119 this.omitNonObserved = omitNonObserved;
1122 public int getNonObservedShiftIndex()
1124 return nonObservedShiftIndex;
1127 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1129 this.nonObservedShiftIndex = nonObservedShiftIndex;
1135 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1136 throws SiftsException
1138 String seqRes = mp.getSeqResidue();
1139 String seqName = mp.getSeqName();
1140 int sStart = mp.getSeqStart();
1141 int sEnd = mp.getSeqEnd();
1143 String strRes = mp.getStrResidue();
1144 String strName = mp.getStrName();
1145 int pdbStart = mp.getStrStart();
1146 int pdbEnd = mp.getStrEnd();
1148 String type = mp.getType();
1150 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1152 int len = 72 - maxid - 1;
1154 int nochunks = ((seqRes.length()) / len)
1155 + ((seqRes.length()) % len > 0 ? 1 : 0);
1157 StringBuilder output = new StringBuilder(512);
1158 output.append(NEWLINE);
1159 output.append("Sequence \u27f7 Structure mapping details")
1161 output.append("Method: SIFTS");
1162 output.append(NEWLINE).append(NEWLINE);
1164 output.append(new Format("%" + maxid + "s").form(seqName));
1165 output.append(" : ");
1166 output.append(String.valueOf(sStart));
1167 output.append(" - ");
1168 output.append(String.valueOf(sEnd));
1169 output.append(" Maps to ");
1170 output.append(NEWLINE);
1171 output.append(new Format("%" + maxid + "s").form(structId));
1172 output.append(" : ");
1173 output.append(String.valueOf(pdbStart));
1174 output.append(" - ");
1175 output.append(String.valueOf(pdbEnd));
1176 output.append(NEWLINE).append(NEWLINE);
1178 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1179 int matchedSeqCount = 0;
1180 for (int j = 0; j < nochunks; j++)
1182 // Print the first aligned sequence
1183 output.append(new Format("%" + (maxid) + "s").form(seqName))
1186 for (int i = 0; i < len; i++)
1188 if ((i + (j * len)) < seqRes.length())
1190 output.append(seqRes.charAt(i + (j * len)));
1194 output.append(NEWLINE);
1195 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1198 * Print out the match symbols:
1199 * | for exact match (ignoring case)
1200 * . if PAM250 score is positive
1203 for (int i = 0; i < len; i++)
1207 if ((i + (j * len)) < seqRes.length())
1209 char c1 = seqRes.charAt(i + (j * len));
1210 char c2 = strRes.charAt(i + (j * len));
1211 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1212 if (sameChar && !Comparison.isGap(c1))
1217 else if (type.equals("pep"))
1219 if (pam250.getPairwiseScore(c1, c2) > 0)
1233 } catch (IndexOutOfBoundsException e)
1238 // Now print the second aligned sequence
1239 output = output.append(NEWLINE);
1240 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1242 for (int i = 0; i < len; i++)
1244 if ((i + (j * len)) < strRes.length())
1246 output.append(strRes.charAt(i + (j * len)));
1249 output.append(NEWLINE).append(NEWLINE);
1251 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1252 if (pid < SiftsSettings.getFailSafePIDThreshold())
1254 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1256 output.append("Length of alignment = " + seqRes.length())
1258 output.append(new Format("Percentage ID = %2.2f").form(pid));
1263 public int getEntityCount()
1265 return siftsEntry.getEntity().size();
1269 public String getDbAccessionId()
1271 return siftsEntry.getDbAccessionId();
1275 public String getDbCoordSys()
1277 return siftsEntry.getDbCoordSys();
1281 public String getDbSource()
1283 return siftsEntry.getDbSource();
1287 public String getDbVersion()
1289 return siftsEntry.getDbVersion();
1292 public static void setMockSiftsFile(File file)
1294 mockSiftsFile = file;