Source code for dendra.models.mod.EXP2SYN

import torch

from ..mechanisms import PointProcess as PP
from ..mechanisms import State as S
from ..mechanisms import Synapse as Syn
from ..mechanisms.ops import exp, log


@torch.compiler.allow_in_graph
def _validation_predicate_values(value):
    """Validate every physical lane without differentiating a bool predicate.

    Tensor assertions have no vmap rule. The predicate is already boolean,
    so exposing its physical transform axes preserves the validity check
    without changing the differentiable time-constant calculations.
    """
    functorch = torch._C._functorch
    while functorch.is_functorch_wrapped_tensor(value):
        value = functorch.get_unwrapped(value)
    return value


class A(S):
    S.STATE("A")
    S.ASSIGNED("tau1_effective")
    S.RANGE(tau1=0.1)
    S.DERIVATIVE("A' = -A / tau1_effective")

    def state_defaults(self, v, values):
        del values
        return {"A": torch.zeros_like(v)}

    def assigned_values(self, v, values):
        del v
        return {"tau1_effective": values["tau1_effective"]}


class B(S):
    S.STATE("B")
    S.RANGE(tau2=10.0)
    S.DERIVATIVE("B' = -B / tau2")

    def state_defaults(self, v, values):
        del values
        return {"B": torch.zeros_like(v)}


[docs] class exp2syn(PP, Syn): r""" A synaptic mechanism that uses a double-exponential function to model synaptic conductance. The conductance is modeled using two state variables ``A`` and ``B``, each following an exponential decay with different time constants. Parameters ---------- e : float The reversal potential (in mV) of the synapse. Default is 0.0 mV. tau1 : float The rise time constant (in ms) of the synapse. Default is 0.1 ms. tau2 : float The decay time constant (in ms) of the synapse. Default is 10.0 ms. Notes ----- The synaptic conductance :math:`g` is calculated as the difference between the two state variables, :math:`g = B - A`. The lumped current is :math:`i = g(V-e)`; the reversal potential does not scale the conductance. This is a :class:`~dendra.models.mechanisms.PointProcess`. Event weights, :math:`A`, :math:`B`, and :math:`g` are numerical values in µS; for example, ``weight=0.05`` means 0.05 µS. Do not multiply such a weight by :data:`dendra.units.uS`. The normalized event weight is added to both state variables. ``i(v)`` returns lumped, outward-positive current in nA, which Dendra converts to mA/cm² using compartment area during current assembly. The factor for scaling the weights is calculated based on the time constants of the two states, following the formula .. math:: \text{factor} = \frac{1}{-\exp\left(-\frac{t_p}{\tau_1}\right) + \exp\left(-\frac{t_p}{\tau_2}\right)} where :math:`t_p` is the time point at which the two exponentials are equal: .. math:: t_p = \frac{\tau_1 \tau_2}{\tau_2 - \tau_1} \log\left(\frac{\tau_2}{\tau_1}\right) This ensures that the synaptic response is properly normalized based on the time constants. As in NEURON's ``Exp2Syn``, the effective ratio ``tau1 / tau2`` is limited to ``[1e-9, 0.9999]`` during initialization. Equal, nearly equal, or reversed time constants therefore approach a normalized alpha-synapse response instead of producing a division by zero. Both time constants must be positive and finite; invalid values raise :class:`ValueError` in eager execution or a tensor assertion :class:`RuntimeError` in compiled execution. For low precision dtypes, the bounds are tightened to the nearest representable values strictly between zero and one. """ PP.STATE_BUNDLE(A, B) PP.RANGE(e=0.0) PP.DERIVED_BUFFER("factor", "tau1_effective") PP.NONSPECIFIC_CURRENT("i") PP.AFFINE("i") def derive_buffers(self): state_a = self.DE["A"] tau1 = state_a.tau1 tau2 = self.DE["B"].tau2 valid = torch.isfinite(tau1) & torch.isfinite(tau2) & (tau1 > 0) & (tau2 > 0) valid = _validation_predicate_values(valid) message = "exp2syn tau1 and tau2 must be positive and finite." if torch.compiler.is_compiling(): torch._assert_async(torch.all(valid), message) elif not bool(torch.all(valid).item()): raise ValueError(message) ratio = tau1 / tau2 zero = torch.zeros_like(ratio) one = torch.ones_like(ratio) lower = torch.maximum( torch.full_like(ratio, 1.0e-9), torch.nextafter(zero, one) ) upper = torch.minimum( torch.full_like(ratio, 0.9999), torch.nextafter(one, zero) ) ratio = torch.minimum(torch.maximum(ratio, lower), upper) tau1_effective = ratio * tau2 # At the peak, exp(-tp/tau1) is exactly ratio times # exp(-tp/tau2). This log-domain form is algebraically equivalent to # NEURON's tp expression but stays finite as ratio approaches one. log_denominator = torch.log1p(-ratio) + ratio / (1 - ratio) * log(ratio) return { "factor": exp(-log_denominator), "tau1_effective": tau1_effective, } def i(self, v): return (self.B - self.A) * (v - self.e) def i_with_conductance(self, v): """Return the current and its exact voltage derivative.""" conductance = self.B - self.A return conductance * (v - self.e), conductance def net_receive_values(self, weights, dt, values): weights = weights * values["factor"] return {"states": {"A": values["A"] + weights, "B": values["B"] + weights}}