Dynamical system model
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, bool useCache=false, std::optional< unsigned int > seed=std::nullopt)
 Construct a new FirstOrderDynamics object.
void setErrorProbability (double errorProbability)
 Set the error probability.
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 setWeightFunction (PathWeight const pathWeight, std::optional< double > weightThreshold=std::nullopt)
 Set the weight function.
template<typename... TArgs>
void setSpeedFunction (SpeedFunction const speedFunction, TArgs &&... args)
 Set the speed function. Options are:
void setForcePriorities (bool forcePriorities) noexcept
 Set the force priorities flag.
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 setOriginNodes (std::unordered_map< Id, double > const &originNodes={})
 Set the origin nodes. If the provided map is empty, the origin nodes are set using the streets' stationary weights. NOTE: the default stationary weights are 1.0 so, if not set, this is equivalent to setting uniform weights.
void setDestinationNodes (std::unordered_map< Id, double > const &destinationNodes)
 Set the destination nodes.
void setDestinationNodes (std::initializer_list< Id > destinationNodes)
 Set the destination nodes.
void setODs (std::vector< std::tuple< Id, Id, double > > const &ODs)
 Set the origin-destination pairs with their associated weights.
template<typename TContainer>
void setDestinationNodes (TContainer const &destinationNodes)
 Set the destination nodes.
void initTurnCounts ()
 Initialize the turn counts map.
void resetTurnCounts ()
 Reset the turn counts map values to zero.
void saveData (std::time_t const savingInterval, bool const saveAverageStats=false, bool const saveStreetData=false, bool const saveTravelData=false)
 Enable data saving to the database.
void updatePaths (bool const throw_on_empty=true)
 Update the paths of the itineraries based on the given weight function.
void addAgentsUniformly (std::size_t nAgents, std::optional< Id > itineraryId=std::nullopt)
 Add agents uniformly on the road network.
void addAgent (std::unique_ptr< Agent > agent)
 Add an agent to the simulation.
template<typename... TArgs>
void addAgent (TArgs &&... args)
template<typename... TArgs>
void addAgents (std::size_t const nAgents, TArgs &&... args)
void addAgents (std::size_t const nAgents, AgentInsertionMethod const mode)
 Add agents to the simulation.
template<typename... TArgs>
void addItinerary (TArgs &&... args)
 Add an itinerary.
void addItinerary (std::shared_ptr< Itinerary > itinerary)
 Add an itinerary.
void evolve (bool const reinsert_agents=false)
 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.
auto const & itineraries () const noexcept
 Get the itineraries.
std::vector< std::tuple< Id, double > > const & originNodes () const noexcept
 Get the origin nodes of the graph.
std::vector< std::tuple< Id, double > > & originNodes () noexcept
 Get the origin nodes of the graph.
std::vector< std::tuple< Id, double > > const & destinationNodes () const noexcept
 Get the destination nodes of the graph.
std::vector< std::tuple< Id, double > > & destinationNodes () noexcept
 Get the destination nodes of the graph.
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.
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\).
std::unordered_map< Id, std::unordered_map< Id, size_t > > 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.
std::unordered_map< Id, std::array< long, 4 > > turnMapping () const
tbb::concurrent_unordered_map< Id, std::size_t > originCounts (bool const bReset=true) noexcept
 Get the origin counts of the agents.
tbb::concurrent_unordered_map< Id, std::size_t > destinationCounts (bool const bReset=true) noexcept
 Get the destination counts of the agents.
Measurement< double > streetMeanDensity (bool normalized=false) const
 Get the mean density of the streets in \(m^{-1}\).
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}\).
void summary (std::ostream &os=std::cout) const
 Print a summary of the dynamics to an output stream.
Public Member Functions inherited from dsf::Dynamics< RoadNetwork >
 Dynamics (RoadNetwork &graph, std::optional< unsigned int > seed=std::nullopt)
 Construct a new Dynamics object.
void setName (const std::string &name)
 Set the name of the simulation.
void setInitTime (std::time_t timeEpoch)
 Set the initial time as epoch time.
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).
void connectDataBase (std::string const &dbPath)
auto const & graph () const
 Get the graph.
auto const & id () const
 Get the id of the simulation.
auto const & name () const
 Get the name of the simulation.
auto const & database () const
 Get the database connection (const version).
auto time () const
 Get the current simulation time as epoch time.
auto time_step () const
 Get the current simulation time-step.
auto strDateTime () const
 Get the current simulation time as formatted string (YYYY-MM-DD HH:MM:SS).

Protected Attributes

std::unordered_map< Id, std::unordered_map< Id, size_t > > m_turnCounts
std::unordered_map< Id, std::array< long, 4 > > m_turnMapping
tbb::concurrent_unordered_map< Id, std::unordered_map< Direction, double > > m_queuesAtTrafficLights
tbb::concurrent_vector< std::pair< double, double > > m_travelDTs
std::time_t m_previousOptimizationTime {0}
std::function< double(std::unique_ptr< Street > const &)> m_weightFunction
std::optional< double > m_errorProbability {std::nullopt}
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
bool m_bCacheEnabled
PathWeight m_pathWeight = PathWeight::TRAVELTIME
double m_weightTreshold
std::optional< double > m_timeToleranceFactor {std::nullopt}
bool m_forcePriorities {false}
std::optional< std::time_t > m_savingInterval {std::nullopt}
bool m_bSaveStreetData {false}
bool m_bSaveTravelData {false}
bool m_bSaveAverageStats {false}
Protected Attributes inherited from dsf::Dynamics< RoadNetwork >
tbb::task_arena m_taskArena
std::mt19937_64 m_generator

Additional Inherited Members

Protected Member Functions inherited from dsf::Dynamics< RoadNetwork >
void m_evolve ()
auto m_safeDateTime () const
 Get a safe date-time string for filenames (YYYYMMDD_HHMMSS).
auto m_safeName () const
 Get a safe name string for filenames (spaces replaced by underscores).

Detailed Description

The FirstOrderDynamics class represents the dynamics of the network.

Constructor & Destructor Documentation

◆ FirstOrderDynamics()

dsf::mobility::FirstOrderDynamics::FirstOrderDynamics ( RoadNetwork & graph,
bool useCache = false,
std::optional< unsigned int > seed = std::nullopt )

Construct a new FirstOrderDynamics object.

Parameters
graphThe graph representing the network
useCacheIf true, the cache is used (default is false)
seedThe seed for the random number generator (default is std::nullopt)

Member Function Documentation

◆ addAgent()

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 > itineraryId = std::nullopt )

Add agents uniformly on the road network.

Parameters
nAgentsThe number of agents to add
itineraryIdThe id of the itinerary to use (default is std::nullopt)
Exceptions
std::runtime_errorIf there are no itineraries

◆ addItinerary() [1/2]

void dsf::mobility::FirstOrderDynamics::addItinerary ( std::shared_ptr< Itinerary > itinerary)

Add an itinerary.

Parameters
itinerarystd::unique_ptr to the itinerary
Exceptions
std::invalid_argumentIf the itinerary already exists
std::invalid_argumentIf the itinerary's destination is not a node of the graph

◆ addItinerary() [2/2]

template<typename... TArgs>
void dsf::mobility::FirstOrderDynamics::addItinerary ( TArgs &&... args)

Add an itinerary.

Parameters
...argsThe arguments to construct the itinerary

The arguments must be compatible with any constructor of the Itinerary class

◆ 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

◆ destinationCounts()

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

Get the destination counts of the agents.

Parameters
bResetIf true, the destination counts are cleared (default is true)

◆ destinationNodes() [1/2]

std::vector< std::tuple< Id, double > > const & dsf::mobility::FirstOrderDynamics::destinationNodes ( ) const
inlinenoexcept

Get the destination nodes of the graph.

Returns
std::vector<std::tuple<Id, double>> const& The destination nodes of the graph

◆ destinationNodes() [2/2]

std::vector< std::tuple< Id, double > > & dsf::mobility::FirstOrderDynamics::destinationNodes ( )
inlinenoexcept

Get the destination nodes of the graph.

Returns
std::vector<std::tuple<Id, double>>>& The destination nodes of the graph

◆ evolve()

void dsf::mobility::FirstOrderDynamics::evolve ( bool const reinsert_agents = false)

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 error probability is not zero, the agents can move to a random street. 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
    reinsert_agentsIf true, the agents are reinserted in the simulation after they reach their destination

◆ initTurnCounts()

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

Initialize the turn counts map.

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

◆ itineraries()

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

Get the itineraries.

Returns
const std::unordered_map<Id, Itinerary>&, The itineraries

◆ 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

◆ 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)
noexcept

Get the origin counts of the agents.

Parameters
bResetIf true, the origin counts are cleared (default is true)

◆ originNodes() [1/2]

std::vector< std::tuple< Id, double > > const & dsf::mobility::FirstOrderDynamics::originNodes ( ) const
inlinenoexcept

Get the origin nodes of the graph.

Returns
std::vector<std::tuple<Id, double>> const& The origin nodes of the graph

◆ originNodes() [2/2]

std::vector< std::tuple< Id, double > > & dsf::mobility::FirstOrderDynamics::originNodes ( )
inlinenoexcept

Get the origin nodes of the graph.

Returns
std::vector<std::tuple<Id, double>>& The origin nodes of the graph

◆ 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

◆ saveData()

void dsf::mobility::FirstOrderDynamics::saveData ( std::time_t const savingInterval,
bool const saveAverageStats = false,
bool const saveStreetData = false,
bool const saveTravelData = false )

Enable data saving to the database.

Parameters
savingIntervalThe interval at which save the data (in time steps). If zero, saves data at the next time step and then disables saving (working like a manual trigger).
saveAverageStatsIf true, saves the average stats of the simulation (default is false)
saveStreetDataIf true, saves the street data (default is false)
saveTravelDataIf true, saves the travel data of the agents (default is false)

◆ 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.

◆ setDestinationNodes() [1/3]

void dsf::mobility::FirstOrderDynamics::setDestinationNodes ( std::initializer_list< Id > destinationNodes)

Set the destination nodes.

Parameters
destinationNodesThe destination nodes (as an initializer list)

◆ setDestinationNodes() [2/3]

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

Set the destination nodes.

Parameters
destinationNodesThe destination nodes

◆ setDestinationNodes() [3/3]

template<typename TContainer>
void dsf::mobility::FirstOrderDynamics::setDestinationNodes ( TContainer const & destinationNodes)

Set the destination nodes.

Parameters
destinationNodesA container of destination nodes ids

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

◆ setErrorProbability()

void dsf::mobility::FirstOrderDynamics::setErrorProbability ( double errorProbability)

Set the error probability.

Parameters
errorProbabilityThe error probability
Exceptions
std::invalid_argumentIf the error probability is not between 0 and 1

◆ setForcePriorities()

void dsf::mobility::FirstOrderDynamics::setForcePriorities ( bool 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

◆ 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

◆ setODs()

void dsf::mobility::FirstOrderDynamics::setODs ( std::vector< std::tuple< Id, Id, double > > const & ODs)

Set the origin-destination pairs with their associated weights.

Parameters
ODsA vector of tuples (origin node id, destination node id, weight)

◆ setOriginNodes()

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

Set the origin nodes. If the provided map is empty, the origin nodes are set using the streets' stationary weights. NOTE: the default stationary weights are 1.0 so, if not set, this is equivalent to setting uniform weights.

Parameters
originNodesThe origin nodes

◆ 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

◆ 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 * density), where alpha is a parameter in [0, 1)
  • (CUSTOM, func): speed = func(pointer to a street), where func is a callable provided by the user that takes the street's pointer.

◆ setWeightFunction()

void dsf::mobility::FirstOrderDynamics::setWeightFunction ( PathWeight const pathWeight,
std::optional< double > weightThreshold = std::nullopt )

Set the weight function.

Parameters
pathWeightThe dsf::PathWeight function to use for the pathfinding
weightThresholdThe weight threshold for updating the paths (default is std::nullopt)

◆ streetMeanDensity()

Measurement< double > dsf::mobility::FirstOrderDynamics::streetMeanDensity ( bool normalized = false) const

Get the mean density of the streets in \(m^{-1}\).

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}\).

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}\).

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

◆ turnCounts()

std::unordered_map< Id, std::unordered_map< Id, size_t > > 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

◆ updatePaths()

void dsf::mobility::FirstOrderDynamics::updatePaths ( bool const throw_on_empty = true)

Update the paths of the itineraries based on the given weight function.

Parameters
throw_on_emptyIf true, throws an exception if an itinerary has an empty path (default is true) If false, removes the itinerary with empty paths and the associated node from the origin/destination nodes
Exceptions
std::runtime_errorif throw_on_empty is true and an itinerary has an empty path

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