Skip to content

laser.measles.base

laser.measles.base

Base classes for laser-measles components and models.

This module contains the base classes for laser-measles components and models.

The BaseComponent class is the base class for all laser-measles components. It provides a uniform interface for all components with a call(model, tick) method for execution during simulation loops.

The BaseLaserModel class is the base class for all laser-measles models.

laser.measles.base.BaseComponent(model, verbose=False, params=None)

Base class for all laser-measles components.

Components follow a uniform interface with call(model, tick) method for execution during simulation loops.

Initialize the component.

Parameters:

Name Type Description Default
model BaseLaserModel

The model instance this component belongs to.

required
verbose bool

Whether to enable verbose output. Defaults to False.

False

laser.measles.base.BaseComponent.__str__()

Return string representation using class docstring.

Returns:

Type Description
str

String representation of the component.

laser.measles.base.BaseComponent.plot(fig=None)

Placeholder for plotting method.

Parameters:

Name Type Description Default
fig Figure | None

Optional matplotlib figure to plot on.

None

Yields:

Name Type Description
None

Placeholder for plot objects.

laser.measles.base.BaseComponent.select_function(numpy_func, numba_func)

Select between numpy and numba implementations based on model configuration.

This method provides a convenient way for components to choose between numpy and numba implementations based on model parameters and environment variables.

Parameters:

Name Type Description Default
numpy_func Any

The numpy implementation function.

required
numba_func Any

The numba implementation function.

required

Returns:

Type Description
Any

The selected function implementation.

Example

In a component's init or _initialize method:

self.update_func = self.select_function(numpy_update, numba_update)

laser.measles.base.BaseLaserModel(scenario, params, name)

Bases: ABC

Base class for laser-measles simulation models.

Provides common functionality for model initialization, component management, timing, metrics collection, and execution loops.

Initialize the model with common attributes.

Parameters:

Name Type Description Default
scenario DataFrame | BaseScenario

Scenario data (type varies by model).

required
params BaseModelParams

Model parameters (type varies by model).

required
name str

Model name.

required

laser.measles.base.BaseLaserModel.components property writable

Retrieve the list of model components.

Returns:

Type Description
PrettyComponentsList

A PrettyComponentsList containing the components with enhanced formatting.

laser.measles.base.BaseLaserModel.__call__(model, tick) abstractmethod

Hook for subclasses to update the model for a given tick.

Parameters:

Name Type Description Default
model BaseLaserModel

The model instance.

required
tick int

The current time step or tick.

required

laser.measles.base.BaseLaserModel.__repr__()

Return a string representation of the model, showing key attributes.

Returns:

Name Type Description
str str

String representation of the model, including LaserFrame attributes.

laser.measles.base.BaseLaserModel.__str__()

Return a string representation of the model, showing key attributes.

laser.measles.base.BaseLaserModel.add_component(component)

Add the component class and an instance in model.instances.

Note that this does not create new instances of other components.

Parameters:

Name Type Description Default
component type[BaseComponent]

A component class to be initialized and integrated into the model.

required

laser.measles.base.BaseLaserModel.cleanup()

Clean up model resources to prevent memory leaks.

This method should be called when the model is no longer needed to free up memory from LaserFrame objects and other large data structures.

laser.measles.base.BaseLaserModel.get_component(cls)

Alias for get_instance (instances are instantiated, components are not).

Parameters:

Name Type Description Default
cls type | str

The component class to search for.

required

Returns:

Type Description
list

List of instances of the specified class, or [None] if none found.

laser.measles.base.BaseLaserModel.get_instance(cls)

Get all instances of a specific component class.

Parameters:

Name Type Description Default
cls type | str

The component class to search for.

required

Returns:

Type Description
list

List of instances of the specified class, or [None] if none found.

list

Works with inheritance - subclasses will match parent class searches.

Example

state_trackers = model.get_instance(StateTracker) if state_trackers: state_tracker = state_trackers[0] # Get first instance

laser.measles.base.BaseLaserModel.get_tick_date(tick)

Return the date for a given tick.

laser.measles.base.BaseLaserModel.plot(fig=None)

Placeholder for plotting method.

Parameters:

Name Type Description Default
fig Figure | None

Optional matplotlib figure to plot on.

None

Raises:

Type Description
NotImplementedError

Subclasses must implement this method.

laser.measles.base.BaseLaserModel.prepend_component(component)

Add a component to the beginning of the component list.

Parameters:

Name Type Description Default
component type[BaseComponent]

A component class to be initialized and integrated into the model.

required

laser.measles.base.BaseLaserModel.run()

Execute the model for a specified number of ticks, recording timing metrics.

laser.measles.base.BaseLaserModel.time_elapsed(units='days')

Return time elapsed since the start of the model.

Parameters:

Name Type Description Default
units str

Time units to return. Currently only supports "days" and "ticks".

'days'

Returns:

Type Description
int | float

Time elapsed in the specified units.

Raises:

Type Description
ValueError

If invalid time units are specified.

laser.measles.base.BaseLaserModel.visualize(pdf=True)

Visualize each component instances either by displaying plots or saving them to a PDF file.

Parameters:

Name Type Description Default
pdf bool

If True, save the plots to a PDF file. If False, display the plots interactively. Defaults to True.

True

Returns:

Type Description
None

None

laser.measles.base.BaseModelParams

Bases: BaseModel

Base parameter schema for all laser-measles simulation models.

This class defines configuration options that are common across all model variants. Subclasses must extend this class and implement model-specific properties.

Validation behavior

  • Extra/unknown fields are forbidden.
  • start_time must be a string in "YYYY-MM" format (year and month only).
  • num_ticks represents discrete simulation steps, not calendar days. The duration of each tick is determined by the subclass implementation of time_step_days.

Attributes:

Name Type Description
seed int

Random seed used to initialize all stochastic processes. Ensures reproducibility of simulation results.

start_time str

Simulation start time in "YYYY-MM" format (e.g., "2000-01"). Day values are not supported; the model assumes the first day of the given month unless otherwise defined by subclasses.

num_ticks int

Total number of discrete time steps to simulate. The total simulated duration equals: num_ticks x time_step_days

verbose bool

If True, prints detailed logging output during execution.

show_progress bool

If True, displays a progress bar during simulation runs.

use_numba bool

If True, enables numba JIT acceleration when available. Falls back to pure Python if numba is unavailable.

laser.measles.base.BaseModelParams.states property

List of model states. Must be implemented by subclasses.

laser.measles.base.BaseModelParams.time_step_days property

Time step in days. Must be implemented by subclasses.

laser.measles.base.BasePatchLaserFrame(capacity, initial_count=-1, **kwargs)

Bases: LaserFrame

LaserFrame that has a states property.

laser.measles.base.BasePeopleLaserFrame(capacity, initial_count=-1, **kwargs)

Bases: LaserFrame

Base class for people LaserFrames with enhanced printing capabilities.

This class provides factory methods for creating new instances with the same properties but different capacity, making it easy to resize people collections.

laser.measles.base.BasePeopleLaserFrame.copy_properties_from(source_frame)

Copy all properties from another LaserFrame instance.

This method copies all scalar and vector properties from the source frame, including their data types and default values.

Parameters:

Name Type Description Default
source_frame BasePeopleLaserFrame

The source LaserFrame to copy properties from.

required

laser.measles.base.BasePeopleLaserFrame.create_with_capacity(capacity, source_frame, initial_count=-1) classmethod

Create a new instance of the same type with specified capacity.

This factory method creates a new instance of the same class as the source_frame, with the specified capacity, and copies all properties from the source.

Parameters:

Name Type Description Default
capacity int

The capacity for the new LaserFrame.

required
source_frame BasePeopleLaserFrame

The source LaserFrame to copy properties from.

required
initial_count int

The initial number of "active" agents in the new frame. If -1, the count is set to the capacity. Defaults to -1.

-1

Returns:

Type Description
Any

A new instance of the same type with copied properties.

laser.measles.base.BasePhase(model, verbose=False, params=None)

Bases: BaseComponent

Base class for all laser-measles phases.

Phases are components that are called every tick and include a call method.

laser.measles.base.BasePhase.__call__(model, tick) abstractmethod

Execute component logic for a given simulation tick.

Parameters:

Name Type Description Default
model

The model instance.

required
tick int

The current simulation tick.

required

laser.measles.base.BaseScenario(df)

Bases: ABC

Base class for scenario data wrappers.

Provides a wrapper around polars DataFrames with additional validation and convenience methods.

Initialize the scenario with a DataFrame.

Parameters:

Name Type Description Default
df DataFrame

The polars DataFrame containing scenario data.

required

laser.measles.base.BaseScenario.__getattr__(attr)

Forward attribute access to the underlying DataFrame.

Parameters:

Name Type Description Default
attr

The attribute name.

required

Returns:

Type Description

The attribute value from the underlying DataFrame.

laser.measles.base.BaseScenario.__getitem__(key)

Forward item access to the underlying DataFrame.

Parameters:

Name Type Description Default
key

The key to access.

required

Returns:

Type Description

The value from the underlying DataFrame.

laser.measles.base.BaseScenario.__len__()

Return the length of the underlying DataFrame.

Returns:

Type Description

The number of rows in the DataFrame.

laser.measles.base.BaseScenario.__repr__()

Return string representation of the scenario.

Returns:

Type Description

String representation of the underlying DataFrame.

laser.measles.base.BaseScenario.find_row_number(column, target_value)

Find the row number (0-based index) of a target string in a DataFrame column.

Parameters:

Name Type Description Default
column str

Column name to search in.

required
target_value str

String value to find.

required

Returns:

Type Description
int

Row number (0-based index) of the target string.

Raises:

Type Description
ValueError

If the target string is not found.

laser.measles.base.BaseScenario.unwrap()

Return the underlying polars DataFrame.

Returns:

Type Description
DataFrame

The underlying polars DataFrame.

laser.measles.base.ParamsProtocol

Bases: Protocol

Protocol defining the expected structure of model parameters.