Graph classes#

NNGT provides four main graph classes that provide specific features to work as conveniently as possible with different object types: topological versus space-embedded graphs or neuronal networks.

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.SpatialGraph(*args, **kwargs)

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

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.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.

A summary of the methods provided by these classes as well as more detailed descriptions are provided below. Unless specified, child classes can use all methods from the parent class (the only exception is set_types() which is not available to the Network subclasses).

Summary of the class members and methods#

Graph#

The main class for topological graphs.

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.Graph.adjacency_matrix([types, ...])

Return the graph adjacency matrix.

nngt.Graph.clear_all_edges()

Remove all edges from the graph

nngt.Graph.copy()

Returns a deepcopy of the current Graph instance

nngt.Graph.delete_edges(edges)

Remove a list of edges

nngt.Graph.delete_nodes(nodes)

Remove nodes (and associated edges) from the graph.

nngt.Graph.edge_attributes

Access edge attributes.

nngt.Graph.edge_id(edge)

Return the ID a given edge or a list of edges in the graph.

nngt.Graph.edge_nb()

Number of edges in the graph

nngt.Graph.edges_array

Edges of the graph, sorted by order of creation, as an array of 2-tuple.

nngt.Graph.from_file(filename[, fmt, ...])

Import a saved graph from a file.

nngt.Graph.from_library(library_graph[, ...])

Create a Graph by wrapping a graph object from one of the supported libraries.

nngt.Graph.from_matrix(matrix[, weighted, ...])

Creates a Graph from a scipy.sparse matrix or a dense matrix.

nngt.Graph.get_attribute_type(attribute_name)

Return the type of an attribute (e.g.

nngt.Graph.get_betweenness([btype, weights])

Returns the normalized betweenness centrality of the nodes and edges.

nngt.Graph.get_degrees([mode, nodes, ...])

Degree sequence of all the nodes.

nngt.Graph.get_delays([edges])

Returns the delays of all or a subset of the edges.

nngt.Graph.get_density()

Density of the graph: \frac{E}{N^2}, where E is the number of edges and N the number of nodes.

nngt.Graph.get_edge_attributes([edges, name])

Attributes of the graph's edges.

nngt.Graph.get_edge_types([edges])

Return the type of all or a subset of the edges.

nngt.Graph.get_edges([attribute, value, ...])

Return the edges in the network fulfilling a given condition.

nngt.Graph.get_node_attributes([nodes, name])

Attributes of the graph's edges.

nngt.Graph.get_nodes([attribute, value])

Return the nodes in the network fulfilling a given condition.

nngt.Graph.get_structure_graph()

Return a coarse-grained version of the graph containing one node per nngt.Group.

nngt.Graph.get_weights([edges])

Returns the weights of all or a subset of the edges.

nngt.Graph.graph

Returns the underlying library object.

nngt.Graph.graph_id

Unique int identifying the instance.

nngt.Graph.has_edge(edge)

Whether edge is present in the graph.

nngt.Graph.is_connected([mode])

Return whether the graph is connected.

nngt.Graph.is_directed()

Whether the graph is directed or not

nngt.Graph.is_network()

Whether the graph is a subclass of Network (i.e.

nngt.Graph.is_spatial()

Whether the graph is embedded in space (i.e.

nngt.Graph.is_weighted()

Whether the edges have weights

nngt.Graph.make_network(graph, neural_pop[, ...])

Turn a Graph object into a Network, or a SpatialGraph into a SpatialNetwork.

nngt.Graph.make_spatial(graph[, shape, ...])

Turn a Graph object into a SpatialGraph, or a Network into a SpatialNetwork.

nngt.Graph.name

Name of the graph.

nngt.Graph.neighbours(node[, mode])

Return the neighbours of node.

nngt.Graph.new_edge(source, target[, ...])

Adding a connection to the graph, with optional properties.

nngt.Graph.new_edge_attribute(name, value_type)

Create a new attribute for the edges.

nngt.Graph.new_edges(edge_list[, ...])

Add a list of edges to the graph.

nngt.Graph.new_node([n, neuron_type, ...])

Adding a node to the graph, with optional properties.

nngt.Graph.new_node_attribute(name, value_type)

Create a new attribute for the nodes.

nngt.Graph.node_attributes

Access node attributes.

nngt.Graph.node_nb()

Number of nodes in the graph

nngt.Graph.num_graphs()

Returns the number of alive instances.

nngt.Graph.set_delays([delay, elist, ...])

Set the delay for spike propagation between neurons.

nngt.Graph.set_edge_attribute(attribute[, ...])

Set attributes to the connections between neurons.

nngt.Graph.set_name([name])

Set graph name

nngt.Graph.set_node_attribute(attribute[, ...])

Set attributes to the connections between neurons.

nngt.Graph.set_types(edge_type[, nodes, ...])

Set the synaptic/connection types.

nngt.Graph.set_weights([weight, elist, ...])

Set the synaptic weights.

nngt.Graph.structure

Object structuring the graph into specific groups.

nngt.Graph.to_file(filename[, fmt, ...])

Save graph to file; options detailed below.

nngt.Graph.to_undirected([combine_numeric_eattr])

Convert the graph to its undirected variant.

nngt.Graph.type

Type of the graph.

SpatialGraph#

Subclass of Graph providing additional tools to work with spatial graphs. It works together with the Shape object from the geometry module.

nngt.SpatialGraph(*args, **kwargs)

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

nngt.SpatialGraph.get_positions([nodes])

Returns a copy of the nodes' positions as a (N, 2) array.

nngt.SpatialGraph.set_positions(positions[, ...])

Set the nodes' positions as a (N, 2) array.

nngt.SpatialGraph.shape

The environment's spatial structure.

Network#

Subclass of Graph providing additional tools to work with neuronal networks. It works together with the NeuralPop object.

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.Network.exc_and_inhib(size[, iratio, ...])

Generate a network containing a population of two neural groups: inhibitory and excitatory neurons.

nngt.Network.from_gids(gids[, ...])

Generate a network from gids.

nngt.Network.get_neuron_type(neuron_ids)

Return the type of the neurons (+1 for excitatory, -1 for inhibitory).

nngt.Network.id_from_nest_gid(gids)

Return the ids of the nodes in the nngt.Network instance from the corresponding NEST gids.

nngt.Network.nest_gids

nngt.Network.neuron_properties(idx_neuron)

Properties of a neuron in the graph.

nngt.Network.num_networks()

Returns the number of alive instances.

nngt.Network.population

NeuralPop that divides the neurons into groups with specific properties.

nngt.Network.to_nest([send_only, weights])

Send the network to NEST.

nngt.Network.uniform(size[, neuron_model, ...])

Generate a network containing only one type of neurons.

SpatialNetwork#

Subclass of Graph providing additional tools to work with spatial neuronal networks. It works together with both NeuralPop and the Shape object from the geometry module.

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.SpatialNetwork.exc_and_inhib(size[, ...])

Generate a network containing a population of two neural groups: inhibitory and excitatory neurons.

nngt.SpatialNetwork.from_gids(gids[, ...])

Generate a network from gids.

nngt.SpatialNetwork.get_neuron_type(neuron_ids)

Return the type of the neurons (+1 for excitatory, -1 for inhibitory).

nngt.SpatialNetwork.get_positions([nodes])

Returns a copy of the nodes' positions as a (N, 2) array.

nngt.SpatialNetwork.id_from_nest_gid(gids)

Return the ids of the nodes in the nngt.Network instance from the corresponding NEST gids.

nngt.SpatialNetwork.nest_gids

nngt.SpatialNetwork.neuron_properties(idx_neuron)

Properties of a neuron in the graph.

nngt.SpatialNetwork.num_networks()

Returns the number of alive instances.

nngt.SpatialNetwork.population

NeuralPop that divides the neurons into groups with specific properties.

nngt.SpatialNetwork.set_positions(positions)

Set the nodes' positions as a (N, 2) array.

nngt.SpatialNetwork.shape

The environment's spatial structure.

nngt.SpatialNetwork.to_nest([send_only, weights])

Send the network to NEST.

nngt.SpatialNetwork.uniform(size[, ...])

Generate a network containing only one type of neurons.

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)

adjacency_matrix(types=False, weights=False, mformat='csr')[source]#

Return the graph adjacency matrix.

Note

Source nodes are represented by the rows, targets by the corresponding columns.

Parameters
  • types (bool, optional (default: False)) – Wether the edge types should be taken into account (negative values for inhibitory connections).

  • weights (bool or string, optional (default: False)) – Whether the adjacecy matrix should be weighted. If True, all connections are multiply bythe associated synaptic strength; if weight is a string, the connections are scaled bythe corresponding edge attribute.

  • mformat (str, optional (default: “csr”)) – Type of scipy.sparse matrix that will be returned, by default scipy.sparse.csr_matrix.

Returns

mat (scipy.sparse matrix) – The adjacency matrix of the graph.

clear_all_edges()#

Remove all edges from the graph

copy()[source]#

Returns a deepcopy of the current Graph instance

delete_edges(edges)#

Remove a list of edges

delete_nodes(nodes)#

Remove nodes (and associated edges) from the graph.

property edge_attributes#

Access edge attributes.

edge_id(edge)#

Return the ID a given edge or a list of edges in the graph. Raises an error if the edge is not in the graph or if one of the vertices in the edge is nonexistent.

Parameters

edge (2-tuple or array of edges) – Edge descriptor (source, target).

Returns

index (int or array of ints) – Index of the given edge.

edge_nb()#

Number of edges in the graph

property edges_array#

Edges of the graph, sorted by order of creation, as an array of 2-tuple.

static from_file(filename, fmt='auto', separator=' ', secondary=';', attributes=None, attributes_types=None, notifier='@', ignore='#', from_string=False, name=None, directed=True, cleanup=False)[source]#

Import a saved graph from a file.

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

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

  • fmt (str, optional (default: deduced from filename)) – The format used to save the graph. Supported formats are: “neighbour” (neighbour list), “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: [])) – 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, @population, and @graph.

  • from_string (bool, optional (default: False)) – Load from a string instead of a file.

  • 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.

classmethod from_library(library_graph, name='ImportedGraph', weighted=True, directed=True, **kwargs)[source]#

Create a Graph by wrapping a graph object from one of the supported libraries.

Parameters
  • library_graph (object) – Graph object from one of the supported libraries (graph-tool, igraph, networkx).

  • name (str, optional (default: “ImportedGraph”))

  • **kwargs – Other standard arguments (see __init__())

classmethod from_matrix(matrix, weighted=True, directed=True, population=None, shape=None, positions=None, name=None, **kwargs)[source]#

Creates a Graph from a scipy.sparse matrix or a dense matrix.

Parameters
  • matrix (scipy.sparse matrix or numpy.ndarray) – Adjacency matrix.

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

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

  • population (NeuralPop) – Population to associate to the new Network.

  • shape (Shape, optional (default: None)) – Shape to associate to the new SpatialGraph.

  • positions ((N, 2) array) – Positions, in a 2D space, of the N neurons.

  • name (str, optional) – Graph name.

Returns

Graph

get_attribute_type(attribute_name, attribute_class=None)[source]#

Return the type of an attribute (e.g. string, double, int).

Parameters
  • attribute_name (str) – Name of the attribute.

  • attribute_class (str, optional (default: both)) – Whether attribute_name is a “node” or an “edge” attribute.

Returns

type (str) – Type of the attribute.

get_betweenness(btype='both', weights=None)[source]#

Returns the normalized betweenness centrality of the nodes and edges.

Parameters
  • g (Graph) – Graph to analyze.

  • btype (str, optional (default ‘both’)) – The centrality that should be returned (either ‘node’, ‘edge’, or ‘both’). By default, both betweenness centralities are computed.

  • weights (bool or str, optional (default: binary edges)) – Whether edge weights should be considered; if None or False then use binary edges; if True, uses the ‘weight’ edge attribute, otherwise uses any valid edge attribute required.

Returns

  • nb (numpy.ndarray) – The nodes’ betweenness if btype is ‘node’ or ‘both’

  • eb (numpy.ndarray) – The edges’ betweenness if btype is ‘edge’ or ‘both’

See also

betweenness()

get_degrees(mode='total', nodes=None, weights=None, edge_type='all')[source]#

Degree sequence of all the nodes.

Changed in version 2.0: Changed deg_type to mode, node_list to nodes, use_weights to weights, and edge_type to edge_type.

Parameters
  • mode (string, optional (default: “total”)) – Degree type (among ‘in’, ‘out’ or ‘total’).

  • nodes (list, optional (default: None)) – List of the nodes which degree should be returned

  • weights (bool or str, optional (default: binary edges)) – Whether edge weights should be considered; if None or False then use binary edges; if True, uses the ‘weight’ edge attribute, otherwise uses any valid edge attribute required.

  • edge_type (int or str, optional (default: all)) – Restrict to a given synaptic type (“excitatory”, 1, or “inhibitory”, -1), using either the “type” edge attribute for non-Network or the inhibitory nodes.

Returns

  • degrees (numpy.array)

  • .. warning :: – When using MPI with “nngt” (distributed) backend, returns only the degrees associated to local edges. “Complete” degrees are obtained by taking the sum of the results on all MPI processes.

get_delays(edges=None)[source]#

Returns the delays of all or a subset of the edges.

Changed in version 1.0.1: Added the possibility to ask for a subset of edges.

Parameters

edges ((E, 2) array, optional (default: all edges)) – Edges for which the type should be returned.

Returns

the list of delays

get_density()[source]#

Density of the graph: \frac{E}{N^2}, where E is the number of edges and N the number of nodes.

get_edge_attributes(edges=None, name=None)[source]#

Attributes of the graph’s edges.

Parameters
  • edges (tuple or list of tuples, optional (default: None)) – Edge whose attribute should be displayed.

  • name (str, optional (default: None)) – Name of the desired attribute.

Returns

  • Dict containing all graph’s attributes (synaptic weights, delays…)

  • by default. If edge is specified, returns only the values for these

  • edges. If name is specified, returns value of the attribute for each

  • edge.

Note

The attributes values are ordered as the edges in edges_array() if edges is None.

get_edge_types(edges=None)[source]#

Return the type of all or a subset of the edges.

Parameters

edges ((E, 2) array, optional (default: all edges)) – Edges for which the type should be returned.

Returns

the list of types (1 for excitatory, -1 for inhibitory)

get_edges(attribute=None, value=None, source_node=None, target_node=None)[source]#

Return the edges in the network fulfilling a given condition.

For undirected graphs, edges are always returned in the order (u, v) where u <= v.

Warning

Contrary to edges_array() that returns edges ordered by creation time (i.e. corresponding to the order of the edge attribute array), this function does not enforce any specific edge order. This also means that, if order does not matter, it may be faster to call get_edges that to call edges_array.

Parameters
  • attribute (str, optional (default: all nodes)) – Whether the attribute of the returned edges should have a specific value.

  • value (object, optional (default : None)) – If an attribute name is passed, then only edges with attribute being equal to value will be returned.

  • source_node (int or list of ints, optional (default: all nodes)) – Retrict the edges to those stemming from source_node.

  • target_node (int or list of ints, optional (default: all nodes)) – Retrict the edges to those arriving at target_node.

Returns

A list of edges (2-tuples).

get_node_attributes(nodes=None, name=None)[source]#

Attributes of the graph’s edges.

Changed in version 1.0.1: Corrected default behavior and made it the same as get_edge_attributes().

New in version 0.9.

Parameters
  • nodes (list of ints, optional (default: None)) – Nodes whose attribute should be displayed.

  • name (str, optional (default: None)) – Name of the desired attribute.

Returns

  • Dict containing all nodes attributes by default. If nodes is

  • specified, returns a dict containing only the attributes of these

  • nodes. If name is specified, returns a list containing the values of

  • the specific attribute for the required nodes (or all nodes if

  • unspecified).

get_nodes(attribute=None, value=None)[source]#

Return the nodes in the network fulfilling a given condition.

Parameters
  • attribute (str, optional (default: all nodes)) – Whether the attribute of the returned nodes should have a specific value.

  • value (object, optional (default : None)) – If an attribute name is passed, then only nodes with attribute being equal to value will be returned.

get_structure_graph()[source]#

Return a coarse-grained version of the graph containing one node per nngt.Group. Connections between groups are associated to the sum of all connection weights. If no structure is present, returns an empty Graph.

get_weights(edges=None)[source]#

Returns the weights of all or a subset of the edges.

Changed in version 1.0.1: Added the possibility to ask for a subset of edges.

Parameters

edges ((E, 2) array, optional (default: all edges)) – Edges for which the type should be returned.

Returns

the list of weights

property graph#

Returns the underlying library object.

Warning

Do not add or remove edges directly through this object.

property graph_id#

Unique int identifying the instance.

has_edge(edge)#

Whether edge is present in the graph.

New in version 2.0.

is_connected(mode='strong')[source]#

Return whether the graph is connected.

Parameters

mode (str, optional (default: “strong”)) – Whether to test connectedness with directed (“strong”) or undirected (“weak”) connections.

References

ig-connected

igraph - is_connected

is_directed()[source]#

Whether the graph is directed or not

is_network()[source]#

Whether the graph is a subclass of Network (i.e. if it has a NeuralPop attribute).

is_spatial()[source]#

Whether the graph is embedded in space (i.e. is a subclass of SpatialGraph).

is_weighted()[source]#

Whether the edges have weights

static make_network(graph, neural_pop, copy=False, **kwargs)[source]#

Turn a Graph object into a Network, or a SpatialGraph into a SpatialNetwork.

Parameters
  • graph (Graph or SpatialGraph) – Graph to convert

  • neural_pop (NeuralPop) – Population to associate to the new Network

  • copy (bool, optional (default: False)) – Whether the operation should be made in-place on the object or if a new object should be returned.

Notes

In-place operation that directly converts the original graph if copy is False, else returns the copied Graph turned into a Network.

static make_spatial(graph, shape=None, positions=None, copy=False)[source]#

Turn a Graph object into a SpatialGraph, or a Network into a SpatialNetwork.

Parameters
  • graph (Graph or SpatialGraph) – Graph to convert.

  • shape (Shape, optional (default: None)) – Shape to associate to the new SpatialGraph.

  • positions ((N, 2) array) – Positions, in a 2D space, of the N neurons.

  • copy (bool, optional (default: False)) – Whether the operation should be made in-place on the object or if a new object should be returned.

Notes

In-place operation that directly converts the original graph if copy is False, else returns the copied Graph turned into a SpatialGraph. The shape argument can be skipped if positions are given; in that case, the neurons will be embedded in a rectangle that contains them all.

property name#

Name of the graph.

neighbours(node, mode='all')[source]#

Return the neighbours of node.

Parameters
  • node (int) – Index of the node of interest.

  • mode (string, optional (default: “all”)) – Type of neighbours that will be returned: “all” returns all the neighbours regardless of directionality, “in” returns the in-neighbours (also called predecessors) and “out” retruns the out-neighbours (or successors).

Returns

neighbours (set) – The neighbours of node.

new_edge(source, target, attributes=None, ignore=False, self_loop=False)#

Adding a connection to the graph, with optional properties.

Changed in version 2.0: Added self_loop argument to enable adding self-loops.

Parameters
  • source (int/node) – Source node.

  • target (int/node) – Target node.

  • attributes (dict, optional (default: {})) – Dictionary containing optional edge properties. If the graph is weighted, defaults to {"weight": 1.}, the unit weight for the connection (synaptic strength in NEST).

  • ignore (bool, optional (default: False)) – If set to True, ignore attempts to add an existing edge and accept self-loops; otherwise an error is raised.

  • self_loop (bool, optional (default: False)) – Whether to allow self-loops or not.

Returns

The new connection or None if nothing was added.

new_edge_attribute(name, value_type, values=None, val=None)[source]#

Create a new attribute for the edges.

Parameters
  • name (str) – The name of the new attribute.

  • value_type (str) – Type of the attribute, among ‘int’, ‘double’, ‘string’, or ‘object’

  • values (array, optional (default: None)) – Values with which the edge attribute should be initialized. (must have one entry per node in the graph)

  • val (int, float or str , optional (default: None)) – Identical value for all edges.

new_edges(edge_list, attributes=None, check_duplicates=False, check_self_loops=True, check_existing=True, ignore_invalid=False)#

Add a list of edges to the graph.

Changed in version 2.0: Can perform all possible checks before adding new edges via the check_duplicates check_self_loops, and check_existing arguments.

Parameters
  • edge_list (list of 2-tuples or np.array of shape (edge_nb, 2)) – List of the edges that should be added as tuples (source, target)

  • attributes (dict, optional (default: {})) – Dictionary containing optional edge properties. If the graph is weighted, defaults to {"weight": ones}, where ones is an array the same length as the edge_list containing a unit weight for each connection (synaptic strength in NEST).

  • check_duplicates (bool, optional (default: False)) – Check for duplicate edges within edge_list.

  • check_self_loops (bool, optional (default: True)) – Check for self-loops.

  • check_existing (bool, optional (default: True)) – Check whether some of the edges in edge_list already exist in the graph or exist multiple times in edge_list (also performs check_duplicates).

  • ignore_invalid (bool, optional (default: False)) – Ignore invalid edges: they are not added to the graph and are silently dropped. Unless this is set to true, an error is raised whenever one of the three checks fails.

  • .. warning:: – Setting check_existing to False will lead to undefined behavior if existing edges are provided! Only use it (for speedup) if you are sure that you are indeed only adding new edges.

Returns

Returns new edges only.

new_node(n=1, neuron_type=1, attributes=None, value_types=None, positions=None, groups=None)#

Adding a node to the graph, with optional properties.

Parameters
  • n (int, optional (default: 1)) – Number of nodes to add.

  • neuron_type (int, optional (default: 1)) – Type of neuron (1 for excitatory, -1 for inhibitory)

  • attributes (dict, optional (default: None)) – Dictionary containing the attributes of the nodes.

  • value_types (dict, optional (default: None)) – Dict of the attributes types, necessary only if the attributes do not exist yet.

  • positions (array of shape (n, 2), optional (default: None)) – Positions of the neurons. Valid only for SpatialGraph or SpatialNetwork.

  • groups (str, int, or list, optional (default: None)) – NeuralGroup to which the neurons belong. Valid only for Network or SpatialNetwork.

Returns

The node or a list of the nodes created.

new_node_attribute(name, value_type, values=None, val=None)[source]#

Create a new attribute for the nodes.

Parameters
  • name (str) – The name of the new attribute.

  • value_type (str) – Type of the attribute, among ‘int’, ‘double’, ‘string’, or ‘object’

  • values (array, optional (default: None)) – Values with which the node attribute should be initialized. (must have one entry per node in the graph)

  • val (int, float or str , optional (default: None)) – Identical value for all nodes.

property node_attributes#

Access node attributes.

node_nb()#

Number of nodes in the graph

classmethod num_graphs()[source]#

Returns the number of alive instances.

set_delays(delay=None, elist=None, distribution=None, parameters=None, noise_scale=None)[source]#

Set the delay for spike propagation between neurons.

Parameters
  • delay (float or class:numpy.array, optional (default: None)) – Value or list of delays (for user defined delays).

  • elist (class:numpy.array, optional (default: None)) – List of the edges (for user defined delays).

  • distribution (class:string, optional (default: None)) – Type of distribution (choose among “constant”, “uniform”, “gaussian”, “lognormal”, “lin_corr”, “log_corr”).

  • parameters (dict, optional (default: {})) – Dictionary containing the properties of the delay distribution.

  • noise_scale (class:int, optional (default: None)) – Scale of the multiplicative Gaussian noise that should be applied on the delays.

set_edge_attribute(attribute, values=None, val=None, value_type=None, edges=None)[source]#

Set attributes to the connections between neurons.

Warning

The special “type” attribute cannot be modified when using graphs that inherit from the Network class. This is because for biological networks, neurons make only one kind of synapse, which is determined by the nngt.NeuralGroup they belong to.

Parameters
  • attribute (str) – The name of the attribute.

  • value_type (str) – Type of the attribute, among ‘int’, ‘double’, ‘string’

  • values (array, optional (default: None)) – Values with which the edge attribute should be initialized. (must have one entry per node in the graph)

  • val (int, float or str , optional (default: None)) – Identical value for all edges.

  • value_type (str, optional (default: None)) – Type of the attribute, among ‘int’, ‘double’, ‘string’. Only used if the attribute does not exist and must be created.

  • edges (list of edges or array of shape (E, 2), optional (default: all)) – Edges whose attributes should be set. Others will remain unchanged.

set_name(name=None)[source]#

Set graph name

set_node_attribute(attribute, values=None, val=None, value_type=None, nodes=None)[source]#

Set attributes to the connections between neurons.

Parameters
  • attribute (str) – The name of the attribute.

  • value_type (str) – Type of the attribute, among ‘int’, ‘double’, ‘string’

  • values (array, optional (default: None)) – Values with which the edge attribute should be initialized. (must have one entry per node in the graph)

  • val (int, float or str , optional (default: None)) – Identical value for all edges.

  • value_type (str, optional (default: None)) – Type of the attribute, among ‘int’, ‘double’, ‘string’. Only used if the attribute does not exist and must be created.

  • nodes (list of nodes, optional (default: all)) – Nodes whose attributes should be set. Others will remain unchanged.

set_types(edge_type, nodes=None, fraction=None)[source]#

Set the synaptic/connection types.

Changed in version 2.0: Changed syn_type to edge_type.

Warning

The special “type” attribute cannot be modified when using graphs that inherit from the Network class. This is because for biological networks, neurons make only one kind of synapse, which is determined by the nngt.NeuralGroup they belong to.

Parameters
  • edge_type (int, string, or array of ints) – Type of the connection among ‘excitatory’ (also 1) or ‘inhibitory’ (also -1).

  • nodes (int, float or list, optional (default: None)) – If nodes is an int, number of nodes of the required type that will be created in the graph (all connections from inhibitory nodes are inhibitory); if it is a float, ratio of edge_type nodes in the graph; if it is a list, ids of the edge_type nodes.

  • fraction (float, optional (default: None)) – Fraction of the selected edges that will be set as edge_type (if nodes is not None, it is the fraction of the specified nodes’ edges, otherwise it is the fraction of all edges in the graph).

Returns

t_list (numpy.ndarray) – List of the types in an order that matches the edges attribute of the graph.

set_weights(weight=None, elist=None, distribution=None, parameters=None, noise_scale=None)[source]#

Set the synaptic weights.

Parameters
  • weight (float or class:numpy.array, optional (default: None)) – Value or list of the weights (for user defined weights).

  • elist (class:numpy.array, optional (default: None)) – List of the edges (for user defined weights).

  • distribution (class:string, optional (default: None)) – Type of distribution (choose among “constant”, “uniform”, “gaussian”, “lognormal”, “lin_corr”, “log_corr”).

  • parameters (dict, optional (default: {})) – Dictionary containing the properties of the weight distribution. Properties are as follow for the distributions

    • ‘constant’: ‘value’

    • ‘uniform’: ‘lower’, ‘upper’

    • ‘gaussian’: ‘avg’, ‘std’

    • ‘lognormal’: ‘position’, ‘scale’

  • noise_scale (class:int, optional (default: None)) – Scale of the multiplicative Gaussian noise that should be applied on the weights.

Note

If distribution and parameters are provided and the weights are set for the whole graph (elist is None), then the distribution properties will be kept as the new default for subsequent edges. That is, if new edges are created without specifying their weights, then these new weights will automatically be drawn from this previous distribution.

property structure#

Object structuring the graph into specific groups.

Note

Points to population if the graph is a Network.

to_file(filename, fmt='auto', separator=' ', secondary=';', attributes=None, notifier='@')[source]#

Save graph to file; options detailed below.

See also

nngt.lib.save_to_file()

to_undirected(combine_numeric_eattr='sum')[source]#

Convert the graph to its undirected variant.

Note

All non-numeric edge attributes will be discarded from the returned undirected graph.

Parameters

combine_numeric_eattr (str, optional (default: “sum”)) – How to combine numeric attributes from reciprocal edges. Can be either:

  • “sum” (attributes are summed)

  • “min” (smallest value is kept)

  • “max” (largest value is kept)

  • “mean” (the average of both attributes is taken)

In addition, combine_numeric_eattr can be a dictionary with one entry for each edge attribute.

property type#

Type of the graph.

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)

get_positions(nodes=None)[source]#

Returns a copy of the nodes’ positions as a (N, 2) array.

Parameters

nodes (int or array-like, optional (default: all nodes)) – List of the nodes for which the position should be returned.

set_positions(positions, nodes=None)[source]#

Set the nodes’ positions as a (N, 2) array.

Parameters
  • positions (array-like) – List of positions, of shape (N, 2).

  • nodes (int or array-like, optional (default: all nodes)) – List of the nodes for which the position should be set.

property shape#

The environment’s spatial structure.

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)

classmethod exc_and_inhib(size, iratio=0.2, en_model='aeif_cond_alpha', en_param=None, in_model='aeif_cond_alpha', in_param=None, syn_spec=None, **kwargs)[source]#

Generate a network containing a population of two neural groups: inhibitory and excitatory neurons.

Parameters
  • size (int) – Number of neurons in the network.

  • i_ratio (double, optional (default: 0.2)) – Ratio of inhibitory neurons: \frac{N_i}{N_e+N_i}.

  • en_model (string, optional (default: ‘aeif_cond_alpha’)) – Nest model for the excitatory neuron.

  • en_param (dict, optional (default: {})) – Dictionary of parameters for the the excitatory neuron.

  • in_model (string, optional (default: ‘aeif_cond_alpha’)) – Nest model for the inhibitory neuron.

  • in_param (dict, optional (default: {})) – Dictionary of parameters for the the inhibitory neuron.

  • syn_spec (dict, optional (default: static synapse)) – Dictionary containg a directed edge between groups as key and the associated synaptic parameters for the post-synaptic neurons (i.e. those of the second group) as value. If provided, all connections between groups will be set according to the values contained in syn_spec. Valid keys are:

    • (‘excitatory’, ‘excitatory’)

    • (‘excitatory’, ‘inhibitory’)

    • (‘inhibitory’, ‘excitatory’)

    • (‘inhibitory’, ‘inhibitory’)

Returns

net (Network or subclass) – Network of disconnected excitatory and inhibitory neurons.

See also

exc_and_inhib()

classmethod from_gids(gids, get_connections=True, get_params=False, neuron_model='aeif_cond_alpha', neuron_param=None, syn_model='static_synapse', syn_param=None, **kwargs)[source]#

Generate a network from gids.

Warning

Unless get_connections and get_params is True, or if your population is homogeneous and you provide the required information, the information contained by the network and its population attribute will be erroneous! To prevent conflicts the to_nest() function is not available. If you know what you are doing, you should be able to find a workaround…

Parameters
  • gids (array-like) – Ids of the neurons in NEST or simply user specified ids.

  • get_params (bool, optional (default: True)) – Whether the parameters should be obtained from NEST (can be very slow).

  • neuron_model (string, optional (default: None)) – Name of the NEST neural model to use when simulating the activity.

  • neuron_param (dict, optional (default: {})) – Dictionary containing the neural parameters; the default value will make NEST use the default parameters of the model.

  • syn_model (string, optional (default: ‘static_synapse’)) – NEST synaptic model to use when simulating the activity.

  • syn_param (dict, optional (default: {})) – Dictionary containing the synaptic parameters; the default value will make NEST use the default parameters of the model.

Returns

net (Network or subclass) – Uniform network of disconnected neurons.

get_edge_types(edges=None)[source]#

Return the type of all or a subset of the edges. For all edges, the types are ordered according to the edges ids, i.e. in the same order as :property:`~nngt.Graph.edges_array`.

Changed in version 2.4: Updated it to make it compatible with the default Graph function, including the edges argument.

Parameters

edges ((E, 2) array, optional (default: all edges)) – Edges for which the type should be returned.

Returns

the list of types (1 for excitatory, -1 for inhibitory)

get_neuron_type(neuron_ids)[source]#

Return the type of the neurons (+1 for excitatory, -1 for inhibitory).

Parameters

neuron_ids (int or tuple) – NEST gids.

Returns

ids (int or tuple) – Ids in the network. Same type as the requested gids type.

id_from_nest_gid(gids)[source]#

Return the ids of the nodes in the nngt.Network instance from the corresponding NEST gids.

Parameters

gids (int or tuple) – NEST gids.

Returns

ids (int or tuple) – Ids in the network. Same type as the requested gids type.

neuron_properties(idx_neuron)[source]#

Properties of a neuron in the graph.

Parameters

idx_neuron (int) – Index of a neuron in the graph.

Returns

dict of the neuron’s properties.

classmethod num_networks()[source]#

Returns the number of alive instances.

property population#

NeuralPop that divides the neurons into groups with specific properties.

set_types(edge_type, nodes=None, fraction=None)[source]#

Warning

This function is not available for Network subclasses.

to_nest(send_only=None, weights=True)[source]#

Send the network to NEST.

See also

make_nest_network() for parameters

classmethod uniform(size, neuron_model='aeif_cond_alpha', neuron_param=None, syn_model='static_synapse', syn_param=None, **kwargs)[source]#

Generate a network containing only one type of neurons.

Parameters
  • size (int) – Number of neurons in the network.

  • neuron_model (string, optional (default: ‘aief_cond_alpha’)) – Name of the NEST neural model to use when simulating the activity.

  • neuron_param (dict, optional (default: {})) – Dictionary containing the neural parameters; the default value will make NEST use the default parameters of the model.

  • syn_model (string, optional (default: ‘static_synapse’)) – NEST synaptic model to use when simulating the activity.

  • syn_param (dict, optional (default: {})) – Dictionary containing the synaptic parameters; the default value will make NEST use the default parameters of the model.

Returns

net (Network or subclass) – Uniform network of disconnected neurons.

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)

set_types(syn_type, nodes=None, fraction=None)[source]#

Warning

This function is not available for Network subclasses.