SymPy simplify cannot 2*3**n/3 ---> 2*3**(n-1) - sympy

Thank you in advance and sorry for the bad english!
FullScript.py
from sympy import *
var('n')
f= 3**n/3
print(simplify(f))
#---------------------
f= 2*3**n/3
print(simplify(f))
# 3**(n - 1) # OK
# 2*3**n/3 # I want 2*3**(n-1)
2018-11-27------------------------------
Please tell me how to use the if statement
How to extract numerator and denominator from polynomial without evaluating?
FullScript.py
from sympy import *
var('n')
def MySimplify(h):
Mypoly = poly(h)
aa = Mypoly.all_coeffs()[1]
bb = h - aa
n, d = fraction(bb)
nn0 = n.as_base_exp()[0]
nn1 = poly(nn0)
import re
rese1 = re.search('^Poly\((.+?),(.+?),', str(nn1)).group(1)
rese2 = re.search('^Poly\((.+?),(.+?),', str(nn1)).group(2)
two=sympify(rese1)/sympify(rese2)
ans = powsimp(bb/two)*two+aa
return ans
f= 3**n/3
print("f1=",f)
print("f2=",simplify(f))
g= 4+2*3**n/3
print("g1=",g)
print("g2=",simplify(g))
print("g3=",MySimplify(g))
# f1= 3**n/3
# f2= 3**(n - 1)
# g1= 2*3**n/3 + 4
# g2= 2*3**n/3 + 4
# g3= 2*3**(n - 1) + 4
2018-11-28------------------------------
FullScript.py
from sympy import *
var('m n p q r s t u v x')
def ps(e, *args):
x = Dummy(integer=True)
t=list(Add.make_args(e))
for i, ti in enumerate(t):
c, r = ti.as_coeff_Mul()
if c.is_Rational and not c.is_Integer:
t[i] = Mul(c.p, r, Pow(c.q, x), evaluate=False)
# t[i] = powersimp(t[i], *args).xreplace({x: -1})
t[i] = powsimp(t[i], *args).xreplace({x: -1})
else:
t[i] = powsimp(t[i], *args)
return Add(*t)
f= 4+2*3**n/3
print("f1=",f)
print("f1=",ps(f))
f= 4+2*3**n/3+5*2.4**(m-1)/2.4+6*5.6*(p-7)/8.9
print("f2=",f)
print("f2=",ps(f))
g= x+p**n/p
print("g1=",g)
print("g1=",ps(g))
g= x+p**n/p+q*s**(m-1)/s+r*t**(u-2)/v
print("g2=",g)
print("g2=",ps(g))
# f1= 2*3**n/3 + 4
# f1= 2*3**(n - 1) + 4
# f2= 2.08333333333333*2.4**(m - 1) + 2*3**n/3 + 3.7752808988764*p - 22.4269662921348
# f2= 2.08333333333333*2.4**(m - 1) + 2*3**(n - 1) + 3.7752808988764*p - 22.4269662921348
# g1= x + p**n/p
# g1= p**(n - 1) + x
# g2= q*s**(m - 1)/s + r*t**(u - 2)/v + x + p**n/p
# g2= p**(n - 1) + q*s**(m - 2) + r*t**(u - 2)/v + x

powsimp(f/2)*2 will do what you want. The following is a more general workaround that incorporates this idea:
def ps(e, *args):
x = Dummy(integer=True)
t=list(Add.make_args(e))
for i, ti in enumerate(t):
c, r = ti.as_coeff_Mul()
if c.is_Rational and not c.is_Integer:
t[i] = Mul(c.p, r, Pow(c.q, x), evaluate=False)
t[i] = powersimp(t[i], *args).xreplace({x: -1})
else:
t[i] = powsimp(t[i], *args)
return Add(*t)

Related

Model Matrix Least Squares (Frobenius Norm) Problem with pyomo?

How to model the following problem with pyomo and Gurobi solver?
This is a non-convex problem, and can not model as a QCQP problem. So I want to solve it with pyomo and Gurobi solver. The most difficult part is matrix algebra (pyomo do not support yet).
Many thanks!
Here is my own answer. Please let me know if there are any mistakes. Thanks!
import pyomo.environ as pyo
## get your param
L, Delta =
K, P =
O, l =
ones3 = np.ones((3, 1))
model = pyo.ConcreteModel()
model.r = pyo.RangeSet(0,2) # 3
model.s = pyo.RangeSet(0,0) # 1
model.n = pyo.RangeSet(0,len(L)-1) # n
model.m = pyo.RangeSet(0,len(K)-1) # m
model.q = pyo.RangeSet(0,len(O)-1) # q
def param_rule(I, J, mat):
return dict(((i,j), mat[i,j]) for i in I for j in J)
model.L = pyo.Param(model.n, model.n, initialize=param_rule(model.n, model.n, L)) # L
model.Delta = pyo.Param(model.n, model.r, initialize=param_rule(model.n, model.r, Delta)) # Delta
model.K = pyo.Param(model.m, model.n, initialize=param_rule(model.m, model.n, K)) # K
model.P = pyo.Param(model.m, model.r, initialize=param_rule(model.m, model.r, P)) # P
model.O = pyo.Param(model.q, model.n, initialize=param_rule(model.q, model.n, O)) # O
model.ones3 = pyo.Param(model.r, model.s, initialize=param_rule(model.r, model.s, ones3)) # ones3
model.l = pyo.Param(model.q, initialize=dict(((i),l[i,0]) for i in model.q)) # l
model.V = pyo.Var(model.n, model.r, initialize=param_rule(model.n, model.r, Delta)) # V
def ObjRule(model):
return 0.5*sum((sum(model.L[i,k]*model.V[k,j] for k in model.n) - model.Delta[i,j])**2 for i in model.n for j in model.r)
model.obj = pyo.Objective(rule=ObjRule, sense=pyo.minimize)
model.constraints = pyo.ConstraintList()
# constraints 1
[model.constraints.add(sum(model.K[i,k] * model.V[k,j] for k in model.n) == model.P[i,j]) for i in model.m for j in model.r]
# constraint 2
for i in model.q:
model.constraints.add(sum(sum(model.O[i,k] * model.V[k,j] for k in model.n)**2 for j in model.r) == model.l[i])
opt = pyo.SolverFactory('gurobi')
opt.options['nonconvex'] = 2
solution = opt.solve(model)
V_opt = np.array([pyo.value(model.V[i,j]) for i in model.n for j in model.r]).reshape(len(model.n),len(model.r))
obj_values = pyo.value(model.obj)
print("optimum point: \n {} ".format(V_opt))
print("optimal objective: {}".format(obj_values))

how to rewrite (a+b+c)**2 as a**2 + b**2 + c*2 + 2*(a*b + b*c + c*a) & ^2-->**2

sympy conversion:(a+b+c)^2 --> a^2 +b^2+c^2+2*(ab + bc + c*a) : I want
sorry add
sympy conversion: I want
(a+b+c)**2 --> a**2 +b**2+c**2+2*(a*b + b*c + c*a)
I try
from sympy import *
var('a b c')
f=(a+b+c)**2
print("#f",f)
print("#e",expand(f))
#f (a + b + c)**2
#e a**2 + 2*a*b + 2*a*c + b**2 + 2*b*c + c**2
(2022-02-02)
i try use factor atom
from sympy import *
var('a b c x')
f_str="a+b+c"
g_str="a**2+b**2+c**2"
f =factor(simplify(f_str))
g =factor(simplify(g_str))
mySubs={f:1,g:13}
#
h =factor(f**2-g)
ha=list(h.atoms(Number))[0]
hb=h/ha
Le=(f.subs(mySubs))**2
Ri1=g.subs(mySubs)
Ri2=h.subs({hb:x})
print("#","(",f_str,")**2=",g_str,"+",ha,"*(",hb,")")
print("#",f_str,"=",mySubs[f],",",g_str,"=",mySubs[g])
print("#",Le,"**2=",Ri1,"+",ha,"*(",solve(Eq(Le,Ri1+Ri2))[0],")")
# ( a+b+c )**2= a**2+b**2+c**2 + 2 *( a*b + a*c + b*c )
# a+b+c = 1 , a**2+b**2+c**2 = 13
# 1 **2= 13 + 2 *( -6 )
(2022-02-04) value subs
from sympy import *
var('a b c')
f_str="a+b+c "
g_str="a**2+b**2+c**2"
h_str="a*b+a*c+b*c "
mySubs={a:0,b:-2,c:3}
f=factor(simplify(f_str)).subs(mySubs)
g=factor(simplify(g_str)).subs(mySubs)
h=factor(simplify(h_str)).subs(mySubs)
print("#",mySubs)
print("#",f_str,"=",f)
print("#",g_str,"=",g)
print("#",h_str,"=",h)
print("#",f_str,"**2=",g_str,"+2*(",h_str,")")
print("#",f,"**2=",g,"+2*(",h,")")
# {a: 0, b: -2, c: 3}
# a+b+c = 1
# a**2+b**2+c**2 = 13
# a*b+a*c+b*c = -6
# a+b+c **2= a**2+b**2+c**2 +2*( a*b+a*c+b*c )
# 1 **2= 13 +2*( -6 )
(2022-02-05) value subs
from sympy import *
var('a b c')
f=a+b+c
g=a**2+b**2+c**2
h=a*b+a*c+b*c
mySubs={a:0,b:-2,c:3}
#
f_val=factor(f).subs(mySubs)
g_val=factor(g).subs(mySubs)
h_val=factor(h).subs(mySubs)
print("#",mySubs)
print("#",f,"=",f_val)
print("#",g,"=",g_val)
print("#",h,"=",h_val)
print("#",f,"**2=",g_val,"+2*(",h,")")
print("#",f_val,"**2=",g_val,"+2*(",h_val,")")
# {a: 0, b: -2, c: 3}
# a + b + c = 1
# a**2 + b**2 + c**2 = 13
# a*b + a*c + b*c = -6
# a + b + c **2= 13 +2*( a*b + a*c + b*c )
# 1 **2= 13 +2*( -6 )
(Reference)
2022 Mathematics IA Q1 < The Common Test for University Admissions is a common entrance examination for Japanese universities
japanese only
https://cdn.mainichi.jp/item/jp/etc/kyotsu-2022/pdf/MT1P.pdf#page=1
>>> from sympy.parsing.sympy_parser import *
>>> f = parse_expr('(a+b+c)^2', transformations=(auto_symbol, convert_xor))
>>> f
(a + b + c)**2
>>> from sympy import Pow
>>> nopow, pow = f.expand().as_independent(Pow)
>>> pow + nopow.factor()
a**2 + b**2 + c**2 + 2*(a*b + a*c + b*c)

Collecting sub-expressions of a multivariate polynomial function in Sympy

I have a degree 6 multivariate equation in x and y written in Sympy, e.g.
eqn = a*x**6 + b*x**5*y + c*x**4*y + d*x**3*y + e*x**3*y**2 + ...
Is there a way to collect (x**2+y**2) and rearrange them into the following format?
eqn2 = A*(x**2+y**2)**3 + B*(x**2+y**2)**2 + C*(x**2+y**2) + D
A, B, C, D can be in x, y.
So far I have only tried collect(eqn, x**2 + y**2) and it returned the original equation.
Thank you!
Consider using a temporary symbol z = x**2 + y**2 and replace x**2 with z - y**2, then expand and restore:
>>> ex
A*x**6 + 3*A*x**4*y**2 + 3*A*x**2*y**4 + A*y**6 + B*x**4 + 2*B*x**2*y**2 +
B*y**4 + C*x**2 + C*y**2 + D
>>> ex.subs(x**2, z - y**2).expand().subs(z, x**2 + y**2)
A*(x**2 + y**2)**3 + B*(x**2 + y**2)**2 + C*(x**2 + y**2) + D
Although that works, perhaps a more direct thing to do is separate the expression by coefficients A-D and then factor those collections of terms:
def separatevars_additively(expr, symbols=[]):
free = set(symbols) or expr.free_symbols
d = {}
while free:
f = free.pop()
expr, dep = expr.as_independent(f, as_Add=True)
if dep.has(*free):
return None
d[f] = dep
if expr:
d[0] = expr
return d
>>> coeff = var("A:D")
>>> separatevars_additively(ex, coeff)
{B: B*x**4 + 2*B*x**2*y**2 + B*y**4, A: A*x**6 + 3*A*x**4*y**2 + 3*A*x**2*y**4 + A*y**6, D: D, C: C*x**2 + C*y**2}
>>> Add(*[factor(i) for i in _.values()])
A*(x**2 + y**2)**3 + B*(x**2 + y**2)**2 + C*(x**2 + y**2) + D

How to change a module's function

I have a module that I want to import. Lets say its name is module1.py .
There is a function inside this module (F(X,Y)). Here is a part of this module:
def F(X,Y):
S=complex(X,Y)
Fs=2/(pow(S,3))
Rfs=real(Fs)
return Rfs
Sum=F(X,0)/2.
print Sum
I can import this module by:
import module1
But I need to change something in the F function after I import it. For example I want to substitute this function in the module with the old one (I want to change Fs in the F function):
def F(X,Y):
S=complex(X,Y)
Fs=1/(S-1)
Rfs=real(Fs)
return Rfs
Could you please tell me how I can do that in python 2.7?
You can do this by extending Module1. Extending a class allows you to keep all of the previous functions and attributes of the base class but override any that you would like to change.
This example shows that you can call all of the other functions inside of the original Module1 but that when you call the F() function it uses the one from extended class.
Python2.7
Module1.py
class Module1():
def F(self,X,Y):
S=complex(X,Y)
Fs=2/(pow(S,3))
Rfs=real(Fs)
return Rfs
def G(self):
return "function G"
def H(self):
return "function H"
Module1_ext.py
import Module1
class Module1(Module1.Module1):
def F(self,X,Y):
return X*Y;
run.py
from Module1_ext import Module1
mod = Module1()
print(mod.G())
print(mod.H())
print(mod.F(2,3))
Python3+
Module1.py
class Module1():
def F(X,Y):
S=complex(X,Y)
Fs=2/(pow(S,3))
Rfs=real(Fs)
return Rfs
def G():
return "function G"
def H():
return "function H"
Module1_ext.py
import Module1
class Module1(Module1.Module1):
def F(X,Y):
return X*Y;
run.py
from Module1_ext import Module1
print(Module1.G())
print(Module1.H())
print(Module1.F(2,3))
Finally I figured it out by myself. This is how I solved the issue:
First we need to rewrite the module in this form:
module1.py
from numpy import *
M = 11
SU = zeros(M + 2)
C = zeros(M + 1)
C[0] = 1
for k in range(1, M + 1):
C[k] = (M - (k - 1)) * C[k - 1] / k
# T=input("TIME=")
class BB:
def F(self, fnRf):
T=1
A = 19.1
U = exp(A / 2.) / T
X = A / (2. * T)
H = pi / T
Ntr = 15
Sum = fnRf(X, 0) / 2.
for N in range(1, Ntr + 1):
Y = N * H
Sum += (-1) ** N * fnRf(X, Y)
SU[0] = Sum
for K in range(1, M + 2):
N = Ntr + K
Y = N * H
SU[K] = SU[K - 1] + (-1) ** N * fnRf(X, Y)
Avgsu = 0.
Avgsu1 = 0.
for J in range(M + 1):
Avgsu += C[J] * SU[J]
Avgsu1 += C[J] * SU[J + 1]
Fun = U * Avgsu / 2048
Fun1 = U * Avgsu1 / 2048
print Fun1
We can import this module like this:
from module1 import *
def fnRf(X, Y):
S = complex(X, Y)
Fs = 1. / (S-1)
Rfs = real(Fs)
return Rfs
ss=BB()
ss.F(fnRf)
This way we are flexible to define the function (in the module). Now it works perfectly. I hope it was helpful.

Why does SymPy ignore my initial condition?

import sympy as sp
t = sp.Symbol("t")
y = sp.Function("y")
v = sp.Function("v")
sol = sp.dsolve([
y(t).diff(t) - v(t),
v(t).diff(t) + 2*y(t)
],
ics={y(0):2, v(0):0.45})
sol
gives:
[y(t) == C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t),
v(t) == sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t)]
Why are C1 and C2 not calculated?