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 jalview.analysis.AlignSeq;
24 import jalview.analysis.scoremodels.ScoreMatrix;
25 import jalview.analysis.scoremodels.ScoreModels;
26 import jalview.api.DBRefEntryI;
27 import jalview.api.SiftsClientI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.StructureFile;
32 import jalview.schemes.ResidueProperties;
33 import jalview.structure.StructureMapping;
34 import jalview.util.Comparison;
35 import jalview.util.DBRefUtils;
36 import jalview.util.Format;
37 import jalview.xml.binding.sifts.Entry;
38 import jalview.xml.binding.sifts.Entry.Entity;
39 import jalview.xml.binding.sifts.Entry.Entity.Segment;
40 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListMapRegion.MapRegion;
41 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue;
42 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.CrossRefDb;
43 import jalview.xml.binding.sifts.Entry.Entity.Segment.ListResidue.Residue.ResidueDetail;
46 import java.io.FileInputStream;
47 import java.io.FileOutputStream;
48 import java.io.IOException;
49 import java.io.InputStream;
50 import java.io.PrintStream;
52 import java.net.URLConnection;
53 import java.nio.file.Files;
54 import java.nio.file.Path;
55 import java.nio.file.attribute.BasicFileAttributes;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.Collection;
59 import java.util.Collections;
60 import java.util.Date;
61 import java.util.HashMap;
62 import java.util.HashSet;
63 import java.util.List;
66 import java.util.TreeMap;
67 import java.util.zip.GZIPInputStream;
69 import javax.xml.bind.JAXBContext;
70 import javax.xml.bind.Unmarshaller;
71 import javax.xml.stream.XMLInputFactory;
72 import javax.xml.stream.XMLStreamReader;
75 import MCview.PDBChain;
77 public class SiftsClient implements SiftsClientI
80 * for use in mocking out file fetch for tests only
81 * - reset to null after testing!
83 private static File mockSiftsFile;
85 private Entry siftsEntry;
87 private StructureFile pdb;
91 private String structId;
93 private CoordinateSys seqCoordSys = CoordinateSys.UNIPROT;
96 * PDB sequence position to sequence coordinate mapping as derived from SIFTS
97 * record for the identified SeqCoordSys Used for lift-over from sequence
98 * derived from PDB (with first extracted PDBRESNUM as 'start' to the sequence
99 * being annotated with PDB data
101 private jalview.datamodel.Mapping seqFromPdbMapping;
103 private static final int BUFFER_SIZE = 4096;
105 public static final int UNASSIGNED = Integer.MIN_VALUE;
107 private static final int PDB_RES_POS = 0;
109 private static final int PDB_ATOM_POS = 1;
111 private static final int PDBE_POS = 2;
113 private static final String NOT_OBSERVED = "Not_Observed";
115 private static final String SIFTS_FTP_BASE_URL = "http://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/";
117 private final static String NEWLINE = System.lineSeparator();
119 private String curSourceDBRef;
121 private HashSet<String> curDBRefAccessionIdsString;
123 private enum CoordinateSys
125 UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
128 private CoordinateSys(String name)
133 public String getName()
139 private enum ResidueDetailType
141 NAME_SEC_STRUCTURE("nameSecondaryStructure"),
142 CODE_SEC_STRUCTURE("codeSecondaryStructure"), ANNOTATION("Annotation");
145 private ResidueDetailType(String code)
150 public String getCode()
157 * Fetch SIFTs file for the given PDBfile and construct an instance of
161 * @throws SiftsException
163 public SiftsClient(StructureFile pdb) throws SiftsException
166 this.pdbId = pdb.getId();
167 File siftsFile = getSiftsFile(pdbId);
168 siftsEntry = parseSIFTs(siftsFile);
172 * Parse the given SIFTs File and return a JAXB POJO of parsed data
175 * - the GZipped SIFTs XML file to parse
178 * if a problem occurs while parsing the SIFTs XML
180 private Entry parseSIFTs(File siftFile) throws SiftsException
182 try (InputStream in = new FileInputStream(siftFile);
183 GZIPInputStream gzis = new GZIPInputStream(in);)
185 // System.out.println("File : " + siftFile.getAbsolutePath());
186 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
187 XMLStreamReader streamReader = XMLInputFactory.newInstance()
188 .createXMLStreamReader(gzis);
189 Unmarshaller um = jc.createUnmarshaller();
190 return (Entry) um.unmarshal(streamReader);
191 } catch (Exception e)
194 throw new SiftsException(e.getMessage());
199 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
200 * repository if not found in cache
203 * @return SIFTs XML file
204 * @throws SiftsException
206 public static File getSiftsFile(String pdbId) throws SiftsException
209 * return mocked file if it has been set
211 if (mockSiftsFile != null)
213 return mockSiftsFile;
216 String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
217 + pdbId.toLowerCase() + ".xml.gz";
218 File siftsFile = new File(siftsFileName);
219 if (siftsFile.exists())
221 // The line below is required for unit testing... don't comment it out!!!
222 System.out.println(">>> SIFTS File already downloaded for " + pdbId);
224 if (isFileOlderThanThreshold(siftsFile,
225 SiftsSettings.getCacheThresholdInDays()))
227 File oldSiftsFile = new File(siftsFileName + "_old");
228 siftsFile.renameTo(oldSiftsFile);
231 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
232 oldSiftsFile.delete();
234 } catch (IOException e)
237 oldSiftsFile.renameTo(siftsFile);
238 return new File(siftsFileName);
248 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
249 } catch (IOException e)
251 throw new SiftsException(e.getMessage());
257 * This method enables checking if a cached file has exceeded a certain
263 * the threshold in days
266 public static boolean isFileOlderThanThreshold(File file, int noOfDays)
268 Path filePath = file.toPath();
269 BasicFileAttributes attr;
273 attr = Files.readAttributes(filePath, BasicFileAttributes.class);
274 diffInDays = (int) ((new Date().getTime()
275 - attr.lastModifiedTime().toMillis())
276 / (1000 * 60 * 60 * 24));
277 // System.out.println("Diff in days : " + diffInDays);
278 } catch (IOException e)
282 return noOfDays <= diffInDays;
286 * Download a SIFTs XML file for a given PDB Id from an FTP repository
289 * @return downloaded SIFTs XML file
290 * @throws SiftsException
291 * @throws IOException
293 public static File downloadSiftsFile(String pdbId)
294 throws SiftsException, IOException
296 if (pdbId.contains(".cif"))
298 pdbId = pdbId.replace(".cif", "");
300 String siftFile = pdbId + ".xml.gz";
301 String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
302 String downloadedSiftsFile = SiftsSettings.getSiftDownloadDirectory()
304 File siftsDownloadDir = new File(
305 SiftsSettings.getSiftDownloadDirectory());
306 if (!siftsDownloadDir.exists())
308 siftsDownloadDir.mkdirs();
310 // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
311 // long now = System.currentTimeMillis();
312 URL url = new URL(siftsFileFTPURL);
313 URLConnection conn = url.openConnection();
314 InputStream inputStream = conn.getInputStream();
315 FileOutputStream outputStream = new FileOutputStream(
316 downloadedSiftsFile);
317 byte[] buffer = new byte[BUFFER_SIZE];
319 while ((bytesRead = inputStream.read(buffer)) != -1)
321 outputStream.write(buffer, 0, bytesRead);
323 outputStream.close();
325 // System.out.println(">>> File downloaded : " + downloadedSiftsFile
326 // + " took " + (System.currentTimeMillis() - now) + "ms");
327 return new File(downloadedSiftsFile);
331 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
335 * @return true if the file was deleted or doesn't exist
337 public static boolean deleteSiftsFileByPDBId(String pdbId)
339 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
340 + pdbId.toLowerCase() + ".xml.gz");
341 if (siftsFile.exists())
343 return siftsFile.delete();
349 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
352 * - the target sequence for the operation
353 * @return a valid DBRefEntry that is SIFTs compatible
355 * if no valid source DBRefEntry was found for the given sequences
357 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
358 throws SiftsException
360 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
361 if (dbRefs == null || dbRefs.size() < 1)
363 throw new SiftsException(
364 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
367 for (DBRefEntry dbRef : dbRefs)
369 if (dbRef == null || dbRef.getAccessionId() == null
370 || dbRef.getSource() == null)
374 String canonicalSource = DBRefUtils
375 .getCanonicalName(dbRef.getSource());
376 if (isValidDBRefEntry(dbRef)
377 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
378 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
383 throw new SiftsException("Could not get source DB Ref");
387 * Check that the DBRef Entry is properly populated and is available in this
388 * SiftClient instance
391 * - DBRefEntry to validate
392 * @return true validation is successful otherwise false is returned.
394 boolean isValidDBRefEntry(DBRefEntryI entry)
396 return entry != null && entry.getAccessionId() != null
397 && isFoundInSiftsEntry(entry.getAccessionId());
401 public HashSet<String> getAllMappingAccession()
403 HashSet<String> accessions = new HashSet<String>();
404 List<Entity> entities = siftsEntry.getEntity();
405 for (Entity entity : entities)
407 List<Segment> segments = entity.getSegment();
408 for (Segment segment : segments)
410 List<MapRegion> mapRegions = segment.getListMapRegion()
412 for (MapRegion mapRegion : mapRegions)
415 .add(mapRegion.getDb().getDbAccessionId().toLowerCase());
423 public StructureMapping getSiftsStructureMapping(SequenceI seq,
424 String pdbFile, String chain) throws SiftsException
426 SequenceI aseq = seq;
427 while (seq.getDatasetSequence() != null)
429 seq = seq.getDatasetSequence();
431 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
432 System.out.println("Getting SIFTS mapping for " + structId + ": seq "
435 final StringBuilder mappingDetails = new StringBuilder(128);
436 PrintStream ps = new PrintStream(System.out)
439 public void print(String x)
441 mappingDetails.append(x);
445 public void println()
447 mappingDetails.append(NEWLINE);
450 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
452 String mappingOutput = mappingDetails.toString();
453 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
454 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
460 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
461 SequenceI seq, java.io.PrintStream os) throws SiftsException
463 List<Integer> omitNonObserved = new ArrayList<>();
464 int nonObservedShiftIndex = 0,pdbeNonObserved=0;
465 // System.out.println("Generating mappings for : " + entityId);
466 Entity entity = null;
467 entity = getEntityById(entityId);
468 String originalSeq = AlignSeq.extractGaps(
469 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
470 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
471 DBRefEntryI sourceDBRef;
472 sourceDBRef = getValidSourceDBRef(seq);
473 // TODO ensure sequence start/end is in the same coordinate system and
474 // consistent with the choosen sourceDBRef
476 // set sequence coordinate system - default value is UniProt
477 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
479 seqCoordSys = CoordinateSys.PDB;
482 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
483 for (DBRefEntry dbref : seq.getDBRefs())
485 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
487 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
489 curDBRefAccessionIdsString = dbRefAccessionIdsString;
490 curSourceDBRef = sourceDBRef.getAccessionId();
492 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
493 List<Segment> segments = entity.getSegment();
494 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
495 omitNonObserved, nonObservedShiftIndex,pdbeNonObserved);
496 processSegments(segments, shp);
499 populateAtomPositions(entityId, mapping);
500 } catch (Exception e)
504 if (seqCoordSys == CoordinateSys.UNIPROT)
506 padWithGaps(resNumMap, omitNonObserved);
508 int seqStart = UNASSIGNED;
509 int seqEnd = UNASSIGNED;
510 int pdbStart = UNASSIGNED;
511 int pdbEnd = UNASSIGNED;
513 if (mapping.isEmpty())
515 throw new SiftsException("SIFTS mapping failed");
517 // also construct a mapping object between the seq-coord sys and the PDB seq's coord sys
519 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
522 seqEnd = keys[keys.length - 1];
523 List<int[]> from=new ArrayList<>(),to=new ArrayList<>();
524 int[]_cfrom=null,_cto=null;
525 String matchedSeq = originalSeq;
526 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb sequence that starts <-1
530 int pdbpos = mapping.get(seqps)[PDBE_POS];
531 if (pdbpos == UNASSIGNED)
533 // not correct - pdbpos might be -1, but leave it for now
536 if (_cfrom==null || seqps!=_cfrom[1]+1)
538 _cfrom = new int[] { seqps,seqps};
540 _cto = null; // discontinuity
544 if (_cto==null || pdbpos!=1+_cto[1])
546 _cto = new int[] { pdbpos,pdbpos};
552 _cfrom = new int[from.size() * 2];
553 _cto = new int[to.size() * 2];
555 for (int[] range : from)
557 _cfrom[p++] = range[0];
558 _cfrom[p++] = range[1];
562 for (int[] range : to)
564 _cto[p++] = range[0];
565 _cto[p++] = range[1];
569 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
572 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
573 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
574 int orignalSeqStart = seq.getStart();
575 if (orignalSeqStart >= 1)
577 int subSeqStart = (seqStart >= orignalSeqStart)
578 ? seqStart - orignalSeqStart
580 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
581 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
583 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
587 matchedSeq = originalSeq.substring(1, originalSeq.length());
591 StringBuilder targetStrucSeqs = new StringBuilder();
592 for (String res : resNumMap.values())
594 targetStrucSeqs.append(res);
599 MappingOutputPojo mop = new MappingOutputPojo();
600 mop.setSeqStart(seqStart);
601 mop.setSeqEnd(seqEnd);
602 mop.setSeqName(seq.getName());
603 mop.setSeqResidue(matchedSeq);
605 mop.setStrStart(pdbStart);
606 mop.setStrEnd(pdbEnd);
607 mop.setStrName(structId);
608 mop.setStrResidue(targetStrucSeqs.toString());
611 os.print(getMappingOutput(mop).toString());
617 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
619 SequenceI seq = shp.getSeq();
620 HashMap<Integer, int[]> mapping = shp.getMapping();
621 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
622 List<Integer> omitNonObserved = shp.getOmitNonObserved();
623 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
624 int pdbeNonObservedCount = shp.getPdbeNonObserved();
625 int firstPDBResNum = UNASSIGNED;
626 for (Segment segment : segments)
628 // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
630 List<Residue> residues = segment.getListResidue().getResidue();
631 for (Residue residue : residues)
633 boolean isObserved = isResidueObserved(residue);
634 int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
636 int currSeqIndex = UNASSIGNED;
637 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
638 CrossRefDb pdbRefDb = null;
639 for (CrossRefDb cRefDb : cRefDbs)
641 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
644 if (firstPDBResNum == UNASSIGNED)
646 firstPDBResNum = getLeadingIntegerValue(cRefDb.getDbResNum(),
653 // after we find the first observed residue we just increment
658 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
659 && isAccessionMatched(cRefDb.getDbAccessionId()))
661 currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
663 if (pdbRefDb != null)
665 break;// exit loop if pdb and uniprot are already found
671 ++pdbeNonObservedCount;
673 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
676 // if the sequence has a primary reference to the PDB, then we are
677 // dealing with a sequence extracted directly from the PDB. In that
678 // case, numbering is PDBe - non-observed residues
679 currSeqIndex = seq.getStart() - 1 + pdbeIndex;
683 if (seqCoordSys != CoordinateSys.UNIPROT) // FIXME: PDB or PDBe only
686 // mapping to PDB or PDBe so we need to bookkeep for the
689 omitNonObserved.add(currSeqIndex);
690 ++nonObservedShiftIndex;
693 if (currSeqIndex == UNASSIGNED)
695 // change in logic - unobserved residues with no currSeqIndex
696 // corresponding are still counted in both nonObservedShiftIndex and
700 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
710 int resNum = (pdbRefDb == null)
711 ? getLeadingIntegerValue(residue.getDbResNum(),
713 : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
718 char resCharCode = ResidueProperties
719 .getSingleCharacterCode(ResidueProperties
720 .getCanonicalAminoAcid(residue.getDbResName()));
721 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
723 int[] mappingcols = new int[] { Integer.valueOf(resNum),
724 UNASSIGNED, isObserved ? firstPDBResNum : UNASSIGNED };
726 mapping.put(currSeqIndex - nonObservedShiftIndex, mappingcols);
734 * Get the leading integer part of a string that begins with an integer.
737 * - the string input to process
739 * - value returned if unsuccessful
742 static int getLeadingIntegerValue(String input, int failValue)
748 String[] parts = input.split("(?=\\D)(?<=\\d)");
749 if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
751 return Integer.valueOf(parts[0]);
759 * Target chain to populate mapping of its atom positions.
761 * Two dimension array of residue index versus atom position
762 * @throws IllegalArgumentException
763 * Thrown if chainId or mapping is null
764 * @throws SiftsException
766 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
767 throws IllegalArgumentException, SiftsException
771 PDBChain chain = pdb.findChain(chainId);
773 if (chain == null || mapping == null)
775 throw new IllegalArgumentException(
776 "Chain id or mapping must not be null.");
778 for (int[] map : mapping.values())
780 if (map[PDB_RES_POS] != UNASSIGNED)
782 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
785 } catch (NullPointerException e)
787 throw new SiftsException(e.getMessage());
788 } catch (Exception e)
790 throw new SiftsException(e.getMessage());
796 * @param residueIndex
797 * The residue index used for the search
799 * A collection of Atom to search
800 * @return atom position for the given residue index
802 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
806 throw new IllegalArgumentException(
807 "atoms collection must not be null!");
809 for (Atom atom : atoms)
811 if (atom.resNumber == residueIndex)
813 return atom.atomIndex;
820 * Checks if the residue instance is marked 'Not_observed' or not
825 private boolean isResidueObserved(Residue residue)
827 Set<String> annotations = getResidueAnnotaitons(residue,
828 ResidueDetailType.ANNOTATION);
829 if (annotations == null || annotations.isEmpty())
833 for (String annotation : annotations)
835 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
844 * Get annotation String for a given residue and annotation type
850 private Set<String> getResidueAnnotaitons(Residue residue,
851 ResidueDetailType type)
853 HashSet<String> foundAnnotations = new HashSet<String>();
854 List<ResidueDetail> resDetails = residue.getResidueDetail();
855 for (ResidueDetail resDetail : resDetails)
857 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
859 foundAnnotations.add(resDetail.getContent());
862 return foundAnnotations;
866 public boolean isAccessionMatched(String accession)
868 boolean isStrictMatch = true;
869 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
870 : curDBRefAccessionIdsString.contains(accession.toLowerCase());
873 private boolean isFoundInSiftsEntry(String accessionId)
875 Set<String> siftsDBRefs = getAllMappingAccession();
876 return accessionId != null
877 && siftsDBRefs.contains(accessionId.toLowerCase());
881 * Pad omitted residue positions in PDB sequence with gaps
885 void padWithGaps(Map<Integer, String> resNumMap,
886 List<Integer> omitNonObserved)
888 if (resNumMap == null || resNumMap.isEmpty())
892 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
893 // Arrays.sort(keys);
894 int firstIndex = keys[0];
895 int lastIndex = keys[keys.length - 1];
896 // System.out.println("Min value " + firstIndex);
897 // System.out.println("Max value " + lastIndex);
898 for (int x = firstIndex; x <= lastIndex; x++)
900 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
902 resNumMap.put(x, "-");
908 public Entity getEntityById(String id) throws SiftsException
910 // Determines an entity to process by performing a heuristic matching of all
911 // Entities with the given chainId and choosing the best matching Entity
912 Entity entity = getEntityByMostOptimalMatchedId(id);
917 throw new SiftsException("Entity " + id + " not found");
921 * This method was added because EntityId is NOT always equal to ChainId.
922 * Hence, it provides the logic to greedily detect the "true" Entity for a
923 * given chainId where discrepancies exist.
928 public Entity getEntityByMostOptimalMatchedId(String chainId)
930 // System.out.println("---> advanced greedy entityId matching block
932 List<Entity> entities = siftsEntry.getEntity();
933 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
935 for (Entity entity : entities)
937 sPojo[count] = new SiftsEntitySortPojo();
938 sPojo[count].entityId = entity.getEntityId();
940 List<Segment> segments = entity.getSegment();
941 for (Segment segment : segments)
943 List<Residue> residues = segment.getListResidue().getResidue();
944 for (Residue residue : residues)
946 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
947 for (CrossRefDb cRefDb : cRefDbs)
949 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
953 ++sPojo[count].resCount;
954 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
956 ++sPojo[count].chainIdFreq;
961 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
962 / sPojo[count].resCount;
965 Arrays.sort(sPojo, Collections.reverseOrder());
966 // System.out.println("highest matched entity : " + sPojo[0].entityId);
967 // System.out.println("highest matched pid : " + sPojo[0].pid);
969 if (sPojo[0].entityId != null)
971 if (sPojo[0].pid < 1)
975 for (Entity entity : entities)
977 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
987 private class SiftsEntitySortPojo
988 implements Comparable<SiftsEntitySortPojo>
990 public String entityId;
992 public int chainIdFreq;
999 public int compareTo(SiftsEntitySortPojo o)
1001 return this.pid - o.pid;
1005 private class SegmentHelperPojo
1007 private SequenceI seq;
1009 private HashMap<Integer, int[]> mapping;
1011 private TreeMap<Integer, String> resNumMap;
1013 private List<Integer> omitNonObserved;
1015 private int nonObservedShiftIndex;
1018 * count of number of 'not observed' positions in the PDB record's SEQRES
1019 * (total number of residues with coordinates == length(SEQRES) -
1022 private int pdbeNonObserved;
1024 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
1025 TreeMap<Integer, String> resNumMap,
1026 List<Integer> omitNonObserved, int nonObservedShiftIndex,
1027 int pdbeNonObserved)
1030 setMapping(mapping);
1031 setResNumMap(resNumMap);
1032 setOmitNonObserved(omitNonObserved);
1033 setNonObservedShiftIndex(nonObservedShiftIndex);
1034 setPdbeNonObserved(pdbeNonObserved);
1038 public void setPdbeNonObserved(int pdbeNonObserved2)
1040 this.pdbeNonObserved = pdbeNonObserved2;
1043 public int getPdbeNonObserved()
1045 return pdbeNonObserved;
1047 public SequenceI getSeq()
1052 public void setSeq(SequenceI seq)
1057 public HashMap<Integer, int[]> getMapping()
1062 public void setMapping(HashMap<Integer, int[]> mapping)
1064 this.mapping = mapping;
1067 public TreeMap<Integer, String> getResNumMap()
1072 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1074 this.resNumMap = resNumMap;
1077 public List<Integer> getOmitNonObserved()
1079 return omitNonObserved;
1082 public void setOmitNonObserved(List<Integer> omitNonObserved)
1084 this.omitNonObserved = omitNonObserved;
1087 public int getNonObservedShiftIndex()
1089 return nonObservedShiftIndex;
1092 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1094 this.nonObservedShiftIndex = nonObservedShiftIndex;
1100 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1101 throws SiftsException
1103 String seqRes = mp.getSeqResidue();
1104 String seqName = mp.getSeqName();
1105 int sStart = mp.getSeqStart();
1106 int sEnd = mp.getSeqEnd();
1108 String strRes = mp.getStrResidue();
1109 String strName = mp.getStrName();
1110 int pdbStart = mp.getStrStart();
1111 int pdbEnd = mp.getStrEnd();
1113 String type = mp.getType();
1115 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1117 int len = 72 - maxid - 1;
1119 int nochunks = ((seqRes.length()) / len)
1120 + ((seqRes.length()) % len > 0 ? 1 : 0);
1122 StringBuilder output = new StringBuilder(512);
1123 output.append(NEWLINE);
1124 output.append("Sequence \u27f7 Structure mapping details")
1126 output.append("Method: SIFTS");
1127 output.append(NEWLINE).append(NEWLINE);
1129 output.append(new Format("%" + maxid + "s").form(seqName));
1130 output.append(" : ");
1131 output.append(String.valueOf(sStart));
1132 output.append(" - ");
1133 output.append(String.valueOf(sEnd));
1134 output.append(" Maps to ");
1135 output.append(NEWLINE);
1136 output.append(new Format("%" + maxid + "s").form(structId));
1137 output.append(" : ");
1138 output.append(String.valueOf(pdbStart));
1139 output.append(" - ");
1140 output.append(String.valueOf(pdbEnd));
1141 output.append(NEWLINE).append(NEWLINE);
1143 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1144 int matchedSeqCount = 0;
1145 for (int j = 0; j < nochunks; j++)
1147 // Print the first aligned sequence
1148 output.append(new Format("%" + (maxid) + "s").form(seqName))
1151 for (int i = 0; i < len; i++)
1153 if ((i + (j * len)) < seqRes.length())
1155 output.append(seqRes.charAt(i + (j * len)));
1159 output.append(NEWLINE);
1160 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1163 * Print out the match symbols:
1164 * | for exact match (ignoring case)
1165 * . if PAM250 score is positive
1168 for (int i = 0; i < len; i++)
1172 if ((i + (j * len)) < seqRes.length())
1174 char c1 = seqRes.charAt(i + (j * len));
1175 char c2 = strRes.charAt(i + (j * len));
1176 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1177 if (sameChar && !Comparison.isGap(c1))
1182 else if (type.equals("pep"))
1184 if (pam250.getPairwiseScore(c1, c2) > 0)
1198 } catch (IndexOutOfBoundsException e)
1203 // Now print the second aligned sequence
1204 output = output.append(NEWLINE);
1205 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1207 for (int i = 0; i < len; i++)
1209 if ((i + (j * len)) < strRes.length())
1211 output.append(strRes.charAt(i + (j * len)));
1214 output.append(NEWLINE).append(NEWLINE);
1216 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1217 if (pid < SiftsSettings.getFailSafePIDThreshold())
1219 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1221 output.append("Length of alignment = " + seqRes.length())
1223 output.append(new Format("Percentage ID = %2.2f").form(pid));
1228 public int getEntityCount()
1230 return siftsEntry.getEntity().size();
1234 public String getDbAccessionId()
1236 return siftsEntry.getDbAccessionId();
1240 public String getDbCoordSys()
1242 return siftsEntry.getDbCoordSys();
1246 public String getDbSource()
1248 return siftsEntry.getDbSource();
1252 public String getDbVersion()
1254 return siftsEntry.getDbVersion();
1257 public static void setMockSiftsFile(File file)
1259 mockSiftsFile = file;