Skip to content

Commit

Permalink
Update MATSim CW31 2nd (#108)
Browse files Browse the repository at this point in the history
* Score explanation functionality

* rename a method from add... to set... since that is what is does.

* changes

* update config group

* update tests and added attributes

* fix un initialized attribute

* small improvement to object creation

* add leg score for individual legs

* more consistent naming

* more consistent naming

* revert unintentional changes

* CreateDrtDashboard

* Bump org.apache.maven.plugins:maven-failsafe-plugin from 3.2.5 to 3.3.0

Bumps [org.apache.maven.plugins:maven-failsafe-plugin](https://github.com/apache/maven-surefire) from 3.2.5 to 3.3.0.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](apache/maven-surefire@surefire-3.2.5...surefire-3.3.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-failsafe-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* rename pooling ratio to occupancy rate

* account for group bookings in DrtAnalysisPostProcessing (and thus DrtDashboard)

* typo in CreateDrtDashboard

* fix wrong sum calculation

* debug NoiseAnalysis and proper testing in NoiseDashboardTests

* fix wrong map selection

* add reduction of numberOfJobs

* add comments and format log massages

* combine

* rename parameter

* reduce code

* format logging

* use method for demand calculating

* use method for shipment creation

* remove todo

* use method to calculate demand based on link lengths

* introduce parameter

* simplify

* cleanup

* Support TransitRouteStops where boarding or alighting is not allowed

In reality, there are trains that call at stops but where it might not be allowed to enter or exit such trains. Examples are night trains, where on the first few stops, only boarding is allowed, while at the last few stops only alighting is allowed. This means that it is not allowed to use such night trains to just travel between the first few stops.

This commit adds two optional attributes `allowBoarding` and `allowAlighting` to TransitRouteStops, with the default value being true for backwards compatibility and when the attribute is not specified. SwissRailRaptor respects these attributes and will not return routes where agents would enter a vehicle at a route stop where boarding is not allowed, or where agents would exit a vehicle at a route stop where alighting is not allowed.

* make drt shifts multi mode drt comatible

* adjust shift efficiency tracker as well

* Extended Trip analysis and dashboard (matsim-org#3332)

* trip analysis for subgroups

* refactor categories

* write trip analysis

* write out correct table

* use static method

* prepare for facets, add TODOs

* start working on plotly facet integration

* Added Test Trip Dashboard for Facets

* update API

* add trip choice analysis

* adding test case and some todos

* calculating some trip choice metrics

* add choice metrics to trip dashboard

* hide tab if not needed

* add text box and round metrics

* normalize shares per reference group correctly, added some facet dashboards (WIP)

* fix pivot usage

* rename entries

* add plots for distance distributions

* add todo

* use dropdown for plots

* add cohen kappa to evaluation

* output euclidean distance for trip choices

* add ref_id attribute

* added heatmap to TripDashboard

* update description

* allow arbitrary object for ref ids

* show heatmap labels

* comment out trip dashboard wip part

* use correct logger

* improve wording

---------

Co-authored-by: frievoe97 <[email protected]>

* Bump org.apache.maven.plugins:maven-surefire-plugin from 3.2.5 to 3.3.0

Bumps [org.apache.maven.plugins:maven-surefire-plugin](https://github.com/apache/maven-surefire) from 3.2.5 to 3.3.0.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](apache/maven-surefire@surefire-3.2.5...surefire-3.3.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-surefire-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* Bump org.apache.maven.plugins:maven-surefire-report-plugin

Bumps [org.apache.maven.plugins:maven-surefire-report-plugin](https://github.com/apache/maven-surefire) from 3.2.5 to 3.3.0.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](apache/maven-surefire@surefire-3.2.5...surefire-3.3.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-surefire-report-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* Bump org.apache.maven.plugins:maven-jar-plugin from 3.4.1 to 3.4.2

Bumps [org.apache.maven.plugins:maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.4.1 to 3.4.2.
- [Release notes](https://github.com/apache/maven-jar-plugin/releases)
- [Commits](apache/maven-jar-plugin@maven-jar-plugin-3.4.1...maven-jar-plugin-3.4.2)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-jar-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* Bump com.fasterxml.woodstox:woodstox-core from 6.6.2 to 7.0.0

Bumps [com.fasterxml.woodstox:woodstox-core](https://github.com/FasterXML/woodstox) from 6.6.2 to 7.0.0.
- [Commits](FasterXML/woodstox@woodstox-core-6.6.2...woodstox-core-7.0.0)

---
updated-dependencies:
- dependency-name: com.fasterxml.woodstox:woodstox-core
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>

* Bump org.jfree:jfreechart from 1.5.4 to 1.5.5

Bumps [org.jfree:jfreechart](https://github.com/jfree/jfreechart) from 1.5.4 to 1.5.5.
- [Release notes](https://github.com/jfree/jfreechart/releases)
- [Commits](jfree/jfreechart@v1.5.4...v1.5.5)

---
updated-dependencies:
- dependency-name: org.jfree:jfreechart
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* make drt work with only custom constraints sets

* add some logging to NetworkChangeEventsWriter

* correct logging statement

* add router binding for complex request unscheduling

* use time as disutility

* Bump junit.version from 5.10.2 to 5.10.3

Bumps `junit.version` from 5.10.2 to 5.10.3.

Updates `org.junit.jupiter:junit-jupiter-engine` from 5.10.2 to 5.10.3
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](junit-team/junit5@r5.10.2...r5.10.3)

Updates `org.junit.jupiter:junit-jupiter` from 5.10.2 to 5.10.3
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](junit-team/junit5@r5.10.2...r5.10.3)

---
updated-dependencies:
- dependency-name: org.junit.jupiter:junit-jupiter-engine
  dependency-type: direct:development
  update-type: version-update:semver-patch
- dependency-name: org.junit.jupiter:junit-jupiter
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* * repair wrong positioning of vehicles if linkSpeedCalculator returns speed larger than free speed
* replace some (but not all) link.getAttributes()... by BicycleUtils.set/getXyz( link, ...)
* bind BicycleConfigGroup explicitly in BicycleModule so that not materializing it before does not lead to a non-interpretable error message (stating that Scenario is not bound about 20 times although that is not the root of the problem)
* possibly one or the other additional things

* norm subgroups to 1 (matsim-org#3346)

* add test integration test case for complex unscheduler

* Bump io.grpc:grpc-all from 1.64.0 to 1.65.0

Bumps [io.grpc:grpc-all](https://github.com/grpc/grpc-java) from 1.64.0 to 1.65.0.
- [Release notes](https://github.com/grpc/grpc-java/releases)
- [Commits](grpc/grpc-java@v1.64.0...v1.65.0)

---
updated-dependencies:
- dependency-name: io.grpc:grpc-all
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* Bump com.google.protobuf:protobuf-java from 4.27.1 to 4.27.2

Bumps [com.google.protobuf:protobuf-java](https://github.com/protocolbuffers/protobuf) from 4.27.1 to 4.27.2.
- [Release notes](https://github.com/protocolbuffers/protobuf/releases)
- [Changelog](https://github.com/protocolbuffers/protobuf/blob/main/protobuf_release.bzl)
- [Commits](https://github.com/protocolbuffers/protobuf/commits)

---
updated-dependencies:
- dependency-name: com.google.protobuf:protobuf-java
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* Split CalculateSkimMatrices.prepareAndCalculateNetworkMatrices() to allow for custom travel times objects

* Bump org.checkerframework:checker-qual from 3.44.0 to 3.45.0

Bumps [org.checkerframework:checker-qual](https://github.com/typetools/checker-framework) from 3.44.0 to 3.45.0.
- [Release notes](https://github.com/typetools/checker-framework/releases)
- [Changelog](https://github.com/typetools/checker-framework/blob/master/docs/CHANGELOG.md)
- [Commits](typetools/checker-framework@checker-framework-3.44.0...checker-framework-3.45.0)

---
updated-dependencies:
- dependency-name: org.checkerframework:checker-qual
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* Switch to DrtWithExtensionsConfigGroup

* Bump org.apache.poi:poi-ooxml from 5.2.5 to 5.3.0

Bumps org.apache.poi:poi-ooxml from 5.2.5 to 5.3.0.

---
updated-dependencies:
- dependency-name: org.apache.poi:poi-ooxml
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* reworked CreatePseudoNetwork with loop-links to avoid duplicating stops

* repair test failures

* Trip facet dashboard (matsim-org#3350)

* implement dropdown facets on the trip dashboard

* implement dropdown facets on the trip dashboard

* added backgroundColor attribute and restyled text seperators

* set backgroundcolor on all plots

---------

Co-authored-by: rakow <[email protected]>

* adjust rounding

* exclude case

* Drt dashboard typo fix (matsim-org#3360)

* added tooltip for gridmap/emissionsDashboard

* fix typo in drt dashboard

---------

Co-authored-by: rakow <[email protected]>

* Bump com.fasterxml.jackson:jackson-bom from 2.17.1 to 2.17.2

Bumps [com.fasterxml.jackson:jackson-bom](https://github.com/FasterXML/jackson-bom) from 2.17.1 to 2.17.2.
- [Commits](FasterXML/jackson-bom@jackson-bom-2.17.1...jackson-bom-2.17.2)

---
updated-dependencies:
- dependency-name: com.fasterxml.jackson:jackson-bom
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* Bump net.bytebuddy:byte-buddy from 1.14.17 to 1.14.18

Bumps [net.bytebuddy:byte-buddy](https://github.com/raphw/byte-buddy) from 1.14.17 to 1.14.18.
- [Release notes](https://github.com/raphw/byte-buddy/releases)
- [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md)
- [Commits](raphw/byte-buddy@byte-buddy-1.14.17...byte-buddy-1.14.18)

---
updated-dependencies:
- dependency-name: net.bytebuddy:byte-buddy
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* set networkMode based on vehicleTypes

* Bump org.assertj:assertj-core from 3.26.0 to 3.26.3

Bumps [org.assertj:assertj-core](https://github.com/assertj/assertj) from 3.26.0 to 3.26.3.
- [Release notes](https://github.com/assertj/assertj/releases)
- [Commits](assertj/assertj@assertj-build-3.26.0...assertj-build-3.26.3)

---
updated-dependencies:
- dependency-name: org.assertj:assertj-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore: clean up MinimalTransferTimes (matsim-org#3365)

* chore: cleanup adaptive transfers (matsim-org#3366)

* chore: cleanup adaptvie transfers

* make final

* Bump org.apache.maven.plugins:maven-failsafe-plugin from 3.3.0 to 3.3.1

Bumps [org.apache.maven.plugins:maven-failsafe-plugin](https://github.com/apache/maven-surefire) from 3.3.0 to 3.3.1.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](apache/maven-surefire@surefire-3.3.0...surefire-3.3.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-failsafe-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* add missing case of enum

* add functionality to split jobs

* use new methods

* update activity creation

* set activity time correctly

* remove unneeded exception

* change to parameterized log message

* delete empty test methods

* remove unused import

* fix unchecked assignment

* remove redundant local variables

* minor code style update

* remove not needed throw information

* make things final

* remove redundant final declaration

* remove unnecessary 'throws' declarations

* simplify assertions

* cleanup Strings

* remove redundant casts

* code style update

* cleanup imports

* Java language: Replace explicit type with <>

* Java language: use computeIfAbsent

* Java language: use Double.hashCode(...)

* Java language: replace if by switch

* Java language: avoid raw use

* Java language: use text block

* Java language: use pattern variable

* Java language: use add/getFirst()

* Access to TestUtils.EPSILION

* add not null assertion

* remove one layer of "LSPs"

* add prebooking support for drt shifts
some minor shift cleanups
possibility to assign requests to shifts that are assigned bot not started yet

* cancel assigned shifts

* add some documentation

* shift drt maintenance

* some more drt shift maintenance

* consider break corridors for (pre)bookings

* consider break corridors for (pre)bookings

* clean up obsolete method

* update FISS test, reduce iterations to reduce runtime

* avoid abandoning prebooked requests twice in the same time step

* remove redundant suppression

* remove unused field

* internal renaming

* remove unnecessary toString() calls

* remove unnecessary semicolon

* inline and remove method

* cleanup imports

* simplification

* make final, internal renaming

* replace 'if' by 'switch'

* simplification

* use enhanced 'switch'

* simplification

* use 'getFirst()'

* javadoc: replace blank lines with '<p>'

* javadoc: set link as a link

* logging: use parameterized logging

* add casting

* simplification

* use 'append()' calls

* simplification by removing inaccessibly parts of if statements.

* remove duplicated setting of variable

* Simplify assertions

* Simplify stream

* avoid casting

* suppress warning

* fix some (language) grammar

* fix some typos

* more simplifications

* cleanup: remove commented out code

* small cleanups

* optimize h3 zone system initialization; move h3 test to common module

* shift drt maintenance; fix bug for prebooked e-drt scenarios that need shifts to be assignable to requests in advance; change priority queues in shift dispatcher to sorted sets to ensure correct iteration order

* make FISS integration test less sensible to smaller changes in link events

* set level of some logging's back from WARN to DEBUG

* SimWrapper Dashboard features (matsim-org#3381)

* add explanations to the traffic dashboard, add pt viewer dashboard

* add additional description

* add avg beeline speed to trip dashboard

* added mode share distance distribution

* added plot for detailed distance distribution

* upscale emission dashboard with sample size

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: rakow <[email protected]>
Co-authored-by: Kai Nagel <[email protected]>
Co-authored-by: kainagel <[email protected]>
Co-authored-by: rakow <[email protected]>
Co-authored-by: schlenther <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ricardo Ewert <[email protected]>
Co-authored-by: Ricardo Ewert <[email protected]>
Co-authored-by: Marcel Rieser <[email protected]>
Co-authored-by: frievoe97 <[email protected]>
Co-authored-by: Joschka Bischoff <[email protected]>
Co-authored-by: Michal Maciejewski <[email protected]>
Co-authored-by: marecabo <[email protected]>
Co-authored-by: steffenaxer <[email protected]>
Co-authored-by: u229351 <[email protected]>
Co-authored-by: frievoe97 <[email protected]>
Co-authored-by: Sebastian Hörl <[email protected]>
Co-authored-by: Kai Martins-Turner <[email protected]>
Co-authored-by: Kai Martins-Turner <[email protected]>
  • Loading branch information
20 people authored Aug 1, 2024
1 parent 2c35ab2 commit edb9f45
Show file tree
Hide file tree
Showing 30 changed files with 856 additions and 262 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,11 @@ private void writeOutput(Network network, EmissionsOnLinkEventHandler emissionsE
if (link2pollutants.get(linkId).get(pollutant) != null) {
emissionValue = link2pollutants.get(linkId).get(pollutant);
}
absolute.print(nf.format(emissionValue));
absolute.print(nf.format(emissionValue * sample.getUpscaleFactor()));

Link link = network.getLinks().get(linkId);
double emissionPerM = emissionValue / link.getLength();
perMeter.print(nf.format(emissionPerM));
perMeter.print(nf.format(emissionPerM * sample.getUpscaleFactor()));
}

absolute.println();
Expand Down Expand Up @@ -246,7 +246,7 @@ private void writeTotal(Network network, EmissionsOnLinkEventHandler emissionsEv

total.printRecord("Pollutant", "kg");
for (Pollutant p : Pollutant.values()) {
double val = (sum.getDouble(p) / sample.getSample()) / 1000;
double val = (sum.getDouble(p) * sample.getUpscaleFactor()) / 1000;
total.printRecord(p, val < 100_000 && val > 100 ? simple.format(val) : scientific.format(val));
}

Expand Down Expand Up @@ -286,7 +286,7 @@ private void writeAvroRaster(Network network, Config config, EmissionsOnLinkEven
for (int xi = 0; xi < xLength.get(0); xi++) {
for (int yi = 0; yi < yLength.get(0); yi++) {
Coord coord = raster.getCoordForIndex(xi, yi);
double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi);
double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor();
if (xi == 0) yCoords.add((float) coord.getY());
if (yi == 0) xCoords.add((float) coord.getX());
valuesList.add((float) value);
Expand Down Expand Up @@ -349,7 +349,7 @@ private void writeRaster(Network network, Config config, EmissionsOnLinkEventHan
for (int yi = 0; yi < yLength.get(0); yi++) {

Coord coord = raster.getCoordForIndex(xi, yi);
double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi);
double value = rasterMap.get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor();

if (value == 0)
continue;
Expand Down Expand Up @@ -406,7 +406,7 @@ private void writeTimeDependentRaster(Network network, Config config, EmissionsO
for (TimeBinMap.TimeBin<Map<Pollutant, Raster>> timeBin : timeBinMap.getTimeBins()) {

Coord coord = raster.getCoordForIndex(xi, yi);
double value = timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi);
double value = timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor();

if (value == 0)
continue;
Expand Down Expand Up @@ -467,7 +467,8 @@ private void writeTimeDependentAvroRaster(Network network, Config config, Emissi
if (yi == 0 && isFirst)
xCoords.add((float) coord.getX());

valuesList.add((float) timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi));
double value = timeBin.getValue().get(Pollutant.CO2_TOTAL).getValueByIndex(xi, yi) * sample.getUpscaleFactor();
valuesList.add((float) value);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.math3.analysis.interpolation.LoessInterpolator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.locationtech.jts.geom.Coordinate;
Expand All @@ -32,6 +33,7 @@
import java.math.RoundingMode;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.IntStream;

import static tech.tablesaw.aggregate.AggregateFunctions.count;

Expand All @@ -41,6 +43,7 @@
produces = {
"mode_share.csv", "mode_share_per_dist.csv", "mode_users.csv", "trip_stats.csv",
"mode_share_per_%s.csv", "population_trip_stats.csv", "trip_purposes_by_hour.csv",
"mode_share_distance_distribution.csv",
"mode_choices.csv", "mode_choice_evaluation.csv", "mode_choice_evaluation_per_mode.csv",
"mode_confusion_matrix.csv", "mode_prediction_error.csv"
}
Expand Down Expand Up @@ -109,6 +112,25 @@ private static int durationToSeconds(String d) {
return (Integer.parseInt(split[0]) * 60 * 60) + (Integer.parseInt(split[1]) * 60) + Integer.parseInt(split[2]);
}

private static double[] calcHistogram(double[] data, double[] bins) {

double[] hist = new double[bins.length - 1];

for (int i = 0; i < bins.length - 1; i++) {

double binStart = bins[i];
double binEnd = bins[i + 1];

// The last right bin edge is inclusive, which is consistent with the numpy implementation
if (i == bins.length - 2)
hist[i] = Arrays.stream(data).filter(d -> d >= binStart && d <= binEnd).count();
else
hist[i] = Arrays.stream(data).filter(d -> d >= binStart && d < binEnd).count();
}

return hist;
}

@Override
public Integer call() throws Exception {

Expand Down Expand Up @@ -247,6 +269,8 @@ public Integer call() throws Exception {

writeTripPurposes(joined);

writeTripDistribution(joined);

return 0;
}

Expand Down Expand Up @@ -293,13 +317,15 @@ private void writeTripStats(Table trips) throws IOException {
Object2IntMap<String> n = new Object2IntLinkedOpenHashMap<>();
Object2LongMap<String> travelTime = new Object2LongOpenHashMap<>();
Object2LongMap<String> travelDistance = new Object2LongOpenHashMap<>();
Object2LongMap<String> beelineDistance = new Object2LongOpenHashMap<>();

for (Row trip : trips) {
String mainMode = trip.getString("main_mode");

n.mergeInt(mainMode, 1, Integer::sum);
travelTime.mergeLong(mainMode, durationToSeconds(trip.getString("trav_time")), Long::sum);
travelDistance.mergeLong(mainMode, trip.getLong("traveled_distance"), Long::sum);
beelineDistance.mergeLong(mainMode, trip.getLong("euclidean_distance"), Long::sum);
}

try (CSVPrinter printer = new CSVPrinter(Files.newBufferedWriter(output.getPath("trip_stats.csv")), CSVFormat.DEFAULT)) {
Expand Down Expand Up @@ -338,6 +364,13 @@ private void writeTripStats(Table trips) throws IOException {
}
printer.println();

printer.print("Avg. beeline speed [km/h]");
for (String m : modeOrder) {
double speed = (beelineDistance.getLong(m) / 1000d) / (travelTime.getLong(m) / (60d * 60d));
printer.print(new BigDecimal(speed).setScale(2, RoundingMode.HALF_UP));
}
printer.println();

printer.print("Avg. distance per trip [km]");
for (String m : modeOrder) {
double avg = (travelDistance.getLong(m) / 1000d) / (n.getInt(m));
Expand Down Expand Up @@ -458,6 +491,55 @@ private void writeTripPurposes(Table trips) {

}

private void writeTripDistribution(Table trips) throws IOException {

Map<String, double[]> dists = new LinkedHashMap<>();

// Note that the results of this interpolator are consistent with the one performed in matsim-python-tools
// This makes the results comparable with reference data, changes here will also require changes in the python package
LoessInterpolator inp = new LoessInterpolator(0.05, 0);

long max = distGroups.get(distGroups.size() - 3) + distGroups.get(distGroups.size() - 2);

double[] bins = IntStream.range(0, (int) (max / 100)).mapToDouble(i -> i * 100).toArray();
double[] x = Arrays.copyOf(bins, bins.length - 1);

for (String mode : modeOrder) {
double[] distances = trips.where(
trips.stringColumn("main_mode").equalsIgnoreCase(mode))
.numberColumn("traveled_distance").asDoubleArray();

double[] hist = calcHistogram(distances, bins);

double[] y = inp.smooth(x, hist);
dists.put(mode, y);
}

try (CSVPrinter printer = new CSVPrinter(Files.newBufferedWriter(output.getPath("mode_share_distance_distribution.csv")), CSVFormat.DEFAULT)) {

printer.print("dist");
for (String s : modeOrder) {
printer.print(s);
}
printer.println();

for (int i = 0; i < x.length; i++) {

double sum = 0;
for (String s : modeOrder) {
sum += Math.max(0, dists.get(s)[i]);
}

printer.print(x[i]);
for (String s : modeOrder) {
double value = Math.max(0, dists.get(s)[i]) / sum;
printer.print(value);
}
printer.println();
}
}
}

/**
* How shape file filtering should be applied.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

/**
* Class to calculate the traffic congestion index based on the paper
* "A Traffic Congestion Assessment Method for Urban Road Networks Based on Speed Performance Index" by Feifei He, Xuedong Yan*, Yang Liu, Lu Ma.
* "A Traffic Congestion Assessment Method for Urban Road Networks Based on Speed Performance Index" by Feifei He, Xuedong Yan, Yang Liu, Lu Ma.
*/
public final class TrafficStatsCalculator {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,13 @@ public double getSample() {
return sample;
}

/**
* Return factor that is used to upscale the sample size.
*/
public double getUpscaleFactor() {
return 1.0 / sample;
}

private void setSize(double sample) {
this.set = true;
this.sample = sample;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,6 @@ else if (samplingOption.equals("changeDemandOnLocation")) {
.skip(rand.nextInt(usedServiceLocations.size() - 1)).findFirst().get()));
}
int demandForThisLink = calculateDemandForThisLink(demandToDistribute, numberOfJobs, distributedDemand, i);

Carrier thisCarrier = CarriersUtils.getCarriers(scenario).getCarriers()
.get(Id.create(newDemandInformationElement.getCarrierName(), Carrier.class));
int numberOfJobsForDemand = calculateNumberOfJobsForDemand(thisCarrier, demandForThisLink);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ public final class BicycleLinkSpeedCalculatorDefaultImpl implements BicycleLinkS
private static final Logger log = LogManager.getLogger(BicycleLinkSpeedCalculatorDefaultImpl.class );
@Inject private BicycleConfigGroup bicycleConfigGroup;
@Inject private QSimConfigGroup qSimConfigGroup;
@Inject private BicycleLinkSpeedCalculatorDefaultImpl() { }
@Inject private Config config;
@Inject private BicycleLinkSpeedCalculatorDefaultImpl() {
}

/**
* for unit testing
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,12 @@
import com.google.inject.Singleton;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.units.qual.C;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.Scenario;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigGroup;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.controler.AbstractModule;
import org.matsim.core.controler.events.StartupEvent;
import org.matsim.core.controler.listener.StartupListener;
Expand All @@ -34,37 +38,51 @@
* @author smetzler, dziemke
*/
public final class BicycleModule extends AbstractModule {

private static final Logger LOG = LogManager.getLogger(BicycleModule.class);

@Inject
private BicycleConfigGroup bicycleConfigGroup;
@Inject private BicycleConfigGroup bicycleConfigGroup;

@Override public void install() {
// BicycleConfigGroup bicycleConfigGroup = ConfigUtils.addOrGetModule( this.getConfig(), BicycleConfigGroup.class );
// this.bind( BicycleConfigGroup.class ).toInstance( bicycleConfigGroup );
// the above feels odd. But it seems to work. I actually have no idea where the config groups are bound, neither for the core config
// groups nor for the added config groups. In general, the original idea was that AbstractModule provides the config from
// getConfig(), not from injection. kai, jun'24

// It actually does not work in general. The ExplodedConfigModule injects all config groups that are materialized by then. Which
// means that it needs to be materialized "quite early", and in particular before this install method is called. For the time being,
// a run script using the contrib thus needs to materialize the config group. kai, jul'24


@Override
public void install() {
// The idea here is the following:
// * scores are just added as score events. no scoring function is replaced.

// * link speeds are computed via a plugin handler to the DefaultLinkSpeedCalculator. If the plugin handler returns a speed, it is
// used, otherwise the default speed is used. This has the advantage that multiple plugins can register such special link speed calculators.

// this gives the typical things to the router:
addTravelTimeBinding(bicycleConfigGroup.getBicycleMode()).to(BicycleTravelTime.class).in(Singleton.class);
addTravelDisutilityFactoryBinding(bicycleConfigGroup.getBicycleMode()).to(BicycleTravelDisutilityFactory.class).in(Singleton.class);
// (the BicycleTravelTime uses the BicycleLinkSpeed Calculator bound below)
// (the BicycleDisutility uses a BicycleTravelDisutility)

// compute and throw the additional score events:
this.addEventHandlerBinding().to( BicycleScoreEventsCreator.class );
// (the motorized interaction is in the BicycleScoreEventsCreator)
// (this uses the AdditionalBicycleLinkScore to compute and throw corresponding scoring events)
// (it also computes and throws the motorized interaction events, if they are switched on)

this.bind( AdditionalBicycleLinkScore.class ).to( AdditionalBicycleLinkScoreDefaultImpl.class );

bind( BicycleLinkSpeedCalculator.class ).to( BicycleLinkSpeedCalculatorDefaultImpl.class ) ;
// this is still needed because the bicycle travel time calculator for routing needs to use the same bicycle speed as the mobsim. kai, jun'23
// (this computes the value of the per-link scoring event. yyyy Very unfortunately, it is a re-implementation of the BicycleTravelDisutility (mentioned above).)

this.installOverridingQSimModule( new AbstractQSimModule(){
@Override protected void configureQSim(){
this.addLinkSpeedCalculator().to( BicycleLinkSpeedCalculator.class );
}
} );

bind( BicycleLinkSpeedCalculator.class ).to( BicycleLinkSpeedCalculatorDefaultImpl.class ) ;
// (both the router and the mobsim need this)

addControlerListenerBinding().to(ConsistencyCheck.class);
}

Expand All @@ -73,7 +91,6 @@ static class ConsistencyCheck implements StartupListener {
@Inject private Scenario scenario;

@Override public void notifyStartup(StartupEvent event) {

Id<VehicleType> bicycleVehTypeId = Id.create(bicycleConfigGroup.getBicycleMode(), VehicleType.class);
if (scenario.getVehicles().getVehicleTypes().get(bicycleVehTypeId) == null) {
LOG.warn("There is no vehicle type '" + bicycleConfigGroup.getBicycleMode() + "' specified in the vehicle types. "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import com.google.inject.Inject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.config.groups.ScoringConfigGroup;
import org.matsim.core.config.groups.RoutingConfigGroup;
import org.matsim.core.router.costcalculators.TravelDisutilityFactory;
Expand All @@ -35,21 +37,20 @@
*/
public final class BicycleTravelDisutilityFactory implements TravelDisutilityFactory {
// public-final is ok since ctor is package-private: can only be used through injection

private static final Logger LOG = LogManager.getLogger(BicycleTravelDisutilityFactory.class);

@Inject BicycleConfigGroup bicycleConfigGroup;
@Inject
ScoringConfigGroup cnScoringGroup;
@Inject
RoutingConfigGroup routingConfigGroup;

private BicycleConfigGroup bicycleConfigGroup;
@Inject Config config;
@Inject ScoringConfigGroup cnScoringGroup;
@Inject RoutingConfigGroup routingConfigGroup;
private static int normalisationWrnCnt = 0;

/* package-private */ BicycleTravelDisutilityFactory(){}
/* package-private */ BicycleTravelDisutilityFactory(){
}

@Override
public TravelDisutility createTravelDisutility(TravelTime timeCalculator) {
this.bicycleConfigGroup = ConfigUtils.addOrGetModule( config, BicycleConfigGroup.class );

double sigma = routingConfigGroup.getRoutingRandomness();

double normalization = 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,11 @@ private static boolean hasNoCycleway( String cyclewayType ) {
}
return userDefinedNetworkAttributeFactor;
}
// ===
public static void setSmoothness( Link link, String smoothness ){
link.getAttributes().putAttribute( SMOOTHNESS, smoothness );
}
public static void setBicycleInfrastructureFactor( Link link, double factor ){
link.getAttributes().putAttribute( BICYCLE_INFRASTRUCTURE_SPEED_FACTOR, factor );
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ protected void setOrModifyLinkAttributes(Link l, OsmWay way, boolean forwardDire
// Smoothness
String smoothness = way.tags.get(BicycleUtils.SMOOTHNESS);
if (smoothness != null) {
l.getAttributes().putAttribute(BicycleUtils.SMOOTHNESS, smoothness);
BicycleUtils.setSmoothness( l, smoothness );
this.countSmoothness++;
}

Expand Down
Loading

0 comments on commit edb9f45

Please sign in to comment.