{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# First notebook. Learning about python, ipython notebooks" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Numpy Arrays" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# importing some commonly used python libraries\n", "import numpy as np # module for scientific computing\n", "import matplotlib.pyplot as plt # module for plotting \"a la\" matlab\n", "# this command conveniently allows you to show figures inline (i.e. within the notebook)\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Create a one dimensional numpy array with 10 elements\n", "x = np.linspace(1, 2.55, 10)\n", "print(x)\n", "\n", "# what does np.linsapce exactly do?\n", "help(np.linspace)\n", "\n", "# once you are solid with the basics of a new programming language (e.g. ############################ webpage #):\n", "# 1.) use search engines to find solutions for your particular problem\n", "# e.g.: search \"how print every odd element of array\" -> x[1::2]\n", "# 2.) once you find something cool, yet more involved (e.g., the \"pandas\" module in python),\n", "# take time to learn about this by working through online tutorials\n", "# - it's worth the effort, even if you won't remember everything right away\n", "# 3.) learn by examples: either from documentations or other people's code\n", "# 4.) learn by debugging: embrace to make, but even more to find mistakes in your code" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# learn about array slicing\n", "x = np.linspace(1, 2.55, 10)\n", "print(x)\n", "print()\n", "# numpy array indices are zero-based\n", "# note the formatted string used here with \"%f\" and \"%.1f\", which prints out a \"float\", i.e. an rational number,\n", "# e.g. \"%.1f\" prints out a float with one significant digit\n", "print(\"First and last element of array: %f %.1f\" % (x[0], x[-1]))\n", "# when slicing with \"i:j\", only elements until j-1 are included\n", "print(\"Second to 5th element of array: %s\" % (x[1:5]))\n", "print(\"Reversed array: %s\" % x[::-1])\n", "print(\"Reversed array with only odd elements until the 4th element:\\n\", x[-1:4:-2])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# one-dimensional array\n", "x = np.linspace(1, 2.5, 10)\n", "print(x)\n", "print(\"Length of numpy array:\", len(x))\n", "print(\"Shape of numpy array:\", x.shape)\n", "\n", "print()\n", "# two-dimensional array, defined by a list of lists\n", "x = np.array([[1, 2, 3], [4, 5, 6]])\n", "print(x)\n", "print(\"Length of numpy array:\", len(x))\n", "print(\"Shape of numpy array (rows, columns):\", x.shape)\n", "print(\"Transpose of 2D-array:\\n\", x.transpose() )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Plotting" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# learn a bit about plotting\n", "x = np.linspace(1,10, 100)\n", "plt.plot(x)\n", "plt.xlabel('index of array element')\n", "plt.ylabel('x')\n", "plt.title(\"Who let the dogs out?\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Now, let us create it so using variables that can be changed easily:\n", "xlow = -2.0\n", "xhigh = 2.\n", "ndiscrete = 2 * 120\n", "x = np.linspace(xlow, xhigh, ndiscrete)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot(range(len(x[120:])), 2.0 * x[120:], label = \"%s student learning curve\" % (\"motivated\"))\n", "plt.plot(range(len(x[120:])), 0.5 + 0.25 * x[120:], label = \"%12s student learning curve\" % (\"bored\"))\n", "plt.xlabel('class progression [min.]')\n", "plt.ylabel('Ultimate Wisdom [mana]')\n", "plt.title(\"Boredom kills Wisdom\")\n", "plt.legend()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Next we learn how to write small, simple functions.\n", "# See how the mandatory arguments and the default values are defined\n", "def harm_pot(xinput, k=1, xo=0.0):\n", " return k/2.*(xinput-xo)**2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Compute harmonic potential for the first element of x\n", "harm_pot(x[0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Compute harmonic potential of the last element of x\n", "harm_pot(x[-1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# EXERCISE: look up the quick \"lambda\" way to define functions, call this function \"harm_pot_lambda\"\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Compute and plot harm_pot for the entire array x\n", "plt.plot(x, harm_pot(x, k=10))\n", "plt.xlabel('x')\n", "plt.ylabel('V(x)')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Now, let us create an array with different force constants and see the effect \n", "# they have on the potential:\n", "k_vector=np.array([10, 25, 50, 100])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "# This way, we also learn how loops work and how the current plot axes work\n", "for myk in k_vector:\n", " #### EXERCISE: use the plotting function, the potential fucntion\n", " #### (for pretty printing, use label='k = %u'%k at the end of each plotting function call\n", " #### and plt.legend() at the end to add a legend\n", " \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib as mpl\n", "from mpl_toolkits.mplot3d import Axes3D\n", "%matplotlib notebook\n", "\n", "mpl.rcParams['legend.fontsize'] = 10\n", "fig = plt.figure()\n", "ax = fig.gca(projection='3d')\n", "theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)\n", "z = np.linspace(-2, 2, 100)\n", "r = z**2 + 1\n", "x = r * np.sin(theta)\n", "y = r * np.cos(theta)\n", "ax.plot(x, y, z, label='parametric curve')\n", "ax.legend()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Random Numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Learn how to draw uniformly random numbers in python\n", "r = np.random.rand(100000)\n", "# Print the first 100 entries\n", "print(r[:50])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline\n", "#\n", "# Learn how to histogram an array\n", "h, x_edges = np.histogram(r, bins = 50)\n", "\n", "# EXERCISE: Plot the histogram frequencies together with the mean of these frequencies\n", "# hint: to plot the mean for each data point of the histogram frequencies,\n", "# use np.mean(h) * np.ones(len(h))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline\n", "\n", "# probability density of the normal distribution \n", "def prob_dens_normal(x, mu, sigma):\n", " return 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (x - mu)**2 / (2 * sigma**2))\n", "\n", "# sample from a normal distribution\n", "numsamples = 10000\n", "mymu = 0\n", "mysigma = 1\n", "r = np.random.normal(loc = mymu, scale = mysigma, size = numsamples)\n", "\n", "# EXERCISE: \n", "# Plot the histogram *density* frequencies together with the corresponding probability density\n", "# Bonus EXERCISE: plot the frequencies to together with error bars, using plt.errorbar\n", "# (come up with a resaonable uncertainty measure for the error bars given \"yerr\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "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.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }