sdeditでシーケンス図をかきかきして、Sphinxドキュメントに貼り付ける

Sphinxでインラインでシーケンス図を書くには、sphinxcontrib-seqdiagのほかに、sphinxcontrib-sdeditという選択肢もあります。

seqdiagの直感性は最強なのですが、ちょっといろいろ省略が入った図とか、条件文が入った図とかをつくろうとした時につまづいてしまうことが多いので、とりあえずsdeditのほうも試してみました。

(ちなみに、sdeditはすごく書きにくい上に、絵がダサいです。なので、ほんとに凝った図を作りたいとき以外はおすすめしません)


LinuxMacだとそんなにハマることはない気がしますが、
Windows上のPython3でだと、いろいろとハマりどころがあります。

ハマりどころ1
 pip install しようとすると、PILのインストールが出来ずにコケる
Downloading/unpacking PIL
Could not find any downloads that satisfy the requirement PIL
Some insecure and unverifiable files were ignored (use --allow-unverified PIL to allow).
Cleaning up...


https://github.com/liori/sphinxcontrib-sdedit.git に、Pillowを使うよううまく改造した(らしい)sphinxcontrib-sdeditがあります。
pip install git+https://github.com/liori/sphinxcontrib-sdedit.git
とすれば、この特殊なsphinxcontrib-sdeditをインストールすることができます。

ハマりどころ2
 Unicode系のエラー。bytesとstrは足し算できんぞ!てきな。
@@ -70,10 +70,10 @@
"""
Render sequence diagram into a PNG or PDF output file.
"""
- hashkey = code.encode('utf-8') + str(options) + \
+ hashkey = code + str(options) + \
str(self.builder.config.sdedit_args)
- ofname = '%s-%s.%s' % (prefix, sha(hashkey).hexdigest(), format)
- ifname = '%s-%s.sd' % (prefix, sha(hashkey).hexdigest())
+ ofname = '%s-%s.%s' % (prefix, sha(hashkey.encode("utf-8")).hexdigest(), format)
+ ifname = '%s-%s.sd' % (prefix, sha(hashkey.encode("utf-8")).hexdigest())
infn = os.path.join(self.builder.outdir, ifname)
if hasattr(self.builder, 'imgpath'):
# HTML
@@ -92,8 +92,6 @@
ensuredir(os.path.dirname(outfn))
ensuredir(os.path.dirname(infn))
- inputfile = open(infn, "w")
- if isinstance(code, unicode):
- code = code.encode('utf-8')
+ inputfile = open(infn, "w", encoding="utf-8")
inputfile.write(code)
inputfile.close()

こんなかんじでPython3対応させます


ハマりどころ3
 except OSError, err の構文エラー

sdedit.pyの例外構文をPython3対応すればよいです。
except XXError, err → except XXError as err


ハマりどころ4
 PILで「TypeError: integer argument expected, got float」

これはPILが悪いわけではなくて、使う側(sdedit.py)が悪い。
Python2では 3/2 = 1,  3.0/2 = 1.5
 のようになっていたのが
Python3では 3//2=1,  3/2 = 1.5
 のように'/'の意味が変わっているので、/を//に修正します。

@@ -161,7 +161,7 @@

def html_tag_with_thumbnail(self, code, fname, new_width, image, imgcls):
width, height = image.size
- new_height = height * new_width / width
+ new_height = height * new_width // width
image.resize((new_width, new_height), Image.ANTIALIAS)
image.filter(ImageFilter.DETAIL)
dir, file = os.path.split(fname)

これで、グラフが出力されるようになると思います。

sdedit.pyの修正結果はアップしておきます→https://gist.github.com/yi01/9d5a0480a50271c3794f

SphinxとMatplotlibでお手軽にレポートを書こう

Matplotlibでグラフを作る方法を何度か紹介してきましたが、今回は、それをSphinx文書中に埋め込む方法をちょろっと書きます。


WindowsPython 3.3+Matplotlib 1.4.0 という少々微妙な構成でやっています。
この構成だと、リファレンス通りにやってもエラーが出て動きません。

結論から言うと、

pip install ipython

でIPythonをインストールして
sys.path.append(os.path.abspath('sphinxext'))
extensions += [
'matplotlib.sphinxext.mathmpl',
'matplotlib.sphinxext.only_directives',
'matplotlib.sphinxext.plot_directive',
'IPython.sphinxext.ipython_directive',
'IPython.sphinxext.ipython_console_highlighting']
のようにconf.pyに追記すればいいのです。
こうすれば、

インラインで。 :math:`(a + b)^2 = a^2 + 2ab + b^2` とか

ブロックで

.. math::

(a + b)^2 $=$ (a + b)(a + b)

あと、ちょっとかっこいいので

.. math::

\int_{-\infty}^{\infty} \lim_{n\to\infty}\sum_{i=0}^{n} \frac{\sin(ix)}{x} dx


.. plot::

from pylab import *
x=arange(0,10,0.1)
y=sin(x)
title(u"さいんかーぶだお")
plot(x,y,"-")
show()
みたいなことを書いて文書をビルドして、トップ画像のようなページができます。
「お、思ったより書く量が少ないぞ?!」って思いません?
ちょっと文法に癖はありますが、覚えてしまうと図もプログラムコードをそのまま埋め込んで書けますし、なによりWindowsじゃなくてLinuxでもMacでも動くのでMS Officeの心配しなくてもよいのです。
最初の1回はビルドするための環境構築が若干面倒ですが、それを乗り越えればAndroid端末ででもSONY VAIO Pみたいな超非力マシンでもメモだけはとれるので、かなり有用だと思います。

jsmathとかを使ったほうが .. math:: の処理はいろいろできるっぽいんですが、
  • ・いかんせん動作が重い
  • ・httpサーバを立ててファイルをおかないと(ローカルHTMLファイルを開くだけでは)数式が表示できない
という理由(とくに2点目が致命的)で却下・・・。


あ、最後に、どんなエラーに悩まされるか、少しだけ書いておきます。
リファレンスによると、conf.pyには
sys.path.append(os.path.abspath('sphinxext'))
extensions += [
'matplotlib.sphinxext.mathmpl',
'matplotlib.sphinxext.only_directives',
'matplotlib.sphinxext.plot_directive',
'matplotlib.sphinxext.ipython_directive',
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'ipython_console_highlighting',
'inheritance_diagram',
'numpydoc']
と追記してやれば動くように書いてますが、時代は進んでそうはいかず、
ビルド時にIPythonを使えと言われます。
C:\Users\yi01\Desktop\sphinx\example>make html
Running Sphinx v1.2.3
C:\Python33\lib\site-packages\matplotlib\cbook.py:133: MatplotlibDeprecationWarning:
The Sphinx extension ipython_console_highlighting has moved from
matplotlib to IPython, and its use in matplotlib is deprecated.
Change your import from 'matplotlib.sphinxext.ipython_directive' to
'IPython.sphinxext.ipython_directive.
warnings.warn(message, mplDeprecation, stacklevel=1)

Extension error:
Could not import extension matplotlib.sphinxext.ipython_directive (exception: Unable to import the necessary objects from IPython. You may need to install or upgrade your IPython installation.)
んで、ipythonを入れて、なんとなくextensionsの中身をmatpltlibからipythonに変えても、いろいろまだいわれます。
継承図をかくためにinheritance_diagramをインポートしないといけないんですが、それがインストールされていない、とかそういう系の。

継承図はわざわざMatplotLibを使って書かないと思うので、外して、最初の方に書いた結論に至りました。


おわり。

中国のグレート・ファイアウォールをすり抜ける方法をいくつか

VPNで家のルータにつなぐ


家のルータがVPNに対応しているなら、この方法が一番楽です。
プロトコルの制限とかもとくにないし、プロキシと違って、各アプリ側で設定が必要となることもほぼありません。

ただ、相性の問題で、ブチブチ切れることがあるので、そういう場合は②の方法を試しましょう。

SSHプロキシで1080番ポートをフォワードして、SOCKSプロキシ


家のルータがVPN非対応の場合とか、対応していても不安定の場合はこっちの方法を使います。

ssh -D 1080 xxx.hogehoge.com -N
あとは、ネットワークの設定でSOCKSプロキシを「localhost:1080」に設定します。

VPSは有料契約が必要ですが、持っている人ならこれを利用するのがいいです。
VPNに比べて速度がでます。
ただ、①とは逆に、アプリごとにプロキシ設定もってたりするとちょっと厄介です。


で、結局、PCはなんとでもなるのですが、
Androidスマートフォン使っていると、GooglePlayもGmailもハングアウトもGoogle検索もTwitterFacebookもブロックされているので、かなり困ります。
SOCKSなんてAndroidでは使えませんし、VPNはセキュリティロック掛けないとダメとかで、色々面倒です。

で、私は結局どうやっているかというと、Macの「インターネット共有」を利用して、①で接続したルートをWifiで飛ばしてます。
これで意外にもスマートフォンからGooglePlayつながりますし、メールやTwitterもできました。

ふぅ、これで発狂を免れた。