5

I need to call a R script from AnyLogic. I have an agent 'sensor' and it is going to send a random file from a specific location to a R script and then the R script will analyze that file and will let us know type of that file (image, sound, text etc)

Please let me know how to call a R script from AnyLogic..

Dylan Knowles
  • 2,726
  • 1
  • 26
  • 52
user2543622
  • 5,760
  • 25
  • 91
  • 159
  • 1
    I would say most of us do not know what anylogic is. Can you run system commands from anylogic? if so, you could run the rscript that way. otherwise, this would be better posed on an anylogic forum or to their support service – rawr Jul 03 '14 at 17:08

3 Answers3

3

i'm not sure there is an direct adapter for AnyLogic and R,but all agents in AnyLogic are Java objects so you can call external java (.jar) programs. JRI is a Java/R interface http://rforge.net/JRI/ you can write your R script within JRI then call from AnyLogic

tyavuz
  • 46
  • 4
2

Rcaller is another route. Pretty simple and still active development: https://code.google.com/p/rcaller/

0

Resurrecting an old question because neither of the above solutions were what I was after. An alternative that doesn't require external interfaces is to use system commands as rawr suggested. This can be done with something like the following. First, create a java class in AnyLogic with the following code (modified from this guide)

import java.io.*; 
public class SystemUtil {
    public static Process executeCommands(String commands, String directory, String errorFile) {
        Process process = null;
        
        boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
        
        ProcessBuilder pb;
        if(isWindows) {
            pb = new ProcessBuilder("cmd.exe","/c",commands);
        } else {
            pb = new ProcessBuilder("/bin/sh","-c",commands);
        }
         
        pb.directory(new File(directory)); //Set current directory
        pb.redirectError(new File(errorFile)); //Log errors in specified log file.
        try {
            process = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return process;
    }
}

With that done, you should be able to invoke any system command you want, including Rscript, using the newly defined class. As a toy example, if you place this code into a button you'll create a CSV file containing a 3x3 diagonal matrix. Replace the command with the appropriate Rscript call for your script.

String command = "Rscript -e write.csv(diag(3),file='out.csv')";
String dir = System.getProperty("user.dir");
String log = String.format("%s/log.txt",dir);

SystemUtil.executeCommands(command,dir,log);

HJohns
  • 1