I have a mathematical optimization algorithm in Python and each time I have to evaluate the function value I have to call an R script where there is written a simulation code (simulation-based optimization).
Before trying to link these two codes I would like to understand how to link something easier.
Let's imagine I have this little R script :
x <- c(1,2,3,4,5,6)
y <- c(2,3,4,54)
x1 <- mean(x)
y1 <- mean(y)
z <- x1 + y1
print(z)
I want to call it from Spyder ( Anaconda) in order to have z showed on my console.
I have read about the rpy2 library but as I have understood (correct me if I am wrong), I should write the equivalent R code in Python.
Does anyone know about an easier way to do that? ( I am not able to code really well in R, therefore, I won't be able to translate the simulation code that I have).
If necessary, R is installed on a Windows environment, as Anaconda.
Thank you in advance!
After trying couple of other options, subprocess seemed to work sufficiently well. You can run an R script from Python via subprocess and provide a function value as an argument (x):
def R_script_runner(x):
import subprocess
output=subprocess.run(
["your_path_to_R_source_folder/Rscript.exe", "your_path_to_R_script/R_script.R", x],
shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).stderr
return output
The R script will do what it is supposed to do. The output is being returned by the function mainly for debugging purposes so you can print it or evaluate otherwise..
Related
I have created a jl file having the following content:
for i in 1:10
println(i)
end
1+2
When I am calling that jl file in python using the following code:
import julia
from julia.api import Julia
j = julia.Julia(compiled_modules=False)
x = j.include("experiment.jl")
only x is being printed as 3. No integers(i) from 1-10 are not being printed.
I am getting following warning:
/opt/conda/lib/python3.7/site-packages/julia/core.py:689: FutureWarning: Accessing `Julia().<name>` to obtain Julia objects is deprecated. Use `from julia import Main; Main.<name>` or `jl = Julia(); jl.eval('<name>')`.
Your julia program is running just fine. As you can see you get the right result from your julia script. And also your loop is running, it is just not printed to the same output stream as the one from python (that is why you don't see it). Here is a discussion how to print to the same output as python's. But I would not bother to much about it, to test if your loop actually runs try something like that:
z = 0
for i in 1:10
z = z + i
end
z + 1
I am trying to define a splunk dashboard equivalent to this code in python
from scipy import stats
stats.beta.cdf(x, T, F) - stats.beta.cdf(y, T, F)
Where x and y are splunk expressions (defined with splunk's eval).
I saw a lot of complex stuff (classifiers, anomaly detection, etc...) when looking at the splunk docs, but I couldn't find any reference to known distribution functions such as Beta and Gamma.
Could someone refer me to any statistics package for splunk ?
I discovered the | script directive in splunk.
Now, This is the python code I wrote, and it runs directly from splunk
from scipy import stats
import splunk.Intersplunk
src_cols = ["s1","s2"]
new_cols = ["n1"]
print (",".join(src_cols+new_cols))
for row in splunk.Intersplunk.readResults():
output = map(lambda c: row[c], src_cols)
output += [stats.beta.cdf(row["s1"],0, 1) - row["s2"],0, 1)]
print (",".join(output))
I would really appreciate some help with running code written in Python 3 from Matlab.
My Python code loads various libraries and uses them to perform numerical integration of a differential equation (for the numpy vector: e_array ).
The Python code which I would like to call from Matlab is the following:
from numba import jit
from scipy.integrate import quad
import numpy as np
#jit(nopython = True)
def integrand1(x,e,delta,r):
return (-2*np.sqrt(e*r)/np.pi)*(x/np.sqrt(1-x**2))/(1+(delta+2*x*np.sqrt(e*r))**2)
#jit(nopython = True)
def f1(e,delta,r):
return quad(integrand1, -1, 1, args=(e,delta,r))[0]
#jit(nopython = True)
def runge1(e,dtau,delta,r):
k1 = f1(e,delta,r)
k2 = f1((e+k1*dtau/2),delta,r)
k3 = f1((e+k2*dtau/2),delta,r)
k4 = f1((e+k3*dtau),delta,r)
return e + (dtau/6)*(k1+2*k2+2*k3+k4)
time_steps = 60
e = 10
dtau=1
r=1
delta=-1
e_array = np.zeros(time_steps)
time = np.zeros(time_steps)
for i in range(time_steps):
e_array[i] = e
time[i] = i*dtau
e = runge1(e,dtau,delta,r)
Ideally, I would like to be able to call this Python code (pythoncode.py) in Matlab as if it were a Matlab function and feed it the parameters: time_steps, e, dtau, r and delta. I would be very happy with a solution which looks like this:
e_array = pythoncode.py(time_steps = 60, e = 10, dtau = 1, r = 1, delta = -1)
where pythoncode.py is treated as a Matlab function which takes said parameters, feeds them into the Python code and returns the Matlab vector e_array.
I want to point out that there are several additional Python codes that I'd like to be able to call from Matlab and I'm hope to get an idea of how to do this from your answers regarding this specific Python code.
A related question involves the Python libraries which I use in the Python code: Is there a way to "compile" the Python code such that I can call it in Matlab without installing the libraries it uses (f.e the numba library) on the computer running the Matlab code?
Thanks very much for helping,
Asaf
You'll probably need to shell escape out of Matlab to invoke python -- prefix the command you'd run on the shell with !.
Matlab Shell Escape Functions suggests saving a mat file and then opening it in your python code -- see Read .mat files in Python .
In terms of compiling the python, you could take a look at How to compile a Python file and see if that helps you.
I'm a student working on an extra-curricular coding project and I have a Chromebook. I'm writing a Python programme which requires basic integration and I haven't been able to find any file that my chromebook will run which will let me do that. Does anyone know anything about that?
Thanks
JL
You're looking for something like sympy. Documentation for sympy's symbolic integrals is available here.
from sympy import *
x = Symbol('x')
integrate(x**2 + x + 1, x)
should result in:
3 2
x x
-- + -- + x
3 2
So I recently decided to learn python and as a exercise (plus making something useful) I decided to make a Euler's Modified Method algorithm for solving higher-then-first order differential equations. An example input would be:
python script_name.py -y[0] [10,0]
where the first argument is the deferential equation (here: y''=-y), and the second one the initial conditions (here: y(0)=10, y'(0)=0). It is then meant to out put the resusts to two files (x-data.txt, and y-data.txt).
Heres the problem:
When in run the code with the specified the final line (at t=1) reads -0.0, but if you solve the ODE (y=10*cos(x)), it should read 5.4. Even if you go through the program with a pen and paper and execute the code, your (and the computers) results apart to diverge by the second iteration). Any idea what could have caused this?
NB: I'm using python 2.7 on a os x
Here's my code:
#! /usr/bin/python
# A higher order differential equation solver using Euler's Modified Method
import math
import sys
step_size = 0.01
x=0
x_max=1
def derivative(x, y):
d = eval(sys.argv[1])
return d
y=eval(sys.argv[2])
order = len(y)
y_derivative=y
xfile = open('x-data.txt','w+')
yfile = open('y-data.txt','w+')
while (x<x_max):
xfile.write(str(x)+"\n")
yfile.write(str(y[0])+"\n")
for i in range(order-1):
y_derivative[i]=y[(i+1)]
y_derivative[(order-1)] = derivative(x,y)
for i in range(order):
y[i]=y[i]+step_size*y_derivative[i]
x=x+step_size
xfile.close()
yfile.close()
print('done')
When you say y_derivative=y they are the SAME list with different names. I.e. when you change y_derivative[i]=y[i+1] both lists are changing. You want to use y_derivative=y[:] to make a copy of y to put in y_derivative
See How to clone or copy a list? for more info
Also see http://effbot.org/zone/python-list.htm
Note, I was able to debug this in IDLE by replacing sys.argv with your provided example. Then if you turn on the debugger and step through the code, you can see both lists change.