Resample

class stcal.resample.Resample(output_wcs, n_input_models=None, pixfrac=1.0, kernel='square', fillval=0.0, weight_type='ivm', good_bits=0, enable_ctx=True, enable_var=True, compute_err=None, propagate_dq=False, pixmap_stepsize=1, pixmap_order=1)[source]

Bases: object

Base class for resampling images.

The main purpose of this class is to resample and add input images (data, variance array) to an output image defined by an output WCS.

In particular, this class performs the following operations:

  1. Sets up output arrays based on arguments used at initialization.

  2. Based on information about the input images and user arguments, computes scale factors needed to convert resampled counts to fluxes.

  3. For each input image, computes coordinate transformations (pixmap) from the coordinate system of the input image to the coordinate system of the output image.

  4. Computes the weight image for each input image.

  5. Calls Drizzle methods to resample and combine input images and their variance/error arrays.

  6. Keeps track of total exposure time and other time-related quantities.

Initialize Resample.

Parameters:
  • output_wcs (dict) – Specifies output WCS as a dictionary with keys 'wcs' (WCS object) and 'pixel_scale' (pixel scale in arcseconds). 'pixel_scale', when provided, will be used for computation of drizzle scaling factor. When it is not provided, output pixel scale will be estimated from the provided WCS object.

  • n_input_models (int, None, optional) – Number of input models expected to be resampled. When provided, this is used to estimate memory requirements and optimize memory allocation for the context array.

  • pixfrac (float, optional) – The fraction of a pixel that the pixel flux is confined to. The default value of 1 has the pixel flux evenly spread across the image. A value of 0.5 confines it to half a pixel in the linear dimension, so the flux is confined to a quarter of the pixel area when the square kernel is used.

  • kernel (str, optional) –

    The name of the kernel used to combine the input: “square”, “gaussian”, “point”, “turbo”, “lanczos2”, or “lanczos3”. The choice of kernel controls the distribution of flux over the kernel. The square kernel is the default.

    Warning

    The “gaussian” and “lanczos2/3” kernels DO NOT conserve flux.

  • fillval (float, None, str, optional) – The value of output pixels that did not have contributions from input images’ pixels. When fillval is either None or "INDEF" and out_img is provided, the values of out_img will not be modified. When fillval is either None or "INDEF" and out_img is not provided, the values of out_img will be initialized to numpy.nan. If fillval is a string that can be converted to a number, then the output pixels with no contributions from input images will be set to this fillval value.

  • weight_type (str, optional) – The weighting type (“ivm”, “exptime”, or “ivm-sky”) for adding models’ data. For weight_type="ivm" (the default), the weighting will be determined per-pixel using the inverse of the read noise (VAR_RNOISE) array stored in each input image. If the VAR_RNOISE array does not exist, the variance is set to 1 for all pixels (i.e., equal weighting). If weight_type="ivm-sky", the weighting will be determined per-pixel using the inverse of the sky variance (VAR_SKY) array stored in each input image. If the VAR_SKY array does not exist, the variance is set to 0 for all pixels (i.e., equal weighting). If weight_type="exptime", the weight will be set equal to the measurement time when available and to the exposure time otherwise.

  • good_bits (int, str, None, optional) –

    An integer bit mask, None, a Python list of bit flags, a comma-, or '|'-separated, '+'-separated string list of integer bit flags or mnemonic flag names that indicate what bits in models’ DQ bitfield array should be ignored (i.e., zeroed).

    When co-adding models using add_model(), any pixels with a non-zero DQ values are assigned a weight of zero and therefore they do not contribute to the output (resampled) data. good_bits provides a mean to ignore some of the DQ bitflags.

    When good_bits is an integer, it must be the sum of all the DQ bit values from the input model’s DQ array that should be considered “good” (or ignored). For example, if pixels in the DQ array can be combinations of 1, 2, 4, and 8 flags and one wants to consider DQ “defects” having flags 2 and 4 as being acceptable, then good_bits should be set to 2+4=6. Then a pixel with DQ values 2,4, or 6 will be considered a good pixel, while a pixel with DQ value, e.g., 1+2=3, 4+8=12, etc. will be flagged as a “bad” pixel.

    Alternatively, when good_bits is a string, it can be a comma-separated or ‘+’ separated list of integer bit flags that should be summed to obtain the final “good” bits. For example, both “4,8” and “4+8” are equivalent to integer good_bits=12.

    Finally, instead of integers, good_bits can be a string of comma-separated mnemonics. For example, for JWST, all the following specifications are equivalent:

    ”12” == “4+8” == “4, 8” == “JUMP_DET, DROPOUT”

    In order to “translate” mnemonic code to integer bit flags, Resample.dq_flag_name_map attribute must be set to either a dictionary (with keys being mnemonc codes and the values being integer flags) or a ~astropy.nddata.BitFlagNameMap.

    In order to reverse the meaning of the flags from indicating values of the “good” DQ flags to indicating the “bad” DQ flags, prepend ‘~’ to the string value. For example, in order to exclude pixels with DQ flags 4 and 8 for computations and to consider as “good” all other pixels (regardless of their DQ flag), use a value of ~4+8, or ~4,8. A string value of ~0 would be equivalent to a setting of None.

    Default value (0) will make all pixels with non-zero DQ values be considered “bad” pixels, and the corresponding data pixels will be assigned zero weight and thus these pixels will not contribute to the output resampled data array.

    Set good_bits to None to turn off the use of model’s DQ array.

    For more details, see documentation for astropy.nddata.bitmask.extend_bit_flag_map.

  • enable_ctx (bool, optional) – Indicates whether to create a context image. If disable_ctx is set to True, parameters out_ctx, begin_ctx_id, and max_ctx_id will be ignored.

  • enable_var (bool, optional) – Indicates whether to resample variance arrays.

  • compute_err (str or None, optional) –

    Options are “from_var” or “driz_err”:

    • "from_var": compute output model’s error array from all (Poisson, flat, readout) resampled variance arrays. Setting compute_err to "from_var" will assume enable_var was set to True regardless of actual value of the parameter enable_var.

    • "driz_err": compute output model’s error array by drizzling together all input models’ error arrays.

    Error array will be assigned to 'err' key of the output model.

    Note

    At this time, output error array is not equivalent to error propagation results.

  • propagate_dq (bool, optional) – Indicates whether to propagate DQ flags from input models to the output model. DQ flags are propagated by bitwise OR of all input DQ flags that contribute to a given output pixel. If True, output model will have a DQ array with the same shape as the output data array. If False, output model will not have a DQ array.

  • pixmap_stepsize (int, optional) – If pixmap_stepsize>1, when computing pixel map used for resampling, perform the full WCS calculation on a sparser grid and use interpolation to fill in the rest of the pixels. This option speeds up pixel map computation by reducing the number of WCS calls, though at the cost of reduced pixel map accuracy. The loss of accuracy is typically negligible if the underlying distortion correction is smooth, but if the distortion is non-smooth, pixmap_stepsize>1 is not recommended. Large pixmap_stepsize values are automatically reduced to no more than 1/10 of image size. Default 1.

  • pixmap_order (int, optional) – Order of the 2D spline to interpolate the sparse pixel mapping if pixmap_stepsize>1. Supported values are: 1 (bilinear) or 3 (bicubic). This parameter is ignored when pixmap_stepsize <= 1. Default 1.

Attributes Summary

compute_err

Indicates whether error array is computed and how it is computed.

dq_flag_name_map

enable_ctx

Indicates whether context array is enabled.

enable_var

Indicates whether variance arrays are resampled.

error_from_variances

group_ids

List of all group IDs of models resampled and added to the output model.

output_array_shape

Shape of the output model arrays.

output_array_types

output_model

Output (resampled) model.

output_pixel_scale

Get pixel scale of the output model in arcsec.

output_wcs

WCS of the output (resampled) model.

pixel_scale_ratio

Get the ratio of the output pixel scale to the input pixel scale.

propagate_dq

Indicates whether DQ flags are propagated and output model has DQ array.

variance_array_names

Methods Summary

add_model(model)

Resample a model.

add_model_hook(model, pixmap, ...)

Perform additional processing while resampling.

check_output_wcs(output_wcs[, ...])

Check output WCS.

create_output_model()

Create a new "output model": a dictionary of data and meta fields.

finalize()

Finalize computations.

finalize_resample_variance(output_model)

Finalize variance calculations.

finalize_time_info()

Perform final computations for the total time and update relevant fields of the output model.

get_input_model_pixel_area(model[, prefer_mean])

Compute input pixel area.

get_output_model_pixel_area(model)

Compute output pixel area.

init_time_counters()

Initialize variables/arrays needed to process exposure time.

init_variance_arrays()

Allocate arrays that hold co-added resampled variances and their weights.

is_finalized()

Check if output_model has been finalized.

resample_variance_arrays(model, pixmap, ...)

Resample variance arrays.

reset_arrays([n_input_models])

Reset intermediate arrays.

update_time(model)

Update time calculations.

validate_input_model(model)

Validate input model.

Attributes Documentation

compute_err

Indicates whether error array is computed and how it is computed.

dq_flag_name_map = None
enable_ctx

Indicates whether context array is enabled.

enable_var

Indicates whether variance arrays are resampled.

error_from_variances = None
group_ids

List of all group IDs of models resampled and added to the output model.

output_array_shape

Shape of the output model arrays.

output_array_types: defaultdict[str, DTypeLike] = {'con': <class 'numpy.int32'>, 'data': <class 'numpy.float32'>, 'err': <class 'numpy.float32'>, 'var_flat': <class 'numpy.float32'>, 'var_poisson': <class 'numpy.float32'>, 'var_rnoise': <class 'numpy.float32'>, 'wht': <class 'numpy.float32'>}
output_model

Output (resampled) model.

output_pixel_scale

Get pixel scale of the output model in arcsec.

output_wcs

WCS of the output (resampled) model.

pixel_scale_ratio

Get the ratio of the output pixel scale to the input pixel scale.

propagate_dq

Indicates whether DQ flags are propagated and output model has DQ array.

variance_array_names = ['var_rnoise', 'var_flat', 'var_poisson']

Methods Documentation

add_model(model)[source]

Resample a model.

Resamples model image, variance data (if enable_var is True) , and error data (if enable_err is True), and adds them to the corresponding arrays of the output model using appropriate weighting. It also updates the weight array and context array (if enable_ctx is True) of the resampled data, as well as relevant metadata.

Whenever model has a unique group ID that was never processed before, the “pointings” value of the output model is incremented and the “group_id” attribute is updated. Also, time counters are updated with new values from the input model by calling update_time() .

Parameters:

model (dict) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines.

add_model_hook(model, pixmap, pixel_scale_ratio, iscale, weight_map, xmin, xmax, ymin, ymax)[source]

Perform additional processing while resampling.

A hook method called by the add_model() method. It allows subclasses perform additional processing at the time the model["data"] array is resampled.

This method is called immediately after model["data"] is resampled.

Parameters:
  • model (dict) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines.

  • pixmap (np.ndarray) – A mapping (3D array) from input image (data) coordinates to resampled (out_img) coordinates. pixmap must be an array of shape (Ny, Nx, 2) where (Ny, Nx) is the shape of the input image. pixmap[..., 0] forms a 2D array of X-coordinates of input pixels in the output frame and pixmap[..., 1] forms a 2D array of Y-coordinates of input pixels in the output coordinate frame.

  • pixel_scale_ratio (float) – Pixel scale ratio defined as the ratio of the output pixel scale to the first input model’s pixel scale computed from model WCS at the fiducial point (taken as the ref_ra and ref_dec from the wcsinfo meta attribute of the first input image).

  • iscale (float) – The scale to apply to the input variance data before drizzling.

  • weight_map (numpy.ndarray, None, optional) –

    A 2D numpy array containing the pixel by pixel weighting. Must have the same dimensions as data.

    When weight_map is None, the weight of input data pixels will be assumed to be 1.

  • xmin (float, optional) – This and the following three parameters set a bounding rectangle on the input image. Only pixels on the input image inside this rectangle will have their flux added to the output image. Xmin sets the minimum value of the x dimension. The x dimension is the dimension that varies quickest on the image. If the value is zero, no minimum will be set in the x dimension. All four parameters are zero based, counting starts at zero.

  • xmax (float, optional) – Sets the maximum value of the x dimension on the bounding box of the input image. If the value is zero, no maximum will be set in the x dimension, the full x dimension of the output image is the bounding box.

  • ymin (float, optional) – Sets the minimum value in the y dimension on the bounding box. The y dimension varies less rapidly than the x and represents the line index on the input image. If the value is zero, no minimum will be set in the y dimension.

  • ymax (float, optional) – Sets the maximum value in the y dimension. If the value is zero, no maximum will be set in the y dimension, the full x dimension of the output image is the bounding box.

check_output_wcs(output_wcs, estimate_output_shape=True)[source]

Check output WCS.

Check that provided WCS has expected properties and that its array_shape property is defined. May modify output_wcs.

Parameters:
  • output_wcs (gwcs.wcs.WCS) – A WCS object corresponding to the output (resampled) image.

  • estimate_output_shape (bool, optional) – Indicates whether to estimate output image shape of the output_wcs from other available attributes such as bounding_box when output_wcs.array_shape is None. If estimate_output_shape is True and output_wcs.array_shape is None, upon return output_wcs.array_shape will be assigned an estimated value.

create_output_model()[source]

Create a new “output model”: a dictionary of data and meta fields.

Returns:

output_model – A dictionary of data model attributes and values.

Return type:

dict

finalize()[source]

Finalize computations.

Performs final computations from any intermediate values, sets output model values, and optionally frees temporary/intermediate objects.

finalize calls finalize_resample_variance() and finalize_time_info().

Warning

Once the resample process has been finalized, adding new models to the output resampled model is not allowed.

finalize_resample_variance(output_model)[source]

Finalize variance calculations.

Compute variance for the resampled image from running sums and weights. Free memory that holds these running sums and weights arrays.

output_modeldict, None

A dictionary containing data arrays and other attributes that will be used to add new models to. When accumulate is False, only the WCS object of the model will be used. When accumulate is True, new models will be added to the existing data in the output_model.

finalize_time_info()[source]

Perform final computations for the total time and update relevant fields of the output model.

get_input_model_pixel_area(model, prefer_mean=True)[source]

Compute input pixel area.

Computes or retrieves pixel area of an input model. By default, this is the average pixel area of the input model’s pixels within either the bounding box (if available) or the entire data array. Alternatively, this is the “nominal” pixel area as provided by the "pixelarea_steradians" keyword of the input model.

Subclasses can override this method to return the most appropriate pixel area value.

Parameters:
  • model (dict, None) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines. In particular, it must have a keyword “wcs” and a WCS associated with it.

  • prefer_mean (bool, optional) – If True, computes the mean pixel area of the model’s pixels within either the bounding box (if available) or the entire data array. If this fails, it will fall back to the value of the "pixelarea_steradians" keyword of the input model. If False, returns the “nominal” pixel area as provided by the "pixelarea_steradians" keyword of the input model and if this is None, it will return mean pixel area.

Returns:

pix_area – Pixel area in steradians.

Return type:

float, None

get_output_model_pixel_area(model)[source]

Compute output pixel area.

Computes or retrieves pixel area of the output model. Currently, this is the average pixel area of the model’s pixels within either the bounding box (if available) or the entire data array.

Parameters:

model (dict, None) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines. In particular, it must have a keyword “wcs” and a WCS associated with it.

Returns:

pix_area – Pixel area in steradians.

Return type:

float

init_time_counters()[source]

Initialize variables/arrays needed to process exposure time.

init_variance_arrays()[source]

Allocate arrays that hold co-added resampled variances and their weights.

is_finalized()[source]

Check if output_model has been finalized.

Indicates whether all attributes of the output_model have been computed from intermediate (running) values.

resample_variance_arrays(model, pixmap, pixel_scale_ratio, iscale, weight_map, xmin, xmax, ymin, ymax)[source]

Resample variance arrays.

Resample and co-add variance arrays using appropriate weights and update total weights.

Parameters:
  • model (dict) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines.

  • pixmap (np.ndarray) – A mapping (3D array) from input image (data) coordinates to resampled (out_img) coordinates. pixmap must be an array of shape (Ny, Nx, 2) where (Ny, Nx) is the shape of the input image. pixmap[..., 0] forms a 2D array of X-coordinates of input pixels in the output frame and pixmap[..., 1] forms a 2D array of Y-coordinates of input pixels in the output coordinate frame.

  • pixel_scale_ratio (float) – Pixel scale ratio defined as the ratio of the output pixel scale to the first input model’s pixel scale computed from this model’s WCS at the fiducial point (taken as the ref_ra and ref_dec from the wcsinfo meta attribute of the first input image).

  • iscale (float) – The scale to apply to the input variance data before drizzling.

  • weight_map (numpy.ndarray, None, optional) –

    A 2D numpy array containing the pixel by pixel weighting. Must have the same dimensions as data.

    When weight_map is None, the weight of input data pixels will be assumed to be 1.

  • xmin (float, optional) – This and the following three parameters set a bounding rectangle on the input image. Only pixels on the input image inside this rectangle will have their flux added to the output image. Xmin sets the minimum value of the x dimension. The x dimension is the dimension that varies quickest on the image. If the value is zero, no minimum will be set in the x dimension. All four parameters are zero based, counting starts at zero.

  • xmax (float, optional) – Sets the maximum value of the x dimension on the bounding box of the input image. If the value is zero, no maximum will be set in the x dimension, the full x dimension of the output image is the bounding box.

  • ymin (float, optional) – Sets the minimum value in the y dimension on the bounding box. The y dimension varies less rapidly than the x and represents the line index on the input image. If the value is zero, no minimum will be set in the y dimension.

  • ymax (float, optional) – Sets the maximum value in the y dimension. If the value is zero, no maximum will be set in the y dimension, the full x dimension of the output image is the bounding box.

reset_arrays(n_input_models=None)[source]

Reset intermediate arrays.

Initialize/reset Drizzle objects, output model and arrays, and time counters and clears the “finalized” flag. Output WCS and shape are not modified from Resample object initialization. This method needs to be called before calling add_model() for the first time after finalize() was called.

Parameters:

n_input_models (int, None, optional) – Number of input models expected to be resampled. When provided, this is used to estimate memory requirements and optimize memory allocation for the context array.

update_time(model)[source]

Update time calculations.

A method called by the add_model() method to process each image’s time attributes only when model has a new group ID.

Parameters:

model (dict) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines.

validate_input_model(model)[source]

Validate input model.

Checks that model has all the required keywords needed for processing based on settings used during initialisation if the Resample object.

Parameters:

model (dict) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines.

Raises:

KeyError – A KeyError is raised when model does not have a required keyword.