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.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.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:
objectClass 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 thefftmethod of the class. If though, you’re certain the array to transform is C-contiguous, and its size is the same asinputSize, then you can set:fftObj.inputData = fftData
then:
outputData = fftObj()
where
fftDatais 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
-
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:
objectClass 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
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.ConfigObjConfiguration parameters characterising the atmosphere. These should be held in the
Atmospheregroup in the parameter file.- Required:
Parameter Description scrnNoint: Number of turbulence layers scrnHeightslist, int: Phase screen heights in metres scrnStrengthlist, float: Relative layer scrnStrength windDirslist, float: Wind directions in degrees. windSpeedslist, float: Wind velocities in m/s r0float: integrated seeing strength (metres at 500nm) - Optional:
Parameter Description Default scrnNameslist, string: filenames of phase if loading from fits files. If Nonewill make new screens.NonesubHarmonicsbool: Use sub-harmonic screen generation algorithm for better tip-tilt statistics - useful for small phase screens. FalseL0list, float: Outer scale of each layer. Kolmogorov turbulence if None.NonerandomScrnsbool: Use a random set of phase phase screens for each loop iteration? Falseinfinitebool: Use infinite phase screens? Falsetau0float: Turbulence coherence time, if set wind speeds are scaled. NonewholeScrnSizeint: Size of the phase screens to store in the atmosphereobject. 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.ConfigObjConfiguration parameters characterising Deformable Mirrors. These should be held in the
DMsub-group of the parameter file. Each DM is specified seperately, by first specifying an index, then the DM parameters. Any entries abovesim.nGSwill be ignored.- Required:
Parameter Description typestring: Type of DM. This must the name of a class in the DMmodule.nxActuatorsint: 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. gainfloat: The loop gain for the DM.** svdConditioningfloat: 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.ConfigObjConfiguration parameters characterising the Laser Guide Stars. These should be held in theLGSsub-group of the WFS parameter group.- Optional:
Parameter Description Default uplinkbool: Include LGS uplink effects FalsepupilDiamfloat: Diameter of LGS launch aperture in metres. 0.3wavelengthfloat: Wavelength of laser beam in metres 600e-9propagationModestr: Mode of light propogation from GS. Can be “Physical” or “Geometric”. "Phsyical"heightfloat: Height to use physical propogation of LGS (does not effect cone-effect) in metres 90000elongationDepthfloat: Depth of LGS elongation in metres 0elongationLayersint: Number of layers to simulate for elongation. 10launchPositiontuple: 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)fftwThreadsint: number of threads for fftw to use. If 0, will use system processor number.1fftwFlagstr: Flag to pass to FFTW when preparing plan. FFTW_PATIENTnaProfilelist: 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:
objectThe 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
Simdict. For example, ifnGSis set to 2 inSim, then in theWFSdict, 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.ConfigObjConfiguration parameters describing the reconstructor that will be used to calculate DM commands from WFS measurements. The
typemust be an object in thesoapy.reconstructionmodule. Other parameters may be specific to this reconstructor- Optional:
Parameter Description Default typestring: Type of reconstructor to use. Must be a class in reconstruction module. MVMsvdConditioningfloat: Conditioning parameter to be using in Least Squares reconstructor inversion SVD to cut off unwanted DM modes. See numpy.linalg.pinvfor details about the inversion.0gainfloat: Gain of the integrator loop. 0.6imat_noisebool: 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.ConfigObjConfiguration parameters characterising Science Cameras.
These should be held in the
Scienceof the parameter file. Each Science target is created seperately with an integer index. Any entries abovesim.nSciwill be ignored.- Required:
Parameter Description positiontuple: The position of the science camera in the field in arc-seconds FOVfloat: The field of fiew of the science detector in arc-seconds wavelengthfloat: The wavelength of the science detector light pxlsint: Number of pixels in the science detector - Optional:
Parameter Description Default pxlScalefloat: Pixel scale of science camera, in arcseconds. If set, overwrites FOV.Nonetypestring: Type of science camera This must the name of a class in the SCImodule.PSFfftOversampint: Multiplied by the number of of phase points required for FOV to increase fidelity from FFT. 2fftwThreadsint: number of threads for fftw to use. If 0, will use system processor number.1fftwFlagstr: Flag to pass to FFTW when preparing plan. FFTW_MEASUREheightfloat: Altitude of the object. 0 denotes infinity. 0propagationModestr: Mode of light propogation from object. Can be “Physical” or “Geometric”. "Geometric"instStrehlWithTTbool: 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.ConfigObjConfiguration parameters relavent for the entire simulation. These should be held at the beginning of the parameter file with no indendation.
- Required:
Parameter Description pupilSizeint: Number of phase points across the simulation pupil nItersint: Number of iteration to run simulation loopTimefloat: Time between simulation frames (1/framerate) - Optional:
Parameter Description Default nGSint: Number of Guide Stars and WFS 0nDMint: Number of deformable Mirrors 0nSciint: Number of Science Cameras 0reconstructorstr: name of reconstructor class to use. See reconstructormodule for available reconstructors."MVM"simNamestr: directory name to store simulation data NonewfsMPbool: Each WFS uses its own process Falseverbosityint: debug output for the simulation ranging from 0 (no-ouput) to 3 (all debug output) 2logfilestr: name of file to store logging data, NonelearnItersint: Number of learn iterations for Learn & Apply reconstructor 0learnAtmosstr: if random, then random phase screens used for learnrandomsimOversizefloat: The fraction to pad the pupil size with to reduce edge effects 1.2loopDelayint: loop delay in integer count of loopTime0threadsint: Number of threads to use for multithreaded operations 1photometric_zpfloat: Photometric zeropoint - number of photons/meter/second from a magnitude 0 star 2e9- Data Saving (all default to False):
Parameter Description saveSlopesSave all WFS slopes. Accessed from sim with sim.allSlopessaveDmCommandsSaves all DM Commands. Accessed from sim with sim.allDmCommandssaveWfsFramesSaves all WFS pixel data. Saves to disk a after every frame to avoid using too much memory saveStrehlSaves the science camera Strehl Ratio. Accessed from sim with sim.longStrehlandsim.instStrehlsaveWfeSaves the science camera wave front error. Accessed from sim with sim.WFE.saveSciPsfSaves the science PSF. saveInstPsfSaves the instantenous science PSF. saveInstScieFieldSaves the instantaneous electric field at focal plane. saveSciResSave 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.ConfigObjConfiguration parameters characterising the Telescope. These should be held in theTelescopegroup in the parameter file.- Required:
Parameter Description telDiamfloat: Diameter of telescope pupil in metres - Optional:
Parameter Description Default obsDiamfloat: Diameter of central obscuration 0maskstr: Shape of pupil (only accepts circlecurrently)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.ConfigObjConfiguration parameters characterising Wave-front Sensors. These should be held in the
WFSgroup in the parameter file. Each WFS is specified by first specifying an index, then the WFS parameters. Any entries abovesim.nGSwill be ignored.- Required:
Parameter Description GSPositiontuple: position of GS on-sky in arc-secs wavelengthfloat: wavelength of GS light in metres nxSubapsint: number of SH sub-apertures - Optional:
Parameter Description Default typestring: Which WFS object to load from WFS.py? ShackHartmannGSMagfloat: Apparent magnitude of the guide star 0photonNoisebool: Include photon (shot) noise. FalseeReadNoisefloat: Electrons of read noise 0throughputfloat: 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.propagationModestring: Mode of light propogation from GS. Can be “Physical” or “Geometric”**. "Geometric"subapFieldStopbool: 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. FalseremoveTTbool: if True, remove TT signal from WFS slopes before reconstruction.** FalsefftOversampint: Multiplied by the number of of phase points required for FOV to increase fidelity from FFT. 3GSHeightfloat: Height of GS beacon. 0if at infinity.0subapThresholdfloat: How full should subap be to be used for wavefront sensing? 0.5lgsbool: is WFS an LGS? FalsecentMethodstring: Method used for Centroiding. Can be centreOfGravity,brightestPxl, orcorrelation.**centreOfGravityreferenceImagearray: Reference images used in the correlation centroider. Full image plane image, each subap has a separate reference image NoneangleEquivNoisefloat: width of gaussian noise added to slopes measurements in arc-secs 0centThresholdfloat: Centroiding threshold as a fraction of the max subap value.** 0.1exposureTimefloat: Exposure time of the WFS camera - must be higher than loopTime. If None, will be set to loopTime. NonewvlBandWidthfloat: Width of wavelength band sent to WFS in nm 100extendedObjectndarray 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. NonefftwThreadsint: number of threads for fftw to use. If 0, will use system processor number.1fftwFlagstr: Flag to pass to FFTW when preparing plan. FFTW_PATIENTpxlsPerSubapint: number of pixels per sub-apertures 10subapFOVfloat: Field of View of sub-aperture in arc-secs 5correlationFFTPadint: Padding for correlation WFS Nonenx_guard_pixelsint: 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]