Better numerics for Berton 2023 model
<skill name="grill-me" location="[REDACTED_LOCAL_PATH]">
References are relative to [REDACTED_LOCAL_PATH]
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Ask the questions one at a time.
If a question can be answered by exploring the codebase, explore the codebase instead.
</skill>
The numerical method used in stepping the Berton 2023 model is very unsophisticated (explicit Euler only). I'm pretty sure that the model is quite stiff, which is what leads to the very small timestep requirement to make the numerics work. Please add options to make use of different timestepping methods, ideally exposing an API that makes it easy to swap in an ODE integration method from scipy.integrate. The existing explicit Euler method should be preserved as an option that can be explicitly selected.
Good call on stiffness. I checked the code: simulate(...) is hard-wired to euler_step(...), so this is very straightforward to generalize.
Question 1 (only one at a time):
How should dt behave with non-Euler integrators?
- A) keep
dtas a strict fixed step/time index (backward-compatible behavior), and let SciPy methods still be forced to that cadence, or - B) treat
dtas output cadence only, while SciPy decides its own internal step size unless the user explicitly overrides it.
Recommended answer: A for now, with optional override via solver options (e.g., scipy_options={"max_step": ...}), because it preserves existing semantics and avoids surprising behavior changes.
OK, but will that not be a little misleading for solvers that do not provide a fixed timestep? I was thinking that we would probably have some sort of integration method parameter to the simulation function: setting it to "euler" would give the current behavior, while setting it to anything else would use scipy.integrate.solve_ivp with the given method. Time control for most of the scipy integrators is not by fixed timestep, and solve_ivp takes a time output argument (called t_eval in the docs) which is based on the desired output cadence. I would like to be able to use the new integration API in two modes: one where an output timestep is given, for direct comparison between new integration methods and the explicit Euler method; and a "free output timestep" method, where the integrator chooses the output times based on tolerance and solution smoothness.
Yes—you're right. For non-Euler methods, dt should be output cadence only (not the internal step), with solve_ivp controlling its own adaptivity unless fixed output is requested.
Question 2 (one at a time):
How should SciPy solver options be exposed?
- A) Explicit fields in
SimulationConfig(e.g.,rtol,atol,max_step) - B) A generic passthrough
scipy_options: dict[str, Any](plus method name)
Recommended answer: B (generic passthrough), so users can pass method-specific kwargs without us pinning API changes per integrator.
Yes, B is better, I think.
Great clarification. Good call.
Question 3:
For SciPy output control, do you want to add a dedicated output_dt parameter (Quantity) and keep sample_every as legacy Euler-only behavior, or do you want to deprecate sample_every and route everything through output_dt?
Recommended answer: Keep both for now:
output_dtfor physical-time output across all methods (includingeuler)sample_everyretained as legacy Euler-only fallback/default, since tests and existing scripts already use it.
OK, yes. There are two "bridging" things going on here: first, using the explicit Euler method at all was just part of replicating the Berton 2023 paper results; second, having a fixed Δt output mode is there just for validating the behavior of new integration methods compare to the explicit Euler method. The first of those things has been validated already, and once the second is also validated, neither the explicit Euler method nor the fixed timestep output will be used any more. Further work on this model will use an efficient integrator, and will allow the integrator to choose output times based on the model.
Question 4:
When integration_method != "euler" and sample_every is passed (legacy param), should we:
- A) ignore it silently and rely on
output_dt/Nonebehavior, or - B) raise a
ValueErrorto forceoutput_dtfor non-Euler modes?
Recommended answer: A, but with an explicit doc note: sample_every is Euler-only; for non-Euler methods use output_dt or leave unset for adaptive output.
Agreed.
Implemented. I added a configurable integration API with explicit Euler preserved, and added support for SciPy solve_ivp methods.
What changed
src/cloud_rom/berton2023.pySimulationConfignow includes:
- integration_method: str = "euler" (legacy default)
- output_dt: Quantity | None = None
- scipy_options: dict[str, Any] = {}
simulate(...)now supports:
Show remaining 29 lines
- integration_method="euler": same explicit-Euler behavior (including legacy sample_every)
- other SciPy methods (e.g. "RK45", "Radau", etc.) via scipy.integrate.solve_ivp
- output_dt for fixed output times (for direct comparison)
- adaptive output when output_dt is None
- passthrough scipy_options
- sample_every is Euler-only and ignored for SciPy methods
- Added internal helpers for:
- ODE RHS conversion
- fixed-output grid generation
- mass-termination event handling
tests/test_berton2023.py(new coverage)test_euler_can_use_fixed_output_dttest_rk45_supports_scipy_method_with_fixed_output_dttest_rk45_adaptive_output_is_not_forced_to_fixed_step
- Docs updated
docs/berton2023-model-code.mddocs/MODEL_EXTRACTION.md
- Minor typing fix in plotting helper
src/cloud_rom/berton2023_plots.py: safegetattraccess in a comprehension to keeppyrighthappy withitertuples.
Validation
uv run pytest -q✅ (10 passed)uv run pyright✅ (0 errors)
If you want, I can now do a follow-up pass to add a small public convenience like simulate(..., method="RK45") (without changing SimulationConfig), so callers don’t need to touch config for one-off experiments.
<skill name="grill-me" location="[REDACTED_LOCAL_PATH]">
References are relative to [REDACTED_LOCAL_PATH]
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Ask the questions one at a time.
If a question can be answered by exploring the codebase, explore the codebase instead.
</skill>
Yes, please add that convenience function. Also please add a new notebook (notebooks/integration-methods.ipynb) that does side-by-side comparisons of the results of the explicit Euler integration (saved as df_steady_magnitudes.csv and df_oscillatory_magnitudes.csv from the replicate-{steady,oscillatory}-state.ipynb notebooks) with fixed output time simulations using the Radau, CDF and LSODA scipy integration methods. As well as the comparison to the explicit Euler method, the notebook should also demonstrate the "native" time outputs from the new integration methods.
One clarification before I implement the notebook:
Question 1: Did you mean SciPy’s BDF method, not CDF?
SciPy solve_ivp supports Radau, BDF, and LSODA; I don’t think it has a CDF method.
Recommended answer: Yes, use BDF alongside Radau and LSODA.
Yes, BDF. That was a typo.
Implemented.
Added convenience API
- Added
b.simulate_with_method(...)insrc/cloud_rom/berton2023.py - Example:
```python
df = b.simulate_with_method(
"Radau",
state,
Show remaining 38 lines
atmosphere,
config=cfg,
output_dt=b.Q_(10, "s"),
scipy_options={"rtol": 1e-6, "atol": 1e-9},
)
```
- Supports
"euler"and any SciPysolve_ivpmethod ("Radau","BDF","LSODA", etc.).
Added notebook
- New notebook:
notebooks/integration-methods.ipynb
It compares saved Euler CSVs:
notebooks/df_steady_magnitudes.csvnotebooks/df_oscillatory_magnitudes.csv
against fixed-output simulations using:
RadauBDFLSODA
It also demonstrates native/adaptive solver output times with output_dt=None.
Updated docs/tests
- Updated:
docs/berton2023-model-code.mddocs/MODEL_EXTRACTION.mddocs/notebooks.md- Added tests for
simulate_with_method(...).
Validation
uv run pyright✅uv run pytest -q✅ — 11 passed
Please add some progress tracking for the integrations to the integration methods notebook.
Added progress tracking.
Changes:
src/cloud_rom/berton2023.py- SciPy
solve_ivpintegrations now use the existingprogress/progress_descargs. - Progress bar tracks elapsed model seconds during solver RHS calls.
notebooks/integration-methods.ipynb- Fixed-output and native-output runs now call
simulate_with_method(..., progress=True, progress_desc=...). - Added markdown note explaining progress behavior.
Show remaining 3 lines
Validation:
uv run pyright✅uv run pytest -q✅ — 11 passed
Please commit the changes.
Committed changes.
Commit: 75a8d8b Add configurable ODE integration methods
Goal
Add configurable timestepping/integration options to the Berton 2023 model, preserving explicit Euler while enabling scipy.integrate.solve_ivp methods and adaptive output behavior.
Constraints & Preferences
- Ask design questions one at a time.
- If a question can be answered by exploring the codebase, explore instead.
- Preserve existing explicit Euler method as an explicitly selectable option.
- Prefer API that makes swapping SciPy ODE integrators easy.
- For non-Euler methods,
dtshould not imply internal fixed timestep. - Want two SciPy output modes:
- fixed output cadence for comparison with Euler;
- free/adaptive output times chosen by integrator.
- Generic SciPy options passthrough is preferred over many explicit config fields.
Progress
Done
- [x] Inspected repository structure.
- [x] Located main implementation in
src/cloud_rom/berton2023.py. - [x] Confirmed
simulate(...)currently callseuler_step(...)directly. - [x] Reviewed existing docs and tests mentioning Euler integration.
- [x] Clarified that
solve_ivpshould use adaptive internal stepping, with optional fixedt_evaloutput.
In Progress
- [ ] Resolving API design details before implementation.
Blocked
- Awaiting user answer to current design question about how
sample_everyshould behave for non-Euler methods.
Key Decisions
- Integrator selection: Add an integration method parameter/config;
"euler"preserves current behavior, other values usescipy.integrate.solve_ivp. - SciPy timestep semantics: For non-Euler methods,
dt/output cadence should map tot_eval, not force internal fixed timesteps. - SciPy options exposure: Use a generic passthrough such as
scipy_options: dict[str, Any]. - Output cadence API: Add
output_dtfor physical-time output across methods; retainsample_everyas legacy Euler behavior for compatibility. - Long-term direction: Euler and fixed timestep output are mainly validation/bridging paths; future model work should use efficient adaptive integrators.
Next Steps
- Ask/resolve whether
sample_everywith non-Euler methods should be ignored or rejected. - Inspect
State,euler_step,accelerations, andsimulateinsrc/cloud_rom/berton2023.pyin detail. - Design state-vector conversion helpers for
solve_ivp. - Add integration config fields/method parameter while preserving backward compatibility.
- Implement SciPy integration path using
solve_ivp. - Update tests in
tests/test_berton2023.py. - Update docs in
docs/berton2023-model-code.mdand examples if needed.
Critical Context
- Main file:
src/cloud_rom/berton2023.py - Current integration functions:
SimulationConfigeuler_step(...)simulate(...)- Current docs say
simulateperforms repeated Euler stepping. - Existing dependency
scipyis already present inpyproject.toml. - Current unanswered question:
- When
integration_method != "euler"andsample_everyis passed, should it be ignored with docs or raiseValueError?
Turn Context (split turn):
Original Request
Add support for non-Euler ODE integration methods (e.g. SciPy solve_ivp/RK45) to the Berton 2023 cirrus parcel model while preserving the paper-matching explicit Euler default.
Early Progress
- Updated
src/cloud_rom/berton2023.py: - Added imports for
numpy,solve_ivp, anddataclasses.field. - Extended
SimulationConfigwith:
- integration_method: str = "euler"
- output_dt: Quantity | None = None
- scipy_options: dict[str, Any] = field(default_factory=dict)
- Added SciPy integration helpers:
- _state_from_vector
- _ode_rhs
- _nonpositive_mass_event
- _fixed_output_times
- _euler_output_indices
- Modified
simulate(...):
- Uses explicit Euler when integration_method == "euler".
- Uses solve_ivp for other methods.
- Supports output_dt fixed outputs.
- Keeps Pint-valued DataFrame output.
- Preserves nonpositive-mass stopping via SciPy event.
- Added tests in
tests/test_berton2023.pyfor: - Euler fixed
output_dt. - RK45 fixed
output_dt. - RK45 adaptive output when
output_dt=None. - Fixed a syntax error in the new Euler test.
- Fixed SciPy event callback signature to accept extra
args. - Fixed Pyright complaints about assigning
.terminal/.directionto event functions by casting throughAny. - Updated docs:
docs/berton2023-model-code.mdnow documentsintegration_method,output_dt,scipy_options, and RK45 example.docs/MODEL_EXTRACTION.mdnow notes Euler is default but SciPy methods are selectable.- Pyright initially failed due to an unrelated
berton2023_plots.pytuple attribute issue; changedrow.w/row.ztogetattr(row, "w")/getattr(row, "z").
Context for Suffix
- Validation commands run successfully after fixes:
uv run pytest -q→10 passeduv run pyright→0 errors- Modified files at the end of the prefix:
src/cloud_rom/berton2023.pytests/test_berton2023.pydocs/berton2023-model-code.mddocs/MODEL_EXTRACTION.mdsrc/cloud_rom/berton2023_plots.py- There was a temporary restore of
berton2023_plots.py, but the Pyright-relatedgetattr(...)change was reapplied and remains part of the working diff.
<read-files>
pyproject.toml
src/cloud_rom/__init__.py
</read-files>
<modified-files>
docs/MODEL_EXTRACTION.md
docs/berton2023-model-code.md
src/cloud_rom/berton2023.py
src/cloud_rom/berton2023_plots.py
tests/test_berton2023.py
</modified-files>
<skill name="grill-me" location="[REDACTED_LOCAL_PATH]">
References are relative to [REDACTED_LOCAL_PATH]
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Ask the questions one at a time.
If a question can be answered by exploring the codebase, explore the codebase instead.
</skill>
Please now write a page for the project website (which will go in
[REDACTED_LOCAL_PATH]) describing the integration updates, including figures
comparing the different methods, both in terms of the outputs and in terms of the total integration times
needed for the steady and oscillatory simulations. I would like to experiment with using Vega-Lite for interactive plots in the website, so please use that for this page.
Question 1: Should I add a reusable website component/dependencies for Vega-Lite, or keep this page self-contained with CDN-loaded Vega scripts?
Recommended answer: Add a small reusable VegaLite.astro component and install vega, vega-lite, and vega-embed as project dependencies. That makes the experiment production-buildable, avoids relying on CDN availability, and lets future project pages reuse the same component.
Agreed.
Question 2: Where should the plotted/benchmark data come from at site build time?
Options:
- Generate static JSON/CSV artifacts now from the
cloud-romcode and commit them under the website, then Vega-Lite reads those static files. - Have the website build import/run the simulation code directly.
- Embed the data inline in the MDX page.
Recommended answer: Generate and commit static JSON artifacts under the website, e.g. src/data/berton-integration-methods/*.json. The website should not depend on importing/running the research Python code during Astro builds, and inline data would make the MDX page bulky and hard to maintain.
Agreed.
Question 3: For “total integration times”, should the page show single-run wall-clock timings, or more stable repeated benchmark summaries?
Recommended answer: Use repeated timings and plot the median wall-clock time for each scenario/method/output mode, with min/max or quartile ranges if easy. Single-run times are too noisy, especially for LSODA/BDF startup overhead and laptop load. I’d use a modest default like 3 repeats so artifact generation remains practical, and record the machine/context caveat in the page.
Sounds good.
Question 4: How much trajectory data should we include for interactive Vega-Lite plots?
Full fixed-output baselines are [REDACTED_LOCAL_PATH],800 steady rows and [REDACTED_LOCAL_PATH],400 oscillatory rows; multiplied by Euler + 3 methods + several variables is still fine. Native/adaptive outputs are probably smaller but variable. However, embedding/serving too many series can make the page sluggish if we include lots of diagnostics.
Recommended answer: Keep the site artifacts focused:
- include trajectories for altitude offset (
z_minus_z0_km), mass (m_ug), and maybe vertical velocity (w_m_s); - include both scenarios, all methods, and both output modes;
- do not include every diagnostic column from the notebooks;
- downsample only if needed after checking artifact size.
Agreed.
Question 5: For the timing comparison, should we time both fixed-output and native/adaptive-output integrations, or only fixed-output?
Recommended answer: Time both. Fixed-output timing answers “how expensive is a direct Euler-comparison run?”, while native/adaptive timing answers “how expensive is the method in normal use?”. The page can facet or color by output mode.
Yes, both.
You will probably need longer timeouts for some of these simulations. The oscillatory case may take a long time to run. For reference, in 70 seconds, you just got about 12,500 steps into a 900,000 step simulation. Set a conservative timeout. There's no rush.
Implemented the website page and Vega-Lite plumbing.
Added
- New reusable component:
website/src/components/VegaLite.astro- Vega dependencies:
vegavega-litevega-embed
Show remaining 35 lines
- New project page:
website/src/content/project/berton-integration-methods.mdx- Static data artifacts:
website/public/data/berton-integration-methods/trajectories.jsonwebsite/public/data/berton-integration-methods/timings.jsonwebsite/public/data/berton-integration-methods/timing-runs.jsonwebsite/public/data/berton-integration-methods/metadata.json
Page includes
- Interactive fixed-output comparison:
- saved Euler CSV baseline
RadauBDFLSODA- Interactive native/adaptive-output comparison.
- Timing comparison:
- median of 3 full SciPy runs
- min/max range
- projected Euler timing from short 2,000-step benchmarks, clearly marked/explained.
- Quantity selector for:
- altitude offset
- crystal mass
- vertical velocity
Validation
Ran:
cd [REDACTED_LOCAL_PATH]
npm run build
Build succeeds. There are pre-existing TypeScript deprecation hints and a Vite large-chunk warning from Vega, but no errors.
That's OK, but there are some changes needed. Let's improve the time series plots first:
- The steady-state and oscillatory solutions should be displayed separately, because they are of very different timescales. The plot panels in the "Fixed-output comparisons" and "Native solver output times" sections should have a tabbed layout, one "Steady" tab for the steady solution and one "Oscillatory" tab for the oscillatory solution. Implement the tab layout as an MDX component so that it's reusable.
- It should be possible to show/hide the individual traces on the time series plots, i.e. the "Method" laegend entries should be on/off switches for those traces. (Incidentally, use "Method" and "Quantity" for labels, not "method" and "quantity", and style the legends the same - currently one has lines and one has filled circles.)
- Label the time axis as "Time (h)", not "time (h)".
Updated the time-series plots as requested.
Changes made in the website project:
- Added reusable MDX tab components:
src/components/TabSet.astrosrc/components/TabPanel.astro- Updated the integration methods page so both time-series sections now use tabs:
- Steady
- Oscillatory
Show remaining 18 lines
- Split Vega-Lite time-series specs by scenario instead of faceting steady/oscillatory together.
- Added interactive Method legend selection:
- click Method legend entries to show/hide traces.
- Updated visible labels:
QuantityMethodTime (h)- Styled the Method legends consistently with line-style symbols.
- Added tab styling in
src/styles/global.css.
Validation:
cd [REDACTED_LOCAL_PATH]
npm run build
Build succeeds. Existing deprecation hints and Vega chunk-size warning remain.
Getting better. Some more changes:
- The method selection UI is strange. Each method entry in the legend should have the semantics of a checkbox: switch a single trace on or off.
- There is no data for the Euler method on the native solver output times plots.
- The outer containing boxes for the plots extend the whole width of the page, but the plots within the box do not. Make the width of the outer boxes conform to the width of the article body text, and scale the time axis of the plots appropriately so they fit within the outer box.
Made those plot/UI adjustments.
Changes
- Method legend now behaves more like checkbox toggles:
- all traces start visible;
- clicking a Method legend entry toggles that method on/off rather than isolating it.
- Native solver plots no longer show an Euler legend entry, since there is no native Euler-output dataset.
- Plot containers now use the article body width instead of the wide page rail.
- Time-series Vega specs now use responsive container width:
Show remaining 16 lines
width: "container"autosize: { type: "fit", contains: "padding" }- Updated Vega rendering so charts inside inactive tabs are rendered only when their tab becomes visible. This avoids hidden-tab width calculation problems.
- Kept axis/label cleanup:
Time (h)QuantityMethod
Validation:
cd [REDACTED_LOCAL_PATH]
npm run build
Build succeeds.
OK, let's look at the integration times plot now. There is no data visible for the non-Euler methods, either because the times are so much shorter or because there's a problem with the plot. The wall-clock time axis label on the left claims to be on a log scale, but the right hand scale is linear. Please make the time axis a log axis and ensure that the data for the non-Euler methods is visible.
Updated the integration-times plot.
Fixes
- Reworked the timing Vega-Lite spec as an explicit faceted chart with a layered inner spec.
- Applied the log scale directly to the timing layers:
- median bar layer
- min/max rule layer
- Set a shared log-domain:
1to30000seconds
Show remaining 12 lines
- Updated axis title:
Median wall-clock time (s)- The non-Euler methods should now be visible alongside the much slower Euler estimate.
Validation:
cd [REDACTED_LOCAL_PATH]
npm run build
Build succeeds.
The integration time plots should use the same tabbed layout for the steady/oscillatory cases as for the time series plots.
Done.
The integration time plot now uses the same tabbed layout:
- Steady
- Oscillatory
Each tab shows the fixed-output/native-output timing comparison for that scenario only.
Validation:
Show remaining 7 lines
cd [REDACTED_LOCAL_PATH]
npm run build
Build succeeds.
The "fixed output" and "native output" labels in those plots should be "Fixed output" and "Native output".
Updated the integration time plot labels to:
Fixed outputNative output
Also updated the tooltip field label to Output mode.
Build still succeeds.
Now, a question: is it possible to make the fonts used in the Vega-Lite plots match the fonts used in the website?
Yes. Vega-Lite lets us set fonts globally in the spec config, e.g. for axis labels, axis titles, legends, headers, and text marks.
For this site, the relevant CSS font is:
--font-ui: "STIX Two Text", Georgia, "Times New Roman", serif;
So we can add a shared Vega-Lite config like:
Show remaining 23 lines
export const vegaConfig = {
config: {
font: 'STIX Two Text, Georgia, Times New Roman, serif',
axis: {
labelFont: 'STIX Two Text, Georgia, Times New Roman, serif',
titleFont: 'STIX Two Text, Georgia, Times New Roman, serif',
},
legend: {
labelFont: 'STIX Two Text, Georgia, Times New Roman, serif',
titleFont: 'STIX Two Text, Georgia, Times New Roman, serif',
},
header: {
labelFont: 'STIX Two Text, Georgia, Times New Roman, serif',
titleFont: 'STIX Two Text, Georgia, Times New Roman, serif',
},
},
};
Then spread it into each spec.
Caveat: Vega renders SVG text using normal browser fonts, so this works as long as STIX Two Text has loaded on the page — which it already does via the site CSS.
OK, please make that change so that the plot fonts match the page fonts.
Done. The Vega-Lite plots now use the site font stack:
STIX Two Text, Georgia, Times New Roman, serif
Applied to:
- axis labels/titles
- legend labels/titles
Show remaining 4 lines
- facet/header labels/titles
- default plot text
Build succeeds.
Please increase all font sizes in the plots by 100%.
Done. Doubled the Vega-Lite plot font sizes for:
- axis labels/titles
- legend labels/titles
- facet/header labels/titles
- text marks
Build succeeds.
Oops. That was a little too much. Please adjust the font sizes in the plots to make the legend labels for the method types the same size as the font in the main body text, and adjust all other plot fonts proportionately.
Adjusted plot font sizes down proportionately:
- Legend labels:
18px - Axis labels / text marks:
18px - Axis titles / legend titles / headers:
20px
Build succeeds.
Please make the lines in the method legend somewhat thicker and twice as long.
Done. Increased the Method legend line glyphs:
- thicker:
symbolStrokeWidth: 3 - longer:
symbolSize: 400
Build succeeds.
Please make the initial state on page load of the fixed-output comparisons plots to show only the Euler trace, with Radau, BDF and LSODA all deselected in the legend. For the native solver output times plots, make the page load state have only Radau selected.
Done.
Initial legend selection now is:
- Fixed-output comparison plots: only Euler selected.
- Native solver output plots: only Radau selected.
Build succeeds.
For the native solver output times plots only, please make the legend have radio button group behavior, i.e. only one trace is selected at a time.
Done.
For native solver output plots only, the Method legend now has radio-button behavior:
- initial selection: Radau
- selecting BDF or LSODA replaces the current selection
- one method remains selected at a time
Build succeeds.