2

我偶然发现了一个很棒的开源项目 openCPU.org,我对这个项目感到非常兴奋。作为一名试图创建一个网站来托管我的工作的研究科学家,我最希望能够在云上运行 R 以让我的脚本实时运行并显示在我的网页上。非常感谢 Jeroen 促成了这个项目。

有了这个,我的问题。

我到底如何与 openCPU 交互?

我可以将示例函数放入“运行一些代码”中:

http://public.opencpu.org/userapps/opencpu/opencpu.demo/runco​​de/

并检索我的代码的 PNG 图像,这很棒!

但是如何在我自己的网页中或通过 URL 执行此操作?

我可以从此页面获取原始代码上传的对象,例如:“x3ce3bf3e33”

如果是类似的函数:

myfun <-function(){

x = seq(1,6.28)
y = cos(x)
p = plot(x,y)
print(p)
# also tried return(p)
}

我不应该可以通过以下方式调用它:

http://public.opencpu.org/R/tmp/x3ce3bf3e33/png

输入变量呢?例如:

myfun <-function(foo){

x = seq(1,foo)
y = cos(x)
p = plot(x,y)
print(p)
}

我觉得也许我缺少一些东西。如何使用 url 指定“GET”或“POST”?

编辑

好的,为了响应下面的@Jeroen,我需要使用 POST 和 GET 和 API。现在我的问题延伸到以下问题,即让 PHP 与它正确交互。

说我有代码:

<?php

$foo = 'bar';
$options = array(
    'method' => 'POST',
    'foo' => $foo,
    );
$url = "http://public.opencpu.org/R/tmp/x0188b9b9ce/save";
$result = drupal_http_request($url,$options); // drupal function
?>

然后我如何访问 $result 中传回的内容?我正在寻找一张图表。它看起来像这样:

{
    "object" : null,
    "graphs" : [
        "x2acba9501a"
    ],
    "files" : {}
} 

下一步将是获取图像,类似于:

$newurl = "http://public.opencpu.org/R/tmp/".$result["graph"]."/png";
$image = drupal_http_request($newurl);
echo $image;

但我不知道如何访问 $result 的各个元素?

编辑#2

好的,伙计们,我已经完成了这项工作,这要归功于下面的答案和其他多个帮助会话,以及很多我的头撞在显示器上。

我们开始了,用 cURL 完成

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://public.opencpu.org/R/tmp/x0188b9b9ce/save');
curl_setopt($ch, CURLOPT_POST, 1); // Method is "POST"
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns the curl_exec string, rather than just Logical value
$result = curl_exec($ch);
curl_close($ch);
$new = json_decode($result,true); // $result is in 'json' format, decode it
$get = $new['graphs'][0]; // the 'hashkey for the image, "x2acba9501a" above

$img = 'http://public.opencpu.org/R/tmp/'.$get.'/png'; // link to the png image

echo <<<END  // use this to display an image from the url
<a href="$img">
<img src="$img">
</a>
END

?>
4

2 回答 2

3

OpenCPU 使用 HTTP POST 执行函数,使用 HTTP GET 读取/渲染对象和图形。您可以先将函数保存到临时存储,然后从那里调用它。交互式手册的“/R/tmp API”一章中给出了一个基本示例。如果您单击名为 的红色演示按钮,save a function它将帮助您完成这些步骤。get the functioncall the function

基本上在第一步中,您对身份函数执行 HTTP POST 以将您的函数保存在存储中。这也是您找到的运行代码示例页面的第三种形式正在执行的操作。所以我只是在那里复制了你的代码,然后它返回给我 object x0188b9b9ce

要检查一切是否正常,您可以使用 HTTP GET 读取此对象。例如,打开这个 url 来阅读你的函数的源代码:

http://public.opencpu.org/R/tmp/x0188b9b9ce/ascii

例如,替代输出是将函数作为 RData 文件获取:

http://public.opencpu.org/R/tmp/x0188b9b9ce/rda

重要的是 HTTP GET 从不执行函数。它只是查找内容,并以您请求的输出格式返回。所以现在你确信你的函数在我们想要运行的 store 中。为此,您需要再次进行 HTTP POST。例如要获取 PDF,您可以执行

POST http://public.opencpu.org/R/tmp/x0188b9b9ce/pdf
POST http://public.opencpu.org/R/tmp/x0188b9b9ce/svg
POST http://public.opencpu.org/R/tmp/x0188b9b9ce/png

如果您调用的函数接受参数,则将它们作为参数包含在 HTTP POST 请求中。当你想在你的网页中包含输出时,通常你只想结合/save输出类型使用 HTTP POST。因此,您将使用 jquery 或其他任何方法:

POST http://public.opencpu.org/R/tmp/x0188b9b9ce/save

这可能会返回如下内容:

{
    "object" : null,
    "graphs" : [
        "x2acba9501a"
    ],
    "files" : {}
}

这表明您的函数已成功执行,并且它创建了一个绘图(耶!)。图形被保存到 tmp 存储。因此,您现在可以使用 HTTP GET 获取图形并将其嵌入到您的页面中:

http://public.opencpu.org/R/tmp/x2acba9501a/png
http://public.opencpu.org/R/tmp/x2acba9501a/png?!width=900&!height=500
http://public.opencpu.org/R/tmp/x2acba9501a/pdf
http://public.opencpu.org/R/tmp/x2acba9501a/svg
于 2012-08-13T10:17:59.570 回答
1

这是一个完整的示例网页,我模拟了使用 OpenCPU 来演示使用我编写的 R 包 (MARSS) 进行的特定分析。我一直在努力提供对特定分析的便捷访问——可以说是一个实时用户指南。警告,我的示例严重依赖 JavaScript,除此示例之外我没有使用 JavaScript 的经验;所以编码很笨拙,但它适用于我的目的。将 html 复制并粘贴到文件中并在浏览器中打开,它应该可以工作。


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
html, body
{
background: #6699FF;
text-align: center;
font-family : "Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size:14px;
}
#container
{
background: #FFF;
border: 0px #222 solid;
margin: 0 auto;
text-align: left;
width: 10.25in;
padding: 5px;
overflow: auto;
}
#container form
{
margin: 0 auto;
}
label
{
float: left;
width: 50px;
}
.leftCol
{
float: left;
width: 3in;
}
.rightCol
{
float: left;
width: 7in;
}
.references
{
font-size: x-small;
text-indent: 20px;
}
</style>
<base target="_blank" />
<title>Count-based population viability analysis (PVA) using corrupted data</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">       </script>
<script>
baseurl="http://public.opencpu.org"          
// This is done on load since we need the function on the server to deal with the file upload
function saveRFunction(){
//Run this bit of code and store the R function to run on OpenCPU
var baseurl = "http://public.opencpu.org";
var url = "http://public.opencpu.org/R/pub/base/identity/save";
// #txtRCommands is the id of the text box in the javascript
var rFunction = $("#RFunction").val();
// this bit sends the the RFunction in the hidden text area
$.post(url,{ x: rFunction },  
function (data) { 
var funloc = $.parseJSON(data).object;
funloc = "http://public.opencpu.org/R/tmp/"+funloc;
//set the action for the form
document.getElementById('FunctionLocation').value = funloc;                  
} );              
setTimeout(function() {
// Wait 2 seconds because of Chrome before loading default form
var frm = document.getElementById("inputForm2");
subm2(frm,'/svg');
}, 1000); 
};
//function for first submit button; subm and subm2 same except the id
function subm(f,ftype){
document.getElementById("inputForm").action=document.getElementById('FunctionLocation').value+ftype;
f.submit();
}
function subm2(f,ftype){
document.getElementById("inputForm2").action=document.getElementById('FunctionLocation').value+ftype;
f.submit();
}
</script>

</head>
<body onload="saveRFunction()">
<div id="container">
<h2>MARSS Case Study 1: Count-based PVA for data with observation error</h2>
This web tool fits a count-based PVA model (sensu Dennis et al. 1991) from a univariate (one site) time series of abundance data with observation error (Holmes 2001, 2004).  The result is an estimated long-term rate of population growth (&lambda;), process variance estimate (&sigma;<sup>2</sup>) and non-process or observation error variance.  Extinction risk metrics sensu Dennis et al. (1991) along with an uncertainty plot sensu Ellner and Holmes (2008) are shown.
</br></br>
<div class="leftCol">
<form enctype="multipart/form-data" action="" method="POST" target="test" id="inputForm">
<fieldset>
<legend><b>Upload a Dataset</b></legend>
<i>Comma-delimited. 1st col time, 2nd col counts.  Missing counts NA.</i></br>
File: <input name="!file:file" type="file" /> <!-- param name has to be file -->
Header: <select name="header"><option value=TRUE> TRUE </option> <option value=FALSE> FALSE </option> </select> </br />
<input name="!width" type="hidden" value=7 /> <!-- in inches -->
<input name="!height" type="hidden" value=6 /> <!-- in inches -->
<INPUT type="button" name="Submit" value="Run Analysis" onclick="subm(this.form,'/svg');"> <!-- svg so Firefox doesn't cache -->
<INPUT type="button" name="Submit" value="Get PDF of Plot" onclick="subm(this.form,'/pdf');">           </fieldset>
</form>
<form action="" method="POST" target="test" id="inputForm2">
<fieldset>
<legend><b>Select an Example Dataset</b></legend>
Dataset: 
<select name="dataname">
<option value='"wilddogs"' selected >African Wilddogs</option>
<option value='"prairiechicken"'>Prairie Chickens</option>
<option value='"grouse"'>Sage Grouse</option>
<option value='"graywhales"'>Gray Whales</option>
</select></br />
<input name="!width" type="hidden" value=7 /> <!-- in inches -->
<input name="!height" type="hidden" value=6 /> <!-- in inches -->
<INPUT type="button" name="Submit" value="Run Analysis" onclick="subm2(this.form,'/svg');">
<INPUT type="button" name="Submit" value="Get PDF of Plot" onclick="subm2(this.form,'/pdf');">
</fieldset>
</form>
<fieldset class="references">
<legend><b>References</b></legend>
<p>Dennis, Brian, Patricia L. Munholland, and J. Michael Scott. "Estimation of growth and extinction parameters for endangered species." Ecological monographs 61.2 (1991): 115-143.</p>
<p>Holmes, E. E. 2001. Estimating risks in declining populations with poor data. Proceedings of the National Academy of Science 98: 5072-5077.</p>
</fieldset>
<fieldset class="references">
<legend><b>R Code</b></legend>
<!-- if you do not want to see the R code, use this <textarea hidden="hidden" id="RFunction" style="display:none;"> -->
<textarea id="RFunction" readonly="readonly" cols="27" rows="18" style="border:0px;margin:0px">
function(file=NULL, header=TRUE,  dataname="wilddogs" ){

library(MARSS)

if(is.null(file)){
dat=get(dataname)
}else{
dat=read.csv(file, header=header)
dat=as.matrix(dat)
}

CSEGriskfigure(dat, silent=TRUE)
}
</textarea> 
</fieldset>
<input type="hidden" value="not set" id="FunctionLocation" /> <!-- this is where the function is stored -->
<br />
</div>
<!-- This iframe holds the output image. -->
<iframe style='width: 7in; height: 6in; border: 0px solid #000000; padding: 10px;' name='test' id="image_iframe" class="rightCol"></iframe>      
</div> 
<!-- This is an onload script, but Chrome is not loading the whole page before running the onload script.  Time out used above for this problem. -->
</body>
</html>
于 2013-05-30T20:39:00.763 回答