List of usage examples for java.lang Double POSITIVE_INFINITY
double POSITIVE_INFINITY
To view the source code for java.lang Double POSITIVE_INFINITY.
Click Source Link
From source file:com.clust4j.algo.NearestCentroid.java
/** * To be used from {@link KMeans}//from w w w . j a v a 2s .c o m * @param data * @return */ protected EntryPair<int[], double[]> predict(double[][] data) { if (null == centroids) throw new ModelNotFitException("model not yet fit"); int[] predictions = new int[data.length]; double[] dists = new double[data.length]; double[] row, centroid; for (int i = 0; i < data.length; i++) { row = data[i]; double minDist = Double.POSITIVE_INFINITY, dist = minDist; int nearestLabel = 0; // should not equal -1, because dist could be infinity for (int j = 0; j < centroids.size(); j++) { centroid = centroids.get(j); dist = getSeparabilityMetric().getPartialDistance(centroid, row); // Can afford to compute partial dist--faster if (dist < minDist) { minDist = dist; nearestLabel = j; } } predictions[i] = nearestLabel; dists[i] = minDist; } return new EntryPair<>(encoder.reverseTransform(predictions), dists); }
From source file:com.opengamma.analytics.financial.model.finitedifference.CraigSneydFiniteDifference2D.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]; initializeMatrices(pdeData, xSteps, ySteps, xLowerBoundary, yLowerBoundary, dx, dy, v, x, y); double t = 0.0; double a, b, c, d, e, f; for (int n = 0; n < tSteps; n++) { // stag 1 full Explicit for (int i = 1; i < xSteps; i++) { for (int j = 1; j < ySteps; j++) { a = pdeData.getA(t, x[i], y[j]); b = pdeData.getB(t, x[i], y[j]); c = pdeData.getC(t, x[i], y[j]); d = pdeData.getD(t, x[i], y[j]); e = pdeData.getE(t, x[i], y[j]); f = pdeData.getF(t, x[i], y[j]); vt[i][j] = (1 - dt * (1 - 0.5 * THETA) * c) * v[i][j]; vt[i][j] -= dtdx2 * a * (1 - THETA) * (v[i + 1][j] + v[i - 1][j] - 2 * v[i][j]); vt[i][j] -= 0.5 * dtdx * b * (1 - THETA) * (v[i + 1][j] - v[i - 1][j]); vt[i][j] -= dtdy2 * d * (v[i][j + 1] + v[i][j - 1] - 2 * v[i][j]); // upwind // if (f > 0) { // vt[i][j] -= dtdy * f * (v[i][j] - v[i][j - 1]); // } else if (f < 0) { // vt[i][j] -= dtdy * f * (v[i][j + 1] - v[i][j]); // } vt[i][j] -= 0.5 * dtdy * f * (v[i][j + 1] - v[i][j - 1]); vt[i][j] -= 0.25 * dtdxdy * e * (v[i + 1][j + 1] + v[i - 1][j - 1] - v[i + 1][j - 1] - v[i - 1][j + 1]); }// w w w .ja va 2 s . com // really not sure what to do with boundary conditions in these intermediate steps vt[i][0] = v[i][0]; vt[i][ySteps] = v[i][ySteps]; } // for (int i = 0; i <= xSteps; i++) { // double[] temp = yLowerBoundary.getRightMatrixCondition(pdeData, t, x[i]); // double sum = 0; // for (int k = 0; k < temp.length; k++) { // sum += temp[k] * v[i][k]; // } // sum += yLowerBoundary.getConstant(pdeData, t, x[i], dy); // // temp = yLowerBoundary.getLeftMatrixCondition(pdeData, t, x[i]); // for (int k = 1; k < temp.length; k++) { // sum -= temp[k] * vt[i][k]; // } // vt[i][0] = sum / temp[0]; // // temp = yUpperBoundary.getRightMatrixCondition(pdeData, t, x[i]); // sum = 0; // for (int k = 0; k < temp.length; k++) { // sum += temp[k] * v[i][ySteps - k]; // } // sum += yUpperBoundary.getConstant(pdeData, t, x[i], dy); // // temp = yUpperBoundary.getLeftMatrixCondition(pdeData, t, x[i]); // for (int k = 1; k < temp.length; k++) { // sum -= temp[k] * vt[i][ySteps - k]; // } // vt[i][ySteps] = sum / temp[0]; // } // // for (int j = 1; j < ySteps; j++) { // double[] temp = xLowerBoundary.getRightMatrixCondition(pdeData, t, y[j]); // double sum = 0; // for (int k = 0; k < temp.length; k++) { // sum += temp[k] * v[k][j]; // } // sum += xLowerBoundary.getConstant(pdeData, t, y[j], dx); // // temp = xLowerBoundary.getLeftMatrixCondition(pdeData, t, y[j]); // for (int k = 1; k < temp.length; k++) { // sum -= temp[k] * vt[k][j]; // } // vt[0][j] = sum / temp[0]; // // temp = xUpperBoundary.getRightMatrixCondition(pdeData, t, y[j]); // sum = 0; // for (int k = 0; k < temp.length; k++) { // sum += temp[k] * v[xSteps - k][j]; // } // sum += xUpperBoundary.getConstant(pdeData, t, y[j], dx); // // temp = xUpperBoundary.getLeftMatrixCondition(pdeData, t, y[j]); // for (int k = 1; k < temp.length; k++) { // sum -= temp[k] * vt[xSteps - k][j]; // } // vt[xSteps][j] = sum / temp[0]; // } // stag 2 implicit in x t += dt / 2; 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] = THETA * (dtdx2 * a - 0.5 * dtdx * b); mx[i][i] = 1 + THETA * (-2 * dtdx2 * a + 0.5 * dt * c); mx[i][i + 1] = THETA * (dtdx2 * a + 0.5 * dtdx * b); q[i] = vt[i][j]; } 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; final int count = sor(xSteps, vt, q, mx, j, omega); Validate.isTrue(count < 1000, "SOR exceeded max iterations"); } // stag 3 explicit in y for (int i = 0; i <= xSteps; i++) { for (int j = 1; j < ySteps; j++) { c = pdeData.getC(t, x[i], y[j]); d = pdeData.getD(t, x[i], y[j]); f = pdeData.getF(t, x[i], y[j]); vt[i][j] += THETA * 0.5 * dt * c * v[i][j]; vt[i][j] += THETA * dtdy2 * d * (v[i][j + 1] + v[i][j - 1] - 2 * v[i][j]); // upwind // if (f > 0) { // vt[i][j] += THETA * dtdy * f * (v[i][j] - v[i][j - 1]); // } else if (f < 0) { // vt[i][j] += THETA * dtdy * f * (v[i][j + 1] - v[i][j]); // } vt[i][j] += THETA * 0.5 * dtdy * f * (v[i][j + 1] - v[i][j - 1]); } // double[] temp = yLowerBoundary.getRightMatrixCondition(pdeData, t, x[i]); // double sum = 0; // for (int k = 0; k < temp.length; k++) { // sum += temp[k] * v[i][k]; // } // sum += yLowerBoundary.getConstant(pdeData, t, x[i], dy); // // temp = yLowerBoundary.getLeftMatrixCondition(pdeData, t, x[i]); // for (int k = 1; k < temp.length; k++) { // sum -= temp[k] * vt[i][k]; // } // vt[i][0] = sum / temp[0]; // // temp = yUpperBoundary.getRightMatrixCondition(pdeData, t, x[i]); // sum = 0; // for (int k = 0; k < temp.length; k++) { // sum += temp[k] * v[i][ySteps - k]; // } // sum += yUpperBoundary.getConstant(pdeData, t, x[i], dy); // // temp = yUpperBoundary.getLeftMatrixCondition(pdeData, t, x[i]); // for (int k = 1; k < temp.length; k++) { // sum -= temp[k] * vt[i][ySteps - k]; // } // vt[i][ySteps] = sum / temp[0]; } // The y = 0 and y = yStep boundary values are assumed the same as the previous sub-step // Again we could apply the y boundary conditions here // stag 4 implicit in y for (int i = 0; i <= xSteps; i++) { for (int j = 1; j < ySteps; j++) { c = pdeData.getC(t, x[i], y[j]); d = pdeData.getD(t, x[i], y[j]); f = pdeData.getF(t, x[i], y[j]); // upwind // if (f > 0) { // my[j][j - 1] = THETA * (dtdy2 * d - dtdy * f); // my[j][j] = 1 + THETA * (-2 * dtdy2 * d + dtdy * f + 0.5 * dt * c); // my[j][j + 1] = THETA * (dtdy2 * d); // } else if (f < 0) { // my[j][j - 1] = THETA * (dtdy2 * d); // my[j][j] = 1 + THETA * (-2 * dtdy2 * d - dtdy * f + 0.5 * dt * c); // my[j][j + 1] = THETA * (dtdy2 * d + dtdy * f); // } my[j][j - 1] = THETA * (dtdy2 * d - 0.5 * dtdy * f); my[j][j] = 1 + THETA * (-2 * dtdy2 * d + 0.5 * dt * c); my[j][j + 1] = THETA * (dtdy2 * d + 0.5 * dtdy * f); r[j] = vt[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] * v[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] * v[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 < 1000) { 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 < 1000, "SOR exceeded max interations"); } } // time loop return v; }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.targetcharts.SparkLine.java
private void addAvaregeSeries(TimeSeries series, XYPlot plot) { logger.debug("IN"); boolean isFirst = true; double avg = 0, min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY; int count = 0; for (int i = 0; i < series.getItemCount(); i++) { if (series.getValue(i) != null) { count++;// w w w .j a va 2s . c o m if (isFirst) { min = series.getValue(i).doubleValue(); max = series.getValue(i).doubleValue(); isFirst = false; } double n = series.getValue(i).doubleValue(); avg += n; if (n < min) min = n; if (n > max) max = n; logger.debug(n); } } avg = avg / (double) count; //plot.getRangeAxis().setRange(new Range(min-2, max+2)); addMarker(1, avg, colorAverage, 0.8f, plot); logger.debug("OUT"); }
From source file:mase.app.soccer.ProgSoccerAgent.java
@Override public void step(SimState state) { super.step(state); Soccer soc = (Soccer) state;//from w ww .j ava 2 s . co m Ball ball = soc.ball; /** * ***** Update agent status ****** */ // the agent just kicked the ball (is over the ball), do nothing if (justKicked) { return; } // Is the agent free to drible towards the goal? SoccerAgent impedingDrible = closestInFront(oppGoal.subtract(getLocation()).angle(), openDistance, openAngle); this.openToDrible = impedingDrible == null; // Update the justPassed flag if (justPassed) { if (ball.getCurrentSpeed() < 0.01) { justPassed = false; } else { for (SoccerAgent a : others) { if (a.hasPossession) { justPassed = false; break; } } } } /** * ***** Actions ****** */ // Execute the first possible action // If the agent has possession of the ball: // -- Shoot to goal if it has clear shot and it is within range // -- Pass to a teammate that is open and closer to the goal // -- Drible towards the goal if open // -- Drible away from the closest agent in front, if there is space to do so // -- Pass the ball to any teammate open to drible // -- Pass the ball to any teammate with clear pass // -- Shoot the ball away from the closest agent in front // If the agent doesnt have the ball: // -- Move towards the ball if it is the closest teammate closest to it // -- Move towards the ball if it is the closest teammate to it with the path clear (clearDist = agentRadius) // -- Defend the goal if it is the closest teammate to it // -- If on defense or team possession is undefined: // -- Mark the nearest undefended opponent (undefended = no nearby teammate, move to between the opponent and their goal) // -- If on attack // -- ?? // -- Keep within passing distance of the closest agent (what about 2 isolate agents, with no ball) // -- Get open if (hasPossession) { // Shoot to goal if it has clear shot and it is within range List<Double2D> shuffledTargets = new ArrayList<>(goalTargets); Collections.shuffle(shuffledTargets, rand); for (Double2D target : shuffledTargets) { if (clearShot(ball, target, kickRange, clearDistance)) { kickTowards(ball, target, kickSpeed); lastAction = "Clear shot to goal: " + target; return; } } // Pass to a teammate that is open and closer to the goal List<SoccerAgent> shuffledTeam = new ArrayList<>(teamMates); Collections.shuffle(shuffledTeam, rand); double distToGoal = this.distanceTo(oppGoal); for (SoccerAgent mate : shuffledTeam) { // at least one robot of distance closer if (((ProgSoccerAgent) mate).openToDrible && mate.distanceTo(oppGoal) < distToGoal - soc.par.agentRadius * 2) { double d = this.distanceTo(mate); if (clearShot(ball, mate, kickRange, clearDistance)) { kickTowards(ball, mate.getLocation(), optimalKickSpeed(d)); lastAction = "Pass to advanced teammate: " + mate; justPassed = true; return; } } } // Drible towards the goal if open if (openToDrible) { kickTowards(ball, oppGoal, dribleSpeed); lastAction = "Drible towards goal"; return; } // Drible away from closest in front if there is space to do so // Calculate the vectors perpendicular to the agent-obstacle vector Double2D agToClosest = impedingDrible.getLocation().subtract(getLocation()); Double2D awayOne = agToClosest.rotate(-Math.PI / 2); Double2D awayTwo = agToClosest.rotate(Math.PI / 2); Double2D futureOne = ball.getLocation().add(awayOne.normalize().multiply(openDistance)); Double2D futureTwo = ball.getLocation().add(awayTwo.normalize().multiply(openDistance)); // One is the closest to goal, Two is the farthest if (futureTwo.distance(oppGoal) < futureOne.distance(oppGoal)) { Double2D temp = futureOne; futureOne = futureTwo; futureTwo = temp; temp = awayOne; awayOne = awayTwo; awayTwo = temp; } // Try to move in the One direction, checking if it is inside the field and is clear if (futureOne.x < field.width && futureOne.x > 0 && futureOne.y > 0 && futureOne.y < field.height && closestInFront(awayOne.angle(), openDistance, openAngle) == null) { kickBall(awayOne.angle(), dribleSpeed); lastAction = "Drible away from closest (1): " + impedingDrible; return; } // Otherwise, try to move in the Two direction if (futureTwo.x < field.width && futureTwo.x > 0 && futureTwo.y > 0 && futureTwo.y < field.height && closestInFront(awayTwo.angle(), openDistance, openAngle) == null) { kickBall(awayTwo.angle(), dribleSpeed); lastAction = "Drible away from closest (2): " + impedingDrible; return; } // Pass to any teammate that can drible towards goal for (SoccerAgent mate : shuffledTeam) { if (((ProgSoccerAgent) mate).openToDrible && clearShot(ball, mate, kickRange, clearDistance)) { kickTowards(ball, mate.getLocation(), optimalKickSpeed(this.distanceTo(mate))); lastAction = "Pass to any teammate open to drible: " + mate; justPassed = true; return; } } // Pass to any teammate with clear pass for (SoccerAgent mate : shuffledTeam) { if (clearShot(ball, mate, kickRange, clearDistance)) { kickTowards(ball, mate.getLocation(), optimalKickSpeed(this.distanceTo(mate))); lastAction = "Pass to any teammate with clear pass: " + mate; justPassed = true; return; } } // Shoot ball away from closest in front -- last case scenario, should this exist? kickBall(awayOne.angle(), kickSpeed); lastAction = "Shooting away from the closest agent"; } else { // NO BALL POSSESSION List<Pair<SoccerAgent, Double>> sorted = sortByProximity(ownTeam, ball.getLocation()); // Move towards the ball it is the closest agent, regardless of clear paths if (!justPassed && sorted.get(0).getLeft() == this) { moveTowards(ball.getLocation()); lastAction = "Closest, move to the ball"; return; } // Defend the goal if it is the closest to it (excluding the agent closest to the ball) sorted = sortByProximity(ownTeam, ownGoal); boolean closestToGoal = false; for (Pair<SoccerAgent, Double> p : sorted) { ProgSoccerAgent pp = (ProgSoccerAgent) p.getLeft(); if (!pp.lastAction.equals("Closest, move to the ball")) { closestToGoal = (pp == this); break; } } if (closestToGoal) { Double2D gkPosition = new Double2D( ownGoal.x < oppGoal.x ? ownGoal.x + soc.par.agentRadius + 1 : ownGoal.x - soc.par.agentRadius - 1, Math.min(ownGoal.y + soc.par.goalWidth / 2, Math.max(ownGoal.y - soc.par.goalWidth / 2, ball.getLocation().y))); moveTowards(gkPosition); lastAction = "Goalkeeper duty: " + gkPosition; return; } if (!justPassed) { // Move towards the ball if it is the closest one with clear line boolean closestClear = false; for (Pair<SoccerAgent, Double> p : sorted) { ProgSoccerAgent pp = (ProgSoccerAgent) p.getLeft(); if (pp.clearPath(ball.getLocation(), pp.getRadius())) { closestClear = (pp == this); break; } } if (closestClear) { moveTowards(ball.getLocation()); lastAction = "Closest with clear path, move to the ball"; return; } } // If on defense if (soc.referee.teamPossession == null || soc.referee.teamPossession != this.teamColor) { // Mark the nearest opponent that I'm the closest SoccerAgent closestOpp = null; double min = Double.POSITIVE_INFINITY; for (SoccerAgent a : oppTeam) { if (closestTeammate(a.getLocation(), true, true) == this) { // check if I'm the closest double d = this.distanceTo(a); if (d < min) { min = d; closestOpp = a; } } } if (closestOpp != null) { // Move to between the agent and my goal Double2D intersect = ownGoal.subtract(closestOpp.getLocation()).normalize() .multiply(soc.par.agentRadius * 3).add(closestOpp.getLocation()); moveTowards(intersect); lastAction = "Mark closest: " + closestOpp; return; } } else { // On attack // Find the closest agent between me and the ball SoccerAgent closestOther = null; double min = Double.POSITIVE_INFINITY; for (SoccerAgent a : others) { if (StaticPolygon.distToSegment(a.getLocation(), this.getLocation(), ball.getLocation()) < soc.par.agentRadius * 2) { double d = this.distanceTo(a); if (d < min) { min = d; closestOther = a; } } } // Move perendicularly to the agent-ball vector, in the direction opposite to the closest agent if (closestOther != null) { boolean left = StaticPolygon.isLeftOf(closestOther.getLocation(), this.getLocation(), ball.getLocation()); double angle = ball.getLocation().subtract(this.getLocation()).angle(); if (left) { // Go to right super.move(angle - Math.PI / 2, moveSpeed); } else { super.move(angle + Math.PI / 2, moveSpeed); } lastAction = "Get open"; return; } } lastAction = "Do nothing without the ball"; } }
From source file:com.duy.pascal.interperter.libraries.math.MathLib.java
@PascalMethod(description = "") public boolean IsInfinite(double x) { return Double.POSITIVE_INFINITY == x || Double.NEGATIVE_INFINITY == x; }
From source file:com.rapidminer.gui.plotter.charts.Abstract2DChartPlotter.java
private void prepareNominalData() { this.nominal = true; dataSet = new DefaultXYDataset(); if (axis[X_AXIS] >= 0 && axis[Y_AXIS] >= 0) { Map<String, List<double[]>> dataCollection = new LinkedHashMap<String, List<double[]>>(); Map<String, List<String>> idCollection = new LinkedHashMap<String, List<String>>(); synchronized (dataTable) { if (colorColumn >= 0) { for (int v = 0; v < dataTable.getNumberOfValues(colorColumn); v++) { dataCollection.put(dataTable.mapIndex(colorColumn, v), new LinkedList<double[]>()); idCollection.put(dataTable.mapIndex(colorColumn, v), new LinkedList<String>()); }/* w ww.j a va 2 s . co m*/ } Iterator<DataTableRow> i = this.dataTable.iterator(); int index = 0; while (i.hasNext()) { DataTableRow row = i.next(); double xValue = row.getValue(axis[X_AXIS]); double yValue = row.getValue(axis[Y_AXIS]); double colorValue = Double.NaN; if (colorColumn >= 0) { colorValue = row.getValue(colorColumn); } // TM: removed check // if (!Double.isNaN(xValue) && !Double.isNaN(yValue)) { addPoint(dataCollection, idCollection, row.getId(), xValue, yValue, colorValue); // } index++; } } double minX = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; Iterator<Map.Entry<String, List<double[]>>> i = dataCollection.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, List<double[]>> entry = i.next(); List<double[]> dataList = entry.getValue(); Iterator<double[]> j = dataList.iterator(); while (j.hasNext()) { double[] current = j.next(); minX = MathFunctions.robustMin(minX, current[X_AXIS]); maxX = MathFunctions.robustMax(maxX, current[X_AXIS]); minY = MathFunctions.robustMin(minY, current[Y_AXIS]); maxY = MathFunctions.robustMax(maxY, current[Y_AXIS]); } } Random jitterRandom = new Random(2001); double oldXRange = maxX - minX; double oldYRange = maxY - minY; if (Double.isInfinite(oldXRange) || Double.isNaN(oldXRange)) { oldXRange = 0; } if (Double.isInfinite(oldYRange) || Double.isNaN(oldYRange)) { oldYRange = 0; } i = dataCollection.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, List<double[]>> entry = i.next(); String seriesName = entry.getKey(); List<double[]> dataList = entry.getValue(); double[][] data = new double[2][dataList.size()]; int listCounter = 0; Iterator<double[]> j = dataList.iterator(); while (j.hasNext()) { double[] current = j.next(); data[X_AXIS][listCounter] = current[X_AXIS]; data[Y_AXIS][listCounter] = current[Y_AXIS]; if (this.jitterAmount > 0) { double pertX = oldXRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian(); double pertY = oldYRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian(); data[X_AXIS][listCounter] += pertX; data[Y_AXIS][listCounter] += pertY; } listCounter++; } ((DefaultXYDataset) dataSet).addSeries(seriesName, data); } int seriesCounter = 0; Iterator<List<String>> v = idCollection.values().iterator(); while (v.hasNext()) { List<String> idList = v.next(); int itemCounter = 0; Iterator<String> j = idList.iterator(); while (j.hasNext()) { idMap.put(new SeriesAndItem(seriesCounter, itemCounter++), j.next()); } seriesCounter++; } } }
From source file:com.wwidesigner.optimization.ObjectiveFunctionOptimizer.java
protected static PointValuePair doSingleStart(BaseObjectiveFunction objective, double[] startPoint, int maxEvaluations, double[] nextStart) { singleRunEvaluations = 0;//w w w. j a v a 2 s. c om PointValuePair result = null; try { int numVariables = objective.getNrDimensions(); if (numVariables > 1) // Use BOBYQA { double trustRegion = objective.getInitialTrustRegionRadius(nextStart); double stoppingTrustRegion = objective.getStoppingTrustRegionRadius(); BOBYQAOptimizer optimizer = new BOBYQAOptimizer(objective.getNrInterpolations(), trustRegion, stoppingTrustRegion); result = runBobyqa(optimizer, objective, nextStart, maxEvaluations); singleRunEvaluations = optimizer.getEvaluations(); } else // Use Brent { BrentOptimizer optimizer = new BrentOptimizer(1.e-6, 1.e-14); UnivariatePointValuePair outcome = runBrent(optimizer, objective, startPoint); result = new PointValuePair(new double[] { outcome.getPoint() }, outcome.getValue()); singleRunEvaluations = optimizer.getEvaluations(); } double value = result.getValue(); if (value == Double.POSITIVE_INFINITY) { System.out.print("no valid solution found"); } else { System.out.print("optimum " + result.getValue()); } } catch (TooManyEvaluationsException e) { System.out.println("Exception: " + e.getMessage()); } // Thrown by BOBYQA for no apparent reason: a bug? catch (NoSuchElementException e) { System.out.println("no valid solution found"); } catch (OperationCancelledException e) { // Restore starting point. objective.setGeometryPoint(startPoint); // Re-throw the exception to give up the whole multi-start // optimization. throw new OperationCancelledException(e.getMessage()); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); // e.printStackTrace(); } finally { System.out.println(" at start point " + Arrays.toString(nextStart)); } return result; }
From source file:org.jfree.data.jdbc.JDBCXYDataset.java
/** * ExecuteQuery will attempt execute the query passed to it against the * provided database connection. If connection is null then no action is * taken./* w ww . ja v a 2 s.c o m*/ * * The results from the query are extracted and cached locally, thus * applying an upper limit on how many rows can be retrieved successfully. * * @param query the query to be executed. * @param con the connection the query is to be executed against. * * @throws SQLException if there is a problem executing the query. */ public void executeQuery(Connection con, String query) throws SQLException { if (con == null) { throw new SQLException("There is no database to execute the query."); } ResultSet resultSet = null; Statement statement = null; try { statement = con.createStatement(); resultSet = statement.executeQuery(query); ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); int numberOfValidColumns = 0; int[] columnTypes = new int[numberOfColumns]; for (int column = 0; column < numberOfColumns; column++) { try { int type = metaData.getColumnType(column + 1); switch (type) { case Types.NUMERIC: case Types.REAL: case Types.INTEGER: case Types.DOUBLE: case Types.FLOAT: case Types.DECIMAL: case Types.BIT: case Types.DATE: case Types.TIME: case Types.TIMESTAMP: case Types.BIGINT: case Types.SMALLINT: ++numberOfValidColumns; columnTypes[column] = type; break; default: columnTypes[column] = Types.NULL; break; } } catch (SQLException e) { columnTypes[column] = Types.NULL; throw e; } } if (numberOfValidColumns <= 1) { throw new SQLException("Not enough valid columns where generated by query."); } /// First column is X data this.columnNames = new String[numberOfValidColumns - 1]; /// Get the column names and cache them. int currentColumn = 0; for (int column = 1; column < numberOfColumns; column++) { if (columnTypes[column] != Types.NULL) { this.columnNames[currentColumn] = metaData.getColumnLabel(column + 1); ++currentColumn; } } // Might need to add, to free memory from any previous result sets if (this.rows != null) { for (int column = 0; column < this.rows.size(); column++) { ArrayList row = (ArrayList) this.rows.get(column); row.clear(); } this.rows.clear(); } // Are we working with a time series. switch (columnTypes[0]) { case Types.DATE: case Types.TIME: case Types.TIMESTAMP: this.isTimeSeries = true; break; default: this.isTimeSeries = false; break; } // Get all rows. // rows = new ArrayList(); while (resultSet.next()) { ArrayList newRow = new ArrayList(); for (int column = 0; column < numberOfColumns; column++) { Object xObject = resultSet.getObject(column + 1); switch (columnTypes[column]) { case Types.NUMERIC: case Types.REAL: case Types.INTEGER: case Types.DOUBLE: case Types.FLOAT: case Types.DECIMAL: case Types.BIGINT: case Types.SMALLINT: newRow.add(xObject); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newRow.add(new Long(((Date) xObject).getTime())); break; case Types.NULL: break; default: System.err.println("Unknown data"); columnTypes[column] = Types.NULL; break; } } this.rows.add(newRow); } /// a kludge to make everything work when no rows returned if (this.rows.size() == 0) { ArrayList newRow = new ArrayList(); for (int column = 0; column < numberOfColumns; column++) { if (columnTypes[column] != Types.NULL) { newRow.add(new Integer(0)); } } this.rows.add(newRow); } /// Determine max and min values. if (this.rows.size() < 1) { this.maxValue = 0.0; this.minValue = 0.0; } else { ArrayList row = (ArrayList) this.rows.get(0); this.maxValue = Double.NEGATIVE_INFINITY; this.minValue = Double.POSITIVE_INFINITY; for (int rowNum = 0; rowNum < this.rows.size(); ++rowNum) { row = (ArrayList) this.rows.get(rowNum); for (int column = 1; column < numberOfColumns; column++) { Object testValue = row.get(column); if (testValue != null) { double test = ((Number) testValue).doubleValue(); if (test < this.minValue) { this.minValue = test; } if (test > this.maxValue) { this.maxValue = test; } } } } } fireDatasetChanged(new DatasetChangeInfo()); //TODO: fill in real change info } finally { if (resultSet != null) { try { resultSet.close(); } catch (Exception e) { // TODO: is this a good idea? } } if (statement != null) { try { statement.close(); } catch (Exception e) { // TODO: is this a good idea? } } } }
From source file:br.unicamp.cst.learning.QLearning.java
/** * Selects the best action for this state with probability "e", * and a random one with probability (1-e) * If a given state has no record of one or more actions, it will consider them as valued 0. * @param state//w w w . j av a2s .co m * @param e * @return selectedAction */ public String getAction(String state) {//TODO should improve this. It should consider all non explored actions as being equally 0 for all purposes // System.out.println("Inside get action"); String selectedAction = null; if (r.nextDouble() <= e) { //TODO Use boltzmann distribution here? // if(ql.getAction(stringState)!=null){ // action=ql.getAction(stringState);// //----- if (this.Q.get(state) != null) { ArrayList<String> actionsLeft = new ArrayList<String>(); actionsLeft.addAll(this.actionsList); HashMap<String, Double> actionsQ = this.Q.get(state); double bestQval = -Double.POSITIVE_INFINITY; Iterator<Entry<String, Double>> it = actionsQ.entrySet().iterator(); while (it.hasNext()) { Entry<String, Double> pairs = it.next(); double qVal = pairs.getValue(); String qAct = pairs.getKey(); if (qVal > bestQval) { bestQval = qVal; selectedAction = qAct; } actionsLeft.remove(qAct); } if ((bestQval < 0) && (actionsLeft.size() > 0)) { //this means we should randomly choose from the other actions; selectedAction = selectRandomAction(actionsLeft); } if (showDebugMessages) { System.out.println("Selected the best available action."); } } else { // System.out.println("Inside else null"); // selectedAction=null; selectedAction = selectRandomAction(actionsList); if (showDebugMessages) { System.out.println("Selected a random action because there was no available suggestion."); } } // }else{ // action=selectRandomAction(); // } } else { if (showDebugMessages) { System.out.println("Naturally selected a random action."); } selectedAction = selectRandomAction(actionsList); } return selectedAction; }
From source file:cc.osint.graphd.server.GraphCommandExecutor.java
protected String execute(Channel responseChannel, String clientId, ConcurrentHashMap<String, String> clientState, InboundChannelProcess inboundChannelProcess, String request, String cmd, String[] args) throws Exception { StringBuffer rsb = new StringBuffer(); // all operations require a db to be selected (via GraphServerProtocol.CMD_USE) if (null == clientState.get(GraphServerHandler.ST_DB)) { rsb.append(GraphServerProtocol.R_ERR); rsb.append(" REQUIRE_USE_DB"); return rsb.toString(); }//from w w w . j a va2s . co m Graph gr = graphRef.get(); if (null == gr) { GraphCommand killCmd = new GraphCommand(); killCmd.poisonPill = true; graphCommandQueue.clear(); graphCommandQueue.put(killCmd); return GraphServerProtocol.R_ERR + GraphServerProtocol.SPACE + " GRAPH_NO_LONGER_EXISTS :queue cleared & poison pill sent"; } /* * handle dynamic <<query>> expansion, replacement & execution, e.g. * * [...] <<_type:v _key:m*>> [...] * * TODO: take the responseChannel direct-send hack out of this and think about * how to either queue the commands (& add an "echo-batch-ok" or equiv to the tail to * signify end of the batched command execution) or move this up to the thread loop? * */ if (request.indexOf("<<") != -1 && request.indexOf(">>") != -1) { String query = request.substring(request.indexOf("<<") + 2, request.indexOf(">>")); String prefix = request.substring(0, request.indexOf("<<")).trim(); String suffix = request.substring(request.indexOf(">>") + 2).trim(); log.info("executing selector: [" + prefix + "] " + query + " [" + suffix + "]:"); List<JSONObject> selectorResults = gr.queryGraphIndex(query); for (JSONObject selectorResult : selectorResults) { String batchRequestKey = selectorResult.getString(Graph.KEY_FIELD); String batchRequest = prefix + " " + batchRequestKey + " " + suffix; String batchCmd; String[] batchArgs; if (batchRequest.indexOf(GraphServerProtocol.SPACE) != -1) { batchCmd = batchRequest.substring(0, batchRequest.indexOf(GraphServerProtocol.SPACE)).trim() .toLowerCase(); batchArgs = batchRequest.substring(batchRequest.indexOf(GraphServerProtocol.SPACE)).trim() .split(GraphServerProtocol.SPACE); } else { batchCmd = batchRequest.trim().toLowerCase(); batchArgs = new String[0]; } log.info("batchRequest: " + batchRequest); String batchCmdResponse = execute(responseChannel, clientId, clientState, inboundChannelProcess, batchRequest, batchCmd, batchArgs); String responseParts[] = batchCmdResponse.split(GraphServerProtocol.NL); for (String responsePart : responseParts) { if (responsePart.charAt(0) != '-') { responseChannel.write(responsePart.trim() + GraphServerProtocol.NL); } } } return GraphServerProtocol.R_BATCH_OK; } /* * graph commands * */ // CREATE VERTEX: cvert <key> <json> if (cmd.equals(GraphServerProtocol.CMD_CVERT)) { String key = args[0]; String json = request.substring(request.indexOf(GraphServerProtocol.SPACE + key) + (key.length() + 1)) .trim(); // remainder of line JSONObject jo = null; try { jo = new JSONObject(json); gr.addVertex(key, jo); rsb.append(GraphServerProtocol.R_OK); } catch (org.json.JSONException jsonEx) { jsonEx.printStackTrace(); rsb.append(GraphServerProtocol.R_ERR); rsb.append(" BAD_JSON "); rsb.append(jsonEx.getMessage()); } catch (Exception ex) { ex.printStackTrace(); rsb.append(GraphServerProtocol.R_ERR); rsb.append(GraphServerProtocol.SPACE); rsb.append(ex.getMessage()); } // CREATE EDGE: cedge <key> <vFromKey> <vToKey> <rel> <json> // OR: cedge <key> <vFromKey> <vToKey> <rel> <weight> <json> } else if (cmd.equals(GraphServerProtocol.CMD_CEDGE)) { String key = args[0]; String vFromKey = args[1]; String vToKey = args[2]; String rel = args[3]; double weight = 1.0; String json; if (args[4].charAt(0) == '{') { json = request.substring(request.indexOf(GraphServerProtocol.SPACE + rel) + (rel.length() + 1)) .trim(); // remainder of line } else { weight = Double.parseDouble(args[4]); json = request .substring(request.indexOf(GraphServerProtocol.SPACE + args[4]) + (args[4].length() + 1)) .trim(); // remainder of line } JSONObject jo = null; try { jo = new JSONObject(json); jo.put(Graph.EDGE_SOURCE_FIELD, vFromKey); jo.put(Graph.EDGE_TARGET_FIELD, vToKey); jo.put(Graph.WEIGHT_FIELD, weight); jo.put(Graph.RELATION_FIELD, rel); gr.addEdge(key, jo, vFromKey, vToKey, rel, weight); rsb.append(GraphServerProtocol.R_OK); } catch (org.json.JSONException jsonEx) { jsonEx.printStackTrace(); rsb.append(GraphServerProtocol.R_ERR); rsb.append(" BAD_JSON "); rsb.append(jsonEx.getMessage()); } catch (Exception ex) { ex.printStackTrace(); rsb.append(GraphServerProtocol.R_ERR); rsb.append(GraphServerProtocol.SPACE); rsb.append(ex.getMessage()); } // DELETE OBJECT: del <key> } else if (cmd.equals(GraphServerProtocol.CMD_DEL)) { String key = args[0]; JSONObject obj = gr.getGraphObject(key); if (null == obj) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { String _type = obj.getString(Graph.TYPE_FIELD); if (_type.equals(Graph.VERTEX_TYPE)) { JSONVertex jv = gr.getVertex(key); gr.removeVertex(jv); rsb.append(GraphServerProtocol.R_OK); } else if (_type.equals(Graph.EDGE_TYPE)) { JSONEdge je = gr.getEdge(key); gr.removeEdge(je); rsb.append(GraphServerProtocol.R_OK); } else { rsb.append(GraphServerProtocol.R_ERR); rsb.append(GraphServerProtocol.SPACE); rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE); } } // OBJECT EXISTS: exists <key> } else if (cmd.equals(GraphServerProtocol.CMD_EXISTS)) { String key = args[0]; JSONObject jo = new JSONObject(); jo.put("key", key); jo.put("exists", gr.exists(key)); rsb.append(jo); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); // GET OBJECT: get <key> } else if (cmd.equals(GraphServerProtocol.CMD_GET)) { String key = args[0]; JSONObject jo = gr.getGraphObject(key); if (jo == null) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { rsb.append(jo); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // QUERY GRAPH OBJECTS: q <query> } else if (cmd.equals(GraphServerProtocol.CMD_Q)) { String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "q " List<JSONObject> results = gr.queryGraphIndex(q); JSONArray ja = new JSONArray(); for (JSONObject jo : results) { ja.put(jo); } JSONObject res = new JSONObject(); res.put("results", ja); rsb.append(res); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); // DEPRECATED // QUERY PROCESSES: qp <query> } else if (cmd.equals(GraphServerProtocol.CMD_QP)) { String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "qp " /* List<JSONObject> results = gr.queryProcessIndex(q); JSONArray ja = new JSONArray(); for(JSONObject jo: results) { ja.put(jo); } JSONObject res = new JSONObject(); res.put("results", ja); rsb.append(res); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); */ // DIJKSTRA SHORTEST PATH: spath <from> <to> <radius> } else if (cmd.equals(GraphServerProtocol.CMD_SPATH)) { String vFromKey = args[0]; String vToKey = args[1]; double radius = Double.POSITIVE_INFINITY; if (args.length == 3) { radius = Double.parseDouble(args[2]); } JSONObject result = gr.getShortestPath(vFromKey, vToKey, radius); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // SET VERTEX/EDGE ATTRIBUTE: set <key> <attr> <value> } else if (cmd.equals(GraphServerProtocol.CMD_SET)) { String key = args[0]; String attr = args[1]; String val; if (args.length == 2) { // clear value val = null; } else { val = request .substring(request.indexOf(GraphServerProtocol.SPACE + args[1]) + (args[1].length() + 1)) .trim(); // remainder of line } if (attr.startsWith("_") && !attr.equals(Graph.WEIGHT_FIELD)) { rsb.append(GraphServerProtocol.R_ERR); rsb.append(" CANNOT_SET_RESERVED_PROPERTY"); } else { JSONObject obj = gr.getGraphObject(key); if (null == obj) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { String _type = obj.getString(Graph.TYPE_FIELD); if (_type.equals(Graph.VERTEX_TYPE)) { JSONVertex jv = gr.getVertex(key); if (null != val) { jv.put(attr, val); } else { jv.remove(attr); } gr.indexObject(key, _type, jv); rsb.append(GraphServerProtocol.R_OK); } else if (_type.equals(Graph.EDGE_TYPE)) { JSONEdge je = gr.getEdge(key); if (null != val) { je.put(attr, val); } else { je.remove(attr); } if (attr.equals(Graph.WEIGHT_FIELD)) { gr.setEdgeWeight(je, Double.parseDouble(val)); } gr.indexObject(key, _type, je.asJSONObject().getJSONObject(Graph.DATA_FIELD)); rsb.append(GraphServerProtocol.R_OK); } else { rsb.append(GraphServerProtocol.R_ERR); rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE); } } } // INCREASE EDGE WEIGHT: incw <edge_key> <amount> } else if (cmd.equals(GraphServerProtocol.CMD_INCW)) { String key = args[0]; double w_amt = Double.parseDouble(args[1]); JSONEdge je = gr.getEdge(key); if (null == je) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { double weight = gr.getEdgeWeight(je); weight += w_amt; gr.setEdgeWeight(je, weight); je.put(Graph.WEIGHT_FIELD, "" + weight); gr.indexObject(key, Graph.EDGE_TYPE, je.asJSONObject().getJSONObject(Graph.DATA_FIELD)); rsb.append(GraphServerProtocol.R_OK); } // DUMP INTERNAL REPRESENTATION OF VERTEX/EDGE: spy <key> } else if (cmd.equals(GraphServerProtocol.CMD_SPY)) { String key = args[0]; JSONObject obj = gr.getGraphObject(key); if (null == obj) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { String _type = obj.getString(Graph.TYPE_FIELD); if (_type.equals(Graph.EDGE_TYPE)) { JSONEdge je = gr.getEdge(key); if (null == je) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { rsb.append(je.asClientJSONObject().toString() + GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } } else if (_type.equals(Graph.VERTEX_TYPE)) { JSONVertex jv = gr.getVertex(key); if (null == jv) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { rsb.append(jv.toString() + GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } } else { rsb.append(GraphServerProtocol.R_ERR); rsb.append(GraphServerProtocol.R_UNKNOWN_OBJECT_TYPE); } } // K-SHORTEST-PATHS: kspath <from> <to> <k> <optional:maxHops> } else if (cmd.equals(GraphServerProtocol.CMD_KSPATH)) { String vFromKey = args[0]; String vToKey = args[1]; int k = Integer.parseInt(args[2]); int maxHops = 0; if (args.length > 3) { maxHops = Integer.parseInt(args[3]); } JSONObject result = gr.getKShortestPaths(vFromKey, vToKey, k, maxHops); rsb.append(result); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); // HAMILTONIAN CYCLE: hc } else if (cmd.equals(GraphServerProtocol.CMD_HC)) { List<JSONVertex> results = gr.getHamiltonianCycle(); if (null == results) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { JSONObject res = new JSONObject(); JSONArray cycle = new JSONArray(); for (JSONVertex jo : results) { cycle.put(jo); } res.put("cycle", cycle); rsb.append(res); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // EULERIAN CIRCUIT: ec } else if (cmd.equals(GraphServerProtocol.CMD_EC)) { List<JSONVertex> results = gr.getEulerianCircuit(); if (null == results) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { JSONObject res = new JSONObject(); JSONArray circuit = new JSONArray(); for (JSONVertex jo : results) { circuit.put(jo); } res.put("circuit", circuit); rsb.append(res); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // EDWARDS KARP MAXIMUM FLOW: ekmf <from> <to> } else if (cmd.equals(GraphServerProtocol.CMD_EKMF)) { String vSourceKey = args[0]; String vSinkKey = args[1]; JSONObject flowResult = gr.getEKMF(vSourceKey, vSinkKey); if (null == flowResult) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(flowResult.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // CHROMATIC NUMBER: cn } else if (cmd.equals(GraphServerProtocol.CMD_CN)) { JSONObject result = new JSONObject(); result.put("chromatic_number", gr.getChromaticNumber()); rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); // KRUSKAL'S MINIMUM SPANNING TREE: kmst } else if (cmd.equals(GraphServerProtocol.CMD_KMST)) { JSONObject result = gr.getKMST(); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // VERTEX COVER: GREEDY: vcg } else if (cmd.equals(GraphServerProtocol.CMD_VCG)) { JSONObject result = gr.getGreedyVertexCover(); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // VERTEX COVER: 2-APPROXIMATION: vc2a } else if (cmd.equals(GraphServerProtocol.CMD_VC2A)) { JSONObject result = gr.get2ApproximationVertexCover(); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // MAXIMALLY CONNECTED SET BY VERTEX: csetv <key> } else if (cmd.equals(GraphServerProtocol.CMD_CSETV)) { String key = args[0]; JSONVertex v = gr.getVertex(key); if (null == v) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { JSONObject result = gr.getConnectedSetByVertex(v); rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // ALL MAXIMALLY CONNECTED SETS: csets } else if (cmd.equals(GraphServerProtocol.CMD_CSETS)) { JSONObject result = gr.getConnectedSets(); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // CONNECTEDNESS TEST: iscon } else if (cmd.equals(GraphServerProtocol.CMD_ISCON)) { rsb.append("" + gr.isConnected()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); // UNDIRECTED PATH EXISTENCE TEST: upathex <from> <to> } else if (cmd.equals(GraphServerProtocol.CMD_UPATHEX)) { JSONVertex vFrom = gr.getVertex(args[0]); JSONVertex vTo = gr.getVertex(args[1]); if (null == vFrom || null == vTo) { rsb.append(GraphServerProtocol.R_NOT_FOUND); } else { rsb.append("" + gr.pathExists(vFrom, vTo)); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // FIND ALL MAXIMAL CLIQUES: Bron Kerosch Clique Finder } else if (cmd.equals(GraphServerProtocol.CMD_FAMC)) { JSONObject result = gr.getAllMaximalCliques(); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // FIND BIGGEST MAXIMAL CLIQUES: Bron Kerosch Clique Finder } else if (cmd.equals(GraphServerProtocol.CMD_FBMC)) { JSONObject result = gr.getBiggestMaximalCliques(); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } } else if (cmd.equals(GraphServerProtocol.CMD_ASPV)) { JSONObject result = gr.getAllShortestPathsFrom(gr.getVertex(args[0])); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } } else if (cmd.equals(GraphServerProtocol.CMD_GCYC)) { JSONObject result = gr.getGraphCycles(); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } } else if (cmd.equals(GraphServerProtocol.CMD_VCYC)) { JSONObject result = gr.getGraphCyclesContainingVertex(gr.getVertex(args[0])); if (null == result) { rsb.append(GraphServerProtocol.R_NOT_EXIST); } else { rsb.append(result.toString()); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } /* * TRAVERSAL */ // custom traversal code // TRAV <start_vertex> <traversal_type> ( - | <udf_key> ) [channel] // // <traversal_type> values: // breadth_first depth_first closest_first topological // // the following <traversal_type> may be specified with a suffix // denoting a maximum radius from <start_vertex>: // closest_first[:radius] // // if parameter 3 is "-", events will be sent to argument 4 [channel] // if parameter 3 is not "-", it will be interpreted as a server-side udf // that implements TraversalEvent functions // // NOTE: topological <traversal_type> ignores the value of <start_vertex> // but some value must be specified // } else if (cmd.equals(GraphServerProtocol.CMD_TRAV)) { String startVertex = args[0]; String traversalType = args[1]; String udfKey = args[2]; String channel = null; JSONArray pipelineEventPassList = null; boolean isPipelined = false; if (udfKey.equals("-")) { isPipelined = true; channel = args[3]; if (args.length == 5) { String peplStr = request.substring( request.lastIndexOf(GraphServerProtocol.SPACE + channel) + (channel.length() + 1)) .trim(); // remainder of line pipelineEventPassList = new JSONArray(peplStr); } } double radius = 0.0; if (traversalType.indexOf(":") != -1) { radius = Double.parseDouble(traversalType.substring(traversalType.indexOf(":") + 1)); traversalType = traversalType.substring(0, traversalType.indexOf(":")); } JSONVertex v = gr.getVertex(startVertex); if (null == v) { rsb.append(GraphServerProtocol.R_ERR); rsb.append(GraphServerProtocol.SPACE); rsb.append("startVertex does not exist"); } else { if (isPipelined) { gr.pipelinedTraversal(traversalType, v, channel, radius, pipelineEventPassList); rsb.append(GraphServerProtocol.R_OK); } else { gr.scriptedTraversal(traversalType, v, udfKey, radius); rsb.append(GraphServerProtocol.R_OK); } } /* * USER-DEFINED FUNCTIONS */ // DEFINE A UDF } else if (cmd.equals(GraphServerProtocol.CMD_DEFINE_UDF)) { String udfKey = args[0]; String udfType = args[1]; String udfURL = args[2]; gr.defineUDF(udfKey, udfType, udfURL); rsb.append(GraphServerProtocol.R_OK); /* * ANONYMOUS BLOCKS */ // block_begin <block_key> } else if (cmd.equals(GraphServerProtocol.CMD_BLOCK_BEGIN)) { throw new Exception("not implemented"); // block_end <block_key> } else if (cmd.equals(GraphServerProtocol.CMD_BLOCK_END)) { throw new Exception("not implemented"); // block_get <block_key> } else if (cmd.equals(GraphServerProtocol.CMD_BLOCK_GET)) { throw new Exception("not implemented"); // block_remove <block_key> } else if (cmd.equals(GraphServerProtocol.CMD_BLOCK_REMOVE)) { throw new Exception("not implemented"); /* * SIMULATION */ // query simulation index: qsim <query> e.g., _type:udf udf_name:test* } else if (cmd.equals(GraphServerProtocol.CMD_QSIM)) { String q = request.substring(request.indexOf(GraphServerProtocol.SPACE)).trim(); // remainder of line past "q " List<JSONObject> results = gr.querySimIndex(q); JSONArray ja = new JSONArray(); for (JSONObject jo : results) { ja.put(jo); } JSONObject res = new JSONObject(); res.put("results", ja); rsb.append(res); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); // START A UDF-BACKED PROCESS } else if (cmd.equals(GraphServerProtocol.CMD_SPROC)) { String objKey = args[0]; String udfKey = args[1]; String processName; if (args.length == 3) { processName = args[2]; } else { processName = objKey + "-" + udfKey; } gr.startProcess(objKey, udfKey, processName); rsb.append(GraphServerProtocol.R_OK); // EMIT A MESSAGE TO A RUNNING SIMULATION PROCESS: emit <key> <process_name> <json_msg> } else if (cmd.equals(GraphServerProtocol.CMD_EMIT)) { String key = args[0]; String processName = args[1]; String json = request .substring( request.indexOf(GraphServerProtocol.SPACE + processName) + (processName.length() + 1)) .trim(); // remainder of line JSONObject jo = null; jo = new JSONObject(json); gr.emit(key, processName, jo); rsb.append(GraphServerProtocol.R_OK); /* * CHANNEL MESSAGING */ // create a channel: cchan <channel_name> } else if (cmd.equals(GraphServerProtocol.CMD_CCHAN)) { String channelName = args[0]; String pid = gr.createEndpointChannel(channelName); if (null == pid) { rsb.append(GraphServerProtocol.R_ALREADY_EXIST); } else { rsb.append(pid); rsb.append(GraphServerProtocol.NL); rsb.append(GraphServerProtocol.R_OK); } // publish a message to a channel: publish <channel_name> <json_msg> } else if (cmd.equals(GraphServerProtocol.CMD_PUBLISH)) { String channelName = args[0]; String json = request .substring( request.indexOf(GraphServerProtocol.SPACE + channelName) + (channelName.length() + 1)) .trim(); // remainder of line gr.publishToEndpointByName(channelName, new JSONObject(json)); rsb.append(GraphServerProtocol.R_OK); // subscribe to a channel: subscribe <channel_name> } else if (cmd.equals(GraphServerProtocol.CMD_SUBSCRIBE)) { String channelName = args[0]; /* log.info("channelName = " + channelName); log.info("inboundChannelProcess = " + inboundChannelProcess); log.info("inboundChannelProcess = " + inboundChannelProcess); log.info("inboundChannelProcess.getChannel() = " + inboundChannelProcess.getChannel()); */ gr.subscribeToEndpointByName(channelName, inboundChannelProcess.getChannel()); rsb.append(GraphServerProtocol.R_OK); // unsubscribe from a channel: unsubscribe <channel_name> } else if (cmd.equals(GraphServerProtocol.CMD_UNSUBSCRIBE)) { String channelName = args[0]; gr.unsubscribeToEndpointByName(channelName, inboundChannelProcess.getChannel()); rsb.append(GraphServerProtocol.R_OK); } else { log.info("GraphServerProtocol.R_UNK: " + cmd); rsb.append(GraphServerProtocol.R_UNK); rsb.append(GraphServerProtocol.SPACE); rsb.append(cmd); } return rsb.toString(); }