Skip to content

Instantly share code, notes, and snippets.

@kenjisato
Last active August 29, 2015 14:21
Show Gist options
  • Save kenjisato/07a51e08fbd790c020f8 to your computer and use it in GitHub Desktop.
Save kenjisato/07a51e08fbd790c020f8 to your computer and use it in GitHub Desktop.
2015 経済動学 講義資料 (2015-05-18)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 2015-05-20 資料\n",
"\n",
"力学系のシミュレーションをするのに最低限必要なこと\n",
"\n",
"+ 関数を定義すること\n",
"+ 関数を任意の回数繰り返し適用すること\n",
"\n",
"## 関数定義\n",
"\n",
"ポイント\n",
"+ `def`\n",
"+ 4つの空白"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def f(x):\n",
" return x ** 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 関数呼び出し"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"100"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f(10)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def g(x):\n",
" return x * 2"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"20"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Integer -> Integer\n",
"g(10)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"4.0"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Float -> Float\n",
"g(2.0)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 1, 2, 3]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# List -> List (期待通りではない)\n",
"g([1, 2, 3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## `for` ループ\n",
"\n",
"リストに対する操作は `for`ループを使う (`numpy`を使わないならば ... )"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"4\n",
"6\n"
]
}
],
"source": [
"x = [1, 2, 3]\n",
"for i in x:\n",
" print(i * 2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"リストを返すようにするにはこうする"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[2, 4, 6]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y = []\n",
"for i in x:\n",
" y.append(i * 2)\n",
"y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"もっとよい方法"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[2, 4, 6]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[i * 2 for i in x]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`for` は色々な局面で現れるのでマスターしておく。ただし数値計算をする場合には頼りすぎないこと"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## モジュール\n",
"\n",
"自分で作った関数をファイルに保存しておく方法。IPythonから呼び出す場合は, IPython のカレントディレクトリをファイルがある場所に移動しておく。"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'/Users/kenjisato/Dropbox/Lectures/2015/kobe-u/py/2015-05-20'"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# カレントディレクトリへのパスを表示\n",
"%pwd "
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Untitled.ipynb \u001b[34m__pycache__\u001b[m\u001b[m/ duck.py klass.py note.py\r\n"
]
}
],
"source": [
"# カレントディレクトリのファイルをリストアップ\n",
"%ls "
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"# Generators\r\n",
"\r\n",
"def logistic(x):\r\n",
" \"\"\"Logistic map\"\"\"\r\n",
" return 4 * x * (1 - x)\r\n",
" \r\n",
"def logistic_path(x, length):\r\n",
" y = [x]\r\n",
" for _ in range(length - 1):\r\n",
" y.append(logistic(y[-1]))\r\n",
" return y\r\n",
"\r\n",
"def logistic_gen(x, length):\r\n",
" for _ in range(length):\r\n",
" x1 = logistic(x)\r\n",
" yield x\r\n",
" x = x1\r\n",
" \r\n",
"\r\n",
" "
]
}
],
"source": [
"# ファイルの内容を表示\n",
"%cat note.py"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# ファイルを実行\n",
"%run note.py"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"0.6400000000000001"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"logistic(0.2)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0.2,\n",
" 0.6400000000000001,\n",
" 0.9215999999999999,\n",
" 0.28901376000000045,\n",
" 0.8219392261226504]"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"logistic_path(0.2, 5)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.2\n",
"0.6400000000000001\n",
"0.9215999999999999\n",
"0.28901376000000045\n",
"0.8219392261226504\n"
]
}
],
"source": [
"for x in logistic_gen(0.2, 5):\n",
" print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### ジェネレータ\n",
"\n",
"上で定義されている `logistic_gen` はジェネレータ関数と呼ばれるもの. 関数定義の中で `return` の代わりに `yield` を使っている. ループの中で`yield` を使うと, `yield`文が実行されるたびに関数の実行が一時停止する. デザイン上の理由でたくさんのデータを返す関数を作るよりも必要なデータをひとつずつ出力するほうが望ましい場合に使う"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def pm_gen(maxnum):\n",
" n = 0\n",
" while n < maxnum:\n",
" if n % 2 == 0:\n",
" yield 1\n",
" else:\n",
" yield -1\n",
" n += 1"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, -1, 1, -1, 1, -1, 1, -1, 1, -1]"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(pm_gen(10))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## クラス"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"import numpy as np\r\n",
"\r\n",
"class System:\r\n",
" def __init__(self, dim):\r\n",
" self.dim = dim\r\n",
" \r\n",
" def forward(self, x):\r\n",
" pass\r\n",
" \r\n",
"class Logistic(System):\r\n",
" def __init__(self, a):\r\n",
" self.a = a\r\n",
" super().__init__(dim=1)\r\n",
" # System.__init__(dim=1)\r\n",
" \r\n",
" def forward(self, x):\r\n",
" return self.a * x * (1 - x)\r\n",
" \r\n",
"class Tent(System):\r\n",
" def __init__(self, a):\r\n",
" self.a = a\r\n",
" super().__init__(dim=1)\r\n",
" \r\n",
" def forward(self, x):\r\n",
" return self.a * min(x, 1 - x)\r\n",
" \r\n",
"\r\n",
"class Linear(System):\r\n",
" def __init__(self, A):\r\n",
" self.A = A\r\n",
" super().__init__(dim=A.shape[0])\r\n",
" \r\n",
" def forward(self, x):\r\n",
" return np.dot(self.A, x)\r\n",
"\r\n",
"class NoUse:\r\n",
" def forward(self, x):\r\n",
" return 2 * x \r\n",
" \r\n",
"def run(system, x, steps):\r\n",
" for i in range(steps):\r\n",
" x1 = system.forward(x)\r\n",
" yield x\r\n",
" x = x1\r\n",
" \r\n",
" \r\n",
" \r\n",
" \r\n",
" "
]
}
],
"source": [
"%cat klass.py"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"run klass"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"A = np.array([[0.9, 0.0], [0.0, -0.5]])"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ct = Linear(A)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = np.array([2, 3])"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2 3]\n",
"[ 1.8 -1.5]\n",
"[ 1.62 0.75]\n",
"[ 1.458 -0.375]\n",
"[ 1.3122 0.1875]\n",
"[ 1.18098 -0.09375]\n",
"[ 1.062882 0.046875]\n",
"[ 0.9565938 -0.0234375]\n",
"[ 0.86093442 0.01171875]\n",
"[ 0.77484098 -0.00585938]\n"
]
}
],
"source": [
"for y in run(ct, x, 10):\n",
" print(y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### ダックタイピング\n",
"\n",
"特定のクラスのインスタンスに対して動作する関数を定義したとする. 他のクラスのインスタンスが, その関数が正常に動作するのに必要な性質を備えていれば, クラスが違っても関数が正常に実行される"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"nu = NoUse()"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(run(nu, 1, 10))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
import numpy as np
class System:
def __init__(self, f, dim):
self.f = f
self.dim = dim
def forward(self, x):
return self.f(x)
def simulate(s, *, start, steps):
x = np.array(start)
count = 0
while count < steps:
yield x
x = s.forward(x)
count += 1
def shoot(s, *, goal, steps):
for
if __name__ == "__main__":
def f(x):
A = np.array([[1.0, -0.5], [0.0, 1.0]])
return np.dot(A, x)
s = System(f, (2, 2))
path = simulate(s, start=[1., 1.], steps=10)
import numpy as np
class System:
def __init__(self, dim):
self.dim = dim
def forward(self, x):
pass
class Logistic(System):
def __init__(self, a):
self.a = a
super().__init__(dim=1)
# System.__init__(dim=1)
def forward(self, x):
return self.a * x * (1 - x)
class Tent(System):
def __init__(self, a):
self.a = a
super().__init__(dim=1)
def forward(self, x):
return self.a * min(x, 1 - x)
class Linear(System):
def __init__(self, A):
self.A = A
super().__init__(dim=A.shape[0])
def forward(self, x):
return np.dot(self.A, x)
class NoUse:
def forward(self, x):
return 2 * x
def run(system, x, steps):
for i in range(steps):
x1 = system.forward(x)
yield x
x = x1
# Generators
def logistic(x):
"""Logistic map"""
return 4 * x * (1 - x)
def logistic_path(x, length):
y = [x]
for _ in range(length - 1):
y.append(logistic(y[-1]))
return y
def logistic_gen(x, length):
for _ in range(length):
x1 = logistic(x)
yield x
x = x1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment