| 1 |
import abc |
| 2 |
|
| 3 |
from asdf.extension import Converter |
| 4 |
|
| 5 |
from asdf_astropy.converters.utils import import_type |
| 6 |
|
| 7 |
|
| 8 |
def parameter_to_value(param): |
| 9 |
""" |
| 10 |
Convert a model parameter to a Quantity or number, |
| 11 |
depending on the presence of a unit. |
| 12 |
|
| 13 |
Parameters |
| 14 |
---------- |
| 15 |
param : astropy.modeling.Parameter |
| 16 |
|
| 17 |
Returns |
| 18 |
------- |
| 19 |
astropy.units.Quantity or float |
| 20 |
""" |
| 21 |
from astropy import units as u |
| 22 |
|
| 23 |
if param.unit is not None: |
| 24 |
return u.Quantity(param) |
| 25 |
|
| 26 |
return param.value |
| 27 |
|
| 28 |
|
| 29 |
# One converter, UnitsMappingConverter, does not inherit |
| 30 |
# this class. When adding features here consider also |
| 31 |
# updating UnitsMappingConverter. |
| 32 |
# This class is used by other packages, e.g., gwcs, to implement |
| 33 |
# converters for custom models. Keep that in mind when modifying |
| 34 |
# this code. |
| 35 |
class TransformConverterBase(Converter): |
| 36 |
""" |
| 37 |
ABC for transform/model converters. Handles common |
| 38 |
properties after concrete converter sets model-specific |
| 39 |
properties. |
| 40 |
""" |
| 41 |
|
| 42 |
@abc.abstractmethod |
| 43 |
def to_yaml_tree_transform(self, model, tag, ctx): |
| 44 |
""" |
| 45 |
Convert a model's parameters into a dict suitable |
| 46 |
for ASDF serialization. Common model properties |
| 47 |
such as name and inverse will be handled by this |
| 48 |
base class. |
| 49 |
|
| 50 |
Parameters |
| 51 |
---------- |
| 52 |
model : astropy.modeling.Model |
| 53 |
The model instance to convert. |
| 54 |
tag : str |
| 55 |
The tag identifying the YAML type that `astropy.modeling.Model` should be |
| 56 |
converted into. |
| 57 |
ctx : asdf.asdf.SerializationContext |
| 58 |
The context of the current serialization request. |
| 59 |
|
| 60 |
Returns |
| 61 |
------- |
| 62 |
dict |
| 63 |
ASDF node. |
| 64 |
""" |
| 65 |
|
| 66 |
@abc.abstractmethod |
| 67 |
def from_yaml_tree_transform(self, node, tag, ctx): |
| 68 |
""" |
| 69 |
Convert an ASDF node into an instance of the appropriate |
| 70 |
model class. The implementing class need only instantiate |
| 71 |
the model and set parameter values; common model properties |
| 72 |
such as name and inverse will be handled by this base class. |
| 73 |
|
| 74 |
Parameters |
| 75 |
---------- |
| 76 |
node : dict |
| 77 |
The ASDF node to convert. |
| 78 |
tag : str |
| 79 |
The tag identifying the YAML type of the node. |
| 80 |
ctx : asdf.asdf.SerializationContext |
| 81 |
The context of the current serialization request. |
| 82 |
|
| 83 |
Returns |
| 84 |
------- |
| 85 |
astropy.modeling.Model |
| 86 |
The resulting model instance. |
| 87 |
""" |
| 88 |
|
| 89 |
def to_yaml_tree(self, model, tag, ctx): |
| 90 |
from astropy.modeling.core import CompoundModel |
| 91 |
|
| 92 |
node = self.to_yaml_tree_transform(model, tag, ctx) |
| 93 |
|
| 94 |
if model.name is not None: |
| 95 |
node["name"] = model.name |
| 96 |
|
| 97 |
node["inputs"] = list(model.inputs) |
| 98 |
node["outputs"] = list(model.outputs) |
| 99 |
|
| 100 |
# Don't bother serializing analytic inverses provided |
| 101 |
# by the model: |
| 102 |
if getattr(model, "_user_inverse", None) is not None: |
| 103 |
node["inverse"] = model._user_inverse |
| 104 |
|
| 105 |
self._serialize_bounding_box(model, node) |
| 106 |
|
| 107 |
# model / parameter constraints |
| 108 |
if not isinstance(model, CompoundModel): |
| 109 |
fixed_nondefaults = {k: f for k, f in model.fixed.items() if f} |
| 110 |
if fixed_nondefaults: |
| 111 |
node["fixed"] = fixed_nondefaults |
| 112 |
bounds_nondefaults = {k: b for k, b in model.bounds.items() if any(b)} |
| 113 |
if bounds_nondefaults: |
| 114 |
node["bounds"] = bounds_nondefaults |
| 115 |
|
| 116 |
# model input_units_equivalencies |
| 117 |
if not isinstance(model, CompoundModel) and model.input_units_equivalencies: |
| 118 |
node["input_units_equivalencies"] = model.input_units_equivalencies |
| 119 |
|
| 120 |
return node |
| 121 |
|
| 122 |
def _serialize_bounding_box(self, model, node): |
| 123 |
from astropy.modeling.bounding_box import CompoundBoundingBox, ModelBoundingBox |
| 124 |
|
| 125 |
# ignore any default bounding_box |
| 126 |
if (bbox := model._user_bounding_box) is not None: |
| 127 |
if isinstance(bbox, ModelBoundingBox): |
| 128 |
self._serialize_bbox(model, node) |
| 129 |
elif isinstance(bbox, CompoundBoundingBox): |
| 130 |
self._serialize_cbbox(model, node) |
| 131 |
|
| 132 |
def _serialize_bbox(self, model, node): |
| 133 |
from astropy.modeling.bounding_box import ModelBoundingBox |
| 134 |
|
| 135 |
bbox = model.bounding_box |
| 136 |
|
| 137 |
if len(bbox.ignored) > 0: |
| 138 |
kwargs = {"_preserve_ignore": True} |
| 139 |
else: |
| 140 |
kwargs = {} |
| 141 |
|
| 142 |
node["bounding_box"] = ModelBoundingBox.validate(model, bbox, **kwargs) |
| 143 |
|
| 144 |
def _serialize_cbbox(self, model, node): |
| 145 |
node["bounding_box"] = model.bounding_box |
| 146 |
|
| 147 |
def from_yaml_tree(self, node, tag, ctx): |
| 148 |
from astropy.modeling.core import CompoundModel |
| 149 |
|
| 150 |
model = self.from_yaml_tree_transform(node, tag, ctx) |
| 151 |
|
| 152 |
if "name" in node: |
| 153 |
model.name = node["name"] |
| 154 |
|
| 155 |
if "inputs" in node: |
| 156 |
model.inputs = tuple(node["inputs"]) |
| 157 |
|
| 158 |
if "outputs" in node: |
| 159 |
model.outputs = tuple(node["outputs"]) |
| 160 |
|
| 161 |
self._deserialize_bounding_box(model, node) |
| 162 |
|
| 163 |
param_and_model_constraints = {} |
| 164 |
for constraint in ["fixed", "bounds"]: |
| 165 |
if constraint in node: |
| 166 |
param_and_model_constraints[constraint] = node[constraint] |
| 167 |
model._initialize_constraints(param_and_model_constraints) |
| 168 |
|
| 169 |
# this still writes eqs. for compound, but operates on each sub model |
| 170 |
if "input_units_equivalencies" in node and not isinstance(model, CompoundModel): |
| 171 |
model.input_units_equivalencies = node["input_units_equivalencies"] |
| 172 |
|
| 173 |
yield model |
| 174 |
|
| 175 |
if "inverse" in node: |
| 176 |
model.inverse = node["inverse"] |
| 177 |
|
| 178 |
def _deserialize_bounding_box(self, model, node): |
| 179 |
if "bounding_box" in node: |
| 180 |
bounding_box = node["bounding_box"] |
| 181 |
|
| 182 |
if isinstance(bounding_box, list): |
| 183 |
model.bounding_box = bounding_box |
| 184 |
elif callable(bounding_box): |
| 185 |
model.bounding_box = bounding_box(model) |
| 186 |
else: |
| 187 |
msg = f"Cannot form bounding_box from: {bounding_box}" |
| 188 |
raise TypeError(msg) |
| 189 |
|
| 190 |
|
| 191 |
class SimpleTransformConverter(TransformConverterBase): |
| 192 |
""" |
| 193 |
Class for converters that serialize all of a model's parameters |
| 194 |
and do not require special behavior based on tag version. |
| 195 |
|
| 196 |
Parameters |
| 197 |
---------- |
| 198 |
tags : list of str |
| 199 |
Tag patterns. |
| 200 |
|
| 201 |
model_type_name |
| 202 |
Fully-qualified model type name. |
| 203 |
""" |
| 204 |
|
| 205 |
def __init__(self, tags, model_type_name): |
| 206 |
self._tags = tags |
| 207 |
self._model_type_name = model_type_name |
| 208 |
self._model_type = None |
| 209 |
|
| 210 |
@property |
| 211 |
def tags(self): |
| 212 |
return self._tags |
| 213 |
|
| 214 |
@property |
| 215 |
def types(self): |
| 216 |
return [self._model_type_name] |
| 217 |
|
| 218 |
@property |
| 219 |
def model_type(self): |
| 220 |
# Delay import until the model class is needed to improve speed |
| 221 |
# of loading the extension. |
| 222 |
if self._model_type is None: |
| 223 |
self._model_type = import_type(self._model_type_name) |
| 224 |
return self._model_type |
| 225 |
|
| 226 |
def to_yaml_tree_transform(self, model, tag, ctx): |
| 227 |
return {p: parameter_to_value(getattr(model, p)) for p in model.param_names} |
| 228 |
|
| 229 |
def from_yaml_tree_transform(self, node, tag, ctx): |
| 230 |
model_type = self.model_type |
| 231 |
model_kwargs = {} |
| 232 |
for param in model_type.param_names: |
| 233 |
if param in node: |
| 234 |
model_kwargs[param] = node[param] |
| 235 |
return model_type(**model_kwargs) |