Module contents
Lesson 27 of 27Research 110 min

Frontier II: differentiable simulation, hybrid solvers and equation discovery

Combine learned models and solvers through differentiable simulation and solver-in-the-loop corrections, discover equations with SINDy, and critically examine learned weather forecasting.

After this lesson you can

  • Write a differentiable PDE solver in PyTorch and obtain gradients of initial conditions and parameters for design or control.
  • Train a neural correction inside a coarse solver with multi-step unrolling and explain its comparison to one-step training.
  • Discover dynamical equations with SINDy and STLSQ and evaluate robustness to noise and library choice.
  • Explain learned weather models, reanalysis, autoregressive forecasts, ensembles and their limitations against numerical prediction.
  • Design a fair experiment comparing a hybrid method with a classical solver at equal cost.

Before you start

Differentiating through a simulation

Rather than asking a network to replace an equation entirely, we can combine a known numerical step with learnable parameters. Differentiable simulation executes a program computing un+1=Fθ(un)u_{n+1}=F_\theta(u_n) and permits differentiation of an objective with respect to θ\theta or the initial state. For a horizon of TT steps, the chain rule multiplies the Jacobians of those steps. This is backpropagation through time applied to a simulator; it calculates the derivative of the discretized algorithm, not an automatic guarantee about the continuous PDE.

For periodic Burgers we use

ut+∂x(u2/2)=νuxx+fθ(x),fθ(x)=θ1sin⁡x+θ2cos⁡(2x).u_t+\partial_x(u^2/2)=\nu u_{xx}+f_\theta(x), \qquad f_\theta(x)=\theta_1\sin x+\theta_2\cos(2x).

The lab computes spatial derivatives with FFT, filters nonlinearity by the two-thirds rule and advances with RK4. The time step is fixed before differentiation and must satisfy stability restrictions. Boundary conditions, transforms, filters and floating-point operations are part of the differentiated model. Comparison with an adjoint gradient or finite differences must refer to the same discretization and parametrization.

InteractiveControl a PDE with gradients
  • Target
  • Final state

Control: periodic Burgers, 160 RK4 steps and two forcing modes. The second plot shows the chaotic logistic-map derivative; its peaks depend on the trajectory and do not guarantee monotonic growth.

Target profile
0
20
Regularized objective0.20431
Sine coefficient0.000
log10 sensitivity6.08
Choose one of two manufactured targets and browse real optimizations. Sensitivity of a chaotic map is shown as a separate example.

In this test the target is generated with the same solver being optimized: it is a controlled check, not validation against a physical installation. Two forcing coefficients are fitted over 40 iterations and a small quadratic penalty is added. The autograd directional gradient was approximately −0.37298364655-0.37298364655, versus −0.37298364655-0.37298364655 by centered difference in the tested direction. The test detects implementation errors at that point and step; it does not guarantee global optimization or validity for other discretizations.

Saving every state for the backward pass requires memory growing with horizon. Checkpointing retains some and recomputes intermediate states, trading compute for memory. In systems sensitive to initial conditions, products of Jacobians can grow or shrink rapidly. The figure uses logistic map xn+1=4xn(1−xn)x_{n+1}=4x_n(1-x_n) to illustrate this: it is a separate chaotic system, not a claim that this unforced viscous Burgers system is chaotic. Growth depends on trajectory and need not be monotonic at every step.

To see the connection with the discrete adjoint, consider terminal objective J=ℓ(uT)J=\ell(u_T) and parameters shared at each step. If An=∂Fθ(un)/∂unA_n=\partial F_\theta(u_n)/\partial u_n and Bn=∂Fθ(un)/∂θB_n=\partial F_\theta(u_n)/\partial\theta, define λT=∇ℓ(uT)\lambda_T=\nabla\ell(u_T) and traverse backward λn=An⊤λn+1\lambda_n=A_n\T\lambda_{n+1}. Then

∇θJ=∑n=0T−1Bn⊤λn+1.\nabla_\theta J=\sum_{n=0}^{T-1}B_n\T\lambda_{n+1}.

If the objective contains intermediate costs or directly depends on θ\theta, their derivatives must be added. Autograd performs this chain for operations actually executed. If an adaptive step changes branch, a projection is nonsmooth or an iterative solver stops with variable tolerance, the derivative may be locally discontinuous or correspond to the executed iteration count. Compare directional derivatives at several points and perturbation sizes, and study time refinement before interpreting the result as physical sensitivity.

Forward stability also limits gradient usefulness. For example, for a purely diffusive component z˙=−νk2z\dot z=-\nu k^2z, explicit RK4 requires νk2Δt\nu k^2\Delta t to remain inside its stable interval on the negative real axis. This isolated check does not guarantee stability of the full nonlinear equation: advection, filtering and state magnitude matter too. Reducing Δt\Delta t and comparing trajectories separates time error from spatial and training error.

Correction inside the loop

Solver-in-the-loop training compares trajectories already containing their own corrections. Um and colleagues studied this difference and observed improvements on their problems and protocols. With one-step loss, the network trains on reference states; in real use it receives its own predictions. Distribution shift can accumulate errors the one-step loss did not penalize. Unrolling several steps exposes part of this effect, at greater compute and memory cost. It does not prove a finite horizon gives stability for every time or input.

Our control uses periodic viscous Burgers and data generated with a 64-point spectral solver, filtered to 16. The convolutional network produces a zero-mean correction, projected onto retained modes; this preserves discrete mean up to roundoff, but does not prove local conservation or physical energy. We compare a network trained for one step and another with eight unrolled steps, from the same initialization. There are 48 training trajectories and 12 held out, one seed and a finite horizon. Training costs are not equal.

InteractiveCorrected coarse mesh
  • Reference
  • Coarse
  • One step
  • Eight steps

Unforced periodic Burgers, 12 held-out inputs and one seed; profile of the first input, metrics averaged over all 12. The 64-point reference is not exact and mean conservation does not guarantee future stability.

View
40 steps
Mean coarse error0.0521
Mean one-step error0.0518
Mean eight-step error0.0675
Saved errors and profiles of the filtered reference, coarse solver and two corrections trained with different horizons.

At final test time mean relative error was 0.7404 without correction, 0.1570 with one-step training and 0.1386 with eight. In this run unrolling improves on one-step fitting, but the difference is of the same order as the reference refinement check. Do not generalize to other coefficients, horizons or seeds. Maximum absolute change of discrete mean across the 12 trajectories was 1.9e-07.

For 240 steps, batch of 12 and the same device, these are medians of three measurements in alternating order. The 64-point row defines the discrete reference itself, so zero error does not measure continuous error:

MethodMean relative errorMedian forward time (s)
classical 160.74042.40
classical 320.16682.86
classical 64reference2.80
one step 160.15704.66
eight steps 160.13866.27

The three measurements varied considerably under shared load. In these medians the 64-point reference cost less than either network; that prevents concluding an equal-cost advantage in this environment. Training and data are excluded. Repeat on isolated hardware and consider reference error before deciding.

We also tested 2000 steps with a new fixed forcing, although corrections were trained without it. Filtered field energy is averaged over two halves of the latter part of the rollout; these are four initial conditions and two finite windows, not a test of ergodicity:

MethodMean energy, first windowMean energy, second windowState
ref640.06930.0831finite
grueso160.13440.1492finite
un_paso160.06940.0819finite
ocho_pasos160.06990.0832finite

The forcing changes the problem distribution, and both averages help detect drift but do not certify a stationary distribution. A real application would require repetition with more times, states and references.

Hybrid-model evaluation should not measure only against a coarse solver if the network takes longer. The lab times classical advancement with 16, 32 and 64 points and corrections with 16, on the same device and batch. This is a measurement under shared load, excluding training and data generation; repeat and adapt it to accuracy target and hardware before deciding the cheapest method. The 64-point reference is not exact either: refining to 128, filtering to 16 and comparing four inputs at final time gave mean relative difference 0.02696. Reference uncertainty matters when interpreting small improvements.

The unforced system in this example dissipates; energy and long-term error are transient checks, not estimates of ergodic turbulent statistics. A forced stationary flow would need warmup, a long window, multiple initial states and uncertainty estimates for statistics. Infinite stability or improved statistical climate should not be inferred from one finite trajectory.

The zero-mean correction imposes a useful global property but can redistribute values nonphysically. A corrective face flux whose discrete divergence sums to zero across neighbors would express stronger local conservation; limits, entropy or positivity would also need checking as appropriate. Our correction is added after RK4 and not reevaluated in its stages: it is one specific split method. Changing operation order changes both trajectory and trained gradient.

For a fair test, decide before seeing results whether relevant cost is one query, total training and querying, or cost amortized after a number of queries. Include CPU–GPU transfers, reference projection, batch size and timing synchronizations. A finer classical solver can be cheaper than a correction on a small mesh if the network adds many operations. This lesson’s table is a local diagnostic with measurement noise, not a definitive efficiency frontier.

Discovering equations with a library

SINDy assumes each component of the vector field can be expressed with few terms from a chosen library. With observations XX and approximate derivatives X˙\dot X, construct Θ(X)\Theta(X) and seek

X˙≈Θ(X)Ξ.\dot X\approx\Theta(X)\Xi.

STLSQ sparse selection fits by least squares, zeros small coefficients and refits retained terms. The threshold applies to coefficients in their columns’ units: scaling a variable or normalizing a column changes its meaning. Library, noise, system excitation and derivative estimation determine which terms can be distinguished. Brunton, Proctor and Kutz developed SINDy; PDE-FIND adds spatial derivatives as candidates, with additional difficulties estimating them from noisy data.

InteractiveSINDy prunes the library
Termdx/dtdy/dtdz/dt
1−0.39−0.39−0.59
x−9.8928.130.01
y9.91−1.064.4e−3
z0.040.01−2.59
x²3.5e−3−0.010.02
xy−0.010.010.99
xz−3.0e-3−1.00−3.5e-4
y²3.5e−3−1.1e-34.0e−3
yz2.8e−31.5e−3−4.8e-4
z²−8.9e-44.7e−4−2.5e-3

Synthetic Lorenz, seed 27; 11-point Savitzky–Golay window and training through t = 20. Displayed error is for the final model at later times; it does not automatically validate long chaotic trajectories.

Noise relative to standard deviation
Threshold
0
Nonzero coefficients30
Final field error, validation0.0013
Browse real Lorenz STLSQ fits, change noise and threshold, and observe omitted and spurious terms.

For Lorenz we generate a trajectory with high-precision integration, add noise at 1% of each coordinate’s standard deviation and estimate derivatives with Savitzky–Golay in an 11-point window. With threshold 0.5 and that seed, all seven nonzero terms are recovered, with relative vector-field error around 0.0013 on the held-out time segment. Raising the threshold to 1 removes true terms and increases error. This selection is known because the system is synthetic; a real problem would require choosing library and hyperparameters through independent validation and repeating with different trajectories and noise.

The SIR system illustrates identifiability. Since S+I+R=1S+I+R=1, a full polynomial library contains nearly dependent columns on one trajectory; the fit may produce large compensating coefficients. Restricting the library to SS, II and SISI incorporates structural knowledge and approximately recovers the simulated rates. A good fit on one trajectory does not prove the discovered model is unique or causal. Check the field on new data, conservation constraints and trajectories from other initial conditions; for Lorenz, long-term chaotic divergence requires statistical metrics in addition to pointwise error.

Numerical differentiation amplifies noise: a centered difference divides the difference of two measurements by the time step. Smoothing reduces some amplification, but a wide window also erases rapid variation and biases the derivative. The Lorenz test uses a fixed window chosen for this synthetic signal, not a rule for arbitrary data. We separate the held-out segment before smoothing so later data do not enter the edges of the fit. Moreover, that segment belongs to the same trajectory: it does not replace repeating the experiment from other initial conditions.

If two columns of Θ\Theta are nearly proportional on the data, many coefficient combinations yield similar predictions. The threshold may select one or the other under small perturbations. Check scales, rank and conditioning, and test support stability when resampling observations. A restricted library can improve identification because it incorporates prior knowledge; that advantage must be declared and not interpreted as assumption-free discovery.

Learned weather forecasting

Learned weather models do not eliminate the need to estimate the initial state. A reanalysis combines observations and a physical model through assimilation; its fields permit historical examples but depend on that infrastructure and its resolution and biases. GraphCast trained on reanalysis and produces global autoregressive forecasts. The paper reported improvements on 90% of 1380 targets against its specific deterministic comparison: that does not mean it beats every system on every variable, extreme situation or date.

A deterministic forecast does not by itself quantify all uncertainty. Ensembles can be obtained through perturbed initial states or probabilistic models, and must be evaluated with calibration and probabilistic scores in addition to mean error. Operational verification must distinguish reference analysis, horizon, variable, latency, assimilation cost and rare events. A model trained on reanalysis can be useful while still depending on observations and methods for incorporating them.

A concrete research question could compare a learned ensemble with a classical one for a held-out region and season. Variables, lead times, observation sources, common resolution and calibration metrics would be fixed in advance; then both average quality and tails of relevant events would be measured. Training resolution or an aggregate result from a paper does not replace that protocol. Observation-system changes, interpolation and reanalysis updates can change the input distribution.

Reproducible laboratories

The following experiments are built from scratch. Local cells require NumPy and PyTorch; SINDy cells use NumPy, SciPy and PySINDy in Pyodide. Figures correspond to one specific run; times, accuracy and evolution can vary with device or version. Results are created in the reader’s working directory.

Solver, data and corrections

This cell generates training and test data, fits both networks and saves weights as hybrid_models.pt. The network returns a zero-mean correction and filters its modes; 500 updates with horizon eight require more work than one-step updates.

[ ]Burgers and solver in the loopLocal GPU
"""Burgers espectral diferenciable y corrección convolucional entrenada en bucle."""
import json,time
from pathlib import Path
import numpy as np
import torch
from torch import nn

torch.set_num_threads(1);torch.manual_seed(27)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dtype=torch.float32; nu=.01; dt=.005

def rhs(u,nu,forcing=None):
    n=u.shape[-1]; k=torch.arange(n//2+1,device=u.device,dtype=u.dtype)
    keep=(k<=n//3).to(u.dtype)
    uh=torch.fft.rfft(u); filtered=torch.fft.irfft(uh*keep,n=n)
    nonlinear=torch.fft.rfft(filtered.square())*keep
    result=torch.fft.irfft(-.5j*k*nonlinear-nu*k*k*uh*keep,n=n)
    return result if forcing is None else result+forcing

def step(u,nu,dt,forcing=None):
    k1=rhs(u,nu,forcing);k2=rhs(u+dt*k1/2,nu,forcing)
    k3=rhs(u+dt*k2/2,nu,forcing);k4=rhs(u+dt*k3,nu,forcing)
    return u+dt*(k1+2*k2+2*k3+k4)/6

def initial(coeff,n):
    x=2*torch.pi*torch.arange(n,device=coeff.device,dtype=coeff.dtype)/n
    modes=torch.arange(1,5,device=coeff.device,dtype=coeff.dtype)
    return (coeff[:,:4,None]*torch.sin(modes[:,None]*x)+coeff[:,4:,None]*torch.cos(modes[:,None]*x)).sum(dim=1)

def restrict(u,n):
    m=u.shape[-1];k=torch.arange(m//2+1,device=u.device)
    low=torch.fft.irfft(torch.fft.rfft(u)*(k<=n//3),n=m)
    return low[...,::m//n]

def reference(coeff,steps):
    u=initial(coeff,64);history=[restrict(u,16)]
    for _ in range(steps):
        u=step(u,nu,dt);history.append(restrict(u,16))
    return torch.stack(history,dim=1)

gen=torch.Generator(device=device).manual_seed(27)
train_coeff=.35*torch.randn(48,8,generator=gen,device=device,dtype=dtype)
test_coeff=.35*torch.randn(12,8,generator=gen,device=device,dtype=dtype)
with torch.no_grad():
    train=reference(train_coeff,120);test=reference(test_coeff,240)
print('referencias generadas',train.shape,test.shape,flush=True)

class Correction(nn.Module):
    def __init__(self):
        super().__init__()
        self.net=nn.Sequential(nn.Conv1d(1,16,5,padding=2,padding_mode='circular'),nn.Tanh(),
            nn.Conv1d(16,16,5,padding=2,padding_mode='circular'),nn.Tanh(),nn.Conv1d(16,1,5,padding=2,padding_mode='circular'))
        nn.init.zeros_(self.net[-1].weight);nn.init.zeros_(self.net[-1].bias)
    def forward(self,u):
        value=self.net(u[:,None,:]).squeeze(1)
        value=value-value.mean(dim=-1,keepdim=True)
        k=torch.arange(u.shape[-1]//2+1,device=u.device)
        return torch.fft.irfft(torch.fft.rfft(value)*(k<=u.shape[-1]//3),n=u.shape[-1])

models={};training=[]
for horizon in (1,8):
    torch.manual_seed(27);model=Correction().to(device);opt=torch.optim.Adam(model.parameters(),lr=.002)
    sample_gen=torch.Generator(device=device).manual_seed(127)
    start=time.perf_counter()
    for update in range(501):
        ids=torch.randint(0,len(train),(12,),generator=sample_gen,device=device)
        begin=torch.randint(0,120-horizon,(12,),generator=sample_gen,device=device)
        state=train[ids,begin];loss=0.
        for k in range(1,horizon+1):
            state=step(state,nu,dt)+dt*model(state)
            loss=loss+(state-train[ids,begin+k]).square().mean()/horizon
        if update in (0,100,500):
            training.append({'horizon':horizon,'update':update,'loss':loss.item()});print('entrenamiento',horizon,update,loss.item(),flush=True)
        if update<500:opt.zero_grad(set_to_none=True);loss.backward();opt.step()
    if device.type=='cuda':torch.cuda.synchronize()
    print('tiempo entrenamiento',horizon,time.perf_counter()-start,flush=True)
    models[horizon]=model.eval()

with torch.no_grad():
    states={'grueso':test[:,0].clone(),'un_paso':test[:,0].clone(),'ocho_pasos':test[:,0].clone()}
    errors={key:[] for key in states};energy={key:[] for key in states};mass={key:[] for key in states}
    frames=[]
    for t in range(241):
        ref=test[:,t]; denom=torch.linalg.vector_norm(ref,dim=1).clamp_min(1e-12)
        for key,state in states.items():
            errors[key].append((torch.linalg.vector_norm(state-ref,dim=1)/denom).mean().item())
            energy[key].append(state.square().mean().item()/2)
            mass[key].append((state.mean(dim=1)-test[:,0].mean(dim=1)).abs().max().item())
        if t in (0,40,80,160,240):
            frames.append({'step':t,'reference':ref[0].cpu().tolist(),**{k:v[0].cpu().tolist() for k,v in states.items()}})
        if t<240:
            for key in states:
                state=states[key];states[key]=step(state,nu,dt)+(dt*models[1](state) if key=='un_paso' else dt*models[8](state) if key=='ocho_pasos' else 0)
    reference_energy=(test.square().mean(dim=(0,2))/2).cpu().tolist()
    benchmarks=[]
    for label,n,correction in [('clásico 16',16,None),('clásico 32',32,None),('clásico 64',64,None),
                               ('un paso 16',16,models[1]),('ocho pasos 16',16,models[8])]:
        state=initial(test_coeff,n)
        if device.type=='cuda':torch.cuda.synchronize()
        started=time.perf_counter()
        for _ in range(240):
            previous=state
            state=step(previous,nu,dt)+(dt*correction(previous) if correction is not None else 0)
        if device.type=='cuda':torch.cuda.synchronize()
        elapsed=time.perf_counter()-started
        comparable=state if n==16 else restrict(state,16)
        target=test[:,-1]
        error=(torch.linalg.vector_norm(comparable-target,dim=1)/torch.linalg.vector_norm(target,dim=1).clamp_min(1e-12)).mean().item()
        benchmarks.append({'label':label,'seconds':elapsed,'relative_error':error})
    print('costes y error',benchmarks,flush=True)
out={'seed':27,'device':str(device),'dt':dt,'nu':nu,'training':training,'errors':errors,'energy':energy,
     'mass':mass,'reference_energy':reference_energy,'frames':frames,'benchmarks':benchmarks,
     'notes':'Burgers 1D periódico sin forzamiento; espectral RK4 con corte 2/3, referencia 64 filtrada a 16, 48 trayectorias y 12 reservadas. Corrección de media cero; una semilla.'}
Path('hybrid_data.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
torch.save({k:v.state_dict() for k,v in models.items()},'hybrid_models.pt')
print('errores finales', {k:v[-1] for k,v in errors.items()},'máximo cambio de masa',{k:max(v) for k,v in mass.items()},flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Reference, cost and temporal averages

Run these cells after the preceding one. The first control compares 64 and 128 points on four inputs and projects both results to 16. The second measures each configuration three times, with device synchronization and alternating order. The third introduces unseen forcing to observe averages in two windows and check every ten steps for a nonfinite state.

[ ]Reference refinementLocal GPU
gen=torch.Generator(device=device).manual_seed(27)
_train=.35*torch.randn(48,8,generator=gen,device=device,dtype=dtype)
test=.35*torch.randn(12,8,generator=gen,device=device,dtype=dtype)[:4]
with torch.no_grad():
    coarse=initial(test,64);fine=initial(test,128)
    for _ in range(240):coarse=step(coarse,nu,dt);fine=step(fine,nu,dt)
    coarse=restrict(coarse,16);fine=restrict(fine,16)
    error=(torch.linalg.vector_norm(coarse-fine,dim=1)/torch.linalg.vector_norm(fine,dim=1)).mean().item()
Path('reference_check.json').write_text(json.dumps({'cases':4,'relative_difference':error}),encoding='utf8')
print('refinamiento 64/128, tras filtrar a 16:',error)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Forward costLocal GPU
gen=torch.Generator(device=device).manual_seed(27)
_train=.35*torch.randn(48,8,generator=gen,device=device,dtype=dtype)
test_coeff=.35*torch.randn(12,8,generator=gen,device=device,dtype=dtype)
saved=torch.load('hybrid_models.pt',map_location=device,weights_only=True)
models={}
for horizon in (1,8):
    models[horizon]=Correction().to(device);models[horizon].load_state_dict(saved[horizon]);models[horizon].eval()
configs=[('clásico 16',16,None),('clásico 32',32,None),('clásico 64',64,None),('un paso 16',16,1),('ocho pasos 16',16,8)]
timings={label:[] for label,_,_ in configs};errors={}
with torch.no_grad():
    reference_final=reference(test_coeff,240)[:,-1]
    for repeat in range(3):
        order=configs[repeat:]+configs[:repeat]
        for label,n,horizon in order:
            state=initial(test_coeff,n)
            if device.type=='cuda':torch.cuda.synchronize()
            start=time.perf_counter()
            for _ in range(240):
                previous=state
                state=step(previous,nu,dt)+(dt*models[horizon](previous) if horizon is not None else 0)
            if device.type=='cuda':torch.cuda.synchronize()
            timings[label].append(time.perf_counter()-start)
            comparable=state if n==16 else restrict(state,16)
            errors[label]=(torch.linalg.vector_norm(comparable-reference_final,dim=1)/torch.linalg.vector_norm(reference_final,dim=1).clamp_min(1e-12)).mean().item()
out={label:{'seconds':values,'median_seconds':float(np.median(values)),'relative_error':errors[label]} for label,values in timings.items()}
Path('benchmark_data.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
print(out,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Finite temporal averagesLocal GPU
gen=torch.Generator(device=device).manual_seed(27)
_train=.35*torch.randn(48,8,generator=gen,device=device,dtype=dtype)
coeff=.35*torch.randn(12,8,generator=gen,device=device,dtype=dtype)[:4]
saved=torch.load('hybrid_models.pt',map_location=device,weights_only=True)
models={}
for h in (1,8):
    models[h]=Correction().to(device);models[h].load_state_dict(saved[h]);models[h].eval()
states={'ref64':initial(coeff,64),'grueso16':initial(coeff,16),
        'un_paso16':initial(coeff,16),'ocho_pasos16':initial(coeff,16)}
summaries={k:[[],[]] for k in states};max_abs={k:0. for k in states}
failed={k:None for k in states}
with torch.no_grad():
    for i in range(2000):
        for key,u in list(states.items()):
            n=u.shape[-1];x=2*torch.pi*torch.arange(n,device=device,dtype=dtype)/n
            force=.1*torch.sin(x)[None,:]
            next_u=step(u,nu,dt,force)
            if key=='un_paso16':next_u=next_u+dt*models[1](u)
            if key=='ocho_pasos16':next_u=next_u+dt*models[8](u)
            states[key]=next_u
            if i%10==0 or i==1999:
                if not torch.isfinite(next_u).all():
                    failed[key]=i+1;del states[key];continue
                max_abs[key]=max(max_abs[key],float(next_u.abs().max()))
                if i>=1000 and i%10==0:
                    projected=restrict(next_u,16) if n==64 else next_u
                    summaries[key][0 if i<1500 else 1].append(float(projected.square().mean()/2))
out={k:{'mean_energy_first':float(np.mean(v[0])) if v[0] else None,'mean_energy_second':float(np.mean(v[1])) if v[1] else None,
        'max_abs_muestreado':max_abs[k],'failed_step':failed[k]} for k,v in summaries.items()}
Path('long_data.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
print('promedios finitos',out,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Control and sensitivity

The target is synthetic and generated with the same solver. The autograd/centered-difference comparison checks the differentiated program in one direction; the logistic map is a separate experiment.

[ ]Differentiable controlLocal GPU
dtype=torch.float64
n=32;x=2*torch.pi*torch.arange(n,device=device,dtype=dtype)/n
base=torch.stack((torch.sin(x),torch.cos(2*x)))
u0=torch.zeros((1,n),device=device,dtype=dtype)

def run(params):
    force=(params[:,None]*base).sum(dim=0)[None,:]
    state=u0
    for _ in range(160):state=step(state,.01,.005,force)
    return state

targets=[(.7,-.4),(-.5,.8)];experiments=[]
for values in targets:
    with torch.no_grad():target=run(torch.tensor(values,device=device,dtype=dtype))
    parameter=torch.nn.Parameter(torch.zeros(2,device=device,dtype=dtype))
    optimizer=torch.optim.Adam([parameter],lr=.12);snapshots=[]
    for iteration in range(41):
        optimizer.zero_grad(set_to_none=True)
        state=run(parameter); loss=(state-target).square().mean()+.0001*parameter.square().sum()
        if iteration in (0,5,10,20,40):
            snapshots.append({'iteration':iteration,'loss':loss.item(),'params':parameter.detach().cpu().tolist(),
                'prediction':state.detach().cpu().flatten().tolist()})
        if iteration<40:loss.backward();optimizer.step()
    experiments.append({'target_params':list(values),'target':target.cpu().flatten().tolist(),'snapshots':snapshots})

test_params=torch.tensor([.1,-.1],device=device,dtype=dtype,requires_grad=True)
with torch.no_grad():target=run(torch.tensor(targets[0],device=device,dtype=dtype))
objective=lambda p:(run(p)-target).square().mean()+.0001*p.square().sum()
g=torch.autograd.grad(objective(test_params),test_params)[0]
direction=torch.tensor([.6,-.8],device=device,dtype=dtype); eps=1e-5
fd=(objective(test_params.detach()+eps*direction)-objective(test_params.detach()-eps*direction))/(2*eps)
adj=(g@direction).item();fd=fd.item()

state=torch.tensor(.213,dtype=torch.float64,requires_grad=True);logs=[]
current=state
for horizon in range(1,61):
    current=4*current*(1-current)
    derivative=torch.autograd.grad(current,state,retain_graph=True)[0].abs().item()
    logs.append([horizon,float(np.log10(max(derivative,1e-300)))])
out={'experiments':experiments,'gradient_directional':adj,'finite_difference':fd,'chaos_log10':logs,
     'notes':'Burgers periódico 32 puntos, RK4 160 pasos, dos modos de forzamiento fijo y objetivo sintético. El mapa logístico 4x(1−x) es un ejemplo caótico separado, no la EDP.'}
Path('control_data.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
print('gradiente',adj,'diferencia centrada',fd,'pérdidas',[(e['target_params'],e['snapshots'][0]['loss'],e['snapshots'][-1]['loss']) for e in experiments],flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Initial-condition and viscosity sensitivity

The same solver also permits differentiating terminal energy with respect to the initial profile and viscosity. Two derivatives are checked: a normalized direction in state space and scalar parameter ν\nu. In the reference run, autograd and centered difference gave approximately 1.13995×10−51.13995\times10^{-5} in the initial direction and −0.38009809-0.38009809 for viscosity. This comparison remains local and corresponds to 100 steps of the chosen discretization.

[ ]Initial-state and viscosity gradientsLocal GPU
n=32; dtype=torch.float64
x=2*torch.pi*torch.arange(n,device=device,dtype=dtype)/n
u0=(torch.sin(x)+.3*torch.cos(2*x))[None,:].requires_grad_(True)
nu0=torch.tensor(.01,device=device,dtype=dtype,requires_grad=True)
direction=torch.sin(3*x)[None,:]; direction=direction/torch.linalg.vector_norm(direction)
def cost(initial,viscosity):
    state=initial
    for _ in range(100):state=step(state,viscosity,.005)
    return state.square().mean()/2
loss=cost(u0,nu0)
grad_u,grad_nu=torch.autograd.grad(loss,(u0,nu0))
eps=1e-5
fd_u=(cost(u0.detach()+eps*direction,nu0.detach())-cost(u0.detach()-eps*direction,nu0.detach()))/(2*eps)
fd_nu=(cost(u0.detach(),nu0.detach()+eps)-cost(u0.detach(),nu0.detach()-eps))/(2*eps)
print('condición inicial: autograd',float((grad_u*direction).sum()),'diferencia centrada',fd_u.item())
print('viscosidad: autograd',grad_nu.item(),'diferencia centrada',fd_nu.item())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

STLSQ and PySINDy

Derivatives are smoothed only on the training segment. The later time segment is held out to verify the vector field against the noise-free synthetic solution. SIR compares a redundant library with one restricted by model knowledge. PySINDy uses the same libraries and precomputed derivatives for Lorenz and the two independent SIR equations; in SIR it obtains the third through conservation. The comparison does not depend on two different derivative estimators.

[ ]STLSQ from scratchBrowser
"""SINDy reproducible: Lorenz y SIR, derivadas suavizadas y STLSQ."""
import json
from pathlib import Path
import numpy as np
from scipy.integrate import solve_ivp
from scipy.signal import savgol_filter

def library(x):
    a,b,c=x.T
    return np.column_stack((np.ones(len(x)),a,b,c,a*a,a*b,a*c,b*b,b*c,c*c))

def stlsq(theta,dxdt,threshold,n_iter=10):
    coef=np.linalg.lstsq(theta,dxdt,rcond=None)[0]
    history=[coef.copy()]
    for _ in range(n_iter):
        active=np.abs(coef)>=threshold
        new=np.zeros_like(coef)
        for j in range(dxdt.shape[1]):
            if np.any(active[:,j]):new[active[:,j],j]=np.linalg.lstsq(theta[:,active[:,j]],dxdt[:,j],rcond=None)[0]
        history.append(new.copy())
        if np.array_equal(np.abs(new)>=threshold,active):coef=new;break
        coef=new
    return coef,history

def lorenz(t,x):
    a,b,c=x;return np.array([10*(b-a),a*(28-c)-b,a*b-(8/3)*c])

def sir(t,x):
    s,i,r=x;return np.array([-1.2*s*i,1.2*s*i-.3*i,.3*i])

def trajectory(rhs,initial,stop,dt):
    t=np.arange(round(stop/dt)+1)*dt
    sol=solve_ivp(rhs,(0,stop),initial,t_eval=t,rtol=1e-10,atol=1e-12)
    if not sol.success:raise RuntimeError(sol.message)
    return t,sol.y.T

names=['1','x','y','z','x²','xy','xz','y²','yz','z²']
t,x=trajectory(lorenz,[1.,1.,1.],25.,.01)
truth=np.column_stack([lorenz(0,row) for row in x]).T
split=2001; rng=np.random.default_rng(27);noise_base=rng.normal(size=x.shape)
data=[]
for noise in (0.,.01,.03):
    observed=x+noise*noise_base*x[:split].std(axis=0)
    smooth=savgol_filter(observed[:split],11,3,axis=0)
    derivative=savgol_filter(observed[:split],11,3,deriv=1,delta=.01,axis=0)
    for threshold in (.05,.2,.5,1.):
        coef,history=stlsq(library(smooth[:split]),derivative[:split],threshold)
        pred=library(x[split:])@coef
        err=np.linalg.norm(pred-truth[split:])/np.linalg.norm(truth[split:])
        data.append({'noise':noise,'threshold':threshold,'coef':coef.tolist(),'history':[v.tolist() for v in history],
                     'validation_relative':float(err),'nonzero':int(np.count_nonzero(coef))})
print('Lorenz',[(r['noise'],r['threshold'],r['nonzero'],round(r['validation_relative'],4)) for r in data],flush=True)

ts,s=trajectory(sir,[.99,.01,0.],30.,.02)
rng=np.random.default_rng(28);obs=s+.001*rng.normal(size=s.shape)
smooth=savgol_filter(obs[:1001],21,3,axis=0); deriv=savgol_filter(obs[:1001],21,3,deriv=1,delta=.02,axis=0)
sir_coef,sir_history=stlsq(library(smooth[:1001]),deriv[:1001],.03)
sir_true=np.column_stack([sir(0,row) for row in s[1001:]]).T
sir_error=np.linalg.norm(library(s[1001:])@sir_coef-sir_true)/np.linalg.norm(sir_true)
print('SIR',sir_coef,'validación relativa',sir_error,flush=True)
def sir_library(x):
    s,i=x[:,0],x[:,1]
    return np.column_stack((s,i,s*i))
sir_reduced,_=stlsq(sir_library(smooth),deriv,.03)
sir_reduced_error=np.linalg.norm(sir_library(s[1001:])@sir_reduced-sir_true)/np.linalg.norm(sir_true)
print('SIR biblioteca restringida',sir_reduced,'validación relativa',sir_reduced_error,flush=True)
out={'seed':27,'names':names,'experiments':data,'sir_coef':sir_coef.tolist(),'sir_error':float(sir_error),
     'sir_reduced':sir_reduced.tolist(),'sir_reduced_error':float(sir_reduced_error),
     'notes':'Lorenz dt=.01: entrenamiento t≤20 y validación posterior; derivadas Savitzky-Golay, ruido relativo por variable a su desviación típica. SIR ruido absoluto .001.'}
Path('sindy_data.json').write_text(json.dumps(out,ensure_ascii=False),encoding='utf8')
[ ]Compare PySINDyBrowser
"""Comparación real con PySINDy usando la misma trayectoria y derivadas."""
import numpy as np
import pysindy as ps
from scipy.integrate import solve_ivp
from scipy.signal import savgol_filter

def lorenz(t,x):
    a,b,c=x;return [10*(b-a),a*(28-c)-b,a*b-(8/3)*c]
dt=.01;t=np.arange(2001)*dt
sol=solve_ivp(lorenz,(0,20),[1.,1.,1.],t_eval=t,rtol=1e-10,atol=1e-12)
clean=sol.y.T
noise=np.random.default_rng(27).normal(size=(2501,3))[:2001]
observed=clean+.01*noise*clean.std(axis=0)
smooth=savgol_filter(observed,11,3,axis=0)
deriv=savgol_filter(observed,11,3,deriv=1,delta=dt,axis=0)
model=ps.SINDy(feature_library=ps.PolynomialLibrary(degree=2,include_bias=True),
               optimizer=ps.STLSQ(threshold=.5,alpha=0,normalize_columns=False,max_iter=10))
model.fit(smooth,t=dt,x_dot=deriv)
print('versión PySINDy:',ps.__version__)
print('biblioteca:',model.get_feature_names())
print('coeficientes:\n',model.coefficients())
print('términos no nulos:',np.count_nonzero(model.coefficients()))

own = next(r for r in data if r['noise']==.01 and r['threshold']==.5)
print('diferencia máxima con STLSQ propio:',np.max(np.abs(model.coefficients().T-np.asarray(own['coef']))))

"""PySINDy en SIR con biblioteca restringida y conservación explícita."""
import numpy as np
import pysindy as ps
from scipy.integrate import solve_ivp
from scipy.signal import savgol_filter

def sir(t,x):
    s,i,r=x;return [-1.2*s*i,1.2*s*i-.3*i,.3*i]
dt=.02;ts=np.arange(1501)*dt
clean=solve_ivp(sir,(0,30),[.99,.01,0.],t_eval=ts,rtol=1e-10,atol=1e-12).y.T
obs=clean+.001*np.random.default_rng(28).normal(size=clean.shape)
sm=savgol_filter(obs[:1001],21,3,axis=0)
der=savgol_filter(obs[:1001],21,3,deriv=1,delta=dt,axis=0)
features=ps.CustomLibrary(library_functions=[lambda x:x,lambda x,y:x*y],include_bias=False)
model_sir=ps.SINDy(feature_library=features,optimizer=ps.STLSQ(threshold=.03,alpha=0,normalize_columns=False,max_iter=10))
model_sir.fit(sm[:,:2],t=dt,x_dot=der[:,:2])
print('biblioteca SIR:',model_sir.get_feature_names())
print('coeficientes para S e I:\n',model_sir.coefficients())
print('R punto se obtiene como menos la suma de S punto e I punto')

print('diferencia máxima S/I frente a STLSQ propio:',np.max(np.abs(model_sir.coefficients().T-sir_reduced[:,:2])))

Exercises

Code
Implement stlsq(Theta, dXdt, threshold, n_iter): fit by least squares, remove coefficients with magnitude below the threshold, and refit each column on active terms. Return only the coefficient matrix. The threshold is positive and n_iter nonnegative.
import numpy as np

def stlsq(Theta, dXdt, threshold, n_iter):
  pass
Shift+Enter to run
Quiz
Why can a correction trained only on one-step reference states fail when deployed recursively?
Numeric
With Lyapunov exponent 0.9 and horizon 50, an approximate model predicts a factor exp(0.9×50). Enter its base-10 logarithm, rounded to two decimal places.
Quiz
A weather model is trained on reanalysis and predicts the next state. Does it automatically eliminate the need for data assimilation?
Quiz
What protocol evaluates a learned correction against a classical solver?
Key idea
A differentiable simulator permits parameter optimization and correction training, but gradient, cost and stability belong to a specific algorithm and horizon. Sparse identification needs libraries, data and validation capable of distinguishing proposed terms.