Example usage for com.google.common.math DoubleMath roundToInt

List of usage examples for com.google.common.math DoubleMath roundToInt

Introduction

In this page you can find the example usage for com.google.common.math DoubleMath roundToInt.

Prototype

@GwtIncompatible("#roundIntermediate")
public static int roundToInt(double x, RoundingMode mode) 

Source Link

Document

Returns the int value that is equal to x rounded with the specified rounding mode, if possible.

Usage

From source file:de.fhg.igd.iva.explorer.main.JStatBar.java

private int mapXToScreen(double val, int width) {
    double min = stats.getMin();
    double max = stats.getMax();

    int barWidth = width - 2 * insetX;

    int value = DoubleMath.roundToInt(barWidth * (val - min) / (max - min), RoundingMode.HALF_UP);

    if (!metric.moreIsBetter())
        value = barWidth - value; // maybe we have to subtract 1px here

    return value;
}

From source file:gobblin.source.extractor.watermark.TimestampWatermark.java

/**
 * recalculate interval(in hours) if total number of partitions greater than maximum number of allowed partitions
 *
 * @param difference in range//from   www . ja  va2s .  c  om
 * @param hour interval (ex: 4 hours)
 * @param Maximum number of allowed partitions
 * @return calculated interval in hours
 */

private static int getInterval(long diffInMilliSecs, long hourInterval, int maxIntervals) {

    long totalHours = DoubleMath.roundToInt((double) diffInMilliSecs / (60 * 60 * 1000), RoundingMode.CEILING);
    long totalIntervals = DoubleMath.roundToInt((double) totalHours / hourInterval, RoundingMode.CEILING);
    if (totalIntervals > maxIntervals) {
        hourInterval = DoubleMath.roundToInt((double) totalHours / maxIntervals, RoundingMode.CEILING);
    }
    return Ints.checkedCast(hourInterval);
}

From source file:org.terasology.world.viewer.layers.FieldFacetLayer.java

/**
 * Computes the color of the facet at a given world coordinate.
 * @param facet the underlying facet/*from   w ww .ja va2 s . c o  m*/
 * @param x the world x coordinate
 * @param z the world z coordinate
 * @return the color at the given world coords. Never <code>null</code>.
 */
protected Color getColor(FieldFacet2D facet, int x, int z) {
    double value = facet.get(x, z);
    if (Double.isFinite(value)) {
        int round = DoubleMath.roundToInt(config.offset + config.scale * value, RoundingMode.HALF_UP);
        int idx = TeraMath.clamp(round, 0, 255);
        return GRAYS.get(idx);
    } else {
        return MISSING;
    }
}

From source file:org.terasology.StaticCities.walls.TownWallRasterizer.java

private void rasterGate(RasterTarget target, GateWallSegment element, HeightMap terrain) {

    int x1 = element.getStart().getX();
    int z1 = element.getStart().getY();
    int y1 = terrain.apply(x1, z1) + element.getWallHeight();
    int x2 = element.getEnd().getX();
    int z2 = element.getEnd().getY();
    int y2 = terrain.apply(x2, z2) + element.getWallHeight();

    Ramp ramp = new Ramp(x1, y1, z1, x2, y2, z2);

    HeightMap hmTop = new HeightMap() {

        @Override// ww w  . java  2  s . co  m
        public int apply(int x, int z) {
            float y = ramp.getY(x, z);
            return DoubleMath.roundToInt(y, RoundingMode.HALF_UP);
        }
    };

    HeightMap hmBottom = new HeightMap() {

        @Override
        public int apply(int x, int z) {
            int top = hmTop.apply(x, z);
            int minHeight = element.getWallHeight() / 3;

            float l = ramp.getLambda(x, z);

            // dist is max. at 0.5 * width
            float zig = Math.abs(0.5f - l);
            float arc = zig * zig * 4; // applying the sqr makes 0.25 the max. So we multiply with 4

            int base = TeraMath.floorToInt((top - minHeight) * (1 - arc));
            return base;
        }
    };

    Pen pen = Pens.fill(target, hmBottom, hmTop, DefaultBlockType.TOWER_WALL);
    RasterUtil.drawLine(pen, new LineSegment(x1, z1, x2, z2));
}

From source file:org.apache.gobblin.source.extractor.watermark.HourWatermark.java

/**
 * recalculate interval(in hours) if total number of partitions greater than maximum number of allowed partitions
 *
 * @param difference in range//from w ww  . ja v  a  2  s.c o m
 * @param hour interval (ex: 4 hours)
 * @param Maximum number of allowed partitions
 * @return calculated interval in hours
 */
private static int getInterval(long diffInMilliSecs, long hourInterval, int maxIntervals) {
    int totalHours = DoubleMath.roundToInt((double) diffInMilliSecs / (60 * 60 * 1000), RoundingMode.CEILING);
    int totalIntervals = DoubleMath.roundToInt((double) totalHours / hourInterval, RoundingMode.CEILING);
    if (totalIntervals > maxIntervals) {
        hourInterval = DoubleMath.roundToInt((double) totalHours / maxIntervals, RoundingMode.CEILING);
    }
    return Ints.checkedCast(hourInterval);
}

From source file:edu.mit.streamjit.impl.compiler2.CompositionAllocationStrategy.java

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    if (group.isStateful()) {
        int minStatefulId = Integer.MAX_VALUE;
        for (Actor a : group.actors())
            if (a instanceof WorkerActor && ((WorkerActor) a).archetype().isStateful())
                minStatefulId = Math.min(minStatefulId, a.id());
        Configuration.SwitchParameter<Integer> param = config.getParameter("Group" + minStatefulId + "Core",
                Configuration.SwitchParameter.class, Integer.class);
        cores.get(param.getValue() % cores.size()).allocate(group, iterations);
        return;/*from  www . j  a v a  2  s. c om*/
    }

    Configuration.CompositionParameter param = config.getParameter("Group" + group.id() + "Cores",
            Configuration.CompositionParameter.class);
    assert iterations.lowerBoundType() == BoundType.CLOSED && iterations.upperBoundType() == BoundType.OPEN;
    int totalAvailable = iterations.upperEndpoint() - iterations.lowerEndpoint();
    int[] allocations = new int[cores.size()];
    int totalAllocated = 0;
    for (int i = 0; i < param.getLength() && i < allocations.length; ++i) {
        int allocation = DoubleMath.roundToInt(param.getValue(i) * totalAvailable, RoundingMode.HALF_EVEN);
        allocations[i] = allocation;
        totalAllocated += allocation;
    }
    //If we allocated more than we have, remove from the cores with the least.
    //Need a loop here because we might not have enough on the least core.
    while (totalAllocated > totalAvailable) {
        int least = Ints.indexOf(allocations, Ints.max(allocations));
        for (int i = 0; i < allocations.length; ++i)
            if (allocations[i] > 0 && allocations[i] < allocations[least])
                least = i;
        int toRemove = Math.min(allocations[least], totalAllocated - totalAvailable);
        allocations[least] -= toRemove;
        totalAllocated -= toRemove;
    }
    //If we didn't allocate enough, allocate on the cores with the most.
    if (totalAllocated < totalAvailable) {
        int most = Ints.indexOf(allocations, Ints.min(allocations));
        for (int i = 0; i < allocations.length; ++i)
            if (allocations[i] > allocations[most])
                most = i;
        allocations[most] += totalAvailable - totalAllocated;
        totalAllocated += totalAvailable - totalAllocated;
    }
    assert totalAllocated == totalAvailable : totalAllocated + " " + totalAvailable;

    int lower = iterations.lowerEndpoint();
    for (int i = 0; i < allocations.length; ++i)
        if (allocations[i] > 0) {
            cores.get(i).allocate(group, Range.closedOpen(lower, lower + allocations[i]));
            lower += allocations[i];
        }
}

From source file:org.apache.gobblin.source.extractor.watermark.DateWatermark.java

/**
 * recalculate interval(in hours) if total number of partitions greater than maximum number of allowed partitions
 *
 * @param difference in range/*from   w  ww.  j a  v a  2 s  . c  o m*/
 * @param hour interval (ex: 4 hours)
 * @param Maximum number of allowed partitions
 * @return calculated interval in days
 */
private static int getInterval(long diffInMilliSecs, long hourInterval, int maxIntervals) {
    long dayInterval = TimeUnit.HOURS.toDays(hourInterval);
    int totalHours = DoubleMath.roundToInt((double) diffInMilliSecs / (60 * 60 * 1000), RoundingMode.CEILING);
    int totalIntervals = DoubleMath.roundToInt((double) totalHours / (dayInterval * 24), RoundingMode.CEILING);
    if (totalIntervals > maxIntervals) {
        hourInterval = DoubleMath.roundToInt((double) totalHours / maxIntervals, RoundingMode.CEILING);
        dayInterval = DoubleMath.roundToInt((double) hourInterval / 24, RoundingMode.CEILING);
    }
    return Ints.checkedCast(dayInterval);
}

From source file:com.github.rinde.rinsim.experiment.JppfComputer.java

@Override
public ExperimentResults compute(Builder builder, Set<SimArgs> inputs) {
    final IdMap<MASConfiguration> configMap = new IdMap<>("c", MASConfiguration.class);
    final IdMap<ScenarioProvider> scenarioMap = new IdMap<>("s", ScenarioProvider.class);

    final List<ResultListener> listeners = new ArrayList<>(builder.resultListeners);

    @SuppressWarnings({ "rawtypes", "unchecked" })
    final IdMap<PostProcessor<?>> ppMap = new IdMap("p", PostProcessor.class);
    final Map<String, Scenario> scenariosMap = new LinkedHashMap<>();

    // create tasks
    final List<SimulationTask> tasks = new ArrayList<>();
    constructTasks(inputs, tasks, configMap, scenarioMap, ppMap, scenariosMap);

    // this sorts tasks using this chain: scenario, configuration, objective
    // function, postprocessor, seed
    Collections.sort(tasks);//from w w w  .  j a  va2  s .  c om

    // determine size of batches
    final int numBatches = Math.min(tasks.size(), builder.numBatches);
    final int batchSize = DoubleMath.roundToInt(tasks.size() / (double) numBatches, RoundingMode.CEILING);

    final Map<Task<?>, JPPFJob> taskJobMap = new LinkedHashMap<>();
    final ResultsCollector res = new ResultsCollector(tasks.size(), scenariosMap, taskJobMap, listeners);
    final List<JPPFJob> jobs = new ArrayList<>();

    final int compositeTaskSize = builder.compositeTaskSize;
    for (int i = 0; i < numBatches; i++) {
        final JPPFJob job = new JPPFJob(new MemoryMapDataProvider(), res);
        job.setName(Joiner.on("").join(JOB_NAME, " ", i + 1, "/", numBatches));
        jobs.add(job);

        final List<SimulationTask> batch = tasks.subList(i * batchSize, (i + 1) * batchSize);

        for (int j = 0; j < batch.size(); j += compositeTaskSize) {

            final List<SimulationTask> compositeTasks = batch.subList(j,
                    Math.min(batch.size(), j + compositeTaskSize));

            for (final SimulationTask t : compositeTasks) {
                final MASConfiguration config = configMap.getValue(t.getConfigurationId());
                final ScenarioProvider scenario = scenarioMap.getValue(t.getScenarioId());
                job.getDataProvider().setParameter(t.getPostProcessorId(),
                        ppMap.getValue(t.getPostProcessorId()));
                job.getDataProvider().setParameter(t.getConfigurationId(), config);
                job.getDataProvider().setParameter(t.getScenarioId(), scenario);

                taskJobMap.put(t, job);
            }

            try {
                if (compositeTasks.size() > 1) {
                    final CompositeTask composite = new CompositeTask(compositeTasks);
                    job.add(composite);
                } else {
                    for (final SimulationTask st : compositeTasks) {
                        job.add(st);
                    }
                }
            } catch (final JPPFException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    checkState(!getJppfClient().isClosed());
    try {
        for (final JPPFJob job : jobs) {
            getJppfClient().submitJob(job);
        }
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
    res.awaitResults();

    final ExperimentResults results = ExperimentResults.create(builder, res.buildResults());
    for (final ResultListener l : listeners) {
        l.doneComputing(results);
    }
    return results;
}

From source file:org.terasology.polyworld.voronoi.GraphFacetProvider.java

private Graph createGraph(WorldRegion wr) {
    Rect2i area = wr.getArea();/*  w  w  w .  j  a  v  a 2  s .  com*/
    if (wr.getType() == RegionType.OCEAN) {
        //            int rows = DoubleMath.roundToInt(area.height() / cellSize, RoundingMode.HALF_UP);
        //            int cols = DoubleMath.roundToInt(area.width() / cellSize, RoundingMode.HALF_UP);
        return createGridGraph(area, 1, 1);
    } else {
        int numSites = DoubleMath.roundToInt(area.area() / configuration.graphDensity, RoundingMode.HALF_UP);
        return createVoronoiGraph(area, numSites);
    }
}

From source file:pojos.ChannelData.java

/**
 * Returns the label of the channel./*from   w  ww.  ja v a2s. c  o m*/
 * Following the specification: Name>Fluor>Emission wavelength>index.
 *
 * @return See above.
 */
public String getChannelLabeling() {
    String value = getName();
    if (StringUtils.isNotBlank(value))
        return value;
    value = getFluor();
    if (StringUtils.isNotBlank(value))
        return value;
    Length v = null;
    try {
        v = getEmissionWavelength(null);
    } catch (BigResult e) {
    }
    if (v != null) {
        return "" + DoubleMath.roundToInt(v.getValue(), RoundingMode.DOWN);
    }
    return "" + index;
}