On Wed, Feb 15, 2012 at 7:02 PM, Akin <[email protected]> wrote:
> Thank you. Is there a way to create a non-commutative expression
> *directly* from a string? To be specific, if I write something like
>
> ex1 = sympify('x1*x2*x1**-1')
>
Other than preprocessing the string and replacing symbols foo with
Symbol(foo, commutative=False), nothing comes to mind. Could this be
done in these steps?
1) replace all numbers with symbols so no variables would be lost
2) make the exression then find what variables it contains
3) replace those variables in the string with the symbol instances and resympify
It ain't pretty; it might break; but it works at least for this expression :-)
def nc_sympify(s):
import re as regex
from sympy.tensor.indexed import IndexedBase
# this matches numbers
pat = '([-+]?((\\d*\\.\\d+)|(\\d+\\.?))(eE[-+]?\\d+)?)'
# split on anything that matches a variable name
bits = regex.split('([_a-z][_a-z0-9]*)', s)
new=[]
for i in range(1, len(bits), 2):
# process piece with numbers in it (maybe):
# replace numbers with symbols having name being str(number)
for n in regex.findall(pat, bi):
bi = bi.replace(n[0], 'Symbol("%s")'%n[0])
bits[i] = bi
new = ''.join(bits)
# sympify and pull out the variables, none of which should have
# disappeared because numbers were replaced with symbols
v = [si for si in S(new).atoms(Symbol) if not regex.match(pat, si.name)]
# replace symbols with a sympify-able object which is noncommutative
for vi in v:
s = s.replace(vi.name, "IndexedBase('%s')"%vi.name)
# resymify and now replace the symbols with non-commutative symbols
eq = S(s)
neweq = eq.subs([(a, Symbol('%s'%a.label, commutative=False)) for
a in eq.atoms(IndexedBase)])
return neweq
>>> s
'x1*x2*x1**(-1) + 2*x2'
>>> nc_sympify(s)
x1*x2*x1**(-1) + 2*x2
HTH,
Chris
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sympy?hl=en.