Debian Codegraph @

asdf_astropy/converters/transform/compound.py

raw
1 from asdf_astropy.converters.helpers import get_tag_name
2
3 from .core import TransformConverterBase
4
5 __all__ = ["CompoundConverter"]
6
7
8 _OPERATOR_TO_TAG_NAME = {
9 "+": "add",
10 "-": "subtract",
11 "*": "multiply",
12 "/": "divide",
13 "**": "power",
14 "|": "compose",
15 "&": "concatenate",
16 "fix_inputs": "fix_inputs",
17 }
18
19
20 _TAG_NAME_TO_MODEL_METHOD = {
21 "add": "__add__",
22 "subtract": "__sub__",
23 "multiply": "__mul__",
24 "divide": "__truediv__",
25 "power": "__pow__",
26 "compose": "__or__",
27 "concatenate": "__and__",
28 "fix_inputs": "fix_inputs",
29 }
30
31
32 class CompoundConverter(TransformConverterBase):
33 """
34 ASDF serialization support for CompoundModel.
35 """
36
37 tags = (
38 "tag:stsci.edu:asdf/transform/add-*",
39 "tag:stsci.edu:asdf/transform/subtract-*",
40 "tag:stsci.edu:asdf/transform/multiply-*",
41 "tag:stsci.edu:asdf/transform/divide-*",
42 "tag:stsci.edu:asdf/transform/power-*",
43 "tag:stsci.edu:asdf/transform/compose-*",
44 "tag:stsci.edu:asdf/transform/concatenate-*",
45 "tag:stsci.edu:asdf/transform/fix_inputs-*",
46 )
47 types = ("astropy.modeling.core.CompoundModel",)
48
49 def select_tag(self, model, tags, ctx):
50 tag_name = _OPERATOR_TO_TAG_NAME[model.op]
51
52 # The extension will never include two tags with the
53 # same name but different version, so we can just
54 # return the first matching tag that we discover in
55 # the list:
56 return next(t for t in tags if get_tag_name(t) == tag_name)
57
58 def to_yaml_tree_transform(self, model, tag, ctx):
59 left = model.left
60
61 right = (
62 {
63 "keys": list(model.right.keys()),
64 "values": list(model.right.values()),
65 }
66 if isinstance(model.right, dict)
67 else model.right
68 )
69
70 return {"forward": [left, right]}
71
72 def from_yaml_tree_transform(self, node, tag, ctx):
73 from astropy.modeling.core import CompoundModel, Model
74
75 oper = _TAG_NAME_TO_MODEL_METHOD[get_tag_name(tag)]
76
77 left = node["forward"][0]
78 if not isinstance(left, Model):
79 msg = f"Unknown left model type '{node['forward'][0]._tag}'"
80 raise TypeError(msg)
81
82 right = node["forward"][1]
83 if (oper == "fix_inputs" and not isinstance(right, dict)) or (
84 oper != "fix_inputs" and not isinstance(right, Model)
85 ):
86 msg = f"Unknown right model type '{node['forward'][1]._tag}'"
87 raise TypeError(msg)
88
89 if oper == "fix_inputs":
90 right = dict(zip(right["keys"], right["values"]))
91 return CompoundModel("fix_inputs", left, right)
92
93 return getattr(left, oper)(right)