Try to use this one:

from sympy.unify import unify

def to_abs(node):
    if not isinstance(node, Mul):
        return node
    zm1, zm2 = symbols('zm1, zm2')
    m = unify(node, zm1 * zm2 * conjugate(zm2), {}, variables=[zm1, zm2])
    try:
        m = next(m)
    except:
        return node
    e = m[zm2]
    return node.xreplace({e: S.One, conjugate(e): S.One})*abs(e)**2


I believe that the standard matcher matches too much, let's try the unify 
matcher, which is a structural matcher (and not a math-sensitive matcher).

On Friday, June 6, 2014 1:22:59 PM UTC+2, Andrei Berceanu wrote:
>
> That fixed the error, however, the problem is now if I apply  this 
> function to expressions like
>
> -2*g*conjugate(psi^ss_1)*conjugate(psi^ss_2)
>
> I get
>
> -2*g*conjugate(psi^ss_1)*Abs(psi^ss_2)**2
> so it looks like the pattern matching is working overtime, since it should 
> leave the expression unchanged :)
>
>
>
> On Friday, June 6, 2014 1:07:26 PM UTC+2, F. B. wrote:
>>
>>
>>
>> On Friday, June 6, 2014 12:22:14 PM UTC+2, Andrei Berceanu wrote:
>>>
>>> Tnx!
>>> I think there is an error in the line (unbalanced paranthesis):
>>>
>>> return node.xreplace ({e: S.One, conjugate(e): S.One})*abs(e)**2)
>>>
>>>
>> Yes, sorry, just remove the last parenthesis.
>>
>>  
>>
>>> Also, do you know how I can force the factorization of the 2*g to get 
>>> 2*g(|psi1|**2 + |psi2|**2)?
>>>
>>>
>> Try this one:
>>
>> import collections
>>
>> def unflatten_mul(node):
>>     d = collections.defaultdict(lambda: [])
>>     new_args = []
>>     for arg in node.args:
>>         if arg.args and arg.args[0].is_Number:
>>             d[arg.args[0]].append(arg.func(*arg.args[1:]))
>>             continue
>>         new_args.append(arg)
>>     print d
>>     for key, item in d.items():
>>         new_args.append(Mul(key, Add(*item), evaluate=False))
>>     return node.func(*new_args, evaluate=False)
>>
>>
>> apply this function on *expr*, it should work.
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sympy+unsubscr...@googlegroups.com.
To post to this group, send email to sympy@googlegroups.com.
Visit this group at http://groups.google.com/group/sympy.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sympy/eae490f1-b891-437e-98b6-d0ef192d56dd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to