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

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

Introduction

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

Prototype

@GwtIncompatible("#roundIntermediate")
public static long roundToLong(double x, RoundingMode mode) 

Source Link

Document

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

Usage

From source file:org.apache.beam.runners.dataflow.worker.IsmSinkFactory.java

@Override
public Sink<?> create(CloudObject spec, Coder<?> coder, PipelineOptions options,
        @Nullable DataflowExecutionContext executionContext, DataflowOperationContext operationContext)
        throws Exception {

    // The validity of this coder is checked in detail by the typed create, below
    @SuppressWarnings("unchecked")
    Coder<WindowedValue<IsmRecord<Object>>> typedCoder = (Coder<WindowedValue<IsmRecord<Object>>>) coder;

    String filename = getString(spec, WorkerPropertyNames.FILENAME);

    checkArgument(typedCoder instanceof WindowedValueCoder, "%s only supports using %s but got %s.",
            IsmSink.class, WindowedValueCoder.class, typedCoder);
    WindowedValueCoder<IsmRecord<Object>> windowedCoder = (WindowedValueCoder<IsmRecord<Object>>) typedCoder;

    checkArgument(windowedCoder.getValueCoder() instanceof IsmRecordCoder,
            "%s only supports using %s but got %s.", IsmSink.class, IsmRecordCoder.class,
            windowedCoder.getValueCoder());
    @SuppressWarnings("unchecked")
    IsmRecordCoder<Object> ismCoder = (IsmRecordCoder<Object>) windowedCoder.getValueCoder();

    long bloomFilterSizeLimitBytes = Math.max(MIN_BLOOM_FILTER_SIZE_BYTES,
            DoubleMath.roundToLong(BLOOM_FILTER_SIZE_LIMIT_MULTIPLIER
                    * options.as(DataflowWorkerHarnessOptions.class).getWorkerCacheMb()
                    // Note the conversion from MiB to bytes
                    * 1024 * 1024, RoundingMode.DOWN));

    return new IsmSink<>(FileSystems.matchNewResource(filename, false), ismCoder, bloomFilterSizeLimitBytes);
}

From source file:com.github.rinde.rinsim.examples.demo.factory.AgvModel.java

void init() {
    if (simulator.isPresent() && rm.isPresent()) {
        int max = 0;
        for (final List<Point> ps : points) {
            max = Math.max(max, ps.size());
        }//w w  w . ja v  a 2s .  co m
        final int num = max;
        for (int i = 0; i < num; i++) {
            final long duration = DoubleMath.roundToLong(
                    FactoryExample.SERVICE_DURATION / 2d + rng.nextDouble() * FactoryExample.SERVICE_DURATION,
                    RoundingMode.CEILING);

            final Point rnd = rndBorder();
            Point dest;
            if (i >= points.get(0).size()) {
                dest = rndBorder();
            } else {
                dest = points.get(0).get(i);
                occupiedPositions.add(dest);
            }

            final BoxHandle bh = new BoxHandle(i);
            final Box b = new Box(rnd, dest, duration, bh);
            bh.box = b;

            boxes.add(bh);
            simulator.get().register(verifyNotNull(boxes.get(boxes.size() - 1).box));
        }
    }
}

From source file:com.github.rinde.rinsim.core.model.road.PlaneRoadModel.java

@Override
protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) {
    final long startTimeConsumed = time.getTimeConsumed();
    Point loc = objLocs.get(object);

    double traveled = 0;
    final double speed = min(unitConversion.toInSpeed(object.getSpeed()), maxSpeed);
    if (speed == 0d) {
        // FIXME add test for this case, also check GraphRoadModel
        final Measure<Double, Length> dist = Measure.valueOf(0d, getDistanceUnit());
        final Measure<Long, Duration> dur = Measure.valueOf(0L, time.getTimeUnit());
        return MoveProgress.create(dist, dur, new ArrayList<Point>());
    }/*from   ww  w  . j  av a  2 s  .  com*/

    final List<Point> travelledNodes = new ArrayList<>();
    while (time.hasTimeLeft() && !path.isEmpty()) {
        checkArgument(isPointInBoundary(path.peek()),
                "points in the path must be within the predefined boundary of the " + "plane");

        // distance in internal time unit that can be traveled with timeleft
        final double travelDistance = speed * unitConversion.toInTime(time.getTimeLeft(), time.getTimeUnit());
        final double stepLength = unitConversion.toInDist(Point.distance(loc, path.peek()));

        if (travelDistance >= stepLength) {
            loc = path.remove();
            travelledNodes.add(loc);

            final long timeSpent = DoubleMath.roundToLong(
                    unitConversion.toExTime(stepLength / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN);
            time.consume(timeSpent);
            traveled += stepLength;
        } else {
            final Point diff = Point.diff(path.peek(), loc);

            if (stepLength - travelDistance < DELTA) {
                loc = path.peek();
                traveled += stepLength;
            } else {
                final double perc = travelDistance / stepLength;
                loc = new Point(loc.x + perc * diff.x, loc.y + perc * diff.y);
                traveled += travelDistance;
            }
            time.consumeAll();

        }
    }
    objLocs.put(object, loc);

    // convert to external units
    final Measure<Double, Length> distTraveled = unitConversion.toExDistMeasure(traveled);
    final Measure<Long, Duration> timeConsumed = Measure.valueOf(time.getTimeConsumed() - startTimeConsumed,
            time.getTimeUnit());
    return MoveProgress.create(distTraveled, timeConsumed, travelledNodes);
}

From source file:veloziped.ws1516.disposal.PurchasingDisposal.java

private long calcNeededConsumption(long consumInDeliverTime, long missing) {

    double bufferFact = SharedInstance.getInstance().getBufferFactor();
    double neededCon = ((double) consumInDeliverTime + missing) * (1 + bufferFact);
    long neededConsumption = 0;

    switch (SharedInstance.getInstance().getCalculationMode()) {
    case OPTIMISTIC:
        neededConsumption = DoubleMath.roundToLong(neededCon, RoundingMode.DOWN);

        //10er losgren
        if (neededConsumption % 10 != 0) {
            neededConsumption += neededConsumption % 10;
        }/*  w  ww.j a  va 2 s.c  o m*/
    case PESSIMISTIC:
        neededConsumption = DoubleMath.roundToLong(neededCon, RoundingMode.CEILING);

        //10er losgren
        if (neededConsumption % 10 != 0) {
            neededConsumption -= neededConsumption % 10;
        }
    }
    return neededConsumption;
}

From source file:com.github.rinde.rinsim.examples.demo.factory.AgvModel.java

@Override
public void handleEvent(Event e) {
    verify(e instanceof PDPModelEvent);
    final PDPModelEvent event = (PDPModelEvent) e;
    final Box box = (Box) verifyNotNull(event.parcel);
    if (e.getEventType() == PDPModelEventType.END_PICKUP) {
        occupiedPositions.remove(box.getPickupLocation());
    }/* w  ww  .jav  a2s  . c  o  m*/
    if (e.getEventType() == PDPModelEventType.END_DELIVERY) {
        final long duration = DoubleMath.roundToLong(
                FactoryExample.SERVICE_DURATION / 2d + rng.nextDouble() * FactoryExample.SERVICE_DURATION,
                RoundingMode.CEILING);
        simulator.get().unregister(box);

        final BoxHandle bh = box.boxHandle;
        bh.wordIndex = (bh.wordIndex + 1) % points.size();

        Point dest;
        if (bh.index >= points.get(bh.wordIndex).size()) {
            dest = rndBorder();
        } else {
            dest = points.get(bh.wordIndex).get(bh.index);
            occupiedPositions.add(dest);
        }

        final Box newBox = new Box(box.getDeliveryLocation(), dest, duration, bh);
        bh.box = newBox;

        simulator.get().register(newBox);
    }
}

From source file:gobblin.salesforce.SalesforceSource.java

String generateSpecifiedPartitions(Histogram histogram, int maxPartitions, long expectedHighWatermark) {
    long interval = DoubleMath.roundToLong((double) histogram.totalRecordCount / maxPartitions,
            RoundingMode.CEILING);
    int totalGroups = histogram.getGroups().size();

    log.info("Histogram total record count: " + histogram.totalRecordCount);
    log.info("Histogram total groups: " + totalGroups);
    log.info("maxPartitions: " + maxPartitions);
    log.info("interval: " + interval);

    List<HistogramGroup> groups = histogram.getGroups();
    List<String> partitionPoints = new ArrayList<>();
    DescriptiveStatistics statistics = new DescriptiveStatistics();

    int count = 0;
    HistogramGroup group;/*from  w ww . j  a  v  a  2  s  . c o  m*/
    Iterator<HistogramGroup> it = groups.iterator();
    while (it.hasNext()) {
        group = it.next();
        if (count == 0) {
            // Add a new partition point;
            partitionPoints
                    .add(Utils.toDateTimeFormat(group.getKey(), DAY_FORMAT, Partitioner.WATERMARKTIMEFORMAT));
        }

        // Move the candidate to a new bucket if the attempted total is 2x of interval
        if (count != 0 && count + group.count >= 2 * interval) {
            // Summarize current group
            statistics.addValue(count);
            // A step-in start
            partitionPoints
                    .add(Utils.toDateTimeFormat(group.getKey(), DAY_FORMAT, Partitioner.WATERMARKTIMEFORMAT));
            count = group.count;
        } else {
            // Add group into current partition
            count += group.count;
        }

        if (count >= interval) {
            // Summarize current group
            statistics.addValue(count);
            // A fresh start next time
            count = 0;
        }
    }

    // If the last group is used as the last partition point
    if (count == 0) {
        // Exchange the last partition point with global high watermark
        partitionPoints.set(partitionPoints.size() - 1, Long.toString(expectedHighWatermark));
    } else {
        // Summarize last group
        statistics.addValue(count);
        // Add global high watermark as last point
        partitionPoints.add(Long.toString(expectedHighWatermark));
    }

    log.info("Dynamic partitioning statistics: ");
    log.info("data: " + Arrays.toString(statistics.getValues()));
    log.info(statistics.toString());
    String specifiedPartitions = Joiner.on(",").join(partitionPoints);
    log.info("Calculated specified partitions: " + specifiedPartitions);
    return specifiedPartitions;
}

From source file:veloziped.ws1516.articles.ExtendedArticle.java

public long getDeliveryTimeNormalInDays(CalculationMode mode) {
    if (null == mode) {
        return 0;
    }//  ww w. j  av a  2  s.c o  m
    double deliverNormal;

    //1 day moving to warehouse
    switch (mode) {
    case OPTIMISTIC:
        //5 days
        deliverNormal = (this.deliverTime - this.deviation) * 5;
        return DoubleMath.roundToLong(deliverNormal, RoundingMode.DOWN) + 1;

    case PESSIMISTIC:
        //5 days
        deliverNormal = (this.deliverTime + this.deviation) * 5;
        return DoubleMath.roundToLong(deliverNormal, RoundingMode.CEILING) + 1;
    default:
        return 0;
    }
}

From source file:org.apache.beam.runners.dataflow.worker.util.ScalableBloomFilter.java

/** Calculate the number of optimal insertions based upon the number of bytes. */
private static long optimalNumInsertions(long bytes, double p) {
    checkArgument(p > 0, "Expected false positive probability to be positive.");
    return LongMath.checkedMultiply(8,
            DoubleMath.roundToLong(-bytes * Math.log(2) * Math.log(2) / Math.log(p), RoundingMode.DOWN));
}

From source file:veloziped.ws1516.costs.Costs.java

private long calcProductionAmountInOvertime(WorkloadResult wRes, ProcessTime time) {
    long result = 0;
    double calc = result = wRes.getOverTimePeriod() / time.getRunTime() - time.getSetupTime();
    try {/*from   w w  w  . j  ava  2 s  . c  o  m*/
        if (calc > 0) {
            result = DoubleMath.roundToLong(calc, RoundingMode.HALF_UP);
        }
    } catch (NumberFormatException ex) {

    }
    return result;
}

From source file:veloziped.ws1516.costs.Costs.java

private long calcProductionAmountInShift(WorkloadResult wRes, ProcessTime time) {
    long result = 0;
    double calc = result = (wRes.getTotalCapacityNeeded() - wRes.getOverTimePeriod()) / time.getRunTime()
            - time.getSetupTime();/*from www. j  a  v a  2s . c o m*/
    try {
        if (calc > 0) {
            result = DoubleMath.roundToLong(calc, RoundingMode.HALF_UP);
        }
    } catch (NumberFormatException ex) {

    }
    return result;
}