Main module (API)#

For more details regarding the main classes, see:

NNGT#

Package aimed at facilitating the analysis of Neural Networks and Graphs’ Topologies in Python by providing a unified interface for network generation and analysis.

The library mainly provides algorithms for

  1. generating networks

  2. studying their topological properties

  3. doing some basic spatial, topological, and statistical visualizations

  4. interacting with neuronal simulators and analyzing neuronal activity

Available modules#

analysis

Tools to study graph topology and neuronal activity.

core

Where the main classes are coded; however, most useful classes and methods for users are loaded at the main level (nngt) when the library is imported, so nngt.core should generally not be used.

generation

Functions to generate specific networks.

geometry

Tools to work on metric graphs (see PyNCulture).

io

Tools for input/output operations.

lib

Basic functions used by several most other modules.

simulation

Tools to provide complex network generation with NEST and help analyze the influence of the network structure on neuronal activity.

plot

Plot data or graphs using matplotlib.

Units#

Functions related to spatial embedding of networks are using micrometers (um) as default unit; other units from the metric system can also be provided:

  • mm for milimeters

  • cm centimeters

  • dm for decimeters

  • m for meters

Main classes and functions#

nngt.Graph(*args, **kwargs)

The basic graph class, which inherits from a library class such as graph_tool.Graph, networkx.DiGraph, or igraph.Graph.

nngt.Group([nodes, properties, name])

Class defining groups of nodes.

nngt.GroupProperty(size[, constraints, ...])

Class defining the properties needed to create groups of neurons from an existing Graph or one of its subclasses.

nngt.MetaGroup([nodes, properties, name])

Class defining a meta-group of nodes.

nngt.MetaNeuralGroup([nodes, neuron_type, ...])

Class defining a meta-group of neurons.

nngt.Network(*args, **kwargs)

The detailed class that inherits from Graph and implements additional properties to describe various biological functions and interact with the NEST simulator.

nngt.NeuralGroup([nodes, neuron_type, ...])

Class defining groups of neurons.

nngt.NeuralPop([size, parent, meta_groups, ...])

The basic class that contains groups of neurons and their properties.

nngt.SpatialGraph(*args, **kwargs)

The detailed class that inherits from Graph and implements additional properties to describe spatial graphs (i.e.

nngt.SpatialNetwork(*args, **kwargs)

Class that inherits from Network and SpatialGraph to provide a detailed description of a real neural network in space, i.e. with positions and biological properties to interact with NEST.

nngt.Structure([size, parent, meta_groups])

The basic class that contains groups of nodes and their properties.

nngt.generate(di_instructions, **kwargs)

Generate a Graph or one of its subclasses from a dict containing all the relevant informations.

nngt.get_config([key, detailed])

Get the NNGT configuration as a dictionary.

nngt.load_from_file(filename[, fmt, ...])

Load a Graph from a file.

nngt.num_mpi_processes()

Returns the number of MPI processes (1 if MPI is not used)

nngt.on_master_process()

Check whether the current code is executing on the master process (rank 0) if MPI is used.

nngt.reset_config()

Removed saved configuration and switch back to default

nngt.save_config()

Save configuration to make it persistent

nngt.save_to_file(graph, filename[, fmt, ...])

Save a graph to file.

nngt.seed([msd, seeds])

Seed the random generator used by NNGT (i.e.

nngt.set_config(config[, value, silent])

Set NNGT's configuration.

nngt.use_backend(backend[, reloading, silent])

Allows the user to switch to a specific graph library as backend.

Details#

class nngt.Graph(*args, **kwargs)[source]#

The basic graph class, which inherits from a library class such as graph_tool.Graph, networkx.DiGraph, or igraph.Graph.

The objects provides several functions to easily access some basic properties.

Initialize Graph instance

Changed in version 2.0: Renamed from_graph to copy_graph.

Changed in version 2.2: Added structure argument.

Parameters:
  • nodes (int, optional (default: 0)) – Number of nodes in the graph.

  • name (string, optional (default: “Graph”)) – The name of this Graph instance.

  • weighted (bool, optional (default: True)) – Whether the graph edges have weight properties.

  • directed (bool, optional (default: True)) – Whether the graph is directed or undirected.

  • copy_graph (Graph, optional) – An optional Graph that will be copied.

  • structure (Structure, optional (default: None)) – A structure dividing the graph into specific groups, which can be used to generate specific connectivities and visualise the connections in a more coarse-grained manner.

  • kwargs (optional keywords arguments) – Optional arguments that can be passed to the graph, e.g. a dict containing information on the synaptic weights (weights={"distribution": "constant", "value": 2.3} which is equivalent to weights=2.3), the synaptic delays, or a type information.

Note

When using copy_graph, only the topological properties are copied (nodes, edges, and attributes), spatial and biological properties are ignored. To copy a graph exactly, use copy().

Returns:

self (Graph)

class nngt.Group(nodes=None, properties=None, name=None, **kwargs)[source]#

Class defining groups of nodes.

Its main variables are:

Variables:
  • ~nngt.Group.idslist of int the ids of the nodes in this group.

  • ~nngt.Group.properties – dict, optional (default: {}) properties associated to the nodes

  • ~nngt.Group.is_metagroupbool whether the group is a meta-group or not.

Note

A Group contains a set of nodes that are unique; the size of the group is the number of unique nodes contained in the group. Passing non-unique nodes will automatically convert them to a unique set.

Warning

Equality between Group`s only compares the  size and ``properties` attributes. This means that groups differing only by their ids will register as equal.

Calling the class creates a group of nodes. The default is an empty group but it is not a valid object for most use cases.

Parameters:
  • nodes (int or array-like, optional (default: None)) – Desired size of the group or, a posteriori, NNGT indices of the nodes in an existing graph.

  • properties (dict, optional (default: {})) – Dictionary containing the properties associated to the nodes.

Returns:

A new Group instance.

class nngt.GroupProperty(size, constraints={}, neuron_model=None, neuron_param={}, syn_model=None, syn_param={})[source]#

Class defining the properties needed to create groups of neurons from an existing Graph or one of its subclasses.

Variables:
  • ~nngt.GroupProperty.sizeint Size of the group.

  • constraintsdict, optional (default: {}) Constraints to respect when building the NeuralGroup .

  • ~nngt.GroupProperty.neuron_model – str, optional (default: None) name of the model to use when simulating the activity of this group.

  • ~nngt.GroupProperty.neuron_param – dict, optional (default: {}) the parameters to use (if they differ from the model’s defaults)

Create a new instance of GroupProperties.

Notes

The constraints can be chosen among:
  • “avg_deg”, “min_deg”, “max_deg” (int) to constrain the total degree of the nodes

  • “avg/min/max_in_deg”, “avg/min/max_out_deg”, to work with the in/out-degrees

  • “avg/min/max_betw” (double) to constrain the betweenness centrality

  • “in_shape” (nngt.geometry.Shape) to chose neurons inside a given spatial region

Examples

>>> di_constrain = { "avg_deg": 10, "min_betw": 0.001 }
>>> group_prop = GroupProperties(200, constraints=di_constrain)
class nngt.MetaGroup(nodes=None, properties=None, name=None, **kwargs)[source]#

Class defining a meta-group of nodes.

Its main variables are:

Variables:

~nngt.MetaGroup.idslist of int the ids of the nodes in this group.

Calling the class creates a group of nodes. The default is an empty group but it is not a valid object for most use cases.

Parameters:
  • nodes (int or array-like, optional (default: None)) – Desired size of the group or, a posteriori, NNGT indices of the nodes in an existing graph.

  • name (str, optional (default: “Group N”)) – Name of the meta-group.

Returns:

A new MetaGroup object.

class nngt.MetaNeuralGroup(nodes=None, neuron_type='undefined', neuron_model=None, neuron_param=None, name=None, **kwargs)[source]#

Class defining a meta-group of neurons.

Its main variables are:

Variables:
  • ~nngt.MetaGroup.idslist of int the ids of the neurons in this group.

  • ~nngt.MetaGroup.is_metagroupbool whether the group is a meta-group or not (neuron_type is None for meta-groups)

Calling the class creates a group of neurons. The default is an empty group but it is not a valid object for most use cases.

Parameters:
  • nodes (int or array-like, optional (default: None)) – Desired size of the group or, a posteriori, NNGT indices of the neurons in an existing graph.

  • name (str, optional (default: “Group N”)) – Name of the meta-group.

Returns:

A new MetaNeuralGroup object.

class nngt.Network(*args, **kwargs)[source]#

The detailed class that inherits from Graph and implements additional properties to describe various biological functions and interact with the NEST simulator.

Initializes Network instance.

Parameters:
  • nodes (int, optional (default: 0)) – Number of nodes in the graph.

  • name (string, optional (default: “Graph”)) – The name of this Graph instance.

  • weighted (bool, optional (default: True)) – Whether the graph edges have weight properties.

  • directed (bool, optional (default: True)) – Whether the graph is directed or undirected.

  • copy_graph (GraphObject, optional (default: None)) – An optional GraphObject to serve as base.

  • population (nngt.NeuralPop, (default: None)) – An object containing the neural groups and their properties: model(s) to use in NEST to simulate the neurons as well as their parameters.

  • inh_weight_factor (float, optional (default: 1.)) – Factor to apply to inhibitory synapses, to compensate for example the strength difference due to timescales between excitatory and inhibitory synapses.

Returns:

self (Network)

class nngt.NeuralGroup(nodes=None, neuron_type='undefined', neuron_model=None, neuron_param=None, name=None, **kwargs)[source]#

Class defining groups of neurons.

Its main variables are:

Variables:
  • ~nngt.NeuralGroup.idslist of int the ids of the neurons in this group.

  • ~nngt.NeuralGroup.neuron_typeint the default is 1 for excitatory neurons; -1 is for inhibitory neurons; meta-groups must have neuron_type set to None

  • ~nngt.NeuralGroup.neuron_model – str, optional (default: None) the name of the model to use when simulating the activity of this group

  • ~nngt.NeuralGroup.neuron_param – dict, optional (default: {}) the parameters to use (if they differ from the model’s defaults)

  • ~nngt.NeuralGroup.is_metagroupbool whether the group is a meta-group or not (neuron_type is None for meta-groups)

Warning

Equality between NeuralGroup`s only compares the  size and neuronal type, ``model` and param attributes. This means that groups differing only by their ids will register as equal.

Calling the class creates a group of neurons. The default is an empty group but it is not a valid object for most use cases.

Parameters:
  • nodes (int or array-like, optional (default: None)) – Desired size of the group or, a posteriori, NNGT indices of the neurons in an existing graph.

  • neuron_type (int, optional (default: 1)) – Type of the neurons (1 for excitatory, -1 for inhibitory) or None if not relevant (only allowed for metag roups).

  • neuron_model (str, optional (default: None)) – NEST model for the neuron.

  • neuron_param (dict, optional (default: model defaults)) – Dictionary containing the parameters associated to the NEST model.

Returns:

A new NeuralGroup instance.

class nngt.NeuralPop(size=None, parent=None, meta_groups=None, with_models=True, **kwargs)[source]#

The basic class that contains groups of neurons and their properties.

Variables:
  • has_modelsbool, True if every group has a model attribute.

  • ~nngt.NeuralPop.sizeint, Returns the number of neurons in the population.

  • syn_specdict, Dictionary containing informations about the synapses between the different groups in the population.

  • ~nngt.NeuralPop.is_validbool, Whether this population can be used to create a network in NEST.

Initialize NeuralPop instance.

Parameters:
  • size (int, optional (default: 0)) – Number of neurons that the population will contain.

  • parent (Network, optional (default: None)) – Network associated to this population.

  • meta_groups (dict of str/NeuralGroup items) – Optional set of groups. Contrary to the primary groups which define the population and must be disjoint, meta groups can overlap: a neuron can belong to several different meta groups.

  • with_models (bool) – whether the population’s groups contain models to use in NEST

  • *args (items for OrderedDict parent)

  • **kwargs (dict)

Returns:

pop (NeuralPop object.)

class nngt.SpatialGraph(*args, **kwargs)[source]#

The detailed class that inherits from Graph and implements additional properties to describe spatial graphs (i.e. graph where the structure is embedded in space.

Initialize SpatialClass instance.

Parameters:
  • nodes (int, optional (default: 0)) – Number of nodes in the graph.

  • name (string, optional (default: “Graph”)) – The name of this Graph instance.

  • weighted (bool, optional (default: True)) – Whether the graph edges have weight properties.

  • directed (bool, optional (default: True)) – Whether the graph is directed or undirected.

  • shape (Shape, optional (default: None)) – Shape of the neurons’ environment (None leads to a square of side 1 cm)

  • positions (numpy.array (N, 2), optional (default: None)) – Positions of the neurons; if not specified and nodes is not 0, then neurons will be reparted at random inside the Shape object of the instance.

  • **kwargs (keyword arguments for Graph or) – Shape if no shape was given.

Returns:

self (SpatialGraph)

class nngt.SpatialNetwork(*args, **kwargs)[source]#

Class that inherits from Network and SpatialGraph to provide a detailed description of a real neural network in space, i.e. with positions and biological properties to interact with NEST.

Initialize SpatialNetwork instance.

Parameters:
  • name (string, optional (default: “Graph”)) – The name of this Graph instance.

  • weighted (bool, optional (default: True)) – Whether the graph edges have weight properties.

  • directed (bool, optional (default: True)) – Whether the graph is directed or undirected.

  • shape (Shape, optional (default: None)) – Shape of the neurons’ environment (None leads to a square of side 1 cm)

  • positions (numpy.array, optional (default: None)) – Positions of the neurons; if not specified and nodes != 0, then neurons will be reparted at random inside the Shape object of the instance.

  • population (class:~nngt.NeuralPop, optional (default: None)) – Population from which the network will be built.

Returns:

self (SpatialNetwork)

class nngt.Structure(size=None, parent=None, meta_groups=None, **kwargs)[source]#

The basic class that contains groups of nodes and their properties.

Variables:
  • ~nngt.Structure.idslst, Returns the ids of nodes in the structure.

  • ~nngt.Structure.is_validbool, Whether the structure is consistent with its associated network.

  • ~nngt.Structure.parentNetwork, Parent network.

  • ~nngt.Structure.sizeint, Returns the number of nodes in the structure.

Initialize Structure instance.

Parameters:
  • size (int, optional (default: 0)) – Number of nodes that the structure will contain.

  • parent (Network, optional (default: None)) – Network associated to this structure.

  • meta_groups (dict of str/Group items) – Optional set of groups. Contrary to the primary groups which define the structure and must be disjoint, meta groups can overlap: a neuron can belong to several different meta groups.

  • **kwargs (dict)

Returns:

struct (Structure object.)

nngt.generate(di_instructions, **kwargs)[source]#

Generate a Graph or one of its subclasses from a dict containing all the relevant informations.

Parameters:

di_instructions (dict) – Dictionary containing the instructions to generate the graph. It must have at least "graph_type" in its keys, with a value among "distance_rule", "erdos_renyi", "fixed_degree", "newman_watts", "price_scale_free", "random_scale_free". Depending on the type, di_instructions should also contain at least all non-optional arguments of the generator function.

See also

generation

nngt.get_config(key=None, detailed=False)[source]#

Get the NNGT configuration as a dictionary.

Note

This function has no MPI barrier on it.

nngt.load_from_file(filename, fmt='auto', separator=' ', secondary=';', attributes=None, attributes_types=None, notifier='@', ignore='#', name='LoadedGraph', directed=True, cleanup=False)[source]#

Load a Graph from a file.

Changed in version 2.0: Added optional attributes_types and cleanup arguments.

Warning

Support for GraphML and DOT formats are currently limited and require one of the non-default backends (DOT requires graph-tool).

Parameters:
  • filename (str) – The path to the file.

  • fmt (str, optional (default: “neighbour”)) – The format used to save the graph. Supported formats are: “neighbour” (neighbour list, default if format cannot be deduced automatically), “ssp” (scipy.sparse), “edge_list” (list of all the edges in the graph, one edge per line, represented by a source target-pair), “gml” (gml format, default if filename ends with ‘.gml’), “graphml” (graphml format, default if filename ends with ‘.graphml’ or ‘.xml’), “dot” (dot format, default if filename ends with ‘.dot’), “gt” (only when using graph_tool`<http://graph-tool.skewed.de/>_ as library, detected if `filename ends with ‘.gt’).

  • separator (str, optional (default “ “)) – separator used to separate inputs in the case of custom formats (namely “neighbour” and “edge_list”)

  • secondary (str, optional (default: “;”)) – Secondary separator used to separate attributes in the case of custom formats.

  • attributes (list, optional (default: [])) – List of names for the attributes present in the file. If a notifier is present in the file, names will be deduced from it; otherwise the attributes will be numbered. For “edge_list”, attributes may also be present as additional columns after the source and the target.

  • attributes_types (dict, optional (default: str)) – Backup information if the type of the attributes is not specified in the file. Values must be callables (types or functions) that will take the argument value as a string input and convert it to the proper type.

  • notifier (str, optional (default: “@”)) – Symbol specifying the following as meaningfull information. Relevant information are formatted @info_name=info_value, where info_name is in (“attributes”, “directed”, “name”, “size”) and associated info_value are of type (list, bool, str, int). Additional notifiers are @type=SpatialGraph/Network/SpatialNetwork, which must be followed by the relevant notifiers among @shape, @structure, and @graph.

  • ignore (str, optional (default: “#”)) – Ignore lines starting with the ignore string.

  • name (str, optional (default: from file information or ‘LoadedGraph’)) – The name of the graph.

  • directed (bool, optional (default: from file information or True)) – Whether the graph is directed or not.

  • cleanup (bool, optional (default: False)) – If true, removes nodes before the first one that appears in the edges and after the last one and renumber the nodes from 0.

Returns:

graph (Graph or subclass) – Loaded graph.

nngt.num_mpi_processes()[source]#

Returns the number of MPI processes (1 if MPI is not used)

nngt.on_master_process()[source]#

Check whether the current code is executing on the master process (rank 0) if MPI is used.

Returns:

  • True if rank is 0, if mpi4py is not present or if MPI is not used,

  • otherwise False.

nngt.reset_config()[source]#

Removed saved configuration and switch back to default

nngt.save_config()[source]#

Save configuration to make it persistent

nngt.save_to_file(graph, filename, fmt='auto', separator=' ', secondary=';', attributes=None, notifier='@')[source]#

Save a graph to file.

@todo: implement dot, xml/graphml, and gt formats

Parameters:
  • graph (Graph or subclass) – Graph to save.

  • filename (str) – The path to the file.

  • fmt (str, optional (default: “auto”)) – The format used to save the graph. Supported formats are: “neighbour” (neighbour list, default if format cannot be deduced automatically), “ssp” (scipy.sparse), “edge_list” (list of all the edges in the graph, one edge per line, represented by a source target-pair), “gml” (gml format, default if filename ends with ‘.gml’), “graphml” (graphml format, default if filename ends with ‘.graphml’ or ‘.xml’), “dot” (dot format, default if filename ends with ‘.dot’), “gt” (only when using graph_tool as library, detected if filename ends with ‘.gt’).

  • separator (str, optional (default “ “)) – separator used to separate inputs in the case of custom formats (namely “neighbour” and “edge_list”)

  • secondary (str, optional (default: “;”)) – Secondary separator used to separate attributes in the case of custom formats.

  • attributes (list, optional (default: None)) – List of names for the edge attributes present in the graph that will be saved to disk; by default (None), all attributes will be saved.

  • notifier (str, optional (default: “@”)) – Symbol specifying the following as meaningfull information. Relevant information are formatted @info_name=info_value, with info_name in (“attributes”, “attr_types”, “directed”, “name”, “size”). Additional notifiers are @type=SpatialGraph/Network/SpatialNetwork, which are followed by the relevant notifiers among @shape, @structure, and @graph to separate the sections.

Note

Positions are saved as bytes by numpy.nparray.tostring()

nngt.seed(msd=None, seeds=None)[source]#

Seed the random generator used by NNGT (i.e. the numpy RandomState: for details, see numpy.random.RandomState).

Parameters:
  • msd (int, optional) – Master seed for numpy RandomState. Must be convertible to 32-bit unsigned integers.

  • seeds (list of ints, optional) – Seeds for RandomState (when using MPI). Must be convertible to 32-bit unsigned integers, one entry per MPI process.

nngt.set_config(config, value=None, silent=False)[source]#

Set NNGT’s configuration.

Parameters:
  • config (dict or str) – Either a full configuration dictionary or one key to be set together with its associated value.

  • value (object, optional (default: None)) – Value associated to config if config is a key.

Examples

>>> nngt.set_config({'multithreading': True, 'omp': 4})
>>> nngt.set_config('multithreading', False)

Notes

See the config file nngt/nngt.conf.default or ~/.nngt/nngt.conf for details about your configuration.

This function has an MPI barrier on it, so it must always be called on all processes.

See also

get_config()

nngt.use_backend(backend, reloading=True, silent=False)[source]#

Allows the user to switch to a specific graph library as backend.

Warning

If Graph objects have already been created, they will no longer be compatible with NNGT methods.

Parameters:
  • backend (string) – Name of a graph library among ‘graph_tool’, ‘igraph’, ‘networkx’, or ‘nngt’.

  • reloading (bool, optional (default: True)) – Whether the graph objects should be reloaded through reload (this should always be set to True except when NNGT is first initiated!)

  • silent (bool, optional (default: False)) – Whether the changes made to the configuration should be logged at the DEBUG (True) or INFO (False) level.