{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "
\n", "**This is a fixed-text formatted version of a Jupyter notebook.**\n", "\n", " You can contribute with your own notebooks in this\n", " [GitHub repository](https://github.com/gammapy/gammapy-extra/tree/master/notebooks).\n", "\n", "**Source files:**\n", "[using_numpy.ipynb](../_static/notebooks/using_numpy.ipynb) |\n", "[using_numpy.py](../_static/notebooks/using_numpy.py)\n", "
\n" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "# Rapid introduction on using numpy, scipy, matplotlib\n", "\n", "This is meant to be a very brief reminder. It is strongly suggested to refer to more detailed\n", "introductions and tutorials see for instance:\n", "- [A Whirlwind tour of Python](http://nbviewer.jupyter.org/github/jakevdp/WhirlwindTourOfPython/blob/master/Index.ipynb)\n", "- [Python data science handbook](http://nbviewer.jupyter.org/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/Index.ipynb)\n", "- [Scipy lectures](http://www.scipy-lectures.org/)\n", "\n", "## Introduction\n", "\n", "Here we will look at :\n", "- basic features regarding array manipulation and indexing\n", "- do a bit of plotting with matplotlib\n", "- use a number of useful scipy features\n", "- see an example of vectorization with a simple Monte Carlo problem" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "## numpy: arrays, indexing etc\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true, "deletable": true, "editable": true }, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "array([3, 4, 5])" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.array([3,4,5])" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "array([[1, 2],\n", " [3, 4]])" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.array([[1, 2],[3,4]])" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "### linearly spaced 1D array\n", "np.linspace(1.,10.,10)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "array([ 1. , 1.29154967, 1.66810054, 2.15443469,\n", " 2.7825594 , 3.59381366, 4.64158883, 5.9948425 ,\n", " 7.74263683, 10. ])" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "### log spaced 1D array\n", "np.logspace(0.,1.,10)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "array([ 0., 0., 0., 0., 0.])" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "### 1D array of zeros\n", "np.zeros(5)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "array([[ 0., 0., 0.],\n", " [ 0., 0., 0.],\n", " [ 0., 0., 0.]])" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "### 2D array of zeros\n", "np.zeros((3,3))" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Types and casts\n", "\n", "See numpy [dtypes](https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 1 1 1 2 2 3 4 5 7 10]\n" ] } ], "source": [ "x_int = np.logspace(0.,1.,10).astype('int') # cast array as int\n", "print(x_int)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "x_int[1] = 2.34 # 2.34 is cast as int\n", "print(x_int[1])" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "data": { "text/plain": [ "dtype('" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "values = poisson_sample_maximum_better(mu,N,Ntrials)\n", "\n", "### Make and plot the normalized histogram\n", "### We define the binning ouselves to have bins for each integer\n", "bins = np.arange(0, 10 * mu)\n", "histo = plt.hist(values, bins=bins, normed=True, log=True)\n", "\n", "### Now compare to the analytical solution\n", "from scipy.special import gammaincc\n", "\n", "### Define a lambda function to compute analytical solution\n", "proba = lambda nv, Nr, mu_p : gammaincc(nv + 1, mu_p) ** Nr - gammaincc(nv, mu_p) ** Nr\n", "\n", "x = 0.5 * (bins[:-1] + bins[1:])\n", "y = proba(bins[:-1], N, mu)\n", "plt.plot(x, y)\n", "plt.ylim(1e-6,1) # restrict y range" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "## Exercices\n", "\n", "- write a vectorized function that takes an array of int and returns an array where square integers are replaced by their square root and the others are left unchanged" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7.0\n", "[ 0. 1. 2. 3. 2. 5. 6. 7. 8. 3. 10. 11. 12. 13. 14.\n", " 15. 4. 17. 18. 19. 20. 21. 22. 23. 24. 5.]\n" ] } ], "source": [ "### A solution\n", "def replace_square(n):\n", " sqrt_n = np.sqrt(n)\n", " return n + (sqrt_n == sqrt_n.astype(int))*(-n + sqrt_n)\n", "\n", "print(replace_square(7.0))\n", "print(replace_square(np.arange(26)))" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7.0\n", "[ 0. 1. 2. 3. 2. 5. 6. 7. 8. 3. 10. 11. 12. 13. 14.\n", " 15. 4. 17. 18. 19. 20. 21. 22. 23. 24. 5.]\n" ] } ], "source": [ "### or using where\n", "def replace_square2(n):\n", " sqrt_n = np.sqrt(n)\n", " return np.where(sqrt_n == sqrt_n.astype(int), \n", " sqrt_n, n)\n", " \n", "print(replace_square2(7.0)) \n", "print(replace_square2(np.arange(26)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "deletable": true, "editable": 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.5.3" }, "nbsphinx": { "orphan": true } }, "nbformat": 4, "nbformat_minor": 0 }