List of usage examples for java.lang Double isNaN
public static boolean isNaN(double v)
From source file:edu.cudenver.bios.power.glmm.GLMMTestUnirepHuynhFeldt.java
/** * Calculate the Huynh-Feldt epsilon to correct for violations * of sphericity//from w w w .j a va2 s . co m */ @Override protected void calculateEpsilon() { super.calculateEpsilon(); double b = rankU; if (this.epsilonMethod == UnivariateEpsilonApproximation.MULLER_BARTON_APPROX) { // calculate the expected value of the epsilon estimate // E[h(lambda)] = h(lambda) + g1 / (N - r) // h(lambda) = h1(lambda) / (b*h2(lambda) // see Muller, Barton (1989) for details double h1 = totalN * sumLambda * sumLambda - 2 * sumLambdaSquared; double h2 = (totalN - rank) * sumLambdaSquared - (sumLambda * sumLambda); double g1 = 0; for (int i = 0; i < distinctSigmaStarEigenValues.size(); i++) { EigenValueMultiplicityPair evmI = distinctSigmaStarEigenValues.get(i); // derivatives of sub-equations comprising epsilon estimator double h1firstDerivative = (2 * totalN * sumLambda) - (4 * evmI.eigenValue); double h1secondDerivative = 2 * totalN - 4; double h2firstDerivative = (2 * (totalN - rank) * evmI.eigenValue) - (2 * sumLambda); double h2secondDerivative = 2 * (totalN - rank) - 2; // derivatives of estimate of epsilon double firstDerivative = ((h1firstDerivative) - ((h1 * h2firstDerivative) / h2)) / (h2 * b); double secondDerivative = (h1secondDerivative - ((2 * h1firstDerivative * h2firstDerivative) / (h2)) + (2 * h1 * h2firstDerivative * h2firstDerivative) / (h2 * h2) - (h1 * h2secondDerivative) / (h2)) / (h2 * b); // accumulate the first term of g1 (sum over distinct eigen vals of 1st derivative * eigen val ^2 * multiplicity) g1 += secondDerivative * evmI.eigenValue * evmI.eigenValue * evmI.multiplicity; // loop over elements not equal to current for (int j = 0; j < distinctSigmaStarEigenValues.size(); j++) { if (i != j) { EigenValueMultiplicityPair evmJ = distinctSigmaStarEigenValues.get(j); // accumulate second term of g1 g1 += ((firstDerivative * evmI.eigenValue * evmI.multiplicity * evmJ.eigenValue * evmJ.multiplicity) / (evmI.eigenValue - evmJ.eigenValue)); } } } expectedEpsilon = (totalN * b * epsilonD - 2) / (b * (totalN - rank - b * epsilonD)) + g1 / (totalN - rank); } else { double sum = 0; for (int i = 0; i < sigmaStarEigenValues.length; i++) { for (int j = 0; j < sigmaStarEigenValues.length; j++) { sum += sigmaStarEigenValues[i] * sigmaStarEigenValues[j]; } } double nu = totalN - rank; double expT1 = (2 * nu * sumLambdaSquared) + (nu * nu * sumLambda * sumLambda); double expT2 = ((nu * (nu + 1)) * sumLambdaSquared) + (nu * sum); double numerator = (1 / b) * (((nu + 1) * expT1) - 2 * expT2); double denominator = (nu * expT2) - expT1; expectedEpsilon = numerator / denominator; } // ensure that expected value is within bounds 1/b to 1 if (!Double.isNaN(expectedEpsilon)) { if (expectedEpsilon < 1 / b) { expectedEpsilon = 1 / b; } else if (expectedEpsilon > 1) { expectedEpsilon = 1; } } }
From source file:org.mwc.cmap.grideditor.chart.RendererWithDynamicFeedback.java
/** * @see drawSecondaryPass/* w w w. j a v a 2s.c om*/ */ private void drawFeedBackNode(final Graphics2D g2, final XYPlot plot, final XYDataset dataset, final int pass, // final int series, final int item, final ValueAxis domainAxis, final Rectangle2D dataArea, final ValueAxis rangeAxis, // final CrosshairState crosshairState, final EntityCollection entities) { // get the data point... final double x1 = myFeedBackValue != null ? myFeedBackValue.x : dataset.getXValue(series, item); final double y1 = myFeedBackValue != null ? myFeedBackValue.y : dataset.getYValue(series, item); if (Double.isNaN(y1) || Double.isNaN(x1)) { return; } final PlotOrientation orientation = plot.getOrientation(); final RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); final RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); final double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); final double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); if (getItemShapeVisible(series, item)) { Shape shape = getItemShape(series, item); if (orientation == PlotOrientation.HORIZONTAL) { shape = ShapeUtilities.createTranslatedShape(shape, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { shape = ShapeUtilities.createTranslatedShape(shape, transX1, transY1); } if (shape.intersects(dataArea)) { g2.setPaint(getFeedbackNodePaint()); g2.fill(shape); } } double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } drawFeedbackItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0)); }
From source file:no.met.jtimeseries.chart.XYSplineRenderer.java
/** * Draws the item (first pass). This method draws the lines * connecting the items. Instead of drawing separate lines, * a GeneralPath is constructed and drawn at the end of * the series painting./*from ww w. j a v a2s . c o m*/ * * @param g2 the graphics device. * @param state the renderer state. * @param plot the plot (can be used to obtain standard color information * etc). * @param dataset the dataset. * @param pass the pass. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataArea the area within which the data is being drawn. */ @Override protected void drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); // get the data points double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); // collect points if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) { ControlPoint p = new ControlPoint( plot.getOrientation() == PlotOrientation.HORIZONTAL ? (float) transY1 : (float) transX1, plot.getOrientation() == PlotOrientation.HORIZONTAL ? (float) transX1 : (float) transY1); if (!this.points.contains(p)) { this.points.add(p); } } if (item == dataset.getItemCount(series) - 1) { State s = (State) state; // construct path if (this.points.size() > 1) { // we need at least two points to draw something ControlPoint cp0 = this.points.get(0); s.seriesPath.moveTo(cp0.x, cp0.y); if (this.points.size() == 2) { // we need at least 3 points to spline. Draw simple line // for two points ControlPoint cp1 = this.points.get(1); s.seriesPath.lineTo(cp1.x, cp1.y); } else { // construct spline int np = this.points.size(); // number of points float[] d = new float[np]; // Newton form coefficients float[] x = new float[np]; // x-coordinates of nodes float y; float t; float oldy = 0; float oldt = 0; float[] a = new float[np]; float t1; float t2; float[] h = new float[np]; for (int i = 0; i < np; i++) { ControlPoint cpi = this.points.get(i); x[i] = cpi.x; d[i] = cpi.y; } for (int i = 1; i <= np - 1; i++) { h[i] = x[i] - x[i - 1]; } float[] sub = new float[np - 1]; float[] diag = new float[np - 1]; float[] sup = new float[np - 1]; for (int i = 1; i <= np - 2; i++) { diag[i] = (h[i] + h[i + 1]) / 3; sup[i] = h[i + 1] / 6; sub[i] = h[i] / 6; a[i] = (d[i + 1] - d[i]) / h[i + 1] - (d[i] - d[i - 1]) / h[i]; } solveTridiag(sub, diag, sup, a, np - 2); // note that a[0]=a[np-1]=0 // draw oldt = x[0]; oldy = d[0]; s.seriesPath.moveTo(oldt, oldy); for (int i = 1; i <= np - 1; i++) { // loop over intervals between nodes for (int j = 1; j <= this.precision; j++) { t1 = (h[i] * j) / this.precision; t2 = h[i] - t1; y = ((-a[i - 1] / 6 * (t2 + h[i]) * t1 + d[i - 1]) * t2 + (-a[i] / 6 * (t1 + h[i]) * t2 + d[i]) * t1) / h[i]; t = x[i - 1] + t1; s.seriesPath.lineTo(t, y); oldt = t; oldy = y; } } } // draw path drawFirstPassShape(g2, pass, series, item, s.seriesPath); } // reset points vector this.points = new Vector<ControlPoint>(); } }
From source file:org.talend.dataprofiler.chart.util.TopChartFactory.java
/** * Creates a bubble chart with default settings. The chart is composed of an {@link XYPlot}, with a {@link NumberAxis} for the * domain axis, a {@link NumberAxis} for the range axis, and an {@link XYBubbleRenderer} to draw the data items. * /*w w w. jav a2s .c o m*/ * This method is copied from * {@link org.jfree.chart.ChartFactory#createBubbleChart(String, String, String, XYZDataset, PlotOrientation, boolean, boolean, boolean)} * * @param title the chart title (<code>null</code> permitted). * @param xAxisLabel a label for the X-axis (<code>null</code> permitted). * @param yAxisLabel a label for the Y-axis (<code>null</code> permitted). * @param dataset the dataset for the chart (<code>null</code> permitted). * @param orientation the orientation (horizontal or vertical) (<code>null</code> NOT permitted). * @param legend a flag specifying whether or not a legend is required. * @param tooltips configure chart to generate tool tips? * @param urls configure chart to generate URLs? * * @return A bubble chart. */ public static JFreeChart createBubbleChart(String title, String xAxisLabel, String yAxisLabel, XYZDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) { if (orientation == null) { throw new IllegalArgumentException(Messages.getString("TopChartFactory.argument")); //$NON-NLS-1$ } NumberAxis xAxis = new NumberAxis(xAxisLabel); xAxis.setAutoRangeIncludesZero(false); NumberAxis yAxis = new NumberAxis(yAxisLabel); yAxis.setAutoRangeIncludesZero(false); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, null); XYItemRenderer renderer = new XYBubbleRenderer(XYBubbleRenderer.SCALE_ON_RANGE_AXIS) { @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // return straight away if the item is not visible if (!getItemVisible(series, item)) { return; } PlotOrientation orientation = plot.getOrientation(); // get the data point... double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); double z = Double.NaN; if (dataset instanceof XYZDataset) { XYZDataset xyzData = (XYZDataset) dataset; z = xyzData.getZValue(series, item); } if (!Double.isNaN(z)) { RectangleEdge domainAxisLocation = plot.getDomainAxisEdge(); RectangleEdge rangeAxisLocation = plot.getRangeAxisEdge(); double transX = domainAxis.valueToJava2D(x, dataArea, domainAxisLocation); double transY = rangeAxis.valueToJava2D(y, dataArea, rangeAxisLocation); double transDomain = 0.0; double transRange = 0.0; double zero; // MOD scorreia +2L avoid points: minimal size of circle must be 1 // z = z * transX + 1; // ADD xqliu 2009-07-06 bug 8035 double zSize = getBubbleSize(z); // calculate the multiple of bubble's default size z = 0; // use bubble's default size // ~ switch (getScaleType()) { case SCALE_ON_DOMAIN_AXIS: zero = domainAxis.valueToJava2D(0.0, dataArea, domainAxisLocation); transDomain = domainAxis.valueToJava2D(z, dataArea, domainAxisLocation) - zero; transRange = transDomain; break; case SCALE_ON_RANGE_AXIS: zero = rangeAxis.valueToJava2D(0.0, dataArea, rangeAxisLocation); transRange = zero - rangeAxis.valueToJava2D(z, dataArea, rangeAxisLocation); transDomain = transRange; break; default: double zero1 = domainAxis.valueToJava2D(0.0, dataArea, domainAxisLocation); double zero2 = rangeAxis.valueToJava2D(0.0, dataArea, rangeAxisLocation); transDomain = domainAxis.valueToJava2D(z, dataArea, domainAxisLocation) - zero1; transRange = zero2 - rangeAxis.valueToJava2D(z, dataArea, rangeAxisLocation); } transDomain = Math.abs(transDomain); transRange = Math.abs(transRange); // MODSCA 2008-11-27 enlarge ellipse by diag% of the total diagonal double diag = Math.sqrt(dataArea.getHeight() * dataArea.getHeight() + dataArea.getWidth() * dataArea.getWidth()); transDomain += diag / 100; transRange += diag / 100; Ellipse2D circle = null; // ADD xqliu 2009-07-06 bug 8035 transDomain *= zSize; transRange *= zSize; // ~ if (orientation == PlotOrientation.VERTICAL) { circle = new Ellipse2D.Double(transX - transDomain / 2.0, transY - transRange / 2.0, transDomain, transRange); } else if (orientation == PlotOrientation.HORIZONTAL) { circle = new Ellipse2D.Double(transY - transRange / 2.0, transX - transDomain / 2.0, transRange, transDomain); } g2.setPaint(getItemPaint(series, item)); g2.fill(circle); g2.setStroke(getItemOutlineStroke(series, item)); g2.setPaint(getItemOutlinePaint(series, item)); g2.draw(circle); if (isItemLabelVisible(series, item)) { if (orientation == PlotOrientation.VERTICAL) { drawItemLabel(g2, orientation, dataset, series, item, transX, transY, false); } else if (orientation == PlotOrientation.HORIZONTAL) { drawItemLabel(g2, orientation, dataset, series, item, transY, transX, false); } } // add an entity if this info is being collected EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); if (entities != null && circle.intersects(dataArea)) { addEntity(entities, circle, dataset, series, item, circle.getCenterX(), circle.getCenterY()); } } int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY, orientation); } } /** * DOC xqliu : calculate the size of bubble. for bug 8035 2009-07-06. * * @param z multiple of bubble's default size * @return */ private double getBubbleSize(double z) { if (z > 0 && z <= 10) { return 2; } else if (z > 10 && z <= 100) { return 3; } else if (z > 100) { return 4; } return 1; } }; if (tooltips) { renderer.setBaseToolTipGenerator(new StandardXYZToolTipGenerator()); } if (urls) { renderer.setURLGenerator(new StandardXYZURLGenerator()); } plot.setRenderer(renderer); plot.setOrientation(orientation); JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend); return chart; }
From source file:com.joptimizer.util.MPSParserNetlibTest.java
/** * Tests the parsing of a netlib problem. *//* w w w .j a v a 2 s . c om*/ public void xxxtestSingleNetlib() throws Exception { log.debug("testSingleNetlib"); //String problemName = "afiro"; //String problemName = "afiroPresolved"; //String problemName = "adlittle"; //String problemName = "kb2"; //String problemName = "sc50a"; //String problemName = "sc50b"; //String problemName = "blend"; //String problemName = "scorpion"; //String problemName = "recipe"; //String problemName = "recipePresolved"; //String problemName = "sctap1"; //String problemName = "fit1d"; //String problemName = "israel"; //String problemName = "grow15"; //String problemName = "etamacro"; //String problemName = "pilot"; //String problemName = "pilot4"; //String problemName = "osa-14"; //String problemName = "brandyPresolved"; String problemName = "maros"; File f = Utils.getClasspathResourceAsFile("lp" + File.separator + "netlib" + File.separator + problemName + File.separator + problemName + ".mps"); MPSParser mpsParser = new MPSParser(); mpsParser.parse(f); Properties expectedSolProps = null; try { //this is the solution of the mps problem given by Mathematica expectedSolProps = load(Utils.getClasspathResourceAsFile( "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "sol.txt")); } catch (Exception e) { } log.debug("name: " + mpsParser.getName()); log.debug("n : " + mpsParser.getN()); log.debug("meq : " + mpsParser.getMeq()); log.debug("mieq: " + mpsParser.getMieq()); log.debug("meq+mieq: " + (mpsParser.getMeq() + mpsParser.getMieq())); List<String> variablesNames = mpsParser.getVariablesNames(); log.debug("x: " + ArrayUtils.toString(variablesNames)); // log.debug("c: " + ArrayUtils.toString(p.getC())); // log.debug("G: " + ArrayUtils.toString(p.getG())); // log.debug("h: " + ArrayUtils.toString(p.getH())); // log.debug("A: " + ArrayUtils.toString(p.getA())); // log.debug("b: " + ArrayUtils.toString(p.getB())); // log.debug("lb:" + ArrayUtils.toString(p.getLb())); // log.debug("ub:" + ArrayUtils.toString(p.getUb())); //check consistency: if the problem was correctly parsed, the expectedSol must be its solution double delta = 1.e-7; if (expectedSolProps != null) { //key = variable name //value = sol value assertEquals(expectedSolProps.size(), variablesNames.size()); RealVector expectedSol = new ArrayRealVector(variablesNames.size()); for (int i = 0; i < variablesNames.size(); i++) { expectedSol.setEntry(i, Double.parseDouble(expectedSolProps.getProperty(variablesNames.get(i)))); } log.debug("expectedSol: " + ArrayUtils.toString(expectedSol.toArray())); //check objective function value Map<String, LPNetlibProblem> problemsMap = LPNetlibProblem.loadAllProblems(); LPNetlibProblem problem = problemsMap.get(problemName); RealVector c = new ArrayRealVector(mpsParser.getC().toArray()); double value = c.dotProduct(expectedSol); log.debug("optimalValue: " + problem.optimalValue); log.debug("value : " + value); assertEquals(problem.optimalValue, value, delta); //check G.x < h if (mpsParser.getG() != null) { RealMatrix G = new Array2DRowRealMatrix(mpsParser.getG().toArray()); RealVector h = new ArrayRealVector(mpsParser.getH().toArray()); RealVector Gxh = G.operate(expectedSol).subtract(h); double maxGxh = -Double.MAX_VALUE; for (int i = 0; i < Gxh.getDimension(); i++) { //log.debug(i); maxGxh = Math.max(maxGxh, Gxh.getEntry(i)); assertTrue(Gxh.getEntry(i) <= 0); } log.debug("max(G.x - h): " + maxGxh); } //check A.x = b if (mpsParser.getA() != null) { RealMatrix A = new Array2DRowRealMatrix(mpsParser.getA().toArray()); RealVector b = new ArrayRealVector(mpsParser.getB().toArray()); RealVector Axb = A.operate(expectedSol).subtract(b); double norm = Axb.getNorm(); log.debug("||A.x -b||: " + norm); assertEquals(0., norm, delta * mpsParser.getN());//some more tolerance } //check upper and lower bounds for (int i = 0; i < mpsParser.getLb().size(); i++) { double di = Double.isNaN(mpsParser.getLb().getQuick(i)) ? -Double.MAX_VALUE : mpsParser.getLb().getQuick(i); assertTrue(di <= expectedSol.getEntry(i)); } for (int i = 0; i < mpsParser.getUb().size(); i++) { double di = Double.isNaN(mpsParser.getUb().getQuick(i)) ? Double.MAX_VALUE : mpsParser.getUb().getQuick(i); assertTrue(di >= expectedSol.getEntry(i)); } } Utils.writeDoubleArrayToFile(mpsParser.getC().toArray(), "target" + File.separator + "c.txt"); Utils.writeDoubleMatrixToFile(mpsParser.getG().toArray(), "target" + File.separator + "G.csv"); Utils.writeDoubleArrayToFile(mpsParser.getH().toArray(), "target" + File.separator + "h.txt"); Utils.writeDoubleMatrixToFile(mpsParser.getA().toArray(), "target" + File.separator + "A.csv"); Utils.writeDoubleArrayToFile(mpsParser.getB().toArray(), "target" + File.separator + "b.txt"); Utils.writeDoubleArrayToFile(mpsParser.getLb().toArray(), "target" + File.separator + "lb.txt"); Utils.writeDoubleArrayToFile(mpsParser.getUb().toArray(), "target" + File.separator + "ub.txt"); }
From source file:lirmm.inria.fr.math.OpenLongToDoubleHashMapTest.java
@Test public void testRemoveFromEmpty() { OpenLongToDoubleHashMap map = new OpenLongToDoubleHashMap(); Assert.assertTrue(Double.isNaN(map.remove(50))); }
From source file:gov.sandia.umf.platform.ui.jobs.Raster.java
public JFreeChart createChart(final XYDataset dataset) { final JFreeChart chart = ChartFactory.createScatterPlot(null, // chart title null, // x axis label null, // y axis label dataset, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips false // urls );//from w w w . ja v a 2s . c o m chart.setBackgroundPaint(Color.white); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.white); plot.setRangeGridlinePaint(Color.lightGray); plot.setDomainPannable(true); plot.setRangePannable(true); plot.setRenderer(new XYDotRenderer() { public void drawItem(java.awt.Graphics2D g2, XYItemRendererState state, java.awt.geom.Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // Copied from org.jfree.chart.renderer.xy.XYDotRenderer.java and modified. // This would only need to be a couple of lines if they authors of jfreechart had not made dotWidth and dotHeight private members. // Yet another example of textbook OO programming gone awry. (Can anyone hear me scream?) if (!getItemVisible(series, item)) return; int dotWidth = 1; double rasterLines = rangeAxis.getRange().getLength(); int pixels = g2.getClipBounds().height; double height = pixels / rasterLines; if (height > 10) height -= 2; else if (height > 2) height -= 1; int dotHeight = (int) Math.min(20, Math.max(1, Math.floor(height))); double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); if (Double.isNaN(y)) return; double adjx = (dotWidth - 1) / 2.0; double adjy = (dotHeight - 1) / 2.0; RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX = domainAxis.valueToJava2D(x, dataArea, xAxisLocation) - adjx; double transY = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation) - adjy; g2.setPaint(Color.black); PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) g2.fillRect((int) transY, (int) transX, dotHeight, dotWidth); else g2.fillRect((int) transX, (int) transY, dotWidth, dotHeight); int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x, y, domainAxisIndex, rangeAxisIndex, transX, transY, orientation); } }); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); // Integer units only return chart; }
From source file:com.opengamma.analytics.math.interpolation.MonotoneConvexSplineInterpolator.java
@Override public double interpolate(final double[] xValues, final double[] yValues, final double x) { final PiecewisePolynomialResult result = interpolate(xValues, yValues); final DoubleMatrix2D coefsMatrixIntegrate = result.getCoefMatrix(); final int nKnots = coefsMatrixIntegrate.getNumberOfRows() + 1; final double[] knots = result.getKnots().getData(); int indicator = 0; if (x <= knots[1]) { indicator = 0;// w ww .j ava 2 s. c o m } else { for (int i = 1; i < nKnots - 1; ++i) { if (knots[i] < x) { indicator = i; } } } final double[] coefs = coefsMatrixIntegrate.getRowVector(indicator).getData(); final double res = getValue(coefs, x, knots[indicator]); ArgumentChecker.isFalse(Double.isInfinite(res), "Too large/small data values or xKey"); ArgumentChecker.isFalse(Double.isNaN(res), "Too large/small data values or xKey"); return res; }
From source file:com.itemanalysis.jmetrik.stats.itemanalysis.ItemAnalysisOutputFile.java
public File saveOutput(LinkedHashMap<VariableName, ClassicalItem> itemTreeMap, boolean allCategories, boolean addDIndex) throws IOException { this.outputfile = getUniqueFile(outputfile); int nItems = itemTreeMap.size(); int maxCategory = 0; ClassicalItem item = null;/* w ww . ja va 2 s . c om*/ for (VariableName v : itemTreeMap.keySet()) { item = itemTreeMap.get(v); maxCategory = Math.max(maxCategory, item.numberOfCategories()); } int totalColumns = 4 + 3 * maxCategory; LinkedHashMap<VariableName, VariableAttributes> variableAttributeMap = new LinkedHashMap<VariableName, VariableAttributes>(); VariableAttributes nameAtt = new VariableAttributes(new VariableName("name"), new VariableLabel("Item Name"), DataType.STRING, 0); VariableAttributes difficultyAtt = new VariableAttributes(new VariableName("difficulty"), new VariableLabel("Item Difficulty"), DataType.DOUBLE, 1); VariableAttributes stdDevAtt = new VariableAttributes(new VariableName("stdev"), new VariableLabel("Item Standard Deviation"), DataType.DOUBLE, 2); VariableAttributes discrimAtt = new VariableAttributes(new VariableName("discrimination"), new VariableLabel("Item Discrimination"), DataType.DOUBLE, 3); variableAttributeMap.put(nameAtt.getName(), nameAtt); variableAttributeMap.put(difficultyAtt.getName(), difficultyAtt); variableAttributeMap.put(stdDevAtt.getName(), stdDevAtt); variableAttributeMap.put(discrimAtt.getName(), discrimAtt); VariableAttributes lower = null; VariableAttributes upper = null; VariableAttributes dIndex = null; if (addDIndex) { lower = new VariableAttributes(new VariableName("lower"), new VariableLabel("Difficulty for lower 27%"), DataType.DOUBLE, 4); upper = new VariableAttributes(new VariableName("upper"), new VariableLabel("Difficulty for upper 27%"), DataType.DOUBLE, 5); dIndex = new VariableAttributes(new VariableName("D_index"), new VariableLabel("Discrimination index"), DataType.DOUBLE, 6); variableAttributeMap.put(lower.getName(), lower); variableAttributeMap.put(upper.getName(), upper); variableAttributeMap.put(dIndex.getName(), dIndex); } VariableAttributes vPropAtt = null; VariableAttributes vSDAtt = null; VariableAttributes vCorAtt = null; int colNumber = 4; if (addDIndex) colNumber = 7; if (allCategories) { for (int k = 0; k < maxCategory; k++) { vPropAtt = new VariableAttributes(new VariableName("prop" + (k + 1)), new VariableLabel("Proportion endorsing option " + (k + 1)), DataType.DOUBLE, colNumber++); vSDAtt = new VariableAttributes(new VariableName("stdev" + (k + 1)), new VariableLabel("Std. Dev. for option " + (k + 1)), DataType.DOUBLE, colNumber++); vCorAtt = new VariableAttributes(new VariableName("cor" + (k + 1)), new VariableLabel("Distractor-total correlation for option " + (k + 1)), DataType.DOUBLE, colNumber++); variableAttributeMap.put(vPropAtt.getName(), vPropAtt); variableAttributeMap.put(vSDAtt.getName(), vSDAtt); variableAttributeMap.put(vCorAtt.getName(), vCorAtt); } } int n = 0; try (JmetrikFileWriter writer = new JmetrikFileWriter(outputfile, variableAttributeMap)) { writer.openConnection(); writer.writeHeader(nItems); int index = 0; double df = 0, sd = 0, ds = 0, dL = 0, dU = 0, D = 0; for (VariableName v : itemTreeMap.keySet()) { index = 0; item = itemTreeMap.get(v); writer.writeValue(nameAtt.getName(), item.getName().toString()); df = item.getDifficulty(); if (Double.isNaN(df)) { writer.writeValue(difficultyAtt.getName(), ""); } else { writer.writeValue(difficultyAtt.getName(), df); } index++; sd = item.getStdDev(); if (Double.isNaN(sd)) { writer.writeValue(stdDevAtt.getName(), ""); } else { writer.writeValue(stdDevAtt.getName(), sd); } index++; ds = item.getDiscrimination(); if (Double.isNaN(ds)) { writer.writeValue(discrimAtt.getName(), ""); } else { writer.writeValue(discrimAtt.getName(), ds); } index++; if (addDIndex) { dL = item.getDindexLower(); if (Double.isNaN(dL)) { writer.writeValue(lower.getName(), ""); } else { writer.writeValue(lower.getName(), dL); } index++; dU = item.getDindexUpper(); if (Double.isNaN(dU)) { writer.writeValue(upper.getName(), ""); } else { writer.writeValue(upper.getName(), dU); } index++; D = dU - dL; if (Double.isNaN(D)) { writer.writeValue(dIndex.getName(), ""); } else { writer.writeValue(dIndex.getName(), D); } index++; } if (allCategories) { Object temp; Iterator<Object> iter = item.categoryIterator(); int catIndex = 1; VariableName catProp = null; VariableName catStDev = null; VariableName catDisc = null; while (iter.hasNext()) { temp = iter.next(); catProp = new VariableName("prop" + catIndex); catStDev = new VariableName("stdev" + catIndex); catDisc = new VariableName("cor" + catIndex); vPropAtt = variableAttributeMap.get(catProp); vSDAtt = variableAttributeMap.get(catStDev); vCorAtt = variableAttributeMap.get(catDisc); //category difficulty df = item.getDifficultyAt(temp); if (Double.isNaN(df)) { writer.writeValue(vPropAtt.getName(), ""); } else { writer.writeValue(vPropAtt.getName(), df); } index++; //category sd sd = item.getStdDevAt(temp); if (Double.isNaN(sd)) { writer.writeValue(vSDAtt.getName(), ""); } else { writer.writeValue(vSDAtt.getName(), sd); } index++; //category discrimination ds = item.getDiscriminationAt(temp); if (Double.isNaN(ds)) { writer.writeValue(vCorAtt.getName(), ""); } else { writer.writeValue(vCorAtt.getName(), ds); } index++; catIndex++; } //end loop over categories //index should be equal to totalColumns // if not, add null values to remaining columns // while(index<totalColumns-1){ // writer.writeValue(index++, ""); // } } writer.updateRow(); } //end loop over items } return outputfile; }
From source file:edu.oregonstate.eecs.mcplan.ml.ClusterContingencyTable.java
public double adjustedMutualInformation_max() { if (C == 1 && R == 1) { return 1.0; }//from w ww . jav a 2 s .c o m final double emi = expectedMutualInformation(); assert (!Double.isNaN(emi)); final double HU = entropyU(); final double HV = entropyV(); if (HU < 1e-100 && HV < 1e-100) { return 1.0; } final double num = mutualInformation() - emi; final double denom = Math.max(HU, HV) - emi; // if( Math.abs( denom ) < 1e-100 && Math.abs( num ) < 1e-100 ) { // return 0.0; // } return num / denom; }