API References
Functions
SNNModels.C_mem — Method
C_mem(;Cd=Cd,d=d,l=l)
Capacitance of a cylinder of length l and diameter d
return Capacitance in pFSNNModels.FanoFactor — Method
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.1993SNNModels.G_axial — Method
G_axial(;Ri=Ri,d=d,l=l)
Axial conductance of a cylinder of length l and diameter d
return Conductance in nSSNNModels.G_mem — Method
G_mem(;Rd=Rd,d=d,l=l)
Membrane conductance of a cylinder of length l and diameter d
return Conductance in nSSNNModels.ISI_CV2 — Method
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.1806SNNModels.Receptors — Function
Receptors struct represents a synaptic connection with different types of receptors.
Fields
AMPA::T: AMPA receptorNMDA::T: NMDA receptor (with voltage dependency)GABAa::T: GABAa receptorGABAb::T: GABAb receptor
SNNModels.Receptors — Method
Construct a Receptors from Glutamatergic and GABAergic receptors.
Arguments
glu::Glutamatergic: Glutamatergic receptorsgaba::GABAergic: GABAergic receptors
Returns
Receptors: A Receptors object
SNNModels.SNNfile — Function
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
SNNModels.SNNfolder — Method
SNNfolder(path, name, info)Generate folder path for SNN model storage using DrWatson's savename convention.
Arguments
path: Base directory pathname: Model nameinfo: NamedTuple with model metadata
Returns
- String path to the model folder
SNNModels.SNNload — Method
SNNload(; path, name="", info=nothing, count=1, type=:model)Load SNN model or data from disk.
Arguments
path::String: File path or directoryname::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
ArgumentErrorif path is directory but name or info is missing
SNNModels.SNNpath — Method
SNNpath(path, name, info, type, count)Generate complete file path for SNN data files.
Arguments
path: Base directory pathname: Model nameinfo: NamedTuple with model metadatatype: Type of file (:model, :data, etc.)count: File counter
Returns
- Complete file path string
SNNModels.SNNsave — Method
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 savepath: Base directory pathname: Model nameinfo: NamedTuple with model metadataconfig: Optional configuration to save alongside modeltype: What to save - :all (both model and data), :model (model only), :data (data only)count: Version number for the filekwargs...: 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
SNNModels.STTC — Function
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.
SNNModels.STTC — Method
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.
SNNModels.SpikeTimeStimulusIdentity — Method
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 appliedsym::Symbol: The symbol representing the synaptic connectiontarget: The target of the stimulus (optional)param::SpikeTimeStimulusParameter: The spike time parameters for the stimuluskwargs...: Additional keyword arguments to pass to theSpikeTimeStimulusconstructor
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
SNNModels.Stimulus — Method
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.
SNNModels.alpha_function — Method
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 τ.SNNModels.asynchronous_state — Function
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.
SNNModels.bin_spiketimes — Method
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.
SNNModels.clear_monitor! — Method
clear_monitor!(obj)
Clears all the records of a given object.
SNNModels.clear_records! — Method
clear_records!(objs::AbstractArray)
Clears the records of multiple objects.
SNNModels.clear_records! — Method
clear_records!(obj, sym::Symbol)
Clears the records of a given object for a specific symbol.
SNNModels.clear_records! — Method
clear_records!(obj)
Clears all the records of a given object.
SNNModels.compose — Method
compose(kwargs...; syn=nothing, pop=nothing)Merge multiple models into a single model.
Arguments
kwargs...: List ofkwargelements, i.e., dictionary or named tuples, containing the models to be merged.- if
kwarghas elements with:popand:synentries, the function copies them into the merged model. - if
kwarghas no:popand:synentries, the function iterates over all the elements contained inkwargand merge them into the model.
- if
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
SNNModels.compute_connections — Method
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, includingpandμ.
Returns
P::Matrix{Bool}: A matrix indicating the presence of connections.W::Matrix{Float32}: A matrix containing the weights of the connections.
SNNModels.compute_covariance_density — Method
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.
SNNModels.compute_cross_correlogram — Function
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.
SNNModels.data2model — Method
data2model(; path, name=randstring(10), info=nothing, kwargs...)Convert data file to model file by clearing records.
Arguments
path: Directory pathname: Model name (default: random string)info: Model metadata
Returns
trueif model file exists or was created,falseif data file doesn't exist
SNNModels.exp256 — Method
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)
SNNModels.exp32 — Method
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)
SNNModels.exp64 — Method
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)
SNNModels.extract_items — Method
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 thepopdictionary. - If the type of the item in the container is
AbstractConnection, it is added to thesyndictionary. - If the type of the item in the container is
AbstractStimulus, it is added to thestimdictionary. - 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.
SNNModels.f2l — Function
f2l(s, l=10)Format string to fixed length by padding or truncating.
Arguments
s: Input value to convert to stringl: Target length (default: 10)
Returns
- String of exactly length
l, padded with spaces or truncated
SNNModels.firing_rate — Method
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
SNNModels.firing_rate_average — Method
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:firein itsrecordsfield 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.
SNNModels.gaussian_kernel — Method
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.
SNNModels.gaussian_kernel_estimate — Method
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.
SNNModels.gaussian_weight — Function
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.
SNNModels.get_dt — Method
get_dt(T::Time)Get the time step size.
Arguments
T::Time: The Time object.
Returns
Float32: The time step size.
SNNModels.get_git_commit_hash — Method
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
SNNModels.get_interval — Method
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.
SNNModels.get_step — Method
get_step(T::Time)Get the current time step.
Arguments
T::Time: The Time object.
Returns
Float32: The current time step.
SNNModels.get_time — Method
get_time(T::Time)Get the current time.
Arguments
T::Time: The Time object.
Returns
Float32: The current time.
SNNModels.get_timestamp — Method
get_timestamp()Get current timestamp.
Returns
- Current date and time
SNNModels.getrecord — Method
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.
SNNModels.getvariable — Function
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.
SNNModels.graph — Method
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.
SNNModels.infer_receptors — Method
infer_receptors(receptors::ReceptorArray)::NamedTupleInfer 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
targetfield 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])SNNModels.integrate! — Method
integrate!(p::IZ, param::IZParameter, dt::Float32)Update Izhikevich neuron population for one timestep.
Arguments
p::IZ: The neuron populationparam::IZParameter: Model parametersdt::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
SNNModels.integrate! — Method
integrate!(p::Rate, param::RateParameter, dt::Float32)Update rate-based neuron population for one timestep.
Arguments
p::Rate: The neuron populationparam::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
SNNModels.interpolated_record — Function
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.SNNModels.interval_standard_spikes — Method
interval_standard_spikes(spiketimes, interval)Standardize the spiketimes to the interval [0, interval_duration]. Return a copy of the 'Spiketimes' vector.
SNNModels.is_attractor_state — Method
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.
SNNModels.isa_model — Method
isa_model(model)Validate that a model has the required structure for a network model.
Arguments
model: The model to validate
Returns
trueif 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
SNNModels.linear_network — Method
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.
SNNModels.load_data — Method
load_data(path, name, info; kwargs...)Load saved data from disk.
Arguments
path::String: Directory pathname::String: Model nameinfo::NamedTuple: Model metadatakwargs...: Additional arguments passed to SNNload
Returns
- Loaded data as NamedTuple
SNNModels.load_model — Method
load_model(path, name, info; kwargs...)Load a saved model from disk.
Arguments
path::String: Directory pathname::String: Model nameinfo::NamedTuple: Model metadatakwargs...: Additional arguments passed to SNNload
Returns
- Loaded model as NamedTuple
SNNModels.load_or_run — Method
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 (receivesinfoas argument)path: Directory pathname: Model nameinfo: Model metadataexp_config...: Configuration passed to save_model if running
Returns
- Loaded or newly generated model
SNNModels.max_neuron — Method
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
neuronsvector
SNNModels.merge_spiketimes — Method
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 spiketimesSNNModels.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.
SNNModels.name — Function
name(pre, post, k=nothing)Generate a Symbol name for connections between populations.
Arguments
pre: Pre-synaptic population namepost: Post-synaptic population namek: Optional suffix for the name
Returns
- Symbol in format
:pre_to_postor:pre_to_post_kif k is provided
SNNModels.neurons_outside_area — Method
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.
SNNModels.neurons_within_circle — Method
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.
SNNModels.next_neuron — Method
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
SNNModels.norm_synapse — Method
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
SNNModels.norm_synapse — Method
Calculate the normalization factor for a receptor.
Arguments
receptor::Receptor: The receptor for which to calculate the normalization factor
Returns
Float32: The normalization factor
SNNModels.periodic_distance — Method
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.
SNNModels.place_populations — Method
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.
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.
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 potentialv0, STDP time constantτy, maximal and minimal synaptic weight (WmaxandWmin).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
WminandWmax.
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 rater, STDP time constantτy, maximal and minimal synaptic weight (WmaxandWmin).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
WminandWmax.
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.
SNNModels.population_indices — Method
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.
SNNModels.print_model — Function
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.
SNNModels.print_summary — Method
print_summary(p)
Prints a summary of the given element.SNNModels.rand_value — Method
rand_value(N, p1, p2)Generate N random values uniformly distributed between p1 and p2.
Arguments
N: Number of random values to generatep1: First boundary valuep2: Second boundary value
Returns
- Vector of N random values between min(p1,p2) and max(p1,p2)
SNNModels.read_folder — Function
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 fromfiles: 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
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 topath: Directory path to read fromtype: File type to match (default: :model)name: Optional name filter
Returns
- The modified df vector
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 usingrecord_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.
SNNModels.record — Method
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:firefor firing rate,:spiketimesor:spikesfor spike times.range::Bool=false: Iftrue, return both the recorded data and the range. Default isfalse.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 = :fireandrange = true, returns a tuple(v, r)wherevis the firing rate andris the range. - If
sym = :fireandrange = false, returns the firing ratev. - If
sym = :spiketimesorsym = :spikes, returns the spike times. - For other symbols, returns a tuple
(v, r)ifrange = true, orvifrange = 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)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.
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.
SNNModels.relative_time! — Method
relative_time(spiketimes::Spiketimes, start_time)Return the spiketimes relative to the start_time of the interval
SNNModels.remove_element — Method
remove_element(model, key)Remove an element (population, synapse, or stimulus) from a model by its key.
Arguments
model: The network modelkey: Symbol key of the element to remove
Returns
- New model with the element removed
Throws
ArgumentErrorif the key is not found in the model
SNNModels.sample_spikes — Method
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.
SNNModels.save_config — Method
save_config(; path, name=randstring(10), config, info=nothing)Save configuration to disk as JLD2 file.
Arguments
path: Directory pathname: Config name (default: random string)config: Configuration data to saveinfo: Optional metadata
Returns
- Nothing
SNNModels.save_model — Method
save_model(; model, path, name, info, config=nothing, kwargs...)Convenience function to save both model and data.
Arguments
model: The model to savepath: Directory pathname: Model nameinfo: Model metadataconfig: Optional configurationkwargs...: Additional data to save
Returns
- Path to the saved files
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 shifteddelay::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
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 shifteddelay::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
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 shifteddelay::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
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 is0.1f0.duration::Float32: Duration of the simulation. Default value is10.0f0.pbar::Bool: Flag indicating whether to display a progress bar during the simulation. Default value isfalse.
Details
- The function creates a range of time steps from
0.0f0toduration-dtwith a step size ofdt. - If
pbaristrue, the function creates a progress bar using theProgressBarfunction 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 withP,C, anddt.
SNNModels.snn_kw_get_concrete_types — Method
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
SNNModels.snn_kw_str_field — Method
snn_kw_str_field(x)Parse struct field expressions for the @snn_kw macro.
Arguments
x::Symbol: Simple field namex::Expr: Field expression with type annotation or default value
Returns
- Tuple containing parsed field information
SNNModels.snn_kw_str_kws — Method
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
SNNModels.snn_kw_str_kws_types — Method
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
SNNModels.snn_kw_str_param — Method
snn_kw_str_param(x)Parse struct type parameter expressions for the @snn_kw macro.
Arguments
x::Symbol: Simple type parameterx::Expr: Type parameter expression with constraints or defaults
Returns
- Tuple containing parsed parameter information
SNNModels.snn_kw_str_sentinel_check — Method
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
SNNModels.snn_kw_str_sentinel_check_concrete — Method
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 informationdict: Dictionary mapping type parameters to inferred concrete types
Returns
- Expression checking for sentinel and inferring concrete type
SNNModels.snn_kw_str_sentinels — Method
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
SNNModels.spatial_activity — Method
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 vectorsxsandys, 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)SNNModels.spikecount — Method
spikecount(model, Trange, neurons)
Return the total number of spikes of the neurons in the selected intervalSNNModels.spikes_in_interval — Method
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
SNNModels.spiketimes — Method
spiketimes(P::NamedTuple; kwargs...)
Return the spiketimes of each population in single vector of Spiketimes.SNNModels.spiketimes — Method
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. Ifnothing, the interval is set to (0, firing_time[end]).
Returns:
spiketimes: A vector of vectors containing the spike times of each neuron.
SNNModels.spiketimes_from_bool — Method
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 typeSpiketimeswhich contains the calculated spike times of each neuron.
Examples
julia
spiketimes = spike_times(population_records, time_constant)SNNModels.spiketimes_split — Method
spiketimes_split(Ps; kwargs...)
Return the spiketimes of each population in a vector of Spiketimes.SNNModels.st_order — Method
st_order(spiketimes::Spiketimes)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.
SNNModels.stimulate! — Method
stimulate!(p::BalancedStimulus, param::BalancedParameter, time::Time, dt::Float32)Generate a Balanced stimulus for a postsynaptic population.
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 updateparam::SpikeTimeStimulusParameter: The spike time parameters containing spike times and neuron indicestime::Time: The current simulation timedt::Float32: The time step of the simulation (unused in this function)
Details
- The function first resets the
firevector 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, andnext_indexfields 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
SNNModels.str_name — Function
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 namek: Optional suffix for the name
Returns
- String in format "pretopost" or "pretopost_k" if k is provided
SNNModels.str_name — Function
str_name(pre::String, k=nothing)Generate a String name with optional suffix.
Arguments
pre::String: Base namek: Optional suffix
Returns
- String in format "pre" or "pre_k" if k is provided
SNNModels.subpopulations — Function
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
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 modifyp_rewire::Float64=0.05: Probability threshold for rewiring existing connectionsp_pre::Function=x->rand(): Function that returns probability for each presynaptic connectionsto be rewiredp_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:
- Generating thresholds for selecting connections to rewire.
- Identifying plausible new connections for each presynaptic neuron
- Selecting connections to rewire based on the probability thresholds
- Replacing the selected connections with new ones
- Updating the sparse matrix structure
The function modifies the connection matrix in-place and updates its sparse matrix representation.
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 is0.1ms.duration::Float32: Duration of the training. Default value is10ms.
Details
- The function converts
dttoFloat32if it is not already. - The function creates a progress bar using the
ProgressBarfunction with a range of time steps from0.0f0toduration-dtwith a step size ofdt. - The function iterates over the time steps and calls the
train!function withP,C, anddt.
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 aparamfield withspiketimesandneuronsvectors)spikes: An object containing new spike times and neuron indices (must havespiketimesandneuronsfields)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
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.
SNNModels.update_with_merge — Function
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 updatepath::Vector{Symbol}: Field path to update (e.g., [:a, :b, :c] for a.b.c)value: New value to assignfull_path: Full path for error messages (internal use)
Returns
- Updated NamedTuple with the field modified
SNNModels.validate_population_model — Method
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
SNNModels.validate_stimulus_model — Method
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
SNNModels.validate_synapse_model — Method
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
SNNModels.write_config — Method
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 fileinfo: NamedTuple with model metadataconfig: Configuration to savename: Optional name for the config filekwargs...: 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
SNNModels.write_value — Function
write_value(file, key, value, indent="", equal_sign="=")Write a value to a configuration file with proper formatting.
Arguments
file: IO stream to write tokey: 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.)
SNNModels.α_synapse — Method
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
Plots
SNNPlots.plot_connection_distances — Method
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:
- A bar plot showing the binned connection counts (density).
- A line plot showing the connection probability, normalized by the area of the annulus at each distance.
Arguments
fig: The MakieFigureobject 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.
SNNPlots.plot_spatial_connectivity — Method
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 MakieFigureobject to plot into.connectivity: A structure containing neuronpoints(locations) andlinks(adjacency matrices).config: The network configuration object, containing parameters fornetworkandspatialproperties.post::Symbol: The symbol for the postsynaptic population (default::Exc).n0::Int: The index of the target postsynaptic neuron within its population.
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 kernelOther types
SNNModels.AbstractConnectivity — Type
AbstractConnectivitySNNModels.AbstractMarkramSTPParameter — Type
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).
SNNModels.Dendrite — Type
DendriteA 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.
SNNModels.EmptyParam — Type
EmptyParamA struct representing an empty parameter.
Fields
type::Symbol: The type of the parameter, default is:empty.
SNNModels.GABAergic — Type
GABAergic struct represents a group of GABAergic receptors.
Fields
GABAa::T: GABAa receptorGABAb::T: GABAb receptor
SNNModels.Glutamatergic — Type
Glutamatergic struct represents a group of glutamatergic receptors.
Fields
AMPA::T: AMPA receptorNMDA::T: NMDA receptor
SNNModels.IZParameter — Type
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.
SNNModels.KwStrSentinel — Type
KwStrSentinelSentinel type used internally by @snn_kw to track unassigned type parameters.
SNNModels.NMDAVoltageDependency — Type
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)
SNNModels.PlasticityParameter — Type
PlasticityParameterSNNModels.PlasticityVariables — Type
PlasticityVariablesSNNModels.PostSpike — Type
PostSpikeA 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.
SNNModels.Receptor — Type
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 ong0,τr, andτd)α::T: Alpha factor for the differential equation (default: calculated based onτrandτ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)
SNNModels.STDPGerstner — Type
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
SNNModels.STDPMexicanHat — Type
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.SNNModels.STDPSymmetric — Type
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.SNNModels.Spiketimes — Type
SpiketimesA type alias for a vector of vectors of Float32, representing spike times.
SNNModels.Time — Type
struct Time
TimeA 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.
SNNModels.Time — Method
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
SNNModels.vSTDPParameter — Type
vSTDPParameter{FT = Float32} <: SpikingSynapseParameterContains 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 variablex.Wmax::FT: Maximum synaptic weight.Wmin::FT: Minimum synaptic weight.active::Vector{Bool}: Flag to activate or deactivate the plasticity rule.
Helper macros
SNNModels.@load_units — Macro
@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.SNNModels.@snn_kw — Macro
@snn_kwA 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.0SNNModels.@symdict — Macro
@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)SNNModels.@update — Macro
@updateMacro 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
endArguments
base: Base configuration (NamedTuple or struct)update_expr: Field assignment(s) to apply
Returns
- New configuration with updated fields