### Example Usage of Forecasting Functions Source: https://teaspoontda.github.io/teaspoon/modules/DAF/Forecasting.html Demonstrates setting up plotting configurations and importing necessary libraries for time series forecasting examples. ```python import numpy as np from matplotlib import rc import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows import lorenz from teaspoon.DAF.forecasting import random_feature_map_model from teaspoon.DAF.forecasting import get_forecast # Set font rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.rcParams.update({'font.size': 16}) ``` -------------------------------- ### PHN Example Output Source: https://teaspoontda.github.io/teaspoon/_sources/modules/TDA/PHN.rst.txt Expected console output for the provided PHN implementation example. ```text 1-D Persistent Homology (loops): [[ 1. 15.]] Persistent homology of network statistics: [0.0, 0, 0.02127659574468085] ``` -------------------------------- ### Example PAMI Output Source: https://teaspoontda.github.io/teaspoon/modules/ParamSelection/PAMI.html This is the expected output when running the PAMI_for_delay function with the provided example code. ```text Permutation Embedding Delay: 8 ``` -------------------------------- ### Example Output for MsPE Source: https://teaspoontda.github.io/teaspoon/modules/ParamSelection/MsPE.html This is the expected output when running the MsPE example code for selecting time delay and dimension. ```text Embedding Delay: 21 Embedding Dimension: 3 ``` -------------------------------- ### Optimization Output Example Source: https://teaspoontda.github.io/teaspoon/modules/SP/parameter_path_opt.html Example output from the first step of the parameter optimization process, showing gradients, loss, and current parameter values. ```text d(Loss)/d(sigma): 0.97641 d(Loss)/d(rho): 0.21593 Loss: -1.0 Rho: 189.0 -- Sigma: 19.0 ``` -------------------------------- ### Install Teaspoon Package Source: https://teaspoontda.github.io/teaspoon/_sources/installation/index.rst.txt Use this command to install the Teaspoon package from PyPI. Ensure you have pip installed. ```bash pip install teaspoon ``` -------------------------------- ### Install Documentation Dependencies Source: https://teaspoontda.github.io/teaspoon/_sources/contributing.rst.txt Required Python packages for building the project documentation. ```bash pip install Sphinx==6.2.1 ``` ```bash pip install sphinxcontrib-bibtex ``` ```bash pip install sphinx-rtd-theme ``` ```bash pip install nbsphinx ``` -------------------------------- ### Sinc, Gaussians, and Gaussian Field Generation Examples Source: https://teaspoontda.github.io/teaspoon/_sources/modules/MakeData/PointCloud.rst.txt Examples demonstrating the generation of Sinc, Gaussians, and 2D Gaussian Field data. ```APIDOC ## Specialized Data Generation ### Description Generates data for Sinc function, multiple Gaussians, or a 2D Gaussian Field. ### Method Instantiation of `Sinc`, `Gaussians`, or `GaussianField` classes. ### Endpoint N/A (Python module) ### Parameters **Sinc:** - **x1, x2, y1, y2** (float) - Optional - Bounds for the field. - **N1, N2** (int) - Optional - Number of samples along x and y axes. - **mu, sigma** (float) - Optional - Mean and standard deviation for Sinc function. **Gaussians:** - **centers** (numpy.ndarray) - Required - Array of Gaussian centers. - **variances** (numpy.ndarray) - Required - Array of variances for each Gaussian. - **amplitudes** (numpy.ndarray) - Required - Array of amplitudes for each Gaussian. **GaussianField:** - **width, height** (int) - Required - Dimensions of the field. - **a, b** (float) - Optional - Parameters for the Gaussian field. ### Request Example ```python import numpy as np from teaspoon.MakeData.PointCloud import Sinc, Gaussians, GaussianField # Sinc function f_sinc = Sinc(x1=-5, x2=5, y1=-5, y2=5, N1=1000, N2=500, mu=0, sigma=0.01) # Gaussians centers = np.array([[0, 0], [1, 1], [-1, 0], [4,2]]) variances = np.array([0.1, 0.5, 0.3, 0.2]) amplitudes = np.array([1, 2, 1.5, 2]) f_gaussians = Gaussians(centers, variances, amplitudes) # Gaussian Field field1 = GaussianField(256, 256, a=0.8, b=100) ``` ### Response - **Data** (numpy.ndarray or matplotlib.figure.Figure) - Generated data or plot. ``` -------------------------------- ### Point Cloud Generation Examples Source: https://teaspoontda.github.io/teaspoon/_sources/modules/MakeData/PointCloud.rst.txt Examples demonstrating the generation of point clouds from different underlying shapes such as Torus, Annulus, Sphere, Cube, and Clusters. ```APIDOC ## Point Cloud Generation ### Description Generates point clouds sampled from various underlying shapes. ### Method Instantiation of shape classes (e.g., Torus, Annulus, Sphere, Cube, Clusters). ### Endpoint N/A (Python module) ### Parameters - **N** (int) - Required - Number of points to generate. - **seed** (int) - Optional - Seed for random number generation. - **noise** (float) - Optional - Noise level for Sphere generation. - **centers** (numpy.ndarray) - Required for Clusters - Array of cluster centers. - **sd** (float) - Optional for Clusters - Standard deviation for clusters. ### Request Example ```python import numpy as np from teaspoon.MakeData.PointCloud import Torus, Annulus, Cube, Clusters, Sphere numPts = 500 seed = 0 # Generate Torus t = Torus(N=numPts, seed=seed) # Generate Annulus a = Annulus(N=numPts, seed=seed) # Generate Sphere s = Sphere(N=numPts, noise=.05, seed=seed) # Generate Cube c = Cube(N=numPts, seed=seed) # Generate 3 clusters cl = Clusters(centers=np.array([[0,0], [0,2], [2,0]]), N=numPts, seed=seed, sd=.05) ``` ### Response - **Point Cloud Data** (numpy.ndarray) - Array of points representing the generated point cloud. ``` -------------------------------- ### Example Output for Delay Calculation Source: https://teaspoontda.github.io/teaspoon/modules/ParamSelection/FSA.html This is the expected output format when calculating the permutation embedding delay using the provided example code. ```text Permutation Embedding Delay: 19 ``` -------------------------------- ### Example Implementation of MI_for_delay Source: https://teaspoontda.github.io/teaspoon/modules/ParamSelection/MI.html Provides a Python code example demonstrating the usage of the MI_for_delay function to find the embedding delay. ```APIDOC ## Example Implementation of MI_for_delay ### Description This example demonstrates how to use the `MI_for_delay` function to calculate the embedding delay (tau) for permutation entropy analysis. ### Method ```python from teaspoon.parameter_selection.MI_delay import MI_for_delay import numpy as np fs = 10 t = np.linspace(0, 100, fs*100) ts = np.sin(t) + np.sin((1/np.pi)*t) tau = MI_for_delay(ts, plotting = True, method = 'basic', h_method = 'sturge', k = 2, ranking = True) print('Delay from MI: ',tau) ``` ### Response Example ``` Delay from MI: 23 ``` ``` -------------------------------- ### Example FNN Output Source: https://teaspoontda.github.io/teaspoon/modules/ParamSelection/FNN.html This is the expected output when running the FNN_n function with the provided example parameters. ```text FNN embedding Dimension: 2 ``` -------------------------------- ### Install Latest Teaspoon from Source Source: https://teaspoontda.github.io/teaspoon/_sources/installation/index.rst.txt Clone the Teaspoon repository and install the most up-to-date version using pip. This method is useful for development or when needing the absolute latest code. ```bash pip install . ``` -------------------------------- ### Output of auto-correlation example Source: https://teaspoontda.github.io/teaspoon/modules/ParamSelection/AC.html The expected console output resulting from the provided auto-correlation implementation example. ```text Delay from AC: 13 ``` -------------------------------- ### Example Usage of Graph Generation Functions Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/SP/network.html Demonstrates the basic usage of the `knn_graph` and `ordinal_partition_graph` functions with a generated sine wave time series. This example requires numpy and assumes the necessary graph generation functions and their dependencies are available. ```python # import needed packages import numpy as np t = np.linspace(0, 30, 200) ts = np.sin(t) + np.sin(2*t) # generate a simple time series A_knn = knn_graph(ts) # ordinal partition network from time series A_op = ordinal_partition_graph(ts) # knn network from time series ``` -------------------------------- ### Persistence Diagram Generation Example Source: https://teaspoontda.github.io/teaspoon/_sources/modules/MakeData/PointCloud.rst.txt Example demonstrating the generation of persistence diagrams from point clouds sampled from different underlying shapes. ```APIDOC ## Persistence Diagram Generation ### Description Generates persistence diagrams computed from point clouds sampled from different underlying shapes. ### Method `teaspoon.MakeData.PointCloud.testSetManifolds` function. ### Endpoint N/A (Python function) ### Parameters - **numDgms** (int) - Required - Number of diagrams to generate. - **numPts** (int) - Required - Number of points for each point cloud. - **seed** (int) - Optional - Seed for random number generation. ### Request Example ```python from teaspoon.MakeData import PointCloud df = PointCloud.testSetManifolds(numDgms=1, numPts=500, seed=0) ``` ### Response - **DataFrame** (pandas.DataFrame) - DataFrame containing persistence diagrams (Dgm0, Dgm1) and training labels. ``` -------------------------------- ### Example: MsPE for selecting n and tau Source: https://teaspoontda.github.io/teaspoon/modules/ParamSelection/MsPE.html This example demonstrates how to use MsPE_tau and MsPE_n together to find the optimal embedding delay and dimension for a given time series. Plotting options are enabled for visualization. ```python import numpy as np from teaspoon.parameter_selection.MsPE import MsPE_n, MsPE_tau t = np.linspace(0, 100, 1000) ts = np.sin(t) m_s, m_e, d_s, d_e = 3, 7, 1, 200 #m_s and m_e are the starting and ending dimensions n to search through #d_e = max delay tau to search through #plotting option will show you how delay tau or dimension n were selected tau = int(MsPE_tau(ts, d_e, plotting = True)) n = MsPE_n(ts, tau, m_s, m_e, plotting = True) print('Embedding Delay: '+str(tau)) print('Embedding Dimension: '+str(n)) print('Embedding Delay: '+str(tau)) print('Embedding Dimension: '+str(n)) ``` -------------------------------- ### Execute MI Delay Estimation Example Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/parameter_selection/MI_delay.html Demonstrates how to import and use the MI_for_delay function with a synthetic sine wave signal. ```python if __name__ == "__main__": from teaspoon.parameter_selection.MI_delay import MI_for_delay import numpy as np fs = 10 t = np.linspace(0, 100, fs*100) ts = np.sin(t) + np.sin((1/np.pi)*t) tau = MI_for_delay(ts, plotting=True, method='basic', h_method='sturge', k=2, ranking=True) print('Delay from MI: ', tau) ``` -------------------------------- ### Parameter Path Optimization Example Source: https://teaspoontda.github.io/teaspoon/_sources/modules/SP/parameter_path_opt.rst.txt Demonstrates setting up and running parameter path optimization for a Lorenz system. Requires PyTorch, torchdiffeq, and teaspoon. Ensure the device is set correctly for CUDA or CPU. ```python import torch from torchdiffeq import odeint from torch.optim.lr_scheduler import LambdaLR from teaspoon.SP.parameter_path_opt import PathOptimizer from IPython.display import clear_output device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Set bounds for the parameters x_min = 80 x_max = 300 y_min = 4 y_max = 50 # Define the system of ODEs using PyTorch class LorenzSystem(torch.nn.Module): def __init__(self, params): super().__init__() self.params = torch.nn.Parameter(params) def forward(self, t, state): x, y, z = state rho, sigma = self.params dxdt = sigma * (y - x) dydt = x * (rho - z) - y dzdt = x * y - (8.0/3.0) * z return torch.stack([dxdt, dydt, dzdt]) # Time settings t_main = torch.linspace(0, 10, 1000, device=device, dtype=torch.float64) # Main simulation # Initial conditions x0 = torch.tensor([1.0, 1.0, 1.0], requires_grad=True, device=device, dtype=torch.float64) # Combine parameters into a single vector params = torch.nn.Parameter(torch.tensor([190.0, 20.0], device=device)) # Instantiate the system with the combined parameter vector lorenz = LorenzSystem(params).to(device) # Initialize optimizer and learning rate scheduler optimizer = torch.optim.Adam([lorenz.params], lr=1.0) scheduler = LambdaLR(optimizer, lr_lambda=lambda epoch: 0.995**epoch) # Initialize lists for saving the path and losses path = [[lorenz.params[0].item(), lorenz.params[1].item()]] losses = [] # Define the forbidden regions for the parameter path forbidden_regions = [ lambda params, pd1: (params[0] - x_max), lambda params, pd1: -(params[0] - x_min), lambda params, pd1: (params[1] - y_max), lambda params, pd1: -(params[1] - y_min), lambda params, pd1: -((1/400)*(params[0]-190)**2+(1/25)*(params[1]-10)**2 - 1.0), # Example constraint: unit disk of radius 5 centered at (190, 27) ] # Initialize the PathOptimizer with the Lorenz system and forbidden regions p_opt = PathOptimizer({ 'maxPers': -1}, forbidden_regions=forbidden_regions) for epoch in range(5): # Perform the optimization step y, pd1, loss, grads = p_opt.optimize(lorenz, x0, t_main, optimizer, scheduler) # Extract the gradients with resspect to the parameters d_rho, d_sigma = grads[0], grads[1] # Print result of optimization step clear_output(wait=True) print(f"d(Loss)/d(sigma): {d_sigma.item():.5}") print(f"d(Loss)/d(rho): {d_rho.item():.5}") print(f"Loss: {loss.item():.8}") print(f"Rho: {lorenz.params[0].item():.8} -- Sigma: {lorenz.params[1].item():.8}") # Save the path and the loss path.append([lorenz.params[0].item(), lorenz.params[1].item()]) losses.append(loss.item()) ``` -------------------------------- ### Build documentation Source: https://teaspoontda.github.io/teaspoon/contributing.html Command to generate the HTML documentation from the teaspoon directory. ```bash make html ``` -------------------------------- ### Simulate Rossler system with custom parameters Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/index.html An example showing how to provide specific simulation parameters, sample rates, and initial conditions to the Rossler system. ```python import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows import rossler L, fs, SampleSize = 1000, 20, 2000 # the length (in seconds) of the time series, the sample rate, and the sample size of the time series of the simulated system. parameters = [0.1, 0.2, 13.0] # these are the a, b, and c parameters from the Rossler system model. InitialConditions = [1.0, 0.0, 0.0] # [x_0, y_0, x_0] t, ts = rossler(L=L, fs=fs, SampleSize=SampleSize, parameters=parameters, InitialConditions=InitialConditions) TextSize = 15 plt.figure(figsize = (12,4)) gs = gridspec.GridSpec(1,2) ax = plt.subplot(gs[0, 0]) plt.xticks(size = TextSize) plt.yticks(size = TextSize) plt.ylabel(r'$x(t)$', size = TextSize) plt.xlabel(r'$t$', size = TextSize) plt.plot(t,ts[0], 'k') ax = plt.subplot(gs[0, 1]) plt.plot(ts[0], ts[1],'k.') plt.plot(ts[0], ts[1],'k', alpha = 0.25) plt.xticks(size = TextSize) plt.yticks(size = TextSize) plt.xlabel(r'$x(t)$', size = TextSize) plt.ylabel(r'$y(t)$', size = TextSize) plt.show() ``` -------------------------------- ### Example Usage and Visualization Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/DAF/forecasting.html Demonstrates training a random feature map model on Lorenz system data and plotting the resulting forecast. ```python if __name__ == "__main__": import numpy as np from matplotlib import rc import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows import lorenz from teaspoon.DAF.forecasting import random_feature_map_model from teaspoon.DAF.forecasting import get_forecast # Set font rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']}) rc('text', usetex=True) plt.rc('text', usetex=True) plt.rc('font', family='serif') plt.rcParams.update({'font.size': 16}) # Set model parameters Dr=300 train_len = 4000 forecast_len = 2000 r_seed = 48824 np.random.seed(r_seed) # Get training and tesing data at random initial condition ICs = list(np.random.normal(size=(3,1)).reshape(-1,)) t, ts = lorenz(L=500, fs=50, SampleSize=6001, parameters=[28,10.0,8.0/3.0],InitialConditions=ICs) ts = np.array(ts) # Add noise to signals noise = np.random.normal(scale=0.01, size=np.shape(ts[:,0:train_len+forecast_len])) u_obs = ts[:,0:train_len+forecast_len] + noise # Train model W_LR, W_in, b_in = random_feature_map_model(u_obs[:,0:train_len],Dr, seed=r_seed) # Generate forecast forecast_len = 500 X_model= get_forecast(u_obs[:,train_len].reshape(-1,1), W_LR, mu=(W_in, b_in),forecast_len=forecast_len) X_meas = u_obs[:,train_len:train_len+forecast_len] # Plot measurements and forecast fig = plt.figure(figsize=(15, 5)) gs = GridSpec(1, 3) ax1 = fig.add_subplot(gs[0, 0]) ax1.plot(X_model[0,:],'r', label="Forecast") ax1.plot(X_meas[0,:], '.b', label="Measurement") ax1.plot([],[]) ax1.set_title('x', fontsize='x-large') ax1.tick_params(axis='both', which='major', labelsize='x-large') ax1.set_ylim((-30,30)) ax2 = fig.add_subplot(gs[0, 1]) ``` -------------------------------- ### Execute parameter selection example Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/parameter_selection/MsPE.html Demonstrates the usage of MsPE_tau and MsPE_n to determine parameters for a sine wave time series. ```python if __name__ == "__main__": import numpy as np import matplotlib.pyplot as plt fs = 10 t = np.linspace(0, 100, fs*100) ts = np.sin(t) m_s, m_e, d_s, d_e = 3, 7, 1, 200 # m_s and m_e are the starting and ending dimensions n to search through # d_e = max delay tau to search through # plotting option will show you how delay tau or dimension n were selected tau = int(MsPE_tau(ts, d_e, plotting=True)) n = MsPE_n(ts, tau, m_s, m_e, plotting=True) print('Embedding Delay: '+str(tau)) print('Embedding Dimension: '+str(n)) ``` -------------------------------- ### Initialize Partition Parameters Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/SP/adaptivePart.html Sets default values for boxSize and split parameters if not provided. ```python if 'boxSize' in partitionParams: self.boxSize = partitionParams['boxSize'] else: self.boxSize = 2 # if self.convertToOrd == True: # self.convertToOrd = False if 'split' in partitionParams: self.split = partitionParams['split'] else: self.split = False ``` -------------------------------- ### Initialize Partitions Class Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/parameter_selection/MI_delay.html Initializes the Partitions class, handling data conversion to ordinal coordinates if necessary and setting up partition borders and parameters. ```python import scipy import numpy as np class Partitions: def __init__(self, data=None, meshingScheme=None, numParts=3, alpha=0.05): import scipy if data is not None: # check that the data is in ordinal coordinates if not self.isOrdinal(data): print("Converting the data to ordinal...") # perform ordinal sampling (ranking) transformation xRanked = scipy.stats.rankdata(data[:, 0], method='ordinal') yRanked = scipy.stats.rankdata(data[:, 1], method='ordinal') xFloats = np.copy(data[:, 0]) xFloats.sort() yFloats = np.copy(data[:, 1]) yFloats.sort() self.xFloats = xFloats self.yFloats = yFloats data = np.column_stack((xRanked, yRanked)) # and return an empty partition bucket # If there is data, set the bounding box to be the max and in the data xmin = data[:, 0].min() xmax = data[:, 0].max() ymin = data[:, 1].min() ymax = data[:, 1].max() self.borders = {} self.borders['nodes'] = np.array([xmin, xmax, ymin, ymax]) self.borders['npts'] = data.shape[0] self.numParts = numParts self.alpha = alpha # If there is data, use the chosen meshing scheme to build the partitions. if meshingScheme == 'DV' and self.isOrdinal(data): # Figure out self.partitionBucket = self.return_partition_DV(data=data, borders=self.borders, r=self.numParts, alpha=self.alpha) else: # meshingScheme == None # Note that right now, this will just do the dumb thing for every other input self.partitionBucket = [self.borders] # set the partitions to just be the bounding box else: self.partitionBucket = [] ``` -------------------------------- ### Random Feature Map Data Assimilation Example Source: https://teaspoontda.github.io/teaspoon/modules/DAF/DataAssimilation.html Demonstrates setting up a Lorenz system, adding noise, and preparing data for assimilation using random feature maps. ```python import numpy as np from teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows import lorenz from teaspoon.DAF.data_assimilation import TADA from teaspoon.DAF.forecasting import forecast_time from teaspoon.DAF.forecasting import random_feature_map_model from teaspoon.DAF.forecasting import get_forecast from teaspoon.DAF.forecasting import G_rfm import tensorflow as tf # Set random seed r_seed = 48824 np.random.seed(r_seed) # Set TADA parameters snr = 100.0 lr = 1e-6 train_len = 4000 forecast_len = 2000 window_size = 50 max_window_number = 100 # Get training and validation data at random initial condition ics = np.random.uniform(0, 1, size=(3,)) t, ts = lorenz(L=500, fs=50, SampleSize=6001, parameters=[28,10.0,8.0/3.0], InitialConditions=ics) ts = np.array(ts) # Get signal and noise amplitudes using signal-to-noise ratio a_sig = np.sqrt(np.mean(np.square(ts),axis=1)) a_noise = a_sig * 10**(-snr/20) # Add noise to the signal Gamma = np.diag(a_noise) noise = np.random.normal(size=np.shape(ts[:,0:train_len+forecast_len])) u_obs = ts[:,0:train_len+forecast_len] + Gamma@noise ``` -------------------------------- ### initialize_Q_M Function Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/TDA/SLSP.html Initializes the priority queue (Q), mapping (M), and index list (I) for persistence calculation. ```APIDOC ## initialize_Q_M Function ### Description Initializes data structures (Q, M, I) required for calculating persistence. It identifies extrema, calculates differences, and structures them into a priority queue. ### Parameters - **sample_data** (1-D array) - The input time series data. ### Returns - **Q** (SortedList) - The priority queue containing persistence information. - **M** (list of lists) - A mapping of initial persistence data. - **I** (SortedList) - An index list for tracking elements in M. ``` -------------------------------- ### GET /nose_hoover_oscillator Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/MakeData/DynSysLib/conservative_flows.html Simulates the Nose-Hoover oscillator system. ```APIDOC ## GET /nose_hoover_oscillator ### Description Simulates the Nose-Hoover oscillator represented by the equations x_dot = y, y_dot = -x + yz, and z_dot = a - y^2. ### Parameters #### Query Parameters - **fs** (int) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. - **L** (int) - Optional - Number of iterations. - **parameters** (list) - Optional - List of values for [a]. - **InitialConditions** (list) - Optional - List of values for [x0, y0, z0]. - **dynamic_state** (str) - Optional - Set dynamic state as 'periodic' or 'chaotic'. ### Response #### Success Response (200) - **t** (array) - Time indices. - **ts** (array) - Simulation time series. ``` -------------------------------- ### Simulate Rossler system with dynamic state Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/index.html A minimal example demonstrating how to generate data from the Rossler system using a predefined dynamic state. ```python import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows import rossler t, ts = rossler(dynamic_state='periodic') TextSize = 15 plt.figure(figsize = (12,4)) gs = gridspec.GridSpec(1,2) ax = plt.subplot(gs[0, 0]) plt.xticks(size = TextSize) plt.yticks(size = TextSize) plt.ylabel(r'$x(t)$', size = TextSize) plt.xlabel(r'$t$', size = TextSize) plt.plot(t,ts[0], 'k') ax = plt.subplot(gs[0, 1]) plt.plot(ts[0], ts[1],'k.') plt.plot(ts[0], ts[1],'k', alpha = 0.25) plt.xticks(size = TextSize) plt.yticks(size = TextSize) plt.xlabel(r'$x(t)$', size = TextSize) plt.ylabel(r'$y(t)$', size = TextSize) plt.show() ``` -------------------------------- ### GET /teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows.diffusionless_lorenz_attractor Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/autonomous_dissipative_flows.html Simulates the Diffusionless Lorenz attractor system. ```APIDOC ## GET /teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows.diffusionless_lorenz_attractor ### Description Simulates the Diffusionless Lorenz attractor defined by specific differential equations. Supports periodic or chaotic response configurations. ### Parameters #### Query Parameters - **parameters** (floats) - Optional - Array of one float [R] or None if using dynamic_state - **fs** (float) - Optional - Sampling rate for simulation - **SampleSize** (int) - Optional - Length of sample at end of entire time series - **L** (int) - Optional - Number of iterations - **InitialConditions** (floats) - Optional - List of values for [x0, y0, z0] - **dynamic_state** (str) - Optional - Set dynamic state as 'periodic' or 'chaotic' ### Response #### Success Response (200) - **array** (array) - Array of time indices (t) and simulation time series (ts) ``` -------------------------------- ### GET /linear_congruential_generator_map Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/MakeData/DynSysLib/maps.html Simulates the Linear Congruential Generator map. ```APIDOC ## GET /linear_congruential_generator_map ### Description Calculates the Linear Congruential Generator map sequence defined by x_{n+1}=(ax_n+b) mod c. ### Parameters #### Query Parameters - **parameters** (array of float) - Optional - Array of 3 floats [a, b, c]. - **dynamic_state** (string) - Optional - Dynamic state ('periodic' or 'chaotic'). - **InitialConditions** (array of float) - Optional - Initial condition [x0]. - **L** (int) - Optional - Number of map iterations. - **fs** (int) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. ### Response #### Success Response (200) - **t** (array) - Time indices. - **ts** (array) - Simulation time series. ``` -------------------------------- ### Optimize Dynamical System Parameters Source: https://teaspoontda.github.io/teaspoon/modules/SP/parameter_path_opt.html Demonstrates optimizing parameters for a Lorenz system using PathOptimizer. Requires PyTorch and torchdiffeq. Ensure correct device placement and data types. ```python import torch from torchdiffeq import odeint from torch.optim.lr_scheduler import LambdaLR from teaspoon.SP.parameter_path_opt import PathOptimizer from IPython.display import clear_output device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Set bounds for the parameters x_min = 80 x_max = 300 y_min = 4 y_max = 50 # Define the system of ODEs using PyTorch class LorenzSystem(torch.nn.Module): def __init__(self, params): super().__init__() self.params = torch.nn.Parameter(params) def forward(self, t, state): x, y, z = state rho, sigma = self.params dxdt = sigma * (y - x) dydt = x * (rho - z) - y dzdt = x * y - (8.0/3.0) * z return torch.stack([dxdt, dydt, dzdt]) # Time settings t_main = torch.linspace(0, 10, 1000, device=device, dtype=torch.float64) # Main simulation # Initial conditions x0 = torch.tensor([1.0, 1.0, 1.0], requires_grad=True, device=device, dtype=torch.float64) # Combine parameters into a single vector params = torch.nn.Parameter(torch.tensor([190.0, 20.0], device=device)) # Instantiate the system with the combined parameter vector lorenz = LorenzSystem(params).to(device) # Initialize optimizer and learning rate scheduler optimizer = torch.optim.Adam([lorenz.params], lr=1.0) scheduler = LambdaLR(optimizer, lr_lambda=lambda epoch: 0.995**epoch) # Initialize lists for saving the path and losses path = [[lorenz.params[0].item(), lorenz.params[1].item()]] losses = [] # Define the forbidden regions for the parameter path forbidden_regions = [ lambda params, pd1: (params[0] - x_max), lambda params, pd1: -(params[0] - x_min), lambda params, pd1: (params[1] - y_max), lambda params, pd1: -(params[1] - y_min), lambda params, pd1: -((1/400)*(params[0]-190)**2+(1/25)*(params[1]-10)**2 - 1.0), # Example constraint: unit disk of radius 5 centered at (190, 27) ] # Initialize the PathOptimizer with the Lorenz system and forbidden regions p_opt = PathOptimizer({ 'maxPers': -1}, forbidden_regions=forbidden_regions) for epoch in range(5): # Perform the optimization step y, pd1, loss, grads = p_opt.optimize(lorenz, x0, t_main, optimizer, scheduler) # Extract the gradients with resspect to the parameters d_rho, d_sigma = grads[0], grads[1] # Print result of optimization step clear_output(wait=True) print(f"d(Loss)/d(sigma): {d_sigma.item():.5}") print(f"d(Loss)/d(rho): {d_rho.item():.5}") print(f"Loss: {loss.item():.8}") print(f"Rho: {lorenz.params[0].item():.8} -- Sigma: {lorenz.params[1].item():.8}") # Save the path and the loss path.append([lorenz.params[0].item(), lorenz.params[1].item()]) losses.append(loss.item()) ``` -------------------------------- ### GET /teaspoon.MakeData.DynSysLib.maps.kaplan_yorke_map Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/maps.html Generates a time series using the Kaplan-Yorke map. ```APIDOC ## GET /teaspoon.MakeData.DynSysLib.maps.kaplan_yorke_map ### Description Generates a time series based on the Kaplan-Yorke map definition. Allows configuration of system parameters, dynamic state, and sampling settings. ### Parameters #### Query Parameters - **parameters** (array of float) - Optional - Array of system parameters [a,b]. - **dynamic_state** (string) - Optional - Dynamic state ('periodic' or 'chaotic'). - **InitialConditions** (list) - Optional - Initial conditions for the system. - **L** (int) - Optional - Number of map iterations. - **fs** (int) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. ### Response #### Success Response (200) - **array** (array) - Array of the time indices as t and the simulation time series ts. ``` -------------------------------- ### Chen's System Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/autonomous_dissipative_flows.html Simulates Chen's System. ```APIDOC ## GET teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows.chens_system ### Description Simulates Chen's System defined by x˙=a(y−x), y˙=(c−a)x−xz+cy, z˙=xy−bz. ### Parameters #### Query Parameters - **parameters** (floats) - Optional - Array of three floats [a, b, c] or None if using dynamic_state. - **fs** (float) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. - **L** (int) - Optional - Number of iterations. - **InitialConditions** (floats) - Optional - List of values for [x0, y0, z0]. - **dynamic_state** (str) - Optional - Set dynamic state as ‘periodic’ or ‘chaotic’. ### Response - **array** - Array of the time indices as t and the simulation time series ts. ``` -------------------------------- ### GET /teaspoon.MakeData.DynSysLib.maps.cusp_map Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/maps.html Generates a time series using the Cusp map. ```APIDOC ## GET /teaspoon.MakeData.DynSysLib.maps.cusp_map ### Description Generates time series data based on the Cusp map equation xn+1 = 1 - a*|xn|. ### Parameters #### Query Parameters - **parameters** (array of float) - Optional - Array of system parameters [a]. - **dynamic_state** (string) - Optional - Dynamic state ('periodic' or 'chaotic'). - **L** (int) - Optional - Number of map iterations. - **fs** (int) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. ### Response #### Success Response (200) - **array** (array) - Array of the time indices as t and the simulation time series ts. ``` -------------------------------- ### Simulate Rössler System Source: https://teaspoontda.github.io/teaspoon/_sources/modules/MakeData/DynSysLib/index.rst.txt A minimal example demonstrating how to generate and plot time-series data using the Rössler system from the library. ```python import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from teaspoon.MakeData.DynSysLib.autonomous_dissipative_flows import rossler t, ts = rossler(dynamic_state='periodic') TextSize = 15 plt.figure(figsize = (12,4)) gs = gridspec.GridSpec(1,2) ax = plt.subplot(gs[0, 0]) plt.xticks(size = TextSize) plt.yticks(size = TextSize) plt.ylabel(r'$x(t)$', size = TextSize) plt.xlabel(r'$t$', size = TextSize) plt.plot(t,ts[0], 'k') ax = plt.subplot(gs[0, 1]) plt.plot(ts[0], ts[1],'k.') plt.plot(ts[0], ts[1],'k', alpha = 0.25) plt.xticks(size = TextSize) plt.yticks(size = TextSize) plt.xlabel(r'$x(t)$', size = TextSize) plt.ylabel(r'$y(t)$', size = TextSize) plt.show() ``` -------------------------------- ### GET /teaspoon.MakeData.DynSysLib.maps.gauss_map Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/maps.html Generates a time series using the Gauss map. ```APIDOC ## GET /teaspoon.MakeData.DynSysLib.maps.gauss_map ### Description Generates time series data based on the Gauss map equation xn+1 = exp(-alpha*xn^2) + beta. ### Parameters #### Query Parameters - **parameters** (array of floats) - Optional - Array of parameters [alpha, beta]. - **beta** (float) - Optional - System parameter. - **dynamic_state** (string) - Optional - Dynamic state ('periodic' or 'chaotic'). - **L** (int) - Optional - Number of map iterations. - **fs** (int) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. ### Response #### Success Response (200) - **array** (array) - Array of the time indices as t and the simulation time series ts. ``` -------------------------------- ### Get Partition Size Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/parameter_selection/MI_delay.html Returns the number of partitions currently stored. ```python def __len__(self): return len(self.partitionBucket) ``` -------------------------------- ### GET /teaspoon.MakeData.DynSysLib.maps.gingerbread_man_map Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/maps.html Generates a time series using the Gingerbread Man map. ```APIDOC ## GET /teaspoon.MakeData.DynSysLib.maps.gingerbread_man_map ### Description Generates a time series based on the Gingerbread Man map definition. Allows configuration of system parameters, dynamic state, and sampling settings. ### Parameters #### Query Parameters - **a** (float) - Optional - System parameter. - **b** (float) - Optional - System parameter. - **dynamic_state** (string) - Optional - Dynamic state ('periodic' or 'chaotic'). - **L** (int) - Optional - Number of map iterations. - **fs** (int) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. ### Response #### Success Response (200) - **array** (array) - Array of the time indices as t and the simulation time series ts. ``` -------------------------------- ### GET /teaspoon.MakeData.DynSysLib.maps.sine_circle_map Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/maps.html Generates a time series using the Sine Circle map. ```APIDOC ## GET /teaspoon.MakeData.DynSysLib.maps.sine_circle_map ### Description Generates time series data based on the Sine Circle map equation xn+1 = xn + omega - [k/2pi * sin(2pi*xn)]. ### Parameters #### Query Parameters - **parameters** (array of float) - Optional - Array of system parameters [omega, k]. - **dynamic_state** (string) - Optional - Dynamic state ('periodic' or 'chaotic'). - **L** (int) - Optional - Number of map iterations. - **fs** (int) - Optional - Sampling rate for simulation. ### Response #### Success Response (200) - **array** (array) - Array of the time indices as t and the simulation time series ts. ``` -------------------------------- ### Initialize Persistence Data Structures Source: https://teaspoontda.github.io/teaspoon/_modules/teaspoon/TDA/SLSP.html Initializes data structures (Q, M, I) for persistence calculation from sample time series data. Assumes trend at edges continues infinitely. ```python def initialize_Q_M(sample_data): #import packages import numpy as np from scipy.signal import find_peaks from sortedcontainers import SortedList slope_o, slope_f = sample_data[0] - \ sample_data[1], sample_data[-1]-sample_data[-2] # assumes trend at edges continues to infinity NegEnd, PosEnd = -float('inf'), float('inf') if slope_o < 0: sample_data[0] = NegEnd else: sample_data[0] = PosEnd if slope_f < 0: sample_data[-1] = NegEnd else: sample_data[-1] = PosEnd # get extrema locations max_locs, _ = find_peaks(sample_data) min_locs, _ = find_peaks(-sample_data) # add outside borders as infinity extrema if slope_o < 0: min_locs = np.insert(min_locs, 0, 0, axis=0) else: max_locs = np.insert(max_locs, 0, 0, axis=0) if slope_f < 0: min_locs = np.insert(min_locs, len(min_locs), -1, axis=0) else: max_locs = np.insert(max_locs, len(max_locs), -1, axis=0) # get extrema values max_vals, min_vals = sample_data[max_locs], sample_data[min_locs] if max_locs[0] < min_locs[0]: # if peak first # chronologically ordered peaks and valleys PV = interleave(max_vals, min_vals) # indices of ordered peaks and valleys I_PV = interleave(max_locs, min_locs) else: # if valley first # chronologically ordered peaks and valleys PV = interleave(min_vals, max_vals) # indices of ordered peaks and valleys I_PV = interleave(min_locs, max_locs) # get priority value array as chronological pairwise difference v = abs(np.diff(PV)) # get pointer to M array before sorting ptr = np.arange(len(v)) # generate priority matrix Q by stacking together v, ptr, PV and I_PV Q = (np.array([v, ptr, PV[:-1], PV[1:], I_PV[:-1], I_PV[1:]]).T).tolist() # generate dictionary for quick looking up indices in Q M = Q # M is defined as the unordered Q because it allows for pointers back to Q by a value lookup O(log(n)), # which is a lot faster than trying to update all the pointers in M to Q for each deleted pair. # created sorted list from Q Q = SortedList(Q) # get indice array for knowing which element of Q have been deleted. I = np.arange(len(Q)).tolist() I = SortedList(I) return Q, M, I ``` -------------------------------- ### Initialize Partitions Data Structure Source: https://teaspoontda.github.io/teaspoon/modules/SP/misc.html Instantiate the `Partitions` class to store data from an adaptive meshing scheme. Supports optional ordinal conversion and custom meshing parameters. ```python partitions = _teaspoon.SP.adaptivePart.Partitions(_data=None, _convertToOrd=False, _meshingScheme=None, _partitionParams={}) ``` -------------------------------- ### GET /teaspoon.MakeData.DynSysLib.maps.pinchers_map Source: https://teaspoontda.github.io/teaspoon/modules/MakeData/DynSysLib/maps.html Generates a time series using the Pincher's map. ```APIDOC ## GET /teaspoon.MakeData.DynSysLib.maps.pinchers_map ### Description Generates time series data based on the Pincher's map equation xn+1 = |tanh(s(xn-c))|. ### Parameters #### Query Parameters - **parameters** (array of float) - Optional - Array of system parameters [s, c]. - **dynamic_state** (string) - Optional - Dynamic state ('periodic' or 'chaotic'). - **L** (int) - Optional - Number of map iterations. - **fs** (int) - Optional - Sampling rate for simulation. - **SampleSize** (int) - Optional - Length of sample at end of entire time series. ### Response #### Success Response (200) - **array** (array) - Array of the time indices as t and the simulation time series ts. ```