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:
- Scans
../config/for*.configYAML files - For each config, instantiates
Partial→AutoDiffType→ callsmake_auto_diff_type() - Writes each generated module to
../private/<name>_module.f90 - Writes
../make/source_list.txt(build manifest) - Writes
../public/auto_diff.f90(public aggregation module thatuses 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 variablearray: whether the last independent variable is an array (vector-valued)net_order: sum of orderscompletion_partials(): returns all one-lower-order partials needed for chain rule closureincrement_order(variable_index): returns the partial with one more derivative w.r.t. that variable__str__(): produces Fortran field name liked1val1,d2val1_d1val2,d1Array
AutoDiffType(name, array, array_length, partials)
Models the complete auto-diff derived type. On construction:
- Takes the highest-order partials requested
- Auto-completes: iteratively adds all one-lower-order partials until the set closes
- Sorts partials by net order and lexicographic order
- Pre-computes
unary_partialsandbinary_partialsfor the generic operator chain rules
Key methods generate Fortran:
type()— thetype :: ...block with all derivative fieldsassignment_routine_from_*()— assignment from self,real(dp),integercomparison_function_with_*()—.eq.,.ne.,.gt.,.lt.,.le.,.ge.against self, real, intgeneric_unary_operator_function()—make_unop(user supplies derivatives of their function)generic_binary_operator_function()—make_binopspecific_unary_operator_function()— callsunary_specific_chain_rulefor each unary math functionspecific_binary_operator_function_*()— binary ops against self, real, int (mixed-type pairs reduce to unary chain rule on one argument)derivative_function()—differentiate_Nthat shifts derivative indices
Chain Rule Approach (Power Series Method)
- Independent variables (
val1,val2, …) are SymPy symbols - The function argument
xis 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! * ...) - The operator
z = f(x)(orz = f(x,y)for binary) is applied symbolically - For each target partial, SymPy computes
diff(z, val_i, order_i)for all independent vars, then evaluates atval_i = 0 - 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 formake_unop/make_binopwhere the user supplies derivative values at runtime.
Post-derivation optimization:
- SymPy
simplifywithmeasure=weighted_count_ops— minimizes estimated runtime cost, not expression size cse()(common sub-expression elimination) — extracts shared sub-expressions into temporary variables- 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 (defaultFalse)fixed_length: if array, use fixedarray_length(defaultFalse— 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:
substitute_pow: Replacesx**N(integer N ≤ 8) withpowN(x), replacesx**(i/2)withpowi(sqrt(x)), replacesx**(-N)withpowm1(x**N). Iterates until fixed point because replacements can interfere.substitute_rational: Replacesi/jwithfloat_dpsymbols to prevent Fortran integer division.substitute_dp: Appends_dpsuffix to allFloatconstants for bit-exact reproducibility.Pow→PPow: Replaces SymPyPowwithPPowfunction to prevent simplification, thenpy_to_fortconvertsPPow→powin 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 trigdiv = 30: division andpowm1(which is1/x)basic = 1:add,mul,sub,neg,abs,heaviside,sgnpowN:basic * log2(N+1)(sincepowNbuilds 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.f90files and../public/auto_diff.f90are fully generated. Changes must be made in this Python toolchain and re-generated. fixed_length: Truefor all array types: A comment inparser.pynotes that gfortran (as of Sep 2021) does not support variable-length arrays in parameterized derived types, so all array configs setfixed_length: true._dpsuffix enforced:substitute_dpensures all floating-point literals get_dpfor bit-exact reproducibility.powNenforcement:substitute_powautomatically converts all integer powers ≤ 8 topowNcalls. 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;
AutoDiffTypeautomatically 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.pyweights 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/→ Generatedauto_diff.f90aggregation module (sibling — read-only; do NOT hand-edit)../make/→ Receives generatedsource_list.txt(sibling — read-only)../test/→ Test suite for the Fortran auto-diff modules (sibling — read-only)../../const/→const_defprovidingdp,ln10,pi(sibling — read-only)../../math/→math_libprovidingpow2..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_order1has 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.pyassumes it runs from thepython/directory. Running from elsewhere will fail. - No incremental generation: Running
parser.pyregenerates ALL types. There is no mechanism to regenerate just one type.
See Also
../(parent) — theauto_diffmodule overview, including the complete type table../../math/— provides thepow2..pow8fast power routines that the generator assumes../../const/— providesdpkind parameter andln10constant used in generated code