|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "code", |
| 5 | + "execution_count": null, |
| 6 | + "metadata": {}, |
| 7 | + "outputs": [], |
| 8 | + "source": [ |
| 9 | + "#\n", |
| 10 | + "# Program 5.5: Nonlindro: Nonlinear driven oscillator (nonlindro.ipynb)\n", |
| 11 | + "# J Wang, Computational modeling and visualization with Python\n", |
| 12 | + "#\n", |
| 13 | + "\n", |
| 14 | + "import matplotlib.pyplot as plt # get matplotlib plot functions\n", |
| 15 | + "import ode, math as ma # get ODE, math functions \n", |
| 16 | + "%matplotlib notebook\n", |
| 17 | + "\n", |
| 18 | + "def pendulum(y, t): # y = [theta, omega], omega_0 = 1\n", |
| 19 | + " return [y[1], -ma.sin(y[0]) - b*y[1] + fd*ma.cos(omega_d*t)]\n", |
| 20 | + "\n", |
| 21 | + "def solution(n_periods): # find solutions for n_periods\n", |
| 22 | + " bins = 40 # number of points per period \n", |
| 23 | + " t, y, h = 0.0, [1.0, 0.0], 2*pi/(omega_d*bins) # init values \n", |
| 24 | + " ta, theta, omega = [], [], []\n", |
| 25 | + " for i in range(n_periods*bins):\n", |
| 26 | + " ta.append(t), theta.append(y[0]), omega.append(y[1])\n", |
| 27 | + " t, y = t+h, ode.RK4n(pendulum, y, t, h)\n", |
| 28 | + " return ta, theta, omega\n", |
| 29 | + "\n", |
| 30 | + "b, omega_d = 0.5, 0.6 # damping coeff., driving frequency\n", |
| 31 | + "subnum, pi = 1, ma.pi # subplot number, pi\n", |
| 32 | + "plt.figure()\n", |
| 33 | + "for fd in [0.7, 1.1]: \n", |
| 34 | + " ax1 = plt.subplot(2, 2, subnum) # 2x2 subplots \n", |
| 35 | + " ax2 = plt.subplot(2, 2, subnum+2)\n", |
| 36 | + " ta, theta, omega = solution(n_periods = 5)\n", |
| 37 | + " ax1.plot(ta, theta), ax2.plot(ta, omega)\n", |
| 38 | + " if (subnum == 1): # subplot specific label\n", |
| 39 | + " ax1.set_ylabel('$\\\\theta$ (rad)')\n", |
| 40 | + " ax2.set_ylabel('$\\\\omega$ (rad/s)')\n", |
| 41 | + " subnum, fdtxt = subnum + 1, '$F_d=$'+repr(fd)\n", |
| 42 | + " ax1.text(17, max(theta), fdtxt), ax2.text(17, max(omega), fdtxt)\n", |
| 43 | + " plt.xlabel('t (s)')\n", |
| 44 | + "plt.show()" |
| 45 | + ] |
| 46 | + }, |
| 47 | + { |
| 48 | + "cell_type": "code", |
| 49 | + "execution_count": null, |
| 50 | + "metadata": { |
| 51 | + "collapsed": true |
| 52 | + }, |
| 53 | + "outputs": [], |
| 54 | + "source": [] |
| 55 | + } |
| 56 | + ], |
| 57 | + "metadata": { |
| 58 | + "kernelspec": { |
| 59 | + "display_name": "Python 3", |
| 60 | + "language": "python", |
| 61 | + "name": "python3" |
| 62 | + }, |
| 63 | + "language_info": { |
| 64 | + "codemirror_mode": { |
| 65 | + "name": "ipython", |
| 66 | + "version": 3 |
| 67 | + }, |
| 68 | + "file_extension": ".py", |
| 69 | + "mimetype": "text/x-python", |
| 70 | + "name": "python", |
| 71 | + "nbconvert_exporter": "python", |
| 72 | + "pygments_lexer": "ipython3", |
| 73 | + "version": "3.6.1" |
| 74 | + } |
| 75 | + }, |
| 76 | + "nbformat": 4, |
| 77 | + "nbformat_minor": 2 |
| 78 | +} |
0 commit comments