My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
UsingRFortran  
Provides a references for the RFortran functionality
Featured
Updated May 13, 2010 by mark.th...@gmail.com

Core Functionality


Rinit

Description

Initialises R ready to transfer commands to and data to/from R and Fortran

Syntax

Rinit([Rfortran_ScriptPathIn],[wait4RIn],[RGuiPathIn],[workingDirIn],[log_file],[log_append],[log_echo],[RgraphicsDevTypeIn],[GraphicsDev_name],[GraphicsDev_cmd])

Arguments

Name Type Description
Rfortran_ScriptPathIn character(*) Path to R scripts used by RFortran, overrides default: %RFORTRAN_PATH%\Rscripts
wait4RIn integer(mik) Milliseconds Rfortran waits after R auto-opens, overrides default wait4RDef set by RFortran.set
RGuiPathIn character Path to Rgui.exe, overrides default RguiPathDef set by RFortran.set
workingDirIn character(*) Sets R working directory, overrides default of the current directory of the executable
rGuiVisibleIn logical if TRUE (default): Rgui is "visible" (foreground), if FALSE: Rgui is "invisible" (background). Note if Rgui is "visible" other Fortran executables will use the same Rgui instance (with potential for conflicts), if Rgui is "invisible" each Fortran executable will use a different R instance (avoiding conflicts)
log_file character Sets name of log file used for message logging
log_append logical Sets whether to append RFortran messages to an existing log file - useful if calling routine has its own log file
log_echo logical Sets whether to echo log messages to the screen during console output
RgraphicsDevTypeIn integer(mik) If present R will open a new graphics device of this type, current options are: RgraphicsDevTypeIn=WINDOW - opens a graphics window, RgraphicsDevTypeIn=PDF - opens a pdf file, RgraphicsDevTypeIn=PS - opens a postscript file
GraphicsDev_name character Name of graphics device - usage depends on graphics device type: WINDOW - name of graphics window, PDF\PS - full pathname of file (including extension)
GraphicsDev_cmd character Any additional commands to passed to R when opening graphics device

Value

Returns scalar integer(mik):

0 = success

other values = failure, see also Error Handling

Details

Rinit performs the following tasks:

  1. Activates the message logger, using arguments log_file, log_append, log_echo if present, otherwise defaults are used
  2. Reads the RFortran settings file RFortran.set which sets the user modifiable global settings in RFortran_GlobalVars.f90
  3. Auto-open R - check if R is open and if it isn't opens RGui.exe in path RguiPathIn if present or default RguiPathIn set by RFortran.set. After opening RFortran waits for wait4R milliseconds to ensure R is properly initialised. wait4R is set by wait4Rin if present or default wait4Rdef in RFortran.set.
  4. Initialises and creates COM Interface
  5. Loads RFortran's R scripts from Rfortran_ScriptPathIn if present or default %RFORTRAN_PATH%\Rscripts - this enables auto-loading of scripts that RFortran depends on
  6. Loads R scripts from current directory of Fortran executable - this enables auto-loading of R scripts that are specific to the Fortran executable
  7. Sets the R working directory to workingDirIn if present or the default which is the current directory of executable
  8. Opens a new graphics device if RgraphicsDevTypeIn is present, with arguments GraphicsDev_name and GraphicsDev_cmd if present
See Also

RFortran Settings

Examples

Initialise R and auto-load R scripts in path D:\RFortran\Rscripts

ok=Rinit(Rfortran_ScriptPathIn='D:\RFortran\Rscripts')

Initialise R and wait 5 secs after auto-opening R before initialising COM interface

ok=Rinit(wait4RIn=5000)

Initialise R and auto-load Rgui.exe in path C:\Program Files\R\R-2.8.1\bin\ wait 5 secs after auto-opening R before initialising COM interface

ok=Rinit(RGuiPathIn='C:\Program Files\R\R-2.8.1\bin\')

Reval

Description

This evaluates commands to be executed in R.

Syntax

Reval(commandstring)

Arguments

Name Type Description
commandstring character command to be executed in R

Value

Returns scalar integer(mik):

0 = success

other values = failure, see also Error Handling

Details

commandstring is the R command that you would type at the R prompt, see examples below

Examples

Set value of R variable x to 1

ok=Reval("x=1")

Generate 100 normal random numbers and store in a and b, then plot them (illustrates use of double and single quotes)

ok=Reval("a=rnorm(100)")
ok=Reval("b=rnorm(100)")
ok=Reval("plot(a,b,xlab='x')")

Rput

Description

There two forms for using Rput - this one transfers variables from Fortran to R.

The other is for commands to be executed in R - see [Rput(command)]

Syntax

Rput(R_var,Fortran_var,[mv],[status])

Arguments

Name Type Description
R_var character Name of R variable that received data from Fortran_var
Fortran_var See Details Name of fortran variable transferred to R_var
[mv] logical optional array/vector that denotes which elements of Fortran_var will be denoted as NA in R_var
[status] character determines how the overwriting of R variables by Rput is handled - see details below

Value

Returns scalar integer(mik):

0 = success

other values = failure, see also Error Handling

Details

Current types of Fortran_var that are supported are:

Scalars, 1-D, 2-D, 3-D arrays

integer(2), integer(4), real(4), real(8), logical(4), character(*)

[mv] is useful for transferring missing values from Fortran to R - see Examples below

[status] determines how the overwriting of R variables by Rput is handled. Possible values and actions are:

Value Action
"new" If R_var already exists in R an error will be returned and it will not be overwritten
"old" If R_var does not exist in R, an error will be returned
"unknown" (default) Create or overwrite R_var depending on whether it exists or not

These options are similar to the STATUS argument for the Fortran function OPEN used for connecting to files.

Examples

Transfer a real(4) scalar

real(4)    :: pi_short = 3.1415
ok = Rput("pi_short",pi_short)

At R prompt:

> pi_short
[1] 3.1415

Transfer an integer(4) 1D array

integer(4) :: cc(1:5) = (/112, 222, 333, 444, 555/)
ok = Rput("cc",cc)

At R prompt:

> cc
[1] 112 222 333 444 555

Transfer an integer(4) 1D array with missing values

integer(4) :: cc(1:5) = (/112, 222, 333, 444, 555/)
ok = Rput("cc",cc,mv=(cc==222))  

At R prompt:

> cc
[1] 112  NA 333 444 555

Many more examples of using Rput and Rget are provided in TEST_RputRget.f90


Rget

Description

Transfers data from a variable in R to a Fortran variable.

Syntax

Rget(R_var,Fortran_var,[alloc],[typeOption],[InvalidOption])

Arguments

Name Type Description
R_var character Name of R variable transferred to Fortran variable, Fortran_var
Fortran_var See Details Name of fortran variable that receives data from R variable R_var
alloc logical Flag which sets whether to reallocate/allocate Fortran_var to match size of R_var
typeOption integer Flag which specifies how to handle type mismatches between R_var and Fortran_var
InvalidOption integer Flag which specifies how to handle invalid data (e.g. NA, NaN, Inf) when transferring from R to Fortran

Value

Returns scalar integer(mik):

0 = success

other values = failure, see also Error Handling

Details

The types and shapes of data being transferred from R to Fortran currently supported are are the same as with the Rput function.

Fortran_var must match the type and the dimension of R_var- see Error Handling for how type and dimension mismatches are handled.

For arrays, if alloc=.true. and Fortran_var is allocatable then Fortran_var is reallocated/allocated to match size of R_var

In all other cases R_var and Fortran_var must have the same size, otherwise an error will result.

The Rget routine can handle R expressions providing they result in a data variable that matches the Fortran variable, see examples below.

Examples

Get a real(4) scalar

real(4)    :: pi_short = 3.1415
ok = Rput("pi_short",pi_short)
ok = Rget("pi_short",pi_short)

Get an integer(4) 1D array

integer(4) :: cc(1:5) = (/112, 222, 333, 444, 555/)
ok = Rput("cc",cc)
ok = Rget("cc",cc)

Examples of R expressions that can be Rget:

components of objects '$' symbol

Rget('a$statistic',scalar)

portions of arrays '[]' symbols

Rget('x[3:10]',array)

results of functions '()' symbols

Rget('length(x)', scalar)

arithmetic expressions +/-*, etc

Rget('1+2', scalar)

all of the above

Rget('arima(rnorm(50),c(1,0,0))$coef[1]', scalar)

Many more examples of using Rput and Rget are provided in TEST_RputRget.f90


Rcall

Description

Handles passing of multiple variables and commands to R.

Syntax

Rcall(vars,cmds)

Arguments

Name Type Description
vars integer vector return values for passing variables to R (see examples below)
cmds character vector vector of commands to be executed in R

Value

Returns scalar integer(mik):

0 = success

other values = failure, see also Error Handling

Details

This is a really useful function!

vars can be used to pass multiple variables to R via a series of Rput commands

cmds is a character vector of commands to be executed in R (usually using the variables passed to R in vars)

Examples

Send xdata and ydata to R, plot them and then remove them

Rcall(vars=(/Rput("x",xdata),Rput("y",ydata)/), &
      cmds=(/cl("plot(x,y,xlab='x',ylab='y-axis',xlim=c(0,1.2),ylim=c(0,1.2))"),&
             cl("rm(x,y)")/))

Note: cl is simply a string function 'common length) used to ensure all the components of the cmds character vectors have the same length to avoid a Fortran compiler warning!


Error Handling

All RFortran functions return integer error flags, using non-zero values to indicate error conditions. Descriptive error messages are written to a log file, message.log. In addition, a look-up table of the error codes is provided below.

Error Codes

[rcom] in description denotes an error produced by the rcom interface and passed to RFortran.

All other errors are produced within the RFortran code itself.

ErrorCodeID Description Remedy
-2147221503[rcom] reserved for future use
-2147221502[rcom] reserved for future use
-2147221501[rcom] reserved for future use
-2147221500[rcom] R variable is a R object that cannot be transferred to Fortran
-2147221499[rcom] Init not called
-2147221498[rcom] Init already called
-2147221497[rcom] symbol not found
-2147221496[rcom] invalid expression
-2147221495[rcom] incomplete expression
-2147221494[rcom] data type not supported
-2147221493[rcom] R variable does not exist
-2147221488[rcom] version mismatch (rproxy /= R (D)COM Server)
-2147221487[rcom] reserved for future use
-2147221486[rcom] reserved for future use
-2147221485[rcom] rproxy.dll could not be loaded
-2147221484[rcom] invalid rpoxy dll
-2147221483[rcom] initialization failed
-2147221482[rcom] reserved for future use
-2147221481[rcom] connector name ""R"" expected
-2147221472[rcom] access violation in R (interpreter,package code)
-2147024732[rcom] Strange bug produced when commit stack size is >450 MBReduce commit stack size < 450 MB - value found by trial and error
-2147024888[rcom] Strange bug produced when reserve stack size is >370 MBReduce reserve stack size < 370 MB - value found by trial and error
-2147221164[rcom] R not open OR rcom not registeredManually open R or for auto-open of R inc. 'wait4Rdef>10000ms' in Rfortran.set OR ensure Rcom is registered with R (use installer or see rfortran.org for manual registration)
-2147467262[rcom] rcom not registeredR command comRegisterRegistry() has not been executed - see rfortran.org for registration instructions
-2147417851[rcom] R server threw an exceptionPossible causes - if NA is passed via Rput or Rget - not always at source of NA
-1Rfortran not initialised Call Rinit before Rput/Rget etc.
-100rput array size /= mv array sizesize of mv array needs to match rput array
-101type mismatch between fortran and R variable
-103dimension mismatch between fortran and R variable
-104array size mismatch between fortran and R variable
-105 R variable exists and status='new'
-106 R variable does not exist and status='old'
-107Unknown value of status in Rput
-108Invalid symbols NA, Inf or NAN exist in R object
-109R variable is a scalar when fortran variable is an array
-110R variable is an array when fortran variable is an scalar

When transferring variables using Rput from Fortran to R, as long as the syntax is correct there are minimal errors since the flexible R language changes the R variable to the type,dimension and size of the Fortran variable

When transferring from R to Fortran using Rget many potential errors can occur. How each type of error is handled is as follows:

Type Mismatches

If types of R_var and Fortran_var are different then this handled depending on the value of optional argument typeOption to Rget or if it isn't present, then typeOptionDef set in RFortran.set

Possible values for typeOption and their actions are:

typeOption Action
ERROR_DONTPASS reports an error and does not transfer R_var to Fortran_var
ERROR_DOPASS reports an error, but still attempts to transfer R_var to Fortran_var - results are unpredictable
CONVERT reports a warning and attempts to convert R_var to same type as Fortran_var. Currently only conversion from integer to real and real to integer is supported, all other type mismatchs report an error and the R_var is not transferred

Dimension Mismatches

Dimension mismatches between R_var and Fortran_var report an error and no transfer occurs

Size Mismatches

Size mismatches between R_var and Fortran_var report a warning but a transfer from R to Fortran occurs - with any potential side effects

Invalid Values

R variables can take certain values, such as NA, NaN and Inf which cannot be transferred to Fortran. RFortran checks for the existence of these invalid values and takes action depending on value of optional argument InvalidOption to Rget or if it isn't present then InvalidOptionDef set in RFortran.set

Possible values for InvalidOption and their actions are:

InvalidOption Action
ERROR_DONTPASS reports an error and does not transfer R_var to Fortran_var
ERROR_DOPASS reports an error, but still attempts to transfer R_var to Fortran_var - results are unpredictable
CONVERT reports a warning and converts invalid values in R-var to valid numeric values specified for different types set in RFortran.set and shown in the following table

If InvalidOption=CONVERT, different variable types are converted to following values:

Type Convert value
integer(4) Convert_Invalid_I4_val
real(8) Convert_Invalid_R8_val
character Convert_Invalid_str_val

A side effect of this conversion is that the invalid values in r_var are converted to the convert values specified in the table above.

Example

Put an integer(4) 1D array with missing values

integer(4) :: cc(1:5) = (/112, 222, 333, 444, 555/)
ok = Rput("cc",cc,mv=(cc==222))  

At R prompt:

> cc
[1] 112  NA 333 444 555

Get an integer(4) 1D array with missing values

Case 1: InvalidOption=ERROR_DONTPASS

ok = Rget("cc",cc,InvalidOption=ERROR_DONTPASS)  

Result in Fortran:

ok!=0 and cc is not transferred

Case 2: InvalidOption=ERROR_DOPASS

ok = Rget("cc",cc,InvalidOption=ERROR_DOPASS)  

Result in Fortran:

ok=0 and cc is transferred - unpredictable results

Case 3: InvalidOption=ERROR_DOPASS and Convert_Invalid_I4_val=-999

ok = Rget("cc",cc,InvalidOption=CONVERT)  

Result in Fortran:

ok=0 and cc=(/112,-999,333,444,555/) 

At R prompt (shows side-effect):

>cc
[1] 112 -999 333 444 555

If InvalidOption were not present in any of the above then InvalidOptionDef in would determine action.

RFortran Settings

RFortran has several global variables that can be modified by the user to suit their own configuration/project.

These variables are all contained in the RFortran.set file and are listed in the table below.

Global Variable Meaning
TypeOptionDef Default flag value for handling type mismatches
InvalidOptionDef Default flag value for handling invalid values
Convert_Invalid_* Default value for conversion of invalid values
wait4RDef Default time (in milliseconds) RFortran waits when R is auto-opened, overridden by wait4RIn optional argument to Rinit
RGuiPath Path to RGui.exe - written by RFortran installer and overridden by RGuipathIn optional argument to Rinit

A default version of RFortran.set is installed to the folder RFortran\Settings. This file contains instructions on how to modify it to change these global variables.

When Rinit is called it looks for RFortran.set in the following locations in order of priority:

  1. Current folder of executable
  2. RFortran\settings

This enables different projects which use RFortran to have different 'RFortran.set' files

Setting up your own projects to use RFortran Functionality

XXX=CVF or IVF. CVF users substitute 'solution' for 'workspace' below

There are two ways to use the RFortran software library in your own projects

(1) Insert the source code directly into your project

The easiest way to do this is to add the project RFortran\RFORTRAN_XXX\RFORTRAN_XXX_LIB to your solution, and copy the folders RFortran and MUtilslib-readonly into your project

This has the disadvantage that RFortran can be re-compiled everytime you rebuild your project

(2) Add the static library RFortran_XXX.lib to your project

This has the advantage that only one version of RFortran is compiled on your computer.

Choose one of the following methods:

  1. Add the RFortran_XXX.lib into your project.
  2. This does not auto-link to the debug and release configurations of RFortran
  3. Change the project properties/settings to specify the path to the debug/release folder of the static link library
  4. This is the optimal solution - auto-links to debug and release configurations of a single RFortran static library.

The following are suggested project properties\settings:

IVF

Property Value
Project > Properties > Fortran > General > Additional Include Directories$(RFORTRAN_PATH)\RFORTRAN_IVF\RFORTRAN_IVF_LIB\$(ConfigurationName)
Project > Properties > Linker > Input$(RFORTRAN_PATH)\RFORTRAN_IVF\RFORTRAN_IVF_LIB\$(ConfigurationName)\RFORTRAN_IVF_LIB.lib

If you apply the above project properties to "All Configurations" you do not need to change the debug and release configurations seperately.

CVF

Setting Value
Project > Settings > Fortran > Preprocessor > INCLUDE and USE Path Directories RFortran install path\RFortran\RFortan_CVF_LIB\ZZZ\
Project > Settings > Linker > Input > Object/library modules RFortran install path\RFortran\RFortan_CVF_LIB\ZZZ\RFortan_CVF_LIB.LIB

where

RFortran install path = install path of RFortran

ZZZ = debug or release configuration

The projects in the tutorial examples folder provide an example of how to configure the project properties/settings to use the static library.


Sign in to add a comment
Powered by Google Project Hosting