ergodicity.tools package

Submodules

ergodicity.tools.automate module

automate Submodule

The automate submodule provides tools to automate simulations and visualizations of stochastic processes over various parameter configurations. It enables batch processing of parameter ranges for a given process class, making it useful for large-scale simulations or research that requires exploration of many different process behaviors.

Key Features:

  1. Automated Parameter Exploration:

    • automated_live_visualization: Automates the generation of visualizations for all combinations of parameters in a specified range. It supports 1D, 2D, and 3D visualizations, making it versatile for different types of stochastic processes.

  2. Parameter Combination:

    • The submodule uses itertools.product to generate all possible combinations of parameter values, allowing exhaustive exploration of the parameter space.

  3. Dynamic Visualization:

    • Based on the dimensionality of the process (1, 2, or 3 dimensions), the function automatically selects the correct visualization method and produces live simulations of the process. Simulations can be saved as videos for further analysis.

  4. Customizable Simulations:

    • The user can control the total simulation time, time step, number of instances, and speed of the simulation.

    • Simulations can be tailored to different dimensions (1D, 2D, or 3D) and saved for later review.

Typical Use Cases:

  • Research and Development:

    Useful in exploring how different parameter values affect the behavior of stochastic processes, particularly in areas like finance, physics, and biology.

  • Simulation Studies:

    Helps automate large-scale simulation studies where multiple parameter combinations need to be analyzed in an efficient manner.

  • Educational Tools:

    Ideal for demonstrating the dynamics of stochastic processes in classrooms or presentations, with real-time visualizations across different parameter sets.

Example Usage:

param_ranges = {

‘alpha’: [0.1, 0.5, 1.0], ‘beta’: [0.1, 0.2, 0.3]

}

automated_live_visualization(

dimensions=2, process_class=MyStochasticProcess, param_ranges=param_ranges, t=10, timestep=0.01, num_instances=100, speed=1.0

)

ergodicity.tools.automate.automated_live_visualization(dimensions: int, process_class, param_ranges: dict, t: float = 10, timestep: float = 0.01, num_instances: int = 100, speed: float = 1.0)[source]

Generate live visualizations for all parameter combinations of a stochastic process.

Parameters:
  • dimensions (int) – Number of dimensions (1, 2, or 3)

  • process_class (class) – The stochastic process class

  • param_ranges (dict) – Dictionary of parameter ranges (key: param name, value: list of values)

  • t (float) – Total time for the simulation

  • timestep (float) – Time step for the simulation

  • num_instances (int) – Number of instances to simulate

  • speed (float) – Speed multiplier for the video

ergodicity.tools.compute module

compute Submodule

The compute submodule provides a comprehensive set of utilities and functions for performing various numerical computations and visualizations related to stochastic processes. This includes tools for calculating growth rates, visualizing time series data, and generating sample paths for different types of stochastic processes. Additionally, it offers advanced numerical methods, such as solving partial differential equations like the Fokker-Planck equation, which is essential for understanding the dynamics of stochastic processes.

Key Features:

  1. Visualization of Time Series Data:

    • Functions like visualize_function and average allow for easy visualization of data over time, aiding in the analysis of simulated processes.

    • The submodule also supports visualizing more complex quantities such as growth rates and comparing them with theoretical models like Geometric Brownian Motion (GBM).

  2. Increment Calculation and Validation:

    • Functions are decorated with validate_input_shape to ensure correct input data structure and shape.

    • Tools such as growth_rates, growth_rate_of_average, and relative_increments calculate the growth rates and relative increments for a variety of stochastic processes.

  3. Alpha-Stable Processes:

    • The demonstrate_alpha_stable_self_similarity function illustrates the self-similarity property of alpha-stable processes.

    • It also allows for the comparison of different scaling factors and their effects on the distribution of end values, making it useful for simulating heavy-tailed distributions.

  4. Lévy and Gaussian Processes:

    • This submodule includes functions to generate and simulate Lévy processes and Gaussian processes, such as generate_levy_process and create_multivariate_gaussian_process.

    • The matrix A is constructed from correlation matrices and variances to model multivariate Gaussian processes, enhancing the ability to work with correlated variables.

  5. Fokker-Planck Equation Solver:

    • The solve_fokker_planck_numerically function numerically solves the Fokker-Planck equation using finite difference methods.

    • The solution is visualized in 3D, making it an invaluable tool for studying drift-diffusion processes and their time evolution.

  6. Statistical Tools:

    • Functions such as mu_sigma and compare_distributions provide statistical insights, allowing the user to compute averages, variances, and distributions of stochastic processes over time.

Applications:

This submodule is useful in various fields, including:

  • Financial Modeling: Simulation of processes like Geometric Brownian Motion and Lévy processes to study asset price dynamics and other market phenomena.

  • Physics and Environmental Science: Modeling diffusion processes, random walks, and other phenomena where stochastic differential equations apply.

  • Machine Learning and Data Science: Incorporating stochastic processes in optimization algorithms and reinforcement learning environments.

The compute submodule equips users with robust tools for simulating, visualizing, and analyzing stochastic processes. Whether working on theoretical models or practical applications, this submodule offers both simplicity and flexibility in dealing with complex stochastic dynamics.

ergodicity.tools.compute.average(data: ndarray, visualize: bool = True, name='average', save: bool = False) ndarray[source]

Calculate the average over all instances for each time step.

Parameters:
  • data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

  • visualize (bool) – Whether to visualize the average values.

  • name (str) – The name of the data to display.

  • save (bool) – Whether to save the plot as a PNG file.

Returns:

The average values for each time step.

Return type:

np.ndarray

ergodicity.tools.compute.average_growth_rate(data: ndarray, visualize: bool = True, save: bool = False) ndarray[source]

Calculate the average of the cumulative log growth rates for all instances.

Parameters:
  • data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

  • visualize (bool) – Whether to visualize the average growth rates.

  • save (bool) – Whether to save the plot as a PNG file.

Returns:

The average of the cumulative log growth rates for all instances.

Return type:

np.ndarray

ergodicity.tools.compute.average_growth_rate_vs_gbm(data: ndarray, save: bool = False) ndarray[source]

Calculate the average of the cumulative log growth rates for all instances and compare with the graph mu*t - 0.5*sigma^2*t

Parameters:
  • data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

  • save (bool) – Whether to save the plot as a PNG file.

Returns:

The average of the cumulative log growth rates for all instances.

Return type:

np.ndarray

ergodicity.tools.compute.compare_averages(data: ndarray, save: bool = False) ndarray[source]

Compare and plot average growth rate and growth rate of average.

Parameters:
  • data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

  • save (bool) – Whether to save the plot as a PNG file.

Returns:

None

Return type:

None

ergodicity.tools.compute.compare_distributions(alpha, T=1, N=1000, scales=[1, 10, 100], num_realizations=1000)[source]

Compare the scaled distributions of end values for Lévy processes with different scales to check self-similarity.

Parameters:
  • alpha (float) – Stability parameter (0 < alpha <= 2).

  • T (float) – Time horizon.

  • N (int) – Number of time steps.

  • scales (list) – List of scales to compare.

  • num_realizations (int)

Returns:

None

Return type:

None

ergodicity.tools.compute.create_A_from_correlation_and_variances(correlation_matrix, variances)[source]

Create matrix A from a given correlation matrix and variance vector.

Parameters:
  • correlation_matrix (np.ndarray) – Desired correlation matrix R.

  • variances (np.ndarray) – Desired variances for each process.

Returns:

The matrix used to create the multivariate Gaussian process.

Return type:

np.ndarray

ergodicity.tools.compute.create_multivariate_gaussian_process(A, independent_processes)[source]

Create a multivariate Gaussian process by linearly combining independent Gaussian processes.

Parameters:
  • A (np.ndarray) – Matrix to combine the independent processes.

  • independent_processes (np.ndarray) – Matrix of independent Gaussian processes.

Returns:

The multivariate Gaussian process.

Return type:

np.ndarray

ergodicity.tools.compute.demonstrate_alpha_stable_self_similarity(alpha, c, n_points, n_simulations)[source]

Demonstrate the self-similarity of an α-stable process.

Parameters:
  • alpha (float) – Stability parameter (0 < alpha <= 2).

  • c (float) – Scaling factor for time.

  • n_points (int) – Number of points in each process realization.

  • n_simulations (int) – Number of process realizations to generate.

Returns:

Figure and axes objects for the plot.

Return type:

tuple

ergodicity.tools.compute.generate_levy_process(T=10, N=10, alpha=1.5, beta=0, loc=0, scale=1)[source]

A Function to generate a Lévy process with the given parameters.

Parameters:
  • T (float) – Time horizon.

  • N (int) – Number of time steps.

  • alpha – Stability parameter (0 < alpha <= 2).

Returns:

The generated Lévy process dataset.

Return type:

np.ndarray

ergodicity.tools.compute.growth_rate_of_average(data: ndarray, visualize: bool = True, save: bool = False) ndarray[source]

Calculate the cumulative log growth rates for the average of all instances.

Parameters:
  • data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

  • visualize (bool) – Whether to visualize the growth rates.

  • save (bool) – Whether to save the plot as a PNG file.

Returns:

The cumulative log growth rates for the average of all instances.

Return type:

np.ndarray

ergodicity.tools.compute.growth_rate_of_average_per_time(data: ndarray) ndarray[source]

Calculate the cumulative log growth rates for the average of all instances per time.

Parameters:

data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

Returns:

The cumulative log growth rates for the average of all instances per time.

Return type:

np.ndarray

ergodicity.tools.compute.growth_rates(data: ndarray, visualize: bool = True, name='growth rates', save: bool = False) ndarray[source]

Calculate cumulative log growth rates for each time step based on the input data.

Parameters:
  • data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

  • visualize (bool) – Whether to visualize the growth rates.

  • name (str) – The name of the data to display.

  • save (bool) – Whether to save the plot as a PNG file.

Returns:

The cumulative log growth rates for each time step.

Return type:

np.ndarray

ergodicity.tools.compute.mu_sigma(data: ndarray)[source]

Calculate the average and standard deviation of the dataset.

Parameters:

data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

Returns:

The average and standard deviation of the dataset.

Return type:

tuple

ergodicity.tools.compute.random_variable_from_pdf(pdf, x, num_samples, t=1)[source]

Generate random variable samples from a given probability density function (pdf).

Parameters:
  • pdf (sympy.core.add.Add) – Probability density function.

  • x (sympy.core.symbol.Symbol) – Symbolic variable for the random variable.

  • num_samples (int) – Number of random variable samples to generate.

  • t (float) – Time parameter for the PDF (default is 1).

Returns:

Random variable samples.

Return type:

np.ndarray

ergodicity.tools.compute.relative_increments(data: ndarray, visualize: bool = True) ndarray[source]

Calculate the relative increments for each time step based on the input data.

Parameters:
  • data (np.ndarray) – The input data array of shape (1 + number of instances, number of time steps).

  • visualize (bool) – Whether to visualize the relative increments.

Returns:

The relative increments for each time step.

Return type:

np.ndarray

ergodicity.tools.compute.simulate_independent_gaussian_processes(n, size, mean=0, std=1)[source]

Simulate n independent Gaussian processes.

Parameters:
  • n (int) – Number of processes.

  • size (int) – Number of time steps.

  • mean (float) – Mean of the Gaussian distribution.

  • std (float) – Standard deviation of the Gaussian distribution.

Returns:

Matrix of independent Gaussian processes.

Return type:

np.ndarray

ergodicity.tools.compute.solve_fokker_planck_numerically(mu_func, sigma_func, P0_func, x_range, t_range, Nx, Nt, boundary_conditions)[source]

Solve the Fokker-Planck equation numerically using finite differences and visualize the result in 3D.

Parameters:
  • mu_func (function) – Function for drift term, mu(x, t).

  • sigma_func (function) – Function for diffusion term, sigma(x, t).

  • P0_func (function) – Function for the initial condition P(x, 0).

  • x_range (Tuple[float, float]) – Tuple (x_min, x_max) defining the spatial domain.

  • t_range (Tuple[float, float]) – Tuple (t_min, t_max) defining the time domain.

  • Nx (int) – Number of spatial grid points.

  • Nt (int) – Number of time steps.

  • boundary_conditions (Tuple[float, float]) – Tuple specifying Dirichlet boundary conditions as (P(x_min, t), P(x_max, t)).

Returns:

Arrays for the solution P(x, t) at each time step and the spatial grid points.

Return type:

Tuple[np.ndarray, np.ndarray, np.ndarray]

ergodicity.tools.compute.validate_input_shape(func)[source]

Decorator to validate the input shape of the data array for the functions in this module. The correct shape is a 2D array with the first row representing the time points and the remaining rows representing the instances.

Parameters:

func (Any) – The function to decorate.

Returns:

The decorated function.

Return type:

Any

ergodicity.tools.compute.visualize_function(time: ndarray, data: ndarray, name: str, save: bool = False) None[source]

Visualize the given precomputed data evolution over time. The data should be a 2D array with the first row. This function is intended to work with the outputs of the other functions in this module.

Parameters:
  • time (np.ndarray) – The time points for the data.

  • data (np.ndarray) – The data to visualize.

  • name (str) – The name of the data to display.

  • save (bool) – Whether to save the plot as a PNG file.

Returns:

None

Return type:

None

ergodicity.tools.evaluate module

evaluate Submodule

The evaluate submodule provides tools for assessing the statistical properties and characteristics of stochastic processes. This includes methods for testing ergodicity, self-similarity, fat-tailedness, and more. It offers a variety of functions for time series analysis, focusing on stochastic processes commonly used in finance, physics, and other fields requiring statistical modeling.

Key Features:

  1. Ergodicity Testing:

    • test_ergodicity_increments: Tests ergodicity by comparing time and ensemble averages of a process’s increments. It also checks for stationarity and normality of the increments.

  2. Self-Similarity Analysis:

    • hurst_exponent: Estimates the Hurst exponent using the Rescaled Range (R/S) method, a key indicator of self-similarity and long-term memory.

    • aggregate_variance: Uses the aggregate variance method to estimate the scaling parameter.

    • test_self_similarity: Combines multiple methods to test for self-similarity, including Hurst exponent estimation and scaling parameter analysis.

    • test_self_similarity_wavelet: Uses wavelet analysis to estimate the Hurst exponent, offering an alternative method for testing self-similarity.

  3. Fat-Tailedness Testing:

    • test_fat_tailedness: Performs multiple tests to detect fat-tailedness in data, including kurtosis tests, Jarque-Bera tests, and tail index estimation using the Hill estimator. It also generates Q-Q plots for visual analysis.

    • kurtosis_test, jarque_bera_test, tail_index_hill: Individual functions to test for fat tails in distributions.

  4. Wavelet-Based Analysis:

    • wavelet_estimation: Estimates the Hurst exponent using wavelet-based techniques. This is particularly useful for processes with fractal or self-similar properties.

    • plot_wavelet_analysis: Provides visual analysis of wavelet decomposition, allowing users to assess the variance of wavelet coefficients across scales.

  5. Visualization:

    • The submodule includes multiple plotting functions such as plot_ergodicity_results and qqplot_analysis, which help visualize important statistical properties of time series data.

Applications:

This submodule is highly applicable in fields such as:

  • Financial Modeling: Understanding stock prices, asset returns, and market dynamics through ergodicity and self-similarity testing.

  • Physics: Analyzing systems governed by stochastic dynamics, such as diffusion processes.

  • Environmental Science: Studying long-range dependence in environmental data (e.g., temperature, rainfall).

  • Machine Learning: Utilizing statistical tools to evaluate the properties of learning algorithms that incorporate random processes.

The evaluate submodule serves as a powerful toolkit for researchers and practitioners who need to test key statistical properties of their models or real-world data. By providing a range of methods, it simplifies complex evaluations and enhances the understanding of stochastic processes.

ergodicity.tools.evaluate.detrended_fluctuation_analysis(time_series)[source]

Estimate the Hurst exponent using Detrended Fluctuation Analysis (DFA).

Parameters:

time_series (array_like) – The time series to analyze

Returns:

Estimated Hurst exponent

Return type:

float

ergodicity.tools.evaluate.jarque_bera_test(data)[source]

Perform Jarque-Bera test for normality.

Parameters:

data (array_like) – The data to analyze

Returns:

Dictionary containing the test statistic, p-value, and interpretation

Return type:

dict

ergodicity.tools.evaluate.kurtosis_test(data)[source]

Test for fat-tailedness using excess kurtosis.

Parameters:

data (array_like) – The data to analyze

Returns:

Dictionary containing the kurtosis and its interpretation

Return type:

dict

ergodicity.tools.evaluate.plot_ergodicity_results(data, results)[source]

Plot visualizations to help assess ergodicity of increments.

Parameters:
  • data (numpy.ndarray) – Array of shape (num_time_steps, num_instances + 1) where the first row is time and subsequent rows are instances of the process

  • results (dict) – Dictionary containing test results from test_ergodicity_increments function

Returns:

None

Return type:

None

ergodicity.tools.evaluate.plot_wavelet_analysis(time_series, wavelet='db4', max_level=None)[source]

Perform wavelet analysis and plot the results.

Parameters:
  • time_series (array_like) – The time series to analyze

  • wavelet (str, optional) – The wavelet to use for the analysis (default is ‘db4’)

  • max_level (int, optional) – The maximum decomposition level (default is None, which means it will be automatically determined)

Returns:

None

Return type:

None

ergodicity.tools.evaluate.qqplot_analysis(data)[source]

Perform Q-Q plot analysis against normal distribution.

Parameters:

data (array_like) – The data to analyze

Returns:

None (displays the Q-Q plot)

Return type:

None

ergodicity.tools.evaluate.tail_index_hill(data, tail_fraction=0.1)[source]

Estimate the tail index using Hill estimator.

Parameters:
  • data (array_like) – The data to analyze

  • tail_fraction (float) – Fraction of the data to consider as the tail

Returns:

Dictionary containing the tail index and its interpretation

Return type:

dict

ergodicity.tools.evaluate.test_ergodicity_increments(data, relative_increments=False)[source]

Test the ergodicity of a stochastic process based on its increments.

Parameters:

data (numpy.ndarray) – Array of shape (num_time_steps, num_instances + 1) where the first row is time reprsenting the time steps and subsequent rows are instances of the process

:param dt:vTime step size (1/number of steps in a time unit) :type dt: float :return: Dictionary containing test results and metrics :rtype: dict

ergodicity.tools.evaluate.test_fat_tailedness(data)[source]

Perform a comprehensive test for fat-tailedness.

Parameters:

data (array_like) – The data to analyze

Returns:

Dictionary containing results from various tests

Return type:

dict

ergodicity.tools.evaluate.test_self_similarity(time_series)[source]

Test the self-similarity of a given time series.

Parameters:

time_series (array_like) – The time series to analyze

Returns:

Dictionary containing the estimated Hurst exponents

Return type:

dict

ergodicity.tools.evaluate.test_self_similarity_wavelet(time_series, wavelet='db4', max_level=None)[source]

Test the self-similarity of a given time series using wavelet-based method.

Parameters:
  • time_series (array_like) – The time series to analyze

  • wavelet (str, optional) – The wavelet to use for the analysis (default is ‘db4’)

  • max_level (int, optional) – The maximum decomposition level (default is None, which means it will be automatically determined)

Returns:

Dictionary containing the estimated Hurst exponent and scaling parameter

Return type:

dict

ergodicity.tools.evaluate.wavelet_estimation(time_series, wavelet='db4', max_level=None)[source]

Estimate the Hurst exponent using wavelet-based method.

Parameters:
  • time_series (array_like) – The time series to analyze

  • wavelet (str, optional) – The wavelet to use for the analysis (default is ‘db4’)

  • max_level (int, optional) – The maximum decomposition level (default is None, which means it will be automatically determined)

Returns:

Estimated Hurst exponent

Return type:

float

ergodicity.tools.fit module

fit Submodule

The fit submodule provides a set of tools for fitting various stochastic processes and probability distributions to data. It leverages techniques such as maximum likelihood estimation (MLE) and optimization to find the best parameters that describe the observed data. This submodule is particularly useful in research and simulations that involve probabilistic models and stochastic processes.

Key Features:

  1. Lévy Stable Distribution Fitting:

    • The function levy_stable_fit performs maximum likelihood estimation for fitting Lévy stable distributions to data, a family of distributions used in finance, physics, and other fields that involve heavy tails and skewness.

  2. Distribution Fitting and Model Comparison:

    • fit_distributions: Fits various probability distributions (e.g., normal, lognormal, exponential, Lévy stable) to a given dataset and provides goodness-of-fit measures like the Kolmogorov-Smirnov test, AIC (Akaike Information Criterion), and BIC (Bayesian Information Criterion).

    • print_results: Summarizes and compares the fitted distributions based on their AIC and BIC values to help identify the best model.

  3. Visualization of Fitted Distributions:

    • plot_fitted_distributions: Visualizes the fitted distributions by overlaying them on the histogram of the data, providing a clear comparison between the data and the fitted models.

  4. Stochastic Process Parameter Fitting:

    • fit_stochastic_process: Fits the parameters of a given stochastic process to observed data using optimization techniques. This is particularly useful when simulating stochastic processes like Ornstein-Uhlenbeck or Brownian motion and comparing them to real-world or simulated data.

  5. Fitting Success Testing:

    • test_fitting_success: Generates synthetic data using known parameters and tests the success of fitting the process to the data, evaluating the accuracy of the fitted parameters across multiple tests.

  6. Distribution Comparison:

    • compare_distributions: Generates data from a specified probability distribution and compares the fitted parameters with the original generating parameters. This function is helpful for understanding the reliability of different fitting techniques.

Typical Use Cases:

  • Research and Data Analysis:

    Provides tools for fitting complex stochastic models to experimental or observed data, enabling researchers to validate theoretical models.

  • Simulation Studies:

    Enables parameter fitting for stochastic simulations, especially when simulating processes like Lévy flights, Brownian motion, or other random walks.

  • Model Selection:

    Facilitates the selection of the best probabilistic model using AIC, BIC, and goodness-of-fit tests.

Example Usage:

data = np.random.normal(0, 1, 1000) # Example data

# Fit various distributions

fitted_dists = fit_distributions(data)

# Print the results

print_results(fitted_dists)

# Plot the fitted distributions

plot_fitted_distributions(data, fitted_dists)

ergodicity.tools.fit.compare_distributions(dist_name, params, size=1000)[source]

Generates a dataset from a specified probability distribution, fits the dataset back to the distribution, and compares the fitted distribution with the generating distribution.

Parameters:
  • dist_name (str) – Name of the probability distribution (e.g., ‘norm’, ‘expon’, ‘gamma’)

  • params (tuple) – Parameters for the generating distribution (e.g., (mean, std) for ‘norm’)

  • size (int) – Number of samples to generate

Returns:

None

Return type:

None

ergodicity.tools.fit.fit_distributions(data)[source]

Fit various probability distributions to the given data, including Lévy stable.

Parameters:

data (array) – The data to fit the distributions to

Returns:

A dictionary containing the fitted distributions, parameters, and goodness-of-fit measures

Return type:

dict

ergodicity.tools.fit.fit_stochastic_process(process_func, external_data, initial_params, param_names, bounds=None, num_fits=10, t=10, timestep=0.01)[source]

Fit parameters for a given stochastic process function to external data.

Parameters:
  • process_func (callable) – The stochastic process function decorated with @custom_simulate

  • external_data (array) – External observed data points

  • initial_params (dict) – Initial guess for the parameters

  • param_names (list) – Names of the parameters to fit

  • bounds (list of tuples, optional) – Bounds for the parameters [(low1, high1), (low2, high2), …]

  • num_fits (int) – Number of fitting attempts with different initial conditions

  • t (float) – Total simulation time

  • timestep (float) – Time step for the simulation

Returns:

Optimized parameters and the plot figure

Return type:

dict, matplotlib.figure.Figure

ergodicity.tools.fit.levy_stable_fit(data)[source]

Estimate the parameters of a stable distribution using the Empirical Characteristic Function method.

Parameters:

data (array-like) – The data to fit the stable distribution to

Returns:

The estimated parameters of the stable distribution

Return type:

dict

ergodicity.tools.fit.plot_fitted_distributions(data, fitted_dists)[source]

Plot the histogram of the data with fitted distributions.

Parameters:
  • data (array or list of arrays) – The data to plot the histogram of

  • fitted_dists (dict) – A dictionary containing the fitted distributions and their parameters

Returns:

None

Return type:

None

ergodicity.tools.fit.print_results(fitted_dists)[source]

Print the results of distribution fitting, including goodness-of-fit and information criteria.

Parameters:

fitted_dists (dict) – A dictionary containing the fitted distributions and their information

Returns:

None

Return type:

None

ergodicity.tools.fit.test_fitting_success(process_func: Callable, true_params: Dict[str, float], param_names: List[str], bounds: List[Tuple[float, float]] = None, num_tests: int = 10, t: float = 10, timestep: float = 0.01, initial_value: float = 1.0) Dict[str, List[float]][source]

Test the success of fitting by generating data with known parameters and then fitting it.

Parameters:
  • process_func (callable) – The stochastic process function decorated with @custom_simulate

  • true_params (dict) – The true parameters of the process to generate data

  • param_names (list) – Names of the parameters to fit

  • bounds (list of tuples, optional) – Bounds for the parameters [(low1, high1), (low2, high2), …]

  • num_tests (int) – Number of tests to run

  • t (float) – Total time for each simulation

  • timestep (float) – Time step for simulations

  • initial_value (float) – Initial value for the process

Returns:

Dictionary with lists of true and fitted values for each parameter

Return type:

dict

ergodicity.tools.helper module

helper Submodule

The helper submodule provides various utility functions designed to assist with data manipulation, visualization, and process encoding within stochastic process simulations. These helper functions streamline the workflow for saving results, plotting simulation data, encoding processes, and handling system-level data transformations. It is commonly used in conjunction with other modules such as process, compute, and fit.

Key Features:

  1. Data Manipulation:

    • separate: A simple utility that separates time and process data from a given dataset. Often used to split simulation data into its respective components.

  2. Saving and Visualization:

    • save_to_file: Saves simulation data to a specified directory. It can create necessary directories if they do not exist.

    • visualize_process_from_data: Visualizes the output of a stochastic process simulation.

    • plot_simulate_ensemble: Plots the results of an ensemble of simulated processes, showing portfolio evolution, asset weights, and geometric means.

    • plot: Plots the simulation results of custom processes with multiple instances.

    • plot_system: A more advanced plotting function designed for systems of stochastic differential equations (SDEs), where multiple equations are simulated simultaneously.

  3. Process Encoding:

    • ProcessEncoder: A class designed to encode different stochastic processes and their parameters into a numeric representation. This is useful for handling multiple processes programmatically and standardizing their representation in simulations.

      • Methods:

        • encode: Encodes a process type as a unique integer.

        • decode: Decodes an integer back into the corresponding process type.

        • encode_process: Encodes a process instance into a list of floats, allowing for the serialization of its parameters.

        • pad_encoded_process: Pads the encoded process representation to ensure uniform length.

        • encode_process_with_time: Encodes a process along with a time value to preserve temporal information for the simulation.

  4. Parallelism:

    • The module imports ProcessPoolExecutor to enable parallel execution, although no explicit parallel functionality is currently implemented in the given code. This suggests potential future extensions for parallel processing of simulations or fitting routines.

Example Usage:

data = np.random.randn(100, 50) # Example data

# Save the data

save_to_file(data, output_dir=”results”, file_name=”simulation_data”, save=True)

# Plot the data

plot(data, num_instances=10, save=True, plot=True)

# Encode a process instance

encoder = ProcessEncoder()

encoded_process = encoder.encode_process(MyProcessClass())

print(“Encoded process:”, encoded_process)

class ergodicity.tools.helper.ProcessEncoder[source]

Bases: object

A class to encode different stochastic processes and their parameters into a numeric representation. It is neeeded for handling multiple processes programmatically and standardizing their representation in simulations. It is used in the submodules ‘multiprocessing’ and ‘automate’ of the ‘compute’ module and in the ‘agents’ module.

process_types

A dictionary mapping process types to their encoded integer values.

Type:

dict

reverse_mapping

A dictionary mapping encoded integer values to their corresponding process types.

Type:

dict

next_id

The next available integer value for encoding a new process type.

Type:

int

decode(process_id: int) str[source]

Decode an integer back into the corresponding process type.

Parameters:

process_id (int) – The integer value to decode

Returns:

The decoded process type

Return type:

str

encode(process_type: str) int[source]

Encode a process type as a unique integer.

Parameters:

process_type (str) – The type of the process to encode

Returns:

The encoded integer value

Return type:

int

encode_process(process: object) List[float][source]

Encode a process instance into a list of floats.

Parameters:

process (object) – A process instance

Returns:

A list of floats representing the encoded process

Return type:

List[float]

encode_process_with_time(process: Dict | object, time: float) List[float][source]

Encode a process with its time value, maintaining the original total length.

Parameters:
  • process (Union[Dict, object]) – The process to encode (either a dictionary or an object)

  • time (float) – The time value to include in the encoding

Returns:

A list of floats representing the encoded process with time

Return type:

List[float]

get_decoding() Dict[int, str][source]

Get the decoding of process types.

Returns:

A dictionary mapping encoded integer values to their corresponding process types

Return type:

Dict[int, str]

get_encoding() Dict[str, int][source]

Get the encoding of process types.

Returns:

A dictionary mapping process types to their encoded integer values

Return type:

Dict[str, int]

pad_encoded_process(encoded_process: List[float], max_params: int = 10) List[float][source]

Pad the encoded process representation to ensure uniform length.

Parameters:
  • encoded_process (List[float]) – The encoded process to pad

  • max_params (int) – The maximum number of parameters to include

Returns:

The padded encoded process

Return type:

List[float]

ergodicity.tools.helper.covariance_to_correlation(covariance_matrix)[source]

Convert a covariance matrix to a correlation matrix.

Parameters:

covariance_matrix (numpy.ndarray) – The covariance matrix to convert

Returns:

The correlation matrix

Return type:

numpy.ndarray

ergodicity.tools.helper.plot(data_full, num_instances: int, save: bool = False, plot: bool = False)[source]

Plot the simulation results of custom processes with multiple instances.

Parameters:
  • data_full (numpy.ndarray) – The simulation data to plot

  • num_instances (int) – The number of instances to plot

  • save (bool) – Whether to save the plots as image files

  • plot (bool) – Whether to display the plots

Returns:

None

Return type:

None

ergodicity.tools.helper.plot_simulate_ensemble(simulation_result: Dict[str, Any], t: float, save: bool = False) None[source]

Plot the results of the simulate_ensemble method.

Parameters:
  • simulation_result (Dict[str, Any]) – Dictionary containing ‘portfolio’, ‘geometric_means’, and ‘weights’

  • t (float) – Total simulation time

  • save (bool) – Whether to save the plots as image files

Returns:

None

Return type:

None

ergodicity.tools.helper.plot_system(data_full, num_instances: int, num_equations: int, save: bool = False, plot: bool = False)[source]

Plot the simulation results of a system of stochastic differential equations (SDEs).

Parameters:
  • data_full (numpy.ndarray) – The simulation data to plot

  • num_instances (int) – The number of instances to plot

  • num_equations (int) – The number of equations in the system

  • save (bool) – Whether to save the plots as image files

  • plot (bool) – Whether to display the plots

Returns:

None

Return type:

None

ergodicity.tools.helper.save_to_file(data, output_dir: str, file_name: str, save: bool = False)[source]

Save the given data to a file in the specified output directory.

Parameters:
  • data (numpy.ndarray) – The data to save

  • output_dir (str) – The directory to save the file in

  • file_name (str) – The name of the file to save

  • save (bool) – Whether to save the data

Returns:

None

Return type:

None

ergodicity.tools.helper.separate(data)[source]

Separate time and data from the given dataset.

Parameters:

data (numpy.ndarray) – The dataset to separate

Returns:

A tuple containing the time values and the data values

Return type:

tuple

ergodicity.tools.multiprocessing module

multiprocessing Submodule

The multiprocessing submodule provides tools and functions to execute tasks in parallel, optimizing the performance of stochastic process simulations and other computationally intensive tasks. The submodule leverages Python’s concurrent.futures and multiprocessing libraries to distribute tasks across multiple CPU cores.

Key Features:

  1. Parallel Task Execution:

    • ParallelExecutionManager: Manages the execution of tasks in parallel using ProcessPoolExecutor. It supports both standalone functions and methods within objects.

    • run_task_parallel: Executes individual tasks either as standalone functions or as methods of objects.

  2. Task Wrappers:

    • task_wrapper: A decorator that facilitates parallel execution and saves results to disk. It can be applied to functions that create tasks for parallel execution.

    • initial_tasks_wrapper and secondary_tasks_wrapper: Decorators for wrapping tasks related to simulations and visualizations. These wrappers handle the creation and submission of tasks for parallel execution.

    • growth_rate_wrapper: A special-purpose decorator for wrapping functions related to growth rate calculations.

  3. Parallel Processing Pipelines:

    • multi_simulations: Executes multiple simulations in parallel, each with a different parameter configuration.

    • multi_visualize_moments: Executes parallel tasks for visualizing moments of the simulation results.

    • multi_growth_rate_time_average and multi_growth_rate_ensemble_average: Executes growth rate calculations for time average and ensemble average in parallel.

  4. Parallel Execution of Arbitrary Functions:

    • parallel_processor: A decorator that wraps any function, allowing it to process multiple datasets in parallel. It submits each dataset as a separate task to the ProcessPoolExecutor.

    • parallel: A higher-level function that runs any library function in parallel with multiple sets of arguments.

  5. Task Result Management:

    • The submodule handles task results by saving them to files, ensuring that they can be reloaded or inspected later.

    • The results are organized and filtered to remove invalid or failed tasks before further analysis or visualization.

  6. Example Pipelines:

    • general_pipeline: Runs a full pipeline that includes simulations, visualizations, and growth rate calculations.

    • ensemble_vs_time_average_pipeline: Compares the ensemble average and time average growth rates in parallel.

  7. Parallel Function Wrapping:

    • Parallel.wrapp: A class method that converts any function into a parallel processing function, automatically distributing its workload across available CPU cores.

Example Usage:

if __name__ == “__main__”:

import ergodicity.process.multiplicative as ep

# Define parameter ranges for a Geometric Lévy process

param_ranges = {

‘alpha’: [1.5, 1.6, 1.7], ‘loc’: [0.004, 0.005, 0.006], ‘scale’: [0.002, 0.003, 0.004], ‘beta’: [0]

}

# Run a general pipeline that includes simulations, visualizations, and growth rate calculations

results = general_pipeline(ep.GeometricLevyProcess, param_ranges)

# Parallel processing example using the ‘average’ function

data_arrays = [np.random.rand(10, 100) for _ in range(5)]

results1 = parallel(average, data_arrays, visualize=False, name=”multi_average”)

print(results1)

class ergodicity.tools.multiprocessing.Parallel[source]

Bases: object

A class that provides tools for parallel processing of functions.

static run_function(func, kwargs)[source]

Helper function to run the target function with given arguments.

Parameters:
  • func (Callable) – The target function to run

  • kwargs (dict) – The keyword arguments to pass to the function

Returns:

The result of the function

Return type:

Any

classmethod wrapp(func: Callable) Callable[source]

Wrapper function that transforms a given function into a parallel processing function.

Parameters:

func (Callable) – The original function to be parallelized

Returns:

A new function that runs parallel instances of the original function

Return type:

Callable

class ergodicity.tools.multiprocessing.ParallelExecutionManager[source]

Bases: object

A class to manage the parallel execution of tasks using ProcessPoolExecutor.

Parameters:

object (Any) – The object to get the name of

Returns:

The name of the object

Return type:

str

execute(tasks)[source]

Execute multiple tasks in parallel using ProcessPoolExecutor.

Parameters:

tasks (List[dict]) – A list of tasks to execute

Returns:

A dictionary of results for each task

Return type:

dict

Raises:

Exception – If an error occurs during task execution

run_task_parallel(task)[source]

Run a task in parallel using ProcessPoolExecutor.

Parameters:

task (dict) – The task to run

Returns:

The result of the task

Return type:

Any

ergodicity.tools.multiprocessing.create_task_key(params)[source]

” Create a unique key for a task based on its parameters.

Parameters:

params (dict) – The parameters of the task

Returns:

A string key representing the task

Return type:

str

ergodicity.tools.multiprocessing.ensemble_vs_time_average_pipeline(process_class, param_ranges, timestep=0.1, num_instances=3, time_average_time=10)[source]

Compare the ensemble average and time average growth rates for multiple parameter combinations.

Parameters:
  • process_class (type) – The stochastic process class

  • param_ranges (dict) – Dictionary of process parameters ranges

  • timestep (float) – Time step for the simulation

  • num_instances (int) – Number of instances to simulate

  • time_average_time (float) – Time for time average calculation

Returns:

A dictionary of results

Return type:

dict

ergodicity.tools.multiprocessing.general_pipeline(process_class, param_ranges, t=1, timestep=0.1, num_instances=3, time_average_time=10)[source]

Run an example of general research pipeline that includes simulations, visualizations, and growth rate calculations.

Parameters:
  • process_class (type) – The stochastic process class

  • param_ranges (dict) – Dictionary of process parameters ranges

  • t (float) – Total time for the simulation

  • timestep (float) – Time step for the simulation

  • num_instances (int) – Number of instances to simulate

  • time_average_time (float) – Time for time average calculation

Returns:

A dictionary of results

Return type:

dict

ergodicity.tools.multiprocessing.get_object_name(obj)[source]

Get the name of an object from the local variables in the calling frame.

Parameters:

obj (Any) – The object to get the name of

Returns:

The name of the object

Return type:

str

ergodicity.tools.multiprocessing.growth_rate_of_average_pipeline(process_class, process_params, t, timestep)[source]

Compute the growth rate of the average of multiple instances of a stochastic process. When num_instances = 1 and time is large, this function returns a time average approximation. When num_instance -> infinity and time is relatively small, this function returns an ensemble average approximation. The idea is to look at what exactly happens when num_instances is in between 1 and infinity.

Parameters:
  • process_class (type) – The stochastic process class

  • process_params (dict) – Dictionary of process parameters

  • t (float) – Total time for the simulation

  • timestep (float) – Time step for the simulation

Returns:

The growth rate of the average of multiple instances

Return type:

float

ergodicity.tools.multiprocessing.growth_rate_wrapper(func)[source]

A decorator that wraps functions related to growth rate calculations.

Parameters:

func (Callable) – The function to wrap

Returns:

The wrapped function

Return type:

Callable

ergodicity.tools.multiprocessing.initial_tasks_wrapper(task_name, specific_args)[source]

A decorator for functions that create initial tasks for parallel execution. Initial tasks are the tasks that generate the data to be used in subsequent tasks. They do not require any input data.

Parameters:
  • task_name (str) – The name of the task

  • specific_args (dict) – Specific arguments for the task

Returns:

The decorator function

Return type:

Callable

ergodicity.tools.multiprocessing.multi_growth_rate_ensemble_average(process_class, param_ranges)[source]

Run multiple growth rate calculations for ensemble average in parallel.

Parameters:
  • process_class (type) – The stochastic process class

  • param_ranges (dict) – Dictionary of process parameters ranges

Returns:

A tuple of tasks and a mapping of parameters to tasks

Return type:

tuple

ergodicity.tools.multiprocessing.multi_growth_rate_processor(process_class, params, t_range, num_instances_range, timestep=0.1)[source]

Run the growth rate calculation for multiple parameter combinations in parallel.

Parameters:
  • process_class (type) – The stochastic process class

  • params (dict) – Dictionary of process parameters

  • t_range (list) – List of time values

  • num_instances_range (list) – List of number of instances

  • timestep (float) – Time step for the simulation

Returns:

The growth rates for each parameter combination

Return type:

dict

Raises:

Exception – If an error occurs during the simulation or calculation

ergodicity.tools.multiprocessing.multi_growth_rate_time_average(process_class, param_ranges)[source]

Run multiple growth rate calculations for time average in parallel.

Parameters:
  • process_class (type) – The stochastic process class

  • param_ranges (dict) – Dictionary of process parameters ranges

Returns:

A tuple of tasks and a mapping of parameters to tasks

Return type:

tuple

ergodicity.tools.multiprocessing.multi_simulations(process_class, param_ranges)[source]

Run multiple simulations of stochastic processes in parallel for different parameter combinations.

Parameters:
  • process_class (type) – The stochastic process class

  • param_ranges (dict) – Dictionary of process parameters ranges

Returns:

A tuple of tasks and a mapping of parameters to tasks

Return type:

tuple

ergodicity.tools.multiprocessing.multi_visualize_moment(simulation_results, param_to_task)[source]

Run multiple tasks in parallel to visualize a specific moment of the simulation results.

Parameters:
  • simulation_results (Any) – The results of the simulations

  • param_to_task (dict) – The mapping of parameters to tasks

Returns:

A tuple of tasks and a mapping of parameters to tasks

Return type:

tuple

ergodicity.tools.multiprocessing.multi_visualize_moments(simulation_results, param_to_task)[source]

Run multiple tasks in parallel to visualize moments of the simulation results.

Parameters:
  • simulation_results (Any) – The results of the simulations

  • param_to_task – The mapping of parameters to tasks

Returns:

A tuple of tasks and a mapping of parameters to tasks

Return type:

tuple

ergodicity.tools.multiprocessing.parallel(func: Callable, data, **kwargs) int[source]

Run any library function in parallel with multiple sets of arguments.

Parameters:
  • func (Callable) – The function to be run in parallel

  • data (list) – The list of arguments to be passed to the function

  • kwargs (dict) – Additional keyword arguments to be passed to the function

Returns:

The results of the function run in parallel

Return type:

int

ergodicity.tools.multiprocessing.parallel_example()[source]

Example function to demonstrate the parallel processing capabilities.

Returns:

The results of the parallel execution

Return type:

Any

ergodicity.tools.multiprocessing.parallel_processor(func: Callable)[source]

A decorator that wraps any function, allowing it to process multiple datasets in parallel.

Parameters:

func (Callable) – The function to wrap

Returns:

The wrapped function

Return type:

Callable

ergodicity.tools.multiprocessing.secondary_tasks_wrapper(task_name, specific_args)[source]

A decorator for functions that create secondary tasks for parallel execution. Secondary tasks are the tasks that process the data generated by the initial tasks. They require input data from the initial tasks.

Parameters:
  • task_name (str) – The name of the task

  • specific_args (dict) – Specific arguments for the task

Returns:

The decorator function

Return type:

Callable

ergodicity.tools.multiprocessing.simulate_and_calculate_growth_rate(data: ndarray)[source]

Simulate a stochastic process and calculate the growth rate of the average.

Parameters:

data (np.ndarray) – The data array for the simulation

Returns:

The growth rate of the average

Return type:

float

Raises:

Exception – If an error occurs during the simulation or calculation

ergodicity.tools.multiprocessing.task_wrapper(save: bool = True, output_dir='output', print_debug=False)[source]

A decorator for functions that create tasks for parallel execution.

Parameters:
  • save (bool) – Whether to save the results to disk

  • output_dir (str) – The directory to save the results

  • print_debug (bool) – Whether to print debug information

Returns:

The decorator function

Return type:

Callable

ergodicity.tools.multiprocessing.visualize_growth_rates(results, process_class, params)[source]

Visualize the growth rates for multiple parameter combinations.

Parameters:
  • results (dict) – The growth rates for each parameter combination

  • process_class (type) – The stochastic process class

  • params (dict) – Dictionary of process parameters

Returns:

None

Return type:

None

ergodicity.tools.partial_sde module

partial_sde Submodule

The Partial SDE submodule provides functionality for simulating, visualizing, and analyzing stochastic partial differential equations (SPDEs). The core of this module is the PSDESimulator class, which implements numerical solutions to SPDEs, allowing users to model systems with both deterministic drift and stochastic diffusion terms over time and space.

Key Features:

  1. Stochastic PDE Simulation:

    • The simulator models the evolution of a spatially distributed quantity u(t, x) over time with specified drift and diffusion terms. These terms represent the deterministic and stochastic components of the equation, respectively.

    • The simulator supports different boundary conditions including Dirichlet, Neumann, and periodic.

  2. Numerical Solution:

    • The SPDE is solved using a finite difference approach in both time and space, with the option to include stochastic noise (via a Wiener process) at each time step.

  3. Visualization:

    • 2D Plots: The plot_results method provides a 2D surface plot of the solution over time and space, along with a time slice at the final time step.

    • 3D Plots: The plot_3d method generates a 3D surface plot to visualize the evolution of the solution.

    • Animations: The create_animation method generates an animation of the solution’s evolution, saved as a video file.

  4. Customizability:

    • Users can define their own drift and diffusion terms, initial conditions, and boundary conditions to simulate a wide variety of SPDEs.

    • The spatial and temporal resolution can be adjusted through the nx (number of spatial points) and nt (number of time points) parameters.

Example Usage:

if __name__ == “__main__”:

# Define the drift (deterministic) term of the SPDE (e.g., heat equation)

def drift(t, x, u, u_x, u_xx):

return 0.01 * u_xx # Heat equation term

# Define the diffusion (stochastic) term of the SPDE

def diffusion(t, x, u):

return 0.1 * np.ones_like(x) # Constant noise term

# Define the initial condition

def initial_condition(x):

return np.sin(np.pi * x) # Initial sine wave

# Initialize the simulator

simulator = PSDESimulator(

drift=drift, diffusion=diffusion, initial_condition=initial_condition, x_range=(0, 1), t_range=(0, 1), nx=100, nt=1000

)

# Run the simulation

simulator.simulate()

# Visualize the results

simulator.plot_results()

simulator.plot_3d()

simulator.create_animation(“spde_evolution.mp4”)

print(“Simulation and visualization complete.”)

class ergodicity.tools.partial_sde.PSDESimulator(drift: ~typing.Callable, diffusion: ~typing.Callable, initial_condition: ~typing.Callable, x_range: tuple, t_range: tuple, nx: int, nt: int, boundary_condition: ~typing.Tuple[str, ~typing.Callable] = ('dirichlet', <function PSDESimulator.<lambda>>), increment: ~typing.Callable = <function wiener_increment_function>)[source]

Bases: object

Partial Stochastic Differential Equation (PSDE) Simulator. This class provides functionality to simulate and visualize the stochastic evolution of a spatially distributed quantity

drift

The drift function f(t, x, u, u_x, u_xx)

Type:

Callable

diffusion

The diffusion function g(t, x, u)

Type:

Callable

initial_condition

The initial condition u(0, x)

Type:

Callable

x_range

The spatial range (x_min, x_max)

Type:

tuple

t_range

The time range (t_min, t_max)

Type:

tuple

nx

Number of spatial points

Type:

int

nt

Number of time points

Type:

int

boundary_type

Type of boundary condition (e.g., “dirichlet”, “neumann”, “periodic”)

Type:

str

boundary_func

The boundary condition function

Type:

Callable

x

Spatial grid points

Type:

ndarray

t

Time grid points

Type:

ndarray

dx

Spatial step size

Type:

float

dt

Time step size

Type:

float

u

Array to store the solution u(t, x)

Type:

ndarray

apply_boundary_condition(n)[source]

Apply boundary conditions at time step n.

Parameters:

n (int) – The time step index

Returns:

None

Return type:

None

create_animation(filename='psde_evolution.mp4')[source]

Create an animation of the function evolution. The animation shows the spatial distribution of u at each time step.

Parameters:

filename (str) – The name of the output file (default: ‘psde_evolution.mp4’)

Returns:

None

Return type:

None

plot_3d()[source]

Create a 3D plot of the function evolution. This plot shows the surface of u(t,x) over time and space.

Returns:

None

Return type:

None

plot_results()[source]

Plot the results of the simulation. This includes a 2D surface plot of the function evolution and a time slice at the final time step.

Returns:

None

Return type:

None

simulate()[source]

Run the simulation.

Returns:

None

Return type:

None

ergodicity.tools.partial_sde.wiener_increment_function(timestep_increment: float)[source]

Function to generate Wiener process increments. This is a default increment function for the PSDE simulator. It can be changed to use different increments, such as for example Levy increments.

Parameters:

timestep_increment (float) – The time step of the discrete increment

Returns:

The Wiener process increment

Return type:

float

ergodicity.tools.preasymptotics module

preasymptotic Submodule

The Preasymptotics submodule provides tools to estimate, model, and test the speed of convergence to a limiting distribution, such as the normal distribution or other asymptotic limits. The core functionality is divided into three main components:

  1. Preasymptotic Behavior Quantification: This class analyzes the rate at which a time series converges to its asymptotic value and investigates transient behaviors before reaching the steady state.

  2. Visualization Tools: This class visualizes various aspects of the time series, including distribution evolution, multi-scale analysis, and scaling behavior.

  3. Statistical Testing and Validation: This class performs statistical tests, such as bootstrapping, surrogate data testing, and cross-validation, to validate hypotheses about the time series.

Key Features:

  1. Preasymptotic Behavior Quantification:

    • Convergence Rate Estimation: Estimates how quickly a time series converges to its asymptotic value using an exponential decay model.

    • Transient Fluctuation Analysis: Examines fluctuations in the time series over time, estimating the decay rate of these fluctuations.

    • Time-to-Stationarity Estimation: Determines how long it takes for the time series to become approximately stationary using the Augmented Dickey-Fuller (ADF) test.

  2. Visualization Tools:

    • Time Series Plotting: Plots the time series over different time windows to visualize transient behavior.

    • Distribution Evolution: Shows how the distribution of the time series changes over different time intervals.

    • Scaling Analysis: Creates log-log plots for different statistical properties of the time series (e.g., variance, mean, max).

    • Heatmap and 3D Surface Plotting: Provides heatmaps for time-dependent statistics and 3D surface plots for multi-scale analysis.

  3. Statistical Testing and Validation:

    • Bootstrap Confidence Interval Estimation: Provides confidence intervals for statistical metrics through bootstrapping.

    • Surrogate Data Testing: Validates time series characteristics against surrogate data using methods such as phase randomization.

    • Cross-Validation for Time Series: Implements time series cross-validation with user-defined models to validate forecasting performance.

  4. Reporting and Exporting:

    • PDF/HTML Report Generation: Creates detailed reports summarizing the preasymptotic behavior and statistical testing results in PDF or HTML format.

    • Result Export: Exports results in CSV and JSON formats.

    • Visualization Export: Saves visualizations as image files (PNG or SVG).

Example Usage:

if __name__ == “__main__”:

# Generate a sample non-stationary time series

np.random.seed(0)

t = np.linspace(0, 10, 1000)

non_stationary_series = 10 * np.exp(-0.5 * t) * np.sin(t) + np.cumsum(np.random.normal(0, 0.1, 1000))

# Initialize the PreasymptoticBehaviorQuantification object

pbq = PreasymptoticBehaviorQuantification(non_stationary_series, t)

# Perform analyses

convergence_results = pbq.convergence_rate_estimation()

fluctuation_results = pbq.transient_fluctuation_analysis()

stationarity_results = pbq.time_to_stationarity_estimation()

# Visualize the results

pbq.plot_results(convergence_results, fluctuation_results, stationarity_results)

# Generate and export reports

reporter = ReportingAndExport(non_stationary_series, t)

reporter.generate_pdf_report()

reporter.export_results_csv()

reporter.export_visualizations(format=’png’)

class ergodicity.tools.preasymptotics.PreasymptoticBehaviorQuantification(time_series, time_values=None)[source]

Bases: object

Class to quantify preasymptotic behavior in time series data. It provides methods to estimate convergence rates, transient fluctuations, and time to stationarity.

time_series

Time series data

Type:

array

time_values

Time values corresponding to the data points

Type:

array

convergence_rate_estimation(window_size=100, asymptotic_value=None)[source]

Estimate the convergence rate to asymptotic value.

Parameters:
  • window_size (int) – Size of the moving window

  • asymptotic_value (float, optional) – Known asymptotic value. If None, uses the mean of the last window as an estimate.

Returns:

Dictionary containing convergence rate and related information

Return type:

dict

plot_results(convergence_results, fluctuation_results, stationarity_results)[source]

Plot the results of preasymptotic behavior quantification.

Parameters:
  • convergence_results (dict) – Results from convergence_rate_estimation

  • fluctuation_results (dict) – Results from transient_fluctuation_analysis

  • stationarity_results (dict) – Results from time_to_stationarity_estimation

Returns:

None

Return type:

None

time_to_stationarity_estimation(window_size=100, p_threshold=0.05)[source]

Estimate the time to reach approximate stationarity.

Parameters:
  • window_size (int) – Size of the moving window for the ADF test

  • p_threshold (float) – p-value threshold for the ADF test

Returns:

Dictionary containing time-to-stationarity estimation results

Return type:

dict

transient_fluctuation_analysis(window_size=100)[source]

Analyze transient fluctuations in the time series.

Parameters:

window_size (int) – Size of the moving window

Returns:

Dictionary containing transient fluctuation analysis results

Return type:

dict

class ergodicity.tools.preasymptotics.PreasymptoticVisualizationTools(time_series, time_values=None)[source]

Bases: object

Class to visualize preasymptotic behavior in time series data. It provides tools to plot time series windows,

time_series

array

time_values

array

plot_3d_multiscale_analysis(max_scale=10)[source]

Create a 3D surface plot for multi-scale analyses.

Parameters:

max_scale (int) – Maximum scale for the analysis

Returns:

None

Return type:

None

plot_distribution_evolution(num_windows=5)[source]

Plot the evolution of the distribution over time.

Parameters:

num_windows (int) – Number of time windows to use for distribution evolution

Returns:

None

Return type:

None

plot_scaling_analysis(statistic='variance', num_points=20)[source]

Create log-log plots of various statistics.

Parameters:
  • statistic (str) – Statistic to analyze (‘variance’, ‘abs_mean’, or ‘max’)

  • num_points (int) – Number of points to use in the log-log plot

Returns:

None

Return type:

None

plot_time_dependent_heatmap(window_size=100, step_size=10)[source]

Create a heatmap for time-dependent analyses. It allows visualization of time-dependent statistics like mean, standard deviation, and skewness.

Parameters:
  • window_size (int) – Size of the sliding window

  • step_size (int) – Step size for sliding the window

Returns:

None

Return type:

None

plot_time_series_windows(window_sizes=[100, 500, 1000])[source]

Plot time series with variable time windows.

Parameters:

window_sizes (list of int) – Sizes of time windows to plot

Returns:

None

Return type:

None

class ergodicity.tools.preasymptotics.ReportingAndExport(time_series, time_values=None)[source]

Bases: object

Class to generate reports and export results of preasymptotic analysis. The reports can be generated in PDF or HTML format.

time_series

array

time_values

array

export_results_csv(filename='preasymptotic_analysis_results.csv')[source]

Export analysis results to a CSV file.

Parameters:

filename (str) – Name of the CSV file, optional

Returns:

None

Return type:

None

export_results_json(filename='preasymptotic_analysis_results.json')[source]

Export analysis results to a JSON file.

Parameters:

filename (str) – Name of the JSON file, optional

Returns:

None

Return type:

None

export_visualizations(format='png')[source]

Export visualizations as image files.

Parameters:

format (str) – Format for the exported files (‘png’ or ‘svg’)

Returns:

None

Return type:

None

generate_html_report(filename='preasymptotic_analysis_report.html')[source]

Generate an HTML report of the preasymptotic analysis.

Parameters:

filename (str) – Name of the HTML file, optional

Returns:

None

Return type:

None

generate_pdf_report(filename='preasymptotic_analysis_report.pdf')[source]

Generate a PDF report of the preasymptotic analysis.

Parameters:

filename (str) – name of the PDF file, optional

Returns:

None

Return type:

None

class ergodicity.tools.preasymptotics.StatisticalTestingValidation(time_series, time_values=None)[source]

Bases: object

Class to perform statistical testing and validation on time series data with the emphasis on preasymptotics.

time_series

array

time_values

array

bootstrap_confidence_interval(statistic_func, n_bootstraps=1000, confidence_level=0.95)[source]

Estimate confidence intervals using bootstrap method.

Parameters:
  • statistic_func (callable) – Function to compute the statistic of interest

  • n_bootstraps (int) – Number of bootstrap samples

  • confidence_level (float) – Confidence level for the interval

Returns:

Lower and upper bounds of the confidence interval

Return type:

tuple

cross_validation(model_func, n_splits=5)[source]

Perform time series cross-validation.

Parameters:
  • model_func (callable) – Function that takes training data and returns predictions for test data

  • n_splits (int) – Number of splits for cross-validation

Returns:

List of error scores for each split

Return type:

list

plot_results(bootstrap_results, surrogate_results, cv_results)[source]

Plot the results of statistical testing and validation.

Parameters:
  • bootstrap_results (tuple) – Results from bootstrap_confidence_interval

  • surrogate_results (tuple) – Results from surrogate_data_test

  • cv_results (list) – Results from cross_validation

Returns:

None

Return type:

None

surrogate_data_test(test_statistic_func, n_surrogates=1000, method='phase_randomization')[source]

Perform surrogate data testing.

Parameters:
  • test_statistic_func (callable) – Function to compute the test statistic

  • n_surrogates (int) – Number of surrogate series to generate

  • method (str) – Method for generating surrogates (‘phase_randomization’ or ‘bootstrap’)

Returns:

Tuple of p-value, original statistic, and surrogate statistics

Return type:

tuple

ergodicity.tools.research module

research Submodule

This submodule provides predefined high-level functions to run massive parallel simulations and compute various statistical measures for different stochastic processes. The functions are organized into pipelines, each designed to handle a specific process type with customizable parameter ranges. These pipelines return simulation results in the form of dictionaries, allowing for easy analysis and visualization.

Key Functions:

  1. LevyMicro_case:

    • Simulates and analyzes Geometric Lévy processes for specific values of the stability parameter (α), location (loc), scale, and skewness (β).

  2. TestingGeometricLevyPipeline_case:

    • Runs a similar pipeline as LevyMicro_case, but for a broader range of α values.

  3. GeometricLevyPipeline_case:

    • Simulates Geometric Lévy processes across a larger set of parameter ranges, including more granular values for α, location, scale, and β.

  4. GBMPipeline_case:

    • Simulates Multivariate Geometric Brownian Motion (GBM) processes for a range of drift and scale parameters.

  5. FractionalGBMPipeline_case:

    • Runs simulations of Geometric Fractional Brownian Motion (fBM) for different values of drift, scale, and Hurst exponent (H).

  6. LevyPipeline_case:

    • Simulates Lévy stable processes using different combinations of α, loc, scale, and β parameters.

  7. Live 3D Visualization Pipelines:

    • live_3d_Levy_pipeline_case, live_3d_Brownian_pipeline_case, and live_3d_geometricLevy_pipeline_case are used to generate live 3D visualizations for Lévy, Brownian Motion, and Geometric Lévy processes respectively.

  8. TINstancesPipeline_case:

    • This pipeline is designed to analyze the growth rate of the average over time for multiple instances of the Geometric Lévy process.

  9. AverageRateVsRateAveragePipeline_case:

    • Compares the average of growth rates over multiple instances with the rate of the overall average for Geometric Lévy processes.

Combining Pipelines:

  • live_3d_meta_pipeline_case:

    • Combines the 3D visualization pipelines for Lévy, Brownian Motion, and Geometric Lévy processes into a single meta pipeline.

Example Usage:

if __name__ == “__main__”:

# Example: Running the Geometric Lévy process pipeline with a variety of parameters

results = GeometricLevyPipeline_case()

print(“Geometric Lévy process simulation results:”, results)

# Example: Running the Brownian Motion process pipeline

results_gbm = GBMPipeline_case()

print(“GBM process simulation results:”, results_gbm)

# Example: Running a live 3D visualization for Geometric Lévy processes

live_3d_geometricLevy_pipeline_case()

ergodicity.tools.research.AverageRateVsRateAveragePipeline_case()[source]

This function compares the average of growth rates over multiple instances with the rate of the overall average for Geometric Lévy processes.

Returns:

results (dict): Simulation results for the average rate comparison

Return type:

dict

ergodicity.tools.research.FractionalGBMPipeline_case()[source]

This function runs a pipeline for Geometric Fractional Brownian Motion processes with different values of drift, scale, and Hurst exponent.

Returns:

results (dict): Simulation results for the Geometric fBM process

Return type:

dict

ergodicity.tools.research.GBMPipeline_case()[source]

This function runs a pipeline for Multivariate Geometric Brownian Motion processes with a range of drift and scale parameters.

Returns:

results (dict): Simulation results for the Multivariate GBM process

Return type:

dict

ergodicity.tools.research.GeometricLevyPipeline_case()[source]

This function runs a large full-fledged pipeline for Geometric Lévy processes with a larger set of parameter ranges.

Returns:

results (dict): Simulation results for the Geometric Lévy process

Return type:

dict

ergodicity.tools.research.LevyMicro_case()[source]

This function runs a small pipeline for Geometric Lévy processes with specific parameter values.

Returns:

results (dict): Simulation results for the Geometric Lévy process

Return type:

dict

ergodicity.tools.research.LevyPipeline_case()[source]

This function runs a pipeline for Lévy stable processes with different combinations of α, loc, scale, and β parameters.

Returns:

results (dict): Simulation results for the Lévy stable process

Return type:

dict

ergodicity.tools.research.TINstancesPipelineTest_case()[source]

This function runs a test pipeline for analyzing the growth rate of the average over time for multiple instances of the Geometric Lévy process.

Returns:

results (dict): Simulation results for the growth rate analysis

Return type:

dict

ergodicity.tools.research.TINstancesPipeline_case()[source]

This function runs a pipeline for analyzing the growth rate of the average over time for multiple instances of the Geometric Lévy process.

Returns:

results (dict): Simulation results for the growth rate analysis

Return type:

dict

ergodicity.tools.research.TestingGeometricLevyPipeline_case()[source]

This function runs a testing pipeline for Geometric Lévy processes with a broader range of α values.

Returns:

results (dict): Simulation results for the Geometric Lévy process

Return type:

dict

ergodicity.tools.research.live_3d_Brownian_pipeline_case()[source]

This function generates a live 3D visualization for Brownian Motion processes.

Returns:

None

ergodicity.tools.research.live_3d_Levy_pipeline_case()[source]

This function generates a live 3D visualization for Lévy stable processes.

Returns:

None

ergodicity.tools.research.live_3d_geometricLevy_pipeline_case()[source]

This function generates a live 3D visualization for Geometric Lévy processes.

Returns:

None

ergodicity.tools.research.live_3d_meta_pipeline_case()[source]

This function combines the 3D visualization pipelines for Lévy, Brownian Motion, and Geometric Lévy processes into a single meta pipeline.

Returns:

None

ergodicity.tools.solve module

solve Submodule

The solve submodule is designed to tackle stochastic differential equations (SDEs) and related topics in stochastic calculus, particularly through symbolic computation. The submodule provides tools for applying Ito’s Lemma, integrating SDEs, performing transformations for ergodicity, and solving Fokker-Planck equations. It also offers methods to analyze convergence rates and ergodic behavior in stochastic systems.

Key Features:

  1. Ito Calculus:

    • ito_differential: Applies Ito’s Lemma to a given function f(x, t) where x follows a stochastic differential equation (SDE).

    • ito_integrate: Performs Ito integration of drift and diffusion terms over time and Wiener processes.

  2. Solving SDEs:

    • solve: Solves stochastic differential equations analytically where possible, by leveraging substitution techniques and Ito’s Lemma.

    • integration_check: Validates the solution of an SDE by verifying consistency between the initial SDE and the solution found through integration.

  3. Ergodicity:

    • ergodicity_transform: Checks the consistency condition for ergodicity and computes the transformation if the condition is met.

    • calculate_time_average_dynamics: Computes the time-average dynamics of a stochastic process using the ergodicity transform.

    • compare_averages: Compares the time and ensemble averages to determine long-term behavior.

  4. Convergence Analysis:

    • functions_convergence_rate: Computes the convergence rate of a function to its asymptotic behavior.

    • mean_convergence_rate_alpha_stable: Calculates the convergence rate for processes in the domain of attraction of stable distributions.

    • mad_convergence_rate_alpha_stable: Determines the rate of convergence of the Mean Absolute Deviation (MAD) for alpha-stable processes.

  5. Fokker-Planck Equation:

    • solve_fokker_planck: Symbolically solves the Fokker-Planck equation for a given drift and diffusion term under specified initial and boundary conditions.

  6. Advanced Theorems:

    • apply_girsanov: Applies Girsanov’s theorem to change the drift of an SDE under a new probability measure, ensuring Novikov’s condition holds.

    • check_novikov_condition: Validates the applicability of Girsanov’s theorem by checking if Novikov’s condition is satisfied.

  7. Utilities:

    • find_inverse: Attempts to symbolically invert a function.

    • asymptotic_approximation: Finds the leading term in an expression as time tends to infinity, providing insights into the long-term behavior of a process.

    • ensemble_average and time_average: Calculate the ensemble and time averages of a stochastic process.

Applications:

  • Financial Mathematics: Solve SDEs related to asset prices, option pricing, and portfolio optimization.

  • Physics: Model diffusion processes, Brownian motion, and ergodic behavior in physical systems.

  • Engineering: Analyze control systems and noise in dynamic environments.

  • Mathematical Research: Study convergence rates, stochastic calculus, and the behavior of complex stochastic systems.

This submodule is a powerful toolkit for anyone involved in the analysis of stochastic processes, offering symbolic solutions and insights into the dynamics of complex systems.

ergodicity.tools.solve.apply_girsanov(initial_drift, new_drift, diffusion, time_horizon)[source]

Applies Girsanov’s theorem to an Itô process to change the drift of the process.

Parameters:
  • initial_drift (sympy expression) – The initial drift function mu_initial(X_t, t)

  • new_drift (sympy expression) – The new drift function mu_new(X_t, t)

  • diffusion (sympy expression) – The diffusion term sigma(X_t, t)

  • time_horizon (float) – The time horizon T for the process

Returns:

The transformed drift and the new process

Return type:

sympy expression

Raises:

ValueError – If Novikov’s condition is not satisfied

ergodicity.tools.solve.asymptotic_approximation(expr, t=t, W=W(t))[source]

Find the asymptotic approximation of an expression as t approaches infinity. This basiscally allows to calculate time average behavior of the expression.

Parameters:
  • expr (sympy expression) – The expression to approximate

  • t (sympy symbol) – The symbol representing the variable approaching infinity

  • W (sympy function) – The Wiener process W(t)

Returns:

The leading term in the expression as t -> infinity

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.calculate_moment(pdf, x, n)[source]

Calculate the n-th moment of a probability density function (PDF).

Parameters:
  • pdf (sympy expression) – The probability density function (PDF)

  • x (sympy symbol) – The random variable in the PDF

  • n (int) – The order of the moment to calculate (e.g., 1 for mean, 2 for variance)

Returns:

The n-th moment of the PDF

Return type:

sympy expression

ergodicity.tools.solve.calculate_time_average_dynamics(u, a_u, x, t)[source]

Calculate the time average dynamics using the ergodicity transform. It is done by inverting the ergodicity transform and applying the inverse to a_u * t.

Parameters:
  • u (sympy expression) – The ergodicity transform u(t,x)

  • a_u (sympy expression) – The transformed drift term

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

Returns:

The time average dynamics expression

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.check_novikov_condition(theta_t, t, T)[source]

Checks Novikov’s condition over a finite time horizon T.

Parameters:
  • theta_t (sympy expression) – The adjustment to the drift (Radon-Nikodym derivative)

  • t (sympy symbol) – The time variable

  • T (float or sympy expression) – The finite time horizon

Returns:

Whether Novikov’s condition holds over [0, T]

Return type:

boolean

ergodicity.tools.solve.compare_averages(expr, t=t, W=W(t))[source]

Compare the time average and ensemble average of a stochastic process.

Parameters:
  • expr (sympy expression) – The stochastic process x(t, W(t))

  • t (sympy symbol) – The symbol representing time t

  • W (sympy function) – The Wiener process W(t)

Returns:

The ratio of time average to ensemble average

Return type:

float

ergodicity.tools.solve.compare_growth(term1, term2, t)[source]

Compare the growth rates of two terms as t approaches infinity. A helper function for asymptotic approximation.

Parameters:
  • term1 (sympy expression) – The first term to compare

  • term2 (sympy expression) – The second term to compare

  • t (sympy symbol) – The symbol representing the variable approaching infinity

Returns:

1 if term1 grows faster, -1 if term2 grows faster, 0 if equal

Return type:

int

ergodicity.tools.solve.dynamic_from_utility(u_function, x, mu_u, sigma_u)[source]

Calculate the dynamics of the ergodicity transform u(t,x) using Ito calculus. It finds a stochastic dynamic corresponding to the given ergodicity transform. Hence, it allows to estimate what stochastic dynamics corresponds to the given “utility” function.

Parameters:
  • u_function (sympy expression) – The ergodicity transform u(t,x)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • mu_u (sympy expression) – The drift term mu_u(x,t)

  • sigma_u (sympy expression) – The diffusion term sigma_u(x,t)

Returns:

The stochastic dynamic corresponding to the ergodicity transform u(t,x)

Return type:

sympy expression

ergodicity.tools.solve.ensemble_average(x_expr, t, W)[source]

Calculate the expected value of a stochastic process x(t, W(t)) by replacing W(t) with a standard normal distribution N(0,1).

Parameters:
  • x_expr (sympy expression) – The stochastic process x(t, W(t))

  • t (sympy symbol) – The symbol representing time t

  • W (sympy function) – The Wiener process W(t)

Returns:

The expected value of x(t, W(t))

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.ergodicity_transform(mu, sigma, x, t)[source]

Check the consistency condition for ergodicity and find the ergodicity transform if consistent. b_u from the ergodicity economics book (page 57) is set to 1. Then, a_u = c. The function is implemented only for the case when mu ang sigma are only functions of x.

Parameters:
  • mu (sympy expression) – The drift term mu(x,t)

  • sigma (sympy expression) – The diffusion term sigma(x,t)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

Returns:

A tuple (is_consistent, u(t,x), a_u, b_u) where u(t,x) is the ergodicity transform

Return type:

tuple

Exception:

Returns (False, None, None) if an error occurs during the calculation

ergodicity.tools.solve.ergodicity_transform_differential(u, a_u, b_u, x, t)[source]

Calculate the differential form of the ergodicity transform. The function is implemented only for the case when mu ang sigma are only functions of x.

Parameters:
  • u (sympy expression) – The ergodicity transform u(t,x)

  • a_u (sympy expression) – The transformed drift term a_u

  • b_u (sympy expression) – The transformed diffusion term b_u

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

Returns:

The transformed differential df(x,t) = a_u dt + b_u dW(t)

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.extract_ito_terms(differential, x, t)[source]

Extract the mu(x,t) and sigma(x,t) terms from a differential expression of the form: mu(x,t)dt + sigma(x,t)dW(t)

Parameters:
  • differential (sympy expression) – The differential expression, typically the result of applying Ito’s Lemma

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

Returns:

A tuple of sympy expressions (mu(x,t), sigma(x,t))

Return type:

tuple

ergodicity.tools.solve.find_dx(x, t, W)[source]

Find dX(X,t,W(t)) for a given X(t,W(t)) using Ito calculus rules, and attempt to simplify the result in terms of X where possible.

Parameters:
  • x (sympy expression) – The stochastic process X(t,W(t))

  • t (sympy symbol) – The symbol representing time t

  • W (sympy function) – The Wiener process W(t)

Returns:

The SDE in the form dX = … dt + … dW, with X substituted where possible

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.find_inverse(f, x, y)[source]

Attempt to find the inverse of f(x,t) with respect to x.

Parameters:
  • f (sympy expression) – The function f(x,t) to invert

  • x (sympy symbol) – The symbol representing the variable x

  • y (sympy symbol) – The symbol to represent f(x,t) in the inverse function

Returns:

The inverse function if found, None otherwise

Return type:

sympy expression or None

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.find_substitution(mu, sigma, x, t)[source]

Find a suitable substitution for solving a stochastic differential equation analytically.

Parameters:
  • mu (sympy expression) – The drift term mu(x,t)

  • sigma (sympy expression) – The diffusion term sigma(x,t)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

Returns:

The substitution function f(t,x) if found, None otherwise

Return type:

sympy expression or None

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.functions_convergence_rate(f, g, t)[source]

Calculate the rate of convergence of f(t) to its asymptotic approximation g(t).

Parameters:
  • f (sympy expression) – The original function

  • g (sympy expression) – The asymptotic approximation

  • t (sympy symbol) – The symbol representing the variable approaching infinity

Returns:

The order of convergence

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.integrate_with_substitution(f, mu, sigma, x, t, x0=1)[source]

Perform Ito integration with substitution.

Parameters:
  • f (sympy expression) – The function f(x,t) for substitution

  • mu (sympy expression) – The drift term mu(x,t)

  • sigma (sympy expression) – The diffusion term sigma(x,t)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

  • x0 (int, optional) – The initial value of x at t=0, defaults to 1

Returns:

The result of the integration after substitution

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.integration_check(f, mu, sigma, x, t, x0=1)[source]

Check the integration of a function f(x,t) with drift mu(x,t) and diffusion sigma(x,t).

Parameters:
  • f (sympy expression) – The function f(x,t) to integrate

  • mu (sympy expression) – The drift term mu(x,t)

  • sigma (sympy expression) – The diffusion term sigma(x,t)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

  • x0 (int, optional) – The initial value of x at t=0, defaults to 1

Returns:

The result of the integration if successful

Return type:

sympy expression

ergodicity.tools.solve.ito_differential(f, mu, sigma, x, t)[source]

Apply Ito’s Lemma to a function f(x,t) where x follows the SDE: dx = mu(x,t)dt + sigma(x,t)dW

Parameters:
  • f (sympy expression) – The function f(x,t) to which Ito’s Lemma is applied

  • mu (sympy expression) – The drift term mu(x,t) in the SDE

  • sigma (sympy expression) – The diffusion term sigma(x,t) in the SDE

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

Returns:

The resulting df(x,t) according to Ito’s Lemma

Return type:

sympy expression

ergodicity.tools.solve.ito_integrate(mu, sigma, x, t, x0=1)[source]

Integrate terms by dt and dW(t) from 0 to t. The dt term is integrated as a Riemann integral. The dW(t) term is integrated using Ito isometry.

Parameters:
  • mu (sympy expression) – The coefficient of dt (drift term)

  • sigma (sympy expression) – The coefficient of dW(t) (diffusion term)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

  • x0 (int, optional) – The initial value of x at t=0, defaults to 1

Returns:

The Ito integral expression

Return type:

sympy expression

ergodicity.tools.solve.mad_convergence_rate_alpha_stable(alpha, n)[source]

Calculate the convergence rate of Mean Absolute Deviation for alpha-stable processes.

Parameters:
  • alpha (float) – The stability parameter of the alpha-stable distribution (1 < alpha < 2)

  • n (sympy symbol) – The symbol representing the sample size

Returns:

The rate of convergence of the sample MAD

Return type:

sympy expression

Raises:

ValueError if alpha is not in the range (1, 2)

ergodicity.tools.solve.mean_convergence_rate_alpha_stable(alpha, n)[source]

Calculate the convergence rate for a distribution with infinite variance (alpha-stable).

Parameters:
  • alpha (float) – The stability parameter of the alpha-stable distribution (0 < alpha < 2)

  • n (sympy symbol) – The symbol representing the sample size

Returns:

The rate of convergence

Return type:

sympy expression

Raises:

ValueError if alpha is not in the range (0, 2)

ergodicity.tools.solve.replace_integration_constants(expr)[source]

Check if a given expression contains integration constants (C1, C2, etc. or numbers) and substitute them with 1.

Parameters:

expr (sympy expression) – The expression to check and modify

Returns:

The modified expression with integration constants replaced by 1

Return type:

sympy expression

ergodicity.tools.solve.solve(mu, sigma, x, t, x0=1)[source]

Solve the stochastic differential equation dx = mu dt + sigma dW(t) for x(t) analytically.

Parameters:
  • mu (sympy expression) – The drift term mu(x,t)

  • sigma (sympy expression) – The diffusion term sigma(x,t)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

  • x0 (int, optional) – The initial value of x at t=0, defaults to 1

Returns:

The solution x(t) if found

Return type:

sympy expression

ergodicity.tools.solve.time_average(mu, sigma, x, t)[source]

Calculate the time average of a stochastic process x(t, W(t)) using the ergodicity transform.

Parameters:
  • mu (sympy expression) – The drift term mu(x,t)

  • sigma (sympy expression) – The diffusion term sigma(x,t)

  • x (sympy symbol) – The symbol representing the stochastic variable x

  • t (sympy symbol) – The symbol representing time t

Returns:

The time average of x(t, W(t))

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

ergodicity.tools.solve.time_average_limit(x_expr, t, W)[source]

Calculate the time average of a stochastic process x(t, W(t)) by expressing W(t) as sqrt(t) * N(0,1) and finding the limit of x/t as t -> infinity.

Parameters:
  • x_expr (sympy expression) – The stochastic process x(t, W(t))

  • t (sympy symbol) – The symbol representing time t

  • W (sympy function) – The Wiener process W(t)

Returns:

The time average of x(t, W(t))

Return type:

sympy expression

Exception:

Returns None if an error occurs during the calculation

Module contents

tools Module Overview

The `tools` module is a comprehensive collection of submodules designed to facilitate the simulation, analysis, and evaluation of stochastic processes and related models. Each submodule serves a specific purpose, providing tools for various aspects of mathematical modeling, statistical analysis, numerical computation, and automation.

The module is structured to support high-efficiency parallel simulations, fitting of complex processes, analysis of preasymptotic behavior, and solving partial stochastic differential equations (PSDEs). The `tools` module is flexible, allowing for integration with different types of stochastic processes such as Brownian Motion, Lévy processes, and fractional processes.

Submodules:

  1. automate.py

    • Provides functions for automating large-scale simulations, including live visualizations and parameter sweeps. Designed for scalability and repetitive tasks in research and experimentation.

  2. compute.py

    • Contains numerical methods and algorithms to compute key metrics and statistics from simulations. It includes tools for analyzing ergodicity, ensemble averages, and time averages.

  3. evaluate.py

    • Implements evaluation methods to assess the behavior of stochastic processes. It includes functions for calculating rates of convergence and evaluating results against theoretical expectations.

  4. fit.py

    • Tools for fitting stochastic processes to observed data. Provides utilities to fit parameters of various distributions, including Lévy stable and geometric Brownian motion, using techniques like maximum likelihood estimation (MLE).

  5. helper.py

    • A utility module containing helper functions that support other submodules. These include data separation, saving and loading results, and visualization tools.

  6. multiprocessing.py

    • Manages parallel execution of simulations and tasks. This submodule allows for efficient parallelization using multiprocessing, enabling high-speed simulations of stochastic processes across different parameter ranges.

  7. partial_sde.py

    • Tools for simulating and solving partial stochastic differential equations (PSDEs). This submodule includes functions for handling boundary conditions, drift and diffusion terms, and creating visualizations of the resulting solutions.

  8. preasymptotics.py

    • Focuses on preasymptotic behavior, convergence analysis, and the speed of convergence to limiting distributions (e.g., normal or Lévy). Includes tools for analyzing transient fluctuations, time to stationarity, and convergence rates.

  9. research.py

    • A high-level submodule that organizes pipelines for running massive simulations and computing statistical measures. It provides pre-defined functions for simulating various stochastic processes, including Lévy and Brownian Motion, using parallel computing for large-scale experiments.

  10. solve.py

    • Includes methods for solving stochastic differential equations (SDEs) and related optimization tasks. Provides tools for applying Ito’s Lemma, solving complex SDEs, and performing integration with substitution.

Key Features:

  • Parallel Computing: The module extensively leverages multiprocessing for efficient simulations, allowing large-scale parameter sweeps and statistical analysis.

  • Live Visualizations: Real-time 2D and 3D visualizations to help researchers observe the dynamic evolution of stochastic processes.

  • Comprehensive Analysis Tools: From preasymptotic behavior to statistical validation, the module provides all necessary tools to assess the behavior and properties of simulated processes.

  • Flexible and Scalable: The structure of the module allows for easy expansion with additional processes, fitting techniques, and evaluation metrics.

Example Usage:

```python

from ergodicity.tools import research, fit, multiprocessing

# Run a Geometric Lévy Process pipeline with a wide range of parameters

results = research.GeometricLevyPipeline_case()

# Fit a Lévy stable distribution to observed data

data = np.random.normal(size=1000)

fitted_distribution = fit.levy_stable_fit(data)

# Run parallel simulations of a process

sim_results = multiprocessing.multi_simulations(MyStochasticProcess, param_ranges)