ALLEN INSTITUTE

# bmtk.builder package

## Subpackages

- bmtk.builder.auxi package
  - Submodules
  - bmtk.builder.auxi.edge_connectors module
    - `connect_random()`
    - `distance_connector()`
  - bmtk.builder.auxi.node_params module
    - `CellLocations`
      - `CellLocations.CCF_orientation`
      - `CellLocations.add_positions()`
      - `CellLocations.add_positions_columnar()`
      - `CellLocations.add_positions_ellipsoid()`
      - `CellLocations.add_positions_nrrd()`
      - `CellLocations.add_positions_rect_prism()`
      - `CellLocations.dmin`
      - `CellLocations.plot_locs()`
    - `hcp()`
    - `partition_locations()`
    - `plot_positions()`
    - `positions_columinar()`
    - `positions_columnar()`
    - `positions_cuboid()`
    - `positions_density_matrix()`
    - `positions_dmin_lattice()`
    - `positions_dmin_prog()`
    - `positions_ellipsoid()`
    - `positions_list()`
    - `positions_nrrd()`
    - `positions_rect_prism()`
    - `xiter_random()`
  - Module contents
- bmtk.builder.bionet package
  - Submodules
  - bmtk.builder.bionet.swc_reader module
    - `SWCReader`
      - `SWCReader.choose_sections()`
      - `SWCReader.delete_axon()`
      - `SWCReader.find_sections()`
      - `SWCReader.fix_axon()`
      - `SWCReader.get_coords()`
      - `SWCReader.get_section()`
      - `SWCReader.get_swc_id()`
      - `SWCReader.move_and_rotate()`
      - `SWCReader.n_sections`
      - `SWCReader.nseg`
      - `SWCReader.sec_type_swc`
      - `SWCReader.sections`
      - `SWCReader.seg_coords`
      - `SWCReader.seg_props`
      - `SWCReader.set_segment_dl()`
      - `SWCReader.soma_position`
      - `SWCReader.swc_map`
    - `SegmentCoords`
      - `SegmentCoords.p0`
      - `SegmentCoords.p05`
      - `SegmentCoords.p1`
    - `SegmentProps`
      - `SegmentProps.area`
      - `SegmentProps.dist`
      - `SegmentProps.dist0`
      - `SegmentProps.dist1`
      - `SegmentProps.length`
      - `SegmentProps.sec_id`
      - `SegmentProps.type`
      - `SegmentProps.x`
    - `get_swc()`
    - `rotation_matrix()`
  - Module contents
    - `rand_syn_locations()`
- bmtk.builder.edges_sorter package
  - Submodules
  - bmtk.builder.edges_sorter.memory_sorter module
    - `copy_attributes()`
    - `quicksort_edges()`
  - bmtk.builder.edges_sorter.merge_sorter module
    - `ProgressFile`
      - `ProgressFile.update()`
    - `external_merge_sort()`
  - Module contents
    - `sort_edges()`
- bmtk.builder.network_adaptors package
  - Submodules
  - bmtk.builder.network_adaptors.dm_network module
    - `DenseNetwork`
      - `DenseNetwork.edges_iter()`
      - `DenseNetwork.edges_table()`
      - `DenseNetwork.import_nodes()`
      - `DenseNetwork.nedges`
      - `DenseNetwork.nnodes`
      - `DenseNetwork.nodes_iter()`
    - `add_hdf5_attrs()`
  - bmtk.builder.network_adaptors.dm_network_orig module
    - `DenseNetworkOrig`
      - `DenseNetworkOrig.EdgeTable`
      - `DenseNetworkOrig.PropertyTable`
      - `DenseNetworkOrig.edges_iter()`
      - `DenseNetworkOrig.edges_table()`
      - `DenseNetworkOrig.import_nodes()`
      - `DenseNetworkOrig.nedges`
      - `DenseNetworkOrig.nnodes`
      - `DenseNetworkOrig.nodes_iter()`
    - `add_hdf5_attrs()`
  - bmtk.builder.network_adaptors.edge_props_table module
    - `EdgeTypesTable`
    - `EdgeTypesTableIFace`
      - `EdgeTypesTableIFace.n_edges`
      - `EdgeTypesTableIFace.n_syns`
    - `EdgeTypesTableMPI`
      - `EdgeTypesTableMPI.get_tmp_table_path()`
      - `EdgeTypesTableMPI.save()`
    - `EdgeTypesTableMemory`
      - `EdgeTypesTableMemory.create_property()`
      - `EdgeTypesTableMemory.edge_type_node_ids`
      - `EdgeTypesTableMemory.edge_type_properties`
      - `EdgeTypesTableMemory.free_data()`
      - `EdgeTypesTableMemory.get_property_metatadata()`
      - `EdgeTypesTableMemory.get_property_value()`
      - `EdgeTypesTableMemory.hash_key`
      - `EdgeTypesTableMemory.iter_edges()`
      - `EdgeTypesTableMemory.n_edges`
      - `EdgeTypesTableMemory.n_syns`
      - `EdgeTypesTableMemory.save()`
      - `EdgeTypesTableMemory.set_nsyns()`
      - `EdgeTypesTableMemory.set_property_value()`
      - `EdgeTypesTableMemory.source_nodes_map`
      - `EdgeTypesTableMemory.target_nodes_map`
      - `EdgeTypesTableMemory.to_dataframe()`
  - bmtk.builder.network_adaptors.edges_collator module
    - `EdgesCollator`
    - `EdgesCollatorMPI`
      - `EdgesCollatorMPI.get_edge_group_ids()`
      - `EdgesCollatorMPI.get_edge_group_indices()`
      - `EdgesCollatorMPI.get_edge_type_ids()`
      - `EdgesCollatorMPI.get_group_data()`
      - `EdgesCollatorMPI.get_group_metadata()`
      - `EdgesCollatorMPI.get_group_property()`
      - `EdgesCollatorMPI.get_source_node_ids()`
      - `EdgesCollatorMPI.get_target_node_ids()`
      - `EdgesCollatorMPI.get_tmp_table_path()`
      - `EdgesCollatorMPI.group_ids`
      - `EdgesCollatorMPI.itr_chunks()`
      - `EdgesCollatorMPI.process()`
      - `EdgesCollatorMPI.sort()`
    - `EdgesCollatorSingular`
      - `EdgesCollatorSingular.assign_groups()`
      - `EdgesCollatorSingular.get_edge_group_ids()`
      - `EdgesCollatorSingular.get_edge_group_indices()`
      - `EdgesCollatorSingular.get_edge_type_ids()`
      - `EdgesCollatorSingular.get_group_data()`
      - `EdgesCollatorSingular.get_group_metadata()`
      - `EdgesCollatorSingular.get_group_property()`
      - `EdgesCollatorSingular.get_source_node_ids()`
      - `EdgesCollatorSingular.get_target_node_ids()`
      - `EdgesCollatorSingular.group_ids`
      - `EdgesCollatorSingular.itr_chunks()`
      - `EdgesCollatorSingular.process()`
      - `EdgesCollatorSingular.sort()`
  - bmtk.builder.network_adaptors.network module
    - `Network`
      - `Network.add_edges()`
      - `Network.add_gap_junctions()`
      - `Network.add_nodes()`
      - `Network.build()`
      - `Network.clear()`
      - `Network.edges()`
      - `Network.edges_built`
      - `Network.edges_iter()`
      - `Network.get_connections()`
      - `Network.import_nodes()`
      - `Network.name`
      - `Network.nedges`
      - `Network.nnodes`
      - `Network.nodes()`
      - `Network.nodes_built`
      - `Network.nodes_iter()`
      - `Network.save()`
      - `Network.save_edges()`
      - `Network.save_nodes()`
  - bmtk.builder.network_adaptors.nxnetwork module
    - `NxNetwork`
      - `NxNetwork.nedges`
      - `NxNetwork.nnodes`
  - Module contents

## Submodules

## bmtk.builder.builder_utils module

bmtk.builder.builder_utils.add_hdf5_attrs(hdf5_handle)

bmtk.builder.builder_utils.build_time_uuid()

  Produces a unique identifier that will be unique for each time a network building script is executed.

bmtk.builder.builder_utils.check_properties_across_ranks(properties, graph_type='node')

  Checks that a properties table is consistant across all MPI ranks. Mainly used by add_nodes() and add_edges() method due to bug where using random generator without rng_seed was causing issues building the network properties consistantly using multiple cores.

  Will throw an Exception or a warning message (if MPI_fail_params_nonuniform is false)

  Parameters:

    - properties – A dictionary

    - graph_type – ‘node’ or ‘edge’, used in error message. default ‘node’.

bmtk.builder.builder_utils.list_to_hash(str_list)

## bmtk.builder.connection_map module

class bmtk.builder.connection_map.ConnectionMap(sources=None, targets=None, connector=None, connector_params=None, iterator='one_to_one', edge_type_properties=None)

  Bases: `object`

  Class for keeping track of connection rules. Used for saving unique edge properties in a network

  For every connection from source –> target this keeps track of rules (functions, literals, lists) for

    1. the number of synapses between source and target

    2. Used defined parameters (syn-weight, synaptic-location) for every synapse.

  The number of synapses rule (1) is stored as a connector. Individual synaptic parameters, if they exists, are stored as ParamsRules.

  Usage:

    Do not create a ConnectionMap object directly. Rather one is created and return every time NetworkBuilder’s add_edges() method is called.

    For example, The following will create a set of edges where there is between 1 to 16 synapatic connections between each source and target node. Properties ‘dynamics_params’ and ‘model_template’ will be global properties:

        cm = net.add_edges(source={'ei': 'exc'}, target={'ei': 'inh'},
                           connection_rule=lambda *_: np.random.randn(1, 16),
                           dynamics_params='ExcToInh.json',
                           model_template='Exp2Syn',
                           ...)

    If we want all edges to have a unique ‘syn_weight’ value calculated from source/target locations, we create a function that takes in source and target (Node object) and returns the syn weight. This function will be called for every individual connection:

        def syn_weight_by_loc(source, target):
            src_loc, trg_loc = source['loc'], target['loc']
            ...
            return syn_weight

        cm.add_properties('syn_weight', rule=syn_weight_by_loc, dtypes=np.float)

    We can also add multiple properties at the same time:

        def get_target_loc_and_dist(source, target):
            ...
            return trg_loc, trg_dist

        cm.add_properties(['syn_location', 'syn_distance'],
                      rule=get_target_loc_and_dist,
                      dtypes=[string, np.float])

    Once NetworkBuilder.build() is called the ‘connection_rule’ will be called.

  class ParamsRules(names, rule, rule_params, dtypes)

    Bases: `object`

    A subclass to store indvidiual synpatic parameter rules

    property dtypes
    get_prop_dtype(prop_name)
    property names
    property rule
  add_properties(names, rule=None, rule_params=None, values=None, dtypes=None)

    Add a synaptic property for an individual edge.

    Typically this requires a custom rule that will be used for every source/target pair of nodes and returns a value for the property. Such rule is a user defined function, and will be called by NetworkBuilder.build():

        def syn_weight_by_loc(source, target):
            ...
            return syn_weight

        cm.add_properties('syn_weight', rule=syn_weight_by_loc, dtypes=np.float)

    If the connection_rule function requires additional parameters use the rule_params option:

        def syn_weight_by_loc(source, target, min_weight, max_weight):
            ...
            return syn_weight

        cm.add_properties('syn_weight',
                          rule=syn_weight_by_loc,
                          rule_params={'min_weigth':1.0e-7, 'max_weight': 5.0e-6},
                          dtypes=np.float)

    You may also have the rule define multiple connection parameters at one time:

        def conn_rule(source, target, min_weight, max_weight):
            ...
            return syn_weight, syn_location, delay

        cm.add_properties(['syn_weight', 'syn_loc', 'delay'],
                          rule=syn_weight_by_loc,
                          rule_params={'min_weigth':1.0e-7, 'max_weight': 5.0e-6},
                          dtypes=[np.float, str, np.float])

    Parameters:

      - names – list, or single string, of the property

      - rule – function, list or value of property

      - values – A list of values to use for property

      - rule_params – when rule is a function, rule_params will be passed into function when called.

      - dtypes – expected property type

  connection_itr()

    Returns a generator that will iterate through the source/target pairs (as specified by the iterator function, and create a connection rule based on the connector.

  property connector
  property connector_params
  property edge_type_id
  property edge_type_properties
  property iterator
  max_connections()
  property params
  properties_keys()
  property property_names
  property source_network_name
  property source_nodes
  property target_network_name
  property target_nodes

class bmtk.builder.connection_map.ListIterator(my_list)

  Bases: `object`

## bmtk.builder.connector module

bmtk.builder.connector.create(connector, **params)

bmtk.builder.connector.register(name, func)

## bmtk.builder.edge module

class bmtk.builder.edge.Edge(src_gid, trg_gid, edge_type_props, syn_props)

  Bases: `object`

  property edge_type_id
  property edge_type_properties
  property source_gid
  property source_node_id
  property synaptic_properties
  property target_gid
  property target_node_id

## bmtk.builder.functor_cache module

class bmtk.builder.functor_cache.FunctorCache

  Bases: `object`

  create(connector, **params)
  register(name, func)

## bmtk.builder.id_generator module

class bmtk.builder.id_generator.IDGenerator(init_val=0)

  Bases: `object`

  A simple class for fetching global ids. To get a unqiue global ID class next(), which should be thread-safe. It Also has a remove_id(gid) in which case next() will never return the gid. The remove_id function is used for cases when using imported networks and we want to eliminate previously created id.

  TODO:

    - Implement a bit array to keep track of already existing gids

    - It might be necessary to implement with MPI support?

  get_ids(size)
  next()
  remove_id(gid)

## bmtk.builder.index_builders module

bmtk.builder.index_builders.create_index_in_memory(edges_file, edges_population, index_type, force_rebuild=True, compression='gzip', **kwargs)

bmtk.builder.index_builders.create_index_on_disk(edges_file, edges_population, index_type, force_rebuild=False, cache_file=None, max_edge_reads=200000000, **kwargs)

bmtk.builder.index_builders.remove_index(edges_file, edges_population)

## bmtk.builder.iterator module

class bmtk.builder.iterator.IteratorCache

  Bases: `object`

  create(itr_name, itr_type, **params)
  register(name, itr_type, func)

bmtk.builder.iterator.all_to_one_iterator(source_nodes, target_nodes, connector)

  Iterate through all the target nodes and return target node + list of all sources

bmtk.builder.iterator.all_to_one_list_iterator(source_nodes, target_nodes, vals)

bmtk.builder.iterator.create(iterator, connector, **params)

bmtk.builder.iterator.lambda_iterator(source_nodes, target_nodes, lambda_val)

bmtk.builder.iterator.one_to_all_iterator(source_nodes, target_nodes, connector)

  Calls the connector function with (1 source, all targets), iterated for each source

bmtk.builder.iterator.one_to_all_list_iterator(source_nodes, target_nodes, vals)

bmtk.builder.iterator.one_to_one_iterator(source_nodes, target_nodes, connector)

bmtk.builder.iterator.one_to_one_list_iterator(source_nodes, target_nodes, vals)

bmtk.builder.iterator.register(name, dtype, func)

## bmtk.builder.network_builder module

class bmtk.builder.network_builder.BioNetBuilder(name, adaptor_cls=<class 'bmtk.builder.network_adaptors.dm_network.DenseNetwork'>, **network_props)

  Bases: `NetworkBuilder`

  An instance of NetworkBuilder specifically designed for building BioNet (NEURON) complainant networks

  add_edges(source=None, target=None, connection_rule=1, connection_params=None, iterator='one_to_one', model_template=None, dynamics_params=None, syn_weight=None, delay=None, target_sections=None, distance_range=None, **properties)

    Add rules for creating edges between a subset of source and target cells.

    Parameters:

      - source – A dictionary or list of Node objects (see nodes() method). Used to filter out pre-synaptic subset of nodes.

      - target – A dictionary or list of Node objects). Used to filter out post-synaptic subset of nodes

      - connection_rule – Integer or a function that returns integer(s). Rule to determine number of connections between each source and target node

      - connection_params – A dictionary, used when the ‘connection_rule’ is a function that requires additional argments

      - iterator – ‘one_to_one’, ‘all_to_one’, ‘one_to_all’. When ‘connection_rule’ is a function this sets how the subsets of source/target nodes are passed in. By default (one-to-one) the connection_rule is called for every source/target pair. ‘all-to-one’ will pass in a list of all possible source nodes for each target, and ‘one-to-all’ will pass in a list of all possible targets for each source.

      - model_template – A predefined or user generated NEURON function name for generating connection. (default: exp2syn).

      - dynamics_params – A json file path or a dictionary of edge/synapse dynamics parameter values used for generating the connection, according to the model_template function. If passing in the name or path of a json file the parameter values will be applied to a edges.

      - syn_weight – float or list of N floats, weights applied to each edge/synpase, value dependent on model

      - delay – float or list of N floats, delay in milliseconds for cell-cell events

      - target_sections – list of strings, non-SONATA compliant, locations of where to place synpases when the target cell is model_type=biophysical. One or more of the following values: somatic, basal, apical, axon. If specified post-synaptic location will be randomly chosen from given sections (+ distance_range value). To assign specific locations use afferent_section_id/afferent_section_pos along with the ConnectionMap instance returned.

      - distance_range – A numeric range of floats [beg, end]. non SONATA compliant. Start and end arc-length distance from SOMA where the post-synaptic location will be placed on a model_type=biophysical cell. Along with target_sections parameter can be used to randomly but strategically connection cells. To assign specific locations use afferent_section_id/afferent_section_pos along with the returned ConnectionMap.

      - properties – properties/attributes of the given edge type

    Returns:

      A ConnectionMap object

  add_nodes(N=1, model_type=None, model_template=None, model_processing=None, dynamics_params=None, morphology=None, x=None, y=None, z=None, rotation_angle_xaxis=None, rotation_angle_yaxis=None, rotation_angle_zaxis=None, **properties)

    Add a set of N NEURON type nodes/cells to the network

    Parameters:

      - N – number of nodes (cells) in this group

      - model_type – the type of node, ‘biophysical’, ‘virtual’, ‘single_compartment’, or ‘point_neuron’

      - model_template – Template or class used to instantiate all instances of each cell, eg. a NeuroML or NEURON Hoc Template file. Should contain a prefix of the format type (‘nml:<Cell.nml>’ or ‘ctdb:Biophys1.hoc’

      - model_processing – string, pre-defined or user function applied to instantiated cell property/morphology, if using Allen Cell-Type Database biophysical models use ‘aibs_perisomatic’ or ‘aibs_allactive’.

      - dynamics_params –

        A file-name or a dictionary of cell-dynamics parameter values used for generating the cell. If using models from Allen Cell-Type Database then passing in the name of <model>_fit.json file will apply the same model params to all N cells. If you want unique params for each cell pass in a dictionary where each key has an associated list of size N:

            dynamics_params={'g_bar': [0.5, 0.2, ...], 'na_bar': [1.653e-5, 9.235e-6, ...]}

      - morphology – string, name of morphology swc file used for creating model_type=biophysical cells

      - x – list/array of size N floats for each cell’s x-axis soma position

      - y – list/array of size N floats for each cell’s y-axis soma position

      - z – list/array of size N floats for each cell’s z-axis soma position

      - rotation_angle_xaxis – x-axis euler rotation angle around the soma in radians

      - rotation_angle_yaxis – y-axis euler rotation angle around the soma in radians

      - rotation_angle_zaxis – z-axis euler rotation angle around the soma in radians

      - properties – Individual and group properties of given nodes

class bmtk.builder.network_builder.NetworkBuilder(name, adaptor_cls=<class 'bmtk.builder.network_adaptors.dm_network.DenseNetwork'>, **network_props)

  Bases: `object`

  The NetworkBuilder class is used for building and saving a brain network/circuit. By default it will save to SONATA format for running network simulations using BioNet, PointNet, PopNet or FilterNet bmtk modules, however it can be generalized to build any time of network for any time of simulation.

  Building the network:

    For the general use-case building a network consists of 4 steps, each with a corresponding method.

    1. Initialize the network:

           net = NetworkBuilder("network_name")

    2. Create nodes (ie cells) using the add_nodes() method:

           net.add_nodes(N=80, model_type='Biophysical', ei='exc')
           net.add_nodes(N=20, model_type='IntFire', ei='inh')
           ...

    3. Create Connection rules between different subsets of nodes using add_edges() method:

           net.add_edges(source={'ei': 'exc'}, target={'ei': 'inh'},
                         connection_rule=my_conn_func, synaptic_model='e2i')
           ...

    4. Finally build the network and save the files:

           net.build()
           net.save(output_dir='network_path')

    See the bmtk documentation, or the method doc-strings for more advanced functionality

  Network Accessor methods:

    nodes()

    Will return a iterable of Node objects for each node created. The Node objects can be used like dictionaries to fetch their properties. By default returns all nodes in the network, but you can filter out a given subset by passing in property/values pairs:

        for node in net.nodes(model_type='Biophysical', ei='exc'):
            assert(node['ei'] == 'exc')
            ...

    edges()

    Like the nodes() methods, but insteads returns a list of Edge type objects. It too can be filtered by an edge property:

        for edge in net.edges(synaptic_model='exp2'):
            ...

    One can also pass in a list of source (or target) to filter out only those edges which belong to a specific subset of cells:

        for edge in net.edges(target_nodes=net.nodes(ei='exc')):
        ...

  Network Properties:

    - name - name of the network

    - nnodes - number of nodes (cells) in the network.

    - nedges - number of edges. Will be zero if build() method hasn’t been called

  add_edges(source=None, target=None, connection_rule=1, connection_params=None, iterator='one_to_one', **edge_type_properties)

    Used to create the connectivity matrix between subsets of nodes. The actually connections will not be created until the build() method is called, using the ‘connection_rule.

    Node Selection:

      To specify what subset of nodes will be used for the pre- and post-synaptic one can use a dictionary to filter the nodes. In the following all inh nodes will be used for the pre-synaptic neurons, but only exc fast-spiking neurons will be used in the post-synaptic neurons (If target or source is not specified all neurons will be used):

          net.add_edges(source={'ei': 'inh'}, target={'ei': 'exc', 'etype': 'fast-spiking'},
                        dynamic_params='i2e.json', synaptic_model='alpha', ...)

      In the above code there is one connection between each source/target pair of nodes, but to create a multi-graph with N connections between each pair use ‘connection_rule’ parameter with an integer value:

          net.add_edges(
              source={'ei': 'inh'},
              target={'ei': 'exc', 'etype': 'fast-spiking'},
              connection_rule=N,
              ...
          )

    Connection rules:

      Usually the ‘connection_rule’ parameter will be the name of a function that takes in source-node and target-node object (which can be treated like dictionaries, and returns the number of connections (ie synapses, 0 or None if no synapses should exists) between the source and target cell:

          def my_conn_fnc(source_node, target_node):
              src_pos = source_node['position']
              trg_pos = target_node['position']
              ...
              return N_syns

          net.add_edges(source={'ei': 'exc'}, target={'ei': 'inh'}, connection_rule=my_conn_fnc, **opt_edge_attrs)

      If the connection_rule function requires addition arguments use the ‘connection_params’ option:

          def my_conn_fnc(source_node, target_node, min_edges, max_edges)
              ...

          net.add_edges(connection_rule=my_conn_fnc, connection_params={'min_edges': 0, 'max_edges': 20}, ...)

      Sometimes it may be more efficient or even a requirement that multiple connections are created at the same time. For example a post-synaptic neuron may only be targeted by a limited number of sources which couldn’t be done by the previous connection_rule function. But by setting property ‘iterator’ to value ‘all_to_one’ the connection_rule function now takes in as a value a list of N source neurons, a single target, and should return a list of size N:

          def bulk_conn_fnc(sources, target):
              syn_list = np.zeros(len(sources))
              for source in sources:
                  ....
              return syn_list

          net.add_edges(connection_rule=bulk_conn_fnc, iterator='all_to_one', ...)

      There is also a ‘one_to_all’ iterator option that will pair each source node with a list of all available target nodes.

    Edge Properties:

      Normally the properties used when creating a given type of edge will be shared by all the individual connections. To create unique values for each edge, the add_edges() method returns a ConnectionMap object:

          def set_syn_weight_by_dist(source, target):
              src_pos, trg_pos = source['position'], target['position']
              ....
              return syn_weight

          cm = net.add_edges(connection_rule=my_conn_fnc, model_template='Exp2Syn', ...)
                          delay=2.0)
          cm.add_properties('syn_weight', rule=set_syn_weight_by_dist)
          cm.add_properties('delay', rule=lambda *_: np.random.rand(0.01, 0.50))

      In this case the ‘model_template’ property has a value for all connections of this given type of edge. The ‘syn_weight’ and ‘delay’ properties will (most likely) be unique values. See ConnectionMap documentation for more info.

    Parameters:

      - source – A dictionary or list of Node objects (see nodes() method). Used to filter out pre-synaptic subset of nodes.

      - target – A dictionary or list of Node objects). Used to filter out post-synaptic subset of nodes

      - connection_rule – Integer or a function that returns integer(s). Rule to determine number of connections between each source and target node

      - connection_params – A dictionary, used when the ‘connection_rule’ is a function that requires additional argments

      - iterator – ‘one_to_one’, ‘all_to_one’, ‘one_to_all’. When ‘connection_rule’ is a function this sets how the subsets of source/target nodes are passed in. By default (one-to-one) the connection_rule is called for every source/target pair. ‘all-to-one’ will pass in a list of all possible source nodes for each target, and ‘one-to-all’ will pass in a list of all possible targets for each source.

      - edge_type_properties – properties/attributes of the given edge type

    Returns:

      A ConnectionMap object

  add_nodes(N=1, **properties)

    Used to add nodes (eg cells) to a network. User should specify the number of Nodes (N) and can use any properties/attributes they require to define the nodes. By default, all individual cells will be assigned a unique ‘node_id’ to identify each node in the network and a ‘node_type_id’ to identify each group of nodes.

    If a property is a singular value then said property will be shared by all the nodes in the group. If a value is a list of length N then each property will be uniquely assigned to each node. In the below example a group of 100 nodes is created, all share the same ‘model_type’ parameter but the pos_x values will be different for each node:

        net.add_nodes(N=100, pos_x=np.random.rand(100), model_type='intfire1', ...)

    You can use a tuple to store property values (in which the SONATA hdf5 will save it as a dataset with multiple columns). For example to have one property ‘positions’ which keeps track of the x/y/z coordinates of each cell:

        net.add_nodes(N=100, positions=[(rand(), rand(), rand()) for _ in range(100)], ...)

    Parameters:

      - N – number of nodes in this group

      - properties – Individual and group properties of given nodes

  build(force=False)

    Builds nodes and edges.

    Parameters:

      force – set true to force complete rebuilding of nodes and edges, if nodes() or save_nodes() has been called before then forcing a rebuild may change gids of each node.

  clear()

    Resets the network removing the nodes and edges created.

  edges(target_nodes=None, source_nodes=None, target_network=None, source_network=None, **properties)

    Returns a list of dictionary-like Edge objects, given filter parameters.

    To get all edges from a network:

        edges = net.edges()

    To specify the target and/or source node-set:

        edges = net.edges(target_nodes=net.nodes(type='biophysical'), source_nodes=net.nodes(ei='i'))

    To only get edges with a given edge_property:

        edges = net.edges(weight=100, syn_type='AMPA_Exc2Exc')

    Parameters:

      - target_nodes – gid, list of gid, dict or node-pool. Set of target nodes for a given edge.

      - source_nodes – gid, list of gid, dict or node-pool. Set of source nodes for a given edge.

      - target_network – name of network containing target nodes.

      - source_network – name of network containing source nodes.

      - properties – edge-properties used to filter out only certain edges.

    Returns:

      list of bmtk.builder.edge.Edge properties.

  property edges_built

    Returns True if the connectivity matrix has been instantiated for this network.

  import_nodes(nodes_file_name, node_types_file_name)

    Import nodes from an existing sonata file

    Parameters:

      - nodes_file_name

      - node_types_file_name

  property name

    Get the name (string) of this network.

  property nedges

    Returns the total number of edges for this network.

  property nnodes

    Returns the number of nodes for this network.

  nodes(**properties)

    Returns an iterator of Node (glorified dictionary) objects, filtered by parameters.

    To get all nodes on a network:

        for node in net.nodes():
            ...

    To only get those nodes with properties that match a given list of parameter values:

        for nod in net.nodes(param1=value1, param2=value2, ...):
            ...

    Parameters:

      properties – key-value pair of node attributes to filter returned nodes

    Returns:

      An iterator of Node objects

  property nodes_built

    Returns True if nodes has been instantiated for this network.

  save(output_dir='.', force_overwrite=True, compression='gzip')

    Used to save the network files in the appropriate (eg SONATA) format into the output_dir directory. The file names will be automatically generated based on the network names.

    To have more control over the output and file names use the save_nodes() and save_edges() methods.

    Parameters:

      - output_dir – string, directory where network files will be generated. Default, current working directory.

      - force_overwrite – Overwrites existing network files.

      - compression – Compression algorithm used to save hdf5 files. ‘gzip’ (default), ‘lzf’, ‘none’, or None. you can also specify an integer (1-9) to specify the level of gzip compression.

  save_edges(edges_file_name=None, edge_types_file_name=None, output_dir='.', src_network=None, trg_network=None, name=None, force_build=True, force_overwrite=False, compression='gzip')

    Save the instantiated edges in SONATA format files.

    Parameters:

      - edges_file_name – file-name of hdf5 edges file. By default will use <src_network>_<trg_network>_edges.h5.

      - edge_types_file_name – file-name of csv edge-types file. By default will use <src_network>_<trg_network>_edges.h5.

      - output_dir – Directory where network files will be generated. Default, current working directory.

      - src_network – Name of the source-node populations.

      - trg_network – Name of the target-node populations.

      - name – Name of edge populations, eg /edges/<name> in edges.h5 file.

      - force_build – Force to (re)build the connection matrix if it hasn’t already been built.

      - force_overwrite – Overwrites existing network files.

      - compression – Compression algorithm used to save hdf5 files. ‘gzip’ (default), ‘lzf’, ‘none’, or None. you can also specify an integer (1-9) to specify the level of gzip compression.

  save_nodes(nodes_file_name=None, node_types_file_name=None, output_dir='.', force_overwrite=True, compression='gzip')

    Save the instantiated nodes in SONATA format files.

    Parameters:

      - nodes_file_name – file-name of hdf5 nodes file. By default will use <network.name>_nodes.h5.

      - node_types_file_name – file-name of the csv node-types file. By default will use <network.name>_node_types.csv

      - output_dir – Directory where network files will be generated. Default, current working directory.

      - force_overwrite – Overwrites existing network files.

      - compression – Compression algorithm used to save hdf5 files. ‘gzip’ (default), ‘lzf’, ‘none’, or None. you can also specify an integer (1-9) to specify the level of gzip compression.

class bmtk.builder.network_builder.PointNetBuilder(name, adaptor_cls=<class 'bmtk.builder.network_adaptors.dm_network.DenseNetwork'>, **network_props)

  Bases: `NetworkBuilder`

  An instance of NetworkBuilder specifically designed for building PointNet (NEST) complainant networks

  add_edges(source=None, target=None, connection_rule=1, connection_params=None, iterator='one_to_one', model_template=None, dynamics_params=None, syn_weight=None, delay=None, **properties)

    Add rules for creating edges between a subset of source and target cells.

    Parameters:

      - source – A dictionary or list of Node objects (see nodes() method). Used to filter out pre-synaptic subset of nodes.

      - target – A dictionary or list of Node objects). Used to filter out post-synaptic subset of nodes

      - connection_rule – Integer or a function that returns integer(s). Rule to determine number of connections between each source and target node

      - connection_params – A dictionary, used when the ‘connection_rule’ is a function that requires additional argments

      - iterator – ‘one_to_one’, ‘all_to_one’, ‘one_to_all’. When ‘connection_rule’ is a function this sets how the subsets of source/target nodes are passed in. By default (one-to-one) the connection_rule is called for every source/target pair. ‘all-to-one’ will pass in a list of all possible source nodes for each target, and ‘one-to-all’ will pass in a list of all possible targets for each source.

      - model_template – A predefined or user generated NEURON function name for generating connection. (default: exp2syn).

      - dynamics_params – A json file path or a dictionary of edge/synapse dynamics parameter values used for generating the connection, according to the model_template function. If passing in the name or path of a json file the parameter values will be applied to a edges.

      - syn_weight – float or list of N floats, weights applied to each edge/synpase, value dependent on model

      - delay – float or list of N floats, delay in milliseconds for cell-cell events

      - properties – properties/attributes of the given edge type

    Returns:

      A ConnectionMap object

  add_nodes(N=1, model_type='point_neuron', model_template=None, dynamics_params=None, x=None, y=None, z=None, **properties)

    Add a set of N NEST model nodes/cells to the network.

    Parameters:

      - N

      - model_type – The type of node, should be value ‘point_neuron’

      - model_template – Name of NEST neuron model to used, should have a ‘nest:’ prefix; nest:iaf_psc_alpha, nest:glif_asc

      - dynamics_params –

        A file-name or a dictionary of cell-dynamics parameter values used for generating the cell, with parameters matching that of the parameters used to initialize NEST model_template cell. If you want unique params for each cell pass in a dictionary where each key has an associated list of size N:

            dynamics_params={'v_init': [-90, -85, ...], 'v_reset': [-20, -20, ...]}

      - x – list/array of size N floats for each cell’s x-axis position

      - y – list/array of size N floats for each cell’s y-axis position

      - z – list/array of size N floats for each cell’s z-axis position

      - properties – Individual and group properties of given nodes

class bmtk.builder.network_builder.PopNetBuilder(name, adaptor_cls=<class 'bmtk.builder.network_adaptors.dm_network.DenseNetwork'>, **network_props)

  Bases: `NetworkBuilder`

  An instance of NetworkBuilder specifically designed for building PopNet (DiPDE) complainant networks

  add_edges(source=None, target=None, nsyns=1, syn_weight=None, delay=None, dynamics_params=None, **properties)
    Parameters:

      - source – A dictionary or list of efferent dipde Populations

      - target – A dictionary or list of afferent dipde Populations

      - nsyns – Number of connections between the populations

      - syn_weight – connection weight between the populations

      - delay – connection delay between the populations

      - dynamics_params – Additional parameters used for initializing connection

      - properties – properties/attributes of the given edge type

    Returns:

      A ConnectionMap object

  add_nodes(model_type='population', model_template=None, dynamics_params=None, **properties)

    Add a DiPDE cell population

    Parameters:

      - model_type – The type of node, should be value ‘population’

      - model_template – Should be either ‘dipde:Internal’ or ‘dipde:External’ (or ‘virtual’)

      - dynamics_params – path to json file, or dictionary, of parameters for dipde population

      - properties – Individual and group properties of given nodes

## bmtk.builder.networks module

## bmtk.builder.node module

class bmtk.builder.node.Node(node_id, node_params, node_type_properties, params_hash=-1)

  Bases: `dict`

  get(key, default=None)

    Return the value for key if key is in the dictionary, else default.

  property node_id
  property node_type_id
  property node_type_properties
  property params
  property params_hash

## bmtk.builder.node_pool module

class bmtk.builder.node_pool.NodePool(network, **properties)

  Bases: `object`

  Stores a collection of nodes based off some query of the network.

  Returns the results of a query of nodes from a network using the nodes() method. Nodes are still generated and saved by the network, this just stores the query information and provides iterator methods for accessing different nodes.

  TODO:
    - Implement a collection-set algebra including | and not operators. ie.

        nodes = net.nodes(type=1) | net.nodes(type=2)

    - Implement operators on properties

        nodes = net.nodes(val) > 100 nodes = 100 in net.nodes(val)

  property filter_str
  classmethod from_filter(network, filter_str)
  property network
  property network_name

## bmtk.builder.node_set module

class bmtk.builder.node_set.NodeSet(N, node_params, node_type_properties)

  Bases: `object`

  property N
  build(nid_generator)
  property node_type_id
  property params_hash
  property params_keys

## Module contents