%load_ext sage
import os
DATA = os.getcwd() + '/' ; DATA
# ChromeではPDFをimgタグで表示できないので、pngに変換するように変更 2012/06/27
#
# Rのグラフをsageで表示するためのユーティリティ関数
import time
def preGraph(pdfFile):
filename = DATA+pdfFile
r.pdf(file='"%s"' %filename)
return pdfFile
def offGraph():
r.dev_off()
def postGraph(pdfFile, fac=0.75):
r.dev_off()
width = int(640*fac)
# html('<img src="%s?%s" width="%spx">'%(pdfFile, time.time(), width))
pngFile = convertPdf2Png(pdfFile)
html('<img src="%s?%s" width="%spx">'%(pngFile, time.time(), width))
def getGraph(pdfFile, fac=0.75):
width = int(640*fac)
# return '<img src="%s?%s" width="%spx">'%(pdfFile, time.time(), width)
pngFile = convertPdf2Png(pdfFile)
return '<img src="%s?%s" width="%spx">'%(pngFile, time.time(), width)
def convertPdf2Png(pdfFile):
pngFile = pdfFile.replace(".pdf", ".png")
result = os.popen("cd %s; convert -density 600 -geometry 1000 %s %s"%(DATA, pdfFile, pngFile)).read()
# print result
return pngFile
from IPython.display import Image, display
from IPython.display import display, Math
def my_show(obj):
return display(Math(latex(obj)))
class ListTable(list):
""" Overridden list class which takes a 2-dimensional list of
the form [[1,2,3],[4,5,6]], and renders an HTML Table in
IPython Notebook. """
def _repr_html_(self):
html = ["<table>"]
for row in self:
html.append("<tr>")
for col in row:
html.append("<td>{0}</td>".format(col))
html.append("</tr>")
html.append("</table>")
return ''.join(html)
# table = ListTable()
# table.append([getGraph(fig_3_7a, fac=0.5), getGraph(fig_3_7b, fac=0.5)])
# table
from IPython.display import HTML
# 変数の受け渡し
# Sage -> R
# すべてリストの形式に変換されてRに渡される
s_age = r([1,3,5,2,11,9,3,9,12,3]).name('age')
# name関数で名前を指定することで、Rの変数も定義される
print r('age')
# RからSageへの変換は、sageobj関数または_sage_()メソッドを使用
print sageobj(r('age'))
# 文字列配列の受け渡しができないことが分かりました。以下のように無理矢理セットしてください。
ary = ["a", "b"]
ss = str(ary)[1:-1]; print ss # リストを文字列に変換して[と]を取り除く
rary = r('c(%s)'%ss).name('rary')
print rary # Rに変換した配列
sary = sageobj(rary)
print sary # sageに戻した配列
# マトリックスの生成も同様に生成後に名前をつけて代入すればよい
m = r.matrix([1, 2, 3, 4], 2, 2, byrow=True).name('m'); m
# rでも同じ変数名が定義される
r('m')
# from IPython.display import display, Math
# def my_show(obj): return display(Math(latex(obj)))
# Rのマトリックス変数をsageの変数に変換する
print type(m)
sm = sageobj(m)
my_show(sm)
print type(sm)
# fig1.4
age = r([1,3,5,2,11,9,3,9,12,3]).name('age')
weight = r([4.4,5.3,7.2,5.2,8.5,7.3,6.0,10.4,10.2,6.1]).name('weight')
print r.mean(weight)
print r.sd(weight)
print r.cor(age, weight)
# グラフ表示
graph = preGraph("fig1.4.pdf")
r.plot(age, weight)
postGraph(graph, fac=0.5)
# ImageMagick の convert を使っている
os.system("convert -resize 400x fig1.4.png fig1.4b.png")
display(Image('fig1.4b.png'))
# タイトルを追加する場合には、r.plotではなく、r関数を使用する
graph = preGraph("fig1.4withTitle.pdf")
r("plot(age, weight, main='Title')")
postGraph(graph, fac=0.5)
os.system("convert -resize 400x fig1.4withTitle.png fig1.4withTitleb.png")
display(Image('fig1.4withTitleb.png'))