Example usage for java.lang Double MAX_VALUE

List of usage examples for java.lang Double MAX_VALUE

Introduction

In this page you can find the example usage for java.lang Double MAX_VALUE.

Prototype

double MAX_VALUE

To view the source code for java.lang Double MAX_VALUE.

Click Source Link

Document

A constant holding the largest positive finite value of type double , (2-2-52)·21023.

Usage

From source file:edu.stanford.cfuller.imageanalysistools.fitting.GaussianImageObject.java

/**
 * Fits this object to a 3-dimensional gaussian, and estimates error and goodness of fit.
 * @param p     The parameters for the current analysis.
 *//*from www.jav a2 s.c  o m*/
public void fitPosition(ParameterDictionary p) {

    if (this.sizeInPixels == 0) {
        this.nullifyImages();
        return;
    }

    this.fitParametersByChannel = new java.util.ArrayList<FitParameters>();
    this.fitR2ByChannel = new java.util.ArrayList<Double>();
    this.fitErrorByChannel = new java.util.ArrayList<Double>();
    this.nPhotonsByChannel = new java.util.ArrayList<Double>();

    GaussianFitter3D gf = new GaussianFitter3D();

    //System.out.println(this.parent.getDimensionSizes().getZ());

    int numChannels = 0;

    if (p.hasKey(NUM_WAVELENGTHS_PARAM)) {
        numChannels = p.getIntValueForKey(NUM_WAVELENGTHS_PARAM);
    } else {
        numChannels = this.parent.getDimensionSizes().get(ImageCoordinate.C);
    }

    for (int channelIndex = 0; channelIndex < numChannels; channelIndex++) {

        RealVector fitParameters = new ArrayRealVector(7, 0.0);

        double ppg = p.getDoubleValueForKey(PHOTONS_PER_LEVEL_PARAM);

        this.parentBoxMin.set(ImageCoordinate.C, channelIndex);
        this.parentBoxMax.set(ImageCoordinate.C, channelIndex + 1);

        this.boxImages();

        List<Double> x = new java.util.ArrayList<Double>();
        List<Double> y = new java.util.ArrayList<Double>();
        List<Double> z = new java.util.ArrayList<Double>();
        List<Double> f = new java.util.ArrayList<Double>();

        for (ImageCoordinate ic : this.parent) {
            x.add((double) ic.get(ImageCoordinate.X));
            y.add((double) ic.get(ImageCoordinate.Y));
            z.add((double) ic.get(ImageCoordinate.Z));
            f.add((double) parent.getValue(ic));
        }

        xValues = new double[x.size()];
        yValues = new double[y.size()];
        zValues = new double[z.size()];
        functionValues = new double[f.size()];

        double xCentroid = 0;
        double yCentroid = 0;
        double zCentroid = 0;
        double totalCounts = 0;

        for (int i = 0; i < x.size(); i++) {

            xValues[i] = x.get(i);
            yValues[i] = y.get(i);
            zValues[i] = z.get(i);
            functionValues[i] = f.get(i) * ppg;
            xCentroid += xValues[i] * functionValues[i];
            yCentroid += yValues[i] * functionValues[i];
            zCentroid += zValues[i] * functionValues[i];
            totalCounts += functionValues[i];
        }

        xCentroid /= totalCounts;
        yCentroid /= totalCounts;
        zCentroid /= totalCounts;

        //z sometimes seems to be a bit off... trying (20110415) to go back to max value pixel at x,y centroid

        int xRound = (int) Math.round(xCentroid);
        int yRound = (int) Math.round(yCentroid);

        double maxVal = 0;
        int maxInd = 0;

        double minZ = Double.MAX_VALUE;
        double maxZ = 0;

        for (int i = 0; i < x.size(); i++) {

            if (zValues[i] < minZ)
                minZ = zValues[i];
            if (zValues[i] > maxZ)
                maxZ = zValues[i];

            if (xValues[i] == xRound && yValues[i] == yRound) {
                if (functionValues[i] > maxVal) {
                    maxVal = functionValues[i];
                    maxInd = (int) zValues[i];
                }
            }
        }

        zCentroid = maxInd;

        //parameter ordering: amplitude, var x-y, var z, x/y/z coords, background

        //amplitude: find the max value; background: find the min value

        double maxValue = 0;

        double minValue = Double.MAX_VALUE;

        for (ImageCoordinate ic : this.parent) {

            if (parent.getValue(ic) > maxValue)
                maxValue = parent.getValue(ic);
            if (parent.getValue(ic) < minValue)
                minValue = parent.getValue(ic);

        }

        fitParameters.setEntry(0, (maxValue - minValue) * 0.95);
        fitParameters.setEntry(6, minValue + 0.05 * (maxValue - minValue));

        //positions

        fitParameters.setEntry(3, xCentroid);
        fitParameters.setEntry(4, yCentroid);
        fitParameters.setEntry(5, zCentroid);

        //variances

        final double limitedWidthxy = 200;
        final double limitedWidthz = 500;

        double sizex = limitedWidthxy / p.getDoubleValueForKey(PIXELSIZE_PARAM);
        double sizez = limitedWidthz / p.getDoubleValueForKey(SECTIONSIZE_PARAM);

        if (p.hasKey(Z_WIDTH_PARAM)) {
            sizez = p.getDoubleValueForKey(Z_WIDTH_PARAM);
        }

        if (p.hasKey(XY_WIDTH_PARAM)) {
            sizex = p.getDoubleValueForKey(XY_WIDTH_PARAM);
        }

        fitParameters.setEntry(1, sizex / 2);
        fitParameters.setEntry(2, sizez / 2);

        //amplitude and background are in arbitrary intensity units; convert to photon counts

        fitParameters.setEntry(0, fitParameters.getEntry(0) * ppg);
        fitParameters.setEntry(6, fitParameters.getEntry(6) * ppg);

        //System.out.println("guess: " + fitParameters);

        //do the fit

        fitParameters = gf.fit(this, fitParameters, ppg);

        //System.out.println("fit: " + fitParameters);

        FitParameters fp = new FitParameters();

        fp.setPosition(ImageCoordinate.X, fitParameters.getEntry(3));
        fp.setPosition(ImageCoordinate.Y, fitParameters.getEntry(4));
        fp.setPosition(ImageCoordinate.Z, fitParameters.getEntry(5));

        fp.setSize(ImageCoordinate.X, fitParameters.getEntry(1));
        fp.setSize(ImageCoordinate.Y, fitParameters.getEntry(1));
        fp.setSize(ImageCoordinate.Z, fitParameters.getEntry(2));

        fp.setAmplitude(fitParameters.getEntry(0));
        fp.setBackground(fitParameters.getEntry(6));

        fitParametersByChannel.add(fp);

        //calculate R2

        double residualSumSquared = 0;
        double mean = 0;
        double variance = 0;
        double R2 = 0;

        double n_photons = 0;

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

            residualSumSquared += Math.pow(GaussianFitter3D.fitResidual(functionValues[i], xValues[i],
                    yValues[i], zValues[i], fitParameters), 2);

            mean += functionValues[i];

            n_photons += functionValues[i] - fitParameters.getEntry(6);

        }

        mean /= functionValues.length;

        for (int i = 0; i < this.xValues.length; i++) {
            variance += Math.pow(functionValues[i] - mean, 2);
        }

        R2 = 1 - (residualSumSquared / variance);

        this.fitR2ByChannel.add(R2);

        this.unboxImages();

        //calculate fit error

        double s_xy = fitParameters.getEntry(1) * fitParameters.getEntry(1)
                * Math.pow(p.getDoubleValueForKey(PIXELSIZE_PARAM), 2);
        double s_z = fitParameters.getEntry(2) * fitParameters.getEntry(2)
                * Math.pow(p.getDoubleValueForKey(SECTIONSIZE_PARAM), 2);

        //s_z = 0; //remove!!

        double error = (2 * s_xy + s_z) / (n_photons - 1);// + 4*Math.sqrt(Math.PI) * Math.pow(2*s_xy,1.5)*Math.pow(fitParameters.getEntry(6),2)/(p.getDoubleValueForKey("pixelsize_nm")*n_photons*n_photons);

        double b = fitParameters.getEntry(6);
        double a = p.getDoubleValueForKey(PIXELSIZE_PARAM);
        double alpha = p.getDoubleValueForKey(SECTIONSIZE_PARAM);
        double sa_x = s_xy + Math.pow(a, 2) / 12;
        double sa_z = s_z + Math.pow(alpha, 2) / 12;

        //System.out.printf("b = %f, a = %f, alpha = %f, s_xy = %f, s_z = %f, n= %f\n", b, a, alpha, s_xy, s_z, n_photons);

        double error_x = sa_x / n_photons * (16.0 / 9.0 + 8 * Math.PI * sa_x * b * b
                / (n_photons * Math.pow(p.getDoubleValueForKey(PIXELSIZE_PARAM), 2)));
        double error_z = sa_z / n_photons * (16.0 / 9.0 + 8 * Math.PI * sa_z * b * b
                / (n_photons * Math.pow(p.getDoubleValueForKey(SECTIONSIZE_PARAM), 2)));

        double A = 1.0 / (2 * Math.sqrt(2) * Math.pow(Math.PI, 1.5) * Math.sqrt(sa_z) * sa_x);

        ErrIntFunc eif = new ErrIntFunc();

        eif.setParams(b, n_photons, A, sa_z, sa_x, a, alpha);

        LegendreGaussIntegrator lgi = new LegendreGaussIntegrator(5, 10, 1000);

        //integrate over 10*width of PSF in z 

        double size = 10 * Math.sqrt(sa_z);

        double intpart = 0;
        try {

            if (b < 0)
                throw new ConvergenceException(new DummyLocalizable("negative background!")); // a negative value for b seems to cause the integration to hang, preventing the program from progressing

            intpart = lgi.integrate(10000, eif, -size, size);

            double fullIntPart = intpart + Math.pow(2 * Math.PI, 1.5) * sa_x * A / Math.sqrt(sa_z);

            error_x = Math.sqrt(2 / (n_photons * sa_z / (2 * sa_z + sa_x) * fullIntPart));
            error_z = Math.sqrt(2 / (n_photons * sa_x / (2 * sa_z + sa_x) * fullIntPart));

        } catch (ConvergenceException e) {
            LoggingUtilities.getLogger().severe("Integration error: " + e.getMessage());
            error_x = -1;
            error_z = -1;
        }

        if (error_x > 0 && error_z > 0) {

            error = Math.sqrt(2 * error_x * error_x + error_z * error_z);

        } else {
            error = Double.NaN;
        }

        this.fitErrorByChannel.add(error);

        this.positionsByChannel.add(fitParameters.getSubVector(3, 3));

        this.nPhotonsByChannel.add(n_photons);

    }

    this.hadFittingError = false;
}

From source file:eu.vital.orchestrator.rest.EvaluationRESTService.java

@POST
@Path("/prediction")
public Response executePredictionScenario(JsonNode input) throws Exception {
    String dmsUrl = "https://local.vital-iot.eu:8443/vital-core-dms";

    // 1. Get List of sensors from DMS observing AvailableBikes
    Client dmsClient = ClientBuilder.newClient();
    WebTarget dmsTarget = dmsClient.target(dmsUrl).path("querySensor").queryParam("encodeKeys", "false");
    ObjectNode sensorQuery = objectMapper.createObjectNode();
    sensorQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observes.@type",
            "http://vital-iot.eu/ontology/ns/Speed");
    ArrayNode sensorList = dmsTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(sensorQuery),
            ArrayNode.class);

    // 2. Find the nearest sensor
    double minDistance = Double.MAX_VALUE;
    JsonNode nearestSensor = null;//from  w w  w. java2 s  .c  o  m
    for (int i = 0; i < sensorList.size(); i++) {
        JsonNode sensor = sensorList.get(i);

        // Calculate Distance:
        double tmp = distance(input.get("lat").asDouble(), input.get("lng").asDouble(),
                sensor.get("hasLastKnownLocation").get("geo:lat").asDouble(),
                sensor.get("hasLastKnownLocation").has("geo:long")
                        ? sensor.get("hasLastKnownLocation").get("geo:long").asDouble()
                        : sensor.get("hasLastKnownLocation").get("geo:lon").asDouble());
        if (tmp < minDistance) {
            minDistance = tmp;
            nearestSensor = sensor;
        }
    }

    // 3. Get all observations of this sensor from DMS archive
    dmsTarget = dmsClient.target(dmsUrl).path("queryObservation").queryParam("encodeKeys", "false");
    ObjectNode observationQuery = objectMapper.createObjectNode();
    observationQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observedBy.@value",
            nearestSensor.get("id").asText());
    observationQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observationProperty.@type",
            "http://vital-iot.eu/ontology/ns/Speed");

    ArrayNode observationList = dmsTarget.request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.json(observationQuery), ArrayNode.class);

    // 4. Run the prediction algorithm
    SimpleRegression regression = new SimpleRegression();
    for (int i = 0; i < observationList.size(); i++) {
        JsonNode observation = observationList.get(i);
        double value = observation.get("ssn:observationResult").get("ssn:hasValue").get("value").asDouble();
        String dateStr = observation.get("ssn:observationResultTime").get("time:inXSDDateTime").asText();
        Calendar date = javax.xml.bind.DatatypeConverter.parseDateTime(dateStr);
        regression.addData(date.getTimeInMillis(), value);
    }
    double futureMillis = javax.xml.bind.DatatypeConverter.parseDateTime(input.get("atDate").asText())
            .getTimeInMillis();
    double prediction = regression.predict(futureMillis);

    // 5. Return the result:
    ObjectNode result = objectMapper.createObjectNode();
    result.put("predictionValue", prediction);
    result.put("predictionDate", input.get("atDate").asText());

    return Response.ok(result).build();
}

From source file:edu.stanford.cfuller.imageanalysistools.fitting.NelderMeadMinimizer.java

/**
 * Runs the minimization of the specified function starting from an initial simplex.
 * @param f                 The ObjectiveFunction to be minimized.
 * @param initialSimplex    The initial simplex to use to start optimization, as might be returned from {@link #generateInitialSimplex}
 * @return                  The parameters at the function minimum in the same order as specified for each point on the simplex.
 *//*from  ww w.  j  av  a 2  s  . c o  m*/
public RealVector optimize(ObjectiveFunction f, RealMatrix initialSimplex) {

    RealMatrix currentSimplex = initialSimplex.copy();

    double currTolVal = 1.0e6;

    RealVector values = new ArrayRealVector(initialSimplex.getRowDimension(), 0.0);

    RealVector centerOfMass = new ArrayRealVector(initialSimplex.getColumnDimension(), 0.0);

    boolean shouldEvaluate = false;

    long iterCounter = 0;

    while (Math.abs(currTolVal) > this.tol) {

        int maxIndex = 0;
        int minIndex = 0;
        double maxValue = -1.0 * Double.MAX_VALUE;
        double minValue = Double.MAX_VALUE;
        double secondMaxValue = -1.0 * Double.MAX_VALUE;

        centerOfMass.mapMultiplyToSelf(0.0);

        if (shouldEvaluate) {

            for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
                RealVector currRow = currentSimplex.getRowVector(i);
                values.setEntry(i, f.evaluate(currRow));
            }

        }

        for (int i = 0; i < currentSimplex.getRowDimension(); i++) {

            double currValue = values.getEntry(i);

            if (currValue < minValue) {
                minValue = currValue;
                minIndex = i;
            }
            if (currValue > maxValue) {
                secondMaxValue = maxValue;
                maxValue = currValue;
                maxIndex = i;
            } else if (currValue > secondMaxValue) {
                secondMaxValue = currValue;
            }
        }

        for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
            if (i == maxIndex)
                continue;

            centerOfMass = centerOfMass.add(currentSimplex.getRowVector(i));

        }

        centerOfMass.mapDivideToSelf(currentSimplex.getRowDimension() - 1);

        RealVector oldPoint = currentSimplex.getRowVector(maxIndex);

        RealVector newPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(a).add(centerOfMass); // newpoint = COM + a*(COM-oldpoint)

        double newValue = f.evaluate(newPoint);

        if (newValue < secondMaxValue) { // success

            if (newValue < minValue) { // best found so far

                //expansion

                RealVector expPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(g).add(centerOfMass);

                double expValue = f.evaluate(expPoint);

                if (expValue < newValue) {
                    currentSimplex.setRowVector(maxIndex, expPoint);
                    currTolVal = 2.0 * (expValue - maxValue) / (1.0e-20 + expValue + maxValue);

                    values.setEntry(maxIndex, expValue);
                    shouldEvaluate = false;
                    continue;
                }

            }

            //reflection

            currentSimplex.setRowVector(maxIndex, newPoint);
            currTolVal = 2.0 * (newValue - maxValue) / (1.0e-20 + newValue + maxValue);
            values.setEntry(maxIndex, newValue);
            shouldEvaluate = false;
            continue;

        }

        //contraction

        RealVector conPoint = centerOfMass.subtract(oldPoint).mapMultiplyToSelf(r).add(centerOfMass);
        double conValue = f.evaluate(conPoint);

        if (conValue < maxValue) {
            currentSimplex.setRowVector(maxIndex, conPoint);
            currTolVal = 2.0 * (conValue - maxValue) / (1.0e-20 + conValue + maxValue);
            values.setEntry(maxIndex, conValue);
            shouldEvaluate = false;
            continue;
        }

        //reduction

        for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
            if (i == minIndex)
                continue;

            currentSimplex.setRowVector(i,
                    currentSimplex.getRowVector(i).subtract(currentSimplex.getRowVector(minIndex))
                            .mapMultiplyToSelf(s).add(currentSimplex.getRowVector(minIndex)));

        }

        double redValue = f.evaluate(currentSimplex.getRowVector(maxIndex));

        currTolVal = 2.0 * (redValue - maxValue) / (1.0e-20 + redValue + maxValue);

        shouldEvaluate = true;

        if (iterCounter++ > 100000) {
            System.out.println("stalled?  tol: " + currTolVal + "  minValue: " + minValue);
        }

    }

    double minValue = Double.MAX_VALUE;

    RealVector minVector = null;

    for (int i = 0; i < currentSimplex.getRowDimension(); i++) {
        values.setEntry(i, f.evaluate(currentSimplex.getRowVector(i)));
        if (values.getEntry(i) < minValue) {
            minValue = values.getEntry(i);
            minVector = currentSimplex.getRowVector(i);
        }
    }

    return minVector;

}

From source file:ml.shifu.shifu.core.NNTrainerTest.java

@Test
public void testAndOperation() throws IOException {
    MLDataPair dataPair0 = BasicMLDataPair.createPair(2, 1);
    dataPair0.setInputArray(new double[] { 0.0, 0.0 });
    dataPair0.setIdealArray(new double[] { 0.0 });
    trainSet.add(dataPair0);//from  w  ww .java2  s. c om

    MLDataPair dataPair1 = BasicMLDataPair.createPair(2, 1);
    dataPair1.setInputArray(new double[] { 0.0, 1.0 });
    dataPair1.setIdealArray(new double[] { 0.0 });
    trainSet.add(dataPair1);

    MLDataPair dataPair2 = BasicMLDataPair.createPair(2, 1);
    dataPair2.setInputArray(new double[] { 1.0, 0.0 });
    dataPair2.setIdealArray(new double[] { 0.0 });
    trainSet.add(dataPair2);

    MLDataPair dataPair3 = BasicMLDataPair.createPair(2, 1);
    dataPair3.setInputArray(new double[] { 1.0, 1.0 });
    dataPair3.setIdealArray(new double[] { 1.0 });
    trainSet.add(dataPair3);

    Propagation propagation = new QuickPropagation(network, trainSet, 0.1);

    double error = 0.0;
    double lastError = Double.MAX_VALUE;
    int iterCnt = 0;
    do {
        propagation.iteration();
        lastError = error;
        error = propagation.getError();
        System.out.println("The #" + (++iterCnt) + " error is " + error);
    } while (Math.abs(lastError - error) > 0.001);

    propagation.finishTraining();

    File tmp = new File("model_folder");
    if (!tmp.exists()) {
        FileUtils.forceMkdir(tmp);
    }
    File modelFile = new File("model_folder/model6.nn");
    EncogDirectoryPersistence.saveObject(modelFile, network);
    Assert.assertTrue(modelFile.exists());
    FileUtils.deleteQuietly(modelFile);
}

From source file:juicebox.tools.utils.original.NormalizationCalculations.java

private static double[] computeKRNormVector(SparseSymmetricMatrix A, double tol, double[] x0, double delta) {

    int n = x0.length;
    double[] e = new double[n];
    for (int i = 0; i < e.length; i++)
        e[i] = 1;//from  w  ww  .  j  a va  2s  .  c  o  m

    double g = 0.9;
    double etamax = 0.1;
    double eta = etamax;
    double[] x = x0;
    double rt = Math.pow(tol, 2);

    double[] v = A.multiply(x);
    double[] rk = new double[v.length];
    for (int i = 0; i < v.length; i++) {
        v[i] = v[i] * x[i];
        rk[i] = 1 - v[i];
    }
    double rho_km1 = 0;
    for (double aRk : rk) {
        rho_km1 += aRk * aRk;
    }
    double rout = rho_km1;
    double rold = rout;
    int MVP = 0; // We'll count matrix vector products.

    int not_changing = 0;
    while (rout > rt && not_changing < 100) { // Outer iteration
        int k = 0;
        double[] y = new double[e.length];
        double[] ynew = new double[e.length];
        double[] Z = new double[e.length];
        double[] p = new double[e.length];
        double[] w = new double[e.length];
        double alpha;
        double beta;
        double gamma;
        double rho_km2 = rho_km1;
        System.arraycopy(e, 0, y, 0, y.length);

        double innertol = Math.max(Math.pow(eta, 2) * rout, rt);
        while (rho_km1 > innertol) { // Inner iteration by CG
            k++;

            if (k == 1) {
                rho_km1 = 0;
                for (int i = 0; i < Z.length; i++) {
                    Z[i] = rk[i] / v[i];
                    p[i] = Z[i];
                    rho_km1 += rk[i] * Z[i];
                }
            } else {
                beta = rho_km1 / rho_km2;
                for (int i = 0; i < p.length; i++) {
                    p[i] = Z[i] + beta * p[i];
                }
            }
            double[] tmp = new double[e.length];
            for (int i = 0; i < tmp.length; i++) {
                tmp[i] = x[i] * p[i];
            }
            tmp = A.multiply(tmp);
            alpha = 0;
            // Update search direction efficiently.
            for (int i = 0; i < tmp.length; i++) {
                w[i] = x[i] * tmp[i] + v[i] * p[i];
                alpha += p[i] * w[i];
            }
            alpha = rho_km1 / alpha;
            double minynew = Double.MAX_VALUE;
            // Test distance to boundary of cone.
            for (int i = 0; i < p.length; i++) {
                ynew[i] = y[i] + alpha * p[i];
                if (ynew[i] < minynew)
                    minynew = ynew[i];
            }
            if (minynew <= delta) {
                if (delta == 0)
                    break; // break out of inner loop?
                gamma = Double.MAX_VALUE;
                for (int i = 0; i < ynew.length; i++) {
                    if (alpha * p[i] < 0) {
                        if ((delta - y[i]) / (alpha * p[i]) < gamma) {
                            gamma = (delta - y[i]) / (alpha * p[i]);
                        }
                    }
                }
                for (int i = 0; i < y.length; i++)
                    y[i] = y[i] + gamma * alpha * p[i];
                break; // break out of inner loop?
            }
            rho_km2 = rho_km1;
            rho_km1 = 0;
            for (int i = 0; i < y.length; i++) {
                y[i] = ynew[i];
                rk[i] = rk[i] - alpha * w[i];
                Z[i] = rk[i] / v[i];
                rho_km1 += rk[i] * Z[i];
            }

        } // end inner loop
        for (int i = 0; i < x.length; i++) {
            x[i] = x[i] * y[i];
        }
        v = A.multiply(x);
        rho_km1 = 0;
        for (int i = 0; i < v.length; i++) {
            v[i] = v[i] * x[i];
            rk[i] = 1 - v[i];
            rho_km1 += rk[i] * rk[i];
        }
        if (Math.abs(rho_km1 - rout) < 0.000001 || Double.isInfinite(rho_km1)) {
            not_changing++;
        }
        rout = rho_km1;
        MVP = MVP + k + 1;
        //  Update inner iteration stopping criterion.
        double rat = rout / rold;
        rold = rout;
        double r_norm = Math.sqrt(rout);
        double eta_o = eta;
        eta = g * rat;
        if (g * Math.pow(eta_o, 2) > 0.1) {
            eta = Math.max(eta, g * Math.pow(eta_o, 2));
        }
        eta = Math.max(Math.min(eta, etamax), 0.5 * tol / r_norm);
    }
    if (not_changing >= 100) {
        return null;
    }
    return x;
}

From source file:be.makercafe.apps.makerbench.editors.GCodeEditor.java

public GCodeEditor(String tabText, Path path) {
    super(tabText);

    this.viewGroup = new Group();
    this.editorContainer = new BorderPane();
    this.viewContainer = new Pane();

    this.caCodeArea = new CodeArea("");
    this.caCodeArea.setEditable(true);
    this.caCodeArea.setParagraphGraphicFactory(LineNumberFactory.get(caCodeArea));
    this.caCodeArea.setPrefSize(Double.MAX_VALUE, Double.MAX_VALUE);

    // this.caCodeArea.getStylesheets().add(this.getClass().getResource("java-keywords.css").toExternalForm());
    // this.caCodeArea.richChanges().subscribe(change -> {
    // caCodeArea.setStyleSpans(0,
    // computeHighlighting(caCodeArea.getText()));
    // });/*from   w ww . j a v  a 2 s .  c o  m*/

    addContextMenu(this.caCodeArea);
    EventStream<Change<String>> textEvents = EventStreams.changesOf(caCodeArea.textProperty());

    textEvents.reduceSuccessions((a, b) -> b, Duration.ofMillis(3000)).subscribe(code -> {
        if (autoCompile) {
            compile(code.getNewValue());
        }
    });

    if (path == null) {
        this.caCodeArea.replaceText("#empty");
    } else {
        try {
            this.caCodeArea.replaceText(FileUtils.readFileToString(path.toFile()));
        } catch (IOException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error reading file.", ex);
        }

    }

    // editorContainer.setCenter(this.codeArea);

    subScene = new SubScene(viewGroup, 100, 100, true, SceneAntialiasing.BALANCED);

    subScene.widthProperty().bind(viewContainer.widthProperty());
    subScene.heightProperty().bind(viewContainer.heightProperty());

    PerspectiveCamera subSceneCamera = new PerspectiveCamera(false);
    subScene.setCamera(subSceneCamera);

    viewContainer.getChildren().add(subScene);

    SplitPane editorPane = new SplitPane(caCodeArea, viewContainer);
    editorPane.setOrientation(Orientation.HORIZONTAL);
    BorderPane rootPane = new BorderPane();

    BorderPane pane = (BorderPane) this.getTab().getContent();
    toolBar = createToolBar();
    rootPane.setTop(toolBar);
    rootPane.setCenter(editorPane);
    this.getTab().setContent(rootPane);

    subScene.setOnScroll(new EventHandler<ScrollEvent>() {
        @Override
        public void handle(ScrollEvent event) {
            System.out
                    .println(String.format("deltaX: %.3f deltaY: %.3f", event.getDeltaX(), event.getDeltaY()));

            double z = subSceneCamera.getTranslateZ();
            double newZ = z + event.getDeltaY();
            subSceneCamera.setTranslateZ(newZ);

        }
    });

}

From source file:com.joptimizer.algebra.Matrix1NormRescaler.java

/**
 * Check if the scaling algorithm returned proper results.
 * Note that AOriginal cannot be only subdiagonal filled, because this check
 * is for both symm and bath notsymm matrices.
 * @param AOriginal the ORIGINAL (before scaling) matrix
 * @param U the return of the scaling algorithm
 * @param V the return of the scaling algorithm
 * @param base//from ww  w  .  ja v  a2s.  co m
 * @return
 */
public boolean checkScaling(final DoubleMatrix2D AOriginal, final DoubleMatrix1D U, final DoubleMatrix1D V) {

    int c = AOriginal.columns();
    int r = AOriginal.rows();
    final double[] maxValueHolder = new double[] { -Double.MAX_VALUE };

    IntIntDoubleFunction myFunct = new IntIntDoubleFunction() {
        public double apply(int i, int j, double pij) {
            maxValueHolder[0] = Math.max(maxValueHolder[0], Math.abs(pij));
            return pij;
        }
    };

    DoubleMatrix2D AScaled = ColtUtils.diagonalMatrixMult(U, AOriginal, V);

    //view A row by row
    boolean isOk = true;
    for (int i = 0; isOk && i < r; i++) {
        maxValueHolder[0] = -Double.MAX_VALUE;
        DoubleMatrix2D P = AScaled.viewPart(i, 0, 1, c);
        P.forEachNonZero(myFunct);
        isOk = Math.abs(1. - maxValueHolder[0]) < eps;
    }
    //view A col by col
    for (int j = 0; isOk && j < c; j++) {
        maxValueHolder[0] = -Double.MAX_VALUE;
        DoubleMatrix2D P = AScaled.viewPart(0, j, r, 1);
        P.forEachNonZero(myFunct);
        isOk = Math.abs(1. - maxValueHolder[0]) < eps;
    }
    return isOk;
}

From source file:de.tuberlin.uebb.jdae.simulation.PendulumTest.java

@Test
public void testLongSimulationVariableStep() {

    dae.data[1][0] = 0.1;//  w ww.  j ava2 s . c om
    dae.initialize();

    runtime.simulateVariableStep(dae, SIM_TEST_STOP_TIME, Double.MIN_VALUE, Double.MAX_VALUE, 1e-6, 1e-6);

    assertEquals(SIM_TEST_STOP_TIME, dae.data[0][0], 1e-8);
    assertThat(runtime.lastResults().results.size(), is(greaterThan(1)));
}

From source file:com.joptimizer.algebra.Matrix1NornRescaler.java

/**
 * //from w w w  .ja  v  a 2  s.  c  o m
 * @param ASymm symm matrix filled in its subdiagonal elements
 * @param r the index of the row
 * @return
 */
public static double getRowInfinityNorm(final DoubleMatrix2D ASymm, final int r) {

    final double[] maxValueHolder = new double[] { -Double.MAX_VALUE };

    IntIntDoubleFunction myFunct = new IntIntDoubleFunction() {
        @Override
        public double apply(int i, int j, double pij) {
            maxValueHolder[0] = Math.max(maxValueHolder[0], Math.abs(pij));
            return pij;
        }
    };

    //view A row from starting element to diagonal
    DoubleMatrix2D AR = ASymm.viewPart(r, 0, 1, r + 1);
    AR.forEachNonZero(myFunct);
    //view A col from diagonal to final element
    DoubleMatrix2D AC = ASymm.viewPart(r, r, ASymm.rows() - r, 1);
    AC.forEachNonZero(myFunct);

    return maxValueHolder[0];
}

From source file:javalibs.CSVDataNormalizer.java

private Pair getMaxMinFromLinkedColumns(String columnName) {
    List<String> cols = this.columnsWithLinkings.get(columnName);
    // Also need to look at the primary column name
    cols.add(columnName);/*from  www. j a  va  2 s. c o  m*/
    double max = Double.MIN_VALUE;
    double min = Double.MAX_VALUE;

    for (String col : cols) {
        Pair<Double, Double> maxMin = getMaxMinFromCol(col);
        if (maxMin.left() > max)
            max = maxMin.left();
        if (maxMin.right() < min)
            min = maxMin.right();
    }

    return new Pair(max, min);
}