Utilities

Modules containing some functions and classes commonly used throughout the simulation.

soapy.logger module

A module to provide a common logging interface for all simulation code.

Contains a Logger object, which can either, print information, save to file or both. The verbosity can also be adjusted between 0 and 3, where all is logged when verbosity is 3, debugging and warning information is logged when verbosity is 2, warnings logged when verbosity is 1 and nothing is logged when verbosity is 0.

soapy.logger.debug(message)[source]

Logs messages if debug level is 3. Intended for very detailed debugging information.

Parameters:message (string) – The message to log
soapy.logger.info(message)[source]

Logs message if verbosity is 2 or higher. Useful for information which is not vital, but good to know.

Parameters:message (string) – The message to log
soapy.logger.print_(message)[source]

Always logs message, regardless of verbosity level

Parameters:message (str) – The message to log
soapy.logger.setLoggingFile(logFile)[source]
soapy.logger.setLoggingLevel(level)[source]

sets which messages are printed from logger.

if logging level is set to 0, nothing is printed. if set to 1, only warnings are printed. if set to 2, warnings and info is printed. if set to 3 detailed debugging info is printed.

Parameters:level (int) – the desired logging level
soapy.logger.setStatusFunc(func)[source]
soapy.logger.statusMessage(i, maxIter, message)[source]
soapy.logger.warning(message)[source]

Logs messages if debug level is 1 or over. Intended for warnings

Parameters:message (string) – The message to log

soapy.AOFFT module

A Module to perform FFTs, wrapping a variety of FFT Backends in a common interface. Currently supports either pyfftw (requires FFTW3), the scipy fftpack or some GPU algorithms

class soapy.AOFFT.Convolve(shape1, shape2=None, mode='pyfftw', fftw_FLAGS=('FFTW_MEASURE', ), threads=0, axes=(-2, -1))[source]

Bases: object

class soapy.AOFFT.FFT(inputSize, axes=(-1, ), mode='pyfftw', dtype='complex64', direction='FORWARD', fftw_FLAGS=('FFTW_MEASURE', 'FFTW_DESTROY_INPUT'), THREADS=None, loggingLevel=None)[source]

Bases: object

Class for performing FFTs in a variety of ways, with the same API.

Once the class has been initialised, FFTs going in the same direction and using the same padding size can be performed with re-initialising. The inputSize set is actually the padding size, any array smaller than this can then be transformed.

Usually, its best to best to pass the data when performing the fft, either calling the class directly (fftobj(fftData)) or calling the fft method of the class. If though, you’re certain the array to transform is C-contiguous, and its size is the same as inputSize, then you can set:

fftObj.inputData = fftData

then:

outputData = fftObj()

where fftData is the data to be transformed. This is faster, as it avoids an array copying operation, but is dangerous as the FFT may fail if the input data is not correct.

Parameters:
  • inputSize (tuple) – The size of the input array, including any padding
  • axes (tuple, optional) – The axes to transform. defaults to the last.
  • mode (string, optional) – Which FFT library to use, can by 'pyfftw', 'scipy' or 'gpu'. Defaults to 'pyfftw'.
  • dtype (str, optional) – The data type to transform, defaults to 'complex64'
  • direction (str, optional) – Forward or inverse FFT. Either FORWARD or BACKWARD. Default is FORWARD.
  • THREADS (int, optional) – Number of threads to use for FFT. Defualt is 1
fft(data=None)[source]

Perform the fft of data.

Parameters:data (ndarray, optional) – The data to transform. Optional as sometimes it can be faster to access inputData directly, though if and only if the data will be c-contiguous.
Returns:The transformed data
Return type:ndarray
soapy.AOFFT.convolve(img1, img2, mode='pyfftw', fftw_FLAGS=('FFTW_MEASURE', ), threads=0)[source]

Convolves two, 2-dimensional arrays Uses the AOFFT library to do fast convolution of 2, 2-dimensional numpy ndarrays. The FFT mode, and some parameters can be set in the arguments. :param img1: 1st array to be convolved :type img1: ndarray :param img2: 2nd array to be convolved :type img2: ndarray :param mode: The fft mode used, defaults to fftw :type mode: string, optional :param fftw_FLAGS: flags for fftw, defaults to (“FFTW_MEASURE”,) :type fftw_FLAGS: tuple, optional :param threads: Number of threads used if mode is fftw :type threads: int, optional

Returns:The convolved 2-dimensional array
Return type:ndarray
soapy.AOFFT.ftShift2d(inputData, outputData=None)[source]

Helper function to shift an array of 2-D FFT data

Parameters:
  • inputData (ndarray) – array of data to be shifted. Will shift final 2 axes
  • outputData (ndarray, optional) – array to place data. If not given, will overwrite inputData
class soapy.AOFFT.mpFFT(inputSize, axes=(-1, ), mode='pyfftw', dtype='complex64', direction='FORWARD', fftw_FLAGS=('FFTW_MEASURE', ), processes=None)[source]

Bases: object

Class to perform FFTs on a large number of problems, using the FFT class, and seperate processes for different problems. The input array will be split in the 0 axis onto different processes

doMpFFT(fftObj, data, Q)[source]
fft()[source]

soapy.aoSimLib module

soapy.opticalPropagationLib module

soapy.confParse module

A module to generate configuration objects for Soapy, given a parameter file.

This module defines a number of classes, which when instantiated, create objects used to configure the entire simulation, or just submodules. All configuration objects are stored in the Configurator object which deals with loading parameters from file, checking some potential conflicts and using parameters to calculate some other parameters used in parts of the simulation.

The ConfigObj provides a base class used by other module configuration objects, and provides methods to read the parameters from the dictionary read from file, and set defaults if appropriate. Each other module in the system has its own configuration object, and for components such as wave-front sensors (WFSs), Deformable Mirrors (DMs), Laser Guide Stars (LGSs) and Science Cameras, lists of the config objects for each component are created.

class soapy.confParse.AtmosConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters characterising the atmosphere. These should be held in the Atmosphere group in the parameter file.

Required:
Parameter Description
scrnNo int: Number of turbulence layers
scrnHeights list, int: Phase screen heights in metres
scrnStrength list, float: Relative layer scrnStrength
windDirs list, float: Wind directions in degrees.
windSpeeds list, float: Wind velocities in m/s
r0 float: integrated seeing strength (metres at 500nm)
Optional:
Parameter Description Default
scrnNames list, string: filenames of phase if loading from fits files. If None will make new screens. None
subHarmonics bool: Use sub-harmonic screen generation algorithm for better tip-tilt statistics - useful for small phase screens. False
L0 list, float: Outer scale of each layer. Kolmogorov turbulence if None. None
randomScrns bool: Use a random set of phase phase screens for each loop iteration? False
infinite bool: Use infinite phase screens? False
tau0 float: Turbulence coherence time, if set wind speeds are scaled. None
wholeScrnSize int: Size of the phase screens to store in the atmosphere object. Required if large screens used. None
allowedAttrs = ['scrnNo', 'scrnHeights', 'scrnStrengths', 'r0', 'windDirs', 'windSpeeds', 'normScrnStrengths', 'N', 'scrnNames', 'subHarmonics', 'L0', 'randomScrns', 'tau0', 'infinite', 'wholeScrnSize']
calcParams()[source]
calculatedParams = ['normScrnStrengths']
optionalParams = [('scrnNames', None), ('subHarmonics', False), ('L0', None), ('randomScrns', False), ('tau0', None), ('infinite', False), ('wholeScrnSize', None)]
p = ('wholeScrnSize', None)
requiredParams = ['scrnNo', 'scrnHeights', 'scrnStrengths', 'r0', 'windDirs', 'windSpeeds']
class soapy.confParse.ConfigObj(N=None)[source]

Bases: object

calcParams()[source]

Dummy method to be overidden if required

initParams()[source]
loadParams(configDict)[source]
warnAndDefault(param, newValue)[source]
warnAndExit(param)[source]
exception soapy.confParse.ConfigurationError[source]

Bases: exceptions.Exception

soapy.confParse.Configurator

alias of PY_Configurator

class soapy.confParse.DmConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters characterising Deformable Mirrors. These should be held in the DM sub-group of the parameter file. Each DM is specified seperately, by first specifying an index, then the DM parameters. Any entries above sim.nGS will be ignored.

Required:
Parameter Description
type string: Type of DM. This must the name of a class in the DM module.
nxActuators int: Number independent DM shapes. e.g., for stack-array DMs this is number of actuators in one dimension, for Zernike DMs this is number of Zernike modes.
gain float: The loop gain for the DM.**
svdConditioning float: The conditioning parameter used in the pseudo inverse of the interaction matrix. This is performed by numpy.linalg.pinv.
Optional:
allowedAttrs = ['type', 'N', 'nxActuators', 'svdConditioning', 'gain', 'closed', 'iMatValue', 'wfs', 'rotation', 'interpOrder', 'gaussWidth', 'altitude', 'diameter', 'gauss_width']
calcParams()[source]
calculatedParams = []
optionalParams = [('nxActuators', None), ('svdConditioning', 0), ('gain', 0.6), ('closed', True), ('iMatValue', 10), ('wfs', None), ('rotation', 0), ('interpOrder', 2), ('gaussWidth', 0.5), ('altitude', 0.0), ('diameter', None), ('gauss_width', 0.7)]
p = ('gauss_width', 0.7)
requiredParams = ['type']
class soapy.confParse.LgsConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters characterising the Laser Guide Stars. These should be held in the LGS sub-group of the WFS parameter group.
Optional:
Parameter Description Default
uplink bool: Include LGS uplink effects False
pupilDiam float: Diameter of LGS launch aperture in metres. 0.3
wavelength float: Wavelength of laser beam in metres 600e-9
propagationMode str: Mode of light propogation from GS. Can be “Physical” or “Geometric”. "Phsyical"
height float: Height to use physical propogation of LGS (does not effect cone-effect) in metres 90000
elongationDepth float: Depth of LGS elongation in metres 0
elongationLayers int: Number of layers to simulate for elongation. 10
launchPosition tuple: The launch position of the LGS in units of the pupil radii, where (0,0) is the centre launched case, and (1,0) is side-launched. (0,0)
fftwThreads int: number of threads for fftw to use. If 0, will use system processor number. 1
fftwFlag str: Flag to pass to FFTW when preparing plan. FFTW_PATIENT
naProfile list: The relative sodium layer strength for each elongation layer. If None, all equal. None
allowedAttrs = ['position', 'N', 'uplink', 'pupilDiam', 'wavelength', 'propagationMode', 'height', 'fftwFlag', 'fftwThreads', 'elongationDepth', 'elongationLayers', 'launchPosition', 'naProfile']
calcParams()[source]
calculatedParams = ['position']
optionalParams = [('uplink', False), ('pupilDiam', 0.3), ('wavelength', 6e-07), ('propagationMode', 'Physical'), ('height', 90000), ('fftwFlag', 'FFTW_PATIENT'), ('fftwThreads', 0), ('elongationDepth', 0), ('elongationLayers', 10), ('launchPosition', array([0, 0])), ('naProfile', None)]
p = ('naProfile', None)
requiredParams = []
class soapy.confParse.PY_Configurator(filename)[source]

Bases: object

The configuration class holding all simulation configuration information

This class is used to load the parameter dictionary from file, instantiate each configuration object and calculate some other parameters from the parameters given.

The configuration file given to this class must contain a python dictionary, named simConfiguration. This must contain other dictionaries for each sub-module of the system, Sim, Atmosphere, Telescope, WFS, LGS, DM, Science. For the final 4 sub-dictionaries, each entry must be formatted as a list (or numpy array) where each value corresponds to that component.

The number of components on the module will only depend on the number set in the Sim dict. For example, if nGS is set to 2 in Sim, then in the WFS dict, each parameters must have at least 2 entries, e.g. subaps : [10,10]. If the parameter has more than 2 entries, then only the first 2 will be noted and any others discarded.

Descriptions of the available parameters for each sub-module are given in that that config classes documentation

Parameters:filename (string) – The name of the configuration file
calcParams()[source]

Calculates some parameters from the configuration parameters.

loadSimParams()[source]
readfile()[source]
class soapy.confParse.ReconstructorConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters describing the reconstructor that will be used to calculate DM commands from WFS measurements. The type must be an object in the soapy.reconstruction module. Other parameters may be specific to this reconstructor

Optional:
Parameter Description Default
type string: Type of reconstructor to use. Must be a class in reconstruction module. MVM
svdConditioning float: Conditioning parameter to be using in Least Squares reconstructor inversion SVD to cut off unwanted DM modes. See numpy.linalg.pinv for details about the inversion. 0
gain float: Gain of the integrator loop. 0.6
imat_noise bool: include WFS noise when making in interaction matrix True
allowedAttrs = ['N', 'type', 'svdConditioning', 'gain', 'imat_noise']
calculatedParams = []
optionalParams = [('type', 'MVM'), ('svdConditioning', 0.0), ('gain', 0.6), ('imat_noise', True)]
p = ('imat_noise', True)
requiredParams = []
class soapy.confParse.SciConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters characterising Science Cameras.

These should be held in the Science of the parameter file. Each Science target is created seperately with an integer index. Any entries above sim.nSci will be ignored.

Required:
Parameter Description
position tuple: The position of the science camera in the field in arc-seconds
FOV float: The field of fiew of the science detector in arc-seconds
wavelength float: The wavelength of the science detector light
pxls int: Number of pixels in the science detector
Optional:
Parameter Description Default
pxlScale float: Pixel scale of science camera, in arcseconds. If set, overwrites FOV. None
type string: Type of science camera This must the name of a class in the SCI module. PSF
fftOversamp int: Multiplied by the number of of phase points required for FOV to increase fidelity from FFT. 2
fftwThreads int: number of threads for fftw to use. If 0, will use system processor number. 1
fftwFlag str: Flag to pass to FFTW when preparing plan. FFTW_MEASURE
height float: Altitude of the object. 0 denotes infinity. 0
propagationMode str: Mode of light propogation from object. Can be “Physical” or “Geometric”. "Geometric"
instStrehlWithTT bool: Whether or not to include tip/tilt in instantaneous Strehl calculations. False
allowedAttrs = ['position', 'wavelength', 'pxls', 'N', 'pxlScale', 'FOV', 'type', 'fftOversamp', 'fftwFlag', 'fftwThreads', 'instStrehlWithTT', 'height', 'propagationMode']
calcParams()[source]
calculatedParams = []
optionalParams = [('pxlScale', None), ('FOV', None), ('type', 'PSF'), ('fftOversamp', 2), ('fftwFlag', 'FFTW_MEASURE'), ('fftwThreads', 1), ('instStrehlWithTT', False), ('height', 0), ('propagationMode', 'Geometric')]
p = ('propagationMode', 'Geometric')
requiredParams = ['position', 'wavelength', 'pxls']
class soapy.confParse.SimConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters relavent for the entire simulation. These should be held at the beginning of the parameter file with no indendation.

Required:
Parameter Description
pupilSize int: Number of phase points across the simulation pupil
nIters int: Number of iteration to run simulation
loopTime float: Time between simulation frames (1/framerate)
Optional:
Parameter Description Default
nGS int: Number of Guide Stars and WFS 0
nDM int: Number of deformable Mirrors 0
nSci int: Number of Science Cameras 0
reconstructor str: name of reconstructor class to use. See reconstructor module for available reconstructors. "MVM"
simName str: directory name to store simulation data None
wfsMP bool: Each WFS uses its own process False
verbosity int: debug output for the simulation ranging from 0 (no-ouput) to 3 (all debug output) 2
logfile str: name of file to store logging data, None
learnIters int: Number of learn iterations for Learn & Apply reconstructor 0
learnAtmos str: if random, then random phase screens used for learn random
simOversize float: The fraction to pad the pupil size with to reduce edge effects 1.2
loopDelay int: loop delay in integer count of loopTime 0
threads int: Number of threads to use for multithreaded operations 1
photometric_zp float: Photometric zeropoint - number of photons/meter/second from a magnitude 0 star 2e9
Data Saving (all default to False):
Parameter Description
saveSlopes Save all WFS slopes. Accessed from sim with sim.allSlopes
saveDmCommands Saves all DM Commands. Accessed from sim with sim.allDmCommands
saveWfsFrames Saves all WFS pixel data. Saves to disk a after every frame to avoid using too much memory
saveStrehl Saves the science camera Strehl Ratio. Accessed from sim with sim.longStrehl and sim.instStrehl
saveWfe Saves the science camera wave front error. Accessed from sim with sim.WFE.
saveSciPsf Saves the science PSF.
saveInstPsf Saves the instantenous science PSF.
saveInstScieField Saves the instantaneous electric field at focal plane.
saveSciRes Save Science residual phase
allowedAttrs = ['pupilSize', 'nIters', 'loopTime', 'pxlScale', 'simPad', 'simSize', 'scrnSize', 'totalWfsData', 'totalActs', 'saveHeader', 'N', 'nGS', 'nDM', 'nSci', 'gain', 'reconstructor', 'simName', 'saveSlopes', 'saveDmCommands', 'saveLgsPsf', 'saveLearn', 'saveStrehl', 'saveWfsFrames', 'saveSciPsf', 'saveInstPsf', 'saveInstScieField', 'saveWfe', 'saveSciRes', 'wfsMP', 'verbosity', 'logfile', 'learnIters', 'learnAtmos', 'simOversize', 'loopDelay', 'threads', 'photometric_zp']
calculatedParams = ['pxlScale', 'simPad', 'simSize', 'scrnSize', 'totalWfsData', 'totalActs', 'saveHeader']
optionalParams = [('nGS', 0), ('nDM', 0), ('nSci', 0), ('gain', 0.6), ('reconstructor', 'MVM'), ('simName', None), ('saveSlopes', False), ('saveDmCommands', False), ('saveLgsPsf', False), ('saveLearn', False), ('saveStrehl', False), ('saveWfsFrames', False), ('saveSciPsf', False), ('saveInstPsf', False), ('saveInstScieField', False), ('saveWfe', False), ('saveSciRes', False), ('wfsMP', False), ('verbosity', 2), ('logfile', None), ('learnIters', 0), ('learnAtmos', 'random'), ('simOversize', 1.02), ('loopDelay', 0), ('threads', 1), ('photometric_zp', 2000000000.0)]
p = ('photometric_zp', 2000000000.0)
requiredParams = ['pupilSize', 'nIters', 'loopTime']
class soapy.confParse.TelConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters characterising the Telescope. These should be held in the Telescope group in the parameter file.
Required:
Parameter Description
telDiam float: Diameter of telescope pupil in metres
Optional:
Parameter Description Default
obsDiam float: Diameter of central obscuration 0
mask str: Shape of pupil (only accepts circle currently) circle
allowedAttrs = ['telDiam', 'N', 'obsDiam', 'mask']
calculatedParams = []
optionalParams = [('obsDiam', 0), ('mask', 'circle')]
p = ('mask', 'circle')
requiredParams = ['telDiam']
class soapy.confParse.WfsConfig(N=None)[source]

Bases: soapy.confParse.ConfigObj

Configuration parameters characterising Wave-front Sensors. These should be held in the WFS group in the parameter file. Each WFS is specified by first specifying an index, then the WFS parameters. Any entries above sim.nGS will be ignored.

Required:
Parameter Description
GSPosition tuple: position of GS on-sky in arc-secs
wavelength float: wavelength of GS light in metres
nxSubaps int: number of SH sub-apertures
Optional:
Parameter Description Default
type string: Which WFS object to load from WFS.py? ShackHartmann
GSMag float: Apparent magnitude of the guide star 0
photonNoise bool: Include photon (shot) noise. False
eReadNoise float: Electrons of read noise 0
throughput float: Throughput of the entire optical and electronic system from guide star photons to recorded WFS detector counts. Includes atmospheric effects, the optical train and detector gain. 1.
propagationMode string: Mode of light propogation from GS. Can be “Physical” or “Geometric”**. "Geometric"
subapFieldStop bool: if True, add a field stop to the wfs to prevent spots wandering into adjacent sub-apertures. if False, oversample subap FOV by a factor of 2 to allow into adjacent subaps. False
removeTT bool: if True, remove TT signal from WFS slopes before reconstruction.** False
fftOversamp int: Multiplied by the number of of phase points required for FOV to increase fidelity from FFT. 3
GSHeight float: Height of GS beacon. 0 if at infinity. 0
subapThreshold float: How full should subap be to be used for wavefront sensing? 0.5
lgs bool: is WFS an LGS? False
centMethod string: Method used for Centroiding. Can be centreOfGravity, brightestPxl, or correlation.** centreOfGravity
referenceImage array: Reference images used in the correlation centroider. Full image plane image, each subap has a separate reference image None
angleEquivNoise float: width of gaussian noise added to slopes measurements in arc-secs 0
centThreshold float: Centroiding threshold as a fraction of the max subap value.** 0.1
exposureTime float: Exposure time of the WFS camera - must be higher than loopTime. If None, will be set to loopTime. None
wvlBandWidth float: Width of wavelength band sent to WFS in nm 100
extendedObject ndarray or str: The object used as extended source for WFS, of size 2*fftOversamp*pxlsPerSubap. The FOV of the object should be twice the FOV of the sub-aperture. None
fftwThreads int: number of threads for fftw to use. If 0, will use system processor number. 1
fftwFlag str: Flag to pass to FFTW when preparing plan. FFTW_PATIENT
pxlsPerSubap int: number of pixels per sub-apertures 10
subapFOV float: Field of View of sub-aperture in arc-secs 5
correlationFFTPad int: Padding for correlation WFS None
nx_guard_pixels int: Guard Pixels between Shack-Hartmann sub-apertures (Not currently operational) 0
allowedAttrs = ['GSPosition', 'wavelength', 'nxSubaps', 'position', 'pxlsPerSubap2', 'dataStart', 'lgs', 'N', 'propagationMode', 'fftwThreads', 'fftwFlag', 'angleEquivNoise', 'subapFieldStop', 'removeTT', 'angleEquivNoise', 'fftOversamp', 'GSHeight', 'subapThreshold', 'lgs', 'centThreshold', 'centMethod', 'type', 'exposureTime', 'referenceImage', 'throughput', 'eReadNoise', 'photonNoise', 'GSMag', 'wvlBandWidth', 'extendedObject', 'pxlsPerSubap', 'subapFOV', 'correlationFFTPad', 'nx_guard_pixels']
calcParams()[source]
calculatedParams = ['position', 'pxlsPerSubap2', 'dataStart', 'lgs']
optionalParams = [('propagationMode', 'Geometric'), ('fftwThreads', 1), ('fftwFlag', 'FFTW_PATIENT'), ('angleEquivNoise', 0), ('subapFieldStop', False), ('removeTT', 'False'), ('angleEquivNoise', 0), ('fftOversamp', 3), ('GSHeight', 0), ('subapThreshold', 0.5), ('lgs', None), ('centThreshold', 0.0), ('centMethod', 'centreOfGravity'), ('type', 'ShackHartmann'), ('exposureTime', None), ('referenceImage', None), ('throughput', 1.0), ('eReadNoise', 0), ('photonNoise', False), ('GSMag', 0.0), ('wvlBandWidth', 100.0), ('extendedObject', None), ('pxlsPerSubap', 10), ('subapFOV', 5), ('correlationFFTPad', None), ('nx_guard_pixels', 0)]
p = ('nx_guard_pixels', 0)
requiredParams = ['GSPosition', 'wavelength', 'nxSubaps']
class soapy.confParse.YAML_Configurator(filename)[source]

Bases: soapy.confParse.PY_Configurator

loadSimParams()[source]
readfile()[source]
soapy.confParse.loadSoapyConfig(configfile)[source]
soapy.confParse.test()[source]