2007-10-16 21:51:57
PHPからRを操作してみた。最初に3行3列の行列を作って、固有値と固有ベクトルを得るというもの。
<?php
$array = array(1,2,3,9,11,16,21,22,23);
$descriptorspec = array(
0 => array("pipe","r"),
1 => array("pipe","w"),
);
$process = proc_open("R --vanilla --slave",$descriptorspec,\\
$pipes);
if(is_resource($process)){
fwrite($pipes[0], "A <- matrix (c(".implode(",",\\
$array)."), nrow=3,ncol=3)\n");
fwrite($pipes[0], "eigen(A)\n");
fwrite($pipes[0], "quit()\n");
fclose($pipes[0]);
while(!feof($pipes[1])){
$result .= fread($pipes[1], 4096);
}
fclose($pipes[1]);
proc_close($process);
}
echo $result;
?>
これを実行すると、
$values
[1] 38.8024950 -3.3394581 -0.4630369
$vectors
[,1] [,2] [,3]
[1,] -0.5003593 -0.8296818 -0.97423841
[2,] -0.5591098 -0.4301570 0.22377201
[3,] -0.6610876 0.3557992 -0.02802863
という結果が得られる。なかなかいい感じではないか。Rを呼び出すときに、「--vanilla --slave」というのを入れるのは、余計なものを表示させないためらしい。さて、今度は図を書かせたい。
<?php
$array = array(21,12,33,39,11,16,21,22,23);
$descriptorspec = array(
0 => array("pipe","r"),
1 => array("pipe","w"),
);
$process = proc_open("R --vanilla --slave",$descriptorspec,\\
$pipes);
if(is_resource($process)){
fwrite($pipes[0], "A <- c(".implode(",",$array).")\n");
fwrite($pipes[0], "bitmap(file=\"%stdout\", type=\\
\"png256\")\n");
fwrite($pipes[0], "hist(A)\n");
fwrite($pipes[0], "quit()\n");
fclose($pipes[0]);
while(!feof($pipes[1])){
$result .= fread($pipes[1], 4096);
}
fclose($pipes[1]);
proc_close($process);
}
header("Content-type:image/png");
echo $result;
?>
このファイルを保存してブラウザで表示させてみると、ヒストグラムが表示される。
もちろんこれだけならわざわざPHPから操作する必要もないことだけれども、自動的に生成される数値を処理するときなどには、なんらかのスクリプトで動かしてやらなくてはならないから、必要になるときが来るだろう。
他のでもいろいろ試してみようかな。
参考にしたのは主に以下の3箇所。
●
PHPでグラフを作る(gnuplot編)
●
PHPについて質問致します。
●
DokuWikiの日本語対応