2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ws.sifts;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.PrintStream;
30 import java.net.URLConnection;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.attribute.BasicFileAttributes;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Date;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
44 import java.util.TreeMap;
45 import java.util.zip.GZIPInputStream;
47 import javax.xml.bind.JAXBContext;
48 import javax.xml.bind.JAXBElement;
49 import javax.xml.bind.Unmarshaller;
50 import javax.xml.stream.XMLInputFactory;
51 import javax.xml.stream.XMLStreamReader;
53 import jalview.analysis.AlignSeq;
54 import jalview.analysis.scoremodels.ScoreMatrix;
55 import jalview.analysis.scoremodels.ScoreModels;
56 import jalview.api.DBRefEntryI;
57 import jalview.api.SiftsClientI;
58 import jalview.datamodel.DBRefEntry;
59 import jalview.datamodel.DBRefSource;
60 import jalview.datamodel.SequenceI;
61 import jalview.io.BackupFiles;
62 import jalview.io.StructureFile;
63 import jalview.schemes.ResidueProperties;
64 import jalview.structure.StructureMapping;
65 import jalview.util.Comparison;
66 import jalview.util.DBRefUtils;
67 import jalview.util.Format;
68 import jalview.util.Platform;
69 import jalview.xml.binding.sifts.Entry;
70 import jalview.xml.binding.sifts.Entry.Entity;
71 import jalview.xml.binding.sifts.Entry.Entity.Segment;
72 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListMapRegion.MapRegion;
73 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue;
74 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.CrossRefDb;
75 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.ResidueDetail;
77 import mc_view.PDBChain;
79 public class SiftsClient implements SiftsClientI
82 * for use in mocking out file fetch for tests only
83 * - reset to null after testing!
85 private static File mockSiftsFile;
87 private Entry siftsEntry;
89 private StructureFile pdb;
93 private String structId;
95 private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
98 * PDB sequence position to sequence coordinate mapping as derived from SIFTS
99 * record for the identified SeqCoordSys Used for lift-over from sequence
100 * derived from PDB (with first extracted PDBRESNUM as 'start' to the sequence
101 * being annotated with PDB data
103 private jalview.datamodel.Mapping seqFromPdbMapping;
105 private static final int BUFFER_SIZE = 4096;
107 public static final int UNASSIGNED = Integer.MIN_VALUE;
109 private static final int PDB_RES_POS = 0;
111 private static final int PDB_ATOM_POS = 1;
113 private static final int PDBE_POS = 2;
115 private static final String NOT_OBSERVED = "Not_Observed";
117 private static final String SIFTS_FTP_BASE_URL = "http://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/";
119 private final static String NEWLINE = System.lineSeparator();
121 private String curSourceDBRef;
123 private HashSet<String> curDBRefAccessionIdsString;
125 private enum CoordinateSys
127 UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
131 private CoordinateSys(String name)
136 public String getName()
142 private enum ResidueDetailType
144 NAME_SEC_STRUCTURE("nameSecondaryStructure"),
145 CODE_SEC_STRUCTURE("codeSecondaryStructure"), ANNOTATION("Annotation");
149 private ResidueDetailType(String code)
154 public String getCode()
161 * Fetch SIFTs file for the given PDBfile and construct an instance of
165 * @throws SiftsException
167 public SiftsClient(StructureFile pdb) throws SiftsException
170 this.pdbId = pdb.getId();
171 File siftsFile = getSiftsFile(pdbId);
172 siftsEntry = parseSIFTs(siftsFile);
176 * Parse the given SIFTs File and return a JAXB POJO of parsed data
179 * - the GZipped SIFTs XML file to parse
182 * if a problem occurs while parsing the SIFTs XML
184 private Entry parseSIFTs(File siftFile) throws SiftsException
186 try (InputStream in = new FileInputStream(siftFile);
187 GZIPInputStream gzis = new GZIPInputStream(in);)
189 // System.out.println("File : " + siftFile.getAbsolutePath());
190 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
191 XMLStreamReader streamReader = XMLInputFactory.newInstance()
192 .createXMLStreamReader(gzis);
193 Unmarshaller um = jc.createUnmarshaller();
194 JAXBElement<Entry> jbe = um.unmarshal(streamReader, Entry.class);
195 return jbe.getValue();
196 } catch (Exception e)
199 throw new SiftsException(e.getMessage());
204 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
205 * repository if not found in cache
208 * @return SIFTs XML file
209 * @throws SiftsException
211 public static File getSiftsFile(String pdbId) throws SiftsException
214 * return mocked file if it has been set
216 if (mockSiftsFile != null)
218 return mockSiftsFile;
221 String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
222 + pdbId.toLowerCase() + ".xml.gz";
223 File siftsFile = new File(siftsFileName);
224 if (siftsFile.exists())
226 // The line below is required for unit testing... don't comment it out!!!
227 System.out.println(">>> SIFTS File already downloaded for " + pdbId);
229 if (isFileOlderThanThreshold(siftsFile,
230 SiftsSettings.getCacheThresholdInDays()))
232 File oldSiftsFile = new File(siftsFileName + "_old");
233 BackupFiles.moveFileToFile(siftsFile, oldSiftsFile);
236 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
237 oldSiftsFile.delete();
239 } catch (IOException e)
242 BackupFiles.moveFileToFile(oldSiftsFile, siftsFile);
243 return new File(siftsFileName);
253 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
254 } catch (IOException e)
256 throw new SiftsException(e.getMessage());
262 * This method enables checking if a cached file has exceeded a certain
268 * the threshold in days
271 public static boolean isFileOlderThanThreshold(File file, int noOfDays)
273 Path filePath = file.toPath();
274 BasicFileAttributes attr;
278 attr = Files.readAttributes(filePath, BasicFileAttributes.class);
279 diffInDays = (int) ((new Date().getTime()
280 - attr.lastModifiedTime().toMillis())
281 / (1000 * 60 * 60 * 24));
282 // System.out.println("Diff in days : " + diffInDays);
283 } catch (IOException e)
287 return noOfDays <= diffInDays;
291 * Download a SIFTs XML file for a given PDB Id from an FTP repository
294 * @return downloaded SIFTs XML file
295 * @throws SiftsException
296 * @throws IOException
298 public static File downloadSiftsFile(String pdbId)
299 throws SiftsException, IOException
301 if (pdbId.contains(".cif"))
303 pdbId = pdbId.replace(".cif", "");
305 String siftFile = pdbId + ".xml.gz";
306 String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
309 * Download the file from URL to either
310 * Java: directory of cached downloaded SIFTS files
311 * Javascript: temporary 'file' (in-memory cache)
313 File downloadTo = null;
316 downloadTo = File.createTempFile(siftFile, ".xml.gz");
320 downloadTo = new File(
321 SiftsSettings.getSiftDownloadDirectory() + siftFile);
322 File siftsDownloadDir = new File(
323 SiftsSettings.getSiftDownloadDirectory());
324 if (!siftsDownloadDir.exists())
326 siftsDownloadDir.mkdirs();
330 // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
331 // long now = System.currentTimeMillis();
332 URL url = new URL(siftsFileFTPURL);
333 URLConnection conn = url.openConnection();
334 InputStream inputStream = conn.getInputStream();
335 FileOutputStream outputStream = new FileOutputStream(downloadTo);
336 byte[] buffer = new byte[BUFFER_SIZE];
338 while ((bytesRead = inputStream.read(buffer)) != -1)
340 outputStream.write(buffer, 0, bytesRead);
342 outputStream.close();
344 // System.out.println(">>> File downloaded : " + downloadedSiftsFile
345 // + " took " + (System.currentTimeMillis() - now) + "ms");
350 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
354 * @return true if the file was deleted or doesn't exist
356 public static boolean deleteSiftsFileByPDBId(String pdbId)
358 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
359 + pdbId.toLowerCase() + ".xml.gz");
360 if (siftsFile.exists())
362 return siftsFile.delete();
368 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
371 * - the target sequence for the operation
372 * @return a valid DBRefEntry that is SIFTs compatible
374 * if no valid source DBRefEntry was found for the given sequences
376 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
377 throws SiftsException
379 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
380 if (dbRefs == null || dbRefs.size() < 1)
382 throw new SiftsException(
383 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
386 for (DBRefEntry dbRef : dbRefs)
388 if (dbRef == null || dbRef.getAccessionId() == null
389 || dbRef.getSource() == null)
393 String canonicalSource = DBRefUtils
394 .getCanonicalName(dbRef.getSource());
395 if (isValidDBRefEntry(dbRef)
396 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
397 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
402 throw new SiftsException("Could not get source DB Ref");
406 * Check that the DBRef Entry is properly populated and is available in this
407 * SiftClient instance
410 * - DBRefEntry to validate
411 * @return true validation is successful otherwise false is returned.
413 boolean isValidDBRefEntry(DBRefEntryI entry)
415 return entry != null && entry.getAccessionId() != null
416 && isFoundInSiftsEntry(entry.getAccessionId());
420 public HashSet<String> getAllMappingAccession()
422 HashSet<String> accessions = new HashSet<String>();
423 List<Entity> entities = siftsEntry.getEntity();
424 for (Entity entity : entities)
426 List<Segment> segments = entity.getSegment();
427 for (Segment segment : segments)
429 List<MapRegion> mapRegions = segment.getListMapRegion()
431 for (MapRegion mapRegion : mapRegions)
434 .add(mapRegion.getDb().getDbAccessionId().toLowerCase());
442 public StructureMapping getSiftsStructureMapping(SequenceI seq,
443 String pdbFile, String chain) throws SiftsException
445 SequenceI aseq = seq;
446 while (seq.getDatasetSequence() != null)
448 seq = seq.getDatasetSequence();
450 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
451 System.out.println("Getting SIFTS mapping for " + structId + ": seq "
454 final StringBuilder mappingDetails = new StringBuilder(128);
455 PrintStream ps = new PrintStream(System.out)
458 public void print(String x)
460 mappingDetails.append(x);
464 public void println()
466 mappingDetails.append(NEWLINE);
469 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
471 String mappingOutput = mappingDetails.toString();
472 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
473 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
479 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
480 SequenceI seq, java.io.PrintStream os) throws SiftsException
482 List<Integer> omitNonObserved = new ArrayList<>();
483 int nonObservedShiftIndex = 0, pdbeNonObserved = 0;
484 // System.out.println("Generating mappings for : " + entityId);
485 Entity entity = null;
486 entity = getEntityById(entityId);
487 String originalSeq = AlignSeq.extractGaps(
488 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
489 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
490 DBRefEntryI sourceDBRef;
491 sourceDBRef = getValidSourceDBRef(seq);
492 // TODO ensure sequence start/end is in the same coordinate system and
493 // consistent with the choosen sourceDBRef
495 // set sequence coordinate system - default value is UniProt
496 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
498 seqCoordSys = CoordinateSys.PDB;
501 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
502 for (DBRefEntry dbref : seq.getDBRefs())
504 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
506 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
508 curDBRefAccessionIdsString = dbRefAccessionIdsString;
509 curSourceDBRef = sourceDBRef.getAccessionId();
511 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
512 List<Segment> segments = entity.getSegment();
513 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
514 omitNonObserved, nonObservedShiftIndex, pdbeNonObserved);
515 processSegments(segments, shp);
518 populateAtomPositions(entityId, mapping);
519 } catch (Exception e)
523 if (seqCoordSys == CoordinateSys.UNIPROT)
525 padWithGaps(resNumMap, omitNonObserved);
527 int seqStart = UNASSIGNED;
528 int seqEnd = UNASSIGNED;
529 int pdbStart = UNASSIGNED;
530 int pdbEnd = UNASSIGNED;
532 if (mapping.isEmpty())
534 throw new SiftsException("SIFTS mapping failed");
536 // also construct a mapping object between the seq-coord sys and the PDB
539 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
542 seqEnd = keys[keys.length - 1];
543 List<int[]> from = new ArrayList<>(), to = new ArrayList<>();
544 int[] _cfrom = null, _cto = null;
545 String matchedSeq = originalSeq;
546 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb
547 // sequence that starts <-1
549 for (int seqps : keys)
551 int pdbpos = mapping.get(seqps)[PDBE_POS];
552 if (pdbpos == UNASSIGNED)
554 // not correct - pdbpos might be -1, but leave it for now
557 if (_cfrom == null || seqps != _cfrom[1] + 1)
559 _cfrom = new int[] { seqps, seqps };
561 _cto = null; // discontinuity
567 if (_cto == null || pdbpos != 1 + _cto[1])
569 _cto = new int[] { pdbpos, pdbpos };
577 _cfrom = new int[from.size() * 2];
578 _cto = new int[to.size() * 2];
580 for (int[] range : from)
582 _cfrom[p++] = range[0];
583 _cfrom[p++] = range[1];
587 for (int[] range : to)
589 _cto[p++] = range[0];
590 _cto[p++] = range[1];
594 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
596 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
597 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
598 int orignalSeqStart = seq.getStart();
599 if (orignalSeqStart >= 1)
601 int subSeqStart = (seqStart >= orignalSeqStart)
602 ? seqStart - orignalSeqStart
604 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
605 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
607 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
611 matchedSeq = originalSeq.substring(1, originalSeq.length());
615 StringBuilder targetStrucSeqs = new StringBuilder();
616 for (String res : resNumMap.values())
618 targetStrucSeqs.append(res);
623 MappingOutputPojo mop = new MappingOutputPojo();
624 mop.setSeqStart(seqStart);
625 mop.setSeqEnd(seqEnd);
626 mop.setSeqName(seq.getName());
627 mop.setSeqResidue(matchedSeq);
629 mop.setStrStart(pdbStart);
630 mop.setStrEnd(pdbEnd);
631 mop.setStrName(structId);
632 mop.setStrResidue(targetStrucSeqs.toString());
635 os.print(getMappingOutput(mop).toString());
641 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
643 SequenceI seq = shp.getSeq();
644 HashMap<Integer, int[]> mapping = shp.getMapping();
645 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
646 List<Integer> omitNonObserved = shp.getOmitNonObserved();
647 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
648 int pdbeNonObservedCount = shp.getPdbeNonObserved();
649 int firstPDBResNum = UNASSIGNED;
650 for (Segment segment : segments)
652 // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
654 List<Residue> residues = segment.getListResidue().getResidue();
655 for (Residue residue : residues)
657 boolean isObserved = isResidueObserved(residue);
658 int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
660 int currSeqIndex = UNASSIGNED;
661 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
662 CrossRefDb pdbRefDb = null;
663 for (CrossRefDb cRefDb : cRefDbs)
665 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
668 if (firstPDBResNum == UNASSIGNED)
670 firstPDBResNum = getLeadingIntegerValue(cRefDb.getDbResNum(),
677 // after we find the first observed residue we just increment
682 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
683 && isAccessionMatched(cRefDb.getDbAccessionId()))
685 currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
687 if (pdbRefDb != null)
689 break;// exit loop if pdb and uniprot are already found
695 ++pdbeNonObservedCount;
697 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
700 // if the sequence has a primary reference to the PDB, then we are
701 // dealing with a sequence extracted directly from the PDB. In that
702 // case, numbering is PDBe - non-observed residues
703 currSeqIndex = seq.getStart() - 1 + pdbeIndex;
707 if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
710 // mapping to PDB or PDBe so we need to bookkeep for the
713 omitNonObserved.add(currSeqIndex);
714 ++nonObservedShiftIndex;
717 if (currSeqIndex == UNASSIGNED)
719 // change in logic - unobserved residues with no currSeqIndex
720 // corresponding are still counted in both nonObservedShiftIndex and
724 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
734 int resNum = (pdbRefDb == null)
735 ? getLeadingIntegerValue(residue.getDbResNum(),
737 : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
742 char resCharCode = ResidueProperties
743 .getSingleCharacterCode(ResidueProperties
744 .getCanonicalAminoAcid(residue.getDbResName()));
745 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
747 int[] mappingcols = new int[] { Integer.valueOf(resNum),
748 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
750 mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
758 * Get the leading integer part of a string that begins with an integer.
761 * - the string input to process
763 * - value returned if unsuccessful
766 static int getLeadingIntegerValue(String input, int failValue)
772 String[] parts = input.split("(?=\\D)(?<=\\d)");
773 if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
775 return Integer.valueOf(parts[0]);
783 * Target chain to populate mapping of its atom positions.
785 * Two dimension array of residue index versus atom position
786 * @throws IllegalArgumentException
787 * Thrown if chainId or mapping is null
788 * @throws SiftsException
790 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
791 throws IllegalArgumentException, SiftsException
795 PDBChain chain = pdb.findChain(chainId);
797 if (chain == null || mapping == null)
799 throw new IllegalArgumentException(
800 "Chain id or mapping must not be null.");
802 for (int[] map : mapping.values())
804 if (map[PDB_RES_POS] != UNASSIGNED)
806 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
809 } catch (NullPointerException e)
811 throw new SiftsException(e.getMessage());
812 } catch (Exception e)
814 throw new SiftsException(e.getMessage());
820 * @param residueIndex
821 * The residue index used for the search
823 * A collection of Atom to search
824 * @return atom position for the given residue index
826 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
830 throw new IllegalArgumentException(
831 "atoms collection must not be null!");
833 for (Atom atom : atoms)
835 if (atom.resNumber == residueIndex)
837 return atom.atomIndex;
844 * Checks if the residue instance is marked 'Not_observed' or not
849 private boolean isResidueObserved(Residue residue)
851 Set<String> annotations = getResidueAnnotaitons(residue,
852 ResidueDetailType.ANNOTATION);
853 if (annotations == null || annotations.isEmpty())
857 for (String annotation : annotations)
859 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
868 * Get annotation String for a given residue and annotation type
874 private Set<String> getResidueAnnotaitons(Residue residue,
875 ResidueDetailType type)
877 HashSet<String> foundAnnotations = new HashSet<String>();
878 List<ResidueDetail> resDetails = residue.getResidueDetail();
879 for (ResidueDetail resDetail : resDetails)
881 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
883 foundAnnotations.add(resDetail.getContent());
886 return foundAnnotations;
890 public boolean isAccessionMatched(String accession)
892 boolean isStrictMatch = true;
893 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
894 : curDBRefAccessionIdsString.contains(accession.toLowerCase());
897 private boolean isFoundInSiftsEntry(String accessionId)
899 Set<String> siftsDBRefs = getAllMappingAccession();
900 return accessionId != null
901 && siftsDBRefs.contains(accessionId.toLowerCase());
905 * Pad omitted residue positions in PDB sequence with gaps
909 void padWithGaps(Map<Integer, String> resNumMap,
910 List<Integer> omitNonObserved)
912 if (resNumMap == null || resNumMap.isEmpty())
916 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
917 // Arrays.sort(keys);
918 int firstIndex = keys[0];
919 int lastIndex = keys[keys.length - 1];
920 // System.out.println("Min value " + firstIndex);
921 // System.out.println("Max value " + lastIndex);
922 for (int x = firstIndex; x <= lastIndex; x++)
924 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
926 resNumMap.put(x, "-");
932 public Entity getEntityById(String id) throws SiftsException
934 // Determines an entity to process by performing a heuristic matching of all
935 // Entities with the given chainId and choosing the best matching Entity
936 Entity entity = getEntityByMostOptimalMatchedId(id);
941 throw new SiftsException("Entity " + id + " not found");
945 * This method was added because EntityId is NOT always equal to ChainId.
946 * Hence, it provides the logic to greedily detect the "true" Entity for a
947 * given chainId where discrepancies exist.
952 public Entity getEntityByMostOptimalMatchedId(String chainId)
954 // System.out.println("---> advanced greedy entityId matching block
956 List<Entity> entities = siftsEntry.getEntity();
957 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
959 for (Entity entity : entities)
961 sPojo[count] = new SiftsEntitySortPojo();
962 sPojo[count].entityId = entity.getEntityId();
964 List<Segment> segments = entity.getSegment();
965 for (Segment segment : segments)
967 List<Residue> residues = segment.getListResidue().getResidue();
968 for (Residue residue : residues)
970 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
971 for (CrossRefDb cRefDb : cRefDbs)
973 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
977 ++sPojo[count].resCount;
978 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
980 ++sPojo[count].chainIdFreq;
985 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
986 / sPojo[count].resCount;
989 Arrays.sort(sPojo, Collections.reverseOrder());
990 // System.out.println("highest matched entity : " + sPojo[0].entityId);
991 // System.out.println("highest matched pid : " + sPojo[0].pid);
993 if (sPojo[0].entityId != null)
995 if (sPojo[0].pid < 1)
999 for (Entity entity : entities)
1001 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
1011 private class SiftsEntitySortPojo
1012 implements Comparable<SiftsEntitySortPojo>
1014 public String entityId;
1016 public int chainIdFreq;
1020 public int resCount;
1023 public int compareTo(SiftsEntitySortPojo o)
1025 return this.pid - o.pid;
1029 private class SegmentHelperPojo
1031 private SequenceI seq;
1033 private HashMap<Integer, int[]> mapping;
1035 private TreeMap<Integer, String> resNumMap;
1037 private List<Integer> omitNonObserved;
1039 private int nonObservedShiftIndex;
1042 * count of number of 'not observed' positions in the PDB record's SEQRES
1043 * (total number of residues with coordinates == length(SEQRES) -
1046 private int pdbeNonObserved;
1048 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1049 TreeMap<Integer, String> resNumMap,
1050 List<Integer> omitNonObserved, int nonObservedShiftIndex,
1051 int pdbeNonObserved)
1054 setMapping(mapping);
1055 setResNumMap(resNumMap);
1056 setOmitNonObserved(omitNonObserved);
1057 setNonObservedShiftIndex(nonObservedShiftIndex);
1058 setPdbeNonObserved(pdbeNonObserved);
1062 public void setPdbeNonObserved(int pdbeNonObserved2)
1064 this.pdbeNonObserved = pdbeNonObserved2;
1067 public int getPdbeNonObserved()
1069 return pdbeNonObserved;
1072 public SequenceI getSeq()
1077 public void setSeq(SequenceI seq)
1082 public HashMap<Integer, int[]> getMapping()
1087 public void setMapping(HashMap<Integer, int[]> mapping)
1089 this.mapping = mapping;
1092 public TreeMap<Integer, String> getResNumMap()
1097 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1099 this.resNumMap = resNumMap;
1102 public List<Integer> getOmitNonObserved()
1104 return omitNonObserved;
1107 public void setOmitNonObserved(List<Integer> omitNonObserved)
1109 this.omitNonObserved = omitNonObserved;
1112 public int getNonObservedShiftIndex()
1114 return nonObservedShiftIndex;
1117 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1119 this.nonObservedShiftIndex = nonObservedShiftIndex;
1125 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1126 throws SiftsException
1128 String seqRes = mp.getSeqResidue();
1129 String seqName = mp.getSeqName();
1130 int sStart = mp.getSeqStart();
1131 int sEnd = mp.getSeqEnd();
1133 String strRes = mp.getStrResidue();
1134 String strName = mp.getStrName();
1135 int pdbStart = mp.getStrStart();
1136 int pdbEnd = mp.getStrEnd();
1138 String type = mp.getType();
1140 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1142 int len = 72 - maxid - 1;
1144 int nochunks = ((seqRes.length()) / len)
1145 + ((seqRes.length()) % len > 0 ? 1 : 0);
1147 StringBuilder output = new StringBuilder(512);
1148 output.append(NEWLINE);
1149 output.append("Sequence \u27f7 Structure mapping details")
1151 output.append("Method: SIFTS");
1152 output.append(NEWLINE).append(NEWLINE);
1154 output.append(new Format("%" + maxid + "s").form(seqName));
1155 output.append(" : ");
1156 output.append(String.valueOf(sStart));
1157 output.append(" - ");
1158 output.append(String.valueOf(sEnd));
1159 output.append(" Maps to ");
1160 output.append(NEWLINE);
1161 output.append(new Format("%" + maxid + "s").form(structId));
1162 output.append(" : ");
1163 output.append(String.valueOf(pdbStart));
1164 output.append(" - ");
1165 output.append(String.valueOf(pdbEnd));
1166 output.append(NEWLINE).append(NEWLINE);
1168 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1169 int matchedSeqCount = 0;
1170 for (int j = 0; j < nochunks; j++)
1172 // Print the first aligned sequence
1173 output.append(new Format("%" + (maxid) + "s").form(seqName))
1176 for (int i = 0; i < len; i++)
1178 if ((i + (j * len)) < seqRes.length())
1180 output.append(seqRes.charAt(i + (j * len)));
1184 output.append(NEWLINE);
1185 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1188 * Print out the match symbols:
1189 * | for exact match (ignoring case)
1190 * . if PAM250 score is positive
1193 for (int i = 0; i < len; i++)
1197 if ((i + (j * len)) < seqRes.length())
1199 char c1 = seqRes.charAt(i + (j * len));
1200 char c2 = strRes.charAt(i + (j * len));
1201 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1202 if (sameChar && !Comparison.isGap(c1))
1207 else if (type.equals("pep"))
1209 if (pam250.getPairwiseScore(c1, c2) > 0)
1223 } catch (IndexOutOfBoundsException e)
1228 // Now print the second aligned sequence
1229 output = output.append(NEWLINE);
1230 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1232 for (int i = 0; i < len; i++)
1234 if ((i + (j * len)) < strRes.length())
1236 output.append(strRes.charAt(i + (j * len)));
1239 output.append(NEWLINE).append(NEWLINE);
1241 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1242 if (pid < SiftsSettings.getFailSafePIDThreshold())
1244 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1246 output.append("Length of alignment = " + seqRes.length())
1248 output.append(new Format("Percentage ID = %2.2f").form(pid));
1253 public int getEntityCount()
1255 return siftsEntry.getEntity().size();
1259 public String getDbAccessionId()
1261 return siftsEntry.getDbAccessionId();
1265 public String getDbCoordSys()
1267 return siftsEntry.getDbCoordSys();
1271 public String getDbSource()
1273 return siftsEntry.getDbSource();
1277 public String getDbVersion()
1279 return siftsEntry.getDbVersion();
1282 public static void setMockSiftsFile(File file)
1284 mockSiftsFile = file;