pyTomoAO.slodar.slodarProfiler

class pyTomoAO.slodar.slodarProfiler(validLLMap, D, gsDirections, gsHeight=inf, L0=25.0, wavelength=5e-07, conjugationAltitude=0.0, zenithAngleInDeg=0.0, subapOrder='F', slopesOrder='simu', slopeScale=1.0, nEdgePoints=3)[source]

Bases: object

SLODAR turbulence profiler for a multi-guide-star Shack-Hartmann system.

Parameters:
  • validLLMap (array_like of bool) – (nLenslet, nLenslet) valid-subaperture map, shared by all sensors.

  • D (float) – Pupil diameter spanned by nLenslet subapertures [m]; the subaperture size is d = D / nLenslet.

  • gsDirections (array_like) – (nGS, 2) Cartesian angular positions [x, y] of the guide stars [rad].

  • gsHeight (float, optional) – Guide-star range [m]; np.inf (default) for natural guide stars.

  • L0 (float, optional) – Outer scale used by the response functions [m] (default 25).

  • wavelength (float, optional) – Wavelength at which r0 is reported [m] (default 500 nm).

  • conjugationAltitude (float, optional) – Altitude the WFS lenslet arrays are optically conjugated to [m]. Zero (default) is the pupil-conjugated case; a negative value gives generalised SLODAR, in which the ground layer is displaced from zero offset and can be resolved. This only changes the geometric model – it must match how the sensors were actually built.

  • zenithAngleInDeg (float, optional) – Zenith angle of the observation, used to report altitudes and zenith r0.

  • subapOrder ({"F", "C"}, optional) – Enumeration of valid subapertures in the slope vector: column-major ("F", default, as pyTomoAO’s gradient operator) or row-major ("C").

  • slopesOrder ({"simu", "inverted", "keck"}, optional) – Per-sensor slope layout: "simu" = X block then Y block (default), "inverted" = Y block then X block, "keck" = interleaved [x0, y0, x1, y1, ...].

  • slopeScale (float, optional) – Factor converting the input slopes to radians (default 1).

  • nEdgePoints (int, optional) – Samples per subaperture edge in the gradient model. 3 (default) reproduces pyTomoAO’s tomographic gradient operator.

Examples

>>> from pyTomoAO import example_config
>>> from pyTomoAO.slodar import slodarProfiler
>>> prof = slodarProfiler.from_config(example_config("kapa"))
>>> prof.compute_covariance_maps(slopes, removeTT=True)
>>> result = prof.fit_profile()
classmethod from_parameters(lgsWfsParams, lgsAsterismParams, atmParams, **kwargs)[source]

Build a profiler from pyTomoAO parameter objects.

Parameters:
  • lgsWfsParams (lgsWfsParameters) – Provides validLLMap and D.

  • lgsAsterismParams (lgsAsterismParameters) – Provides the guide-star directions and LGSheight (airmass-scaled range).

  • atmParams (atmosphereParameters) – Provides L0, wavelength and zenithAngleInDeg.

  • **kwargs – Overrides for any other slodarProfiler argument.

Returns:

slodarProfiler

classmethod from_config(config_file, **kwargs)[source]

Build a profiler from a pyTomoAO YAML configuration file.

Only the atmosphere_parameters, lgs_asterism and lgs_wfs_parameters sections are read.

Parameters:
  • config_file (str) – Path to the YAML configuration.

  • **kwargs – Overrides passed to from_parameters().

Returns:

slodarProfiler

classmethod from_reconstructor(rec, **kwargs)[source]

Build a profiler sharing the geometry of a tomographicReconstructor.

Parameters:
Returns:

slodarProfiler

property airmass

Airmass 1 / cos(zenith).

property pairs

Cross pairs (i, j) with i < j.

separation(i, j)[source]

Angular separation of guide stars i and j [rad].

lattice_step(i, j)[source]

Subaperture-lattice step along the baseline of pair (i, j) [m].

Offsets along a baseline at angle \(\phi\) cross whole subapertures of the dominant axis every \(d / \max(|\cos\phi|, |\sin\phi|)\); this is d for baselines along X or Y and \(\sqrt{2} d\) for diagonal ones.

native_altitudes(i, j, nMax=None)[source]

Native SLODAR altitude bins of a guide-star pair.

The range whose covariance peak falls delta lattice steps d' along the baseline (see lattice_step()):

  • natural guide stars, h = hc + delta d' / theta;

  • guide stars at range H (cone effect), h = H (delta d' + theta hc) / (delta d' + theta H), which for hc = 0 is h = delta d' / (theta + delta d' / H): the NGS bins compressed by 1 - h/H.

Parameters:
  • i (int) – Guide-star indices (i != j).

  • j (int) – Guide-star indices (i != j).

  • nMax (int, optional) – Largest offset in lattice steps (default nLenslet - 1).

Returns:

numpy.ndarray – Ranges [m] for delta = 0 .. nMax.

default_altitudes(hMax=None, oversample=1)[source]

Altitude grid combining the native bins of every baseline.

The baseline with the finest native spacing sets the grid at low altitude; the others, which reach higher, extend it upwards with their own (coarser) spacing.

Parameters:
  • hMax (float, optional) – Truncate the grid at this range [m].

  • oversample (int, optional) – Insert oversample - 1 extra bins between native ones (default 1, none). Response functions closer than the native resolution are strongly correlated, so oversampling mostly helps when paired with regularization.

Returns:

numpy.ndarray – Sorted ranges [m], starting at the conjugation altitude (or 0).

property counts

Valid subaperture pairs per offset, (2N-1, 2N-1); the map normalisation.

compute_covariance_maps(slopes, removeTT=False, chunkSize=None)[source]

Compute the slope auto- and cross-covariance maps of all sensor pairs.

For sensors i, j and slope components a, b the map is

\[C_{ij}^{ab}(\boldsymbol\delta) = \frac{1}{N_{\boldsymbol\delta}} \sum_{\mathbf p} \langle s_i^a(\mathbf p)\, s_j^b(\mathbf p+\boldsymbol\delta) \rangle_t,\]

where the sum runs over the \(N_{\boldsymbol\delta}\) valid subaperture pairs at offset \(\boldsymbol\delta\) (X along columns, Y along rows). The temporal mean of every slope is removed first.

Parameters:
  • slopes (numpy.ndarray) – (nFrames, nGS*2*nValid) or (nFrames, nGS, 2*nValid) open-loop or pseudo-open-loop slopes, ordered as configured.

  • removeTT (bool, optional) – Remove the per-frame mean X and Y slope (tip-tilt) of every sensor before correlating, as needed for LGS sensors whose tip-tilt is unreliable. The response maps then include the same projection (default False).

  • chunkSize (int, optional) – Frames processed per FFT batch. The batch’s FFT buffer takes chunkSize * nGS * 2 * 2N * (N + 1) * 16 bytes (about 0.3 GB for 2000 frames of six 20x20 sensors, but 3 GB for six 60x60 ones). By default it is sized to keep that buffer near 256 MB.

Returns:

dict – {(i, j): ndarray (4, 2N-1, 2N-1)} for all i <= j, components in COMPONENTS order. Also stored in self.maps.

temporal_noise_variance(slopes, lag=1, removeTT=False)[source]

Per-WFS slope noise variance from the temporal covariance of the slopes.

White measurement noise is uncorrelated from frame to frame, while turbulence evolves little over one frame at kHz-class rates. The noise variance is therefore C(0) - C(lag): the slope variance minus the covariance at lag frames, averaged over the subapertures and both axes of each sensor.

This is the recommended noise estimate for build_reconstructor(noiseCovariance=...), through slope_noise_covariance(). The spatial estimate of fit_profile() (zero-offset excess of the auto-covariance) also absorbs any mismatch between the sensor and the geometric slope model and can be several times too large on a physical Shack-Hartmann. In SPECULA tests this estimator was within 15% of the true noise.

Parameters:
  • slopes (numpy.ndarray) – Time-ordered open-loop or pseudo-open-loop slopes, as for compute_covariance_maps(), at the loop frame rate (do not decimate).

  • lag (int, optional) – Lag in frames (default 1). The estimate is biased high by the turbulence decorrelation over lag frames, which grows with wind speed and frame time.

  • removeTT (bool, optional) – Remove the per-frame tip-tilt of each sensor first. The result is corrected for the 1 - 1/nValid loss of white-noise variance this causes.

Returns:

numpy.ndarray – (nGS,) angle-of-arrival noise variances [rad^2], non-negative.

Notes

With an exact interaction matrix, pseudo-open-loop slopes s + M c(t - 1) cancel the applied correction exactly, so their noise stays white and the estimate is unbiased. Interaction-matrix or centroid-gain errors leave a loop-filtered residual, correlated over a few frames, that biases it. At low flux, calibrate the centroid gain first: a thresholded centroid loses gain, which scales the noise and the turbulence alike.

response_maps(h, L0=None, removeTT=None)[source]

Theoretical covariance maps for a thin layer of unit \(r_0^{-5/3}\) at range h.

Parameters:
  • h (float) – Layer range [m].

  • L0 (float, optional) – Outer scale [m] (default self.L0).

  • removeTT (bool, optional) – Include the per-frame tip-tilt removal projection (default: as used for the measured maps).

Returns:

dict – {(i, j): ndarray (4, 2N-1, 2N-1)} for all i <= j.

fit_profile(altitudes=None, pairs=None, components=('xx', 'yy'), useAuto=True, fitNoise=True, L0=None, fitL0=False, L0Grid=None, minOverlap=0.1, regularization=0.0)[source]

Fit the measured covariance maps with thin-layer response functions.

Solves the weighted non-negative least-squares problem

\[\min_{w \ge 0} \left\| W \left(\sum_k w_k\, R(h_k) + \sum_g n_g\, R_n^{(g)} - C_{\rm meas}\right) \right\|^2,\]

where \(R(h_k)\) are the response maps of response_maps(), \(w_k\) the layer strengths (\(r_0^{-5/3}\)), \(n_g\) optional per-WFS noise variances (auto-covariance only) and \(W\) weights each map entry by \(\sqrt{N_\delta}\).

Parameters:
  • altitudes (array_like, optional) – Layer ranges [m] (default default_altitudes()).

  • pairs (list of tuple, optional) – Cross pairs to use (default: all).

  • components (sequence of str, optional) – Map components to fit: any of "xx", "xy", "yx", "yy" and the longitudinal / transverse combinations "ll", "tt" (cross maps only). Default ("xx", "yy").

  • useAuto (bool, optional) – Also fit the auto-covariance maps (default True). They carry no altitude information for NGS but constrain the total turbulence and the noise. Their xx and yy components are always used, whichever components are selected for the cross maps ("ll"/"tt" are not defined without a baseline).

  • fitNoise (bool, optional) – Fit per-WFS noise variances on the zero-offset point of the auto-covariance (requires useAuto); otherwise that point, which noise biases, is excluded (default True). See slodarResult.noise_covariance() for why temporal_noise_variance() is the better noise estimate for the reconstructor.

  • L0 (float, optional) – Outer scale to use (default self.L0); ignored if fitL0.

  • fitL0 (bool, optional) – Estimate L0 by minimising the fit residual over L0Grid (default False).

  • L0Grid (array_like, optional) – Outer scales tried when fitL0 (default 12 values from 5 to 200 m).

  • minOverlap (float, optional) – Offsets with fewer than minOverlap * nValidSubap subaperture pairs are not fitted (default 0.1).

  • regularization (float, optional) – Ridge penalty on the normalised layer strengths (default 0).

Returns:

slodarResult

profile(slopes, removeTT=False, **fitKwargs)[source]

Compute the covariance maps and fit the profile in one call.

Parameters:
Returns:

slodarResult

slope_covariance(altitudes, r0m53, L0=None)[source]

Full theoretical slope covariance of all sensors for a layered profile.

Parameters:
  • altitudes (array_like) – Layer ranges [m].

  • r0m53 (array_like) – Layer strengths \(r_0^{-5/3}\) at wavelength.

  • L0 (float, optional) – Outer scale (default self.L0).

Returns:

numpy.ndarray – (nGS*2*nValid, nGS*2*nValid) covariance [rad^2], rows and columns in the (WFS, component, subaperture) order of the "simu" layout.

draw_slopes(altitudes, r0m53, nFrames, noiseRms=0.0, L0=None, rng=None)[source]

Draw independent Gaussian slope frames from the theoretical covariance.

Useful to validate the estimator: the maps of these slopes converge to response_maps() by construction, so any bias comes from the estimator and the finite number of frames, not from the turbulence model.

Parameters:
  • altitudes (array_like) – Layered profile (ranges [m] and \(r_0^{-5/3}\)).

  • r0m53 (array_like) – Layered profile (ranges [m] and \(r_0^{-5/3}\)).

  • nFrames (int) – Number of frames.

  • noiseRms (float, optional) – White measurement noise per slope [rad] (default 0).

  • L0 (float, optional) – Outer scale (default self.L0).

  • rng (numpy.random.Generator or int, optional) – Random generator or seed.

Returns:

numpy.ndarray – (nFrames, nGS*2*nValid) slopes in the configured layout and units (i.e. divided by slopeScale).

static cn2dh_to_r0m53(cn2dh, wavelength=5e-07)[source]

Convert \(C_n^2 dh\) [m^1/3] to \(r_0^{-5/3}\) at wavelength.

static profile_to_r0m53(r0, fractions)[source]

Split a total r0 into per-layer \(r_0^{-5/3}\) with the given fractions.

plot_covariance_maps(pair, components=('xx', 'yy'), model=None)[source]

Display measured (and optionally model) covariance maps of one pair.

Parameters:
  • pair (tuple of int) – (i, j) with i <= j.

  • components (sequence of str, optional) – Components to show (default ("xx", "yy")).

  • model (dict, optional) – Model maps with the layout of self.maps to show below the data.

Returns:

matplotlib.figure.Figure