at.latticetools.response_matrix#

Definition of ResponseMatrix objects.

A ResponseMatrix object defines a general-purpose response matrix, based on a VariableList of attributes which will be independently varied, and an ObservableList of attributes which will be recorded for each variable step.

ResponseMatrix objects can be combined with the “+” operator to define combined responses. This concatenates the variables and the observables.

This module also defines two commonly used response matrices: OrbitResponseMatrix for circular machines and TrajectoryResponseMatrix for beam lines. Other matrices can be easily defined by providing the desired Observables and Variables to the ResponseMatrix base class.

Generic response matrix#

The ResponseMatrix class defines a general-purpose response matrix, based on a VariableList of quantities which will be independently varied, and an ObservableList of quantities which will be recorded for each step.

For instance let’s take the horizontal displacements of all quadrupoles as variables:

>>> variables = VariableList(
...     RefptsVariable(ik, "dx", name=f"dx_{ik}", delta=0.0001)
...     for ik in ring.get_uint32_index(at.Quadrupole)
... )

The variables are the horizontal displacement dx of all quadrupoles. The variable name is set to dx_nnnn where nnnn is the index of the quadrupole in the lattice. The step is set to 0.0001 m.

Let’s take the horizontal positions at all beam position monitors as observables:

>>> observables = at.ObservableList([at.OrbitObservable(at.Monitor, axis="x")])

This is a single observable named orbit[x] by default, with multiple values.

Instantiation#

>>> resp_dx = at.ResponseMatrix(ring, variables, observables)

At that point, the response matrix is empty.

Matrix Building#

The response matrix may be filled by several means:

  1. Direct assignment of an array to the response property. The shape of the array is checked.

  2. load() loads data from a file containing previously saved values or experimentally measured values,

  3. build_tracking() computes the matrix using tracking,

  4. For some specialized response matrices a build_analytical() method is available.

Matrix normalisation#

To be correctly inverted, the response matrix must be correctly normalised: the norms of its columns must be of the same order of magnitude, and similarly for the rows.

Normalisation is done by adjusting the weights \(w_v\) for the variables \(\mathbf{V}\) and \(w_o\) for the observables \(\mathbf{O}\). With \(\mathbf{R}\) the response matrix:

\[\mathbf{O} = \mathbf{R} . \mathbf{V}\]

The weighted response matrix \(\mathbf{R}_w\) is:

\[\frac{\mathbf{O}}{w_o} = \mathbf{R}_w . \frac{\mathbf{V}}{w_v}\]

The \(\mathbf{R}_w\) is dimensionless and should be normalised. This can be checked using:

  • check_norm() which prints the ratio of the maximum / minimum norms for variables and observables. These should be less than 10.

  • plot_norm()

Both natural and weighted response matrices can be retrieved with the response and weighted_response properties.

Matrix pseudo-inversion#

The solve() method computes the singular values of the weighted response matrix.

After solving, correction is available, for instance with

  • correction_matrix() which returns the correction matrix (pseudo-inverse of the response matrix),

  • get_correction() which returns a correction vector when given error values,

  • correct() which computes and optionally applies a correction for the provided Lattice.

Exclusion of variables and observables#

Variables may be added to a set of excluded values, and similarly for observables. Excluding an item does not change the response matrix. The values are excluded from the pseudo-inversion of the response, possibly reducing the number of singular values. After inversion the correction matrix is expanded to its original size by inserting zero lines and columns at the location of excluded items. This way:

  • error and correction vectors keep the same size independently of excluded values,

  • excluded error values are ignored,

  • excluded corrections are set to zero.

Variables can be added to the set of excluded variables using exclude_vars() and observables using exclude_obs().

After excluding items, the pseudo-inverse is discarded so one must recompute it again by calling solve().

The exclusion masks can be reset with reset_vars() and reset_obs().

Classes

ResponseMatrix(ring, variables, observables)

Base class for response matrices.

OrbitResponseMatrix(ring, plane[, bpmrefs, ...])

Orbit response matrix.

TrajectoryResponseMatrix(ring, plane[, ...])

Trajectory response matrix.

class OrbitResponseMatrix(ring, plane, bpmrefs=<class 'at.lattice.elements.Monitor'>, steerrefs=functools.partial(<function _chkattr>, 'KickAngle'), *, cavrefs=None, bpmweight=1.0, bpmtarget=0.0, steerdelta=0.0001, cavdelta=None, steersum=False, stsumweight=None)[source]#

Bases: ResponseMatrix

Orbit response matrix.

An OrbitResponseMatrix applies to a single plane, horizontal or vertical. A combined response matrix is obtained by adding horizontal and vertical matrices. However, the resulting matrix has the ResponseMatrix class, which implies that the OrbitResponseMatrix specific methods are not available.

Variables are a set of steerers and optionally the RF frequency. Steerer variables are named xnnnn or ynnnn where nnnn is the index in the lattice. The RF frequency variable is named RF frequency.

Observables are the closed orbit position at selected points, named orbit[x] for the horizontal plane or orbit[y] for the vertical plane, and optionally the sum of steerer angles named sum(h_kicks) or sum(v_kicks)

The variable elements must have the KickAngle attribute used for correction. It’s available for all magnets, though not present by default except in Corrector magnets. For other magnets, the attribute should be explicitly created.

By default, the observables are all the Monitor elements, and the variables are all the elements having a KickAngle attribute. This is equivalent to:

>>> resp_v = OrbitResponseMatrix(
...     ring, "v", bpmrefs=at.Monitor, steerrefs=at.checkattr("KickAngle")
... )
Parameters:
  • ring (Lattice) – Design lattice, used to compute the response.

  • plane (AxisDef) – One out of {0, ‘x’, ‘h’, ‘H’} for horizontal orbit, or one of {1, ‘y’, ‘v’, ‘V’} for vertical orbit.

  • bpmrefs (ndarray[tuple[int, ...], dtype[uint32]]) – Location of closed orbit observation points. See “Selecting elements in a lattice”. Default: all Monitor elements.

  • steerrefs (ndarray[tuple[int, ...], dtype[uint32]]) – Location of orbit steerers. Their KickAngle attribute is used and must be present in the selected elements. Default: All Elements having a KickAngle attribute.

  • cavrefs (Refpts) – Location of RF cavities. Their Frequency attribute is used. If None, no cavity is included in the response. Cavities must be active. Cavity variables are appended to the steerer variables.

  • bpmweight (float | Sequence[float]) – Weight of position readings. Must be broadcastable to the number of BPMs.

  • bpmtarget (float | Sequence[float]) – Target orbit position. Must be broadcastable to the number of observation points.

  • cavdelta (float | None) – Step on RF frequency for matrix computation [Hz]. This is also the cavity weight. Default: automatically computed.

  • steerdelta (float | Sequence[float]) – Step on steerers for matrix computation [rad]. This is also the steerer weight. Must be broadcastable to the number of steerers.

  • steersum (bool) – If True, the sum of steerers is appended to the Observables.

  • stsumweight (float | None) – Weight on steerer summation. Default: automatically computed.

Variables:

By default, the weights of cavities and steerers summation are set to give a factor 2 more efficiency than steerers and BPMs

build_analytical(**kwargs)[source]#

Build analytically the response matrix.

Keyword Arguments:
  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation from the nominal RF frequency. Defaults to None

Returns:

response – Response matrix

References

build_tracking(use_mp=False, pool_size=None, start_method=None, **kwargs)#

Build the response matrix.

Parameters:
  • use_mp (bool) – Use multiprocessing

  • pool_size (int | None) – number of processes. If None, min(len(self.variables, nproc) is used

  • start_method (str | None) – python multiprocessing start method. None uses the python default that is considered safe. Available values: 'fork', 'spawn', 'forkserver'. Default for linux is 'fork', default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation, however it is considered unsafe.

Keyword Arguments:
  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation from the nominal RF frequency. Defaults to None

  • r_in (Orbit) – Initial trajectory, used for TrajectoryResponseMatrix, Default: zeros(6)

Returns:

response – Response matrix

check_norm()#

Display the norm of the rows and columns of the weighted response matrix.

Adjusting the variables and observable weights to equalize the norms of rows and columns is important.

Returns:
  • obs_norms – Norms of observables (rows)

  • var_norms – Norms of Variables (columns)

correct(ring, nvals=None, niter=1, apply=False)#

Compute and optionally apply the correction.

Parameters:
  • ring (Lattice) – Lattice description. The response matrix observables will be evaluated for ring and the deviation from target will be corrected

  • apply (bool) – If True, apply the correction to ring

  • niter (int) – Number of iterations. For more than one iteration, apply must be True

  • nvals (int) – Desired number of singular values. If None, use all singular values. nvals may be a scalar or an iterable with niter values.

Returns:

correction – Vector of correction values

correction_matrix(nvals=None)#

Return the correction matrix (pseudo-inverse of the response matrix).

Parameters:

nvals (int | None) – Desired number of singular values. If None, use all singular values

Returns:

cormat – Correction matrix

exclude_obs(*, obsid=0, refpts=None)[source]#

Add an observable item to the set of excluded values.

After excluding observation points, the matrix must be inverted again using solve().

Parameters:
Raises:

Example

>>> resp = OrbitResponseMatrix(ring, "h")
>>> resp.exclude_obs("BPM_02")

Create an horizontal OrbitResponseMatrix from Corrector elements to Monitor elements, and exclude all monitors with name “BPM_02”

exclude_vars(*varid, refpts=None)[source]#

Add correctors to the set of excluded variables.

Parameters:

After excluding correctors, the matrix must be inverted again using solve().

Examples

>>> resp.exclude_vars(0, "x0097", -1)

Exclude the 1st variable, the variable named “x0097” and the last variable.

>>> resp.exclude_vars(refpts="SD1E")

Exclude all variables associated with the element named “SD1E”.

get_correction(observed, nvals=None)#

Compute the correction of the given observation.

Parameters:
  • observed (ndarray[tuple[int, ...], dtype[float64]]) – Vector of observed deviations,

  • nvals (int | None) – Desired number of singular values. If None, use all singular values

Returns:

corr – Correction vector

get_target(*, obsid=0)#

Return the target of the specified observable

Parameters:

obsid (int | str) – Observable name or index in the observable list.

Returns:

target – observable target

load(file)#

Load a response matrix saved in the NumPy .npy format.

Parameters:

file – file-like object, string, or pathlib.Path: the file to read. A file object must always be opened in binary mode.

normalise(cav_ampl=2.0, stsum_ampl=2.0)[source]#

Normalise the response matrix

Adjust the RF cavity delta and/or the weight of steerer summation so that the weighted response matrix is normalised.

Parameters:
  • cav_ampl (float | None) – Desired ratio between the cavity response and the average of steerer responses. If None, do not normalise.

  • stsum_ampl (float | None) – Desired inverse ratio between the weight of the steerer summation and the average of Monitor responses. If None, do not normalise.

By default, the normalisation gives to the RF frequency and steerer summation a factor 2 more efficiency than steerers and BPMs

plot_norm(ax=None)#

Plot the norm of the lines and columns of the weighted response matrix

For a stable solution, the norms should have the same order of magnitude. If not, the weights of observables and variables should be adjusted.

Parameters:
plot_obs_analysis(lattice, ax=None, logscale=True)#

Plot the decomposition of an error vector on the basis of singular vectors

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • lattice (Lattice) – Lattice description. The response matrix observables will be evaluated for this Lattice and the deviation from target will be decomposed on the basis of singular vectors,

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

plot_singular_values(ax=None, logscale=True)#

Plot the singular values of a response matrix

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

plot_var_analysis(lattice, ax=None, logscale=False)#

Plot the decomposition of a correction vector on the basis of singular vectors

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • lattice (Lattice) – Lattice description. The variables will be evaluated for this Lattice and will be decomposed on the basis of singular vectors,

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

reset_obs()#

Reset the observable exclusion mask: enable all observables

reset_vars()#

Reset the variable exclusion mask: enable all variables

save(file)#

Save a response matrix in the NumPy .npy format.

Parameters:

file – file-like object, string, or pathlib.Path: File to which the data is saved. If file is a file-object, it must be opened in binary mode. If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one.

set_target(target, *, obsid=0)#

Set the target of the specified observable

Parameters:
solve()#

Compute the singular values of the response matrix.

bpmrefs: ndarray[tuple[int, ...], dtype[uint32]]#

location of position monitors

property bpmweight: ndarray[tuple[int, ...], dtype[float64]]#

Weight of position readings.

property cavdelta: ndarray[tuple[int, ...], dtype[float64]]#

Step and weight of RF frequency deviation.

property excluded_obs: dict#

Directory of excluded observables.

The dictionary keys are the observable names, the values are the integer indices of excluded items (empty list if no exclusion).

property excluded_vars: list#

List of excluded variables

observables: ObservableList#

List of matrix Observables

property obsweights: ndarray#

Observable weights.

property response: ndarray[tuple[int, ...], dtype[float64]]#

Response matrix.

ring: Lattice#
property shape: tuple[int, int]#

Shape of the response matrix.

singular_values: ndarray[tuple[int, ...], dtype[float64]] | None = None#

Singular values of the response matrix

property steerdelta: ndarray[tuple[int, ...], dtype[float64]]#

Step and weight of steerers.

steerrefs: ndarray[tuple[int, ...], dtype[uint32]]#

location of steerers

property stsumweight: ndarray[tuple[int, ...], dtype[float64]]#

Weight of steerer summation.

variables: VariableList#

List of matrix Variables

property varweights: ndarray#

Variable weights.

property weighted_response: ndarray[tuple[int, ...], dtype[float64]]#

Weighted response matrix.

class ResponseMatrix(ring, variables, observables)[source]#

Bases: _SvdSolver

Base class for response matrices.

It is defined by any arbitrary set of VariableBases and Observables

Addition is defined on ResponseMatrix objects as the addition of their VariableBases and Observables to produce combined responses.

Parameters:
build_analytical()[source]#

Build the response matrix.

build_tracking(use_mp=False, pool_size=None, start_method=None, **kwargs)[source]#

Build the response matrix.

Parameters:
  • use_mp (bool) – Use multiprocessing

  • pool_size (int | None) – number of processes. If None, min(len(self.variables, nproc) is used

  • start_method (str | None) – python multiprocessing start method. None uses the python default that is considered safe. Available values: 'fork', 'spawn', 'forkserver'. Default for linux is 'fork', default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation, however it is considered unsafe.

Keyword Arguments:
  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation from the nominal RF frequency. Defaults to None

  • r_in (Orbit) – Initial trajectory, used for TrajectoryResponseMatrix, Default: zeros(6)

Returns:

response – Response matrix

check_norm()#

Display the norm of the rows and columns of the weighted response matrix.

Adjusting the variables and observable weights to equalize the norms of rows and columns is important.

Returns:
  • obs_norms – Norms of observables (rows)

  • var_norms – Norms of Variables (columns)

correct(ring, nvals=None, niter=1, apply=False)[source]#

Compute and optionally apply the correction.

Parameters:
  • ring (Lattice) – Lattice description. The response matrix observables will be evaluated for ring and the deviation from target will be corrected

  • apply (bool) – If True, apply the correction to ring

  • niter (int) – Number of iterations. For more than one iteration, apply must be True

  • nvals (int) – Desired number of singular values. If None, use all singular values. nvals may be a scalar or an iterable with niter values.

Returns:

correction – Vector of correction values

correction_matrix(nvals=None)#

Return the correction matrix (pseudo-inverse of the response matrix).

Parameters:

nvals (int | None) – Desired number of singular values. If None, use all singular values

Returns:

cormat – Correction matrix

exclude_obs(*, obsid=0, refpts=None)[source]#

Add an observable item to the set of excluded values

After excluding observation points, the matrix must be inverted again using solve().

Parameters:
Raises:

Example

>>> resp = OrbitResponseMatrix(ring, "h", Monitor, Corrector)
>>> resp.exclude_obs(obsid="x_orbit", refpts="BPM_02")

Create an horizontal OrbitResponseMatrix from Corrector elements to Monitor elements, and exclude the monitor with name “BPM_02”

exclude_vars(*varid)[source]#

Add variables to the set of excluded variables.

Parameters:

*varid (int | str) – Variable names or variable indices in the variable list

After excluding variables, the matrix must be inverted again using solve().

Examples

>>> resp.exclude_vars(0, "var1", -1)

Exclude the 1st variable, the variable named “var1” and the last variable.

get_correction(observed, nvals=None)#

Compute the correction of the given observation.

Parameters:
  • observed (ndarray[tuple[int, ...], dtype[float64]]) – Vector of observed deviations,

  • nvals (int | None) – Desired number of singular values. If None, use all singular values

Returns:

corr – Correction vector

get_target(*, obsid=0)[source]#

Return the target of the specified observable

Parameters:

obsid (int | str) – Observable name or index in the observable list.

Returns:

target – observable target

load(file)#

Load a response matrix saved in the NumPy .npy format.

Parameters:

file – file-like object, string, or pathlib.Path: the file to read. A file object must always be opened in binary mode.

plot_norm(ax=None)#

Plot the norm of the lines and columns of the weighted response matrix

For a stable solution, the norms should have the same order of magnitude. If not, the weights of observables and variables should be adjusted.

Parameters:
plot_obs_analysis(lattice, ax=None, logscale=True)#

Plot the decomposition of an error vector on the basis of singular vectors

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • lattice (Lattice) – Lattice description. The response matrix observables will be evaluated for this Lattice and the deviation from target will be decomposed on the basis of singular vectors,

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

plot_singular_values(ax=None, logscale=True)#

Plot the singular values of a response matrix

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

plot_var_analysis(lattice, ax=None, logscale=False)#

Plot the decomposition of a correction vector on the basis of singular vectors

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • lattice (Lattice) – Lattice description. The variables will be evaluated for this Lattice and will be decomposed on the basis of singular vectors,

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

reset_obs()#

Reset the observable exclusion mask: enable all observables

reset_vars()#

Reset the variable exclusion mask: enable all variables

save(file)#

Save a response matrix in the NumPy .npy format.

Parameters:

file – file-like object, string, or pathlib.Path: File to which the data is saved. If file is a file-object, it must be opened in binary mode. If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one.

set_target(target, *, obsid=0)[source]#

Set the target of the specified observable

Parameters:
solve()#

Compute the singular values of the response matrix.

property excluded_obs: dict#

Directory of excluded observables.

The dictionary keys are the observable names, the values are the integer indices of excluded items (empty list if no exclusion).

property excluded_vars: list#

List of excluded variables

observables: ObservableList#

List of matrix Observables

property obsweights: ndarray#

Observable weights.

property response: ndarray[tuple[int, ...], dtype[float64]]#

Response matrix.

ring: Lattice#
property shape: tuple[int, int]#

Shape of the response matrix.

singular_values: ndarray[tuple[int, ...], dtype[float64]] | None = None#

Singular values of the response matrix

variables: VariableList#

List of matrix Variables

property varweights: ndarray#

Variable weights.

property weighted_response: ndarray[tuple[int, ...], dtype[float64]]#

Weighted response matrix.

class TrajectoryResponseMatrix(ring, plane, bpmrefs=<class 'at.lattice.elements.Monitor'>, steerrefs=functools.partial(<function _chkattr>, 'KickAngle'), *, bpmweight=1.0, bpmtarget=0.0, steerdelta=0.0001)[source]#

Bases: ResponseMatrix

Trajectory response matrix.

A TrajectoryResponseMatrix applies to a single plane, horizontal or vertical. A combined response matrix is obtained by adding horizontal and vertical matrices. However, the resulting matrix has the ResponseMatrix class, which implies that the OrbitResponseMatrix specific methods are not available.

Variables are a set of steerers. Steerer variables are named xnnnn or ynnnn where nnnn is the index in the lattice.

Observables are the trajectory position at selected points, named trajectory[x] for the horizontal plane or trajectory[y] for the vertical plane.

The variable elements must have the KickAngle attribute used for correction. It’s available for all magnets, though not present by default except in Corrector magnets. For other magnets, the attribute should be explicitly created.

By default, the observables are all the Monitor elements, and the variables are all the elements having a KickAngle attribute.

Parameters:
  • ring (Lattice) – Design lattice, used to compute the response

  • plane (AxisDef) – One out of {0, ‘x’, ‘h’, ‘H’} for horizontal orbit, or one of {1, ‘y’, ‘v’, ‘V’} for vertical orbit

  • bpmrefs (ndarray[tuple[int, ...], dtype[uint32]]) – Location of closed orbit observation points. See “Selecting elements in a lattice”. Default: all Monitor elements.

  • steerrefs (ndarray[tuple[int, ...], dtype[uint32]]) – Location of orbit steerers. Their KickAngle attribute is used and must be present in the selected elements. Default: All Elements having a KickAngle attribute.

  • bpmweight (float) – Weight on position readings. Must be broadcastable to the number of BPMs

  • bpmtarget (float) – Target position

  • steerdelta (float) – Step on steerers for matrix computation [rad]. This is also the steerer weight. Must be broadcastable to the number of steerers.

build_analytical(**kwargs)[source]#

Build analytically the response matrix.

Keyword Arguments:
  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation from the nominal RF frequency. Defaults to None

Returns:

response – Response matrix

build_tracking(use_mp=False, pool_size=None, start_method=None, **kwargs)#

Build the response matrix.

Parameters:
  • use_mp (bool) – Use multiprocessing

  • pool_size (int | None) – number of processes. If None, min(len(self.variables, nproc) is used

  • start_method (str | None) – python multiprocessing start method. None uses the python default that is considered safe. Available values: 'fork', 'spawn', 'forkserver'. Default for linux is 'fork', default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation, however it is considered unsafe.

Keyword Arguments:
  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation from the nominal RF frequency. Defaults to None

  • r_in (Orbit) – Initial trajectory, used for TrajectoryResponseMatrix, Default: zeros(6)

Returns:

response – Response matrix

check_norm()#

Display the norm of the rows and columns of the weighted response matrix.

Adjusting the variables and observable weights to equalize the norms of rows and columns is important.

Returns:
  • obs_norms – Norms of observables (rows)

  • var_norms – Norms of Variables (columns)

correct(ring, nvals=None, niter=1, apply=False)#

Compute and optionally apply the correction.

Parameters:
  • ring (Lattice) – Lattice description. The response matrix observables will be evaluated for ring and the deviation from target will be corrected

  • apply (bool) – If True, apply the correction to ring

  • niter (int) – Number of iterations. For more than one iteration, apply must be True

  • nvals (int) – Desired number of singular values. If None, use all singular values. nvals may be a scalar or an iterable with niter values.

Returns:

correction – Vector of correction values

correction_matrix(nvals=None)#

Return the correction matrix (pseudo-inverse of the response matrix).

Parameters:

nvals (int | None) – Desired number of singular values. If None, use all singular values

Returns:

cormat – Correction matrix

exclude_obs(*, obsid=0, refpts=None)[source]#

Add a monitor to the set of excluded values.

After excluding observation points, the matrix must be inverted again using solve().

Parameters:

refpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) – location of Monitors to exclude

Raises:

Example

>>> resp = TrajectoryResponseMatrix(ring, "v")
>>> resp.exclude_obs("BPM_02")

Create a vertical TrajectoryResponseMatrix from Corrector elements to Monitor elements, and exclude all monitors with name “BPM_02”

exclude_vars(*varid, refpts=None)[source]#

Add correctors to the set of excluded variables.

Parameters:

After excluding correctors, the matrix must be inverted again using solve().

Examples

>>> resp.exclude_vars(0, "x0103", -1)

Exclude the 1st variable, the variable named “x0103” and the last variable.

>>> resp.exclude_vars(refpts="SD1E")

Exclude all variables associated with the element named “SD1E”.

get_correction(observed, nvals=None)#

Compute the correction of the given observation.

Parameters:
  • observed (ndarray[tuple[int, ...], dtype[float64]]) – Vector of observed deviations,

  • nvals (int | None) – Desired number of singular values. If None, use all singular values

Returns:

corr – Correction vector

get_target(*, obsid=0)#

Return the target of the specified observable

Parameters:

obsid (int | str) – Observable name or index in the observable list.

Returns:

target – observable target

load(file)#

Load a response matrix saved in the NumPy .npy format.

Parameters:

file – file-like object, string, or pathlib.Path: the file to read. A file object must always be opened in binary mode.

plot_norm(ax=None)#

Plot the norm of the lines and columns of the weighted response matrix

For a stable solution, the norms should have the same order of magnitude. If not, the weights of observables and variables should be adjusted.

Parameters:
plot_obs_analysis(lattice, ax=None, logscale=True)#

Plot the decomposition of an error vector on the basis of singular vectors

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • lattice (Lattice) – Lattice description. The response matrix observables will be evaluated for this Lattice and the deviation from target will be decomposed on the basis of singular vectors,

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

plot_singular_values(ax=None, logscale=True)#

Plot the singular values of a response matrix

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

plot_var_analysis(lattice, ax=None, logscale=False)#

Plot the decomposition of a correction vector on the basis of singular vectors

Parameters:
  • resp (ResponseMatrix) – Response matrix object

  • lattice (Lattice) – Lattice description. The variables will be evaluated for this Lattice and will be decomposed on the basis of singular vectors,

  • logscale (bool) – If True, use log scale

  • ax (Axes) – If given, plots will be drawn in these axes.

reset_obs()#

Reset the observable exclusion mask: enable all observables

reset_vars()#

Reset the variable exclusion mask: enable all variables

save(file)#

Save a response matrix in the NumPy .npy format.

Parameters:

file – file-like object, string, or pathlib.Path: File to which the data is saved. If file is a file-object, it must be opened in binary mode. If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one.

set_target(target, *, obsid=0)#

Set the target of the specified observable

Parameters:
solve()#

Compute the singular values of the response matrix.

bpmrefs: ndarray[tuple[int, ...], dtype[uint32]]#
property bpmweight: ndarray[tuple[int, ...], dtype[float64]]#

Weight of position readings.

property excluded_obs: dict#

Directory of excluded observables.

The dictionary keys are the observable names, the values are the integer indices of excluded items (empty list if no exclusion).

property excluded_vars: list#

List of excluded variables

observables: ObservableList#

List of matrix Observables

property obsweights: ndarray#

Observable weights.

property response: ndarray[tuple[int, ...], dtype[float64]]#

Response matrix.

ring: Lattice#
property shape: tuple[int, int]#

Shape of the response matrix.

singular_values: ndarray[tuple[int, ...], dtype[float64]] | None = None#

Singular values of the response matrix

property steerdelta: ndarray#

Step and weight on steerers.

steerrefs: ndarray[tuple[int, ...], dtype[uint32]]#
variables: VariableList#

List of matrix Variables

property varweights: ndarray#

Variable weights.

property weighted_response: ndarray[tuple[int, ...], dtype[float64]]#

Weighted response matrix.

sequence_split(seq, nslices)[source]#

Split a sequence into multiple sub-sequences.

The length of seq does not have to be a multiple of nslices.

Parameters:
  • seq (Sequence) – sequence to split

  • nslices (int) – number of sub-sequences

Returns:

subseqs – Iterator over sub-sequences