All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.opentripplanner.ext.sorlandsbanen.MergePaths Maven / Gradle / Ivy

The newest version!
package org.opentripplanner.ext.sorlandsbanen;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import org.opentripplanner.raptor.api.model.RaptorTripSchedule;
import org.opentripplanner.raptor.api.path.PathLeg;
import org.opentripplanner.raptor.api.path.RaptorPath;
import org.opentripplanner.routing.algorithm.raptoradapter.transit.request.TripScheduleWithOffset;
import org.opentripplanner.transit.model.basic.TransitMode;

/**
 * Strategy for merging the main results and the extra rail results from Sorlandsbanen.
 * Everything from the main result is kept, and any additional rail results from the alternative
 * search are added.
 */
class MergePaths
  implements
    BiFunction>, Collection>, Collection>> {

  @Override
  public Collection> apply(
    Collection> main,
    Collection> alternatives
  ) {
    Map> result = new HashMap<>();
    addAllToMap(result, main);
    addRailToMap(result, alternatives);
    return result.values();
  }

  private void addAllToMap(Map> map, Collection> paths) {
    for (var it : paths) {
      map.put(new PathKey(it), it);
    }
  }

  private void addRailToMap(Map> map, Collection> paths) {
    for (var it : paths) {
      if (hasRail(it)) {
        // Avoid replacing an existing value if it exists, there might be minor differences in the
        // path, in which case we want to keep the main result.
        map.computeIfAbsent(new PathKey(it), k -> it);
      }
    }
  }

  private static boolean hasRail(RaptorPath path) {
    return path
      .legStream()
      .filter(PathLeg::isTransitLeg)
      .anyMatch(leg -> {
        var trip = (TripScheduleWithOffset) leg.asTransitLeg().trip();
        var mode = trip.getOriginalTripPattern().getMode();
        return mode == TransitMode.RAIL;
      });
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy