file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
StaticLoggerBinder.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/slf4j/impl/StaticLoggerBinder.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.slf4j.impl; import org.slf4j.ILoggerFactory; import org.slf4j.impl.WandoraLoggerFactory; import org.slf4j.spi.LoggerFactoryBinder; /** * * @author akivela */ public class StaticLoggerBinder implements LoggerFactoryBinder { /** * The unique instance of this class. */ private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); /** * Return the singleton of this class. * * @return the StaticLoggerBinder singleton */ public static final StaticLoggerBinder getSingleton() { return SINGLETON; } /** * Declare the version of the SLF4J API this implementation is * compiled against. The value of this field is usually modified * with each release. */ // To avoid constant folding by the compiler, // this field must *not* be final public static String REQUESTED_API_VERSION = "1.7.6"; // !final private static final String loggerFactoryClassStr = WandoraLoggerFactory.class.getName(); /** * The ILoggerFactory instance returned by the * {@link #getLoggerFactory} method should always be the same * object. */ private final ILoggerFactory loggerFactory; private StaticLoggerBinder() { loggerFactory = new WandoraLoggerFactory(); } public ILoggerFactory getLoggerFactory() { return loggerFactory; } public String getLoggerFactoryClassStr() { return loggerFactoryClassStr; } }
2,319
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraLoggerFactory.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/slf4j/impl/WandoraLoggerFactory.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.slf4j.impl; import java.util.HashMap; import java.util.Map; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.wandora.application.Wandora; import org.wandora.utils.Options; /** * * @author akivela */ public class WandoraLoggerFactory implements ILoggerFactory { private Map<String, WandoraLoggerAdapter> loggerMap; private Map<String, Integer> loggingLevels = new HashMap<>(); public WandoraLoggerFactory() { loggingLevels = new HashMap<>(); loggerMap = new HashMap<String, WandoraLoggerAdapter>(); initializeLoggerFactory(); } @Override public Logger getLogger(String name) { synchronized (loggerMap) { if (!loggerMap.containsKey(name)) { // System.out.println("Creating logger for '"+name+"' with level "+getLoggingLevel(name)); WandoraLoggerAdapter logger = new WandoraLoggerAdapter(name); logger.setLogLevel(getLoggingLevel(name)); loggerMap.put(name, logger); } return loggerMap.get(name); } } private int getLoggingLevel(String name) { if(name != null) { for(String logRegex : loggingLevels.keySet()) { if(name.matches(logRegex)) { Integer i = loggingLevels.get(logRegex); if(i != null) { return i.intValue(); } else { // System.out.println("Warning, log level is null"); } } } } return WandoraLoggerAdapter.LOG_INFO; } // ------------------------------------------------------------------------- private void initializeLoggerFactory() { Wandora wandora = Wandora.getWandora(); if(wandora != null) { Options options = wandora.getOptions(); if(options != null) { int i = 0; String regex; int level; do { regex = options.get("loggerRules.loggerRule["+i+"].nameRegex"); level = options.getInt("loggerRules.loggerRule["+i+"].logLevel", 9999); if(regex != null && level != 9999) { loggingLevels.put(regex, level); } i++; } while(regex != null && i < 1000); } } } }
3,420
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ScoreCalculatorTest.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/test/java/org/matsim/prepare/opt/ScoreCalculatorTest.java
package org.matsim.prepare.opt; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class ScoreCalculatorTest { @Test public void absChange() { ErrorMetric e = ErrorMetric.abs_error; // some count value int c = 5; assertThat(ScoreCalculator.diffChange(e, c, 3, 5)) .isEqualTo(-2); assertThat(ScoreCalculator.diffChange(e, c, 6, 5)) .isEqualTo(-1); assertThat(ScoreCalculator.diffChange(e, c, 4, 6)) .isEqualTo(0); assertThat(ScoreCalculator.diffChange(e, c, 5, 3)) .isEqualTo(2); assertThat(ScoreCalculator.diffChange(e, c, 10, 15)) .isEqualTo(5); } @Test public void logChange() { ErrorMetric e = ErrorMetric.log_error; assertThat(ScoreCalculator.diffChange(e, 5, 3, 5)) .isEqualTo(-0.10536051565782628); assertThat(ScoreCalculator.diffChange(e, 5, 5, 3)) .isEqualTo(0.10536051565782628); // Does not hold anymore, because of the constant // assertThat(ScoreCalculator.diffChange(e, 10, 5, 20)) // .isEqualTo(0); } }
1,048
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunOpenBerlinScenarioTest.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/test/java/org/matsim/run/RunOpenBerlinScenarioTest.java
package org.matsim.run; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.matsim.application.MATSimApplication; import org.matsim.testcases.MatsimTestUtils; import static org.assertj.core.api.Assertions.assertThat; public class RunOpenBerlinScenarioTest { @RegisterExtension public MatsimTestUtils utils = new MatsimTestUtils(); @Test public void pct1() { int code = MATSimApplication.execute(OpenBerlinScenario.class, "--1pct", "--output", utils.getOutputDirectory(), "--iterations", "2", "--config:simwrapper.defaultDashboards", "disabled" ); assertThat(code).isEqualTo(0); } }
666
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DistanceGroupModeUtilityParametersTest.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/test/java/org/matsim/run/scoring/DistanceGroupModeUtilityParametersTest.java
package org.matsim.run.scoring; import it.unimi.dsi.fastutil.doubles.DoubleList; import org.junit.jupiter.api.Test; import org.matsim.core.scoring.functions.ModeUtilityParameters; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; class DistanceGroupModeUtilityParametersTest { private final ModeUtilityParameters base = new ModeUtilityParameters( 0, -1, 0, 0, 0, 0 ); private static DistanceGroupModeUtilityParameters params(ModeUtilityParameters base, List<Integer> dists, DoubleList utils) { return new DistanceGroupModeUtilityParameters( base, new DistanceGroupModeUtilityParameters.DeltaBuilder(), IndividualPersonScoringParameters.calcDistanceGroups(dists, utils)); } @Test void empty() { DistanceGroupModeUtilityParameters m = params(base, List.of(), DoubleList.of()); // Delta will be 0 for any distance assertThat(m.calcUtilityDistDelta(1000)).isEqualTo(0); assertThat(m.calcUtilityDistDelta(0)).isEqualTo(0); assertThat(m.calcUtilityDistDelta(5000)).isEqualTo(0); } @Test void manyGroups() { List<Integer> dists = List.of(1000, 5000, 10000); DistanceGroupModeUtilityParameters m = params(base, dists, DoubleList.of(-1d, -0.5d, -0.1d)); assertThat(m.calcUtilityDistDelta(0)).isEqualTo(0); assertThat(m.calcUtilityDistDelta(500)).isEqualTo(-0.5); assertThat(m.calcUtilityDistDelta(1000)).isEqualTo(-1); assertThat(m.calcUtilityDistDelta(3000)).isEqualTo(-0.75); assertThat(m.calcUtilityDistDelta(5000)).isEqualTo(-0.5); assertThat(m.calcUtilityDistDelta(10000)).isEqualTo(-0.1d); assertThat(m.calcUtilityDistDelta(20000)).isEqualTo(-0.2d); } @Test void mixedSigns() { List<Integer> dists = List.of(1000, 2000, 3000); DistanceGroupModeUtilityParameters m = params(base, dists, DoubleList.of(-1d, 1d, 0)); assertThat(m.calcUtilityDistDelta(0)).isEqualTo(0); assertThat(m.calcUtilityDistDelta(500)).isEqualTo(-0.5); assertThat(m.calcUtilityDistDelta(1000)).isEqualTo(-1); assertThat(m.calcUtilityDistDelta(1500)).isEqualTo(0); assertThat(m.calcUtilityDistDelta(2000)).isEqualTo(1); assertThat(m.calcUtilityDistDelta(3000)).isEqualTo(0); assertThat(m.calcUtilityDistDelta(5000)).isEqualTo(0); } @Test void oneGroup() { DistanceGroupModeUtilityParameters m = params(base, List.of(1000), DoubleList.of(-1)); assertThat(m.calcUtilityDistDelta(0)).isEqualTo(0); assertThat(m.calcUtilityDistDelta(500)).isEqualTo(-0.5); assertThat(m.calcUtilityDistDelta(1000)).isEqualTo(-1); assertThat(m.calcUtilityDistDelta(2000)).isEqualTo(-2); } }
2,597
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunOpenBerlinCalibration.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/RunOpenBerlinCalibration.java
package org.matsim.prepare; import com.google.inject.Inject; import com.google.inject.TypeLiteral; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.*; import org.matsim.application.MATSimAppCommand; import org.matsim.application.MATSimApplication; import org.matsim.application.options.SampleOptions; import org.matsim.application.prepare.CreateLandUseShp; import org.matsim.application.prepare.freight.tripExtraction.ExtractRelevantFreightTrips; import org.matsim.application.prepare.network.CleanNetwork; import org.matsim.application.prepare.network.CreateNetworkFromSumo; import org.matsim.application.prepare.population.*; import org.matsim.application.prepare.pt.CreateTransitScheduleFromGtfs; import org.matsim.contrib.cadyts.car.CadytsCarModule; import org.matsim.contrib.cadyts.car.CadytsContext; import org.matsim.contrib.cadyts.general.CadytsScoring; import org.matsim.contrib.locationchoice.frozenepsilons.FrozenTastes; import org.matsim.contrib.locationchoice.frozenepsilons.FrozenTastesConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.ReplanningConfigGroup; import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.VspExperimentalConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.population.PopulationUtils; import org.matsim.core.replanning.choosers.ForceInnovationStrategyChooser; import org.matsim.core.replanning.choosers.StrategyChooser; import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule; import org.matsim.core.router.DefaultAnalysisMainModeIdentifier; import org.matsim.core.router.MainModeIdentifier; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scoring.ScoringFunction; import org.matsim.core.scoring.ScoringFunctionFactory; import org.matsim.core.scoring.SumScoringFunction; import org.matsim.core.scoring.functions.*; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.prepare.choices.ComputePlanChoices; import org.matsim.prepare.choices.ComputeTripChoices; import org.matsim.prepare.counts.CreateCountsFromGeoPortalBerlin; import org.matsim.prepare.counts.CreateCountsFromVMZ; import org.matsim.prepare.counts.CreateCountsFromVMZOld; import org.matsim.prepare.download.DownloadCommuterStatistic; import org.matsim.prepare.network.FixNetworkV5; import org.matsim.prepare.network.FreeSpeedOptimizer; import org.matsim.prepare.network.PrepareNetworkParams; import org.matsim.prepare.network.SampleNetwork; import org.matsim.prepare.opt.RunCountOptimization; import org.matsim.prepare.opt.SelectPlansFromIndex; import org.matsim.prepare.population.*; import org.matsim.run.Activities; import org.matsim.run.OpenBerlinScenario; import org.matsim.run.scoring.AdvancedScoringModule; import org.matsim.simwrapper.SimWrapperConfigGroup; import org.matsim.simwrapper.SimWrapperModule; import org.matsim.smallScaleCommercialTrafficGeneration.GenerateSmallScaleCommercialTrafficDemand; import picocli.CommandLine; import java.math.BigDecimal; import java.math.RoundingMode; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; /** * This scenario class is used for run a MATSim scenario in various stages of the calibration process. */ @CommandLine.Command(header = ":: Open Berlin Calibration ::", version = OpenBerlinScenario.VERSION, mixinStandardHelpOptions = true) @MATSimApplication.Prepare({ CreateLandUseShp.class, CreateBerlinPopulation.class, CreateBrandenburgPopulation.class, MergePopulations.class, LookupRegioStaR.class, ExtractFacilityShp.class, DownSamplePopulation.class, DownloadCommuterStatistic.class, RunActitopp.class, CreateNetworkFromSumo.class, CreateTransitScheduleFromGtfs.class, CleanNetwork.class, SampleNetwork.class, CreateMATSimFacilities.class, InitLocationChoice.class, FilterRelevantAgents.class, CreateCountsFromGeoPortalBerlin.class, CreateCountsFromVMZOld.class, CreateCountsFromVMZ.class, ReprojectNetwork.class, RunActivitySampling.class, MergePlans.class, SplitActivityTypesDuration.class, CleanPopulation.class, CleanAttributes.class, GenerateSmallScaleCommercialTrafficDemand.class, RunCountOptimization.class, SelectPlansFromIndex.class, FixNetworkV5.class, ExtractRelevantFreightTrips.class, CheckCarAvailability.class, FixSubtourModes.class, ComputeTripChoices.class, ComputePlanChoices.class, PrepareNetworkParams.class, FreeSpeedOptimizer.class, SetCarAvailabilityByAge.class }) public class RunOpenBerlinCalibration extends MATSimApplication { /** * Scaling factor if all persons use car (~20% share). */ public static final int CAR_FACTOR = 5; /** * Flexible activities, which need to be known for location choice and during generation. * A day can not end on a flexible activity. */ public static final Set<String> FLEXIBLE_ACTS = Set.of("shop_daily", "shop_other", "leisure", "dining"); private static final Logger log = LogManager.getLogger(RunOpenBerlinCalibration.class); @CommandLine.Mixin private final SampleOptions sample = new SampleOptions(25, 10, 3, 1); @CommandLine.Option(names = "--mode", description = "Calibration mode that should be run.") private CalibrationMode mode; @CommandLine.Option(names = "--weight", description = "Strategy weight.", defaultValue = "1") private double weight; @CommandLine.Option(names = "--population", description = "Path to population.") private Path populationPath; @CommandLine.Option(names = "--all-car", description = "All plans will use car mode. Capacity is adjusted automatically by " + CAR_FACTOR, defaultValue = "false") private boolean allCar; @CommandLine.Option(names = "--scale-factor", description = "Scale factor for capacity to avoid congestions.", defaultValue = "1.5") private double scaleFactor; @CommandLine.Option(names = "--plan-index", description = "Only use one plan with specified index") private Integer planIndex; public RunOpenBerlinCalibration() { super("input/v6.1/berlin-v6.1.config.xml"); } /** * Round to two digits. */ public static double roundNumber(double x) { return BigDecimal.valueOf(x).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); } /** * Round coordinates to sufficient precision. */ public static Coord roundCoord(Coord coord) { return new Coord(roundNumber(coord.getX()), roundNumber(coord.getY())); } public static void main(String[] args) { MATSimApplication.run(RunOpenBerlinCalibration.class, args); } @Override protected Config prepareConfig(Config config) { if (populationPath == null) { throw new IllegalArgumentException("Population path is required [--population]"); } config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); log.info("Running {} calibration {}", mode, populationPath); config.plans().setInputFile(populationPath.toString()); config.controller().setRunId(mode.toString()); config.scoring().setWriteExperiencedPlans(true); // Location choice does not work with the split types Activities.addScoringParams(config, mode != CalibrationMode.locationChoice); SimWrapperConfigGroup sw = ConfigUtils.addOrGetModule(config, SimWrapperConfigGroup.class); if (sample.isSet()) { double sampleSize = sample.getSample(); double countScale = allCar ? CAR_FACTOR : 1; config.qsim().setFlowCapFactor(sampleSize * countScale); config.qsim().setStorageCapFactor(sampleSize * countScale); // Counts can be scaled with sample size config.counts().setCountsScaleFactor(sampleSize * countScale); config.plans().setInputFile(sample.adjustName(config.plans().getInputFile())); sw.sampleSize = sampleSize * countScale; } // Routes are not relaxed yet, and there should not be too heavy congestion // factors are increased to accommodate for more than usual traffic config.qsim().setFlowCapFactor(config.qsim().getFlowCapFactor() * scaleFactor); config.qsim().setStorageCapFactor(config.qsim().getStorageCapFactor() * scaleFactor); log.info("Running with flow and storage capacity: {} / {}", config.qsim().getFlowCapFactor(), config.qsim().getStorageCapFactor()); if (allCar) config.transit().setUseTransit(false); // Required for all calibration strategies for (String subpopulation : List.of("person", "commercialPersonTraffic", "commercialPersonTraffic_service", "goodsTraffic")) { config.replanning().addStrategySettings( new ReplanningConfigGroup.StrategySettings() .setStrategyName(DefaultPlanStrategiesModule.DefaultSelector.ChangeExpBeta) .setWeight(1.0) .setSubpopulation(subpopulation) ); } if (mode == null) throw new IllegalArgumentException("Calibration mode [--mode} not set!"); if (mode == CalibrationMode.locationChoice) { config.replanning().addStrategySettings(new ReplanningConfigGroup.StrategySettings() .setStrategyName(FrozenTastes.LOCATION_CHOICE_PLAN_STRATEGY) .setWeight(weight) .setSubpopulation("person") ); config.replanning().addStrategySettings(new ReplanningConfigGroup.StrategySettings() .setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute) .setWeight(weight / 5) .setSubpopulation("person") ); // Overwrite these to fix scoring warnings config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("work").setTypicalDuration(8 * 3600)); config.scoring().addActivityParams(new ScoringConfigGroup.ActivityParams("pt interaction").setTypicalDuration(30)); config.vspExperimental().setAbleToOverwritePtInteractionParams(true); config.replanning().setFractionOfIterationsToDisableInnovation(0.8); config.scoring().setFractionOfIterationsToStartScoreMSA(0.8); FrozenTastesConfigGroup dccg = ConfigUtils.addOrGetModule(config, FrozenTastesConfigGroup.class); dccg.setEpsilonScaleFactors(FLEXIBLE_ACTS.stream().map(s -> "1.0").collect(Collectors.joining(","))); dccg.setAlgorithm(FrozenTastesConfigGroup.Algotype.bestResponse); dccg.setFlexibleTypes(String.join(",", FLEXIBLE_ACTS)); dccg.setTravelTimeApproximationLevel(FrozenTastesConfigGroup.ApproximationLevel.localRouting); dccg.setRandomSeed(2); dccg.setDestinationSamplePercent(25); } else if (mode == CalibrationMode.cadyts) { // Re-route for all populations for (String subpopulation : List.of("person", "commercialPersonTraffic", "commercialPersonTraffic_service", "goodsTraffic")) { config.replanning().addStrategySettings(new ReplanningConfigGroup.StrategySettings() .setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute) .setWeight(weight) .setSubpopulation(subpopulation) ); } config.controller().setRunId("cadyts"); config.controller().setOutputDirectory("./output/cadyts-" + scaleFactor); config.scoring().setFractionOfIterationsToStartScoreMSA(0.75); config.replanning().setFractionOfIterationsToDisableInnovation(0.75); // Need to store more plans because of plan types config.replanning().setMaxAgentPlanMemorySize(8); config.vspExperimental().setVspDefaultsCheckingLevel(VspExperimentalConfigGroup.VspDefaultsCheckingLevel.ignore); } else if (mode == CalibrationMode.routeChoice) { // Re-route for all populations for (String subpopulation : List.of("person", "commercialPersonTraffic", "commercialPersonTraffic_service", "goodsTraffic")) { config.replanning().addStrategySettings(new ReplanningConfigGroup.StrategySettings() .setStrategyName(DefaultPlanStrategiesModule.DefaultStrategy.ReRoute) .setWeight(weight) .setSubpopulation(subpopulation) ); } } else if (mode == CalibrationMode.eval) { iterations = 0; config.controller().setLastIteration(0); } else throw new IllegalStateException("Mode not implemented:" + mode); return config; } @Override protected void prepareScenario(Scenario scenario) { if (mode == CalibrationMode.cadyts) // each initial plan needs a separate type, so it won't be removed for (Person person : scenario.getPopulation().getPersons().values()) { for (int i = 0; i < person.getPlans().size(); i++) { person.getPlans().get(i).setType(String.valueOf(i)); } } if (planIndex != null) { log.info("Using plan with index {}", planIndex); for (Person person : scenario.getPopulation().getPersons().values()) { SelectPlansFromIndex.selectPlanWithIndex(person, planIndex); } } if (allCar) { log.info("Converting all agents to car plans."); MainModeIdentifier mmi = new DefaultAnalysisMainModeIdentifier(); for (Person person : scenario.getPopulation().getPersons().values()) { for (Plan plan : person.getPlans()) { final List<PlanElement> planElements = plan.getPlanElements(); final List<TripStructureUtils.Trip> trips = TripStructureUtils.getTrips(plan); for (TripStructureUtils.Trip trip : trips) { final List<PlanElement> fullTrip = planElements.subList( planElements.indexOf(trip.getOriginActivity()) + 1, planElements.indexOf(trip.getDestinationActivity())); String mode = mmi.identifyMainMode(fullTrip); // Already car, nothing to do if (Objects.equals(mode, TransportMode.car) || Objects.equals(mode, TransportMode.truck) || Objects.equals(mode, "freight")) continue; double dist = CoordUtils.calcEuclideanDistance(getCoord(scenario, trip.getOriginActivity()), getCoord(scenario, trip.getDestinationActivity())); // short bike and walk trips are not changed if (dist <= 350 && (Objects.equals(mode, TransportMode.walk) || Objects.equals(mode, TransportMode.bike))) continue; // rest of the trips is set to walk if below threshold, car otherwise String desiredMode = dist <= 350 ? TransportMode.walk : TransportMode.car; if (!Objects.equals(mode, desiredMode)) { fullTrip.clear(); Leg leg = PopulationUtils.createLeg(desiredMode); TripStructureUtils.setRoutingMode(leg, desiredMode); fullTrip.add(leg); } } } } } } private Coord getCoord(Scenario scenario, Activity act) { if (act.getCoord() != null) return act.getCoord(); if (act.getFacilityId() != null) return scenario.getActivityFacilities().getFacilities().get(act.getFacilityId()).getCoord(); return scenario.getNetwork().getLinks().get(act.getLinkId()).getCoord(); } @Override protected void prepareControler(Controler controler) { if (mode == CalibrationMode.locationChoice) { FrozenTastes.configure(controler); controler.addOverridingModule(new AbstractModule() { @Override public void install() { binder().bind(new TypeLiteral<StrategyChooser<Plan, Person>>() { }).toInstance(new ForceInnovationStrategyChooser<>(5, ForceInnovationStrategyChooser.Permute.no)); } }); } else if (mode == CalibrationMode.cadyts) { controler.addOverridingModule(new CadytsCarModule()); controler.setScoringFunctionFactory(new ScoringFunctionFactory() { @Inject ScoringParametersForPerson parameters; @Inject private CadytsContext cadytsContext; @Override public ScoringFunction createNewScoringFunction(Person person) { SumScoringFunction sumScoringFunction = new SumScoringFunction(); Config config = controler.getConfig(); final ScoringParameters params = parameters.getScoringParameters(person); sumScoringFunction.addScoringFunction(new CharyparNagelLegScoring(params, controler.getScenario().getNetwork())); sumScoringFunction.addScoringFunction(new CharyparNagelActivityScoring(params)); sumScoringFunction.addScoringFunction(new CharyparNagelAgentStuckScoring(params)); final CadytsScoring<Link> scoringFunction = new CadytsScoring<>(person.getSelectedPlan(), config, cadytsContext); scoringFunction.setWeightOfCadytsCorrection(30 * config.scoring().getBrainExpBeta()); sumScoringFunction.addScoringFunction(scoringFunction); return sumScoringFunction; } }); } controler.addOverridingModule(new AbstractModule() { @Override public void install() { addControlerListenerBinding().to(ExtendExperiencedPlansListener.class); } }); controler.addOverridingModule(new OpenBerlinScenario.TravelTimeBinding()); controler.addOverridingModule(new AdvancedScoringModule()); controler.addOverridingModule(new SimWrapperModule()); } @Override protected List<MATSimAppCommand> preparePostProcessing(Path outputFolder, String runId) { return List.of( new CleanPopulation().withArgs( "--plans", outputFolder.resolve(runId + ".output_plans.xml.gz").toString(), "--output", outputFolder.resolve(runId + ".output_selected_plans.xml.gz").toString(), "--remove-unselected-plans" ) ); } /** * Different calibration stages. */ public enum CalibrationMode { eval, locationChoice, cadyts, routeChoice } }
17,341
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateMATSimFacilities.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/CreateMATSimFacilities.java
package org.matsim.prepare; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.geom.TopologyException; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ShpOptions; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.facilities.*; import org.opengis.feature.simple.SimpleFeature; import picocli.CommandLine; import java.nio.file.Path; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; @CommandLine.Command( name = "facilities", description = "Creates MATSim facilities from shape-file and network" ) public class CreateMATSimFacilities implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(CreateMATSimFacilities.class); /** * Filter link types that don't have a facility associated. */ public static final Set<String> IGNORED_LINK_TYPES = Set.of("motorway", "trunk", "motorway_link", "trunk_link", "secondary_link", "primary_link"); @CommandLine.Option(names = "--network", required = true, description = "Path to car network") private Path network; @CommandLine.Option(names = "--output", required = true, description = "Path to output facility file") private Path output; @CommandLine.Mixin private ShpOptions shp; public static void main(String[] args) { new CreateMATSimFacilities().execute(args); } @Override public Integer call() throws Exception { if (shp.getShapeFile() == null) { log.error("Shp file with facilities is required."); return 2; } Network completeNetwork = NetworkUtils.readNetwork(this.network.toString()); TransportModeNetworkFilter filter = new TransportModeNetworkFilter(completeNetwork); Network carOnlyNetwork = NetworkUtils.createNetwork(); filter.filter(carOnlyNetwork, Set.of(TransportMode.car)); List<SimpleFeature> fts = shp.readFeatures(); Map<Id<Link>, Holder> data = new ConcurrentHashMap<>(); fts.parallelStream().forEach(ft -> processFeature(ft, carOnlyNetwork, data)); ActivityFacilities facilities = FacilitiesUtils.createActivityFacilities(); ActivityFacilitiesFactory f = facilities.getFactory(); for (Map.Entry<Id<Link>, Holder> e : data.entrySet()) { Holder h = e.getValue(); Id<ActivityFacility> id = Id.create(String.join("_", h.ids), ActivityFacility.class); // Create mean coordinate OptionalDouble x = h.coords.stream().mapToDouble(Coord::getX).average(); OptionalDouble y = h.coords.stream().mapToDouble(Coord::getY).average(); if (x.isEmpty() || y.isEmpty()) { log.warn("Empty coordinate (Should never happen)"); continue; } ActivityFacility facility = f.createActivityFacility(id, CoordUtils.round(new Coord(x.getAsDouble(), y.getAsDouble()))); for (String act : h.activities) { facility.addActivityOption(f.createActivityOption(act)); } facilities.addActivityFacility(facility); } log.info("Created {} facilities, writing to {}", facilities.getFacilities().size(), output); FacilitiesWriter writer = new FacilitiesWriter(facilities); writer.write(output.toString()); return 0; } /** * Sample points and choose link with the nearest points. Aggregate everything so there is at most one facility per link. */ private void processFeature(SimpleFeature ft, Network network, Map<Id<Link>, Holder> data) { // Actual id is the last part String[] id = ft.getID().split("\\."); // Pairs of coords and corresponding links List<Coord> coords = samplePoints((MultiPolygon) ft.getDefaultGeometry(), 23); List<Id<Link>> links = coords.stream().map(coord -> NetworkUtils.getNearestLinkExactly(network, coord).getId()).toList(); Map<Id<Link>, Long> map = links.stream() .filter(l -> !IGNORED_LINK_TYPES.contains(NetworkUtils.getType(network.getLinks().get(l)))) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); // Everything could be filtered and map empty if (map.isEmpty()) return; List<Map.Entry<Id<Link>, Long>> counts = map.entrySet().stream().sorted(Map.Entry.comparingByValue()) .toList(); // The "main" link of the facility Id<Link> link = counts.get(counts.size() - 1).getKey(); Holder holder = data.computeIfAbsent(link, k -> new Holder(ConcurrentHashMap.newKeySet(), ConcurrentHashMap.newKeySet(), Collections.synchronizedList(new ArrayList<>()))); holder.ids.add(id[id.length - 1]); holder.activities.addAll(activities(ft)); // Search for the original drawn coordinate of the associated link for (int i = 0; i < links.size(); i++) { if (links.get(i).equals(link)) { holder.coords.add(coords.get(i)); break; } } } /** * Sample coordinates within polygon. */ private List<Coord> samplePoints(MultiPolygon geometry, int n) { SplittableRandom rnd = new SplittableRandom(); List<Coord> result = new ArrayList<>(); Envelope bbox = geometry.getEnvelopeInternal(); int max = n * 10; for (int i = 0; i < max && result.size() < n; i++) { Coord coord = CoordUtils.round(new Coord( bbox.getMinX() + (bbox.getMaxX() - bbox.getMinX()) * rnd.nextDouble(), bbox.getMinY() + (bbox.getMaxY() - bbox.getMinY()) * rnd.nextDouble() )); try { if (geometry.contains(MGC.coord2Point(coord))) { result.add(coord); } } catch (TopologyException e) { if (geometry.getBoundary().contains(MGC.coord2Point(coord))) { result.add(coord); } } } if (result.isEmpty()) result.add(MGC.point2Coord(geometry.getCentroid())); return result; } private Set<String> activities(SimpleFeature ft) { Set<String> act = new HashSet<>(); if (Boolean.TRUE == ft.getAttribute("work")) { act.add("work"); act.add("work_business"); } if (Boolean.TRUE == ft.getAttribute("shop")) { act.add("shop_other"); } if (Boolean.TRUE == ft.getAttribute("shop_daily")) { act.add("shop_other"); act.add("shop_daily"); } if (Boolean.TRUE == ft.getAttribute("leisure")) act.add("leisure"); if (Boolean.TRUE == ft.getAttribute("dining")) act.add("dining"); if (Boolean.TRUE == ft.getAttribute("edu_higher")) act.add("edu_higher"); if (Boolean.TRUE == ft.getAttribute("edu_prim")) { act.add("edu_primary"); act.add("edu_secondary"); } if (Boolean.TRUE == ft.getAttribute("edu_kiga")) act.add("edu_kiga"); if (Boolean.TRUE == ft.getAttribute("edu_other")) act.add("edu_other"); if (Boolean.TRUE == ft.getAttribute("p_business") || Boolean.TRUE == ft.getAttribute("medical") || Boolean.TRUE == ft.getAttribute("religious")) { act.add("personal_business"); act.add("work_business"); } return act; } /** * Temporary data holder for facilities. */ private record Holder(Set<String> ids, Set<String> activities, List<Coord> coords) { } }
7,337
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ReprojectNetwork.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/ReprojectNetwork.java
package org.matsim.prepare; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Node; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CrsOptions; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.NetworkUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.pt.transitSchedule.api.TransitScheduleWriter; import picocli.CommandLine; import java.nio.file.Path; import java.util.HashSet; import java.util.Map; import java.util.Set; @CommandLine.Command(name = "reproject-network", description = "Change the CRS of a network") public class ReprojectNetwork implements MATSimAppCommand { @CommandLine.Option(names = "--input", description = "Path to input network", required = true) private Path input; @CommandLine.Option(names = "--transit-schedule", description = "Path to input transit schedule", required = true) private Path transitSchedule; @CommandLine.Option(names = "--output", description = "Desired output path", required = true) private Path output; @CommandLine.Option(names = "--mode", description = "Remap existing modes in the network", required = false, split = ",") private Map<String, String> remapModes; @CommandLine.Option(names = "--output-transit", description = "Desired output path", required = true) private Path outputTransit; @CommandLine.Mixin private CrsOptions crs; public static void main(String[] args) { new ReprojectNetwork().execute(args); } @Override public Integer call() throws Exception { Config config = ConfigUtils.createConfig(); config.global().setCoordinateSystem(crs.getTargetCRS()); config.network().setInputFile(input.toString()); config.network().setInputCRS(crs.getInputCRS()); config.transit().setInputScheduleCRS(crs.getInputCRS()); config.transit().setTransitScheduleFile(transitSchedule.toString()); // Scenario loader does the reprojection for the network Scenario scenario = ScenarioUtils.loadScenario(config); for (Node node : scenario.getNetwork().getNodes().values()) { node.setCoord(CoordUtils.round(node.getCoord())); } if (!remapModes.isEmpty()) { for (Link link : scenario.getNetwork().getLinks().values()) { Set<String> modes = new HashSet<>(link.getAllowedModes()); // Only add mode without removing remapModes.forEach((oldMode, newMode) -> { if (modes.contains(oldMode)) { modes.add(newMode); } }); link.setAllowedModes(modes); } } NetworkUtils.writeNetwork(scenario.getNetwork(), output.toString()); TransitScheduleWriter writer = new TransitScheduleWriter(scenario.getTransitSchedule()); writer.writeFile(outputTransit.toString()); return 0; } }
2,868
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ExtractFacilityShp.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/ExtractFacilityShp.java
package org.matsim.prepare; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.databind.ObjectMapper; import com.slimjars.dist.gnu.trove.iterator.TLongObjectIterator; import de.topobyte.osm4j.core.dataset.InMemoryMapDataSet; import de.topobyte.osm4j.core.dataset.MapDataSetLoader; import de.topobyte.osm4j.core.model.iface.*; import de.topobyte.osm4j.core.resolve.EntityNotFoundException; import de.topobyte.osm4j.geometry.GeometryBuilder; import de.topobyte.osm4j.pbf.seq.PbfIterator; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntMap; import me.tongfei.progressbar.ProgressBar; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.geotools.data.FileDataStoreFactorySpi; import org.geotools.data.collection.ListFeatureCollection; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.data.shapefile.ShapefileDataStoreFactory; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.geometry.jts.JTS; import org.geotools.referencing.CRS; import org.locationtech.jts.geom.*; import org.locationtech.jts.index.strtree.STRtree; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CrsOptions; import org.matsim.run.OpenBerlinScenario; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CRSAuthorityFactory; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import picocli.CommandLine; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; @CommandLine.Command( name = "facility-shp", description = "Generate facility shape file from OSM data." ) public class ExtractFacilityShp implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(ExtractFacilityShp.class); private static final double POI_BUFFER = 6; /** * Structures of this size are completely ignored. */ private static final double MAX_AREA = 50_000_000; /** * Structures larger than this will not be assigned smaller scale types, but remain independently. * Usually large areas such as parks, campus, etc. */ private static final double MAX_ASSIGN = 50_000; private final GeometryBuilder geometryBuilder = new GeometryBuilder(); @CommandLine.Option(names = "--input", description = "Path to input .pbf file", required = true) private Path pbf; @CommandLine.Option(names = "--output", description = "Path to output shape file", required = true) private Path output; @CommandLine.Option(names = "--activity-mapping", description = "Path to activity napping json", required = true) private Path mappingPath; @CommandLine.Option(names = "--exclude", description = "Exclude these activities types from the output", split = ",", defaultValue = "") private Set<String> exclude; @CommandLine.Mixin private CrsOptions crs = new CrsOptions("EPSG:4326", OpenBerlinScenario.CRS); /** * Maps types to feature index. */ private Object2IntMap<String> types; private ActivityMapping config; private List<Feature> pois; private List<Feature> landuse; private List<Feature> entities; private MathTransform transform; private InMemoryMapDataSet data; private int ignored; public static void main(String[] args) { new ExtractFacilityShp().execute(args); } @Override public Integer call() throws Exception { PbfIterator reader = new PbfIterator(Files.newInputStream(pbf), true); config = new ObjectMapper().readerFor(ActivityMapping.class).readValue(mappingPath.toFile()); CRSAuthorityFactory cFactory = CRS.getAuthorityFactory(true); transform = CRS.findMathTransform(cFactory.createCoordinateReferenceSystem(crs.getInputCRS()), CRS.decode(crs.getTargetCRS()), true); log.info("Configured tags: {}", config.getTypes()); types = new Object2IntLinkedOpenHashMap<>(); config.types.values().stream() .flatMap(c -> c.values.values().stream()) .flatMap(Collection::stream) .filter(t -> !exclude.contains(t)) .distinct() .sorted() .forEach(e -> types.put(e, types.size())); log.info("Configured activity types: {}", types.keySet()); if (types.keySet().stream().anyMatch(t -> t.length() > 10)) { log.error("Activity names max length is 10, due to shp format limitation."); return 2; } // Collect all geometries first pois = new ArrayList<>(); entities = new ArrayList<>(); landuse = new ArrayList<>(); data = MapDataSetLoader.read(reader, true, true, true); log.info("Finished loading pbf file."); TLongObjectIterator<OsmNode> it = data.getNodes().iterator(); while (it.hasNext()) { it.advance(); process(it.value()); } log.info("Collected {} POIs", pois.size()); TLongObjectIterator<OsmWay> it2 = data.getWays().iterator(); while (it2.hasNext()) { it2.advance(); process(it2.value()); } TLongObjectIterator<OsmRelation> it3 = data.getRelations().iterator(); while (it3.hasNext()) { it3.advance(); process(it3.value()); } log.info("Collected {} landuse shapes", landuse.size()); log.info("Collected {} other entities", entities.size()); if (ignored > 0) log.warn("Ignored {} invalid geometries", ignored); STRtree index = new STRtree(); for (Feature entity : entities) { index.insert(entity.geometry.getBoundary().getEnvelopeInternal(), entity); } index.build(); processIntersection(landuse, index); log.info("Remaining landuse shapes after assignment: {} ", landuse.size()); processIntersection(pois, index); log.info("Remaining POI after assignment: {}", pois.size()); FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory(); ShapefileDataStore ds = (ShapefileDataStore) factory.createNewDataStore(Map.of("url", output.toFile().toURI().toURL())); SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder(); typeBuilder.setName("schema"); typeBuilder.setCRS(CRS.decode(crs.getTargetCRS())); typeBuilder.add("the_geom", MultiPolygon.class); for (String t : types.keySet()) { typeBuilder.add(t, Boolean.class); } SimpleFeatureType featureType = typeBuilder.buildFeatureType(); ds.createSchema(featureType); SimpleFeatureStore source = (SimpleFeatureStore) ds.getFeatureSource(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); ListFeatureCollection collection = new ListFeatureCollection(featureType); // Transaction transaction = new DefaultTransaction("create"); // source.setTransaction(transaction); addFeatures(entities, featureBuilder, collection); addFeatures(landuse, featureBuilder, collection); addFeatures(pois, featureBuilder, collection); source.addFeatures(collection); // transaction.commit(); log.info("Wrote {} features", collection.size()); // transaction.close(); ds.dispose(); return 0; } /** * Tags buildings within that intersections with geometries from list. Used geometries are removed from the list. */ private void processIntersection(List<Feature> list, STRtree index) { Iterator<Feature> it = ProgressBar.wrap(list.iterator(), "Assigning features"); while (it.hasNext()) { Feature ft = it.next(); List<Feature> query = index.query(ft.geometry.getBoundary().getEnvelopeInternal()); boolean used = false; for (Feature other : query) { // Assign other features to the buildings try { if (ft.geometry.intersects(other.geometry) && other.geometry.getArea() < MAX_ASSIGN) { other.assign(ft); used = true; } } catch (TopologyException e) { // some geometries are not well defined if (ft.geometry.getBoundary().intersects(other.geometry.getBoundary()) && other.geometry.getArea() < MAX_ASSIGN) { other.assign(ft); used = true; } } } if (used) it.remove(); } } private void addFeatures(List<Feature> fts, SimpleFeatureBuilder featureBuilder, ListFeatureCollection collection) { for (Feature ft : ProgressBar.wrap(fts, "Creating features")) { // Relations are ignored at this point if (!ft.bits.isEmpty()) collection.add(ft.createFeature(featureBuilder)); } } /** * Stores entities and geometries as necessary. */ private void process(OsmEntity entity) { boolean filtered = true; int n = entity.getNumberOfTags(); for (int i = 0; i < n; i++) { OsmTag tag = entity.getTag(i); // Buildings are always kept if (tag.getKey().equals("building")) { filtered = false; break; } MappingConfig c = config.types.get(tag.getKey()); if (c != null) { if (c.values.containsKey("*") || c.values.containsKey(tag.getValue())) { filtered = false; break; } } } if (filtered) return; if (entity instanceof OsmNode node) { Point p = geometryBuilder.build(node); MultiPolygon geometry; try { Polygon polygon = (Polygon) JTS.transform(p, transform).buffer(POI_BUFFER); geometry = geometryBuilder.getGeometryFactory().createMultiPolygon(new Polygon[]{polygon}); } catch (TransformException e) { ignored++; return; } pois.add(new Feature(entity, types.size(), geometry)); } else { boolean landuse = false; for (int i = 0; i < n; i++) { if (entity.getTag(i).getKey().equals("landuse")) { landuse = true; break; } } MultiPolygon geometry; try { geometry = createPolygon(entity); if (geometry == null) { ignored++; return; } geometry = (MultiPolygon) JTS.transform(geometry, transform); } catch (TransformException e) { // Will be ignored geometry = null; } if (geometry == null) { ignored++; return; } Feature ft = new Feature(entity, types.size(), geometry); if (landuse) { this.landuse.add(ft); } else { // some non landuse shapes might be too large if (ft.geometry.getArea() < MAX_AREA) entities.add(ft); } } } private MultiPolygon createPolygon(OsmEntity entity) { Geometry geom = null; try { if (entity instanceof OsmWay) { geom = geometryBuilder.build((OsmWay) entity, data); } else if (entity instanceof OsmRelation) { geom = geometryBuilder.build((OsmRelation) entity, data); } } catch (EntityNotFoundException e) { return null; } if (geom == null) throw new IllegalStateException("Unrecognized type."); if (geom instanceof LinearRing lr) { Polygon polygon = geometryBuilder.getGeometryFactory().createPolygon(lr); return geometryBuilder.getGeometryFactory().createMultiPolygon(new Polygon[]{polygon}); } else if (geom instanceof MultiPolygon p) { return p; } return null; } private static final class ActivityMapping { private final Map<String, MappingConfig> types = new HashMap<>(); public Set<String> getTypes() { return types.keySet(); } @JsonAnyGetter public MappingConfig getTag(String type) { return types.get(type); } @JsonAnySetter private void setTag(String type, MappingConfig config) { types.put(type, config); } } /** * Helper class to define data structure for mapping. */ public static final class MappingConfig { private final Map<String, Set<String>> values = new HashMap<>(); @JsonAnyGetter public Set<String> getActivities(String value) { return values.get(value); } @JsonAnySetter private void setActivities(String value, Set<String> activities) { values.put(value, activities); } } /** * Features for one facility, stored as bit set. */ private final class Feature { private final OsmEntity entity; private final BitSet bits; private final MultiPolygon geometry; Feature(OsmEntity entity, int n, MultiPolygon geometry) { this.entity = entity; this.bits = new BitSet(n); this.bits.clear(); this.geometry = geometry; parse(entity); } /** * Parse tags into features. Can also be from different entity. */ private void parse(OsmEntity entity) { for (int i = 0; i < entity.getNumberOfTags(); i++) { OsmTag tag = entity.getTag(i); MappingConfig conf = config.getTag(tag.getKey()); if (conf == null) continue; if (conf.values.containsKey("*")) { set(conf.values.get("*")); } if (conf.values.containsKey(tag.getValue())) { set(conf.values.get(tag.getValue())); } } } private void set(Set<String> acts) { for (String act : acts) { bits.set(types.getInt(act), true); } } void assign(Feature other) { for (int i = 0; i < types.size(); i++) { if (other.bits.get(i)) this.bits.set(i); } } public SimpleFeature createFeature(SimpleFeatureBuilder builder) { builder.add(geometry); for (int i = 0; i < types.size(); i++) { builder.add(bits.get(i)); } return builder.buildFeature(null); } } }
13,068
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
MergePlans.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/MergePlans.java
package org.matsim.prepare; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.core.population.PopulationUtils; import picocli.CommandLine; import java.nio.file.Path; import java.util.List; import java.util.Objects; @CommandLine.Command( name = "merge-plans", description = "Merge selected plans of the same person into one population." ) public class MergePlans implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(MergePlans.class); @CommandLine.Parameters(arity = "1..*", description = "Path to input populations") private List<Path> inputs; @CommandLine.Option(names = "--output", description = "Path to output population", required = true) private Path output; public static void main(String[] args) { new MergePlans().execute(args); } @Override public Integer call() throws Exception { Population population = PopulationUtils.readPopulation(inputs.get(0).toString()); for (Person person : population.getPersons().values()) { Plan selected = person.getSelectedPlan(); List<? extends Plan> toRemove = person.getPlans().stream() .filter(plan -> !Objects.equals(plan, selected)) .toList(); // Need intermediate list to avoid concurrent modification toRemove.forEach(person::removePlan); } for (int i = 1; i < inputs.size(); i++) { String filename = inputs.get(i).toString(); log.info("Reading {}", filename); Population pop = PopulationUtils.readPopulation(filename); for (Person p : pop.getPersons().values()) { Person destPerson = population.getPersons().get(p.getId()); if (destPerson == null) { log.warn("Person {} not present in all populations.", p.getId()); continue; } destPerson.addPlan(p.getSelectedPlan()); } } PopulationUtils.writePopulation(population, output.toString()); return 0; } }
2,098
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ExtendExperiencedPlansListener.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/ExtendExperiencedPlansListener.java
package org.matsim.prepare; import jakarta.inject.Inject; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.core.controler.events.ScoringEvent; import org.matsim.core.controler.listener.ScoringListener; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scoring.ExperiencedPlansService; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.Vehicles; import java.util.Map; /** * This class attached information to the experienced plans needed for calibration. */ class ExtendExperiencedPlansListener implements ScoringListener { private final ExperiencedPlansService service; @Inject ExtendExperiencedPlansListener(ExperiencedPlansService service) { this.service = service; } @Override public void notifyScoring(ScoringEvent event) { // Run before ExperiencedPlansServiceImpl Vehicles vehicles = event.getServices().getScenario().getVehicles(); for (Map.Entry<Id<Person>, Plan> e : service.getExperiencedPlans().entrySet()) { for (Leg leg : TripStructureUtils.getLegs(e.getValue())) { Map<String, Object> attr = leg.getAttributes().getAsMap(); if (attr.containsKey("vehicleId") && attr.get("vehicleId") != null) { Id<Vehicle> id = (Id<Vehicle>) attr.get("vehicleId"); Vehicle veh = vehicles.getVehicles().get(id); if (veh == null) continue; leg.getAttributes().putAttribute("vehicleType", veh.getType().getId().toString()); leg.getAttributes().putAttribute("networkMode", veh.getType().getNetworkMode()); } } } } }
1,677
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunActitopp.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/RunActitopp.java
package org.matsim.prepare; import edu.kit.ifv.mobitopp.actitopp.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.*; import org.matsim.application.MATSimAppCommand; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.ParallelPersonAlgorithmUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import org.matsim.prepare.population.Attributes; import picocli.CommandLine; import java.nio.file.Path; import java.util.List; import java.util.Random; import java.util.SplittableRandom; @CommandLine.Command( name = "actitopp", description = "Run actiTopp activity generation" ) @Deprecated public class RunActitopp implements MATSimAppCommand, PersonAlgorithm { private static final Logger log = LogManager.getLogger(RunActitopp.class); @CommandLine.Option(names = "--input", description = "Path to input population", required = true) private Path input; @CommandLine.Option(names = "--output", description = "Path to output population", required = true) private Path output; @CommandLine.Option(names = "--n", description = "Number of plans to generate per agent", defaultValue = "1") private int n; @CommandLine.Option(names = "--seed", description = "Seed used to generate plans", defaultValue = "1") private long seed; private PopulationFactory factory; private int index; private ThreadLocal<Context> tl; public static void main(String[] args) throws InvalidPatternException { new RunActitopp().execute(args); } @Override public Integer call() throws Exception { Population population = PopulationUtils.readPopulation(input.toString()); factory = population.getFactory(); log.info("Generating activity chains..."); tl = ThreadLocal.withInitial(() -> new Context(seed)); ParallelPersonAlgorithmUtils.run(population, 8, this); PopulationUtils.writePopulation(population, output.toString()); return 0; } @Override public void run(Person person) { // actitopp can only create correct activity schedules for persons aged 10 years and older! if (PersonUtils.getAge(person) < 10) return; Context ctx = tl.get(); // Assume that there is only the stay home plan, which is the selected one for (int i = 0; i < n; i++) { boolean newPlan = generatePlan(person, ctx); // Create a copy of the stay home plan if no new one was generated if (!newPlan) person.createCopyOfSelectedPlanAndMakeSelected(); } // Remove initial plan person.removePlan(person.getSelectedPlan()); person.setSelectedPlan(person.getPlans().get(0)); } private boolean generatePlan(Person person, Context ctx) { ActitoppPerson ap = convertPerson(person, ctx.rnd); if (PersonUtils.isEmployed(person)) { // attr was removed // ap.setCommutingdistance_work((double) person.getAttributes().getAttribute(Attributes.COMMUTE_KM)); } boolean scheduleOK = false; int tries = 0; while (!scheduleOK) { try { Coord homeCoord = new Coord((Double) person.getAttributes().getAttribute(Attributes.HOME_X), (Double) person.getAttributes().getAttribute(Attributes.HOME_Y)); ap.generateSchedule(ctx.fileBase, ctx.rng); // choose random tuesday, wednesday, thursday HWeekPattern week = ap.getWeekPattern(); HDay day = week.getDay(ctx.rnd.nextInt(2, 5)); if (!day.isHomeDay()) { Plan plan = factory.createPlan(); convertDay(day.getWeekday(), week.getAllActivities(), plan, homeCoord); person.addPlan(plan); } else return false; scheduleOK = true; } catch (InvalidPatternException e) { // Re-try tries++; if (tries > 100) { log.warn("No chain generated for person {} after 100 attempts", person.getId()); return false; } } } return true; } /** * Convert actitopp day into matsim schedule. */ private void convertDay(int weekDay, List<HActivity> activities, Plan plan, Coord homeCoord) { Activity a = null; HActivity prev = null; for (HActivity act : activities) { int actDay = act.getDay().getWeekday(); if (actDay < weekDay) { prev = act; continue; } // Collect activities until agent is at home if (actDay > weekDay && prev != null && prev.isHomeActivity()) { break; } if (actDay > weekDay && !act.isHomeActivity()) continue; if (plan.getPlanElements().isEmpty() && !act.isHomeActivity()) { Activity home = factory.createActivityFromCoord("home", homeCoord); // This should not occur if (prev == null) throw new IllegalStateException("Previous activity is null, can not set home end time"); // If activity started on previous day, the end time needs to be adjusted to new day home.setEndTime((prev.getEndTime() * 60) % 86400); plan.addActivity(home); } if (act.isHomeActivity()) { a = factory.createActivityFromCoord("home", homeCoord); } else a = factory.createActivityFromLinkId(getActivityType(act.getActivityType()), Id.createLinkId("unassigned")); a.setStartTime(act.getStartTime() * 60); a.setMaximumDuration(act.getDuration() * 60); // Cut late activities 3h after midnight if (actDay > weekDay) a.setStartTime(Math.min(a.getStartTime().seconds() + 86400d, 4 * 3600 + 86400d)); // No leg needed for first activity if (!plan.getPlanElements().isEmpty()) plan.addLeg(factory.createLeg("walk")); plan.addActivity(a); prev = act; } // Last home activity has no end time and duration if (a != null && a.getType().equals("home")) { a.setEndTimeUndefined(); a.setMaximumDurationUndefined(); } } private String getActivityType(ActivityType activityType) { if (activityType == ActivityType.TRANSPORT || activityType == ActivityType.UNKNOWN) { return "other"; } return activityType.name().toLowerCase(); } /** * Convert actitopp person into matsim. */ private ActitoppPerson convertPerson(Person p, SplittableRandom rnd) { // TODO: from data int children0_10 = rnd.nextInt(0, 2); int children_u18 = rnd.nextInt(0, 2); int age = PersonUtils.getAge(p); // gender type Coding: 1 - male 2 - female int gender = PersonUtils.getSex(p).equals("m") ? 1 : 2; // main occupation status of the person Coding: // 1 - full-time occupied 2 - half-time occupied 3 - not occupied // 4 - student (school or university) 5 - worker in vocational program 6 -housewife, househusband // 7 - retired person / pensioner int employment = 3; if (PersonUtils.isEmployed(p)) { employment = 1; // random half time: TODO: from data if (rnd.nextDouble() < 0.2) employment = 2; } else { if (age < 18) employment = 4; // random students TODO: from data if (age < 28 && rnd.nextDouble() < 0.1) { employment = 4; } if (age > 65) employment = 7; } // https://bmdv.bund.de/SharedDocs/DE/Artikel/G/regionalstatistische-raumtypologie.html // Raumtyp Coding: 1 - rural 2 - provincial 3 - cityoutskirt 4 - metropolitan 5 - conurbation int regioStar = (int) p.getAttributes().getAttribute(Attributes.RegioStaR7); int areaType = switch (regioStar) { case 1 -> 4; case 2, 5 -> 5; case 3 -> 3; case 4, 6 -> 2; case 7 -> 1; default -> throw new IllegalStateException("Unknown regioStar type: " + regioStar); }; // TODO from data int numberofcarsinhousehold = rnd.nextInt(0, 3); // TODO: edu commuting distances return new ActitoppPerson(index++, children0_10, children_u18, age, employment, gender, areaType, numberofcarsinhousehold); } /** * Context for one thread. */ private static final class Context { private final ModelFileBase fileBase = new ModelFileBase(); private final RNGHelper rng; private final SplittableRandom rnd; Context(long seed) { // Generate a new uncorrelated seed long l = new Random(seed).nextLong(); rng = new RNGHelper(l); rnd = new SplittableRandom(l); } } }
8,093
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
FilterRelevantAgents.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/FilterRelevantAgents.java
package org.matsim.prepare; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ShpOptions; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.ParallelPersonAlgorithmUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.router.costcalculators.OnlyTimeDependentTravelDisutility; import org.matsim.core.router.speedy.SpeedyALTFactory; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.LeastCostPathCalculatorFactory; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.facilities.ActivityFacilities; import org.matsim.facilities.FacilitiesUtils; import org.matsim.facilities.MatsimFacilitiesReader; import org.matsim.run.OpenBerlinScenario; import picocli.CommandLine; import java.nio.file.Path; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @CommandLine.Command( name = "filter-relevant-agents", description = "Filter agents that have any activities or routes within the shp file." ) public class FilterRelevantAgents implements MATSimAppCommand, PersonAlgorithm { private static final Logger log = LogManager.getLogger(FilterRelevantAgents.class); @CommandLine.Option(names = "--input", description = "Path to input population", required = true) private Path input; @CommandLine.Option(names = "--output", description = "Path to output population", required = true) private Path output; @CommandLine.Option(names = "--facilities", description = "Path to facilities file", required = true) private Path facilityPath; @CommandLine.Option(names = "--network", description = "Path to network file", required = true) private Path networkPath; @CommandLine.Mixin private ShpOptions shp; private ActivityFacilities facilities; private Network network; private CoordinateTransformation ct; private Geometry geometry; private ThreadLocal<LeastCostPathCalculator> ctxs; private Set<Id<Person>> toRemove; public static void main(String[] args) { new FilterRelevantAgents().execute(args); } @Override public Integer call() throws Exception { if (shp.getShapeFile() == null) { log.error("Shape file argument is required."); return 2; } Network completeNetwork = NetworkUtils.readNetwork(networkPath.toString()); TransportModeNetworkFilter filter = new TransportModeNetworkFilter(completeNetwork); network = NetworkUtils.createNetwork(); filter.filter(network, Set.of(TransportMode.car)); geometry = shp.getGeometry(); ct = shp.createTransformation(OpenBerlinScenario.CRS); facilities = FacilitiesUtils.createActivityFacilities(); new MatsimFacilitiesReader(OpenBerlinScenario.CRS, OpenBerlinScenario.CRS, facilities) .readFile(facilityPath.toString()); ctxs = ThreadLocal.withInitial(() -> this.createRouter(network)); toRemove = ConcurrentHashMap.newKeySet(); Population population = PopulationUtils.readPopulation(input.toString()); ParallelPersonAlgorithmUtils.run(population, 8, this); log.info("Removing {} out of {} agents", toRemove.size(), population.getPersons().size()); toRemove.forEach(population::removePerson); PopulationUtils.writePopulation(population, output.toString()); log.info("Written {} agents to output", population.getPersons().size()); return 0; } @Override public void run(Person person) { boolean keep = false; outer: for (Plan plan : person.getPlans()) { List<Activity> activities = TripStructureUtils.getActivities(plan, TripStructureUtils.StageActivityHandling.ExcludeStageActivities); // Check activities frist, which is faster for (Activity act : activities) { Point p = MGC.coord2Point(ct.transform(getCoordinate(act))); if (geometry.contains(p)) { keep = true; break outer; } } // If not sure yet, also do the routing for (TripStructureUtils.Trip trip : TripStructureUtils.getTrips(plan)) { LeastCostPathCalculator lc = ctxs.get(); Node from = NetworkUtils.getNearestNode(network, getCoordinate(trip.getOriginActivity())); Node to = NetworkUtils.getNearestNode(network, getCoordinate(trip.getDestinationActivity())); LeastCostPathCalculator.Path path = lc.calcLeastCostPath(from, to, 0, null, null); for (Node node : path.nodes) { if (geometry.contains(MGC.coord2Point(ct.transform(node.getCoord())))) { keep = true; break outer; } } } } if (!keep) { toRemove.add(person.getId()); } } private Coord getCoordinate(Activity act) { Coord coord; // Determine coord of activity if (act.getCoord() != null) coord = act.getCoord(); else { coord = facilities.getFacilities().get(act.getFacilityId()).getCoord(); } return coord; } private LeastCostPathCalculator createRouter(Network network) { FreeSpeedTravelTime travelTime = new FreeSpeedTravelTime(); LeastCostPathCalculatorFactory factory = new SpeedyALTFactory(); OnlyTimeDependentTravelDisutility travelDisutility = new OnlyTimeDependentTravelDisutility(travelTime); return factory.createPathCalculator(network, travelDisutility, travelTime); } }
6,072
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CleanAttributes.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/CleanAttributes.java
package org.matsim.prepare; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.ParallelPersonAlgorithmUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import picocli.CommandLine; import java.nio.file.Path; @CommandLine.Command(name = "clean-attributes", description = "Remove attributes from certain entities") public class CleanAttributes implements MATSimAppCommand, PersonAlgorithm { @CommandLine.Option(names = "--input", description = "Path to input population", required = true) private Path input; @CommandLine.Option(names = "--output", description = "Desired output path", required = true) private Path output; @Override public Integer call() throws Exception { Population population = PopulationUtils.readPopulation(input.toString()); ParallelPersonAlgorithmUtils.run(population, 8, this); PopulationUtils.writePopulation(population, output.toString()); return 0; } @Override public void run(Person person) { for (Plan plan : person.getPlans()) { plan.getAttributes().clear(); for (PlanElement el : plan.getPlanElements()) { el.getAttributes().clear(); } } } }
1,437
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
BestKPlanGenerator.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/BestKPlanGenerator.java
package org.matsim.prepare.choices; import org.jetbrains.annotations.Nullable; import org.matsim.modechoice.CandidateGenerator; import org.matsim.modechoice.PlanCandidate; import org.matsim.modechoice.PlanModel; import org.matsim.modechoice.search.TopKChoicesGenerator; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Keeps selected plan as the first candidate and adds the rest with best options. */ public class BestKPlanGenerator implements CandidateGenerator { private final int topK; private final TopKChoicesGenerator generator; public <T> BestKPlanGenerator(int topK, TopKChoicesGenerator generator) { this.topK = topK; this.generator = generator; } @Override public List<PlanCandidate> generate(PlanModel planModel, @Nullable Set<String> consideredModes, @Nullable boolean[] mask) { List<String[]> chosen = new ArrayList<>(); chosen.add(planModel.getCurrentModes()); // Chosen candidate from data PlanCandidate existing = generator.generatePredefined(planModel, chosen).get(0); List<PlanCandidate> result = new ArrayList<>(); result.add(existing); result.addAll(generator.generate(planModel, consideredModes, mask)); return result.stream().distinct().limit(topK).toList(); } }
1,254
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PseudoScorer.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/PseudoScorer.java
package org.matsim.prepare.choices; import com.google.inject.Injector; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Plan; 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.config.Config; import org.matsim.core.events.EventsUtils; import org.matsim.core.scoring.EventsToActivities; import org.matsim.core.scoring.EventsToLegs; import org.matsim.core.scoring.ScoringFunction; import org.matsim.core.scoring.ScoringFunctionFactory; import org.matsim.core.utils.timing.TimeInterpretation; import org.matsim.core.utils.timing.TimeTracker; /** * Replicates the event sequence of a trip to perform scoring without simulation. */ final class PseudoScorer { private final EventsManager eventsManager; private final ScoringFunctionsForPopulation scoring; private final TimeInterpretation timeInterpretation; /** * Buffer resulting score outputs. */ private final StringBuilder result = new StringBuilder(); PseudoScorer(Injector injector, Population population) { this.eventsManager = EventsUtils.createEventsManager(); this.scoring = new ScoringFunctionsForPopulation( eventsManager, new EventsToActivities(), new EventsToLegs(injector.getInstance(Scenario.class)), population, injector.getInstance(ScoringFunctionFactory.class) ); this.timeInterpretation = TimeInterpretation.create(injector.getInstance(Config.class)); } public Object2DoubleMap<String> score(Plan plan) { scoring.reset(0); scoring.init(plan.getPerson()); createEvents(plan); scoring.finishScoringFunctions(); ScoringFunction scoring = this.scoring.getScoringFunctionForAgent(plan.getPerson().getId()); result.setLength(0); if (true) throw new UnsupportedOperationException("This functionality depends on code that is not yet available in MATSim core"); // scoring.explainScore(result); Object2DoubleOpenHashMap<String> scores = new Object2DoubleOpenHashMap<>(); String[] split = new String[0]; // String[] split = result.toString().split(ScoringFunction.SCORE_DELIMITER); for (String s : split) { String[] kv = s.split("="); if (kv.length > 1) { scores.put(kv[0], Double.parseDouble(kv[1])); } } scores.put("score", scoring.getScore()); return scores; } private void createEvents(Plan plan) { TimeTracker tt = new TimeTracker(timeInterpretation); Activity currentAct = null; for (PlanElement el : plan.getPlanElements()) { if (el instanceof Activity act) { // The first activity does not have a start event if (currentAct != null) { eventsManager.processEvent(new ActivityStartEvent(tt.getTime().seconds(), plan.getPerson().getId(), act.getLinkId(), act.getFacilityId(), act.getType(), act.getCoord() )); } tt.addElement(act); // The last activity does not have an end time if (tt.getTime().isDefined()) { eventsManager.processEvent(new ActivityEndEvent(tt.getTime().seconds(), plan.getPerson().getId(), act.getLinkId(), act.getFacilityId(), act.getType(), act.getCoord() )); } currentAct = act; } else tt.addElement(el); } } }
3,545
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DiversePlanGenerator.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/DiversePlanGenerator.java
package org.matsim.prepare.choices; import org.jetbrains.annotations.Nullable; import org.matsim.core.population.PersonUtils; import org.matsim.modechoice.CandidateGenerator; import org.matsim.modechoice.PlanCandidate; import org.matsim.modechoice.PlanModel; import org.matsim.modechoice.search.TopKChoicesGenerator; import java.util.*; /** * Generator to create candidates with different modes. */ public class DiversePlanGenerator implements CandidateGenerator { private final int topK; private final TopKChoicesGenerator gen; DiversePlanGenerator(int topK, TopKChoicesGenerator generator) { this.topK = topK; this.gen = generator; } @Override public List<PlanCandidate> generate(PlanModel planModel, @Nullable Set<String> consideredModes, @Nullable boolean[] mask) { List<String[]> chosen = new ArrayList<>(); chosen.add(planModel.getCurrentModes()); // Chosen candidate from data PlanCandidate existing = gen.generatePredefined(planModel, chosen).get(0); List<PlanCandidate> candidates = new ArrayList<>(); boolean carUser = PersonUtils.canUseCar(planModel.getPerson()); Set<String> modes = new HashSet<>(consideredModes); modes.remove(carUser ? "ride": "car"); for (String mode : modes) { List<PlanCandidate> tmp = gen.generate(planModel, Set.of(mode), mask); if (!tmp.isEmpty()) candidates.add(tmp.get(0)); } Collections.sort(candidates); candidates.add(0, existing); return candidates.stream().distinct().limit(topK).toList(); } }
1,501
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PlanBuilder.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/PlanBuilder.java
package org.matsim.prepare.choices; import it.unimi.dsi.fastutil.Pair; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import me.tongfei.progressbar.ProgressBar; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Geometry; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.application.options.ShpOptions; import org.matsim.application.prepare.population.SplitActivityTypesDuration; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.prepare.population.InitLocationChoice; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.VehicleUtils; import org.opengis.feature.simple.SimpleFeature; import tech.tablesaw.api.Row; import tech.tablesaw.api.Table; import java.nio.file.Path; import java.util.*; /** * Utility class to build plans from data. */ public class PlanBuilder { private static final Logger log = LogManager.getLogger(PlanBuilder.class); /** * Stores of warning for a zone was generated. */ private final Set<Location> warnings = new HashSet<>(); /** * Maps zone ids to contained coordinates. */ private final Long2ObjectMap<Set<Coord>> zones = new Long2ObjectOpenHashMap<>(); /** * Maps location key to zone id. */ private final Object2LongMap<Location> features = new Object2LongOpenHashMap<>(); private final SplitActivityTypesDuration splitDuration = new SplitActivityTypesDuration(); private final SplittableRandom rnd = new SplittableRandom(); private final PopulationFactory f; /** * Drop plans with more than this number of trips. */ private int maxTripNumber = 0; public PlanBuilder(ShpOptions zones, ShpOptions facilities, PopulationFactory f) { // Collect all zones for (SimpleFeature ft : zones.readFeatures()) { features.put(new Location((String) ft.getAttribute("raum_id"), (String) ft.getAttribute("zone")), (long) ft.getAttribute("id")); } ShpOptions.Index index = zones.createIndex("id"); for (SimpleFeature ft : ProgressBar.wrap(facilities.readFeatures(), "Reading facilities")) { Geometry geom = (Geometry) ft.getDefaultGeometry(); Coord coord = new Coord(geom.getCentroid().getX(), geom.getCentroid().getY()); Long result = index.query(coord); if (result != null) { this.zones.computeIfAbsent(result, k -> new HashSet<>()).add(coord); } } this.f = f; } /** * Set the maximum number of trips in a plan. */ public PlanBuilder setMaxTripNumber(int maxTripNumber) { this.maxTripNumber = maxTripNumber; return this; } /** * Add necesarry vehicles to the scenario. */ public static void addVehiclesToScenario(Scenario scenario) { Id<Vehicle> car = Id.createVehicleId("car"); Vehicle vehicle = scenario.getVehicles().getFactory().createVehicle( car, scenario.getVehicles().getVehicleTypes().get(Id.create("car", VehicleType.class)) ); scenario.getVehicles().addVehicle(vehicle); Id<Vehicle> ride = Id.createVehicleId("ride"); vehicle = scenario.getVehicles().getFactory().createVehicle( ride, scenario.getVehicles().getVehicleTypes().get(Id.create("ride", VehicleType.class)) ); scenario.getVehicles().addVehicle(vehicle); } /** * Create persons with plans from a table. */ public List<Person> createPlans(Path input) { Table table = Table.read().csv(input.toFile()); String currentPerson = null; int currentSeq = -1; List<Person> result = new ArrayList<>(); List<Row> trips = new ArrayList<>(); try (ProgressBar pb = new ProgressBar("Reading trips", table.rowCount())) { for (int i = 0; i < table.rowCount(); i++) { Row row = table.row(i); String pId = row.getString("p_id"); int seq = row.getInt("seq"); if (!pId.equals(currentPerson) || seq != currentSeq) { if (!trips.isEmpty()) { // Filter person with too many trips if (maxTripNumber <= 0 || trips.size() <= maxTripNumber) { Person person = createPerson(pId, seq, trips); if (person != null) result.add(person); } trips.clear(); } currentPerson = pId; currentSeq = seq; } trips.add(row); pb.step(); } } return result; } /** * Create person from row data. */ private Person createPerson(String id, int seq, List<Row> trips) { Person person = f.createPerson(Id.createPersonId(id + "_" + seq)); PopulationUtils.putSubpopulation(person, "person"); PersonUtils.setCarAvail(person, trips.get(0).getInt("p_age") >= 18 ? "always" : "never"); VehicleUtils.insertVehicleIdsIntoPersonAttributes(person, Map.of("car", Id.createVehicleId("car"), "ride", Id.createVehicleId("ride"))); Plan plan = f.createPlan(); Pair<Coord, Coord> trip = sampleOD(trips.get(0)); if (trip == null) return null; // source-destination purpose String sd = trips.get(0).getString("sd_group"); Activity act = f.createActivityFromCoord(sd.startsWith("home") ? "home": "other", trip.first()); int departure = trips.get(0).getInt("departure") * 60; act.setEndTime(departure); act.getAttributes().putAttribute("n", trips.get(0).getInt("n")); plan.addActivity(act); plan.addLeg(f.createLeg(trips.get(0).getString("main_mode"))); act = f.createActivityFromCoord(trips.get(0).getString("purpose"), trip.second()); act.setStartTime(departure + trips.get(0).getInt("duration") * 60); plan.addActivity(act); for (int i = 1; i < trips.size(); i++) { Row row = trips.get(i); Coord dest = sampleDest(row, act.getCoord()); if (dest == null) return null; departure = row.getInt("departure") * 60; act.setEndTime(departure); act.getAttributes().putAttribute("n", row.getInt("n")); plan.addLeg(f.createLeg(row.getString("main_mode"))); act = f.createActivityFromCoord(row.getString("purpose"), dest); act.setStartTime(departure + row.getInt("duration") * 60); plan.addActivity(act); } person.getAttributes().putAttribute("seq", seq); person.addPlan(plan); person.setSelectedPlan(plan); splitDuration.run(person); return person; } /** * Sample pair of from and to facility. Tries to find relation with similar distance to the input. */ private Pair<Coord, Coord> sampleOD(Row row) { Set<Coord> from = matchLocation(row.getString("from_location"), row.getString("from_zone")); Set<Coord> to = matchLocation(row.getString("to_location"), row.getString("to_zone")); if (from == null || from.isEmpty() || to == null || to.isEmpty()) return null; double targetDist = InitLocationChoice.beelineDist(row.getDouble("gis_length") * 1000); double dist = Double.POSITIVE_INFINITY; Coord f = null; Coord t = null; int i = 0; do { Coord newF = from.stream().skip(rnd.nextInt(from.size())).findFirst().orElseThrow(); Coord newT = to.stream().skip(rnd.nextInt(to.size())).findFirst().orElseThrow(); double newDist = CoordUtils.calcEuclideanDistance(newF, newT); if (Math.abs(newDist - targetDist) < Math.abs(dist - targetDist)) { dist = newDist; f = newF; t = newT; } i++; } while (i < 8); return Pair.of(f, t); } /** * Sample destination from a row and existing location. */ private Coord sampleDest(Row row, Coord coord) { Set<Coord> to = matchLocation(row.getString("to_location"), row.getString("to_zone")); if (to == null || to.isEmpty()) return null; double targetDist = InitLocationChoice.beelineDist(row.getDouble("gis_length") * 1000); double dist = Double.POSITIVE_INFINITY; Coord f = null; int i = 0; do { Coord newT = to.stream().skip(rnd.nextInt(to.size())).findFirst().orElseThrow(); double newDist = CoordUtils.calcEuclideanDistance(coord, newT); if (Math.abs(newDist - targetDist) < Math.abs(dist - targetDist)) { dist = newDist; f = newT; } i++; } while (i < 8); return f; } /** * Select a random facility for a person. */ private Set<Coord> matchLocation(String location, String zone) { Location loc = new Location(location, zone); long id = features.getOrDefault(loc, -1); if (id == -1) { if (warnings.add(loc)) log.error("No zone found for location {} and zone {}", location, zone); return null; } Set<Coord> facilities = zones.get(id); if (facilities == null) { if (warnings.add(loc)) log.error("No facilities found in zone {}", loc); return null; } return facilities; } private record Location(String name, String zone) { } }
9,033
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RandomPlanGenerator.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/RandomPlanGenerator.java
package org.matsim.prepare.choices; import org.jetbrains.annotations.Nullable; import org.matsim.modechoice.CandidateGenerator; import org.matsim.modechoice.ModeEstimate; import org.matsim.modechoice.PlanCandidate; import org.matsim.modechoice.PlanModel; import org.matsim.modechoice.search.TopKChoicesGenerator; import java.util.*; /** * Generates random candidates. */ public class RandomPlanGenerator implements CandidateGenerator { private final int topK; private final TopKChoicesGenerator gen; private final SplittableRandom rnd = new SplittableRandom(0); public RandomPlanGenerator(int topK, TopKChoicesGenerator generator) { this.topK = topK; this.gen = generator; } @Override public List<PlanCandidate> generate(PlanModel planModel, @Nullable Set<String> consideredModes, @Nullable boolean[] mask) { List<String[]> chosen = new ArrayList<>(); chosen.add(planModel.getCurrentModes()); // Chosen candidate from data PlanCandidate existing = gen.generatePredefined(planModel, chosen).get(0); // This changes the internal state to randomize the estimates for (Map.Entry<String, List<ModeEstimate>> entry : planModel.getEstimates().entrySet()) { for (ModeEstimate est : entry.getValue()) { double[] utils = est.getEstimates(); if (utils != null) for (int i = 0; i < utils.length; i++) { utils[i] = -rnd.nextDouble(); } } } List<PlanCandidate> result = new ArrayList<>(); result.add(existing); result.addAll(gen.generate(planModel, consideredModes, mask)); return result.stream().distinct().limit(topK).toList(); } }
1,598
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ExclusiveCarPlanGenerator.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/ExclusiveCarPlanGenerator.java
package org.matsim.prepare.choices; import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.Nullable; import org.matsim.api.core.v01.TransportMode; import org.matsim.core.population.PersonUtils; import org.matsim.modechoice.CandidateGenerator; import org.matsim.modechoice.PlanCandidate; import org.matsim.modechoice.PlanModel; import org.matsim.modechoice.search.TopKChoicesGenerator; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Generate two plans only, one with car and one without. * Also considers car availability and the current plan. */ public class ExclusiveCarPlanGenerator implements CandidateGenerator { private final TopKChoicesGenerator generator; public ExclusiveCarPlanGenerator(TopKChoicesGenerator generator) { this.generator = generator; } @Override public List<PlanCandidate> generate(PlanModel planModel, @Nullable Set<String> consideredModes, @Nullable boolean[] mask) { List<String[]> chosen = new ArrayList<>(); chosen.add(planModel.getCurrentModes()); // Chosen candidate from data PlanCandidate existing = generator.generatePredefined(planModel, chosen).get(0); List<PlanCandidate> candidates = new ArrayList<>(); candidates.add(existing); Set<String> modes = new HashSet<>(consideredModes); modes.removeAll(Set.of(TransportMode.car, TransportMode.ride)); boolean carUser = PersonUtils.canUseCar(planModel.getPerson()); String carMode = carUser ? TransportMode.car : TransportMode.ride; PlanCandidate alternative; if (ArrayUtils.contains(planModel.getCurrentModes(), carMode)) { List<PlanCandidate> choices = generator.generate(planModel, modes, mask); if (choices.isEmpty()) return null; alternative = choices.get(0); } else { modes.add(carMode); List<PlanCandidate> choices = generator.generate(planModel, modes, mask); if (choices.isEmpty()) return null; alternative = choices.get(0); // The generated plan might not contain the car mode, remove other modes that might be better if (!ArrayUtils.contains(alternative.getModes(), carMode)) { modes.remove(TransportMode.pt); modes.remove(TransportMode.bike); choices = generator.generate(planModel, modes, mask); if (choices.isEmpty()) return null; alternative = choices.get(0); } } candidates.add(alternative); return candidates.stream().distinct().limit(2).toList(); } }
2,458
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ScoringFunctionsForPopulation.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/ScoringFunctionsForPopulation.java
/* *********************************************************************** * * project: org.matsim.* * ScoringFunctionsForPopulation.java * * * *********************************************************************** * * * * copyright : (C) 2013 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.prepare.choices; import gnu.trove.TDoubleCollection; import gnu.trove.iterator.TDoubleIterator; import gnu.trove.list.array.TDoubleArrayList; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.IdMap; import org.matsim.api.core.v01.events.*; import org.matsim.api.core.v01.population.*; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.api.experimental.events.TeleportationArrivalEvent; import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; import org.matsim.core.events.algorithms.Vehicle2DriverEventHandler; import org.matsim.core.events.handler.BasicEventHandler; import org.matsim.core.population.PopulationUtils; import org.matsim.core.router.StageActivityTypeIdentifier; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scoring.*; import org.matsim.core.utils.io.IOUtils; import org.matsim.vehicles.Vehicle; import java.io.BufferedWriter; import java.io.IOException; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; import static org.matsim.core.router.TripStructureUtils.Trip; /** * This class helps EventsToScore by keeping ScoringFunctions for the entire Population - one per Person -, and dispatching Activities * and Legs to the ScoringFunctions. It also gives out the ScoringFunctions, so they can be given other events by EventsToScore. * It is not independently useful. Please do not make public. * * This class was copied from its original location. It would have been useful if it was public. * * @author michaz * @author rakow * */ @SuppressWarnings({"CyclomaticComplexity","WhitespaceAfter", "TrailingComment", "TodoComment"}) final class ScoringFunctionsForPopulation implements BasicEventHandler { private final Population population; private final ScoringFunctionFactory scoringFunctionFactory; private final EventsToLegs legsDelegate; private final EventsToActivities actsDelegate; private final IdMap<Person, ScoringFunction> agentScorers = new IdMap<>(Person.class); private final IdMap<Person, TDoubleCollection> partialScores = new IdMap<>(Person.class); private final AtomicReference<Throwable> exception = new AtomicReference<>(); private final IdMap<Person, Plan> tripRecords = new IdMap<>(Person.class); private final Vehicle2DriverEventHandler vehicles2Drivers = new Vehicle2DriverEventHandler(); ScoringFunctionsForPopulation(EventsManager eventsManager, EventsToActivities eventsToActivities, EventsToLegs eventsToLegs, Population population, ScoringFunctionFactory scoringFunctionFactory) { this.population = population; this.legsDelegate = eventsToLegs; this.actsDelegate = eventsToActivities; this.scoringFunctionFactory = scoringFunctionFactory; eventsManager.addHandler(this); eventsToActivities.addActivityHandler(this::handleActivity); eventsToLegs.addLegHandler(this::handleLeg); } void init(Person person) { this.agentScorers.put(person.getId(), this.scoringFunctionFactory.createNewScoringFunction(person ) ); this.partialScores.put(person.getId(), new TDoubleArrayList()); this.tripRecords.put(person.getId(), PopulationUtils.createPlan()); } @Override public void handleEvent(Event o) { // this is for the stuff that is directly based on events. note that this passes on _all_ person events, even those which are // aggregated into legs and activities. for the time being, not all PersonEvents may "implement HasPersonId". link enter/leave events // are NOT passed on, for performance reasons. kai/dominik, dec'12 if (o instanceof HasPersonId) { ScoringFunction scoringFunction = getScoringFunctionForAgent(((HasPersonId) o).getPersonId()); if (scoringFunction != null) { if (o instanceof PersonStuckEvent) { scoringFunction.agentStuck(o.getTime()); } else if (o instanceof PersonMoneyEvent) { scoringFunction.addMoney(((PersonMoneyEvent) o).getAmount()); // yy looking at this, I am a bit skeptic if it truly makes sense to not pass this additionally into the general events handling function below. // A use case might be different utilities of money by money transaction type (e.g. toll, fare, reimbursement, ...). kai, mar'17 } else if (o instanceof PersonScoreEvent) { scoringFunction.addScore(((PersonScoreEvent) o).getAmount()); } scoringFunction.handleEvent(o); // passing this on in any case, see comment above. kai, mar'17 } } // Establish and end connection between driver and vehicle if (o instanceof VehicleEntersTrafficEvent) { this.vehicles2Drivers.handleEvent((VehicleEntersTrafficEvent) o); } if (o instanceof VehicleLeavesTrafficEvent) { this.vehicles2Drivers.handleEvent((VehicleLeavesTrafficEvent) o); } // Pass LinkEnterEvent to person scoring, required e.g. for bicycle where link attributes are observed in scoring /* * (This shouldn't really be more expensive than passing the link events to the router: here, we have a map lookup * for agentId, there we have a map lookup for linkId. Should be somewhat similar in terms of average * computational complexity. In BetaTravelTest, 194sec w/ "false", 193sec w/ "true". However, the experienced * plans service in fact does the same thing, so we should be able to get away without having to do this twice. * kai, mar'17) */ if (o instanceof LinkEnterEvent) { Id<Vehicle> vehicleId = ((LinkEnterEvent)o).getVehicleId(); Id<Person> driverId = this.vehicles2Drivers.getDriverOfVehicle(vehicleId); ScoringFunction scoringFunction = getScoringFunctionForAgent( driverId ); // (this will NOT do the scoring function lookup twice since LinkEnterEvent is not an instance of HasPersonId. kai, mar'17) if (scoringFunction != null) { scoringFunction.handleEvent(o); } } /* Now also handle events for eventsToLegs and eventsToActivities. * This class deliberately only implements BasicEventHandler and not the individual event handlers required * by EventsToLegs and EventsToActivities to better control the order in which events are passed to scoring * functions. By handling the delegation here *after* having the events passed to scoringFunction.handleEvent() * makes sure that the corresponding event was already seen by a scoring function when the call to handleActivity(), * handleLeg() or handleTrip() is done. */ if (o instanceof ActivityStartEvent) this.handleActivityStart((ActivityStartEvent) o); if (o instanceof ActivityEndEvent) this.actsDelegate.handleEvent((ActivityEndEvent) o); if (o instanceof PersonDepartureEvent) this.legsDelegate.handleEvent((PersonDepartureEvent) o); if (o instanceof PersonArrivalEvent) this.legsDelegate.handleEvent((PersonArrivalEvent) o); if (o instanceof LinkEnterEvent) this.legsDelegate.handleEvent((LinkEnterEvent) o); if (o instanceof TeleportationArrivalEvent) this.legsDelegate.handleEvent((TeleportationArrivalEvent) o); if (o instanceof TransitDriverStartsEvent) this.legsDelegate.handleEvent((TransitDriverStartsEvent) o); if (o instanceof PersonEntersVehicleEvent) this.legsDelegate.handleEvent((PersonEntersVehicleEvent) o); if (o instanceof VehicleArrivesAtFacilityEvent) this.legsDelegate.handleEvent((VehicleArrivesAtFacilityEvent) o); if (o instanceof VehicleEntersTrafficEvent) this.legsDelegate.handleEvent((VehicleEntersTrafficEvent) o); if (o instanceof VehicleLeavesTrafficEvent) this.legsDelegate.handleEvent((VehicleLeavesTrafficEvent) o); } private void handleActivityStart(ActivityStartEvent event) { this.actsDelegate.handleEvent(event); if (!StageActivityTypeIdentifier.isStageActivity( event.getActType() ) ) { this.callTripScoring(event); } } private void callTripScoring(ActivityStartEvent event) { Plan plan = this.tripRecords.get(event.getPersonId()); // as container for trip if (plan != null) { // we are at a real activity, which is not the first one we see for this agent. output the trip ... Activity activity = PopulationUtils.createActivityFromLinkId(event.getActType(), event.getLinkId()); activity.setStartTime(event.getTime()); plan.addActivity(activity); final List<Trip> trips = TripStructureUtils.getTrips(plan); // yyyyyy should in principle only return one trip. There are, however, situations where it returns two trips, in particular // in conjunction with the minibus raptor. Possibly something that has to do with not alternating between acts and legs. // (To make matters worse, it passes on my local machine, but fails in jenkins. Possibly, the byte buffer memory management // in the minibus raptor implementation has issues--???) kai, sep'18 ScoringFunction scoringFunction = ScoringFunctionsForPopulation.this.getScoringFunctionForAgent(event.getPersonId()); for (Trip trip : trips) { if (trip != null) { scoringFunction.handleTrip(trip); } } // ... and clean out the intermediate plan (which will remain in tripRecords). plan.getPlanElements().clear(); } } void handleLeg(PersonExperiencedLeg o) { Id<Person> agentId = o.getAgentId(); Leg leg = o.getLeg(); ScoringFunction scoringFunction = ScoringFunctionsForPopulation.this.getScoringFunctionForAgent(agentId); if (scoringFunction != null) { scoringFunction.handleLeg(leg); TDoubleCollection partialScoresForAgent = this.partialScores.get(agentId); partialScoresForAgent.add(scoringFunction.getScore()); } Plan plan = this.tripRecords.get( agentId ) ; // as container for trip if ( plan!=null ) { plan.addLeg( leg ); } } void handleActivity(PersonExperiencedActivity o) { Id<Person> agentId = o.getAgentId(); Activity activity = o.getActivity(); ScoringFunction scoringFunction = ScoringFunctionsForPopulation.this.getScoringFunctionForAgent(agentId); if (scoringFunction != null) { scoringFunction.handleActivity(activity); TDoubleCollection partialScoresForAgent = this.partialScores.get(agentId); partialScoresForAgent.add(scoringFunction.getScore()); } Plan plan = this.tripRecords.get( agentId ); // as container for trip if ( plan!= null ) { plan.addActivity( activity ); } } /** * Returns the scoring function for the specified agent. If the agent * already has a scoring function, that one is returned. If the agent does * not yet have a scoring function, a new one is created and assigned to the * agent and returned. * * @param agentId * The id of the agent the scoring function is requested for. * @return The scoring function for the specified agent. */ ScoringFunction getScoringFunctionForAgent(final Id<Person> agentId) { return this.agentScorers.get(agentId); } void finishScoringFunctions() { // Rethrow an exception in a scoring function (user code) if there was one. Throwable throwable = this.exception.get(); if (throwable != null) { if (throwable instanceof RuntimeException) { throw ((RuntimeException) throwable); } else { throw new RuntimeException(throwable); } } for (ScoringFunction sf : this.agentScorers.values()) { sf.finish(); } for (Entry<Id<Person>, TDoubleCollection> entry : this.partialScores.entrySet()) { entry.getValue().add(this.getScoringFunctionForAgent(entry.getKey()).getScore()); } } void writePartialScores(String iterationFilename) { try ( BufferedWriter out = IOUtils.getBufferedWriter(iterationFilename) ) { for (Entry<Id<Person>, TDoubleCollection> entry : this.partialScores.entrySet()) { out.write(entry.getKey().toString()); TDoubleIterator iterator = entry.getValue().iterator(); while (iterator.hasNext()) { out.write('\t'); out.write(String.valueOf(iterator.next())); } out.write(IOUtils.NATIVE_NEWLINE); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public void reset(int iteration) { this.legsDelegate.reset(iteration); this.actsDelegate.reset(iteration); } }
13,376
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ComputePlanChoices.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/ComputePlanChoices.java
package org.matsim.prepare.choices; import com.google.inject.Injector; import me.tongfei.progressbar.ProgressBar; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; 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.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ScenarioOptions; import org.matsim.application.options.ShpOptions; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.PlansConfigGroup; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.ParallelPersonAlgorithmUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import org.matsim.core.router.*; import org.matsim.core.utils.timing.TimeInterpretation; import org.matsim.modechoice.*; import org.matsim.modechoice.constraints.RelaxedMassConservationConstraint; import org.matsim.modechoice.estimators.DefaultLegScoreEstimator; import org.matsim.modechoice.estimators.FixedCostsEstimator; import org.matsim.modechoice.search.TopKChoicesGenerator; import picocli.CommandLine; import javax.annotation.Nullable; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; @CommandLine.Command( name = "compute-plan-choices", description = "Computes multiple plan choices for a whole day." ) public class ComputePlanChoices implements MATSimAppCommand, PersonAlgorithm { // TODO: move whole class to contrib when done, can probably go into imc private static final Logger log = LogManager.getLogger(ComputePlanChoices.class); /** * Rows for the result table. */ private final Queue<List<Object>> rows = new ConcurrentLinkedQueue<>(); @CommandLine.Mixin private ScenarioOptions scenario; @CommandLine.Mixin private ShpOptions shp; @CommandLine.Option(names = "--trips", description = "Input trips from survey data, in matsim-python-tools format.", required = true) private Path input; @CommandLine.Option(names = "--facilities", description = "Shp file with facilities", required = true) private Path facilities; @CommandLine.Option(names = "--top-k", description = "Use top k estimates", defaultValue = "9") private int topK; @CommandLine.Option(names = "--modes", description = "Modes to include in estimation", split = ",") private Set<String> modes; @CommandLine.Option(names = "--time-util-only", description = "Reset scoring for estimation and only use time utility", defaultValue = "false") private boolean timeUtil; @CommandLine.Option(names = "--calc-scores", description = "Perform pseudo scoring for each plan", defaultValue = "false") private boolean calcScores; @CommandLine.Option(names = "--plan-candidates", description = "Method to generate plan candidates", defaultValue = "bestK") private PlanCandidates planCandidates = PlanCandidates.bestK; @CommandLine.Option(names = "--output", description = "Path to output csv.", required = true) private Path output; private ThreadLocal<Ctx> thread; private ProgressBar pb; private MainModeIdentifier mmi = new DefaultAnalysisMainModeIdentifier(); public static void main(String[] args) { new ComputePlanChoices().execute(args); } @Override public Integer call() throws Exception { if (!shp.isDefined()) { log.error("No shapefile defined. Please specify a shapefile for the zones using the --shp option."); return 2; } if (!Files.exists(input)) { log.error("Input file does not exist: " + input); return 2; } Config config = this.scenario.getConfig(); config.controller().setOutputDirectory("choice-output"); config.controller().setLastIteration(0); config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); if (timeUtil) { // All utilities expect travel time become zero config.scoring().setMarginalUtlOfWaitingPt_utils_hr(0); config.scoring().setUtilityOfLineSwitch(0); config.scoring().getModes().values().forEach(m -> { // Only time goes into the score m.setMarginalUtilityOfTraveling(-config.scoring().getPerforming_utils_hr()); m.setConstant(0); m.setMarginalUtilityOfDistance(0); m.setDailyMonetaryConstant(0); m.setMonetaryDistanceRate(0); }); } // This method only produces two choices if (planCandidates == PlanCandidates.carAlternative) { log.info("Setting top k to 2 for car alternative"); topK = 2; } Controler controler = this.scenario.createControler(); controler.addOverridingModule(InformedModeChoiceModule.newBuilder() .withFixedCosts(FixedCostsEstimator.DailyConstant.class, "car") .withLegEstimator(DefaultLegScoreEstimator.class, ModeOptions.ConsiderIfCarAvailable.class, "car") .withLegEstimator(DefaultLegScoreEstimator.class, ModeOptions.AlwaysAvailable.class, "bike", "walk", "pt", "ride") .withConstraint(RelaxedMassConservationConstraint.class) .build()); InformedModeChoiceConfigGroup imc = ConfigUtils.addOrGetModule(config, InformedModeChoiceConfigGroup.class); imc.setTopK(topK); imc.setModes(modes); imc.setConstraintCheck(InformedModeChoiceConfigGroup.ConstraintCheck.none); controler.run(); Injector injector = controler.getInjector(); PlanBuilder.addVehiclesToScenario(injector.getInstance(Scenario.class)); Population population = PopulationUtils.createPopulation(config); PlanBuilder builder = new PlanBuilder(shp, new ShpOptions(facilities, null, null), population.getFactory()); builder.createPlans(input).forEach(population::addPerson); thread = ThreadLocal.withInitial(() -> new Ctx( new PlanRouter(injector.getInstance(TripRouter.class), TimeInterpretation.create(PlansConfigGroup.ActivityDurationInterpretation.tryEndTimeThenDuration, PlansConfigGroup.TripDurationHandling.ignoreDelays)), switch (planCandidates) { case bestK -> new BestKPlanGenerator(topK, injector.getInstance(TopKChoicesGenerator.class)); case diverse -> new DiversePlanGenerator(topK, injector.getInstance(TopKChoicesGenerator.class)); case random -> new RandomPlanGenerator(topK, injector.getInstance(TopKChoicesGenerator.class)); case carAlternative -> new ExclusiveCarPlanGenerator(injector.getInstance(TopKChoicesGenerator.class)); }, calcScores ? new PseudoScorer(injector, population) : null ) ); pb = new ProgressBar("Computing plan choices", population.getPersons().size()); ParallelPersonAlgorithmUtils.run(population, Runtime.getRuntime().availableProcessors(), this); pb.close(); try (CSVPrinter csv = new CSVPrinter(Files.newBufferedWriter(output), CSVFormat.DEFAULT)) { // header List<Object> header = new ArrayList<>(); header.add("person"); header.add("choice"); for (int i = 1; i <= topK; i++) { for (String mode : modes) { header.add(String.format("plan_%d_%s_usage", i, mode)); header.add(String.format("plan_%d_%s_km", i, mode)); header.add(String.format("plan_%d_%s_hours", i, mode)); header.add(String.format("plan_%d_%s_ride_hours", i, mode)); header.add(String.format("plan_%d_%s_n_switches", i, mode)); } header.add(String.format("plan_%d_act_util", i)); header.add(String.format("plan_%d_valid", i)); } csv.printRecord(header); for (List<Object> row : rows) { csv.printRecord(row); } } return 0; } @Override public void run(Person person) { Plan plan = person.getSelectedPlan(); PlanModel model = PlanModel.newInstance(plan); Ctx ctx = thread.get(); List<Object> row = new ArrayList<>(); row.add(person.getId()); // choice, always the first one row.add(1); List<PlanCandidate> candidates = ctx.generator.generate(model, modes, null); // skip possible error cases if (candidates == null) { pb.step(); return; } int i = 0; for (PlanCandidate candidate : candidates) { if (i >= topK) break; // TODO: apply method might also shift times to better fit the schedule candidate.applyTo(plan); ctx.router.run(plan); row.addAll(convert(plan, ctx.scorer)); // available choice row.add(1); i++; } for (int j = i; j < topK; j++) { row.addAll(convert(null, ctx.scorer)); // not available row.add(0); } rows.add(row); pb.step(); } /** * Create one csv entry row for a plan. */ private List<Object> convert(@Nullable Plan plan, PseudoScorer scorer) { List<Object> row = new ArrayList<>(); if (plan == null) { for (String ignored : modes) { row.addAll(List.of(0, 0, 0, 0, 0)); } row.add(0); return row; } Map<String, ModeStats> stats = collect(plan); for (String mode : modes) { ModeStats modeStats = stats.get(mode); row.add(modeStats.usage); row.add(modeStats.travelDistance / 1000); row.add(modeStats.travelTime / 3600); row.add(modeStats.rideTime / 3600); row.add(modeStats.numSwitches); } if (calcScores) row.add(scorer.score(plan).getDouble("score")); else row.add(0); return row; } /** * Collect aggregated mode stats. */ private Map<String, ModeStats> collect(Plan plan) { Map<String, ModeStats> stats = new HashMap<>(); for (String mode : modes) { int usage = 0; double travelTime = 0; double rideTime = 0; double travelDistance = 0; long switches = 0; for (TripStructureUtils.Trip trip : TripStructureUtils.getTrips(plan)) { List<Leg> legs = trip.getLegsOnly(); String mainMode = mmi.identifyMainMode(legs); if (mode.equals(mainMode)) { usage++; travelTime += legs.stream().mapToDouble(l -> l.getRoute().getTravelTime().seconds()).sum(); travelDistance += legs.stream().mapToDouble(l -> l.getRoute().getDistance()).sum(); rideTime += legs.stream().filter(l -> l.getMode().equals(mode)) .mapToDouble(l -> l.getRoute().getTravelTime().seconds()).sum(); // This is mainly used for PT, to count the number of switches switches += legs.stream().filter(l -> l.getMode().equals(mode)).count() - 1; } } stats.put(mode, new ModeStats(usage, travelTime, travelDistance, rideTime, switches)); } return stats; } /** * Define how candidates are generated. */ public enum PlanCandidates { bestK, diverse, random, carAlternative } private record ModeStats(int usage, double travelTime, double travelDistance, double rideTime, long numSwitches) { } private record Ctx(PlanRouter router, CandidateGenerator generator, PseudoScorer scorer) { } }
10,895
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ComputeTripChoices.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/choices/ComputeTripChoices.java
package org.matsim.prepare.choices; import com.google.inject.Injector; import me.tongfei.progressbar.ProgressBar; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; 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.TransportMode; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ScenarioOptions; import org.matsim.application.options.ShpOptions; import org.matsim.core.config.Config; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.network.NetworkUtils; import org.matsim.core.router.TripRouter; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.facilities.FacilitiesUtils; import org.matsim.facilities.Facility; import org.matsim.utils.objectattributes.attributable.AttributesImpl; import picocli.CommandLine; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.SplittableRandom; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @CommandLine.Command( name = "compute-trip-choices", description = "Computes all choices and metrics for a dataset of trips." ) public class ComputeTripChoices implements MATSimAppCommand { // TODO: move whole class to contrib when done, can probably go into imc private static final Logger log = LogManager.getLogger(ComputeTripChoices.class); @CommandLine.Mixin private ScenarioOptions scenario; @CommandLine.Mixin private ShpOptions shp; @CommandLine.Option(names = "--trips", description = "Input trips from survey data, in matsim-python-tools format.", required = true) private Path input; @CommandLine.Option(names = "--facilities", description = "Shp file with facilities", required = true) private Path facilities; @CommandLine.Option(names = "--modes", description = "Modes to include in choice set", split = ",", required = true) private List<String> modes; @CommandLine.Option(names = "--output", description = "Input trips from survey data, in matsim-python-tools format.", required = true) private Path output; public static void main(String[] args) { new ComputeTripChoices().execute(args); } @Override public Integer call() throws Exception { if (!shp.isDefined()) { log.error("No shapefile defined. Please specify a shapefile for the zones using the --shp option."); return 2; } if (!Files.exists(input)) { log.error("Input file does not exist: " + input); return 2; } Config config = this.scenario.getConfig(); config.controller().setOutputDirectory("choice-output"); config.controller().setLastIteration(0); config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles); Controler controler = this.scenario.createControler(); // Run for one iteration to collect travel times controler.run(); Injector injector = controler.getInjector(); Scenario scenario = injector.getInstance(Scenario.class); PlanBuilder builder = new PlanBuilder(shp, new ShpOptions(facilities, null, null), scenario.getPopulation().getFactory()); PlanBuilder.addVehiclesToScenario(scenario); ThreadLocal<TripRouter> ctx = ThreadLocal.withInitial(() -> injector.getInstance(TripRouter.class)); ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<CompletableFuture<List<Object>>> futures = new ArrayList<>(); List<Person> persons = builder.createPlans(input); // Progress bar will be inaccurate ProgressBar pb = new ProgressBar("Computing choices", persons.size() * 3L); SplittableRandom rnd = new SplittableRandom(); for (Person person : persons) { Plan plan = person.getSelectedPlan(); for (TripStructureUtils.Trip trip : TripStructureUtils.getTrips(plan)) { // Randomize departure times double departure = trip.getOriginActivity().getEndTime().seconds() + rnd.nextInt(-600, 600); futures.add(CompletableFuture.supplyAsync(() -> { TripRouter r = ctx.get(); List<Object> entries = computeAlternatives(r, scenario.getNetwork(), person, trip, departure); pb.step(); return entries; }, executor)); } } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .exceptionally(ex -> { log.error("Error while computing trip choices", ex); return null; }) .join(); executor.shutdown(); pb.close(); try (CSVPrinter csv = new CSVPrinter(Files.newBufferedWriter(output), CSVFormat.DEFAULT)) { List<String> header = new ArrayList<>(List.of("p_id", "seq", "trip_n", "choice", "beelineDist")); for (String mode : modes) { header.add(mode + "_km"); header.add(mode + "_hours"); header.add(mode + "_walk_km"); header.add(mode + "_valid"); } csv.printRecord(header); for (CompletableFuture<List<Object>> f : futures) { List<Object> entries = f.get(); if (entries != null) { csv.printRecord(entries); } } } return 0; } /** * Compute all alternatives for a given trip. */ private List<Object> computeAlternatives(TripRouter router, Network network, Person person, TripStructureUtils.Trip trip, double departure) { double beelineDist = CoordUtils.calcEuclideanDistance(trip.getOriginActivity().getCoord(), trip.getDestinationActivity().getCoord()); Facility origin = FacilitiesUtils.wrapLinkAndCoord(NetworkUtils.getNearestLink(network, trip.getOriginActivity().getCoord()), trip.getOriginActivity().getCoord()); Facility destination = FacilitiesUtils.wrapLinkAndCoord(NetworkUtils.getNearestLink(network, trip.getDestinationActivity().getCoord()), trip.getDestinationActivity().getCoord()); String choice = trip.getLegsOnly().get(0).getMode(); List<Object> row = new ArrayList<>(List.of(person.getId(), person.getAttributes().getAttribute("seq"), trip.getTripAttributes().getAttribute("n"), modes.indexOf(choice) + 1, beelineDist / 1000)); for (String mode : modes) { double travelTime = 0; double travelDistance = 0; double walkDistance = 0; boolean valid = false; List<? extends PlanElement> route = router.calcRoute(mode, origin, destination, departure, person, new AttributesImpl()); for (PlanElement el : route) { if (el instanceof Leg leg) { travelTime += leg.getTravelTime().seconds(); travelDistance += leg.getRoute().getDistance(); if (leg.getMode().equals(TransportMode.walk)) { walkDistance += leg.getRoute().getDistance(); } if (leg.getMode().equals(mode)) valid = true; } } // Filter rows that have been chosen, but would not be valid if (choice.equals(mode) && !valid) { return null; } row.addAll(List.of(travelDistance / 1000, travelTime / 3600, walkDistance / 1000, valid)); } return row; } }
7,324
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DownloadCommuterStatistic.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/download/DownloadCommuterStatistic.java
package org.matsim.prepare.download; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import picocli.CommandLine; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @CommandLine.Command(name = "download-commuter", description = "Download commuter statistic for all Gemeinden.") public class DownloadCommuterStatistic implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(DownloadCommuterStatistic.class); @CommandLine.Option(names = "--username", required = true, description = "Username for regionalstatistik.de") private String username; @CommandLine.Option(names = "--password", defaultValue = "${GENESIS_PW}", interactive = true, description = "Password for regionalstatistik.de") private String password; @CommandLine.Option(names = "--gemeinden", required = true, description = "Path to gemeinden CSV.") private Path gemeinden; @CommandLine.Option(names = "--output", description = "Output csv", required = true) private Path output; @CommandLine.Mixin private CsvOptions csv; private RequestConfig config; private ObjectMapper mapper; private Path tmp; public static void main(String[] args) { new DownloadCommuterStatistic().execute(args); } @Override public Integer call() throws Exception { config = RequestConfig.custom() .setConnectionRequestTimeout(5, TimeUnit.MINUTES) .setResponseTimeout(5, TimeUnit.MINUTES) .build(); mapper = new ObjectMapper(); tmp = Path.of(output.toAbsolutePath() + "_tmp"); Files.createDirectories(tmp); if (password.isBlank()) { log.error("No password given, either set GENESIS_PW or use --password to enter it."); return 1; } List<OD> results = new ArrayList<>(); List<CSVRecord> records; try (CSVParser parser = csv.createParser(gemeinden)) { records = parser.getRecords(); } try (CloseableHttpClient client = HttpClients.createDefault()) { for (CSVRecord gemeinde : records) { String result; try { result = downloadGemeinde(client, gemeinde); } catch (IOException e) { log.error("Error retrieving stats", e); Thread.sleep(15_000); continue; } List<OD> parsed = parseResult(result, gemeinde); log.info("Parsed {} relations", parsed.size()); results.addAll(parsed); } } try (CSVPrinter printer = csv.createPrinter(output)) { printer.printRecord("from", "to", "n"); for (OD od : results) { // commuter codes (pendler) are prefixed with a P which we don't need printer.print(od.origin.replace("P", "")); printer.print(od.destination); printer.print(od.n); printer.println(); } } return 0; } private String downloadGemeinde(CloseableHttpClient client, CSVRecord gemeinde) throws IOException, InterruptedException { String code = gemeinde.get("code"); Path path = tmp.resolve(code + ".csv"); // Return cached result if (Files.exists(path)) { return Files.readString(path); } HttpGet httpGet = new HttpGet(String.format("https://www.regionalstatistik.de/genesisws/rest/2020/data/table?username=%s&password=%s&name=19321-Z-21&area=all&compress=true&regionalvariable=PGEMEIN&regionalkey=%s", username, password, code)); httpGet.setConfig(config); log.info("Processing {}: {}", code, gemeinde.get("name")); JsonNode tree = client.execute(httpGet, response -> mapper.readTree(response.getEntity().getContent())); String result = tree.get("Object").get("Content").asText(); Files.writeString(path, result, StandardCharsets.UTF_8, StandardOpenOption.CREATE); Thread.sleep(5_000); return result; } private List<OD> parseResult(String table, CSVRecord gemeinde) { List<String> lines = table.lines().toList(); List<OD> result = new ArrayList<>(); String from = gemeinde.get("code").intern(); boolean parse = false; for (String line : lines) { // Find beginning of data if (line.startsWith(";;Anzahl")) { parse = true; continue; } if (!parse) continue; // End of data if (line.startsWith("___")) break; String[] split = line.split(";"); try { result.add(new OD(from, split[0].intern(), Integer.parseInt(split[2]))); } catch (NumberFormatException e) { // Ignore parse error } } return result; } private record OD(String origin, String destination, int n) { } }
5,139
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DownloadVariable.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/download/DownloadVariable.java
package org.matsim.prepare.download; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.csv.CSVPrinter; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import picocli.CommandLine; import java.nio.file.Path; import java.util.concurrent.TimeUnit; @CommandLine.Command(name = "download-variable", description = "Downloads existing entries for a variable from Regionalstatistik") public class DownloadVariable implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(DownloadVariable.class); @CommandLine.Option(names = "--username", required = true, description = "Username for regionalstatistik.de") private String username; @CommandLine.Option(names = "--password", defaultValue = "${GENESIS_PW}", interactive = true, description = "Password for regionalstatistik.de") private String password; @CommandLine.Option(names = "--output", description = "Output csv", required = true) private Path output; @CommandLine.Option(names = "--variable", description = "Variable to download (e.g. GEMEIN, PGEMEIN)", required = true) private String variable; @CommandLine.Option(names = "--page-length", description = "Maximum page length", defaultValue = "15000") private int length; @CommandLine.Mixin private CsvOptions csv; public static void main(String[] args) { new DownloadVariable().execute(args); } @Override public Integer call() throws Exception { RequestConfig config = RequestConfig.custom() .setConnectionRequestTimeout(5, TimeUnit.MINUTES) .setResponseTimeout(5, TimeUnit.MINUTES) .build(); ObjectMapper mapper = new ObjectMapper(); if (password.isBlank()) { log.error("No password given, either set GENESIS_PW or use --password to enter it."); return 1; } try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(String.format("https://www.regionalstatistik.de/genesisws/rest/2020/catalogue/values2variable?username=%s&password=%s&name=%s&area=all&pagelength=%d", username, password, variable, length)); httpGet.setConfig(config); log.info("Querying service..."); JsonNode tree = client.execute(httpGet, response -> mapper.readTree(response.getEntity().getContent())); try (CSVPrinter printer = csv.createPrinter(output)) { printer.printRecord("code", "name"); JsonNode list = tree.get("List"); log.info("Processing {} entries", list.size()); for (int i = 0; i < list.size(); i++) { JsonNode entry = list.get(i); printer.print(entry.get("Code").asText()); printer.print(entry.get("Content").asText()); printer.println(); } } } return 0; } }
3,106
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CalculateEmployedPopulation.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/download/CalculateEmployedPopulation.java
package org.matsim.prepare.download; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.json.JsonMapper; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; @CommandLine.Command( name = "calc-employment-rate", description = "Calculate employment rate from population and labor statistics." ) public class CalculateEmployedPopulation implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(CalculateEmployedPopulation.class); @CommandLine.Option(names = "--labor", description = "Path to labor.csv", required = true) private Path labor; @CommandLine.Option(names = "--employment", description = "Path to employment.csv", required = true) private Path employment; @CommandLine.Option(names = "--output", description = "Path to employment_rate.json", required = true) private Path output; @CommandLine.Mixin private CsvOptions csv = new CsvOptions(); public static void main(String[] args) { new CalculateEmployedPopulation().execute(args); } @Override public Integer call() throws Exception { Map<Integer, Integer> employment = readEmployment(this.employment); Map<Integer, Employment> labor = readLabor(this.labor); // Scale labor statistics to employment statistics for (Map.Entry<Integer, Employment> e : labor.entrySet()) { Integer employed = employment.get(e.getKey()); if (employed == null) { log.warn("No employment entry for {}", e.getKey()); continue; } double f = employed / e.getValue().sum(); if (f < 1) { log.warn("Rate is less than 1 for {}", e.getKey()); continue; } e.getValue().scale(f); } JsonMapper mapper = new JsonMapper(); mapper.writerFor(new TypeReference<Map<Integer, Employment>>() { }) .withDefaultPrettyPrinter() .writeValue(Files.newBufferedWriter(output), labor); return 0; } private Map<Integer, Integer> readEmployment(Path path) throws IOException { Map<Integer, Integer> result = new HashMap<>(); try (CSVParser parser = csv.createParser(path)) { for (CSVRecord row : parser) { String code = row.get("code"); if (code.equals("DG")) continue; result.put(Integer.parseInt(code), Integer.parseInt(row.get("employed"))); } } return result; } private Map<Integer, Employment> readLabor(Path path) throws IOException { Map<Integer, Employment> result = new HashMap<>(); try (CSVParser parser = csv.createParser(path)) { for (CSVRecord r : parser) { String code = r.get("code"); if (code.equals("DG")) continue; int gem = Integer.parseInt(code); Employment row = result.computeIfAbsent(gem, k -> new Employment()); for (String gender : List.of("m", "f")) { String age = r.get("age"); Entry entry = gender.equals("m") ? row.men : row.women; int n = Integer.parseInt(r.get(gender)); switch (age) { case "0 - 20" -> entry.age18_20 += n; case "20 - 25" -> entry.age20_25 += n; case "25 - 30" -> entry.age25_30 += n; case "30 - 50" -> entry.age30_50 += n; case "50 - 60" -> entry.age50_60 += n; case "60 - 65" -> entry.age60_65 += n; case "65 - inf" -> entry.age65_75 += n; default -> throw new IllegalStateException("Unknown age group: " + age); } } } } return result; } /** * Helper class to collect employment statistic. */ public static final class Employment { /** * Statistic for men. */ @JsonProperty public final Entry men = new Entry(); /** * Statistics for women. */ @JsonProperty public final Entry women = new Entry(); /** * Sum of men and women. */ public double sum() { return men.sum() + women.sum(); } /** * Multiplier all entries with a factor. */ void scale(double f) { men.scale(f); women.scale(f); } } /** * Age grouping specific for available data. */ @SuppressWarnings(value = {"MemberName", "MissingJavadocMethod"}) public static final class Entry { @JsonProperty double age18_20; @JsonProperty double age20_25; @JsonProperty double age25_30; @JsonProperty double age30_50; @JsonProperty double age50_60; @JsonProperty double age60_65; @JsonProperty double age65_75; public double sum() { return age18_20 + age20_25 + age25_30 + age30_50 + age50_60 + age60_65 + age65_75; } /** * Subtract value from the age groups. * * @param amount amount to subtract * @param age age * @return true if the result is larger than zero. */ public boolean subtract(double amount, int age) { if (age >= 75 || age < 18) return false; if (age < 20) return (age18_20 -= amount) >= 0; if (age < 25) return (age20_25 -= amount) >= 0; if (age < 30) return (age25_30 -= amount) >= 0; if (age < 50) return (age30_50 -= amount) >= 0; if (age < 60) return (age50_60 -= amount) >= 0; if (age < 65) return (age60_65 -= amount) >= 0; return (age65_75 -= amount) >= 0; } void scale(double f) { age18_20 *= f; age20_25 *= f; age25_30 *= f; age30_50 *= f; age50_60 *= f; age60_65 *= f; age65_75 *= f; } } }
5,629
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DownloadEmploymentStatistic.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/download/DownloadEmploymentStatistic.java
package org.matsim.prepare.download; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.csv.CSVPrinter; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @CommandLine.Command(name = "download-employment-statistics", description = "Download table 13312-01-05-4 (Erwerbstätige nach Wirtschaftszweigen) from regionalstatistik.de") public class DownloadEmploymentStatistic implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(DownloadEmploymentStatistic.class); @CommandLine.Option(names = "--username", required = true, description = "Username for regionalstatistik.de") private String username; @CommandLine.Option(names = "--password", defaultValue = "${GENESIS_PW}", interactive = true, description = "Password for regionalstatistik.de") private String password; @CommandLine.Option(names = "--output", description = "Output csv", required = true) private Path output; @CommandLine.Mixin private CsvOptions csv; private RequestConfig config; public static void main(String[] args) { new DownloadEmploymentStatistic().execute(args); } @Override public Integer call() throws Exception { config = RequestConfig.custom() .setConnectionRequestTimeout(5, TimeUnit.MINUTES) .setResponseTimeout(5, TimeUnit.MINUTES) .build(); if (password.isBlank()) { log.error("No password given, either set GENESIS_PW or use --password to enter it."); return 1; } List<Row> rows; try (CloseableHttpClient client = HttpClients.createDefault()) { String result = downloadResult(client); rows = parseResult(result); } try (CSVPrinter printer = csv.createPrinter(output)) { printer.printRecord("code", "employed"); for (Row row : rows) { printer.printRecord(row.code, (int) row.total); } } return 0; } private String downloadResult(CloseableHttpClient client) throws IOException { HttpGet httpGet = new HttpGet(String.format("https://www.regionalstatistik.de/genesisws/rest/2020/data/table?username=%s&password=%s&name=%s&area=all&compress=true", username, password, "13312-01-05-4")); httpGet.setConfig(config); JsonNode tree = client.execute(httpGet, response -> new ObjectMapper().readTree(response.getEntity().getContent())); return tree.get("Object").get("Content").asText(); } private List<Row> parseResult(String table) { List<Row> result = new ArrayList<>(); List<String> lines = table.lines().skip(7).toList(); for (String line : lines) { // End of data if (line.startsWith("___")) break; String[] split = line.split(";"); try { result.add(new Row(split[1], Double.parseDouble(split[3].replace(",", ".")) * 1000)); } catch (NumberFormatException e) { log.warn("Format error in {}", split[2]); } } return result; } private record Row(String code, double total) { } }
3,465
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DownloadLaborStatistic.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/download/DownloadLaborStatistic.java
package org.matsim.prepare.download; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.csv.CSVPrinter; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @CommandLine.Command(name = "download-labor-statistics", description = "Download table 13111-06-02-4 (Sozialversicherungspflichtig Beschäftigte am Wohnort) from regionalstatistik.de") public class DownloadLaborStatistic implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(DownloadLaborStatistic.class); @CommandLine.Option(names = "--username", required = true, description = "Username for regionalstatistik.de") private String username; @CommandLine.Option(names = "--password", defaultValue = "${GENESIS_PW}", interactive = true, description = "Password for regionalstatistik.de") private String password; @CommandLine.Option(names = "--output", description = "Output csv", required = true) private Path output; @CommandLine.Mixin private CsvOptions csv; private RequestConfig config; public static void main(String[] args) { new DownloadLaborStatistic().execute(args); } @Override public Integer call() throws Exception { config = RequestConfig.custom() .setConnectionRequestTimeout(5, TimeUnit.MINUTES) .setResponseTimeout(5, TimeUnit.MINUTES) .build(); if (password.isBlank()) { log.error("No password given, either set GENESIS_PW or use --password to enter it."); return 1; } List<Row> rows; try (CloseableHttpClient client = HttpClients.createDefault()) { String result = downloadResult(client); rows = parseResult(result); } try (CSVPrinter printer = csv.createPrinter(output)) { printer.printRecord("code", "age", "m", "f"); for (Row row : rows) { printer.printRecord(row.code, row.ageGroup, row.m, row.f); } } return 0; } private String downloadResult(CloseableHttpClient client) throws IOException { HttpGet httpGet = new HttpGet(String.format("https://www.regionalstatistik.de/genesisws/rest/2020/data/table?username=%s&password=%s&name=%s&area=all&compress=true", username, password, "13111-06-02-4")); httpGet.setConfig(config); JsonNode tree = client.execute(httpGet, response -> new ObjectMapper().readTree(response.getEntity().getContent())); return tree.get("Object").get("Content").asText(); } private List<Row> parseResult(String table) { List<Row> result = new ArrayList<>(); List<String> lines = table.lines().skip(10).toList(); for (String line : lines) { // End of data if (line.startsWith("___")) break; String[] split = line.split(";"); if (split[3].equals("Insgesamt")) continue; try { result.add(new Row(split[1], DownloadPopulationStatistic.formatAge(split[3]), Integer.parseInt(split[5]), Integer.parseInt(split[6]))); } catch (NumberFormatException e) { log.warn("Format error in {}", split[2]); } } return result; } private record Row(String code, String ageGroup, int m, int f) { } }
3,596
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DownloadPopulationStatistic.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/download/DownloadPopulationStatistic.java
package org.matsim.prepare.download; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.csv.CSVPrinter; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @CommandLine.Command(name = "download-population-statistics", description = "Download table 12411-02-03-5 for existing job from regionalstatistik.de") public class DownloadPopulationStatistic implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(DownloadPopulationStatistic.class); @CommandLine.Option(names = "--username", required = true, description = "Username for regionalstatistik.de") private String username; @CommandLine.Option(names = "--password", defaultValue = "${GENESIS_PW}", interactive = true, description = "Password for regionalstatistik.de") private String password; @CommandLine.Option(names = "--name", required = true, defaultValue = "12411-02-03-5", description = "Name of the saved result on regionalstatistik.de") private String name; @CommandLine.Option(names = "--output", description = "Output csv", required = true) private Path output; @CommandLine.Mixin private CsvOptions csv; private RequestConfig config; public static void main(String[] args) { new DownloadPopulationStatistic().execute(args); } /** * Format string for age group. */ public static String formatAge(String input) { return input.replace("bis unter", "-") .replace("unter", "0 -").replace(" Jahre", "") .replace(" und mehr", " - inf"); } @Override public Integer call() throws Exception { config = RequestConfig.custom() .setConnectionRequestTimeout(5, TimeUnit.MINUTES) .setResponseTimeout(5, TimeUnit.MINUTES) .build(); if (password.isBlank()) { log.error("No password given, either set GENESIS_PW or use --password to enter it."); return 1; } List<Row> rows; try (CloseableHttpClient client = HttpClients.createDefault()) { String result = downloadResult(client); rows = parseResult(result); } try (CSVPrinter printer = csv.createPrinter(output)) { printer.printRecord("code", "age", "gender", "n"); for (Row row : rows) { printer.printRecord(row.code, row.ageGroup, row.gender, row.n); } } return 0; } private String downloadResult(CloseableHttpClient client) throws IOException { HttpGet httpGet = new HttpGet(String.format("https://www.regionalstatistik.de/genesisws/rest/2020/data/result?username=%s&password=%s&name=%s&area=all&compress=true", username, password, name)); httpGet.setConfig(config); log.info("Processing result {}", name); JsonNode tree = client.execute(httpGet, response -> new ObjectMapper().readTree(response.getEntity().getContent())); return tree.get("Object").get("Content").asText(); } private List<Row> parseResult(String table) { List<Row> result = new ArrayList<>(); List<String> lines = table.lines().skip(6).collect(Collectors.toList()); // Normalize header lines String[] gender = lines.remove(0).split(";"); for (int i = 0; i < gender.length; i++) { gender[i] = gender[i].length() > 0 ? gender[i].substring(0, 1) : gender[i]; } lines.remove(0); String[] age = lines.remove(0).split(";"); for (int i = 0; i < age.length; i++) { age[i] = formatAge(age[i]); } for (String line : lines) { // End of data if (line.startsWith("___")) break; String[] split = line.split(";"); for (int i = 0; i < split.length; i++) { if (!gender[i].equals("m") && !gender[i].equals("w")) continue; if (age[i].equals("Insgesamt")) continue; if (split[i].equals("-") | split[i].equals(".")) continue; try { result.add(new Row( split[0], age[i], gender[i], Integer.parseInt(split[i]) )); } catch (NumberFormatException e) { log.warn("Invalid entry in {}: {}", split[1], split[i]); } } } return result; } /** * One row in the csv. * * @param code location code * @param ageGroup age * @param gender gender * @param n amount */ private record Row(String code, String ageGroup, String gender, int n) { } }
4,770
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Speedrelative_right_before_left.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/Speedrelative_right_before_left.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; /** * Generated model, do not modify. */ public final class Speedrelative_right_before_left implements FeatureRegressor { public static Speedrelative_right_before_left INSTANCE = new Speedrelative_right_before_left(); public static final double[] DEFAULT_PARAMS = {0.8963104890604893, 0.907779780107761, 0.9657777777777777, 0.9390178571428571, 0.8976287001287001, 0.8780142118863049, 0.8887809250136831, 0.825, 0.9178789873780846, 0.9118619338974725, 0.8633333333333333, 0.8988143023581764, 0.8620000000000001, 0.9060461051236138, 0.9125183877611075, 0.9289101037851039, 0.86, 0.8830906593406594, 0.90612800068587, 0.9417142857142856, 0.9073636363636365, 0.8774057457693821, 0.8917696504884008, 0.9224348574237957, 0.8724999999999999, 0.8942378151260503, 0.9119517494603098, 0.8995305004135644, 0.81, 0.906801705037773, 0.9127536984823196, 0.8988636363636364, 0.9315416065416066, 0.9349062049062049, 0.8969890335444526, 0.9348571428571428, 0.8980857142857145, 0.8856666666666667, 0.8736043689320387, 0.9128539042140267, 0.8522222222222222, 0.8728571428571428, 0.8957270063048499, 0.81, 0.9057298460517382, 0.9119159948649355, 0.923600529100529, 0.8955372363557295, 0.8474999999999999, 0.9111714922048996, 0.9140597667638484, 0.8940000000000001, 0.8817649456521732, 0.8923656604072576, 0.9115526965460413, 0.9063091992909768, 0.9278564102564104, 0.9116596143892381, 0.8369444444444444, 0.9533333333333334, 0.9179887755102042, 0.8961407076719574, 0.9065209235209234, 0.9053174603174603, 0.8755526210484196, 0.9266666666666664, 0.8903952437777016, 0.9126892319168844, 0.9060949275362316, 0.94375, 0.9279761904761904, 0.8872294372294374, 0.905262565112545, 0.9335344827586207, 0.9117431057774061, 0.9133333333333334, 0.9624999999999999, 0.9205203634085211, 0.9046606919921524, 0.885290738837501, 0.9462499999999999, 0.9050396825396825, 0.8938604921077065, 0.9306392632524707, 0.9115489742058761, 0.9015513059544803, 0.9097905589449835, 0.8355555555555555, 0.9115875715365513, 0.9463898412698414, 0.8869117216117216, 0.920287356321839, 0.8915902876001878, 0.912917748917749, 0.8812435897435896, 0.8908123114259477, 0.9134191437851321, 0.8608, 0.925595238095238, 0.9428900112233443, 0.8983750112097563, 0.9066231157184487, 0.9185284455128196, 0.9111929377013993, 0.9156882190184944, 0.9618518518518518, 0.8480000000000001, 0.9034016996972196, 0.9089377289377286, 0.9450000000000001, 0.8411111111111111, 0.8852724694005188, 0.9275840455840455, 0.9115927977152296, 0.95, 0.9016370911621433, 0.8932330896397288, 0.9073952380057445, 0.858, 0.9240311059907833, 0.9065454324586977, 0.9539506172839507, 0.8913375992063499, 0.8720893719806763, 0.8978113316960016, 0.8754740740740743, 0.9241414141414144, 0.97, 0.9134333965063667, 0.9332121212121212, 0.896646095484826, 0.9048114248624498, 0.9179519979573592, 0.9096654880059047, 0.9114651707205671, 0.9353006535947712, 0.9017669906570216, 0.8225, 0.888325396825397, 0.9155204872646732, 0.8477083333333333, 0.88645889623455, 0.9138631499519039, 0.9069037807430658, 0.8760732323232324, 0.9133333333333334, 0.8987480607120432, 0.83, 0.9065239779355977, 0.9118807043650808, 0.9261224489795917, 0.8964603174603176, 0.9724999999999999, 0.8635093167701863, 0.8968705868205864, 0.8710444444444442, 0.8864712389380531, 0.913670796731158, 0.83, 0.8801234567901235, 0.9064023487773486, 0.8966307979602087, 0.8468181818181819, 0.9067232056921173, 0.9121806805399314, 0.9164756097560975, 0.8997246216315977, 0.9264285714285715, 0.9604444444444444, 0.9023615160349855, 0.8667811224489795, 0.9209126984126983, 0.8912381796690306, 0.9131125601456902, 0.8758333333333331, 0.8491666666666666, 0.95, 0.9003444986294373, 0.9089710496249118, 0.84, 0.9137755102040817, 0.8479166666666668, 0.9460000000000001, 0.9131474108769188, 0.9006687988628284, 0.85125, 0.9233333333333332, 0.8871921846187221, 0.9128130849019936, 0.82, 0.8994898294098979, 0.9065283439133278, 0.9270833333333333, 0.9470370370370369, 0.9176040208590636, 0.9102188855452498, 0.9077810348537008, 0.8616666666666667, 0.952888888888889, 0.9195555555555556, 0.955, 0.8721872082166194, 0.9058176190476189, 0.8892145779752149, 0.9197197674418602, 0.97, 0.9114728738100862, 0.9575, 0.9233571428571428, 0.8994351212279782, 0.9121506653469709, 0.9063740332759166, 0.9168739177489179, 0.9409811875367432, 0.8930322510822511, 0.9079232991857105, 0.8975975422427037, 0.9173449735449737, 0.8767065527065526, 0.8904209252806806, 0.9025109270761444, 0.9151556198525614, 0.8965180991095627, 0.9102292539165499, 0.9000625828324853, 0.9071489459661338, 0.9146306074877499, 0.9078297424948234, 0.9538461538461538, 0.9235871546149326, 0.9095966386554623, 0.88685, 0.9036226333907056, 0.8761461412151064, 0.8875914918414916, 0.82, 0.9043749999999999, 0.913229965839154, 0.8966499118165784, 0.8963636527800346, 0.81, 0.9144076211853991, 0.9069250171640673, 0.859375, 0.9123046707054904, 0.8663888888888889, 0.8832426406926406, 0.8535416666666668, 0.9062405372405371, 0.8921325471698108, 0.9130257648749901, 0.9066011383678083, 0.98, 0.9127431685188195, 0.8403030303030303, 0.8686054421768706, 0.9020917508417506, 0.9575, 0.8817531975600162, 0.9521904761904764, 0.9, 0.975, 0.8998432744231712, 0.9128722973772332, 0.91125, 0.9404676767676766, 0.8961609560652104, 0.94, 0.9055938359214272, 0.9118614953127417, 0.9026623376623375, 0.9124921522673196, 0.9376174603174602, 0.91625, 0.8791836734693877, 0.91704609929078, 0.8764207650273224, 0.8900302810077519, 0.8514285714285714, 0.9320639880952379, 0.9120123720933075, 0.9458333333333332, 0.932607843137255, 0.9008569007850045, 0.9144233992140552, 0.9076185406350459, 0.9087216457204349, 0.8698809523809523, 0.9504575163398695, 0.9168253968253968, 0.9575, 0.9113914910226386, 0.8742735042735044, 0.8892988178878105, 0.9186808201058205, 0.9413000000000002, 0.9127886733946768, 0.90525048590865, 0.9117047340165935, 0.9040737698312573, 0.9342436974789914, 0.9124143956634909, 0.9629166666666668, 0.9166075268817203, 0.900836701734957, 0.8590476190476192, 0.9549999999999998, 0.9583333333333334, 0.8835339947089947, 0.9173510689990282, 0.9105930717949452, 0.9267499999999999, 0.9537037037037037, 0.8965379354544167, 0.81, 0.9057372513233752, 0.9117025676937486, 0.9289152661064425, 0.9072296813462226, 0.9461693121693122, 0.88, 0.9021743915343915, 0.8525, 0.8773258145363407, 0.8899619229371141, 0.9145110071291122, 0.9034828192640693, 0.8982925824175823, 0.914337398373984, 0.8986023000827502, 0.9065549852824765, 0.9303571428571429, 0.9129700650682545, 0.9085714285714286, 0.8844444444444446, 0.9530769230769232, 0.9159847655537314, 0.8586607142857143, 0.9047658359293874, 0.8796229508196718, 0.8946043247344458, 0.9733333333333333, 0.9256361231361232, 0.9124370733198691, 0.9077759551495022, 0.9011375404530748, 0.906432943165566, 0.9138637566137569, 0.90588351594325, 0.9039004054520362, 0.859, 0.9348684371184373, 0.8893333333333334, 0.9223529411764707, 0.8875427948957362, 0.8343750000000001, 0.8802500000000002, 0.9146802030000676, 0.9044582378405911, 0.9494366744366745, 0.9238461538461539, 0.8990830986322339, 0.8680769230769231, 0.9067528832624594, 0.9124966462445298, 0.9488461538461539, 0.916897838568051, 0.9037300505050504, 0.855, 0.8762508116883115, 0.8175, 0.9170204081632654, 0.888842857142857, 0.9131314199147661, 0.8588888888888889, 0.8639087301587302, 0.9011538461538464, 0.9139651062970262, 0.8813333333333334, 0.9029880629154616, 0.910469066515498, 0.9142822352685367, 0.9044583640473731, 0.8587499999999999, 0.8925146825396825, 0.8746021062271059, 0.9314285714285713, 0.8920663446873409, 0.9266163623344076, 0.9121442636126181, 0.9118387142537488, 0.8522222222222222, 0.8998732867435937, 0.8653333333333333, 0.9061258978611965, 0.9115514565598496, 0.94125, 0.9156936605918088, 0.8885156249999999, 0.9072331390370802, 0.9575, 0.9061148459383753, 0.8818014264264258, 0.8927877544614837, 0.9007142857142857, 0.9328092970521545, 0.9123191792416646, 0.8586666666666666, 0.9000817379685306, 0.9060046016957547, 0.9276495726495727, 0.9118913255910112, 0.9158933410762681, 0.9033565335583049, 0.9161445845666372, 0.82, 0.9031756756756758, 0.8734375, 0.9633333333333334, 0.9082225294985248, 0.9574999999999999, 0.908732409381663, 0.8717295597484276, 0.8932220652501507, 0.909896473265074, 0.9047709940822045, 0.9375892857142859, 0.9102582220465107, 0.923735229276896, 0.98, 0.882116883116883, 0.9073649772408962, 0.8809014136904761, 0.8924398057548741, 0.8752380952380951, 0.845, 0.9165307017543857, 0.9412380952380952, 0.911517294727134, 0.932104700854701, 0.900056958056958, 0.81, 0.9120916666666661, 0.9067132328896942, 0.9570000000000001, 0.9011841527939084, 0.9121304824561406, 0.9374074074074075, 0.908556628056628, 0.8730658914728682, 0.8848747334754794, 0.9181322620032301, 0.9114789302991948, 0.879422619047619, 0.9041666666666666, 0.8944099216710178, 0.9008846493013155, 0.9147012195121947, 0.9070592602316181}; @Override public double predict(Object2DoubleMap<String> ft) { return predict(ft, DEFAULT_PARAMS); } @Override public double[] getData(Object2DoubleMap<String> ft) { double[] data = new double[14]; data[0] = (ft.getDouble("length") - 133.10125331063188) / 78.97094374399138; data[1] = (ft.getDouble("speed") - 8.333418463866819) / 0.13514417432622952; data[2] = (ft.getDouble("numFoes") - 2.239973514945138) / 0.6527240855058805; data[3] = (ft.getDouble("numLanes") - 1.007094211123723) / 0.09043758661115839; data[4] = (ft.getDouble("junctionSize") - 10.936152099886492) / 3.8735682630465176; data[5] = ft.getDouble("dir_l"); data[6] = ft.getDouble("dir_r"); data[7] = ft.getDouble("dir_s"); data[8] = ft.getDouble("dir_multiple_s"); data[9] = ft.getDouble("dir_exclusive"); data[10] = ft.getDouble("priority_lower"); data[11] = ft.getDouble("priority_equal"); data[12] = ft.getDouble("priority_higher"); data[13] = ft.getDouble("changeNumLanes"); return data; } @Override public double predict(Object2DoubleMap<String> ft, double[] params) { double[] data = getData(ft); for (int i = 0; i < data.length; i++) if (Double.isNaN(data[i])) throw new IllegalArgumentException("Invalid data at index: " + i); return score(data, params); } public static double score(double[] input, double[] params) { double var0; if (input[0] <= -1.1051058769226074) { if (input[6] <= 0.5) { if (input[3] <= 16.507580757141113) { if (input[0] <= -1.3007474541664124) { var0 = params[0]; } else { var0 = params[1]; } } else { var0 = params[2]; } } else { if (input[2] <= -1.133669689297676) { if (input[0] <= -1.4498529434204102) { var0 = params[3]; } else { var0 = params[4]; } } else { if (input[0] <= -1.2934029698371887) { var0 = params[5]; } else { var0 = params[6]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.45138441026210785) { if (input[7] <= 0.5) { var0 = params[7]; } else { var0 = params[8]; } } else { if (input[1] <= 20.545328298583627) { var0 = params[9]; } else { var0 = params[10]; } } } else { if (input[0] <= -0.6253091394901276) { if (input[0] <= -0.6280316710472107) { var0 = params[11]; } else { var0 = params[12]; } } else { if (input[0] <= 0.8570715188980103) { var0 = params[13]; } else { var0 = params[14]; } } } } double var1; if (input[0] <= -1.1047260165214539) { if (input[6] <= 0.5) { if (input[4] <= -1.919716238975525) { if (input[0] <= -1.1063088178634644) { var1 = params[15]; } else { var1 = params[16]; } } else { if (input[4] <= -1.403396487236023) { var1 = params[17]; } else { var1 = params[18]; } } } else { if (input[4] <= -1.5324764251708984) { if (input[7] <= 0.5) { var1 = params[19]; } else { var1 = params[20]; } } else { if (input[0] <= -1.314866542816162) { var1 = params[21]; } else { var1 = params[22]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.9077547788619995) { if (input[4] <= -0.3707568794488907) { var1 = params[23]; } else { var1 = params[24]; } } else { if (input[0] <= -0.8595725297927856) { var1 = params[25]; } else { var1 = params[26]; } } } else { if (input[0] <= -0.6498751640319824) { if (input[12] <= 0.5) { var1 = params[27]; } else { var1 = params[28]; } } else { if (input[0] <= 0.7061932384967804) { var1 = params[29]; } else { var1 = params[30]; } } } } double var2; if (input[0] <= -1.2157161831855774) { if (input[6] <= 0.5) { if (input[4] <= -1.919716238975525) { if (input[4] <= -2.177876114845276) { var2 = params[31]; } else { var2 = params[32]; } } else { if (input[0] <= -1.567047894001007) { var2 = params[33]; } else { var2 = params[34]; } } } else { if (input[2] <= -1.133669689297676) { if (input[7] <= 0.5) { var2 = params[35]; } else { var2 = params[36]; } } else { if (input[5] <= 0.5) { var2 = params[37]; } else { var2 = params[38]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= 4.217991352081299) { if (input[1] <= 20.545328298583627) { var2 = params[39]; } else { var2 = params[40]; } } else { var2 = params[41]; } } else { if (input[0] <= -0.6553834974765778) { if (input[12] <= 0.5) { var2 = params[42]; } else { var2 = params[43]; } } else { if (input[0] <= 0.6136908531188965) { var2 = params[44]; } else { var2 = params[45]; } } } } double var3; if (input[0] <= -0.8563434779644012) { if (input[6] <= 0.5) { if (input[0] <= -1.2232505679130554) { if (input[4] <= -1.919716238975525) { var3 = params[46]; } else { var3 = params[47]; } } else { if (input[7] <= 0.5) { var3 = params[48]; } else { var3 = params[49]; } } } else { if (input[2] <= -1.133669689297676) { if (input[0] <= -0.9815794229507446) { var3 = params[50]; } else { var3 = params[51]; } } else { if (input[0] <= -1.2356602549552917) { var3 = params[52]; } else { var3 = params[53]; } } } } else { if (input[1] <= 30.830639839172363) { if (input[0] <= 0.8461181223392487) { if (input[6] <= 0.5) { var3 = params[54]; } else { var3 = params[55]; } } else { if (input[0] <= 0.9087360799312592) { var3 = params[56]; } else { var3 = params[57]; } } } else { var3 = params[58]; } } double var4; if (input[0] <= -1.0086146593093872) { if (input[6] <= 0.5) { if (input[4] <= -1.661556363105774) { if (input[13] <= -0.5) { var4 = params[59]; } else { var4 = params[60]; } } else { if (input[0] <= -1.274345338344574) { var4 = params[61]; } else { var4 = params[62]; } } } else { if (input[0] <= -1.314866542816162) { if (input[4] <= -1.5324764251708984) { var4 = params[63]; } else { var4 = params[64]; } } else { if (input[4] <= -1.403396487236023) { var4 = params[65]; } else { var4 = params[66]; } } } } else { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[0] <= 1.2864699959754944) { var4 = params[67]; } else { var4 = params[68]; } } else { if (input[13] <= -0.5) { var4 = params[69]; } else { var4 = params[70]; } } } else { if (input[0] <= 0.7018245458602905) { if (input[0] <= -0.9565069079399109) { var4 = params[71]; } else { var4 = params[72]; } } else { if (input[4] <= -1.5324764251708984) { var4 = params[73]; } else { var4 = params[74]; } } } } double var5; if (input[0] <= -0.8548872768878937) { if (input[6] <= 0.5) { if (input[13] <= -0.5) { if (input[4] <= -2.177876114845276) { var5 = params[75]; } else { var5 = params[76]; } } else { if (input[4] <= -1.919716238975525) { var5 = params[77]; } else { var5 = params[78]; } } } else { if (input[0] <= -1.111817181110382) { if (input[3] <= 5.450231730937958) { var5 = params[79]; } else { var5 = params[80]; } } else { if (input[0] <= -1.0847819447517395) { var5 = params[81]; } else { var5 = params[82]; } } } } else { if (input[1] <= 20.545328298583627) { if (input[6] <= 0.5) { if (input[0] <= -0.7834686040878296) { var5 = params[83]; } else { var5 = params[84]; } } else { if (input[0] <= -0.48563751578330994) { var5 = params[85]; } else { var5 = params[86]; } } } else { var5 = params[87]; } } double var6; if (input[0] <= -1.005195677280426) { if (input[4] <= -0.628916785120964) { if (input[5] <= 0.5) { if (input[3] <= 5.450231730937958) { var6 = params[88]; } else { var6 = params[89]; } } else { if (input[0] <= -1.1810198426246643) { var6 = params[90]; } else { var6 = params[91]; } } } else { if (input[6] <= 0.5) { if (input[0] <= -1.1175788640975952) { var6 = params[92]; } else { var6 = params[93]; } } else { if (input[0] <= -1.2956823110580444) { var6 = params[94]; } else { var6 = params[95]; } } } } else { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[0] <= 4.217991352081299) { var6 = params[96]; } else { var6 = params[97]; } } else { if (input[0] <= -0.6404412686824799) { var6 = params[98]; } else { var6 = params[99]; } } } else { if (input[0] <= 0.4344477206468582) { if (input[0] <= -0.6612084209918976) { var6 = params[100]; } else { var6 = params[101]; } } else { if (input[7] <= 0.5) { var6 = params[102]; } else { var6 = params[103]; } } } } double var7; if (input[0] <= -1.0085513591766357) { if (input[6] <= 0.5) { if (input[5] <= 0.5) { if (input[3] <= 16.507580757141113) { var7 = params[104]; } else { var7 = params[105]; } } else { if (input[2] <= -2.6657105684280396) { var7 = params[106]; } else { var7 = params[107]; } } } else { if (input[2] <= -1.133669689297676) { if (input[0] <= -1.0409683585166931) { var7 = params[108]; } else { var7 = params[109]; } } else { if (input[4] <= -1.016156643629074) { var7 = params[110]; } else { var7 = params[111]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= 3.8902758359909058) { if (input[0] <= -0.9906966984272003) { var7 = params[112]; } else { var7 = params[113]; } } else { var7 = params[114]; } } else { if (input[0] <= -0.6476591229438782) { if (input[0] <= -0.7535208463668823) { var7 = params[115]; } else { var7 = params[116]; } } else { if (input[1] <= 30.830639839172363) { var7 = params[117]; } else { var7 = params[118]; } } } } double var8; if (input[0] <= -1.1095378994941711) { if (input[2] <= -1.133669689297676) { if (input[3] <= 16.507580757141113) { if (input[4] <= -1.919716238975525) { var8 = params[119]; } else { var8 = params[120]; } } else { var8 = params[121]; } } else { if (input[0] <= -1.2979615926742554) { if (input[6] <= 0.5) { var8 = params[122]; } else { var8 = params[123]; } } else { if (input[0] <= -1.1265061497688293) { var8 = params[124]; } else { var8 = params[125]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -1.0758545994758606) { if (input[0] <= -1.0857316851615906) { var8 = params[126]; } else { var8 = params[127]; } } else { if (input[3] <= 5.450231730937958) { var8 = params[128]; } else { var8 = params[129]; } } } else { if (input[0] <= 0.45166924595832825) { if (input[0] <= -0.8577364087104797) { var8 = params[130]; } else { var8 = params[131]; } } else { if (input[7] <= 0.5) { var8 = params[132]; } else { var8 = params[133]; } } } } double var9; if (input[0] <= -1.008741319179535) { if (input[6] <= 0.5) { if (input[4] <= -0.628916785120964) { if (input[3] <= 5.450231730937958) { var9 = params[134]; } else { var9 = params[135]; } } else { if (input[0] <= -1.0114638209342957) { var9 = params[136]; } else { var9 = params[137]; } } } else { if (input[2] <= -1.133669689297676) { if (input[0] <= -1.3244270086288452) { var9 = params[138]; } else { var9 = params[139]; } } else { if (input[4] <= -1.016156643629074) { var9 = params[140]; } else { var9 = params[141]; } } } } else { if (input[6] <= 0.5) { if (input[4] <= -0.3707568794488907) { if (input[0] <= 0.6772585511207581) { var9 = params[142]; } else { var9 = params[143]; } } else { if (input[0] <= 0.2858487665653229) { var9 = params[144]; } else { var9 = params[145]; } } } else { if (input[0] <= -0.6472792625427246) { if (input[4] <= 2.4690020084381104) { var9 = params[146]; } else { var9 = params[147]; } } else { if (input[0] <= 0.6519327759742737) { var9 = params[148]; } else { var9 = params[149]; } } } } double var10; if (input[0] <= -1.228442370891571) { if (input[4] <= -1.661556363105774) { if (input[8] <= 0.5) { if (input[0] <= -1.3532984256744385) { var10 = params[150]; } else { var10 = params[151]; } } else { var10 = params[152]; } } else { if (input[6] <= 0.5) { if (input[0] <= -1.4902475476264954) { var10 = params[153]; } else { var10 = params[154]; } } else { if (input[0] <= -1.3146132826805115) { var10 = params[155]; } else { var10 = params[156]; } } } } else { if (input[6] <= 0.5) { if (input[13] <= 0.5) { if (input[1] <= 20.545328298583627) { var10 = params[157]; } else { var10 = params[158]; } } else { if (input[0] <= -0.763967752456665) { var10 = params[159]; } else { var10 = params[160]; } } } else { if (input[0] <= -0.6249925792217255) { if (input[0] <= -0.6280316710472107) { var10 = params[161]; } else { var10 = params[162]; } } else { if (input[0] <= 1.2350586652755737) { var10 = params[163]; } else { var10 = params[164]; } } } } double var11; if (input[0] <= -1.1651912927627563) { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[4] <= -1.919716238975525) { var11 = params[165]; } else { var11 = params[166]; } } else { if (input[4] <= -1.5324764251708984) { var11 = params[167]; } else { var11 = params[168]; } } } else { if (input[0] <= -1.2691535353660583) { if (input[0] <= -1.4550447463989258) { var11 = params[169]; } else { var11 = params[170]; } } else { if (input[4] <= -0.628916785120964) { var11 = params[171]; } else { var11 = params[172]; } } } } else { if (input[6] <= 0.5) { if (input[1] <= 20.545328298583627) { if (input[13] <= 1.5) { var11 = params[173]; } else { var11 = params[174]; } } else { var11 = params[175]; } } else { if (input[0] <= -0.5590822398662567) { if (input[0] <= -1.1631651520729065) { var11 = params[176]; } else { var11 = params[177]; } } else { if (input[1] <= 30.830639839172363) { var11 = params[178]; } else { var11 = params[179]; } } } } double var12; if (input[0] <= -1.0568602681159973) { if (input[4] <= -0.628916785120964) { if (input[7] <= 0.5) { if (input[4] <= -1.5324764251708984) { var12 = params[180]; } else { var12 = params[181]; } } else { if (input[13] <= -0.5) { var12 = params[182]; } else { var12 = params[183]; } } } else { if (input[6] <= 0.5) { if (input[0] <= -1.0625585913658142) { var12 = params[184]; } else { var12 = params[185]; } } else { if (input[0] <= -1.5740758180618286) { var12 = params[186]; } else { var12 = params[187]; } } } } else { if (input[0] <= 0.5139706432819366) { if (input[6] <= 0.5) { if (input[1] <= 20.545328298583627) { var12 = params[188]; } else { var12 = params[189]; } } else { if (input[0] <= -0.5450897812843323) { var12 = params[190]; } else { var12 = params[191]; } } } else { if (input[0] <= 0.5236577391624451) { if (input[5] <= 0.5) { var12 = params[192]; } else { var12 = params[193]; } } else { if (input[7] <= 0.5) { var12 = params[194]; } else { var12 = params[195]; } } } } double var13; if (input[0] <= -0.8563434779644012) { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[4] <= -0.3707568794488907) { var13 = params[196]; } else { var13 = params[197]; } } else { if (input[0] <= -1.1465768218040466) { var13 = params[198]; } else { var13 = params[199]; } } } else { if (input[0] <= -1.29099702835083) { if (input[2] <= -2.6657105684280396) { var13 = params[200]; } else { var13 = params[201]; } } else { if (input[2] <= -1.133669689297676) { var13 = params[202]; } else { var13 = params[203]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.5379352271556854) { if (input[0] <= -0.5415441691875458) { var13 = params[204]; } else { var13 = params[205]; } } else { if (input[0] <= 4.024438858032227) { var13 = params[206]; } else { var13 = params[207]; } } } else { if (input[0] <= -0.4812055081129074) { if (input[0] <= -0.8421610593795776) { var13 = params[208]; } else { var13 = params[209]; } } else { if (input[7] <= 0.5) { var13 = params[210]; } else { var13 = params[211]; } } } } double var14; if (input[0] <= -0.8596358299255371) { if (input[6] <= 0.5) { if (input[5] <= 0.5) { if (input[3] <= 5.450231730937958) { var14 = params[212]; } else { var14 = params[213]; } } else { if (input[0] <= -1.3018237948417664) { var14 = params[214]; } else { var14 = params[215]; } } } else { if (input[2] <= -1.133669689297676) { if (input[4] <= -1.661556363105774) { var14 = params[216]; } else { var14 = params[217]; } } else { if (input[0] <= -1.2979615926742554) { var14 = params[218]; } else { var14 = params[219]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= 0.5618363618850708) { if (input[9] <= 0.5) { var14 = params[220]; } else { var14 = params[221]; } } else { if (input[0] <= 0.8989856541156769) { var14 = params[222]; } else { var14 = params[223]; } } } else { if (input[0] <= 0.6518694758415222) { if (input[0] <= -0.6355660855770111) { var14 = params[224]; } else { var14 = params[225]; } } else { if (input[0] <= 1.8887167572975159) { var14 = params[226]; } else { var14 = params[227]; } } } } double var15; if (input[0] <= -1.1047260165214539) { if (input[4] <= -1.661556363105774) { if (input[13] <= -0.5) { var15 = params[228]; } else { if (input[4] <= -1.919716238975525) { var15 = params[229]; } else { var15 = params[230]; } } } else { if (input[6] <= 0.5) { if (input[0] <= -1.295935571193695) { var15 = params[231]; } else { var15 = params[232]; } } else { if (input[0] <= -1.2906171679496765) { var15 = params[233]; } else { var15 = params[234]; } } } } else { if (input[6] <= 0.5) { if (input[7] <= 0.5) { if (input[0] <= -0.5164716523140669) { var15 = params[235]; } else { var15 = params[236]; } } else { if (input[4] <= 0.016482964158058167) { var15 = params[237]; } else { var15 = params[238]; } } } else { if (input[0] <= -0.6553834974765778) { if (input[12] <= 0.5) { var15 = params[239]; } else { var15 = params[240]; } } else { if (input[7] <= 0.5) { var15 = params[241]; } else { var15 = params[242]; } } } } double var16; if (input[0] <= -0.8562168478965759) { if (input[6] <= 0.5) { if (input[4] <= -0.3707568794488907) { if (input[7] <= 0.5) { var16 = params[243]; } else { var16 = params[244]; } } else { var16 = params[245]; } } else { if (input[0] <= -1.2295820116996765) { if (input[0] <= -1.2462337613105774) { var16 = params[246]; } else { var16 = params[247]; } } else { if (input[2] <= -1.133669689297676) { var16 = params[248]; } else { var16 = params[249]; } } } } else { if (input[1] <= 20.545328298583627) { if (input[0] <= 0.7021411061286926) { if (input[6] <= 0.5) { var16 = params[250]; } else { var16 = params[251]; } } else { if (input[0] <= 0.7029008865356445) { var16 = params[252]; } else { var16 = params[253]; } } } else { var16 = params[254]; } } double var17; if (input[0] <= -1.2201481461524963) { if (input[8] <= 0.5) { if (input[6] <= 0.5) { if (input[0] <= -1.5065193176269531) { var17 = params[255]; } else { var17 = params[256]; } } else { if (input[4] <= -1.919716238975525) { var17 = params[257]; } else { var17 = params[258]; } } } else { if (input[0] <= -1.2585167288780212) { if (input[0] <= -1.2837791442871094) { var17 = params[259]; } else { var17 = params[260]; } } else { var17 = params[261]; } } } else { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[9] <= 0.5) { var17 = params[262]; } else { var17 = params[263]; } } else { if (input[0] <= -1.1211877465248108) { var17 = params[264]; } else { var17 = params[265]; } } } else { if (input[0] <= -0.6608918607234955) { if (input[3] <= 5.450231730937958) { var17 = params[266]; } else { var17 = params[267]; } } else { if (input[0] <= 0.6421823501586914) { var17 = params[268]; } else { var17 = params[269]; } } } } double var18; if (input[0] <= -0.8577364087104797) { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[0] <= -1.2636452317237854) { var18 = params[270]; } else { var18 = params[271]; } } else { if (input[0] <= -0.9790468513965607) { var18 = params[272]; } else { var18 = params[273]; } } } else { if (input[2] <= -1.133669689297676) { if (input[0] <= -1.3244270086288452) { var18 = params[274]; } else { var18 = params[275]; } } else { if (input[0] <= -1.3780543804168701) { var18 = params[276]; } else { var18 = params[277]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.7834686040878296) { if (input[9] <= 0.5) { var18 = params[278]; } else { var18 = params[279]; } } else { if (input[3] <= 5.450231730937958) { var18 = params[280]; } else { var18 = params[281]; } } } else { if (input[0] <= -0.485067680478096) { if (input[0] <= -0.8490623235702515) { var18 = params[282]; } else { var18 = params[283]; } } else { if (input[7] <= 0.5) { var18 = params[284]; } else { var18 = params[285]; } } } } double var19; if (input[0] <= -1.005195677280426) { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[0] <= -1.0191248655319214) { var19 = params[286]; } else { var19 = params[287]; } } else { if (input[13] <= 0.5) { var19 = params[288]; } else { var19 = params[289]; } } } else { if (input[2] <= -1.133669689297676) { if (input[4] <= -1.919716238975525) { var19 = params[290]; } else { var19 = params[291]; } } else { if (input[7] <= 0.5) { var19 = params[292]; } else { var19 = params[293]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.7146458029747009) { if (input[0] <= -0.7500385642051697) { var19 = params[294]; } else { var19 = params[295]; } } else { if (input[0] <= 0.5618996620178223) { var19 = params[296]; } else { var19 = params[297]; } } } else { if (input[0] <= 0.5017509460449219) { if (input[7] <= 0.5) { var19 = params[298]; } else { var19 = params[299]; } } else { if (input[9] <= 0.5) { var19 = params[300]; } else { var19 = params[301]; } } } } double var20; if (input[0] <= -1.1047260165214539) { if (input[6] <= 0.5) { if (input[5] <= 0.5) { if (input[0] <= -1.4813202023506165) { var20 = params[302]; } else { var20 = params[303]; } } else { if (input[0] <= -1.126632809638977) { var20 = params[304]; } else { var20 = params[305]; } } } else { if (input[13] <= -0.5) { var20 = params[306]; } else { if (input[4] <= -1.919716238975525) { var20 = params[307]; } else { var20 = params[308]; } } } } else { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[0] <= -0.6604486405849457) { var20 = params[309]; } else { var20 = params[310]; } } else { if (input[0] <= -0.412002831697464) { var20 = params[311]; } else { var20 = params[312]; } } } else { if (input[0] <= -0.656269907951355) { if (input[12] <= 0.5) { var20 = params[313]; } else { var20 = params[314]; } } else { if (input[0] <= 0.40234731137752533) { var20 = params[315]; } else { var20 = params[316]; } } } } double var21; if (input[0] <= -1.1047260165214539) { if (input[4] <= -0.7579967528581619) { if (input[3] <= 5.450231730937958) { if (input[0] <= -1.4044564366340637) { var21 = params[317]; } else { var21 = params[318]; } } else { if (input[0] <= -1.1504389643669128) { var21 = params[319]; } else { var21 = params[320]; } } } else { if (input[6] <= 0.5) { if (input[2] <= 0.39837120473384857) { var21 = params[321]; } else { var21 = params[322]; } } else { if (input[0] <= -1.2906171679496765) { var21 = params[323]; } else { var21 = params[324]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= 1.4713480472564697) { if (input[13] <= 0.5) { var21 = params[325]; } else { var21 = params[326]; } } else { if (input[0] <= 2.425053358078003) { var21 = params[327]; } else { var21 = params[328]; } } } else { if (input[0] <= 0.5139706432819366) { if (input[0] <= -0.6541171967983246) { var21 = params[329]; } else { var21 = params[330]; } } else { if (input[4] <= -1.5324764251708984) { var21 = params[331]; } else { var21 = params[332]; } } } } double var22; if (input[0] <= -0.8563434779644012) { if (input[4] <= -0.628916785120964) { if (input[7] <= 0.5) { if (input[0] <= -1.4446611404418945) { var22 = params[333]; } else { var22 = params[334]; } } else { if (input[13] <= -0.5) { var22 = params[335]; } else { var22 = params[336]; } } } else { if (input[6] <= 0.5) { if (input[0] <= -1.4768248796463013) { var22 = params[337]; } else { var22 = params[338]; } } else { if (input[0] <= -1.3162594437599182) { var22 = params[339]; } else { var22 = params[340]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.7834686040878296) { if (input[0] <= -0.8546973168849945) { var22 = params[341]; } else { var22 = params[342]; } } else { if (input[0] <= 0.4723730683326721) { var22 = params[343]; } else { var22 = params[344]; } } } else { if (input[0] <= 0.8184497058391571) { if (input[0] <= -0.600046694278717) { var22 = params[345]; } else { var22 = params[346]; } } else { if (input[0] <= 2.063591241836548) { var22 = params[347]; } else { var22 = params[348]; } } } } double var23; if (input[0] <= -1.09332937002182) { if (input[6] <= 0.5) { if (input[8] <= 0.5) { if (input[2] <= 0.39837120473384857) { var23 = params[349]; } else { var23 = params[350]; } } else { if (input[5] <= 0.5) { var23 = params[351]; } else { var23 = params[352]; } } } else { if (input[2] <= 0.39837120473384857) { if (input[0] <= -1.5286160707473755) { var23 = params[353]; } else { var23 = params[354]; } } else { if (input[0] <= -1.4621992111206055) { var23 = params[355]; } else { var23 = params[356]; } } } } else { if (input[6] <= 0.5) { if (input[3] <= 5.450231730937958) { if (input[0] <= 1.4455791115760803) { var23 = params[357]; } else { var23 = params[358]; } } else { if (input[2] <= -2.6657105684280396) { var23 = params[359]; } else { var23 = params[360]; } } } else { if (input[0] <= -0.5590822398662567) { if (input[0] <= -0.5637042224407196) { var23 = params[361]; } else { var23 = params[362]; } } else { if (input[0] <= 0.7276568412780762) { var23 = params[363]; } else { var23 = params[364]; } } } } double var24; if (input[0] <= -1.0078548789024353) { if (input[6] <= 0.5) { if (input[2] <= -1.133669689297676) { if (input[13] <= -0.5) { var24 = params[365]; } else { var24 = params[366]; } } else { if (input[0] <= -1.0181118249893188) { var24 = params[367]; } else { var24 = params[368]; } } } else { if (input[0] <= -1.341078758239746) { if (input[0] <= -1.345510721206665) { var24 = params[369]; } else { var24 = params[370]; } } else { if (input[2] <= -1.133669689297676) { var24 = params[371]; } else { var24 = params[372]; } } } } else { if (input[6] <= 0.5) { if (input[4] <= -0.3707568794488907) { if (input[1] <= 20.545328298583627) { var24 = params[373]; } else { var24 = params[374]; } } else { if (input[0] <= -0.10809359326958656) { var24 = params[375]; } else { var24 = params[376]; } } } else { if (input[7] <= 0.5) { if (input[0] <= 3.844815969467163) { var24 = params[377]; } else { var24 = params[378]; } } else { if (input[0] <= 0.20752882212400436) { var24 = params[379]; } else { var24 = params[380]; } } } } double var25; if (input[0] <= -1.093962550163269) { if (input[6] <= 0.5) { if (input[4] <= -0.11259698867797852) { if (input[4] <= -1.661556363105774) { var25 = params[381]; } else { var25 = params[382]; } } else { var25 = params[383]; } } else { if (input[0] <= -1.2906171679496765) { if (input[0] <= -1.4162963032722473) { var25 = params[384]; } else { var25 = params[385]; } } else { if (input[4] <= -1.5324764251708984) { var25 = params[386]; } else { var25 = params[387]; } } } } else { if (input[6] <= 0.5) { if (input[5] <= 0.5) { if (input[0] <= -0.5533206462860107) { var25 = params[388]; } else { var25 = params[389]; } } else { if (input[1] <= 20.545328298583627) { var25 = params[390]; } else { var25 = params[391]; } } } else { if (input[0] <= -0.6249925792217255) { if (input[0] <= -0.6280316710472107) { var25 = params[392]; } else { var25 = params[393]; } } else { if (input[0] <= 0.49067093431949615) { var25 = params[394]; } else { var25 = params[395]; } } } } double var26; if (input[0] <= -0.8577364087104797) { if (input[6] <= 0.5) { if (input[5] <= 0.5) { if (input[13] <= -0.5) { var26 = params[396]; } else { var26 = params[397]; } } else { if (input[0] <= -1.392806589603424) { var26 = params[398]; } else { var26 = params[399]; } } } else { if (input[2] <= -1.133669689297676) { if (input[4] <= -1.919716238975525) { var26 = params[400]; } else { var26 = params[401]; } } else { if (input[0] <= -1.2191351652145386) { var26 = params[402]; } else { var26 = params[403]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.7834686040878296) { if (input[0] <= -0.8515948951244354) { var26 = params[404]; } else { var26 = params[405]; } } else { if (input[1] <= 20.545328298583627) { var26 = params[406]; } else { var26 = params[407]; } } } else { if (input[0] <= 0.7063831686973572) { if (input[0] <= -0.5598420202732086) { var26 = params[408]; } else { var26 = params[409]; } } else { if (input[0] <= 0.7436753809452057) { var26 = params[410]; } else { var26 = params[411]; } } } } double var27; if (input[6] <= 0.5) { if (input[0] <= 0.4918105900287628) { if (input[0] <= -1.0668006539344788) { if (input[4] <= -0.628916785120964) { var27 = params[412]; } else { var27 = params[413]; } } else { if (input[1] <= 20.545328298583627) { var27 = params[414]; } else { var27 = params[415]; } } } else { if (input[0] <= 0.618945986032486) { if (input[0] <= 0.5814638137817383) { var27 = params[416]; } else { var27 = params[417]; } } else { if (input[0] <= 0.6213519275188446) { var27 = params[418]; } else { var27 = params[419]; } } } } else { if (input[0] <= -0.8718554973602295) { if (input[2] <= -1.133669689297676) { if (input[4] <= -1.919716238975525) { var27 = params[420]; } else { var27 = params[421]; } } else { if (input[0] <= -1.3780543804168701) { var27 = params[422]; } else { var27 = params[423]; } } } else { if (input[0] <= 0.5256838202476501) { if (input[7] <= 0.5) { var27 = params[424]; } else { var27 = params[425]; } } else { if (input[4] <= -1.5324764251708984) { var27 = params[426]; } else { var27 = params[427]; } } } } double var28; if (input[0] <= -0.8577364087104797) { if (input[6] <= 0.5) { if (input[4] <= -1.661556363105774) { if (input[3] <= 16.507580757141113) { var28 = params[428]; } else { var28 = params[429]; } } else { if (input[0] <= -1.4784077405929565) { var28 = params[430]; } else { var28 = params[431]; } } } else { if (input[0] <= -0.8635613322257996) { if (input[0] <= -1.3146132826805115) { var28 = params[432]; } else { var28 = params[433]; } } else { if (input[4] <= -0.11259698867797852) { var28 = params[434]; } else { var28 = params[435]; } } } } else { if (input[6] <= 0.5) { if (input[0] <= -0.7837218642234802) { if (input[0] <= -0.8006901144981384) { var28 = params[436]; } else { var28 = params[437]; } } else { if (input[3] <= 5.450231730937958) { var28 = params[438]; } else { var28 = params[439]; } } } else { if (input[0] <= -0.6540538966655731) { if (input[12] <= 0.5) { var28 = params[440]; } else { var28 = params[441]; } } else { if (input[7] <= 0.5) { var28 = params[442]; } else { var28 = params[443]; } } } } double var29; if (input[0] <= -1.0892139077186584) { if (input[6] <= 0.5) { if (input[13] <= -0.5) { var29 = params[444]; } else { if (input[0] <= -1.2200848460197449) { var29 = params[445]; } else { var29 = params[446]; } } } else { if (input[2] <= -1.133669689297676) { if (input[0] <= -1.4477635622024536) { var29 = params[447]; } else { var29 = params[448]; } } else { if (input[0] <= -1.2912502884864807) { var29 = params[449]; } else { var29 = params[450]; } } } } else { if (input[6] <= 0.5) { if (input[4] <= 0.016482964158058167) { if (input[0] <= -0.7861911058425903) { var29 = params[451]; } else { var29 = params[452]; } } else { if (input[0] <= 0.24589736759662628) { var29 = params[453]; } else { var29 = params[454]; } } } else { if (input[0] <= -0.566679984331131) { if (input[0] <= -0.8577364087104797) { var29 = params[455]; } else { var29 = params[456]; } } else { if (input[7] <= 0.5) { var29 = params[457]; } else { var29 = params[458]; } } } } return (var0 + var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8 + var9 + var10 + var11 + var12 + var13 + var14 + var15 + var16 + var17 + var18 + var19 + var20 + var21 + var22 + var23 + var24 + var25 + var26 + var27 + var28 + var29) * 0.03333333333333333; } }
72,943
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Capacity_right_before_left.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/Capacity_right_before_left.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; /** * Generated model, do not modify. */ public class Capacity_right_before_left implements FeatureRegressor { @Override public double predict(Object2DoubleMap<String> ft) { double[] data = new double[14]; data[0] = (ft.getDouble("length") - 143.2389153599584) / 82.89404850064653; data[1] = (ft.getDouble("speed") - 8.335057610673134) / 0.16560556934846477; data[2] = (ft.getDouble("numFoes") - 2.2646625660573507) / 0.5530393650197418; data[3] = (ft.getDouble("numLanes") - 1.001732651823616) / 0.04742831736799205; data[4] = (ft.getDouble("junctionSize") - 10.911721389586763) / 3.6843422614733417; data[5] = ft.getDouble("dir_l"); data[6] = ft.getDouble("dir_r"); data[7] = ft.getDouble("dir_s"); data[8] = ft.getDouble("dir_multiple_s"); data[9] = ft.getDouble("dir_exclusive"); data[10] = ft.getDouble("priority_lower"); data[11] = ft.getDouble("priority_equal"); data[12] = ft.getDouble("priority_higher"); data[13] = ft.getDouble("changeNumLanes"); for (int i = 0; i < data.length; i++) if (Double.isNaN(data[i])) throw new IllegalArgumentException("Invalid data at index: " + i); return score(data); } public static double score(double[] input) { double var0; if (input[6] >= 0.5) { if (input[0] >= -1.5304345) { if (input[0] >= -0.8743561) { var0 = 543.02203; } else { if (input[0] >= -1.358649) { var0 = 551.5959; } else { var0 = 537.0214; } } } else { var0 = 490.56137; } } else { if (input[7] >= 0.5) { if (input[5] >= 0.5) { if (input[0] >= -1.4772341) { var0 = 562.7193; } else { var0 = 508.44012; } } else { if (input[2] >= -1.3826549) { var0 = 481.01984; } else { var0 = 552.8317; } } } else { if (input[2] >= -1.3826549) { var0 = 406.14957; } else { if (input[4] >= -2.2831) { var0 = 423.45297; } else { var0 = 532.2111; } } } } double var1; if (input[6] >= 0.5) { if (input[0] >= 0.11612516) { var1 = 354.51038; } else { var1 = 358.45264; } } else { if (input[7] >= 0.5) { if (input[5] >= 0.5) { var1 = 368.85345; } else { if (input[4] >= -1.4688432) { var1 = 316.52917; } else { var1 = 365.6316; } } } else { if (input[4] >= -2.011681) { var1 = 268.80936; } else { var1 = 360.54126; } } } double var2; if (input[0] >= -1.5846001) { if (input[0] >= -0.06452714) { if (input[0] >= 2.3802202) { if (input[0] >= 2.3961442) { var2 = 227.44934; } else { var2 = 195.80382; } } else { var2 = 233.4072; } } else { if (input[0] >= -1.4278337) { if (input[5] >= 0.5) { var2 = 239.41277; } else { var2 = 234.45143; } } else { if (input[4] >= -0.11174896) { var2 = 196.45692; } else { var2 = 221.93068; } } } } else { var2 = 170.41333; } double var3; if (input[6] >= 0.5) { if (input[0] >= -0.9497535) { if (input[0] >= 2.3870964) { if (input[0] >= 2.4688876) { var3 = 150.76233; } else { var3 = 134.64958; } } else { if (input[4] >= -0.6545867) { var3 = 153.18239; } else { var3 = 157.96965; } } } else { if (input[0] >= -1.3503251) { if (input[0] >= -1.2762547) { var3 = 157.86868; } else { var3 = 167.71962; } } else { if (input[0] >= -1.375719) { var3 = 135.61624; } else { var3 = 152.26018; } } } } else { if (input[7] >= 0.5) { if (input[0] >= 0.20069094) { if (input[4] >= -0.6545867) { var3 = 153.88422; } else { var3 = 138.51962; } } else { if (input[0] >= -1.4451449) { var3 = 162.93457; } else { var3 = 131.97504; } } } else { if (input[0] >= -1.0968087) { if (input[4] >= -2.011681) { var3 = 89.50018; } else { var3 = 155.0651; } } else { var3 = 119.29793; } } } double var4; if (input[4] >= -0.6545867) { if (input[6] >= 0.5) { if (input[4] >= 0.838217) { if (input[0] >= -1.5008787) { var4 = 100.17956; } else { var4 = 125.07426; } } else { if (input[0] >= -1.5846001) { var4 = 101.55701; } else { var4 = 33.580494; } } } else { if (input[4] >= -0.38316783) { if (input[0] >= -0.45767957) { var4 = 104.90588; } else { var4 = 75.31006; } } else { if (input[0] >= -0.33577698) { var4 = 101.95027; } else { var4 = 110.16751; } } } } else { if (input[6] >= 0.5) { if (input[4] >= -1.6045527) { if (input[0] >= -0.6972625) { var4 = 104.37561; } else { var4 = 96.292656; } } else { if (input[7] >= 0.5) { var4 = 116.222946; } else { var4 = 105.27524; } } } else { if (input[4] >= -2.011681) { if (input[7] >= 0.5) { var4 = 92.31727; } else { var4 = 62.111286; } } else { if (input[0] >= -0.8903403) { var4 = 113.45996; } else { var4 = 98.70161; } } } } double var5; if (input[0] >= -1.6262195) { if (input[0] >= -1.5846001) { if (input[0] >= -0.8740545) { if (input[0] >= -0.84691143) { var5 = 66.37503; } else { var5 = 57.4509; } } else { if (input[4] >= -1.061715) { var5 = 70.12865; } else { var5 = 62.45739; } } } else { var5 = 15.395686; } } else { var5 = 101.0086; } double var6; if (input[5] >= 0.5) { if (input[6] >= 0.5) { if (input[0] >= -1.3524363) { if (input[0] >= -1.2760134) { var6 = 43.219643; } else { var6 = 61.00119; } } else { if (input[0] >= -1.3763222) { var6 = -16.218624; } else { var6 = 41.674767; } } } else { if (input[0] >= 0.5568082) { if (input[0] >= 0.57478297) { var6 = 40.5038; } else { var6 = 17.24149; } } else { if (input[7] >= 0.5) { var6 = 49.03576; } else { var6 = 25.952227; } } } } else { if (input[6] >= 0.5) { if (input[0] >= -0.92671204) { if (input[0] >= -0.7916602) { var6 = 42.48562; } else { var6 = 38.10122; } } else { if (input[4] >= -1.6045527) { var6 = 46.721798; } else { var6 = 63.55647; } } } else { if (input[4] >= -1.4688432) { if (input[0] >= -0.45044142) { var6 = 36.77849; } else { var6 = 0.25321835; } } else { if (input[0] >= -0.6943673) { var6 = 55.99813; } else { var6 = 37.537594; } } } } double var7; if (input[4] >= -1.7402622) { if (input[0] >= -1.3696872) { if (input[0] >= -0.5538868) { if (input[0] >= 2.8411098) { var7 = 22.419878; } else { var7 = 28.323011; } } else { if (input[4] >= -1.061715) { var7 = 30.736572; } else { var7 = 24.638706; } } } else { if (input[0] >= -1.3775889) { var7 = -9.827128; } else { if (input[0] >= -1.4211384) { var7 = 19.67911; } else { var7 = 26.064049; } } } } else { if (input[0] >= -1.3551506) { if (input[7] >= 0.5) { if (input[0] >= 1.2156613) { var7 = 16.103474; } else { var7 = 36.99192; } } else { if (input[0] >= -0.92671204) { var7 = 28.380285; } else { var7 = 20.853481; } } } else { var7 = 47.911446; } } double var8; if (input[3] >= 10.505693) { var8 = -1.3740605; } else { if (input[2] >= -1.3826549) { if (input[4] >= -1.061715) { if (input[0] >= -1.4658943) { var8 = 19.018583; } else { var8 = 9.421148; } } else { if (input[6] >= 0.5) { var8 = 22.61962; } else { var8 = 2.840992; } } } else { if (input[0] >= -1.2745054) { if (input[0] >= -1.2036319) { var8 = 22.45902; } else { var8 = -3.9138093; } } else { if (input[0] >= -1.4386306) { var8 = 31.737265; } else { var8 = 44.07152; } } } } double var9; if (input[0] >= 0.5568082) { if (input[0] >= 0.56284) { if (input[0] >= 2.8411098) { if (input[4] >= -0.92600554) { var9 = 9.682289; } else { var9 = -4.70924; } } else { if (input[0] >= 2.476005) { var9 = 14.64853; } else { var9 = 11.442158; } } } else { var9 = -20.384542; } } else { if (input[3] >= 10.505693) { var9 = -13.706076; } else { if (input[8] >= 0.5) { if (input[0] >= -0.58766484) { var9 = 23.868244; } else { var9 = 37.65763; } } else { if (input[0] >= -1.6226003) { var9 = 12.734839; } else { var9 = 31.730734; } } } } double var10; if (input[2] >= -1.3826549) { if (input[0] >= -1.4278337) { if (input[0] >= -1.4233701) { if (input[4] >= -0.6545867) { var10 = 8.150048; } else { var10 = 0.9488669; } } else { var10 = 45.64961; } } else { if (input[4] >= -0.92600554) { if (input[0] >= -1.4402592) { var10 = -15.72133; } else { var10 = 5.2316422; } } else { var10 = -28.511341; } } } else { if (input[0] >= -1.3562965) { if (input[0] >= -1.2368671) { if (input[0] >= -1.0021698) { var10 = 10.42216; } else { var10 = 19.795193; } } else { if (input[0] >= -1.2951945) { var10 = -5.035073; } else { var10 = -15.515878; } } } else { if (input[4] >= -1.7402622) { var10 = 28.46493; } else { var10 = 15.796429; } } } double var11; if (input[6] >= 0.5) { if (input[0] >= -1.6146384) { if (input[0] >= -1.5304345) { if (input[0] >= -1.5124598) { var11 = 5.0131564; } else { var11 = 27.167768; } } else { var11 = -23.874939; } } else { var11 = 35.637455; } } else { if (input[0] >= 0.21221167) { if (input[5] >= 0.5) { if (input[0] >= 0.3298317) { var11 = 4.202126; } else { var11 = 9.688707; } } else { if (input[0] >= 0.7130317) { var11 = 10.963935; } else { var11 = -36.82294; } } } else { if (input[3] >= 10.505693) { var11 = -20.268118; } else { if (input[0] >= -1.2059842) { var11 = 8.79956; } else { var11 = 3.1335795; } } } } double var12; if (input[8] >= 0.5) { if (input[4] >= -1.7402622) { var12 = 34.82415; } else { if (input[0] >= -0.38409168) { var12 = -0.02732322; } else { var12 = 3.823143; } } } else { if (input[0] >= -1.6343021) { if (input[0] >= -1.5936477) { if (input[0] >= -1.5440061) { var12 = 3.3823683; } else { var12 = 17.747597; } } else { var12 = -34.317272; } } else { var12 = 25.036434; } } double var13; if (input[8] >= 0.5) { if (input[3] >= 10.505693) { var13 = 23.745955; } else { if (input[4] >= -2.011681) { var13 = 9.957307; } else { var13 = 2.5570643; } } } else { if (input[5] >= 0.5) { if (input[2] >= 0.42553467) { if (input[4] >= -0.11174896) { var13 = 1.8485298; } else { var13 = -4.337325; } } else { if (input[7] >= 0.5) { var13 = 3.8602858; } else { var13 = 2.2540298; } } } else { if (input[6] >= 0.5) { if (input[4] >= -1.6045527) { var13 = 1.7718652; } else { var13 = 4.742608; } } else { if (input[4] >= -2.2831) { var13 = -9.571589; } else { var13 = 12.383347; } } } } double var14; if (input[3] >= 10.505693) { var14 = -10.783418; } else { if (input[0] >= -1.6343021) { if (input[0] >= -1.5846001) { if (input[0] >= -1.5285044) { var14 = 1.5586574; } else { var14 = 16.950235; } } else { var14 = -18.127615; } } else { var14 = 15.967343; } } double var15; if (input[3] >= 10.505693) { var15 = -15.85842; } else { if (input[0] >= -1.6110797) { if (input[0] >= -1.5304345) { if (input[0] >= -1.5166218) { var15 = 0.9036607; } else { var15 = 21.02109; } } else { if (input[0] >= -1.5474442) { var15 = -10.50429; } else { var15 = -21.103048; } } } else { var15 = 21.620377; } } double var16; if (input[0] >= -1.366611) { if (input[0] >= -1.3592522) { if (input[2] >= -3.1908445) { if (input[5] >= 0.5) { var16 = 0.9689615; } else { var16 = -0.1255827; } } else { if (input[8] >= 0.5) { var16 = 4.1350226; } else { var16 = 17.781046; } } } else { var16 = 31.038706; } } else { if (input[0] >= -1.3758999) { var16 = -26.341656; } else { if (input[0] >= -1.6218766) { if (input[2] >= 0.42553467) { var16 = -10.234127; } else { var16 = 0.55429405; } } else { var16 = -15.756909; } } } double var17; if (input[8] >= 0.5) { if (input[4] >= -1.7402622) { var17 = 26.483034; } else { var17 = 0.117565565; } } else { if (input[4] >= 0.838217) { if (input[4] >= 1.5167642) { if (input[0] >= -0.21031564) { var17 = -6.698242; } else { var17 = 6.0077324; } } else { if (input[0] >= -1.1696728) { var17 = -0.32344314; } else { var17 = 6.0142803; } } } else { if (input[2] >= 0.42553467) { if (input[0] >= -0.84854) { var17 = 0.42032775; } else { var17 = -23.634436; } } else { if (input[0] >= -1.5846001) { var17 = 0.8066593; } else { var17 = -20.790316; } } } } double var18; if (input[3] >= 10.505693) { var18 = -15.158027; } else { if (input[0] >= -1.6157844) { if (input[0] >= -1.5050406) { if (input[0] >= -1.4601038) { var18 = 0.11258989; } else { var18 = 14.442382; } } else { if (input[0] >= -1.5142694) { var18 = -35.922295; } else { var18 = 1.2593673; } } } else { var18 = -20.33668; } } double var19; if (input[8] >= 0.5) { if (input[3] >= 10.505693) { var19 = 23.921568; } else { var19 = 0.49384382; } } else { if (input[9] >= 0.5) { if (input[5] >= 0.5) { if (input[4] >= -0.6545867) { var19 = 0.12744687; } else { var19 = 2.4686174; } } else { if (input[6] >= 0.5) { var19 = 0.22484401; } else { var19 = -6.859681; } } } else { if (input[6] >= 0.5) { if (input[4] >= 3.1452775) { var19 = 0.34566537; } else { var19 = 4.5314803; } } else { var19 = 7.110166; } } } double var20; if (input[0] >= -1.6110797) { if (input[0] >= -1.5474442) { if (input[0] >= -1.5328473) { if (input[0] >= -1.5237997) { var20 = 0.13573115; } else { var20 = -21.876308; } } else { var20 = 14.282313; } } else { var20 = -19.858559; } } else { if (input[0] >= -1.6343021) { var20 = 25.054792; } else { var20 = 19.373396; } } double var21; if (input[0] >= -1.1005484) { if (input[0] >= -1.0699673) { if (input[0] >= 2.6892893) { if (input[0] >= 2.7411628) { var21 = -1.8941181; } else { var21 = -16.262783; } } else { if (input[2] >= -3.1908445) { var21 = 0.07606414; } else { var21 = 6.7022796; } } } else { if (input[0] >= -1.0818498) { if (input[0] >= -1.0771451) { var21 = -19.556412; } else { var21 = -41.727806; } } else { if (input[0] >= -1.0968087) { var21 = 5.044799; } else { var21 = -22.938114; } } } } else { if (input[0] >= -1.1656919) { if (input[0] >= -1.1409011) { if (input[0] >= -1.1366789) { var21 = 5.7243176; } else { var21 = -7.8977947; } } else { if (input[0] >= -1.1557393) { var21 = 9.533543; } else { var21 = 14.563201; } } } else { if (input[0] >= -1.1700348) { var21 = -26.660381; } else { if (input[0] >= -1.1798666) { var21 = 13.019152; } else { var21 = 1.886038; } } } } double var22; if (input[4] >= -1.061715) { if (input[0] >= -1.5846001) { if (input[2] >= 0.42553467) { if (input[0] >= -1.3445346) { var22 = -0.22792563; } else { var22 = -11.211833; } } else { if (input[0] >= -1.5285044) { var22 = 0.23592049; } else { var22 = 29.51904; } } } else { var22 = -13.298237; } } else { if (input[7] >= 0.5) { if (input[6] >= 0.5) { if (input[0] >= -0.061511233) { var22 = -3.6082382; } else { var22 = 3.9404857; } } else { if (input[0] >= 2.105291) { var22 = -14.739092; } else { var22 = 6.560977; } } } else { if (input[6] >= 0.5) { if (input[4] >= -2.2831) { var22 = 3.27665; } else { var22 = -6.206473; } } else { if (input[4] >= -2.011681) { var22 = -16.98648; } else { var22 = -2.0693188; } } } } double var23; if (input[0] >= -1.6110797) { if (input[0] >= -1.5304345) { if (input[0] >= -1.4247575) { if (input[0] >= -1.4069637) { var23 = 0.0058279335; } else { var23 = -12.574236; } } else { if (input[0] >= -1.4281353) { var23 = 28.729404; } else { var23 = 1.0624564; } } } else { if (input[0] >= -1.5441871) { var23 = -21.719168; } else { var23 = -6.0660253; } } } else { if (input[0] >= -1.6262195) { var23 = 8.824266; } else { var23 = 17.930897; } } double var24; if (input[0] >= -1.2988136) { if (input[0] >= -1.2829499) { if (input[9] >= 0.5) { if (input[4] >= -1.061715) { var24 = 0.078482985; } else { var24 = -2.069406; } } else { if (input[4] >= -1.7402622) { var24 = 2.6634102; } else { var24 = 10.424127; } } } else { if (input[5] >= 0.5) { var24 = 11.484903; } else { var24 = 4.8381333; } } } else { if (input[0] >= -1.3074391) { var24 = -24.193026; } else { if (input[0] >= -1.3154614) { var24 = 11.129827; } else { if (input[4] >= 0.023960479) { var24 = 3.2866764; } else { var24 = -2.8106174; } } } } double var25; if (input[3] >= 10.505693) { var25 = -13.873767; } else { if (input[0] >= -1.0870372) { if (input[0] >= -1.0699673) { if (input[0] >= -0.9522869) { var25 = -0.12327542; } else { var25 = 1.7734003; } } else { if (input[2] >= 0.42553467) { var25 = -27.763315; } else { var25 = -4.3645062; } } } else { if (input[0] >= -1.0944563) { var25 = 11.844988; } else { if (input[0] >= -1.0986183) { var25 = -14.054545; } else { var25 = 1.4738897; } } } } double var26; if (input[3] >= 10.505693) { var26 = -12.905225; } else { if (input[13] >= 0.5) { if (input[8] >= 0.5) { var26 = -8.218271; } else { var26 = -2.7714384; } } else { if (input[2] >= -3.1908445) { if (input[5] >= 0.5) { var26 = 0.1919713; } else { var26 = -0.34239304; } } else { var26 = 13.057341; } } } double var27; if (input[0] >= -1.6110797) { if (input[5] >= 0.5) { if (input[0] >= -1.3544871) { if (input[4] >= 0.838217) { var27 = -0.28236327; } else { var27 = 0.49259615; } } else { if (input[4] >= -1.061715) { var27 = -6.032808; } else { var27 = 6.1769953; } } } else { if (input[0] >= -0.27232254) { if (input[6] >= 0.5) { var27 = 0.30610603; } else { var27 = 7.8584433; } } else { if (input[6] >= 0.5) { var27 = -0.79939336; } else { var27 = -9.435571; } } } } else { var27 = 11.286037; } double var28; if (input[3] >= 10.505693) { var28 = 7.1790824; } else { if (input[4] >= -1.7402622) { if (input[13] >= 0.5) { var28 = -4.953042; } else { if (input[7] >= 0.5) { var28 = 0.11932213; } else { var28 = -0.42846715; } } } else { if (input[6] >= 0.5) { if (input[4] >= -2.2831) { var28 = 6.0286536; } else { var28 = -3.695003; } } else { if (input[4] >= -2.2831) { var28 = -3.099296; } else { var28 = 4.8989415; } } } } double var29; if (input[4] >= -0.38316783) { if (input[0] >= -1.5389395) { if (input[0] >= -1.463361) { if (input[0] >= -1.0731037) { var29 = -0.045030884; } else { var29 = 4.8160086; } } else { var29 = -14.874015; } } else { var29 = 22.95401; } } else { if (input[0] >= -1.6187401) { if (input[0] >= -1.4884533) { if (input[0] >= -1.4665577) { var29 = -0.22108805; } else { var29 = -22.836859; } } else { if (input[0] >= -1.5106503) { var29 = 20.822256; } else { var29 = 3.0943563; } } } else { var29 = -25.067308; } } return 0.5 + (var0 + var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8 + var9 + var10 + var11 + var12 + var13 + var14 + var15 + var16 + var17 + var18 + var19 + var20 + var21 + var22 + var23 + var24 + var25 + var26 + var27 + var28 + var29); } }
36,587
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
FixNetworkV5.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/FixNetworkV5.java
package org.matsim.prepare.network; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.application.CommandSpec; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.InputOptions; import org.matsim.application.options.OutputOptions; import org.matsim.core.network.NetworkUtils; import picocli.CommandLine; import java.util.Map; /** * This class won't be necesarry with a updated network. */ @CommandLine.Command(name = "fix-network-v5", description = "Apply corrects to the v5 network.") @CommandSpec( requireNetwork = true, produces = "network.xml.gz" ) @Deprecated public class FixNetworkV5 implements MATSimAppCommand { @CommandLine.Mixin private final InputOptions input = InputOptions.ofCommand(FixNetworkV5.class); @CommandLine.Mixin private final OutputOptions output = OutputOptions.ofCommand(FixNetworkV5.class); public static void main(String[] args) { new FixNetworkV5().execute(args); } @Override public Integer call() throws Exception { Network network = input.getNetwork(); fixLinks(network.getLinks()); NetworkUtils.writeNetwork(network, output.getPath().toString()); return 0; } private void fixLinks(Map<Id<Link>, ? extends Link> links) { // Subtract a bus lane manually links.get(Id.createLinkId("106347")).setNumberOfLanes(2); links.get(Id.createLinkId("138826")).setNumberOfLanes(2); links.get(Id.createLinkId("154291")).setNumberOfLanes(2); links.get(Id.createLinkId("7875")).setNumberOfLanes(3); links.get(Id.createLinkId("106330")).setNumberOfLanes(2); } }
1,660
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PrepareNetworkParams.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/PrepareNetworkParams.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; 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.IdMap; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.application.CommandSpec; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.InputOptions; import org.matsim.application.options.OutputOptions; import org.matsim.core.network.NetworkUtils; import org.matsim.core.utils.io.IOUtils; import picocli.CommandLine; import java.io.IOException; import java.util.List; import java.util.Map; @CommandLine.Command( name = "network-params", description = "Apply network parameters for capacity and speed." ) @CommandSpec( requireNetwork = true, requires = "features.csv", produces = "network.xml.gz" ) @Deprecated public class PrepareNetworkParams implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(PrepareNetworkParams.class); @CommandLine.Mixin private final InputOptions input = InputOptions.ofCommand(PrepareNetworkParams.class); @CommandLine.Mixin private final OutputOptions output = OutputOptions.ofCommand(PrepareNetworkParams.class); private int warn = 0; public static void main(String[] args) { new PrepareNetworkParams().execute(args); } /** * Theoretical capacity. */ private static double capacityEstimate(double v) { // headway double tT = 1.2; // car length double lL = 7.0; double Qc = v / (v * tT + lL); return 3600 * Qc; } /** * Read network edge features from csv. */ static Map<Id<Link>, Feature> readFeatures(String input, int size) throws IOException { Map<Id<Link>, Feature> features = new IdMap<>(Link.class, size); try (CSVParser reader = new CSVParser(IOUtils.getBufferedReader(input), CSVFormat.DEFAULT.builder().setHeader().setSkipHeaderRecord(true).build())) { List<String> header = reader.getHeaderNames(); for (CSVRecord row : reader) { Id<Link> id = Id.createLinkId(row.get("edgeId")); Object2DoubleOpenHashMap<String> ft = new Object2DoubleOpenHashMap<>(); ft.defaultReturnValue(Double.NaN); for (String column : header) { String v = row.get(column); try { ft.put(column, Double.parseDouble(v)); } catch (NumberFormatException e) { // every not equal to True will be false ft.put(column, Boolean.parseBoolean(v) ? 1 : 0); } } features.put(id, new Feature(row.get("junctionType"), ft)); } } return features; } @Override public Integer call() throws Exception { Network network = input.getNetwork(); Map<Id<Link>, Feature> features = readFeatures(input.getPath("features.csv"), network.getLinks().size()); for (Link link : network.getLinks().values()) { Feature ft = features.get(link.getId()); applyChanges(link, ft.junctionType, ft.features); } log.warn("Observed {} warnings out of {} links", warn, network.getLinks().size()); NetworkUtils.writeNetwork(network, output.getPath("network.xml.gz").toString()); return 0; } /** * Apply speed and capacity models and apply changes. */ private void applyChanges(Link link, String junctionType, Object2DoubleMap<String> features) { String type = NetworkUtils.getHighwayType(link); FeatureRegressor capacity = switch (junctionType) { case "traffic_light" -> new Capacity_traffic_light(); case "right_before_left" -> new Capacity_right_before_left(); case "priority" -> new Capacity_priority(); default -> throw new IllegalArgumentException("Unknown type: " + junctionType); }; double perLane = capacity.predict(features); double cap = capacityEstimate(features.getDouble("speed")); boolean modified = false; // Minimum thresholds double threshold = switch (junctionType) { // traffic light can reduce capacity at least to 50% (with equal green split) case "traffic_light" -> 0.4; case "right_before_left" -> 0.6; // Motorways are kept at their max theoretical capacity case "priority" -> type.startsWith("motorway") ? 1 : 0.8; default -> throw new IllegalArgumentException("Unknown type: " + junctionType); }; if (perLane < cap * threshold) { log.warn("Increasing capacity per lane on {} ({}, {}) from {} to {}", link.getId(), type, junctionType, perLane, cap * threshold); perLane = cap * threshold; modified = true; } link.setCapacity(link.getNumberOfLanes() * perLane); double speedFactor = 1.0; if (!type.startsWith("motorway")) { FeatureRegressor speedModel = switch (junctionType) { case "traffic_light" -> new Speedrelative_traffic_light(); case "right_before_left" -> new Speedrelative_right_before_left(); case "priority" -> new Speedrelative_priority(); default -> throw new IllegalArgumentException("Unknown type: " + junctionType); }; speedFactor = speedModel.predict(features); if (speedFactor > 1) { log.warn("Reducing speed factor on {} from {} to 1", link.getId(), speedFactor); speedFactor = 1; modified = true; } // Threshold for very low speed factors if (speedFactor < 0.25) { log.warn("Increasing speed factor on {} from {} to 0.25", link, speedFactor); speedFactor = 0.25; modified = true; } } if (modified) warn++; link.setFreespeed((double) link.getAttributes().getAttribute("allowed_speed") * speedFactor); link.getAttributes().putAttribute("speed_factor", speedFactor); } record Feature(String junctionType, Object2DoubleMap<String> features) { } }
5,846
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Speedrelative_priority.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/Speedrelative_priority.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; /** * Generated model, do not modify. */ public final class Speedrelative_priority implements FeatureRegressor { public static Speedrelative_priority INSTANCE = new Speedrelative_priority(); public static final double[] DEFAULT_PARAMS = {0.8929842014268579, 0.8947034806870571, 0.8969997893375394, 0.8988690670884303, 0.8919660847748271, 0.898741523864776, 0.896932363265675, 0.8942835732422608, 0.8894293065747837, 0.8916650956941955, 0.8915898183047055, 0.8887579511683131, 0.893293460019746, 0.8935403651436455, 0.8891393883339468, 0.8968624721923842, 0.8916676123723914, 0.888741320626169, 0.8923453802464755, 0.8939105471430318, 0.892045777506383, 0.8884261914324344, 0.8942743321122739, 0.8897698102348497, 0.88992276348519, 0.88344088895989, 0.8864393596444606, 0.8959343964806725, 0.8939554190775862, 0.8942056855950486, 0.8886954872446198, 0.8946189865866182, 0.0035946893269604083, -0.00037586783071427075, 0.0014564712582525053, 0.004358285565462845, -0.0005278396452887324, 0.004656046665723653, 0.002944322242242215, 0.0002687904470097077, -0.009153251607334009, -0.0018077473617709285, -0.0014800508184662099, -0.0017572335150929548, -0.005491935295157103, -9.210054608028862e-05, -0.002050273646797897, -0.00023359793369099571, -0.004366236929616469, -0.0011748712003885934, -0.006171831121892263, -0.0007003414042384324, -0.0036582584558239196, 0.0001814143704377232, 0.0005819983416323589, -0.0031571570805645622, -0.0031019715266897094, -0.009091269706686212, -0.006316004107230821, -0.0021178458266022837, 0.0011072820189547872, -0.004692412549341147, 0.0009133385793177371, 0.0016291670039645452, 0.001652770594504699, 0.00012419473480936572, 0.004358261771246124, -0.00136580977681832, 0.004280427895951118, 0.002752180607391828, 0.0006402668741239056, -0.002526140848493023, -0.008237926283798129, -0.001584395256545445, 0.00028155339830497335, -0.0025667959346123664, -0.007432183609171929, -0.0012495981032841254, -0.0015821468717665326, -1.8938748549666314e-05, -0.0014916459430654467, 7.87662201520331e-05, -0.0038842575659068126, -0.0009597406080185134, -0.005276804077598788, -0.0018214055098514804, 0.0003132810424659884, 0.0006007128713591621, -0.002841441479325621, -0.0027917744765271445, -0.008182142830764128, -0.005684403738227719, -0.003939677840110654, 0.00014074448453617043, 0.0008220047838962739, 0.0014662503306650575, 0.0009219550427784281, -0.004847338271363609, -0.0004030102797075952, -0.0001589834323679818, -0.004537988706511653, 0.003793907323163718, 0.0021194390792565665, -0.001091439812143751, -0.004437441640132822, -0.0016651135136554881, -8.427309692555543e-05, 0.0006845262328391876, -0.008206764201645093, -0.004255284730273494, -0.002778032482514706, -0.007541810796945412, -0.0002807222251177917, -0.0028795331805234357, -0.007969414577631, -0.0038314047381011527, -0.0009824674902464145, 0.0031918677323852017, -0.003559420328913629, -0.0001524865811498478, -0.007274666777568249, 0.0014409376320593736, -0.0015506394854850865, 0.00042483618519344684, -0.00020276328969557613, -0.004012701158608532, 0.0007261924564426816, 0.0013251461948861787, -0.0005851052012524379, 0.0008438854491559348, 0.002682671386129795, -0.00018669483116696926, -0.0028742893987572446, 0.0029090553203494126, 0.001918147029125722, -0.002145687753667822, -0.001271767929665785, -0.0007716068297369867, -0.0032542896816599937, -1.377675524664698e-05, -0.0012189209591586976, 8.732410065335718e-05, -0.0031892019371381726, 0.0027330893756310395, -0.0036368353978987627, -0.0008450129386268499, -0.00043499994359050693, -0.0030779015060099, 0.00022458334085280335, 0.0004825938651956326, -0.007523951579291139, 0.001648097497955805, -0.002394607433016095, -0.00541476657598326, -0.004421717198469776, -0.00021176566181567007, 0.0012629031457715382, -0.000666677033032405, 0.0008708766532030403, 0.0012299148924191578, -0.0012278861079410642, 0.003156789018261936, -0.001648592385600456, -0.00042295589231925536, 0.0031904609749212245, 0.001740654912153055, 0.0008235092529067739, -0.0018306365198825587, -0.0006575762881680733, -0.0030503413245326974, -0.0014631217007757544, 0.0003738617724366614, -0.0026296688048073552, -0.006128947761257038, -0.0027633495935472352, -0.006988527620462874, -0.0015263414153428706, -0.007302009079288266, -0.0032393715567955806, -0.0006451792348851753, 0.002916122917112838, -0.002999270415220012, -5.223151948174142e-05, -0.006430633053745329, 0.0013735492347603752, -0.0013221200705708612, 0.0021486424582700323, 0.00022632882375074354, 2.1968672279220188e-05, -0.0034944829694279183, 0.000604063330381504, 0.001098428913942466, -0.0005312875755322732, 0.0006413306407620539, 0.0021998002204766504, -0.00021368015505860392, -0.00279214764873075, 0.0018424470228973753, -0.005885404542648929, -0.0035685818630842208, -0.0007600464037238111, -0.003162483815919417, -0.0011766261456155804, -0.00517864586038667, -0.0009144736312343811, -0.0005982734118695661, -0.0027059562647969706, -0.0001941600993402244, -0.0026189520071341005, -0.0006697562930759481, 0.0001959225634984838, 1.100380204047289e-05, -0.0027165518031688884, 0.00044005140327862523, -0.006696589436244804, -0.0007719561764204463, -0.0028438656300014483, -0.004893818947924601, -0.006253032810655326, -0.0011559555373227568, 0.0010973031569336837, -0.0008209567858038394, 0.0007137379247819497, 0.001034685390941133, 0.0021135971068710446, 0.0005042045951812604, -0.0022486840637737423, 0.0011274972106418628, -0.0009631093840322659, 0.0022300345173954183, 0.000612595054772382, 0.0009090122310770721, 0.002815953380963201, -0.0023916732888923774, -0.0012765360755545175, 7.837554093010669e-05, 0.00133042329835432, -0.0013806108893186881, -0.006042484158066969, -0.004504017631982265, -0.000841071364687062, 0.002609536733701188, 0.00022527899788642183, 0.002222998668323341, 0.00014475240505091948, -0.005179480430109434, -0.0016477633006311385, -0.0006122974647876724, -0.00016992457588491038, -0.0003512265007903106, -0.00662229506688598, -0.0031345056764943875, 0.0007279580263152467, -2.9018376539293742e-05, 0.0011228357856237813, -0.00031250222610473187, -0.0010201841322743722, 0.0025765900626661085, -0.004987953528160748, 0.0016450026919441264, -0.001442820546918389, 0.0017809630721995085, -0.0006005209607052864, 0.0006175223924028811, -0.0008705249666996861, 0.0012766528192895866, -0.004852559211078187, -0.0012213612651037942, -0.000664619271638752, -0.0021934305100990486, -0.0006965747845645402, 0.00017400688224515374, -0.0014944499318476378, -0.006464869595827621, -0.0001789825048940695, -0.0014381865497085306, 0.00047872923560289847, -0.005589679688677513, -0.00017387237324346843, -0.002117882646894224, -0.004116631155479588, -0.00013648503741375722, -0.0030583935862099334, 0.0004683588334904857, 0.0010105522490347738, -0.0007578563465091826, -0.005741674816348256, 0.0005361467433880649, 0.0017227803799302211, -0.0010597394858117657, -0.0047647283659613075, 0.000939412522228994, -0.0007795879023538469, 0.0010249817815307645, 0.0012123057511939281, -0.0001809903243364967, 0.0006932116130126914, -6.528284124522851e-05, -0.0022528705759192066, -0.000900240071821331, 0.00034257326538389725, 0.0024791980311524697, -0.0027061793031368615, -0.004144560232811441, 0.0019297265225927274, -0.005077553794506504, 0.004563919875706374, 0.0011666348101275698, 0.00026019176177812263, -0.005009143877322564, -0.005951379184993129, -0.0011873269638275783, -0.0005591700633344619, -2.714078935388578e-05, -0.0029329514593271727, -0.0021865483274683233, 0.00010182870469751154, -4.792457786013138e-05, -0.005421556478201636, -0.002562699783922168, 0.0023065582502376563, -0.0044935978445075665, 0.0022975793850694664, -0.0003218694237517478, 0.0008609108747799414, -0.0036480026103118167, -0.0005480733797422501, -0.0011179488625795654, 0.0014399005807338731, -0.0003748210508752406, 0.001462424636644217, -0.002855213711376316, -0.001021211355789432, -0.0027825476187352035, -0.0023700228856700957, -0.0004457948130434087, -0.0016890177231013007, 0.0014656834275651699, -0.00308413551690543, 0.0012716402365587597, 0.00020857804849154965, -0.00012377556799413132, -6.314804663710229e-05, -0.004901266667635024, -0.006977706196747566, -0.0023805111812674894, -1.4154462968598829e-05, -0.0021391926542325104, 0.0004024184172526005, 0.0014579942782765461, -0.0013685105864333783, 0.00042637869590616396, 0.0020759024228549547, -0.004044238043174619, -0.0004673470678984133, -0.0007614489741621794, 0.0017160331928642342, 0.00045098751729422213, -0.002751915740093021, -7.58478226104142e-05, 0.0014452242343456342, 0.0020194658385057915, -0.002591137814039712, -0.004714303682515909, -0.0008658400044970883, -0.0005695236412090362, -0.000919914739518763, -0.00047138748214523246, 0.003221371141426401, 0.00010946398822912357, -0.0006313881754263677, 0.00028675514870511997, -0.004242783124500892, -0.0006059141641506576, -0.00037978559380092314, 0.0005018695924861565, -0.005277603157000345, -0.002823982482228995, -0.0003661808101977544, -0.002447569929623637, 0.0002899334177787877, 0.0013121948146408578, -0.0012316595988830538, 0.00038374078509299125, 0.0019261300658640825, 0.00060404460022287, 0.0018916888366632637, -0.00048133738531045073, -0.0006689718118152455, 0.0020771317174005303, -0.00029771362273803997, 0.00019203470397180899, 0.0009730803566888332, -0.0010785764039548164, -0.0030212189286750644, -0.002227608762060374, -0.00047795255681549434, 0.003388020714684464, -0.0004019306890992964, -0.0017445686838821455, 8.712659864944575e-05, -2.392590566498285e-05, -0.005002815240769641, -0.0015982671861405004, 0.0014176584792663788, 0.00024264137891374102, -1.8581158680176262e-05, -1.5142192658539736e-05, -0.004101132432692541, -0.0021218756544280895, -0.004946513613018059, -0.0008919220509942529, 0.0006224296975045222, 0.0005977526226154771, -0.0004531349416936618, 0.0006393982110620405, 0.001997324211645017, -0.0041189525993420035, 0.002015479348912021, -0.002200247025987949, -3.870243194306074e-06, 0.0012800444197168925, -0.005283784434171608, -0.00039327358204286505, -0.003330551695361645, 0.00015716166914817232, 0.0005092893066194595, 0.0012522634007137868, -0.001392203704336637, 0.0002871200871369374, -0.00024520884375703946, -0.0014372707881021576, 3.883250587326714e-05, 0.0008303101058975327, -0.0005576243562405236, -0.004788509299076939, -0.0011845797367818958, -0.004649032320007146, -0.0030062665952377333, -0.0005233344726748654, -0.003983094500423801, -0.0034293018351513466, -0.000295159596800945, -0.00012444762175908437, -0.0009654469441292314, -0.0056743449637678125, 0.00028710265596348076, -0.002511927530065599, -0.0029786217170417904, 0.0012127794500719857, -0.0003695458562401879, 0.0018071337224504248, -0.002890199582888331, 0.0009534936459175485, -0.005170729927347737, 6.03661519060518e-05, 0.000878157108550888, 0.0043671090055617005, 0.0008697451218208351, -9.65619912183889e-05, 0.002274836970740852, 0.0009407875046723186, -0.0015439916918232898, 1.3232240309950676e-06, -0.001234959962218228, -0.0014243761394037546, -0.0024881557764527065, 0.00013132611120749536, -0.002510629243167608, 0.0018806146646936786, 0.0002923941403538209, -0.0008264528022539357, -0.003753365375315758, -0.0030276019450231396, -0.003324825975657231, -0.0004262652626107844, 0.0005369303620401132, -0.0017768173072849063, 7.280571343440225e-05, 0.000547983275646389, 0.0012050976733727079, 0.0015802596122967871, -0.002469937071941724, 0.004363771757697576, 0.0015523222932550273, -0.0007962916185175952, -0.0005855547466840779, 0.002877534344071026, -0.00022194174904751983, 0.0015440240739653087, 0.00027071296524107315, -0.0009701947478661, 0.00021017635825398124, -0.001650040202845742, 0.0006201092001679992, -0.002858489481784231, -0.0004293877737742847, 0.001113840783985749, -0.0006926370938856859, 0.0034680529958351206, -0.0041327719272129864, -0.0010055915190450453, -0.0004124731680538096, -0.0029186886820710876, -0.0003005701799831656, -0.00014193447448066786, -0.004613265719108652, -0.0014532375391892566, 0.00011055787105790887, -0.002138567345744761, -0.0020096608776732704, -5.5450382378167845e-05, 0.0018654663047373615, -0.0015867457571954826, 0.0003794906353587839, 0.0004300410848480099, -0.00026266061658361566, -0.004499548956305928, -0.000902788710478985, 0.0020803541733895032, -0.000293647577017551, 0.0010963985139188193, -0.000273989443206432, -0.0038307912183812715, 0.00023285402496777048, -0.00033467431023730094, 0.0005434885326987351, -0.002980380184188683, -0.00041277729995545037, -0.004577299620025222, -0.0006207832297724465, -0.0025239270644549757, -0.006624671299510327, -0.000632725083396809, 0.000258530235643995, -0.003708128887636277, -0.000533519895509034, -0.004756165847664406, -0.0005998462094402033, 0.0011963265920507393, 9.665521935084084e-05, -0.0018959939308395117, -0.00203640468157127, -0.0001568229065146378, 0.0016789196752502698, -0.0022051895409365874, 0.0001752667250997519, -0.0014519567049288552, 0.0006688298685532914, 0.0004434874894654633, 0.0015089042000864478, -0.00023639457064097134, -0.004049594015989349, -0.00081250979396651, 0.0018723188062314334, -0.00026428279957191103, 0.0009867586649815834, -0.0010093576499873985, 0.00016583787652050982, 0.0004124403063131259, -0.0005117998136605029, -0.0013599157448429351, 0.0013268565122866584, 0.00017748262902119114, -0.0009452150726843276, -0.00411956961846869, -0.00046710411100514136, -0.002444199689245525, -0.0031114069750769087, -0.00029398964289011124, 0.0020481582815502285, 8.497237125327916e-05, -0.002412989399689751, -0.0008970222374408241, -0.0018327641592305495, -0.0001411405923762223, -0.0002631094481007655, -0.002375024256568494, 0.0010309494478712743, -0.0004521664329725374, -0.0008319602633530625, 0.0011699467752930009, -8.830604561592948e-05, -0.0028763465107334, 0.00041392918061441064, 0.00012769892843216872, -0.0017872333693898853, 0.0004602853005102099, -0.00036224954528652723, 0.0008870000309195433, -0.0006615457709247749, 0.002980810555620287, -0.0014976676345733843, -0.0025698950398455054, 0.0002783655830385584, -0.005333250805514374, -0.002984087351429051, 0.002193776929344003, -0.0040338637995449055, -0.0005836389779224523, -0.00038440948154040586, -0.002970809322356312, 7.025315009043306e-05, -0.0023646857819432836, -0.0006447612529800775, -0.0015867448222346395, -0.0011756819957299298, 0.0001078960645319549, 0.00034639587441448433, 0.00016500408364573786, -0.0010494001662197138, 0.002235899676554094, -0.0019015126543677052, -0.005247232384543711, -0.0040140655089406915, -0.00014289969126538696, 0.0007942960678680859, -0.0038083523043029328, -0.0004932095187147019, -0.004347737418693299, -0.0006928804912560788, -0.003317111501317441, -0.0014505775088429248, -0.0024476693211668197, -0.0006771351605631143, -3.224485465209122e-05, -0.002443173183147365, 0.0007084345033374862, -0.0006543980239472653, -0.004628165489139404, 0.0021575353121933423, -0.0009173562217516436, -0.0048691877295241265, -0.00029480962211080313, 0.00013701893456009035, 0.00032861140608864516, 0.0004630639790038107, 0.0009013041157162646, -0.0019365349586619417, -0.00040187215426655684, 0.0007610652862833785, -0.0017269885975011669, 0.0012879637895324486, -0.0002986716277904944, 0.0002046710963817436, -0.001751365779036051, 0.0004315294590789092, -0.0002947335693452577, 0.0006138804278849974, 0.00046863979375319075, 0.0022012091565167366, -0.004497344824888875, -0.0019231859940072498, 0.0005143160423461737, -0.0009795582387279996, -0.0024239239835029667, -0.0018114894556864342, 0.002228793031959012, 0.00045262966448005585, -0.002311334089299748, -0.000244399189213861, -0.000398000040176715, -0.0016494288611425736, -0.00015450494613730424, 0.0009616942324039929, -0.0036372508965378937, 0.0019835491582428136, -0.0016752249448832937, 4.228192242720207e-05, -0.0014679159972705604, -0.0013531973727877586, 5.646988075778849e-05, -0.002557275172047046, 3.238720169057063e-05, 0.0009926401550071353, -0.0006372001490567615, 0.0001558074672795215, -0.0015762291663560986, 0.00010858097362190217, 0.0005524924006706657, 0.0004217758157085475, -0.001572793139849574, 0.002098606230894445, -0.004103667443380322, -0.0005889178725194165, -0.0021815315338149593, 0.0004777342408543388, -0.0019930714978629942, -0.0002271274559412271, 0.0018634493820859667, -0.0004743682193561049, -0.0013690559544774026, -0.0019888431644020477, -3.308178577289721e-05, 0.0003684159458676641, -0.004721126566714064, -0.0010476555972045642, -0.004898227602030358, -0.0005754476982447466, 0.002050736987703373, -7.804400724822047e-05, -0.0013211243929719101, -0.0012178776581605005, 5.0822866481579286e-05, 0.0004900347910343666, -0.0014169213735355961, -0.000608022803259355, 8.006467544616768e-05, 0.00027913071570168064, -0.0014313753049631243, 0.0007153703245745153, 0.0018975775498113754, -0.00215498107682944, -0.00035327187870654573, -0.003925253060244796, -0.0026607674764743358, 0.0010765239669353122, -0.0021886446212807135, -0.00020796576553769645, -0.00012028398469539448, -0.0018050462385249281, 0.00032972473332263904, -0.003239409469057797, -0.0002769755742464304, 0.00015158084159170614, 0.0008157606323021635, 0.0010828573441005187, -0.0005763313996695805, 0.00026402711256285374, 0.0019865806054997276, -0.0015857846066245703, -0.00015801720402600978, -9.536438544877041e-05, -0.0014817322163817453, 0.0003695347384406354, 0.00020515024242062524, -0.0023721962750720173, 0.0006129312319102138, -0.0005420447415056607, 0.00013070863924552522, -0.002256681328421381, 6.664878555680441e-05, -0.00025324734489062215, -0.005376534606511116, -0.002439427369418069, -0.0007247857221672852, -0.0028332328297223453, 0.0011897280294338836, -0.0008041461872859576, -0.0038619648444764587, 0.0006204491808700723, 0.0010314914984430167, -0.0025558956712712416, -0.0003212411910850811, 0.0018984992523579589, -0.0010526267898045801, -0.0005571343566592745, 0.0020834722727040736, -0.0011493708071032467, 0.0014423669718582543, 0.00044769616854447496, -0.0019651443890431187, 0.00022469292922066257, -0.0008853933172750293, 0.000913338803224837, -0.0003570429495917677, -0.0033751538724344347, 7.327709847976499e-05, -0.0039062124342022775, -0.0007971009218506154, -0.0019218387683571352, -4.0039284168783896e-05, 0.0030400216461339835, 0.0006176156853279432, -0.002347003224692862, 0.00017160850266587492, -0.00042193509775274933, 0.00029714957254781696, 0.00022623493718570872, -0.004530122807863264, -0.0019184689012933477, -0.0025499095762526085, -0.004532061200288242, -0.0023763978348809393, 0.001165761990967983, -0.0029724674667834746, 5.384999067611472e-05, 0.001167423180270441, -0.0006730831434014501, -0.0030276162056105237, 0.0036284447773815387, 0.0014613130663393872, 0.0003168368728617045, -0.0003037009544858498, -0.0018657186283644032, 0.00018671171692936776, 0.0010229679955779216, -0.0007707839826074391, -0.005113134064821313, -0.00037434713856608745, 0.0002065442169227503, 0.0008717432618122509, -0.0019448147333784823, -0.0054899303127898735, -0.0011809376163653212, 0.0005303218009070949, 0.00043927355080290243, -0.0024238636141119814, -0.0009890361232854608, 0.0006849152315372759, 0.00024373234227373028, -0.00176661319799823, -0.004680618864645413, -0.0009262587539811918, 0.001201525974330795, -4.4802255672805636e-05, -0.0019806362787574564, -0.0017216580075793183, -0.0004003367783351657, -0.0022515169247091, -0.00018566322469166117, 0.0009197209883154399, 0.0012171475321542157, 5.766368392089925e-05, 0.00029045538010404634, -0.0016430464179818809, -0.0001485993394711273, -0.0010358076600735673, 0.0005870045752463214, -0.001033503000142661, -0.0009987448927459579, 0.00015479446220258874, -0.0013820639056553537, -0.0020999968978724598, -0.004808529401460508, 0.0014417886748721428, -0.000563142174534198, 0.0004122560935559283, -0.0015112426704853086, -6.965616440621149e-05, 0.002757341804435501, 0.00016275087744050846, -0.001287008842897859, -0.0005351631915063359, 0.0010302128689216419, -0.0022156593520597867, 0.000154624194965164, -0.0029410986938570335, -0.0005407743470675683, 0.00013393672109301684, -0.00412046028147495, 0.00022407833514272377, -0.001495499945373689, 0.0002811269719231851, 0.0033164700825247246, -9.256620680495258e-05, -0.0009908310253067443, -0.0037154644352613096, -0.00012332398085409082, -0.0029700261214825035, -0.00018983325698347447, 8.275486776255085e-06, 0.0010157357522517514, 0.00031052327275918844, 0.0001772898112201941, -0.0017784738811216555, -0.0015064550664692672, -0.0015514727584590457, 0.0012672231337400868, -0.0010532961454194933, -0.004077122128995964, 0.0017886233244073858, 0.0004593072169792452, -0.001929160642718586, -0.00019725211005503288, -0.00038119323143035464, 0.0017795253936850502, -0.00031106686650251344, 0.0019856521713986263, -0.0014505449062938462, -0.004980466538278226, -0.0024694108857360266, 0.00017936641168055212, -0.001842214104887857, 0.0032293144986253047, -0.00015575552599947622, -0.0038081849997693984, -0.00042090225570454897, -7.042423772697952e-05, 0.00018104570246564407, 0.0005536448630447914, 0.0007296210307090124, -0.001157196967252281, -0.0013766655834767665, 0.00010945421576707119, 0.0009536988195713713, -0.0020998878654396643, 0.0010188903383336555, -0.0024249624229271518, -0.0001626240073644725, -0.00409651583436116, 0.0017220217962253485, -7.080498174986765e-05, 0.001505818971092063, -0.0012634505110719462, 0.0008337735296075332, 0.0031530862411922977, -0.0014889629100513025, 0.0011163474056372837, 0.0002476606253812845, -0.00283849846474017, -0.0007627870183321586, 0.0002962592778091484, 0.0009588340117547865, 0.0009075685619896021, -0.0010594475439306373, 0.0001344907769660714, -0.00015887210386992184, 0.0011131146524338672, -0.0004772017810051617, -0.002655774977174731, 0.0001823581010914221, -0.0014968176140166712, -0.0002973844220526317, 7.689250981180622e-05, -0.0009567073200500778, 0.003947427620740371, 0.0008960709292974939, -0.0020334769131698754, 1.5670284492507508e-05, 0.00024387515816520368, 0.00023840398191539056, 0.00120666189599229, -0.0009364799784715213, -0.003817476744325584, -0.00010973197040718348, 0.00010523673280311091, -0.004537753706361943, 0.00013260143998813071, -0.0013638095859172265, 0.0007431988527584119, -0.0007079502380609999, -0.004668403424186416, -0.00260623418445159, 0.0009711100494124215, -0.0015978547154228947, 0.00046869676037388213, -0.00010061215713961955, -0.001453682614015893, -0.0038509801218192478, -0.0006283655447869773, 0.0029788011583838357, 0.00021276190625175783, -0.00045705704813246413, -0.0015911736295777087, 0.0007563021826535679, 0.0006909336816221423, -0.0021396747763328602, -0.0003862720604434276, 0.0004187363132067}; @Override public double predict(Object2DoubleMap<String> ft) { return predict(ft, DEFAULT_PARAMS); } @Override public double[] getData(Object2DoubleMap<String> ft) { double[] data = new double[14]; data[0] = (ft.getDouble("length") - 146.19835633626096) / 105.72932259026847; data[1] = (ft.getDouble("speed") - 13.76408333576493) / 4.076913004789775; data[2] = (ft.getDouble("numFoes") - 1.284905605322284) / 1.1453318033366016; data[3] = (ft.getDouble("numLanes") - 1.2330250065653177) / 0.6202185676684495; data[4] = (ft.getDouble("junctionSize") - 7.121677219806834) / 4.776491989487674; data[5] = ft.getDouble("dir_l"); data[6] = ft.getDouble("dir_r"); data[7] = ft.getDouble("dir_s"); data[8] = ft.getDouble("dir_multiple_s"); data[9] = ft.getDouble("dir_exclusive"); data[10] = ft.getDouble("priority_lower"); data[11] = ft.getDouble("priority_equal"); data[12] = ft.getDouble("priority_higher"); data[13] = ft.getDouble("changeNumLanes"); return data; } @Override public double predict(Object2DoubleMap<String> ft, double[] params) { double[] data = getData(ft); for (int i = 0; i < data.length; i++) if (Double.isNaN(data[i])) throw new IllegalArgumentException("Invalid data at index: " + i); return score(data, params); } public static double score(double[] input, double[] params) { double var0; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5591954520070176) { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9832499990483197) { var0 = params[0]; } else { var0 = params[1]; } } else { var0 = params[2]; } } else { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 4.118536903904549) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var0 = params[3]; } else { var0 = params[4]; } } else { if (input[0] > 0.5799398138713011) { var0 = params[5]; } else { var0 = params[6]; } } } else { var0 = params[7]; } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.25483333928728746) { if (input[0] <= -0.8417093210852754) { if (input[0] <= -1.2643451510070014) { var0 = params[8]; } else { var0 = params[9]; } } else { if (input[1] > 1.0524915933192283) { if (input[0] <= -0.5146477344523274) { var0 = params[10]; } else { var0 = params[11]; } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var0 = params[12]; } else { if (input[4] <= -0.9675881860533706) { var0 = params[13]; } else { if (input[4] > 0.4979224890207059) { var0 = params[14]; } else { if (input[13] > 1.5000000000000002) { var0 = params[15]; } else { var0 = params[16]; } } } } } } } else { if (input[1] > 2.4150421293433446) { var0 = params[17]; } else { if (input[1] > 1.0524915933192283) { var0 = params[18]; } else { if (input[4] > 1.7540744962270574) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var0 = params[19]; } else { if (input[0] > 0.20194628264557038) { var0 = params[20]; } else { var0 = params[21]; } } } else { var0 = params[22]; } } } } } else { if (input[0] > 0.48791236338146365) { var0 = params[23]; } else { if (input[4] <= -1.1769468539210957) { var0 = params[24]; } else { if (input[0] <= -0.1652649984713819) { var0 = params[25]; } else { var0 = params[26]; } } } } } else { if (input[4] <= -0.7582295181856453) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var0 = params[27]; } else { var0 = params[28]; } } else { if (input[0] <= -0.9753524737493459) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var0 = params[29]; } else { var0 = params[30]; } } else { var0 = params[31]; } } } } double var1; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5591954520070176) { if (input[1] <= -0.9919474197790644) { var1 = params[32]; } else { if (input[0] <= -0.9917150111951237) { var1 = params[33]; } else { var1 = params[34]; } } } else { if (input[1] > 3.09693060641752) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var1 = params[35]; } else { var1 = params[36]; } } else { if (input[0] > 0.23358367441211783) { var1 = params[37]; } else { var1 = params[38]; } } } } else { var1 = params[39]; } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.3718302110816648) { if (input[0] <= -0.8417093210852754) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { var1 = params[40]; } else { var1 = params[41]; } } else { var1 = params[42]; } } else { if (input[1] > 1.0524915933192283) { if (input[0] <= -0.5146477344523274) { var1 = params[43]; } else { var1 = params[44]; } } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { var1 = params[45]; } else { var1 = params[46]; } } else { var1 = params[47]; } } } } else { if (input[1] > 2.4150421293433446) { var1 = params[48]; } else { if (input[1] > 1.0524915933192283) { var1 = params[49]; } else { if (input[4] > 1.1259984926238817) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var1 = params[50]; } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.23358367441211783) { var1 = params[51]; } else { var1 = params[52]; } } else { var1 = params[53]; } } } else { var1 = params[54]; } } } } } else { if (input[0] > 0.6563613760458015) { var1 = params[55]; } else { if (input[4] <= -1.1769468539210957) { var1 = params[56]; } else { if (input[0] <= -0.1652649984713819) { var1 = params[57]; } else { var1 = params[58]; } } } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.825914270487328) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.4979224890207059) { var1 = params[59]; } else { var1 = params[60]; } } else { var1 = params[61]; } } else { var1 = params[62]; } } else { var1 = params[63]; } } } double var2; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5591954520070176) { if (input[3] > 2.0427879129732376) { var2 = params[64]; } else { var2 = params[65]; } } else { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 4.118536903904549) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var2 = params[66]; } else { var2 = params[67]; } } else { if (input[0] > 0.6134215378932977) { var2 = params[68]; } else { var2 = params[69]; } } } else { var2 = params[70]; } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.25483333928728746) { if (input[1] > 1.0524915933192283) { var2 = params[71]; } else { if (input[0] <= -0.8417093210852754) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { var2 = params[72]; } else { var2 = params[73]; } } else { if (input[2] <= -0.6853084870564866) { if (input[4] <= -0.9675881860533706) { var2 = params[74]; } else { var2 = params[75]; } } else { if (input[4] <= -0.9675881860533706) { var2 = params[76]; } else { var2 = params[77]; } } } } else { if (input[4] > 0.4979224890207059) { var2 = params[78]; } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { var2 = params[79]; } else { var2 = params[80]; } } else { var2 = params[81]; } } } } } else { if (input[1] > 2.4150421293433446) { var2 = params[82]; } else { if (input[1] > 1.0524915933192283) { var2 = params[83]; } else { if (input[4] > 1.7540744962270574) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var2 = params[84]; } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { var2 = params[85]; } else { var2 = params[86]; } } } else { var2 = params[87]; } } } } } else { if (input[0] > 0.6563613760458015) { var2 = params[88]; } else { if (input[4] <= -1.1769468539210957) { var2 = params[89]; } else { if (input[0] <= -0.1652649984713819) { var2 = params[90]; } else { var2 = params[91]; } } } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.825914270487328) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var2 = params[92]; } else { var2 = params[93]; } } else { var2 = params[94]; } } else { var2 = params[95]; } } } double var3; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5734772043440838) { if (input[4] <= -0.13015351458246976) { var3 = params[96]; } else { if (input[1] > 1.0524915933192283) { var3 = params[97]; } else { var3 = params[98]; } } } else { if (input[1] > 2.4150421293433446) { var3 = params[99]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var3 = params[100]; } else { if (input[0] > 0.23358367441211783) { var3 = params[101]; } else { var3 = params[102]; } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.7909192482044504) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var3 = params[103]; } else { var3 = params[104]; } } else { if (input[1] > 0.3718295343692867) { var3 = params[105]; } else { if (input[0] <= -0.10293602635133768) { var3 = params[106]; } else { var3 = params[107]; } } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { if (input[0] <= -0.36284500265768266) { var3 = params[108]; } else { var3 = params[109]; } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.6989228896330851) { var3 = params[110]; } else { var3 = params[111]; } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.9166398247561565) { if (input[0] > 0.31624759191275303) { var3 = params[112]; } else { var3 = params[113]; } } else { if (input[0] <= -0.22295949466747736) { var3 = params[114]; } else { var3 = params[115]; } } } else { var3 = params[116]; } } } } else { if (input[1] > 1.7331536522691693) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var3 = params[117]; } else { var3 = params[118]; } } else { if (input[0] <= -0.22295949466747736) { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { var3 = params[119]; } else { var3 = params[120]; } } else { if (input[13] > 1.5000000000000002) { var3 = params[121]; } else { var3 = params[122]; } } } else { var3 = params[123]; } } } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9364796246729602) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var3 = params[124]; } else { var3 = params[125]; } } else { var3 = params[126]; } } else { var3 = params[127]; } } } double var4; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5591954520070176) { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9917150111951237) { var4 = params[128]; } else { var4 = params[129]; } } else { var4 = params[130]; } } else { if (input[1] > 3.09693060641752) { var4 = params[131]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var4 = params[132]; } else { if (input[0] > 0.676034253437257) { var4 = params[133]; } else { var4 = params[134]; } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.25483333928728746) { if (input[1] > 1.0524915933192283) { var4 = params[135]; } else { if (input[0] <= -0.8417093210852754) { var4 = params[136]; } else { if (input[4] > 0.4979224890207059) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var4 = params[137]; } else { var4 = params[138]; } } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { var4 = params[139]; } else { var4 = params[140]; } } else { var4 = params[141]; } } } } } else { if (input[1] > 2.4150421293433446) { var4 = params[142]; } else { if (input[13] > 1.5000000000000002) { var4 = params[143]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var4 = params[144]; } else { if (input[1] > 1.0524915933192283) { var4 = params[145]; } else { if (input[4] > 1.7540744962270574) { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.20194628264557038) { var4 = params[146]; } else { var4 = params[147]; } } else { var4 = params[148]; } } else { var4 = params[149]; } } } } } } } else { if (input[0] > 0.5058827802294276) { if (input[1] > 0.3718295343692867) { var4 = params[150]; } else { if (input[4] <= -1.1769468539210957) { var4 = params[151]; } else { var4 = params[152]; } } } else { var4 = params[153]; } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9684480504340754) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var4 = params[154]; } else { var4 = params[155]; } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var4 = params[156]; } else { if (input[0] <= -0.2706283898852349) { var4 = params[157]; } else { var4 = params[158]; } } } } else { var4 = params[159]; } } } double var5; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.5984304269964432) { if (input[1] > 5.5485404367615425) { var5 = params[160]; } else { var5 = params[161]; } } else { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 4.118536903904549) { var5 = params[162]; } else { if (input[0] <= -0.9917150111951237) { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { var5 = params[163]; } else { var5 = params[164]; } } else { var5 = params[165]; } } } else { if (input[4] <= -0.7582295181856453) { var5 = params[166]; } else { var5 = params[167]; } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5591954520070176) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var5 = params[168]; } else { var5 = params[169]; } } else { if (input[1] > 0.3718295343692867) { var5 = params[170]; } else { var5 = params[171]; } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.5488708503179202) { if (input[0] > 0.06480362775321215) { var5 = params[172]; } else { var5 = params[173]; } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.3432032171846993) { var5 = params[174]; } else { var5 = params[175]; } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.9166398247561565) { var5 = params[176]; } else { if (input[0] <= -0.3718302110816648) { var5 = params[177]; } else { var5 = params[178]; } } } else { var5 = params[179]; } } } } else { if (input[1] > 1.7331536522691693) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var5 = params[180]; } else { var5 = params[181]; } } else { if (input[0] <= -0.21520384108046123) { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { var5 = params[182]; } else { var5 = params[183]; } } else { if (input[13] > 1.5000000000000002) { var5 = params[184]; } else { var5 = params[185]; } } } else { if (input[13] > 1.5000000000000002) { var5 = params[186]; } else { var5 = params[187]; } } } } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9064974028792516) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var5 = params[188]; } else { var5 = params[189]; } } else { var5 = params[190]; } } else { var5 = params[191]; } } } double var6; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5591954520070176) { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.0177248250540192) { var6 = params[192]; } else { var6 = params[193]; } } else { var6 = params[194]; } } else { if (input[1] > 3.09693060641752) { var6 = params[195]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var6 = params[196]; } else { var6 = params[197]; } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.2372412470045436) { if (input[1] > 1.0524915933192283) { if (input[0] <= -0.5146477344523274) { if (input[0] <= -1.172979768506299) { var6 = params[198]; } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { var6 = params[199]; } else { var6 = params[200]; } } } else { var6 = params[201]; } } else { if (input[0] <= -0.765098596628165) { if (input[0] <= -1.2864771380723887) { if (input[2] <= -0.6853084870564866) { var6 = params[202]; } else { var6 = params[203]; } } else { var6 = params[204]; } } else { if (input[4] > 0.4979224890207059) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var6 = params[205]; } else { var6 = params[206]; } } else { var6 = params[207]; } } } } else { if (input[1] > 2.4150421293433446) { var6 = params[208]; } else { if (input[1] > 1.0524915933192283) { var6 = params[209]; } else { if (input[4] > 1.7540744962270574) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var6 = params[210]; } else { if (input[0] > 0.5633408235722607) { var6 = params[211]; } else { var6 = params[212]; } } } else { var6 = params[213]; } } } } } else { if (input[0] > 0.09918387261760682) { if (input[1] > 0.3718295343692867) { var6 = params[214]; } else { if (input[0] > 1.301688503170326) { var6 = params[215]; } else { var6 = params[216]; } } } else { var6 = params[217]; } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.1137719740493224) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var6 = params[218]; } else { var6 = params[219]; } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var6 = params[220]; } else { if (input[0] <= -0.2706283898852349) { var6 = params[221]; } else { var6 = params[222]; } } } } else { var6 = params[223]; } } } double var7; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var7 = params[224]; } else { if (input[1] > 4.118536903904549) { if (input[3] > 3.655122744803958) { var7 = params[225]; } else { var7 = params[226]; } } else { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { var7 = params[227]; } else { var7 = params[228]; } } else { if (input[3] > 2.0427879129732376) { if (input[4] <= -0.33951218245019493) { var7 = params[229]; } else { var7 = params[230]; } } else { var7 = params[231]; } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 1.7331536522691693) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var7 = params[232]; } else { var7 = params[233]; } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 0.3718295343692867) { var7 = params[234]; } else { var7 = params[235]; } } else { var7 = params[236]; } } else { var7 = params[237]; } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { var7 = params[238]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var7 = params[239]; } else { var7 = params[240]; } } } else { if (input[13] > 1.5000000000000002) { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { var7 = params[241]; } else { var7 = params[242]; } } else { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var7 = params[243]; } else { var7 = params[244]; } } else { var7 = params[245]; } } else { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] <= -0.6853084870564866) { var7 = params[246]; } else { var7 = params[247]; } } else { var7 = params[248]; } } } } } } } else { if (input[4] <= -1.1769468539210957) { var7 = params[249]; } else { if (input[1] > 0.3718295343692867) { var7 = params[250]; } else { var7 = params[251]; } } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var7 = params[252]; } else { var7 = params[253]; } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var7 = params[254]; } else { var7 = params[255]; } } } } double var8; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.5984304269964432) { if (input[1] > 5.5485404367615425) { var8 = params[256]; } else { var8 = params[257]; } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var8 = params[258]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var8 = params[259]; } else { if (input[1] > 3.09693060641752) { var8 = params[260]; } else { if (input[0] <= -0.647155913420737) { if (input[3] > 2.0427879129732376) { if (input[4] <= -0.33951218245019493) { var8 = params[261]; } else { var8 = params[262]; } } else { if (input[4] <= -0.9675881860533706) { var8 = params[263]; } else { var8 = params[264]; } } } else { var8 = params[265]; } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.3800114798045537) { if (input[1] > 1.7331536522691693) { if (input[4] <= -0.9675881860533706) { var8 = params[266]; } else { var8 = params[267]; } } else { var8 = params[268]; } } else { if (input[1] > 1.0524915933192283) { if (input[1] > 2.4150421293433446) { var8 = params[269]; } else { var8 = params[270]; } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var8 = params[271]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.2754358294396135) { var8 = params[272]; } else { var8 = params[273]; } } else { if (input[0] > 0.15063601348756742) { var8 = params[274]; } else { var8 = params[275]; } } } } else { var8 = params[276]; } } } } else { if (input[0] > 0.08698290538925213) { if (input[1] > 0.3718295343692867) { var8 = params[277]; } else { if (input[0] > 1.5496802556722316) { var8 = params[278]; } else { var8 = params[279]; } } } else { var8 = params[280]; } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9064974028792516) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var8 = params[281]; } else { var8 = params[282]; } } else { var8 = params[283]; } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var8 = params[284]; } else { if (input[0] <= -0.5667619433114235) { if (input[4] <= -0.7582295181856453) { var8 = params[285]; } else { var8 = params[286]; } } else { var8 = params[287]; } } } } } double var9; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[288]; } else { if (input[1] > 4.118536903904549) { var9 = params[289]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[290]; } else { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { var9 = params[291]; } else { var9 = params[292]; } } else { var9 = params[293]; } } } } } else { if (input[1] <= -0.9919474197790644) { if (input[4] <= -0.7582295181856453) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[294]; } else { var9 = params[295]; } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[296]; } else { var9 = params[297]; } } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 1.0524915933192283) { if (input[1] > 2.4150421293433446) { var9 = params[298]; } else { var9 = params[299]; } } else { if (input[13] > 1.5000000000000002) { if (input[2] <= -0.6853084870564866) { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[300]; } else { var9 = params[301]; } } else { var9 = params[302]; } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[303]; } else { var9 = params[304]; } } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[305]; } else { if (input[2] <= -0.6853084870564866) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 0.3718295343692867) { var9 = params[306]; } else { var9 = params[307]; } } else { var9 = params[308]; } } else { var9 = params[309]; } } } else { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.5488708503179202) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var9 = params[310]; } else { var9 = params[311]; } } else { var9 = params[312]; } } else { var9 = params[313]; } } } else { if (input[4] <= -0.7582295181856453) { var9 = params[314]; } else { if (input[1] > 0.3718295343692867) { var9 = params[315]; } else { var9 = params[316]; } } } } } } } else { if (input[4] <= -1.1769468539210957) { var9 = params[317]; } else { if (input[1] > 0.3718295343692867) { var9 = params[318]; } else { var9 = params[319]; } } } } } double var10; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.676034253437257) { var10 = params[320]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var10 = params[321]; } else { if (input[1] <= -0.9919474197790644) { var10 = params[322]; } else { if (input[0] <= -0.647155913420737) { if (input[2] <= -0.6853084870564866) { if (input[0] <= -1.008739616630037) { var10 = params[323]; } else { var10 = params[324]; } } else { if (input[1] > 1.0524915933192283) { var10 = params[325]; } else { var10 = params[326]; } } } else { if (input[1] > 3.09693060641752) { var10 = params[327]; } else { if (input[4] <= -0.13015351458246976) { var10 = params[328]; } else { if (input[0] <= -0.12223057917757284) { var10 = params[329]; } else { var10 = params[330]; } } } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.3326736185813639) { if (input[1] > 1.7331536522691693) { var10 = params[331]; } else { if (input[4] > 0.4979224890207059) { if (input[4] > 1.335357160491607) { var10 = params[332]; } else { var10 = params[333]; } } else { if (input[0] <= -1.2864771380723887) { var10 = params[334]; } else { var10 = params[335]; } } } } else { if (input[1] > 2.4150421293433446) { var10 = params[336]; } else { if (input[13] > 1.5000000000000002) { var10 = params[337]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var10 = params[338]; } else { var10 = params[339]; } } else { var10 = params[340]; } } } } } else { if (input[0] > 1.642558936433815) { var10 = params[341]; } else { if (input[4] <= -1.1769468539210957) { var10 = params[342]; } else { if (input[0] <= -0.3718302110816648) { var10 = params[343]; } else { if (input[1] > 0.3718295343692867) { var10 = params[344]; } else { var10 = params[345]; } } } } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.7725705067912659) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var10 = params[346]; } else { var10 = params[347]; } } else { var10 = params[348]; } } else { if (input[0] <= -0.6705647458937428) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var10 = params[349]; } else { var10 = params[350]; } } else { var10 = params[351]; } } } } double var11; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.676034253437257) { var11 = params[352]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var11 = params[353]; } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.008739616630037) { var11 = params[354]; } else { if (input[1] > 3.09693060641752) { var11 = params[355]; } else { if (input[0] <= -0.19203146146071792) { if (input[2] <= -0.6853084870564866) { if (input[3] > 2.0427879129732376) { var11 = params[356]; } else { var11 = params[357]; } } else { if (input[1] > 1.0524915933192283) { var11 = params[358]; } else { var11 = params[359]; } } } else { var11 = params[360]; } } } } else { var11 = params[361]; } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.22295949466747736) { if (input[1] > 1.7331536522691693) { var11 = params[362]; } else { if (input[0] <= -0.8471477367103172) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { var11 = params[363]; } else { var11 = params[364]; } } else { var11 = params[365]; } } else { if (input[4] > 0.4979224890207059) { var11 = params[366]; } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { var11 = params[367]; } else { if (input[13] > 1.5000000000000002) { var11 = params[368]; } else { var11 = params[369]; } } } } } } else { if (input[1] > 1.0524915933192283) { var11 = params[370]; } else { var11 = params[371]; } } } else { if (input[0] > 0.7192578350136761) { if (input[1] > 0.3718295343692867) { var11 = params[372]; } else { var11 = params[373]; } } else { if (input[4] <= -1.1769468539210957) { var11 = params[374]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var11 = params[375]; } else { if (input[0] <= -0.5146477344523274) { var11 = params[376]; } else { var11 = params[377]; } } } } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9364796246729602) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var11 = params[378]; } else { var11 = params[379]; } } else { var11 = params[380]; } } else { if (input[0] <= -0.6705647458937428) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var11 = params[381]; } else { var11 = params[382]; } } else { var11 = params[383]; } } } } double var12; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.7192578350136761) { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[384]; } else { var12 = params[385]; } } else { if (input[1] <= -0.9919474197790644) { var12 = params[386]; } else { if (input[0] <= -1.008739616630037) { var12 = params[387]; } else { if (input[1] > 3.09693060641752) { var12 = params[388]; } else { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[389]; } else { var12 = params[390]; } } else { if (input[0] <= -0.20754276863475016) { var12 = params[391]; } else { var12 = params[392]; } } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.550777730430866) { if (input[4] > 0.4979224890207059) { if (input[4] > 1.335357160491607) { var12 = params[393]; } else { var12 = params[394]; } } else { if (input[0] <= -1.2864771380723887) { var12 = params[395]; } else { var12 = params[396]; } } } else { if (input[1] > 1.0524915933192283) { if (input[0] > 0.1628842712865746) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[397]; } else { var12 = params[398]; } } else { var12 = params[399]; } } else { if (input[4] > 0.4979224890207059) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[400]; } else { if (input[0] > 0.30470869267353407) { var12 = params[401]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[402]; } else { var12 = params[403]; } } } } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[404]; } else { var12 = params[405]; } } } } } else { if (input[0] > 1.642558936433815) { var12 = params[406]; } else { if (input[4] <= -1.1769468539210957) { var12 = params[407]; } else { if (input[0] <= -0.39500259070140803) { var12 = params[408]; } else { var12 = params[409]; } } } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.1137719740493224) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[410]; } else { var12 = params[411]; } } else { if (input[0] > 0.08698290538925213) { var12 = params[412]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var12 = params[413]; } else { var12 = params[414]; } } } } else { var12 = params[415]; } } } double var13; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 1.0379962812117778) { var13 = params[416]; } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.1464497583702258) { var13 = params[417]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.112914336759023) { if (input[0] <= -0.9364796246729602) { var13 = params[418]; } else { if (input[0] <= -0.7990532263566867) { var13 = params[419]; } else { var13 = params[420]; } } } else { var13 = params[421]; } } else { if (input[4] > 0.7072811568884312) { var13 = params[422]; } else { var13 = params[423]; } } } } else { if (input[1] > 1.0524915933192283) { if (input[4] > 0.2885638211529807) { var13 = params[424]; } else { var13 = params[425]; } } else { if (input[0] <= -0.647155913420737) { var13 = params[426]; } else { var13 = params[427]; } } } } } else { if (input[0] > 0.06480362775321215) { if (input[1] > 2.4150421293433446) { var13 = params[428]; } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var13 = params[429]; } else { var13 = params[430]; } } } else { if (input[1] <= -0.9919474197790644) { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9364796246729602) { var13 = params[431]; } else { var13 = params[432]; } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var13 = params[433]; } else { var13 = params[434]; } } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 1.0524915933192283) { if (input[0] <= -1.172979768506299) { var13 = params[435]; } else { var13 = params[436]; } } else { if (input[0] <= -0.550777730430866) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { var13 = params[437]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var13 = params[438]; } else { var13 = params[439]; } } } else { if (input[4] > 0.7072811568884312) { var13 = params[440]; } else { if (input[4] <= -1.1769468539210957) { var13 = params[441]; } else { var13 = params[442]; } } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var13 = params[443]; } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { var13 = params[444]; } else { var13 = params[445]; } } } else { var13 = params[446]; } } } } else { var13 = params[447]; } } } } double var14; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[448]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[449]; } else { if (input[1] > 3.09693060641752) { var14 = params[450]; } else { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.13015351458246976) { var14 = params[451]; } else { if (input[3] > 3.655122744803958) { var14 = params[452]; } else { var14 = params[453]; } } } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.4979224890207059) { var14 = params[454]; } else { var14 = params[455]; } } else { var14 = params[456]; } } } } } } else { if (input[4] <= -0.9675881860533706) { if (input[1] > 0.3718295343692867) { var14 = params[457]; } else { var14 = params[458]; } } else { var14 = params[459]; } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 1.0524915933192283) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[460]; } else { if (input[1] > 1.7331536522691693) { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { var14 = params[461]; } else { var14 = params[462]; } } else { if (input[4] <= -0.9675881860533706) { var14 = params[463]; } else { var14 = params[464]; } } } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[465]; } else { if (input[4] <= -0.7582295181856453) { var14 = params[466]; } else { var14 = params[467]; } } } else { if (input[2] <= -0.6853084870564866) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[468]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[469]; } else { if (input[4] <= -0.9675881860533706) { var14 = params[470]; } else { var14 = params[471]; } } } } else { if (input[4] <= -0.9675881860533706) { var14 = params[472]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[473]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[474]; } else { var14 = params[475]; } } } } } } } else { if (input[4] <= -1.1769468539210957) { var14 = params[476]; } else { var14 = params[477]; } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var14 = params[478]; } else { var14 = params[479]; } } } double var15; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.7192578350136761) { var15 = params[480]; } else { if (input[1] <= -0.9919474197790644) { var15 = params[481]; } else { if (input[0] <= -1.008739616630037) { if (input[1] > 1.0524915933192283) { var15 = params[482]; } else { if (input[1] > 0.3718295343692867) { var15 = params[483]; } else { if (input[3] > 3.655122744803958) { var15 = params[484]; } else { var15 = params[485]; } } } } else { if (input[1] > 3.09693060641752) { var15 = params[486]; } else { if (input[3] > 2.0427879129732376) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.868523074645264) { var15 = params[487]; } else { var15 = params[488]; } } else { var15 = params[489]; } } else { var15 = params[490]; } } } } } } else { if (input[0] > 0.09918387261760682) { if (input[1] > 2.4150421293433446) { var15 = params[491]; } else { var15 = params[492]; } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.123939446739618) { var15 = params[493]; } else { var15 = params[494]; } } else { if (input[0] <= -1.0688932225000645) { var15 = params[495]; } else { var15 = params[496]; } } } else { if (input[0] <= -0.18385019273782902) { var15 = params[497]; } else { var15 = params[498]; } } } else { if (input[13] > 2.5000000000000004) { var15 = params[499]; } else { if (input[1] > 1.0524915933192283) { if (input[0] <= -1.1464497583702258) { var15 = params[500]; } else { var15 = params[501]; } } else { if (input[0] <= -0.550777730430866) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var15 = params[502]; } else { var15 = params[503]; } } else { var15 = params[504]; } } else { if (input[2] > 1.0609103764846841) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var15 = params[505]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var15 = params[506]; } else { var15 = params[507]; } } } else { var15 = params[508]; } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { var15 = params[509]; } else { if (input[0] <= -0.8471477367103172) { var15 = params[510]; } else { var15 = params[511]; } } } } } double var16; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.112914336759023) { if (input[4] <= -0.13015351458246976) { if (input[3] > 3.655122744803958) { var16 = params[512]; } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.6048781432573686) { var16 = params[513]; } else { var16 = params[514]; } } else { var16 = params[515]; } } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var16 = params[516]; } else { if (input[4] > 0.4979224890207059) { var16 = params[517]; } else { var16 = params[518]; } } } } else { if (input[0] > 1.7473548409998372) { var16 = params[519]; } else { if (input[1] > 3.09693060641752) { var16 = params[520]; } else { var16 = params[521]; } } } } else { if (input[0] > 0.06480362775321215) { if (input[1] > 0.3718295343692867) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var16 = params[522]; } else { var16 = params[523]; } } else { var16 = params[524]; } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { if (input[4] > 1.544715828359332) { var16 = params[525]; } else { var16 = params[526]; } } else { if (input[1] > 1.7331536522691693) { if (input[4] <= -0.9675881860533706) { var16 = params[527]; } else { var16 = params[528]; } } else { if (input[4] > 0.4979224890207059) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var16 = params[529]; } else { var16 = params[530]; } } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.5488708503179202) { if (input[2] <= -0.6853084870564866) { var16 = params[531]; } else { var16 = params[532]; } } else { var16 = params[533]; } } else { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { var16 = params[534]; } else { var16 = params[535]; } } else { var16 = params[536]; } } } else { if (input[0] <= -1.027845007173662) { if (input[4] <= -0.7582295181856453) { var16 = params[537]; } else { var16 = params[538]; } } else { if (input[4] <= -0.13015351458246976) { var16 = params[539]; } else { var16 = params[540]; } } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { var16 = params[541]; } else { if (input[0] <= -0.9010116966835572) { var16 = params[542]; } else { var16 = params[543]; } } } } } double var17; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.112914336759023) { if (input[4] <= -0.13015351458246976) { if (input[3] > 3.655122744803958) { var17 = params[544]; } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.708066168421205) { var17 = params[545]; } else { var17 = params[546]; } } else { if (input[1] > 1.0524915933192283) { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { var17 = params[547]; } else { var17 = params[548]; } } else { var17 = params[549]; } } } else { var17 = params[550]; } } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var17 = params[551]; } else { if (input[4] > 0.4979224890207059) { var17 = params[552]; } else { var17 = params[553]; } } } } else { if (input[0] > 1.7473548409998372) { var17 = params[554]; } else { if (input[1] > 3.09693060641752) { var17 = params[555]; } else { var17 = params[556]; } } } } else { if (input[0] > 0.06480362775321215) { if (input[1] > 2.4150421293433446) { var17 = params[557]; } else { var17 = params[558]; } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { if (input[4] > 0.2885638211529807) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var17 = params[559]; } else { var17 = params[560]; } } else { if (input[0] <= -1.2492121683981894) { var17 = params[561]; } else { if (input[0] <= -0.6261589000510103) { var17 = params[562]; } else { var17 = params[563]; } } } } else { if (input[1] > 1.0524915933192283) { var17 = params[564]; } else { if (input[4] > 0.4979224890207059) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var17 = params[565]; } else { if (input[4] > 0.9166398247561565) { var17 = params[566]; } else { var17 = params[567]; } } } else { if (input[0] <= -0.5667619433114235) { if (input[4] <= -1.1769468539210957) { var17 = params[568]; } else { var17 = params[569]; } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var17 = params[570]; } else { var17 = params[571]; } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.2885638211529807) { var17 = params[572]; } else { var17 = params[573]; } } else { if (input[0] <= -0.9010116966835572) { var17 = params[574]; } else { var17 = params[575]; } } } } } double var18; if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.9917150111951237) { var18 = params[576]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var18 = params[577]; } else { if (input[0] > 1.0379962812117778) { var18 = params[578]; } else { if (input[1] > 3.09693060641752) { var18 = params[579]; } else { if (input[3] > 2.0427879129732376) { if (input[4] > 1.1259984926238817) { var18 = params[580]; } else { var18 = params[581]; } } else { if (input[1] > 1.0524915933192283) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var18 = params[582]; } else { var18 = params[583]; } } else { var18 = params[584]; } } } } } } } else { if (input[0] > 0.09918387261760682) { var18 = params[585]; } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { if (input[4] > 0.2885638211529807) { if (input[0] <= -1.1059690298916538) { var18 = params[586]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var18 = params[587]; } else { var18 = params[588]; } } } else { if (input[0] <= -0.22295949466747736) { var18 = params[589]; } else { var18 = params[590]; } } } else { if (input[13] > 2.5000000000000004) { var18 = params[591]; } else { if (input[1] > 1.7331536522691693) { var18 = params[592]; } else { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var18 = params[593]; } else { var18 = params[594]; } } else { if (input[0] <= -1.2643451510070014) { var18 = params[595]; } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { var18 = params[596]; } else { var18 = params[597]; } } } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.7990532263566867) { var18 = params[598]; } else { var18 = params[599]; } } else { if (input[0] <= -0.8770826679333733) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var18 = params[600]; } else { var18 = params[601]; } } else { var18 = params[602]; } } } else { if (input[0] > 0.0109396677799722) { var18 = params[603]; } else { var18 = params[604]; } } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { var18 = params[605]; } else { if (input[0] <= -0.6418120789370002) { var18 = params[606]; } else { var18 = params[607]; } } } } } double var19; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.08487102836206846) { if (input[2] <= -0.6853084870564866) { var19 = params[608]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { var19 = params[609]; } else { var19 = params[610]; } } else { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.7909192482044504) { var19 = params[611]; } else { var19 = params[612]; } } else { if (input[4] > 0.4979224890207059) { var19 = params[613]; } else { if (input[4] <= -0.33951218245019493) { var19 = params[614]; } else { var19 = params[615]; } } } } } } else { var19 = params[616]; } } else { if (input[1] > 1.0524915933192283) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.172979768506299) { var19 = params[617]; } else { var19 = params[618]; } } else { var19 = params[619]; } } else { if (input[0] <= -0.550777730430866) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.13015351458246976) { if (input[1] <= -0.9919474197790644) { var19 = params[620]; } else { if (input[4] <= -0.7582295181856453) { var19 = params[621]; } else { var19 = params[622]; } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.1059690298916538) { var19 = params[623]; } else { var19 = params[624]; } } else { var19 = params[625]; } } } else { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { if (input[0] <= -0.6705647458937428) { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { var19 = params[626]; } else { var19 = params[627]; } } else { var19 = params[628]; } } else { if (input[0] <= -1.2643451510070014) { var19 = params[629]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var19 = params[630]; } else { if (input[0] <= -1.0950921986415703) { var19 = params[631]; } else { var19 = params[632]; } } } } } else { var19 = params[633]; } } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var19 = params[634]; } else { if (input[1] <= -0.9919474197790644) { var19 = params[635]; } else { if (input[0] > 1.7473548409998372) { var19 = params[636]; } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var19 = params[637]; } else { var19 = params[638]; } } else { var19 = params[639]; } } } } } } } double var20; if (input[0] > 0.13701632913963654) { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[640]; } else { if (input[1] > 0.3718295343692867) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[641]; } else { if (input[0] > 2.8250123650298575) { var20 = params[642]; } else { var20 = params[643]; } } } else { var20 = params[644]; } } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { if (input[4] > 0.2885638211529807) { if (input[0] <= -1.0950921986415703) { var20 = params[645]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[646]; } else { var20 = params[647]; } } } else { var20 = params[648]; } } else { if (input[3] > 2.0427879129732376) { var20 = params[649]; } else { if (input[13] > 2.5000000000000004) { var20 = params[650]; } else { if (input[1] > 1.0524915933192283) { if (input[0] <= -1.172979768506299) { var20 = params[651]; } else { if (input[0] <= -0.7578158487476743) { if (input[4] > 0.2885638211529807) { var20 = params[652]; } else { var20 = params[653]; } } else { var20 = params[654]; } } } else { if (input[0] <= -0.8471477367103172) { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { if (input[4] <= -1.1769468539210957) { var20 = params[655]; } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[656]; } else { if (input[0] <= -1.2329442120937164) { var20 = params[657]; } else { var20 = params[658]; } } } } else { var20 = params[659]; } } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[660]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[661]; } else { var20 = params[662]; } } } } else { if (input[4] > 1.1259984926238817) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[663]; } else { if (input[0] <= -0.5146477344523274) { var20 = params[664]; } else { if (input[0] <= -0.3547110245054463) { var20 = params[665]; } else { if (input[0] <= -0.30921749553770533) { var20 = params[666]; } else { var20 = params[667]; } } } } } else { var20 = params[668]; } } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { var20 = params[669]; } else { if (input[0] <= -0.8471477367103172) { var20 = params[670]; } else { var20 = params[671]; } } } } double var21; if (input[0] > 0.13701632913963654) { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var21 = params[672]; } else { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { var21 = params[673]; } else { var21 = params[674]; } } } else { if (input[1] > 1.7331536522691693) { var21 = params[675]; } else { var21 = params[676]; } } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { if (input[4] > 0.2885638211529807) { if (input[0] <= -1.0950921986415703) { var21 = params[677]; } else { var21 = params[678]; } } else { var21 = params[679]; } } else { if (input[3] > 2.0427879129732376) { var21 = params[680]; } else { if (input[1] > 3.09693060641752) { var21 = params[681]; } else { if (input[13] > 2.5000000000000004) { var21 = params[682]; } else { if (input[0] <= -0.8546669374440706) { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { if (input[1] > 1.0524915933192283) { if (input[0] <= -1.0950921986415703) { var21 = params[683]; } else { var21 = params[684]; } } else { if (input[4] <= -1.1769468539210957) { var21 = params[685]; } else { var21 = params[686]; } } } else { var21 = params[687]; } } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var21 = params[688]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 0.3718295343692867) { var21 = params[689]; } else { var21 = params[690]; } } else { var21 = params[691]; } } } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 1.0524915933192283) { var21 = params[692]; } else { var21 = params[693]; } } else { var21 = params[694]; } } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var21 = params[695]; } else { if (input[0] > 0.0109396677799722) { if (input[0] > 0.043995776666095825) { var21 = params[696]; } else { var21 = params[697]; } } else { var21 = params[698]; } } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var21 = params[699]; } else { var21 = params[700]; } } } } } } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { var21 = params[701]; } else { if (input[0] <= -0.8471477367103172) { var21 = params[702]; } else { var21 = params[703]; } } } } double var22; if (input[0] <= -0.19203146146071792) { if (input[3] > 2.0427879129732376) { var22 = params[704]; } else { if (input[1] <= -0.9919474197790644) { if (input[0] <= -1.2492121683981894) { var22 = params[705]; } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.7725705067912659) { var22 = params[706]; } else { var22 = params[707]; } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var22 = params[708]; } else { var22 = params[709]; } } else { var22 = params[710]; } } } } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] > 2.5000000000000004) { var22 = params[711]; } else { if (input[0] <= -0.8471477367103172) { if (input[1] > 1.7331536522691693) { var22 = params[712]; } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var22 = params[713]; } else { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { var22 = params[714]; } else { if (input[0] <= -1.0950921986415703) { var22 = params[715]; } else { if (input[0] <= -0.9753524737493459) { var22 = params[716]; } else { var22 = params[717]; } } } } } else { var22 = params[718]; } } } else { var22 = params[719]; } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var22 = params[720]; } else { var22 = params[721]; } } } } } else { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 4.118536903904549) { var22 = params[722]; } else { var22 = params[723]; } } else { var22 = params[724]; } } else { var22 = params[725]; } } else { if (input[1] > 1.0524915933192283) { if (input[0] > 2.8250123650298575) { var22 = params[726]; } else { var22 = params[727]; } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var22 = params[728]; } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 2.900298953508697) { var22 = params[729]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var22 = params[730]; } else { if (input[0] > 0.32986727626068385) { var22 = params[731]; } else { if (input[0] <= -0.04845728895961467) { var22 = params[732]; } else { var22 = params[733]; } } } } } else { var22 = params[734]; } } else { var22 = params[735]; } } } } } double var23; if (input[0] > 0.13701632913963654) { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var23 = params[736]; } else { var23 = params[737]; } } else { if (input[1] > 1.7331536522691693) { var23 = params[738]; } else { var23 = params[739]; } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 2.382150499830233) { var23 = params[740]; } else { var23 = params[741]; } } else { if (input[1] <= -0.9919474197790644) { var23 = params[742]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.1652649984713819) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { var23 = params[743]; } else { var23 = params[744]; } } else { var23 = params[745]; } } else { if (input[0] <= -1.1137719740493224) { var23 = params[746]; } else { if (input[3] > 3.655122744803958) { var23 = params[747]; } else { var23 = params[748]; } } } } } } else { if (input[1] > 1.0524915933192283) { if (input[0] <= -1.2164398029359809) { var23 = params[749]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var23 = params[750]; } else { if (input[3] > 3.655122744803958) { var23 = params[751]; } else { if (input[0] <= -0.7578158487476743) { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { var23 = params[752]; } else { if (input[0] <= -0.8338117957863016) { var23 = params[753]; } else { var23 = params[754]; } } } else { var23 = params[755]; } } } } } else { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.7072811568884312) { if (input[0] <= -0.9364796246729602) { var23 = params[756]; } else { var23 = params[757]; } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.38838191081005285) { var23 = params[758]; } else { var23 = params[759]; } } else { var23 = params[760]; } } } else { if (input[4] <= -0.9675881860533706) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var23 = params[761]; } else { var23 = params[762]; } } else { if (input[0] <= -0.8063359742371775) { if (input[4] <= -0.5488708503179202) { var23 = params[763]; } else { if (input[4] <= -0.13015351458246976) { var23 = params[764]; } else { if (input[4] > 0.2885638211529807) { var23 = params[765]; } else { var23 = params[766]; } } } } else { var23 = params[767]; } } } } } } double var24; if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.6775164597796659) { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] > 0.9166398247561565) { var24 = params[768]; } else { var24 = params[769]; } } else { if (input[0] <= -1.2864771380723887) { var24 = params[770]; } else { var24 = params[771]; } } } else { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { var24 = params[772]; } else { var24 = params[773]; } } else { if (input[4] <= -0.9675881860533706) { var24 = params[774]; } else { var24 = params[775]; } } } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { if (input[0] <= -0.2706283898852349) { var24 = params[776]; } else { var24 = params[777]; } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 1.2313201340393503) { var24 = params[778]; } else { if (input[0] <= -0.46262810673453636) { var24 = params[779]; } else { var24 = params[780]; } } } else { if (input[0] <= -1.1137719740493224) { var24 = params[781]; } else { if (input[4] <= -0.9675881860533706) { if (input[0] > 0.6989228896330851) { var24 = params[782]; } else { if (input[0] <= -0.05730062567163916) { var24 = params[783]; } else { var24 = params[784]; } } } else { if (input[1] > 4.118536903904549) { var24 = params[785]; } else { if (input[0] > 0.32986727626068385) { var24 = params[786]; } else { if (input[3] > 3.655122744803958) { var24 = params[787]; } else { var24 = params[788]; } } } } } } } } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { if (input[0] <= -1.1464497583702258) { var24 = params[789]; } else { if (input[1] > 0.3718295343692867) { var24 = params[790]; } else { var24 = params[791]; } } } else { var24 = params[792]; } } else { if (input[4] <= -0.9675881860533706) { if (input[1] > 1.7331536522691693) { if (input[0] > 0.05501447962813694) { var24 = params[793]; } else { var24 = params[794]; } } else { var24 = params[795]; } } else { if (input[3] > 3.655122744803958) { var24 = params[796]; } else { if (input[0] <= -1.2492121683981894) { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { var24 = params[797]; } else { var24 = params[798]; } } else { var24 = params[799]; } } } } } } double var25; if (input[0] > 0.7192578350136761) { var25 = params[800]; } else { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] > 1.5000000000000002) { if (input[4] <= -0.13015351458246976) { var25 = params[801]; } else { var25 = params[802]; } } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.14918620444951916) { var25 = params[803]; } else { var25 = params[804]; } } else { var25 = params[805]; } } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { if (input[1] > 4.118536903904549) { if (input[1] > 5.5485404367615425) { var25 = params[806]; } else { var25 = params[807]; } } else { if (input[4] <= -1.1769468539210957) { var25 = params[808]; } else { var25 = params[809]; } } } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] <= -0.6853084870564866) { var25 = params[810]; } else { var25 = params[811]; } } else { if (input[4] <= -0.9675881860533706) { if (input[1] > 1.7331536522691693) { if (input[0] <= -0.7725705067912659) { var25 = params[812]; } else { var25 = params[813]; } } else { if (input[2] <= -0.6853084870564866) { if (input[0] <= -1.2329442120937164) { var25 = params[814]; } else { var25 = params[815]; } } else { var25 = params[816]; } } } else { if (input[0] <= -1.1341069194299134) { var25 = params[817]; } else { var25 = params[818]; } } } } } else { if (input[4] > 2.800867835565684) { var25 = params[819]; } else { if (input[0] <= -0.6705647458937428) { var25 = params[820]; } else { if (input[4] <= -0.13015351458246976) { var25 = params[821]; } else { if (input[0] <= -0.6336308102141113) { var25 = params[822]; } else { var25 = params[823]; } } } } } } } } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var25 = params[824]; } else { if (input[0] <= -0.9684480504340754) { var25 = params[825]; } else { var25 = params[826]; } } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var25 = params[827]; } else { var25 = params[828]; } } } } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { var25 = params[829]; } else { if (input[0] <= -0.8471477367103172) { var25 = params[830]; } else { var25 = params[831]; } } } } double var26; if (input[0] <= -0.5976426859475304) { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var26 = params[832]; } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { var26 = params[833]; } else { if (input[1] > 1.0524915933192283) { if (input[0] <= -1.1341069194299134) { var26 = params[834]; } else { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { var26 = params[835]; } else { var26 = params[836]; } } } else { var26 = params[837]; } } } } else { var26 = params[838]; } } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var26 = params[839]; } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] <= -0.6853084870564866) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var26 = params[840]; } else { var26 = params[841]; } } else { var26 = params[842]; } } else { var26 = params[843]; } } } } else { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { if (input[13] > 1.5000000000000002) { var26 = params[844]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.7582295181856453) { var26 = params[845]; } else { var26 = params[846]; } } else { if (input[1] > 3.09693060641752) { if (input[0] <= -0.07602769165004397) { var26 = params[847]; } else { var26 = params[848]; } } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] <= -0.9919474197790644) { var26 = params[849]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.36284500265768266) { var26 = params[850]; } else { if (input[0] > 1.7473548409998372) { var26 = params[851]; } else { var26 = params[852]; } } } else { if (input[0] <= -0.5361176535285793) { if (input[0] <= -0.550777730430866) { var26 = params[853]; } else { var26 = params[854]; } } else { if (input[0] > 0.32986727626068385) { var26 = params[855]; } else { if (input[0] > 0.0109396677799722) { if (input[0] > 0.043995776666095825) { var26 = params[856]; } else { var26 = params[857]; } } else { if (input[0] <= -0.3718302110816648) { if (input[0] <= -0.4240862916527185) { var26 = params[858]; } else { var26 = params[859]; } } else { var26 = params[860]; } } } } } } } else { if (input[4] <= -0.33951218245019493) { var26 = params[861]; } else { var26 = params[862]; } } } } } } else { var26 = params[863]; } } double var27; if (input[0] > 0.7192578350136761) { var27 = params[864]; } else { if (input[4] > 2.800867835565684) { var27 = params[865]; } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[7] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5976426859475304) { if (input[4] <= -1.1769468539210957) { var27 = params[866]; } else { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.0177248250540192) { if (input[4] <= -0.7582295181856453) { if (input[0] <= -1.2164398029359809) { var27 = params[867]; } else { var27 = params[868]; } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { var27 = params[869]; } else { var27 = params[870]; } } } else { if (input[0] <= -0.9291968767924694) { var27 = params[871]; } else { if (input[0] <= -0.6261589000510103) { var27 = params[872]; } else { var27 = params[873]; } } } } else { var27 = params[874]; } } } else { if (input[1] > 1.0524915933192283) { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[3] > 3.655122744803958) { if (input[0] > 0.06480362775321215) { var27 = params[875]; } else { var27 = params[876]; } } else { if (input[4] <= -0.9675881860533706) { var27 = params[877]; } else { if (input[0] <= -0.5361176535285793) { var27 = params[878]; } else { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.2795190171679119) { var27 = params[879]; } else { var27 = params[880]; } } else { if (input[0] <= -0.2628727362982188) { var27 = params[881]; } else { if (input[3] > 0.000000000000000000000000000000000010000000180025095) { var27 = params[882]; } else { var27 = params[883]; } } } } } } } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { var27 = params[884]; } else { var27 = params[885]; } } } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.13216159901460575) { var27 = params[886]; } else { var27 = params[887]; } } else { var27 = params[888]; } } else { var27 = params[889]; } } } } else { if (input[4] <= -1.1769468539210957) { var27 = params[890]; } else { if (input[12] > 0.000000000000000000000000000000000010000000180025095) { var27 = params[891]; } else { var27 = params[892]; } } } } else { if (input[9] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -1.2492121683981894) { var27 = params[893]; } else { var27 = params[894]; } } else { var27 = params[895]; } } } } double var28; if (input[3] > 0.000000000000000000000000000000000010000000180025095) { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { var28 = params[896]; } else { if (input[0] > 1.7473548409998372) { var28 = params[897]; } else { if (input[1] > 0.000000000000000000000000000000000010000000180025095) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[1] > 3.09693060641752) { var28 = params[898]; } else { if (input[0] <= -1.0769326195109958) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var28 = params[899]; } else { var28 = params[900]; } } else { if (input[1] > 1.7331536522691693) { var28 = params[901]; } else { var28 = params[902]; } } } } else { if (input[4] > 0.7072811568884312) { var28 = params[903]; } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.3254854518421782) { var28 = params[904]; } else { var28 = params[905]; } } else { if (input[3] > 3.655122744803958) { if (input[0] <= -1.053003590760812) { var28 = params[906]; } else { if (input[0] <= -0.9291968767924694) { var28 = params[907]; } else { var28 = params[908]; } } } else { if (input[0] <= -1.2492121683981894) { if (input[0] <= -1.2864771380723887) { var28 = params[909]; } else { var28 = params[910]; } } else { if (input[4] <= -1.1769468539210957) { var28 = params[911]; } else { var28 = params[912]; } } } } } } } else { var28 = params[913]; } } } } else { if (input[1] > 3.09693060641752) { if (input[0] > 2.8250123650298575) { var28 = params[914]; } else { var28 = params[915]; } } else { if (input[0] > 0.6989228896330851) { var28 = params[916]; } else { if (input[5] > 0.000000000000000000000000000000000010000000180025095) { var28 = params[917]; } else { if (input[11] > 0.000000000000000000000000000000000010000000180025095) { if (input[4] <= -0.9675881860533706) { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] > 0.06480362775321215) { var28 = params[918]; } else { if (input[0] <= -1.053003590760812) { var28 = params[919]; } else { var28 = params[920]; } } } else { if (input[2] <= -0.6853084870564866) { var28 = params[921]; } else { var28 = params[922]; } } } else { var28 = params[923]; } } else { if (input[6] > 0.000000000000000000000000000000000010000000180025095) { var28 = params[924]; } else { if (input[4] <= -0.9675881860533706) { var28 = params[925]; } else { if (input[1] > 1.0524915933192283) { var28 = params[926]; } else { var28 = params[927]; } } } } } } } } double var29; if (input[12] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.10293602635133768) { if (input[4] <= -0.9675881860533706) { var29 = params[928]; } else { var29 = params[929]; } } else { var29 = params[930]; } } else { if (input[13] > 0.000000000000000000000000000000000010000000180025095) { if (input[2] <= -0.6853084870564866) { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { var29 = params[931]; } else { var29 = params[932]; } } else { if (input[4] <= -0.33951218245019493) { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var29 = params[933]; } else { var29 = params[934]; } } else { var29 = params[935]; } } } else { if (input[1] <= -0.9919474197790644) { var29 = params[936]; } else { if (input[10] > 0.000000000000000000000000000000000010000000180025095) { if (input[0] <= -0.5437787259742904) { var29 = params[937]; } else { if (input[0] > 1.2313201340393503) { var29 = params[938]; } else { var29 = params[939]; } } } else { if (input[3] > 3.655122744803958) { var29 = params[940]; } else { if (input[1] > 4.118536903904549) { if (input[0] > 0.033260817127969806) { var29 = params[941]; } else { var29 = params[942]; } } else { if (input[4] <= -0.9675881860533706) { if (input[2] <= -0.6853084870564866) { if (input[0] <= -1.1137719740493224) { if (input[1] > 1.0524915933192283) { var29 = params[943]; } else { var29 = params[944]; } } else { if (input[0] <= -1.0769326195109958) { var29 = params[945]; } else { if (input[13] <= -0.000000000000000000000000000000000010000000180025095) { var29 = params[946]; } else { var29 = params[947]; } } } } else { var29 = params[948]; } } else { if (input[0] <= -1.1137719740493224) { if (input[8] > 0.000000000000000000000000000000000010000000180025095) { var29 = params[949]; } else { var29 = params[950]; } } else { if (input[0] <= -1.0603809197826077) { if (input[4] > 0.2885638211529807) { var29 = params[951]; } else { var29 = params[952]; } } else { if (input[0] <= -0.6184978276052994) { if (input[0] <= -0.6705647458937428) { var29 = params[953]; } else { var29 = params[954]; } } else { if (input[0] <= -0.5361176535285793) { var29 = params[955]; } else { if (input[1] > 1.0524915933192283) { if (input[3] > 2.0427879129732376) { var29 = params[956]; } else { var29 = params[957]; } } else { if (input[2] > 0.000000000000000000000000000000000010000000180025095) { var29 = params[958]; } else { var29 = params[959]; } } } } } } } } } } } } } return var0 + var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8 + var9 + var10 + var11 + var12 + var13 + var14 + var15 + var16 + var17 + var18 + var19 + var20 + var21 + var22 + var23 + var24 + var25 + var26 + var27 + var28 + var29; } }
210,011
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Speedrelative_traffic_light.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/Speedrelative_traffic_light.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; /** * Generated model, do not modify. */ public final class Speedrelative_traffic_light implements FeatureRegressor { public static Speedrelative_traffic_light INSTANCE = new Speedrelative_traffic_light(); public static final double[] DEFAULT_PARAMS = {0.02672967, 0.081900865, 0.053034972, 0.08446151, 0.03276493, 0.071407326, -0.023928678, 0.03410692, -0.042862535, 0.007113333, 0.0023266017, 0.042514097, -0.058245804, -0.013689547, 0.0049403505, -0.021806315, 0.039555844, 0.012205355, 0.055683292, 0.040495906, -0.018197138, 0.012440386, 0.032121252, 0.008326337, -0.042096734, -0.020887302, 0.0044887, -0.035267785, 0.010093981, -0.016060995, 0.022857327, -0.0062540593, 0.017679192, 0.04323236, -0.009998074, 0.036675263, -0.034326367, -0.0027236857, -0.029326094, 0.023139749, -0.02400434, 0.009349212, -0.06401877, 0.00803626, -0.03857581, -0.011204823, -0.05182662, -0.01122764, -0.04997249, 0.0016140289, 0.01590757, 0.03240009, -0.048695743, -0.025288235, -0.015816864, -0.0008354368, 0.028008368, 0.04024639, 0.00086700777, 0.025649697, -0.017507378, 0.015326313, 0.041393295, -0.045492128, -0.0139780585, 0.018288834, -0.007137278, 0.019313008, 0.006469012, 0.0047062146, 0.023600647, -0.010110819, -0.023493957, 0.010161423, -0.015696606, -0.03562217, 0.006692773, -0.018435616, 0.0038985629, -0.016864264, -0.001187908, 0.011493373, 0.0018385139, -0.016310629, 0.0013226686, -0.027069269, -0.011383642, -0.023405619, -0.009091406, 0.0012356937, -0.02051276, -0.0016820772, -0.037399866, 0.013381466, -0.03972806, 0.006310406, -0.004882459, -0.00018265756, 0.014005854, -0.0049224123, -0.019507458, -0.010337537, 0.019420264, -0.043424454, 0.01803482, -0.012511946, 0.029618748, -0.00330452, -0.024241628, 0.020220226, -0.0012113304, 0.0060021942, -0.010335434, -0.022662979, 0.008070686, -0.007909735, 0.0061049, -0.00754677, 0.009248198, 0.00042798033, -0.016113643, -0.004144019, -0.015797436, -0.036987927, 0.0052333786, -0.007865147, -0.00038512584, -0.019125879, 0.006921055, -0.004053284, 0.036284827, 0.013979893, -0.00031446968, -0.0014063935, -0.020877214, 0.008057659, -0.00344305, 0.0037369246, 0.030612065, -0.0050245672, 0.013907017, 0.014756328, -0.010173623, -0.011990903, 0.016641164, -0.023504745, 0.010938932, -0.04214916, 0.017000519, -0.031579223, -0.014754095, -0.0056909057, 0.0115929125, 0.0033608908, -0.0012129244, -0.006745956, 0.0005271181, 0.024115793, -0.002309813, -0.019186174, 0.004995935, -0.0032075713, -0.018796884, -0.005572311, -0.012635144, 0.014109028, 0.001250176, 0.0057716053, -0.020501874, -0.0006526424, 0.008763132, 0.012876768, -0.008461759, 0.004772153, -0.01012048, -0.0018596641, 0.0, 0.022573654, -0.01835205, 0.0046745646, 0.0, -0.03536958, 0.008444654, 0.0017268299, -0.011742718, 0.006219295, 0.015834937, -0.014433121, -0.0054902495, 0.012779403, -0.009488669, 0.00030039944, 0.00042476412, 0.0054790135, -0.0031896585, -0.021349462, 0.011214811, 0.036101967, -0.011064748, 0.00026978576, 0.020780737, 0.0021785772, 0.0032453018, -0.0124553535, 0.0061376505, -0.021886118, -0.009512777, 0.015981643, -0.008499147, -0.0005367195, -0.011721236, 0.0020560187, 0.017658614, 0.0069867484, -0.009386386, -0.001393256, -0.006149292, 0.008796969, 0.00023590519, -0.005488677, 0.011950189, -0.04180444, -0.010375813, -0.0049798763, 0.019866657, -0.0043466855, 0.00602803, 0.02591866, 0.019801212, -0.0017350526, 0.0052215727, -0.00015579026, -0.007276478, 0.011183358, 0.0064067603, 0.0061288537, -0.0071214447, 0.0020716758, -0.01603627, 0.0076239635, -0.017927235, 0.014956552, 0.010882739, -0.011055113, 0.01847202, -0.015520886, 0.005722581, -0.00868443, -0.010827428, 0.006549411, -0.014514054, -0.0024962898, 0.00061903097, -0.003289423, 0.003863995, -0.0015401262, 0.005169729, -0.00041814084, -0.007748396, 0.0011531163, 0.012569849, 0.016971465, 0.0018450491, -0.0008069037, -0.004156409, -0.024098692, -0.008196066, 0.0009979605, -0.032654915, 0.007038396, -0.017315391, -0.0065580253, 0.0149074355, 0.02341699, -0.0004702245, -0.018915761, 0.002015762, 5.8807153e-05, -0.010585102, 0.041828405, 0.0, -0.0355101, -0.010269751, 0.014998806, 0.018291168, -0.0028743467, 0.0174826, -0.0004413311, -0.017520329, -0.00425402, -0.019582683, 0.004545165, -0.01844734, 0.0005263567, 0.007093741, 0.0023567427, -0.0038803825, 0.016031163, -0.00978845, 0.014525503, 0.0007352337, -0.0077979243, 0.0023218181, -0.017925201, 0.0012097007, -0.0006081959, -0.00069398317, -0.03405387, -0.0055578984, 0.0010618606, -0.005371819, -0.023276644, -0.02600419, -0.002633595, -0.00010532885, -0.0028377676, 0.012748503, -0.00203033, -0.017263561, 0.0005562401, -0.017590124, 0.0006730753, 0.004691983, 0.012806608, -0.02300126, -0.0036971956, 0.0024646786, -0.0027914767, 0.0048576733, 0.0020022457, -0.0036141973, 0.00035840302, -0.0017047703, -0.008714578, -0.00038072825, -0.01033011, 0.00611105, -0.008052845, 0.0018109282, 0.0066358177, 0.03232777, -0.009639772, 0.021862363, -0.017429113, -0.01042969, -0.0016700295, 0.0001407893, -0.0031154866, 0.0017336892, -0.008227171, 0.007140533, -0.012689197, 0.0051840413, -0.0012753225, -0.0076941233, 0.005221435, 0.03517991, 0.008712071, -0.024997069, 0.0131085245, 0.0005197675, -0.0002524971, -0.016701791, 0.020968925, -0.0039766366, -0.03530954, 0.024028504, 0.016613068, -0.0052661067, 0.05225834, 9.833425e-05, 0.008169875, -0.0008635007, 0.005399532, -0.014806244, 0.0015388669, -0.010500554, -0.020747289, -0.0069364654, 0.002613798, 0.00013274471, 0.026170686, -0.029559238, 0.005938267, -0.006929883, 0.0002942946, 0.00029299964, -0.0084923105, 0.0016527828, 0.028015409, -0.016085954, 0.006183133, 0.033776708, 0.004530843, -0.011248405, 0.0039703366, 0.0019399134, -0.0075180284}; @Override public double predict(Object2DoubleMap<String> ft) { return predict(ft, DEFAULT_PARAMS); } @Override public double[] getData(Object2DoubleMap<String> ft) { double[] data = new double[14]; data[0] = (ft.getDouble("length") - 123.77791684254963) / 86.92545218615102; data[1] = (ft.getDouble("speed") - 13.195084423807513) / 2.5553097705928556; data[2] = (ft.getDouble("numFoes") - 2.4094554664415364) / 0.6618814394678828; data[3] = (ft.getDouble("numLanes") - 1.9147319544111439) / 0.9803419977659901; data[4] = (ft.getDouble("junctionSize") - 13.871042634022794) / 4.3880523696095075; data[5] = ft.getDouble("dir_l"); data[6] = ft.getDouble("dir_r"); data[7] = ft.getDouble("dir_s"); data[8] = ft.getDouble("dir_multiple_s"); data[9] = ft.getDouble("dir_exclusive"); data[10] = ft.getDouble("priority_lower"); data[11] = ft.getDouble("priority_equal"); data[12] = ft.getDouble("priority_higher"); data[13] = ft.getDouble("changeNumLanes"); return data; } @Override public double predict(Object2DoubleMap<String> ft, double[] params) { double[] data = getData(ft); for (int i = 0; i < data.length; i++) if (Double.isNaN(data[i])) throw new IllegalArgumentException("Invalid data at index: " + i); return score(data, params); } public static double score(double[] input, double[] params) { double var0; if (input[0] >= -0.12318505) { if (input[0] >= 0.6606475) { if (input[0] >= 1.4716873) { if (input[1] >= 0.815915) { var0 = params[0]; } else { var0 = params[1]; } } else { if (input[1] >= -0.27201572) { var0 = params[2]; } else { var0 = params[3]; } } } else { if (input[13] >= -0.5) { if (input[1] >= -1.3599465) { var0 = params[4]; } else { var0 = params[5]; } } else { if (input[4] >= 0.3712256) { var0 = params[6]; } else { var0 = params[7]; } } } } else { if (input[0] >= -0.58559275) { if (input[3] >= -0.42304826) { if (input[4] >= 0.14333406) { var0 = params[8]; } else { var0 = params[9]; } } else { if (input[1] >= -0.8159811) { var0 = params[10]; } else { var0 = params[11]; } } } else { if (input[6] >= 0.5) { if (input[1] >= -0.8159811) { var0 = params[12]; } else { var0 = params[13]; } } else { if (input[0] >= -0.79623306) { var0 = params[14]; } else { var0 = params[15]; } } } } double var1; if (input[0] >= -0.21590818) { if (input[0] >= 0.44782144) { if (input[4] >= 1.0549002) { if (input[0] >= 1.5108013) { var1 = params[16]; } else { var1 = params[17]; } } else { if (input[0] >= 1.17839) { var1 = params[18]; } else { var1 = params[19]; } } } else { if (input[4] >= 0.59911716) { if (input[3] >= 0.59700394) { var1 = params[20]; } else { var1 = params[21]; } } else { if (input[13] >= -0.5) { var1 = params[22]; } else { var1 = params[23]; } } } } else { if (input[6] >= 0.5) { if (input[3] >= -0.42304826) { if (input[4] >= 0.14333406) { var1 = params[24]; } else { var1 = params[25]; } } else { if (input[0] >= -0.8024453) { var1 = params[26]; } else { var1 = params[27]; } } } else { if (input[13] >= -0.5) { if (input[0] >= -0.67089576) { var1 = params[28]; } else { var1 = params[29]; } } else { if (input[0] >= -0.7430841) { var1 = params[30]; } else { var1 = params[31]; } } } } double var2; if (input[0] >= -0.07365987) { if (input[0] >= 0.4490294) { if (input[4] >= 0.59911716) { if (input[1] >= -0.8159811) { var2 = params[32]; } else { var2 = params[33]; } } else { if (input[1] >= 0.815915) { var2 = params[34]; } else { var2 = params[35]; } } } else { if (input[4] >= 1.0549002) { if (input[4] >= 1.9664664) { var2 = params[36]; } else { var2 = params[37]; } } else { if (input[1] >= 0.815915) { var2 = params[38]; } else { var2 = params[39]; } } } } else { if (input[0] >= -0.67336917) { if (input[4] >= 0.59911716) { if (input[1] >= -0.8159811) { var2 = params[40]; } else { var2 = params[41]; } } else { if (input[1] >= 1.9018891) { var2 = params[42]; } else { var2 = params[43]; } } } else { if (input[4] >= -0.08455747) { if (input[1] >= -0.8159811) { var2 = params[44]; } else { var2 = params[45]; } } else { if (input[1] >= 0.815915) { var2 = params[46]; } else { var2 = params[47]; } } } } double var3; if (input[1] >= -1.3599465) { if (input[0] >= 0.12116225) { if (input[1] >= 0.815915) { if (input[4] >= 0.3712256) { var3 = params[48]; } else { var3 = params[49]; } } else { if (input[6] >= 0.5) { var3 = params[50]; } else { var3 = params[51]; } } } else { if (input[10] >= 0.5) { if (input[1] >= 0.815915) { var3 = params[52]; } else { var3 = params[53]; } } else { if (input[4] >= 0.3712256) { var3 = params[54]; } else { var3 = params[55]; } } } } else { if (input[0] >= -0.8852173) { if (input[0] >= -0.4262033) { if (input[10] >= 0.5) { var3 = params[56]; } else { var3 = params[57]; } } else { if (input[4] >= 0.59911716) { var3 = params[58]; } else { var3 = params[59]; } } } else { if (input[4] >= -1.2240152) { if (input[5] >= 0.5) { var3 = params[60]; } else { var3 = params[61]; } } else { var3 = params[62]; } } } double var4; if (input[0] >= -0.4053234) { if (input[1] >= 0.815915) { if (input[6] >= 0.5) { if (input[1] >= 1.9018891) { var4 = params[63]; } else { var4 = params[64]; } } else { if (input[4] >= -0.7682321) { var4 = params[65]; } else { var4 = params[66]; } } } else { if (input[1] >= -1.3599465) { if (input[0] >= 1.0439644) { var4 = params[67]; } else { var4 = params[68]; } } else { if (input[13] >= 1.5) { var4 = params[69]; } else { var4 = params[70]; } } } } else { if (input[6] >= 0.5) { if (input[1] >= -0.27201572) { if (input[12] >= 0.5) { var4 = params[71]; } else { var4 = params[72]; } } else { if (input[0] >= -0.9071902) { var4 = params[73]; } else { var4 = params[74]; } } } else { if (input[1] >= 1.9018891) { var4 = params[75]; } else { if (input[0] >= -1.13756) { var4 = params[76]; } else { var4 = params[77]; } } } } double var5; if (input[0] >= -0.47975498) { if (input[4] >= 1.0549002) { if (input[10] >= 0.5) { if (input[13] >= 1.5) { var5 = params[78]; } else { var5 = params[79]; } } else { var5 = params[80]; } } else { if (input[7] >= 0.5) { if (input[13] >= -0.5) { var5 = params[81]; } else { var5 = params[82]; } } else { if (input[4] >= -0.54034054) { var5 = params[83]; } else { var5 = params[84]; } } } } else { if (input[4] >= 1.0549002) { if (input[4] >= 1.5106833) { var5 = params[85]; } else { if (input[2] >= 0.13679874) { var5 = params[86]; } else { var5 = params[87]; } } } else { if (input[7] >= 0.5) { if (input[4] >= -0.08455747) { var5 = params[88]; } else { var5 = params[89]; } } else { if (input[4] >= -1.2240152) { var5 = params[90]; } else { var5 = params[91]; } } } } double var6; if (input[0] >= -0.8296525) { if (input[1] >= 1.9018891) { if (input[0] >= -0.059337243) { if (input[4] >= 0.029388294) { var6 = params[92]; } else { var6 = params[93]; } } else { var6 = params[94]; } } else { if (input[1] >= -1.3599465) { if (input[12] >= 0.5) { var6 = params[95]; } else { var6 = params[96]; } } else { if (input[4] >= 1.0549002) { var6 = params[97]; } else { var6 = params[98]; } } } } else { if (input[4] >= -1.6797982) { if (input[1] >= -0.8159811) { if (input[13] >= 0.5) { var6 = params[99]; } else { var6 = params[100]; } } else { if (input[4] >= -0.7682321) { var6 = params[101]; } else { var6 = params[102]; } } } else { if (input[1] >= 0.815915) { var6 = params[103]; } else { if (input[0] >= -1.1556215) { var6 = params[104]; } else { var6 = params[105]; } } } } double var7; if (input[0] >= -0.31329048) { if (input[1] >= 0.815915) { if (input[0] >= 2.0634587) { var7 = params[106]; } else { if (input[8] >= 0.5) { var7 = params[107]; } else { var7 = params[108]; } } } else { if (input[0] >= 2.7587671) { var7 = params[109]; } else { if (input[13] >= 0.5) { var7 = params[110]; } else { var7 = params[111]; } } } } else { if (input[1] >= 0.815915) { if (input[0] >= -1.1831162) { if (input[8] >= 0.5) { var7 = params[112]; } else { var7 = params[113]; } } else { var7 = params[114]; } } else { if (input[6] >= 0.5) { if (input[5] >= 0.5) { var7 = params[115]; } else { var7 = params[116]; } } else { if (input[2] >= 0.13679874) { var7 = params[117]; } else { var7 = params[118]; } } } } double var8; if (input[1] >= -1.3599465) { if (input[4] >= -0.54034054) { if (input[13] >= -0.5) { if (input[4] >= -0.312449) { var8 = params[119]; } else { var8 = params[120]; } } else { if (input[8] >= 0.5) { var8 = params[121]; } else { var8 = params[122]; } } } else { if (input[1] >= 2.987863) { var8 = params[123]; } else { if (input[7] >= 0.5) { var8 = params[124]; } else { var8 = params[125]; } } } } else { if (input[4] >= -0.7682321) { if (input[4] >= 1.0549002) { if (input[4] >= 1.2827917) { var8 = params[126]; } else { var8 = params[127]; } } else { if (input[7] >= 0.5) { var8 = params[128]; } else { var8 = params[129]; } } } else { if (input[13] >= 1.5) { var8 = params[130]; } else { if (input[13] >= -0.5) { var8 = params[131]; } else { var8 = params[132]; } } } } double var9; if (input[0] >= -0.89390296) { if (input[13] >= 0.5) { if (input[8] >= 0.5) { if (input[0] >= 0.024297638) { var9 = params[133]; } else { var9 = params[134]; } } else { if (input[0] >= 1.0261331) { var9 = params[135]; } else { var9 = params[136]; } } } else { if (input[13] >= -0.5) { if (input[0] >= -0.87469107) { var9 = params[137]; } else { var9 = params[138]; } } else { if (input[6] >= 0.5) { var9 = params[139]; } else { var9 = params[140]; } } } } else { if (input[7] >= 0.5) { if (input[13] >= 0.5) { if (input[9] >= 0.5) { var9 = params[141]; } else { var9 = params[142]; } } else { if (input[0] >= -1.285963) { var9 = params[143]; } else { var9 = params[144]; } } } else { if (input[6] >= 0.5) { if (input[0] >= -1.2283274) { var9 = params[145]; } else { var9 = params[146]; } } else { var9 = params[147]; } } } double var10; if (input[1] >= 0.815915) { if (input[0] >= 2.187588) { var10 = params[148]; } else { if (input[9] >= 0.5) { if (input[1] >= 2.987863) { var10 = params[149]; } else { var10 = params[150]; } } else { var10 = params[151]; } } } else { if (input[0] >= -0.7737425) { if (input[0] >= 2.1705046) { var10 = params[152]; } else { if (input[12] >= 0.5) { var10 = params[153]; } else { var10 = params[154]; } } } else { if (input[2] >= -1.3740458) { if (input[1] >= -0.8159811) { var10 = params[155]; } else { var10 = params[156]; } } else { if (input[5] >= 0.5) { var10 = params[157]; } else { var10 = params[158]; } } } } double var11; if (input[4] >= 0.59911716) { if (input[12] >= 0.5) { if (input[13] >= -0.5) { if (input[3] >= 1.6170561) { var11 = params[159]; } else { var11 = params[160]; } } else { if (input[0] >= -0.7426239) { var11 = params[161]; } else { var11 = params[162]; } } } else { if (input[0] >= -1.154471) { if (input[0] >= -0.6638782) { var11 = params[163]; } else { var11 = params[164]; } } else { var11 = params[165]; } } } else { if (input[7] >= 0.5) { if (input[0] >= -1.064739) { if (input[4] >= -0.54034054) { var11 = params[166]; } else { var11 = params[167]; } } else { if (input[0] >= -1.1093749) { var11 = params[168]; } else { var11 = params[169]; } } } else { if (input[0] >= 0.93818414) { var11 = params[170]; } else { if (input[3] >= 0.59700394) { var11 = params[171]; } else { var11 = params[172]; } } } } double var12; if (input[1] >= -1.3599465) { if (input[4] >= -1.4519067) { if (input[0] >= 1.4982617) { var12 = params[173]; } else { if (input[4] >= 1.5106833) { var12 = params[174]; } else { var12 = params[175]; } } } else { if (input[0] >= -0.5758718) { if (input[0] >= 0.81267434) { var12 = params[176]; } else { var12 = params[177]; } } else { if (input[0] >= -0.72611547) { var12 = params[178]; } else { var12 = params[179]; } } } } else { if (input[10] >= 0.5) { if (input[8] >= 0.5) { if (input[3] >= -0.42304826) { var12 = params[180]; } else { var12 = params[181]; } } else { if (input[0] >= 0.2536896) { var12 = params[182]; } else { var12 = params[183]; } } } else { if (input[3] >= 1.6170561) { var12 = params[184]; } else { if (input[0] >= -0.30805612) { var12 = params[185]; } else { var12 = params[186]; } } } } double var13; if (input[0] >= -0.93761855) { if (input[1] >= 1.9018891) { if (input[6] >= 0.5) { var13 = params[187]; } else { if (input[4] >= -1.4519067) { var13 = params[188]; } else { var13 = params[189]; } } } else { if (input[13] >= 0.5) { if (input[8] >= 0.5) { var13 = params[190]; } else { var13 = params[191]; } } else { if (input[4] >= -0.9961236) { var13 = params[192]; } else { var13 = params[193]; } } } } else { if (input[13] >= 0.5) { if (input[6] >= 0.5) { if (input[9] >= 0.5) { var13 = params[194]; } else { var13 = params[195]; } } else { if (input[4] >= -2.363473) { var13 = params[196]; } else { var13 = params[197]; } } } else { if (input[0] >= -1.2768748) { if (input[4] >= -1.9076898) { var13 = params[198]; } else { var13 = params[199]; } } else { if (input[4] >= -0.312449) { var13 = params[200]; } else { var13 = params[201]; } } } } double var14; if (input[1] >= -1.3599465) { if (input[8] >= 0.5) { if (input[3] >= -0.42304826) { if (input[0] >= -1.0242445) { var14 = params[202]; } else { var14 = params[203]; } } else { if (input[0] >= 0.95802873) { var14 = params[204]; } else { var14 = params[205]; } } } else { if (input[4] >= 0.59911716) { if (input[0] >= -1.157117) { var14 = params[206]; } else { var14 = params[207]; } } else { if (input[1] >= 0.815915) { var14 = params[208]; } else { var14 = params[209]; } } } } else { if (input[3] >= 1.6170561) { var14 = params[210]; } else { if (input[10] >= 0.5) { if (input[4] >= -1.4519067) { var14 = params[211]; } else { var14 = params[212]; } } else { if (input[0] >= -1.1216843) { var14 = params[213]; } else { var14 = params[214]; } } } } double var15; if (input[4] >= -1.6797982) { if (input[0] >= -1.0676725) { if (input[4] >= 1.0549002) { if (input[0] >= -0.584845) { var15 = params[215]; } else { var15 = params[216]; } } else { if (input[3] >= 1.6170561) { var15 = params[217]; } else { var15 = params[218]; } } } else { if (input[4] >= -0.9961236) { if (input[4] >= -0.7682321) { var15 = params[219]; } else { var15 = params[220]; } } else { if (input[8] >= 0.5) { var15 = params[221]; } else { var15 = params[222]; } } } } else { if (input[13] >= -0.5) { if (input[6] >= 0.5) { if (input[10] >= 0.5) { var15 = params[223]; } else { var15 = params[224]; } } else { if (input[0] >= -1.0703759) { var15 = params[225]; } else { var15 = params[226]; } } } else { if (input[4] >= -1.9076898) { var15 = params[227]; } else { if (input[11] >= 0.5) { var15 = params[228]; } else { var15 = params[229]; } } } } double var16; if (input[1] >= -0.27201572) { if (input[7] >= 0.5) { if (input[13] >= -1.5) { if (input[3] >= 1.6170561) { var16 = params[230]; } else { var16 = params[231]; } } else { if (input[6] >= 0.5) { var16 = params[232]; } else { var16 = params[233]; } } } else { if (input[0] >= 1.2212428) { var16 = params[234]; } else { if (input[3] >= 0.59700394) { var16 = params[235]; } else { var16 = params[236]; } } } } else { if (input[4] >= -0.9961236) { if (input[2] >= -1.3740458) { var16 = params[237]; } else { var16 = params[238]; } } else { if (input[0] >= -0.96540093) { var16 = params[239]; } else { if (input[2] >= -1.3740458) { var16 = params[240]; } else { var16 = params[241]; } } } } double var17; if (input[4] >= 1.5106833) { if (input[0] >= 0.3480808) { if (input[0] >= 0.56614125) { if (input[0] >= 1.427454) { var17 = params[242]; } else { var17 = params[243]; } } else { var17 = params[244]; } } else { if (input[0] >= -0.13808289) { var17 = params[245]; } else { if (input[0] >= -0.3474002) { var17 = params[246]; } else { var17 = params[247]; } } } } else { if (input[1] >= 0.815915) { if (input[0] >= -0.06146551) { if (input[4] >= 0.14333406) { var17 = params[248]; } else { var17 = params[249]; } } else { if (input[4] >= 0.3712256) { var17 = params[250]; } else { var17 = params[251]; } } } else { if (input[9] >= 0.5) { if (input[13] >= -0.5) { var17 = params[252]; } else { var17 = params[253]; } } else { if (input[12] >= 0.5) { var17 = params[254]; } else { var17 = params[255]; } } } } double var18; if (input[0] >= 2.1705046) { var18 = params[256]; } else { if (input[0] >= -1.3181746) { if (input[1] >= -1.3599465) { if (input[0] >= -1.1492941) { var18 = params[257]; } else { var18 = params[258]; } } else { if (input[0] >= -1.1124811) { var18 = params[259]; } else { var18 = params[260]; } } } else { var18 = params[261]; } } double var19; if (input[4] >= -0.9961236) { if (input[7] >= 0.5) { if (input[13] >= -1.5) { if (input[3] >= 0.59700394) { var19 = params[262]; } else { var19 = params[263]; } } else { if (input[5] >= 0.5) { var19 = params[264]; } else { var19 = params[265]; } } } else { if (input[5] >= 0.5) { if (input[9] >= 0.5) { var19 = params[266]; } else { var19 = params[267]; } } else { var19 = params[268]; } } } else { if (input[6] >= 0.5) { if (input[13] >= -0.5) { if (input[2] >= -2.8848906) { var19 = params[269]; } else { var19 = params[270]; } } else { if (input[4] >= -1.2240152) { var19 = params[271]; } else { var19 = params[272]; } } } else { if (input[5] >= 0.5) { if (input[8] >= 0.5) { var19 = params[273]; } else { var19 = params[274]; } } else { if (input[4] >= -1.6797982) { var19 = params[275]; } else { var19 = params[276]; } } } } double var20; if (input[0] >= -1.2502427) { if (input[0] >= -1.1201887) { if (input[0] >= -1.1093749) { if (input[0] >= -1.0791191) { var20 = params[277]; } else { var20 = params[278]; } } else { if (input[5] >= 0.5) { var20 = params[279]; } else { var20 = params[280]; } } } else { if (input[0] >= -1.1238701) { var20 = params[281]; } else { if (input[13] >= -0.5) { var20 = params[282]; } else { var20 = params[283]; } } } } else { if (input[4] >= -0.312449) { var20 = params[284]; } else { if (input[0] >= -1.330599) { var20 = params[285]; } else { var20 = params[286]; } } } double var21; if (input[0] >= -0.10316791) { if (input[4] >= -0.9961236) { if (input[5] >= 0.5) { if (input[0] >= -0.07475275) { var21 = params[287]; } else { var21 = params[288]; } } else { if (input[3] >= -0.42304826) { var21 = params[289]; } else { var21 = params[290]; } } } else { if (input[2] >= 0.13679874) { if (input[10] >= 0.5) { var21 = params[291]; } else { var21 = params[292]; } } else { if (input[5] >= 0.5) { var21 = params[293]; } else { var21 = params[294]; } } } } else { if (input[4] >= 1.0549002) { if (input[11] >= 0.5) { var21 = params[295]; } else { var21 = params[296]; } } else { if (input[3] >= 1.6170561) { if (input[5] >= 0.5) { var21 = params[297]; } else { var21 = params[298]; } } else { if (input[13] >= 1.5) { var21 = params[299]; } else { var21 = params[300]; } } } } double var22; if (input[7] >= 0.5) { if (input[4] >= 1.7385747) { if (input[8] >= 0.5) { if (input[12] >= 0.5) { var22 = params[301]; } else { var22 = params[302]; } } else { var22 = params[303]; } } else { if (input[0] >= -1.1599929) { if (input[13] >= -0.5) { var22 = params[304]; } else { var22 = params[305]; } } else { if (input[4] >= -1.9076898) { var22 = params[306]; } else { var22 = params[307]; } } } } else { if (input[2] >= -2.8848906) { if (input[0] >= -0.89119947) { if (input[4] >= -0.54034054) { var22 = params[308]; } else { var22 = params[309]; } } else { if (input[6] >= 0.5) { var22 = params[310]; } else { var22 = params[311]; } } } else { if (input[0] >= -0.6404674) { var22 = params[312]; } else { var22 = params[313]; } } } double var23; if (input[0] >= -0.18306395) { if (input[0] >= -0.17294034) { if (input[4] >= -1.6797982) { if (input[0] >= 0.31678966) { var23 = params[314]; } else { var23 = params[315]; } } else { if (input[4] >= -1.9076898) { var23 = params[316]; } else { var23 = params[317]; } } } else { var23 = params[318]; } } else { if (input[0] >= -0.7737425) { if (input[10] >= 0.5) { if (input[5] >= 0.5) { var23 = params[319]; } else { var23 = params[320]; } } else { if (input[4] >= 0.14333406) { var23 = params[321]; } else { var23 = params[322]; } } } else { if (input[3] >= 1.6170561) { if (input[5] >= 0.5) { var23 = params[323]; } else { var23 = params[324]; } } else { if (input[0] >= -1.0423635) { var23 = params[325]; } else { var23 = params[326]; } } } } double var24; if (input[13] >= -1.5) { if (input[3] >= 0.59700394) { if (input[0] >= -0.5477443) { if (input[11] >= 0.5) { var24 = params[327]; } else { var24 = params[328]; } } else { if (input[2] >= 0.13679874) { var24 = params[329]; } else { var24 = params[330]; } } } else { if (input[13] >= -0.5) { var24 = params[331]; } else { if (input[5] >= 0.5) { var24 = params[332]; } else { var24 = params[333]; } } } } else { if (input[3] >= 1.6170561) { var24 = params[334]; } else { var24 = params[335]; } } double var25; if (input[3] >= 1.6170561) { if (input[4] >= 1.2827917) { if (input[3] >= 2.6371083) { var25 = params[336]; } else { if (input[12] >= 0.5) { var25 = params[337]; } else { var25 = params[338]; } } } else { if (input[5] >= 0.5) { if (input[0] >= -0.9272648) { var25 = params[339]; } else { var25 = params[340]; } } else { if (input[4] >= -1.4519067) { var25 = params[341]; } else { var25 = params[342]; } } } } else { if (input[4] >= 2.1943579) { var25 = params[343]; } else { if (input[1] >= 0.815915) { if (input[4] >= 0.14333406) { var25 = params[344]; } else { var25 = params[345]; } } else { if (input[0] >= -0.93865395) { var25 = params[346]; } else { var25 = params[347]; } } } } double var26; if (input[0] >= -0.18904608) { if (input[0] >= 1.2391891) { if (input[0] >= 1.364469) { if (input[0] >= 1.4716873) { var26 = params[348]; } else { var26 = params[349]; } } else { var26 = params[350]; } } else { if (input[0] >= 1.1457758) { var26 = params[351]; } else { if (input[0] >= 1.0254428) { var26 = params[352]; } else { var26 = params[353]; } } } } else { if (input[0] >= -0.28665847) { if (input[0] >= -0.2803312) { if (input[3] >= 1.6170561) { var26 = params[354]; } else { var26 = params[355]; } } else { if (input[0] >= -0.28326476) { var26 = params[356]; } else { var26 = params[357]; } } } else { if (input[0] >= -0.2903973) { var26 = params[358]; } else { if (input[3] >= 2.6371083) { var26 = params[359]; } else { var26 = params[360]; } } } } double var27; if (input[0] >= -1.0976982) { if (input[0] >= -1.0897604) { if (input[0] >= -1.0423635) { if (input[0] >= -1.0373592) { var27 = params[361]; } else { var27 = params[362]; } } else { if (input[0] >= -1.0566286) { var27 = params[363]; } else { var27 = params[364]; } } } else { var27 = params[365]; } } else { if (input[2] >= -1.3740458) { if (input[0] >= -1.1121935) { var27 = params[366]; } else { if (input[4] >= 0.82700866) { var27 = params[367]; } else { var27 = params[368]; } } } else { if (input[9] >= 0.5) { if (input[4] >= -2.363473) { var27 = params[369]; } else { var27 = params[370]; } } else { var27 = params[371]; } } } double var28; if (input[4] >= 0.59911716) { if (input[8] >= 0.5) { if (input[3] >= -0.42304826) { if (input[3] >= 0.59700394) { var28 = params[372]; } else { var28 = params[373]; } } else { var28 = params[374]; } } else { if (input[13] >= 0.5) { if (input[0] >= -0.7650569) { var28 = params[375]; } else { var28 = params[376]; } } else { if (input[0] >= 0.022399459) { var28 = params[377]; } else { var28 = params[378]; } } } } else { if (input[0] >= -1.1557364) { if (input[0] >= -1.1488916) { if (input[3] >= 0.59700394) { var28 = params[379]; } else { var28 = params[380]; } } else { var28 = params[381]; } } else { if (input[0] >= -1.1731652) { var28 = params[382]; } else { if (input[6] >= 0.5) { var28 = params[383]; } else { var28 = params[384]; } } } } double var29; if (input[0] >= -0.93060106) { if (input[0] >= -0.9254817) { if (input[4] >= -1.2240152) { var29 = params[385]; } else { if (input[0] >= -0.3976156) { var29 = params[386]; } else { var29 = params[387]; } } } else { if (input[3] >= 0.59700394) { var29 = params[388]; } else { var29 = params[389]; } } } else { if (input[13] >= 0.5) { if (input[4] >= -0.9961236) { if (input[0] >= -1.0436289) { var29 = params[390]; } else { var29 = params[391]; } } else { if (input[2] >= 0.13679874) { var29 = params[392]; } else { var29 = params[393]; } } } else { if (input[0] >= -1.0159616) { if (input[1] >= -0.8159811) { var29 = params[394]; } else { var29 = params[395]; } } else { if (input[3] >= -0.42304826) { var29 = params[396]; } else { var29 = params[397]; } } } } return 0.5 + (var0 + var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8 + var9 + var10 + var11 + var12 + var13 + var14 + var15 + var16 + var17 + var18 + var19 + var20 + var21 + var22 + var23 + var24 + var25 + var26 + var27 + var28 + var29); } }
58,186
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
FreeSpeedOptimizer.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/FreeSpeedOptimizer.java
package org.matsim.prepare.network; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleList; import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.application.CommandSpec; import org.matsim.application.MATSimAppCommand; import org.matsim.application.analysis.traffic.traveltime.SampleValidationRoutes; import org.matsim.application.options.InputOptions; import org.matsim.contrib.osm.networkReader.LinkProperties; import org.matsim.core.network.NetworkUtils; import org.matsim.core.router.DijkstraFactory; import org.matsim.core.router.costcalculators.OnlyTimeDependentTravelDisutility; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.trafficmonitoring.FreeSpeedTravelTime; import org.matsim.core.utils.geometry.CoordUtils; import picocli.CommandLine; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.stream.DoubleStream; @CommandLine.Command( name = "network-freespeed", description = "Start server for freespeed optimization." ) @CommandSpec( requireNetwork = true, requires = "features.csv" ) @Deprecated public class FreeSpeedOptimizer implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(FreeSpeedOptimizer.class); @CommandLine.Mixin private InputOptions input = InputOptions.ofCommand(FreeSpeedOptimizer.class); @CommandLine.Option(names = "--output", description = "Path to output network") private Path output; @CommandLine.Option(names = "--params", description = "Apply params and write to output if given") private Path params; @CommandLine.Parameters(arity = "0..*", description = "Input validation files loaded from APIs") private List<String> validationFiles; private Network network; private Object2DoubleMap<SampleValidationRoutes.FromToNodes> validationSet; private Map<Id<Link>, PrepareNetworkParams.Feature> features; private ObjectMapper mapper; /** * Original speeds. */ private Object2DoubleMap<Id<Link>> speeds = new Object2DoubleOpenHashMap<>(); public static void main(String[] args) { new FreeSpeedOptimizer().execute(args); } @Override public Integer call() throws Exception { // TODO: must be reusable class // TODO: evaluate many factors (f) and write results to csv network = input.getNetwork(); mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); for (Link link : network.getLinks().values()) { speeds.put(link.getId(), link.getFreespeed()); } validationSet = readValidation(validationFiles); features = PrepareNetworkParams.readFeatures(input.getPath("features.csv"), network.getLinks().size()); log.info("Initial score:"); evaluateNetwork(null, "init"); evaluateNetwork(new Request(0.5), "05"); evaluateNetwork(new Request(0.75), "075"); evaluateNetwork(new Request(0.9), "09"); if (output != null && params != null) { Request p = mapper.readValue(params.toFile(), Request.class); evaluateNetwork(p, null); NetworkUtils.writeNetwork(network, output.toString()); return 0; } Server server = new Server(9090); ServletHandler handler = new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping(new ServletHolder(new Backend()), "/"); try { server.start(); server.join(); } finally { server.destroy(); } return 0; } private Result evaluateNetwork(Request request, String save) throws IOException { Map<Id<Link>, double[]> attributes = new HashMap<>(); if (request != null) { for (Link link : network.getLinks().values()) { double allowedSpeed = NetworkUtils.getAllowedSpeed(link); if (request.f == 0) { PrepareNetworkParams.Feature ft = features.get(link.getId()); String type = NetworkUtils.getHighwayType(link); if (type.startsWith("motorway")) { link.setFreespeed(allowedSpeed); continue; } FeatureRegressor speedModel = switch (ft.junctionType()) { case "traffic_light" -> Speedrelative_traffic_light.INSTANCE; case "right_before_left" -> Speedrelative_right_before_left.INSTANCE; case "priority" -> Speedrelative_priority.INSTANCE; default -> throw new IllegalArgumentException("Unknown type: " + ft.junctionType()); }; double[] p = switch (ft.junctionType()) { case "traffic_light" -> request.traffic_light; case "right_before_left" -> request.rbl; case "priority" -> request.priority; default -> throw new IllegalArgumentException("Unknown type: " + ft.junctionType()); }; double speedFactor = Math.max(0.25, speedModel.predict(ft.features(), p)); attributes.put(link.getId(), speedModel.getData(ft.features())); link.setFreespeed((double) link.getAttributes().getAttribute("allowed_speed") * speedFactor); link.getAttributes().putAttribute("speed_factor", speedFactor); } else // Old MATSim freespeed logic link.setFreespeed(LinkProperties.calculateSpeedIfSpeedTag(allowedSpeed, request.f)); } if (save != null) mapper.writeValue(new File(save + "-params.json"), request); } FreeSpeedTravelTime tt = new FreeSpeedTravelTime(); OnlyTimeDependentTravelDisutility util = new OnlyTimeDependentTravelDisutility(tt); LeastCostPathCalculator router = new DijkstraFactory(false).createPathCalculator(network, util, tt); SummaryStatistics rmse = new SummaryStatistics(); SummaryStatistics mse = new SummaryStatistics(); CSVPrinter csv = save != null ? new CSVPrinter(Files.newBufferedWriter(Path.of(save + "-eval.csv")), CSVFormat.DEFAULT) : null; if (csv != null) csv.printRecord("from_node", "to_node", "beeline_dist", "dist", "travel_time"); List<Data> priority = new ArrayList<>(); List<Data> rbl = new ArrayList<>(); List<Data> traffic_light = new ArrayList<>(); for (Object2DoubleMap.Entry<SampleValidationRoutes.FromToNodes> e : validationSet.object2DoubleEntrySet()) { SampleValidationRoutes.FromToNodes r = e.getKey(); Node fromNode = network.getNodes().get(r.fromNode()); Node toNode = network.getNodes().get(r.toNode()); LeastCostPathCalculator.Path path = router.calcLeastCostPath(fromNode, toNode, 0, null, null); // iterate over the path, calc better correction double distance = path.links.stream().mapToDouble(Link::getLength).sum(); double speed = distance / path.travelTime; double correction = speed / e.getDoubleValue(); for (Link link : path.links) { if (!attributes.containsKey(link.getId())) continue; PrepareNetworkParams.Feature ft = features.get(link.getId()); double[] input = attributes.get(link.getId()); double speedFactor = (double) link.getAttributes().getAttribute("speed_factor"); List<Data> category = switch (ft.junctionType()) { case "traffic_light" -> traffic_light; case "right_before_left" -> rbl; case "priority" -> priority; default -> throw new IllegalArgumentException("not happening"); }; category.add(new Data(input, speedFactor, speedFactor / correction)); } rmse.addValue(Math.pow(e.getDoubleValue() - speed, 2)); mse.addValue(Math.abs((e.getDoubleValue() - speed) * 3.6)); if (csv != null) csv.printRecord(r.fromNode(), r.toNode(), (int) CoordUtils.calcEuclideanDistance(fromNode.getCoord(), toNode.getCoord()), (int) distance, (int) path.travelTime); } if (csv != null) csv.close(); log.info("{}, rmse: {}, mae: {}", request, rmse.getMean(), mse.getMean()); return new Result(rmse.getMean(), mse.getMean(), priority, rbl, traffic_light); } /** * Calculate the target speed. */ static Object2DoubleMap<SampleValidationRoutes.FromToNodes> readValidation(List<String> validationFiles) throws IOException { // entry to hour and list of speeds Map<SampleValidationRoutes.FromToNodes, Int2ObjectMap<DoubleList>> entries = SampleValidationRoutes.readValidation(validationFiles); Object2DoubleMap<SampleValidationRoutes.FromToNodes> result = new Object2DoubleOpenHashMap<>(); // Target values for (Map.Entry<SampleValidationRoutes.FromToNodes, Int2ObjectMap<DoubleList>> e : entries.entrySet()) { Int2ObjectMap<DoubleList> perHour = e.getValue(); // Use avg from all values for 3:00 and 21:00 double avg = DoubleStream.concat(perHour.get(3).doubleStream(), perHour.get(21).doubleStream()) .average().orElseThrow(); result.put(e.getKey(), avg); } return result; } private record Data(double[] x, double yPred, double yTrue) { } private record Result(double rmse, double mse, List<Data> priority, List<Data> rbl, List<Data> traffic_light) {} /** * JSON request containing desired parameters. */ private static final class Request { double[] priority; double[] rbl; double[] traffic_light; double f; public Request() { } public Request(double f) { this.f = f; } @Override public String toString() { if (f == 0) return "Request{" + "priority=" + priority.length + ", rbl=" + rbl.length + ", traffic_light=" + traffic_light.length + '}'; return "Request{f=" + f + "}"; } } private final class Backend extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Request request = mapper.readValue(req.getInputStream(), Request.class); boolean save = req.getRequestURI().equals("/save"); Result stats = evaluateNetwork(request, save ? "network-opt" : null); if (save) NetworkUtils.writeNetwork(network, "network-opt.xml.gz"); resp.setStatus(200); PrintWriter writer = resp.getWriter(); mapper.writeValue(writer, stats); writer.close(); } } }
11,057
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
SampleNetwork.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/SampleNetwork.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.*; import org.locationtech.jts.io.WKTWriter; import org.locationtech.jts.simplify.TopologyPreservingSimplifier; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.api.core.v01.population.Person; import org.matsim.application.CommandSpec; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.InputOptions; import org.matsim.application.options.OutputOptions; import org.matsim.core.config.groups.NetworkConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.MultimodalNetworkCleaner; import org.matsim.core.network.filter.NetworkFilterManager; import org.matsim.core.router.DijkstraFactory; import org.matsim.core.router.costcalculators.OnlyTimeDependentTravelDisutility; import org.matsim.core.router.util.LeastCostPathCalculator; import org.matsim.core.router.util.TravelTime; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.prepare.RunOpenBerlinCalibration; import org.matsim.vehicles.Vehicle; import picocli.CommandLine; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.util.stream.Collectors; /** * Now available in the contrib. */ @CommandLine.Command( name = "sample-network", description = "Sample nodes and junctions ids from network" ) @CommandSpec(requireNetwork = true, produces = {"intersections.txt", "edges.txt", "routes.txt"}) @Deprecated public class SampleNetwork implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(SampleNetwork.class); @CommandLine.Mixin private InputOptions input = InputOptions.ofCommand(SampleNetwork.class); @CommandLine.Mixin private OutputOptions output = OutputOptions.ofCommand(SampleNetwork.class); @CommandLine.Option(names = "--sample-size", description = "Number of samples to collect for each category.", defaultValue = "5000") private int sample; public static void main(String[] args) { new SampleNetwork().execute(args); } /** * Random coord in the same direction as a link. */ static Coord rndCoord(SplittableRandom rnd, double dist, Link link) { Coord v = link.getFromNode().getCoord(); Coord u = link.getToNode().getCoord(); var angle = Math.atan2(u.getY() - v.getY(), u.getX() - v.getX()); var sample = angle + rnd.nextDouble(-0.2, 0.2) * Math.PI * 2; var x = Math.cos(sample) * dist; var y = Math.sin(sample) * dist; return new Coord(RunOpenBerlinCalibration.roundNumber(v.getX() + x), RunOpenBerlinCalibration.roundNumber(v.getY() + y)); } /** * Skip certain nodes to improve class imbalance regarding the allowed speed. */ private static double skip(Node node, String key) { // all traffic lights are considered if (key.equals("traffic_light")) return 1; Optional<? extends Link> first = node.getInLinks().values().stream().findFirst(); if (first.isEmpty()) return 0; Link link = first.get(); // very long or short links are skipped if (link.getLength() > 500 || link.getLength() < 15) return 0; double skip = 1; if (NetworkUtils.getAllowedSpeed(link) == 13.89) skip = 0.6; else if (NetworkUtils.getAllowedSpeed(link) == 8.33) skip = 0.3; // Increase samples with more than 1 lane if (link.getNumberOfLanes() == 1) skip *= 0.7; return skip; } @Override public Integer call() throws Exception { Network network = input.getNetwork(); Map<String, ? extends List<? extends Node>> byType = network.getNodes().values().stream().collect(Collectors.groupingBy( n -> (String) n.getAttributes().getAttribute("type"), Collectors.toList() )); SplittableRandom rnd = new SplittableRandom(0); try (BufferedWriter intersections = Files.newBufferedWriter(output.getPath("intersections.txt"))) { for (Map.Entry<String, ? extends List<? extends Node>> e : byType.entrySet()) { List<? extends Node> list = e.getValue(); log.info("Sampling {} out of {} intersections for type {}", sample, list.size(), e.getKey()); for (int i = 0; i < sample && !list.isEmpty(); i++) { Node n = list.remove(rnd.nextInt(0, list.size())); // leave out certain links if (rnd.nextDouble() > skip(n, e.getKey())) { i--; continue; } intersections.write(n.getId().toString() + "\n"); } } } Map<Double, ? extends List<? extends Link>> bySpeed = network.getLinks().values().stream() .filter(l -> !"traffic_light".equals(l.getToNode().getAttributes().getAttribute("type"))) .filter(l -> l.getLength() < 500 && l.getLength() > 50) .collect(Collectors.groupingBy( n -> (Double) n.getAttributes().getAttribute("allowed_speed"), Collectors.toList() )); try (BufferedWriter links = Files.newBufferedWriter(output.getPath("edges.txt"))) { for (Map.Entry<Double, ? extends List<? extends Link>> e : bySpeed.entrySet()) { List<? extends Link> list = e.getValue(); if (list.size() < 50) continue; log.info("Sampling {} out of {} links for speed {}", sample / 10, list.size(), e.getKey()); // Use longest link segments list.sort(Comparator.comparingDouble(l -> -l.getLength())); for (int i = 0; i < sample / 10 && i < list.size(); i++) { Link link = list.get(i); links.write(link.getId().toString() + "\n"); } } } Network cityNetwork = createCityNetwork(network); RandomizedTravelTime tt = new RandomizedTravelTime(rnd); LeastCostPathCalculator router = createRandomizedRouter(network, tt); sampleCityRoutes(cityNetwork, router, tt, rnd); return 0; } /** * Samples routes from the network. */ private void sampleCityRoutes(Network network, LeastCostPathCalculator router, RandomizedTravelTime tt, SplittableRandom rnd) throws IOException { List<? extends Link> links = new ArrayList<>(network.getLinks().values()); GeometryFactory f = new GeometryFactory(); WKTWriter w = new WKTWriter(); w.setPrecisionModel(new PrecisionModel(1)); try (CSVPrinter csv = new CSVPrinter(Files.newBufferedWriter(output.getPath("routes.txt")), CSVFormat.DEFAULT)) { csv.printRecord("fromEdge", "toEdge", "min_capacity", "travel_time", "geometry"); for (int i = 0; i < 3000; i++) { Link link = links.get(rnd.nextInt(0, links.size())); Coord dest = rndCoord(rnd, 6000, link); Link to = NetworkUtils.getNearestLink(network, dest); LeastCostPathCalculator.Path path = router.calcLeastCostPath(link.getFromNode(), to.getToNode(), 0, null, null); if (path.nodes.size() < 2) { i--; continue; } double minCapacity = path.links.stream().mapToDouble(Link::getCapacity).min().orElse(-1); LineString lineString = f.createLineString(path.nodes.stream().map(n -> MGC.coord2Point(n.getCoord()).getCoordinate()).toArray(Coordinate[]::new)); Polygon polygon = (Polygon) lineString.buffer(100); Polygon simplified = (Polygon) TopologyPreservingSimplifier.simplify(polygon, 30); csv.print(link.getId()); csv.print(path.links.get(path.links.size() - 1).getId()); csv.print(minCapacity); csv.print(path.travelTime); csv.print(w.write(simplified)); csv.println(); // Reset randomness tt.reset(); } } } /** * Create network without highways. */ private Network createCityNetwork(Network network) { NetworkFilterManager filter = new NetworkFilterManager(network, new NetworkConfigGroup()); filter.addLinkFilter(l -> !NetworkUtils.getHighwayType(l).startsWith("motorway")); Network net = filter.applyFilters(); MultimodalNetworkCleaner cleaner = new MultimodalNetworkCleaner(net); cleaner.run(Set.of("car")); return net; } /** * Router with randomization. */ private LeastCostPathCalculator createRandomizedRouter(Network network, TravelTime tt) { OnlyTimeDependentTravelDisutility util = new OnlyTimeDependentTravelDisutility(tt); return new DijkstraFactory(false).createPathCalculator(network, util, tt); } private static final class RandomizedTravelTime implements TravelTime { private final Object2DoubleMap<Link> factors = new Object2DoubleOpenHashMap<>(); private final SplittableRandom rnd; RandomizedTravelTime(SplittableRandom rnd) { this.rnd = rnd; } void reset() { factors.clear(); } @Override public double getLinkTravelTime(Link link, double time, Person person, Vehicle vehicle) { String type = NetworkUtils.getHighwayType(link); double f = factors.computeIfAbsent(link, l -> rnd.nextDouble(0.5, 1.5)); // Main roads are avoided if (type.startsWith("primary") || type.startsWith("secondary")) f = 1.5; double speed = link.getLength() / Math.max(link.getFreespeed(time), 8.3); return speed * f; } } }
9,186
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Capacity_priority.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/Capacity_priority.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; /** * Generated model, do not modify. */ public class Capacity_priority implements FeatureRegressor { @Override public double predict(Object2DoubleMap<String> ft) { double[] data = new double[14]; data[0] = (ft.getDouble("length") - 148.0745794277257) / 111.09738260925752; data[1] = (ft.getDouble("speed") - 14.667442032560434) / 5.4536411840395225; data[2] = (ft.getDouble("numFoes") - 1.1944992599901332) / 1.1479306507188651; data[3] = (ft.getDouble("numLanes") - 1.2444499259990134) / 0.6166874690379405; data[4] = (ft.getDouble("junctionSize") - 6.785273803650715) / 4.8225180177060665; data[5] = ft.getDouble("dir_l"); data[6] = ft.getDouble("dir_r"); data[7] = ft.getDouble("dir_s"); data[8] = ft.getDouble("dir_multiple_s"); data[9] = ft.getDouble("dir_exclusive"); data[10] = ft.getDouble("priority_lower"); data[11] = ft.getDouble("priority_equal"); data[12] = ft.getDouble("priority_higher"); data[13] = ft.getDouble("changeNumLanes"); for (int i = 0; i < data.length; i++) if (Double.isNaN(data[i])) throw new IllegalArgumentException("Invalid data at index: " + i); return score(data); } public static double score(double[] input) { double var0; if (input[13] >= -0.5) { if (input[1] >= -0.90718144) { if (input[7] >= 0.5) { if (input[3] >= 2.0359585) { var0 = 528.2315; } else { var0 = 678.9136; } } else { if (input[2] >= -0.60500103) { var0 = 545.95953; } else { var0 = 513.5971; } } } else { if (input[7] >= 0.5) { if (input[0] >= -0.053012766) { var0 = 532.0486; } else { var0 = 551.90857; } } else { if (input[4] >= -0.8885968) { var0 = 530.28046; } else { var0 = 490.33154; } } } } else { if (input[3] >= 2.0359585) { if (input[3] >= 3.6575255) { if (input[3] >= 5.2790923) { var0 = 329.68658; } else { var0 = 407.84097; } } else { if (input[1] >= 1.8946164) { var0 = 551.58856; } else { var0 = 463.95148; } } } else { var0 = 344.90738; } } double var1; if (input[13] >= -0.5) { if (input[1] >= -0.90718144) { if (input[7] >= 0.5) { if (input[3] >= 2.0359585) { var1 = 351.37134; } else { var1 = 452.8441; } } else { if (input[2] >= -0.60500103) { var1 = 362.52734; } else { var1 = 341.0468; } } } else { if (input[3] >= 2.0359585) { var1 = 244.8547; } else { if (input[7] >= 0.5) { var1 = 364.16348; } else { var1 = 349.63425; } } } } else { if (input[9] >= 0.5) { var1 = 229.99834; } else { if (input[3] >= 3.6575255) { if (input[13] >= -1.5) { var1 = 276.54538; } else { var1 = 232.33159; } } else { if (input[1] >= 1.8946164) { var1 = 367.8001; } else { var1 = 304.73376; } } } } double var2; if (input[13] >= -0.5) { if (input[1] >= -0.90718144) { if (input[7] >= 0.5) { if (input[4] >= 0.5629271) { var2 = 267.97882; } else { var2 = 303.57843; } } else { if (input[0] >= -0.7527142) { var2 = 236.92879; } else { var2 = 251.3941; } } } else { if (input[0] >= -0.37489253) { if (input[4] >= -1.0959573) { var2 = 234.57248; } else { var2 = 172.93842; } } else { if (input[0] >= -1.0727037) { var2 = 252.1177; } else { var2 = 216.38428; } } } } else { if (input[3] >= 2.0359585) { if (input[3] >= 3.6575255) { if (input[13] >= -1.5) { var2 = 183.27914; } else { var2 = 160.37532; } } else { if (input[1] >= 0.62115526) { var2 = 244.39363; } else { var2 = 199.57362; } } } else { if (input[7] >= 0.5) { var2 = 153.73575; } else { var2 = 126.66589; } } } double var3; if (input[13] >= -0.5) { if (input[1] >= -0.39743024) { if (input[3] >= 3.6575255) { if (input[0] >= -0.9738265) { var3 = 10.114798; } else { var3 = 74.12102; } } else { if (input[6] >= 0.5) { var3 = 182.49957; } else { var3 = 205.18987; } } } else { if (input[6] >= 0.5) { if (input[3] >= 0.41439155) { var3 = 50.8256; } else { var3 = 156.43225; } } else { if (input[0] >= -1.0977719) { var3 = 171.65904; } else { var3 = 138.68129; } } } } else { if (input[3] >= 2.0359585) { if (input[3] >= 3.6575255) { if (input[3] >= 5.2790923) { var3 = 83.71184; } else { var3 = 122.21861; } } else { if (input[0] >= -0.08721699) { var3 = 160.40189; } else { var3 = 144.6932; } } } else { if (input[8] >= 0.5) { var3 = 76.86066; } else { var3 = 102.30043; } } } double var4; if (input[7] >= 0.5) { if (input[13] >= -0.5) { if (input[1] >= -0.39743024) { if (input[0] >= -1.0632976) { var4 = 137.5552; } else { var4 = 98.03021; } } else { if (input[0] >= -0.6347996) { var4 = 104.684204; } else { var4 = 120.135826; } } } else { if (input[9] >= 0.5) { var4 = 68.47832; } else { if (input[1] >= 1.8946164) { var4 = 105.024254; } else { var4 = 82.94903; } } } } else { if (input[2] >= -0.60500103) { if (input[5] >= 0.5) { if (input[0] >= -1.187963) { var4 = 101.44326; } else { var4 = 42.216213; } } else { if (input[1] >= -0.65230584) { var4 = 154.08447; } else { var4 = 111.6845; } } } else { if (input[6] >= 0.5) { if (input[4] >= -0.8885968) { var4 = 124.653305; } else { var4 = 38.009064; } } else { if (input[11] >= 0.5) { var4 = 99.03142; } else { var4 = 33.777233; } } } } double var5; if (input[13] >= -0.5) { if (input[3] >= 2.0359585) { if (input[4] >= -0.47387564) { if (input[3] >= 3.6575255) { var5 = -52.25111; } else { var5 = 43.67992; } } else { if (input[3] >= 3.6575255) { var5 = -28.815895; } else { var5 = 46.78004; } } } else { if (input[10] >= 0.5) { if (input[8] >= 0.5) { var5 = -10.979303; } else { var5 = 63.3409; } } else { if (input[7] >= 0.5) { var5 = 90.672165; } else { var5 = 64.64078; } } } } else { if (input[3] >= 2.0359585) { if (input[4] >= -0.68123615) { if (input[3] >= 5.2790923) { var5 = 25.173052; } else { var5 = 54.33675; } } else { if (input[3] >= 3.6575255) { var5 = 49.93983; } else { var5 = 71.85198; } } } else { if (input[7] >= 0.5) { if (input[8] >= 0.5) { var5 = 24.934956; } else { var5 = 45.695312; } } else { var5 = 19.088688; } } } double var6; if (input[3] >= 0.41439155) { if (input[0] >= -1.0631626) { if (input[9] >= 0.5) { if (input[13] >= -0.5) { var6 = -269.20898; } else { var6 = 30.201042; } } else { if (input[3] >= 2.0359585) { var6 = 34.990143; } else { var6 = 67.52307; } } } else { if (input[2] >= -0.60500103) { if (input[13] >= -0.5) { var6 = -137.58873; } else { var6 = 38.572998; } } else { if (input[0] >= -1.2234273) { var6 = -8.754881; } else { var6 = -176.93155; } } } } else { if (input[2] >= 1.1372645) { if (input[12] >= 0.5) { if (input[1] >= -0.65230584) { var6 = 73.2211; } else { var6 = 43.449955; } } else { if (input[1] >= -0.65230584) { var6 = 10.302028; } else { var6 = 39.984016; } } } else { if (input[7] >= 0.5) { if (input[1] >= -0.39743024) { var6 = 66.583626; } else { var6 = 48.81097; } } else { if (input[0] >= -0.7527142) { var6 = 44.597507; } else { var6 = 53.671276; } } } } double var7; if (input[3] >= 0.41439155) { if (input[0] >= -1.1372867) { if (input[8] >= 0.5) { if (input[3] >= 3.6575255) { var7 = 7.308279; } else { var7 = 37.1175; } } else { if (input[13] >= -0.5) { var7 = -128.86482; } else { var7 = 20.46987; } } } else { if (input[8] >= 0.5) { if (input[3] >= 2.0359585) { var7 = 21.48796; } else { var7 = -70.786705; } } else { var7 = 33.37381; } } } else { if (input[2] >= 1.1372645) { if (input[12] >= 0.5) { if (input[1] >= -0.65230584) { var7 = 49.545773; } else { var7 = 28.931652; } } else { if (input[1] >= -0.65230584) { var7 = 7.2723947; } else { var7 = 27.238398; } } } else { if (input[7] >= 0.5) { if (input[1] >= -0.39743024) { var7 = 44.53098; } else { var7 = 33.792645; } } else { if (input[2] >= -0.60500103) { var7 = 33.040085; } else { var7 = 16.181316; } } } } double var8; if (input[0] >= -1.1373768) { if (input[10] >= 0.5) { if (input[0] >= -1.0084357) { if (input[1] >= -0.39743024) { var8 = 8.954352; } else { var8 = 24.357721; } } else { if (input[6] >= 0.5) { var8 = -2.263031; } else { var8 = -71.02918; } } } else { if (input[3] >= 0.41439155) { if (input[8] >= 0.5) { var8 = 23.2148; } else { var8 = 5.490529; } } else { if (input[0] >= 0.47796285) { var8 = 19.852242; } else { var8 = 30.092987; } } } } else { if (input[9] >= 0.5) { if (input[10] >= 0.5) { if (input[6] >= 0.5) { var8 = -2.0775354; } else { var8 = -63.5745; } } else { if (input[0] >= -1.1523635) { var8 = -2.125128; } else { var8 = 25.38647; } } } else { if (input[0] >= -1.1417873) { var8 = -146.80832; } else { if (input[0] >= -1.1794119) { var8 = 6.429794; } else { var8 = -66.40415; } } } } double var9; if (input[2] >= 1.1372645) { if (input[12] >= 0.5) { if (input[3] >= 3.6575255) { var9 = -48.911915; } else { if (input[7] >= 0.5) { var9 = 18.719929; } else { var9 = -19.283041; } } } else { if (input[8] >= 0.5) { var9 = -66.93798; } else { if (input[4] >= 3.2586143) { var9 = -31.181293; } else { var9 = 4.2541704; } } } } else { if (input[3] >= 0.41439155) { if (input[10] >= 0.5) { if (input[8] >= 0.5) { var9 = -57.253754; } else { var9 = 44.259327; } } else { if (input[4] >= 0.77028763) { var9 = 34.63077; } else { var9 = 10.169308; } } } else { if (input[7] >= 0.5) { if (input[4] >= -0.8885968) { var9 = 22.80177; } else { var9 = 14.995254; } } else { if (input[2] >= -0.60500103) { var9 = 14.998435; } else { var9 = 4.0855465; } } } } double var10; if (input[1] >= 0.112320915) { if (input[3] >= 0.41439155) { if (input[10] >= 0.5) { var10 = 57.883648; } else { if (input[2] >= -0.60500103) { var10 = -4.4244; } else { var10 = 10.891248; } } } else { if (input[13] >= 1.5) { if (input[11] >= 0.5) { var10 = 16.430185; } else { var10 = 28.339996; } } else { if (input[12] >= 0.5) { var10 = 23.248491; } else { var10 = 19.238781; } } } } else { if (input[12] >= 0.5) { if (input[2] >= -0.60500103) { if (input[1] >= -0.65230584) { var10 = 17.401398; } else { var10 = 4.569379; } } else { if (input[3] >= 0.41439155) { var10 = -38.15419; } else { var10 = -52.68213; } } } else { if (input[13] >= 0.5) { if (input[2] >= -0.60500103) { var10 = 3.4235497; } else { var10 = 16.195328; } } else { if (input[9] >= 0.5) { var10 = 6.5853243; } else { var10 = -0.56392515; } } } } double var11; if (input[0] >= -1.1373768) { if (input[0] >= 0.55411226) { if (input[1] >= 0.112320915) { if (input[1] >= 2.9132018) { var11 = 0.62620103; } else { var11 = 14.878931; } } else { if (input[7] >= 0.5) { var11 = -2.5142908; } else { var11 = 6.8762465; } } } else { if (input[2] >= 1.1372645) { if (input[0] >= -0.8838154) { var11 = 6.8013735; } else { var11 = -15.94711; } } else { if (input[1] >= -0.90718144) { var11 = 10.624735; } else { var11 = 5.6352816; } } } } else { if (input[3] >= 0.41439155) { if (input[6] >= 0.5) { if (input[0] >= -1.1603746) { var11 = 8.050981; } else { var11 = -116.49522; } } else { if (input[0] >= -1.1650553) { var11 = -34.69784; } else { var11 = 6.8808713; } } } else { if (input[0] >= -1.1523635) { if (input[10] >= 0.5) { var11 = -87.16453; } else { var11 = -13.80964; } } else { if (input[2] >= 0.2661317) { var11 = -9.089337; } else { var11 = 11.343403; } } } } double var12; if (input[3] >= 3.6575255) { if (input[13] >= -0.5) { if (input[0] >= -0.9738265) { if (input[3] >= 5.2790923) { var12 = -119.68611; } else { var12 = -42.352478; } } else { var12 = 16.52595; } } else { if (input[13] >= -1.5) { if (input[3] >= 5.2790923) { var12 = -30.987036; } else { var12 = 5.687293; } } else { if (input[1] >= 0.8760308) { var12 = 11.329675; } else { var12 = -29.204445; } } } } else { if (input[0] >= -1.0579419) { if (input[0] >= 0.0083748195) { if (input[1] >= 0.112320915) { var12 = 10.043247; } else { var12 = 0.8739378; } } else { if (input[3] >= 2.0359585) { var12 = -4.389075; } else { var12 = 7.804355; } } } else { if (input[8] >= 0.5) { if (input[4] >= -0.68123615) { var12 = -56.314365; } else { var12 = 1.5425118; } } else { if (input[10] >= 0.5) { var12 = -25.511044; } else { var12 = 5.712395; } } } } double var13; if (input[12] >= 0.5) { if (input[2] >= -0.60500103) { if (input[0] >= -1.0002449) { if (input[0] >= -0.86824346) { var13 = 6.2731028; } else { var13 = 18.373245; } } else { if (input[3] >= 0.41439155) { var13 = -39.403736; } else { var13 = 5.872574; } } } else { if (input[4] >= -0.8885968) { if (input[4] >= -0.68123615) { var13 = -12.1119375; } else { var13 = 27.933044; } } else { if (input[0] >= -0.28290117) { var13 = 13.355004; } else { var13 = -157.3527; } } } } else { if (input[4] >= -0.68123615) { if (input[0] >= -1.1889081) { if (input[0] >= -1.1485381) { var13 = 0.27297387; } else { var13 = 32.984024; } } else { if (input[9] >= 0.5) { var13 = -13.410682; } else { var13 = -76.172905; } } } else { if (input[4] >= -0.8885968) { if (input[0] >= -1.1870629) { var13 = 8.722857; } else { var13 = 37.79114; } } else { if (input[0] >= -0.8034355) { var13 = 0.74079645; } else { var13 = 6.788251; } } } } double var14; if (input[0] >= -1.1613197) { if (input[0] >= -1.1592944) { if (input[0] >= -1.1579443) { if (input[3] >= 2.0359585) { var14 = -2.9327502; } else { var14 = 2.4178932; } } else { var14 = -66.88381; } } else { var14 = 62.04901; } } else { if (input[0] >= -1.16393) { var14 = -163.3757; } else { if (input[10] >= 0.5) { if (input[5] >= 0.5) { var14 = -43.509354; } else { var14 = 17.002201; } } else { if (input[1] >= -0.65230584) { var14 = -5.082277; } else { var14 = 25.77814; } } } } double var15; if (input[1] >= 0.112320915) { if (input[0] >= -1.179322) { if (input[0] >= -1.1613197) { if (input[0] >= -1.1573143) { var15 = 3.3508396; } else { var15 = 65.48243; } } else { if (input[0] >= -1.1664953) { var15 = -109.310425; } else { var15 = -35.480015; } } } else { if (input[5] >= 0.5) { var15 = 67.554756; } else { if (input[4] >= -0.68123615) { var15 = 38.588894; } else { var15 = 18.756956; } } } } else { if (input[3] >= 5.2790923) { var15 = -61.343594; } else { if (input[0] >= -1.2025898) { if (input[0] >= -0.28114593) { var15 = -0.42895037; } else { var15 = 2.6195402; } } else { if (input[0] >= -1.2156863) { var15 = -47.398; } else { var15 = -1.7252911; } } } } double var16; if (input[13] >= 2.5) { if (input[4] >= -0.47387564) { if (input[10] >= 0.5) { var16 = 19.59329; } else { var16 = 70.468575; } } else { if (input[1] >= 0.112320915) { var16 = 11.641106; } else { var16 = 6.0238376; } } } else { if (input[4] >= 1.1850088) { if (input[13] >= 0.5) { if (input[4] >= 2.014451) { var16 = 8.684455; } else { var16 = 22.966534; } } else { if (input[4] >= 1.3923693) { var16 = -2.7507231; } else { var16 = -77.75282; } } } else { if (input[3] >= 0.41439155) { if (input[4] >= 0.77028763) { var16 = 16.853094; } else { var16 = -2.1627543; } } else { if (input[4] >= -0.8885968) { var16 = 2.7756567; } else { var16 = -0.7487754; } } } } double var17; if (input[0] >= 2.6104612) { if (input[2] >= 1.1372645) { if (input[0] >= 2.8206823) { if (input[11] >= 0.5) { var17 = -38.839565; } else { var17 = -62.620193; } } else { var17 = 7.287822; } } else { if (input[0] >= 2.6351695) { if (input[6] >= 0.5) { var17 = 6.541465; } else { var17 = -4.9654703; } } else { var17 = -41.533714; } } } else { if (input[1] >= 0.112320915) { if (input[0] >= -1.1831024) { if (input[0] >= -1.1613197) { var17 = 2.9192882; } else { var17 = -36.10568; } } else { if (input[5] >= 0.5) { var17 = 43.377895; } else { var17 = 16.026234; } } } else { if (input[5] >= 0.5) { if (input[6] >= 0.5) { var17 = -0.56135464; } else { var17 = 5.624888; } } else { if (input[0] >= -1.2654626) { var17 = -0.8403878; } else { var17 = 31.056335; } } } } double var18; if (input[3] >= 3.6575255) { if (input[11] >= 0.5) { if (input[4] >= -0.68123615) { if (input[0] >= -1.0060055) { var18 = -13.423488; } else { var18 = 48.401585; } } else { if (input[0] >= -1.0651429) { var18 = 0.15271015; } else { var18 = -8.452369; } } } else { var18 = -38.282375; } } else { if (input[8] >= 0.5) { if (input[10] >= 0.5) { if (input[0] >= 0.031237647) { var18 = -91.87799; } else { var18 = -27.677452; } } else { if (input[0] >= -1.0598772) { var18 = 5.6159496; } else { var18 = -13.98993; } } } else { if (input[3] >= 0.41439155) { if (input[2] >= -0.60500103) { var18 = -27.822721; } else { var18 = -2.6279118; } } else { if (input[0] >= -0.8071709) { var18 = 0.06455274; } else { var18 = 3.1713042; } } } } double var19; if (input[0] >= 2.6839554) { if (input[4] >= 1.4960496) { if (input[0] >= 2.8206823) { var19 = -45.474518; } else { var19 = 3.229492; } } else { if (input[3] >= 0.41439155) { if (input[3] >= 2.0359585) { var19 = 1.8878864; } else { var19 = 14.81505; } } else { if (input[4] >= 0.6666074) { var19 = 23.195015; } else { var19 = -6.715007; } } } } else { if (input[4] >= -0.68123615) { if (input[0] >= -1.0604622) { if (input[3] >= 2.0359585) { var19 = -9.758646; } else { var19 = 0.86491394; } } else { if (input[13] >= 0.5) { var19 = -46.288296; } else { var19 = -2.084998; } } } else { if (input[0] >= -0.9702261) { if (input[10] >= 0.5) { var19 = 13.765902; } else { var19 = 0.071049064; } } else { if (input[1] >= -0.39743024) { var19 = 3.4194317; } else { var19 = 33.17832; } } } } double var20; if (input[0] >= -1.0579419) { if (input[3] >= 5.2790923) { if (input[13] >= -0.5) { var20 = -69.22155; } else { if (input[13] >= -1.5) { var20 = -13.856637; } else { var20 = 0.12842758; } } } else { if (input[8] >= 0.5) { if (input[3] >= 2.0359585) { var20 = -1.250055; } else { var20 = 5.624028; } } else { if (input[3] >= 0.41439155) { var20 = -6.4796576; } else { var20 = 0.14111054; } } } } else { if (input[1] >= 2.9132018) { var20 = 78.854515; } else { if (input[0] >= -1.0641077) { if (input[9] >= 0.5) { var20 = -11.734342; } else { var20 = -150.81587; } } else { if (input[6] >= 0.5) { var20 = 4.1645727; } else { var20 = -7.5857835; } } } } double var21; if (input[13] >= -0.5) { if (input[3] >= 2.0359585) { if (input[3] >= 3.6575255) { if (input[3] >= 5.2790923) { var21 = -46.729935; } else { var21 = -20.255753; } } else { if (input[0] >= -1.074099) { var21 = -9.346616; } else { var21 = 18.665245; } } } else { if (input[9] >= 0.5) { if (input[3] >= 0.41439155) { var21 = -147.08301; } else { var21 = 0.3073819; } } else { if (input[0] >= -1.010776) { var21 = 4.6676335; } else { var21 = -10.136607; } } } } else { if (input[0] >= -1.0566819) { if (input[10] >= 0.5) { var21 = -29.316162; } else { if (input[4] >= -0.68123615) { var21 = 7.7767005; } else { var21 = 1.0589573; } } } else { if (input[11] >= 0.5) { if (input[0] >= -1.1779718) { var21 = 14.425096; } else { var21 = -0.71505195; } } else { var21 = 41.934597; } } } double var22; if (input[0] >= -1.1028125) { if (input[0] >= -1.1013722) { if (input[0] >= -1.0604622) { if (input[0] >= -1.0407948) { var22 = 0.36555678; } else { var22 = 9.767401; } } else { if (input[0] >= -1.0641077) { var22 = -45.325027; } else { var22 = -4.7544327; } } } else { var22 = -175.64833; } } else { if (input[1] >= 2.9132018) { var22 = 76.40113; } else { if (input[0] >= -1.1373768) { if (input[9] >= 0.5) { var22 = 8.45536; } else { var22 = 31.564167; } } else { if (input[0] >= -1.1423724) { var22 = -36.197815; } else { var22 = 2.8641822; } } } } double var23; if (input[13] >= 2.5) { if (input[0] >= -0.75563955) { if (input[0] >= -0.39190465) { if (input[0] >= 0.7170324) { var23 = 2.352394; } else { var23 = 17.483053; } } else { var23 = -8.217469; } } else { var23 = 68.741554; } } else { if (input[1] >= 2.1494918) { if (input[0] >= -1.0704535) { if (input[0] >= -1.0414249) { var23 = 2.6117754; } else { var23 = -85.30798; } } else { if (input[3] >= 0.41439155) { var23 = 54.56402; } else { var23 = 7.834694; } } } else { if (input[0] >= 0.96159256) { if (input[0] >= 0.9669933) { var23 = -1.7996783; } else { var23 = -64.47756; } } else { if (input[0] >= 0.92792845) { var23 = 21.341352; } else { var23 = -0.177293; } } } } double var24; if (input[4] >= 3.2586143) { if (input[0] >= -0.8377297) { if (input[0] >= 0.25869575) { if (input[0] >= 1.0008824) { var24 = -25.567339; } else { var24 = 14.744424; } } else { if (input[0] >= 0.11539804) { var24 = -58.946354; } else { var24 = 4.666309; } } } else { var24 = -65.78561; } } else { if (input[12] >= 0.5) { if (input[4] >= 0.77028763) { if (input[1] >= -0.65230584) { var24 = 6.796015; } else { var24 = -3.8748004; } } else { if (input[1] >= -0.65230584) { var24 = 1.5722843; } else { var24 = -5.0968976; } } } else { if (input[0] >= -1.2044351) { if (input[0] >= -1.1927786) { var24 = -0.2537231; } else { var24 = 13.428278; } } else { if (input[8] >= 0.5) { var24 = -47.856255; } else { var24 = -1.6130934; } } } } double var25; if (input[5] >= 0.5) { if (input[4] >= -1.0959573) { if (input[0] >= 0.8400326) { if (input[0] >= 0.9067308) { var25 = -1.2772002; } else { var25 = -22.573118; } } else { if (input[6] >= 0.5) { var25 = 0.16855976; } else { var25 = 4.5786915; } } } else { var25 = -46.09022; } } else { if (input[2] >= 1.1372645) { if (input[11] >= 0.5) { var25 = 63.907482; } else { if (input[12] >= 0.5) { var25 = 6.5244155; } else { var25 = -12.243132; } } } else { if (input[4] >= -0.26651508) { if (input[0] >= -1.1603296) { var25 = -2.693653; } else { var25 = -46.41377; } } else { if (input[2] >= -0.60500103) { var25 = 4.54096; } else { var25 = -0.46053287; } } } } double var26; if (input[1] >= 0.112320915) { if (input[4] >= -0.8885968) { if (input[13] >= -0.5) { if (input[11] >= 0.5) { var26 = -4.120392; } else { var26 = 1.8585286; } } else { if (input[2] >= -0.60500103) { var26 = 9.289226; } else { var26 = 2.014836; } } } else { if (input[7] >= 0.5) { if (input[2] >= -0.60500103) { var26 = -22.293093; } else { var26 = 4.087899; } } else { var26 = 50.089314; } } } else { if (input[4] >= -0.8885968) { if (input[4] >= -0.68123615) { if (input[3] >= 0.41439155) { var26 = -4.367316; } else { var26 = -0.08913819; } } else { if (input[7] >= 0.5) { var26 = 3.4653053; } else { var26 = 22.376299; } } } else { if (input[2] >= -0.60500103) { if (input[7] >= 0.5) { var26 = 4.639402; } else { var26 = 32.232265; } } else { if (input[12] >= 0.5) { var26 = -75.83786; } else { var26 = -2.4805021; } } } } double var27; if (input[10] >= 0.5) { if (input[1] >= -0.90718144) { if (input[2] >= 1.1372645) { if (input[0] >= -0.5392978) { var27 = -65.09315; } else { var27 = -23.705198; } } else { if (input[0] >= -1.1443976) { var27 = -3.8233435; } else { var27 = -47.873787; } } } else { if (input[13] >= 0.5) { if (input[0] >= -1.0881857) { var27 = 6.3074617; } else { var27 = 48.21055; } } else { if (input[0] >= -1.2313483) { var27 = 3.3293352; } else { var27 = 63.340492; } } } } else { if (input[7] >= 0.5) { if (input[5] >= 0.5) { if (input[1] >= -0.65230584) { var27 = 3.2068865; } else { var27 = -6.119835; } } else { if (input[0] >= -1.2661376) { var27 = 0.26134154; } else { var27 = 35.127155; } } } else { if (input[13] >= 0.5) { var27 = 43.92848; } else { if (input[0] >= -1.009786) { var27 = -7.3419294; } else { var27 = 18.001553; } } } } double var28; if (input[0] >= -1.220052) { if (input[0] >= -1.211996) { if (input[0] >= -1.0113611) { if (input[0] >= -0.9522239) { var28 = -0.04635202; } else { var28 = 7.458867; } } else { if (input[0] >= -1.0132064) { var28 = -78.54606; } else { var28 = -1.7559289; } } } else { if (input[0] >= -1.2156863) { var28 = -72.64668; } else { var28 = -3.2740362; } } } else { if (input[0] >= -1.2272528) { if (input[0] >= -1.2240574) { var28 = 48.41117; } else { var28 = 64.93376; } } else { if (input[0] >= -1.2413396) { if (input[0] >= -1.2332835) { var28 = -13.813472; } else { var28 = 57.241142; } } else { if (input[0] >= -1.2436349) { var28 = -81.38212; } else { var28 = 3.4469526; } } } } double var29; if (input[0] >= 3.157864) { var29 = -20.65781; } else { if (input[9] >= 0.5) { if (input[0] >= -1.1677555) { if (input[0] >= -1.1532637) { var29 = -0.20954037; } else { var29 = 21.08421; } } else { if (input[0] >= -1.1792319) { var29 = -27.783361; } else { var29 = 0.8293829; } } } else { if (input[0] >= -1.1218048) { if (input[0] >= -1.0119011) { var29 = 1.6578834; } else { var29 = -15.785636; } } else { if (input[4] >= -0.47387564) { var29 = 52.502968; } else { var29 = -2.1309283; } } } } return 0.5 + (var0 + var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8 + var9 + var10 + var11 + var12 + var13 + var14 + var15 + var16 + var17 + var18 + var19 + var20 + var21 + var22 + var23 + var24 + var25 + var26 + var27 + var28 + var29); } }
52,379
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Capacity_traffic_light.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/Capacity_traffic_light.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; /** * Generated model, do not modify. */ public class Capacity_traffic_light implements FeatureRegressor { @Override public double predict(Object2DoubleMap<String> ft) { double[] data = new double[14]; data[0] = (ft.getDouble("length") - 129.80599755865998) / 93.91484389753218; data[1] = (ft.getDouble("speed") - 12.726744879967448) / 3.0571847342843816; data[2] = (ft.getDouble("numFoes") - 2.4327953343279534) / 0.6498808003630541; data[3] = (ft.getDouble("numLanes") - 1.8202902482029024) / 0.9477667668865584; data[4] = (ft.getDouble("junctionSize") - 13.943035399430354) / 4.355585031201389; data[5] = ft.getDouble("dir_l"); data[6] = ft.getDouble("dir_r"); data[7] = ft.getDouble("dir_s"); data[8] = ft.getDouble("dir_multiple_s"); data[9] = ft.getDouble("dir_exclusive"); data[10] = ft.getDouble("priority_lower"); data[11] = ft.getDouble("priority_equal"); data[12] = ft.getDouble("priority_higher"); data[13] = ft.getDouble("changeNumLanes"); for (int i = 0; i < data.length; i++) if (Double.isNaN(data[i])) throw new IllegalArgumentException("Invalid data at index: " + i); return score(data); } public static double score(double[] input) { double var0; if (input[13] >= -0.5) { if (input[4] >= 0.5870542) { if (input[13] >= 0.5) { if (input[3] >= -0.33794206) { var0 = 367.50482; } else { var0 = 424.35815; } } else { if (input[9] >= 0.5) { var0 = 206.34163; } else { var0 = 364.96725; } } } else { if (input[12] >= 0.5) { if (input[4] >= -0.5608972) { var0 = 462.75888; } else { var0 = 541.3571; } } else { if (input[5] >= 0.5) { var0 = 423.2037; } else { var0 = 484.65845; } } } } else { if (input[4] >= 0.12787366) { if (input[9] >= 0.5) { if (input[3] >= 0.7171699) { var0 = 147.20288; } else { var0 = 192.373; } } else { if (input[13] >= -1.5) { var0 = 270.54285; } else { var0 = 219.35835; } } } else { if (input[9] >= 0.5) { if (input[3] >= 0.7171699) { var0 = 185.97235; } else { var0 = 272.20184; } } else { if (input[13] >= -1.5) { var0 = 396.2951; } else { var0 = 305.99268; } } } } double var1; if (input[3] >= -0.33794206) { if (input[9] >= 0.5) { if (input[6] >= 0.5) { if (input[3] >= 0.7171699) { var1 = 88.558716; } else { var1 = 123.2088; } } else { if (input[0] >= -0.88001) { var1 = 194.34872; } else { var1 = 101.6791; } } } else { if (input[3] >= 0.7171699) { if (input[6] >= 0.5) { var1 = 195.41751; } else { var1 = 278.5694; } } else { if (input[0] >= -0.9177569) { var1 = 304.28644; } else { var1 = 219.76962; } } } } else { if (input[4] >= -0.5608972) { if (input[10] >= 0.5) { if (input[0] >= -0.9436314) { var1 = 252.97453; } else { var1 = 198.98586; } } else { if (input[0] >= -0.67690045) { var1 = 286.61203; } else { var1 = 250.8239; } } } else { if (input[7] >= 0.5) { if (input[0] >= -0.89715314) { var1 = 384.269; } else { var1 = 262.40286; } } else { if (input[0] >= -0.9429393) { var1 = 287.37; } else { var1 = 192.14041; } } } } double var2; if (input[13] >= -0.5) { if (input[1] >= -0.9835012) { if (input[4] >= 0.5870542) { if (input[13] >= 0.5) { var2 = 181.357; } else { var2 = 126.57919; } } else { if (input[7] >= 0.5) { var2 = 203.57613; } else { var2 = 150.32642; } } } else { if (input[4] >= -0.5608972) { if (input[12] >= 0.5) { var2 = 96.03897; } else { var2 = 140.53992; } } else { if (input[2] >= -1.4353329) { var2 = 171.74016; } else { var2 = 230.64528; } } } } else { if (input[6] >= 0.5) { if (input[4] >= -0.10171662) { if (input[4] >= 1.275825) { var2 = 103.24647; } else { var2 = 66.63641; } } else { if (input[7] >= 0.5) { var2 = 123.71024; } else { var2 = 85.63842; } } } else { if (input[8] >= 0.5) { if (input[13] >= -1.5) { var2 = 173.88304; } else { var2 = 111.6038; } } else { if (input[4] >= -1.0200777) { var2 = 59.0332; } else { var2 = 135.35942; } } } } double var3; if (input[13] >= -0.5) { if (input[4] >= 0.12787366) { if (input[3] >= -0.33794206) { if (input[9] >= 0.5) { var3 = 11.842827; } else { var3 = 91.307655; } } else { if (input[1] >= -0.5288346) { var3 = 114.71714; } else { var3 = 86.89338; } } } else { if (input[12] >= 0.5) { if (input[7] >= 0.5) { var3 = 140.3354; } else { var3 = 45.98516; } } else { if (input[3] >= -0.33794206) { var3 = 75.785545; } else { var3 = 120.961426; } } } } else { if (input[4] >= 0.35746396) { if (input[4] >= 1.275825) { if (input[13] >= -1.5) { var3 = 72.557045; } else { var3 = 29.454908; } } else { if (input[13] >= -1.5) { var3 = 42.771923; } else { var3 = 24.680012; } } } else { if (input[9] >= 0.5) { if (input[6] >= 0.5) { var3 = 54.55675; } else { var3 = 81.069145; } } else { if (input[13] >= -1.5) { var3 = 104.61941; } else { var3 = 63.19876; } } } } double var4; if (input[3] >= -0.33794206) { if (input[9] >= 0.5) { if (input[13] >= -0.5) { if (input[4] >= 0.5870542) { var4 = 10.065217; } else { var4 = -63.55682; } } else { if (input[3] >= 0.7171699) { var4 = 12.907462; } else { var4 = 37.413372; } } } else { if (input[4] >= 0.5870542) { if (input[8] >= 0.5) { var4 = 42.821278; } else { var4 = -51.201416; } } else { if (input[3] >= 1.7722819) { var4 = 39.46324; } else { var4 = 86.999664; } } } } else { if (input[2] >= 0.10341075) { if (input[4] >= 2.079391) { if (input[1] >= -0.5288346) { var4 = -50.248425; } else { var4 = -97.71123; } } else { if (input[1] >= 1.7428633) { var4 = -55.380566; } else { var4 = 62.089447; } } } else { if (input[10] >= 0.5) { if (input[4] >= -1.0200777) { var4 = 78.4107; } else { var4 = 51.70315; } } else { if (input[1] >= 0.83516544) { var4 = 25.73279; } else { var4 = 103.682045; } } } } double var5; if (input[0] >= -0.8952365) { if (input[13] >= -0.5) { if (input[1] >= -0.9835012) { if (input[6] >= 0.5) { var5 = 50.868576; } else { var5 = 91.90699; } } else { if (input[13] >= 0.5) { var5 = 47.022156; } else { var5 = 18.278261; } } } else { if (input[1] >= -0.07416786) { if (input[4] >= 0.35746396) { var5 = 17.759998; } else { var5 = 34.367268; } } else { if (input[13] >= -1.5) { var5 = -2.7607558; } else { var5 = -42.612473; } } } } else { if (input[0] >= -1.062356) { if (input[0] >= -0.98590374) { if (input[0] >= -0.8997086) { var5 = -122.39893; } else { var5 = 14.461245; } } else { if (input[1] >= -0.5288346) { var5 = -96.585014; } else { var5 = 5.1462226; } } } else { if (input[12] >= 0.5) { if (input[0] >= -1.1253918) { var5 = -24.820234; } else { var5 = 22.29909; } } else { if (input[1] >= 1.7428633) { var5 = -63.869198; } else { var5 = 47.73467; } } } } double var6; if (input[3] >= -0.33794206) { if (input[8] >= 0.5) { if (input[0] >= -0.77262545) { if (input[4] >= 0.5870542) { var6 = 18.032515; } else { var6 = 55.521206; } } else { if (input[0] >= -1.1238478) { var6 = -8.596528; } else { var6 = 44.01731; } } } else { if (input[13] >= -0.5) { if (input[12] >= 0.5) { var6 = -56.772415; } else { var6 = -3.060491; } } else { if (input[1] >= 2.6505613) { var6 = -55.203384; } else { var6 = 12.321973; } } } } else { if (input[2] >= 0.10341075) { if (input[4] >= 2.079391) { if (input[0] >= -0.21568474) { var6 = -72.007034; } else { var6 = -48.37604; } } else { if (input[1] >= 0.83516544) { var6 = -54.694817; } else { var6 = 24.901882; } } } else { if (input[0] >= -0.9593371) { if (input[1] >= -0.9835012) { var6 = 49.22337; } else { var6 = 26.828186; } } else { if (input[0] >= -1.0187526) { var6 = -68.58256; } else { var6 = 26.439283; } } } } double var7; if (input[0] >= -0.81649494) { if (input[1] >= -0.07416786) { if (input[13] >= -0.5) { if (input[4] >= 0.35746396) { var7 = 20.20199; } else { var7 = 35.359833; } } else { if (input[4] >= -0.79048747) { var7 = 3.465759; } else { var7 = 17.98743; } } } else { if (input[12] >= 0.5) { if (input[8] >= 0.5) { var7 = -28.217916; } else { var7 = -5.8268604; } } else { if (input[13] >= 1.5) { var7 = 43.058315; } else { var7 = 8.249209; } } } } else { if (input[3] >= 0.7171699) { if (input[0] >= -0.9773854) { if (input[4] >= -0.10171662) { var7 = 7.316835; } else { var7 = -31.032711; } } else { if (input[0] >= -1.0923831) { var7 = -98.45283; } else { var7 = -29.935713; } } } else { if (input[0] >= -1.0580436) { if (input[0] >= -0.9774386) { var7 = 6.3834796; } else { var7 = -47.006844; } } else { if (input[0] >= -1.3048097) { var7 = 21.243135; } else { var7 = -110.55501; } } } } double var8; if (input[4] >= -1.7088487) { if (input[1] >= 0.83516544) { if (input[7] >= 0.5) { if (input[4] >= -1.2496681) { var8 = 1.5170248; } else { var8 = -33.17703; } } else { if (input[9] >= 0.5) { var8 = -35.911354; } else { var8 = -76.122894; } } } else { if (input[5] >= 0.5) { if (input[13] >= 1.5) { var8 = 26.433702; } else { var8 = 6.529245; } } else { if (input[3] >= 1.7722819) { var8 = -37.337563; } else { var8 = 20.534056; } } } } else { if (input[4] >= -2.3976195) { if (input[7] >= 0.5) { if (input[4] >= -2.1680293) { var8 = 39.35434; } else { var8 = -10.004152; } } else { if (input[10] >= 0.5) { var8 = 78.96174; } else { var8 = 33.651665; } } } else { if (input[2] >= -2.9740767) { if (input[10] >= 0.5) { var8 = 1.8065205; } else { var8 = -99.45925; } } else { if (input[3] >= -0.33794206) { var8 = 33.425495; } else { var8 = 61.353897; } } } } double var9; if (input[0] >= -0.77816236) { if (input[0] >= 1.1071093) { if (input[1] >= -0.9835012) { if (input[0] >= 3.8216429) { var9 = -37.22993; } else { var9 = 24.57778; } } else { if (input[0] >= 1.1284053) { var9 = 0.3728113; } else { var9 = 66.340096; } } } else { if (input[13] >= -1.5) { if (input[1] >= -0.9835012) { var9 = 9.357347; } else { var9 = 0.60598314; } } else { if (input[3] >= 2.8273938) { var9 = 3.6079726; } else { var9 = -16.304659; } } } } else { if (input[13] >= 2.5) { var9 = -92.2187; } else { if (input[1] >= 1.7428633) { if (input[0] >= -1.0156115) { var9 = -87.49487; } else { var9 = -10.97046; } } else { if (input[0] >= -1.1236882) { var9 = -6.368576; } else { var9 = 12.208469; } } } } double var10; if (input[4] >= 2.6533668) { var10 = -88.87163; } else { if (input[4] >= 1.7350056) { if (input[12] >= 0.5) { if (input[0] >= -0.57963145) { var10 = 34.971157; } else { var10 = 104.556496; } } else { if (input[0] >= 0.056317) { var10 = -37.35852; } else { var10 = 14.457261; } } } else { if (input[13] >= 1.5) { if (input[0] >= -0.83342516) { var10 = 24.28627; } else { var10 = -11.021199; } } else { if (input[4] >= -0.5608972) { var10 = -0.095924966; } else { var10 = 6.294528; } } } } double var11; if (input[4] >= -1.7088487) { if (input[0] >= -1.2990066) { if (input[2] >= -2.9740767) { if (input[6] >= 0.5) { var11 = 0.9681548; } else { var11 = 11.654723; } } else { if (input[3] >= 1.7722819) { var11 = -112.22902; } else { var11 = -4.612288; } } } else { var11 = -103.43151; } } else { if (input[6] >= 0.5) { if (input[0] >= -1.0409536) { if (input[0] >= -0.6289314) { var11 = 28.585384; } else { var11 = 76.80479; } } else { var11 = -41.350395; } } else { if (input[2] >= -2.9740767) { if (input[4] >= -2.3976195) { var11 = 2.070047; } else { var11 = -54.752262; } } else { if (input[0] >= -1.1103783) { var11 = 54.594933; } else { var11 = 6.3451734; } } } } double var12; if (input[1] >= 1.7428633) { if (input[0] >= -1.1630856) { if (input[7] >= 0.5) { if (input[0] >= -1.015718) { var12 = -7.1897907; } else { var12 = 30.621687; } } else { if (input[0] >= -0.7237514) { var12 = -30.915073; } else { var12 = -95.31315; } } } else { var12 = -131.99312; } } else { if (input[0] >= -1.2741436) { if (input[0] >= -1.2439567) { if (input[7] >= 0.5) { var12 = 2.8154845; } else { var12 = -5.132764; } } else { if (input[13] >= 0.5) { var12 = 123.264465; } else { var12 = 2.819096; } } } else { if (input[4] >= -0.79048747) { var12 = -125.41991; } else { var12 = 38.844765; } } } double var13; if (input[0] >= -0.97573495) { if (input[0] >= -0.9735521) { if (input[0] >= 1.4593966) { if (input[4] >= -1.4792583) { var13 = 5.815014; } else { var13 = 40.06303; } } else { if (input[13] >= 0.5) { var13 = 5.9172087; } else { var13 = -1.522723; } } } else { var13 = 94.280464; } } else { if (input[0] >= -1.0580436) { if (input[1] >= -0.5288346) { if (input[0] >= -1.0477684) { var13 = -36.895367; } else { var13 = -119.79888; } } else { if (input[3] >= -0.33794206) { var13 = 58.00334; } else { var13 = -6.6933064; } } } else { if (input[3] >= 1.7722819) { var13 = -92.35661; } else { if (input[0] >= -1.0691174) { var13 = 48.734802; } else { var13 = 2.117843; } } } } double var14; if (input[11] >= 0.5) { if (input[3] >= 1.7722819) { if (input[5] >= 0.5) { if (input[13] >= -1.5) { var14 = -7.957535; } else { var14 = -0.5557697; } } else { if (input[13] >= -0.5) { var14 = -104.637955; } else { var14 = -6.9212604; } } } else { if (input[8] >= 0.5) { if (input[2] >= -1.4353329) { var14 = 28.980356; } else { var14 = -2.3783262; } } else { if (input[7] >= 0.5) { var14 = 4.044478; } else { var14 = -6.5452895; } } } } else { if (input[13] >= 0.5) { if (input[7] >= 0.5) { if (input[6] >= 0.5) { var14 = -0.44899765; } else { var14 = -11.136123; } } else { if (input[2] >= 0.10341075) { var14 = 13.100871; } else { var14 = 25.965353; } } } else { if (input[7] >= 0.5) { if (input[1] >= -0.5288346) { var14 = 2.1125808; } else { var14 = -7.3830647; } } else { if (input[1] >= -0.9835012) { var14 = -18.711391; } else { var14 = -2.7296703; } } } } double var15; if (input[5] >= 0.5) { if (input[6] >= 0.5) { if (input[12] >= 0.5) { if (input[9] >= 0.5) { var15 = -0.6816591; } else { var15 = -12.157176; } } else { if (input[9] >= 0.5) { var15 = -2.0696847; } else { var15 = 7.578963; } } } else { if (input[0] >= -0.70538366) { if (input[8] >= 0.5) { var15 = 26.441994; } else { var15 = 9.369286; } } else { if (input[2] >= -1.4353329) { var15 = -12.483892; } else { var15 = 35.922173; } } } } else { if (input[6] >= 0.5) { if (input[8] >= 0.5) { if (input[13] >= -0.5) { var15 = 22.111153; } else { var15 = -6.503288; } } else { if (input[2] >= 0.10341075) { var15 = -20.640434; } else { var15 = 6.24046; } } } else { if (input[0] >= -1.0711937) { if (input[13] >= 1.5) { var15 = -110.477066; } else { var15 = -18.03973; } } else { if (input[0] >= -1.0825338) { var15 = 67.67926; } else { var15 = 5.2958064; } } } } double var16; if (input[3] >= -0.33794206) { if (input[8] >= 0.5) { if (input[0] >= -0.8923615) { if (input[0] >= -0.8263444) { var16 = 4.6402855; } else { var16 = 38.941223; } } else { if (input[0] >= -0.90295625) { var16 = -112.70789; } else { var16 = -12.201777; } } } else { if (input[4] >= 1.275825) { if (input[3] >= 1.7722819) { var16 = -10.222688; } else { var16 = -67.16906; } } else { if (input[0] >= 1.2416995) { var16 = -56.433655; } else { var16 = -7.2505217; } } } } else { if (input[8] >= 0.5) { if (input[0] >= -0.9555571) { if (input[4] >= 0.8166445) { var16 = -3.7876277; } else { var16 = -63.65588; } } else { var16 = 48.45108; } } else { if (input[4] >= 1.5054154) { if (input[0] >= 0.0721292) { var16 = -14.576662; } else { var16 = -54.5959; } } else { if (input[7] >= 0.5) { var16 = 6.5006685; } else { var16 = -2.639079; } } } } double var17; if (input[4] >= -1.0200777) { if (input[4] >= -0.10171662) { if (input[4] >= 0.5870542) { if (input[10] >= 0.5) { var17 = 4.3190055; } else { var17 = -6.19649; } } else { if (input[3] >= 0.7171699) { var17 = 23.102257; } else { var17 = 0.5622126; } } } else { if (input[9] >= 0.5) { if (input[13] >= 0.5) { var17 = 6.520137; } else { var17 = -47.899445; } } else { if (input[0] >= -0.9142963) { var17 = 7.2601857; } else { var17 = -32.4989; } } } } else { if (input[13] >= 2.5) { var17 = -97.06859; } else { if (input[7] >= 0.5) { if (input[4] >= -1.4792583) { var17 = 13.207709; } else { var17 = -6.060059; } } else { if (input[4] >= -1.4792583) { var17 = -12.0581665; } else { var17 = 21.24667; } } } } double var18; if (input[3] >= 0.7171699) { if (input[4] >= -0.10171662) { if (input[4] >= 0.35746396) { if (input[0] >= -0.9264882) { var18 = -1.5360795; } else { var18 = -33.38052; } } else { if (input[12] >= 0.5) { var18 = 32.38799; } else { var18 = -11.132994; } } } else { if (input[4] >= -1.7088487) { if (input[7] >= 0.5) { var18 = -19.722092; } else { var18 = 9.975108; } } else { if (input[0] >= -0.70533043) { var18 = 34.78269; } else { var18 = -26.166338; } } } } else { if (input[12] >= 0.5) { if (input[4] >= -2.1680293) { if (input[1] >= -0.5288346) { var18 = 1.0084791; } else { var18 = -13.03896; } } else { if (input[2] >= -1.4353329) { var18 = -111.12665; } else { var18 = -9.917932; } } } else { if (input[9] >= 0.5) { if (input[7] >= 0.5) { var18 = 3.0441973; } else { var18 = -5.132044; } } else { if (input[3] >= -0.33794206) { var18 = 31.354824; } else { var18 = 3.2640269; } } } } double var19; if (input[0] >= 1.8111515) { if (input[0] >= 3.8108885) { var19 = -40.914886; } else { if (input[0] >= 2.6085758) { if (input[0] >= 3.4641914) { var19 = 21.752987; } else { var19 = -4.062738; } } else { if (input[2] >= 0.10341075) { var19 = 24.770464; } else { var19 = 4.686978; } } } } else { if (input[4] >= -1.0200777) { if (input[0] >= -1.0619833) { if (input[0] >= -0.9213772) { var19 = -1.3459871; } else { var19 = -17.356071; } } else { if (input[2] >= 0.10341075) { var19 = 21.783834; } else { var19 = -6.78555; } } } else { if (input[0] >= -1.2499195) { if (input[0] >= -1.045479) { var19 = 4.8528085; } else { var19 = -10.240755; } } else { if (input[0] >= -1.2683938) { var19 = 75.3572; } else { var19 = 2.5274491; } } } } double var20; if (input[4] >= 1.7350056) { if (input[12] >= 0.5) { if (input[4] >= 2.1941862) { if (input[0] >= -0.31705314) { var20 = -41.948612; } else { var20 = 18.974371; } } else { if (input[0] >= -0.62914443) { var20 = 49.45087; } else { var20 = 91.05704; } } } else { if (input[0] >= -0.7876923) { if (input[13] >= 0.5) { var20 = 23.00791; } else { var20 = -10.842686; } } else { var20 = -43.38333; } } } else { if (input[4] >= 0.5870542) { if (input[12] >= 0.5) { if (input[4] >= 1.0462348) { var20 = -0.8745569; } else { var20 = -10.110093; } } else { if (input[5] >= 0.5) { var20 = 0.21081121; } else { var20 = 50.255238; } } } else { if (input[8] >= 0.5) { if (input[1] >= -0.5288346) { var20 = 9.206179; } else { var20 = -21.05868; } } else { if (input[13] >= 1.5) { var20 = 14.225177; } else { var20 = -1.3628882; } } } } double var21; if (input[0] >= -1.3048097) { if (input[0] >= -1.0982928) { if (input[0] >= -1.0899341) { if (input[0] >= -1.0788071) { var21 = -0.30390498; } else { var21 = 25.795858; } } else { if (input[10] >= 0.5) { var21 = 2.6885552; } else { var21 = -93.70193; } } } else { if (input[0] >= -1.1053736) { if (input[3] >= -0.33794206) { var21 = 23.336504; } else { var21 = 66.62827; } } else { if (input[0] >= -1.1236882) { var21 = -15.759997; } else { var21 = 8.292577; } } } } else { var21 = -58.131153; } double var22; if (input[0] >= -1.0315834) { if (input[0] >= -1.0243428) { if (input[0] >= -1.0187526) { if (input[0] >= -1.0148661) { var22 = 0.032961894; } else { var22 = -75.93611; } } else { if (input[4] >= -0.79048747) { var22 = -30.125967; } else { var22 = 99.532455; } } } else { if (input[0] >= -1.0270048) { var22 = -101.17118; } else { if (input[12] >= 0.5) { var22 = -70.19988; } else { var22 = 7.367056; } } } } else { if (input[0] >= -1.0406342) { if (input[5] >= 0.5) { if (input[4] >= -0.5608972) { var22 = 71.505905; } else { var22 = -47.84937; } } else { var22 = 159.42519; } } else { if (input[0] >= -1.0580436) { if (input[2] >= 0.10341075) { var22 = 14.025388; } else { var22 = -46.703384; } } else { if (input[0] >= -1.072578) { var22 = 42.089104; } else { var22 = 1.7467211; } } } } double var23; if (input[11] >= 0.5) { if (input[0] >= 0.04944908) { if (input[4] >= 0.5870542) { if (input[0] >= 0.34556842) { var23 = 4.179637; } else { var23 = -26.827099; } } else { if (input[0] >= 0.34615403) { var23 = 7.450673; } else { var23 = 26.639925; } } } else { if (input[0] >= -0.098344386) { if (input[9] >= 0.5) { var23 = -10.470457; } else { var23 = -75.14347; } } else { if (input[0] >= -1.1230493) { var23 = -0.56143826; } else { var23 = 20.072157; } } } } else { if (input[0] >= -1.2706298) { if (input[0] >= -1.2559357) { if (input[4] >= -2.3976195) { var23 = -1.2197328; } else { var23 = -30.672867; } } else { if (input[9] >= 0.5) { var23 = -6.778308; } else { var23 = 96.23706; } } } else { if (input[12] >= 0.5) { var23 = -0.8686448; } else { var23 = -64.14468; } } } double var24; if (input[0] >= -1.3034787) { if (input[4] >= 1.0462348) { if (input[2] >= 0.10341075) { if (input[0] >= 1.2677867) { var24 = -22.290045; } else { var24 = -0.11668297; } } else { if (input[3] >= 0.7171699) { var24 = 6.5693946; } else { var24 = 30.435068; } } } else { if (input[0] >= -1.2817037) { if (input[0] >= -1.2706298) { var24 = -0.13412413; } else { var24 = -70.36895; } } else { var24 = 46.042397; } } } else { var24 = -57.535797; } double var25; if (input[0] >= 3.6052234) { if (input[3] >= -0.33794206) { var25 = 5.3210993; } else { if (input[0] >= 3.8257422) { var25 = -56.23565; } else { if (input[0] >= 3.7195292) { var25 = 12.495119; } else { var25 = -35.313454; } } } } else { if (input[0] >= 3.4756913) { if (input[0] >= 3.5295167) { var25 = 27.95722; } else { var25 = 60.733276; } } else { if (input[8] >= 0.5) { if (input[3] >= -0.33794206) { var25 = 2.9827752; } else { var25 = -23.103254; } } else { if (input[3] >= -0.33794206) { var25 = -5.7312903; } else { var25 = 0.3952112; } } } } double var26; if (input[0] >= 0.7945922) { if (input[0] >= 0.81434417) { if (input[6] >= 0.5) { if (input[13] >= -0.5) { var26 = -4.437909; } else { var26 = 32.362137; } } else { if (input[12] >= 0.5) { var26 = 4.9694543; } else { var26 = 45.244526; } } } else { if (input[2] >= 0.10341075) { var26 = -90.08293; } else { if (input[0] >= 0.8024185) { var26 = -9.868344; } else { var26 = -2.538421; } } } } else { if (input[0] >= 0.7876711) { var26 = 56.135788; } else { if (input[0] >= 0.7830924) { var26 = -52.967896; } else { if (input[0] >= 0.7261791) { var26 = 20.134798; } else { var26 = 0.7366501; } } } } double var27; if (input[4] >= -1.9384389) { if (input[4] >= -1.4792583) { if (input[0] >= -1.2941618) { if (input[13] >= -1.5) { var27 = 0.3939423; } else { var27 = -7.9987173; } } else { var27 = -45.682926; } } else { if (input[2] >= -1.4353329) { if (input[6] >= 0.5) { var27 = 22.475674; } else { var27 = -13.486884; } } else { if (input[13] >= -0.5) { var27 = -54.619587; } else { var27 = 20.175884; } } } } else { if (input[2] >= 0.10341075) { var27 = -45.88502; } else { if (input[0] >= -1.0286553) { if (input[0] >= -0.8878362) { var27 = 13.42434; } else { var27 = -36.88931; } } else { if (input[13] >= 0.5) { var27 = -1.9395915; } else { var27 = 48.769196; } } } } double var28; if (input[1] >= 1.7428633) { if (input[13] >= -0.5) { if (input[2] >= -1.4353329) { if (input[4] >= 0.2426688) { var28 = -62.849438; } else { var28 = -9.177687; } } else { var28 = -71.55584; } } else { if (input[5] >= 0.5) { if (input[4] >= 0.70184934) { var28 = 15.813318; } else { var28 = 2.7658036; } } else { if (input[8] >= 0.5) { var28 = -35.10312; } else { var28 = -7.872855; } } } } else { if (input[3] >= 0.7171699) { if (input[4] >= -0.10171662) { if (input[5] >= 0.5) { var28 = -2.2804086; } else { var28 = 28.995634; } } else { if (input[4] >= -0.79048747) { var28 = -14.542291; } else { var28 = 0.9258674; } } } else { if (input[4] >= 2.1941862) { if (input[13] >= 0.5) { var28 = -38.98531; } else { var28 = -19.796707; } } else { if (input[2] >= -1.4353329) { var28 = 1.3527946; } else { var28 = 11.355799; } } } } double var29; if (input[4] >= -2.3976195) { if (input[0] >= -1.2169108) { if (input[1] >= -0.07416786) { if (input[0] >= -0.9213772) { var29 = 2.0215807; } else { var29 = -5.4085274; } } else { if (input[0] >= -0.531556) { var29 = -4.501681; } else { var29 = 8.182131; } } } else { if (input[2] >= 0.10341075) { if (input[4] >= -0.44610205) { var29 = 11.59023; } else { var29 = 87.30313; } } else { if (input[12] >= 0.5) { var29 = -33.024693; } else { var29 = 23.35533; } } } } else { if (input[10] >= 0.5) { var29 = 27.671478; } else { if (input[2] >= -2.9740767) { if (input[0] >= -1.0329144) { var29 = -89.100525; } else { var29 = -41.065678; } } else { if (input[0] >= -1.0396758) { var29 = -7.8055677; } else { var29 = -6.5929723; } } } } return 0.5 + (var0 + var1 + var2 + var3 + var4 + var5 + var6 + var7 + var8 + var9 + var10 + var11 + var12 + var13 + var14 + var15 + var16 + var17 + var18 + var19 + var20 + var21 + var22 + var23 + var24 + var25 + var26 + var27 + var28 + var29); } }
53,561
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
FeatureRegressor.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/network/FeatureRegressor.java
package org.matsim.prepare.network; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; /** * Predictor interface for regression. */ public interface FeatureRegressor { /** * Predict value from given features. */ double predict(Object2DoubleMap<String> ft); /** * Predict values with adjusted model params. */ default double predict(Object2DoubleMap<String> ft, double[] params) { throw new UnsupportedOperationException("Not implemented"); } /** * Return data that is used for internal prediction function (normalization already applied). */ default double[] getData(Object2DoubleMap<String> ft) { throw new UnsupportedOperationException("Not implemented"); } }
700
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateBrandenburgPopulation.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/CreateBrandenburgPopulation.java
package org.matsim.prepare.population; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.json.JsonMapper; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.MultiPolygon; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import org.matsim.application.options.LanduseOptions; import org.matsim.application.options.ShpOptions; import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.scenario.ProjectionUtils; import org.matsim.run.OpenBerlinScenario; import org.opengis.feature.simple.SimpleFeature; import picocli.CommandLine; import java.nio.file.Path; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SplittableRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.matsim.prepare.population.CreateBerlinPopulation.generateId; import static org.matsim.prepare.download.CalculateEmployedPopulation.*; @CommandLine.Command( name = "brandenburg-population", description = "Create synthetic population for brandenburg." ) public class CreateBrandenburgPopulation implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(CreateBerlinPopulation.class); private static final int MAX_AGE = 100; @CommandLine.Option(names = "--population", description = "Path to population csv (Regional statistic)", required = true) private Path stats; @CommandLine.Option(names = "--employees", description = "Path to employees json (See CalculateEmployedPopulation).", required = true) private Path employedPath; @CommandLine.Option(names = "--output", description = "Path to output population", required = true) private Path output; @CommandLine.Option(names = "--sample", description = "Sample size to generate", defaultValue = "0.25") private double sample; @CommandLine.Mixin private ShpOptions shp = new ShpOptions(); @CommandLine.Mixin private LanduseOptions landuse = new LanduseOptions(); private final CsvOptions csv = new CsvOptions(CSVFormat.Predefined.Default); private SplittableRandom rnd; private Population population; private Map<Integer, Employment> employed; public static void main(String[] args) { new CreateBrandenburgPopulation().execute(args); } @Override public Integer call() throws Exception { if (shp.getShapeFile() == null) { log.error("Shape file with Gemeinden and ARS/AGS codes is required."); return 2; } employed = new JsonMapper().readerFor(new TypeReference<Map<Integer, Employment>>() {}) .readValue(employedPath.toFile()); // Filter for Brandenburg Map<String, SimpleFeature> zones = shp.readFeatures().stream() .filter(ft -> ft.getAttribute("SN_L").equals("12")) .collect(Collectors.toMap(ft -> (String) ft.getAttribute("AGS"), ft -> ft)); Set<String> found = new HashSet<>(); rnd = new SplittableRandom(0); population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); try (CSVParser parser = csv.createParser(stats)) { for (CSVRecord row : parser) { String code = row.get("code"); // Some cities are LK level if (!zones.containsKey(code) && code.length() == 5) code += "000"; if (zones.containsKey(code)) { addPersons(row, code, (String) zones.get(code).getAttribute("ARS"), (MultiPolygon) zones.get(code).getDefaultGeometry()); found.add(code); } } } for (Map.Entry<String, SimpleFeature> zone : zones.entrySet()) { if (!found.contains(zone.getKey())) log.warn("Zone not found in population statistic: {} ({})", zone.getValue().getAttribute("GEN"), zone.getKey()); } log.info("Generated {} persons", population.getPersons().size()); PopulationUtils.sortPersons(population); ProjectionUtils.putCRS(population, OpenBerlinScenario.CRS); PopulationUtils.writePopulation(population, output.toString()); return 0; } /** * Add number of persons to the population according to entry. */ private void addPersons(CSVRecord r, String code, String ars, MultiPolygon geom) { int n = Integer.parseInt(r.get("n")); // Convert to english gender String gender = r.get("gender").equals("m") ? "m" : "f"; String[] group = r.get("age").split(" - "); int low = Integer.parseInt(group[0]); int high = group[1].equals("inf") ? MAX_AGE : Integer.parseInt(group[1]); UniformAttributeDistribution<Integer> ageDist = new UniformAttributeDistribution<>(IntStream.range(low, high).boxed().toList()); // Landkreis int lk = Integer.parseInt(code.substring(0, code.length() - 3)); if (!employed.containsKey(lk)) { log.error("No employment for {}", code); return; } Entry employed = gender.equals("m") ? this.employed.get(lk).men : this.employed.get(lk).women; PopulationFactory f = population.getFactory(); for (int i = 0; i < n * sample; i++) { Person person = f.createPerson(generateId(population, "bb", rnd)); int age = ageDist.sample(); PersonUtils.setSex(person, gender); PersonUtils.setAge(person, age); PopulationUtils.putSubpopulation(person, "person"); // All persons will be employed until employed population is empty. PersonUtils.setEmployed(person, employed.subtract(1 / sample, age)); Coord coord = CreateBerlinPopulation.sampleHomeCoordinate(geom, OpenBerlinScenario.CRS, landuse, rnd); person.getAttributes().putAttribute(Attributes.HOME_X, coord.getX()); person.getAttributes().putAttribute(Attributes.HOME_Y, coord.getY()); person.getAttributes().putAttribute(Attributes.GEM, Integer.parseInt(code)); person.getAttributes().putAttribute(Attributes.ARS, Long.parseLong(ars)); Plan plan = f.createPlan(); plan.addActivity(f.createActivityFromCoord("home", coord)); person.addPlan(plan); person.setSelectedPlan(plan); population.addPerson(person); } } }
6,395
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
UniformAttributeDistribution.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/UniformAttributeDistribution.java
package org.matsim.prepare.population; import java.util.*; /** * Distribution where each attribute is equally likely. */ public class UniformAttributeDistribution<T> implements AttributeDistribution<T> { private final List<T> attributes; private final Random rnd; public UniformAttributeDistribution(T... attributes) { this(Arrays.stream(attributes).toList()); } public UniformAttributeDistribution(Collection<T> attributes) { this.attributes = new ArrayList<>(attributes); this.rnd = new Random(0); } @Override public T sample() { return attributes.get(rnd.nextInt(attributes.size())); } }
617
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateBerlinPopulation.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/CreateBerlinPopulation.java
package org.matsim.prepare.population; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.MultiPolygon; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.LanduseOptions; import org.matsim.application.options.ShpOptions; import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.scenario.ProjectionUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.geometry.transformations.GeotoolsTransformation; import org.matsim.prepare.RunOpenBerlinCalibration; import org.matsim.run.OpenBerlinScenario; import org.opengis.feature.simple.SimpleFeature; import picocli.CommandLine; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; import java.util.stream.IntStream; @CommandLine.Command( name = "berlin-population", description = "Create synthetic population for berlin." ) public class CreateBerlinPopulation implements MATSimAppCommand { private static final NumberFormat FMT = NumberFormat.getInstance(Locale.GERMAN); private static final Logger log = LogManager.getLogger(CreateBerlinPopulation.class); private final CoordinateTransformation ct = new GeotoolsTransformation("EPSG:25833", "EPSG:25832"); @CommandLine.Option(names = "--input", description = "Path to input csv data", required = true) private Path input; @CommandLine.Mixin private LanduseOptions landuse = new LanduseOptions(); @CommandLine.Mixin private ShpOptions shp = new ShpOptions(); @CommandLine.Option(names = "--output", description = "Path to output population", required = true) private Path output; @CommandLine.Option(names = "--year", description = "Year to use statistics from", defaultValue = "2019") private int year; @CommandLine.Option(names = "--sample", description = "Sample size to generate", defaultValue = "0.25") private double sample; private Map<String, MultiPolygon> lors; private SplittableRandom rnd; private Population population; public static void main(String[] args) { new CreateBerlinPopulation().execute(args); } /** * Generate a new unique id within population. */ public static Id<Person> generateId(Population population, String prefix, SplittableRandom rnd) { Id<Person> id; byte[] bytes = new byte[4]; do { rnd.nextBytes(bytes); id = Id.createPersonId(prefix + "_" + HexFormat.of().formatHex(bytes)); } while (population.getPersons().containsKey(id)); return id; } /** * Samples a home coordinates from geometry and landuse. */ public static Coord sampleHomeCoordinate(MultiPolygon geometry, String crs, LanduseOptions landuse, SplittableRandom rnd) { Envelope bbox = geometry.getEnvelopeInternal(); int i = 0; Coord coord; do { coord = landuse.select(crs, () -> new Coord( bbox.getMinX() + (bbox.getMaxX() - bbox.getMinX()) * rnd.nextDouble(), bbox.getMinY() + (bbox.getMaxY() - bbox.getMinY()) * rnd.nextDouble() )); i++; } while (!geometry.contains(MGC.coord2Point(coord)) && i < 1500); if (i == 1500) log.warn("Invalid coordinate generated"); return RunOpenBerlinCalibration.roundCoord(coord); } @Override @SuppressWarnings("IllegalCatch") public Integer call() throws Exception { if (!shp.isDefined()) { log.error("Shape file with LOR zones is required."); return 2; } List<SimpleFeature> fts = shp.readFeatures(); rnd = new SplittableRandom(0); lors = new HashMap<>(); population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); // Collect all LORs for (SimpleFeature ft : fts) { // Support both old and new key for different shape files String key = ft.getAttribute("SCHLUESSEL") != null ? "SCHLUESSEL" : "PLR_ID"; lors.put((String) ft.getAttribute(key), (MultiPolygon) ft.getDefaultGeometry()); } log.info("Found {} LORs", lors.size()); CSVFormat.Builder format = CSVFormat.DEFAULT.builder().setDelimiter(';').setHeader().setSkipHeaderRecord(true); try (CSVParser reader = new CSVParser(Files.newBufferedReader(input, Charset.forName("windows-1252")), format.build())) { for (CSVRecord row : reader) { int year = Integer.parseInt(row.get("Jahr")); if (this.year != year) continue; try { processLOR(row); } catch (RuntimeException e) { log.error("Error processing lor", e); log.error(row.toString()); } } } log.info("Generated {} persons", population.getPersons().size()); PopulationUtils.sortPersons(population); ProjectionUtils.putCRS(population, OpenBerlinScenario.CRS); PopulationUtils.writePopulation(population, output.toString()); return 0; } private void processLOR(CSVRecord row) throws ParseException { String raumID = row.get("RaumID"); int n = Integer.parseInt(row.get("Einwohnerinnen und Einwohner (EW) insgesamt")); log.info("Processing {} with {} inhabitants", raumID, n); double young = FMT.parse(row.get("Anteil der unter 18-Jährigen an Einwohnerinnen und Einwohner (EW) gesamt")).doubleValue() / 100; double old = FMT.parse(row.get("Anteil der 65-Jährigen und älter an Einwohnerinnen und Einwohner (EW) gesamt")).doubleValue() / 100; // x women for 100 men double women = FMT.parse(row.get("Geschlechterverteilung")).doubleValue(); double quota = women / (100 + women); // sometimes this entry is not set double unemployed; try { unemployed = FMT.parse(row.get("Anteil Arbeitslose nach SGB II und SGB III an Einwohnerinnen und Einwohner (EW) im Alter von 15 bis unter 65 Jahren")).doubleValue() / 100; } catch (ParseException e) { unemployed = 0; log.warn("LOR {} {} has no unemployment", raumID, row.get(1)); } var sex = new EnumeratedAttributeDistribution<>(Map.of("f", quota, "m", 1 - quota)); var employment = new EnumeratedAttributeDistribution<>(Map.of(true, 1 - unemployed, false, unemployed)); var ageGroup = new EnumeratedAttributeDistribution<>(Map.of( AgeGroup.YOUNG, young, AgeGroup.MIDDLE, 1.0 - young - old, AgeGroup.OLD, old )); if (!lors.containsKey(raumID)) { log.warn("LOR {} not found", raumID); return; } MultiPolygon geom = lors.get(raumID); PopulationFactory f = population.getFactory(); var youngDist = new UniformAttributeDistribution<>(IntStream.range(1, 18).boxed().toList()); var middleDist = new UniformAttributeDistribution<>(IntStream.range(18, 65).boxed().toList()); var oldDist = new UniformAttributeDistribution<>(IntStream.range(65, 100).boxed().toList()); for (int i = 0; i < n * sample; i++) { Person person = f.createPerson(generateId(population, "berlin", rnd)); PersonUtils.setSex(person, sex.sample()); PopulationUtils.putSubpopulation(person, "person"); AgeGroup group = ageGroup.sample(); if (group == AgeGroup.MIDDLE) { PersonUtils.setAge(person, middleDist.sample()); PersonUtils.setEmployed(person, employment.sample()); } else if (group == AgeGroup.YOUNG) { PersonUtils.setAge(person, youngDist.sample()); PersonUtils.setEmployed(person, false); } else if (group == AgeGroup.OLD) { PersonUtils.setAge(person, oldDist.sample()); PersonUtils.setEmployed(person, false); } Coord coord = ct.transform(sampleHomeCoordinate(geom, "EPSG:25833", landuse, rnd)); person.getAttributes().putAttribute(Attributes.HOME_X, coord.getX()); person.getAttributes().putAttribute(Attributes.HOME_Y, coord.getY()); person.getAttributes().putAttribute(Attributes.GEM, 11000000); person.getAttributes().putAttribute(Attributes.ARS, 110000000000L); person.getAttributes().putAttribute(Attributes.LOR, Integer.parseInt(raumID)); Plan plan = f.createPlan(); plan.addActivity(f.createActivityFromCoord("home", coord)); person.addPlan(plan); person.setSelectedPlan(plan); population.addPerson(person); } } private enum AgeGroup { YOUNG, MIDDLE, OLD } }
8,607
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
EnumeratedAttributeDistribution.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/EnumeratedAttributeDistribution.java
package org.matsim.prepare.population; import org.apache.commons.math3.distribution.EnumeratedDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.util.Pair; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Distribution with fixed probabilities for each entry. * * @param <T> type of the produced value. */ public class EnumeratedAttributeDistribution<T> implements AttributeDistribution<T> { private final EnumeratedDistribution<T> dist; /** * Constructor. * * @param probabilities map of attributes to their probabilities. */ public EnumeratedAttributeDistribution(Map<T, Double> probabilities) { List<Pair<T, Double>> pairs = probabilities.entrySet().stream().map( e -> new Pair<>(e.getKey(), e.getValue()) ).collect(Collectors.toList()); dist = new EnumeratedDistribution<T>(new MersenneTwister(0), pairs); } @Override public T sample() { return dist.sample(); } }
994
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CommuterAssignment.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/CommuterAssignment.java
package org.matsim.prepare.population; import it.unimi.dsi.fastutil.longs.*; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; import org.matsim.application.options.CsvOptions; import org.matsim.facilities.ActivityFacility; import org.opengis.feature.simple.SimpleFeature; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.Map; import java.util.SplittableRandom; /** * Helper class for commuter assignment. */ public class CommuterAssignment { private static final Logger log = LogManager.getLogger(CommuterAssignment.class); private final Map<Long, SimpleFeature> zones; /** * Outgoing commuter from ars to ars. */ private final Long2ObjectMap<Long2DoubleMap> commuter; private final CsvOptions csv = new CsvOptions(CSVFormat.Predefined.Default); private final double sample; public CommuterAssignment(Long2ObjectMap<SimpleFeature> zones, Path commuterPath, double sample) { this.sample = sample; // outgoing commuters this.commuter = new Long2ObjectOpenHashMap<>(); this.zones = zones; // read commuters try (CSVParser parser = csv.createParser(commuterPath)) { for (CSVRecord row : parser) { long from; long to; try { from = Long.parseLong(row.get("from")); to = Long.parseLong(row.get("to")); } catch (NumberFormatException e) { continue; } String n = row.get("n"); commuter.computeIfAbsent(from, k -> Long2DoubleMaps.synchronize(new Long2DoubleOpenHashMap())) .mergeDouble(to, Integer.parseInt(n), Double::sum); } } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Select and return a commute target. * * @param f sampler producing target locations * @param ars origin zone */ public ActivityFacility selectTarget(SplittableRandom rnd, long ars, double dist, Point refPoint, Sampler f) { // Commute in same zone Long2DoubleMap comms = commuter.get(ars); if (!commuter.containsKey(ars) || comms.isEmpty()) return null; LongList entries; synchronized (comms) { entries = new LongArrayList(comms.keySet()); } while (!entries.isEmpty()) { long key = entries.removeLong(rnd.nextInt(entries.size())); SimpleFeature ft = zones.get(key); // TODO: should maybe not be allowed if (ft == null) continue; Geometry zone = (Geometry) ft.getDefaultGeometry(); // Zones too far away don't need to be considered if (zone.distance(refPoint) > dist * 1.2) continue; ActivityFacility res = f.sample(zone); if (res != null) { synchronized (comms) { double old = comms.get(key); // Check if other thread reduced the counter while computing // result needs to be thrown away if (old <= 0) { comms.remove(key); continue; } // subtract available commuters double newValue = old - (1 / sample); comms.put(key, newValue); if (newValue <= 0) comms.remove(key); } return res; } } return null; } /** * Sample locations from specific zone. */ interface Sampler { ActivityFacility sample(Geometry zone); } }
3,380
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
AttributeDistribution.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/AttributeDistribution.java
package org.matsim.prepare.population; /** * Distribution of attribute values. * @param <T> attribute type */ public interface AttributeDistribution<T> { /** * Draw a random sample from the distribution. */ T sample(); }
234
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
InitLocationChoice.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/InitLocationChoice.java
package org.matsim.prepare.population; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.index.strtree.STRtree; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.ShpOptions; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.ParallelPersonAlgorithmUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.facilities.ActivityFacility; import org.matsim.prepare.RunOpenBerlinCalibration; import org.opengis.feature.simple.SimpleFeature; import picocli.CommandLine; import java.nio.file.Path; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static org.matsim.prepare.CreateMATSimFacilities.IGNORED_LINK_TYPES; @CommandLine.Command( name = "init-location-choice", description = "Assign initial locations to agents" ) @SuppressWarnings("unchecked") public class InitLocationChoice implements MATSimAppCommand, PersonAlgorithm { /** * Detour factor for car routes, which was determined based on sampled routes. */ private static final double DETOUR_FACTOR = 1.46; /** * Factor for short trips < 2000m. */ private static final double DETOUR_FACTOR_SHORT = 1.3; private static final Logger log = LogManager.getLogger(InitLocationChoice.class); @CommandLine.Option(names = "--input", description = "Path to input population.") private Path input; @CommandLine.Option(names = "--output", description = "Path to output population", required = true) private Path output; @CommandLine.Option(names = "--k", description = "Number of choices to generate", defaultValue = "5") private int k; @CommandLine.Option(names = "--commuter", description = "Path to commuter.csv", required = true) private Path commuterPath; @CommandLine.Option(names = "--facilities", description = "Path to facilities file", required = true) private Path facilityPath; @CommandLine.Option(names = "--network", description = "Path to network file", required = true) private Path networkPath; @CommandLine.Option(names = "--sample", description = "Sample size of the population", defaultValue = "0.25") private double sample; @CommandLine.Option(names = "--seed", description = "Seed used to sample locations", defaultValue = "1") private long seed; @CommandLine.Mixin private ShpOptions shp; private FacilityIndex facilities; private Long2ObjectMap<SimpleFeature> zones; private CommuterAssignment commuter; private Network network; private ThreadLocal<Context> ctxs; private AtomicLong total = new AtomicLong(); private AtomicLong warning = new AtomicLong(); public static void main(String[] args) { new InitLocationChoice().execute(args); } private static Coord rndCoord(SplittableRandom rnd, double dist, Coord origin) { var angle = rnd.nextDouble() * Math.PI * 2; var x = Math.cos(angle) * dist; var y = Math.sin(angle) * dist; return new Coord(RunOpenBerlinCalibration.roundNumber(origin.getX() + x), RunOpenBerlinCalibration.roundNumber(origin.getY() + y)); } /** * Approximate beeline dist from known traveled distance. Distance will be reduced by a fixed detour factor. * Dist in meter. */ public static double beelineDist(double travelDist) { double detourFactor = travelDist <= 2000 ? DETOUR_FACTOR_SHORT : DETOUR_FACTOR; return travelDist * 1000 / detourFactor; } @Override public Integer call() throws Exception { if (shp.getShapeFile() == null) { log.error("Shape file with commuter zones is required."); return 2; } Network completeNetwork = NetworkUtils.readNetwork(networkPath.toString()); TransportModeNetworkFilter filter = new TransportModeNetworkFilter(completeNetwork); network = NetworkUtils.createNetwork(); filter.filter(network, Set.of(TransportMode.car)); facilities = new FacilityIndex(facilityPath.toString()); zones = new Long2ObjectOpenHashMap<>(shp.readFeatures().stream() .collect(Collectors.toMap(ft -> Long.parseLong((String) ft.getAttribute("ARS")), ft -> ft))); log.info("Read {} zones", zones.size()); log.info("Using input file: {}", input); List<Population> populations = new ArrayList<>(); for (int i = 0; i < k; i++) { long seed = this.seed + i; log.info("Generating plan {} with seed {}", i , seed); ctxs = ThreadLocal.withInitial(() -> new Context(seed)); commuter = new CommuterAssignment(zones, commuterPath, sample); Population population = PopulationUtils.readPopulation(input.toString()); ParallelPersonAlgorithmUtils.run(population, 8, this); populations.add(population); log.info("Processed {} activities with {} warnings", total.get(), warning.get()); total.set(0); warning.set(0); } Population population = populations.get(0); // Merge all plans into the first population for (int i = 1; i < populations.size(); i++) { Population pop = populations.get(i); for (Person p : pop.getPersons().values()) { Person destPerson = population.getPersons().get(p.getId()); if (destPerson == null) { log.warn("Person {} not present in all populations.", p.getId()); continue; } destPerson.addPlan(p.getPlans().get(0)); } } PopulationUtils.writePopulation(population, output.toString()); return 0; } @Override public void run(Person person) { Coord homeCoord = Attributes.getHomeCoord(person); // Activities that only occur on one place per person Map<String, ActivityFacility> fixedLocations = new HashMap<>(); Context ctx = ctxs.get(); for (Plan plan : person.getPlans()) { List<Activity> acts = TripStructureUtils.getActivities(plan, TripStructureUtils.StageActivityHandling.ExcludeStageActivities); // keep track of the current coordinate Coord lastCoord = homeCoord; for (Activity act : acts) { String type = act.getType(); total.incrementAndGet(); if (Attributes.isLinkUnassigned(act.getLinkId())) { act.setLinkId(null); ActivityFacility location = null; // target leg distance in km double origDist = (double) act.getAttributes().getAttribute("orig_dist"); // Distance will be reduced double dist = beelineDist(origDist); if (fixedLocations.containsKey(type)) { location = fixedLocations.get(type); } if (location == null && type.equals("work")) { // sample work commute location = sampleCommute(ctx, dist, lastCoord, (long) person.getAttributes().getAttribute(Attributes.ARS)); } if (location == null && facilities.index.containsKey(type)) { // Needed for lambda final Coord refCoord = lastCoord; List<ActivityFacility> query = facilities.index.get(type).query(MGC.coord2Point(lastCoord).buffer(dist * 1.2).getEnvelopeInternal()); // Distance should be within the bounds List<ActivityFacility> res = query.stream().filter(f -> checkDistanceBound(dist, refCoord, f.getCoord(), 1)).toList(); if (!res.isEmpty()) { location = query.get(ctx.rnd.nextInt(query.size())); } // Try with larger bounds again if (location == null) { res = query.stream().filter(f -> checkDistanceBound(dist, refCoord, f.getCoord(), 1.2)).toList(); if (!res.isEmpty()) { location = query.get(ctx.rnd.nextInt(query.size())); } } } if (location == null) { // sample only coordinate if nothing else is possible // Activities without facility entry, or where no facility could be found Coord c = sampleLink(ctx.rnd, dist, lastCoord); act.setCoord(c); lastCoord = c; // An activity with type could not be put into correct facility. if (facilities.index.containsKey(type)) { warning.incrementAndGet(); } continue; } if (type.equals("work") || type.startsWith("edu")) fixedLocations.put(type, location); act.setFacilityId(location.getId()); } if (act.getCoord() != null) lastCoord = act.getCoord(); else if (act.getFacilityId() != null) lastCoord = facilities.all.getFacilities().get(act.getFacilityId()).getCoord(); } } } /** * Sample work place by using commute and distance information. */ private ActivityFacility sampleCommute(Context ctx, double dist, Coord refCoord, long ars) { STRtree index = facilities.index.get("work"); ActivityFacility workPlace = null; // Only larger distances can be commuters to other zones if (dist > 3000) { workPlace = commuter.selectTarget(ctx.rnd, ars, dist, MGC.coord2Point(refCoord), zone -> sampleZone(index, dist, refCoord, zone, ctx.rnd)); } if (workPlace == null) { // Try selecting within same zone workPlace = sampleZone(index, dist, refCoord, (Geometry) zones.get(ars).getDefaultGeometry(), ctx.rnd); } return workPlace; } /** * Sample a coordinate for which the associated link is not one of the ignored types. */ private Coord sampleLink(SplittableRandom rnd, double dist, Coord origin) { Coord coord = null; for (int i = 0; i < 500; i++) { coord = rndCoord(rnd, dist, origin); Link link = NetworkUtils.getNearestLink(network, coord); if (!IGNORED_LINK_TYPES.contains(NetworkUtils.getType(link))) break; } return coord; } /** * Only samples randomly from the zone, ignoring the distance. */ private ActivityFacility sampleZone(STRtree index, double dist, Coord refCoord, Geometry zone, SplittableRandom rnd) { ActivityFacility location = null; List<ActivityFacility> query = index.query(MGC.coord2Point(refCoord).buffer(dist * 1.2).getEnvelopeInternal()); query = query.stream().filter(f -> checkDistanceBound(dist, refCoord, f.getCoord(), 1)).collect(Collectors.toList()); while (!query.isEmpty()) { ActivityFacility af = query.remove(rnd.nextInt(query.size())); if (zone.contains(MGC.coord2Point(af.getCoord()))) { location = af; break; } } return location; } /** * General logic to filter coordinate within target distance. */ private boolean checkDistanceBound(double target, Coord refCoord, Coord other, double factor) { double lower = target * 0.8 * (2 - factor); double upper = target * 1.15 * factor; double dist = CoordUtils.calcEuclideanDistance(refCoord, other); return dist >= lower && dist <= upper; } private static final class Context { private final SplittableRandom rnd; Context(long seed) { rnd = new SplittableRandom(seed); } } }
11,330
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Attributes.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/Attributes.java
package org.matsim.prepare.population; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; import java.util.Objects; /** * Defines available attributes. */ @SuppressWarnings("ConstantName") public final class Attributes { public static final String HOME_X = "home_x"; public static final String HOME_Y = "home_y"; /** * Gemeinde code. */ public static final String GEM = "gem"; public static final String ARS = "ars"; /** * LOR for Berlin. */ public static final String LOR = "lor"; public static final String RegioStaR7 = "RegioStaR7"; public static final String BIKE_AVAIL = "bikeAvail"; public static final String PT_ABO_AVAIL = "ptAboAvail"; public static final String EMPLOYMENT = "employment"; public static final String RESTRICTED_MOBILITY = "restricted_mobility"; public static final String ECONOMIC_STATUS = "economic_status"; public static final String HOUSEHOLD_SIZE = "household_size"; private Attributes() { } public static boolean isLinkUnassigned(Id<Link> link) { return link != null && Objects.equals(link.toString(), "unassigned"); } /** * Return home coordinate of a person. */ public static Coord getHomeCoord(Person p) { return new Coord((Double) p.getAttributes().getAttribute(HOME_X), (Double) p.getAttributes().getAttribute(HOME_Y)); } }
1,430
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
AssignIncome.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/AssignIncome.java
package org.matsim.prepare.population; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import java.util.SplittableRandom; /** * Draw income from german wide distribution. */ public class AssignIncome implements PersonAlgorithm { private final SplittableRandom rnd = new SplittableRandom(1234); /** * Assign income on whole population. */ public static void assignIncomeToPersons(Population population) { AssignIncome assignIncome = new AssignIncome(); population.getPersons().values().forEach(assignIncome::run); } @Override public void run(Person person) { // Only handle persons if (!PopulationUtils.getSubpopulation(person).equals("person")) return; // The income is german wide and not related to other attributes // even though srv contains the (household) economic status, this can not be easily back calculated to the income person.getAttributes().removeAttribute(Attributes.ECONOMIC_STATUS); // https://de.wikipedia.org/wiki/Einkommensverteilung_in_Deutschland // besser https://www.destatis.de/DE/Themen/Gesellschaft-Umwelt/Einkommen-Konsum-Lebensbedingungen/Einkommen-Einnahmen-Ausgaben/Publikationen/Downloads-Einkommen/einkommensverteilung-2152606139004.pdf?__blob=publicationFile // Anteil der Personen (%) an allen Personen 10 20 30 40 50 60 70 80 90 100 // Nettoäquivalenzeinkommen(€) 826 1.142 1.399 1.630 1.847 2.070 2.332 2.659 3.156 4.329 double income = 0.; double rndDouble = rnd.nextDouble(); if (rndDouble <= 0.1) income = 826.; else if (rndDouble <= 0.2) income = 1142.; else if (rndDouble <= 0.3) income = 1399.; else if (rndDouble <= 0.4) income = 1630.; else if (rndDouble <= 0.5) income = 1847.; else if (rndDouble <= 0.6) income = 2070.; else if (rndDouble <= 0.7) income = 2332.; else if (rndDouble <= 0.8) income = 2659.; else if (rndDouble <= 0.9) income = 3156.; else { income = 4329.; } PersonUtils.setIncome(person, income); } }
2,165
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
FacilityIndex.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/FacilityIndex.java
package org.matsim.prepare.population; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.index.strtree.STRtree; import org.matsim.api.core.v01.Id; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.facilities.ActivityFacilities; import org.matsim.facilities.ActivityFacility; import org.matsim.facilities.FacilitiesUtils; import org.matsim.facilities.MatsimFacilitiesReader; import org.matsim.run.OpenBerlinScenario; import java.util.HashMap; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.stream.Collectors; /** * Spatial index for facilities. */ final class FacilityIndex { private static final Logger log = LogManager.getLogger(FacilityIndex.class); final ActivityFacilities all = FacilitiesUtils.createActivityFacilities(); /** * Maps activity type to spatial index. */ final Map<String, STRtree> index = new HashMap<>(); FacilityIndex(String facilityPath) { new MatsimFacilitiesReader(OpenBerlinScenario.CRS, OpenBerlinScenario.CRS, all) .readFile(facilityPath); Set<String> activities = all.getFacilities().values().stream() .flatMap(a -> a.getActivityOptions().keySet().stream()) .collect(Collectors.toSet()); log.info("Found activity types: {}", activities); for (String act : activities) { NavigableMap<Id<ActivityFacility>, ActivityFacility> afs = all.getFacilitiesForActivityType(act); for (ActivityFacility af : afs.values()) { STRtree idx = this.index.computeIfAbsent(act, k -> new STRtree()); idx.insert(MGC.coord2Point(af.getCoord()).getEnvelopeInternal(), af); } } // Build all trees index.values().forEach(STRtree::build); } }
1,735
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
LookupRegioStaR.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/LookupRegioStaR.java
package org.matsim.prepare.population; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; @CommandLine.Command( name = "lookup-regiostar", description = "RegioStaR7 lookup using gemeinde id." ) public class LookupRegioStaR implements MATSimAppCommand, PersonAlgorithm { private static final Logger log = LogManager.getLogger(LookupRegioStaR.class); @CommandLine.Option(names = "--input", required = true, description = "Input Population") private Path input; @CommandLine.Option(names = "--xls", required = true, description = "Path to RegioStar Excel sheet") private Path regiostar; @CommandLine.Option(names = "--output", required = true, description = "Output Population") private Path output; private Int2IntMap lookup; public static void main(String[] args) { new LookupRegioStaR().execute(args); } @Override public Integer call() throws Exception { if (!Files.exists(regiostar)) { log.error("File {} does not exist.", regiostar); return 2; } lookup = readXls(); log.info("Read {} entries from xls.", lookup.size()); Population population = PopulationUtils.readPopulation(input.toString()); population.getPersons().values().forEach(this::run); PopulationUtils.writePopulation(population, output.toString()); return 0; } @Override public void run(Person person) { int gem = (int) person.getAttributes().getAttribute(Attributes.GEM); if (!lookup.containsKey(gem)) log.warn("Unknown Gemeinde {}", gem); // Currently hardcoded to R7 person.getAttributes().putAttribute(Attributes.RegioStaR7, lookup.get(gem) - 70); } private Int2IntMap readXls() throws IOException, InvalidFormatException { Int2IntMap result = new Int2IntOpenHashMap(); try (XSSFWorkbook workbook = new XSSFWorkbook(regiostar.toFile())) { XSSFSheet sheet = workbook.getSheet("ReferenzGebietsstand2020"); XSSFRow first = sheet.getRow(0); Map<String, Integer> header = new HashMap<>(); for (Cell cell : first) { header.put(cell.getStringCellValue(), cell.getColumnIndex()); } for (int i = 1; i < sheet.getLastRowNum(); i++) { XSSFRow row = sheet.getRow(i); result.put( (int) row.getCell(header.get("gem_20")).getNumericCellValue(), (int) row.getCell(header.get(Attributes.RegioStaR7)).getNumericCellValue() ); } } return result; } }
3,150
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunActivitySampling.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/population/RunActivitySampling.java
package org.matsim.prepare.population; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.*; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import org.matsim.core.population.PersonUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.algorithms.ParallelPersonAlgorithmUtils; import org.matsim.core.population.algorithms.PersonAlgorithm; import org.matsim.core.router.TripStructureUtils; import org.matsim.prepare.RunOpenBerlinCalibration; import picocli.CommandLine; import java.nio.file.Path; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; @CommandLine.Command( name = "activity-sampling", description = "Create activities by sampling from survey data" ) public class RunActivitySampling implements MATSimAppCommand, PersonAlgorithm { private static final Logger log = LogManager.getLogger(RunActivitySampling.class); private final CsvOptions csv = new CsvOptions(CSVFormat.Predefined.Default); private final Map<Key, IntList> groups = new HashMap<>(); private final Int2ObjectMap<CSVRecord> persons = new Int2ObjectOpenHashMap<>(); /** * Maps person index to list of activities. */ private final Int2ObjectMap<List<CSVRecord>> activities = new Int2ObjectOpenHashMap<>(); @CommandLine.Option(names = "--input", description = "Path to input population", required = true) private Path input; @CommandLine.Option(names = "--output", description = "Output path for population", required = true) private Path output; @CommandLine.Option(names = "--persons", description = "Path to person table", required = true) private Path personsPath; @CommandLine.Option(names = "--activities", description = "Path to activity table", required = true) private Path activityPath; @CommandLine.Option(names = "--seed", description = "Seed used to sample plans", defaultValue = "1") private long seed; private ThreadLocal<Context> ctxs; private PopulationFactory factory; public static void main(String[] args) { new RunActivitySampling().execute(args); } @Override public Integer call() throws Exception { Population population = PopulationUtils.readPopulation(input.toString()); try (CSVParser parser = csv.createParser(personsPath)) { buildSubgroups(parser); } try (CSVParser parser = csv.createParser(activityPath)) { readActivities(parser); } ctxs = ThreadLocal.withInitial(() -> new Context(new SplittableRandom(seed))); factory = population.getFactory(); ParallelPersonAlgorithmUtils.run(population, 8, this); PopulationUtils.writePopulation(population, output.toString()); double atHome = 0; for (Person person : population.getPersons().values()) { List<Leg> legs = TripStructureUtils.getLegs(person.getSelectedPlan()); if (legs.isEmpty()) atHome++; } int size = population.getPersons().size(); double mobile = (size - atHome) / size; log.info("Processed {} persons, mobile persons: {}%", size, 100 * mobile); return 0; } /** * Create subpopulations for sampling. */ private void buildSubgroups(CSVParser csv) { int i = 0; for (CSVRecord r : csv) { int idx = Integer.parseInt(r.get("idx")); int regionType = Integer.parseInt(r.get("region_type")); String gender = r.get("gender"); String employment = r.get("employment"); int age = Integer.parseInt(r.get("age")); Stream<Key> keys = createKey(gender, age, regionType, employment); keys.forEach(key -> groups.computeIfAbsent(key, (k) -> new IntArrayList()).add(idx)); persons.put(idx, r); i++; } log.info("Read {} persons from csv.", i); } private void readActivities(CSVParser csv) { int currentId = -1; List<CSVRecord> current = null; int i = 0; for (CSVRecord r : csv) { int pId = Integer.parseInt(r.get("p_id")); if (pId != currentId) { if (current != null) activities.put(currentId, current); currentId = pId; current = new ArrayList<>(); } current.add(r); i++; } if (current != null && !current.isEmpty()) { activities.put(currentId, current); } log.info("Read {} activities for {} persons", i, activities.size()); } private Stream<Key> createKey(String gender, int age, int regionType, String employment) { if (age < 6) { return IntStream.rangeClosed(0, 5).mapToObj(i -> new Key(null, i, regionType, null)); } if (age <= 10) { return IntStream.rangeClosed(6, 10).mapToObj(i -> new Key(null, i, regionType, null)); } if (age < 18) { return IntStream.rangeClosed(11, 18).mapToObj(i -> new Key(gender, i, regionType, null)); } Boolean isEmployed = age > 65 ? null : !employment.equals("unemployed"); int min = Math.max(18, age - 6); int max = Math.min(65, age + 6); // larger groups for older people if (age > 65) { min = Math.max(66, age - 10); max = Math.min(99, age + 10); } return IntStream.rangeClosed(min, max).mapToObj(i -> new Key(gender, i, regionType, isEmployed)); } private Key createKey(Person person) { Integer age = PersonUtils.getAge(person); String gender = PersonUtils.getSex(person); if (age <= 10) gender = null; Boolean employed = PersonUtils.isEmployed(person); if (age < 18 || age > 65) employed = null; int regionType = (int) person.getAttributes().getAttribute(Attributes.RegioStaR7); // Region types have been reduced to 1 and 3 if (regionType != 1) regionType = 3; return new Key(gender, age, regionType, employed); } @Override public void run(Person person) { SplittableRandom rnd = ctxs.get().rnd; Key key = createKey(person); IntList subgroup = groups.get(key); if (subgroup == null) { log.error("No subgroup found for key {}", key); throw new IllegalStateException("Invalid entry"); } if (subgroup.size() < 30) { log.warn("Group {} has low sample size: {}", key, subgroup.size()); } int idx = subgroup.getInt(rnd.nextInt(subgroup.size())); CSVRecord row = persons.get(idx); PersonUtils.setCarAvail(person, row.get("car_avail").equals("True") ? "always" : "never"); PersonUtils.setLicence(person, row.get("driving_license").toLowerCase()); person.getAttributes().putAttribute(Attributes.BIKE_AVAIL, row.get("bike_avail").equals("True") ? "always" : "never"); person.getAttributes().putAttribute(Attributes.PT_ABO_AVAIL, row.get("pt_abo_avail").equals("True") ? "always" : "never"); person.getAttributes().putAttribute(Attributes.EMPLOYMENT, row.get("employment")); person.getAttributes().putAttribute(Attributes.RESTRICTED_MOBILITY, row.get("restricted_mobility").equals("True")); person.getAttributes().putAttribute(Attributes.ECONOMIC_STATUS, row.get("economic_status")); person.getAttributes().putAttribute(Attributes.HOUSEHOLD_SIZE, Integer.parseInt(row.get("n_persons"))); String mobile = row.get("mobile_on_day"); // ensure mobile agents have a valid plan switch (mobile.toLowerCase()) { case "true" -> { List<CSVRecord> activities = this.activities.get(idx); if (activities == null) throw new AssertionError("No activities for mobile person " + idx); if (activities.size() == 0) throw new AssertionError("Activities for mobile agent can not be empty."); person.removePlan(person.getSelectedPlan()); Plan plan = createPlan(Attributes.getHomeCoord(person), activities, rnd); person.addPlan(plan); person.setSelectedPlan(plan); } case "false" -> { // Keep the stay home plan } default -> throw new AssertionError("Invalid mobile_on_day attribute " + mobile); } } /** * Randomize the duration slightly, depending on total duration. */ private int randomizeDuration(int minutes, SplittableRandom rnd) { if (minutes <= 10) return minutes * 60; if (minutes <= 60) return minutes * 60 + rnd.nextInt(300) - 150; if (minutes <= 240) return minutes * 60 + rnd.nextInt(600) - 300; return minutes * 60 + rnd.nextInt(1200) - 600; } private Plan createPlan(Coord homeCoord, List<CSVRecord> activities, SplittableRandom rnd) { Plan plan = factory.createPlan(); Activity a = null; String lastMode = null; double startTime = 0; // Track the distance to the first home activity double homeDist = 0; boolean arrivedHome = false; for (int i = 0; i < activities.size(); i++) { CSVRecord act = activities.get(i); String actType = act.get("type"); // First and last activities that are other are changed to home if (actType.equals("other") && (i == 0 || i == activities.size() - 1)) actType = "home"; int duration = Integer.parseInt(act.get("duration")); if (actType.equals("home")) { a = factory.createActivityFromCoord("home", homeCoord); } else a = factory.createActivityFromLinkId(actType, Id.createLinkId("unassigned")); double legDuration = Double.parseDouble(act.get("leg_duration")); if (plan.getPlanElements().isEmpty()) { // Add little int seconds = randomizeDuration(duration, rnd); a.setEndTime(seconds); startTime += seconds; } else if (duration < 1440) { startTime += legDuration * 60; // Flexible modes are represented with duration // otherwise start and end time int seconds = randomizeDuration(duration, rnd); if (RunOpenBerlinCalibration.FLEXIBLE_ACTS.contains(actType)) a.setMaximumDuration(seconds); else { a.setStartTime(startTime); a.setEndTime(startTime + seconds); } startTime += seconds; } double legDist = Double.parseDouble(act.get("leg_dist")); if (i > 0) { a.getAttributes().putAttribute("orig_dist", legDist); a.getAttributes().putAttribute("orig_duration", legDuration); } if (!plan.getPlanElements().isEmpty()) { lastMode = act.get("leg_mode"); // other mode is initialized as walk if (lastMode.equals("other")) lastMode = "walk"; plan.addLeg(factory.createLeg(lastMode)); } if (!arrivedHome) { homeDist += legDist; } if (a.getType().equals("home")) { arrivedHome = true; } plan.addActivity(a); } // First activity contains the home distance Activity act = (Activity) plan.getPlanElements().get(0); act.getAttributes().putAttribute("orig_dist", homeDist); // Last activity has no end time and duration if (a != null) { if (!RunOpenBerlinCalibration.FLEXIBLE_ACTS.contains(a.getType())) { a.setEndTimeUndefined(); a.setMaximumDurationUndefined(); } else { // End open activities a.setMaximumDuration(30 * 60); plan.addLeg(factory.createLeg(lastMode)); plan.addActivity(factory.createActivityFromCoord("home", homeCoord)); //log.warn("Last activity of type {}", a.getType()); } } return plan; } /** * Key used for sampling activities. */ private record Key(String gender, int age, int regionType, Boolean employed) { } private record Context(SplittableRandom rnd) { } }
11,389
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
SelectPlansFromIndex.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/SelectPlansFromIndex.java
package org.matsim.prepare.opt; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import org.matsim.core.population.PopulationUtils; import picocli.CommandLine; import java.nio.file.Path; import java.util.HashSet; import java.util.List; import java.util.Set; @CommandLine.Command(name = "select-plans-idx", description = "Select plan index as specified from input.") public class SelectPlansFromIndex implements MATSimAppCommand { @CommandLine.Option(names = "--input", description = "Path to input plans.", required = true) private Path input; @CommandLine.Option(names = "--output", description = "Desired output plans.", required = true) private Path output; @CommandLine.Option(names = "--csv", description = "Path to input plans (Usually experienced plans).", required = true) private Path csv; @CommandLine.Mixin private CsvOptions csvOpt; public static void main(String[] args) { new SelectPlansFromIndex().execute(args); } @Override public Integer call() throws Exception { Population population = PopulationUtils.readPopulation(input.toString()); Object2IntMap<Id<Person>> idx = new Object2IntOpenHashMap<>(); try (CSVParser parser = csvOpt.createParser(csv)) { for (CSVRecord row : parser) { idx.put(Id.createPersonId(row.get("id")), Integer.parseInt(row.get("idx"))); } } Set<Id<Person>> toRemove = new HashSet<>(); for (Person person : population.getPersons().values()) { // will be 0 if no value is present int planIndex = idx.getInt(person.getId()); if (planIndex == -1) { toRemove.add(person.getId()); continue; } selectPlanWithIndex(person, planIndex); } toRemove.forEach(population::removePerson); PopulationUtils.writePopulation(population, output.toString()); return 0; } /** * Select the plan with the given index and remove all other plans. * If the index is larger than the number of plans, the index is modulo the number of plans. */ public static void selectPlanWithIndex(Person person, int planIndex) { List<? extends Plan> plans = person.getPlans(); Set<Plan> removePlans = new HashSet<>(); // make sure that one plan is always selected, even if there are less plans than index int idx = planIndex % plans.size(); for (int i = 0; i < plans.size(); i++) { if (i == idx) { person.setSelectedPlan(plans.get(i)); } else removePlans.add(plans.get(i)); } removePlans.forEach(person::removePlan); } }
2,875
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ErrorMetric.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/ErrorMetric.java
package org.matsim.prepare.opt; /** * Error metric to calculate. */ enum ErrorMetric { abs_error, log_error, symmetric_percentage_error }
144
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ScoreCalculator.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/ScoreCalculator.java
package org.matsim.prepare.opt; import it.unimi.dsi.fastutil.ints.Int2IntMap; import org.apache.commons.math3.util.FastMath; import org.optaplanner.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import org.optaplanner.core.api.score.calculator.IncrementalScoreCalculator; import java.math.BigDecimal; /** * Score calculator. */ public final class ScoreCalculator implements IncrementalScoreCalculator<PlanAssignmentProblem, SimpleBigDecimalScore> { private static final double C = 15.0; /** * Error metric. */ private double error = 0; /** * Real counts. */ private int[] counts; /** * Observed counts from sim. */ private int[] observed; private ErrorMetric metric; static double diffChange(ErrorMetric err, int count, int old, int update) { // Floating point arithmetic still leads to score corruption in full assert mode // logarithm can not even be efficiently calculated using big decimal, the corruption needs to be accepted as this point return switch (err) { case abs_error -> Math.abs(count - update) - Math.abs(count - old); case log_error -> FastMath.abs(FastMath.log((update + C) / (count + C))) - FastMath.abs(FastMath.log((old + C) / (count + C))); case symmetric_percentage_error -> FastMath.abs((double) (update - count) / (update + count + 2 * C) / 2.) - FastMath.abs((double) (old - count) / (old + count + 2 * C) / 2.); }; } @Override public void resetWorkingSolution(PlanAssignmentProblem problem) { observed = new int[problem.counts.length]; counts = problem.counts; metric = problem.metric; for (PlanPerson person : problem) { for (Int2IntMap.Entry e : person.selected().int2IntEntrySet()) { observed[e.getIntKey()] += e.getIntValue(); } } calcScoreInternal(); } private void calcScoreInternal() { error = 0; // Log score needs to shift counts by 1.0 to avoid log 0 if (metric == ErrorMetric.abs_error) for (int j = 0; j < counts.length; j++) error += Math.abs(counts[j] - observed[j]); else if (metric == ErrorMetric.log_error) for (int j = 0; j < counts.length; j++) error += FastMath.abs(Math.log((observed[j] + C) / (counts[j] + C))); else if (metric == ErrorMetric.symmetric_percentage_error) { for (int j = 0; j < counts.length; j++) error += FastMath.abs((double) (observed[j] - counts[j]) / (observed[j] + counts[j] + 2 * C) / 2); } } @Override public void beforeEntityAdded(Object entity) { } @Override public void afterEntityAdded(Object entity) { } @Override public void beforeVariableChanged(Object entity, String variableName) { assert variableName.equals("k"); PlanPerson person = (PlanPerson) entity; // remove this persons plan from the calculation for (Int2IntMap.Entry e : person.selected().int2IntEntrySet()) { int old = observed[e.getIntKey()]; int update = observed[e.getIntKey()] -= e.getIntValue(); error += diffChange(metric, counts[e.getIntKey()], old, update); } } @Override public void afterVariableChanged(Object entity, String variableName) { assert variableName.equals("k"); PlanPerson person = (PlanPerson) entity; // add this persons contribution to the score for (Int2IntMap.Entry e : person.selected().int2IntEntrySet()) { int old = observed[e.getIntKey()]; int update = observed[e.getIntKey()] += e.getIntValue(); error += diffChange(metric, counts[e.getIntKey()], old, update); } } @Override public void beforeEntityRemoved(Object entity) { } @Override public void afterEntityRemoved(Object entity) { } @Override public SimpleBigDecimalScore calculateScore() { return SimpleBigDecimalScore.of(BigDecimal.valueOf(-error)); } double scoreEntry(Int2IntMap.Entry e) { int idx = e.getIntKey(); // Calculate impact compared to a plan without the observations of this plan // old can not get negative return -diffChange(metric, counts[idx], Math.max(0, observed[idx] - e.getIntValue()), observed[idx]); } }
3,990
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
LargeShuffleMoveSelector.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/LargeShuffleMoveSelector.java
package org.matsim.prepare.opt; import org.optaplanner.core.api.score.director.ScoreDirector; import org.optaplanner.core.impl.heuristic.selector.move.factory.MoveIteratorFactory; import java.util.*; /** * Select a move that is guaranteed to improve the solution. */ public class LargeShuffleMoveSelector implements MoveIteratorFactory<PlanAssignmentProblem, LargeChangeMove> { private static final int SIZE = 30; @Override public long getSize(ScoreDirector<PlanAssignmentProblem> scoreDirector) { return scoreDirector.getWorkingSolution().getPersons().size() / 8; } @Override public Iterator<LargeChangeMove> createOriginalMoveIterator(ScoreDirector<PlanAssignmentProblem> scoreDirector) { return createRandomMoveIterator(scoreDirector, new Random(0)); } @Override public Iterator<LargeChangeMove> createRandomMoveIterator(ScoreDirector<PlanAssignmentProblem> scoreDirector, Random workingRandom) { List<PlanPerson> persons = scoreDirector.getWorkingSolution().getPersons(); return new It(scoreDirector.getWorkingSolution().getMaxK(), persons.subList(0, persons.size() / 8), workingRandom); } private static final class It implements Iterator<LargeChangeMove> { private final int maxK; private final List<PlanPerson> list; private final Random random; private int done = 0; It(int maxK, List<PlanPerson> list, Random random) { this.maxK = maxK; this.list = list; this.random = random; } @Override public boolean hasNext() { return done < list.size(); } @Override public LargeChangeMove next() { done++; List<PlanPerson> subset = new ArrayList<>(); for (int i = 0; i < SIZE; i++) { subset.add(list.get(random.nextInt(list.size()))); } int[] ks = new int[subset.size()]; for (int i = 0; i < ks.length; i++) { ks[i] = random.nextInt(maxK); } return new LargeChangeMove(subset, ks); } } }
1,894
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunCountOptimization.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/RunCountOptimization.java
package org.matsim.prepare.opt; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntMap; import org.apache.commons.csv.CSVPrinter; 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.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.*; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CsvOptions; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.counts.Counts; import org.matsim.counts.MatsimCountsReader; import org.matsim.counts.Measurable; import org.matsim.counts.MeasurementLocation; import org.matsim.prepare.RunOpenBerlinCalibration; import org.optaplanner.core.api.solver.Solver; import org.optaplanner.core.api.solver.SolverFactory; import picocli.CommandLine; import java.nio.file.Path; import java.util.*; import java.util.concurrent.atomic.AtomicLong; @CommandLine.Command(name = "run-count-opt", description = "Select plans to match counts data") public class RunCountOptimization implements MATSimAppCommand { static final Logger log = LogManager.getLogger(RunCountOptimization.class); private static final int H = 24; @CommandLine.Option(names = "--input", description = "Path to input plans (Usually experienced plans).", required = true) private Path input; @CommandLine.Option(names = "--output", description = "Output plan selection csv.", required = true) private Path output; @CommandLine.Option(names = "--network", description = "Path to network", required = true) private Path networkPath; @CommandLine.Option(names = "--counts", description = "Path to counts", required = true) private Path countsPath; @CommandLine.Option(names = "--network-mode", description = "Path to vehicle types", defaultValue = TransportMode.car) private String networkMode; @CommandLine.Option(names = "--all-car", description = "Plans have been created with the all car option and counts should be scaled. ", defaultValue = "false") private boolean allCar; @CommandLine.Option(names = "--metric") private ErrorMetric metric = ErrorMetric.abs_error; @CommandLine.Option(names = "--sample-size", defaultValue = "0.25") private double sampleSize; @CommandLine.Option(names = "--k", description = "Number of plans to use from each agent", defaultValue = "5") private int maxK; @CommandLine.Mixin private CsvOptions csv; private Object2IntMap<Id<Link>> linkMapping; private PlanAssignmentProblem problem; public static void main(String[] args) { new RunCountOptimization().execute(args); } @Override public Integer call() throws Exception { Counts<Link> linkCounts = new Counts<>(); new MatsimCountsReader(linkCounts).readFile(countsPath.toString()); Map<Id<Link>, MeasurementLocation<Link>> countStations = linkCounts.getMeasureLocations(); int[] counts = new int[countStations.size() * H]; linkMapping = new Object2IntLinkedOpenHashMap<>(); int k = 0; for (MeasurementLocation<Link> station : countStations.values()) { // hard coded to car calibration Measurable volumes = station.getVolumesForMode(networkMode); for (int i = 0; i < H; i++) { OptionalDouble v = volumes.getAtHour(i); if (v.isPresent()) { int idx = k * H + i; counts[idx] = (int) v.getAsDouble(); if (allCar) counts[idx] = (int) (counts[idx] * RunOpenBerlinCalibration.CAR_FACTOR); } } linkMapping.put(station.getRefId(), k++); } Network network = NetworkUtils.readNetwork(networkPath.toString()); List<PlanPerson> persons = processPopulation(input, network, linkCounts); problem = new PlanAssignmentProblem(maxK, metric, persons, counts); log.info("Collected {} relevant plans", persons.size()); if (allCar) log.info("Scaled counts by car factor of {}", RunOpenBerlinCalibration.CAR_FACTOR); // Error scales are very different so different betas are needed double beta = switch (metric) { case abs_error -> 1; case log_error -> 100; case symmetric_percentage_error -> 300; }; problem.iterate(5000, 0.5, beta, 0.01); PlanAssignmentProblem solution = solve(problem); try (CSVPrinter printer = csv.createPrinter(output)) { printer.printRecord("id", "idx"); for (PlanPerson person : solution) { printer.printRecord(person.getId(), person.getK() - person.getOffset()); } } return 0; } /** * Create an array for each person. */ private List<PlanPerson> processPopulation(Path input, Network network, Counts<Link> linkCounts) { Population population = PopulationUtils.readPopulation(input.toString()); List<PlanPerson> persons = new ArrayList<>(); Set<Id<Link>> links = linkCounts.getMeasureLocations().keySet(); SplittableRandom rnd = new SplittableRandom(0); for (Person person : population.getPersons().values()) { int scale = (int) (1 / sampleSize); Int2IntMap[] plans = new Int2IntMap[maxK]; for (int i = 0; i < plans.length; i++) { plans[i] = new Int2IntOpenHashMap(); } boolean keep = false; int offset = 0; // commercial traffic is scaled here if (!person.getId().toString().startsWith("person")) { // if other trips have been scaled, these unscaled trips are scaled as well if (allCar) // scale with mean of CAR_FACTOR scale *= RunOpenBerlinCalibration.CAR_FACTOR; } // Index for plan int k = offset; for (Plan plan : person.getPlans()) { if (k >= maxK) break; for (PlanElement el : plan.getPlanElements()) { if (el instanceof Leg leg) { Object networkMode = leg.getAttributes().getAttribute("networkMode"); if (!Objects.equals(networkMode, this.networkMode)) continue; if (leg.getRoute() instanceof NetworkRoute route) { double travelTime = leg.getTravelTime().orElseThrow(() -> new IllegalStateException("No travel time for leg")); double freeTravelTime = route.getLinkIds().stream() .map(id -> network.getLinks().get(id)) // Use ceil because traversal over links is always whole seconds during simulation .mapToDouble(l -> Math.ceil(l.getLength() / l.getFreespeed())) .sum(); boolean relevant = route.getLinkIds().stream().anyMatch(links::contains); // The actual travel time per link is not known // The overall deviation is applied to all links equally double factor = travelTime / freeTravelTime; double time = leg.getDepartureTime().seconds(); if (relevant) { keep = true; for (Id<Link> linkId : route.getLinkIds()) { Link link = network.getLinks().get(linkId); // Assume free speed travel time time += Math.ceil(link.getLength() / link.getFreespeed()) * factor; if (linkMapping.containsKey(linkId)) { int idx = linkMapping.getInt(linkId); int hour = (int) Math.floor(time / 3600); if (hour >= H) continue; plans[k].merge(idx * H + hour, scale, Integer::sum); } } } } } } k++; } if (keep) { for (int i = 0; i < plans.length; i++) { if (plans[i].isEmpty()) plans[i] = PlanPerson.NOOP_PLAN; } persons.add(new PlanPerson(person.getId(), offset, plans)); } } return persons; } private PlanAssignmentProblem solve(PlanAssignmentProblem problem) { // Loading fails if xerces is on the classpath SolverFactory<PlanAssignmentProblem> factory = SolverFactory.createFromXmlResource("solver.xml"); Solver<PlanAssignmentProblem> solver = factory.buildSolver(); AtomicLong ts = new AtomicLong(System.currentTimeMillis()); solver.addEventListener(event -> { // Only log every x seconds if (ts.get() + 60_000 < System.currentTimeMillis()) { log.info("New best solution: {}", event.getNewBestScore()); ts.set(System.currentTimeMillis()); } }); return solver.solve(problem); } }
8,292
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PlanPerson.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/PlanPerson.java
package org.matsim.prepare.opt; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.ints.Int2IntMaps; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.population.Person; import org.optaplanner.core.api.domain.entity.PlanningEntity; import org.optaplanner.core.api.domain.lookup.PlanningId; import org.optaplanner.core.api.domain.variable.PlanningVariable; import java.util.Arrays; import java.util.Comparator; import java.util.SplittableRandom; /** * Entity representing a person. */ @PlanningEntity(difficultyComparatorClass = PlanPerson.DifficultyComparator.class) public final class PlanPerson { /** * A plan that does not affect any count stations. */ public static final Int2IntMap NOOP_PLAN = Int2IntMaps.EMPTY_MAP; @PlanningId private final Id<Person> id; /** * If 1, an empty plan was inserted at the front. */ private final int offset; /** * Index of the selected plans. */ @PlanningVariable(valueRangeProviderRefs = "numPlans") private Integer k; /** * Plans and their count increment. */ private final Int2IntMap[] plans; /** * Scores of each plan. */ private final double[] scores; /** * Maximum number of affected counts. */ final int maxImpact; public PlanPerson(Id<Person> id, int offset, Int2IntMap[] plans) { this.id = id; this.offset = offset; this.plans = plans; this.k = 0; int max = 0; for (Int2IntMap plan : plans) { max = Math.max(max, plan.values().intStream().sum()); } this.scores = new double[plans.length]; Arrays.fill(scores, Float.NaN); this.maxImpact = max; } /** * Constructor for cloning. */ private PlanPerson(Integer k, Id<Person> id, int offset, Int2IntMap[] plans, double[] scores, int maxImpact) { this.k = k; this.id = id; this.offset = offset; this.plans = plans; this.scores = scores; this.maxImpact = maxImpact; } public Id<Person> getId() { return id; } /** * Offset compared to the original plans loaded from input. */ public int getOffset() { return offset; } /** * Counts of selected maps. */ public Int2IntMap selected() { return plans[k]; } public Int2IntMap get(int idx) { return plans[idx]; } public void setK(int k) { this.k = k; } public int getK() { return k; } public void setScore(ScoreCalculator calc) { for (int i = 0; i < plans.length; i++) { double score = 0; Int2IntMap p = plans[i]; for (Int2IntMap.Entry e : p.int2IntEntrySet()) { score += calc.scoreEntry(e); } scores[i] = score; } } /** * Change plan with exp beta probability. * * @see org.matsim.core.replanning.strategies.ChangeExpBeta */ public int changePlanExpBeta(double beta, double w, SplittableRandom rnd) { int other = rnd.nextInt(scores.length); double currentPlan = scores[k]; double otherPlan = scores[other]; if (Double.isNaN(otherPlan)) return other; if (Double.isNaN(currentPlan)) return k; double weight = Math.exp(0.5 * beta * (otherPlan - currentPlan)); // switch plan if (rnd.nextDouble() < w * weight) { return other; } return k; } PlanPerson copy() { return new PlanPerson(k, id, offset, plans, scores, maxImpact); } /** * Compares plans by difficulty. */ public static final class DifficultyComparator implements Comparator<PlanPerson> { @Override public int compare(PlanPerson o1, PlanPerson o2) { return Float.compare(o1.maxImpact, o2.maxImpact); } } }
3,476
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PlanAssignmentProblem.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/PlanAssignmentProblem.java
package org.matsim.prepare.opt; import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; import org.optaplanner.core.api.domain.solution.PlanningScore; import org.optaplanner.core.api.domain.solution.PlanningSolution; import org.optaplanner.core.api.domain.solution.cloner.SolutionCloner; import org.optaplanner.core.api.domain.valuerange.CountableValueRange; import org.optaplanner.core.api.domain.valuerange.ValueRangeFactory; import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; import org.optaplanner.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import java.math.BigDecimal; import java.util.*; /** * Planning problem containing all entities and information. */ @PlanningSolution(solutionCloner = PlanAssignmentProblem.Cloner.class) public final class PlanAssignmentProblem implements Iterable<PlanPerson> { final int[] counts; final ErrorMetric metric; private final int maxK; @PlanningEntityCollectionProperty private final List<PlanPerson> persons; @PlanningScore private SimpleBigDecimalScore score; public PlanAssignmentProblem(int maxK, ErrorMetric metric, List<PlanPerson> persons, int[] counts) { this.maxK = maxK; this.metric = metric; this.persons = persons; this.counts = counts; this.score = SimpleBigDecimalScore.ofUninitialized(-1, BigDecimal.ZERO); persons.sort(new PlanPerson.DifficultyComparator()); Collections.reverse(persons); } private PlanAssignmentProblem(int maxK, ErrorMetric metric, List<PlanPerson> persons, int[] counts, SimpleBigDecimalScore score) { this.maxK = maxK; this.metric = metric; this.persons = persons; this.counts = counts; this.score = score; } public int getMaxK() { return maxK; } public List<PlanPerson> getPersons() { return persons; } public int getSize() { return persons.size(); } public SimpleBigDecimalScore getScore() { return score; } public void setScore(SimpleBigDecimalScore score) { this.score = score; } @ValueRangeProvider(id = "numPlans") public CountableValueRange<Integer> getPlanRange() { return ValueRangeFactory.createIntValueRange(0, maxK); } @Override public Iterator<PlanPerson> iterator() { return persons.iterator(); } /** * Iterative pre optimization using change plan exp beta logic. */ public void iterate(int n, double prob, double beta, double w) { ScoreCalculator calc = new ScoreCalculator(); calc.resetWorkingSolution(this); score = calc.calculateScore(); RunCountOptimization.log.info("Iterating {} iters with prob {} and beta {}", n, prob, beta); SplittableRandom rnd = new SplittableRandom(0); double step = prob / n; double best = score.score().doubleValue(); int noBest = 0; for (int i = 0; i < n; i++) { calc.resetWorkingSolution(this); score = calc.calculateScore(); if (i % 100 == 0) RunCountOptimization.log.info("Iteration {} score: {}", i, score); if (score.score().doubleValue() >= best) { best = score.score().doubleValue(); noBest = 0; } else { noBest++; } if (noBest >= 30) { RunCountOptimization.log.info("Stopping after {} with score: {}", i, score); break; } // Best p and beta are not known, so it will be annealed double p = prob - step * i; double b = beta - (beta / n) * i; for (PlanPerson person : persons) { if (rnd.nextDouble() < p) { person.setScore(calc); person.setK(person.changePlanExpBeta(b, w, rnd)); } } } } /** * Create a clone of a solution. */ public static final class Cloner implements SolutionCloner<PlanAssignmentProblem> { @Override public PlanAssignmentProblem cloneSolution(PlanAssignmentProblem original) { List<PlanPerson> personsCopy = new ArrayList<>(); for (PlanPerson person : original.persons) { personsCopy.add(person.copy()); } return new PlanAssignmentProblem(original.maxK, original.metric, personsCopy, original.counts, original.score); } } }
3,976
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
LargeChangeMove.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/opt/LargeChangeMove.java
package org.matsim.prepare.opt; import org.optaplanner.core.api.score.director.ScoreDirector; import org.optaplanner.core.impl.heuristic.move.AbstractMove; import java.util.List; /** * Switch multiple plan assignments at once. */ public class LargeChangeMove extends AbstractMove<PlanAssignmentProblem> { private final List<PlanPerson> persons; private final int[] ks; public LargeChangeMove(List<PlanPerson> persons, int[] ks) { this.persons = persons; this.ks = ks; if (persons.size() != ks.length) throw new IllegalArgumentException("Persons and k must be of equal size"); } @Override protected LargeChangeMove createUndoMove(ScoreDirector<PlanAssignmentProblem> scoreDirector) { return new LargeChangeMove(persons, persons.stream().mapToInt(PlanPerson::getK).toArray()); } @Override protected void doMoveOnGenuineVariables(ScoreDirector<PlanAssignmentProblem> scoreDirector) { for (int i = 0; i < ks.length; i++) { PlanPerson p = persons.get(i); scoreDirector.beforeVariableChanged(p, "k"); p.setK(ks[i]); scoreDirector.afterVariableChanged(p, "k"); } } @Override public LargeChangeMove rebase(ScoreDirector<PlanAssignmentProblem> destinationScoreDirector) { List<PlanPerson> other = persons.stream() .map(destinationScoreDirector::lookUpWorkingObject) .toList(); return new LargeChangeMove(other, ks); } @Override public boolean isMoveDoable(ScoreDirector<PlanAssignmentProblem> scoreDirector) { return true; } }
1,489
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateCountsFromGeoPortalBerlin.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/counts/CreateCountsFromGeoPortalBerlin.java
package org.matsim.prepare.counts; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.geotools.geometry.jts.JTS; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.referencing.CRS; import org.geotools.referencing.operation.transform.IdentityTransform; import org.locationtech.jts.geom.*; import org.locationtech.jts.index.strtree.STRtree; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.application.CommandSpec; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CountsOption; import org.matsim.application.options.InputOptions; import org.matsim.application.options.OutputOptions; import org.matsim.application.options.ShpOptions; import org.matsim.application.prepare.counts.NetworkIndex; import org.matsim.core.config.groups.NetworkConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.filter.NetworkFilterManager; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.run.OpenBerlinScenario; import org.opengis.feature.simple.SimpleFeature; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import picocli.CommandLine; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.function.Predicate; /** * Data can be obtained at Data portal from Berlin. * <a href="https://fbinter.stadt-berlin.de/fb/?loginkey=alphaDataStart&alphaDataId=s_vmengen2019@senstadt">GeoPortal Berlin</a> */ @CommandLine.Command(name = "counts-from-geoportal", description = "Creates MATSim counts from Berlin FIS Broker count data") @CommandSpec( requireNetwork = true, produces = {"dtv_berlin.csv", "dtv_links_capacity.csv"} ) public class CreateCountsFromGeoPortalBerlin implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(CreateCountsFromGeoPortalBerlin.class); /** * Assumed peak traffic during one hour, relative to DTV. */ private static final double PEAK_PERCENTAGE = 0.09; private static final List<String> ROAD_TYPES = List.of("motorway", "trunk", "primary", "secondary", "tertiary", "residential"); /** * Stores all mappings. */ private final Map<Id<Link>, Mapping> mappings = new HashMap<>(); @CommandLine.Mixin private InputOptions input = InputOptions.ofCommand(CreateCountsFromGeoPortalBerlin.class); @CommandLine.Mixin private OutputOptions output = OutputOptions.ofCommand(CreateCountsFromGeoPortalBerlin.class); @CommandLine.Option(names = "--network-geometries", description = "path to *linkGeometries.csv") private Path networkGeometries; @CommandLine.Mixin private CountsOption counts = new CountsOption(); @CommandLine.Mixin private ShpOptions shp = new ShpOptions(); public static void main(String[] args) { new CreateCountsFromGeoPortalBerlin().execute(args); } private static MathTransform getCoordinateTransformation(String inputCRS, String targetCRS) { try { return CRS.findMathTransform(CRS.decode(inputCRS, true), CRS.decode(targetCRS, true)); } catch (FactoryException e) { throw new RuntimeException("Please check the coordinate systems!"); } } @Override public Integer call() throws Exception { if (!shp.isDefined()) { log.error("FIS-Broker shape file path [--shp] is required!"); return 2; } log.info("Read shape file."); List<SimpleFeature> features = shp.readFeatures(); List<Predicate<Link>> roadTypeFilter = createRoadTypeFilter(); log.info("Read network and apply filters"); Network filteredNetwork; { Network network = input.getNetwork(); NetworkFilterManager filter = new NetworkFilterManager(network, new NetworkConfigGroup()); filter.addLinkFilter(link -> link.getAllowedModes().contains(TransportMode.car)); filter.addLinkFilter(link -> roadTypeFilter.stream().anyMatch(predicate -> predicate.test(link))); filteredNetwork = filter.applyFilters(); } log.info("Build Index."); Map<Id<Link>, Geometry> geometries = networkGeometries != null ? NetworkIndex.readGeometriesFromSumo(networkGeometries.toString(), IdentityTransform.create(2)) : new HashMap<>(); NetworkIndex<MultiLineString> index = new NetworkIndex<>(filteredNetwork, geometries, 20, toMatch -> toMatch); // Compare two line strings index.setDistanceCalculator(NetworkIndex::minHausdorffDistance); MathTransform transformation = getCoordinateTransformation(shp.getShapeCrs(), OpenBerlinScenario.CRS); log.info("Processing features."); int counter = 0; for (SimpleFeature feature : features) { counter++; String id = (String) feature.getAttribute("link_id"); if (counts.getIgnored().contains(id)) continue; if (!(feature.getDefaultGeometry() instanceof MultiLineString ls)) { throw new RuntimeException("Geometry #" + counter + " is no LineString. Please check your shape file!."); } MultiLineString transformed = (MultiLineString) JTS.transform(ls, transformation); String direction = (String) feature.getAttribute("vricht"); switch (direction) { case "R" -> handleMatch(feature, index.query(transformed, this::filterDirection), null); case "G" -> handleMatch(feature, null, index.query(transformed, this::filterOppositeDirection)); case "B" -> handleMatch(feature, index.query(transformed, this::filterDirection), index.query(transformed, this::filterOppositeDirection)); default -> throw new IllegalStateException("Unknown direction " + direction); } } Path out = output.getPath(); log.info("Write results to {}", out); try (CSVPrinter csv = new CSVPrinter(Files.newBufferedWriter(out), CSVFormat.DEFAULT)) { csv.printRecord("station_id", "station_name", "to_link", "from_link", "vol_car", "vol_freight"); // There are double entries Set<Mapping> ms = new HashSet<>(mappings.values()); for (Mapping m : ms) { String to = m.toDirection != null ? m.toDirection.toString() : ""; String from = m.fromDirection != null ? m.fromDirection.toString() : ""; csv.printRecord(m.stationId, m.stationName, to, from, m.avgCar, m.avgHGV); } } InverseIndex invIndex = new InverseIndex(features, transformation); try (CSVPrinter csv = new CSVPrinter(Files.newBufferedWriter(output.getPath("dtv_links_capacity.csv")), CSVFormat.DEFAULT)) { createLinksCapacity(csv, filteredNetwork, invIndex, mappings); } return 0; } private void handleMatch(SimpleFeature feature, Link toDirection, Link fromDirection) { String name = (String) feature.getAttribute("str_name"); // throws exceptions if attribute isn't casted to type 'long' long carDTVLong = (long) feature.getAttribute("dtvw_kfz"); int carDTV = (int) carDTVLong; long freightDTVLong = (long) feature.getAttribute("dtvw_lkw"); int freightDTV = (int) freightDTVLong; Mapping m = new Mapping((String) feature.getAttribute("link_id"), name, toDirection != null ? toDirection.getId() : null, fromDirection != null ? fromDirection.getId() : null, carDTV, freightDTV); // A link can not be mapped twice if ((m.toDirection != null && mappings.containsKey(m.toDirection)) || (m.fromDirection != null && mappings.containsKey(m.fromDirection))) { log.warn("Entry with links that are already mapped {}", m); return; } if (m.toDirection != null) mappings.put(m.toDirection, m); if (m.fromDirection != null) mappings.put(m.fromDirection, m); } /** * Create comparison of expected capacity and estimated peak for mapped links. */ private void createLinksCapacity(CSVPrinter csv, Network network, InverseIndex invIndex, Map<Id<Link>, Mapping> mappings) throws IOException { csv.printRecord("link_id", "station_id", "matched_name", "road_type", "peak_volume", "link_capacity", "is_valid"); for (Link link : network.getLinks().values()) { String stationId = null; String stationName = null; double volume = 0; if (mappings.containsKey(link.getId())) { Mapping m = mappings.get(link.getId()); stationId = m.stationId; stationName = m.stationName; volume = (m.avgCar + m.avgHGV) * PEAK_PERCENTAGE; // Links in both direction are assumed to be slightly asymmetric if (m.fromDirection != null && m.toDirection != null) volume /= 1.8; } else { SimpleFeature ft = invIndex.query(link); if (ft != null) { // actually nothing is mapped log.info("Inverse mapped {}", ft); stationId = (String) ft.getAttribute("link_id"); stationName = (String) ft.getAttribute("str_name"); volume = (long) ft.getAttribute("dtvw_kfz") + (long) ft.getAttribute("dtvw_lkw"); volume *= PEAK_PERCENTAGE; String direction = (String) ft.getAttribute("vricht"); if (direction.equals("B")) volume /= 1.8; } } if (stationId != null) { csv.printRecord(link.getId(), stationId, stationName, NetworkUtils.getHighwayType(link), volume, link.getCapacity(), link.getCapacity() >= volume); } } } private List<Predicate<Link>> createRoadTypeFilter() { List<Predicate<Link>> filter = new ArrayList<>(); for (String type : CreateCountsFromGeoPortalBerlin.ROAD_TYPES) { Predicate<Link> p = link -> { var attr = NetworkUtils.getHighwayType(link); return attr.toLowerCase().contains(type); }; filter.add(p); } return filter; } private boolean filterDirection(NetworkIndex.LinkGeometry link, MultiLineString other) { Coordinate[] coordinates = other.getCoordinates(); Coordinate from = coordinates[0]; Coordinate to = coordinates[coordinates.length - 1]; GeometryFactory f = JTSFactoryFinder.getGeometryFactory(); double angle = NetworkIndex.angle((LineString) link.geometry(), f.createLineString(new Coordinate[]{from, to})); return Math.abs(angle) < (Math.PI / 2) * 0.9; } private boolean filterOppositeDirection(NetworkIndex.LinkGeometry link, MultiLineString other) { Coordinate[] coordinates = other.getCoordinates(); Coordinate from = coordinates[0]; Coordinate to = coordinates[coordinates.length - 1]; GeometryFactory f = JTSFactoryFinder.getGeometryFactory(); // Same as above, but to and from are reversed double angle = NetworkIndex.angle((LineString) link.geometry(), f.createLineString(new Coordinate[]{to, from})); return Math.abs(angle) < (Math.PI / 2) * 0.9; } private record Mapping(String stationId, String stationName, Id<Link> toDirection, Id<Link> fromDirection, int avgCar, int avgHGV) { } /** * Maps networks links to geometry. Which is the otherway round than the usual network index. */ private static class InverseIndex { private static final double THRESHOLD = 15; private final STRtree index; InverseIndex(List<SimpleFeature> features, MathTransform ct) throws TransformException { index = new STRtree(); for (SimpleFeature ft : features) { Geometry geometry = JTS.transform((Geometry) ft.getDefaultGeometry(), ct); index.insert(geometry.getBoundary().getEnvelopeInternal(), ft); } index.build(); } public SimpleFeature query(Link link) { GeometryFactory f = JTSFactoryFinder.getGeometryFactory(); Coordinate[] coord = {MGC.coord2Coordinate(link.getFromNode().getCoord()), MGC.coord2Coordinate(link.getToNode().getCoord())}; LineString ls = f.createLineString(coord); List<SimpleFeature> result = index.query(ls.buffer(THRESHOLD).getBoundary().getEnvelopeInternal()); Comparator<SimpleFeature> cmp = Comparator.comparingDouble(value -> NetworkIndex.minHausdorffDistance(ls, (Geometry) value.getDefaultGeometry())); Optional<SimpleFeature> first = result.stream() .sorted(cmp.reversed()) .filter(feature -> NetworkIndex.minHausdorffDistance(ls, (Geometry) feature.getDefaultGeometry()) < THRESHOLD) .findFirst(); return first.orElse(null); } } }
12,113
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
Station.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/counts/Station.java
package org.matsim.prepare.counts; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.network.Link; import java.util.concurrent.atomic.AtomicReference; /** * Record class to hold VIZ count station data, e.g. coords and aggregated volumes. */ public record Station(String id, String name, String direction, Coord coord, AtomicReference<Link> linkAtomicReference) { public Station(String id, String name, String direction, Coord coord) { this(id, name, direction, coord, new AtomicReference<>()); } public String getStationId(){ return id + "_" + name; } }
589
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateCountsFromVMZ.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/counts/CreateCountsFromVMZ.java
package org.matsim.prepare.counts; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.geotools.referencing.operation.transform.IdentityTransform; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CountsOption; import org.matsim.application.options.CrsOptions; import org.matsim.application.prepare.counts.NetworkIndex; import org.matsim.core.config.groups.NetworkConfigGroup; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.filter.NetworkFilterManager; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.counts.Count; import org.matsim.counts.Counts; import org.matsim.counts.CountsWriter; import org.opengis.referencing.operation.TransformException; import picocli.CommandLine; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.*; import java.util.regex.Pattern; @CommandLine.Command( name = "counts-from-vmz", description = "Create counts from the now deprecated (VMZ) data" ) public class CreateCountsFromVMZ implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(CreateCountsFromVMZ.class); @CommandLine.Option(names = "--excel", description = "Path to excel file containing the counts") private Path excel; @CommandLine.Option(names = "--network", description = "Path to network", required = true) private Path network; @CommandLine.Option(names = "--network-geometries", description = "path to *linkGeometries.csv") private Path networkGeometries; @CommandLine.Option(names = "--version", description = "scenario version") private String version = ""; @CommandLine.Option(names = "--output", description = "Base path for the output") private String output; @CommandLine.Mixin private final CrsOptions crs = new CrsOptions(); @CommandLine.Mixin private final CountsOption counts = new CountsOption(); private final Map<Integer, BerlinCount> stations = new HashMap<>(); private final List<BerlinCount> unmatched = new ArrayList<>(); public static void main(String[] args) { new CreateCountsFromVMZ().execute(args); } @Override public Integer call() throws Exception { readExcelFile(excel.toString()); matchWithNetwork(network); createCountsFile(output); return 0; } private void matchWithNetwork(Path network) throws TransformException, IOException { /* * TODO * how to handle count station outside of berlin? * */ Network net; { Network unfiltered = NetworkUtils.readNetwork(network.toString()); NetworkFilterManager manager = new NetworkFilterManager(unfiltered, new NetworkConfigGroup()); manager.addLinkFilter(l -> !l.getId().toString().startsWith("pt_")); net = manager.applyFilters(); } CoordinateTransformation transformation = crs.getTransformation(); NetworkIndex.GeometryGetter<BerlinCount> getter = toMatch -> { Coord coord = toMatch.coord; Coord transform = transformation.transform(coord); return MGC.coord2Point(transform); }; NetworkIndex<BerlinCount> index = networkGeometries != null ? new NetworkIndex<>(net, NetworkIndex.readGeometriesFromSumo(networkGeometries.toString(), IdentityTransform.create(2)), 100, getter): new NetworkIndex<>(net, 100, getter); index.addLinkFilter((link, berlinCounts) -> { String orientation = berlinCounts.orientation; Coord from = link.link().getFromNode().getCoord(); Coord to = link.link().getToNode().getCoord(); String linkDir = ""; if (to.getY() > from.getY()) { linkDir += "nord"; } else linkDir += "süd"; if (to.getX() > from.getX()) { linkDir += "ost"; } else linkDir += "west"; Pattern pattern = Pattern.compile(orientation, Pattern.CASE_INSENSITIVE); return pattern.matcher(linkDir).find(); }); Map<Id<Link>, ? extends Link> links = net.getLinks(); for (var it = stations.entrySet().iterator(); it.hasNext();) { Map.Entry<Integer, BerlinCount> next = it.next(); BerlinCount station = next.getValue(); if (counts.isIgnored(String.valueOf(next.getKey()))) { it.remove(); continue; } Id<Link> manuallyMatched = counts.isManuallyMatched(String.valueOf(next.getKey())); if (manuallyMatched != null && links.containsKey(manuallyMatched)) { station.linkId = manuallyMatched; index.remove(links.get(manuallyMatched)); } Link link = index.query(station); if (link == null) { it.remove(); unmatched.add(station); } else { station.linkId = link.getId(); index.remove(link); } } log.info("Could not match {} stations.", unmatched.size()); } private void readExcelFile(String excel) { XSSFWorkbook wb; try { wb = new XSSFWorkbook(excel); } catch (IOException e) { log.error("Error reading excel file", e); throw new RuntimeException("Error reading excel file"); } extractStations(wb.getSheet("Stammdaten")); extractCarVolumes(wb.getSheet("DTVW_KFZ")); extractFreightVolumes(wb.getSheet("DTVW_LKW")); extractHourlyDistribution(wb.getSheet("typ.Ganglinien_Mo-Do")); extractFreightShare(wb.getSheet("LKW-Anteile")); } private void createCountsFile(String outputFile) { log.info("Create count files."); Counts<Link> countsPkw = new Counts<>(); countsPkw.setYear(2018); countsPkw.setDescription("data from the berliner senate to matsim counts"); Counts<Link> countsLkw = new Counts<>(); countsLkw.setYear(2018); countsLkw.setDescription("data from the berliner senate to matsim counts"); int counter = 0; for (BerlinCount station : stations.values()) { Count<Link> car = countsPkw.createAndAddCount(station.linkId, station.id + "_" + station.position + "_" + station.orientation); //create hour volumes from 'Tagesganglinie' double[] carShareAtHour = station.carShareAtHour; for (int i = 1; i < 25; i++) { car.createVolume(i, ( (station.totalVolume - station.freightVolume) * carShareAtHour[i - 1])); } if (station.hasFreightShare) { Count<Link> freight = countsLkw.createAndAddCount(station.linkId, station.id + "_" + station.position + "_" + station.orientation); double[] freightShareAtHour = station.freightShareAtHour; for (int i = 1; i < 25; i++) { freight.createVolume(i, (station.freightVolume * freightShareAtHour[i - 1])); } } counter++; } if (!version.isBlank()) version += "-"; log.info("Write down {} count stations to file", counter); new CountsWriter(countsPkw).write(outputFile + version + "counts-car-vmz.xml.gz"); new CountsWriter(countsLkw).write(outputFile + version + "counts-freight-vmz.xml.gz"); log.info("Write down {} unmatched count stations to file", unmatched.size()); try (CSVPrinter printer = CSVFormat.Builder.create().setHeader("id", "position", "x", "y").build() .print(Path.of(outputFile + "unmatched_stations.csv"), Charset.defaultCharset())) { CoordinateTransformation transformation = crs.getTransformation(); for (BerlinCount count : unmatched) { printer.print(count.id); printer.print(count.position); Coord transform = transformation.transform(count.coord); printer.print(transform.getX()); printer.print(transform.getY()); printer.println(); } } catch (IOException e) { log.error("Error printing unmatched stations", e); } } private void extractStations(Sheet sheet) { Iterator<Row> it = sheet.iterator(); //skip header row it.next(); while (it.hasNext()) { Row row = it.next(); int id = (int) (row.getCell(0).getNumericCellValue()); BerlinCount station = new BerlinCount(id); //get coord double x = row.getCell(4).getNumericCellValue(); double y = row.getCell(5).getNumericCellValue(); station.coord = new Coord(x, y); String position = row.getCell(1).getStringCellValue(); station.position = replaceUmlaute(position); station.orientation = row.getCell(3).getStringCellValue(); this.stations.put(id, station); } } private void extractCarVolumes(Sheet sheet) { Iterator<Row> it = sheet.iterator(); //skip header row it.next(); while (it.hasNext()) { Row row = it.next(); int id = (int) row.getCell(0).getNumericCellValue(); BerlinCount station = this.stations.get(id); station.totalVolume = (int) row.getCell(1).getNumericCellValue(); } } private void extractFreightVolumes(Sheet sheet) { Iterator<Row> it = sheet.iterator(); //skip header row it.next(); while (it.hasNext()) { Row row = it.next(); int id = (int) row.getCell(0).getNumericCellValue(); BerlinCount station = this.stations.get(id); station.freightVolume = (int) row.getCell(1).getNumericCellValue(); } } private void extractHourlyDistribution(Sheet sheet) { Iterator<Row> it = sheet.iterator(); //skip header row it.next(); while (it.hasNext()) { Row row = it.next(); int id = (int) row.getCell(0).getNumericCellValue(); BerlinCount station = this.stations.get(id); int hour = (int) row.getCell(1).getNumericCellValue(); double carShareAtHour = 0.0; double freightShareAtHour = 0.0; if (row.getCell(2) != null) { carShareAtHour = row.getCell(2).getNumericCellValue(); } if (row.getCell(4) != null) { freightShareAtHour = row.getCell(4).getNumericCellValue(); } station.carShareAtHour[hour] = carShareAtHour; station.freightShareAtHour[hour] = freightShareAtHour; } } private void extractFreightShare(Sheet sheet) { Iterator<Row> it = sheet.iterator(); //skip header row it.next(); while (it.hasNext()) { Row row = it.next(); int id = (int) row.getCell(0).getNumericCellValue(); BerlinCount station = stations.get(id); station.hasFreightShare = true; } } private String replaceUmlaute(String str) { str = str.replace("ü", "ue") .replace("ö", "oe") .replace("ä", "ae") .replace("ß", "ss") .replaceAll("Ü(?=[a-zäöüß ])", "Ue") .replaceAll("Ö(?=[a-zäöüß ])", "Oe") .replaceAll("Ä(?=[a-zäöüß ])", "Ae") .replaceAll("Ü", "UE") .replaceAll("Ö", "OE") .replaceAll("Ä", "AE"); return str; } /** * The BerlinCount object to save the scanned data for further processing. */ private static final class BerlinCount { private final int id; private int totalVolume; private int freightVolume; private final double[] carShareAtHour = new double[24]; private final double[] freightShareAtHour = new double[24]; private Id<Link> linkId; private String position; private String orientation; private boolean hasFreightShare = false; private Coord coord; BerlinCount(int id) { this.id = id; } @Override public String toString() { return "BerlinCount{" + "MQ_ID=" + id + ", linkid=" + linkId.toString() + ", position='" + position + '\'' + ", orientation='" + orientation + '\'' + '}'; } } }
11,334
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateCountsFromVMZOld.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/counts/CreateCountsFromVMZOld.java
package org.matsim.prepare.counts; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.application.MATSimAppCommand; import org.matsim.counts.Counts; import org.matsim.counts.CountsWriter; import org.matsim.counts.Measurable; import org.matsim.counts.MeasurementLocation; import picocli.CommandLine; import java.io.*; import java.nio.file.Path; import java.util.HashMap; import java.lang.String; @CommandLine.Command( name = "counts-from-vmz-old", description = "Create counts from the now deprecated (VMZ) data" ) @Deprecated public class CreateCountsFromVMZOld implements MATSimAppCommand { private static final Logger log = LogManager.getLogger(CreateCountsFromVMZOld.class); @CommandLine.Option(names = "--excel", description = "Path to excel file containing the counts") private Path excel; @CommandLine.Option(names = "--csv", description = "Path to csv file with the mapping") private Path csv; @CommandLine.Option(names = "--output", description = "Base path for the output") private String output; private final HashMap<Integer, BerlinCounts> berlinCountsMap = new HashMap<>(); public static void main(String[] args) { new CreateCountsFromVMZOld().execute(args); } @Override public Integer call() throws Exception { readExcelFile(excel.toString()); readMappingFile(csv.toString()); createCountsFile(output); return 0; } /** * reads the given excel file and creates an BerlinCounts object for every count * * @param excel */ private void readExcelFile(String excel) { try { XSSFWorkbook wb = new XSSFWorkbook(excel); for (int i = 0; i < wb.getNumberOfSheets(); i++) { XSSFSheet sheet = wb.getSheetAt(i); if (sheet.getRow(0).getCell(0).getStringCellValue().equals("MQ_ID")) { ExcelDataFormat.handleSheet(berlinCountsMap, i, sheet); } else { log.warn("sheets should start with MQ_ID, skipping sheet number: {}", i); } } } catch (Exception e) { log.error(e); } } /** * uses the BerlinCounts object to create a car and a truck counts file for matsim * * @param outputFile */ private void createCountsFile(String outputFile) { Counts<Link> counts = new Counts<>(); counts.setYear(2018); counts.setDescription("data from the berliner senate to matsim counts"); for (BerlinCounts berlinCounts : berlinCountsMap.values()) { if (!berlinCounts.isUsing()) { continue; } MeasurementLocation<Link> station = counts.createAndAddMeasureLocation(Id.createLinkId(berlinCounts.getLinkid()), berlinCounts.getMQ_ID() + "_" + berlinCounts.getPosition() + "_" + berlinCounts.getOrientation()); Measurable carVolume = station.createVolume(); double[] PERC_Q_PKW_TYPE = berlinCounts.getPERC_Q_KFZ_TYPE(); for (int i = 1; i < 25; i++) { carVolume.setAtHour(i -1, ( (berlinCounts.getDTVW_KFZ() - berlinCounts.getDTVW_LKW()) * PERC_Q_PKW_TYPE[i - 1])); } if (berlinCounts.isLKW_Anteil()) { Measurable truckVolume = station.createVolume(TransportMode.truck); double[] PERC_Q_LKW_TYPE = berlinCounts.getPERC_Q_LKW_TYPE(); for (int i = 1; i < 25; i++) { truckVolume.setAtHour(i-1, (berlinCounts.getDTVW_LKW() * PERC_Q_LKW_TYPE[i - 1])); } } } new CountsWriter(counts).write(outputFile); } /** * reads a given csv file and adds the data to the BerlinCounts object * * @param file */ private void readMappingFile(String file) { try (BufferedReader br = new BufferedReader(new FileReader(file))) { String headerLine = br.readLine(); String line; while ((line = br.readLine()) != null) { String[] information = line.split(";"); if (information.length < 3) { continue; } int MQ_ID = Integer.parseInt(information[0]); int linkid = -999; if (!information[1].isBlank()) { linkid = Integer.parseInt(information[1]); } String using = information[2]; BerlinCounts count = berlinCountsMap.get(MQ_ID); count.setLinkid(linkid); if (using.equals("x")) { count.setUsing(true); } if (linkid == -999) { berlinCountsMap.remove(MQ_ID); log.warn("No link id: {}", count); } } } catch (IOException e) { log.error(e); } } /** * a description for every excel sheet that is given in the input file to process the data correctly */ private static final class ExcelDataFormat { private static final String[] sheet0 = {"MQ_ID", "DTVW_KFZ", "QUALITY"}; private static final String[] sheet1 = {"MQ_ID", "DTVW_LKW"}; private static final String[] sheet2 = {"MQ_ID", "PERC_LKW"}; private static final String[] sheet3 = {"MQ_ID", "HOUR", "PERC_Q_KFZ_TYPE", "PERC_Q_PKW_TYPE", "PERC_Q_LKW_TYPE"}; private static final String[] sheet4 = {"MQ_ID", "POSITION", "DETAIL", "ORIENTATION", "X_GK4", "Y_GK4", "linkid"}; public static HashMap<Integer, BerlinCounts> handleSheet(HashMap<Integer, BerlinCounts> berlinCountsMap, int i, XSSFSheet sheet) { if (i == 0) { for (int j = 1; j <= sheet.getLastRowNum(); j++) { BerlinCounts berlinCounts = new BerlinCounts((int) sheet.getRow(j).getCell(0).getNumericCellValue()); berlinCounts.setDTVW_KFZ((int) sheet.getRow(j).getCell(1).getNumericCellValue()); berlinCountsMap.put(berlinCounts.getMQ_ID(), berlinCounts); } } else if (i == 1) { for (int j = 1; j <= sheet.getLastRowNum(); j++) { BerlinCounts berlinCounts = berlinCountsMap.get((int) sheet.getRow(j).getCell(0).getNumericCellValue()); berlinCounts.setDTVW_LKW((int) sheet.getRow(j).getCell(1).getNumericCellValue()); } } else if (i == 2) { for (int j = 1; j <= sheet.getLastRowNum(); j++) { BerlinCounts berlinCounts = berlinCountsMap.get((int) sheet.getRow(j).getCell(0).getNumericCellValue()); berlinCounts.setPERC_LKW(sheet.getRow(j).getCell(1).getNumericCellValue()); berlinCounts.setLKW_Anteil(true); } } else if (i == 3) { for (int j = 1; j <= sheet.getLastRowNum(); j++) { BerlinCounts berlinCounts = berlinCountsMap.get((int) sheet.getRow(j).getCell(0).getNumericCellValue()); int hour = (int) sheet.getRow(j).getCell(1).getNumericCellValue(); double PERC_Q_KFZ_TYPE = 0.0; double PERC_Q_PKW_TYPE = 0.0; double PERC_Q_LKW_TYPE = 0.0; if (sheet.getRow(j).getCell(2) != null) { PERC_Q_KFZ_TYPE = sheet.getRow(j).getCell(2).getNumericCellValue(); } if (sheet.getRow(j).getCell(3) != null) { PERC_Q_PKW_TYPE = sheet.getRow(j).getCell(3).getNumericCellValue(); } if (sheet.getRow(j).getCell(4) != null) { PERC_Q_LKW_TYPE = sheet.getRow(j).getCell(4).getNumericCellValue(); } berlinCounts.setArrays(hour, PERC_Q_KFZ_TYPE, PERC_Q_PKW_TYPE, PERC_Q_LKW_TYPE); } } else if (i == 4) { for (int j = 1; j <= sheet.getLastRowNum(); j++) { BerlinCounts berlinCounts = berlinCountsMap.get((int) sheet.getRow(j).getCell(0).getNumericCellValue()); berlinCounts.setPosition(replaceUmlaute(sheet.getRow(j).getCell(1).getStringCellValue())); if (sheet.getRow(j).getCell(2) != null) { berlinCounts.setDetail(replaceUmlaute(sheet.getRow(j).getCell(2).getStringCellValue())); } else { berlinCounts.setDetail(""); } berlinCounts.setOrientation(replaceUmlaute(sheet.getRow(j).getCell(3).getStringCellValue())); // berlinCounts.setLinkid((int) sheet.getRow(j).getCell(6).getNumericCellValue()); } } return berlinCountsMap; } /** * replaces the german umlauts * * @param str * @return */ private static String replaceUmlaute(String str) { str = str.replace("ü", "ue") .replace("ö", "oe") .replace("ä", "ae") .replace("ß", "ss") .replaceAll("Ü(?=[a-zäöüß ])", "Ue") .replaceAll("Ö(?=[a-zäöüß ])", "Oe") .replaceAll("Ä(?=[a-zäöüß ])", "Ae") .replaceAll("Ü", "UE") .replaceAll("Ö", "OE") .replaceAll("Ä", "AE"); return str; } } /** * the BerlinCounts object to save the scanned data for further processing */ private static final class BerlinCounts { private int MQ_ID; private int DTVW_KFZ; private int DTVW_LKW; private double PERC_LKW; private double[] PERC_Q_KFZ_TYPE = new double[24]; private double[] PERC_Q_PKW_TYPE = new double[24]; private double[] PERC_Q_LKW_TYPE = new double[24]; private int linkid; private String position; private String orientation; private String detail; private boolean LKW_Anteil = false; private boolean using = false; public boolean isUsing() { return using; } public void setUsing(boolean using) { this.using = using; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getOrientation() { return orientation; } public void setOrientation(String orientation) { this.orientation = orientation; } public boolean isLKW_Anteil() { return LKW_Anteil; } public void setLKW_Anteil(boolean LKW_Anteil) { this.LKW_Anteil = LKW_Anteil; } public BerlinCounts(int MQ_ID) { this.MQ_ID = MQ_ID; } public int getMQ_ID() { return MQ_ID; } public void setMQ_ID(int MQ_ID) { this.MQ_ID = MQ_ID; } public int getDTVW_KFZ() { return DTVW_KFZ; } public void setDTVW_KFZ(int DTVW_KFZ) { this.DTVW_KFZ = DTVW_KFZ; } public int getDTVW_LKW() { return DTVW_LKW; } public void setDTVW_LKW(int DTVW_LKW) { this.DTVW_LKW = DTVW_LKW; } public double getPERC_LKW() { return PERC_LKW; } public void setPERC_LKW(double PERC_LKW) { this.PERC_LKW = PERC_LKW; } public double[] getPERC_Q_KFZ_TYPE() { return PERC_Q_KFZ_TYPE; } public void setPERC_Q_KFZ_TYPE(double[] PERC_Q_KFZ_TYPE) { this.PERC_Q_KFZ_TYPE = PERC_Q_KFZ_TYPE; } public double[] getPERC_Q_PKW_TYPE() { return PERC_Q_PKW_TYPE; } public void setPERC_Q_PKW_TYPE(double[] PERC_Q_PKW_TYPE) { this.PERC_Q_PKW_TYPE = PERC_Q_PKW_TYPE; } public double[] getPERC_Q_LKW_TYPE() { return PERC_Q_LKW_TYPE; } public void setPERC_Q_LKW_TYPE(double[] PERC_Q_LKW_TYPE) { this.PERC_Q_LKW_TYPE = PERC_Q_LKW_TYPE; } public int getLinkid() { return linkid; } public void setLinkid(int linkid) { this.linkid = linkid; } public void setArrays(int i, double PERC_Q_KFZ_TYPE, double PERC_Q_PKW_TYPE, double PERC_Q_LKW_TYPE) { this.PERC_Q_KFZ_TYPE[i] = PERC_Q_KFZ_TYPE; this.PERC_Q_PKW_TYPE[i] = PERC_Q_PKW_TYPE; this.PERC_Q_LKW_TYPE[i] = PERC_Q_LKW_TYPE; } @Override public String toString() { return "BerlinCounts{" + "MQ_ID=" + MQ_ID + ", linkid=" + linkid + ", position='" + position + '\'' + ", orientation='" + orientation + '\'' + ", detail='" + detail + '\'' + '}'; } } }
11,164
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateCountsFromMonthlyVizData.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/prepare/counts/CreateCountsFromMonthlyVizData.java
package org.matsim.prepare.counts; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.geotools.referencing.operation.transform.IdentityTransform; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.application.MATSimAppCommand; import org.matsim.application.options.CountsOption; import org.matsim.application.options.CrsOptions; import org.matsim.application.options.CsvOptions; import org.matsim.application.prepare.counts.NetworkIndex; import org.matsim.core.network.NetworkUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.counts.Count; import org.matsim.counts.Counts; import org.matsim.counts.CountsWriter; import org.opengis.referencing.operation.TransformException; import picocli.CommandLine; import tech.tablesaw.api.DateColumn; import tech.tablesaw.api.DoubleColumn; import tech.tablesaw.api.StringColumn; import tech.tablesaw.api.Table; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.*; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; import static tech.tablesaw.aggregate.AggregateFunctions.mean; @CommandLine.Command(name = "counts-detailed", description = "Own aggregation of VIZ data for MATSim Counts") public class CreateCountsFromMonthlyVizData implements MATSimAppCommand { @CommandLine.Option(names = "--input", description = "input count data directory", required = true) Path input; @CommandLine.Option(names = "--network", description = "MATSim network file path", required = true) Path networkPath; @CommandLine.Option(names = "--network-geometries", description = "network geometry file path", required = true) private Path geometries; @CommandLine.Option(names = "--output", description = "output directory", defaultValue = "input/") Path output; @CommandLine.Option(names = "--scenario", description = "scenario name for output files", defaultValue = "berlin-v6.0") String scenario; @CommandLine.Option(names = "--year", description = "year of count data", defaultValue = "2022") int year; @CommandLine.Option(names = "--use-road-names", description = "use road names to filter map matching results") boolean roadNames; @CommandLine.Mixin private final CsvOptions csv = new CsvOptions(); @CommandLine.Mixin private final CrsOptions crs = new CrsOptions(); @CommandLine.Mixin CountsOption counts = new CountsOption(); private final Map<String, Station> stations = new HashMap<>(); private final Logger logger = LogManager.getLogger(CreateCountsFromMonthlyVizData.class); public static void main(String[] args) { new CreateCountsFromMonthlyVizData().execute(args); } @Override public Integer call() throws Exception { String outputString = !output.toString().endsWith("/") || !output.toString().endsWith("\\") ? output + "/" : output.toString(); //Create Counts Objects Counts<Link> car = new Counts<>(); car.setName(scenario + " car counts"); car.setDescription("Car counts based on data from the 'Verkehrsinformationszentrale Berlin'."); car.setYear(year); Counts<Link> freight = new Counts<>(); freight.setName(scenario + " freight counts"); freight.setDescription("Freight counts based on data from the 'Verkehrsinformationszentrale Berlin'."); freight.setYear(year); //Get filepaths List<Path> countPaths = new ArrayList<>(); Path stationPath = null; for (Path path : Files.walk(input).collect(Collectors.toList())) { //Station data is stored as .xlsx if (path.toString().endsWith(".xlsx") && stationPath == null) stationPath = path; //count data is stored in .gz if (path.toString().endsWith(".gz")) countPaths.add(path); } if (countPaths.size() < 12) logger.warn("Expected 12 files, but only {} files containing count data were provided.", countPaths.size()); if (stationPath == null) { logger.warn("No station data were provided. Return Code 1"); return 1; } extractStations(stationPath, stations, counts); matchWithNetwork(networkPath, geometries, stations, counts); List<CSVRecord> records = readCountData(countPaths); aggregateAndAssignCountData(records, stations, car, freight, outputString); new CountsWriter(car).write(outputString + scenario + ".counts_car.xml"); new CountsWriter(freight).write(outputString + scenario + ".counts_freight.xml"); return 0; } private LineString parseCoordinates(String coordinateSequence, GeometryFactory factory) { String[] split = coordinateSequence.split("\\)"); Coordinate[] coordinates = new Coordinate[split.length]; for (int i = 0; i < split.length; i++) { String coord = split[i]; int toRemove = coord.indexOf("("); String cleaned = coord.substring(toRemove + 1); String[] split1 = cleaned.split(","); Coordinate coordinate = new Coordinate(); coordinate.setX(Double.parseDouble(split1[0])); coordinate.setY(Double.parseDouble(split1[1])); coordinates[i] = coordinate; } return factory.createLineString(coordinates); } private void matchWithNetwork(Path networkPath, Path geometries, Map<String, Station> stations, CountsOption countsOption) throws TransformException, IOException { Network network = NetworkUtils.readNetwork(networkPath.toString()); CoordinateTransformation transformation = crs.getTransformation(); Map<Id<Link>, Geometry> networkGeometries = NetworkIndex.readGeometriesFromSumo(geometries.toString(), IdentityTransform.create(2)); NetworkIndex<Station> index = new NetworkIndex<>(network, networkGeometries, 50, toMatch -> { Coord coord = toMatch.coord(); Coord transform = transformation.transform(coord); return MGC.coord2Point(transform); }); //Add link direction filter index.addLinkFilter((link, station) -> { String direction = station.direction(); Coord from = link.link().getFromNode().getCoord(); Coord to = link.link().getToNode().getCoord(); String linkDir = ""; if (to.getY() > from.getY()) { linkDir += "nord"; } else linkDir += "süd"; if (to.getX() > from.getX()) { linkDir += "ost"; } else linkDir += "west"; Pattern pattern = Pattern.compile(direction, Pattern.CASE_INSENSITIVE); return pattern.matcher(linkDir).find(); }); index.addLinkFilter(((link, station) -> !link.link().getId().toString().startsWith("pt_"))); if (roadNames) { index.addLinkFilter((link, station) -> { String name = station.name().toLowerCase(); if (name.endsWith("straße") || name.endsWith("str")) name.replace("straße", "").replace("str", ""); if (name.equals("straße des 17. juni")) return true; Object linkRoadName = link.link().getAttributes().getAttribute("name"); if (linkRoadName == null) return true; return Pattern.compile(name, Pattern.CASE_INSENSITIVE).matcher((String) linkRoadName).find(); }); } logger.info("Start matching stations to network."); int counter = 0; for (var it = stations.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Station> next = it.next(); //Check for manual matching! Id<Link> manuallyMatched = countsOption.isManuallyMatched(next.getKey()); if (manuallyMatched != null) { if (!network.getLinks().containsKey(manuallyMatched)) throw new RuntimeException("Link " + manuallyMatched.toString() + " is not in the network!"); Link link = network.getLinks().get(manuallyMatched); next.getValue().linkAtomicReference().set(link); index.remove(link); continue; } Link query = index.query(next.getValue()); if (query == null) { counter++; it.remove(); continue; } next.getValue().linkAtomicReference().set(query); index.remove(query); } logger.info("Could not match {} stations", counter); } private void extractStations(Path path, Map<String, Station> stations, CountsOption countsOption) { XSSFSheet sheet; try (XSSFWorkbook wb = new XSSFWorkbook(path.toString())) { sheet = wb.getSheetAt(0); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } for (Row row : sheet) { if (row.getRowNum() == 0) continue; String id = row.getCell(0).getStringCellValue(); String lane = row.getCell(9).getStringCellValue(); //for some reason count stations on bus lanes have an own station id, but same coordinates like the regular stations and causing trouble in map matching if (stations.containsKey(id) || "BUS".equals(lane) || countsOption.isIgnored(id)) continue; String name = row.getCell(5).getStringCellValue(); String direction = row.getCell(8).getStringCellValue(); double x = row.getCell(11).getNumericCellValue(); double y = row.getCell(12).getNumericCellValue(); Station station = new Station(id, name, direction, new Coord(x, y)); stations.put(id, station); } } private List<CSVRecord> readCountData(List<Path> paths) { //Read all files and build one record collection logger.info("Start parsing count data."); List<CSVRecord> records = new ArrayList<>(); for (Path path : paths) { try (GZIPInputStream gis = new GZIPInputStream( new FileInputStream(path.toFile())) ) { Path decompressed = Path.of(path.toString().replace(".gz", "")); if (!Files.exists(decompressed)) Files.copy(gis, decompressed); List<CSVRecord> month = csv.createParser(decompressed).getRecords(); records.addAll(month); } catch (IOException e) { logger.warn("Error processing file {}: ", path.toString()); throw new RuntimeException(e.getMessage()); } } return records; } private void aggregateAndAssignCountData(List<CSVRecord> records, Map<String, Station> stations, Counts<Link> carCounts, Counts<Link> freightCounts, String outputString) { //Create table from records first Table table; { StringColumn id = StringColumn.create(ColumnNames.id); DateColumn date = DateColumn.create(ColumnNames.date); StringColumn hour = StringColumn.create(ColumnNames.hour); DoubleColumn car = DoubleColumn.create(ColumnNames.carVolume); DoubleColumn freight = DoubleColumn.create(ColumnNames.freightVolume); DoubleColumn carSpeed = DoubleColumn.create(ColumnNames.carAvgSpeed); DoubleColumn freightSpeed = DoubleColumn.create(ColumnNames.freightAvgSpeed); for (CSVRecord row : records) { id.append(row.get(0)); LocalDate formatedDate = LocalDate.parse(row.get(1), DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.GERMAN)); date.append(formatedDate); hour.append(row.get(2)); car.append(Double.parseDouble(row.get(6))); carSpeed.append(Double.parseDouble(row.get(7))); freight.append(Double.parseDouble(row.get(8))); freightSpeed.append(Double.parseDouble(row.get(9))); } table = Table.create(id, date, hour, car, freight, carSpeed, freightSpeed); } Predicate<LocalDate> dayFilter = localDate -> { int day = localDate.getDayOfWeek().getValue(); return day > 1 && day < 5; }; //filter and aggregation logger.info("Start Aggregation"); Table summarized = table.where(t -> t.dateColumn(ColumnNames.date).eval(dayFilter)) .summarize(ColumnNames.carVolume, ColumnNames.freightVolume, ColumnNames.carAvgSpeed, ColumnNames.freightAvgSpeed, mean) .by(ColumnNames.id, ColumnNames.hour); //Column names were edited by summarize function for (String name : table.columnNames()) summarized.columnNames().stream().filter(s -> s.contains(name)).findFirst().ifPresent(s -> summarized.column(s).setName(name)); //Assign aggregted hourly traffic volumes to count objects AND write avg speed per link and hour to csv file try (CSVPrinter printer = csv.createPrinter(Path.of(outputString + scenario + ".avg_speed.csv"))) { printer.print(ColumnNames.id); printer.print(ColumnNames.hour); printer.print(ColumnNames.carAvgSpeed); printer.print(ColumnNames.freightAvgSpeed); printer.println(); int counter = 0; for (Map.Entry<String, Station> entry : stations.entrySet()) { String key = entry.getKey(); Station station = entry.getValue(); Table idFiltered = summarized.copy().where(t -> t.stringColumn(ColumnNames.id).isEqualTo(key)); if (idFiltered.rowCount() != 24) { logger.warn("Station {} - {} does not contain hour values for the whole day!", key, station.name()); counter++; continue; } Count<Link> carCount = carCounts.createAndAddCount(station.linkAtomicReference().get().getId(), station.getStationId()); Count<Link> freightCount = freightCounts.createAndAddCount(station.linkAtomicReference().get().getId(), station.getStationId()); for (tech.tablesaw.api.Row row : idFiltered) { double car = row.getDouble(ColumnNames.carVolume); //in VIZ data hours starts at 0, in MATSim count data starts at 1 int hour = Integer.parseInt(row.getString(ColumnNames.hour)) + 1; double freight = row.getDouble(ColumnNames.freightVolume); carCount.createVolume(hour, Math.round(car)); freightCount.createVolume(hour, Math.round(freight)); //print to file double carSpeed = row.getDouble(ColumnNames.carAvgSpeed); double freightSpeed = row.getDouble(ColumnNames.freightAvgSpeed); printer.print(station.linkAtomicReference().get().getId().toString()); printer.print(hour); printer.print(Math.round(carSpeed)); printer.print(Math.round(freightSpeed)); printer.println(); } } logger.info("Skipped {} stations, because data was incomplete!", counter); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } private static class ColumnNames { static String id = "id"; static String date = "date"; static String hour = "hour"; static String carVolume = "car_volume"; static String carAvgSpeed = "car_avg_speed"; static String freightVolume = "freight_volume"; static String freightAvgSpeed = "freight_avg_speed"; } }
14,717
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
package-info.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/package-info.java
/* *********************************************************************** * * project: org.matsim.* * * * * *********************************************************************** * * * * copyright : (C) 2008 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ /** * Old code from the Berlin v5 model. */ @Deprecated package org.matsim.legacy;
1,436
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
WriteCountsFileAndUpdateLinkIDs.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/networkCounts/WriteCountsFileAndUpdateLinkIDs.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.networkCounts; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; 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.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.io.tabularFileParser.TabularFileHandler; import org.matsim.core.utils.io.tabularFileParser.TabularFileParser; import org.matsim.core.utils.io.tabularFileParser.TabularFileParserConfig; import org.matsim.counts.Count; import org.matsim.counts.Counts; import org.matsim.counts.CountsWriter; import org.matsim.counts.MatsimCountsReader; /** * @author ikaddoura */ public class WriteCountsFileAndUpdateLinkIDs { private final Logger log = LogManager.getLogger(WriteCountsFileAndUpdateLinkIDs.class); private Network network; private Counts<Link> inputCounts; private Map<String, Id<Link>> countId2LinkId; public static void main(String[] args) { final String countsfile = "/Users/ihab/Documents/workspace/shared-svn/studies/countries/de/open_berlin_scenario/network_counts/vmz_di-do_shortIds.xml"; final String osmNodeFile = "/Users/ihab/Documents/workspace/shared-svn/studies/countries/de/open_berlin_scenario/berlin_4.0/counts/counts_OSM-nodes.csv"; final String networkFile = "/Users/ihab/Documents/workspace/shared-svn/studies/countries/de/open_berlin_scenario/berlin_4.0/network/berlin_brandenburg_berlin4.0_v1_2018-02-21_keepPaths-false_keepCountOSMnodeIDs-true_cleaned_network.xml.gz"; final String countsOutputFile = "/Users/ihab/Documents/workspace/shared-svn/studies/countries/de/open_berlin_scenario/berlin_4.0/counts/vmz_di-do_berlin4.0_detailed-network-v1.xml.gz"; WriteCountsFileAndUpdateLinkIDs writer = new WriteCountsFileAndUpdateLinkIDs(networkFile, countsfile, osmNodeFile); writer.write(countsOutputFile); } private void write(String countsOutputFile) { Counts<Link> outputCounts = new Counts<>(); outputCounts.setDescription("based on 'vmz_di-do.xml' with link IDs for the detailed berlin 4.0 network v1"); outputCounts.setName("vmz_di-do_detailed-network_berlin-4.0_v1"); outputCounts.setYear(inputCounts.getYear()); Set<String> processedCountLinkIDs = new HashSet<>(); for (Count<Link> count : inputCounts.getCounts().values()) { if (processedCountLinkIDs.contains(count.getCsLabel())) { log.warn(count.getCsLabel() + " already processed. Skipping..."); } else { Id<Link> newLinkId = null; if (this.countId2LinkId.get(count.getCsLabel()) == null) { log.warn("Counting station ID " + count.getCsLabel() + " not found in OSM node ID file: " + countId2LinkId.toString()); } else { newLinkId = this.countId2LinkId.get(count.getCsLabel()); log.info("Adding count Id " + count.getCsLabel() + " on link " + newLinkId); outputCounts.createAndAddCount(newLinkId, count.getCsLabel()); outputCounts.getCounts().get(newLinkId).setCoord(count.getCoord()); outputCounts.getCounts().get(newLinkId).getVolumes().putAll(count.getVolumes()); } processedCountLinkIDs.add(count.getCsLabel()); } } CountsWriter countsWriter = new CountsWriter(outputCounts); countsWriter.write(countsOutputFile); log.info("Counts file written to " + countsOutputFile); } public WriteCountsFileAndUpdateLinkIDs(String networkFile, String countsfile, String osmNodeFile) { network = ScenarioUtils.createScenario(ConfigUtils.createConfig()).getNetwork(); MatsimNetworkReader reader = new MatsimNetworkReader(network); reader.readFile(networkFile); countId2LinkId = getCountId2LinkId(osmNodeFile); inputCounts = new Counts<>(); MatsimCountsReader countsReader = new MatsimCountsReader(inputCounts); countsReader.readFile(countsfile); log.info("--> Counts in Count OSM node ID file: " + countId2LinkId.size()); log.info("--> Counts in counts file: " + inputCounts.getCounts().size()); if (countId2LinkId.size() != inputCounts.getCounts().size()) { log.warn("Counts file and Count OSM node ID file doesn't seem to match."); } } private Map<String, Id<Link>> getCountId2LinkId(String csvFile){ final Map<String, Id<Link>> countId2LinkId = new HashMap<>(); TabularFileParserConfig tabfileParserConfig = new TabularFileParserConfig(); tabfileParserConfig.setDelimiterTags(new String[] {";"}); log.info("Reading count Id and osm node IDs from" + csvFile); tabfileParserConfig.setFileName(csvFile); new TabularFileParser().parse(tabfileParserConfig, new TabularFileHandler() { boolean header = true; int lineCounter = 0; @Override public void startRow(String[] row) { if(!header){ if( !(row[0].equals("") || row[1].equals("") || row[2].equals("") ) ) { String countId = row[0]; Id<Node> fromNodeId = Id.createNodeId(row[1]); Id<Node> toNodeId = Id.createNodeId(row[2]); Id<Link> linkId = getLinkId(fromNodeId, toNodeId); countId2LinkId.put(countId, linkId); log.info(countId + " --> " + linkId); } } lineCounter++; if (lineCounter%10 == 0) { log.info("Line " + lineCounter); } header = false; } }); return countId2LinkId; } private Id<Link> getLinkId(Id<Node> fromNodeId, Id<Node> toNodeId) { Id<Link> linkId = null; for (Link link : network.getLinks().values()) { if (link.getFromNode().getId().toString().equals(fromNodeId.toString()) && link.getToNode().getId().toString().equals(toNodeId.toString())) { if (linkId == null) { linkId = link.getId(); } else { log.warn("There is more than one link with the from node Id " + fromNodeId + " and to node Id " + toNodeId + ": " + linkId + " and " + link.getId()); } } } if (linkId == null) { log.warn("No Link id found for from node Id " + fromNodeId + " and to node Id " + toNodeId + "."); // throw new RuntimeException("Aborting..."); } return linkId; } }
7,605
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateNetworkAndKeepCountLinks.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/networkCounts/CreateNetworkAndKeepCountLinks.java
/* *********************************************************************** * * project: org.matsim.* * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ /** * */ package org.matsim.legacy.prepare.networkCounts; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; 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.network.Network; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.algorithms.NetworkCleaner; import org.matsim.core.network.algorithms.NetworkSimplifier; import org.matsim.core.network.io.NetworkWriter; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.io.OsmNetworkReader; import org.matsim.core.utils.io.tabularFileParser.TabularFileHandler; import org.matsim.core.utils.io.tabularFileParser.TabularFileParser; import org.matsim.core.utils.io.tabularFileParser.TabularFileParserConfig; /** * * * The osm input file may be generated as follows: * * Download the latest osm files (*osm.pbf) from https://download.geofabrik.de * * Install the programm osmosis and use the following commands to plug everything together: * * detailed network: * osmosis --rb file=berlin-latest.osm.pbf --tf accept-ways highway=motorway,motorway_link,trunk,trunk_link,primary,primary_link,secondary_link,secondary,tertiary,motorway_junction,residential,unclassified,living_street --used-node --wb berlin-latest-2018-02-20_incl-residential-and-living-street.osm.pbf * * coarse network: * osmosis --rb file=brandenburg-latest.osm.pbf --tf accept-ways highway=motorway,motorway_link,trunk,trunk_link,primary,primary_link,secondary_link,secondary,tertiary,motorway_junction --used-node --wb brandenburg-latest-2018-02-20_incl-tertiary.osm.pbf * * merge: * osmosis --rb file=brandenburg-latest-2018-02-20_incl-tertiary.osm.pbf --rb berlin-latest-2018-02-20_incl-residential-and-living-street.osm.pbf --merge --wx berlin-brandenburg-network_2018-02-20.osm * * @author tschlenther, ikaddoura * */ public class CreateNetworkAndKeepCountLinks { private final Logger log = LogManager.getLogger(CreateNetworkAndKeepCountLinks.class); private final String INPUT_OSMFILE ; private final List<String> INPUT_COUNT_NODE_MAPPINGS; private final String outputDir; private final String prefix; private final String networkCS ; private Network network = null; private String outnetworkPrefix ; public static void main(String[] args) { String osmfile = "/Users/ihab/Documents/workspace/shared-svn/studies/countries/de/open_berlin_scenario/be_3/network/osm/berlin-brandenburg-network_2018-02-20.osm"; String prefix = "berlin-car_be_5_withVspAdjustments" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String outDir = "/Users/ihab/Documents/workspace/shared-svn/studies/countries/de/open_berlin_scenario/be_5/network/"; boolean keepCountsOSMnodes = true; List<String> inputCountNodeMappingFiles = Arrays.asList("/Users/ihab/Documents/workspace/shared-svn/studies/countries/de/open_berlin_scenario/be_3/counts/counts_OSM-nodes.csv"); String crs = TransformationFactory.DHDN_GK4; CreateNetworkAndKeepCountLinks berlinNetworkCreator = new CreateNetworkAndKeepCountLinks(osmfile, inputCountNodeMappingFiles, crs , outDir, prefix); boolean keepPaths = false; boolean clean = true; boolean simplify = false; berlinNetworkCreator.createNetwork(keepCountsOSMnodes, keepPaths, simplify, clean); berlinNetworkCreator.writeNetwork(); } public CreateNetworkAndKeepCountLinks(String inputOSMFile, List<String> inputCountNodeMappingFiles, String networkCoordinateSystem, String outputDir, String prefix) { this.INPUT_OSMFILE = inputOSMFile; this.INPUT_COUNT_NODE_MAPPINGS = inputCountNodeMappingFiles; this.networkCS = networkCoordinateSystem; this.outputDir = outputDir.endsWith("/")?outputDir:outputDir+"/"; this.prefix = prefix; this.outnetworkPrefix = prefix; initLogger(); log.info("--- set the coordinate system for network to be created to " + this.networkCS + " ---"); } public void writeNetwork(){ String outNetwork = this.outputDir+outnetworkPrefix+"_network.xml.gz"; log.info("Writing network to " + outNetwork); new NetworkWriter(network).write(outNetwork); log.info("... done."); } public void createNetwork(boolean keepCountOSMnodes, boolean keepPaths, boolean doSimplify, boolean doCleaning){ CoordinateTransformation ct = TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, networkCS); Set<Long> nodeIDsToKeep = readNodeIDs(INPUT_COUNT_NODE_MAPPINGS); if(this.network == null) { Config config = ConfigUtils.createConfig(); Scenario scenario = ScenarioUtils.createScenario(config); network = scenario.getNetwork(); log.info("start parsing from osm file " + INPUT_OSMFILE); OsmNetworkReader networkReader = new OsmNetworkReader(network,ct, true, true); if (keepPaths) { networkReader.setKeepPaths(true); } else { networkReader.setKeepPaths(false); } // outnetworkPrefix += "_keepPaths-" + keepPaths; if (keepCountOSMnodes) { networkReader.setNodeIDsToKeep(nodeIDsToKeep); } // outnetworkPrefix += "_keepCountOSMnodeIDs-" + keepCountOSMnodes; networkReader.parse(INPUT_OSMFILE); log.info("finished parsing osm file"); } log.info("checking if all count nodes are in the network.."); for(Long id : nodeIDsToKeep){ if(!network.getNodes().containsKey(Id.createNodeId(id))){ log.error("COULD NOT FIND NODE " + id + " IN THE NETWORK BEFORE SIMPLIFYING AND CLEANING"); } } if (doSimplify){ outnetworkPrefix += "_simplified"; log.info("number of nodes before simplifying:" + network.getNodes().size()); log.info("number of links before simplifying:" + network.getLinks().size()); log.info("start simplifying the network"); /* * simplify network: merge links that are shorter than the given threshold */ NetworkSimplifier simp = new NetworkSimplifier(); simp.setNodesNotToMerge(nodeIDsToKeep); simp.setMergeLinkStats(false); simp.run(network); log.info("number of nodes after simplifying:" + network.getNodes().size()); log.info("number of links after simplifying:" + network.getLinks().size()); log.info("checking if all count nodes are in the network.."); for(Long id : nodeIDsToKeep){ if(!network.getNodes().containsKey(Id.createNodeId(id))){ log.error("COULD NOT FIND NODE " + id + " IN THE NETWORK AFTER SIMPLIFYING"); } } } if (doCleaning){ // outnetworkPrefix += "_cleaned"; /* * Clean the Network. Cleaning means removing disconnected components, so that afterwards there is a route from every link * to every other link. This may not be the case in the initial network converted from OpenStreetMap. */ log.info("number of nodes before cleaning:" + network.getNodes().size()); log.info("number of links before cleaning:" + network.getLinks().size()); log.info("attempt to clean the network"); new NetworkCleaner().run(network); } log.info("number of nodes after cleaning:" + network.getNodes().size()); log.info("number of links after cleaning:" + network.getLinks().size()); log.info("checking if all count nodes are in the network.."); for(Long id : nodeIDsToKeep){ if(!network.getNodes().containsKey(Id.createNodeId(id))){ log.error("COULD NOT FIND NODE " + id + " IN THE NETWORK AFTER NETWORK CREATION"); } } } /** * expects a path to a csv file that has the following structure: <br><br> * * COUNT-ID;OSM_FROMNODE_ID;OSM_TONODE_ID <br><br> * * It is assumed that the csv file contains a header line. * Returns a set of all mentioned osm-node-ids. * * @param listOfCSVFiles * @return */ private Set<Long> readNodeIDs(List<String> listOfCSVFiles){ final Set<Long> allNodeIDs = new HashSet<Long>(); TabularFileParserConfig config = new TabularFileParserConfig(); config.setDelimiterTags(new String[] {";"}); log.info("start reading osm node id's of counts"); for(String path : listOfCSVFiles){ log.info("reading node id's from" + path); config.setFileName(path); new TabularFileParser().parse(config, new TabularFileHandler() { boolean header = true; @Override public void startRow(String[] row) { if(!header){ if( !(row[1].equals("") || row[2].equals("") ) ){ allNodeIDs.add( Long.parseLong(row[1])); allNodeIDs.add( Long.parseLong(row[2])); } } header = false; } }); } return allNodeIDs; } private void initLogger(){ // FileAppender fa = new FileAppender(); // fa.setFile(outputDir + prefix +"_LOG_" + CreateNetworkAndKeepCountLinks.class.getSimpleName() + outnetworkPrefix + ".txt"); // fa.setName("BerlinNetworkCreator"); // fa.activateOptions(); // fa.setLayout(new PatternLayout("%d{dd MMM yyyy HH:mm:ss,SSS} %-4r [%t] %-5p %c %x - %m%n")); // log.addAppender(fa); throw new RuntimeException( "seems to have broken with update of log4j. kai, mar'20" ); } }
10,556
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DeleteDRTRoutesFromPopulation.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/drt/DeleteDRTRoutesFromPopulation.java
/* *********************************************************************** * * project: org.matsim.* * Controler.java * * * *********************************************************************** * * * * copyright : (C) 2007 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.drt; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.GenericRouteImpl; import org.matsim.core.router.TripStructureUtils; import java.util.ArrayList; import java.util.List; public class DeleteDRTRoutesFromPopulation { public static void main(String[] args) { String inputPopulation = "D:/svn/shared-svn/projects/pave/matsim-input-files/drt-test-demand/pave109.output_plans.xml.gz"; Population population = PopulationUtils.readPopulation(inputPopulation); population.getPersons().values().parallelStream() .forEach(person -> { List<Plan> plansToDelete = new ArrayList<>(); person.getPlans().forEach(plan -> { if (plan.equals(person.getSelectedPlan())){ TripStructureUtils.getLegs(plan) .forEach(leg -> { if(leg.getRoute() instanceof GenericRouteImpl && leg.getMode().equals("drt")){ leg.setRoute(null); } }); } else plansToDelete.add(plan); } ); plansToDelete.forEach(plan -> person.removePlan(plan)); }); PopulationUtils.writePopulation(population, "D:/svn/shared-svn/projects/pave/matsim-input-files/drt-test-demand/pave109.output_plans_selected-only-woDrtRoutes.xml.gz"); } }
2,748
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
DrtVehicleCreator.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/drt/DrtVehicleCreator.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.drt; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import com.opencsv.CSVWriter; import org.apache.commons.math3.distribution.EnumeratedDistribution; import org.apache.commons.math3.util.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Point; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.population.Activity; import org.matsim.contrib.dvrp.fleet.DvrpVehicle; import org.matsim.contrib.dvrp.fleet.DvrpVehicleSpecification; import org.matsim.contrib.dvrp.fleet.FleetWriter; import org.matsim.contrib.dvrp.fleet.ImmutableDvrpVehicleSpecification; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.network.NetworkUtils; import org.matsim.core.network.algorithms.TransportModeNetworkFilter; import org.matsim.core.network.io.NetworkWriter; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.io.PopulationReader; import org.matsim.core.router.StageActivityTypeIdentifier; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.facilities.MatsimFacilitiesReader; import org.matsim.legacy.run.drt.BerlinShpUtils; import org.matsim.legacy.run.drt.RunDrtOpenBerlinScenario; /** * @author gleich * */ public class DrtVehicleCreator { private static final Logger log = LogManager.getLogger(DrtVehicleCreator.class); private final CoordinateTransformation ct; private final Scenario scenario ; private final Random random = MatsimRandom.getRandom(); private final String drtNetworkMode = "drt"; private final BerlinShpUtils shpUtils; private final Network drtNetwork; private List<Pair<Id<Link>, Double>> links2weights = new ArrayList(); public static void main(String[] args) { String networkFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-network.xml.gz"; String populationFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-10pct.plans.xml.gz"; String facilitiesFile = ""; String drtServiceAreaShapeFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-shp/berlin.shp"; CoordinateTransformation ct = TransformationFactory.getCoordinateTransformation("EPSG:31468", "EPSG:31468"); // String vehiclesFilePrefix = "berlin-drt-v5.5.spandau_b-drt-by-actLocations-sqrt-"; String vehiclesFilePrefix = "berlin-drt-v5.5.drt-by-rndLocations-"; Set<Integer> numbersOfVehicles = new HashSet<>(); numbersOfVehicles.add(20); numbersOfVehicles.add(30); numbersOfVehicles.add(50); numbersOfVehicles.add(80); numbersOfVehicles.add(100); numbersOfVehicles.add(120); numbersOfVehicles.add(150); numbersOfVehicles.add(200); numbersOfVehicles.add(250); numbersOfVehicles.add(300); numbersOfVehicles.add(400); numbersOfVehicles.add(500); numbersOfVehicles.add(600); numbersOfVehicles.add(700); numbersOfVehicles.add(800); numbersOfVehicles.add(900); numbersOfVehicles.add(1000); numbersOfVehicles.add(1200); numbersOfVehicles.add(1500); numbersOfVehicles.add(2000); numbersOfVehicles.add(2500); numbersOfVehicles.add(3000); numbersOfVehicles.add(4000); numbersOfVehicles.add(5000); numbersOfVehicles.add(10000); int seats = 4; DrtVehicleCreator tvc = new DrtVehicleCreator(networkFile, drtServiceAreaShapeFile, ct); // tvc.setLinkWeightsByActivities(populationFile, facilitiesFile); // tvc.setWeightsToSquareRoot(); for (int numberOfVehicles: numbersOfVehicles) { // tvc.createVehiclesByWeightedDraw(numberOfVehicles, seats, vehiclesFilePrefix); tvc.createVehiclesByRandomPointInShape(numberOfVehicles, seats, vehiclesFilePrefix); } } public DrtVehicleCreator(String networkfile, String drtServiceAreaShapeFile, CoordinateTransformation ct) { this.ct = ct; Config config = ConfigUtils.createConfig(); config.network().setInputFile(networkfile); this.scenario = ScenarioUtils.loadScenario(config); shpUtils = new BerlinShpUtils(drtServiceAreaShapeFile); RunDrtOpenBerlinScenario.addDRTmode(scenario, drtNetworkMode, drtServiceAreaShapeFile, 0); Set<String> modes = new HashSet<>(); modes.add(drtNetworkMode); drtNetwork = NetworkUtils.createNetwork(); Set<String> filterTransportModes = new HashSet<>(); filterTransportModes.add(drtNetworkMode); new TransportModeNetworkFilter(scenario.getNetwork()).filter(drtNetwork, filterTransportModes); new NetworkWriter(drtNetwork).write("drtNetwork.xml.gz"); } public final void createVehiclesByWeightedDraw(int amount, int seats, String vehiclesFilePrefix) { List<DvrpVehicleSpecification> vehicles = new ArrayList<>(); EnumeratedDistribution<Id<Link>> weightedLinkDraw = new EnumeratedDistribution<>(links2weights); for (int i = 0 ; i< amount; i++) { Id<Link> linkId = weightedLinkDraw.sample(); vehicles.add(ImmutableDvrpVehicleSpecification.newBuilder().id(Id.create("drt" + i, DvrpVehicle.class)) .startLinkId(linkId) .capacity(seats) .serviceBeginTime(Math.round(1)) .serviceEndTime(Math.round(30 * 3600)) .build()); } String fileNameBase = vehiclesFilePrefix + amount + "vehicles-" + seats + "seats"; new FleetWriter(vehicles.stream()).write(fileNameBase + ".xml.gz"); writeVehStartPositionsCSV(vehicles, fileNameBase); } private void writeVehStartPositionsCSV(List<DvrpVehicleSpecification> vehicles, String fileNameBase) { Map<Id<Link>, Long> linkId2NrVeh = vehicles.stream(). map(veh -> veh.getStartLinkId()). collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); try { CSVWriter writer = new CSVWriter(Files.newBufferedWriter(Paths.get(fileNameBase + "_startPositions.csv")), ';', '"', '"', "\n"); writer.writeNext(new String[]{"link", "x", "y", "drtVehicles"}, false); linkId2NrVeh.forEach( (linkId, numberVeh) -> { Coord coord = scenario.getNetwork().getLinks().get(linkId).getCoord(); double x = coord.getX(); double y = coord.getY(); writer.writeNext(new String[]{linkId.toString(), "" + x, "" + y, "" + numberVeh}, false); }); writer.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } public final void setLinkWeightsByActivities(String populationFile, String facilitiesFile) { links2weights.clear(); // initial reset if already set before PopulationReader popReader = new PopulationReader(scenario); popReader.readFile(populationFile); //TODO: coord transformations if (facilitiesFile != null && !facilitiesFile.equals("")) { MatsimFacilitiesReader facilitiesReader = new MatsimFacilitiesReader(scenario); facilitiesReader.readFile(facilitiesFile); //TODO: coord transformations } Map<Id<Link>, Long> link2Occurences = scenario.getPopulation().getPersons().values().stream(). map(person -> person.getSelectedPlan()). map(plan -> plan.getPlanElements()). flatMap(planElements -> planElements.stream()). filter(planElement -> planElement instanceof Activity). map(planElement -> (Activity) planElement). filter(activity -> activity.getType().equals(TripStructureUtils.createStageActivityType(TransportMode.pt)) || !StageActivityTypeIdentifier.isStageActivity(activity.getType())). filter(activity -> shpUtils.isCoordInDrtServiceAreaWithBuffer(PopulationUtils.decideOnCoordForActivity(activity, scenario), 2000.0)). map(activity -> getLinkIdOnDrtNetwork(activity)). collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); for (Map.Entry<Id<Link>, Long> entry : link2Occurences.entrySet()) { // check link is in shape file Link link = scenario.getNetwork().getLinks().get(entry.getKey()); if (shpUtils.isCoordInDrtServiceArea(link.getFromNode().getCoord()) && shpUtils.isCoordInDrtServiceArea(link.getToNode().getCoord())) { links2weights.add(new Pair<>(entry.getKey(), entry.getValue().doubleValue())); } // else forget that link because it's not usable for drt } } private Id<Link> getLinkIdOnDrtNetwork(Activity activity) { Id<Link> linkId = PopulationUtils.decideOnLinkIdForActivity(activity, scenario); if (!drtNetwork.getLinks().containsKey(linkId)) { linkId = NetworkUtils.getNearestLink(drtNetwork, PopulationUtils.decideOnCoordForActivity(activity, scenario)).getId(); } return linkId; } /** * Overwrites weights with the square root of the previous weight. Shifts some vehicles to otherwise empty areas. */ public final void setWeightsToSquareRoot() { links2weights = links2weights.stream().map(pair -> new Pair<>(pair.getFirst(), Math.sqrt(pair.getSecond()))).collect(Collectors.toList()); } public final void createVehiclesByRandomPointInShape(int amount, int seats, String vehiclesFilePrefix) { List<DvrpVehicleSpecification> vehicles = new ArrayList<>(); for (int i = 0 ; i< amount; i++) { Link link = null; while (link == null) { Point p = shpUtils.getRandomPointInServiceArea(random); link = NetworkUtils.getNearestLinkExactly(drtNetwork, ct.transform( MGC.point2Coord(p))); if (shpUtils.isCoordInDrtServiceArea(link.getFromNode().getCoord()) && shpUtils.isCoordInDrtServiceArea(link.getToNode().getCoord())) { if (link.getAllowedModes().contains(drtNetworkMode)) { // ok } else { link = null; } // ok, the link is within the shape file } else { link = null; } } if (i%100 == 0) log.info("#"+i); vehicles.add(ImmutableDvrpVehicleSpecification.newBuilder().id(Id.create("drt" + i, DvrpVehicle.class)) .startLinkId(link.getId()) .capacity(seats) .serviceBeginTime(Math.round(1)) .serviceEndTime(Math.round(30 * 3600)) .build()); } String fileNameBase = vehiclesFilePrefix + amount + "vehicles-" + seats + "seats"; new FleetWriter(vehicles.stream()).write(fileNameBase + ".xml.gz"); writeVehStartPositionsCSV(vehicles, fileNameBase); } }
12,028
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
package-info.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/cadyts/package-info.java
/** * The cemdap stuff is under {@link playground.vsp.openberlinscenario.cemdap}. Since the plan is to replace it by the Actitopp approach, we leave it there. * kai/ihab, mat'20 */ package org.matsim.legacy.prepare.cadyts;
227
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
NetworkFileModifier.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/bicycle/NetworkFileModifier.java
package org.matsim.legacy.prepare.bicycle; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.bicycle.BicycleUtils; import org.matsim.core.api.internal.MatsimWriter; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.network.io.NetworkWriter; import org.matsim.core.scenario.ScenarioUtils; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class NetworkFileModifier { public static void main(String[] args) { String inputNetworkFile = "../../public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-network.xml.gz"; String outputNetworkFile = "../../public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-network-with-bicycles.xml.gz"; String BICYCLE = "bicycle"; Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); MatsimNetworkReader networkReader = new MatsimNetworkReader(scenario.getNetwork()); networkReader.readFile(inputNetworkFile); // Add bicycles to all link which can be traversed by cars for (Link link : scenario.getNetwork().getLinks().values()) { if (link.getAllowedModes().contains(TransportMode.car)) { Set<String> updatedAllowedModes = new HashSet<>(link.getAllowedModes()); updatedAllowedModes.add(BICYCLE); link.setAllowedModes(updatedAllowedModes); } } // Add bicycle infrastructure speed factor for all links scenario.getNetwork().getLinks().values().parallelStream() .filter(link -> link.getAllowedModes().contains(BICYCLE)) .forEach(link -> link.getAttributes().putAttribute(BicycleUtils.BICYCLE_INFRASTRUCTURE_SPEED_FACTOR, 1.0)); NetworkWriter networkWriter = new NetworkWriter(scenario.getNetwork()); networkWriter.write(outputNetworkFile); } }
2,091
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PlanFileModifier.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/bicycle/PlanFileModifier.java
package org.matsim.legacy.prepare.bicycle; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.io.PopulationReader; import org.matsim.core.scenario.ScenarioUtils; public class PlanFileModifier { public static void main(String[] args) { String inputPlansFile = "../../public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-10pct.plans_uncalibrated.xml.gz"; String outputPlansFile = "../../public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-10pct.plans-no-bicycle-routes.xml.gz"; Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); PopulationReader populationReader = new PopulationReader(scenario); populationReader.readFile(inputPlansFile); // Delete routes for bicycling agents scenario.getPopulation().getPersons().values().parallelStream() .flatMap(person -> person.getPlans().stream()) .flatMap(plan -> plan.getPlanElements().stream()) .filter(element -> element instanceof Leg) .map(element -> (Leg) element) .filter(leg -> leg.getMode().equals("bicycle")) .forEach(leg -> leg.setRoute(null)); PopulationWriter populationWriter = new PopulationWriter(scenario.getPopulation()); populationWriter.write(outputPlansFile); } }
1,571
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CorineForCemdapPlans.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/CorineForCemdapPlans.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; import java.util.HashMap; import java.util.Map; import playground.vsp.corineLandcover.CORINELandCoverCoordsModifier; /** * @author ikaddoura */ public class CorineForCemdapPlans { public static void main(String[] args) { String corineLandCoverFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/input/shapefiles/corine_landcover/corine_lancover_berlin-brandenburg_GK4.shp"; String zoneFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/input/shapefiles/2013/gemeindenLOR_DHDN_GK4.shp"; String zoneIdTag = "NR"; String matsimPlans = "../../shared-svn/studies/countries/de/open_berlin_scenario/berlin_4.0/population/pop_300ik1/plans_10pct.xml.gz"; String outPlans = "../../shared-svn/studies/countries/de/open_berlin_scenario/berlin_4.0/population/pop_300ik1/plans_10pct_corine-landcover.xml.gz"; boolean simplifyGeom = false; boolean combiningGeoms = false; boolean sameHomeActivity = true; String homeActivityPrefix = "home"; Map<String, String> shapeFileToFeatureKey = new HashMap<>(); shapeFileToFeatureKey.put(zoneFile, zoneIdTag); CORINELandCoverCoordsModifier plansFilterForCORINELandCover = new CORINELandCoverCoordsModifier(matsimPlans, shapeFileToFeatureKey, corineLandCoverFile, simplifyGeom, combiningGeoms, sameHomeActivity, homeActivityPrefix); plansFilterForCORINELandCover.process(); plansFilterForCORINELandCover.writePlans(outPlans); } }
2,928
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
SplitActivityTypesBasedOnDuration.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/SplitActivityTypesBasedOnDuration.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.ConfigWriter; import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.config.groups.ScoringConfigGroup.TypicalDurationScoreComputation; import org.matsim.core.population.io.PopulationWriter; import org.matsim.core.scenario.ScenarioUtils; import playground.vsp.openberlinscenario.cemdap.output.ActivityTypes; import playground.vsp.openberlinscenario.planmodification.CemdapPopulationTools; /** * @author ikaddoura */ public class SplitActivityTypesBasedOnDuration { private final Logger log = LogManager.getLogger(SplitActivityTypesBasedOnDuration.class); private Scenario scenario; public SplitActivityTypesBasedOnDuration(String inputPopulationFile) { Config config = ConfigUtils.createConfig(); config.plans().setInputFile(inputPopulationFile); this.scenario = ScenarioUtils.loadScenario(config); } public static void main(String[] args) { final String inputPopulationFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10-1_10pct_clc.xml.gz"; final String outputPopulationFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10-1_10pct_clc_act-split.xml.gz"; final String outputConfigFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/config_act-split.xml"; final double timeBinSize_s = 600.; final String[] activityTypes = {ActivityTypes.HOME, ActivityTypes.WORK, ActivityTypes.EDUCATION, ActivityTypes.LEISURE, ActivityTypes.SHOPPING, ActivityTypes.OTHER}; SplitActivityTypesBasedOnDuration splitAct = new SplitActivityTypesBasedOnDuration(inputPopulationFile); splitAct.run(outputPopulationFile, outputConfigFile, timeBinSize_s, activityTypes, 0.0); } public void run(String outputPopulationFile, String outputConfigFile, double timeBinSize_s, String[] activities, double dayStartTime) { CemdapPopulationTools tools = new CemdapPopulationTools(); tools.setActivityTypesAccordingToDurationAndMergeOvernightActivities(scenario.getPopulation(), timeBinSize_s, dayStartTime); PopulationWriter writer = new PopulationWriter(scenario.getPopulation()); writer.write(outputPopulationFile); // Config List<ActivityParams> initialActivityParams = new ArrayList<>(); log.info("Initial activity parameters: "); for (String activity : activities) { ActivityParams params = new ActivityParams(activity); initialActivityParams.add(params); log.info(" -> " + params.getActivityType()); } log.info("Adding duration-specific activity types to config..."); List<ActivityParams> newActivityParams = new ArrayList<>(); for (ActivityParams actParams : initialActivityParams) { String activityType = actParams.getActivityType(); if (activityType.contains("interaction")) { log.info("Skipping activity " + activityType + "..."); } else { log.info("Splitting activity " + activityType + " in duration-specific activities."); double maximumDuration = tools.getMaxEndTime(); for (double n = timeBinSize_s; n <= maximumDuration ; n = n + timeBinSize_s) { ActivityParams params = new ActivityParams(activityType + "_" + n); params.setTypicalDuration(n); params.setTypicalDurationScoreComputation(TypicalDurationScoreComputation.relative); newActivityParams.add(params); } } } for (ActivityParams actParams : newActivityParams) { scenario.getConfig().scoring().addActivityParams(actParams); } log.info("New activity parameters: "); for (ActivityParams actParams : scenario.getConfig().scoring().getActivityParams()) { initialActivityParams.add(actParams); log.info(" -> " + actParams.getActivityType()); } log.info("Adding duration-specific activity types to config... Done."); ConfigWriter configWriter = new ConfigWriter(scenario.getConfig()); configWriter.write(outputConfigFile); } }
5,608
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
FilterSelectedPlans.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/FilterSelectedPlans.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2015 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; 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.population.*; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.algorithms.TripsToLegsAlgorithm; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scenario.ScenarioUtils; /** * @author ikaddoura */ public class FilterSelectedPlans { private static final Logger log = LogManager.getLogger(FilterSelectedPlans.class); private final static String inputPlans = "D:/svn/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/base_b18_pt03_c1_mgn0.6.output_plans.xml.gz";//"..."; private final static String outputPlans = "D:/svn/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-10pct.plans.xml.gz";//"..."; private final static boolean deleteRoutes = false; public static void main(String[] args) { FilterSelectedPlans filter = new FilterSelectedPlans(); filter.run(inputPlans, outputPlans, deleteRoutes); } public void run (final String inputPlans, final String outputPlans, final boolean deleteRoutes) { Config config = ConfigUtils.createConfig(); config.global().setCoordinateSystem("EPSG:31468"); config.plans().setInputFile(inputPlans); config.plans().setInputCRS("EPSG:31468"); Scenario scInput = ScenarioUtils.loadScenario(config); Scenario scOutput = ScenarioUtils.createScenario(ConfigUtils.createConfig()); Population popOutput = scOutput.getPopulation(); popOutput.getAttributes().putAttribute("coordinateReferenceSystem", "EPSG:31468"); TripsToLegsAlgorithm trips2Legs = new TripsToLegsAlgorithm(TripStructureUtils.getRoutingModeIdentifier()); for (Person p : scInput.getPopulation().getPersons().values()){ Person personNew = popOutput.getFactory().createPerson(p.getId()); for (String attribute : p.getAttributes().getAsMap().keySet()) { personNew.getAttributes().putAttribute(attribute, p.getAttributes().getAttribute(attribute)); } Plan selectedPlan = p.getSelectedPlan(); if (deleteRoutes) { trips2Legs.run(selectedPlan); } personNew.addPlan(selectedPlan); popOutput.addPerson(personNew); } log.info("Writing population..."); new PopulationWriter(scOutput.getPopulation()).write(outputPlans); log.info("Writing population... Done."); } }
3,817
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
FilterSelectedPlansWithDrtMode.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/FilterSelectedPlansWithDrtMode.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2015 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; 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.TransportMode; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; /** * @author ikaddoura */ public class FilterSelectedPlansWithDrtMode { private static final Logger log = LogManager.getLogger(FilterSelectedPlansWithDrtMode.class); private final static String inputPlans = "..."; private final static String outputPlans = "..."; public static void main(String[] args) { FilterSelectedPlansWithDrtMode filter = new FilterSelectedPlansWithDrtMode(); filter.run(inputPlans, outputPlans); } public void run (final String inputPlans, final String outputPlans) { Config config = ConfigUtils.createConfig(); config.global().setCoordinateSystem("EPSG:31468"); config.plans().setInputFile(inputPlans); config.plans().setInputCRS("EPSG:31468"); Scenario scInput = ScenarioUtils.loadScenario(config); Scenario scOutput = ScenarioUtils.createScenario(ConfigUtils.createConfig()); Population popOutput = scOutput.getPopulation(); popOutput.getAttributes().putAttribute("coordinateReferenceSystem", "EPSG:31468"); for (Person p : scInput.getPopulation().getPersons().values()){ if (p.getSelectedPlan().getPlanElements().stream(). filter(pe -> pe instanceof Leg). map(l -> ((Leg) l).getMode()). anyMatch(mode -> mode.equals(TransportMode.drt))) { Person personNew = popOutput.getFactory().createPerson(p.getId()); for (String attribute : p.getAttributes().getAsMap().keySet()) { personNew.getAttributes().putAttribute(attribute, p.getAttributes().getAttribute(attribute)); } personNew.addPlan(p.getSelectedPlan()); popOutput.addPerson(personNew); } } log.info("Writing population..."); new PopulationWriter(scOutput.getPopulation()).write(outputPlans); log.info("Writing population... Done."); } }
3,610
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RemovePtRoutes.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/RemovePtRoutes.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; import java.util.List; 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.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.gbl.Gbl; import org.matsim.core.population.PopulationUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.router.TripStructureUtils.Trip; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.legacy.run.drt.OpenBerlinIntermodalPtDrtRouterModeIdentifier; /** * * Not ready for intermodal trips * * @author gleich * */ public class RemovePtRoutes { private final static Logger log = LogManager.getLogger(RemovePtRoutes.class); public static void main(String[] args) { Config config = ConfigUtils.createConfig(); config.global().setCoordinateSystem("EPSG:31468"); config.network().setInputFile("https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-network.xml.gz"); config.plans().setInputFile("https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-10pct.plans.xml.gz"); Scenario scenario = ScenarioUtils.loadScenario(config); for (Person person: scenario.getPopulation().getPersons().values()) { for (Plan plan: person.getPlans()) { // new TransitActsRemover().run(plan); // converts pt trips to a single non_network_walk leg :-( // TripsToLegsAlgorithm affects not only pt trips, but all trips, so not useable yet here, // new TripsToLegsAlgorithm(new StageActivityTypesImpl(), new MainModeIdentifierImpl()).run(plan); // use adapted copy of TripsToLegsAlgorithm.run() to restrict to pt trips run(plan); // check if there are references to the old now replaced pseudo pt network for (PlanElement pe : plan.getPlanElements()){ if (pe instanceof Leg){ Leg leg = (Leg) pe; if (leg.getRoute() != null) { if (leg.getRoute().getStartLinkId().toString().startsWith("pt_") || leg.getRoute().getEndLinkId().toString().startsWith("pt_")) { log.error("agent " + person.getId() + " still has route starting or ending at a link of the pt network after removing pt routes: " + leg.getRoute().getStartLinkId().toString() + " / " + leg.getRoute().getEndLinkId().toString()); log.error("full plan: " + plan); } Gbl.assertIf(!leg.getRoute().getStartLinkId().toString().startsWith("pt_")); Gbl.assertIf(!leg.getRoute().getEndLinkId().toString().startsWith("pt_")); if (leg.getRoute() instanceof NetworkRoute) { NetworkRoute networkRoute = (NetworkRoute) leg.getRoute(); for (Id<Link> linkId: networkRoute.getLinkIds()) { Gbl.assertIf(!linkId.toString().startsWith("pt_")); } } } } else if (pe instanceof Activity){ Activity act = (Activity) pe; if (act.getLinkId() != null) { Gbl.assertIf(!act.getLinkId().toString().startsWith("pt_")); } } } } } PopulationWriter popWriter = new PopulationWriter(scenario.getPopulation()); popWriter.write("berlin-v5.5-10pct.plans_wo_PtRoutes.xml.gz"); } private static void run(final Plan plan) { final List<PlanElement> planElements = plan.getPlanElements(); final List<Trip> trips = TripStructureUtils.getTrips( plan ); for ( Trip trip : trips ) { final List<PlanElement> fullTrip = planElements.subList( planElements.indexOf( trip.getOriginActivity() ) + 1, planElements.indexOf( trip.getDestinationActivity() )); final String mode = (new OpenBerlinIntermodalPtDrtRouterModeIdentifier()).identifyMainMode( fullTrip ); if (mode.equals(TransportMode.pt)) { fullTrip.clear(); fullTrip.add( PopulationUtils.createLeg(mode) ); if ( fullTrip.size() != 1 ) throw new RuntimeException( fullTrip.toString() ); } } } }
5,830
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CorineForFreightAgents.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/CorineForFreightAgents.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; import java.util.HashMap; import java.util.Map; import playground.vsp.corineLandcover.CORINELandCoverCoordsModifier; /** * @author ikaddoura */ public class CorineForFreightAgents { public static void main(String[] args) { String corineLandCoverFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/input/shapefiles/corine_landcover_berlin-brandenburg/corine_lancover_berlin-brandenburg_GK4.shp"; String zoneFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/input/shapefiles/2013/Berlin_DHDN_GK4.shp"; String zoneIdTag = "NR"; String matsimPlans = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_3/population/freight/freight-agents-berlin4.1_sampleSize0.1.xml.gz"; String outPlans = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_3/population/freight/freight-agents-berlin4.1_sampleSize0.1_corine-landcover_1.xml.gz"; boolean simplifyGeom = false; boolean combiningGeoms = false; boolean sameHomeActivity = false; String homeActivityPrefix = "home"; Map<String, String> shapeFileToFeatureKey = new HashMap<>(); shapeFileToFeatureKey.put(zoneFile, zoneIdTag); CORINELandCoverCoordsModifier plansFilterForCORINELandCover = new CORINELandCoverCoordsModifier(matsimPlans, shapeFileToFeatureKey, corineLandCoverFile, simplifyGeom, combiningGeoms, sameHomeActivity, homeActivityPrefix); plansFilterForCORINELandCover.process(); plansFilterForCORINELandCover.writePlans(outPlans); } }
2,986
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
MergePlans.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/MergePlans.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; 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.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.population.io.PopulationWriter; import org.matsim.core.scenario.ScenarioUtils; /** * @author ikaddoura */ public class MergePlans { public static void main(String[] args) { // subpopulation: persons final String inputFile1 = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10-1_10pct_clc_act-split_duration7200.xml.gz"; // subpopulation: freight final String inputFile2 = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_3/population/freight/freight-agents-berlin4.1_sampleSize0.1_corine-landcover.xml.gz"; final String populationOutputFileName = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10pct.xml.gz"; Config config1 = ConfigUtils.createConfig(); config1.plans().setInputFile(inputFile1); Scenario scenario1 = ScenarioUtils.loadScenario(config1); Config config2 = ConfigUtils.createConfig(); config2.plans().setInputFile(inputFile2); Scenario scenario2 = ScenarioUtils.loadScenario(config2); Scenario scenario3 = ScenarioUtils.createScenario(ConfigUtils.createConfig()); Population population = scenario3.getPopulation(); for (Person person: scenario1.getPopulation().getPersons().values()) { population.addPerson(person); population.getPersons().get(person.getId()).getAttributes().putAttribute(scenario3.getConfig().plans().getSubpopulationAttributeName(), "person"); } for (Person person : scenario2.getPopulation().getPersons().values()) { population.addPerson(person); population.getPersons().get(person.getId()).getAttributes().putAttribute(scenario3.getConfig().plans().getSubpopulationAttributeName(), "freight"); } PopulationWriter writer = new PopulationWriter(population); writer.write(populationOutputFileName); } }
3,424
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
UseDurationInsteadOfEndTime.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/UseDurationInsteadOfEndTime.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2015 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; 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.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; /** * @author ikaddoura */ public class UseDurationInsteadOfEndTime { private static final Logger log = LogManager.getLogger(UseDurationInsteadOfEndTime.class); private final static String inputPlans = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10-1_10pct_clc_act-split.xml.gz"; private final static String outputPlans = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10-1_10pct_clc_act-split_duration7200.xml.gz"; private static final String[] attributes = {}; private final double durationThreshold = 7200.; public static void main(String[] args) { UseDurationInsteadOfEndTime filter = new UseDurationInsteadOfEndTime(); filter.run(inputPlans, outputPlans, attributes); } public void run (final String inputPlans, final String outputPlans, final String[] attributes) { log.info("Accounting for the following attributes:"); for (String attribute : attributes) { log.info(attribute); } log.info("Other person attributes will not appear in the output plans file."); Scenario scOutput; Config config = ConfigUtils.createConfig(); config.plans().setInputFile(inputPlans); Scenario scInput = ScenarioUtils.loadScenario(config); scOutput = ScenarioUtils.createScenario(ConfigUtils.createConfig()); Population popOutput = scOutput.getPopulation(); for (Person p : scInput.getPopulation().getPersons().values()){ PopulationFactory factory = popOutput.getFactory(); Person personNew = factory.createPerson(p.getId()); for (String attribute : attributes) { personNew.getAttributes().putAttribute(attribute, p.getAttributes().getAttribute(attribute)); } popOutput.addPerson(personNew); for (Plan plan : p.getPlans()) { for (PlanElement pE : plan.getPlanElements()) { if (pE instanceof Activity) { Activity act = (Activity) pE; if (act.getEndTime().seconds() > 0. && act.getEndTime().seconds() <= 30 * 3600.) { if (act.getAttributes().getAttribute("cemdapStopDuration_s") != null) { int cemdapDuration = (int) act.getAttributes().getAttribute("cemdapStopDuration_s"); if (cemdapDuration <= durationThreshold) { // log.info("end time: " + act.getEndTime() + " --> " + Double.NEGATIVE_INFINITY); act.setEndTime(Double.NEGATIVE_INFINITY); // log.info("duration: " + act.getMaximumDuration() + " --> " + cemdapDuration); act.setMaximumDuration(cemdapDuration); } } } else { // don't do anything } } } personNew.addPlan(plan); } } log.info("Writing population..."); new PopulationWriter(scOutput.getPopulation()).write(outputPlans); log.info("Writing population... Done."); } }
4,786
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateFreightAgents.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/CreateFreightAgents.java
/* *********************************************************************** * * project: org.matsim.* * * * * *********************************************************************** * * * * copyright : (C) 2018 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; import java.io.IOException; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.api.core.v01.population.PopulationFactory; import org.matsim.api.core.v01.population.PopulationWriter; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.ShapeFileReader; import org.opengis.feature.simple.SimpleFeature; /** * * @author ikaddoura * */ public class CreateFreightAgents { private static final Logger log = LogManager.getLogger(CreateFreightAgents.class); private int personCounter = 0; private final Map<String, SimpleFeature> features = new HashMap<>(); private final Scenario scenario; private final Map<Id<Link>, Integer> linkId2dailyFreightTrafficVolumeToBerlin = new HashMap<>(); private final Map<Id<Link>, Integer> linkId2dailyFreightTrafficVolumeFromBerlin = new HashMap<>(); private final String freightActivityType = "freight"; public static void main(String [] args) throws IOException, ParseException { final String networkFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_3/network/network_300.xml.gz"; final String inputFileSHP = "../../shared-svn/studies/ihab/berlin/shapeFiles/berlin_area/Berlin.shp"; final String outputFilePopulation = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_3/population/freight/freight-agents-berlin4.1_sampleSize0.1.xml.gz"; final double sampleSize = 0.1; CreateFreightAgents popGenerator = new CreateFreightAgents(networkFile, inputFileSHP); popGenerator.run(sampleSize, outputFilePopulation); } public CreateFreightAgents(String networkFile, String inputFileSHP) throws IOException { // 2064 B1 Mahlsdorf linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("44729"), (int) (1916/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("44732"), (int) (1916/2.)); // 3625 B158 Ahrensfelde linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("37354"), (int) (1279/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("37355"), (int) (1279/2.)); // 2065 B2 Malchow linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("87998"), (int) (1045/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("87997"), (int) (1045/2.)); // 2011 A114 Buchholz linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("47076"), (int) (1762/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("31062"), (int) (1762/2.)); // 2063 B96a Blankenfelde linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("27534"), (int) (401/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("27533"), (int) (401/2.)); // 2010 A111 Heiligensee 2 linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("100059"), (int) (4329/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("143046"), (int) (4329/2.)); // 2062 B5 Staaken linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("13245"), (int) (1986/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("98267"), (int) (1986/2.)); // 2061 B1 Nikolassee linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("144245"), (int) (805/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("144244"), (int) (805/2.)); // 3615 A115 Drewitz linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("57921"), (int) (5135/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("130736"), (int) (5135/2.)); // 2066 B101 Marienfelde linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("89980"), (int) (2409/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("119310"), (int) (2409/2.)); // 3720 B96 Dahlewitz 2 linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("119942"), (int) (1143/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("142698"), (int) (1143/2.)); // 2013 A113 Schönefeld linkId2dailyFreightTrafficVolumeToBerlin.put(Id.createLinkId("87464"), (int) (5203/2.)); linkId2dailyFreightTrafficVolumeFromBerlin.put(Id.createLinkId("105681"), (int) (5203/2.)); Config config = ConfigUtils.createConfig(); config.network().setInputFile(networkFile); scenario = ScenarioUtils.loadScenario(config); log.info("Reading shp file..."); SimpleFeatureSource fts = ShapeFileReader.readDataFile(inputFileSHP); SimpleFeatureIterator it = fts.getFeatures().features(); while (it.hasNext()) { SimpleFeature ft = it.next(); features.put("berlin", ft); } it.close(); log.info("Reading shp file... Done."); } private void run(double sampleSize, String outputFilePopulation) throws ParseException, IOException { Random rnd = new Random(); for (Id<Link> linkId : linkId2dailyFreightTrafficVolumeToBerlin.keySet()) { createFreightBerlinZielverkehr(scenario, rnd, linkId, linkId2dailyFreightTrafficVolumeToBerlin.get(linkId) * sampleSize); } for (Id<Link> linkId : linkId2dailyFreightTrafficVolumeFromBerlin.keySet()) { createFreightBerlinQuellverkehr(scenario, rnd, linkId, linkId2dailyFreightTrafficVolumeFromBerlin.get(linkId) * sampleSize); } new PopulationWriter(scenario.getPopulation(), scenario.getNetwork()).write(outputFilePopulation); log.info("population written to: " + outputFilePopulation); log.info("Population contains " + personCounter +" agents."); } private void createFreightBerlinQuellverkehr(Scenario scenario, Random rnd, Id<Link> linkId, double odSum) { Population population = scenario.getPopulation(); PopulationFactory popFactory = population.getFactory(); for (int i = 0; i <= odSum; i++) { Person pers = popFactory.createPerson(Id.create("freight_" + personCounter + "_berlin" + "-" + linkId.toString(), Person.class)); Plan plan = popFactory.createPlan(); Point startP = getRandomPointInFeature(rnd, features.get("berlin")); if ( startP==null ) log.warn("Point is null."); Activity startActivity = popFactory.createActivityFromCoord(this.freightActivityType, MGC.point2Coord(startP) ) ; double startTime = calculateNormallyDistributedTime(12 * 3600, 6 * 3600.); // approx. 2/3 between 6.00 and 18.00 startActivity.setEndTime(startTime); plan.addActivity(startActivity); Leg leg1 = popFactory.createLeg("freight"); plan.addLeg(leg1); Activity endActivity = popFactory.createActivityFromCoord(this.freightActivityType, scenario.getNetwork().getLinks().get(linkId).getToNode().getCoord()); plan.addActivity(endActivity); pers.addPlan(plan) ; population.addPerson(pers) ; scenario.getPopulation().getPersons().get(pers.getId()).getAttributes().putAttribute(scenario.getConfig().plans().getSubpopulationAttributeName(), "freight"); personCounter++; } } private void createFreightBerlinZielverkehr(Scenario scenario, Random rnd, Id<Link> linkId, double odSum) { Population population = scenario.getPopulation(); PopulationFactory popFactory = population.getFactory(); for (int i = 0; i <= odSum; i++) { Person pers = popFactory.createPerson(Id.create("freight_" + personCounter + "_" + linkId.toString() + "-" + "berlin", Person.class)); Plan plan = popFactory.createPlan(); Activity startActivity = popFactory.createActivityFromCoord(this.freightActivityType, scenario.getNetwork().getLinks().get(linkId).getFromNode().getCoord()); double startTime = calculateNormallyDistributedTime(10 * 3600., 4 * 3600.); // approx. 2/3 between 6.00 and 14.00 startActivity.setEndTime(startTime); plan.addActivity(startActivity); Leg leg1 = popFactory.createLeg("freight"); plan.addLeg(leg1); Point endPoint = getRandomPointInFeature(rnd, features.get("berlin")); if ( endPoint==null ) log.warn("Point is null."); Activity endActivity = popFactory.createActivityFromCoord(this.freightActivityType, MGC.point2Coord(endPoint) ) ; plan.addActivity(endActivity); pers.addPlan(plan) ; population.addPerson(pers) ; scenario.getPopulation().getPersons().get(pers.getId()).getAttributes().putAttribute(scenario.getConfig().plans().getSubpopulationAttributeName(), "freight"); personCounter++; } } private double calculateRandomlyDistributedValue(Random rnd, double i, double abweichung){ double rnd1 = rnd.nextDouble(); double rnd2 = rnd.nextDouble(); double vorzeichen = 0; if (rnd1<=0.5){ vorzeichen = -1.0; } else { vorzeichen = 1.0; } double endTimeInSec = (i + (rnd2 * abweichung * vorzeichen)); return endTimeInSec; } private double calculateNormallyDistributedTime(double mean, double stdDev) { Random random = new Random(); boolean leaveLoop = false; double endTimeInSec = Double.MIN_VALUE; while(leaveLoop == false) { double normal = random.nextGaussian(); endTimeInSec = mean + stdDev * normal; if (endTimeInSec >= 0. && endTimeInSec <= 24. * 3600.) { leaveLoop = true; } } if (endTimeInSec < 0. || endTimeInSec > 24. * 3600) { throw new RuntimeException("Shouldn't happen. Aborting..."); } return endTimeInSec; } private static Point getRandomPointInFeature(Random rnd, SimpleFeature ft) { // TODO: account for intra-zonal land use areas, e.g. CORINE Landuse data if ( ft!=null ) { Point p = null; double x, y; do { x = ft.getBounds().getMinX() + rnd.nextDouble() * (ft.getBounds().getMaxX() - ft.getBounds().getMinX()); y = ft.getBounds().getMinY() + rnd.nextDouble() * (ft.getBounds().getMaxY() - ft.getBounds().getMinY()); p = MGC.xy2Point(x, y); } while ( !((Geometry) ft.getDefaultGeometry()).contains(p)); return p; } else { return null ; } } }
11,921
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
ReducePopulation.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/ReducePopulation.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; import java.util.Iterator; import java.util.Random; 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.population.PopulationWriter; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; /** * * @author gleich * */ public class ReducePopulation { private final static Logger log = LogManager.getLogger(ReducePopulation.class); public static void main(String[] args) { Config config = ConfigUtils.createConfig(); config.global().setCoordinateSystem("DHDN_GK4"); config.network().setInputFile("https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.4-10pct/input/berlin-v5-network.xml.gz"); config.plans().setInputFile("/home/gregor/Downloads/berlin-drt-v5.5-1pct_drt-119.output_plans.xml.gz"); double factor = 0.1; Scenario scenario = ScenarioUtils.loadScenario(config); reducePopulation(scenario, factor); PopulationWriter popWriter = new PopulationWriter(scenario.getPopulation()); popWriter.write("/home/gregor/Downloads/berlin-drt-v5.5-1pct_drt-119_0.1.output_plans.xml.gz"); } static void reducePopulation( Scenario scenario, double factor ) { log.info("Reducing population by a factor of " + factor); // reduce to some sample in order to increase turnaround during debugging: Random random = new Random(4711) ; Iterator<?> it = scenario.getPopulation().getPersons().entrySet().iterator() ; while( it.hasNext() ) { it.next() ; if ( random.nextDouble() < (1-factor) ) { it.remove(); } } } }
3,053
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
WriteHomeAreaToPersonAttributesFile.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/population/WriteHomeAreaToPersonAttributesFile.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.population; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Person; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.geotools.MGC; import org.matsim.core.utils.gis.ShapeFileReader; import org.opengis.feature.simple.SimpleFeature; /** * @author ikaddoura */ public class WriteHomeAreaToPersonAttributesFile { private static final Logger log = LogManager.getLogger(WriteHomeAreaToPersonAttributesFile.class); public static void main(String[] args) { // subpopulation: persons final String inputPlansFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/plans_500_10pct.xml.gz"; final String inputPersonAttributesFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/be_5/population/personAttributes_500_10pct.xml.gz"; final String zoneFile = "../../shared-svn/studies/countries/de/open_berlin_scenario/input/shapefiles/2013/Berlin_DHDN_GK4.shp"; // needs to be in the same CRS final String homeZoneAttributeInside = "berlin"; final String homeZoneAttributeOutside = "brandenburg"; final String homeActivityPrefix = "home"; Config config = ConfigUtils.createConfig(); config.plans().setInputFile(inputPlansFile); Scenario scenario = ScenarioUtils.loadScenario(config); log.info("Reading shape file..."); final Map<String, Geometry> zoneFeatures = new HashMap<>(); if (zoneFile != null) { Collection<SimpleFeature> features = ShapeFileReader.getAllFeatures(zoneFile); int counter = 0; for (SimpleFeature feature : features) { Geometry geometry = (Geometry) feature.getDefaultGeometry(); zoneFeatures.put(String.valueOf(counter), geometry); counter++; } } log.info("Reading shape file... Done."); log.info("Getting persons' home coordinates..."); final Map<Id<Person>, Coord> personId2homeCoord = new HashMap<>(); if (zoneFile != null) { for (Person person : scenario.getPopulation().getPersons().values()) { Activity act = (Activity) person.getSelectedPlan().getPlanElements().get(0); if (act.getType().startsWith(homeActivityPrefix)) { personId2homeCoord.put(person.getId(), act.getCoord()); } } if (personId2homeCoord.isEmpty()) log.warn("No person with home activity."); } log.info("Getting persons' home coordinates... Done."); int counter = 0; for (Person person : scenario.getPopulation().getPersons().values()) { if (counter%10000 == 0) { log.info("Person #" + counter); } if (personId2homeCoord.get(person.getId()) != null) { if (isInsideArea(zoneFeatures, personId2homeCoord.get(person.getId()))) { scenario.getPopulation().getPersons().get(person.getId()).getAttributes().putAttribute("home-activity-zone", homeZoneAttributeInside); } else { scenario.getPopulation().getPersons().get(person.getId()).getAttributes().putAttribute("home-activity-zone", homeZoneAttributeOutside); } } counter++; } log.info("Done."); } private static boolean isInsideArea(Map<String, Geometry> zoneFeatures, Coord coord) { // assuming the same CRS! for (Geometry geometry : zoneFeatures.values()) { Point point = MGC.coord2Point(coord); if (point.within(geometry)) { return true; } } return false; } }
5,157
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
WriteBVWPAccidentRoadTypesIntoLinkAttributes.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/accidents/WriteBVWPAccidentRoadTypesIntoLinkAttributes.java
package org.matsim.legacy.prepare.accidents; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.Scenario; import org.matsim.contrib.accidents.AccidentsConfigGroup; import org.matsim.contrib.accidents.runExample.AccidentsNetworkModification; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.network.NetworkUtils; import org.matsim.legacy.run.RunBerlinScenario; public class WriteBVWPAccidentRoadTypesIntoLinkAttributes { private static final Logger log = LogManager.getLogger(WriteBVWPAccidentRoadTypesIntoLinkAttributes.class); public static void main(String[] args) throws IOException { for (String arg : args) { log.info( arg ); } if ( args.length==0 ) { args = new String[] {"scenarios/berlin-v5.5-1pct/input/berlin-v5.5-1pct.config.xml"} ; } String outputFile = "./scenarios/input/berlin-v5.5-network-with-bvwp-accidents-attributes.xml.gz"; String landOSMInputShapeFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/original-data/osmBerlin/gis.osm_landuse_a_free_1_GK4.shp"; String tunnelLinkCSVInputFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.1.tunnel-linkIDs.csv"; //the CSV has also a column for the percentage of the links wich is tunnel, The new String is produced by a new class String planfreeLinkCSVInputFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5.planfree-linkIDs.csv"; //The Ids of links the between the two versions have change. Because of that the equivalent in the new network for the plan free links Config config = RunBerlinScenario.prepareConfig(args); AccidentsConfigGroup accidentsSettings = ConfigUtils.addOrGetModule(config, AccidentsConfigGroup.class); Scenario scenario = RunBerlinScenario.prepareScenario(config); AccidentsNetworkModification accidentsNetworkModification = new AccidentsNetworkModification(scenario); NetworkUtils.writeNetwork(accidentsNetworkModification.setLinkAttributsBasedOnOSMFile( landOSMInputShapeFile, "EPSG:31468", readColumn(0,tunnelLinkCSVInputFile,";"), readColumn(0,planfreeLinkCSVInputFile, ";") ), outputFile); } public static String[] readColumn(int numCol, String csvFile, String separator) throws IOException { StringBuilder sb = new StringBuilder(); String line; URL url = new URL(csvFile); BufferedReader br = new BufferedReader( new InputStreamReader(url.openStream())); // read line by line try { while ((line = br.readLine()) != null) { String value = "ERROR"; String list[] = line.split(separator); if(numCol<list.length) { value = list[numCol]; } sb.append(value).append(separator); } } catch (IOException e) { e.printStackTrace(); } return sb.toString().split(separator); } }
3,154
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunGTFS2MATSimOpenBerlin.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/transit/schedule/RunGTFS2MATSimOpenBerlin.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ /** * */ package org.matsim.legacy.prepare.transit.schedule; import java.io.File; import java.time.LocalDate; import java.util.List; 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.network.Link; import org.matsim.api.core.v01.network.Network; import org.matsim.api.core.v01.network.Node; import org.matsim.contrib.gtfs.RunGTFS2MATSim; import org.matsim.contrib.gtfs.TransitSchedulePostProcessTools; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.NetworkConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.network.filter.NetworkFilterManager; import org.matsim.core.network.filter.NetworkLinkFilter; import org.matsim.core.network.filter.NetworkNodeFilter; import org.matsim.core.network.io.MatsimNetworkReader; import org.matsim.core.network.io.NetworkWriter; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.legacy.prepare.transit.schedule.CheckPtDelays.DelayRecord; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitRouteStop; import org.matsim.pt.transitSchedule.api.TransitSchedule; import org.matsim.pt.transitSchedule.api.TransitScheduleReader; import org.matsim.pt.transitSchedule.api.TransitScheduleWriter; import org.matsim.pt.utils.CreatePseudoNetwork; import org.matsim.pt.utils.TransitScheduleValidator; import org.matsim.pt.utils.TransitScheduleValidator.ValidationResult; import org.matsim.vehicles.Vehicle; import org.matsim.vehicles.VehicleCapacity; import org.matsim.vehicles.VehicleType; import org.matsim.vehicles.MatsimVehicleWriter; import org.matsim.vehicles.VehiclesFactory; import org.matsim.vehicles.VehicleType.DoorOperationMode; import org.matsim.vehicles.VehicleUtils; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorModule; /** * @author vsp-gleich * This is an script that utilizes GTFS2MATSim and creates a pseudo network and vehicles using MATSim standard API functionality. * * It then adapts the link freespeeds of the pt pseudo network to reduce pt delays and early arrivals. This is not perfect. * Check manually after running, e.g. using the log output on maximum delays per TransitLine. * * TODO: Theoretically we would have to increase the boarding/alighting time and reduce the capacity of the transit vehicle types * according to the sample size. */ public class RunGTFS2MATSimOpenBerlin { private static final Logger log = LogManager.getLogger(RunGTFS2MATSimOpenBerlin.class); public static void main(String[] args) { //this was tested for the latest VBB GTFS, available at // http://www.vbb.de/de/article/fahrplan/webservices/datensaetze/1186967.html //input data, https paths don't work probably due to old GTFS library :( String gtfsZipFile = "../public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/original-data/GTFS-VBB-20181214/GTFS-VBB-20181214.zip"; CoordinateTransformation ct = TransformationFactory.getCoordinateTransformation(TransformationFactory.WGS84, TransformationFactory.DHDN_GK4); // choose date not too far away (e.g. on 2019-12-12 S2 is almost completey missing for 2019-08-20 gtfs data set!), // but not too close either (diversions and interruptions due to short term construction work included in GTFS) // -> hopefully no construction sites in GTFS for that date // -> Thursday is more "typical" than Friday // check date for construction work in BVG Navi booklet: 18-20 Dec'2018 seemed best over the period from Dec'2018 to Sep'2019 LocalDate date = LocalDate.parse("2018-12-20"); //output files String outputDirectory = "RunGTFS2MATSimOpenBerlin"; String networkFile = outputDirectory + "/berlin-v5.6-network.xml.gz"; String scheduleFile = outputDirectory + "/berlin-v5.6-transit-schedule.xml.gz"; String transitVehiclesFile = outputDirectory + "/berlin-v5.6-transit-vehicles.xml.gz"; // ensure output directory exists File directory = new File(outputDirectory); if (! directory.exists()){ directory.mkdirs(); } //Convert GTFS RunGTFS2MATSim.convertGtfs(gtfsZipFile, scheduleFile, date, ct, false); //Parse the schedule again Scenario scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); new TransitScheduleReader(scenario).readFile(scheduleFile); // copy late/early departures to have at complete schedule from ca. 0:00 to ca. 30:00 TransitSchedulePostProcessTools.copyLateDeparturesToStartOfDay(scenario.getTransitSchedule(), 24 * 3600, "copied", false); TransitSchedulePostProcessTools.copyEarlyDeparturesToFollowingNight(scenario.getTransitSchedule(), 6 * 3600, "copied"); //if necessary, parse in an existing network file here: new MatsimNetworkReader(scenario.getNetwork()).readFile("../public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-network.xml.gz"); Config config = ConfigUtils.loadConfig("../public-svn/matsim/scenarios/countries/de/berlin/berlin-v5.5-10pct/input/berlin-v5.5-10pct.config.xml"); //remove existing pt network (nodes and links) Network networkWoPt = getNetworkWOExistingPtLinksAndNodes(scenario.getNetwork(), "pt_", config.network()); new NetworkWriter(networkWoPt).write(outputDirectory + "/network_filtered_woNewPt.xml.gz"); //Create a network around the schedule and transit vehicles scenario = getScenarioWithPseudoPtNetworkAndTransitVehicles(networkWoPt, scenario.getTransitSchedule(), "pt_"); //Check schedule and network ValidationResult checkResult = TransitScheduleValidator.validateAll(scenario.getTransitSchedule(), networkWoPt); if (checkResult.isValid()) { log.info("TransitSchedule and Network valid according to TransitScheduleValidator"); log.warn("TransitScheduleValidator warnings:\n" + checkResult.getWarnings()); } else { log.error(checkResult.getErrors()); throw new RuntimeException("TransitSchedule and/or Network invalid"); } //Write out network, vehicles and schedule new NetworkWriter(networkWoPt).write(networkFile); new TransitScheduleWriter(scenario.getTransitSchedule()).writeFile(scheduleFile); new MatsimVehicleWriter(scenario.getTransitVehicles()).writeFile(transitVehiclesFile); // test for delays String testRunOutputDirectory = outputDirectory + "/runOneIteration"; runOneIteration(scenario, testRunOutputDirectory); CheckPtDelays delayChecker = new CheckPtDelays(testRunOutputDirectory + "/output_events.xml.gz", scheduleFile); delayChecker.run(); DelayRecord minDelay = delayChecker.getMinDelay(); DelayRecord maxDelay = delayChecker.getMaxDelay(); log.warn("min delay: " + minDelay); log.warn("average of negatively delayed over total number of arrivals and departures " + delayChecker.getAverageOfNegativelyDelayedOverTotalNumberOfRecords() + " s"); if (minDelay.getDelay() < -1) { log.warn(delayChecker.minDelayPerTransitLine()); } log.warn("max delay: " + maxDelay); log.warn("average of positively delayed over positively delayed arrivals and departures " + delayChecker.getAverageOfPositivelyDelayedOverPositivelyDelayed() + " s"); log.warn("average of positively delayed over total number of arrivals and departures " + delayChecker.getAverageOfPositivelyDelayedOverTotalNumberOfRecords() + " s"); if (maxDelay.getDelay() > 1) { log.warn(delayChecker.maxDelayPerTransitLine()); } // delays up to 60s are probably ok, because most input gtfs schedule data has an accuracy of only one minute } private static Network getNetworkWOExistingPtLinksAndNodes(Network network, String ptNetworkIdentifier, NetworkConfigGroup networkConfigGroup) { NetworkFilterManager nfmPT = new NetworkFilterManager(network, networkConfigGroup); nfmPT.addLinkFilter(new NetworkLinkFilter() { @Override public boolean judgeLink(Link l) { if (l.getId().toString().contains(ptNetworkIdentifier)) return false; else return true; } }); nfmPT.addNodeFilter(new NetworkNodeFilter() { @Override public boolean judgeNode(Node n) { if (n.getId().toString().contains(ptNetworkIdentifier)) return false; else return true; } }); Network networkWoPt = nfmPT.applyFilters(); return networkWoPt; } private static Scenario getScenarioWithPseudoPtNetworkAndTransitVehicles(Network network, TransitSchedule schedule, String ptNetworkIdentifier) { ScenarioUtils.ScenarioBuilder builder = new ScenarioUtils.ScenarioBuilder(ConfigUtils.createConfig()); builder.setNetwork(network); builder.setTransitSchedule(schedule); Scenario scenario = builder.build(); // add pseudo network for pt new CreatePseudoNetwork(scenario.getTransitSchedule(), scenario.getNetwork(), "pt_", 0.1, 100000.0).createNetwork(); // create TransitVehicle types // see https://svn.vsp.tu-berlin.de/repos/public-svn/publications/vspwp/2014/14-24/ for veh capacities // the values set here are at the upper end of the typical capacity range, so on lines with high capacity vehicles the // capacity of the matsim vehicle equals roughly the real vehicles capacity and on other lines the Matsim vehicle // capacity is higher than the real used vehicle's capacity (gtfs provides no information on which vehicle type is used, // and this would be beyond scope here). - gleich sep'19 VehiclesFactory vehicleFactory = scenario.getVehicles().getFactory(); VehicleType reRbVehicleType = vehicleFactory.createVehicleType( Id.create( "RE_RB_veh_type", VehicleType.class ) ); { VehicleCapacity capacity = reRbVehicleType.getCapacity(); capacity.setSeats( 500 ); capacity.setStandingRoom( 600 ); VehicleUtils.setDoorOperationMode(reRbVehicleType, DoorOperationMode.serial); // first finish boarding, then start alighting VehicleUtils.setAccessTime(reRbVehicleType, 1.0 / 10.0); // 1s per boarding agent, distributed on 10 doors VehicleUtils.setEgressTime(reRbVehicleType, 1.0 / 10.0); // 1s per alighting agent, distributed on 10 doors scenario.getTransitVehicles().addVehicleType( reRbVehicleType ); } VehicleType sBahnVehicleType = vehicleFactory.createVehicleType( Id.create( "S-Bahn_veh_type", VehicleType.class ) ); { VehicleCapacity capacity = sBahnVehicleType.getCapacity(); capacity.setSeats( 400 ); capacity.setStandingRoom( 800 ); VehicleUtils.setDoorOperationMode(sBahnVehicleType, DoorOperationMode.serial); // first finish boarding, then start alighting VehicleUtils.setAccessTime(sBahnVehicleType, 1.0 / 24.0); // 1s per boarding agent, distributed on 8*3 doors VehicleUtils.setEgressTime(sBahnVehicleType, 1.0 / 24.0); // 1s per alighting agent, distributed on 8*3 doors scenario.getTransitVehicles().addVehicleType( sBahnVehicleType ); } VehicleType uBahnVehicleType = vehicleFactory.createVehicleType( Id.create( "U-Bahn_veh_type", VehicleType.class ) ); { VehicleCapacity capacity = uBahnVehicleType.getCapacity() ; capacity.setSeats( 300 ); capacity.setStandingRoom( 600 ); VehicleUtils.setDoorOperationMode(uBahnVehicleType, DoorOperationMode.serial); // first finish boarding, then start alighting VehicleUtils.setAccessTime(uBahnVehicleType, 1.0 / 18.0); // 1s per boarding agent, distributed on 6*3 doors VehicleUtils.setEgressTime(uBahnVehicleType, 1.0 / 18.0); // 1s per alighting agent, distributed on 6*3 doors scenario.getTransitVehicles().addVehicleType( uBahnVehicleType ); } VehicleType tramVehicleType = vehicleFactory.createVehicleType( Id.create( "Tram_veh_type", VehicleType.class ) ); { VehicleCapacity capacity = tramVehicleType.getCapacity() ; capacity.setSeats( 80 ); capacity.setStandingRoom( 170 ); VehicleUtils.setDoorOperationMode(tramVehicleType, DoorOperationMode.serial); // first finish boarding, then start alighting VehicleUtils.setAccessTime(tramVehicleType, 1.0 / 5.0); // 1s per boarding agent, distributed on 5 doors VehicleUtils.setEgressTime(tramVehicleType, 1.0 / 5.0); // 1s per alighting agent, distributed on 5 doors scenario.getTransitVehicles().addVehicleType( tramVehicleType ); } VehicleType busVehicleType = vehicleFactory.createVehicleType( Id.create( "Bus_veh_type", VehicleType.class ) ); { VehicleCapacity capacity = busVehicleType.getCapacity() ; capacity.setSeats( 50 ); capacity.setStandingRoom( 100 ); VehicleUtils.setDoorOperationMode(busVehicleType, DoorOperationMode.serial); // first finish boarding, then start alighting VehicleUtils.setAccessTime(busVehicleType, 1.0 / 3.0); // 1s per boarding agent, distributed on 3 doors VehicleUtils.setEgressTime(busVehicleType, 1.0 / 3.0); // 1s per alighting agent, distributed on 3 doors scenario.getTransitVehicles().addVehicleType( busVehicleType ); } VehicleType ferryVehicleType = vehicleFactory.createVehicleType( Id.create( "Ferry_veh_type", VehicleType.class ) ); { VehicleCapacity capacity = ferryVehicleType.getCapacity() ; capacity.setSeats( 100 ); capacity.setStandingRoom( 100 ); VehicleUtils.setDoorOperationMode(ferryVehicleType, DoorOperationMode.serial); // first finish boarding, then start alighting VehicleUtils.setAccessTime(ferryVehicleType, 1.0 / 1.0); // 1s per boarding agent, distributed on 1 door VehicleUtils.setEgressTime(ferryVehicleType, 1.0 / 1.0); // 1s per alighting agent, distributed on 1 door scenario.getTransitVehicles().addVehicleType( ferryVehicleType ); } // set link speeds and create vehicles according to pt mode for (TransitLine line: scenario.getTransitSchedule().getTransitLines().values()) { VehicleType lineVehicleType; String stopFilter = ""; // identify veh type / mode using gtfs route type (3-digit code, also found at the end of the line id (gtfs: route_id)) int gtfsTransitType; try { gtfsTransitType = Integer.parseInt( (String) line.getAttributes().getAttribute("gtfs_route_type")); } catch (NumberFormatException e) { log.error("unknown transit mode! Line id was " + line.getId().toString() + "; gtfs route type was " + (String) line.getAttributes().getAttribute("gtfs_route_type")); throw new RuntimeException("unknown transit mode"); } int agencyId; try { agencyId = Integer.parseInt( (String) line.getAttributes().getAttribute("gtfs_agency_id")); } catch (NumberFormatException e) { log.error("invalid transit agency! Line id was " + line.getId().toString() + "; gtfs agency was " + (String) line.getAttributes().getAttribute("gtfs_agency_id")); throw new RuntimeException("invalid transit agency"); } switch (gtfsTransitType) { // the vbb gtfs file generally uses the new gtfs route types, but some lines use the old enum in the range 0 to 7 // see https://sites.google.com/site/gtfschanges/proposals/route-type // and https://developers.google.com/transit/gtfs/reference/#routestxt // In GTFS-VBB-20181214.zip some RE lines are wrongly attributed as type 700 (bus)! // freespeed are set to make sure that no transit service is delayed // and arrivals are as punctual (not too early) as possible case 100: lineVehicleType = reRbVehicleType; stopFilter = "station_S/U/RE/RB"; break; case 109: // S-Bahn-Berlin is agency id 1 lineVehicleType = sBahnVehicleType; stopFilter = "station_S/U/RE/RB"; break; case 400: lineVehicleType = uBahnVehicleType; stopFilter = "station_S/U/RE/RB"; break; case 3: // bus, same as 700 case 700: // BVG is agency id 796 lineVehicleType = busVehicleType; break; case 900: lineVehicleType = tramVehicleType; break; case 1000: lineVehicleType = ferryVehicleType; break; default: log.error("unknown transit mode! Line id was " + line.getId().toString() + "; gtfs route type was " + (String) line.getAttributes().getAttribute("gtfs_route_type")); throw new RuntimeException("unknown transit mode"); } for (TransitRoute route: line.getRoutes().values()) { int routeVehId = 0; // simple counter for vehicle id _per_ TransitRoute // increase speed if current freespeed is lower. List<TransitRouteStop> routeStops = route.getStops(); if (routeStops.size() < 2) { log.error("TransitRoute with less than 2 stops found: line " + line.getId().toString() + ", route " + route.getId().toString()); throw new RuntimeException(""); } double lastDepartureOffset = route.getStops().get(0).getDepartureOffset().seconds(); // min. time spend at a stop, useful especially for stops whose arrival and departure offset is identical, // so we need to add time for passengers to board and alight double minStopTime = 30.0; for (int i = 1; i < routeStops.size(); i++) { // TODO cater for loop link at first stop? Seems to just work without. TransitRouteStop routeStop = routeStops.get(i); // if there is no departure offset set (or infinity), it is the last stop of the line, // so we don't need to care about the stop duration double stopDuration = routeStop.getDepartureOffset().isDefined() ? routeStop.getDepartureOffset().seconds() - routeStop.getArrivalOffset().seconds() : minStopTime; // ensure arrival at next stop early enough to allow for 30s stop duration -> time for passengers to board / alight // if link freespeed had been set such that the pt veh arrives exactly on time, but departure tiome is identical // with arrival time the pt vehicle would have been always delayed // Math.max to avoid negative values of travelTime double travelTime = Math.max(1, routeStop.getArrivalOffset().seconds() - lastDepartureOffset - 1.0 - (stopDuration >= minStopTime ? 0 : (minStopTime - stopDuration))) ; Link link = network.getLinks().get(routeStop.getStopFacility().getLinkId()); increaseLinkFreespeedIfLower(link, link.getLength() / travelTime); lastDepartureOffset = routeStop.getDepartureOffset().seconds(); } // create vehicles for Departures for (Departure departure: route.getDepartures().values()) { Vehicle veh = vehicleFactory.createVehicle(Id.create("pt_" + route.getId().toString() + "_" + Long.toString(routeVehId++), Vehicle.class), lineVehicleType); scenario.getTransitVehicles().addVehicle(veh); departure.setVehicleId(veh.getId()); } // tag RE, RB, S- and U-Bahn stations for Drt stop filter attribute if (!stopFilter.isEmpty()) { for (TransitRouteStop routeStop: route.getStops()) { routeStop.getStopFacility().getAttributes().putAttribute("stopFilter", stopFilter); } } } } return scenario; } private static void increaseLinkFreespeedIfLower(Link link, double newFreespeed) { if (link.getFreespeed() < newFreespeed) { link.setFreespeed(newFreespeed); } } private static void runOneIteration(Scenario scenario, String outputDirectory) { new File(outputDirectory).mkdirs(); scenario.getConfig().controller().setOutputDirectory(outputDirectory); scenario.getConfig().controller().setLastIteration(0); scenario.getConfig().controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); scenario.getConfig().transit().setUseTransit(true); Controler controler = new Controler( scenario ); // use the sbb pt raptor router which takes less time to build a transit router network controler.addOverridingModule( new AbstractModule() { @Override public void install() { install( new SwissRailRaptorModule() ); } } ); controler.run(); } }
21,325
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CheckPtDelays.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/transit/schedule/CheckPtDelays.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.transit.schedule; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; 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.core.api.experimental.events.EventsManager; import org.matsim.core.api.experimental.events.VehicleArrivesAtFacilityEvent; import org.matsim.core.api.experimental.events.VehicleDepartsAtFacilityEvent; import org.matsim.core.api.experimental.events.handler.VehicleArrivesAtFacilityEventHandler; import org.matsim.core.api.experimental.events.handler.VehicleDepartsAtFacilityEventHandler; import org.matsim.core.config.ConfigUtils; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.pt.transitSchedule.api.TransitScheduleReader; import org.matsim.pt.transitSchedule.api.TransitStopFacility; import org.matsim.vehicles.Vehicle; /** * * @author vsp-gleich * */ public class CheckPtDelays { private static final Logger log = LogManager.getLogger(CheckPtDelays.class); private final String eventsFile; private final String scheduleFile; private Scenario scenario; private List<DelayRecord> allDelays = new ArrayList<>(); private Map<Id<Vehicle>, DelayRecord> veh2minDelay = new HashMap<>(); private Map<Id<Vehicle>, DelayRecord> veh2maxDelay = new HashMap<>(); private Map<Id<TransitLine>, DelayRecord> line2minDelay = new TreeMap<>(); private Map<Id<TransitLine>, DelayRecord> line2maxDelay = new TreeMap<>(); private Map<Id<Vehicle>, Id<TransitRoute>> vehId2RouteId = new HashMap<>(); private Map<Id<TransitRoute>, Id<TransitLine>> transitRouteId2TransitLineId = new HashMap<>(); CheckPtDelays (String eventsFile, String scheduleFile) { this.eventsFile = eventsFile; this.scheduleFile = scheduleFile; } public static void main(String[] args) { String eventsFile = "scenarios/berlin-v5.5-1pct/output-berlin-v5.5-1pct/ITERS/it.0/berlin-v5.5-1pct.0.events.xml.gz"; String scheduleFile = "transitSchedule.xml.gz"; CheckPtDelays runner = new CheckPtDelays(eventsFile, scheduleFile); runner.run(); log.info(runner.minDelayPerTransitLine()); log.info(runner.maxDelayPerTransitLine()); } void run() { // read TransitSchedule in order to sum up results by TransitLine scenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); TransitScheduleReader tsReader = new TransitScheduleReader(scenario); tsReader.readFile(scheduleFile); for (TransitLine line: scenario.getTransitSchedule().getTransitLines().values()) { for (TransitRoute route: line.getRoutes().values()) { transitRouteId2TransitLineId.put(route.getId(), line.getId()); for (Departure dep: route.getDepartures().values()) { vehId2RouteId.put(dep.getVehicleId(), route.getId()); } } } EventsManager eventsManager = EventsUtils.createEventsManager(); VehicleDelayEventHandler delayHandler = this.new VehicleDelayEventHandler(); eventsManager.addHandler(delayHandler); eventsManager.initProcessing(); MatsimEventsReader reader = new MatsimEventsReader(eventsManager); reader.readFile(eventsFile); eventsManager.finishProcessing(); aggregatePerTransitLine(); } // it seems that VehicleArrivesAtFacility and VehicleDepartsAtFacility evnt types are only used for transit vehicles, // because both have TransitStopFacility private class VehicleDelayEventHandler implements VehicleArrivesAtFacilityEventHandler, VehicleDepartsAtFacilityEventHandler { @Override public void handleEvent(VehicleArrivesAtFacilityEvent event) { Id<Vehicle> vehId = event.getVehicleId(); Id<TransitRoute> routeId = vehId2RouteId.get(vehId); Id<TransitLine> lineId = transitRouteId2TransitLineId.get(routeId); DelayRecord delay = new DelayRecord(lineId, routeId, vehId, event.getFacilityId(), event.getDelay()); if (Double.isFinite(delay.delay)) { allDelays.add(delay); if (!veh2minDelay.containsKey(event.getVehicleId())) veh2minDelay.put(event.getVehicleId(), delay); if (!veh2maxDelay.containsKey(event.getVehicleId())) veh2maxDelay.put(event.getVehicleId(), delay); if (delay.delay > 0) { if (delay.delay > veh2maxDelay.get(event.getVehicleId()).delay){ veh2maxDelay.put(event.getVehicleId(), delay); } } else { if (delay.delay < veh2minDelay.get(event.getVehicleId()).delay){ veh2minDelay.put(event.getVehicleId(), delay); } } } } @Override public void handleEvent(VehicleDepartsAtFacilityEvent event) { Id<Vehicle> vehId = event.getVehicleId(); Id<TransitRoute> routeId = vehId2RouteId.get(vehId); Id<TransitLine> lineId = transitRouteId2TransitLineId.get(routeId); DelayRecord delay = new DelayRecord(lineId, routeId, vehId, event.getFacilityId(), event.getDelay()); if (Double.isFinite(delay.delay)) { allDelays.add(delay); if (!veh2maxDelay.containsKey(event.getVehicleId())) veh2maxDelay.put(event.getVehicleId(), delay); if (!veh2minDelay.containsKey(event.getVehicleId())) veh2minDelay.put(event.getVehicleId(), delay); if (delay.delay > 0) { if (delay.delay > veh2maxDelay.get(event.getVehicleId()).delay){ veh2maxDelay.put(event.getVehicleId(), delay); } } else { if (delay.delay < veh2minDelay.get(event.getVehicleId()).delay){ veh2minDelay.put(event.getVehicleId(), delay); } } } } } /** * This assumes that each TransitVehicle is used on exactly one TransitLine, never on multiple lines */ private void aggregatePerTransitLine() { for (Entry<Id<Vehicle>, DelayRecord> entry: veh2maxDelay.entrySet()) { Id<TransitLine> lineId = entry.getValue().lineId; if (!line2maxDelay.containsKey(lineId)) line2maxDelay.put(lineId, entry.getValue()); if (entry.getValue().delay > line2maxDelay.get(lineId).delay){ line2maxDelay.put(lineId, entry.getValue()); } } for (Entry<Id<Vehicle>, DelayRecord> entry: veh2minDelay.entrySet()) { Id<TransitLine> lineId = entry.getValue().lineId; if (!line2minDelay.containsKey(lineId)) line2minDelay.put(lineId, entry.getValue()); if (entry.getValue().delay < line2minDelay.get(lineId).delay){ line2minDelay.put(lineId, entry.getValue()); } } } DelayRecord getMaxDelay() { return Collections.max(line2maxDelay.values(), new DelayRecordDelayComparator()); } DelayRecord getMinDelay() { return Collections.min(line2minDelay.values(), new DelayRecordDelayComparator()); } double getAverageOfPositivelyDelayedOverPositivelyDelayed() { double sum = 0; int counter = 0; for (DelayRecord delay: allDelays) { if (delay.delay > 0) { counter++; sum = sum + delay.delay; } } if (counter < 1) { return Double.NaN; } return sum / counter; } double getAverageOfPositivelyDelayedOverTotalNumberOfRecords() { double sum = 0; for (DelayRecord delay: allDelays) { if (delay.delay > 0) { sum = sum + delay.delay; } } if (allDelays.size() < 1) { return Double.NaN; } return sum / allDelays.size(); } double getAverageOfNegativelyDelayedOverTotalNumberOfRecords() { double sum = 0; for (DelayRecord delay: allDelays) { if (delay.delay < 0) { sum = sum + delay.delay; } } if (allDelays.size() < 1) { return Double.NaN; } return sum / allDelays.size(); } String minDelayPerTransitLine() { DelayRecord min = getMinDelay(); StringBuilder str = new StringBuilder(); str.append("#Min delay: " + min.toString()); str.append("\nlineId;routeId;vehId;stopId;delaySec"); for (DelayRecord delay: line2minDelay.values()) { str.append("\n"); str.append(delay.toValueString()); } return str.toString(); } String maxDelayPerTransitLine() { DelayRecord max = getMaxDelay(); StringBuilder str = new StringBuilder(); str.append("#Max delay: " + max.toString()); str.append("\nlineId;routeId;vehId;stopId;delaySec"); for (DelayRecord delay: line2maxDelay.values()) { str.append("\n"); str.append(delay.toValueString()); } return str.toString(); } class DelayRecord { private final Id<TransitLine> lineId; private final Id<TransitRoute> routeId; private final Id<Vehicle> vehId; private final Id<TransitStopFacility> stopId; private final double delay; DelayRecord(Id<TransitLine> lineId, Id<TransitRoute> routeId, Id<Vehicle> vehId, Id<TransitStopFacility> stopId, double delay) { this.lineId = lineId; this.routeId = routeId; this.vehId = vehId; this.stopId = stopId; this.delay = delay; } @Override public String toString() { return "lineId " + lineId + "; routeId " + routeId + "; vehId " + vehId + "; stopId " + stopId + "; delay " + delay; } String toValueString() { return lineId + ";" + routeId + ";" + vehId + ";" + stopId + ";" + delay; } double getDelay() { return delay; } } private class DelayRecordDelayComparator implements Comparator<DelayRecord> { @Override public int compare(DelayRecord o1, DelayRecord o2) { return Double.compare(o1.delay, o2.delay); } } }
10,794
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
CreateRoadPricingXml.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/roadpricing/CreateRoadPricingXml.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2021 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.prepare.roadpricing; import org.locationtech.jts.geom.prep.PreparedGeometry; import org.matsim.api.core.v01.Coord; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.roadpricing.RoadPricingScheme; import org.matsim.contrib.roadpricing.RoadPricingSchemeImpl; import org.matsim.contrib.roadpricing.RoadPricingUtils; import org.matsim.contrib.roadpricing.RoadPricingWriterXMLv1; import org.matsim.core.config.Config; import org.matsim.core.utils.geometry.CoordinateTransformation; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.core.utils.io.IOUtils; import org.matsim.core.utils.misc.Time; import org.matsim.legacy.run.RunBerlinScenario; import org.matsim.utils.gis.shp2matsim.ShpGeometryUtils; import java.util.List; public class CreateRoadPricingXml { public static void main (String[] args) { // String zoneShpFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/projects/avoev/shp-files/shp-berlin-bezirksregionen/berlin-bezirksregion_GK4_fixed.shp"; String zoneShpFile = "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/projects/avoev/shp-files/shp-inner-city-area/inner-city-area.shp"; String zoneShpCRS = "EPSG:31468"; // String outputFile = "berlin_distance_roadpricing.xml"; String outputFile = "berlin_cordon_roadpricing.xml"; if (args.length == 0) { args = new String[]{"scenarios/berlin-v5.5-1pct/input/berlin-v5.5-1pct.config.xml"}; } Config config = RunBerlinScenario.prepareConfig( args ) ; Scenario scenario = RunBerlinScenario.prepareScenario( config ) ; // createDistanceCostRoadPricingXml(scenario, zoneShpFile, zoneShpCRS, outputFile); createCordonRoadPricingXml(scenario, zoneShpFile, zoneShpCRS, outputFile); } static void createDistanceCostRoadPricingXml(Scenario scenario, String zoneShpFile, String shapeFileCRS, String outputFile) { CoordinateTransformation transformer = TransformationFactory.getCoordinateTransformation(scenario.getConfig().global().getCoordinateSystem(), shapeFileCRS); List<PreparedGeometry> geometries = ShpGeometryUtils.loadPreparedGeometries(IOUtils.resolveFileOrResource(zoneShpFile)); RoadPricingSchemeImpl scheme = RoadPricingUtils.addOrGetMutableRoadPricingScheme(scenario ); /* Configure roadpricing scheme. */ RoadPricingUtils.setName(scheme, "Berlin_distance_toll"); RoadPricingUtils.setType(scheme, RoadPricingScheme.TOLL_TYPE_DISTANCE); RoadPricingUtils.setDescription(scheme, "distance toll within Berlin city border"); /* Add general toll. */ for (Link link : scenario.getNetwork().getLinks().values()) { Coord fromNodeTransformed = transformer.transform(link.getFromNode().getCoord()); Coord toNodeTransformed = transformer.transform(link.getToNode().getCoord()); if (ShpGeometryUtils.isCoordInPreparedGeometries(fromNodeTransformed, geometries) && ShpGeometryUtils.isCoordInPreparedGeometries(toNodeTransformed, geometries)) { RoadPricingUtils.addLink(scheme, link.getId()); } } RoadPricingUtils.createAndAddGeneralCost(scheme, Time.parseTime("00:00:00"), Time.parseTime("30:00:00"), 0.00005); RoadPricingWriterXMLv1 writer = new RoadPricingWriterXMLv1(scheme); writer.writeFile(outputFile); } static void createCordonRoadPricingXml(Scenario scenario, String zoneShpFile, String shapeFileCRS, String outputFile) { CoordinateTransformation transformer = TransformationFactory.getCoordinateTransformation(scenario.getConfig().global().getCoordinateSystem(), shapeFileCRS); List<PreparedGeometry> geometries = ShpGeometryUtils.loadPreparedGeometries(IOUtils.resolveFileOrResource(zoneShpFile)); RoadPricingSchemeImpl scheme = RoadPricingUtils.addOrGetMutableRoadPricingScheme(scenario ); /* Configure roadpricing scheme. */ RoadPricingUtils.setName(scheme, "Berlin_distance_toll"); RoadPricingUtils.setType(scheme, RoadPricingScheme.TOLL_TYPE_LINK); RoadPricingUtils.setDescription(scheme, "cordon toll within Berlin inner city border"); /* Add general toll. */ for (Link link : scenario.getNetwork().getLinks().values()) { Coord fromNodeTransformed = transformer.transform(link.getFromNode().getCoord()); Coord toNodeTransformed = transformer.transform(link.getToNode().getCoord()); if (!ShpGeometryUtils.isCoordInPreparedGeometries(fromNodeTransformed, geometries) && ShpGeometryUtils.isCoordInPreparedGeometries(toNodeTransformed, geometries)) { RoadPricingUtils.addLink(scheme, link.getId()); } } RoadPricingUtils.createAndAddGeneralCost(scheme, Time.parseTime("00:00:00"), Time.parseTime("30:00:00"), 5.0); RoadPricingWriterXMLv1 writer = new RoadPricingWriterXMLv1(scheme); writer.writeFile(outputFile); } }
6,626
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
NetworkToShp.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/prepare/wasteCollection/NetworkToShp.java
package org.matsim.legacy.prepare.wasteCollection; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.utils.gis.matsim2esri.network.Links2ESRIShape; public class NetworkToShp { public static void main(String[] args) { String networkFile = "original-input-data/berlin-v5.2-1pct.output_network.xml.gz"; String shapeFileLine = "C:\\Users\\erica\\OneDrive\\Dokumente\\Studium\\0 Masterarbeit\\shapeNetzwerk\\berlin-v5.2-1pct.output_networkFl.shp"; String shapeFilePoly = "C:\\Users\\erica\\OneDrive\\Dokumente\\Studium\\0 Masterarbeit\\shapeNetzwerk\\berlin-v5.2-1pct.output_networkP.shp"; String crs = TransformationFactory.DHDN_GK4; Links2ESRIShape.main(new String[]{networkFile, shapeFileLine, shapeFilePoly, crs}); } }
779
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunBerlinScenario.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/RunBerlinScenario.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run; 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.TypeLiteral; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; 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.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.contrib.drt.routing.DrtRoute; import org.matsim.contrib.drt.routing.DrtRouteFactory; import org.matsim.contrib.roadpricing.RoadPricing; import org.matsim.contrib.roadpricing.RoadPricingConfigGroup; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup.TrafficDynamics; import org.matsim.core.config.groups.VspExperimentalConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryLogging; import org.matsim.core.gbl.Gbl; import org.matsim.core.gbl.MatsimRandom; import org.matsim.core.population.routes.RouteFactories; import org.matsim.core.replanning.choosers.ForceInnovationStrategyChooser; import org.matsim.core.replanning.choosers.StrategyChooser; import org.matsim.core.router.AnalysisMainModeIdentifier; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.scoring.functions.ScoringParametersForPerson; import org.matsim.core.utils.geometry.transformations.TransformationFactory; import org.matsim.extensions.pt.PtExtensionsConfigGroup; import org.matsim.extensions.pt.routing.EnhancedRaptorIntermodalAccessEgress; import org.matsim.legacy.run.drt.OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier; import org.matsim.legacy.run.drt.RunDrtOpenBerlinScenario; import org.matsim.prepare.population.AssignIncome; import playground.vsp.scoring.IncomeDependentUtilityOfMoneyPersonScoringParameters; import java.util.*; import static org.matsim.core.config.groups.ControllerConfigGroup.RoutingAlgorithmType.AStarLandmarks; /** * @author ikaddoura */ public final class RunBerlinScenario { private static final Logger log = LogManager.getLogger(RunBerlinScenario.class ); public static void main(String[] args) { for (String arg : args) { log.info( arg ); } if ( args.length==0 ) { args = new String[] {"scenarios/berlin-v5.5-10pct/input/berlin-v5.5-10pct.config.xml"} ; } Config config = prepareConfig( args ) ; Scenario scenario = prepareScenario( config ) ; Controler controler = prepareControler( scenario ) ; controler.run(); } public static Controler prepareControler( Scenario scenario ) { // note that for something like signals, and presumably drt, one needs the controler object Gbl.assertNotNull(scenario); final Controler controler = new Controler( scenario ); if (controler.getConfig().transit().isUseTransit()) { // use the sbb pt raptor router controler.addOverridingModule( new AbstractModule() { @Override public void install() { install( new SwissRailRaptorModule() ); } } ); } else { log.warn("Public transit will be teleported and not simulated in the mobsim! " + "This will have a significant effect on pt-related parameters (travel times, modal split, and so on). " + "Should only be used for testing or car-focused studies with a fixed modal split. "); } // use the (congested) car travel time for the teleported ride mode controler.addOverridingModule( new AbstractModule() { @Override public void install() { addTravelTimeBinding( TransportMode.ride ).to( networkTravelTime() ); addTravelDisutilityFactoryBinding( TransportMode.ride ).to( carTravelDisutilityFactoryKey() ); bind(AnalysisMainModeIdentifier.class).to(OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier.class); // addPlanStrategyBinding("RandomSingleTripReRoute").toProvider(RandomSingleTripReRoute.class); // addPlanStrategyBinding("ChangeSingleTripModeAndRoute").toProvider(ChangeSingleTripModeAndRoute.class); bind(RaptorIntermodalAccessEgress.class).to(EnhancedRaptorIntermodalAccessEgress.class); //use income-dependent marginal utility of money for scoring bind(ScoringParametersForPerson.class).to(IncomeDependentUtilityOfMoneyPersonScoringParameters.class).in(Singleton.class); // set Plantypes to keep the initial selected plan up to the last iteration BerlinExperimentalConfigGroup berlinCfg = ConfigUtils.addOrGetModule(controler.getConfig(), BerlinExperimentalConfigGroup.class); if (!berlinCfg.getPlanTypeOverwriting().equals(BerlinExperimentalConfigGroup.PlanTypeOverwriting.NO_OVERWRITE)) { PlanTypeOverwriter overwriter = new PlanTypeOverwriter(berlinCfg, scenario.getPopulation()); addControlerListenerBinding().toInstance(overwriter); } // analysis output if (berlinCfg.getAnalysisLevel().equals(BerlinExperimentalConfigGroup.AnalysisLevel.FULL)) { install(new LinkPaxVolumesAnalysisModule()); install(new PtStop2StopAnalysisModule()); install(new PersonMoneyEventsAnalysisModule()); } // use forced innovation every 10 iterations bind(new TypeLiteral<StrategyChooser<Plan, Person>>() {}).toInstance(new ForceInnovationStrategyChooser<>(10, ForceInnovationStrategyChooser.Permute.yes)); } } ); RoadPricingConfigGroup roadPricingConfigGroup = ConfigUtils.addOrGetModule(scenario.getConfig(), RoadPricingConfigGroup.class); if (roadPricingConfigGroup.getTollLinksFile() != null) { RoadPricing.configure( controler ); } return controler; } public static Scenario prepareScenario( Config config ) { Gbl.assertNotNull( config ); // note that the path for this is different when run from GUI (path of original config) vs. // when run from command line/IDE (java root). :-( See comment in method. kai, jul'18 // yy Does this comment still apply? kai, jul'19 /* * We need to set the DrtRouteFactory before loading the scenario. Otherwise DrtRoutes in input plans are loaded * as GenericRouteImpls and will later cause exceptions in DrtRequestCreator. So we do this here, although this * class is also used for runs without drt. */ final Scenario scenario = ScenarioUtils.createScenario( config ); BerlinExperimentalConfigGroup berlinCfg = ConfigUtils.addOrGetModule(config, BerlinExperimentalConfigGroup.class); RouteFactories routeFactories = scenario.getPopulation().getFactory().getRouteFactories(); routeFactories.setRouteFactory(DrtRoute.class, new DrtRouteFactory()); ScenarioUtils.loadScenario(scenario); // add NetworkModesToAddToAllCarLinks for (Link link: scenario.getNetwork().getLinks().values()) { Set<String> allowedModes = link.getAllowedModes(); if (allowedModes.contains(TransportMode.car)) { Set<String> extendedAllowedModes = new HashSet<>(allowedModes); extendedAllowedModes.addAll(berlinCfg.getNetworkModesToAddToAllCarLinks()); link.setAllowedModes(extendedAllowedModes); } } if (berlinCfg.getPopulationDownsampleFactor() != 1.0) { downsample(scenario.getPopulation().getPersons(), berlinCfg.getPopulationDownsampleFactor()); } AssignIncome.assignIncomeToPersons(scenario.getPopulation()); return scenario; } public static Config prepareConfig( String [] args, ConfigGroup... customModules ){ return prepareConfig( RunDrtOpenBerlinScenario.AdditionalInformation.none, args, customModules ) ; } public static Config prepareConfig( RunDrtOpenBerlinScenario.AdditionalInformation additionalInformation, String [] args, ConfigGroup... customModules ) { OutputDirectoryLogging.catchLogEntries(); String[] typedArgs = Arrays.copyOfRange( args, 1, args.length ); ConfigGroup[] customModulesToAdd; if (additionalInformation == RunDrtOpenBerlinScenario.AdditionalInformation.acceptUnknownParamsBerlinConfig) { customModulesToAdd = new ConfigGroup[]{new BerlinExperimentalConfigGroup(true), new PtExtensionsConfigGroup()}; } else { customModulesToAdd = new ConfigGroup[]{new BerlinExperimentalConfigGroup(false), new PtExtensionsConfigGroup()}; } ConfigGroup[] customModulesAll = new ConfigGroup[customModules.length + customModulesToAdd.length]; int counter = 0; for (ConfigGroup customModule : customModules) { customModulesAll[counter] = customModule; counter++; } for (ConfigGroup customModule : customModulesToAdd) { customModulesAll[counter] = customModule; counter++; } final Config config = ConfigUtils.loadConfig( args[ 0 ], customModulesAll ); config.controller().setRoutingAlgorithmType( AStarLandmarks ); config.subtourModeChoice().setProbaForRandomSingleTripMode( 0.5 ); config.routing().setRoutingRandomness( 3. ); config.routing().removeModeRoutingParams(TransportMode.ride); config.routing().removeModeRoutingParams(TransportMode.pt); config.routing().removeModeRoutingParams(TransportMode.bike); config.routing().removeModeRoutingParams("undefined"); config.qsim().setInsertingWaitingVehiclesBeforeDrivingVehicles( true ); // vsp defaults config.vspExperimental().setVspDefaultsCheckingLevel( VspExperimentalConfigGroup.VspDefaultsCheckingLevel.info ); config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); config.qsim().setUsingTravelTimeCheckInTeleportation( true ); config.qsim().setTrafficDynamics( TrafficDynamics.kinematicWaves ); // activities: for ( long ii = 600 ; ii <= 97200; ii+=600 ) { config.scoring().addActivityParams( new ActivityParams( "home_" + ii + ".0" ).setTypicalDuration( ii ) ); config.scoring().addActivityParams( new ActivityParams( "work_" + ii + ".0" ).setTypicalDuration( ii ).setOpeningTime(6. * 3600. ).setClosingTime(20. * 3600. ) ); config.scoring().addActivityParams( new ActivityParams( "leisure_" + ii + ".0" ).setTypicalDuration( ii ).setOpeningTime(9. * 3600. ).setClosingTime(27. * 3600. ) ); config.scoring().addActivityParams( new ActivityParams( "shopping_" + ii + ".0" ).setTypicalDuration( ii ).setOpeningTime(8. * 3600. ).setClosingTime(20. * 3600. ) ); config.scoring().addActivityParams( new ActivityParams( "other_" + ii + ".0" ).setTypicalDuration( ii ) ); } config.scoring().addActivityParams( new ActivityParams( "freight" ).setTypicalDuration( 12.*3600. ) ); ConfigUtils.applyCommandline( config, typedArgs ) ; return config ; } public static void runAnalysis(Controler controler) { Config config = controler.getConfig(); String modesString = ""; for (String mode: config.scoring().getAllModes()) { modesString = modesString + mode + ","; } // remove last "," if (modesString.length() < 2) { log.error("no valid mode found"); modesString = null; } else { modesString = modesString.substring(0, modesString.length() - 1); } String[] args = new String[] { config.controller().getOutputDirectory(), config.controller().getRunId(), "null", // TODO: reference run, hard to automate "null", // TODO: reference run, hard to automate config.global().getCoordinateSystem(), "https://svn.vsp.tu-berlin.de/repos/public-svn/matsim/scenarios/countries/de/berlin/projects/avoev/shp-files/shp-bezirke/bezirke_berlin.shp", TransformationFactory.DHDN_GK4, "SCHLUESSEL", "home", "10", // TODO: scaling factor, should be 10 for 10pct scenario and 100 for 1pct scenario "null", // visualizationScriptInputDirectory modesString }; // Removed so that the dependency could be dropped // RunPersonTripAnalysis.main(args); } private static void downsample( final Map<Id<Person>, ? extends Person> map, final double sample ) { final Random rnd = MatsimRandom.getLocalInstance(); log.warn( "Population downsampled from " + map.size() + " agents." ) ; map.values().removeIf( person -> rnd.nextDouble() > sample ) ; log.warn( "Population downsampled to " + map.size() + " agents." ) ; } }
13,855
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PlanTypeOverwriter.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/PlanTypeOverwriter.java
package org.matsim.legacy.run; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.api.core.v01.population.Person; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.Population; import org.matsim.core.controler.events.BeforeMobsimEvent; import org.matsim.core.controler.events.IterationStartsEvent; import org.matsim.core.controler.listener.BeforeMobsimListener; import org.matsim.core.controler.listener.IterationStartsListener; /** * Helper class to ensure the initial input selected plan is kept until the last iteration. Helps to ease issues when * learning speed between base case continued and drt policy cases is different. * * @author vsp-gleich */ class PlanTypeOverwriter implements BeforeMobsimListener, IterationStartsListener { private static final Logger log = LogManager.getLogger(RunBerlinScenario.class); static final String initialPlanType = "initial"; static final String modifiedPlanType = "modified"; private final BerlinExperimentalConfigGroup berlinExperimentalConfigGroup; private final Population population; PlanTypeOverwriter(BerlinExperimentalConfigGroup berlinExperimentalConfigGroup, Population population) { this.berlinExperimentalConfigGroup = berlinExperimentalConfigGroup; this.population = population; } @Override public void notifyBeforeMobsim(BeforeMobsimEvent beforeMobsimEvent) { /* * Unfortunately new modified plans from the replanning step have the same plan type as the original plan * from which they were created. But they are always the selected plan, so if there are 2 plans of type * "initial", the selected one is new and the unselected one is the real original initial plan. This feels * hacky, but seems to be the only possible way at the moment. vsp-gleich april'21 */ if (berlinExperimentalConfigGroup.getPlanTypeOverwriting().equals( BerlinExperimentalConfigGroup.PlanTypeOverwriting.TAG_INITIAL_SELECTED_PLAN_AND_MODIFIED_PLANS_DIFFERENTLY)) { for (Person person : population.getPersons().values()) { int countPlansTaggedInitialPlan = 0; for (Plan plan : person.getPlans()) { if (plan.getType().equals(initialPlanType)) { countPlansTaggedInitialPlan++; } } // if countPlansTaggedInitialPlan==1 do nothing, the only initial plan is the real initial plan if (countPlansTaggedInitialPlan == 2) { // rename the selected plan which has type "initial" but is not the initial plan person.getSelectedPlan().setType(modifiedPlanType); } else if (countPlansTaggedInitialPlan > 2) { log.error("More than two plans tagged initial plan for person " + person.getId().toString() + " this should not happen. Terminating."); throw new RuntimeException("\"More than two plans tagged initial plan for person " + person.getId().toString() + " this should not happen. Terminating."); } } } } @Override public void notifyIterationStarts(IterationStartsEvent iterationStartsEvent) { if (iterationStartsEvent.getIteration() == 0 && berlinExperimentalConfigGroup.getPlanTypeOverwriting().equals( BerlinExperimentalConfigGroup.PlanTypeOverwriting.TAG_INITIAL_SELECTED_PLAN_AND_MODIFIED_PLANS_DIFFERENTLY)) { population.getPersons().values().forEach(person -> person.getSelectedPlan().setType(initialPlanType)); } } }
3,779
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
BerlinExperimentalConfigGroup.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/BerlinExperimentalConfigGroup.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run; import java.util.Collection; import java.util.Collections; import com.google.common.collect.ImmutableSet; import org.matsim.core.config.ReflectiveConfigGroup; import org.matsim.core.utils.misc.StringUtils; /** * * @author ikaddoura */ public class BerlinExperimentalConfigGroup extends ReflectiveConfigGroup { public static final String GROUP_NAME = "berlinExperimental" ; private static final String POPULATION_DOWNSAMPLE_FACTOR = "populationDownsampleFactor"; private static final String TAG_DRT_LINKS_BUFFER_AROUND_SERVICE_AREA_SHP = "tagDrtLinksBufferAroundServiceAreaShp"; private static final String PLAN_TYPE_OVERWRITING = "planTypeOverwriting"; private static final String NETWORK_MODES_TO_ADD_TO_ALL_CAR_LINKS = "networkModesToAddToAllCarLinks"; private static final String ANALYSIS_LEVEL = "analysisLevel"; enum PlanTypeOverwriting {NO_OVERWRITE, TAG_INITIAL_SELECTED_PLAN_AND_MODIFIED_PLANS_DIFFERENTLY}; enum AnalysisLevel {MINIMAL, FULL} public BerlinExperimentalConfigGroup() { super(GROUP_NAME); } public BerlinExperimentalConfigGroup( boolean storeUnknownParametersAsStrings ){ super( GROUP_NAME, storeUnknownParametersAsStrings ) ; } private double populationDownsampleFactor = 1.0; private double tagDrtLinksBufferAroundServiceAreaShp = 2000.0; private PlanTypeOverwriting planTypeOverwriting = PlanTypeOverwriting.NO_OVERWRITE; private Collection<String> networkModesToAddToAllCarLinks = Collections.emptyList(); private AnalysisLevel analysisLevel = AnalysisLevel.MINIMAL; @StringGetter(POPULATION_DOWNSAMPLE_FACTOR) public double getPopulationDownsampleFactor() { return populationDownsampleFactor; } @StringSetter(POPULATION_DOWNSAMPLE_FACTOR) public void setPopulationDownsampleFactor(double populationDownsampleFactor) { this.populationDownsampleFactor = populationDownsampleFactor; } @StringGetter(TAG_DRT_LINKS_BUFFER_AROUND_SERVICE_AREA_SHP) public double getTagDrtLinksBufferAroundServiceAreaShp() { return tagDrtLinksBufferAroundServiceAreaShp; } @StringSetter(TAG_DRT_LINKS_BUFFER_AROUND_SERVICE_AREA_SHP) public void setTagDrtLinksBufferAroundServiceAreaShp(double tagDrtLinksBufferAroundServiceAreaShp) { this.tagDrtLinksBufferAroundServiceAreaShp = tagDrtLinksBufferAroundServiceAreaShp; } @StringGetter(PLAN_TYPE_OVERWRITING) public PlanTypeOverwriting getPlanTypeOverwriting () { return planTypeOverwriting; } @StringSetter(PLAN_TYPE_OVERWRITING) public void setPlanTypeOverwriting (PlanTypeOverwriting planTypeOverwriting) { this.planTypeOverwriting = planTypeOverwriting; } public Collection<String> getNetworkModesToAddToAllCarLinks() { return this.networkModesToAddToAllCarLinks; } @StringGetter(NETWORK_MODES_TO_ADD_TO_ALL_CAR_LINKS) public String getNetworkModesToAddToAllCarLinksAsString() { return String.join(",", networkModesToAddToAllCarLinks); } public void setNetworkModesToAddToAllCarLinks(Collection<String> networkModesToAddToAllCarLinks) { this.networkModesToAddToAllCarLinks = networkModesToAddToAllCarLinks; } @StringSetter(NETWORK_MODES_TO_ADD_TO_ALL_CAR_LINKS) public void setNetworkModesToAddToAllCarLinksAsString(String networkModesToAddToAllCarLinksString) { this.networkModesToAddToAllCarLinks = ImmutableSet.copyOf(StringUtils.explode(networkModesToAddToAllCarLinksString, ',')); } @StringGetter(ANALYSIS_LEVEL) public AnalysisLevel getAnalysisLevel () { return analysisLevel; } @StringSetter(ANALYSIS_LEVEL) public void setAnalysisLevel (AnalysisLevel analysisLevel) { this.analysisLevel = analysisLevel; } }
5,168
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunPtDisturbancesBerlin.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/ptdisturbances/RunPtDisturbancesBerlin.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.ptdisturbances; import static org.matsim.core.config.groups.ControllerConfigGroup.RoutingAlgorithmType.AStarLandmarks; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.inject.Provider; 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.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.api.core.v01.network.NetworkFactory; import org.matsim.api.core.v01.network.Node; import org.matsim.api.core.v01.population.Activity; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.Plan; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigGroup; import org.matsim.core.config.ConfigUtils; import org.matsim.core.config.groups.RoutingConfigGroup; import org.matsim.core.config.groups.ScoringConfigGroup.ActivityParams; import org.matsim.core.config.groups.ScoringConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup.TrafficDynamics; import org.matsim.core.config.groups.VspExperimentalConfigGroup; import org.matsim.core.controler.AbstractModule; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryLogging; import org.matsim.core.controler.OutputDirectoryHierarchy.OverwriteFileSetting; import org.matsim.core.gbl.Gbl; import org.matsim.core.mobsim.framework.MobsimAgent; import org.matsim.core.mobsim.qsim.AbstractQSimModule; import org.matsim.core.mobsim.qsim.InternalInterface; import org.matsim.core.mobsim.qsim.QSim; import org.matsim.core.mobsim.qsim.agents.WithinDayAgentUtils; import org.matsim.core.mobsim.qsim.components.QSimComponentsConfigGroup; import org.matsim.core.mobsim.qsim.interfaces.MobsimEngine; import org.matsim.core.mobsim.qsim.pt.TransitDriverAgentImpl; import org.matsim.core.network.NetworkChangeEvent; import org.matsim.core.network.NetworkUtils; import org.matsim.core.population.routes.NetworkRoute; import org.matsim.core.population.routes.RouteUtils; import org.matsim.core.network.NetworkChangeEvent.ChangeType; import org.matsim.core.network.NetworkChangeEvent.ChangeValue; import org.matsim.core.router.StageActivityTypeIdentifier; import org.matsim.core.router.TripRouter; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.core.utils.geometry.CoordUtils; import org.matsim.core.utils.timing.TimeInterpretation; import org.matsim.pt.config.TransitConfigGroup; import org.matsim.pt.router.TransitScheduleChangedEvent; import org.matsim.pt.routes.DefaultTransitPassengerRoute; import org.matsim.pt.transitSchedule.api.Departure; import org.matsim.pt.transitSchedule.api.TransitLine; import org.matsim.pt.transitSchedule.api.TransitRoute; import org.matsim.withinday.utils.EditTrips; import org.matsim.withinday.utils.ReplanningException; import com.google.inject.Inject; import ch.sbb.matsim.routing.pt.raptor.SwissRailRaptorModule; /** * @author smueller, ikaddoura */ public final class RunPtDisturbancesBerlin { private static final Logger log = LogManager.getLogger(RunPtDisturbancesBerlin.class ); public static void main(String[] args) { for (String arg : args) { log.info( arg ); } if ( args.length==0 ) { args = new String[] {"scenarios/berlin-v5.5-1pct/input/berlin-v5.5-1pct.config.xml"} ; } Config config = prepareConfig( args ) ; Scenario scenario = prepareScenario( config ) ; // NetworkChangeEvents are added so there are no U9 departures between 0730 and 0830. This ensures that no agent can use U9 in the disturbed period addNetworkChangeEvents( scenario ); Controler controler = prepareControler( scenario ) ; QSimComponentsConfigGroup qsimComponentsConfig = ConfigUtils.addOrGetModule(config, QSimComponentsConfigGroup.class); // the following requests that a component registered under the name "...NAME" // will be used: List<String> cmps = qsimComponentsConfig.getActiveComponents(); cmps.add(DisturbanceAndReplanningEngine.NAME); qsimComponentsConfig.setActiveComponents(cmps); controler.addOverridingQSimModule(new AbstractQSimModule() { @Override protected void configureQSim() { // the following registers the component under the name "...NAME": this.addQSimComponentBinding(DisturbanceAndReplanningEngine.NAME) .to(DisturbanceAndReplanningEngine.class); // bind(TransitStopHandlerFactory.class).to(SimpleTransitStopHandlerFactory.class); } }); controler.run() ; } private static void addNetworkChangeEvents(Scenario scenario) { { NetworkFactory networkFactory = scenario.getNetwork().getFactory(); Link oldFirstLink = scenario.getNetwork().getLinks().get(Id.createLinkId("pt_43431")); oldFirstLink.setFreespeed(50.); Node toNodeLink1 = oldFirstLink.getFromNode(); Node fromNodeLink1 = networkFactory.createNode(Id.createNodeId("dummyNodeRathausSteglitz1"), CoordUtils.createCoord(toNodeLink1.getCoord().getX() + 1000, toNodeLink1.getCoord().getY())); Node fromNodeLink0 = networkFactory.createNode(Id.createNodeId("dummyNodeRathausSteglitz0"), CoordUtils.createCoord(toNodeLink1.getCoord().getX() + 1010, toNodeLink1.getCoord().getY())); Link link1 = networkFactory.createLink(Id.createLinkId("dummyLinkRathausSteglitz1"), fromNodeLink1, toNodeLink1); link1.setAllowedModes(oldFirstLink.getAllowedModes()); link1.setFreespeed(999.); link1.setCapacity(oldFirstLink.getCapacity()); Link link0 = networkFactory.createLink(Id.createLinkId("dummyLinkRathausSteglitz0"), fromNodeLink0, fromNodeLink1); link0.setAllowedModes(oldFirstLink.getAllowedModes()); link0.setFreespeed(999.); link0.setCapacity(oldFirstLink.getCapacity()); scenario.getNetwork().addNode(fromNodeLink1); scenario.getNetwork().addNode(fromNodeLink0); scenario.getNetwork().addLink(link1); scenario.getNetwork().addLink(link0); TransitLine disturbedLine = scenario.getTransitSchedule().getTransitLines().get(Id.create("U9---17526_400", TransitLine.class)); for (TransitRoute transitRoute : disturbedLine.getRoutes().values()) { if (transitRoute.getRoute().getStartLinkId().equals(oldFirstLink.getId())) { List<Id<Link>> newRouteLinkIds = new ArrayList<>(); List<Id<Link>> oldRouteLinkIds = new ArrayList<>(); newRouteLinkIds.add(link0.getId()); newRouteLinkIds.add(link1.getId()); oldRouteLinkIds = transitRoute.getRoute().getLinkIds(); newRouteLinkIds.add(transitRoute.getRoute().getStartLinkId()); newRouteLinkIds.addAll(oldRouteLinkIds); newRouteLinkIds.add(transitRoute.getRoute().getEndLinkId()); NetworkRoute networkRoute = RouteUtils.createNetworkRoute(newRouteLinkIds, scenario.getNetwork()); transitRoute.setRoute(networkRoute); transitRoute.setRoute(networkRoute); } } NetworkChangeEvent networkChangeEvent1 = new NetworkChangeEvent(7.5*3600); // Link link = scenario.getNetwork().getLinks().get(Id.createLinkId("pt_43431")); networkChangeEvent1.setFreespeedChange(new ChangeValue(ChangeType.ABSOLUTE_IN_SI_UNITS, link1.getLength()/3600)); networkChangeEvent1.addLink(link1); NetworkUtils.addNetworkChangeEvent(scenario.getNetwork(), networkChangeEvent1); // NetworkChangeEvent networkChangeEvent2 = new NetworkChangeEvent(8.5*3600); // networkChangeEvent2.setFreespeedChange(new ChangeValue(ChangeType.ABSOLUTE_IN_SI_UNITS, 50. / 3.6)); // networkChangeEvent2.addLink(link1); // NetworkUtils.addNetworkChangeEvent(scenario.getNetwork(), networkChangeEvent2); } { NetworkFactory networkFactory = scenario.getNetwork().getFactory(); Link oldFirstLink = scenario.getNetwork().getLinks().get(Id.createLinkId("pt_43450")); oldFirstLink.setFreespeed(50.); Node toNodeLink1 = oldFirstLink.getFromNode(); Node fromNodeLink1 = networkFactory.createNode(Id.createNodeId("dummyNodeOslo1"), CoordUtils.createCoord(toNodeLink1.getCoord().getX() + 1000, toNodeLink1.getCoord().getY())); Node fromNodeLink0 = networkFactory.createNode(Id.createNodeId("dummyNodeOslo0"), CoordUtils.createCoord(toNodeLink1.getCoord().getX() + 1010, toNodeLink1.getCoord().getY())); Link link1 = networkFactory.createLink(Id.createLinkId("dummyLinkOslo1"), fromNodeLink1, toNodeLink1); link1.setAllowedModes(oldFirstLink.getAllowedModes()); link1.setFreespeed(999.); link1.setCapacity(oldFirstLink.getCapacity()); Link link0 = networkFactory.createLink(Id.createLinkId("dummyLinkOslo0"), fromNodeLink0, fromNodeLink1); link0.setAllowedModes(oldFirstLink.getAllowedModes()); link0.setFreespeed(999.); link0.setCapacity(oldFirstLink.getCapacity()); scenario.getNetwork().addNode(fromNodeLink1); scenario.getNetwork().addNode(fromNodeLink0); scenario.getNetwork().addLink(link1); scenario.getNetwork().addLink(link0); TransitLine disturbedLine = scenario.getTransitSchedule().getTransitLines().get(Id.create("U9---17526_400", TransitLine.class)); for (TransitRoute transitRoute : disturbedLine.getRoutes().values()) { if (transitRoute.getRoute().getStartLinkId().equals(oldFirstLink.getId())) { List<Id<Link>> newRouteLinkIds = new ArrayList<>(); List<Id<Link>> oldRouteLinkIds = new ArrayList<>(); newRouteLinkIds.add(link0.getId()); newRouteLinkIds.add(link1.getId()); oldRouteLinkIds = transitRoute.getRoute().getLinkIds(); newRouteLinkIds.add(transitRoute.getRoute().getStartLinkId()); newRouteLinkIds.addAll(oldRouteLinkIds); newRouteLinkIds.add(transitRoute.getRoute().getEndLinkId()); NetworkRoute networkRoute = RouteUtils.createNetworkRoute(newRouteLinkIds, scenario.getNetwork()); transitRoute.setRoute(networkRoute); transitRoute.setRoute(networkRoute); } } NetworkChangeEvent networkChangeEvent1 = new NetworkChangeEvent(7.5*3600); // Link link = scenario.getNetwork().getLinks().get(Id.createLinkId("pt_43431")); networkChangeEvent1.setFreespeedChange(new ChangeValue(ChangeType.ABSOLUTE_IN_SI_UNITS, link1.getLength()/3600)); networkChangeEvent1.addLink(link1); NetworkUtils.addNetworkChangeEvent(scenario.getNetwork(), networkChangeEvent1); // NetworkChangeEvent networkChangeEvent2 = new NetworkChangeEvent(8.5*3600); // networkChangeEvent2.setFreespeedChange(new ChangeValue(ChangeType.ABSOLUTE_IN_SI_UNITS, 50. / 3.6)); // networkChangeEvent2.addLink(link1); // NetworkUtils.addNetworkChangeEvent(scenario.getNetwork(), networkChangeEvent2); } } public static Controler prepareControler( Scenario scenario ) { // note that for something like signals, and presumably drt, one needs the controler object Gbl.assertNotNull(scenario); final Controler controler = new Controler( scenario ); if (controler.getConfig().transit().isUsingTransitInMobsim()) { // use the sbb pt raptor router controler.addOverridingModule( new AbstractModule() { @Override public void install() { install( new SwissRailRaptorModule() ); } } ); } else { log.warn("Public transit will be teleported and not simulated in the mobsim! " + "This will have a significant effect on pt-related parameters (travel times, modal split, and so on). " + "Should only be used for testing or car-focused studies with a fixed modal split. "); } // use the (congested) car travel time for the teleported ride mode controler.addOverridingModule( new AbstractModule() { @Override public void install() { addTravelTimeBinding( TransportMode.ride ).to( networkTravelTime() ); addTravelDisutilityFactoryBinding( TransportMode.ride ).to( carTravelDisutilityFactoryKey() ); } } ); return controler; } public static Scenario prepareScenario( Config config ) { Gbl.assertNotNull( config ); // note that the path for this is different when run from GUI (path of original config) vs. // when run from command line/IDE (java root). :-( See comment in method. kai, jul'18 // yy Does this comment still apply? kai, jul'19 final Scenario scenario = ScenarioUtils.loadScenario( config ); return scenario; } public static Config prepareConfig( String [] args, ConfigGroup... customModules ) { OutputDirectoryLogging.catchLogEntries(); String[] typedArgs = Arrays.copyOfRange( args, 1, args.length ); final Config config = ConfigUtils.loadConfig( args[ 0 ], customModules ); // I need this to set the context config.controller().setRoutingAlgorithmType( AStarLandmarks ); config.controller().setOverwriteFileSetting(OverwriteFileSetting.deleteDirectoryIfExists); config.controller().setLastIteration(0); config.transit().setBoardingAcceptance( TransitConfigGroup.BoardingAcceptance.checkStopOnly ); config.subtourModeChoice().setProbaForRandomSingleTripMode( 0.5 ); config.routing().setRoutingRandomness( 3. ); config.routing().removeModeRoutingParams(TransportMode.ride); config.routing().removeModeRoutingParams(TransportMode.pt); config.routing().removeModeRoutingParams(TransportMode.bike); config.routing().removeModeRoutingParams("undefined"); config.network().setTimeVariantNetwork(true); // TransportMode.non_network_walk has no longer a default, // in the long run: copy from walk; for now: use the parameter set given in the config (for backward compatibility) // ModeRoutingParams walkRoutingParams = config.routing().getOrCreateModeRoutingParams(TransportMode.walk); // ModeRoutingParams non_network_walk_routingParams = new ModeRoutingParams(TransportMode.non_network_walk); // non_network_walk_routingParams.setBeelineDistanceFactor(walkRoutingParams.getBeelineDistanceFactor()); // non_network_walk_routingParams.setTeleportedModeSpeed(walkRoutingParams.getTeleportedModeSpeed()); // config.routing().addModeRoutingParams(non_network_walk_routingParams); config.qsim().setInsertingWaitingVehiclesBeforeDrivingVehicles( true ); // vsp defaults config.vspExperimental().setVspDefaultsCheckingLevel( VspExperimentalConfigGroup.VspDefaultsCheckingLevel.info ); config.routing().setAccessEgressType(RoutingConfigGroup.AccessEgressType.accessEgressModeToLink); config.qsim().setUsingTravelTimeCheckInTeleportation( true ); config.qsim().setTrafficDynamics( TrafficDynamics.kinematicWaves ); // activities: for ( long ii = 600 ; ii <= 97200; ii+=600 ) { config.scoring().addActivityParams( new ActivityParams( "home_" + ii + ".0" ).setTypicalDuration( ii ) ); config.scoring().addActivityParams( new ActivityParams( "work_" + ii + ".0" ).setTypicalDuration( ii ).setOpeningTime(6. * 3600. ).setClosingTime(20. * 3600. ) ); config.scoring().addActivityParams( new ActivityParams( "leisure_" + ii + ".0" ).setTypicalDuration( ii ).setOpeningTime(9. * 3600. ).setClosingTime(27. * 3600. ) ); config.scoring().addActivityParams( new ActivityParams( "shopping_" + ii + ".0" ).setTypicalDuration( ii ).setOpeningTime(8. * 3600. ).setClosingTime(20. * 3600. ) ); config.scoring().addActivityParams( new ActivityParams( "other_" + ii + ".0" ).setTypicalDuration( ii ) ); } config.scoring().addActivityParams( new ActivityParams( "freight" ).setTypicalDuration( 12.*3600. ) ); ConfigUtils.applyCommandline( config, typedArgs ) ; return config ; } private static class DisturbanceAndReplanningEngine implements MobsimEngine { public static final String NAME = "disturbanceAndReplanningEngine"; @Inject private Scenario scenario; @Inject private EventsManager events; @Inject private Provider<TripRouter> tripRouterProvider; private InternalInterface internalInterface; @Override public void doSimStep(double now) { // replan after an affected bus has already departed -> pax on the bus are // replanned to get off earlier double replanTime = 7 * 3600 + 40 * 60; if ((int) now == replanTime - 1.) { // yyyyyy this needs to come one sec earlier. :-( // clear transit schedule from transit router provider: events.processEvent(new TransitScheduleChangedEvent(now)); } if ((int) now == replanTime) { // modify transit schedule: final Id<TransitLine> disturbedLineId = Id.create("U9---17526_400", TransitLine.class); TransitLine disturbedLine = scenario.getTransitSchedule().getTransitLines().get(disturbedLineId); Gbl.assertNotNull(disturbedLine); // TransitRoute disturbedRoute = disturbedLine.getRoutes().get(Id.create("U9---17526_400_0", TransitRoute.class)); // Gbl.assertNotNull(disturbedRoute); // // log.warn("before removal: nDepartures=" + disturbedRoute.getDepartures().size()); // // List<Departure> toRemove = new ArrayList<>(); // for (Departure departure : disturbedRoute.getDepartures().values()) { // if (departure.getDepartureTime() >= 7.5 * 3600. && departure.getDepartureTime() < 8.5 * 3600.) { // toRemove.add(departure); // } // } // for (Departure departure : toRemove) { // disturbedRoute.removeDeparture(departure); // } // // log.warn("after removal: nDepartures=" + disturbedRoute.getDepartures().size()); // for (TransitRoute route : disturbedLine.getRoutes().values()) { log.warn("before removal: nDepartures= " + route.getDepartures().size() + "--- Route: " + route.getId()); } List<Departure> toRemove = new ArrayList<>(); for (TransitRoute route : disturbedLine.getRoutes().values()) { for (Departure departure : route.getDepartures().values()) { if (departure.getDepartureTime() >= 7.5 * 3600 && departure.getDepartureTime() < 8.5 * 3600.) { toRemove.add(departure); } } } for (Departure departure : toRemove) { for (TransitRoute route : disturbedLine.getRoutes().values()) { if (route.getDepartures().containsValue(departure)) { route.removeDeparture(departure); } } } for (TransitRoute route : disturbedLine.getRoutes().values()) { log.warn("after removal: nDepartures= " + route.getDepartures().size() + "--- Route: " + route.getId()); } // // --- replanPtPassengers(now, disturbedLineId, tripRouterProvider, scenario, internalInterface); } } @Override public void onPrepareSim() { } @Override public void afterSim() { } @Override public void setInternalInterface(InternalInterface internalInterface) { this.internalInterface = internalInterface; } } static void replanPtPassengers(double now, final Id<TransitLine> disturbedLineId, Provider<TripRouter> tripRouterProvider, Scenario scenario, InternalInterface internalInterface) { final QSim qsim = internalInterface.getMobsim() ; // force new transit router: final TripRouter tripRouter = tripRouterProvider.get(); EditTrips editTrips = new EditTrips( tripRouter, scenario, internalInterface, TimeInterpretation.create(scenario.getConfig()) ); int currentTripsReplanned = 0; int futureTripsReplanned = 0; // find the affected agents and replan affected trips: for( MobsimAgent agent : (qsim).getAgents().values() ){ if( agent instanceof TransitDriverAgentImpl ){ /* This is a pt vehicle driver. TransitDriverAgentImpl does not support getModifiablePlan(...). So we should skip him. * This probably means that the driver continues driving the pt vehicle according to the old schedule. * However, this cannot be resolved by the editTrips.replanCurrentTrip() method anyway. */ continue; } Plan plan = WithinDayAgentUtils.getModifiablePlan( agent ); int currentPlanElementIndex = WithinDayAgentUtils.getCurrentPlanElementIndex( agent ); TripStructureUtils.Trip currentTrip; try{ currentTrip = editTrips.findCurrentTrip( agent ); } catch( ReplanningException e ){ // The agent might not be on a trip at the moment (but at a "real" activity). currentTrip = null; } Activity nextRealActivity = null; // would be nicer to use TripStructureUtils to find trips, but how can we get back to the original plan to modify it? for( int ii = currentPlanElementIndex ; ii < plan.getPlanElements().size() ; ii++ ){ PlanElement pe = plan.getPlanElements().get( ii ); // Replan each trip at maximum once, otherwise bad things might happen. // So we either have to keep track which Trip has already been re-planned // or move on manually to the next real activity after we re-planned. // Trips seem hard to identify, so try the latter approach. // Replanning the same trip twice could happen e.g. if first replanCurrentTrip is called and keeps or re-inserts // a leg with the disturbed line. So on a later plan element (higher ii) of the same trip replanCurrentTrip or // replanFutureTrip might be called. - gl, jul '19 if (nextRealActivity != null) { // we are trying to move on to the next trip in order not to replan twice the same trip if( pe instanceof Activity && nextRealActivity.equals((Activity) pe)) { nextRealActivity = null; } // continue to next pe if we still are on the trip we just replanned. continue; } else if( pe instanceof Leg ){ Leg leg = (Leg) pe; if( leg.getMode().equals( TransportMode.pt ) ){ DefaultTransitPassengerRoute transitRoute = (DefaultTransitPassengerRoute) leg.getRoute(); if( transitRoute.getLineId().equals( disturbedLineId ) ){ TripStructureUtils.Trip affectedTrip = editTrips.findTripAtPlanElement( agent, pe ); if( currentTrip != null && currentTrip.getTripElements().contains( pe ) ){ // current trip is disturbed log.warn(agent.getId()+";current"); editTrips.replanCurrentTrip( agent, now, TransportMode.pt ); currentTripsReplanned++; // break; } else { // future trip is disturbed log.warn(agent.getId()+";future"); editTrips.replanFutureTrip( affectedTrip, plan, TransportMode.pt ); futureTripsReplanned++; } nextRealActivity = affectedTrip.getDestinationActivity(); } } } } { // agents that abort their leg before boarding a vehicle need to be actively advanced: PlanElement pe = WithinDayAgentUtils.getCurrentPlanElement( agent ); if ( pe instanceof Activity ) { if ( StageActivityTypeIdentifier.isStageActivity( ((Activity) pe).getType() ) ){ internalInterface.arrangeNextAgentState( agent ); internalInterface.unregisterAdditionalAgentOnLink( agent.getId(), agent.getCurrentLinkId() ) ; } } // yyyyyy would be much better to hide this inside EditXxx. kai, jun'19 } } log.warn("Replanned " + currentTripsReplanned + " current trips"); log.warn("Replanned " + futureTripsReplanned + " future trips"); } }
24,107
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
PtAnalysisEventHandler.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/ptdisturbances/PtAnalysisEventHandler.java
/* *********************************************************************** * * project: org.matsim.* * EditRoutesTest.java * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.ptdisturbances; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.events.ActivityEndEvent; import org.matsim.api.core.v01.events.ActivityStartEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; import org.matsim.api.core.v01.events.handler.ActivityEndEventHandler; import org.matsim.api.core.v01.events.handler.ActivityStartEventHandler; import org.matsim.api.core.v01.events.handler.PersonEntersVehicleEventHandler; import org.matsim.api.core.v01.population.Person; import org.matsim.core.router.StageActivityTypeIdentifier; /** * @author smueller */ public class PtAnalysisEventHandler implements ActivityEndEventHandler, ActivityStartEventHandler, PersonEntersVehicleEventHandler { private static Map<Id<Person>, List<Event>> personMap = new HashMap<>(); @Override public void handleEvent(ActivityEndEvent event) { if (StageActivityTypeIdentifier.isStageActivity(event.getActType()) == false) { if (personMap.containsKey(event.getPersonId())) { List<Event> eventList = personMap.get(event.getPersonId()); eventList.add(event); } else { List<Event> eventList = new ArrayList<>(); eventList.add(event); personMap.putIfAbsent(event.getPersonId(), eventList ); } } } @Override public void handleEvent(ActivityStartEvent event) { if (StageActivityTypeIdentifier.isStageActivity(event.getActType()) == false) { List<Event> eventList = personMap.get(event.getPersonId()); eventList.add(event); } } @Override public void handleEvent(PersonEntersVehicleEvent event) { if (event.getPersonId().toString().startsWith("pt_pt") == false) { List<Event> eventList = personMap.get(event.getPersonId()); eventList.add(event); } } public static Map<Id<Person>, List<Event>> getPersonMap(){ return personMap; } }
3,356
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunEventAnalysis.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/ptdisturbances/RunEventAnalysis.java
/* *********************************************************************** * * project: org.matsim.* * EditRoutesTest.java * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.ptdisturbances; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; 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.events.ActivityStartEvent; import org.matsim.api.core.v01.events.Event; import org.matsim.api.core.v01.events.PersonEntersVehicleEvent; import org.matsim.api.core.v01.population.Person; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.events.EventsUtils; import org.matsim.core.events.MatsimEventsReader; /** * @author smueller */ public class RunEventAnalysis { private static final Logger log = LogManager.getLogger(RunEventAnalysis.class ); public static void main(String[] args) throws IOException { Map<Id<Person>, List<Event>> personMapBase = handleEvents("/Volumes/smueller_ssd/Replanning0800neu/berlin-drt-v5.5-10pct.output_events.xml"); writeTravelTimesToCSV(personMapBase); } private static Map<Id<Person>, List<Event>> handleEvents(String eventsFile) { EventsManager events = EventsUtils.createEventsManager(); PtAnalysisEventHandler ptAnalysisEventHandler = new PtAnalysisEventHandler(); events.addHandler(ptAnalysisEventHandler); MatsimEventsReader reader = new MatsimEventsReader(events); reader.readFile(eventsFile); Map<Id<Person>, List<Event>> personMap = PtAnalysisEventHandler.getPersonMap(); return personMap; } private static void writeTravelTimesToCSV(Map<Id<Person>, List<Event>> personMap) throws IOException { BufferedWriter bw; FileWriter fw = new FileWriter("Events.csv"); bw = new BufferedWriter(fw); bw.write("PersonId;TripIndex;PersonId+TripId;LegStartTime;LegEndTime;TravelTime;NextActType;LineChanges;Line1;Line2;Line3;Line4;Line5;Line6;Line7;Line8"); bw.newLine(); for (List<Event> eventList : personMap.values()) { double legStartTime = 0; double legEndTime = 0; boolean isPtTrip = false; int tripId = 0; List<String> vehicles = new ArrayList<>(); for (int ii = 0; ii < eventList.size(); ii++) { Event event = eventList.get(ii); if (event.getEventType().equals("actend")) { legStartTime = event.getTime(); tripId++; } if (event.getEventType().equals("PersonEntersVehicle")) { String vehicle = ((PersonEntersVehicleEvent) event).getVehicleId().toString(); vehicles.add(vehicle); if (vehicle.startsWith("pt")) { isPtTrip = true; } } if (event.getEventType().equals("actstart")) { legEndTime = event.getTime(); if(isPtTrip && legStartTime > 6. * 3600 && legStartTime < 10. * 3600) { // if(isPtTrip) { bw.write(((ActivityStartEvent) event).getPersonId().toString()); bw.write(";"); bw.write(String.valueOf(tripId)); bw.write(";"); bw.write(((ActivityStartEvent) event).getPersonId().toString()+"+"+String.valueOf(tripId)); bw.write(";"); bw.write(String.valueOf(legStartTime)); bw.write(";"); bw.write(String.valueOf(legEndTime)); bw.write(";"); bw.write(String.valueOf(legEndTime-legStartTime)); bw.write(";"); bw.write(((ActivityStartEvent) event).getActType().toString()); bw.write(";"); bw.write(String.valueOf(vehicles.size()-1)); bw.write(";"); if (vehicles != null) { for (int jj = 0; jj < vehicles.size(); jj++) { String[] lines = vehicles.get(jj).split("---"); bw.write(lines[0]); bw.write(";"); } } bw.newLine(); } legStartTime = 0; legEndTime= 0; vehicles.clear(); isPtTrip = false; } } bw.flush(); } bw.close(); log.info("done writing events to csv"); } }
5,200
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunDrtOpenBerlinScenario.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/drt/RunDrtOpenBerlinScenario.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.drt; import java.util.HashSet; import java.util.Set; import com.google.inject.Singleton; 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.TransportMode; import org.matsim.api.core.v01.network.Link; import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.drt.run.DrtConfigs; import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; import org.matsim.contrib.drt.run.MultiModeDrtModule; import org.matsim.contrib.dvrp.run.DvrpConfigGroup; import org.matsim.contrib.dvrp.run.DvrpModule; import org.matsim.contrib.dvrp.run.DvrpQSimComponents; import org.matsim.core.config.CommandLine; 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.Controler; import org.matsim.core.network.algorithms.MultimodalNetworkCleaner; import org.matsim.core.router.MainModeIdentifier; import org.matsim.core.scoring.functions.ScoringParametersForPerson; import org.matsim.extensions.pt.fare.intermodalTripFareCompensator.IntermodalTripFareCompensatorsConfigGroup; import org.matsim.extensions.pt.fare.intermodalTripFareCompensator.IntermodalTripFareCompensatorsModule; import org.matsim.extensions.pt.routing.ptRoutingModes.PtIntermodalRoutingModesConfigGroup; import org.matsim.extensions.pt.routing.ptRoutingModes.PtIntermodalRoutingModesModule; import org.matsim.legacy.run.BerlinExperimentalConfigGroup; import org.matsim.legacy.run.RunBerlinScenario; import org.matsim.pt.transitSchedule.api.TransitSchedule; import org.matsim.pt.transitSchedule.api.TransitStopFacility; import ch.sbb.matsim.config.SwissRailRaptorConfigGroup; import playground.vsp.scoring.IncomeDependentUtilityOfMoneyPersonScoringParameters; /** * This class starts a simulation run with DRT. * * - The input DRT vehicles file specifies the number of vehicles and the vehicle capacity (a vehicle capacity of 1 means there is no ride-sharing). * - The DRT service area is set to the the inner-city Berlin area (see input shape file). * - Initial plans only modified such that persons receive a specific income. * * @author ikaddoura */ public final class RunDrtOpenBerlinScenario { private static final Logger log = LogManager.getLogger(RunDrtOpenBerlinScenario.class); private static final String DRT_ACCESS_EGRESS_TO_PT_STOP_FILTER_ATTRIBUTE = "drtStopFilter"; private static final String DRT_ACCESS_EGRESS_TO_PT_STOP_FILTER_VALUE = "station_S/U/RE/RB_drtServiceArea"; public static void main(String[] args) throws CommandLine.ConfigurationException { for (String arg : args) { log.info( arg ); } if ( args.length==0 ) { args = new String[] {"scenarios/berlin-v5.5-1pct/input/drt/berlin-drt-v5.5-1pct.config.xml"} ; } Config config = prepareConfig( args ) ; Scenario scenario = prepareScenario( config ) ; Controler controler = prepareControler( scenario ) ; controler.run() ; } public static Controler prepareControler( Scenario scenario ) { Controler controler = RunBerlinScenario.prepareControler( scenario ) ; // drt + dvrp module controler.addOverridingModule(new MultiModeDrtModule()); controler.addOverridingModule(new DvrpModule()); controler.configureQSimComponents(DvrpQSimComponents.activateAllModes(MultiModeDrtConfigGroup.get(controler.getConfig()))); controler.addOverridingModule(new AbstractModule() { @Override public void install() { bind(MainModeIdentifier.class).to(OpenBerlinIntermodalPtDrtRouterModeIdentifier.class); //use income-dependent marginal utility of money for scoring bind(ScoringParametersForPerson.class).to(IncomeDependentUtilityOfMoneyPersonScoringParameters.class).in(Singleton.class); } }); // yyyy there is fareSModule (with S) in config. ?!?! kai, jul'19 controler.addOverridingModule(new IntermodalTripFareCompensatorsModule()); controler.addOverridingModule(new PtIntermodalRoutingModesModule()); return controler; } public static Scenario prepareScenario( Config config ) { Scenario scenario = RunBerlinScenario.prepareScenario( config ); BerlinExperimentalConfigGroup berlinCfg = ConfigUtils.addOrGetModule(config, BerlinExperimentalConfigGroup.class); for (DrtConfigGroup drtCfg : MultiModeDrtConfigGroup.get(config).getModalElements()) { String drtServiceAreaShapeFile = drtCfg.drtServiceAreaShapeFile; if (drtServiceAreaShapeFile != null && !drtServiceAreaShapeFile.equals("") && !drtServiceAreaShapeFile.equals("null")) { // Michal says restricting drt to a drt network roughly the size of the service area helps to speed up. // This is even more true since drt started to route on a freespeed TT matrix (Nov '20). // A buffer of 10km to the service area Berlin includes the A10 on some useful stretches outside Berlin. if(berlinCfg.getTagDrtLinksBufferAroundServiceAreaShp() >= 0.0) { addDRTmode(scenario, drtCfg.getMode(), drtServiceAreaShapeFile, berlinCfg.getTagDrtLinksBufferAroundServiceAreaShp()); } tagTransitStopsInServiceArea(scenario.getTransitSchedule(), DRT_ACCESS_EGRESS_TO_PT_STOP_FILTER_ATTRIBUTE, DRT_ACCESS_EGRESS_TO_PT_STOP_FILTER_VALUE, drtServiceAreaShapeFile, "stopFilter", "station_S/U/RE/RB", // some S+U stations are located slightly outside the shp File, e.g. U7 Neukoelln, U8 // Hermannstr., so allow buffer around the shape. // This does not mean that a drt vehicle can pick the passenger up outside the service area, // rather the passenger has to walk the last few meters from the drt drop off to the station. 200.0); // TODO: Use constant in RunGTFS2MATSimOpenBerlin and here? Or better some kind of set available pt modes? } } return scenario; } public enum AdditionalInformation { none, acceptUnknownParamsBerlinConfig } public static Config prepareConfig( AdditionalInformation additionalInformation, String [] args, ConfigGroup... customModules) { ConfigGroup[] customModulesToAdd = new ConfigGroup[] { new DvrpConfigGroup(), new MultiModeDrtConfigGroup(), new SwissRailRaptorConfigGroup(), new IntermodalTripFareCompensatorsConfigGroup(), new PtIntermodalRoutingModesConfigGroup() }; ConfigGroup[] customModulesAll = new ConfigGroup[customModules.length + customModulesToAdd.length]; int counter = 0; for (ConfigGroup customModule : customModules) { customModulesAll[counter] = customModule; counter++; } for (ConfigGroup customModule : customModulesToAdd) { customModulesAll[counter] = customModule; counter++; } Config config = RunBerlinScenario.prepareConfig( additionalInformation, args, customModulesAll ) ; DrtConfigs.adjustMultiModeDrtConfig(MultiModeDrtConfigGroup.get(config), config.scoring(), config.routing()); return config ; } public static Config prepareConfig( String [] args, ConfigGroup... customModules) { return prepareConfig( AdditionalInformation.none, args, customModules ) ; } public static void addDRTmode(Scenario scenario, String drtNetworkMode, String drtServiceAreaShapeFile, double buffer) { log.info("Adjusting network..."); BerlinShpUtils shpUtils = new BerlinShpUtils( drtServiceAreaShapeFile ); int counter = 0; int counterInside = 0; int counterOutside = 0; for (Link link : scenario.getNetwork().getLinks().values()) { if (counter % 10000 == 0) log.info("link #" + counter); counter++; if (link.getAllowedModes().contains(TransportMode.car)) { if (shpUtils.isCoordInDrtServiceAreaWithBuffer(link.getFromNode().getCoord(), buffer) || shpUtils.isCoordInDrtServiceAreaWithBuffer(link.getToNode().getCoord(), buffer)) { Set<String> allowedModes = new HashSet<>(link.getAllowedModes()); allowedModes.add(drtNetworkMode); link.setAllowedModes(allowedModes); counterInside++; } else { counterOutside++; } } else if (link.getAllowedModes().contains(TransportMode.pt)) { // skip pt links } else { throw new RuntimeException("Aborting..."); } } log.info("Total links: " + counter); log.info("Total links inside service area: " + counterInside); log.info("Total links outside service area: " + counterOutside); Set<String> modes = new HashSet<>(); modes.add(drtNetworkMode); new MultimodalNetworkCleaner(scenario.getNetwork()).run(modes); } private static void tagTransitStopsInServiceArea(TransitSchedule transitSchedule, String newAttributeName, String newAttributeValue, String drtServiceAreaShapeFile, String oldFilterAttribute, String oldFilterValue, double bufferAroundServiceArea) { log.info("Tagging pt stops marked for intermodal access/egress in the service area."); BerlinShpUtils shpUtils = new BerlinShpUtils( drtServiceAreaShapeFile ); for (TransitStopFacility stop: transitSchedule.getFacilities().values()) { if (stop.getAttributes().getAttribute(oldFilterAttribute) != null) { if (stop.getAttributes().getAttribute(oldFilterAttribute).equals(oldFilterValue)) { if (shpUtils.isCoordInDrtServiceAreaWithBuffer(stop.getCoord(), bufferAroundServiceArea)) { stop.getAttributes().putAttribute(newAttributeName, newAttributeValue); } } } } } }
10,694
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
OpenBerlinIntermodalPtDrtRouterModeIdentifier.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/drt/OpenBerlinIntermodalPtDrtRouterModeIdentifier.java
/* *********************************************************************** * * project: org.matsim.* * OpenBerlinIntermodalPtDrtRouterModeIdentifier.java * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.drt; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.matsim.analysis.TransportPlanningMainModeIdentifier; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.router.AnalysisMainModeIdentifier; import com.google.inject.Inject; /** * Based on {@link TransportPlanningMainModeIdentifier} * * @author nagel / gleich * */ public final class OpenBerlinIntermodalPtDrtRouterModeIdentifier implements AnalysisMainModeIdentifier { private final List<String> modeHierarchy = new ArrayList<>() ; private final List<String> drtModes; @Inject public OpenBerlinIntermodalPtDrtRouterModeIdentifier() { drtModes = Arrays.asList(TransportMode.drt, "drt2", "drt_teleportation"); modeHierarchy.add( TransportMode.walk ) ; modeHierarchy.add( "bicycle" ); // TransportMode.bike is not registered as main mode, only "bicycle" ; modeHierarchy.add( TransportMode.ride ) ; modeHierarchy.add( TransportMode.car ) ; modeHierarchy.add( "car2" ) ; for (String drtMode: drtModes) { modeHierarchy.add( drtMode ) ; } modeHierarchy.add( TransportMode.pt ) ; modeHierarchy.add( "freight" ); // NOTE: This hierarchical stuff is not so great: is park-n-ride a car trip or a pt trip? Could weigh it by distance, or by time spent // in respective mode. Or have combined modes as separate modes. In any case, can't do it at the leg level, since it does not // make sense to have the system calibrate towards something where we have counted the car and the pt part of a multimodal // trip as two separate trips. kai, sep'16 } @Override public String identifyMainMode( List<? extends PlanElement> planElements ) { int mainModeIndex = -1 ; for ( PlanElement pe : planElements ) { int index; String mode; if ( pe instanceof Leg ) { Leg leg = (Leg) pe ; mode = leg.getMode(); } else { continue; } if (mode.equals(TransportMode.non_network_walk)) { // skip, this is only a helper mode in case walk is routed on the network continue; } index = modeHierarchy.indexOf( mode ) ; if ( index < 0 ) { throw new RuntimeException("unknown mode=" + mode ) ; } if ( index > mainModeIndex ) { mainModeIndex = index ; } } if (mainModeIndex == -1) { throw new RuntimeException("no main mode found for trip " + planElements.toString() ) ; } return modeHierarchy.get( mainModeIndex ) ; } }
3,942
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
RunDrtOpenBerlinScenarioWithOptDrtAndModeCoverage.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/drt/RunDrtOpenBerlinScenarioWithOptDrtAndModeCoverage.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.drt; 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.population.Person; import org.matsim.contrib.drt.run.DrtConfigGroup; import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup; import org.matsim.contrib.drt.speedup.DrtSpeedUpParams; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.core.controler.Controler; import org.matsim.legacy.run.dynamicShutdown.DynamicShutdownConfigGroup; import org.matsim.legacy.run.dynamicShutdown.DynamicShutdownModule; import org.matsim.optDRT.MultiModeOptDrtConfigGroup; import org.matsim.optDRT.OptDrt; /** * @author ikaddoura */ public class RunDrtOpenBerlinScenarioWithOptDrtAndModeCoverage { private static final Logger log = LogManager.getLogger(RunDrtOpenBerlinScenarioWithOptDrtAndModeCoverage.class); public static void main(String[] args) { for (String arg : args) { log.info(arg); } if (args.length == 0) { args = new String[] { "scenarios/berlin-v5.5-1pct/input/drt/berlin-drt-v5.5-1pct.config.xml" }; } Config config = RunDrtOpenBerlinScenario.prepareConfig(args, new MultiModeOptDrtConfigGroup(), new DynamicShutdownConfigGroup()); for (DrtConfigGroup drtCfg : MultiModeDrtConfigGroup.get(config).getModalElements()) { if (drtCfg.getDrtSpeedUpParams().isEmpty()) { drtCfg.addParameterSet(new DrtSpeedUpParams()); } } Scenario scenario = RunDrtOpenBerlinScenario.prepareScenario(config); for (Person person : scenario.getPopulation().getPersons().values()) { person.getPlans().removeIf((plan) -> plan != person.getSelectedPlan()); } Controler controler = RunDrtOpenBerlinScenario.prepareControler(scenario); OptDrt.addAsOverridingModule(controler, ConfigUtils.addOrGetModule(scenario.getConfig(), MultiModeOptDrtConfigGroup.class)); controler.addOverridingModule(new DynamicShutdownModule()); controler.run() ; // RunBerlinScenario.runAnalysis(controler); } }
3,400
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/drt/OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier.java
/* *********************************************************************** * * project: org.matsim.* * OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier.java * * * *********************************************************************** * * * * copyright : (C) 2019 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.drt; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.matsim.analysis.TransportPlanningMainModeIdentifier; import org.matsim.api.core.v01.TransportMode; import org.matsim.api.core.v01.population.Leg; import org.matsim.api.core.v01.population.PlanElement; import org.matsim.core.router.AnalysisMainModeIdentifier; import com.google.inject.Inject; /** * Based on {@link TransportPlanningMainModeIdentifier} * * @author nagel / gleich * */ public final class OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier implements AnalysisMainModeIdentifier { private final List<String> modeHierarchy = new ArrayList<>() ; private final List<String> drtModes; private static final Logger log = LogManager.getLogger(OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier.class); public static final String ANALYSIS_MAIN_MODE_PT_WITH_DRT_USED_FOR_ACCESS_OR_EGRESS = "pt_w_drt_used"; @Inject public OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier() { drtModes = Arrays.asList(TransportMode.drt, "drt2", "drt_teleportation"); modeHierarchy.add( TransportMode.walk ) ; modeHierarchy.add( "bicycle" ); // TransportMode.bike is not registered as main mode, only "bicycle" ; modeHierarchy.add( TransportMode.ride ) ; modeHierarchy.add( TransportMode.car ) ; modeHierarchy.add( "car2" ) ; for (String drtMode: drtModes) { modeHierarchy.add( drtMode ) ; } modeHierarchy.add( TransportMode.pt ) ; modeHierarchy.add( "freight" ); // NOTE: This hierarchical stuff is not so great: is park-n-ride a car trip or a pt trip? Could weigh it by distance, or by time spent // in respective mode. Or have combined modes as separate modes. In any case, can't do it at the leg level, since it does not // make sense to have the system calibrate towards something where we have counted the car and the pt part of a multimodal // trip as two separate trips. kai, sep'16 } @Override public String identifyMainMode( List<? extends PlanElement> planElements ) { int mainModeIndex = -1 ; List<String> modesFound = new ArrayList<>(); for ( PlanElement pe : planElements ) { int index; String mode; if ( pe instanceof Leg ) { Leg leg = (Leg) pe ; mode = leg.getMode(); } else { continue; } if (mode.equals(TransportMode.non_network_walk)) { // skip, this is only a helper mode in case walk is routed on the network continue; } modesFound.add(mode); index = modeHierarchy.indexOf( mode ) ; if ( index < 0 ) { throw new RuntimeException("unknown mode=" + mode ) ; } if ( index > mainModeIndex ) { mainModeIndex = index ; } } if (mainModeIndex == -1) { throw new RuntimeException("no main mode found for trip " + planElements.toString() ) ; } String mainMode = modeHierarchy.get( mainModeIndex ) ; // differentiate pt monomodal/intermodal if (mainMode.equals(TransportMode.pt)) { boolean isDrtPt = false; for (String modeFound: modesFound) { if (modeFound.equals(TransportMode.pt)) { continue; } else if (modeFound.equals(TransportMode.walk)) { continue; } else if (drtModes.contains(modeFound)) { isDrtPt = true; } else { log.error("unknown intermodal pt trip: " + planElements.toString()); throw new RuntimeException("unknown intermodal pt trip"); } } if (isDrtPt) { return OpenBerlinIntermodalPtDrtRouterAnalysisModeIdentifier.ANALYSIS_MAIN_MODE_PT_WITH_DRT_USED_FOR_ACCESS_OR_EGRESS; } else { return TransportMode.pt; } } else { return mainMode; } } }
5,094
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z
KNVisOutputDrtOpenBerlinScenario.java
/FileExtraction/Java_unseen/matsim-scenarios_matsim-berlin/src/main/java/org/matsim/legacy/run/drt/KNVisOutputDrtOpenBerlinScenario.java
/* *********************************************************************** * * project: org.matsim.* * * * *********************************************************************** * * * * copyright : (C) 2017 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.legacy.run.drt; import java.util.ArrayList; import java.util.List; 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.population.Leg; import org.matsim.api.core.v01.population.Person; import org.matsim.contrib.drt.run.DrtControlerCreator; import org.matsim.contrib.otfvis.OTFVisLiveModule; 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.QSimConfigGroup; import org.matsim.core.config.groups.QSimConfigGroup.SnapshotStyle; import org.matsim.core.controler.Controler; import org.matsim.core.controler.OutputDirectoryHierarchy; import org.matsim.core.population.PopulationUtils; import org.matsim.core.router.TripStructureUtils; import org.matsim.core.scenario.ScenarioUtils; import org.matsim.vis.otfvis.OTFVisConfigGroup; /** * @author knagel */ public class KNVisOutputDrtOpenBerlinScenario { private static final Logger log = LogManager.getLogger( KNVisOutputDrtOpenBerlinScenario.class); public static void main(String[] args) { // final String base = "/Users/kainagel/mnt/mathe/ils3/leich/open-berlin/output/"; // final String runID="berlin-drt-v5.5-1pct_drt-132"; // final String base="/Users/kainagel/mnt/mathe/ils3/kaddoura/avoev-intermodal-routing/output/output-"; // final String runID="i89e"; final String base="/Users/kainagel/mnt/mathe/ils3/leich/open-berlin-intermodal-remove-buses/output/output-"; final String runID="B115b"; // Config config = RunDrtOpenBerlinScenario.prepareConfig( new String[] {"berlin-drt-v5.5-1pct_drt-114/berlin-drt-v5.5-1pct_drt-114.output_config.xml"} ) ; // Config config = RunDrtOpenBerlinScenario.prepareConfig( new String[] {"/Users/kainagel/mnt/mathe/ils3/leich/open-berlin/output/berlin-drt-v5" + // ".5-1pct_drt-132/berlin-drt-v5.5-1pct_drt-132.output_config_reduced.xml"} ) ; // yyyyyy todo do the above in a more flexible way! Config config = RunDrtOpenBerlinScenario.prepareConfig( RunDrtOpenBerlinScenario.AdditionalInformation.acceptUnknownParamsBerlinConfig, new String[] {base + runID + "/" + runID + ".output_config_reduced.xml"} ) ; config.network().setInputFile( config.controller().getRunId() + ".output_network.xml.gz" ); config.plans().setInputFile( config.controller().getRunId() + ".output_plans.xml.gz" ); // config.plans().setInputFile( "/Users/kainagel/git/berlin-matsim/popSel.xml.gz" ); config.transit().setTransitScheduleFile( config.controller().getRunId() + ".output_transitSchedule.xml.gz" ); config.global().setNumberOfThreads(6); config.controller() .setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists); config.controller().setLastIteration(0); final OTFVisConfigGroup otfVisConfigGroup = ConfigUtils.addOrGetModule(config, OTFVisConfigGroup.class); otfVisConfigGroup.setDrawTransitFacilityIds(false); otfVisConfigGroup.setDrawTransitFacilities(false); otfVisConfigGroup.setLinkWidth(10.f); //uncomment to enable drt-speed-up // for (DrtConfigGroup drtCfg : MultiModeDrtConfigGroup.get(config).getModalElements()) { // if (drtCfg.getDrtSpeedUpParams().isEmpty()) { // drtCfg.addParameterSet(new DrtSpeedUpParams()); // } // } for (final ScoringConfigGroup.ActivityParams params : config.scoring().getActivityParams()) { if (params.getActivityType().endsWith("interaction")) { params.setScoringThisActivityAtAll(false); } } config.qsim().setSnapshotStyle(SnapshotStyle.kinematicWaves); config.qsim().setTrafficDynamics(QSimConfigGroup.TrafficDynamics.kinematicWaves); config.transit().setUsingTransitInMobsim(true); // --- // Scenario scenario = RunDrtOpenBerlinScenario.prepareScenario( config ) ; Scenario scenario = DrtControlerCreator.createScenarioWithDrtRouteFactory( config ) ; ScenarioUtils.loadScenario( scenario ); // for ( final Person person : scenario.getPopulation().getPersons().values() ) { // person.getPlans().removeIf( (plan) -> !plan.equals( person.getSelectedPlan() ) ) ; // } // PopulationUtils.writePopulation( scenario.getPopulation(), "popWOnlySelectedPlans.xml.gz" ); List<Person> toRemove = new ArrayList<>() ; for ( final Person person : scenario.getPopulation().getPersons().values() ) { boolean containsDrt = false ; boolean containsPT = false ; for ( final Leg leg : TripStructureUtils.getLegs( person.getSelectedPlan() ) ) { if ( leg.getMode().contains( "drt" ) ) { containsDrt = true ; } if ( leg.getMode().contains( "pt" ) ) { containsPT = true ; } } if ( ! ( containsDrt /*&& containsPT*/ ) ) { toRemove.add( person ); } } log.warn( "population size before=" + scenario.getPopulation().getPersons().size() ); scenario.getPopulation().getPersons().values().removeAll( toRemove ) ; log.warn( "population size after=" + scenario.getPopulation().getPersons().size() ); PopulationUtils.writePopulation( scenario.getPopulation(), "popWOnlyDrtPtPlans.xml.gz" ); // --- Controler controler = RunDrtOpenBerlinScenario.prepareControler( scenario ) ; controler.addOverridingModule( new OTFVisLiveModule() ) ; // --- controler.run() ; } }
6,685
Java
.java
matsim-scenarios/matsim-berlin
28
111
2
2018-05-23T12:30:42Z
2024-05-07T19:56:36Z