diff --git a/.gitignore b/.gitignore index d7a6e3e..719bc76 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ /docs/items /docs/static/items /ipython/.ipynb_checkpoints +.DS_Store diff --git a/ipython/BuildingArrays.ipynb b/ipython/BuildingArrays.ipynb index ecd39bd..35936f7 100644 --- a/ipython/BuildingArrays.ipynb +++ b/ipython/BuildingArrays.ipynb @@ -1,859 +1,937 @@ { - "metadata": { - "name": "" - }, - "nbformat": 3, - "nbformat_minor": 0, - "worksheets": [ + "cells": [ { - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Building arrays\n", - "======================================================================\n", - "\n", - "This is a brief introduction to array objects, their declaration and use\n", - "in scipy. A comprehensive list of examples of Numpy functions for arrays\n", - "can be found at [Numpy Example List With Doc](http://wiki.scipy.org/Numpy_Example_List_With_Doc)\n", - "\n", - "Basics\n", - "------\n", - "\n", - "Numerical arrays are not yet defined in the standard python language. To\n", - "load the array object and its methods into the namespace, the numpy\n", - "package must be imported:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from numpy import *" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 1 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Arrays can be created from the usual python lists and tuples using the\n", - "array function. For example," - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a = array([1,2,3])" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 2 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "returns a one dimensional array of integers. The array instance has a\n", - "large set of methods and properties attached to it. For example, is the\n", - "dimension of the array. In this case, it would simply be .\n", - "\n", - "One big difference between array objects and python's sequences object\n", - "is the definition of the mathematical operators. Whereas the addition of\n", - "two lists concatenates those list, the addition of two arrays adds the\n", - "arrays element-wise. For example :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "b = array((10,11,12))\n", - "a + b" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 3, - "text": [ - "array([11, 13, 15])" - ] - } - ], - "prompt_number": 3 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Subtraction, multiplication and division are defined similarly.\n", - "\n", - "A common gotcha for beginners is the type definition of arrays. Unless\n", - "otherwise instructed, the array construct uses the type of its argument.\n", - "Since was created from a list of integers, it is defined as an integer\n", - "array, more precisely :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a.dtype" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 4, - "text": [ - "dtype('int64')" - ] - } - ], - "prompt_number": 4 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Accordingly, mathematical operations such as division will operate as\n", - "usual in python, that is, will return an integer answer :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a/3" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 5, - "text": [ - "array([0, 0, 1])" - ] - } - ], - "prompt_number": 5 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To obtain the expected answer, one solution is to force the casting of\n", - "integers into real numbers by dividing by a real number . A more careful\n", - "approach is to define the type at initialization time :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a = array([1,2,3], dtype=float)" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 6 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Another way to cast is by using Numpy's built-in cast functions astype\n", - "and cast. These allow you to change the type of data you're working\n", - "with:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a = array([1,2,3], dtype=int)\n", - "b = a.astype('float')" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 7 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The elements of an array are accessed using the bracket notation where\n", - "is an integer index starting at 0. Sub-arrays can be accessed by using\n", - "general indexes of the form `start:stop:step`. `a[start:stop:step]` will\n", - "return a reference to a sub-array of array `a` starting with (including)\n", - "the element at index `start` going up to (but not including) the\n", - "element at index stop in steps of *step*. e.g.:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "data = array([0.5, 1.2, 2.2, 3.4, 3.5, 3.4, 3.4, 3.4], float)\n", - "t = arange(len(data), dtype='float') * 2*pi/(len(data)-1)\n", - "t[:] # get all t-values" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 8, - "text": [ - "array([ 0. , 0.8975979 , 1.7951958 , 2.6927937 , 3.5903916 ,\n", - " 4.48798951, 5.38558741, 6.28318531])" - ] - } - ], - "prompt_number": 8 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "t[2:4] # get sub-array with the elements at the indexes 2,3" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 9, - "text": [ - "array([ 1.7951958, 2.6927937])" - ] - } - ], - "prompt_number": 9 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "t[slice(2,4)] # the same using slice" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 10, - "text": [ - "array([ 1.7951958, 2.6927937])" - ] - } - ], - "prompt_number": 10 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "t[0:6:2] # every even-indexed value up to but excluding 6" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 11, - "text": [ - "array([ 0. , 1.7951958, 3.5903916])" - ] - } - ], - "prompt_number": 11 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Furthermore, there is the possibility to access array-elements using\n", - "bool-arrays. The bool-array has the indexes of elements which are to be\n", - "accessed set to *True.*" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "i = array(len(t)*[False], bool) # create an bool-array for indexing\n", - "i[2] = True; i[4] = True; i[6] = True # we want elements with indexes 2,4 and 6\n", - "t[i]" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 12, - "text": [ - "array([ 1.7951958 , 3.5903916 , 5.38558741])" - ] - } - ], - "prompt_number": 12 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can use this syntax to make slightly more elaborate constructs.\n", - "Consider the `data[:]` and `t[:]` arrays defined before. Suppose we want to\n", - "get the four (`t[i]/data[i]`)-pairs with the four `t[i]-values` being\n", - "closest to a point `p=1.8`. We could proceed as follows:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "p=1.8 # set our point\n", - "abs(t-p) # how much do the t[:]-values differ from p?" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 13, - "text": [ - "array([ 1.8 , 0.9024021 , 0.0048042 , 0.8927937 , 1.7903916 ,\n", - " 2.68798951, 3.58558741, 4.48318531])" - ] - } - ], - "prompt_number": 13 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "dt_m = sort(abs(t-p))[3] # how large is the 4-th largest absolute distance between the\n", - " # t[:]-values and p" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 14 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "abs(t-p) <= dt_m # where are the four elements of t[:]closest to p ?" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 15, - "text": [ - "array([False, True, True, True, True, False, False, False], dtype=bool)" - ] - } - ], - "prompt_number": 15 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "y_p = data[abs(t-p) <= dt_m] # construct the sub-arrays; (1) get the 4 t[:]-values\n", - "t_p = t[abs(t-p) <= dt_m] # (2) get the data t[:]-values corresponding to the 4 t[:] values\n", - "y_p" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 16, - "text": [ - "array([ 1.2, 2.2, 3.4, 3.5])" - ] - } - ], - "prompt_number": 16 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "t_p" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 17, - "text": [ - "array([ 0.8975979, 1.7951958, 2.6927937, 3.5903916])" - ] - } - ], - "prompt_number": 17 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It has to be kept in mind that slicing returns a reference to the data.\n", - "As a consequence, changes in the returned sub-array cause changes in the\n", - "original array and vice versa. If one wants to copy only the values one\n", - "can use the copy()-method of the matrix object. For example:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "# first lets define a 2-d matrix\n", - "A = array([[0, 1, 2, 3], # initialize 2-d array\n", - " [4, 5, 6, 7],\n", - " [8, 9, 10, 11],\n", - " [12, 13, 14, 15]])\n", - "A" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 18, - "text": [ - "array([[ 0, 1, 2, 3],\n", - " [ 4, 5, 6, 7],\n", - " [ 8, 9, 10, 11],\n", - " [12, 13, 14, 15]])" - ] - } - ], - "prompt_number": 18 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "b=A[1:3,0:2] # let's get a sub-matrix containing the cross-section of\n", - " # rows 1,2 and columns 0,1\n", - " # !attention! this assigns to b a reference to the\n", - " # sub-matrix of A\n", - "b" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 19, - "text": [ - "array([[4, 5],\n", - " [8, 9]])" - ] - } - ], - "prompt_number": 19 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "c=A[1:3,0:2].copy() # copy the entries\n", - "c" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 20, - "text": [ - "array([[4, 5],\n", - " [8, 9]])" - ] - } - ], - "prompt_number": 20 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "A[1:3,0:2] = 42 # we can also assign by slicing (this also changes shallow copies)\n", - "b # b also affected (only a reference to sub matrix)" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 21, - "text": [ - "array([[42, 42],\n", - " [42, 42]])" - ] - } - ], - "prompt_number": 21 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "c # still the same (deep copy)" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 22, - "text": [ - "array([[4, 5],\n", - " [8, 9]])" - ] - } - ], - "prompt_number": 22 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Matrix dot product\n", - "------------------\n", - "\n", - "The next example creates two matrices: `a` and `b`, and computes the dot\n", - "product `axb` (in other words, the standard matrix product)" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a = array([[1,2], [2,3]])\n", - "b = array([[7,1], [0,1]])\n", - "dot(a, b)" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 23, - "text": [ - "array([[ 7, 3],\n", - " [14, 5]])" - ] - } - ], - "prompt_number": 23 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Automatic array creation\n", - "------------------------\n", - "\n", - "Scipy (via Numpy) provides numerous ways to create arrays automatically.\n", - "For example, to create a vector of evenly spaced numbers, the linspace\n", - "function can be called. This is often useful to compute the result of a\n", - "function on some domain. For example, to compute the value of the\n", - "function on one period, we would define a vector going from 0 to 2 pi\n", - "and compute the value of the function for all values in this vector :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "x = linspace(0, 2*pi, 100)\n", - "y = sin(x)" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 24 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The same can be done on a N dimensional grid using the class and some of\n", - "its object creation methods and . For example," - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "x, y = mgrid[0:10:.1, 0:10:.2]" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 25 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "returns two matrices, x and y, whose elements range from 0 to 10\n", - "(non-inclusively) in .1 and .2 increments respectively. These matrices\n", - "can be used to compute the value of a function at the points (x\\_i,\n", - "y\\_i) defined by those grids :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "z = (x+y)**2" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 26 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The ogrid object has the exact same behavior, but instead of storing an\n", - "N-D matrix into memory, it stores only the 1-D vector that defines it.\n", - "For large matrices, this can lead to significant economy of memory\n", - "space.\n", - "\n", - "Other useful functions to create matrices are and who initialize arrays\n", - "full of zeros and ones. Note that those will be float arrays by default.\n", - "This may lead to curious behaviour for the unawares. For example, let's\n", - "initialize a matrix with zeros, and then place values in it element by\n", - "element." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "mz = zeros((2, 2), dtype=int)\n", - "mz[0, 0] = .5**2\n", - "mz[1, 1] = 1.6**2" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 27 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this example, we are trying to store floating point numbers in an\n", - "integer array. Thus, the numbers are then recast to integers, so that if\n", - "we print the matrix, we obtain :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "mz" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 28, - "text": [ - "array([[0, 0],\n", - " [0, 2]])" - ] - } - ], - "prompt_number": 28 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To create real number arrays, one simply need to state the type\n", - "explicitly in the call to the function :" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "mz = zeros((2, 2), dtype=float)" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 29 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Repeating array segments\n", - "------------------------\n", - "\n", - "The ndarray.repeat() method returns a new array with dimensions repeated\n", - "from the old one." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a = array([[0, 1],\n", - "... [2, 3]])\n", - "a.repeat(2, axis=0) # repeats each row twice in succession" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 30, - "text": [ - "array([[0, 1],\n", - " [0, 1],\n", - " [2, 3],\n", - " [2, 3]])" - ] - } - ], - "prompt_number": 30 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a.repeat(3, axis=1) # repeats each column 3 times in succession" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 31, - "text": [ - "array([[0, 0, 0, 1, 1, 1],\n", - " [2, 2, 2, 3, 3, 3]])" - ] - } - ], - "prompt_number": 31 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "a.repeat(2, axis=None) # flattens (ravels), then repeats each element twice" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 32, - "text": [ - "array([0, 0, 1, 1, 2, 2, 3, 3])" - ] - } - ], - "prompt_number": 32 - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These can be combined to do some useful things, like enlarging image\n", - "data stored in a 2D array:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def enlarge(a, x=2, y=None):\n", - " \"\"\"Enlarges 2D image array a using simple pixel repetition in both dimensions.\n", - " Enlarges by factor x horizontally and factor y vertically.\n", - " If y is left as None, uses factor x for both dimensions.\"\"\"\n", - " a = asarray(a)\n", - " assert a.ndim == 2\n", - " if y == None:\n", - " y = x\n", - " for factor in (x, y):\n", - " assert factor.__class__ == int\n", - " assert factor > 0\n", - " return a.repeat(y, axis=0).repeat(x, axis=1)\n", - "\n", - "enlarge(a, x=2, y=2)" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "metadata": {}, - "output_type": "pyout", - "prompt_number": 33, - "text": [ - "array([[0, 0, 1, 1],\n", - " [0, 0, 1, 1],\n", - " [2, 2, 3, 3],\n", - " [2, 2, 3, 3]])" - ] - } - ], - "prompt_number": 33 + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Building arrays\n", + "========\n", + "\n", + "This is a brief introduction to array objects, their declaration and use\n", + "in SciPy. A comprehensive list of examples of Numpy functions for arrays\n", + "can be found at [Numpy Example List With Doc](http://wiki.scipy.org/Numpy_Example_List_With_Doc)\n", + "\n", + "Basics\n", + "------\n", + "\n", + "Numerical arrays are not yet defined in the standard Python language. To\n", + "load the array object and its methods into the namespace, the Numpy\n", + "package must be imported:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "from numpy import *" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Arrays can be created from the usual python lists and tuples using the\n", + "array function. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "a = array([1,2,3])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "returns a one dimensional array of integers. The array instance has a\n", + "large set of methods and properties attached to it. For example, is the\n", + "dimension of the array. In this case, it would simply be .\n", + "\n", + "One big difference between array objects and python's sequences object\n", + "is the definition of the mathematical operators. Whereas the addition of\n", + "two lists concatenates those list, the addition of two arrays adds the\n", + "arrays element-wise. For example :" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([11, 13, 15])" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b = array((10,11,12))\n", + "a + b" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Subtraction, multiplication and division are defined similarly.\n", + "\n", + "A common gotcha for beginners is the type definition of arrays. Unless\n", + "otherwise instructed, the array construct uses the type of its argument.\n", + "Since was created from a list of integers, it is defined as an integer\n", + "array, more precisely :" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dtype('int64')" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a.dtype" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Accordingly, mathematical operations such as division will operate as\n", + "usual in python, that is, will return an integer answer :" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([0.33333333, 0.66666667, 1. ])" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a/3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To obtain the expected answer, one solution is to force the casting of\n", + "integers into real numbers by dividing by a real number . A more careful\n", + "approach is to define the type at initialization time :" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "a = array([1,2,3], dtype=float)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another way to cast is by using Numpy's built-in cast functions `astype`\n", + "and `cast`. These allow you to change the type of data you're working\n", + "with:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "a = array([1,2,3], dtype=int)\n", + "b = a.astype('float')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The elements of an array are accessed using the bracket notation where\n", + "is an integer index starting at 0. Sub-arrays can be accessed by using\n", + "general indexes of the form `start:stop:step`. `a[start:stop:step]` will\n", + "return a reference to a sub-array of array `a` starting with (including)\n", + "the element at index `start` going up to (but not including) the\n", + "element at index stop in steps of *step*. e.g.:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([0. , 0.8975979 , 1.7951958 , 2.6927937 , 3.5903916 ,\n", + " 4.48798951, 5.38558741, 6.28318531])" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "data = array([0.5, 1.2, 2.2, 3.4, 3.5, 3.4, 3.4, 3.4], float)\n", + "t = arange(len(data), dtype='float') * 2*pi/(len(data)-1)\n", + "t[:] # get all t-values" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1.7951958, 2.6927937])" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "t[2:4] # get sub-array with the elements at the indexes 2,3" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1.7951958, 2.6927937])" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "t[slice(2,4)] # the same using slice" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([0. , 1.7951958, 3.5903916])" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "t[0:6:2] # every even-indexed value up to but excluding 6" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Furthermore, there is the possibility to access array-elements using\n", + "bool-arrays. The bool-array has the indexes of elements which are to be\n", + "accessed set to *True.*" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1.7951958 , 3.5903916 , 5.38558741])" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "i = array(len(t)*[False], bool) # create an bool-array for indexing\n", + "i[2] = True; i[4] = True; i[6] = True # we want elements with indexes 2,4 and 6\n", + "t[i]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use this syntax to make slightly more elaborate constructs.\n", + "Consider the `data[:]` and `t[:]` arrays defined before. Suppose we want to\n", + "get the four (`t[i]/data[i]`)-pairs with the four `t[i]-values` being\n", + "closest to a point `p=1.8`. We could proceed as follows:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1.8 , 0.9024021 , 0.0048042 , 0.8927937 , 1.7903916 ,\n", + " 2.68798951, 3.58558741, 4.48318531])" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "p=1.8 # set our point\n", + "abs(t-p) # how much do the t[:]-values differ from p?" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "dt_m = sort(abs(t-p))[3] # how large is the 4-th largest absolute distance between the\n", + " # t[:]-values and p" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([False, True, True, True, True, False, False, False])" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "abs(t-p) <= dt_m # where are the four elements of t[:]closest to p ?" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1.2, 2.2, 3.4, 3.5])" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "y_p = data[abs(t-p) <= dt_m] # construct the sub-arrays; (1) get the 4 t[:]-values\n", + "t_p = t[abs(t-p) <= dt_m] # (2) get the data t[:]-values corresponding to the 4 t[:] values\n", + "y_p" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([0.8975979, 1.7951958, 2.6927937, 3.5903916])" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "t_p" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It has to be kept in mind that slicing returns a reference to the data.\n", + "As a consequence, changes in the returned sub-array cause changes in the\n", + "original array and vice versa. If one wants to copy only the values one\n", + "can use the `copy()`-method of the matrix object. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0, 1, 2, 3],\n", + " [ 4, 5, 6, 7],\n", + " [ 8, 9, 10, 11],\n", + " [12, 13, 14, 15]])" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# first lets define a 2-d matrix\n", + "A = array([[0, 1, 2, 3], # initialize 2-d array\n", + " [4, 5, 6, 7],\n", + " [8, 9, 10, 11],\n", + " [12, 13, 14, 15]])\n", + "A" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[4, 5],\n", + " [8, 9]])" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b=A[1:3,0:2] # let's get a sub-matrix containing the cross-section of\n", + " # rows 1,2 and columns 0,1\n", + " # !attention! this assigns to b a reference to the\n", + " # sub-matrix of A\n", + "b" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[4, 5],\n", + " [8, 9]])" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c=A[1:3,0:2].copy() # copy the entries\n", + "c" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[42, 42],\n", + " [42, 42]])" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A[1:3,0:2] = 42 # we can also assign by slicing (this also changes shallow copies)\n", + "b # b also affected (only a reference to sub matrix)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[4, 5],\n", + " [8, 9]])" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c # still the same (deep copy)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Matrix dot product\n", + "------------------\n", + "\n", + "The next example creates two matrices: `a` and `b`, and computes the dot\n", + "product `axb` (in other words, the standard matrix product)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 7, 3],\n", + " [14, 5]])" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = array([[1,2], [2,3]])\n", + "b = array([[7,1], [0,1]])\n", + "dot(a, b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As of Python 3.5, the `@` operator may be used for matrix multiplication:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 7, 3],\n", + " [14, 5]])" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" } ], - "metadata": {} + "source": [ + "a @ b" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Automatic array creation\n", + "------------------------\n", + "\n", + "SciPy (via Numpy) provides numerous ways to create arrays automatically.\n", + "For example, to create a vector of evenly spaced numbers, the linspace\n", + "function can be called. This is often useful to compute the result of a\n", + "function on some domain. For example, to compute the value of the\n", + "function on one period, we would define a vector going from 0 to 2 pi ($\\pi$)\n", + "and compute the value of the function for all values in this vector :" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [], + "source": [ + "x = linspace(0, 2*pi, 100)\n", + "y = sin(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The same can be done on a N-dimensional grid using the class and some of\n", + "its object creation methods. For example," + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [], + "source": [ + "x, y = mgrid[0:10:.1, 0:10:.2]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "returns two matrices, x and y, whose elements range from 0 to 10\n", + "(non-inclusively) in .1 and .2 increments respectively. These matrices\n", + "can be used to compute the value of a function at the points (x\\_i,\n", + "y\\_i) defined by those grids :" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "z = (x+y)**2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The ogrid object has the exact same behavior, but instead of storing an\n", + "N-D matrix into memory, it stores only the 1-D vector that defines it.\n", + "For large matrices, this can lead to significant economy of memory\n", + "space.\n", + "\n", + "Other useful functions to create matrices are and who initialize arrays\n", + "full of zeros and ones. Note that those will be float arrays by default.\n", + "This may lead to curious behaviour for the unawares. For example, let's\n", + "initialize a matrix with zeros, and then place values in it element by\n", + "element." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [], + "source": [ + "mz = zeros((2, 2), dtype=int)\n", + "mz[0, 0] = .5**2\n", + "mz[1, 1] = 1.6**2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this example, we are trying to store floating point numbers in an\n", + "integer array. Thus, the numbers are then recast to integers, so that if\n", + "we print the matrix, we obtain :" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0, 0],\n", + " [0, 2]])" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "mz" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To create real number arrays, one simply need to state the type\n", + "explicitly in the call to the function :" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [], + "source": [ + "mz = zeros((2, 2), dtype=float)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Repeating array segments\n", + "------------------------\n", + "\n", + "The ndarray.repeat() method returns a new array with dimensions repeated\n", + "from the old one." + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0, 1],\n", + " [0, 1],\n", + " [2, 3],\n", + " [2, 3]])" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = array([[0, 1],\n", + "... [2, 3]])\n", + "a.repeat(2, axis=0) # repeats each row twice in succession" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0, 0, 0, 1, 1, 1],\n", + " [2, 2, 2, 3, 3, 3]])" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a.repeat(3, axis=1) # repeats each column 3 times in succession" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([0, 0, 1, 1, 2, 2, 3, 3])" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a.repeat(2, axis=None) # flattens (ravels), then repeats each element twice" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "These can be combined to do some useful things, like enlarging image\n", + "data stored in a 2D array:" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0, 0, 1, 1],\n", + " [0, 0, 1, 1],\n", + " [2, 2, 3, 3],\n", + " [2, 2, 3, 3]])" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def enlarge(a, x=2, y=None):\n", + " \"\"\"Enlarges 2D image array a using simple pixel repetition in both dimensions.\n", + " Enlarges by factor x horizontally and factor y vertically.\n", + " If y is left as None, uses factor x for both dimensions.\"\"\"\n", + " a = asarray(a)\n", + " assert a.ndim == 2\n", + " if y == None:\n", + " y = x\n", + " for factor in (x, y):\n", + " assert factor.__class__ == int\n", + " assert factor > 0\n", + " return a.repeat(y, axis=0).repeat(x, axis=1)\n", + "\n", + "enlarge(a, x=2, y=2)" + ] + } + ], + "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.6.4" + }, + "latex_envs": { + "LaTeX_envs_menu_present": true, + "autoclose": false, + "autocomplete": true, + "bibliofile": "biblio.bib", + "cite_by": "apalike", + "current_citInitial": 1, + "eqLabelWithNumbers": true, + "eqNumInitial": 1, + "hotkeys": { + "equation": "Ctrl-E", + "itemize": "Ctrl-I" + }, + "labels_anchors": false, + "latex_user_defs": false, + "report_style_numbering": false, + "user_envs_cfg": false + }, + "toc": { + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false + }, + "varInspector": { + "cols": { + "lenName": 16, + "lenType": 16, + "lenVar": 40 + }, + "kernels_config": { + "python": { + "delete_cmd_postfix": "", + "delete_cmd_prefix": "del ", + "library": "var_list.py", + "varRefreshCmd": "print(var_dic_list())" + }, + "r": { + "delete_cmd_postfix": ") ", + "delete_cmd_prefix": "rm(", + "library": "var_list.r", + "varRefreshCmd": "cat(var_dic_list()) " + } + }, + "types_to_exclude": [ + "module", + "function", + "builtin_function_or_method", + "instance", + "_Feature" + ], + "window_display": false } - ] -} \ No newline at end of file + }, + "nbformat": 4, + "nbformat_minor": 1 +}