Repository: sympy/sympy

Issue:
create_expand_pow_optimization() is not robust
Using SymPy 1.3:

```
import sympy as sp
from sympy.codegen.rewriting import create_expand_pow_optimization
expand_opt = create_expand_pow_optimization(7)
a = sp.symbols("a")
expr = a**(5) - a**2
print("should be a**5 - a**2:",expr)
print("should be a*a*a*a*a - a*a:",expand_opt(expr))
expr = a**(-5)
print("should be a**(-5):",expr)
print("should be equal to a**(-5):", expand_opt(expr))
```

Output is:
```
should be a**5 - a**2: a**5 - a**2
should be a*a*a*a*a - a*a: -a**2 + a*a*a*a*a
should be a**(-5): a**(-5)
should be equal to a**(-5): 1
```

Notice that it failed to optimize `-a**2` and more disturbingly `a**(-5)` was evaluated to `1`.

Discussion:

Patch:
diff --git a/sympy/codegen/rewriting.py b/sympy/codegen/rewriting.py
index c005717c56..f5742d2fb6 100644
--- a/sympy/codegen/rewriting.py
+++ b/sympy/codegen/rewriting.py
@@ -221,7 +221,7 @@ def create_expand_pow_optimization(limit):
 
     """
     return ReplaceOptim(
-        lambda e: e.is_Pow and e.base.is_symbol and e.exp.is_integer and e.exp <= limit,
+        lambda e: e.is_Pow and e.base.is_symbol and e.exp.is_integer and e.exp.is_nonnegative and e.exp <= limit,
         lambda p: Mul(*([p.base]*p.exp), evaluate=False)
     )
 


Test patch:
diff --git a/sympy/codegen/tests/test_rewriting.py b/sympy/codegen/tests/test_rewriting.py
index 2001f95e72..075a62389e 100644
--- a/sympy/codegen/tests/test_rewriting.py
+++ b/sympy/codegen/tests/test_rewriting.py
@@ -169,3 +169,5 @@ def test_create_expand_pow_optimization():
 
     sin4x = sin(x)**4
     assert ccode(optimize(sin4x, [my_opt])) == 'pow(sin(x), 4)'
+
+    assert ccode(optimize((x**(-4)), [my_opt])) == 'pow(x, -4)'