I am having a bit of trouble with Sympy's solveset. I am trying to use Sympy to find a solution to an basic circuit analysis question involving three unknown resistors and two equations. I realize that I will have to guess at the value of one of the resistors and then calculate the value of the other two resistors. I am using superposition to solve the circuit.
This is the circuit and superposition I am trying to solve
import sympy
V_outa, V_outb, R_1, R_2, R_3, V_1, V_2 = symbols('V_outa V_outb R_1 R_2 R_3 V_1 V_2')
### Here are a bunch of variable definitions.
R_eq12 = R_2*R_3/(R_2+R_3)
R_eq123 = R_eq12 + R_1
V_outa = V_1 *R_eq12/R_eq123
R_eq13 = R_1*R_3/(R_1+R_3)
R_eq123b = R_2 + R_eq13
V_outb = V_2 * R_eq13/R_eq123b
### Here is my governing equation.
V_out = 0.5* V_outb + (1/6) *V_outa
### Now I can start setting up the equations to solve. This sets the
### coefficient of the V1 term equal to the 1/2 in the governing equation
### and the coefficient of the V2 term equal to 1/6. I have also guessed
### that R_3 is equal to 10 ohms.
eq1 = Eq(1.0/2.0, V_out.coeff(V_2).subs(R_3, 10))
eq2 = Eq(1.0/6.0, V_out.coeff(V_2).subs(R_3, 10))
#### Now when I try to solve eq1 and eq2 with solveset, I get an error.
solveset([eq1, eq2], (R_2, R_3))
And here is the error I get:
ValueError: [Eq(0.500000000000000, 10*R_1/((R_1 + 10)*(10*R_1/(R_1 +
10) + R_2))), Eq(0.166666666666667, 10*R_1/((R_1 + 10)*(10*R_1/(R_1 +
10) + R_2)))] is not a valid SymPy expression
The other thing I don't understand is the set type I get when I try to solve it this way. Could someone also explain what set type this is, and how to make use of it?
expr3 = -1.0/2.0 + V_out.coeff(V_2).subs(R_3, 10)
solveset(expr3, R_2)
A screen shot of the weird set type
Any help would be much appreciated. I know it is a solvable set because Wolfram Alpha had no problems with it.
Thanks!
David
Related
I've got this equation from mathematical model to know the thermal behavior of a battery.
dTsdt = Ts * a+ Ta * b + dTadt * c + d
However, i can't get to solve it due to the nested derivatives.
I need to solve the equation for Ts and Ta.
I tried to define it as follows, but python does not like it and several eŕrors show up.
Im using scipy.integrate and the solver ODEint
Since the model takes data from vectors, it has to be solved for every time step and record the output accordingly.
I also tried assinging the derivatives to a variable v1,v2, and then put everything in an equation without derivatives like the second approach shown as follows.
def Tmodel(z,t,a,b,c,d):
Ts,Ta= z
dTsdt = Ts*a+ Ta*b + dTadt*c+ d
dzdt=[dTsdt]
return dzdt
z0=[0,0]
# solve ODE
for i in range(0,n-1):
tspan = [t[i],t[i+1]]
# solve for next step
z = odeint(Tmodel,z0,tspan,arg=(a[i],b[i],c[i],d[i],))
# store solution for plotting
Ts[i] = z[1][0]
Ta[i] = z[1][1]
# next initial condition
z0 = z[1]
def Tmodel(z,t,a,b,c,d):
Ts,v1,Ta,v2= z
# v1= dTsdt
# v2= dTadt
v1 = Ts*a+ Ta*b + v2*c+ d
dzdt=[v1,v2]
return dzdt
That did not work either.I believe there might be a solver capable of solving that equation or the equation must be decouple in a way and solve accordingly.
Any advice on how to solve such eqtn with python would be appreciate it.
Best regards,
MM
Your difficulty seems to be that you are given Ta in a form with no easy derivative, so you do not know where to take it from. One solution is to avoid this derivative completely and solve the system for y=Ts-c*Ta. Substitute Ts=y+c*Ta in the right side to get
dy/dt = y*a + Ta*(b+c*a) + d
Of course, this requires then a post-processing step Ts=y+c*Ta to get to the requested variable.
If Ta is given as function table, use an interpolation function to get values at any odd time t that is demanded by the ODE solver.
Ta_func = interp1d(Ta_times,Ta_values)
def Tmodel(y,t,a,b,c,d):
Ta= Ta_func(t)
dydt = y*a+ Ta*(b+c*a) + d
return dydt
y[0] = Ts0-c*Ta_func(t[0])
for i in range(len(t)-1):
y[i+1] = odeint(Tmodel,y[i],t[i:i+2],arg=(a[i],b[i],c[i],d[i],))[-1,0]
Ts = y + c*Ta_func(t)
I have attempted to solve the following problem.
For the calculation of gradient we are obliged to use an approximate calculation:
I tried to solve it for each vector e of the canonical basis of R^4 and using h = 1e-05 for example.
However, I made an example for R^2, but I'm not sure if my code is correct for this case and I need to change code for the formule in the picture.
def f(x,y):
return np.sin(x)+np.cos(y)
def derivative(func, vx, h):
e = np.array([[1,0],[0,1]]) #Basis canonique of R^2
x = vx[0]
y = vx[1]
dx=(func(x + e[0]*h,y) - func(x,y)) / h #directional derivative in x
dy=(func(x ,y+e[1]*h) - func(x,y)) / h #directional derivative in y
grad = np.array([dx[0],dy[1]])
return grad
vx=np.array([np.pi,1])
derivative(f,vx,h)
Results of this code:
In [150]: derivative(f,vx,h)
Out[150]: array([-1. , -0.84147369])
I am a little confused how to do this problem but I was hoping to get some help with fixing the code I produced so far. Thanks!
Review section 4.6 - Systems of Equations of the text below:
Numerical Methods in Engineering with Python 3 (3rd ed.)
I came across a problem. One string is taken as input say
input_string = "12345 + x = x * 5 + (1+x)* x + (1+18/100)"
And get output of x using python. I am not able to figure out logic for this.
Here is a complete SymPy example for your input:
from sympy import Symbol, solve, Eq
from sympy.parsing.sympy_parser import parse_expr
input_string = "12345 + x = x * 5 + (1+x)* x + (1+18/100)"
x = Symbol('x', real=True)
lhs = parse_expr(input_string.split('=')[0], local_dict={'x':x})
rhs = parse_expr(input_string.split('=')[1], local_dict={'x':x})
print(lhs, "=", rhs)
sol = solve(Eq(lhs, rhs), x)
print(sol)
print([s.evalf() for s in sol])
This outputs:
x + 12345 = x*(x + 1) + 5*x + 59/50
[-5/2 + 9*sqrt(15247)/10, -9*sqrt(15247)/10 - 5/2]
[108.630868798908, -113.630868798908]
Note that solve() gives a list of solutions. And that SymPy normally does not evaluate fractions and square roots, as it prefers solutions without loss of precision. evalf() evaluates a float value for these expressions.
Well, that example shows a quadratic equation which may have no solutions, one solution, or two solutions. You would have to rearrange the terms symbolically to come to
input_string = "x**2 + 5*x - 12345 + (118/100)"
But that means you need to implement rules for multiplication, addition, subtraction and potentially division. At least for Python there is a library called SymPy which can parse such strings and provide an expression that you can evaluate and even solve.
I'm attempting to solve the differential equation:
m(t) = M(x)x'' + C(x, x') + B x'
where x and x' are vectors with 2 entries representing the angles and angular velocity in a dynamical system. M(x) is a 2x2 matrix that is a function of the components of theta, C is a 2x1 vector that is a function of theta and theta' and B is a 2x2 matrix of constants. m(t) is a 2*1001 array containing the torques applied to each of the two joints at the 1001 time steps and I would like to calculate the evolution of the angles as a function of those 1001 time steps.
I've transformed it to standard form such that :
x'' = M(x)^-1 (m(t) - C(x, x') - B x')
Then substituting y_1 = x and y_2 = x' gives the first order linear system of equations:
y_2 = y_1'
y_2' = M(y_1)^-1 (m(t) - C(y_1, y_2) - B y_2)
(I've used theta and phi in my code for x and y)
def joint_angles(theta_array, t, torques, B):
phi_1 = np.array([theta_array[0], theta_array[1]])
phi_2 = np.array([theta_array[2], theta_array[3]])
def M_func(phi):
M = np.array([[a_1+2.*a_2*np.cos(phi[1]), a_3+a_2*np.cos(phi[1])],[a_3+a_2*np.cos(phi[1]), a_3]])
return np.linalg.inv(M)
def C_func(phi, phi_dot):
return a_2 * np.sin(phi[1]) * np.array([-phi_dot[1] * (2. * phi_dot[0] + phi_dot[1]), phi_dot[0]**2])
dphi_2dt = M_func(phi_1) # (torques[:, t] - C_func(phi_1, phi_2) - B # phi_2)
return dphi_2dt, phi_2
t = np.linspace(0,1,1001)
initial = theta_init[0], theta_init[1], dtheta_init[0], dtheta_init[1]
x = odeint(joint_angles, initial, t, args = (torque_array, B))
I get the error that I cannot index into torques using the t array, which makes perfect sense, however I am not sure how to have it use the current value of the torques at each time step.
I also tried putting odeint command in a for loop and only evaluating it at one time step at a time, using the solution of the function as the initial conditions for the next loop, however the function simply returned the initial conditions, meaning every loop was identical. This leads me to suspect I've made a mistake in my implementation of the standard form but I can't work out what it is. It would be preferable however to not have to call the odeint solver in a for loop every time, and rather do it all as one.
If helpful, my initial conditions and constant values are:
theta_init = np.array([10*np.pi/180, 143.54*np.pi/180])
dtheta_init = np.array([0, 0])
L_1 = 0.3
L_2 = 0.33
I_1 = 0.025
I_2 = 0.045
M_1 = 1.4
M_2 = 1.0
D_2 = 0.16
a_1 = I_1+I_2+M_2*(L_1**2)
a_2 = M_2*L_1*D_2
a_3 = I_2
Thanks for helping!
The solver uses an internal stepping that is problem adapted. The given time list is a list of points where the internal solution gets interpolated for output samples. The internal and external time lists are in no way related, the internal list only depends on the given tolerances.
There is no actual natural relation between array indices and sample times.
The translation of a given time into an index and construction of a sample value from the surrounding table entries is called interpolation (by a piecewise polynomial function).
Torque as a physical phenomenon is at least continuous, a piecewise linear interpolation is the easiest way to transform the given function value table into an actual continuous function. Of course one also needs the time array.
So use numpy.interp1d or the more advanced routines of scipy.interpolate to define the torque function that can be evaluated at arbitrary times as demanded by the solver and its integration method.
I have a standard problem in economics, which I would like to solve using sympy's nonlinsolve.
I want to symbolically find the steady state of a model and to that end solve a nonlinear system of equations.
I was happy to see sympy has nonlinsolve which is supposed to be able to solve such problems but I am so far unable to do so.
In the following you find the part of the problem which does not solve on it's own:
from sympy.solvers.solveset import nonlinsolve
from sympy import var
var('c k mc n r_k eta w alpha', Rational = True, positive=True)
eq1 = -r_k + alpha * mc * k**(-1 + alpha) * n**(1 - alpha)
eq2 = -w + mc * (1 - alpha) * k**alpha * n**(-alpha)
eq3 = c**-1 * w - n**eta
eq_system = [eq1,eq2,eq3]
nonlinsolve(eq_system , [n,k,w])
alpha and eta are parameters whereas the other symbols are variables. I know they are rational positive numbers but for a reason I do not understand yet, the code throws:
ValueError: alpha: Exponent must be a positive Integer
Neither do I see why alpha must be an integer nor does it help if I declare alpha as such.
Any hint as to how I can get a meaningful solution using sympy?
Many thanks,
Thore