use of ffx.potential.parsers.PDBFilter in project ffx by mjschnie.
the class MainPanel method savePDBSymMates.
public void savePDBSymMates(File file, String suffix) {
FFXSystem system = hierarchy.getActive();
if (system == null) {
logger.log(Level.INFO, " No active system to save.");
return;
}
if (system.isClosing()) {
logger.log(Level.INFO, " {0} is being closed and can no longer be saved.", system);
return;
}
File saveFile = file;
if (saveFile == null) {
resetFileChooser();
fileChooser.setCurrentDirectory(pwd);
fileChooser.setFileFilter(pdbFileFilter);
fileChooser.setAcceptAllFileFilterUsed(false);
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
saveFile = fileChooser.getSelectedFile();
pwd = saveFile.getParentFile();
}
}
if (saveFile == null) {
logger.log(Level.INFO, " No filename is defined for {0}.", system);
return;
}
String filename = FilenameUtils.removeExtension(file.getName());
PDBFilter pdbFilter = new PDBFilter(saveFile, system, null, null);
if (pdbFilter.writeFile(saveFile, false)) {
// Refresh Panels with the new System name
hierarchy.setActive(system);
activeFilter = pdbFilter;
} else {
logger.log(Level.INFO, " Save failed for: {0}", system);
}
Crystal crystal = system.getCrystal();
int nSymOps = crystal.spaceGroup.getNumberOfSymOps();
logger.info(String.format(" Writing %d symmetry mates for %s", nSymOps, system.toString()));
for (int i = 1; i < nSymOps; i++) {
pdbFilter.setSymOp(i);
String saveFileName = filename + suffix + "_" + i + ".pdb";
saveFile = new File(saveFileName);
for (int j = 1; j < 1000; j++) {
if (!saveFile.exists()) {
break;
}
saveFile = new File(saveFileName + "_" + j);
}
StringBuilder symSb = new StringBuilder();
String[] symopLines = crystal.spaceGroup.getSymOp(i).toString().split("\\r?\\n");
int nLines = symopLines.length;
symSb.append("REMARK 350\nREMARK 350 SYMMETRY OPERATORS");
for (int j = 0; j < nLines; j++) {
symSb.append("\nREMARK 350 ").append(symopLines[j]);
}
symopLines = crystal.spaceGroup.getSymOp(i).toXYZString().split("\\r?\\n");
nLines = symopLines.length;
symSb.append("\nREMARK 350\nREMARK 350 SYMMETRY OPERATORS XYZ FORM");
for (int j = 0; j < nLines; j++) {
symSb.append("\nREMARK 350 ").append(symopLines[j]);
}
if (saveFile.exists()) {
logger.warning(String.format(" Could not successfully version file " + "%s: appending to file %s", saveFileName, saveFile.getName()));
if (!pdbFilter.writeFileWithHeader(saveFile, symSb.toString(), true)) {
logger.log(Level.INFO, " Save failed for: {0}", system);
}
} else {
if (!pdbFilter.writeFileWithHeader(saveFile, symSb.toString(), false)) {
logger.log(Level.INFO, " Save failed for: {0}", system);
}
}
}
}
use of ffx.potential.parsers.PDBFilter in project ffx by mjschnie.
the class PotentialsUtils method saveAsPDB.
/**
* Saves the current state of an array of MolecularAssemblys to a PDB file.
*
* @param assemblies MolecularAssembly array to save
* @param file Destination .pdb
*/
@Override
public void saveAsPDB(MolecularAssembly[] assemblies, File file) {
if (assemblies == null) {
logger.info(" Null array of molecular assemblies to write.");
} else if (assemblies.length == 0) {
logger.info(" Zero-length array of molecular assemblies to write.");
} else if (file == null) {
logger.info(" No valid file to write to.");
} else {
PDBFilter pdbFilter = new PDBFilter(file, Arrays.asList(assemblies), null, null);
pdbFilter.writeFile(file, false);
lastFilter = pdbFilter;
}
}
use of ffx.potential.parsers.PDBFilter in project ffx by mjschnie.
the class PotentialsUtils method saveAsSIFTPDB.
public void saveAsSIFTPDB(MolecularAssembly assembly, File file, String[] resAndScore) {
if (assembly == null) {
logger.info(" Assembly to save was null.");
} else if (file == null) {
logger.info(" No valid file provided to save assembly to.");
} else if (resAndScore == null) {
logger.info(" Res and score array was null.");
} else {
PDBFilter pdbFilter = new PDBFilter(file, assembly, null, null);
if (!pdbFilter.writeSIFTFile(file, false, resAndScore)) {
logger.info(String.format(" Save failed for %s", assembly.toString()));
}
lastFilter = pdbFilter;
}
}
use of ffx.potential.parsers.PDBFilter in project ffx by mjschnie.
the class RotamerOptimization method slidingWindowOptimization.
private double slidingWindowOptimization(ArrayList<Residue> residueList, int windowSize, int increment, boolean revert, double distance, Direction direction) {
long beginTime = -System.nanoTime();
boolean incrementTruncated = false;
boolean firstWindowSaved = false;
int counter = 1;
int windowEnd;
int nOptimize = residueList.size();
if (nOptimize < windowSize) {
windowSize = nOptimize;
logger.info(" Window size too small for given residue range; truncating window size.");
}
switch(direction) {
case BACKWARD:
ArrayList<Residue> temp = new ArrayList<>();
for (int i = nOptimize - 1; i >= 0; i--) {
temp.add(residueList.get(i));
}
residueList = temp;
// Fall through into the FORWARD case.
case FORWARD:
for (int windowStart = 0; windowStart + (windowSize - 1) < nOptimize; windowStart += increment) {
long windowTime = -System.nanoTime();
windowEnd = windowStart + (windowSize - 1);
logIfMaster(format("\n Iteration %d of the sliding window.\n", counter++));
Residue firstResidue = residueList.get(windowStart);
Residue lastResidue = residueList.get(windowEnd);
if (firstResidue != lastResidue) {
logIfMaster(format(" Residues %s ... %s", firstResidue.toString(), lastResidue.toString()));
} else {
logIfMaster(format(" Residue %s", firstResidue.toString()));
}
ArrayList<Residue> currentWindow = new ArrayList<>();
// Not filled if useForcedResidues == false.
ArrayList<Residue> onlyRotameric = new ArrayList<>();
for (int i = windowStart; i <= windowEnd; i++) {
Residue residue = residueList.get(i);
if (useForcedResidues && residue.getRotamers(library) != null) {
onlyRotameric.add(residue);
}
currentWindow.add(residueList.get(i));
}
if (distance > 0) {
for (int i = windowStart; i <= windowEnd; i++) {
Residue residuei = residueList.get(i);
int indexI = allResiduesList.indexOf(residuei);
int lengthRi;
if (checkIfForced(residuei)) {
lengthRi = 1;
} else {
lengthRi = residuei.getRotamers(library).length;
}
for (int ri = 0; ri < lengthRi; ri++) {
for (int j = 0; j < numResidues; j++) {
Residue residuej = allResiduesArray[j];
Rotamer[] rotamersj = residuej.getRotamers(library);
if (currentWindow.contains(residuej) || rotamersj == null) {
continue;
}
int lengthRj = rotamersj.length;
for (int rj = 0; rj < lengthRj; rj++) {
double rotamerSeparation = get2BodyDistance(indexI, ri, j, rj);
// if (distanceMatrix[indexI][ri][j][rj] <= distance) {
if (rotamerSeparation <= distance) {
if (!currentWindow.contains(residuej)) {
logIfMaster(format(" Adding residue %s at distance %16.8f Ang from %s %d.", residuej.toFormattedString(false, true), rotamerSeparation, residuei.toFormattedString(false, true), ri));
currentWindow.add(residuej);
if (useForcedResidues) {
onlyRotameric.add(residuej);
}
}
break;
}
}
}
}
}
}
/**
* If the window starts with a nucleic acid, and there is a
* 5' NA residue, ensure that 5' NA residue has been
* included in the window. Otherwise, that previous residue
* may not have had a chance to be flexible about its sugar
* pucker.
*
* If window size is greater than increment, however, this
* has already been handled. Additionally, do not perform
* this for the first window (counter is already incremented
* by the time this check is performed, so first window's
* counter will be 2). Furthermore, do not include Residues
* with null Rotamer lists (this breaks things).
*
* The issue: if window size = increment, the last NA
* residue in each window will not have flexibility about
* its sugar pucker, because its self-energy includes the
* O3' (i) to P (i+1) bond, so it must remain in the
* original sugar pucker to meet the i+1 residue. However,
* this problem can be solved by ensuring that final residue
* is included in the next window, where it will have
* flexibility about its sugar pucker.
*
* If you are running successive sliding window jobs on the
* same file, I would suggest starting the next job on the
* last residue of the previous job, unless you know your
* settings will include it.
*/
if (counter > 2 && windowSize <= increment && firstResidue.getResidueType() == NA) {
Residue prevResidue = firstResidue.getPreviousResidue();
if (prevResidue != null && prevResidue.getResidueType() == NA && !currentWindow.contains(prevResidue) && prevResidue.getRotamers(library) != null) {
logIfMaster(format(" Adding nucleic acid residue 5' of window start %s to give it flexibility about its sugar pucker.", prevResidue.toString()));
currentWindow.add(prevResidue);
if (useForcedResidues) {
onlyRotameric.add(prevResidue);
}
}
}
if (useForcedResidues) {
sortResidues(onlyRotameric);
} else {
sortResidues(currentWindow);
}
if (revert) {
ResidueState[] coordinates = ResidueState.storeAllCoordinates(currentWindow);
// If x has not yet been constructed, construct it.
if (x == null) {
Atom[] atoms = molecularAssembly.getAtomArray();
int nAtoms = atoms.length;
x = new double[nAtoms * 3];
}
double startingEnergy = Double.NaN;
try {
startingEnergy = currentEnergy(currentWindow);
} catch (ArithmeticException ex) {
logger.severe(String.format(" Exception %s in calculating starting energy of a window; FFX shutting down", ex.toString()));
}
if (useForcedResidues) {
if (onlyRotameric.size() < 1) {
logger.info(" Window has no rotameric residues.");
ResidueState.revertAllCoordinates(currentWindow, coordinates);
} else {
globalOptimization(onlyRotameric);
double finalEnergy = Double.NaN;
try {
finalEnergy = currentEnergy(currentWindow);
} catch (ArithmeticException ex) {
logger.severe(String.format(" Exception %s in calculating final energy of a window; FFX shutting down", ex.toString()));
}
if (startingEnergy <= finalEnergy) {
logger.warning("Optimization did not yield a better energy. Reverting to orginal coordinates.");
ResidueState.revertAllCoordinates(currentWindow, coordinates);
}
}
} else {
globalOptimization(currentWindow);
double finalEnergy = Double.NaN;
try {
finalEnergy = currentEnergy(currentWindow);
} catch (ArithmeticException ex) {
logger.severe(String.format(" Exception %s in calculating final energy of a window; FFX shutting down", ex.toString()));
}
if (startingEnergy <= finalEnergy) {
logger.warning("Optimization did not yield a better energy. Reverting to orginal coordinates.");
ResidueState.revertAllCoordinates(currentWindow, coordinates);
}
}
} else if (useForcedResidues) {
if (onlyRotameric.size() < 1) {
logger.info(" Window has no rotameric residues.");
} else {
globalOptimization(onlyRotameric);
}
} else {
globalOptimization(currentWindow);
}
if (!incrementTruncated) {
if (windowStart + (windowSize - 1) + increment > nOptimize - 1) {
increment = nOptimize - windowStart - windowSize;
if (increment == 0) {
break;
}
logger.warning(" Increment truncated in order to optimize entire residue range.");
incrementTruncated = true;
}
}
if (master && printFiles) {
File file = molecularAssembly.getFile();
if (firstWindowSaved) {
file.delete();
}
// Don't write a file if its the final iteration.
if (windowStart + windowSize == nOptimize) {
continue;
}
// String filename = FilenameUtils.removeExtension(file.getAbsolutePath());
// File tempFile = new File(filename + ".win");
// PDBFilter windowFilter = new PDBFilter(new File(filename + ".win"), molecularAssembly, null, null);
PDBFilter windowFilter = new PDBFilter(file, molecularAssembly, null, null);
// StringBuilder header = new StringBuilder(format("Iteration %d of the sliding window\n", counter - 1));
try {
windowFilter.writeFile(file, false);
if (firstResidue != lastResidue) {
logger.info(format(" File with residues %s ... %s in window written to.", firstResidue.toString(), lastResidue.toString()));
} else {
logger.info(format(" File with residue %s in window written to.", firstResidue.toString()));
}
} catch (Exception e) {
logger.warning(format("Exception writing to file: %s", file.getName()));
}
firstWindowSaved = true;
}
long currentTime = System.nanoTime();
windowTime += currentTime;
logIfMaster(format(" Time elapsed for this iteration: %11.3f sec", windowTime * 1.0E-9));
logIfMaster(format(" Overall time elapsed: %11.3f sec", (currentTime + beginTime) * 1.0E-9));
/*for (Residue residue : residueList) {
if (residue instanceof MultiResidue) {
((MultiResidue) residue).setDefaultResidue();
residue.reInitOriginalAtomList();
}
}*/
}
break;
default:
// No default case.
break;
}
return 0.0;
}
use of ffx.potential.parsers.PDBFilter in project ffx by mjschnie.
the class RotamerOptimization method boxOptimization.
/**
* Breaks down a structure into a number of overlapping boxes for
* optimization.
*
* @return Potential energy of final structure.
*/
private double boxOptimization(ArrayList<Residue> residueList) {
this.usingBoxOptimization = true;
long beginTime = -System.nanoTime();
Residue[] residues = residueList.toArray(new Residue[residueList.size()]);
boolean firstCellSaved = false;
/*
* A new dummy Crystal will be constructed for an aperiodic system. The
* purpose is to avoid using the overly large dummy Crystal used for
* Ewald purposes. Atoms are not and should not be moved into the dummy
* Crystal boundaries; to check if an Atom is inside a cell, use an
* array of coordinates adjusted to be 0 < coordinate < 1.0.
*/
Crystal crystal = generateSuperbox(residueList);
// Cells indexed by x*(YZ divisions) + y*(Z divisions) + z.
// Also initializes cell count if using -bB
int totalCells = getTotalCellCount(crystal);
if (boxStart > totalCells - 1) {
logger.severe(format(" FFX shutting down: Box optimization start is out of range of total boxes: %d > %d", (boxStart + 1), totalCells));
}
if (boxEnd > totalCells - 1) {
boxEnd = totalCells - 1;
logIfMaster(" Final box out of range: reset to last possible box.");
} else if (boxEnd < 0) {
boxEnd = totalCells - 1;
}
BoxOptCell[] cells = loadCells(crystal, residues);
int numCells = cells.length;
logIfMaster(format(" Optimizing boxes %d to %d", (boxStart + 1), (boxEnd + 1)));
for (int i = 0; i < numCells; i++) {
BoxOptCell celli = cells[i];
ArrayList<Residue> residuesList = celli.getResiduesAsList();
int[] cellIndices = celli.getXYZIndex();
logIfMaster(format("\n Iteration %d of the box optimization.", (i + 1)));
logIfMaster(format(" Cell index (linear): %d", (celli.getLinearIndex() + 1)));
logIfMaster(format(" Cell xyz indices: x = %d, y = %d, z = %d", cellIndices[0] + 1, cellIndices[1] + 1, cellIndices[2] + 1));
int nResidues = residuesList.size();
if (nResidues > 0) {
readyForSingles = false;
finishedSelf = false;
readyFor2Body = false;
finished2Body = false;
readyFor3Body = false;
finished3Body = false;
energiesToWrite = Collections.synchronizedList(new ArrayList<String>());
receiveThread = new ReceiveThread(residuesList.toArray(new Residue[1]));
receiveThread.start();
if (master && writeEnergyRestart && printFiles) {
if (energyWriterThread != null) {
int waiting = 0;
while (energyWriterThread.getState() != java.lang.Thread.State.TERMINATED) {
try {
if (waiting++ > 20) {
logger.log(Level.SEVERE, " ReceiveThread/EnergyWriterThread from previous box locked up.");
}
logIfMaster(" Waiting for previous iteration's communication threads to shut down... ");
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
}
}
energyWriterThread = new EnergyWriterThread(receiveThread, i + 1, cellIndices);
energyWriterThread.start();
}
if (loadEnergyRestart) {
boxLoadIndex = i + 1;
boxLoadCellIndices = new int[3];
boxLoadCellIndices[0] = cellIndices[0];
boxLoadCellIndices[1] = cellIndices[1];
boxLoadCellIndices[2] = cellIndices[2];
}
long boxTime = -System.nanoTime();
Residue firstResidue = residuesList.get(0);
Residue lastResidue = residuesList.get(nResidues - 1);
if (firstResidue != lastResidue) {
logIfMaster(format(" Residues %s ... %s", firstResidue.toString(), lastResidue.toString()));
} else {
logIfMaster(format(" Residue %s", firstResidue.toString()));
}
if (revert) {
ResidueState[] coordinates = ResidueState.storeAllCoordinates(residuesList);
// If x has not yet been constructed, construct it.
if (x == null) {
Atom[] atoms = molecularAssembly.getAtomArray();
int nAtoms = atoms.length;
x = new double[nAtoms * 3];
}
double startingEnergy = 0;
double finalEnergy = 0;
try {
startingEnergy = currentEnergy(residuesList);
} catch (ArithmeticException ex) {
logger.severe(String.format(" Exception %s in calculating starting energy of a box; FFX shutting down", ex.toString()));
}
globalOptimization(residuesList);
try {
finalEnergy = currentEnergy(residuesList);
} catch (ArithmeticException ex) {
logger.severe(String.format(" Exception %s in calculating starting energy of a box; FFX shutting down", ex.toString()));
}
if (startingEnergy <= finalEnergy) {
logger.warning("Optimization did not yield a better energy. Reverting to orginal coordinates.");
ResidueState.revertAllCoordinates(residuesList, coordinates);
}
long currentTime = System.nanoTime();
boxTime += currentTime;
logIfMaster(format(" Time elapsed for this iteration: %11.3f sec", boxTime * 1.0E-9));
logIfMaster(format(" Overall time elapsed: %11.3f sec", (currentTime + beginTime) * 1.0E-9));
} else {
globalOptimization(residuesList);
long currentTime = System.nanoTime();
boxTime += currentTime;
logIfMaster(format(" Time elapsed for this iteration: %11.3f sec", boxTime * 1.0E-9));
logIfMaster(format(" Overall time elapsed: %11.3f sec", (currentTime + beginTime) * 1.0E-9));
}
if (master && printFiles) {
String filename = FilenameUtils.removeExtension(molecularAssembly.getFile().getAbsolutePath()) + ".partial";
File file = new File(filename);
if (firstCellSaved) {
file.delete();
}
// Don't write a file if it's the final iteration.
if (i == (numCells - 1)) {
continue;
}
PDBFilter windowFilter = new PDBFilter(file, molecularAssembly, null, null);
try {
windowFilter.writeFile(file, false);
if (firstResidue != lastResidue) {
logIfMaster(format(" File with residues %s ... %s in window written.", firstResidue.toString(), lastResidue.toString()));
} else {
logIfMaster(format(" File with residue %s in window written.", firstResidue.toString()));
}
firstCellSaved = true;
} catch (Exception e) {
logger.warning(format("Exception writing to file: %s", file.getName()));
}
}
/*for (Residue residue : residueList) {
if (residue instanceof MultiResidue) {
((MultiResidue) residue).setDefaultResidue();
residue.reInitOriginalAtomList();
}
}*/
} else {
logIfMaster(format(" Empty box: no residues found."));
}
}
return 0.0;
}
Aggregations