Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  
  package rinde.sim.pdptw.central;
  
  import static com.google.common.base.Preconditions.checkArgument;
  import static com.google.common.collect.Lists.newArrayList;
  import static com.google.common.collect.Lists.newLinkedList;
  import static com.google.common.collect.Sets.newHashSet;
 import static com.google.common.collect.Sets.newLinkedHashSet;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  javax.annotation.Nullable;
 
 

Author(s):
Rinde van Lon <rinde.vanlon@cs.kuleuven.be>
 
 public final class Solvers {
 
   private Solvers() {}

  
Creates a builder for creating SimulationSolver instances. For more information see AdapterBuilder.

Parameters:
sol The solver to use internally.
Returns:
The builder.
 
   public static AdapterBuilder<SimulationSolversolverBuilder(Solver sol) {
     return new AdapterBuilder<SimulationSolver>(sol);
   }

  
Creates a builder for creating SimulationConverter instances.

Returns:
The builder.
 
     return new AdapterBuilder<SimulationConverter>(null);
   }

  
Computes the duration which is required to travel the specified distance with the given velocity. Note: although time is normally a long, we use double here instead. Converting it to long in this method would introduce rounding in a too early stage.

Parameters:
speed The travel speed.
distance The distance to travel.
outputTimeUnit The time unit to use for the output.
Returns:
The time it takes to travel the specified distance with the specified speed.
 
   public static double computeTravelTime(Measure<DoubleVelocityspeed,
       Measure<DoubleLengthdistanceUnit<DurationoutputTimeUnit) {
     // meters
     return Measure.valueOf(distance.doubleValue(.)
         // divided by m/s
         / speed.doubleValue(.),
         // gives seconds
         .)
         // convert to desired unit
         .doubleValue(outputTimeUnit);
   }

  
Computes a StatisticsDTO instance for the given GlobalStateObject and routes. For each vehicle in the state the specified route is used and it its arrival times, tardiness and travel times are computed. The resulting 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 StatisticsDTO.totalDeliveries does not necessarily equal StatisticsDTO.totalPickups.

Parameters:
state The state which represents a simulation.
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 null the VehicleStateObject.route field must be set instead for each vehicle.
Returns:
The statistics that will be generated when executing this simulation.
  public static StatisticsDTO computeStats(GlobalStateObject state,
      @Nullable ImmutableList<ImmutableList<ParcelDTO>> routes) {
    final Optional<ImmutableList<ImmutableList<ParcelDTO>>> r = Optional
        .fromNullable(routes);
    if (r.isPresent()) {
      checkArgument(state.vehicles.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.time;
    long maxTime = 0;
    int movedVehicles = 0;
    final Set<ParcelDTOparcels = newHashSet();
    final ImmutableList.Builder<ImmutableList<Long>> arrivalTimesBuilder = ImmutableList
        .builder();
    for (int i = 0; i < state.vehicles.size(); i++) {
      final VehicleStateObject vso = state.vehicles.get(i);
      checkArgument(r.isPresent() || vso.route.isPresent());
      final ImmutableList.Builder<LongtruckArrivalTimesBuilder = ImmutableList
          .builder();
      truckArrivalTimesBuilder.add(state.time);
      ImmutableList<ParcelDTOroute;
      if (r.isPresent()) {
        route = r.get().get(i);
      } else {
        route = vso.route.get();
      }
      parcels.addAll(route);
      long time = state.time;
      Point vehicleLocation = vso.location;
      final Measure<DoubleVelocityspeed = Measure.valueOf(vso.speed,
          state.speedUnit);
      final Set<ParcelDTOseen = newHashSet();
      for (int j = 0; j < route.size(); j++) {
        final ParcelDTO cur = route.get(j);
        final boolean inCargo = vso.contents.contains(cur)
            || seen.contains(cur);
        seen.add(cur);
        if (vso.destination != null && j == 0) {
          checkArgument(
              vso.destination == cur,
              "If a vehicle has a destination, the first position in the route must equal this. Expected %s, is %s.",
              vso.destinationcur);
        }
        boolean firstAndServicing = false;
        if (j == 0 && vso.remainingServiceTime > 0) {
          // we are already at the service location
          firstAndServicing = true;
          truckArrivalTimesBuilder.add(time);
          time += vso.remainingServiceTime;
        } else {
          // vehicle is not there yet, go there first, then service
          final Point nextLoc = inCargo ? cur.destinationLocation
              : cur.pickupLocation;
          final Measure<DoubleLengthdistance = Measure.valueOf(
              Point.distance(vehicleLocationnextLoc), state.distUnit);
          totalDistance += distance.getValue();
          vehicleLocation = nextLoc;
          final long tt = DoubleMath.roundToLong(
              computeTravelTime(speeddistancestate.timeUnit),
              .);
          time += tt;
        }
        if (inCargo) {
          // check if we are early
          if (cur.deliveryTimeWindow.isBeforeStart(time)) {
            time = cur.deliveryTimeWindow.begin;
          }
          if (!firstAndServicing) {
            truckArrivalTimesBuilder.add(time);
            time += cur.deliveryDuration;
          }
          // delivering
          if (cur.deliveryTimeWindow.isAfterEnd(time)) {
            final long tardiness = time - cur.deliveryTimeWindow.end;
            deliveryTardiness += tardiness;
          }
          totalDeliveries++;
        } else {
          // check if we are early
          if (cur.pickupTimeWindow.isBeforeStart(time)) {
            time = cur.pickupTimeWindow.begin;
          }
          if (!firstAndServicing) {
            truckArrivalTimesBuilder.add(time);
            time += cur.pickupDuration;
          }
          // picking up
          if (cur.pickupTimeWindow.isAfterEnd(time)) {
            final long tardiness = time - cur.pickupTimeWindow.end;
            pickupTardiness += tardiness;
          }
          totalPickups++;
        }
      }
      // go to depot
      final Measure<DoubleLengthdistance = Measure.valueOf(
          Point.distance(vehicleLocationvso.startPosition), state.distUnit);
      totalDistance += distance.getValue();
      final long tt = DoubleMath.roundToLong(
          computeTravelTime(speeddistancestate.timeUnit),
          .);
      time += tt;
      // check overtime
      if (vso.availabilityTimeWindow.isAfterEnd(time)) {
        overTime += time - vso.availabilityTimeWindow.end;
      }
      maxTime = Math.max(maxTimetime);
      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.vehicles.size();
    final long simulationTime = maxTime - startTime;
    return new ExtendedStats(totalDistancetotalPickupstotalDeliveries,
        totalParcelstotalParcelspickupTardinessdeliveryTardiness, 0,
        simulationTimetruetotalVehiclesoverTimetotalVehicles,
        movedVehiclesstate.timeUnitstate.distUnitstate.speedUnit,
        arrivalTimesBuilder.build());
  }

  
Converts the specified collection containing DefaultParcels into an ImmutableList of ParcelDTOs.

Parameters:
parcels The parcels to convert.
Returns:
A list of ParcelDTOs in the same order as in the provided collection.
  public static ImmutableList<ParcelDTOtoDtoList(
      Collection<DefaultParcelparcels) {
    final ImmutableList.Builder<ParcelDTObuilder = ImmutableList.builder();
    for (final DefaultParcel dp : parcels) {
      builder.add(dp.dto);
    }
    return builder.build();
  }

  
Converts the specified collection of collections containing DefaultParcels into a list of lists containing ParcelDTOs.

Parameters:
routes The collection of collections of parcels to convert.
Returns:
A list of lists of ParcelDTOs in the same order as the provided lists.
      Collection<? extends Collection<DefaultParcel>> routes) {
    final ImmutableList.Builder<ImmutableList<ParcelDTO>> newRoutes = ImmutableList
        .builder();
    for (final Collection<DefaultParcelroute : routes) {
      newRoutes.add(toDtoList(route));
    }
    return newRoutes.build();
  }
  // converts the routes received from Solver.solve(..) into a format which is
  // expected by the simulator
      List<? extends List<ParcelDTO>> routes) {
    final ImmutableList.Builder<Queue<DefaultParcel>> routesBuilder = ImmutableList
        .builder();
    for (final List<ParcelDTOroute : routes) {
      final Queue<DefaultParcelnewRoute = newLinkedList();
      for (final ParcelDTO dto : route) {
        newRoute.add(cont.parcelMap.get(dto));
      }
      routesBuilder.add(newRoute);
    }
    return routesBuilder.build();
  }
    final List<DefaultParcell = newArrayList();
    for (final Parcel p : input) {
      checkArgument(p instanceof DefaultParcel);
      l.add((DefaultParcelp);
    }
    return l;
  }
      Collection<DefaultVehiclevehicles,
      Collection<DefaultParcelavailableParcelsMeasure<LongDurationtime,
      Optional<ImmutableList<ImmutableList<DefaultParcel>>> currentRoutes) {
    final ImmutableMap<VehicleDTODefaultVehiclevehicleMap = toVehicleMap(vehicles);
    final ImmutableList.Builder<VehicleStateObjectvbuilder = ImmutableList
        .builder();
    final ImmutableMap.Builder<ParcelDTODefaultParcelallParcels = ImmutableMap
        .builder();
    @Nullable
    Iterator<ImmutableList<DefaultParcel>> routeIterator = null;
    if (currentRoutes.isPresent()) {
      checkArgument(currentRoutes.get().size() == vehicles.size(),
          "The number of routes (%s) must equal the number of vehicles (%s).",
          currentRoutes.get().size(), vehicles.size());
      routeIterator = currentRoutes.get().iterator();
    }
    final ImmutableMap.Builder<ParcelDTODefaultParcelavailableDestParcels = ImmutableMap
        .builder();
    for (final DefaultVehicle v : vehicles) {
      final ImmutableMap<ParcelDTODefaultParcelcontentsMap = contentsToMap(
          pmv);
      @Nullable
      ImmutableList<DefaultParcelroute = null;
      if (routeIterator != null) {
        route = routeIterator.next();
      }
      vbuilder.add(convertToVehicleState(rmpmvcontentsMaproute,
          availableDestParcels));
      allParcels.putAll(contentsMap);
    }
    final ImmutableMap<ParcelDTODefaultParcelavailableMap = toMap(availableParcels);
    final ImmutableMap<ParcelDTODefaultParcelavailableDestMap = availableDestParcels
        .build();
    final Map<ParcelDTODefaultParceltoAdd = Maps.difference(availableMap,
        availableDestMap).entriesOnlyOnRight();
    allParcels.putAll(availableMap);
    allParcels.putAll(toAdd);
    final ImmutableSet<ParcelDTOavailableParcelsKeys = ImmutableSet
        .<ParcelDTObuilder()
        .addAll(availableMap.keySet())
        .addAll(toAdd.keySet()).build();
    return new StateContext(new GlobalStateObject(availableParcelsKeys,
        vbuilder.build(), time.getValue().longValue(), time.getUnit(),
        rm.getSpeedUnit(), rm.getDistanceUnit()), vehicleMap,
        allParcels.build());
  }
      DefaultVehicle vehicle) {
    // this is ok since we actually check the type
    @SuppressWarnings({ "unchecked""rawtypes" })
    final Set<DefaultParcelps = Collections.checkedSet(
        (SetnewLinkedHashSet(pm.getContents(vehicle)), DefaultParcel.class);
    return toMap(ps);
  }
  // TODO check for bugs
      DefaultVehicle vehicleImmutableMap<ParcelDTODefaultParcelcontents,
      @Nullable ImmutableList<DefaultParcelroute,
      ImmutableMap.Builder<ParcelDTODefaultParcelavailableDestBuilder) {
    final boolean isIdle = pm.getVehicleState(vehicle) == ..;
    long remainingServiceTime = 0;
    @Nullable
    DefaultParcel destination = null;
    if (!isIdle) {
      final VehicleParcelActionInfo vpai = pm.getVehicleActionInfo(vehicle);
      destination = ((DefaultParcelvpai.getParcel());
      remainingServiceTime = vpai.timeNeeded();
    } else if (!rm.isVehicleDiversionAllowed()) {
      // check whether the vehicle is already underway to parcel
      destination = rm.getDestinationToParcel(vehicle);
    }
    // destinations which are not yet picked up should be put in the builder
    if (destination != null && !pm.getParcelState(destination).isPickedUp()) {
      availableDestBuilder.put(destination.dtodestination);
    }
    @Nullable
    ImmutableList<ParcelDTOr = null;
    if (route != null) {
      r = toDtoList(route);
    }
    return new VehicleStateObject(vehicle.getDTO(), rm.getPosition(vehicle),
        contents.keySet(), remainingServiceTimedestination == null ? null
            : destination.dtor);
  }
      Collection<DefaultParcelparcels) {
    final ImmutableMap.Builder<ParcelDTODefaultParcelparcelMapBuilder = ImmutableMap
        .builder();
    for (final DefaultParcel dp : parcels) {
      parcelMapBuilder.put(dp.dtodp);
    }
    return parcelMapBuilder.build();
  }
      Collection<DefaultVehiclevehicles) {
    final ImmutableMap.Builder<VehicleDTODefaultVehiclevehicleMapBuilder = ImmutableMap
        .builder();
    for (final DefaultVehicle dp : vehicles) {
      vehicleMapBuilder.put(dp.getDTO(), dp);
    }
    return vehicleMapBuilder.build();
  }

  
Converter that converts simulations into StateContext instances which are needed to call Solver.solve(GlobalStateObject).

Author(s):
Rinde van Lon <rinde.vanlon@cs.kuleuven.be>
  public interface SimulationConverter {
    
Converts the simulation into a StateContext object.

Parameters:
args SolveArgs.
Returns:
StateContext.
  }

  
Builder for specifying parameters used in SimulationSolver and SimulationConverter.

Author(s):
Rinde van Lon <rinde.vanlon@cs.kuleuven.be>
  public static final class SolveArgs {
    private SolveArgs() {
       = Optional.absent();
       = Optional.absent();
    }

    

Returns:
SolveArgs builder.
    public static SolveArgs create() {
      return new SolveArgs();
    }

    
Indicates that receivers of this object should use all parcels it knows.

Returns:
This, as per the builder pattern.
    public SolveArgs useAllParcels() {
       = Optional.absent();
      return this;
    }

    
Indicates that receivers of this object should use only the parcels that are specified.

Parameters:
ps The parcels to use.
Returns:
This, as per the builder pattern.
       = Optional.of(ps);
      return this;
    }

    
Indicates that receivers of this object should use no current routes for the vehicles it knows about.

Returns:
This, as per the builder pattern.
    public SolveArgs noCurrentRoutes() {
       = Optional.absent();
      return this;
    }

    
Indicates that receivers of this object should use the specified current routes for the vehicles it knows about. The number of specified route needs to match the number of known vehicles.

Parameters:
cr The current routes to use.
Returns:
This, as per the builder pattern.
    public SolveArgs useCurrentRoutes(
        ImmutableList<ImmutableList<DefaultParcel>> cr) {
       = Optional.of(cr);
      return this;
    }
  }

  
Adapter for Solvers.

Author(s):
Rinde van Lon <rinde.vanlon@cs.kuleuven.be>
  public static class SimulationSolver implements SimulationConverter {
    final Optional<Solversolver;
    final SimulatorAPI simulator;
    final PDPRoadModel roadModel;
    final PDPModel pdpModel;
    final List<DefaultVehiclevehicles;
        SimulatorAPI simList<DefaultVehiclevs) {
       = s;
       = sim;
       = rm;
       = pm;
       = vs;
    }

    
Calls the Solver to solve the problem as defined by the current simulation state.

Parameters:
args SolveArgs specifying what information to include.
Returns:
A list containing routes for each vehicle known to this solver.
    public List<Queue<DefaultParcel>> solve(SolveArgs args) {
      return solve(convert(args));
    }

    
Calls the Solver to solve the problem as defined by the current simulation state.

Parameters:
state The StateContext that specifies the current simulation state.
Returns:
A list of routes, one for each vehicle.
    public List<Queue<DefaultParcel>> solve(StateContext state) {
      return Solvers.convertRoutes(state.get().solve(state.state));
    }
    @Override
    public StateContext convert(SolveArgs args) {
      final Collection<DefaultVehiclevs = .isEmpty() ? 
          .getObjectsOfType(DefaultVehicle.class) : ;
      final Collection<DefaultParcelps = args.parcels.isPresent() ? args.parcels
          .get()
              ..));
      return Solvers.convert(vspstime(),
          args.currentRoutes);
    }
    Measure<LongDurationtime() {
      return Measure.valueOf(.getCurrentTime(),
          .getTimeUnit());
    }
  }

  
Builder for creating adapters for Solvers that need to solve simulation instances. For creating an adapter four different pieces of information are required, each can be supplied to this builder via a variety of methods which are listed below.
  • PDPRoadModel - can be supplied directly, via a ModelProvider or via Simulator instance
  • PDPModel - can be supplied directly, via a ModelProvider or via Simulator instance
  • SimulatorAPI - can be supplied directly or via a Simulator instance.
  • A number of DefaultVehicles - can be supplied directly or if not supplied all vehicles available in the PDPRoadModel instance will be used.

Parameters:
<T> The type of adapter to produce.
Author(s):
Rinde van Lon <rinde.vanlon@cs.kuleuven.be>
  public static class AdapterBuilder<T extends SimulationConverter> {
    final List<DefaultVehiclevehicles;
    final Optional<Solversolver;
    AdapterBuilder(@Nullable Solver s) {
       = Optional.fromNullable(s);
       = newArrayList();
    }

    

Parameters:
sim The Simulator to provide to the adapter.
Returns:
This, as per the builder pattern.
    public AdapterBuilder<T> with(Simulator sim) {
       = sim;
      return this;
    }

    

Parameters:
mp The ModelProvider to use for extracting the models. Calls to this method take precedence over with(Simulator).
Returns:
This, as per the builder pattern.
    public AdapterBuilder<T> with(ModelProvider mp) {
       = mp;
      return this;
    }

    

Parameters:
rm The PDPRoadModel to use in the adapter. Calls to this method take precedence over with(ModelProvider) and with(Simulator).
Returns:
This, as per the builder pattern.
    public AdapterBuilder<T> with(PDPRoadModel rm) {
       = rm;
      return this;
    }

    

Parameters:
pm The PDPModel to use in the adapter. Calls to this method take precedence over with(ModelProvider) and with(Simulator).
Returns:
This, as per the builder pattern.
    public AdapterBuilder<T> with(PDPModel pm) {
       = pm;
      return this;
    }

    

Parameters:
sim The SimulatorAPI to use in the adapter. Calls to this method take precedence over with(Simulator).
Returns:
This, as per the builder pattern.
    public AdapterBuilder<T> with(SimulatorAPI sim) {
       = sim;
      return this;
    }

    
Adds the specified vehicle to the resulting adapter, the vehicle will be included in the resulting adapter. When no vehicles are supplied, the adapter will use all vehicles in PDPRoadModel.

Parameters:
dv The DefaultVehicle to add.
Returns:
This, as per the builder pattern.
    public AdapterBuilder<T> with(DefaultVehicle dv) {
      .add(dv);
      return this;
    }

    
Adds the specified vehicles to the resulting adapter, the vehicles will be included in the resulting adapter. When no vehicles are supplied, the adapter will use all vehicles in PDPRoadModel.

Parameters:
dv The DefaultVehicles to include.
Returns:
This, as per the builder pattern.
    public AdapterBuilder<T> with(List<? extends DefaultVehicledv) {
      .addAll(dv);
      return this;
    }

    
Builds the adapter.

Returns:
The newly created adapter.
    @SuppressWarnings("unchecked")
    public T build() {
      PDPRoadModel rm = ;
      PDPModel pm = ;
      if (rm == null || pm == null) {
        // in this case we need a model provider
        ModelProvider mp = ;
        if (mp == null) {
          checkArgument(
               != null,
              "Attempt to find a model provider failed. Either provide the models directly, provide a model provider or a simulator.");
          mp = .getModelProvider();
        }
        if (rm == null) {
          rm = mp.getModel(PDPRoadModel.class);
        }
        if (pm == null) {
          pm = mp.getModel(PDPModel.class);
        }
      }
      SimulatorAPI sapi = ;
      if (sapi == null) {
        sapi = ;
      }
      if (sapi != null && rm != null && pm != null) {
        return (T) new SimulationSolver(rmpmsapi);
      } else {
        throw new IllegalArgumentException(
            "Not all required components could be found, PDPRoadModel: " + rm
                + ", PDPModel: " + pm + ", SimulatorAPI: " + sapi);
      }
    }

    
Builds an adapter which can deal with only one vehicle.

Returns:
A new created adapter.
    public T buildSingle() {
      checkArgument(.size() == 1);
      return build();
    }
  }

  
Value object containing representing the state of a simulation. It contains a GlobalStateObject (the actual state) and two maps with references to the original vehicles and parcels. Using these maps the state object can be translated back to the original simulation objects.

Author(s):
Rinde van Lon <rinde.vanlon@cs.kuleuven.be>
  public static class StateContext {
    
A reference to the GlobalStateObject.
    public final GlobalStateObject state;
    
A mapping of VehicleDTO to DefaultVehicle.
    public final ImmutableMap<VehicleDTODefaultVehiclevehicleMap;
    
A mapping of ParcelDTO to DefaultParcel.
    public final ImmutableMap<ParcelDTODefaultParcelparcelMap;
        ImmutableMap<VehicleDTODefaultVehiclevehicleMap,
        ImmutableMap<ParcelDTODefaultParcelparcelMap) {
      this. = state;
      this. = vehicleMap;
      this. = parcelMap;
    }
  }
  // only used for testing
  static class ExtendedStats extends StatisticsDTO {
    private static final long serialVersionUID = 3682772955122186862L;
    ExtendedStats(double distint pickint delint parcint accP,
        long pickTarlong delTarlong compTlong simTboolean finish,
        int atDepotlong overTint totalint movedUnit<Durationtime,
        Unit<LengthdistUnitUnit<Velocityspeed,
        ImmutableList<ImmutableList<Long>> arrivalTimes) {
      super(distpickdelparcaccPpickTardelTarcompTsimTfinish,
          atDepotoverTtotalmovedtimedistUnitspeed);
      this. = arrivalTimes;
    }
  }
New to GrepCode? Check out our FAQ X