<jupyter_start><jupyter_text>01. First-Order Equations<jupyter_code>import numpy as np
import scipy
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import IPython
import sklearn
import nltk

from IPython.display import Image
%matplotlib inline

import datetime
dt = datetime.datetime.now()

print(
'''{}-{}-{} {}:{}:{}
----------------------
numpy\t\t{}
scipy\t\t{}
pandas\t\t{}
matplotlib\t{}
----------------------
ipython\t\t{}
----------------------
sklearn\t\t{}
nltk\t\t{}'''.format(
    dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 
    np.__version__, 
    scipy.__version__, 
    pd.__version__, 
    matplotlib.__version__, 
    IPython.__version__, 
    sklearn.__version__, 
    nltk.__version__))

c = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']<jupyter_output>2019-5-8 19:43:1
----------------------
numpy		1.15.2
scipy		1.1.0
pandas		0.24.1
matplotlib	3.0.0
----------------------
ipython		7.2.0
----------------------
sklearn		0.20.0
nltk		3.2.5<jupyter_text>01.01. The Simplest Example<jupyter_code>def dx_dt(x, a):
    return x * a

def x(x, a, k):
    return k * np.e ** (a * t)

def flow(x0, t0, iteration, dt):
    xs = np.array([x0])
    ts = np.array([t0])
    
    for i in range(iteration):
        xi = xs[i]
        ti = ts[i]
        xs = np.append(xs, xi + dx_dt(xi, a)*dt)
        ts = np.append(ts, ti + dt)
    return xs, ts

k, t = 1, 1
aa = np.array([-1, 0, 1])

fig, axs = plt.subplots(figsize=(15, 5), ncols=3, nrows=1, sharex=True, sharey=True)

# ax.plot()
X, T = np.meshgrid(np.linspace(-1.0, 1.0, 10), np.linspace(0.0, 2.0, 10))
x = np.linspace(-1.0, 1.0, 9)
x0s = x#np.linspace(-.75, .75, 10)

for ax, a in zip(axs, aa):
#     ax.quiver(T, X, np.repeat(t, len(X)*len(T)), dx_dt(X, a), alpha=1, color=c[2])
    for x0 in x0s:
        xs, ts = flow(x0, 0, 47, .1)
        ax.plot(ts, xs, color=c[0])
    ax.quiver(np.repeat(5, len(x)), x, np.repeat(0, len(x)), dx_dt(x, a), color=c[2])
    ax.grid(True)
    ax.set_xlabel(r'$t$')
    if a > 0:
        ax.set_title('\n' r'$a > 0$')
        ax.scatter(5, 0, marker='o', facecolor='none', edgecolor=c[2], label='Unstable')
    elif a < 0:
        ax.set_title('\n' r'$a < 0$')
        ax.scatter(5, 0, marker='o', facecolor=c[0], edgecolor=c[2], label='Stable')
    elif a == 0:
        ax.set_title(r'$\frac{dx}{dt} = ax$' '\n' r'$a = 0$')
        ax.scatter(np.repeat(5, len(x)), x, color=c[2], label='Stable')
    
#     ax.set_xlim(0, 2.1)
    ax.set_ylim(-1.2, 1.2)
    ax.legend(loc='upper center')

axs[0].set_ylabel(r'$x$')
# axs[1].set_title()


plt.tight_layout()
# plt.savefig('fig/fig0101.png')
plt.show()
def dx_dt(x, a):
    return x * a

def x(x, a, k):
    return k * np.e ** (a * t)

def flow(x0, t0, iteration, dt):
    xs = np.array([x0])
    ts = np.array([t0])
    
    for i in range(iteration):
        xi = xs[i]
        ti = ts[i]
        xs = np.append(xs, xi + dx_dt(xi, a)*dt)
        ts = np.append(ts, ti + dt)
    return xs, ts

k, t = 1, 1
aa = np.array([-1, 0, 1])

fig, axs = plt.subplots(figsize=(15, 5), ncols=3, nrows=1, sharex=True, sharey=True)

# ax.plot()
x, t = np.linspace(-1.0, 1.0, 10), np.linspace(0.0, 4.0, 10)
X, T = np.meshgrid(x, t)
x0s = x#np.linspace(-.75, .75, 10)

for ax, a in zip(axs, aa):
    ax.quiver(T, X, np.tile(1, (len(X), len(T))), dx_dt(X, a), np.abs(dx_dt(X, a)), cmap='viridis', alpha=1)
    
    if a != 0:
        ax.quiver(np.repeat(5, len(x)), x, np.repeat(0, len(x)), dx_dt(x, a), np.abs(dx_dt(x, a)), cmap='viridis')
        
    ax.grid(True)
    ax.set_xlabel(r'$t$')
    if a > 0:
        ax.set_title('\n' r'$a > 0$')
        ax.scatter(5, 0, marker='o', facecolor='none', edgecolor=c[4], label='Unstable')
    elif a < 0:
        ax.set_title('\n' r'$a < 0$')
        ax.scatter(5, 0, marker='o', facecolor=c[4], edgecolor=c[4], label='Stable')
    elif a == 0:
        ax.set_title(r'$\frac{dx}{dt} = ax$' '\n' r'$a = 0$')
        ax.scatter(np.repeat(5, len(x)), x, color=c[4], label='Stable')
    
#     ax.set_xlim(0, 2.1)
    ax.set_ylim(-1.2, 1.2)
    ax.legend(loc='upper center')

axs[0].set_ylabel(r'$x$')
# axs[1].set_title()


plt.tight_layout()
# plt.savefig('fig/fig0101.png')
plt.show()<jupyter_output><empty_output><jupyter_text>01.02. The Logistic Population Model<jupyter_code>def logistic(x, a):
    return a * x * (1 - x)

def flow(x0, t0, iteration, dt):
    xs = np.array([x0])
    ts = np.array([t0])
    
    for i in range(iteration):
        xi = xs[i]
        ti = ts[i]
        xs = np.append(xs, xi + logistic(xi, a)*dt)
        ts = np.append(ts, ti + dt)
    return xs, ts

a, t = 1, 1

X, T = np.meshgrid(np.arange(0.0, 1.5, 0.1), np.arange(0.0, 1.5, 0.1))
x0s = np.linspace(0.0, 1.2, 25)

fig, ax = plt.subplots(figsize=(5, 5))

for x0 in x0s:
    xs, ts = flow(x0, 0, 75, .1)
    ax.plot(ts, xs, c=c[0])

# ax.quiver(T, X, np.repeat(1, len(T)*len(X)), dx_dt(X, a), color=c[2])
ax.grid(True)
ax.set_xlabel(r'$t$')
ax.set_ylabel(r'$x$')
ax.set_title(r"$x' = ax (1 - \frac{x}{N})$")
ax.set_ylim(-.05, 1.25)

ax.quiver(np.repeat(8, len(x0s)), x0s, np.repeat(0, len(x0s)), logistic(x0s, a), color=c[2], alpha=.75)
ax.scatter(8, 0, marker='o', label='', edgecolor=c[2], facecolor='none')
ax.scatter(8, 1, marker='o', edgecolor=c[0], facecolor=c[2])


plt.tight_layout()
# plt.savefig('fig/fig0103.png')
plt.show()
def logistic(x, a):
    return a * x * (1 - x)

a = 1

n = 10
t, x = np.linspace(0, 9.5, n), np.linspace(-.2, 1.2, n)
T, X = np.meshgrid(t, x)
dT = np.tile(1, (n, n))
fig, ax = plt.subplots(figsize=(5,5))

ax.streamplot(T, X, dT, logistic(X, a), 
              color=(np.sqrt(np.abs(dT) + np.abs(logistic(X, a)))), 
              cmap='viridis')
ax.quiver(np.repeat(10, n), x, np.repeat(0, n), logistic(x, a), np.abs(logistic(x, a)), cmap='viridis')
ax.scatter(10.0, 1.0, marker='o', facecolor=c[4], edgecolor=c[4], label='Stable')
ax.scatter(10.0, 0.0, marker='o', facecolor='none', edgecolor=c[4], label='Unstable')

ax.grid(True)
ax.set_title(r"$x' = ax(1-x)$")
ax.set_xlabel(r'$t$')
ax.set_ylabel(r'$x$')
ax.set_xlim(0, 10.2)
ax.set_ylim(-0.2, 1.2)
ax.legend(loc='best')

plt.tight_layout()
# plt.savefig('fig/fig.png')
plt.show()
def logistic(x, a):
    return a * x * (1 - x)

a = 3.2
x = np.linspace(-0.05, 1.05, 30)

fig, ax = plt.subplots(figsize=(5, 5))

ax.plot(x, logistic(x,a))

ax.set_title(r"$x' = ax(1 - x)$")
ax.grid(True)
ax.set_xlim(-0.05, 1.05)
ax.set_ylim(logistic(-0.05, a), logistic(0.5, a)+.05)

plt.tight_layout()
plt.show()
def dx_dt(x):
    return x - x**3


def stream(x0, t0, iteration, delta):
    xs = np.array([x0])
    #ys = np.array([y0])
    ts = np.array([t0])
    for i in range(iteration):
        xi = xs[i] + dx_dt(xs[i]) * delta
        xs = np.append(xs, xi)
        #yi = ys[i] + dy_dt(ys[i]) * delta
        #ys = np.append(ys, yi)
        ti = ts[i] + delta
        ts = np.append(ts, ti)
    return xs, ts

X, T = np.meshgrid(np.linspace(-1.3, 1.3, 20), np.linspace(0, 2.2, 20))
x0s = np.linspace(-1.2, 1.2, 11)

fig, ax = plt.subplots(figsize=(10, 5), ncols=2, sharey=True)

ax[0].quiver(T, X, np.tile(1, (20, 20)), dx_dt(X), np.abs(dx_dt(X)))

for x0 in x0s:
    xs, ts = stream(x0, 0, 244, .01)
    ax[1].plot(ts, xs, color=c[0])#, alpha=.75)

ax[1].quiver(np.repeat(2.5, len(x0s)), x0s, np.repeat(0, len(x0s)), dx_dt(x0s), dx_dt(x0s), alpha=.7)
ax[1].scatter(2.5, -1, facecolor=c[0], edgecolor=c[0], label='stable')
ax[1].scatter(2.5, 0, facecolor='none', edgecolor=c[0], label='unstable')
ax[1].scatter(2.5, 1, facecolor=c[0], edgecolor=c[0])#, label='stable')

# ax.streamplot(T, X, dt(T), dx_dt(X))#, 
#               density=2, 
#               color=np.sqrt(np.repeat(1, len(T)*len(X))**2+dx_dt(X)**2), 
#               cmap='YlGnBu')

ax[0].grid(True)
ax[0].set_xlabel(r'$t$')
ax[0].set_ylabel(r'$x$')
ax[1].grid(True)
ax[1].legend(loc='best')
ax[1].set_xlabel(r'$t$')

plt.tight_layout()
# plt.savefig('fig/fig0105.png')
plt.show()
def dx_dt(x):
    return x - x**3


T, X = np.meshgrid(np.linspace(0, 9.5, 10), np.linspace(-1.1, 1.1, 10))
dT = np.tile(1, (10, 10))
x = np.linspace(-1.1, 1.1, 10)
fig, ax = plt.subplots(figsize=(5,5))
ax.streamplot(T, X, dT, dx_dt(X), 
              color=np.sqrt(dT**2 + dx_dt(X)**2), cmap='viridis')

ax.quiver(np.repeat(10, len(x)), x, np.repeat(0, len(x)), dx_dt(x), np.abs(dx_dt(x)))#, cmap='viridis')
ax.scatter(10, -1, marker='o', facecolor=c[0], edgecolor=c[0], label='Stable')
ax.scatter(10, 1, marker='o', facecolor=c[0], edgecolor=c[0])
ax.scatter(10, 0, marker='o', facecolor='white', edgecolor=c[4], label='Unstable')

ax.grid(True)
ax.set_title(r"$x' = x - x^3$")

plt.tight_layout()
# plt.savefig('fig/fig0105.png')
plt.show()<jupyter_output><empty_output><jupyter_text>01.03. Constant Harversting and Bifurcations<jupyter_code>def f_h(x, a, h):
    return a * x * (1 - x) - h

def h(x, a):
    return a*x * (1 - x)

a, n = 1, 20

hh, xx = np.linspace(0, .3, n), np.linspace(-0.1, 1.1, n)
H, X = np.meshgrid(hh, xx)
x_u, x_s = np.linspace(0.0, 0.5, 100), np.linspace(0.5, 1.0, 100)


fig, ax = plt.subplots(figsize=(5, 5))

ax.quiver(H, X, np.tile(0, (n, n)), f_h(X, a, H), np.abs(f_h(X, a, H)))
ax.plot(h(x_s, a), x_s, c=c[4], label='stable')
ax.plot(h(x_u, a), x_u, c=c[4], linestyle='--', label='unstable')

ax.set_title(r'$f_h(x) = ax(1 - x) - h$')
ax.set_xlabel(r'$h$')
ax.set_ylabel(r'$x$')
ax.set_xlim(0.0, 0.3)
ax.set_ylim(-0.1, 1.1)
ax.grid(True)
ax.legend(loc='lower right')

plt.tight_layout()
# plt.savefig('fig/fig0107.png')
plt.show()
def g_a(x, a):
    return x**2 - a*x

n = 17

a, x = np.linspace(-1, 1, n), np.linspace(-1, 1, n)
A, X = np.meshgrid(a, x)
a0 = np.linspace(-1, 0, n)
a1 = np.linspace(0, 1, n)

fig, ax = plt.subplots(figsize=(5, 5))

ax.quiver(A, X, np.tile(0, (n, n)), g_a(X, A), np.abs(g_a(X, A)))
ax.plot(a0, a0, c=c[4], label='stable')
ax.plot(a1, np.repeat(0, len(a1)), c=c[4])
ax.plot(a0, np.repeat(0, len(a0)), c=c[4],  label='unstable', linestyle='--')
ax.plot(a1, a1, c=c[4], linestyle='--')

ax.set_xlabel(r'$a$')
ax.set_ylabel(r'$x$')
ax.grid(True)
ax.set_title(r"$x' = x (x - a)$")
ax.legend(loc='best')
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)

plt.tight_layout()
# plt.savefig('fig/fig0108.png')
plt.show()<jupyter_output><empty_output><jupyter_text>01.04. Periodic Harvesting and Periodic Solutions<jupyter_code>def logistic(x, t):
#     return a * x * (1 - x) - h * (1 + np.sin(2*t*np.pi))
    return a * x * (1 - x) - h * (1 + np.sin(2*np.pi*t))

a, h = 5.0, .8
n = 10
t, x = np.linspace(0, 2, n), np.linspace(-0.2, 1.2, n)
T, X = np.meshgrid(t, x)

fig, ax = plt.subplots(figsize=(10,5))

ax.streamplot(T, X, np.tile(1, (n, n)), logistic(X, T), color=np.abs(logistic(X, T)), cmap='viridis')

ax.set_title(r'$\frac{dx}{dt} = ax(1-x) - h(1+\sin{(2\pi t)})$')# '\n' r'$(a, h) = $' '({}, {})'.format(a, h))
ax.text(1.0, -0.15, (r'$(a, h) = $' '({}, {})'.format(a, h)), 
        ha='center', va='bottom',
        bbox=dict(fc='white', alpha=.7))
ax.grid(True)
ax.set_xlim(0, 2)
ax.set_ylim(-0.2, 1.2)
ax.set_xlabel(r'$t$')
ax.set_ylabel(r'$x$')

plt.tight_layout()
plt.savefig('fig/fig0109.png')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.25026804860614726, 'fraction_numerical': 0.05521801286633309, 'mean_word_length': 3.2705074399084317, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '638367', 'license': 'MIT', 'n_tokens_mistral': 5697, 'n_tokens_neox': 5396, 'n_words': 1049, 'path': '01/code.ipynb', 'repo_name': 'shumez/DEDSIC', 'size': '11192'}