Skip to content

containers

Data classes for describing models in a structured way

Model dataclass

Source code in witch/containers.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@dataclass
class Model:
    name: str
    structures: list[Structure]
    xyz: jax.Array  # arcseconds
    x0: float  # rad
    y0: float  # rad
    dz: float  # arcseconds * unknown
    beam: jax.Array
    n_rounds: int
    cur_round: int = 0
    chisq: float = np.inf
    original_order: list[int] = field(init=False)

    def __post_init__(self):
        # Make sure the structure is in the order that core expects
        structure_idx = np.argsort(
            [core.ORDER.index(structure.structure) for structure in self.structures]
        )
        self.structures = [self.structures[i] for i in structure_idx]
        self.original_order = list(np.sort(structure_idx))

    @property
    def n_struct(self) -> list[int]:
        n_struct = [0] * len(core.ORDER)
        for structure in self.structures:
            idx = core.ORDER.index(structure.structure)
            n_struct[idx] += 1
        return n_struct

    @property
    def pars(self) -> list[float]:
        pars = []
        for structure in self.structures:
            pars += [parameter.val for parameter in structure.parameters]
        return pars

    @property
    def par_names(self) -> list[str]:
        par_names = []
        for structure in self.structures:
            par_names += [parameter.name for parameter in structure.parameters]
        return par_names

    @property
    def priors(self) -> list[Optional[tuple[float, float]]]:
        priors = []
        for structure in self.structures:
            priors += [parameter.prior for parameter in structure.parameters]
        return priors

    @property
    def to_fit(self) -> list[bool]:
        to_fit = []
        for structure in self.structures:
            to_fit += [
                parameter.fit[self.cur_round] for parameter in structure.parameters
            ]
        return to_fit

    @property
    def to_fit_ever(self) -> list[bool]:
        to_fit = []
        for structure in self.structures:
            to_fit += [parameter.fit_ever for parameter in structure.parameters]
        return to_fit

    def __repr__(self) -> str:
        rep = self.name + ":\n"
        rep += f"Round {self.cur_round + 1} out of {self.n_rounds}\n"
        for i in self.original_order:
            struct = self.structures[i]
            rep += "\t" + struct.name + ":\n"
            for par in struct.parameters:
                rep += (
                    "\t\t"
                    + par.name
                    + "*" * par.fit[self.cur_round]
                    + str(par.prior) * (par.prior is not None)
                    + " = "
                    + str(par.val)
                    + " ± "
                    + str(par.err)
                    + "\n"
                )
        rep += f"chisq is {self.chisq}"
        return rep

    def update(self, vals, errs, chisq):
        n = 0
        for struct in self.structures:
            for par in struct.parameters:
                par.val = vals[n]
                par.err = errs[n]
                n += 1
        self.chisq = chisq

    def minkasi_helper(
        self, params: NDArray[np.floating], tod: Tod
    ) -> tuple[NDArray[np.floating], NDArray[np.floating]]:
        """
        Helper function to work with minkasi fitting routines.

        Arguments:

            params: An array of model parameters.

            tod: A minkasi tod instance.
                'dx' and 'dy' must be in tod.info and be in radians.

        Returns:

            grad: The gradient of the model with respect to the model parameters.

            pred: The model with the specified substructure.
        """
        dx = (tod.info["dx"] - self.x0) * wu.rad_to_arcsec
        dy = (tod.info["dy"] - self.y0) * wu.rad_to_arcsec
        argnums = tuple(np.where(self.to_fit)[0] + core.ARGNUM_SHIFT_TOD)

        pred, grad = core.model_tod_grad(
            self.xyz,
            *self.n_struct,
            self.dz,
            self.beam,
            dx,
            dy,
            argnums,
            *params,
        )

        pred = jax.device_get(pred)
        grad = jax.device_get(grad)

        return grad, pred

    def save(self, path: str):
        """
        Serialize the model to a file with dill.

        Arguments:

            path: The file to save to.
        """
        with open(path, "wb") as f:
            dill.dump(self, f)

    @classmethod
    def load(cls, path: str) -> Self:
        """
        Load the model from a file with dill.

        Arguments:

            path: The path to the saved model
        """
        with open(path, "rb") as f:
            return dill.load(f)

    @classmethod
    def from_cfg(cls, cfg: dict) -> Self:
        """
        Create an instance of model from a witch config.

        Arguments:

            cfg: Config loaded into a dict.
        """
        # Load constants
        constants = {
            name: eval(str(const)) for name, const in cfg.get("constants", {}).items()
        }  # pyright: ignore [reportUnusedVariable]

        # Get jax device
        dev_id = cfg.get("jax_device", 0)
        device = jax.devices()[dev_id]

        # Setup coordindate stuff
        r_map = eval(str(cfg["coords"]["r_map"]))
        dr = eval(str(cfg["coords"]["dr"]))
        dz = eval(str(cfg["coords"].get("dz", dr)))
        x0 = eval(str(cfg["coords"]["x0"]))
        y0 = eval(str(cfg["coords"]["y0"]))

        xyz_host = wu.make_grid(r_map, dr, dr, dz)
        xyz = jax.device_put(xyz_host, device)
        xyz[0].block_until_ready()
        xyz[1].block_until_ready()
        xyz[2].block_until_ready()

        # Make beam
        beam = wu.beam_double_gauss(
            dr,
            eval(str(cfg["beam"]["fwhm1"])),
            eval(str(cfg["beam"]["amp1"])),
            eval(str(cfg["beam"]["fwhm2"])),
            eval(str(cfg["beam"]["amp2"])),
        )
        beam = jax.device_put(beam, device)

        n_rounds = cfg.get("n_rounds", 1)
        dz = dz * eval(str(cfg["model"]["unit_conversion"]))

        structures = []
        for name, structure in cfg["model"]["structures"].items():
            parameters = []
            for par_name, param in structure["parameters"].items():
                val = eval(str(param["value"]))
                fit = param.get("to_fit", [False] * n_rounds)
                if isinstance(fit, bool):
                    fit = [fit] * n_rounds
                if len(fit) != n_rounds:
                    raise ValueError(
                        "to_fit has %d entries but we only have %d rounds",
                        len(fit),
                        n_rounds,
                    )
                priors = param.get("priors", None)
                if priors is not None:
                    priors = eval(str(priors))
                parameters.append(Parameter(par_name, fit, val, 0.0, priors))
            structures.append(Structure(name, structure["structure"], parameters))
        name = cfg["model"].get(
            "name", "-".join([structure.name for structure in structures])
        )

        return cls(name, structures, xyz, x0, y0, dz, beam, n_rounds)

from_cfg(cfg) classmethod

Create an instance of model from a witch config.

Arguments:

cfg: Config loaded into a dict.
Source code in witch/containers.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@classmethod
def from_cfg(cls, cfg: dict) -> Self:
    """
    Create an instance of model from a witch config.

    Arguments:

        cfg: Config loaded into a dict.
    """
    # Load constants
    constants = {
        name: eval(str(const)) for name, const in cfg.get("constants", {}).items()
    }  # pyright: ignore [reportUnusedVariable]

    # Get jax device
    dev_id = cfg.get("jax_device", 0)
    device = jax.devices()[dev_id]

    # Setup coordindate stuff
    r_map = eval(str(cfg["coords"]["r_map"]))
    dr = eval(str(cfg["coords"]["dr"]))
    dz = eval(str(cfg["coords"].get("dz", dr)))
    x0 = eval(str(cfg["coords"]["x0"]))
    y0 = eval(str(cfg["coords"]["y0"]))

    xyz_host = wu.make_grid(r_map, dr, dr, dz)
    xyz = jax.device_put(xyz_host, device)
    xyz[0].block_until_ready()
    xyz[1].block_until_ready()
    xyz[2].block_until_ready()

    # Make beam
    beam = wu.beam_double_gauss(
        dr,
        eval(str(cfg["beam"]["fwhm1"])),
        eval(str(cfg["beam"]["amp1"])),
        eval(str(cfg["beam"]["fwhm2"])),
        eval(str(cfg["beam"]["amp2"])),
    )
    beam = jax.device_put(beam, device)

    n_rounds = cfg.get("n_rounds", 1)
    dz = dz * eval(str(cfg["model"]["unit_conversion"]))

    structures = []
    for name, structure in cfg["model"]["structures"].items():
        parameters = []
        for par_name, param in structure["parameters"].items():
            val = eval(str(param["value"]))
            fit = param.get("to_fit", [False] * n_rounds)
            if isinstance(fit, bool):
                fit = [fit] * n_rounds
            if len(fit) != n_rounds:
                raise ValueError(
                    "to_fit has %d entries but we only have %d rounds",
                    len(fit),
                    n_rounds,
                )
            priors = param.get("priors", None)
            if priors is not None:
                priors = eval(str(priors))
            parameters.append(Parameter(par_name, fit, val, 0.0, priors))
        structures.append(Structure(name, structure["structure"], parameters))
    name = cfg["model"].get(
        "name", "-".join([structure.name for structure in structures])
    )

    return cls(name, structures, xyz, x0, y0, dz, beam, n_rounds)

load(path) classmethod

Load the model from a file with dill.

Arguments:

path: The path to the saved model
Source code in witch/containers.py
208
209
210
211
212
213
214
215
216
217
218
@classmethod
def load(cls, path: str) -> Self:
    """
    Load the model from a file with dill.

    Arguments:

        path: The path to the saved model
    """
    with open(path, "rb") as f:
        return dill.load(f)

minkasi_helper(params, tod)

Helper function to work with minkasi fitting routines.

Arguments:

params: An array of model parameters.

tod: A minkasi tod instance.
    'dx' and 'dy' must be in tod.info and be in radians.

Returns:

grad: The gradient of the model with respect to the model parameters.

pred: The model with the specified substructure.
Source code in witch/containers.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def minkasi_helper(
    self, params: NDArray[np.floating], tod: Tod
) -> tuple[NDArray[np.floating], NDArray[np.floating]]:
    """
    Helper function to work with minkasi fitting routines.

    Arguments:

        params: An array of model parameters.

        tod: A minkasi tod instance.
            'dx' and 'dy' must be in tod.info and be in radians.

    Returns:

        grad: The gradient of the model with respect to the model parameters.

        pred: The model with the specified substructure.
    """
    dx = (tod.info["dx"] - self.x0) * wu.rad_to_arcsec
    dy = (tod.info["dy"] - self.y0) * wu.rad_to_arcsec
    argnums = tuple(np.where(self.to_fit)[0] + core.ARGNUM_SHIFT_TOD)

    pred, grad = core.model_tod_grad(
        self.xyz,
        *self.n_struct,
        self.dz,
        self.beam,
        dx,
        dy,
        argnums,
        *params,
    )

    pred = jax.device_get(pred)
    grad = jax.device_get(grad)

    return grad, pred

save(path)

Serialize the model to a file with dill.

Arguments:

path: The file to save to.
Source code in witch/containers.py
197
198
199
200
201
202
203
204
205
206
def save(self, path: str):
    """
    Serialize the model to a file with dill.

    Arguments:

        path: The file to save to.
    """
    with open(path, "wb") as f:
        dill.dump(self, f)