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 |
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
|
energy_grid
|
ArrayLike | None
|
Optional shared grid of energy bin edges in keV ( |
None
|
Source code in src/jaxspec/fit/_bayesian_model.py
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 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | |
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.
Distribution validation makes out-of-support values produce -inf, allowing
external samplers such as AIES, ESS, and MH to reject them.
observation_names
cached
property
¶
List of the observations.
parameter_names
cached
property
¶
List of the free parameter names for the model.
Excludes deterministic sites: numpyro's sample_dist covers both sample
and deterministic site types, so without the filter a tied parameter — or the
per-bin observed_background.<obs> vector of a non-stochastic background —
would be reported as a free coordinate, and dict_to_array /
array_to_dict would build the wrong shape for external samplers.
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. 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.
array_to_dict(theta)
¶
Turn a flat parameter vector into a {name: value} dict.
theta must be ordered by parameter_names, which is sorted and lists
only free sites — tied parameters and the per-bin rate of a non-stochastic
background are derived, so they are absent. Build the vector from
parameter_names rather than from your prior dict's declaration order.
Source code in src/jaxspec/fit/_bayesian_model.py
460 461 462 463 464 465 466 467 468 | |
dict_to_array(dict_of_params)
¶
Inverse of array_to_dict: pack a {name: value} dict into a vector
ordered by parameter_names.
Source code in src/jaxspec/fit/_bayesian_model.py
470 471 472 473 474 475 476 | |
numpyro_model(observed=True)
¶
Sample the prior, evaluate the forward model, register likelihoods.
Thin wrapper around 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
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 | |
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
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | |
prior_samples(key=rng_key(0), num_samples=100)
¶
Sample from the prior distribution.
Returns the free parameters and the deterministic sites. Unlike
parameter_names — which feeds dict_to_array and external samplers,
and so must list only free coordinates — a prior predictive check wants to see
derived quantities such as TiedParameter destinations.
Source code in src/jaxspec/fit/_bayesian_model.py
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |
ForwardModel
¶
Bases: HideUnderscore, 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
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 | |
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 (n_points, energy_grid, spectrum_shared).
derived_quantities(inputs)
¶
Collect bound derived values as deterministically ordered records.
Background owner paths are normalized to their public prior-key form. This layer validates hook names but creates no NumPyro sites.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
dict[str, ArrayLike]
|
Fully resolved parameter paths to values, as for |
required |
Returns:
| Type | Description |
|---|---|
_DerivedQuantity
|
Records containing the model prefix, observation, public owner path, |
...
|
quantity name, and traceable value. |
Source code in src/jaxspec/fit/_forward_model.py
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 | |
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
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 | |
Fitter classes¶
MCMCFitter
¶
Bases: BayesianModelFitter
Fit a spectral model via MCMC sampling (NUTS, AIES, or ESS).
Inherits from 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
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 89 90 91 92 93 94 95 96 97 | |
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
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 89 90 91 92 93 94 95 96 97 | |
VIFitter
¶
Bases: BayesianModelFitter
Source code in src/jaxspec/fit/_fitter/_vi.py
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 | |
fit(rng_key=0, num_steps=10000, optimizer=None, loss=None, num_samples=1000, guide=None, use_transformed_model=True, plot_diagnostics=False, svi_kwargs=None)
¶
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 | None
|
the optimizer to use. Defaults to |
None
|
num_samples
|
int
|
the number of samples to draw. |
1000
|
loss
|
ELBO | None
|
the loss function to use. Defaults to |
None
|
guide
|
AutoGuide | None
|
the guide to use. Defaults to an |
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
|
svi_kwargs
|
dict | None
|
additional arguments to pass to the SVI runner. See [ |
None
|
Returns:
| Type | Description |
|---|---|
FitResult
|
A |
Source code in src/jaxspec/fit/_fitter/_vi.py
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 | |
NSFitter
¶
Bases: BayesianModelFitter
Fit a model using the Nested Sampling algorithm via
jaxns through the
[numpyro.contrib.nested_sampling.NestedSampler][] wrapper.
Because jaxns requires sample-site names to be valid Python identifiers,
this fitter transparently renames sites that contain characters such as
. (e.g. forward.spectrum.MOS1.powerlaw_1.alpha) before passing
the model to the nested sampler, and maps them back afterwards.
Info
Ensure the prior distributions cover a large enough volume for the algorithm to yield proper results.
Source code in src/jaxspec/fit/_fitter/_ns.py
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 | |
fit(rng_key=0, num_samples=1000, num_live_points=1000, plot_diagnostics=False, termination_kwargs=None, constructor_kwargs=None, verbose=True, use_transformed_model=True)
¶
Fit the model to the data using the Phantom-Powered nested sampling algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rng_key
|
int
|
the random key used to initialize the sampler. |
0
|
num_samples
|
int
|
the number of posterior samples to draw. |
1000
|
num_live_points
|
int
|
the number of live points used by the NS algorithm. |
1000
|
plot_diagnostics
|
bool
|
whether to plot the diagnostics of the NS algorithm. |
False
|
termination_kwargs
|
dict | None
|
keyword arguments forwarded to the jaxns termination criterion. |
None
|
constructor_kwargs
|
dict | None
|
extra keyword arguments forwarded to
|
None
|
verbose
|
bool
|
whether to print progress. |
True
|
use_transformed_model
|
bool
|
whether to use the reparameterised model. |
True
|
Returns:
| Type | Description |
|---|---|
FitResult
|
A |
Source code in src/jaxspec/fit/_fitter/_ns.py
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 | |
Prior helpers¶
TiedParameter
¶
Define a parameter as a deterministic transformation of another parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tied_to
|
str
|
Dotted prior key for the source parameter. An optional |
required |
func
|
Transformation applied to the resolved source value. |
required |
Example::
prior = {
"spectrum.powerlaw_1.alpha": dist.Uniform(0, 5),
"spectrum.powerlaw_2.alpha": TiedParameter(
"spectrum.powerlaw_1.alpha", lambda x: 0.5 * x
),
}
Source code in src/jaxspec/fit/_parameter.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
joint_prior_factory(components, joint_dist, *, name=None)
¶
Draw a joint sample and return a lookup for its parameter components.
Call this function inside a callable-prior factory. The returned lookup accepts
a parameter leaf path and returns its component of the joint sample, or None
when the path is not listed in components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
Sequence[str]
|
Ordered user-facing parameter paths. Component |
required |
joint_dist
|
Distribution
|
Distribution whose final event dimension has one entry per component. |
required |
name
|
str | None
|
NumPyro site name. Defaults to the component paths joined by |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[str], ArrayLike | None]
|
A |
Example::
def prior_factory():
joint = joint_prior_factory(
("spectrum.powerlaw_1.alpha", "spectrum.powerlaw_1.norm"),
joint_dist,
)
def prior(path, shape):
value = joint(path)
return value if value is not None else default_prior(path, shape)
return prior
Check explicitly for None: matched values may be traced JAX arrays and cannot
be used as booleans.
Source code in src/jaxspec/fit/_parameter.py
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 | |
dict_prior(prior_dict)
¶
Return a leaf-prior callable backed by prior_dict.
Call this function inside a callable-prior factory. Shared distributions are
sampled immediately and reused across observations. Observation-specific and
wildcard entries return their distribution or fixed value when looked up. Missing
paths return None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior_dict
|
dict
|
Prior values keyed by bare, |
required |
Returns:
| Type | Description |
|---|---|
Callable[[str, tuple], Distribution | ArrayLike | None]
|
A |
Callable[[str, tuple], Distribution | ArrayLike | None]
|
fixed array value, or |
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):
value = covered(path, shape)
return value if value is not None else default_prior(path, shape)
return prior
Keep scopes disjoint. This helper does not validate overlaps and resolves them in
[obs], [*], then bare-key order. Also check results explicitly for None;
matched values may be traced JAX arrays and cannot be used as booleans.
Source code in src/jaxspec/fit/_parameter.py
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 | |