Solve a nonlinear system of equation via sympy - sympy
I have a system of ODE and want to find equilibrium points by using nonlinsolve() but when i run it by jubyter or spyder the program keep running without any result.
N,x1,x2,x3,x4,y1,y2,r1,r2,r3,r4,eta1,eta2,eta3,eta4,R,c1,c2,c3,c4,a11,a12,a21,a22,a31,a32,a41,a42,b12,h,h11,h12,h21,h22,h31,h32,h41,h42,s1,s2,s3,s4,epsilon1,epsilon2,omega1,omega2,K11,K22,beta11,beta21,beta31,beta41,beta12,beta22,beta32,beta42,gamma12=sp.symbols('x1,x2,x3,x4,y1,y2,r1,r2,r3,r4,eta1,eta2,eta3,eta4,N,R,c1,c2,c3,c4,a11,a12,a21,a22,a31,a32,a41,a42,b12,h,h11,h12,h21,h22,h31,h32,h41,h42,s1,s2,s3,s4,epsilon1,epsilon2,omega1,omega2,K11,K22,beta11,beta21,beta3a,beta41,beta12,beta22,beta32,beta42,gamma12')
F2=x1*(r1*(1-(eta1*x1+eta2*x2+eta3*x3+eta4*x4)/N)-(a11*y1)/(y1+a11*h11*x1)-(a12*y2)/(y2+a12*h12*x1))+s1
F3=x2*(r2*(1-(eta1*x1+eta2*x2+eta3*x3+eta4*x4)/N)-(a21*y1)/(y1+a21*h21*x2)-(a22*y2)/(y2+a22*h22*x2))+s2
F4=x3*(r3*(1-(eta1*x1+eta2*x2+eta3*x3+eta4*x4)/N)-(a31*y1)/(y1+a31*h31*x3)-(a32*y2)/(y2+a32*h32*x3))+s3
F5=x4*(r4*(1-(eta1*x1+eta2*x2+eta3*x3+eta4*x4)/N)-(a41*y1)/(y1+a42*h41*x4)-(a42*y2)/(y2+a42*h42*x4))+s4
F6=y1*(-epsilon1*(1+(y1+omega2*y2)/K11)-(b12*y2)/(y2+b12*h*y1)\
+beta11*(a11*x1)/(y1+a11*h11*x1)\
+beta21*(a21*x2)/(y1+a21*h21*x2)\
+beta31*(a31*x3)/(y1+a31*h31*x3)\
+beta41*(a41*x4)/(y1+a41*h41*x4))
F7=y2*(-epsilon2*(1+(omega1*y1+y2)/K22)+gamma12*(b12*y1)/(y2+b12*h*y1)\
+beta12*(a12*x1)/(y2+a12*h12*x1)\
+beta22*(a22*x2)/(y2+a22*h22*x2)\
+beta32*(a32*x3)/(y2+a32*h32*x3)\
+beta42*(a42*x4)/(y2+a42*h42*x4))
equ=(F2,F3,F4,F5,F6,F7)
sol=nonlinsolve(equ,x1,x2,x3,x4,y1,y2)
print(sol)
Is it possible to get the solution in terms of parameters?
Your system of equations can be recast as multivariate polynomial system if you multiply through by all of the denominators. Doing this for example in the case of F2 you would get
In [26]: F2.as_numer_denom()[0]
Out[26]:
s₁⋅x₁⋅(a₁₁⋅h₁₁⋅x₂ + y₂)⋅(a₁₂⋅h₁₂⋅x₂ + r₁) + x₂⋅(-a₁₁⋅x₁⋅y₂⋅(a₁₂⋅h₁₂⋅x₂ + r₁) - a₁₂⋅r₁⋅x₁⋅(a₁₁⋅h₁₁⋅x₂ + y₂) + r₂⋅(a₁₁⋅h₁₁⋅x₂ + y₂
)⋅(a₁₂⋅h₁₂⋅x₂ + r₁)⋅(-N⋅y₁ - η₂⋅x₂ - η₃⋅x₃ - η₄⋅x₄ + x₁))
We can see from here that the polynomial is of order 5 since it has terms like x2**3*N*y1 so broadly you have a system of 7 polynomials not of low order. I expect that a general closed form solution will not be possible unless you are lucky.
Related
How do programs calculate square roots?
I understand that this is a pretty math-y question, but how do programs get square roots? From what I've read, this is something that is usually native to the cpu of a device, but I need to be able to do it, probably in c++ (although that's irrelevant). The reason I need to know about this specifically is that I have an intranet server and I am getting started with crowdsourcing. For this, I am going to start with finding a lot of digits of a certain square root, like sqrt(17) or something. This is the extent of what python provides is just math.sqrt() I am going to make a client that can work with other identical clients, so I need complete control over the processes of the math. Heck, this question might not even have an answer, but thanks for your help anyway. [edit] I got it working, this is the 'final' product of it: (many thanks to #djhaskin987) def square_root(number): old_guess = 1 guess = 2 guesssquared = 0 while round(guesssquared, 10) != round(number, 10): old_guess = guess guess = ((number / guess) + guess ) / 2 print(guess) guesssquared = guess * guess return guess solution = square_root(7) #finds square root of 7 print(solution)
Computers use a method that people have actually been using since babylonian times: def square_root(number): old_guess = 1 guess = 2 while old_guess != guess: old_guess = guess guess = ((number / guess) + guess ) / 2 return guess
x86 has many sqrt in registry, starting with FSQRT for float. In general, if your function is too complicated or has no implementation, and is C^\infty ("infinitely" differentiable), you can expand it into a polynom via Taylor expansion. This is extremely common in HPC.
Declaring variables in Python 2.7x to avoid issues later
I am new to Python, coming from MATLAB, and long ago from C. I have written a script in MATLAB which simulates sediment transport in rivers as a Markov Process. The code randomly places circles of a random diameter within a rectangular area of a specified dimension. The circles are non-uniform is size, drawn randomly from a specified range of sizes. I do not know how many times I will step through the circle placement operation so I use a while loop to complete the process. In an attempt to be more community oriented, I am translating the MATLAB script to Python. I used the online tool OMPC to get started, and have been working through it manually from the auto-translated version (was not that helpful, which is not surprising). To debug the code as I go, I use the MATLAB generated results to generally compare and contrast against results in Python. It seems clear to me that I have declared variables in a way that introduces problems as calculations proceed in the script. Here are two examples of consistent problems between different instances of code execution. First, the code generated what I think are arrays within arrays because the script is returning results which look like: array([[ True] [False]], dtype=bool) This result was generated for the following code snippet at the overlap_logix operation: CenterCoord_Array = np.asarray(CenterCoordinates) Diameter_Array = np.asarray(Diameter) dist_check = ((CenterCoord_Array[:,0] - x_Center) ** 2 + (CenterCoord_Array[:,1] - y_Center) ** 2) ** 0.5 radius_check = (Diameter_Array / 2) + radius radius_check_update = np.reshape(radius_check,(len(radius_check),1)) radius_overlap = (radius_check_update >= dist_check) # Now actually check the overalp condition. if np.sum([radius_overlap]) == 0: # The new circle does not overlap so proceed. newCircle_Found = 1 debug_value = 2 elif np.sum([radius_overlap]) == 1: # The new circle overlaps with one other circle overlap = np.arange(0,len(radius_overlap), dtype=int) overlap_update = np.reshape(overlap,(len(overlap),1)) overlap_logix = (radius_overlap == 1) idx_true = overlap_update[overlap_logix] radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2) A similar result for the same run was produced for variables: radius_check_update radius_overlap overlap_update Here is the same code snippet for the working MATLAB version (as requested): distcheck = ((Circles.CenterCoordinates(1,:)-x_Center).^2 + (Circles.CenterCoordinates(2,:)-y_Center).^2).^0.5; radius_check = (Circles.Diameter ./ 2) + radius; radius_overlap = (radius_check >= distcheck); % Now actually check the overalp condition. if sum(radius_overlap) == 0 % The new circle does not overlap so proceed. newCircle_Found = 1; debug_value = 2; elseif sum(radius_overlap) == 1 % The new circle overlaps with one other circle temp = 1:size(radius_overlap,2); idx_true = temp(radius_overlap == 1); radius = distcheck(1,idx_true) - (Circles.Diameter(1,idx_true)/2); In the Python version I have created arrays from lists to more easily operate on the contents (the first two lines of the code snippet). The array within array result and creating arrays to access data suggests to me that I have incorrectly declared variable types, but I am not sure. Furthermore, some variables have a size, for example, (2L,) (the numerical dimension will change as circles are placed) where there is no second dimension. This produces obvious problems when I try to use the array in an operation with another array with a size (2L,1L). Because of these problems I started reshaping arrays, and then I stopped because I decided these were hacks because I had declared one, or more than one variable incorrectly. Second, for the same run I encountered the following error: TypeError: 'numpy.ndarray' object is not callable for the operation: radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2) which occurs at the bottom of the above code snippet. I have posted the entire script at the following link because it is probably more useful to execute the script for oneself: https://github.com/smchartrand/MarkovProcess_Bedload I have set-up the code to run with some initial parameter values so decisions do not need to be made; these parameter values produce the expected results in the MATLAB-based script, which look something like this when plotted: So, I seem to specifically be having issues with operations on lines 151-165, depending on the test value np.sum([radius_overlap]) and I think it is because I incorrectly declared variable types, but I am really not sure. I can say with confidence that the Python version and the MATLAB version are consistent in output through the first step of the while loop, and code line 127 which is entering the second step of the while loop. Below this point in the code the above documented issues eventually cause the script to crash. Sometimes the script executes to 15% complete, and sometimes it does not make it to 5% - this is due to the random nature of circle placement. I am preparing the code in the Spyder (Python 2.7) IDE and will share the working code publicly as a part of my research. I would greatly appreciate any help that can be offered to identify my mistakes and misapplications of python coding practice.
I believe I have answered my own question, and maybe it will be of use for someone down the road. The main sources of instruction for me can be found at the following three web pages: Stackoverflow Question 176011 SciPy FAQ SciPy NumPy for Matlab users The third web page was very helpful for me coming from MATLAB. Here is the modified and working python code snippet which relates to the original snippet provided above: dist_check = ((CenterCoordinates[0,:] - x_Center) ** 2 + (CenterCoordinates[1,:] - y_Center) ** 2) ** 0.5 radius_check = (Diameter / 2) + radius radius_overlap = (radius_check >= dist_check) # Now actually check the overalp condition. if np.sum([radius_overlap]) == 0: # The new circle does not overlap so proceed. newCircle_Found = 1 debug_value = 2 elif np.sum([radius_overlap]) == 1: # The new circle overlaps with one other circle overlap = np.arange(0,len(radius_overlap[0]), dtype=int).reshape(1, len(radius_overlap[0])) overlap_logix = (radius_overlap == 1) idx_true = overlap[overlap_logix] radius = dist_check[idx_true] - (Diameter[0,idx_true] / 2) In the end it was clear to me that it was more straightforward for this example to use numpy arrays vs. lists to store results for each iteration of filling the rectangular area. For the corrected code snippet this means I initialized the variables: CenterCoordinates, and Diameter as numpy arrays whereas I initialized them as lists in the posted question. This made a few mathematical operations more straightforward. I was also incorrectly indexing into variables with parentheses () as opposed to the correct method using brackets []. Here is an example of a correction I made which helped the code execute as envisioned: Incorrect: radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2) Correct: radius = dist_check[idx_true] - (Diameter[0,idx_true] / 2) This example also shows that I had issues with array dimensions which I corrected variable by variable. I am still not sure if my working code is the most pythonic or most efficient way to fill a rectangular area in a random fashion, but I have tested it about 100 times with success. The revised and working code can be downloaded here: Working Python Script to Randomly Fill Rectangular Area with Circles Here is an image of a final results for a successful run of the working code: The main lessons for me were (1) numpy arrays are more efficient for repetitive numerical calculations, and (2) dimensionality of arrays which I created were not always what I expected them to be and care must be practiced when establishing arrays. Thanks to those who looked at my question and asked for clarification.
PID controller and transfer function in C++
I have a PID controller working in simulink, but I want to pass it to C++ code. I found how to make a PID with code, something like this: error = input - refeed; iError += error * sampleTime; dError = (error - lastError)/ sampleTime; //PID Function output = Kp * error + Ki * iError + Kd * dError; refeed = output; lastError = error; But, that's the only clear thing I got in my research. I need to know what's the next step, I have the transfer function discretized but I'm not sure about what should I do with the "z" parameters, the times, ... Is it possible to pass manually a PID controller to C++? How?
The Temperature Control Lab passes a PID output from Python to an Arduino that runs C++ code through a serial USB interface. It is easier to plot values with Python than C++ if you can create an interface for your application. GitHub source code is here.
For the digital control systems, you need to sample the data and execute the controller at every sampling time. z-transform converts the continuous system to the discrete system. For exampl, if your sampling time is '1', you can express a simple time-series model as below, y(t) = a1*u(t-1) + a2*u(t-2) --> y(t) = a1*z^-1*u(t) + a2*z^-2*u(t) --> y(t) = A(z)u(t), where A(z) = a1*z^-1 + a2*z^-2 a1, a2 = FIR coefficients However, this time-shift operator 'z^-1' does not appear in your code. It is implicitly expressed with your sampling-time and FOR or DO loop depending on the language that you are using. Please see the python code for velocity form of PID controller. Velocity form is a little bit easier to implement because you don't worry about the additional logic for the anti-reset windup. for i in range(1, ns): #ns = simulation time # PID Velocity form e[i] = sp[i] - pv[i] P[i] = Kc * (e[i] - e[i-1]) I[i] = Kc*delta_t/tauI * (e[i]) D[i] = Kc*tauD/delta_t * (pv[i] - 2*(pv[i-1]) + pv[i-2]) op[i] = op[i-1] + P[i] + I[i] + D[i] if op[i] < oplo or op[i] > ophi: # clip output op[i] = max(oplo,min(ophi,op[i])) You can also find an example of a PID controller using a GEKKO package in the following link. https://apmonitor.com/wiki/index.php/Main/GekkoPythonOptimization
Yes it is possible. Have you considered using someone else's code? Or do you want to write it yourself? If you have no problem using allready written code, check out Github. It has a lot of PID projects. For example PID-controller. It has a usage example and you only have to pass in your p, i and d parameters (which you allready got from Matlab). Good luck!
Basically, you should send the values somewhere. Reading through the comments, you want to make a plot of the output variable in time, so I guess your best bet (and easier way) is to use gnuplot. Basically, output the data in a text file, then use gnuplot to display it.
Sin pi : give wrong result [duplicate]
This question already has answers here: floating point in python gives a wrong answer [duplicate] (3 answers) why am I getting an error using math.sin(math.pi) in python? (1 answer) Closed 5 years ago. i tried to create polar array with math module ; but math.sin(math.pi) always give wrong result. with python 2.7 or 3.5 the same wrong result : import math m = math.radians(180) print (math.sin(m)) pi = math.pi print (pi) print (math.sin(pi)) 1.2246467991473532e-16 3.141592653589793 1.2246467991473532e-16 this is my code and the same error: import math a = 180 #(degree) r = 10 n = 8 b = float(a)/n pi = math.radians(180) print math.sin(pi) for i in range(0,2*n+1): print i c1 = b*i print c1 c2 = c1*math.pi/a #c : radians print c2 sinb = math.sin(c2) cosb = math.cos(c2) x = r*sinb y = r*cosb #print (x, y) the threads mentioned in the comment give explanation not a solution ; so i don't need explanation how and why without solution to solve my problem and the answer from cody give me the solution. if you think that the other threads show the answer mention in these threads that are duplicate.
Since pi is an irrational number and goes on forever, the Python version is not actually exact pi. As a result, the sin of almost-pi is almost-0. Basically you can chalk it up to a Python rounding error. Here's some more information on the topic in general: Floating Point Arithmetic: Issues and Limitations why am I getting an error using math.sin(math.pi) in python? I suggest you put some rounding in to the nearest N units that will suffice for your module. The numerical value of what you got is 0.000000000000000122. Five digits after the decimal should be good for almost anything you could need the module for.
OverflowError in a for loop
I'm working on problem 3 of Project Euler using Python, but I can't seem to solve the problem without running into the following error: "OverflowError: range() result has too many items" I'm wondering if there's a way to increase the allowed range? My code looks as follows: target = 600851475143 largest_prime_factor = 1 #find largest prime factor of target for possible_factor in range(2,(target/2)+1): if target % possible_factor == 0: is_prime = True for i in range(2,(possible_factor/2)+1): if possible_factor % i == 0: is_prime = False break if is_prime: largest_prime_factor = possible_factor print largest_prime_factor
If you run into limitations of your computer or language while trying to solve a puzzle problem, or if it takes too long, it is an indication that probably there exists a better way (read: algorithm) to solve the problem. In your case, you do not need to loop to target / 2 + 1 (though that is a good educated upper bound). You only need to go as far as ceil(sqrt(target)). And, as a sidenote, you can overcome this limitation by using xrange, which will create a generator, instead of range for Python 2, which creates a list. In Python 3, range will return a sequence type instead of a list by default. Thanks to #Fernando for the clarification in the comments.