Miscellaneous Utilities

We have a whole bunch of miscellaneous helper functions and classes in the galsim.utilities module. Most of these are probably not particularly useful for anything other than internal GalSim code. But we highlight a few things that might be more widely useful beyond GalSim usage.

Decorators

class galsim.utilities.lazy_property(fget)[source]

This decorator will act similarly to @property, but will be efficient for multiple access to values that require some significant calculation.

It works by replacing the attribute with the computed value, so after the first access, the property (an attribute of the class) is superseded by the new attribute of the instance.

Note that is should only be used for non-mutable data, since the calculation will not be repeated if anything about the instance changes.

Usage:

@lazy_property
def slow_function_to_be_used_as_a_property(self):
    x =  ...  # Some slow calculation.
    return x

Base on an answer from http://stackoverflow.com/a/6849299

class galsim.utilities.doc_inherit(mthd)[source]

This decorator will grab a doc string from a base class version of a method. Useful if the subclass doesn’t change anything about the method API, but just has a specialized implementation. This lets the documentation live only in one place.

Usage:

class Base:
    def some_method(self):
        """A nice description of the functionality
        """
        pass

class Sub(Base):

    @doc_inherit
    def some_method(self):
        # Don't bother with any doc string here.
        pass

Based on the Docstring Inheritance Decorator at:

https://github.com/ActiveState/code/wiki/Python_index_1

Although I (MJ) modified it slightly, since the original recipe there had a bug that made it not work properly with 2 levels of sub-classing (e.g. Pixel <- Box <- GSObject).

class galsim.utilities.timer(f)[source]

A decorator that reports how long a function took to run.

In GalSim we decorate all of our tests with this to try to watch for long-running tests.

OpenMP Utilties

galsim.utilities.get_omp_threads()[source]

Get the current number of OpenMP threads to be used in the C++ layer.

Returns:

num_threads

galsim.utilities.set_omp_threads(num_threads, logger=None)[source]

Set the number of OpenMP threads to use in the C++ layer.

Parameters:
  • num_threads – The target number of threads to use (If None or <=0, then try to use the numer of cpus.)

  • logger – If desired, a logger object for logging any warnings here. (default: None)

Returns:

The number of threads OpenMP reports that it will use. Typically this matches the input, but OpenMP reserves the right not to comply with the requested number of threads.

class galsim.utilities.single_threaded(*, num_threads=1)[source]

A context manager that turns off (or down) OpenMP threading e.g. during multiprocessing.

Usage:

with single_threaded():
    # Code where you don't want to use any OpenMP threads in the C++ layer
    # E.g. starting a multiprocessing pool, where you don't want each process
    # to use multiple threads, potentially ending up with n_cpu^2 threads
    # running at once, which would generally be bad for performance.

Note

This is especaily important when your compiler is gcc and you are using the “fork” context in multiprocessing. There is a bug in gcc that can cause an OpenMP parallel block to hang after forking. cf. make it possible to use OMP on both sides of a fork for more discussion about this issue.

It can also be used to set a particular number of threads other than 1, using the optional parameter num_threads, although the original intent of this class is to leave that as 1 (the default).

Parameters:

num_threads – The number of threads you want during the context [default: 1]

LRU Cache

class galsim.utilities.LRU_Cache(user_function, maxsize=1024)[source]

Simplified Least Recently Used Cache.

Mostly stolen from http://code.activestate.com/recipes/577970-simplified-lru-cache/, but added a method for dynamic resizing. The least recently used cached item is overwritten on a cache miss.

Parameters:
  • user_function – A python function to cache.

  • maxsize – Maximum number of inputs to cache. [Default: 1024]

Example:

>>> def slow_function(*args) # A slow-to-evaluate python function
>>>    ...
>>>
>>> v1 = slow_function(*k1)  # Calling function is slow
>>> v1 = slow_function(*k1)  # Calling again with same args is still slow
>>> cache = galsim.utilities.LRU_Cache(slow_function)
>>> v1 = cache(*k1)  # Returns slow_function(*k1), slowly the first time
>>> v1 = cache(*k1)  # Returns slow_function(*k1) again, but fast this time.
resize(maxsize)[source]

Resize the cache.

Increasing the size of the cache is non-destructive, i.e., previously cached inputs remain in the cache. Decreasing the size of the cache will necessarily remove items from the cache if the cache is already filled. Items are removed in least recently used order.

Parameters:

maxsize – The new maximum number of inputs to cache.

Context Manager for writing AtmosphericScreen pickles

galsim.utilities.pickle_shared()[source]

A context manager to flag that one wishes to include object state from shared memory in pickle objects.

Example:

obj = galsim_obj_with_shared_state()  # e.g., galsim.phase_screens.AtmosphericScreen
pickle.dump(obj, file)

# restart python, unloading shared state
obj = pickle.load(file)  # fails due to missing shared state.

obj = galsim_obj_with_shared_state()
with pickle_shared():
    pickle.dump(obj, filename)

# restart python, again unloading shared state
obj = pickle.load(file)  # loads both obj and required shared state.

Other Possibly Useful Classes

class galsim.utilities.WeakMethod(f)[source]

Wrap a method in a weakref.

This is useful if you want to specialize a function if certain conditions hold. You can check those conditions and return one of several possible implementations as a lazy_property.

Using just a normal weakref doesn’t work, but this class will work.

From http://code.activestate.com/recipes/81253-weakmethod/

class galsim.utilities.OrderedWeakRef[source]

Assign an arbitrary ordering to weakref.ref so that it can be part of a heap.

class galsim.utilities.SimpleGenerator(obj)[source]

A simple class that is constructed with an arbitrary object. Then generator() will return that object.

This is useful as a way to use an already existing object in a multiprocessing Proxy, since that normally needs a factory function. So this is a factory function that just returns an already existing object.

Math Calculations

galsim.utilities.horner(x, coef, dtype=None)[source]

Evaluate univariate polynomial using Horner’s method.

I.e., take A + Bx + Cx^2 + Dx^3 and evaluate it as A + x(B + x(C + x(D)))

Parameters:
  • x – A numpy array of values at which to evaluate the polynomial.

  • coef – Polynomial coefficients of increasing powers of x.

  • dtype – Optionally specify the dtype of the return array. [default: None]

Returns:

a numpy array of the evaluated polynomial. Will be the same shape as x.

galsim.utilities._horner(x, coef, result)[source]

Equivalent to horner, but x, coef, and result must be contiguous arrays.

In particular, result must be already allocated as an array in which to put the answer. This is the thing that is returned from the regular horner.

Parameters:
  • x – A numpy array of values at which to evaluate the polynomial.

  • coef – Polynomial coefficients of increasing powers of x.

  • result – Numpy array into which to write the result. Must be same shape as x.

galsim.utilities.horner2d(x, y, coefs, dtype=None, triangle=False)[source]

Evaluate bivariate polynomial using nested Horner’s method.

Parameters:
  • x – A numpy array of the x values at which to evaluate the polynomial.

  • y – A numpy array of the y values at which to evaluate the polynomial.

  • coefs – 2D array-like of coefficients in increasing powers of x and y. The first axis corresponds to increasing the power of y, and the second to increasing the power of x.

  • dtype – Optionally specify the dtype of the return array. [default: None]

  • triangle – If True, then the coefs are only non-zero in the upper-left triangle of the array. [default: False]

Returns:

a numpy array of the evaluated polynomial. Will be the same shape as x and y.

galsim.utilities._horner2d(x, y, coefs, result, temp, triangle=False)[source]

Equivalent to horner2d, but x, y, coefs, result, and temp must be contiguous arrays.

In particular, result must be already allocated as an array in which to put the answer. This is the thing that is returned from the regular horner. In addition, temp must be allocated for the function to use as temporary work space.

Parameters:
  • x – A numpy array of the x values at which to evaluate the polynomial.

  • y – A numpy array of the y values at which to evaluate the polynomial.

  • coefs – 2D array-like of coefficients in increasing powers of x and y. The first axis corresponds to increasing the power of y, and the second to increasing the power of x.

  • result – Numpy array into which to write the result. Must be same shape as x.

  • temp – Numpy array to hold temporary results. Must be the same shape as x.

  • triangle – If True, then the coefs are only non-zero in the upper-left triangle of the array. [default: False]

galsim.utilities.binomial(a, b, n)[source]

Return xy coefficients of (ax + by)^n ordered by descending powers of a.

Example:

# (x + y)^3 = 1 x^3 + 3 x^2 y + 3 x y^2 + 1 y^3
>>>  print(binomial(1, 1, 3))
array([ 1.,  3.,  3.,  1.])


# (2 x + y)^3 = 8 x^3 + 12 x^2 y + 6 x y^2 + 1 y^3
>>>  print(binomial(2, 1, 3))
array([ 8.,  12.,  6.,  1.])
Parameters:
  • a – First scalar in binomial to be expanded.

  • b – Second scalar in binomial to be expanded.

  • n – Exponent of expansion.

Returns:

Array of coefficients in expansion.

galsim.utilities.nCr(n, r)[source]

Combinations. I.e., the number of ways to choose r distiguishable things from n distinguishable things.

Parameters:
  • from. (n The number of options to choose) –

  • choose (r The number of items to) –

Returns:

nCr, the (n,r) binomial coefficient.

Note

In Python 3, the factorial function was improved such that doing this the direct way of calculating n! / (r! (n-r)!) seems to be the fastest algorith. In Python 2, for largish values of n, a more complicated algorithm that avoided large integers was faster. This function uses the direct method for both – we don’t bother to check the version of Python to potentially select a different algorithm in the two cases.

galsim.utilities.rotate_xy(x, y, theta)[source]

Rotates points in the xy-Cartesian plane counter-clockwise through an angle theta about the origin of the Cartesian coordinate system.

Parameters:
  • x – NumPy array of input x coordinates

  • y – NumPy array of input y coordinates

  • theta – Rotation angle (+ve counter clockwise) as an Angle instance

Returns:

the rotated coordinates (x_rot,y_rot).

galsim.utilities.g1g2_to_e1e2(g1, g2)[source]

Convenience function for going from (g1, g2) -> (e1, e2).

Here g1 and g2 are reduced shears, and e1 and e2 are distortions - see Shear for definitions of reduced shear and distortion in terms of axis ratios or other ways of specifying ellipses.

Parameters:
  • g1 – First reduced shear component

  • g2 – Second reduced shear component

Returns:

the corresponding distortions, e1 and e2.

Test Suite Helper Functions and Contexts

galsim.utilities.check_pickle(obj, func=<function <lambda>>, irreprable=False, random=None)[source]

Check that the object is picklable.

Also check some related desirable properties that we want for (almost) all galsim objects:

  1. pickle.loads(pickle.dumps(obj)) recovers something equivalent to the original.

  2. obj != object() and object() != obj. (I.e. it doesn’t == things it shouldn’t.)

  3. hash(obj) is the same for two equivalent objects, if it is hashable.

  4. copy.copy(obj) returns an equivalent copy unless random=True.

  5. copy.deepcopy(obj) returns an equivalent copy.

  6. eval(repr(obj)) returns an equivalent copy unless random or irreprable=True.

  7. repr(obj) makes something if irreprable=False.

Parameters:
  • obj – The object to test

  • func – A function of obj to use to test for equivalence. [default: lambda x: x]

  • irreprable – Whether to skip the eval(repr(obj)) test. [default: False]

  • random – Whether the obj has some intrinsic randomness. [default: False, unless it has an rng attribute or it is a galsim.BaseDeviate]

galsim.utilities.check_all_diff(objs, check_hash=True)[source]

Test that all objects test as being unequal.

It checks all pairs of objects in the list and asserts that obj1 != obj2.

If check_hash=True, then it also checks that their hashes are different.

Parameters:
  • objs – A list of objects to test.

  • check_hash – Whether to also check the hash values.

class galsim.utilities.CaptureLog(level=3)[source]

A context manager that saves logging output into a string that is accessible for checking in unit tests.

After exiting the context, the attribute output will have the logging output.

Sample usage:

>>> with CaptureLog() as cl:
...     cl.logger.info('Do some stuff')
>>> assert cl.output == 'Do some stuff'
class galsim.utilities.Profile(sortby='tottime', nlines=30, reverse=False, filename=None)[source]

A context manager that profiles a snippet of code.

Sample usage:

>>> with Profile():
...     slow_function()
Parameters:
  • sortby – What parameter to sort the results by. [default: tottime]

  • nlines – How many lines of output to report. [default: 30]

  • reverse – Whether to reverse the order of the output lines to put the most important items at the bottom rather than the top. [default: False]

  • filename – If desired, a file to output the full profile information in pstats format. [default: None]

Other Helper Functions

galsim.utilities.isinteger(value)[source]

Check if a value is an integer type (including np.int64, long, etc.)

Specifically, it checks whether value == int(value).

Parameter:

value: The value to be checked whether it is an integer

Returns:

True if the value is an integer type, False otherwise.

galsim.utilities.listify(arg)[source]

Turn argument into a list if not already iterable.

Parameters:

arg – An argument that may be a lit or a single item

Returns:

[arg] if arg was not already a list, otherwise arg.

galsim.utilities.dol_to_lod(dol, N=None, scalar_string=True)[source]

Generate list of dicts from dict of lists (with broadcasting). Specifically, generate “scalar-valued” kwargs dictionaries from a kwarg dictionary with values that are length-N lists, or possibly length-1 lists or scalars that should be broadcasted up to length-N lists.

Parameters:
  • dol – A dict of lists

  • N – The length of the lists if known in advance. [default: None, which will determine the maximum length of the lists for you]

  • scalar_string – Whether strings in the input list should be treated as scalars (and thus broadcast to each item in the output) or not (in which case, they will be treated as lists of characters) [default: True]

Returns:

A list of dicts

galsim.utilities.functionize(f)[source]

Decorate a function f which accepts scalar positional or keyword arguments, to accept arguments that can be either scalars or _functions_. If the arguments include univariate (N-variate) functions, then the output will be a univariate (N-variate) function. While it’s okay to mix scalar and N-variate function arguments, it is an error to mix N-variate and M-variate function arguments.

Example:

>>> def f(x, y):      # Function of two scalars.
...     return x + y
>>> decorated = functionize(f)   # Function of two scalars, functions, or a mix.
>>> result = f(2, 3)  # 5
>>> result = f(2, lambda u: u)  # Generates a TypeError
>>> result = decorated(2, 3)  # Scalar args returns a scalar
>>> result = decorated(2, lambda u: u)  # Univariate argument leads to a univariate output.
>>> print(result(5))  # 7
>>> result = decorated(2, lambda u,v: u*v)  # Bivariate argument leads to a bivariate output.
>>> print(result(5, 7))  # 2 + (5*7) = 37

We can use arguments that accept keyword arguments too:

>>> def f2(u, v=None):
...    if v is None:
...        v = 6.0
...    return u / v
>>> result = decorated(2, f2)
>>> print(result(12))  # 2 + (12./6) = 4.0
>>> print(result(12, v=4))  # 2 + (12/4) = 5

Note that you can also use python’s decorator syntax:

>>> @functionize
>>> def f(x, y):
...     return x + y
Parameters:

f – The function to be decorated.

Returns:

The decorated function.

galsim.utilities.ensure_dir(target)[source]

Make sure the directory for the target location exists, watching for a race condition

In particular check if the OS reported that the directory already exists when running makedirs, which can happen if another process creates it before this one can

Parameter:

target: The file name for which to ensure that all necessary directories exist.

GalSim-specific Helper Functions

galsim.utilities.interleaveImages(im_list, N, offsets, add_flux=True, suppress_warnings=False, catch_offset_errors=True)[source]

Interleaves the pixel values from two or more images and into a single larger image.

This routine converts a list of images taken at a series of (uniform) dither offsets into a single higher resolution image, where the value in each final pixel is the observed pixel value from exactly one of the original images. It can be used to build a Nyquist-sampled image from a set of images that were observed with pixels larger than the Nyquist scale.

In the original observed images, the integration of the surface brightness over the pixels is equivalent to convolution by the pixel profile and then sampling at the centers of the pixels. This procedure simulates an observation sampled at a higher resolution than the original images, while retaining the original pixel convolution.

Such an image can be obtained in a fairly simple manner in simulations of surface brightness profiles by convolving them explicitly with the native pixel response and setting a lower sampling scale (or higher sampling rate) using the pixel_scale argument in GSObject.drawImage routine and setting the method parameter to ‘no_pixel’.

However, pixel level detector effects can be included only on images drawn at the native pixel scale, which happen to be undersampled in most cases. Nyquist-sampled images that also include the effects of detector non-idealities can be obtained by drawing multiple undersampled images (with the detector effects included) that are offset from each other by a fraction of a pixel.

This is similar to other procedures that build a higher resolution image from a set of low resolution images, such as MultiDrizzle and IMCOM. A disadvantage of this routine compared to ther others is that the images must be offset in equal steps in each direction. This is difficult to acheive with real observations but can be precisely acheived in a series of simulated images.

An advantage of this procedure is that the noise in the final image is not correlated as the pixel values are each taken from just a single input image. Thus, this routine preserves the noise properties of the pixels.

Here’s an example script using this routine:

Example:

>>> n = 2
>>> gal = galsim.Gaussian(sigma=2.8)
>>> DX = numpy.arange(0.0,1.0,1./n)
>>> DX -= DX.mean()
>>> im_list, offsets = [], []
>>> for dx in DX:
    ... offset = galsim.PositionD(dx,0.0)
    ... offsets.append(offset)
    ... im = galsim.Image(16,16)
    ... gal.drawImage(image=im,offset=offset,scale=1.0)
    ... im.applyNonlinearity(lambda x: x - 0.01*x**2) # detector effects
    ... im_list.append(im)
>>> img = galsim.utilities.interleaveImages(im_list=im_list,N=(n,1),offsets=offsets)
Parameters:
  • im_list – A list containing the galsim.Image instances to be interleaved.

  • N – Number of images to interleave in either directions. It can be of type int if equal number of images are interleaved in both directions or a list or tuple of two integers, containing the number of images in x and y directions respectively.

  • offsets – A list containing the offsets as galsim.PositionD instances corresponding to every image in im_list. The offsets must be spaced equally and must span an entire pixel area. The offset values must be symmetric around zero, hence taking positive and negative values, with upper and lower limits of +0.5 and -0.5 (limit values excluded).

  • add_flux – Should the routine add the fluxes of all the images (True) or average them (False)? [default: True]

  • suppress_warnings – Suppresses the warnings about the pixel scale of the output, if True. [default: False]

  • catch_offset_errors – Checks for the consistency of offsets with N and raises errors if inconsistencies found (True). Recommended, but could slow down the routine a little. [default: True]

Returns:

the interleaved Image

galsim.utilities.deInterleaveImage(image, N, conserve_flux=False, suppress_warnings=False)[source]

The routine to do the opposite of what interleaveImages routine does. It generates a (uniform) dither sequence of low resolution images from a high resolution image.

Many pixel level detector effects, such as interpixel capacitance, persistence, charge diffusion etc. can be included only on images drawn at the native pixel scale, which happen to be undersampled in most cases. Nyquist-sampled images that also include the effects of detector non-idealities can be obtained by drawing multiple undersampled images (with the detector effects included) that are offset from each other by a fraction of a pixel. If the offsets are uniformly spaced, then images can be combined using interleaveImages into a Nyquist-sampled image.

Drawing multiple low resolution images of a light profile can be a lot slower than drawing a high resolution image of the same profile, even if the total number of pixels is the same. A uniformly offset dither sequence can be extracted from a well-resolved image that is drawn by convolving the surface brightness profile explicitly with the native pixel response and setting a lower sampling scale (or higher sampling rate) using the pixel_scale argument in GSObject.drawImage routine and setting the method parameter to ‘no_pixel’.

Here is an example script using this routine:

Example:

>>> n = 2
>>> gal = galsim.Gaussian(sigma=2.8)
>>> gal_pix = galsim.Convolve([gal,galsim.Pixel(scale=1.0)])
>>> img = gal_pix.drawImage(gal_pix,scale=1.0/n,method='no_pixel')
>>> im_list, offsets = galsim.utilities.deInterleaveImage(img,N=n)
>>> for im in im_list:
>>>     im.applyNonlinearity(lambda x: x-0.01*x**2) #detector effects
>>> img_new = galsim.utilities.interleaveImages(im_list,N=n,offsets)
Parameters:
  • image – Input image from which lower resolution images are extracted.

  • N – Number of images extracted in either directions. It can be of type ‘int’ if equal number of images are extracted in both directions or a list or tuple of two integers, containing the number of images in x and y directions respectively.

  • conserve_flux – Should the routine output images that have, on average, same total pixel values as the input image (True) or should the pixel values summed over all the images equal the sum of pixel values of the input image (False)? [default: False]

  • suppress_warnings – Suppresses the warnings about the pixel scale of the output, if True. [default: False]

Returns:

a list of images (Image) and offsets (PositionD) to reconstruct the input image using interleaveImages.

galsim.utilities.thin_tabulated_values(x, f, rel_err=0.0001, trim_zeros=True, preserve_range=True, fast_search=True, interpolant='linear')[source]

Remove items from a set of tabulated f(x) values so that the error in the integral is still accurate to a given relative accuracy.

The input x and f values can be lists, NumPy arrays, or really anything that can be converted to a NumPy array. The new lists will be output as numpy arrays.

Parameters:
  • x – The x values in the f(x) tabulation.

  • f – The f values in the f(x) tabulation.

  • rel_err – The maximum relative error to allow in the integral from the removal. [default: 1.e-4]

  • trim_zeros – Remove redundant leading and trailing points where f=0? (The last leading point with f=0 and the first trailing point with f=0 will be retained). Note that if both trim_leading_zeros and preserve_range are True, then the only the range of x after zero trimming is preserved. [default: True]

  • preserve_range – Should the original range of x be preserved? (True) Or should the ends be trimmed to include only the region where the integral is significant? (False) [default: True]

  • fast_search – If set to True, then the underlying algorithm will use a relatively fast O(N) algorithm to select points to include in the thinned approximation. If set to False, then a slower O(N^2) algorithm will be used. We have found that the slower algorithm tends to yield a thinned representation that retains fewer samples while still meeting the relative error requirement. [default: True]

  • interpolant – The interpolant to assume for the tabulated values. [default: ‘linear’]

Returns:

a tuple of lists (x_new, y_new) with the thinned tabulation.

galsim.utilities.old_thin_tabulated_values(x, f, rel_err=0.0001, preserve_range=False)[source]

Remove items from a set of tabulated f(x) values so that the error in the integral is still accurate to a given relative accuracy.

The input x and f values can be lists, NumPy arrays, or really anything that can be converted to a NumPy array. The new lists will be output as python lists.

Note

In Issue #739, Josh wrote thin_tabulated_values as a replacement for this function, which had been buggy – not actually hitting its target relative accuracy. So on the same issue, Mike fixed this algorithm to at least work correctly.

However, we recommend using the above algorithm, since it keeps fewer sample locations for a given rel_err than the old algorithm.

On the other hand, the old algorithm (this one) may be quite a bit faster, so we retain it here in case there is a use case where it is more appropriate.

Parameters:
  • x – The x values in the f(x) tabulation.

  • f – The f values in the f(x) tabulation.

  • rel_err – The maximum relative error to allow in the integral from the removal. [default: 1.e-4]

  • preserve_range – Should the original range of x be preserved? (True) Or should the ends be trimmed to include only the region where the integral is significant? (False) [default: False]

Returns:

a tuple of lists (x_new, y_new) with the thinned tabulation.

galsim.utilities.parse_pos_args(args, kwargs, name1, name2, integer=False, others=[])[source]

Parse the args and kwargs of a function call to be some kind of position.

We allow four options:

f(x,y) f(galsim.PositionD(x,y)) or f(galsim.PositionI(x,y)) f( (x,y) ) (or any indexable thing) f(name1=x, name2=y)

If the inputs must be integers, set integer=True. If there are other args/kwargs to parse after these, then their names should be be given as the parameter others, which are passed back in a tuple after the position.

Parameters:
  • args – The args of the original function.

  • kwargs – The kwargs of the original function.

  • name1 – The allowed kwarg for the first coordinate.

  • name2 – The allowed kwarg for the second coordinate.

  • integer – Whether to return a PositionI rather than a PositionD. [default: False]

  • others – If given, other values to also parse and return from the kwargs. [default: []]

Returns:

a Position instance, possibly also with other values if others is given.

galsim.utilities.rand_arr(shape, deviate)[source]

Function to make a 2d array of random deviates (of any sort).

Parameters:
  • shape – A list of length 2, indicating the desired 2d array dimensions

  • deviate – Any GalSim deviate (see random.py) such as UniformDeviate, GaussianDeviate, etc. to be used to generate random numbers

Returns:

a NumPy array of the desired dimensions with random numbers generated using the supplied deviate.

galsim.utilities.convert_interpolant(interpolant)[source]

Convert a given interpolant to an Interpolant if it is given as a string.

Parameter:

interpolant: Either an Interpolant or a string to convert.

Returns:

an Interpolant

galsim.utilities.structure_function(image)[source]

Estimate the angularly-averaged structure function of a 2D random field.

The angularly-averaged structure function D(r) of the 2D field phi is defined as:

\[D(|r|) = \langle |phi(x) - phi(x+r)|^2 \rangle\]

where the x and r on the RHS are 2D vectors, but the \(|r|\) on the LHS is just a scalar length.

The image must have its scale attribute defined. It will be used in the calculations to set the scale of the radial distances.

Parameters:

imageImage containing random field realization.

Returns:

A python callable mapping a separation length r to the estimate of the structure function D(r).

galsim.utilities.combine_wave_list(*args)[source]

Combine wave_list attributes of all objects in obj_list while respecting blue_limit and red_limit attributes. Should work with any combination of SED, Bandpass, and ChromaticObject instances.

Parameters:

obj_list – List of SED, Bandpass, or ChromaticObject instances.

Returns:

wave_list, blue_limit, red_limit

galsim.utilities.math_eval(str, other_modules=())[source]

Evaluate a string that may include numpy, np, or math commands.

Parameters:
  • str – The string to evaluate

  • numpy (other_modules. Other modules in addition to) – Should be given as a list of strings. [default: None]

  • np – Should be given as a list of strings. [default: None]

  • well. (math to import as) – Should be given as a list of strings. [default: None]

Returns:

Whatever the string evaluates to.

galsim.utilities.unweighted_moments(image, origin=None)[source]

Computes unweighted 0th, 1st, and 2nd moments in image coordinates. Respects image bounds, but ignores any scale or wcs.

Parameters:
  • imageImage from which to compute moments

  • origin – Optional origin in image coordinates used to compute Mx and My [default: galsim.PositionD(0, 0)].

Returns:

Dict with entries for [M0, Mx, My, Mxx, Myy, Mxy]

galsim.utilities.unweighted_shape(arg)[source]

Computes unweighted second moment size and ellipticity given either an image or a dict of unweighted moments.

The size is:

rsqr = Mxx+Myy

The ellipticities are:

e1 = (Mxx-Myy) / rsqr e2 = 2*Mxy / rsqr

Parameters:

arg – Either a galsim.Image or the output of unweighted_moments(image).

Returns:

Dict with entries for [rsqr, e1, e2]

galsim.utilities.rand_with_replacement(n, n_choices, rng, weight=None, _n_rng_calls=False)[source]

Select some number of random choices from a list, with replacement, using a supplied RNG.

n random choices with replacement are made assuming that those choices should range from 0 to n_choices-1, so they can be used as indices in a list/array. If weight is supplied, then it should be an array of length n_choices that ranges from 0-1, and can be used to make weighted choices from the list.

Parameters:
  • n – Number of random selections to make.

  • n_choices – Number of entries from which to choose.

  • rng – RNG to use. Must a galsim.BaseDeviate instance.

  • weight – Optional list of weight factors to use for weighting the selection of random indices.

Returns:

a NumPy array of length n containing the integer-valued indices that were selected.

galsim.utilities.check_share_file(filename, subdir)[source]

Find SED or Bandpass file, possibly adding share_dir/subdir.

Parameters:
Returns:

True, correct_filename if the file was found False, ‘’ if not

galsim.utilities.find_out_of_bounds_position(x, y, bounds, grid=False)[source]

Given arrays of x and y values that are known to contain at least one position that is out-of-bounds of the given bounds instance, return one such PositionD.

Parameters:
  • x – Array of x values

  • y – Array of y values

  • boundsBounds instance

  • grid – Bool indicating whether to check the outer product of x and y (grid=True), or each sequential pair of x and y (grid=False). If the latter, then x and y should have the same shape.

Returns:

a PositionD from x and y that is out-of-bounds of bounds.