fitting¶
Gradient-based parameter estimation through the ODE solve, with any optax optimiser. For a task-oriented introduction, see Fit model parameters to data.
from jbubble import FitResult, fit_parameters
from jbubble.fitting import Parameter, unwrap
fit_parameters
¶
fit_parameters(
make_model: Callable[..., tuple[EquationOfMotion, Pulse]],
params0: Any,
*,
loss_fn: Callable[..., ArrayLike],
optimizer: GradientTransformation,
n_steps: int = 200,
conditions: Sequence[Any] | None = None,
save_spec: SaveSpec | None = None,
t_max: ArrayLike | None = None,
config: SolverConfig | None = None,
adjoint: AbstractAdjoint | None = None,
max_backtracks: int = 5,
step_callback: Callable[[int, Any, float], None] | None = None,
log_every: int = 25,
) -> FitResult
Fit model parameters by differentiating through the ODE solve.
fit_parameters minimises the mean loss over the conditions,
where \(\theta\) holds the optimiser's coordinates (see
Parameter), \(\ell\) is loss_fn, and
\(\mathrm{simulate}\) is
run_simulation with save_spec,
t_max, config, and adjoint. Without conditions, \(N = 1\) and
neither make_model nor loss_fn receives a condition. Each step
computes the update \(\Delta\theta\) with optimizer and tries
accepting the first \(\theta_k\) at which every solve converges and both \(L\) and its gradient are finite.
fit_parameters runs a Python loop around compiled functions, so you
can't call it under jax.jit or jax.vmap, and each call compiles
again. For many fits, such as multi-start fits, write the training loop
yourself with unwrap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
make_model
|
callable
|
|
required |
params0
|
Any
|
Initial parameters: a float, a
Everything else is held fixed: integers, booleans, strings,
callables, and Python floats inside an Equinox module. If you set a
Python float inside a module, |
required |
loss_fn
|
callable
|
|
required |
optimizer
|
GradientTransformation
|
For example |
required |
n_steps
|
int
|
Number of accepted steps. Default: |
200
|
conditions
|
list or tuple
|
One entry per experimental condition, for example per driving
pressure or per recording. Each entry can be any pytree, and
|
None
|
save_spec
|
SaveSpec
|
Output sampling. |
None
|
t_max
|
float
|
Integration end time [s]. |
None
|
config
|
SolverConfig
|
ODE solver settings. |
None
|
adjoint
|
AbstractAdjoint
|
How the gradient is computed through the solve. |
None
|
max_backtracks
|
int
|
How many times to halve a step that fails before stopping. If every
halved step fails, the fit warns and returns the last accepted
parameters. Default: |
5
|
step_callback
|
callable
|
|
None
|
log_every
|
int
|
Print progress every |
25
|
Returns:
| Type | Description |
|---|---|
FitResult
|
Fitted parameters, loss history, the simulation at the fitted parameters, and how the fit ended. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
RuntimeError
|
If a solve fails, or the loss or its gradient isn't finite, at
|
Warns:
| Type | Description |
|---|---|
UserWarning
|
If you set a Python float inside an Equinox module in |
RuntimeWarning
|
If every halved step fails and the fit stops early. |
Examples:
import optax
from jbubble import fit_parameters
from jbubble.fitting import Parameter
from jbubble.metrics import normalised_mse_radius
fit = fit_parameters(
lambda p: (make_eom(kappa_s=p["kappa_s"], chi=p["chi"]), pulse),
{
"kappa_s": Parameter(1e-9, lower=0.0), # [N s/m]
"chi": Parameter(0.3, lower=0.0, upper=1.5), # [N/m]
},
loss_fn=lambda r: normalised_mse_radius(r.radius, measured, R0),
optimizer=optax.adam(0.05),
)
Source code in jbubble/fitting.py
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 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 | |
FitResult
¶
FitResult(
params: Any,
loss_history: Array,
result: SimulationResult | list[SimulationResult],
num_rejected: int = 0,
stopped_early: bool = False,
message: str = "",
)
Output of fit_parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
params |
Any
|
Fitted parameters in physical units, with the structure of
|
loss_history |
(Array, shape(n_accepted + 1))
|
|
result |
SimulationResult or list of SimulationResult
|
The simulation at |
num_rejected |
int
|
Number of candidate steps rejected because a solve failed or the loss or gradient wasn't finite. Each rejection halves the step. |
stopped_early |
bool
|
|
message |
str
|
Why the fit ended. |
Parameter
¶
Parameter(
value: ArrayLike,
lower: float | None = None,
upper: float | None = None,
*,
scale: float | None = None,
fixed: bool = False,
)
Bases: Module
A fitted quantity, with optional bounds, a scale, or a fixed value.
The optimiser never updates the physical value \(x\) directly. It updates an unconstrained coordinate \(u\) of order one, and \(x\) follows from \(u\):
where \(s\) is scale. The default scale is \(|x_0|\) without bounds and
the distance from the initial value \(x_0\) to the bound with one bound.
So an optimiser step of 0.05 in \(u\) changes \(x\) by about 5 %, whatever
its units, and one learning rate suits kappa_s near \(10^{-9}\) N s/m and
chi near 0.5 N/m alike. With bounds, \(x\) stays strictly inside them.
Build a Parameter outside jax.jit and jax.vmap: the constructor
checks the value and bounds on concrete numbers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float or array
|
Initial physical value, in SI units. An array is fitted element by element. |
required |
lower
|
float
|
Lower bound. |
None
|
upper
|
float
|
Upper bound. |
None
|
scale
|
float
|
Typical magnitude of \(x\) (no bounds) or of its distance from the
bound (one bound). Required when |
None
|
fixed
|
bool
|
Whether to hold \(x\) at |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
raw |
Array
|
The coordinate \(u\) that the optimiser updates. For a fixed parameter, the value itself. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
kappa_s = Parameter(1e-9, lower=0.0) # positive, log-scaled [N s/m]
chi = Parameter(0.3, lower=0.0, upper=1.5) # bounded [N/m]
R0 = Parameter(2e-6, fixed=True) # held fixed [m]
Source code in jbubble/fitting.py
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 | |
unwrap
¶
Replace every Parameter in tree by its value.
fit_parameters calls this for you
before it calls make_model. Call it yourself in a hand-written training
loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Any
|
Any pytree, such as a dict of |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Source code in jbubble/fitting.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
How a step works¶
fit_parameters evaluates the loss and its gradient in one compiled call, with reverse-mode differentiation through the ODE solve. Each step then does the following:
- Computes an update with
optimizer.update(grads, opt_state, params). - Tries the candidate
params + update. If any solve fails to converge, or the loss or gradient isn't finite, it halves the update and tries again, up tomax_backtrackstimes. - Accepts the first candidate that succeeds. Its loss goes into
loss_history, and its gradient drives the next step.
If every halved update fails, the fit warns, stops, and returns the last accepted parameters. A failed solve during the fit never raises. Only a failure at params0 raises RuntimeError, before the first step.
What gets fitted¶
Leaf of params0 |
Fitted | Coordinate that the optimiser updates |
|---|---|---|
Parameter(x) |
Yes | x / scale |
Parameter(x, lower=a) |
Yes | log((x - a) / scale) |
Parameter(x, upper=b) |
Yes | log((b - x) / scale) |
Parameter(x, lower=a, upper=b) |
Yes | logit((x - a) / (b - a)) |
Parameter(x, fixed=True) |
No | |
Python float or np.float64 in a dict, list, or tuple, or as params0 |
Yes | as Parameter(x) |
| Floating-point JAX or NumPy array, or another NumPy scalar | Yes | the value itself |
| Python float inside an Equinox module | No, with a warning if you set it | |
| Integer, boolean, string, or callable | No |
make_model, loss_fn, step_callback, and FitResult.params all see physical values.
Gradients through the ODE solve¶
solve_eom evaluates the equation of motion through a guard, so a trial step that the adaptive solver rejects, for example one that overshoots a strong collapse to R <= 0, can't make the gradient NaN. With an explicit solver, such as the default Dopri5, the guard leaves the solution unchanged, bit for bit.