OSXにChEMBLを入れる

今週末の勉強会の内容です。ChEMBLダンプのimportに時間がかかるので、pythonラッパー弄りたい人はChEMBLを予め入れてから参加するといいでしょう。

当日行う手順を記しておきます。

Homebrewのインストール

パッケージ管理システムです(WIndowsユーザーは飛ばしてください)。

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

こんだけ。

PostgreSQLのインストール

brewを入れてあればインストールは下のコマンドを打つだけ。(WIndowsユーザーはここから最新版のインストーラをダウンロードしてください)

brew install postgresql

インストール後にデータベースを初期化します

initdb /usr/local/var/postgres

サーバー起動

postgres -D /usr/local/var/postgres

別のターミナルから動いているか確認をします

psql -l

(エラーになる場合)

Lionだと標準でPostgreSQLがインストールされているようで、/usr/bin/psqlが存在します。homebrewでインストールする場合には/usr/local/bin/psqlなので、

which psql
/usr/local/bin/psql

とならない場合はPATHを通すか

/usr/local/bin/psql -l

と打ってください

環境変数に設定する場合は~/.bashrcに以下の行を追加します

export PATH=/usr/local/bin:$PATH

その後新しいターミナルを立ち上げた後、

psql -l

ChEMBLを入れる

ChEMBLのftpサイトから最新版(chembl_17_postgresql.tar.gz)をダウンロードします。

展開します

tar xvfz chembl_17_postgresql.tar.gz
cd chembl_17_postgresql

PostgreSQLにChEMBL用のデータベースを用意します

psql postgres
postgres=# create database chembl_17;
#Ctrl-D で抜けます

ダンプをインポートします

psql chembl_17 < chembl_17.pgdump.sql

数時間待ちます。(MBAの2013バージョンだと1.5hくらいかかったそうです)

僕のMBAではこのような結果でした。(ERRORは特に問題ありません)

ALTER TABLE
ALTER TABLE
REVOKE
ERROR:  role "postgres" does not exist
ERROR:  role "postgres" does not exist
GRANT

real    44m46.001s
user    0m10.153s
sys 0m13.130s

動作確認

$ psql chembl_17
psql (9.2.4)
Type "help" for help.

chembl_17=# select pref_name from target_dictionary;

と打ってターゲット名が表示されればきちんと動いています。

今週読んだ本(140105-140111)

青春、よさこい好きにはたまらないと思う。

ProductName 夏のくじら
大崎 梢
文藝春秋 / 1700円 ( 2008-08 )


サンカク△

ProductName 鹿男あをによし (幻冬舎文庫)
万城目 学
幻冬舎 / 720円 ( 2010-04 )


冷めないスープはない。

ProductName 5
佐藤 正午
角川書店 / ?円 ( 2007-01 )


アイデンティティを巡る旅

ProductName ムーン・パレス (新潮文庫)
ポール・オースター
新潮社 / 882円 ( 1997-09-30 )


来週末は三島で創薬系の勉強会兼新年会です

タイムテーブルと懇親会会場が決まりました。それからQAを追加しておきました。

ChEMBLはPostgres,MySQL,OracleのSQLダンプが配布されているので、データベースの構築は非常に簡単に行えます。構築を実際にやってみようというのが今回のメインです。

あわせてPythonでアクセスする方法や、イントラにWeb(REST)インターフェースを実装する方法なんかもお話できればと。

細かい話は後でまた書きますが、楽しいので興味があればお気軽に参加されるといいと思います。

今週読んだ本(131230-140104)

この著者はとても好き。妻の超然はよかった。

ProductName 妻の超然 (新潮文庫)
絲山 秋子
新潮社 / 515円 ( 2013-02-28 )


重松清は何作か読んだけどポジティブ過ぎるのよね。

ProductName その日のまえに (文春文庫)
重松 清
文藝春秋 / 610円 ( 2008-09-03 )


ドープな気分になった。あとちょっと読みづらかった。69のほうが好きかな。

ProductName 新装版 コインロッカー・ベイビーズ (講談社文庫)
村上 龍
講談社 / 920円 ( 2009-07-15 )


短篇集。「停電の夜に」はとても良かったけど、それ以外はそそられなかった。

ProductName 停電の夜に (新潮文庫)
ジュンパ ラヒリ
新潮社 / 620円 ( 2003-02-28 )


あけましておめでとうございます

老人ホームに入居した祖母の家を処分するために労働力として駆り出されていたため、掃除漬けの年末年始だった。なんとか片付いて良かった。

去年は

  • simple dietで体重の記録をつけるだけで10kg以上痩せた
  • 小説を読むようになった
  • それとともにBlogの更新も減った

今年は

  • 料理をたくさん
  • 技術を追いかけるよりはサービスを作る
  • もっと本を読む

ProductName 色彩

Familysong / Polystar Songs Inc. / 1200円 ( 2013-10-02 )


今週読んだ本(131222-131229)

著者の悲壮感というか、漂う諦め感みたいなのが好きかも。

ProductName 対岸の彼女 (文春文庫)
角田 光代
文藝春秋 / ?円 ( 2012-09-20 )


「親離れ、子離れはあるけど、夫婦離れという言葉はないよな」ということ。ざらっとした感じが残った。

ProductName 終の住処
磯崎 憲一郎
新潮社 / 1260円 ( 2009-07-24 )


面白かった。

ProductName 模倣犯3 (新潮文庫)
宮部 みゆき
新潮社 / 746円 ( 2005-11-26 )


ProductName 模倣犯〈4〉 (新潮文庫)
宮部 みゆき
新潮社 / 788円 ( 2005-12-22 )


ProductName 模倣犯〈5〉 (新潮文庫)
宮部 みゆき
新潮社 / 788円 ( 2005-12-22 )


ポジティブかな

ProductName たぶらかし (集英社文庫)
安田 依央
集英社 / 540円 ( 2012-03-16 )


好きかも

ProductName 熊の場所
舞城 王太郎
講談社 / ?円 ( 2002-10 )


このドープさは、かなり好き。江國香織が透明度高いのに対してスモーキーに感じる。

ProductName 袋小路の男 (講談社文庫)
絲山 秋子
講談社 / 420円 ( 2007-11-15 )


勢いとスピード

ProductName 阿修羅ガール (新潮文庫)
舞城 王太郎
新潮社 / 620円 ( 2005-04-24 )


「勤労感謝の日」のほうが好みかな。

ProductName 沖で待つ
絲山 秋子
文藝春秋 / 1000円 ( 2006-02-23 )


「女の過程」と「夏旅」はよかった。特に夏旅は惹きこまれた。

ProductName TRIP TRAP トリップ・トラップ
金原 ひとみ
角川書店(角川グループパブリッシング) / ?円 ( 2009-12-25 )


letter from home で泣いた

ProductName 海の仙人 (新潮文庫)
絲山 秋子
新潮社 / 380円 ( 2006-12-22 )


とても好き

ProductName 69 sixty nine (集英社文庫)
村上 龍
集英社 / 525円 ( 2013-06-26 )


逆引きPandas (DataFrame編)

R逆引きハンドブックのMatrixの章をPandasで。

ProductName R言語逆引きハンドブック
石田基広
シーアンドアール研究所 / 4830円 ( 2012-01-26 )


作者の書いた本はオススメ

ProductName Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理
Wes McKinney
オライリージャパン / 3780円 ( 2013-12-26 )


データフレームを作成する

>>> pd.DataFrame([[1,2,3],[4,5,6]])
   0  1  2
0  1  2  3
1  4  5  6

データフレームに列名と行名を追加

>>> x = pd.DataFrame([[1,2,3],[4,5,6]])
>>> pd.DataFrame([[1,2,3],[4,5,6]])
   0  1  2
0  1  2  3
1  4  5  6
>>> x = pd.DataFrame([[1,2,3],[4,5,6]])
>>> x
   0  1  2
0  1  2  3
1  4  5  6
>>> x.index = list("ab")
>>> x.columns = list("cde")
>>> x
   c  d  e
a  1  2  3
b  4  5  6

データフレームの列にアクセスする

>>> x = pd.DataFrame([[1,2,3],[4,5,6]], index=list("ab"), columns=list("cde"))
>>> x
   c  d  e
a  1  2  3
b  4  5  6
>>> x["c"]
a    1
b    4
Name: c, dtype: int64
>>> x.c
a    1
b    4
Name: c, dtype: int64

Seriesが返ってくるのでメソッドもよべる

>>> x.c.mean()
2.5
>>> x.c.sum()
5

データフレームに要素を追加する

>>> x = pd.DataFrame([[1,2,3],[4,5,6]], index=list("ab"), columns=list("cde"))
>>> y = pd.Series([7,8,9], index=list("cde"))
>>> x.append(y, ignore_index=True)
   c  d  e
0  1  2  3
1  4  5  6
2  7  8  9

データフレームを結合する

rbind

::: python
>>> x
   0  1
0  1  0
1 -2  3
>>> x.append(x)
   0  1
0  1  0
1 -2  3
0  1  0
1 -2  3
>>> pd.concat([x, x], axis=0)
   0  1
0  1  0
1 -2  3
0  1  0
1 -2  3

cbind

::: python
>>> pd.concat([x, x], axis=1)
   0  1  0  1
0  1  0  1  0
1 -2  3 -2  3

データフレームから一部を抽出する

ggplotの組込みデータを使う。 wt>3のname,disp列を抽出

>>> from ggplot import mtcars
>>> mtcars[mtcars.wt > 3][["name","disp"]]
                   name   disp
3        Hornet 4 Drive  258.0
4     Hornet Sportabout  360.0
5               Valiant  225.0
6            Duster 360  360.0
7             Merc 240D  146.7
8              Merc 230  140.8
9              Merc 280  167.6
10            Merc 280C  167.6
11           Merc 450SE  275.8
12           Merc 450SL  275.8
13          Merc 450SLC  275.8
14   Cadillac Fleetwood  472.0
15  Lincoln Continental  460.0
16    Chrysler Imperial  440.0
21     Dodge Challenger  318.0
22          AMC Javelin  304.0
23           Camaro Z28  350.0
24     Pontiac Firebird  400.0
28       Ford Pantera L  351.0
30        Maserati Bora  301.0

データフレームの列を変換する

transform

>>> x = pd.DataFrame([(1,2),(3,4),(5,6),(7,8)])
>>> x
   0  1
0  1  2
1  3  4
2  5  6
3  7  8
>>> x[2] = x[0]+2
>>> x
   0  1  2
0  1  2  3
1  3  4  5
2  5  6  7
3  7  8  9

因子ごとに組み合わせを作成する

R expand.grid() function in Python

データフレームの列や行ごとの合計を求める

::: python
>>> x
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
>>> x.sum(axis=0)
0    12
1    15
2    18
dtype: int64
>>> x.sum(axis=1)
0     6
1    15
2    24
dtype: int64

データフレームの列ごとに関数を適用する

>>> x = pd.DataFrame([(1,2),(3,4),(5,6),(7,8)])
>>> x.apply(sum)
0    16
1    20
dtype: int64

データフレームから欠損値を取り除く

>>> x = pd.DataFrame([(1,2),(3,np.nan),(np.nan,6),(7,8)])
>>> x
    0   1
0   1   2
1   3 NaN
2 NaN   6
3   7   8
>>> x.dropna()
   0  1
0  1  2
3  7  8

データフレームの列を分解、統合する

multiindex便利

>>> x = pd.DataFrame([(1,"Y"),(3,"N"),(6,"N"),(7,"Y")])
>>> x
   0  1
0  1  Y
1  3  N
2  6  N
3  7  Y
>>> y = x.groupby(1)
>>> y.head()
     0  1
1        
N 1  3  N
  2  6  N
Y 0  1  Y
  3  7  Y
>>> y.mean()
     0
1     
N  4.5
Y  4.0

縦長形式のデータフレームを横長形式に変換する

>>> x = pd.DataFrame([(1,0,1),(1,1,2),(1,2,0),(2,0,1),(2,1,1),(2,2,3),(3,0,0),(3,1,1),(3,2,2)], columns=["subject","time","conc"])
>>> x
   subject  time  conc
0        1     0     1
1        1     1     2
2        1     2     0
3        2     0     1
4        2     1     1
5        2     2     3
6        3     0     0
7        3     1     1
8        3     2     2
>>> x.pivot(index="time", columns="subject")
         conc      
subject     1  2  3
time               
0           1  1  0
1           2  1  1
2           0  3  2

データフレームを分割する

groupby

データフレームを並べ替える

>>> x = pd.DataFrame([(1,0,1),(1,1,2),(1,2,0),(2,0,1),(2,1,1),(2,2,3),(3,0,0),(3,1,1),(3,2,2)], columns=["subject","time","conc"])
>>> x
   subject  time  conc
0        1     0     1
1        1     1     2
2        1     2     0
3        2     0     1
4        2     1     1
5        2     2     3
6        3     0     0
7        3     1     1
8        3     2     2
>>> x.sort("time")
   subject  time  conc
0        1     0     1
3        2     0     1
6        3     0     0
1        1     1     2
4        2     1     1
7        3     1     1
2        1     2     0
5        2     2     3
8        3     2     2

逆引きPandas (Matrix編)

R逆引きハンドブックのMatrixの章をPandasで。

ProductName R言語逆引きハンドブック
石田基広
シーアンドアール研究所 / 4830円 ( 2012-01-26 )


Pandasの場合MatrixないからDataFrameだけど。

ProductName Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理
Wes McKinney
オライリージャパン / 3780円 ( 2013-12-26 )


行列ではなくデータフレーム

行列の演算を行う

>>> x = pd.DataFrame([[1,0],[-2,3]])
>>> y = pd.DataFrame([[-1,1],[4,2]])
>>> x.dot(y)
    0  1
0  -1  1
1  14  4
>>> x * y
   0  1
0 -1  0
1 -8  6

x %o% y はわからない

逆行列もnumpyに頼る感じ

行列の次元ごとに演算を適用する

applyでaxisで行か列かを選択する。applyはよく使う

>>> x
   0  1
0  1  0
1 -2  3
>>> x.apply(sum, axis=0) #colsum
0   -1
1    3
dtype: int64
>>> x.apply(sum, axis=1) #rowsum
0    1
1    1
dtype: int64

テータフレームを行列に変換する

numpyのarrayに

>>> x
   0  1
0  1  0
1 -2  3
>>> x.as_matrix()
array([[ 1,  0],
       [-2,  3]], dtype=int64)

行列に行名と列名を設定する

DataFrameなので

>>> x
   0  1
0  1  0
1 -2  3
>>> x.index
Int64Index([0, 1], dtype=int64)
>>> x.columns
Int64Index([0, 1], dtype=int64)
>>> x.index = list("ab")
>>> x.columns = list("cd")
>>> x
   c  d
a  1  0
b -2  3

行列の属性を確認する

>>> x.shape
(2, 2)

行列から成分を抽出する

>>> x
    0   1   2   3
0   1   2   3   4
1   5   6   7   8
2   9  10  11  12
3  13  14  15  16
>>> x.iloc[[2],[3]]
    3
2  12
>>> x.iloc[1:4,[3]]
    3
1   8
2  12
3  16

行列を結合する

rbind

concatで行か列を指定する。これもよく使う

>>> x
   0  1
0  1  0
1 -2  3
>>> x.append(x)
   0  1
0  1  0
1 -2  3
0  1  0
1 -2  3
>>> pd.concat([x, x], axis=0)
   0  1
0  1  0
1 -2  3
0  1  0
1 -2  3

cbind

>>> pd.concat([x, x], axis=1)
   0  1  0  1
0  1  0  1  0
1 -2  3 -2  3

対角行列を作成する

>>> pd.DataFrame(np.diag(range(4)))
   0  1  2  3
0  0  0  0  0
1  0  1  0  0
2  0  0  2  0
3  0  0  0  3

三角行列を作成する

>>> x
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
>>> pd.DataFrame(np.triu(x.as_matrix()))
   0  1  2
0  1  2  3
1  0  5  6
2  0  0  9
>>> pd.DataFrame(np.tril(x.as_matrix()))
   0  1  2
0  1  0  0
1  4  5  0
2  7  8  9

転置行列を作成する

>>> x
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
>>> x.T
   0  1  2
0  1  4  7
1  2  5  8
2  3  6  9

列や行ごとの和や周辺和を求める

>>> x
   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
>>> x.sum(axis=0)
0    12
1    15
2    18
dtype: int64
>>> x.sum(axis=1)
0     6
1    15
2    24
dtype: int64
>>> x.sum(axis=0).sum()
45

固有値分解、特異値分解を適用する

固有値分解

>>> x
   0  1
0  4  1
1  1  4
>>> pd.DataFrame(np.linalg.eig(x.as_matrix())[1])
          0         1
0  0.707107 -0.707107
1  0.707107  0.707107

特異値分解は知らん

逆引きPandas (ベクトル編)

pandas本はpandasの話がメインなので逆引きがないのが辛いかなと思う。pandasに慣れると手放せないけど☆

ProductName Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理
Wes McKinney
オライリージャパン / 3780円 ( 2013-12-26 )


というわけで、R言語逆引きハンドブックのベクトルの章をPandasでやってみた。

文字列を規則的に合成したベクトルを作成する

n = pd.Series(range(1,10))
n.apply(lambda r: "ID " + str(r))

因子を作成する

f = pd.Series(["y","n","y","n","n"])
pd.factorize(f)
(array([0, 1, 0, 1, 1]), array(['y', 'n'], dtype=object))

Why does pandas (python library) has no factor like variable?に書かれている

  • 因子の水準に並び順を定義する
  • 使われていない因子の水準を削除する
  • 因子の水準に大小関係を設定する
  • 因子の水準を自由に組み合わせる
  • 因子の水準ごとに関数を適用する

論理ベクトルを作成する

as.logicalに対応するものはない?

pd.Series([True, False, True, True])

論理ベクトルを計算する

>>> r = pd.Series(range(11))
>>> l = r[r > 5]
>>> l.sum()
5
>>> l.any()
True

which?

>>> l[l == True].index
Int64Index([6, 7, 8, 9, 10], dtype=int64)

空のベクトルを初期化する

>>> pd.Series([])
Series([], dtype: float64)

ベクトルの要素数を変更する

length(x) <- 10

みたいにサイズを増やすことはできない?

減らすのは

>>> a = pd.Series(range(10))
>>> a[:5]
0    0
1    1
2    2
3    3
4    4
dtype: int64

ベクトルの要素に名前をつける

>>> a = pd.Series(range(5), index=list("abcde"))
>>> a
a    0
b    1
c    2
d    3
e    4
dtype: int64
>>> a["c"]
2

ベクトルから要素を抽出する

>>> a = pd.Series(range(5), index=list("abcde"))
>>> a[list("ace")]
a    0
c    2
e    4
dtype: int64
>>> a[[0,2,4]]
a    0
c    2
e    4
dtype: int64
>>> a[(a<1)|(a>3)]
a    0
e    4
dtype: int64

ベクトルから条件に適合する添字番号を取得する

indexを使う

>>> a = pd.Series(range(5))
>>> a[(a<1)|(a>3)].index
Int64Index([0, 4], dtype=int64)

ベクトルの要素を並べ替える

>>> import numpy as np
>>> a = pd.Series(range(5))
>>> a.reindex(np.random.permutation(a.index))
2    2
0    0
3    3
1    1
4    4
dtype: int64
>>> b = a.reindex(np.random.permutation(a.index))
>>> b.sort()
>>> b
0    0
1    1
2    2
3    3
4    4
dtype: int64

ベクトルの要素を置き換える

>>> a = pd.Series(range(5))
>>> a
0    0
1    1
2    2
3    3
4    4
dtype: int64
>>> a[(a<1)|(a>3)] = 10
>>> a
0    10
1     1
2     2
3     3
4    10
dtype: int64

ベクトルに要素を追加する

>>> a = pd.Series(range(5))
>>> a.append(pd.Series([0,0,0,0]))
0    0
1    1
2    2
3    3
4    4
0    0
1    0
2    0
3    0
dtype: int64

ベクトルの要素の重複を調べる

>>> a = pd.Series([1,2,3,4,5,4,6,3,2])
>>> a.duplicated()
0    False
1    False
2    False
3    False
4    False
5     True
6    False
7     True
8     True
dtype: bool
>>> a[a.duplicated()]
5    4
7    3
8    2
dtype: int64

ベクトルの要素の重複を削除する

>>> a.drop_duplicates()
0    1
1    2
2    3
3    4
4    5
6    6
dtype: int64

R逆引きハンドブックは手元に置いておくと重宝する☆

ProductName R言語逆引きハンドブック
石田基広
シーアンドアール研究所 / 4830円 ( 2012-01-26 )


The PubChemQC project

中田さんが興味深い試みを始めていた

ChEMBLだとSARもろなデータなので、こちらで同じことやるのも楽しそう。pybel+pygamessでスクリプト書けばよさげ。

正月休みに考えてみようかな。

ChEMBLといえば来月勉強会やるので興味があれば是非参加を。(懇親会のみでももちろん歓迎です☆)