Example usage for java.lang Double POSITIVE_INFINITY

List of usage examples for java.lang Double POSITIVE_INFINITY

Introduction

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

Prototype

double POSITIVE_INFINITY

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

Click Source Link

Document

A constant holding the positive infinity of type double .

Usage

From source file:gedi.util.math.stat.distributions.GeneralizedExtremeValueDistribution.java

@Override
public double getNumericalMean() {
    if (shape == 0)
        return location + scale * EULER;
    if (shape >= 1)
        return Double.POSITIVE_INFINITY;
    return location + scale * (Gamma.gamma(1 - shape) - 1) / shape;
}

From source file:de.saring.util.gui.jfreechart.StackedRenderer.java

/**
 * Returns the range of values the renderer requires to display all the
 * items from the specified dataset./*from  w ww.  j  a  v  a2s .  c  o  m*/
 *
 * @param dataset the dataset (<code>null</code> permitted).
 * @return The range (or <code>null</code> if the dataset is
 *         <code>null</code> or empty).
 */
@Override
public Range findRangeBounds(XYDataset dataset) {
    if (dataset == null) {
        return null;
    }
    double min = Double.POSITIVE_INFINITY;
    double max = Double.NEGATIVE_INFINITY;
    TableXYDataset d = (TableXYDataset) dataset;
    int itemCount = d.getItemCount();
    for (int i = 0; i < itemCount; i++) {
        double[] stackValues = getStackValues((TableXYDataset) dataset, d.getSeriesCount(), i);
        min = Math.min(min, stackValues[0]);
        max = Math.max(max, stackValues[1]);
    }
    if (min == Double.POSITIVE_INFINITY) {
        return null;
    }
    return new Range(min, max);
}

From source file:com.opengamma.analytics.financial.model.finitedifference.OperatorSplittingFiniteDifference2D.java

@Override
public double[][] solve(final ConvectionDiffusion2DPDEDataBundle pdeData, final int tSteps, final int xSteps,
        final int ySteps, final double tMax, final BoundaryCondition2D xLowerBoundary,
        final BoundaryCondition2D xUpperBoundary, final BoundaryCondition2D yLowerBoundary,
        final BoundaryCondition2D yUpperBoundary, final Cube<Double, Double, Double, Double> freeBoundary) {

    final double dt = tMax / (tSteps);
    final double dx = (xUpperBoundary.getLevel() - xLowerBoundary.getLevel()) / (xSteps);
    final double dy = (yUpperBoundary.getLevel() - yLowerBoundary.getLevel()) / (ySteps);
    final double dtdx2 = dt / dx / dx;
    final double dtdx = dt / dx;
    final double dtdy2 = dt / dy / dy;
    final double dtdy = dt / dy;
    final double dtdxdy = dt / dx / dy;

    final double[][] v = new double[xSteps + 1][ySteps + 1];
    final double[][] vt = new double[xSteps + 1][ySteps + 1];

    final double[] x = new double[xSteps + 1];
    final double[] y = new double[ySteps + 1];

    final double[] q = new double[xSteps + 1];
    final double[] r = new double[ySteps + 1];
    final double[][] mx = new double[xSteps + 1][xSteps + 1];
    final double[][] my = new double[ySteps + 1][ySteps + 1];

    double currentX = 0;
    double currentY = 0;

    for (int j = 0; j <= ySteps; j++) {
        currentY = yLowerBoundary.getLevel() + j * dy;
        y[j] = currentY;/*from w ww. ja  v a2s . c o  m*/
    }
    for (int i = 0; i <= xSteps; i++) {
        currentX = xLowerBoundary.getLevel() + i * dx;
        x[i] = currentX;
        for (int j = 0; j <= ySteps; j++) {
            v[i][j] = pdeData.getInitialValue(x[i], y[j]);
        }
    }

    double t;
    double a, b, c, d, e, f;

    for (int n = 0; n < tSteps; n++) {

        t = n * dt;
        // stag 1 Explicit in the cross
        for (int i = 1; i < xSteps; i++) {
            for (int j = 1; j < ySteps; j++) {
                e = pdeData.getE(t, x[i], y[j]);
                vt[i][j] = v[i][j];
                vt[i][j] -= 0.125 * dtdxdy * e
                        * (v[i + 1][j + 1] + v[i - 1][j - 1] - v[i + 1][j - 1] - v[i - 1][j + 1]);
            }
            // the explicit intermediate stag vt is missed the boundary
            vt[i][0] = v[i][0];
            vt[i][ySteps] = v[i][ySteps];
        }

        // stag 2 - Implicit in x
        t += 0.5 * dt;
        for (int j = 0; j <= ySteps; j++) {
            for (int i = 1; i < xSteps; i++) {
                a = pdeData.getA(t, x[i], y[j]);
                b = pdeData.getB(t, x[i], y[j]);
                c = pdeData.getC(t, x[i], y[j]);

                mx[i][i - 1] = (dtdx2 * a - 0.5 * dtdx * b);
                mx[i][i] = 1 + (-2 * dtdx2 * a + dt * c);
                mx[i][i + 1] = (dtdx2 * a + 0.5 * dtdx * b);

                q[i] = vt[i][j];
            }

            // it is not clear that these boundary conditions apply in the intermediate stage of operator splitting
            double[] temp = xLowerBoundary.getLeftMatrixCondition(t, y[j]);
            for (int k = 0; k < temp.length; k++) {
                mx[0][k] = temp[k];
            }
            temp = xUpperBoundary.getLeftMatrixCondition(t, y[j]);
            for (int k = 0; k < temp.length; k++) {
                mx[xSteps][xSteps - k] = temp[k];
            }

            temp = xLowerBoundary.getRightMatrixCondition(t, y[j]);
            double sum = 0;
            for (int k = 0; k < temp.length; k++) {
                sum += temp[k] * v[k][j];
            }
            q[0] = sum + xLowerBoundary.getConstant(t, y[j], dx);

            temp = xUpperBoundary.getRightMatrixCondition(t, y[j]);
            sum = 0;
            for (int k = 0; k < temp.length; k++) {
                sum += temp[k] * v[xSteps - k][j];
            }
            q[xSteps] = sum + xUpperBoundary.getConstant(t, y[j], dx);

            // SOR
            final double omega = 1.5;
            double scale = 1.0;
            double errorSqr = Double.POSITIVE_INFINITY;
            int min, max;
            int count = 0;
            while (errorSqr / (scale + 1e-10) > 1e-18 && count < SOR_MAX) {
                errorSqr = 0.0;
                scale = 0.0;
                for (int l = 0; l <= xSteps; l++) {
                    min = (l == xSteps ? 0 : Math.max(0, l - 1));
                    max = (l == 0 ? xSteps : Math.min(xSteps, l + 1));
                    sum = 0;
                    // for (int k = 0; k <= xSteps; k++) {
                    for (int k = min; k <= max; k++) { // mx is tri-diagonal so only need 3 steps here
                        sum += mx[l][k] * vt[k][j];
                    }
                    final double correction = omega / mx[l][l] * (q[l] - sum);
                    // if (freeBoundary != null) {
                    // correction = Math.max(correction, freeBoundary.getZValue(t, x[j]) - f[j]);
                    // }
                    errorSqr += correction * correction;
                    vt[l][j] += correction;
                    scale += vt[l][j] * vt[l][j];
                }
                count++;
            }
            Validate.isTrue(count < SOR_MAX, "SOR exceeded max interations");
        }

        for (int j = 1; j < ySteps; j++) {
            for (int i = 1; i < xSteps; i++) {
                e = pdeData.getE(t, x[i], y[j]);
                v[i][j] = vt[i][j];
                v[i][j] -= 0.125 * dtdxdy * e
                        * (vt[i + 1][j + 1] + vt[i - 1][j - 1] - vt[i + 1][j - 1] - vt[i - 1][j + 1]);
            }
            // again now v on the boundary is undefined
            v[0][j] = vt[0][j];
            v[xSteps][j] = vt[xSteps][j];
        }

        // stag 4 - implicit in y
        t = (n + 1) * dt;
        for (int i = 0; i <= xSteps; i++) {
            for (int j = 1; j < ySteps; j++) {

                d = pdeData.getD(t, x[i], y[j]);
                f = pdeData.getF(t, x[i], y[j]);

                my[j][j - 1] = (dtdy2 * d - 0.5 * dtdy * f);
                my[j][j] = 1 + (-2 * dtdy2 * d);
                my[j][j + 1] = (dtdy2 * d + 0.5 * dtdy * f);

                r[j] = v[i][j];
            }

            double[] temp = yLowerBoundary.getLeftMatrixCondition(t, x[i]);
            for (int k = 0; k < temp.length; k++) {
                my[0][k] = temp[k];
            }
            temp = yUpperBoundary.getLeftMatrixCondition(t, x[i]);
            for (int k = 0; k < temp.length; k++) {
                my[ySteps][ySteps - k] = temp[k];
            }

            temp = yLowerBoundary.getRightMatrixCondition(t, x[i]);
            double sum = 0;
            for (int k = 0; k < temp.length; k++) {
                sum += temp[k] * vt[i][k];
            }
            r[0] = sum + yLowerBoundary.getConstant(t, x[i], dy);

            temp = yUpperBoundary.getRightMatrixCondition(t, x[i]);
            sum = 0;
            for (int k = 0; k < temp.length; k++) {
                sum += temp[k] * vt[i][ySteps - k];
            }
            r[ySteps] = sum + yUpperBoundary.getConstant(t, x[i], dy);

            // SOR
            final double omega = 1.5;
            double scale = 1.0;
            double errorSqr = Double.POSITIVE_INFINITY;
            int count = 0;
            while (errorSqr / (scale + 1e-10) > 1e-18 && count < SOR_MAX) {
                errorSqr = 0.0;
                scale = 0.0;
                int min, max;
                for (int l = 0; l <= ySteps; l++) {
                    min = (l == ySteps ? 0 : Math.max(0, l - 1));
                    max = (l == 0 ? ySteps : Math.min(ySteps, l + 1));
                    sum = 0;
                    // for (int k = 0; k <= ySteps; k++) {
                    for (int k = min; k <= max; k++) {
                        sum += my[l][k] * v[i][k];
                    }
                    final double correction = omega / my[l][l] * (r[l] - sum);
                    // if (freeBoundary != null) {
                    // correction = Math.max(correction, freeBoundary.getZValue(t, x[j]) - f[j]);
                    // }
                    errorSqr += correction * correction;
                    v[i][l] += correction;
                    scale += v[i][l] * v[i][l];
                }
                count++;
            }
            Validate.isTrue(count < SOR_MAX, "SOR exceeded max interations");
        }

    } // time loop
    return v;

}

From source file:de._13ducks.cor.game.server.movement.SubSectorPathfinder.java

/**
 * Sucht einen Weg auf Freiflchen (FreePolygon) um ein Hindernis herum.
 * Beachtet weitere Hindernisse auf der "Umleitung".
 * Sucht die Route nur bis zum nchsten Ziel.
 * Der Mover darf sich nicht bereits auf einer Umleitung befinden,
 * diese muss ggf vorher gelscht worden sein.
 * @param mover//from ww  w . j  av  a 2 s  .c  o m
 * @param obstacle
 * @return 
 */
static List<SubSectorEdge> searchDiversion(Moveable mover, Moveable obstacle, SimplePosition target) {
    // Vorberprfung: Ist das Ziel berhaupt noch frei?
    List<Moveable> moversAroundTarget = Server.getInnerServer().moveMan.moveMap
            .moversAroundPoint(target.toFPP(), mover.getRadius() + 5);
    moversAroundTarget.remove(mover); // Falls drin
    for (Moveable m : moversAroundTarget) {
        if (m.getPrecisePosition().getDistance(target.toFPP()) < m.getRadius() + mover.getRadius()
                + ServerBehaviourMove.MIN_DISTANCE) {
            System.out.println("No div, target blocked!");
            return null;
        }
    }

    /**
     * Wegsuche in 2 Schritten:
     * 1. Aufbauen eines geeigneten Graphen, der das gesamte Problem enthlt.
     * 2. Suchen einer Route in diesem Graphen mittels A* (A-Star).
     */
    // Aufbauen des Graphen:
    ArrayList<SubSectorObstacle> graph = new ArrayList<SubSectorObstacle>(); // Der Graph selber
    LinkedList<Moveable> openObstacles = new LinkedList<Moveable>(); // Die Liste mit noch zu untersuchenden Knoten
    ArrayList<Moveable> closedObstacles = new ArrayList<Moveable>(); // Bearbeitete Knoten

    openObstacles.add(obstacle); // Startpunkt des Graphen.
    closedObstacles.add(mover); // Wird im Graphen nicht mitbercksichtigt.
    double radius = mover.getRadius() + ServerBehaviourMove.MIN_DISTANCE;

    while (!openObstacles.isEmpty()) {
        // Neues Element aus der Liste holen und als bearbeitet markieren.
        Moveable work = openObstacles.poll();
        closedObstacles.add(work);
        SubSectorObstacle next = new SubSectorObstacle(work.getPrecisePosition().x(),
                work.getPrecisePosition().y(), work.getRadius());
        // Zuerst alle Punkte des Graphen lschen, die jetzt nichtmehr erreichbar sind:
        for (SubSectorObstacle obst : graph) {
            obst.removeNearNodes(next, radius);
        }
        // Mit Graph vernetzen
        for (SubSectorObstacle node : graph) {
            if (node.inColRange(next, radius)) {
                // Schnittpunkte suchen
                SubSectorNode[] intersections = node.calcIntersections(next, radius);
                for (SubSectorNode n2 : intersections) {
                    boolean reachable = true;
                    for (SubSectorObstacle o : graph) {
                        if (o.equals(node)) {
                            continue; // Um den gehts jetzt ja gerade, natrlich liegen wir auf diesem Kreis
                        }
                        if (o.moveCircleContains(n2, radius)) {
                            reachable = false;
                            break;
                        }
                    }
                    if (reachable) {
                        // Schnittpunkt einbauen
                        next.addNode(n2);
                        node.addNode(n2);
                    }
                }
            }
        }
        // Bearbeitetes selbst in Graph einfgen
        graph.add(next);
        // Weitere Hindernisse suchen, die jetzt relevant sind.
        List<Moveable> moversAround = Server.getInnerServer().moveMan.moveMap.moversAround(work,
                (work.getRadius() + radius) * 2);
        for (Moveable pmove : moversAround) {
            if (!closedObstacles.contains(pmove) && !openObstacles.contains(pmove)) {
                openObstacles.add(pmove);
            }
        }
    }

    // Jetzt drber laufen und Graph aufbauen:
    for (SubSectorObstacle obst : graph) {
        // Vorgensweise:
        // In jedem Hinderniss die Linie entlanglaufen und Knoten mit Kanten verbinden.
        // Ein Knoten darf auf einem Kreis immer nur in eine Richtung gehen.
        // (das sollte mithilfe seiner beiden, bekannten hindernisse recht einfach sein)
        // Die Lnge des Kreissegments lsst sich einfach mithilfe des winkels ausrechnen (Math.atan2(y,x)
        // Dann darf der A*. Bzw. Dijkstra, A* ist hier schon fast Overkill.
        // Alle Knoten ihrem Bogenma nach sortieren.
        obst.sortNodes();
        obst.interConnectNodes(radius);
    }

    // Start- und Zielknoten einbauen und mit dem Graph vernetzten.
    SubSectorNode startNode = new SubSectorNode(mover.getPrecisePosition().x(), mover.getPrecisePosition().y());
    SubSectorNode targetNode = new SubSectorNode(target.x(), target.y());
    double min = Double.POSITIVE_INFINITY;
    SubSectorObstacle minObstacle = null;
    for (SubSectorObstacle obst : graph) {
        double newdist = Math.sqrt((obst.getX() - startNode.getX()) * (obst.getX() - startNode.getX())
                + (obst.getY() - startNode.getY()) * (obst.getY() - startNode.getY()));
        newdist -= obst.getRadius() + radius; // Es interessiert uns der nchstmgliche Kreis, nicht das nchste Hinderniss
        if (newdist < min) {
            min = newdist;
            minObstacle = obst;
        }
    }
    // Punkt auf Laufkreis finden
    Vector direct = new Vector(startNode.getX() - minObstacle.getX(), startNode.getY() - minObstacle.getY());
    direct = direct.normalize().multiply(minObstacle.getRadius() + radius);

    SubSectorNode minNode = new SubSectorNode(minObstacle.getX() + direct.getX(),
            minObstacle.getY() + direct.getY(), minObstacle);

    // In das Hinderniss integrieren:
    minObstacle.lateIntegrateNode(minNode);
    SubSectorEdge startEdge = new SubSectorEdge(startNode, minNode, min);

    if (!startNode.equals(minNode)) {

        startNode.addEdge(startEdge);
        minNode.addEdge(startEdge);

    } else {
        // Wir stehen schon auf dem minNode.
        // Die Einsprungkante ist nicht notwendig.
        startNode = minNode;
    }

    double min2 = Double.POSITIVE_INFINITY;
    SubSectorObstacle minObstacle2 = null;
    for (SubSectorObstacle obst : graph) {
        double newdist = Math.sqrt((obst.getX() - targetNode.getX()) * (obst.getX() - targetNode.getX())
                + (obst.getY() - targetNode.getY()) * (obst.getY() - targetNode.getY()));
        newdist -= obst.getRadius() + radius; // Es interessiert uns der nchstmgliche Kreis, nicht das nchste Hinderniss
        if (newdist < min2) {
            min2 = newdist;
            minObstacle2 = obst;
        }
    }
    // Punkt auf Laufkreis finden
    Vector direct2 = new Vector(targetNode.getX() - minObstacle2.getX(),
            targetNode.getY() - minObstacle2.getY());
    direct2 = direct2.normalize().multiply(minObstacle2.getRadius() + radius);

    SubSectorNode minNode2 = new SubSectorNode(minObstacle2.getX() + direct2.getX(),
            minObstacle2.getY() + direct2.getY(), minObstacle2);

    // In das Hinderniss integrieren:
    minObstacle2.lateIntegrateNode(minNode2);
    SubSectorEdge targetEdge = new SubSectorEdge(minNode2, targetNode, min2);

    if (!targetNode.equals(minNode2)) {

        targetNode.addEdge(targetEdge);
        minNode2.addEdge(targetEdge);

    } else {
        // Das Ziel ist schon auf dem Laufkreis.
        // Die Aussprungkante ist nicht ntig.
        targetNode = minNode2;
    }

    /**
     * Hier jetzt einen Weg suchen von startNode nach targetNode.
     * Die Kanten sind in node.myEdges
     * Die Ziele bekommt man mit edge.getOther(startNode)
     * Die Lnge (Wegkosten) stehen in edge.length (vorsicht: double-Wert!)
     */
    PriorityBuffer open = new PriorityBuffer(); // Liste fr entdeckte Knoten
    LinkedHashSet<SubSectorNode> containopen = new LinkedHashSet<SubSectorNode>(); // Auch fr entdeckte Knoten, hiermit kann viel schneller festgestellt werden, ob ein bestimmter Knoten schon enthalten ist.
    LinkedHashSet<SubSectorNode> closed = new LinkedHashSet<SubSectorNode>(); // Liste fr fertig bearbeitete Knoten

    double cost_t = 0; //Movement Kosten (gerade 5, diagonal 7, wird spter festgelegt)

    open.add(startNode);

    while (open.size() > 0) {
        SubSectorNode current = (SubSectorNode) open.remove();
        containopen.remove(current);

        if (current.equals(targetNode)) { //Abbruch, weil Weg von Start nach Ziel gefunden wurde
            //targetNode.setParent(current.getParent());   //"Vorgngerfeld" von Ziel bekannt
            break;
        }

        // Aus der open wurde current bereits gelscht, jetzt in die closed verschieben
        closed.add(current);

        ArrayList<SubSectorEdge> neighbors = current.getMyEdges();

        for (SubSectorEdge edge : neighbors) {

            SubSectorNode node = edge.getOther(current);

            if (closed.contains(node)) {
                continue;
            }

            // Kosten dort hin berechnen
            cost_t = edge.getLength();

            if (containopen.contains(node)) { //Wenn sich der Knoten in der openlist befindet, muss berechnet werden, ob es einen krzeren Weg gibt

                if (current.getCost() + cost_t < node.getCost()) { //krzerer Weg gefunden?

                    node.setCost(current.getCost() + cost_t); //-> Wegkosten neu berechnen
                    //node.setValF(node.cost + node.getHeuristic());  //F-Wert, besteht aus Wegkosten vom Start + Luftlinie zum Ziel
                    node.setParent(current); //aktuelles Feld wird zum Vorgngerfeld
                }
            } else {
                node.setCost(current.getCost() + cost_t);
                //node.setHeuristic(Math.sqrt(Math.pow(Math.abs((targetNode.getX() - node.getX())), 2) + Math.pow(Math.abs((targetNode.getY() - node.getY())), 2)));   // geschtzte Distanz zum Ziel
                //Die Zahl am Ende der Berechnung ist der Aufwand der Wegsuche
                //5 ist schnell, 4 normal, 3 dauert lange

                node.setParent(current); // Parent ist die RogPosition, von dem der aktuelle entdeckt wurde
                //node.setValF(node.cost + node.getHeuristic());  //F-Wert, besteht aus Wegkosten vom Start aus + Luftlinie zum Ziel
                open.add(node); // in openlist hinzufgen
                containopen.add(node);
            }
        }
    }

    if (targetNode.getParent() == null) { //kein Weg gefunden
        return null;
    }

    ArrayList<SubSectorNode> pathrev = new ArrayList<SubSectorNode>(); //Pfad aus parents erstellen, von Ziel nach Start
    while (!targetNode.equals(startNode)) {
        pathrev.add(targetNode);
        targetNode = targetNode.getParent();
    }
    pathrev.add(startNode);

    ArrayList<SubSectorNode> path = new ArrayList<SubSectorNode>(); //Pfad umkehren, sodass er von Start nach Ziel ist
    for (int k = pathrev.size() - 1; k >= 0; k--) {
        path.add(pathrev.get(k));
    }

    // Nachbearbeitung:
    // Wir brauchen eine Kanten-Liste mit arc/direct Informationen

    ArrayList<SubSectorEdge> finalPath = new ArrayList<SubSectorEdge>();
    for (int i = 0; i < path.size() - 1; i++) {
        SubSectorNode from = path.get(i);
        SubSectorNode to = path.get(i + 1);
        SubSectorEdge edge = shortestCommonEdge(from, to);
        if (edge != null) {
            finalPath.add(edge);
        } else {
            throw new RuntimeException("ERROR Cannot find edge from " + from + " to " + to
                    + " but it is part of the calculated path!!!");
        }
    }

    return finalPath; //Pfad zurckgeben
}

From source file:com.rapidminer.operator.preprocessing.discretization.MinimalEntropyDiscretization.java

@Override
public PreprocessingModel createPreprocessingModel(ExampleSet exampleSet) throws OperatorException {
    HashMap<Attribute, double[]> rangesMap = new HashMap<Attribute, double[]>();
    double[][] ranges = getRanges(exampleSet);
    int attributeIndex = 0;
    for (Attribute attribute : exampleSet.getAttributes()) {
        if (attribute.isNumerical()) {
            ranges[attributeIndex][ranges[attributeIndex].length - 1] = Double.POSITIVE_INFINITY;
            rangesMap.put(attribute, ranges[attributeIndex]);
            attributeIndex++;//www.  j  a v a2 s . co  m
        }
    }

    DiscretizationModel model = new DiscretizationModel(exampleSet,
            getParameterAsBoolean(PARAMETER_REMOVE_USELESS));

    // determine number of digits
    int numberOfDigits = -1;
    if (getParameterAsBoolean(FrequencyDiscretization.PARAMETER_AUTOMATIC_NUMBER_OF_DIGITS) == false) {
        numberOfDigits = getParameterAsInt(FrequencyDiscretization.PARAMETER_NUMBER_OF_DIGITS);
    }

    model.setRanges(rangesMap, "range", getParameterAsInt(FrequencyDiscretization.PARAMETER_RANGE_NAME_TYPE),
            numberOfDigits);
    return model;
}

From source file:com.rapidminer.operator.preprocessing.discretization.BinDiscretization.java

@Override
public PreprocessingModel createPreprocessingModel(ExampleSet exampleSet) throws OperatorException {
    DiscretizationModel model = new DiscretizationModel(exampleSet);

    exampleSet.recalculateAllAttributeStatistics();
    int numberOfBins = getParameterAsInt(PARAMETER_NUMBER_OF_BINS);
    HashMap<Attribute, double[]> ranges = new HashMap<Attribute, double[]>();

    if (getParameterAsBoolean(PARAMETER_DEFINE_BOUNDARIES)) {
        double min = getParameterAsDouble(PARAMETER_MIN_VALUE);
        double max = getParameterAsDouble(PARAMETER_MAX_VALUE);
        if (min > max) {
            throw new UserError(this, 116, PARAMETER_MIN_VALUE + " and " + PARAMETER_MAX_VALUE,
                    "minimum must be less than maximum");
        }//ww w . ja  v  a2s .  c  o m
        for (Attribute attribute : exampleSet.getAttributes()) {
            if (attribute.isNumerical()) { // skip nominal and date attributes
                double[] binRange = new double[numberOfBins + 2];
                binRange[0] = min;
                for (int b = 1; b < numberOfBins; b++) {
                    binRange[b] = min + (((double) b / (double) numberOfBins) * (max - min));
                }
                binRange[numberOfBins] = max;
                binRange[numberOfBins + 1] = Double.POSITIVE_INFINITY;
                ranges.put(attribute, binRange);
            }
        }
    } else {
        for (Attribute attribute : exampleSet.getAttributes()) {
            if (attribute.isNumerical()) { // skip nominal and date attributes
                double[] binRange = new double[numberOfBins];
                double min = exampleSet.getStatistics(attribute, Statistics.MINIMUM);
                double max = exampleSet.getStatistics(attribute, Statistics.MAXIMUM);
                for (int b = 0; b < numberOfBins - 1; b++) {
                    binRange[b] = min + (((double) (b + 1) / (double) numberOfBins) * (max - min));
                }
                binRange[numberOfBins - 1] = Double.POSITIVE_INFINITY;
                ranges.put(attribute, binRange);
            }
        }
    }

    // determine number of digits
    int numberOfDigits = -1;
    if (getParameterAsBoolean(PARAMETER_AUTOMATIC_NUMBER_OF_DIGITS) == false) {
        numberOfDigits = getParameterAsInt(PARAMETER_NUMBER_OF_DIGITS);
    }

    model.setRanges(ranges, RANGE_NAME_BASE, getParameterAsInt(PARAMETER_RANGE_NAME_TYPE), numberOfDigits);
    return (model);
}

From source file:etomica.models.co2.PNCO2GCPM.java

/**
 * This returns the pairwise-additive portion of the GCPM potential for a
 * pair of atoms (dispersion + fixed-charge electrostatics)
 *///from www. j  av a  2  s .  co  m
public double getNonPolarizationEnergy(IMoleculeList molecules) {
    IAtomList water1Atoms = molecules.getMolecule(0).getChildList();
    IAtomList water2Atoms = molecules.getMolecule(1).getChildList();

    IVectorMutable C1r = water1Atoms.getAtom(0).getPosition();
    IVectorMutable C2r = water2Atoms.getAtom(0).getPosition();

    work.Ev1Mv2(C1r, C2r);
    shift.Ea1Tv1(-1, work);
    boundary.nearestImage(work);
    shift.PE(work);
    final boolean zeroShift = shift.squared() < 0.1;

    double r2 = work.squared();

    if (r2 <= sigmaC * coreFac) {
        return Double.POSITIVE_INFINITY;
    }

    IVectorMutable O11r = water1Atoms.getAtom(1).getPosition();
    IVectorMutable O12r = water1Atoms.getAtom(2).getPosition();
    IVectorMutable O21r = water2Atoms.getAtom(1).getPosition();
    IVectorMutable O22r = water2Atoms.getAtom(2).getPosition();

    double sum = 0;
    if (zeroShift) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                r2 = water1Atoms.getAtom(i).getPosition().Mv1Squared(water2Atoms.getAtom(j).getPosition());
                double r = Math.sqrt(r2);
                double rOverSigma = r / sigmaAll[i][j];
                double sigma2OverR2 = 1 / (rOverSigma * rOverSigma);
                if (1 / sigma2OverR2 < coreFac)
                    return Double.POSITIVE_INFINITY;
                double sixOverGamma = 6 / gamma;
                sum += epsilonAll[i][j] / (1 - sixOverGamma)
                        * (sixOverGamma * Math.exp(gamma * (1 - rOverSigma))
                                - sigma2OverR2 * sigma2OverR2 * sigma2OverR2);//exp-6 potential(Udisp)
            }
        }
    } else {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                IVector r1 = water1Atoms.getAtom(i).getPosition();
                shift.PE(r1);
                r2 = water2Atoms.getAtom(j).getPosition().Mv1Squared(shift);
                shift.ME(r1);

                double r = Math.sqrt(r2);
                double rOverSigma = r / sigmaAll[i][j];
                double sigma2OverR2 = 1 / (rOverSigma * rOverSigma);
                if (1 / sigma2OverR2 < coreFac)
                    return Double.POSITIVE_INFINITY;
                double sixOverGamma = 6 / gamma;

                sum += epsilonAll[i][j] / (1 - sixOverGamma)
                        * (sixOverGamma * Math.exp(gamma * (1 - rOverSigma))
                                - sigma2OverR2 * sigma2OverR2 * sigma2OverR2);//exp-6 potential(Udisp)
            }
        }
    }

    if (zeroShift) {
        r2 = O11r.Mv1Squared(O21r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        r2 = O11r.Mv1Squared(O22r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        r2 = O12r.Mv1Squared(O21r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        r2 = O12r.Mv1Squared(O22r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        r2 = C1r.Mv1Squared(O21r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        r2 = C1r.Mv1Squared(O22r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        r2 = C2r.Mv1Squared(O11r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        r2 = C2r.Mv1Squared(O12r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        r2 = C1r.Mv1Squared(C2r);
        sum += chargeC * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauC)));
    } else {
        shift.PE(O11r);
        r2 = O21r.Mv1Squared(shift);
        shift.ME(O11r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        shift.PE(O11r);
        r2 = O22r.Mv1Squared(shift);
        shift.ME(O11r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        shift.PE(O12r);
        r2 = O21r.Mv1Squared(shift);
        shift.ME(O12r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        shift.PE(O12r);
        r2 = O22r.Mv1Squared(shift);
        shift.ME(O12r);
        sum += chargeO * chargeO / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauO)));

        shift.PE(C1r);
        r2 = O21r.Mv1Squared(shift);
        shift.ME(C1r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        shift.PE(C1r);
        r2 = O22r.Mv1Squared(shift);
        shift.ME(C1r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        shift.PE(O11r);
        r2 = C2r.Mv1Squared(shift);
        shift.ME(O11r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        shift.PE(O12r);
        r2 = C2r.Mv1Squared(shift);
        shift.ME(O12r);
        sum += chargeO * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / sqrtCOtau));

        shift.PE(C1r);
        r2 = C2r.Mv1Squared(shift);
        shift.ME(C1r);
        sum += chargeC * chargeC / Math.sqrt(r2)
                * (1 - org.apache.commons.math3.special.Erf.erfc(Math.sqrt(r2) / (2 * tauC)));

    }
    return sum;
}

From source file:com.clust4j.algo.KMedoids.java

@Override
protected KMedoids fit() {
    synchronized (fitLock) {

        if (null != labels) // already fit
            return this;

        final LogTimer timer = new LogTimer();
        final double[][] X = data.getData();
        final double nan = Double.NaN;

        // Corner case: K = 1 or all singular
        if (1 == k) {
            labelFromSingularK(X);/*from   w  w  w .  j  a va  2 s . c  o  m*/
            fitSummary.add(new Object[] { iter, converged, tss, // tss
                    tss, // avg per cluster
                    tss, // wss
                    nan, // bss (none)
                    timer.wallTime() });
            sayBye(timer);
            return this;
        }

        // We do this in KMedoids and not KMeans, because KMedoids uses
        // real points as medoids and not means for centroids, thus
        // the recomputation of distances is unnecessary with the dist mat
        dist_mat = Pairwise.getDistance(X, getSeparabilityMetric(), true, false);
        info("distance matrix computed in " + timer.toString());

        // Initialize labels
        medoid_indices = init_centroid_indices;

        ClusterAssignments clusterAssignments;
        MedoidReassignmentHandler rassn;
        int[] newMedoids = medoid_indices;

        // Cost vars
        double bestCost = Double.POSITIVE_INFINITY, maxCost = Double.NEGATIVE_INFINITY, avgCost = Double.NaN,
                wss_sum = nan;

        // Iterate while the cost decreases:
        boolean convergedFromCost = false; // from cost or system changes?
        boolean configurationChanged = true;
        while (configurationChanged && iter < maxIter) {

            /*
             * 1. In each cluster, make the point that minimizes 
             *    the sum of distances within the cluster the medoid
             */
            try {
                clusterAssignments = assignClosestMedoid(newMedoids);
            } catch (IllegalClusterStateException ouch) {
                exitOnBadDistanceMetric(X, timer);
                return this;
            }

            /*
             * 1.5 The entries are not 100% equal, so we can (re)assign medoids...
             */
            try {
                rassn = new MedoidReassignmentHandler(clusterAssignments);
            } catch (IllegalClusterStateException ouch) {
                exitOnBadDistanceMetric(X, timer);
                return this;
            }

            /*
             * 1.75 This happens in the case of bad kernels that cause
             * infinities to propagate... we can't segment the input
             * space and need to just return a single cluster.
             */
            if (rassn.new_clusters.size() == 1) {
                this.k = 1;
                warn("(dis)similarity metric cannot partition space without propagating Infs. Returning one cluster");

                labelFromSingularK(X);
                fitSummary.add(new Object[] { iter, converged, tss, // tss
                        tss, // avg per cluster
                        tss, // wss
                        nan, // bss (none) 
                        timer.wallTime() });
                sayBye(timer);
                return this;
            }

            /*
             * 2. Reassign each point to the cluster defined by the 
             *    closest medoid determined in the previous step.
             */
            newMedoids = rassn.reassignedMedoidIdcs;

            /*
             * 2.5 Determine whether configuration changed
             */
            boolean lastIteration = VecUtils.equalsExactly(newMedoids, medoid_indices);

            /*
             * 3. Update the costs
             */
            converged = lastIteration || (convergedFromCost = FastMath.abs(wss_sum - bestCost) < tolerance);
            double tmp_wss_sum = rassn.new_clusters.total_cst;
            double tmp_bss = tss - tmp_wss_sum;

            // Check whether greater than max
            if (tmp_wss_sum > maxCost)
                maxCost = tmp_wss_sum;

            if (tmp_wss_sum < bestCost) {
                bestCost = wss_sum = tmp_wss_sum;
                labels = rassn.new_clusters.assn; // will be medoid idcs until encoded at end
                med_to_wss = rassn.new_clusters.costs;
                centroids = rassn.centers;
                medoid_indices = newMedoids;
                bss = tmp_bss;

                // get avg cost
                avgCost = wss_sum / (double) k;
            }

            if (converged) {
                reorderLabelsAndCentroids();
            }

            /*
             * 3.5 If this is the last one, it'll show the wss and bss
             */
            fitSummary.add(new Object[] { iter, converged, tss, avgCost, wss_sum, bss, timer.wallTime() });

            iter++;
            configurationChanged = !converged;
        }

        if (!converged)
            warn("algorithm did not converge");
        else
            info("algorithm converged due to "
                    + (convergedFromCost ? "cost minimization" : "harmonious state"));

        // wrap things up, create summary..
        sayBye(timer);

        return this;
    }

}

From source file:com.rapidminer.gui.plotter.charts.DeviationChartPlotter.java

private int prepareData() {
    // calculate min and max
    int columns = this.dataTable.getNumberOfColumns();
    double[] min = new double[columns];
    double[] max = new double[columns];
    for (int c = 0; c < columns; c++) {
        min[c] = Double.POSITIVE_INFINITY;
        max[c] = Double.NEGATIVE_INFINITY;
    }/*w w  w.j  a  v a 2 s .  com*/

    synchronized (dataTable) {
        Iterator<DataTableRow> i = dataTable.iterator();
        while (i.hasNext()) {
            DataTableRow row = i.next();
            for (int c = 0; c < dataTable.getNumberOfColumns(); c++) {
                double value = row.getValue(c);
                min[c] = MathFunctions.robustMin(min[c], value);
                max[c] = MathFunctions.robustMax(max[c], value);
            }
        }
    }

    synchronized (dataTable) {
        this.dataset = new YIntervalSeriesCollection();
        if (colorColumn >= 0 && dataTable.isNominal(colorColumn)) {
            for (int v = 0; v < dataTable.getNumberOfValues(colorColumn); v++) {
                String valueName = dataTable.mapIndex(colorColumn, v);
                YIntervalSeries series = new YIntervalSeries(valueName);
                boolean first = true;
                List<String> domainValues = new LinkedList<String>();
                for (int column = 0; column < dataTable.getNumberOfColumns(); column++) {
                    if (!dataTable.isSpecial(column) && column != colorColumn) {
                        Iterator<DataTableRow> i = this.dataTable.iterator();
                        double sum = 0.0d;
                        double squaredSum = 0.0d;
                        int counter = 0;
                        while (i.hasNext()) {
                            DataTableRow row = i.next();
                            if (row.getValue(colorColumn) != v) {
                                continue;
                            }
                            double value = row.getValue(column);
                            sum += value;
                            squaredSum += value * value;
                            counter++;
                        }

                        double mean = sum / counter;
                        double deviation = Math.sqrt(squaredSum / counter - mean * mean);
                        if (isLocalNormalized()) {
                            mean = (mean - min[column]) / (max[column] - min[column]);
                            deviation = (deviation - min[column]) / (max[column] - min[column]);
                        }
                        series.add(column, mean, mean - deviation, mean + deviation);
                        domainValues.add(dataTable.getColumnName(column));
                    }
                }
                if (first) {
                    this.domainAxisMap = new String[domainValues.size()];
                    domainValues.toArray(this.domainAxisMap);
                }
                first = false;
                dataset.addSeries(series);
            }
            return dataTable.getNumberOfValues(colorColumn);
        } else {
            YIntervalSeries series = new YIntervalSeries(dataTable.getName());
            List<String> domainValues = new LinkedList<String>();
            for (int column = 0; column < dataTable.getNumberOfColumns(); column++) {
                if (!dataTable.isSpecial(column) && column != colorColumn) {
                    Iterator<DataTableRow> i = this.dataTable.iterator();
                    double sum = 0.0d;
                    double squaredSum = 0.0d;
                    int counter = 0;
                    while (i.hasNext()) {
                        DataTableRow row = i.next();
                        double value = row.getValue(column);
                        sum += value;
                        squaredSum += value * value;
                        counter++;
                    }

                    double mean = sum / counter;
                    double deviation = Math.sqrt(squaredSum / counter - mean * mean);
                    if (isLocalNormalized()) {
                        mean = (mean - min[column]) / (max[column] - min[column]);
                        // deviation = (deviation - min[column]) / (max[column] - min[column]);
                    }
                    series.add(column, mean, mean - deviation, mean + deviation);
                    domainValues.add(dataTable.getColumnName(column));
                }
            }
            dataset.addSeries(series);
            this.domainAxisMap = new String[domainValues.size()];
            domainValues.toArray(this.domainAxisMap);
            return 0;
        }
    }
}