1.3.1.1. PyRates.pyrates.frontend.template

1.3.1.1.1. pyrates.frontend.template module

pyrates.frontend.template.clear_cache()[source]

Shorthand to clear template cache for whatever reason.

pyrates.frontend.template.from_yaml(path)[source]

Load template from yaml file. Templates are cached by path. Depending on the ‘base’ key of the yaml template, either a template class is instantiated or the function recursively loads base templates until it hits a known template class.

path

(str) path to YAML template of the form path.to.template_file.template_name or path/to/template_file/template_name.TemplateName. The dot notation refers to a path that can be found using python’s import functionality. That means it needs to be a module (a folder containing an __init__.py) located in the Python path (e.g. the current working directory). The slash notation refers to a file in an absolute or relative path from the current working directory. In either case the second-to-last part refers to the filename without file extension and the last part refers to the template name.

pyrates.frontend.template.register_template_class(name, cls)[source]

Register a given template class to the module attribute _known_template_classes. This way new template classes can be registered by users. Could also be used to overwrite existing template classes.

pyrates.frontend.template.to_yaml(template, path: str, **kwargs) None[source]

Save a CircuitTemplate to a yaml file.

template

Instance of a CircuitTemplate.

path

(str) path to YAML template of the form path.to.template_file.template_name or path/to/template_file/template_name.TemplateName. The dot notation refers to a path that can be found using python’s import functionality. That means it needs to be a module (a folder containing an __init__.py) located in the Python path (e.g. the current working directory). The slash notation refers to a file in an absolute or relative path from the current working directory. In either case the second-to-last part refers to the filename without file extension and the last part refers to the template name.

kwargs

1.3.1.1.2. pyrates.frontend.template.abc module

Abstract base classes

class pyrates.frontend.template.abc.AbstractBaseTemplate(name: str, path: Optional[str] = None, description: str = 'A template.')[source]

Bases: object

Abstract base class for templates

__repr__()[source]

Defines how an instance identifies itself when called with str() or repr(), e.g. when shown in an interactive terminal. Shows Class name and path that was used to construct the class.

apply(*args, **kwargs)[source]

Converts the template into its corresponding intermediate representation class.

classmethod from_yaml(path)[source]

Load a template from yaml file. After importing the template, this method also checks whether the resulting template is actually an instance of the class that this method was called from. This is done to ensure any cls.from_yaml() produces only instances of that class and not other classes for consistency. Templates are cached by path. Depending on the ‘base’ key of the yaml template, either a template class is instantiated or the function recursively loads base templates until it hits a known template class.

Parameters

path – (str) path to YAML template of the form path.to.template_file.template_name or path/to/template_file/template_name.TemplateName. The dot notation refers to a path that can be found using python’s import functionality. That means it needs to be a module (a folder containing an __init__.py) located in the Python path (e.g. the current working directory). The slash notation refers to a file in an absolute or relative path from the current working directory. In either case the second-to-last part refers to the filename without file extension and the last part refers to the template name.

target_ir = None
to_yaml(path, **kwargs) None[source]

Saves template to YAML file.

update_template(*args, **kwargs)[source]

Updates the template with a given list of arguments and returns a new instance of the template class.

1.3.1.1.3. pyrates.frontend.template.circuit module

Basic neural mass backend class plus derivations of it.

This module includes the base circuit class that manages the set-up and simulation of population networks. Additionally, it features various subclasses that act as circuit constructors and allow to build circuits based on different input arguments. For more detailed descriptions, see the respective docstrings.

class pyrates.frontend.template.circuit.CircuitTemplate(name: str, path: Optional[str] = None, description: str = 'A circuit template.', circuits: Optional[dict] = None, nodes: Optional[dict] = None, edges: Optional[List[tuple]] = None)[source]

Bases: AbstractBaseTemplate

Base class for hierarchical networks, composed of either nodes or other circuits, connected by edges.

Parameters
  • name – String-based label of the network. Merely serves identification purposes.

  • path – Path to the YAML template this template was loaded from. If the CircuitTemplate is not loaded from a YAML template, this parameter can be ignored.

  • description – Optional description of the network. Merely serves documentation purposes.

  • circuits – For hierarchical networks, CircuitTemplate instances can be constructed from a dictionary of other circuits. Keys should be the circuit names and values the CircuitTemplate instances.

  • nodes – Dictionary with keys being node names and values being NodeTemplate instances or paths to YAML definitions of node templates. This parameter has to be left empty of circuits are provided.

  • edges – Lists of tuples, where each tuple contains (1) a source node name, (2) a target node name, (3) an EdgeTemplate instance, path to a YAML definition of an EdgeTemplate or null, and (4) a dictionary with edge attributes.

nodes

Dictionary with keys being node names and values being NodeTemplate instances.

circuits

Dictionary with keys being circuit names and values being CircuitTemplate instances.

edges

List with edge tuples that contain: (1) a source node name, (2) a target node name, (3) an EdgeTemplate instance or None, and (4) a dictionary with edge attributes.

__getitem__(item)[source]

Attempts to return the node with name item.

add_edges_from_matrix(source_var: str, target_var: str, nodes: list, weight=None, template=None, edge_attr: Optional[dict] = None, min_weight: float = 1e-06) None[source]

Adds all possible edges between the source_var and target_var of all passed nodes. Weight and Delay need to be arrays containing scalars for each of those edges.

Parameters
  • source_var – Pointer to a variable on the source nodes (‘op/var’).

  • target_var – Pointer to a variable on the target nodes (‘op/var’).

  • nodes – List of node names that should be connected to each other

  • weight – Optional N x N matrix with edge weights (N = number of nodes). If not passed, all edges receive a weight of 1.0.

  • template – Can be link to edge template that should be used for each edge.

  • edge_attr – Additional edge attributes. Can either be N x N matrices or other scalars/objects.

  • min_weight – Minimum absolute value a weight needs to have in order to be implemented as an edge.

Return type

None

add_node_template(node: Union[str, list], template: NodeTemplate) None[source]

Add node template to nodes or circuits list.

Parameters
  • node – Can be a simple string or a list of strings. If the CircuitTemplate is a hierarchical circuit (composed of circuits itself), different list entries should refer to the different hierarchy levels. Alternatively, separation via slashes can be used if a string is provided.

  • template – NodeTemplate instance of the node to-be-added.

Return type

None

apply(adaptive_steps: Optional[bool] = None, label: Optional[str] = None, node_values: Optional[dict] = None, edge_values: Optional[dict] = None, vectorize: bool = True, verbose: bool = True, **kwargs) None[source]

Create a CircuitIR instance based on the template.

Parameters
  • adaptive_steps – If true, a numerical solver with step-size adaptation can be used to integrate the network dynamics over time.

  • label – (optional) Assign a label that is saved as a sort of name to the circuit instance. This is particularly relevant, when adding multiple circuits to a bigger circuit. This way circuits can be identified by their given label.

  • node_values – (optional) Dictionary containing values (and possibly other variable properties) that overwrite defaults in specific nodes/operators/variables. Values must be given in the form: {‘node/op/var’: value}

  • edge_values – (optional) Dictionary containing source and target variable pairs as items and value dictionaries as values (e.g. {(‘source/op1/var1’, ‘target/op1/var2’): {‘weight’: 0.3, ‘delay’: 1.0}}). Can be used to overwrite default values defined in template.

  • vectorize – If true, nodes that are governed by the same underlying equations will be vectorized, i.e. grouped together.

  • verbose – If true, updates about the backend translation process will be given.

Return type

None

clear()[source]

Removes all temporary files and directories that may have been created during simulations of that circuit. Also deletes operator template caches, _imports and path variables from working memory.

collect_edges(delay_info: bool = False) List[tuple][source]

Collect all edges that exist in circuit.

Parameters

delay_info – If true, it will be indicated via a 5th tuple entry for each edge whether it contains a delay or not.

Returns

  • List of edge tuples with entries 1 - source variable, 2 - target variable, 3 - edge template,

  • 4 - edge dictionary. Source and target variables are strings that use slash notations to resolve node

  • hierarchies.

property compute_graph

Instance of pyrates.backend.computegraph.ComputeGraph that contains a graph representation of all network equations that this CircuitTemplate contains.

get_edge(source: str, target: str, idx: Optional[int] = None) tuple[source]

Extract edge information from network.

Parameters
  • source – Source node of edge.

  • target – Target node of edge.

  • idx – Index of the desired edge among all edges from source to target.

Returns

Has 4 entries: 1 - source, 2 - target, 3 - edge template, 4 - edge attributes.

Return type

tuple

get_edges(source: Union[str, list], target: Union[str, list]) List[tuple][source]

Extracts nodes from the CircuitTemplate that match the provided identifier.

Parameters
  • source – Can be a simple string or a list of strings. If the CircuitTemplate is a hierarchical circuit (composed of circuits itself), different list entries should refer to the different hierarchy levels. Alternatively, separation via slashes can be used if a string is provided.

  • target – Can be a simple string or a list of strings. If the CircuitTemplate is a hierarchical circuit (composed of circuits itself), different list entries should refer to the different hierarchy levels. Alternatively, separation via slashes can be used if a string is provided.

Returns

List of edge keys that match the provided identifier. Each entry is a tuple that includes the source and target variables as well as the edge template. Circuit hierarchy levels are separated via slashes in the variable names.

Return type

List[tuple]

get_node_template(node: Union[str, list]) NodeTemplate[source]

Extract NodeTemplate from CircuitTemplate.

Parameters

node – Can be a simple string or a list of strings. If the CircuitTemplate is a hierarchical circuit (composed of circuits itself), different list entries should refer to the different hierarchy levels. Alternatively, separation via slashes can be used if a string is provided.

Returns

Instance of the NodeTemplate of that particular node.

Return type

NodeTemplate

get_nodes(node_identifier: Union[str, list, tuple], var_identifier: Optional[tuple] = None) List[str][source]

Extracts nodes from the CircuitTemplate that match the provided identifier.

Parameters
  • node_identifier – Can be a simple string or a list of strings. If the CircuitTemplate is a hierarchical circuit (composed of circuits itself), different list entries should refer to the different hierarchy levels. Alternatively, separation via slashes can be used if a string is provided.

  • var_identifier – If provided, only nodes will be returned for which this variable is defined.

Returns

List of node keys that match the provided identifier. Each entry is a string that refers to a node of the circuit with circuit hierarchy levels separated via slashes.

Return type

List[str]

get_run_func(func_name: str, step_size: float, inputs: Optional[dict] = None, backend: Optional[str] = None, vectorize: bool = True, verbose: bool = True, clear: bool = False, in_place: bool = True, **kwargs) Tuple[Callable, tuple, tuple, dict][source]

Generate a function that evaluates the vector field of the dynamical system represented by this CircuitTemplate instance.

Parameters
  • func_name – Name of the vector field evaluation function.

  • step_size – Integration step-size. Required for the implementation of the extrinsic inputs.

  • inputs – Dictionary providing extrinsic, time-dependent inputs to the system. Keys are the names of system variables, following the *circuit/node/op/var notation. Values are 1D numpy arrays that represent the input over time with time steps of size step_size.

  • backend

    Name of the backend that should be used for implementing the system equations. Possible choices are:
    • ’default’ or ‘numpy’: A backend based on numpy functions, representing all system variables as

      np.ndarray.

    • ’tensorflow’: A backend that represents the system equations as a tensorflow graph, in which all

      system variables are stored as tf.constant or tf.Variable.

    • ’torch’: A backend based on pytorch which represents all variables as torch.tensor.

    • ’fortran’: Translates all system variables and equations into Fortran90 equivalents and uses

      numpy.f2py to make them available via Python. Requires vectorize to be set to False.

    • ’julia’: Translates all system variables and equations into Julia equivalents and uses PyJulia to

      make them available via Python. Requires vectorize to be set to False. Also requires that the path to the julia executable that should be used for the simulation is provided via the keyword argument julia_path.

  • vectorize – If true, nodes that are governed by the same equation sets will be grouped and the respective equations will be vectorized. If false, all equations will be scalar in nature.

  • verbose – If true updates regarding the status of the run procedure will be displayed.

  • clear – If true, all cached variables will be freed and all temporary files will be deleted after the run procedure. To inspect the vector field evaluation function, clear should be set to False.

  • in_place

  • kwargs – Additional keyword arguments.

Returns

The vector field evaluation function, all its positional arguments, the argument keys, and the indices of the different state variables in the state vector.

Return type

Tuple[Callable, tuple, tuple, dict]

get_var(var: str) tuple[source]
Parameters

var – Identifier of variable in the network.

Returns

2-entry tuple: (1) Backend variable, (2) index of requested variable in the backend variable.

Return type

tuple

get_variable_positions(outputs: Union[dict, str]) tuple[source]

Finds the indices of variables in the system state vector as well as the backend variables from which the variables can be extracted via the indices.

Parameters

outputs – Either a simple variable name, or a dictionary where the keys define the keys of the return dictionaries, whereas the values refer to variables in the network.

Returns

two dictionaries: (1) containing the variable indices, (2) containing the backend variables.

Return type

tuple

property intermediate_representation

Instance of pyrates.ir.CircuitIR that this template is translated into when run or get_run_func are called.

run(simulation_time: float, step_size: float, inputs: Optional[dict] = None, outputs: Optional[Union[dict, list]] = None, sampling_step_size: Optional[float] = None, cutoff: Optional[float] = 0.0, solver: str = 'euler', backend: Optional[str] = None, vectorize: bool = True, verbose: bool = True, clear: bool = True, in_place: Optional[bool] = True, **kwargs) DataFrame[source]

Method for calculating numerical solutions to the initial value problem for the dynamical system defined by this CircuitTemplate instance.

Parameters
  • simulation_time – Total integration time. Unit depends on the definition of the time constants in the system.

  • step_size – Integration step-size. If a numerical solver with fixed step-size is chosen, this step-size determines the accuracy of the numerical solution. Else, it merely defines the inital step-size of the integration algorithm.

  • inputs – Dictionary providing extrinsic, time-dependent inputs to the system. Keys are the names of system variables, following the *circuit/node/op/var notation. Values are 1D numpy arrays that represent the input over time with time steps of size step_size.

  • outputs – Dictionary indicating for which system variables the dynamics over time (i.e. the numerical solution to the initial value problem) should be returned. Keys are the names under which the solutions will be available in the returned pandas.DataFrame. Values are the names of the system variables, following the *circuit/node/op/var notation.

  • sampling_step_size – Step-size at which the return values should be sampled.

  • cutoff – Initial simulation time that should be ignored for the return values.

  • solver

    Numerical solver method that should be used to solve the initial value problem. Possible choices are:
    • ’euler’: standard forward Euler method

    • ’scipy’: Any method that is available via the scipy.integrate.solve_ivp function. See the

    documentation of that function for ways to adjust its default settings. Any arguments to the solve_ivp function can also be passed to the CircuitTemplate.run function.

  • backend

    Name of the backend that should be used for implementing the system equations. Possible choices are:
    • ’default’ or ‘numpy’: A backend based on numpy functions, representing all system variables as

      np.ndarray.

    • ’tensorflow’: A backend that represents the system equations as a tensorflow graph, in which all

      system variables are stored as tf.constant or tf.Variable.

    • ’torch’: A backend based on pytorch which represents all variables as torch.tensor.

    • ’fortran’: Translates all system variables and equations into Fortran90 equivalents and uses

      numpy.f2py to make them available via Python. Requires vectorize to be set to False.

    • ’julia’: Translates all system variables and equations into Julia equivalents and uses PyJulia to

      make them available via Python. Requires vectorize to be set to False. Also requires that the path to the julia executable that should be used for the simulation is provided via the keyword argument julia_path.

  • vectorize – If true, nodes that are governed by the same equation sets will be grouped and the respective equations will be vectorized. If false, all equations will be scalar in nature.

  • verbose – If true updates regarding the status of the run procedure will be displayed.

  • clear – If true, all cached variables will be freed and all temporary files will be deleted after the run procedure.

  • in_place – If false, a deep copy of the template instance will be made before translating it into the backend. This allows to call run multiple times on the same CircuitTemplate instance.

  • kwargs – Additional keyword arguments.

Returns

A Dataframe that includes the time series of the requested output variables.

Return type

pd.DataFrame

target_ir

alias of CircuitIR

to_yaml(path, **kwargs) None[source]

Shorthand to save the CircuitTemplate to a yaml file. After that call, either a new YAML file has been created including all template definitions required to reconstruct the CircuitTemplate instance, or additional operators have been added to the already existing YAML file.

Parameters
  • path – (str) path to YAML template of the form path.to.template_file.template_name or path/to/template_file/template_name.TemplateName. The dot notation refers to a path that can be found using python’s import functionality. That means it needs to be a module (a folder containing an __init__.py) located in the Python path (e.g. the current working directory). The slash notation refers to a file in an absolute or relative path from the current working directory. In either case the second-to-last part refers to the filename without file extension and the last part refers to the template name.

  • kwargs – Additional keyword arguments passed to pyrates.frontend.fileio.yaml.dump_to_yaml

Return type

None

update_template(name: Optional[str] = None, path: Optional[str] = None, description: Optional[str] = None, circuits: Optional[dict] = None, nodes: Optional[dict] = None, edges: Optional[List[tuple]] = None, in_place: bool = False)[source]

Update all entries of the circuit template in their respective ways. See the documentation of CircuitTemplate for a detailed description of the method parameters.

Parameters
  • name – Name of the template.

  • path – Path to the YAML template definition.

  • description – Optional description of the template.

  • circuits – Updates to template circuits. Keys should be the circuit names and values the CircuitTemplate instances.

  • nodes – Updates to template nodes. Keys should be the node names and values the NodeTemplate instances.

  • edges – Updates to template edges. List with edge tuples that contain: (1) a source node name, (2) a target node name, (3) an EdgeTemplate instance or None, and (4) a dictionary with edge attributes.

  • in_place – If true, all changes will be made to this particular CircuitTemplate instance and nothing is returned. If False, a new instance with the updates will be returned while keeping the old instance as it was.

Returns

New, updated CircuitTemplate instance.

Return type

CircuitTemplate

update_var(node_vars: Optional[dict] = None, edge_vars: Optional[list] = None)[source]

Update the value of node or edge variables.

Parameters
  • node_vars – Dictionary with keys being pointers to variable names on nodes, using the *circuit/node/op/var notation.

  • edge_vars – List with edge tuples that contain: (1) a source node name, (2) a target node name, (3) an edge index, and (4) a dictionary with edge attributes. The latter can be used to update edge attributes.

Returns

Pointer to the CircuitTemplate instance this method was called from.

Return type

CircuitTemplate

pyrates.frontend.template.circuit.create_input_node(var: str, inp: ndarray, continuous: bool, T: float, vectorized_net: bool) tuple[source]
pyrates.frontend.template.circuit.is_integration_adaptive(solver: str, **solver_kwargs)[source]
pyrates.frontend.template.circuit.update_dict(base_dict: dict, updates: dict)[source]
pyrates.frontend.template.circuit.update_edges(base_edges: List[tuple], updates: List[Union[tuple, dict]])[source]

Add edges to list of edges. Removing or altering is currently not supported.

1.3.1.1.4. pyrates.frontend.template.node module

class pyrates.frontend.template.node.NodeTemplate(name: str, operators: Union[str, List[str], dict, List[AbstractBaseTemplate]], path: Optional[str] = None, description: str = 'A node or an edge.')[source]

Bases: OperatorGraphTemplate

Generic template for a node in the computational backend graph. A single node may encompass several different operators. One template defines a typical structure of a given node type.

static target_ir(label: str, operators: dict, values: Optional[dict] = None, template: Optional[str] = None, **kwargs)[source]

1.3.1.1.5. pyrates.frontend.template.edge module

class pyrates.frontend.template.edge.EdgeTemplate(name: str, operators: Union[str, List[str], dict, List[AbstractBaseTemplate]], path: Optional[str] = None, description: str = 'A node or an edge.')[source]

Bases: OperatorGraphTemplate

Generic template for an edge in the computational backend graph. A single edge may encompass several different operators. One template defines a typical structure of a given edge type.

static target_ir(label: str, operators: dict, values: Optional[dict] = None, template: Optional[str] = None, **kwargs)[source]

1.3.1.1.6. pyrates.frontend.template.operator module

class pyrates.frontend.template.operator.OperatorTemplate(name: str, equations: Union[list, str], variables: dict, path: Optional[str] = None, description: str = 'An operator template.')[source]

Bases: AbstractBaseTemplate

Generic template for an operator with a name, equations, variables and possible initialization conditions. The template can be used to create variations of a specific equations or variables.

__getitem__(item)[source]

Attempts to return the variable with name item.

apply(return_key=False, values: Optional[dict] = None)[source]

Returns the non-editable but unique, cashed definition of the operator.

cache = {}
target_ir

alias of OperatorIR

update_template(name: Optional[str] = None, path: Optional[str] = None, equations: Optional[Union[str, list, dict]] = None, variables: Optional[dict] = None, description: Optional[str] = None)[source]

Update all entries of the Operator template in their respective ways.

pyrates.frontend.template.operator.check_vname(v: str, vtype: str)[source]

1.3.1.1.7. pyrates.frontend.template.operator_graph module

class pyrates.frontend.template.operator_graph.OperatorGraphTemplate(name: str, operators: Union[str, List[str], dict, List[AbstractBaseTemplate]], path: Optional[str] = None, description: str = 'A node or an edge.')[source]

Bases: AbstractBaseTemplate

__getitem__(item)[source]

Attempts to return the operator with name item.

apply(values: Optional[dict] = None, label: Optional[str] = None, **kwargs)[source]

Apply template to gain a node or edge intermediate representation.

Parameters
  • values – dictionary with operator/variable as keys and values to update these variables as items.

  • label – Label of the resulting intermediate representation. If None, the name of the template will be used.

get_op(op: str)[source]
static target_ir(*args, **kwargs)[source]
update_template(name: Optional[str] = None, path: Optional[str] = None, operators: Optional[Union[str, List[str], dict]] = None, description: Optional[str] = None)[source]

Update all entries of a base edge template to a more specific template.

update_var(op: str, var: str, val: Union[float, int])[source]