API References

Functions

SNNModels.C_memMethod
C_mem(;Cd=Cd,d=d,l=l)
Capacitance of a cylinder of length l and diameter d
return Capacitance in pF
source
SNNModels.FanoFactorMethod
FanoFactor(spiketimes::Vector{Float32}; window=100ms)

Return the Fano Factor of the spike train
Softky, W. R., & Koch, C. (1993). The highly irregular firing of cortical cells is inconsistent with temporal integration of random EPSPs. Journal of Neuroscience, 13(1), 334–350. https://doi.org/10.1523/JNEUROSCI.13-01-00334.1993
source
SNNModels.G_axialMethod
G_axial(;Ri=Ri,d=d,l=l)
Axial conductance of a cylinder of length l and diameter d
return Conductance in nS
source
SNNModels.G_memMethod
G_mem(;Rd=Rd,d=d,l=l)
Membrane conductance of a cylinder of length l and diameter d
return Conductance in nS
source
SNNModels.ISI_CV2Method
ISI_CV2(spiketimes::Vector{Float32})

Return the local coefficient of variation of the interspike intervals
Holt, G. R., Softky, W. R., Koch, C., & Douglas, R. J. (1996). Comparison of discharge variability in vitro and in vivo in cat visual cortex neurons. Journal of Neurophysiology, 75(5), 1806–1814. https://doi.org/10.1152/jn.1996.75.5.1806
source
SNNModels.ReceptorsFunction

Receptors struct represents a synaptic connection with different types of receptors.

Fields

  • AMPA::T: AMPA receptor
  • NMDA::T: NMDA receptor (with voltage dependency)
  • GABAa::T: GABAa receptor
  • GABAb::T: GABAb receptor
source
SNNModels.ReceptorsMethod

Construct a Receptors from Glutamatergic and GABAergic receptors.

Arguments

  • glu::Glutamatergic: Glutamatergic receptors
  • gaba::GABAergic: GABAergic receptors

Returns

  • Receptors: A Receptors object
source
SNNModels.SNNfileFunction
SNNfile(type, count)

Generate filename for SNN data files.

Arguments

  • type: Type of file (:model, :data, etc.)
  • count: File counter (0 for base file, >0 for numbered versions)

Returns

  • Filename string with .jld2 extension
source
SNNModels.SNNfolderMethod
SNNfolder(path, name, info)

Generate folder path for SNN model storage using DrWatson's savename convention.

Arguments

  • path: Base directory path
  • name: Model name
  • info: NamedTuple with model metadata

Returns

  • String path to the model folder
source
SNNModels.SNNloadMethod
SNNload(; path, name="", info=nothing, count=1, type=:model)

Load SNN model or data from disk.

Arguments

  • path::String: File path or directory
  • name::String: Model name (required if path is directory)
  • info: NamedTuple with model metadata (required if path is directory)
  • count::Int: File version number (default: 1)
  • type::Symbol: Type to load (:model or :data, default: :model)

Returns

  • Loaded data as NamedTuple

Throws

  • ArgumentError if path is directory but name or info is missing
source
SNNModels.SNNpathMethod
SNNpath(path, name, info, type, count)

Generate complete file path for SNN data files.

Arguments

  • path: Base directory path
  • name: Model name
  • info: NamedTuple with model metadata
  • type: Type of file (:model, :data, etc.)
  • count: File counter

Returns

  • Complete file path string
source
SNNModels.SNNsaveMethod
SNNsave(model; path, name, info, config=nothing, type=:all, count=1, kwargs...)

Save SNN model and/or data to disk.

Arguments

  • model: The model to save
  • path: Base directory path
  • name: Model name
  • info: NamedTuple with model metadata
  • config: Optional configuration to save alongside model
  • type: What to save - :all (both model and data), :model (model only), :data (data only)
  • count: Version number for the file
  • kwargs...: Additional data to save

Returns

  • Path to the saved file

Details

  • When type=:all, saves both model (with cleared records) and full data
  • Creates config.jl file with metadata and git commit hash
  • Model records are cleared before saving to reduce file size
source
SNNModels.STTCFunction
STTC(spiketrains::Vector{Vector{Float32}}, Δt::Float32, interval::AbstractVector=nothing)

Calculate the Spike Time Tiling Coefficient (STTC) matrix for a set of spike trains.

Arguments

  • spiketrains: A vector of vectors containing the spike times of each neuron.
  • Δt: The time window for considering spikes as coincident.
  • interval: The time interval over which to compute the STTC. If not provided, it will be inferred from the first and last events in the spike trains.

Returns

  • sttc_matrix: A matrix containing the STTC values between all pairs of spike trains.
source
SNNModels.STTCMethod
STTC(spiketrain1::Vector{Float32}, spiketrain2::Vector{Float32}, Δt::Float32)

Calculate the Spike Time Tiling Coefficient (STTC) between two spike trains.

Arguments

  • spiketrain1: A vector of spike times for the first neuron.
  • spiketrain2: A vector of spike times for the second neuron.
  • Δt: The time window for considering spikes as coincident.

Returns

  • sttc_value: The calculated STTC value.
source
SNNModels.SpikeTimeStimulusIdentityMethod
SpikeTimeStimulusIdentity(post::AbstractPopulation, sym::Symbol, comp::AbstractCompartment; param::SpikeTimeStimulusParameter, kwargs...)

Create an identity spike time stimulus where each presynaptic neuron connects to a corresponding postsynaptic neuron.

This constructor creates a 1-to-1 connection between presynaptic and postsynaptic neurons, with each neuron in the presynaptic population connecting to the same neuron in the postsynaptic population. The synaptic weight matrix is set to an identity matrix.

Arguments

  • post::AbstractPopulation: The postsynaptic population to which the stimulus will be applied
  • sym::Symbol: The symbol representing the synaptic connection
  • target: The target of the stimulus (optional)
  • param::SpikeTimeStimulusParameter: The spike time parameters for the stimulus
  • kwargs...: Additional keyword arguments to pass to the SpikeTimeStimulus constructor

Returns

  • SpikeTimeStimulus: A spike time stimulus with identity connections

Notes

  • The number of presynaptic neurons (N) is set to the size of the postsynaptic population (post.N)
  • The synaptic weight matrix is set to an identity matrix (LinearAlgebra.I(post.N))
  • This is useful for creating direct connections between corresponding neurons in presynaptic and postsynaptic populations
source
SNNModels.StimulusMethod
CurrentStimulus(param::CurrentStimulus, post::T, sym::Symbol = :I; kwargs...) where {T<:AbstractPopulation}

Construct a CurrentStimulus with the given parameters and postsynaptic population.

Arguments

  • param: Parameters for the stimulus.
  • post: Postsynaptic population.
  • sym: Symbol for the input current field (default: :I).
  • kwargs: Additional keyword arguments.
source
SNNModels.alpha_functionMethod
alpha_function(t::T; t0::T, τ::T) where T <: AbstractFloat

Alpha function for convolution of spiketimes. Evaluate the alpha function at time t, with time of peak t0 and time constant τ.
source
SNNModels.asynchronous_stateFunction
inter_spike_interval(spiketimes::Vector{Float32})

Calculate the inter-spike intervals (ISIs) for a given set of spike times.

Arguments

  • spiketimes: A vector of spike times for a single neuron.

Returns

  • isis: A vector of inter-spike intervals.
source
SNNModels.bin_spiketimesMethod
bin_spiketimes(spiketimes, interval, sr)

Given a list of spike times spiketimes, an interval [start, end], and a sampling rate sr, this function counts the number of spikes that fall within each time bin of width 1/sr within the interval. The function returns a sparse matrix count containing the spike counts for each bin, and an array r containing the time points corresponding to the center of each bin.

Arguments

  • spiketimes: A 1-dimensional array of spike times.
  • interval: A 2-element array specifying the start and end times of the interval.
  • sr: The sampling rate, i.e., the number of time bins per second.

Returns

  • count: A sparse matrix containing the spike counts for each time bin.
  • r: An array of time points corresponding to the center of each time bin.
source
SNNModels.composeMethod
compose(kwargs...; syn=nothing, pop=nothing)

Merge multiple models into a single model.

Arguments

  • kwargs...: List of kwarg elements, i.e., dictionary or named tuples, containing the models to be merged.
    • if kwarg has elements with :pop and :syn entries, the function copies them into the merged model.
    • if kwarg has no :pop and :syn entries, the function iterates over all the elements contained in kwarg and merge them into the model.
  • syn: Optional dictionary of synapses to be merged.
  • pop: Optional dictionary of populations to be merged.
  • stim: Optional dictionary of stimuli to be merged.

Returns

A tuple (pop, syn) representing the merged populations and synapses.

Details

This function takes in multiple models represented as keyword arguments and merges them into a single model. The models can be specified using the pop and syn fields in the keyword arguments. If the pop and syn fields are not present, the function expects the keyword arguments to have elements with :pop or :syn fields.

The merged populations and synapses are stored in dictionaries populations and synapses, respectively. The function performs type assertions to ensure that the elements being merged are of the correct types (AbstractPopulation for populations and AbstractConnection for synapses).

If syn and/or pop and/or stim arguments are provided, they are merged into the respective dictionaries.

Example

source
SNNModels.compute_connectionsMethod
compute_long_short_connections(pre::Symbol, post::Symbol, points; dc, pl, ϵ, grid_size, conn)

Compute the connections between two populations of neurons based on their spatial distance. This function will assign connections with probability p_short for short-range connections and p_long for long-range connections. The weights of the connections are determined by the μ parameter in the conn named tuple. The function uses a periodic boundary condition to calculate distances in a 2D grid. The total number of connections per the post-synaptic neuron is: ϵ * Npre * pshort + (1 - ϵ) * Npre * plong.

Arguments

  • pre::Symbol: The symbol representing the pre-synaptic population.
  • post::Symbol: The symbol representing the post-synaptic population.
  • points::NamedTuple: A named tuple containing the spatial points for each population.
  • dc::Float64: The critical distance for short-range connections.
  • pl::Float64: The probability of long-range connections.
  • ϵ::Float64: The scaling factor for connection probabilities.
  • grid_size::Float64: The size of the grid.
  • conn::NamedTuple: A named tuple containing connection parameters, including p and μ.

Returns

  • P::Matrix{Bool}: A matrix indicating the presence of connections.
  • W::Matrix{Float32}: A matrix containing the weights of the connections.
source
SNNModels.compute_covariance_densityMethod
compute_covariance_density(t_post, t_pre, T; τ=200ms, sr=50Hz)

Compute the covariance density of spike trains t_post and t_pre over a time interval T. The function returns the covariance density vectors for positive and negative time lags.

Arguments

  • spike_times1:: Vector{Float32}: A vector of spike times for the first neuron.
  • spike_times2:: Vector{Float32}: A vector of spike times for the second neuron.
  • bin_width:: Float32: The width of the time bins in milliseconds.
  • max_lag:: Float32: The maximum time lag in milliseconds.

Returns

  • lags:: Vector{Float32}: The time lags in milliseconds.
  • covariance_density:: Vector{Float32}: The covariance density for each time lag.
source
SNNModels.compute_cross_correlogramFunction
autocor(spiketimes::Spiketimes; interval = 0:1:1000)

Calculate the cross-correlation of two spike trains.

Arguments

  • spike_times1: A vector of spike times for the first neuron.
  • spike_times2: A vector of spike times for the second neuron.
  • bin_width: The width of the time bins in milliseconds.
  • max_lag: The maximum time lag in milliseconds.

Returns

  • lags: The time lags in milliseconds.
  • auto_corr: The auto-correlation for each time lag.
source
SNNModels.data2modelMethod
data2model(; path, name=randstring(10), info=nothing, kwargs...)

Convert data file to model file by clearing records.

Arguments

  • path: Directory path
  • name: Model name (default: random string)
  • info: Model metadata

Returns

  • true if model file exists or was created, false if data file doesn't exist
source
SNNModels.exp256Method
exp256(x::Float32)

Fast approximation of exp(x) using 256 iterations. Clamps input to avoid underflow.

Arguments

  • x::Float32: Input value

Returns

  • Approximation of exp(x)
source
SNNModels.exp32Method
exp32(x::R) where {R<:Real}

Fast approximation of exp(x) using 32 iterations. Clamps input to avoid underflow.

Arguments

  • x::Real: Input value

Returns

  • Approximation of exp(x)
source
SNNModels.exp64Method
exp64(x::R) where {R<:Real}

Fast approximation of exp(x) using 64 iterations. Clamps input to avoid underflow.

Arguments

  • x::Real: Input value

Returns

  • Approximation of exp(x)
source
SNNModels.extract_itemsMethod
extract_items(root::Symbol, container; pop::Dict{Symbol,Any}, syn::Dict{Symbol, Any}, stim::Dict{Symbol,Any})

Extracts items from a container and adds them to the corresponding dictionaries based on their type.

Arguments

  • root::Symbol: The root symbol for the items being extracted.
  • container: The container from which to extract items.
  • pop::Dict{Symbol,Any}: The dictionary to store population items.
  • syn::Dict{Symbol, Any}: The dictionary to store synapse items.
  • stim::Dict{Symbol,Any}: The dictionary to store stimulus items.

Returns

  • true: Always returns true.

Details

  • If the type of the item in the container is AbstractPopulation, it is added to the pop dictionary.
  • If the type of the item in the container is AbstractConnection, it is added to the syn dictionary.
  • If the type of the item in the container is AbstractStimulus, it is added to the stim dictionary.
  • If the type of the item in the container is none of the above, the function is recursively called to extract items from the nested container.
source
SNNModels.f2lFunction
f2l(s, l=10)

Format string to fixed length by padding or truncating.

Arguments

  • s: Input value to convert to string
  • l: Target length (default: 10)

Returns

  • String of exactly length l, padded with spaces or truncated
source
SNNModels.firing_rateMethod
firing_rate(
    spiketimes::Spiketimes,
    interval::AbstractVector = [],
    sampling = 20,
    τ = 25,
    ttf = -1,
    tt0 = -1,
    cache = true,
    pop::Union{Symbol,Vector{Int}}= :ALL,
)

Calculate the firing rates for a population or an individual neuron.

Arguments

  • spiketimes: Spiketimes object.
  • interval: Time interval vector (default is an empty vector).
  • sampling: Sampling rate (default is 20ms).
  • τ: Time constant for convolution (default is 25ms).
  • ttf: Final time point (default is -1, which means until the end of the simulation time).
  • tt0: Initial time point (default is -1, which means from the start of the simulation time based on the sampling rate).
  • cache: If true, uses cached data (default is true).
  • pop: Either :ALL for all populations or a Vector of Integers specifying specific neuron indices. Default is :ALL.

Returns

A tuple containing:

  • rates: A vector of firing rates for each neuron in the chosen population.
  • interval: The time interval over which the firing rates were calculated.

Examples

source
SNNModels.firing_rate_averageMethod
firing_rate_average(P; dt=0.1ms)

Calculates and returns the average firing rates of neurons in a network.

Arguments:

  • P: A structure containing neural data, with a key :fire in its records field which stores spike information for each neuron.
  • dt: An optional parameter specifying the time interval (default is 0.1ms).

Returns:

An array of floating point values representing the average firing rate for each neuron.

Usage:# Notes:

Each row of P.records[:fire] represents a neuron, and each column represents a time point. The value in a cell indicates whether that neuron has fired at that time point (non-zero value means it has fired). The firing rate of a neuron is calculated as the total number of spikes divided by the total time span.

source
SNNModels.gaussian_kernelMethod
gaussian_kernel(σ::Float64, length::Int)

Create a Gaussian kernel with standard deviation σ and specified length.

Arguments

  • σ: Standard deviation of the Gaussian kernel.
  • length: Length of the kernel.

Returns

  • kernel: A vector representing the Gaussian kernel.
source
SNNModels.gaussian_kernel_estimateMethod
gaussian_kernel_estimate(support_vector::Vector{Float64}, σ::Float64, length::Int)

Apply a Gaussian kernel estimate to a support vector with closed boundary conditions.

Arguments

  • support_vector: The input support vector.
  • σ: Standard deviation of the Gaussian kernel.
  • length: Length of the kernel.

Returns

  • estimated_vector: The estimated vector after applying the Gaussian kernel.
source
SNNModels.gaussian_weightFunction
gaussian_weight(pre, post; σx, σy, grid_size)

Compute the Gaussian weight between pre- and post-synaptic neurons based on their spatial coordinates.

Arguments

  • pre::Vector{Float32}: The coordinates of the pre-synaptic neuron.
  • post::Vector{Float32}: The coordinates of the post-synaptic neuron.
  • σx::Float32: The standard deviation of the Gaussian in the x-direction.
  • σy::Float32: The standard deviation of the Gaussian in the y-direction.
  • grid_size::Vector{Float32}: The size of the grid.

Returns

  • weight::Float32: The Gaussian weight between the pre- and post-synaptic neurons.
source
SNNModels.get_dtMethod
get_dt(T::Time)

Get the time step size.

Arguments

  • T::Time: The Time object.

Returns

  • Float32: The time step size.
source
SNNModels.get_git_commit_hashMethod
get_git_commit_hash()

Get current git commit hash of the repository.

Returns

  • String containing the full commit hash

Note

  • Requires git to be available in PATH
source
SNNModels.get_intervalMethod
get_interval(T::Time)

Get the time interval from 0 to the current time.

Arguments

  • T::Time: The Time object.

Returns

  • StepRange{Float32}: The time interval.
source
SNNModels.get_stepMethod
get_step(T::Time)

Get the current time step.

Arguments

  • T::Time: The Time object.

Returns

  • Float32: The current time step.
source
SNNModels.get_timeMethod
get_time(T::Time)

Get the current time.

Arguments

  • T::Time: The Time object.

Returns

  • Float32: The current time.
source
SNNModels.getrecordMethod

getrecord(p, sym)

Returns the recorded values for a given object and symbol. If the symbol is not found in the object's records, it checks the records of the object's plasticity and returns the values for the matching symbol.

source
SNNModels.getvariableFunction

getvariable(obj, key, id=nothing)

Returns the recorded values for a given object and key. If an id is provided, returns the recorded values for that specific id.

source
SNNModels.graphMethod
graph(model)

Generate a graph representation of the model.

Arguments

  • model: The model to generate the graph from.

Returns

A MetaGraphs.MetaDiGraph object representing the graph.

Details

  • Each vertex represents either a population ('pop'), a normalization synapse ('meta'), or a stimulus pre-target ('pre'). Its metadata includes:

    • name: Actual name of the population, 'meta' for a SynapseNormalization, or the pre-target's name for a stimulus.
    • id: Identifier of the population, SynapseNormalization, or stimulus.
    • key: Key from the original 'pop', 'syn', or 'stim' dictionary in the model.
  • Each edge represents a synaptic connection or a stimulus. Its metadata includes:

    • type: Type of the edge, ':firetog' for SpikingSynapse, ':meta' for SynapseNormalization, or ':stim' for a stimulus.
    • name: Name of the edge, formatted as "fromvertexname to tovertexname".
    • key: Key from the original 'syn' or 'stim' dictionary in the model.
    • id: Identifier of the synapse or stimulus.
  • The function iterates over the populations, synapses, and stimuli in the model.

AbstractPopulation items are added as vertices.

For each connection it checks the type of the synapse and adds an edge between the pre-synaptic population and the post-synaptic population. - SpikingSynapse: the edge represents a connection from the firing population to the receiving population. - SynapseNormalization: the edge represents a normalization of synapses between populations. - PoissonStimulus: the edge represents a stimulus from the pre-synaptic population to the post-synaptic population.

For each stimulus, it adds a vertex to the graph representing an implicit pre-synaptic population [:fire] an edge between it and the post-synaptic population [:post].

Returns a MetaGraphs.MetaDiGraph where:

Errors

Throws ArgumentError when the synapse type is neither SpikingSynapse nor SynapseNormalization.

source
SNNModels.infer_receptorsMethod
infer_receptors(receptors::ReceptorArray)::NamedTuple

Infer receptor types and their indices from a ReceptorArray.

This function processes an array of receptors and returns a named tuple where each field corresponds to a receptor type (specified by the target field of each receptor). The value of each field is a vector of indices that reference the receptors of that type in the input array.

Arguments

  • receptors::ReceptorArray: An array of receptor objects to be processed

Returns

  • NamedTuple: A named tuple where each field name is a receptor type (Symbol) and the corresponding value is a vector of indices (Int) of receptors of that type in the input array

Throws

  • Error: If any receptor in the input array has a target field set to :none

Example

receptors = ReceptorArray([
    Receptor(target=:glu),
    Receptor(target=:gaba),
    Receptor(target=:glu),
])  
result = infer_receptors(receptors)
# result will be (; glu = [1, 3], gaba = [2])
source
SNNModels.integrate!Method
integrate!(p::IZ, param::IZParameter, dt::Float32)

Update Izhikevich neuron population for one timestep.

Arguments

  • p::IZ: The neuron population
  • param::IZParameter: Model parameters
  • dt::Float32: Time step size

Details

  • Updates synaptic conductances exponentially
  • Integrates membrane potential using Euler method (two half-steps for stability)
  • Updates recovery variable u
  • Applies synaptic currents
  • Detects spikes (v > 30mV) and applies reset
source
SNNModels.integrate!Method
integrate!(p::Rate, param::RateParameter, dt::Float32)

Update rate-based neuron population for one timestep.

Arguments

  • p::Rate: The neuron population
  • param::RateParameter: Model parameters (unused)
  • dt::Float32: Time step size

Details

  • Updates internal state x: dx/dt = -x + g + I
  • Computes output rate: r = tanh(x)
  • Rate r is bounded between -1 and 1
source
SNNModels.interpolated_recordFunction
interpolated_record(p, sym)

Returns the recording with interpolated time values and the extrema of the recorded time points.

N.B. 
----
The element can be accessed at whichever time point by using the index of the array. The time point must be within the range of the recorded time points, in r_v.
source
SNNModels.interval_standard_spikesMethod
interval_standard_spikes(spiketimes, interval)

Standardize the spiketimes to the interval [0, interval_duration]. Return a copy of the 'Spiketimes' vector.

source
SNNModels.is_attractor_stateMethod
is_attractor_state(spiketimes::Spiketimes, interval::AbstractVector, N::Int)

Check if the network is in an attractor state by verifying that the average firing rate over the last N seconds of the simulation is a unimodal distribution.

Arguments

  • spiketimes: A vector of vectors containing the spike times of each neuron.
  • interval: The time interval over which to compute the firing rate.
  • N: The number of seconds over which to check the unimodality of the firing rate distribution.

Returns

  • is_attractor: A boolean indicating whether the network is in an attractor state.
source
SNNModels.isa_modelMethod
isa_model(model)

Validate that a model has the required structure for a network model.

Arguments

  • model: The model to validate

Returns

  • true if valid

Throws

  • AssertionError if required fields (pop, syn, stim, time, name) are missing
  • AssertionError if any component fails validation

Details

  • Checks for presence of all required fields
  • Validates each population, synapse, and stimulus
  • Ensures time field is a Time struct
source
SNNModels.linear_networkMethod
linear_network(N, σ_w=0.38, w_max=2.0)

Create a linear network with Gaussian-shaped connections.

Arguments

  • N::Int: The number of neurons.
  • σ_w::Float64: The standard deviation of the Gaussian distribution.
  • w_max::Float64: The maximum weight.

Returns

  • W::Matrix{Float32}: A matrix containing the weights of the connections.
source
SNNModels.load_dataMethod
load_data(path, name, info; kwargs...)

Load saved data from disk.

Arguments

  • path::String: Directory path
  • name::String: Model name
  • info::NamedTuple: Model metadata
  • kwargs...: Additional arguments passed to SNNload

Returns

  • Loaded data as NamedTuple
source
SNNModels.load_modelMethod
load_model(path, name, info; kwargs...)

Load a saved model from disk.

Arguments

  • path::String: Directory path
  • name::String: Model name
  • info::NamedTuple: Model metadata
  • kwargs...: Additional arguments passed to SNNload

Returns

  • Loaded model as NamedTuple
source
SNNModels.load_or_runMethod
load_or_run(f; path, name, info, exp_config...)

Load model from disk if available, otherwise run function to generate it.

Arguments

  • f::Function: Function to run if model doesn't exist (receives info as argument)
  • path: Directory path
  • name: Model name
  • info: Model metadata
  • exp_config...: Configuration passed to save_model if running

Returns

  • Loaded or newly generated model
source
SNNModels.max_neuronMethod
max_neuron(param::SpikeTimeStimulusParameter)

Get the maximum neuron index in a SpikeTimeStimulusParameter.

This function returns the highest neuron index present in the parameter structure. If there are no neurons, it returns 0.

Arguments

  • param::SpikeTimeStimulusParameter: The parameter structure containing neuron indices

Returns

  • The maximum neuron index, or 0 if there are no neurons

Notes

  • This function does not modify the parameter structure
  • The maximum neuron index is determined by finding the maximum value in the neurons vector
source
SNNModels.merge_spiketimesMethod
merge_spiketimes(spikes::Vector{Spiketimes}; start::Float32=0.0f0)

Merge spiketimes from different simulations. 
This function is not thread safe, it is not recommended to use it in parallel.
Parameters
----------
spikes: Vector{Spiketimes}
    Vector of spiketimes from different simulations
Return
------
neurons: Spiketimes
    Single vector of spiketimes
source
SNNModels.monitor!Method
monitor!(obj::Item, keys::Vector; sr = 1000Hz, variables::Symbol = :none) where {Item<:Union{AbstractPopulation,AbstractStimulus,AbstractConnection}}

Initialize monitoring for specified variables in an object.

Arguments

  • obj::Item: The object to monitor (must be a population, stimulus, or connection).
  • keys::Vector: A vector of symbols or tuples specifying variables to monitor.
    • If a symbol is provided, it specifies the variable to monitor.
    • If a tuple is provided, the first element is the variable symbol and the second is a list of indices to monitor.
  • sr::Float32: The sampling rate for recording (default: 1000Hz).
  • variables::Symbol: The variable group to monitor (default: :none). If specified, monitors variables within this group.

Details

This function sets up monitoring for the specified variables in the object. It initializes necessary recording structures if they don't exist, and configures the sampling rate and indices for each variable to be monitored.

For firing activity (:fire), it creates a dictionary to store spike times and neuron indices. For other variables, it determines the appropriate data type and creates a vector to store the recorded values.

Notes

  • If a variable is not found in the object, a warning is issued.
  • If a variable is already being monitored, a warning is issued.
  • The function handles both direct object fields and nested fields within variable groups.
source
SNNModels.nameFunction
name(pre, post, k=nothing)

Generate a Symbol name for connections between populations.

Arguments

  • pre: Pre-synaptic population name
  • post: Post-synaptic population name
  • k: Optional suffix for the name

Returns

  • Symbol in format :pre_to_post or :pre_to_post_k if k is provided
source
SNNModels.neurons_outside_areaMethod
neurons_outside_area(points, center, distance, grid_size)

Find the indices of neurons outside a specified area around a center point.

Arguments

  • points::Vector{Vector{Float64}}: The coordinates of the neurons.
  • center::Vector{Float64}: The coordinates of the center point.
  • distance::Float64: The minimum distance from the center point.
  • grid_size::Float64: The size of the grid.

Returns

  • indices::Vector{Int}: The indices of neurons outside the specified area.
source
SNNModels.neurons_within_circleMethod
neurons_within_circle(points, center, distance, grid_size)

Find the indices of neurons within a specified area around a center point.

Arguments

  • points::Vector{Vector{Float64}}: The coordinates of the neurons.
  • center::Vector{Float64}: The coordinates of the center point.
  • distance::Float64: The maximum distance from the center point.
  • grid_size::Float64: The size of the grid.

Returns

  • indices::Vector{Int}: The indices of neurons within the specified area.
source
SNNModels.next_neuronMethod
next_neuron(p::SpikeTimeStimulus)

Get the index of the next neuron that will fire in the spike time stimulus.

This function returns the index of the presynaptic neuron that will fire next in the stimulus. If there are no more spikes to process, it returns an empty array.

Arguments

  • p::SpikeTimeStimulus: The spike time stimulus to query

Returns

  • The index of the next neuron to fire, or an empty array if there are no more spikes

Notes

  • This function does not modify the stimulus state
  • The returned neuron index corresponds to the presynaptic neuron in the stimulus
source
SNNModels.norm_synapseMethod

Calculate the normalization factor for a synapse given rise and decay time constants.

Arguments

  • τr: Rise time constant
  • τd: Decay time constant

Returns

  • Float32: The normalization factor
source
SNNModels.norm_synapseMethod

Calculate the normalization factor for a receptor.

Arguments

  • receptor::Receptor: The receptor for which to calculate the normalization factor

Returns

  • Float32: The normalization factor
source
SNNModels.periodic_distanceMethod
periodic_distance(point1, point2, grid_size)

Calculate the periodic distance between two points in a 2D grid.

Arguments

  • point1::Vector{Float64}: The coordinates of the first point.
  • point2::Vector{Float64}: The coordinates of the second point.
  • grid_size::Float64: The size of the grid.

Returns

  • distance::Float64: The periodic distance between the two points.
source
SNNModels.place_populationsMethod
place_populations(config)

Create a 2D spatial structure and dispose N points for each population.

Arguments

  • Npop::NamedTuple: A named tuple containing the number of neurons for each population.
  • grid_size::Vector{Float64}: A vector specifying the size of the grid in each dimension.

Returns

  • Pops::NamedTuple: A named tuple containing the spatial points for each population.
source
SNNModels.plasticity!Method
plasticity!(c::SynapseNormalization, param::AdditiveNorm, dt::Float32)

Updates the synaptic weights using additive or multiplicative normalization (operator). This function calculates the rate of change μ as the difference between initial weight W0 and the current weight W1, normalized by W1. The weights are updated at intervals specified by time constant τ.

Arguments

  • c: An instance of SynapseNormalization.
  • param: An instance of AdditiveNorm.
  • dt: Simulation time step.
source
SNNModels.plasticity!Method
plasticity!(c::AbstractSparseSynapse, param::iSTDPPotential, dt::Float32)

Performs the synaptic plasticity calculation based on the inihibitory spike-timing dependent plasticity (iSTDP) model from Vogels (2011) using membrane potential traces. The function updates synaptic weights W of each synapse in the network according to the firing status of pre and post-synaptic neurons. This is an in-place operation that modifies the input AbstractSparseSynapse object c.

Arguments

  • c::AbstractSparseSynapse: The current spiking synapse object which contains data structures to represent the synapse network.
  • param::iSTDPPotential: Parameters needed for the iSTDP model, including learning rate η, reference membrane potential v0, STDP time constant τy, maximal and minimal synaptic weight (Wmax and Wmin).
  • dt::Float32: The time step for the numerical integration.

Algorithm

  • For each pre-synaptic neuron, if it fires, it increases the synaptic weight by an amount proportional to the difference between the post-synaptic membrane potential trace and a reference potential v0, otherwise the pre-synaptic trace decays exponentially over time with a time constant τy.
  • For each post-synaptic neuron, if it fires, it increases the synaptic weight by an amount proportional to the pre-synaptic trace, otherwise the post-synaptic trace decays exponentially over time with a time constant τy.
  • The synaptic weights are bounded by Wmin and Wmax.
source
SNNModels.plasticity!Method
plasticity!(c::AbstractSparseSynapse, param::iSTDPRate, dt::Float32)

Performs the synaptic plasticity calculation based on the inihibitory spike-timing dependent plasticity (iSTDP) model from Vogels (2011). The function updates synaptic weights W of each synapse in the network according to the firing status of pre and post-synaptic neurons. This is an in-place operation that modifies the input AbstractSparseSynapse object c.

Arguments

  • c::AbstractSparseSynapse: The current spiking synapse object which contains data structures to represent the synapse network.
  • param::iSTDPRate: Parameters needed for the iSTDP model, including learning rate η, target rate r, STDP time constant τy, maximal and minimal synaptic weight (Wmax and Wmin).
  • dt::Float32: The time step for the numerical integration.

Algorithm

  • For each pre-synaptic neuron, if it fires, it reduces the synaptic weight by an amount proportional to the difference between the target rate and the actual rate and increases the inhibitory term, otherwise the inhibitory term decays exponentially over time with a time constant τy.
  • For each post-synaptic neuron, if it fires, it increases the synaptic weight by an amount proportional to the pre-synaptic trace and increases the excitatory term, otherwise the excitatory term decays exponentially over time with a time constant τy.
  • The synaptic weights are bounded by Wmin and Wmax.
source
SNNModels.plasticity!Method
plasticity!(c::SynapseNormalization, param::AdditiveNorm, dt::Float32)

Updates the synaptic weights using additive or multiplicative normalization (operator). This function calculates the rate of change μ as the difference between initial weight W0 and the current weight W1, normalized by W1. The weights are updated at intervals specified by time constant τ.

Arguments

  • c: An instance of SynapseNormalization.
  • param: An instance of AdditiveNorm.
  • dt: Simulation time step.
source
SNNModels.population_indicesMethod
population_indices(P, type = "ˆ")

Given a dictionary P containing population names as keys and population objects as values, this function returns a named tuple indices that maps each population name to a range of indices. The range represents the indices of the neurons belonging to that population.

Arguments

  • P: A dictionary containing population names as keys and population objects as values.
  • type: A string specifying the type of population to consider. Only population names that contain the specified type will be included in the output. Defaults to "ˆ".

Returns

A named tuple indices where each population name is mapped to a range of indices.

source
SNNModels.print_modelFunction
print_model(model)

Prints the details of the given model. The model is expected to have three components: pop (populations), syn (synapses), and stim (stimuli).

The function displays a graph representation of the model, followed by detailed information about each component.

Arguments

  • model: The model containing populations, synapses, and stimuli to be printed.

Outputs

Prints the graph of the model, along with the name, key, type, and parameters of each component in the populations, synapses, and stimuli.

Exception

Raises an assertion error if any component in the populations is not a subtype of AbstractPopulation, if any component in the synapses is not a subtype of AbstractConnection, or if any component in the stimuli is not a subtype of AbstractStimulus.

source
SNNModels.rand_valueMethod
rand_value(N, p1, p2)

Generate N random values uniformly distributed between p1 and p2.

Arguments

  • N: Number of random values to generate
  • p1: First boundary value
  • p2: Second boundary value

Returns

  • Vector of N random values between min(p1,p2) and max(p1,p2)
source
SNNModels.read_folderFunction
read_folder(path, files=nothing; my_filter=(file,_type)->endswith(file,"type.jld2"), type=:model, name=nothing)

Read all matching files from a folder.

Arguments

  • path: Directory path to read from
  • files: Optional vector to append results to (default: creates new vector)
  • my_filter: Filter function (file, type) -> Bool (default: matches .jld2 files)
  • type: File type to match (default: :model)
  • name: Optional name filter

Returns

  • Vector of file paths matching the filter
source
SNNModels.read_folder!Method
read_folder!(df, path; type=:model, name=nothing)

Read matching files from folder and append to existing vector.

Arguments

  • df: Vector to append results to
  • path: Directory path to read from
  • type: File type to match (default: :model)
  • name: Optional name filter

Returns

  • The modified df vector
source
SNNModels.record!Method
record!(obj, T::Time)

Record the state of the object obj at the current time T.

Arguments

  • obj: The object to record the state from.
  • T::Time: The current time object.

Details

This function records the state of the object by iterating through all keys in the object's records. For each key:

  • If the key is :fire, it records the firing activity using record_fire!.
  • For plasticity variables, it checks if the key starts with a variable name and records the corresponding field.
  • For other fields, it records the field if it exists in the object.
  • It updates the start and end times for each recorded variable.

Notes

  • The function skips special keys like :indices, :sr, and :timestamp.
  • The recording is performed only if the sampling rate condition is met.
source
SNNModels.recordMethod
record(p, sym::Symbol; range = false, interval = nothing, kwargs...)

Record data from a population p based on the specified symbol sym.

Arguments

  • p: The population from which to record data.
  • sym::Symbol: The type of data to record. Valid options are :fire for firing rate, :spiketimes or :spikes for spike times.
  • range::Bool=false: If true, return both the recorded data and the range. Default is false.
  • interval: The time interval for recording. Required for firing rate recording (sym = :fire).
  • kwargs...: Additional keyword arguments to pass to the recording function.

Returns

  • If sym = :fire and range = true, returns a tuple (v, r) where v is the firing rate and r is the range.
  • If sym = :fire and range = false, returns the firing rate v.
  • If sym = :spiketimes or sym = :spikes, returns the spike times.
  • For other symbols, returns a tuple (v, r) if range = true, or v if range = false.

Examples

# Record firing rate for a population p over a specific interval
v = record(p, :fire; interval = (0.0, 1.0))

# Record firing rate and range for a population p over a specific interval
v, r = record(p, :fire; range = true, interval = (0.0, 1.0))

# Record spike times for a population p
spikes = record(p, :spiketimes)
source
SNNModels.record_fire!Method
record_fire!(obj::PT, T::Time, indices::Dict{Symbol,Vector{Int}}) where {PT <: Union{AbstractPopulation, AbstractStimulus}}

Record the firing activity of the obj object into the obj.records[:fire] array.

Arguments

  • obj::PT: The object to record the firing activity from.
  • T::Time: The time at which the recording is happening.
  • indices::Dict{Symbol,Vector{Int}}: A dictionary containing indices for each variable to record.
source
SNNModels.record_sym!Method
record_sym!(obj, key::Symbol, T::Time, indices::Dict{Symbol,Vector{Int}})

Record the variable key of the obj object into the obj.records[key] array.

Arguments

  • obj: The object to record the variable from.
  • key::Symbol: The key of the variable to record.
  • T::Time: The time at which the recording is happening.
  • indices::Dict{Symbol,Vector{Int}}: A dictionary containing indices for each variable to record.
source
SNNModels.relative_time!Method
relative_time(spiketimes::Spiketimes, start_time)

Return the spiketimes relative to the start_time of the interval

source
SNNModels.remove_elementMethod
remove_element(model, key)

Remove an element (population, synapse, or stimulus) from a model by its key.

Arguments

  • model: The network model
  • key: Symbol key of the element to remove

Returns

  • New model with the element removed

Throws

  • ArgumentError if the key is not found in the model
source
SNNModels.sample_spikesMethod
sample_spikes(N, rate::Vector, interval::R; dt=0.125f0) where {R <: AbstractRange}

Generate sample spike times for N neurons from a rate vector. The function generates spike times for each neuron based on the rate vector and the time interval. The spike times are generated such that during the interval of the rate, the number of spikes is Poisson distributed with the rate.

Arguments

  • N: The number of neurons.
  • rate::Vector: The vector with the rate to be sampled.
  • interval::R: The time interval over which the rate is recorded.
  • dt=0.125f0: The time step size.

Returns

An array of spike times for each neuron.

source
SNNModels.save_configMethod
save_config(; path, name=randstring(10), config, info=nothing)

Save configuration to disk as JLD2 file.

Arguments

  • path: Directory path
  • name: Config name (default: random string)
  • config: Configuration data to save
  • info: Optional metadata

Returns

  • Nothing
source
SNNModels.save_modelMethod
save_model(; model, path, name, info, config=nothing, kwargs...)

Convenience function to save both model and data.

Arguments

  • model: The model to save
  • path: Directory path
  • name: Model name
  • info: Model metadata
  • config: Optional configuration
  • kwargs...: Additional data to save

Returns

  • Path to the saved files
source
SNNModels.shift_spikes!Method
shift_spikes!(stimulus::SpikeTimeStimulus, delay::Number)

Shift all spike times in a SpikeTimeStimulus by a specified delay.

This function modifies the spike times in the stimulus by adding the specified delay to each time. It also resets the stimulus to start processing spikes from the beginning of the shifted spike train.

Arguments

  • stimulus::SpikeTimeStimulus: The stimulus containing spike times to be shifted
  • delay::Number: The amount of time to shift each spike (can be positive or negative)

Notes

  • The function modifies the spike times in the stimulus in-place
  • The stimulus is reset to start processing spikes from the first spike in the shifted spike train
  • The delay is converted to Float32 before being added to the spike times
source
SNNModels.shift_spikes!Method
shift_spikes!(param::SpikeTimeStimulusParameter, delay::Number)

Shift all spike times in a SpikeTimeStimulusParameter by a specified delay.

This function modifies the spike times in the parameter structure by adding the specified delay to each time. This effectively shifts all spikes forward or backward in time.

Arguments

  • param::SpikeTimeStimulusParameter: The parameter structure containing spike times to be shifted
  • delay::Number: The amount of time to shift each spike (can be positive or negative)

Notes

  • The function modifies the spike times in the parameter structure in-place
  • The delay is converted to Float32 before being added to the spike times
source
SNNModels.shift_spikes!Method
shift_spikes!(param::Vector{Float32}, delay::Number)

Shift all spike times in a vector by a specified delay.

This function modifies the spike times in the vector by adding the specified delay to each time. This effectively shifts all spikes forward or backward in time.

Arguments

  • param::Vector{Float32}: Vector of spike times to be shifted
  • delay::Number: The amount of time to shift each spike (can be positive or negative)

Notes

  • The function modifies the input vector in-place
  • The delay is converted to Float32 before being added to the spike times
source
SNNModels.sim!Method
sim!(
    P::Vector{TN},
    C::Vector{TS};
    dt = 0.1f0,
    duration = 10.0f0,
    pbar = false,
) where {TN <: AbstractPopulation, TS<:AbstractConnection }

Simulates the spiking neural network for a specified duration by repeatedly calling sim! function.

Arguments

  • P::Vector{TN}: Vector of neurons in the network.
  • C::Vector{TS}: Vector of synapses in the network.
  • dt::Float32: Time step for the simulation. Default value is 0.1f0.
  • duration::Float32: Duration of the simulation. Default value is 10.0f0.
  • pbar::Bool: Flag indicating whether to display a progress bar during the simulation. Default value is false.

Details

  • The function creates a range of time steps from 0.0f0 to duration-dt with a step size of dt.
  • If pbar is true, the function creates a progress bar using the ProgressBar function with the time step range. Otherwise, it uses the time step range directly.
  • The function iterates over the time steps and calls the sim! function with P, C, and dt.
source
SNNModels.snn_kw_get_concrete_typesMethod
snn_kw_get_concrete_types(x)

Infer concrete types for type parameters from field definitions.

Arguments

  • x: Vector of parsed field information

Returns

  • Dictionary mapping type parameters to inferred concrete types
source
SNNModels.snn_kw_str_fieldMethod
snn_kw_str_field(x)

Parse struct field expressions for the @snn_kw macro.

Arguments

  • x::Symbol: Simple field name
  • x::Expr: Field expression with type annotation or default value

Returns

  • Tuple containing parsed field information
source
SNNModels.snn_kw_str_kwsMethod
snn_kw_str_kws(x::Tuple)

Convert parsed field tuple to keyword argument expression.

Arguments

  • x::Tuple: Parsed field information (name, type, default)

Returns

  • Expression for keyword argument in constructor
source
SNNModels.snn_kw_str_kws_typesMethod
snn_kw_str_kws_types(x::Tuple)

Convert parsed parameter tuple to typed keyword argument expression.

Arguments

  • x::Tuple: Parsed parameter information

Returns

  • Expression for typed keyword argument
source
SNNModels.snn_kw_str_paramMethod
snn_kw_str_param(x)

Parse struct type parameter expressions for the @snn_kw macro.

Arguments

  • x::Symbol: Simple type parameter
  • x::Expr: Type parameter expression with constraints or defaults

Returns

  • Tuple containing parsed parameter information
source
SNNModels.snn_kw_str_sentinel_checkMethod
snn_kw_str_sentinel_check(x)

Generate code to check if type parameter was assigned or use default.

Arguments

  • x: Parsed parameter information

Returns

  • Expression checking for sentinel value
source
SNNModels.snn_kw_str_sentinel_check_concreteMethod
snn_kw_str_sentinel_check_concrete(x; dict)

Generate code to infer concrete type from field types if not explicitly provided.

Arguments

  • x: Parsed parameter information
  • dict: Dictionary mapping type parameters to inferred concrete types

Returns

  • Expression checking for sentinel and inferring concrete type
source
SNNModels.snn_kw_str_sentinelsMethod
snn_kw_str_sentinels(x)

Add sentinel default values to type parameters for tracking assignment.

Arguments

  • x: Parsed parameter tuple

Returns

  • Tuple with sentinel default value added
source
SNNModels.spatial_activityMethod
spatial_activity(points, activity; N, L, grid_size=(x=0.1, y=0.1))

Compute the spatial average of activity data over a grid.

Arguments

  • points::Tuple{Vector{Float64}, Vector{Float64}}: A tuple containing two vectors xs and ys, which represent the x and y coordinates of the points.
  • activity::Matrix{Float64}: A matrix where rows correspond to points and columns correspond to activity values over time.
  • N::Int: The number of time steps to group together for averaging.
  • L::Float64: The size of each grid cell in both x and y directions.
  • grid_size::NamedTuple{(:x, :y), Tuple{Float64, Float64}} (optional): The total size of the grid in the x and y directions. Defaults to (x=0.1, y=0.1).

Returns

  • spatial_avg::Array{Float64, 3}: A 3D array where the first two dimensions correspond to the grid cells in the x and y directions, and the third dimension corresponds to the time groups. Each element contains the average activity for the points within the corresponding grid cell and time group.
  • x_range::Vector{Float64}: A vector representing the range of x coordinates for the grid cells.
  • y_range::Vector{Float64}: A vector representing the range of y coordinates for the grid cells.

Details

The function divides the spatial domain into a grid based on the grid_size and L parameters. For each grid cell, it computes the average activity of the points that fall within the cell over time groups defined by N. If no points are found in a grid cell, the average for that cell is skipped.

Example

xs = [0.05, 0.15, 0.25, 0.35]
ys = [0.05, 0.15, 0.25, 0.35]
points = (xs, ys)
activity = rand(4, 100)  # Random activity data for 4 points over 100 time steps
N = 10
L = 0.1
grid_size = (x=0.4, y=0.4)

spatial_avg, x_range, y_range = spatial_activity(points, activity; N, L, grid_size)
source
SNNModels.spikecountMethod
spikecount(model, Trange, neurons)

Return the total number of spikes of the neurons in the selected interval
source
SNNModels.spikes_in_intervalMethod

spikesininterval(spiketimes::Spiketimes, interval::AbstractRange)

Return the spiketimes in the selected interval

Arguments

spiketimes::Spiketimes: Vector with each neuron spiketime interval: 2 dimensional array with the start and end of the interval

source
SNNModels.spiketimesMethod
spiketimes(P::NamedTuple; kwargs...)

Return the spiketimes of each population in single vector of Spiketimes.
source
SNNModels.spiketimesMethod
spiketimes(population::AbstractComponent, interval = nothing, indices = nothing)

Compute the spike times of a population.

Arguments:

  • p: The network parameters.
  • interval: The time interval within which to compute the spike times. If nothing, the interval is set to (0, firing_time[end]).

Returns:

  • spiketimes: A vector of vectors containing the spike times of each neuron.
source
SNNModels.spiketimes_from_boolMethod
spiketimes_from_bool(P, τ; dt = 0.1ms)

This function takes in the records of a neural population P and time constant τ to calculate spike times for each neuron.

Arguments

  • P: A data structure containing the recorded data of a neuronal population.
  • τ: A time constant parameter.

Keyword Arguments

  • dt: The time step used for the simulation, defaults to 0.1 milliseconds.

Returns

  • spiketimes: An object of type Spiketimes which contains the calculated spike times of each neuron.

Examples

julia
spiketimes = spike_times(population_records, time_constant)
source
SNNModels.stimulate!Method
stimulate!(p, param::CurrentNoise, time::Time, dt::Float32)

Generate a noisy current stimulus for a postsynaptic population.

Arguments

  • p: Current stimulus.
  • param: Parameters for the noise.
  • time: Current time.
  • dt: Time step.
source
SNNModels.stimulate!Method
stimulate!(p::BalancedStimulus, param::BalancedParameter, time::Time, dt::Float32)

Generate a Balanced stimulus for a postsynaptic population.

source
SNNModels.stimulate!Method
stimulate!(s::SpikeTimeStimulus, param::SpikeTimeStimulusParameter, time::Time, dt::Float32)

Update the synaptic conductances of a SpikeTimeStimulus based on the current simulation time.

This function processes all spikes that have occurred up to the current simulation time, updating the synaptic conductances of the postsynaptic neurons accordingly. It also advances the spike index to the next unprocessed spike.

Arguments

  • s::SpikeTimeStimulus: The spike time stimulus to update
  • param::SpikeTimeStimulusParameter: The spike time parameters containing spike times and neuron indices
  • time::Time: The current simulation time
  • dt::Float32: The time step of the simulation (unused in this function)

Details

  • The function first resets the fire vector to indicate no neurons have fired
  • It then processes all spikes that have occurred up to the current time:
    • For each spike, it marks the presynaptic neuron as fired
    • It updates the synaptic conductances of all postsynaptic neurons connected to the firing neuron
    • It advances to the next spike in the spike train
  • If there are no more spikes, the next spike time is set to infinity and the next index is set to -1

Notes

  • The function modifies the fire, g, next_spike, and next_index fields of the stimulus
  • The synaptic conductances are updated by adding the synaptic weights of the connected neurons
  • This function is typically called during each time step of a simulation
source
SNNModels.str_nameFunction
str_name(pre, post, k=nothing)

Generate a String name for connections between populations.

Arguments

  • pre: Pre-synaptic population name (String or Symbol)
  • post: Post-synaptic population name
  • k: Optional suffix for the name

Returns

  • String in format "pretopost" or "pretopost_k" if k is provided
source
SNNModels.str_nameFunction
str_name(pre::String, k=nothing)

Generate a String name with optional suffix.

Arguments

  • pre::String: Base name
  • k: Optional suffix

Returns

  • String in format "pre" or "pre_k" if k is provided
source
SNNModels.subpopulationsFunction
subpopulations(stim)

Extracts the names and the neuron ids projected from a given set of stimuli.

Arguments

  • stim: A dictionary containing stimulus information.

Returns

  • names: A vector of strings representing the names of the subpopulations.
  • pops: A vector of arrays representing the populations of the subpopulations.

Example

source
SNNModels.synaptic_turnover!Method
synaptic_turnover!(C::SpikingSynapse; p_rewire=0.05, p_pre = x->rand(), p_new = x->rand(), μ = 3.0)

Perform synaptic turnover on a spiking synapse connection matrix.

Arguments

  • C::SpikingSynapse: The spiking synapse connection to modify
  • p_rewire::Float64=0.05: Probability threshold for rewiring existing connections
  • p_pre::Function=x->rand(): Function that returns probability for each presynaptic connection s to be rewired
  • p_new::Function=x->rand(): Function that returns probability for selecting new postsynaptic neurons
  • μ::Float64=3.0: Weight value for new connections

Description

This function implements synaptic turnover by:

  1. Generating thresholds for selecting connections to rewire.
  2. Identifying plausible new connections for each presynaptic neuron
  3. Selecting connections to rewire based on the probability thresholds
  4. Replacing the selected connections with new ones
  5. Updating the sparse matrix structure

The function modifies the connection matrix in-place and updates its sparse matrix representation.

source
SNNModels.train!Method
train!(
    P::Vector{TN},
    C::Vector{TS};
    dt = 0.1ms,
    duration = 10ms,
) where {TN <: AbstractPopulation, TS<:AbstractConnection }

Trains the spiking neural network for a specified duration by repeatedly calling train! function.

Arguments

  • P::Vector{TN}: Vector of neurons in the network.
  • C::Vector{TS}: Vector of synapses in the network.
  • dt::Float32: Time step for the training. Default value is 0.1ms.
  • duration::Float32: Duration of the training. Default value is 10ms.

Details

  • The function converts dt to Float32 if it is not already.
  • The function creates a progress bar using the ProgressBar function with a range of time steps from 0.0f0 to duration-dt with a step size of dt.
  • The function iterates over the time steps and calls the train! function with P, C, and dt.
source
SNNModels.update_spikes!Function
update_spikes!(stim, spikes, start_time = 0.0f0)

Update the spike times in a stimulus with new spike data.

This function replaces the existing spike times and neuron indices in the stimulus with new data from the provided spikes object. The new spike times are offset by the specified start time.

Arguments

  • stim: The stimulus to update (must have a param field with spiketimes and neurons vectors)
  • spikes: An object containing new spike times and neuron indices (must have spiketimes and neurons fields)
  • start_time::Float32: The time offset to apply to the new spike times (default: 0.0f0)

Returns

  • The updated stimulus

Notes

  • The function clears the existing spike data and replaces it with the new data
  • The stimulus is reset to start processing spikes from the first spike in the new spike train
  • The new spike times are offset by the specified start time
source
SNNModels.update_time!Method
update_time!(T::Time, dt::Float32)

Update the current time and time step.

Arguments

  • T::Time: The Time object.
  • dt::Float32: The time step size.
source
SNNModels.update_with_mergeFunction
update_with_merge(base_config::NamedTuple, path::Vector{Symbol}, value, full_path=nothing)

Recursively update a nested field in a NamedTuple.

Arguments

  • base_config::NamedTuple: The configuration to update
  • path::Vector{Symbol}: Field path to update (e.g., [:a, :b, :c] for a.b.c)
  • value: New value to assign
  • full_path: Full path for error messages (internal use)

Returns

  • Updated NamedTuple with the field modified
source
SNNModels.validate_population_modelMethod
validate_population_model(model)

Validate a population model structure.

Arguments

  • model: The population model to validate

Throws

  • AssertionError if model doesn't inherit from AbstractPopulation
  • AssertionError if param doesn't inherit from AbstractPopulationParameter
  • AssertionError if required fields (N, param, id, name, records) are missing
source
SNNModels.validate_stimulus_modelMethod
validate_stimulus_model(model)

Validate a stimulus model structure.

Arguments

  • model: The stimulus model to validate

Throws

  • AssertionError if model doesn't inherit from AbstractStimulus
  • AssertionError if param doesn't inherit from AbstractStimulusParameter
  • AssertionError if required fields (param, id, name, records) are missing
source
SNNModels.validate_synapse_modelMethod
validate_synapse_model(model)

Validate a synapse/connection model structure.

Arguments

  • model: The synapse model to validate

Throws

  • AssertionError if model doesn't inherit from AbstractConnection
  • AssertionError if param doesn't inherit from AbstractConnectionParameter
  • AssertionError if required fields (param, id, name, records) are missing
source
SNNModels.write_configMethod
write_config(path, info; config, name="", kwargs...)

Write configuration and metadata to a Julia config file.

Arguments

  • path::String: File path or directory for config file
  • info: NamedTuple with model metadata
  • config: Configuration to save
  • name: Optional name for the config file
  • kwargs...: Additional named tuples to save

Details

  • Generates timestamped config file with git commit hash
  • Creates human-readable Julia syntax output
  • Skips "study" and "models" fields
source
SNNModels.write_valueFunction
write_value(file, key, value, indent="", equal_sign="=")

Write a value to a configuration file with proper formatting.

Arguments

  • file: IO stream to write to
  • key: Key name (empty string for array elements)
  • value: Value to write (supports Number, String, Symbol, Tuple, Array, Dict, NamedTuple, etc.)
  • indent: Indentation string (default: "")
  • equal_sign: Assignment operator (default: "=")

Details

  • Recursively handles nested structures
  • Formats different types appropriately (quoted strings, symbols with :, etc.)
source
SNNModels.α_synapseMethod

Calculate the alpha factor for a synapse given rise and decay time constants.

Arguments

  • τr: Rise time constant
  • τd: Decay time constant

Returns

  • Float32: The alpha factor
source

Plots

SNNPlots.plot_connection_distancesMethod
plot_connection_distances(fig; ds, rs)

Computes and plots the distribution of connection distances for different presynaptic populations to the excitatory (:Exc) population.

This function calculates the periodic distance for every established connection from presynaptic populations (:Exc, :PV, :SST) to all postsynaptic :Exc neurons. It then generates two plots:

  1. A bar plot showing the binned connection counts (density).
  2. A line plot showing the connection probability, normalized by the area of the annulus at each distance.

Arguments

  • fig: The Makie Figure object to plot into.
  • ds: A dictionary containing the binned connection counts for each presynaptic population.
  • rs: The edges of the distance bins used for histogramming the connection distances.
source
SNNPlots.plot_spatial_connectivityMethod
plot_spatial_connectivity(fig, connectivity, config; post = :Exc, n0::Int = rand(1:20))

Visualizes the spatial layout of neuronal populations and their connections to a single postsynaptic neuron.

This function plots all neurons from the excitatory (Exc), PV, and SST populations with distinct markers. For a specified postsynaptic neuron (n0 from population post), it highlights all presynaptic neurons that form a connection to it and draws arrows indicating these connections.

Arguments

  • fig: The Makie Figure object to plot into.
  • connectivity: A structure containing neuron points (locations) and links (adjacency matrices).
  • config: The network configuration object, containing parameters for network and spatial properties.
  • post::Symbol: The symbol for the postsynaptic population (default: :Exc).
  • n0::Int: The index of the target postsynaptic neuron within its population.
source
SNNPlots.stdp_kernel!Method
stdp_kernel(stdp_param; ΔT= -97.5:5:100ms)

Plot the STDP kernel for the given STDP parameters. 

# Arguments
- `stdp_param::STDPParameter`: STDP parameters
- `ΔT::Array{Float32}`: Arrays of time differences between pre and post-synaptic spikes

# Return
- `Plots.Plot`: Plot of the STDP kernel
source

Other types

SNNModels.AbstractMarkramSTPParameterType
MarkramSTPParameter{FT <: AbstractFloat} <: STPParameter

The model is based on refractoriness of the synaptic release process, which can be rephrased by stating that:
The fraction (U) of the synaptic efficacy used by an AP becomes instantaneously unavailable for subsequent use and recovers with a time constant of τD (τrec, depression). The fraction of available synaptic efficacy is termed `x.`  A facilitating mechanism is included in the model as a pulsed increase in U by each AP. The running value of U is referred to as u and U remains a parameter that applies to the first AP in a train. u decays with a single exponential, τF (facilitation), to its resting value U. The amount of synaptic efficacy enhanced by a action potential is assumed to be U(1-u).
The increase in the amplitude of the postsynaptic response is proportional to the product of u and x.

The actual implementation follows the equations described in Mongillo et al. (2008) for clarity.

Fields

  • τD::FT: Time constant for depression (default: 200ms)
  • τF::FT: Time constant for facilitation (default: 1500ms)
  • U::FT: Maximum utilization of synaptic resources (default: 0.2)
  • Wmax::FT: Maximum synaptic weight (default: 1.0pF)
  • Wmin::FT: Minimum synaptic weight (default: 0.0pF)

This struct is used to configure the short-term plasticity dynamics in synaptic connections following the model described by Markram et al. (1998).

source
SNNModels.DendriteType
Dendrite

A structure representing a dendritic compartment within a neuron model.

Fields

  • El::FT = -70.6mV: Resting potential.
  • C::FT = 10pF: Membrane capacitance.
  • gax::FT = 10nS: Axial conductance.
  • gm::FT = 1nS: Membrane conductance.
  • l::FT = 150um: Length of the dendritic compartment.
  • d::FT = 4um: Diameter of the dendrite.

The type FT represents Float32.

source
SNNModels.EmptyParamType
EmptyParam

A struct representing an empty parameter.

Fields

  • type::Symbol: The type of the parameter, default is :empty.
source
SNNModels.GABAergicType

GABAergic struct represents a group of GABAergic receptors.

Fields

  • GABAa::T: GABAa receptor
  • GABAb::T: GABAb receptor
source
SNNModels.GlutamatergicType

Glutamatergic struct represents a group of glutamatergic receptors.

Fields

  • AMPA::T: AMPA receptor
  • NMDA::T: NMDA receptor
source
SNNModels.IZParameterType
IZParameter{FT<:AbstractFloat}

Parameters for the Izhikevich neuron model.

Fields

  • a::FT: Time scale of recovery variable u (default: 0.01)
  • b::FT: Sensitivity of u to v (default: 0.2)
  • c::FT: After-spike reset value of v in mV (default: -65)
  • d::FT: After-spike increment of u (default: 2)
  • τe::FT: Excitatory synaptic time constant (default: 5ms)
  • τi::FT: Inhibitory synaptic time constant (default: 10ms)
  • Ee::FT: Excitatory reversal potential (default: 0mV)
  • Ei::FT: Inhibitory reversal potential (default: -80mV)

References

  • Izhikevich, E. M. (2003). Simple model of spiking neurons. IEEE Transactions on neural networks, 14(6), 1569-1572.
source
SNNModels.NMDAVoltageDependencyType

NMDAVoltageDependency struct represents the voltage dependence of NMDA receptors.

Fields

  • b::T: Voltage dependence factor (default: 3.36)
  • k::T: Voltage dependence factor (default: -0.077)
  • mg::T: Magnesium concentration (default: 1.0)
source
SNNModels.PostSpikeType
PostSpike

A structure defining the parameters of a post-synaptic spike event.

Fields

  • A::FT: Amplitude of the Post-Synaptic Potential (PSP).
  • τA::FT: Time constant of the PSP.

The type FT represents Float32.

source
SNNModels.ReceptorType

Receptor struct represents a synaptic receptor with parameters for reversal potential, rise time, decay time, and conductance.

Fields

  • E_rev::T: Reversal potential (default: 0.0)
  • τr::T: Rise time constant (default: -1.0)
  • τd::T: Decay time constant (default: -1.0)
  • g0::T: Maximum conductance (default: 0.0)
  • gsyn::T: Synaptic conductance (default: calculated based on g0, τr, and τd)
  • α::T: Alpha factor for the differential equation (default: calculated based on τr and τd)
  • τr⁻::T: Inverse of rise time constant (default: calculated based on τr)
  • τd⁻::T: Inverse of decay time constant (default: calculated based on τd)
  • nmda::T: NMDA factor (default: 0.0)
source
SNNModels.STDPGerstnerType

Gerstner, W., Kempter, R., van Hemmen, J. L., & Wagner, H. (1996). A neuronal learning rule for sub-millisecond temporal coding. Nature, 383(6595), 76–78. https://doi.org/10.1038/383076a0

source
SNNModels.STDPMexicanHatType
STDPMexicanHat{FT = Float32}

The STDP is defined such that integral of the kernel is zero. The STDP kernel is defined as:

`` A x * exp(-x/sqrt(2)) ``

where   ``A`` is the learning rate for post and pre-synaptic spikes, respectively, and ``x`` is the difference between the post and pre-synaptic traces.
source
SNNModels.STDPSymmetricType
STDPSymmetric{FT = Float32}

Symmetric STDP rules described in:
`Structured stabilization in recurrent neural circuits through inhibitory synaptic plasticity` 
by Festa, D., Cusseddu, C, and Gjorgjieva, J. (2024).

The STDP is defined such that integral of the kernel is zero. The STDP kernel is defined as:

`` (rac{A_{post}}{1/	au_{post}} * exp(-t/	au_{post} - rac{A_{pre}}{	au_pre} * exp(-t/	au_{pre}) ``

where ``A_{post}`` and ``A_{pre}`` are the learning rates for post and pre-synaptic spikes, respectively, and ``	au_{post}`` and ``	au_{pre}`` are the time constants for post and pre-synaptic traces, respectively.
source
SNNModels.TimeType
struct Time
Time

A mutable struct representing time. A mutable struct representing time.

Fields

  • t::Vector{Float32}: A vector containing the current time.
  • tt::Vector{Int}: A vector containing the current time step.
  • dt::Float32: The time step size.
source
SNNModels.TimeMethod
Time(time::Number)

Create a Time struct from a numeric time value.

Arguments

  • time::Number: Time value (in ms units typically)

Returns

  • Time struct with t, tt, and dt fields initialized

Details

  • Converts time to timesteps using dt=0.125ms
  • Initializes vectors for current time and timestep
source
SNNModels.vSTDPParameterType
vSTDPParameter{FT = Float32} <: SpikingSynapseParameter

Contains parameters for the voltage-dependent Spike-Timing Dependent Plasticity (vSTDP) model.

Fields

  • A_LTD::FT: Long Term Depression learning rate.
  • A_LTP::FT: Long Term Potentiation learning rate.
  • θ_LTD::FT: LTD threshold.
  • θ_LTP::FT: LTP threshold.
  • τu::FT: Time constant for the pre-synaptic spike trace.
  • τv::FT: Time constant for the post-synaptic membrane trace.
  • τx::FT: Time constant for the variable x.
  • Wmax::FT: Maximum synaptic weight.
  • Wmin::FT: Minimum synaptic weight.
  • active::Vector{Bool}: Flag to activate or deactivate the plasticity rule.
source

Helper macros

SNNModels.@load_unitsMacro
@load_units
Load all the units defined in the module into the current scope.
This macro generates a block of expressions that assign the unit constants
    
The base units in the module are:
- cm : centimeters
- ms : milliseconds
- kHz : kilohertz
- mV : millivolts
- pA : picoamperes
- pF : picofarads
- nS : nanosiemens
- GΩ : gigaohms
- uM : micromolar

The derived units in the module are obtained as multiple or division of the base units. 

The standard integration time step is 0.125ms, which is used in the simulation.
source
SNNModels.@snn_kwMacro
@snn_kw

A minimal implementation of Base.@kwdef with default type parameter support. Generates keyword constructors for structs with automatic type parameter inference.

Usage

@snn_kw struct MyStruct{FT = Float32}
    x::FT = 1.0
    y::FT = 2.0
end

# Can now create with:
MyStruct()              # Uses Float32 (default)
MyStruct(FT=Float64)    # Uses Float64
MyStruct(x=3.0)         # Uses Float32, x=3.0
source
SNNModels.@symdictMacro
@symdict(x...)

Create a Dict{Symbol,Any} from variable names.

Arguments

  • x...: Variable names to include in the dictionary

Returns

  • Dictionary mapping variable names (as symbols) to their values

Example

a = 1
b = 2
d = @symdict(a, b)  # Dict(:a => 1, :b => 2)
source
SNNModels.@updateMacro
@update

Macro to update fields in a named tuple configuration immutably.

Usage

config = (a = 1, b = (c = 2, d = 3))
new_config = @update config b.c = 5
# or with multiple updates:
new_config = @update config begin
    b.c = 5
    b.d = 6
end

Arguments

  • base: Base configuration (NamedTuple or struct)
  • update_expr: Field assignment(s) to apply

Returns

  • New configuration with updated fields
source