pynestml.codegeneration package

Subpackages

Submodules

pynestml.codegeneration.autodoc_builder module

pynestml.codegeneration.autodoc_code_generator module

class pynestml.codegeneration.autodoc_code_generator.AutoDocCodeGenerator

Bases: CodeGenerator

generate_code(models: Sequence[ASTModel]) None

Generate model documentation and index page for each neuron and synapse that is provided.

generate_index(neurons: Sequence[ASTModel], synapses: Sequence[ASTModel])

Generate model documentation and index page for each neuron and synapse that is provided.

generate_neuron_code(neuron: ASTModel)

Generate model documentation for neuron model. :param neuron: a single neuron object.

generate_synapse_code(synapse: ASTModel)

Generate model documentation for synapse model. :param synapse: a single synapse object.

setup_index_generation_helpers(neurons: Sequence[ASTModel], synapses: Sequence[ASTModel])

Returns a namespace for Jinja2 neuron model index page template.

Parameters:

neurons – a list of neuron instances

Returns:

a map from name to functionality.

Return type:

dict

setup_neuron_model_generation_helpers(neuron: ASTModel)

Returns a namespace for Jinja2 neuron model documentation template.

Parameters:

neuron – a single neuron instance

Returns:

a map from name to functionality.

Return type:

dict

setup_synapse_model_generation_helpers(synapse: ASTModel)

Returns a namespace for Jinja2 synapse model documentation template.

Parameters:

neuron – a single neuron instance

Returns:

a map from name to functionality.

Return type:

dict

pynestml.codegeneration.autodoc_code_generator_utils module

pynestml.codegeneration.builder module

class pynestml.codegeneration.builder.Builder(target, options: Mapping[str, Any] | None = None)

Bases: WithOptions

Compile, build and install the code for a given target platform. Runs after the CodeGenerator.

abstract build() None
get_builder_name() str
process_output_redirection_(options)
set_options(options: Mapping[str, Any]) Mapping[str, Any]

Set options. “Eats off” any options that it knows how to set, and returns the rest as “unhandled” options.

pynestml.codegeneration.code_generator module

class pynestml.codegeneration.code_generator.CodeGenerator(target, options: Mapping[str, Any] | None = None)

Bases: WithOptions

abstract generate_code(models: Sequence[ASTModel]) None

the base class CodeGenerator does not generate any code

generate_model_code(model_name: str, model_templates: List[Template], template_namespace: Dict[str, Any], model_name_escape_string: str = '@MODEL_NAME@') None

For a handed over model, this method generates the corresponding header and implementation file. :param model_name: name of the neuron or synapse model :param model_templates: list of neuron or synapse model templates :param template_namespace: namespace for the template :param model_name_escape_string: escape string where the model name is replaced

generate_module_code(neurons: Sequence[ASTModel], synapses: Sequence[ASTModel]) None
generate_neuron_code(neuron: ASTModel) None
generate_neurons(neurons: Sequence[ASTModel]) None

Generate code for the given neurons.

Parameters:

neurons – a list of neurons.

generate_synapse_code(synapse: ASTModel) None
generate_synapses(synapses: Sequence[ASTModel]) None

Generates code for a list of synapses. :param synapses: a list of synapses.

raise_helper(msg)
setup_template_env()

Setup the Jinja2 template environment

pynestml.codegeneration.code_generator_utils module

class pynestml.codegeneration.code_generator_utils.CodeGeneratorUtils

Bases: object

classmethod get_model_types_from_names(models: List[str], neuron_models: List[str] | None = None, synapse_models: List[str] | None = None)

Returns a prefix corresponding to the origin of the variable symbol. :param variable_symbol: a single variable symbol. :return: the corresponding prefix

pynestml.codegeneration.nest_assignments_helper module

class pynestml.codegeneration.nest_assignments_helper.NestAssignmentsHelper

Bases: object

This class contains several helper functions as used during printing of code.

classmethod is_vectorized_assignment(assignment) bool

Indicates whether the handed over assignment is vectorized, i.e., an assignment of vectors. :param assignment: a single assignment. :type assignment: ASTAssignment :return: True if vectorized, otherwise False.

classmethod lhs_variable(assignment: ASTAssignment) VariableSymbol | None

Returns the corresponding symbol of the assignment. :param assignment: a single assignment. :return: a single variable symbol

classmethod lhs_vector_variable(assignment: ASTAssignment) VariableSymbol

Returns the corresponding symbol of the assignment. :param assignment: a single assignment. :return: a single variable symbol

classmethod print_assignments_operation(assignment) str

Returns a nest processable format of the assignment operation. :param assignment: a single assignment :type assignment: ASTAssignment :return: the corresponding string representation

classmethod print_size_parameter(assignment) str

Prints in a nest processable format the size parameter of the assignment. :param assignment: a single assignment :type assignment: ASTAssignment :return: the corresponding size parameter

pynestml.codegeneration.nest_builder module

class pynestml.codegeneration.nest_builder.NESTBuilder(options: Mapping[str, Any] | None = None)

Bases: Builder

Compile, build and install the NEST C++ code and NEST extension module.

build() None

This method can be used to build the generated code and install the resulting extension module into NEST.

Raises:
pynestml.codegeneration.nest_builder.add_libraries_to_sli(paths: str | Sequence[str])

This method can be used to add external modules to SLI environment

Parameters:

paths – paths to external nest modules

pynestml.codegeneration.nest_code_generator module

class pynestml.codegeneration.nest_code_generator.NESTCodeGenerator(options: Mapping[str, Any] | None = None)

Bases: CodeGenerator

Code generator for a NEST Simulator C++ extension module.

Options:

  • neuron_parent_class: The C++ class from which the generated NESTML neuron class inherits. Examples: "ArchivingNode", "StructuralPlasticityNode". Default: "ArchivingNode".

  • neuron_parent_class_include: The C++ header filename to include that contains neuron_parent_class. Default: "archiving_node.h".

  • neuron_synapse_pairs: List of pairs of (neuron, synapse) model names.

  • neuron_models: List of neuron model names. Instructs the code generator that models with these names are neuron models.

  • synapse_models: List of synapse model names. Instructs the code generator that models with these names are synapse models.

  • preserve_expressions: Set to True, or a list of strings corresponding to individual variable names, to disable internal rewriting of expressions, and return same output as input expression where possible. Only applies to variables specified as first-order differential equations. (This parameter is passed to ODE-toolbox.)

  • simplify_expression: For all expressions expr that are rewritten by ODE-toolbox: the contents of this parameter string are eval()``ed in Python to obtain the final output expression. Override for custom expression simplification steps. Example: ``sympy.simplify(expr). Default: "sympy.logcombine(sympy.powsimp(sympy.expand(expr)))". (This parameter is passed to ODE-toolbox.)

  • gap_junctions:
    • membrane_potential_variable

    • gap_current_port

  • templates: Path containing jinja templates used to generate code for NEST simulator.
    • path: Path containing jinja templates used to generate code for NEST simulator.

    • model_templates: A list of the jinja templates or a relative path to a directory containing the neuron and synapse model templates.
      • neuron: A list of neuron model jinja templates.

      • synapse: A list of synapse model jinja templates.

    • module_templates: A list of the jinja templates or a relative path to a directory containing the templates related to generating the NEST module.

  • nest_version: A string identifying the version of NEST Simulator to generate code for. The string corresponds to the NEST Simulator git repository tag or git branch name, for instance, "v2.20.2" or "master". The default is the empty string, which causes the NEST version to be automatically identified from the nest Python module.

  • solver: A string identifying the preferred ODE solver. "analytic" for propagator solver preferred; fallback to numeric solver in case ODEs are not analytically solvable. Use "numeric" to disable analytic solver.

  • numeric_solver: A string identifying the preferred numeric ODE solver. Supported are "rk45" and "forward-Euler".

  • redirect_build_output: An optional boolean key for redirecting the build output. Setting the key to True, two files will be created for redirecting the stdout and the stderr`. The ``target_path will be used as the default location for creating the two files.

  • build_output_dir: An optional string key representing the new path where the files corresponding to the output of the build phase will be created. This key requires that the redirect_build_output is set to True.

analyse_neuron(neuron: ASTModel) Tuple[Dict[str, ASTAssignment], Dict[str, ASTAssignment], List[ASTOdeEquation], List[ASTOdeEquation]]

Analyse and transform a single neuron. :param neuron: a single neuron. :return: see documentation for get_spike_update_expressions() for more information. :return: post_spike_updates: list of post-synaptic spike update expressions :return: equations_with_delay_vars: list of equations containing delay variables :return: equations_with_vector_vars: list of equations containing delay variables

analyse_synapse(synapse: ASTModel) Dict[str, ASTAssignment]

Analyse and transform a single synapse. :param synapse: a single synapse.

analyse_transform_neurons(neurons: List[ASTModel]) None

Analyse and transform a list of neurons. :param neurons: a list of neurons.

analyse_transform_synapses(synapses: List[ASTModel]) None

Analyse and transform a list of synapses. :param synapses: a list of synapses.

generate_code(models: Sequence[ASTModel]) None

the base class CodeGenerator does not generate any code

get_spike_update_expressions(neuron: ASTModel, kernel_buffers, solver_dicts, delta_factors) Tuple[Dict[str, ASTAssignment], Dict[str, ASTAssignment]]

Generate the equations that update the dynamical variables when incoming spikes arrive. To be invoked after ode-toolbox.

For example, a resulting assignment_str could be “I_kernel_in += (inh_spikes/nS) * 1”. The values are taken from the initial values for each corresponding dynamical variable, either from ode-toolbox or directly from user specification in the model. from the initial values for each corresponding dynamical variable, either from ode-toolbox or directly from user specification in the model.

Note that for kernels, initial_values actually contains the increment upon spike arrival, rather than the initial value of the corresponding ODE dimension. spike_updates is a mapping from input port name (as a string) to update expressions.

post_spike_updates is a mapping from kernel name (as a string) to update expressions.

ode_toolbox_analysis(neuron: ASTModel, kernel_buffers: Mapping[ASTKernel, ASTInputPort])

Prepare data for ODE-toolbox input format, invoke ODE-toolbox analysis via its API, and return the output.

run_nest_target_specific_cocos(neurons: Sequence[ASTModel], synapses: Sequence[ASTModel])
set_options(options: Mapping[str, Any]) Mapping[str, Any]

Set options. “Eats off” any options that it knows how to set, and returns the rest as “unhandled” options.

setup_printers()
update_symbol_table(neuron) None

Update symbol table and scope.

pynestml.codegeneration.nest_code_generator.find_spiking_post_port(synapse, namespace)

pynestml.codegeneration.nest_code_generator_utils module

class pynestml.codegeneration.nest_code_generator_utils.NESTCodeGeneratorUtils

Bases: object

classmethod generate_code_for(nestml_neuron_model: str, nestml_synapse_model: str | None = None, module_name: str | None = None, target_path: str = 'target', post_ports: List[str] | None = None, mod_ports: List[str] | None = None, logging_level: str = 'WARNING')

Generate code for a given neuron and synapse model, passed as a string. The neuron and synapse models can be passed directly as strings in NESTML syntax, or as filenames, in which case the NESTML model is loaded from the given filename.

Return type:

If a synapse is specified, returns a tuple (module_name, mangled_neuron_name, mangled_synapse_name) containing the names that can be used in nest.Install(), nest.Create() and nest.Connect() calls. If no synapse is specified, returns a tuple (module_name, mangled_neuron_name).

classmethod print_symbol_origin(variable_symbol: VariableSymbol, variable: ASTVariable) str

Returns a prefix corresponding to the origin of the variable symbol. :param variable_symbol: a single variable symbol. :return: the corresponding prefix

pynestml.codegeneration.nest_compartmental_code_generator module

class pynestml.codegeneration.nest_compartmental_code_generator.NESTCompartmentalCodeGenerator(options: Mapping[str, Any] | None = None)

Bases: CodeGenerator

Code generator for a C++ NEST extension module.

Options: - neuron_parent_class: The C++ class from which the generated NESTML neuron class inherits. Examples: "ArchivingNode", "StructuralPlasticityNode". Default: "ArchivingNode". - neuron_parent_class_include: The C++ header filename to include that contains neuron_parent_class. Default: "archiving_node.h". - preserve_expressions: Set to True, or a list of strings corresponding to individual variable names, to disable internal rewriting of expressions, and return same output as input expression where possible. Only applies to variables specified as first-order differential equations. (This parameter is passed to ODE-toolbox.) - simplify_expression: For all expressions expr that are rewritten by ODE-toolbox: the contents of this parameter string are eval()``ed in Python to obtain the final output expression. Override for custom expression simplification steps. Example: ``sympy.simplify(expr). Default: "sympy.logcombine(sympy.powsimp(sympy.expand(expr)))". (This parameter is passed to ODE-toolbox.) - templates: Path containing jinja templates used to generate code for NEST simulator.

  • path: Path containing jinja templates used to generate code for NEST simulator.

  • model_templates: A list of the jinja templates or a relative path to a directory containing the templates related to the neuron model(s).

  • module_templates: A list of the jinja templates or a relative path to a directory containing the templates related to generating the NEST module.

  • nest_version: A string identifying the version of NEST Simulator to generate code for. The string corresponds to the NEST Simulator git repository tag or git branch name, for instance, "v2.20.2" or "master". The default is the empty string, which causes the NEST version to be automatically identified from the nest Python module.

analyse_neuron(neuron: ASTModel) List[ASTAssignment]

Analyse and transform a single neuron. :param neuron: a single neuron. :return: spike_updates: list of spike updates, see documentation for get_spike_update_expressions() for more information.

analyse_transform_neurons(neurons: List[ASTModel]) None

Analyse and transform a list of neurons. :param neurons: a list of neurons.

compute_name_of_generated_file(jinja_file_name, neuron)
create_initial_values_for_ode_toolbox_odes(neuron, solver_dicts, kernel_buffers, kernels)

Add the variables used in ODEs from the ode-toolbox result dictionary as ODEs in NESTML AST.

create_ode_indict(neuron: ASTModel, parameters_block: ASTBlockWithVariables, kernel_buffers: Mapping[ASTKernel, ASTInputPort])
find_non_equations_state_variables(neuron: ASTModel)
generate_code(models: List[ASTModel]) None

the base class CodeGenerator does not generate any code

generate_module_code(neurons: List[ASTModel]) None

t Generates code that is necessary to integrate neuron models into the NEST infrastructure. :param neurons: a list of neurons

getUniqueSuffix(neuron: ASTModel) str
get_cm_syns_compartmentcurrents_file_prefix(neuron)
get_cm_syns_main_file_prefix(neuron)
get_cm_syns_tree_file_prefix(neuron)
get_spike_update_expressions(neuron: ASTModel, kernel_buffers, solver_dicts, delta_factors) List[ASTAssignment]

Generate the equations that update the dynamical variables when incoming spikes arrive. To be invoked after ode-toolbox.

For example, a resulting assignment_str could be “I_kernel_in += (in_spikes/nS) * 1”. The values are taken from the initial values for each corresponding dynamical variable, either from ode-toolbox or directly from user specification in the model.

Note that for kernels, initial_values actually contains the increment upon spike arrival, rather than the initial value of the corresponding ODE dimension.

XXX: TODO: update this function signature (+ templates) to match NESTCodegenerator::get_spike_update_expressions().

ode_solve_analytically(neuron: ASTModel, parameters_block: ASTBlockWithVariables, kernel_buffers: Mapping[ASTKernel, ASTInputPort])
ode_toolbox_analysis(neuron: ASTModel, kernel_buffers: Mapping[ASTKernel, ASTInputPort])

Prepare data for ODE-toolbox input format, invoke ODE-toolbox analysis via its API, and return the output.

raise_helper(msg)
set_options(options: Mapping[str, Any]) Mapping[str, Any]

Set options. “Eats off” any options that it knows how to set, and returns the rest as “unhandled” options.

setup_printers()
transform_ode_and_kernels_to_json(neuron: ASTModel, parameters_block, kernel_buffers)

Converts AST node to a JSON representation suitable for passing to ode-toolbox.

Each kernel has to be generated for each spike buffer convolve in which it occurs, e.g. if the NESTML model code contains the statements

convolve(G, ex_spikes) convolve(G, in_spikes)

then kernel_buffers will contain the pairs (G, ex_spikes) and (G, in_spikes), from which two ODEs will be generated, with dynamical state (variable) names G__X__ex_spikes and G__X__in_spikes.

Parameters:

parameters_block – ASTBlockWithVariables

Returns:

Dict

update_symbol_table(neuron, kernel_buffers)

Update symbol table and scope.

pynestml.codegeneration.nest_declarations_helper module

class pynestml.codegeneration.nest_declarations_helper.NestDeclarationsHelper(type_symbol_printer: TypeSymbolPrinter)

Bases: object

This class contains several methods as used during generation of code.

get_domain_from_type(type_symbol)

Returns the domain for the handed over type symbol :param type_symbol: a single type symbol :type type_symbol: type_symbol :return: the corresponding domain :rtype: str

classmethod get_variables(ast_declaration)

For a given meta_model declaration it returns a list of all corresponding variable symbols. :param ast_declaration: a single meta_model declaration. :type ast_declaration: ASTDeclaration :return: a list of all corresponding variable symbols. :rtype: list(VariableSymbol)

classmethod print_delay_parameter(variable: VariableSymbol) str

Prints the delay parameter :param variable: Variable with delay parameter :return: the corresponding delay parameter

classmethod print_size_parameter(ast_declaration) str

Prints the size parameter of a single meta_model declaration. :param ast_declaration: a single meta_model declaration. :type ast_declaration: ASTDeclaration :return: a string representation of the size parameter. :rtype: str

print_variable_type(variable_symbol) str

Prints the type of the variable symbol to a corresponding nest representation. :param variable_symbol: a single variable symbol :type variable_symbol: variable_symbol :return: a string presentation of the variable symbol’s type :rtype: str

pynestml.codegeneration.nest_tools module

class pynestml.codegeneration.nest_tools.NESTTools

Bases: object

Helper functions for NEST Simulator

classmethod detect_nest_version() str

Auto-detect NEST Simulator installed version. The returned string corresponds to a git tag or git branch name.

Do this in a separate process to avoid potential side-effects of import the nest Python module.

pynestml.codegeneration.nest_unit_converter module

class pynestml.codegeneration.nest_unit_converter.NESTUnitConverter

Bases: object

NEST Simulator uses a set of default physical units internally. This class calculates the factor needed to convert any given physical unit to its NEST counterpart.

classmethod get_factor(unit: UnitBase) float

Gives a factor for a given unit that transforms it to a “neuroscience” scale. If the given unit is not listed as a neuroscience unit, the factor is 1.

Parameters:

unit (IrreducibleUnit or Unit or CompositeUnit) – an astropy unit

Returns:

a factor to that unit, converting it to “neuroscience” scales.

pynestml.codegeneration.python_code_generator_utils module

class pynestml.codegeneration.python_code_generator_utils.PythonCodeGeneratorUtils

Bases: object

classmethod print_symbol_origin(variable_symbol: VariableSymbol, variable: ASTVariable) str

Returns a prefix corresponding to the origin of the variable symbol. :param variable_symbol: a single variable symbol. :return: the corresponding prefix

pynestml.codegeneration.python_standalone_code_generator module

class pynestml.codegeneration.python_standalone_code_generator.PythonStandaloneCodeGenerator(options: Mapping[str, Any] | None = None)

Bases: NESTCodeGenerator

Code generator for a standalone Python target.

Options:

  • neuron_models: List of neuron model names. Instructs the code generator that models with these names are neuron models.

  • synapse_models: List of synapse model names. Instructs the code generator that models with these names are synapse models.

  • preserve_expressions: Set to True, or a list of strings corresponding to individual variable names, to disable internal rewriting of expressions, and return same output as input expression where possible. Only applies to variables specified as first-order differential equations. (This parameter is passed to ODE-toolbox.)

  • simplify_expression: For all expressions expr that are rewritten by ODE-toolbox: the contents of this parameter string are eval()``ed in Python to obtain the final output expression. Override for custom expression simplification steps. Example: ``sympy.simplify(expr). Default: "sympy.logcombine(sympy.powsimp(sympy.expand(expr)))". (This parameter is passed to ODE-toolbox.)

  • templates: Path containing jinja templates used to generate code.
    • path: Path containing jinja templates used to generate code.

    • model_templates: A list of the jinja templates or a relative path to a directory containing the neuron model templates.
      • neuron: A list of neuron model jinja templates.

    • module_templates: A list of the jinja templates or a relative path to a directory containing the templates related to generating the module/package.

  • solver: A string identifying the preferred ODE solver. "analytic" for propagator solver preferred; fallback to numeric solver in case ODEs are not analytically solvable. Use "numeric" to disable analytic solver.

setup_printers()

pynestml.codegeneration.spinnaker_builder module

class pynestml.codegeneration.spinnaker_builder.SpiNNakerBuilder(options: Mapping[str, Any] | None = None)

Bases: Builder

Compiles and build the SpiNNaker generated C code.

build() None

This method can be used to build the generated code.

Raises:

pynestml.codegeneration.spinnaker_code_generator module

pynestml.codegeneration.spinnaker_code_generator_utils module

class pynestml.codegeneration.spinnaker_code_generator_utils.SPINNAKERCodeGeneratorUtils

Bases: object

classmethod print_symbol_origin(variable_symbol: VariableSymbol, numerical_state_symbols=None) str

Returns a prefix corresponding to the origin of the variable symbol. :param variable_symbol: a single variable symbol. :return: the corresponding prefix

pynestml.codegeneration.spinnaker_unit_converter module

class pynestml.codegeneration.spinnaker_unit_converter.SpinnakerUnitConverter

Bases: object

NEST Simulator uses a set of default physical units internally. This class calculates the factor needed to convert any given physical unit to its NEST counterpart.

classmethod get_factor(unit: UnitBase) float

Gives a factor for a given unit that transforms it to a “neuroscience” scale. If the given unit is not listed as a neuroscience unit, the factor is 1.

Parameters:

unit (IrreducibleUnit or Unit or CompositeUnit) – an astropy unit

Returns:

a factor to that unit, converting it to “neuroscience” scales.