コード例 #1
0
ファイル: MyNetworkGenerator.java プロジェクト: krlmlr/matsim
  public static void main(String[] args) {
    String osm = "/Users/johanwjoubert/Downloads/map.osm";

    Network net = NetworkImpl.createNetwork();
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, UTM35S);

    OsmNetworkReader onr = new OsmNetworkReader(net, ct);
    onr.setHierarchyLayer(-25.8875, 28.1204, -25.9366, 28.1612, 6);
    onr.parse(osm);
    new NetworkCleaner().run(net);
    new NetworkWriter(net).write("/Users/johanwjoubert/Desktop/Temp/network.xml");

    Config c =
        ((ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig())).getConfig();
    c.global().setCoordinateSystem(UTM35S);

    // TODO Sort out these errors: Cannot instatiate FeatureGeneratorBuilder.

    //		FeatureGeneratorBuilder fgb = new FeatureGeneratorBuilderImpl(net, UTM35S);
    //		FeatureGenerator builder = fgb.createFeatureGenerator();
    //
    //		builder.setWidthCoefficient(0.01);
    //		builder.setFeatureGeneratorPrototype(PolygonFeatureGenerator.class);
    //		builder.setWidthCalculatorPrototype(CapacityBasedWidthCalculator.class);
    //		new Links2ESRIShape(net,"/Users/johanwjoubert/Desktop/Temp/network.shp", builder).write();

  }
コード例 #2
0
  public boolean loadNetFromOSM(final String path, final String crs) {
    // REVISAR UTM33N a UTM19N
    //        String UTM19N_PROJCS =
    // "PROJCS[\"WGS_1984_UTM_Zone_19N\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"latitude_of_origin\",0],PARAMETER[\"central_meridian\",-69],PARAMETER[\"scale_factor\",0.9996],PARAMETER[\"false_easting\",500000],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]";
    //	String crs = UTM19N_PROJCS; // the coordinate reference system to be used.

    this.crs = crs;
    String osm = path;

    Scenario sc = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Network net = sc.getNetwork();

    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, crs);

    OsmNetworkReader onr = new OsmNetworkReader(net, ct); // constructs a new openstreetmap reader
    try {
      onr.parse(osm); // starts the conversion from osm to matsim
    } catch (UncheckedIOException e) {
      e.printStackTrace();
      return false;
    }
    // at this point we already have a matsim network...
    new NetworkCleaner()
        .run(net); // but may be there are isolated (not connected) links. The network cleaner
    // removes those links
    board.setNetwork((NetworkImpl) net);
    board.repaint();
    return true;
  }
コード例 #3
0
  /** @param args */
  public static void main(String[] args) {

    String input = args[0];
    String output = args[1];

    /* Read the network. */
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario.getNetwork()).readFile(input);

    /* Transform each node. */
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, "EPSG:25832");
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84,TransformationFactory.DHDN_GK4);

    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation("EPSG:25832",TransformationFactory.WGS84);
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.DHDN_GK4,TransformationFactory.WGS84);

    for (Node node : scenario.getNetwork().getNodes().values()) {
      ((Node) node).setCoord(ct.transform(node.getCoord()));
    }

    /* Write the resulting network. */
    new NetworkWriter(scenario.getNetwork()).write(output);
  }
コード例 #4
0
ファイル: PlansDumpingImpl.java プロジェクト: sebhoerl/matsim
  @Override
  public void notifyBeforeMobsim(final BeforeMobsimEvent event) {
    if ((writePlansInterval > 0)
        && ((event.getIteration() % writePlansInterval == 0)
            || (event.getIteration() == (firstIteration + 1)))) {
      stopwatch.beginOperation("dump all plans");
      log.info("dumping plans...");
      final String inputCRS = config.plans().getInputCRS();
      final String internalCRS = config.global().getCoordinateSystem();

      if (inputCRS == null) {
        new PopulationWriter(population, network)
            .write(controlerIO.getIterationFilename(event.getIteration(), "plans.xml.gz"));
      } else {
        log.info(
            "re-projecting population from " + internalCRS + " to " + inputCRS + " for export");

        final CoordinateTransformation transformation =
            TransformationFactory.getCoordinateTransformation(internalCRS, inputCRS);

        new PopulationWriter(transformation, population, network)
            .write(controlerIO.getIterationFilename(event.getIteration(), "plans.xml.gz"));
      }
      log.info("finished plans dump.");
      stopwatch.endOperation("dump all plans");
    }
  }
コード例 #5
0
ファイル: NetConverter.java プロジェクト: sebhoerl/matsim
  public void convertCoordinates(Network net, String outputFile) {

    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            "EPSG:32719", TransformationFactory.WGS84);

    for (Node node : net.getNodes().values()) {
      Coord newCoord = ct.transform(node.getCoord());
      ((NodeImpl) node).setCoord(newCoord);
    }

    new NetworkWriter(net).write(outputFile);
  }
コード例 #6
0
  protected void write(
      final OccupancyAnalyzer ocupAnalizer, final int itNum, final boolean stopZoneConversion) {

    PtCountComparisonAlgorithm4confTimeBinSize ccaOccupancy =
        new PtCountComparisonAlgorithm4confTimeBinSize(ocupAnalizer, occupCounts, net, scalefactor);
    ccaOccupancy.calculateComparison();

    // set and use kml writter
    Config config = controler.getConfig();
    PtCountSimComparisonKMLWriter kmlWriter =
        new PtCountSimComparisonKMLWriter(
            ccaOccupancy.getComparison(),
            ccaOccupancy.getComparison(),
            ccaOccupancy.getComparison(),
            TransformationFactory.getCoordinateTransformation(
                config.global().getCoordinateSystem(), TransformationFactory.WGS84),
            occupCounts,
            occupCounts,
            occupCounts);
    kmlWriter.setIterationNumber(itNum);

    // write counts comparison
    String kmlFile;
    String ocuppCompTxtFile;
    String outDir;
    if (controler.getControlerIO() != null) {
      kmlFile = controler.getControlerIO().getIterationFilename(itNum, kmzFile);
      ocuppCompTxtFile = controler.getControlerIO().getIterationFilename(itNum, txtCompFile);
      outDir = controler.getControlerIO().getIterationPath(itNum) + S;
    } else { // <-it happens when this method is invoked outside a simulation run
      outDir =
          controler.getConfig().controler().getOutputDirectory() + ITERS + itNum + SL + itNum + PNT;
      kmlFile = outDir + kmzFile;
      ocuppCompTxtFile = outDir + txtCompFile;
    }
    kmlWriter.writeFile(kmlFile);
    ccaOccupancy.write(ocuppCompTxtFile);

    //// extract the specific plot in the iteration folder
    String plotName = (stopZoneConversion) ? STR_HOUROCCUPPLOT : STR_ERRPLOT;
    KMZ_Extractor extractor = new KMZ_Extractor(kmlFile, outDir);
    extractor.extractFile(plotName);
    log.info(kmlFile + strDONE);

    plotName = null;
    extractor = null;
    outDir = null;
    kmlFile = null;
    ccaOccupancy = null;
    kmlWriter = null;
  }
コード例 #7
0
ファイル: NetConverter.java プロジェクト: sebhoerl/matsim
  public void createNetwork(String osmFile, String outputFile) {

    Config config = ConfigUtils.createConfig();
    Scenario scenario = ScenarioUtils.createScenario(config);
    Network network = scenario.getNetwork();
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, "EPSG:32719");
    OsmNetworkReader onr = new OsmNetworkReader(network, ct);
    onr.parse(osmFile);
    new NetworkCleaner().run(network);

    new NetworkWriter(network).write(outputFile);
  }
コード例 #8
0
 private void write(final String filename) {
   // init kml
   this.mainKml = this.kmlObjectFactory.createKmlType();
   this.mainDoc = this.kmlObjectFactory.createDocumentType();
   this.mainKml.setAbstractFeatureGroup(this.kmlObjectFactory.createDocument(mainDoc));
   // create a folder
   this.mainFolder = this.kmlObjectFactory.createFolderType();
   this.mainFolder.setName("Matsim Data");
   this.mainDoc.getAbstractFeatureGroup().add(this.kmlObjectFactory.createFolder(this.mainFolder));
   // the writer
   this.writer = new KMZWriter(filename);
   Set<Plan> planSetBig = filterPlans();
   log.info("Found " + planSetBig.size() + " relevant plans");
   int i = 0;
   int max = 50;
   Set<Plan> planSet = new HashSet<Plan>(max);
   for (Plan p : planSetBig) {
     planSet.add(p);
     i++;
     if (i > max) break;
   }
   try {
     // add the matsim logo to the kml
     ScreenOverlayType logo = MatsimKMLLogo.writeMatsimKMLLogo(writer);
     this.mainFolder
         .getAbstractFeatureGroup()
         .add(this.kmlObjectFactory.createScreenOverlay(logo));
     KmlPlansWriter plansWriter =
         new KmlPlansWriter(
             this.scenario.getNetwork(),
             TransformationFactory.getCoordinateTransformation(
                 this.scenario.getConfig().global().getCoordinateSystem(),
                 TransformationFactory.WGS84),
             this.writer,
             this.mainDoc);
     FolderType plansFolder = plansWriter.getPlansFolder(planSet);
     this.mainFolder
         .getAbstractFeatureGroup()
         .add(this.kmlObjectFactory.createFolder(plansFolder));
   } catch (IOException e) {
     log.error("Cannot create kmz or logo.", e);
   }
   this.writer.writeMainKml(this.mainKml);
   this.writer.close();
   log.info("Plans written to kmz: " + filename);
 }
コード例 #9
0
ファイル: PlanExpander.java プロジェクト: krlmlr/matsim
  public static void main(String[] args) {

    String networkFile = "./bb_cl.xml.gz";
    String plansFile = "./baseplan";
    int numberOfAdditionalCopies = 9;
    double radiusOfPerimeter = 1000.0;

    Gbl.startMeasurement();

    ScenarioImpl sc = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());

    Network net = sc.getNetwork();
    new MatsimNetworkReader(sc).readFile(networkFile);

    Population inPop = sc.getPopulation();
    PopulationReader popReader = new MatsimPopulationReader(sc);
    popReader.readFile(plansFile + ".xml.gz");

    DuplicatePlans dp = new DuplicatePlans(net, inPop, "tmp.xml.gz", numberOfAdditionalCopies);
    dp.run(inPop);
    dp.writeEndPlans();

    System.out.println("Dublicating plans finished");
    Gbl.printElapsedTime();

    inPop =
        ((ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig())).getPopulation();
    popReader = new MatsimPopulationReader(new SharedNetScenario(sc, inPop));
    popReader.readFile("tmp.xml.gz");

    ShuffleCoords shuffleCoords =
        new ShuffleCoords(
            net,
            inPop,
            plansFile + "_" + (numberOfAdditionalCopies + 1) + "x.xml.gz",
            radiusOfPerimeter,
            TransformationFactory.getCoordinateTransformation(
                TransformationFactory.DHDN_GK4, TransformationFactory.DHDN_GK4));
    shuffleCoords.setChangeHomeActsOnlyOnceTrue("home");
    shuffleCoords.run(inPop);
    shuffleCoords.writeEndPlans();

    (new File("tmp.xml.gz")).deleteOnExit();

    Gbl.printElapsedTime();
  }
コード例 #10
0
  public static void main(String[] args) {
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    Map<String, Set<String>> tagKeyValues = new HashMap<String, Set<String>>();
    tagKeyValues.put(
        "highway",
        new HashSet<String>(
            Arrays.asList(
                "motorway",
                "motorway_link",
                "trunk",
                "trunk_link",
                "primary",
                "primary_link",
                "secondary",
                "tertiary",
                "minor",
                "unclassified",
                "residential",
                "living_street")));
    String filename = "inputs/schweiz/zurich.osm";
    Set<String> tagKeys = Collections.emptySet();
    TagFilter tagFilter = new TagFilter("accept-way", tagKeys, tagKeyValues);

    FastXmlReader reader = new FastXmlReader(new File(filename), true, CompressionMethod.None);

    SimplifyTask simplify = new SimplifyTask(IdTrackerType.BitSet);

    TransformTask tagTransform =
        new TransformTask("input/schweiz/tagtransform.xml", "output/tagtransform-stats.xml");

    CoordinateTransformation coordinateTransformation =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, TransformationFactory.WGS84_UTM35S);
    NetworkSink sink = new NetworkSink(scenario.getNetwork(), coordinateTransformation);

    reader.setSink(tagFilter);
    tagFilter.setSink(simplify);
    simplify.setSink(tagTransform);
    tagTransform.setSink(sink);

    reader.run();

    new NetworkWriter(scenario.getNetwork()).write("output/wurst.xml");
  }
コード例 #11
0
  public static void main(final String[] args)
      throws SAXException, ParserConfigurationException, IOException {
    TransitScheduleFactory builder = new TransitScheduleFactoryImpl();
    TransitSchedule schedule = builder.createTransitSchedule();
    CoordinateTransformation transformation =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, TransformationFactory.DHDN_GK4);
    TransitScheduleReaderBerta reader = new TransitScheduleReaderBerta(schedule, transformation);
    reader.setLocalDtdDirectory("../thesis-data/examples/berta/");
    //		reader.readFile("../thesis-data/examples/berta/Bus145.xml");
    reader.readDirectory("../thesis-data/examples/berta/sample/");

    log.info("writing schedule.xml");
    new TransitScheduleWriterV1(schedule).write("../thesis-data/examples/berta/schedule.xml");

    //		log.info("creating routing network.xml");
    //		new TransitRouter(schedule); // writes out "wrappedNetwork.xml" for debugging
    //		new CreatePseudoNetwork().run();// writes out "pseudoNetwork.xml" for debugging
  }
コード例 #12
0
ファイル: Converter.java プロジェクト: matsim-org/matsim
  public static void main(String[] args) {

    //		Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    //		NetworkImpl network = (NetworkImpl) scenario.getNetwork();
    //		CoordinateTransformation ct =
    //
    //	TransformationFactory.getCoordinateTransformation(TransformationFactory.GK4,TransformationFactory.WGS84);
    //		OsmNetworkReader reader = new OsmNetworkReader(scenario.getNetwork(), ct);
    //		reader.parse("C:/Users/Tille/WORK/Cottbus/Cottbus-pt/Demand_input/network_pt_cap60.xml");
    //
    //		NetworkWriter writer = new NetworkWriter(scenario.getNetwork());
    //		writer.write("C:/Users/Tille/WORK/Cottbus/Cottbus-pt/Demand_input/transformiert.xml");
    //

    String input = "C:/Users/Tille/WORK/Cottbus/Cottbus-pt/Demand_input/bearbeitetWGS84.xml";
    String output = "C:/Users/Tille/WORK/Cottbus/Cottbus-pt/Demand_input/RUECKtransformiert.xml";

    /* Read the network. */
    Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
    new MatsimNetworkReader(scenario.getNetwork()).readFile(input);

    /* Transform each node. */
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, "EPSG:25833");
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84,TransformationFactory.DHDN_GK4);

    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation("EPSG:25833",TransformationFactory.WGS84);
    //		CoordinateTransformation ct =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.DHDN_GK4,TransformationFactory.WGS84);

    for (Node node : scenario.getNetwork().getNodes().values()) {
      ((Node) node).setCoord(ct.transform(node.getCoord()));
    }

    /* Write the resulting network. */
    new NetworkWriter(scenario.getNetwork()).write(output);
  }
コード例 #13
0
 // Main
 public static final void main(String[] args) throws NumberFormatException, IOException {
   Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig());
   new MatsimNetworkReader(scenario).readFile(args[0]);
   CoordinateTransformation coordinateTransformation =
       TransformationFactory.getCoordinateTransformation(
           TransformationFactory.WGS84, TransformationFactory.WGS84_UTM48N);
   Coord c1 =
       coordinateTransformation.transform(
           new Coord(Double.parseDouble(args[2]), Double.parseDouble(args[3])));
   Coord c2 =
       coordinateTransformation.transform(
           new Coord(Double.parseDouble(args[4]), Double.parseDouble(args[5])));
   new BusLaneAdderWindow(
           "Bus lanes adder",
           scenario.getNetwork(),
           new File(args[1]),
           new double[] {c1.getX(), c1.getY()},
           new double[] {c2.getX(), c2.getY()},
           args[6],
           coordinateTransformation)
       .setVisible(true);
 }
コード例 #14
0
 // Main
 public static void main(String[] args)
     throws SQLException, NoConnectionException, IOException, InstantiationException,
         IllegalAccessException, ClassNotFoundException {
   Map<Id<ActivityFacility>, Double> maximums = new HashMap<Id<ActivityFacility>, Double>();
   Map<Id<ActivityFacility>, Polygon> masterAreas = new HashMap<Id<ActivityFacility>, Polygon>();
   ShapeFileReader shapeFileReader = new ShapeFileReader();
   Collection<SimpleFeature> features = shapeFileReader.readFileAndInitialize(POLYGONS_FILE);
   for (SimpleFeature feature : features)
     masterAreas.put(
         Id.create((Integer) feature.getAttribute(1), ActivityFacility.class),
         (Polygon) ((MultiPolygon) feature.getDefaultGeometry()).getGeometryN(0));
   DataBaseAdmin dataBaseRealState =
       new DataBaseAdmin(new File("./data/facilities/DataBaseRealState.properties"));
   ResultSet buildingsR =
       dataBaseRealState.executeQuery("SELECT type, longitude, latitude FROM building_directory");
   CoordinateTransformation coordinateTransformation =
       TransformationFactory.getCoordinateTransformation(
           TransformationFactory.WGS84, TransformationFactory.WGS84_TM);
   GeometryFactory factory = new GeometryFactory();
   while (buildingsR.next()) {
     Coord buildingCoord =
         coordinateTransformation.transform(
             new Coord(buildingsR.getDouble(2), buildingsR.getDouble(3)));
     Point p = factory.createPoint(new Coordinate(buildingCoord.getX(), buildingCoord.getY()));
     for (Entry<Id<ActivityFacility>, Polygon> polygon : masterAreas.entrySet())
       if (p.within(polygon.getValue())) {
         Double maximum = maximums.get(polygon.getKey());
         if (maximum == null) maximum = 0.0;
         maximum += getMaximum(buildingsR.getString(1), null);
         maximums.put(polygon.getKey(), maximum);
       }
   }
   dataBaseRealState.close();
   DataBaseAdmin dataBaseAux =
       new DataBaseAdmin(new File("./data/facilities/DataBaseAuxiliar.properties"));
   for (Entry<Id<ActivityFacility>, Double> maximum : maximums.entrySet())
     dataBaseAux.executeUpdate("INSERT INTO buildings VALUES");
   dataBaseAux.close();
 }
コード例 #15
0
  private static Network filterNetwork(Network network) {
    CoordinateTransformation transform =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.CH1903_LV03_GT, TransformationFactory.DHDN_GK4);
    //		CoordinateTransformation transform =
    // TransformationFactory.getCoordinateTransformation(TransformationFactory.CH1903_LV03_GT,
    // "WGS84_UTM32T");

    Network net = NetworkUtils.createNetwork();
    RoadPricingSchemeImpl rps = new RoadPricingSchemeImpl();
    RoadPricingReaderXMLv1 rpr = new RoadPricingReaderXMLv1(rps);
    rpr.parse(linksToFilter);
    Set<Id<Link>> linkList = rps.getTolledLinkIds();
    for (Link link : network.getLinks().values()) {
      Id linkId = link.getId();
      if (linkList.contains(linkId)) {
        Id fromId = link.getFromNode().getId();
        Id toId = link.getToNode().getId();
        Coord fromNodeCoord = link.getFromNode().getCoord();
        Coord toNodeCoord = link.getToNode().getCoord();
        Coord fromNodeTransformed = transform.transform(fromNodeCoord);
        Coord toNodeTransformed = transform.transform(toNodeCoord);
        //				Node newFromNode = net.getFactory().createNode(fromId, fromNodeCoord);
        //				Node newToNode = net.getFactory().createNode(toId, toNodeCoord);
        Node newFromNode = net.getFactory().createNode(fromId, fromNodeTransformed);
        Node newToNode = net.getFactory().createNode(toId, toNodeTransformed);
        if (!net.getNodes().containsKey(fromId)) {
          net.addNode(newFromNode);
        }
        if (!net.getNodes().containsKey(toId)) {
          net.addNode(newToNode);
        }
        Link ll = net.getFactory().createLink(link.getId(), newFromNode, newToNode);
        net.addLink(ll);
      }
    }
    return net;
  }
コード例 #16
0
  public static void main(String[] args) {

    /*
     * We enter coordinates in the WGS84 reference system, but we want them to appear in the population file
     * projected to UTM33N, because we also generated the network in UTM33N.
     */
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation(
            TransformationFactory.WGS84, TransformationFactory.WGS84_UTM33N);

    /*
     * First, create a new Config and a new Scenario.
     */
    Config config = ConfigUtils.createConfig();
    Scenario sc = ScenarioUtils.createScenario(config);

    /*
     * Pick the Network and the Population out of the Scenario for convenience.
     */
    Network network = sc.getNetwork();
    Population population = sc.getPopulation();

    /*
     * Pick the PopulationFactory out of the Population for convenience.
     * It contains methods to create new Population items.
     */
    PopulationFactory populationFactory = population.getFactory();

    /*
     * Create a Person designated "1" and add it to the Population.
     */

    long key = 1;
    for (long i = 1; i <= 5000; i++) {
      key = i;
      Person person = populationFactory.createPerson(Id.createPersonId(key));
      population.addPerson(person);

      /*
       * Create a Plan for the Person
       */
      Plan plan = populationFactory.createPlan();

      /*
       * Create a "home" Activity for the Person. In order to have the Person end its day at the same location,
       * we keep the home coordinates for later use (see below).
       * Note that we use the CoordinateTransformation created above.
       */
      Coord homeCoordinates = new Coord(686661.13571, 4827510.51845);
      Activity activity1 = populationFactory.createActivityFromCoord("home", homeCoordinates);
      activity1.setEndTime(
          21600
              + i * 0.72); // leave at 6 o'clock, one vehicle entering after other in a short while
      // so that there is no peak at one second
      // activity1.setEndTime(21600);
      plan.addActivity(activity1); // add the Activity to the Plan

      /*
       * Create a Leg. A Leg initially hasn't got many attributes. It just says that a car will be used.
       */
      plan.addLeg(populationFactory.createLeg("car"));

      /*
       * Create a "work" Activity, at a different location.
       */
      Activity activity2 =
          populationFactory.createActivityFromCoord("work", new Coord(689426.65361, 4826700.65288));
      activity2.setEndTime(57600); // leave at 4 p.m.
      plan.addActivity(activity2);
      System.out.println("Last Departure Time: " + claculateTime(activity1.getEndTime()));

      /*
       * Create another car Leg.
       */
      person.addPlan(plan);
    }

    for (long i = 1; i <= 5000; i++) {
      key = i + 5000;
      Person person = populationFactory.createPerson(Id.createPersonId(key));
      population.addPerson(person);
      Plan plan = populationFactory.createPlan();
      Coord homeCoordinates = new Coord(686661.13571, 4826063.88649);
      Activity activity1 = populationFactory.createActivityFromCoord("home", homeCoordinates);
      activity1.setEndTime(21600 + i * 1); // leave at 6 o'clock
      // activity1.setEndTime(21600);
      plan.addActivity(activity1); // add the Activity to the Plan
      plan.addLeg(populationFactory.createLeg("car"));
      Activity activity2 =
          populationFactory.createActivityFromCoord("work", new Coord(689426.65361, 4826700.65288));
      activity2.setEndTime(57600); // leave at 4 p.m.
      plan.addActivity(activity2);
      System.out.println("Last Departure Time: " + claculateTime(activity1.getEndTime()));
      person.addPlan(plan);
    }

    /*
     * Write the population (of 1 Person) to a file.
     */
    MatsimWriter popWriter =
        new org.matsim.api.core.v01.population.PopulationWriter(population, network);
    popWriter.write("H:\\Mike Work\\input\\population.xml");
  }
コード例 #17
0
  /** @param args */
  public static void main(String[] args) {
    Header.printHeader(ExtractVehiclesForSollyFrans.class.toString(), args);

    String path = "/home/jwjoubert/Documents/data/Digicore/ByMonth/201403/SollyFrans/xml/";
    String output = "/home/jwjoubert/Documents/data/Digicore/ByMonth/201403/SollyFrans/chains.csv";
    List<File> list =
        FileUtils.sampleFiles(new File(path), 100, FileUtils.getFileFilter(".xml.gz"));

    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation("WGS84_SA_Albers", "WGS84");

    BufferedWriter bw = IOUtils.getBufferedWriter(output);
    try {
      bw.write("Vehicle,Chain,Activity,X,Y,Long,Lat,Start,End");
      bw.newLine();

      for (File f : list) {
        DigicoreVehicleReader_v1 dvr = new DigicoreVehicleReader_v1();
        dvr.readFile(f.getAbsolutePath());
        DigicoreVehicle v = dvr.getVehicle();
        bw.write(v.getId().toString());
        bw.write(",");

        int chain = 1;
        for (DigicoreChain c : v.getChains()) {
          int act = 1;
          for (DigicoreActivity a : c.getAllActivities()) {
            Coord coord = a.getCoord();
            Coord coordWgs84 = ct.transform(coord);

            String s =
                String.format(
                    "%s,%d,%d,%.0f,%.0f,%.6f,%.6f,%s,%s\n",
                    v.getId().toString(),
                    chain,
                    act,
                    coord.getX(),
                    coord.getY(),
                    coordWgs84.getX(),
                    coordWgs84.getY(),
                    getNiceDate(a.getStartTimeGregorianCalendar()),
                    getNiceDate(a.getEndTimeGregorianCalendar()));
            bw.write(s);
            act++;
          }
          chain++;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException("Cannot write to " + output);
    } finally {
      try {
        bw.close();
      } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Cannot close " + output);
      }
    }

    Header.printFooter();
  }
コード例 #18
0
ファイル: SurveyParser.java プロジェクト: sebhoerl/matsim
  public void cleanUpScenario(Scenario sc) {
    LOG.info("Cleaning up scenario...");
    /* TODO Still need to figure out what cleaning up must happen. */

    /* Search for location-less activities, and sample its locations from
     * the kernel density estimates. */
    LOG.info("Sampling locations for those without known zones...");
    int locationsFixed = 0;
    int knownLocations = 0;
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            Coord coord = act.getCoord();
            if (coord.getX() == 0.0 || coord.getY() == 0.0) {
              ((ActivityImpl) act).setCoord(sampleActivityLocation(act.getType()));
              locationsFixed++;
            } else {
              knownLocations++;
            }
          }
        }
      }
    }
    LOG.info("Number of known locations: " + knownLocations);
    LOG.info("Number of locations fixed: " + locationsFixed);
    LOG.info("Done sampling locations.");

    /* Ensure each activity, except the last, has both a start and end time. */
    LOG.info("Ensure each activity has an end time...");
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        List<PlanElement> list = plan.getPlanElements();
        for (int i = 0; i < list.size() - 2; i += 2) {
          PlanElement pe = list.get(i);
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            double endTime = act.getEndTime();
            if (endTime < 0.0) {
              double legStart = ((Leg) list.get(i + 1)).getDepartureTime();
              act.setEndTime(legStart);
            }
          } else {
            LOG.warn("Every second PlanElement should be of type 'Activity'.");
          }
        }
      }
    }
    LOG.info("Done fixing activity end times.");

    /* Ensure that the home location/coordinate for all members in the
     * household are the same for all their "h" activities. */
    LOG.info("Fix home locations for each household member. ");
    int homeLocationsFixed = 0;
    int nonTravellers = 0;
    for (Household hh : sc.getHouseholds().getHouseholds().values()) {
      Object o =
          sc.getHouseholds()
              .getHouseholdAttributes()
              .getAttribute(hh.getId().toString(), "transportZone");
      if (o instanceof String) {
        String zoneId = (String) o;
        Coord homeCoord = null;
        if (zoneId != null && !zoneId.equalsIgnoreCase("")) {
          /* There is known home zone. */
          Point p = this.zoneMap.get(zoneId).sampleRandomInteriorPoint();
          homeCoord = CoordUtils.createCoord(p.getX(), p.getY());
        } else {
          /* There is no transport zone. */
          homeCoord = sampleActivityLocation("h");
        }

        /* Now assign the home coordinate to ALL home activities for
         * all members of the household. */
        for (Id<Person> id : hh.getMemberIds()) {
          Person person = sc.getPopulation().getPersons().get(id);
          Plan plan = person.getSelectedPlan();
          if (plan != null) {
            for (PlanElement pe : person.getSelectedPlan().getPlanElements()) {
              if (pe instanceof ActivityImpl) {
                ActivityImpl act = (ActivityImpl) pe;
                if (act.getType().equalsIgnoreCase("h")) {
                  act.setCoord(homeCoord);
                  homeLocationsFixed++;
                }
              }
            }
          } else {
            /* The member does not have ANY plan. We 'fix' this by
             * adding aPlan with a single home-based activity for
             * which not times are specified. */
            Plan stayHomePlan = sc.getPopulation().getFactory().createPlan();
            Activity act = sc.getPopulation().getFactory().createActivityFromCoord("h", homeCoord);
            stayHomePlan.addActivity(act);
            person.addPlan(stayHomePlan);
            nonTravellers++;
          }
        }
      }
    }
    LOG.info("Total number of home locations fixed: " + homeLocationsFixed);
    LOG.info("      Total number of non-travellers: " + nonTravellers);
    LOG.info("Done fixing home locations.");

    /* TODO Check what to do with those household members that are not
     * travelling. Are they just given a single 'h' activities, and
     * left at that? */

    /* Look for erroneous activity times that can/should be fixed in
     * the raw travel diary input data. This will typically include very
     * long activity times or leg durations. */
    LOG.info("Checking leg durations:");
    int remainingLegOddities = 0;
    double legDurationThreshold = Time.parseTime("03:00:00");
    for (Person p : sc.getPopulation().getPersons().values()) {
      Plan plan = p.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Leg) {
            double duration = ((Leg) pe).getTravelTime();
            if (duration < 0 || duration > legDurationThreshold) {
              LOG.warn(
                  " -> Odd leg duration: "
                      + p.getId().toString()
                      + " ("
                      + Time.writeTime(duration)
                      + ")");
              remainingLegOddities++;
            }
          }
        }
      }
    }
    LOG.info("Done checking leg durations. (" + remainingLegOddities + " remain)");

    /* Parse the activity duration times in an effort to pick up
     * erroneous travel time data that results in negative activity
     * durations. Then fix in input data. */
    LOG.info("Checking activity durations (from leg times):");
    int remainingActivityOddities = 0;
    double activityDurationThreshold = Time.parseTime("16:00:00");
    for (Person p : sc.getPopulation().getPersons().values()) {
      Plan plan = p.getSelectedPlan();
      if (plan != null) {
        for (int i = 1; i < plan.getPlanElements().size() - 2; i += 2) {
          PlanElement pe1 = plan.getPlanElements().get(i);
          PlanElement pe2 = plan.getPlanElements().get(i + 2);
          if (pe1 instanceof Leg && pe2 instanceof Leg) {
            Leg l1 = (Leg) pe1;
            Leg l2 = (Leg) pe2;
            double act = l2.getDepartureTime() - (l1.getDepartureTime() + l1.getTravelTime());
            if (act < 0 || act > activityDurationThreshold) {
              LOG.warn(
                  " -> Odd activity duration: "
                      + p.getId().toString()
                      + " ("
                      + Time.writeTime(act)
                      + ")");
              remainingActivityOddities++;
            }
          } else {
            LOG.error("PlanElements not of type Leg!!");
            LOG.error("   pe1: " + pe1.getClass().toString());
            LOG.error("   pe2: " + pe2.getClass().toString());
          }
        }
      }
    }
    LOG.info("Done checking activity durations. (" + remainingActivityOddities + " remain)");

    /* TODO Fix plans for night workers. They typically start with 'h',
     * but should actually start with 'w'. */

    /* TODO Consider what to do with repeating activities, especially
     * consecutive home activities. */

    /* Convert all activity locations to a projected coordinate system. */
    LOG.info("Converting all activity locations to EPSG:3857...");
    CoordinateTransformation ct =
        TransformationFactory.getCoordinateTransformation("WGS84", "EPSG:3857");
    for (Person person : sc.getPopulation().getPersons().values()) {
      Plan plan = person.getSelectedPlan();
      if (plan != null) {
        for (PlanElement pe : plan.getPlanElements()) {
          if (pe instanceof Activity) {
            Activity act = (Activity) pe;
            ((ActivityImpl) act).setCoord(ct.transform(act.getCoord()));
          }
        }
      }
    }
    LOG.info("Done converting activity locations.");

    LOG.info("Done cleaning up scenario.");
  }
コード例 #19
0
  private static void main(final Args args) {
    final String netFile = args.getValue("-n");
    final String countsFile = args.getValue("-c");
    final String eventsFile = args.getValue("-e");

    final double scaleFactor = args.getDoubleValue("-s");

    final String coordSystem = args.getValue("-proj");

    final Coord center = new Coord(args.getDoubleValue("-x"), args.getDoubleValue("-y"));
    final double radius = 1000 * args.getDoubleValue("-r");

    final String htmlOutFile = args.getValue("-html");
    final String kmzOutFile = args.getValue("-kmz");
    final String txtOutFile = args.getValue("-txt");

    final Network network = readNetwork(netFile);
    final Counts counts = readCounts(countsFile);
    final VolumesAnalyzer volumes = readVolumes(network, eventsFile);

    // this is pretty confusing: parameters to the algorithm are passed
    // by the constructor, algorithm is run by the run() method, and
    // results can be obtained by the getComparison() method.
    final CountsComparisonAlgorithm cca =
        new CountsComparisonAlgorithm(volumes, counts, network, scaleFactor);
    cca.setDistanceFilter(
        new DistanceFilter() {
          @Override
          public boolean isInRange(final Count count) {
            try {
              final Coord c =
                  count.getCoord() != null
                      ? count.getCoord()
                      : network.getLinks().get(count.getLocId()).getCoord();
              return CoordUtils.calcEuclideanDistance(c, center) <= radius;
            } catch (Exception e) {
              // ignore and proceed, as is the case in the default distance filter...
              log.error("Error while locating count " + count + ". Error was: ", e);
              log.error("Proceed anyway...");
              return false;
            }
          }
        });
    cca.run();

    if (htmlOutFile != null) {
      try {
        final CountsHtmlAndGraphsWriter cgw =
            new CountsHtmlAndGraphsWriter(htmlOutFile, cca.getComparison(), -1);
        cgw.addGraphsCreator(new CountsSimRealPerHourGraphCreator("sim and real volumes"));
        cgw.addGraphsCreator(new CountsErrorGraphCreator("errors"));
        cgw.addGraphsCreator(new CountsLoadCurveGraphCreator("link volumes"));
        cgw.addGraphsCreator(
            new CountsSimReal24GraphCreator("average working day sim and count volumes"));
        cgw.createHtmlAndGraphs();
      } catch (Exception e) {
        log.error("got exception when creating html output.", e);
        log.error("proceed to next output format, if any.");
      }
    }

    if (kmzOutFile != null) {
      try {
        final CountSimComparisonKMLWriter kmlWriter =
            new CountSimComparisonKMLWriter(
                cca.getComparison(),
                network,
                TransformationFactory.getCoordinateTransformation(
                    coordSystem, TransformationFactory.WGS84));
        kmlWriter.writeFile(kmzOutFile);
      } catch (Exception e) {
        log.error("got exception when creating kmz output.", e);
        log.error("proceed to next output format, if any.");
      }
    }

    if (txtOutFile != null) {
      try {
        final CountSimComparisonTableWriter ctw =
            new CountSimComparisonTableWriter(cca.getComparison(), Locale.ENGLISH);
        ctw.writeFile(txtOutFile);
      } catch (Exception e) {
        log.error("got exception when creating txt output.", e);
        log.error("proceed to next output format, if any.");
      }
    }
  }