Search in sources :

Example 76 with Max

use of org.apache.commons.math3.stat.descriptive.rank.Max in project xian by happyyangyuan.

the class TestDistributedAtomicLong method testSimulation.

@Test
public void testSimulation() throws Exception {
    final int threadQty = 20;
    final int executionQty = 50;
    final AtomicInteger optimisticTries = new AtomicInteger();
    final AtomicInteger promotedLockTries = new AtomicInteger();
    final AtomicInteger failures = new AtomicInteger();
    final AtomicInteger errors = new AtomicInteger();
    final SummaryStatistics timingStats = new SynchronizedSummaryStatistics();
    List<Future<Void>> procs = Lists.newArrayList();
    ExecutorService executorService = Executors.newFixedThreadPool(threadQty);
    for (int i = 0; i < threadQty; ++i) {
        Callable<Void> proc = new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                doSimulation(executionQty, timingStats, optimisticTries, promotedLockTries, failures, errors);
                return null;
            }
        };
        procs.add(executorService.submit(proc));
    }
    for (Future<Void> f : procs) {
        f.get();
    }
    System.out.println("OptimisticTries: " + optimisticTries.get());
    System.out.println("PromotedLockTries: " + promotedLockTries.get());
    System.out.println("Failures: " + failures.get());
    System.out.println("Errors: " + errors.get());
    System.out.println();
    System.out.println("Avg time: " + timingStats.getMean());
    System.out.println("Max time: " + timingStats.getMax());
    System.out.println("Min time: " + timingStats.getMin());
    System.out.println("Qty: " + timingStats.getN());
    Assert.assertEquals(errors.get(), 0);
    Assert.assertTrue(optimisticTries.get() > 0);
    Assert.assertTrue(promotedLockTries.get() > 0);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) SynchronizedSummaryStatistics(org.apache.commons.math3.stat.descriptive.SynchronizedSummaryStatistics) SummaryStatistics(org.apache.commons.math3.stat.descriptive.SummaryStatistics) Future(java.util.concurrent.Future) SynchronizedSummaryStatistics(org.apache.commons.math3.stat.descriptive.SynchronizedSummaryStatistics) Callable(java.util.concurrent.Callable) Test(org.testng.annotations.Test)

Example 77 with Max

use of org.apache.commons.math3.stat.descriptive.rank.Max in project narchy by automenta.

the class MyCMAESOptimizer method doOptimize.

// /**
// * {@inheritDoc}
// *
// * @param optData Optimization data. In addition to those documented in
// * {@link MultivariateOptimizer#parseOptimizationData(OptimizationData[])
// * MultivariateOptimizer}, this method will register the following data:
// * <ul>
// *  <li>{@link MyCMAESOptimizer.Sigma}</li>
// *  <li>{@link MyCMAESOptimizer.PopulationSize}</li>
// * </ul>
// * @return {@inheritDoc}
// * @throws TooManyEvaluationsException if the maximal number of
// * evaluations is exceeded.
// * @throws DimensionMismatchException if the initial guess, target, and weight
// * arguments have inconsistent dimensions.
// */
// @Override
// public PointValuePair optimize(OptimizationData... optData)
// throws TooManyEvaluationsException,
// DimensionMismatchException {
// // Set up base class and perform computation.
// return super.optimize(optData);
// }
/**
 * {@inheritDoc}
 */
@Override
protected PointValuePair doOptimize() {
    // -------------------- Initialization --------------------------------
    isMinimize = getGoalType().equals(GoalType.MINIMIZE);
    final MyCMAESOptimizer.FitnessFunction fitfun = new MyCMAESOptimizer.FitnessFunction();
    final double[] guess = getStartPoint();
    // number of objective variables/problem dimension
    dimension = guess.length;
    initializeCMA(guess);
    iterations = 0;
    MyCMAESOptimizer.ValuePenaltyPair valuePenalty = fitfun.value(guess);
    double bestValue = valuePenalty.value + valuePenalty.penalty;
    push(fitnessHistory, bestValue);
    PointValuePair optimum = new PointValuePair(guess, isMinimize ? bestValue : -bestValue);
    PointValuePair lastResult = null;
    final double[] lB = MyCMAESOptimizer.this.getLowerBound();
    final double[] uB = MyCMAESOptimizer.this.getUpperBound();
    generationLoop: for (iterations = 1; iterations <= maxIterations; iterations++) {
        incrementIterationCount();
        // Generate and evaluate lambda offspring
        final RealMatrix arz = randn1(dimension, lambda);
        final RealMatrix arx = zeros(dimension, lambda);
        final double[] fitness = new double[lambda];
        final MyCMAESOptimizer.ValuePenaltyPair[] valuePenaltyPairs = new MyCMAESOptimizer.ValuePenaltyPair[lambda];
        // generate random offspring
        for (int k = 0; k < lambda; k++) {
            RealMatrix arzK = arz.getColumnMatrix(k);
            RealMatrix arxk = null;
            for (int i = 0; i < checkFeasableCount + 1; i++) {
                if (diagonalOnly <= 0) {
                    arxk = xmean.add(BD.multiply(arzK).scalarMultiply(// m + sig * Normal(0,C)
                    sigma));
                } else {
                    arxk = xmean.add(times(diagD, arzK).scalarMultiply(sigma));
                }
                if (i >= checkFeasableCount || fitfun.isFeasible(arxk.getColumn(0), lB, uB)) {
                    break;
                }
                // regenerate random arguments for row
                arz.setColumn(k, randn(dimension));
            }
            copyColumn(arxk, 0, arx, k);
            try {
                // compute fitness
                valuePenaltyPairs[k] = fitfun.value(arx.getColumn(k));
            } catch (TooManyEvaluationsException e) {
                break generationLoop;
            }
        }
        // Compute fitnesses by adding value and penalty after scaling by value range.
        double valueRange = valueRange(valuePenaltyPairs);
        for (int iValue = 0; iValue < valuePenaltyPairs.length; iValue++) {
            fitness[iValue] = valuePenaltyPairs[iValue].value + valuePenaltyPairs[iValue].penalty * valueRange;
        }
        // Sort by fitness and compute weighted mean into xmean
        final int[] arindex = sortedIndices(fitness);
        // Calculate new xmean, this is selection and recombination
        // for speed up of Eq. (2) and (3)
        final RealMatrix xold = xmean;
        int[] arMu = MathArrays.copyOf(arindex, mu);
        final RealMatrix bestArx = selectColumns(arx, arMu);
        xmean = bestArx.multiply(weights);
        final RealMatrix bestArz = selectColumns(arz, arMu);
        final RealMatrix zmean = bestArz.multiply(weights);
        final boolean hsig = updateEvolutionPaths(zmean, xold);
        if (diagonalOnly <= 0) {
            updateCovariance(hsig, bestArx, arz, arindex, xold);
        } else {
            updateCovarianceDiagonalOnly(hsig, bestArz);
        }
        // Adapt step size sigma - Eq. (5)
        sigma *= Math.exp(Math.min(1, (normps / chiN - 1) * cs / damps));
        final double bestFitness = fitness[arindex[0]];
        final double worstFitness = fitness[arindex[arindex.length - 1]];
        if (bestValue > bestFitness) {
            bestValue = bestFitness;
            lastResult = optimum;
            optimum = new PointValuePair(fitfun.repair(bestArx.getColumn(0)), isMinimize ? bestFitness : -bestFitness);
            if (getConvergenceChecker() != null && getConvergenceChecker().converged(iterations, optimum, lastResult)) {
                break generationLoop;
            }
        }
        // Break, if fitness is good enough
        if (stopFitness == stopFitness && bestFitness < (isMinimize ? stopFitness : -stopFitness)) {
            break generationLoop;
        }
        final double[] sqrtDiagC = sqrt(diagC).getColumn(0);
        final double[] pcCol = pc.getColumn(0);
        for (int i = 0; i < dimension; i++) {
            if (sigma * Math.max(Math.abs(pcCol[i]), sqrtDiagC[i]) > stopTolX) {
                break;
            }
            if (i >= dimension - 1) {
                break generationLoop;
            }
        }
        for (int i = 0; i < dimension; i++) {
            if (sigma * sqrtDiagC[i] > stopTolUpX) {
                break generationLoop;
            }
        }
        final double historyBest = min(fitnessHistory);
        final double historyWorst = max(fitnessHistory);
        if (iterations > 2 && Math.max(historyWorst, worstFitness) - Math.min(historyBest, bestFitness) < stopTolFun) {
            break generationLoop;
        }
        if (iterations > fitnessHistory.length && historyWorst - historyBest < stopTolHistFun) {
            break generationLoop;
        }
        // condition number of the covariance matrix exceeds 1e14
        if (max(diagD) / min(diagD) > tENmILLION) {
            break generationLoop;
        }
        // user defined termination
        if (getConvergenceChecker() != null) {
            final PointValuePair current = new PointValuePair(bestArx.getColumn(0), isMinimize ? bestFitness : -bestFitness);
            if (lastResult != null && getConvergenceChecker().converged(iterations, current, lastResult)) {
                break generationLoop;
            }
            lastResult = current;
        }
        // Adjust step size in case of equal function values (flat fitness)
        if (bestValue == fitness[arindex[(int) (0.1 + lambda / 4.0)]]) {
            sigma *= Math.exp(0.2 + cs / damps);
        }
        if (iterations > 2 && Math.max(historyWorst, bestFitness) - Math.min(historyBest, bestFitness) == 0) {
            sigma *= Math.exp(0.2 + cs / damps);
        }
        // store best in history
        push(fitnessHistory, bestFitness);
        if (generateStatistics) {
            statisticsSigmaHistory.add(sigma);
            statisticsFitnessHistory.add(bestFitness);
            statisticsMeanHistory.add(xmean.transpose());
            statisticsDHistory.add(diagD.transpose().scalarMultiply(hUNDreDtHOUSAND));
        }
    }
    return optimum;
}
Also used : TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) RealMatrix(org.apache.commons.math3.linear.RealMatrix) PointValuePair(org.apache.commons.math3.optim.PointValuePair)

Example 78 with Max

use of org.apache.commons.math3.stat.descriptive.rank.Max in project narchy by automenta.

the class MyCMAESOptimizer method updateBD.

/**
 * Update B and D from C.
 *
 * @param negccov Negative covariance factor.
 */
private void updateBD(double negccov) {
    if (ccov1 + ccovmu + negccov > 0 && (iterations % 1.0 / (ccov1 + ccovmu + negccov) / dimension / dimensionDivisorWTF) < 1) {
        // to achieve O(N^2)
        C = triu(C, 0).add(triu(C, 1).transpose());
        // enforce symmetry to prevent complex numbers
        final EigenDecomposition eig = new EigenDecomposition(C);
        // eigen decomposition, B==normalized eigenvectors
        B = eig.getV();
        D = eig.getD();
        diagD = diag(D);
        if (min(diagD) <= 0) {
            for (int i = 0; i < dimension; i++) {
                if (diagD.getEntry(i, 0) < 0) {
                    diagD.setEntry(i, 0, 0);
                }
            }
            final double tfac = max(diagD) / big_magic_number_WTF;
            C = C.add(eye(dimension, dimension).scalarMultiply(tfac));
            diagD = diagD.add(ones(dimension, 1).scalarMultiply(tfac));
        }
        if (max(diagD) > big_magic_number_WTF * min(diagD)) {
            final double tfac = max(diagD) / big_magic_number_WTF - min(diagD);
            C = C.add(eye(dimension, dimension).scalarMultiply(tfac));
            diagD = diagD.add(ones(dimension, 1).scalarMultiply(tfac));
        }
        diagC = diag(C);
        // D contains standard deviations now
        diagD = sqrt(diagD);
        // O(n^2)
        BD = times(B, repmat(diagD.transpose(), dimension, 1));
    }
}
Also used : EigenDecomposition(org.apache.commons.math3.linear.EigenDecomposition)

Example 79 with Max

use of org.apache.commons.math3.stat.descriptive.rank.Max in project narchy by automenta.

the class Optimize method run.

public Result<X> run(int maxIterations, int repeats, FloatFunction<Supplier<X>> eval) {
    assert (repeats >= 1);
    final int dim = tweaks.size();
    double[] mid = new double[dim];
    // double[] sigma = new double[n];
    double[] min = new double[dim];
    double[] max = new double[dim];
    double[] inc = new double[dim];
    // double[] range = new double[dim];
    X example = subject.get();
    int i = 0;
    for (Tweak w : tweaks) {
        TweakFloat s = (TweakFloat) w;
        // initial guess: get from sample, otherwise midpoint of min/max range
        Object guess = s.get(example);
        mid[i] = guess != null ? ((float) guess) : ((s.getMax() + s.getMin()) / 2f);
        min[i] = (s.getMin());
        max[i] = (s.getMax());
        inc[i] = s.getInc();
        // range[i] = max[i] - min[i];
        // sigma[i] = Math.abs(max[i] - min[i]) * 0.75f; //(s.getInc());
        i++;
    }
    FasterList<DoubleObjectPair<double[]>> experiments = new FasterList<>(maxIterations);
    final double[] maxScore = { Double.NEGATIVE_INFINITY };
    ObjectiveFunction func = new ObjectiveFunction(point -> {
        double score;
        try {
            double sum = 0;
            for (int r = 0; r < repeats; r++) {
                Supplier<X> x = () -> subject(point);
                sum += eval.floatValueOf(x);
            }
            score = sum / repeats;
        } catch (Exception e) {
            logger.error("{} {} {}", this, point, e);
            score = Float.NEGATIVE_INFINITY;
        }
        if (trace)
            csv.out(ArrayUtils.add(point, (int) 0, score));
        maxScore[0] = Math.max(maxScore[0], score);
        // System.out.println(
        // n4(score) + " / " + n4(maxScore[0]) + "\t" + n4(point)
        // );
        experiments.add(pair(score, point));
        experimentIteration(point, score);
        return score;
    });
    if (trace)
        csv = new CSVOutput(System.out, Stream.concat(Stream.of("score"), tweaks.stream().map(t -> t.id)).toArray(String[]::new));
    experimentStart();
    try {
        solve(dim, func, mid, min, max, inc, maxIterations);
    } catch (Throwable t) {
        logger.info("solve {} {}", func, t);
    }
    return new Result<>(experiments, tweaks);
}
Also used : MultiDirectionalSimplex(org.apache.commons.math3.optim.nonlinear.scalar.noderiv.MultiDirectionalSimplex) Logger(org.slf4j.Logger) SortedSet(java.util.SortedSet) DoubleObjectPair(org.eclipse.collections.api.tuple.primitive.DoubleObjectPair) MathArrays(org.apache.commons.math3.util.MathArrays) FasterList(jcog.list.FasterList) LoggerFactory(org.slf4j.LoggerFactory) ArrayUtils(org.apache.commons.lang3.ArrayUtils) ObjectiveFunction(org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction) Supplier(java.util.function.Supplier) SimplexOptimizer(org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer) List(java.util.List) Stream(java.util.stream.Stream) MersenneTwister(org.apache.commons.math3.random.MersenneTwister) GoalType(org.apache.commons.math3.optim.nonlinear.scalar.GoalType) Map(java.util.Map) PrimitiveTuples.pair(org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples.pair) CSVOutput(jcog.meter.event.CSVOutput) InitialGuess(org.apache.commons.math3.optim.InitialGuess) MaxEval(org.apache.commons.math3.optim.MaxEval) Pair(org.eclipse.collections.api.tuple.Pair) FloatFunction(org.eclipse.collections.api.block.function.primitive.FloatFunction) Joiner(com.google.common.base.Joiner) SimpleBounds(org.apache.commons.math3.optim.SimpleBounds) FasterList(jcog.list.FasterList) ObjectiveFunction(org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction) DoubleObjectPair(org.eclipse.collections.api.tuple.primitive.DoubleObjectPair) CSVOutput(jcog.meter.event.CSVOutput)

Example 80 with Max

use of org.apache.commons.math3.stat.descriptive.rank.Max in project chordatlas by twak.

the class SkelFootprint method profileRuns.

private static void profileRuns(SuperLine sl, MultiMap<SuperLine, List<Prof>> profSets) {
    MegaFacade mf = sl.getMega();
    Cache<Integer, Double> distance2Next = new Cache<Integer, Double>() {

        @Override
        public Double create(Integer i) {
            Prof pc = mf.profiles.get(i), pn = mf.profiles.get(i + 1);
            if (pc == null || pn == null)
                return 1e6;
            return pc.distance(pn, true, false, false);
        }
    };
    // i -> mf.profiles.get( i ).distance( mf.profiles.get(i+1), true ));
    int start = mf.hExtentMin;
    for (int i = mf.hExtentMin; i < mf.hExtentMax; i++) {
        if (distance2Next.get(i) > 4 || i == mf.hExtentMax - 1) {
            // if ( (Math.random() > 0.95 || i == mf.hExtentMax - 1)  ){//0.5 / ProfileGen.HORIZ_SAMPLE_DIST) {
            if (i - start > 0.5 / TweedSettings.settings.profileHSampleDist) {
                List<Prof> lp = IntStream.range(start, i + 1).mapToObj(p -> mf.profiles.get(p)).filter(p -> p != null).collect(Collectors.toList());
                if (lp != null && !lp.isEmpty())
                    profSets.put(sl, lp);
            }
            start = i + 1;
        // i++;
        // }
        }
    }
// System.out.println( (mf.hExtentMax - mf.hExtentMin)+  " mm " + min+ " / " + max +" found " + profSets.size() );
}
Also used : Color(java.awt.Color) XStream(com.thoughtworks.xstream.XStream) Arrays(java.util.Arrays) FloatBuffer(java.nio.FloatBuffer) HalfFace(org.twak.utils.geom.HalfMesh2.HalfFace) Type(com.jme3.scene.VertexBuffer.Type) Arrayz(org.twak.utils.collections.Arrayz) Loop(org.twak.utils.collections.Loop) Node(com.jme3.scene.Node) SkelGen(org.twak.tweed.gen.skel.SkelGen) MutableDouble(org.twak.utils.MutableDouble) ColorRGBAPainter(org.twak.viewTrace.ColorRGBAPainter) Map(java.util.Map) Cache(org.twak.utils.Cache) Material(com.jme3.material.Material) ChangeListener(javax.swing.event.ChangeListener) Streamz(org.twak.utils.collections.Streamz) Point3d(javax.vecmath.Point3d) ChangeEvent(javax.swing.event.ChangeEvent) VertexBuffer(com.jme3.scene.VertexBuffer) LoopL(org.twak.utils.collections.LoopL) Predicate(java.util.function.Predicate) Line(org.twak.utils.Line) HalfEdge(org.twak.utils.geom.HalfMesh2.HalfEdge) Set(java.util.Set) HalfMesh2(org.twak.utils.geom.HalfMesh2) CollisionResult(com.jme3.collision.CollisionResult) Vector2d(javax.vecmath.Vector2d) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) MFPoint(org.twak.tweed.gen.FeatureCache.MFPoint) List(java.util.List) JSlider(javax.swing.JSlider) Optional(java.util.Optional) Rainbow(org.twak.utils.ui.Rainbow) CollisionResults(com.jme3.collision.CollisionResults) Mesh(com.jme3.scene.Mesh) Geometry(com.jme3.scene.Geometry) IntStream(java.util.stream.IntStream) ActionListener(java.awt.event.ActionListener) DBSCANClusterer(org.apache.commons.math3.ml.clustering.DBSCANClusterer) Vector2f(com.jme3.math.Vector2f) HashMap(java.util.HashMap) MiniFacade(org.twak.viewTrace.facades.MiniFacade) Cach(org.twak.utils.Cach) Plot(org.twak.utils.ui.Plot) SwingConstants(javax.swing.SwingConstants) TreeSet(java.util.TreeSet) Clusterable(org.apache.commons.math3.ml.clustering.Clusterable) Tweed(org.twak.tweed.Tweed) IndexBuffer(com.jme3.scene.mesh.IndexBuffer) ArrayList(java.util.ArrayList) TweedSettings(org.twak.tweed.TweedSettings) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Mathz(org.twak.utils.Mathz) PaintThing(org.twak.utils.PaintThing) NoSuchElementException(java.util.NoSuchElementException) ProgressMonitor(javax.swing.ProgressMonitor) LinkedHashSet(java.util.LinkedHashSet) MatParam(com.jme3.material.MatParam) JButton(javax.swing.JButton) Texture2D(com.jme3.texture.Texture2D) Iterator(java.util.Iterator) MultiMap(org.twak.utils.collections.MultiMap) BufferUtils(com.jme3.util.BufferUtils) Vector3f(com.jme3.math.Vector3f) MeshBuilder(org.twak.siteplan.jme.MeshBuilder) MegaFacade(org.twak.tweed.gen.ProfileGen.MegaFacade) ModeCollector(org.twak.viewTrace.ModeCollector) JOptionPane(javax.swing.JOptionPane) MegaFeatures(org.twak.tweed.gen.FeatureCache.MegaFeatures) ActionEvent(java.awt.event.ActionEvent) File(java.io.File) Loopz(org.twak.utils.collections.Loopz) Point2d(javax.vecmath.Point2d) Jme3z(org.twak.siteplan.jme.Jme3z) Ray(com.jme3.math.Ray) SuperLine(org.twak.viewTrace.SuperLine) LineHeight(org.twak.viewTrace.facades.LineHeight) Format(com.jme3.scene.VertexBuffer.Format) Cluster(org.apache.commons.math3.ml.clustering.Cluster) ColorRGBA(com.jme3.math.ColorRGBA) FileReader(java.io.FileReader) ImageRaster(com.jme3.texture.image.ImageRaster) Comparator(java.util.Comparator) Collections(java.util.Collections) MegaFacade(org.twak.tweed.gen.ProfileGen.MegaFacade) MutableDouble(org.twak.utils.MutableDouble) MFPoint(org.twak.tweed.gen.FeatureCache.MFPoint) Cache(org.twak.utils.Cache)

Aggregations

ArrayList (java.util.ArrayList)26 List (java.util.List)19 Collectors (java.util.stream.Collectors)13 DescriptiveStatistics (org.apache.commons.math3.stat.descriptive.DescriptiveStatistics)13 Arrays (java.util.Arrays)11 Map (java.util.Map)11 IntStream (java.util.stream.IntStream)10 RandomGenerator (org.apache.commons.math3.random.RandomGenerator)10 Array2DRowRealMatrix (org.apache.commons.math3.linear.Array2DRowRealMatrix)9 RealMatrix (org.apache.commons.math3.linear.RealMatrix)9 Plot2 (ij.gui.Plot2)8 File (java.io.File)8 IOException (java.io.IOException)8 TooManyEvaluationsException (org.apache.commons.math3.exception.TooManyEvaluationsException)7 Test (org.testng.annotations.Test)7 StoredDataStatistics (gdsc.core.utils.StoredDataStatistics)6 Collections (java.util.Collections)6 HashMap (java.util.HashMap)6 Random (java.util.Random)6 UnivariateFunction (org.apache.commons.math3.analysis.UnivariateFunction)6