diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/CostCalculatorFactory.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/CostCalculatorFactory.java index aee2a23b94a..efcdf1916fe 100644 --- a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/CostCalculatorFactory.java +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/CostCalculatorFactory.java @@ -30,6 +30,12 @@ public static RaptorCostCalculator createCost ); } + // 酔いの表が読み込めていれば、酔いのコストを重ねる(-Dsickness.dir=... で指定) + SicknessData sicknessData = SicknessData.instance(); + if (sicknessData != null) { + calculator = new SicknessCostCalculator<>(calculator, sicknessData); + } + return calculator; } } diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/SicknessCostCalculator.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/SicknessCostCalculator.java new file mode 100644 index 00000000000..c0ce4a83a21 --- /dev/null +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/SicknessCostCalculator.java @@ -0,0 +1,150 @@ +package org.opentripplanner.routing.algorithm.raptoradapter.transit.cost; + +import org.opentripplanner.raptor.spi.RaptorCostCalculator; +import org.opentripplanner.raptor.spi.RaptorCostConverter; +import org.opentripplanner.raptor.spi.RaptorTransferConstraint; +import org.opentripplanner.routing.algorithm.raptoradapter.transit.TripSchedule; + +/** + * バスを降りるときに、その区間の「酔いの点数」に応じたコストを足す。 + *

+ * S = (a_curve * N_curve/L + a_signal * N_signal/L + a_stop * N_stop/L) * sqrt(T_ride) + *

+ * 追加するコスト = BETA_SECONDS * S(秒)。 + *

+ * PatternCostCalculator と同じく、ほかの計算の上に重ねて使う。 + */ +class SicknessCostCalculator implements RaptorCostCalculator { + + // ===== 重み(仮の値) ===== + static final double ALPHA_CURVE = 1.0; + static final double ALPHA_SIGNAL = 1.0; + static final double ALPHA_STOP = 1.0; + /** 酔い1点を、何秒の遠回りと同じとみなすか */ + static final double BETA_SECONDS = 10.0; + /** これより短い区間(km)は計算しない(0で割るのを防ぐ) */ + static final double MIN_LENGTH_KM = 0.05; + // ========================= + + private final RaptorCostCalculator delegate; + private final SicknessData data; + + SicknessCostCalculator(RaptorCostCalculator delegate, SicknessData data) { + this.delegate = delegate; + this.data = data; + } + + @Override + public int boardingCost( + boolean firstBoarding, + int prevArrivalTime, + int boardStopIndex, + int boardTime, + T trip, + RaptorTransferConstraint transferConstraints + ) { + return delegate.boardingCost( + firstBoarding, + prevArrivalTime, + boardStopIndex, + boardTime, + trip, + transferConstraints + ); + } + + @Override + public int transitCost(int transitDuration, T tripScheduledBoarded) { + return delegate.transitCost(transitDuration, tripScheduledBoarded); + } + + @Override + public int transitArrivalCost( + int boardCost, + int alightSlack, + int transitDuration, + T trip, + int toStopIndex + ) { + int defaultCost = delegate.transitArrivalCost( + boardCost, + alightSlack, + transitDuration, + trip, + toStopIndex + ); + double seconds = sicknessSeconds(transitDuration, trip, toStopIndex); + return seconds > 0 ? defaultCost + RaptorCostConverter.toRaptorCost(seconds) : defaultCost; + } + + /** 酔いの追加コスト(秒)。計算できないときは 0。 */ + double sicknessSeconds(int transitDuration, T trip, int toStopIndex) { + if (!(trip instanceof TripSchedule schedule)) { + return 0; + } + SicknessData.Cumulative cum = data.forTrip( + schedule.getOriginalTripTimes().getTrip().getId().getId() + ); + if (cum == null) { + // 表に無い便(市営バス以外など)は足さない + return 0; + } + var pattern = trip.pattern(); + int nStops = pattern.numberOfStopsInPattern(); + if (nStops != cum.numberOfStops()) { + // OTPのバス停の並びと表が合わないときは足さない + return 0; + } + // 降りたバス停の位置と、乗ったバス停の位置を探す。 + // 乗った時刻 = 降りたバス停の到着時刻 - 乗っていた時間 + for (int alight = nStops - 1; alight > 0; alight--) { + if (pattern.stopIndex(alight) != toStopIndex) { + continue; + } + int boardTime = trip.arrival(alight) - transitDuration; + for (int board = alight - 1; board >= 0; board--) { + if (trip.departure(board) == boardTime) { + return BETA_SECONDS * score(cum, board, alight, transitDuration); + } + } + } + return 0; + } + + static double score(SicknessData.Cumulative c, int board, int alight, int transitDurationSec) { + double lengthKm = (c.distM()[alight] - c.distM()[board]) / 1000.0; + if (lengthKm < MIN_LENGTH_KM) { + return 0; + } + int curves = c.curves()[alight] - c.curves()[board]; + int signals = c.signals()[alight] - c.signals()[board]; + int stops = alight - board - 1; + double density = + (ALPHA_CURVE * curves + ALPHA_SIGNAL * signals + ALPHA_STOP * stops) / lengthKm; + double rideMin = Math.max(0, transitDurationSec) / 60.0; + return density * Math.sqrt(rideMin); + } + + @Override + public int waitCost(int waitTimeInSeconds) { + return delegate.waitCost(waitTimeInSeconds); + } + + @Override + public int calculateRemainingMinCost( + int minTravelDuration, + int minNumTransfers, + int fromStopIndex + ) { + return delegate.calculateRemainingMinCost(minTravelDuration, minNumTransfers, fromStopIndex); + } + + @Override + public int costEgress(int stopIndex, boolean egressHasRides) { + return delegate.costEgress(stopIndex, egressHasRides); + } +} diff --git a/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/SicknessData.java b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/SicknessData.java new file mode 100644 index 00000000000..4adafb294b9 --- /dev/null +++ b/application/src/main/java/org/opentripplanner/routing/algorithm/raptoradapter/transit/cost/SicknessData.java @@ -0,0 +1,155 @@ +package org.opentripplanner.routing.algorithm.raptoradapter.transit.cost; + +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 酔いの計算に使う表(hops.csv と trip_pattern.csv)を読み込んで持っておくクラス。 + *

+ * 起動時に {@code -Dsickness.dir=フォルダ} を指定すると、そのフォルダから2つのCSVを読む。 + * 指定がなければ何もしない(酔いのコストは足されない)。 + *

+ * 便ごとに「1番目のバス停からの累積値」を持っておくので、 + * 乗ったバス停から降りたバス停までの合計は、引き算1回で出せる。 + */ +public final class SicknessData { + + private static final Logger LOG = LoggerFactory.getLogger(SicknessData.class); + private static volatile SicknessData instance; + private static volatile boolean initialized = false; + + /** 1つの区間の並び(pattern)の累積値。配列の長さ = バス停の数。 */ + public record Cumulative(double[] distM, int[] curves, int[] signals) { + public int numberOfStops() { + return distM.length; + } + } + + private final Map byTripId; + + private SicknessData(Map byTripId) { + this.byTripId = byTripId; + } + + /** 表が読み込めていればそのデータ、なければ null を返す。 */ + @Nullable + public static SicknessData instance() { + if (!initialized) { + synchronized (SicknessData.class) { + if (!initialized) { + instance = load(System.getProperty("sickness.dir")); + initialized = true; + } + } + } + return instance; + } + + @Nullable + public Cumulative forTrip(String gtfsTripId) { + return byTripId.get(gtfsTripId); + } + + @Nullable + private static SicknessData load(@Nullable String dir) { + if (dir == null || dir.isBlank()) { + LOG.info("sickness.dir が指定されていないので、酔いのコストは使いません。"); + return null; + } + try { + Path hops = Path.of(dir, "hops.csv"); + Path tripPattern = Path.of(dir, "trip_pattern.csv"); + + // pattern_id -> 区間の行(hop_index 順) + Map> hopsByPattern = new HashMap<>(); + try (BufferedReader r = Files.newBufferedReader(hops, StandardCharsets.UTF_8)) { + String[] header = r.readLine().replace("", "").split(","); + int iPattern = col(header, "pattern_id"); + int iIndex = col(header, "hop_index"); + int iDist = col(header, "dist_m"); + int iCurve = col(header, "n_curve"); + int iSignal = col(header, "n_signal"); + String line; + while ((line = r.readLine()) != null) { + if (line.isBlank()) { + continue; + } + String[] f = line.split(","); + hopsByPattern + .computeIfAbsent(f[iPattern], k -> new ArrayList<>()) + .add(new double[] { + Integer.parseInt(f[iIndex]), + Double.parseDouble(f[iDist]), + Integer.parseInt(f[iCurve]), + Integer.parseInt(f[iSignal]), + }); + } + } + + // pattern_id -> 累積値 + Map cumByPattern = new HashMap<>(); + for (var e : hopsByPattern.entrySet()) { + List rows = e.getValue(); + rows.sort((a, b) -> Double.compare(a[0], b[0])); + int n = rows.size() + 1; + double[] dist = new double[n]; + int[] curves = new int[n]; + int[] signals = new int[n]; + for (int k = 0; k < rows.size(); k++) { + dist[k + 1] = dist[k] + rows.get(k)[1]; + curves[k + 1] = curves[k] + (int) rows.get(k)[2]; + signals[k + 1] = signals[k] + (int) rows.get(k)[3]; + } + cumByPattern.put(e.getKey(), new Cumulative(dist, curves, signals)); + } + + // trip_id -> 累積値 + Map byTripId = new HashMap<>(); + try (BufferedReader r = Files.newBufferedReader(tripPattern, StandardCharsets.UTF_8)) { + String[] header = r.readLine().replace("", "").split(","); + int iTrip = col(header, "trip_id"); + int iPattern = col(header, "pattern_id"); + String line; + while ((line = r.readLine()) != null) { + if (line.isBlank()) { + continue; + } + String[] f = line.split(","); + Cumulative c = cumByPattern.get(f[iPattern]); + if (c != null) { + byTripId.put(f[iTrip], c); + } + } + } + LOG.info( + "酔いの表を読み込みました: 区間の並び {} 通り, 便 {} 本 ({})", + cumByPattern.size(), + byTripId.size(), + dir + ); + return new SicknessData(byTripId); + } catch (IOException | RuntimeException e) { + LOG.error("酔いの表を読み込めませんでした ({}): {}", dir, e.toString()); + return null; + } + } + + private static int col(String[] header, String name) { + for (int i = 0; i < header.length; i++) { + if (header[i].trim().equals(name)) { + return i; + } + } + throw new IllegalArgumentException("列が見つかりません: " + name); + } +}