     [file version.texi not included]

CNrun Lua API
*************

Copyright © 2014 Andrei Zavada johnhommer@gmail.com.

The files representing this documentation set are part of CNrun project, and covered by GPL-2+.

This file documents the CNrun functions exposed in Lua.

Introduction
************

CNrun is a slow but precise neuronal network model simulator written in C++, for which functions are exposed in the Lua scripting language. These functions are described in this document.

In the present version (2.x), CNrun core is made into a shared library, in contrast to CNrun 1.x which had it as a single executable interpreting its own, very simple scripts.  In order to enable a more competent scripting, with interesting possibilities such as network plastic processes regulated by some model activity (excitation levels, spike patterns, etc), wrappers are provided to call core functions from Lua.

In the simplest case where you have a NeuroML-defined topology, a simulation session could be as brief as this:

     local M = require("cnrun")
     _, C = M.get_context()
     _, M = M.new_model (C, "fafa")
     M.import_nml (C, "fafa", "model.nml")
     M.advance (C, "fafa", 1000)

This snippet will create an interpreter context, create a model in it, load an NML file, and advance the model one second.

To report a bug or request a wishlist item, go to http://github.com/hmmr/cnrun.

General notes
*************

Preparations
============

All functions are made available in cnrun module namespace, by means of standard require.  Thus, local N = require("cnrun"); M.some_function(args).

Returned arguments
==================

On error, all functions return two arguments: first a nil, and second, an error message describing what went wrong (a string).

On success, the first returned argument will be 1 (integer), followed by one or more values specifically described in the following sections. Unless stated otherwise, functions which have nothing meaningful to return, on success return 1, model_name.

Interpreter context
*******************

In Lua, after loading the cnrun module with require("cnrun"), the first step is to get an interpreter context.  It is an opaque light user data object, which you should pass as the first argument to all subsequent calls to CNrun functions.

You can create and keep multiple models in a context, modify and advance them independently.

The function to create a CNrun context is get_context():

 -- Function: get_context ()
     Create a CNrun interpreter context, in which all subsequent operations will be performed.

     On success, returns the newly created context object C as the second argument.

 -- Function: drop_context (C)
     Drop the interpreter context C, previously obtained with get_context().

In the following sections, context is passed as the first (or only) argument to all functions.  It is denoted as C and not described each time.

Models
******

Multiple models can be created, accessed, modified, advanced within a single interpreter context.  Models are identified by a label (a string).

Creating and deleting models
============================

 -- Function: new_model (C, M)
     Create a model named M (model label).

 -- Function: delete_model (C, M)
     Delete model M.

 -- Function: list_models (C)
     List models existing in context C, returned as strings.

Populating models
=================

Models can be populated by constituent neurons and synapses in two ways:

 1. importing topology from a file (import_nml());

 2. adding individual units one by one (new_neuron(), new_synapse()).

 -- Function: import_nml (C, M, file_name)
     Import network topology from a file (FILE_NAME) into a model named M.

 -- Function: export_nml (C, M, file_name)
     Export network topology of model M into file FILE_NAME.

 -- Function: new_neuron (C, M, type, label)
     Create a neuron of type TYPE, with this LABEL, in model M.  LABEL must be of the form ``population.id''.

 -- Function: new_synapse (C, M, type, source, target)
     Create a synapse of this TYPE connecting neurons labelled SOURCE and TARGET.

Other operations on models as a whole
=====================================

 -- Function: reset_model (C, M)
     Reset the state of all units, rewind all periodic sources and flush and close any logs in model M.

 -- Function: cull_deaf_synapses (C, M)
     Remove all synapses with a zero GSYN, in model M.  This makes sense unless you are going to modify GSYN at a later time.

 -- Function: describe_model (C, M)
     Describe model M.  The output will be printed to stdout and look like this:
     Model "FAFA":
          13 units total (7 Neurons, 6 Synapses):
            11 hosted,
             2 standalone
             0 discrete dt-bound
           0 Listening units
           0 Spikelogging neurons
           0 Units being tuned continuously
           0 Units being tuned periodically
           2 Spontaneously firing neurons
           2 Multiplexing synapses
          26 vars on integration vector

 -- Function: advance (C, M, duration)
     Run simulation in model M for DURATION milliseconds.

 -- Function: advance_until (C, M, time)
     Run simulation in model M until point in time TIME.

     Note that the real eventual model time after this function has returned may be a little (less than the last DT) greater than expected.

Model parameters
================

Each model has the following parameters that affect its behaviour:

verbosely
     Level of verbosity of printed messages (integer, 0 up to 6).

integration_dt_min
     Lower bound for DT (float).

integration_dt_max
     Upper bound for DT (float).

integration_dt_cap
     Maximal factor by which DT can be allowed to increase in consecutive iterations (float).

listen_dt
     A time increment between consecutive sampling and logging of state variables (float).

listen_mode
     A string of symbols defining unit `listening' mode, of the form x{-}, where x indicates the mode and -, whether to disable that mode (if given, else enable).  There are three modes: 1, whether to log the first state variable only, or all unit vars; D, whether to defer writing until end of simulation; and B, whether to write FP values in native machine representation instead of "%g".

sxf_start_delay
     Length of time, before and after sampling point, limiting the extent of counting spikes for sdf/sxf evaluation (float).  Leave at 0 to count all spikes from 0 until current model time; a couple of seconds should be good for reasonable accuracy.

sxf_period
     Sampling period for sdf and shf (spike density and spike heterogeneity) functions.

sdf_sigma
     Parameter SIGMA in sdf (float).

 -- Function: get_model_parameter (C, M, P)
     Get a model parameter P, one of those listed above.

 -- Function: set_model_parameter (C, M, P, V)
     Set a model parameter P to value V.

Individulal unit identification, properties and parameters
**********************************************************

Units populating a model are uniquely identified by their label, set at creation time.  Where a single unit needs to be selected for a function, the corresponding argument to that function is designated L.  Or, if an operation is supposed to affect many units, selected by a regex pattern on their labels, that argument is designated R.

Apart from the (arbitrary) label, units are classified as belonging to either Neuron or Synapse class, further belonging to a certain family and species.  These categories are built-in, each species defining a set of parameters and state variables.

All available unit species are listed in Unit species.

 -- Function: get_unit_properties (C, M, L)
     Return the following attributes and properties of unit L, in order: label, class_name, family, species, as strings, followed by flags has_sources and is_not_altered.

 -- Function: get_unit_parameter (C, M, L, P)
     Get the value of unit L's parameter P.

 -- Function: set_unit_parameter (C, M, L, P, V)
     Set unit L's parameter P to a value of V.

 -- Function: get_unit_vars (C, M, L)
     Get the values of all state variables of unit L, returned as floats in the order they are listed in Unit species table.

 -- Function: reset_unit (C, M, L)
     Reset all state variables of unit L.

 -- Function: get_units_matching (C, M, R)
     Return all units with labels matching regex R.

 -- Function: get_units_of_type (C, M, sp)
     Return all units of a species SP.

 -- Function: set_matching_neuron_parameter (C, M, R, P, V)
     Set the value of parameter P to V in all neurons labelled matching regex R.

 -- Function: set_matching_synapse_parameter (C, M, Rs, Rt, P, V)
     Set the value of parameter P to V in all synapses connecting, resp., any neurons labelled matching regexes RS and RT.

 -- Function: revert_matching_unit_parameters (C, M, R)
     Revert to defaults all parameters of units labelled matching regex R.

 -- Function: decimate (C, M, R, frac)
     Delete a random FRAC of all units matching regex R.

 -- Function: putout (C, M, R)
     Delete all units matching regex R.

External excitation sources
***************************

CNrun provides for three types of external stimulation sources:

  * Tape, with all possible values defined in sequence, with timestamps, in a file, optionally looping.

  * Periodic, with a sequence of values defined to occur at regular intervals within a specified period.

  * Noise, a continuous sampling from a uniform or gaussian distribution.

 -- Function: new_tape_source (C, M, source_name, file_name, looping)
     Set up a new tape source named SOURCE_NAME, from data in file FILE_NAME.

 -- Function: new_periodic_source (C, M, source_name, file_name, looping, period)
     Set up a new periodic source named SOURCE_NAME, from data in file FILE_NAME, optionally LOOPING over a PERIOD (stuck at the last value, if not).

 -- Function: new_noise_source (C, M, source_name, min, max, sigma, distribution)
     Set up a new noise source named SOURCE_NAME, of a given DISTRIBUTION (possible values are "uniform" and "gaussian"), with given MIN, MAX, and (for the gaussian) SIGMA.

 -- Function: get_sources (C, M)
     Get all sources created in the model, returning labels as strings.

 -- Function: connect_source (C, M, L, P, source_name)
     Connect source SOURCE_NAME to parameter P of unit L.

 -- Function: disconnect_source (C, M, L, P, source_name)
     Disconnect a previously connected source SOURCE_NAME from parameter P of unit L.

Sampling state variables
************************

In addition to direct access to unit state variables in Lua (see get_unit_parameter()), there are two ways to record unit state for offline assessment:

  * Have units write their state variable(s) to logs (created in the current directory with unit labels with a suffix ``.vars'' as names);

  * Have neurons record the times of spikes (written to files similarly named except with suffix ``.spikes'').

 -- Function: start_listen (C, M, R)
     Enable logging of state variables (with options as defined in model parameter LISTEN_MODE Models) in all units labelled matching regex R.  Return the count of units affected.

 -- Function: stop_listen (C, M, R)
     Disable logging of state variables in all units labelled matching regex R.  Units writing logs will flush and close.  Return the count of units affected.

 -- Function: start_log_spikes (C, M, R)
     Enable logging of spike times in all neurons labelled matching regex R.  Return the count of units affected.

 -- Function: stop_log_spikes (C, M, R)
     Disable logging spikes in all units labelled matching regex R. Return the count of units affected.

Unit species
************

Given below are some unit species available for your models.  For a complete list, with parameter standard values and descriptions, see the output of dump_available_units().

Neuron species
==============

Species   Parameters   State vars   Description

HH
gNa, ENa, gK, EK, gl, El, Cmem, Idc
E
A classical, conductance-based Hodgkin-Huxley neuron

HHRate
a, I0, r, Idc
F
Rate-based model of the Hodgkin-Huxley neuron

DotPoisson
lambda, Vrst, Vfir
E
Duration-less spike Poisson oscillator

Poisson
lambda, trel, trel+trfr, Vrst, Vfir
E
Poisson oscillator

VdPol
eta, omegasq
A
Van der Pol oscillator

DotPulse
f, Vrst, Vfir
E
Dot Pulse generator

NMap
Vspike, alpha, gamma, beta, Idc
E
Map neuron

Synapse species
===============

In addition to parameters listed in the table, each synapse has a conductance (parameter GSYN).

Synapse   Parameters   State vars   Description

AB
Esyn, Epre, alpha, beta, trel
S
An alpha-beta synapse (Destexhe, Mainen, Sejnowsky, 1994)

Rall
Esyn, Epre, tau
S, R
Rall synapse (Rall, 1967)

Map
tau, delta, Vrev
S
Map synapse

Planned features
****************

Interconnections, both control as well as direct, asynchronous stimuli transduction, between external peer CNrun nodes.