Ejemplo n.º 1
0
  public static void readWorkplaces(Scenario scenario, String file) {

    BufferedReader reader = IOUtils.getBufferedReader(file);

    final int idxX = 0;
    final int idxY = 1;

    int counter = 0;

    try {

      String line = reader.readLine();

      while ((line = reader.readLine()) != null) {

        String[] parts = line.split(",");

        Coord coord =
            Global.ct.transform(
                new Coord(Double.parseDouble(parts[idxX]), Double.parseDouble(parts[idxY])));

        ActivityFacility facility =
            scenario
                .getActivityFacilities()
                .getFactory()
                .createActivityFacility(
                    Id.create(Global.ActType.work.name() + "_" + counter, ActivityFacility.class),
                    coord);
        ActivityOption work =
            scenario
                .getActivityFacilities()
                .getFactory()
                .createActivityOption(Global.ActType.work.name());
        facility.addActivityOption(work);

        scenario.getActivityFacilities().addActivityFacility(facility);

        GAPScenarioBuilder.getWorkLocations()
            .put(facility.getCoord().getX(), facility.getCoord().getY(), facility);

        counter++;
      }

    } catch (IOException e) {

      e.printStackTrace();
    }
  }
Ejemplo n.º 2
0
  // Create external Facilities that are used by transit traffic agents.
  private static void createExternalFacilities(Scenario scenario, Set<Id<Node>> externalNodes) {

    ActivityFacilities activityFacilities = scenario.getActivityFacilities();
    ActivityFacilitiesFactory factory = activityFacilities.getFactory();

    /*
     * We check for all OutLinks of all external nodes if they already host a facility. If not,
     * a new facility with a tta ActivityOption will be created and added.
     */
    for (Id<Node> id : externalNodes) {
      Node externalNode = scenario.getNetwork().getNodes().get(id);

      for (Link externalLink : externalNode.getOutLinks().values()) {
        ActivityFacility facility = activityFacilities.getFacilities().get(externalLink.getId());

        // if already a facility exists we have nothing left to do
        if (facility != null) continue;

        /*
         * No Facility exists at that link therefore we create and add a new one.
         */
        double fromX = externalLink.getFromNode().getCoord().getX();
        double fromY = externalLink.getFromNode().getCoord().getY();
        double toX = externalLink.getToNode().getCoord().getX();
        double toY = externalLink.getToNode().getCoord().getY();

        double dX = toX - fromX;
        double dY = toY - fromY;

        double length = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));

        double centerX = externalLink.getCoord().getX();
        double centerY = externalLink.getCoord().getY();

        /*
         * Unit vector that directs with an angle of 90° away from the link.
         */
        double unitVectorX = dY / length;
        double unitVectorY = -dX / length;

        Coord coord = new Coord(centerX + unitVectorX, centerY + unitVectorY);

        facility =
            activityFacilities
                .getFactory()
                .createActivityFacility(
                    Id.create(externalLink.getId().toString(), ActivityFacility.class), coord);
        activityFacilities.addActivityFacility(facility);
        ((ActivityFacilityImpl) facility).setLinkId(externalLink.getId());

        ActivityOption activityOption = factory.createActivityOption(ttaActivityType);
        activityOption.addOpeningTime(new OpeningTimeImpl(0 * 3600, 24 * 3600));
        activityOption.setCapacity(capacity);
        facility.addActivityOption(activityOption);
      }
    }
  }
  /** test, that the number of created facilities corresponds to what is expected. */
  public void testGenerateParkingFacilities() {

    String inputPlansFile = getPackageInputDirectory() + "plans2.xml";
    String networkFile = "test/scenarios/berlin/network.xml.gz";

    Scenario scenario = ScenarioUtils.createScenario(super.loadConfig(null));
    new MatsimNetworkReader(scenario.getNetwork()).readFile(networkFile);
    new MatsimPopulationReader(scenario).readFile(inputPlansFile);

    GenerateParkingFacilities.generateParkingFacilties(scenario);

    ActivityFacilities facilities = scenario.getActivityFacilities();

    assertEquals(4, facilities.getFacilities().size());
  }
Ejemplo n.º 4
0
  // Create Facilities inside the simulated area.
  private static void createInternalFacilities(
      Scenario scenario,
      Map<Integer, Emme2Zone> zonalAttributes,
      Map<Integer, SimpleFeature> zonalShapes) {

    // create indices for the zones
    Map<Integer, Integer> indices = new HashMap<Integer, Integer>();
    int index = 0;
    for (Integer taz : zonalShapes.keySet()) {
      indices.put(taz, index);
      index++;
    }

    NetworkImpl network = (NetworkImpl) scenario.getNetwork();

    ActivityFacilities activityFacilities = scenario.getActivityFacilities();
    ObjectAttributes facilitiesAttributes = activityFacilities.getFacilityAttributes();
    ActivityFacilitiesFactory factory = activityFacilities.getFactory();

    for (Entry<Integer, SimpleFeature> entry : zonalShapes.entrySet()) {
      int taz = entry.getKey();
      SimpleFeature feature = entry.getValue();
      Geometry geometry = (Geometry) feature.getDefaultGeometry();
      List<Coord> coordinates = getRandomCoordinatesInZone(facilitiesPerZone, geometry, random);

      int i = 0;
      for (Coord coord : coordinates) {
        Id<ActivityFacility> id = Id.create(taz + "_" + i, ActivityFacility.class);
        ActivityFacility facility = factory.createActivityFacility(id, coord);
        createAndAddActivityOptions(scenario, facility, zonalAttributes.get(taz));
        activityFacilities.addActivityFacility(facility);
        Link link = network.getNearestLinkExactly(coord);
        ((ActivityFacilityImpl) facility).setLinkId(link.getId());
        i++;

        // Also add a tta activity to all facilities.
        ActivityOption activityOption = factory.createActivityOption(ttaActivityType);
        activityOption.addOpeningTime(new OpeningTimeImpl(0 * 3600, 24 * 3600));
        activityOption.setCapacity(capacity);
        facility.addActivityOption(activityOption);

        facilitiesAttributes.putAttribute(id.toString(), TAZObjectAttributesName, taz);
        facilitiesAttributes.putAttribute(
            id.toString(), indexObjectAttributesName, indices.get(taz));
      }
    }
  }
Ejemplo n.º 5
0
  // create f2l mapping file
  private static void createAndWriteF2LMapping(Scenario scenario) {
    log.info("creating f2l mapping and write it to a file ...");
    try {
      BufferedWriter bw = IOUtils.getBufferedWriter(basePath + f2lFile);

      // write Header
      bw.write("fid" + "\t" + "lid" + "\n");

      for (ActivityFacility facility : scenario.getActivityFacilities().getFacilities().values()) {
        bw.write(facility.getId().toString() + "\t" + facility.getLinkId().toString() + "\n");
      }

      bw.flush();
      bw.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    log.info("done.");
  }
Ejemplo n.º 6
0
  public static void main(final String[] args) {
    final String pathToFolder = args[0];
    final String pathToTargetFolder = args[1];
    final double xCoordCenter = Double.parseDouble(args[2]);
    final double yCoordCenter = Double.parseDouble(args[3]);
    final int radius = Integer.parseInt(args[4]);
    // For 30km around Zurich Center (Bellevue): X - 2683518.0, Y - 1246836.0, radius - 30000

    // load files
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new PopulationReaderMatsimV5(scenario).readFile(pathToFolder + POPULATION);
    ObjectAttributes personAttributes = new ObjectAttributes();
    new ObjectAttributesXmlReader(personAttributes).parse(pathToFolder + POPULATION_ATTRIBUTES);
    Households origHouseholds = new HouseholdsImpl();
    new HouseholdsReaderV10(origHouseholds).readFile(pathToFolder + HOUSEHOLDS);
    ObjectAttributes householdAttributes = new ObjectAttributes();
    new ObjectAttributesXmlReader(householdAttributes).parse(pathToFolder + HOUSEHOLD_ATTRIBUTES);
    new FacilitiesReaderMatsimV1(scenario).readFile(pathToFolder + FACILITIES);
    // cut to area
    ZHCutter cutter = new ZHCutter();
    cutter.setArea(new Coord(xCoordCenter, yCoordCenter), radius);
    Population filteredPopulation =
        cutter.geographicallyFilterPopulation(scenario.getPopulation(), personAttributes);
    Households filteredHouseholds =
        cutter.filterHouseholdsWithPopulation(origHouseholds, householdAttributes);
    ActivityFacilities filteredFacilities =
        cutter.filterFacilitiesWithPopulation(scenario.getActivityFacilities());
    // write new files
    new PopulationWriter(filteredPopulation).write(pathToTargetFolder + POPULATION);
    new ObjectAttributesXmlWriter(personAttributes)
        .writeFile(pathToTargetFolder + POPULATION_ATTRIBUTES);
    new HouseholdsWriterV10(filteredHouseholds).writeFile(pathToTargetFolder + HOUSEHOLDS);
    new ObjectAttributesXmlWriter(householdAttributes)
        .writeFile(pathToTargetFolder + HOUSEHOLD_ATTRIBUTES);
    new FacilitiesWriter(filteredFacilities).writeV1(pathToTargetFolder + FACILITIES);
  }
Ejemplo n.º 7
0
 public PopulationReaderMatsimV4(final Scenario scenario) {
   this.scenario = scenario;
   this.plans = scenario.getPopulation();
   this.network = scenario.getNetwork();
   this.facilities = scenario.getActivityFacilities();
 }
Ejemplo n.º 8
0
  /**
   * @param args
   * @throws FactoryException
   */
  public static void main(String[] args) throws FactoryException {
    String popFile = args[0];
    String facFile = args[1];
    String netFile = args[2];
    int n = Integer.parseInt(args[3]);
    String outDir = args[4];

    Logger logger = Logger.getLogger(DemoScenario.class);

    MathTransform transform = CRS.findMathTransform(CRSUtils.getCRS(31467), CRSUtils.getCRS(3857));

    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    /*
     * remove foreign persons and extract subsample
     */
    logger.info("Loading persons...");
    MatsimPopulationReader pReader = new MatsimPopulationReader(scenario);
    pReader.readFile(popFile);
    logger.info("Done.");

    logger.info("Removing foreign persons...");
    Set<Id<Person>> remove = new HashSet<>();
    for (Id<Person> id : scenario.getPopulation().getPersons().keySet()) {
      if (id.toString().startsWith("foreign")) {
        remove.add(id);
      }
    }

    int cnt = 0;
    for (Id<Person> id : remove) {
      if (scenario.getPopulation().getPersons().remove(id) != null) {
        cnt++;
      }
    }
    logger.info(String.format("Done. Removed %s foreign persons.", cnt));

    logger.info("Drawing population subsample...");
    List<Person> persons = new ArrayList<>(scenario.getPopulation().getPersons().values());
    Collections.shuffle(persons);
    Population population = PopulationUtils.createPopulation(config);
    cnt = 0;
    for (int i = 0; i < n; i++) {
      population.addPerson(persons.get(i));
    }
    logger.info("Done.");

    logger.info("Bluring activity end times...");
    Random random = new XORShiftRandom();
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          double endTim = act.getEndTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setEndTime(endTim);
          double startTim = act.getStartTime() - 15 * 60 + (random.nextDouble() * 30 * 60);
          act.setStartTime(startTim);
        }
      }
    }
    logger.info("Done.");

    logger.info("Writing population...");
    PopulationWriter pWriter = new PopulationWriter(population);
    pWriter.write(String.format("%s/plans.xml.gz", outDir));
    logger.info("Done.");
    /*
     * filter only used facilities
     */
    logger.info("Loading facilities...");
    MatsimFacilitiesReader fReader = new MatsimFacilitiesReader(scenario);
    fReader.readFile(facFile);
    logger.info("Done.");

    logger.info("Removing unsused facilities...");
    Set<Id<ActivityFacility>> unused =
        new HashSet<>(scenario.getActivityFacilities().getFacilities().keySet());
    for (Person person : population.getPersons().values()) {
      for (Plan plan : person.getPlans()) {
        for (int i = 0; i < plan.getPlanElements().size(); i += 2) {
          Activity act = (Activity) plan.getPlanElements().get(i);
          unused.remove(act.getFacilityId());
        }
      }
    }
    logger.info("Done.");

    logger.info("Transforming facility coordinates...");
    for (ActivityFacility fac : scenario.getActivityFacilities().getFacilities().values()) {
      double[] points = new double[] {fac.getCoord().getX(), fac.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((ActivityFacilityImpl) fac).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing facilities...");
    FacilitiesWriter fWrtier = new FacilitiesWriter(scenario.getActivityFacilities());
    fWrtier.write(String.format("%s/facilities.xml.gz", outDir));
    logger.info("Done.");
    /*
     * clean network from foreign links
     */
    logger.info("Loading network...");
    MatsimNetworkReader nReader = new MatsimNetworkReader(scenario);
    nReader.readFile(netFile);
    logger.info("Done.");

    logger.info("Removing foreign links...");
    Set<Id<Link>> linksRemove = new HashSet<>();
    for (Id<Link> id : scenario.getNetwork().getLinks().keySet()) {
      if (id.toString().contains(".l")) {
        linksRemove.add(id);
      }
    }

    for (Id<Link> id : linksRemove) {
      scenario.getNetwork().removeLink(id);
    }
    logger.info("Done.");

    logger.info("Removing foreign nodes...");
    Set<Id<Node>> nodesRemove = new HashSet<>();
    for (Id<Node> id : scenario.getNetwork().getNodes().keySet()) {
      if (id.toString().contains(".n")) {
        nodesRemove.add(id);
      }
    }

    for (Id<Node> id : nodesRemove) {
      scenario.getNetwork().removeNode(id);
    }
    logger.info("Done.");

    logger.info("Transforming node coordinates...");
    for (Node node : scenario.getNetwork().getNodes().values()) {
      double[] points = new double[] {node.getCoord().getX(), node.getCoord().getY()};
      try {
        transform.transform(points, 0, points, 0, 1);
      } catch (TransformException e) {
        e.printStackTrace();
      }

      ((NodeImpl) node).setCoord(new Coord(points[0], points[1]));
    }
    logger.info("Done.");

    logger.info("Writing network...");
    NetworkWriter nWriter = new NetworkWriter(scenario.getNetwork());
    nWriter.write(String.format("%s/network.xml.gz", outDir));
    logger.info("Done.");
  }
  public static void main(String[] args) {
    // Input and output
    String networkFile =
        "../../matsimExamples/countries/za/nmbm/network/NMBM_Network_CleanV7.xml.gz";
    String facilitiesFile =
        "../../matsimExamples/countries/za/nmbm/facilities/20121010/facilities.xml.gz";
    String outputDirectory = "../../accessibility-sa/data/12/";
    //		String travelTimeMatrix = folderStructure +
    // "matsimExamples/countries/za/nmbm/minibus-pt/JTLU_14i_06/travelTimeMatrix.csv.gz";
    //		String travelDistanceMatrix = folderStructure +
    // "matsimExamples/countries/za/nmbm/minibus-pt/JTLU_14i_06/travelDistanceMatrix.csv.gz";
    //		String ptStops = folderStructure +
    // "matsimExamples/countries/za/nmbm/minibus-pt/JTLU_14i_06/measuringPointsAsStops.csv.gz";
    //		String minibusPtTravelTimeMatrix = folderStructure +
    // "matsimExamples/countries/za/nmbm/minibus-pt/JTLU_14i_07/travelTimeMatrix.csv";
    //		String minibusPtTravelDistanceMatrix = folderStructure +
    // "matsimExamples/countries/za/nmbm/minibus-pt/JTLU_14i_07/travelDistanceMatrix.csv";
    //		String measuringPointsAsPtStops = folderStructure +
    // "matsimExamples/countries/za/nmbm/minibus-pt/JTLU_14i_07/measuringPointsAsStops.csv";

    // Parameters
    boolean includeDensityLayer = true;
    String crs = TransformationFactory.WGS84_SA_Albers;
    Double lowerBound = 2.;
    Double upperBound = 5.5;
    Integer range = 9;
    int symbolSize = 1010;
    int populationThreshold = (int) (200 / (1000 / cellSize * 1000 / cellSize));

    final Config config = ConfigUtils.createConfig(new AccessibilityConfigGroup());
    config.controler().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists);
    config.controler().setOutputDirectory(outputDirectory);
    config.network().setInputFile(networkFile);
    config.facilities().setInputFile(facilitiesFile);

    config.controler().setLastIteration(0);

    final Scenario scenario = ScenarioUtils.loadScenario(config);

    String typeWEQ = "w-eq";
    List<String> activityTypes = new ArrayList<>();
    activityTypes.add(typeWEQ);

    final ActivityFacilities homes = FacilitiesUtils.createActivityFacilities("homes");
    final ActivityFacilities amenities = FacilitiesUtils.createActivityFacilities("amenities");
    for (ActivityFacility fac : scenario.getActivityFacilities().getFacilities().values()) {
      for (ActivityOption option : fac.getActivityOptions().values()) {
        // figure out all activity types
        if (!activityTypes.contains(option.getType())) {
          activityTypes.add(option.getType());
        }

        // add all facilites that are not home or work
        if (!option.getType().equals("h")
            && !option.getType().equals("w")
            && !option.getType().equals("minor")) {
          if (!amenities.getFacilities().containsKey(fac.getId())) {
            amenities.addActivityFacility(fac);
          }
        }

        // figure out where the homes are
        if (option.getType().equals("h")) {
          homes.addActivityFacility(fac);
        }
      }
    }

    // extends of the network are (as they can looked up by using the bounding box):
    // minX = 111083.9441831379, maxX = 171098.03695045778, minY = -3715412.097693177,	maxY =
    // -3668275.43481496

    //		double[] mapViewExtent = {100000,-3720000,180000,-3675000}; // choose map view a bit bigger
    double[] mapViewExtent = {
      115000, -3718000, 161000, -3679000
    }; // what actually needs to be drawn

    Controler controler = new Controler(scenario);
    controler.addOverridingModule(
        new AbstractModule() {
          @Override
          public void install() {
            addControlerListenerBinding()
                .toProvider(
                    new Provider<ControlerListener>() {
                      @Inject Scenario scenario;
                      @Inject Map<String, TravelTime> travelTimes;
                      @Inject Map<String, TravelDisutilityFactory> travelDisutilityFactories;

                      @Override
                      public ControlerListener get() {
                        GridBasedAccessibilityControlerListenerV3 listener =
                            new GridBasedAccessibilityControlerListenerV3(
                                amenities,
                                null,
                                config,
                                scenario,
                                travelTimes,
                                travelDisutilityFactories);
                        listener.setComputingAccessibilityForMode(
                            Modes4Accessibility.freeSpeed, true);
                        listener.addAdditionalFacilityData(homes);
                        listener.generateGridsAndMeasuringPointsByNetwork(cellSize);
                        listener.writeToSubdirectoryWithName("w-eq");
                        listener.setUrbansimMode(
                            false); // avoid writing some (eventually: all) files that related to
                                    // matsim4urbansim
                        return listener;
                      }
                    });
          }
        });
    controler.run();

    String workingDirectory = config.controler().getOutputDirectory();

    String osName = System.getProperty("os.name");

    //		for (String actType : activityTypes) {
    String actSpecificWorkingDirectory = workingDirectory + typeWEQ + "/";

    for (Modes4Accessibility mode : Modes4Accessibility.values()) {
      //				VisualizationUtilsDZ.createQGisOutput(typeWEQ, mode, mapViewExtent, workingDirectory,
      // crs, includeDensityLayer);
      VisualizationUtilsDZ.createQGisOutput(
          typeWEQ,
          mode,
          mapViewExtent,
          workingDirectory,
          crs,
          includeDensityLayer,
          lowerBound,
          upperBound,
          range,
          symbolSize,
          populationThreshold);
      VisualizationUtilsDZ.createSnapshot(actSpecificWorkingDirectory, mode, osName);
    }
    //		}
  }
Ejemplo n.º 10
0
  /**
   * Parses a given osm file in order to extract the amenities defined in it. Amenities are needed
   * to create activity facilities for activity types
   *
   * <ul>
   *   <li>tourism (splitted into tourism1 (tourist's 'home') and tourism2 (attractions)
   *   <li>education
   *   <li>shop
   * </ul>
   *
   * @param scenario
   */
  public static void initAmenities(Scenario scenario) {

    Map<String, String> osmToMatsimTypeMap = new HashMap<>();
    osmToMatsimTypeMap.put("alpine_hut", "tourism1");
    osmToMatsimTypeMap.put("apartment", "tourism1");
    osmToMatsimTypeMap.put("attraction", "tourism2");
    osmToMatsimTypeMap.put("artwork", "tourism2");
    osmToMatsimTypeMap.put("camp_site", "tourism1");
    osmToMatsimTypeMap.put("caravan_site", "tourism1");
    osmToMatsimTypeMap.put("chalet", "tourism1");
    osmToMatsimTypeMap.put("gallery", "tourism2");
    osmToMatsimTypeMap.put("guest_house", "tourism1");
    osmToMatsimTypeMap.put("hostel", "tourism1");
    osmToMatsimTypeMap.put("hotel", "tourism1");
    osmToMatsimTypeMap.put("information", "tourism2");
    osmToMatsimTypeMap.put("motel", "tourism1");
    osmToMatsimTypeMap.put("museum", "tourism2");
    osmToMatsimTypeMap.put("picnic_site", "tourism2");
    osmToMatsimTypeMap.put("theme_park", "tourism2");
    osmToMatsimTypeMap.put("viewpoint", "tourism2");
    osmToMatsimTypeMap.put("wilderness_hut", "tourism1");
    osmToMatsimTypeMap.put("zoo", "tourism2");

    // education
    osmToMatsimTypeMap.put("college", "education");
    osmToMatsimTypeMap.put("kindergarten", "education");
    osmToMatsimTypeMap.put("school", "education");
    osmToMatsimTypeMap.put("university", "education");

    // leisure
    osmToMatsimTypeMap.put("arts_centre", "leisure");
    osmToMatsimTypeMap.put("cinema", "leisure");
    osmToMatsimTypeMap.put("community_centre", "leisure");
    osmToMatsimTypeMap.put("fountain", "leisure");
    osmToMatsimTypeMap.put("nightclub", "leisure");
    osmToMatsimTypeMap.put("planetarium", "leisure");
    osmToMatsimTypeMap.put("social_centre", "leisure");
    osmToMatsimTypeMap.put("theatre", "leisure");

    // shopping
    osmToMatsimTypeMap.put("alcohol", "shop");
    osmToMatsimTypeMap.put("bakery", "shop");
    osmToMatsimTypeMap.put("beverages", "shop");
    osmToMatsimTypeMap.put("butcher", "shop");
    osmToMatsimTypeMap.put("cheese", "shop");
    osmToMatsimTypeMap.put("chocolate", "shop");
    osmToMatsimTypeMap.put("coffee", "shop");
    osmToMatsimTypeMap.put("confectionery", "shop");
    osmToMatsimTypeMap.put("convenience", "shop");
    osmToMatsimTypeMap.put("deli", "shop");
    osmToMatsimTypeMap.put("dairy", "shop");
    osmToMatsimTypeMap.put("farm", "shop");
    osmToMatsimTypeMap.put("greengrocer", "shop");
    osmToMatsimTypeMap.put("pasta", "shop");
    osmToMatsimTypeMap.put("pastry", "shop");
    osmToMatsimTypeMap.put("seafood", "shop");
    osmToMatsimTypeMap.put("tea", "shop");
    osmToMatsimTypeMap.put("wine", "shop");
    osmToMatsimTypeMap.put("department_store", "shop");
    osmToMatsimTypeMap.put("general", "shop");
    osmToMatsimTypeMap.put("kiosk", "shop");
    osmToMatsimTypeMap.put("mall", "shop");
    osmToMatsimTypeMap.put("supermarket", "shop");
    osmToMatsimTypeMap.put("baby_goods", "shop");
    osmToMatsimTypeMap.put("bag", "shop");
    osmToMatsimTypeMap.put("boutique", "shop");
    osmToMatsimTypeMap.put("clothes", "shop");
    osmToMatsimTypeMap.put("fabric", "shop");
    osmToMatsimTypeMap.put("fashion", "shop");
    osmToMatsimTypeMap.put("jewelry", "shop");
    osmToMatsimTypeMap.put("leather", "shop");
    osmToMatsimTypeMap.put("shoes", "shop");
    osmToMatsimTypeMap.put("tailor", "shop");
    osmToMatsimTypeMap.put("watches", "shop");
    // TODO many more types of amenities to come...

    Set<String> keys = new HashSet<>();
    keys.add("tourism");
    keys.add("amenity");
    keys.add("shop");

    OsmObjectsToFacilitiesParser reader =
        new OsmObjectsToFacilitiesParser(
            Global.dataDir + "/Netzwerk/garmisch-latest.osm", Global.ct, osmToMatsimTypeMap, keys);
    reader.parse();
    //		reader.writeFacilities(Global.matsimInputDir + "facilities/facilities.xml");
    //		reader.writeFacilityAttributes(Global.matsimInputDir + "facilities/facilityAttribues.xml");
    reader.writeFacilityCoordinates(Global.matsimInputDir + "facilities.csv");

    for (ActivityFacility facility : reader.getFacilities().getFacilities().values()) {

      scenario.getActivityFacilities().addActivityFacility(facility);
    }
  }
Ejemplo n.º 11
0
  /*
   * Creates and adds the possible activities to the facility. The capacities
   * have to defined elsewhere...
   *
   * home	/	no (Activity)	/	0 .. 24
   * work	/	work	/	8 .. 18
   * education	/	study	/	8 .. 18
   * shopping	/	shopping	/	9 .. 19
   * leisure	/	other	6 .. 22
   *
   * Mapping from the zones file:
   *
   * Cultural Areas -> leisure, work
   * Education -> education_university, education_highschool, education_elementaryschool, work
   * Office -> work
   * Shopping -> leisure, work
   * Health Institutions -> work, leisure
   * Urban Cores -> ignore
   * Religions Character -> ignore
   * Transportation -> work, leisure (airport, big train stations, etc.)
   */
  private static void createAndAddActivityOptions(
      Scenario scenario, ActivityFacility facility, Emme2Zone zone) {

    boolean hasHome = false;
    boolean hasWork = false;
    boolean hasEducationUniversity = false;
    boolean hasEducationHighSchool = false;
    boolean hasEducationElementarySchool = false;
    boolean hasShopping = false;
    boolean hasLeisure = false;

    hasHome = zone.hasHome();
    hasWork = zone.hasWork();
    hasEducationUniversity = zone.hasEducationUniversity();
    hasEducationHighSchool = zone.hasEducationHighSchool();
    hasEducationElementarySchool = zone.hasEducationElementarySchool();
    hasShopping = zone.hasShopping();
    hasLeisure = zone.hasLeisure();
    //		if (zone.POPULATION > 0) { hasHome = true; }
    //		if (zone.CULTURAL > 0) { hasLeisure = true; hasWork = true; }
    //		if (zone.EDUCATION == 1) { hasEducationUniversity = true; hasWork = true; }
    //		if (zone.EDUCATION == 2) { hasEducationHighSchool = true; hasWork = true; }
    //		if (zone.EDUCATION == 3) { hasEducationElementarySchool = true; hasWork = true; }
    //		if (zone.OFFICE > 0) { hasWork = true; }
    //		if (zone.SHOPPING > 0) { hasShopping = true; hasWork = true; }
    //		if (zone.HEALTH > 0) { hasLeisure = true; hasWork = true; }
    //		if (zone.TRANSPORTA > 0) { hasLeisure = true; hasWork = true; }
    //		if (zone.EMPL_TOT > 0) { hasWork = true; }

    // "Other" activities - should be possible in every zone.
    //		hasLeisure = true;

    // "Shopping" activities - should be possible in every zone.
    //		hasShopping = true;

    ActivityOption activityOption;

    ActivityFacilitiesFactory factory = scenario.getActivityFacilities().getFactory();

    if (hasHome) {
      activityOption = factory.createActivityOption("home");
      facility.addActivityOption(activityOption);
      activityOption.addOpeningTime(new OpeningTimeImpl(0 * 3600, 24 * 3600));
      activityOption.setCapacity(capacity);
    }

    if (hasWork) {
      activityOption = factory.createActivityOption("work");
      facility.addActivityOption(activityOption);
      activityOption.addOpeningTime(new OpeningTimeImpl(8 * 3600, 18 * 3600));
      activityOption.setCapacity(capacity);
    }

    if (hasEducationUniversity) {
      activityOption = factory.createActivityOption("education_university");
      facility.addActivityOption(activityOption);
      activityOption.addOpeningTime(new OpeningTimeImpl(9 * 3600, 18 * 3600));
      activityOption.setCapacity(capacity);
    }

    if (hasEducationHighSchool) {
      activityOption = factory.createActivityOption("education_highschool");
      facility.addActivityOption(activityOption);
      activityOption.addOpeningTime(new OpeningTimeImpl(8 * 3600, 16 * 3600));
      activityOption.setCapacity(capacity);
    }

    if (hasEducationElementarySchool) {
      activityOption = factory.createActivityOption("education_elementaryschool");
      facility.addActivityOption(activityOption);
      activityOption.addOpeningTime(new OpeningTimeImpl(8 * 3600, 14 * 3600));
      activityOption.setCapacity(capacity);
    }

    if (hasShopping) {
      activityOption = factory.createActivityOption("shopping");
      facility.addActivityOption(activityOption);
      activityOption.addOpeningTime(new OpeningTimeImpl(9 * 3600, 19 * 3600));
      activityOption.setCapacity(capacity);
    }

    if (hasLeisure) {
      activityOption = factory.createActivityOption("leisure");
      facility.addActivityOption(activityOption);
      activityOption.addOpeningTime(new OpeningTimeImpl(6 * 3600, 22 * 3600));
      activityOption.setCapacity(capacity);
    }
  }
Ejemplo n.º 12
0
  public static void main(String[] args) {
    try {
      if (args.length > 0) {
        String file = args[0];
        Map<String, String> parameterMap = new XMLParameterParser().parseFile(file);
        String value;

        value = parameterMap.remove("basePath");
        if (value != null) basePath = value;

        value = parameterMap.remove("networkFile");
        if (value != null) networkFile = value;

        value = parameterMap.remove("zonalAttributesFile");
        if (value != null) zonalAttributesFile = value;

        value = parameterMap.remove("separator");
        if (value != null) separator = value;

        value = parameterMap.remove("zonalSHPFile");
        if (value != null) zonalSHPFile = value;

        value = parameterMap.remove("facilitiesFile");
        if (value != null) facilitiesFile = value;

        value = parameterMap.remove("facilitiesAttributesFile");
        if (value != null) facilitiesAttributesFile = value;

        value = parameterMap.remove("f2lFile");
        if (value != null) f2lFile = value;

        value = parameterMap.remove("facilitiesPerZone");
        if (value != null) facilitiesPerZone = Integer.parseInt(value);

        value = parameterMap.remove("validLinkTypes");
        if (value != null) validLinkTypes = CollectionUtils.stringToSet(value);

        for (String key : parameterMap.keySet())
          log.warn("Found parameter " + key + " which is not handled!");
      } else {
        log.error("No input config file was given. Therefore cannot proceed. Aborting!");
        return;
      }

      log.info("loading network ...");
      Config config = ConfigUtils.createConfig();
      config.network().setInputFile(basePath + networkFile);
      Scenario scenario = ScenarioUtils.loadScenario(config);
      log.info("done.\n");

      log.info("loading zonal attributes ...");
      boolean skipHeader = true;
      Map<Integer, Emme2Zone> zonalAttributes =
          new Emme2ZonesFileParser(basePath + zonalAttributesFile, separator).readFile(skipHeader);
      log.info("done.\n");

      log.info("loading zonal shp file ...");
      // use a TreeMap to be deterministic
      Map<Integer, SimpleFeature> zonalShapes = new TreeMap<Integer, SimpleFeature>();
      for (SimpleFeature feature : ShapeFileReader.getAllFeatures(basePath + zonalSHPFile)) {
        zonalShapes.put((Integer) feature.getAttribute(3), feature);
      }
      log.info("done.\n");

      log.info("identify nodes outside the model area ...");
      Set<Id<Node>> externalNodes = getExternalNodes(scenario, zonalShapes);
      log.info("\tfound " + externalNodes.size() + " nodes outside the mapped area");
      log.info("done.\n");

      /*
       * We have to create tta activities BEFORE filtering the network. They might also start
       * and end at highways. We do not know their real start and end positions. The coordinate
       * we know might only be the place where the agents enter the modeled area, which will
       * probably be by using a highway.
       */
      log.info("creating external facilities for tta activities ...");
      createExternalFacilities(scenario, externalNodes);
      log.info("done.\n");

      /*
       * Before creating the internal facilities, we can perform the links filtering.
       */
      log.info("removing links from network where no facilities should be attached to ...");
      List<Id<Link>> linksToRemove = new ArrayList<Id<Link>>();
      for (Link link : scenario.getNetwork().getLinks().values()) {
        String type = ((LinkImpl) link).getType();
        if (!validLinkTypes.contains(type)) linksToRemove.add(link.getId());
      }
      log.info("\tfound " + linksToRemove.size() + " links which do not match the criteria");
      for (Id<Link> linkId : linksToRemove)
        ((NetworkImpl) scenario.getNetwork()).removeLink(linkId);
      log.info(
          "\tprocessed network contains "
              + scenario.getNetwork().getLinks().size()
              + " valid links");
      log.info("done.\n");

      log.info("creating internal facilities ...");
      createInternalFacilities(scenario, zonalAttributes, zonalShapes);
      log.info("done.\n");

      log.info("writing facilities to links mapping to a file ...");
      createAndWriteF2LMapping(scenario);
      log.info("done.\n");

      log.info(
          "writing "
              + scenario.getActivityFacilities().getFacilities().size()
              + " facilities to a file ...");
      FacilitiesWriter facilitiesWriter = new FacilitiesWriter(scenario.getActivityFacilities());
      facilitiesWriter.write(basePath + facilitiesFile);
      new ObjectAttributesXmlWriter(scenario.getActivityFacilities().getFacilityAttributes())
          .writeFile(basePath + facilitiesAttributesFile);
      log.info("done.\n");
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 13
0
 @Override
 public ActivityFacilities getActivityFacilities() {
   return delegate.getActivityFacilities();
 }
Ejemplo n.º 14
0
public class AssignShopAndLeisure {
  private final Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
  private final Population plans = scenario.getPopulation();
  private final ActivityFacilities facilities = scenario.getActivityFacilities();
  private final Network network = scenario.getNetwork();

  private String plansfilePath;
  private String facilitiesfilePath;
  private String networkfilePath;
  private final String outpath = "output/plans/";

  private static final Logger log = Logger.getLogger(AssignShopAndLeisure.class);

  public static void main(final String[] args) {
    Gbl.startMeasurement();
    final AssignShopAndLeisure assigner = new AssignShopAndLeisure();
    assigner.run(args[0]);
    Gbl.printElapsedTime();
  }

  public void run(String variant) {
    this.init();
    if (variant.equals("0")) {
      ActivityDifferentiationShop differentiator = new ActivityDifferentiationShop(this.scenario);
      differentiator.run();
    }
    // handle leisure
    // ...

    this.writePlans(variant);
  }

  private void readInputFile(final String inputFile) {
    try {
      FileReader fileReader = new FileReader(inputFile);
      BufferedReader bufferedReader = new BufferedReader(fileReader);

      this.networkfilePath = bufferedReader.readLine();
      this.facilitiesfilePath = bufferedReader.readLine();
      this.plansfilePath = bufferedReader.readLine();

      bufferedReader.close();
      fileReader.close();

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private void init() {

    String pathsFile = "./input/trb/valid/paths.txt";
    this.readInputFile(pathsFile);

    log.info("reading the facilities ...");
    new FacilitiesReaderMatsimV1(this.scenario).readFile(facilitiesfilePath);

    log.info("reading the network ...");
    new MatsimNetworkReader(this.scenario.getNetwork()).readFile(networkfilePath);

    log.info("  reading file " + plansfilePath);
    final PopulationReader plansReader = new MatsimPopulationReader(this.scenario);
    plansReader.readFile(plansfilePath);
  }

  private void writePlans(String variant) {
    if (variant.equals("0")) {
      new PopulationWriter(this.plans, this.network).write(this.outpath + "plans0.xml.gz");
    } else {
      new PopulationWriter(this.plans, this.network).write(this.outpath + "plans1.xml.gz");
    }
  }
}