中野智文のブログ

データ・マエショリストのメモ

自宅macのJuliaLang環境を治す(2)

nakano-tomofumi.hatenablog.com のつづき。

xcode を入れる。

app store にて。

julia を再インストー

$ brew reinstall julia
Error: You have not agreed to the Xcode license. Please resolve this by running:
  sudo xcodebuild -license accept

とでた。そこで上記のコマンドを実行し、再び julia をインストールするのも失敗。

web の話

Can't load module libopenblas · Issue #76 · staticfloat/homebrew-julia · GitHub

やっぱりこういうのしっかり読むべきだよね。

最後の方に、次を実行しろと書いてある。

brew rm --force gcc gfortran openblas-julia arpack-julia suite-sparse-julia && brew update && brew install julia

R と Julia を既にインストールしてしまっているので、エラーが出たが(--force とは何だったか)、先にそれらを消してから、 再度実行すると、無事インストールされる。

ところが、また同じエラー。

$ brew install --HEAD julia
...
==> make prefix=/usr/local/Cellar/julia/HEAD-bac32d3 USE_BLAS64=0 TAGGED_RELEASE_BANNER="homebrew-julia release" FC=/usr/local/bin/gfortran LLVM_CONFIG=llvm-config-3.7 LLVM_VER=3.7.1 LOCALBASE=/usr/local/Cellar/julia/HEAD-bac32d3 USECLANG=1
Last 15 lines from /Users/nakanotomofumi/Library/Logs/Homebrew/julia/02.make:
            new_enter->setMetadata(LLVMContext::MD_dbg, dbg);
                                   ^~~~~~~~~~~~~
/usr/local/Cellar/llvm37-julia/3.7.1_3/lib/llvm-3.7/include/llvm/IR/DebugLoc.h:23:9: note: forward declaration of 'llvm::LLVMContext'
  class LLVMContext;
        ^
/private/tmp/julia-20170525-4774-rwb8x2/src/llvm-lower-handlers.cpp:218:29: error: incomplete type 'llvm::LLVMContext' named in nested name specifier
            sj->setMetadata(LLVMContext::MD_dbg, dbg);
                            ^~~~~~~~~~~~~
/usr/local/Cellar/llvm37-julia/3.7.1_3/lib/llvm-3.7/include/llvm/IR/DebugLoc.h:23:9: note: forward declaration of 'llvm::LLVMContext'
  class LLVMContext;
        ^
3 errors generated.
make[1]: *** [llvm-lower-handlers.o] Error 1
make[1]: *** Waiting for unfinished jobs....
make: *** [julia-src-release] Error 2

If reporting this issue please do so at (not Homebrew/brew or Homebrew/core):
https://github.com/staticfloat/homebrew-julia/issues

These open issues may also help:
julia quasi-broken after gcc update https://github.com/staticfloat/homebrew-julia/issues/238

うーむ、これもうまくいかない。

よって次のコマンドを実行。

$ brew reinstall --build-from-source openblas-julia

gfortran のコンパイル(gfortran 自身のコンパイルではありませんでした。)でしばらく時間がかかる。おそらく数時間はかかるんじゃないかな。今日はここでおしまい。と思ったらでた。

$ brew reinstall --build-from-source openblas-julia
==> Reinstalling staticfloat/julia/openblas-julia
==> Using Homebrew-provided fortran compiler.
This may be changed by setting the FC environment variable.
==> Downloading http://github.com/xianyi/OpenBLAS/archive/v0.2.19.tar.gz
==> Downloading from https://codeload.github.com/xianyi/OpenBLAS/tar.gz/v0.2.19
######################################################################## 100.0%
==> make FC=/usr/local/bin/gfortran
==> make PREFIX=/usr/local/Cellar/openblas-julia/0.2.19 install
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because Conflicts with openblas in homebrew-science..

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/openblas-julia/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/openblas-julia/lib
    CPPFLAGS: -I/usr/local/opt/openblas-julia/include

/usr/local/opt/openblas-julia/bin や、/usr/local/Cellar/openblas-julia/0.2.19/bin には何もないことを確認 ^^;

つづきは、 nakano-tomofumi.hatenablog.com

自宅のMacにRを入れる

背景

Juliaを入れ直そうと思ったら、うまくいかない。

Rを入れる。

とりあえず、Rをいれればなんとかなるかもしれない。

OS XにRをインストールするときに知っておきたいこと - Qiita

にしたがって、brew で入れる方法を試すことに

$ brew tap homebrew/science
$ brew install R

==> Installing homebrew/science/r dependency: readline
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because macOS provides the BSD libedit library, which shadows libreadline.
In order to prevent conflicts when programs look for libreadline we are
defaulting this GNU Readline installation to keg-only..

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/readline/lib
    CPPFLAGS: -I/usr/local/opt/readline/include

==> Installing homebrew/science/r dependency: gettext
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because macOS provides the BSD gettext library & some software gets confused if both are in the library path.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/gettext/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/gettext/lib
    CPPFLAGS: -I/usr/local/opt/gettext/include

==> Installing homebrew/science/r
==> Caveats
To enable rJava support, run the following command:
  R CMD javareconf JAVA_CPPFLAGS=-I/System/Library/Frameworks/JavaVM.framework/Headers
If you've installed a version of Java other than the default, you might need to instead use:
  R CMD javareconf JAVA_CPPFLAGS="-I/System/Library/Frameworks/JavaVM.framework/Headers -I/Library/Java/JavaVirtualMachines/jdk<version>.jdk/"
(where <version> can be found by running `java -version`, `/usr/libexec/java_home`, or `locate jni.h`), or:
  R CMD javareconf JAVA_CPPFLAGS="-I/System/Library/Frameworks/JavaVM.framework/Headers -I$(/usr/libexec/java_home | grep -o '.*jdk')"

気になるメッセージは記録しておこう。

動作確認

> binom.test(1,2)

    Exact binomial test

data:  1 and 2
number of successes = 1, number of trials = 2, p-value = 1
alternative hypothesis: true probability of success is not equal to 0.5
95 percent confidence interval:
 0.01257912 0.98742088
sample estimates:
probability of success
                   0.5

問題なし、と思う。

virtualbox の時刻がずれている

背景

make をやっても、うまくいかないことがある。 ターゲットを共通化するために、前処理の複数のターゲットのアウトプットを同じものにしてあったが、 時刻がずれているため?、本来意図してない処理が呼ばれてしまう模様。

ntpd がインストールされているかどうかを確認する。

$ ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 ntp00.iij.net   210.130.188.1    3 u  332 1024  377    2.571  1065461 2351.27
 ntp01.iij.net   210.130.188.1    3 u  621 1024  377    2.735  1066141 1942.83
 ntp02.iij.net   210.130.188.1    3 u  761 1024  377    2.874  1065675 2352.60

で確認。大幅にずれていることを確認した。

時刻を設定する

大幅にずれている場合は自動調整されない。 ntpdate ntp.nict.jp などのコマンドで設定するが、先に ntpd を止めておかないと、

24 May 13:16:45 ntpdate[8055]: the NTP socket is in use, exiting

みたいなエラーが出てしまう。

$ sudo service ntp stop
 * Stopping NTP server ntpd
   ...done.
$ sudo ntpdate ntp.nict.jp
24 May 13:44:18 ntpdate[8105]: step time server 133.243.238.243 offset 1071.115719 sec
$ sudo service ntp start
 * Starting NTP server ntpd
   ...done.
$ ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 ntp00.iij.net   210.130.188.1    3 u   11   64    1    2.312    0.382   0.000
 ntp01.iij.net   210.130.188.1    3 u   10   64    1    3.126    0.034   0.000
 ntp02.iij.net   210.130.188.1    3 u    9   64    1    3.070   -0.137   0.000

防止策

また発生するでしょう。

makefile のターゲットの先頭に、次のように書いた。

test  `ntpq -p | grep '*' | wc -l` -ge 1 # clock sync check

意味:ntpq -p で * の行が一行以上あれば(syncされたサーバがある)OK。なければ失敗。

自宅macのJuliaLang環境を治す

背景

色々不具合があるので修正しよう。

brew doctor のメッセージ

Warning: You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built. Run `brew link` on these:
  cloog
  cloog018-julia
  gmp4-julia
  isl
  isl011-julia
  suite-sparse42-julia

取り敢えずこんな感じで実行してみよう。

brew link cloog gmp4-julia isl suite-sparse42-julia

すると、

Linking /usr/local/Cellar/cloog/0.18.4_1... 8 symlinks created
Linking /usr/local/Cellar/gmp4-julia/4.3.2...
Error: Could not symlink include/gmp.h
Target /usr/local/include/gmp.h
is a symlink belonging to gmp. You can unlink it:
  brew unlink gmp

To force the link and overwrite all conflicting files:
  brew link --overwrite gmp4-julia

To list all files that would be deleted:
  brew link --overwrite --dry-run gmp4-julia

とりあえず、次を実行

brew unlink gmp4
brew link --overwrite gmp4-julia

そんな感じで次を実行。

brew link cloog018
brew link --overwrite cloog018-julia
brew link isl
brew link --overwrite isl011-julia
brew link suite-sparse42-julia

とりあえず何も出なくなった。

julia 起動時のエラーメッセージ

WARNING: Error during initialization of module GMP:
ErrorException("The dynamically loaded GMP library (version 4.3.2 with __gmp_bits_per_limb == 64)
does not correspond to the compile time version (version 6.1.2 with __gmp_bits_per_limb == 64).
Please rebuild Julia.")
WARNING: Error during initialization of module LinAlg:
ErrorException("could not load library "libopenblas"
dlopen(libopenblas.dylib, 1): Library not loaded: /usr/local/opt/gcc/lib/gcc/6/libgfortran.3.dylib
  Referenced from: /usr/local/opt/openblas-julia/lib/libopenblas.dylib
  Reason: image not found")
WARNING: Error during initialization of module CHOLMOD:
ErrorException("could not load library "libcholmod"
dlopen(libcholmod.dylib, 1): Library not loaded: /usr/local/opt/gcc/lib/gcc/6/libgfortran.3.dylib
  Referenced from: /usr/local/opt/openblas-julia/lib/libopenblasp-r0.2.19.dylib
  Reason: image not found")

相当やられているに違いない。

決断はすばやく。次のコマンドを実行

$ brew uninstall julia

すると、

Uninstalling /usr/local/Cellar/julia/0.5.1... (752 files, 143.6MB)
julia 0.5.0 is still installed.
Remove all versions with `brew uninstall --force julia`.

はい。やります。

そして julia をアンインストールし、インストールし直す。

はい。また同じエラー

面倒だなー。

homebrew 全部消去

もう面倒だからこれで。悩む必要など無い。このリンクの不具合など到底直せるわけがない。

brew remove --force --ignore-dependencies $(brew list)

emacs とか、font とか消えていったような気がしたな…。まあいいか。

再インストール時のメッセージ。

==> Installing julia from staticfloat/julia
==> Installing dependencies for staticfloat/julia/julia: gmp, mpfr, libmpc, isl, gcc, libffi, staticfloat/julia/llvm37-julia, pcre2, fftw, openssl, libssh2, libgit2, mbedtls, staticfloat/julia/openblas-julia, staticfloat/julia/arpack-julia, staticfloat/julia/suite-sparse-julia

次のメッセージでインストールが完了した。

Documentation and Examples have been installed into:
/usr/local/opt/julia/share/julia

Test suite has been installed into:
/usr/local/opt/julia/share/julia/test

To perform a quick sanity check, run the command:
brew test -v julia

To crunch through the full test suite, run the command:
/usr/local/opt/julia/bin/julia -e "Base.runtests()"
==> Summary
🍺  /usr/local/Cellar/julia/0.5.1: 752 files, 143.6MB

念のためテスト

brew test -v julia

すごいいっぱいエラーが出るんですけど。

dlopen(libopenblas.dylib, 1): Library not loaded: /usr/local/opt/gcc/lib/gcc/6/libgfortran.3.dylib

とりあえず、現状確認。

$ ls /usr/local/opt/gcc/lib/gcc/
7

ほう?

今なら何も消えても怖くはない。

cd /usr/local/opt/gcc/lib/gcc
ln -s 7 6

どりゃ。

/usr/local/opt/gcc/lib/gcc/7/libgfortran.4.dylib

はあるみたいだけど、libgfortran.3.dylib はないらしい。

つづきは、

nakano-tomofumi.hatenablog.com

luigi と格闘中

背景

luigi と airflow と make を比較している。

luigi と格闘中

big query のクエリを書き換えたので再実行

あれ? 再実行されない。

ズバリな記事が見つかる。

datapipelinearchitect.com

なるほど…。というか、removing all intermediate and final outputs って…。 downstream のすべての出力を調べて削除しないといけないわけだよ。それが面倒だから、こういったツールを使っているのに。 ちなみに、make で touch 作戦でチマチマ依存関係書いていく作戦だと、依存関係のあるターゲットは全て実行され更新される。

一つの解決策としては、 upstream の依存ファイルのハッシュ値みたいなものをパラメータとして持たせる方法が考えられる。 パラメータが変われば、別のタスクとして見なされるので再実行される(はず。luigji も詳しくないのでよくわからないが) downstream では upstream の全ての依存ファイルのハッシュ値をパラメータとして渡す必要があるが、各クラスの依存ファイルが何であるかを示すような interface を持ち、かつ upstreamの全ての依存ファイルのハッシュ値を取得しパラメータとして自動的に渡す関数を実装した task class を使うことにすれば解決するかもしれない。 誰かそういうの作っていないかな…(自分で作れよ)。いやもっとマシな解決策があるのかもしれないが…

もうちょっと調べると、complete を再実装した例が見つかった。

stackoverflow.com

こちらは make のように出力のタイムスタンプを見て完了かどうかを判断する。 ただし、big query とかのタイムスタンプに対応させるには、色々頑張らないといけないかもしれない。

luigi の RangeDaily

luigi の backfill コマンドとして、RangeDaily というのがあり、 start と stop で日付を指定する。

luigi --module xxx RangeDaily --of XXX   --start 2017-02-07 --stop 2017-05-17 --task-limit 100 --workers 5

こんな感じ。ところが、

DEBUG: Checking if RangeDaily(of=XXX, of_params={}, reverse=False, task_limit=100, now=None, param_name=None, start=2017-02-07, stop=2017-05-17, days_back=100, days_forward=0) is complete
DEBUG: Actually checking if range [2017-02-09, 2017-05-16] of XXX is complete

と出て、 2017-02-09 と、2017-05-16 に勝手に狭められている…。stopがその日を含まない、としても、start は2日もずれてるだろ。

以下に書いてあった。

http://luigi.readthedocs.io/en/stable/api/luigi.tools.range.html#luigi.tools.range.RangeDailyBase.days_back

days_back 今日から何日前まで遡れるか、を決めているらしい。無限に過去に遡ったりするのを防止するために。 デフォルトは100ということで、それにひかかっただけの模様。ちなみに、stop の方は、exclusive だそうで、その日を含まない、ということを意味する。 stop でその日を含まないって、誰得なんだろうか。backfill としてはその日(特に当日)を含むと色々まずいのかな…。

Wilson score interval を使う。

背景

以前、

blog.goo.ne.jp

にて、Wilson score interval with continuity correction の式のテンプレートを書いたが、本当は外側に条件分岐 if が必要だったり、判別式の中が負になることもあったりと、ちょっと注意して使う必要があった(おいおい)。ちなみに、Wald法とよばれる信頼区間を求める方法があるが、これは正しくないかもしれない信頼区間(こんなものを信頼区間と呼べるのか)を求める方法なので絶対に使わないように。

そこで今回は単なる(with continuity correction が付かない) wilson score interval のテンプレートを作成する。

Wilson score interval テンプレート

前回は P という標本平均をもとにテンプレートを作ったが、結局、P を計算する式が必要で、置換後もっと複雑になるので、成功した回数をX、試行回数をN、標準正規分布の分位数を Zとすると、

UCB: (X+Z*Z/2+Z*sqrt(X*(N-X)/N+Z*Z/4))/(N+Z*Z)
LCB: (X+Z*Z/2-Z*sqrt(X*(N-X)/N+Z*Z/4))/(N+Z*Z)

なんとシンプルな。UCBは信頼上限、LCBは信頼下限を示す。p=0.05(95%信頼区間)ならZ=1.96 となる。

もし、Xが0(もしくはnull)の場合は、

UCB: (Z*Z)/(N+Z*Z) 
LCB: 0 

となる。

参考

数式

https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval

文献

Wilson の論文 http://www.barestatistics.nl/uploads/1/1/7/9/11797954/wilson_1927.pdf

追記

Z=1.96 バージョン

UCB: (X+1.96*1.96/2+1.96*sqrt(X*(N-X)/N+1.96*1.96/4))/(N+1.96*1.96)
LCB: (X+1.96*1.96/2-1.96*sqrt(X*(N-X)/N+1.96*1.96/4))/(N+1.96*1.96)

airflow と格闘中 (11)

nakano-tomofumi.hatenablog.com

のつづき

pysqlite2 がない

apt-get install sqlite3-dev
pip install pysqlite

click がない?

次のエラー

[2017-05-15 10:12:53,877] {__init__.py:57} INFO - Using executor SequentialExecutor
Traceback (most recent call last):
  ....
  File "/xxxxxxxxx/python/venv/lib/python2.7/site-packages/flask/cli.py", line 17, in <module>
    import click
pip install flask

を実行しても、インストール済みと表示される。

次を参考に、

python flask import error - Stack Overflow

sudo apt-get install python-flask

を実行。virtualenv を使っているからか、解決せず。 pip install flask のメッセージをもう一度確認してみる。

Requirement already satisfied (use --upgrade to upgrade): flask in /xxxxxxxxx/python/venv/lib/python2.7/site-packages

そういうこと?

pip install --upgrade flask

で無事インストール。私の python 環境構築力が問われる。

つづきは、 nakano-tomofumi.hatenablog.com