### Clone Repository and Install PyMultifracs Source: https://www.neurospin.fr/pymultifracs/index.html Clone the entire PyMultifracs repository to your local machine and then install it in editable mode. This is useful if you plan to modify the package or run examples. ```bash git clone https://github.com/neurospin/pymultifracs pip install -e pymultifracs ``` -------------------------------- ### Install PyMultifracs using Pip Source: https://www.neurospin.fr/pymultifracs/index.html Install the package directly from the GitHub repository using pip. This method installs the package for import. ```bash pip install git+https://github.com/neurospin/pymultifracs ``` -------------------------------- ### Query benchmark results Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Query the results dataframe to inspect specific subsets of the benchmark data. This example filters for results from the 'pleader' method and displays the first 10 rows. ```python bench.results.query('method=="pleader"').head(10) ``` -------------------------------- ### Install PyMultifracs using Conda Source: https://www.neurospin.fr/pymultifracs/index.html Use this command to update your conda environment with the necessary files from the env.yml. Ensure you have the correct environment name set. ```bash wget https://raw.githubusercontent.com/neurospin/pymultifracs/master/env.yml conda env update -f env.yml --name $ENVNAME ``` -------------------------------- ### Derive statistics from results Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Derive statistics from the benchmark results dataframe by grouping and calculating means. This example calculates the mean of 'c1' and 'c2' for 'fbm' signals with H=0.7, grouped by 'p_exp'. ```python bench.results.xs( ('fbm', 'pleader', .7), level=('model', 'method', 'H') ).groupby('p_exp').mean() ``` -------------------------------- ### Get Wavelet Transform Coefficients Source: https://www.neurospin.fr/pymultifracs/auto_examples/01-simul.html Extracts multi-resolution quantities from the wavelet transform. `get_leaders()` retrieves wavelet (p-)leaders, and `get_wse()` retrieves wavelet scale-wise energy. `p_exp` in `get_leaders` determines the exponent for the p-norm. ```python WTL = WT.get_leaders(p_exp=np.inf) WTpL = WT.get_leaders(p_exp=2) WSE = WT.get_wse(theta=0.5) ``` -------------------------------- ### Visualize group statistics with Seaborn Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Use Seaborn to visualize group statistics from the benchmark results. This example creates a boxplot comparing the 'c2' values for 'mrw' signals estimated with the 'pleader' method, across different 'p_exp' values. ```python import seaborn as sns sns.boxplot(data=bench.results.xs( ('mrw','pleader'), level=('model', 'method')), x='p_exp', y='c2') ``` -------------------------------- ### Instantiate and compute benchmark Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Instantiate the Benchmark class with the defined signal and estimation grids, then compute the benchmark to generate results. This process systematically tests all combinations. ```python bench = Benchmark( signal_gen_grid, signal_param_grid, estimation_grid, estimation_param_grid) bench.compute_benchmark() ``` -------------------------------- ### Method: bootstrap Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.multiresquantity.WaveletWSE.html Bootstrap the multi-resolution quantity by repeating. ```APIDOC ## bootstrap ### Description Bootstrap the multi-resolution quantity by repeating. ### Parameters #### Request Body - **R** (int) - Required - Number of repetitions of the bootstrap. - **min_scale** (int) - Optional - Minimum scale that will be kept in the bootstrapped MRQ. - **idx_reject** (dict[str, np.ndarray] | None) - Optional - Dictionary of rejected values. ### Response #### Success Response (200) - **WaveletDec** - MRQ containing the bootstrapped values. ``` -------------------------------- ### Define estimation parameter grids Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Create dictionaries specifying parameter grids for the estimation methods. This allows the benchmark to test different estimation parameters for each method. ```python estimation_param_grid = { 'pleader': { 'p_exp': np.array([0.5, 1, 2, 5]), }, 'coef': {} } estimation_grid = { 'pleader': pleader_est, 'coef': coef_est, } ``` -------------------------------- ### Import necessary libraries Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Import numpy and required modules from pymultifracs for signal simulation, wavelet analysis, multifractal analysis, and benchmarking. ```python import numpy as np from pymultifracs.simul import fbm, mrw from pymultifracs import wavelet_analysis, mfa from pymultifracs.robust.benchmark import Benchmark ``` -------------------------------- ### Determine Optimal Scaling Range (Per Moment) Source: https://www.neurospin.fr/pymultifracs/_downloads/12297bf87b30ae3499b9d7500abaf258/02-bootstrap.ipynb Finds the optimal scaling range on a per-moment basis using bootstrapping, allowing for moment-specific scale selection. ```python pwt.cumulants.find_best_range(per_moment=True) ``` -------------------------------- ### Define signal generation parameter grids Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Create dictionaries that specify the parameter grids for generating different types of signals (fbm and mrw). This allows the benchmark to systematically vary signal properties. ```python signal_param_grid = { 'fbm': { 'H': np.array([.7, .8]) }, 'mrw': { 'H': np.array([.7, .9]) } } signal_gen_grid = { 'fbm': fbm_gen, 'mrw': mrw_gen, } ``` -------------------------------- ### WaveletDec Class Overview Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.multiresquantity.WaveletDec.html Provides an overview of the WaveletDec class, its purpose, and how it should be instantiated. ```APIDOC ## Class WaveletDec ### Description Represents the wavelet coefficients of a signal dX(j,k). This class should not be instantiated directly but rather created using the `wavelet_analysis` function. ### Attributes - **values** (`dict`[`int`, `ndarray`]): A dictionary where `values[j]` contains the coefficients at scale `j`. The arrays have a shape of (nj, n_rep). - **n_channel** (`int`): The number of underlying signals in the wavelet decomposition. - **gamint** (`float`): The fractional integration used in the computation of the MRQ. - **wt_name** (`str`): The name of the wavelet used for the decomposition. - **interval_size** (`int`): The width of the coefficient interval over which the MRQ was computed. - **origin_mrq** (`WaveletDec` | `None`): If the MRQ is derived from another MRQ, this refers to the original MRQ. - **bootstrapped_obj** (`WaveletDec` | `None`): Stores the bootstrapped version of the MRQ if bootstrapping has been used. ``` -------------------------------- ### fbm() Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.simul.fbm.html Function to simulate fractional Brownian motion (fBm). ```APIDOC ## fbm() ### Description Simulate fractional Brownian motion (fBm). ### Endpoint pymultifracs.simul.fbm(*args, **kwargs) ``` -------------------------------- ### StructureFunction Analysis and Plotting Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.scalingfunction.StructureFunction.html Methods for finding optimal scaling ranges and visualizing results. ```APIDOC ## POST StructureFunction.find_best_range ### Description Find the best range among those computed, given bootstrap was already performed. ### Parameters #### Request Body - **per_moment** (bool) - Optional - If True, returns the best range for each moment. Otherwise, returns the overall best range. ## GET StructureFunction.plot ### Description Plots the structure functions. ### Parameters #### Query Parameters - **nrow** (int) - Optional - Number of rows in the plot. - **filename** (str) - Optional - If provided, the file is saved to this path. - **ignore_q0** (bool) - Optional - Whether to include the structure function for q=0. - **figsize** (tuple) - Optional - Size of the figure in inches. - **scaling_range** (int) - Optional - Index of the scaling range to use. - **plot_scales** (tuple) - Optional - Constrains the x-axis to the interval [j1,j2]. - **plot_CI** (bool) - Optional - If using bootstrap, plot confidence intervals. - **signal_idx** (int) - Optional - Index of the signal to plot for multivariate signals. ``` -------------------------------- ### Method: get_wse Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.multiresquantity.WaveletWSE.html Compute weak scaling exponents from the wavelet coefficients. ```APIDOC ## get_wse ### Description Compute weak scaling exponents from the wavelet coefficients. ### Parameters #### Request Body - **theta** (float) - Optional - Parameter controlling cone reach in lower scales. - **omega** (float) - Optional - Parameter controlling the angle of the cone. - **gamint** (float) - Optional - Fractional integration coefficient. ### Response #### Success Response (200) - **WaveletWSE** - Weak scaling exponent derived from the coefficients. ``` -------------------------------- ### build_q_log Function Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.utils.build_q_log.html This function constructs a vector of q values for multifractal analysis, including log-spaced values between specified bounds and key integer points. ```APIDOC ## build_q_log() ### Description Build a convenient vector of q values for multifractal analysis. ### Method N/A (This is a Python function, not an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **q** (ndarray of float) - log-spaced values between q_min and q_max, along with their opposites, and accompanied by -2, -1, 0, 1, 2. #### Response Example ```python import numpy as np q_min = 0.1 q_max = 10.0 n = 5 q = build_q_log(q_min, q_max, n) print(q) # Expected output might look like: [-10. -5. -2. -1. 0. 1. 2. 5. 10.] (actual values depend on logspace calculation and inclusion of opposites/integers) ``` ### Parameters - **_q_min_** (float) - Lower bound of q, needs to be strictly positive. - **_q_max_** (float) - Upper value of q, needs to be strictly positive. - **_n_** (int) - Number of logspaced values to include. ``` -------------------------------- ### Plot Bootstrapped Results Source: https://www.neurospin.fr/pymultifracs/auto_examples/02-bootstrap.html Visualizes cumulants and multifractal spectrum with empirical confidence intervals. ```python pwt.cumulants.plot() ``` ```python pwt.spectrum.plot() ``` -------------------------------- ### Automatically Integrate Time Series Source: https://www.neurospin.fr/pymultifracs/auto_examples/01-simul.html Attempts to find a fractional integration coefficient to satisfy regularity conditions. Returns the integrated multi-resolution quantity. This is useful when the minimal regularity is too low. ```python WTpL = WTpL.auto_integrate(scaling_ranges) ``` -------------------------------- ### Load Bivariate Data using pooch and scipy Source: https://www.neurospin.fr/pymultifracs/auto_examples/10-bivariate.html Loads a .mat file containing bivariate time series data using pooch for retrieval and scipy for loading. Ensure the 'bivar' directory exists in your cache or adjust the path. ```python import pooch from scipy.io import loadmat url = ('https://github.com/neurospin/pymultifracs/raw/refs/heads/master/tests/' 'data/DataSet_ssMF.mat') fname = pooch.retrieve(url=url, known_hash=None, path=pooch.os_cache("bivar")) X = loadmat(fname)['data'].T ``` -------------------------------- ### Perform Wavelet Analysis for p-Leaders Source: https://www.neurospin.fr/pymultifracs/auto_examples/10-bivariate.html Conducts wavelet analysis on the input data to obtain p-leaders, which are then used for bivariate multifractal analysis. The integrate method is used with a specific exponent. ```python from pymultifracs import wavelet_analysis WTpL = wavelet_analysis(X).integrate(.75).get_leaders(2) ``` -------------------------------- ### WaveletLeader Methods Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.multiresquantity.WaveletLeader.html This section details various methods available for the WaveletLeader object, including data access, computation, and visualization. ```APIDOC ## GET /api/values ### Description Get the values of the MRQ, applying any finite size effects corrections if necessary (Wavelet p-leaders). ### Method GET ### Endpoint /api/values ### Parameters #### Query Parameters - **_j_** (any) - Required - The scale parameter. - **_idx_reject_** (dict[str, np.ndarray] | None) - Optional - Dictionary of rejected values. ### Response #### Success Response (200) - **values** (any) - The computed values. ## GET /api/wse ### Description Compute weak scaling exponents from the wavelet coefficients. ### Method GET ### Endpoint /api/wse ### Parameters #### Query Parameters - **_theta_** (float) - Optional - Parameter controlling to which extent the cone reaches in the lower scales. Practically, (θ,ω)-leaders computed at scale j reach down to j−jθ. - **_omega_** (float) - Optional - Parameter controlling the angle of the cone over which the weak scaling exponents are computed: practically, for computing the (θ,ω)-leaders at scale j, the width of the cone at scale j′ is (j−j′)omega+1. - **_gamint_** (float) - Optional - Fractional integration coefficient, defaults to 0 (no integration). ### Response #### Success Response (200) - **WaveletWSE** (WaveletWSE) - Weak scaling exponent derived from the coefficients. ## POST /api/integrate ### Description Re-compute the (p-)leaders on the fractionally integrated wavelet coefficients. ### Method POST ### Endpoint /api/integrate ### Parameters #### Request Body - **gamint** (float) - Required - Fractional integration coefficient ### Response #### Success Response (200) - **WaveletLeader** (WaveletLeader) - The re-computed wavelet leaders. ## GET /api/j2_eff ### Description Returns the effective maximal scale. ### Method GET ### Endpoint /api/j2_eff ## GET /api/max_scale_bootstrap ### Description Maximum scale at which bootstrapping can be done. ### Method GET ### Endpoint /api/max_scale_bootstrap ### Parameters #### Query Parameters - **idx_reject** (dict[str, np.ndarray] | None) - Optional - Dictionary of rejected values, by default None which means no rejected values. ### Response #### Success Response (200) - **Scale** (int) - The maximum scale for bootstrapping. ## POST /api/plot ### Description Plot the multi-resolution quantity. ### Method POST ### Endpoint /api/plot ### Parameters #### Request Body - **j1** (int) - Required - Initial scale from which to display the values. - **j2** (int) - Required - Maximal scale from which to display the values. - **ax** (matplotlib.pyplot.axes | None) - Optional - pyplot axes, defaults to None which creates a new figure. - **vmin** (float | None) - Optional - Minimal value of the colorbar, by default None which uses the minimal value in the data. - **vmax** (float | None) - Optional - Maximal value of the colorbar, by default None which uses the maximal value in the data. - **cbar** (bool) - Optional - Whether to display a colorbar. - **figsize** (tuple) - Optional - Size of the figure, used if ax is None. - **gamma** (float) - Optional - Exponent of the power-law color normalization, set to 1 for no normalization. - **nan_idx** (dict[str, ndarray] | None) - Optional - Index of values to highlight (smart indexing), or boolean mask index of values to highlight as output by robust.get_outliers. - **signal_idx** (int) - Optional - Index of the signal to plot, defaults to the first signal. - **cbar_kw** (dict | None) - Optional - Arguments to pass to the colorbar function call. - **cmap** (str) - Optional - Colormap for the plot. ## GET /api/scale2freq ### Description Get the frequencies associated to scales. ### Method GET ### Endpoint /api/scale2freq ### Parameters #### Query Parameters - **scale** (int | float | ndarray) - Required - Scales to convert to frequency. - **sfreq** (float) - Required - Sampling frequency of the signal. ### Response #### Success Response (200) - **freq** (float | ndarray) - Frequencies associated to scales. ``` -------------------------------- ### Compute Wavelet Leaders Source: https://www.neurospin.fr/pymultifracs/_downloads/4f7c425147b815e98b3001323044b973/10-bivariate.ipynb Performs wavelet analysis on the input data X to obtain p-leaders. This step is a prerequisite for bivariate multifractal analysis, integrating the wavelet transform and selecting leaders for a specific order q. ```python from pymultifracs import wavelet_analysis WTpL = wavelet_analysis(X).integrate(.75).get_leaders(2) ``` -------------------------------- ### Apply MFA with Bootstrapping Source: https://www.neurospin.fr/pymultifracs/_downloads/12297bf87b30ae3499b9d7500abaf258/02-bootstrap.ipynb Applies multifractal analysis (mfa) to the wavelet leaders, performing R bootstrapping repetitions to estimate confidence intervals for the specified scaling ranges. ```python from pymultifracs import mfa from pymultifracs.utils import build_q_log scaling_ranges = [(2, 8), (3, 8)] pwt = mfa(WTpL, scaling_ranges, weighted=None, q=build_q_log(.1, 4, 15), R=20) ``` -------------------------------- ### Perform Multifractal Analysis (MFA) Source: https://www.neurospin.fr/pymultifracs/auto_examples/01-simul.html Conducts the multifractal analysis using the `mfa()` function. It takes a multi-resolution quantity, scaling ranges, and optionally weighting and a list of moments `q`. Regularity check is performed by default. ```python from pymultifracs import mfa from pymultifracs.utils import build_q_log pwt = mfa(WTpL, scaling_ranges, weighted='Nj', q=[-2, -1, 0, 1, 2]) ``` -------------------------------- ### Benchmark.compute_benchmark Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.Benchmark.html Executes the benchmark computation based on the provided signal generation and estimation grids. ```APIDOC ## compute_benchmark ### Description Compute the benchmark by iterating over the defined signal generation and estimation grids. ### Parameters - **n_jobs** (int) - Optional - Number of jobs that joblib will start in parallel. Each job handles a different signal configuration. - **save_load_signals** (bool) - Optional - Whether to save the signals, and load them if found, to speed up computation. Currently not implemented yet. - **save** (bool) - Optional - Whether to save the final results dataframe to a pickled file. ``` -------------------------------- ### Plot Multifractal Spectrum Source: https://www.neurospin.fr/pymultifracs/auto_examples/01-simul.html Visualize the multifractal spectrum using the `spectrum.plot()` method. This requires densely sampled values of q, which can be generated using `build_q_log`. ```python pwt = mfa(WTpL, scaling_ranges, weighted='Nj', q=build_q_log(.1, 5, 20)) pwt.spectrum.plot() ``` -------------------------------- ### Plot Cumulants with Confidence Intervals Source: https://www.neurospin.fr/pymultifracs/_downloads/12297bf87b30ae3499b9d7500abaf258/02-bootstrap.ipynb Plots the cumulants of the multifractal analysis, displaying empirical confidence intervals if bootstrapping was applied. ```python pwt.cumulants.plot() ``` -------------------------------- ### Method: auto_integrate Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.multiresquantity.WaveletWSE.html Automatically integrates the signal to match the requirements of the multifractal formalism associated to the multi-resolution quantity. ```APIDOC ## auto_integrate ### Description Automatically integrates the signal to match the requirements of the multifractal formalism associated to the multi-resolution quantity. ### Parameters #### Request Body - **scaling_ranges** (list[tuple[int, int]]) - Required - List of pairs of (j1,j2) ranges of scales for the analysis. - **weighted** (str | None) - Optional - Weighting mode for the linear regressions. Defaults to None. - **idx_reject** (dict[int, ndarray of bool]) - Optional - Dictionary associating each scale to a boolean array indicating whether certain coefficients should be removed. ``` -------------------------------- ### Simulation Functions Source: https://www.neurospin.fr/pymultifracs/reference.html Functions for simulating signals like fractional Brownian motion. ```APIDOC ## simul.mrw(shape, H, lam, L, sigma, method, z0) ### Description Create a realization of fractional Brownian motion using circulant matrix embedding. ## simul.fbm(*args, **kwargs) ### Description Simulate fractional Brownian motion (fBm). ``` -------------------------------- ### Simulate Multifractal Random Walks (MRW) Source: https://www.neurospin.fr/pymultifracs/auto_examples/01-simul.html Generates simulated Multifractal Random Walks (MRWs) using specified parameters. Requires matplotlib and numpy. The output is a numpy array representing the time series. ```python import matplotlib.pyplot as plt import numpy as np from pymultifracs.simul import mrw X = mrw(shape=(2**15, 5), H=0.8, lam=np.sqrt(.05), L=2**15) plt.plot(X) plt.show() ``` -------------------------------- ### StructureFunction Methods Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.scalingfunction.StructureFunction.html This section lists and describes the core methods of the StructureFunction class for multifractal analysis. ```APIDOC ## StructureFunction.find_best_range() ### Description Finds the optimal range for multifractal analysis. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters None ### Request Example ```python # Example usage within a class instance structure_function_instance.find_best_range() ``` ### Response Returns the determined best range for analysis. #### Success Response (200) - **range** (tuple) - The optimal range (min, max). #### Response Example ```json { "range": [0.1, 10.0] } ``` ``` ```APIDOC ## StructureFunction.get_jrange() ### Description Retrieves the range of 'j' values used in the analysis. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters None ### Request Example ```python # Example usage within a class instance j_range = structure_function_instance.get_jrange() ``` ### Response Returns the 'j' range. #### Success Response (200) - **j_range** (list) - A list of 'j' values. #### Response Example ```json { "j_range": [1, 2, 3, 4, 5] } ``` ``` ```APIDOC ## StructureFunction.get_n_bootstrap() ### Description Gets the number of bootstrap samples used for statistical analysis. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters None ### Request Example ```python # Example usage within a class instance n_bootstrap = structure_function_instance.get_n_bootstrap() ``` ### Response Returns the number of bootstrap samples. #### Success Response (200) - **n_bootstrap** (int) - The number of bootstrap samples. #### Response Example ```json { "n_bootstrap": 100 } ``` ``` ```APIDOC ## StructureFunction.get_nj_interv() ### Description Retrieves the interval information for 'nj' values. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters None ### Request Example ```python # Example usage within a class instance nj_intervals = structure_function_instance.get_nj_interv() ``` ### Response Returns the 'nj' intervals. #### Success Response (200) - **nj_intervals** (list) - A list of 'nj' interval data. #### Response Example ```json { "nj_intervals": [[0.5, 1.5], [1.5, 2.5]] } ``` ``` ```APIDOC ## StructureFunction.plot() ### Description Generates a plot of the structure function. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters None ### Request Example ```python # Example usage within a class instance structure_function_instance.plot() ``` ### Response Displays a plot. #### Success Response (200) - **plot** (visualization) - The generated plot. #### Response Example (No JSON response, displays a plot) ``` ```APIDOC ## StructureFunction.plot_scaling() ### Description Generates a plot of the scaling function. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters None ### Request Example ```python # Example usage within a class instance structure_function_instance.plot_scaling() ``` ### Response Displays a scaling plot. #### Success Response (200) - **plot** (visualization) - The generated scaling plot. #### Response Example (No JSON response, displays a plot) ``` ```APIDOC ## StructureFunction.s_q() ### Description Calculates the structure function values for a given order 'q'. ### Method Not applicable (method of a class) ### Endpoint Not applicable (method of a class) ### Parameters #### Query Parameters - **q** (float or list) - The order(s) of the structure function to calculate. ### Request Example ```python # Example usage within a class instance sq_values = structure_function_instance.s_q(q=[1, 2, 3]) ``` ### Response Returns the calculated structure function values. #### Success Response (200) - **s_q** (dict) - A dictionary where keys are 'q' values and values are the corresponding structure function values. #### Response Example ```json { "s_q": { "1": 0.5, "2": 0.25, "3": 0.125 } } ``` ``` -------------------------------- ### mrw() - Simulate Multifractal Random Walk Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.simul.mrw.html Generates a realization of a Multifractal Random Walk (MRW) using fractional Brownian motion and circulant matrix embedding. This function allows for customization of shape, Hurst exponent, intermittency, scale, variance, and the simulation method. ```APIDOC ## mrw() ### Description Create a realization of fractional Brownian motion using circulant matrix embedding. ### Method Python Function ### Endpoint `pymultifracs.simul.mrw` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **shape** (`int` | `tuple`(`int`, `int`)) - Required - If integer, it is the number of samples N. If tuple it is (N, R), the number of samples and realizations, respectively. - **H** (`float`) - Required - Hurst exponent - **lam** (`float`) - Required - Lambda, intermittency parameter - **L** (`float`) - Optional - Integral scale - **sigma** (`float`) - Optional - Variance of process (default: 1) - **method** (`str`) - Optional - Method to use: ‘cme’ selects circulant matrix embedding (default, O(NlogN) in memory), ‘chol’ selects Cholesky decomposition (O(N2) in memory). (default: 'cme') - **z0** (`tuple`(`ndarray` of `float`, `ndarray` of `float`)) - Optional - Tuple of white noise values, to fix the random component across simulations. The shape should be (2N−2,R) for ‘cme’ and (N,R). ### Request Example ```python import numpy as np from pymultifracs.simul import mrw # Example with integer shape N = 1000 H = 0.7 lam = 1.5 realization_int = mrw(shape=N, H=H, lam=lam) # Example with tuple shape (N, R) R = 5 realization_tuple = mrw(shape=(N, R), H=H, lam=lam) # Example with optional parameters L_scale = 10.0 sigma_val = 0.5 method_chol = 'chol' realization_custom = mrw(shape=N, H=H, lam=lam, L=L_scale, sigma=sigma_val, method=method_chol) # Example with z0 z_noise1 = np.random.randn(2*N - 2, R) # for 'cme' z_noise2 = np.random.randn(N, R) # for 'chol' realization_with_z0 = mrw(shape=(N, R), H=H, lam=lam, z0=(z_noise1, z_noise2)) ``` ### Response #### Success Response (200) - **mrw** (`ndarray`) - Synthesized mrw realizations. If shape is scalar, fbm is of shape (N,). Otherwise, it is of shape (N, R). #### Response Example ```json { "mrw": "[numpy array of shape (N,) or (N, R)]" } ``` ### References [1] Bacry, Delour, Muzy, “Multifractal Random Walk”, Physical Review E, 2001 ``` -------------------------------- ### Method: get_leaders Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.multiresquantity.WaveletWSE.html Compute (p-)leaders from the wavelet coefficients. ```APIDOC ## get_leaders ### Description Compute (p-)leaders from the wavelet coefficients. ### Parameters #### Request Body - **p_exp** (float | numpy.inf) - Required - Value of the p exponent. - **interval_size** (int) - Optional - Width of the time shift interval. - **gamint** (int | None) - Optional - Fractional integration coefficient. ### Response #### Success Response (200) - **WaveletLeader** - Wavelet (p-)leader derived from the coefficients. ``` -------------------------------- ### Check Regularity of Multi-resolution Quantities Source: https://www.neurospin.fr/pymultifracs/auto_examples/01-simul.html Verifies the minimum regularity condition for multifractal analysis using the specified scaling ranges. This method is available for `WaveletDec`, `WaveletLeader`, and `WaveletWSE` objects. ```python WT.check_regularity(scaling_ranges) WTL.check_regularity(scaling_ranges) WTpL.check_regularity(scaling_ranges) WSE.check_regularity(scaling_ranges) ``` -------------------------------- ### Compute Bivariate Multifractal Analysis (BiMFA) Source: https://www.neurospin.fr/pymultifracs/auto_examples/10-bivariate.html Applies the bivariate multifractal analysis function (bimfa) to the p-leaders. It requires the p-leader data for both channels and specifies the scaling ranges and q-values for analysis. ```python import numpy as np from pymultifracs.bivariate import bimfa q1 = np.array([0, 1, 2]) q2 = np.array([0, 1, 2]) pwt = bimfa(WTpL, WTpL, scaling_ranges=[(3, 9)], q1=q1, q2=q2) ``` -------------------------------- ### Determine Optimal Scaling Range (Overall) Source: https://www.neurospin.fr/pymultifracs/_downloads/12297bf87b30ae3499b9d7500abaf258/02-bootstrap.ipynb Determines the best overall scaling range from a list of choices using a bootstrapped-based criterion. ```python pwt = mfa(WTpL, [(2, 8), (3, 8), (2, 7), (3, 7)], weighted=None, R=20) pwt.cumulants.find_best_range() ``` -------------------------------- ### Define Multifractal Estimation Functions Source: https://www.neurospin.fr/pymultifracs/_downloads/6968a062e5f822a7836cfdeb15f66b35/05-benchmark.ipynb Define functions for estimating multifractal properties using different methods like 'pleader' (based on wavelet leaders) and 'coef' (based on wavelet coefficients). These functions process the generated signals. ```python def pleader_est(X, p_exp): WT = wavelet_analysis(X).get_leaders(p_exp=p_exp) pwt = mfa(WT, [(3, 7)], estimates='c', weighted='Nj') out = pwt.cumulants.log_cumulants.isel( scaling_range=0).to_series().unstack('m') out.columns = out.columns.to_flat_index().map(lambda x: f'c{x}') return out def coef_est(X): WT = wavelet_analysis(X) dwt = mfa(WT, [(3, 7)], estimates='c') out = dwt.cumulants.log_cumulants.isel( scaling_range=0).to_series().unstack('m') out.columns = out.columns.to_flat_index().map(lambda x: f'c{x}') return out ``` -------------------------------- ### Define multifractal estimation functions Source: https://www.neurospin.fr/pymultifracs/auto_examples/05-benchmark.html Define functions for estimating multifractal parameters using the p-leader and coefficient-based methods. These functions process wavelet transform results to extract log-cumulants. ```python def pleader_est(X, p_exp): WT = wavelet_analysis(X).get_leaders(p_exp=p_exp) pwt = mfa(WT, [(3, 7)], estimates='c', weighted='Nj') out = pwt.cumulants.log_cumulants.isel( scaling_range=0).to_series().unstack('m') out.columns = out.columns.to_flat_index().map(lambda x: f'c{x}') return out def coef_est(X): WT = wavelet_analysis(X) dwt = mfa(WT, [(3, 7)], estimates='c') out = dwt.cumulants.log_cumulants.isel(scaling_range=0).to_series().unstack('m') out.columns = out.columns.to_flat_index().map(lambda x: f'c{x}') return out ``` -------------------------------- ### WaveletDec Methods Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.multiresquantity.WaveletDec.html Details the methods available for the WaveletDec class, including integration, bootstrapping, regularity checks, and data retrieval. ```APIDOC ## Methods ### `auto_integrate(_scaling_ranges_ , _weighted =None_, _idx_reject =None_)` Automatically integrates the signal to match the requirements of the multifractal formalism associated with the multi-resolution quantity. **Parameters:** - **scaling_ranges** (`list`[`tuple`[`int`, `int`]]): List of pairs of (j1, j2) ranges of scales for the analysis. - **weighted** (`str` | `None`): Weighting mode for the linear regressions. Defaults to None (no weighting). Possible values are ‘Nj’ (weighs by number of coefficients) and ‘bootstrap’ (weighs by bootstrap-derived estimates of variance). - **idx_reject** (`dict`[`int`, `ndarray` of bool]): Dictionary associating each scale to a boolean array indicating whether certain coefficients should be removed. ### `bootstrap(_R_ , _min_scale =1_, _idx_reject =None_)` Bootstrap the multi-resolution quantity by repeating. **Parameters:** - **R** (`int`): Number of repetitions of the bootstrap. - **min_scale** (`int`): Minimum scale to be kept in the bootstrapped MRQ. - **idx_reject** (`dict`[`str`, `np.ndarray`] | `None`): Dictionary of rejected values. **Returns:** - `WaveletDec`: MRQ containing the bootstrapped values. ### `bootstrap_multiple(_R_ , _min_scale_ , _mrq_list_)` Class method to bootstrap multiple MRQs at once. **Parameters:** - **R** (`int`): Number of repetitions of the bootstrap. - **min_scale** (`int`): Minimum scale to be kept in the bootstrapped MRQ. - **mrq_list** (`list`[`WaveletDec`]): List of MRQs to bootstrap. **Returns:** - `list`[`WaveletDec`]: List of bootstrapped MRQs. ### `check_regularity(_scaling_ranges_ , _weighted =None_, _idx_reject =None_, _min_j =1_)` Verify that the MRQ has enough regularity for analysis. **Parameters:** - **scaling_ranges** (`list`[`tuple`[`int`, `int`]]): List of pairs of (j1, j2) ranges of scales for the analysis. - **weighted** (`str` | `None`): Weighting mode for the linear regressions. Defaults to None. - **idx_reject** (`Dict`[`int`, `ndarray`]): Dictionary associating each scale to a boolean array indicating whether certain coefficients should be removed. **Returns:** - `ndarray`: Estimate of the minimal Hölder exponent in the MRQ. ### `freq2scale(_freq_ , _sfreq_)` Get the scales associated to frequencies. **Parameters:** - **freq** (`float` | `ndarray`): Frequencies to convert to scales. - **sfreq** (`float`): Sampling frequency of the signal. **Returns:** - **scales** (`float` | `ndarray`): Scales associated to freq. ### `get_formalism()` Obtains the formalism of the multi-resolution quantity. **Returns:** - **formalism** (`str`): The formalism of the MRQ. ### `get_leaders(_p_exp_ , _interval_size =3_, _gamint =None_)` Compute (p-)leaders from the wavelet coefficients. **Parameters:** - **p_exp** (`float` | `numpy.inf`): `np.inf` for wavelet leaders, a float for wavelet p-leader formalism. - **interval_size** (`int`): Width of the time shift interval for leader computation. - **gamint** (`int` | `None`): Fractional integration coefficient. **Returns:** - `WaveletLeader`: Wavelet (p-)leader derived from the coefficients. ### `get_n_bootstrap()` Returns the number of bootstrapping repetitions, or 0 if no bootstrapping was performed. **Returns:** - `int`: The number of bootstrap repetitions. ### `get_nj_interv(_j1 =None_, _j2 =None_, _idx_reject =None_)` Returns `nj` as an array for scales `j` in the range [j1, j2], optionally considering rejected indices. **Parameters:** - **j1** (`int`, optional): The starting scale. - **j2** (`int`, optional): The ending scale. - **idx_reject** (`dict`, optional): Dictionary of rejected indices. **Returns:** - `ndarray`: Array of `nj` values. ### `get_values(_j_ , _idx_reject =None_)` Get the values of the MRQ, applying any finite size effects corrections if necessary. **Parameters:** - **j** (`int`): The scale for which to retrieve values. - **idx_reject** (`dict`, optional): Dictionary of rejected indices. **Returns:** - `ndarray`: The MRQ values at scale `j`. ### `get_wse(_theta =0.5_, _omega =1_, _gamint =None_)` Compute weak scaling exponents from the wavelet coefficients. **Parameters:** - **theta** (`float`, optional): Parameter for weak scaling exponent calculation. Defaults to 0.5. - **omega** (`int`, optional): Parameter for weak scaling exponent calculation. Defaults to 1. - **gamint** (`int` | `None`): Fractional integration coefficient. ``` -------------------------------- ### Visualization Functions Source: https://www.neurospin.fr/pymultifracs/reference.html Functions for visualizing multifractal analysis results. ```APIDOC ## viz.plot_psd(signal, fs, wt_name, log_base, ax) ### Description Plot the superposition of Fourier-based Welch estimation and Wavelet-based estimation of PSD on a log-log graphic. ## viz.plot_cm(cm, ind_m, j1, j2, range_idx, ax) ### Description Helper function to plot individual Cm(j) functions along with their associated cm fit. ``` -------------------------------- ### MFSpectrum Class Overview Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.scalingfunction.MFSpectrum.html The MFSpectrum class estimates the Multifractal Spectrum based on Herwig Wendt's thesis. It should not be instantiated directly but obtained from pymultifracs.mfa(). ```APIDOC ## Class: MFSpectrum ### Description Estimates the Multifractal Spectrum based on equations 2.74 - 2.78 of Herwig Wendt’s thesis [1]. This class should not be instantiated directly but obtained from calling `pymultifracs.mfa()`. ### Attributes - **formalism** (`str`): Formalism used. Can be any of ‘wavelet coefs’, ‘wavelet leaders’, or ‘wavelet p-leaders’. - **j** (`ndarray`, shape (n_scales,)) : List of the j values (scales), in order presented in the value arrays. - **nj** (`dict`[`int`, `ndarray`]): Dictionary giving the number of non-NaN values at every scale. Arrays are of shape (n_rep,) - **gamint** (`float`): Value of gamint used in the computation of the underlying MRQ. - **Dq** (`ndarray`, shape (`n_exponents`, `n_rep`)): Fractal dimensions : D(q), y-axis of the multifractal spectrum. - **hq** (`ndarray`, shape (`n_exponents`, `n_rep`)): Hölder exponents : h(q), x-axis of the multifractal spectrum. - **weighted** (`str` | `None`): Weighting mode for the linear regressions. Defaults to None. Possible values are ‘Nj’ or ‘bootstrap’. - **weights** (`ndarray`): Weights of the linear regression. - **bootstrapped_obj** (`MFSpectrum` | `None`): Storing the bootstrapped version of the structure function if bootstraping has been used. ### References [1] H. Wendt (2008). Contributions of Wavelet Leaders and Bootstrap to Multifractal Analysis... Ph.D thesis, Laboratoire de Physique, Ecole Normale Superieure de Lyon. https://www.irit.fr/~Herwig.Wendt/data/ThesisWendt.pdf ``` -------------------------------- ### Perform Wavelet Analysis Source: https://www.neurospin.fr/pymultifracs/_downloads/12297bf87b30ae3499b9d7500abaf258/02-bootstrap.ipynb Performs a wavelet transform on the input data X and extracts the leaders with a specified p-exponent. ```python from pymultifracs import wavelet_analysis WT = wavelet_analysis(X, wt_name='db3', j2=None, normalization=1) WTpL = WT.get_leaders(p_exp=2) ``` -------------------------------- ### Generate Multifractal Random Walks Source: https://www.neurospin.fr/pymultifracs/_downloads/12297bf87b30ae3499b9d7500abaf258/02-bootstrap.ipynb Generates a Multifractal Random Walk (MRW) with specified parameters H and lambda, then plots the generated series. ```python import matplotlib.pyplot as plt import numpy as np from pymultifracs.simul import mrw X = mrw(shape=2**15, H=0.8, lam=np.sqrt(.05), L=2**15) plt.plot(X) plt.show() ``` -------------------------------- ### Generate Fractional Brownian Motion with mrw Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.simul.mrw.html Use this function to create a realization of fractional Brownian motion. Specify the shape, Hurst exponent (H), and intermittency parameter (lam). The method can be 'cme' (default) or 'chol'. ```python pymultifracs.simul.mrw(_shape_ , _H_ , _lam_ , _L =None_, _sigma =1_, _method ='cme'_, _z0 =(None, None)_) ``` -------------------------------- ### BiStructureFunction Methods Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.bivariate.BiStructureFunction.html Methods available for the BiStructureFunction class. ```APIDOC ## Methods ### S_qq(q1, q2) #### Description Get bivariate Sq1q2 function. #### Parameters - **q1** (float) - Required - The first q value. - **q2** (float) - Required - The second q value. ### get_jrange(j1=None, j2=None, bootstrap=False) #### Description Get the range of j values. #### Parameters - **j1** (int) - Optional - First j value. - **j2** (int) - Optional - Second j value. - **bootstrap** (bool) - Optional - Whether to consider bootstrapping. ### get_n_bootstrap() #### Description Returns the number of bootstrapping repetitions, or 0 if no bootstrapping. ### get_nj_interv(j_min, j_max) #### Description Get number of coefficients per scale. #### Parameters - **j_min** (int) - Required - Minimum j value. - **j_max** (int) - Required - Maximum j value. ### get_nj_interv_margin(j_min, j_max, margin) #### Description Get number of coefficients per scale for the margins. #### Parameters - **j_min** (int) - Required - Minimum j value. - **j_max** (int) - Required - Maximum j value. - **margin** (int) - Required - Margin value. ### plot(figsize=None, scaling_range=0, signal_idx1=0, signal_idx2=0, plot_CI=True, plot_scales=None, filename=None) #### Description Plot bivariate structure function. #### Parameters - **figsize** (tuple) - Optional - Figure size. - **scaling_range** (int) - Optional - Scaling range (default: 0). - **signal_idx1** (int) - Optional - Index for the first signal (default: 0). - **signal_idx2** (int) - Optional - Index for the second signal (default: 0). - **plot_CI** (bool) - Optional - Whether to plot confidence intervals (default: True). - **plot_scales** (list) - Optional - Scales to plot. - **filename** (str) - Optional - Filename to save the plot. ### s_qq(q1, q2) #### Description Get bivariate sq1q2 exponents. #### Parameters - **q1** (float) - Required - The first q value. - **q2** (float) - Required - The second q value. ``` -------------------------------- ### Generate White Noise for z0 Source: https://www.neurospin.fr/pymultifracs/_autosummary/pymultifracs.simul.mrw.html Arrays in `z0` can be generated using this command. Ensure the shape matches the requirements of the 'cme' or 'chol' methods. ```python z = np.random.randn(N, R). ```