Skip to content

FIX: Fix lambdifying models that evaluate to have complex numbers - #599

Merged
bocklund merged 4 commits into
pycalphad:developfrom
bocklund:fix-float-exponents-negative-bases
Apr 12, 2025
Merged

bocklund merged 4 commits into
pycalphad:developfrom
bocklund:fix-float-exponents-negative-bases

Conversation

@bocklund

@bocklund bocklund commented Apr 8, 2025 •

Copy link
Copy Markdown
Collaborator

In PyCalphad we eventually represent all our exponents as floating points, even if they are actually integer values. This becomes troublesome because SymEngine evaluates small, negligible imaginary parts, as in the following example:

from sympy import Symbol
x = Symbol("x")
print((x**(2.0)).subs({x: -1})) 
# prints: `1`
from symengine import Symbol
x = Symbol("x")
print((x**(2)).subs({x: -1})) 
# prints: `1`
print((x**(2.0)).subs({x: -1})) 
# prints: `1.0 - 2.44929359829471e-16*I` complex just by using floating point exponent

In this case, the imaginary part is not useful and causes an issue when we call lambdify in (build_functions) with the default argument that real=True. We probably haven't run into this before because our bases are typically symbolic (e.g. T in power functions) and these are typically not evaluated to a complex number until the function is actually evaluated inside lambdify (where the imaginary part gets thrown away because we call lambdify(..., real=True) implicitly). Consequently, doing this replacement outside of lambdify can't be a source of a regression because lambdify has been throwing away any complex parts anyway.

We end up doing this workaround to find complex numbers by atoms and replace the imaginary unit with zero, which is working around SymEngine not having a re (real) function and calling subs or xreplace with {I: 0.0} directly on the Model expression doesn't replace arbitrarily nested imaginary numbers.

@bocklund
bocklund requested a review from richardotis April 8, 2025 21:49
Comment thread pycalphad/codegen/sympydiff_utils.py Resolved
@bocklund
bocklund merged commit 6622030 into pycalphad:develop Apr 12, 2025
@bocklund
bocklund deleted the fix-float-exponents-negative-bases branch April 12, 2025 04:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants