auto_diff/python/

Intent

The MESA auto-diff code generation toolchain. A Python code generator that produces complete Fortran module files implementing forward-mode automatic differentiation types. It uses SymPy to symbolically derive chain rule expressions for all overloaded operators and mathematical functions, then emits optimized Fortran code. This is a development-time tool — the generated Fortran is committed to the repo and compiled as part of MESA; the generator is not invoked during the normal build.

API Surface

Entry Point: parser.py

The orchestrator. Run this to regenerate all auto-diff Fortran modules:

  1. Scans ../config/ for *.config YAML files
  2. For each config, instantiates Partial → AutoDiffType → calls make_auto_diff_type()
  3. Writes each generated module to ../private/<name>_module.f90
  4. Writes ../make/source_list.txt (build manifest)
  5. Writes ../public/auto_diff.f90 (public aggregation module that uses all private modules)

Core Modules

File Key Export Role
parser.py — (script) Orchestrator; reads configs, drives generation, writes output
partial.py Partial Models a single partial derivative (e.g., d2val1_d1val3); handles naming, ordering, completion
auto_diff_type.py AutoDiffType Models the full auto-diff type with all partials; generates all Fortran routines (assignment, comparison, operators, differentiation) via chain_rule
chain_rule.py unary_generic_chain_rule, unary_specific_chain_rule, binary_generic_chain_rule, binary_specific_chain_rule SymPy-based chain rule derivation via power series method + CSE optimization
functions.py unary_operators, binary_operators, comparison_operators, intrinsics SymPy lambda definitions for all supported operators
routine.py FortranRoutine, FortranFunction Simple AST for Fortran subroutine/function code generation
utils.py fortran_substitutions, substitute_pow, substitute_dp, py_to_fort Fortran-specific post-processing of SymPy expressions
make_auto_diff_type.py make_auto_diff_type Assembles the full Fortran module (imports, type def, operator interfaces, function bodies)
measure.py weighted_count_ops Operation cost model used by SymPy simplify to minimize runtime cost (not expression size)

Generation Pipeline

Config (YAML)
  │
  ▼
Partial objects ───► AutoDiffType (auto-completes to all lower-order partials)
  │                        │
  │          ┌─────────────┼──────────────────┐
  │          │             │                  │
  │     chain_rule.py  functions.py     routine.py
  │     (SymPy power    (SymPy lambda    (Fortran AST:
  │      series + CSE)   definitions)     subroutines,
  │          │             │               functions)
  │          └─────────────┼──────────────────┘
  │                        │
  ▼                        ▼
  make_auto_diff_type.py (assembles full module)
  │
  ▼
  Fortran output → ../private/<name>_module.f90

Key Classes

Partial(orders, array)

Represents a partial derivative like ∂³/(∂val1² ∂val3). Stores:

  • orders: tuple of derivative orders per independent variable
  • array: whether the last independent variable is an array (vector-valued)
  • net_order: sum of orders
  • completion_partials(): returns all one-lower-order partials needed for chain rule closure
  • increment_order(variable_index): returns the partial with one more derivative w.r.t. that variable
  • __str__(): produces Fortran field name like d1val1, d2val1_d1val2, d1Array

AutoDiffType(name, array, array_length, partials)

Models the complete auto-diff derived type. On construction:

  1. Takes the highest-order partials requested
  2. Auto-completes: iteratively adds all one-lower-order partials until the set closes
  3. Sorts partials by net order and lexicographic order
  4. Pre-computes unary_partials and binary_partials for the generic operator chain rules

Key methods generate Fortran:

  • type() — the type :: ... block with all derivative fields
  • assignment_routine_from_*() — assignment from self, real(dp), integer
  • comparison_function_with_*() — .eq., .ne., .gt., .lt., .le., .ge. against self, real, int
  • generic_unary_operator_function() — make_unop (user supplies derivatives of their function)
  • generic_binary_operator_function() — make_binop
  • specific_unary_operator_function() — calls unary_specific_chain_rule for each unary math function
  • specific_binary_operator_function_*() — binary ops against self, real, int (mixed-type pairs reduce to unary chain rule on one argument)
  • derivative_function() — differentiate_N that shifts derivative indices

Chain Rule Approach (Power Series Method)

  1. Independent variables (val1, val2, …) are SymPy symbols
  2. The function argument x is constructed as a Taylor/power series in terms of its partial derivatives w.r.t. the independent variables:
    x = sum over partials p: x%[p_name] * (val1^o1 * val2^o2 * ...) / (o1! * o2! * ...)
    
  3. The operator z = f(x) (or z = f(x,y) for binary) is applied symbolically
  4. For each target partial, SymPy computes diff(z, val_i, order_i) for all independent vars, then evaluates at val_i = 0
  5. This extracts the chain rule expression purely in terms of the known partial derivatives stored in the auto-diff type

Generic vs Specific:

  • Specific (*_specific_chain_rule): operator is a concrete SymPy lambda (e.g., exp, sin, x*y). Used for built-in math.
  • Generic (*_generic_chain_rule): operator is a power series with symbolic derivative coefficients (z_*). Used for make_unop/make_binop where the user supplies derivative values at runtime.

Post-derivation optimization:

  1. SymPy simplify with measure=weighted_count_ops — minimizes estimated runtime cost, not expression size
  2. cse() (common sub-expression elimination) — extracts shared sub-expressions into temporary variables
  3. Array-type propagation — intermediates that involve : (colon for array sections) are marked as array-typed and declared with proper Fortran array syntax

Config File Format (in ../config/)

YAML with fields:

  • name: Fortran type name (e.g., auto_diff_real_2var_order2)
  • orders: list of highest-order partials, each as a list of per-variable orders (e.g., [[2,0],[1,1],[0,2]])
  • array: whether the last variable is an array (default False)
  • fixed_length: if array, use fixed array_length (default False — variable-length parameterized derived type)
  • array_length: integer size for fixed-length arrays

Note: auto_diff_real_15var_order1 has NO corresponding config file and is generated separately (or hand-written). It is not produced by this toolchain.

Fortran Post-Processing (utils.py)

fortran_substitutions() applies in order:

  1. substitute_pow: Replaces x**N (integer N ≤ 8) with powN(x), replaces x**(i/2) with powi(sqrt(x)), replaces x**(-N) with powm1(x**N). Iterates until fixed point because replacements can interfere.
  2. substitute_rational: Replaces i/j with float_dp symbols to prevent Fortran integer division.
  3. substitute_dp: Appends _dp suffix to all Float constants for bit-exact reproducibility.
  4. Pow→PPow: Replaces SymPy Pow with PPow function to prevent simplification, then py_to_fort converts PPow → pow in string output.

py_to_fort() performs final string-level substitutions: PPow→pow, ssqrt→sqrt, log(10.0_dp)→ln10, colon→:.

Operation Cost Model (measure.py)

Defines relative costs for SymPy expression simplification:

  • special = 1000: sin, cos, exp, log, pow, sqrt, hyperbolic/arc trig
  • div = 30: division and powm1 (which is 1/x)
  • basic = 1: add, mul, sub, neg, abs, heaviside, sgn
  • powN: basic * log2(N+1) (since powN builds up via repeated squaring)
  • DiracDelta, Derivative: 0 (eliminated in post-processing)

Constraints

  • Python 3 with PyYAML and SymPy: Required dependencies for running the generator.
  • Must be run from the python/ directory: Config paths are relative (../config, ../private, ../public).
  • Do NOT hand-edit generated Fortran: The ../private/*_module.f90 files and ../public/auto_diff.f90 are fully generated. Changes must be made in this Python toolchain and re-generated.
  • fixed_length: True for all array types: A comment in parser.py notes that gfortran (as of Sep 2021) does not support variable-length arrays in parameterized derived types, so all array configs set fixed_length: true.
  • _dp suffix enforced: substitute_dp ensures all floating-point literals get _dp for bit-exact reproducibility.
  • powN enforcement: substitute_pow automatically converts all integer powers ≤ 8 to powN calls. This is the mechanism that enforces the MESA-wide convention.

Design Decisions

  • Power series method: Instead of hard-coding chain rule formulas (Faa di Bruno for unary, etc.), the generator lets SymPy symbolically differentiate power series. This is more general and less error-prone, though computationally expensive at generation time.
  • Auto-completion of partials: The user only specifies highest-order partials in the config; AutoDiffType automatically computes which lower-order partials are needed for chain rule closure. This prevents inconsistent specifications.
  • Cost-weighted simplification: Expressions are simplified to minimize estimated runtime cost, not syntactic simplicity. The measure.py weights guide SymPy toward fewer special-function calls even if the expression gets larger.
  • CSE in chain rule: After deriving all partial derivatives for an operator, common sub-expression elimination is applied across them collectively. This is crucial for performance — higher-order types have many partials that share sub-expressions.
  • Mixed-type binary ops reduced to unary: (auto_diff, real) and (auto_diff, int) binary operations are implemented by treating the scalar as a constant and invoking the unary chain rule. This avoids duplicating the binary chain rule logic for mixed types.
  • Generic operators (make_unop/make_binop): Allow users to supply their own function derivatives at runtime. The generator produces the chain rule in terms of these symbolic derivative coefficients, which are passed as Fortran arguments.
  • Golden-source approach: Generated Fortran is committed to version control. This means most developers never need to run the Python generator — only when adding new auto-diff types or operators.

Routing Table

  • ../config/ → YAML config files specifying each auto-diff type's parameters (sibling — read-only)
  • ../private/ → Generated Fortran output (sibling — read-only; do NOT hand-edit)
  • ../public/ → Generated auto_diff.f90 aggregation module (sibling — read-only; do NOT hand-edit)
  • ../make/ → Receives generated source_list.txt (sibling — read-only)
  • ../test/ → Test suite for the Fortran auto-diff modules (sibling — read-only)
  • ../../const/ → const_def providing dp, ln10, pi (sibling — read-only)
  • ../../math/ → math_lib providing pow2..pow8, safe_log (sibling — read-only)

Test Strategy

There is no test suite for the Python generator itself. Validation happens indirectly:

  • The generated Fortran is compiled and tested via ../test/src/test_auto_diff.f90
  • Golden output comparison in ../test/test_output
  • Correctness of the chain rule and optimizations is verified by inspection of the generated Fortran and by the physics results depending on it

When modifying the generator, regenerate all modules and run the Fortran test suite to verify correctness.

Known Issues

  • auto_diff_real_15var_order1 has no config: It is generated (or hand-written) by a different mechanism and is not reproducible from this toolchain.
  • gfortran PDT limitation: Variable-length arrays in parameterized derived types are commented out because gfortran does not support them (as of Sep 2021). All array types use fixed array_length.
  • Config paths are relative: parser.py assumes it runs from the python/ directory. Running from elsewhere will fail.
  • No incremental generation: Running parser.py regenerates ALL types. There is no mechanism to regenerate just one type.

See Also

  • ../ (parent) — the auto_diff module overview, including the complete type table
  • ../../math/ — provides the pow2..pow8 fast power routines that the generator assumes
  • ../../const/ — provides dp kind parameter and ln10 constant used in generated code