1.お絵かき
論文を執筆する時、説明のために必ずいくつかの図を描く。特に、概念が難しい時は、図の役割はとても大きい。この頃は、Power Pointで図を描くことが多くなってきた。これは、Power Pointを用いると、割に簡単に描けることに起因している。しかし、中心同士をつなぐと、どうしても直線が水平にならないなど、不満な点も多い。ヒマワリが実をつけている様子をPower Pointで描こうとしたら、大変なことになってしまうが、繰り返しパターンの多いこの手の問題は、Diagramsは得意である。
Diagramsのギャラリーがこのホームページにある。見ているとなかなか楽しくなり、自分でも描いてみたいという衝動に駆られる。
2.Diagramsを使えるようにする
DiagramsをWindows7あるいは8.1に実装するためには次のようにすればよい(注意:diagramsのインストールにはたくさんのライブラリを必要とする。途中でresource busyと出力されることがあるが、その時は再度 cabal install diagramsと入力し、中断した時点から再開させる)。
cabal update
cabal install cabal-install
cabal install diagrams
cabal install –fps diagrams
cabal install –frasterific diagrams
但し、Diagramsを実装しようとするときに、
Preprocessing library arithmoi-0.4.1.1... no location info>: Warning: Couldn't figure out LLVM version! Make sure you have installed LLVM ghc: could not execute: opt Failed to install arithmoi-0.4.1.1 cabal: Error: some packages failed to install: arithmoi-0.4.1.1 failed during the building phase. The exception was: ExitFailure 1 diagrams-1.2 depends on arithmoi-0.4.1.1 which failed to install. diagrams-contrib-1.1.2 depends on arithmoi-0.4.1.1 which failed to install.
というエラーが現れる。LLVMがインストールされていないことに起因するエラーだが、これが出たときは、arithmoiをLLVMなしでコンパイルする。これは次のようにすればよい。
cabal install -f-llvm arithmoi
また、実装してあるモジュールを再度実装したいときは次のようにする。
cabal install –-reinstall モジュール名
3.ヒマワリを描く
ギャラリーからヒマワリのソースコード(作者はJeffrey Rosenbluth)を得て、実際にシステムが動くことを確認する。ヒマワリのプログラムは次の通りである。
import Diagrams.Prelude import Diagrams.Backend.Rasterific.CmdLine import Data.Colour.Palette.BrewerSet mkCoords :: Int -> [P2] mkCoords n =[coord (fromIntegral i) | i <- [1..n]] where coord m = p2 $ fromPolar (sqrt m) (2.4 * m) fromPolar r theta = (r * cos theta, r * sin theta) floret :: Double -> Diagram B R2 floret r = circle 0.6 # lw none # fc (colors !! n) where n = floor (1.4 * sqrt r) `mod` 10 colors = black : (reverse $ brewerSet YlOrBr 9) sunflower :: Int -> Diagram B R2 sunflower n = position $ zip (mkCoords n) (florets n) where florets m = [floret (sqrt (fromIntegral i)) | i <- [1..m]] example :: Diagram B R2 example = sunflower 2000 # centerXY # pad 1.1 # bg black main = mainWith example
何とも短いプログラムある。このプログラムを実行するためには、コンパイルしなければならないが、その前に一仕事残っている。それはpaletteの実装である。
cabal install palette
コンパイル、実行は次のように行う。
ghc -–make sunflower sunflower –w 200 –h 200 –o sunflower.png
なお、ヒマワリのソースコードのタイトルはsunflower.hsである。実行結果から次の描画を得る。