what do variables after options in fmincon stand for? - python

I looked for the definition of fmincon in Matworkds and tried to convert my fmincon matlab function to a similar python function using from scipy.optimize import least_squares
As it's mentioned in the optimset function, my python solver will need the Levenberg Marquardt algorithm. Then I guess last_squares is the right choice.
Although, as it's mentioned in the optimset function, my python solver will need the Levenberg Marquardt algorithm. Then I guess last_squares is the right choice.
function [alpha,beta,lambda,gamma,c,fX,yhat,ehat,G]=parestlm(y,X,W,q,T,nX,nW,m,gamma,c)
% Compute starting values
% -----------------------
[alpha,beta,lambda,gamma,c] = startval(y,X,W,q,m,gamma,c);
PSI = setpar(gamma,c);
options = optimset('Display','off','Jacobian','on','MaxFunEvals',1e10,...
'LargeScale','off','MaxIter',4000,'TolFun',1e-10,...
'DerivativeCheck','off','LevenbergMarquardt','on',...
'LineSearchType','cubicpoly','TolX',1e-10,'TolCon',1e-10);
PSI = fmincon('msecost',PSI,[],[],[],[],...
[zeros(m,1);ones(m,1)*prctile(q,10)],...
[inf(m,1);ones(m,1)*prctile(q,90)],[],options,...
y,X,W,q,m);
From fmincon, i got the fun,X0,lb,ub ,the nonlcon and the options, my question is :
What do y,X,W,q,m stand for in this current code and what place it'll take in the future python function ?

Related

Tell Python that two sympy symbols are related by a complex conjugate

My Problem
I am using Sympy v. 1.11.1 on (Jupyter Notebook) Python v. 3.8.5. I am dealing with a large Hessian, where terms such as these appear:
Pi+ and Pi- are complex Sympy symbols. However, one is the complex conjugate of the other, that is conjugate(Pi+) = Pi- and vice versa. This means that the product Pi+ * Pi- is real and the derivatives can be easily evaluated by removing the Re/Im (in one case Re(Pi+ * Pi-) = Pi+ * Pi-, in the other Im(Pi+ * Pi-) = 0).
My Question
Is it possible to tell Sympy that Pi+ and Pi- are related by a complex conjugate, and it can therefore simplify the derivatives as explained above? Or does there exist some other way to simplify my derivatives?
My Attempts
Optimally, I would like to find a way to express the above relation between Pi+ and Pi- to Python, such that it can make simplifications where needed throughout the code.
Initially I wanted to use Sympy global assumptions and try to set an assumption that (Pi+ * Pi-) is real. However, when I try to use global assumptions it says name 'global_assumptions' is not defined and when I try to explicitly import it (instead of import *), it says cannot import name 'global_assumptions' from 'sympy.assumptions' I could not figure out the root of this problem.
My next attempt was to replace all instances of Re(Pi+ * Pi-) -> Pi+ * Pi- etc. manually with the Sympy function subs. The code replaced these instances successfully, but never evaluated the derivatives, so I got stuck with these instead:
Please let me know if any clarification is needed.
I found a similar question Setting Assumptions on Variables in Sympy Relative to Other Variables and it seems from the discussion there that there does not exist an efficient way to do this. However, seeing that this was asked back in 2013, and the discussions pointed towards the possibility of implementation of a new improved assumption system within Sympy in the near future, it would be nice to know if any new such useful methods exist.
Given one and the other, try replacing one with conjugate(other):
>>> one = x; other = y
>>> p = one*other; q = p.subs(one, conjugate(other); im(q),re(q)
(Abs(y)**2, 0)
If you want to get back the original symbol after the simplifications wrought by the first replacement, follow up with a second replacement:
>>> p.sub(one, conjugate(other)).subs(conjugate(other), one)
x*y

Can I pass additional arguments into a scipy bvp function or boundary conditions? / SciPy questions from MATLAB

I'm working on converting a code that solves a BVP (Boundary Value Problem) from MATLAB to Python (SciPy). However, I'm having a little bit of trouble. I wanted to pass a few arguments into the function and the boundary conditions; so in MATLAB, it's something like:
solution = bvp4c(#(x,y)fun(x,y,args),#(ya,yb)boundarycond(ya,yb,arg1,args),solinit);
Where arg1 is a value, and args is a structure or a class instance. So I've been trying to do this on scipy, and the closest I get to is something like:
solBVP = solve_bvp(func(x,y,args), boundC(x,y,arg1,args), x, y)
But then it errors out saying that y is not defined (which it isn't, because it's the vector of first order DEs).
Has anyone tried to pass additional arguments into solve_bvp? If so, how did you manage to do it? I have a workaround right now essentially putting args and arg1 as global variables, but that seems incredibly sketchy if I want to make this code somewhat modular.
Thank you!

How to define function from input string in python at runtime?

I was trying to solve UVA 11036. It requires defining function at runtime.
For Example: I have to take input (2*x + 7) % N as a string and define a function at runtime like func = lambda x : (2*x + 7) % N to work on it. Please help me to find out how to convert string to function at runtime.
You could use exec to define a function from a string. However that allows to inject any code into your program. But as it's only for solving that challenge, it might be fine.
exec 'func = lambda x : '+input
It seems captivating riddle, so if you want to solve it in C++ have two way. The hard way is implementing a small math parser using some algorithms like Shunting-yard algorithm. Or instead of, if you are familiar with library linking in C++, it is better to use a mathematical expression parser libraries. There are many libraries on Internet. Here, I suggest one of them as below.
mathematical expression library I personalty have tested it and obviously is fast. you can clone source code in GitHub
Anyway, you can not solve this case with lambda functions because, the input is a mathematical expression you should parse and calculate it runtime.
if you use python see this post.

Matlab mynorm function

I am trying to convert a code from Matlab to Python in which I came across a function named mynorm(x,y) in Matlab which I want to convert to Python. I searched equivalent for this function in Python but was not successful. So tried to find the implementation of this function on the net and found a small mynorm.m file which contains the function with just one-liner code which is as follows:
function L = mynorm(x,y)
%length of the vector [x,y]
L = sqrt(x^2 + y^2);
%note - if the input was a vector v, a better way to do this would be
%L = sqrt(dot(v,v))
%see help dot for the dot product. This would work for vectors of any size.
But when I looked into the call which is made to this function in matlab file, it is as follows:
feaNorm = mynorm(fea2, 1)
feaNorm = mynorm(iris(:,1:4),2);
which doesn't really look like length function as in the above implementation.
Thus, I am skeptical to use sqrt function in Python for this function call.
Can someone redirect me to the correct implementation or the equivalent python code?
I suggest you use the hypot trigonometric function available in the math module. You will find a description of the math module here.

Defining a global function in a Python script

I'm new to Python. I am writing a script that will numerically integrate a set of ordinary differential equations using a Runge-Kutta method. Since the Runge-Kutta method is a useful mathematical algorithm, I've put it in its own .py file, rk4.py.
def rk4(x,dt):
k1=diff(x)*dt
k2=diff(x+k1/2)*dt
k3=diff(x+k2/2)*dt
k4=diff(x+k3)*dt
return x+(k1+2*k2+2*k3+k4)/6
The method needs to know the set of equations that the user is working with in order to perform the algorithm, so it calls a function diff(x) that will find give rk4 the derivatives it needs to work. Since the equations will change by use, I want diff() to be defined in the script that will run the particular problem. In this case the problem is the orbit of mercury, so I wrote mercury.py. (This isn't how it will look in the end, but I've simplified it for the sake of figuring out what I'm doing.)
from rk4 import rk4
import numpy as np
def diff(x):
return x
def mercury(u0,phi0,dphi):
x=np.array([u0,phi0])
dt=2
x=rk4(x,dt)
return x
mercury(1,1,2)
When I run mercury.py, I get an error:
File "PATH/mercury.py", line 10, in mercury
x=rk4(x,dt)
File "PATH/rk4.py", line 2, in rk4
k1=diff(x)*dt
NameError: global name 'diff' is not defined
I take it since diff() is not a global function, when rk4 runs it knows nothing about diff. Obviously rk4 is a small piece of code and I could just shove it into whatever script I'm using at the time, but I think a Runge-Kutta integrator is a fundamental mathematical tool, just like the array defined in NumPy, and so it makes sense to make it a function that is called rather one that is defined in every script that uses it (which may be many). But I also can't go telling rk4.py to import a particular diff from a particular .py file, because that ruins the generality of rk4 that I want in the first place.
Is there a way to define diff globally within a script like mercury.py so that when rk4 is called, it will know about diff?
Accept the function as an argument:
def rk4(diff, # accept an argument of the function to call
x, dt)
k1=diff(x)*dt
k2=diff(x+k1/2)*dt
k3=diff(x+k2/2)*dt
k4=diff(x+k3)*dt
return x+(k1+2*k2+2*k3+k4)/6
Then, when you call rk4, simply pass in the function to be executed:
from rk4 import rk4
import numpy as np
def diff(x):
return x
def mercury(u0,phi0,dphi):
x=np.array([u0,phi0])
dt=2
x=rk4(diff, # here we send the function to rk4
x, dt)
return x
mercury(1,1,2)
It might be a good idea for mercury to accept diff as an argument too, rather than getting it from the closure (the surrounding code). You then have to pass it in as usual - your call to mercury in the last line would read mercury(diff, 1, 1, 2).
Functions are 'first-class citizens' in Python (as is nearly everything, including classes and modules), in the sense that they can be used as arguments, be held in lists, be assigned to names in namespaces, etc etc.
diff is already a global in the module mercury.py. But in order to use it in rk4.py you would need to import it like this:
from mercury import diff
That's the direct answer to your question.
However, passing the diff function to rk4 as suggested by #poorsod is much more elegant and also avoids a circular dependency between mercury.py and rk4.py, so I suggest you do it that way.

Categories