Fitting
BayesianModel
¶
Bayesian spectral model that composes a deterministic forward model with numpyro priors and Poisson likelihoods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
SpectralModel | ModelComponent
|
The spectral model to fit (cloned per observation inside the
internal :class: |
required |
prior
|
dict | Callable
|
Either a unified prior dict using the |
required |
observations
|
ObsConfiguration | list[ObsConfiguration] | dict[str, ObsConfiguration]
|
One or more observation configurations. |
required |
background_model
|
BackgroundModel | dict[str, BackgroundModel | None] | None
|
|
None
|
instrument_model
|
dict[str, InstrumentModel | None] | None
|
|
None
|
sparsify_matrix
|
bool
|
Whether to use sparse transfer matrices. |
False
|
n_points
|
int
|
Number of quadrature points per energy bin. |
2
|
Source code in src/jaxspec/fit/_bayesian_model.py
51 52 53 54 55 56 57 58 59 60 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
log_likelihood
cached
property
¶
Build the total log likelihood function.
log_likelihood_per_obs
cached
property
¶
Build the log likelihood function for each bin in each observation.
log_posterior_prob
cached
property
¶
Build the posterior probability function.
Enables distribution validation only during this trace so that
out-of-support parameter values produce -inf log-probabilities
(instead of silently bogus finite values), letting external samplers
such as AIES / ESS / MH correctly reject them.
We don't use numpyro.validation_enabled() because that context
manager has an upstream bug: it saves _VALIDATION_ENABLED (a
module-global) but restores via enable_validation which writes
to both that global and Distribution._validate_args — and
those two can be out of sync (they are at fresh import). The
manual save/restore below targets Distribution._validate_args
directly, which is the attribute every Distribution instance
actually reads at construction time.
observation_names
cached
property
¶
List of the observations.
parameter_names
cached
property
¶
List of parameter names for the model.
spectral_model
property
¶
A representative spectral model replica (PN's, or whichever obs is first).
All per-obs replicas share the same structure; this is provided for
callers (e.g. :class:~jaxspec.analysis.results.FitResult) that want
a single SpectralModel to introspect topology or compute fluxes.
Per-obs parameter values live on the bound replicas after sampling.
spectrum
property
¶
Per-obs replicas of the spectral model held on the ForwardModel.
numpyro_model(observed=True)
¶
Sample the prior, evaluate the forward model, register likelihoods.
Thin wrapper around :meth:ForwardModel.evaluate: this method owns
only the numpyro-specific concerns (sample sites + Poisson
likelihoods on the observed counts). The deterministic forward pass
— spectral evaluation, instrument folding, background — lives on
the forward model and is reused by fakeit and posterior-predictive
checks.
Source code in src/jaxspec/fit/_bayesian_model.py
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 | |
prior_predictive_coverage(key=rng_key(0), num_samples=1000, min_counts=None, grouping=None)
¶
Check if the prior distribution includes the observed data.
Source code in src/jaxspec/fit/_bayesian_model.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
prior_samples(key=rng_key(0), num_samples=100)
¶
Sample from the prior distribution.
Source code in src/jaxspec/fit/_bayesian_model.py
407 408 409 410 411 412 413 414 415 416 | |
ForwardModel
¶
Bases: HideUnderscoreMixin, Module
Parametric nnx tree + per-obs caches + a deterministic evaluate.
Only parameters and parametric submodules live on the nnx tree.
Non-parametric state (xarray observations, response caches, settings) is
held off the nnx tree on _aux — these Python objects aren't
pytree-friendly and don't belong in nnx's Variable tracking.
Parameters live as nnx.Param leaves under three dict-of-modules attributes:
spectrum:{obs_name: SpectralModel}— one cloned replica per observation, so per-obs spectral params become natural nnx leaves atspectrum.<obs>.<path>.instrument:{obs_name: InstrumentModel}— only observations with a non-Noneentry in the user'sinstrument_modelarg.background:{obs_name: BackgroundModel}— singleton expanded to per-obs clones, or the per-obs dict as supplied;Noneentries dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spectral_model
|
SpectralModel | ModelComponent
|
The spectral model template; cloned per observation. A
single bare component (e.g. |
required |
observations
|
ObsConfiguration | list | dict
|
One or more observation configurations. Accepts a single
|
required |
background_model
|
BackgroundModel | dict[str, BackgroundModel | None] | None
|
|
None
|
instrument_model
|
dict[str, InstrumentModel | None] | None
|
|
None
|
sparsify_matrix
|
bool
|
Whether to store transfer matrices as sparse BCOO. |
False
|
n_points
|
int
|
Number of quadrature points per energy bin for the flux integration. |
2
|
energy_grid
|
ArrayLike | None
|
Optional shared 1-D array of energy bin edges (keV,
strictly increasing) on which to evaluate the spectral model before
redistributing onto each observation's native grid via
|
None
|
Source code in src/jaxspec/fit/_forward_model.py
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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
obs_caches
property
¶
Per-observation JAX-typed response caches (transfer matrix and components).
observations
property
¶
The name-keyed observation configurations, {obs_name: ObsConfiguration}.
settings
property
¶
Evaluation settings (sparse, n_points, energy_grid, spectrum_shared).
evaluate(inputs, *, split_branches=False, with_background=True, missing_key_style='inputs')
¶
Bind inputs and run the per-observation forward pass.
inputs is a flat {leaf_path: value} dict keyed by nnx leaf
paths (e.g. "spectrum.PN.powerlaw_1.norm",
"instrument.MOS1.gain.factor", "background.PN.countrate").
Every nnx.Param leaf of the tree must be covered; a miss raises a
KeyError with the rich _missing_prior_message.
The method is deterministic — no numpyro sites are created here.
Callers that need numpyro sampling build the inputs dict via
sample_prior first (which is what
BayesianModel.numpyro_model
does), then call evaluate. Non-sampling callers (fakeit,
posterior-predictive checks) build the inputs dict from concrete values
and call evaluate directly, vmapping over batch dimensions.
When settings["energy_grid"] is set, the spectral model is
evaluated over that grid and redistributed onto each obs's native
grid by InstrumentModel.fold.
With settings["spectrum_shared"] additionally True the grid
evaluation happens once and is broadcast to every obs (the
BayesianModel sets this flag when no per-obs spectral prior is
present). When energy_grid is None each obs evaluates the
spectrum on its own (instrument-shifted) native grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
dict[str, ArrayLike]
|
Flat leaf-path → value dict covering every
|
required |
split_branches
|
bool
|
If |
False
|
with_background
|
bool
|
If |
True
|
missing_key_style
|
str
|
Internal selector for the "missing leaf" error
wording. |
'inputs'
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, Any]]
|
``{obs_name: {"source": folded_flux | {branch: folded_flux}, |
dict[str, dict[str, Any]]
|
"background": background_rate | None}}``. The background entry |
dict[str, dict[str, Any]]
|
is |
Source code in src/jaxspec/fit/_forward_model.py
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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
Fitter classes¶
MCMCFitter
¶
Bases: BayesianModelFitter
Fit a spectral model via MCMC sampling (NUTS, AIES, or ESS).
Inherits from :class:BayesianModel and accepts the same constructor
arguments (spectral model, prior dict with dotted-path keys, observations,
optional background/instrument models).
Source code in src/jaxspec/fit/_fitter/_mcmc.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
fit(rng_key=0, num_chains=len(jax.devices()), num_warmup=1000, num_samples=1000, sampler='nuts', use_transformed_model=True, kernel_kwargs=None, mcmc_kwargs=None)
¶
Fit the model to the data using a MCMC sampler from numpyro.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rng_key
|
int
|
the random key used to initialize the sampler. |
0
|
num_chains
|
int
|
the number of chains to run. |
len(devices())
|
num_warmup
|
int
|
the number of warmup steps. |
1000
|
num_samples
|
int
|
the number of samples to draw. |
1000
|
sampler
|
Literal['nuts', 'aies', 'ess']
|
the sampler to use. Can be one of "nuts", "aies" or "ess". |
'nuts'
|
use_transformed_model
|
bool
|
whether to use the transformed model to build the InferenceData. |
True
|
kernel_kwargs
|
dict | None
|
additional arguments to pass to the kernel. See [ |
None
|
mcmc_kwargs
|
dict | None
|
additional arguments to pass to the MCMC sampler. See [ |
None
|
Returns:
| Type | Description |
|---|---|
FitResult
|
A |
Source code in src/jaxspec/fit/_fitter/_mcmc.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
VIFitter
¶
Bases: BayesianModelFitter
Source code in src/jaxspec/fit/_fitter/_vi.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
fit(rng_key=0, num_steps=10000, optimizer=numpyro.optim.Adam(step_size=0.0005), loss=Trace_ELBO(), num_samples=1000, guide=None, use_transformed_model=True, plot_diagnostics=False)
¶
Fit the model to the data using a variational inference approach from numpyro.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rng_key
|
int
|
the random key used to initialize the sampler. |
0
|
num_steps
|
int
|
the number of steps for VI. |
10000
|
optimizer
|
_NumPyroOptim
|
the optimizer to use. |
Adam(step_size=0.0005)
|
num_samples
|
int
|
the number of samples to draw. |
1000
|
loss
|
ELBO
|
the loss function to use. |
Trace_ELBO()
|
guide
|
AutoGuide | None
|
the guide to use. |
None
|
use_transformed_model
|
bool
|
whether to use the transformed model to build the InferenceData. |
True
|
plot_diagnostics
|
bool
|
plot the loss during VI. |
False
|
Returns:
| Type | Description |
|---|---|
FitResult
|
A |
Source code in src/jaxspec/fit/_fitter/_vi.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
Prior helpers¶
joint_prior_factory(components, joint_dist, *, name=None)
¶
Sample a single multivariate site and return a per-leaf value lookup.
Use from inside a factory-callable prior to give several parameters a
correlated joint draw (the dict form is strictly per-leaf, so joint
sampling has to drop into the callable form). The returned lookup
function maps a leaf path to the pre-sampled component value when the
leaf matches one of components, and None otherwise — letting the
caller chain it with structural defaults via or.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
Sequence[str]
|
Ordered tuple of user-facing parameter keys (without
|
required |
joint_dist
|
Distribution
|
A multivariate distribution whose |
required |
name
|
str | None
|
Optional numpyro site name; defaults to |
None
|
Example::
def my_prior_factory():
alpha_norm = joint_prior_factory(
components=("spectrum.powerlaw_1.alpha", "spectrum.powerlaw_1.norm"),
joint_dist=dist.MultivariateNormal(
loc=jnp.array([2.0, 1e-4]),
covariance_matrix=jnp.array([[0.5, 1e-5], [1e-5, 1e-8]]),
),
)
def prior(path, shape):
return alpha_norm(path) or _structural_defaults(path, shape)
return prior
fitter = MCMCFitter(spectral_model, observations, prior=my_prior_factory, ...)
The implementation samples joint_dist exactly once (under the supplied
name), then returns the per-component scalar slice on match. The leaf
callable contract in :func:~jaxspec.fit._bayesian_model._sample_leaves
treats array-like returns as pre-sampled values: they are written straight
to the leaf with no extra numpyro.sample site.
Source code in src/jaxspec/fit/_parameter.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
dict_prior(prior_dict)
¶
Wrap a dict-form prior as a leaf callable.
Useful for hybrid setups: cover the common cases with dict-style entries
and the special ones with custom callable logic. The returned function
returns None on miss (so callers can chain with or) — unlike the
framework's internal dict adapter which raises KeyError on miss.
Per the leaf-callable contract: the return value is either a
:class:numpyro.distributions.Distribution (registered as a numpyro
sample site by :func:~jaxspec.fit._bayesian_model._sample_leaves), a
pre-sampled array (written straight to the leaf, no site), or None
on miss.
Must be called from INSIDE the numpyro trace (typically from inside a factory-callable prior) since shared entries get sampled here.
Example::
def my_prior_factory():
covered = dict_prior({
"spectrum.powerlaw_1.alpha": dist.Uniform(0, 5),
"spectrum.powerlaw_1.norm[*]": dist.LogUniform(1e-5, 1e-2),
})
def prior(path, shape):
return covered(path, shape) or _structural_defaults(path, shape)
return prior
The dict resolution order is the same as the framework's: explicit
[obs] > [*] > shared > miss.
Source code in src/jaxspec/fit/_parameter.py
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 | |