Matlab mynorm function - python

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.

Related

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.

what do variables after options in fmincon stand for?

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 ?

Simplifying exponential representation of hyperbolic functions in sympy

I am trying to rewrite some exponential functions in an expression to cosh and sinh. The rewrite() function works to get from a hyperbolic function to its exponential representation. But it does not work to get back.
>>> import sympy
>>> x=sympy.Symbol('x')
>>> sympy.cosh(x).rewrite(sympy.exp)
exp(x)/2 + exp(-x)/2
>>> sympy.cosh(x).rewrite(sympy.exp).rewrite(sympy.cosh)
exp(x)/2 + exp(-x)/2
I would expect the result of the last command to be 'cosh(x)'. Can someone explain to me why it is not?
I tried to find some documentation on the rewrite() function but the only bit I found was the short section in http://docs.sympy.org/latest/tutorial/simplification.html that is not really helpful.
Applying .rewrite(sympy.cos) returns cosh(x) as you wanted. Apparently, the hyperbolic cosine is treated by rewrite as a variant of the normal one.
Here is a reference on rewrite method.
Alternatively, simplify(expr) also transforms exp(x)/2 + exp(-x)/2 into cosh(x).

theano.function - how does it work?

I've read the official documenation and read the comments here https://github.com/Theano/theano/blob/ddfd7d239a1e656cee850cdbc548da63f349c37d/theano/compile/function.py#L74-L324, and one man told me that it tells Theano to compile the symbolic computation graph into an actual program that you can run.
However, I still cannot figure out how does it know, for example in this code:
self.update_fun = theano.function(
inputs=[self.input_mat, self.output_mat],
outputs=self.cost,
updates=updates,
allow_input_downcast=True)
how to compute all that, if it has no body? I mean all those things are computed in some code above these pasted lines, but... is theano.function actually looking to source code to find out how to compute those things? I'm just guessing and would really like to know how it works.
Maybe the problem I have in the explanation that "it tells Theano to compile the symbolic computation graph into an actual program" is that I have no clue what symbolic computation graph is, so that would be another question very related to the previous.
Explanation would be appreciated.
I'm no expert but here's my take at explaining it:
Yes the 'body' is defined in the code above. But theano doesn't 'interpret' that code directly like the python interpreter would. The code in question is just creating theano objects that will allow theano to compile the desired function. Let's take a simple example: how you would create a function f(x) = 2x + x**3.
You first create a symbolic input variable x. Then you define the 'body' of the function by building the symbolic expression of f(x):
y = 2 * x + x**3 # defines a new symbolic variable which depends on x
This y object is equivalent to a graph representing the formula. Something like Plus(Times(2,x), Power(x,3)).
You finally call theano.function with input=x and output=y. Then theano does its magic and compiles the actual function f(x) = y = 2 * x + x**3 from the information (the graph) 'contained' in y.
Does it make things clearer?

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