Model¶
-
class
astropy.modeling.Model[source] [edit on github]¶ Bases:
objectBase class for all models.
This is an abstract class and should not be instantiated directly.
This class sets the constraints and other properties for all individual parameters and performs parameter validation.
The following initialization arguments apply to the majority of Model subclasses by default (exceptions include specialized utility models like
Mapping). Parametric models take all their parameters as arguments, followed by any of the following optional keyword arguments:Parameters: name : str, optional
A human-friendly name associated with this model instance (particularly useful for identifying the individual components of a compound model).
meta : dict, optional
An optional dict of user-defined metadata to attach to this model. How this is used and interpreted is up to the user or individual use case.
n_models : int, optional
If given an integer greater than 1, a model set is instantiated instead of a single model. This affects how the parameter arguments are interpreted. In this case each parameter must be given as a list or array–elements of this array are taken along the first axis (or
model_set_axisif specified), such that the Nth element is the value of that parameter for the Nth model in the set.See the section on model sets in the documentation for more details.
model_set_axis : int, optional
This argument only applies when creating a model set (i.e.
n_models > 1). It changes how parameter values are interpreted. Normally the first axis of each input parameter array (properly the 0th axis) is taken as the axis corresponding to the model sets. However, any axis of an input array may be taken as this “model set axis”. This accepts negative integers as well–for example usemodel_set_axis=-1if the last (most rapidly changing) axis should be associated with the model sets.fixed : dict, optional
Dictionary
{parameter_name: bool}setting the fixed constraint for one or more parameters.Truemeans the parameter is held fixed during fitting and is prevented from updates once an instance of the model has been created.Alternatively the
fixedproperty of a parameter may be used to lock or unlock individual parameters.tied : dict, optional
Dictionary
{parameter_name: callable}of parameters which are linked to some other parameter. The dictionary values are callables providing the linking relationship.Alternatively the
tiedproperty of a parameter may be used to set thetiedconstraint on individual parameters.bounds : dict, optional
Dictionary
{parameter_name: value}of lower and upper bounds of parameters. Keys are parameter names. Values are a list of length 2 giving the desired range for the parameter.Alternatively the
minandmaxor ~astropy.modeling.Parameter.bounds` properties of a parameter may be used to set bounds on individual parameters.eqcons : list, optional
List of functions of length n such that
eqcons[j](x0, *args) == 0.0in a successfully optimized problem.ineqcons : list, optional
List of functions of length n such that
ieqcons[j](x0, *args) >= 0.0is a successfully optimized problem.Examples
>>> from astropy.modeling import models >>> def tie_center(model): ... mean = 50 * model.stddev ... return mean >>> tied_parameters = {'mean': tie_center}
Specify that
'mean'is a tied parameter in one of two ways:>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3, ... tied=tied_parameters)
or
>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3) >>> g1.mean.tied False >>> g1.mean.tied = tie_center >>> g1.mean.tied <function tie_center at 0x...>
Fixed parameters:
>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3, ... fixed={'stddev': True}) >>> g1.stddev.fixed True
or
>>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3) >>> g1.stddev.fixed False >>> g1.stddev.fixed = True >>> g1.stddev.fixed True
Attributes Summary
bounding_boxA tupleof lengthn_inputsdefining the bounding box limits, orNonefor no bounding box.boundsA dictmapping parameter names to their upper and lower bounds as(min, max)tuples.eqconsList of parameter equality constraints. fittablefixedA dictmapping parameter names to their fixed constraint.has_user_bounding_boxA 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_inverseA flag indicating whether or not a custom inverse model has been assigned to this model by a user, via assignment to model.inverse.ineqconsList of parameter inequality constraints. inputsThe name(s) of the input variable(s) on which a model is evaluated. inverseReturns a new Modelinstance which performs the inverse transform, if an analytic inverse is defined for this model.linearmodel_constraintsPrimarily for informational purposes, these are the types of constraints that constrain model evaluation. model_set_axisThe 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. n_inputsThe number of inputs to this model. n_outputsThe number of outputs from this model. nameUser-provided name for this model instance. outputsThe name(s) of the output(s) of the model. param_dimDeprecated since version 0.4.
param_namesNames of the parameters that describe models of this type. param_setsReturn parameters as a pset. parameter_constraintsPrimarily for informational purposes, these are the types of constraints that can be set on a model’s parameters. parametersA flattened array of all parameter values in all parameter sets. standard_broadcastingtiedA dictmapping parameter names to their tied constraint.Methods Summary
__call__(*inputs, **kwargs)Evaluate this model using the given input(s) and the parameter values that were specified when the model was instantiated. add_model(*args, **kwargs)Deprecated since version 1.0.
copy()Return a copy of this model. evaluate(*args, **kwargs)Evaluate the model on some input variables. prepare_inputs(*inputs, **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.prepare_outputs(format_info, *outputs, **kwargs)rename(name)Creates a copy of this model class with a new name. render([out, coords])Evaluates a model on an input array. Attributes Documentation
-
bounding_box¶ A
tupleof lengthn_inputsdefining the bounding box limits, orNonefor 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
numpyindexing 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): File "<stdin>", line 1, in <module> File "astropy\modeling\core.py", line 980, in bounding_box "No bounding box is defined for this model (note: the " 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).
- for 1D:
-
bounds¶ A
dictmapping parameter names to their upper and lower bounds as(min, max)tuples.
-
eqcons¶ List of parameter equality constraints.
-
fittable= False¶
-
fixed¶ A
dictmapping parameter names to their fixed constraint.
-
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.
-
inputs= ()¶ The name(s) of the input variable(s) on which a model is evaluated.
-
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= True¶
-
model_constraints= (u'eqcons', u'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¶ The number of inputs to this model.
Equivalent to
len(model.inputs).
-
n_outputs¶ The number of outputs from this model.
Equivalent to
len(model.outputs).
-
name¶ User-provided name for this model instance.
-
outputs= ()¶ The name(s) of the output(s) of the model.
-
param_dim¶ Deprecated since version 0.4: The param_dim function is deprecated and may be removed in a future version. Use len(model) instead.
-
param_names= ()¶ 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= (u'fixed', u'tied', u'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.
-
standard_broadcasting= True¶
-
tied¶ A
dictmapping parameter names to their tied constraint.
Methods Documentation
-
__call__(*inputs, **kwargs)[source] [edit on github]¶ Evaluate this model using the given input(s) and the parameter values that were specified when the model was instantiated.
-
add_model(*args, **kwargs)[source] [edit on github]¶ Deprecated since version 1.0: The add_model function is deprecated and may be removed in a future version. Use Use Model operators (TODO: link to compound model docs instead.
Create a CompositeModel by chaining the current model with the new one using the specified mode.
Parameters: model : an instance of a subclass of Model
mode : string
‘parallel’, ‘serial’, ‘p’ or ‘s’ a flag indicating whether to combine the models in series or in parallel
Returns: model : CompositeModel
an instance of CompositeModel
-
copy()[source] [edit on github]¶ Return a copy of this model.
Uses a deep copy so that all model attributes, including parameter values, are copied as well.
-
evaluate(*args, **kwargs)[source] [edit on github]¶ Evaluate the model on some input variables.
-
prepare_inputs(*inputs, **kwargs)[source] [edit on github]¶ 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(format_info, *outputs, **kwargs)[source] [edit on github]¶
-
classmethod
rename(name)[source] [edit on github]¶ Creates a copy of this model class with a new name.
The new class is technically a subclass of the original class, so that instance and type checks will still work. For example:
>>> from astropy.modeling.models import Rotation2D >>> SkyRotation = Rotation2D.rename('SkyRotation') >>> SkyRotation <class '__main__.SkyRotation'> Name: SkyRotation (Rotation2D) Inputs: ('x', 'y') Outputs: ('x', 'y') Fittable parameters: ('angle',) >>> issubclass(SkyRotation, Rotation2D) True >>> r = SkyRotation(90) >>> isinstance(r, Rotation2D) True
-
render(out=None, coords=None)[source] [edit on github]¶ Evaluates a model on an input array. Evaluation is limited to a bounding box if the
Model.bounding_boxattribute is set.Parameters: out :
numpy.ndarray, optionalThe array on which the model is to be evaluated.
coords : array-like, optional
Coordinate arrays mapping to
arr, such thatarr[coords] == arr.Returns: out :
numpy.ndarrayThe model evaluated on the input array if given, or else a new array from
coords. Ifoutandcoordsare bothNone, the returned array is limited to theModel.bounding_boxlimits. IfModel.bounding_boxisNone,arrorcoordsmust be passed.Examples
-