Example usage for org.apache.commons.io FilenameUtils removeExtension

List of usage examples for org.apache.commons.io FilenameUtils removeExtension

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils removeExtension.

Prototype

public static String removeExtension(String filename) 

Source Link

Document

Removes the extension from a filename.

Usage

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Generates a style based on a graphic.
 * //from  ww w. j  a v  a 2  s .  c om
 * @param graphicsPath the graphic.
 * @return the generated style.
 * @throws IOException
 */
public static StyleWrapper createStyleFromGraphic(File graphicsPath) throws IOException {
    String name = graphicsPath.getName();
    ExternalGraphic exGraphic = null;
    if (name.toLowerCase().endsWith(".png")) {
        exGraphic = sf.createExternalGraphic(graphicsPath.toURI().toURL(), "image/png");
    } else if (name.toLowerCase().endsWith(".svg")) {
        exGraphic = sf.createExternalGraphic(graphicsPath.toURI().toURL(), "image/svg+xml");
    } else if (name.toLowerCase().endsWith(".sld")) {
        StyledLayerDescriptor sld = readStyle(graphicsPath);
        Style style = SLDs.getDefaultStyle(sld);
        return new StyleWrapper(style);
    }

    if (exGraphic == null) {
        throw new IOException("Style could not be created!");
    }

    Graphic gr = sf.createDefaultGraphic();
    gr.graphicalSymbols().clear();
    gr.graphicalSymbols().add(exGraphic);
    Expression size = ff.literal(20);
    gr.setSize(size);

    Rule rule = sf.createRule();
    PointSymbolizer pointSymbolizer = sf.createPointSymbolizer(gr, null);
    rule.symbolizers().add(pointSymbolizer);

    FeatureTypeStyle featureTypeStyle = sf.createFeatureTypeStyle();
    featureTypeStyle.rules().add(rule);

    Style namedStyle = sf.createStyle();
    namedStyle.featureTypeStyles().add(featureTypeStyle);
    namedStyle.setName(FilenameUtils.removeExtension(name));

    return new StyleWrapper(namedStyle);
}

From source file:com.mgmtp.perfload.loadprofiles.ui.AppFrame.java

/**
 * Exports the events file for perfLoad tests. This method is registered on the {@link EventBus}
 * and called when the specified event is posted.
 * //from   w  w w  .j  a  v  a2s  . co  m
 * @param e
 *            the event that triggers calling of this method when posted on the event bus
 */
@Subscribe
public void exportEventListForPerfLoad(final ToolsExportEventListAction.Event e) throws IOException {
    if (checkLoadProfileEntityDirty() && checkLoadProfilePropertiesDirty()) {
        File dir = loadProfileEventsFile != null ? loadProfileEventsFile
                : loadProfileConfigFile.getParentFile();
        JFileChooser fc = SwingUtils.createFileChooser(dir,
                "Load Profile BaseLoadProfileEvent Files (*.perfload)", "perfload");
        fc.setAccessory(new SaveAccessoryPanel());

        if (loadProfileEventsFile == null) {
            loadProfileEventsFile = new File(
                    FilenameUtils.removeExtension(loadProfileConfigFile.getAbsolutePath()) + ".perfload");
        }

        File file = showSaveDialog(fc, loadProfileEventsFile, "perfload");
        if (file != null) {
            loadProfileEventsFile = file;

            LoadProfileConfig lpc = createLoadProfileConfig();
            LoadTestConfiguration ltc = loadProfilesController.createLoadTestConfiguration(lpc,
                    getSelectedTargets(), getSelectedClients());

            List<LoadCurveAssignment> loadCurveAssignments = ltc.getLoadCurveAssignments();
            Set<Operation> operations = newHashSet();
            int caCount = loadCurveAssignments.size();

            double maxTime = 0; // max time for histogram creation

            List<LoadCurve> loadCurves = newArrayListWithCapacity(caCount);
            for (LoadCurveAssignment loadCurveAssignment : loadCurveAssignments) {
                LoadCurve loadCurve = loadCurveAssignment.getLoadCurve();
                loadCurves.add(loadCurve);
                operations.add(loadCurveAssignment.getOperation());
                double[] timeValues = loadCurve.getTimeValues();
                maxTime = max(maxTime, timeValues[timeValues.length - 1]);
            }

            EventDistributor.addScaledLoadCurvesToAssignments(ltc, loadCurves);

            List<LoadEvent> clientEventList = EventDistributor.createClientEventList(ltc);
            List<BaseLoadProfileEvent> events = newArrayListWithExpectedSize(clientEventList.size());

            // One time and marker events are added separately

            for (OneTime oneTime : getOneTimes()) {
                double startTimeInHours = oneTime.t0 / 60d;

                // We must add one event per target
                for (Target target : oneTime.targets) {
                    LoadEvent event = new LoadEvent(startTimeInHours, oneTime.getOperation());
                    event.setProcessId(0); // 1 added later to make it zero-based
                    event.setDaemonId(1);
                    event.setTarget(target);
                    clientEventList.add(event);
                }
            }

            events.addAll(clientEventList);

            for (Marker marker : getMarkers()) {
                double time = marker.left / 60d;
                MarkerEvent event = new MarkerEvent(marker.name, time, MarkerEvent.Type.left);
                events.add(event);

                time = marker.right / 60d;
                event = new MarkerEvent(marker.name, time, MarkerEvent.Type.right);
                events.add(event);
            }

            Collections.sort(events, new LoadEventComparator());

            StrBuilder sb = new StrBuilder();
            sb.appendln("# Created: " + new Date());
            sb.appendln("# Load Profile Config File: " + loadProfileConfigFile.getName());
            sb.append("# Load Profile Name: " + txtName.getText());

            EventDistributor.writeEventListForPerfLoadClientsToFile(file, sb.toString(), events);

            // Create additional histogram file if selected
            dir = file.getParentFile();
            final String baseName = FilenameUtils.getBaseName(file.getName());
            int numClients = ltc.getClients().size();
            SaveAccessoryPanel sap = (SaveAccessoryPanel) fc.getAccessory();
            Collection<LoadEvent> loadEvents = transform(filter(clientEventList, new IsLoadEventPredicate()),
                    new EventToLoadEventFunction());

            if (sap.isEventDistriChecked()) {
                for (int i = 0; i < numClients; ++i) {
                    for (LoadCurve loadCurve : loadCurves) {
                        File f = new File(dir,
                                baseName + "-event-distri-client-" + i + "-" + loadCurve.getName() + ".csv");
                        PlotFileCreator.createPlot(f, loadEvents, loadCurve, i,
                                LoadCurveCalculator.timeUnit_minute);
                    }
                }
            }

            if (sap.isOperationHistogramChecked()) {
                for (Operation operation : operations) {
                    String opName = operation.getName();
                    File f = new File(dir, baseName + "-histogram-operation-" + opName + ".csv");
                    PlotFileCreator.createOperationHistogram(f, loadEvents, opName, (int) maxTime * 2, 0.,
                            maxTime, LoadCurveCalculator.timeUnit_minute);
                }
            }

            if (sap.isClientLoadHistrogramChecked()) {
                for (int i = 0; i < numClients; i++) {
                    File f = new File(dir, baseName + "-histogram-client-load-" + i + ".csv");
                    PlotFileCreator.createClientHistogram(f, loadEvents, i, (int) maxTime * 2, 0., maxTime,
                            LoadCurveCalculator.timeUnit_minute);
                }
            }
        }
    }
}

From source file:ffx.algorithms.mc.RosenbluthChiAllMove.java

/**
 * For validation. Performs Monte Carlo chi moves WITHOUT biasing.
 * Give ALL CHIs a random theta simultaneously.
 * Accept on the vanilla Metropolis criterion.
 *///from w w  w . j a va 2 s  . c  om
private boolean engage_controlAll() {
    report.append(String.format(" Rosenbluth Control Move: %4d  %s\n", moveNumber, target));
    double origEnergy = totalEnergy();
    double origChi[] = RotamerLibrary.measureRotamer(target, false);
    double newChi[] = new double[origChi.length];
    System.arraycopy(origChi, 0, newChi, 0, origChi.length);
    for (int i = 0; i < origChi.length; i++) {
        if (doChi[i]) {
            double theta = rand.nextDouble(360.0) - 180;
            newChi[i] = theta;
        }
    }
    proposedChis = newChi;
    Rotamer newState = createRotamer(target, newChi);
    RotamerLibrary.applyRotamer(target, newState);

    finalEnergy = totalEnergy();
    if (this.finalEnergy < CATASTROPHE_THRESHOLD) {
        report.append("\nWARNING: Multipole catastrophe in CBMC.\n");
        report.append("  Discarding move.\n");
        target.revertState(origState);
        updateAll();
        Wn = -1.0;
        Wo = 1000;
        logger.info(report.toString());
        return false;
    }

    double dU = finalEnergy - origEnergy;
    double criterion = FastMath.exp(-beta * dU);
    double rng = rand.nextDouble();
    report.append(String.format("    move (thetas):    "));
    for (int i = 0; i < newChi.length; i++) {
        report.append(String.format("%7.2f ", newChi[i]));
    }
    report.append(String.format("\n"));
    report.append(String.format("    orig, final, dU:  %.2g %.2g %.2g\n", origEnergy, finalEnergy, dU));
    report.append(String.format("    crit, rng:        %.2g %.2g\n", criterion, rng));
    if (rng < criterion) {
        accepted = true;
        numAccepted++;
        report.append(String.format(" Accepted! %5d    NewEnergy: %.4f    Chi:", numAccepted, finalEnergy));
        for (int k = 0; k < proposedChis.length; k++) {
            report.append(String.format(" %7.2f", proposedChis[k]));
        }
        report.append(String.format("\n"));
        updateAll();
        if (!noSnaps) {
            PDBFilter writer = new PDBFilter(mola.getFile(), mola, null, null);
            String filename = FilenameUtils.removeExtension(mola.getFile().toString());
            filename = mola.getFile().getAbsolutePath();
            if (!filename.contains("_mc")) {
                filename = FilenameUtils.removeExtension(filename) + "_mc.pdb";
            }
            File file = new File(filename);
            writer.writeFile(file, false);
        }
    } else {
        accepted = false;
        report.append(String.format(" Denied.   %5d    NewEnergy: %.4f    Chi:", numAccepted, origEnergy));
        for (int k = 0; k < origChi.length; k++) {
            report.append(String.format(" %7.2f", origChi[k]));
        }
        report.append(String.format("\n"));
        target.revertState(origState);
    }

    updateAll();
    endTime = System.nanoTime();
    double took = (endTime - startTime) * NS_TO_MS;
    if (logTimings) {
        report.append(String.format("   Timing (ms): %.2f", took));
    }
    logger.info(report.toString());
    return accepted;
}

From source file:net.minecraftforge.common.ForgeHooks.java

private static boolean loadAdvancements(Map<ResourceLocation, Advancement.Builder> map, ModContainer mod) {
    return CraftingHelper.findFiles(mod, "assets/" + mod.getModId() + "/advancements", null, (root, file) -> {

        String relative = root.relativize(file).toString();
        if (!"json".equals(FilenameUtils.getExtension(file.toString())) || relative.startsWith("_"))
            return true;

        String name = FilenameUtils.removeExtension(relative).replaceAll("\\\\", "/");
        ResourceLocation key = new ResourceLocation(mod.getModId(), name);

        if (!map.containsKey(key)) {
            BufferedReader reader = null;

            try {
                reader = Files.newBufferedReader(file);
                Advancement.Builder builder = JsonUtils.fromJson(AdvancementManager.GSON, reader,
                        Advancement.Builder.class);
                map.put(key, builder);/*  w  ww .  j  ava  2  s .  c  o  m*/
            } catch (JsonParseException jsonparseexception) {
                FMLLog.log.error("Parsing error loading built-in advancement " + key,
                        (Throwable) jsonparseexception);
                return false;
            } catch (IOException ioexception) {
                FMLLog.log.error("Couldn't read advancement " + key + " from " + file, (Throwable) ioexception);
                return false;
            } finally {
                IOUtils.closeQuietly(reader);
            }
        }

        return true;
    });
}

From source file:it.drwolf.ridire.session.async.Mapper.java

private File uncompressGzippedArcFile(File f) throws IOException {
    FileInputStream fin = new FileInputStream(f.getAbsolutePath());
    BufferedInputStream in = new BufferedInputStream(fin);
    File uncompressedFile = new File(FilenameUtils.removeExtension(f.getAbsolutePath()));
    FileOutputStream out = new FileOutputStream(uncompressedFile);
    GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in, true);
    final byte[] buffer = new byte[1024];
    int n = 0;// www .j  av a 2 s.  c o m
    while (-1 != (n = gzIn.read(buffer))) {
        out.write(buffer, 0, n);
    }
    out.close();
    gzIn.close();
    return uncompressedFile;
}

From source file:ffx.algorithms.DiscountPh.java

private void writeSnapshot(String extension) {
    String filename = FilenameUtils.removeExtension(originalFilename);
    if (snapshotType == Snapshots.INTERLEAVED) {
        if (filename.contains("_dyn")) {
            filename = filename.replace("_dyn", format("_dyn_%d.pdb", ++snapshotIndex));
        } else {//from w  w w. j  a  v  a 2s  .  co  m
            filename = FilenameUtils.removeExtension(filename) + format("_dyn_%d.pdb", ++snapshotIndex);
        }
    } else {
        if (!extension.startsWith(".")) {
            extension = "." + extension;
        }
        filename = filename + format("_%d", ++snapshotIndex) + extension;
    }
    File file = new File(filename);
    PDBFilter writer = new PDBFilter(file, mola, null, null);
    writer.writeFile(file, false);
}

From source file:ffx.potential.ForceFieldEnergy.java

/**
 * <p>/*from w w  w  .  jav a2 s  . co m*/
 * energy</p>
 *
 * @param gradient a boolean.
 * @param print a boolean.
 * @return a double.
 */
public double energy(boolean gradient, boolean print) {
    try {
        bondTime = 0;
        angleTime = 0;
        stretchBendTime = 0;
        ureyBradleyTime = 0;
        outOfPlaneBendTime = 0;
        torsionTime = 0;
        piOrbitalTorsionTime = 0;
        torsionTorsionTime = 0;
        improperTorsionTime = 0;
        vanDerWaalsTime = 0;
        electrostaticTime = 0;
        restraintBondTime = 0;
        ncsTime = 0;
        coordRestraintTime = 0;
        totalTime = System.nanoTime();

        // Zero out the potential energy of each bonded term.
        bondEnergy = 0.0;
        angleEnergy = 0.0;
        stretchBendEnergy = 0.0;
        ureyBradleyEnergy = 0.0;
        outOfPlaneBendEnergy = 0.0;
        torsionEnergy = 0.0;
        piOrbitalTorsionEnergy = 0.0;
        torsionTorsionEnergy = 0.0;
        improperTorsionEnergy = 0.0;
        totalBondedEnergy = 0.0;

        // Zero out potential energy of restraint terms
        restraintBondEnergy = 0.0;
        ncsEnergy = 0.0;
        restrainEnergy = 0.0;

        // Zero out bond and angle RMSDs.
        bondRMSD = 0.0;
        angleRMSD = 0.0;

        // Zero out the potential energy of each non-bonded term.
        vanDerWaalsEnergy = 0.0;
        permanentMultipoleEnergy = 0.0;
        polarizationEnergy = 0.0;
        totalElectrostaticEnergy = 0.0;
        totalNonBondedEnergy = 0.0;

        // Zero out the solvation energy.
        solvationEnergy = 0.0;

        // Zero out the relative solvation energy (sequence optimization)
        relativeSolvationEnergy = 0.0;
        nRelativeSolvations = 0;

        esvBias = 0.0;

        // Zero out the total potential energy.
        totalEnergy = 0.0;

        // Zero out the Cartesian coordinate gradient for each atom.
        if (gradient) {
            for (int i = 0; i < nAtoms; i++) {
                atoms[i].setXYZGradient(0.0, 0.0, 0.0);
                atoms[i].setLambdaXYZGradient(0.0, 0.0, 0.0);
            }
        }

        /**
         * Computed the bonded energy terms in parallel.
         */
        try {
            bondedRegion.setGradient(gradient);
            parallelTeam.execute(bondedRegion);
        } catch (Exception e) {
            e.printStackTrace();
            logger.severe(e.toString());
        }

        if (!lambdaBondedTerms) {
            /**
             * Compute restraint terms.
             */
            if (ncsTerm) {
                ncsTime = -System.nanoTime();
                ncsEnergy = ncsRestraint.residual(gradient, print);
                ncsTime += System.nanoTime();
            }
            if (restrainTerm && !coordRestraints.isEmpty()) {
                coordRestraintTime = -System.nanoTime();
                for (CoordRestraint restraint : coordRestraints) {
                    restrainEnergy += restraint.residual(gradient, print);
                }
                coordRestraintTime += System.nanoTime();
            }
            if (comTerm) {
                comRestraintTime = -System.nanoTime();
                comRestraintEnergy = comRestraint.residual(gradient, print);
                comRestraintTime += System.nanoTime();
            }
            /**
             * Compute non-bonded terms.
             */
            if (vanderWaalsTerm) {
                vanDerWaalsTime = -System.nanoTime();
                vanDerWaalsEnergy = vanderWaals.energy(gradient, print);
                nVanDerWaalInteractions = this.vanderWaals.getInteractions();
                vanDerWaalsTime += System.nanoTime();
            }
            if (multipoleTerm) {
                electrostaticTime = -System.nanoTime();
                totalElectrostaticEnergy = particleMeshEwald.energy(gradient, print);
                permanentMultipoleEnergy = particleMeshEwald.getPermanentEnergy();
                polarizationEnergy = particleMeshEwald.getPolarizationEnergy();
                nPermanentInteractions = particleMeshEwald.getInteractions();
                solvationEnergy = particleMeshEwald.getGKEnergy();
                nGKInteractions = particleMeshEwald.getGKInteractions();
                electrostaticTime += System.nanoTime();
            }
        }

        if (relativeSolvationTerm) {
            List<Residue> residuesList = molecularAssembly.getResidueList();
            for (Residue residue : residuesList) {
                if (residue instanceof MultiResidue) {
                    Atom refAtom = residue.getSideChainAtoms().get(0);
                    if (refAtom != null && refAtom.getUse()) {
                        /**
                         * Reasonably confident that it should be -=, as we
                         * are trying to penalize residues with strong
                         * solvation energy.
                         */
                        double thisSolvation = relativeSolvation.getSolvationEnergy(residue, false);
                        relativeSolvationEnergy -= thisSolvation;
                        if (thisSolvation != 0) {
                            nRelativeSolvations++;
                        }
                    }
                }
            }
        }

        totalTime = System.nanoTime() - totalTime;

        totalBondedEnergy = bondEnergy + restraintBondEnergy + angleEnergy + stretchBendEnergy
                + ureyBradleyEnergy + outOfPlaneBendEnergy + torsionEnergy + piOrbitalTorsionEnergy
                + improperTorsionEnergy + torsionTorsionEnergy + ncsEnergy + restrainEnergy;
        totalNonBondedEnergy = vanDerWaalsEnergy + totalElectrostaticEnergy + relativeSolvationEnergy;
        totalEnergy = totalBondedEnergy + totalNonBondedEnergy + solvationEnergy;
        if (esvTerm) {
            esvBias = esvSystem.getBiasEnergy(null);
            totalEnergy += esvBias;
        }
    } catch (EnergyException ex) {
        if (printOnFailure) {
            String timeString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd-HH_mm_ss"));

            String filename = String.format("%s-ERROR-%s.pdb",
                    FilenameUtils.removeExtension(molecularAssembly.getFile().getName()), timeString);

            PotentialsFunctions ef = new PotentialsUtils();
            filename = ef.versionFile(filename);
            logger.info(String.format(" Writing on-error snapshot to file %s", filename));
            ef.saveAsPDB(molecularAssembly, new File(filename));
        }
        if (ex.doCauseSevere()) {
            logger.log(Level.SEVERE, " Error in calculating energies or gradients", ex);
            return 0.0;
        } else {
            throw ex; // Rethrow exception
        }
    }

    if (print || printOverride) {
        if (printCompact) {
            logger.info(this.toString());
        } else {
            StringBuilder sb = new StringBuilder();
            if (gradient) {
                sb.append("\n Computed Potential Energy and Atomic Coordinate Gradients\n");
            } else {
                sb.append("\n Computed Potential Energy\n");
            }
            sb.append(this);
            logger.info(sb.toString());
        }
    }
    return totalEnergy;
}

From source file:WpRDFFunctionLibrary.java

public static void mergeGpmltoSingleFile(String gpmlLocation) throws IOException, XMLStreamException,
        ParserConfigurationException, SAXException, TransformerException {
    // Based on: http://stackoverflow.com/questions/10759775/how-to-merge-1000-xml-files-into-one-in-java
    //for (int i = 1; i < 8 ; i++) {      
    Writer outputWriter = new FileWriter("/tmp/WpGPML.xml");
    XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory();
    XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter);
    XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory();

    xmlEventWriter.add(xmlEventFactory.createStartDocument("ISO-8859-1", "1.0"));
    xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "PathwaySet"));
    xmlEventWriter.add(xmlEventFactory.createAttribute("creationData", basicCalls.now()));
    XMLInputFactory xmlInFactory = XMLInputFactory.newFactory();

    File dir = new File(gpmlLocation);

    File[] rootFiles = dir.listFiles();
    //the section below is only in case of analysis sets
    for (File rootFile : rootFiles) {
        String fileName = FilenameUtils.removeExtension(rootFile.getName());
        System.out.println(fileName);
        String[] identifiers = fileName.split("_");
        System.out.println(fileName);
        String wpIdentifier = identifiers[identifiers.length - 2];
        String wpRevision = identifiers[identifiers.length - 1];
        //Pattern pattern = Pattern.compile("_(WP[0-9]+)_([0-9]+).gpml");
        //Matcher matcher = pattern.matcher(fileName);
        //System.out.println(matcher.find());
        //String wpIdentifier = matcher.group(1);
        File tempFile = new File(constants.localAllGPMLCacheDir() + wpIdentifier + "_" + wpRevision + ".gpml");
        //System.out.println(matcher.group(1));
        //String wpRevision = matcher.group(2);
        //System.out.println(matcher.group(2));
        if (!(tempFile.exists())) {
            System.out.println(tempFile.getName());
            Document currentGPML = basicCalls.openXmlFile(rootFile.getPath());
            basicCalls.saveDOMasXML(WpRDFFunctionLibrary.addWpProvenance(currentGPML, wpIdentifier, wpRevision),
                    constants.localCurrentGPMLCache() + tempFile.getName());
        }/*from w  w  w.j a v  a  2  s.  c  om*/
    }

    dir = new File("/tmp/GPML");
    rootFiles = dir.listFiles();
    for (File rootFile : rootFiles) {
        System.out.println(rootFile);
        XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile));
        XMLEvent event = xmlEventReader.nextEvent();
        // Skip ahead in the input to the opening document element
        try {
            while (event.getEventType() != XMLEvent.START_ELEMENT) {
                event = xmlEventReader.nextEvent();
            }

            do {
                xmlEventWriter.add(event);
                event = xmlEventReader.nextEvent();
            } while (event.getEventType() != XMLEvent.END_DOCUMENT);
            xmlEventReader.close();
        } catch (Exception e) {
            System.out.println("Malformed gpml file");
        }
    }

    xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "PathwaySet"));
    xmlEventWriter.add(xmlEventFactory.createEndDocument());

    xmlEventWriter.close();
    outputWriter.close();
}

From source file:com.iyonger.apm.web.service.PerfTestService.java

private String buildReportName(String key, File file) {
    String reportName = FilenameUtils.removeExtension(file.getName());
    if (key.equals(reportName)) {
        return reportName;
    }/*from   w  w w  . j a v a 2s  .  com*/
    String[] baseName = StringUtils.split(reportName, "-", 2);
    if (SingleConsole.INTERESTING_PER_TEST_STATISTICS.contains(baseName[0]) && baseName.length >= 2) {
        reportName = baseName[1];
    }
    return reportName;
}

From source file:ffx.potential.ForceFieldEnergy.java

/**
 * {@inheritDoc}/*  ww  w  . j  a v a 2 s.  c o m*/
 */
@Override
public double energyAndGradient(double x[], double g[], boolean verbose) {
    /**
     * Un-scale the coordinates.
     */
    if (optimizationScaling != null) {
        int len = x.length;
        for (int i = 0; i < len; i++) {
            x[i] /= optimizationScaling[i];
        }
    }
    setCoordinates(x);
    double e = energy(true, verbose);

    // Try block already exists inside energy(boolean, boolean), so only
    // need to try-catch getGradients.
    try {
        getGradients(g);
        /**
         * Scale the coordinates and gradients.
         */
        if (optimizationScaling != null) {
            int len = x.length;
            for (int i = 0; i < len; i++) {
                x[i] *= optimizationScaling[i];
                g[i] /= optimizationScaling[i];
            }
        }
        return e;
    } catch (EnergyException ex) {
        ex.printStackTrace();
        if (printOnFailure) {
            String timeString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd-HH_mm_ss"));

            String filename = String.format("%s-ERROR-%s.pdb",
                    FilenameUtils.removeExtension(molecularAssembly.getFile().getName()), timeString);

            PotentialsFunctions ef = new PotentialsUtils();
            filename = ef.versionFile(filename);
            logger.info(String.format(" Writing on-error snapshot to file %s", filename));
            ef.saveAsPDB(molecularAssembly, new File(filename));
        }
        if (ex.doCauseSevere()) {
            ex.printStackTrace();
            logger.log(Level.SEVERE, " Error in calculating energies or gradients", ex);
        } else {
            ex.printStackTrace();
            throw ex; // Rethrow exception
        }

        return 0; // Should ordinarily be unreachable.
    }
}