Search in sources :

Example 1 with DoubleIndexPair

use of ffx.utilities.DoubleIndexPair in project ffx by mjschnie.

the class Rescore method rescore.

public File[] rescore(File[] modelFiles) {
    int numFiles = modelFiles.length;
    DoubleIndexPair[] energies = new DoubleIndexPair[numFiles];
    File[] rescoredFiles = new File[numFiles];
    for (int i = 0; i < numFiles; i++) {
        rescoredFiles[i] = rescoreSingle(modelFiles[i], rscType, energies, i);
    }
    Arrays.sort(energies);
    ArrayList<Integer> acceptedFileIndices = new ArrayList<>();
    int numAccepted = 1;
    acceptedFileIndices.add(energies[0].getIndex());
    double minEnergy = energies[0].getDoubleValue();
    if (acceptThreshold > 0.0) {
        for (int i = 1; i < numFiles; i++) {
            DoubleIndexPair currentPair = energies[i];
            double e = currentPair.getDoubleValue();
            if (e - minEnergy <= acceptThreshold) {
                acceptedFileIndices.add(currentPair.getIndex());
                ++numAccepted;
            } else {
                break;
            }
        }
    } else {
        numAccepted = numToAccept < numFiles ? numToAccept : numFiles;
        for (int i = 1; i < numAccepted; i++) {
            acceptedFileIndices.add(energies[i].getIndex());
        }
    }
    for (int i = 0; i < numAccepted; i++) {
        File filei = rescoredFiles[energies[i].getIndex()];
        Path pathi;
        pathi = generatePath(filei);
        String relPath = pwdPath.relativize(pathi).toString();
        logger.info(String.format(" Accepted: %s at %10.6f kcal/mol", relPath, energies[i].getDoubleValue()));
    }
    for (int i = numAccepted; i < numFiles; i++) {
        File filei = rescoredFiles[energies[i].getIndex()];
        Path pathi;
        pathi = generatePath(filei);
        String relPath = pwdPath.relativize(pathi).toString();
        logger.info(String.format(" Rejected: %s at %10.6f kcal/mol", relPath, energies[i].getDoubleValue()));
    }
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(resultsFile, true))) {
        Path rscFilePath = generatePath(resultsFile);
        String rscFileName = pwdPath.relativize(rscFilePath).toString();
        logger.info(String.format(" Printing accepted files to rescore file %s", rscFileName));
        if (acceptThreshold > 0.0) {
            String message = String.format("Minimum potential energy: %f, threshold = %6.4f", minEnergy, acceptThreshold);
            bw.write(message);
            message = " " + message + "\n";
            logger.info(message);
        } else {
            double maxEnergy = energies[numAccepted - 1].getDoubleValue();
            String message = String.format("Minimum potential energy: %f, maximum accepted energy %f", minEnergy, maxEnergy);
            bw.write(message);
            message = " " + message + "\n";
            logger.info(message);
        }
        bw.newLine();
        bw.newLine();
        String message = String.format("Number of files accepted: %d", numAccepted);
        bw.write(message);
        bw.newLine();
        logger.info(String.format(" %s", message));
        for (int i = 0; i < numAccepted; i++) {
            int fileIndex = energies[i].getIndex();
            File pointedFile = rescoredFiles[fileIndex];
            Path pointedPath = generatePath(pointedFile);
            String relPath = pwdPath.relativize(pointedPath).toString();
            double thisEnergy = energies[i].getDoubleValue();
            logger.info(String.format(" Accepted file %d energy %9.3f < %9.3f kcal/mol", (i + 1), thisEnergy, minEnergy + acceptThreshold));
            logger.info(String.format(" %s", relPath));
            try {
                bw.write(String.format("Accepted file: %s rank %d energy %f\n", relPath, (i + 1), thisEnergy));
                if (printModels) {
                    bw.newLine();
                    try (BufferedReader br = new BufferedReader(new FileReader(pointedFile))) {
                        String line = br.readLine();
                        while (line != null) {
                            bw.write(line);
                            bw.newLine();
                            line = br.readLine();
                        }
                    }
                    bw.newLine();
                }
            } catch (IOException ex) {
                logger.warning(String.format(" File %s had exception printing to rescore file %s", relPath, ex.toString()));
            }
        }
        message = String.format("\n Number of files not accepted: %d", numFiles - numAccepted);
        logger.info(String.format(" %s", message));
        bw.newLine();
        bw.write(message);
        bw.newLine();
        if (includeRejected) {
            for (int i = numAccepted; i < numFiles; i++) {
                int fileIndex = energies[i].getIndex();
                File pointedFile = rescoredFiles[fileIndex];
                Path pointedPath = generatePath(pointedFile);
                String relPath = pwdPath.relativize(pointedPath).toString();
                double thisEnergy = energies[i].getDoubleValue();
                message = String.format("Non-accepted file: %s rank %d energy %f", relPath, (i + 1), thisEnergy);
                logger.info(String.format(" %s", message));
                try {
                    bw.write(message);
                    bw.newLine();
                } catch (IOException ex) {
                    logger.warning(String.format(" File %s had exception printing to rescore file %s", relPath, ex.toString()));
                }
            }
        }
    } catch (IOException ex) {
        logger.warning(String.format(" Exception in writing rescore file: %s", ex.toString()));
    }
    return rescoredFiles;
}
Also used : Path(java.nio.file.Path) ClusterStructures.generatePath(ffx.algorithms.ClusterStructures.generatePath) DoubleIndexPair(ffx.utilities.DoubleIndexPair) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) DiffractionFile(ffx.xray.parsers.DiffractionFile) File(java.io.File) RealSpaceFile(ffx.realspace.RealSpaceFile)

Example 2 with DoubleIndexPair

use of ffx.utilities.DoubleIndexPair in project ffx by mjschnie.

the class RotamerOptimization method eliminateNABackboneRotamers.

/**
 * Eliminates NA backbone rotamers with corrections greater than threshold.
 * The int[] parameter allows the method to know how many Rotamers for each
 * residue have previously been pruned; currently, this means any Rotamer
 * pruned by reconcileNARotamersWithPriorResidues.
 * <p>
 * A nucleic correction threshold of 0 skips the entire method; this check
 * is presently being performed inside the method in case it is called again
 * at some point.
 *
 * @param residues Residues to eliminate bad backbone rotamers over.
 * @param numEliminatedRotamers Number of previously eliminated rotamers per
 * residue.
 */
private void eliminateNABackboneRotamers(Residue[] residues, int[] numEliminatedRotamers) {
    /* Atom atoms[] = molecularAssembly.getAtomArray();
         int nAtoms = atoms.length;
         String begin[] = new String[nAtoms];
         for (int i = 0; i < nAtoms; i++) {
         begin[i] = atoms[i].toString();
         } */
    if (nucleicCorrectionThreshold != 0) {
        logIfMaster(format(" Eliminating nucleic acid rotamers with correction vectors larger than %5.3f A", nucleicCorrectionThreshold));
        logIfMaster(format(" A minimum of %d rotamers per NA residue will carry through to energy calculations.", minNumberAcceptedNARotamers));
        ArrayList<Residue> resList = new ArrayList<>();
        resList.addAll(Arrays.asList(residues));
        ResidueState[] origCoordinates = ResidueState.storeAllCoordinates(resList);
        for (int j = 0; j < residues.length; j++) {
            Residue nucleicResidue = residues[j];
            Rotamer[] rotamers = nucleicResidue.getRotamers(library);
            if (nucleicResidue.getResidueType() == NA && rotamers != null) {
                int nrotamers = rotamers.length;
                // Default to all rotamers that have not previously been
                // eliminated; subtract as rotamers are rejected.
                int numAcceptedRotamers = nrotamers - numEliminatedRotamers[j];
                if (minNumberAcceptedNARotamers >= numAcceptedRotamers) {
                    continue;
                }
                ArrayList<DoubleIndexPair> rejectedRotamers = new ArrayList<>();
                for (int i = 0; i < nrotamers; i++) {
                    if (!check(j, i)) {
                        try {
                            RotamerLibrary.applyRotamer(nucleicResidue, rotamers[i], nucleicCorrectionThreshold);
                        } catch (NACorrectionException error) {
                            double rejectedCorrection = error.getCorrection();
                            numAcceptedRotamers--;
                            DoubleIndexPair rejected = new DoubleIndexPair(i, rejectedCorrection);
                            rejectedRotamers.add(rejected);
                        }
                    }
                }
                int numAdditionalRotamersToAccept = minNumberAcceptedNARotamers - numAcceptedRotamers;
                if (numAdditionalRotamersToAccept > 0) {
                    DoubleIndexPair[] rejectedArray = new DoubleIndexPair[rejectedRotamers.size()];
                    for (int i = 0; i < rejectedArray.length; i++) {
                        rejectedArray[i] = rejectedRotamers.get(i);
                    }
                    Arrays.sort(rejectedArray);
                    rejectedRotamers = new ArrayList<>();
                    rejectedRotamers.addAll(Arrays.asList(rejectedArray));
                    for (int i = 0; i < numAdditionalRotamersToAccept; i++) {
                        rejectedRotamers.remove(0);
                    }
                }
                for (DoubleIndexPair rotToReject : rejectedRotamers) {
                    eliminateRotamer(residues, j, rotToReject.getIndex(), print);
                    logIfMaster(format(" Correction magnitude was %6.4f A > %5.3f A", rotToReject.getDoubleValue(), nucleicCorrectionThreshold));
                }
            }
            nucleicResidue.revertState(origCoordinates[j]);
        // revertSingleResidueCoordinates(nucleicResidue, originalCoordinates[j]);
        }
    }
}
Also used : DoubleIndexPair(ffx.utilities.DoubleIndexPair) ResidueState(ffx.potential.bonded.ResidueState) ArrayList(java.util.ArrayList) RotamerLibrary.applyRotamer(ffx.potential.bonded.RotamerLibrary.applyRotamer) Rotamer(ffx.potential.bonded.Rotamer) NACorrectionException(ffx.potential.bonded.NACorrectionException) Residue(ffx.potential.bonded.Residue) MultiResidue(ffx.potential.bonded.MultiResidue)

Example 3 with DoubleIndexPair

use of ffx.utilities.DoubleIndexPair in project ffx by mjschnie.

the class Rescore method rescoreSingle.

private File rescoreSingle(File modelFile, RescoreStrategy rscType, DoubleIndexPair[] energies, int i) {
    Path filepath = generatePath(modelFile);
    if (filepath == null) {
        logger.warning(String.format(" Could not generate path to file %s", modelFile.toPath()));
        return null;
    }
    String filename = pwdPath.relativize(filepath).toString();
    File retFile = modelFile;
    try {
        MolecularAssembly assembly = utils.open(filename);
        switch(rscType) {
            case NO_RESCORE:
                logger.warning(" Rescore is being called with rscType = NO_RESCORE");
                break;
            case ENERGY_EVAL:
                break;
            case MINIMIZE:
                logger.info(String.format("\n Running minimize on %s", filename));
                logger.info(String.format(" RMS gradient convergence criteria: %f", eps));
                utils.energy(assembly);
                utils.minimize(assembly, eps);
                String ext = FilenameUtils.getExtension(filename);
                ext = ".".concat(ext);
                if (resultDir != null) {
                    filename = FilenameUtils.getBaseName(filename);
                    filename = FilenameUtils.concat(resultPath.toString(), filename);
                } else {
                    filename = FilenameUtils.removeExtension(filename);
                }
                filename = filename.concat(fileSuffix).concat(ext);
                retFile = new File(filename);
                if (ext.toUpperCase().contains("XYZ")) {
                    utils.saveAsXYZ(assembly, retFile);
                } else {
                    utils.saveAsPDB(assembly, retFile);
                }
                break;
            case XRAY_MIN:
                logger.info(String.format("\n Running x-ray minimize on %s", filename));
                DiffractionFile diffractionFile = null;
                if (diffractionFiles.isEmpty()) {
                    diffractionFile = new DiffractionFile(assembly, 1.0, false);
                    diffractionFiles.add(diffractionFile);
                }
                CompositeConfiguration properties = Keyword.loadProperties(modelFile);
                DiffractionData diffractionData = new DiffractionData(assembly, properties, SolventModel.POLYNOMIAL, diffractionFiles.toArray(new DiffractionFile[diffractionFiles.size()]));
                diffractionData.scaleBulkFit();
                diffractionData.printStats();
                utils.energy(assembly);
                RefinementMinimize refinementMinimize = new RefinementMinimize(diffractionData, refinementMode);
                if (eps < 0.0) {
                    eps = refinementMinimize.getEps();
                }
                logger.info(String.format("\n RMS gradient convergence criteria: %8.5f max number of iterations %d", eps, maxiter));
                refinementMinimize.minimize(eps, maxiter);
                diffractionData.scaleBulkFit();
                diffractionData.printStats();
                ext = FilenameUtils.getExtension(filename);
                ext = ".".concat(ext);
                if (resultDir != null) {
                    filename = FilenameUtils.getBaseName(filename);
                    filename = FilenameUtils.concat(resultPath.toString(), filename);
                } else {
                    filename = FilenameUtils.removeExtension(filename);
                }
                filename = filename.concat(fileSuffix);
                diffractionData.writeData(filename + ".mtz");
                filename = filename.concat(ext);
                diffractionData.writeModel(filename);
                retFile = new File(filename);
                if (diffractionFile != null) {
                    try {
                        diffractionFiles.remove(diffractionFile);
                    } catch (UnsupportedOperationException ex) {
                        // This should never occur, because diffractionFiles should be of a List type supporting remove(object).
                        diffractionFiles = new ArrayList<>();
                    }
                }
                break;
            case RS_MIN:
                logger.info(String.format("\n Running real-space minimize on %s", filename));
                RealSpaceFile realspaceFile = null;
                if (mapFiles.isEmpty()) {
                    realspaceFile = new RealSpaceFile(assembly);
                    mapFiles.add(realspaceFile);
                }
                properties = Keyword.loadProperties(modelFile);
                RealSpaceData realspaceData = new RealSpaceData(assembly, properties, new ParallelTeam(), mapFiles.toArray(new RealSpaceFile[mapFiles.size()]));
                utils.energy(assembly);
                refinementMinimize = new RefinementMinimize(realspaceData, refinementMode);
                if (eps < 0.0) {
                    eps = 1.0;
                }
                logger.info(String.format("\n RMS gradient convergence criteria: %8.5f max number of iterations %d", eps, maxiter));
                refinementMinimize.minimize(eps, maxiter);
                ext = FilenameUtils.getExtension(filename);
                ext = ".".concat(ext);
                if (resultDir != null) {
                    filename = FilenameUtils.getBaseName(filename);
                    filename = FilenameUtils.concat(resultPath.toString(), filename);
                } else {
                    filename = FilenameUtils.removeExtension(filename);
                }
                filename = filename.concat(fileSuffix).concat(ext);
                retFile = new File(filename);
                if (ext.toUpperCase().contains("XYZ")) {
                    utils.saveAsXYZ(assembly, retFile);
                } else {
                    utils.saveAsPDB(assembly, retFile);
                }
                if (realspaceFile != null) {
                    try {
                        mapFiles.remove(realspaceFile);
                    } catch (UnsupportedOperationException ex) {
                        // This should never occur, because diffractionFiles should be of a List type supporting remove(object).
                        mapFiles = new ArrayList<>();
                    }
                }
                break;
            default:
                logger.severe(" No valid rescore type: FFX will not continue.");
        }
        double e = utils.returnEnergy(assembly);
        energies[i] = new DoubleIndexPair(i, e);
        utils.close(assembly);
    } catch (Exception ex) {
        logger.warning(String.format(" Exception rescoring on file %s", filename));
        logger.info(ex.toString());
    }
    return retFile;
}
Also used : Path(java.nio.file.Path) ClusterStructures.generatePath(ffx.algorithms.ClusterStructures.generatePath) DoubleIndexPair(ffx.utilities.DoubleIndexPair) ParallelTeam(edu.rit.pj.ParallelTeam) RealSpaceFile(ffx.realspace.RealSpaceFile) CompositeConfiguration(org.apache.commons.configuration.CompositeConfiguration) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DiffractionFile(ffx.xray.parsers.DiffractionFile) MolecularAssembly(ffx.potential.MolecularAssembly) RealSpaceData(ffx.realspace.RealSpaceData) DiffractionFile(ffx.xray.parsers.DiffractionFile) File(java.io.File) RealSpaceFile(ffx.realspace.RealSpaceFile)

Aggregations

DoubleIndexPair (ffx.utilities.DoubleIndexPair)3 ArrayList (java.util.ArrayList)3 ClusterStructures.generatePath (ffx.algorithms.ClusterStructures.generatePath)2 RealSpaceFile (ffx.realspace.RealSpaceFile)2 DiffractionFile (ffx.xray.parsers.DiffractionFile)2 File (java.io.File)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 ParallelTeam (edu.rit.pj.ParallelTeam)1 MolecularAssembly (ffx.potential.MolecularAssembly)1 MultiResidue (ffx.potential.bonded.MultiResidue)1 NACorrectionException (ffx.potential.bonded.NACorrectionException)1 Residue (ffx.potential.bonded.Residue)1 ResidueState (ffx.potential.bonded.ResidueState)1 Rotamer (ffx.potential.bonded.Rotamer)1 RotamerLibrary.applyRotamer (ffx.potential.bonded.RotamerLibrary.applyRotamer)1 RealSpaceData (ffx.realspace.RealSpaceData)1 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1 FileReader (java.io.FileReader)1