package org.opentrafficsim.ahfe; import java.awt.Color; import java.io.BufferedWriter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.djunits.unit.FrequencyUnit; import org.djunits.unit.SpeedUnit; import org.djunits.unit.TimeUnit; import org.djunits.value.ValueRuntimeException; import org.djunits.value.storage.StorageType; import org.djunits.value.vdouble.scalar.Acceleration; import org.djunits.value.vdouble.scalar.Duration; import org.djunits.value.vdouble.scalar.Frequency; import org.djunits.value.vdouble.scalar.Length; import org.djunits.value.vdouble.scalar.Speed; import org.djunits.value.vdouble.vector.FrequencyVector; import org.djunits.value.vdouble.vector.TimeVector; import org.djunits.value.vdouble.vector.base.DoubleVector; import org.djutils.cli.CliException; import org.djutils.cli.CliUtil; import org.djutils.exceptions.Throw; import org.djutils.exceptions.Try; import org.djutils.io.URLResource; import org.opentrafficsim.base.CompressedFileWriter; import org.opentrafficsim.base.parameters.ParameterException; import org.opentrafficsim.base.parameters.ParameterSet; import org.opentrafficsim.base.parameters.ParameterTypeDouble; import org.opentrafficsim.base.parameters.ParameterTypeDuration; import org.opentrafficsim.base.parameters.ParameterTypes; import org.opentrafficsim.base.parameters.Parameters; import org.opentrafficsim.base.parameters.constraint.DualBound; import org.opentrafficsim.base.parameters.constraint.NumericConstraint; import org.opentrafficsim.core.animation.gtu.colorer.AccelerationGTUColorer; import org.opentrafficsim.core.animation.gtu.colorer.SpeedGTUColorer; import org.opentrafficsim.core.animation.gtu.colorer.SwitchableGTUColorer; import org.opentrafficsim.core.distributions.Distribution; import org.opentrafficsim.core.distributions.Distribution.FrequencyAndObject; import org.opentrafficsim.core.distributions.Generator; import org.opentrafficsim.core.distributions.ProbabilityException; import org.opentrafficsim.core.dsol.OTSSimulatorInterface; import org.opentrafficsim.core.gtu.AbstractGTU; import org.opentrafficsim.core.gtu.GTUException; import org.opentrafficsim.core.gtu.GTUType; import org.opentrafficsim.core.gtu.perception.DirectEgoPerception; import org.opentrafficsim.core.gtu.plan.operational.OperationalPlanException; import org.opentrafficsim.core.network.Node; import org.opentrafficsim.core.network.OTSNetwork; import org.opentrafficsim.core.parameters.ParameterFactoryByType; import org.opentrafficsim.core.perception.HistoryManagerDEVS; import org.opentrafficsim.core.units.distributions.ContinuousDistSpeed; import org.opentrafficsim.draw.core.OTSDrawingException; import org.opentrafficsim.draw.factory.DefaultAnimationFactory; import org.opentrafficsim.kpi.interfaces.LaneDataInterface; import org.opentrafficsim.kpi.sampling.KpiGtuDirectionality; import org.opentrafficsim.kpi.sampling.KpiLaneDirection; import org.opentrafficsim.kpi.sampling.SpaceTimeRegion; import org.opentrafficsim.kpi.sampling.data.ExtendedDataTypeNumber; import org.opentrafficsim.road.gtu.colorer.DesiredHeadwayColorer; import org.opentrafficsim.road.gtu.colorer.DesiredSpeedColorer; import org.opentrafficsim.road.gtu.colorer.FixedColor; import org.opentrafficsim.road.gtu.colorer.GTUTypeColorer; import org.opentrafficsim.road.gtu.colorer.IncentiveColorer; import org.opentrafficsim.road.gtu.colorer.ReactionTimeColorer; import org.opentrafficsim.road.gtu.colorer.SynchronizationColorer; import org.opentrafficsim.road.gtu.colorer.TaskColorer; import org.opentrafficsim.road.gtu.colorer.TaskSaturationColorer; import org.opentrafficsim.road.gtu.colorer.TotalDesireColorer; import org.opentrafficsim.road.gtu.generator.od.DefaultGTUCharacteristicsGeneratorOD; import org.opentrafficsim.road.gtu.generator.od.ODApplier; import org.opentrafficsim.road.gtu.generator.od.ODOptions; import org.opentrafficsim.road.gtu.generator.od.StrategicalPlannerFactorySupplierOD; import org.opentrafficsim.road.gtu.lane.CollisionDetector; import org.opentrafficsim.road.gtu.lane.CollisionException; import org.opentrafficsim.road.gtu.lane.LaneBasedGTU; import org.opentrafficsim.road.gtu.lane.perception.CategoricalLanePerception; import org.opentrafficsim.road.gtu.lane.perception.LanePerception; import org.opentrafficsim.road.gtu.lane.perception.PerceptionCollectable; import org.opentrafficsim.road.gtu.lane.perception.PerceptionFactory; import org.opentrafficsim.road.gtu.lane.perception.RelativeLane; import org.opentrafficsim.road.gtu.lane.perception.categories.AnticipationTrafficPerception; import org.opentrafficsim.road.gtu.lane.perception.categories.DirectInfrastructurePerception; import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.Anticipation; import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.DirectNeighborsPerception; import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.Estimation; import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.HeadwayGtuType.PerceivedHeadwayGtuType; import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.NeighborsPerception; import org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.TaskHeadwayCollector; import org.opentrafficsim.road.gtu.lane.perception.headway.HeadwayGTU; import org.opentrafficsim.road.gtu.lane.perception.mental.AbstractTask; import org.opentrafficsim.road.gtu.lane.perception.mental.AdaptationHeadway; import org.opentrafficsim.road.gtu.lane.perception.mental.AdaptationSituationalAwareness; import org.opentrafficsim.road.gtu.lane.perception.mental.Fuller; import org.opentrafficsim.road.gtu.lane.perception.mental.Fuller.BehavioralAdaptation; import org.opentrafficsim.road.gtu.lane.perception.mental.Task; import org.opentrafficsim.road.gtu.lane.perception.mental.TaskManager; import org.opentrafficsim.road.gtu.lane.tactical.following.AbstractIDM; import org.opentrafficsim.road.gtu.lane.tactical.following.CarFollowingModelFactory; import org.opentrafficsim.road.gtu.lane.tactical.following.DesiredSpeedModel; import org.opentrafficsim.road.gtu.lane.tactical.following.IDMPlus; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.AccelerationIncentive; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.DefaultLMRSPerceptionFactory; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveCourtesy; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveGetInLane; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveKeep; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveRoute; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSocioSpeed; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSpeed; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveSpeedWithCourtesy; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.IncentiveStayRight; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.LMRSFactory; import org.opentrafficsim.road.gtu.lane.tactical.lmrs.SocioDesiredSpeed; import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Cooperation; import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.GapAcceptance; import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.LmrsParameters; import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.MandatoryIncentive; import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Synchronization; import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Tailgating; import org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.VoluntaryIncentive; import org.opentrafficsim.road.gtu.strategical.LaneBasedStrategicalPlannerFactory; import org.opentrafficsim.road.gtu.strategical.od.Categorization; import org.opentrafficsim.road.gtu.strategical.od.Category; import org.opentrafficsim.road.gtu.strategical.od.Interpolation; import org.opentrafficsim.road.gtu.strategical.od.ODMatrix; import org.opentrafficsim.road.gtu.strategical.route.LaneBasedStrategicalRoutePlannerFactory; import org.opentrafficsim.road.network.OTSRoadNetwork; import org.opentrafficsim.road.network.factory.xml.parser.XmlNetworkLaneParser; import org.opentrafficsim.road.network.lane.CrossSectionLink; import org.opentrafficsim.road.network.sampling.GtuData; import org.opentrafficsim.road.network.sampling.LinkData; import org.opentrafficsim.road.network.sampling.RoadSampler; import org.opentrafficsim.road.network.sampling.data.LeaderId; import org.opentrafficsim.road.network.sampling.data.ReactionTime; import org.opentrafficsim.road.network.sampling.data.TimeToCollision; import org.opentrafficsim.swing.script.AbstractSimulationScript; import nl.tudelft.simulation.jstats.distributions.DistLogNormal; import nl.tudelft.simulation.jstats.distributions.DistNormal; import nl.tudelft.simulation.jstats.distributions.DistTriangular; import nl.tudelft.simulation.jstats.streams.StreamInterface; import picocli.CommandLine.Option; /** * Distraction simulation. *
* Copyright (c) 2013-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
* BSD-style license. See OpenTrafficSim License.
*
* @version $Revision$, $LastChangedDate$, by $Author$, initial version 9 apr. 2018
* Copyright (c) 2013-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
*
* @version $Revision$, $LastChangedDate$, by $Author$, initial version 9 apr. 2018
* @author Alexander Verbraeck
* @author Peter Knoppers
* @author Wouter Schakel
*/
public final class AnticipationRelianceScript extends AbstractSimulationScript
{
/** */
private static final long serialVersionUID = 20200516L;
/** Car-following task parameter. */
static final ParameterTypeDuration HEXP = new ParameterTypeDuration("Hexp",
"Exponential decay of car-following task by headway.", Duration.instantiateSI(4.0), NumericConstraint.POSITIVE);
/** Fraction of primary task that can be reduced by anticipation reliance. */
static final ParameterTypeDouble ALPHA = new ParameterTypeDouble("alpha",
"Fraction of primary task that can be reduced by anticipation reliance.", 0.8, DualBound.UNITINTERVAL);
/** Fraction of auxiliary tasks that can be reduced by anticipation reliance. */
static final ParameterTypeDouble BETA = new ParameterTypeDouble("beta",
"Fraction of auxiliary tasks that can be reduced by anticipation reliance.", 0.6, DualBound.UNITINTERVAL);
/** Distance to not consider at start of the network. */
private static Length ignoreStart = Length.instantiateSI(2900); // Not 100m on pre-link, so 3000 total
/** Distance to not consider at end of the network. */
private static Length ignoreEnd = Length.instantiateSI(1000);
/** Sampler. */
private RoadSampler sampler;
/** Truck fraction. */
@Option(names = {"-f", "--fTruck"}, description = "Truck fraction", defaultValue = "0.05")
private double fTruck;
/** Left demand. */
@Option(names = "--leftDemand", description = "Left demand", defaultValue = "3500/h")
private Frequency leftDemand;
/** Right demand. */
@Option(names = "--rightDemand", description = "Right demand", defaultValue = "3200/h")
private Frequency rightDemand;
/** Sampler. */
@Option(names = "--sampler", description = "Sampler", negatable = true, defaultValue = "false")
private boolean doSampler;
/** Sampler. */
@Option(names = "--scenario", description = "Scenario", defaultValue = "test")
private String scenario;
/** Output directory. */
@Option(names = "--outputDir", description = "Output directory", defaultValue = "")
private String outputDir;
/** Tasks. */
@Option(names = "--tasks", description = "Use tasks", negatable = true, defaultValue = "false")
private boolean tasks;
/** Strategies. */
@Option(names = "--strategies", description = "Use strategies", negatable = true, defaultValue = "false")
private boolean strategies;
/** Adaptation. */
@Option(names = "--adaptation", description = "Use adaptation", negatable = true, defaultValue = "false")
private boolean adaptation;
/** Alpha. */
@Option(names = "--alpha", description = "Alpha: maximum lane-change reduction", defaultValue = "0.8")
private double alpha;
/** Beta. */
@Option(names = "--beta", description = "Beta: maximum car-following reduction", defaultValue = "0.6")
private double beta;
/** Fraction of underestimation. */
@Option(names = "--fUnderestimate", description = "Fraction underestimation", defaultValue = "0.75")
private double fractionUnderestimation;
/**
* Main method.
* @param args String[]; command line arguments
*/
public static void main(final String... args)
{
// Long start = System.currentTimeMillis();
AnticipationRelianceScript script = new AnticipationRelianceScript();
if (script.isAutorun())
{
System.out.println("Running " + script.scenario + "_" + script.getSeed());
}
// script.setProperty("sampler", true);
// script.setProperty("autorun", false);
// script.setProperty("tasks", true);
// script.setProperty("strategies", false);
// script.setProperty("adaptation", false);
// script.setProperty("alpha", 0.0);
// script.setProperty("beta", 0.0);
try
{
CliUtil.execute(script, args); // XX from old version
script.start();
}
catch (Throwable throwable)
{
// Note: we only get here if we autorun
Throwable original = throwable;
while (throwable != null)
{
if (throwable instanceof CollisionException)
{
double tCollision = script.getSimulator().getSimulatorTime().si;
script.onSimulationEnd();
String file = script.getOutputFileStart() + "_collision.txt";
BufferedWriter writer = CompressedFileWriter.create(file, false);
try
{
writer.write(String.format("Collision at: %.6f", tCollision));
writer.newLine();
writer.write(throwable.getMessage());
writer.close();
}
catch (IOException ex)
{
System.err.println("Unable to write to file.");
}
System.exit(0);
}
throwable = throwable.getCause();
}
throw new RuntimeException(original);
}
}
/**
* Returns the start for output files, which can be amended with some name of contained data and extension.
* @return String; start for output files, which can be amended with some name of contained data and extension
*/
private String getOutputFileStart()
{
return this.outputDir + this.scenario + "_" + getSeed();
}
/**
* Constructor.
*/
private AnticipationRelianceScript()
{
super("Distraction", "Distraction simulation");
setGtuColorer(SwitchableGTUColorer.builder().addActiveColorer(new FixedColor(Color.BLUE, "Blue"))
.addColorer(new TaskColorer("car-following")).addColorer(new TaskColorer("lane-changing"))
.addColorer(new TaskSaturationColorer()).addColorer(new ReactionTimeColorer(Duration.instantiateSI(1.0)))
.addColorer(GTUTypeColorer.DEFAULT).addColorer(new SpeedGTUColorer(new Speed(150, SpeedUnit.KM_PER_HOUR)))
.addColorer(
new DesiredSpeedColorer(new Speed(50, SpeedUnit.KM_PER_HOUR), new Speed(150, SpeedUnit.KM_PER_HOUR)))
.addColorer(new AccelerationGTUColorer(Acceleration.instantiateSI(-6.0), Acceleration.instantiateSI(2)))
.addColorer(new SynchronizationColorer())
.addColorer(new DesiredHeadwayColorer(Duration.instantiateSI(0.56), Duration.instantiateSI(2.4)))
.addColorer(new TotalDesireColorer()).addColorer(new IncentiveColorer(IncentiveRoute.class))
.addColorer(new IncentiveColorer(IncentiveSpeedWithCourtesy.class))
.addColorer(new IncentiveColorer(IncentiveSpeed.class)).addColorer(new IncentiveColorer(IncentiveKeep.class))
.addColorer(new IncentiveColorer(IncentiveGetInLane.class))
.addColorer(new IncentiveColorer(IncentiveCourtesy.class))
.addColorer(new IncentiveColorer(IncentiveSocioSpeed.class)).build());
try
{
CliUtil.changeOptionDefault(this, "warmupTime", "360s");
CliUtil.changeOptionDefault(this, "simulationTime", "3960s");
}
catch (NoSuchFieldException | IllegalStateException | IllegalArgumentException | CliException exception)
{
throw new RuntimeException(exception);
}
}
/** {@inheritDoc} */
@Override
protected void onSimulationEnd()
{
if (this.sampler != null)
{
this.sampler.getSamplerData().writeToFile(getOutputFileStart() + ".csv");
}
}
/** {@inheritDoc} */
@Override
protected OTSRoadNetwork setupSimulation(final OTSSimulatorInterface sim) throws Exception
{
AbstractGTU.ALIGNED = true;
// Network
URL xmlURL = URLResource.getResource("/AHFE/Network.xml");
OTSRoadNetwork network = new OTSRoadNetwork("Distraction", true, sim);
new CollisionDetector(network); // XXX: is this needed here? was in old version...
XmlNetworkLaneParser.build(xmlURL, network, false);
// new Distraction("distraction", ((CrossSectionLink) network.getLink("END")).getLanes().get(0),
// Length.instantiateSI(1000),
// sim, new TrapezoidProfile(0.2, Length.instantiateSI(-400), Length.instantiateSI(200), Length.instantiateSI(400)));
// OD
List
* BSD-style license. See OpenTrafficSim License.
*
* @author Alexander Verbraeck
* @author Peter Knoppers
* @author Wouter Schakel
*/
private class DistractionFactorySupplier implements StrategicalPlannerFactorySupplierOD
{
/** Factory cars. */
private LaneBasedStrategicalRoutePlannerFactory factoryCar = null;
/** Factory trucks. */
private LaneBasedStrategicalRoutePlannerFactory factoryTruck = null;
/** */
DistractionFactorySupplier()
{
}
/** {@inheritDoc} */
@SuppressWarnings("synthetic-access")
@Override
public LaneBasedStrategicalPlannerFactory> getFactory(final Node origin, final Node destination,
final Category category, final StreamInterface randomStream) throws GTUException
{
OTSRoadNetwork network = (OTSRoadNetwork) origin.getNetwork();
if (this.factoryCar == null)
{
// car-following model, with different desired speed models
CarFollowingModelFactory