Probability Utilities

This module provides utilities for probability calculations and statistical operations in TBsim simulations.

Main Probabilities Module

class tbsim.utils.probabilities.Range(min: float, max: float, dist: str = 'uniform')[source]

Bases: object

Represents a numeric range for a named parameter with a probability distribution.

min

Lower bound or mean, depending on the distribution type.

Type:

float

max

Upper bound or standard deviation, depending on the distribution type.

Type:

float

dist

Distribution type: ‘uniform’, ‘normal’, or ‘lognormal’. Defaults to ‘uniform’.

Type:

str

min: float
max: float
dist: str = 'uniform'
validate()[source]

Validates the range configuration based on the distribution type.

Raises:

ValueError – If the range is improperly configured.

sample(size: int | tuple | None = None) float | ndarray[source]

Generate samples from the defined probability distribution.

Parameters:

size (int or tuple, optional) – Number of samples or shape of sample array.

Returns:

Sampled value(s).

Return type:

float or np.ndarray

__init__(min: float, max: float, dist: str = 'uniform') None
class tbsim.utils.probabilities.RangeDict[source]

Bases: object

Dictionary-like container for named probability ranges.

Provides both dictionary-style and attribute-style access to Range instances.

Example

ranges.activation.min ranges[“activation”].sample(10)

__init__()[source]
add(name: str, min_val: float, max_val: float, dist: str = 'uniform')[source]

Add a new named range.

Parameters:
  • name (str) – Name of the parameter.

  • min_val (float) – Minimum value or mean.

  • max_val (float) – Maximum value or standard deviation.

  • dist (str) – Distribution type. Defaults to ‘uniform’.

keys()[source]
items()[source]
values()[source]
to_dict() Dict[str, dict][source]

Convert the internal data to a plain dictionary.

Returns:

Dictionary with keys and serializable Range definitions.

Return type:

dict

class tbsim.utils.probabilities.Probability[source]

Bases: object

General-purpose class for managing and sampling from parameter ranges.

Supports:
  • Uniform, normal, and lognormal distributions

  • Loading from JSON, CSV, or Python dict

  • Dot-style and dict-style access

  • Export to JSON and CSV

__init__()[source]
from_dict(data: Dict[str, dict])[source]

Load probability ranges from a Python dictionary.

Format:
{

“param_name”: {“min”: 0.1, “max”: 0.9, “dist”: “uniform”}, …

}

Parameters:

data (dict) – Dictionary with named parameter configurations.

Raises:

ValueError – If required fields are missing or invalid.

from_json(filename: str)[source]

Load probability ranges from a JSON file and store them in self.values.

The JSON file must contain a dictionary where each key is the name of a probability parameter, and the value is a dictionary with at least:

  • min (float): Minimum value or mean (for normal/lognormal)

  • max (float): Maximum value or std dev (for normal/lognormal)

  • dist (str, optional): Distribution type (‘uniform’, ‘normal’, ‘lognormal’).

Defaults to ‘uniform’ if not provided.

Example JSON:
{

“activation”: {“min”: 0.5, “max”: 0.65}, “clearance”: {“min”: 1.3, “max”: 1.5, “dist”: “normal”}

}

Parameters:

filename (str) – Path to the JSON file.

Populates:

self.values (RangeDict): A dictionary-like object mapping each parameter name to a validated Range object that supports sampling and access via dot/dict notation.

Raises:
from_csv(filename: str)[source]

Load probability ranges from a CSV file and store them in self.values.

The CSV file must contain a header row with the following columns:
  • name (str): Identifier for each probability (e.g., ‘activation’).

  • min (float): Minimum value or mean (for normal/lognormal).

  • max (float): Maximum value or std dev (for normal/lognormal).

  • dist (str, optional): Distribution type (‘uniform’, ‘normal’, ‘lognormal’).

Defaults to ‘uniform’ if not provided.

Parameters:

filename (str) – Path to the input CSV file.

Populates:

self.values (RangeDict): A dictionary-like object mapping each parameter name to a validated Range object that supports sampling and access via dot/dict notation.

Raises:
  • FileNotFoundError – If the file is not found or cannot be opened.

  • ValueError – If the CSV is missing required columns or contains invalid data.

  • csv.Error – If the file format is malformed and cannot be parsed.

sample(name: str, size: int | tuple | None = None) float | ndarray[source]

Sample from the distribution for a specific parameter.

Parameters:
  • name (str) – Parameter name to sample.

  • size (int or tuple, optional) – Shape of the sampled output.

Returns:

Sampled value(s).

Return type:

float or np.ndarray

Raises:

KeyError – If the parameter is not found.

to_json(filename: str)[source]

Export current parameter ranges to a JSON file.

to_csv(filename: str)[source]

Export current parameter ranges to a CSV file.

Available Classes

Range

Class for managing probability ranges with min/max values and distributions

Probability

Class for handling probability values with various input formats

Key Features

  • Probability Management: Handle probability values and ranges

  • Distribution Support: Various probability distributions

  • Range Operations: Min/max probability bounds

  • Input Flexibility: Multiple input formats (dict, JSON, CSV)

  • Validation: Ensure probability values are valid

Usage Examples

Creating probability ranges:

from tbsim.utils.probabilities import Range

# Create range with min/max values
prob_range = Range(min=0.1, max=0.5)

# Create range with distribution
prob_range = Range(min=0.0, max=1.0, dist='uniform')

Working with probabilities:

from tbsim.utils.probabilities import Probability

# Create from dictionary
prob = Probability.from_dict({
    'value': 0.3,
    'uncertainty': 0.1
})

# Create from JSON file
prob = Probability.from_json('probabilities.json')

# Create from CSV
prob = Probability.from_csv('prob_data.csv')

Probability Operations

Range Properties
  • min: Minimum probability value

  • max: Maximum probability value

  • dist: Probability distribution type

Probability Methods
  • from_dict(): Create from dictionary input

  • from_json(): Create from JSON file

  • from_csv(): Create from CSV data

  • validate(): Check probability validity

Common Distributions
  • Uniform distribution

  • Normal distribution

  • Beta distribution

  • Custom distributions

These utilities help manage uncertainty and probability parameters in TBsim simulations.