Example usage for java.io BufferedWriter newLine

List of usage examples for java.io BufferedWriter newLine

Introduction

In this page you can find the example usage for java.io BufferedWriter newLine.

Prototype

public void newLine() throws IOException 

Source Link

Document

Writes a line separator.

Usage

From source file:ffx.algorithms.RotamerOptimization.java

/**
 * A global optimization over side-chain rotamers using a recursive
 * algorithm and information about eliminated rotamers, rotamer pairs and
 * rotamer triples/*from  ww w  .j  a  v a  2  s .co  m*/
 *
 * @param molecularAssembly
 * @param residues
 * @param i
 * @param currentRotamers
 * @param lowEnergy
 * @param optimum Optimum set of rotamers.
 * @param permutationEnergies Energies of visited permutations or null.
 *
 * @return current energy.
 */
public double rotamerOptimizationDEE(MolecularAssembly molecularAssembly, Residue residues[], int i,
        int currentRotamers[], double lowEnergy, int optimum[], double[] permutationEnergies) {
    // This is the initialization condition.
    if (i == 0) {
        evaluatedPermutations = 0;
    }
    int nResidues = residues.length;
    Residue residuei = residues[i];
    Rotamer[] rotamersi = residuei.getRotamers(library);
    int lenri = rotamersi.length;
    double currentEnergy = Double.MAX_VALUE;
    List<Residue> resList = Arrays.asList(residues);

    /**
     * As long as there are more residues, continue the recursion for each
     * rotamer of the current residue.
     */
    if (i < nResidues - 1) {
        /**
         * Loop over rotamers of residue i.
         */
        for (int ri = 0; ri < lenri; ri++) {
            /**
             * Check if rotamer ri has been eliminated by DEE.
             */
            if (check(i, ri)) {
                continue;
            }
            /**
             * Check if rotamer ri has been eliminated by an upstream
             * rotamer (any residue's rotamer from j = 0 .. i-1).
             */
            boolean deadEnd = false;
            for (int j = 0; j < i; j++) {
                int rj = currentRotamers[j];
                deadEnd = check(j, rj, i, ri);
                if (deadEnd) {
                    break;
                }
            }
            if (deadEnd) {
                continue;
            }
            applyRotamer(residuei, rotamersi[ri]);
            currentRotamers[i] = ri;
            double rotEnergy = rotamerOptimizationDEE(molecularAssembly, residues, i + 1, currentRotamers,
                    lowEnergy, optimum, permutationEnergies);
            if (rotEnergy < currentEnergy) {
                currentEnergy = rotEnergy;
            }
            if (rotEnergy < lowEnergy) {
                optimum[i] = ri;
                lowEnergy = rotEnergy;
            }
        }
    } else {
        if (ensembleStates == null) {
            ensembleStates = new ArrayList<>();
        }

        /**
         * At the end of the recursion, compute the potential energy for
         * each rotamer of the final residue. If a lower potential energy is
         * discovered, the rotamers of each residue will be collected as the
         * recursion returns up the chain.
         */
        for (int ri = 0; ri < lenri; ri++) {
            /**
             * Check if rotamer ri has been eliminated by DEE.
             */
            if (check(i, ri)) {
                continue;
            }
            currentRotamers[i] = ri;
            /**
             * Check if rotamer ri has been eliminated by an upstream
             * rotamer (any residue's rotamer from 0 .. i-1.
             */
            boolean deadEnd = false;
            for (int j = 0; j < i; j++) {
                int rj = currentRotamers[j];
                deadEnd = check(j, rj, i, ri);
                if (deadEnd) {
                    break;
                }
            }
            if (deadEnd) {
                continue;
            }
            applyRotamer(residuei, rotamersi[ri]);
            // Compute the energy based on a 3-body approximation
            double approximateEnergy = computeEnergy(residues, currentRotamers, false);
            double comparisonEnergy = approximateEnergy;
            evaluatedPermutations++;
            // Compute the AMOEBA energy
            if (useFullAMOEBAEnergy) {
                double amoebaEnergy = currentEnergy(resList);
                if (permutationEnergies != null) {
                    permutationEnergies[evaluatedPermutations - 1] = amoebaEnergy;
                }
                comparisonEnergy = amoebaEnergy;
                // Log current results
                logIfMaster(String.format(" %d AMOEBA: %16.8f 3-Body: %16.8f Neglected: %16.8f",
                        evaluatedPermutations, amoebaEnergy, approximateEnergy,
                        amoebaEnergy - approximateEnergy));
            } else {
                if (permutationEnergies != null) {
                    permutationEnergies[evaluatedPermutations - 1] = approximateEnergy;
                }
                if (threeBodyTerm) {
                    logIfMaster(String.format(" %d Energy through 3-Body interactions: %16.8f",
                            evaluatedPermutations, approximateEnergy));
                } else {
                    logIfMaster(String.format(" %d Energy through 2-Body interactions: %16.8f",
                            evaluatedPermutations, approximateEnergy));
                }
            }

            if (algorithmListener != null) {
                algorithmListener.algorithmUpdate(molecularAssembly);
            }

            if (ensembleNumber > 1) {
                if (master && printFiles) {
                    try {
                        FileWriter fw = new FileWriter(ensembleFile, true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(String.format("MODEL        %d", evaluatedPermutations));
                        for (int j = 0; j < 75; j++) {
                            bw.write(" ");
                        }
                        bw.newLine();
                        bw.flush();
                        ensembleFilter.writeFile(ensembleFile, true);
                        bw.write(String.format("ENDMDL"));
                        for (int j = 0; j < 64; j++) {
                            bw.write(" ");
                        }
                        bw.newLine();
                        bw.close();
                    } catch (IOException e) {
                        logger.warning(String.format("Exception writing to file: %s", ensembleFile.getName()));
                    }
                }
                ResidueState[] states = ResidueState.storeAllCoordinates(residues);
                ensembleStates.add(new ObjectPair<>(states, comparisonEnergy));
            }

            if (comparisonEnergy < currentEnergy) {
                currentEnergy = comparisonEnergy;
            }

            if (comparisonEnergy < lowEnergy) {
                lowEnergy = comparisonEnergy;
                optimum[i] = ri;
            }
        }

        ensembleStates.sort(null);
    }
    return currentEnergy;
}

From source file:com.quinsoft.zeidon.zeidonoperations.KZOEP1AA.java

public int SysWriteLine(TaskQualification taskView, int file, String fileBuffer) throws IOException {
    BufferedWriter writer = getWriterFromInt(taskView.getTask(), file);
    writer.write(fileBuffer);/*from   w  ww  .  j ava2  s  . co m*/
    writer.newLine();
    return 0;
}

From source file:ffx.algorithms.RotamerOptimization.java

/**
 * The main driver for optimizing a block of residues using DEE.
 *
 * @param residueList Residues to optimize.
 * @return Final energy.//from   ww w .  j a v  a 2 s  .c om
 */
private double globalUsingEliminations(List<Residue> residueList) {
    int currentEnsemble = Integer.MAX_VALUE;
    Residue residues[] = residueList.toArray(new Residue[residueList.size()]);
    int nResidues = residues.length;
    int currentRotamers[] = new int[nResidues];
    int optimum[] = new int[nResidues];
    int iterations = 0;
    boolean finalTry = false;
    int bestEnsembleTargetDiffThusFar = Integer.MAX_VALUE;
    double bestBufferThusFar = ensembleBuffer;
    double startingBuffer = ensembleBuffer;

    if (ensembleEnergy > 0.0) {
        ensembleBuffer = ensembleEnergy;
        applyEliminationCriteria(residues, true, true);
        if (x == null) {
            Atom atoms[] = molecularAssembly.getAtomArray();
            int nAtoms = atoms.length;
            x = new double[nAtoms * 3];
        }
        /**
         * Compute the number of permutations without eliminating dead-ends
         * and compute the number of permutations using singleton
         * elimination.
         */
        double permutations = 1;
        double singletonPermutations = 1;
        for (int i = 0; i < nResidues; i++) {
            Residue residue = residues[i];
            Rotamer[] rotamers = residue.getRotamers(library);
            int nr = rotamers.length;
            if (nr > 1) {
                int nrot = 0;
                for (int ri = 0; ri < nr; ri++) {
                    if (!eliminatedSingles[i][ri]) {
                        nrot++;
                    }
                }
                permutations *= rotamers.length;
                if (nrot > 1) {
                    singletonPermutations *= nrot;
                }
            }
        }
        dryRun(residues, 0, currentRotamers);
        double pairTotalElimination = singletonPermutations - (double) evaluatedPermutations;
        if (evaluatedPermutations == 0) {
            logger.severe(
                    "No valid path through rotamer space found; try recomputing without pruning or using ensemble.");
        }
        if (master && printFiles && ensembleFile == null) {
            File file = molecularAssembly.getFile();
            String filename = FilenameUtils.removeExtension(file.getAbsolutePath());
            //ensembleFile = SystemFilter.version(new File(filename + ".ens"));
            ensembleFile = new File(filename + ".ens");
            if (ensembleFile.exists()) {
                for (int i = 2; i < 1000; i++) {
                    ensembleFile = new File(filename + ".ens_" + i);
                    if (!ensembleFile.exists()) {
                        break;
                    }
                }
                if (ensembleFile.exists()) {
                    logger.warning(String.format(" Versioning failed: appending to end of file %s",
                            ensembleFile.getName()));
                }
            }
            ensembleFilter = new PDBFilter(new File(ensembleFile.getName()), molecularAssembly, null, null);
            logger.info(String.format(" Ensemble file: %s", ensembleFile.getName()));
        }
        logIfMaster(String.format(" Number of permutations without DEE conditions: %10.4e.", permutations));
        logIfMaster(String.format(" Number of permutations after singleton eliminations: %10.4e.",
                singletonPermutations));
        logIfMaster(String.format(" Number of permutations removed by pairwise eliminations: %10.4e.",
                pairTotalElimination));
        logIfMaster(
                String.format(" Number of permutations remaining: %10.4e.", (double) evaluatedPermutations));

        double e;
        if (useMonteCarlo()) {
            firstValidPerm(residues, 0, currentRotamers);
            System.arraycopy(currentRotamers, 0, optimum, 0, nResidues);
            rotamerOptimizationMC(residues, optimum, currentRotamers, nMCsteps, false, mcUseAll);

            logIfMaster(" Ensembles not currently compatible with Monte Carlo search");
            /**
             * Not currently compatible with ensembles.
             */
        } else {
            double[] permutationEnergies = new double[evaluatedPermutations];
            ensembleStates = new ArrayList<>();

            e = rotamerOptimizationDEE(molecularAssembly, residues, 0, currentRotamers, Double.MAX_VALUE,
                    optimum, permutationEnergies);
            int[][] acceptedPermutations = new int[evaluatedPermutations][];
            for (int i = 0; i < acceptedPermutations.length; i++) {
                acceptedPermutations[i] = null;
            }
            logIfMaster(String.format(
                    "\n Checking permutations for distance < %5.3f kcal/mol from GMEC energy %10.8f kcal/mol",
                    ensembleEnergy, e));
            dryRunForEnsemble(residues, 0, currentRotamers, e, permutationEnergies, acceptedPermutations);
            int numAcceptedPermutations = 0;

            for (int i = 0; i < acceptedPermutations.length; i++) {
                if (acceptedPermutations[i] != null) {
                    ++numAcceptedPermutations;
                    logIfMaster(String.format(" Accepting permutation %d at %8.6f < %8.6f", i,
                            permutationEnergies[i] - e, ensembleEnergy));
                    for (int j = 0; j < nResidues; j++) {
                        Residue residuej = residues[j];
                        Rotamer[] rotamersj = residuej.getRotamers(library);
                        RotamerLibrary.applyRotamer(residuej, rotamersj[acceptedPermutations[i][j]]);
                    }

                    ResidueState[] states = ResidueState.storeAllCoordinates(residues);
                    ensembleStates.add(new ObjectPair<>(states, permutationEnergies[i]));

                    if (printFiles && master) {
                        try {
                            FileWriter fw = new FileWriter(ensembleFile, true);
                            BufferedWriter bw = new BufferedWriter(fw);
                            bw.write(String.format("MODEL        %d", numAcceptedPermutations));
                            for (int j = 0; j < 75; j++) {
                                bw.write(" ");
                            }
                            bw.newLine();
                            bw.flush();
                            ensembleFilter.writeFile(ensembleFile, true);
                            bw.write(String.format("ENDMDL"));
                            for (int j = 0; j < 64; j++) {
                                bw.write(" ");
                            }
                            bw.newLine();
                            bw.close();
                        } catch (IOException ex) {
                            logger.warning(
                                    String.format(" Exception writing to file: %s", ensembleFile.getName()));
                        }
                    }
                }
            }
            logIfMaster(String.format(" Number of permutations within %5.3f kcal/mol of GMEC energy: %6.4e",
                    ensembleEnergy, (double) numAcceptedPermutations));
            ensembleStates.sort(null);
        }

        logIfMaster("\n Final rotamers:");
        for (int i = 0; i < nResidues; i++) {
            Residue residue = residues[i];
            Rotamer[] rotamers = residue.getRotamers(library);
            int ri = optimum[i];
            Rotamer rotamer = rotamers[ri];
            logIfMaster(String.format(" %c %s %s (%d)", residue.getChainID(), residue, rotamer.toString(), ri));
            RotamerLibrary.applyRotamer(residue, rotamer);
        }

        double sumSelfEnergy = 0;
        double sumPairEnergy = 0;
        double sumTrimerEnergy = 0;
        for (int i = 0; i < nResidues; i++) {
            int ri = optimum[i];
            sumSelfEnergy += selfEnergy[i][ri];
        }
        for (int i = 0; i < nResidues - 1; i++) {
            int ri = optimum[i];
            for (int j = i + 1; j < nResidues; j++) {
                int rj = optimum[j];
                sumPairEnergy += twoBodyEnergy[i][ri][j][rj];
            }
        }

        e = currentEnergy(residueList);
        logIfMaster(String.format(" Self Energy:   %16.8f", sumSelfEnergy));
        logIfMaster(String.format(" Pair Energy:   %16.8f", sumPairEnergy));

        double approximateEnergy = backboneEnergy + sumSelfEnergy + sumPairEnergy;

        if (threeBodyTerm) {
            for (int i = 0; i < nResidues - 2; i++) {
                int ri = optimum[i];
                for (int j = i + 1; j < nResidues - 1; j++) {
                    int rj = optimum[j];
                    for (int k = j + 1; k < nResidues; k++) {
                        int rk = optimum[k];
                        sumTrimerEnergy += threeBodyEnergy[i][ri][j][rj][k][rk];
                    }
                }
            }
            approximateEnergy += sumTrimerEnergy;
            double higherOrderEnergy = e - sumSelfEnergy - sumPairEnergy - sumTrimerEnergy - backboneEnergy;
            logIfMaster(String.format(" Trimer Energy: %16.8f", sumTrimerEnergy));
            logIfMaster(String.format(" Neglected:     %16.8f", higherOrderEnergy));
        } else {
            double higherOrderEnergy = e - sumSelfEnergy - sumPairEnergy - backboneEnergy;
            logIfMaster(String.format(" Neglected:     %16.8f", higherOrderEnergy));
        }
        logIfMaster(String.format(" Approximate Energy:     %16.8f", approximateEnergy));
        return e;
    }

    /**
     * Permutations used only to set maximum bound on ensembleNumber, thus
     * it is safe here to put that value in a 32-bit int.
     */
    int nPerms = 1;
    for (int i = 0; i < nResidues; i++) {
        Residue residue = residues[i];
        Rotamer[] rotamers = residue.getRotamers(library);
        int nr = rotamers.length;
        if (nr > 1) {
            nPerms *= rotamers.length;
        }
        if (nPerms > ensembleNumber) {
            break;
        }
    }

    if (nPerms < ensembleNumber) {
        logger.info(String.format(
                " Requested an ensemble of %d, but only %d permutations exist; returning full ensemble",
                ensembleNumber, nPerms));
        ensembleNumber = nPerms;
    }

    while (currentEnsemble != ensembleNumber) {
        if (monteCarlo) {
            logIfMaster(" Ensemble search not currently compatible with Monte Carlo");
            ensembleNumber = 1;
        }
        if (iterations == 0) {
            applyEliminationCriteria(residues, true, true);
        } else {
            applyEliminationCriteria(residues, false, false);
        }

        if (x == null) {
            Atom atoms[] = molecularAssembly.getAtomArray();
            int nAtoms = atoms.length;
            x = new double[nAtoms * 3];
        }

        /**
         * Compute the number of permutations without eliminating dead-ends
         * and compute the number of permutations using singleton
         * elimination.
         */
        double permutations = 1;
        double singletonPermutations = 1;
        for (int i = 0; i < nResidues; i++) {
            Residue residue = residues[i];
            Rotamer[] rotamers = residue.getRotamers(library);
            int nr = rotamers.length;
            if (nr > 1) {
                int nrot = 0;
                for (int ri = 0; ri < nr; ri++) {
                    if (!eliminatedSingles[i][ri]) {
                        nrot++;
                    }
                }
                permutations *= rotamers.length;
                if (nrot > 1) {
                    singletonPermutations *= nrot;
                }
            }
        }
        dryRun(residues, 0, currentRotamers);
        double pairTotalElimination = singletonPermutations - (double) evaluatedPermutations;
        currentEnsemble = (int) evaluatedPermutations;
        if (ensembleNumber == 1 && currentEnsemble == 0) {
            logger.severe(
                    "No valid path through rotamer space found; try recomputing without pruning or using ensemble.");
            /*  PROGRAMMATIC ENSEMBLE CONTROL (dangerous)
             if (getPruning() == 0) {
             logger.warning(" Unable to recover a rotamer path; commencing ensemble search.");
             setEnsemble(10, 5.0);
             startingBuffer = 5.0;
             continue;
             } else {
             logger.warning(" Pruning left no valid path through rotamer space; recomputing without pruning.");
             setPruning(0);
             continue;
             }
             */
        }
        if (ensembleNumber > 1) {
            if (master && printFiles && ensembleFile == null) {
                File file = molecularAssembly.getFile();
                String filename = FilenameUtils.removeExtension(file.getAbsolutePath());
                ensembleFile = new File(filename + ".ens");
                if (ensembleFile.exists()) {
                    for (int i = 2; i < 1000; i++) {
                        ensembleFile = new File(filename + ".ens_" + i);
                        if (!ensembleFile.exists()) {
                            break;
                        }
                    }
                    if (ensembleFile.exists()) {
                        logger.warning(String.format(" Versioning failed: appending to end of file %s",
                                ensembleFile.getName()));
                    }
                }
                ensembleFilter = new PDBFilter(new File(ensembleFile.getName()), molecularAssembly, null, null);
                logger.info(String.format(" Ensemble file: %s", ensembleFile.getName()));
            }
            logIfMaster(String.format(" Ensemble Search Stats: (buffer: %5.3f, current: %d, target: %d)",
                    ensembleBuffer, currentEnsemble, ensembleNumber));
        }
        if (ensembleNumber == 1 || finalTry) {
            logIfMaster(String.format(" Number of permutations without DEE conditions: %10.4e.", permutations));
            logIfMaster(String.format(" Number of permutations after singleton eliminations: %10.4e.",
                    singletonPermutations));
            logIfMaster(String.format(" Number of permutations removed by pairwise eliminations: %10.4e.",
                    pairTotalElimination));
            logIfMaster(String.format(" Number of permutations remaining: %10.4e.",
                    (double) evaluatedPermutations));
            break;
        }
        if (Math.abs(currentEnsemble - ensembleNumber) < bestEnsembleTargetDiffThusFar) {
            bestEnsembleTargetDiffThusFar = Math.abs(currentEnsemble - ensembleNumber);
            bestBufferThusFar = ensembleBuffer;
        }
        if (currentEnsemble > ensembleNumber) {
            ensembleBuffer -= ensembleBufferStep;
            ensembleBufferStep -= (ensembleBufferStep * 0.01);
            iterations++;
        } else if (currentEnsemble < ensembleNumber) {
            ensembleBuffer += ensembleBufferStep;
            ensembleBufferStep -= (ensembleBufferStep * 0.01);
            iterations++;
        }
        if (iterations > 100) {
            if (currentEnsemble == 0) {
                // TODO: Decide whether we like these next four lines.  Has the potential to produce a crazy amount of permutations.
                logIfMaster(" Ensemble still empty; increasing buffer energy.");
                startingBuffer = 3 * startingBuffer;
                setEnsemble(10, startingBuffer);
                iterations = 0;
            } else {
                ensembleBuffer = bestBufferThusFar;
                finalTry = true;
            }
        }
    }

    if (currentEnsemble == 0) {
        logger.warning(
                " No valid rotamer permutations found; results will be unreliable.  Try increasing the starting ensemble buffer.");
    }
    double[] permutationEnergyStub = null;
    if (useMonteCarlo()) {
        firstValidPerm(residues, 0, currentRotamers);
        rotamerOptimizationMC(residues, optimum, currentRotamers, nMCsteps, false, mcUseAll);
    } else {
        rotamerOptimizationDEE(molecularAssembly, residues, 0, currentRotamers, Double.MAX_VALUE, optimum,
                permutationEnergyStub);
    }

    logIfMaster("\n Final rotamers:");
    for (int i = 0; i < nResidues; i++) {
        Residue residue = residues[i];
        Rotamer[] rotamers = residue.getRotamers(library);
        int ri = optimum[i];
        Rotamer rotamer = rotamers[ri];
        logIfMaster(String.format(" %c %s %s (%d)", residue.getChainID(), residue, rotamer.toString(), ri));
        RotamerLibrary.applyRotamer(residue, rotamer);
    }

    double sumSelfEnergy = 0;
    double sumPairEnergy = 0;
    double sumTrimerEnergy = 0;
    for (int i = 0; i < nResidues; i++) {
        int ri = optimum[i];
        sumSelfEnergy += selfEnergy[i][ri];
    }
    for (int i = 0; i < nResidues - 1; i++) {
        int ri = optimum[i];
        for (int j = i + 1; j < nResidues; j++) {
            int rj = optimum[j];
            sumPairEnergy += twoBodyEnergy[i][ri][j][rj];
        }
    }

    double e = currentEnergy(residueList);
    logIfMaster(String.format(" Self Energy:   %16.8f", sumSelfEnergy));
    logIfMaster(String.format(" Pair Energy:   %16.8f", sumPairEnergy));

    double approximateEnergy = backboneEnergy + sumSelfEnergy + sumPairEnergy;

    if (threeBodyTerm) {
        for (int i = 0; i < nResidues - 2; i++) {
            int ri = optimum[i];
            for (int j = i + 1; j < nResidues - 1; j++) {
                int rj = optimum[j];
                for (int k = j + 1; k < nResidues; k++) {
                    int rk = optimum[k];
                    sumTrimerEnergy += threeBodyEnergy[i][ri][j][rj][k][rk];
                }
            }
        }
        approximateEnergy += sumTrimerEnergy;
        double higherOrderEnergy = e - sumSelfEnergy - sumPairEnergy - sumTrimerEnergy - backboneEnergy;
        logIfMaster(String.format(" Trimer Energy: %16.8f", sumTrimerEnergy));
        logIfMaster(String.format(" Neglected:     %16.8f", higherOrderEnergy));
    } else {
        double higherOrderEnergy = e - sumSelfEnergy - sumPairEnergy - backboneEnergy;
        logIfMaster(String.format(" Neglected:     %16.8f", higherOrderEnergy));
    }

    logIfMaster(String.format(" Approximate Energy:     %16.8f", approximateEnergy));

    return e;
}

From source file:com.quinsoft.zeidon.zeidonoperations.KZOEP1AA.java

public int SysWriteLineLth(TaskQualification taskView, int file, String fileBuffer, int nLth)
        throws IOException {
    BufferedWriter writer = getWriterFromInt(taskView.getTask(), file);
    writer.write(fileBuffer.substring(0, nLth));
    writer.newLine();
    return 0;//from w w  w  . j ava 2 s.  com
}

From source file:StreamFlusher.java

public Object visit(ASTtestTokensTextFile_statement node, Object data) {
    // Total: 11 regexp arguments, syntactically constrained
    // /*from w  w w  .ja v a2s  .c om*/
    // 0.  the Fst to test

    node.jjtGetChild(0).jjtAccept(this, data);
    Fst testFst = (Fst) (stack.pop());

    // 1.  path of the input file

    node.jjtGetChild(1).jjtAccept(this, data);
    Fst tempFst = (Fst) (stack.pop());

    String inputFilePath = lib.GetSingleString(tempFst,
            "Second arg to testTokensTextFile must denote a language of exactly one string.");

    if (inputFilePath.length() == 0) {
        throw new KleeneArgException(
                "Second arg to testTokensTextFile must denote a language of exactly one non-empty string");
    }

    // 2.  encoding of the input file

    node.jjtGetChild(2).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String inputFileEncoding = lib.GetSingleString(tempFst,
            "Third arg to testTokensTextFile must denote a language of exactly one string.");

    if (inputFileEncoding.length() == 0) {
        throw new KleeneArgException("Third arg to testTokensTextFile must denote one non-empty string");
    }

    // 3.  path of the output file

    node.jjtGetChild(3).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputFilePath = lib.GetSingleString(tempFst,
            "Fourth arg to testTokensTextFile must denote a language of exactly one string.");

    if (outputFilePath.length() == 0) {
        throw new KleeneArgException("Fourth arg to testTokensTextFile must denote one non-empty string");
    }

    // 4.  encoding of the output file

    node.jjtGetChild(4).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputFileEncoding = lib.GetSingleString(tempFst,
            "Fifth arg to testTokensTextFile must denote a language of exactly one string.");

    if (outputFileEncoding.length() == 0) {
        throw new KleeneArgException("Fifth arg to testTokensTextFile must denote one non-empty string");
    }

    //          And for the XML output

    // 5.  name of the root element

    node.jjtGetChild(5).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String rootElmtName = lib.GetSingleString(tempFst,
            "Sixth arg to testTokensTextFile must denote a language of exactly one string.");

    if (rootElmtName.length() == 0) {
        throw new KleeneArgException("Sixth arg to testTokensTextFile must denote one non-empty string");
    }

    // 6.  name of the token element

    node.jjtGetChild(6).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String tokenElmtName = lib.GetSingleString(tempFst,
            "Seventh arg to testTokensTextFile must denote a language of exactly one string.");

    if (tokenElmtName.length() == 0) {
        throw new KleeneArgException("Seventh arg to testTokensTextFile must denote one non-empty string");
    }

    // 7.  name of the input element

    node.jjtGetChild(7).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String inputElmtName = lib.GetSingleString(tempFst,
            "Eighth arg to testTokensTextFile must denote a language of exactly one string.");

    if (inputElmtName.length() == 0) {
        throw new KleeneArgException("Eighth arg to testTokensTextFile must denote one non-empty string");
    }

    // 8.  name of the outputs element (N.B. plural)

    node.jjtGetChild(8).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputsElmtName = lib.GetSingleString(tempFst,
            "Ninth arg to testTokensTextFile must denote a language of exactly one string.");

    if (outputsElmtName.length() == 0) {
        throw new KleeneArgException("Ninth arg to testTokensTextFile must denote one non-empty string");
    }

    // 9.  name of the output element  (N.B. singular)

    node.jjtGetChild(9).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputElmtName = lib.GetSingleString(tempFst,
            "Tenth arg to testTokensTextFile must denote a language of exactly one string.");

    if (outputElmtName.length() == 0) {
        throw new KleeneArgException("Tenth arg to testTokensTextFile must denote one non-empty string");
    }

    // 10.  name of the weight attr in the output elmt

    node.jjtGetChild(10).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String weightAttrName = lib.GetSingleString(tempFst,
            "Eleventh arg to testTokensTextFile must denote a language of exactly one string.");

    if (weightAttrName.length() == 0) {
        throw new KleeneArgException("Eleventh arg to testTokensTextFile must denote one non-empty string");
    }

    String fullpath = getFullpath(inputFilePath);

    TranslitTokenizerBuilder ttb = new TranslitTokenizerBuilder(symmap, testFst.getSigma(), lib);
    lib.Iterate4mcs(testFst, ttb, symmap.getStartPuaCpv());
    Transliterator trInput = ttb.getTranslitTokenizer(true); // true for input side

    try {
        BufferedReader in = null;
        if (inputFileEncoding.equals("default") || inputFileEncoding.equals("-")) {
            // get the current default encoding of the operating system
            inputFileEncoding = System.getProperty("file.encoding");
        }
        if (inputFileEncoding.equals("UTF-8")) {
            in = new BufferedReader(new InputStreamReader(
                    new UTF8BOMStripperInputStream(new FileInputStream(fullpath)), inputFileEncoding));
        } else {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(fullpath), inputFileEncoding));
        }

        // now try to open the output file 
        fullpath = getFullpath(outputFilePath);

        BufferedWriter out = null;
        if (outputFileEncoding.equals("default") || outputFileEncoding.equals("-")) {
            // get the current default encoding of the operating system
            outputFileEncoding = System.getProperty("file.encoding");
        }
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fullpath), outputFileEncoding));

        out.write("<?xml version=\"1.0\" encoding=\"" + outputFileEncoding + "\"?>");
        out.newLine();
        out.write("<" + rootElmtName + ">");
        out.newLine();

        // read the input string/words, one per line, from the input file, write output to the output file

        XMLOutputLister xmlOutputLister = new XMLOutputLister(symmap, out, outputElmtName, weightAttrName);

        String token; // one per line in the input file

        Fst modifiedTestFst;

        while ((token = in.readLine()) != null) {
            String cpvstr = trInput.transliterate(token);
            // converts cpvstr to a sequence of code pt values, and
            // each one could fill one or two 16-bit code units;
            // this is where multichar symbols are reduced to their
            // code point values

            // get length in Unicode characters (not code units)
            int inputlen = cpvstr.codePointCount(0, cpvstr.length());
            // allocate an int array to hold those code-point values,
            //    one int per code point value
            int[] cpvArray = new int[inputlen];

            // UCharacterIterator knows how to iterate over a String and
            // return the Unicode-Character code point values
            UCharacterIterator iter = UCharacterIterator.getInstance(cpvstr);

            // we need to build each input string into a one-path Fst

            // store the codepoints in the int array (which will be passed to
            //    oneStringNativeFst(), a native method
            int codepoint;
            int index = 0;
            while ((codepoint = iter.nextCodePoint()) != UCharacterIterator.DONE) {
                // any multichar symbols will already be in the
                // symmap, or they wouldn't have been identified;
                // but BMP characters may not yet be in the symmap
                if (Character.charCount(codepoint) == 1) {
                    symmap.putsym(String.valueOf((char) codepoint));
                }
                cpvArray[index++] = codepoint;
            }

            // 0 arg means generate
            Fst compFst = lib.ApplyToOneString(testFst, cpvArray, 0);

            // prepare to list the output strings (and their weights)
            long stringCount = lib.NumPaths(compFst);

            // XML output for this input token

            out.write("  <" + tokenElmtName + ">");
            out.newLine();

            // be careful to escape XML special chars in line; 
            // N.B. escapeXml also escapes non-ASCII Unicode letters
            //out.write("    <" + inputElmtName + ">" + 
            //  StringEscapeUtils.escapeXml(token) + "</" + 
            //  inputElmtName + ">") ;

            out.write("    <" + inputElmtName + ">" + EscapeXML.escapeXML(token) + "</" + inputElmtName + ">");
            out.newLine();

            out.write("    <" + outputsElmtName + ">");
            out.newLine();

            if (stringCount == 0) {
                // output nothing
            } else if (stringCount == -1) {
                // means that the composedFstPtr has loops, 
                //   denotes an infinite language
                out.write("      <infinite/>");
                out.newLine();
            } else {
                // native function listAllStrings will find all 
                //      strings in the Fst
                // and make callbacks to xmlOutputLister, 
                //      which knows how to output them as XML elements
                lib.ListAllStrings(compFst, 1, xmlOutputLister);
            }

            out.write("    </" + outputsElmtName + ">");
            out.newLine();

            out.write("  </" + tokenElmtName + ">");
            out.newLine();
        }
        in.close();

        out.write("</" + rootElmtName + ">");
        out.newLine();
        out.flush();
        out.close();
    } catch (Exception e) {
        System.out.println("Exception found while testing input from file.");
        e.printStackTrace();
    }
    return data;
}

From source file:StreamFlusher.java

public Object visit(ASTtestTokensXMLFile_statement node, Object data) {
    // Total: 11 regexp arguments, syntactically constrained
    // /*from w ww.  j  a  v a2  s. com*/
    // 0.  the Fst to test

    node.jjtGetChild(0).jjtAccept(this, data);
    Fst testFst = (Fst) (stack.pop());

    // 1.  path of the input file

    node.jjtGetChild(1).jjtAccept(this, data);
    Fst tempFst = (Fst) (stack.pop());

    String inputFilePath = lib.GetSingleString(tempFst,
            "Second arg to testTokensXMLFile must denote a language of exactly one string.");

    if (inputFilePath.length() == 0) {
        throw new KleeneArgException(
                "Second arg to testTokensXMLFile must denote exactly one non-empty string");
    }

    // 2. argument supplying the name of the element holding
    //      the input strings, by default, "input", i.e.
    //      <input>...</input>
    // N.B. in testTokensTextFile, this argument specifies the
    // encoding of the input file, which is not needed for XML,
    // which either has an explicit "encoding" specification, or
    // is UTF-8 by default

    node.jjtGetChild(2).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String srcInputElmtName = lib.GetSingleString(tempFst,
            "Third arg to testTokensXMLFile must denote a language of exactly one string.");

    if (srcInputElmtName.length() == 0) {
        throw new KleeneArgException("Third arg to testTokensXMLFile must denote one non-empty string");
    }

    // 3.  path of the output file

    node.jjtGetChild(3).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputFilePath = lib.GetSingleString(tempFst,
            "Fourth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputFilePath.length() == 0) {
        throw new KleeneArgException("Fourth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 4.  encoding of the output file

    node.jjtGetChild(4).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputFileEncoding = lib.GetSingleString(tempFst,
            "Fifth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputFileEncoding.length() == 0) {
        throw new KleeneArgException("Fifth arg to testTokensXMLFile must denote one non-empty string");
    }

    //          And for the XML output

    // 5.  name of the root element

    node.jjtGetChild(5).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String rootElmtName = lib.GetSingleString(tempFst,
            "Sixth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (rootElmtName.length() == 0) {
        throw new KleeneArgException("Sixth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 6.  name of the token element

    node.jjtGetChild(6).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String tokenElmtName = lib.GetSingleString(tempFst,
            "Seventh arg to testTokensXMLFile must denote a language of exactly one string.");

    if (tokenElmtName.length() == 0) {
        throw new KleeneArgException("Seventh arg to testTokensXMLFile must denote one non-empty string");
    }

    // 7.  name of the input element

    node.jjtGetChild(7).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String inputElmtName = lib.GetSingleString(tempFst,
            "Eighth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (inputElmtName.length() == 0) {
        throw new KleeneArgException("Eighth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 8.  name of the outputs element (N.B. plural)

    node.jjtGetChild(8).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputsElmtName = lib.GetSingleString(tempFst,
            "Ninth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputsElmtName.length() == 0) {
        throw new KleeneArgException("Ninth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 9.  name of the output element  (N.B. singular)

    node.jjtGetChild(9).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String outputElmtName = lib.GetSingleString(tempFst,
            "Tenth arg to testTokensXMLFile must denote a language of exactly one string.");

    if (outputElmtName.length() == 0) {
        throw new KleeneArgException("Tenth arg to testTokensXMLFile must denote one non-empty string");
    }

    // 10.  name of the weight attr in the output elmt

    node.jjtGetChild(10).jjtAccept(this, data);
    tempFst = (Fst) (stack.pop());

    String weightAttrName = lib.GetSingleString(tempFst,
            "Eleventh arg to testTokensXMLFile must denote a language of exactly one string.");

    if (weightAttrName.length() == 0) {
        throw new KleeneArgException("Eleventh arg to testTokensXMLFile must denote one non-empty string");
    }

    String fullpath = getFullpath(inputFilePath);

    TranslitTokenizerBuilder ttb = new TranslitTokenizerBuilder(symmap, testFst.getSigma(), lib);
    lib.Iterate4mcs(testFst, ttb, symmap.getStartPuaCpv());
    Transliterator trInput = ttb.getTranslitTokenizer(true); // true for input side

    try {
        // try to read/parse the XML input file

        Document doc = null;

        doc = parseXML(fullpath); // dom4j

        // Read all the <input></input> elements into a list
        // N.B. by default, the name of the element is "input",
        // but in general it is specified in arg srcInputElmtName
        List list = doc.selectNodes("//" + srcInputElmtName);

        // now try to open the output file 

        fullpath = getFullpath(outputFilePath);

        BufferedWriter out = null;
        if (outputFileEncoding.equals("default") || outputFileEncoding.equals("-")) {
            // get the current default encoding of the operating system
            outputFileEncoding = System.getProperty("file.encoding");
        }
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fullpath), outputFileEncoding));

        out.write("<?xml version=\"1.0\" encoding=\"" + outputFileEncoding + "\"?>");
        out.newLine();
        out.write("<" + rootElmtName + ">");
        out.newLine();

        XMLOutputLister xmlOutputLister = new XMLOutputLister(symmap, out, outputElmtName, weightAttrName);

        // Loop through the <input></input> elements, extracting and
        //   running the text string from each one; write output to
        //   the output file

        String token;

        Fst modifiedTestFst;

        for (Iterator it = list.iterator(); it.hasNext();) {
            Element inputElmt = (Element) it.next();
            token = inputElmt.getText();

            String cpvstr = trInput.transliterate(token);
            // converts cpvstr to a sequence of code pt values, and
            // each one could fill one or two 16-bit code units;
            // this is where multichar symbols are reduced to their
            // code point values

            // get length in Unicode characters (not code units)
            int inputlen = cpvstr.codePointCount(0, cpvstr.length());
            // allocate an int array to hold those code-point values,
            //    one int per code point value
            int[] cpvArray = new int[inputlen];

            // UCharacterIterator knows how to iterate over a 
            //   String and
            // return the Unicode-Character code point values
            UCharacterIterator iter = UCharacterIterator.getInstance(cpvstr);

            // we need to build each input string into a one-path Fst

            // store the codepoints in the int array 
            //      (which will be passed to
            //    oneStringNativeFst(), a native method
            int codepoint;
            int index = 0;
            while ((codepoint = iter.nextCodePoint()) != UCharacterIterator.DONE) {
                // any multichar symbols will already be in the
                // symmap, or they wouldn't have been identified;
                // but BMP characters may not yet be in the symmap
                if (Character.charCount(codepoint) == 1) {
                    symmap.putsym(String.valueOf((char) codepoint));
                }
                cpvArray[index++] = codepoint;
            }

            // 0 arg for generation, apply the inputFst to the "input"
            // side of testFst
            Fst compFst = lib.ApplyToOneString(testFst, cpvArray, 0);

            // prepare to list the output strings (and their weights)
            long stringCount = lib.NumPaths(compFst);

            // XML output for this input token

            out.write("  <" + tokenElmtName + ">");
            out.newLine();

            // be careful to escape XML special chars in line; 
            // N.B. escapeXml also escapes non-ASCII Unicode letters
            //out.write("    <" + inputElmtName + ">" + 
            //          StringEscapeUtils.escapeXml(token) + 
            //          "</" + inputElmtName + ">") ;

            out.write("    <" + inputElmtName + ">" + EscapeXML.escapeXML(token) + "</" + inputElmtName + ">");
            out.newLine();

            out.write("    <" + outputsElmtName + ">");
            out.newLine();

            if (stringCount == 0) {
                // output nothing
            } else if (stringCount == -1) {
                // means that the compFstPtr has loops, 
                //      denotes an infinite language
                out.write("      <infinite/>");
                out.newLine();
            } else {
                // native function listAllStrings will find all 
                //      strings in the Fst
                // and make callbacks to xmlOutputLister, 
                //      which knows how to output
                // them as XML elements
                lib.ListAllStrings(compFst, 1, xmlOutputLister);
            }

            out.write("    </" + outputsElmtName + ">");
            out.newLine();

            out.write("  </" + tokenElmtName + ">");
            out.newLine();
        }

        out.write("</" + rootElmtName + ">");
        out.newLine();
        out.flush();
        out.close();

    } catch (Exception e) {
        // KRB:  review this
        System.out.println("Exception found while testing input from file.");
        e.printStackTrace();
    }
    return data;
}

From source file:ffx.potential.parsers.BiojavaFilter.java

/**
 * <p>//  w w w . j a v a  2s. c  o m
 * writeFile</p>
 *
 * @param saveFile a {@link java.io.File} object.
 * @param append a {@link java.lang.StringBuilder} object.
 * @param printLinear Whether to print atoms linearly or by element
 * @return Success of writing.
 */
public boolean writeFile(File saveFile, boolean append, boolean printLinear) {
    if (saveFile == null) {
        return false;
    }

    if (vdwH) {
        logger.info(" Printing hydrogens to van der Waals centers instead of nuclear locations.");
    }

    /**
     * Create StringBuilders for ATOM, ANISOU and TER records that can be
     * reused.
     */
    StringBuilder sb = new StringBuilder("ATOM  ");
    StringBuilder anisouSB = new StringBuilder("ANISOU");
    StringBuilder terSB = new StringBuilder("TER   ");
    for (int i = 6; i < 80; i++) {
        sb.append(' ');
        anisouSB.append(' ');
        terSB.append(' ');
    }
    FileWriter fw;
    BufferedWriter bw;
    try {
        File newFile = saveFile;
        if (!append) {
            newFile = version(saveFile);
        }
        activeMolecularAssembly.setFile(newFile);
        activeMolecularAssembly.setName(newFile.getName());
        logger.log(Level.INFO, " Saving {0}", newFile.getName());
        fw = new FileWriter(newFile, append);
        bw = new BufferedWriter(fw);
        // =============================================================================
        // The CRYST1 record presents the unit cell parameters, space group, and Z
        // value. If the structure was not determined by crystallographic means, CRYST1
        // simply provides the unitary values, with an appropriate REMARK.
        //
        //  7 - 15       Real(9.3)     a              a (Angstroms).
        // 16 - 24       Real(9.3)     b              b (Angstroms).
        // 25 - 33       Real(9.3)     c              c (Angstroms).
        // 34 - 40       Real(7.2)     alpha          alpha (degrees).
        // 41 - 47       Real(7.2)     beta           beta (degrees).
        // 48 - 54       Real(7.2)     gamma          gamma (degrees).
        // 56 - 66       LString       sGroup         Space  group.
        // 67 - 70       Integer       z              Z value.
        // =============================================================================
        Crystal crystal = activeMolecularAssembly.getCrystal();
        if (crystal != null && !crystal.aperiodic()) {
            Crystal c = crystal.getUnitCell();
            if (!listMode) {
                bw.write(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s\n", c.a, c.b, c.c, c.alpha, c.beta,
                        c.gamma, padRight(c.spaceGroup.pdbName, 10)));
            } else {
                listOutput.add(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s", c.a, c.b, c.c, c.alpha,
                        c.beta, c.gamma, padRight(c.spaceGroup.pdbName, 10)));
            }
        }
        // =============================================================================
        // The SSBOND record identifies each disulfide bond in protein and polypeptide
        // structures by identifying the two residues involved in the bond.
        // The disulfide bond distance is included after the symmetry operations at
        // the end of the SSBOND record.
        //
        //  8 - 10        Integer         serNum       Serial number.
        // 12 - 14        LString(3)      "CYS"        Residue name.
        // 16             Character       chainID1     Chain identifier.
        // 18 - 21        Integer         seqNum1      Residue sequence number.
        // 22             AChar           icode1       Insertion code.
        // 26 - 28        LString(3)      "CYS"        Residue name.
        // 30             Character       chainID2     Chain identifier.
        // 32 - 35        Integer         seqNum2      Residue sequence number.
        // 36             AChar           icode2       Insertion code.
        // 60 - 65        SymOP           sym1         Symmetry oper for 1st resid
        // 67 - 72        SymOP           sym2         Symmetry oper for 2nd resid
        // 74  78        Real(5.2)      Length        Disulfide bond distance
        //
        // If SG of cysteine is disordered then there are possible alternate linkages.
        // wwPDB practice is to put together all possible SSBOND records. This is
        // problematic because the alternate location identifier is not specified in
        // the SSBOND record.
        // =============================================================================
        int serNum = 1;
        Polymer polymers[] = activeMolecularAssembly.getChains();
        if (polymers != null) {
            for (Polymer polymer : polymers) {
                ArrayList<Residue> residues = polymer.getResidues();
                for (Residue residue : residues) {
                    if (residue.getName().equalsIgnoreCase("CYS")) {
                        List<Atom> cysAtoms = residue.getAtomList();
                        Atom SG1 = null;
                        for (Atom atom : cysAtoms) {
                            if (atom.getName().equalsIgnoreCase("SG")) {
                                SG1 = atom;
                                break;
                            }
                        }
                        List<Bond> bonds = SG1.getBonds();
                        for (Bond bond : bonds) {
                            Atom SG2 = bond.get1_2(SG1);
                            if (SG2.getName().equalsIgnoreCase("SG")) {
                                if (SG1.xyzIndex < SG2.xyzIndex) {
                                    bond.energy(false);
                                    if (!listMode) {
                                        bw.write(format("SSBOND %3d CYS %1s %4s    CYS %1s %4s %36s %5.2f\n",
                                                serNum++, SG1.getChainID().toString(),
                                                Hybrid36.encode(4, SG1.getResidueNumber()),
                                                SG2.getChainID().toString(),
                                                Hybrid36.encode(4, SG2.getResidueNumber()), "",
                                                bond.getValue()));
                                    } else {
                                        listOutput.add(
                                                format("SSBOND %3d CYS %1s %4s    CYS %1s %4s %36s %5.2f\n",
                                                        serNum++, SG1.getChainID().toString(),
                                                        Hybrid36.encode(4, SG1.getResidueNumber()),
                                                        SG2.getChainID().toString(),
                                                        Hybrid36.encode(4, SG2.getResidueNumber()), "",
                                                        bond.getValue()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // =============================================================================
        //
        //  7 - 11        Integer       serial       Atom serial number.
        // 13 - 16        Atom          name         Atom name.
        // 17             Character     altLoc       Alternate location indicator.
        // 18 - 20        Residue name  resName      Residue name.
        // 22             Character     chainID      Chain identifier.
        // 23 - 26        Integer       resSeq       Residue sequence number.
        // 27             AChar         iCode        Code for insertion of residues.
        // 31 - 38        Real(8.3)     x            Orthogonal coordinates for X in Angstroms.
        // 39 - 46        Real(8.3)     y            Orthogonal coordinates for Y in Angstroms.
        // 47 - 54        Real(8.3)     z            Orthogonal coordinates for Z in Angstroms.
        // 55 - 60        Real(6.2)     occupancy    Occupancy.
        // 61 - 66        Real(6.2)     tempFactor   Temperature factor.
        // 77 - 78        LString(2)    element      Element symbol, right-justified.
        // 79 - 80        LString(2)    charge       Charge  on the atom.
        // =============================================================================
        //         1         2         3         4         5         6         7
        //123456789012345678901234567890123456789012345678901234567890123456789012345678
        //ATOM      1  N   ILE A  16      60.614  71.140 -10.592  1.00  7.38           N
        //ATOM      2  CA  ILE A  16      60.793  72.149  -9.511  1.00  6.91           C
        MolecularAssembly molecularAssemblies[] = this.getMolecularAssemblys();
        int serial = 1;
        // Loop over biomolecular chains
        if (polymers != null) {
            for (Polymer polymer : polymers) {
                currentSegID = polymer.getName();
                currentChainID = polymer.getChainID();
                sb.setCharAt(21, currentChainID);
                // Loop over residues
                ArrayList<Residue> residues = polymer.getResidues();
                for (Residue residue : residues) {
                    String resName = residue.getName();
                    if (resName.length() > 3) {
                        resName = resName.substring(0, 3);
                    }
                    int resID = residue.getResidueNumber();
                    sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
                    sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
                    // Loop over atoms
                    ArrayList<Atom> residueAtoms = residue.getAtomList();
                    ArrayList<Atom> backboneAtoms = residue.getBackboneAtoms();
                    boolean altLocFound = false;
                    for (Atom atom : backboneAtoms) {
                        writeAtom(atom, serial++, sb, anisouSB, bw);
                        Character altLoc = atom.getAltLoc();
                        if (altLoc != null && !altLoc.equals(' ')) {
                            altLocFound = true;
                        }
                        residueAtoms.remove(atom);
                    }
                    for (Atom atom : residueAtoms) {
                        writeAtom(atom, serial++, sb, anisouSB, bw);
                        Character altLoc = atom.getAltLoc();
                        if (altLoc != null && !altLoc.equals(' ')) {
                            altLocFound = true;
                        }
                    }
                    // Write out alternate conformers
                    if (altLocFound) {
                        for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                            MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                            Polymer altPolymer = altMolecularAssembly.getPolymer(currentChainID, currentSegID,
                                    false);
                            Residue altResidue = altPolymer.getResidue(resName, resID, false);
                            backboneAtoms = altResidue.getBackboneAtoms();
                            residueAtoms = altResidue.getAtomList();
                            for (Atom atom : backboneAtoms) {
                                if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                        && !atom.getAltLoc().equals('A')) {
                                    writeAtom(atom, serial++, sb, anisouSB, bw);
                                }
                                residueAtoms.remove(atom);
                            }
                            for (Atom atom : residueAtoms) {
                                if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                        && !atom.getAltLoc().equals('A')) {
                                    writeAtom(atom, serial++, sb, anisouSB, bw);
                                }
                            }
                        }
                    }
                }
                terSB.replace(6, 11, String.format("%5s", Hybrid36.encode(5, serial++)));
                terSB.replace(12, 16, "    ");
                terSB.replace(16, 26, sb.substring(16, 26));
                if (!listMode) {
                    bw.write(terSB.toString());
                    bw.newLine();
                } else {
                    listOutput.add(terSB.toString());
                }
            }
        }
        sb.replace(0, 6, "HETATM");
        sb.setCharAt(21, 'A');
        int resID = 1;
        Polymer polymer = activeMolecularAssembly.getPolymer('A', "A", false);
        if (polymer != null) {
            ArrayList<Residue> residues = polymer.getResidues();
            for (Residue residue : residues) {
                int resID2 = residue.getResidueNumber();
                if (resID2 >= resID) {
                    resID = resID2 + 1;
                }
            }
        }

        /**
         * Loop over molecules, ions and then water.
         */
        ArrayList<Molecule> molecules = activeMolecularAssembly.getMolecules();
        for (int i = 0; i < molecules.size(); i++) {
            Molecule molecule = (Molecule) molecules.get(i);
            Character chainID = molecule.getChainID();
            sb.setCharAt(21, chainID);
            String resName = molecule.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> moleculeAtoms = molecule.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : moleculeAtoms) {
                writeAtom(atom, serial++, sb, anisouSB, bw);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altmolecule = altMolecularAssembly.getMolecules().get(i);
                    moleculeAtoms = altmolecule.getAtomList();
                    for (Atom atom : moleculeAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeAtom(atom, serial++, sb, anisouSB, bw);
                        }
                    }
                }
            }
            resID++;
        }

        ArrayList<MSNode> ions = activeMolecularAssembly.getIons();
        for (int i = 0; i < ions.size(); i++) {
            Molecule ion = (Molecule) ions.get(i);
            Character chainID = ion.getChainID();
            sb.setCharAt(21, chainID);
            String resName = ion.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> ionAtoms = ion.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : ionAtoms) {
                writeAtom(atom, serial++, sb, anisouSB, bw);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altion = altMolecularAssembly.getIons().get(i);
                    ionAtoms = altion.getAtomList();
                    for (Atom atom : ionAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeAtom(atom, serial++, sb, anisouSB, bw);
                        }
                    }
                }
            }
            resID++;
        }

        ArrayList<MSNode> waters = activeMolecularAssembly.getWaters();
        for (int i = 0; i < waters.size(); i++) {
            Molecule water = (Molecule) waters.get(i);
            Character chainID = water.getChainID();
            sb.setCharAt(21, chainID);
            String resName = water.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> waterAtoms = water.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : waterAtoms) {
                writeAtom(atom, serial++, sb, anisouSB, bw);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altwater = altMolecularAssembly.getWaters().get(i);
                    waterAtoms = altwater.getAtomList();
                    for (Atom atom : waterAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeAtom(atom, serial++, sb, anisouSB, bw);
                        }
                    }
                }
            }
            resID++;
        }

        if (!listMode) {
            bw.write("END");
            bw.newLine();
        } else {
            listOutput.add("END");
        }
        bw.close();
    } catch (Exception e) {
        String message = "Exception writing to file: " + saveFile.toString();
        logger.log(Level.WARNING, message, e);
        return false;
    }
    return true;
}

From source file:ffx.potential.parsers.BiojavaFilter.java

public boolean writeSIFTFile(File saveFile, boolean append, String[] resAndScore) {
    if (saveFile == null) {
        return false;
    }//from   w  w w  . j  a va 2s .com

    if (vdwH) {
        logger.info(" Printing hydrogens to van der Waals centers instead of nuclear locations.");
    }

    /**
     * Create StringBuilders for ATOM, ANISOU and TER records that can be
     * reused.
     */
    StringBuilder sb = new StringBuilder("ATOM  ");
    StringBuilder anisouSB = new StringBuilder("ANISOU");
    StringBuilder terSB = new StringBuilder("TER   ");
    for (int i = 6; i < 80; i++) {
        sb.append(' ');
        anisouSB.append(' ');
        terSB.append(' ');
    }
    FileWriter fw;
    BufferedWriter bw;
    try {
        File newFile = saveFile;
        if (!append) {
            newFile = version(saveFile);
        }
        activeMolecularAssembly.setFile(newFile);
        activeMolecularAssembly.setName(newFile.getName());
        logger.log(Level.INFO, " Saving {0}", newFile.getName());
        fw = new FileWriter(newFile, append);
        bw = new BufferedWriter(fw);
        // =============================================================================
        // The CRYST1 record presents the unit cell parameters, space group, and Z
        // value. If the structure was not determined by crystallographic means, CRYST1
        // simply provides the unitary values, with an appropriate REMARK.
        //
        //  7 - 15       Real(9.3)     a              a (Angstroms).
        // 16 - 24       Real(9.3)     b              b (Angstroms).
        // 25 - 33       Real(9.3)     c              c (Angstroms).
        // 34 - 40       Real(7.2)     alpha          alpha (degrees).
        // 41 - 47       Real(7.2)     beta           beta (degrees).
        // 48 - 54       Real(7.2)     gamma          gamma (degrees).
        // 56 - 66       LString       sGroup         Space  group.
        // 67 - 70       Integer       z              Z value.
        // =============================================================================
        Crystal crystal = activeMolecularAssembly.getCrystal();
        if (crystal != null && !crystal.aperiodic()) {
            Crystal c = crystal.getUnitCell();
            if (!listMode) {
                bw.write(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s\n", c.a, c.b, c.c, c.alpha, c.beta,
                        c.gamma, padRight(c.spaceGroup.pdbName, 10)));
            } else {
                listOutput.add(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s", c.a, c.b, c.c, c.alpha,
                        c.beta, c.gamma, padRight(c.spaceGroup.pdbName, 10)));
            }
        }
        // =============================================================================
        // The SSBOND record identifies each disulfide bond in protein and polypeptide
        // structures by identifying the two residues involved in the bond.
        // The disulfide bond distance is included after the symmetry operations at
        // the end of the SSBOND record.
        //
        //  8 - 10        Integer         serNum       Serial number.
        // 12 - 14        LString(3)      "CYS"        Residue name.
        // 16             Character       chainID1     Chain identifier.
        // 18 - 21        Integer         seqNum1      Residue sequence number.
        // 22             AChar           icode1       Insertion code.
        // 26 - 28        LString(3)      "CYS"        Residue name.
        // 30             Character       chainID2     Chain identifier.
        // 32 - 35        Integer         seqNum2      Residue sequence number.
        // 36             AChar           icode2       Insertion code.
        // 60 - 65        SymOP           sym1         Symmetry oper for 1st resid
        // 67 - 72        SymOP           sym2         Symmetry oper for 2nd resid
        // 74  78        Real(5.2)      Length        Disulfide bond distance
        //
        // If SG of cysteine is disordered then there are possible alternate linkages.
        // wwPDB practice is to put together all possible SSBOND records. This is
        // problematic because the alternate location identifier is not specified in
        // the SSBOND record.
        // =============================================================================
        int serNum = 1;
        Polymer polymers[] = activeMolecularAssembly.getChains();
        if (polymers != null) {
            for (Polymer polymer : polymers) {
                ArrayList<Residue> residues = polymer.getResidues();
                for (Residue residue : residues) {
                    if (residue.getName().equalsIgnoreCase("CYS")) {
                        List<Atom> cysAtoms = residue.getAtomList();
                        Atom SG1 = null;
                        for (Atom atom : cysAtoms) {
                            if (atom.getName().equalsIgnoreCase("SG")) {
                                SG1 = atom;
                                break;
                            }
                        }
                        List<Bond> bonds = SG1.getBonds();
                        for (Bond bond : bonds) {
                            Atom SG2 = bond.get1_2(SG1);
                            if (SG2.getName().equalsIgnoreCase("SG")) {
                                if (SG1.xyzIndex < SG2.xyzIndex) {
                                    bond.energy(false);
                                    if (!listMode) {
                                        bw.write(format("SSBOND %3d CYS %1s %4s    CYS %1s %4s %36s %5.2f\n",
                                                serNum++, SG1.getChainID().toString(),
                                                Hybrid36.encode(4, SG1.getResidueNumber()),
                                                SG2.getChainID().toString(),
                                                Hybrid36.encode(4, SG2.getResidueNumber()), "",
                                                bond.getValue()));
                                    } else {
                                        listOutput.add(
                                                format("SSBOND %3d CYS %1s %4s    CYS %1s %4s %36s %5.2f\n",
                                                        serNum++, SG1.getChainID().toString(),
                                                        Hybrid36.encode(4, SG1.getResidueNumber()),
                                                        SG2.getChainID().toString(),
                                                        Hybrid36.encode(4, SG2.getResidueNumber()), "",
                                                        bond.getValue()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // =============================================================================
        //
        //  7 - 11        Integer       serial       Atom serial number.
        // 13 - 16        Atom          name         Atom name.
        // 17             Character     altLoc       Alternate location indicator.
        // 18 - 20        Residue name  resName      Residue name.
        // 22             Character     chainID      Chain identifier.
        // 23 - 26        Integer       resSeq       Residue sequence number.
        // 27             AChar         iCode        Code for insertion of residues.
        // 31 - 38        Real(8.3)     x            Orthogonal coordinates for X in Angstroms.
        // 39 - 46        Real(8.3)     y            Orthogonal coordinates for Y in Angstroms.
        // 47 - 54        Real(8.3)     z            Orthogonal coordinates for Z in Angstroms.
        // 55 - 60        Real(6.2)     occupancy    Occupancy.
        // 61 - 66        Real(6.2)     tempFactor   Temperature factor.
        // 77 - 78        LString(2)    element      Element symbol, right-justified.
        // 79 - 80        LString(2)    charge       Charge  on the atom.
        // =============================================================================
        //         1         2         3         4         5         6         7
        //123456789012345678901234567890123456789012345678901234567890123456789012345678
        //ATOM      1  N   ILE A  16      60.614  71.140 -10.592  1.00  7.38           N
        //ATOM      2  CA  ILE A  16      60.793  72.149  -9.511  1.00  6.91           C
        MolecularAssembly molecularAssemblies[] = this.getMolecularAssemblys();
        int serial = 1;
        // Loop over biomolecular chains
        if (polymers != null) {
            for (Polymer polymer : polymers) {
                currentSegID = polymer.getName();
                currentChainID = polymer.getChainID();
                sb.setCharAt(21, currentChainID);
                // Loop over residues
                ArrayList<Residue> residues = polymer.getResidues();
                for (Residue residue : residues) {
                    String resName = residue.getName();
                    if (resName.length() > 3) {
                        resName = resName.substring(0, 3);
                    }
                    int resID = residue.getResidueNumber();
                    int i = 0;
                    String[] entries = null;
                    for (; i < resAndScore.length; i++) {
                        entries = resAndScore[i].split("\\t");
                        if (!entries[0].equals(entries[0].replaceAll("\\D+", ""))) {
                            String[] subEntries = entries[0].split("[^0-9]");
                            entries[0] = subEntries[0];
                        }
                        if (entries[0].equals(String.valueOf(resID)) && !".".equals(entries[1])) {
                            break;
                        }
                    }
                    sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
                    sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
                    // Loop over atoms
                    ArrayList<Atom> residueAtoms = residue.getAtomList();
                    boolean altLocFound = false;
                    for (Atom atom : residueAtoms) {
                        if (i != resAndScore.length) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, entries[1]);
                        } else {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                        Character altLoc = atom.getAltLoc();
                        if (altLoc != null && !altLoc.equals(' ')) {
                            altLocFound = true;
                        }
                    }
                    // Write out alternate conformers
                    if (altLocFound) {
                        for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                            MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                            Polymer altPolymer = altMolecularAssembly.getPolymer(currentChainID, currentSegID,
                                    false);
                            Residue altResidue = altPolymer.getResidue(resName, resID, false);
                            residueAtoms = altResidue.getAtomList();
                            for (Atom atom : residueAtoms) {
                                if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                        && !atom.getAltLoc().equals('A')) {
                                    if (i != resAndScore.length) {
                                        writeSIFTAtom(atom, serial++, sb, anisouSB, bw, entries[1]);
                                    } else {
                                        writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                                    }
                                }
                            }
                        }
                    }
                }
                terSB.replace(6, 11, String.format("%5s", Hybrid36.encode(5, serial++)));
                terSB.replace(12, 16, "    ");
                terSB.replace(16, 26, sb.substring(16, 26));
                if (!listMode) {
                    bw.write(terSB.toString());
                    bw.newLine();
                } else {
                    listOutput.add(terSB.toString());
                }
            }
        }
        sb.replace(0, 6, "HETATM");
        sb.setCharAt(21, 'A');
        int resID = 1;
        Polymer polymer = activeMolecularAssembly.getPolymer('A', "A", false);
        if (polymer != null) {
            ArrayList<Residue> residues = polymer.getResidues();
            for (Residue residue : residues) {
                int resID2 = residue.getResidueNumber();
                if (resID2 >= resID) {
                    resID = resID2 + 1;
                }
            }
        }

        /**
         * Loop over molecules, ions and then water.
         */
        ArrayList<Molecule> molecules = activeMolecularAssembly.getMolecules();
        for (int i = 0; i < molecules.size(); i++) {
            Molecule molecule = (Molecule) molecules.get(i);
            Character chainID = molecule.getChainID();
            sb.setCharAt(21, chainID);
            String resName = molecule.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> moleculeAtoms = molecule.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : moleculeAtoms) {
                writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altmolecule = altMolecularAssembly.getMolecules().get(i);
                    moleculeAtoms = altmolecule.getAtomList();
                    for (Atom atom : moleculeAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                    }
                }
            }
            resID++;
        }

        ArrayList<MSNode> ions = activeMolecularAssembly.getIons();
        for (int i = 0; i < ions.size(); i++) {
            Molecule ion = (Molecule) ions.get(i);
            Character chainID = ion.getChainID();
            sb.setCharAt(21, chainID);
            String resName = ion.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> ionAtoms = ion.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : ionAtoms) {
                writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altion = altMolecularAssembly.getIons().get(i);
                    ionAtoms = altion.getAtomList();
                    for (Atom atom : ionAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                    }
                }
            }
            resID++;
        }

        ArrayList<MSNode> waters = activeMolecularAssembly.getWaters();
        for (int i = 0; i < waters.size(); i++) {
            Molecule water = (Molecule) waters.get(i);
            Character chainID = water.getChainID();
            sb.setCharAt(21, chainID);
            String resName = water.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> waterAtoms = water.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : waterAtoms) {
                writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altwater = altMolecularAssembly.getWaters().get(i);
                    waterAtoms = altwater.getAtomList();
                    for (Atom atom : waterAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                    }
                }
            }
            resID++;
        }

        if (!listMode) {
            bw.write("END");
            bw.newLine();
        } else {
            listOutput.add("END");
        }
        bw.close();
    } catch (Exception e) {
        String message = "Exception writing to file: " + saveFile.toString();
        logger.log(Level.WARNING, message, e);
        return false;
    }
    return true;
}

From source file:ffx.potential.parsers.PDBFilter.java

public boolean writeSIFTFile(File saveFile, boolean append, String[] resAndScore) {
    if (saveFile == null) {
        return false;
    }/*  ww  w.  j  a  v  a 2s.  c  o m*/

    if (vdwH) {
        logger.info(" Printing hydrogens to van der Waals centers instead of nuclear locations.");
    }

    if (nSymOp != 0) {
        logger.info(String.format(" Printing atoms with symmetry operator %s",
                activeMolecularAssembly.getCrystal().spaceGroup.getSymOp(nSymOp).toString()));
    }

    /**
     * Create StringBuilders for ATOM, ANISOU and TER records that can be
     * reused.
     */
    StringBuilder sb = new StringBuilder("ATOM  ");
    StringBuilder anisouSB = new StringBuilder("ANISOU");
    StringBuilder terSB = new StringBuilder("TER   ");
    for (int i = 6; i < 80; i++) {
        sb.append(' ');
        anisouSB.append(' ');
        terSB.append(' ');
    }
    FileWriter fw;
    BufferedWriter bw;
    try {
        File newFile = saveFile;
        if (!append && !noVersioning) {
            newFile = version(saveFile);
        }
        activeMolecularAssembly.setFile(newFile);
        activeMolecularAssembly.setName(newFile.getName());
        if (logWrites) {
            logger.log(Level.INFO, " Saving {0}", newFile.getName());
        }
        fw = new FileWriter(newFile, append);
        bw = new BufferedWriter(fw);
        // =============================================================================
        // The CRYST1 record presents the unit cell parameters, space group, and Z
        // value. If the structure was not determined by crystallographic means, CRYST1
        // simply provides the unitary values, with an appropriate REMARK.
        //
        //  7 - 15       Real(9.3)     a              a (Angstroms).
        // 16 - 24       Real(9.3)     b              b (Angstroms).
        // 25 - 33       Real(9.3)     c              c (Angstroms).
        // 34 - 40       Real(7.2)     alpha          alpha (degrees).
        // 41 - 47       Real(7.2)     beta           beta (degrees).
        // 48 - 54       Real(7.2)     gamma          gamma (degrees).
        // 56 - 66       LString       sGroup         Space  group.
        // 67 - 70       Integer       z              Z value.
        // =============================================================================
        Crystal crystal = activeMolecularAssembly.getCrystal();
        if (crystal != null && !crystal.aperiodic()) {
            Crystal c = crystal.getUnitCell();
            if (!listMode) {
                bw.write(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s\n", c.a, c.b, c.c, c.alpha, c.beta,
                        c.gamma, padRight(c.spaceGroup.pdbName, 10)));
            } else {
                listOutput.add(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s", c.a, c.b, c.c, c.alpha,
                        c.beta, c.gamma, padRight(c.spaceGroup.pdbName, 10)));
            }
        }
        // =============================================================================
        // The SSBOND record identifies each disulfide bond in protein and polypeptide
        // structures by identifying the two residues involved in the bond.
        // The disulfide bond distance is included after the symmetry operations at
        // the end of the SSBOND record.
        //
        //  8 - 10        Integer         serNum       Serial number.
        // 12 - 14        LString(3)      "CYS"        Residue name.
        // 16             Character       chainID1     Chain identifier.
        // 18 - 21        Integer         seqNum1      Residue sequence number.
        // 22             AChar           icode1       Insertion code.
        // 26 - 28        LString(3)      "CYS"        Residue name.
        // 30             Character       chainID2     Chain identifier.
        // 32 - 35        Integer         seqNum2      Residue sequence number.
        // 36             AChar           icode2       Insertion code.
        // 60 - 65        SymOP           sym1         Symmetry oper for 1st resid
        // 67 - 72        SymOP           sym2         Symmetry oper for 2nd resid
        // 74  78        Real(5.2)      Length        Disulfide bond distance
        //
        // If SG of cysteine is disordered then there are possible alternate linkages.
        // wwPDB practice is to put together all possible SSBOND records. This is
        // problematic because the alternate location identifier is not specified in
        // the SSBOND record.
        // =============================================================================
        int serNum = 1;
        Polymer polymers[] = activeMolecularAssembly.getChains();
        if (polymers != null) {
            for (Polymer polymer : polymers) {
                ArrayList<Residue> residues = polymer.getResidues();
                for (Residue residue : residues) {
                    if (residue.getName().equalsIgnoreCase("CYS")) {
                        List<Atom> cysAtoms = residue.getAtomList();
                        Atom SG1 = null;
                        for (Atom atom : cysAtoms) {
                            if (atom.getName().equalsIgnoreCase("SG")) {
                                SG1 = atom;
                                break;
                            }
                        }
                        List<Bond> bonds = SG1.getBonds();
                        for (Bond bond : bonds) {
                            Atom SG2 = bond.get1_2(SG1);
                            if (SG2.getName().equalsIgnoreCase("SG")) {
                                if (SG1.xyzIndex < SG2.xyzIndex) {
                                    bond.energy(false);
                                    if (!listMode) {
                                        bw.write(format("SSBOND %3d CYS %1s %4s    CYS %1s %4s %36s %5.2f\n",
                                                serNum++, SG1.getChainID().toString(),
                                                Hybrid36.encode(4, SG1.getResidueNumber()),
                                                SG2.getChainID().toString(),
                                                Hybrid36.encode(4, SG2.getResidueNumber()), "",
                                                bond.getValue()));
                                    } else {
                                        listOutput.add(
                                                format("SSBOND %3d CYS %1s %4s    CYS %1s %4s %36s %5.2f\n",
                                                        serNum++, SG1.getChainID().toString(),
                                                        Hybrid36.encode(4, SG1.getResidueNumber()),
                                                        SG2.getChainID().toString(),
                                                        Hybrid36.encode(4, SG2.getResidueNumber()), "",
                                                        bond.getValue()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // =============================================================================
        //
        //  7 - 11        Integer       serial       Atom serial number.
        // 13 - 16        Atom          name         Atom name.
        // 17             Character     altLoc       Alternate location indicator.
        // 18 - 20        Residue name  resName      Residue name.
        // 22             Character     chainID      Chain identifier.
        // 23 - 26        Integer       resSeq       Residue sequence number.
        // 27             AChar         iCode        Code for insertion of residues.
        // 31 - 38        Real(8.3)     x            Orthogonal coordinates for X in Angstroms.
        // 39 - 46        Real(8.3)     y            Orthogonal coordinates for Y in Angstroms.
        // 47 - 54        Real(8.3)     z            Orthogonal coordinates for Z in Angstroms.
        // 55 - 60        Real(6.2)     occupancy    Occupancy.
        // 61 - 66        Real(6.2)     tempFactor   Temperature factor.
        // 77 - 78        LString(2)    element      Element symbol, right-justified.
        // 79 - 80        LString(2)    charge       Charge  on the atom.
        // =============================================================================
        //         1         2         3         4         5         6         7
        //123456789012345678901234567890123456789012345678901234567890123456789012345678
        //ATOM      1  N   ILE A  16      60.614  71.140 -10.592  1.00  7.38           N
        //ATOM      2  CA  ILE A  16      60.793  72.149  -9.511  1.00  6.91           C
        MolecularAssembly molecularAssemblies[] = this.getMolecularAssemblys();
        int serial = 1;
        // Loop over biomolecular chains
        if (polymers != null) {
            for (Polymer polymer : polymers) {
                currentSegID = polymer.getName();
                currentChainID = polymer.getChainID();
                sb.setCharAt(21, currentChainID);
                // Loop over residues
                ArrayList<Residue> residues = polymer.getResidues();
                for (Residue residue : residues) {
                    String resName = residue.getName();
                    if (resName.length() > 3) {
                        resName = resName.substring(0, 3);
                    }
                    int resID = residue.getResidueNumber();
                    int i = 0;
                    String[] entries = null;
                    for (; i < resAndScore.length; i++) {
                        entries = resAndScore[i].split("\\t");
                        if (!entries[0].equals(entries[0].replaceAll("\\D+", ""))) {
                            String[] subEntries = entries[0].split("[^0-9]");
                            entries[0] = subEntries[0];
                        }
                        if (entries[0].equals(String.valueOf(resID)) && !".".equals(entries[1])) {
                            break;
                        }
                    }
                    sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
                    sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
                    // Loop over atoms
                    ArrayList<Atom> residueAtoms = residue.getAtomList();
                    boolean altLocFound = false;
                    for (Atom atom : residueAtoms) {
                        if (i != resAndScore.length) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, entries[1]);
                        } else {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                        Character altLoc = atom.getAltLoc();
                        if (altLoc != null && !altLoc.equals(' ')) {
                            altLocFound = true;
                        }
                    }
                    // Write out alternate conformers
                    if (altLocFound) {
                        for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                            MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                            Polymer altPolymer = altMolecularAssembly.getPolymer(currentChainID, currentSegID,
                                    false);
                            Residue altResidue = altPolymer.getResidue(resName, resID, false);
                            residueAtoms = altResidue.getAtomList();
                            for (Atom atom : residueAtoms) {
                                if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                        && !atom.getAltLoc().equals('A')) {
                                    if (i != resAndScore.length) {
                                        writeSIFTAtom(atom, serial++, sb, anisouSB, bw, entries[1]);
                                    } else {
                                        writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                                    }
                                }
                            }
                        }
                    }
                }
                terSB.replace(6, 11, String.format("%5s", Hybrid36.encode(5, serial++)));
                terSB.replace(12, 16, "    ");
                terSB.replace(16, 26, sb.substring(16, 26));
                if (!listMode) {
                    bw.write(terSB.toString());
                    bw.newLine();
                } else {
                    listOutput.add(terSB.toString());
                }
            }
        }
        sb.replace(0, 6, "HETATM");
        sb.setCharAt(21, 'A');
        int resID = 1;
        Polymer polymer = activeMolecularAssembly.getPolymer('A', "A", false);
        if (polymer != null) {
            ArrayList<Residue> residues = polymer.getResidues();
            for (Residue residue : residues) {
                int resID2 = residue.getResidueNumber();
                if (resID2 >= resID) {
                    resID = resID2 + 1;
                }
            }
        }

        /**
         * Loop over molecules, ions and then water.
         */
        ArrayList<Molecule> molecules = activeMolecularAssembly.getMolecules();
        for (int i = 0; i < molecules.size(); i++) {
            Molecule molecule = (Molecule) molecules.get(i);
            Character chainID = molecule.getChainID();
            sb.setCharAt(21, chainID);
            String resName = molecule.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> moleculeAtoms = molecule.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : moleculeAtoms) {
                writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altmolecule = altMolecularAssembly.getMolecules().get(i);
                    moleculeAtoms = altmolecule.getAtomList();
                    for (Atom atom : moleculeAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                    }
                }
            }
            resID++;
        }

        ArrayList<MSNode> ions = activeMolecularAssembly.getIons();
        for (int i = 0; i < ions.size(); i++) {
            Molecule ion = (Molecule) ions.get(i);
            Character chainID = ion.getChainID();
            sb.setCharAt(21, chainID);
            String resName = ion.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> ionAtoms = ion.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : ionAtoms) {
                writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altion = altMolecularAssembly.getIons().get(i);
                    ionAtoms = altion.getAtomList();
                    for (Atom atom : ionAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                    }
                }
            }
            resID++;
        }

        ArrayList<MSNode> waters = activeMolecularAssembly.getWaters();
        for (int i = 0; i < waters.size(); i++) {
            Molecule water = (Molecule) waters.get(i);
            Character chainID = water.getChainID();
            sb.setCharAt(21, chainID);
            String resName = water.getResidueName();
            if (resName.length() > 3) {
                resName = resName.substring(0, 3);
            }
            sb.replace(17, 20, padLeft(resName.toUpperCase(), 3));
            sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID)));
            ArrayList<Atom> waterAtoms = water.getAtomList();
            boolean altLocFound = false;
            for (Atom atom : waterAtoms) {
                writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                Character altLoc = atom.getAltLoc();
                if (altLoc != null && !altLoc.equals(' ')) {
                    altLocFound = true;
                }
            }
            // Write out alternate conformers
            if (altLocFound) {
                for (int ma = 1; ma < molecularAssemblies.length; ma++) {
                    MolecularAssembly altMolecularAssembly = molecularAssemblies[ma];
                    MSNode altwater = altMolecularAssembly.getWaters().get(i);
                    waterAtoms = altwater.getAtomList();
                    for (Atom atom : waterAtoms) {
                        if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ')
                                && !atom.getAltLoc().equals('A')) {
                            writeSIFTAtom(atom, serial++, sb, anisouSB, bw, null);
                        }
                    }
                }
            }
            resID++;
        }

        if (!listMode) {
            bw.write("END");
            bw.newLine();
        } else {
            listOutput.add("END");
        }
        bw.close();
    } catch (Exception e) {
        String message = "Exception writing to file: " + saveFile.toString();
        logger.log(Level.WARNING, message, e);
        return false;
    }
    return true;
}