graph
– Interface for the Aesara graph¶
Reference¶
Core graph classes.

class
aesara.graph.basic.
Apply
(op: OpType, inputs: Sequence[Variable], outputs: Sequence[Variable])[source]¶ A
Node
representing the application of an operation to inputs.Basically, an
Apply
instance is an object that represents the Python statementoutputs = op(*inputs)
.This class is typically instantiated by a
Op.make_node
method, which is called byOp.__call__
.The function
aesara.compile.function.function
usesApply.inputs
together withVariable.owner
to search the expression graph and determine which inputs are necessary to compute the function’s outputs.A
Linker
uses theApply
instance’sop
field to compute numeric values for the output variables.Notes
The
Variable.owner
field of eachApply.outputs
element is set toself
inApply.make_node
.If an output element has an owner that is neither
None
norself
, then aValueError
exception will be raised.
clone
(clone_inner_graph: bool = False) Apply[OpType] [source]¶ Clone this
Apply
instance.Parameters: clone_inner_graph – If True
, cloneHasInnerGraph
Op
s and their innergraphs.Return type: A new Apply
instance with new outputs.Notes
Tags are copied from
self
to the returned instance.

clone_with_new_inputs
(inputs: Sequence[Variable], strict=True, clone_inner_graph=False) Apply[OpType] [source]¶ Duplicate this
Apply
instance in a new graph.Parameters:  inputs (list of Variables) – List of
Variable
instances to use as inputs.  strict (bool) – If
True
, the type fields of all the inputs must be equal to the current ones (or compatible, for instanceTensorType
of the same dtype and broadcastable patterns, in which case they will be converted into currentType
), and returned outputs are guaranteed to have the same types asself.outputs
. IfFalse
, then there’s no guarantee that the clone’s outputs will have the same types asself.outputs
, and cloning may not even be possible (it depends on theOp
).  clone_inner_graph (bool) – If
True
, cloneHasInnerGraph
Op
s and their innergraphs.
Returns: An
Apply
instance with the sameOp
but different outputs.Return type: object
 inputs (list of Variables) – List of

default_output
()[source]¶ Returns the default output for this node.
Returns: An element of self.outputs, typically self.outputs[0]. Return type: Variable instance Notes
May raise AttributeError self.op.default_output is out of range, or if there are multiple outputs and self.op.default_output does not exist.


class
aesara.graph.basic.
AtomicVariable
(type: _TypeType, name: Optional[str] = None, **kwargs)[source]¶ A node type that has no ancestors and should never be considered an input to a graph.

clone
(**kwargs)[source]¶ Return a new, unowned
Variable
likeself
.Parameters: **kwargs (dict) – Optional “name” keyword argument for the copied instance. Same as self.name
if value not provided.Returns: A new Variable
instance with no owner or index.Return type: Variable instance Notes
Tags and names are copied to the returned instance.


class
aesara.graph.basic.
Constant
(type: _TypeType, data: Any, name: Optional[str] = None)[source]¶ A
Variable
with a fixeddata
field.Constant
nodes make numerous optimizations possible (e.g. constant inlining in C code, constant folding, etc.)Notes
The data field is filtered by what is provided in the constructor for the
Constant
’s type field.
clone
(**kwargs)[source]¶ Return a new, unowned
Variable
likeself
.Parameters: **kwargs (dict) – Optional “name” keyword argument for the copied instance. Same as self.name
if value not provided.Returns: A new Variable
instance with no owner or index.Return type: Variable instance Notes
Tags and names are copied to the returned instance.

get_test_value
()[source]¶ Get the test value.
Raises: TestValueError –


class
aesara.graph.basic.
Node
[source]¶ A
Node
in an Aesara graph.Currently, graphs contain two kinds of
Nodes
:Variable
s andApply
s. Edges in the graph are not explicitly represented. Instead eachNode
keeps track of its parents viaVariable.owner
/Apply.inputs
.

class
aesara.graph.basic.
NominalVariable
(id: _IdType, typ: _TypeType, **kwargs)[source]¶ A variable that enables alphaequivalent comparisons.

clone
(**kwargs)[source]¶ Return a new, unowned
Variable
likeself
.Parameters: **kwargs (dict) – Optional “name” keyword argument for the copied instance. Same as self.name
if value not provided.Returns: A new Variable
instance with no owner or index.Return type: Variable instance Notes
Tags and names are copied to the returned instance.


class
aesara.graph.basic.
Variable
(type: _TypeType, owner: OptionalApplyType, index: Optional[int] = None, name: Optional[str] = None)[source]¶ A Variable is a node in an expression graph that represents a variable.
The inputs and outputs of every
Apply
areVariable
instances. The input and output arguments to create afunction
are alsoVariable
instances. AVariable
is like a stronglytyped variable in some other languages; eachVariable
contains a reference to aType
instance that defines the kind of value theVariable
can take in a computation.A
Variable
is a container for four important attributes:type
aType
instance defining the kind of value thisVariable
can have,owner
eitherNone
(for graph roots) or theApply
instance of whichself
is an output,index
the integer such thatowner.outputs[index] is this_variable
(ignored ifowner
isNone
),name
a string to use in prettyprinting and debugging.
There are a few kinds of
Variable
s to be aware of: AVariable
which is the output of a symbolic computation has a reference to theApply
instance to which it belongs (property: owner) and the position of itself in the owner’s output list (property: index).Variable
(this base type) is typically the output of a symbolic computation.Constant
: a subclass which adds a default and unreplaceablevalue
, and requires that owner is None.TensorVariable
subclass ofVariable
that represents anumpy.ndarray
 object.
TensorSharedVariable
: a shared version ofTensorVariable
.SparseVariable
: a subclass ofVariable
that represents ascipy.sparse.{csc,csr}_matrix
object.RandomVariable
.
A
Variable
which is the output of a symbolic computation will have an owner not equal to None.Using a
Variable
s’ owner field and anApply
node’s inputs fields, one can navigate a graph from an output all the way to the inputs. The opposite direction is possible with aFunctionGraph
and itsFunctionGraph.clients
dict
, which mapsVariable
s to a list of their clients.Parameters:  type (a Type instance) – The type governs the kind of data that can be associated with this variable.
 owner (None or Apply instance) – The
Apply
instance which computes the value for this variable.  index (None or int) – The position of this
Variable
in owner.outputs.  name (None or str) – A string for prettyprinting and debugging.
Examples
import aesara import aesara.tensor as at a = at.constant(1.5) # declare a symbolic constant b = at.fscalar() # declare a symbolic floatingpoint scalar c = a + b # create a simple expression f = aesara.function([b], [c]) # this works because a has a value associated with it already assert 4.0 == f(2.5) # bind 2.5 to an internal copy of b and evaluate an internal c aesara.function([a], [c]) # compilation error because b (required by c) is undefined aesara.function([a,b], [c]) # compilation error because a is constant, it can't be an input
The python variables
a, b, c
all refer to instances of typeVariable
. TheVariable
referred to bya
is also an instance ofConstant
.
clone
(**kwargs)[source]¶ Return a new, unowned
Variable
likeself
.Parameters: **kwargs (dict) – Optional “name” keyword argument for the copied instance. Same as self.name
if value not provided.Returns: A new Variable
instance with no owner or index.Return type: Variable instance Notes
Tags and names are copied to the returned instance.

eval
(inputs_to_values=None)[source]¶ Evaluate the
Variable
.Parameters: inputs_to_values – A dictionary mapping Aesara Variable
s to values.Examples
>>> import numpy as np >>> import aesara.tensor as at >>> x = at.dscalar('x') >>> y = at.dscalar('y') >>> z = x + y >>> np.allclose(z.eval({x : 16.3, y : 12.1}), 28.4) True
We passed
eval()
a dictionary mapping symbolic AesaraVariable
s to the values to substitute for them, and it returned the numerical value of the expression.Notes
eval()
will be slow the first time you call it on a variable – it needs to callfunction()
to compile the expression behind the scenes. Subsequent calls toeval()
on that same variable will be fast, because the variable caches the compiled function.This way of computing has more overhead than a normal Aesara function, so don’t use it too much in real scripts.

get_parents
()[source]¶ Return a list of the parents of this node. Should return a copy–i.e., modifying the return value should not modify the graph structure.

get_test_value
()[source]¶ Get the test value.
Raises: TestValueError –

aesara.graph.basic.
ancestors
(graphs: Iterable[Variable], blockers: Optional[Collection[Variable]] = None) Generator[Variable, None, None] [source]¶ Return the variables that contribute to those in given graphs (inclusive).
Parameters: Yields: Variable
s – All input nodes, in the order found by a leftrecursive depthfirst search started at the nodes ingraphs
.

aesara.graph.basic.
applys_between
(ins: Collection[Variable], outs: Iterable[Variable]) Generator[Apply, None, None] [source]¶ Extract the
Apply
s contained within the subgraph between given input and output variables.Parameters: Yields:

aesara.graph.basic.
as_string
(inputs: ~typing.List[~aesara.graph.basic.Variable], outputs: ~typing.List[~aesara.graph.basic.Variable], leaf_formatter=<class 'str'>, node_formatter=<function default_node_formatter>) List[str] [source]¶ Returns a string representation of the subgraph between
inputs
andoutputs
.Parameters: Returns: Returns a string representation of the subgraph between
inputs
andoutputs
. If the same node is used by several other nodes, the first occurrence will be marked as*n > description
and all subsequent occurrences will be marked as*n
, wheren
is an id number (ids are attributed in an unspecified order and only exist for viewing convenience).Return type: list of str

aesara.graph.basic.
clone
(inputs: List[Variable], outputs: List[Variable], copy_inputs: bool = True, copy_orphans: Optional[bool] = None, clone_inner_graphs: bool = False) Tuple[Collection[Variable], Collection[Variable]] [source]¶ Copies the subgraph contained between inputs and outputs.
Parameters:  inputs – Input
Variable
s.  outputs – Output
Variable
s.  copy_inputs – If
True
, the inputs will be copied (defaults toTrue
).  copy_orphans – When
None
, use thecopy_inputs
value. WhenTrue
, new orphans nodes are created. WhenFalse
, original orphans nodes are reused in the new graph.  clone_inner_graphs (bool) – If
True
, cloneHasInnerGraph
Op
s and their innergraphs.
Return type: The inputs and outputs of that copy.
Notes
A constant, if in the
inputs
list is not an orphan. So it will be copied conditional on thecopy_inputs
parameter; otherwise, it will be copied conditional on thecopy_orphans
parameter. inputs – Input

aesara.graph.basic.
clone_get_equiv
(inputs: Sequence[Variable], outputs: Sequence[Variable], copy_inputs: bool = True, copy_orphans: bool = True, memo: Optional[Dict[Union[Apply, Variable, Op], Union[Apply, Variable, Op]]] = None, clone_inner_graphs: bool = False, **kwargs) Dict[Union[Apply, Variable, Op], Union[Apply, Variable, Op]] [source]¶ Clone the graph between
inputs
andoutputs
and return a map of the cloned objects.This function works by recursively cloning inputs and rebuilding a directed graph from the inputs up.
If
memo
already contains entries for some of the objects in the graph, those objects are replaced with their values inmemo
and not unnecessarily cloned.Parameters:  inputs – Inputs of the graph to be cloned.
 outputs – Outputs of the graph to be cloned.
 copy_inputs –
True
means to create the cloned graph from cloned input nodes.False
means to clone a graph that is rooted at the original input nodes.Constant
s are not cloned.  copy_orphans – When
True
, inputs with no owners are cloned. WhenFalse
, original inputs are reused in the new graph. Cloning is not performed forConstant
s.  memo – Optionally start with a partlyfilled dictionary for the return value. If a dictionary is passed, this function will work inplace on that dictionary and return it.
 clone_inner_graphs – If
True
, cloneHasInnerGraph
Op
s and their innergraphs.  kwargs – Keywords passed to
Apply.clone_with_new_inputs
.

aesara.graph.basic.
clone_node_and_cache
(node: Apply, clone_d: Dict[Union[Apply, Variable, Op], Union[Apply, Variable, Op]], clone_inner_graphs=False, **kwargs) Optional[Apply] [source]¶ Clone an
Apply
node and cache the results inclone_d
.This function handles
Op
clones that are generated by innergraph cloning.Returns: None
if all ofnode
’s outputs are already inclone_d
; otherwise, return the clone of
node
.

aesara.graph.basic.
clone_replace
(output: Collection[Variable], replace: Optional[Union[Iterable[Tuple[Variable, Variable]], Dict[Variable, Variable]]] = None, **rebuild_kwds) List[Variable] [source]¶ Clone a graph and replace subgraphs within it.
It returns a copy of the initial subgraph with the corresponding substitutions.
Parameters:  output – Aesara expression that represents the computational graph.
 replace – Dictionary describing which subgraphs should be replaced by what.
 rebuild_kwds – Keywords to
rebuild_collect_shared
.

aesara.graph.basic.
equal_computations
(xs: List[Union[ndarray, Variable]], ys: List[Union[ndarray, Variable]], in_xs: Optional[List[Variable]] = None, in_ys: Optional[List[Variable]] = None) bool [source]¶ Checks if Aesara graphs represent the same computations.
The two lists
xs
,ys
should have the same number of entries. The function checks if for any corresponding pair(x, y)
fromzip(xs, ys)
x
andy
represent the same computations on the same variables (unless equivalences are provided usingin_xs
,in_ys
).If
in_xs
andin_ys
are provided, then when comparing a nodex
with a nodey
they are automatically considered as equal if there is some indexi
such thatx == in_xs[i]
andy == in_ys[i]
(and they both have the same type). Note thatx
andy
can be in the listxs
andys
, but also represent subgraphs of a computational graph inxs
orys
.Parameters: Return type: bool

aesara.graph.basic.
general_toposort
(outputs: Iterable[T], deps: Callable[[T], Union[OrderedSet, List[T]]], compute_deps_cache: Optional[Callable[[T], Optional[Union[OrderedSet, List[T]]]]] = None, deps_cache: Optional[Dict[T, List[T]]] = None, clients: Optional[Dict[T, List[T]]] = None) List[T] [source]¶ Perform a topological sort of all nodes starting from a given node.
Parameters:  deps (callable) – A Python function that takes a node as input and returns its dependence.
 compute_deps_cache (optional) – If provided,
deps_cache
should also be provided. This is a function likedeps
, but that also caches its results in adict
passed asdeps_cache
.  deps_cache (dict) – A
dict
mapping nodes to their children. This is populated bycompute_deps_cache
.  clients (dict) – If a
dict
is passed, it will be filled with a mapping of nodestoclients for each node in the subgraph.
Notes
deps(i)
should behave like a pure function (no funny business with internal state).deps(i)
will be cached by this function (to be fast).The order of the return value list is determined by the order of nodes returned by the
deps
function.The second option removes a Python function call, and allows for more specialized code, so it can be faster.

aesara.graph.basic.
get_var_by_name
(graphs: Iterable[Variable], target_var_id: str, ids: str = 'CHAR') Tuple[Variable, ...] [source]¶ Get variables in a graph using their names.
Parameters:  graphs – The graph, or graphs, to search.
 target_var_id – The name to match against either
Variable.name
orVariable.auto_name
.
Return type: A
tuple
containing all theVariable
s that matchtarget_var_id
.

aesara.graph.basic.
graph_inputs
(graphs: Iterable[Variable], blockers: Optional[Collection[Variable]] = None) Generator[Variable, None, None] [source]¶ Return the inputs required to compute the given Variables.
Parameters: Yields:  Input nodes with no owner, in the order found by a leftrecursive
 depthfirst search started at the nodes in
graphs
.

aesara.graph.basic.
io_connection_pattern
(inputs, outputs)[source]¶ Return the connection pattern of a subgraph defined by given inputs and outputs.

aesara.graph.basic.
io_toposort
(inputs: Iterable[Variable], outputs: Reversible[Variable], orderings: Optional[Dict[Apply, List[Apply]]] = None, clients: Optional[Dict[Variable, List[Variable]]] = None) List[Apply] [source]¶ Perform topological sort from input and output nodes.
Parameters:  inputs (list or tuple of Variable instances) – Graph inputs.
 outputs (list or tuple of Apply instances) – Graph outputs.
 orderings (dict) – Keys are
Apply
instances, values are lists ofApply
instances.  clients (dict) – If provided, it will be filled with mappings of nodestoclients for each node in the subgraph that is sorted.

aesara.graph.basic.
is_in_ancestors
(l_apply: Apply, f_node: Apply) bool [source]¶ Determine if
f_node
is in the graph given byl_apply
.Parameters: Return type: bool

aesara.graph.basic.
list_of_nodes
(inputs: Collection[Variable], outputs: Iterable[Variable]) List[Apply] [source]¶ Return the
Apply
nodes of the graph betweeninputs
andoutputs
.Parameters:

aesara.graph.basic.
op_as_string
(i, op, leaf_formatter=<class 'str'>, node_formatter=<function default_node_formatter>)[source]¶ Return a function that returns a string representation of the subgraph between
i
andop.inputs

aesara.graph.basic.
orphans_between
(ins: Collection[Variable], outs: Iterable[Variable]) Generator[Variable, None, None] [source]¶ Extract the
Variable
s not within the subgraph between input and output nodes.Parameters: Yields: Variable – The
Variable
s upon which one or moreVariable
s inouts
depend, but are neither inins
nor in the subgraph that lies between them.Examples
>>> orphans_between([x], [(x+y).out]) [y]

aesara.graph.basic.
replace_nominals_with_dummies
(inputs, outputs)[source]¶ Replace nominal inputs with dummy variables.
When constructing a new graph with nominal inputs from an existing graph, preexisting nominal inputs need to be replaced with dummy variables beforehand; otherwise, sequential ID ordering (i.e. when nominals are IDed based on the ordered inputs to which they correspond) of the nominals could be broken, and/or circular replacements could manifest.
FYI: This function assumes that all the nominal variables in the subgraphs between
inputs
andoutputs
are present ininputs
.

aesara.graph.basic.
vars_between
(ins: Collection[Variable], outs: Iterable[Variable]) Generator[Variable, None, None] [source]¶ Extract the
Variable
s within the subgraph between input and output nodes.Parameters: Yields:  The
Variable
s that are involved in the subgraph that lies  between
ins
andouts
. This includesins
,outs
, orphans_between(ins, outs)
and all values of all intermediary steps fromins
toouts
.
 The

aesara.graph.basic.
view_roots
(node: Variable) List[Variable] [source]¶ Return the leaves from a search through consecutive viewmaps.

aesara.graph.basic.
walk
(nodes: ~typing.Iterable[~aesara.graph.basic.T], expand: ~typing.Callable[[~aesara.graph.basic.T], ~typing.Optional[~typing.Iterable[~aesara.graph.basic.T]]], bfs: bool = True, return_children: bool = False, hash_fn: ~typing.Callable[[~aesara.graph.basic.T], int] = <builtin function id>) Generator[Union[T, Tuple[T, Optional[Iterable[T]]]], None, None] [source]¶ Walk through a graph, either breadth or depthfirst.
Parameters:  nodes – The nodes from which to start walking.
 expand – A callable that is applied to each node in
nodes
, the results of which are either new nodes to visit orNone
.  bfs – If
True
, breath first search is used; otherwise, depth first search.  return_children – If
True
, each output node will be accompanied by the output ofexpand
(i.e. the corresponding child nodes).  hash_fn – The function used to produce hashes of the elements in
nodes
. The default isid
.
Notes
A node will appear at most once in the return value, even if it appears multiple times in the
nodes
parameter.