Skip to content

API Reference

This section documents the Python API for rclib. The C++ core is wrapped efficiently to provide a seamless experience.

Reservoirs

rclib.reservoirs

Reservoir configurations.

RandomSparse

Random Sparse Reservoir configuration.

Source code in python/rclib/reservoirs.py
class RandomSparse:
    """Random Sparse Reservoir configuration."""

    def __init__(
        self,
        n_neurons: int,
        spectral_radius: float,
        sparsity: float = 0.1,
        leak_rate: float = 1.0,
        input_scaling: float = 1.0,
        *,
        include_bias: bool = False,
        seed: int = 42,
        spectral_radius_method: str = "power_iteration",
        bias_scaling: float = 1.0,
    ) -> None:
        """Initialize the Random Sparse Reservoir.

        Args:
            n_neurons: Number of neurons in the reservoir.
            spectral_radius: Spectral radius of the reservoir weight matrix.
            sparsity: Sparsity of the reservoir weight matrix (0.0 to 1.0).
            leak_rate: Leaking rate of the neurons.
            input_scaling: Scaling factor for the input weights.
            include_bias: Whether to include a bias term: one constant input per neuron, drawn
                uniformly from [-1, 1] and multiplied by ``bias_scaling``.
            seed: Random seed for weights initialization.
            spectral_radius_method: How the spectral radius of the random weight matrix is
                found before it is scaled to ``spectral_radius``. "power_iteration" (default)
                estimates it by seeded power iteration, typically to within 0.3%. "dense"
                computes it exactly from all eigenvalues of the matrix, which costs
                O(n_neurons^3) time and O(n_neurons^2) memory, so it is meant for small
                reservoirs.
            bias_scaling: Scaling factor for the bias, set apart from ``input_scaling``: the bias
                lies in [-bias_scaling, bias_scaling]. The draws do not depend on it, so the same
                seed gives the same recurrent and input weights at every bias_scaling, and 1
                (default) gives the unscaled bias. Without ``include_bias`` it has no effect.
        """
        _check_random_sparse(
            n_neurons, spectral_radius, sparsity, leak_rate, input_scaling, spectral_radius_method, bias_scaling
        )

        self.n_neurons = n_neurons
        self.spectral_radius = spectral_radius
        self.sparsity = sparsity
        self.leak_rate = leak_rate
        self.input_scaling = input_scaling
        self.include_bias = include_bias
        self.seed = seed
        self.spectral_radius_method = spectral_radius_method
        self.bias_scaling = bias_scaling

__init__(n_neurons, spectral_radius, sparsity=0.1, leak_rate=1.0, input_scaling=1.0, *, include_bias=False, seed=42, spectral_radius_method='power_iteration', bias_scaling=1.0)

Initialize the Random Sparse Reservoir.

Args: n_neurons: Number of neurons in the reservoir. spectral_radius: Spectral radius of the reservoir weight matrix. sparsity: Sparsity of the reservoir weight matrix (0.0 to 1.0). leak_rate: Leaking rate of the neurons. input_scaling: Scaling factor for the input weights. include_bias: Whether to include a bias term: one constant input per neuron, drawn uniformly from [-1, 1] and multiplied by bias_scaling. seed: Random seed for weights initialization. spectral_radius_method: How the spectral radius of the random weight matrix is found before it is scaled to spectral_radius. "power_iteration" (default) estimates it by seeded power iteration, typically to within 0.3%. "dense" computes it exactly from all eigenvalues of the matrix, which costs O(n_neurons^3) time and O(n_neurons^2) memory, so it is meant for small reservoirs. bias_scaling: Scaling factor for the bias, set apart from input_scaling: the bias lies in [-bias_scaling, bias_scaling]. The draws do not depend on it, so the same seed gives the same recurrent and input weights at every bias_scaling, and 1 (default) gives the unscaled bias. Without include_bias it has no effect.

Source code in python/rclib/reservoirs.py
def __init__(
    self,
    n_neurons: int,
    spectral_radius: float,
    sparsity: float = 0.1,
    leak_rate: float = 1.0,
    input_scaling: float = 1.0,
    *,
    include_bias: bool = False,
    seed: int = 42,
    spectral_radius_method: str = "power_iteration",
    bias_scaling: float = 1.0,
) -> None:
    """Initialize the Random Sparse Reservoir.

    Args:
        n_neurons: Number of neurons in the reservoir.
        spectral_radius: Spectral radius of the reservoir weight matrix.
        sparsity: Sparsity of the reservoir weight matrix (0.0 to 1.0).
        leak_rate: Leaking rate of the neurons.
        input_scaling: Scaling factor for the input weights.
        include_bias: Whether to include a bias term: one constant input per neuron, drawn
            uniformly from [-1, 1] and multiplied by ``bias_scaling``.
        seed: Random seed for weights initialization.
        spectral_radius_method: How the spectral radius of the random weight matrix is
            found before it is scaled to ``spectral_radius``. "power_iteration" (default)
            estimates it by seeded power iteration, typically to within 0.3%. "dense"
            computes it exactly from all eigenvalues of the matrix, which costs
            O(n_neurons^3) time and O(n_neurons^2) memory, so it is meant for small
            reservoirs.
        bias_scaling: Scaling factor for the bias, set apart from ``input_scaling``: the bias
            lies in [-bias_scaling, bias_scaling]. The draws do not depend on it, so the same
            seed gives the same recurrent and input weights at every bias_scaling, and 1
            (default) gives the unscaled bias. Without ``include_bias`` it has no effect.
    """
    _check_random_sparse(
        n_neurons, spectral_radius, sparsity, leak_rate, input_scaling, spectral_radius_method, bias_scaling
    )

    self.n_neurons = n_neurons
    self.spectral_radius = spectral_radius
    self.sparsity = sparsity
    self.leak_rate = leak_rate
    self.input_scaling = input_scaling
    self.include_bias = include_bias
    self.seed = seed
    self.spectral_radius_method = spectral_radius_method
    self.bias_scaling = bias_scaling

Nvar

NVAR Reservoir configuration.

Source code in python/rclib/reservoirs.py
class Nvar:
    """NVAR Reservoir configuration."""

    def __init__(self, num_lags: int, polynomial_order: int = 1) -> None:
        """Initialize the NVAR Reservoir.

        Args:
            num_lags: Number of time lags to include.
            polynomial_order: Maximum monomial degree to include. The default
                of 1 preserves a linear delay embedding.
        """
        if num_lags <= 0:
            msg = "num_lags must be positive."
            raise ValueError(msg)
        if polynomial_order <= 0:
            msg = "polynomial_order must be positive."
            raise ValueError(msg)
        if polynomial_order > MAX_POLYNOMIAL_ORDER:
            msg = f"polynomial_order exceeds the supported maximum ({MAX_POLYNOMIAL_ORDER})."
            raise ValueError(msg)

        self.num_lags = num_lags
        self.polynomial_order = polynomial_order

__init__(num_lags, polynomial_order=1)

Initialize the NVAR Reservoir.

Args: num_lags: Number of time lags to include. polynomial_order: Maximum monomial degree to include. The default of 1 preserves a linear delay embedding.

Source code in python/rclib/reservoirs.py
def __init__(self, num_lags: int, polynomial_order: int = 1) -> None:
    """Initialize the NVAR Reservoir.

    Args:
        num_lags: Number of time lags to include.
        polynomial_order: Maximum monomial degree to include. The default
            of 1 preserves a linear delay embedding.
    """
    if num_lags <= 0:
        msg = "num_lags must be positive."
        raise ValueError(msg)
    if polynomial_order <= 0:
        msg = "polynomial_order must be positive."
        raise ValueError(msg)
    if polynomial_order > MAX_POLYNOMIAL_ORDER:
        msg = f"polynomial_order exceeds the supported maximum ({MAX_POLYNOMIAL_ORDER})."
        raise ValueError(msg)

    self.num_lags = num_lags
    self.polynomial_order = polynomial_order

RewardModulated

Reward-modulated reservoir configuration: random sparse recurrence that learns from rewards.

The neurons integrate a potential v and fire at the rate r = tanh(v)::

v = (1 - leak_rate) * v + leak_rate * (u @ W_in + bias + r_prev @ W_res) + noise

where the exploration noise of the rule enters only exploring steps (ESN.act), outside the leak. ESN.reinforce then changes the existing recurrent synapses from the neurons in plastic_presynaptic to those in plastic_postsynaptic. With leak_rate 1 and no noise this is a RandomSparse reservoir with the same weights. A model without a readout returns the rates from ESN.act, so designated neurons can serve as outputs.

Source code in python/rclib/reservoirs.py
class RewardModulated:
    """Reward-modulated reservoir configuration: random sparse recurrence that learns from rewards.

    The neurons integrate a potential ``v`` and fire at the rate ``r = tanh(v)``::

        v = (1 - leak_rate) * v + leak_rate * (u @ W_in + bias + r_prev @ W_res) + noise

    where the exploration noise of the rule enters only exploring steps (``ESN.act``), outside the
    leak. ``ESN.reinforce`` then changes the existing recurrent synapses from the neurons in
    ``plastic_presynaptic`` to those in ``plastic_postsynaptic``. With ``leak_rate`` 1 and no noise
    this is a ``RandomSparse`` reservoir with the same weights. A model without a readout returns
    the rates from ``ESN.act``, so designated neurons can serve as outputs.
    """

    def __init__(
        self,
        n_neurons: int,
        spectral_radius: float,
        sparsity: float = 0.1,
        leak_rate: float = 1.0,
        input_scaling: float = 1.0,
        *,
        rule: RewardModulatedHebbian,
        include_bias: bool = False,
        seed: int = 42,
        spectral_radius_method: str = "power_iteration",
        bias_scaling: float = 1.0,
        plastic_presynaptic: Iterable[int] | None = None,
        plastic_postsynaptic: Iterable[int] | None = None,
    ) -> None:
        """Initialize the reward-modulated reservoir.

        Args:
            n_neurons: Number of neurons in the reservoir.
            spectral_radius: Spectral radius of the initial recurrent weights.
            sparsity: Sparsity of the recurrent weights (0.0 to 1.0); the pattern stays fixed.
            leak_rate: Leak rate of the potential, in (0, 1].
            input_scaling: Scaling factor for the input weights.
            rule: The learning rule, a ``learning.RewardModulatedHebbian``.
            include_bias: Whether to include a bias, as in ``RandomSparse``.
            seed: Random seed for the weights, as in ``RandomSparse``.
            spectral_radius_method: "power_iteration" or "dense", as in ``RandomSparse``.
            bias_scaling: Scaling factor for the bias, as in ``RandomSparse``.
            plastic_presynaptic: Neurons whose outgoing synapses learn; None means all.
            plastic_postsynaptic: Neurons whose incoming synapses learn; None means all.
        """
        _check_random_sparse(
            n_neurons, spectral_radius, sparsity, leak_rate, input_scaling, spectral_radius_method, bias_scaling
        )
        if not isinstance(rule, RewardModulatedHebbian):
            msg = "rule must be a learning.RewardModulatedHebbian."
            raise TypeError(msg)

        self.n_neurons = n_neurons
        self.spectral_radius = spectral_radius
        self.sparsity = sparsity
        self.leak_rate = leak_rate
        self.input_scaling = input_scaling
        self.rule = rule
        self.include_bias = include_bias
        self.seed = seed
        self.spectral_radius_method = spectral_radius_method
        self.bias_scaling = bias_scaling
        self.plastic_presynaptic = _normalize_mask("plastic_presynaptic", plastic_presynaptic, n_neurons)
        self.plastic_postsynaptic = _normalize_mask("plastic_postsynaptic", plastic_postsynaptic, n_neurons)

__init__(n_neurons, spectral_radius, sparsity=0.1, leak_rate=1.0, input_scaling=1.0, *, rule, include_bias=False, seed=42, spectral_radius_method='power_iteration', bias_scaling=1.0, plastic_presynaptic=None, plastic_postsynaptic=None)

Initialize the reward-modulated reservoir.

Args: n_neurons: Number of neurons in the reservoir. spectral_radius: Spectral radius of the initial recurrent weights. sparsity: Sparsity of the recurrent weights (0.0 to 1.0); the pattern stays fixed. leak_rate: Leak rate of the potential, in (0, 1]. input_scaling: Scaling factor for the input weights. rule: The learning rule, a learning.RewardModulatedHebbian. include_bias: Whether to include a bias, as in RandomSparse. seed: Random seed for the weights, as in RandomSparse. spectral_radius_method: "power_iteration" or "dense", as in RandomSparse. bias_scaling: Scaling factor for the bias, as in RandomSparse. plastic_presynaptic: Neurons whose outgoing synapses learn; None means all. plastic_postsynaptic: Neurons whose incoming synapses learn; None means all.

Source code in python/rclib/reservoirs.py
def __init__(
    self,
    n_neurons: int,
    spectral_radius: float,
    sparsity: float = 0.1,
    leak_rate: float = 1.0,
    input_scaling: float = 1.0,
    *,
    rule: RewardModulatedHebbian,
    include_bias: bool = False,
    seed: int = 42,
    spectral_radius_method: str = "power_iteration",
    bias_scaling: float = 1.0,
    plastic_presynaptic: Iterable[int] | None = None,
    plastic_postsynaptic: Iterable[int] | None = None,
) -> None:
    """Initialize the reward-modulated reservoir.

    Args:
        n_neurons: Number of neurons in the reservoir.
        spectral_radius: Spectral radius of the initial recurrent weights.
        sparsity: Sparsity of the recurrent weights (0.0 to 1.0); the pattern stays fixed.
        leak_rate: Leak rate of the potential, in (0, 1].
        input_scaling: Scaling factor for the input weights.
        rule: The learning rule, a ``learning.RewardModulatedHebbian``.
        include_bias: Whether to include a bias, as in ``RandomSparse``.
        seed: Random seed for the weights, as in ``RandomSparse``.
        spectral_radius_method: "power_iteration" or "dense", as in ``RandomSparse``.
        bias_scaling: Scaling factor for the bias, as in ``RandomSparse``.
        plastic_presynaptic: Neurons whose outgoing synapses learn; None means all.
        plastic_postsynaptic: Neurons whose incoming synapses learn; None means all.
    """
    _check_random_sparse(
        n_neurons, spectral_radius, sparsity, leak_rate, input_scaling, spectral_radius_method, bias_scaling
    )
    if not isinstance(rule, RewardModulatedHebbian):
        msg = "rule must be a learning.RewardModulatedHebbian."
        raise TypeError(msg)

    self.n_neurons = n_neurons
    self.spectral_radius = spectral_radius
    self.sparsity = sparsity
    self.leak_rate = leak_rate
    self.input_scaling = input_scaling
    self.rule = rule
    self.include_bias = include_bias
    self.seed = seed
    self.spectral_radius_method = spectral_radius_method
    self.bias_scaling = bias_scaling
    self.plastic_presynaptic = _normalize_mask("plastic_presynaptic", plastic_presynaptic, n_neurons)
    self.plastic_postsynaptic = _normalize_mask("plastic_postsynaptic", plastic_postsynaptic, n_neurons)

Readouts

rclib.readouts

Readout configurations.

Ridge

Ridge Regression Readout configuration.

Source code in python/rclib/readouts.py
class Ridge:
    """Ridge Regression Readout configuration."""

    def __init__(
        self,
        alpha: float,
        *,
        include_bias: bool,
        solver: str = "auto",
        tolerance: float = 1e-10,
    ) -> None:
        """Initialize the Ridge Readout.

        Args:
            alpha: Regularization parameter.
            include_bias: Whether to include a bias term.
            solver: Solver to use ("auto", "cholesky", "dual_cholesky",
                "conjugate_gradient", "conjugate_gradient_implicit").
            tolerance: Convergence tolerance for iterative solvers (CG).
        """
        if not math.isfinite(alpha) or alpha < 0:
            msg = "alpha must be finite and non-negative."
            raise ValueError(msg)
        if not math.isfinite(tolerance) or tolerance <= 0:
            msg = "tolerance must be finite and positive."
            raise ValueError(msg)

        self.alpha = alpha
        self.include_bias = include_bias
        self.solver = solver
        self.tolerance = tolerance

__init__(alpha, *, include_bias, solver='auto', tolerance=1e-10)

Initialize the Ridge Readout.

Args: alpha: Regularization parameter. include_bias: Whether to include a bias term. solver: Solver to use ("auto", "cholesky", "dual_cholesky", "conjugate_gradient", "conjugate_gradient_implicit"). tolerance: Convergence tolerance for iterative solvers (CG).

Source code in python/rclib/readouts.py
def __init__(
    self,
    alpha: float,
    *,
    include_bias: bool,
    solver: str = "auto",
    tolerance: float = 1e-10,
) -> None:
    """Initialize the Ridge Readout.

    Args:
        alpha: Regularization parameter.
        include_bias: Whether to include a bias term.
        solver: Solver to use ("auto", "cholesky", "dual_cholesky",
            "conjugate_gradient", "conjugate_gradient_implicit").
        tolerance: Convergence tolerance for iterative solvers (CG).
    """
    if not math.isfinite(alpha) or alpha < 0:
        msg = "alpha must be finite and non-negative."
        raise ValueError(msg)
    if not math.isfinite(tolerance) or tolerance <= 0:
        msg = "tolerance must be finite and positive."
        raise ValueError(msg)

    self.alpha = alpha
    self.include_bias = include_bias
    self.solver = solver
    self.tolerance = tolerance

Rls

Recursive Least Squares (RLS) Readout configuration.

Source code in python/rclib/readouts.py
class Rls:
    """Recursive Least Squares (RLS) Readout configuration."""

    def __init__(
        self,
        lambda_: float,
        delta: float,
        *,
        include_bias: bool,
        solver: str = "rank1_update",
        forgetting_method: str = "exponential",
    ) -> None:
        """Initialize the RLS Readout.

        Args:
            lambda_: Forgetting factor (0.0 to 1.0).
            delta: Initial value for the covariance matrix diagonal.
            include_bias: Whether to include a bias term.
            solver: Solver type ("rank1_update" or "rank_k_update").
                "rank1_update" is traditional sequential RLS.
                "rank_k_update" is optimized for mini-batches using Woodbury identity.
            forgetting_method: How each sample forgets the old information when
                ``lambda_ < 1`` ("exponential" or "directional"). "exponential"
                discounts it in every direction, so directions that the inputs do
                not excite wind up: the covariance grows there as ``lambda_**-n``
                until the weights are lost. "directional" discounts it only along
                each sample's input, so those directions keep it. At ``lambda_ = 1``
                the two are the same.
        """
        if not 0 < lambda_ <= 1:
            msg = "lambda_ must be in (0, 1]."
            raise ValueError(msg)
        if not math.isfinite(delta) or delta <= 0:
            msg = "delta must be finite and positive."
            raise ValueError(msg)
        if forgetting_method not in {"exponential", "directional"}:
            msg = "forgetting_method must be 'exponential' or 'directional'."
            raise ValueError(msg)

        self.lambda_ = lambda_
        self.delta = delta
        self.include_bias = include_bias
        self.solver = solver
        self.forgetting_method = forgetting_method

__init__(lambda_, delta, *, include_bias, solver='rank1_update', forgetting_method='exponential')

Initialize the RLS Readout.

Args: lambda_: Forgetting factor (0.0 to 1.0). delta: Initial value for the covariance matrix diagonal. include_bias: Whether to include a bias term. solver: Solver type ("rank1_update" or "rank_k_update"). "rank1_update" is traditional sequential RLS. "rank_k_update" is optimized for mini-batches using Woodbury identity. forgetting_method: How each sample forgets the old information when lambda_ < 1 ("exponential" or "directional"). "exponential" discounts it in every direction, so directions that the inputs do not excite wind up: the covariance grows there as lambda_**-n until the weights are lost. "directional" discounts it only along each sample's input, so those directions keep it. At lambda_ = 1 the two are the same.

Source code in python/rclib/readouts.py
def __init__(
    self,
    lambda_: float,
    delta: float,
    *,
    include_bias: bool,
    solver: str = "rank1_update",
    forgetting_method: str = "exponential",
) -> None:
    """Initialize the RLS Readout.

    Args:
        lambda_: Forgetting factor (0.0 to 1.0).
        delta: Initial value for the covariance matrix diagonal.
        include_bias: Whether to include a bias term.
        solver: Solver type ("rank1_update" or "rank_k_update").
            "rank1_update" is traditional sequential RLS.
            "rank_k_update" is optimized for mini-batches using Woodbury identity.
        forgetting_method: How each sample forgets the old information when
            ``lambda_ < 1`` ("exponential" or "directional"). "exponential"
            discounts it in every direction, so directions that the inputs do
            not excite wind up: the covariance grows there as ``lambda_**-n``
            until the weights are lost. "directional" discounts it only along
            each sample's input, so those directions keep it. At ``lambda_ = 1``
            the two are the same.
    """
    if not 0 < lambda_ <= 1:
        msg = "lambda_ must be in (0, 1]."
        raise ValueError(msg)
    if not math.isfinite(delta) or delta <= 0:
        msg = "delta must be finite and positive."
        raise ValueError(msg)
    if forgetting_method not in {"exponential", "directional"}:
        msg = "forgetting_method must be 'exponential' or 'directional'."
        raise ValueError(msg)

    self.lambda_ = lambda_
    self.delta = delta
    self.include_bias = include_bias
    self.solver = solver
    self.forgetting_method = forgetting_method

Lms

Least Mean Squares (LMS) Readout configuration.

Source code in python/rclib/readouts.py
class Lms:
    """Least Mean Squares (LMS) Readout configuration."""

    def __init__(self, learning_rate: float, *, include_bias: bool) -> None:
        """Initialize the LMS Readout.

        Args:
            learning_rate: Learning rate for the LMS algorithm.
            include_bias: Whether to include a bias term.
        """
        if not math.isfinite(learning_rate) or learning_rate <= 0:
            msg = "learning_rate must be finite and positive."
            raise ValueError(msg)

        self.learning_rate = learning_rate
        self.include_bias = include_bias

__init__(learning_rate, *, include_bias)

Initialize the LMS Readout.

Args: learning_rate: Learning rate for the LMS algorithm. include_bias: Whether to include a bias term.

Source code in python/rclib/readouts.py
def __init__(self, learning_rate: float, *, include_bias: bool) -> None:
    """Initialize the LMS Readout.

    Args:
        learning_rate: Learning rate for the LMS algorithm.
        include_bias: Whether to include a bias term.
    """
    if not math.isfinite(learning_rate) or learning_rate <= 0:
        msg = "learning_rate must be finite and positive."
        raise ValueError(msg)

    self.learning_rate = learning_rate
    self.include_bias = include_bias

RewardModulated

Reward-modulated readout configuration: a linear readout that learns from rewards.

The output is x @ W (plus a bias row) and, while exploring, the exploration noise of the rule. ESN.act explores and records the eligibility, and ESN.reinforce changes W. The weights start at zero at the first act; get_readout().setWeights can set them first. ESN.fit and ESN.partial_fit do not apply to this readout.

Source code in python/rclib/readouts.py
class RewardModulated:
    """Reward-modulated readout configuration: a linear readout that learns from rewards.

    The output is ``x @ W`` (plus a bias row) and, while exploring, the exploration noise of the
    rule. ``ESN.act`` explores and records the eligibility, and ``ESN.reinforce`` changes ``W``.
    The weights start at zero at the first ``act``; ``get_readout().setWeights`` can set them
    first. ``ESN.fit`` and ``ESN.partial_fit`` do not apply to this readout.
    """

    def __init__(self, n_outputs: int, rule: RewardModulatedHebbian, *, include_bias: bool) -> None:
        """Initialize the reward-modulated readout.

        Args:
            n_outputs: Number of outputs.
            rule: The learning rule, a ``learning.RewardModulatedHebbian``.
            include_bias: Whether to include a bias term, a constant input of 1 with a plastic weight.
        """
        if n_outputs <= 0:
            msg = "n_outputs must be positive."
            raise ValueError(msg)
        if not isinstance(rule, RewardModulatedHebbian):
            msg = "rule must be a learning.RewardModulatedHebbian."
            raise TypeError(msg)

        self.n_outputs = n_outputs
        self.rule = rule
        self.include_bias = include_bias

__init__(n_outputs, rule, *, include_bias)

Initialize the reward-modulated readout.

Args: n_outputs: Number of outputs. rule: The learning rule, a learning.RewardModulatedHebbian. include_bias: Whether to include a bias term, a constant input of 1 with a plastic weight.

Source code in python/rclib/readouts.py
def __init__(self, n_outputs: int, rule: RewardModulatedHebbian, *, include_bias: bool) -> None:
    """Initialize the reward-modulated readout.

    Args:
        n_outputs: Number of outputs.
        rule: The learning rule, a ``learning.RewardModulatedHebbian``.
        include_bias: Whether to include a bias term, a constant input of 1 with a plastic weight.
    """
    if n_outputs <= 0:
        msg = "n_outputs must be positive."
        raise ValueError(msg)
    if not isinstance(rule, RewardModulatedHebbian):
        msg = "rule must be a learning.RewardModulatedHebbian."
        raise TypeError(msg)

    self.n_outputs = n_outputs
    self.rule = rule
    self.include_bias = include_bias

Learning from Rewards

rclib.learning

Configurations of reward-modulated Hebbian learning.

A reward-modulated component (readouts.RewardModulated) adds exploration noise to the potentials of its post-synaptic units, correlates pre-synaptic activity with a post-synaptic signal into an eligibility, and changes its weights in proportion to the eligibility and a modulator derived from the reward. In the row-vector convention of rclib, with the weights of shape (n_pre, n_post)::

S(y)  = sign(y) * |y| ** eligibility_power
e     = trace_decay * e + S(pre).T @ S(post)        (update="online", every exploring row)
E     = E + S(pre).T @ S(post)                       (update="trial", cleared by each update)
dW    = eta * m * e,  eta * m * E,  or  eta * m * inv(C + decorrelation * I) @ E
m     = R - R_avg  ("difference")  or  1 if R > R_avg else 0  ("heaviside")

where post is the injected noise, the potential minus its average before the row ("high_pass"), or the potential itself, C sums pre.T @ pre over the trial, and R_avg is the reward baseline of the reward's key before that reward. The presets :func:legenstein2010, :func:hoerzer2014, :func:miconi2017 and :func:burms2015 give the settings of four published variants.

RewardModulatedHebbian dataclass

A reward-modulated Hebbian rule.

Attributes:

Name Type Description
learning_rate float

Learning rate eta at the first update.

exploration Exploration

The exploration noise.

post str

Post-synaptic signal: "noise" (the injected noise, node perturbation), "high_pass" (the potential minus its average before the row) or "potential".

post_decay float

Decay in [0, 1) of the potential's average for "high_pass"; 0 makes the signal the first difference of the potential.

eligibility_power float

Exponent p > 0 of S(y) = sign(y) |y|^p: 1 is linear, 3 the supralinear cube.

update str

"online": the eligibility decays by trace_decay every exploring row and each update uses it; "trial": the eligibility sums the rows of a trial, and each update uses and clears it.

trace_decay float

Decay in [0, 1] of the online eligibility; must be 0 with update="trial".

modulator str

"difference" (R - R_avg) or "heaviside" (1 if R > R_avg, else 0).

baseline Baseline

The reward baseline.

learning_rate_decay_steps (float, optional)

T in eta_n = learning_rate / (1 + n / T), n the number of updates so far.

max_update (float, optional)

Clip of each weight change to [-max_update, max_update].

decorrelation (float, optional)

Ridge term lambda > 0 of the decorrelated update inv(C + lambda I) @ E; requires update="trial" and an eligibility_power of 1.

Source code in python/rclib/learning.py
@dataclass(frozen=True, kw_only=True)
class RewardModulatedHebbian:
    """A reward-modulated Hebbian rule.

    Attributes
    ----------
    learning_rate : float
        Learning rate ``eta`` at the first update.
    exploration : Exploration
        The exploration noise.
    post : str
        Post-synaptic signal: ``"noise"`` (the injected noise, node perturbation),
        ``"high_pass"`` (the potential minus its average before the row) or ``"potential"``.
    post_decay : float
        Decay in ``[0, 1)`` of the potential's average for ``"high_pass"``; 0 makes the signal
        the first difference of the potential.
    eligibility_power : float
        Exponent ``p > 0`` of ``S(y) = sign(y) |y|^p``: 1 is linear, 3 the supralinear cube.
    update : str
        ``"online"``: the eligibility decays by ``trace_decay`` every exploring row and each
        update uses it; ``"trial"``: the eligibility sums the rows of a trial, and each update uses
        and clears it.
    trace_decay : float
        Decay in ``[0, 1]`` of the online eligibility; must be 0 with ``update="trial"``.
    modulator : str
        ``"difference"`` (``R - R_avg``) or ``"heaviside"`` (1 if ``R > R_avg``, else 0).
    baseline : Baseline
        The reward baseline.
    learning_rate_decay_steps : float, optional
        ``T`` in ``eta_n = learning_rate / (1 + n / T)``, ``n`` the number of updates so far.
    max_update : float, optional
        Clip of each weight change to ``[-max_update, max_update]``.
    decorrelation : float, optional
        Ridge term ``lambda > 0`` of the decorrelated update ``inv(C + lambda I) @ E``; requires
        ``update="trial"`` and an ``eligibility_power`` of 1.
    """

    learning_rate: float
    exploration: Exploration = field(default_factory=Exploration)
    post: str = "high_pass"
    post_decay: float = 0.0
    eligibility_power: float = 1.0
    update: str = "online"
    trace_decay: float = 0.0
    modulator: str = "difference"
    baseline: Baseline = field(default_factory=Baseline)
    learning_rate_decay_steps: float | None = None
    max_update: float | None = None
    decorrelation: float | None = None

    def __post_init__(self) -> None:
        """Validate the settings.

        Raises
        ------
        ValueError
            If a setting is out of range or settings conflict.
        TypeError
            If ``exploration`` or ``baseline`` has the wrong type.
        """
        _check_positive("learning_rate", self.learning_rate)
        if not isinstance(self.exploration, Exploration):
            msg = "exploration must be an Exploration."
            raise TypeError(msg)
        if not isinstance(self.baseline, Baseline):
            msg = "baseline must be a Baseline."
            raise TypeError(msg)
        if self.post not in {"noise", "high_pass", "potential"}:
            msg = "post must be 'noise', 'high_pass' or 'potential'."
            raise ValueError(msg)
        _check_unit_interval("post_decay", self.post_decay, include_one=False)
        _check_positive("eligibility_power", self.eligibility_power)
        if self.update not in {"online", "trial"}:
            msg = "update must be 'online' or 'trial'."
            raise ValueError(msg)
        _check_unit_interval("trace_decay", self.trace_decay, include_one=True)
        if self.update == "trial" and self.trace_decay != 0:
            msg = "trace_decay applies to online updates only; trial eligibility never decays."
            raise ValueError(msg)
        if self.modulator not in {"difference", "heaviside"}:
            msg = "modulator must be 'difference' or 'heaviside'."
            raise ValueError(msg)
        _check_positive("learning_rate_decay_steps", self.learning_rate_decay_steps, optional=True)
        _check_positive("max_update", self.max_update, optional=True)
        _check_positive("decorrelation", self.decorrelation, optional=True)
        if self.decorrelation is not None and self.update != "trial":
            msg = "decorrelation requires trial updates."
            raise ValueError(msg)
        if self.decorrelation is not None and self.eligibility_power != 1:
            msg = "decorrelation requires an eligibility_power of 1."
            raise ValueError(msg)

__post_init__()

Validate the settings.

Raises:

Type Description
ValueError

If a setting is out of range or settings conflict.

TypeError

If exploration or baseline has the wrong type.

Source code in python/rclib/learning.py
def __post_init__(self) -> None:
    """Validate the settings.

    Raises
    ------
    ValueError
        If a setting is out of range or settings conflict.
    TypeError
        If ``exploration`` or ``baseline`` has the wrong type.
    """
    _check_positive("learning_rate", self.learning_rate)
    if not isinstance(self.exploration, Exploration):
        msg = "exploration must be an Exploration."
        raise TypeError(msg)
    if not isinstance(self.baseline, Baseline):
        msg = "baseline must be a Baseline."
        raise TypeError(msg)
    if self.post not in {"noise", "high_pass", "potential"}:
        msg = "post must be 'noise', 'high_pass' or 'potential'."
        raise ValueError(msg)
    _check_unit_interval("post_decay", self.post_decay, include_one=False)
    _check_positive("eligibility_power", self.eligibility_power)
    if self.update not in {"online", "trial"}:
        msg = "update must be 'online' or 'trial'."
        raise ValueError(msg)
    _check_unit_interval("trace_decay", self.trace_decay, include_one=True)
    if self.update == "trial" and self.trace_decay != 0:
        msg = "trace_decay applies to online updates only; trial eligibility never decays."
        raise ValueError(msg)
    if self.modulator not in {"difference", "heaviside"}:
        msg = "modulator must be 'difference' or 'heaviside'."
        raise ValueError(msg)
    _check_positive("learning_rate_decay_steps", self.learning_rate_decay_steps, optional=True)
    _check_positive("max_update", self.max_update, optional=True)
    _check_positive("decorrelation", self.decorrelation, optional=True)
    if self.decorrelation is not None and self.update != "trial":
        msg = "decorrelation requires trial updates."
        raise ValueError(msg)
    if self.decorrelation is not None and self.eligibility_power != 1:
        msg = "decorrelation requires an eligibility_power of 1."
        raise ValueError(msg)

Exploration dataclass

Exploration noise added to the potentials of the post-synaptic units.

Attributes:

Name Type Description
distribution str

"uniform" on [-amplitude, amplitude] or "gaussian" with standard deviation amplitude.

amplitude float

Scale of the noise. With 0 nothing is perturbed: a rule whose post-synaptic signal is the noise then learns nothing, but "high_pass" and "potential" signals still change the weights when the inputs change. To step without recording eligibility at all, use ESN.act(x, explore=False).

probability float

Probability in (0, 1] that a unit is perturbed in a row; 1 perturbs every unit in every row, and small values give sparse kicks.

seed int

Seed of the noise in [0, 2**32 - 1]. Components that share a rule draw separate noise.

Source code in python/rclib/learning.py
@dataclass(frozen=True, kw_only=True)
class Exploration:
    """Exploration noise added to the potentials of the post-synaptic units.

    Attributes
    ----------
    distribution : str
        ``"uniform"`` on ``[-amplitude, amplitude]`` or ``"gaussian"`` with standard deviation
        ``amplitude``.
    amplitude : float
        Scale of the noise. With 0 nothing is perturbed: a rule whose post-synaptic signal is the
        noise then learns nothing, but ``"high_pass"`` and ``"potential"`` signals still change
        the weights when the inputs change. To step without recording eligibility at all, use
        ``ESN.act(x, explore=False)``.
    probability : float
        Probability in ``(0, 1]`` that a unit is perturbed in a row; 1 perturbs every unit in
        every row, and small values give sparse kicks.
    seed : int
        Seed of the noise in ``[0, 2**32 - 1]``. Components that share a rule draw separate noise.
    """

    distribution: str = "uniform"
    amplitude: float = 0.1
    probability: float = 1.0
    seed: int = 0

    def __post_init__(self) -> None:
        """Validate the settings.

        Raises
        ------
        ValueError
            If a setting is out of range.
        """
        if self.distribution not in {"uniform", "gaussian"}:
            msg = "distribution must be 'uniform' or 'gaussian'."
            raise ValueError(msg)
        if not math.isfinite(self.amplitude) or self.amplitude < 0:
            msg = "amplitude must be finite and non-negative."
            raise ValueError(msg)
        if not 0 < self.probability <= 1:
            msg = "probability must be in (0, 1]."
            raise ValueError(msg)
        if not 0 <= self.seed <= MAX_SEED:
            msg = f"seed must be in [0, {MAX_SEED}]."
            raise ValueError(msg)

__post_init__()

Validate the settings.

Raises:

Type Description
ValueError

If a setting is out of range.

Source code in python/rclib/learning.py
def __post_init__(self) -> None:
    """Validate the settings.

    Raises
    ------
    ValueError
        If a setting is out of range.
    """
    if self.distribution not in {"uniform", "gaussian"}:
        msg = "distribution must be 'uniform' or 'gaussian'."
        raise ValueError(msg)
    if not math.isfinite(self.amplitude) or self.amplitude < 0:
        msg = "amplitude must be finite and non-negative."
        raise ValueError(msg)
    if not 0 < self.probability <= 1:
        msg = "probability must be in (0, 1]."
        raise ValueError(msg)
    if not 0 <= self.seed <= MAX_SEED:
        msg = f"seed must be in [0, {MAX_SEED}]."
        raise ValueError(msg)

Baseline dataclass

The reward baseline R_avg a reward is compared with, kept per integer key.

The first reward of a key with an "ema" or "window" baseline becomes its own baseline, so its modulator is zero.

Attributes:

Name Type Description
kind str

"ema": R_avg = decay * R_avg + (1 - decay) * R after each reward; "window": the mean of the last window rewards; "none": 0, so the modulator uses the reward itself.

decay float

Decay in [0, 1) of the "ema" baseline.

window int

Number of rewards in [1, 1000000] the "window" baseline averages.

Source code in python/rclib/learning.py
@dataclass(frozen=True, kw_only=True)
class Baseline:
    """The reward baseline ``R_avg`` a reward is compared with, kept per integer key.

    The first reward of a key with an ``"ema"`` or ``"window"`` baseline becomes its own baseline,
    so its modulator is zero.

    Attributes
    ----------
    kind : str
        ``"ema"``: ``R_avg = decay * R_avg + (1 - decay) * R`` after each reward; ``"window"``: the
        mean of the last ``window`` rewards; ``"none"``: 0, so the modulator uses the reward itself.
    decay : float
        Decay in ``[0, 1)`` of the ``"ema"`` baseline.
    window : int
        Number of rewards in ``[1, 1000000]`` the ``"window"`` baseline averages.
    """

    kind: str = "ema"
    decay: float = 0.8
    window: int = 50

    def __post_init__(self) -> None:
        """Validate the settings.

        Raises
        ------
        ValueError
            If a setting is out of range.
        """
        if self.kind not in {"ema", "window", "none"}:
            msg = "kind must be 'ema', 'window' or 'none'."
            raise ValueError(msg)
        _check_unit_interval("decay", self.decay, include_one=False)
        if not 1 <= self.window <= MAX_BASELINE_WINDOW:
            msg = f"window must be in [1, {MAX_BASELINE_WINDOW}]."
            raise ValueError(msg)

__post_init__()

Validate the settings.

Raises:

Type Description
ValueError

If a setting is out of range.

Source code in python/rclib/learning.py
def __post_init__(self) -> None:
    """Validate the settings.

    Raises
    ------
    ValueError
        If a setting is out of range.
    """
    if self.kind not in {"ema", "window", "none"}:
        msg = "kind must be 'ema', 'window' or 'none'."
        raise ValueError(msg)
    _check_unit_interval("decay", self.decay, include_one=False)
    if not 1 <= self.window <= MAX_BASELINE_WINDOW:
        msg = f"window must be in [1, {MAX_BASELINE_WINDOW}]."
        raise ValueError(msg)

legenstein2010(learning_rate, **overrides)

The exploratory Hebbian (EH) rule of Legenstein et al. (2010).

Every unit's potential gets uniform noise in every row; the post-synaptic signal is the potential minus its exponential average (post_decay 0.8), and the modulator is the reward minus its exponential average (decay 0.8). The weights change at every rewarded row.

Parameters:

Name Type Description Default
learning_rate float

The learning rate.

required
**overrides Any

Settings of :class:RewardModulatedHebbian to replace.

{}

Returns:

Type Description
RewardModulatedHebbian

The rule.

References

Legenstein, R., Chase, S. M., Schwartz, A. B., & Maass, W. (2010). A reward-modulated Hebbian learning rule can explain experimentally observed network reorganization in a brain control task. The Journal of Neuroscience, 30(25), 8400-8410.

Source code in python/rclib/learning.py
def legenstein2010(learning_rate: float, **overrides: Any) -> RewardModulatedHebbian:  # noqa: ANN401
    """The exploratory Hebbian (EH) rule of Legenstein et al. (2010).

    Every unit's potential gets uniform noise in every row; the post-synaptic signal is the
    potential minus its exponential average (``post_decay`` 0.8), and the modulator is the reward
    minus its exponential average (decay 0.8). The weights change at every rewarded row.

    Parameters
    ----------
    learning_rate : float
        The learning rate.
    **overrides : Any
        Settings of :class:`RewardModulatedHebbian` to replace.

    Returns
    -------
    RewardModulatedHebbian
        The rule.

    References
    ----------
    Legenstein, R., Chase, S. M., Schwartz, A. B., & Maass, W. (2010). A reward-modulated Hebbian
    learning rule can explain experimentally observed network reorganization in a brain control
    task. The Journal of Neuroscience, 30(25), 8400-8410.
    """
    rule = RewardModulatedHebbian(
        learning_rate=learning_rate,
        exploration=Exploration(distribution="uniform", amplitude=0.1),
        post="high_pass",
        post_decay=0.8,
        update="online",
        modulator="difference",
        baseline=Baseline(kind="ema", decay=0.8),
    )
    return dataclasses.replace(rule, **overrides)

hoerzer2014(learning_rate, **overrides)

The EH rule with a binary modulator of Hoerzer et al. (2014).

Meant for a readout whose noisy output is fed back into a chaotic reservoir. The output gets uniform noise in every row, the post-synaptic signal is its first difference (post_decay 0), and the weights change only when the reward beats its exponential average (decay 0.8): the modulator is 1 or 0. Hoerzer et al. let the learning rate decay over training; set learning_rate_decay_steps to do the same.

Parameters:

Name Type Description Default
learning_rate float

The learning rate.

required
**overrides Any

Settings of :class:RewardModulatedHebbian to replace.

{}

Returns:

Type Description
RewardModulatedHebbian

The rule.

References

Hoerzer, G. M., Legenstein, R., & Maass, W. (2014). Emergence of complex computational structures from chaotic neural networks through reward-modulated Hebbian learning. Cerebral Cortex, 24(3), 677-690.

Source code in python/rclib/learning.py
def hoerzer2014(learning_rate: float, **overrides: Any) -> RewardModulatedHebbian:  # noqa: ANN401
    """The EH rule with a binary modulator of Hoerzer et al. (2014).

    Meant for a readout whose noisy output is fed back into a chaotic reservoir. The output gets
    uniform noise in every row, the post-synaptic signal is its first difference (``post_decay``
    0), and the weights change only when the reward beats its exponential average (decay 0.8):
    the modulator is 1 or 0. Hoerzer et al. let the learning rate decay over training; set
    ``learning_rate_decay_steps`` to do the same.

    Parameters
    ----------
    learning_rate : float
        The learning rate.
    **overrides : Any
        Settings of :class:`RewardModulatedHebbian` to replace.

    Returns
    -------
    RewardModulatedHebbian
        The rule.

    References
    ----------
    Hoerzer, G. M., Legenstein, R., & Maass, W. (2014). Emergence of complex computational
    structures from chaotic neural networks through reward-modulated Hebbian learning. Cerebral
    Cortex, 24(3), 677-690.
    """
    rule = RewardModulatedHebbian(
        learning_rate=learning_rate,
        exploration=Exploration(distribution="uniform", amplitude=0.2),
        post="high_pass",
        post_decay=0.0,
        update="online",
        modulator="heaviside",
        baseline=Baseline(kind="ema", decay=0.8),
    )
    return dataclasses.replace(rule, **overrides)

miconi2017(learning_rate, **overrides)

The rule of Miconi (2017) for recurrent weights learning from a delayed reward.

Each neuron's potential gets a sparse uniform kick (probability 0.003, amplitude 0.5 per row). The eligibility sums the cube of the Hebbian product of the previous rate and the potential minus its fast average over the trial; the cube keeps the large products of the kicks and suppresses the small ones of the network's relaxation. One update per trial uses the reward minus its exponential average for the trial's key (decay 0.33), clipped to 1e-4 per weight. Use it with reservoirs.RewardModulated, whose potential-leak dynamics it assumes.

Parameters:

Name Type Description Default
learning_rate float

The learning rate.

required
**overrides Any

Settings of :class:RewardModulatedHebbian to replace.

{}

Returns:

Type Description
RewardModulatedHebbian

The rule.

References

Miconi, T. (2017). Biologically plausible learning in recurrent neural networks reproduces neural dynamics observed during cognitive tasks. eLife, 6, e20899.

Source code in python/rclib/learning.py
def miconi2017(learning_rate: float, **overrides: Any) -> RewardModulatedHebbian:  # noqa: ANN401
    """The rule of Miconi (2017) for recurrent weights learning from a delayed reward.

    Each neuron's potential gets a sparse uniform kick (probability 0.003, amplitude 0.5 per row).
    The eligibility sums the cube of the Hebbian product of the previous rate and the potential
    minus its fast average over the trial; the cube keeps the large products of the kicks and
    suppresses the small ones of the network's relaxation. One update per trial uses the reward
    minus its exponential average for the trial's key (decay 0.33), clipped to 1e-4 per weight.
    Use it with ``reservoirs.RewardModulated``, whose potential-leak dynamics it assumes.

    Parameters
    ----------
    learning_rate : float
        The learning rate.
    **overrides : Any
        Settings of :class:`RewardModulatedHebbian` to replace.

    Returns
    -------
    RewardModulatedHebbian
        The rule.

    References
    ----------
    Miconi, T. (2017). Biologically plausible learning in recurrent neural networks reproduces
    neural dynamics observed during cognitive tasks. eLife, 6, e20899.
    """
    rule = RewardModulatedHebbian(
        learning_rate=learning_rate,
        exploration=Exploration(distribution="uniform", amplitude=0.5, probability=0.003),
        post="high_pass",
        post_decay=0.05,
        eligibility_power=3.0,
        update="trial",
        modulator="difference",
        baseline=Baseline(kind="ema", decay=0.33),
        max_update=1e-4,
    )
    return dataclasses.replace(rule, **overrides)

burms2015(learning_rate, **overrides)

The decorrelated trial rule of Burms et al. (2015).

Every unit gets Gaussian noise (standard deviation 0.05) in every row, and the eligibility correlates the pre-synaptic activity with this known noise over the trial. One update per trial uses inv(C + I) @ E, which decorrelates correlated pre-synaptic activity such as redundant sensors, and the reward minus the mean of the last 50 rewards of the trial's key. Pass modulator="heaviside" for the variant that learns only from better-than-expected trials.

Parameters:

Name Type Description Default
learning_rate float

The learning rate.

required
**overrides Any

Settings of :class:RewardModulatedHebbian to replace.

{}

Returns:

Type Description
RewardModulatedHebbian

The rule.

References

Burms, J., Caluwaerts, K., & Dambre, J. (2015). Reward-modulated Hebbian plasticity as leverage for partially embodied control in compliant robotics. Frontiers in Neurorobotics, 9, 9.

Source code in python/rclib/learning.py
def burms2015(learning_rate: float, **overrides: Any) -> RewardModulatedHebbian:  # noqa: ANN401
    """The decorrelated trial rule of Burms et al. (2015).

    Every unit gets Gaussian noise (standard deviation 0.05) in every row, and the eligibility
    correlates the pre-synaptic activity with this known noise over the trial. One update per trial
    uses ``inv(C + I) @ E``, which decorrelates correlated pre-synaptic activity such as redundant
    sensors, and the reward minus the mean of the last 50 rewards of the trial's key. Pass
    ``modulator="heaviside"`` for the variant that learns only from better-than-expected trials.

    Parameters
    ----------
    learning_rate : float
        The learning rate.
    **overrides : Any
        Settings of :class:`RewardModulatedHebbian` to replace.

    Returns
    -------
    RewardModulatedHebbian
        The rule.

    References
    ----------
    Burms, J., Caluwaerts, K., & Dambre, J. (2015). Reward-modulated Hebbian plasticity as leverage
    for partially embodied control in compliant robotics. Frontiers in Neurorobotics, 9, 9.
    """
    rule = RewardModulatedHebbian(
        learning_rate=learning_rate,
        exploration=Exploration(distribution="gaussian", amplitude=0.05),
        post="noise",
        update="trial",
        modulator="difference",
        baseline=Baseline(kind="window", window=50),
        decorrelation=1.0,
    )
    return dataclasses.replace(rule, **overrides)

Model

rclib.model

Model module for Reservoir Computing.

ESN

Echo State Network (ESN) model.

Source code in python/rclib/model.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
class ESN:
    """Echo State Network (ESN) model."""

    def __init__(self, connection_type: str = "serial") -> None:
        """Initialize the ESN model.

        Parameters
        ----------
        connection_type : str, optional
            The type of connection between reservoirs ("serial" or "parallel").
            Default is "serial".
        """
        if connection_type not in {"serial", "parallel"}:
            msg = "connection_type must be 'serial' or 'parallel'."
            raise ValueError(msg)

        self.connection_type = connection_type
        self._reservoirs_params: list[Any] = []  # Store parameters for Python-side reservoir objects
        self._readout_params: Any = None  # Store parameters for Python-side readout object
        self._cpp_model = _rclib.Model()  # Initialize the C++ Model object

    def add_reservoir(self, reservoir: Any) -> None:  # noqa: ANN401
        """Add a reservoir to the model.

        Parameters
        ----------
        reservoir : Any
            The reservoir object to add.

        Raises
        ------
        TypeError
            If the reservoir type is unsupported.
        ValueError
            If a RandomSparse reservoir has an unsupported spectral_radius_method.
        """
        # Create and add the C++ reservoir to the C++ model
        if isinstance(reservoir, reservoirs.RandomSparse):
            if reservoir.spectral_radius_method not in _SPECTRAL_RADIUS_METHODS:
                msg = f"Unsupported spectral_radius_method: {reservoir.spectral_radius_method}"
                raise ValueError(msg)
            cpp_res = _rclib.RandomSparseReservoir(
                reservoir.n_neurons,
                reservoir.spectral_radius,
                reservoir.sparsity,
                reservoir.leak_rate,
                reservoir.input_scaling,
                reservoir.include_bias,
                reservoir.seed,
                _SPECTRAL_RADIUS_METHODS[reservoir.spectral_radius_method],
                reservoir.bias_scaling,
            )
            self._cpp_model.addReservoir(cpp_res, self.connection_type)
        elif isinstance(reservoir, reservoirs.Nvar):
            cpp_res = _rclib.NvarReservoir(reservoir.num_lags, reservoir.polynomial_order)
            self._cpp_model.addReservoir(cpp_res, self.connection_type)
        elif isinstance(reservoir, reservoirs.RewardModulated):
            cpp_res = _rclib.RewardModulatedReservoir(
                reservoir.n_neurons,
                reservoir.spectral_radius,
                reservoir.sparsity,
                reservoir.leak_rate,
                reservoir.input_scaling,
                reservoir.include_bias,
                reservoir.seed,
                _SPECTRAL_RADIUS_METHODS[reservoir.spectral_radius_method],
                reservoir.bias_scaling,
                _rule_to_cpp(reservoir.rule),
                reservoir.plastic_presynaptic,
                reservoir.plastic_postsynaptic,
            )
            self._cpp_model.addReservoir(cpp_res, self.connection_type)
        # Add other reservoir types here as they are implemented
        else:
            msg = "Unsupported reservoir type"
            raise TypeError(msg)

        # Store the Python reservoir object's parameters only once the C++ model holds the
        # reservoir, so a rejected reservoir leaves both sides unchanged.
        self._reservoirs_params.append(reservoir)

        # Update readout in case it's using "auto" solver
        self._update_readout()

    def set_readout(self, readout: Any) -> None:  # noqa: ANN401
        """Set the readout for the model.

        Parameters
        ----------
        readout : Any
            The readout object to set.

        Raises
        ------
        TypeError
            If the readout type is unsupported.
        """
        # Build the C++ readout first and record the configuration only once the C++ model
        # holds it, so a rejected readout leaves both sides unchanged and a second call
        # replaces the readout set before.
        self._cpp_model.setReadout(_cpp_readout_from_config(readout))
        self._readout_params = readout

    def _update_readout(self) -> None:
        """Create the C++ readout from the stored configuration if the C++ model has none."""
        if self._readout_params is None:
            return

        # An existing readout is kept, so its fitted or online learning state survives.
        try:
            if self._cpp_model.getReadout() is not None:
                return
        except RuntimeError:
            # getReadout() throws if not set
            pass

        self._cpp_model.setReadout(_cpp_readout_from_config(self._readout_params))

    def fit(self, x: ArrayLike, y: ArrayLike, washout_len: int = 0) -> None:
        """Fit the model to the data.

        Parameters
        ----------
        x : ArrayLike
            Input data.
        y : ArrayLike
            Target data.
        washout_len : int, optional
            Number of initial samples to discard. Default is 0.
        """
        # Ensure readout is correctly initialized (especially for "auto" solver)
        self._update_readout()
        # Call the C++ model's fit method
        self._cpp_model.fit(x, y, washout_len)

    def fit_sequences(self, inputs: Sequence[ArrayLike], targets: Sequence[ArrayLike], washout_len: int = 0) -> None:
        """Fit the readout once on several independent sequences, such as episodes.

        Each sequence starts from reset reservoirs and discards its own first
        ``washout_len`` samples. The remaining reservoir states and targets of all
        sequences are stacked and the readout is fitted once, so nothing carries over
        from one sequence to the next. With a single sequence this equals :meth:`fit`.

        Parameters
        ----------
        inputs : Sequence[ArrayLike]
            Input data, one 2-D array of shape (n_samples_i, n_inputs) per sequence,
            for example a list of arrays. Sequences may differ in length but not in
            width.
        targets : Sequence[ArrayLike]
            Target data, one 2-D array of shape (n_samples_i, n_outputs) per sequence,
            with as many rows as the matching input sequence.
        washout_len : int, optional
            Number of initial samples to discard from each sequence. Default is 0.

        Raises
        ------
        ValueError
            If a single 2-D array is passed instead of a sequence of arrays, if there
            are no sequences or unequal numbers of input and target sequences, or if a
            sequence is empty, its inputs and targets differ in length, its width
            differs from the first sequence's, or its input width differs from the one
            the reservoirs are locked to by earlier input. Messages name the sequence
            index.
        IndexError
            If ``washout_len`` is negative or not shorter than a sequence.
        RuntimeError
            If the model has no reservoir or no readout.

        Notes
        -----
        These checks run before the model changes. Afterwards the reservoirs hold
        their states at the end of the last sequence.
        """
        # A single 2-D array would otherwise be split into one-row sequences.
        for name, sequences in (("inputs", inputs), ("targets", targets)):
            if isinstance(sequences, np.ndarray) and sequences.ndim == 2:  # noqa: PLR2004
                msg = f"{name} must be a sequence of 2-D arrays, one per sequence, not a single 2-D array."
                raise ValueError(msg)
        self._update_readout()
        self._cpp_model.fitSequences(inputs, targets, washout_len)

    def predict(self, x: ArrayLike, *, reset_state_before_predict: bool = True) -> np.ndarray:
        """Predict using the trained model.

        Parameters
        ----------
        x : ArrayLike
            Input data.
        reset_state_before_predict : bool, optional
            Whether to reset the reservoir state before prediction. Default is True.

        Returns
        -------
        np.ndarray
            The predicted values.
        """
        # Call the C++ model's predict method
        return self._cpp_model.predict(x, reset_state_before_predict)

    def predict_online(self, x: ArrayLike) -> np.ndarray:
        """Predict in online mode (updating state).

        Parameters
        ----------
        x : ArrayLike
            Input data.

        Returns
        -------
        np.ndarray
            The predicted values.
        """
        # Call the C++ model's predictOnline method
        return self._cpp_model.predictOnline(x)

    def predict_generative(self, prime_data: ArrayLike, n_steps: int) -> np.ndarray:
        """Generative prediction.

        Advances the reservoirs through ``prime_data`` (if any), then generates
        ``n_steps`` outputs, feeding each output back as the next input. Every
        generated output, including the last, advances the reservoirs, so a following
        call with empty ``prime_data`` continues the sequence: generating ``a`` steps
        and then ``b`` steps equals generating ``a + b`` steps. With ``n_steps == 0``
        no output is fed back.

        Parameters
        ----------
        prime_data : ArrayLike
            Initial data to prime the reservoir.
        n_steps : int
            Number of steps to generate.

        Returns
        -------
        np.ndarray
            The generated data.

        Raises
        ------
        ValueError
            If a generated output cannot be fed back because its width differs from
            the input width the reservoirs are locked to (also for ``n_steps == 1``).
        """
        # Call the C++ model's predictGenerative method
        return self._cpp_model.predictGenerative(prime_data, n_steps)

    def get_reservoir(self, index: int) -> Any:  # noqa: ANN401
        """Get the reservoir object at the specified index.

        Parameters
        ----------
        index : int
            The index of the reservoir.

        Returns
        -------
        Any
            The C++ reservoir object.
        """
        # Return the C++ reservoir object
        return self._cpp_model.getReservoir(index)

    def get_readout(self) -> Any:  # noqa: ANN401
        """Get the readout object, such as a fitted ridge readout to read its weights from.

        Returns
        -------
        Any
            The C++ readout object.

        Raises
        ------
        RuntimeError
            If no readout is set.
        """
        return self._cpp_model.getReadout()

    def reset_reservoirs(self) -> None:
        """Reset the states of all reservoirs."""
        # Call the C++ model's resetReservoirs method
        self._cpp_model.resetReservoirs()

    def partial_fit(self, x: ArrayLike | None, y: ArrayLike) -> None:
        """Update the model with a single sample (online learning).

        Parameters
        ----------
        x : ArrayLike, optional
            Input data sample. If None, the reservoir state is not advanced
            (useful if predict_online was already called).
        y : ArrayLike
            Target data sample.

        Raises
        ------
        RuntimeError
            If no reservoir or readout is set.
        """
        # Assuming only one reservoir for simplicity in online learning for now.
        # If multiple reservoirs are present, the logic would need to be more complex
        # to handle how their states are combined before feeding to the readout.
        if not self._reservoirs_params:
            msg = "No reservoir added to the model."
            raise RuntimeError(msg)
        if not self._readout_params:
            msg = "No readout set for the model."
            raise RuntimeError(msg)

        # Ensure readout is correctly initialized
        self._update_readout()

        if x is None:
            cpp_readout = self._cpp_model.getReadout()
            states = [self._cpp_model.getReservoir(i).getState() for i in range(len(self._reservoirs_params))]
            if any(state.shape[1] == 0 for state in states):
                msg = "Reservoir state is uninitialized; call predict_online or partial_fit with input first."
                raise RuntimeError(msg)
            current_state = states[-1] if self.connection_type == "serial" else np.hstack(states)
            cpp_readout.partialFit(current_state, y)
        else:
            self._cpp_model.partialFit(x, y)

    def act(self, x: ArrayLike, *, explore: bool = True) -> np.ndarray:
        """Step the model through ``x`` row by row to learn from rewards.

        With ``explore``, the reward-modulated components add exploration noise and record each
        row's eligibility for the next :meth:`reinforce`; without it every step is noise-free and
        no learning state changes, which equals :meth:`predict_online`. A model without a readout
        returns the reservoir states, whose designated neurons can serve as outputs.

        Parameters
        ----------
        x : ArrayLike
            Input rows, one per time step.
        explore : bool, optional
            Whether to explore and record eligibility. Default is True.

        Returns
        -------
        np.ndarray
            The output of each row: the readout's, or the reservoir states without a readout.

        Raises
        ------
        ValueError
            If the inputs are not finite or do not fit the widths the model is locked to.
        RuntimeError
            If a reservoir object is listed twice, or a row's output or eligibility is not
            finite. A failing row changes no learning state and keeps the rows before it.
        """
        self._update_readout()
        return self._cpp_model.act(x, explore)

    def reinforce(self, reward: float, *, key: int = 0, baseline: float | None = None) -> None:
        """Update the reward-modulated components for a reward.

        Each component compares the reward with its baseline for ``key`` (see
        ``learning.Baseline``), or with ``baseline`` when given, and changes its weights in
        proportion to the eligibility recorded by :meth:`act`. The update applies to every
        component or to none.

        Parameters
        ----------
        reward : float
            The reward.
        key : int, optional
            The baseline to use and update, such as a trial type. Default is 0.
        baseline : float, optional
            A baseline to use instead of the internal one, which is then left unchanged.

        Raises
        ------
        ValueError
            If the reward or baseline is not finite.
        RuntimeError
            If the model has no reward-modulated component, a component has not explored since
            its last update, or the update would not be finite.
        """
        self._cpp_model.reinforce(reward, key, baseline)

    def modulate(self, modulator: float) -> None:
        """Update the reward-modulated components with the modulator given directly.

        This applies ``dW = eta * modulator * eligibility`` without a baseline, so any critic,
        such as a temporal-difference error, can drive learning.

        Parameters
        ----------
        modulator : float
            The modulator ``m``.
        """
        self._cpp_model.modulate(modulator)

    def clear_eligibility(self) -> None:
        """Zero the eligibility of the reward-modulated components, for example after an aborted trial."""
        self._cpp_model.clearEligibility()

    def save(self, path: str | os.PathLike[str]) -> None:
        """Save the model to a file.

        The file holds the configuration, the trained weights and the current
        reservoir states, so a loaded model continues exactly where this one
        stopped. It can also be loaded from C++ with ``Model::load``. An existing
        file at ``path`` is replaced in one step and is left unchanged if saving
        fails.

        Parameters
        ----------
        path : str or os.PathLike
            Destination file.

        Raises
        ------
        SerializationError
            If the model lacks a reservoir or readout, is internally inconsistent,
            or the file cannot be written.
        """
        self._cpp_model.save(os.fspath(path))

    @classmethod
    def load(cls, path: str | os.PathLike[str]) -> ESN:
        """Load a model saved by :meth:`save` or by C++ ``Model::save``.

        Only load files from sources you trust: the format contains no executable
        code, but it is parsed by native code.

        Parameters
        ----------
        path : str or os.PathLike
            Model file to read.

        Returns
        -------
        ESN
            The restored model, including its reservoir states.

        Raises
        ------
        SerializationError
            If the file cannot be read or is not a valid model file.
        """
        return cls._from_cpp_model(_rclib.Model.load(os.fspath(path)))

    @classmethod
    def _from_cpp_model(cls, cpp_model: Any) -> ESN:  # noqa: ANN401
        """Wrap a loaded C++ model, rebuilding the Python configuration objects."""
        esn = cls(cpp_model.getConnectionType())
        esn._cpp_model = cpp_model
        # partial_fit and _update_readout read these configuration objects.
        try:
            esn._reservoirs_params = [
                _reservoir_config_from_cpp(cpp_model.getReservoir(i)) for i in range(cpp_model.getNumReservoirs())
            ]
            # A model without a readout, such as one learning in its reservoirs, has no readout config.
            esn._readout_params = _readout_config_from_cpp(cpp_model.getReadout()) if cpp_model.hasReadout() else None
        except (TypeError, ValueError) as err:
            msg = f"Invalid model file: {err}"
            raise _rclib.SerializationError(msg) from err
        return esn

    def __getstate__(self) -> dict[str, Any]:
        """Support pickle and copy.deepcopy.

        Every instance attribute is kept, including ones added by users or
        subclasses; the C++ model is stored as bytes in the model file format.
        Unpickling can run arbitrary code, so only unpickle data you trust.
        """
        state = self.__dict__.copy()
        state["_cpp_model"] = self._cpp_model.dumps()
        return state

    def __setstate__(self, state: dict[str, Any]) -> None:
        """Restore a model pickled by __getstate__."""
        cpp_model = _rclib.Model.loads(state["_cpp_model"])  # before touching self, in case it fails
        self.__dict__.update(state)
        self._cpp_model = cpp_model

__getstate__()

Support pickle and copy.deepcopy.

Every instance attribute is kept, including ones added by users or subclasses; the C++ model is stored as bytes in the model file format. Unpickling can run arbitrary code, so only unpickle data you trust.

Source code in python/rclib/model.py
def __getstate__(self) -> dict[str, Any]:
    """Support pickle and copy.deepcopy.

    Every instance attribute is kept, including ones added by users or
    subclasses; the C++ model is stored as bytes in the model file format.
    Unpickling can run arbitrary code, so only unpickle data you trust.
    """
    state = self.__dict__.copy()
    state["_cpp_model"] = self._cpp_model.dumps()
    return state

__init__(connection_type='serial')

Initialize the ESN model.

Parameters:

Name Type Description Default
connection_type str

The type of connection between reservoirs ("serial" or "parallel"). Default is "serial".

'serial'
Source code in python/rclib/model.py
def __init__(self, connection_type: str = "serial") -> None:
    """Initialize the ESN model.

    Parameters
    ----------
    connection_type : str, optional
        The type of connection between reservoirs ("serial" or "parallel").
        Default is "serial".
    """
    if connection_type not in {"serial", "parallel"}:
        msg = "connection_type must be 'serial' or 'parallel'."
        raise ValueError(msg)

    self.connection_type = connection_type
    self._reservoirs_params: list[Any] = []  # Store parameters for Python-side reservoir objects
    self._readout_params: Any = None  # Store parameters for Python-side readout object
    self._cpp_model = _rclib.Model()  # Initialize the C++ Model object

__setstate__(state)

Restore a model pickled by getstate.

Source code in python/rclib/model.py
def __setstate__(self, state: dict[str, Any]) -> None:
    """Restore a model pickled by __getstate__."""
    cpp_model = _rclib.Model.loads(state["_cpp_model"])  # before touching self, in case it fails
    self.__dict__.update(state)
    self._cpp_model = cpp_model

act(x, *, explore=True)

Step the model through x row by row to learn from rewards.

With explore, the reward-modulated components add exploration noise and record each row's eligibility for the next :meth:reinforce; without it every step is noise-free and no learning state changes, which equals :meth:predict_online. A model without a readout returns the reservoir states, whose designated neurons can serve as outputs.

Parameters:

Name Type Description Default
x ArrayLike

Input rows, one per time step.

required
explore bool

Whether to explore and record eligibility. Default is True.

True

Returns:

Type Description
ndarray

The output of each row: the readout's, or the reservoir states without a readout.

Raises:

Type Description
ValueError

If the inputs are not finite or do not fit the widths the model is locked to.

RuntimeError

If a reservoir object is listed twice, or a row's output or eligibility is not finite. A failing row changes no learning state and keeps the rows before it.

Source code in python/rclib/model.py
def act(self, x: ArrayLike, *, explore: bool = True) -> np.ndarray:
    """Step the model through ``x`` row by row to learn from rewards.

    With ``explore``, the reward-modulated components add exploration noise and record each
    row's eligibility for the next :meth:`reinforce`; without it every step is noise-free and
    no learning state changes, which equals :meth:`predict_online`. A model without a readout
    returns the reservoir states, whose designated neurons can serve as outputs.

    Parameters
    ----------
    x : ArrayLike
        Input rows, one per time step.
    explore : bool, optional
        Whether to explore and record eligibility. Default is True.

    Returns
    -------
    np.ndarray
        The output of each row: the readout's, or the reservoir states without a readout.

    Raises
    ------
    ValueError
        If the inputs are not finite or do not fit the widths the model is locked to.
    RuntimeError
        If a reservoir object is listed twice, or a row's output or eligibility is not
        finite. A failing row changes no learning state and keeps the rows before it.
    """
    self._update_readout()
    return self._cpp_model.act(x, explore)

add_reservoir(reservoir)

Add a reservoir to the model.

Parameters:

Name Type Description Default
reservoir Any

The reservoir object to add.

required

Raises:

Type Description
TypeError

If the reservoir type is unsupported.

ValueError

If a RandomSparse reservoir has an unsupported spectral_radius_method.

Source code in python/rclib/model.py
def add_reservoir(self, reservoir: Any) -> None:  # noqa: ANN401
    """Add a reservoir to the model.

    Parameters
    ----------
    reservoir : Any
        The reservoir object to add.

    Raises
    ------
    TypeError
        If the reservoir type is unsupported.
    ValueError
        If a RandomSparse reservoir has an unsupported spectral_radius_method.
    """
    # Create and add the C++ reservoir to the C++ model
    if isinstance(reservoir, reservoirs.RandomSparse):
        if reservoir.spectral_radius_method not in _SPECTRAL_RADIUS_METHODS:
            msg = f"Unsupported spectral_radius_method: {reservoir.spectral_radius_method}"
            raise ValueError(msg)
        cpp_res = _rclib.RandomSparseReservoir(
            reservoir.n_neurons,
            reservoir.spectral_radius,
            reservoir.sparsity,
            reservoir.leak_rate,
            reservoir.input_scaling,
            reservoir.include_bias,
            reservoir.seed,
            _SPECTRAL_RADIUS_METHODS[reservoir.spectral_radius_method],
            reservoir.bias_scaling,
        )
        self._cpp_model.addReservoir(cpp_res, self.connection_type)
    elif isinstance(reservoir, reservoirs.Nvar):
        cpp_res = _rclib.NvarReservoir(reservoir.num_lags, reservoir.polynomial_order)
        self._cpp_model.addReservoir(cpp_res, self.connection_type)
    elif isinstance(reservoir, reservoirs.RewardModulated):
        cpp_res = _rclib.RewardModulatedReservoir(
            reservoir.n_neurons,
            reservoir.spectral_radius,
            reservoir.sparsity,
            reservoir.leak_rate,
            reservoir.input_scaling,
            reservoir.include_bias,
            reservoir.seed,
            _SPECTRAL_RADIUS_METHODS[reservoir.spectral_radius_method],
            reservoir.bias_scaling,
            _rule_to_cpp(reservoir.rule),
            reservoir.plastic_presynaptic,
            reservoir.plastic_postsynaptic,
        )
        self._cpp_model.addReservoir(cpp_res, self.connection_type)
    # Add other reservoir types here as they are implemented
    else:
        msg = "Unsupported reservoir type"
        raise TypeError(msg)

    # Store the Python reservoir object's parameters only once the C++ model holds the
    # reservoir, so a rejected reservoir leaves both sides unchanged.
    self._reservoirs_params.append(reservoir)

    # Update readout in case it's using "auto" solver
    self._update_readout()

clear_eligibility()

Zero the eligibility of the reward-modulated components, for example after an aborted trial.

Source code in python/rclib/model.py
def clear_eligibility(self) -> None:
    """Zero the eligibility of the reward-modulated components, for example after an aborted trial."""
    self._cpp_model.clearEligibility()

fit(x, y, washout_len=0)

Fit the model to the data.

Parameters:

Name Type Description Default
x ArrayLike

Input data.

required
y ArrayLike

Target data.

required
washout_len int

Number of initial samples to discard. Default is 0.

0
Source code in python/rclib/model.py
def fit(self, x: ArrayLike, y: ArrayLike, washout_len: int = 0) -> None:
    """Fit the model to the data.

    Parameters
    ----------
    x : ArrayLike
        Input data.
    y : ArrayLike
        Target data.
    washout_len : int, optional
        Number of initial samples to discard. Default is 0.
    """
    # Ensure readout is correctly initialized (especially for "auto" solver)
    self._update_readout()
    # Call the C++ model's fit method
    self._cpp_model.fit(x, y, washout_len)

fit_sequences(inputs, targets, washout_len=0)

Fit the readout once on several independent sequences, such as episodes.

Each sequence starts from reset reservoirs and discards its own first washout_len samples. The remaining reservoir states and targets of all sequences are stacked and the readout is fitted once, so nothing carries over from one sequence to the next. With a single sequence this equals :meth:fit.

Parameters:

Name Type Description Default
inputs Sequence[ArrayLike]

Input data, one 2-D array of shape (n_samples_i, n_inputs) per sequence, for example a list of arrays. Sequences may differ in length but not in width.

required
targets Sequence[ArrayLike]

Target data, one 2-D array of shape (n_samples_i, n_outputs) per sequence, with as many rows as the matching input sequence.

required
washout_len int

Number of initial samples to discard from each sequence. Default is 0.

0

Raises:

Type Description
ValueError

If a single 2-D array is passed instead of a sequence of arrays, if there are no sequences or unequal numbers of input and target sequences, or if a sequence is empty, its inputs and targets differ in length, its width differs from the first sequence's, or its input width differs from the one the reservoirs are locked to by earlier input. Messages name the sequence index.

IndexError

If washout_len is negative or not shorter than a sequence.

RuntimeError

If the model has no reservoir or no readout.

Notes

These checks run before the model changes. Afterwards the reservoirs hold their states at the end of the last sequence.

Source code in python/rclib/model.py
def fit_sequences(self, inputs: Sequence[ArrayLike], targets: Sequence[ArrayLike], washout_len: int = 0) -> None:
    """Fit the readout once on several independent sequences, such as episodes.

    Each sequence starts from reset reservoirs and discards its own first
    ``washout_len`` samples. The remaining reservoir states and targets of all
    sequences are stacked and the readout is fitted once, so nothing carries over
    from one sequence to the next. With a single sequence this equals :meth:`fit`.

    Parameters
    ----------
    inputs : Sequence[ArrayLike]
        Input data, one 2-D array of shape (n_samples_i, n_inputs) per sequence,
        for example a list of arrays. Sequences may differ in length but not in
        width.
    targets : Sequence[ArrayLike]
        Target data, one 2-D array of shape (n_samples_i, n_outputs) per sequence,
        with as many rows as the matching input sequence.
    washout_len : int, optional
        Number of initial samples to discard from each sequence. Default is 0.

    Raises
    ------
    ValueError
        If a single 2-D array is passed instead of a sequence of arrays, if there
        are no sequences or unequal numbers of input and target sequences, or if a
        sequence is empty, its inputs and targets differ in length, its width
        differs from the first sequence's, or its input width differs from the one
        the reservoirs are locked to by earlier input. Messages name the sequence
        index.
    IndexError
        If ``washout_len`` is negative or not shorter than a sequence.
    RuntimeError
        If the model has no reservoir or no readout.

    Notes
    -----
    These checks run before the model changes. Afterwards the reservoirs hold
    their states at the end of the last sequence.
    """
    # A single 2-D array would otherwise be split into one-row sequences.
    for name, sequences in (("inputs", inputs), ("targets", targets)):
        if isinstance(sequences, np.ndarray) and sequences.ndim == 2:  # noqa: PLR2004
            msg = f"{name} must be a sequence of 2-D arrays, one per sequence, not a single 2-D array."
            raise ValueError(msg)
    self._update_readout()
    self._cpp_model.fitSequences(inputs, targets, washout_len)

get_readout()

Get the readout object, such as a fitted ridge readout to read its weights from.

Returns:

Type Description
Any

The C++ readout object.

Raises:

Type Description
RuntimeError

If no readout is set.

Source code in python/rclib/model.py
def get_readout(self) -> Any:  # noqa: ANN401
    """Get the readout object, such as a fitted ridge readout to read its weights from.

    Returns
    -------
    Any
        The C++ readout object.

    Raises
    ------
    RuntimeError
        If no readout is set.
    """
    return self._cpp_model.getReadout()

get_reservoir(index)

Get the reservoir object at the specified index.

Parameters:

Name Type Description Default
index int

The index of the reservoir.

required

Returns:

Type Description
Any

The C++ reservoir object.

Source code in python/rclib/model.py
def get_reservoir(self, index: int) -> Any:  # noqa: ANN401
    """Get the reservoir object at the specified index.

    Parameters
    ----------
    index : int
        The index of the reservoir.

    Returns
    -------
    Any
        The C++ reservoir object.
    """
    # Return the C++ reservoir object
    return self._cpp_model.getReservoir(index)

load(path) classmethod

Load a model saved by :meth:save or by C++ Model::save.

Only load files from sources you trust: the format contains no executable code, but it is parsed by native code.

Parameters:

Name Type Description Default
path str or PathLike

Model file to read.

required

Returns:

Type Description
ESN

The restored model, including its reservoir states.

Raises:

Type Description
SerializationError

If the file cannot be read or is not a valid model file.

Source code in python/rclib/model.py
@classmethod
def load(cls, path: str | os.PathLike[str]) -> ESN:
    """Load a model saved by :meth:`save` or by C++ ``Model::save``.

    Only load files from sources you trust: the format contains no executable
    code, but it is parsed by native code.

    Parameters
    ----------
    path : str or os.PathLike
        Model file to read.

    Returns
    -------
    ESN
        The restored model, including its reservoir states.

    Raises
    ------
    SerializationError
        If the file cannot be read or is not a valid model file.
    """
    return cls._from_cpp_model(_rclib.Model.load(os.fspath(path)))

modulate(modulator)

Update the reward-modulated components with the modulator given directly.

This applies dW = eta * modulator * eligibility without a baseline, so any critic, such as a temporal-difference error, can drive learning.

Parameters:

Name Type Description Default
modulator float

The modulator m.

required
Source code in python/rclib/model.py
def modulate(self, modulator: float) -> None:
    """Update the reward-modulated components with the modulator given directly.

    This applies ``dW = eta * modulator * eligibility`` without a baseline, so any critic,
    such as a temporal-difference error, can drive learning.

    Parameters
    ----------
    modulator : float
        The modulator ``m``.
    """
    self._cpp_model.modulate(modulator)

partial_fit(x, y)

Update the model with a single sample (online learning).

Parameters:

Name Type Description Default
x ArrayLike

Input data sample. If None, the reservoir state is not advanced (useful if predict_online was already called).

required
y ArrayLike

Target data sample.

required

Raises:

Type Description
RuntimeError

If no reservoir or readout is set.

Source code in python/rclib/model.py
def partial_fit(self, x: ArrayLike | None, y: ArrayLike) -> None:
    """Update the model with a single sample (online learning).

    Parameters
    ----------
    x : ArrayLike, optional
        Input data sample. If None, the reservoir state is not advanced
        (useful if predict_online was already called).
    y : ArrayLike
        Target data sample.

    Raises
    ------
    RuntimeError
        If no reservoir or readout is set.
    """
    # Assuming only one reservoir for simplicity in online learning for now.
    # If multiple reservoirs are present, the logic would need to be more complex
    # to handle how their states are combined before feeding to the readout.
    if not self._reservoirs_params:
        msg = "No reservoir added to the model."
        raise RuntimeError(msg)
    if not self._readout_params:
        msg = "No readout set for the model."
        raise RuntimeError(msg)

    # Ensure readout is correctly initialized
    self._update_readout()

    if x is None:
        cpp_readout = self._cpp_model.getReadout()
        states = [self._cpp_model.getReservoir(i).getState() for i in range(len(self._reservoirs_params))]
        if any(state.shape[1] == 0 for state in states):
            msg = "Reservoir state is uninitialized; call predict_online or partial_fit with input first."
            raise RuntimeError(msg)
        current_state = states[-1] if self.connection_type == "serial" else np.hstack(states)
        cpp_readout.partialFit(current_state, y)
    else:
        self._cpp_model.partialFit(x, y)

predict(x, *, reset_state_before_predict=True)

Predict using the trained model.

Parameters:

Name Type Description Default
x ArrayLike

Input data.

required
reset_state_before_predict bool

Whether to reset the reservoir state before prediction. Default is True.

True

Returns:

Type Description
ndarray

The predicted values.

Source code in python/rclib/model.py
def predict(self, x: ArrayLike, *, reset_state_before_predict: bool = True) -> np.ndarray:
    """Predict using the trained model.

    Parameters
    ----------
    x : ArrayLike
        Input data.
    reset_state_before_predict : bool, optional
        Whether to reset the reservoir state before prediction. Default is True.

    Returns
    -------
    np.ndarray
        The predicted values.
    """
    # Call the C++ model's predict method
    return self._cpp_model.predict(x, reset_state_before_predict)

predict_generative(prime_data, n_steps)

Generative prediction.

Advances the reservoirs through prime_data (if any), then generates n_steps outputs, feeding each output back as the next input. Every generated output, including the last, advances the reservoirs, so a following call with empty prime_data continues the sequence: generating a steps and then b steps equals generating a + b steps. With n_steps == 0 no output is fed back.

Parameters:

Name Type Description Default
prime_data ArrayLike

Initial data to prime the reservoir.

required
n_steps int

Number of steps to generate.

required

Returns:

Type Description
ndarray

The generated data.

Raises:

Type Description
ValueError

If a generated output cannot be fed back because its width differs from the input width the reservoirs are locked to (also for n_steps == 1).

Source code in python/rclib/model.py
def predict_generative(self, prime_data: ArrayLike, n_steps: int) -> np.ndarray:
    """Generative prediction.

    Advances the reservoirs through ``prime_data`` (if any), then generates
    ``n_steps`` outputs, feeding each output back as the next input. Every
    generated output, including the last, advances the reservoirs, so a following
    call with empty ``prime_data`` continues the sequence: generating ``a`` steps
    and then ``b`` steps equals generating ``a + b`` steps. With ``n_steps == 0``
    no output is fed back.

    Parameters
    ----------
    prime_data : ArrayLike
        Initial data to prime the reservoir.
    n_steps : int
        Number of steps to generate.

    Returns
    -------
    np.ndarray
        The generated data.

    Raises
    ------
    ValueError
        If a generated output cannot be fed back because its width differs from
        the input width the reservoirs are locked to (also for ``n_steps == 1``).
    """
    # Call the C++ model's predictGenerative method
    return self._cpp_model.predictGenerative(prime_data, n_steps)

predict_online(x)

Predict in online mode (updating state).

Parameters:

Name Type Description Default
x ArrayLike

Input data.

required

Returns:

Type Description
ndarray

The predicted values.

Source code in python/rclib/model.py
def predict_online(self, x: ArrayLike) -> np.ndarray:
    """Predict in online mode (updating state).

    Parameters
    ----------
    x : ArrayLike
        Input data.

    Returns
    -------
    np.ndarray
        The predicted values.
    """
    # Call the C++ model's predictOnline method
    return self._cpp_model.predictOnline(x)

reinforce(reward, *, key=0, baseline=None)

Update the reward-modulated components for a reward.

Each component compares the reward with its baseline for key (see learning.Baseline), or with baseline when given, and changes its weights in proportion to the eligibility recorded by :meth:act. The update applies to every component or to none.

Parameters:

Name Type Description Default
reward float

The reward.

required
key int

The baseline to use and update, such as a trial type. Default is 0.

0
baseline float

A baseline to use instead of the internal one, which is then left unchanged.

None

Raises:

Type Description
ValueError

If the reward or baseline is not finite.

RuntimeError

If the model has no reward-modulated component, a component has not explored since its last update, or the update would not be finite.

Source code in python/rclib/model.py
def reinforce(self, reward: float, *, key: int = 0, baseline: float | None = None) -> None:
    """Update the reward-modulated components for a reward.

    Each component compares the reward with its baseline for ``key`` (see
    ``learning.Baseline``), or with ``baseline`` when given, and changes its weights in
    proportion to the eligibility recorded by :meth:`act`. The update applies to every
    component or to none.

    Parameters
    ----------
    reward : float
        The reward.
    key : int, optional
        The baseline to use and update, such as a trial type. Default is 0.
    baseline : float, optional
        A baseline to use instead of the internal one, which is then left unchanged.

    Raises
    ------
    ValueError
        If the reward or baseline is not finite.
    RuntimeError
        If the model has no reward-modulated component, a component has not explored since
        its last update, or the update would not be finite.
    """
    self._cpp_model.reinforce(reward, key, baseline)

reset_reservoirs()

Reset the states of all reservoirs.

Source code in python/rclib/model.py
def reset_reservoirs(self) -> None:
    """Reset the states of all reservoirs."""
    # Call the C++ model's resetReservoirs method
    self._cpp_model.resetReservoirs()

save(path)

Save the model to a file.

The file holds the configuration, the trained weights and the current reservoir states, so a loaded model continues exactly where this one stopped. It can also be loaded from C++ with Model::load. An existing file at path is replaced in one step and is left unchanged if saving fails.

Parameters:

Name Type Description Default
path str or PathLike

Destination file.

required

Raises:

Type Description
SerializationError

If the model lacks a reservoir or readout, is internally inconsistent, or the file cannot be written.

Source code in python/rclib/model.py
def save(self, path: str | os.PathLike[str]) -> None:
    """Save the model to a file.

    The file holds the configuration, the trained weights and the current
    reservoir states, so a loaded model continues exactly where this one
    stopped. It can also be loaded from C++ with ``Model::load``. An existing
    file at ``path`` is replaced in one step and is left unchanged if saving
    fails.

    Parameters
    ----------
    path : str or os.PathLike
        Destination file.

    Raises
    ------
    SerializationError
        If the model lacks a reservoir or readout, is internally inconsistent,
        or the file cannot be written.
    """
    self._cpp_model.save(os.fspath(path))

set_readout(readout)

Set the readout for the model.

Parameters:

Name Type Description Default
readout Any

The readout object to set.

required

Raises:

Type Description
TypeError

If the readout type is unsupported.

Source code in python/rclib/model.py
def set_readout(self, readout: Any) -> None:  # noqa: ANN401
    """Set the readout for the model.

    Parameters
    ----------
    readout : Any
        The readout object to set.

    Raises
    ------
    TypeError
        If the readout type is unsupported.
    """
    # Build the C++ readout first and record the configuration only once the C++ model
    # holds it, so a rejected readout leaves both sides unchanged and a second call
    # replaces the readout set before.
    self._cpp_model.setReadout(_cpp_readout_from_config(readout))
    self._readout_params = readout