Sympy rewrite expression to template - sympy

If I have an expression such as c1 / (c2*s + c3) I would like sympy to transform the expression to a template looking like C1 / (s + C2) such that C1 = c1/c2 and C2 = c3/c2.
Is there an easy way to do that?

So you are asking "What must C1 and C2 be to make this true?" solve can answer that question:
>>> v = var('c1:4 C1:3 s')
>>> expr = c1 / (c2*s + c3)
>>> tmpl = C1 / (s + C2)
>>> t = tmpl.free_symbols - expr.free_symbols
>>> solve(expr - tmpl, t, dict=True)
[{C1: c1/c2, C2: c3/c2}]

Related

SymPy cannot rearrange results while solving a system of equations about Stackelberg game

Function f (assume n=3 for simplicity):
There are 3 symbols related to entities, corresponding to x[j](j=1,2,3) respectively. R and c is other symbols, which can be treated like constant for now. I try to diff f w.r.t x[j], and solve the results equations together and get x[j]=g(R,c). However, sympy cannot rearrange or split x[j] from the equation.
Derivatives:
Expected Results:
from sympy import *
import sympy as sym
real_n = 3
x = IndexedBase('x')
j, k, n = symbols('j,k n', cls=Idx)
f = x[j]*Symbol("R")/Sum(x[k],(k,1,real_n))-Symbol("c")*x[j]
equ = diff(f,x[j])
ee = solve([equ.subs(j,1),equ.subs(j,2),equ.subs(j,3)], (x[1],x[2],x[3]))
simplify(ee)
Sympy's result:
{x[1]: (R*Sum(x[k], (k, 1, 3)) - c*Sum(x[k], (k, 1, 3))**2)/(R*Sum(KroneckerDelta(1, k), (k, 1, 3))),
x[2]: (R*Sum(x[k], (k, 1, 3)) - c*Sum(x[k], (k, 1, 3))**2)/(R*Sum(KroneckerDelta(2, k), (k, 1, 3))),
x[3]: (R*Sum(x[k], (k, 1, 3)) - c*Sum(x[k], (k, 1, 3))**2)/(R*Sum(KroneckerDelta(3, k), (k, 1, 3)))}
I tried to check if the indexed symbol caused the error, and wrote x[i] as 3 different symbols, but it still didn't work.
from sympy import *
a, b, c = symbols('a b c', cls=Idx)
R = symbols("R")
eq1 = diff(a/(a+b+c)-a*R,a)
eq2 = diff(b/(a+b+c)-b*R,b)
eq3 = diff(c/(a+b+c)-c*R,c)
print(eq1,"\n",eq2,"\n",eq3)
solve([eq1,eq2,eq3], [a,b,c])
Output:
-R + 1/(a + b + c) - a/(a + b + c)**2
-R + 1/(a + b + c) - b/(a + b + c)**2
-R + 1/(a + b + c) - c/(a + b + c)**2
[]
Is there something wrong with my approach? Is it possible to approach this problem in SymPy from another angle?
Any suggestions for the solution of equations are also most welcome.
You can use doit to expand the summation and then solve:
In [6]: solve([equ.subs(j,1).doit(),equ.subs(j,2).doit(),equ.subs(j,3).doit()], (x[1],x[2],x[3]))
Out[6]:
⎡⎛ ____ ⎞⎤
⎢⎜ ╱ 2 ⎟⎥
⎢⎜R + 3⋅╲╱ R 2⋅R 2⋅R⎟⎥
⎢⎜─────────────, ───, ───⎟⎥
⎣⎝ 18⋅c 9⋅c 9⋅c⎠⎦

How to quickly generate a large number of constraints with pyomo

Actually I want to express a set of constraints like this: A + B + C + D + E <= F,
A,B,C,D,E,F are all l*t matrices.
Unfortunately, I only do constraint construction by using “for” loops,like this:
'''
model.TN = pyo.Set(initialize = TN)
model.LN = pyo.Set(initialize = LN)
model.Pc = pyo.Var(model.GN, model.TN, domain = pyo.NonNegativeReals)
def branch_Cap1(t, l):
return sum(Tc[l, n] * model.Pc[n, t] for n in range(GenCount)) - sum(Tl[l, bus] * ldata[bus , t] for bus in range(loadCount)) <= Fmax[l]
def branch_Cap2(t, l):
return sum(Tc[l, n] * model.Pc[n, t] for n in range(GenCount)) - sum(Tl[l, bus] * ldata[bus , t] for bus in range(loadCount)) >= - Fmax[l]
model.branch_Cap1 = pyo.Constraint(model.TN, model.LN, rule = lambda model, t, l: branch_Cap1(t, l))
model.branch_Cap2 = pyo.Constraint(model.TN, model.LN, rule = lambda model, t, l: branch_Cap2(t, l))
'''
Can somebody help me?
thanks a lot.

SML: why the return type is unit?

So I have wrote a function (I will describe it briefly to avoid confusion)
fun function1 (l, a1,a2, suma, b2, sumb, d) =
while(a1<a2 andalso k>d) do
let
val k = Real.fromInt(a2-a1)
val suma = suma - Real.fromInt(List.nth(l, a1))
val sumb = sumb - Real.fromInt(List.nth(l, b2))
val a1 = a1+1
val b2 = b2-1
in
if suma<0.0 andalso ( (~sumf)/(N*k) )>1.0 andalso k>d
then k
else if sumb<0.0 andalso ((~sumb)/(N*k))>1.0 andalso k>d
then k
else d
end;
The system says this:
val function1 = fn : int list * int * int * real * int * real * real -> unit
I don't get the return type. I want to return a real like d & k . Why it's unit??

Regular expression of string of a, b that doesn't contain aa

Using only parenthesis and * symbol, one example that comes in my mind is
((a|b)(bb*))*
but I can have a string for example abba that the last letter is a, which is not included in this... Any ideas?
Here is the DFA:
Use the method described here to derive and solve the equation for R1 (the initial state):
R1 = bR1 + aR2 + λ
R2 = bR1 + λ
Substitute R2 to R1:
R1 = bR1 + abR1 + a + λ
Apply the Arden's theorem:
R1 = (b + ab)*(a + λ)
The rest is change the syntax a bit:
(b|ab)*(a|)
This can be rewritten to regex in Perl-syntax for testing:
^(a?b)*a?$

How to solve a simple quadratic equation with Sympy?

solve(-14.4*(x**2)+71.8*x+5.083, x)
result is None. how come? My calculation by hand gives two roots, 5.0559 and -0.063
Perhaps you are not using the most current version. I get
>>> from sympy import *
>>> var('x')
x
>>> solve(-14.4*(x**2)+71.8*x+5.083, x)
[-0.0698162934055920, 5.05592740451670]
More generally:
import sympy as sp
y = 'a * x ** 2 + b * x + c' # for example a quadratic polynomial
s = sp.var('x a b c') # define four symbols as variables
print(sp.solve(y, s )) # sympy solves y(a,b,c,x) for each of a, b, c, x
print(sp.solve(y, x )) # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
print(sp.solve(y, 'x')) # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
Yields:
[(x, -(b*x + c)/x**2, b, c)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
While:
s = sp.var('x') # define one symbol as a varible
print(sp.solve(y, s )) # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
print(sp.solve(y, x )) # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
print(sp.solve(y, 'x')) # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
Returns:
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]