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:org.eclipse.hawkbit.rest.util.FileStreamingUtil.java

private static long copyStreams(final InputStream from, final OutputStream to,
        final FileStreamingProgressListener progressListener, final long start, final long length,
        final String filename) throws IOException {

    final long startMillis = System.currentTimeMillis();
    LOG.trace("Start of copy-streams of file {} from {} to {}", filename, start, length);

    Preconditions.checkNotNull(from);/*from   w  ww. j a  va  2 s .c  om*/
    Preconditions.checkNotNull(to);
    final byte[] buf = new byte[BUFFER_SIZE];
    long total = 0;
    int progressPercent = 1;

    ByteStreams.skipFully(from, start);

    long toRead = length;
    boolean toContinue = true;
    long shippedSinceLastEvent = 0;

    while (toContinue) {
        final int r = from.read(buf);
        if (r == -1) {
            break;
        }

        toRead -= r;
        if (toRead > 0) {
            to.write(buf, 0, r);
            total += r;
            shippedSinceLastEvent += r;
        } else {
            to.write(buf, 0, (int) toRead + r);
            total += toRead + r;
            shippedSinceLastEvent += toRead + r;
            toContinue = false;
        }

        if (progressListener != null) {
            final int newPercent = DoubleMath.roundToInt(total * 100.0 / length, RoundingMode.DOWN);

            // every 10 percent an event
            if (newPercent == 100 || newPercent > progressPercent + 10) {
                progressPercent = newPercent;
                progressListener.progress(length, shippedSinceLastEvent, total);
                shippedSinceLastEvent = 0;
            }
        }
    }

    final long totalTime = System.currentTimeMillis() - startMillis;

    if (total < length) {
        throw new FileStreamingFailedException(filename + ": " + (length - total)
                + " bytes could not be written to client, total time on write: !" + totalTime + " ms");
    }

    LOG.trace("Finished copy-stream of file {} with length {} in {} ms", filename, length, totalTime);

    return total;
}

From source file:com.github.rinde.datgen.pdptw.DatasetGenerator.java

Dataset<GeneratedScenario> doGenerate() {

    final ListeningExecutorService service = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(builder.numThreads));
    final Dataset<GeneratedScenario> dataset = Dataset.naturalOrder();

    final List<ScenarioCreator> jobs = new ArrayList<>();

    final RandomGenerator rng = new MersenneTwister(builder.randomSeed);
    final Map<GeneratorSettings, IdSeedGenerator> rngMap = new LinkedHashMap<>();

    for (final Long urgency : builder.urgencyLevels) {
        for (final Double scale : builder.scaleLevels) {
            for (final Entry<TimeSeriesType, Collection<Range<Double>>> dynLevel : builder.dynamismLevels
                    .asMap().entrySet()) {

                final int reps = builder.numInstances * dynLevel.getValue().size();

                final long urg = urgency * 60 * 1000L;
                // The office hours is the period in which new orders are accepted,
                // it is defined as [0,officeHoursLength).
                final long officeHoursLength;
                if (urg < halfDiagTT) {
                    officeHoursLength = builder.scenarioLengthMs - twoDiagTT - PICKUP_DURATION
                            - DELIVERY_DURATION;
                } else {
                    officeHoursLength = builder.scenarioLengthMs - urg - oneAndHalfDiagTT - PICKUP_DURATION
                            - DELIVERY_DURATION;
                }//from  ww  w.j  a v  a  2  s . c  om

                final int numOrders = DoubleMath.roundToInt(scale * numOrdersPerScale,
                        RoundingMode.UNNECESSARY);

                final ImmutableMap.Builder<String, String> props = ImmutableMap.builder();

                props.put("expected_num_orders", Integer.toString(numOrders));
                props.put("pickup_duration", Long.toString(PICKUP_DURATION));
                props.put("delivery_duration", Long.toString(DELIVERY_DURATION));
                props.put("width_height", String.format("%1.1fx%1.1f", AREA_WIDTH, AREA_WIDTH));

                // TODO store this in TimeSeriesType?
                final RangeSet<Double> rset = TreeRangeSet.create();
                for (final Range<Double> r : dynLevel.getValue()) {
                    rset.add(r);
                }

                // createTimeSeriesGenerator(dynLevel.getKey(), officeHoursLength,
                // numOrders, numOrdersPerScale, props);

                final GeneratorSettings set = GeneratorSettings.builder().setDayLength(builder.scenarioLengthMs)
                        .setOfficeHours(officeHoursLength).setTimeSeriesType(dynLevel.getKey())
                        .setDynamismRangeCenters(builder.dynamismRangeMap.subRangeMap(rset.span()))
                        .setUrgency(urg).setScale(scale).setNumOrders(numOrders).setProperties(props.build())
                        .build();

                final IdSeedGenerator isg = new IdSeedGenerator(rng.nextLong());
                rngMap.put(set, isg);

                for (int i = 0; i < reps; i++) {
                    final LocationGenerator lg = Locations.builder().min(0d).max(AREA_WIDTH).buildUniform();

                    final TimeSeriesGenerator tsg2 = createTimeSeriesGenerator(dynLevel.getKey(),
                            officeHoursLength, numOrders, numOrdersPerScale,
                            ImmutableMap.<String, String>builder());
                    final ScenarioGenerator gen = createGenerator(officeHoursLength, urg, scale, tsg2,
                            set.getDynamismRangeCenters(), lg, builder, numOrdersPerScale);

                    jobs.add(ScenarioCreator.create(isg.next(), set, gen));
                }
            }
        }
    }

    final AtomicLong currentJobs = new AtomicLong(0L);
    final AtomicLong datasetSize = new AtomicLong(0L);

    LOGGER.info(" - Submitting " + jobs.size() + " Jobs");
    for (final ScenarioCreator job : jobs) {
        submitJob(currentJobs, service, job, builder.numInstances, dataset, rngMap, datasetSize);
    }

    final long targetSize = builder.numInstances * builder.dynamismLevels.values().size()
            * builder.scaleLevels.size() * builder.urgencyLevels.size();
    while (datasetSize.get() < targetSize || dataset.size() < targetSize) {
        try {
            // LOGGER.info(" - Waiting, current size ==" + dataset.size());
            Thread.sleep(THREAD_SLEEP_DURATION);
        } catch (final InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    LOGGER.info(" - Shutdown Service, Awaiting Termination");
    service.shutdown();
    try {
        service.awaitTermination(1L, TimeUnit.HOURS);
    } catch (final InterruptedException e) {
        throw new IllegalStateException(e);
    }

    LOGGER.info(" - Returning dataset");

    return dataset;
}

From source file:org.apache.gobblin.salesforce.SalesforceSource.java

/**
 * Compute the target partition size.//from w w w . jav a2 s .c o m
 */
private int computeTargetPartitionSize(Histogram histogram, int minTargetPartitionSize, int maxPartitions) {
    return Math.max(minTargetPartitionSize,
            DoubleMath.roundToInt((double) histogram.totalRecordCount / maxPartitions, RoundingMode.CEILING));
}

From source file:org.sleuthkit.autopsy.timeline.ui.listvew.ListTimeline.java

/**
 * Scroll the table to the given index (if it is not already visible).
 *
 * @param index The index of the item that should be scrolled in to view.
 *///from  w w w. j a v  a 2s.c  o m
private void scrollTo(Integer index) {
    if (visibleEvents.contains(table.getItems().get(index)) == false) {
        table.scrollTo(DoubleMath.roundToInt(index - ((table.getHeight() / DEFAULT_ROW_HEIGHT)) / 2,
                RoundingMode.HALF_EVEN));
    }
}

From source file:com.github.rinde.rinsim.central.arrays.ArraysSolvers.java

static int computeRoundedTravelTime(Measure<Double, Velocity> speed, Measure<Double, Length> dist,
        Unit<Duration> outputTimeUnit) {
    return DoubleMath.roundToInt(RoadModels.computeTravelTime(speed, dist, outputTimeUnit),
            RoundingMode.CEILING);
}

From source file:com.github.rinde.rinsim.central.arrays.ArraysSolvers.java

static int[] toRemainingServiceTimes(GlobalStateObject state, Unit<Duration> outputTimeUnit) {
    final UnmodifiableIterator<VehicleStateObject> iterator = state.getVehicles().iterator();
    final int[] remainingServiceTimes = new int[state.getVehicles().size()];
    for (int i = 0; i < state.getVehicles().size(); i++) {
        remainingServiceTimes[i] = DoubleMath
                .roundToInt(Measure.valueOf(iterator.next().getRemainingServiceTime(), state.getTimeUnit())
                        .doubleValue(outputTimeUnit), RoundingMode.CEILING);
    }//w  w  w .  j  ava 2  s . c o  m
    return remainingServiceTimes;
}

From source file:com.github.rinde.rinsim.central.arrays.ArraysSolvers.java

static int fixTWstart(long start, long time, UnitConverter timeConverter) {
    return DoubleMath.roundToInt(timeConverter.convert(start - time), RoundingMode.CEILING);
}

From source file:com.github.rinde.rinsim.central.arrays.ArraysSolvers.java

static int fixTWend(long end, long time, UnitConverter timeConverter) {
    return DoubleMath.roundToInt(timeConverter.convert(end - time), RoundingMode.FLOOR);
}

From source file:com.github.rinde.datgen.pdptw.DatasetGenerator.java

static ScenarioGenerator createGenerator(final long officeHours, long urgency, double scale,
        TimeSeriesGenerator tsg, final ImmutableRangeMap<Double, Double> dynamismRangeCenters,
        LocationGenerator lg, Builder b, int numOrdersPerScale) {
    final ScenarioGenerator.Builder builder = ScenarioGenerator.builder();

    ModelBuilder<? extends RoadModel, ? extends RoadUser> roadModelBuilder;
    DepotGenerator depotBuilder;//from  w  w w .  j  a v a 2 s .com
    VehicleGenerator vehicleBuilder;
    final List<DynamicSpeeds.Builder> dynamicSpeedsBuilders = new ArrayList<>();
    for (int i = 0; i < b.numberOfShockwaves.size(); i++) {
        dynamicSpeedsBuilders.add(DynamicSpeeds.builder());
    }

    if (!b.graphSup.isPresent()) {
        roadModelBuilder = RoadModelBuilders.plane().withMaxSpeed(VEHICLE_SPEED_KMH)
                .withSpeedUnit(NonSI.KILOMETERS_PER_HOUR).withDistanceUnit(SI.KILOMETER);
        depotBuilder = Depots.singleCenteredDepot();
        vehicleBuilder = Vehicles.builder().capacities(constant(1)).centeredStartPositions()
                .creationTimes(constant(-1L))
                .numberOfVehicles(
                        constant(DoubleMath.roundToInt(VEHICLES_PER_SCALE * scale, RoundingMode.UNNECESSARY)))
                .speeds(constant(VEHICLE_SPEED_KMH)).timeWindowsAsScenario().build();
    } else {
        final Point startingLocation = getCenterMostPoint(b.graphSup.get().get());
        if (b.cacheSup.isPresent() || b.cachePath.isPresent()) {
            roadModelBuilder = CachedDynamicGraphRoadModel
                    .builder(
                            ListenableGraph
                                    .supplier((Supplier<? extends Graph<MultiAttributeData>>) b.graphSup.get()),
                            null, b.cachePath.get())
                    .withSpeedUnit(NonSI.KILOMETERS_PER_HOUR).withDistanceUnit(SI.KILOMETER)
                    .withModificationCheck(false);
        } else {
            roadModelBuilder = RoadModelBuilders
                    .dynamicGraph(ListenableGraph
                            .supplier((Supplier<? extends Graph<MultiAttributeData>>) b.graphSup.get()))
                    .withSpeedUnit(NonSI.KILOMETERS_PER_HOUR).withDistanceUnit(SI.KILOMETER)
                    .withModificationCheck(false);
        }

        depotBuilder = Depots.builder().positions(StochasticSuppliers.constant(startingLocation)).build();
        vehicleBuilder = Vehicles.builder().capacities(constant(1))
                .startPositions(StochasticSuppliers.constant(startingLocation)).creationTimes(constant(-1L))
                .numberOfVehicles(
                        constant(DoubleMath.roundToInt(VEHICLES_PER_SCALE * scale, RoundingMode.UNNECESSARY)))
                .speeds(constant(VEHICLE_SPEED_KMH)).timeWindowsAsScenario().build();

        // dynamic speed events
        for (int i = 0; i < dynamicSpeedsBuilders.size(); i++) {
            final DynamicSpeeds.Builder dynamicSpeedsBuilder = dynamicSpeedsBuilders.get(i);

            dynamicSpeedsBuilder.withGraph((Graph<MultiAttributeData>) b.graphSup.get().get())
                    .creationTimes(constant(-1L)).randomStartConnections()
                    .shockwaveWaitForRecedeDurations(constant(b.scenarioLengthMs / 2))
                    .numberOfShockwaves(StochasticSuppliers.constant(b.numberOfShockwaves.get(i)));
            if (b.shockwaveDurations.isPresent()) {
                dynamicSpeedsBuilder.shockwaveWaitForRecedeDurations(b.shockwaveDurations.get().get(i));
            }
            if (b.shockwaveBehaviours.isPresent()) {
                dynamicSpeedsBuilder.shockwaveBehaviour(b.shockwaveBehaviours.get().get(i));
            }
            if (b.shockwaveExpandingSpeeds.isPresent()) {
                dynamicSpeedsBuilder.shockwaveExpandingSpeed(b.shockwaveExpandingSpeeds.get().get(i));
            }
            if (b.shockwaveRecedingSpeeds.isPresent()) {
                dynamicSpeedsBuilder.shockwaveRecedingSpeed(b.shockwaveRecedingSpeeds.get().get(i));
            }
            if (b.shockwaveCreationTimes.isPresent()) {
                dynamicSpeedsBuilder.creationTimes(b.shockwaveCreationTimes.get().get(i));
            }
        }

        ImmutableList<DynamicSpeedGenerator> dsg;
        if (b.numberOfShockwaves.isEmpty()) {
            dsg = (ImmutableList<DynamicSpeedGenerator>) DynamicSpeeds.zeroEvents();
        } else {
            final List<DynamicSpeedGenerator> dsgList = new ArrayList<>();
            for (final DynamicSpeeds.Builder dsb : dynamicSpeedsBuilders) {
                dsgList.add(dsb.build());
            }
            dsg = ImmutableList.copyOf(dsgList);
        }
        builder.dynamicSpeedGenerators(dsg);
    }

    builder
            // global
            .addModel(TimeModel.builder().withRealTime().withStartInClockMode(ClockMode.SIMULATED)
                    .withTickLength(TICK_SIZE).withTimeUnit(SI.MILLI(SI.SECOND)))
            .scenarioLength(b.scenarioLengthMs)
            .setStopCondition(StopConditions.and(StatsStopConditions.vehiclesDoneAndBackAtDepot(),
                    StatsStopConditions.timeOutEvent()))
            // parcels
            .parcels(
                    Parcels.builder()
                            .announceTimes(TimeSeries.filter(
                                    TimeSeries.filter(tsg,
                                            TimeSeries.numEventsPredicate(DoubleMath.roundToInt(
                                                    numOrdersPerScale * scale, RoundingMode.UNNECESSARY))),
                                    new Predicate<List<Double>>() {
                                        @Override
                                        public boolean apply(@Nullable List<Double> input) {
                                            final double dynamism = Metrics
                                                    .measureDynamism(verifyNotNull(input), officeHours);
                                            final boolean isInBin = dynamismRangeCenters.get(dynamism) != null;
                                            if (isInBin) {
                                                System.out.println("Dynamism " + dynamism + " is in bin!");
                                            }
                                            return isInBin;
                                        }
                                    }))
                            .pickupDurations(constant(PICKUP_DURATION))
                            .deliveryDurations(constant(DELIVERY_DURATION)).neededCapacities(constant(0))
                            .locations(lg).withGraph(b.graphSup)
                            .timeWindows(new CustomTimeWindowGenerator(urgency)).build())

            // vehicles
            .vehicles(vehicleBuilder)

            // depots
            .depots(depotBuilder);

    // models
    builder.addModel(PDPDynamicGraphRoadModel
            .builderForDynamicGraphRm(
                    (ModelBuilder<? extends DynamicGraphRoadModel, ? extends RoadUser>) roadModelBuilder)
            .withAllowVehicleDiversion(true));
    builder.addModel(DefaultPDPModel.builder().withTimeWindowPolicy(TimeWindowPolicies.TARDY_ALLOWED));

    return builder.build();
}

From source file:org.smartdeveloperhub.harvesters.it.testing.generator.ProjectActivityGenerator.java

private Duration estimateEffort(final LocalDateTime start, final LocalDateTime dueTo) {
    final Days daysBetween = Days.daysBetween(start, dueTo);
    int workingDays = 0;
    for (int i = 0; i < daysBetween.getDays(); i++) {
        if (Utils.isWorkingDay(start.toLocalDate().plusDays(i))) {
            workingDays++;/*from www.ja va2  s  .  c  om*/
        }
    }
    final int maxMinutes = workingDays * this.workDay.effortPerDay();
    final double ratio = (100 + this.random.nextInt(900)) / 1000d;
    Duration result = Duration.standardMinutes(
            33 * maxMinutes / 100 + DoubleMath.roundToInt(67 * maxMinutes / 100 * ratio, RoundingMode.CEILING));
    if (result.isShorterThan(MINIMUM_EFFORT)) {
        result = MINIMUM_EFFORT;
    }
    return result;
}