Skip to content

CallingR

Baptiste Lesquoy edited this page May 8, 2022 · 15 revisions

Calling R from GAMA models

Introduction

The R language is a powerful tool for statistical computing and graphics, and its community is very large in the world (See the website). Adding a support for the R language is one of our strong endeavors to accelerate many statistical and data mining tools integration into the GAMA platform.

Table of contents

Configuration in GAMA

  1. Install R on your computer: please refer to the R official website, or to RStudio if you want in addition a nice IDE.

  2. Before running this model, you should install the rJava library in R. In the R (RStudio) console, write: install.packages("rJava") to install the library. To check that the install is correct, you load the library using library(rJava) (in the R console). If no error message appears, it means the installation is correct.

  3. In case of trouble:

    • On MacOSX, in recent versions you should first write in a terminal:
    R CMD javareconf
    sudo ln -f -s $(/usr/libexec/java_home)/jre/lib/server/libjvm.dylib /usr/local/lib
    
    • For linux, make sure you have the default-jdk and default-jre packages installed and then execute the command sudo R CMD javareconf
  4. You need to Configure the Environment Variable R_HOME (the procedure depends on your OS).

    • On Windows,
    • On Linux, by default it should be /usr/lib/R, you can thus just append the line R_HOME=/usr/lib/R to your /etc/environment file and reboot your computer
    • On macOS, you need to create (or update) the file environment.plist in the folder: ~/Library/LaunchAgents/ (for the current user, note that this folder is a hidden folder) or in /Library/LaunchAgents/ (for all users) It should look like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>my.startup</string>
    <key>ProgramArguments</key>
    <array>
      <string>sh</string>
      <string>-c</string>
      <string> launchctl setenv R_HOME /Library/Frameworks/R.framework/Resources/ </string>
    </array>
    <key>RunAtLoad</key>
    <true/>
  </dict>
</plist>
  1. From GAMA 1.8.2, you need to specify the path to the R connector library in the GAMA launching arguments. To this purpose, you need to add to either (1) the GAMA.ini file if you use the release version of GAMA, or (2) the launching configuration (if you use the source code version) the following line: (replace PATH_TO_R by the path to R, i.e. the value in $R_HOME):
    • on macOS: -Djava.library.path=PATH_TO_R/library/rJava/jri/rlibjri.jnilib
    • on Windows: -Djava.library.path=PATH_TO_R/library/rJava/jri/jri.dll
    • on Linux: -Djava.library.path=PATH_TO_R/library/rJava/jri/

As an example, under macOS, you need to add:

-Djava.library.path=/Library/Frameworks/R.framework/Resources/library/rJava/jri/

Calling R from GAML

Before computation

Any agent aiming at using R for some computation needs to be provided with the RSkill.

Before calling any computation, this agent needs to start a connection with the R software.

As an example, if we want that the global agent can use R, we need to have the following minimal model:

global skills: [RSkill] {
   init {
      do startR;
   }
}

Computation

Evaluate an R expression

The R_eval operator can be used to evaluate any R expression. It can also be used to initialize a variable or call any function. It can return any data type (depending on the R output). As in an R session, the various evaluations are dependent on the previous ones.

Example:

global skills: [RSkill] {
	
	init{
		do startR;
		
		write R_eval("x<-1");
		write R_eval("rnorm(50,0,5)");
	}

}

Evaluate an R script

To evaluate an R script, stored in a (text) file, open the file and execute each of its lines.

global skills:[RSkill]{
	file Rcode <- text_file("../includes/rScript.txt");
		init{
		do startR;
		// Loop that takes each line of the R script and execute it.
	 	loop s over: Rcode.contents{
			unknown a <- R_eval(s);
			write "R>"+s;
			write a;
		}
	}
}

Convert GAMA object to R object

To use GAMA complex objects into R functions, we need to transform them using the to_R_data operator: it transforms any GAMA object into a R object.

global skills:[RSkill] {
	init {
		do startR();
		
		string s2 <- "s2";
		list<int> numlist <- [1,2,3,4]; 
  		write R_eval("numlist = " + to_R_data(numlist));
	}
}

Convert a species to a dataframe

Dataframe is a powerful R data type allowing to ease data manipulation... Dataframe wan of course be defined at hand using R commands. But GAML provides the to_R_dataframe operator to directly transform a species of agents into a dataframe for future analysis.

global skills: [RSkill] {
	
	init{
		do startR();
		
		create people number: 10;
		
		do R_eval("df<-" + to_R_dataframe(people));
		write R_eval("df");
		write R_eval("df$flipCoin");	
	}
}
species people {
	bool flipCoin <- flip(0.5);
}
  1. What's new (Changelog)
  1. Installation and Launching
    1. Installation
    2. Launching GAMA
    3. Updating GAMA
    4. Installing Plugins
  2. Workspace, Projects and Models
    1. Navigating in the Workspace
    2. Changing Workspace
    3. Importing Models
  3. Editing Models
    1. GAML Editor (Generalities)
    2. GAML Editor Tools
    3. Validation of Models
  4. Running Experiments
    1. Launching Experiments
    2. Experiments User interface
    3. Controls of experiments
    4. Parameters view
    5. Inspectors and monitors
    6. Displays
    7. Batch Specific UI
    8. Errors View
  5. Running Headless
    1. Headless Batch
    2. Headless Server
    3. Headless Legacy
  6. Preferences
  7. Troubleshooting
  1. Introduction
    1. Start with GAML
    2. Organization of a Model
    3. Basic programming concepts in GAML
  2. Manipulate basic Species
  3. Global Species
    1. Regular Species
    2. Defining Actions and Behaviors
    3. Interaction between Agents
    4. Attaching Skills
    5. Inheritance
  4. Defining Advanced Species
    1. Grid Species
    2. Graph Species
    3. Mirror Species
    4. Multi-Level Architecture
  5. Defining GUI Experiment
    1. Defining Parameters
    2. Defining Displays Generalities
    3. Defining 3D Displays
    4. Defining Charts
    5. Defining Monitors and Inspectors
    6. Defining Export files
    7. Defining User Interaction
  6. Exploring Models
    1. Run Several Simulations
    2. Batch Experiments
    3. Exploration Methods
  7. Optimizing Model Section
    1. Runtime Concepts
    2. Optimizing Models
  8. Multi-Paradigm Modeling
    1. Control Architecture
    2. Defining Differential Equations
  1. Manipulate OSM Data
  2. Diffusion
  3. Using Database
  4. Using FIPA ACL
  5. Using BDI with BEN
  6. Using Driving Skill
  7. Manipulate dates
  8. Manipulate lights
  9. Using comodel
  10. Save and restore Simulations
  11. Using network
  12. Headless mode
  13. Using Headless
  14. Writing Unit Tests
  15. Ensure model's reproducibility
  16. Going further with extensions
    1. Calling R
    2. Using Graphical Editor
    3. Using Git from GAMA
  1. Built-in Species
  2. Built-in Skills
  3. Built-in Architecture
  4. Statements
  5. Data Type
  6. File Type
  7. Expressions
    1. Literals
    2. Units and Constants
    3. Pseudo Variables
    4. Variables And Attributes
    5. Operators [A-A]
    6. Operators [B-C]
    7. Operators [D-H]
    8. Operators [I-M]
    9. Operators [N-R]
    10. Operators [S-Z]
  8. Exhaustive list of GAMA Keywords
  1. Installing the GIT version
  2. Developing Extensions
    1. Developing Plugins
    2. Developing Skills
    3. Developing Statements
    4. Developing Operators
    5. Developing Types
    6. Developing Species
    7. Developing Control Architectures
    8. Index of annotations
  3. Introduction to GAMA Java API
    1. Architecture of GAMA
    2. IScope
  4. Using GAMA flags
  5. Creating a release of GAMA
  6. Documentation generation

  1. Predator Prey
  2. Road Traffic
  3. 3D Tutorial
  4. Incremental Model
  5. Luneray's flu
  6. BDI Agents

  1. Team
  2. Projects using GAMA
  3. Scientific References
  4. Training Sessions

Resources

  1. Videos
  2. Conferences
  3. Code Examples
  4. Pedagogical materials
Clone this wiki locally