List of usage examples for java.lang Double NEGATIVE_INFINITY
double NEGATIVE_INFINITY
To view the source code for java.lang Double NEGATIVE_INFINITY.
Click Source Link
From source file:com.bmwcarit.barefoot.markov.Filter.java
/** * Executes Hidden Markov Model (HMM) filter iteration that determines for a given measurement * sample <i>z<sub>t</sub></i>, which is a {@link Sample} object, and of a predecessor state * vector <i>S<sub>t-1</sub></i>, which is a set of {@link StateCandidate} objects, a state * vector <i>S<sub>t</sub></i> with filter and sequence probabilities set. * <p>//from ww w. ja v a 2 s . c o m * <b>Note:</b> The set of state candidates <i>S<sub>t-1</sub></i> is allowed to be empty. This * is either the initial case or an HMM break occured, which is no state candidates representing * the measurement sample could be found. * * @param predecessors State vector <i>S<sub>t-1</sub></i>, which may be empty. * @param sample Measurement sample <i>z<sub>t</sub></i>. * @param previous Previous measurement sample <i>z<sub>t-1</sub></i>. * * @return State vector <i>S<sub>t</sub></i>, which may be empty if an HMM break occured. */ public Set<C> execute(Set<C> predecessors, S previous, S sample) { if (logger.isTraceEnabled()) { try { logger.trace("execute sample {}", sample.toJSON().toString()); } catch (JSONException e) { logger.trace("execute sample (not JSON parsable sample: {})", e.getMessage()); } } assert (predecessors != null); assert (sample != null); Set<C> result = new HashSet<>(); Set<Tuple<C, Double>> candidates = candidates(predecessors, sample); logger.trace("{} state candidates", candidates.size()); double normsum = 0; if (!predecessors.isEmpty()) { Set<C> states = new HashSet<>(); for (Tuple<C, Double> candidate : candidates) { states.add(candidate.one()); } Map<C, Map<C, Tuple<T, Double>>> transitions = transitions(new Tuple<>(previous, predecessors), new Tuple<>(sample, states)); for (Tuple<C, Double> candidate : candidates) { C candidate_ = candidate.one(); candidate_.seqprob(Double.NEGATIVE_INFINITY); if (logger.isTraceEnabled()) { try { logger.trace("state candidate {} ({}) {}", candidate_.id(), candidate.two(), candidate_.toJSON().toString()); } catch (JSONException e) { logger.trace("state candidate (not JSON parsable candidate: {})", e.getMessage()); } } for (C predecessor : predecessors) { Tuple<T, Double> transition = transitions.get(predecessor).get(candidate_); if (transition == null || transition.two() == 0) { continue; } candidate_.filtprob(candidate_.filtprob() + (transition.two() * predecessor.filtprob())); double seqprob = predecessor.seqprob() + Math.log10(transition.two()) + Math.log10(candidate.two()); if (logger.isTraceEnabled()) { try { logger.trace("state transition {} -> {} ({}, {}, {}) {}", predecessor.id(), candidate_.id(), predecessor.seqprob(), Math.log10(transition.two()), Math.log10(candidate.two()), transition.one().toJSON().toString()); } catch (JSONException e) { logger.trace("state transition (not JSON parsable transition: {})", e.getMessage()); } } if (seqprob > candidate_.seqprob()) { candidate_.predecessor(predecessor); candidate_.transition(transition.one()); candidate_.seqprob(seqprob); } } if (candidate_.predecessor() != null) { logger.trace("state candidate {} -> {} ({}, {})", candidate_.predecessor().id(), candidate_.id(), candidate_.filtprob(), candidate_.seqprob()); } else { logger.trace("state candidate - -> {} ({}, {})", candidate_.id(), candidate_.filtprob(), candidate_.seqprob()); } if (candidate_.filtprob() == 0) { continue; } candidate_.filtprob(candidate_.filtprob() * candidate.two()); result.add(candidate_); normsum += candidate_.filtprob(); } } if (!candidates.isEmpty() && result.isEmpty() && !predecessors.isEmpty()) { logger.info("HMM break - no state transitions"); } if (result.isEmpty() || predecessors.isEmpty()) { for (Tuple<C, Double> candidate : candidates) { if (candidate.two() == 0) { continue; } C candidate_ = candidate.one(); normsum += candidate.two(); candidate_.filtprob(candidate.two()); candidate_.seqprob(Math.log10(candidate.two())); result.add(candidate_); if (logger.isTraceEnabled()) { try { logger.trace("state candidate {} ({}) {}", candidate_.id(), candidate.two(), candidate_.toJSON().toString()); } catch (JSONException e) { logger.trace("state candidate (not JSON parsable candidate: {})", e.getMessage()); } } } } if (result.isEmpty()) { logger.info("HMM break - no state emissions"); } for (C candidate : result) { candidate.filtprob(candidate.filtprob() / normsum); } logger.trace("{} state candidates for state update", result.size()); return result; }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.QUELLE.QuelleService.java
@POST @Path("/recommend") @Consumes(MediaType.APPLICATION_XML)/* w ww . j a va 2 s .c o m*/ @Produces(MediaType.APPLICATION_XML) public Recommendations getRecommendation(MultiLevelRequirements multiLevelRequirements) { EngineLogger.logger .debug("Getting recommendation for multiple requirement: " + multiLevelRequirements.getName()); List<MultiLevelRequirements> individualServiceUnitRequirements = multiLevelRequirements.flatten(); List<ServiceUnitServicesRecommendation> recommendations = new ArrayList<>(); // load cloud provider List<CloudProvider> cloudProviders = loadCloudAllDescription(); EngineLogger.logger.debug("Loaded " + cloudProviders.size() + " provider done."); if (cloudProviders.isEmpty()) { EngineLogger.logger .error("Do not found any cloud provider infomation. Please submit at least one first !"); return null; } for (MultiLevelRequirements reqs : individualServiceUnitRequirements) { RequirementsResolutionResult requirementsMatchingResult = requirementsMatchingEngine .analyzeMultiLevelRequirements(cloudProviders, reqs); Map<MultiLevelRequirements, Map<Requirements, List<ServiceUnitConfigurationSolution>>> bestElasticity = requirementsMatchingResult .getConcreteConfigurations(serviceUnitComparators); List<CloudServiceConfigurationRecommendation> recommendedConfigurations = new ArrayList<>(); { for (MultiLevelRequirements levelRequirements : bestElasticity.keySet()) { Map<Requirements, List<ServiceUnitConfigurationSolution>> solutions = bestElasticity .get(levelRequirements); String strategies = ""; for (Strategy s : levelRequirements.getOptimizationStrategies()) { strategies += "_" + s.getStrategyCategory(); } for (Requirements requirements : solutions.keySet()) { String solutionsNames = ""; int solutionsCount = solutions.get(requirements).size(); // compute average elasticities double averageCostElasticity = 0d; double averageSUElasticity = 0d; double averageResourceElasticity = 0d; double averageQualityElasticity = 0d; double minCostElasticity = Double.POSITIVE_INFINITY; double minSUElasticity = Double.POSITIVE_INFINITY; double minResourceElasticity = Double.POSITIVE_INFINITY; double minQualityElasticity = Double.POSITIVE_INFINITY; double maxCostElasticity = Double.NEGATIVE_INFINITY; double maxSUElasticity = Double.NEGATIVE_INFINITY; double maxResourceElasticity = Double.NEGATIVE_INFINITY; double maxQualityElasticity = Double.NEGATIVE_INFINITY; for (ServiceUnitConfigurationSolution solutionConfiguration : solutions.get(requirements)) { CloudServiceUnitAnalysisEngine cloudServiceElasticityAnalysisEngine = new CloudServiceUnitAnalysisEngine(); CloudServiceUnitAnalysisEngine.AnalysisResult analysisResult = cloudServiceElasticityAnalysisEngine .analyzeElasticity(solutionConfiguration.getServiceUnit()); solutionsNames += " " + solutionConfiguration.getServiceUnit().getName(); double costElasticity = (Integer) analysisResult .getValue(CloudServiceElasticityAnalysisEngine.COST_ELASTICITY); double sUElasticity = (Integer) analysisResult.getValue( CloudServiceElasticityAnalysisEngine.SERVICE_UNIT_ASSOCIATION_ELASTICITY); double resourceElasticity = (Integer) analysisResult .getValue(CloudServiceElasticityAnalysisEngine.RESOURCE_ELASTICITY); double qualityElasticity = (Integer) analysisResult .getValue(CloudServiceElasticityAnalysisEngine.QUALITY_ELASTICITY); averageCostElasticity += costElasticity; averageSUElasticity += sUElasticity; averageResourceElasticity += resourceElasticity; averageQualityElasticity += qualityElasticity; if (minCostElasticity > costElasticity) { minCostElasticity = costElasticity; } if (minSUElasticity > sUElasticity) { minSUElasticity = sUElasticity; } if (minResourceElasticity > resourceElasticity) { minResourceElasticity = resourceElasticity; } if (minQualityElasticity > qualityElasticity) { minQualityElasticity = qualityElasticity; } if (maxCostElasticity < costElasticity) { maxCostElasticity = costElasticity; } if (maxSUElasticity < sUElasticity) { maxSUElasticity = sUElasticity; } if (maxResourceElasticity < resourceElasticity) { maxResourceElasticity = resourceElasticity; } if (maxQualityElasticity < qualityElasticity) { maxQualityElasticity = qualityElasticity; } recommendedConfigurations.add(new CloudServiceConfigurationRecommendation() .withServiceUnitConfigurationSolution(requirements.getName(), solutionConfiguration, costElasticity, sUElasticity, resourceElasticity, qualityElasticity)); // ObjectMapper mapper = new ObjectMapper(); // System.out.println("solutionConfiguration" + mapper.writeValueAsString(solutionConfiguration)); // System.out.println("recommendedConfigurations: " + mapper.writeValueAsString(recommendedConfigurations)); recommendations.add(new ServiceUnitServicesRecommendation() .withSolutionRecommendation(requirements, recommendedConfigurations)); } // averageCostElasticity /= solutionsCount; // averageSUElasticity /= solutionsCount; // averageResourceElasticity /= solutionsCount; // averageQualityElasticity /= solutionsCount; // System.out.println(requirements.getName() + "," + strategies + "," + solutionsNames + "," + solutionsCount + "," + averageCostElasticity + "," // + minCostElasticity + "," + maxCostElasticity + "," + averageSUElasticity + "," + minSUElasticity + "," + maxSUElasticity // + "," + averageResourceElasticity + "," + minResourceElasticity + "," + maxResourceElasticity + "," // + averageQualityElasticity + "," + minQualityElasticity + "," + maxQualityElasticity); // System.out.println("\n"); } } } } EngineLogger.logger.debug("Quelle recommendation is done, returning result ...."); // wrapping return new Recommendations(recommendations); // File saveAs = new File("/tmp/quelleresult"); // Writer result = new StringWriter(); // JAXBContext jaxbContext; // try { // jaxbContext = JAXBContext.newInstance(Recommendations.class); // Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // jaxbMarshaller.marshal(new Recommendations(recommendations), saveAs); // // jaxbMarshaller.marshal(new Recommendations(recommendations), result); // } catch (JAXBException ex) { // ex.printStackTrace(); // } // return result.toString(); }
From source file:com.microsoft.azure.storage.table.TableEntitySerializer.java
/** * Reserved for internal use. Writes an entity to the specified <code>JsonGenerator</code> as a JSON resource * //w ww. ja va2s . c o m * @param generator * The <code>JsonGenerator</code> to write the entity to. * @param options * The {@link TableRequestOptions} to use for serializing. * @param entity * The instance implementing {@link TableEntity} to write to the output stream. * @param isTableEntry * A flag indicating the entity is a reference to a table at the top level of the storage service when * <code>true<code> and a reference to an entity within a table when <code>false</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * * @throws StorageException * if a Storage service error occurs. * @throws IOException * if an error occurs while accessing the stream. */ private static void writeJsonEntity(final JsonGenerator generator, final TableRequestOptions options, final TableEntity entity, final boolean isTableEntry, final OperationContext opContext) throws StorageException, IOException { Map<String, EntityProperty> properties = getPropertiesFromDictionary(entity, options, opContext); // start object generator.writeStartObject(); if (!isTableEntry) { Utility.assertNotNull(TableConstants.PARTITION_KEY, entity.getPartitionKey()); Utility.assertNotNull(TableConstants.ROW_KEY, entity.getRowKey()); Utility.assertNotNull(TableConstants.TIMESTAMP, entity.getTimestamp()); // PartitionKey generator.writeStringField(TableConstants.PARTITION_KEY, entity.getPartitionKey()); // RowKey generator.writeStringField(TableConstants.ROW_KEY, entity.getRowKey()); // Timestamp generator.writeStringField(TableConstants.TIMESTAMP, Utility.getJavaISO8601Time(entity.getTimestamp())); } for (final Entry<String, EntityProperty> ent : properties.entrySet()) { if (ent.getKey().equals(TableConstants.PARTITION_KEY) || ent.getKey().equals(TableConstants.ROW_KEY) || ent.getKey().equals(TableConstants.TIMESTAMP) || ent.getKey().equals("Etag")) { continue; } EntityProperty currProp = ent.getValue(); if (currProp.getEdmType().mustAnnotateType()) { final String edmTypeString = currProp.getEdmType().toString(); // property type generator.writeStringField(ent.getKey() + ODataConstants.ODATA_TYPE_SUFFIX, edmTypeString); // property key and value generator.writeStringField(ent.getKey(), ent.getValue().getValueAsString()); } else if (currProp.getEdmType() == EdmType.DOUBLE && currProp.getIsNull() == false) { final String edmTypeString = currProp.getEdmType().toString(); final Double value = currProp.getValueAsDouble(); // property type, if needed if (value.equals(Double.POSITIVE_INFINITY) || value.equals(Double.NEGATIVE_INFINITY) || value.equals(Double.NaN)) { generator.writeStringField(ent.getKey() + ODataConstants.ODATA_TYPE_SUFFIX, edmTypeString); // property key and value generator.writeStringField(ent.getKey(), ent.getValue().getValueAsString()); } else { writeJsonProperty(generator, ent); } } else { writeJsonProperty(generator, ent); } } // end object generator.writeEndObject(); }
From source file:com.aliyun.odps.ship.common.RecordConverterTest.java
/** * double? ???"Infinity",?"-Infinity"<br/> * <br/>//from w w w . j ava2s . c o m * 1) double??<br/> * 2?????<br/> * 3) <br/> * */ @Test public void testDouble() throws Exception { TableSchema rs = new TableSchema(); rs.addColumn(new Column("d1", OdpsType.DOUBLE)); rs.addColumn(new Column("d2", OdpsType.DOUBLE)); rs.addColumn(new Column("d3", OdpsType.DOUBLE)); rs.addColumn(new Column("d4", OdpsType.DOUBLE)); rs.addColumn(new Column("d5", OdpsType.DOUBLE)); rs.addColumn(new Column("d6", OdpsType.DOUBLE)); rs.addColumn(new Column("d7", OdpsType.DOUBLE)); String[] l = new String[] { "211.234567", "Infinity", "-Infinity", "12345678.1234567", "1.23456781234567E7", "1.2345E2", "1.2345E10" }; RecordConverter cv = new RecordConverter(rs, "NULL", "yyyyMMddHHmmss", null); Record r = cv.parse(toByteArray(l)); assertEquals("d1 not equal.", "211.234567", r.getDouble(0).toString()); assertEquals("d2 not equal.", new Double(Double.POSITIVE_INFINITY).toString(), r.getDouble(1).toString()); assertEquals("d3 not equal.", new Double(Double.NEGATIVE_INFINITY).toString(), r.getDouble(2).toString()); assertEquals("d3 not equal d4.", r.getDouble(3), r.getDouble(4)); l = new String[] { "211.234567", "Infinity", "-Infinity", "12345678.1234567", "12345678.1234567", "123.45", "12345000000" }; byte[][] l1 = cv.format(r); for (int i = 0; i < l1.length; i++) { assertEquals("converter at index:" + i, l[i], new String(l1[i])); } try { String[] l2 = new String[] { "12345678.1234567", "1.23456781234567E7", "1", "a", "b", "1", "1" }; Record r2 = cv.parse(toByteArray(l2)); fail("need fail"); } catch (Exception e) { assertTrue(e.getMessage(), e.getMessage().indexOf("ERROR: format error - :4, DOUBLE:'a'") >= 0); } }
From source file:ffx.realspace.CCP4MapFilter.java
/** * {@inheritDoc}/*from w ww. j a v a 2 s .c o m*/ */ @Override public boolean readFile(String filename, RealSpaceRefinementData refinementdata, CompositeConfiguration properties) { int imapData; double cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma; String stampString; ByteOrder byteOrder = ByteOrder.nativeOrder(); FileInputStream fileInputStream; DataInputStream dataInputStream; double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; double mean = 0.0; double sd = 0.0; double rmsd = 0.0; // First determine byte order of file versus system try { fileInputStream = new FileInputStream(filename); dataInputStream = new DataInputStream(fileInputStream); dataInputStream.skipBytes(212); byte bytes[] = new byte[4]; dataInputStream.read(bytes, 0, 4); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); imapData = byteBuffer.order(ByteOrder.BIG_ENDIAN).getInt(); stampString = Integer.toHexString(imapData); switch (stampString.charAt(0)) { case '1': case '3': if (byteOrder.equals(ByteOrder.LITTLE_ENDIAN)) { byteOrder = ByteOrder.BIG_ENDIAN; } break; case '4': if (byteOrder.equals(ByteOrder.BIG_ENDIAN)) { byteOrder = ByteOrder.LITTLE_ENDIAN; } break; } if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(String.format("\n Opening CCP4 map: %s\n", filename)); //sb.append(String.format("file type (machine stamp): %s\n", stampString)); logger.info(sb.toString()); } fileInputStream.close(); } catch (Exception e) { String message = " Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); } try { fileInputStream = new FileInputStream(filename); dataInputStream = new DataInputStream(fileInputStream); byte bytes[] = new byte[2048]; dataInputStream.read(bytes, 0, 1024); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); int ext[] = new int[3]; ext[0] = byteBuffer.order(byteOrder).getInt(); ext[1] = byteBuffer.order(byteOrder).getInt(); ext[2] = byteBuffer.order(byteOrder).getInt(); // mode (2 = reals, only one we accept) int mode = byteBuffer.order(byteOrder).getInt(); int ori[] = new int[3]; ori[0] = byteBuffer.order(byteOrder).getInt(); ori[1] = byteBuffer.order(byteOrder).getInt(); ori[2] = byteBuffer.order(byteOrder).getInt(); int ni[] = new int[3]; ni[0] = byteBuffer.order(byteOrder).getInt(); ni[1] = byteBuffer.order(byteOrder).getInt(); ni[2] = byteBuffer.order(byteOrder).getInt(); cellA = byteBuffer.order(byteOrder).getFloat(); cellB = byteBuffer.order(byteOrder).getFloat(); cellC = byteBuffer.order(byteOrder).getFloat(); cellAlpha = byteBuffer.order(byteOrder).getFloat(); cellBeta = byteBuffer.order(byteOrder).getFloat(); cellGamma = byteBuffer.order(byteOrder).getFloat(); int axisi[] = new int[3]; for (int i = 0; i < 3; i++) { int axis = byteBuffer.order(byteOrder).getInt(); switch (axis) { case 1: axisi[0] = i; break; case 2: axisi[1] = i; break; case 3: axisi[2] = i; break; } } min = byteBuffer.order(byteOrder).getFloat(); max = byteBuffer.order(byteOrder).getFloat(); mean = byteBuffer.order(byteOrder).getFloat(); int sg = byteBuffer.order(byteOrder).getInt(); int nsymb = byteBuffer.order(byteOrder).getInt(); int skew = byteBuffer.order(byteOrder).getInt(); for (int i = 0; i < 12; i++) { byteBuffer.order(byteOrder).getFloat(); } for (int i = 0; i < 15; i++) { byteBuffer.order(byteOrder).getInt(); } byte word[] = new byte[2048]; byteBuffer.order(byteOrder).get(word, 0, 4); String mapString = new String(word); sd = byteBuffer.order(byteOrder).getFloat(); rmsd = byteBuffer.order(byteOrder).getFloat(); if (logger.isLoggable(Level.INFO)) { StringBuilder sb = new StringBuilder(); sb.append(String.format(" Column origin: %d\t Extent: %d\n", ori[0], ext[0])); sb.append(String.format(" Row origin: %d\t Extent: %d\n", ori[1], ext[1])); sb.append(String.format(" Section origin: %d\t Extent: %d\n", ori[2], ext[2])); sb.append(String.format(" Axis order: %d %d %d\n", axisi[0], axisi[1], axisi[2])); sb.append(String.format(" Number of X, Y, Z columns: %d %d %d\n", ni[0], ni[1], ni[2])); sb.append(String.format(" Spacegroup: %d (%s)\n", sg, SpaceGroup.spaceGroupNames[sg - 1])); sb.append(String.format(" Cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", cellA, cellB, cellC, cellAlpha, cellBeta, cellGamma)); logger.info(sb.toString()); } int nlabel = byteBuffer.order(byteOrder).getInt(); for (int i = 0; i < 10; i++) { byteBuffer.order(byteOrder).get(word, 0, 80); mapString = new String(word); } if (nsymb > 0) { byteBuffer.rewind(); dataInputStream.read(bytes, 0, nsymb); for (int i = 0; i < nsymb / 80; i += 80) { byteBuffer.order(byteOrder).get(word, 0, 80); mapString = new String(word); } } byteBuffer.rewind(); dataInputStream.read(bytes, 0, 2048); refinementdata.setData(new double[ext[0] * ext[1] * ext[2]]); int ijk[] = new int[3]; int index, x, y, z; refinementdata.setOrigin(ori[axisi[0]], ori[axisi[1]], ori[axisi[2]]); int nx = ext[axisi[0]]; int ny = ext[axisi[1]]; int nz = ext[axisi[2]]; refinementdata.setExtent(nx, ny, nz); refinementdata.setNI(ni[0], ni[1], ni[2]); for (ijk[2] = 0; ijk[2] < ext[2]; ijk[2]++) { for (ijk[1] = 0; ijk[1] < ext[1]; ijk[1]++) { for (ijk[0] = 0; ijk[0] < ext[0]; ijk[0]++) { x = ijk[axisi[0]]; y = ijk[axisi[1]]; z = ijk[axisi[2]]; index = x + nx * (y + ny * z); refinementdata.getData()[index] = byteBuffer.order(byteOrder).getFloat(); if (!byteBuffer.hasRemaining()) { byteBuffer.rewind(); dataInputStream.read(bytes, 0, 2048); } } } } fileInputStream.close(); } catch (Exception e) { String message = " Fatal exception reading CCP4 map.\n"; logger.log(Level.SEVERE, message, e); } return true; }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.targetcharts.SparkLine.java
@Override public JFreeChart createChart(DatasetMap datasets) { logger.debug("IN"); XYDataset dataset = (XYDataset) datasets.getDatasets().get("1"); final JFreeChart sparkLineGraph = ChartFactory.createTimeSeriesChart(null, null, null, dataset, legend, false, false);/* w w w . j a va2s . c om*/ sparkLineGraph.setBackgroundPaint(color); TextTitle title = setStyleTitle(name, styleTitle); sparkLineGraph.setTitle(title); if (subName != null && !subName.equals("")) { TextTitle subTitle = setStyleTitle(subName, styleSubTitle); sparkLineGraph.addSubtitle(subTitle); } sparkLineGraph.setBorderVisible(false); sparkLineGraph.setBorderPaint(Color.BLACK); XYPlot plot = sparkLineGraph.getXYPlot(); plot.setOutlineVisible(false); plot.setInsets(new RectangleInsets(0.0, 0.0, 0.0, 0.0)); plot.setBackgroundPaint(null); plot.setDomainGridlinesVisible(false); plot.setDomainCrosshairVisible(false); plot.setRangeGridlinesVisible(false); plot.setRangeCrosshairVisible(false); plot.setBackgroundPaint(color); // calculate the last marker color Paint colorLast = getLastPointColor(); // Calculate average, minimum and maximum to draw plot borders. boolean isFirst = true; double avg = 0, min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY; int count = 0; for (int i = 0; i < timeSeries.getItemCount(); i++) { if (timeSeries.getValue(i) != null) { count++; if (isFirst) { min = timeSeries.getValue(i).doubleValue(); max = timeSeries.getValue(i).doubleValue(); isFirst = false; } double n = timeSeries.getValue(i).doubleValue(); //calculate avg, min, max avg += n; if (n < min) min = n; if (n > max) max = n; } } // average avg = avg / (double) count; // calculate min and max between thresholds! boolean isFirst2 = true; double lb = 0, ub = 0; for (Iterator iterator = thresholds.keySet().iterator(); iterator.hasNext();) { Double thres = (Double) iterator.next(); if (isFirst2 == true) { ub = thres.doubleValue(); lb = thres.doubleValue(); isFirst2 = false; } if (thres.doubleValue() > ub) ub = thres.doubleValue(); if (thres.doubleValue() < lb) lb = thres.doubleValue(); } plot.getRangeAxis().setRange(new Range(Math.min(lb, min - 2), Math.max(ub, max + 2) + 2)); addMarker(1, avg, Color.GRAY, 0.8f, plot); //addAvaregeSeries(series, plot); addPointSeries(timeSeries, plot); int num = 3; for (Iterator iterator = thresholds.keySet().iterator(); iterator.hasNext();) { Double thres = (Double) iterator.next(); TargetThreshold targThres = thresholds.get(thres); Color color = Color.WHITE; if (targThres != null && targThres.getColor() != null) { color = targThres.getColor(); } if (targThres.isVisible()) { addMarker(num++, thres.doubleValue(), color, 0.5f, plot); } } ValueAxis domainAxis = plot.getDomainAxis(); domainAxis.setVisible(false); domainAxis.setUpperMargin(0.2); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setVisible(false); plot.getRenderer().setSeriesPaint(0, Color.BLACK); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) { public boolean getItemShapeVisible(int _series, int item) { TimeSeriesDataItem tsdi = timeSeries.getDataItem(item); if (tsdi == null) return false; Month period = (Month) tsdi.getPeriod(); int currMonth = period.getMonth(); int currYear = period.getYearValue(); int lastMonthFilled = lastMonth.getMonth(); int lastYearFilled = lastMonth.getYearValue(); boolean isLast = false; if (currYear == lastYearFilled && currMonth == lastMonthFilled) { isLast = true; } return isLast; } }; renderer.setSeriesPaint(0, Color.decode("0x000000")); renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); renderer.setDrawOutlines(true); renderer.setUseFillPaint(true); renderer.setBaseFillPaint(colorLast); renderer.setBaseOutlinePaint(Color.BLACK); renderer.setUseOutlinePaint(true); renderer.setSeriesShape(0, new Ellipse2D.Double(-4.0, -4.0, 8.0, 8.0)); if (wlt_mode.doubleValue() == 0) { renderer.setBaseItemLabelsVisible(Boolean.FALSE, true); } else { renderer.setBaseItemLabelsVisible(Boolean.TRUE, true); renderer.setBaseItemLabelFont( new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize())); renderer.setBaseItemLabelPaint(styleValueLabels.getColor()); renderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator("{2}", new DecimalFormat("0.###"), new DecimalFormat("0.###")) { public String generateLabel(CategoryDataset dataset, int row, int column) { if (dataset.getValue(row, column) == null || dataset.getValue(row, column).doubleValue() == 0) return ""; String columnKey = (String) dataset.getColumnKey(column); int separator = columnKey.indexOf('-'); String month = columnKey.substring(0, separator); String year = columnKey.substring(separator + 1); int monthNum = Integer.parseInt(month); if (wlt_mode.doubleValue() >= 1 && wlt_mode.doubleValue() <= 4) { if (wlt_mode.doubleValue() == 2 && column % 2 == 0) return ""; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MONTH, monthNum - 1); SimpleDateFormat dataFormat = new SimpleDateFormat("MMM"); return dataFormat.format(calendar.getTime()); } else return "" + monthNum; } }); } if (wlt_mode.doubleValue() == 3) { renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, org.jfree.ui.TextAnchor.BOTTOM_CENTER, org.jfree.ui.TextAnchor.BOTTOM_RIGHT, Math.PI / 2)); renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, org.jfree.ui.TextAnchor.TOP_CENTER, org.jfree.ui.TextAnchor.HALF_ASCENT_LEFT, Math.PI / 2)); } else if (wlt_mode.doubleValue() == 4) { renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, org.jfree.ui.TextAnchor.BOTTOM_CENTER, org.jfree.ui.TextAnchor.BOTTOM_RIGHT, Math.PI / 4)); renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, org.jfree.ui.TextAnchor.TOP_CENTER, org.jfree.ui.TextAnchor.HALF_ASCENT_LEFT, Math.PI / 4)); } if (legend == true) { LegendItemCollection collection = createThresholdLegend(plot); LegendItem item = new LegendItem("Avg", "Avg", "Avg", "Avg", new Rectangle(10, 10), colorAverage); collection.add(item); plot.setFixedLegendItems(collection); } plot.setRenderer(0, renderer); logger.debug("OUT"); return sparkLineGraph; }
From source file:de.cebitec.readXplorer.differentialExpression.plot.ExpressTestGraphicsTopComponent.java
public Map<PersistentFeature, Pair<Double, Double>> createSamplePoints(int n) { Random r = new Random(System.nanoTime()); Map<PersistentFeature, Pair<Double, Double>> points = new HashMap<>(); for (int i = 0; i < n; i++) { PersistentFeature dummyFeature = new PersistentFeature(0, 0, "", "", "", "", 0, 0, true, FeatureType.ANY, ""); double random = Math.random(); if (random > 0.95) { points.put(dummyFeature, new Pair<>(r.nextDouble() * 256.0d, Double.POSITIVE_INFINITY)); points.put(dummyFeature, new Pair<>(r.nextDouble() * 256.0d, Double.NEGATIVE_INFINITY)); } else {// w w w.ja v a 2 s . c o m points.put(dummyFeature, new Pair<>(2 * i + (r.nextGaussian() - 0.5d), r.nextDouble() * 256.0d)); } } PersistentFeature dummyFeature = new PersistentFeature(0, 0, "", "", "", "", 0, 0, true, FeatureType.ANY, ""); points.put(dummyFeature, new Pair<>(200d, 300d)); dummyFeature = new PersistentFeature(0, 0, "", "", "", "", 0, 0, true, FeatureType.ANY, ""); points.put(dummyFeature, new Pair<>(100d, Double.POSITIVE_INFINITY)); return points; }
From source file:de.bund.bfr.knime.pmmlite.views.chart.ChartCreator.java
public JFreeChart getChart(List<String> idsToPaint) throws ParseException, UnitException { if (varX == null || varY == null || varX.getName() == null || varY.getName() == null) { return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, new XYPlot(), showLegend); }//from www . j a v a2 s.com NumberAxis xAxis = new NumberAxis(varX.getDisplayString()); NumberAxis yAxis = new NumberAxis(varY.getDisplayString()); XYPlot plot = new XYPlot(null, xAxis, yAxis, null); double usedMinX = Double.POSITIVE_INFINITY; double usedMaxX = Double.NEGATIVE_INFINITY; int index = 0; List<Color> defaultColors = ChartUtils.createColorList(idsToPaint.size()); List<NamedShape> defaultShapes = ChartUtils.createShapeList(idsToPaint.size()); for (String id : idsToPaint) { Plotable plotable = plotables.get(id); if (plotable == null) { continue; } if (plotable.getType() == Plotable.Type.BOTH || plotable.getType() == Plotable.Type.BOTH_MANY || plotable.getType() == Plotable.Type.FUNCTION || plotable.getType() == Plotable.Type.FUNCTION_SAMPLE) { double minArg = varX.to(MathUtils.nullToNan(plotable.getMinValues().get(varX.getName())), plotable.getUnits().get(varX.getName())); double maxArg = varX.to(MathUtils.nullToNan(plotable.getMaxValues().get(varX.getName())), plotable.getUnits().get(varX.getName())); if (Double.isFinite(minArg)) { usedMinX = Math.min(usedMinX, minArg); } if (Double.isFinite(maxArg)) { usedMaxX = Math.max(usedMaxX, maxArg); } } if (plotable.getType() == Plotable.Type.BOTH || plotable.getType() == Plotable.Type.BOTH_MANY) { for (Map<String, Integer> choice : plotable.getAllChoices(varX.getName())) { double[][] points = plotable.getPoints(varX, varY, choice); if (points != null) { for (int i = 0; i < points[0].length; i++) { usedMinX = Math.min(usedMinX, points[0][i]); usedMaxX = Math.max(usedMaxX, points[0][i]); } } } } if (plotable.getType() == Plotable.Type.DATASET || plotable.getType() == Plotable.Type.DATASET_MANY) { double[][] points = plotable.getPoints(varX, varY); if (points != null) { for (int i = 0; i < points[0].length; i++) { usedMinX = Math.min(usedMinX, points[0][i]); usedMaxX = Math.max(usedMaxX, points[0][i]); } } } if (plotable.getType() == Plotable.Type.FUNCTION_SAMPLE) { for (Double x : plotable.getSamples()) { if (x != null && Double.isFinite(x)) { usedMinX = Math.min(usedMinX, x); usedMaxX = Math.max(usedMaxX, x); } } } } if (Double.isInfinite(usedMinX)) { usedMinX = 0.0; } if (Double.isInfinite(usedMaxX)) { usedMaxX = 100.0; } if (varX.getName().equals(PmmUtils.TIME) || varX.getName().equals(PmmUtils.CONCENTRATION)) { usedMinX = Math.min(usedMinX, 0.0); xAxis.setAutoRangeIncludesZero(true); } else { xAxis.setAutoRangeIncludesZero(false); } if (varY.getName().equals(PmmUtils.TIME) || varY.getName().equals(PmmUtils.CONCENTRATION)) { yAxis.setAutoRangeIncludesZero(true); } else { yAxis.setAutoRangeIncludesZero(false); } if (usedMinX == usedMaxX) { usedMinX -= 1.0; usedMaxX += 1.0; } if (useManualRange && minX < maxX && minY < maxY) { usedMinX = minX; usedMaxX = maxX; xAxis.setRange(new Range(minX, maxX)); yAxis.setRange(new Range(minY, maxY)); } for (String id : idsToPaint) { Plotable plotable = plotables.get(id); if (plotable == null) { continue; } plotable.setFunctionSteps(resolution); switch (plotable.getType()) { case DATASET: plotDataSet(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index)); break; case DATASET_MANY: plotDataSetStrict(plot, plotable, id); break; case FUNCTION: plotFunction(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index), usedMinX, usedMaxX); break; case FUNCTION_SAMPLE: plotFunctionSample(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index), usedMinX, usedMaxX); break; case BOTH: plotBoth(plot, plotable, id, defaultColors.get(index), defaultShapes.get(index), usedMinX, usedMaxX); break; case BOTH_MANY: plotBothStrict(plot, plotable, id, usedMinX, usedMaxX); break; default: throw new RuntimeException("Unknown type of plotable: " + plotable.getType()); } index++; } return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, showLegend); }
From source file:com.facebook.presto.AbstractTestQueries.java
@Test void testSpecialFloatingPointValues() throws Exception { MaterializedResult actual = computeActual("SELECT nan(), infinity(), -infinity()"); MaterializedTuple tuple = Iterables.getOnlyElement(actual.getMaterializedTuples()); assertEquals(tuple.getField(0), Double.NaN); assertEquals(tuple.getField(1), Double.POSITIVE_INFINITY); assertEquals(tuple.getField(2), Double.NEGATIVE_INFINITY); }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.diagnostics.ApproximationSetViewer.java
/** * Initializes the reference set bounds. *///from w ww. j a v a2s . co m protected void initializeReferenceSetBounds() { if (referenceSet == null) { return; } double domainMin = Double.POSITIVE_INFINITY; double domainMax = Double.NEGATIVE_INFINITY; double rangeMin = Double.POSITIVE_INFINITY; double rangeMax = Double.NEGATIVE_INFINITY; for (Solution solution : referenceSet) { domainMin = Math.min(domainMin, getValue(solution, 0)); domainMax = Math.max(domainMax, getValue(solution, 0)); rangeMin = Math.min(rangeMin, getValue(solution, 1)); rangeMax = Math.max(rangeMax, getValue(solution, 1)); } domainMax += (domainMax - domainMin); rangeMax += (rangeMax - rangeMin); referenceDomainBounds = new Range(domainMin, domainMax); referenceRangeBounds = new Range(rangeMin, rangeMax); }