50 minNumerical teaching modelExecuted reading edition

Inspect damping and forced resonance

Connect free decay, steady frequency response and time-domain integration with dimensional parameters.

Physics · Lesson 02🔋 Offline core analysis⏱ 50 minNumerical teaching model📦 numpy · pandas · scipy · matplotlib · IPython

Goal and how to run

This lesson assumes basic Python knowledge. Read each method and caption before changing parameters. AI exercises are optional; no AI account is needed for the core workflow. Data lives in notebook metadata, so there is no companion data download. Keep the notebook saved in the active working folder.

Your goal is to understand the research question, execute transparent calculations, check the results, and state the limits of the conclusion.

Setup and parameters

In [1] · Python
from pathlib import Path
import base64, gzip, hashlib, json, platform
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, HTML
from scipy.integrate import solve_ivp
from IPython.display import display as _display
def display(value):
    if isinstance(value,pd.DataFrame):
        table=value.to_html(max_rows=12,escape=True)
        style="<style>.vibeit-readable-table{max-width:100%;overflow-x:auto}.vibeit-readable-table table{width:max-content;max-width:none;border-collapse:collapse}.vibeit-readable-table td,.vibeit-readable-table th{white-space:nowrap!important;word-break:normal!important;overflow-wrap:normal!important}</style>"
        return _display(HTML(style+'<div class="vibeit-readable-table">'+table+'</div>'))
    return _display(value)
RECIPE_ID='ph02-oscillator'
OUTPUT_DIR=Path.cwd()/"results"/RECIPE_ID
plt.rcParams.update({"figure.dpi":120,"font.size":10,"axes.spines.top":False,"axes.spines.right":False,
                      "axes.prop_cycle":plt.cycler(color=["#18785f","#416aa6","#bc6541","#9974a5"])})
print("Python:",platform.python_version(),"; NumPy:",np.__version__,"; Pandas:",pd.__version__)
print("Working folder:",Path.cwd())
print("Core data mode: embedded snapshot; no network requests")
Python: 3.13.13 ; NumPy: 2.5.3 ; Pandas: 3.0.6
Working folder: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads
Core data mode: embedded snapshot; no network requests

Load the embedded snapshot

In [2] · Python
def load_snapshot(recipe_id, expected_sha256, snapshot_key):
    """Read embedded data from this notebook, including a renamed copy."""
    for path in sorted(Path.cwd().glob("*.ipynb")):
        try:
            notebook = json.loads(path.read_text(encoding="utf-8"))
            metadata = notebook.get("metadata", {}).get("vibeit_cookbook", {})
            blob = metadata.get("snapshots", {}).get(snapshot_key)
            if metadata.get("recipe_id") != recipe_id or not blob:
                continue
            if blob.get("sha256") != expected_sha256:
                continue
            raw = gzip.decompress(base64.b64decode(blob["gzip_base64"], validate=True))
            if hashlib.sha256(raw).hexdigest() != expected_sha256:
                raise ValueError("Embedded snapshot checksum mismatch: " + snapshot_key)
            return json.loads(raw)
        except (OSError, json.JSONDecodeError):
            continue
    raise FileNotFoundError(
        "Save/open the complete .ipynb in the active working folder. "
        "The embedded snapshot could not be located for " + recipe_id)

SNAPSHOT_HASHES={'models': '48fd2e6e706650fe2ee0c0ad80b6d794a546a1dec78dd9d370ac09db3cc3adbf'}
def snapshot(key):
    return load_snapshot(RECIPE_ID,SNAPSHOT_HASHES[key],key)
print("Embedded snapshots:",list(SNAPSHOT_HASHES))
Embedded snapshots: ['models']

Read the method functions

In [3] · Python
def oscillator_solution(mass,stiffness,damping,force_amplitude=0,drive_frequency=0,duration_s=20,initial_displacement=1,samples=2001):
    if mass<=0 or stiffness<=0 or damping<0 or duration_s<=0 or samples<3:
        raise ValueError('Invalid oscillator parameters')
    def dynamics(t,state):
        x,v=state;return [v,(force_amplitude*np.cos(drive_frequency*t)-damping*v-stiffness*x)/mass]
    t=np.linspace(0,duration_s,samples)
    solved=solve_ivp(dynamics,[0,duration_s],[initial_displacement,0],t_eval=t,rtol=1e-8,atol=1e-10)
    if not solved.success:raise RuntimeError(solved.message)
    return dict(t=t,x=solved.y[0],velocity=solved.y[1])

print("Method ready: oscillator_solution")
Method ready: oscillator_solution

Data and model boundary

Pendulum, oscillator, projectile and heat trajectories are declared numerical models, not laboratory measurements. The gravitational acceleration is the conventional standard g0 when used. GW150914 uses actual frozen detector strain and published event timing; a filtered curve is not an independent significance or source-parameter analysis. Blackbody curves assume an ideal emitter.

Steps

1. Declare the linear oscillator

The equation is m x″+c x′+k x=F cos(omega t). Mass is kg, stiffness N/m and damping N·s/m. First inspect free decay from a one-metre initial displacement; the example is a teaching model rather than a measured apparatus.

In [4] · Python
p=snapshot("models")["oscillator"];mass=p["mass_kg"];stiffness=p["stiffness_N_per_m"];dampings=p["damping_N_s_per_m"]
natural=np.sqrt(stiffness/mass)
fig,ax=plt.subplots(figsize=(9,4))
for damping in dampings:
 solution=oscillator_solution(mass,stiffness,damping)
 ax.plot(solution["t"],solution["x"],label=f"c={damping} N·s/m")
ax.set(xlabel="Time (s)",ylabel="Displacement (m)",title="Free damped motion");ax.legend();plt.tight_layout();plt.show()
Computed figure from this code cell

2. Read the steady frequency response

For positive damping, amplitude is F/sqrt((k−m omega²)²+(c omega)²). The horizontal coordinate is angular frequency in rad/s, not Hz. The damped amplitude maximum need not equal the undamped natural frequency.

In [5] · Python
frequencies=np.linspace(.1,8,501);force=p["force_N"]
fig,ax=plt.subplots(figsize=(8,4))
for damping in dampings:
 amplitude=force/np.sqrt((stiffness-mass*frequencies**2)**2+(damping*frequencies)**2)
 ax.plot(frequencies,amplitude,label=f"c={damping}")
ax.axvline(natural,color="gray",linestyle="--",label="Undamped natural omega")
ax.set(xlabel="Drive angular frequency (rad/s)",ylabel="Steady displacement amplitude (m)",title="Damping changes peak location and width");ax.legend();plt.tight_layout();plt.show()
Computed figure from this code cell

3. Check one forced trajectory against the analytic response

Integrate zero initial state long enough for transients to decay. The late trajectory should match a sinusoid with the analytic amplitude and phase. Comparing the initial transient to a steady-state formula would be an invalid check.

In [6] · Python
damping=1.6;drive=natural
forced=oscillator_solution(mass,stiffness,damping,force,drive,duration_s=80,initial_displacement=0,samples=8001)
amplitude=force/np.sqrt((stiffness-mass*drive**2)**2+(damping*drive)**2)
phase=np.arctan2(damping*drive,stiffness-mass*drive**2)
expected=amplitude*np.cos(drive*forced["t"]-phase);late=forced["t"]>70
fig,ax=plt.subplots(figsize=(9,4));ax.plot(forced["t"][late],forced["x"][late],label="ODE integration")
ax.plot(forced["t"][late],expected[late],"--",label="Analytic steady state")
ax.set(xlabel="Late model time (s)",ylabel="Displacement (m)",title="Time/frequency-domain consistency");ax.legend();plt.tight_layout();plt.show()
Computed figure from this code cell

4. Reconcile and export the declared model

Verify late-time amplitude/phase agreement with a separate closed expression. Keep natural angular frequency, damping units and solver tolerances with the exported trace. No fitted laboratory parameters are claimed.

In [7] · Python
assert np.max(np.abs(forced["x"][late]-expected[late]))<1e-6
assert np.isclose(natural,4.0)
OUTPUT_DIR.mkdir(parents=True,exist_ok=True)
pd.DataFrame({"time_s":forced["t"],"ODE_displacement_m":forced["x"],"steady_displacement_m":expected}).to_csv(OUTPUT_DIR/"forced-oscillation.csv",index=False)
(OUTPUT_DIR/"parameters.json").write_text(json.dumps({"mass_kg":mass,"stiffness_N_per_m":stiffness,"damping_N_s_per_m":damping,"force_N":force,"drive_rad_per_s":drive,"natural_rad_per_s":natural},indent=2))
print("Steady-state cross-check passed; exports:",OUTPUT_DIR)
Steady-state cross-check passed; exports: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads/results/ph02-oscillator

Exercises and reference explanation

  1. Distinguish rad/s from Hz.
  2. Why compare steady response only after transient decay?

Reference explanation. Angular frequency is 2pi times cycles/s. A steady sinusoid omits the transient determined by initial conditions.

Keep a copy before changing parameters. Compare old and new figures and record which inputs, calculations and conclusions changed.

Optional AI coding exercises

Prompt 1

Using NumPy/SciPy/Matplotlib, add damping=8 N·s/m and inspect free-decay versus frequency-response behavior.

Prompt 2

With the same packages, export the analytical phase curve using atan2 and clear radian units.

Human acceptance. Dimensional parameters are retained; late-time amplitude/phase checks pass for positive damping.

Review the edited source, then manually run affected cells and subsequent checks. Ask the assistant to explain the purpose, packages and data provenance of its changes, and reconcile that explanation with actual output.

Optional online extension

In [8] · Python
RUN_ONLINE_UPDATE=False
if RUN_ONLINE_UPDATE:
    import requests
    try:
        response=requests.get('https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html',timeout=20)
        response.raise_for_status()
        print("Source:",response.url)
        print(response.text[:700])
    except requests.RequestException as error:
        print("Online extension unavailable:",type(error).__name__,str(error)[:160])
else:
    print("Online extension skipped; embedded core data unchanged")
Online extension skipped; embedded core data unchanged

Sources, snapshots and next steps

  • IAPWS saturation reference release — IAPWS SR1-86(1992): unrestricted publication allowed in all countries (cover page); retrieved 2026-10-09. SHA-256 a10d38d73339b0713c86cfac88f9adcba137202167ccdfa1cd58238c438361d7. Reference equations and numerical coefficients transcribed from release pages 2–3; pedagogical model values are not new experiments.

  • Authored numerical teaching model parameters — Original teaching parameters/code MIT; reference equation coefficients attributed to IAPWS SR1-86(1992); retrieved 2026-10-09. SHA-256 4350c4305a83c772fa295a8be0ef86a247f2bfaae930a081720d3cd0c753abe0. Declared parameters and seed; generated trajectories and calibration observations must be labelled simulated.

Next steps. Transfer these methods to your own public or authorized data while retaining input checks, recorded parameters and result validation. Document the new experimental design and method limits; this example does not validate a new experiment. Full data licenses and generation instructions accompany the cookbook.