Extract Berton 2023 model

User

<skill name="extract-model" location="[REDACTED_LOCAL_PATH]">
References are relative to [REDACTED_LOCAL_PATH]

Extract Model

Use this skill to turn a scientific paper's mathematical model into a Python reference implementation. Prioritize physical correctness, traceability to the paper, and legibility over performance or architectural polish.

Core Principles

  • Work in two phases every time:
  1. Extract and write an implementation specification.
  2. Pause for user review/clarification before implementing.
  • Do not implement until the user explicitly confirms phase 2.
  • Use pint for units of physical quantities.
  • Preserve the paper's notation in code as closely as Python allows.
  • Greek identifiers are fine and encouraged: ρ, κ, Ω, etc.
  • Subscripts become underscores: ρ_{ie} -> ρ_ie.
  • Avoid unnecessarily long identifiers.
  • Add ASCII aliases only at public API boundaries if genuinely helpful.
  • Keep dependencies lean. Acceptable defaults: pint, numpy, pandas, xarray, scipy, matplotlib.
  • Prefer a literal, equation-by-equation reference implementation over vectorized or optimized code.
  • Use comments and docstrings to map code back to paper equations, tables, sections, and assumptions.
  • If NumPy or vectorization makes units or equations harder to verify, do not use it; add a comment explaining why.
  • Use simple functions and lightweight dataclasses. Avoid protocols and class-heavy frameworks unless the target package already requires them.

Phase 0: Intake and Normalization

  1. Identify the source material:
  • PDF file path
  • LaTeX source
  • Markdown/plain text
  • HTML/DOCX or other source convertible by Pandoc
  • pasted excerpts
  1. Check that Pandoc is available:

``bash pandoc --version ``

If Pandoc is missing, stop and tell the user it is required for this skill.

  1. Normalize the paper/source to Markdown with Pandoc where possible:
  • For .tex, .md, .html, .docx, etc., use Pandoc to produce a Markdown extraction file.
  • For PDFs, try Pandoc as a best effort, but do not assume it will preserve equations or tables well.
  1. If conversion fails or output loses important equations/tables, stop and ask for better source material: LaTeX, publisher HTML, supplementary material, manually extracted equations/tables, or pasted relevant sections.

Phase 1: Extraction Specification

Always write a Markdown spec file before implementation. Use an appropriate path in the target project, usually one of:

  • MODEL_EXTRACTION.md
  • docs/MODEL_EXTRACTION.md
  • docs/<model-name>-extraction.md

If working inside an existing package, inspect project conventions first:

  • pyproject.toml, setup.cfg, setup.py
  • source/package layout
  • test framework and test style
  • examples/docs layout
  • formatting/linting configuration

If no package exists, propose a minimal layout with src/, tests/, and examples/.

The phase-1 spec must include:

  1. Paper/source citation
  • title, authors, year if available
  • source file/path/URL if available
  1. Implementation goal
  • what model or submodel will be implemented
  • intended inputs and outputs
  1. Domain of validity and assumptions
  • assumptions stated by the paper
  • assumptions inferred from implementation needs, clearly labeled
  1. Symbol table
  • paper notation
  • Python identifier
  • units/dimensions
  • meaning
  • where defined in the paper
  1. Constants and parameters
  • values, units, source table/equation
  • whether fixed, configurable, or unknown
  1. Equation inventory
  • equation number or section reference
  • original mathematical expression when possible
  • plain-language meaning
  • proposed Python function/name
  • inputs, outputs, units
  1. Evaluation order / algorithm
  • a step-by-step order matching the paper as closely as possible
  1. Numerical methods
  • solvers, approximations, discretization, interpolation, convergence criteria, etc.
  • note anything unspecified by the paper
  1. Ambiguities / required user decisions
  • missing constants
  • undefined symbols
  • unclear units
  • inconsistent equations
  • boundary/initial conditions
  • choices that would otherwise require guessing
  1. Proposed file layout

- implementation files
- tests
- examples/docs

  1. Test plan

- dimensional/unit tests
- equation smoke tests
- paper regression/reference tests if data exist
- physical sanity tests only where justified

  1. Example plan

- minimal run
- paper scenario, limiting case, or figure/table reproduction if possible

After writing the spec, stop and ask the user to review it, especially the ambiguities and required decisions. Do not proceed until the user confirms phase 2 and resolves blocking ambiguities.

Handling Ambiguity

Be strict about gaps in the paper:

  • Do not silently fill gaps from common knowledge unless clearly labeled as an assumption.
  • If ambiguity blocks implementation, ask the user for clarification in phase 1.
  • If implementation can proceed with placeholders, make them explicit using required parameters, documented TODOs, or NotImplementedError.
  • Prefer exposing uncertain constants, closures, parameterizations, and boundary conditions as inputs.
  • Never invent validation data or expected numerical results.

Phase 2: Implementation

Proceed only after explicit user approval.

Implementation style:

  • Use a flat module structure with functions and simple dataclasses.
  • Prefer pure functions for equations.
  • Provide one obvious high-level evaluation function plus lower-level equation functions.
  • Keep parameters explicit and unit-bearing.
  • Implement equations in the same order/structure as the paper where possible.
  • Add comments such as # Eq. (12) at the corresponding code.
  • Use docstrings for each public function with:
  • paper equation/section reference
  • expected units
  • returned units
  • assumptions/limitations
  • Use lightweight type hints when they improve clarity.
  • Dataclasses are OK.
  • Protocols and elaborate generic abstractions are not.
Units with Pint

Use pint.UnitRegistry and favor simplicity/legibility:

  • Public APIs should accept and return Pint quantities where practical.
  • Validate dimensionality at boundaries.
  • Keep units visible in code so a reader can verify physical correctness.
  • Avoid stripping to magnitudes unless it clearly improves readability and is documented.
  • If using NumPy with Pint makes code harder to verify, avoid NumPy for that part and comment why.
  • Optional xarray integration may be used if the target package already uses it, but do not require pint-xarray by default.
Tests

Include tests as far as possible. Prefer pytest if the target project already uses it or if creating a new package.

Required test categories:

  1. Dimensional tests
  • expected units accepted
  • incompatible units rejected
  1. Equation smoke tests
  • simple hand-checkable values for individual equations/functions
  1. Reference/regression tests
  • use paper tables, figures, examples, or limiting cases when available
  1. Physical sanity tests
  • conservation, monotonicity, positivity, asymptotic behavior, etc., only when justified by the paper

If the paper lacks reference outputs, say so explicitly and avoid pretending smoke/sanity tests validate the whole model.

Examples

Prefer plain Python scripts in examples/ over notebooks by default.

Examples should:

  • reproduce a paper scenario, table, figure, limiting case, or minimal run when possible
  • include comments mapping inputs/outputs to paper sections/tables/figures
  • use matplotlib only when plots help compare to the paper
  • clearly label synthetic examples as non-validation

Final Response Checklist

When phase 1 is complete, report:

  • path to the extraction spec
  • major ambiguities or required user decisions
  • whether implementation is currently blocked
  • exact confirmation needed to proceed

When phase 2 is complete, report:

  • implementation files changed/created
  • tests added and commands run
  • examples added
  • validation status against the paper
  • remaining assumptions or risks

</skill>

Please make a Python implementation of the model in @../../papers/berton-2023-2d-ice-crystal-cirrus-model.pdf - it should go into src/cloud_rom/berton2023.py

Assistant

Wrote the phase-1 extraction spec here:

  • docs/MODEL_EXTRACTION.md

I have not implemented src/cloud_rom/berton2023.py yet, per the extract-model workflow.

Major decisions/ambiguities to review:

  1. PDF text extraction lost Eq. (69) horizontal-wind constants. I inferred some upper-layer values, but need confirmation for lower-layer constants.
  2. Eq. (17) likely means X = (Sc Re)^(1/3), but PDF extraction prints ambiguously as 3 Sc Re.
Show remaining 10 lines
  1. ρ_a / ρ_m usage is somewhat inconsistent in the paper.
  2. Radiative-transfer coefficient α is only given as a range, not a default.

Implementation is partly blocked by the wind constants unless you approve an inferred profile.

To proceed, please reply with something like:

Proceed with phase 2. Use the inferred wind profile and cube-root ventilation formula.

or provide corrections for the ambiguities above.

User

Corrections and questions:

  1. z_U1 = 5 km, U_a1 = 5 m/s.
  2. X = (Sc)^(1/3) (Re)^(1/2). Extraction of text dropped both root signs.
  3. Question: is ρ_m used anywhere else? I can't see it. If not, don't worry about it. I think there might be a misprint in the symbol table (Table 1), because they mention ρ as the density of moist air, not ρ_m. But as far as I can see, neither ρ nor ρ_m is used anywhere in the paper, apart from the definition in Eq. (7).
  4. Question: I don't think α is an input parameter: it's something that's inferred from η and η_a using Eq. (27). Can you see anywhere that α is used?

Non-blocking:

  • Include Coriolis terms along with Ω_0 parameter.
  • Outputs should be Pint quantities.
  • Add pytest as a development dependency.

If you can answer the two questions here, I think we can proceed.

Assistant

Answers:

  1. ρ_m / moist-air density: I agree. In the extracted paper text, ρ_m appears only around Eq. (7). The governing equations use ρ_a in Eq. (1), Eq. (4), Eq. (18), and the Euler update Eq. (42). I’ll implement Eq. (7) as a reference helper, but won’t use ρ_m in the simulator.
  1. α: I also agree. I only see α in Eq. (27) and the surrounding explanatory prose. It is not used as an input to the numerical cases; the model uses η directly. I’ll make η the input/profile and, at most, include alpha_from_eta(...) / eta_from_alpha(...) diagnostic helpers.

I updated docs/MODEL_EXTRACTION.md with your corrections:

  • z_U1 = 5 km, U_a1 = 5 m/s
  • X = Sc^(1/3) Re^(1/2)
  • Coriolis included via Ω0, θ
Show remaining 4 lines
  • Pint outputs
  • add pytest dev dependency

Please explicitly confirm phase 2 with: “Proceed with phase 2.”

User

Please proceed with phase 2.

Assistant

Implemented phase 2.

Created/changed:

  • src/cloud_rom/berton2023.py — equation-by-equation Pint implementation
  • src/cloud_rom/__init__.py
  • tests/test_berton2023.py
  • examples/berton2023_case0.py
  • pyproject.toml — added pytest dev dependency
  • uv.lock — updated by uv run
Show remaining 9 lines

Validation run:

  • PYTHONPATH=src uv run pytest -q → 6 passed
  • PYTHONPATH=src uv run python examples/berton2023_case0.py → successful short Case 0 run

Notes:

  • ρ_m is implemented as moist_air_density(...) for Eq. (7), but not used in the simulator.
  • η is used directly; α is only available via diagnostic helpers.
  • Coriolis is included and controlled by SimulationConfig(include_coriolis=..., θ=...).
  • Outputs from simulate(...) are Pint quantities stored directly in a pandas DataFrame.
User

Can you check the compatibility of the version of Pint you installed with Python 3.12? There are a lot of Pyright errors about PlainQuantity versus Quantity. (You can run Pyright with "uv run pyright".) Also, there is some very weird stuff on lines 269 and 281 using __import__("math"). Where on earth did you get that idea from?!

Assistant

You’re right on both counts.

  • Pint compatibility: installed Pint is 0.25.3; metadata says:
  • Requires-Python: >=3.11
  • classifiers include Python 3.12
  • so runtime compatibility with Python 3.12 is fine.
  • Pyright issue: Pint 0.25.x exposes registry-created quantities as PlainQuantity[...], while pint.Quantity annotations trigger Pyright incompatibilities. I changed the module’s Quantity annotation alias to Any while keeping runtime isinstance(..., pint.Quantity) checks. Not ideal, but it avoids false type noise for this reference/unit-heavy code.
  • __import__("math").log(...): no good reason. That was bad/ugly generated code. I replaced it with a normal from math import log.
Show remaining 10 lines

Validation now passes:

PYTHONPATH=src uv run pyright
# 0 errors, 0 warnings, 0 informations

PYTHONPATH=src uv run pytest -q
# 6 passed
User

Some further small changes:

  • In local_diagnostics, build the result using dict(...) and do not create additional local variables unless they are needed in the calculation of other quantities.
  • Make the functions that take an Atmosphere and a vertical level (horizontal_wind, updraft, temperature, relative_humidity_profile, eta, atmospheric_eta) methods of Atmosphere. The breakpoints for the piecewise linear profiles of temperature, relative humidity and atmospheric_eta should be class attributes of the Atmosphere class, just like the breakpoints for the horizontal wind profile.
Assistant

Done.

Changes made:

  • Moved profile functions onto Atmosphere:
  • horizontal_wind
  • updraft
  • temperature
  • relative_humidity_profile
  • atmospheric_eta
  • eta
Show remaining 12 lines
  • Added temperature, humidity, and η_a profile breakpoints/values as Atmosphere attributes.
  • Kept module-level compatibility wrappers for existing tests/API.
  • Refactored local_diagnostics to return dict(...) and removed locals that were only used for output fields.

Validation:

PYTHONPATH=src uv run pyright
# 0 errors, 0 warnings

PYTHONPATH=src uv run pytest -q
# 6 passed
User

Please remove those module-level compatibility wrappers and update the tests. There is no requirement for any kind of backwards compatibility here. This is completely new code with no users.

Assistant

Done.

Removed module-level wrappers:

  • horizontal_wind
  • updraft
  • temperature
  • relative_humidity_profile
  • atmospheric_eta
  • eta
Show remaining 10 lines

Updated tests to call Atmosphere methods directly.

Validation:

PYTHONPATH=src uv run pyright
# 0 errors, 0 warnings

PYTHONPATH=src uv run pytest -q
# 6 passed
User

Please make the local diagnostics into a class.

Assistant

Done.

Changes:

  • Replaced local_diagnostics(...) with LocalDiagnostics dataclass.
  • Added LocalDiagnostics.from_state(...).
  • Added LocalDiagnostics.to_dict() for DataFrame output.
  • Updated accelerations, euler_step, simulate, _row, and tests to use the class.

Validation:

Show remaining 6 lines

PYTHONPATH=src uv run pyright

0 errors, 0 warnings

PYTHONPATH=src uv run pytest -q

6 passed

User

Why is it not necessary to set PYTHONPATH=src? That's not normal.

Assistant

You’re right — needing PYTHONPATH=src was not normal for a packaged project. It was necessary because pyproject.toml had no build backend/package config, so uv run pytest could not install/import cloud_rom.

I fixed this by adding Hatchling config:

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
Show remaining 12 lines

packages = ["src/cloud_rom"]


Now these work without `PYTHONPATH`:

uv run pytest -q

6 passed

uv run pyright

0 errors

User

Please add a notebook (notebooks/atmospheric-profiles.ipynb) to reproduce Figures 1-5 from the paper.

Assistant

Added:

  • notebooks/atmospheric-profiles.ipynb

It includes code to reproduce:

  • Figure 1: horizontal wind
  • Figure 2: updraft profiles
  • Figure 3: temperature and pressure
  • Figure 4: relative humidity and saturation ratios
  • Figure 5: atmospheric infrared ratio
Show remaining 2 lines

I also validated that all notebook code cells execute successfully with uv run python using a non-interactive matplotlib backend.