2

openCPU.org という素晴らしいオープン ソース プロジェクトに出くわし、このプロジェクトに非常に興奮しています。自分の研究をホストする Web サイトを作成しようとしている研究者として、R をクラウド上で実行して、スクリプトをリアルタイムで実行し、Web ページに表示できることを何よりも望んでいます。このプロジェクトを実現してくれた Jeroen に心から感謝します。

それでは、私の質問に移ります。

どうやってopenCPUと対話するのですか?

サンプル関数を「いくつかのコードを実行する」に入れることができます:

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

そして、私のコードの PNG 画像を取得します。これは素晴らしいことです!

しかし、自分の Web ページや 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 への返信として、API で POST と GET を使用する必要があります。ここで、私の質問は、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はHTTPPOSTを使用して関数を実行し、HTTPGETを使用してオブジェクトとグラフを読み取り/レンダリングします。関数を一時ストアに保存し、そこから呼び出すことから始めることができます。基本的な例は、インタラクティブマニュアルの「/ R/tmpAPI」の章に記載されています。save a function、という名前の赤いデモボタンをクリックするget the functioncall the function、手順が実行されます。

基本的に、最初のステップでは、ID関数に対してHTTP POSTを実行して、関数をストアに保存します。これは、見つけた実行中のコードサンプルページの3番目の形式で行われていることでもあります。そこで、コードをコピーしたところ、オブジェクトが返されましたx0188b9b9ce

すべてが正常に行われたかどうかを調べるために、HTTPGETを使用してこのオブジェクトを読み取ることができます。たとえば、次のURLを開いて、関数のソースコードを読み取ります。

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

代替出力は、たとえば、関数をRDataファイルとして取得するためのものです。

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

重要なのは、HTTPGETが関数を実行しないことです。調べて、要求した出力形式で返します。これで、関数がストアにあると確信したので、実行したいと思います。これを行うには、HTTPPOSTが再度必要です。たとえば、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

呼び出す関数が引数を取る場合は、それらをHTTPPOSTリクエストのパラメーターとして含めます。/saveWebページに出力を含める場合は、通常、出力タイプと組み合わせてHTTPPOSTのみを使用する必要があります。したがって、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) を使用した特定の分析をデモするためにモックアップした完全な Web ページの例です。私は、特定の分析に簡単にアクセスできるようにすることをおろそかにしていました。いわば、ライブ ユーザー ガイドです。警告、私の例は 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 に答える