List of usage examples for java.lang Float compare
public static int compare(float f1, float f2)
From source file:org.esa.nest.gpf.TestGCPSelectionOp.java
private static float sinc(float x) { if (Float.compare(x, 0.0f) == 0) { return 0.0f; } else {/*from w w w .j a va 2 s . c o m*/ return (float) (FastMath.sin(x * Constants.PI) / (x * Constants.PI)); } }
From source file:example.RepoContract.java
public boolean match(RepoContract o) { if (this == o) return true; RepoContract that = (RepoContract) o; if (Float.compare(that.getRepoRate(), getRepoRate()) != 0) return false; if (Float.compare(that.getStartAmount(), getStartAmount()) != 0) return false; if (getPar() != that.getPar()) return false; if (!getCusip().equals(that.getCusip())) return false; if (!getPartID().equals(that.getContraID())) return false; return getContraID().equals(that.getPartID()); }
From source file:gov.nih.nci.ncicb.cadsr.util.BeanPropertyComparator.java
private int compareTo(Object o1, Object o2) { if (o1 instanceof String) return ((String) o1).compareToIgnoreCase((String) o2); else if (o1 instanceof Float && o2 instanceof Float) { return Float.compare((Float) o1, (Float) o2); } else//from www. j a va2 s . co m return (Integer.parseInt(o1.toString()) - Integer.parseInt(o2.toString())); }
From source file:org.diorite.nbt.NbtTagFloat.java
@Override public boolean equals(final Object o) { if (this == o) { return true; }/* www . j av a 2s .c o m*/ if (!(o instanceof NbtTagFloat)) { return false; } if (!super.equals(o)) { return false; } final NbtTagFloat that = (NbtTagFloat) o; return Float.compare(that.value, this.value) == 0; }
From source file:edu.umich.robot.gp.Gamepad.java
public void initializeGamepad(final Controller controller) { if (gpji == null) return;/*from ww w . j a v a 2 s .c o m*/ gpji.addListener("0", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); if (Float.compare(value, 0) != 0) controller.toggleGamepadOverride(); } }); gpji.addListener("1", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); if (Float.compare(value, 0) != 0) controller.toggleSoarRunState(); } }); gpji.addListener("6", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); if (Float.compare(value, 0) != 0) controller.toggleRate(); } }); gpji.addListener("3", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); if (Float.compare(value, 0) != 0) slow = !slow; } }); gpji.addListener("2", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); if (Float.compare(value, 0) != 0) { int index = gpInputScheme.ordinal() + 1; index %= GamepadInputScheme.values().length; gpInputScheme = GamepadInputScheme.values()[index]; logger.info("Input changed to " + gpInputScheme); } } }); gpji.addListener("5", new GamepadListener() { public void stateChanged(String id, float value) { if (Float.compare(value, 0) != 0) { if (output == null) { logger.info("Get/Drop object called: no robot output"); return; } if (output.getCarriedObject() != null) controller.fireGamepadControlEvent(new EffectorDropObjectEvent()); else { VirtualObject target = null; double targetDistance = Double.MAX_VALUE; for (VirtualObject vo : output.getVisibleObjects()) { pose_t me = output.getPose().asLcmType(); pose_t targetPose = vo.getPose().asLcmType(); double distance = LinAlg.squaredDistance(me.pos, targetPose.pos); if (target == null || distance < targetDistance) { target = vo; targetDistance = distance; } } if (target == null) logger.warn("No objects to get."); else controller.fireGamepadControlEvent(new EffectorGetObjectEvent(target.getId())); } } } }); gpji.addListener("4", new GamepadListener() { public void stateChanged(String id, float value) { if (Float.compare(value, 0) != 0) { if (output == null) { logger.info("Open/close/unlock door called: no robot output"); return; } Gateway target = null; double targetDistance = Double.MAX_VALUE; for (Gateway g : output.getAreaDescription().getGateways()) { pose_t me = output.getPose().asLcmType(); pose_t targetPose = g.getPose().asLcmType(); double distance = LinAlg.squaredDistance(me.pos, targetPose.pos); if (target == null || distance < targetDistance) { target = g; targetDistance = distance; } } if (target == null) logger.warn("No door to manipulate."); else { Door door = target.getDoor(); switch (door.getState()) { case CLOSED: controller.fireGamepadControlEvent(new DoorOpenEvent(door.getId())); break; case LOCKED: controller.fireGamepadControlEvent(new DoorUnlockEvent(door.getId(), door.getCode())); break; case OPEN: controller.fireGamepadControlEvent(new DoorCloseEvent(door.getId())); break; } controller.fireGamepadControlEvent(new EffectorGetObjectEvent(target.getId())); } } } }); gpji.addListener("LY", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); ly = value; update(controller); } }); gpji.addListener("RX", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); rx = value; update(controller); } }); gpji.addListener("RY", new GamepadListener() { public void stateChanged(String id, float value) { if (logger.isTraceEnabled()) logger.trace(id + ": " + value); ry = value; update(controller); } }); }
From source file:com.gs.collections.impl.jmh.map.ChainMapPutTest.java
@Benchmark public scala.collection.mutable.HashMap<String, String> scala() { int localSize = this.size; if (Float.compare(this.loadFactor, 0.75f) != 0) { throw new IllegalArgumentException(); }/* w w w. j a v a 2 s .c om*/ String[] localElements = this.elements; /** * @see HashTable#initialSize() */ int defaultInitialSize = 16; scala.collection.mutable.HashMap<String, String> scala = this.isPresized ? new PresizableHashMap<>(localSize) : new PresizableHashMap<>(defaultInitialSize); for (int i = 0; i < localSize; i++) { scala.put(localElements[i], "dummy"); } return scala; }
From source file:org.diorite.utils.math.DioriteRandom.java
public float getRandFloat(final float min, final float max) throws IllegalArgumentException { if (Float.compare(min, max) == 0) { return max; }//from w w w . jav a 2 s .c o m Validate.isTrue(max > min, "Max can't be smaller than min!"); return (this.nextFloat() * (max - min)) + min; }
From source file:ml.shifu.shifu.core.dtrain.nn.NNWorker.java
@Override public void load(GuaguaWritableAdapter<LongWritable> currentKey, GuaguaWritableAdapter<Text> currentValue, WorkerContext<NNParams, NNParams> workerContext) { super.count += 1; if ((super.count) % 5000 == 0) { LOG.info("Read {} records.", super.count); }//from w w w .j a v a 2s. co m float[] inputs = new float[super.featureInputsCnt]; float[] ideal = new float[super.outputNodeCount]; if (super.isDry) { // dry train, use empty data. addDataPairToDataSet(0, new BasicFloatMLDataPair(new BasicFloatMLData(inputs), new BasicFloatMLData(ideal))); return; } long hashcode = 0; float significance = 1f; // use guava Splitter to iterate only once // use NNConstants.NN_DEFAULT_COLUMN_SEPARATOR to replace getModelConfig().getDataSetDelimiter(), super follows // the function in akka mode. int index = 0, inputsIndex = 0, outputIndex = 0; String[] fields = Lists.newArrayList(this.splitter.split(currentValue.getWritable().toString())) .toArray(new String[0]); int pos = 0; for (pos = 0; pos < fields.length;) { String input = fields[pos]; // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f) float floatValue = input.length() == 0 ? 0f : NumberFormatUtils.getFloat(input, 0f); // no idea about why NaN in input data, we should process it as missing value TODO , according to norm type floatValue = (Float.isNaN(floatValue) || Double.isNaN(floatValue)) ? 0f : floatValue; if (pos == fields.length - 1) { // do we need to check if not weighted directly set to 1f; if such logic non-weight at first, then // weight, how to process??? if (StringUtils.isBlank(modelConfig.getWeightColumnName())) { significance = 1f; // break here if we reach weight column which is last column break; } // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 1f) significance = input.length() == 0 ? 1f : NumberFormatUtils.getFloat(input, 1f); // if invalid weight, set it to 1f and warning in log if (Float.compare(significance, 0f) < 0) { LOG.warn( "The {} record in current worker weight {} is less than 0f, it is invalid, set it to 1.", count, significance); significance = 1f; } // the last field is significance, break here break; } else { ColumnConfig columnConfig = super.columnConfigList.get(index); if (columnConfig != null && columnConfig.isTarget()) { if (isLinearTarget || modelConfig.isRegression()) { ideal[outputIndex++] = floatValue; } else { if (modelConfig.getTrain().isOneVsAll()) { // if one vs all, set correlated idea value according to trainerId which means in trainer // with id 0, target 0 is treated with 1, other are 0. Such target value are set to index of // tags like [0, 1, 2, 3] compared with ["a", "b", "c", "d"] ideal[outputIndex++] = Float.compare(floatValue, trainerId) == 0 ? 1f : 0f; } else { if (modelConfig.getTags().size() == 2) { // if only 2 classes, output node is 1 node. if target = 0 means 0 is the index for // positive prediction, set positive to 1 and negative to 0 int ideaIndex = (int) floatValue; ideal[0] = ideaIndex == 0 ? 1f : 0f; } else { // for multiple classification int ideaIndex = (int) floatValue; ideal[ideaIndex] = 1f; } } } pos++; } else { if (subFeatureSet.contains(index)) { if (columnConfig.isMeta() || columnConfig.isForceRemove()) { // it shouldn't happen here pos += 1; } else if (columnConfig != null && columnConfig.isNumerical() && modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ONEHOT)) { for (int k = 0; k < columnConfig.getBinBoundary().size() + 1; k++) { String tval = fields[pos]; // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f) float fval = tval.length() == 0 ? 0f : NumberFormatUtils.getFloat(tval, 0f); // no idea about why NaN in input data, we should process it as missing value TODO , // according to norm type fval = (Float.isNaN(fval) || Double.isNaN(fval)) ? 0f : fval; inputs[inputsIndex++] = fval; pos++; } } else if (columnConfig != null && columnConfig.isCategorical() && (modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ZSCALE_ONEHOT) || modelConfig.getNormalizeType() .equals(ModelNormalizeConf.NormType.ONEHOT))) { for (int k = 0; k < columnConfig.getBinCategory().size() + 1; k++) { String tval = fields[pos]; // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f) float fval = tval.length() == 0 ? 0f : NumberFormatUtils.getFloat(tval, 0f); // no idea about why NaN in input data, we should process it as missing value TODO , // according to norm type fval = (Float.isNaN(fval) || Double.isNaN(fval)) ? 0f : fval; inputs[inputsIndex++] = fval; pos++; } } else { inputs[inputsIndex++] = floatValue; pos++; } hashcode = hashcode * 31 + Double.valueOf(floatValue).hashCode(); } else { if (!CommonUtils.isToNormVariable(columnConfig, hasCandidates, modelConfig.isRegression())) { pos += 1; } else if (columnConfig.isNumerical() && modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ONEHOT) && columnConfig.getBinBoundary() != null && columnConfig.getBinBoundary().size() > 0) { pos += (columnConfig.getBinBoundary().size() + 1); } else if (columnConfig.isCategorical() && (modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ZSCALE_ONEHOT) || modelConfig.getNormalizeType() .equals(ModelNormalizeConf.NormType.ONEHOT)) && columnConfig.getBinCategory().size() > 0) { pos += (columnConfig.getBinCategory().size() + 1); } else { pos += 1; } } } } index += 1; } if (index != this.columnConfigList.size() || pos != fields.length - 1) { throw new RuntimeException("Wrong data indexing. ColumnConfig index = " + index + ", while it should be " + columnConfigList.size() + ". " + "Data Pos = " + pos + ", while it should be " + (fields.length - 1)); } // output delimiter in norm can be set by user now and if user set a special one later changed, this exception // is helped to quick find such issue. if (inputsIndex != inputs.length) { String delimiter = workerContext.getProps().getProperty(Constants.SHIFU_OUTPUT_DATA_DELIMITER, Constants.DEFAULT_DELIMITER); throw new RuntimeException("Input length is inconsistent with parsing size. Input original size: " + inputs.length + ", parsing size:" + inputsIndex + ", delimiter:" + delimiter + "."); } // sample negative only logic here if (modelConfig.getTrain().getSampleNegOnly()) { if (this.modelConfig.isFixInitialInput()) { // if fixInitialInput, sample hashcode in 1-sampleRate range out if negative records int startHashCode = (100 / this.modelConfig.getBaggingNum()) * this.trainerId; // here BaggingSampleRate means how many data will be used in training and validation, if it is 0.8, we // should take 1-0.8 to check endHashCode int endHashCode = startHashCode + Double.valueOf((1d - this.modelConfig.getBaggingSampleRate()) * 100).intValue(); if ((modelConfig.isRegression() || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or // onevsall && (int) (ideal[0] + 0.01d) == 0 // negative record && isInRange(hashcode, startHashCode, endHashCode)) { return; } } else { // if not fixed initial input, and for regression or onevsall multiple classification (regression also). // if negative record if ((modelConfig.isRegression() || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or // onevsall && (int) (ideal[0] + 0.01d) == 0 // negative record && Double.compare(super.sampelNegOnlyRandom.nextDouble(), this.modelConfig.getBaggingSampleRate()) >= 0) { return; } } } FloatMLDataPair pair = new BasicFloatMLDataPair(new BasicFloatMLData(inputs), new BasicFloatMLData(ideal)); // up sampling logic, just add more weights while bagging sampling rate is still not changed if (modelConfig.isRegression() && isUpSampleEnabled() && Double.compare(ideal[0], 1d) == 0) { // Double.compare(ideal[0], 1d) == 0 means positive tags; sample + 1 to avoid sample count to 0 pair.setSignificance(significance * (super.upSampleRng.sample() + 1)); } else { pair.setSignificance(significance); } boolean isValidation = false; if (workerContext.getAttachment() != null && workerContext.getAttachment() instanceof Boolean) { isValidation = (Boolean) workerContext.getAttachment(); } boolean isInTraining = addDataPairToDataSet(hashcode, pair, isValidation); // do bagging sampling only for training data if (isInTraining) { float subsampleWeights = sampleWeights(pair.getIdealArray()[0]); if (isPositive(pair.getIdealArray()[0])) { this.positiveSelectedTrainCount += subsampleWeights * 1L; } else { this.negativeSelectedTrainCount += subsampleWeights * 1L; } // set weights to significance, if 0, significance will be 0, that is bagging sampling pair.setSignificance(pair.getSignificance() * subsampleWeights); } else { // for validation data, according bagging sampling logic, we may need to sampling validation data set, while // validation data set are only used to compute validation error, not to do real sampling is ok. } }
From source file:org.opencms.ui.contextmenu.CmsContextMenuTreeBuilder.java
/** * Builds a tree from a list of available context menu items.<p> * * The root node of the returned tree has no useful data, its child nodes correspond to the top-level * entries of the ccontext menu.//from w w w . jav a2s . c om * * @param items the available context menu items * @return the context menu item tree */ public CmsTreeNode<I_CmsContextMenuItem> buildTree(List<I_CmsContextMenuItem> items) { items = Lists.newArrayList(items); // First sort by priority and then use a map with the id as the key to store the items, // eliminating items with the same id but a lower priority than another item Collections.sort(items, new Comparator<I_CmsContextMenuItem>() { public int compare(I_CmsContextMenuItem a, I_CmsContextMenuItem b) { return Integer.compare(a.getPriority(), b.getPriority()); } }); LinkedHashMap<String, I_CmsContextMenuItem> itemsById = Maps.newLinkedHashMap(); for (I_CmsContextMenuItem item : items) { String id = item.getId(); I_CmsContextMenuItem prevItem = itemsById.get(id); if (prevItem != null) { LOG.info("Discarding overridden context menu item " + prevItem + " because of higher priority item " + item); } itemsById.put(id, item); } // Now sort by order. Since all children of a node should be processed in one iteration of the following loop, // this order also applies to the child order of each tree node built in the next step List<I_CmsContextMenuItem> uniqueItems = Lists.newArrayList(itemsById.values()); uniqueItems = filterVisible(uniqueItems); if (m_context.getResources().size() == 1) { m_defaultActionItem = findDefaultAction(uniqueItems); } Collections.sort(uniqueItems, new Comparator<I_CmsContextMenuItem>() { public int compare(I_CmsContextMenuItem a, I_CmsContextMenuItem b) { return Float.compare(a.getOrder(), b.getOrder()); } }); Set<String> processedIds = Sets.newHashSet(); boolean changed = true; Map<String, CmsTreeNode<I_CmsContextMenuItem>> treesById = Maps.newHashMap(); // Create childless tree node for each item for (I_CmsContextMenuItem item : itemsById.values()) { CmsTreeNode<I_CmsContextMenuItem> node = new CmsTreeNode<I_CmsContextMenuItem>(); node.setData(item); treesById.put(item.getId(), node); } CmsTreeNode<I_CmsContextMenuItem> root = new CmsTreeNode<I_CmsContextMenuItem>(); // Use null as the root node, which does not have any useful data treesById.put(null, root); // Iterate through list multiple times, each time only processing those items whose parents // we have encountered in a previous iteration (actually, in the last iteration). We do this so that the resulting // tree is actually a tree and contains no cycles, even if there is a reference cycle between the context menu items via their parent ids. // (Items which form such a cycle will never be reached.) while (changed) { changed = false; Iterator<I_CmsContextMenuItem> iterator = uniqueItems.iterator(); Set<String> currentLevel = Sets.newHashSet(); while (iterator.hasNext()) { I_CmsContextMenuItem currentItem = iterator.next(); String parentId = currentItem.getParentId(); if ((parentId == null) || processedIds.contains(parentId)) { changed = true; iterator.remove(); currentLevel.add(currentItem.getId()); treesById.get(parentId).addChild(treesById.get(currentItem.getId())); } } processedIds.addAll(currentLevel); } return root; }
From source file:eu.itesla_project.modules.histo.tools.HistoDbPrintVoltageRangeTool.java
@Override public void run(CommandLine line) throws Exception { Interval interval = Interval.parse(line.getOptionValue("interval")); Path caseFile = Paths.get(line.getOptionValue("case-file")); Map<String, VoltageStats> ranges = new HashMap<>(); Network network = Importers.loadNetwork(caseFile); if (network == null) { throw new RuntimeException("Case '" + caseFile + "' not found"); }/*from w ww . java 2 s.c o m*/ network.getStateManager().allowStateMultiThreadAccess(true); OfflineConfig config = OfflineConfig.load(); try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create()) { Set<HistoDbAttributeId> attrIds = new LinkedHashSet<>(); for (VoltageLevel vl : network.getVoltageLevels()) { attrIds.add(new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.V)); } HistoDbStats stats = histoDbClient.queryStats(attrIds, interval, HistoDbHorizon.SN, false); for (VoltageLevel vl : network.getVoltageLevels()) { HistoDbNetworkAttributeId attrId = new HistoDbNetworkAttributeId(vl.getId(), HistoDbAttr.V); float min = stats.getValue(HistoDbStatsType.MIN, attrId, Float.NaN) / vl.getNominalV(); float max = stats.getValue(HistoDbStatsType.MAX, attrId, Float.NaN) / vl.getNominalV(); int count = (int) stats.getValue(HistoDbStatsType.COUNT, attrId, 0); VoltageStats vstats = new VoltageStats(Range.closed(min, max), count, vl.getNominalV()); for (Generator g : vl.getGenerators()) { vstats.pmax += g.getMaxP(); } ranges.put(vl.getId(), vstats); } } Table table = new Table(7, BorderStyle.CLASSIC_WIDE); table.addCell("ID"); table.addCell("vnom"); table.addCell("range"); table.addCell("min"); table.addCell("max"); table.addCell("count"); table.addCell("pmax"); ranges.entrySet().stream().sorted((e1, e2) -> { VoltageStats stats1 = e1.getValue(); VoltageStats stats2 = e2.getValue(); Range<Float> r1 = stats1.range; Range<Float> r2 = stats2.range; float s1 = r1.upperEndpoint() - r1.lowerEndpoint(); float s2 = r2.upperEndpoint() - r2.lowerEndpoint(); return Float.compare(s1, s2); }).forEach(e -> { String vlId = e.getKey(); VoltageStats stats = e.getValue(); Range<Float> r = stats.range; float s = r.upperEndpoint() - r.lowerEndpoint(); table.addCell(vlId); table.addCell(Float.toString(stats.vnom)); table.addCell(Float.toString(s)); table.addCell(Float.toString(r.lowerEndpoint())); table.addCell(Float.toString(r.upperEndpoint())); table.addCell(Integer.toString(stats.count)); table.addCell(Float.toString(stats.pmax)); }); System.out.println(table.render()); }