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_FTP_BASE_URL = "http://ftp.ebi.ac.uk/pub/databases/msd/sifts/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 = SIFTS_FTP_BASE_URL + 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");
352 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
356 * @return true if the file was deleted or doesn't exist
358 public static boolean deleteSiftsFileByPDBId(String pdbId)
360 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
361 + pdbId.toLowerCase(Locale.ROOT) + ".xml.gz");
362 if (siftsFile.exists())
364 return siftsFile.delete();
370 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
373 * - the target sequence for the operation
374 * @return a valid DBRefEntry that is SIFTs compatible
376 * if no valid source DBRefEntry was found for the given sequences
378 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
379 throws SiftsException
381 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
382 if (dbRefs == null || dbRefs.size() < 1)
384 throw new SiftsException(
385 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
388 for (DBRefEntry dbRef : dbRefs)
390 if (dbRef == null || dbRef.getAccessionId() == null
391 || dbRef.getSource() == null)
395 String canonicalSource = DBRefUtils
396 .getCanonicalName(dbRef.getSource());
397 if (isValidDBRefEntry(dbRef)
398 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
399 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
404 throw new SiftsException("Could not get source DB Ref");
408 * Check that the DBRef Entry is properly populated and is available in this
409 * SiftClient instance
412 * - DBRefEntry to validate
413 * @return true validation is successful otherwise false is returned.
415 boolean isValidDBRefEntry(DBRefEntryI entry)
417 return entry != null && entry.getAccessionId() != null
418 && isFoundInSiftsEntry(entry.getAccessionId());
422 public HashSet<String> getAllMappingAccession()
424 HashSet<String> accessions = new HashSet<String>();
425 List<Entity> entities = siftsEntry.getEntity();
426 for (Entity entity : entities)
428 List<Segment> segments = entity.getSegment();
429 for (Segment segment : segments)
431 List<MapRegion> mapRegions = segment.getListMapRegion()
433 for (MapRegion mapRegion : mapRegions)
436 .add(mapRegion.getDb().getDbAccessionId().toLowerCase(Locale.ROOT));
444 public StructureMapping getSiftsStructureMapping(SequenceI seq,
445 String pdbFile, String chain) throws SiftsException
447 SequenceI aseq = seq;
448 while (seq.getDatasetSequence() != null)
450 seq = seq.getDatasetSequence();
452 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
453 System.out.println("Getting SIFTS mapping for " + structId + ": seq "
456 final StringBuilder mappingDetails = new StringBuilder(128);
457 PrintStream ps = new PrintStream(System.out)
460 public void print(String x)
462 mappingDetails.append(x);
466 public void println()
468 mappingDetails.append(NEWLINE);
471 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
473 String mappingOutput = mappingDetails.toString();
474 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
475 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
481 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
482 SequenceI seq, java.io.PrintStream os) throws SiftsException
484 List<Integer> omitNonObserved = new ArrayList<>();
485 int nonObservedShiftIndex = 0, pdbeNonObserved = 0;
486 // System.out.println("Generating mappings for : " + entityId);
487 Entity entity = null;
488 entity = getEntityById(entityId);
489 String originalSeq = AlignSeq.extractGaps(
490 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
491 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
492 DBRefEntryI sourceDBRef;
493 sourceDBRef = getValidSourceDBRef(seq);
494 // TODO ensure sequence start/end is in the same coordinate system and
495 // consistent with the choosen sourceDBRef
497 // set sequence coordinate system - default value is UniProt
498 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
500 seqCoordSys = CoordinateSys.PDB;
503 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
504 for (DBRefEntry dbref : seq.getDBRefs())
506 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase(Locale.ROOT));
508 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase(Locale.ROOT));
510 curDBRefAccessionIdsString = dbRefAccessionIdsString;
511 curSourceDBRef = sourceDBRef.getAccessionId();
513 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
514 List<Segment> segments = entity.getSegment();
515 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
516 omitNonObserved, nonObservedShiftIndex, pdbeNonObserved);
517 processSegments(segments, shp);
520 populateAtomPositions(entityId, mapping);
521 } catch (Exception e)
525 if (seqCoordSys == CoordinateSys.UNIPROT)
527 padWithGaps(resNumMap, omitNonObserved);
529 int seqStart = UNASSIGNED;
530 int seqEnd = UNASSIGNED;
531 int pdbStart = UNASSIGNED;
532 int pdbEnd = UNASSIGNED;
534 if (mapping.isEmpty())
536 throw new SiftsException("SIFTS mapping failed");
538 // also construct a mapping object between the seq-coord sys and the PDB
541 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
544 seqEnd = keys[keys.length - 1];
545 List<int[]> from = new ArrayList<>(), to = new ArrayList<>();
546 int[] _cfrom = null, _cto = null;
547 String matchedSeq = originalSeq;
548 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb
549 // sequence that starts <-1
551 for (int seqps : keys)
553 int pdbpos = mapping.get(seqps)[PDBE_POS];
554 if (pdbpos == UNASSIGNED)
556 // not correct - pdbpos might be -1, but leave it for now
559 if (_cfrom == null || seqps != _cfrom[1] + 1)
561 _cfrom = new int[] { seqps, seqps };
563 _cto = null; // discontinuity
569 if (_cto == null || pdbpos != 1 + _cto[1])
571 _cto = new int[] { pdbpos, pdbpos };
579 _cfrom = new int[from.size() * 2];
580 _cto = new int[to.size() * 2];
582 for (int[] range : from)
584 _cfrom[p++] = range[0];
585 _cfrom[p++] = range[1];
589 for (int[] range : to)
591 _cto[p++] = range[0];
592 _cto[p++] = range[1];
596 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
598 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
599 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
600 int orignalSeqStart = seq.getStart();
601 if (orignalSeqStart >= 1)
603 int subSeqStart = (seqStart >= orignalSeqStart)
604 ? seqStart - orignalSeqStart
606 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
607 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
609 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
613 matchedSeq = originalSeq.substring(1, originalSeq.length());
617 StringBuilder targetStrucSeqs = new StringBuilder();
618 for (String res : resNumMap.values())
620 targetStrucSeqs.append(res);
625 MappingOutputPojo mop = new MappingOutputPojo();
626 mop.setSeqStart(seqStart);
627 mop.setSeqEnd(seqEnd);
628 mop.setSeqName(seq.getName());
629 mop.setSeqResidue(matchedSeq);
631 mop.setStrStart(pdbStart);
632 mop.setStrEnd(pdbEnd);
633 mop.setStrName(structId);
634 mop.setStrResidue(targetStrucSeqs.toString());
637 os.print(getMappingOutput(mop).toString());
643 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
645 SequenceI seq = shp.getSeq();
646 HashMap<Integer, int[]> mapping = shp.getMapping();
647 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
648 List<Integer> omitNonObserved = shp.getOmitNonObserved();
649 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
650 int pdbeNonObservedCount = shp.getPdbeNonObserved();
651 int firstPDBResNum = UNASSIGNED;
652 for (Segment segment : segments)
654 // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
656 List<Residue> residues = segment.getListResidue().getResidue();
657 for (Residue residue : residues)
659 boolean isObserved = isResidueObserved(residue);
660 int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
662 int currSeqIndex = UNASSIGNED;
663 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
664 CrossRefDb pdbRefDb = null;
665 for (CrossRefDb cRefDb : cRefDbs)
667 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
670 if (firstPDBResNum == UNASSIGNED)
672 firstPDBResNum = getLeadingIntegerValue(cRefDb.getDbResNum(),
679 // after we find the first observed residue we just increment
684 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
685 && isAccessionMatched(cRefDb.getDbAccessionId()))
687 currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
689 if (pdbRefDb != null)
691 break;// exit loop if pdb and uniprot are already found
697 ++pdbeNonObservedCount;
699 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
702 // if the sequence has a primary reference to the PDB, then we are
703 // dealing with a sequence extracted directly from the PDB. In that
704 // case, numbering is PDBe - non-observed residues
705 currSeqIndex = seq.getStart() - 1 + pdbeIndex;
709 if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
712 // mapping to PDB or PDBe so we need to bookkeep for the
715 omitNonObserved.add(currSeqIndex);
716 ++nonObservedShiftIndex;
719 if (currSeqIndex == UNASSIGNED)
721 // change in logic - unobserved residues with no currSeqIndex
722 // corresponding are still counted in both nonObservedShiftIndex and
726 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
736 int resNum = (pdbRefDb == null)
737 ? getLeadingIntegerValue(residue.getDbResNum(),
739 : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
744 char resCharCode = ResidueProperties
745 .getSingleCharacterCode(ResidueProperties
746 .getCanonicalAminoAcid(residue.getDbResName()));
747 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
749 int[] mappingcols = new int[] { Integer.valueOf(resNum),
750 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
752 mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
760 * Get the leading integer part of a string that begins with an integer.
763 * - the string input to process
765 * - value returned if unsuccessful
768 static int getLeadingIntegerValue(String input, int failValue)
774 String[] parts = input.split("(?=\\D)(?<=\\d)");
775 if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
777 return Integer.valueOf(parts[0]);
785 * Target chain to populate mapping of its atom positions.
787 * Two dimension array of residue index versus atom position
788 * @throws IllegalArgumentException
789 * Thrown if chainId or mapping is null
790 * @throws SiftsException
792 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
793 throws IllegalArgumentException, SiftsException
797 PDBChain chain = pdb.findChain(chainId);
799 if (chain == null || mapping == null)
801 throw new IllegalArgumentException(
802 "Chain id or mapping must not be null.");
804 for (int[] map : mapping.values())
806 if (map[PDB_RES_POS] != UNASSIGNED)
808 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
811 } catch (NullPointerException e)
813 throw new SiftsException(e.getMessage());
814 } catch (Exception e)
816 throw new SiftsException(e.getMessage());
822 * @param residueIndex
823 * The residue index used for the search
825 * A collection of Atom to search
826 * @return atom position for the given residue index
828 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
832 throw new IllegalArgumentException(
833 "atoms collection must not be null!");
835 for (Atom atom : atoms)
837 if (atom.resNumber == residueIndex)
839 return atom.atomIndex;
846 * Checks if the residue instance is marked 'Not_observed' or not
851 private boolean isResidueObserved(Residue residue)
853 Set<String> annotations = getResidueAnnotaitons(residue,
854 ResidueDetailType.ANNOTATION);
855 if (annotations == null || annotations.isEmpty())
859 for (String annotation : annotations)
861 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
870 * Get annotation String for a given residue and annotation type
876 private Set<String> getResidueAnnotaitons(Residue residue,
877 ResidueDetailType type)
879 HashSet<String> foundAnnotations = new HashSet<String>();
880 List<ResidueDetail> resDetails = residue.getResidueDetail();
881 for (ResidueDetail resDetail : resDetails)
883 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
885 foundAnnotations.add(resDetail.getContent());
888 return foundAnnotations;
892 public boolean isAccessionMatched(String accession)
894 boolean isStrictMatch = true;
895 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
896 : curDBRefAccessionIdsString.contains(accession.toLowerCase(Locale.ROOT));
899 private boolean isFoundInSiftsEntry(String accessionId)
901 Set<String> siftsDBRefs = getAllMappingAccession();
902 return accessionId != null
903 && siftsDBRefs.contains(accessionId.toLowerCase(Locale.ROOT));
907 * Pad omitted residue positions in PDB sequence with gaps
911 void padWithGaps(Map<Integer, String> resNumMap,
912 List<Integer> omitNonObserved)
914 if (resNumMap == null || resNumMap.isEmpty())
918 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
919 // Arrays.sort(keys);
920 int firstIndex = keys[0];
921 int lastIndex = keys[keys.length - 1];
922 // System.out.println("Min value " + firstIndex);
923 // System.out.println("Max value " + lastIndex);
924 for (int x = firstIndex; x <= lastIndex; x++)
926 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
928 resNumMap.put(x, "-");
934 public Entity getEntityById(String id) throws SiftsException
936 // Determines an entity to process by performing a heuristic matching of all
937 // Entities with the given chainId and choosing the best matching Entity
938 Entity entity = getEntityByMostOptimalMatchedId(id);
943 throw new SiftsException("Entity " + id + " not found");
947 * This method was added because EntityId is NOT always equal to ChainId.
948 * Hence, it provides the logic to greedily detect the "true" Entity for a
949 * given chainId where discrepancies exist.
954 public Entity getEntityByMostOptimalMatchedId(String chainId)
956 // System.out.println("---> advanced greedy entityId matching block
958 List<Entity> entities = siftsEntry.getEntity();
959 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
961 for (Entity entity : entities)
963 sPojo[count] = new SiftsEntitySortPojo();
964 sPojo[count].entityId = entity.getEntityId();
966 List<Segment> segments = entity.getSegment();
967 for (Segment segment : segments)
969 List<Residue> residues = segment.getListResidue().getResidue();
970 for (Residue residue : residues)
972 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
973 for (CrossRefDb cRefDb : cRefDbs)
975 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
979 ++sPojo[count].resCount;
980 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
982 ++sPojo[count].chainIdFreq;
987 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
988 / sPojo[count].resCount;
991 Arrays.sort(sPojo, Collections.reverseOrder());
992 // System.out.println("highest matched entity : " + sPojo[0].entityId);
993 // System.out.println("highest matched pid : " + sPojo[0].pid);
995 if (sPojo[0].entityId != null)
997 if (sPojo[0].pid < 1)
1001 for (Entity entity : entities)
1003 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
1013 private class SiftsEntitySortPojo
1014 implements Comparable<SiftsEntitySortPojo>
1016 public String entityId;
1018 public int chainIdFreq;
1022 public int resCount;
1025 public int compareTo(SiftsEntitySortPojo o)
1027 return this.pid - o.pid;
1031 private class SegmentHelperPojo
1033 private SequenceI seq;
1035 private HashMap<Integer, int[]> mapping;
1037 private TreeMap<Integer, String> resNumMap;
1039 private List<Integer> omitNonObserved;
1041 private int nonObservedShiftIndex;
1044 * count of number of 'not observed' positions in the PDB record's SEQRES
1045 * (total number of residues with coordinates == length(SEQRES) -
1048 private int pdbeNonObserved;
1050 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1051 TreeMap<Integer, String> resNumMap,
1052 List<Integer> omitNonObserved, int nonObservedShiftIndex,
1053 int pdbeNonObserved)
1056 setMapping(mapping);
1057 setResNumMap(resNumMap);
1058 setOmitNonObserved(omitNonObserved);
1059 setNonObservedShiftIndex(nonObservedShiftIndex);
1060 setPdbeNonObserved(pdbeNonObserved);
1064 public void setPdbeNonObserved(int pdbeNonObserved2)
1066 this.pdbeNonObserved = pdbeNonObserved2;
1069 public int getPdbeNonObserved()
1071 return pdbeNonObserved;
1074 public SequenceI getSeq()
1079 public void setSeq(SequenceI seq)
1084 public HashMap<Integer, int[]> getMapping()
1089 public void setMapping(HashMap<Integer, int[]> mapping)
1091 this.mapping = mapping;
1094 public TreeMap<Integer, String> getResNumMap()
1099 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1101 this.resNumMap = resNumMap;
1104 public List<Integer> getOmitNonObserved()
1106 return omitNonObserved;
1109 public void setOmitNonObserved(List<Integer> omitNonObserved)
1111 this.omitNonObserved = omitNonObserved;
1114 public int getNonObservedShiftIndex()
1116 return nonObservedShiftIndex;
1119 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1121 this.nonObservedShiftIndex = nonObservedShiftIndex;
1127 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1128 throws SiftsException
1130 String seqRes = mp.getSeqResidue();
1131 String seqName = mp.getSeqName();
1132 int sStart = mp.getSeqStart();
1133 int sEnd = mp.getSeqEnd();
1135 String strRes = mp.getStrResidue();
1136 String strName = mp.getStrName();
1137 int pdbStart = mp.getStrStart();
1138 int pdbEnd = mp.getStrEnd();
1140 String type = mp.getType();
1142 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1144 int len = 72 - maxid - 1;
1146 int nochunks = ((seqRes.length()) / len)
1147 + ((seqRes.length()) % len > 0 ? 1 : 0);
1149 StringBuilder output = new StringBuilder(512);
1150 output.append(NEWLINE);
1151 output.append("Sequence \u27f7 Structure mapping details")
1153 output.append("Method: SIFTS");
1154 output.append(NEWLINE).append(NEWLINE);
1156 output.append(new Format("%" + maxid + "s").form(seqName));
1157 output.append(" : ");
1158 output.append(String.valueOf(sStart));
1159 output.append(" - ");
1160 output.append(String.valueOf(sEnd));
1161 output.append(" Maps to ");
1162 output.append(NEWLINE);
1163 output.append(new Format("%" + maxid + "s").form(structId));
1164 output.append(" : ");
1165 output.append(String.valueOf(pdbStart));
1166 output.append(" - ");
1167 output.append(String.valueOf(pdbEnd));
1168 output.append(NEWLINE).append(NEWLINE);
1170 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1171 int matchedSeqCount = 0;
1172 for (int j = 0; j < nochunks; j++)
1174 // Print the first aligned sequence
1175 output.append(new Format("%" + (maxid) + "s").form(seqName))
1178 for (int i = 0; i < len; i++)
1180 if ((i + (j * len)) < seqRes.length())
1182 output.append(seqRes.charAt(i + (j * len)));
1186 output.append(NEWLINE);
1187 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1190 * Print out the match symbols:
1191 * | for exact match (ignoring case)
1192 * . if PAM250 score is positive
1195 for (int i = 0; i < len; i++)
1199 if ((i + (j * len)) < seqRes.length())
1201 char c1 = seqRes.charAt(i + (j * len));
1202 char c2 = strRes.charAt(i + (j * len));
1203 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1204 if (sameChar && !Comparison.isGap(c1))
1209 else if (type.equals("pep"))
1211 if (pam250.getPairwiseScore(c1, c2) > 0)
1225 } catch (IndexOutOfBoundsException e)
1230 // Now print the second aligned sequence
1231 output = output.append(NEWLINE);
1232 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1234 for (int i = 0; i < len; i++)
1236 if ((i + (j * len)) < strRes.length())
1238 output.append(strRes.charAt(i + (j * len)));
1241 output.append(NEWLINE).append(NEWLINE);
1243 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1244 if (pid < SiftsSettings.getFailSafePIDThreshold())
1246 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1248 output.append("Length of alignment = " + seqRes.length())
1250 output.append(new Format("Percentage ID = %2.2f").form(pid));
1255 public int getEntityCount()
1257 return siftsEntry.getEntity().size();
1261 public String getDbAccessionId()
1263 return siftsEntry.getDbAccessionId();
1267 public String getDbCoordSys()
1269 return siftsEntry.getDbCoordSys();
1273 public String getDbSource()
1275 return siftsEntry.getDbSource();
1279 public String getDbVersion()
1281 return siftsEntry.getDbVersion();
1284 public static void setMockSiftsFile(File file)
1286 mockSiftsFile = file;