2012-08-13 176 views
2

我偶然發現了一個名爲openCPU.org的令人敬畏的開源項目,我對這個項目感到非常興奮。作爲一名研究科學家,我試圖創建一個託管我的工作的網站,我只想在雲上運行R,讓我的腳本實時運行並顯示在我的網頁上。所以感謝Jeroen讓這個項目發生了很長時間。與openCPU交互

有了這個,我的問題。

我該如何與openCPU交互?

我可以把一個例子功能爲「運行一些代碼」:

http://public.opencpu.org/userapps/opencpu/opencpu.demo/runcode/

和檢索我的代碼,這是偉大的一個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並與該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 
?> 

我怎麼那麼訪問哪些傳遞回來$結果?我正在尋找一個圖表。它看起來像這樣:

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

下一個步驟將是獲得圖像,沿着線的東西:

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

但我不知道如何訪問$結果中的單個元素?

編輯#2

玉傢伙,我已經得到了這個工作,由於下方和多個其他幫助會話的答案,很多砸我的頭監視器。

在這裏,我們走了,帶着捲曲

<?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 

?> 
+1

你的問題有幾個問題:你的第一個編輯可能應該是一個單獨的問題,因爲它非常獨立的,第二,你的第二個編輯絕對應該是一個答案,而不是一個問題。請記住,stackoverflow不應該是一個論壇,而是一個問答網站,這裏的問題的真正答案:如何讓opencpu與php交互隱藏在問題中... – cmbarbu 2015-08-12 09:11:13

回答

3

OpenCPU完成使用HTTP POST來執行的功能,以及HTTP GET讀/渲染對象和圖表。您可以先將功能保存到臨時商店,然後從那裏調用它。在interactive manual的「/ R/tmp API」一章中給出了一個基本示例。如果您單擊名爲save a functionget the functioncall the function的紅色演示按鈕,它將幫助您完成這些步驟。

基本上,在第一步中,您對身份函數執行HTTP POST以將您的功能保存在商店中。這也是你發現的running code example page的第三種形式。所以我只是在那裏複製你的代碼,然後它返回對象x0188b9b9ce

要檢查一切是否正常,可以使用HTTP GET讀取此對象。例如,打開這個網址讀取你的函數的源代碼:

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

替代輸出例如得到函數作爲RDATA文件:

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

重要的是HTTP GET從不執行函數。它只是看起來不錯,並以您請求的輸出格式返回。所以現在你確信你的功能在我們想要運行的商店中。要做到這一點,你需要一個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請求。如果要將輸出包含在網頁中,通常只需要將HTTP POST與/save輸出類型結合使用。所以,你可以使用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 
+0

感謝您的澄清。我現在看到我誤解的根源。那麼,你如何在訪問這些信息{ 「對象」:空, 「圖形」: 「x2acba9501a」 ], 「文件」:{} } – 2012-08-14 01:57:37

+0

看到上面的編輯,並感謝您的幫助! – 2012-08-14 02:11:57

+0

感謝您的幫助,我已經得到它的工作。我肯定會回覆更多的問題,但結果將成爲其他人學習的更多示例。 – 2012-08-15 07:46:14

1

下面是一個完整的例子網頁,我嘲笑爲使用OpenCPU使用A 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>