Context

Struct Context 

Source
pub struct Context { /* private fields */ }
Expand description

A manager for the state of a discrete-event simulation

Provides core simulation services including

  • Maintaining a notion of time
  • Scheduling events to occur at some point in the future and executing them at that time
  • Holding data that can be accessed by simulation modules

Simulations are constructed out of a series of interacting modules that take turns manipulating the Context through a mutable reference. Modules store data in the simulation using the DataPlugin trait that allows them to retrieve data by type.

The future event list of the simulation is a queue of Callback objects - called plans - that will assume control of the Context at a future point in time and execute the logic in the associated FnOnce(&mut Context) closure. Modules can add plans to this queue through the Context.

The simulation also has a separate callback mechanism. Callbacks fire before the next timed event (even if it is scheduled for the current time). This allows modules to schedule actions for immediate execution but outside of the current iteration of the event loop.

Modules can also emit ‘events’ that other modules can subscribe to handle by event type. This allows modules to broadcast that specific things have occurred and have other modules take turns reacting to these occurrences.

Implementations§

Source§

impl Context

Source

pub fn new() -> Context

Create a new empty Context

Source

pub fn schedule_debugger( &mut self, time: f64, priority: Option<ExecutionPhase>, callback: Box<dyn FnOnce(&mut Context)>, )

Schedule the simulation to pause at time t and start the debugger. This will give you a REPL which allows you to inspect the state of the simulation (type help to see a list of commands)

§Errors

Internal debugger errors e.g., reading or writing to stdin/stdout; errors in Ixa are printed to stdout

Source

pub fn subscribe_to_event<E: IxaEvent + Copy + 'static>( &mut self, handler: impl Fn(&mut Context, E) + 'static, )

Register to handle emission of events of type E

Handlers will be called upon event emission in order of subscription as queued Callbacks with the appropriate event.

Source

pub fn emit_event<E: IxaEvent + Copy + 'static>(&mut self, event: E)

Emit an event of type E to be handled by registered receivers

Receivers will handle events in the order that they have subscribed and are queued as callbacks

Source

pub fn add_plan( &mut self, time: f64, callback: impl FnOnce(&mut Context) + 'static, ) -> PlanId

Add a plan to the future event list at the specified time in the normal phase

Returns a PlanId for the newly-added plan that can be used to cancel it if needed.

§Panics

Panics if time is in the past, infinite, or NaN.

Source

pub fn add_plan_with_phase( &mut self, time: f64, callback: impl FnOnce(&mut Context) + 'static, phase: ExecutionPhase, ) -> PlanId

Add a plan to the future event list at the specified time and with the specified phase (first, normal, or last among plans at the specified time)

Returns a PlanId for the newly-added plan that can be used to cancel it if needed.

§Panics

Panics if time is in the past, infinite, or NaN.

Source

pub fn add_periodic_plan_with_phase( &mut self, period: f64, callback: impl Fn(&mut Context) + 'static, phase: ExecutionPhase, )

Add a plan with specified priority to the future event list, and continuously repeat the plan at the specified period, stopping only once there are no other plans scheduled.

Notes:

  • The first periodic plan is scheduled at time 0.0. If set_start_time was set to a positive value, this will currently panic because the first plan occurs before the start time (see issue #634 for future behavior).
§Panics

Panics if plan period is negative, infinite, or NaN.

Source

pub fn cancel_plan(&mut self, plan_id: &PlanId)

Cancel a plan that has been added to the queue

§Panics

This function panics if you cancel a plan which has already been cancelled or executed.

Source

pub fn queue_callback(&mut self, callback: impl FnOnce(&mut Context) + 'static)

Add a Callback to the queue to be executed before the next plan

Source

pub fn get_data_mut<T: DataPlugin>( &mut self, _data_plugin: T, ) -> &mut T::DataContainer

Retrieve a mutable reference to the data container associated with a DataPlugin

If the data container has not been already added to the Context then this function will use the DataPlugin::init method to construct a new data container and store it in the Context.

Returns a mutable reference to the data container

Source

pub fn get_data<T: DataPlugin>(&self, _data_plugin: T) -> &T::DataContainer

Retrieve a reference to the data container associated with a DataPlugin

Returns a reference to the data container if it exists or else None

Source

pub fn shutdown(&mut self)

Shutdown the simulation cleanly, abandoning all events after whatever is currently executing.

Source

pub fn get_current_time(&self) -> f64

Get the current simulation time

Returns the current time in the simulation. The behavior depends on execution state:

  • During execution: returns the time of the currently executing plan or callback
  • Before execution: returns the start time (if set via Context::set_start_time), or 0.0

The time can be negative if a negative start time was set before execution.

Source

pub fn set_start_time(&mut self, start_time: f64)

Set the start time for the simulation. Must be finite.

  • Call before Context.execute().
  • start_time must be finite (not NaN or infinite).
  • May be called only once.
  • If plans are already scheduled, start_time must be earlier than or equal to the earliest scheduled plan time.
§Panics

Panics if:

  • start_time is NaN or infinite.
  • the start time was already set.
  • Context::execute() has been called.
  • start_time is later than the earliest scheduled plan time.
Source

pub fn get_start_time(&self) -> Option<f64>

Get the start time that was set via set_start_time, or None if not set.

Source

pub fn request_debugger(&mut self)

Request to enter a debugger session at next event loop

Source

pub fn cancel_debugger_request(&mut self)

Request to enter a debugger session at next event loop

Source

pub fn disable_breakpoints(&mut self)

Disable breakpoints

Source

pub fn enable_breakpoints(&mut self)

Enable breakpoints

Source

pub fn breakpoints_are_enabled(&self) -> bool

Returns true if breakpoints are enabled.

Source

pub fn delete_breakpoint( &mut self, breakpoint_id: u64, ) -> Option<Box<dyn FnOnce(&mut Context)>>

Delete the breakpoint with the given ID

Source

pub fn list_breakpoints( &self, at_most: usize, ) -> Vec<&PlanSchedule<ExecutionPhase>>

Returns a list of length at_most, or unbounded if at_most=0, of active scheduled PlanSchedules ordered as they are in the queue itself.

Source

pub fn clear_breakpoints(&mut self)

Deletes all breakpoints.

Source

pub fn execute(&mut self)

Execute the simulation until the plan and callback queues are empty

Source

pub fn execute_single_step(&mut self)

Executes a single step of the simulation, prioritizing tasks as follows:

  1. Breakpoints
  2. Callbacks
  3. Plans
  4. Shutdown
Source

pub fn get_execution_statistics(&mut self) -> ExecutionStatistics

Trait Implementations§

Source§

impl ContextBase for Context

Source§

fn subscribe_to_event<E: IxaEvent + Copy + 'static>( &mut self, handler: impl Fn(&mut Context, E) + 'static, )

Source§

fn emit_event<E: IxaEvent + Copy + 'static>(&mut self, event: E)

Source§

fn add_plan( &mut self, time: f64, callback: impl FnOnce(&mut Context) + 'static, ) -> PlanId

Source§

fn add_plan_with_phase( &mut self, time: f64, callback: impl FnOnce(&mut Context) + 'static, phase: ExecutionPhase, ) -> PlanId

Source§

fn add_periodic_plan_with_phase( &mut self, period: f64, callback: impl Fn(&mut Context) + 'static, phase: ExecutionPhase, )

Source§

fn cancel_plan(&mut self, plan_id: &PlanId)

Source§

fn queue_callback(&mut self, callback: impl FnOnce(&mut Context) + 'static)

Source§

fn get_data_mut<T: DataPlugin>(&mut self, plugin: T) -> &mut T::DataContainer

Source§

fn get_data<T: DataPlugin>(&self, plugin: T) -> &T::DataContainer

Source§

fn get_current_time(&self) -> f64

Source§

fn get_execution_statistics(&mut self) -> ExecutionStatistics

Source§

impl ContextEntitiesExt for Context

Source§

fn add_entity<E: Entity, PL: PropertyList<E>>( &mut self, property_list: PL, ) -> Result<EntityId<E>, IxaError>

Source§

fn get_property<E: Entity, P: Property<E>>(&self, entity_id: EntityId<E>) -> P

Fetches the property value set for the given entity_id. Read more
Source§

fn set_property<E: Entity, P: Property<E>>( &mut self, entity_id: EntityId<E>, property_value: P, )

Sets the value of the given property. This method unconditionally emits a PropertyChangeEvent.
Source§

fn index_property<E: Entity, P: Property<E>>(&mut self)

Enables indexing of property values for the property P. Read more
Source§

fn index_property_counts<E: Entity, P: Property<E>>(&mut self)

Enables value-count indexing of property values for the property P. Read more
Source§

fn with_query_results<E: Entity, Q: Query<E>>( &self, query: Q, callback: &mut dyn FnMut(&IndexSet<EntityId<E>>), )

This method gives client code direct immutable access to the fully realized set of entity IDs. This is especially efficient for indexed queries, as this method reduces to a simple lookup of a hash bucket. Otherwise, the set is allocated and computed.
Source§

fn query_entity_count<E: Entity, Q: Query<E>>(&self, query: Q) -> usize

Gives the count of distinct entity IDs satisfying the query. This is especially efficient for indexed queries. Read more
Source§

fn sample_entity<E, Q, R>(&self, rng_id: R, query: Q) -> Option<EntityId<E>>
where E: Entity, Q: Query<E>, R: RngId + 'static, R::RngType: Rng,

Sample a single entity uniformly from the query results. Returns None if the query’s result set is empty. Read more
Source§

fn sample_entities<E, Q, R>( &self, rng_id: R, query: Q, n: usize, ) -> Vec<EntityId<E>>
where E: Entity, Q: Query<E>, R: RngId + 'static, R::RngType: Rng,

Sample up to requested entities uniformly from the query results. If the query’s result set has fewer than requested entities, the entire result set is returned. Read more
Source§

fn get_entity_count<E: Entity>(&self) -> usize

Returns a total count of all created entities of type E.
Source§

fn get_entity_iterator<E: Entity>(&self) -> PopulationIterator<E>

Returns an iterator over all created entities of type E.
Source§

fn query_result_iterator<E: Entity, Q: Query<E>>( &self, query: Q, ) -> EntitySetIterator<'_, E>

Generates an iterator over the results of the query.
Source§

fn match_entity<E: Entity, Q: Query<E>>( &self, entity_id: EntityId<E>, query: Q, ) -> bool

Determines if the given person matches this query.
Source§

fn filter_entities<E: Entity, Q: Query<E>>( &self, entities: &mut Vec<EntityId<E>>, query: Q, )

Removes all EntityIds from the given vector that do not match the given query.
Source§

impl ContextGlobalPropertiesExt for Context

Source§

fn get_serialized_value_by_string( &self, name: &str, ) -> Result<Option<String>, IxaError>

Return the serialized value of a global property by fully qualified name Read more
Source§

fn load_global_properties(&mut self, file_name: &Path) -> Result<(), IxaError>

Load global properties from a JSON file. Read more
Source§

fn set_global_property_value<T: GlobalProperty + 'static>( &mut self, property: T, value: T::Value, ) -> Result<(), IxaError>

Set the value of a global property of type T Read more
Source§

fn get_global_property_value<T: GlobalProperty + 'static>( &self, _property: T, ) -> Option<&T::Value>

Return value of global property T
Source§

fn list_registered_global_properties(&self) -> Vec<String>

Source§

fn load_parameters_from_json<T: 'static + Debug + DeserializeOwned>( &mut self, file_name: &Path, ) -> Result<T, IxaError>

Given a file path for a valid json file, deserialize parameter values for a given struct T Read more
Source§

impl ContextNetworkExt for Context

Source§

fn add_edge<E: Entity, ET: EdgeType<E>>( &mut self, entity_id: EntityId<E>, neighbor: EntityId<E>, weight: f32, inner: ET, ) -> Result<(), IxaError>

Add an edge of type ET between entity_id and neighbor with a given weight. Read more
Source§

fn add_edge_bidi<E: Entity, ET: EdgeType<E>>( &mut self, entity1: EntityId<E>, entity2: EntityId<E>, weight: f32, inner: ET, ) -> Result<(), IxaError>

Add a pair of edges of type ET between entity1 and entity2 with a given weight, one edge in each direction. This is syntactic sugar for calling add_edge twice. Read more
Source§

fn remove_edge<E: Entity, ET: EdgeType<E>>( &mut self, entity_id: EntityId<E>, neighbor: EntityId<E>, ) -> Option<Edge<E, ET>>

Remove the edge of type ET from entity_id to neighbor and return it, or None if the edge does not exist.
Source§

fn get_edge<E: Entity, ET: EdgeType<E>>( &self, entity_id: EntityId<E>, neighbor: EntityId<E>, ) -> Option<&Edge<E, ET>>

Get an edge of type ET from entity_id to neighbor if one exists.
Source§

fn get_edges<E: Entity, ET: EdgeType<E>>( &self, entity_id: EntityId<E>, ) -> Vec<Edge<E, ET>>

Get all outgoing edges of type ET from entity_id.
Source§

fn get_matching_edges<E: Entity, ET: EdgeType<E>>( &self, entity_id: EntityId<E>, filter: impl Fn(&Self, &Edge<E, ET>) -> bool, ) -> Vec<Edge<E, ET>>

Get all edges of type ET from entity_id that match the predicate provided in filter. Read more
Source§

fn find_entities_by_degree<E: Entity, ET: EdgeType<E>>( &self, degree: usize, ) -> Vec<EntityId<E>>

Find all entities who have an edge of type ET and degree degree.
Source§

fn select_random_edge<E: Entity, ET: EdgeType<E>, R: RngId + 'static>( &self, rng_id: R, entity_id: EntityId<E>, ) -> Result<Edge<E, ET>, IxaError>
where R::RngType: Rng,

Select a random outgoing edge of type ET from entity_id, weighted by the edge weights. Read more
Source§

impl ContextRandomExt for Context

Source§

fn init_random(&mut self, base_seed: u64)

Initializes the RngPlugin data container to store rngs as well as a base seed. Note that rngs are created lazily when get_rng is called.
Source§

fn sample<R: RngId + 'static, T>( &self, _rng_type: R, sampler: impl FnOnce(&mut R::RngType) -> T, ) -> T

Gets a random sample from the random number generator associated with the given RngId by applying the specified sampler function. If the Rng has not been used before, one will be created with the base seed you defined in set_base_random_seed. Note that this will panic if set_base_random_seed was not called yet.
Source§

fn sample_distr<R: RngId + 'static, T>( &self, _rng_type: R, distribution: impl Distribution<T>, ) -> T
where R::RngType: Rng,

Gets a random sample from the specified distribution using a random number generator associated with the given RngId. If the Rng has not been used before, one will be created with the base seed you defined in set_base_random_seed. Note that this will panic if set_base_random_seed was not called yet.
Source§

fn sample_range<R: RngId + 'static, S, T>(&self, rng_id: R, range: S) -> T
where R::RngType: Rng, S: SampleRange<T>, T: SampleUniform,

Gets a random sample within the range provided by range using the generator associated with the given RngId. Note that this will panic if set_base_random_seed was not called yet.
Source§

fn sample_bool<R: RngId + 'static>(&self, rng_id: R, p: f64) -> bool
where R::RngType: Rng,

Gets a random boolean value which is true with probability p using the generator associated with the given RngId. Note that this will panic if set_base_random_seed was not called yet.
Source§

fn sample_weighted<R: RngId + 'static, T>( &self, _rng_id: R, weights: &[T], ) -> usize

Draws a random entry out of the list provided in weights with the given weights using the generator associated with the given RngId. Note that this will panic if set_base_random_seed was not called yet.
Source§

impl ContextReportExt for Context

Source§

fn generate_filename(&mut self, short_name: &str) -> PathBuf

Source§

fn add_report_by_type_id( &mut self, type_id: TypeId, short_name: &str, ) -> Result<(), IxaError>

Add a report file keyed by a TypeId. The short_name is used for file naming to distinguish what data each output file points to. Read more
Source§

fn add_report<T: Report + 'static>( &mut self, short_name: &str, ) -> Result<(), IxaError>

Call add_report with each report type, passing the name of the report type. The short_name is used for file naming to distinguish what data each output file points to. Read more
Source§

fn get_writer(&self, type_id: TypeId) -> RefMut<'_, Writer<File>>

Source§

fn send_report<T: Report>(&self, report: T)

Write a new row to the appropriate report file
Source§

fn report_options(&mut self) -> &mut ConfigReportOptions

Returns a ConfigReportOptions object which has setter methods for report configuration
Source§

impl Default for Context

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl ProfilingContextExt for Context

Source§

fn print_execution_statistics(&mut self, include_profiling_data: bool)

Prints the execution statistics for this context to the console. Read more
Source§

fn write_profiling_data(&mut self)

Writes the execution statistics for the context and all profiling data to a JSON file.
Source§

impl PluginContext for Context

Auto Trait Implementations§

§

impl Freeze for Context

§

impl !RefUnwindSafe for Context

§

impl !Send for Context

§

impl !Sync for Context

§

impl Unpin for Context

§

impl !UnwindSafe for Context

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V