Optimization
jaxonomy.optimization
AutoTuner
PID autotuning (without a measurement filter) with constraints in the frequency domain.
Supports only SISO systems.
Supports only continuous-time plants (TODO: extend to discrete-time systems)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plant
|
LeafSystem or a Diagram. If plant is not an LTISystem, operating points x_op and u_op must be provided for linearization. |
required | |
n
|
int, optional Filter coefficient for the continuous-time PID controller |
100
|
|
sim_time
|
float, optional Simulation time for computation of the error metric |
2.0
|
|
metric
|
str, optional Error metric to be minimized. Options are "IAE" and "IE" "IAE": Integral of the absolute error "IE": Integral of the error |
'IAE'
|
|
x_op
|
np.ndarray, optional Operating point of state vector for linearization |
None
|
|
u_op
|
np.ndarray, optional Operating point of control vector for linearization |
None
|
|
pid_gains_0
|
list or Array, optional Initial guess for PID gains [kp, ki, kd] |
[1.0, 10.0, 0.1]
|
|
pid_gains_upper_bounds
|
list or Array, optional Upper bounds for PID gains [kp, ki, kd]. Lower bounds are set to 0 |
None
|
|
Ms
|
float, optional Maximum sensitivity |
100.0
|
|
Mt
|
float, optional Maximum complementary sensitivity |
100.0
|
|
add_filter
|
bool, optional Add measurement filter (currently not implemented) |
False
|
|
method
|
str, optional The method for optimization. Available options are: - "scipy-slsqp" - "scipy-cobyla" - "scipy-trust-constr" - "ipopt" - "nlopt-slsqp" - "nlopt-cobyla" - "nlopt-ld_mma" - "nlopt-isres" - "nlopt-ags" - "nlopt-direct" |
'scipy-slsqp'
|
Notes:
The utilities plot_freq_response, plot_time_response, and
plot_freq_and_time_responses can be used to visualize the frequency and time
responses of the closed-loop system.
Post initialization the tune method should be called to obtain the optimal PID
gains. See notebooks/opt_framework/pid_autotuning.ipynb for an example.
Source code in jaxonomy/optimization/pid_autotuning.py
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 | |
circle_constraint_(kp, ki, kd, omega, c, r)
Deprecated: this is needed for self.constraints_ which is deprecated
and replaced by self.constraints.
Source code in jaxonomy/optimization/pid_autotuning.py
272 273 274 275 276 277 278 279 | |
constraints_(pid_params)
Deprecated: replaced by self.constraints
Source code in jaxonomy/optimization/pid_autotuning.py
281 282 283 284 285 286 287 288 289 290 291 292 | |
CompositeTransform
Bases: Transform
A composite transformation that applies a list of transformations in sequence.
Source code in jaxonomy/optimization/framework/base/transformations.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
ConfidenceIntervalResult
dataclass
Confidence intervals and covariance matrix from the Laplace approximation.
All matrix/array attributes are plain numpy.ndarray for easy inspection
and serialisation.
Attributes
param_names : list[str]
Flat parameter names (array params expanded to "theta[0]", etc.).
opt_params : dict
Optimised parameter values in the original (un-transformed) space.
covariance : ndarray, shape (n, n)
Estimated parameter covariance matrix.
correlation : ndarray, shape (n, n)
Correlation matrix (covariance normalised by marginal standard deviations).
standard_errors : ndarray, shape (n,)
Marginal standard deviations sqrt(diag(covariance)).
confidence_intervals : dict[str, tuple[float, float]]
Per-parameter (lower, upper) bounds in the original space.
Keys match param_names.
confidence_level : float
Nominal confidence level (e.g. 0.95 for 95 %).
z_score : float
Standard-normal quantile corresponding to confidence_level.
hessian : ndarray, shape (n, n)
Hessian of the objective evaluated at the optimum, in the (possibly
transformed) optimisation space.
hessian_eigenvalues : ndarray, shape (n,)
Eigenvalues of the Hessian (ascending).
hessian_condition_number : float
Ratio max|λ| / min|λ|. Large values (> 1 000) signal near-collinear
parameters or an ill-conditioned problem.
is_positive_definite : bool
True when the Hessian was positive definite at the supplied point
(necessary condition for a true local minimum).
residual_variance : float or None
Residual variance σ² used to scale the covariance. None when
n_data was not provided (pure MLE / default).
n_data : int or None
Number of observations used (for least-squares scaling).
objective_value : float
Loss at the optimum.
hessian_method : str
How the Hessian was computed: "AD" (automatic differentiation),
"FD" (finite differences), "provided", or "failed".
message : str
Any warnings raised during computation (empty when all is well).
Source code in jaxonomy/optimization/confidence.py
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 | |
contains(param_name, value)
Return True when value lies within the CI for param_name.
Source code in jaxonomy/optimization/confidence.py
298 299 300 301 | |
interval(param_name)
Return (lower, upper) for a single parameter by name.
Raises KeyError if the name is not found. For array parameters
use the expanded name, e.g. ci.interval("theta[0]").
Source code in jaxonomy/optimization/confidence.py
290 291 292 293 294 295 296 | |
summary()
Return a formatted human-readable summary table.
Source code in jaxonomy/optimization/confidence.py
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 | |
DistributionConfig
dataclass
Structure of attributes for specifying distributions for stochastic variables
Source code in jaxonomy/optimization/framework/base/optimizable.py
61 62 63 64 65 66 67 68 69 70 | |
Evosax
Bases: Optimizer
Population based global optimizers from Evosax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizable
|
Optimizable
|
The optimizable object. |
required |
opt_method
|
str
|
The optimization method to use. See |
'CMA_ES'
|
opt_method_config
|
dict
|
Configuration for the optimization method. |
None
|
pop_size
|
int
|
The population size. |
10
|
num_generations
|
int
|
The number of generations. |
100
|
print_every
|
int
|
Print progress every |
1
|
metrics_writer
|
MetricsWriter | None
|
Optional CSV file to write metrics to. |
None
|
seed
|
int
|
The random seed. |
None
|
Source code in jaxonomy/optimization/framework/optimizers_evosax.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 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 | |
optimize()
Run optimization
Source code in jaxonomy/optimization/framework/optimizers_evosax.py
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 | |
IPOPT
Bases: Optimizer
Interior Point Optimizer (IPOPT) for optimization of the objective function with optional constraints and bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizable
|
Optimizable
|
The optimizable object. |
required |
options
|
dict
|
Options forwarded to
|
{'disp': 5}
|
Source code in jaxonomy/optimization/framework/optimizers_ipopt.py
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 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 | |
optimize()
Run optimisation and return an :class:~jaxonomy.optimization.OptimizationResult.
Gradients of the objective and constraint Jacobians are computed with
JAX automatic differentiation (jax.grad / jax.jacrev).
Hessian strategy — JAX's jax.hessian requires forward-mode
automatic differentiation (jacfwd) through the gradient, but the
jaxonomy ODE solver uses custom_vjp which only supports
reverse-mode. Attempting to compute jax.hessian of a simulation
objective therefore raises a runtime error. IPOPT is instead
configured with hessian_approximation = "limited-memory" (L-BFGS
approximation) which only requires first-order gradient information and
converges super-linearly. For problems where you know the objective
is twice-differentiable and do not use the jaxonomy ODE integrator you
can override this by passing options={"hessian_approximation":
"exact", ...} and providing hess via the _hess_fn constructor
argument.
Source code in jaxonomy/optimization/framework/optimizers_ipopt.py
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 | |
IdentityTransform
Bases: Transform
A transformation that does nothing: y = x.
Source code in jaxonomy/optimization/framework/base/transformations.py
50 51 52 53 54 55 56 57 58 59 | |
LogTransform
Bases: Transform
A transformation that applies the natural logarithm to the values of the parameters.
y = log(x).
Source code in jaxonomy/optimization/framework/base/transformations.py
62 63 64 65 66 67 68 69 70 71 72 | |
LogitTransform
Bases: Transform
The logit transformation, defined as:
y = log(x / (1 - x))
Source code in jaxonomy/optimization/framework/base/transformations.py
115 116 117 118 119 120 121 122 123 124 125 | |
MultiStart
Multi-start wrapper for any jaxonomy optimizer.
Runs n_starts optimizations from different initial points and returns
all results as well as the best one (lowest final_loss).
Parameters
optimizable : Optimizable
The problem to optimize. Must be a jaxonomy Optimizable instance.
optimizer_factory : Callable[[Optimizable], Optimizer]
A factory function that takes an Optimizable (potentially with
different initial parameters) and returns a ready-to-run optimizer.
Example::
factory = lambda opt: Scipy(opt, "L-BFGS-B",
opt_method_config={"maxiter": 40},
use_autodiff_grad=True)
ms = MultiStart(optimizable, factory, n_starts=8, seed=0)
result = ms.run()
int
Number of random restarts (default 10).
init_sampler : Callable or None
Custom sampling function with signature
(n_starts: int, params_0_flat: np.ndarray) -> np.ndarray
returning an array of shape (n_starts, n_params).
Row 0 is always replaced with the original params_0_flat when
include_initial=True. If None (default), uniform sampling
around params_0 is used.
sample_scale : float
Scale factor for the default uniform sampler. The search window
for each parameter is
[p0 ± sample_scale * max(|p0|, 1)] (default 1.0).
seed : int or None
Random seed for reproducibility.
include_initial : bool
When True (default), the first start always uses the original
params_0, regardless of the sampler output.
Source code in jaxonomy/optimization/multi_start.py
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 | |
results
property
Results from the last :meth:run call (empty before first run).
run()
Execute all starts sequentially and return a :class:MultiStartResult.
Each start clones the optimizable with a new params_0_flat, calls
optimizer_factory(clone) to get a fresh optimizer, and runs
optimizer.optimize(). Failed starts (exceptions) are recorded as
unsuccessful OptimizationResult entries with success=False.
Returns
MultiStartResult
Source code in jaxonomy/optimization/multi_start.py
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 | |
MultiStartResult
dataclass
Results from a multi-start optimization run.
Attributes:
| Name | Type | Description |
|---|---|---|
results |
list[OptimizationResult]
|
All |
best_result |
OptimizationResult
|
The result with the lowest |
best_start_index |
int
|
Index into |
n_starts |
int
|
Total number of starts attempted. |
n_successful |
int
|
Number of starts that reported |
Source code in jaxonomy/optimization/multi_start.py
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 | |
NLopt
Bases: Optimizer
Optimizers using the NLopt library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizable
|
Optimizable
|
The optimizable object. |
required |
opt_method
|
str
|
The optimization method to use. |
required |
ftol_rel
|
float
|
Relative tolerance on function value. |
1e-06
|
ftol_abs
|
float
|
Absolute tolerance on function value. |
1e-06
|
xtol_rel
|
float
|
Relative tolerance on optimization parameters. |
1e-06
|
xtol_abs
|
float
|
Absolute tolerance on optimization parameters. |
1e-06
|
cons_tol
|
float
|
Tolerance on constraints. |
1e-06
|
maxeval
|
int
|
Maximum number of function evaluations. |
500
|
maxtime
|
float
|
Maximum time in seconds. |
0
|
Source code in jaxonomy/optimization/framework/optimizers_nlopt.py
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 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 | |
optimize()
Run optimization
Source code in jaxonomy/optimization/framework/optimizers_nlopt.py
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 | |
NegativeNegativeLogTransform
Bases: Transform
A transformation that applies the negative of the natural logarithm of the negative
of the values of the parameters.
y = -log(-x)
Source code in jaxonomy/optimization/framework/base/transformations.py
75 76 77 78 79 80 81 82 83 84 85 86 | |
NormalizeTransform
Bases: Transform
A transformation that normalizes the values of the parameters to the range [0, 1].
y = (x - min) / (max - min)
Paramteters:
- params_min: dict with the minimum values for each parameter.
- params_max: dict with the maximum values for each parameter.
Source code in jaxonomy/optimization/framework/base/transformations.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
Optax
Bases: Optimizer
Optax optimizer without support for stochastic variables.
Paramters
optimizable (Optimizable):
The optimizable object.
opt_method (str):
The optimization method to use.
learning_rate (float):
The learning rate.
opt_method_config (dict):
Configuration for the optimization method.
num_epochs (int):
The number of epochs.
clip_range (tuple):
The range to clip the gradients.
print_every (int):
Print progress every print_every epochs.
metrics_writer (MetricsWriter|None):
Optional CSV file to write metrics to.
Source code in jaxonomy/optimization/framework/optimizers_optax.py
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 | |
optimize()
Run optimization
Source code in jaxonomy/optimization/framework/optimizers_optax.py
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 | |
step(params, opt_state)
Take a single optimization step
Source code in jaxonomy/optimization/framework/optimizers_optax.py
309 310 311 312 313 314 315 316 | |
OptaxWithStochasticVars
Bases: Optimizer
Optax optimizer with support for stochastic variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizable
|
OptimizableWithStochasticVars
|
The optimizable object. |
required |
opt_method
|
str
|
The optimization method to use. |
required |
learning_rate
|
float
|
The learning rate. |
required |
opt_method_config
|
dict
|
Configuration for the optimization method. |
required |
num_epochs
|
int
|
The number of epochs. |
100
|
batch_size
|
int
|
The batch size. |
1
|
num_batches
|
int
|
The number of batches. |
1
|
clip_range
|
tuple
|
The range to clip the gradients. |
None
|
print_every
|
int
|
Print progress every |
None
|
metrics_writer
|
MetricsWriter | None
|
Optional CSV file to write metrics to. |
None
|
Source code in jaxonomy/optimization/framework/optimizers_optax.py
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 | |
batched_objective_flat(params, stochastic_vars_batch_flat)
Mean of the objective function over a batch
Source code in jaxonomy/optimization/framework/optimizers_optax.py
143 144 145 146 147 | |
optimize()
Run optimization
Source code in jaxonomy/optimization/framework/optimizers_optax.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 | |
step(params, opt_state, stochastic_vars_batch)
Take a single optimization step over one batch
Source code in jaxonomy/optimization/framework/optimizers_optax.py
149 150 151 152 153 154 155 156 157 158 159 160 | |
Optimizable
Bases: OptimizableBase
Base class for all optimizables with no stochastic variables.
For parameters, see OptimizableBase.
The abstract method prepare_context should update the context to incorporate the
optimization parameters.
This classs creates methods for evaluation of the objective and constraints from the concrete implementation of the abstract methods. This class also creates methods for batched evaluation of the objective and constraints, which are useful for optimizers that can work with batches (eg. Optax), and population-based optimizers.
Source code in jaxonomy/optimization/framework/base/optimizable.py
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 | |
constraints(params)
Constraints function for optimization with dict parameters input
Source code in jaxonomy/optimization/framework/base/optimizable.py
331 332 333 334 335 336 | |
constraints_flat(params)
Constraints function for optimization with flattened parameters input
Source code in jaxonomy/optimization/framework/base/optimizable.py
327 328 329 | |
objective(params)
Objective function for optimization with dict parameters input
Source code in jaxonomy/optimization/framework/base/optimizable.py
320 321 322 323 324 325 | |
objective_flat(params)
Objective function for optimization with flattened parameters input
Source code in jaxonomy/optimization/framework/base/optimizable.py
316 317 318 | |
prepare_context(context, params)
abstractmethod
Model-specific updates to incorporate the sample data and parameters. Return the updated context.
Source code in jaxonomy/optimization/framework/base/optimizable.py
299 300 301 302 303 304 305 | |
run_simulation(params)
Run simulation and return final results context.
Source code in jaxonomy/optimization/framework/base/optimizable.py
307 308 309 310 311 312 313 314 | |
OptimizableWithStochasticVars
Bases: OptimizableBase
Base class for all optimizables with stochastic variables. This is designed only for Optax optimizers and without constraints. Other optimizers are unlikely to work well with stochastic variables.
This class is similar to Optimizable with the key difference that both params
and vars (stochastic variables) need to be updated as opposed to params alone
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vars_0
|
dict
Initial stochastic variable values. If not provided, the
|
None
|
|
distribution_config_vars
|
DistributionConfig Configuration for stochastic variables. If not provided, standard normal distribution is used. |
None
|
Source code in jaxonomy/optimization/framework/base/optimizable.py
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 | |
generate_batches(data, num_batches, batch_size)
Given all samples data, generate num_batches random batches of size
batch_size each
Source code in jaxonomy/optimization/framework/base/optimizable.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
objective(params, vars)
Objective function for optimization with dict parameters and vars input
Source code in jaxonomy/optimization/framework/base/optimizable.py
441 442 443 444 445 446 | |
objective_flat(params, vars)
Objective function for optimization with flattened parameters and vars input
Source code in jaxonomy/optimization/framework/base/optimizable.py
433 434 435 436 437 438 439 | |
prepare_context(context, params, vars)
abstractmethod
Model-specific updates to incorporate the parameters and stochastic vars. Return the updated context.
Source code in jaxonomy/optimization/framework/base/optimizable.py
410 411 412 413 414 415 416 | |
run_simulation(params, vars)
Run simulation and return final results context.
Source code in jaxonomy/optimization/framework/base/optimizable.py
426 427 428 429 430 431 | |
sample_random_vars(num_samples)
Generate random samples of the stochastic variables
Source code in jaxonomy/optimization/framework/base/optimizable.py
448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
stochastic_vars(context)
abstractmethod
Extract stochastic vars from the context.
These should be in the form of a dict of Pytrees.
Source code in jaxonomy/optimization/framework/base/optimizable.py
418 419 420 421 422 423 424 | |
OptimizationResult
dataclass
Unified result returned by all jaxonomy optimizers.
Supports dict-like access (result["param"]) for backward compatibility
with code that treated the old return value as a plain parameter dict.
Attributes:
| Name | Type | Description |
|---|---|---|
params |
dict[str, Any]
|
dict mapping parameter name → optimized value (same as the dict that optimizers used to return directly). |
success |
bool
|
|
nit |
int
|
Number of iterations (or epochs / generations). |
nfev |
int
|
Number of objective-function evaluations. |
message |
str
|
Human-readable status message from the optimizer. |
final_loss |
float | None
|
Objective value at the optimum. |
loss_history |
list[float]
|
Sequence of objective values recorded during optimization (one per epoch / generation). |
Source code in jaxonomy/optimization/framework/base/optimizer.py
8 9 10 11 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 67 68 69 70 71 72 73 74 75 76 77 78 | |
RLEnv
Bases: Env
Base class for reinforcement learning environments in Jaxonomy.
Source code in jaxonomy/optimization/rl_env.py
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 | |
get_done(pipeline_state, obs)
Return a boolean indicating whether the episode is done.
Source code in jaxonomy/optimization/rl_env.py
146 147 148 | |
get_reward(pipeline_state, obs, act)
abstractmethod
Return the reward for the current state and observation.
Source code in jaxonomy/optimization/rl_env.py
139 140 141 142 143 144 | |
randomize(pipeline_state, rng)
Randomize the initial states, parameters, etc.
Source code in jaxonomy/optimization/rl_env.py
150 151 152 | |
render(trajectory, height=240, width=320, camera=None)
Render the trajectory
Source code in jaxonomy/optimization/rl_env.py
154 155 156 157 158 159 160 161 162 163 164 | |
Scipy
Bases: Optimizer
Scipy/JAX-scipy optimizers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizable
|
Optimizable
|
The optimizable object. |
required |
opt_method
|
str
|
The optimization method to use. |
required |
tol
|
float
|
Tolerance for termination. For detailed control, use |
None
|
opt_method_config
|
dict
|
Configuration for the optimization method. |
None
|
use_autodiff_grad
|
bool
|
Whether to use autodiff for gradient computation. |
True
|
use_jax_scipy
|
bool
|
Whether to use JAX's version of |
False
|
Source code in jaxonomy/optimization/framework/optimizers_scipy.py
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 | |
optimize()
Run optimization
Source code in jaxonomy/optimization/framework/optimizers_scipy.py
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 | |
SensitivityResult
dataclass
Result of a parameter sensitivity / identifiability analysis.
All arrays are plain numpy.ndarray for easy inspection.
Attributes
param_names : list[str]
Parameter names, in the same order as the flat parameter vector.
params_0 : dict[str, Any]
The parameter values at which the analysis was performed.
objective_value : float
Objective value at params_0.
gradients : ndarray, shape (n_params,)
Gradient of the objective w.r.t. each parameter.
normalized_sensitivity : ndarray, shape (n_params,)
|p_i * ∂L/∂p_i| — relative sensitivity. Dimensionless and
comparable across parameters with different scales.
hessian : ndarray, shape (n_params, n_params)
Hessian of the objective (FIM approximation). NaN-filled when
compute_hessian=False.
hessian_diagonal : ndarray, shape (n_params,)
Diagonal of the Hessian.
eigenvalues : ndarray, shape (n_params,)
Eigenvalues of the Hessian (ascending).
condition_number : float
Ratio of largest to smallest non-negligible eigenvalue. Large values
(> 1e6) indicate near-collinear parameters.
unidentifiable_params : list[str]
Parameter names whose normalised sensitivity is below
sensitivity_threshold * max_sensitivity.
sensitivity_threshold : float
Relative threshold used to flag unidentifiable parameters.
Source code in jaxonomy/optimization/sensitivity.py
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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
summary()
Return a human-readable summary table.
Source code in jaxonomy/optimization/sensitivity.py
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 | |
Trainer
Base class for optimizing model parameters via simulation.
Should probably get a more descriptive name once we're doing other kinds of training...
Source code in jaxonomy/optimization/training.py
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 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 | |
evaluate_cost(context)
abstractmethod
Model-specific cost function, evaluated on final context
Source code in jaxonomy/optimization/training.py
91 92 93 94 | |
make_forward(start_time, stop_time)
Create a generic forward pass through the simulation, returning loss
Source code in jaxonomy/optimization/training.py
96 97 98 99 100 101 102 103 104 105 106 | |
make_loss_fn(forward, params)
Create a loss function based on a forward pass of the simulation
params here can be any PyTree - it will get flattened to a single array
Source code in jaxonomy/optimization/training.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
optimizable_parameters(context)
abstractmethod
Extract optimizable model-specific parameters from the context.
These should be in the form of a PyTree (e.g. tuple, dict, array, etc)
and should be the first arguments to prepare_context.
Source code in jaxonomy/optimization/training.py
72 73 74 75 76 77 78 79 | |
prepare_context(context, *data, key=None)
abstractmethod
Model-specific updates to incorporate the sample data and parameters.
data should be the combination of the output of optimizable_parameters
along with all the per-simulation "training data". Parameters will
update once per epoch, and training data will update once per sample.
Source code in jaxonomy/optimization/training.py
81 82 83 84 85 86 87 88 89 | |
train(training_data, sim_start_time, sim_stop_time, epochs=100, key=None, params=None, opt_state=None)
Run the optimization loop over the training data
Source code in jaxonomy/optimization/training.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 | |
Transform
Bases: ABC
Base class for transformations.
Source code in jaxonomy/optimization/framework/base/transformations.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
inverse_transform(params)
abstractmethod
Take transformed parameters dict {key:value} and output a dict with identical
keys but inverse-transformed values.
Source code in jaxonomy/optimization/framework/base/transformations.py
22 23 24 25 26 27 28 | |
transform(params)
abstractmethod
Take original parameters dict {key:value} and output a dict with identical keys
but transformed values.
Source code in jaxonomy/optimization/framework/base/transformations.py
14 15 16 17 18 19 20 | |
TuningResult
dataclass
Result of a tune_parameters call.
Attributes:
| Name | Type | Description |
|---|---|---|
params |
Dict[str, Array]
|
Optimal parameter values as a dict {name: jax.Array}. |
objective |
float
|
Final objective value (scalar). |
history |
list
|
List of (iteration, objective) tuples if tracking enabled. |
success |
bool
|
True if the optimizer reported successful convergence. |
message |
str
|
Human-readable status from the underlying optimizer. |
raw |
Optional[OptimizationResult]
|
Underlying |
Source code in jaxonomy/optimization/parameter_tuning.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
compute_confidence_intervals(optimizable, opt_params, confidence_level=0.95, n_data=None, hessian=None, eps_fd=0.0001, regularize=True)
Compute Wald-type confidence intervals for optimised parameters.
Uses the Laplace approximation: the parameter posterior is approximated
as a Gaussian centred at the optimum θ* with covariance H⁻¹, where
H = ∇²L(θ*) is the Hessian of the loss.
Parameters
optimizable : Optimizable
The jaxonomy optimizable whose objective_flat is used.
opt_params : OptimizationResult | dict | array-like
Optimised parameters at which to evaluate the Hessian. Can be:
* An :class:`~jaxonomy.optimization.OptimizationResult` returned by
any jaxonomy optimizer — the ``params`` dict is extracted and
flattened automatically.
* A plain ``dict`` mapping parameter names to values.
* A flat 1-D array matching ``optimizable.params_0_flat``.
confidence_level : float
Nominal confidence level (default 0.95 for 95 % CIs).
n_data : int or None
Number of observations. When provided, the covariance is scaled by
the residual variance estimate
``σ² = 2 · L(θ*) / max(n_data − n_params, 1)``
This is appropriate for **sum-of-squares objectives**
``L = ½ Σ rᵢ²``. For maximum-likelihood objectives leave ``None``.
hessian : ndarray or None
Pre-computed Hessian matrix (e.g. from :func:compute_sensitivity).
When None (default) the Hessian is computed automatically using
JAX AD (with a finite-difference fallback for ODE-based objectives).
eps_fd : float
Step size used for the finite-difference Hessian fallback (default
1e-4). Ignored when hessian is provided or when AD succeeds.
regularize : bool
When True (default), negative eigenvalues of the Hessian are
clipped to a small positive value before inversion. This makes the
covariance well-defined even when the supplied point is not a true
local minimum. A warning is recorded in result.message.
Returns
ConfidenceIntervalResult Dataclass containing the covariance matrix, standard errors, and per-parameter confidence intervals in the original (physical) parameter space.
Notes
Parameter transformations: if the Optimizable uses a
transformation (e.g. :class:LogTransform), the Hessian is computed
in the transformed space and the resulting CI bounds are mapped back to
the original space via transformation.inverse_transform.
Validity: the Laplace approximation requires the objective to be
smooth and the optimum to be a true interior local minimum (positive-
definite Hessian). If is_positive_definite is False in the
result, the CIs are computed but should be treated with caution.
Profile likelihood: the Laplace approximation is a first-order Gaussian approximation. For strongly nonlinear models or highly non-Gaussian posteriors, profile likelihood confidence intervals are more accurate but require repeated re-optimisation.
Examples
from jaxonomy.optimization import Scipy, compute_confidence_intervals opt = Scipy(my_opt, method="L-BFGS-B", use_autodiff_grad=True) result = opt.optimize() ci = compute_confidence_intervals(my_opt, result, confidence_level=0.95) print(ci.summary()) lo, hi = ci.interval("c")
Source code in jaxonomy/optimization/confidence.py
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 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 | |
compute_sensitivity(optimizable, params_0_flat=None, sensitivity_threshold=0.001, compute_hessian=True)
Compute gradient-based parameter sensitivity at a given operating point.
Uses JAX automatic differentiation — no finite differences, no extra simulations beyond two JIT-compiled evaluations (gradient + optional Hessian).
Parameters
optimizable : Optimizable
The jaxonomy optimizable whose objective_flat is differentiated.
params_0_flat : array-like or None
Flat parameter vector to evaluate at. Defaults to
optimizable.params_0_flat.
sensitivity_threshold : float
Relative threshold (0–1) for flagging parameters as low-sensitivity.
A parameter is flagged when its normalised sensitivity is less than
sensitivity_threshold × max(all normalised sensitivities).
Default 1e-3.
compute_hessian : bool
Whether to compute the full Hessian / FIM. Can be expensive for
many parameters (O(n²) simulations). Default True.
Returns
SensitivityResult
Source code in jaxonomy/optimization/sensitivity.py
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 | |
implicit_solver(solver, residual, linear_solve=None)
Make an iterative solver reverse-mode differentiable via the IFT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solver
|
Callable
|
|
required |
residual
|
Callable
|
|
required |
linear_solve
|
Optional[Callable]
|
optional |
None
|
Returns:
| Type | Description |
|---|---|
|
A function |
|
|
to |
Example — an implicit velocity law solved by Newton iteration::
def solve_v(theta): # while_loop inside
def newton(v):
g = v + jnp.tanh(theta * v) - 1.0
dg = 1.0 + theta / jnp.cosh(theta * v) ** 2
return v - g / dg
def cond(carry):
v, i = carry
return (jnp.abs(v + jnp.tanh(theta * v) - 1.0) > 1e-12) & (i < 50)
def body(carry):
v, i = carry
return newton(v), i + 1
v, _ = jax.lax.while_loop(cond, body, (jnp.asarray(0.5), 0))
return v
def residual(v, theta):
return v + jnp.tanh(theta * v) - 1.0
solve_v_diff = implicit_solver(solve_v, residual)
jax.grad(solve_v_diff)(0.3) # works; matches FD
Source code in jaxonomy/optimization/implicit.py
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 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 | |
ise_objective(builder, signal_port, reference_port=None, weight=1.0, initial_cost=0.0, name='ise')
Add blocks to compute the Integral of Squared Error (ISE).
.. math::
J = \int_0^T w \, \| \text{signal}(t) - \text{reference}(t) \|^2 \, dt
When reference_port is None the reference is implicitly zero, so
the objective is :math:\int_0^T w \, \|\text{signal}(t)\|^2 \, dt.
The function adds the following blocks to builder:
- (optional) :class:
~jaxonomy.library.Addercomputingsignal − reference - :class:
~jaxonomy.library.Power(2.0) - :class:
~jaxonomy.library.SumOfElements(handles both scalar and vector signals transparently) - (optional) :class:
~jaxonomy.library.Gainifweight ≠ 1 - :class:
~jaxonomy.library.Integratoraccumulating the cost
Parameters
builder:
The :class:~jaxonomy.DiagramBuilder to add blocks to.
signal_port:
Output port of the signal to penalise.
reference_port:
Output port of the reference signal. None → reference is 0.
weight:
Scalar multiplier applied to the squared norm before integration.
For per-component or matrix weighting use :func:lqr_objective.
initial_cost:
Initial value of the accumulating integrator (default 0.0).
name:
Name prefix for the added blocks.
Returns
OutputPort Scalar port whose value at the end of simulation equals J.
Examples
Minimise oscillation energy of a spring-mass system::
obj = ise_objective(b, x.output_ports[0]) # ∫ x² dt
# later: return obj.eval(ctx)
Multi-signal ISE with a shared reference of zero::
cost_x = ise_objective(b, x.output_ports[0], name="ise_x")
cost_v = ise_objective(b, v.output_ports[0], name="ise_v")
total = weighted_sum(b, [cost_x, cost_v], weights=[1.0, 0.5])
Source code in jaxonomy/optimization/objectives.py
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 | |
lqr_objective(builder, state_port, Q, control_port=None, R=None, initial_cost=0.0, name='lqr')
Add blocks to compute an LQR-style quadratic cost.
.. math::
J = \int_0^T \bigl( x(t)^\top Q\, x(t) \;+\; u(t)^\top R\, u(t) \bigr)\, dt
When control_port or R is None only the state cost
:math:\int x^\top Q x\, dt is computed.
The function adds a single-input :class:~jaxonomy.library.ReduceBlock
for :math:x^\top Q x (and optionally one for :math:u^\top R u), an
optional :class:~jaxonomy.library.Adder, and an
:class:~jaxonomy.library.Integrator.
Parameters
builder:
The :class:~jaxonomy.DiagramBuilder to add blocks to.
state_port:
Output port of the state vector :math:x.
Q:
Positive semi-definite state weight matrix, shape (nx, nx).
control_port:
Output port of the control vector :math:u. None → no control
penalty.
R:
Positive definite control weight matrix, shape (nu, nu).
Required when control_port is provided.
initial_cost:
Initial value of the accumulating integrator (default 0.0).
name:
Name prefix for the added blocks.
Returns
OutputPort Scalar port whose value at the end of simulation equals J.
Examples
Pendulum regulation::
# ∫ θ²·Q[0,0] + ω²·Q[1,1] dt (diagonal Q)
Q = jnp.diag(jnp.array([10.0, 1.0]))
R = jnp.array([[0.1]])
cost = lqr_objective(b, x.output_ports[0], Q, u.output_ports[0], R)
Source code in jaxonomy/optimization/objectives.py
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 | |
tracking_mse(builder, signal_port, t_data, y_data, weight=1.0, interpolation='linear', initial_cost=0.0, name='tracking_mse')
Add blocks to compute the dataset tracking MSE.
Computes
.. math::
J = \int_0^T w \, \| \text{signal}(t) - y_{\text{ref}}(t) \|^2 \, dt
where :math:y_{\text{ref}}(t) is the reference signal interpolated
from the dataset (t_data, y_data) at every simulation time step.
The function wires:
- :class:
~jaxonomy.library.Clock→ current simulation time - :class:
~jaxonomy.library.LookupTable1d→ interpolated reference - :func:
ise_objective→ squared error integrator
Parameters
builder:
The :class:~jaxonomy.DiagramBuilder to add blocks to.
signal_port:
Output port of the simulated signal to compare against the data.
t_data:
1-D array of reference time points (must be strictly increasing).
y_data:
Array of reference values. Shape (N,) for scalar signals or
(N, ny) for vector signals. Extrapolation clamps to the
nearest endpoint value.
weight:
Scalar multiplier applied before integration.
interpolation:
Interpolation method passed to :class:~jaxonomy.library.LookupTable1d:
"linear" (default), "nearest", or "flat".
initial_cost:
Initial value of the integrator.
name:
Name prefix for the added blocks.
Returns
OutputPort Scalar port equal to J at the end of simulation.
Examples
Fit a model to measured step-response data::
import numpy as np
t_meas = np.linspace(0, 5, 50)
y_meas = 1 - np.exp(-t_meas) # first-order step response
cost = tracking_mse(b, plant.output_ports[0], t_meas, y_meas)
Source code in jaxonomy/optimization/objectives.py
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 | |
tune_parameters(diagram, base_context, sim_t_span, params_0, set_params, objective_fn, bounds=None, optimizer='scipy-lbfgs', n_iter=100, learning_rate=0.05, sim_options=None, verbose=True)
Tune scalar parameters of a jaxonomy diagram to minimize an objective.
The simulator is differentiated through using JAX autodiff; the gradient
of objective_fn with respect to each entry of params_0 is computed
automatically, and an optimizer minimizes the objective.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diagram
|
A built jaxonomy diagram. |
required | |
base_context
|
A |
required | |
sim_t_span
|
Tuple[float, float]
|
|
required |
params_0
|
Dict[str, Any]
|
Dict of initial parameter values. Each value must be a scalar or a JAX-compatible array. |
required |
set_params
|
Callable[[Any, Dict[str, Array]], Any]
|
Callback |
required |
objective_fn
|
Callable[[Any], Array]
|
Callback |
required |
bounds
|
Optional[Dict[str, Tuple[float, float]]]
|
Optional dict |
None
|
optimizer
|
str
|
Optimizer alias or scipy method name. Defaults to
"scipy-lbfgs". See |
'scipy-lbfgs'
|
n_iter
|
int
|
Maximum number of optimizer iterations. |
100
|
learning_rate
|
float
|
Learning rate for optax optimizers (ignored by scipy). |
0.05
|
sim_options
|
Optional[SimulatorOptions]
|
Optional |
None
|
verbose
|
bool
|
If True, log progress to the jaxonomy logger. |
True
|
Returns:
| Type | Description |
|---|---|
TuningResult
|
A |
TuningResult
|
and a reference to the raw optimizer result. |
Notes
- Discrete parameters (e.g., a horizon length
N, a state-machine guard threshold) are not differentiable through the simulator and should be left as fixed hyperparameters. If you need to sweep them, wraptune_parametersin an outer loop or grid search. - Saturation regions (
jnp.clip,jax.lax.condwith hard switches) have zero gradient. Tuning parameters whose value determines a saturation region may be impossible from a starting point already saturated; consider warm-starting away from the saturation boundary. - Bounds enforcement: with
scipy-lbfgs/slsqp/trust-constr, bounds are honoured by the solver. Withoptaxoptimizers, bounds are not enforced; clip parameters yourself inset_paramsif you need them.
See also
jaxonomy.optimization.Optimizable — the lower-level interface this
function wraps. Use it directly if you need stochastic variables,
constraints, or batched evaluations.
Source code in jaxonomy/optimization/parameter_tuning.py
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 | |
weighted_sum(builder, objectives, weights=None, name='total_cost')
Combine multiple objective ports into a weighted sum.
.. math::
J_{\text{total}} = \sum_{i} w_i \, J_i
Parameters
builder:
The :class:~jaxonomy.DiagramBuilder to add blocks to.
objectives:
Sequence of scalar output ports, one per term.
weights:
Scalar weights :math:w_i. None → uniform weight 1.0.
Must have the same length as objectives when provided.
name:
Name of the final :class:~jaxonomy.library.Adder block (and prefix
for :class:~jaxonomy.library.Gain blocks when weights differ from 1).
Returns
OutputPort
Scalar port equal to :math:J_{\text{total}}.
Raises
ValueError If objectives is empty or weights has a different length.
Examples
Combine two ISE objectives with different priorities::
cost_pos = ise_objective(b, x.output_ports[0], name="ise_x")
cost_vel = ise_objective(b, v.output_ports[0], name="ise_v")
total = weighted_sum(b, [cost_pos, cost_vel], weights=[10.0, 1.0])
Source code in jaxonomy/optimization/objectives.py
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 | |