Skip to content

Commit

Permalink
prepare data before simulation (DrsData)
Browse files Browse the repository at this point in the history
and refactoring:
- remove .* imports
- directly inject DrsConfigGroup where possible
  • Loading branch information
markusstraub committed Nov 27, 2024
1 parent 5e90f9d commit 687ffae
Show file tree
Hide file tree
Showing 12 changed files with 131 additions and 70 deletions.
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
package at.ac.ait.matsim.drs.engine;

import at.ac.ait.matsim.drs.run.Drs;
import at.ac.ait.matsim.drs.run.DrsConfigGroup;
import com.google.inject.Inject;
import java.util.Objects;

import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.TransportMode;
import org.matsim.api.core.v01.events.PersonMoneyEvent;
import org.matsim.api.core.v01.population.*;
import org.matsim.api.core.v01.population.Leg;
import org.matsim.api.core.v01.population.Person;
import org.matsim.api.core.v01.population.PlanElement;
import org.matsim.api.core.v01.population.Population;
import org.matsim.core.api.experimental.events.EventsManager;
import org.matsim.core.controler.events.BeforeMobsimEvent;
import org.matsim.core.controler.listener.BeforeMobsimListener;

import java.util.*;
import com.google.inject.Inject;

import at.ac.ait.matsim.drs.run.Drs;
import at.ac.ait.matsim.drs.run.DrsConfigGroup;

public class DailyMonetaryConstantListener implements BeforeMobsimListener {
private final Scenario scenario;
private final DrsConfigGroup cfgGroup;
private final DrsConfigGroup drsConfig;
private final EventsManager eventsManager;

@Inject
public DailyMonetaryConstantListener(Scenario scenario, EventsManager eventsManager) {
public DailyMonetaryConstantListener(Scenario scenario, DrsConfigGroup drsConfig, EventsManager eventsManager) {
this.scenario = scenario;
cfgGroup = Drs.addOrGetConfigGroup(scenario);
this.drsConfig = drsConfig;
this.eventsManager = eventsManager;
}

Expand All @@ -47,7 +52,7 @@ private void addDailyMonetaryConstant() {
eventsManager.processEvent(new PersonMoneyEvent(
0,
person.getId(),
cfgGroup.getCarAndDrsDailyMonetaryConstant(),
drsConfig.getCarAndDrsDailyMonetaryConstant(),
"dailyMonetaryConstant",
null,
"drsDriver or car"));
Expand Down
49 changes: 49 additions & 0 deletions src/main/java/at/ac/ait/matsim/drs/engine/DrsData.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package at.ac.ait.matsim.drs.engine;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.network.Network;
import org.matsim.contrib.common.zones.ZoneSystem;
import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystem;
import org.matsim.pt2matsim.tools.NetworkTools;

import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;

import at.ac.ait.matsim.drs.run.Drs;
import at.ac.ait.matsim.drs.run.DrsConfigGroup;

/**
* Data that should only be prepared once (instead of each iteration)
*/
public class DrsData {

private static final Logger LOGGER = LogManager.getLogger();

private Network drsNetwork;
private ZoneSystem zoneSystem;

@Inject
public DrsData(Scenario scenario, DrsConfigGroup drsConfig) {
this.drsNetwork = NetworkTools.createFilteredNetworkByLinkMode(scenario.getNetwork(),
ImmutableSet.of(Drs.DRIVER_MODE));
LOGGER.info("Filtered {} drs driver links from network with {} links", drsNetwork.getLinks().size(),
scenario.getNetwork().getLinks().size());

this.zoneSystem = new SquareGridZoneSystem(scenario.getNetwork(), drsConfig.getCellSize());
LOGGER.info("Initialized zone system.");
}

public static Logger getLogger() {
return LOGGER;
}

public Network getDrsNetwork() {
return drsNetwork;
}

public ZoneSystem getZoneSystem() {
return zoneSystem;
}
}
11 changes: 5 additions & 6 deletions src/main/java/at/ac/ait/matsim/drs/engine/DrsEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.events.PersonEntersVehicleEvent;
import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent;
import org.matsim.api.core.v01.events.PersonMoneyEvent;
Expand Down Expand Up @@ -47,7 +46,7 @@
public class DrsEngine implements MobsimEngine, ActivityHandler, DepartureHandler {
public static final String COMPONENT_NAME = "drsEngine";
private static final Logger LOGGER = LogManager.getLogger();
private final DrsConfigGroup cfgGroup;
private final DrsConfigGroup drsConfig;
private InternalInterface internalInterface;
private final EventsManager eventsManager;
private final Map<Id<Person>, Id<Link>> waitingRiders = new ConcurrentHashMap<>();
Expand All @@ -58,8 +57,8 @@ private static record PickupEntry(MobsimDriverAgent driver, MobsimPassengerAgent
};

@Inject
public DrsEngine(Scenario scenario, EventsManager eventsManager) {
this.cfgGroup = Drs.addOrGetConfigGroup(scenario);
public DrsEngine(DrsConfigGroup drsConfig, EventsManager eventsManager) {
this.drsConfig = drsConfig;
this.eventsManager = eventsManager;
LOGGER.info("Constructed new DrsEngine.");
}
Expand Down Expand Up @@ -230,11 +229,11 @@ private void handleDropoff(MobsimDriverAgent driver, MobsimPassengerAgent rider,
DrsUtil.setDrsStatus(leg, Drs.VALUE_STATUS_DRS);
double distance = legWithRider.getRoute().getDistance();

if (cfgGroup.getDriverProfitPerKm() != 0) {
if (drsConfig.getDriverProfitPerKm() != 0) {
eventsManager.processEvent(new PersonMoneyEvent(
now,
driver.getId(),
cfgGroup.getDriverProfitPerKm() * distance / 1000d,
drsConfig.getDriverProfitPerKm() * distance / 1000d,
Drs.DRIVER_MODE + " profit",
rider.getId().toString(),
null));
Expand Down
15 changes: 6 additions & 9 deletions src/main/java/at/ac/ait/matsim/drs/engine/PlanModifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.network.Network;
import org.matsim.api.core.v01.population.Activity;
import org.matsim.api.core.v01.population.Leg;
import org.matsim.api.core.v01.population.PlanElement;
Expand All @@ -28,9 +27,7 @@
import org.matsim.core.router.RoutingModule;
import org.matsim.core.router.TripRouter;
import org.matsim.core.router.TripStructureUtils;
import org.matsim.pt2matsim.tools.NetworkTools;

import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;

import at.ac.ait.matsim.drs.analysis.DrsTripsInfoCollector;
Expand All @@ -50,7 +47,7 @@
public class PlanModifier implements ReplanningListener, IterationStartsListener {
private static final Logger LOGGER = LogManager.getLogger();
private final Scenario scenario;
private final Network drsNetwork;
private final DrsData drsData;
private final GlobalConfigGroup globalConfig;
private final DrsConfigGroup drsConfig;
private final RoutingModule driverRouter;
Expand All @@ -59,12 +56,12 @@ public class PlanModifier implements ReplanningListener, IterationStartsListener
private final UnmatchedRiderConflictResolver unmatchedRiderConflictResolver;

@Inject
public PlanModifier(Scenario scenario, TripRouter tripRouter, OutputDirectoryHierarchy outputDirectoryHierarchy) {
public PlanModifier(Scenario scenario, DrsConfigGroup drsConfig, DrsData drsData, TripRouter tripRouter,
OutputDirectoryHierarchy outputDirectoryHierarchy) {
this.scenario = scenario;
this.drsNetwork = NetworkTools.createFilteredNetworkByLinkMode(scenario.getNetwork(),
ImmutableSet.of(Drs.DRIVER_MODE));
this.drsData = drsData;
this.globalConfig = scenario.getConfig().global();
this.drsConfig = Drs.addOrGetConfigGroup(scenario);
this.drsConfig = drsConfig;
driverRouter = tripRouter.getRoutingModule(Drs.DRIVER_MODE);
this.outputDirectoryHierarchy = outputDirectoryHierarchy;

Expand Down Expand Up @@ -106,7 +103,7 @@ public void notifyReplanning(ReplanningEvent event) {

private void preplanDay(boolean isLastIteration) {
Population population = scenario.getPopulation();
DrsOptimizer optimizer = new DrsOptimizer(drsNetwork, drsConfig, population, driverRouter);
DrsOptimizer optimizer = new DrsOptimizer(drsData, drsConfig, population, driverRouter);
MatchingResult result = optimizer.optimize();
if (isLastIteration) {
DrsTripsInfoCollector infoCollector = new DrsTripsInfoCollector(globalConfig,
Expand Down
22 changes: 9 additions & 13 deletions src/main/java/at/ac/ait/matsim/drs/optimizer/DrsOptimizer.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,38 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.matsim.api.core.v01.network.Network;
import org.matsim.api.core.v01.population.Population;
import org.matsim.contrib.common.zones.ZoneSystem;
import org.matsim.contrib.common.zones.systems.grid.square.SquareGridZoneSystem;
import org.matsim.core.router.RoutingModule;

import at.ac.ait.matsim.drs.engine.DrsData;
import at.ac.ait.matsim.drs.run.DrsConfigGroup;

public class DrsOptimizer {
private static final Logger LOGGER = LogManager.getLogger();
private final Network network;
private final DrsData drsData;
private final DrsConfigGroup drsConfig;
private final Population population;
private final RoutingModule driverRouter;

public DrsOptimizer(Network network,
public DrsOptimizer(DrsData drsData,
DrsConfigGroup drsConfig,
Population population,
RoutingModule driverRouter) {
this.network = network;
this.drsData = drsData;
this.drsConfig = drsConfig;
this.population = population;
this.driverRouter = driverRouter;
}

public MatchingResult optimize() {
LOGGER.info("Matching process started!");
ZoneSystem zoneSystem = new SquareGridZoneSystem(network, drsConfig.getCellSize());
RequestZoneRegistry originZoneRegistry = RequestZoneRegistry.createRequestZoneRegistry(zoneSystem,
true);
RequestZoneRegistry originZoneRegistry = RequestZoneRegistry.createRequestZoneRegistry(
drsData.getZoneSystem(), true);
RequestZoneRegistry destinationZoneRegistry = RequestZoneRegistry.createRequestZoneRegistry(
zoneSystem,
false);
drsData.getZoneSystem(), false);
RequestTimeSegmentRegistry timeSegmentRegistry = new RequestTimeSegmentRegistry(drsConfig);
RequestsCollector requestsCollector = new RequestsCollector(drsConfig, population, network,
driverRouter);
RequestsCollector requestsCollector = new RequestsCollector(drsConfig, population,
drsData.getDrsNetwork(), driverRouter);
RequestsRegister requestsRegister = new RequestsRegister(originZoneRegistry, destinationZoneRegistry,
timeSegmentRegistry);
PotentialRequestsFinder potentialRequestsFinder = new PotentialRequestsFinder(drsConfig,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,26 @@
import at.ac.ait.matsim.drs.run.DrsConfigGroup;

public class PotentialRequestsFinder {
private final DrsConfigGroup cfgGroup;
private final DrsConfigGroup drsConfig;
private final RequestsRegister requestsRegister;

public PotentialRequestsFinder(DrsConfigGroup cfgGroup, RequestsRegister requestsRegister) {
this.cfgGroup = cfgGroup;
public PotentialRequestsFinder(DrsConfigGroup drsConfig, RequestsRegister requestsRegister) {
this.drsConfig = drsConfig;
this.requestsRegister = requestsRegister;
}

public List<DrsRequest> findRegistryIntersections(Node origin, Node destination, double departureTime) {
return getIntersection(cfgGroup, requestsRegister.getOriginZoneRegistry().findNearestRequests(origin),
return getIntersection(drsConfig, requestsRegister.getOriginZoneRegistry().findNearestRequests(origin),
requestsRegister.getDestinationZoneRegistry().findNearestRequests(destination),
requestsRegister.getTimeSegmentRegistry().findNearestRequests(departureTime));
}

static List<DrsRequest> getIntersection(DrsConfigGroup cfgGroup,
static List<DrsRequest> getIntersection(DrsConfigGroup drsConfig,
Stream<DrsRequest> originNearRequests, Stream<DrsRequest> destinationNearRequests,
Stream<DrsRequest> temporalNearRequests) {
Stream<DrsRequest> zoneRegistryIntersection = originNearRequests
.filter(destinationNearRequests.collect(Collectors.toList())::contains);
return zoneRegistryIntersection.filter(temporalNearRequests.collect(Collectors.toList())::contains)
.limit(cfgGroup.getMaxPossibleCandidates()).collect(Collectors.toCollection(ArrayList::new));
.limit(drsConfig.getMaxPossibleCandidates()).collect(Collectors.toCollection(ArrayList::new));
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package at.ac.ait.matsim.drs.optimizer;

import at.ac.ait.matsim.drs.run.DrsConfigGroup;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import org.matsim.api.core.v01.Id;
import org.matsim.contrib.dvrp.optimizer.Request;
import java.util.*;
import java.util.stream.Stream;

import at.ac.ait.matsim.drs.run.DrsConfigGroup;

/**
* Heavily inspired by
Expand All @@ -13,15 +16,15 @@

public class RequestTimeSegmentRegistry {
private final Map<Integer, Map<Id<Request>, DrsRequest>> requestsInTimeSegments;
private final DrsConfigGroup cfgGroup;
private final DrsConfigGroup drsConfig;

public RequestTimeSegmentRegistry(DrsConfigGroup cfgGroup) {
this.cfgGroup = cfgGroup;
public RequestTimeSegmentRegistry(DrsConfigGroup drsConfig) {
this.drsConfig = drsConfig;
this.requestsInTimeSegments = new HashMap<>();
}

public void addRequest(DrsRequest request) {
int timeSegment = getTimeSegment(request.getDepartureTime(), cfgGroup.getTimeSegmentLengthSeconds());
int timeSegment = getTimeSegment(request.getDepartureTime(), drsConfig.getTimeSegmentLengthSeconds());
Map<Id<Request>, DrsRequest> requestsInTimeSegment = requestsInTimeSegments.get(timeSegment);
if (requestsInTimeSegment != null) {
if (requestsInTimeSegments.get(timeSegment).get(request.getId()) != null) {
Expand All @@ -37,14 +40,14 @@ public void addRequest(DrsRequest request) {
}

public void removeRequest(DrsRequest request) {
int timeSegment = getTimeSegment(request.getDepartureTime(), cfgGroup.getTimeSegmentLengthSeconds());
int timeSegment = getTimeSegment(request.getDepartureTime(), drsConfig.getTimeSegmentLengthSeconds());
if (requestsInTimeSegments.get(timeSegment).remove(request.getId()) == null) {
throw new IllegalStateException(request + " is not in the registry");
}
}

public Stream<DrsRequest> findNearestRequests(double departureTime) {
int timeSegment = getTimeSegment(departureTime, cfgGroup.getTimeSegmentLengthSeconds());
int timeSegment = getTimeSegment(departureTime, drsConfig.getTimeSegmentLengthSeconds());
Stream<DrsRequest> requestsInPreviousSegment = Stream.empty();
Stream<DrsRequest> requestsInCurrentSegment = Stream.empty();
Stream<DrsRequest> requestsInNextSegment = Stream.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,18 @@
public class RequestsCollector {
private static final Logger LOGGER = LogManager.getLogger();

private final DrsConfigGroup cfgGroup;
private final DrsConfigGroup drsConfig;
private final Population population;
private final Network network;
private final Network drsNetwork;
private final RoutingModule driverRouter;
private List<DrsRequest> driverRequests;
private List<DrsRequest> riderRequests;

public RequestsCollector(DrsConfigGroup cfgGroup, Population population, Network network,
public RequestsCollector(DrsConfigGroup drsConfig, Population population, Network drsNetwork,
RoutingModule driverRouter) {
this.cfgGroup = cfgGroup;
this.drsConfig = drsConfig;
this.population = population;
this.network = network;
this.drsNetwork = drsNetwork;
this.driverRouter = driverRouter;
}

Expand All @@ -61,18 +61,18 @@ public void collectRequests() {
}

Id<Request> id = Id.create(++requestId, Request.class);
DrsRequest request = DrsRequest.create(id, driverRouter, network, person, trip);
DrsRequest request = DrsRequest.create(id, driverRouter, drsNetwork, person, trip);

double distance = request.getNetworkRouteDistance();
if (request instanceof DrsDriverRequest) {
if (cfgGroup.getMinDriverLegMeters() <= 0 || cfgGroup.getMinDriverLegMeters() <= distance) {
if (drsConfig.getMinDriverLegMeters() <= 0 || drsConfig.getMinDriverLegMeters() <= distance) {
driverRequests.add(request);
} else {
LOGGER.debug("Ignoring {} request below min distance for person {}", request.getMode(),
person.getId());
}
} else if (request instanceof DrsRiderRequest) {
if (cfgGroup.getMinRiderLegMeters() <= 0 || cfgGroup.getMinRiderLegMeters() <= distance) {
if (drsConfig.getMinRiderLegMeters() <= 0 || drsConfig.getMinRiderLegMeters() <= distance) {
riderRequests.add(request);
} else {
LOGGER.debug("Ignoring {} request below min distance for person {}", request.getMode(),
Expand Down
Loading

0 comments on commit 687ffae

Please sign in to comment.