#!/usr/bin/env python
# coding: utf-8

# # Sensitivity and the Lorenz Attractor
# 
# Copyright (C) 2026 Andreas Kloeckner
# 
# <details>
# <summary>MIT License</summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# </details>

# In[4]:


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy.integrate import solve_ivp

def log_norm_2(A):
    """
    Logarithmic norm (matrix measure) μ₂(A) = λ_max((A + Aᵀ)/2).
    This is the tightest Lipschitz constant available from the 2-norm:
    ‖e^{At}‖₂ ≤ exp(μ₂(A)·t).
    """
    S = 0.5 * (A + A.T)
    return np.max(np.linalg.eigvalsh(S))



# In[3]:


SIGMA = 10.0
RHO   = 28.0
BETA  = 8.0 / 3.0

def lorenz(t, y):
    x, y_, z = y
    return np.array([
        SIGMA * (y_ - x),
        x * (RHO - z) - y_,
        x * y_ - BETA * z,
    ])

def lorenz_jac(y):
    """Jacobian of the Lorenz vector field at y."""
    x, y_, z = y
    return np.array([
        [-SIGMA,  SIGMA,  0.0  ],
        [RHO - z, -1.0, -x    ],
        [y_,       x,  -BETA  ],
    ])



# In[36]:


T_END      = 20
# T_END      = 80
EPSILON    = 1e-6
# EPSILON    = 1e-2

Y0         = np.array([1.0, 0.0, 0.0])
Y0_PERT    = Y0 + EPSILON * np.array([1.0, 0.0, 0.0])

t_eval = np.linspace(0, T_END, 8000)

print("Integrating reference trajectory …")
sol_ref  = solve_ivp(lorenz, [0, T_END], Y0,      t_eval=t_eval,
                     method='RK45', rtol=1e-10, atol=1e-12)
print("Integrating perturbed trajectory …")
sol_pert = solve_ivp(lorenz, [0, T_END], Y0_PERT, t_eval=t_eval,
                     method='RK45', rtol=1e-10, atol=1e-12)

t = sol_ref.t
Y = sol_ref.y      # shape (3, N)
Yp = sol_pert.y


# In[37]:


fig = plt.figure(figsize=(14,10))
ax3d = plt.gcf().add_subplot(projection='3d')

ax3d.plot(*Y,  lw=0.5, alpha=0.7, label="reference")
ax3d.plot(*Yp, lw=0.5, alpha=0.7, label=f"perturbed (ε={EPSILON:.0e})")
ax3d.scatter(*Y[:, 0],   s=20, zorder=5)
ax3d.scatter(*Yp[:, 0],  s=20, zorder=5)

ax3d.set_xlabel("x", )
ax3d.set_ylabel("y", )
ax3d.set_zlabel("z", )
ax3d.legend(fontsize=7, loc="best")



# In[38]:


separation = np.linalg.norm(Y - Yp, axis=0)
plt.plot(t, separation)


# In[39]:


# (a) Tight bound: integrate μ₂(J(y(t))) along the reference orbit.
#     ‖δy(t)‖ ≤ ε · exp(∫₀ᵗ μ₂(J(y(s))) ds)
print("Computing logarithmic norms along orbit …")
log_norms = np.array([log_norm_2(lorenz_jac(Y[:, i])) for i in range(len(t))])
# Cumulative integral via trapezoidal rule
log_norm_integral = np.zeros_like(t)
log_norm_integral[1:] = np.cumsum(
    0.5 * (log_norms[:-1] + log_norms[1:]) * np.diff(t)
)
bound_tight = EPSILON * np.exp(log_norm_integral)

# (b) Crude bound: use the supremum of μ₂ over the observed orbit.
L_crude = np.max(log_norms)
bound_crude = EPSILON * np.exp(L_crude * t)

print(f"  max log-norm along orbit: {L_crude:.4f}")
print(f"  (compare: largest Lyapunov exponent ≈ 0.906)")



# In[41]:


plt.semilogy(t, separation,     lw=1.5, label="actual ‖δy(t)‖")
plt.semilogy(t, bound_tight,     lw=1.2, ls="--",
             label=r"tight P-L: $\varepsilon\exp\!\left(\int_0^t \mu_2(J)\,ds\right)$")
plt.semilogy(t, bound_crude,      lw=1.0, ls=":",
             label=rf"crude P-L: $\varepsilon\exp(L_\max t)$, $L={L_crude:.2f}$")

plt.xlabel("t")
plt.ylabel("‖y(t) − ŷ(t)‖")
plt.legend(loc="best")


# In[ ]:




