use of de.bioforscher.jstructure.align.AlignmentException in project jstructure by JonStargaryen.
the class ContactTogglingReconstruction method computePerformance.
private void computePerformance(List<Chain> reconstructions) throws AlignmentException, IOException {
List<TMAlignAlignmentResult> alignmentResults = new ArrayList<>();
List<ReconstructionContactMap> reconstructionContactMaps = new ArrayList<>();
List<Path> tmpFiles = new ArrayList<>();
for (Chain reconstructedChain : reconstructions) {
Path reconstructPath = Files.createTempFile("confoldservice-recon", ".pdb");
tmpFiles.add(reconstructPath);
Files.write(reconstructPath, reconstructedChain.getPdbRepresentation().getBytes());
alignmentResults.add(TM_ALIGN_SERVICE.process(new String[] { baselineReconstruction.getTmalignPath(), baselineReconstruction.getReferenceChainPath().toFile().getAbsolutePath(), reconstructPath.toFile().getAbsolutePath() }));
reconstructionContactMaps.add(ReconstructionContactMap.createReconstructionContactMap(reconstructedChain, baselineReconstruction.getFullMap().getContactDefinition()));
}
averageRmsd = alignmentResults.stream().map(TMAlignAlignmentResult::getRootMeanSquareDeviation).mapToDouble(RootMeanSquareDeviation::getScore).average().orElseThrow(() -> new ComputationException("could not generate toggled reconstructs"));
averageTmScore = alignmentResults.stream().map(TMAlignAlignmentResult::getTemplateModelingScore1).mapToDouble(TemplateModelingScore::getScore).average().orElseThrow(() -> new ComputationException("could not generate toggled reconstructs"));
averageQ = reconstructionContactMaps.stream().mapToDouble(reconstructContactMap -> BaselineReconstruction.computeQ(baselineReconstruction.getFullMap(), reconstructContactMap)).average().orElseThrow(() -> new ComputationException("could not generate toggled reconstructs"));
logger.info("[{} / {}]: {} reconstruction of contact {}", counter, numberOfCombinations, contactWasRemoved ? "removal" : "addition", contactToToggle);
logger.info("[{} / {}]: average RMSD: {}, average TM-score: {}, average Q: {}", counter, numberOfCombinations, StandardFormat.format(averageRmsd), StandardFormat.format(averageTmScore), StandardFormat.format(averageQ));
if (contactWasRemoved) {
decreaseRmsd = averageRmsd - baselineReconstruction.getAverageRmsd();
increaseTMScore = baselineReconstruction.getAverageTmScore() - averageTmScore;
increaseQ = baselineReconstruction.getAverageQ() - averageQ;
} else {
decreaseRmsd = baselineReconstruction.getAverageRmsd() - averageRmsd;
increaseTMScore = averageTmScore - baselineReconstruction.getAverageTmScore();
increaseQ = averageQ - baselineReconstruction.getAverageQ();
}
logger.info("[{} / {}]: decrease RMSD: {}, increase TM-score: {}, increase Q: {}", counter, numberOfCombinations, StandardFormat.format(decreaseRmsd), StandardFormat.format(increaseTMScore), StandardFormat.format(increaseQ));
// cleanup
for (Path tmpFile : tmpFiles) {
Files.delete(tmpFile);
}
}
use of de.bioforscher.jstructure.align.AlignmentException in project jstructure by JonStargaryen.
the class TMAlignService method process.
public TMAlignAlignmentResult process(StructureAlignmentQuery structureAlignmentQuery) throws AlignmentException {
try {
Path referencePath = writeStructureToTemporaryFile(structureAlignmentQuery.getReference());
Path queryPath = writeStructureToTemporaryFile(structureAlignmentQuery.getQuery());
String[] arguments = new String[] { getServiceLocation(), referencePath.toFile().toString(), queryPath.toFile().toString() };
TMAlignAlignmentResult result = process(arguments);
Files.delete(referencePath);
Files.delete(queryPath);
return result;
} catch (IOException e) {
throw new AlignmentException("could not run tmalign", e);
}
}
use of de.bioforscher.jstructure.align.AlignmentException in project jstructure by JonStargaryen.
the class A03_ReconstructByVariousStrategy method handleChain.
private static void handleChain(ExplorerChain explorerChain) {
logger.info("[{}] starting job", explorerChain.getStfId());
try {
Chain nativeChain = explorerChain.getChain();
Path nativeChainPath = Files.createTempFile("nativechain-", ".pdb");
Files.write(nativeChainPath, nativeChain.getPdbRepresentation().getBytes());
List<ContactStructuralInformation> contactStructuralInformation = explorerChain.getContacts();
// annotate with PLIP data
PLIPInteractionContainer plipInteractionContainer = nativeChain.getFeature(PLIPInteractionContainer.class);
for (ContactStructuralInformation csi : contactStructuralInformation) {
AminoAcid aminoAcid1 = nativeChain.select().residueNumber(csi.getResidueIdentifier1()).asAminoAcid();
AminoAcid aminoAcid2 = nativeChain.select().residueNumber(csi.getResidueIdentifier2()).asAminoAcid();
if (plipInteractionContainer.getHydrogenBonds().stream().anyMatch(hydrogenBond -> isContact(hydrogenBond, aminoAcid1, aminoAcid2))) {
csi.markAsHydrogenBond();
}
if (plipInteractionContainer.getHydrophobicInteractions().stream().anyMatch(hydrophobicInteraction -> isContact(hydrophobicInteraction, aminoAcid1, aminoAcid2))) {
csi.markAsHydrophobicInteraction();
}
}
int numberOfNativeContacts = contactStructuralInformation.size();
int numberOfContactsToSelect = (int) (numberOfNativeContacts * DEFAULT_COVERAGE);
List<ReconstructionContactMap> contactMaps = Stream.of(ReconstructionStrategyDefinition.values()).map(ReconstructionStrategyDefinition::getReconstructionStrategy).flatMap(reconstructionStrategy -> IntStream.range(0, REDUNDANCY).boxed().flatMap(i -> {
if (!reconstructionStrategy.isNegatable()) {
ReconstructionContactMap contactMap = reconstructionStrategy.composeReconstructionContactMap(nativeChain, contactStructuralInformation, numberOfContactsToSelect);
contactMap.setName(reconstructionStrategy.getName() + "-" + (i + 1));
return Stream.of(contactMap);
} else {
// short, long, hydrogen, and hydrophobic bins have to be negated explicitly to get comparable results
Pair<ReconstructionContactMap, ReconstructionContactMap> contactMapPair = reconstructionStrategy.composeReconstructionAndNegatedReconstructionContactMap(nativeChain, contactStructuralInformation, numberOfContactsToSelect);
contactMapPair.getLeft().setName(reconstructionStrategy.getName() + "-" + (i + 1));
contactMapPair.getRight().setName(reconstructionStrategy.getNegatedName() + "-" + (i + 1));
return Stream.of(contactMapPair.getLeft(), contactMapPair.getRight());
}
})).filter(reconstructionContactMap -> reconstructionContactMap.getNumberOfContacts() > 0).collect(Collectors.toList());
Map<String, List<Future<ReconstructionResult>>> reconstructionFutures = new HashMap<>();
for (ReconstructionContactMap contactMap : contactMaps) {
String name = contactMap.getName().split("-")[0];
logger.info("[{}] handling contact map definition {}", explorerChain.getStfId(), name);
if (!reconstructionFutures.containsKey(name)) {
reconstructionFutures.put(name, new ArrayList<>());
}
List<Future<ReconstructionResult>> bin = reconstructionFutures.get(name);
bin.add(executorService.submit(new ConfoldServiceWorker("/home/sb/programs/confold_v1.0/confold.pl", contactMap.getSequence(), contactMap.getSecondaryStructureElements(), contactMap.getCaspRRRepresentation(), contactMap.getConfoldRRType())));
}
for (Map.Entry<String, List<Future<ReconstructionResult>>> reconstructionFuture : reconstructionFutures.entrySet()) {
try {
String name = reconstructionFuture.getKey();
List<Chain> reconstructions = reconstructionFuture.getValue().stream().map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new ComputationException(e);
}
}).map(ReconstructionResult::getChains).flatMap(Collection::stream).collect(Collectors.toList());
logger.info("[{}][{}] {} reconstructs in bin", explorerChain.getStfId(), name, reconstructions.size());
List<TMAlignAlignmentResult> alignmentResults = new ArrayList<>();
List<Path> tmpFiles = new ArrayList<>();
if (reconstructions.isEmpty()) {
throw new ComputationException("reconstruction did not yield any reconstructs");
}
for (Chain reconstructedChain : reconstructions) {
Path reconstructPath = Files.createTempFile("confoldservice-recon", ".pdb");
tmpFiles.add(reconstructPath);
Files.write(reconstructPath, reconstructedChain.getPdbRepresentation().getBytes());
alignmentResults.add(TM_ALIGN_SERVICE.process(new String[] { "/home/sb/programs/tmalign", nativeChainPath.toFile().getAbsolutePath(), reconstructPath.toFile().getAbsolutePath() }));
}
logger.info("[{}][{}] {} alignments in bin", explorerChain.getStfId(), name, alignmentResults.size());
if (alignmentResults.isEmpty()) {
throw new ComputationException("tmalign did not yield any alignments");
}
for (TMAlignAlignmentResult alignmentResult : alignmentResults) {
double rmsd = alignmentResult.getRootMeanSquareDeviation().getScore();
String line = explorerChain.getStfId() + "," + name + "," + rmsd;
logger.info("[{}][{}] {}", explorerChain.getStfId(), name, line);
fileWriter.write(line + System.lineSeparator());
fileWriter.flush();
}
// cleanup
for (Path tmpFile : tmpFiles) {
Files.delete(tmpFile);
}
} catch (IOException e) {
throw new ComputationException(e);
}
}
} catch (IOException | AlignmentException e) {
throw new ComputationException(e);
}
}
use of de.bioforscher.jstructure.align.AlignmentException in project jstructure by JonStargaryen.
the class A04_CreateRmsdVsCoveragePlot method handleChain.
private static void handleChain(ExplorerChain explorerChain) {
logger.info("handling chain {}", explorerChain.getStfId());
try {
Chain nativeChain = explorerChain.getChain();
Path nativeChainPath = Files.createTempFile("nativechain-", ".pdb");
Files.write(nativeChainPath, nativeChain.getPdbRepresentation().getBytes());
ReconstructionContactMap nativeContactMap = ReconstructionContactMap.createReconstructionContactMap(nativeChain, ContactDefinitionFactory.createAlphaCarbonContactDefinition(8.0));
List<AminoAcid> aminoAcids = nativeChain.getAminoAcids();
List<Pair<AminoAcid, AminoAcid>> contacts = nativeContactMap.getLongRangeContacts();
int numberNativeLongRangeContacts = contacts.size();
List<ReconstructionContactMap> reconstructionContactMaps = new ArrayList<>();
for (int coverage = 5; coverage <= 100; coverage = coverage + 5) {
int numberOfContactsToSelect = (int) Math.round(0.01 * coverage * numberNativeLongRangeContacts);
for (int run = 0; run < REDUNDANCY; run++) {
Collections.shuffle(contacts);
List<Pair<AminoAcid, AminoAcid>> selectedContacts = contacts.subList(0, numberOfContactsToSelect);
ReconstructionContactMap contactMap = new ReconstructionContactMap(aminoAcids, selectedContacts, nativeContactMap.getContactDefinition());
contactMap.setName("p" + coverage + "-" + (run + 1));
reconstructionContactMaps.add(contactMap);
}
}
Map<String, List<Future<ReconstructionResult>>> reconstructionFutures = new HashMap<>();
for (ReconstructionContactMap contactMap : reconstructionContactMaps) {
String name = contactMap.getName().split("-")[0];
logger.info("handling contact map with coverage {}", name);
if (!reconstructionFutures.containsKey(name)) {
reconstructionFutures.put(name, new ArrayList<>());
}
List<Future<ReconstructionResult>> bin = reconstructionFutures.get(name);
bin.add(executorService.submit(new ConfoldServiceWorker("/home/sb/programs/confold_v1.0/confold.pl", contactMap.getSequence(), contactMap.getSecondaryStructureElements(), contactMap.getCaspRRRepresentation(), nativeContactMap.getConfoldRRType())));
}
for (Map.Entry<String, List<Future<ReconstructionResult>>> reconstructionFuture : reconstructionFutures.entrySet()) {
try {
String name = reconstructionFuture.getKey();
List<Chain> reconstructions = reconstructionFuture.getValue().stream().map(future -> {
try {
return future.get();
} catch (Exception e) {
throw new ComputationException(e);
}
}).map(ReconstructionResult::getChains).flatMap(Collection::stream).collect(Collectors.toList());
List<TMAlignAlignmentResult> alignmentResults = new ArrayList<>();
List<Path> tmpFiles = new ArrayList<>();
for (Chain reconstructedChain : reconstructions) {
Path reconstructPath = Files.createTempFile("confoldservice-recon", ".pdb");
tmpFiles.add(reconstructPath);
Files.write(reconstructPath, reconstructedChain.getPdbRepresentation().getBytes());
alignmentResults.add(TM_ALIGN_SERVICE.process(new String[] { "/home/sb/programs/tmalign", nativeChainPath.toFile().getAbsolutePath(), reconstructPath.toFile().getAbsolutePath() }));
}
if (alignmentResults.isEmpty()) {
throw new ComputationException("tmalign did not yield any alignments");
}
for (TMAlignAlignmentResult alignmentResult : alignmentResults) {
double rmsd = alignmentResult.getRootMeanSquareDeviation().getScore();
String line = explorerChain.getStfId() + "," + name.replace("p", "") + "," + rmsd;
logger.info(line);
fileWriter.write(line + System.lineSeparator());
fileWriter.flush();
}
// cleanup
for (Path tmpFile : tmpFiles) {
Files.delete(tmpFile);
}
} catch (IOException e) {
throw new ComputationException(e);
}
}
} catch (IOException | AlignmentException e) {
throw new ComputationException(e);
}
}
use of de.bioforscher.jstructure.align.AlignmentException in project jstructure by JonStargaryen.
the class TMAlignService method process.
private synchronized TMAlignAlignmentResult process(String[] arguments, int run) throws AlignmentException {
try {
logger.debug("spawning tmalign process with arguments:{}{}", System.lineSeparator(), arguments);
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
Process process = processBuilder.start();
List<String> outputLines;
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
outputLines = br.lines().collect(Collectors.toList());
}
List<String> errorLines;
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
errorLines = br.lines().collect(Collectors.toList());
}
process.waitFor();
if (outputLines.stream().anyMatch(line -> line.startsWith("Can not open file:"))) {
throw new ComputationException("error during tmalign execution:" + System.lineSeparator() + outputLines.stream().collect(Collectors.joining(System.lineSeparator())));
}
// errors are not reported in error stream
if (!errorLines.isEmpty()) {
throw new ComputationException("error during tmalign execution:" + System.lineSeparator() + errorLines.stream().collect(Collectors.joining(System.lineSeparator())));
}
int length1 = 0;
int length2 = 0;
int alignedLength = 0;
RootMeanSquareDeviation rootMeanSquareDeviation = null;
double seqId = 0;
TemplateModelingScore templateModelingScore1 = null;
TemplateModelingScore templateModelingScore2 = null;
for (String outputLine : outputLines) {
if (outputLine.startsWith("Length of Chain_1")) {
length1 = Integer.valueOf(outputLine.split(":")[1].trim().split("\\s+")[0]);
} else if (outputLine.startsWith("Length of Chain_2")) {
length2 = Integer.valueOf(outputLine.split(":")[1].trim().split("\\s+")[0]);
} else if (outputLine.startsWith("Aligned length")) {
String[] split = outputLine.split("=");
alignedLength = Integer.valueOf(split[1].split(",")[0].trim());
rootMeanSquareDeviation = new RootMeanSquareDeviation(Double.valueOf(split[2].split(",")[0].trim()));
seqId = Double.valueOf(split[4].trim());
} else if (outputLine.startsWith("TM-score")) {
double tmscore = Double.valueOf(outputLine.split("=")[1].split("\\(")[0].trim());
TemplateModelingScore templateModelingScore = new TemplateModelingScore(tmscore);
if (outputLine.contains("Chain_1")) {
templateModelingScore1 = templateModelingScore;
} else {
templateModelingScore2 = templateModelingScore;
}
}
}
return new TMAlignAlignmentResult(length1, length2, alignedLength, rootMeanSquareDeviation, seqId, templateModelingScore1, templateModelingScore2);
} catch (Exception e) {
if (run > 3) {
logger.warn("tmalign computation finally failed:{}{}", System.lineSeparator(), Arrays.toString(arguments), e);
throw new AlignmentException("could not run tmalign", e);
}
return process(arguments, run + 1);
}
}
Aggregations