Normalize Expr and apply basic evaluation methods.
(obj)
| 788 | |
| 789 | |
| 790 | def normalize(obj): |
| 791 | """Normalize Expr and apply basic evaluation methods. |
| 792 | """ |
| 793 | if not isinstance(obj, Expr): |
| 794 | return obj |
| 795 | |
| 796 | if obj.op is Op.TERMS: |
| 797 | d = {} |
| 798 | for t, c in obj.data.items(): |
| 799 | if c == 0: |
| 800 | continue |
| 801 | if t.op is Op.COMPLEX and c != 1: |
| 802 | t = t * c |
| 803 | c = 1 |
| 804 | if t.op is Op.TERMS: |
| 805 | for t1, c1 in t.data.items(): |
| 806 | _pairs_add(d, t1, c1 * c) |
| 807 | else: |
| 808 | _pairs_add(d, t, c) |
| 809 | if len(d) == 0: |
| 810 | # TODO: determine correct kind |
| 811 | return as_number(0) |
| 812 | elif len(d) == 1: |
| 813 | (t, c), = d.items() |
| 814 | if c == 1: |
| 815 | return t |
| 816 | return Expr(Op.TERMS, d) |
| 817 | |
| 818 | if obj.op is Op.FACTORS: |
| 819 | coeff = 1 |
| 820 | d = {} |
| 821 | for b, e in obj.data.items(): |
| 822 | if e == 0: |
| 823 | continue |
| 824 | if b.op is Op.TERMS and isinstance(e, integer_types) and e > 1: |
| 825 | # expand integer powers of sums |
| 826 | b = b * (b ** (e - 1)) |
| 827 | e = 1 |
| 828 | |
| 829 | if b.op in (Op.INTEGER, Op.REAL): |
| 830 | if e == 1: |
| 831 | coeff *= b.data[0] |
| 832 | elif e > 0: |
| 833 | coeff *= b.data[0] ** e |
| 834 | else: |
| 835 | _pairs_add(d, b, e) |
| 836 | elif b.op is Op.FACTORS: |
| 837 | if e > 0 and isinstance(e, integer_types): |
| 838 | for b1, e1 in b.data.items(): |
| 839 | _pairs_add(d, b1, e1 * e) |
| 840 | else: |
| 841 | _pairs_add(d, b, e) |
| 842 | else: |
| 843 | _pairs_add(d, b, e) |
| 844 | if len(d) == 0 or coeff == 0: |
| 845 | # TODO: determine correct kind |
| 846 | assert isinstance(coeff, number_types) |
| 847 | return as_number(coeff) |
searching dependent graphs…