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.bin.Console;
61 import jalview.datamodel.DBRefEntry;
62 import jalview.datamodel.DBRefSource;
63 import jalview.datamodel.SequenceI;
64 import jalview.io.BackupFiles;
65 import jalview.io.StructureFile;
66 import jalview.schemes.ResidueProperties;
67 import jalview.structure.StructureMapping;
68 import jalview.util.Comparison;
69 import jalview.util.DBRefUtils;
70 import jalview.util.Format;
71 import jalview.util.Platform;
72 import jalview.xml.binding.sifts.Entry;
73 import jalview.xml.binding.sifts.Entry.Entity;
74 import jalview.xml.binding.sifts.Entry.Entity.Segment;
75 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListMapRegion.MapRegion;
76 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue;
77 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.CrossRefDb;
78 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.ResidueDetail;
80 import mc_view.PDBChain;
82 public class SiftsClient implements SiftsClientI
85 * for use in mocking out file fetch for tests only
86 * - reset to null after testing!
88 private static File mockSiftsFile;
90 private Entry siftsEntry;
92 private StructureFile pdb;
96 private String structId;
98 private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
101 * PDB sequence position to sequence coordinate mapping as derived from SIFTS
102 * record for the identified SeqCoordSys Used for lift-over from sequence
103 * derived from PDB (with first extracted PDBRESNUM as 'start' to the sequence
104 * being annotated with PDB data
106 private jalview.datamodel.Mapping seqFromPdbMapping;
108 private static final int BUFFER_SIZE = 4096;
110 public static final int UNASSIGNED = Integer.MIN_VALUE;
112 private static final int PDB_RES_POS = 0;
114 private static final int PDB_ATOM_POS = 1;
116 private static final int PDBE_POS = 2;
118 private static final String NOT_OBSERVED = "Not_Observed";
120 private static final String SIFTS_SPLIT_FTP_BASE_URL = "https://ftp.ebi.ac.uk/pub/databases/msd/sifts/split_xml/";
122 private final static String NEWLINE = System.lineSeparator();
124 private String curSourceDBRef;
126 private HashSet<String> curDBRefAccessionIdsString;
128 private enum CoordinateSys
130 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");
152 private ResidueDetailType(String code)
157 public String getCode()
164 * Fetch SIFTs file for the given PDBfile and construct an instance of
168 * @throws SiftsException
170 public SiftsClient(StructureFile pdb) throws SiftsException
173 this.pdbId = pdb.getId();
174 File siftsFile = getSiftsFile(pdbId);
175 siftsEntry = parseSIFTs(siftsFile);
179 * Parse the given SIFTs File and return a JAXB POJO of parsed data
182 * - the GZipped SIFTs XML file to parse
185 * if a problem occurs while parsing the SIFTs XML
187 private Entry parseSIFTs(File siftFile) throws SiftsException
189 try (InputStream in = new FileInputStream(siftFile);
190 GZIPInputStream gzis = new GZIPInputStream(in);)
192 // jalview.bin.Console.outPrintln("File : " + siftFile.getAbsolutePath());
193 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
194 XMLStreamReader streamReader = XMLInputFactory.newInstance()
195 .createXMLStreamReader(gzis);
196 Unmarshaller um = jc.createUnmarshaller();
197 JAXBElement<Entry> jbe = um.unmarshal(streamReader, Entry.class);
198 return jbe.getValue();
199 } catch (Exception e)
202 throw new SiftsException(e.getMessage());
207 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
208 * repository if not found in cache
211 * @return SIFTs XML file
212 * @throws SiftsException
214 public static File getSiftsFile(String pdbId) throws SiftsException
217 * return mocked file if it has been set
219 if (mockSiftsFile != null)
221 return mockSiftsFile;
224 String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
225 + pdbId.toLowerCase(Locale.ROOT) + ".xml.gz";
226 File siftsFile = new File(siftsFileName);
227 if (siftsFile.exists())
229 // The line below is required for unit testing... don't comment it out!!!
231 .outPrintln(">>> SIFTS File already downloaded for " + pdbId);
233 if (isFileOlderThanThreshold(siftsFile,
234 SiftsSettings.getCacheThresholdInDays()))
236 File oldSiftsFile = new File(siftsFileName + "_old");
237 BackupFiles.moveFileToFile(siftsFile, oldSiftsFile);
240 siftsFile = downloadSiftsFile(pdbId.toLowerCase(Locale.ROOT));
241 oldSiftsFile.delete();
243 } catch (IOException e)
246 BackupFiles.moveFileToFile(oldSiftsFile, siftsFile);
247 return new File(siftsFileName);
257 siftsFile = downloadSiftsFile(pdbId.toLowerCase(Locale.ROOT));
258 } catch (IOException e)
260 throw new SiftsException(e.getMessage());
266 * This method enables checking if a cached file has exceeded a certain
272 * the threshold in days
275 public static boolean isFileOlderThanThreshold(File file, int noOfDays)
277 Path filePath = file.toPath();
278 BasicFileAttributes attr;
282 attr = Files.readAttributes(filePath, BasicFileAttributes.class);
283 diffInDays = (int) ((new Date().getTime()
284 - attr.lastModifiedTime().toMillis())
285 / (1000 * 60 * 60 * 24));
286 // jalview.bin.Console.outPrintln("Diff in days : " + diffInDays);
287 } catch (IOException e)
291 return noOfDays <= diffInDays;
295 * Download a SIFTs XML file for a given PDB Id from an FTP repository
298 * @return downloaded SIFTs XML file
299 * @throws SiftsException
300 * @throws IOException
302 public static File downloadSiftsFile(String pdbId)
303 throws SiftsException, IOException
305 if (pdbId.contains(".cif"))
307 pdbId = pdbId.replace(".cif", "");
309 String siftFile = pdbId + ".xml.gz";
310 String siftsFileFTPURL = getDownloadUrlFor(siftFile);
313 * Download the file from URL to either
314 * Java: directory of cached downloaded SIFTS files
315 * Javascript: temporary 'file' (in-memory cache)
317 File downloadTo = null;
320 downloadTo = File.createTempFile(siftFile, ".xml.gz");
324 downloadTo = new File(
325 SiftsSettings.getSiftDownloadDirectory() + siftFile);
326 File siftsDownloadDir = new File(
327 SiftsSettings.getSiftDownloadDirectory());
328 if (!siftsDownloadDir.exists())
330 siftsDownloadDir.mkdirs();
334 // jalview.bin.Console.outPrintln(">> Download ftp url : " +
336 // long now = System.currentTimeMillis();
337 URL url = new URL(siftsFileFTPURL);
338 URLConnection conn = url.openConnection();
339 InputStream inputStream = conn.getInputStream();
340 FileOutputStream outputStream = new FileOutputStream(downloadTo);
341 byte[] buffer = new byte[BUFFER_SIZE];
343 while ((bytesRead = inputStream.read(buffer)) != -1)
345 outputStream.write(buffer, 0, bytesRead);
347 outputStream.close();
349 // jalview.bin.Console.outPrintln(">>> File downloaded : " +
350 // downloadedSiftsFile
351 // + " took " + (System.currentTimeMillis() - now) + "ms");
355 public static String getDownloadUrlFor(String siftFile)
357 String durl = SIFTS_SPLIT_FTP_BASE_URL + siftFile.substring(1, 3) + "/"
359 Console.trace("SIFTS URL for " + siftFile + " is " + durl);
365 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
369 * @return true if the file was deleted or doesn't exist
371 public static boolean deleteSiftsFileByPDBId(String pdbId)
373 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
374 + pdbId.toLowerCase(Locale.ROOT) + ".xml.gz");
375 if (siftsFile.exists())
377 return siftsFile.delete();
383 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
386 * - the target sequence for the operation
387 * @return a valid DBRefEntry that is SIFTs compatible
389 * if no valid source DBRefEntry was found for the given sequences
391 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
392 throws SiftsException
394 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
395 if (dbRefs == null || dbRefs.size() < 1)
397 throw new SiftsException(
398 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
401 for (DBRefEntry dbRef : dbRefs)
403 if (dbRef == null || dbRef.getAccessionId() == null
404 || dbRef.getSource() == null)
408 String canonicalSource = DBRefUtils
409 .getCanonicalName(dbRef.getSource());
410 if (isValidDBRefEntry(dbRef)
411 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
412 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
417 throw new SiftsException("Could not get source DB Ref");
421 * Check that the DBRef Entry is properly populated and is available in this
422 * SiftClient instance
425 * - DBRefEntry to validate
426 * @return true validation is successful otherwise false is returned.
428 boolean isValidDBRefEntry(DBRefEntryI entry)
430 return entry != null && entry.getAccessionId() != null
431 && isFoundInSiftsEntry(entry.getAccessionId());
435 public HashSet<String> getAllMappingAccession()
437 HashSet<String> accessions = new HashSet<String>();
438 List<Entity> entities = siftsEntry.getEntity();
439 for (Entity entity : entities)
441 List<Segment> segments = entity.getSegment();
442 for (Segment segment : segments)
444 List<MapRegion> mapRegions = segment.getListMapRegion()
446 for (MapRegion mapRegion : mapRegions)
448 accessions.add(mapRegion.getDb().getDbAccessionId()
449 .toLowerCase(Locale.ROOT));
457 public StructureMapping getSiftsStructureMapping(SequenceI seq,
458 String pdbFile, String chain) throws SiftsException
460 SequenceI aseq = seq;
461 while (seq.getDatasetSequence() != null)
463 seq = seq.getDatasetSequence();
465 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
466 jalview.bin.Console.outPrintln("Getting SIFTS mapping for " + structId
467 + ": seq " + seq.getName());
469 final StringBuilder mappingDetails = new StringBuilder(128);
470 PrintStream ps = new PrintStream(System.out)
473 public void print(String x)
475 mappingDetails.append(x);
479 public void println()
481 mappingDetails.append(NEWLINE);
484 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
486 String mappingOutput = mappingDetails.toString();
487 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
488 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
494 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
495 SequenceI seq, java.io.PrintStream os) throws SiftsException
497 List<Integer> omitNonObserved = new ArrayList<>();
498 int nonObservedShiftIndex = 0, pdbeNonObserved = 0;
499 // jalview.bin.Console.outPrintln("Generating mappings for : " + entityId);
500 Entity entity = null;
501 entity = getEntityById(entityId);
502 String originalSeq = AlignSeq.extractGaps(
503 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
504 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
505 DBRefEntryI sourceDBRef;
506 sourceDBRef = getValidSourceDBRef(seq);
507 // TODO ensure sequence start/end is in the same coordinate system and
508 // consistent with the choosen sourceDBRef
510 // set sequence coordinate system - default value is UniProt
511 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
513 seqCoordSys = CoordinateSys.PDB;
516 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
517 for (DBRefEntry dbref : seq.getDBRefs())
519 dbRefAccessionIdsString
520 .add(dbref.getAccessionId().toLowerCase(Locale.ROOT));
522 dbRefAccessionIdsString
523 .add(sourceDBRef.getAccessionId().toLowerCase(Locale.ROOT));
525 curDBRefAccessionIdsString = dbRefAccessionIdsString;
526 curSourceDBRef = sourceDBRef.getAccessionId();
528 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
529 List<Segment> segments = entity.getSegment();
530 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
531 omitNonObserved, nonObservedShiftIndex, pdbeNonObserved);
532 processSegments(segments, shp);
535 populateAtomPositions(entityId, mapping);
536 } catch (Exception e)
540 if (seqCoordSys == CoordinateSys.UNIPROT)
542 padWithGaps(resNumMap, omitNonObserved);
544 int seqStart = UNASSIGNED;
545 int seqEnd = UNASSIGNED;
546 int pdbStart = UNASSIGNED;
547 int pdbEnd = UNASSIGNED;
549 if (mapping.isEmpty())
551 throw new SiftsException("SIFTS mapping failed for " + entityId
552 + " and " + seq.getName());
554 // also construct a mapping object between the seq-coord sys and the PDB
557 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
560 seqEnd = keys[keys.length - 1];
561 List<int[]> from = new ArrayList<>(), to = new ArrayList<>();
562 int[] _cfrom = null, _cto = null;
563 String matchedSeq = originalSeq;
564 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb
565 // sequence that starts <-1
567 for (int seqps : keys)
569 int pdbpos = mapping.get(seqps)[PDBE_POS];
570 if (pdbpos == UNASSIGNED)
572 // not correct - pdbpos might be -1, but leave it for now
575 if (_cfrom == null || seqps != _cfrom[1] + 1)
577 _cfrom = new int[] { seqps, seqps };
579 _cto = null; // discontinuity
585 if (_cto == null || pdbpos != 1 + _cto[1])
587 _cto = new int[] { pdbpos, pdbpos };
595 _cfrom = new int[from.size() * 2];
596 _cto = new int[to.size() * 2];
598 for (int[] range : from)
600 _cfrom[p++] = range[0];
601 _cfrom[p++] = range[1];
605 for (int[] range : to)
607 _cto[p++] = range[0];
608 _cto[p++] = range[1];
612 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
614 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
615 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
616 int orignalSeqStart = seq.getStart();
617 if (orignalSeqStart >= 1)
619 int subSeqStart = (seqStart >= orignalSeqStart)
620 ? seqStart - orignalSeqStart
622 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
623 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
625 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
629 matchedSeq = originalSeq.substring(1, originalSeq.length());
633 StringBuilder targetStrucSeqs = new StringBuilder();
634 for (String res : resNumMap.values())
636 targetStrucSeqs.append(res);
641 MappingOutputPojo mop = new MappingOutputPojo();
642 mop.setSeqStart(seqStart);
643 mop.setSeqEnd(seqEnd);
644 mop.setSeqName(seq.getName());
645 mop.setSeqResidue(matchedSeq);
647 mop.setStrStart(pdbStart);
648 mop.setStrEnd(pdbEnd);
649 mop.setStrName(structId);
650 mop.setStrResidue(targetStrucSeqs.toString());
653 os.print(getMappingOutput(mop).toString());
659 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
661 SequenceI seq = shp.getSeq();
662 HashMap<Integer, int[]> mapping = shp.getMapping();
663 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
664 List<Integer> omitNonObserved = shp.getOmitNonObserved();
665 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
666 int pdbeNonObservedCount = shp.getPdbeNonObserved();
667 int firstPDBResNum = UNASSIGNED;
668 for (Segment segment : segments)
670 // jalview.bin.Console.outPrintln("Mapping segments : " +
671 // segment.getSegId() + "\\"s
673 List<Residue> residues = segment.getListResidue().getResidue();
674 for (Residue residue : residues)
676 boolean isObserved = isResidueObserved(residue);
677 int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
679 int currSeqIndex = UNASSIGNED;
680 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
681 CrossRefDb pdbRefDb = null;
682 for (CrossRefDb cRefDb : cRefDbs)
684 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
687 if (firstPDBResNum == UNASSIGNED)
689 firstPDBResNum = getLeadingIntegerValue(cRefDb.getDbResNum(),
696 // after we find the first observed residue we just increment
701 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
702 && isAccessionMatched(cRefDb.getDbAccessionId()))
704 currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
706 if (pdbRefDb != null)
708 break;// exit loop if pdb and uniprot are already found
714 ++pdbeNonObservedCount;
716 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
719 // if the sequence has a primary reference to the PDB, then we are
720 // dealing with a sequence extracted directly from the PDB. In that
721 // case, numbering is PDBe - non-observed residues
722 currSeqIndex = seq.getStart() - 1 + pdbeIndex;
726 if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
729 // mapping to PDB or PDBe so we need to bookkeep for the
732 omitNonObserved.add(currSeqIndex);
733 ++nonObservedShiftIndex;
736 if (currSeqIndex == UNASSIGNED)
738 // change in logic - unobserved residues with no currSeqIndex
739 // corresponding are still counted in both nonObservedShiftIndex and
743 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
753 int resNum = (pdbRefDb == null)
754 ? getLeadingIntegerValue(residue.getDbResNum(),
756 : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
761 char resCharCode = ResidueProperties
762 .getSingleCharacterCode(ResidueProperties
763 .getCanonicalAminoAcid(residue.getDbResName()));
764 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
766 int[] mappingcols = new int[] { Integer.valueOf(resNum),
767 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
769 mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
777 * Get the leading integer part of a string that begins with an integer.
780 * - the string input to process
782 * - value returned if unsuccessful
785 static int getLeadingIntegerValue(String input, int failValue)
791 String[] parts = input.split("(?=\\D)(?<=\\d)");
792 if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
794 return Integer.valueOf(parts[0]);
802 * Target chain to populate mapping of its atom positions.
804 * Two dimension array of residue index versus atom position
805 * @throws IllegalArgumentException
806 * Thrown if chainId or mapping is null
807 * @throws SiftsException
809 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
810 throws IllegalArgumentException, SiftsException
814 PDBChain chain = pdb.findChain(chainId);
816 if (chain == null || mapping == null)
818 throw new IllegalArgumentException(
819 "Chain id or mapping must not be null.");
821 for (int[] map : mapping.values())
823 if (map[PDB_RES_POS] != UNASSIGNED)
825 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
828 } catch (NullPointerException e)
830 throw new SiftsException(e.getMessage());
831 } catch (Exception e)
833 throw new SiftsException(e.getMessage());
839 * @param residueIndex
840 * The residue index used for the search
842 * A collection of Atom to search
843 * @return atom position for the given residue index
845 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
849 throw new IllegalArgumentException(
850 "atoms collection must not be null!");
852 for (Atom atom : atoms)
854 if (atom.resNumber == residueIndex)
856 return atom.atomIndex;
863 * Checks if the residue instance is marked 'Not_observed' or not
868 private boolean isResidueObserved(Residue residue)
870 Set<String> annotations = getResidueAnnotaitons(residue,
871 ResidueDetailType.ANNOTATION);
872 if (annotations == null || annotations.isEmpty())
876 for (String annotation : annotations)
878 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
887 * Get annotation String for a given residue and annotation type
893 private Set<String> getResidueAnnotaitons(Residue residue,
894 ResidueDetailType type)
896 HashSet<String> foundAnnotations = new HashSet<String>();
897 List<ResidueDetail> resDetails = residue.getResidueDetail();
898 for (ResidueDetail resDetail : resDetails)
900 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
902 foundAnnotations.add(resDetail.getContent());
905 return foundAnnotations;
909 public boolean isAccessionMatched(String accession)
911 boolean isStrictMatch = true;
912 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
913 : curDBRefAccessionIdsString
914 .contains(accession.toLowerCase(Locale.ROOT));
917 private boolean isFoundInSiftsEntry(String accessionId)
919 Set<String> siftsDBRefs = getAllMappingAccession();
920 return accessionId != null
921 && siftsDBRefs.contains(accessionId.toLowerCase(Locale.ROOT));
925 * Pad omitted residue positions in PDB sequence with gaps
929 void padWithGaps(Map<Integer, String> resNumMap,
930 List<Integer> omitNonObserved)
932 if (resNumMap == null || resNumMap.isEmpty())
936 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
937 // Arrays.sort(keys);
938 int firstIndex = keys[0];
939 int lastIndex = keys[keys.length - 1];
940 // jalview.bin.Console.outPrintln("Min value " + firstIndex);
941 // jalview.bin.Console.outPrintln("Max value " + lastIndex);
942 for (int x = firstIndex; x <= lastIndex; x++)
944 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
946 resNumMap.put(x, "-");
952 public Entity getEntityById(String id) throws SiftsException
954 // Determines an entity to process by performing a heuristic matching of all
955 // Entities with the given chainId and choosing the best matching Entity
956 Entity entity = getEntityByMostOptimalMatchedId(id);
961 throw new SiftsException("Entity " + id + " not found");
965 * This method was added because EntityId is NOT always equal to ChainId.
966 * Hence, it provides the logic to greedily detect the "true" Entity for a
967 * given chainId where discrepancies exist.
972 public Entity getEntityByMostOptimalMatchedId(String chainId)
974 // jalview.bin.Console.outPrintln("---> advanced greedy entityId matching
977 List<Entity> entities = siftsEntry.getEntity();
978 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
980 for (Entity entity : entities)
982 sPojo[count] = new SiftsEntitySortPojo();
983 sPojo[count].entityId = entity.getEntityId();
985 List<Segment> segments = entity.getSegment();
986 for (Segment segment : segments)
988 List<Residue> residues = segment.getListResidue().getResidue();
989 for (Residue residue : residues)
991 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
992 for (CrossRefDb cRefDb : cRefDbs)
994 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
998 ++sPojo[count].resCount;
999 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
1001 ++sPojo[count].chainIdFreq;
1006 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
1007 / sPojo[count].resCount;
1010 Arrays.sort(sPojo, Collections.reverseOrder());
1011 // jalview.bin.Console.outPrintln("highest matched entity : " +
1012 // sPojo[0].entityId);
1013 // jalview.bin.Console.outPrintln("highest matched pid : " + sPojo[0].pid);
1015 if (sPojo[0].entityId != null)
1017 if (sPojo[0].pid < 1)
1021 for (Entity entity : entities)
1023 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
1033 private class SiftsEntitySortPojo
1034 implements Comparable<SiftsEntitySortPojo>
1036 public String entityId;
1038 public int chainIdFreq;
1042 public int resCount;
1045 public int compareTo(SiftsEntitySortPojo o)
1047 return this.pid - o.pid;
1051 private class SegmentHelperPojo
1053 private SequenceI seq;
1055 private HashMap<Integer, int[]> mapping;
1057 private TreeMap<Integer, String> resNumMap;
1059 private List<Integer> omitNonObserved;
1061 private int nonObservedShiftIndex;
1064 * count of number of 'not observed' positions in the PDB record's SEQRES
1065 * (total number of residues with coordinates == length(SEQRES) -
1068 private int pdbeNonObserved;
1070 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1071 TreeMap<Integer, String> resNumMap,
1072 List<Integer> omitNonObserved, int nonObservedShiftIndex,
1073 int pdbeNonObserved)
1076 setMapping(mapping);
1077 setResNumMap(resNumMap);
1078 setOmitNonObserved(omitNonObserved);
1079 setNonObservedShiftIndex(nonObservedShiftIndex);
1080 setPdbeNonObserved(pdbeNonObserved);
1084 public void setPdbeNonObserved(int pdbeNonObserved2)
1086 this.pdbeNonObserved = pdbeNonObserved2;
1089 public int getPdbeNonObserved()
1091 return pdbeNonObserved;
1094 public SequenceI getSeq()
1099 public void setSeq(SequenceI seq)
1104 public HashMap<Integer, int[]> getMapping()
1109 public void setMapping(HashMap<Integer, int[]> mapping)
1111 this.mapping = mapping;
1114 public TreeMap<Integer, String> getResNumMap()
1119 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1121 this.resNumMap = resNumMap;
1124 public List<Integer> getOmitNonObserved()
1126 return omitNonObserved;
1129 public void setOmitNonObserved(List<Integer> omitNonObserved)
1131 this.omitNonObserved = omitNonObserved;
1134 public int getNonObservedShiftIndex()
1136 return nonObservedShiftIndex;
1139 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1141 this.nonObservedShiftIndex = nonObservedShiftIndex;
1147 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1148 throws SiftsException
1150 String seqRes = mp.getSeqResidue();
1151 String seqName = mp.getSeqName();
1152 int sStart = mp.getSeqStart();
1153 int sEnd = mp.getSeqEnd();
1155 String strRes = mp.getStrResidue();
1156 String strName = mp.getStrName();
1157 int pdbStart = mp.getStrStart();
1158 int pdbEnd = mp.getStrEnd();
1160 String type = mp.getType();
1162 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1164 int len = 72 - maxid - 1;
1166 int nochunks = ((seqRes.length()) / len)
1167 + ((seqRes.length()) % len > 0 ? 1 : 0);
1169 StringBuilder output = new StringBuilder(512);
1170 output.append(NEWLINE);
1171 output.append("Sequence \u27f7 Structure mapping details")
1173 output.append("Method: SIFTS");
1174 output.append(NEWLINE).append(NEWLINE);
1176 output.append(new Format("%" + maxid + "s").form(seqName));
1177 output.append(" : ");
1178 output.append(String.valueOf(sStart));
1179 output.append(" - ");
1180 output.append(String.valueOf(sEnd));
1181 output.append(" Maps to ");
1182 output.append(NEWLINE);
1183 output.append(new Format("%" + maxid + "s").form(structId));
1184 output.append(" : ");
1185 output.append(String.valueOf(pdbStart));
1186 output.append(" - ");
1187 output.append(String.valueOf(pdbEnd));
1188 output.append(NEWLINE).append(NEWLINE);
1190 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1191 int matchedSeqCount = 0;
1192 for (int j = 0; j < nochunks; j++)
1194 // Print the first aligned sequence
1195 output.append(new Format("%" + (maxid) + "s").form(seqName))
1198 for (int i = 0; i < len; i++)
1200 if ((i + (j * len)) < seqRes.length())
1202 output.append(seqRes.charAt(i + (j * len)));
1206 output.append(NEWLINE);
1207 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1210 * Print out the match symbols:
1211 * | for exact match (ignoring case)
1212 * . if PAM250 score is positive
1215 for (int i = 0; i < len; i++)
1219 if ((i + (j * len)) < seqRes.length())
1221 char c1 = seqRes.charAt(i + (j * len));
1222 char c2 = strRes.charAt(i + (j * len));
1223 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1224 if (sameChar && !Comparison.isGap(c1))
1229 else if (type.equals("pep"))
1231 if (pam250.getPairwiseScore(c1, c2) > 0)
1245 } catch (IndexOutOfBoundsException e)
1250 // Now print the second aligned sequence
1251 output = output.append(NEWLINE);
1252 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1254 for (int i = 0; i < len; i++)
1256 if ((i + (j * len)) < strRes.length())
1258 output.append(strRes.charAt(i + (j * len)));
1261 output.append(NEWLINE).append(NEWLINE);
1263 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1264 if (pid < SiftsSettings.getFailSafePIDThreshold())
1266 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1268 output.append("Length of alignment = " + seqRes.length())
1270 output.append(new Format("Percentage ID = %2.2f").form(pid));
1275 public int getEntityCount()
1277 return siftsEntry.getEntity().size();
1281 public String getDbAccessionId()
1283 return siftsEntry.getDbAccessionId();
1287 public String getDbCoordSys()
1289 return siftsEntry.getDbCoordSys();
1293 public String getDbSource()
1295 return siftsEntry.getDbSource();
1299 public String getDbVersion()
1301 return siftsEntry.getDbVersion();
1304 public static void setMockSiftsFile(File file)
1306 mockSiftsFile = file;