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:com.github.rinde.rinsim.central.arrays.ArraysSolvers.java

/**
 * Converts the list of points on a plane into a travel time matrix. For
 * distance between two points the euclidean distance is used, i.e. no
 * obstacles or graph structure are considered.
 * @param points The set of points which will be converted to a travel time
 *          matrix.//from w w w. j a  va2  s .  c  o  m
 * @param distUnit The {@link Unit} that is used for distances (
 *          {@link Length}) between the specified points.
 * @param speed The travel speed specified as a {@link Measure} which includes
 *          its {@link Unit}.
 * @param outputTimeUnit The output time {@link Unit} to which all times are
 *          converted, e.g. if {@link SI#SECOND} is specified the travel times
 *          will be in seconds.
 * @param rm When computing the travel times they often need to be rounded.
 *          The rounding mode indicates how numbers are rounded, see
 *          {@link RoundingMode} for the available options.
 * @return A <code>n x n</code> travel time matrix, where <code>n</code> is
 *         the size of the <code>points</code> list.
 */
public static int[][] toTravelTimeMatrix(List<Point> points, Unit<Length> distUnit,
        Measure<Double, Velocity> speed, Unit<Duration> outputTimeUnit, RoundingMode rm) {
    checkArgument(points.size() >= 2);
    final int[][] matrix = new int[points.size()][points.size()];
    for (int i = 0; i < points.size(); i++) {
        for (int j = 0; j < i; j++) {
            if (i != j) {
                // compute distance
                final Measure<Double, Length> dist = Measure
                        .valueOf(Point.distance(points.get(i), points.get(j)), distUnit);
                // calculate duration in desired unit
                final double duration = RoadModels.computeTravelTime(speed, dist, outputTimeUnit);
                // round duration
                final int tt = DoubleMath.roundToInt(duration, rm);
                matrix[i][j] = tt;
                matrix[j][i] = tt;
            }
        }
    }
    return matrix;
}

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

private Graph createGraph(WorldRegion wr) {
    Rect2i area = wr.getArea();/*from  ww w.j  a va 2s  . c  om*/
    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 / 1000,
                RoundingMode.HALF_UP);
        return createVoronoiGraph(area, numSites);
    }
}

From source file:com.ibm.og.scheduling.RequestRateScheduler.java

private int calculateStepWidth(double ops, double warmUp, TimeUnit rampupUnit) {

    double warmUpSeconds = rampupUnit.toSeconds((long) warmUp);
    double slope = ops / warmUpSeconds;

    int width = 1;
    if (slope < 1.0) {
        width = DoubleMath.roundToInt((warmUpSeconds / ops), RoundingMode.DOWN);
    }//www . j  av a2 s. c o  m

    return width;
}

From source file:org.ldp4j.server.utils.CharsetPreference.java

static int round(double weight) {
    Preconditions.checkArgument(weight >= 0D, "Weight must be greater than or equal to 0 (%s)", weight);
    Preconditions.checkArgument(weight <= 1D, "Weight must be lower than or equal to 1 (%s)", weight);
    return DoubleMath.roundToInt(weight * MAX_WEIGHT_DOUBLE, RoundingMode.DOWN);
}

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

static Graph<?> createGraph(ImmutableList<ImmutableList<Point>> points) {
    int max = 0;/*w ww.j  av  a  2  s.c  o m*/
    double xMax = 0;
    double yMax = 0;
    for (final List<Point> ps : points) {
        max = Math.max(max, ps.size());
        for (final Point p : ps) {
            xMax = Math.max(p.x, xMax);
            yMax = Math.max(p.y, yMax);
        }
    }

    int width = DoubleMath.roundToInt(xMax / SPACING, RoundingMode.CEILING);
    width += VERTICAL_LINE_SPACING - width % VERTICAL_LINE_SPACING;
    width += width / VERTICAL_LINE_SPACING % 2 == 0 ? VERTICAL_LINE_SPACING : 0;

    int height = DoubleMath.roundToInt(yMax / SPACING, RoundingMode.CEILING) + 2;
    height += height % 2;
    return createGrid(width, height, 1, VERTICAL_LINE_SPACING, SPACING);
}

From source file:edu.mit.streamjit.util.ilpsolve.ILPSolver.java

public void solve() {
    checkState(!solved, "system already solved");
    checkState(objFn != null, "objective function not set");

    Pointer<lprec> lp = null;//from   w ww .  j a va  2 s . co m
    Pointer<Double> row = null, column = null;
    Path logFile = null;
    try {
        //Row 0 is the objective function.  Col 0 is apparently the right-hand
        //side but the API hides this.
        lp = makeLp(constraints.size(), variables.size());
        row = Pointer.allocateDoubles(variables.size() + 1);
        column = Pointer.allocateDoubles(constraints.size() + 1);
        if (lp == null || row == null || column == null)
            throw new OutOfMemoryError();

        boolean assertionsEnabled = false;
        assert assertionsEnabled = true; //Intentional side effect.
        if (assertionsEnabled) {
            try {
                logFile = Files.createTempFile("lp", null);
            } catch (IOException ignored) {
            }
            Pointer<Byte> emptyString = Pointer.pointerToCString(logFile != null ? logFile.toString() : "");
            setOutputfile(lp, emptyString);
            emptyString.release();
            setVerbose(lp, FULL);
        } else {
            setVerbose(lp, IMPORTANT);
        }

        setAddRowmode(lp, (byte) 1);
        storeCoefficientsInRow(objFn.expr, row);
        setObjFn(lp, row);

        for (int i = 0; i < constraints.size(); ++i) {
            Constraint c = constraints.get(i);
            storeCoefficientsInRow(c.expr, row);
            setRow(lp, i + 1, row);
        }
        setAddRowmode(lp, (byte) 0);

        if (objFn.signum == 1)
            setMaxim(lp);
        else if (objFn.signum == -1)
            setMinim(lp);
        else
            throw new AssertionError(objFn.signum);

        for (int i = 0; i < variables.size(); ++i) {
            Variable v = variables.get(i);
            Pointer<Byte> name = Pointer.pointerToCString(v.name());
            setColName(lp, i + 1, name);
            name.release();

            setBounds(lp, i + 1, v.lowerBound, v.upperBound);
            setInt(lp, i + 1, (byte) 1);
        }

        for (int i = 0; i < constraints.size(); ++i) {
            Constraint c = constraints.get(i);
            setConstrType(lp, i + 1, c.signum);
            column.setDoubleAtIndex(i + 1, c.value);
        }
        setRhVec(lp, column);

        int solret = Bindings.solve(lp);
        if (solret == OPTIMAL) {
            //For some reason get_variables is 0-based unlike the rest of the API.
            getVariables(lp, row);
            for (int i = 0; i < variables.size(); ++i)
                variables.get(i).value = DoubleMath.roundToInt(row.getDoubleAtIndex(i),
                        RoundingMode.UNNECESSARY);
            solved = true;
        } else {
            printLp(lp);
            String log = "";
            if (logFile != null) {
                try {
                    List<String> logLines = Files.readAllLines(logFile, StandardCharsets.UTF_8);
                    StringBuilder sb = new StringBuilder("\n");
                    for (String s : logLines)
                        sb.append(s).append("\n");
                    log = sb.toString();
                } catch (IOException ignored) {
                }
            }

            switch (solret) {
            case NOMEMORY:
                throw new OutOfMemoryError("when solving" + log);
            case SUBOPTIMAL:
                throw new AssertionError("suboptimal; shouldn't happen?" + log);
            case INFEASIBLE:
                throw new InfeasibleSystemException(log);
            case UNBOUNDED:
                throw new SolverException("system is unbounded" + log);
            case DEGENERATE:
                throw new SolverException("system is degenerate" + log);
            case NUMFAILURE:
                throw new SolverException("numerical failure" + log);
            case USERABORT:
                throw new AssertionError("can't happen; user abort not used" + log);
            case TIMEOUT:
                throw new AssertionError("can't happen; timeout not used" + log);
            case PRESOLVED:
                throw new AssertionError("can't happen; presolve not used" + log);
            case PROCFAIL:
                throw new SolverException("B&B failure" + log);
            case PROCBREAK:
                throw new AssertionError("can't happen; B&B early breaks not used" + log);
            case FEASFOUND:
                throw new AssertionError("feasfound" + log);
            case NOFEASFOUND:
                throw new AssertionError("nofeasfound" + log);
            }
        }
    } finally {
        if (column != null)
            column.release();
        if (row != null)
            row.release();
        if (lp != null)
            deleteLp(lp);
        if (logFile != null)
            try {
                Files.delete(logFile);
            } catch (IOException ignored) {
            }
    }
}

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

/**
 * Converts the {@link GlobalStateObject} into an {@link ArraysObject} using
 * the specified output time unit.// w  w  w  . j  av a2  s.  c  o m
 * @param state The state to convert.
 * @param outputTimeUnit The {@link Unit} to use as time in the resulting
 *          object.
 * @return An {@link ArraysObject} using the specified output time unit.
 */
public static ArraysObject toSingleVehicleArrays(GlobalStateObject state, Unit<Duration> outputTimeUnit) {

    final UnitConverter timeConverter = state.getTimeUnit().getConverterTo(outputTimeUnit);

    final VehicleStateObject v = state.getVehicles().iterator().next();

    // we check all vehicles in case this method is used in other contexts
    final ImmutableSet.Builder<Parcel> cargoBuilder = ImmutableSet.builder();
    for (final VehicleStateObject vs : state.getVehicles()) {
        cargoBuilder.addAll(vs.getContents());
    }
    final Set<Parcel> inCargo = cargoBuilder.build();

    // there are always two locations: the current vehicle location and
    // the depot
    final int numLocations = 2 + state.getAvailableParcels().size() * 2 + inCargo.size();

    final int[] releaseDates = new int[numLocations];
    final int[] dueDates = new int[numLocations];
    final int[][] servicePairs = new int[state.getAvailableParcels().size()][2];
    final int[] serviceTimes = new int[numLocations];

    // we need to create two mappings:
    // Parcel -> pickup index / deliver index
    // index -> Parcel
    final ImmutableMap.Builder<Parcel, ParcelIndexObj> parcel2indexBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<Integer, ParcelIndexObj> index2parcelBuilder = ImmutableMap.builder();

    // we wrap the points in PointWrapper to avoid problems with (possibly)
    // duplicates in the points
    final ImmutableList.Builder<Point> points = ImmutableList.builder();
    points.add(v.getLocation());

    int index = 1;
    int spIndex = 0;
    for (final Parcel p : state.getAvailableParcels()) {
        serviceTimes[index] = DoubleMath.roundToInt(timeConverter.convert(p.getPickupDuration()),
                RoundingMode.CEILING);
        // add pickup location and time window
        points.add(p.getPickupLocation());
        final int deliveryIndex = index + state.getAvailableParcels().size();
        final ParcelIndexObj pio = new ParcelIndexObj(p, index, deliveryIndex);
        parcel2indexBuilder.put(p, pio);
        index2parcelBuilder.put(index, pio);
        index2parcelBuilder.put(deliveryIndex, pio);

        final int[] tw = convertTW(p.getPickupTimeWindow(), state.getTime(), timeConverter);
        releaseDates[index] = tw[0];
        dueDates[index] = tw[1];
        checkState(releaseDates[index] <= dueDates[index]);

        // link the pair with its delivery location (see next loop)
        servicePairs[spIndex++] = new int[] { index, deliveryIndex };

        index++;
    }
    checkState(spIndex == state.getAvailableParcels().size(), "%s %s", state.getAvailableParcels().size(),
            spIndex);

    final List<Parcel> deliveries = new ImmutableList.Builder<Parcel>().addAll(state.getAvailableParcels())
            .addAll(inCargo).build();
    for (final Parcel p : deliveries) {
        serviceTimes[index] = DoubleMath.roundToInt(timeConverter.convert(p.getDeliveryDuration()),
                RoundingMode.CEILING);

        points.add(p.getDeliveryLocation());
        if (inCargo.contains(p)) {
            final ParcelIndexObj pio = new ParcelIndexObj(p, -1, index);
            parcel2indexBuilder.put(p, pio);
            index2parcelBuilder.put(index, pio);
        }

        final int[] tw = convertTW(p.getDeliveryTimeWindow(), state.getTime(), timeConverter);
        releaseDates[index] = tw[0];
        dueDates[index] = tw[1];
        checkState(releaseDates[index] <= dueDates[index]);

        index++;
    }
    checkState(index == numLocations - 1);

    // the start position of the truck points to the depot location
    points.add(v.getDto().getStartPosition());

    // end of the day
    dueDates[index] = fixTWend(v.getDto().getAvailabilityTimeWindow().end(), state.getTime(), timeConverter);

    releaseDates[index] = Math.min(0, dueDates[index]);

    final Measure<Double, Velocity> speed = Measure.valueOf(v.getDto().getSpeed(), state.getSpeedUnit());

    final ImmutableList<Point> pointList = points.build();
    final ImmutableMap<Parcel, ParcelIndexObj> parcel2indexMap = parcel2indexBuilder.build();
    final ImmutableMap<Integer, ParcelIndexObj> index2parcelMap = index2parcelBuilder.build();

    final int[][] travelTime = ArraysSolvers.toTravelTimeMatrix(pointList, state.getDistUnit(), speed,
            outputTimeUnit, RoundingMode.CEILING);

    @Nullable
    SolutionObject[] sol = null;
    if (v.getRoute().isPresent() && state.getVehicles().size() == 1) {
        // the assumption is that if the current route of one vehicle is known,
        // the routes of all vehicles should be known.
        sol = toCurrentSolutions(state, parcel2indexMap, travelTime, releaseDates, dueDates, serviceTimes,
                new int[][] { travelTime[0] }, new int[] { 0 });
    }
    return new ArraysObject(travelTime, releaseDates, dueDates, servicePairs, serviceTimes, sol, pointList,
            parcel2indexMap, index2parcelMap);
}

From source file:com.github.rinde.rinsim.pdptw.common.TimeLinePanel.java

@Override
public void initializePanel(Composite parent) {
    final TimelineBar timelineBar = new TimelineBar(parent.getDisplay());
    final Timeline timeline = new Timeline(parent.getDisplay());
    pdpModel.getEventAPI().addListener(new Listener() {
        @Override// ww w.jav a 2 s.  co  m
        public void handleEvent(Event e) {
            if (e.getEventType() == PDPModelEventType.NEW_PARCEL) {
                verify(e instanceof PDPModelEvent);

                final PDPModelEvent event = (PDPModelEvent) e;
                timeline.addParcel(new ParcelInfo(event.time, verifyNotNull(event.parcel)));
            }
        }
    }, PDPModelEventType.NEW_PARCEL);

    final GridLayout layout = new GridLayout(1, false);
    layout.marginHeight = MARGIN_PX;
    layout.marginWidth = MARGIN_PX;
    layout.verticalSpacing = 0;
    parent.setLayout(layout);
    barCanvas = Optional.of(new Canvas(parent, SWT.NONE));
    final GridData barData = new GridData(SWT.FILL, SWT.TOP, true, false);
    barData.minimumHeight = BAR_HEIGHT_PX;
    barData.heightHint = BAR_HEIGHT_PX;
    barCanvas.get().setLayoutData(barData);
    barCanvas.get().addPaintListener(new PaintListener() {
        @Override
        public void paintControl(@Nullable PaintEvent e) {
            assert e != null;
            timelineBar.update(timeline.getWidth());
            e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
            e.gc.fillRectangle(0, 0, barCanvas.get().getClientArea().width,
                    barCanvas.get().getClientArea().height);

            e.gc.drawImage(timelineBar.contents, origin.x, 0);
            e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_RED));
            e.gc.drawLine(origin.x + (int) (currentTime / TIME_PER_PIXEL), FONT_SIZE,
                    origin.x + (int) (currentTime / TIME_PER_PIXEL), barCanvas.get().getClientArea().height);
        }
    });
    canvas = Optional.of(new Canvas(parent, SWT.DOUBLE_BUFFERED | SWT.NONE | SWT.V_SCROLL | SWT.H_SCROLL));
    final ScrollBar hBar = canvas.get().getHorizontalBar();
    final ScrollBar vBar = canvas.get().getVerticalBar();

    canvas.get().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    canvas.get().addPaintListener(new PaintListener() {
        @Override
        public void paintControl(@Nullable PaintEvent e) {
            assert e != null;
            final int timeX = DoubleMath.roundToInt(origin.x + currentTime / TIME_PER_PIXEL,
                    RoundingMode.HALF_UP);

            final int height = timeline.getHeight();
            timeline.update(timeX);

            final boolean shouldScroll = timeline.getHeight() > height
                    && vBar.getMaximum() == vBar.getSelection() + vBar.getThumb();

            e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
            e.gc.fillRectangle(0, 0, canvas.get().getClientArea().width, canvas.get().getClientArea().height);
            e.gc.drawImage(timeline.contents.get(), origin.x, origin.y);
            e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_RED));
            e.gc.drawLine(timeX, 0, timeX, canvas.get().getClientArea().height);
            hBar.setMaximum(timeline.getWidth() == 0 ? 1 : timeline.getWidth() + H_THUMB_SIZE);
            vBar.setMaximum(timeline.getHeight() + V_THUMB_SIZE);
            hBar.setThumb(Math.min(timeline.getWidth() + H_THUMB_SIZE, canvas.get().getClientArea().width));
            vBar.setThumb(Math.min(timeline.getHeight() + V_THUMB_SIZE, canvas.get().getClientArea().height));

            // if view is currently scrolled down, automatically scroll down when
            // view is expanded downward (similar to the behavior of a terminal)
            if (shouldScroll) {
                vBar.setSelection(vBar.getMaximum());
                final int vSelection = vBar.getSelection();
                final int destY = -vSelection - origin.y;
                canvas.get().scroll(0, destY, 0, 0, timeline.getWidth(), timeline.getHeight(), false);
                origin.y = -vSelection;
            }
        }
    });

    hBar.setIncrement(SCROLL_INCR);
    hBar.setPageIncrement(SCROLL_PAGE_INCR);
    hBar.addListener(SWT.Selection, new org.eclipse.swt.widgets.Listener() {
        @Override
        public void handleEvent(@Nullable org.eclipse.swt.widgets.Event e) {
            final int hSelection = hBar.getSelection();
            final int destX = -hSelection - origin.x;
            canvas.get().scroll(destX, 0, 0, 0, timeline.getWidth(), timeline.getHeight(), false);
            barCanvas.get().scroll(destX, 0, 0, 0, timelineBar.contents.getBounds().width,
                    timelineBar.contents.getBounds().height, false);
            origin.x = -hSelection;
        }
    });
    vBar.setIncrement(SCROLL_INCR);
    vBar.setPageIncrement(SCROLL_PAGE_INCR);
    vBar.addListener(SWT.Selection, new org.eclipse.swt.widgets.Listener() {
        @Override
        public void handleEvent(@Nullable org.eclipse.swt.widgets.Event e) {
            final int vSelection = vBar.getSelection();
            final int destY = -vSelection - origin.y;
            canvas.get().scroll(0, destY, 0, 0, timeline.getWidth(), timeline.getHeight(), false);
            origin.y = -vSelection;
        }
    });
    canvas.get().redraw();
    barCanvas.get().redraw();
}

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

static void addPath(Graph<?> graph, Point... points) {
    final List<Point> newPoints = newArrayList();
    for (int i = 0; i < points.length - 1; i++) {
        final double dist = Point.distance(points[i], points[i + 1]);
        final Point unit = Point.divide(Point.diff(points[i + 1], points[i]), dist);
        final int numPoints = DoubleMath.roundToInt(dist / POINT_DISTANCE, RoundingMode.FLOOR);
        for (int j = 0; j < numPoints; j++) {
            final double factor = j * POINT_DISTANCE;
            newPoints.add(new Point(points[i].x + factor * unit.x, points[i].y + factor * unit.y));
        }/*from   www  . j  av  a 2s .co  m*/
    }
    newPoints.add(points[points.length - 1]);
    Graphs.addPath(graph, newPoints.toArray(new Point[newPoints.size()]));
}

From source file:org.eclipse.hawkbit.rest.util.RestResourceConversionHelper.java

private static long copyStreams(final InputStream from, final OutputStream to,
        final ControllerManagement controllerManagement, final Long statusId, final long start,
        final long length) throws IOException {
    Preconditions.checkNotNull(from);/*from  w  ww.  j  a  va2s.co  m*/
    Preconditions.checkNotNull(to);
    final byte[] buf = new byte[BUFFER_SIZE];
    long total = 0;
    int progressPercent = 1;

    // skipp until start is reached
    long skipped = 0;
    do {
        skipped += from.skip(start);
    } while (skipped < 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 (controllerManagement != 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;
                controllerManagement.downloadProgress(statusId, length, shippedSinceLastEvent, total);
                shippedSinceLastEvent = 0;
            }
        }
    }
    return total;
}