at.lattice.variables#
Definition of Variable objects used in matching and
response matrices.
See Example notebooks for examples of matching and response matrices.
Each Variable has a scalar value.
Class hierarchy
VariableBase(name, bounds, delta)
ElementVariable(elements, attrname, index, …)RefptsVariable(refpts, attrname, index, …)CustomVariable(setfun, getfun, …)
VariableBase methods
VariableBase provides the following methods:
VariableBase properties
VariableBase provides the following properties:
The VariableBase abstract class may be used as a base class to define
custom variables (see examples). Typically, this consist in overloading the abstract
methods _setfun and _getfun
Examples
Write a subclass of VariableBase which varies two drift lengths so
that their sum is constant:
class ElementShifter(at.VariableBase):
'''Varies the length of the elements identified by *ref1* and *ref2*
keeping the sum of their lengths equal to *total_length*.
If *total_length* is None, it is set to the initial total length
'''
def __init__(self, drift1, drift2, total_length=None, **kwargs):
# store the 2 variable elements
self.drift1 = drift1
self.drift2 = drift2
# store the initial total length
if total_length is None:
total_length = drift1.Length + drift2.Length
self.length = total_length
super().__init__(bounds=(0.0, total_length), **kwargs)
def _setfun(self, value, **kwargs):
self.drift1.Length = value
self.drift2.Length = self.length - value
def _getfun(self, **kwargs):
return self.drift1.Length
And create a variable varying the length of drifts DR_01 and DR_01 and keeping their sum constant:
drift1 = hmba_lattice["DR_01"]
drift2 = hmba_lattice["DR_02"]
var2 = ElementShifter(drift1, drift2, name="DR_01")
Classes
|
A Variable controlling an attribute of an object. |
|
A Variable with user-defined get and set functions. |
|
A Variable controlling an item of a dictionary or a sequence. |
|
A Variable abstract base class. |
|
Container for Variable objects. |
subclass of |
|
|
Generalised attribute and item lookup. |
- class AttributeVariable(obj, attrname, index=None, **kwargs)[source]#
Bases:
VariableBaseA Variable controlling an attribute of an object.
- Parameters:
- Keyword Arguments:
name – Name of the Variable. If empty, a unique name is generated.
bounds – Lower and upper bounds of the variable value
delta – Initial variation step
history_length – Maximum length of the history buffer.
Nonemeans infinite.
Example
>>> ring = at.Lattice.load("hmba.mat") >>> v3 = at.AttributeVariable(ring, "energy") >>> v3.value 6000000000.0
v3 points to the “energy” attribute of ring
- class CustomVariable(setfun, getfun, *args, name='', bounds=None, delta=1.0, history_length=None, **kwargs)[source]#
Bases:
VariableBaseA Variable with user-defined get and set functions.
This is a convenience function allowing user-defined get and set functions. But subclassing
Variableshould always be preferred for clarity and efficiency.- Parameters:
getfun (Callable[..., Number]) – Function for getting the variable value. Called as
getfun(*args, **kwargs) -> Number. args are the positional arguments given to the constructor, kwargs are the keyword arguments given to the constructor augmented with the keywords given to theget()function.setfun (Callable[..., None]) – Function for setting the variable value. Called as
setfun(value: Number, *args, **kwargs): None. args are the positional arguments given to the constructor, kwargs are the keyword arguments given to the constructor augmented with the keywords given to theset()function.name (str) – Name of the Variable. If empty, a unique name is generated.
bounds (tuple[Number, Number] | None) – Lower and upper bounds of the variable value
*args – Variable argument list transmitted to both the getfun and setfun functions. Such arguments can always be avoided by using
partial()or callable class objects.
- Keyword Arguments:
**kwargs – Keyword arguments transmitted to both the getfun and setfun functions. Such arguments can always be avoided by using
partial()or callable class objects.
- class ItemVariable(obj, key, *args, **kwargs)[source]#
Bases:
VariableBaseA Variable controlling an item of a dictionary or a sequence.
- Parameters:
obj (MutableSequence | MutableMapping) – Mapping or Sequence containing the variable value,
key – Index or attribute name of the variable. A
strargument is interpreted as a dictionary key. Attribute names must be decorated withattr_(attrname)to distinguish them from directory keys.*args – additional sequence of indices or attribute names allowing to extract elements deeper in the object structure.
- Keyword Arguments:
name – Name of the Variable. If empty, a unique name is generated.
bounds – Lower and upper bounds of the variable value
delta – Initial variation step
history_length – Maximum length of the history buffer.
Nonemeans infinite.
Example
>>> dct = {"a": 42.0, "b": [0.0, 1.0, 2.0, 3.0]} >>> v1 = at.ItemVariable(dct, "a") >>> v1.value 42.0
v1 points to
dct["a"]>>> v2 = at.ItemVariable(dct, "b", 1) >>> v2.value 1.0
v2 points to
dct["b"][1]
- class VariableBase(*args, name='', bounds=None, delta=1.0, history_length=None, **kwargs)[source]#
Bases:
ABCA Variable abstract base class.
Derived classes must implement the
_getfun()and_setfun()methods- Parameters:
*args – Positional arguments passed to the _setfun and _getfun methods
name (str) – Name of the Variable. If omitted or blank, a unique name is generated.
bounds (tuple[Number | None, Number | None] | None) – Lower and upper bounds of the variable value
history_length (int | None) – Maximum length of the history buffer.
Nonemeans infinite.
- Keyword Arguments:
**kwargs – Keyword arguments passed to the _setfun and _getfun methods
- check_bounds(value)[source]#
Check that a value is within the variable bounds.
- Raises:
ValueError – If the value is not within bounds
- get(*, initial=False, check_bounds=False, **getkw)[source]#
Get the actual variable value.
- Parameters:
- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.**getkw – Other keyword arguments to be passed to the getfun function. They augment the keyword arguments given in the constructor.
- Returns:
value – Value of the variable
- reset(**setkw)[source]#
Reset to the initial value and clear the history buffer.
- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.**setkw – Other keyword arguments to be passed to the setfun function. They augment the keyword arguments given in the constructor.
- Raises:
IndexError – If no initial value has been set yet
- restore(**setkw)[source]#
Context manager that saves and restore a variable.
The value of the
Variableis initially saved, and then restored when exiting the context.- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.**setkw – Other keyword arguments to be passed to the setfun function. They augment the keyword arguments given in the constructor.
Example
>>> var = AttributeVariable(ring, "energy") >>> with var.restore(): ... do_something(var)
- set(value, **setkw)[source]#
Set the variable value.
- Parameters:
value (int | float) – New value to be applied on the variable
- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.**setkw – Other keyword arguments to be passed to the setfun function. They augment the keyword arguments given in the constructor.
- set_previous(**setkw)[source]#
Reset to the value before the last one.
- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.**setkw – Other keyword arguments to be passed to the setfun function. They augment the keyword arguments given in the constructor.
- Raises:
IndexError – If there are fewer than 2 values in the history
- status()[source]#
Return a string describing the current status of the variable.
- Returns:
status – Variable description
- step_down(**setkw)[source]#
Set to initial_value - delta.
- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.**setkw – Other keyword arguments to be passed to the setfun function. They augment the keyword arguments given in the constructor.
- step_up(**setkw)[source]#
Set to initial_value + delta.
- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.**setkw – Other keyword arguments to be passed to the setfun function. They augment the keyword arguments given in the constructor.
- DEFAULT_DELTA = 1.0#
- property initial_value: int | float#
Initial value of the variable.
- Raises:
IndexError – If no initial value has been set yet
- property last_value: int | float#
Last value of the variable.
- Raises:
IndexError – If no value has been set yet
- property previous_value: int | float#
Value before the last one.
- Raises:
IndexError – If there are fewer than 2 values in the history
- class VariableList(iterable=(), /)[source]#
Bases:
listContainer for Variable objects.
VariableListsupports alllistmethods, like appending, insertion or concatenation with the “+” operator.- get(ring=None, **kwargs)[source]#
Get the current values of Variables.
- Parameters:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.- Keyword Arguments:
- Returns:
values – 1D array of values of all variables
- reset(ring=None)[source]#
Reset to all variables their initial value and clear their history buffer.
- Parameters:
ring – Depending on the variable type, a
Latticeargument may be necessary to reset the variable.
- restore(**kwargs)[source]#
Context manager that saves and restore the variable list.
The value of the
VariableListis initially saved, and then restored when exiting the context.- Keyword Arguments:
ring – Depending on the variable type, a
Latticeargument may be necessary to set the variable.
- class attr_[source]#
Bases:
strsubclass of
strused to differentiate directory keys and attribute names.
- class membergetter(*args)[source]#
Bases:
objectGeneralised attribute and item lookup.
Callable object fetching attributes or items from its operand object. This generalises
attrgetter()anditemgetter()and allows to extract elements deep in the object structure. For example:With
f1 = membergetter("key1", [2]), thenf1(obj)returnsobj["key1"][2],With
f2 = membergetter("key2", attr_("attr1"), [key3]), thenf2(obj)returnsobj["key2"].attr1["key3"].
- Parameters:
*args –
Sequence of dictionary keys, sequence indices or attribute names. A
strargument is interpreted as a dictionary key. Attribute names must be decorated withattr_(attrname)to distinguish them from directory keys.f1 = SetGet("key1")(obj)returnsobj["key1"],f2 = SetGet(attr("attr1"))(obj)returnsobj.attr1
Example
>>> dct = {"a": 42.0, "b": [0.0, 1.0, 2.0, 3.0]} >>> f = membergetter("b", 1) >>> f(dct) 1.0
- accessor(obj)[source]#
Return an accessor object.
The returned object has set and get methods acting on the selected item of the object obj.
Example
>>> dct = {"a": 42.0, "b": [0.0, 1.0, 2.0, 3.0]} >>> v2 = membergetter("b", 1) >>> accessor = v2.accessor(dct) >>> accessor.get() 1.0 >>> accessor.set(42.0) >>> dct {'a': 42.0, 'b': [0.0, 42.0, 2.0, 3.0]}