GriddedPSFModel#
- class photutils.psf.GriddedPSFModel(nddata, *, flux=1.0, x_0=0.0, y_0=0.0, fill_value=0.0)[source]#
Bases:
Fittable2DModelA model representing a grid of 2D ePSF models.
The ePSF models are defined at fiducial detector locations specified by their
(x, y)detector coordinates. The fiducial locations must form a rectangular grid.This model has three parameters: an image intensity scaling factor (
flux), which scales the input image, and two positional parameters (x_0andy_0), which specify the location of the feature in the coordinate grid where the model is evaluated.When evaluating this model, the input
xandyarrays must have no more than two dimensions.- Parameters:
- nddata
NDData A
NDDataobject containing the reference ePSF grid. Itsdataattribute must be a 3Dndarraywith shape(N_psf, ePSF_ny, ePSF_nx), where each plane is a 2D ePSF image. The x and y dimensions of each ePSF image must both be at least 4 pixels.N_psfmust not be 2 or 3. All values indatamust be finite. The ePSF peak is assumed to be centered in each input image. See the Notes section for details on the required normalization of the input ePSF images.If
N_psfis 1, the single ePSF image is used at all detector positions. This is equivalent to usingImagePSFwith the same ePSF image.The
metaattribute must be a dictionary containing:'grid_xypos': A sequence of the fiducial(x, y)detector coordinates for each reference ePSF. The order must match the first axis ofdata. That is,grid_xypos[i]gives the detector coordinates ofnddata.data[i]. The coordinates must form a rectangular grid.'oversampling': The integer oversampling factor(s) of the input ePSF images. If a scalar is provided, it is applied to both axes. If two values are provided, they must be in(y, x)order.
The
metadictionary may also contain additional metadata, such as the telescope, instrument, detector, or filter.- fluxfloat, optional
The flux scaling factor. This corresponds to the total source flux, assuming the input ePSF images are properly normalized.
- x_0, y_0float, optional
The
(x, y)coordinates of the ePSF peak in the output coordinate grid where the model is evaluated.- fill_valuefloat or
None, optional The value used for points outside the input pixel grid. The default is 0.0. If
None, a point outside the input pixel grid takes the value of the spline at the nearest point on the edge of the grid.
- nddata
Methods
read(*args, **kwargs)
Class method to create a
GriddedPSFModelinstance from a STDPSF FITS file or a WebbPSF (STPSF) FITS file. The file format is identified automatically, or it can be set with theformatkeyword ('stdpsf'or'webbpsf'). This method usesstdpsf_reader()orwebbpsf_reader()with the provided parameters.See also
ImagePSFA model for a single ePSF image.
make_epsf_from_psfMake an ePSF image from a sampled PSF.
Notes
The input images must be effective PSFs (ePSFs). Each value of an ePSF is the fraction of the source flux that falls in a whole detector pixel centered at that position relative to the source, even when the image is oversampled. The model interpolates the input images and does not integrate them over the detector pixels. Evaluating the model at a position
(x, y)therefore gives the flux in a detector pixel centered at(x, y), which can be any fractional pixel position.Because each value is the flux in a whole detector pixel, the model values sum to
fluxonly when the model is evaluated on a grid with a spacing of one detector pixel. That holds for any values ofx_0andy_0. On a finer grid the pixels overlap, and the sum is larger thanfluxby the ratio of the pixel area to the area of a grid cell.Oversampled images that are not ePSFs, such as PSFs sampled at the points of a fine grid or binned into subpixels, are not converted to ePSFs by this model. The model is then sharper than a source in the data. For an undersampled PSF, the sum of the model values over the detector pixels can also change with the subpixel position of the source. Such images should first be integrated over the area of a detector pixel centered at each of their grid points, which is what
make_epsf_from_psfdoes.The fitted
fluxparameter represents the total source flux, provided the input ePSF images are properly normalized. The fitted flux is a multiplicative scale factor applied to the input ePSF after accounting for any oversampling.For a fully sampled ePSF (i.e., no oversampling), the sum of the ePSF values over an infinite grid is 1.0. Because ePSFs are represented by finite images in practice, the sum of the array values may be less than 1.0.
For oversampled ePSFs, the normalization should instead be such that the sum of the array values over an infinite grid equals the product of the oversampling factors (e.g.,
oversampling**2when the oversampling is the same along both axes). Again, a finite image will generally have a smaller sum because it does not contain the full PSF wings.If the input ePSF image covers only a finite region of the PSF, correction factors based on the encircled or ensquared energy can be used to estimate the missing flux and obtain the proper normalization.
With the default
fill_valueof 0, the model is zero outside of the extent of the input ePSF images. The model values on a grid of detector pixels therefore sum to less thanfluxby the fraction of the source flux that is outside of the images. That sum also changes with the subpixel position of the source, because the number of detector pixels inside the images changes (see Image-based PSF Models for example values). The input images should therefore be large enough that the ePSF is small at their edges.Internally, the ePSF grid is reordered so that the reference ePSFs are sorted first by their y detector coordinate and then by their x detector coordinate.
Each grid plane is interpolated with a bicubic spline (
RectBivariateSplinewithkx=ky=3ands=0). The spline coefficients of each evaluated grid plane are cached on the model, in a float64 array with the same number of elements as the grid data, and shared across copies made with thecopymethod. When every grid plane has been evaluated, the cache roughly doubles the model’s memory footprint for float64 grid data and triples it for float32 grid data. The cache is not included when the model is pickled, and a deep copy gets its own copy of it. The splines of the four bounding grid planes are evaluated together by a compiled kernel, which also computes the analytic partial derivatives used byfit_deriv.Examples
Oversampled PSFs whose values are samples of the PSF, such as the output of an optical model, must be converted to ePSFs before they are used as the input images. Here, four narrow Gaussian PSFs are sampled on a grid that is oversampled by a factor of 4 and then integrated over the detector pixels with
make_epsf_from_psf:>>> import numpy as np >>> from astropy.nddata import NDData >>> from photutils.psf import GriddedPSFModel, make_epsf_from_psf >>> oversampling = 4 >>> yy, xx = np.mgrid[-30:31, -30:31] / oversampling >>> sigmas = (0.5, 0.55, 0.6, 0.65) # detector pixels >>> psfs = np.array([np.exp(-(xx**2 + yy**2) / (2 * sigma**2)) ... for sigma in sigmas]) >>> psfs *= oversampling**2 / psfs.sum(axis=(1, 2), keepdims=True) >>> epsfs = make_epsf_from_psf(psfs, oversampling=oversampling) >>> meta = {'grid_xypos': [(0, 0), (100, 0), (0, 100), (100, 100)], ... 'oversampling': oversampling} >>> model = GriddedPSFModel(NDData(epsfs, meta=meta), x_0=40.3, ... y_0=29.6)
The model values on a grid of detector pixels sum to the model flux for any subpixel position of the source:
>>> yy, xx = np.mgrid[23:38, 33:48] >>> print(f'{model(xx, yy).sum():.3f}') 1.000
Attributes Summary
A
tupleof lengthn_inputsdefining the bounding box limits, or raiseNotImplementedErrorfor no bounding_box.A
dictmapping parameter names to their upper and lower bounds as(min, max)tuples or[min, max]lists.Fitter should set covariance matrix, if available.
The 3D array of ePSFs.
List of parameter equality constraints.
A
dictmapping parameter names to their fixed constraint.The
(ny, nx)shape of the ePSF grid.The (x, y) positions of the ePSFs, as an
(N_psf, 2)array.Whether the model has any bounds constraints.
Whether the model has any fixed constraints.
Whether the model has any tied constraints.
A flag indicating whether or not a custom bounding_box has been assigned to this model by a user, via assignment to
model.bounding_box.A flag indicating whether or not a custom inverse model has been assigned to this model by a user, via assignment to
model.inverse.List of parameter inequality constraints.
This property is used to indicate what units or sets of units the evaluate method expects, and returns a dictionary mapping inputs to units (or
Noneif any units are accepted).Allow dimensionless input (and corresponding output).
Enforce strict units on inputs to evaluate.
Returns a new
Modelinstance which performs the inverse transform, if an analytic inverse is defined for this model.A dict-like object to store optional information.
Primarily for informational purposes, these are the types of constraints that constrain model evaluation.
The index of the model set axis--that is the axis of a parameter array that pertains to which model a parameter value pertains to--as specified when the model was initialized.
Return the number of components in a single model, which is obviously 1.
User-provided name for this model instance.
The (x, y) pixel coordinates, as a 1D
ndarray, of the origin of the coordinate system within the model image.The integer oversampling factors of the input ePSF images, as a 1D
ndarrayin(y, x)order.Names of the parameters that describe models of this type.
Return parameters as a pset.
Primarily for informational purposes, these are the types of constraints that can be set on a model's parameters.
A flattened array of all parameter values in all parameter sets.
Read and parse a FITS file into a
GriddedPSFModelinstance.This property is used to indicate what units or sets of units the output of evaluate should be in, and returns a dictionary mapping outputs to units (or
Noneif any units are accepted).A flag indicating whether a model is separable.
Standard deviation of parameters, if covariance matrix is available.
This is a boolean property that indicates whether or not accessing constraints automatically check the constituent models current values.
A
dictmapping parameter names to their tied constraint.True if this model has been created with
Quantityobjects or if there are no parameters.Methods Summary
__call__(*inputs[, model_set_axis, ...])Evaluate this model using the given input(s) and the parameter values that were specified when the model was instantiated.
coerce_units([input_units, return_units, ...])Attach units to this (unitless) model.
copy()Return a copy of this model where only the model parameters are copied.
deepcopy()Return a deep copy of this model.
evaluate(x, y, flux, x_0, y_0)Calculate the ePSF model at the input coordinates for the given model parameters.
fit_deriv(x, y, flux, x_0, y_0)Calculate the partial derivatives of the ePSF model with respect to the model parameters.
get_bounding_box([with_bbox])Return the
bounding_boxof a model if it exists orNoneotherwise.Returns True if the model has an analytic or user inverse defined.
input_shape(inputs)Get input shape for bounding_box evaluation.
output_units(**kwargs)Return a dictionary of output units for this model given a dictionary of fitting inputs and outputs.
plot_grid(*[, ax, vmax_scale, peak_norm, ...])Plot the grid of ePSF models.
prepare_inputs(*inputs[, model_set_axis, ...])This method is used in
__call__to ensure that all the inputs to the model can be broadcast into compatible shapes (if one or both of them are input as arrays), particularly if there are more than one parameter sets.prepare_outputs(broadcasted_shapes, ...)rename([name, inputs, outputs])Return a copy of this model with a new name.
render([out, coords])Evaluate a model at fixed positions, respecting the
bounding_box.set_slice_args(*args)sum_of_implicit_terms(*args, **kwargs)Evaluate the sum of any implicit model terms on some input variables.
with_units_from_data(**kwargs)Return an instance of the model which has units for which the parameter values are compatible with the data units specified.
without_units_for_data(**kwargs)Return an instance of the model for which the parameter values have been converted to the right units for the data, then the units have been stripped away.
Attributes Documentation
- bbox_with_units#
- bounding_box#
A
tupleof lengthn_inputsdefining the bounding box limits, or raiseNotImplementedErrorfor no bounding_box.The default limits are given by a
bounding_boxproperty or method defined in the class body of a specific model. If not defined then this property just raisesNotImplementedErrorby default (but may be assigned a custom value by a user).bounding_boxcan be set manually to an array-like object of shape(model.n_inputs, 2). For further usage, see Efficient Model Rendering with Bounding BoxesThe limits are ordered according to the
numpy'C'indexing convention, and are the reverse of the model input order, e.g. for inputs('x', 'y', 'z'),bounding_boxis defined:for 1D:
(x_low, x_high)for 2D:
((y_low, y_high), (x_low, x_high))for 3D:
((z_low, z_high), (y_low, y_high), (x_low, x_high))
Examples
Setting the
bounding_boxlimits for a 1D and 2D model:>>> from astropy.modeling.models import Gaussian1D, Gaussian2D >>> model_1d = Gaussian1D() >>> model_2d = Gaussian2D(x_stddev=1, y_stddev=1) >>> model_1d.bounding_box = (-5, 5) >>> model_2d.bounding_box = ((-6, 6), (-5, 5))
Setting the bounding_box limits for a user-defined 3D
custom_model:>>> from astropy.modeling.models import custom_model >>> def const3d(x, y, z, amp=1): ... return amp ... >>> Const3D = custom_model(const3d) >>> model_3d = Const3D() >>> model_3d.bounding_box = ((-6, 6), (-5, 5), (-4, 4))
To reset
bounding_boxto its default limits just delete the user-defined value–this will reset it back to the default defined on the class:>>> del model_1d.bounding_box
To disable the bounding box entirely (including the default), set
bounding_boxtoNone:>>> model_1d.bounding_box = None >>> model_1d.bounding_box Traceback (most recent call last): NotImplementedError: No bounding box is defined for this model (note: the bounding box was explicitly disabled for this model; use `del model.bounding_box` to restore the default bounding box, if one is defined for this model).
- bounds#
A
dictmapping parameter names to their upper and lower bounds as(min, max)tuples or[min, max]lists.
- col_fit_deriv = True#
- cov_matrix#
Fitter should set covariance matrix, if available.
- data#
The 3D array of ePSFs.
The shape is
(N_psf, ePSF_ny, ePSF_nx).
- eqcons#
List of parameter equality constraints.
- fittable = True#
- fixed#
A
dictmapping parameter names to their fixed constraint.
- flux = Parameter('flux', value=1.0)#
- grid_shape#
The
(ny, nx)shape of the ePSF grid.
- grid_xypos#
The (x, y) positions of the ePSFs, as an
(N_psf, 2)array.The positions are sorted first by y and then by x, which can differ from the order of the input
grid_xypos.grid_xypos[i]is the (x, y) position of the reference ePSF indata[i].
- has_bounds#
Whether the model has any bounds constraints.
- has_fixed#
Whether the model has any fixed constraints.
- has_tied#
Whether the model has any tied constraints.
- has_user_bounding_box#
A flag indicating whether or not a custom bounding_box has been assigned to this model by a user, via assignment to
model.bounding_box.
- has_user_inverse#
A flag indicating whether or not a custom inverse model has been assigned to this model by a user, via assignment to
model.inverse.
- ineqcons#
List of parameter inequality constraints.
- input_units#
This property is used to indicate what units or sets of units the evaluate method expects, and returns a dictionary mapping inputs to units (or
Noneif any units are accepted).Model sub-classes can also use function annotations in evaluate to indicate valid input units, in which case this property should not be overridden since it will return the input units based on the annotations.
- input_units_allow_dimensionless#
Allow dimensionless input (and corresponding output). If this is True, input values to evaluate will gain the units specified in input_units. If this is a dictionary then it should map input name to a bool to allow dimensionless numbers for that input. Only has an effect if input_units is defined.
- input_units_equivalencies = None#
- input_units_strict#
Enforce strict units on inputs to evaluate. If this is set to True, input values to evaluate will be in the exact units specified by input_units. If the input quantities are convertible to input_units, they are converted. If this is a dictionary then it should map input name to a bool to set strict input units for that parameter.
- inputs#
- inverse#
Returns a new
Modelinstance which performs the inverse transform, if an analytic inverse is defined for this model.Even on models that don’t have an inverse defined, this property can be set with a manually-defined inverse, such a pre-computed or experimentally determined inverse (often given as a
PolynomialModel, but not by requirement).A custom inverse can be deleted with
del model.inverse. In this case the model’s inverse is reset to its default, if a default exists (otherwise the default is to raiseNotImplementedError).Note to authors of
Modelsubclasses: To define an inverse for a model simply override this property to return the appropriate model representing the inverse. The machinery that will make the inverse manually-overridable is added automatically by the base class.
- linear = False#
- meta = None#
A dict-like object to store optional information.
- model_constraints = ('eqcons', 'ineqcons')#
Primarily for informational purposes, these are the types of constraints that constrain model evaluation.
- model_set_axis#
The index of the model set axis–that is the axis of a parameter array that pertains to which model a parameter value pertains to–as specified when the model was initialized.
See the documentation on Model Sets for more details.
- n_inputs = 2#
- n_outputs = 1#
- n_submodels#
Return the number of components in a single model, which is obviously 1.
- name#
User-provided name for this model instance.
- origin[source]#
The (x, y) pixel coordinates, as a 1D
ndarray, of the origin of the coordinate system within the model image.
- outputs#
- oversampling#
The integer oversampling factors of the input ePSF images, as a 1D
ndarrayin(y, x)order.The value can be set with a positive integer, which is used for both axes, or with two positive integers in
(y, x)order.
- param_names = ('flux', 'x_0', 'y_0')#
Names of the parameters that describe models of this type.
The parameters in this tuple are in the same order they should be passed in when initializing a model of a specific type. Some types of models, such as polynomial models, have a different number of parameters depending on some other property of the model, such as the degree.
When defining a custom model class the value of this attribute is automatically set by the
Parameterattributes defined in the class body.
- param_sets#
Return parameters as a pset.
This is a list with one item per parameter set, which is an array of that parameter’s values across all parameter sets, with the last axis associated with the parameter set.
- parameter_constraints = ('fixed', 'tied', 'bounds')#
Primarily for informational purposes, these are the types of constraints that can be set on a model’s parameters.
- parameters#
A flattened array of all parameter values in all parameter sets.
Fittable parameters maintain this list and fitters modify it.
- read#
Read and parse a FITS file into a
GriddedPSFModelinstance.This class enables the astropy unified I/O layer for
GriddedPSFModel. This allows easily reading a file in different supported data formats using syntax such as:>>> from photutils.psf import GriddedPSFModel >>> psf_model = GriddedPSFModel.read('filename.fits', format=format)
Get help on the available readers for
GriddedPSFModelusing thehelp()method:>>> # Get help reading a GriddedPSFModel and list supported formats >>> GriddedPSFModel.read.help() >>> # Get detailed help on the STDPSF FITS reader >>> GriddedPSFModel.read.help('stdpsf') >>> # Get detailed help on the WebbPSF FITS reader >>> GriddedPSFModel.read.help('webbpsf') >>> # Print list of available formats >>> GriddedPSFModel.read.list_formats()
- Parameters:
- instanceobject
Descriptor calling instance or
Noneif no instance.- clstype
Descriptor calling class (either owner class or instance class).
- return_units#
This property is used to indicate what units or sets of units the output of evaluate should be in, and returns a dictionary mapping outputs to units (or
Noneif any units are accepted).Model sub-classes can also use function annotations in evaluate to indicate valid output units, in which case this property should not be overridden since it will return the return units based on the annotations.
- separable#
A flag indicating whether a model is separable.
- standard_broadcasting = True#
- stds#
Standard deviation of parameters, if covariance matrix is available.
- sync_constraints#
This is a boolean property that indicates whether or not accessing constraints automatically check the constituent models current values. It defaults to True on creation of a model, but for fitting purposes it should be set to False for performance reasons.
- tied#
A
dictmapping parameter names to their tied constraint.
- uses_quantity#
True if this model has been created with
Quantityobjects or if there are no parameters.This can be used to determine if this model should be evaluated with
Quantityor regular floats.
- x_0 = Parameter('x_0', value=0.0)#
- y_0 = Parameter('y_0', value=0.0)#
Methods Documentation
- __call__(*inputs, model_set_axis=None, with_bounding_box=False, fill_value=nan, equivalencies=None, inputs_map=None, **new_inputs)#
Evaluate this model using the given input(s) and the parameter values that were specified when the model was instantiated.
- coerce_units(input_units=None, return_units=None, input_units_equivalencies=None, input_units_allow_dimensionless=False)#
Attach units to this (unitless) model.
- Parameters:
- input_unitsdict or tuple, optional
Input units to attach. If dict, each key is the name of a model input, and the value is the unit to attach. If tuple, the elements are units to attach in order corresponding to
inputs.- return_unitsdict or tuple, optional
Output units to attach. If dict, each key is the name of a model output, and the value is the unit to attach. If tuple, the elements are units to attach in order corresponding to
outputs.- input_units_equivalenciesdict, optional
Default equivalencies to apply to input values. If set, this should be a dictionary where each key is a string that corresponds to one of the model inputs.
- input_units_allow_dimensionlessbool or dict, optional
Allow dimensionless input. If this is True, input values to evaluate will gain the units specified in input_units. If this is a dictionary then it should map input name to a bool to allow dimensionless numbers for that input.
- Returns:
CompoundModelA
CompoundModelcomposed of the current model plusUnitsMappingmodel(s) that attach the units.
- Raises:
- ValueError
If the current model already has units.
Examples
Wrapping a unitless model to require and convert units:
>>> from astropy.modeling.models import Polynomial1D >>> from astropy import units as u >>> poly = Polynomial1D(1, c0=1, c1=2) >>> model = poly.coerce_units((u.m,), (u.s,)) >>> model(u.Quantity(10, u.m)) <Quantity 21. s> >>> model(u.Quantity(1000, u.cm)) <Quantity 21. s> >>> model(u.Quantity(10, u.cm)) <Quantity 1.2 s>
Wrapping a unitless model but still permitting unitless input:
>>> from astropy.modeling.models import Polynomial1D >>> from astropy import units as u >>> poly = Polynomial1D(1, c0=1, c1=2) >>> model = poly.coerce_units((u.m,), (u.s,), input_units_allow_dimensionless=True) >>> model(u.Quantity(10, u.m)) <Quantity 21. s> >>> model(10) <Quantity 21. s>
- copy()[source]#
Return a copy of this model where only the model parameters are copied.
All other model attributes are references to the original model, except the
metadictionary, which is copied shallowly. This prevents copying the ePSF grid data, which may contain a large array.This method is useful if one is interested in only changing the model parameters in a model copy. It is used in the PSF photometry classes during model fitting.
Use the
deepcopymethod if you want to copy all the model attributes, including the ePSF grid data.- Returns:
- result
GriddedPSFModel A copy of this model with only the model parameters copied.
- result
- deepcopy()[source]#
Return a deep copy of this model.
The deep copy gets its own copy of the cached spline coefficients, so it does not rebuild the splines that this model already has.
- Returns:
- result
GriddedPSFModel A deep copy of this model.
- result
- evaluate(x, y, flux, x_0, y_0)[source]#
Calculate the ePSF model at the input coordinates for the given model parameters.
- fit_deriv(x, y, flux, x_0, y_0)[source]#
Calculate the partial derivatives of the ePSF model with respect to the model parameters.
Providing this analytic Jacobian allows the fitter to avoid the finite-difference approximation, which requires additional model evaluations.
The position derivatives include both the shift of the ePSF with the model position and the change of the bilinearly interpolated ePSF itself with the model position across the reference grid.
- get_bounding_box(with_bbox=True)#
Return the
bounding_boxof a model if it exists orNoneotherwise.- Parameters:
- with_bbox
The value of the
with_bounding_boxkeyword argument when calling the model. Default isTruefor usage when looking up the model’sbounding_boxwithout risk of error.
- has_inverse()#
Returns True if the model has an analytic or user inverse defined.
- input_shape(inputs)#
Get input shape for bounding_box evaluation.
- output_units(**kwargs)#
Return a dictionary of output units for this model given a dictionary of fitting inputs and outputs.
The input and output Quantity objects should be given as keyword arguments.
Notes
This method is needed in order to be able to fit models with units in the parameters, since we need to temporarily strip away the units from the model during the fitting (which might be done by e.g. scipy functions).
This method will force extra model evaluations, which maybe computationally expensive. To avoid this, one can add a return_units property to the model, see return_units.
- plot_grid(*, ax=None, vmax_scale=None, peak_norm=False, deltas=False, cmap='viridis', dividers=True, divider_color='darkgray', divider_ls='-', figsize=None)[source]#
Plot the grid of ePSF models.
- Parameters:
- ax
matplotlib.axes.AxesorNone, optional The matplotlib axes on which to plot. If
None, a new figure and axes are created.- vmax_scalefloat or
None, optional Scale factor to apply to the image stretch limits. This value is multiplied by the maximum of the plotted data (the ePSF data, or the ePSF differences if
deltas=True) to determine the plottingvmax. IfNone, the value is 1.0 for the ePSF data and 0.03 for the ePSF differences. Ifdeltas=True,vminis set to-vmax. Otherwisevminis set tovmax / 1e4.- peak_normbool, optional
Whether to normalize the ePSF data by the peak value. The default shows the ePSF flux per pixel. If
deltas=True, the differences are divided by the peak of the average ePSF.- deltasbool, optional
Set to
Trueto show the differences between each ePSF and the average ePSF.- cmapstr or
matplotlib.colors.Colormap, optional The colormap to use. The default is ‘viridis’.
- dividersbool, optional
Whether to show divider lines between the ePSFs.
- divider_color, divider_lsstr, optional
Matplotlib color and linestyle options for the divider lines between ePSFs. These keywords have no effect unless
dividers=True.- figsize(float, float), optional
The figure (width, height) in inches. It is used only if
axisNone.
- ax
- Returns:
- fig
matplotlib.figure.Figure The matplotlib figure object. This is a new figure if
ax=None, otherwise the figure ofax. Usefig.savefig()to save the figure to a file.
- fig
- Raises:
- ValueError
If
deltas=Trueand all ePSFs in the grid are blank (all pixels are zero).
Notes
This method returns a figure object. If you are using this method in a script, you will need to call
fig.show()to display the figure. If you are using this method in a Jupyter notebook, the figure will be displayed automatically.When in a notebook, if you do not store the return value of this function, the figure will be displayed twice due to the REPL automatically displaying the return value of the last function call. Alternatively, you can append a semicolon to the end of the function call to suppress the display of the return value.
- prepare_inputs(*inputs, model_set_axis=None, equivalencies=None, **kwargs)#
This method is used in
__call__to ensure that all the inputs to the model can be broadcast into compatible shapes (if one or both of them are input as arrays), particularly if there are more than one parameter sets. This also makes sure that (if applicable) the units of the input will be compatible with the evaluate method.
- prepare_outputs(broadcasted_shapes, *outputs, **kwargs)#
- classmethod rename(name=None, inputs=None, outputs=None)#
Return a copy of this model with a new name.
- render(out=None, coords=None)#
Evaluate a model at fixed positions, respecting the
bounding_box.The key difference relative to evaluating the model directly is that this method is limited to a bounding box if the
bounding_boxattribute is set.- Parameters:
- out
numpy.ndarray, optional An array that the evaluated model will be added to. If this is not given (or given as
None), a new array will be created.- coordsarray-like, optional
An array to be used to translate from the model’s input coordinates to the
outarray. It should have the property thatself(coords)yields the same shape asout. Ifoutis not specified,coordswill be used to determine the shape of the returned array. If this is not provided (or None), the model will be evaluated on a grid determined bybounding_box.
- out
- Returns:
- out
numpy.ndarray The model added to
outifoutis notNone, or else a new array from evaluating the model overcoords. Ifoutandcoordsare bothNone, the returned array is limited to thebounding_boxlimits. Ifbounding_boxisNone,arrorcoordsmust be passed.
- out
- Raises:
- ValueError
If
coordsare not given and thebounding_boxof this model is not set.
Examples
- set_slice_args(*args)#
- strip_units_from_tree()#
- sum_of_implicit_terms(*args, **kwargs)#
Evaluate the sum of any implicit model terms on some input variables. This includes any fixed terms used in evaluating a linear model that do not have corresponding parameters exposed to the user. The prototypical case is
astropy.modeling.functional_models.Shift, which corresponds to a function y = a + bx, where b=1 is intrinsically fixed by the type of model, such that sum_of_implicit_terms(x) == x. This method is needed by linear fitters to correct the dependent variable for the implicit term(s) when solving for the remaining terms (ie. a = y - bx).
- with_units_from_data(**kwargs)#
Return an instance of the model which has units for which the parameter values are compatible with the data units specified.
The input and output Quantity objects should be given as keyword arguments.
Notes
This method is needed in order to be able to fit models with units in the parameters, since we need to temporarily strip away the units from the model during the fitting (which might be done by e.g. scipy functions).
The units that the parameters will gain are not necessarily the units of the input data, but are derived from them. Model subclasses that want fitting to work in the presence of quantities need to define a
_parameter_units_for_data_unitsmethod that takes the input and output units (as two dictionaries) and returns a dictionary giving the target units for each parameter.
- without_units_for_data(**kwargs)#
Return an instance of the model for which the parameter values have been converted to the right units for the data, then the units have been stripped away.
The input and output Quantity objects should be given as keyword arguments.
Notes
This method is needed in order to be able to fit models with units in the parameters, since we need to temporarily strip away the units from the model during the fitting (which might be done by e.g. scipy functions).
The units that the parameters should be converted to are not necessarily the units of the input data, but are derived from them. Model subclasses that want fitting to work in the presence of quantities need to define a
_parameter_units_for_data_unitsmethod that takes the input and output units (as two dictionaries) and returns a dictionary giving the target units for each parameter.