at.latticetools.observables#

Definition of Observable objects used in matching and response matrices.

Observables are ways to monitor various lattice parameters and use them in matching and correction procedures.

Class hierarchy#

Observable(evalfun, name, target, weight, bounds, …)

RingObservable(fun, …)

GlobalOpticsObservable()(attrname, plane, name, …)

EmittanceObservable(attrname, plane, name, …)

ElementObservable(fun, …)

OrbitObservable(refpts, axis, name, …)

TrajectoryObservable(refpts, axis, name, …)

MatrixObservable(refpts, axis, name, …)

LocalOpticsObservable(refpts, attrname, axis, name, …)

LatticeObservable(refpts, attrname, index, name, …)

GeometryObservable(refpts, attrname, name, …)

RDTObservable(refpts, RDTname, name, …)

Observables are usually not evaluated directly, but through a container which performs the required optics computation and feeds each Observable with its specific data. After evaluation, each Observable provides the following properties:

Functions

GlobalOpticsObservable(param[, plane, name, ...])

Observe a global optics parameter.

Classes

Observable(fun, *args[, name, target, ...])

Base class for Observables.

RingObservable(fun[, name])

Observe any user-defined property of a ring.

EmittanceObservable(param[, plane, name])

Observe emittance-related parameters.

ElementObservable(fun, refpts[, name, ...])

Base class for Observables linked to a position in the lattice.

OrbitObservable(refpts[, axis, name])

Observe the closed orbit coordinates at selected locations.

GeometryObservable(refpts, param[, name])

Observe the geometrical parameters of the reference trajectory.

LocalOpticsObservable(refpts, param[, ...])

Observe a local optics parameter at selected locations.

LatticeObservable(refpts, attrname[, index, ...])

Observe an attribute of selected lattice elements.

MatrixObservable(refpts[, axis, name])

Observe the closed orbit at selected locations.

TrajectoryObservable(refpts[, axis, name])

Observe trajectory coordinates at selected locations.

Need(*values)

Defines the computation requirements for an Observable.

class ElementObservable(fun, refpts, name=None, statfun=None, postfun=None, **kwargs)[source]#

Bases: Observable

Base class for Observables linked to a position in the lattice.

Parameters:
  • fun (Callable) – evaluation function

  • refpts (Refpts) – Observation points. See “Selecting elements in a lattice

  • name (str) – Observable name. If None, an explicit name will be generated

  • postfun (Callable | str | None) – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • statfun (Callable | str | None) – Statistics post-processing function. it can be a numpy function or a function name in {“mean”, “std”, “var”, “min”, “max”}. Example: statfun=numpy.mean.

Keyword Arguments:
  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

Shape of the value

A nrefs dimension, with nrefs the number of reference points, is prepended to the shape of the output of fun, even if nrefs == 1. The target, weight and bounds inputs must be broadcastable to the shape of value.

check()[source]#

Check if evaluation is done

Returns:

okTrue if evaluation is done, False otherwise.

Raises:

AtError – if the value is doubtful: evaluation failed, empty value…

class EmittanceObservable(param, plane=None, name=None, **kwargs)[source]#

Bases: Observable

Observe emittance-related parameters.

Process the output of envelope_parameters().

Parameters:
  • param (str) – Parameter name (see envelope_parameters()) or user-defined evaluation function

  • plane (AxisDef) – One out of {0, ‘x’, ‘h’, ‘H’} for horizontal plane, one out of {1, ‘y’, ‘v’, ‘V’} for vertival plane or one out of {2, ‘z’, ‘l’, ‘L’} for longitudinal plane

  • name (str) – Observable name. If None, an explicit name will be generated.

Keyword Arguments:
  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • statfun – Statistics post-processing function. it can be a numpy function or a function name in {“mean”, “std”, “var”, “min”, “max”}. Example: statfun=numpy.mean.

  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

User-defined evaluation function

It is called as:

value = fun(paramdata)

paramdata if the RingParameters object returned by envelope_parameters().

value is the value of the Observable.

Example

>>> EmittanceObservable("emittances", plane="h")

Observe the horizontal emittance

class GeometryObservable(refpts, param, name=None, **kwargs)[source]#

Bases: ElementObservable

Observe the geometrical parameters of the reference trajectory.

Process the geomdata output of get_geometry().

Parameters:
  • refpts (Refpts) – Observation points. See “Selecting elements in a lattice

  • param (str) – Geometry parameter name: one in {‘x’, ‘y’, ‘angle’}

  • name (str) – Observable name. If None, an explicit name will be generated.

Keyword Arguments:
  • statfun – Post-processing function called on the value of the observable. Example: statfun=numpy.mean

  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

The target, weight and bounds inputs must be broadcastable to the shape of value.

Example

>>> obs = GeometryObservable(at.Monitor, param="x")

Observe x coordinate of monitors

class LatticeObservable(refpts, attrname, index=None, name=None, **kwargs)[source]#

Bases: ElementObservable

Observe an attribute of selected lattice elements.

Parameters:
  • refpts (Refpts) – Elements to be observed See “Selecting elements in a lattice

  • attrname (str) – Attribute name

  • index (int | None) – Index in the attribute array. If None, the whole array is specified

  • name (str) – Observable name. If None, an explicit name will be generated.

Keyword Arguments:
  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • statfun – Statistics post-processing function. it can be a numpy function or a function name in {“mean”, “std”, “var”, “min”, “max”}. Example: statfun=numpy.mean.

Example

>>> obs = LatticeObservable(
...     at.Sextupole, "KickAngle", index=0, statfun=np.sum
... )

Observe the sum of horizontal kicks in Sextupoles

class LocalOpticsObservable(refpts, param, plane=Ellipsis, name=None, all_points=False, **kwargs)[source]#

Bases: ElementObservable

Observe a local optics parameter at selected locations.

Process the local output of get_optics().

Parameters:
  • refpts (Refpts) – Observation points. See “Selecting elements in a lattice

  • param (str | Callable) – Optics parameter name or user-defined evaluation function

  • plane (AxisDef) – Index in the parameter array, If Ellipsis, the whole array is specified

  • name (str) – Observable name. If None, an explicit name will be generated

  • all_points (bool) – Compute the local optics at all elements. This avoids discontinuities in phase advances. This is automatically set for the ‘mu’ parameter, but may need to be specified for user-defined evaluation functions using the phase advance.

Keyword Arguments:
  • summary – Set to True if the user-defined evaluation function returns a single item (see below)

  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • statfun – Statistics post-processing function. it can be a numpy function or a function name in {“mean”, “std”, “var”, “min”, “max”}. Example: statfun=numpy.mean.

  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

Shape of the value

If the requested attribute has shape shp, then value has shape (nrefs,) + shp with nrefs number of reference points: a nrefs dimension is prepended to the shape of the attribute, even if nrefs == 1. The target, weight and bounds inputs must be broadcastable to the shape of value. For instance, a target with shape shp will automatically broadcast and apply to all reference points.

Optics parameter name

In addition to get_optics() parameter names, LocalOpticsObservable adds 3 parameters: muf, mu2pi and mu2pif:

s_pos

longitudinal position [m]

M

(6, 6) transfer matrix M from the beginning of ring to the entrance of the element

closed_orbit

(6,) closed orbit vector

dispersion

(4,) dispersion vector

A

(6, 6) A-matrix

R

(3, 6, 6) R-matrices

beta

\(\left[ \beta_x,\beta_y \right]\) vector

alpha

\(\left[ \alpha_x,\alpha_y \right]\) vector

mu

\(\left[ \mu_x,\mu_y \right]\), betatron phase

mu2pi

\(\left[ \mu_x,\mu_y \right]/2\pi\), reduced betatron phase

muf

\(\left[ \mu_x,\mu_y \right]\), betatron phase (modulo \(2\pi\))

mu2pif

\(\mathrm{frac}(\left[ \mu_x,\mu_y \right]/2\pi)\), fractional part of the reduced betatron phase

W

\(\left[ W_x,W_y \right]\) only if get_w is True: chromatic amplitude function

Wp

\(\left[ Wp_x,Wp_y \right]\) only if get_w is True: chromatic phase function

dalpha

(2,) alpha derivative vector (\(\Delta \alpha/ \delta_p\))

dbeta

(2,) beta derivative vector (\(\Delta \beta/ \delta_p\))

dmu

(2,) mu derivative vector (\(\Delta \mu/ \delta_p\))

ddispersion

(4,) dispersion derivative vector (\(\Delta D/ \delta_p\))

dR

(3, 6, 6) R derivative vector (\(\Delta R/ \delta_p\))

User-defined evaluation function

The observable value is computed as:

value = fun(elemdata)[plane]

  • elemdata is the output of get_optics(), evaluated at the refpts of the observable,

  • value is the value of the Observable and must have one line per refpoint. Alternatively, it may be a single line, but then the summary keyword must be set to True.

  • the plane keyword then selects the desired values in the function output.

Examples

>>> obs = LocalOpticsObservable(at.Monitor, "beta")

Observe the beta in both planes at all Monitor locations

>>> obs = LocalOpticsObservable(
...     at.Quadrupole, "beta", plane="y", statfun=np.max
... )

Observe the maximum vertical beta in Quadrupoles

>>> def phase_advance(elemdata):
...     mu = elemdata.mu
...     return mu[-1] - mu[0]
>>>
>>> allobs.append(
...     LocalOpticsObservable(
...         [33, 101], phase_advance, plane="y", all_points=True, summary=True
...     )
... )

The user-defined evaluation function computes the phase-advance between the 1st and last given reference points, here the elements 33 and 101 of the lattice

class MatrixObservable(refpts, axis=Ellipsis, name=None, **kwargs)[source]#

Bases: ElementObservable

Observe the closed orbit at selected locations.

Processs the result of calling find_m44() or find_m44() depending upon is_6d().

Parameters:
  • refpts (Refpts) – Observation points. See “Selecting elements in a lattice

  • axis (AxisDef) – Index in the transfer matrix, If Ellipsis, the whole matrix is specified

  • name (str) – Observable name. If None, an explicit name will be generated.

Keyword Arguments:
  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • statfun – Statistics post-processing function. it can be a numpy function or a function name in {“mean”, “std”, “var”, “min”, “max”}. Example: statfun=numpy.mean.

  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

The target, weight and bounds inputs must be broadcastable to the shape of value.

Example

>>> obs = MatrixObservable(at.Monitor, axis=("x", "px"))

Observe the transfer matrix from origin to monitor locations and extract T[0,1]

class Need(*values)[source]#

Bases: Enum

Defines the computation requirements for an Observable.

ALL_POINTS = 8#

Associated with LOCALOPTICS, require local optics computation at all points: slower but avoids jumps in phase advance

CHROMATICITY = 9#

Associated with LOCALOPTICS, require the get_chrom keyword

EMITTANCE = 7#

Specify envelope_parameters() computation and provide its params output to the evaluation function

GEOMETRY = 11#

Specify get_geometry() computation and provide its output to the evaluation function

GLOBALOPTICS = 4#

Specify get_optics() computation and provide its ringdata output to the evaluation function

LOCALOPTICS = 5#

Specify get_optics() computation and provide its elemdata output to the evaluation function

MATRIX = 3#

Specify find_m44() or find_m44() computation and provide its m44 or m66 output to the evaluation function

ORBIT = 2#

Specify find_orbit() computation and provide its orbit output to the evaluation function

RDT = 12#

Specify RDT computation and provide its output to the evaluation function

RDT_2ND_ORDER = 13#

request 2nd order calculation

Type:

Associated with RDT

RING = 1#

Provides the ring data to the evaluation function

TRAJECTORY = 6#

Specify lattice_pass() computation and provide its r_out to the evaluation function

W_FUNCTIONS = 10#

Associated with LOCALOPTICS, require the get_w keyword

class Observable(fun, *args, name=None, target=None, weight=1.0, bounds=(0.0, 0.0), needs=None, postfun=None, **kwargs)[source]#

Bases: object

Base class for Observables. Can be used for user-defined observables.

Parameters:
  • name (str) – Observable name. If None, an explicit name will be generated

  • fun (Callable) – evaluation function

  • *args – Arguments provided to the evaluation function

  • target (Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None) – Target value for a constraint. If None (default), the residual will always be zero.

  • weight (npt.ArrayLike) – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

  • postfun (Callable | str | None) – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • needs (Set[Need]) – Set of requirements. This selects the data provided to the evaluation function. needs items are members of the Need enumeration

Keyword Arguments:

**kwargs – Keyword arguments provided to the evaluation function

The target, weight and bounds inputs must be broadcastable to the shape of value.

User-defined evaluation function

The general form is:

value = fun(*data, *args, **kwargs)

  • data depends on the needs argument, and by default is empty. If several needed values are specified, their order is: ring, orbit, m44/m66, ringdata, elemdata, r_out, params, geomdata,

  • args are the positional arguments provided to the observable constructor,

  • kwargs are the keyword arguments provided to the observable constructor,

  • value is the value of the observable.

For user-defined evaluation functions using linear optics data or emittance data, it is recommended to use LocalOpticsObservable, GlobalOpticsObservable or EmittanceObservable which provide the corresponding data argument.

static check_value(value)[source]#
check()[source]#

Check if evaluation is done

Returns:

okTrue if evaluation is done, False otherwise.

Raises:

AtError – if the value is doubtful: evaluation failed, empty value…

evaluate(*data, initial=False)[source]#

Compute and store the value of the observable.

The direct evaluation of a single Observable is normally not used. This method is called by the ObservableList container which provides the data arguments.

Parameters:
  • *data – Raw data, provided by ObservableList and sent to the evaluation function

  • initial (bool) – It None, store the result as the initial value

Returns:

value – The value of the observable or the error in evaluation

property deviation: ndarray[tuple[int, ...], dtype[float]]#

Deviation from target value, computed as deviation = value-target.

If target is None, the deviation is zero for any value.

fun: Callable#

Evaluation function

name: str#

Observable name

needs: Set[Need]#

Set of requirements

property residual: ndarray[tuple[int, ...], dtype[float]]#

residual, computed as residual = ((value-target)/weight)**2.

If target is None, the residual is zero for any value.

target: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None#

Target value

property value: ndarray[tuple[int, ...], dtype[float]]#

Value of the observable.

property weight: ndarray[tuple[int, ...], dtype[float]]#

Observable weight.

property weighted_deviation: ndarray[tuple[int, ...], dtype[float]]#

weighted_deviation = (value-target)/weight.

If target is None, the weighted deviation is zero for any value.

property weighted_value: ndarray[tuple[int, ...], dtype[float]]#

Weighted value of the Observable, computed as weighted_value = value/weight.

class OrbitObservable(refpts, axis=None, name=None, **kwargs)[source]#

Bases: ElementObservable

Observe the closed orbit coordinates at selected locations.

Process the orbit output of find_orbit().

Parameters:
  • refpts (Refpts) – Observation points. See “Selecting elements in a lattice

  • axis (AxisDef) – Index in the orbit vector, If None, the whole vector is specified

  • name (str) – Observable name. If None, an explicit name will be generated.

Keyword Arguments:
  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • statfun – Statistics post-processing function. it can be a numpy function or a function name in {“mean”, “std”, “var”, “min”, “max”}. Example: statfun=numpy.mean.

  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

Shape of the value

If axis is None (whole orbit vector), then value has shape (nrefs, 6) with nrefs number of reference points: a nrefs dimension is prepended to the shape of the orbit vector, even if nrefs == 1. A single coordinate has shape (nrefs,). The target, weight and bounds inputs must be broadcastable to the shape of value.

Example

>>> obs = OrbitObservable(at.Monitor, axis=0)

Observe the horizontal closed orbit at monitor locations

class RingObservable(fun, name=None, **kwargs)[source]#

Bases: Observable

Observe any user-defined property of a ring.

Parameters:
Keyword Arguments:
  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

The target, weight and bounds inputs must be broadcastable to the shape of value.

User-defined evaluation function

It is called as:

value = fun(ring)

  • ring is the lattice description,

  • value is the value of the Observable.

Examples

>>> def circumference(ring):
...     return ring.get_s_pos(len(ring))[0]
>>> obs = RingObservable(circumference)

Defines an Observable for the ring circumference.

>>> def momentum_compaction(ring):
...     return ring.get_mcf()
>>> obs = RingObservable(momentum_compaction)

Defines an Observable for the momentum compaction factor.

class TrajectoryObservable(refpts, axis=Ellipsis, name=None, **kwargs)[source]#

Bases: ElementObservable

Observe trajectory coordinates at selected locations.

Process the r_out output if Lattice.track()

Parameters:
  • refpts (Refpts) – Observation points. See “Selecting elements in a lattice

  • axis (AxisDef) – Index in the orbit array, If Ellipsis, the whole array is specified

  • name (str) – Observable name. If None, an explicit name will be generated.

Keyword Arguments:
  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

  • statfun – Statistics post-processing function. it can be a numpy function or a function name in {“mean”, “std”, “var”, “min”, “max”}. Example: statfun=numpy.mean.

  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

The target, weight and bounds inputs must be broadcastable to the shape of value.

GlobalOpticsObservable(param, plane=Ellipsis, name=None, use_integer=False, **kwargs)[source]#

Observe a global optics parameter.

Process the ringdata output of get_optics().

Parameters:
  • param (str) – Optics parameter name (see get_optics()) or user-defined evaluation function

  • plane (str | int | slice | None | EllipsisType | Tuple[str | int | slice | None | EllipsisType, str | int | slice | None | EllipsisType]) – Index in the parameter array, If Ellipsis, the whole array is specified

  • name (str | None) – Observable name. If None, an explicit name will be generated

  • use_integer (bool) – For ‘tune’ parameter: derive the tune from the phase advance to avoid skipping integers. Slower than looking only at the fractional part

Keyword Arguments:
  • target – Target value for a constraint. If None (default), the residual will always be zero.

  • weight – Weight factor: the residual is ((value-target)/weight)**2

  • bounds – Tuple of lower and upper bounds. The parameter is constrained in the interval [target+low_bound target+up_bound]

  • postfun – Post-processing function. It can be any numpy ufunc or a function name in {“real”, “imag”, “abs”, “angle”, “log”, “exp”, “sqrt”}.

The target, weight and bounds inputs must be broadcastable to the shape of value.

User-defined evaluation function

It is called as:

value = fun(ring, ringdata)

  • ringdata is the output of get_optics(),

  • value is the value of the Observable.

Examples

>>> obs = GlobalOpticsObservable("tune", use_integer=True)

Observe the tune in both planes, including the integer part (slower)

>>> obs = GlobalOpticsObservable("chromaticity", plane="v")

Observe the vertical chromaticity