pyreco package

Submodules

pyreco.cross_validation module

pyreco.cross_validation.cross_val(model, X: ndarray, y: ndarray, n_splits: int, metric: str = 'mse') Tuple[List[float], float, float][source]

Performs k-fold cross-validation on a given model.

Parameters: model : object

The RC model to be validated.

Xnp.ndarray

Feature matrix.

ynp.ndarray

Target vector.

n_splitsint

Number of folds.

metricsstr

Metric to evaluate.

Returns: tuple

A tuple containing: - list of metric’s value for each fold - mean of the metric values - standard deviation of the metric values

pyreco.custom_models module

class pyreco.custom_models.AutoRC(FeedbackLayer=None)[source]

Bases: CustomModel

Autonomous version of the reservoir computer.

predict_ar(X: ndarray, n_steps: int = 10)[source]

Perform auto-regressive prediction (time series forecasting).

Args: X (np.ndarray): Initial input data. n_steps (int): Number of steps to predict into the future.

Returns: np.ndarray: Predicted future states.

class pyreco.custom_models.CustomModel[source]

Bases: ABC

Abstract base class for custom reservoir computing model.

Has a syntax similar to the one of TensorFlow model API, e.g. using the model.add() statement to add layers to the model.

A model hast an input layer, a reservoir layer and a readout layer.

AutoRC_compile(optimizer: str = 'ridge', metrics: list | str | None = None, discard_transients: int = 0)[source]

Configure the model for training.

Args: optimizer (str): Name of the optimizer. metrics (list): List of metric names. discard_transients (int): Number of initial transient timesteps to discard.

AutoRC_predict(x: ndarray, fb_scale: float, T_run: int, feedback_indices: ndarray | None = None) ndarray[source]

Contains the prediction function for the AutoRC model along with the feedback mechanism. It returns the predictions and reservoir states.

Parameters:
  • x (np.ndarray) – Input data of shape [n_batch, n_timesteps, n_states]

  • feedback_indices (np.ndarray) – Indices from the inputs to be used for feedback

  • user (because we want to select those feedback/input weights for the feedback. If not given by the)

:param : :param the model will use all available feedback weights.:

Returns:

Reservoir states of shape [(n_batch * n_timesteps), N],

Predictions of shape [n_batch, n_timesteps, n_states_out]

Return type:

np.ndarray

add(layer: Layer)[source]

Add a layer to the model.

Is type-sensitive and will assign the layer to the correct attribute.

Args: layer (Layer): Layer to be added to the model.

compile(optimizer: str = 'ridge', metrics: list | str | None = None, discard_transients: int = 0)[source]

Configure the model for training.

Args: optimizer (str): Name of the optimizer. metrics (list): List of metric names. discard_transients (int): Number of initial transient timesteps to discard.

compute_reservoir_state(x: ndarray) ndarray[source]

Vectorized computation of reservoir states with batch processing.

Parameters:

x (np.ndarray) – Input data of shape [n_batch, n_timesteps, n_states]

Returns:

Reservoir states of shape [(n_batch * n_timesteps), N]

Return type:

np.ndarray

evaluate(x: ndarray, y: ndarray, metrics: str | list | None = None) tuple[source]

Evaluate metrics on predictions made for input data.

Args: x (np.ndarray): Input data of shape [n_batch, n_timesteps, n_states] y (np.ndarray): Target data of shape [n_batch, n_timesteps_out, n_states_out] metrics (Union[str, list, None], optional): List of metric names or a single metric name. If None, use metrics from .compile()

Returns: tuple: Metric values

fit(x: ndarray, y: ndarray, visualize=False, n_init: int = 1, store_states: bool = False) dict[source]

RC training with batch processing.

fit_evolve(X: ndarray, y: ndarray)[source]
get_hp(*args)[source]

Get one or more reservoir hyperparameters. If no args, returns all. Usage: get_hp(‘spec_rad’, ‘activation’) or get_hp()

model_visualize(save=False, file_name=None, file_type=None, Node_colors=None, Edge_Weights=None)[source]

Visualizes the reservoir network. Allows saving in PNG/PDF/JPG?SVG/JPEG formats with a custom filename. Allows user-defined node/edge colors.

plot(path: str)[source]

Print the model to some figure file.

Args: path (str): Path to save the figure.

predict(x: ndarray) ndarray[source]

Make predictions for given input.

Args: x (np.ndarray): Input data of shape [n_batch, n_timestep, n_states] one_shot (bool): If True, don’t re-initialize reservoir between samples.

Returns: np.ndarray: Predictions of shape [n_batch, n_timestep, n_states]

remove_reservoir_edges(edges: list)[source]

Removes specific edges from the reservoir weights by setting them 0.

Parameters:

edges (list of tuple) – List of edges (u, v) tuples representing the edges to remove.

Raises:

TypeError – If ‘edges’ is not a list, or if the reservoir weights are neither a NetworkX graph nor a NumPy array.

Notes

For ‘np.ndarray’ weights, only ‘weights[u, v]’ is zeroed, the reverse direction ‘weights[v, u]’ is not adjusted. This is correct for directed graphs (the assumed case), but for an undirected graphs, leaving the matrix asymmetric, with the edge still present in the reverse direction.

remove_reservoir_nodes(nodes: list)[source]
save(path: str)[source]

Store the model to disk.

Args: path (str): Path to save the model.

set_hp(**kwargs)[source]

Set one or more reservoir hyperparameters. Supported kwargs: spec_rad, leakage_rate, activation

set_input_scaling(input_scaling: float)[source]

Set input scaling factor.

Parameters:

input_scaling (float or np.ndarray) – Scalar or per-channel vector.

set_normalization(normalize_inputs: bool | None = None, normalize_outputs: bool | None = None)[source]

Set normalization flags independently.

Parameters:
  • normalize_inputs (bool or None) – Enable/disable input normalization. If None, leave unchanged.

  • normalize_outputs (bool or None) – Enable/disable output normalization. If None, leave unchanged.

set_output_scaling(output_scaling: float)[source]

Set output scaling factor.

Parameters:

output_scaling (float) – Scalar value for output scaling.

class pyreco.custom_models.HybridRC[source]

Bases: CustomModel

Hybrid version of the reservoir computer.

class pyreco.custom_models.RC[source]

Bases: CustomModel

Non-autonomous version of the reservoir computer.

pyreco.datasets module

Standard chaotic system datasets for reservoir computing.

This module provides time series data from chaotic dynamical systems, formatted for direct use with PyReCo reservoir computers.

All data generators use numerical integration of the governing equations. Lorenz system uses scipy.integrate.solve_ivp for stable ODE integration. Mackey-Glass uses custom Euler integration for delay differential equations.

pyreco.datasets.load(dataset_name, n_samples=5000, train_fraction=0.7, n_in=100, n_out=1, seed=None, val_fraction=None, standardize=False, **kwargs)[source]

Load chaotic time series dataset with train/test split.

This function generates data from chaotic dynamical systems using reservoirpy and formats it for reservoir computing tasks using sliding windows.

Parameters:
  • dataset_name (str) – Name of the dataset. Supported options: - ‘lorentz69’ or ‘lorenz’ or ‘lorenz63’: Lorenz 1963 attractor (3D system) - ‘mackey_glass’ or ‘mackeyglass’ or ‘mg’: Mackey-Glass delay system (1D system)

  • n_samples (int, default=5000) – Number of time steps to generate from the chaotic system

  • train_fraction (float, default=0.7) – Fraction of data to use for training (between 0 and 1)

  • n_in (int, default=100) – Number of time steps in each input window

  • n_out (int, default=1) – Number of time steps in each output window (prediction horizon)

  • seed (int, optional) – Random seed for reproducibility (used for Mackey-Glass)

  • val_fraction (float, optional) – Fraction of training data to use for validation (between 0 and 1). If None (default), no validation split is created. If set, the function will: - Split validation set BEFORE sliding window (prevents data leakage) - Automatically enable standardization (standardize=True) - Fit StandardScaler only on the final training set - Return 7 items: x_train, y_train, x_val, y_val, x_test, y_test, scaler

  • standardize (bool, default=False) – Whether to standardize the data using StandardScaler. If True (and val_fraction=None), returns 5 items including the scaler. If val_fraction is set, standardization is automatically enabled. Standardization is recommended for reservoir computing as it: - Normalizes features to similar scales - Improves Ridge regression performance - Accelerates neural network training

  • **kwargs (dict) – Additional parameters passed to the generator function: - For Lorenz: sigma, rho, beta, h (time step), x0 (initial condition) - For Mackey-Glass: tau, a, b, n, h (time step), x0 (initial value)

Returns:

  • When standardize=False and val_fraction=None (default, backward compatible)

    x_trainndarray of shape (n_train_samples, n_in, n_features)

    Training input windows

    y_trainndarray of shape (n_train_samples, n_out, n_features)

    Training output windows (targets)

    x_testndarray of shape (n_test_samples, n_in, n_features)

    Test input windows

    y_testndarray of shape (n_test_samples, n_out, n_features)

    Test output windows (targets)

  • When standardize=True and val_fraction=None

    x_trainndarray of shape (n_train_samples, n_in, n_features)

    Training input windows (standardized)

    y_trainndarray of shape (n_train_samples, n_out, n_features)

    Training output windows (standardized)

    x_testndarray of shape (n_test_samples, n_in, n_features)

    Test input windows (standardized)

    y_testndarray of shape (n_test_samples, n_out, n_features)

    Test output windows (standardized)

    scalerStandardScaler

    Fitted scaler object (fitted only on training data)

  • When val_fraction is set (standardize automatically enabled)

    x_trainndarray of shape (n_train_final_samples, n_in, n_features)

    Training input windows (standardized)

    y_trainndarray of shape (n_train_final_samples, n_out, n_features)

    Training output windows (standardized)

    x_valndarray of shape (n_val_samples, n_in, n_features)

    Validation input windows (standardized)

    y_valndarray of shape (n_val_samples, n_out, n_features)

    Validation output windows (standardized)

    x_testndarray of shape (n_test_samples, n_in, n_features)

    Test input windows (standardized)

    y_testndarray of shape (n_test_samples, n_out, n_features)

    Test output windows (standardized)

    scalerStandardScaler

    Fitted scaler object (fitted only on training data)

Examples

>>> # Load Lorenz system data
>>> x_train, y_train, x_test, y_test = load('lorentz69', n_samples=5000, seed=42)
>>> print(x_train.shape)  # (3400, 100, 3)
>>> print(y_train.shape)  # (3400, 1, 3)
>>> # Load Mackey-Glass data
>>> x_train, y_train, x_test, y_test = load('mackey_glass', n_samples=5000, seed=42)
>>> print(x_train.shape)  # (3400, 100, 1)
>>> print(y_train.shape)  # (3400, 1, 1)

Notes

  • Input: Past n_in time steps

  • Output: Future n_out time steps (immediately following the input window)

  • Data is split chronologically (earlier data for training, later for testing)

  • Reproducible when seed is set (for Mackey-Glass)

  • Data generation uses numerical integration: * Lorenz: scipy.integrate.solve_ivp for stable ODE integration * Mackey-Glass: Euler integration for delay differential equation

  • When val_fraction is used: * Validation split happens BEFORE sliding window to prevent data leakage * StandardScaler is fitted ONLY on final training data (not on validation) * This ensures validation set statistics don’t leak into training preprocessing * All datasets (train/val/test) are standardized using the same scaler

pyreco.edge_analyzer module

class pyreco.edge_analyzer.EdgeAnalyzer(quantities=None)[source]

Bases: object

A class for analyzing properties of a specific edge in a graph, analogue to ‘NodeAnalyzer for nodes.

Takes a graph and a specific edge (u, v), returning a flat dict of scalars describing that edge and the nodes it connects.

Note: betweenness-based properties (betweenness, source_betweenness, target_betweenness) each trigger a full graph betweenness computation. If all three are requested, consider passing a subset via quantities to avoid redundant computation on large graphs.

extract_properties(graph: Graph | DiGraph | ndarray, edge: tuple) dict[source]

Extracts the specified properties for a given edge.

Parameters:
  • graph (nx.Graph, nx.DiGraph, or np.ndarray) – Graph to analyze.

  • edge (tuple) – Edge (u, v) to extract properties for.

Returns:

Dictionary containing the extracted edge properties.

Return type:

dict

extract_properties_batch(graph: Graph | DiGraph | ndarray, edges: list) list[source]

Extracts properties for a list of edges with expensive graph-level metrics (betweenness centrality, SCC) so that they’re computed only once.

Parameters:
  • graph (nx.Graph, nx.DiGraph, or np.ndarray) – Graph in its current state, e.g. before edge removal.

  • edges (list) – List of edges, (u, v) tuples, to extract properties for.

Returns:

List of dicts containing the extracted edge properties. One per edge, in the same order as edges.

Return type:

list

list_properties()[source]

Returns list of available edge properties.

Returns:

Available edge property names.

Return type:

list

pyreco.edge_analyzer.available_extractors()[source]

Returns a dictionary mapping edge property names to their extractor functions. Each function has signature f(graph, edge) -> scalar, where edge is a (u, v) tuple. Make changes here to add more edge properties.

Returns:

mapping property name -> extractor function

Return type:

dict

pyreco.edge_analyzer.map_extractor_names(prop_names: list)[source]

Return extractors for the requested property names.

Returns:

  • dict – Dict mapping property name to extractor function

  • list – List of extractor functions in same order

pyreco.edge_pruning module

class pyreco.edge_pruning.EdgePruner(edge_selection_strat: str = 'random_uniform_wo_repl', candidate_fraction: float = 0.1, pruning_criterion: str = 'performance', stopping_criterion: list = ['patience'], min_num_nodes: int = 3, min_num_edges: int = 2, patience: int = 0, performance_criterion: str = 'mse', structural_criterion: str = 'betweenness', metrics: list | str = ['mse'], return_best_model: bool = True, graph_analyzer: GraphAnalyzer | None = None, node_analyzer: NodeAnalyzer | None = None, edge_analyzer: EdgeAnalyzer | None = None, remove_isolated_nodes: bool = False, directed: bool = True, parallel: bool = False)[source]

Bases: object

PRUNING_CRITERION = {'performance': '_performance_pruning', 'structure': '_structural_pruning'}
STOPPING_CRITERION = {'min_edges': '_min_num_edges_stopping', 'min_nodes': '_min_num_nodes_stopping', 'patience': '_patience_stopping'}
prune(model: RC, data_train: tuple, data_val: tuple)[source]

Prune a given model by iteratively removing edges.

Parameters:
  • model (RC) – Reservoir computer model to prune.

  • data_train (tuple) – Tuple (x_train, y_train) of training data.

  • data_val (tuple) – Tuple (x_val, y_val) of validation data, used to score candidates and to evaluate the stopping criterion.

Returns:

  • model (RC) – Pruned model (refit on data_train). If return_best_model is True, this is the model with the lowest recorded loss during pruning, otherwise the last model produced before stopping.

  • history (dict) – Nested dictionary recording, per pruning iteration, the model state before and after pruning, the evaluated candidates and their scores, and any nodes removed as a side effect.

pyreco.edge_selector module

class pyreco.edge_selector.EdgeSelector(graph: Graph | ndarray | None = None, strategy: str = 'random_uniform_wo_repl', directed: bool = True)[source]

Bases: object

A class to select edges from a graph based on specific criteria, analogue to ‘NodeSelector’.

Parameters:
  • graph (nx.Graph or np.ndarray) – NetworkX graph or adjacency matrix to select edges from.

  • strategy (str, optional) – Strategy used for edge selection. Default is “random_uniform_wo_repl”.

graph

Input graph.

Type:

nx.Graph or np.ndarray

directed

Whether the graph is directed. Only used for np.ndarray inputs. Default is True.

Type:

bool, optional

edge_indices

List of all edge indices in the graph.

Type:

list of tuple

num_total_edges

Total number of edges in the graph.

Type:

int

num_select_edges

Number of edges to select. Set after calling select_edges.

Type:

int

fraction

Fraction of edges to select. Set after calling select_edges.

Type:

float

strategy

Method corresponding to the selected strategy.

Type:

callable

selected_edges

List of selected edges. Set after calling select_edges.

Type:

list

Raises:
STRATEGIES = {'random_uniform_wo_repl': '_random_uniform_wo_repl'}
select_edges(fraction: float | None = None, num: int | None = None)[source]

Select a subset of edges from the graph.

Parameters:
  • fraction (float, optional) – Fraction of total edges to select. Must be in (0, 1]. Mutually exclusive with num.

  • num (int, optional) – Exact number of edges to select. Must be a positive integer no greater than the total number of edges. Mutually exclusive with fraction.

Returns:

List of selected edge indices as (source, target) tuples.

Return type:

list of tuple

Raises:
  • ValueError – If neither or both of fraction and num are provided.

  • TypeError – If num is not an integer, or fraction is not a float.

  • ValueError – If num is not in [1, num_total_edges], or fraction not in (0, 1].

pyreco.graph_analyzer module

class pyreco.graph_analyzer.GraphAnalyzer(quantities=None)[source]

Bases: object

A class for analyzing graph properties and extracting network properties from a graph.

extract_properties(graph: Graph | DiGraph | ndarray) dict[source]

Extract the specified network properties from the given graph.

Parameters:

graph (nx.Graph, nx.DiGraph, np.ndarray) – The graph to analyze.

Returns:

A dictionary containing the extracted network properties.

Return type:

dict

list_properties()[source]

Return a list of available network properties.

Returns:

A list of available network properties.

Return type:

list

pyreco.graph_analyzer.available_extractors()[source]

Return a dictionary mapping network property names to their corresponding extractor functions. Make changes here if you want to add more network properties.

Returns:

A dictionary mapping network property names to their corresponding extractor functions.

Return type:

dict

pyreco.graph_analyzer.map_extractor_names(prop_names: str)[source]

Return a dictionary mapping network property names to their corresponding extractor functions for the given property names.

Returns:

A dictionary mapping network property names to their corresponding extractor functions.

Return type:

dict

pyreco.initializer module

class pyreco.initializer.NetworkInitializer(method: str = 'random')[source]

Bases: object

network initializers.

gen_initial_states(shape: tuple | list) ndarray[source]

Generate initial states for the reservoir.

Parameters: - shape (tuple, list): The shape of array to generate

Returns: - np.ndarray: The initialized array

pyreco.layers module

We will have an abstract Layer class, from which the following layers inherit:

  • InputLayer

  • ReservoirLayer
    • RandomReservoir

    • RecurrenceReservoir

    • EvolvedReservoir

  • ReadoutLayer

class pyreco.layers.FeedbackLayer(feedback_shape)[source]

Bases: Layer

remove_nodes(nodes: list)[source]
update_layer_properties()[source]
class pyreco.layers.InputLayer(input_shape)[source]

Bases: Layer

remove_nodes(nodes: list)[source]
update_layer_properties()[source]
class pyreco.layers.Layer[source]

Bases: ABC

abstract update_layer_properties()[source]
class pyreco.layers.RandomReservoirLayer(nodes, density: float = 0.1, activation: str = 'tanh', leakage_rate: float = 0.5, fraction_input: float = 0.8, spec_rad: float = 0.9, init_res_sampling='random_normal', seed=None)[source]

Bases: ReservoirLayer

class pyreco.layers.ReadoutLayer(output_shape, fraction_out=1.0)[source]

Bases: Layer

remove_nodes(nodes: list)[source]
update_layer_properties()[source]
class pyreco.layers.ReservoirLayer(nodes, density, activation, leakage_rate, fraction_input, init_res_sampling, seed: int = 42)[source]

Bases: Layer

activation_fun(x: ndarray)[source]
get_activation()[source]
get_leakage_rate()[source]
get_spec_rad()[source]
remove_nodes(nodes: list)[source]

Remove specified nodes from the reservoir network. Parameters: nodes (list): A list of indices representing the nodes to be removed. 1. Removes the specified nodes from the adjacency matrix. 2. Updates the reservoir properties including the number of nodes, density, and spectral radius.

set_activation(value)[source]
set_initial_state(r_init: ndarray)[source]
set_leakage_rate(value)[source]
set_spec_rad(value)[source]

Sets the spectral radius of the reservoir network. Parameters: - value (float): The desired spectral radius. Raises: - ValueError: If the value is not positive or if the weights are not set.

set_weights(network: ndarray)[source]
update_layer_properties()[source]

Updates the reservoir properties including the number of nodes, density, and spectral radius. This method should be called after any changes to the reservoir network.

pyreco.metrics module

pyreco.metrics.assign_metric(metric: str)[source]
pyreco.metrics.available_metrics() list[source]
pyreco.metrics.mae(y_true: ndarray, y_pred: ndarray) float[source]
pyreco.metrics.mse(y_true: ndarray, y_pred: ndarray) float[source]
pyreco.metrics.r2(y_true: ndarray, y_pred: ndarray) float[source]

pyreco.models module

Higher-level model definition for default models (built on custom models):

Wrapper for lower-level implementation of RCs. Instead of the Sequential-API-type syntax, this will provide sklearn-ready models, which under the hood build Sequential-API-type models and ship them.

Currently contains a lot of duplicate code, which needs to be ported to the lower-level implementations.

class pyreco.models.Model(num_nodes: int = 100, activation: str = 'tanh', leakage_rate: float = 0.5)[source]

Bases: ABC

compile(optimizer: str = 'ridge', metrics: None | list = None)[source]
evaluate(X: ndarray, y: ndarray, metrics: str | list = ['mse'])[source]
abstract fit(X: ndarray, y: ndarray)[source]
get_params(deep=True)[source]
abstract predict(X: ndarray) ndarray[source]
abstract remove_reservoir_nodes(nodes: list)[source]
set_params(**get_params)[source]
class pyreco.models.ReservoirComputer(num_nodes: int = 100, density: float = 0.8, activation: str = 'tanh', leakage_rate: float = 0.5, spec_rad: float = 0.9, fraction_input: float = 1.0, fraction_output: float = 1.0, n_time_in=None, n_time_out=None, n_states_in=None, n_states_out=None, metrics: str | list = 'mean_squared_error', optimizer: str | Optimizer = 'ridge', init_res_sampling='random_normal')[source]

Bases: Model

evaluate(x: ndarray, y: ndarray, metrics: list = ['mse'])[source]
fit(x: ndarray, y: ndarray, n_init: int = 1, store_states: bool = False)[source]
get_params(deep=True)[source]
predict(x: ndarray) ndarray[source]
remove_reservoir_nodes(nodes: list)[source]
set_params(**get_params)[source]

pyreco.network_prop_extractor module

pyreco.node_analyzer module

class pyreco.node_analyzer.NodeAnalyzer(quantities=None)[source]

Bases: object

A class for analyzing node properties in a graph.

extract_properties(graph: Graph | DiGraph | ndarray, node: int) dict[source]

Extract the specified network properties from the given graph at the given node(s).

Parameters:
  • graph (nx.Graph, nx.DiGraph, np.ndarray) – The graph to analyze.

  • nodes (int) – The node to analyze.

Returns:

A dictionary containing the extracted network properties.

Return type:

dict

list_properties()[source]

Return a list of available node properties.

Returns:

A list of available node properties.

Return type:

list

pyreco.node_analyzer.available_extractors()[source]

Return a dictionary mapping network property names to their corresponding extractor functions. Make changes here if you want to add more network properties.

Returns:

A dictionary mapping network property names to their corresponding extractor functions.

Return type:

dict

pyreco.node_analyzer.map_extractor_names(prop_names: str)[source]

Return a dictionary mapping network property names to their corresponding extractor functions for the given property names.

Returns:

A dictionary mapping network property names to their corresponding extractor functions.

Return type:

dict

pyreco.node_selector module

class pyreco.node_selector.NodeSelector(strategy: str = 'random_uniform_wo_repl', total_nodes: int | None = None, graph: Graph | ndarray | None = None)[source]

Bases: object

A class to select nodes from a graph based on specific criteria.

This class provides functionality to select a subset of nodes from a total number of nodes using different strategies. Currently, only the “random without replacement” strategy is implemented.

Attributes: - num_total_nodes (int): The total number of nodes in the graph. - num_select_nodes (int): The number of nodes to select. - fraction (float): The fraction of nodes to select. - strategy (str): The strategy used for node selection. - selected_nodes (list): The list of selected nodes.

select_nodes(fraction: float | None = None, num: int | None = None)[source]

Selects a specified number of nodes from the graph either by fraction or by exact number.

Parameters: - fraction (float, optional): The fraction of the total nodes to select. Must be between 0 and 1. - num (int, optional): The exact number of nodes to select. Must be a positive integer.

Raises: - ValueError: If neither or both of fraction and num are provided. - TypeError: If num is not an integer.

Returns: - list: A list of selected node identifiers.

pyreco.optimizers module

class pyreco.optimizers.Optimizer(name: str = '')[source]

Bases: ABC

abstract solve(A: ndarray, b: ndarray) ndarray[source]
class pyreco.optimizers.RidgeSK(name: str = '', alpha=1.0)[source]

Bases: Optimizer

get_alpha() float[source]
set_alpha(value: float)[source]
solve(A: ndarray, b: ndarray) ndarray[source]
pyreco.optimizers.assign_optimizer(optimizer: str) Optimizer[source]

Maps names of optimizers to the correct implementation.

Parameters:

optimizer (str or Optimizer) – The name of the optimizer.

Returns:

An instance of the optimizer class corresponding to the given name.

Return type:

Optimizer

Raises:

ValueError – If the given optimizer name is not implemented.

pyreco.plotting module

Some plotting capabilities

pyreco.plotting.r2_scatter(y_true: ndarray, y_pred: ndarray, state_idx: int | tuple | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None)[source]
pyreco.plotting.visualize_reservoir_network_circle(G_Net, W_inp, W_out, n_inputs, n_outputs, seed=None, save_path=None, Node_colors=None, Edge_Weights=None)[source]

Draws a circular layout diagram for ESN/RC architecture. Handles ANY valid shape of W_inp and W_out safely. Allows custom colors.

pyreco.pruning module

Capabilities to prune an existing RC model, i.e. try to cut reservoir nodes and improve performance while reducing the reservoir size

class pyreco.pruning.NetworkPruner(target_score: float | None = None, stop_at_minimum: bool = True, min_num_nodes: int = 3, patience: int = 0, candidate_fraction: float = 0.1, remove_isolated_nodes: bool = False, criterion: str = 'mse', metrics: list | str = ['mse'], maintain_spectral_radius: bool = False, node_props_extractor=None, graph_props_extractor=None, return_best_model: bool = True, graph_analyzer: GraphAnalyzer | None = None, node_analyzer: NodeAnalyzer | None = None)[source]

Bases: object

add_dict_to_history(keys, value_dict)[source]

Add a dictionary to history dictionary based on a list of keys.

Args: nested_dict (dict): The nested dictionary. keys (list): A list of keys specifying the path in the nested dictionary. value_dict (dict): The dictionary to add.

add_val_to_history(keys, value)[source]

Add a value to history dictionary based on a list of keys.

Parameters:
  • keys (list) – A list of keys specifying the path in the nested dictionary.

  • value – The value to add.

prune(model: RC, data_train: tuple, data_val: tuple)[source]

Prune a given model by removing nodes.

Parameters: - model (RC): The reservoir computer model to prune. - data_train (tuple): Training data. - data_val (tuple): Validation data.

pyreco.pruning.append_to_dict(dict1, dict2)[source]
pyreco.pruning.dictlist_to_dict(dict_list)[source]

Join dictionaries in a list into a common dictionary.

Parameters:

dict_list (list) – A list of dictionaries to join.

Returns:

A common dictionary containing all key-value pairs from the dictionaries in the list.

Return type:

dict

pyreco.remove_transients module

pyreco.remove_transients.RemoveTransient_Inps(X, Transients)[source]
pyreco.remove_transients.RemoveTransient_Outs(Y, Transients)[source]
pyreco.remove_transients.RemoveTransients_Res(ResStates, Transients)[source]
pyreco.remove_transients.TransientRemover(What: str, ResStates, X, Y, Transients: int)[source]

pyreco.tuner module

pyreco.utils_data module

Provides testing data sets.

SHAPES will always be: inputs X: [n_batch, n_timesteps, n_states] outputs y: [n_batch, n_timesteps, n_states]

pyreco.utils_data.gen_cos(n=10, omega=3.141592653589793)[source]
pyreco.utils_data.gen_sincos(n=10, omega=3.141592653589793, a_sc=1, b_sc=0.25, P_sc=3)[source]
pyreco.utils_data.gen_sine(n=10, omega=3.141592653589793)[source]
pyreco.utils_data.sequence_to_scalar(name, n_batch: int = 50, n_states=1, n_time_in=2)[source]
pyreco.utils_data.sequence_to_sequence(name, n_batch: int = 50, n_states: int = 2, n_time: int = 3)[source]
pyreco.utils_data.sincos2(n_batch, n_time_in, n_time_out, n_states)[source]
pyreco.utils_data.sine_pred(n_batch, n_time_in, n_time_out, n_states)[source]
pyreco.utils_data.sine_to_cosine(n_batch, n_time_in, n_time_out, n_states)[source]
pyreco.utils_data.split_sequence(signal, n_batch, n_time_in, n_time_out)[source]
pyreco.utils_data.train_test_split(x, y)[source]
pyreco.utils_data.vector_to_vector(name, n_batch: int = 50, n_states=1)[source]
pyreco.utils_data.x_to_x(name, n_batch: int = 50, n_states_in: int = 2, n_states_out: int = 2, n_time_int: int = 1, n_time_out: int = 1)[source]

pyreco.utils_networks module

Helper routines for networks

pyreco.utils_networks.compute_density(network: ndarray) float[source]
pyreco.utils_networks.compute_spec_rad(network: ndarray) float[source]
pyreco.utils_networks.convert_to_nx_graph(graph: ndarray) Graph[source]

Convert a numpy array to a NetworkX graph. :param adjacency_matrix: The adjacency matrix of the graph. :type adjacency_matrix: np.ndarray

Returns:

The NetworkX graph.

Return type:

nx.Graph

pyreco.utils_networks.extract_av_in_degree(graph: ndarray | Graph | DiGraph) float[source]
pyreco.utils_networks.extract_av_out_degree(graph: ndarray | Graph | DiGraph) float[source]
pyreco.utils_networks.extract_clustering_coefficient(graph: ndarray | Graph | DiGraph) float[source]
pyreco.utils_networks.extract_density(graph: ndarray | Graph | DiGraph) float[source]

Extract the density of a graph from its adjacency matrix. :param adjacency_matrix: The adjacency matrix of :type adjacency_matrix: np.ndarray, nx.Graph, nx.DiGraph :param the graph.:

Returns:

The density of the graph.

Return type:

float

pyreco.utils_networks.extract_edge_betweenness(graph: ndarray | Graph | DiGraph, edge: tuple) float[source]

Extracts the edge betweenness centrality of an edge.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph containing the edge.

  • edge (tuple) – Edge (u, v) to extract betweenness centrality for.

Returns:

Edge’s betweenness centrality, or 0.0 if edge is not found (e.g. due to a direction mismatch).

Return type:

float

pyreco.utils_networks.extract_edge_in_scc(graph: ndarray | Graph | DiGraph, edge: tuple) int[source]

Check whether an edge’s endpoints lie in the same strongly connected component.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – The graph containing the edge.

  • edge (tuple) – The (u, v) edge to check.

Returns:

1 if both endpoints belong to the same strongly connected component, 0 otherwise.

Return type:

int

pyreco.utils_networks.extract_edge_is_reciprocal(graph: ndarray | Graph | DiGraph, edge: tuple) int[source]

Checks whether an edge is reciprocated.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph containing the edge.

  • edge (tuple) – Edge (u, v) to check.

Returns:

1 if reverse edge (v, u) also exists in graph, 0 otherwise.

Return type:

int

pyreco.utils_networks.extract_edge_source_betweenness(graph: ndarray | Graph | DiGraph, edge: tuple) float[source]

Extracts the node betweenness centrality of an edge’s source node.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph containing the edge.

  • edge (tuple) – Edge (u, v) whose source node’s betweenness centrality is extracted.

Returns:

Betweenness centrality of node u.

Return type:

float

pyreco.utils_networks.extract_edge_source_out_degree(graph: ndarray | Graph | DiGraph, edge: tuple) int[source]

Extracts the out-degree of an edge’s source node.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph containing the edge.

  • edge (tuple) – Edge (u, v) whose source node’s out-degree is extracted.

Returns:

Out-degree of node u.

Return type:

int

pyreco.utils_networks.extract_edge_target_betweenness(graph: ndarray | Graph | DiGraph, edge: tuple) float[source]

Extracts the node betweenness centrality of an edge’s target node.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph containing the edge.

  • edge (tuple) – Edge (u, v) whose target node’s betweenness centrality is extracted.

Returns:

Betweenness centrality of node v.

Return type:

float

pyreco.utils_networks.extract_edge_target_in_degree(graph: ndarray | Graph | DiGraph, edge: tuple) int[source]

Extracts the in-degree of an edge’s target node.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph containing the edge.

  • edge (tuple) – Edge(u, v) whose target node’s in-degree is extracted.

Returns:

In-degree of node v.

Return type:

int

pyreco.utils_networks.extract_edge_weight(graph: ndarray | Graph | DiGraph, edge: tuple) float[source]

Extracts the weight of an edge.

Parameters:
  • graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph containing the edge.

  • edge (tuple) – Edge (u, v) to extract the weight for.

Returns:

Edge weight, or 1.0 if edge has no explicit “weight” attribute.

Return type:

float

pyreco.utils_networks.extract_node_betweenness_centrality(graph: ndarray | Graph | DiGraph, node: int) float[source]
pyreco.utils_networks.extract_node_clustering_coefficient(graph: ndarray | Graph | DiGraph, node: int) float[source]
pyreco.utils_networks.extract_node_degree(graph: ndarray | Graph | DiGraph, node: int) float[source]
pyreco.utils_networks.extract_node_in_degree(graph: ndarray | Graph | DiGraph, node: int) float[source]
pyreco.utils_networks.extract_node_out_degree(graph: ndarray | Graph | DiGraph, node: int) float[source]
pyreco.utils_networks.extract_node_pagerank(graph: ndarray | Graph | DiGraph, node: int) float[source]
pyreco.utils_networks.extract_spectral_radius(graph: ndarray | Graph | DiGraph) float[source]
pyreco.utils_networks.gen_ER_graph(nodes: int, density: float, spec_rad: float = 0.9, directed: bool = True, seed=None)[source]

Generate an Erdős-Rényi random graph with specified properties.

Bug Fix Documentation:

Previous Bug:

The line G.remove_nodes_from(list(nx.isolates(G))) removed isolated nodes from the graph before converting to a numpy array. This caused the final matrix to sometimes be smaller than the specified size (e.g., 29x29 instead of 30x30) when isolated nodes were present. This led to dimension mismatches in reservoir computations where other matrices expected the full size.

Solution:

Instead of removing isolated nodes, we now connect them to maintain the specified network size. This ensures consistency between the reservoir weight matrix and other matrices in the computation.

param nodes:

Number of nodes in the graph

type nodes:

int

param density:

Desired connection density (0 to 1)

type density:

float

param spec_rad:

Desired spectral radius

type spec_rad:

float

param directed:

Whether to create a directed graph

type directed:

bool

param seed:

Random seed for reproducibility

type seed:

int, optional

returns:

Adjacency matrix with shape (nodes, nodes)

rtype:

np.ndarray

pyreco.utils_networks.gen_init_states(num_nodes: int, method: str = 'random')[source]
pyreco.utils_networks.get_num_nodes(network: ndarray) int[source]
pyreco.utils_networks.is_zero_col_and_row(x: ndarray, idx: int) bool[source]
pyreco.utils_networks.precompute_edge_metrics(graph: ndarray | Graph | DiGraph) dict[source]

Precomputes expensive graph-level metrics needed for edge property extraction.

Calls once per graph state and passes the result to ‘EdgeAnalyzer.extract_properties_batch’ to avoid recomputing betweenness centrality and SCC membership for every candidate edge.

Parameters:

graph (np.ndarray, nx.Graph, or nx.DiGraph) – Graph to compute metrics for.

Returns:

Dictionary with keys:

  • ’graph’ : nx.DiGraph

  • ’node_betweenness’ : dict mapping node -> centrality

  • ’edge_betweenness’ : dict mapping (u, v) -> centrality

  • ’scc_map’ : dict mapping node -> strongly connected component id

Return type:

dict

pyreco.utils_networks.remove_nodes_from_graph(graph: ndarray, nodes: list)[source]
pyreco.utils_networks.rename_nodes_after_removal(original_nodes: list, removed_nodes: list)[source]
pyreco.utils_networks.set_spec_rad(network: ndarray, spec_radius: float) ndarray[source]

Module contents