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 String NOT_OBSERVED = "Not_Observed";
113 private static final String SIFTS_FTP_BASE_URL = "http://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/";
115 private final static String NEWLINE = System.lineSeparator();
117 private String curSourceDBRef;
119 private HashSet<String> curDBRefAccessionIdsString;
121 private enum CoordinateSys
123 UNIPROT("UniProt"), PDB("PDBresnum"), PDBe("PDBe");
126 private CoordinateSys(String name)
131 public String getName()
137 private enum ResidueDetailType
139 NAME_SEC_STRUCTURE("nameSecondaryStructure"),
140 CODE_SEC_STRUCTURE("codeSecondaryStructure"), ANNOTATION("Annotation");
143 private ResidueDetailType(String code)
148 public String getCode()
155 * Fetch SIFTs file for the given PDBfile and construct an instance of
159 * @throws SiftsException
161 public SiftsClient(StructureFile pdb) throws SiftsException
164 this.pdbId = pdb.getId();
165 File siftsFile = getSiftsFile(pdbId);
166 siftsEntry = parseSIFTs(siftsFile);
170 * Parse the given SIFTs File and return a JAXB POJO of parsed data
173 * - the GZipped SIFTs XML file to parse
176 * if a problem occurs while parsing the SIFTs XML
178 private Entry parseSIFTs(File siftFile) throws SiftsException
180 try (InputStream in = new FileInputStream(siftFile);
181 GZIPInputStream gzis = new GZIPInputStream(in);)
183 // System.out.println("File : " + siftFile.getAbsolutePath());
184 JAXBContext jc = JAXBContext.newInstance("jalview.xml.binding.sifts");
185 XMLStreamReader streamReader = XMLInputFactory.newInstance()
186 .createXMLStreamReader(gzis);
187 Unmarshaller um = jc.createUnmarshaller();
188 return (Entry) um.unmarshal(streamReader);
189 } catch (Exception e)
192 throw new SiftsException(e.getMessage());
197 * Get a SIFTs XML file for a given PDB Id from Cache or download from FTP
198 * repository if not found in cache
201 * @return SIFTs XML file
202 * @throws SiftsException
204 public static File getSiftsFile(String pdbId) throws SiftsException
207 * return mocked file if it has been set
209 if (mockSiftsFile != null)
211 return mockSiftsFile;
214 String siftsFileName = SiftsSettings.getSiftDownloadDirectory()
215 + pdbId.toLowerCase() + ".xml.gz";
216 File siftsFile = new File(siftsFileName);
217 if (siftsFile.exists())
219 // The line below is required for unit testing... don't comment it out!!!
220 System.out.println(">>> SIFTS File already downloaded for " + pdbId);
222 if (isFileOlderThanThreshold(siftsFile,
223 SiftsSettings.getCacheThresholdInDays()))
225 File oldSiftsFile = new File(siftsFileName + "_old");
226 siftsFile.renameTo(oldSiftsFile);
229 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
230 oldSiftsFile.delete();
232 } catch (IOException e)
235 oldSiftsFile.renameTo(siftsFile);
236 return new File(siftsFileName);
246 siftsFile = downloadSiftsFile(pdbId.toLowerCase());
247 } catch (IOException e)
249 throw new SiftsException(e.getMessage());
255 * This method enables checking if a cached file has exceeded a certain
261 * the threshold in days
264 public static boolean isFileOlderThanThreshold(File file, int noOfDays)
266 Path filePath = file.toPath();
267 BasicFileAttributes attr;
271 attr = Files.readAttributes(filePath, BasicFileAttributes.class);
272 diffInDays = (int) ((new Date().getTime()
273 - attr.lastModifiedTime().toMillis())
274 / (1000 * 60 * 60 * 24));
275 // System.out.println("Diff in days : " + diffInDays);
276 } catch (IOException e)
280 return noOfDays <= diffInDays;
284 * Download a SIFTs XML file for a given PDB Id from an FTP repository
287 * @return downloaded SIFTs XML file
288 * @throws SiftsException
289 * @throws IOException
291 public static File downloadSiftsFile(String pdbId)
292 throws SiftsException, IOException
294 if (pdbId.contains(".cif"))
296 pdbId = pdbId.replace(".cif", "");
298 String siftFile = pdbId + ".xml.gz";
299 String siftsFileFTPURL = SIFTS_FTP_BASE_URL + siftFile;
300 String downloadedSiftsFile = SiftsSettings.getSiftDownloadDirectory()
302 File siftsDownloadDir = new File(
303 SiftsSettings.getSiftDownloadDirectory());
304 if (!siftsDownloadDir.exists())
306 siftsDownloadDir.mkdirs();
308 // System.out.println(">> Download ftp url : " + siftsFileFTPURL);
309 // long now = System.currentTimeMillis();
310 URL url = new URL(siftsFileFTPURL);
311 URLConnection conn = url.openConnection();
312 InputStream inputStream = conn.getInputStream();
313 FileOutputStream outputStream = new FileOutputStream(
314 downloadedSiftsFile);
315 byte[] buffer = new byte[BUFFER_SIZE];
317 while ((bytesRead = inputStream.read(buffer)) != -1)
319 outputStream.write(buffer, 0, bytesRead);
321 outputStream.close();
323 // System.out.println(">>> File downloaded : " + downloadedSiftsFile
324 // + " took " + (System.currentTimeMillis() - now) + "ms");
325 return new File(downloadedSiftsFile);
329 * Delete the SIFTs file for the given PDB Id in the local SIFTs download
333 * @return true if the file was deleted or doesn't exist
335 public static boolean deleteSiftsFileByPDBId(String pdbId)
337 File siftsFile = new File(SiftsSettings.getSiftDownloadDirectory()
338 + pdbId.toLowerCase() + ".xml.gz");
339 if (siftsFile.exists())
341 return siftsFile.delete();
347 * Get a valid SIFTs DBRef for the given sequence current SIFTs entry
350 * - the target sequence for the operation
351 * @return a valid DBRefEntry that is SIFTs compatible
353 * if no valid source DBRefEntry was found for the given sequences
355 public DBRefEntryI getValidSourceDBRef(SequenceI seq)
356 throws SiftsException
358 List<DBRefEntry> dbRefs = seq.getPrimaryDBRefs();
359 if (dbRefs == null || dbRefs.size() < 1)
361 throw new SiftsException(
362 "Source DBRef could not be determined. DBRefs might not have been retrieved.");
365 for (DBRefEntry dbRef : dbRefs)
367 if (dbRef == null || dbRef.getAccessionId() == null
368 || dbRef.getSource() == null)
372 String canonicalSource = DBRefUtils
373 .getCanonicalName(dbRef.getSource());
374 if (isValidDBRefEntry(dbRef)
375 && (canonicalSource.equalsIgnoreCase(DBRefSource.UNIPROT)
376 || canonicalSource.equalsIgnoreCase(DBRefSource.PDB)))
381 throw new SiftsException("Could not get source DB Ref");
385 * Check that the DBRef Entry is properly populated and is available in this
386 * SiftClient instance
389 * - DBRefEntry to validate
390 * @return true validation is successful otherwise false is returned.
392 boolean isValidDBRefEntry(DBRefEntryI entry)
394 return entry != null && entry.getAccessionId() != null
395 && isFoundInSiftsEntry(entry.getAccessionId());
399 public HashSet<String> getAllMappingAccession()
401 HashSet<String> accessions = new HashSet<String>();
402 List<Entity> entities = siftsEntry.getEntity();
403 for (Entity entity : entities)
405 List<Segment> segments = entity.getSegment();
406 for (Segment segment : segments)
408 List<MapRegion> mapRegions = segment.getListMapRegion()
410 for (MapRegion mapRegion : mapRegions)
413 .add(mapRegion.getDb().getDbAccessionId().toLowerCase());
421 public StructureMapping getSiftsStructureMapping(SequenceI seq,
422 String pdbFile, String chain) throws SiftsException
424 SequenceI aseq = seq;
425 while (seq.getDatasetSequence() != null)
427 seq = seq.getDatasetSequence();
429 structId = (chain == null) ? pdbId : pdbId + "|" + chain;
430 System.out.println("Getting SIFTS mapping for " + structId + ": seq "
433 final StringBuilder mappingDetails = new StringBuilder(128);
434 PrintStream ps = new PrintStream(System.out)
437 public void print(String x)
439 mappingDetails.append(x);
443 public void println()
445 mappingDetails.append(NEWLINE);
448 HashMap<Integer, int[]> mapping = getGreedyMapping(chain, seq, ps);
450 String mappingOutput = mappingDetails.toString();
451 StructureMapping siftsMapping = new StructureMapping(aseq, pdbFile,
452 pdbId, chain, mapping, mappingOutput, seqFromPdbMapping);
458 public HashMap<Integer, int[]> getGreedyMapping(String entityId,
459 SequenceI seq, java.io.PrintStream os) throws SiftsException
461 List<Integer> omitNonObserved = new ArrayList<Integer>();
462 int nonObservedShiftIndex = 0;
463 // System.out.println("Generating mappings for : " + entityId);
464 Entity entity = null;
465 entity = getEntityById(entityId);
466 String originalSeq = AlignSeq.extractGaps(
467 jalview.util.Comparison.GapChars, seq.getSequenceAsString());
468 HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
469 DBRefEntryI sourceDBRef;
470 sourceDBRef = getValidSourceDBRef(seq);
471 // TODO ensure sequence start/end is in the same coordinate system and
472 // consistent with the choosen sourceDBRef
474 // set sequence coordinate system - default value is UniProt
475 if (sourceDBRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
477 seqCoordSys = CoordinateSys.PDB;
480 HashSet<String> dbRefAccessionIdsString = new HashSet<String>();
481 for (DBRefEntry dbref : seq.getDBRefs())
483 dbRefAccessionIdsString.add(dbref.getAccessionId().toLowerCase());
485 dbRefAccessionIdsString.add(sourceDBRef.getAccessionId().toLowerCase());
487 curDBRefAccessionIdsString = dbRefAccessionIdsString;
488 curSourceDBRef = sourceDBRef.getAccessionId();
490 TreeMap<Integer, String> resNumMap = new TreeMap<Integer, String>();
491 List<Segment> segments = entity.getSegment();
492 SegmentHelperPojo shp = new SegmentHelperPojo(seq, mapping, resNumMap,
493 omitNonObserved, nonObservedShiftIndex);
494 processSegments(segments, shp);
497 populateAtomPositions(entityId, mapping);
498 } catch (Exception e)
502 if (seqCoordSys == CoordinateSys.UNIPROT)
504 padWithGaps(resNumMap, omitNonObserved);
506 int seqStart = UNASSIGNED;
507 int seqEnd = UNASSIGNED;
508 int pdbStart = UNASSIGNED;
509 int pdbEnd = UNASSIGNED;
511 if (mapping.isEmpty())
513 throw new SiftsException("SIFTS mapping failed");
515 // also construct a mapping object between the seq-coord sys and the PDB seq's coord sys
517 Integer[] keys = mapping.keySet().toArray(new Integer[0]);
520 seqEnd = keys[keys.length - 1];
521 List<int[]> from=new ArrayList<>(),to=new ArrayList<>();
522 int[]_cfrom=null,_cto=null;
523 String matchedSeq = originalSeq;
524 if (seqStart != UNASSIGNED) // fixme! seqStart can map to -1 for a pdb sequence that starts <-1
528 int pdbpos = mapping.get(seqps)[PDBE_POS];
529 if (pdbpos == UNASSIGNED)
531 // not correct - pdbpos might be -1, but leave it for now
534 if (_cfrom==null || seqps!=_cfrom[1]+1)
536 _cfrom = new int[] { seqps,seqps};
538 _cto = null; // discontinuity
542 if (_cto==null || pdbpos!=1+_cto[1])
544 _cto = new int[] { pdbpos,pdbpos};
550 _cfrom = new int[from.size() * 2];
551 _cto = new int[to.size() * 2];
553 for (int[] range : from)
555 _cfrom[p++] = range[0];
556 _cfrom[p++] = range[1];
560 for (int[] range : to)
562 _cto[p++] = range[0];
563 _cto[p++] = range[1];
567 seqFromPdbMapping = new jalview.datamodel.Mapping(null, _cto, _cfrom,
570 pdbStart = mapping.get(seqStart)[PDB_RES_POS];
571 pdbEnd = mapping.get(seqEnd)[PDB_RES_POS];
572 int orignalSeqStart = seq.getStart();
573 if (orignalSeqStart >= 1)
575 int subSeqStart = (seqStart >= orignalSeqStart)
576 ? seqStart - orignalSeqStart
578 int subSeqEnd = seqEnd - (orignalSeqStart - 1);
579 subSeqEnd = originalSeq.length() < subSeqEnd ? originalSeq.length()
581 matchedSeq = originalSeq.substring(subSeqStart, subSeqEnd);
585 matchedSeq = originalSeq.substring(1, originalSeq.length());
589 StringBuilder targetStrucSeqs = new StringBuilder();
590 for (String res : resNumMap.values())
592 targetStrucSeqs.append(res);
597 MappingOutputPojo mop = new MappingOutputPojo();
598 mop.setSeqStart(seqStart);
599 mop.setSeqEnd(seqEnd);
600 mop.setSeqName(seq.getName());
601 mop.setSeqResidue(matchedSeq);
603 mop.setStrStart(pdbStart);
604 mop.setStrEnd(pdbEnd);
605 mop.setStrName(structId);
606 mop.setStrResidue(targetStrucSeqs.toString());
609 os.print(getMappingOutput(mop).toString());
615 void processSegments(List<Segment> segments, SegmentHelperPojo shp)
617 SequenceI seq = shp.getSeq();
618 HashMap<Integer, int[]> mapping = shp.getMapping();
619 TreeMap<Integer, String> resNumMap = shp.getResNumMap();
620 List<Integer> omitNonObserved = shp.getOmitNonObserved();
621 int nonObservedShiftIndex = shp.getNonObservedShiftIndex();
622 int pdbeNonObservedCount = shp.getPdbeNonObserved();
623 int firstPDBResNum = UNASSIGNED;
624 for (Segment segment : segments)
626 // System.out.println("Mapping segments : " + segment.getSegId() + "\\"s
628 List<Residue> residues = segment.getListResidue().getResidue();
629 for (Residue residue : residues)
631 int pdbeIndex = getLeadingIntegerValue(residue.getDbResNum(),
633 int currSeqIndex = UNASSIGNED;
634 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
635 CrossRefDb pdbRefDb = null;
636 for (CrossRefDb cRefDb : cRefDbs)
638 if (cRefDb.getDbSource().equalsIgnoreCase(DBRefSource.PDB))
642 if (cRefDb.getDbCoordSys().equalsIgnoreCase(seqCoordSys.getName())
643 && isAccessionMatched(cRefDb.getDbAccessionId()))
645 currSeqIndex = getLeadingIntegerValue(cRefDb.getDbResNum(),
647 if (pdbRefDb != null)
649 break;// exit loop if pdb and uniprot are already found
653 if (seqCoordSys == seqCoordSys.PDB) // FIXME: is seqCoordSys ever PDBe
656 // if the sequence has a primary reference to the PDB, then we are
657 // dealing with a sequence extracted directly from the PDB. In that
658 // case, numbering is PDBe - non-observed residues
659 currSeqIndex = pdbeIndex;
661 if (currSeqIndex == UNASSIGNED)
665 if (!isResidueObserved(residue)
666 && seqCoordSys != seqCoordSys.UNIPROT)
668 // mapping to PDB or PDBe so we need to bookkeep for the non-observed
670 omitNonObserved.add(currSeqIndex);
671 ++nonObservedShiftIndex;
674 // if (currSeqIndex >= seq.getStart() && currSeqIndex <= seqlength) //
684 int resNum = (pdbRefDb == null)
685 ? getLeadingIntegerValue(residue.getDbResNum(),
687 : getLeadingIntegerValue(pdbRefDb.getDbResNum(),
690 if (isResidueObserved(residue)
691 || seqCoordSys == CoordinateSys.UNIPROT)
693 char resCharCode = ResidueProperties
694 .getSingleCharacterCode(ResidueProperties
695 .getCanonicalAminoAcid(residue.getDbResName()));
696 resNumMap.put(currSeqIndex, String.valueOf(resCharCode));
699 mapping.put(currSeqIndex - nonObservedShiftIndex,
701 { Integer.valueOf(resNum), UNASSIGNED });
708 * Get the leading integer part of a string that begins with an integer.
711 * - the string input to process
713 * - value returned if unsuccessful
716 static int getLeadingIntegerValue(String input, int failValue)
722 String[] parts = input.split("(?=\\D)(?<=\\d)");
723 if (parts != null && parts.length > 0 && parts[0].matches("[0-9]+"))
725 return Integer.valueOf(parts[0]);
733 * Target chain to populate mapping of its atom positions.
735 * Two dimension array of residue index versus atom position
736 * @throws IllegalArgumentException
737 * Thrown if chainId or mapping is null
738 * @throws SiftsException
740 void populateAtomPositions(String chainId, Map<Integer, int[]> mapping)
741 throws IllegalArgumentException, SiftsException
745 PDBChain chain = pdb.findChain(chainId);
747 if (chain == null || mapping == null)
749 throw new IllegalArgumentException(
750 "Chain id or mapping must not be null.");
752 for (int[] map : mapping.values())
754 if (map[PDB_RES_POS] != UNASSIGNED)
756 map[PDB_ATOM_POS] = getAtomIndex(map[PDB_RES_POS], chain.atoms);
759 } catch (NullPointerException e)
761 throw new SiftsException(e.getMessage());
762 } catch (Exception e)
764 throw new SiftsException(e.getMessage());
770 * @param residueIndex
771 * The residue index used for the search
773 * A collection of Atom to search
774 * @return atom position for the given residue index
776 int getAtomIndex(int residueIndex, Collection<Atom> atoms)
780 throw new IllegalArgumentException(
781 "atoms collection must not be null!");
783 for (Atom atom : atoms)
785 if (atom.resNumber == residueIndex)
787 return atom.atomIndex;
794 * Checks if the residue instance is marked 'Not_observed' or not
799 private boolean isResidueObserved(Residue residue)
801 Set<String> annotations = getResidueAnnotaitons(residue,
802 ResidueDetailType.ANNOTATION);
803 if (annotations == null || annotations.isEmpty())
807 for (String annotation : annotations)
809 if (annotation.equalsIgnoreCase(NOT_OBSERVED))
818 * Get annotation String for a given residue and annotation type
824 private Set<String> getResidueAnnotaitons(Residue residue,
825 ResidueDetailType type)
827 HashSet<String> foundAnnotations = new HashSet<String>();
828 List<ResidueDetail> resDetails = residue.getResidueDetail();
829 for (ResidueDetail resDetail : resDetails)
831 if (resDetail.getProperty().equalsIgnoreCase(type.getCode()))
833 foundAnnotations.add(resDetail.getContent());
836 return foundAnnotations;
840 public boolean isAccessionMatched(String accession)
842 boolean isStrictMatch = true;
843 return isStrictMatch ? curSourceDBRef.equalsIgnoreCase(accession)
844 : curDBRefAccessionIdsString.contains(accession.toLowerCase());
847 private boolean isFoundInSiftsEntry(String accessionId)
849 Set<String> siftsDBRefs = getAllMappingAccession();
850 return accessionId != null
851 && siftsDBRefs.contains(accessionId.toLowerCase());
855 * Pad omitted residue positions in PDB sequence with gaps
859 void padWithGaps(Map<Integer, String> resNumMap,
860 List<Integer> omitNonObserved)
862 if (resNumMap == null || resNumMap.isEmpty())
866 Integer[] keys = resNumMap.keySet().toArray(new Integer[0]);
867 // Arrays.sort(keys);
868 int firstIndex = keys[0];
869 int lastIndex = keys[keys.length - 1];
870 // System.out.println("Min value " + firstIndex);
871 // System.out.println("Max value " + lastIndex);
872 for (int x = firstIndex; x <= lastIndex; x++)
874 if (!resNumMap.containsKey(x) && !omitNonObserved.contains(x))
876 resNumMap.put(x, "-");
882 public Entity getEntityById(String id) throws SiftsException
884 // Determines an entity to process by performing a heuristic matching of all
885 // Entities with the given chainId and choosing the best matching Entity
886 Entity entity = getEntityByMostOptimalMatchedId(id);
891 throw new SiftsException("Entity " + id + " not found");
895 * This method was added because EntityId is NOT always equal to ChainId.
896 * Hence, it provides the logic to greedily detect the "true" Entity for a
897 * given chainId where discrepancies exist.
902 public Entity getEntityByMostOptimalMatchedId(String chainId)
904 // System.out.println("---> advanced greedy entityId matching block
906 List<Entity> entities = siftsEntry.getEntity();
907 SiftsEntitySortPojo[] sPojo = new SiftsEntitySortPojo[entities.size()];
909 for (Entity entity : entities)
911 sPojo[count] = new SiftsEntitySortPojo();
912 sPojo[count].entityId = entity.getEntityId();
914 List<Segment> segments = entity.getSegment();
915 for (Segment segment : segments)
917 List<Residue> residues = segment.getListResidue().getResidue();
918 for (Residue residue : residues)
920 List<CrossRefDb> cRefDbs = residue.getCrossRefDb();
921 for (CrossRefDb cRefDb : cRefDbs)
923 if (!cRefDb.getDbSource().equalsIgnoreCase("PDB"))
927 ++sPojo[count].resCount;
928 if (cRefDb.getDbChainId().equalsIgnoreCase(chainId))
930 ++sPojo[count].chainIdFreq;
935 sPojo[count].pid = (100 * sPojo[count].chainIdFreq)
936 / sPojo[count].resCount;
939 Arrays.sort(sPojo, Collections.reverseOrder());
940 // System.out.println("highest matched entity : " + sPojo[0].entityId);
941 // System.out.println("highest matched pid : " + sPojo[0].pid);
943 if (sPojo[0].entityId != null)
945 if (sPojo[0].pid < 1)
949 for (Entity entity : entities)
951 if (!entity.getEntityId().equalsIgnoreCase(sPojo[0].entityId))
961 private class SiftsEntitySortPojo
962 implements Comparable<SiftsEntitySortPojo>
964 public String entityId;
966 public int chainIdFreq;
973 public int compareTo(SiftsEntitySortPojo o)
975 return this.pid - o.pid;
979 private class SegmentHelperPojo
981 private SequenceI seq;
983 private HashMap<Integer, int[]> mapping;
985 private TreeMap<Integer, String> resNumMap;
987 private List<Integer> omitNonObserved;
989 private int nonObservedShiftIndex;
991 public SegmentHelperPojo(SequenceI seq, HashMap<Integer, int[]> mapping,
992 TreeMap<Integer, String> resNumMap,
993 List<Integer> omitNonObserved, int nonObservedShiftIndex)
997 setResNumMap(resNumMap);
998 setOmitNonObserved(omitNonObserved);
999 setNonObservedShiftIndex(nonObservedShiftIndex);
1002 public SequenceI getSeq()
1007 public void setSeq(SequenceI seq)
1012 public HashMap<Integer, int[]> getMapping()
1017 public void setMapping(HashMap<Integer, int[]> mapping)
1019 this.mapping = mapping;
1022 public TreeMap<Integer, String> getResNumMap()
1027 public void setResNumMap(TreeMap<Integer, String> resNumMap)
1029 this.resNumMap = resNumMap;
1032 public List<Integer> getOmitNonObserved()
1034 return omitNonObserved;
1037 public void setOmitNonObserved(List<Integer> omitNonObserved)
1039 this.omitNonObserved = omitNonObserved;
1042 public int getNonObservedShiftIndex()
1044 return nonObservedShiftIndex;
1047 public void setNonObservedShiftIndex(int nonObservedShiftIndex)
1049 this.nonObservedShiftIndex = nonObservedShiftIndex;
1054 public StringBuilder getMappingOutput(MappingOutputPojo mp)
1055 throws SiftsException
1057 String seqRes = mp.getSeqResidue();
1058 String seqName = mp.getSeqName();
1059 int sStart = mp.getSeqStart();
1060 int sEnd = mp.getSeqEnd();
1062 String strRes = mp.getStrResidue();
1063 String strName = mp.getStrName();
1064 int pdbStart = mp.getStrStart();
1065 int pdbEnd = mp.getStrEnd();
1067 String type = mp.getType();
1069 int maxid = (seqName.length() >= strName.length()) ? seqName.length()
1071 int len = 72 - maxid - 1;
1073 int nochunks = ((seqRes.length()) / len)
1074 + ((seqRes.length()) % len > 0 ? 1 : 0);
1076 StringBuilder output = new StringBuilder(512);
1077 output.append(NEWLINE);
1078 output.append("Sequence \u27f7 Structure mapping details")
1080 output.append("Method: SIFTS");
1081 output.append(NEWLINE).append(NEWLINE);
1083 output.append(new Format("%" + maxid + "s").form(seqName));
1084 output.append(" : ");
1085 output.append(String.valueOf(sStart));
1086 output.append(" - ");
1087 output.append(String.valueOf(sEnd));
1088 output.append(" Maps to ");
1089 output.append(NEWLINE);
1090 output.append(new Format("%" + maxid + "s").form(structId));
1091 output.append(" : ");
1092 output.append(String.valueOf(pdbStart));
1093 output.append(" - ");
1094 output.append(String.valueOf(pdbEnd));
1095 output.append(NEWLINE).append(NEWLINE);
1097 ScoreMatrix pam250 = ScoreModels.getInstance().getPam250();
1098 int matchedSeqCount = 0;
1099 for (int j = 0; j < nochunks; j++)
1101 // Print the first aligned sequence
1102 output.append(new Format("%" + (maxid) + "s").form(seqName))
1105 for (int i = 0; i < len; i++)
1107 if ((i + (j * len)) < seqRes.length())
1109 output.append(seqRes.charAt(i + (j * len)));
1113 output.append(NEWLINE);
1114 output.append(new Format("%" + (maxid) + "s").form(" ")).append(" ");
1117 * Print out the match symbols:
1118 * | for exact match (ignoring case)
1119 * . if PAM250 score is positive
1122 for (int i = 0; i < len; i++)
1126 if ((i + (j * len)) < seqRes.length())
1128 char c1 = seqRes.charAt(i + (j * len));
1129 char c2 = strRes.charAt(i + (j * len));
1130 boolean sameChar = Comparison.isSameResidue(c1, c2, false);
1131 if (sameChar && !Comparison.isGap(c1))
1136 else if (type.equals("pep"))
1138 if (pam250.getPairwiseScore(c1, c2) > 0)
1152 } catch (IndexOutOfBoundsException e)
1157 // Now print the second aligned sequence
1158 output = output.append(NEWLINE);
1159 output = output.append(new Format("%" + (maxid) + "s").form(strName))
1161 for (int i = 0; i < len; i++)
1163 if ((i + (j * len)) < strRes.length())
1165 output.append(strRes.charAt(i + (j * len)));
1168 output.append(NEWLINE).append(NEWLINE);
1170 float pid = (float) matchedSeqCount / seqRes.length() * 100;
1171 if (pid < SiftsSettings.getFailSafePIDThreshold())
1173 throw new SiftsException(">>> Low PID detected for SIFTs mapping...");
1175 output.append("Length of alignment = " + seqRes.length())
1177 output.append(new Format("Percentage ID = %2.2f").form(pid));
1182 public int getEntityCount()
1184 return siftsEntry.getEntity().size();
1188 public String getDbAccessionId()
1190 return siftsEntry.getDbAccessionId();
1194 public String getDbCoordSys()
1196 return siftsEntry.getDbCoordSys();
1200 public String getDbSource()
1202 return siftsEntry.getDbSource();
1206 public String getDbVersion()
1208 return siftsEntry.getDbVersion();
1211 public static void setMockSiftsFile(File file)
1213 mockSiftsFile = file;