pythonスクリプト内からcommit hashを取得する

自作のパッケージを使っているとバージョニングが疎かになりがちなので、gitのcommit hashをパッケージのAPIから取得したい。 いめーじとしては、pandasのpandas.show_versionsみたいな感じ。 pandas.pydata.org

↓のポストだとgit rev-parse HEADgit describe --alwaysを使えばいいようだ。 stackoverflow.com

とりあえず以下のようなコードを書いて使ってみる。

__version__ = "0.3.2"

import os
import subprocess


# e.g. return 'b3a73ed'
def get_git_commit_hash() -> str:
    cwd = os.path.dirname(os.path.abspath(__file__))
    out = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=cwd)
    return out.strip().decode('ascii')


# e.g. return  '0.3.2+b3a73ed'
def get_version() -> str:
    out = __version__ + '+' + get_git_commit_hash()
    return out

numpy.einsumはそこそこ速い

np.einsumは配列の次元が大きくなるとnp.dotとかnp.tensordotよりかなり遅くなるような気がしていた。

しかし、公式ドキュメントによるとoptimizeフラグをgreedyかoptimalにすればかなり速くなるようだ。

numpy.org

実際に以下のnotebookで試すと、optimizeをつけるだけでかなり速くなる(使用メモリが増えているので計算途中の配列を保存している?)。

gist.github.com

git protocolがタイムアウトする

forkしてきたレポジトリのpre-commitを走らせようとすると以下のようなエラーでてタイムアウトした。

$ pre-commit run
[INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks.
[INFO] Initializing environment for git://github.com/pre-commit/mirrors-yapf.
An unexpected error has occurred: CalledProcessError: Command: ('/usr/bin/git', 'fetch', 'origin', '--tags')
Return code: 128
Expected return code: 0
Output: (none)
Errors: 
    fatal: unable to connect to github.com:
    github.com[0: 13.114.40.48]: errno=Connection timed out

↓の解答に従って調べると、git protocolのポートが開いていなかった。 stackoverflow.com

$ nmap github.com -p http,git

Starting Nmap 7.60 ( https://nmap.org ) at 2020-04-29 01:10 UTC
Nmap scan report for github.com (52.192.72.89)
Host is up (0.011s latency).
rDNS record for 52.192.72.89: ec2-52-192-72-89.ap-northeast-1.compute.amazonaws.com

PORT     STATE    SERVICE
80/tcp   open     http
8008/tcp filtered http
9418/tcp filtered git

Nmap done: 1 IP address (1 host up) scanned in 1.33 seconds

git config をいじってhttp protocolを使うようにして解決

git config --global url."https://".insteadOf git://

latexdiff-vc を使おうとしてハマった

REVTeXを使って書いていた原稿のdiffをlatexdiff-vcで取ろうとするとMissing characters near word 7714 character index: 101222-101224 Length: 1 Match: |1| (expected match marked above). みたいなエラーが出て上手く行かない。

調べると(原因も理由もよくわからないが)、--allow-spacesをつければいいらしい。

github.com

次のようにフラグをつけたら無事動いた。

latexdiff-vc -e utf-8 --git --flatten --force --allow-spaces -d diff -r <commit> main.tex

matplotlibのプロットでtype 3 fontを回避

matplotlibはデフォルトでtype 3 font を使っているが、論文原稿にはtype 1 fontを使えと言われることが多い。

type 1 font を使うためにrcに以下の設定を加える記事が見つかるが、xlabel/ylabelが複雑だとうまく行かない。

'ps.useafm': True,
'pdf.use14corefonts': True,
'text.usetex': True,

仕方ないので一旦svg形式で保存してrsyg-convertでフォントがアウトライン化したpdfに変換する。

# sudo apt-get install librsvg2-bin
rsvg-convert --format=pdf --output=filename.pdf filename.svg

参考サイト

matplotlibで論文用の図を作成

タイトルの通りの目的のためにmatplotlibの勉強をしたのでメモを残しておく。

次のnotebookのように図ごとに明示的にmatplotlibのrcを指定してプロット用の関数を作るのにとりあえず落ち着いている。

gist.github.com

rc

plt.rcParamsを直接いじるのは好きでないので1plt.rc_contextで設定を分離する。

rcparamsの設定はseabornのpaperスタイル が好きなのでこれをベースにする。

デフォルトのseaborn-paperスタイルからの変更は以下の通り2

  • グリッド線を細くする
  • フォントをTimes New Romanに設定
  • 上と右のspineを消す
  • グリッド線をオブジェクトより後ろに置く
  • tickを内側に向ける

図の大きさ

幅は1カラム分なら3.375インチ、2カラム分なら6.75インチ。 (高さは黄金比になるように選ぶといいらしい。)

保存時のdpiは300くらいにする。jupyter notebookを使っている場合、デフォルトのdpiは75とかなり小さいので注意。

plotter

FigureとAxesを引数に取りプロットする関数をつくると後から変更が加えやすい。

図の保存

余計な余白が入らないようにする:

fig.savefig(fname, bbox_inches="tight", pad_inches=0.0)   

保存形式は後から編集できるpdfかepsが無難。

参照リンク

Times New Roman が使えない場合 qiita.com

結局公式ドキュメントが一番わかりやすい matplotlib.org

matplotlibのバージョンが古いが面白い github.com


  1. JupyterLabやJupyter Notebookでプロットを作っているとグローバル変数が訳わからなくなりがちなのでplt.rcParamsはできるだけいじりたくない

  2. プロットの見た目をよくするとは何を最適化することなのか未だにわからない。