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:
objectBase 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:
Sets up output arrays based on arguments used at initialization.
Based on information about the input images and user arguments, computes scale factors needed to convert resampled counts to fluxes.
For each input image, computes coordinate transformations (
pixmap) from the coordinate system of the input image to the coordinate system of the output image.Computes the weight image for each input image.
Calls
Drizzlemethods to resample and combine input images and their variance/error arrays.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
fillvalis either None or"INDEF"andout_imgis provided, the values ofout_imgwill not be modified. Whenfillvalis either None or"INDEF"andout_imgis not provided, the values ofout_imgwill be initialized to numpy.nan. Iffillvalis a string that can be converted to a number, then the output pixels with no contributions from input images will be set to thisfillvalvalue.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 theVAR_RNOISEarray does not exist, the variance is set to 1 for all pixels (i.e., equal weighting). Ifweight_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 theVAR_SKYarray does not exist, the variance is set to 0 for all pixels (i.e., equal weighting). Ifweight_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_bitsprovides a mean to ignore some of the DQ bitflags.When
good_bitsis 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, thengood_bitsshould 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_bitsis 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 integergood_bits=12.Finally, instead of integers,
good_bitscan 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_mapattribute 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~0would be equivalent to a setting ofNone.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_ctxis set to True, parametersout_ctx,begin_ctx_id, andmax_ctx_idwill 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. Settingcompute_errto"from_var"will assumeenable_varwas set to True regardless of actual value of the parameterenable_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>1is not recommended. Largepixmap_stepsizevalues 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 whenpixmap_stepsize <= 1. Default 1.
Attributes Summary
Indicates whether error array is computed and how it is computed.
Indicates whether context array is enabled.
Indicates whether variance arrays are resampled.
List of all group IDs of models resampled and added to the output model.
Shape of the output model arrays.
Output (resampled) model.
Get pixel scale of the output model in arcsec.
WCS of the output (resampled) model.
Get the ratio of the output pixel scale to the input pixel scale.
Indicates whether DQ flags are propagated and output model has DQ array.
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 a new "output model": a dictionary of data and meta fields.
finalize()Finalize computations.
finalize_resample_variance(output_model)Finalize variance calculations.
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.
Initialize variables/arrays needed to process exposure time.
Allocate arrays that hold co-added resampled variances and their weights.
Check if
output_modelhas 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_varis True) , and error data (ifenable_erris True), and adds them to the corresponding arrays of the output model using appropriate weighting. It also updates the weight array and context array (ifenable_ctxis True) of the resampled data, as well as relevant metadata.Whenever
modelhas 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 inputmodelby callingupdate_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 themodel["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.pixmapmust 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 andpixmap[..., 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
modelWCS at the fiducial point (taken as theref_raandref_decfrom thewcsinfometa 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
numpyarray containing the pixel by pixel weighting. Must have the same dimensions asdata.When
weight_mapis 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_shapeproperty is defined. May modifyoutput_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_wcsfrom other available attributes such asbounding_boxwhenoutput_wcs.array_shapeis None. Ifestimate_output_shapeis True andoutput_wcs.array_shapeis None, upon returnoutput_wcs.array_shapewill 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:
- finalize()[source]
Finalize computations.
Performs final computations from any intermediate values, sets output model values, and optionally frees temporary/intermediate objects.
finalizecallsfinalize_resample_variance()andfinalize_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
accumulateis False, only the WCS object of the model will be used. Whenaccumulateis True, new models will be added to the existing data in theoutput_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.
- init_variance_arrays()[source]
Allocate arrays that hold co-added resampled variances and their weights.
- is_finalized()[source]
Check if
output_modelhas been finalized.Indicates whether all attributes of the
output_modelhave 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.pixmapmust 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 andpixmap[..., 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_raandref_decfrom thewcsinfometa 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
numpyarray containing the pixel by pixel weighting. Must have the same dimensions asdata.When
weight_mapis 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 afterfinalize()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 whenmodelhas a new group ID.- Parameters:
model (dict) – A dictionary containing data arrays and other meta attributes and values of actual models used by pipelines.