List of usage examples for com.google.common.math DoubleMath roundToLong
@GwtIncompatible("#roundIntermediate") public static long roundToLong(double x, RoundingMode mode)
From source file:com.github.rinde.rinsim.central.Solvers.java
/** * Computes a {@link StatisticsDTO} instance for the given * {@link GlobalStateObject} and routes. For each vehicle in the state the * specified route is used and its arrival times, tardiness and travel times * are computed. The resulting {@link StatisticsDTO} has the same properties * as performing a simulation with the same state. However, since the current * state may be half-way a simulation, it is possible that the returned * statistics describe only a partial simulation. As a result * {@link StatisticsDTO#totalDeliveries} does not necessarily equal * {@link StatisticsDTO#totalPickups}.//from w ww .j a v a 2 s. c om * @param state The state which represents a simulation. * @param routes Specifies the route the vehicles are currently following, * must be of same size as the number of vehicles (one route per * vehicle). If this is <code>null</code> the * {@link VehicleStateObject#getRoute()} field must be set instead * for <b>each</b> vehicle. * @return The statistics that will be generated when executing this * simulation. */ public static ExtendedStats computeStats(GlobalStateObject state, @Nullable ImmutableList<ImmutableList<Parcel>> routes) { final Optional<ImmutableList<ImmutableList<Parcel>>> r = Optional.fromNullable(routes); if (r.isPresent()) { checkArgument(state.getVehicles().size() == r.get().size(), "Exactly one route should be supplied for every vehicle in state. %s " + "vehicle(s) in state, received %s route(s).", state.getVehicles().size(), r.get().size()); } double totalDistance = 0; int totalDeliveries = 0; int totalPickups = 0; long pickupTardiness = 0; long deliveryTardiness = 0; long overTime = 0; final long startTime = state.getTime(); long maxTime = 0; int movedVehicles = 0; final Set<Parcel> parcels = newHashSet(); final ImmutableList.Builder<ImmutableList<Long>> arrivalTimesBuilder = ImmutableList.builder(); for (int i = 0; i < state.getVehicles().size(); i++) { final VehicleStateObject vso = state.getVehicles().get(i); checkArgument(r.isPresent() || vso.getRoute().isPresent(), "Vehicle routes must either be specified as an argument or must be part" + " of the state object."); final ImmutableList.Builder<Long> truckArrivalTimesBuilder = ImmutableList.builder(); truckArrivalTimesBuilder.add(state.getTime()); ImmutableList<Parcel> route; if (r.isPresent()) { route = r.get().get(i); } else { route = vso.getRoute().get(); } parcels.addAll(route); long time = state.getTime(); Point vehicleLocation = vso.getLocation(); final Measure<Double, Velocity> speed = Measure.valueOf(vso.getDto().getSpeed(), state.getSpeedUnit()); final Set<Parcel> seen = newHashSet(); for (int j = 0; j < route.size(); j++) { final Parcel cur = route.get(j); final boolean inCargo = vso.getContents().contains(cur) || seen.contains(cur); seen.add(cur); if (vso.getDestination().isPresent() && j == 0) { checkArgument(vso.getDestination().asSet().contains(cur), "If a vehicle has a destination, the first position in the route " + "must equal this. Expected %s, is %s.", vso.getDestination().get(), cur); } boolean firstAndServicing = false; if (j == 0 && vso.getRemainingServiceTime() > 0) { // we are already at the service location firstAndServicing = true; truckArrivalTimesBuilder.add(time); time += vso.getRemainingServiceTime(); } else { // vehicle is not there yet, go there first, then service final Point nextLoc = inCargo ? cur.getDeliveryLocation() : cur.getPickupLocation(); final Measure<Double, Length> distance = Measure .valueOf(Point.distance(vehicleLocation, nextLoc), state.getDistUnit()); totalDistance += distance.getValue(); vehicleLocation = nextLoc; final long tt = DoubleMath.roundToLong( RoadModels.computeTravelTime(speed, distance, state.getTimeUnit()), RoundingMode.CEILING); time += tt; } if (inCargo) { // check if we are early if (cur.getDeliveryTimeWindow().isBeforeStart(time)) { time = cur.getDeliveryTimeWindow().begin(); } if (!firstAndServicing) { truckArrivalTimesBuilder.add(time); time += cur.getDeliveryDuration(); } // delivering if (cur.getDeliveryTimeWindow().isAfterEnd(time)) { final long tardiness = time - cur.getDeliveryTimeWindow().end(); deliveryTardiness += tardiness; } totalDeliveries++; } else { // check if we are early if (cur.getPickupTimeWindow().isBeforeStart(time)) { time = cur.getPickupTimeWindow().begin(); } if (!firstAndServicing) { truckArrivalTimesBuilder.add(time); time += cur.getPickupDuration(); } // picking up if (cur.getPickupTimeWindow().isAfterEnd(time)) { final long tardiness = time - cur.getPickupTimeWindow().end(); pickupTardiness += tardiness; } totalPickups++; } } // go to depot final Measure<Double, Length> distance = Measure .valueOf(Point.distance(vehicleLocation, vso.getDto().getStartPosition()), state.getDistUnit()); totalDistance += distance.getValue(); final long tt = DoubleMath.roundToLong( RoadModels.computeTravelTime(speed, distance, state.getTimeUnit()), RoundingMode.CEILING); time += tt; // check overtime if (vso.getDto().getAvailabilityTimeWindow().isAfterEnd(time)) { overTime += time - vso.getDto().getAvailabilityTimeWindow().end(); } maxTime = Math.max(maxTime, time); truckArrivalTimesBuilder.add(time); arrivalTimesBuilder.add(truckArrivalTimesBuilder.build()); if (time > startTime) { // time has progressed -> the vehicle has moved movedVehicles++; } } final int totalParcels = parcels.size(); final int totalVehicles = state.getVehicles().size(); final long simulationTime = maxTime - startTime; return new ExtendedStats(totalDistance, totalPickups, totalDeliveries, totalParcels, totalParcels, pickupTardiness, deliveryTardiness, 0, simulationTime, true, totalVehicles, overTime, totalVehicles, movedVehicles, state.getTimeUnit(), state.getDistUnit(), state.getSpeedUnit(), arrivalTimesBuilder.build()); }
From source file:io.prestosql.type.DoubleOperators.java
@ScalarOperator(CAST) @SqlType(StandardTypes.BIGINT)/*w ww.jav a 2 s . c o m*/ public static long castToLong(@SqlType(StandardTypes.DOUBLE) double value) { try { return DoubleMath.roundToLong(value, HALF_UP); } catch (ArithmeticException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Unable to cast %s to bigint", value), e); } }
From source file:veloziped.ws1516.disposal.PurchasingDisposal.java
private long calcConsumInDays(long stock, ConsumptionPlan plan) { long n1 = plan.getN1(); long n2 = plan.getN2(); long n3 = plan.getN3(); long n4 = plan.getN4(); double days = 0; if (stock < n1) { days = stock / n1 * 5;// w w w. ja v a 2 s . c o m } else if (stock < (n1 + n2)) { days = 5 + ((double) stock - n1) / n2 * 5; } else if (stock < (n1 + n2 + n3)) { days = 10 + ((double) stock - n1 - n2) / n3 * 5; } else if (stock < (n1 + n2 + n3 + n4)) { days = 15 + ((double) stock - n1 - n2 - n3) / n4 * 5; } else { days = 999; } switch (SharedInstance.getInstance().getCalculationMode()) { case OPTIMISTIC: return DoubleMath.roundToLong(days, RoundingMode.CEILING); case PESSIMISTIC: return DoubleMath.roundToLong(days, RoundingMode.DOWN); default: return -1; } }
From source file:com.github.rinde.rinsim.core.model.road.GraphRoadModelImpl.java
@Override protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) { final Loc objLoc = verifyLocation(objLocs.get(object)); Loc tempLoc = objLoc;/*from w w w . j a v a 2 s.co m*/ final MoveProgress.Builder mpBuilder = MoveProgress.builder(unitConversion, time); boolean cont = true; long timeLeft = time.getTimeLeft(); while (timeLeft > 0 && !path.isEmpty() && cont) { checkMoveValidity(tempLoc, path.peek()); // speed in internal speed unit final double speed = getMaxSpeed(object, tempLoc, path.peek()); checkState(speed >= 0, "Found a bug in getMaxSpeed, return value must be >= 0, but is %s.", speed); // distance that can be traveled in current conn with timeleft final double travelableDistance = computeTravelableDistance(tempLoc, path.peek(), speed, timeLeft, time.getTimeUnit()); checkState(travelableDistance >= 0d, "Found a bug in computeTravelableDistance, return value must be >= 0," + " but is %s.", travelableDistance); final double connLength = unitConversion.toInDist(computeDistanceOnConnection(tempLoc, path.peek())); checkState(connLength >= 0d, "Found a bug in computeDistanceOnConnection, return value must be " + ">= 0, but is %s.", connLength); double traveledDistance; if (travelableDistance >= connLength) { // jump to next node in path (this may be a node or a point on a // connection) tempLoc = verifyLocation(asLoc(path.remove())); traveledDistance = connLength; mpBuilder.addNode(tempLoc); } else { // travelableDistance < connLength cont = false; traveledDistance = travelableDistance; final Connection<?> conn = getConnection(tempLoc, path.peek()); tempLoc = verifyLocation( newLoc(conn, tempLoc.relativePos + unitConversion.toExDist(travelableDistance))); } mpBuilder.addDistance(traveledDistance); final long timeSpent = DoubleMath.roundToLong( unitConversion.toExTime(traveledDistance / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN); timeLeft -= timeSpent; } time.consume(time.getTimeLeft() - timeLeft); // update location and construct a MoveProgress object objLocs.put(object, tempLoc); return mpBuilder.build(); }
From source file:io.prestosql.type.DoubleOperators.java
private static long saturatedFloorCastToLong(double value, long minValue, double minValueAsDouble, long maxValue, double maxValuePlusOneAsDouble) { if (value <= minValueAsDouble) { return minValue; }/*from w w w. j a v a 2s. c o m*/ if (value + 1 >= maxValuePlusOneAsDouble) { return maxValue; } return DoubleMath.roundToLong(value, FLOOR); }
From source file:org.eclipse.milo.opcua.sdk.server.SessionManager.java
@Override public void onCreateSession(ServiceRequest serviceRequest) throws UaException { CreateSessionRequest request = (CreateSessionRequest) serviceRequest.getRequest(); long maxSessionCount = server.getConfig().getLimits().getMaxSessionCount().longValue(); if (createdSessions.size() + activeSessions.size() >= maxSessionCount) { serviceRequest.setServiceFault(StatusCodes.Bad_TooManySessions); return;/* www . ja v a 2 s .co m*/ } ByteString serverNonce = NonceUtil.generateNonce(32); NodeId authenticationToken = new NodeId(0, NonceUtil.generateNonce(32)); long maxRequestMessageSize = serviceRequest.getServer().getConfig().getMessageLimits().getMaxMessageSize(); double revisedSessionTimeout = Math.max(5000, Math.min(MAX_SESSION_TIMEOUT_MS, request.getRequestedSessionTimeout())); long secureChannelId = serviceRequest.getSecureChannelId(); EndpointDescription endpoint = serviceRequest.getEndpoint(); SecurityPolicy securityPolicy = SecurityPolicy.fromUri(endpoint.getSecurityPolicyUri()); EndpointDescription[] serverEndpoints = server.getEndpointDescriptions().stream() .filter(ed -> endpointMatchesUrl(ed, request.getEndpointUrl())).toArray(EndpointDescription[]::new); ByteString clientNonce = request.getClientNonce(); if (clientNonce.isNotNull() && (clientNonce.length() < 32)) { throw new UaException(StatusCodes.Bad_NonceInvalid); } if (securityPolicy != SecurityPolicy.None && clientNonces.contains(clientNonce)) { throw new UaException(StatusCodes.Bad_NonceInvalid); } if (securityPolicy != SecurityPolicy.None && clientNonce.isNotNull()) { clientNonces.add(clientNonce); while (clientNonces.size() > 64) { clientNonces.remove(0); } } ByteString clientCertificateBytes = request.getClientCertificate(); if (securityPolicy != SecurityPolicy.None && serviceRequest.getClientCertificateBytes() != null) { if (!Objects.equal(clientCertificateBytes, serviceRequest.getClientCertificateBytes())) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "certificate used to open secure channel " + "differs from certificate used to create session"); } } SecurityConfiguration securityConfiguration = createSecurityConfiguration(endpoint, clientCertificateBytes); if (securityPolicy != SecurityPolicy.None) { X509Certificate clientCertificate = securityConfiguration.getClientCertificate(); List<X509Certificate> clientCertificateChain = securityConfiguration.getClientCertificateChain(); if (clientCertificate == null || clientCertificateChain == null) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "client certificate must be non-null"); } String applicationUri = request.getClientDescription().getApplicationUri(); CertificateValidationUtil.validateApplicationUri(clientCertificate, applicationUri); CertificateValidator certificateValidator = server.getConfig().getCertificateValidator(); certificateValidator.validate(clientCertificate); certificateValidator.verifyTrustChain(clientCertificateChain); } // SignatureData must be created using only the bytes of the client // leaf certificate, not the bytes of the client certificate chain. SignatureData serverSignature = getServerSignature(securityPolicy, securityConfiguration.getKeyPair(), clientNonce, securityConfiguration.getClientCertificateBytes()); NodeId sessionId = new NodeId(1, "Session:" + UUID.randomUUID()); String sessionName = request.getSessionName(); Duration sessionTimeout = Duration.ofMillis(DoubleMath.roundToLong(revisedSessionTimeout, RoundingMode.UP)); Session session = new Session(server, sessionId, sessionName, sessionTimeout, secureChannelId, endpoint, securityConfiguration); session.setLastNonce(serverNonce); session.addLifecycleListener((s, remove) -> { createdSessions.remove(authenticationToken); activeSessions.remove(authenticationToken); }); createdSessions.put(authenticationToken, session); CreateSessionResponse response = new CreateSessionResponse(serviceRequest.createResponseHeader(), sessionId, authenticationToken, revisedSessionTimeout, serverNonce, endpoint.getServerCertificate(), serverEndpoints, new SignedSoftwareCertificate[0], serverSignature, uint(maxRequestMessageSize)); serviceRequest.setResponse(response); }
From source file:io.prestosql.type.RealOperators.java
private static long saturatedFloorCastToLong(long valueBits, long minValue, float minValueAsDouble, long maxValue, float maxValuePlusOneAsDouble) { float value = intBitsToFloat((int) valueBits); if (value <= minValueAsDouble) { return minValue; }//from ww w .j av a 2 s . c om if (value + 1 >= maxValuePlusOneAsDouble) { return maxValue; } return DoubleMath.roundToLong(value, FLOOR); }
From source file:veloziped.ws1516.main.SharedInstance.java
private long getEstimatedDeliverPeriod(ExtendedArticle article, Order order) { long estimatedPeriod = 0; if (order.getMode() == 5) { estimatedPeriod = DoubleMath.roundToLong( article.getDeliveryTimeNormalAsPeriods(this.calculationMode) + order.getOrderperiod(), RoundingMode.DOWN); } else if (order.getMode() == 4) { estimatedPeriod = DoubleMath.roundToLong(article.getDeliveryTimeFastAsPeriod() + order.getOrderperiod(), RoundingMode.DOWN); } else {//from w ww . j a v a2 s .co m throw new IllegalArgumentException("Delivery mode not supported."); } return estimatedPeriod; }
From source file:com.addthis.hydra.data.tree.prop.DataReservoir.java
private static long doubleToLong(double value, boolean doubleToLongBits) { if (doubleToLongBits) { return Double.doubleToLongBits(value); } else {//from w w w .j a va 2s . c o m return DoubleMath.roundToLong(value, RoundingMode.HALF_UP); } }
From source file:com.github.rinde.rinsim.scenario.gendreau06.Gendreau06Parser.java
static ImmutableList<AddParcelEvent> parseParcels(InputStream inputStream, boolean online) { final ImmutableList.Builder<AddParcelEvent> listBuilder = ImmutableList.builder(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8)); String line;// w w w . ja va 2 s . co m try { while ((line = reader.readLine()) != null) { final Iterator<String> parts = Iterators.forArray(line.split(" ")); final long requestArrivalTime = DoubleMath .roundToLong(Double.parseDouble(parts.next()) * TIME_MULTIPLIER, RoundingMode.HALF_EVEN); // currently filtering out first and last lines of file. Is this ok? if (requestArrivalTime >= 0) { final long pickupServiceTime = Long.parseLong(parts.next()) * TIME_MULTIPLIER_INTEGER; final double pickupX = Double.parseDouble(parts.next()); final double pickupY = Double.parseDouble(parts.next()); final long pickupTimeWindowBegin = DoubleMath.roundToLong( Double.parseDouble(parts.next()) * TIME_MULTIPLIER, RoundingMode.HALF_EVEN); final long pickupTimeWindowEnd = DoubleMath.roundToLong( Double.parseDouble(parts.next()) * TIME_MULTIPLIER, RoundingMode.HALF_EVEN); final long deliveryServiceTime = Long.parseLong(parts.next()) * TIME_MULTIPLIER_INTEGER; final double deliveryX = Double.parseDouble(parts.next()); final double deliveryY = Double.parseDouble(parts.next()); final long deliveryTimeWindowBegin = DoubleMath.roundToLong( Double.parseDouble(parts.next()) * TIME_MULTIPLIER, RoundingMode.HALF_EVEN); final long deliveryTimeWindowEnd = DoubleMath.roundToLong( Double.parseDouble(parts.next()) * TIME_MULTIPLIER, RoundingMode.HALF_EVEN); // when an offline scenario is desired, all times are set to -1 final long arrTime = online ? requestArrivalTime : -1; final ParcelDTO dto = Parcel .builder(new Point(pickupX, pickupY), new Point(deliveryX, deliveryY)) .pickupTimeWindow(TimeWindow.create(pickupTimeWindowBegin, pickupTimeWindowEnd)) .deliveryTimeWindow(TimeWindow.create(deliveryTimeWindowBegin, deliveryTimeWindowEnd)) .neededCapacity(PARCEL_MAGNITUDE).orderAnnounceTime(arrTime) .pickupDuration(pickupServiceTime).deliveryDuration(deliveryServiceTime).buildDTO(); listBuilder.add(AddParcelEvent.create(dto)); } } reader.close(); } catch (final IOException e) { throw new IllegalArgumentException(e); } return listBuilder.build(); }