Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011-2014 Rinde van Lon, iMinds DistriNet, KU Leuven
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *         http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package com.github.rinde.rinsim.scenario.gendreau06;
 
 import static com.github.rinde.rinsim.core.model.pdp.PDPScenarioEvent.ADD_DEPOT;
 import static com.github.rinde.rinsim.core.model.pdp.PDPScenarioEvent.ADD_PARCEL;
 import static com.github.rinde.rinsim.core.model.pdp.PDPScenarioEvent.ADD_VEHICLE;
 import static com.github.rinde.rinsim.core.model.pdp.PDPScenarioEvent.TIME_OUT;
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.collect.Lists.newArrayList;
 
 import java.io.File;
 import java.util.List;
 import java.util.Set;
 
Parser for files from the Gendreau et al. (2006) data set. The parser allows to customize some of the properties of the scenarios.

Format specification: (columns)

  • 1: request arrival time
  • 2: pick-up service time
  • 3 and 4: x and y position for the pick-up
  • 5 and 6: service window time of the pick-up
  • 7: delivery service time
  • 8 and 9:x and y position for the delivery
  • 10 and 11: service window time of the delivery
All times are expressed in seconds.

References

  • [1]. Gendreau, M., Guertin, F., Potvin, J.-Y., and Séguin, R. Neighborhood search heuristics for a dynamic vehicle dispatching problem with pick-ups and deliveries. Transportation Research Part C: Emerging Technologies 14, 3 (2006), 157–174.

Author(s):
Rinde van Lon
 
 public final class Gendreau06Parser {
   private static final String REGEX = ".*req_rapide_(\\d+)_(450|240)_(24|33)";
   private static final double TIME_MULTIPLIER = 1000d;
   private static final int TIME_MULTIPLIER_INTEGER = 1000;
   private static final int PARCEL_MAGNITUDE = 0;
   private static final long DEFAULT_TICK_SIZE = 1000L;
 
   private int numVehicles;
   private boolean allowDiversion;
   private boolean online;
   private long tickSize;
  private Gendreau06Parser() {
     = false;
     = true;
     = -1;
     = ImmutableMap.builder();
     = Optional.absent();
  }

  

Returns:
A Gendreau06Parser.
  public static Gendreau06Parser parser() {
    return new Gendreau06Parser();
  }

  
Convenience method for parsing a single file.

Parameters:
file The file to parse.
Returns:
The scenario as described by the file.
  public static Gendreau06Scenario parse(File file) {
    return parser().addFile(file).parse().get(0);
  }
  
  
  public static Function<PathGendreau06Scenarioreader() {
    return new Gendreau06Reader();
  }

  
Add the specified file to the parser.

Parameters:
file The file to add.
Returns:
This, as per the builder pattern.
  public Gendreau06Parser addFile(File file) {
    try {
          new FileInputStream(
              file)));
    } catch (final FileNotFoundException e) {
      throw new IllegalArgumentException(e);
    }
    return this;
  }

  
Add the specified file to the parser.

Parameters:
file The file to add.
Returns:
This, as per the builder pattern.
  public Gendreau06Parser addFile(String file) {
    return addFile(new File(file));
  }

  
Add the specified stream to the parser. A file name needs to be specified for identification of this particular scenario.

Parameters:
stream The stream to use for the parsing of the scenario.
fileName The file name that identifies the scenario's class and instance.
Returns:
This, as per the builder pattern.
  public Gendreau06Parser addFile(InputStream streamString fileName) {
    checkValidFileName(fileName);
    .put(fileNamenew InputStreamToParcels(stream));
    return this;
  }

  
Add a scenario that is composed using the specified com.github.rinde.rinsim.scenario.AddParcelEvent s.

Parameters:
events The events to include.
fileName The filename of the scenario.
Returns:
This, as per the builder pattern.
      String fileName) {
    checkValidFileName(fileName);
    .put(fileNamenew Parcels(events));
    return this;
  }

  
Adds all Gendreau scenario files in the specified directory.

Parameters:
dir The directory to search.
Returns:
This, as per the builder pattern.
    return addDirectory(new File(dir));
  }

  
Adds all Gendreau scenario files in the specified directory.

Parameters:
dir The directory to search.
Returns:
This, as per the builder pattern.
  public Gendreau06Parser addDirectory(File dir) {
    final File[] files = dir.listFiles(
        new FileFilter() {
          @Override
          public boolean accept(File file) {
            checkNotNull(file);
            return isValidFileName(file.getName());
          }
        });
    Arrays.sort(files);
    for (final File f : files) {
      addFile(f);
    }
    return this;
  }

  
When this method is called all scenarios generated by this parser will allow vehicle diversion. For more information about the vehicle diversion concept please consult the class documentation of com.github.rinde.rinsim.pdptw.common.PDPRoadModel.

Returns:
This, as per the builder pattern.
     = true;
    return this;
  }

  
When this method is called, all scenarios generated by this parser will be offline scenarios. This means that all parcel events will arrive at time -1, which means that everything is known beforehand. By default the parser uses the original event arrival times as defined by the scenario file.

Returns:
This, as per the builder pattern.
  public Gendreau06Parser offline() {
     = false;
    return this;
  }

  
This method allows to override the number of vehicles in the scenarios. For the default values see GendreauProblemClass.

Parameters:
num The number of vehicles that should be used in the parsed scenarios. Must be positive.
Returns:
This, as per the builder pattern.
  public Gendreau06Parser setNumVehicles(int num) {
    checkArgument(num > 0, "The number of vehicles must be positive.");
     = num;
    return this;
  }

  
Change the default tick size of 1000 ms into something else.

Parameters:
tick Must be positive.
Returns:
This, as per the builder pattern.
  public Gendreau06Parser setTickSize(long tick) {
    checkArgument(tick > 0L, "Tick size must be positive.");
     = tick;
    return this;
  }

  
Filters out any files that are added to this parser which are not of one of the specified problem classes.

Parameters:
classes The problem classes which should be parsed.
Returns:
This, as per the builder pattern.
  public Gendreau06Parser filter(GendreauProblemClass... classes) {
     = Optional.of(ImmutableList.<ProblemClasscopyOf(classes));
    return this;
  }

  
Parses the files which are added to this parser. In case filter(com.github.rinde.rinsim.scenario.gendreau06.GendreauProblemClass[]) has been called, only files in one of these problem classes will be parsed.

Returns:
A list of scenarios in order of adding them to the parser.
    final ImmutableList.Builder<Gendreau06Scenarioscenarios = ImmutableList
        .builder();
    for (final Entry<StringParcelsSupplierentry : .build()
        .entrySet()) {
      boolean include = false;
      if (!.isPresent()) {
        include = true;
      } else {
        for (final ProblemClass pc : .get()) {
          if (entry.getKey().endsWith(pc.getId())) {
            include = true;
            break;
          }
        }
      }
      if (include) {
        scenarios.add(parse(entry.getValue(), entry.getKey(), ,
            ));
      }
    }
    return scenarios.build();
  }
  static Matcher matcher(String fileName) {
    return Pattern.compile().matcher(fileName);
  }
  static boolean isValidFileName(String name) {
    return Pattern.compile().matcher(name).matches();
  }
  static void checkValidFileName(Matcher mString name) {
        "The filename must conform to the following regex: %s input was: %s",
        name);
  }
  static void checkValidFileName(String name) {
    checkValidFileName(matcher(name), name);
  }
  private static Gendreau06Scenario parse(
      ParcelsSupplier parcels,
      String fileNameint numVehiclesfinal long tickSize,
      final boolean allowDiversionboolean online) {
    final Set<Enum<?>> evTypes = ImmutableSet.<Enum<?>> of(,
        );
    final Matcher m = matcher(fileName);
    checkValidFileName(mfileName);
    final int instanceNumber = Integer.parseInt(m.group(1));
    final long minutes = Long.parseLong(m.group(2));
    final long totalTime = minutes * 60000L;
    final long requestsPerHour = Long.parseLong(m.group(3));
    final GendreauProblemClass problemClass = GendreauProblemClass.with(
        minutesrequestsPerHour);
    final int vehicles = numVehicles == -1 ? problemClass.vehicles
        : numVehicles;
    final Point depotPosition = new Point(2.0, 2.5);
    final double truckSpeed = 30;
    final List<TimedEventevents = newArrayList();
    events.add(new AddDepotEvent(-1, depotPosition));
    for (int i = 0; i < vehiclesi++) {
      events.add(new AddVehicleEvent(-1,
          VehicleDTO.builder()
              .startPosition(depotPosition)
              .speed(truckSpeed)
              .capacity(0)
              .availabilityTimeWindow(new TimeWindow(0, totalTime))
              .build()));
    }
    events.addAll(parcels.get(online));
    events.add(new TimedEvent(totalTime));
    Collections.sort(events.);
    return new Gendreau06Scenario(eventsevTypestickSize,
        problemClassinstanceNumberallowDiversion);
  }
      boolean online) {
    final ImmutableList.Builder<AddParcelEventlistBuilder = ImmutableList
        .builder();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(
        inputStream.));
    String line;
    try {
      while ((line = reader.readLine()) != null) {
        final Iterator<Stringparts = Iterators.forArray(line.split(" "));
        final long requestArrivalTime = DoubleMath.roundToLong(
            Double.parseDouble(parts.next()) * ,
            .);
        // FIXME currently filtering out first and last lines of file. Is
        // this ok?
        if (requestArrivalTime >= 0) {
          final long pickupServiceTime = Long.parseLong(parts.next())
              * ;
          final double pickupX = Double.parseDouble(parts.next());
          final double pickupY = Double.parseDouble(parts.next());
          final long pickupTimeWindowBegin = DoubleMath.roundToLong(
              Double.parseDouble(parts.next()) * ,
              .);
          final long pickupTimeWindowEnd = DoubleMath.roundToLong(
              Double.parseDouble(parts.next()) * ,
              .);
          final long deliveryServiceTime = Long.parseLong(parts.next())
              * ;
          final double deliveryX = Double.parseDouble(parts.next());
          final double deliveryY = Double.parseDouble(parts.next());
          final long deliveryTimeWindowBegin = DoubleMath.roundToLong(
              Double.parseDouble(parts.next()) * ,
              .);
          final long deliveryTimeWindowEnd = DoubleMath.roundToLong(
              Double.parseDouble(parts.next()) * ,
              .);
          // when an offline scenario is desired, all times are set to -1
          final long arrTime = online ? requestArrivalTime : -1;
          final ParcelDTO dto = ParcelDTO.builder(new Point(pickupXpickupY),
              new Point(deliveryXdeliveryY)).
              pickupTimeWindow(new TimeWindow(
                  pickupTimeWindowBeginpickupTimeWindowEnd))
              .deliveryTimeWindow(new TimeWindow(
                  deliveryTimeWindowBegindeliveryTimeWindowEnd))
              .neededCapacity()
              .orderAnnounceTime(arrTime)
              .pickupDuration(pickupServiceTime)
              .deliveryDuration(deliveryServiceTime)
              .build();
          listBuilder.add(new AddParcelEvent(dto));
        }
      }
      reader.close();
    } catch (final IOException e) {
      throw new IllegalArgumentException(e);
    }
    return listBuilder.build();
  }
  static class Gendreau06Reader implements Function<PathGendreau06Scenario> {
    @Override
    public Gendreau06Scenario apply(Path input) {
      return Gendreau06Parser.parse(input.toFile());
    }
  }
  interface ParcelsSupplier {
    
Should return an event list.

Parameters:
online If false, all events except time-out should have time -1.
Returns:
The list of events.
    ImmutableList<AddParcelEventget(boolean online);
  }
  static class InputStreamToParcels implements ParcelsSupplier {
    final InputStream inputStream;
       = is;
    }
    @Override
    public ImmutableList<AddParcelEventget(boolean online) {
      return parseParcels(online);
    }
  }
  static class Parcels implements ParcelsSupplier {
       = ps;
    }
    @Override
    public ImmutableList<AddParcelEventget(boolean online) {
      return ;
    }
  }
New to GrepCode? Check out our FAQ X