`PsResid` keeps its guess cache outside OpenMDAO's vectors, so `load_case` doesn't reproduce off-design solves

Abierto
#125 0 comentarios 0 reacciones 0 asignados Ver en GitHub

@Jhawk414 ya está trabajando en esto.

Desde el 26/11/2026.

  • #126 de @Jhawk414 — abierto

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
45/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

Read pycycle/thermo/static_ps_resid.py, especially PsResid.guess_nonlinear, and trace how Thermo and cycle elements use PsResid. Run the reproduction in the issue with example_cycles/mixedflow_turbofan.py to confirm the cache causes history-dependent results. Decide which proposed state-handling behavior is appropriate, then verify that restoring a recorded case reproduces the same solve.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Summary

PsResid.guess_nonlinear (pycycle/thermo/static_ps_resid.py) decides whether to overwrite the Ps output by comparing the new guess with self._ps_guess_cache, a plain Python attribute. In area mode, which every element's out_stat uses at an off-design point, it re-seeds Ps only when the guess has moved by more than 1e-10 since the last call.

The cache isn't in the output, input or residual vectors, so restoring a model's state with prob.load_case(case), or by copying the vectors back, doesn't restore it. The next solve's starting point then depends on whatever ran in between, and results that should be identical differ at the solver-tolerance level. Warm-start and rollback patterns in off-design sweeps are affected.

Reproduction

The script below uses example_cycles/mixedflow_turbofan.py unchanged; run it from the repo root on master. It solves the off-design point at its own condition (A: 35 kft, M0.8, T4 3100 °R), records the case, and saves every PsResid cache value. It then compares three re-solves of A:

  1. Baseline: load_case(A), then solve A, with nothing run in between.
  2. Case only: solve a different condition (B: 30 kft, M0.7, T4 2900 °R), then load_case(A) and solve A.
  3. Case and cache: solve B, then load_case(A), put the saved cache values back, and solve A.

Runs 2 and 3 start from the same recorded case, so both should match the baseline bit for bit.

"""Run from the pyCycle repo root. Uses example_cycles/mixedflow_turbofan.py unchanged.

Solve the OD point at condition A and record the case. Then solve at condition B, restore A
with prob.load_case() and solve A again. Run 2 restores only the recorded case; run 3 also
restores PsResid._ps_guess_cache. Each run is compared with the baseline (run 1).
"""
import sys

import numpy as np
import openmdao.api as om
from pycycle.thermo.static_ps_resid import PsResid

sys.path.insert(0, 'example_cycles')
from mixedflow_turbofan import MPMixedFlowTurbofan

A = dict(alt=35000., MN=0.8, T4=3100.)  # the example's OD condition
B = dict(alt=30000., MN=0.7, T4=2900.)

prob = om.Problem(model=MPMixedFlowTurbofan())
prob.setup()
prob.set_solver_print(level=-1)
# design inputs and initial guesses copied from mixedflow_turbofan.py's __main__
for name, val in [('fan.PR', 3.3), ('fan.eff', 0.8948), ('lpc.PR', 1.935), ('lpc.eff', 0.9243),
                  ('hpc.PR', 4.9), ('hpc.eff', 0.8707), ('hpt.eff', 0.8888), ('lpt.eff', 0.8996),
                  ('fc.MN', 0.8), ('balance.FAR_core', 0.025), ('balance.FAR_ab', 0.025),
                  ('balance.BPR', 1.0), ('balance.W', 100.), ('balance.lpt_PR', 3.5),
                  ('balance.hpt_PR', 2.5), ('fc.balance.Pt', 5.2), ('fc.balance.Tt', 440.0),
                  ('mixer.balance.P_tot', 15)]:
    prob['DESIGN.' + name] = val
prob.set_val('DESIGN.fc.alt', 35000., units='ft')
prob.set_val('DESIGN.balance.rhs:W', 5500.0, units='lbf')
prob.set_val('DESIGN.balance.rhs:FAR_core', 3200, units='degR')
for name, val in [('balance.FAR_core', 0.025), ('balance.FAR_ab', 0.025), ('balance.BPR', 2.5),
                  ('balance.W', 50.), ('balance.HP_Nmech', 14000), ('balance.LP_Nmech', 4000),
                  ('fc.balance.Pt', 5.2), ('fc.balance.Tt', 440.0), ('mixer.balance.P_tot', 15),
                  ('hpt.PR', 2.0), ('lpt.PR', 4.0), ('fan.map.RlineMap', 2.0),
                  ('lpc.map.RlineMap', 2.0), ('hpc.map.RlineMap', 2.0)]:
    prob['OD.' + name] = val


def solve(c):
    prob.set_val('OD.fc.alt', c['alt'], units='ft')
    prob.set_val('OD.fc.MN', c['MN'])
    prob.set_val('OD.balance.rhs:FAR_core', c['T4'], units='degR')
    prob.run_model()
    return prob.model._outputs.asarray().copy()


ps_resids = list(prob.model.system_iter(recurse=True, typ=PsResid))
prob.add_recorder(om.SqliteRecorder('cases.sql'))
prob.recording_options['includes'] = ['*']
solve(A)
prob.record('A')
case = om.CaseReader(prob.get_outputs_dir() / 'cases.sql').get_case('A')
caches = [np.copy(p._ps_guess_cache) for p in ps_resids]


def restore(with_cache):
    prob.load_case(case)
    if with_cache:
        for p, c in zip(ps_resids, caches):
            p._ps_guess_cache = np.copy(c)


def report(label, R):
    rel = np.abs(R - base) / np.maximum(np.abs(base), 1e-30)
    print(f'{label}\n    identical to baseline: {np.array_equal(R, base)}, outputs differing: {np.sum(R != base)}, '
          f'max rel diff: {rel.max():.1e} ({rel[np.abs(base) > 1e-3].max():.1e} for |value| > 1e-3), '
          f'OD Fn: {prob.get_val("OD.perf.Fn", units="lbf")[0]:.10f} lbf')


# Baseline: restore A and re-solve A, with nothing run in between.
restore(with_cache=True)
base = solve(A)
report('1. Baseline: load_case(A), solve A', base)

# Solve B, then restore A from the recorded case only.
solve(B)
restore(with_cache=False)
report('2. Solve B, then load_case(A), solve A', solve(A))

# Solve B, then restore A from the recorded case and the saved cache values.
solve(B)
restore(with_cache=True)
report('3. Solve B, then load_case(A) and restore _ps_guess_cache, solve A', solve(A))

Output:

1. Baseline: load_case(A), solve A
    identical to baseline: True, outputs differing: 0, max rel diff: 0.0e+00 (0.0e+00 for |value| > 1e-3), OD Fn: 5124.4849204814 lbf
2. Solve B, then load_case(A), solve A
    identical to baseline: False, outputs differing: 1213, max rel diff: 3.7e-04 (4.2e-09 for |value| > 1e-3), OD Fn: 5124.4849204814 lbf
3. Solve B, then load_case(A) and restore _ps_guess_cache, solve A
    identical to baseline: True, outputs differing: 0, max rel diff: 0.0e+00 (0.0e+00 for |value| > 1e-3), OD Fn: 5124.4849204814 lbf
  • Run 2 (case only) differs from the baseline in 1213 outputs across every element's out_stat. The largest difference on values above 1e-3 is 4.2e-9 relative; the 3.7e-4 maximum is on trace CEA species.
  • Run 3 (case and cache) is bitwise identical to the baseline, so the cache accounts for all of the difference.
  • The same sequence on simple_turbojet.py changes 51 outputs, all in OD1's inlet exit statics.

In this example perf is unaffected. In a larger downstream model (two-spool mixed-flow afterburning turbofan, tabular thermo, 18 PsResid per OD point), the same mechanism changed sweep results by up to 7e-5 relative and decided whether one marginal point converged. Saving and restoring the 18 cache values with the vectors made those results byte-identical.

Expected

The state OpenMDAO saves and restores (record/load_case, or the vectors) fully determines the next solve. If it can't, the docs should say PsResid keeps solver state outside them.

Possible fixes

These are options to discuss before picking one:

  • (a) Option to turn the cache off, e.g. PsResid(reseed='always'), passed through Thermo and the elements. The default is unchanged, so existing results don't move unless a user opts in.
  • (b) A stateless rule: always apply the guess in area mode, or apply it only when the current Ps is invalid or non-physical. This removes the hidden state, but converged values shift at solver tolerance, and the turbojet example's OD1 inlet exit statics change. I tried "always apply in area mode" (cache check removed): the 13 golden-value tests in example_cycles/tests/benchmark_*.py and the pycycle unit tests still pass, and the reproduction above becomes history-independent.
  • (c) A public reset or get/set-state hook (e.g. reset_guess_cache() or a helper on MPCycle), plus a docs note. This changes behaviour the least, but every user who warm-starts has to know to call it.
  • (d) Docs only.

MN mode only seeds Ps on the first call, while the cache is still -1, so it doesn't cause this after the first solve.

Environment

pyCycle master @ ee7e161 (4.4.1-dev), OpenMDAO 3.39.0, NumPy 2.0.2, SciPy 1.13.1, Python 3.9.6, macOS.

The cache dates to the initial commit. I couldn't find an existing issue about it.

Lenguaje dominante
Python
Estrellas
212
Forks
101
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

  • Sin Dockerfile ni archivo de Docker Compose
  • Tiene una plantilla de pull request
  • Sin guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de OpenMDAO/pyCycle

Todos los issues de OpenMDAO/pyCycle

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.