Skip to content

auto_math_lyapunov_stability_2

github-actions[bot] edited this page Jul 20, 2026 · 2 revisions

Snippet from Math-Lyapunov-Stability.md

from compitum.control import LyapunovController

# The real LyapunovController has no shrink_factor/expand_factor to tune --
# those multipliers (*0.8 to shrink, *1.1 to expand) are hardcoded inside
# update(). The genuinely tunable constructor params are kappa and
# integral_gain. There is also no lyapunov_gate()/accept-reject return value;
# update() always executes and returns (eta_cap, status_dict). This adapts
# the "auto-tune" idea to something the real API actually supports: search
# for (kappa, integral_gain) that keep trust_radius inside a target band
# across a noisy trajectory, instead of hunting for a fake acceptance rate.


def auto_tune_factors(trajectory_data):
    """Find (kappa, integral_gain) that keep trust_radius within [0.5, 3.0]
    for the largest fraction of steps.

    Args:
        trajectory_data: List of (E_t, E_tp1) tuples.

    Returns:
        Tuple of (best_kappa, best_integral_gain, in_band_rate).
    """
    best_rate = 0.0
    best_params = None

    for kappa in [0.05, 0.1, 0.2, 0.3]:
        for integral_gain in [0.001, 0.005, 0.01, 0.02]:
            controller = LyapunovController(kappa=kappa, r0=1.0, integral_gain=integral_gain)

            in_band = 0
            for E_t, E_tp1 in trajectory_data:
                d_star = max(E_tp1 - E_t, 0.0)
                _, status = controller.update(d_star, grad_norm=1.0)
                if 0.5 <= status["trust_radius"] <= 3.0:
                    in_band += 1

            in_band_rate = in_band / len(trajectory_data)
            if in_band_rate > best_rate:
                best_rate = in_band_rate
                best_params = (kappa, integral_gain)

    return (best_params if best_params else (0.1, 0.005)), best_rate


# Example usage
trajectory = [(1.0, 0.8), (0.8, 0.6), (0.6, 0.7), (0.7, 0.5), (0.5, 0.4)]
(kappa, integral_gain), rate = auto_tune_factors(trajectory)
print(f"Optimal: kappa={kappa}, integral_gain={integral_gain}, in_band_rate={rate:.1%}")

Clone this wiki locally