Example usage for java.math RoundingMode UNNECESSARY

List of usage examples for java.math RoundingMode UNNECESSARY

Introduction

In this page you can find the example usage for java.math RoundingMode UNNECESSARY.

Prototype

RoundingMode UNNECESSARY

To view the source code for java.math RoundingMode UNNECESSARY.

Click Source Link

Document

Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.

Usage

From source file:alfio.model.PriceContainerTest.java

private Stream<Pair<Integer, PriceContainer>> generateTestStream(PriceContainer.VatStatus vatStatus) {
    List<BigDecimal> vatPercentages = IntStream.range(100, 3000).mapToObj(
            vatCts -> new BigDecimal(vatCts).divide(new BigDecimal("100.00"), 2, RoundingMode.UNNECESSARY))
            .collect(Collectors.toList());
    return IntStream.range(1, 500_00).parallel().boxed().flatMap(i -> vatPercentages.stream()
            .map(vat -> Pair.of(i, new PriceContainerImpl(i, "CHF", vat, vatStatus))));
}

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   w ww . jav a  2  s  .c o m*/

                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: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 av  a2 s.co  m
    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();
}