List of usage examples for java.lang Number doubleValue
public abstract double doubleValue();
From source file:org.jfree.chart.demo.ExtendedStackedBarRenderer.java
/** * Calculates the sum of the negative values within a category. * /* ww w . j a v a 2 s . co m*/ * @param dataset the dataset. * @param column the column (category). * * @return the sum of the negative values. */ private double calculateSumOfNegativeValuesForCategory(final CategoryDataset dataset, final int column) { double result = 0.0; for (int r = 0; r < dataset.getRowCount(); r++) { final Number dataValue = dataset.getValue(r, column); if (dataValue != null) { final double v = dataValue.doubleValue(); if (v < 0.0) { result = result + v; } } } return result; }
From source file:com.swordlord.gozer.datatypeformat.DataTypeHelper.java
/** * Return compatible class for typedValue based on untypedValueClass * /*w w w .j a v a 2s. c o m*/ * @param untypedValueClass * @param typedValue * @return */ public static Object fromDataType(Class<?> untypedValueClass, Object typedValue) { Log LOG = LogFactory.getLog(DataTypeHelper.class); if (typedValue == null) { return null; } if (untypedValueClass == null) { return typedValue; } if (ClassUtils.isAssignable(typedValue.getClass(), untypedValueClass)) { return typedValue; } String strTypedValue = null; boolean isStringTypedValue = typedValue instanceof String; Number numTypedValue = null; boolean isNumberTypedValue = typedValue instanceof Number; Boolean boolTypedValue = null; boolean isBooleanTypedValue = typedValue instanceof Boolean; Date dateTypedValue = null; boolean isDateTypedValue = typedValue instanceof Date; if (isStringTypedValue) { strTypedValue = (String) typedValue; } if (isNumberTypedValue) { numTypedValue = (Number) typedValue; } if (isBooleanTypedValue) { boolTypedValue = (Boolean) typedValue; } if (isDateTypedValue) { dateTypedValue = (Date) typedValue; } Object v = null; if (String.class.equals(untypedValueClass)) { v = ObjectUtils.toString(typedValue); } else if (BigDecimal.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = NumberUtils.createBigDecimal(strTypedValue); } else if (isNumberTypedValue) { v = new BigDecimal(numTypedValue.doubleValue()); } else if (isBooleanTypedValue) { v = new BigDecimal(BooleanUtils.toInteger(boolTypedValue.booleanValue())); } else if (isDateTypedValue) { v = new BigDecimal(dateTypedValue.getTime()); } } else if (Boolean.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = BooleanUtils.toBooleanObject(strTypedValue); } else if (isNumberTypedValue) { v = BooleanUtils.toBooleanObject(numTypedValue.intValue()); } else if (isDateTypedValue) { v = BooleanUtils.toBooleanObject((int) dateTypedValue.getTime()); } } else if (Byte.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = Byte.valueOf(strTypedValue); } else if (isNumberTypedValue) { v = new Byte(numTypedValue.byteValue()); } else if (isBooleanTypedValue) { v = new Byte((byte) BooleanUtils.toInteger(boolTypedValue.booleanValue())); } else if (isDateTypedValue) { v = new Byte((byte) dateTypedValue.getTime()); } } else if (byte[].class.equals(untypedValueClass)) { if (isStringTypedValue) { v = strTypedValue.getBytes(); } } else if (Double.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = NumberUtils.createDouble(strTypedValue); } else if (isNumberTypedValue) { v = new Double(numTypedValue.doubleValue()); } else if (isBooleanTypedValue) { v = new Double(BooleanUtils.toInteger(boolTypedValue.booleanValue())); } else if (isDateTypedValue) { v = new Double(dateTypedValue.getTime()); } } else if (Float.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = NumberUtils.createFloat(strTypedValue); } else if (isNumberTypedValue) { v = new Float(numTypedValue.floatValue()); } else if (isBooleanTypedValue) { v = new Float(BooleanUtils.toInteger(boolTypedValue.booleanValue())); } else if (isDateTypedValue) { v = new Float(dateTypedValue.getTime()); } } else if (Short.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = NumberUtils.createInteger(strTypedValue); } else if (isNumberTypedValue) { v = new Integer(numTypedValue.intValue()); } else if (isBooleanTypedValue) { v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue()); } else if (isDateTypedValue) { v = new Integer((int) dateTypedValue.getTime()); } } else if (Integer.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = NumberUtils.createInteger(strTypedValue); } else if (isNumberTypedValue) { v = new Integer(numTypedValue.intValue()); } else if (isBooleanTypedValue) { v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue()); } else if (isDateTypedValue) { v = new Integer((int) dateTypedValue.getTime()); } } else if (Long.class.equals(untypedValueClass)) { if (isStringTypedValue) { v = NumberUtils.createLong(strTypedValue); } else if (isNumberTypedValue) { v = new Long(numTypedValue.longValue()); } else if (isBooleanTypedValue) { v = new Long(BooleanUtils.toInteger(boolTypedValue.booleanValue())); } else if (isDateTypedValue) { v = new Long(dateTypedValue.getTime()); } } else if (java.sql.Date.class.equals(untypedValueClass)) { if (isNumberTypedValue) { v = new java.sql.Date(numTypedValue.longValue()); } else if (isDateTypedValue) { v = new java.sql.Date(dateTypedValue.getTime()); } } else if (java.sql.Time.class.equals(untypedValueClass)) { if (isNumberTypedValue) { v = new java.sql.Time(numTypedValue.longValue()); } else if (isDateTypedValue) { v = new java.sql.Time(dateTypedValue.getTime()); } } else if (java.sql.Timestamp.class.equals(untypedValueClass)) { if (isNumberTypedValue) { v = new java.sql.Timestamp(numTypedValue.longValue()); } else if (isDateTypedValue) { v = new java.sql.Timestamp(dateTypedValue.getTime()); } } else if (Date.class.equals(untypedValueClass)) { if (isNumberTypedValue) { v = new Date(numTypedValue.longValue()); } else if (isStringTypedValue) { try { v = DateFormat.getDateInstance().parse(strTypedValue); } catch (ParseException e) { LOG.error("Unable to parse the date : " + strTypedValue); LOG.debug(e.getMessage()); } } } return v; }
From source file:NumberRange.java
/** * <p>Constructs a new <code>NumberRange</code> with the specified * minimum and maximum numbers.</p> * /*from w ww.j a va2 s. co m*/ * <p><em>If the maximum is less than the minimum, the range will be constructed * from the minimum value to the minimum value, not what you would expect!.</em></p> * * @param min the minimum number in this range * @param max the maximum number in this range * @throws NullPointerException if either the minimum or maximum number is * <code>null</code> */ public NumberRange(Number min, Number max) { if (min == null) { throw new NullPointerException("The minimum value must not be null"); } else if (max == null) { throw new NullPointerException("The maximum value must not be null"); } if (max.doubleValue() < min.doubleValue()) { this.min = this.max = min; } else { this.min = min; this.max = max; } }
From source file:net.bioclipse.model.ScatterPlotMouseHandler.java
public void mouseClicked(MouseEvent me) { Point2D p = null;/*from ww w . j a v a2 s.com*/ ChartDescriptor cd = null; int[] indices = null; JFreeChart selectedChart = null; ChartPanel chartPanel = getChartPanel(me); p = chartPanel.translateScreenToJava2D(new Point(me.getX(), me.getY())); selectedChart = chartPanel.getChart(); cd = ChartUtils.getChartDescriptor(selectedChart); indices = cd.getSourceIndices(); XYPlot plot = (XYPlot) chartPanel.getChart().getPlot(); XYItemRenderer plotRenderer = plot.getRenderer(); if (!(plotRenderer instanceof ScatterPlotRenderer)) { throw new IllegalStateException( "Charts using ScatterPlotMouseHandler must use ScatterPlotRenderer as their renderer"); } renderer = (ScatterPlotRenderer) plot.getRenderer(); // now convert the Java2D coordinate to axis coordinates... Number xx = getDomainX(chartPanel, plot, p); Number yy = getRangeY(chartPanel, plot, p); //Find the selected point in the dataset //If shift is down, save old selections if (!me.isShiftDown() || currentSelection == null) { currentSelection = new ChartSelection(); } for (int j = 0; j < plot.getDataset().getItemCount(plot.getDataset().getSeriesCount() - 1); j++) { for (int i = 0; i < plot.getDataset().getSeriesCount(); i++) { Number xK = plot.getDataset().getX(i, j); Number yK = plot.getDataset().getY(i, j); Number xKCheck = xK.doubleValue() - xx.doubleValue(); Number yKCheck = yK.doubleValue() - yy.doubleValue(); Number xxCheck = xKCheck.doubleValue() * xKCheck.doubleValue(); Number yyCheck = yKCheck.doubleValue() * yKCheck.doubleValue(); //Check distance from click and point, don't want to mark points that are too far from the click if (Math.sqrt(xxCheck.doubleValue()) <= 0.1 && Math.sqrt(yyCheck.doubleValue()) <= 0.1) { //Create a new selection PlotPointData cp = new PlotPointData(indices[j], cd.getXLabel(), cd.getYLabel()); cp.setDataPoint(j, i); currentSelection.addPoint(cp); if (!me.isShiftDown()) renderer.clearMarkedPoints(); renderer.addMarkedPoint(j, i); selectedChart.plotChanged(new PlotChangeEvent(plot)); } } } currentSelection.setDescriptor(cd); ChartUtils.updateSelection(currentSelection); }
From source file:org.jfree.data.statistics.DefaultMultiValueCategoryDataset.java
/** * Returns the average value for the specified item. * * @param row the row key.//from w ww . j a v a2s . c o m * @param column the column key. * * @return The average value. */ @Override public Number getValue(Comparable row, Comparable column) { List l = (List) this.data.getObject(row, column); double average = 0.0d; int count = 0; if (l != null && l.size() > 0) { for (int i = 0; i < l.size(); i++) { Number n = (Number) l.get(i); average += n.doubleValue(); count += 1; } if (count > 0) { average = average / count; } } if (count == 0) { return null; } return new Double(average); }
From source file:org.jfree.data.statistics.DefaultMultiValueCategoryDataset.java
/** * Returns the average value for the specified item. * * @param row the row index.//from ww w . ja va 2 s . c o m * @param column the column index. * * @return The average value. */ @Override public Number getValue(int row, int column) { List l = (List) this.data.getObject(row, column); double average = 0.0d; int count = 0; if (l != null && l.size() > 0) { for (int i = 0; i < l.size(); i++) { Number n = (Number) l.get(i); average += n.doubleValue(); count += 1; } if (count > 0) { average = average / count; } } if (count == 0) { return null; } return new Double(average); }
From source file:com.facebook.presto.operator.aggregation.AbstractTestApproximateAggregationFunction.java
private void testCorrectnessOfErrorFunction(List<Number> inputList) throws Exception { int inRange = 0; int numberOfRuns = 1000; double sampleRatio = 1 / (double) WEIGHT; double actual = getExpectedValue(inputList); Random rand = new Random(1); for (int i = 0; i < numberOfRuns; i++) { //Compute Sampled Value using sampledList (numberOfRuns times) ImmutableList.Builder<Number> sampledList = ImmutableList.builder(); for (Number x : inputList) { if (rand.nextDouble() < sampleRatio) { sampledList.add(x);/* w ww . j ava2 s . c om*/ } } ImmutableList<Number> list = sampledList.build(); BlockBuilder builder = getType().createBlockBuilder(new BlockBuilderStatus(), list.size()); for (Number sample : list) { if (getType().equals(BIGINT)) { BIGINT.writeLong(builder, sample.longValue()); } else if (getType().equals(DOUBLE)) { DOUBLE.writeDouble(builder, sample.doubleValue()); } else { throw new AssertionError("Can only handle longs and doubles"); } } Page page = new Page(builder.build()); page = OperatorAssertion.appendSampleWeight(ImmutableList.of(page), WEIGHT).get(0); Accumulator accumulator = getFunction().bind(ImmutableList.of(0), Optional.empty(), Optional.of(page.getChannelCount() - 1), getConfidence()).createAccumulator(); accumulator.addInput(page); Block result = getFinalBlock(accumulator); String approxValue = BlockAssertions.toValues(accumulator.getFinalType(), result).get(0).toString(); double approx = Double.parseDouble(approxValue.split(" ")[0]); double error = Double.parseDouble(approxValue.split(" ")[2]); //Check if actual answer lies within [approxAnswer - error, approxAnswer + error] if (Math.abs(approx - actual) <= error) { inRange++; } } BinomialDistribution binomial = new BinomialDistribution(numberOfRuns, getConfidence()); int lowerBound = binomial.inverseCumulativeProbability(0.01); int upperBound = binomial.inverseCumulativeProbability(0.99); assertTrue(lowerBound < inRange && inRange < upperBound, String .format("%d out of %d passed. Expected [%d, %d]", inRange, numberOfRuns, lowerBound, upperBound)); }
From source file:com.hortonworks.streamline.streams.metrics.storm.graphite.GraphiteWithStormQuerier.java
private Map<Long, Double> formatDataPointsFromGraphiteToMap(List<List<Number>> dataPoints) { Map<Long, Double> pointsForOutput = new HashMap<>(); if (dataPoints != null && dataPoints.size() > 0) { for (List<Number> dataPoint : dataPoints) { // ex. [2940.0, 1465803540] -> 1465803540000, 2940.0 Number valueNum = dataPoint.get(0); Number timestampNum = dataPoint.get(1); if (valueNum == null) { continue; }//w w w . j a v a 2 s.com pointsForOutput.put(timestampNum.longValue() * 1000, valueNum.doubleValue()); } } return pointsForOutput; }
From source file:gate.plugin.learningframework.engines.EngineServer.java
@Override public List<GateClassification> classify(AnnotationSet instanceAS, AnnotationSet inputAS, AnnotationSet sequenceAS, String parms) { Parms ps = new Parms(parms, "d:dense:b"); boolean dense = (boolean) ps.getValueOrElse("dense", false); CorpusRepresentationMalletTarget data = (CorpusRepresentationMalletTarget) corpusRepresentationMallet; data.stopGrowth();// ww w.j a va 2s . c o m int nrCols = data.getPipe().getDataAlphabet().size(); //System.err.println("Running EngineSklearn.classify on document "+instanceAS.getDocument().getName()); List<GateClassification> gcs = new ArrayList<GateClassification>(); LFPipe pipe = (LFPipe) data.getRepresentationMallet().getPipe(); ArrayList<String> classList = null; // If we have a classification problem, pre-calculate the class label list if (pipe.getTargetAlphabet() != null) { classList = new ArrayList<String>(); for (int i = 0; i < pipe.getTargetAlphabet().size(); i++) { String labelstr = pipe.getTargetAlphabet().lookupObject(i).toString(); classList.add(labelstr); } } // For now create a single request per document // eventually we could allow a parameter for sending a maximum number of // instances per request. List<Annotation> instances = instanceAS.inDocumentOrder(); List<double[]> valuesvec = new ArrayList<double[]>(); List<int[]> indicesvec = new ArrayList<int[]>(); List<Double> weights = new ArrayList<Double>(); ObjectMapper mapper = new ObjectMapper(); boolean haveWeights = false; for (Annotation instAnn : instances) { Instance inst = data.extractIndependentFeatures(instAnn, inputAS); inst = pipe.instanceFrom(inst); FeatureVector fv = (FeatureVector) inst.getData(); //System.out.println("Mallet instance, fv: "+fv.toString(true)+", len="+fv.numLocations()); // Convert to the sparse vector we use to send to the process // TODO: depending on a parameter send sparse or dense vectors, for now always send sparse if (dense) { double[] values = new double[nrCols]; for (int i = 0; i < nrCols; i++) { values[i] = fv.value(i); } valuesvec.add(values); } else { // To send a sparse vector, we need the indices and the values int locs = fv.numLocations(); int[] indices = new int[locs]; double[] values = new double[locs]; for (int i = 0; i < locs; i++) { indices[i] = fv.indexAtLocation(i); values[i] = fv.valueAtLocation(i); } valuesvec.add(values); indicesvec.add(indices); } double weight = Double.NaN; Object weightObj = inst.getProperty("instanceWeight"); if (weightObj != null) { weight = (double) weightObj; haveWeights = true; } weights.add(weight); } // create the JSON for the request Map data4json = new HashMap<String, Object>(); if (!dense) data4json.put("indices", indicesvec); data4json.put("values", valuesvec); data4json.put("n", nrCols); if (haveWeights) data4json.put("weights", weights); String json = null; try { json = mapper.writeValueAsString(data4json); } catch (JsonProcessingException ex) { throw new GateRuntimeException("Could not convert instances to json", ex); } //System.err.println("GOT JSON: "+json); HttpResponse<String> response; try { response = Unirest.post(serverUrl).header("accept", "application/json") .header("content-type", "application/json").body(json).asString(); } catch (UnirestException ex) { throw new GateRuntimeException("Exception when connecting to the server", ex); } // The response should be either OK and JSON or not OK and an error message int status = response.getStatus(); if (status != 200) { throw new GateRuntimeException( "Response von server is NOK, status=" + status + " msg=" + response.getBody()); } //System.err.println("Got response, status is OK, data is: "+response.getBody()); Map responseMap = null; try { // Parse the json responseMap = mapper.readValue(response.getBody(), HashMap.class); } catch (IOException ex) { Logger.getLogger(EngineServer.class.getName()).log(Level.SEVERE, null, ex); } // NOTE: the json created by the weka server currently automatically creates 1 instead // of 1.0 if the value is 1.0, and the parser then creates an Inteer from this. // We could probably change the parsing behaviour into always creating doubles somehow but // for now we simply first parse the arrays into Number, then convert each vector into // a vector of Double ArrayList<ArrayList<Number>> targets = (ArrayList<ArrayList<Number>>) responseMap.get("preds"); GateClassification gc = null; // now go through all the instances again and do the target assignment from the vector(s) we got int instNr = 0; for (Annotation instAnn : instances) { if (pipe.getTargetAlphabet() == null) { // we have regression gc = new GateClassification(instAnn, (double) targets.get(instNr).get(0)); } else { ArrayList<Number> valsN = targets.get(instNr); ArrayList<Double> vals = new ArrayList<Double>(valsN.size()); for (Number valN : valsN) vals.add(valN.doubleValue()); double target = vals.get(0); // if vals contains just one value, this will be what to use if (vals.size() > 1) { // find the maximum probability and use the index as target double maxProb = Double.NEGATIVE_INFINITY; double bestIndex = -1; int curIdx = 0; for (double val : vals) { if (val > maxProb) { maxProb = val; bestIndex = (double) curIdx; } curIdx++; } // for target = bestIndex; } int bestlabel = (int) target; String cl = pipe.getTargetAlphabet().lookupObject(bestlabel).toString(); double bestprob = Double.NaN; if (vals.size() > 1) { bestprob = Collections.max(vals); gc = new GateClassification(instAnn, cl, bestprob, classList, vals); } else { // create a fake probability distribution with 1.0/0.0 probabilities ArrayList<Double> probs = new ArrayList<Double>(classList.size()); for (int i = 0; i < classList.size(); i++) { if (i == bestlabel) probs.add(1.0); else probs.add(0.0); } gc = new GateClassification(instAnn, cl, bestprob, classList, probs); } } gcs.add(gc); instNr++; } data.startGrowth(); return gcs; }
From source file:NumberUtils.java
/** * Convert the given number into an instance of the given target class. * * @param number the number to convert * @param targetClass the target class to convert to * @return the converted number//from w w w .j a v a 2s . c o m * @throws IllegalArgumentException if the target class is not supported * (i.e. not a standard Number subclass as included in the JDK) * @see java.lang.Byte * @see java.lang.Short * @see java.lang.Integer * @see java.lang.Long * @see java.math.BigInteger * @see java.lang.Float * @see java.lang.Double * @see java.math.BigDecimal */ public static Number convertNumberToTargetClass(Number number, Class targetClass) throws IllegalArgumentException { if (targetClass.isInstance(number)) { return number; } else if (targetClass.equals(Byte.class)) { long value = number.longValue(); if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { raiseOverflowException(number, targetClass); } return number.byteValue(); } else if (targetClass.equals(Short.class)) { long value = number.longValue(); if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { raiseOverflowException(number, targetClass); } return number.shortValue(); } else if (targetClass.equals(Integer.class)) { long value = number.longValue(); if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { raiseOverflowException(number, targetClass); } return number.intValue(); } else if (targetClass.equals(Long.class)) { return number.longValue(); } else if (targetClass.equals(Float.class)) { return number.floatValue(); } else if (targetClass.equals(Double.class)) { return number.doubleValue(); } else if (targetClass.equals(BigInteger.class)) { return BigInteger.valueOf(number.longValue()); } else if (targetClass.equals(BigDecimal.class)) { // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double) // (see BigDecimal javadoc for details) return new BigDecimal(number.toString()); } else { throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]"); } }