Example usage for org.apache.commons.math.optimization RealPointValuePair getPoint

List of usage examples for org.apache.commons.math.optimization RealPointValuePair getPoint

Introduction

In this page you can find the example usage for org.apache.commons.math.optimization RealPointValuePair getPoint.

Prototype

public double[] getPoint() 

Source Link

Document

Get the point.

Usage

From source file:com.opengamma.analytics.math.util.wrapper.CommonsMathWrapper.java

/**
 * @param x A Commons pair of <i>(x, f(x))</i>, not null
 * @return A matrix of double with the <i>x</i> as the first element and <i>f(x)</i> the second
 *///from   w ww.  j a  v  a2  s  . co  m
public static double[] unwrap(final RealPointValuePair x) {
    Validate.notNull(x);
    return x.getPoint();
}

From source file:ch.algotrader.option.SABR.java

/**
 * Perfors a SABR calibartion based on specified volatilities.
 *
 * @return SABRSmileVO The SABR smile/* www. j  av  a  2 s  .c o m*/
 */
public static SABRSmileVO calibrate(final Double[] strikes, final Double[] volatilities, final double atmVol,
        final double forward, final double years) throws SABRException {

    MultivariateRealFunction estimateRhoAndVol = x -> {

        double r = x[0];
        double v = x[1];
        double alpha = findAlpha(forward, forward, atmVol, years, beta, x[0], x[1]);
        double sumErrors = 0;

        for (int i = 0; i < volatilities.length; i++) {

            double modelVol = vol(forward, strikes[i], years, alpha, beta, r, v);
            sumErrors += Math.pow(modelVol - volatilities[i], 2);
        }

        if (Math.abs(r) > 1) {
            sumErrors = 1e100;
        }

        return sumErrors;
    };

    NelderMead nelderMead = new NelderMead();
    RealPointValuePair result;
    try {
        result = nelderMead.optimize(estimateRhoAndVol, GoalType.MINIMIZE, new double[] { -0.5, 2.6 });
    } catch (MathException ex) {
        throw new SABRException(ex.getMessage(), ex);
    }

    double rho = result.getPoint()[0];
    double volVol = result.getPoint()[1];

    SABRSmileVO params = new SABRSmileVO();
    params.setYears(years);
    params.setRho(rho);
    params.setVolVol(volVol);
    params.setAlpha(findAlpha(forward, forward, atmVol, years, beta, rho, volVol));
    params.setAtmVol(atmVol);

    return params;
}

From source file:com.polytech4A.cuttingstock.core.method.LinearResolutionMethod.java

/**
 * Resolve linear programming problem when minimizing the equation with current constraints. Returns
 *
 * @param solution Solution to minimize the objective the function from.
 * @return Number of printings and cost value.
 *///from w  ww . ja  va 2 s . c o m
public Result minimize(Solution solution) {
    updateFunction(solution);
    updateConstraints(solution);
    try {
        RealPointValuePair result = new SimplexSolver().optimize(function, constraints, GoalType.MINIMIZE,
                true);
        double[] point = result.getPoint();
        if (result.getValue() < 0) {
            return null;
        }
        for (int i = 0; i < point.length; ++i) {
            if (point[i] < 0) {
                return null;
            }
        }
        return new Result(point, context.getSheetCost(), context.getPatternCost());
    } catch (OptimizationException e) {
        logger.debug("LinearResolutionMethod.minimize: " + e.getMessage());
    }
    return null;
}

From source file:edu.valelab.GaussianFit.ZCalibrator.java

/**
 * Use the fitfunction to estimate the z position given width in x and y
 * //from   w ww.  ja va2 s.  c o m
 * minimize the distance D in sqrt wx and sqrt wy space
 * D = sqrt (  square (sqrt wx - sqrt wx, calib) + sqr(sqrt wy - sqrt w, calib) )
 * 
 * 
 */

public double getZ(double wx, double wy) {
    if (!hasFitFunctions())
        return 0.0;

    NelderMead nmx = new NelderMead();
    SimpleScalarValueChecker convergedChecker_ = new SimpleScalarValueChecker(1e-6, -1);

    MultiVariateZFunction mz = new MultiVariateZFunction(fitFunctionWx_, fitFunctionWy_, wx, wy);

    double[] params0_ = new double[1]; // initial estimates:
    params0_[0] = 15; // TODO: Need the middle z value of the stack here!!!

    nmx.setStartConfiguration(params0_);
    nmx.setConvergenceChecker(convergedChecker_);
    nmx.setMaxIterations(maxIterations_);

    double[] paramsOut = { 0.0 };

    try {
        RealPointValuePair result = nmx.optimize(mz, GoalType.MINIMIZE, params0_);
        paramsOut = result.getPoint();
    } catch (java.lang.OutOfMemoryError e) {
        throw (e);
    } catch (Exception e) {
        ij.IJ.log(" " + e.toString());
    }

    return paramsOut[0];
}

From source file:edu.valelab.gaussianfit.fitting.ZCalibrator.java

/**
 * Use the fitfunction to estimate the z position given width in x and y
 * /* w w w  .j ava  2  s .c om*/
 * minimize the distance D in sqrt wx and sqrt wy space
 * D = sqrt (  square (sqrt wx - sqrt wx, calib) + sqr(sqrt wy - sqrt w, calib) )
 * 
 * 
 * @param wx - width in x
 * @param wy - width in y
 * @return - calculated z position
 */

public double getZ(double wx, double wy) {
    if (!hasFitFunctions())
        return 0.0;

    NelderMead nmx = new NelderMead();
    SimpleScalarValueChecker convergedChecker_ = new SimpleScalarValueChecker(1e-6, -1);

    MultiVariateZFunction mz = new MultiVariateZFunction(fitFunctionWx_, fitFunctionWy_, wx, wy);

    double[] params0_ = new double[1]; // initial estimates:
    params0_[0] = 15; // TODO: Need the middle z value of the stack here!!!

    nmx.setStartConfiguration(params0_);
    nmx.setConvergenceChecker(convergedChecker_);
    nmx.setMaxIterations(maxIterations_);

    double[] paramsOut = { 0.0 };

    try {
        RealPointValuePair result = nmx.optimize(mz, GoalType.MINIMIZE, params0_);
        paramsOut = result.getPoint();
    } catch (java.lang.OutOfMemoryError e) {
        throw (e);
    } catch (FunctionEvaluationException e) {
        ij.IJ.log(" " + e.toString());
    } catch (OptimizationException e) {
        ij.IJ.log(" " + e.toString());
    } catch (IllegalArgumentException e) {
        ij.IJ.log(" " + e.toString());
    }

    return paramsOut[0];
}

From source file:edu.valelab.gaussianfit.fitting.ZCalibrator.java

/**
 * Creates fitFunctionWx_ and fitFunctionWy_ based on data in data_
 * /*w ww  .  j av  a2  s.c  o m*/
 * 
 * @throws org.apache.commons.math.FunctionEvaluationException
 * @throws org.apache.commons.math.optimization.OptimizationException
 */
public void fitFunction() throws FunctionEvaluationException, OptimizationException {

    NelderMead nmx = new NelderMead();
    SimpleScalarValueChecker convergedChecker_ = new SimpleScalarValueChecker(1e-6, -1);

    double[][] wxData = getDataAsArray(0);
    MultiVariateZCalibrationFunction mvcx = new MultiVariateZCalibrationFunction(wxData);

    double[] params0_ = new double[5]; // initial estimates:
    params0_[0] = 37; // TODO: better estimate for c
    params0_[1] = 200; // Estimate for w0
    params0_[2] = 10; // TODO: better estimate for d
    params0_[3] = 1; // TODO: better estimate for A
    params0_[4] = 1; // TODO: better estimate for B

    nmx.setStartConfiguration(params0_);
    nmx.setConvergenceChecker(convergedChecker_);
    nmx.setMaxIterations(maxIterations_);

    double[] paramsOut;

    RealPointValuePair result = nmx.optimize(mvcx, GoalType.MINIMIZE, params0_);
    paramsOut = result.getPoint();

    // write fit result to Results Table:
    ResultsTable res = new ResultsTable();
    res.incrementCounter();
    res.addValue("c", paramsOut[0]);
    res.addValue("w0", paramsOut[1]);
    res.addValue("d", paramsOut[2]);
    res.addValue("A", paramsOut[3]);
    res.addValue("B", paramsOut[4]);

    fitFunctionWx_ = paramsOut;

    double[][] yxData = getDataAsArray(1);
    MultiVariateZCalibrationFunction yvcx = new MultiVariateZCalibrationFunction(yxData);

    nmx.setStartConfiguration(params0_);

    result = nmx.optimize(yvcx, GoalType.MINIMIZE, params0_);
    paramsOut = result.getPoint();

    res.incrementCounter();
    res.addValue("c", paramsOut[0]);
    res.addValue("w0", paramsOut[1]);
    res.addValue("d", paramsOut[2]);
    res.addValue("A", paramsOut[3]);
    res.addValue("B", paramsOut[4]);

    res.show("Fit Parameters");

    fitFunctionWy_ = paramsOut;

    plotFitFunctions();

}

From source file:edu.valelab.GaussianFit.ZCalibrator.java

/**
 * Creates fitFunctionWx_ and fitFunctionWy_ based on data in data_
 * /*from   w w w.j  a  va  2s.  c  om*/
 * 
 */
public void fitFunction() throws FunctionEvaluationException, OptimizationException {

    NelderMead nmx = new NelderMead();
    SimpleScalarValueChecker convergedChecker_ = new SimpleScalarValueChecker(1e-6, -1);

    double[][] wxData = getDataAsArray(0);
    MultiVariateZCalibrationFunction mvcx = new MultiVariateZCalibrationFunction(wxData);

    double[] params0_ = new double[5]; // initial estimates:
    params0_[0] = 37; // TODO: better estimate for c
    params0_[1] = 200; // Estimate for w0
    params0_[2] = 10; // TODO: better estimate for d
    params0_[3] = 1; // TODO: better estimate for A
    params0_[4] = 1; // TODO: better estimate for B

    nmx.setStartConfiguration(params0_);
    nmx.setConvergenceChecker(convergedChecker_);
    nmx.setMaxIterations(maxIterations_);

    double[] paramsOut = { 0.0 };

    RealPointValuePair result = nmx.optimize(mvcx, GoalType.MINIMIZE, params0_);
    paramsOut = result.getPoint();

    //for (int i = 0; i < paramsOut.length; i++) {
    //  System.out.println("Result " + i + " value: " + (int) paramsOut[i]);
    //}

    // write fit result to Results Table:
    ResultsTable res = new ResultsTable();
    res.incrementCounter();
    res.addValue("c", paramsOut[0]);
    res.addValue("w0", paramsOut[1]);
    res.addValue("d", paramsOut[2]);
    res.addValue("A", paramsOut[3]);
    res.addValue("B", paramsOut[4]);

    fitFunctionWx_ = paramsOut;

    double[][] yxData = getDataAsArray(1);
    MultiVariateZCalibrationFunction yvcx = new MultiVariateZCalibrationFunction(yxData);

    nmx.setStartConfiguration(params0_);

    result = nmx.optimize(yvcx, GoalType.MINIMIZE, params0_);
    paramsOut = result.getPoint();

    System.out.println("Y:");

    //for (int i = 0; i < paramsOut.length; i++) {
    //  System.out.println("Result " + i + " value: " + (int) paramsOut[i]);
    //}

    res.incrementCounter();
    res.addValue("c", paramsOut[0]);
    res.addValue("w0", paramsOut[1]);
    res.addValue("d", paramsOut[2]);
    res.addValue("A", paramsOut[3]);
    res.addValue("B", paramsOut[4]);

    res.show("Fit Parameters");

    fitFunctionWy_ = paramsOut;

    plotFitFunctions();

}

From source file:circdesigna.DesignSequenceConstraints.java

private void solveSimplex() {
    //Closest-To-Origin objective
    double[] ones = new double[Std.monomer.getNumMonomers()];
    for (int i = 0; i < ones.length; i++) {
        ones[i] = 1;//from   ww  w . ja  v  a 2s.c  om
    }
    LinearObjectiveFunction f = new LinearObjectiveFunction(ones, 0);

    List<LinearConstraint> constraints = new ArrayList();
    for (Constraint d : maxConstituents) {
        if (d.constraintValue == -1) {
            continue;
        }
        double[] ei = new double[Std.monomer.getNumMonomers()];
        for (int i = 0; i < ei.length; i++) {
            if (d.regulates[i]) {
                ei[i] = 1;
            }
        }
        constraints.add(new LinearConstraint(ei, Relationship.LEQ, d.constraintValue));
    }
    for (Constraint d : minConstituents) {
        if (d.constraintValue == -1) {
            continue;
        }
        double[] ei = new double[Std.monomer.getNumMonomers()];
        for (int i = 0; i < ei.length; i++) {
            if (d.regulates[i]) {
                ei[i] = 1;
            }
        }
        constraints.add(new LinearConstraint(ei, Relationship.GEQ, d.constraintValue));
    }
    try {
        RealPointValuePair optimize = new SimplexSolver().optimize(f, constraints, GoalType.MINIMIZE, true);
        simplexSolution = optimize.getPoint();
        //System.out.println(Arrays.toString(simplexSolution));
    } catch (Throwable e) {
        throw new RuntimeException("Constraints are too strict: " + e.getMessage());
    }

}

From source file:Align_Projections.java

public void run() {

    detectorAngle = Double.valueOf(detectorAngleText.getText()).doubleValue();
    centerPixel = Double.valueOf(centerPixelText.getText()).doubleValue();
    horizontalBorder = Integer.valueOf(horizontalBorderText.getText()).intValue();
    topBorder = Integer.valueOf(topBorderText.getText()).intValue();
    bottomBorder = Integer.valueOf(bottomBorderText.getText()).intValue();

    // IJ.log("Starting worker thread");
    int count = 0;
    double[] x = new double[2];
    x[0] = centerPixel * tuningWeights[0];
    x[1] = detectorAngle * tuningWeights[1];
    PowellOptimizer maximizer = new PowellOptimizer(1E-4);
    maximizer.setConvergenceChecker(new ConvergenceCheckerWithManualCancel(this, 1E-4, 1E-4));
    maximizer.setMaxEvaluations(1000000);
    maximizer.setMaxIterations(1000000);
    try {/*from  w  w  w  . j a  v a 2s.  c o  m*/
        // IJ.log("Starting optimization first round");
        RealPointValuePair result = maximizer.optimize(this, GoalType.MAXIMIZE, x);
        centerPixel = result.getPoint()[0] / tuningWeights[0];
        detectorAngle = result.getPoint()[1] / tuningWeights[1];
        centerPixelText.setText(IJ.d2s(centerPixel, 6));
        detectorAngleText.setText(IJ.d2s(detectorAngle, 6));
        crossCorrelation = result.getValue();
        updateCrossCorrelation();
    } catch (GetMeOuttaHereException e) {
    } catch (Exception e) {
        IJ.log("Exception occurred in optimizer.");
        stopTuning = true;
    }
    // Now do the whole thing again, but with narrower tolerances (the defaults, which are roughly machine precision)
    if (!stopTuning) {
        maximizer = new PowellOptimizer();
        maximizer.setConvergenceChecker(new ConvergenceCheckerWithManualCancel(this));
        maximizer.setMaxEvaluations(1000000);
        maximizer.setMaxIterations(1000000);
        try {
            // IJ.log("Starting optimization second round");
            RealPointValuePair result = maximizer.optimize(this, GoalType.MAXIMIZE, x);
            centerPixel = result.getPoint()[0] / tuningWeights[0];
            detectorAngle = result.getPoint()[1] / tuningWeights[1];
            centerPixelText.setText(IJ.d2s(centerPixel, 6));
            detectorAngleText.setText(IJ.d2s(detectorAngle, 6));
            crossCorrelation = result.getValue();
            updateCrossCorrelation();
        } catch (GetMeOuttaHereException e) {
        } catch (Exception e) {
            IJ.log("Exception occurred in optimizer.");
        }
    }

    UpdateOverlayAndControls();
    optimizeButton.setLabel("Optimize");
    optimizeButton.setEnabled(true);
    updateButton.setEnabled(true);
    applyButton.setEnabled(true);
    resetButton.setEnabled(true);
    detectorAngleText.setEnabled(true);
    centerPixelText.setEnabled(true);
    horizontalBorderText.setEnabled(true);
    topBorderText.setEnabled(true);
    bottomBorderText.setEnabled(true);
    // IJ.log("Exiting worker thread");
}

From source file:emlab.role.AbstractEnergyProducerRole.java

/**
 * The fuel mix is calculated with a linear optimization model of the possible fuels and the requirements.
 * //from ww  w .j  a  v a2s.  co  m
 * @param substancePriceMap
 *            contains the possible fuels and their market prices
 * @param minimumFuelMixQuality
 *            is the minimum fuel quality needed for the power plant to work
 * @param efficiency
 *            of the plant determines the need for fuel per MWhe
 * @param co2TaxLevel
 *            is part of the cost for CO2
 * @param co2AuctionPrice
 *            is part of the cost for CO2
 * @return the fuel mix
 */
public Set<SubstanceShareInFuelMix> calculateFuelMix(PowerPlant plant, Map<Substance, Double> substancePriceMap,
        double co2Price) {

    double efficiency = plant.getActualEfficiency();

    Set<SubstanceShareInFuelMix> fuelMix = (plant.getFuelMix() == null) ? new HashSet<SubstanceShareInFuelMix>()
            : plant.getFuelMix();

    int numberOfFuels = substancePriceMap.size();
    if (numberOfFuels == 0) {
        logger.info("No fuels, so no operation mode is set. Empty fuel mix is returned");
        return new HashSet<SubstanceShareInFuelMix>();
    } else if (numberOfFuels == 1) {
        SubstanceShareInFuelMix ssifm = null;
        if (!fuelMix.isEmpty()) {
            ssifm = fuelMix.iterator().next();
        } else {
            ssifm = new SubstanceShareInFuelMix().persist();
            fuelMix.add(ssifm);
        }

        Substance substance = substancePriceMap.keySet().iterator().next();

        ssifm.setShare(calculateFuelConsumptionWhenOnlyOneFuelIsUsed(substance, efficiency));
        ssifm.setSubstance(substance);
        logger.info("Setting fuel consumption for {} to {}", ssifm.getSubstance().getName(), ssifm.getShare());

        return fuelMix;
    } else {

        double minimumFuelMixQuality = plant.getTechnology().getMinimumFuelQuality();

        double[] fuelAndCO2Costs = new double[numberOfFuels];
        double[] fuelDensities = new double[numberOfFuels];
        double[] fuelQuality = new double[numberOfFuels];

        int i = 0;
        for (Substance substance : substancePriceMap.keySet()) {
            fuelAndCO2Costs[i] = substancePriceMap.get(substance) + substance.getCo2Density() * (co2Price);
            fuelDensities[i] = substance.getEnergyDensity();
            fuelQuality[i] = substance.getQuality() - minimumFuelMixQuality;
            i++;
        }

        logger.info("Fuel prices: {}", fuelAndCO2Costs);
        logger.info("Fuel densities: {}", fuelDensities);
        logger.info("Fuel purities: {}", fuelQuality);

        // Objective function = minimize fuel cost (fuel
        // consumption*fuelprices
        // + CO2 intensity*co2 price/tax)
        LinearObjectiveFunction function = new LinearObjectiveFunction(fuelAndCO2Costs, 0d);

        List<LinearConstraint> constraints = new ArrayList<LinearConstraint>();

        // Constraint 1: total fuel density * fuel consumption should match
        // required energy input
        constraints.add(new LinearConstraint(fuelDensities, Relationship.EQ, (1 / efficiency)));

        // Constraint 2&3: minimum fuel quality (times fuel consumption)
        // required
        // The equation is derived from (example for 2 fuels): q1 * x1 / (x1+x2) + q2 * x2 / (x1+x2) >= qmin
        // so that the fuelquality weighted by the mass percentages is greater than the minimum fuel quality.
        constraints.add(new LinearConstraint(fuelQuality, Relationship.GEQ, 0));

        try {
            SimplexSolver solver = new SimplexSolver();
            RealPointValuePair solution = solver.optimize(function, constraints, GoalType.MINIMIZE, true);

            logger.info("Succesfully solved a linear optimization for fuel mix");

            int f = 0;
            Iterator<SubstanceShareInFuelMix> iterator = plant.getFuelMix().iterator();
            for (Substance substance : substancePriceMap.keySet()) {
                double share = solution.getPoint()[f];

                SubstanceShareInFuelMix ssifm;
                if (iterator.hasNext()) {
                    ssifm = iterator.next();
                } else {
                    ssifm = new SubstanceShareInFuelMix().persist();
                    fuelMix.add(ssifm);
                }

                double fuelConsumptionPerMWhElectricityProduced = convertFuelShareToMassVolume(share);
                logger.info("Setting fuel consumption for {} to {}", substance.getName(),
                        fuelConsumptionPerMWhElectricityProduced);
                ssifm.setShare(fuelConsumptionPerMWhElectricityProduced);
                ssifm.setSubstance(substance);
                f++;
            }

            logger.info("If single fired, it would have been: {}",
                    calculateFuelConsumptionWhenOnlyOneFuelIsUsed(substancePriceMap.keySet().iterator().next(),
                            efficiency));
            return fuelMix;
        } catch (OptimizationException e) {
            logger.warn(
                    "Failed to determine the correct fuel mix. Adding only fuel number 1 in fuel mix out of {} substances and minimum quality of {}",
                    substancePriceMap.size(), minimumFuelMixQuality);
            logger.info("The fuel added is: {}", substancePriceMap.keySet().iterator().next().getName());

            // Override the old one
            fuelMix = new HashSet<SubstanceShareInFuelMix>();
            SubstanceShareInFuelMix ssifm = new SubstanceShareInFuelMix().persist();
            Substance substance = substancePriceMap.keySet().iterator().next();

            ssifm.setShare(calculateFuelConsumptionWhenOnlyOneFuelIsUsed(substance, efficiency));
            ssifm.setSubstance(substance);
            logger.info("Setting fuel consumption for {} to {}", ssifm.getSubstance().getName(),
                    ssifm.getShare());
            fuelMix.add(ssifm);
            return fuelMix;
        }
    }
}