The VariableBase class#
Aliases#
halerium.core.variable.VariableBase
- class VariableBase(name, shape=(), is_dynamic=False, frame=None, distribution=<class 'halerium.core.distribution.normal_distribution.NormalDistribution'>, dtype=None, **kwargs)#
Common base for Variable and StaticVariable.
Common base for Variable and StaticVariable.
- Parameters:
name (str) – The name of the variable.
shape (tuple) – The (tensor) shape of the variable.
is_dynamic (bool) – Whether the variable is dynamic.
frame – The frame for registering in namespace. The default is None, in which case the calling frame is used.
distribution (DistributionBase, optional) – The distribution class. The default is NormalDistribution.
dtype (str, optional) – The data type of the variable. If provided, the distribution needs to support that dtype.
kwargs – The parameters of the distribution.
- __enter__()#
Enter scope.
The __enter__ method is not to be used directly. Instead the user is to utilize python’s with statement to enter the context of the scopetor.
Entering the context of the scopetor makes it the current scope. All instances of Graph, Entity, Variable, StaticVariable or Operator created in the context will be children of the scopetor.
- Returns:
self – The scopetor itself.
- Return type:
Scopetor
- __exit__(exc_type, exc_val, exc_tb)#
Exit scope.
The __exit__ method is not to be used directly. Instead the user is to utilize python’s with statement to enter and exit the context of the scopetor.
- Parameters:
exc_type – The exception type.
exc_val – The exception value.
exc_tb – The traceback.
- Return type:
None.
- accept(visitor)#
Accept visitor.
- Parameters:
visitor – The visitor to accept.
- Returns:
The result of the visit.
- Return type:
result
- property children#
Children.
A dictionary of all children of the scopetor.
- copy(name=None, strict=True)#
Copy.
Returns a copy of the self. Constructed in the current scope.
- Parameters:
name (str, optional) – The name of the copy. The default is the name of the copied instance.
strict (bool, optional) – If True the scopetor has to be self-contained. If False not self-contained parts are left out and will be set to None in the copied instance. The default is True.
- Returns:
copy_of_self – The copied instance.
- Return type:
- deep_scope()#
This method created a DeepScope instance that allows for direct scoping into grandchildren.
- Example:
``` g = Graph(“g”) with g:
g1 = Graph(“g1”) with g1:
g2 = Graph(“g2”)
- with g.g1.g2.deep_scope():
pass
- Returns:
A DeepScope instance that allows for deep scoping of self.
- Return type:
DeepScope
- depends_on(operators, stop_operators=None, stop_criterion=None, include_links=True)#
Check if self depends on operators.
Check whether the operator depends on another operator. The chain of dependencies will be interrupted by the operators in stop_operators or the stop_criterion.
- Parameters:
operators (Iterable, OperatorBase,) – The operators for which the possible influence on self is to be checked.
stop_operators (iterable, optional) – The operators which interrupt the dependency chain. The default is None.
stop_criterion (callable, optional) – A callable that accepts an operator as an argument and returns True for stop and False otherwise. The default is None which means don’t stop.
include_links (bool, optional) – Whether a linked variable if viewed as dependent on the linked source.
- Returns:
result – Whether self depends on operators
- Return type:
bool
Examples
>>> import halerium >>> a = halerium.core.operator.Const(0.) >>> b = a + 1 >>> c = b + 1 >>> c.depends_on(a) True >>> c.depends_on(a, stop_operators=[b]) False
- property distribution#
The underlying distribution
- dump_dict(strict=True)#
Convert scopetor to specification dict. A specification dict is dictionary that contains only JSON-compatible standard types (list, dict, string, float) and fully specifies all properties of the scopetor.
- Parameters:
strict (bool, optional) – If True the scopetor has to be self-contained. If False not self-contained parts are left out and will be set to None in the specification. The default is True.
- Returns:
specification – A dictionary containing the specifications for self and all its (grand-)children.
- Return type:
dict
- dump_file(fp, strict=True)#
Serialize the scopetor into a JSON formatted stream to
fp
.- Parameters:
fp (filename or file-like object) – If a string is provided a file with that name is created. Otherwise a file-like object (supporting
.write()
) is expected to which the serialized specification is written.strict (bool, optional) – If True the scopetor has to be self-contained. If False not self-contained parts are left out and will be set to None in the specification. The default is True.
- Return type:
None.
- dump_string(strict=True)#
Serialize scopetor into a JSON formatted
str
.- Parameters:
strict (bool, optional) – If True the scopetor has to be self-contained. If False not self-contained parts are left out and will be set to None in the specification. The default is True.
- Returns:
serialized_spec – The serialized JSON formatted
str
containing the specifications for self and all its (grand-)children.- Return type:
str
- enforce_distribution_change_rules()#
Enforce distribution change rules.
Should be called whenever an attempt to change the distribution or one of its parameters is make.
- enforce_distribution_operator_parameter_rules(value)#
Check dynamics compatibility for operator parameters.
- Parameters:
value –
- evaluate(cache=None)#
Evaluate operator.
Evaluate the operator and return a numerical value for it. This involves evaluating all the operator’s operands, all operands of those operands, and so on. When evaluating a variable, a value from its distribution is drawn.
Values computed for operands are stored in a cache for reuse should such a value be required again during the evaluation (e.g. when an operator appears more than once in the operand tree). That cache can be provided with values for operators by the user to be used during evaluation.
- Parameters:
cache (dict, optional) – The cache used to store values of intermediate results for later reuse in case the corresponding expression is encountered again during evaluation. The cache can be used to provide values for operators that might be encountered during evaluation.
- Returns:
The result of evaluating the operator. A number or numpy ndarray.
- Return type:
result
Examples
>>> import halerium.core as hal >>> >>> x = hal.Variable('x', shape=(), mean=0, variance=1) >>> y = hal.exp(x) + 1 >>> z = hal.log(y - 1) >>> z.evaluate({x: 3}) 3.0
- classmethod from_specification(specification=None, file=None, overwrite_name=None, frame=None)#
Create a scopetor instance from a (serialized) specification or from a file containing a serialized specification. Optionally, the top-level name can be replaced.
- Parameters:
specification (dict or str, optional) – Can be either a specification dict or a serialized specification dict in a JSON formatted string or file-like object supporting
.read()
.file (file-handle or file name, optional) – Can be either a file-like object supporting
.read()
or a file path to a file containing a JSON formatted string of a specification. Will be ignored if specification is provided.overwrite_name (str, optional) – If provided, the top-level name of the scopetor will be replaced. Names of children are not affected, only their global names. The default is None.
frame (optional,) – If provided, the scopetor instance will try to register its name in the frame’s namespace
- Returns:
A scopetor instance.
- Return type:
- classmethod from_template(template, name)#
Create a scopetor instance from a serialization.
- Parameters:
template (Template object) – The serialization from which to create an instance.
name (str) – The name given to the instance.
- Raises:
TypeError – If the serialization class does not match the scopetor class an exception is raised.
- Returns:
The instanciated serialization.
- Return type:
- get_all_variable_dependencies(include_links=True)#
Get all variable dependencies.
Get the dependencies of every variable in the scopetor.
- Parameters:
include_links (bool, optional) – Whether a link between variables is seen as a dependency.
- Returns:
dependencies – Every variable has its own key, value pair. The keys of the dict are global names of variables. The values are sets of global names of all variables whose values or moments are being used to calculate the distribution parameters of the variable specified in the key.
- Return type:
dict
- get_all_variables(include_self=True, included_types=None, excluded_types=None)#
Get all variables.
Get all variables in the scopetor, including the scopetor itself if it is a variable, too.
- Parameters:
include_self (bool, optional) – Whether to consider self as part of the set of variables. The default is True.
included_types (type, tuple, optional) – Only variables matching one of the listed types will be included. The default is to include all kinds of (static and dynamic) variables.
excluded_types (type, tuple, optional) – Variables matching one of the listed types will be excluded. The default is to exclude no types.
- Returns:
A set of all variable objects contained in the scopetor.
- Return type:
variables
- get_child_by_name(relative_or_absolute_name, name_is_relative=True)#
Get child by name.
Get a (grand-)child of the scopetor by its relative name. The relative name is assumed to be constructed with
keep_self=False
.- Parameters:
relative_or_absolute_name (str) – The absolute or relative name of the (grand-)child.
name_is_relative (bool) – whether the name is relative
- Returns:
child – The python object corresponding to the relative name.
- Return type:
- Raises:
KeyError – If child is not found.
- get_children(depth=- 1, include_self=False, included_types=None, excluded_types=None)#
Get children.
Get all children up to a given depth-level. For example, with depth-level 2 the method returns all children and grand-children. With depth=-1 all contained scopees are returned, no matter how deep. With include_self=True, self will also be considered a child.
- Parameters:
depth (int, optional) – The maximal depth of children, whose name are returned. A negative value corresponds to infinite depth. The default is -1.
include_self (bool, optional) – Whether to consider self as part of the list of children. The default is False.
included_types (type, tuple, optional) – Only children matching one of the listed types will be included. The default is to include Scopees.
excluded_types (type, tuple, optional) – Children matching one of the listed types will be excluded. The default is to exclude any Inputs, Outputs, or Link.
- Returns:
A set of all collected children.
- Return type:
children
- get_children_names(depth=- 1, include_self=False, included_types=None, excluded_types=None)#
Get global names of children.
Get all children global names up to a given depth-level. For example, with depth-level 2 the method returns all children and grand-children. With depth=-1 the global names of all contained scopetors are returned, no matter how deep. With include_self=True, self will also be considered a child.
- Parameters:
depth (int, optional) – The maximal depth of children, whose name are returned. A negative value corresponds to infinite depth. The default is -1.
include_self (bool, optional) – Whether to consider self as part of the set of children. The default is False.
included_types (type, tuple, optional) – Only children matching one of the listed types will be included. The default is to include Scopees.
excluded_types (type, tuple, optional) – Children matching one of the listed types will be excluded. The default is to exclude any Inputs, Outputs, or Link.
- Returns:
The global names of the children.
- Return type:
child_names
- get_containing_class(scopetor_cls)#
Get the closest parent that is of a specific type.
- Parameters:
scopetor_cls (scopetor subclass) – The scopetor subclass of which the next containing instance is to be found.
- Raises:
ValueError – If no containing scopetor of type scopetor_cls is found, an error is raised.
- Returns:
scope – The containing scopetor of type scopetor_cls.
- Return type:
scopetor_cls
Examples
>>> from halerium.core import Graph, Entity >>> g = Graph("g") >>> with g: >>> e = Entity("e") >>> with e: >>> Entity("m") >>> g.e.m.get_containing_class(Graph) is g True >>> assert g.e.m.get_containing_class(Entity) is g.e True
- get_distribution_parameter(name, check_name=False)#
Get distribution parameter.
- Parameters:
name (str) – The name of the distribution parameter.
check_name (bool, optional) – Whether to check the name is the name of a distribution parameter.
- Returns:
The requested parameter of the distribution.
- Return type:
parameter
- get_immediate_dependencies(follow_links)#
Get immediate dependencies.
Get the immediate dependencies of the operator. - If follow_links, for operators (variables) that are targets of a link,
return the source of that link.
For variables that are not targets of a link, return their distribution’s operator parameters.
For operators with operands (N-ary operators) return the operands.
- Parameters:
follow_links (bool) – Whether to follow links. Otherwise ignore them.
- Returns:
dependencies – The set of operators that self directly depends on.
- Return type:
Set
- get_link()#
Get link.
- Returns:
The link (if any) of self as the target.
- Return type:
link
- get_operator_dependencies(stop_operators=None, stop_criterion=None, include_links=True)#
Get operator dependencies.
Get the operator chain that leads to the operator. The chain of dependencies will be interrupted by the operators in stop_operators or the stop_criterion.
- Parameters:
stop_operators (iterable, optional) – A list, tuple or set of operators which interrupt the dependency chain. The default is None.
stop_criterion (callable, optional) – A callable that accepts an operator as an argument and returns True for stop and False otherwise. The default is None which means don’t stop.
include_links (bool, optional) – Whether a linked variable is viewed as dependent on the linked source.
- Returns:
dependencies – A nested dictionary with the dependecies. Keys are operators, values are again dicts. The key-operators depend on the key-operators of the next dict and so on.
- Return type:
dict
Examples
>>> import halerium >>> a = halerium.core.operator.Const(0.) >>> b = a + 1 >>> c = b + 1 >>> c.get_operator_dependencies() {b: {a: {}} >>> c.depends_on(a, stop_operators=[b]) {b: {}}
- get_relative_name(global_name, keep_self=False)#
Get relative name.
Get the relative name of a (grand-) child of the scopetor.
- Example:
global_name of the scopetor: “a/b/c” global_name provided in argument: “a/b/c/d/e/f”
with keep_self = False we get relative_name = “d/e/f”
with keep_self = True we get relative_name = “c/d/e/f”
- Parameters:
global_name (str) – The global name that is to be converted into a relative name.
keep_self (bool, optional) – Whether or not to keep the name of the scopetor as a prefix. The default is False.
- Raises:
ValueError – The the global name cannot be located within the scopetor an expeption is raised.
- Returns:
relative_name – The relative name extracted from the global name.
- Return type:
str
- get_template(name=None, strict=True)#
Get a serialization of self to create duplicates at will.
- Parameters:
name (str, optional) – The name of the serialization. The default is None.
strict (bool, optional) – If True the scopetor has to be self-contained. If False not self-contained parts are left out and will be set to None in the template. The default is True.
- Returns:
The templated version of self. Can be called to create an equivalent copy of self.
- Return type:
- get_variable_dependencies()#
Get variable dependencies.
Get the global names of all other variables on which the distribution parameters of this variable depend.
- Returns:
dependencies – The global names of all variables whose values are used to calculate the distribution parameters of the variable.
- Return type:
set
- property global_name#
The global name of the scopee.
The global name is a chain of all parent names of this scopee separated by ‘/’ characters.
- has_equivalent_scopee(scopee, compare_children=False)#
Whether there is an equivalent instance of scopee in the scopetor.
- Parameters:
scopee (Scopee) – The scopee for which to find its equivalent in this Scopetor. A Graph, Entity, StaticVariable, or Variable instance.
compare_children (bool, optional) – Whether to compare children for equivalence test.
- Returns:
has_scopee – Whether there is an equivalent scopee in this Scopetor.
- Return type:
bool
- is_child_of(scopetor, include_self=True)#
Whether is child of scopetor.
This method checks whether the scopee is a (grand-) child of a given scopetor.
- Parameters:
scopetor (Scopetor) – The (possible) parent scopetor
include_self (bool) – If True, a.is_child_of(a) would return True. If False, a.is_child_of(a) would return False.
- Returns:
Whether self is a (grand-)child of scopetor or not.
- Return type:
bool
- is_circular(stop_criterion=None)#
- property is_itself_linked#
Checks if itself linked.
Checks if self is the target of a link.
- Returns:
linked – If True, then the entity is already linked to. If False, then the entity itself is link-free.
- Return type:
bool
- property is_linked#
Checks if linked.
Checks if self or any of its children are already the target of a link.
- Returns:
linked – If True, then the entity or a child is already linked to. If False, then the entity and all of its children are link-free.
- Return type:
bool
- link(link)#
Link.
Establishes the link according to a Link instance. This function should not be called by the user.
- Parameters:
link (Link) – A Link instance containing self as target.
- property link_source#
The link source for the variable.
- property name#
The name of the scopee.
- property operators#
- primary_link_source()#
- register(child, frame=None)#
Registers a child with the scopetor.
It is not necessary for the user to call this method. It will be automatically called during the creation of any Graph, Entity, Variable, StaticVariable or Operator.
- Parameters:
child (Scopee) – The child instance
frame (frame, optional) – a frame created with the inspect module. The child will be placed into the namespace of the frame. The default is None.
- reset()#
Resets the scopetor.
The children container is emptied.
The children themselves will still hold references to the scopetor. So if they still exist as python variables or are contained in some user-managed structure this can lead to inconsistencies.
- select_from_operator_dependencies(selection_criterion, pre_stop_operators=None, pre_stop_criterion=None, post_stop_operators=None, post_stop_criterion=None, include_links=True, selected=None)#
Select operators from operator dependency tree.
Scans the operator dependency tree for operators satisfying the selection criterion and collects these operators into a set.
- Parameters:
selection_criterion (callable) – The selection criterion for inclusion. A callable that accepts an operator as an argument and returns True if the argument should be included.
pre_stop_operators (collections.abc.Collection[OperatorBase]) – A list, tuple or set of operators which interrupt the dependency chain before selection. The default is None.
pre_stop_criterion (callable, None) – The stop criterion before selection. A callable that accepts an operator as an argument and returns True when to stop following further dependencies. The default is None which means don’t stop.
post_stop_operators (collections.abc.Collection[OperatorBase]) – A list, tuple or set of operators which interrupt the dependency chain after selection. The default is None.
post_stop_criterion (callable, None) – The stop criterion after selection. A callable that accepts an operator as an argument and returns True when to stop following further dependencies. The default is None which means don’t stop.
include_links (bool) – Whether a linked variable is viewed as dependent on the linked source. The default is True.
selected (Set, None) – The set to which the selected operators are added.
- Returns:
selected – The set to with the selected operators are added.
- Return type:
Set
- set_distribution_parameter(name, value, check_name=True, set_dependent_parameters=True)#
Set distribution parameter.
- Parameters:
name (str) – The name of the parameter to change.
value – The value to change the parameter to.
check_name (bool) – Whether to check if the name is a distribution parameter name.
set_dependent_parameters (bool) – Whether to automatically set any dependent parameters using values derived from the provided parameters. Users should keep this set to the default True.
- to_equivalent_scopee(scopee, compare_children=False, on_failure='raise')#
Find the equivalent instance of scopee in the scopetor.
This method helps finding equivalent scopees in e.g. a copy of the containing scopetor.
- Parameters:
scopee (Scopee) – The scopee for which to return its equivalent in this Scopetor. A Graph, Entity, StaticVariable, or Variable instance.
compare_children (bool, optional) – Whether to compare children for equivalence test.
on_failure (str, None, optional) – How to react if no equivalent can be found.
- Returns:
returns – The equivalent to scopee in this Scopetor.
- Return type:
Scopee, None
- to_equivalent_scopees(fetches, compare_children=False, on_failure='raise')#
Find the equivalent instances of fetches in the scopetor.
This method helps finding equivalent scopees in e.g. a copy of the containing scopetor.
- Parameters:
fetches (list, dict, Scopee) – The Scopee(s) for which to return its equivalent in this Scopetor. A container of Graph, Entity, StaticVariable, or Variable instances. The container can be nested, e.g. a list of dicts or a dict with lists as values as long as the contained objects (for dicts its values that matter) are instances of appropriate classes.
compare_children (bool, optional) – Whether to compare children for equivalence test.
on_failure (str, None, optional) – How to react if no equivalent can be found. Possible values are: - ‘raise’: raise an exception (default), - ‘input’: return the input. - None: return None.
- Returns:
The equivalent(s) to fetches in this Scopetor.
- Return type:
returns
- unlink(force=False, _recursion=False)#
Unlink.
Removes link(s) that have self as target.
- Parameters:
force (bool, optional) – With force=True not only the link to self are removed, but also all (possibly) existing links to its children are removed. i.e. self and all its children are ensured to be link-free. The default is False.
_recursion (bool, optional) – This argument is for managing recursions and should not be altered by the user.
- unregister(child, frame=None)#
Unregisters a child.
The child itself will still hold a reference to the scopetor. So if the child still exists as python variables or is contained in some user-managed structure this can lead to inconsistencies.
- Parameters:
child (Scopee) – the child instance
frame (frame, optional) – a frame created with the inspect module. The default is None.
- property variables#
A container with all the
Variable
andStaticVariable
instances inchildren
. The container behaves like a dictionary.