| 1 | =head1 NAME | ||
| 2 | |||
| 3 | RserveClient.pl - Macros for evaluating R code on an Rserve server | ||
| 4 | |||
| 5 | =head1 SYNPOSIS | ||
| 6 | |||
| 7 | =head1 SYNOPSIS | ||
| 8 | |||
| 9 | loadMacros('RserveClient.pl'); | ||
| 10 | |||
| 11 | rserve_start(); | ||
| 12 | my @rnorm = rserve_eval("rnorm(15, mean=$m, sd=$sd)"); | ||
| 13 | rserve_eval(data(stackloss)); | ||
| 14 | my @coeff = rserve_eval('lm(stack.loss ~ stack.x, stackloss)$coeff'); | ||
| 15 | rserve_finish(); | ||
| 16 | |||
| 17 | |||
| 18 | =head1 DESCRIPTION | ||
| 19 | |||
| 20 | The macros in this file provide access to facilities of L<R | ||
| 21 | statistical computing environment|http://www.r-project.org>, | ||
| 22 | optionally located on another server, by using the | ||
| 23 | L<Rserve|http://www.rforge.net/Rserve/> protocol. | ||
| 24 | |||
| 25 | B<IMPORTANT:> Before you can use these macros, you will need to | ||
| 26 | configure the location of your Rserve host by adding it to | ||
| 27 | C<$pg{specialPGEnvironmentVars}{Rserve}{host}>, for instance by | ||
| 28 | appending the following line to F<webwork2/conf/localOverrides.conf>: | ||
| 29 | |||
| 30 | $pg{specialPGEnvironmentVars}{Rserve} = {host => "localhost"}; | ||
| 31 | |||
| 32 | Without this configuration in place, Rserve macros will only print out | ||
| 33 | a warning about missing configuration and return C<undef>. | ||
| 34 | |||
| 35 | =head1 MACROS | ||
| 36 | |||
| 37 | The macros in this file set up a connection to the R server and | ||
| 38 | pass a string parameter to R for evaluation. The resulting | ||
| 39 | vector is returned as a perl array object. | ||
| 40 | |||
| 41 | =over 4 | ||
| 42 | |||
| 43 | =item rserve_eval REXPR | ||
| 44 | |||
| 45 | Evaluates an R expression, given as text string in REXPR, on the | ||
| 46 | L<Rserve|http://www.rforge.net/Rserve/> server and returns its result | ||
| 47 | as a Perl representation of the L<Statistics::R::REXP> object. | ||
| 48 | Multiple calls within the same problem share the R session and the | ||
| 49 | object workspace. | ||
| 50 | |||
| 51 | =item rserve_query | ||
| 52 | |||
| 53 | Evaluates an R expression, given as text string in REXPR, in a | ||
| 54 | single-use session on the L<Rserve|http://www.rforge.net/Rserve/> | ||
| 55 | server and returns its result as a Perl representation of the | ||
| 56 | L<Statistics::R::REXP> object. | ||
| 57 | |||
| 58 | This function is different from C<rserve_eval> in that each call is | ||
| 59 | completely self-enclosed and its R session is discarded after it | ||
| 60 | returns. | ||
| 61 | |||
| 62 | =item rserve_start, rserve_finish | ||
| 63 | |||
| 64 | Start up and close the current connection to the Rserve server. In | ||
| 65 | normal use, these functions are completely optional because the first | ||
| 66 | call to C<rserve_eval> will call start the session if one is not | ||
| 67 | already open. Similarly, the current session will be closed in its | ||
| 68 | destructor when the current question goes out of scope. | ||
| 69 | |||
| 70 | Other than backward compatibility, the only reason for using these | ||
| 71 | functions is to start a new clean session within a single problem, | ||
| 72 | which shouldn't be a common occurrence. | ||
| 73 | |||
| 74 | =item rserve_start_plot [IMG_TYPE, [WIDTH, HEIGHT]] | ||
| 75 | |||
| 76 | Opens a new R graphics device to capture subsequent graphics output in | ||
| 77 | a temporary file on the R server. IMG_TYPE can be 'png', 'jpg', or | ||
| 78 | 'pdf', with 'png' as the default. If left unspecified, WIDTH and | ||
| 79 | HEIGHT, will use the R graphics device's default size. Returns the | ||
| 80 | name of the remote file. | ||
| 81 | |||
| 82 | |||
| 83 | =item rserve_finish_plot REMOTE_NAME | ||
| 84 | |||
| 85 | Closes the R graphics capture to file REMOTE_NAME, transfers the file | ||
| 86 | to WebWork's temporary file area, and returns the name of the local | ||
| 87 | file that can then be used by the image macro. | ||
| 88 | |||
| 89 | =item rserve_get_file REMOTE_NAME, [LOCAL_NAME] | ||
| 90 | |||
| 91 | Transfer the file REMOTE_NAME from the R server to WebWork's temporary | ||
| 92 | file area, and returns the name of the local file that can then be | ||
| 93 | used by the C<htmlLink> macro. If LOCAL_NAME is not specified, the | ||
| 94 | filename portion of the REMOTE_NAME is used. | ||
| 95 | |||
| 96 | =back | ||
| 97 | |||
| 98 | |||
| 99 | =head1 DEPENDENCIES | ||
| 100 | |||
| 101 | Requires perl 5.010 or newer and CPAN module Statistics::R::IO, which | ||
| 102 | has to be loaded in WebWork's Safe compartment by adding it to | ||
| 103 | ${pg}{modules}. | ||
| 104 | |||
| 105 | |||
| 106 | =cut | ||
| 107 | |||
| 108 | |||
| 109 | my $rserve; # Statistics::R::IO::Rserve instance | ||
| 110 | |||
| 111 | |||
| 112 | sub _rserve_warn_no_config { | ||
| 113 | my @trace = split /\n/, Value::traceback(); | ||
| 114 | my ($function, $line, $file) = $trace[0] =~ /^\s*in ([^ ]+) at line (\d+) of (.*)/; | ||
| 115 | |||
| 116 | $PG->warning_message('Calling ' . $function . | ||
| 117 | ' is disabled unless Rserve host is configured in $pg{specialPGEnvironmentVars}{Rserve}{host}') | ||
| 118 | } | ||
| 119 | |||
| 120 | |||
| 121 | sub rserve_start { | ||
| 122 | _rserve_warn_no_config && return unless $Rserve->{host}; | ||
| 123 | |||
| 124 | $rserve = Statistics::R::IO::Rserve->new(server => $Rserve->{host}, _usesocket => 1); | ||
| 125 | |||
| 126 | # Keep R's RNG reproducible for this problem | ||
| 127 | $rserve->eval("set.seed($problemSeed)") | ||
| 128 | } | ||
| 129 | |||
| 130 | |||
| 131 | sub rserve_finish { | ||
| 132 | $rserve->close() if $rserve; | ||
| 133 | undef $rserve | ||
| 134 | } | ||
| 135 | |||
| 136 | |||
| 137 | sub rserve_eval { | ||
| 138 | _rserve_warn_no_config && return unless $Rserve->{host}; | ||
| 139 | |||
| 140 | my $query = shift; | ||
| 141 | |||
| 142 | rserve_start unless $rserve; | ||
| 143 | |||
| 144 | my $result = _try_eval($rserve, $query); | ||
| 145 | _unref_rexp($result) | ||
| 146 | } | ||
| 147 | |||
| 148 | |||
| 149 | sub rserve_query { | ||
| 150 | _rserve_warn_no_config && return unless $Rserve->{host}; | ||
| 151 | |||
| 152 | my $query = shift; | ||
| 153 | $query = "set.seed($problemSeed)\n" . $query; | ||
| 154 | my $rserve_client = Statistics::R::IO::Rserve->new(server => $Rserve->{host}, _usesocket => 1); | ||
| 155 | my $result = _try_eval($rserve_client, $query); | ||
| 156 | $rserve_client->close; | ||
| 157 | _unref_rexp($result) | ||
| 158 | } | ||
| 159 | |||
| 160 | |||
| 161 | ## Evaluates an R expression guarding it inside an R `try` function | ||
| 162 | ## | ||
| 163 | ## Returns the result as a REXP if no exceptions were raised, or | ||
| 164 | ## `die`s with the text of the exception message. | ||
| 165 | sub _try_eval { | ||
| 166 | my ($rserve, $query) = @_; | ||
| 167 | |||
| 168 | my $result = $rserve->eval("try({ $query }, silent=TRUE)"); | ||
| 169 | die $result->to_pl->[0] if $result->inherits('try-error'); | ||
| 170 | |||
| 171 | $result | ||
| 172 | } | ||
| 173 | |||
| 174 | |||
| 175 | ## Returns a REXP's Perl representation, dereferencing it if it's an | ||
| 176 | ## array reference | ||
| 177 | ## | ||
| 178 | ## `REXP::to_pl` returns a string scalar for Symbol, undef for Null, | ||
| 179 | ## and an array reference to contents for all vector types. This | ||
| 180 | ## function is a utility wrapper to make it easy to assign a Vector's | ||
| 181 | ## representation to an array variable, while still working sensibly | ||
| 182 | ## for non-arrays. | ||
| 183 | sub _unref_rexp { | ||
| 184 | my $rexp = shift; | ||
| 185 | |||
| 186 | my $value = $rexp->to_pl; | ||
| 187 | if (ref($value) eq ref([])) { | ||
| 188 | @{$value} | ||
| 189 | } else { | ||
| 190 | $value | ||
| 191 | } | ||
| 192 | } | ||
| 193 | |||
| 194 | sub rserve_start_plot { | ||
| 195 | _rserve_warn_no_config && return unless $Rserve->{host}; | ||
| 196 | |||
| 197 | my $device = shift // 'png'; | ||
| 198 | my $width = shift // ''; | ||
| 199 | my $height = shift // ''; | ||
| 200 | |||
| 201 | die "Unsupported image type $device" unless $device =~ /^(png|pdf|jpg)$/; | ||
| 202 | my $remote_image = (rserve_eval("tempfile(fileext='.$device')"))[0]; | ||
| 203 | |||
| 204 | $device =~ s/jpg/jpeg/; | ||
| 205 | |||
| 206 | rserve_eval("$device('$remote_image', width = ${width}, height = ${height})"); | ||
| 207 | |||
| 208 | $remote_image | ||
| 209 | } | ||
| 210 | |||
| 211 | |||
| 212 | sub rserve_finish_plot { | ||
| 213 | _rserve_warn_no_config && return unless $Rserve->{host}; | ||
| 214 | |||
| 215 | my $remote_image = shift or die "Missing remote image name"; | ||
| 216 | |||
| 217 | rserve_eval("dev.off()"); | ||
| 218 | |||
| 219 | rserve_get_file($remote_image) | ||
| 220 | } | ||
| 221 | |||
| 222 | |||
| 223 | sub rserve_get_file { | ||
| 224 | _rserve_warn_no_config && return unless $Rserve->{host}; | ||
| 225 | |||
| 226 | my $remote = shift or die "Missing remote file name"; | ||
| 227 | my $local = shift // $PG->fileFromPath($remote); | ||
| 228 | |||
| 229 | $local = $PG->surePathToTmpFile($local); | ||
| 230 | |||
| 231 | $rserve->get_file($remote, $local); | ||
| 232 | |||
| 233 | $local | ||
| 234 | } | ||
| 235 | |||
| 236 | |||
| 237 | 1; |