chainopy package¶
Subpackages¶
Submodules¶
chainopy._caching module¶
chainopy._exceptions module¶
chainopy._fileio module¶
chainopy._visualizations module¶
chainopy.markov_chain module¶
- class chainopy.markov_chain.MarkovChain(p=None, states=None)[source]¶
Bases:
objectA class containing Fundamental Functions for Discrete Time Markov Chains.
This class provides a comprehensive suite of methods for working with discrete-time Markov chains (DTMCs), including validation, simulation, and analysis functionalities. It supports learning transition probability matrices (TPMs) from data, checking various properties of the Markov chain (e.g., ergodicity, aperiodicity, symmetry), and computing distributions and probabilities related to the chain’s behavior over time.
- tpm¶
Transition probability matrix (TPM) representing the Markov chain.
- Type:
np.ndarray
- eigenvalues¶
Eigenvalues of the TPM.
- Type:
np.ndarray
- eigenvectors¶
Eigenvectors of the TPM.
- Type:
np.ndarray
- absorption_probabilities()[source]¶
Returns the absorption probabilities matrix for each state.
- Return type:
- Returns:
ndarray: Absorption probabilities matrix.
- eigendecom¶
- eigenvalues¶
- eigenvectors¶
- epsilon¶
- expected_hitting_time(state)[source]¶
Returns the expected hitting time to reach the given absorbing state.
- expected_number_of_visits()[source]¶
Returns the expected number of visits to each state before absorption.
- Return type:
- Returns:
ndarray: Expected number of visits.
- expected_time_to_absorption()[source]¶
Returns the expected time to absorption for each state.
- Return type:
- Returns:
ndarray: Expected time to absorption.
- fit(data, epsilon=1e-16)[source]¶
Learn Transition Matrix from Sequence (list or str) of Data. Each Unique Word is considered a State. It will override the current transition-matrix.
- Parameters:
- Return type:
- Returns:
ndarray: Transition - Matrix based on data
Usage
—– – >>> chainopy.MarkovChain().fit(“My name is John.”)
- is_absorbing()[source]¶
Checks if the Markov chain is absorbing.
- Return type:
- Returns:
bool: True if the Markov chain is absorbing, False otherwise.
- is_aperiodic()[source]¶
Checks if the Markov chain is aperiodic.
- Return type:
- Returns:
bool: True if the Markov chain is aperiodic, False otherwise.
- is_ergodic()[source]¶
Checks if the Markov chain is ergodic.
- Return type:
- Returns:
bool: True if the Markov chain is ergodic, False otherwise.
- is_irreducible()[source]¶
Checks if the Markov chain is irreducible.
- Return type:
- Returns:
bool: True if the Markov chain is irreducible, False otherwise.
- is_symmetric()[source]¶
Checks if the Markov chain is symmetric.
- Return type:
- Returns:
bool: True if the Markov chain is symmetric, False otherwise.
- load_model(path)[source]¶
Load a ChainoPy Model stored as a JSON Object and return as a MarkovChain object.
- Parameters:
path (str) – Path to the file.
Raises:¶
ValueError: If the file cannot be loaded.
- period()[source]¶
Returns the period of the Markov chain.
- Return type:
- Returns:
int: Period of the Markov chain.
- save_model(filename, epsilon=1e-16)[source]¶
Save Model as a JSON Object. If tpm is sparsifyable, it stores tpm as a sparse matrix.
- states¶
- stationary_dist()[source]¶
Returns the stationary distribution of the Markov chain.
- Return type:
- Returns:
ndarray: Stationary distribution.
- tpm¶
chainopy.markov_switching module¶
- class chainopy.markov_switching.MarkovSwitchingModel[source]¶
Bases:
objectMarkovSwitchingModel estimates 1D target values given the current regime. The regimes follow a first-order Markov process.
- evaluate(ts_test, ts_pred)[source]¶
Evaluates the accuracy of the model using the mean squared error metric.
- Parameters:
ts_test (ndarray) – Real target values of the Time Series
ts_pred (ndarray) – Predicted target values of the Time Series
- Returns:
float
- Return type:
mean square error between ts_test and ts_pred
- fit(ts_data, regime_sequence, lags=1)[source]¶
Trains and sets the models self.models and self._markov_chain attributes
chainopy.nn module¶
- class chainopy.nn.MarkovChainNeuralNetwork(markov_chain, num_layers)[source]¶
Bases:
ModuleNeural network for simulating Markov chain behavior.
- Parameters:
markov_chain (chainopy.MarkovChain) – Markov chain object.
num_layers (int) – Number of layers in the neural network.
- Raises:
ValueError – If markov_chain is not of type MarkovChain.:
- __init__(markov_chain, num_layers)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- forward(x)[source]¶
Forward pass of the neural network.
- Parameters:
x (torch.tensor) – Input data.
- Returns:
torch.Tensor: Output data after passing through the network.
- get_weights()[source]¶
Returns the weights of the model.
- Returns:
dict: Dictionary containing layer names and corresponding weights.
- simulate_random_walk(start_state, steps)[source]¶
Simulates a random walk based on the trained model.
- train_model(num_samples, epochs, learning_rate, momentum=0.9, verbose=True, patience=500, factor=0.5)[source]¶
Trains the neural network model.
- Parameters:
num_samples (int) – Number of training samples.
epochs (int) – Number of training epochs.
learning_rate (float) – Learning rate for optimization.
momentum (float) – Momentum factor (default is 0.9).
verbose (bool, optional) – If True, prints training progress (default is True).
patience (int, optional) – Patience parameter for learning rate scheduler (default is 500).
factor (float, optional) – Factor by which the learning rate will be reduced (default is 0.5).
- chainopy.nn.divergance_analysis(mc, nn)[source]¶
KL Divergance between MarkovChain.tpm and MarkovChain().fit(MarkovChainNeuralNetwork.simulate_random_walk).tpm.
- Parameters:
mc (MarkovChain) – Original Markov Chain that is used to fit the MarkovChainNeuralNetwork.
nn (MarkovChainNeuralNetwork) – The fitted MarkovChainNeuralNetwork.
- Return type:
- Returns:
- float: KL-Divergance
Lower the KL-Divergance, better the fit.
Notes
KL-Divergance<https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence>_.
Module contents¶
- class chainopy.MarkovChain(p=None, states=None)[source]¶
Bases:
objectA class containing Fundamental Functions for Discrete Time Markov Chains.
This class provides a comprehensive suite of methods for working with discrete-time Markov chains (DTMCs), including validation, simulation, and analysis functionalities. It supports learning transition probability matrices (TPMs) from data, checking various properties of the Markov chain (e.g., ergodicity, aperiodicity, symmetry), and computing distributions and probabilities related to the chain’s behavior over time.
- tpm¶
Transition probability matrix (TPM) representing the Markov chain.
- Type:
np.ndarray
- eigenvalues¶
Eigenvalues of the TPM.
- Type:
np.ndarray
- eigenvectors¶
Eigenvectors of the TPM.
- Type:
np.ndarray
- absorption_probabilities()[source]¶
Returns the absorption probabilities matrix for each state.
- Return type:
- Returns:
ndarray: Absorption probabilities matrix.
- eigendecom¶
- eigenvalues¶
- eigenvectors¶
- epsilon¶
- expected_hitting_time(state)[source]¶
Returns the expected hitting time to reach the given absorbing state.
- expected_number_of_visits()[source]¶
Returns the expected number of visits to each state before absorption.
- Return type:
- Returns:
ndarray: Expected number of visits.
- expected_time_to_absorption()[source]¶
Returns the expected time to absorption for each state.
- Return type:
- Returns:
ndarray: Expected time to absorption.
- fit(data, epsilon=1e-16)[source]¶
Learn Transition Matrix from Sequence (list or str) of Data. Each Unique Word is considered a State. It will override the current transition-matrix.
- Parameters:
- Return type:
- Returns:
ndarray: Transition - Matrix based on data
Usage
—– – >>> chainopy.MarkovChain().fit(“My name is John.”)
- is_absorbing()[source]¶
Checks if the Markov chain is absorbing.
- Return type:
- Returns:
bool: True if the Markov chain is absorbing, False otherwise.
- is_aperiodic()[source]¶
Checks if the Markov chain is aperiodic.
- Return type:
- Returns:
bool: True if the Markov chain is aperiodic, False otherwise.
- is_ergodic()[source]¶
Checks if the Markov chain is ergodic.
- Return type:
- Returns:
bool: True if the Markov chain is ergodic, False otherwise.
- is_irreducible()[source]¶
Checks if the Markov chain is irreducible.
- Return type:
- Returns:
bool: True if the Markov chain is irreducible, False otherwise.
- is_symmetric()[source]¶
Checks if the Markov chain is symmetric.
- Return type:
- Returns:
bool: True if the Markov chain is symmetric, False otherwise.
- load_model(path)[source]¶
Load a ChainoPy Model stored as a JSON Object and return as a MarkovChain object.
- Parameters:
path (str) – Path to the file.
Raises:¶
ValueError: If the file cannot be loaded.
- period()[source]¶
Returns the period of the Markov chain.
- Return type:
- Returns:
int: Period of the Markov chain.
- save_model(filename, epsilon=1e-16)[source]¶
Save Model as a JSON Object. If tpm is sparsifyable, it stores tpm as a sparse matrix.
- states¶
- stationary_dist()[source]¶
Returns the stationary distribution of the Markov chain.
- Return type:
- Returns:
ndarray: Stationary distribution.
- tpm¶
- class chainopy.MarkovChainNeuralNetwork(markov_chain, num_layers)[source]¶
Bases:
ModuleNeural network for simulating Markov chain behavior.
- Parameters:
markov_chain (chainopy.MarkovChain) – Markov chain object.
num_layers (int) – Number of layers in the neural network.
- Raises:
ValueError – If markov_chain is not of type MarkovChain.:
- __init__(markov_chain, num_layers)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- forward(x)[source]¶
Forward pass of the neural network.
- Parameters:
x (torch.tensor) – Input data.
- Returns:
torch.Tensor: Output data after passing through the network.
- get_weights()[source]¶
Returns the weights of the model.
- Returns:
dict: Dictionary containing layer names and corresponding weights.
- simulate_random_walk(start_state, steps)[source]¶
Simulates a random walk based on the trained model.
- train_model(num_samples, epochs, learning_rate, momentum=0.9, verbose=True, patience=500, factor=0.5)[source]¶
Trains the neural network model.
- Parameters:
num_samples (int) – Number of training samples.
epochs (int) – Number of training epochs.
learning_rate (float) – Learning rate for optimization.
momentum (float) – Momentum factor (default is 0.9).
verbose (bool, optional) – If True, prints training progress (default is True).
patience (int, optional) – Patience parameter for learning rate scheduler (default is 500).
factor (float, optional) – Factor by which the learning rate will be reduced (default is 0.5).
- class chainopy.MarkovSwitchingModel[source]¶
Bases:
objectMarkovSwitchingModel estimates 1D target values given the current regime. The regimes follow a first-order Markov process.
- evaluate(ts_test, ts_pred)[source]¶
Evaluates the accuracy of the model using the mean squared error metric.
- Parameters:
ts_test (ndarray) – Real target values of the Time Series
ts_pred (ndarray) – Predicted target values of the Time Series
- Returns:
float
- Return type:
mean square error between ts_test and ts_pred
- fit(ts_data, regime_sequence, lags=1)[source]¶
Trains and sets the models self.models and self._markov_chain attributes
- chainopy.divergance_analysis(mc, nn)[source]¶
KL Divergance between MarkovChain.tpm and MarkovChain().fit(MarkovChainNeuralNetwork.simulate_random_walk).tpm.
- Parameters:
mc (MarkovChain) – Original Markov Chain that is used to fit the MarkovChainNeuralNetwork.
nn (MarkovChainNeuralNetwork) – The fitted MarkovChainNeuralNetwork.
- Return type:
- Returns:
- float: KL-Divergance
Lower the KL-Divergance, better the fit.
Notes
KL-Divergance<https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence>_.