Dynamical System Framework
Loading...
Searching...
No Matches
dsf::mobility::FirstOrderDynamics Class Reference

The FirstOrderDynamics class represents the dynamics of the network. More...

#include <FirstOrderDynamics.hpp>

Inheritance diagram for dsf::mobility::FirstOrderDynamics:
dsf::Dynamics< RoadNetwork >

Public Member Functions

 FirstOrderDynamics (RoadNetwork &&graph, std::optional< unsigned int > seed=std::nullopt, DynamicsMode const mode=DynamicsMode::EDGES)
 Construct a new FirstOrderDynamics object.
void prepareNetwork (bool const bAdjustNodeCapacities=true, bool const bAutoMapStreetLanes=false, bool const bAutoAssignRoadPriorities=true, bool const bAutoInitTrafficLights=true)
 Automatically prepare the network for the simulation. This method calls the following methods in order:
void setPassageProbability (double passageProbability)
 Set the passage probability.
void killStagnantAgents (double timeToleranceFactor=3.)
 Set the time tolerance factor for killing stagnant agents. An agent will be considered stagnant if it has not moved for timeToleranceFactor * std::ceil(street_length / street_maxSpeed) time units.
void saveData (std::time_t const savingInterval, bool const saveAverageStats=false, bool const saveStreetData=false, bool const saveTravelData=false, bool const saveAgentData=false)
 Enable data saving (compatibility wrapper; persistence is handled by TrafficSimulator).
template<typename... TArgs>
void setSpeedFunction (SpeedFunction const speedFunction, TArgs &&... args)
 Set the speed function. Options are:
void setForcePriorities (bool const forcePriorities) noexcept
 Set the force priorities flag.
void setAllowRandomUTurns (bool const allow) noexcept
 Let random agents take the U-turns of their transition-matrix row.
bool allowRandomUTurns () const noexcept
 Whether random agents take the U-turns of their transition-matrix row.
void setDataUpdatePeriod (Delay const dataUpdatePeriod) noexcept
 Set the data update period.
void setMeanTravelDistance (double const meanTravelDistance)
 Set the mean distance travelled by a random agent. The distance will be sampled from an exponential distribution with this mean.
void setMeanTravelTime (std::time_t const meanTravelTime) noexcept
 Set the mean travel time for random agents. The travel time will be sampled from an exponential distribution with this mean.
void setReinsertAgents (bool const reinsertAgents) noexcept
void setEdgeWeight (std::string_view const weight, double const distanceCost=0.1)
 Set the street costs intelligent agents plan their routes on.
void setPathRandomness (double const sigma)
 Set the path randomness.
void setRouteAlgorithm (RouteAlgorithm const algorithm) noexcept
 Set the algorithm the routes are planned with.
void setIntelligentAgentsFraction (double const intelligentFraction)
 Set the fraction of intelligent agents.
void setMode (DynamicsMode const mode)
 Set how origin, destination and OD ids are interpreted.
void setOrigins (std::unordered_map< Id, double > const &origins={})
 Set the origins.
void setDestinations (std::unordered_map< Id, double > const &destinations)
 Set the destinations.
void setDestinations (std::initializer_list< Id > destinations)
 Set the destinations, with uniform weights.
void setODs (std::vector< ODEntry > const &ODs)
 Set the origin-destination pairs with their associated weights.
void setConditionalODs (std::unordered_map< Id, ConditionalOrigin > const &originToDestinations)
 Set the origin-destination pairs with their associated weights from a map of origins to vectors of destinations and weights.
template<typename TContainer>
requires (std::is_convertible_v<typename TContainer::value_type, Id>)
void setDestinations (TContainer const &destinations)
 Set the destinations, with uniform weights.
void importODsFromCSV (std::string_view const fileName, char const separator=';')
 Import origin-destination pairs from a CSV file. Possibilities are:
void setTransitionMatrix (std::unordered_map< Id, std::unordered_map< Id, double > > const &transitionMatrix)
 Set the transition matrix used to route random agents.
void importTransitionMatrixFromJSON (std::string_view const fileName)
 Import the transition matrix used to route random agents from a JSON file.
void initTurnCounts ()
 Initialize the turn counts map.
void resetTurnCounts ()
 Reset the turn counts map values to zero.
void addAgentsUniformly (std::size_t nAgents, std::optional< Id > destinationId=std::nullopt)
 Add agents uniformly on the road network.
void addAgent (std::unique_ptr< Agent > agent)
 Add an agent to the simulation.
void addAgent (std::optional< Id > optDestinationId=std::nullopt, std::optional< Id > optSrcStreetId=std::nullopt)
 Add an agent to the simulation.
void addAgents (std::size_t const nAgents, AgentInsertionMethod const mode)
 Add agents to the simulation.
StepDataResult evolve (StepDataRequest const &dataRequest={})
 Evolve the simulation.
void optimizeTrafficLights (TrafficLightOptimization optimizationType=TrafficLightOptimization::DOUBLE_TAIL, const std::string &logFile=std::string(), double const percentage=0.3, double const threshold=1.3)
 Optimize the traffic lights by changing the green and red times.
Router const & router ()
 Get the router which plans the agents' routes.
auto intelligentAgentsFraction () const noexcept
 Get the fraction of intelligent agents, i.e. planning on the current traffic.
auto const & destinationStreets () const noexcept
 Get the destination streets of the origins, destinations and OD pairs.
auto mode () const noexcept
 Get how origin, destination and OD ids are interpreted.
auto const & origins () const noexcept
 Get the origins.
auto & origins () noexcept
 Get the origins.
auto const & destinations () const noexcept
 Get the destinations.
auto & destinations () noexcept
 Get the destinations.
auto const & transitionMatrix () const noexcept
 Get the transition matrix used to route random agents.
const std::vector< std::unique_ptr< Agent > > & agents () const noexcept
 Get the agents.
auto nAgents () const
 Get the number of agents currently in the simulation.
auto ghostAgents () const
 Get the number of ghost agents waiting to be inserted.
Measurement< double > meanTravelTime (bool clearData=false)
 Get the mean travel time of the agents in \(s\).
Measurement< double > meanTravelDistance (bool clearData=false)
 Get the mean travel distance of the agents in \(m\).
Measurement< double > meanTravelSpeed (bool clearData=false)
 Get the mean travel speed of the agents in \(m/s\).
TurnCountsDict const & turnCounts () const noexcept
 Get the turn counts of the agents.
std::unordered_map< Id, std::unordered_map< Id, double > > const normalizedTurnCounts () const noexcept
 Get the normalized turn counts of the agents.
tbb::concurrent_unordered_map< Id, std::size_t > originCounts (bool const bReset=true)
 Get the origin counts of the agents.
tbb::concurrent_unordered_map< Id, std::size_t > destinationCounts (bool const bReset=true)
 Get the destination counts of the agents.
template<bool Normalized>
Measurement< double > streetMeanDensity () const
 Get the mean density of the streets in \(m^{-1}\) or \(a.u.\) if Normalized.
Measurement< double > streetMeanFlow () const
 Get the mean flow of the streets in \(s^{-1}\).
Measurement< double > streetMeanFlow (double threshold, bool above) const
 Get the mean flow of the streets in \(s^{-1}\).
AgentStats agentStats () const noexcept
 Get agents stats from this Dynamics.
void summary (std::ostream &os=std::cout) const
 Print a summary of the dynamics to an output stream.
template<bool AllowTermination>
Street const * m_extractStreet (std::span< std::pair< Street const *, double > const > transitionProbabilities, double const cumulativeProbability, std::mt19937_64 &rng)
Public Member Functions inherited from dsf::Dynamics< RoadNetwork >
 Dynamics (RoadNetwork &&graph, std::optional< std::uint64_t > seed=std::nullopt)
 Construct a new Dynamics object.
void setSeed (std::uint64_t const seed)
 Set the seed for the random number generators.
void setConcurrency (std::size_t const concurrency)
 Set the maximum number of threads to use for parallel execution.
auto concurrency () const
 Get the current concurrency (number of threads configured in the task arena).
auto const & graph () const
 Get the graph.
auto time_step () const
 Get the current simulation time-step.

Protected Attributes

TurnCountsDict m_turnCounts
tbb::concurrent_unordered_map< Id, std::unordered_map< Direction, double > > m_queuesAtTrafficLights
tbb::concurrent_vector< TravelRecord > m_travelDTs
tbb::concurrent_vector< std::unique_ptr< Agent > > m_agentsToReinsert
std::time_t m_previousOptimizationTime {0}
std::optional< double > m_passageProbability {std::nullopt}
std::optional< double > m_meanTravelDistance {std::nullopt}
std::optional< std::time_t > m_meanTravelTime {std::nullopt}
std::optional< Delay > m_dataUpdatePeriod
std::optional< double > m_timeToleranceFactor {std::nullopt}
bool m_forcePriorities {false}
bool m_bAllowRandomUTurns {true}
Protected Attributes inherited from dsf::Dynamics< RoadNetwork >
std::unique_ptr< RoadNetwork > m_graph
tbb::task_arena m_taskArena
std::mt19937_64 m_generator
tbb::enumerable_thread_specific< std::mt19937_64 > m_threadGenerators

Additional Inherited Members

Protected Member Functions inherited from dsf::Dynamics< RoadNetwork >
void m_evolve ()
std::uint64_t seed () const noexcept
 Get the base seed of the random number generators.

Detailed Description

The FirstOrderDynamics class represents the dynamics of the network.

Constructor & Destructor Documentation

◆ FirstOrderDynamics()

dsf::mobility::FirstOrderDynamics::FirstOrderDynamics ( RoadNetwork && graph,
std::optional< unsigned int > seed = std::nullopt,
DynamicsMode const mode = DynamicsMode::EDGES )

Construct a new FirstOrderDynamics object.

Parameters
graphThe graph representing the network
seedThe seed for the random number generator (default is std::nullopt)
modeHow origin, destination and OD ids are interpreted (default is DynamicsMode::EDGES)

Member Function Documentation

◆ addAgent() [1/2]

void dsf::mobility::FirstOrderDynamics::addAgent ( std::optional< Id > optDestinationId = std::nullopt,
std::optional< Id > optSrcStreetId = std::nullopt )

Add an agent to the simulation.

Parameters
optDestinationIdThe id of the agent's destination street, whatever mode(): the agent travels it, and arrives at its end. If not provided, the agent is a random agent
optSrcStreetIdstd::optional<Id> representing the source street id. If not provided, the source node will be selected randomly.

◆ addAgent() [2/2]

void dsf::mobility::FirstOrderDynamics::addAgent ( std::unique_ptr< Agent > agent)

Add an agent to the simulation.

Parameters
agentstd::unique_ptr to the agent

◆ addAgents()

void dsf::mobility::FirstOrderDynamics::addAgents ( std::size_t const nAgents,
AgentInsertionMethod const mode )

Add agents to the simulation.

Parameters
nAgentsThe number of agents to add
modeThe method to use for adding the agents.Possible values are:
  • ODS: Agents are generated according to the provided OD pairs
  • RANDOM: Agents spwan randomly in the network and travel with no destination
  • RANDOM_ODS: Agents are generated by randomly selecting their origin and destination according to the weights

◆ addAgentsUniformly()

void dsf::mobility::FirstOrderDynamics::addAgentsUniformly ( std::size_t nAgents,
std::optional< Id > destinationId = std::nullopt )

Add agents uniformly on the road network.

Parameters
nAgentsThe number of agents to add
destinationIdThe id of the agents' destination street. If not provided, each agent gets a random one of destinationStreets(), or none (random agents) if it is empty
Exceptions
std::invalid_argumentIf the destination street does not exist

◆ agents()

const std::vector< std::unique_ptr< Agent > > & dsf::mobility::FirstOrderDynamics::agents ( ) const
inlinenoexcept

Get the agents.

Returns
const std::unordered_map<Id, Agent<Id>>&, The agents

◆ agentStats()

AgentStats dsf::mobility::FirstOrderDynamics::agentStats ( ) const
inlinenoexcept

Get agents stats from this Dynamics.

Returns
AgentStats The numbers of added, inserted, arrived, killed and current agents

◆ destinationCounts()

tbb::concurrent_unordered_map< Id, std::size_t > dsf::mobility::FirstOrderDynamics::destinationCounts ( bool const bReset = true)

Get the destination counts of the agents.

Parameters
bResetIf true, the destination counts are cleared (default is true)
Returns
The counts, keyed by destination street id (EDGES mode) or arrival node id (NODES mode)

◆ destinations() [1/2]

auto const & dsf::mobility::FirstOrderDynamics::destinations ( ) const
inlinenoexcept

Get the destinations.

Returns
std::vector<WeightedId> const& The destination street ids and their weights

◆ destinations() [2/2]

auto & dsf::mobility::FirstOrderDynamics::destinations ( )
inlinenoexcept

Get the destinations.

Returns
std::vector<WeightedId>& The destination street ids and their weights

◆ destinationStreets()

auto const & dsf::mobility::FirstOrderDynamics::destinationStreets ( ) const
inlinenoexcept

Get the destination streets of the origins, destinations and OD pairs.

Returns
std::unordered_set<Id> const& The destination street ids

◆ evolve()

StepDataResult dsf::mobility::FirstOrderDynamics::evolve ( StepDataRequest const & dataRequest = {})

Evolve the simulation.

Evolve the simulation by moving the agents and updating the travel times. In particular:

  • Move the first agent of each street queue, if possible, putting it in the next node
  • Move the agents from each node, if possible, putting them in the next street and giving them a speed. If the agent is in the destination node, it is removed from the simulation (and then reinserted if reinsert_agents is true)
  • Cycle over agents and update their times
    Parameters
    dataRequestThe save/collection request for the current step
    Returns
    StepDataResult The collected data for the current step

◆ ghostAgents()

auto dsf::mobility::FirstOrderDynamics::ghostAgents ( ) const
inline

Get the number of ghost agents waiting to be inserted.

Returns
std::size_t The number of ghost agents

◆ importODsFromCSV()

void dsf::mobility::FirstOrderDynamics::importODsFromCSV ( std::string_view const fileName,
char const separator = ';' )

Import origin-destination pairs from a CSV file. Possibilities are:

  • origin_id;destination_id;weight (for AgentInsertionMethod::ODS)
  • id;type;weight (for AgentInsertionMethod::RANDOM_ODS, where type is either "O" or "D")
  • id;o_prob;d_prob (for AgentInsertionMethod::RANDOM_ODS, compat format)
  • origin_id;weight;destinations (for AgentInsertionMethod::CONDITIONAL_RANDOM_ODS, where destinations is a comma-separated list of destination_id:weight pairs)

Ids are interpreted according to mode()

◆ importTransitionMatrixFromJSON()

void dsf::mobility::FirstOrderDynamics::importTransitionMatrixFromJSON ( std::string_view const fileName)

Import the transition matrix used to route random agents from a JSON file.

Parameters
fileNameThe path of the JSON file

The file must contain an object whose keys are the current street ids and whose values are objects mapping the candidate next street ids to their probabilities, e.g.:

{
"1042": { "1043": 0.6, "1055": 0.2 },
"1043": { "1080": 1.0 }
}

Rows are not required to sum to 1: the probability of ending the trip is always inferred at runtime as one minus the sum of the other probabilities. The imported matrix is then passed to setTransitionMatrix, which validates it.

Exceptions
std::runtime_errorIf the file cannot be parsed or has an invalid structure
std::invalid_argumentIf a key is not a valid street id, if a probability is negative or if a row sums up to more than 1

◆ initTurnCounts()

void dsf::mobility::FirstOrderDynamics::initTurnCounts ( )

Initialize the turn counts map.

Exceptions
std::runtime_errorif the turn counts map is already initialized

◆ intelligentAgentsFraction()

auto dsf::mobility::FirstOrderDynamics::intelligentAgentsFraction ( ) const
inlinenoexcept

Get the fraction of intelligent agents, i.e. planning on the current traffic.

Returns
double The fraction, in [0, 1]

◆ killStagnantAgents()

void dsf::mobility::FirstOrderDynamics::killStagnantAgents ( double timeToleranceFactor = 3.)

Set the time tolerance factor for killing stagnant agents. An agent will be considered stagnant if it has not moved for timeToleranceFactor * std::ceil(street_length / street_maxSpeed) time units.

Parameters
timeToleranceFactorThe time tolerance factor
Exceptions
std::invalid_argumentIf the time tolerance factor is not positive

◆ meanTravelDistance()

Measurement< double > dsf::mobility::FirstOrderDynamics::meanTravelDistance ( bool clearData = false)

Get the mean travel distance of the agents in \(m\).

Parameters
clearDataIf true, the travel distances are cleared after the computation
Returns
Measurement<double> The mean travel distance of the agents and the standard deviation

◆ meanTravelSpeed()

Measurement< double > dsf::mobility::FirstOrderDynamics::meanTravelSpeed ( bool clearData = false)

Get the mean travel speed of the agents in \(m/s\).

Parameters
clearDataIf true, the travel times and distances are cleared after the computation
Returns
Measurement<double> The mean travel speed of the agents and the standard deviation

◆ meanTravelTime()

Measurement< double > dsf::mobility::FirstOrderDynamics::meanTravelTime ( bool clearData = false)

Get the mean travel time of the agents in \(s\).

Parameters
clearDataIf true, the travel times are cleared after the computation
Returns
Measurement<double> The mean travel time of the agents and the standard deviation

◆ mode()

auto dsf::mobility::FirstOrderDynamics::mode ( ) const
inlinenoexcept

Get how origin, destination and OD ids are interpreted.

Returns
DynamicsMode The mode

◆ nAgents()

auto dsf::mobility::FirstOrderDynamics::nAgents ( ) const
inline

Get the number of agents currently in the simulation.

Returns
std::size_t The number of agents

◆ normalizedTurnCounts()

std::unordered_map< Id, std::unordered_map< Id, double > > const dsf::mobility::FirstOrderDynamics::normalizedTurnCounts ( ) const
noexcept

Get the normalized turn counts of the agents.

Returns
const std::unordered_map<Id, std::unordered_map<Id, double>>& The normalized turn counts. The outer map's key is the street id, the inner map's key is the next street id and the value is the normalized number of counts

◆ optimizeTrafficLights()

void dsf::mobility::FirstOrderDynamics::optimizeTrafficLights ( TrafficLightOptimization optimizationType = TrafficLightOptimization::DOUBLE_TAIL,
const std::string & logFile = std::string(),
double const percentage = 0.3,
double const threshold = 1.3 )

Optimize the traffic lights by changing the green and red times.

Parameters
optimizationTypeTrafficLightOptimization, The type of optimization. Default is DOUBLE_TAIL
logFileThe file into which write the logs (default is empty, meaning no logging)
percentagedouble, the maximum amount (percentage) of the green time to change (default is 0.3)
thresholddouble, The ratio between the self-density and neighbour density to trigger the non-local optimization (default is 1.3)

The local optimization is done by changing the green time of each traffic light, trying to make it proportional to the queue lengths at each phase. The non-local optimization is done by synchronizing the traffic lights which are congested over threshold.

◆ originCounts()

tbb::concurrent_unordered_map< Id, std::size_t > dsf::mobility::FirstOrderDynamics::originCounts ( bool const bReset = true)

Get the origin counts of the agents.

Parameters
bResetIf true, the origin counts are cleared (default is true)
Returns
The counts, keyed by origin street id (EDGES mode) or origin node id (NODES mode)

◆ origins() [1/2]

auto const & dsf::mobility::FirstOrderDynamics::origins ( ) const
inlinenoexcept

Get the origins.

Returns
std::vector<WeightedId> const& The origin street ids and their weights

◆ origins() [2/2]

auto & dsf::mobility::FirstOrderDynamics::origins ( )
inlinenoexcept

Get the origins.

Returns
std::vector<WeightedId>& The origin street ids and their weights

◆ prepareNetwork()

void dsf::mobility::FirstOrderDynamics::prepareNetwork ( bool const bAdjustNodeCapacities = true,
bool const bAutoMapStreetLanes = false,
bool const bAutoAssignRoadPriorities = true,
bool const bAutoInitTrafficLights = true )

Automatically prepare the network for the simulation. This method calls the following methods in order:

◆ resetTurnCounts()

void dsf::mobility::FirstOrderDynamics::resetTurnCounts ( )

Reset the turn counts map values to zero.

Exceptions
std::runtime_errorif the turn counts map is not initialized

◆ router()

Router const & dsf::mobility::FirstOrderDynamics::router ( )
inline

Get the router which plans the agents' routes.

The router is first rebuilt if the network has changed (see evolve)

Returns
Router const& The router

◆ setAllowRandomUTurns()

void dsf::mobility::FirstOrderDynamics::setAllowRandomUTurns ( bool const allow)
inlinenoexcept

Let random agents take the U-turns of their transition-matrix row.

Parameters
allowThe flag (default true: a U-turn entry of the transition matrix is kept as a normal entry and a random agent takes the U-turn with its probability)

With the flag unset, random agents never take a U-turn outside a roundabout: the U-turn entries of the transition matrix are redistributed over the row, like forbidden turns. It must be set before the transition matrix (setTransitionMatrix, importTransitionMatrixFromJSON), which validates the rows. Streets without a matrix row keep the uniform behaviour, which never takes a U-turn.

◆ setConditionalODs()

void dsf::mobility::FirstOrderDynamics::setConditionalODs ( std::unordered_map< Id, ConditionalOrigin > const & originToDestinations)

Set the origin-destination pairs with their associated weights from a map of origins to vectors of destinations and weights.

Parameters
originToDestinationsAn unordered map where the keys are origin ids and the values are the origin weights with their (destination id, weight) pairs, ids being interpreted according to mode()

◆ setDataUpdatePeriod()

void dsf::mobility::FirstOrderDynamics::setDataUpdatePeriod ( Delay const dataUpdatePeriod)
inlinenoexcept

Set the data update period.

Parameters
dataUpdatePeriodDelay, The period

Some data, i.e. the street queue lengths, are stored only after a fixed amount of time which is represented by this variable.

◆ setDestinations() [1/3]

void dsf::mobility::FirstOrderDynamics::setDestinations ( std::initializer_list< Id > destinations)

Set the destinations, with uniform weights.

Parameters
destinationsThe destination ids (as an initializer list), interpreted according to mode()

◆ setDestinations() [2/3]

void dsf::mobility::FirstOrderDynamics::setDestinations ( std::unordered_map< Id, double > const & destinations)

Set the destinations.

Parameters
destinationsThe destination ids and weights, ids being interpreted according to mode()

◆ setDestinations() [3/3]

template<typename TContainer>
requires (std::is_convertible_v<typename TContainer::value_type, Id>)
void dsf::mobility::FirstOrderDynamics::setDestinations ( TContainer const & destinations)

Set the destinations, with uniform weights.

Parameters
destinationsA container of destination ids, interpreted according to mode()

The container must have a value_type convertible to Id and begin() and end() methods

◆ setEdgeWeight()

void dsf::mobility::FirstOrderDynamics::setEdgeWeight ( std::string_view const weight,
double const distanceCost = 0.1 )

Set the street costs intelligent agents plan their routes on.

Parameters
weightThe name of the cost function (see Router::edgeWeightFunction), "traveltime" by default. With "datt" (detour-avoiding travel time), every agent, free-flow ones included, plans on (current or free-flow) travel time + k · length, with k = distanceCost
distanceCostThe distance cost of "datt", in s/m: 0.1 makes a metre cost as much as driving it at 36 km/h
Exceptions
std::invalid_argumentif distanceCost is negative

◆ setForcePriorities()

void dsf::mobility::FirstOrderDynamics::setForcePriorities ( bool const forcePriorities)
inlinenoexcept

Set the force priorities flag.

Parameters
forcePrioritiesThe flag

If true, if an agent cannot move to the next street, the whole node is skipped

◆ setIntelligentAgentsFraction()

void dsf::mobility::FirstOrderDynamics::setIntelligentAgentsFraction ( double const intelligentFraction)

Set the fraction of intelligent agents.

Parameters
intelligentFractionThe fraction, in [0, 1]

When it is added, each non-random agent is flagged as intelligent with this probability (default is 0, i.e. no intelligent agents). Every agent plans its route when it departs (see setRouteAlgorithm): intelligent agents on the current traffic, i.e. the street costs of setEdgeWeight, the others on the free-flow travel times (length / maxSpeed). Routes are not planned again, unless the agent meets a closed street: intelligent agents then use the street weights of the previous time step.

Exceptions
std::invalid_argumentIf the fraction is not in [0, 1]

◆ setMeanTravelDistance()

void dsf::mobility::FirstOrderDynamics::setMeanTravelDistance ( double const meanTravelDistance)
inline

Set the mean distance travelled by a random agent. The distance will be sampled from an exponential distribution with this mean.

Parameters
meanTravelDistanceThe mean distance
Exceptions
std::invalid_argumentIf the mean distance is negative

◆ setMeanTravelTime()

void dsf::mobility::FirstOrderDynamics::setMeanTravelTime ( std::time_t const meanTravelTime)
inlinenoexcept

Set the mean travel time for random agents. The travel time will be sampled from an exponential distribution with this mean.

Parameters
meanTravelTimeThe mean travel time

◆ setMode()

void dsf::mobility::FirstOrderDynamics::setMode ( DynamicsMode const mode)

Set how origin, destination and OD ids are interpreted.

Parameters
modeDynamicsMode::EDGES for street ids, DynamicsMode::NODES for node ids

In EDGES mode an agent starts from the source node of its origin street and travels it; it also travels its destination street, and arrives, and is removed, at its end. In NODES mode each node id is spread over the node's outgoing streets for an origin, and over its ingoing streets for a destination, with its weight split evenly among them: agents start from the node and arrive when they reach it. Nodes without such streets are skipped. The dynamics itself always works on streets, so origins(), destinations() and destinationStreets() hold street ids in both modes.

Exceptions
std::runtime_errorIf origins, destinations or OD pairs are already set

◆ setODs()

void dsf::mobility::FirstOrderDynamics::setODs ( std::vector< ODEntry > const & ODs)

Set the origin-destination pairs with their associated weights.

Parameters
ODsA vector of (origin id, destination id, weight) entries, ids being interpreted according to mode()

◆ setOrigins()

void dsf::mobility::FirstOrderDynamics::setOrigins ( std::unordered_map< Id, double > const & origins = {})

Set the origins.

Parameters
originsThe origin ids and weights, ids being interpreted according to mode(). If empty, all streets are used as origins with uniform weights.

◆ setPassageProbability()

void dsf::mobility::FirstOrderDynamics::setPassageProbability ( double passageProbability)

Set the passage probability.

Parameters
passageProbabilityThe passage probability

The passage probability is the probability of passing through a node It is useful in the case of random agents

◆ setPathRandomness()

void dsf::mobility::FirstOrderDynamics::setPathRandomness ( double const sigma)
inline

Set the path randomness.

Parameters
sigmaThe spread of the noise, 0 (the default) to plan without noise

Each agent perceives each street cost multiplied by its own log-normal noise of mean 1, exp(sigma · Z - sigma² / 2) (see Router::noise), the same at every re-plan: agents with the same trip spread over more routes, whatever the weight. Values between 0.1 and 0.5 are sensible

Exceptions
std::invalid_argumentif sigma is negative

◆ setRouteAlgorithm()

void dsf::mobility::FirstOrderDynamics::setRouteAlgorithm ( RouteAlgorithm const algorithm)
inlinenoexcept

Set the algorithm the routes are planned with.

Parameters
algorithmThe algorithm (A* by default, see RouteAlgorithm)

◆ setSpeedFunction()

template<typename... TArgs>
void dsf::mobility::FirstOrderDynamics::setSpeedFunction ( SpeedFunction const speedFunction,
TArgs &&... args )

Set the speed function. Options are:

  • (LINEAR, alpha): speed = max_speed * (1 - alpha * moving_density), where alpha is a parameter in [0, 1) and moving_density = n_moving_agents / capacity (queued agents cost queue time instead, see setEdgeWeight)
  • (CONSTANT): speed = max_speed, i.e. agents always travel in free flow
  • (CUSTOM, func): speed = func(pointer to a street), where func is a callable provided by the user that takes the street's pointer.

◆ setTransitionMatrix()

void dsf::mobility::FirstOrderDynamics::setTransitionMatrix ( std::unordered_map< Id, std::unordered_map< Id, double > > const & transitionMatrix)

Set the transition matrix used to route random agents.

Parameters
transitionMatrixThe transition matrix, i.e. a map whose outer key is the current street id, whose inner keys are the candidate next street ids and whose values are the corresponding probabilities

The probabilities of each row must sum up to at most 1: the missing mass is the probability that the agent ends its trip at that junction, which is inferred at runtime and must not be part of the given matrix. Streets which are not a key of the matrix keep the default uniform behaviour. Entries which cannot be used because the destination street is unknown or is not an outgoing edge of the source street's target node are dropped and reported as warnings, which reduces the row's total probability and thus increases the end probability accordingly. Forbidden turns are handled differently: since random agents can never take them, their probability is instead redistributed proportionally among the other entries of the same row, so that the end probability is unaffected by their weights. U-turn entries are kept as normal entries by default; with setAllowRandomUTurns(false), set before the matrix, they are redistributed like forbidden turns. If a row only contains forbidden-turn and/or U-turn entries, there is nothing to redistribute onto and the probability is dropped (reported as a warning) like any other unusable entry.

Exceptions
std::invalid_argumentIf a probability is negative or if a row sums up to more than 1

◆ streetMeanDensity()

template<bool Normalized>
Measurement< double > dsf::mobility::FirstOrderDynamics::streetMeanDensity ( ) const
inline

Get the mean density of the streets in \(m^{-1}\) or \(a.u.\) if Normalized.

Template Parameters
NormalizedIf true, the density is normalized by the street's capacity
Returns
Measurement<double> The mean density of the streets and the standard deviation

◆ streetMeanFlow() [1/2]

Measurement< double > dsf::mobility::FirstOrderDynamics::streetMeanFlow ( ) const

Get the mean flow of the streets in \(s^{-1}\).

The flow uses the speeds of the agents that left each street since the last data save (see evolve); reading it does not reset them.

Returns
Measurement<double> The mean flow of the streets and the standard deviation

◆ streetMeanFlow() [2/2]

Measurement< double > dsf::mobility::FirstOrderDynamics::streetMeanFlow ( double threshold,
bool above ) const

Get the mean flow of the streets in \(s^{-1}\).

Same speed samples as streetMeanFlow(); reading them does not reset them.

Parameters
thresholdThe density threshold to consider
aboveIf true, the function returns the mean flow of the streets with a density above the threshold, otherwise below
Returns
Measurement<double> The mean flow of the streets and the standard deviation

◆ summary()

void dsf::mobility::FirstOrderDynamics::summary ( std::ostream & os = std::cout) const

Print a summary of the dynamics to an output stream.

Parameters
osThe output stream to write to (default is std::cout)

The summary includes:

  • The RoadNetwork description (nodes, edges, capacity, intersections, traffic lights, roundabouts, coil sensors)
  • Number of inserted agents
  • Number of added agents
  • Number of arrived agents
  • Number of killed agents
  • Current number of agents in the simulation

◆ transitionMatrix()

auto const & dsf::mobility::FirstOrderDynamics::transitionMatrix ( ) const
inlinenoexcept

Get the transition matrix used to route random agents.

Returns
std::unordered_map<Id, std::unordered_map<Id, double>> const& The transition matrix. The outer key is the current street id, the inner key is the next street id and the value is the transition probability. It is empty if no transition matrix has been set.

◆ turnCounts()

TurnCountsDict const & dsf::mobility::FirstOrderDynamics::turnCounts ( ) const
inlinenoexcept

Get the turn counts of the agents.

Returns
const std::unordered_map<Id, std::unordered_map<Id, size_t>>& The turn counts. The outer map's key is the street id, the inner map's key is the next street id and the value is the number of counts

The documentation for this class was generated from the following files:
  • src/dsf/mobility/FirstOrderDynamics.hpp
  • src/dsf/mobility/FirstOrderDynamics.cpp