Example usage for org.apache.commons.math3.optim PointValuePair getPoint

List of usage examples for org.apache.commons.math3.optim PointValuePair getPoint

Introduction

In this page you can find the example usage for org.apache.commons.math3.optim PointValuePair getPoint.

Prototype

public double[] getPoint() 

Source Link

Document

Gets the point.

Usage

From source file:nl.systemsgenetics.cellTypeSpecificAlleleSpecificExpression.CTSbinomialTest.java

public CTSbinomialTest(ArrayList<IndividualSnpData> all_individuals) throws Exception {

    //basic information, get the zero instance.
    snpName = all_individuals.get(0).getSnpName();
    chromosome = all_individuals.get(0).getChromosome();
    position = all_individuals.get(0).getPosition();

    ArrayList<IndividualSnpData> het_individuals = UtilityMethods
            .isolateHeterozygotesFromIndividualSnpData(all_individuals);

    numberOfHets = het_individuals.size();

    hetSampleNames = new ArrayList<String>();

    asRef = new ArrayList<Integer>();
    asAlt = new ArrayList<Integer>();
    asNo = new ArrayList<Integer>();

    cellProp = new ArrayList<Double>();

    int total_overlap = 0;
    int ref_total = 0;

    for (IndividualSnpData temp_het : het_individuals) {
        //Do nothing if there is no data in het_individuals

        hetSampleNames.add(temp_het.getSampleName());

        asRef.add(temp_het.getRefNum());
        asAlt.add(temp_het.getAltNum());
        asNo.add(temp_het.getNoNum());/*w ww . j  a va 2s  .  com*/

        cellProp.add(temp_het.getCellTypeProp());

        //this is used to check if we will continue with calculations.
        total_overlap += temp_het.getRefNum() + temp_het.getAltNum();
        ref_total += temp_het.getRefNum();
    }

    if ((total_overlap >= GlobalVariables.minReads) && (numberOfHets >= GlobalVariables.minHets)) {

        Integer[] asRefArray = asRef.toArray(new Integer[asRef.size()]);
        Integer[] asAltArray = asAlt.toArray(new Integer[asAlt.size()]);
        Double[] cellPropArray = cellProp.toArray(new Double[cellProp.size()]);

        // Just using the alternative likelihood of the binomial test here.
        // As out null loglikelihood.

        try {

            CTSnullBinomialLikelihood CTSbinomNull = new CTSnullBinomialLikelihood(asRefArray, asAltArray,
                    cellPropArray);

            double nullProp = ((double) ref_total / (double) total_overlap);

            double[] nullInput = { nullProp };

            nullLogLik = CTSbinomNull.value(nullInput);

            if (GlobalVariables.verbosity >= 100) {
                System.out.println("LogLik of NULL");
                System.out.println("\tResidual ratio:                   " + Double.toString(nullInput[0]));
                System.out.println("\tnullLogLik:                       " + Double.toString(nullLogLik));

            }

            // Now do MLE of the alternative test 
            // more computationally intensive 
            // than the previous one.

            CTSaltBinomialLikelihood CTSbinom = new CTSaltBinomialLikelihood(asRefArray, asAltArray,
                    cellPropArray);

            NelderMeadSimplex simplex;
            simplex = new NelderMeadSimplex(2, 1.0, 1.0, 2.0, 0.25, 0.25);
            SimplexOptimizer optimizer = new SimplexOptimizer(GlobalVariables.simplexThreshold,
                    GlobalVariables.simplexThreshold);
            PointValuePair solutionAlt = optimizer.optimize(new ObjectiveFunction(CTSbinom),
                    new MaxEval(GlobalVariables.maximumIterations), simplex, GoalType.MINIMIZE,
                    new InitialGuess(new double[] { 0, nullInput[0] }), new SearchInterval(0.0, 1.0));

            double[] valueAlt = solutionAlt.getPoint();

            /*
            In simulations it was found that in about 30% of the cases
            A solution was not found, so we do it again if there 
            */

            if ((optimizer.getIterations() <= 5)) {

                if (GlobalVariables.verbosity >= 100) {

                    System.out.println("\nfirst starting point was already in a minimum.");
                    System.out.println("Trying with other starting values.");

                }

                ArrayList<double[]> StartingValueList = new ArrayList<double[]>();
                //These are the starting values to try
                StartingValueList.add(new double[] { 0.5, 0.0 });
                StartingValueList.add(new double[] { 0.5, 0.5 });
                StartingValueList.add(new double[] { 0.0, 0.0 });
                StartingValueList.add(new double[] { 0.75, 0.0 });
                StartingValueList.add(new double[] { 0.0, 0.75 });

                for (double[] startingValue : StartingValueList) {
                    SimplexOptimizer newOptimizer = new SimplexOptimizer(GlobalVariables.simplexThreshold,
                            GlobalVariables.simplexThreshold);
                    PointValuePair newSolutionAlt = newOptimizer.optimize(new ObjectiveFunction(CTSbinom),
                            new MaxEval(GlobalVariables.maximumIterations), simplex, GoalType.MINIMIZE,
                            new InitialGuess(startingValue), new SearchInterval(0.0, 1.0));

                    double[] newValueAlt = newSolutionAlt.getPoint();

                    if (CTSbinom.value(newValueAlt) < CTSbinom.value(valueAlt)) {

                        if (GlobalVariables.verbosity >= 100 && newOptimizer.getIterations() >= 5) {
                            System.out.println("New starting values are a better fit to the data");
                            System.out.println("keeping results of the new starting values.\n");
                        }
                        //Asign the new values to the actual used ones.
                        valueAlt = newValueAlt;
                        optimizer = newOptimizer;

                        break;
                    }
                }
            }

            altLogLik = CTSbinom.value(valueAlt);
            iterations = optimizer.getIterations();

            MLEratioCellType = valueAlt[1];
            MLEratioResidual = valueAlt[0];

            //chi squared statistic is determined based on both null and alt loglikelihoods.
            chiSq = LikelihoodFunctions.ChiSqFromLogLik(nullLogLik, altLogLik);

            //determine P value based on distribution
            pVal = LikelihoodFunctions.determinePvalFrom1DFchiSq(chiSq);

            if (GlobalVariables.verbosity >= 10) {
                System.out.println("\n--- Starting cell type specific binomial LRT test estimate ---");

                System.out.println("LogLik of Alt converged to a threshold of "
                        + Double.toString(GlobalVariables.simplexThreshold));
                System.out.println("\tCelltype ratio:                   " + Double.toString(valueAlt[0]));
                System.out.println("\tResidual ratio:                   " + Double.toString(valueAlt[1]));
                System.out
                        .println("\tIterations to converge:           " + Integer.toString(iterations) + "\n");
                System.out.println("\tNull log likelihood:              " + Double.toString(nullLogLik));
                System.out.println("\tAlt log likelihood:               " + Double.toString(altLogLik) + "\n");
                System.out.println("\tChisq statistic:                  " + Double.toString(chiSq));
                System.out.println("\tP value:                          " + Double.toString(pVal));
                System.out.println("--------------------------------------------------------------");

            }

            testConverged = true;

        } catch (TooManyEvaluationsException e) {

            if (GlobalVariables.verbosity >= 1) {
                System.out.println("WARNING: Did not converge to a solution for SNP: " + snpName
                        + "in cell type specific beta binomial");
                System.out.println("         After " + Integer.toString(GlobalVariables.maximumIterations)
                        + " iterations.");
                System.out.println("         Continue-ing with the next.");
                System.out.println("--------------------------------------------------------------");

            }

        }

        // Add some extra values that will make sure that there could be some kind of non-convergence.
        testPerformed = true;

    }

}

From source file:org.arrowhead.wp5.market.impl.Market.java

public void clear(List<Bid> demList, List<Bid> supList, List<Bid> winningDemandBids,
        List<Bid> winningSupplyBids) {
    if (demList.isEmpty() || supList.isEmpty()) {
        logger.debug("Empty list, no clearing.");
        return;//from  w w w  . j  av a  2  s  .com
    }
    List<Bid> demandList = new ArrayList<Bid>();
    demandList.addAll(demList);
    List<Bid> supplyList = new ArrayList<Bid>();
    supplyList.addAll(supList);

    long totalDemand = getTotalQuantity(demandList);
    long totalSupply = getTotalQuantity(supplyList);
    long minQuantity = Math.min(totalDemand, totalSupply);
    Bid fakeBid = new Bid(0, totalSupply - totalDemand, true, "", "");
    if (totalDemand < totalSupply) {
        demandList.add(fakeBid);
        totalDemand = getTotalQuantity(demandList);
        totalSupply = getTotalQuantity(supplyList);
        minQuantity = Math.min(totalDemand, totalSupply);
    }

    int numDemand = demandList.size();
    int numSupply = supplyList.size();
    int demandIdx = 0;
    int supplyIdx = numDemand;
    int total = numDemand + numSupply;
    logger.debug("demand: {} supply: {} total: {}", numDemand, numSupply, total);

    double[] demand = getPrice(demandList);
    double[] supply = getPrice(supplyList);

    logger.debug("demand: {}", Arrays.toString(demand));
    logger.debug("supply: {}", Arrays.toString(supply));

    double[] empty = new double[total];

    double[] objective = empty.clone();
    System.arraycopy(demand, 0, objective, demandIdx, numDemand);
    System.arraycopy(supply, 0, objective, supplyIdx, numSupply);
    for (int i = 0; i < supply.length; i++) {
        objective[supplyIdx + i] = -supply[i];
    }
    logger.debug("Empty: {} - obj: {}", Arrays.toString(empty), Arrays.toString(objective));

    // describe the optimization problem
    LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0);
    Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();

    for (int i = 0; i < demandList.size(); i++) {
        generateConstraint(demandList, demandIdx, total, constraints, i, Relationship.LEQ);
    }

    for (int i = 0; i < supplyList.size(); i++) {
        generateConstraint(supplyList, supplyIdx, total, constraints, i, Relationship.GEQ);
    }

    double[] constraint = empty.clone();
    for (int i = 0; i < demandList.size(); i++) {
        constraint[i + demandIdx] = 1;
    }
    logger.debug("Total quantity constraint: {} {} {}", Arrays.toString(constraint), Relationship.LEQ,
            minQuantity);
    constraints.add(new LinearConstraint(constraint, Relationship.LEQ, minQuantity));

    constraint = empty.clone();
    for (int i = 0; i < supplyList.size(); i++) {
        constraint[i + supplyIdx] = 1;
    }
    logger.debug("Total quantity constraint: {} {} {}", Arrays.toString(constraint), Relationship.LEQ,
            minQuantity);
    constraints.add(new LinearConstraint(constraint, Relationship.LEQ, minQuantity));

    for (int i = 0; i < demandList.size(); i++) {
        constraint = empty.clone();
        constraint[i + demandIdx] = 1;
        logger.debug("Non zero constraint: {} {} {}", Arrays.toString(constraint), Relationship.GEQ, 0);
        constraints.add(new LinearConstraint(constraint, Relationship.GEQ, 0));
    }

    for (int i = 0; i < supplyList.size(); i++) {
        constraint = empty.clone();
        constraint[i + supplyIdx] = 1;
        logger.debug("Non zero constraint: {} {} {}", Arrays.toString(constraint), Relationship.GEQ, 0);
        constraints.add(new LinearConstraint(constraint, Relationship.GEQ, 0));
    }

    constraint = empty.clone();
    for (int i = 0; i < demandList.size(); i++) {
        constraint[i + demandIdx] = 1;
    }
    for (int i = 0; i < supplyList.size(); i++) {
        constraint[i + supplyIdx] = -1;
    }
    //      logger.debug("Equilibrium constraint: {} {} {}", Arrays.toString(constraint), Relationship.LEQ, totalSupply-totalDemand);
    //      constraints.add(new LinearConstraint(constraint, Relationship.LEQ, totalSupply-totalDemand));

    LinearConstraintSet set = new LinearConstraintSet(constraints);
    // create and run the solver
    PointValuePair solution;
    try {
        solution = new SimplexSolver().optimize(f, set, GoalType.MAXIMIZE);
    } catch (NoFeasibleSolutionException e) {
        logger.info("No feasuble solution!!");
        return;
    }

    // get the solution
    logger.debug("solution: ");
    double[] solutionPoint = solution.getPoint();
    List<Bid> all = new ArrayList<Bid>();
    all.addAll(demandList);
    all.addAll(supplyList);

    for (int i = 0; i < solutionPoint.length; i++) {
        logger.debug("{} - {} - {}", solutionPoint[i], all.get(i).getQuantity(), all.get(i).getPrice());
    }
    double max = solution.getValue();
    logger.debug("value: {}", max);

    demandList.remove(fakeBid);
    double price = findPrice(demandList, supplyList, solutionPoint);
    logger.debug("win price: {}", price);

    for (int i = 0; i < demandList.size(); i++) {
        if (solutionPoint[i + demandIdx] > 0) {
            Bid d = demandList.get(i);
            if (d == fakeBid) {
                continue;
            }
            if (price <= d.getPrice()) {
                d.setWinPrice(price);
                //               d.setWinQuantity(solutionPoint[i+demandIdx]);
                logger.debug("Win d: p: {} - q: {} - wq: {}", d.getWinPrice(), d.getQuantity(),
                        d.getWinQuantity());
                winningDemandBids.add(d);
            }
        }
    }
    for (int i = 0; i < supplyList.size(); i++) {
        if (solutionPoint[i + supplyIdx] > 0) {
            Bid d = supplyList.get(i);
            if (price >= d.getPrice()) {
                d.setWinPrice(price);
                //               d.setWinQuantity(solutionPoint[i+supplyIdx]);
                logger.debug("Win s: p: {} - q: {} - wq: {}", d.getWinPrice(), d.getQuantity(),
                        d.getWinQuantity());
                winningSupplyBids.add(d);
            }
        }
    }
    logger.debug("winning demand: {} - total quantity: {}", winningDemandBids,
            getTotalWinQuantity(winningDemandBids));

    logger.debug("winning supply: {} - total quantity: {}", winningSupplyBids,
            getTotalWinQuantity(winningSupplyBids));
}

From source file:org.dawnsci.plotting.tools.diffraction.BeamCenterRefinement.java

/**
 * Run optimisation of sector region position in a separate job. 
 * //from  w ww  . j  av  a 2  s.  c  o m
 * @param startPosition Initial position of sector region
 */
public void optimize(final double[] startPosition) {
    final int cmaesLambda = this.cmaesLambda;
    final double[] cmaesInputSigma = this.cmaesInputSigma;
    final int cmaesMaxIterations = this.cmaesMaxIterations;
    final int cmaesCheckFeasableCount = this.cmaesCheckFeasableCount;
    final ConvergenceChecker<PointValuePair> cmaesChecker = this.cmaesChecker;
    final BeamCenterRefinement function = this;
    Job job = new Job("Beam Position Refinement") {
        @Override
        protected IStatus run(IProgressMonitor monitor) {

            function.setInitPeaks(initPeaks);
            function.setMonitor(monitor);

            final double[] lB = new double[] { startPosition[0] - 20, startPosition[1] - 20 };
            final double[] uB = new double[] { startPosition[0] + 20, startPosition[1] + 20 };
            CMAESOptimizer beamPosOptimizer = new CMAESOptimizer(cmaesMaxIterations, 0.0, true, 0,
                    cmaesCheckFeasableCount, new Well19937a(), false, cmaesChecker);
            final PointValuePair result = beamPosOptimizer.optimize(new MaxEval(cmaesMaxIterations),
                    new ObjectiveFunction(function), GoalType.MAXIMIZE,
                    new CMAESOptimizer.PopulationSize(cmaesLambda), new CMAESOptimizer.Sigma(cmaesInputSigma),
                    new SimpleBounds(lB, uB), new InitialGuess(startPosition));

            final double[] newBeamPosition = result.getPoint();
            logger.info("Optimiser terminated at beam position ({}, {}) with the value {}",
                    new Object[] { newBeamPosition[0], newBeamPosition[1], result.getValue() });
            Display.getDefault().syncExec(new Runnable() {
                @Override
                public void run() {
                    ((IDiffractionMetadata) dataset.getMetadata()).getDetector2DProperties()
                            .setBeamCentreCoords(newBeamPosition);
                }
            });

            return Status.OK_STATUS;
        }
    };
    job.schedule();
}

From source file:org.hawkular.datamining.forecast.models.AbstractModelOptimizer.java

protected void optimize(double[] initialGuess, MultivariateFunctionMappingAdapter costFunction) {

    // Nelder-Mead Simplex
    SimplexOptimizer optimizer = new SimplexOptimizer(0.0001, 0.0001);
    PointValuePair unBoundedResult = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(initialGuess), new ObjectiveFunction(costFunction),
            new NelderMeadSimplex(initialGuess.length));

    result = costFunction.unboundedToBounded(unBoundedResult.getPoint());
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executeSimplex(ModelData modelData) {
    long start = System.nanoTime();
    SimplexOptimizer optimizer = new SimplexOptimizer(0.00001, 0.00001);
    PointValuePair unbounded = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction),
            new NelderMeadSimplex(2));
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, unbounded.getPoint(), modelData);

    return executionTime;
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executeMultidirectionalSimplex(ModelData modelData) {
    long start = System.nanoTime();
    SimplexOptimizer optimizer = new SimplexOptimizer(0.00001, 0.00001);
    PointValuePair unbounded = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction),
            new MultiDirectionalSimplex(2));
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, unbounded.getPoint(), modelData);

    return executionTime;
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executeBobyQA(ModelData modelData) {
    long start = System.nanoTime();
    BOBYQAOptimizer optimizer = new BOBYQAOptimizer(6);
    PointValuePair bobyQAResult = optimizer.optimize(GoalType.MINIMIZE, new MaxEval(MAX_EVAL),
            new MaxIter(MAX_ITER), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction),
            SimpleBounds.unbounded(2));/*from   w w  w  . j a v a 2s. c  o m*/
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, bobyQAResult.getPoint(), modelData);

    return executionTime;
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executePowell(ModelData modelData) {
    long start = System.nanoTime();
    PowellOptimizer optimizer = new PowellOptimizer(0.00001, 0.00001);
    PointValuePair unbounded = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction));
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, unbounded.getPoint(), modelData);

    return executionTime;
}

From source file:org.lightjason.agentspeak.action.buildin.math.linearprogram.CSolve.java

@Override
public final IFuzzyValue<Boolean> execute(final IContext p_context, final boolean p_parallel,
        final List<ITerm> p_argument, final List<ITerm> p_return, final List<ITerm> p_annotation) {
    // first argument is the LP pair object, second argument is the goal-type (maximize / minimize),
    // third & fourth argument can be the number of iterations or string with "non-negative" variables
    final List<OptimizationData> l_settings = new LinkedList<>();

    final Pair<LinearObjectiveFunction, Collection<LinearConstraint>> l_default = p_argument.get(0).raw();
    l_settings.add(l_default.getLeft());
    l_settings.add(new LinearConstraintSet(l_default.getRight()));

    p_argument.subList(1, p_argument.size()).stream().map(i -> {
        if (CCommon.rawvalueAssignableTo(i, Number.class))
            return new MaxIter(i.raw());

        if (CCommon.rawvalueAssignableTo(i, String.class))
            switch (i.<String>raw().trim().toLowerCase()) {
            case "non-negative":
                return new NonNegativeConstraint(true);
            case "maximize":
                return GoalType.MAXIMIZE;
            case "minimize":
                return GoalType.MINIMIZE;

            default:
                return null;
            }/*  w  ww  .  j  av  a 2 s  .c o  m*/

        return null;
    }).filter(Objects::nonNull).forEach(l_settings::add);

    // optimze and return
    final SimplexSolver l_lp = new SimplexSolver();
    final PointValuePair l_result = l_lp.optimize(l_settings.toArray(new OptimizationData[l_settings.size()]));

    p_return.add(CRawTerm.from(l_result.getValue()));
    p_return.add(CRawTerm.from(l_result.getPoint().length));
    Arrays.stream(l_result.getPoint()).boxed().map(CRawTerm::from).forEach(p_return::add);

    return CFuzzyValue.from(true);
}

From source file:org.lightjason.agentspeak.action.builtin.math.linearprogram.CSolve.java

@Nonnull
@Override//from  ww w. j  ava2  s. com
public final IFuzzyValue<Boolean> execute(final boolean p_parallel, @Nonnull final IContext p_context,
        @Nonnull final List<ITerm> p_argument, @Nonnull final List<ITerm> p_return) {
    // first argument is the LP pair object, second argument is the goal-type (maximize / minimize),
    // third & fourth argument can be the number of iterations or string with "non-negative" variables
    final List<OptimizationData> l_settings = new LinkedList<>();

    final Pair<LinearObjectiveFunction, Collection<LinearConstraint>> l_default = p_argument.get(0).raw();
    l_settings.add(l_default.getLeft());
    l_settings.add(new LinearConstraintSet(l_default.getRight()));

    p_argument.subList(1, p_argument.size()).stream().map(i -> {
        if (CCommon.rawvalueAssignableTo(i, Number.class))
            return new MaxIter(i.raw());

        if (CCommon.rawvalueAssignableTo(i, String.class))
            switch (i.<String>raw().trim().toLowerCase()) {
            case "non-negative":
                return new NonNegativeConstraint(true);
            case "maximize":
                return GoalType.MAXIMIZE;
            case "minimize":
                return GoalType.MINIMIZE;

            default:
                return null;
            }

        return null;
    }).filter(Objects::nonNull).forEach(l_settings::add);

    // optimze and return
    final SimplexSolver l_lp = new SimplexSolver();
    final PointValuePair l_result = l_lp.optimize(l_settings.toArray(new OptimizationData[l_settings.size()]));

    p_return.add(CRawTerm.from(l_result.getValue()));
    p_return.add(CRawTerm.from(l_result.getPoint().length));
    Arrays.stream(l_result.getPoint()).boxed().map(CRawTerm::from).forEach(p_return::add);

    return CFuzzyValue.from(true);
}