Abstract Trees

Basic tree

class STree(root=None)[source]

A simple tree for use with a simple Node (neat.SNode).

Generic implementation of a tree structure as a linked list extended with some convenience functions

Parameters

root (neat.SNode, optional) – The root of the tree, default is None which creates an empty tree

Variables

root (neat.SNode) – The root of the tree

STree.__getitem__(index, **kwargs)

Returns the node with given index, if no such node is in the tree, None is returned.

STree.__len__([node])

Return the number of nodes in the tree.

STree.__iter__([node])

Iterate over the nodes in the subtree of the given node.

STree.__str__([node])

Generate a string of the subtree of the given node.

STree.__copy__([new_tree])

Fill the new_tree with it’s corresponding nodes in the same structure as self, and copies all node variables that both tree classes have in common

STree.checkOrdered()

Check if the indices of the tree are number in the same order as they appear in the iterator

STree.getNodes([recompute_flag])

Build a list of all the nodes in the tree

STree.nodes

Build a list of all the nodes in the tree

STree.gatherNodes(node)

Build a list of all the nodes in the subtree of the provided node

STree.getLeafs([recompute_flag])

Get all leaf nodes in the tree.

STree.leafs

Get all leaf nodes in the tree.

STree.isLeaf(node)

Check if input node is a leaf of the tree

STree.root

STree.isRoot(node)

Check if input node is root of the tree.

STree.addNodeWithParentFromIndex(node_index, …)

Create a node with the given index and add it to the tree under a specific parent node.

STree.addNodeWithParent(node, pnode)

Add a node to the tree under a specific parent node

STree.softRemoveNode(node)

Remove a node and its subtree from the tree by deleting the reference to it in its parent.

STree.removeNode(node)

Remove a node as well as its subtree from the tree

STree.removeSingleNode(node)

Remove a single node from the tree.

STree.insertNode(node, pnode[, pcnodes])

Insert a node in the tree as a child of a specified parent.

STree.resetIndices([n])

Resets the indices in the order they appear in a depth-first iteration

STree.getSubTree(node[, new_tree])

Get the subtree of the specified node.

STree.depthOfNode(node)

compute the depth of the node (number of edges between node and root)

STree.degreeOfNode(node)

Compute the degree (number of leafs in its subtree) of a node.

STree.orderOfNode(node)

Compute the order (number of bifurcations from the root) of a node.

STree.pathToRoot(node)

Return the path from a given node to the root

STree.pathBetweenNodes(from_node, to_node)

Inclusive path from from_node to to_node.

STree.pathBetweenNodesDepthFirst(from_node, …)

Inclusive path from from_node to to_node, ginven in a depth- first ordering.

STree.getNodesInSubtree(ref_node[, subtree_root])

Returns the nodes in the subtree that contains the given reference nodes and has the given subtree root as root.

STree.sisterLeafs(node)

Find the leafs that are in the subtree of the nearest bifurcation node up from the input node.

STree.upBifurcationNode(node[, cnode])

Find the nearest bifurcation node up (towards root) from the input node.

STree.downBifurcationNode(node)

Find the nearest bifurcation node down (towards leafs) from the input node.

STree.getBifurcationNodes(nodes)

Get the bifurcation nodes in bewteen the provided input nodes

STree.getNearestNeighbours(node, nodes)

Find the nearest neighbours of node in nodes.

STree.__copy__([new_tree])

Fill the new_tree with it’s corresponding nodes in the same structure as self, and copies all node variables that both tree classes have in common

class SNode(index)[source]

Simple Node for use with a simple Tree (neat.STree)

Parameters

index (int) – index of the node

Variables
  • index (int) – index of the node

  • parent_node (neat.SNode or None) – parent of node, None means node is root

  • child_nodes (list of neat.SNode) – child nodes of self, empty list means node is leaf

  • content (dict) – arbitrary items can be stored at the node

Compartment Tree

class CompartmentTree(root=None)[source]

Abstract tree that implements physiological parameters for reduced compartmental models. Also implements the matrix algebra to fit physiological parameters to impedance matrices

CompartmentTree.addCurrent(channel, e_rev)

Add an ion channel current to the tree

CompartmentTree.setExpansionPoints(…)

Set the choice for the state variables of the ion channel around which to linearize.

CompartmentTree.setEEq(e_eq[, indexing])

Set the equilibrium potential at all nodes on the compartment tree

CompartmentTree.getEEq([indexing])

Get the equilibrium potentials at each node.

CompartmentTree.fitEL()

Fit the leak reversal potential to obtain the stored equilibirum potentials as resting membrane potential

CompartmentTree.getEquivalentLocs()

Get list of fake locations in the same order as original list of locations to which the compartment tree was fitted.

CompartmentTree.calcImpedanceMatrix([freqs, …])

Constructs the impedance matrix of the model for each frequency provided in freqs.

CompartmentTree.calcConductanceMatrix([indexing])

Constructs the conductance matrix of the model

CompartmentTree.calcSystemMatrix([freqs, …])

Constructs the matrix of conductance and capacitance terms of the model for each frequency provided in freqs.

CompartmentTree.calcEigenvalues([indexing])

Calculates the eigenvalues and eigenvectors of the passive system

CompartmentTree.computeGMC(z_mat_arg[, …])

Fit the models’ membrane and coupling conductances to a given steady state impedance matrix.

CompartmentTree.computeGChanFromImpedance(…)

Fit the conductances of multiple channels from the given impedance matrices, or store the feature matrix and target vector for later use (see action).

CompartmentTree.computeGSingleChanFromImpedance(…)

Fit the conductances of a single channel from the given impedance matrices, or store the feature matrix and target vector for later use (see action).

CompartmentTree.computeC(alphas, phimat[, …])

Fit the capacitances to the eigenmode expansion

CompartmentTree.resetFitData()

Delete all stored feature matrices and and target vectors.

CompartmentTree.runFit()

Run a linear least squares fit for the conductances concentration mechanisms.

CompartmentTree.computeFakeGeometry([…])

Computes a fake geometry so that the neuron model is a reduced compurtmental model

CompartmentTree.plotDendrogram(ax[, …])

Generate a dendrogram of the NET

class CompartmentNode(index, loc_ind=None, ca=1.0, g_c=0.0, g_l=0.01, e_eq=- 75.0)[source]

Implements a node for CompartmentTree

Variables
  • ca (float) – capacitance of the compartment (uF)

  • g_l (float) – leak conductance at the compartment (uS)

  • g_c (float) – Coupling conductance of compartment with parent compartment (uS). Ignore if node is the root

  • e_eq (float) – equilibrium potential at the compartment

  • currents (dict {str: [g_bar, e_rev]}) – dictionary with as keys the channel names and as elements lists of length two with contain the maximal conductance (uS) and the channels’ reversal potential in (mV)

  • concmechs (dict {str: neat.channels.concmechs.ConcMech}) – dictionary with as keys the ion names and as values the concentration mechanisms governing the concentration of each ion channel

  • expansion_points (dict {str: np.ndarray}) – dictionary with as keys the channel names and as elements the state variables of the ion channel around which to compute the linearizations

Neural Evaluation Tree

class NET(root=None)[source]

Abstract tree class that implements the Neural Evaluation Tree (Wybo et al., 2019), representing the spatial voltage as a number of voltage components present at different spatial scales.

NET.getLocInds([sroot])

Get the indices of the locations a subtree integrates

NET.getLeafLocNode(loc_ind)

Get the node for which loc_ind is a new location

NET.setNewLocInds()

Set the new location indices in a tree

NET.getReducedTree(loc_inds[, indexing])

Construct a reduced tree where only the locations index by ``loc_inds’’ are retained

NET.calcTotalImpedance(node)

Compute the total impedance associated with a node.

NET.calcIZ(loc_inds)

compute I_Z between any pair of locations in loc_inds

NET.calcIZMatrix()

compute the Iz matrix for all locations present in the tree

NET.calcImpedanceMatrix()

Compute the impedance matrix approximation associated with the NET

NET.calcImpMat()

Compute the impedance matrix approximation associated with the NET

NET.getCompartmentalization(Iz[, returntype])

Returns a compartmentalization for the NET tree where each pair of compartments is separated by an Iz of at least Iz.

NET.plotDendrogram(ax[, plotargs, …])

Generate a dendrogram of the NET

class NETNode(index, loc_inds, newloc_inds=[], z_kernel=None)[source]

Node associated with neat.NET.

Variables
  • loc_inds (list of int) – The inidices of locations which the node integrates

  • newloc_inds (list of int) – The locations for which the node is the most local component to integrate them

  • z_kernel (neat.Kernel) – The impedance kernel with which the node integrates inputs

  • z_bar (float) – The steady state impedance associated with the impedance kernel

class Kernel(kernel)[source]

Implements a kernel as a superposition of exponentials:

\[k(t) = \sum_n c_n e^{ - a_n t}\]

Kernels can be added and subtracted, as this class overloads the __add__ and __subtract__ functions.

They can be evaluated as a function of time by calling the object with a time array.

They can be evaluated in the Fourrier domain with Kernel.ft

Parameters

kernel (dict, float, neat.Kernel, tuple or list) – If dict, has the form {‘a’: np.array, ‘c’: np.array}. If float, sets c single exponential prefactor and assumes a is 1 kHz. If neat.Kernel, copies the object. If tuple or list, sets ‘a’ as first element and ‘c’ as last element.

Variables
  • a (np.array of float or complex) – The exponential coefficients (kHz)

  • c (np.array of float or complex) – The exponential prefactors

Kernel.k_bar

The total surface under the kernel

Kernel.t(t_arr)

Evaluates the kernel in the time domain

Kernel.ft(s_arr)

Evaluates the kernel in the Fourrier domain

Simulate reduced compartmental models

class NeuronCompartmentTree(t_calibrate=0.0, dt=0.025, v_init=- 75.0)[source]

Subclass of NeuronSimTree where sections are defined so that they are effectively single compartments. Should be created from a neat.CompartmentTree using neat.createReducedCompartmentModel()

createReducedNeuronModel(ctree, fake_c_m=1.0, fake_r_a=9.999999999999999e-05, method=2)[source]

Creates a neat.NeuronCompartmentTree to simulate reduced compartmentment models from a neat.CompartmentTree.

Parameters

ctree (neat.CompartmentTree) – The tree containing the parameters of the reduced compartmental model to be simulated

Returns

Return type

neat.NeuronCompartmentTree

Notes

The function ctree.getEquivalentLocs() can be used to obtain ‘fake’ locations corresponding to each compartment, which in turn can be used to insert hoc point process at the compartments using the same functions definitions as for as for a morphological neat.NeuronSimTree

Morphological Trees

Morphology Tree

class MorphTree(file_n=None, types=[1, 3, 4])[source]

Subclass of simple tree that implements neuronal morphologies. Reads in trees from ‘.swc’ files (http://neuromorpho.org/).

Neural morphologies are assumed to follow the three-point soma conventions. Internally however, the soma is represented as a sphere. Hence nodes with indices 2 and 3 do not represent anything and are skipped in iterations and getters.

Can also store a simplified version of the original tree, where only nodes are retained that should hold computational parameters - the root, the bifurcation nodes and the leafs at least, although the user can also specify additional nodes. One tree is set as primary by changing the treetype attribute (select ‘original’ for the original morphology and ‘computational’ for the computational morphology). Lookup operations will often use the primary tree. Using nodes from the other tree for lookup operations is unsafe and should be avoided, it is better to set the proper tree to primary first.

For computational efficiency, it is possible to store sets of locations on the morphology, under user-specified names. These sets are stored as lists of neat.MorphLoc, and associated arrays are stored that contain the corresponding node indices of the locations, their x-coordinates, their distances to the soma and their distances to the nearest bifurcation in the ‘up’-direction

Parameters
  • file_n (str (optional)) – the file name of the morphology file. Assumed to follow the ‘.swc’ format. Default is None, which initialized an empty tree

  • types (list of int (optional)) – The list of node types to be included. As per the ‘.swc’ convention, 1 is soma, 2 is axon, 3 is basal dendrite and 4 apical dendrite. Default is [1,3,4].

Variables
  • root (neat.MorphNode instance) – The root of the tree.

  • locs (dict {str: list of neat.MorphLoc}) – Stored sets of locations, key is the user-specified the name of the set of locations. Initialized as empty dict.

  • nids (dict {str: np.array of int}) – Node indices of locations Initialized as empty dict.

  • xs (dict {str: np.array of float}) – x-coordinates of locations Initialized as empty dict.

  • d2s (dict {str: np.array of float}) – distances to soma of locations Initialized as empty dict.

  • d2b (dict {str: np.array of float}) – distances to nearest bifurcation in ‘up’ direction of locations. Initialized as empty dict.

Read a morphology from an SWC file

MorphTree.readSWCTreeFromFile(file_n[, types])

Non-specific for a “tree data structure” Read and load a morphology from an SWC file and parse it into an neat.MorphTree object.

MorphTree.determineSomaType(file_n)

Determine the soma type used in the SWC file.

MorphTree.__getitem__(index[, skip_inds])

Returns the node with given index, if no such node is in the tree, None is returned.

MorphTree.__iter__([node, skip_inds])

Overloaded iterator from parent class that avoids iterating over the nodes with index 2 and 3

Get specific nodes or sets of nodes from the tree.

MorphTree.root

Returns the root of the original or the computational tree, depending on which treetype is active.

MorphTree.getNodes([recompute_flag, skip_inds])

Overloads the parent function to allow skipping nodes with certain indices and to return the nodes associated with the corresponding treetype.

MorphTree.nodes

Overloads the parent function to allow skipping nodes with certain indices and to return the nodes associated with the corresponding treetype.

MorphTree.getLeafs([recompute_flag])

Overloads the getLeafs of the parent class to return the leafs in the current treetype.

MorphTree.leafs

Overloads the getLeafs of the parent class to return the leafs in the current treetype.

MorphTree.getNodesInBasalSubtree()

Return the nodes associated with the basal subtree

MorphTree.getNodesInApicalSubtree()

Return the nodes associated with the apical subtree

MorphTree.getNodesInAxonalSubtree()

Return the nodes associated with the apical subtree

MorphTree._convertNodeArgToNodes(node_arg)

Converts a node argument to a list of nodes.

Relating to the computational tree.

MorphTree.setTreetype(treetype)

Set the active tree

MorphTree.treetype

MorphTree.readSWCTreeFromFile(file_n[, types])

Non-specific for a “tree data structure” Read and load a morphology from an SWC file and parse it into an neat.MorphTree object.

MorphTree.setCompTree([compnodes, …])

Sets the nodes that contain computational parameters.

MorphTree._evaluateCompCriteria(node[, eps, …])

Return True if relative difference between node radius and parent node raidus is larger than margin eps, or if the node is the root or bifurcation node.

MorphTree.removeCompTree()

Removes the computational tree

Storing locations, interacting with stored locations and distributing locations

MorphTree._convertLocArgToLocs(locarg)

Converts locations argument to list of neat.MorphLoc.

MorphTree.storeLocs(*args, **kwargs)

Store locations under a specified name

MorphTree.addLoc(*args, **kwargs)

Add location to set of locations of given name

MorphTree.clearLocs()

Remove all set of locs stored in the tree

MorphTree.removeLocs(name)

Remove a set of locations of a given name

MorphTree._tryName(name)

Tests if the name is in use.

MorphTree.getLocs(name)

Returns a set of locations of a specified name

MorphTree.getNodeIndices(name)

Returns an array of node indices of locations of a specified name

MorphTree.getXCoords(name)

Returns an array of x-values of locations of a specified name

MorphTree.getLocindsOnNode(name, node)

Returns a list of the indices of locations in the list of a given name that are on a the input node, ordered for increasing x

MorphTree.getLocindsOnNodes(name, node_arg)

Returns a list of the indices of locations in the list of a given name that are on one of the nodes specified in the node list.

MorphTree.getLocindsOnPath(name, node0, node1)

Returns a list of the indices of locations in the list of a given name that are on the given path.

MorphTree.getNearestLocinds(locs, name[, …])

For each location in the input location list, find the index of the closest location in a set of locations stored under a given name.

MorphTree.getNearestNeighbourLocinds(loc, locarg)

Search nearest neighbours to loc in locarg.

MorphTree.getLeafLocinds(name[, recompute])

Find the indices in the desire location list that are ‘leafs’, i.e. locations for which no other location exist that is farther from the root.

MorphTree.distancesToSoma(locarg[, recompute])

Compute the distance of each location in a given set to the soma

MorphTree.distancesToBifurcation(name[, …])

Compute the distance of each location to the nearest bifurcation in the ‘up’ direction (towards root)

MorphTree.distributeLocsOnNodes(d2s[, …])

Distributes locs on a given set of nodes at specified distances from the soma.

MorphTree.distributeLocsUniform(*args, **kwargs)

Distributes locations as uniform as possible, i.e. for a given distance between locations dx, locations are distributed equidistantly on each given node in the computational tree and their amount is computed so that the distance in between them is as close to dx as possible.

MorphTree.distributeLocsRandom(num[, dx, …])

Returns a list of input locations randomly distributed on the tree

MorphTree.extendWithBifurcationLocs(loc_arg)

Extends input loc_arg with the intermediate bifurcations.

MorphTree.uniqueLocs(loc_arg[, name])

Gets the unique locations in the provided locs

MorphTree.pathLength(loc1, loc2[, …])

Find the length of the direct path between loc1 and loc2

Plotting on a 1D axis.

MorphTree.makeXAxis([dx, node_arg, loc_arg])

Create a set of locs suitable for serving as the x-axis for 1D plotting.

MorphTree.setNodeColors([startnode])

Set the color code for the nodes for 1D plotting

MorphTree.getXValues(locs)

Get the corresponding location on the x-axis of the input locations

MorphTree.plot1D(ax, parr, *args, **kwargs)

Plot an array where each element corresponds to the matching location on the x-axis with a depth-first ordering on a 1D plot

MorphTree.plotTrueD2S(ax, parr[, cmap])

Plot an array where each element corresponds to the matching location in the x-axis location list.

MorphTree.colorXAxis(ax, cmap[, …])

Color the x-axis of a plot according to the morphology.

Plotting the morphology in 2D.

MorphTree.plot2DMorphology(ax[, node_arg, …])

Plot the morphology projected on the x,y-plane

MorphTree.plotMorphologyInteractive([…])

Show the morphology either in 3d or projected on the x,y-plane.

Creating new trees from the existing tree.

MorphTree.createNewTree(*args, **kwargs)

Creates a new tree where the locs of a given ‘name’ are now the nodes.

MorphTree.createCompartmentTree(*args, **kwargs)

Creates a new compartment tree where the provided set of locations correspond to the nodes.

MorphTree.__copy__([new_tree])

Fill the new_tree with it’s corresponding nodes in the same structure as self, and copies all node variables that both tree classes have in common

class MorphNode(index, p3d=None)[source]

Node associated with neat.MorphTree. Stores the geometrical information associated with a point on the tree morphology

Variables
  • xyz (numpy.array of floats) – The xyz-coordinates associated with the node (um)

  • R (float) – The radius of the node (um)

  • swc_type (int) – The type of node, according to the .swc file format convention: 1 is dendrites, 2 is axon, 3 is basal dendrite and 4 is apical dendrite.

  • L (float) – The length of the node (um)

MorphNode.setP3D(xyz, R, swc_type)

Set the 3d parameters of the node

MorphNode.child_nodes

Get the child_nodes of this node.

class MorphLoc(loc, reftree, set_as_comploc=False)[source]

Stores a location on the morphology. The location is initialized starting from a node and x-value on the real morphology. The location is also be stored in the coordinates of the computational morphology. To toggle between coordinates, the class stores a reference to the morphology tree on which the location is defined, and returns either the original coordinate or the coordinate on the computational tree, depending on which tree is active.

Initialized based on either a tuple or a dict where one entry specifies the node index and the other entry the x-coordinate specifying the location between parent node (x=0) or the node indicated by the index (x=1), or on a neat.MorphLoc.

Parameters
  • loc (tuple or dict or neat.MorphLoc) – if tuple: (node index, x-value) if dict: {‘node’: node index, ‘x’: x-value}

  • reftree (neat.MorphTree) –

  • set_as_comploc (bool) – if True, assumes the paremeters provided in loc are coordinates on the computational tree. Doing this while no computational tree has been initialized in reftree will result in an error. Defaults to False

Raises

ValueError – If x-coordinate of location is not in [0,1]

Physiology Tree

class PhysTree(file_n=None, types=[1, 3, 4])[source]

Adds physiological parameters to neat.MorphTree and convenience functions to set them across the morphology. Initialized in the same way as neat.MorphTree

Variables

channel_storage (dict {str: neat.IonChannel}) – Stores the user defined ion channels present in the tree

PhysTree.asPassiveMembrane(*args, **kwargs)

Makes the membrane act as a passive membrane (for the nodes in node_arg), channels are assumed to add a conductance of g_max * p_open to the membrane conductance, where p_open for each node is evaluated at the equilibrium potential stored in that node

PhysTree.setEEq(*args, **kwargs)

Set the equilibrium potentials throughout the tree

PhysTree.setPhysiology(*args, **kwargs)

Set specifice membrane capacitance, axial resistance and (optionally) static point-like shunt conductances in the tree.

PhysTree.setLeakCurrent(*args, **kwargs)

Set the parameters of the leak current.

PhysTree.addCurrent(*args, **kwargs)

Adds a channel to the morphology.

PhysTree.getChannelsInTree(*args, **kwargs)

Returns list of strings of all channel names in the tree

PhysTree.fitLeakCurrent(*args, **kwargs)

Fits the leak current to fix equilibrium potential and membrane time- scale.

PhysTree._evaluateCompCriteria(node[, eps, …])

Return True if relative difference in any physiological parameters between node and child node is larger than margin eps.

class PhysNode(index, p3d=None, c_m=1.0, r_a=9.999999999999999e-05, g_shunt=0.0, e_eq=- 75.0)[source]

Node associated with neat.PhysTree. Stores the physiological parameters of the cylindrical segment connecting this node with its parent node

Variables
  • currents (dict {str: [float,float]}) – dict with as keys the channel names and as values lists of length two containing as first entry the channels’ conductance density (uS/cm^2) and as second element the channels reversal (mV) (i.e.: {name: [g_max (uS/cm^2), e_rev (mV)]}) For the leak conductance, the corresponding key is ‘L’

  • concmechs (dict) – dict containing concentration mechanisms present in the segment

  • c_m (float) – The sement’s specific membrane capacitance (uF/cm^2)

  • r_a (float) – The segment’s axial resistance (MOhm*cm)

  • g_shunt (float) – Point-like shunt conductance located at x=1 (uS)

  • e_eq (float) – Segment’s equilibrium potential

Separation of Variables Tree

class SOVTree(file_n=None, types=[1, 3, 4])[source]

Class that computes the separation of variables time scales and spatial mode functions for a given morphology and electrical parameter set. Employs the algorithm by (Major, 1994). This three defines a special neat.SomaSOVNode on as a derived class from neat.SOVNode as some functions required for SOV calculation are different and thus overwritten.

The SOV calculation proceeds on the computational tree (see docstring of neat.MorphNode). Thus it makes no sense to look for sov quantities in the original tree.

SOVTree.calcSOVEquations(*args, **kwargs)

Calculate the timescales and spatial functions of the separation of variables approach, using the algorithm by (Major, 1993).

SOVTree.getModeImportance([locarg, …])

Gives the overal importance of the SOV modes for a certain set of locations

SOVTree.getImportantModes([locarg, …])

Returns the most importand eigenmodes (those whose importance is above the threshold defined by eps)

SOVTree.calcImpedanceMatrix([locarg, …])

Compute the impedance matrix for a set of locations

SOVTree.constructNET([dz, dx, eps, …])

Construct a Neural Evaluation Tree (NET) for this cell

SOVTree.computeLinTerms(net[, sov_data, eps])

Construct linear terms for net so that transfer impedance to soma is exactly matched

class SOVNode(index, p3d=None)[source]

Node that defines functions and stores quantities to implement separation of variables calculation (Major, 1993)

Greens Tree

class GreensTree(file_n=None, types=[1, 3, 4])[source]

Class that computes the Green’s function in the Fourrier domain of a given neuronal morphology (Koch, 1985). This three defines a special neat.SomaGreensNode as a derived class from neat.GreensNode as some functions required for Green’s function calculation are different and thus overwritten.

The calculation proceeds on the computational tree (see docstring of neat.MorphNode). Thus it makes no sense to look for Green’s function related quantities in the original tree.

Variables

freqs (np.array of complex) – Frequencies at which impedances are evaluated [Hz]

GreensTree.removeExpansionPoints()

Remove expansion points from all nodes in the tree

GreensTree.setImpedance(*args, **kwargs)

Set the boundary impedances for each node in the tree

GreensTree.calcZF(*args, **kwargs)

Computes the transfer impedance between two locations for all frequencies in self.freqs.

GreensTree.calcImpedanceMatrix(*args, **kwargs)

Computes the impedance matrix of a given set of locations for each frequency stored in self.freqs.

class GreensNode(index, p3d)[source]

Node that stores quantities and defines functions to implement the impedance matrix calculation based on Koch’s algorithm (Koch & Poggio, 1985).

Variables

expansion_points (dict {str: np.ndarray}) – Stores ion channel expansion points for this segment.

GreensNode.setExpansionPoint(channel_name, …)

Set the choice for the state variables of the ion channel around which to linearize.

Simulate NEURON models

class NeuronSimTree(file_n=None, types=[1, 3, 4], factor_lambda=1.0, t_calibrate=0.0, dt=0.025, v_init=- 75.0)[source]

Tree class to define NEURON (Carnevale & Hines, 2004) based on neat.PhysTree.

Variables
  • sections (dict of hoc sections) – Storage for hoc sections. Keys are node indices.

  • shunts (list of hoc mechanisms) – Storage container for shunts

  • syns (list of hoc mechanisms) – Storage container for synapses

  • iclamps (list of hoc mechanisms) – Storage container for current clamps

  • vclamps (lis of hoc mechanisms) – Storage container for voltage clamps

  • vecstims (list of hoc mechanisms) – Storage container for vecstim objects

  • netcons (list of hoc mechanisms) – Storage container for netcon objects

  • vecs (list of hoc vectors) – Storage container for hoc spike vectors

  • dt (float) – timestep of the simulator [ms]

  • t_calibrate (float) – Time for the model to equilibrate``[ms]``. Not counted as part of the simulation.

  • factor_lambda (int or float) – If int, the number of segments per section. If float, multiplies the number of segments given by the standard lambda rule (Carnevale, 2004) to give the number of compartments simulated (default value 1. gives the number given by the lambda rule)

  • v_init (float) – The initial voltage at which the model is initialized [mV]

  • NeuronSimTree can be extended easily with custom point process mechanisms. (A) –

  • make sure that you store the point process in an existing appropriate (Just) –

  • container or in a custom storage container, since if all references (storage) –

  • the hocobject disappear, the object itself will be deleted as well. (to) –

  • code-block: (.) –

    python: class CustomSimTree(NeuronSimTree): def addCustomPointProcessMech(self, loc, **kwargs):

    loc = MorphLoc(loc, self)

    # create the point process pp = h.custom_point_process(self.sections[loc[‘node’]](loc[‘x’])) pp.arg1 = kwargs[‘arg1’] pp.arg2 = kwargs[‘arg2’] …

    self.storage_container_for_point_process.append(pp)

  • you define a custom storage container, make sure that you overwrite the (If) –

  • and deleteModel() functions to make sure it is created and (`__init__()`) –

  • properly. (deleted) –

NeuronSimTree.initModel([dt, t_calibrate, …])

Initialize hoc-objects to simulate the neuron model implemented by this tree.

NeuronSimTree.deleteModel()

Delete all stored hoc-objects

NeuronSimTree.addShunt(loc, g, e_r)

Adds a static conductance at a given location

NeuronSimTree.addDoubleExpCurrent(loc, tau1, …)

Adds a double exponential input current at a given location

NeuronSimTree.addExpSynapse(loc, tau, e_r)

Adds a single-exponential conductance-based synapse

NeuronSimTree.addDoubleExpSynapse(loc, tau1, …)

Adds a double-exponential conductance-based synapse

NeuronSimTree.addNMDASynapse(loc, tau, tau_nmda)

Adds a single-exponential conductance-based synapse with an AMPA and an NMDA component

NeuronSimTree.addDoubleExpNMDASynapse(loc, …)

Adds a double-exponential conductance-based synapse with an AMPA and an NMDA component

NeuronSimTree.addIClamp(loc, amp, delay, dur)

Injects a DC current step at a given lcoation

NeuronSimTree.addSinClamp(loc, amp, delay, …)

Injects a sinusoidal current at a given lcoation

NeuronSimTree.addOUClamp(loc, tau, mean, …)

Injects a Ornstein-Uhlenbeck current at a given lcoation

NeuronSimTree.addOUconductance(loc, tau, …)

Injects a Ornstein-Uhlenbeck conductance at a given location

NeuronSimTree.addOUReversal(loc, tau, mean, …)

NeuronSimTree.addVClamp(loc, e_c, dur)

Adds a voltage clamp at a given location

NeuronSimTree.setSpikeTrain(syn_index, …)

Each hoc point process that receive spikes through should by appended to the synapse stack (stored under the list self.syns).

NeuronSimTree.run(t_max[, downsample, …])

Run the NEURON simulation.

NeuronSimTree.calcEEq([t_dur, set_e_eq])

Compute the equilibrium potentials in the middle (x=0.5) of each node.

Other Classes

Fitting reduced models

class CompartmentFitter(phys_tree, e_hs=array([- 75.0, - 55.0, - 35.0, - 15.0]), freqs=array([0.0]), name='dont save', path='')[source]

Helper class to streamline fitting reduced compartmental models

Variables
  • tree (neat.PhysTree()) – The full tree based on which reductions are made

  • e_hs (np.array of float) – The holding potentials for which quasi active expansions are computed

  • freqs (np.array of float or complex (default is np.array([0.]))) – The frequencies at which impedance matrices are evaluated

  • name (str (default 'dont save')) – name of files in which intermediate trees required for the fit are stored. Details about what is in the actual pickle files are appended as a suffix to name. Default is to not store intermediate files.

  • path (str (default '')) – specify a path under which the intermediate files are saved (only if name is specified). Default is empty string, which means that intermediate files are stored in the working directory.

To implement the default methodology.

CompartmentFitter.setCTree(loc_arg[, …])

Store an initial neat.CompartmentTree, providing a tree structure scaffold for the fit for a given set of locations.

CompartmentFitter.fitModel(loc_arg[, …])

Runs the full fit for a set of locations (the location are automatically extended with the bifurcation locs)

To check the faithfullness of the passive reduction, the following functions implement vizualisation of impedance kernels.

CompartmentFitter.checkPassive(loc_arg[, …])

Checks the impedance kernels of the passive model.

CompartmentFitter.getKernels([recompute, pprint])

Returns the impedance kernels as a double nested list of “neat.Kernel”.

CompartmentFitter.plotKernels([alphas, …])

Plots the impedance kernels.

Individual fit functions.

CompartmentFitter.createTreeGF([channel_names])

Create a FitTreeGF copy of the old tree, but only with the channels in channel_names.

CompartmentFitter.createTreeSOV([eps])

Create a SOVTree copy of the old tree

CompartmentFitter.fitPassiveLeak([…])

Fit leak only.

CompartmentFitter.fitPassive([…])

Fit the steady state passive model, consisting only of leak and coupling conductances, but ensure that the coupling conductances takes the passive opening of all channels into account

CompartmentFitter.evalChannel(channel_name)

Evaluate the impedance matrix for the model restricted to a single ion channel type.

CompartmentFitter.fitChannels([recompute, …])

Fit the active ion channel parameters

CompartmentFitter.fitCapacitance([inds, …])

Fit the capacitances of the model to the largest SOV time scale

CompartmentFitter.setEEq([t_max, dt, …])

Set equilibrium potentials, measured from neuron simulation.

CompartmentFitter.getEEq(e_eqs_type, **kwargs)

Get equilibrium potentials.

CompartmentFitter.fitEEq(**kwargs)

Fits the leak potentials of the reduced model to yield the same equilibrium potentials as the full model

CompartmentFitter.fitSynRescale(c_locarg, …)

Computes the rescaled conductances when synapses are moved to compartment locations, assuming a given average conductance for each synapse.

Defining ion channels

class IonChannel[source]

Base ion channel class that implements linearization and code generation for NEURON (.mod-files) and C++.

Userdefined ion channels should inherit from this class and implement the define() function, where the specific attributes of the ion channel are set.

The ion channel current is of the form

\[i_{chan} = \overline{g} \, p_o(x_1, ... , x_n) \, (e - v)\]

where \(p_o\) is the open probability defined as a function of a number of state variables. State variables evolve according to

\[\dot{x}_i = f_i(x_i, v, c_1, ..., c_k)\]

with \(c_1, ..., c_n\) the (optional) set of concentrations the ion channel depends on. There are two canonical ways to define \(f_i\), either based on reaction rates \(\alpha\) and \(\beta\):

\[\dot{x}_i = \alpha_i(v) \, (1 - x_i) - \beta_i(v) \, x_i,\]

or based on an asymptotic value \(x_i^{\infty}\) and time-scale \(\tau_i\)

\[\dot{x}_i = \frac{x_i^{\infty}(v) - x_i}{\tau_i(v)}.\]

IonChannel accepts handles either description. For the former description, dicts self.alpha and self.beta must be defined with as keys the names of every state variable in the open probability. Similarly, for the latter description, dicts self.tauinf and self.varinf must be defined with as keys the name of every state variable.

The user must define the attributes p_open, and either alpha and beta or tauinf and varinf in the define() function. The other attributes ion, conc, q10, temp, and e are optional.

Parameters
  • p_open (str) – The open probability of the ion channel.

  • alpha (dict {str: str}) – dictionary of the rate function for each state variables. Keys must correspond to the name of every state variable in p_open, values must be formulas written as strings with v and possible ion as variabels

  • beta (dict {str: str}) – dictionary of the rate function for each state variables. Keys must correspond to the name of every state variable in p_open, values must be formulas written as strings with v and possible ion as variabels

  • tauinf (dict {str: str}) – state variable time scale and asymptotic activation level. Keys must correspond to the name of every state variable in p_open, values must be formulas written as strings with v and possible ion as variabels

  • varinf (dict {str: str}) – state variable time scale and asymptotic activation level. Keys must correspond to the name of every state variable in p_open, values must be formulas written as strings with v and possible ion as variabels

  • ion (str ('na', 'ca', 'k' or ''), optional) – The ion to which the ion channel is permeable

  • conc (set of str (containing 'na', 'ca', 'k') or dict of {str: float}) – The concentrations the ion channel activation depends on. Can be a set of ions or a dict with the ions as keys and default values as float.

  • q10 (str, optional) – Temperature dependence of the state variable rate functions. May be a float or a string convertible to a sympy expression containing the temp parameter (temperature in [deg C]). This factor divides the time-scales :math:` au_i(v)` of the ion channel. If not given, default is 1.

  • temp (float, optional) – The temperature at which the ion channel is evaluated. Can be modified after initializiation by calling IonChannel.setDefaultParams(temp=new_temperature). If not given, the evaluates self.q10 at the default temperature of 36 degC.

  • e (float, optional) – Reversal of the ion channel in [mV]. functions that need it allow the default value to be overwritten with a keyword argument. If nothing is provided, will take a default reversal for self.ion (which is -85 mV for ‘K’, 50 mV for ‘Na’ and 50 mV for ‘Ca’). If no ion is provided, errors will occur if functions that need e are called without specifying the value as a keyword argument.

Examples

>>> class Na_Ta(IonChannel):
>>>     def define(self):
>>>         # from (Colbert and Pan, 2002), Used in (Hay, 2011)
>>>         self.ion = 'na'
>>>         # concentrations the ion channel depends on
>>>         self.conc = {}
>>>         # define channel open probability
>>>         self.p_open = 'h * m ** 3'
>>>         # define activation functions
>>>         self.alpha, self.beta = {}, {}
>>>         self.alpha['m'] =  '0.182 * (v + 38.) / (1. - exp(-(v + 38.) / 6.))' # 1/ms
>>>         self.beta['m']  = '-0.124 * (v + 38.) / (1. - exp( (v + 38.) / 6.))' # 1/ms
>>>         self.alpha['h'] = '-0.015 * (v + 66.) / (1. - exp( (v + 66.) / 6.))' # 1/ms
>>>         self.beta['h']  =  '0.015 * (v + 66.) / (1. - exp(-(v + 66.) / 6.))' # 1/ms
>>>         # temperature factor for reaction rates
>>>         self.q10 = '2.3^((temp - 23.)/10.)'

IonChannel.setDefaultParams(**kwargs)

**kwargs

IonChannel.computePOpen(v, **kwargs)

Compute the open probability of the ion channel

IonChannel.computeDerivatives(v, **kwargs)

Compute: (i) the derivatives of the open probability to the state variables (ii) The derivatives of state functions to the voltage (iii) The derivatives of state functions to the state variables

IonChannel.computeDerivativesConc(v, **kwargs)

Compute the derivatives of the state functions to the concentrations

IonChannel.computeVarinf(v)

Compute the asymptotic values for the state variables at a given activation level

IonChannel.computeTauinf(v)

Compute the time-scales for the state variables at a given activation level

IonChannel.computeLinear(v, freqs, **kwargs)

Combute the contributions of the state variables to the linearized channel current

IonChannel.computeLinearConc(v, freqs, ion, …)

Combute the contributions of the state variables to the linearized channel current

IonChannel.computeLinSum(v, freqs[, e])

Combute the linearized channel current contribution (without concentributions from the concentration - see computeLinConc())

IonChannel.computeLinConc(v, freqs, ion[, e])

Combute the linearized channel current contribution from the concentrations

Neural evaluation tree simulator

Compute Fourrier transforms

class FourrierTools(tarr, fmax=7, base=10, num=200)[source]

Performs an accurate Fourrier transform on functions evaluated at a given array of temporal grid points

Parameters
  • tarr (np.array of floats,) – the time points (ms) at which the function is evaluated, have to be regularly spaced

  • fmax (float, optional (default 7.)) – the maximum value to which the logarithm is evaluated to get the maximum evaluation frequency

  • base (float, optional (defaul 10)) – the base of the logarithm used to generated the logspace

  • num (int, even, optional (default 200)) – Number of points. the eventual number of points in frequency space is (2+1/2)*num

Variables
  • s (np.array of complex) – The frequencies at which input arrays in the Fourrier domain are supposed to be evaluated

  • t (np.array of real) – The time array at which input arrays in the time domain are supposed to be evaluated

  • ind_0s (int) – Index of the zero frequency component in self.s

FourrierTools.__call__(arr)

Evaluate the Fourrier transform of arr

FourrierTools.ft(arr)

Evaluate the Fourrier transform of arr

FourrierTools.ftInv(arr)

Evaluate the inverse Fourrier transform of arr