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;
42 import java.util.Locale;
45 import java.util.TreeMap;
46 import java.util.zip.GZIPInputStream;
48 import javax.xml.bind.JAXBContext;
49 import javax.xml.bind.JAXBElement;
50 import javax.xml.bind.Unmarshaller;
51 import javax.xml.stream.XMLInputFactory;
52 import javax.xml.stream.XMLStreamReader;
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.util.Platform;
70 import jalview.xml.binding.sifts.Entry;
71 import jalview.xml.binding.sifts.Entry.Entity;
72 import jalview.xml.binding.sifts.Entry.Entity.Segment;
73 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListMapRegion.MapRegion;
74 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue;
75 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.CrossRefDb;
76 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.ResidueDetail;
78 import mc_view.PDBChain;
80 public class SiftsClient implements SiftsClientI
83 * for use in mocking out file fetch for tests only
84 * - reset to null after testing!
86 private static File mockSiftsFile;
88 private Entry siftsEntry;
90 private StructureFile pdb;
94 private String structId;
96 private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
99 * PDB sequence position to sequence coordinate mapping as derived from SIFTS
100 * record for the identified SeqCoordSys Used for lift-over from sequence
101 * derived from PDB (with first extracted PDBRESNUM as 'start' to the sequence
102 * being annotated with PDB data
104 private jalview.datamodel.Mapping seqFromPdbMapping;
106 private static final int BUFFER_SIZE = 4096;
108 public static final int UNASSIGNED = Integer.MIN_VALUE;
110 private static final int PDB_RES_POS = 0;
112 private static final int PDB_ATOM_POS = 1;
114 private static final int PDBE_POS = 2;
116 private static final String NOT_OBSERVED = "Not_Observed";
118 private static final String SIFTS_FTP_BASE_URL = "http://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/";
120 private final static String NEWLINE = System.lineSeparator();
122 private static final boolean GET_STREAM = false;
123 private static final boolean CACHE_FILE = true;
124 private String curSourceDBRef;
126 private HashSet<String> curDBRefAccessionIdsString;
127 private boolean doCache = false;
129 private enum CoordinateSys
131 UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
134 private CoordinateSys(String name)
139 public String getName()
145 private enum ResidueDetailType
147 NAME_SEC_STRUCTURE("nameSecondaryStructure"),
148 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();
174 File siftsFile = getSiftsFile(pdbId);
175 siftsEntry = parseSIFTs(siftsFile);
177 siftsEntry = parseSIFTSStreamFor(pdbId);
182 * A more streamlined version of SIFT reading that allows for streaming of the data.
186 * @throws SiftsException
188 private static Entry parseSIFTSStreamFor(String pdbId) throws SiftsException
192 InputStream is = (InputStream) downloadSifts(pdbId, GET_STREAM);
193 return parseSIFTs(is);
194 } catch (Exception e)
196 throw new SiftsException(e.getMessage());
201 * Parse the given SIFTs File and return a JAXB POJO of parsed data
204 * - the GZipped SIFTs XML file to parse
207 * if a problem occurs while parsing the SIFTs XML
209 private Entry parseSIFTs(File siftFile) throws SiftsException
211 try (InputStream in = new FileInputStream(siftFile)) {
212 return parseSIFTs(in);
213 } catch (Exception e)
216 throw new SiftsException(e.getMessage());
220 private static Entry parseSIFTs(InputStream in) throws Exception {
221 try (GZIPInputStream gzis = new GZIPInputStream(in);)
223 // System.out.println("File : " + siftFile.getAbsolutePath());
224 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
225 XMLStreamReader streamReader = XMLInputFactory.newInstance()
226 .createXMLStreamReader(gzis);
227 Unmarshaller um = jc.createUnmarshaller();
228 JAXBElement<Entry> jbe = um.unmarshal(streamReader, Entry.class);
229 return jbe.getValue();
234 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
235 * repository if not found in cache
238 * @return SIFTs XML file
239 * @throws SiftsException
241 public static File getSiftsFile(String pdbId) throws SiftsException
244 * return mocked file if it has been set
246 if (mockSiftsFile != null)
248 return mockSiftsFile;
251 String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
252 + pdbId.toLowerCase(Locale.ROOT) + ".xml.gz";
253 File siftsFile = new File(siftsFileName);
254 if (siftsFile.exists())
256 // The line below is required for unit testing... don't comment it out!!!
257 System.out.println(">>> SIFTS File already downloaded for " + pdbId);
259 if (isFileOlderThanThreshold(siftsFile,
260 SiftsSettings.getCacheThresholdInDays()))
262 File oldSiftsFile = new File(siftsFileName + "_old");
263 BackupFiles.moveFileToFile(siftsFile, oldSiftsFile);
266 siftsFile = downloadSiftsFile(pdbId.toLowerCase(Locale.ROOT));
267 oldSiftsFile.delete();
269 } catch (IOException e)
272 BackupFiles.moveFileToFile(oldSiftsFile, siftsFile);
273 return new File(siftsFileName);
283 siftsFile = downloadSiftsFile(pdbId.toLowerCase(Locale.ROOT));
284 } catch (IOException e)
286 throw new SiftsException(e.getMessage());
292 * Download a SIFTs XML file for a given PDB Id from an FTP repository
295 * @return downloaded SIFTs XML file
296 * @throws SiftsException
297 * @throws IOException
299 public static File downloadSiftsFile(String pdbId)
300 throws SiftsException, IOException
302 return (File) downloadSifts(pdbId, CACHE_FILE);
306 * Download SIFTs XML with the option to cache a file or to get a stream.
311 * @throws IOException
313 private static Object downloadSifts(String pdbId, boolean asFile) throws IOException
315 pdbId = pdbId.toLowerCase(Locale.ROOT);
316 if (pdbId.contains(".cif"))
318 pdbId = pdbId.replace(".cif", "");
320 String siftFile = pdbId + ".xml.gz";
321 File downloadTo = null;
324 downloadTo = new File(
325 SiftsSettings.getSiftDownloadDirectory() + siftFile);
326 File siftsDownloadDir = new File(SiftsSettings.getSiftDownloadDirectory());
327 if (!siftsDownloadDir.exists())
329 siftsDownloadDir.mkdirs();
333 String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
334 URL url = new URL(siftsFileFTPURL);
335 URLConnection conn = url.openConnection();
336 InputStream is = conn.getInputStream();
339 // This is MUCH more efficent in JavaScript, as we already have the bytes
340 Platform.streamToFile(is, downloadTo);
346 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
350 * @return true if the file was deleted or doesn't exist
352 public static boolean deleteSiftsFileByPDBId(String pdbId)
354 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
355 + pdbId.toLowerCase(Locale.ROOT) + ".xml.gz");
356 if (siftsFile.exists())
358 return siftsFile.delete();
364 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
367 * - the target sequence for the operation
368 * @return a valid DBRefEntry that is SIFTs compatible
370 * if no valid source DBRefEntry was found for the given sequences
372 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
373 throws SiftsException
375 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
376 if (dbRefs == null || dbRefs.size() < 1)
378 throw new SiftsException(
379 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
382 for (DBRefEntry dbRef : dbRefs)
384 if (dbRef == null || dbRef.getAccessionId() == null
385 || dbRef.getSource() == null)
389 String canonicalSource = DBRefUtils
390 .getCanonicalName(dbRef.getSource());
391 if (isValidDBRefEntry(dbRef)
392 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
393 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
398 throw new SiftsException("Could not get source DB Ref");
402 * Check that the DBRef Entry is properly populated and is available in this
403 * SiftClient instance
406 * - DBRefEntry to validate
407 * @return true validation is successful otherwise false is returned.
409 boolean isValidDBRefEntry(DBRefEntryI entry)
411 return entry != null && entry.getAccessionId() != null
412 && isFoundInSiftsEntry(entry.getAccessionId());
416 public HashSet<String> getAllMappingAccession()
418 HashSet<String> accessions = new HashSet<String>();
419 List<Entity> entities = siftsEntry.getEntity();
420 for (Entity entity : entities)
422 List<Segment> segments = entity.getSegment();
423 for (Segment segment : segments)
425 List<MapRegion> mapRegions = segment.getListMapRegion()
427 for (MapRegion mapRegion : mapRegions)
430 .add(mapRegion.getDb().getDbAccessionId().toLowerCase(Locale.ROOT));
438 public StructureMapping getSiftsStructureMapping(SequenceI seq,
439 String pdbFile, String chain) throws SiftsException
441 SequenceI aseq = seq;
442 while (seq.getDatasetSequence() != null)
444 seq = seq.getDatasetSequence();
446 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
447 System.out.println("Getting SIFTS mapping for " + structId + ": seq "
450 final StringBuilder mappingDetails = new StringBuilder(128);
451 PrintStream ps = new PrintStream(System.out)
454 public void print(String x)
456 mappingDetails.append(x);
460 public void println()
462 mappingDetails.append(NEWLINE);
465 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
467 String mappingOutput = mappingDetails.toString();
468 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
469 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
475 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
476 SequenceI seq, java.io.PrintStream os) throws SiftsException
478 List<Integer> omitNonObserved = new ArrayList<>();
479 int nonObservedShiftIndex = 0,pdbeNonObserved=0;
480 // System.out.println("Generating mappings for : " + entityId);
481 Entity entity = null;
482 entity = getEntityById(entityId);
483 String originalSeq = AlignSeq.extractGaps(
484 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
485 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
486 DBRefEntryI sourceDBRef;
487 sourceDBRef = getValidSourceDBRef(seq);
488 // TODO ensure sequence start/end is in the same coordinate system and
489 // consistent with the choosen sourceDBRef
491 // set sequence coordinate system - default value is UniProt
492 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
494 seqCoordSys = CoordinateSys.PDB;
497 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
498 for (DBRefEntry dbref : seq.getDBRefs())
500 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase(Locale.ROOT));
502 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase(Locale.ROOT));
504 curDBRefAccessionIdsString = dbRefAccessionIdsString;
505 curSourceDBRef = sourceDBRef.getAccessionId();
507 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
508 List<Segment> segments = entity.getSegment();
509 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
510 omitNonObserved, nonObservedShiftIndex,pdbeNonObserved);
511 processSegments(segments, shp);
514 populateAtomPositions(entityId, mapping);
515 } catch (Exception e)
519 if (seqCoordSys == CoordinateSys.UNIPROT)
521 padWithGaps(resNumMap, omitNonObserved);
523 int seqStart = UNASSIGNED;
524 int seqEnd = UNASSIGNED;
525 int pdbStart = UNASSIGNED;
526 int pdbEnd = UNASSIGNED;
528 if (mapping.isEmpty())
530 throw new SiftsException("SIFTS mapping failed");
532 // also construct a mapping object between the seq-coord sys and the PDB seq's coord sys
534 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
537 seqEnd = keys[keys.length - 1];
538 List<int[]> from=new ArrayList<>(),to=new ArrayList<>();
539 int[]_cfrom=null,_cto=null;
540 String matchedSeq = originalSeq;
541 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb sequence that starts <-1
545 int pdbpos = mapping.get(seqps)[PDBE_POS];
546 if (pdbpos == UNASSIGNED)
548 // not correct - pdbpos might be -1, but leave it for now
551 if (_cfrom==null || seqps!=_cfrom[1]+1)
553 _cfrom = new int[] { seqps,seqps};
555 _cto = null; // discontinuity
559 if (_cto==null || pdbpos!=1+_cto[1])
561 _cto = new int[] { pdbpos,pdbpos};
567 _cfrom = new int[from.size() * 2];
568 _cto = new int[to.size() * 2];
570 for (int[] range : from)
572 _cfrom[p++] = range[0];
573 _cfrom[p++] = range[1];
577 for (int[] range : to)
579 _cto[p++] = range[0];
580 _cto[p++] = range[1];
584 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
587 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
588 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
589 int orignalSeqStart = seq.getStart();
590 if (orignalSeqStart >= 1)
592 int subSeqStart = (seqStart >= orignalSeqStart)
593 ? seqStart - orignalSeqStart
595 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
596 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
598 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
602 matchedSeq = originalSeq.substring(1, originalSeq.length());
606 StringBuilder targetStrucSeqs = new StringBuilder();
607 for (String res : resNumMap.values())
609 targetStrucSeqs.append(res);
614 MappingOutputPojo mop = new MappingOutputPojo();
615 mop.setSeqStart(seqStart);
616 mop.setSeqEnd(seqEnd);
617 mop.setSeqName(seq.getName());
618 mop.setSeqResidue(matchedSeq);
620 mop.setStrStart(pdbStart);
621 mop.setStrEnd(pdbEnd);
622 mop.setStrName(structId);
623 mop.setStrResidue(targetStrucSeqs.toString());
626 os.print(getMappingOutput(mop).toString());
632 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
634 SequenceI seq = shp.getSeq();
635 HashMap<Integer, int[]> mapping = shp.getMapping();
636 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
637 List<Integer> omitNonObserved = shp.getOmitNonObserved();
638 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
639 int pdbeNonObservedCount = shp.getPdbeNonObserved();
640 int firstPDBResNum = UNASSIGNED;
641 for (Segment segment : segments)
643 // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
645 List<Residue> residues = segment.getListResidue().getResidue();
646 for (Residue residue : residues)
648 boolean isObserved = isResidueObserved(residue);
649 int pdbeIndex = Platform.getLeadingIntegerValue(residue.getDbResNum(),
651 int currSeqIndex = UNASSIGNED;
652 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
653 CrossRefDb pdbRefDb = null;
654 for (CrossRefDb cRefDb : cRefDbs)
656 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
659 if (firstPDBResNum == UNASSIGNED)
661 firstPDBResNum = Platform.getLeadingIntegerValue(cRefDb.getDbResNum(),
668 // after we find the first observed residue we just increment
673 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
674 && isAccessionMatched(cRefDb.getDbAccessionId()))
676 currSeqIndex = Platform.getLeadingIntegerValue(cRefDb.getDbResNum(),
678 if (pdbRefDb != null)
680 break;// exit loop if pdb and uniprot are already found
686 ++pdbeNonObservedCount;
688 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
691 // if the sequence has a primary reference to the PDB, then we are
692 // dealing with a sequence extracted directly from the PDB. In that
693 // case, numbering is PDBe - non-observed residues
694 currSeqIndex = seq.getStart() - 1 + pdbeIndex;
698 if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
701 // mapping to PDB or PDBe so we need to bookkeep for the
704 omitNonObserved.add(currSeqIndex);
705 ++nonObservedShiftIndex;
708 if (currSeqIndex == UNASSIGNED)
710 // change in logic - unobserved residues with no currSeqIndex
711 // corresponding are still counted in both nonObservedShiftIndex and
715 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
725 int resNum = (pdbRefDb == null)
726 ? Platform.getLeadingIntegerValue(residue.getDbResNum(),
728 : Platform.getLeadingIntegerValue(pdbRefDb.getDbResNum(),
733 char resCharCode = ResidueProperties
734 .getSingleCharacterCode(ResidueProperties
735 .getCanonicalAminoAcid(residue.getDbResName()));
736 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
738 int[] mappingcols = new int[] { Integer.valueOf(resNum),
739 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
741 mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
751 * Target chain to populate mapping of its atom positions.
753 * Two dimension array of residue index versus atom position
754 * @throws IllegalArgumentException
755 * Thrown if chainId or mapping is null
756 * @throws SiftsException
758 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
759 throws IllegalArgumentException, SiftsException
763 PDBChain chain = pdb.findChain(chainId);
765 if (chain == null || mapping == null)
767 throw new IllegalArgumentException(
768 "Chain id or mapping must not be null.");
770 for (int[] map : mapping.values())
772 if (map[PDB_RES_POS] != UNASSIGNED)
774 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
777 } catch (NullPointerException e)
779 throw new SiftsException(e.getMessage());
780 } catch (Exception e)
782 throw new SiftsException(e.getMessage());
788 * @param residueIndex
789 * The residue index used for the search
791 * A collection of Atom to search
792 * @return atom position for the given residue index
794 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
798 throw new IllegalArgumentException(
799 "atoms collection must not be null!");
801 for (Atom atom : atoms)
803 if (atom.resNumber == residueIndex)
805 return atom.atomIndex;
812 * Checks if the residue instance is marked 'Not_observed' or not
817 private boolean isResidueObserved(Residue residue)
819 Set<String> annotations = getResidueAnnotaitons(residue,
820 ResidueDetailType.ANNOTATION);
821 if (annotations == null || annotations.isEmpty())
825 for (String annotation : annotations)
827 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
836 * Get annotation String for a given residue and annotation type
842 private Set<String> getResidueAnnotaitons(Residue residue,
843 ResidueDetailType type)
845 HashSet<String> foundAnnotations = new HashSet<String>();
846 List<ResidueDetail> resDetails = residue.getResidueDetail();
847 for (ResidueDetail resDetail : resDetails)
849 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
851 foundAnnotations.add(resDetail.getContent());
854 return foundAnnotations;
858 public boolean isAccessionMatched(String accession)
860 boolean isStrictMatch = true;
861 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
862 : curDBRefAccessionIdsString.contains(accession.toLowerCase(Locale.ROOT));
865 private boolean isFoundInSiftsEntry(String accessionId)
867 Set<String> siftsDBRefs = getAllMappingAccession();
868 return accessionId != null
869 && siftsDBRefs.contains(accessionId.toLowerCase(Locale.ROOT));
873 * Pad omitted residue positions in PDB sequence with gaps
877 void padWithGaps(Map<Integer, String> resNumMap,
878 List<Integer> omitNonObserved)
880 if (resNumMap == null || resNumMap.isEmpty())
884 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
885 // Arrays.sort(keys);
886 int firstIndex = keys[0];
887 int lastIndex = keys[keys.length - 1];
888 // System.out.println("Min value " + firstIndex);
889 // System.out.println("Max value " + lastIndex);
890 for (int x = firstIndex; x <= lastIndex; x++)
892 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
894 resNumMap.put(x, "-");
900 public Entity getEntityById(String id) throws SiftsException
902 // Determines an entity to process by performing a heuristic matching of all
903 // Entities with the given chainId and choosing the best matching Entity
904 Entity entity = getEntityByMostOptimalMatchedId(id);
909 throw new SiftsException("Entity " + id + " not found");
913 * This method was added because EntityId is NOT always equal to ChainId.
914 * Hence, it provides the logic to greedily detect the "true" Entity for a
915 * given chainId where discrepancies exist.
920 public Entity getEntityByMostOptimalMatchedId(String chainId)
922 // System.out.println("---> advanced greedy entityId matching block
924 List<Entity> entities = siftsEntry.getEntity();
925 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
927 for (Entity entity : entities)
929 sPojo[count] = new SiftsEntitySortPojo();
930 sPojo[count].entityId = entity.getEntityId();
932 List<Segment> segments = entity.getSegment();
933 for (Segment segment : segments)
935 List<Residue> residues = segment.getListResidue().getResidue();
936 for (Residue residue : residues)
938 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
939 for (CrossRefDb cRefDb : cRefDbs)
941 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
945 ++sPojo[count].resCount;
946 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
948 ++sPojo[count].chainIdFreq;
953 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
954 / sPojo[count].resCount;
957 Arrays.sort(sPojo, Collections.reverseOrder());
958 // System.out.println("highest matched entity : " + sPojo[0].entityId);
959 // System.out.println("highest matched pid : " + sPojo[0].pid);
961 if (sPojo[0].entityId != null)
963 if (sPojo[0].pid < 1)
967 for (Entity entity : entities)
969 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
979 private class SiftsEntitySortPojo
980 implements Comparable<SiftsEntitySortPojo>
982 public String entityId;
984 public int chainIdFreq;
991 public int compareTo(SiftsEntitySortPojo o)
993 return this.pid - o.pid;
997 private class SegmentHelperPojo
999 private SequenceI seq;
1001 private HashMap<Integer, int[]> mapping;
1003 private TreeMap<Integer, String> resNumMap;
1005 private List<Integer> omitNonObserved;
1007 private int nonObservedShiftIndex;
1010 * count of number of 'not observed' positions in the PDB record's SEQRES
1011 * (total number of residues with coordinates == length(SEQRES) -
1014 private int pdbeNonObserved;
1016 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1017 TreeMap<Integer, String> resNumMap,
1018 List<Integer> omitNonObserved, int nonObservedShiftIndex,
1019 int pdbeNonObserved)
1022 setMapping(mapping);
1023 setResNumMap(resNumMap);
1024 setOmitNonObserved(omitNonObserved);
1025 setNonObservedShiftIndex(nonObservedShiftIndex);
1026 setPdbeNonObserved(pdbeNonObserved);
1030 public void setPdbeNonObserved(int pdbeNonObserved2)
1032 this.pdbeNonObserved = pdbeNonObserved2;
1035 public int getPdbeNonObserved()
1037 return pdbeNonObserved;
1039 public SequenceI getSeq()
1044 public void setSeq(SequenceI seq)
1049 public HashMap<Integer, int[]> getMapping()
1054 public void setMapping(HashMap<Integer, int[]> mapping)
1056 this.mapping = mapping;
1059 public TreeMap<Integer, String> getResNumMap()
1064 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1066 this.resNumMap = resNumMap;
1069 public List<Integer> getOmitNonObserved()
1071 return omitNonObserved;
1074 public void setOmitNonObserved(List<Integer> omitNonObserved)
1076 this.omitNonObserved = omitNonObserved;
1079 public int getNonObservedShiftIndex()
1081 return nonObservedShiftIndex;
1084 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1086 this.nonObservedShiftIndex = nonObservedShiftIndex;
1092 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1093 throws SiftsException
1095 String seqRes = mp.getSeqResidue();
1096 String seqName = mp.getSeqName();
1097 int sStart = mp.getSeqStart();
1098 int sEnd = mp.getSeqEnd();
1100 String strRes = mp.getStrResidue();
1101 String strName = mp.getStrName();
1102 int pdbStart = mp.getStrStart();
1103 int pdbEnd = mp.getStrEnd();
1105 String type = mp.getType();
1107 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1109 int len = 72 - maxid - 1;
1111 int nochunks = ((seqRes.length()) / len)
1112 + ((seqRes.length()) % len > 0 ? 1 : 0);
1114 StringBuilder output = new StringBuilder(512);
1115 output.append(NEWLINE);
1116 output.append("Sequence \u27f7 Structure mapping details")
1118 output.append("Method: SIFTS");
1119 output.append(NEWLINE).append(NEWLINE);
1121 output.append(new Format("%" + maxid + "s").form(seqName));
1122 output.append(" : ");
1123 output.append(String.valueOf(sStart));
1124 output.append(" - ");
1125 output.append(String.valueOf(sEnd));
1126 output.append(" Maps to ");
1127 output.append(NEWLINE);
1128 output.append(new Format("%" + maxid + "s").form(structId));
1129 output.append(" : ");
1130 output.append(String.valueOf(pdbStart));
1131 output.append(" - ");
1132 output.append(String.valueOf(pdbEnd));
1133 output.append(NEWLINE).append(NEWLINE);
1135 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1136 int matchedSeqCount = 0;
1137 for (int j = 0; j < nochunks; j++)
1139 // Print the first aligned sequence
1140 output.append(new Format("%" + (maxid) + "s").form(seqName))
1143 for (int i = 0; i < len; i++)
1145 if ((i + (j * len)) < seqRes.length())
1147 output.append(seqRes.charAt(i + (j * len)));
1151 output.append(NEWLINE);
1152 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1155 * Print out the match symbols:
1156 * | for exact match (ignoring case)
1157 * . if PAM250 score is positive
1160 for (int i = 0; i < len; i++)
1164 if ((i + (j * len)) < seqRes.length())
1166 char c1 = seqRes.charAt(i + (j * len));
1167 char c2 = strRes.charAt(i + (j * len));
1168 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1169 if (sameChar && !Comparison.isGap(c1))
1174 else if (type.equals("pep"))
1176 if (pam250.getPairwiseScore(c1, c2) > 0)
1190 } catch (IndexOutOfBoundsException e)
1195 // Now print the second aligned sequence
1196 output = output.append(NEWLINE);
1197 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1199 for (int i = 0; i < len; i++)
1201 if ((i + (j * len)) < strRes.length())
1203 output.append(strRes.charAt(i + (j * len)));
1206 output.append(NEWLINE).append(NEWLINE);
1208 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1209 if (pid < SiftsSettings.getFailSafePIDThreshold())
1211 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1213 output.append("Length of alignment = " + seqRes.length())
1215 output.append(new Format("Percentage ID = %2.2f").form(pid));
1220 public int getEntityCount()
1222 return siftsEntry.getEntity().size();
1226 public String getDbAccessionId()
1228 return siftsEntry.getDbAccessionId();
1232 public String getDbCoordSys()
1234 return siftsEntry.getDbCoordSys();
1238 public String getDbSource()
1240 return siftsEntry.getDbSource();
1244 public String getDbVersion()
1246 return siftsEntry.getDbVersion();
1249 public static void setMockSiftsFile(File file)
1251 mockSiftsFile = file;