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:org.uma.jmetal.util.point.impl.ArrayPointTest.java

@Test
public void shouldEqualsReturnFalseIfThePointsAreNotIdentical() {
    int dimension = 5;
    Point point = new ArrayPoint(dimension);
    point.setDimensionValue(0, 1.0);/*from w  w w. ja v a2  s  .c  o  m*/
    point.setDimensionValue(1, -2.0);
    point.setDimensionValue(2, 45.5);
    point.setDimensionValue(3, -323.234);
    point.setDimensionValue(4, Double.MAX_VALUE);

    Point newPoint = new ArrayPoint(point);
    newPoint.setDimensionValue(0, -1.0);

    assertFalse(point.equals(newPoint));
}

From source file:com.google.wireless.speed.speedometer.measurements.PingTask.java

private MeasurementResult constructResult(ArrayList<Double> rrtVals, double packetLoss, int packetsSent) {
    double min = Double.MAX_VALUE;
    double max = Double.MIN_VALUE;
    double mdev, avg, filteredAvg;
    double total = 0;
    boolean success = true;

    if (rrtVals.size() == 0) {
        return null;
    }// w  ww.java  2s . com

    for (double rrt : rrtVals) {
        if (rrt < min) {
            min = rrt;
        }
        if (rrt > max) {
            max = rrt;
        }
        total += rrt;
    }

    avg = total / rrtVals.size();
    mdev = Util.getStandardDeviation(rrtVals, avg);
    filteredAvg = filterPingResults(rrtVals, avg);

    PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

    MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
            phoneUtils.getDeviceProperty(), PingTask.TYPE, System.currentTimeMillis() * 1000, success,
            this.measurementDesc);

    result.addResult("target_ip", targetIp);
    result.addResult("mean_rtt_ms", avg);
    result.addResult("min_rtt_ms", min);
    result.addResult("max_rtt_ms", max);
    result.addResult("stddev_rtt_ms", mdev);
    if (filteredAvg != avg) {
        result.addResult("filtered_mean_rtt_ms", filteredAvg);
    }
    result.addResult("packet_loss", packetLoss);
    result.addResult("packets_sent", packetsSent);
    return result;
}

From source file:ransacBatch.BatchRANSAC.java

public ArrayList<Pair<Integer, Double>> writeratestofile() {

    double lifetime = 0;
    String file = inputfile.getName().replaceFirst("[.][^.]+$", "");
    ArrayList<Pair<Integer, Double>> lifecount = new ArrayList<Pair<Integer, Double>>();

    try {/*from w w w.j a v  a 2 s.  c  o  m*/
        File ratesfile = new File(inputdirectory + "//" + file + "Rates" + ".txt");
        File frequfile = new File(inputdirectory + "//" + file + "Averages" + ".txt");

        FileWriter fw = new FileWriter(ratesfile);

        BufferedWriter bw = new BufferedWriter(fw);

        FileWriter fwfrequ = new FileWriter(frequfile);

        BufferedWriter bwfrequ = new BufferedWriter(fwfrequ);

        bw.write("\tStartTime (px)\tEndTime(px)\tLinearRateSlope(px)\n");
        bwfrequ.write(
                "\tAverageGrowthrate(px)\tAverageShrinkrate(px)\tCatastropheFrequency(px)\tRescueFrequency(px)\n");
        ResultsTable rt = new ResultsTable();
        int count = 0;
        int negcount = 0;
        int rescount = 0;
        double timediff = 0;
        double restimediff = 0;
        double negtimediff = 0;
        double averagegrowth = 0;
        double averageshrink = 0;

        double minstartY = leastStart();

        double minstartX = Double.MAX_VALUE;
        double minendX = Double.MAX_VALUE;
        double catfrequ = 0;
        double resfrequ = 0;
        ArrayList<Double> previousendX = new ArrayList<Double>();
        for (final Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>> result : segments) {

            final Pair<Double, Double> minMax = Tracking.fromTo(result.getB());

            double startX = minMax.getA();
            double endX = minMax.getB();

            if (startX < minstartX) {

                minstartX = startX;
                minendX = endX;
            }

            Polynomial<?, Point> polynomial = (Polynomial) result.getA();

            sortPoints(points);
            if (points.get(points.size() - 1).getW()[0] - endX >= tptolerance) {

                double startY = polynomial.predict(startX);
                LinearFunction linear = new LinearFunction();
                boolean lineartrue = LinearFunction.slopeFits(result.getB(), linear, minSlope, maxSlope);

                double linearrate = linear.getCoefficient(1);

                if (linearrate > 0 && startY - minstartY > restolerance && startX > tptolerance
                        && previousendX.size() > 0 && lineartrue) {
                    System.out.println(startY + " " + previousendX.size());
                    rescount++;
                    restimediff += -previousendX.get(previousendX.size() - 1) + startX;

                }

                if (linearrate > 0 && startX > tptolerance && lineartrue) {

                    count++;
                    timediff += endX - startX;
                    lifetime = endX - startX;
                    averagegrowth += linearrate;

                    rt.incrementCounter();
                    rt.addValue("Start time", startX);
                    rt.addValue("End time", endX);
                    rt.addValue("Growth Rate", linearrate);

                    lifecount.add(new ValuePair<Integer, Double>(count, lifetime));
                }

                if (linearrate < 0) {

                    negcount++;
                    negtimediff += endX - startX;

                    averageshrink += linearrate;

                    rt.incrementCounter();
                    rt.addValue("Start time", startX);
                    rt.addValue("End time", endX);
                    rt.addValue("Growth Rate", linearrate);
                }

                bw.write("\t" + nf.format(startX) + "\t" + "\t" + nf.format(endX) + "\t" + "\t"
                        + nf.format(linearrate) + "\t" + "\t" + "\t" + "\t" + "\n");
                if (linearrate > 0 && lineartrue)
                    previousendX.add(endX);

            }

        }

        if (count > 0)
            averagegrowth /= count;
        if (negcount > 0)
            averageshrink /= negcount;

        if (count > 0) {

            catfrequ = count / timediff;

        }

        if (rescount > 0) {

            resfrequ = rescount / restimediff;
        }

        System.out.println(count + " " + rescount);
        rt.show("Rates(pixel units)");

        rtAll.incrementCounter();
        rtAll.addValue("Average Growth", averagegrowth);
        rtAll.addValue("Average Shrink", averageshrink);
        rtAll.addValue("Catastrophe Frequency", catfrequ);
        rtAll.addValue("Rescue Frequency", resfrequ);

        rtAll.show("Average Rates and Frequencies (pixel units)");

        bwfrequ.write("\t" + nf.format(averagegrowth) + "\t" + "\t" + "\t" + "\t" + nf.format(averageshrink)
                + "\t" + "\t" + "\t" + nf.format(catfrequ) + "\t" + "\t" + "\t" + nf.format(resfrequ)

                + "\n" + "\n");

        bw.close();
        fw.close();

        bwfrequ.close();
        fwfrequ.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return lifecount;

}

From source file:com.cloudera.recordbreaker.schemadict.SchemaSuggest.java

/**
 * This method infers new schema labels for each element in the input.  It returns a Schema object that
 * has the identical format as the input file's Schema object, but the labels may be changed.
 *//* w w w  .ja v  a2 s  .c o m*/
public List<DictionaryMapping> inferSchemaMapping(File avroFile, int k) throws IOException {
    SchemaStatisticalSummary srcSummary = new SchemaStatisticalSummary("input");
    Schema srcSchema = srcSummary.createSummaryFromData(avroFile);
    srcSummary.setUseAttributeLabels(useAttributeLabels);

    //
    // Compare the statistics to the database of schema statistics.  Find the closest matches, both
    // on a per-attribute basis and structurally.
    //
    int schemaSize = srcSchema.getFields().size();
    //
    // We start testing the input database against known schemas that have an identical
    // number of attributes, which should allow for the best matches.  This gives us an
    // initial set of distances.  We then expand the search to schemas of greater or fewer
    // attributes, as long as a given bucket of size-k schemas has a min-distance of less
    // than the current top-k matches.
    //
    //
    TreeSet<DictionaryMapping> sorter = new TreeSet<DictionaryMapping>();
    int numMatches = 0;
    List<Integer> seenIndexes = new ArrayList<Integer>();
    int searchRadius = 0;
    boolean seenAllCandidates = false;
    int srcSchemaSize = srcSchema.getFields().size();
    int totalSchemasExamined = 0;

    while (!seenAllCandidates) {
        // Examine the relevant schema buckets, compute all matches to those schemas
        for (int j = Math.max(1, srcSchemaSize - searchRadius); j <= Math.min(NUM_BUCKETS,
                srcSchemaSize + searchRadius); j++) {

            if (seenIndexes.contains(j - 1)) {
                continue;
            }
            for (SchemaDictionaryEntry elt : dictBySize.get(j - 1)) {
                /////////////////////////////
                // This is where we instrument the mapping stuff.
                // If the pair is an interesting one, then emit the mapping that
                // we discover.  Why are good matches going undiscovered?
                /////////////////////////////
                SchemaMapping mapping = srcSummary.getBestMapping(elt.getSummary());
                if (srcSchema.getName().equals(elt.getSchema().getName())) {
                    System.err
                            .println("Comparing " + srcSchema.getName() + " with " + elt.getSchema().getName());
                    System.err.println("Obtained mapping: " + mapping.toString());
                }

                totalSchemasExamined++;
                sorter.add(new DictionaryMapping(mapping, elt));
                numMatches++;
            }
            seenIndexes.add(j - 1);
        }

        // Have we examined the entire corpus of known schemas?
        if ((srcSchemaSize - searchRadius) <= 1 && (srcSchemaSize + searchRadius) >= NUM_BUCKETS) {
            seenAllCandidates = true;
        } else {
            // Test to see if the best matches are good enough that we can stop looking.
            // We compare the lowest known match distance to the minimum distance for matches
            // in the closest non-examined buckets.
            int lowestSize = srcSchemaSize - searchRadius - 1;
            int highestSize = srcSchemaSize + searchRadius + 1;
            double minNearbyDistance = Double.MAX_VALUE;
            if (lowestSize >= 1) {
                minNearbyDistance = Math.min(minNearbyDistance,
                        SchemaStatisticalSummary.getMinimumMappingCost(srcSchemaSize, lowestSize));
            }
            if (highestSize <= NUM_BUCKETS) {
                minNearbyDistance = Math.min(minNearbyDistance,
                        SchemaStatisticalSummary.getMinimumMappingCost(srcSchemaSize, highestSize));
            }
            // Grab from the Sorter the elt that is MIN_ELTS_SUGGESTED into the sorted list
            if (sorter.size() >= k) {
                DictionaryMapping testDictMapping = null;
                int idx = 0;
                for (DictionaryMapping cur : sorter) {
                    idx++;
                    if (idx == k) {
                        testDictMapping = cur;
                        break;
                    }
                }
                if (testDictMapping.getMapping().getDist() < minNearbyDistance) {
                    seenAllCandidates = true;
                }
            }
        }
        searchRadius++;
    }

    // Return the k best schema mappings
    double smallestDistance = sorter.first().getMapping().getDist();
    List<DictionaryMapping> dsts = new ArrayList<DictionaryMapping>();
    for (DictionaryMapping dp : sorter) {
        if (dsts.size() > k && dp.getMapping().getDist() > smallestDistance) {
            break;
        }
        dsts.add(dp);
    }
    double pct = totalSchemasExamined / (1.0 * dict.contents().size());
    System.err.println("Final search radius of " + searchRadius + " yielded a search over " + pct
            + " of all known databases.");
    return dsts;
}

From source file:edu.stanford.cfuller.imageanalysistools.util.VoronoiDiagram.java

protected Integer findClosestRegion(Vector2D lookup) {

    Vector2D best = null;/*from   w ww  .j a v a 2  s  .  c o m*/

    double bestDist = Double.MAX_VALUE;

    for (Vector2D seedPoint : this.regionLookup.keySet()) {

        if (seedPoint.distance(lookup) < bestDist) {
            bestDist = seedPoint.distance(lookup);
            best = seedPoint;
        }

    }

    return this.regionLookup.get(best);

}

From source file:com.flowpowered.api.geo.discrete.Point.java

/**
 * Gets the largest distance between two points, when projected onto one of the axes.
 *
 * This will return Double.MAX_VALUE if the other Point is null, either world is null, or the two points are in different worlds.
 *
 * Otherwise, it returns the max distance.
 *//*from  www  . j a va  2s.co m*/
public double getMaxDistance(Point other) {
    if (other == null || world == null || other.world == null || !world.equals(other.world)) {
        return Double.MAX_VALUE;
    }
    return Math.max(Math.abs(getX() - other.getX()),
            Math.max(Math.abs(getY() - other.getY()), Math.abs(getZ() - other.getZ())));
}

From source file:acromusashi.stream.ml.clustering.kmeans.KmeansCalculator.java

/**
 * ????????????//from   w ww  .ja v a 2  s.c  om
 * 
 * @param targetPoint ?
 * @param centroids 
 * @return Kmeans?
 */
public static KmeansResult nearestCentroid(KmeansPoint targetPoint, List<KmeansPoint> centroids) {
    int nearestCentroidIndex = 0;
    Double minDistance = Double.MAX_VALUE;
    KmeansPoint currentCentroid = null;
    Double currentDistance;
    for (int index = 0; index < centroids.size(); index++) {
        currentCentroid = centroids.get(index);
        if (currentCentroid != null && currentCentroid.getDataPoint() != null) {
            currentDistance = MathUtils.distance(targetPoint.getDataPoint(), currentCentroid.getDataPoint());
            if (currentDistance < minDistance) {
                minDistance = currentDistance;
                nearestCentroidIndex = index;
            }
        }
    }

    currentCentroid = centroids.get(nearestCentroidIndex);

    KmeansResult result = new KmeansResult();
    result.setDataPoint(targetPoint.getDataPoint());
    result.setCentroidIndex(nearestCentroidIndex);
    result.setCentroid(currentCentroid.getDataPoint());
    result.setDistance(minDistance);

    return result;
}

From source file:gr.iti.mklab.reveal.forensics.maps.dq.DQExtractor.java

public void detectDQDiscontinuities() {

    int imWidth = dcts.length;
    int imHeight = dcts[0].length;

    int[] p_h_avg = new int[maxCoeffs];
    int[] p_h_fft = new int[maxCoeffs];
    int[] p_final = new int[maxCoeffs];

    double[][] pTampered = new double[maxCoeffs][];
    double[][] pUntampered = new double[maxCoeffs][];

    for (int coeffIndex = 0; coeffIndex < maxCoeffs; coeffIndex++) {

        int coe = coeff[coeffIndex];
        int startY = coe % 8 - 1;
        if (startY == -1) {
            startY = 8;/*from   w ww  . java2s .c o m*/
        }
        int startX = (int) Math.floor((coe - 1) / 8);

        List<Integer> selectedCoeffs = new ArrayList<Integer>();
        for (int ii = startX; ii < imWidth; ii += 8) {
            for (int jj = startY; jj < imHeight; jj += 8) {
                selectedCoeffs.add(dcts[ii][jj]);
            }
        }

        int minCoeffValue = Collections.min(selectedCoeffs);
        int maxCoeffValue = Collections.max(selectedCoeffs);
        int s_0;
        Double[] coeffHist = new Double[0];
        if (maxCoeffValue - minCoeffValue > 0) {
            //will be a power of 2 to allow for fft (zero padded)
            int trueHistRange = maxCoeffValue - minCoeffValue + 1;
            //int histLength = trueHistRange;
            int histLength = (int) Math.pow(2, Math.ceil(Math.log(trueHistRange) / Math.log(2)));

            coeffHist = new Double[histLength];

            for (int ii = 0; ii < coeffHist.length; ii++) {
                coeffHist[ii] = 0.0;
            }

            for (Integer selectedCoeff : selectedCoeffs) {
                coeffHist[selectedCoeff - minCoeffValue] += 1;
            }

            List<Double> coeffHistList = Arrays.asList(coeffHist);
            s_0 = coeffHistList.indexOf(Collections.max(coeffHistList));

            List<Double> h = new ArrayList<>();
            DescriptiveStatistics vals;
            for (int coeffInd = 1; coeffInd < coeffHistList.size(); coeffInd++) {
                vals = new DescriptiveStatistics();
                for (int leapInd = s_0; leapInd < coeffHistList.size(); leapInd += coeffInd) {
                    vals.addValue(coeffHistList.get(leapInd));
                }
                for (int leapInd = s_0 - coeffInd; leapInd >= 0; leapInd -= coeffInd) {
                    vals.addValue(coeffHistList.get(leapInd));
                }
                h.add(vals.getMean());
            }
            p_h_avg[coeffIndex] = (h.indexOf(Collections.max(h)));

            FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(
                    DftNormalization.STANDARD);
            Complex[] fft = fastFourierTransformer.transform(ArrayUtils.toPrimitive(coeffHist),
                    TransformType.FORWARD);

            double[] power = new double[fft.length];
            for (int ii = 0; ii < power.length; ii++) {
                power[ii] = fft[ii].abs();
            }

            //Find first local minimum, to bypass DC peak
            double DC = power[0];
            int FreqValley = 1;
            while (FreqValley < power.length - 1 & power[FreqValley] >= power[FreqValley + 1]) {
                FreqValley++;
            }

            int maxFFTInd = 0;
            double maxFFTVal = 0;
            double minFFTVal = Double.MAX_VALUE;
            for (int ii = FreqValley; ii < power.length / 2; ii++) {
                if (power[ii] > maxFFTVal) {
                    maxFFTInd = ii;
                    maxFFTVal = power[ii];
                }
                if (power[ii] < minFFTVal) {
                    minFFTVal = power[ii];
                }
            }
            if (maxFFTInd == 0 | maxFFTVal < (DC / 5) | minFFTVal / maxFFTVal > 0.9) {
                p_h_fft[coeffIndex] = 1;
            } else {
                p_h_fft[coeffIndex] = Math.round(coeffHist.length / maxFFTInd);
            }

        } else {
            p_h_avg[coeffIndex] = 1;
            p_h_fft[coeffIndex] = 1;
            s_0 = 0;
        }
        if (p_h_avg[coeffIndex] < p_h_fft[coeffIndex]) {
            p_final[coeffIndex] = p_h_avg[coeffIndex];
        } else {
            p_final[coeffIndex] = p_h_fft[coeffIndex];
        }

        pTampered[coeffIndex] = new double[selectedCoeffs.size()];
        pUntampered[coeffIndex] = new double[selectedCoeffs.size()];
        int[] adjustedCoeffs = new int[selectedCoeffs.size()];
        int[] period_start = new int[selectedCoeffs.size()];
        int[] period;
        int[] num = new int[selectedCoeffs.size()];
        int[] denom = new int[selectedCoeffs.size()];
        double[] P_u = new double[selectedCoeffs.size()];
        double[] P_t = new double[selectedCoeffs.size()];

        if (p_final[coeffIndex] != 1) {
            for (int ii = 0; ii < adjustedCoeffs.length; ii++) {
                adjustedCoeffs[ii] = selectedCoeffs.get(ii) - minCoeffValue;
                period_start[ii] = adjustedCoeffs[ii] - rem(adjustedCoeffs[ii] - s_0, p_final[coeffIndex]);
            }
            for (int kk = 0; kk < selectedCoeffs.size(); kk++) {
                if (period_start[kk] > s_0) {
                    period = new int[p_final[coeffIndex]];
                    for (int ii = 0; ii < p_final[coeffIndex]; ii++) {
                        period[ii] = period_start[kk] + ii;
                        if (period[ii] >= coeffHist.length) {
                            period[ii] = period[ii] - p_final[coeffIndex];
                        }
                    }
                    num[kk] = (int) coeffHist[adjustedCoeffs[kk]].doubleValue();
                    denom[kk] = 0;
                    for (int ll = 0; ll < period.length; ll++) {
                        denom[kk] = denom[kk] + (int) coeffHist[period[ll]].doubleValue();
                    }
                } else {
                    period = new int[p_final[coeffIndex]];
                    for (int ii = 0; ii < p_final[coeffIndex]; ii++) {
                        period[ii] = period_start[kk] - ii;
                        if (period_start[kk] - p_final[coeffIndex] + 1 <= 0) {
                            if (period[ii] <= 0) {
                                period[ii] = period[ii] + p_final[coeffIndex];
                            }
                        }
                    }
                    num[kk] = (int) coeffHist[adjustedCoeffs[kk]].doubleValue();
                    denom[kk] = 0;
                    for (int ll = 0; ll < period.length; ll++) {
                        denom[kk] = denom[kk] + (int) coeffHist[period[ll]].doubleValue();
                    }
                }

                P_u[kk] = ((double) num[kk] / denom[kk]);
                P_t[kk] = (1.0 / p_final[coeffIndex]);
                if (P_u[kk] + P_t[kk] != 0) {
                    pTampered[coeffIndex][kk] = P_t[kk] / (P_u[kk] + P_t[kk]);
                    pUntampered[coeffIndex][kk] = P_u[kk] / (P_u[kk] + P_t[kk]);

                } else {
                    pTampered[coeffIndex][kk] = 0.5;
                    pUntampered[coeffIndex][kk] = 0.5;
                }
            }

        } else {
            for (int kk = 0; kk < selectedCoeffs.size(); kk++) {
                pTampered[coeffIndex][kk] = 0.5;
                pUntampered[coeffIndex][kk] = 0.5;
            }
        }

    }
    double[] pTamperedOverall = new double[pTampered[0].length];
    double pTamperedProd;
    double pUntamperedProd;

    for (int locationIndex = 0; locationIndex < pTampered[0].length; locationIndex++) {
        pTamperedProd = 1;
        pUntamperedProd = 1;
        for (int coeffIndex = 0; coeffIndex < pTampered.length; coeffIndex++) {
            pTamperedProd = pTamperedProd * pTampered[coeffIndex][locationIndex];
            pUntamperedProd = pUntamperedProd * pUntampered[coeffIndex][locationIndex];
        }
        if (pTamperedProd + pUntamperedProd != 0) {
            pTamperedOverall[locationIndex] = pTamperedProd / (pTamperedProd + pUntamperedProd);
        } else {
            pTamperedOverall[locationIndex] = 0;
        }
    }

    int blocksH = imWidth / 8;
    int blocksV = imHeight / 8;
    double[][] outputMap = new double[blocksV][blocksH];
    for (int kk = 0; kk < pTamperedOverall.length; kk++) {
        outputMap[kk % blocksV][(int) Math.floor(kk / blocksV)] = pTamperedOverall[kk];
        if (pTamperedOverall[kk] > maxProbValue) {
            maxProbValue = pTamperedOverall[kk];
        }
        if (pTamperedOverall[kk] < minProbValue) {
            minProbValue = pTamperedOverall[kk];
        }
    }
    probabilityMap = outputMap;
    BufferedImage outputIm = visualizeWithJet(outputMap);
    // output
    displaySurface = outputIm;
}

From source file:de.biomedical_imaging.traj.math.TrajectorySplineFit.java

/**
 * Calculates a spline to a trajectory. Attention: The spline is fitted through a rotated version of the trajectory.
 * To fit the spline the trajectory is rotated into its main direction. You can access this rotated trajectory by 
 * {@link #getRotatedTrajectory() getRotatedTrajectory}.
 * @return The fitted spline/*from   w  w w . j  a v  a2s. co  m*/
 */
public PolynomialSplineFunction calculateSpline() {

    successfull = false;
    /*
     * 1.Calculate the minimum bounding rectangle
     */
    ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>();
    for (int i = 0; i < t.size(); i++) {
        Point2D.Double p = new Point2D.Double();
        p.setLocation(t.get(i).x, t.get(i).y);
        points.add(p);
    }

    /*
     * 1.1 Rotate that the major axis is parallel with the xaxis
     */

    Array2DRowRealMatrix gyr = RadiusGyrationTensor2D.getRadiusOfGyrationTensor(t);
    EigenDecomposition eigdec = new EigenDecomposition(gyr);

    double inRad = -1 * Math.atan2(eigdec.getEigenvector(0).getEntry(1), eigdec.getEigenvector(0).getEntry(0));
    boolean doTransform = (Math.abs(Math.abs(inRad) - Math.PI) > 0.001);

    if (doTransform) {
        angleRotated = inRad;
        for (int i = 0; i < t.size(); i++) {
            double x = t.get(i).x;
            double y = t.get(i).y;
            double newX = x * Math.cos(inRad) - y * Math.sin(inRad);
            double newY = x * Math.sin(inRad) + y * Math.cos(inRad);
            rotatedTrajectory.add(newX, newY, 0);
            points.get(i).setLocation(newX, newY);
        }
        //for(int i = 0; i < rect.length; i++){
        //   rect[i].setLocation(rect[i].x*Math.cos(inRad)-rect[i].y*Math.sin(inRad), rect[i].x*Math.sin(inRad)+rect[i].y*Math.cos(inRad));
        //}
    } else {
        angleRotated = 0;
        rotatedTrajectory = t;
    }

    /*
     * 2. Divide the rectangle in n equal segments
     * 2.1 Calculate line in main direction
     * 2.2 Project the points in onto this line
     * 2.3 Calculate the distance between the start of the line and the projected point
     * 2.4 Assign point to segment according to distance of (2.3)
     */
    List<List<Point2D.Double>> pointsInSegments = null;
    boolean allSegmentsContainingAtLeastTwoPoints = true;
    int indexSmallestX = 0;

    double segmentWidth = 0;
    do {
        double smallestX = Double.MAX_VALUE;
        double largestX = Double.MIN_VALUE;

        for (int i = 0; i < points.size(); i++) {
            if (points.get(i).x < smallestX) {
                smallestX = points.get(i).x;
                indexSmallestX = i;
            }
            if (points.get(i).x > largestX) {
                largestX = points.get(i).x;
            }
        }

        allSegmentsContainingAtLeastTwoPoints = true;
        segmentWidth = (largestX - smallestX) / nSegments;
        pointsInSegments = new ArrayList<List<Point2D.Double>>(nSegments);
        for (int i = 0; i < nSegments; i++) {
            pointsInSegments.add(new ArrayList<Point2D.Double>());
        }
        for (int i = 0; i < points.size(); i++) {

            int index = (int) Math.abs((points.get(i).x / segmentWidth));

            if (index > (nSegments - 1)) {
                index = (nSegments - 1);
            }
            pointsInSegments.get(index).add(points.get(i));
        }

        for (int i = 0; i < pointsInSegments.size(); i++) {
            if (pointsInSegments.get(i).size() < 2) {
                if (nSegments > 2) {
                    nSegments--;
                    i = pointsInSegments.size();
                    allSegmentsContainingAtLeastTwoPoints = false;

                }
            }
        }

    } while (allSegmentsContainingAtLeastTwoPoints == false);

    /*
     * 3. Calculate the mean standard deviation over each segment: <s>
     */
    //Point2D.Double eMajorP1 = new Point2D.Double(p1.x - (p3.x-p1.x)/2.0,p1.y - (p3.y-p1.y)/2.0); 
    //   Point2D.Double eMajorP2 = new Point2D.Double(p2.x - (p3.x-p1.x)/2.0,p2.y - (p3.y-p1.y)/2.0); 
    double sumSDOrthogonal = 0;
    int Nsum = 0;
    CenterOfGravityFeature cogf = new CenterOfGravityFeature(rotatedTrajectory);
    Point2D.Double cog = new Point2D.Double(cogf.evaluate()[0], cogf.evaluate()[1]);
    Point2D.Double eMajorP1 = cog;
    Point2D.Double eMajorP2 = new Point2D.Double(cog.getX() + 1, cog.getY());
    for (int i = 0; i < nSegments; i++) {
        StandardDeviation sd = new StandardDeviation();
        double[] distances = new double[pointsInSegments.get(i).size()];
        for (int j = 0; j < pointsInSegments.get(i).size(); j++) {
            int factor = 1;
            if (isLeft(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j))) {
                factor = -1;
            }
            distances[j] = factor * distancePointLine(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j));
        }
        if (distances.length > 0) {
            sd.setData(distances);

            sumSDOrthogonal += sd.evaluate();
            Nsum++;
        }
    }
    double s = sumSDOrthogonal / Nsum;
    if (segmentWidth < Math.pow(10, -15)) {
        return null;
    }
    if (s < Math.pow(10, -15)) {
        //If standard deviation is zero, replace it with the half of the segment width

        s = segmentWidth / 2;
    }
    //rotatedTrajectory.showTrajectory("rot");
    /*
     * 4. Build a kd-tree
     */
    KDTree<Point2D.Double> kdtree = new KDTree<Point2D.Double>(2);

    for (int i = 0; i < points.size(); i++) {
        try {
            //To ensure that all points have a different key, add small random number

            kdtree.insert(new double[] { points.get(i).x, points.get(i).y }, points.get(i));
        } catch (KeySizeException e) {
            e.printStackTrace();
        } catch (KeyDuplicateException e) {
            //Do nothing! It is not important
        }

    }

    /*
     * 5. Using the first point f in trajectory and calculate the center of mass
     * of all points around f (radius: 3*<s>))
     */
    List<Point2D.Double> near = null;

    Point2D.Double first = points.get(indexSmallestX);//minDistancePointToLine(p1, p3, points);
    double r1 = 3 * s;
    try {

        near = kdtree.nearestEuclidean(new double[] { first.x, first.y }, r1);

    } catch (KeySizeException e) {
        e.printStackTrace();
    }

    double cx = 0;
    double cy = 0;
    for (int i = 0; i < near.size(); i++) {
        cx += near.get(i).x;
        cy += near.get(i).y;
    }
    cx /= near.size();
    cy /= near.size();

    splineSupportPoints = new ArrayList<Point2D.Double>();
    splineSupportPoints.add(new Point2D.Double(cx, cy));

    /* 
     * 6. The second point is determined by finding the center-of-mass of particles in the p/2 radian 
     * section of an annulus, r1 < r < 2r1, that is directed toward the angle with the highest number 
     * of particles within p/2 radians.
     * 7. This second point is then used as the center of the annulus for choosing the third point, and the process is repeated (6. & 7.).
     */

    /*
     * 6.1 Find all points in the annolous
     */

    /*
     * 6.2 Write each point in a coordinate system centered at the center of the sphere, calculate direction and
     * check if it in the allowed bounds
     */
    int nCircleSegments = 100;
    double deltaRad = 2 * Math.PI / nCircleSegments;
    boolean stop = false;
    int minN = 7;
    double tempr1 = r1;
    double allowedDeltaDirection = 0.5 * Math.PI;

    while (stop == false) {
        List<Point2D.Double> nearestr1 = null;
        List<Point2D.Double> nearest2xr1 = null;
        try {
            nearestr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, tempr1);
            nearest2xr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, 2 * tempr1);
        } catch (KeySizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        nearest2xr1.removeAll(nearestr1);

        double lThreshRad = 0;
        double hThreshRad = Math.PI / 2;
        double stopThresh = 2 * Math.PI;
        if (splineSupportPoints.size() > 1) {
            double directionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            lThreshRad = directionInRad - allowedDeltaDirection / 2 - Math.PI / 4;
            if (lThreshRad < 0) {
                lThreshRad = 2 * Math.PI + lThreshRad;
            }
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            hThreshRad = directionInRad + allowedDeltaDirection / 2 + Math.PI / 4;
            if (hThreshRad < 0) {
                hThreshRad = 2 * Math.PI + hThreshRad;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            stopThresh = directionInRad + allowedDeltaDirection / 2 - Math.PI / 4;
            if (stopThresh > 2 * Math.PI) {
                stopThresh = stopThresh - 2 * Math.PI;
            }

        }

        double newCx = 0;
        double newCy = 0;
        int newCN = 0;
        int candN = 0;

        //Find center with highest density of points
        double lastDist = 0;
        double newDist = 0;
        do {
            lastDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

            candN = 0;
            double candCx = 0;
            double candCy = 0;

            for (int i = 0; i < nearest2xr1.size(); i++) {
                Point2D.Double centerOfCircle = splineSupportPoints.get(splineSupportPoints.size() - 1);
                Vector2d relativeToCircle = new Vector2d(nearest2xr1.get(i).x - centerOfCircle.x,
                        nearest2xr1.get(i).y - centerOfCircle.y);
                relativeToCircle.normalize();
                double angleInRadians = Math.atan2(relativeToCircle.y, relativeToCircle.x) + Math.PI;

                if (lThreshRad < hThreshRad) {
                    if (angleInRadians > lThreshRad && angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                } else {
                    if (angleInRadians > lThreshRad || angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                }

            }

            if (candN > 0 && candN > newCN) {
                candCx /= candN;
                candCy /= candN;
                newCx = candCx;
                newCy = candCy;
                newCN = candN;
            }
            lThreshRad += deltaRad;
            hThreshRad += deltaRad;
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            newDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

        } while ((newDist - lastDist) > 0);

        //Check if the new center is valid
        if (splineSupportPoints.size() > 1) {
            double currentDirectionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            double candDirectionInRad = Math.atan2(
                    newCy - splineSupportPoints.get(splineSupportPoints.size() - 1).y,
                    newCx - splineSupportPoints.get(splineSupportPoints.size() - 1).x) + Math.PI;
            double dDir = Math.max(currentDirectionInRad, candDirectionInRad)
                    - Math.min(currentDirectionInRad, candDirectionInRad);
            if (dDir > 2 * Math.PI) {
                dDir = 2 * Math.PI - dDir;
            }
            if (dDir > allowedDeltaDirection) {

                stop = true;
            }
        }
        boolean enoughPoints = (newCN < minN);
        boolean isNormalRadius = Math.abs(tempr1 - r1) < Math.pow(10, -18);
        boolean isExtendedRadius = Math.abs(tempr1 - 3 * r1) < Math.pow(10, -18);

        if (enoughPoints && isNormalRadius) {
            //Not enough points, extend search radius
            tempr1 = 3 * r1;
        } else if (enoughPoints && isExtendedRadius) {
            //Despite radius extension: Not enough points!
            stop = true;
        } else if (stop == false) {
            splineSupportPoints.add(new Point2D.Double(newCx, newCy));
            tempr1 = r1;
        }

    }

    //Sort
    Collections.sort(splineSupportPoints, new Comparator<Point2D.Double>() {

        public int compare(Point2D.Double o1, Point2D.Double o2) {
            if (o1.x < o2.x) {
                return -1;
            }
            if (o1.x > o2.x) {
                return 1;
            }
            return 0;
        }
    });

    //Add endpoints
    if (splineSupportPoints.size() > 1) {
        Vector2d start = new Vector2d(splineSupportPoints.get(0).x - splineSupportPoints.get(1).x,
                splineSupportPoints.get(0).y - splineSupportPoints.get(1).y);
        start.normalize();
        start.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + start.x,
                splineSupportPoints.get(0).y + start.y));

        Vector2d end = new Vector2d(
                splineSupportPoints.get(splineSupportPoints.size() - 1).x
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).x,
                splineSupportPoints.get(splineSupportPoints.size() - 1).y
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).y);
        end.normalize();
        end.scale(r1 * 6);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + end.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + end.y));
    } else {
        Vector2d majordir = new Vector2d(-1, 0);
        majordir.normalize();
        majordir.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + majordir.x,
                splineSupportPoints.get(0).y + majordir.y));
        majordir.scale(-1);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + majordir.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + majordir.y));

    }

    //Interpolate spline
    double[] supX = new double[splineSupportPoints.size()];
    double[] supY = new double[splineSupportPoints.size()];
    for (int i = 0; i < splineSupportPoints.size(); i++) {
        supX[i] = splineSupportPoints.get(i).x;
        supY[i] = splineSupportPoints.get(i).y;
    }

    SplineInterpolator sIinter = new SplineInterpolator();
    spline = sIinter.interpolate(supX, supY);
    successfull = true;
    return spline;
}

From source file:com.graphhopper.jsprit.core.algorithm.ruin.DBSCANClusterer.java

private double sample(VehicleRoutingTransportCosts costs, VehicleRoute r) {
    double min = Double.MAX_VALUE;
    double sum = 0;
    for (int i = 0; i < noDistanceSamples; i++) {
        TourActivity act1 = RandomUtils.nextItem(r.getActivities(), random);
        TourActivity act2 = RandomUtils.nextItem(r.getActivities(), random);
        double dist = costs.getTransportCost(act1.getLocation(), act2.getLocation(), 0., null, r.getVehicle());
        if (dist < min)
            min = dist;//from   w  w w .  j  a  v a  2s .  c  o  m
        sum += dist;
    }
    double avg = sum / ((double) noDistanceSamples);
    return (avg - min) * epsFactor;
}