So far in this module, we have learned about the finite-difference solution for the linear and non-linear convection equations and the diffusion equation. It’s time to combine all these into one: Burgers’ equation.
Burgers’ equation in one spatial dimension looks like this:
Here, is the viscosity. The nonlinear convection term transports the velocity field, while the diffusion term smooths its spatial variations.
Convection and diffusion in one problem¶
In the convection problems, information traveled across the domain. In the diffusion problem, spatial variations became smoother. Burgers’ equation lets these two processes act together: the local velocity determines how fast the field is transported, while viscosity smooths its gradients. A region with larger velocity can catch a slower region ahead of it, steepening the profile as diffusion works to smooth it.
Before investigating the formation of a steep front, we need a calculation whose answer we can check. We will begin with a smooth, periodic solution that is known exactly. It travels around the domain and gradually smooths, giving us a reference against which to measure numerical error.
We will also return to a question from Lesson 6: does discretizing give the same numerical behavior as discretizing ? The two expressions agree for a smooth function, but their discrete updates need not preserve the same properties. Here we will look for preservation of the mean velocity and agreement with the exact profile. A computation can pass one check without passing the other.
Periodic domain¶
Imagine that the right end of the interval connects back to its left end. A profile leaving one side reappears on the other. The periodic boundary condition is
There is no separate inlet or outlet. For a smooth periodic Burgers solution, the spatial mean stays constant: integrating the conservative form of the equation around the domain leaves no net convective or diffusive boundary flux.
We store each physical point just once. With points, the spacing is , and the final stored point is . The point at coincides with and is excluded using endpoint=False. This differs from our earlier grids with two distinct fixed endpoints.
Reference solution¶
Let , , and . With these parameters, our reference solution is
Here is the mean velocity, while is the evolving field. Taking keeps the denominator positive. The expression is periodic and satisfies the viscous Burgers equation. Its shape translates at speed , and its variation about decays.
The parameter controls the initial shape. It is dimensionless; has units of velocity, and has units of length squared per time. The factors and are therefore dimensionless.
This expression is more complicated than the sine-decay solution in Lesson 8, but it has a similar role: it supplies an independent reference at any position and time. We will evaluate the reference solution directly in a small function. We use , , , and . We will inspect the resulting initial profile before choosing the convection discretization.
The initial condition for this benchmark is the same expression evaluated at . Note that changing viscosity in this formula also changes that initial profile.
First import NumPy and Matplotlib, choose the parameters, and construct the unique periodic grid. The four observation times will let us follow the profile through almost one circuit of the domain.
import numpy as np
import matplotlib.pyplot as plt
L = 2.0 * np.pi
U = 1.0
nu = 0.1
a = 0.95
nx = 256
plot_times = [0.0, 1.0, 3.0, 6.0]
safety = 0.8
k = 2.0 * np.pi / L
dx = L / nx
x = np.linspace(0.0, L, nx, endpoint=False)Evaluate the exact solution¶
The function exact_solution() implements the formula above. It accepts an array of positions, so NumPy evaluates the entire profile at once. We keep the parameters explicit: the same function will provide the initial array and the reference at each later time.
def exact_solution(x, t, nu, U, a, L):
'''Evaluate the smooth periodic Burgers solution.'''
k = 2.0 * np.pi / L
q = a * np.exp(-nu * k**2 * t)
theta = k * (x - U * t)
return U + 2.0 * nu * k * q * np.sin(theta) / (
1.0 + q * np.cos(theta)
)
Inspect the initial profile¶
Evaluate the exact solution at to construct u0, then plot it to see the data we will evolve. First check that and that viscosity is positive, as assumed in the reference formula.
assert 0.0 < a < 1.0
assert nu > 0.0
u0 = exact_solution(x, 0.0, nu, U, a, L)
print(f'Initial velocity range: {u0.min():.3f} to {u0.max():.3f}')
print(f'One circuit at mean speed U takes L/U = {L/U:.3f}')For plotting only, append the point at with the value at to close the periodic curve. The solver will still use the original array of unique points.
fig_initial, ax_initial = plt.subplots(figsize=(5.0, 3.0))
ax_initial.plot(
np.append(x, L), np.append(u0, u0[0]),
color='#181712', linewidth=1.8,
)
ax_initial.axhline(0.0, color='#787876', linestyle=':', linewidth=1)
ax_initial.set(xlabel='x', ylabel='u', title='Initial velocity profile',
xlim=(0.0, L), ylim=(-0.1, 1.8))
ax_initial.grid(alpha=0.25)
fig_initial.tight_layout()
plt.show()The profile lies above zero; its smallest sampled velocity is approximately 0.392. Confirm this at every grid point with np.all(u0 > 0.0): the comparison produces one Boolean value per point, and np.all returns true only if every comparison is true.
These positive initial velocities give us the setting for backward differences in convection. Later, the time-step argument will show why both numerical updates keep their values within the initial range, preserving positivity throughout the calculation.
assert np.all(u0 > 0.0)Two ways to discretize convection¶
Write and . The original pointwise update is
For a smooth solution, . Discretizing this flux derivative instead gives the conservative update:
np.roll(u, 1) supplies every left neighbor, including across the periodic seam; np.roll(u, -1) supplies every right neighbor. All terms read the old state. Backward flux differencing here is used only for positive velocities.
On paper — reconstruct the discretizations
Without copying the updates above, start from .
Use a forward difference in time, a backward difference for , and a centered second difference for . Keep the spatial terms at time level and solve for .
Rewrite the PDE as . Apply a backward difference to the flux and again solve for .
Compare your two updates with those above. Identify the term that changes, and explain why the chain rule for smooth functions does not make these two discrete expressions identical.
The pointwise update¶
burgers_step() combines the backward difference of multiplied by the local velocity with the centered second difference. We retain it as the comparison method from our earlier convection work.
def burgers_step(u, dt, dx, nu):
'''Take one periodic pointwise-convection/centered-diffusion step.'''
left = np.roll(u, 1)
right = np.roll(u, -1)
return (
u - dt / dx * u * (u - left)
+ nu * dt / dx**2 * (right - 2.0 * u + left)
)
The conservative update¶
The function conservative_burgers_step() changes only the convection term: it subtracts neighboring values of the flux . The diffusion term and periodic neighbors are identical. This isolates the effect of the convection discretization.
def conservative_burgers_step(u, dt, dx, nu):
'''Take one periodic conservative-convection/centered-diffusion step.'''
left = np.roll(u, 1)
right = np.roll(u, -1)
return (
u - dt / dx * (0.5 * u**2 - 0.5 * left**2)
+ nu * dt / dx**2 * (right - 2.0 * u + left)
)Why the conservative update preserves the mean¶
Define , counting each periodic point once. Summing the conservative update gives
Each shifted sum contains exactly the same values: both differences telescope around the periodic grid. Conservation follows from the discrete algorithm, up to floating-point roundoff.
For the pointwise scheme, the identity
instead gives
It loses mean whenever the old state is nonconstant. This is a property of the discretization, not an indexing error.
On paper — show that the mean is preserved
Reproduce the conservative mean-balance calculation without looking at the worked result above. Use indices , with periodic neighbors.
Sum the conservative update over all points and divide by to obtain an equation for .
Write out the flux differences for a three-point periodic grid. Show explicitly how every flux cancels, including the terms crossing the periodic seam.
Show that . Use this equality to cancel the diffusion contribution for any .
Conclude that the discrete mean is unchanged. Does this cancellation require the time-step restriction, or does that restriction serve a different purpose?
Derive a common time-step bound¶
For the conservative scheme, factor the flux difference and define
Then
If , then . Thus all three weights are nonnegative and sum to one whenever
Choose as the largest initial velocity. Under the time-step restriction above, both schemes update each point by taking a weighted average of old neighboring values. Neither scheme can therefore create a value outside the initial range. The largest initial velocity remains an upper bound at every later step, so we can keep the same time-step limit throughout the calculation. Since the initial velocities are all positive, the computed velocities remain positive as well.
On paper — check one update
Before running the checks below, use the periodic array with , , and .
Write the left and right neighbor arrays, including the neighbors across the periodic seam.
Calculate one update with each scheme, keeping every term at the old time level.
Sum the initial values and each updated array. Which scheme preserves the total? Explain the other scheme’s change using the mean-balance expression derived above.
Predict what both schemes will return for a constant initial array. Why does that check alone fail to distinguish the two methods?
Compare your hand-calculated values with the expected arrays in the assertions below before executing the cell. The checks also confirm that the input array is unchanged and that both schemes preserve a constant state.
# Hand-checkable periodic update: left neighbors are [1, 1, 2].
u_test = np.array([1.0, 2.0, 1.0])
np.testing.assert_allclose(
burgers_step(u_test, dt=0.1, dx=1.0, nu=0.1),
[1.01, 1.78, 1.11],
)
np.testing.assert_allclose(
conservative_burgers_step(u_test, dt=0.1, dx=1.0, nu=0.1),
[1.01, 1.83, 1.16],
)
np.testing.assert_array_equal(u_test, [1.0, 2.0, 1.0])
for step in (burgers_step, conservative_burgers_step):
constant = np.full(5, 1.5)
np.testing.assert_allclose(step(constant, 0.1, 1.0, 0.1), constant)
print('One-step values, unchanged input, and constant-state checks pass.')Integrate both methods to the same times¶
Use the initial maximum in the time-step bound and multiply the permitted step by the safety factor 0.8. The range-preservation argument lets us use this bound throughout the run.
For each observation interval, np.ceil rounds the required number of steps upward. Dividing the interval by that count gives a step no larger than the target and lands exactly at the requested time. Both methods receive that same step.
The dictionaries states and snapshots keep the two calculations separate, with each starting from its own copy of u0. We retain only the four requested profiles. Within the loop, assertions check for nonfinite values and departures from the initial range. We also record the largest mean drift over all steps and check that the conservative scheme’s drift stays below 10-12 for this run.
# Both methods start independently and use exactly the same time steps.
assert 0.0 < safety <= 1.0
dt_target = safety / (u0.max() / dx + 2.0 * nu / dx**2)
methods = {
'Pointwise': burgers_step,
'Conservative': conservative_burgers_step,
}
states = {name: u0.copy() for name in methods}
snapshots = {name: [u0.copy()] for name in methods}
step_counts = [0]
time = 0.0
total_steps = 0
max_mean_drift = {name: 0.0 for name in methods}
for target_time in plot_times[1:]:
num_steps = int(np.ceil((target_time - time) / dt_target))
dt = (target_time - time) / num_steps
for _ in range(num_steps):
for name, step in methods.items():
states[name] = step(states[name], dt, dx, nu)
actual = states[name]
assert np.all(np.isfinite(actual))
assert actual.min() >= u0.min() - 1e-12
assert actual.max() <= u0.max() + 1e-12
max_mean_drift[name] = max(
max_mean_drift[name], abs(actual.mean() - u0.mean())
)
total_steps += num_steps
for name in methods:
snapshots[name].append(states[name].copy())
step_counts.append(total_steps)
time = target_time
assert max_mean_drift['Conservative'] < 1e-12
print(f'Target time step: {dt_target:.6f}')
print(f'Total steps per method to t={time:g}: {total_steps}')
print('Maximum absolute mean drift over all steps:', max_mean_drift)Compare the profiles¶
The extra point at below is added only for plotting, by copying the value at . The numerical solver always uses the unique periodic grid.
All panels share axis limits, so changes in amplitude can be compared directly. The exact solution is drawn in ink, the pointwise result in gray, and the conservative result in red. Line styles distinguish the curves as well as color.
x_plot = np.append(x, L)
fig, axes = plt.subplots(2, 2, figsize=(7.0, 5.0), sharex=True, sharey=True)
styles = {'Pointwise': ('#787876', '-'), 'Conservative': ('#ce2406', '-.')}
for j, (ax, t) in enumerate(zip(axes.flat, plot_times)):
reference = exact_solution(x, t, nu, U, a, L)
ax.plot(x_plot, np.append(reference, reference[0]),
color='#181712', linestyle='--', linewidth=2, label='Exact')
for name, (color, linestyle) in styles.items():
numerical = snapshots[name][j]
ax.plot(x_plot, np.append(numerical, numerical[0]),
color=color, linestyle=linestyle, linewidth=1.7, label=name)
ax.axhline(U, color='#b4b4b2', linewidth=0.8)
ax.set_title(f't = {t:g}')
ax.set_xlim(0.0, L)
ax.grid(alpha=0.25)
axes[0, 0].legend(fontsize=8)
for ax in axes[-1, :]:
ax.set_xlabel('x')
for ax in axes[:, 0]:
ax.set_ylabel('u')
fig.suptitle('Smooth periodic Burgers solution', fontsize=12)
fig.tight_layout()
plt.show()Measure what the plot cannot establish¶
The curves are close enough that visual agreement alone is difficult to judge. Compute the maximum error over the grid and the change in the discrete mean:
The first quantity measures agreement with the exact reference. The second measures whether the algorithm preserves its initial discrete mean; it uses the sampled initial mean rather than assuming that a finite grid integrates the exact profile perfectly. Neither diagnostic replaces the other.
print(f"{'Time':>5} {'Method':>13} {'Steps':>7} "
f"{'Maximum error':>16} {'Mean drift':>16}")
for j, (t, steps) in enumerate(zip(plot_times, step_counts)):
reference = exact_solution(x, t, nu, U, a, L)
for name in methods:
numerical = snapshots[name][j]
error = np.max(np.abs(numerical - reference))
drift = numerical.mean() - u0.mean()
print(f'{t:5.1f} {name:>13} {steps:7d} '
f'{error:16.6e} {drift:16.6e}')At , the maximum error is about 0.0216 for the pointwise scheme and 0.0101 for the conservative scheme. The pointwise mean has decreased by about 0.00453, while the conservative mean is preserved to roundoff. The negative drift agrees with the sum-of-squares expression derived above.
For these parameters and this grid, the conservative scheme both preserves the mean and has a smaller maximum error. Conservation does not guarantee a smaller error in every comparison, and a single grid does not establish convergence. We have checked an important discrete property and measured accuracy for one smooth problem.
Self-checks
Why does periodicity make the conservative flux differences sum to zero?
Both schemes preserve a constant state. Why is that check insufficient to distinguish them?
Does preserving the mean imply that the computed profile has the correct shape? Use the two columns of the table to support your answer.
Convection steepens and diffusion smooths¶
The reference problem let us check the algorithms against a known solution. Now use the conservative update to investigate the competition in Burgers’ equation. Can a smooth wave develop a steep front before diffusion smooths it away?
Choose a new initial condition on the same periodic domain:
Keep and , and choose . The velocity initially ranges from 0.25 to 1.75. Unlike our reference family, this initial profile does not depend on viscosity. We can change while keeping the initial data fixed, so differences between the calculations reveal the effect of diffusion.
On the descending side of the wave, larger velocities lie behind smaller ones. The faster part catches the slower part, compressing the profile and making its slope more negative. On the ascending side, faster values lie ahead and pull away. Diffusion opposes the formation of sharp spatial variations. Which effect dominates depends on the viscosity, the profile, and the length scale being examined.
We will compare and at the same physical times. With positive viscosity the front remains continuous: a thin, steep transition is often called a viscous shock. It is not a discontinuity.
On paper — predict the competition
Sketch the initial sine profile. Mark two nearby points on its descending side and indicate which has the larger velocity. Predict how their separation changes under convection. Repeat for the ascending side. Which viscosity do you expect to permit a steeper front? Explain why changing the initial data along with viscosity would make this comparison harder to interpret.
Reuse the conservative update¶
The function below organizes repeated calls to conservative_burgers_step(); it introduces no new numerical method. As before, it chooses a step from the initial maximum, adjusts it to reach each requested time, and saves only those profiles. We will reuse it for both viscosities and for the grid check. The requested times start at zero and increase.
def advance_periodic_burgers(initial_state, dx, nu, times, safety=0.8):
'''Advance positive periodic data and save the requested profiles.'''
assert np.all(initial_state > 0.0)
assert nu > 0.0
assert 0.0 < safety <= 1.0
assert times[0] == 0.0 and np.all(np.diff(times) > 0.0)
lower = initial_state.min()
upper = initial_state.max()
dt_target = safety / (upper / dx + 2.0 * nu / dx**2)
state = initial_state.copy()
profiles = [state.copy()]
for start, end in zip(times[:-1], times[1:]):
num_steps = int(np.ceil((end - start) / dt_target))
dt = (end - start) / num_steps
for _ in range(num_steps):
state = conservative_burgers_step(state, dt, dx, nu)
assert np.all(np.isfinite(state))
assert state.min() >= lower - 1e-12
assert state.max() <= upper + 1e-12
assert abs(state.mean() - initial_state.mean()) < 1e-12
profiles.append(state.copy())
return profilesHold the initial data fixed¶
Use 512 unique periodic points for the first comparison. The two runs begin with the same sine array and finish at the same observation times. Their time steps can differ: each must satisfy the combined convection–diffusion restriction for its viscosity. Reducing viscosity does not remove the convection contribution to that restriction.
In your notebook
Construct the sine initial condition and run both viscosities using the conservative update. Before plotting, record your prediction about which side steepens and which calculation retains more of its initial variation.
sine_amplitude = 0.75
sine_nx = 512
sine_dx = L / sine_nx
sine_x = np.linspace(0.0, L, sine_nx, endpoint=False)
sine_initial = U + sine_amplitude * np.sin(2.0 * np.pi * sine_x / L)
sine_times = [0.0, 0.5, 1.0, 2.0]
viscosities = [0.5, 0.05]
sine_profiles = {}
for viscosity in viscosities:
sine_profiles[viscosity] = advance_periodic_burgers(
sine_initial, sine_dx, viscosity, sine_times, safety,
)The panels use common axes. Gray shows the larger viscosity; red shows the smaller one. At zero time the curves coincide because their initial conditions are identical. A duplicated endpoint closes each curve for plotting only.
sine_x_plot = np.append(sine_x, L)
fig_sine, axes_sine = plt.subplots(
2, 2, figsize=(7.0, 5.0), sharex=True, sharey=True,
)
viscosity_styles = {
0.5: ('#787876', '--'),
0.05: ('#ce2406', '-'),
}
for j, (ax, time) in enumerate(zip(axes_sine.flat, sine_times)):
for viscosity in viscosities:
profile = sine_profiles[viscosity][j]
color, linestyle = viscosity_styles[viscosity]
ax.plot(
sine_x_plot, np.append(profile, profile[0]),
color=color, linestyle=linestyle, linewidth=1.8,
label=fr'$\nu={viscosity:g}$',
)
ax.axhline(U, color='#b4b4b2', linewidth=0.8)
ax.set_title(f't = {time:g}')
ax.set_xlim(0.0, L)
ax.set_ylim(0.15, 1.85)
ax.grid(alpha=0.25)
axes_sine[0, 0].legend(fontsize=8)
for ax in axes_sine[-1, :]:
ax.set_xlabel('x')
for ax in axes_sine[:, 0]:
ax.set_ylabel('u')
fig_sine.suptitle('Same initial wave, different viscosities', fontsize=12)
fig_sine.tight_layout()
plt.show()The larger viscosity rapidly reduces the wave’s variation. With the smaller viscosity, the descending side becomes much steeper while the ascending side spreads out. Convection and diffusion act in both calculations; the smaller viscosity allows a thinner transition to develop.
This is the behavior we wanted to observe, but the plot raises a numerical question: is the computed thickness of the front set by physical viscosity, or partly by the grid? A conservative scheme can preserve the mean while smoothing a front too much. The exact-solution comparison verified behavior for that benchmark; it did not certify this new calculation at every viscosity and resolution.
Check the thinner front on finer grids¶
Keep , the initial sine function, and the final time fixed. Compare 256, 512, and 1024 points, recomputing the permitted time step on each grid. Reuse the existing 512-point run.
We will measure the steepest descending slope using a centered difference and compare neighboring-grid solutions at their shared points. These grids are nested: every second point of a fine grid coincides with a point of the next coarser grid. The slice [::2] selects those matching points.
The slope tells us whether refinement changes the front’s sharpness. The maximum difference between grids tells us how much the final profile changes; it is not an error against an exact solution.
front_viscosity = 0.05
front_grids = [256, 512, 1024]
front_results = {
sine_nx: (sine_x, sine_dx, sine_profiles[front_viscosity][-1]),
}
for grid_size in front_grids:
if grid_size == sine_nx:
continue
grid_dx = L / grid_size
grid_x = np.linspace(0.0, L, grid_size, endpoint=False)
initial = U + sine_amplitude * np.sin(2.0 * np.pi * grid_x / L)
profiles = advance_periodic_burgers(
initial, grid_dx, front_viscosity, sine_times, safety,
)
front_results[grid_size] = (grid_x, grid_dx, profiles[-1])
print(f"{'Points':>8} {'Steepest descending slope':>27} "
f"{'Difference to next grid':>25}")
for j, grid_size in enumerate(front_grids):
grid_x, grid_dx, final = front_results[grid_size]
derivative = (np.roll(final, -1) - np.roll(final, 1)) / (2.0 * grid_dx)
if j < len(front_grids) - 1:
finer = front_results[front_grids[j + 1]][2]
difference = np.max(np.abs(final - finer[::2]))
difference_text = f'{difference:.6f}'
else:
difference_text = '—'
print(f'{grid_size:8d} {derivative.min():27.3f} '
f'{difference_text:>25}')The steepest descending slope changes from approximately -3.49 to -3.84 to -4.06 as the grid is refined. For comparison, the initial sine profile has minimum slope -0.75. Thus steepening is clear on all three grids, but the computed front continues to sharpen with refinement.
The maximum difference drops from about 0.0326 between the first two grids to 0.0191 between the next two. This supports decreasing grid sensitivity, but it does not establish an exact error or a fully resolved front thickness. Our defensible conclusion is that the smaller viscosity permits a steep transition and that resolution still affects its computed shape. A quantitative claim about front thickness would need a stated tolerance and further refinement evidence.
Self-checks
Identify the descending side at zero time and follow it through the four panels. Does its evolution match your prediction?
Why can both viscosity runs preserve the same mean while their profiles become very different?
What does the grid comparison add that a mean-conservation check cannot tell you?
If you reduce viscosity again, why is reusing the same grid without checking resolution insufficient, even when the time step satisfies the bound?
Verification with an agent¶
Does the solver approach the exact solution?¶
The sine-wave experiment showed that the computed front changes under refinement. Without an exact answer for that initial condition, differences between grids measure grid sensitivity, not error. Return now to the smooth periodic reference, where we can measure the error directly.
Use the conservative solver to ask: does its error decrease at the rate suggested by the discretization? The repeated grid setup and bookkeeping are useful work to delegate. You will supply the numerical question, predict the behavior, inspect the agent’s proposed experiment, and decide what the evidence supports. The agent will draft code to organize the runs and measurements without changing the numerical method.
Step 1 — Predict before delegating¶
For a smooth solution, backward differencing of the convection flux is first order in space, centered diffusion is second order in space, and forward Euler is first order in time. The expected leading error contributions have the form
with coefficients that depend on the solution and comparison time. Our step restriction couples space and time. At fixed positive viscosity, sufficiently fine grids make the diffusion contribution to the restriction dominant, so scales like . The first-order spatial term should then dominate the error, provided its coefficient is nonzero and the grid is fine enough.
On paper — set expectations
Use the combined time-step bound to explain why halving eventually requires approximately four times as many time steps to reach the same physical time.
Predict the error ratio when the first-order spatial term dominates. Why might a coarse-grid ratio differ from that prediction?
Explain why every run must use the same initial function, viscosity, and final physical time. Why would fixing the number of time steps instead change the experiment?
Record these expectations in your notebook before contacting the agent. They are predictions to test, not output values the agent should be instructed to produce.
Step 2 — Specify the measurements¶
For each grid, you will compare the computed final array with the exact reference evaluated at those same positions and at :
Here is the observed order for a pair of grids. This is a combined space–time refinement study; it does not independently measure the temporal order. An error ratio near two gives an observed order near one.
Use these fixed problem data:
Reference parameters: , , , and .
Unique periodic grid sizes: .
Final time: ; use observation times
[0.0, T].Safety factor:
0.8in the existing combined step restriction.
These are the reference initial data from exact_solution(), not the sine initial condition. Use distinct experiment variable names so that the preceding viscosity study cannot silently supply the wrong parameters.
Retain each grid’s positions, initial array, computed final array, exact final array, and measured error so you can audit a result. Request one table with grid size, spacing, time-step count, actual time step, maximum error, error ratio, and observed order. Put each ratio and order on the coarser row of its grid pair; leave them blank on the final row. The existing runner does not return step counts: the verification code can calculate them from the same stated step-selection formula without modifying the runner.
Step 3 — Write the brief and steer your agent¶
With an agent — draft the verification code
Write a short task brief in your own notebook, using Steps 1 and 2 to supply the numerical specification. Include:
Goal and interface: call your existing
exact_solution()andadvance_periodic_burgers(), which callsconservative_burgers_step(). State their argument order, the fixed problem data, and the required retained arrays and table.Scope: add only unexecuted experiment cells at the end of your notebook. Do not redefine or edit the three existing functions, change earlier cells, install packages, access the network, or execute code. Do not ask for a plot or an interpretation.
Acceptance evidence: every grid must start from fresh exact initial data, reach the same final time, and report measurements computed from the retained arrays. Do not hard-code errors, ratios, or orders, and do not adjust the method or parameters to obtain the predicted trend.
Then ask the agent to read your brief, restate the experiment in a few sentences, and identify any missing information before drafting code. Check that restatement against your specification. Correct any mismatch, then ask it to add the verification code and a short change record within the agreed scope.
If your interface cannot edit a notebook, ask for proposed cells in chat and insert them yourself after inspection. In either case, you remain responsible for reviewing the code before execution.
The staged request gives you a chance to catch a misunderstanding before it becomes code. For example, a proposal to compare against the next finer grid would answer a different question from the exact-error study specified here.
Step 4 — Audit, then execute¶
Inspect the proposed cells and notebook diff. Check that the agent:
uses
endpoint=Falseanddx=L/N, with fresh reference initial data on every grid;calls the existing functions unchanged, passes the correct parameters, and uses
[0.0, T];reports the adjusted step that reaches , rather than just the target step;
compares the final numerical array with the exact solution on the same grid at , using the maximum absolute difference;
forms coarse-error/fine-error ratios in the correct order and computes from those ratios;
retains the arrays and changes only the permitted cells.
If a check fails, ask for a correction confined to the added cells and inspect again. Once the code passes review, run it one cell at a time.
In your notebook — verify one row independently
Choose one grid and recompute its maximum error from the saved final array and a fresh call to exact_solution() at . Do this in your own new cell, without reusing the error field computed from the agent’s code. Then use two neighboring errors to calculate one ratio and observed order yourself. Compare with the table.
If you need a starting point, first write down which arrays have the same spatial positions and time. Subtract them, take absolute values, and find the largest entry. For the order, check that the larger spacing is in the numerator of the error ratio.
A plausible table is not enough if its measurements do not match the saved solutions. Conversely, an observed order away from one is a result to investigate, not permission to ask the agent to alter the calculation until it passes. First check the specification, implementation, and whether the tested grids appear to have reached the predicted refinement regime.
Step 5 — Make the numerical judgment¶
Your verdict
Write a short conclusion supported by your table and independent check:
Did you accept the agent’s first proposal or request revisions? Identify one part of the specification or audit for which your judgment mattered.
How did the measured errors and observed orders change under refinement? Does the evidence support the predicted first-order trend for this smooth benchmark?
What do the mean-preservation check and exact-error study establish separately? Why is neither a substitute for the other?
Does success on this reference establish that the low-viscosity sine-wave front is fully resolved? Explain using the earlier grid comparison.
Leave a brief agent record: name the agent, preserve your brief and any corrective request, state what it could access or change, and record the checks you performed yourself.
Note the limits of your conclusions. Conservation is a property of the discrete update, while agreement with a known solution under refinement supplies evidence about accuracy for the tested problem. A thin front at another viscosity still requires its own resolution evidence.