Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursively get property downwards for Add and Mul #26538

Open
icarosadero opened this issue Apr 24, 2024 · 1 comment
Open

Recursively get property downwards for Add and Mul #26538

icarosadero opened this issue Apr 24, 2024 · 1 comment

Comments

@icarosadero
Copy link

Some objects, like the ones from the physics.quantum submodule, contain properties like that yield a derived expression. However, this same property can't be accessed for a linear combination of these same objects.

For example,

Suppose I create two Ket objects:

from sympy.physics.quantum.state import Ket
x = Ket('1')
y = Ket('2')

Then, I could call the property dual separately on kets $|1\rangle$ and $|2\rangle$ without a problem to generate bras from them:

In: x.dual
Out: <1|

In: y.dual
Out: <2|

However, for any linear combination of $|1\rangle$ and $|2\rangle$, that no longer works:

In: (2*x + 3*y).dual
AttributeError                            Traceback (most recent call last)
Cell In[9], line 1
----> 1 (2*x + 3*y).dual

AttributeError: 'Add' object has no attribute 'dual'

This forces the user to implement a recursive function to call dual on the expression on every new project. This also applies to expr from physics.quantum.state.Wavefunction, for which I created a PR #26520 to temporarily solve it.

The solution that I suggest is to "send" a property or method call down the expression tree whenever it is invalid for Add or Mul.

@sylee957
Copy link
Member

sylee957 commented May 2, 2024

Not only Add don't have dual, but also most of the SymPy methods like Integer, Rational. I don't think that the discussion ends with Add and Mul, and the reason that .dual is not defined for most of the SymPy objects is that we need to discuss Add, Mul, Pow and in fact pretty much everything of Expr about how to handle .dual.

There would be easy or more obvious answers, such as defining def dual(self): self, however, I'm afraid that it doesn't work by simply working with Add, Mul exclusively and hiding the complexity about the discussion,

"send" a property or method call down the expression tree whenever it is invalid for Add or Mul.

It may be possible to override __getattr__ magic method, however, in general, I'd warn that such is very nonstandard programming practice, and we may encounter much more nonstandard compatibility or performance issues that not many people in Python community faces if we pick such direction.

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

No branches or pull requests

2 participants