Skip to content

Commit

Permalink
Refactored test-code
Browse files Browse the repository at this point in the history
  • Loading branch information
Aleksander1234519 committed Jul 3, 2024
1 parent 861dee1 commit 3395237
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 152 deletions.
60 changes: 16 additions & 44 deletions src/main/java/org/matsim/prepare/MigrantBicycleChoiceHandler.java
Original file line number Diff line number Diff line change
@@ -1,58 +1,50 @@
package org.matsim.prepare;

import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.TransportMode;
import org.matsim.api.core.v01.events.PersonDepartureEvent;
import org.matsim.api.core.v01.events.PersonMoneyEvent;
import org.matsim.api.core.v01.events.PersonScoreEvent;
import org.matsim.api.core.v01.events.handler.PersonDepartureEventHandler;
import org.matsim.api.core.v01.population.Person;
import org.matsim.api.core.v01.population.Population;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.controler.events.AfterMobsimEvent;
import org.matsim.core.controler.events.ReplanningEvent;
import org.matsim.core.controler.listener.AfterMobsimListener;
import org.matsim.core.controler.listener.ReplanningListener;
import org.matsim.core.events.EventsUtils;
import org.matsim.core.gbl.MatsimRandom;
import org.matsim.core.population.PopulationUtils;
import org.matsim.core.utils.misc.Time;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
* This handler will give all migrants in the population (persons with attribute {@code "migrant": true}) a massive negative score when using bikes.
* Migrant thus will not use the bike, when this handler is used.
*/
public class MigrantBicycleChoiceHandler implements PersonDepartureEventHandler, AfterMobsimListener {
private List<PersonScoreEvent> migrantDepartures;
private Population population;
private List<Id<Person>> migrants;

public MigrantBicycleChoiceHandler(Population population) {
public MigrantBicycleChoiceHandler(List<Id<Person>> listOfMigrants) {
migrants = listOfMigrants;
migrantDepartures = new LinkedList<>();
this.population = population;
}


public MigrantBicycleChoiceHandler(List<Id<Person>> listOfMigrants) {
migrants = listOfMigrants;
public MigrantBicycleChoiceHandler(Population population) {
migrantDepartures = new LinkedList<>();
migrants = new LinkedList<>();
for(Person p : population.getPersons().values()){
if(p.getAttributes().getAsMap().containsKey("migrant") && p.getAttributes().getAttribute("migrant").equals(true)) migrants.add(p.getId());
}
}

public MigrantBicycleChoiceHandler(String populationPath) {
migrantDepartures = new LinkedList<>();
this.population = PopulationUtils.readPopulation(populationPath);
migrants = new LinkedList<>();
Population population = PopulationUtils.readPopulation(populationPath);
for(Person p : population.getPersons().values()){
if(p.getAttributes().getAsMap().containsKey("migrant") && p.getAttributes().getAttribute("migrant").equals(true)) migrants.add(p.getId());
}
}

@Override
public void handleEvent(PersonDepartureEvent personDepartureEvent) {
/* // Do not do anything, if this Person is not a migrant
if( !population.getPersons().get(personDepartureEvent.getPersonId()).getAttributes().getAsMap().containsKey("subpopulation")
|| !population.getPersons().get(personDepartureEvent.getPersonId()).getAttributes().getAttribute("subpopulation").equals("migrant") ){
return;
}
*/
if(personDepartureEvent.getLegMode().equals("bicycle") && migrants.contains(personDepartureEvent.getPersonId())) {
migrantDepartures.add(new PersonScoreEvent(personDepartureEvent.getTime(), personDepartureEvent.getPersonId(), -10000.0, "punishment_for_cycling"));
}
Expand All @@ -64,30 +56,10 @@ public void notifyAfterMobsim(AfterMobsimEvent afterMobsimEvent) {
for(PersonScoreEvent personScoreEvent : migrantDepartures) {
afterMobsimEvent.getServices().getEvents().processEvent(personScoreEvent);
}



}

@Override
public void reset(int iteration) {
PersonDepartureEventHandler.super.reset(iteration);
}



/* public static void main(String[] args) {
//MigrantBicycleChoiceHandler choiceHandler = new MigrantBicycleChoiceHandler();
}*/

// @Override
// public void notifyReplanning(ReplanningEvent replanningEvent) {
// /*for(PersonScoreEvent e : migrantDepartures){
// // TODO Check if this will actually influence the choice
// // TODO Check what would be a useful value
// // TODO Gibt es keine direktere Möglichkeit? Kann ich das Event nicht einfach irgendwie überschreiben?
// replanningEvent.getServices().getEvents().processEvent(e);
// }*/
// }
}
4 changes: 2 additions & 2 deletions src/main/java/org/matsim/prepare/MigrantMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,8 @@ private void assignMigrantMapToPopulation(){
for(var e : migrantProbabilityMap.entrySet()){
double r = e.getValue();
boolean isMigrant = rand.nextInt(1000) < r*1000;
//pop.getPersons().get(e.getKey()).getAttributes().putAttribute("isMigrant", isMigrant);
pop.getPersons().get(e.getKey()).getAttributes().putAttribute("subpopulation", "migrant");
pop.getPersons().get(e.getKey()).getAttributes().putAttribute("migrant", isMigrant);
// pop.getPersons().get(e.getKey()).getAttributes().putAttribute("subpopulation", "migrant");
if (isMigrant) totalMigrants++;
//TODO DEBUG
if (isMigrant){
Expand Down
102 changes: 28 additions & 74 deletions src/test/java/org/matsim/prepare/MigrantBicycleChoiceHandlerTest.java
Original file line number Diff line number Diff line change
@@ -1,115 +1,69 @@
package org.matsim.prepare;

import ch.sbb.matsim.routing.pt.raptor.RaptorIntermodalAccessEgress;
import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorModule;
import com.google.inject.Singleton;
import com.google.inject.multibindings.Multibinder;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.matsim.analysis.ModeChoiceCoverageControlerListener;
import org.matsim.analysis.linkpaxvolumes.LinkPaxVolumesAnalysisModule;
import org.matsim.analysis.personMoney.PersonMoneyEventsAnalysisModule;
import org.matsim.analysis.pt.stop2stop.PtStop2StopAnalysisModule;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.Scenario;
import org.matsim.api.core.v01.population.Person;
import org.matsim.api.core.v01.population.Population;
import org.matsim.api.core.v01.population.PopulationFactory;
import org.matsim.contrib.bicycle.BicycleConfigGroup;
import org.matsim.contrib.bicycle.Bicycles;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.config.groups.StrategyConfigGroup;
import org.matsim.core.controler.AbstractModule;
import org.matsim.core.controler.Controler;
import org.matsim.core.controler.OutputDirectoryHierarchy;
import org.matsim.core.events.EventsUtils;
import org.matsim.core.population.PopulationUtils;
import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule;
import org.matsim.core.router.AnalysisMainModeIdentifier;
import org.matsim.core.router.MultimodalLinkChooser;
import org.matsim.core.scenario.ScenarioUtils;
import org.matsim.core.scoring.functions.ScoringParametersForPerson;
import org.matsim.examples.ExamplesUtils;
import org.matsim.extensions.pt.fare.intermodalTripFareCompensator.IntermodalTripFareCompensatorsModule;
import org.matsim.extensions.pt.routing.EnhancedRaptorIntermodalAccessEgress;
import org.matsim.extensions.pt.routing.ptRoutingModes.PtIntermodalRoutingModesModule;
import org.matsim.run.IntermodalPtAnalysisModeIdentifier;
import org.matsim.run.NearestLinkChooser;
import org.matsim.run.StrategyWeightFadeout;
import playground.vsp.scoring.IncomeDependentUtilityOfMoneyPersonScoringParameters;
import playground.vsp.simpleParkingCostHandler.ParkingCostConfigGroup;
import playground.vsp.simpleParkingCostHandler.ParkingCostModule;
import org.matsim.testcases.MatsimTestUtils;

public class MigrantBicycleChoiceHandlerTest {

String migrantPopulationPath = "gladbeck-v1.3-10pct.migrants-mapped.xml.gz"; // TODO Adjust path

private void prepareConfig(Config config){}
import java.util.ArrayList;
import java.util.List;

private void prepareScenario(Scenario scenario){}
public class MigrantBicycleChoiceHandlerTest {

private void prepareControler(Controler controler){}
@Rule
public MatsimTestUtils utils = new MatsimTestUtils();

@Test
public void test2(){
public final void runTestMigrantBicycleChoiceHandler() {
String inputPath = String.valueOf(ExamplesUtils.getTestScenarioURL("equil-mixedTraffic"));
Config config = ConfigUtils.loadConfig(inputPath + "config-with-mode-vehicles.xml");
{
config.controler().setLastIteration(3);
config.controler().setOutputDirectory("output/MigrantBicycleTest/");
config.global().setNumberOfThreads(1);
config.qsim().setNumberOfThreads(1);
config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists);
//bike contrib
BicycleConfigGroup bikeConfigGroup = (BicycleConfigGroup)ConfigUtils.addOrGetModule(config, BicycleConfigGroup.class);
bikeConfigGroup.setBicycleMode("bike");
config.changeMode().setModes(new String[]{"car", "pt", "bicycle"});

//Set the replanning strategy for migrants: All migrants will fully reroute their plan
StrategyConfigGroup.StrategySettings migrantStrategySettings = new StrategyConfigGroup.StrategySettings(ConfigUtils.createAvailableStrategyId(config));
migrantStrategySettings.setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ChangeTripMode);
migrantStrategySettings.setSubpopulation("migrant");
migrantStrategySettings.setWeight(1);
config.strategy().addStrategySettings(migrantStrategySettings);
}
Config config = ConfigUtils.loadConfig(inputPath + "config-with-mode-vehicles.xml");
config.controler().setLastIteration(0);
config.controler().setOutputDirectory(utils.getOutputDirectory());
config.global().setNumberOfThreads(1);
config.qsim().setNumberOfThreads(1);
config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists);

Scenario scenario = ScenarioUtils.loadScenario(config);
//Person person = scenario.getPopulation().getPersons().get(Id.createPersonId("10"));
//scenario.getPopulation().getPersons().clear();
//scenario.getPopulation().addPerson(person);
Person migrant = scenario.getPopulation().getPersons().get(Id.createPersonId("1"));
migrant.getAttributes().putAttribute("subpopulation", "migrant");
Person person = scenario.getPopulation().getPersons().get(Id.createPersonId("10"));
person.getAttributes().putAttribute("migrant", "true");

scenario.getPopulation().getPersons().clear();
scenario.getPopulation().addPerson(person);
Controler controler = new Controler(scenario);
{
controler.addOverridingModule(new AbstractModule() {
public void install() {
this.addTravelTimeBinding("ride").to(this.networkTravelTime());
this.addTravelDisutilityFactoryBinding("ride").to(this.carTravelDisutilityFactoryKey());
this.addTravelTimeBinding("bike").to(this.networkTravelTime());
this.addControlerListenerBinding().to(ModeChoiceCoverageControlerListener.class);
this.addControlerListenerBinding().to(StrategyWeightFadeout.class).in(Singleton.class);
Multibinder<StrategyWeightFadeout.Schedule> schedules = Multibinder.newSetBinder(this.binder(), StrategyWeightFadeout.Schedule.class);
schedules.addBinding().toInstance(new StrategyWeightFadeout.Schedule("SubtourModeChoice", "person", 0.75, 0.85));
schedules.addBinding().toInstance(new StrategyWeightFadeout.Schedule("ReRoute", "person", 0.78));
}
});
Bicycles.addAsOverridingModule(controler);
}

MigrantBicycleChoiceHandler choiceHandler = new MigrantBicycleChoiceHandler(scenario.getPopulation());
List<Id<Person>> migrants = new ArrayList<>();
migrants.add(person.getId());

MigrantBicycleChoiceHandler migrantBicycleChoiceHandler = new MigrantBicycleChoiceHandler(migrants);

controler.addOverridingModule(new AbstractModule() {
@Override
public void install() {
addEventHandlerBinding().toInstance(choiceHandler);
// addControlerListenerBinding().toInstance(choiceHandler);
addEventHandlerBinding().toInstance(migrantBicycleChoiceHandler);
addControlerListenerBinding().toInstance(migrantBicycleChoiceHandler);
new PersonMoneyEventsAnalysisModule();
}
});
controler.run();

//Migrant should now have bike as the best plan
controler.run();

System.out.println();
Assert.assertTrue("Score of migrant was not changed! It should be negative but it is:" + person.getSelectedPlan().getScore(), person.getSelectedPlan().getScore() < 0);
}
}
33 changes: 1 addition & 32 deletions src/test/java/org/matsim/run/TestMigrationMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,38 +29,7 @@ public class TestMigrationMapper {

@Test
public final void runTestMigrationMapper() {
String inputPath = String.valueOf(ExamplesUtils.getTestScenarioURL("equil-mixedTraffic"));
Config config = ConfigUtils.loadConfig(inputPath + "config-with-mode-vehicles.xml");
config.controler().setLastIteration(3);
config.controler().setOutputDirectory(utils.getOutputDirectory());
config.global().setNumberOfThreads(1);
config.qsim().setNumberOfThreads(1);
config.controler().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists);
Scenario scenario = ScenarioUtils.loadScenario(config);
Person person = scenario.getPopulation().getPersons().get(Id.createPersonId("10"));
//TODO use migrant mapper class?
//TODO I do
person.getAttributes().putAttribute("migrant", "true");

scenario.getPopulation().getPersons().clear();
scenario.getPopulation().addPerson(person);
Controler controler = new Controler(scenario);

List migrants = new ArrayList<Id<Person>>();
migrants.add(person.getId());

MigrantBicycleChoiceHandler migrantBicycleChoiceHandler = new MigrantBicycleChoiceHandler(migrants);

controler.addOverridingModule(new AbstractModule() {
@Override
public void install() {
addEventHandlerBinding().toInstance(migrantBicycleChoiceHandler);
addControlerListenerBinding().toInstance(migrantBicycleChoiceHandler);
new PersonMoneyEventsAnalysisModule();
}
});

controler.run();
// TODO
}

}

0 comments on commit 3395237

Please sign in to comment.