# utils¶

## arte.utils.capture_output module¶

arte.utils.capture_output.capture_output()

Context manager to capture stdout and stderr.

Captures stddout and stderr from a Python code section, using two StringIO objects. Example:

with capture_output() as (out, err):
routine_that_prints_lots()


out.getvalue() will return as string with whatever was printed on stdout. err.getvalue() will return the same for stderr. Nothing will appear on screen.

## arte.utils.circular_buffer module¶

class arte.utils.circular_buffer.GenericCircularBuffer(n_frames, shape, dtype, constructor)

Bases: object

Generic circular buffer.

Implements a generic circular buffer using any class with a numpy-like interface (must define a constructor with shape and dtype parameters, and the constructed object must have a read/write [] operator)

counter()

Returns the total number of stored frames

get(position)

Returns a frame from the circular buffer

help(search='', prefix='')

Interactive help

Prints on stdout a list of methods that match the search substring or all of them if search is left to the default value of an empty string, together with a one-line help taken from the first line of their docstring, if any.

The prefix argument is prepended to the method name and is used for recursive help of every class member.

position()

Returns the current position in the circular buffer

store(data, position=None)

Store a record in the circular buffer.

By default, the record is stored following an internal counter, which is then incremented.

class arte.utils.circular_buffer.NumpyCircularBuffer(n_frames, shape, dtype)

Implements a circular buffer on top of a numpy array

class arte.utils.circular_buffer.SharedCircularBuffer(n_frames, shape, dtype)

Implements a circular buffer on top of a SharedArray

Warning

Since 3.8 the Python standard library provides a SharedMemory class that makes this implementation not working.

Warning

It does not work on Windows.

## arte.utils.compareIDL module¶

arte.utils.compareIDL.compareIDL(idlscript, pyscript, vars_to_compare, precision=1e-05, verbose=0, tmpfile=None)

Compare IDL and Python routines results, to aid in porting.

This function will run an IDL batch script (containing statements that will be executed as if they were typed on the IDL command prompt) and a Python script. After both scripts have been run, the variables listed in vars_to_compare are extracted from both sessions and compared numerically to the specified precision limit.

Parameters: idlscript (string or list of strings) – IDL statements. If in a single string, they must be separated by newlines pyscript (string or list of strings) – Python statements. If in a single string, they must be separated by newlines vars_to_compare (list of strings) – variable names to compare precision (float, optional) – relative numerical precision verbose (int, optional) – verbose level: if greater than zero, will print on stdout the list of variables for which the comparison fails; If greater than one, will also print the variable values. tmpfile (string, optional) – filename for the temporary file used to save IDL variables. If None, a default filename in the system’s temporary directory will be used. True if the comparison is within the precision limit, False otherwise bool

## arte.utils.constants module¶

class arte.utils.constants.Constants

Bases: object

Class holding global constants

ARCSEC2RAD = 4.84813681109536e-06
DEG2RAD = 0.017453292519943295
RAD2ARCSEC = 206264.80624709636
RAD2DEG = 57.29577951308232

## arte.utils.decorator module¶

class arte.utils.decorator.FitsFileCache

Bases: object

Adapter to cache data into FITS files

check()
load()
store(data)
class arte.utils.decorator.PickleFileCache

Bases: object

Adapter to cache data into files using pickle

check()
load()
store(data)
exception arte.utils.decorator.ReturnTypeMismatchError

Bases: Exception

class arte.utils.decorator.TextFileCache

Bases: object

Adapter to cache data into text files

check()
load()
store(data)
arte.utils.decorator.cacheResult(f)
arte.utils.decorator.cache_on_disk(fname=None, fname_func=None, adapter=<class 'arte.utils.decorator.FitsFileCache'>)

Decorator that caches a function result into a local file.

The file can be specified as either a constant filename, or a function that returns a filename. The second form is useful if the filename is not known when the function is defined, but only at runtime.

Roughly equivalent to:

else:

return data

Parameters: fname (str, optional) – name of the file where the data is stored. One of filename and fname_func must be specified. fname_func (callable, optional) – function or callable without arguments that returns a filename, to be used in case the name changes at runtime. adapter (class) – class managing the load/store to file, optional. By default FITS files will be used as storage.
arte.utils.decorator.logEnterAndExit(enterMessage, exitMessage, level='notice')
arte.utils.decorator.logFailureAndContinue(func)
arte.utils.decorator.logTime(f)
arte.utils.decorator.override(f)
arte.utils.decorator.returns(returnType)
arte.utils.decorator.returnsForExample(exampleInstance)
arte.utils.decorator.returnsNone(f)
arte.utils.decorator.suppressException(resultInCaseOfFailure=None)
arte.utils.decorator.synchronized(item)

## arte.utils.discrete_fourier_transform module¶

class arte.utils.discrete_fourier_transform.BidimensionalFourierTransform

Bases: object

static direct(xyFunct)
static direct_transform(data)
static distances_norm_map(sizeInPoints, pixelSize)
static distances_x_map(sizeInPoints, pixelSize)
static frequencies_norm_map(sizeInPoints, pixelSize)
static frequencies_x_map(sizeInPoints, pixelSize)
static frequencies_y_map(sizeInPoints, pixelSize)
static inverse(xyFunct)
static inverse_transform(data)
static most_negative_frequency(sizeInPoints, pixelSize)
static most_positive_frequency(sizeInPoints, pixelSize)
static smallest_frequency(sizeInPoints, pixelSize)

## arte.utils.executor module¶

exception arte.utils.executor.BusyExecutorException(message, nameOfCurrentTask)

Bases: Exception

class arte.utils.executor.DelayedTaskControl
isDone()
isRunning()
markAsDone()
waitForCompletion(timeoutSec)
class arte.utils.executor.DoneTaskControl
isDone()
isRunning()
waitForCompletion(timeoutSec)
class arte.utils.executor.Executor

Bases: object

execute(task)
class arte.utils.executor.ExecutorFactory

Bases: object

static buildMultiThreadExecutor(maxNumThreads)
static buildSingleThreadExecutor(logger=<arte.utils.logger.PythonLogger object>)
static buildSingleThreadImmediateExecutor(logger=<arte.utils.logger.PythonLogger object>)
class arte.utils.executor.FunctionTask(func, *args, **kwds)
NO_RESULT = <object object>
getException()
getResult()
name()
perform()
reraiseExceptionIfAny()
withName(name)
exception arte.utils.executor.FunctionTaskException

Bases: Exception

class arte.utils.executor.FutureTaskControl(future, taskName, logger)
isDone()
isRunning()
waitForCompletion(timeoutSec=None)
class arte.utils.executor.MultiThreadExecutor(maxThreads, logger=<arte.utils.logger.PythonLogger object>)
execute(task)
class arte.utils.executor.SerialExecutor(logger=<arte.utils.logger.PythonLogger object>)
execute(task)
class arte.utils.executor.SingleThreadExecutor(logger=<arte.utils.logger.PythonLogger object>)
class arte.utils.executor.SingleThreadImmediateExecutor(singleThreadExecutor)
execute(task)
isIdle()
class arte.utils.executor.Task

Bases: object

name()
perform()
class arte.utils.executor.TaskControl

Bases: object

isDone()
isRunning()
waitForCompletion(timeoutSec)
class arte.utils.executor.TaskDelayingExecutor
execute(task)
executeDelayedTasks()
getDelayedTasks()
exception arte.utils.executor.TaskTimeoutError(msg)

Bases: Exception

arte.utils.executor.logTaskFailure(func)

## arte.utils.generalized_fitting_error module¶

class arte.utils.generalized_fitting_error.GeneralizedFittingError(spatialFrequenciesInInverseMeter, altitudeOfDeformableMirrorsInMeter, pitchOfDeformableMirrorsInMeter, optimizedFieldOfViewInArcsec, cn2Profile, zenithAngleInDeg, seeingInArcsec)

Bases: object

## arte.utils.help module¶

Provides tools to build an interactive, searchable help based on docstrings.

Any class to decorated with @add_help gets a help() method that provides an interactive and searchable help based on the method docstrings. All public methods (not starting with “_”) are added, together with all such methods in all the members that are classed decorated with @add_help. Derived classes inherit the help system without a need to use the @add_help decorator.

Help is built dynamically when invoked, so if a new member is added to the class at runtime, it will appear in the help too.

The help method name can be customized giving the help_function parameter to the decorator.

If the classmethod parameter is True, the help function is created as a classmethod instead of an ordinary method. This is useful for classes that only define classmethods and are not normally instanced.

Example:

from arte.utils.help import add_help

class InnerClass():
"""An inner class"""

def a_method(self):
"""This is a method"""
pass

class MyClass():
"""This is my class"""
b = InnerClass()

def a_method(self):
"""This is a method"""
pass

def another_method(self):
"""This is another method"""
pass

class CustomClass():
"""This a custom class"""

def a_method(self):
"""This is a method"""
pass


Interactive session:

>>> a  = MyClass()
>>> a.help()
---------
MyClass                    This is my class
MyClass.a_method()         This is a method
MyClass.another_method()   This is another method
---------
MyClass.b              An inner class
MyClass.b.a_method()   This is a method

>>> a.help('other')
---------
MyClass.another_method()   This is another method

>>> a.help('inner')
---------
MyClass.b              An inner class

>>> b = CustomClass()
>>> b.show_help()
---------
CustomClass               This a custom class
CustomClass.a_method()    This is a method

arte.utils.help.add_help(cls=None, *, help_function='help', classmethod=False)

Decorator to add interactive help to a class

Parameters: help_function (str, optional) – Name of the method that will be added to the class. Defaults to “help” classmethod (bool, optional) – If True, the help method will be added as a classmethod. Default False The decorated class type class
arte.utils.help.hide_from_help(f)

Decorator to hide a method from the interactive help

arte.utils.help.modify_help(call=None, arg_str=None, doc_str=None)

Decorator to modify the automatic help for a method.

Without this decorator, the method signature for help is just “method()”. Using this decorator, other signatures are possible:

@modify_help(call='mymethod1(foo)')
def mymethod1(self, ....)
"""This method is very cool"""

@modify_help(arg_str='idx1, idx2')
def mymethod2(self, ....)
"""Now you see it"""

@modify_help(doc_str='Surprise!')
def mymethod3(self, ....)
"""And now you don't"""


Resulting help:

.mymethod1(foo)        : This method is very cool
.mymethod2(idx1, idx2) : Now you see it
.mymethod3()           : Surprise!


Note

if the method is a @staticmethod, this decorator should be inserted after the staticmethod one.

## arte.utils.image_moments module¶

class arte.utils.image_moments.ImageMoments(image, shiftPixels=0.5)

Bases: object

centralMoment(iord, jord)
centralNormalizedMoment(iord, jord)
centroid()
covarianceMatrix()
eccentricity()
effectiveRadius()
eigenvalues()
orientation()
principalMomentsOfInertia()
rawMoment(iord, jord)
semiAxes()
xBar()
yBar()

## arte.utils.iterators module¶

arte.utils.iterators.flatten(x)

Generator that flatten arbitrarily nested lists.

This generator will flatten a list that may contain other lists (nested arbitrarily) and simple items into a flat list.

>>> flat = flatten([[1,[2,3]],4,[5,6]])
>>> list(flat)
[1, 2, 3, 4, 5, 6]

arte.utils.iterators.pairwise(iterable)

Pairwise iterator, from itertool recipes.

See Python library docs, itertools chapter.

>>> s = [0,1,2,3,4,5,6]
>>> list(pairwise(s))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]


## arte.utils.locate module¶

arte.utils.locate.locate(pattern, rootdir=None)

Generator similar to Unix’s locate utility

Locates all files matching a pattern, inside and below the root directory. If no root directory is given, the current directory is used instead.

Parameters: pattern (string) – the filename pattern to match. Unix wildcards are allowed rootdir (string, optional) – the root directory where the search is started. If not set, the current directory is used. string – the next filename matching pattern
arte.utils.locate.locate_first(pattern, rootdir=None)

Locate the first filename matching pattern

Locate the first file a matching, inside and below the root directory. If no root directory is given, the current directory is used instead.

Parameters: pattern (string) – the filename pattern to match. Unix wildcards are allowed rootdir (string, optional) – the root directory where the search is started. If not set, the current directory is used. the first filename matching pattern, or None if not found. string
arte.utils.locate.replace_in_file(filename, search, replace)

Replaces a string inside a file

## arte.utils.logger module¶

class arte.utils.logger.AbstractLogger

Bases: object

debug(m)
error(m)
fatal(m)
notice(m)
warn(m)
class arte.utils.logger.AbstractLoggerFactory

Bases: object

getLogger(loggerName)
class arte.utils.logger.DummyLogger
debug(m)
error(m)
fatal(m)
notice(m)
warn(m)
class arte.utils.logger.DummyLoggerFactory
getLogger(name)
class arte.utils.logger.Logger

Bases: object

DEFAULT_LOGGER_FACTORY

alias of PythonLoggerFactory

static of(loggerName)
static setLoggerFactory(loggerFactory)
exception arte.utils.logger.LoggerException

Bases: Exception

class arte.utils.logger.LoggerListener

Bases: object

onDebug(message)
onError(message)
onFatal(message)
onNotice(message)
onWarning(message)
class arte.utils.logger.ObservableLogger(wrappedLogger)
addListener(listener)
debug(m)
error(m)
fatal(m)
notice(m)
warn(m)
class arte.utils.logger.ObservableLoggerFactory(wrappedLoggerFactory)
addListener(loggerListener)
getLogger(name)
getLoggerMap()
class arte.utils.logger.PythonLogger(logger)
debug(m)
error(m)
fatal(m)
notice(m)
setRelativePathRadix(radix)
warn(m)
class arte.utils.logger.PythonLoggerFactory
getLogger(name)

## arte.utils.marechal module¶

arte.utils.marechal.scale_strehl_ratio(strehlRatio, fromWavelength, toWavelength)

Scale Strehl ratio from one wavelength to another one according to Marechal approximation

Parameters: strehlRatio (float) – Strehl ratio (0.0-1.0) fromWavelength (astropy.units.quantity.Quantity or float) – Wavelength Strehl Ratio is given at; if float units must be in meter toWavelength (astropy.units.quantity.Quantity or float) – Wavelength to compute Strehl Ratio at; if float units must be in meter strehlRatio – Strehl Ratio computed at toWavelength float
arte.utils.marechal.strehl_ratio_2_wavefront_rms(strehlRatio, wavelength)

Compute wavefront aberration from Strehl ratio according to Marechal approximation

Parameters: strehlRatio (float) – Strehl ratio (0.0-1.0) wavelength (astropy.units.quantity.Quantity or float) – Wavelength to compute Strehl Ratio; if float units must be in meter wavefrontRms – Wavefront aberration rms astropy.units.quantity.Quantity
arte.utils.marechal.wavefront_rms_2_strehl_ratio(wavefrontRms, wavelength)

Compute Strehl ratio from wavefront aberration according to Marechal approximation

Parameters: wavefrontRms (astropy.units.quantity.Quantity or float) – Wavefront aberration rms; if float units must be in meter wavelength (astropy.units.quantity.Quantity or float) – Wavelength to compute Strehl Ratio; if float units must be in meter results – Strehl ratio float

## arte.utils.math module¶

arte.utils.math.besselFirstKind(order, arg)
arte.utils.math.besselFirstKindOnGPU(order, arg)
arte.utils.math.kroneckerDelta(m, n)
arte.utils.math.round_up_to_even(f)

## arte.utils.modal_decomposer module¶

class arte.utils.modal_decomposer.ModalDecomposer(n_zernike_modes)

Bases: object

measureZernikeCoefficientsFromSlopes(slopes, mask, nModes=None)
measureZernikeCoefficientsFromWavefront(wavefront, mask, nModes=None)

## arte.utils.noise_propagation module¶

class arte.utils.noise_propagation.NoisePropagation(nSubaps=3, modesV=array([1, 2, 3, 4, 5, 6]), rcond=0.001)

Bases: object

D
R
leftSingularVectorMapForMode(nMode)
modesVector
nModes
nSlopes
nSubaps
noisePropagationMatrix
noiseSimulation(sigma=1, nSamples=1000)
phaseCube
s
sInv
sigma
slopesMapForMode(nMode)
u
v

## arte.utils.package_data module¶

arte.utils.package_data.dataRootDir()

Created on Oct 16, 2018

@author: lbusoni

arte.utils.quadratic_sum.quadraticSum(arrayOfErrorsWithSign)

Sum in quadrature of errors, considering sign

arte.utils.radial_profile.computeRadialProfile(image, centerInPxY, centerInPxX)

## arte.utils.rebin module¶

# who when what # ——- ———- ——————————— # 2012-11-20 Created from git://gist.github.com/1348792.git # apuglisi 2020-04-15 Added sample option, added exceptions, # allow any kind of sequence for new_shape

arte.utils.rebin.rebin(a, new_shape, sample=False)

Replacement of IDL’s rebin() function for 2d arrays.

Resizes a 2d array by averaging or repeating elements. New dimensions must be integral factors of original dimensions, otherwise a ValueError exception will be raised.

Parameters: a (ndarray) – Input array. new_shape (2-elements sequence) – Shape of the output array sample (bool) – if True, when reducing the array side elements are set using a nearest-neighbor algorithm instead of averaging. This parameter has no effect when enlarging the array. rebinned_array – If the new shape is smaller of the input array the data are averaged, unless the sample parameter is set. If the new shape is bigger array elements are repeated. ndarray ValueError – in the following cases: new_shape is not a sequence of 2 values that can be converted to int new dimensions are not an integral factor of original dimensions NotImplementedError – - one dimension requires an upsampling while the other requires a downsampling

Examples

>>> a = np.array([[0, 1], [2, 3]])
>>> b = rebin(a, (4, 6)) #upsize
>>> b
array([[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[2, 2, 2, 3, 3, 3],
[2, 2, 2, 3, 3, 3]])
>>> rebin(b, (2, 3)) #downsize
array([[0. , 0.5, 1. ],
[2. , 2.5, 3. ]])
>>> rebin(b, (2, 3), sample=True) #downsize
array([[0, 0, 1],
[2, 2, 3]])


## arte.utils.shared_array module¶

class arte.utils.shared_array.SharedArray(shape, dtype)

Bases: object

Class for a numpy-like buffer built on top of multiprocessing.

SharedArray instances can be passed as arguments to processes created with the multiprocessing module, and each of them can call the ndarray() method to get a local view of the array.

No access synchronization is provided.

As a shortcut to read/write the array, the [] operator is supported, thus these two statements are equivalent:

>>> array.ndarray()[2] = 3.1415
>>> array[2] = 3.1415


Warning

SharedArray works with processes spawned with mp.Process, but do not work with mp.Pool, unless an mp.Manager is used.

Warning

Since 3.8 the Python standard library provides a SharedMemory class that must be used instead of this.

Warning

It does not work on Windows.

Parameters: shape (integer sequence) – array shape type (numpy dtype) – array dtype
help(search='', prefix='')

Interactive help

Prints on stdout a list of methods that match the search substring or all of them if search is left to the default value of an empty string, together with a one-line help taken from the first line of their docstring, if any.

The prefix argument is prepended to the method name and is used for recursive help of every class member.

ndarray(realloc=False)

Returns a new numpy wrapper around the buffer contents.

Call this function after a task has been spawned the multiprocessing module in order to have access to the shared memory segment.

If the array had already been accessed before passing it to the multiprocessing task, the task has to set realloc to True in order to reallocate a local copy of the array.

Parameters: Realloc (bool, optional) – force array reallocation. Defaults to False the shared numpy array. The array is read-write and changes will be immediately visible to other processes. numpy.ndarray

## arte.utils.timestamp module¶

class arte.utils.timestamp.Timestamp

Bases: object

asNowString()
asTodayString()
static now()
static nowUSec()
static today()

## arte.utils.tabular_report module¶

class arte.utils.tabular_report.TabularReport(column_names, decimation: int = 1, hdr_decimation: int = 100, add_iter: bool = True, column_width: int = 10, iteration_hdr='iteration')

Bases: object

Report with column-based format.

Prints a new line of values each time it is triggered.

Columns are defined at initialization with the column_names, and they can be set using the [] operator. Each column will occupy column_width characters (default 10 characters). Columns will be printed in the order they were added.

Each column has a formatter function, which can set using the .fmt dictionary. The formatter function must take a single parameter, the value to be displayed, and return a string. By default, all columns are formatted with str().

It is possible to add a column on the fly assigning to it using the [] operator. The new column will be assigned the default str() formatter.

Every time the report() function is called, an internal counter is incremented and, if at least decimation counts have passed since the last time, the values are printed on stdout. By default, decimation is 1 and all lines are printed. A header with the column names is printed before the first line and after each repeat_hdr lines have been printed (default 100). If add_iter is True, the counter is printed as the first column.

decimation

how many calls to report() are needed before a line is printed

Type: int
hdr_decimation

how many lines are printed before the header is printed again

Type: int
add_iter

if True, the iteration number is added as the first column

Type: bool
column_width

number of characters assigned to each column

Type: int
iteration_hdr

string used as column name for the iteration number

Type: str
['column_name']

Assign values to column using the [] operator.

fmt['column_name']

Assign special formatting functions using the fmt dictionary.

Examples

>>> from arte.utils.tabular_report import TabularReport
>>> r = TabularReport(['pippo','pluto'])
>>> for i in range(2):
...    r['pippo'] = i*2
...    r['pluto'] = i+10
...    r.report()
>>> r['paperino'] = 'a'
>>> r.fmt['paperino'] = ord
>>> r.report()


Result:

iteration  pippo      pluto
---------------------------------
1          0          10
2          2          11

iteration  pippo      pluto      paperino
--------------------------------------------
3          2          11         97

print_header()

Unconditionally print a line with the header.

print_line()

Unconditionally print a line with all the current values

report()

Increment the iteration counter and if, conditions match, print a header and/or a line of values.

## arte.utils.unit_checker module¶

arte.utils.unit_checker.assert_array_almost_equal_w_units(a, b)

Clone of np.testing.asset_array_almost_equal for u.Quantities

arte.utils.unit_checker.assert_unit_is_equivalent(var, ref)

Make sure that var has a unit compatible with ref

arte.utils.unit_checker.make_sure_its_a(unit, v, name='')

Make sure that v has the astropy unit unit.

If v does not have any unit, apply unit and return the combined value. If it has one, check that it can be converted to unit, and return the converted value. Otherwise, raise astropy.units.UnitsError.

Parameters: unit (astropy unit) – the wanted unit v – the value under test name (string) – description of v. Will be used in error messages in case the conversion fails. the original value converted to unit. astropy Quantity astropy.units.UnitsError – if the conversion to unit fails.
arte.utils.unit_checker.match_and_remove_unit(var, var_to_match)

Make sure that var has the same unit as var_to_match, if any, and then remove the unit. If var_to_match has no unit, the value of var is returned, without its unit if it has one.

Parameters: var (any type) – the variable to be tested var_to_match (any type) – the variable whose unit must be matched the value of var (without unit attached) after the unit has been changed to be the same as var_to_match value u.UnitsError – if var cannot be converted to var_to_match using the standard astropy method var.to()

Examples

>>> a = 42*u.km
>>> b = 42*u.m
>>> match_and_remove_unit(a,b)
42000.0

>>> a = 42
>>> c = 3.1415
>>> match_and_remove_unit(a,c)
42

arte.utils.unit_checker.match_and_remove_units(*args)

Take a list of variables, make sure that all have the same unit as the first one, and return a list of unitless values plus the common unit.

Order is significant! The first variable’s unit is applied to all others. If the first one does not have a unit, all units are removed.

Parameters: *args (an arbitrary number of parameters) – variables whose units must be matched list of values after unit conversion and removal, plus the unit. If the first parameter had no unit, the unit is set to 1. list u.UnitsError – if any of the parameters cannot be converted using the standard astropy method var.to()

Examples

>>> a = 42*u.m
>>> b = 42*u.cm
>>> c = 42*u.km
>>> match_and_remove_units(a,b,c)
[42.0, 0.42, 42000.0, Unit("m")]

>>> a = 42
>>> b = 42*u.cm
>>> c = 42*u.km
>>> match_and_remove_units(a,b,c)
[42, 42.0, 42.0, 1]

arte.utils.unit_checker.separate_value_and_unit(var)

Returns the argument value and unit, if var has one.

If not, var is returned unchanged and unit is set to 1.

Parameters: var (any type) – the variable to be tested tuple with the value and the astropy unit of var or 1 if var does not have a unit. value, unit

Examples

>>> a = 42 * u.m
>>> separate_value_and_unit(a)
(42.0, Unit("m"))

>>> b = 42
>>> separate_value_and_unit(b)
(42, 1)

arte.utils.unit_checker.unit_check(f)

Decorator to add type checking of astropy units to a function.

This decorator will ensure that, each time the decorated function is called, all the arguments have the correct astropy units, as defined in the default values of the decorated function, calling make_sure_its_a() for each of them.

If the function does not define a unit for a parameter, the corresponding argument is not modified, whether it has a unit or not.

If any of the checks fails, raises TypeError when the decorated function is called.

## arte.utils.zernike_generator module¶

class arte.utils.zernike_generator.ZernikeGenerator(pupil)

Bases: object

Generator of Zernike polynomials and their derivatives

The generator returns masked arrays representing Zernike polynomials sampled over the array grid. The pixels whose distance from the unit disk center is greater than the mask radius are masked.

The discretization of the continous unit disk space into the array grid is done in the pixels’ center (e.g. if the disk diameter is 2 pixels and the center is in x=1 then the first pixel contains polynomial values evaluated in x=-0.5 and the second pixel contains values evaluated in x=0.5)

The user can specify the diameter of the pupil pupil or specify a CircularMask

In the case a scalar real value is passed as pupil argument, The shape of the returned array cannot be specified: it is a square array of size ceil(pupil_diameter). The center of the unit disk cannot be specified and it is the central pixel of the array (if the array size is odd) or the corner of the 4 central pixels (if the array size is even).

In the case a CircularMask is passed as pupil argument, the mask is used as unit disk over which the polynomial are computed. Non-integer center coordinates and radius are properly managed.

Parameters: pupil (real or CircularMask) – If a scalar value, the argument is used as pupil diameter in pixels. If a CircularMask, the argument is used as mask representing the unit disk.

Notes

Polynomials normalization and ordering follows the conventions described in Noll’s paper [1]

 [1] Noll, R. J., “Zernike polynomials and atmospheric turbulence.”, Journal of the Optical Society of America (1917-1983), vol. 66, pp. 207–211, 1976.

Examples

Create a Zernike polynomial sampled with unit circle defined over 64 pixels representing tilt

>>> zg = ZernikeGenerator(64)
>>> tip = zg.getZernike(2)
>>> tilt = zg.getZernike(3)
>>> tilt = zg[3] # equivalent to getZernike(3)

cartesian_coordinates()

Return X, Y maps of cartesian coordinates

The Zernike polynomials and derivatives are evaluated over a grid of points, whose coordinates are accessible through cartesian_coordinates

Returns: X,Y – coordinates of points of the unit disk where the polynomials are evaluated array

Examples

Create Zernike polynomials on a unit disk defined over 4 pixels. The returned arrays have (4,4) shape (corresponding to the coords [-0.75, -0.25, 0.25, 0.75])

>>> zg = ZernikeGenerator(4)
>>> x, y = zg.cartesian_coordinates()
>>> x[0]
array([-0.75, -0.25,  0.25,  0.75])


As above with 3 pixels

>>> zg = ZernikeGenerator(3)
>>> x, y = zg.cartesian_coordinates()
>>> x[0]
array([-0.666, 0,  0.666])


In case of non-integer diameter, the array size is rounded up to the next integer

>>> zg = ZernikeGenerator(2.5)
>>> x, y = zg.cartesian_coordinates()
>>> x[0]
array([-0.8, 0,  0.8])

center()

Y, X coordinates of the unit disk center

Returns: center – Y, X coordinate of the unit disk center in the array reference system array of shape (2,)
classmethod degree(index)
getDerivativeX(index)
getDerivativeXDict(indexVector)
getDerivativeY(index)
getDerivativeYDict(indexVector)
getZernike(index)
getZernikeDict(indexVector)
classmethod radial_order(j)

Return radial order of j-th polynomial

Parameters: j (int or sequence of int) – polynomial index n – radial order of the specified indexes int or sequence of int
radius()

class arte.utils.zernike_projection_on_subaperture.ZernikeProjectionOnSubaperture(pupilRadiusInMeter, subapsRadiusInMeter, subapOffAxisRadiusInMeter, subapOffAxisAzimuthInDegrees)
Bases: object
computeZernikeDecomponsitionOnSubap(zernikeCoeffFrom2To11)
getProjectionMatrix()