FittableImageModel#
- class photutils.psf.FittableImageModel(data, *, flux=1.0, x_0=0.0, y_0=0.0, normalize=False, normalization_correction=1.0, origin=None, oversampling=1, fill_value=0.0, **kwargs)[source]#
Bases:
Fittable2DModel
Deprecated since version 2.0.0: The FittableImageModel class is deprecated and may be removed in a future version. Use
ImagePSF
instead.A fittable image model allowing for intensity scaling and translations.
This class takes 2D image data and computes the values of the model at arbitrary locations, including fractional pixel positions, within the image using spline interpolation provided by
RectBivariateSpline
.The fittable model provided by this class has three model parameters: an image intensity scaling factor (
flux
) which is applied to (normalized) image, and two positional parameters (x_0
andy_0
) indicating the location of a feature in the coordinate grid on which the model is to be evaluated.- Parameters:
- data2D
ndarray
Array containing the 2D image.
- fluxfloat, optional
Intensity scaling factor for image data. If
flux
isNone
, then the normalization constant will be computed so that the total flux of the model’s image data is 1.0.- x_0, y_0float, optional
Position of a feature in the image in the output coordinate grid on which the model is evaluated.
- normalizebool, optional
Indicates whether or not the model should be build on normalized input image data. If true, then the normalization constant (N) is computed so that
\[N \cdot C \cdot \sum\limits_{i,j} D_{i,j} = 1,\]where N is the normalization constant, C is correction factor given by the parameter
normalization_correction
, and \(D_{i,j}\) are the elements of the input imagedata
array.- normalization_correctionfloat, optional
A strictly positive number that represents correction that needs to be applied to model’s data normalization (see C in the equation in the comments to
normalize
for more details). A possible application for this parameter is to account for aperture correction. Assuming model’s data represent a PSF to be fitted to some target star, we setnormalization_correction
to the aperture correction that needs to be applied to the model. That is,normalization_correction
in this case should be set to the ratio between the total flux of the PSF (including flux outside model’s data) to the flux of model’s data. Then, best fitted value of theflux
model parameter will represent an aperture-corrected flux of the target star. In the case of aperture correction,normalization_correction
should be a value larger than one, as the total flux, including regions outside of the aperture, should be larger than the flux inside the aperture, and thus the correction is applied as an inversely multiplied factor.- origintuple, None, optional
A reference point in the input image
data
array. When origin isNone
, origin will be set at the middle of the image array.If
origin
represents the location of a feature (e.g., the position of an intensity peak) in the inputdata
, then model parametersx_0
andy_0
show the location of this peak in an another target image to which this model was fitted. Fundamentally, it is the coordinate in the model’s image data that should map to coordinate (x_0
,y_0
) of the output coordinate system on which the model is evaluated.Alternatively, when
origin
is set to(0, 0)
, then model parametersx_0
andy_0
are shifts by which model’s image should be translated in order to match a target image.- oversamplingint or array_like (int)
The integer oversampling factor(s) of the ePSF relative to the input
stars
along each axis. Ifoversampling
is a scalar then it will be used for both axes. Ifoversampling
has two elements, they must be in(y, x)
order.- fill_valuefloat, optional
The value to be returned by the
evaluate
orastropy.modeling.Model.__call__
methods when evaluation is performed outside the definition domain of the model.- **kwargsdict, optional
Additional optional keyword arguments to be passed directly to the
compute_interpolator
method. Seecompute_interpolator
for more details.
- data2D
Deprecated since version 2.0.0: The FittableImageModel class is deprecated and may be removed in a future version. Use
ImagePSF
instead.Attributes Summary
A
tuple
of lengthn_inputs
defining the bounding box limits, or raiseNotImplementedError
for no bounding_box.A
dict
mapping parameter names to their upper and lower bounds as(min, max)
tuples or[min, max]
lists.Fitter should set covariance matrix, if available.
Get original image data.
List of parameter equality constraints.
Fill value to be returned for coordinates outside of the domain of definition of the interpolator.
Function (similar to the model's
evaluate
) to compute the derivatives of the model with respect to its parameters, for use by fitting algorithms.A
dict
mapping parameter names to their fixed constraint.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
None
if any units are accepted).Allow dimensionless input (and corresponding output).
Enforce strict units on inputs to evaluate.
Get current interpolator's arguments used when interpolator was created.
Returns a new
Model
instance 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.
Get normalization constant.
Set/Get flux correction factor.
Get normalization status.
Get normalized and/or intensity-corrected image data.
Number of columns in the data array.
Number of rows in the data array.
A tuple of
x
andy
coordinates of the origin of the coordinate system in terms of pixels of model's image.The factor by which the stored image is oversampled.
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.
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
None
if any units are accepted).A flag indicating whether a model is separable.
A tuple of dimensions of the data array in numpy style (ny, nx).
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
dict
mapping parameter names to their tied constraint.True if this model has been created with
Quantity
objects or if there are no parameters.X-coordinate of the origin of the coordinate system.
Y-coordinate of the origin of the coordinate system.
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.
compute_interpolator
(**kwargs)Compute/define the interpolating spline.
copy
()Return a copy of this model.
deepcopy
()Return a deep copy of this model.
evaluate
(x, y, flux, x_0, y_0, *[, ...])Calculate the value of the image model at the input coordinates for the given model parameters.
get_bounding_box
([with_bbox])Return the
bounding_box
of a model if it exists orNone
otherwise.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.
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
tuple
of lengthn_inputs
defining the bounding box limits, or raiseNotImplementedError
for no bounding_box.The default limits are given by a
bounding_box
property or method defined in the class body of a specific model. If not defined then this property just raisesNotImplementedError
by default (but may be assigned a custom value by a user).bounding_box
can 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_box
is 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_box
limits 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_box
to 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_box
toNone
:>>> 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
dict
mapping 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#
Get original image data.
- eqcons#
List of parameter equality constraints.
- fill_value#
Fill value to be returned for coordinates outside of the domain of definition of the interpolator.
If
fill_value
isNone
, then values outside of the domain of definition are the ones returned by the interpolator.
- fit_deriv = None#
Function (similar to the model’s
evaluate
) to compute the derivatives of the model with respect to its parameters, for use by fitting algorithms. In other words, this computes the Jacobian matrix with respect to the model’s parameters.
- fittable = True#
- fixed#
A
dict
mapping parameter names to their fixed constraint.
- flux = Parameter('flux', value=1.0)#
- 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
None
if 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#
- interpolator_kwargs#
Get current interpolator’s arguments used when interpolator was created.
- inverse#
Returns a new
Model
instance 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
Model
subclasses: 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.
- normalization_constant#
Get normalization constant.
- normalization_correction#
Set/Get flux correction factor.
Note
When setting correction factor, model’s flux will be adjusted accordingly such that if this model was a good fit to some target image before, then it will remain a good fit after correction factor change.
- normalization_status#
Get normalization status.
Possible status values are:
- 0: Performed. Model has been successfully normalized at
user’s request.
1: Failed. Attempt to normalize has failed.
2: NotRequested. User did not request model to be normalized.
- normalized_data#
Get normalized and/or intensity-corrected image data.
- nx#
Number of columns in the data array.
- ny#
Number of rows in the data array.
- origin#
A tuple of
x
andy
coordinates of the origin of the coordinate system in terms of pixels of model’s image.When setting the coordinate system origin, a tuple of two integers or floats may be used. If origin is set to
None
, the origin of the coordinate system will be set to the middle of the data array ((npix-1)/2.0
).Warning
Modifying
origin
will not adjust (modify) model’s parametersx_0
andy_0
.
- outputs#
- oversampling#
The factor by which the stored image is oversampled.
An input to this model is multiplied by this factor to yield the index into the stored image.
- 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
Parameter
attributes 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.
- 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
None
if 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.
- shape#
A tuple of dimensions of the data array in numpy style (ny, nx).
- 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
dict
mapping parameter names to their tied constraint.
- uses_quantity#
True if this model has been created with
Quantity
objects or if there are no parameters.This can be used to determine if this model should be evaluated with
Quantity
or regular floats.
- x_0 = Parameter('x_0', value=0.0)#
- x_origin#
X-coordinate of the origin of the coordinate system.
- y_0 = Parameter('y_0', value=0.0)#
- y_origin#
Y-coordinate of the origin of the coordinate system.
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:
CompoundModel
A
CompoundModel
composed of the current model plusUnitsMapping
model(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>
- compute_interpolator(**kwargs)[source]#
Compute/define the interpolating spline.
This function can be overridden in a subclass to define custom interpolators.
- Parameters:
- **kwargsdict, optional
Additional optional keyword arguments:
- degreeint, tuple, optional
Degree of the interpolating spline. A tuple can be used to provide different degrees for the X- and Y-axes. Default value is degree=3.
- sfloat, optional
Non-negative smoothing factor. Default value s=0 corresponds to interpolation. See
RectBivariateSpline
for more details.
Notes
When subclassing
FittableImageModel
for the purpose of overridingcompute_interpolator()
, theevaluate()
may need to overridden as well depending on the behavior of the new interpolator. In addition, for improved future compatibility, make sure that the overriding method stores keyword argumentskwargs
by calling_store_interpolator_kwargs
method.Use caution when modifying interpolator’s degree or smoothness in a computationally intensive part of the code as it may decrease code performance due to the need to recompute interpolator.
- copy()#
Return a copy of this model.
Uses a deep copy so that all model attributes, including parameter values, are copied as well.
- deepcopy()#
Return a deep copy of this model.
- evaluate(x, y, flux, x_0, y_0, *, use_oversampling=True)[source]#
Calculate the value of the image model at the input coordinates for the given model parameters.
- Parameters:
- x, yfloat or array_like
The x and y coordinates at which to evaluate the model.
- fluxfloat
The total flux of the source.
- x_0, y_0float
The x and y positions of the feature in the image in the output coordinate grid on which the model is evaluated.
- use_oversamplingbool, optional
Whether to use the oversampling factor to calculate the model pixel indices. The default is
True
, which means the input indices will be multiplied by this factor.
- Returns:
- evaluated_model
ndarray
The evaluated model.
- evaluated_model
- get_bounding_box(with_bbox=True)#
Return the
bounding_box
of a model if it exists orNone
otherwise.- Parameters:
- with_bbox
The value of the
with_bounding_box
keyword argument when calling the model. Default isTrue
for usage when looking up the model’sbounding_box
without 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.
- 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_box
attribute 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
out
array. It should have the property thatself(coords)
yields the same shape asout
. Ifout
is not specified,coords
will 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
out
ifout
is notNone
, or else a new array from evaluating the model overcoords
. Ifout
andcoords
are bothNone
, the returned array is limited to thebounding_box
limits. Ifbounding_box
isNone
,arr
orcoords
must be passed.
- out
- Raises:
- ValueError
If
coords
are not given and thebounding_box
of 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_units
method 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_units
method that takes the input and output units (as two dictionaries) and returns a dictionary giving the target units for each parameter.