0

I want to be able to take an Indexed object, substitute values for its indices but still remember its original indices.

from sympy.tensor import IndexedBase, Idx
C = IndexedBase("C")
i,j = Idx("i"), Idx("j") 
expr = C[i,j]
expr = expr.subs({i:1, j:2})

Is it possible to get the original indices (i,j) from expr? Since expressions are immutable any modifications I do on the original expression won't show up in the new expression.

I suppose the general question here is how do I attach additional information to Sympy symbols.

mohamedmoussa
  • 547
  • 4
  • 13

2 Answers2

0

You can attach general information to symbols like symbols('x', integer=True) but you can't assign values. You can, however, create new variables with the substituted symbols. This leaves your original expression unchanged:

newexpr = expr.subs({i:1, j:2})
smichr
  • 16,948
  • 2
  • 27
  • 34
  • Thanks for your reply. However I'm not sure if this answers the question. Note that in my code I want to get `(i,j)` from the _final_ `expr`, which is equal to `C[1,1]` now. I want the Indexed object to be able to remember what its original indices are. – mohamedmoussa Feb 20 '15 at 16:02
  • What do you need that information for? How would you use that information? – smichr Feb 20 '15 at 19:59
  • From one expression I generate a whole bunch based on the index ranges. e.g. `A[i,j]` could become `[A[1,1], A[1,2], A[1,3] ... ]`. Then I apply transformations on index pairs, typically mapping two adjacent pairs down to one. For example, transform `(i,j)` according to a rule that says where values of `1,1` goes down to one index `1`. So `A[1,1]` becomes `A[1]`. Just one example. – mohamedmoussa Feb 20 '15 at 20:45
  • It's not clear (to me) why you need to know what the original indices are, however. How do you use i and j to make a decision? – smichr Feb 20 '15 at 22:40
  • If I have an expression `expr = A[1,2,3]` that came from an original expression `A[i,j,k]`. I want to do something like `apply_some_rule(expr, (j,k))` and the output would be `A[1,5]`, where the pair `2,3` was mapped to `5`, based on the fact that `j,k` were the 2nd and 3rd indices. It could be a large expression with many terms, where index positions vary for each term. – mohamedmoussa Feb 20 '15 at 23:11
0

SymPy doesn't "remember" where things come from after doing a subs. You should structure your code so that the original expression is retained.

asmeurer
  • 86,894
  • 26
  • 169
  • 240