2

I want to do Optimization in R of a function writen in Python. I already know that scipy has optimization functions, but I want some functions that are in R but not in scipy. The problem is that I have my function in a Python script, this function needs some other information apart of the parameters to fit. So at Initalization the python script import some files and do some operations, thats why I don't want to call each time the script because that would lower the performance.

For doing that I tryed to call once the python script and then connect to it with a socket. This is my R script (It doesn't include the optimization yet):

#Variables to initialize:

p_pos = '"[[0.,0.,True],[1.2378958026, 0,True],[0, 0.7152889725,True]]"'
names = '"[\'bridge\',\'hollow\',\'top\']"'
potential = "a-a"
symmetry = "non"



#Initialize python script

command = "python"
path2script='"Least_squares_potentials.py"'

#data pased to python

string = paste(p_pos, names, potential, symmetry, sep="---")
pattern = "---"

args = c(string, pattern)


# Add path to script as first arg


allArgs = c(path2script, args)

#Initialize

output = system2(command, args=allArgs, stdout=FALSE, wait=FALSE)

Sys.sleep(5)


client <- function(param){
   while(TRUE){
    con <- socketConnection(host="localhost", port = 6011, blocking=TRUE,
                        server=FALSE, open="r+")
    response <- param  
    writeLines(response, con)
    data <- readLines(con, 1)
    print(data)
    close(con)
  }
}


#guess = "[3.589,3.995,1.418,1.809]"
guess = "[3.733,2.413,8]"

client(guess)
client("q")

And in my python side:

# Get the arguments passed in

string = sys.argv[1]
pattern = sys.argv[2]

# Perform the splitting

ans = string.split(pattern)
p_pos = ast.literal_eval(ans[0])
names = ast.literal_eval(ans[1])
potential = ans[2]
symm = ans[3]

#Initialize the potential (this is my function, which is actually a class)

Least = Least_squares(names, p_pos, potential, symm)

#----------------------------------------------------------#
#INITIALIZE SOCKET
#----------------------------------------------------------#

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 6011))
s.listen(1)
while 1:
    (conn, addr) = s.accept()
    data = conn.recv(1024)
    if ( data == 'q' or data == 'Q'):
        conn.close()
        break;
    else:        
        conn.send(Least.xi_square(np.array(ast.literal_eval(data))))

Doing this I get nothing... well I get "\xadȊ\xf3=\xd0Y@" and I don't know what is this, after waiting severlal minutes. So can anyone help me out with this?. Maybe there is another way of doing this I don't know. Any help will be really appreciated.

Kilian A.G.
  • 123
  • 1
  • 6
  • 1
    If you are looking to call python from R have you considered [rPython](https://cran.r-project.org/web/packages/rPython/index.html) – cdeterman Sep 27 '16 at 16:30

0 Answers0