utils

Submodules

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)

Bases: GenericCircularBuffer

Implements a circular buffer on top of a numpy array

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

Bases: GenericCircularBuffer

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.

Returns:

True if the comparison is within the precision limit, False otherwise

Return type:

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

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:

if adapter.check(fname):

data = adapter.load(fname)

else:

data = f() adapter.store(fname, data)

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_transform(data)
static most_negative_frequency(sizeInPoints, pixelSize)
static most_positive_frequency(sizeInPoints, pixelSize)
static reverse(xyFunct)
static smallest_frequency(sizeInPoints, pixelSize)

arte.utils.executor module

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

Bases: Exception

class arte.utils.executor.DelayedTaskControl

Bases: TaskControl

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

Bases: TaskControl

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

Bases: object

abstract 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)

Bases: Task

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)

Bases: TaskControl

isDone()
isRunning()
waitForCompletion(timeoutSec=None)
class arte.utils.executor.MultiThreadExecutor(maxThreads, logger=<arte.utils.logger.PythonLogger object>)

Bases: Executor

execute(task)
class arte.utils.executor.SerialExecutor(logger=<arte.utils.logger.PythonLogger object>)

Bases: Executor

execute(task)
class arte.utils.executor.SingleThreadExecutor(logger=<arte.utils.logger.PythonLogger object>)

Bases: MultiThreadExecutor

class arte.utils.executor.SingleThreadImmediateExecutor(singleThreadExecutor)

Bases: Executor

execute(task)
isIdle()
class arte.utils.executor.Task

Bases: object

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

Bases: object

abstract isDone()
abstract isRunning()
abstract waitForCompletion(timeoutSec)
class arte.utils.executor.TaskDelayingExecutor

Bases: Executor

execute(task)
executeDelayedTasks()
getDelayedTasks()
exception arte.utils.executor.TaskTimeoutError(msg)

Bases: Exception

arte.utils.executor.logTaskFailure(func)

arte.utils.footprint_geometry module

arte.utils.generalized_fitting_error module

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

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

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

@add_help
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

@add_help(help_function='show_help')
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

Returns:

The decorated class type

Return 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

centralNormalizedMoment(iord, jord)
central_moment(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.

Yields:

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.

Returns:

the first filename matching pattern, or None if not found.

Return type:

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

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

Bases: object

getLogger(loggerName)
class arte.utils.logger.DummyLogger

Bases: AbstractLogger

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

Bases: AbstractLoggerFactory

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)

Bases: AbstractLogger

addListener(listener)
debug(m)
error(m)
fatal(m)
notice(m)
warn(m)
class arte.utils.logger.ObservableLoggerFactory(wrappedLoggerFactory)

Bases: AbstractLoggerFactory

addListener(loggerListener)
getLogger(name)
getLoggerMap()
class arte.utils.logger.PythonLogger(logger)

Bases: AbstractLogger

debug(m)
error(m)
fatal(m)
notice(m)
setRelativePathRadix(radix)
warn(m)
class arte.utils.logger.PythonLoggerFactory

Bases: AbstractLoggerFactory

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

Returns:

strehlRatio – Strehl Ratio computed at toWavelength

Return type:

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

Returns:

wavefrontRms – Wavefront aberration rms

Return type:

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:
Returns:

results – Strehl ratio

Return type:

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

arte.utils.noise_propagation module

arte.utils.package_data module

arte.utils.package_data.dataRootDir()

arte.utils.paste module

arte.utils.paste.paste(wall, block, loc)

Paste block array into wall in location loc.

loc must be a tuple (even if block.ndim=1) Going outside of the edges of wall is properly managed. wall is modified in place.

Parameters:
  • wall (array of ndim=N) – Array in which block is pasted.

  • block (array of ndim=N) – Array to be pasted into wall

  • loc (tuple, shape (N,)) – location where to paste block.

Return type:

None

Example

Insert array [1,2,3,4] into an empty array of size 10 at location 8

>>> b = np.zeros([10])
>>> a = np.arange(1, 5)
>>> b
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> a
array([1, 2, 3, 4])
>>> paste(b, a, (8,))
>>> b
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  2.])

References

https://stackoverflow.com/questions/7115437/how-to-embed-a-small-numpy-array-into-a-predefined-block-of-a-large-numpy-arra

arte.utils.quadratic_sum module

Created on Oct 16, 2018

@author: lbusoni

arte.utils.quadratic_sum.quadraticSum(arrayOfErrorsWithSign)

Sum in quadrature of errors, considering sign

5 = quadraticSum([3, 4]) 8 = quadraticSum(10, -6])

Inputs can be numpy arrays

arte.utils.radial_profile module

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

arte.utils.rebin module

# who when what # ——- ———- ——————————— # apuglisi 2022-02-30 Fixed bug in detecting downsampling # on just one axis # apuglisi 2020-04-15 Added sample option, added exceptions, # allow any kind of sequence for new_shape # 2012-11-20 Created from git://gist.github.com/1348792.git

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.

Returns:

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.

Return type:

ndarray

Raises:
  • 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

Returns:

the shared numpy array. The array is read-write and changes will be immediately visible to other processes.

Return type:

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[]

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.print_header()
>>> 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.

Returns:

the original value converted to unit.

Return type:

astropy Quantity

Raises:

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

Returns:

the value of var (without unit attached) after the unit has been changed to be the same as var_to_match

Return type:

value

Raises:

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

Returns:

list of values after unit conversion and removal, plus the unit. If the first parameter had no unit, the unit is set to 1.

Return type:

list

Raises:

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

Returns:

tuple with the value and the astropy unit of var or 1 if var does not have a unit.

Return type:

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

arte.utils.zernike_projection_on_subaperture module

class arte.utils.zernike_projection_on_subaperture.ZernikeProjectionOnSubaperture(pupilRadiusInMeter, subapsRadiusInMeter, subapOffAxisRadiusInMeter, subapOffAxisAzimuthInDegrees)

Bases: object

N_MODES = 10
compute_zernike_decomposition_on_subap(zernikeCoeffFrom2To11)
get_projection_matrix()

Module contents