{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercise -- 2nd Week\n", "\n", "## Outline\n", "\n", "* Setting up Python\n", "\n", "* Useful tools\n", "\n", "* First steps in Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setting up Python\n", "\n", "* Anaconda distribution and navigator\n", "\n", "* Did installation work for everybody?\n", "\n", "## Useful tools \n", "\n", "Some ways of running and editing Python programs\n", "\n", "* Spyder\n", "\n", "* Jupyter notebook and console\n", "\n", "* Python, IPython shell's: -i interactive session\n", "\n", "* pip, PyPI\n", "\n", "## First steps in Python\n", "\n", "* Experience with tutorial?\n", "\n", "### Example: Python as pocket calculator" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Adding two numbers: 400\n", "Subtracting two numbers: -26\n", "Multiplying two numbers: 39831\n", "Diving two numbers: 0.8779342723004695\n", "Floor division: 3\n", "\n", "Checking binary addition example (slide 43)\n", " 01010111\n", "+10110111\n", "==========\n", "100001110\n" ] } ], "source": [ "print('Adding two numbers:', 187 + 213)\n", "print('Subtracting two numbers:', 187 - 213)\n", "print('Multiplying two numbers:', 187 * 213)\n", "print('Diving two numbers:', 187 / 213)\n", "print('Floor division:', 10//3)\n", "\n", "# check calculation from lecture\n", "a10 = 87\n", "b10 = 183\n", "c10 = a10 + b10\n", "\n", "a2 = '{0:08b}'.format(a10)\n", "b2 = '{0:08b}'.format(b10)\n", "c2 = '{0:08b}'.format(c10)\n", "\n", "print('\\nChecking binary addition example (slide 43)')\n", "print(' ' + a2)\n", "print('+' + b2)\n", "print('=' * 10)\n", "print(c2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Running a script \n", "\n", "In the consolve, we have to invoke Python or IPython\n", "~~~ bash\n", "python helloworld.py\n", "~~~\n", "The option \"-i\" allows us to run the script interactive (that is all variables created when running the script still exist in the global namespace)\n", "~~~ bash\n", "python -i helloworld.py\n", "~~~\n", "Replace *python* with *ipython* to use the IPython interpreter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Running a system's command from within Python" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# os - import operating system bindings\n", "import os\n", "\n", "# works on Linux\n", "os.system('xclock &')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Importing modules\n", "\n", "Built-in and third-party packages can be loaded with the *import* command. " ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Content of package \"string\"\n", "['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']\n", "0123456789abcdefABCDEF\n", "\n", "The source is here: /home/mhabeck/anaconda3/lib/python3.7/string.py\n", "\n", "Doc string for math function \"gcd\"\n", "greatest common divisor of x and y\n" ] } ], "source": [ "import string\n", "# We can list the content of a package\n", "print('Content of package \"{}\"'.format(string.__name__))\n", "print(dir(string))\n", "print(string.hexdigits)\n", "\n", "# We can look at the source!\n", "print('\\nThe source is here: {}'.format(string.__file__))\n", "\n", "# We can look at documentation\n", "import math\n", "print('\\nDoc string for math function \"gcd\"')\n", "print(math.gcd.__doc__)" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Image Processing for Python\n", "\n", "``scikit-image`` (a.k.a. ``skimage``) is a collection of algorithms for image\n", "processing and computer vision.\n", "\n", "The main package of ``skimage`` only provides a few utilities for converting\n", "between image data types; for most features, you need to import one of the\n", "following subpackages:\n", "\n", "Subpackages\n", "-----------\n", "color\n", " Color space conversion.\n", "data\n", " Test images and example data.\n", "draw\n", " Drawing primitives (lines, text, etc.) that operate on NumPy arrays.\n", "exposure\n", " Image intensity adjustment, e.g., histogram equalization, etc.\n", "feature\n", " Feature detection and extraction, e.g., texture analysis corners, etc.\n", "filters\n", " Sharpening, edge finding, rank filters, thresholding, etc.\n", "graph\n", " Graph-theoretic operations, e.g., shortest paths.\n", "io\n", " Reading, saving, and displaying images and video.\n", "measure\n", " Measurement of image properties, e.g., similarity and contours.\n", "morphology\n", " Morphological operations, e.g., opening or skeletonization.\n", "restoration\n", " Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.\n", "segmentation\n", " Partitioning an image into multiple regions.\n", "transform\n", " Geometric and other transforms, e.g., rotation or the Radon transform.\n", "util\n", " Generic utilities.\n", "viewer\n", " A simple graphical user interface for visualizing results and exploring\n", " parameters.\n", "\n", "Utility Functions\n", "-----------------\n", "img_as_float\n", " Convert an image to floating point format, with values in [0, 1].\n", " Is similar to `img_as_float64`, but will not convert lower-precision\n", " floating point arrays to `float64`.\n", "img_as_float32\n", " Convert an image to single-precision (32-bit) floating point format,\n", " with values in [0, 1].\n", "img_as_float64\n", " Convert an image to double-precision (64-bit) floating point format,\n", " with values in [0, 1].\n", "img_as_uint\n", " Convert an image to unsigned integer format, with values in [0, 65535].\n", "img_as_int\n", " Convert an image to signed integer format, with values in [-32768, 32767].\n", "img_as_ubyte\n", " Convert an image to unsigned byte format, with values in [0, 255].\n", "img_as_bool\n", " Convert an image to boolean format, with values either True or False.\n", "dtype_limits\n", " Return intensity limits, i.e. (min, max) tuple, of the image's dtype.\n", "\n", "\n" ] } ], "source": [ "import skimage\n", "\n", "print(skimage.__doc__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Data types\n", "\n", "For basic data types see Lecture 2 of Jake VanderPlas's [Whirlwind Tour of Python](https://github.com/jakevdp/WhirlwindTourOfPython). The notebooks accompanying the book are freely available at [github](https://github.com). \n", "\n", "The following [notebook](https://github.com/jakevdp/WhirlwindTourOfPython/blob/master/05-Built-in-Scalar-Types.ipynb) provides an overview over simple data types:\n", "\n", "| Type | Example | Description |\n", "|-------------|----------------|--------------------------------------------------------------|\n", "| ``int`` | ``x = 1`` | integers (i.e., whole numbers) |\n", "| ``float`` | ``x = 1.0`` | floating-point numbers (i.e., real numbers) |\n", "| ``complex`` | ``x = 1 + 2j`` | Complex numbers (i.e., numbers with real and imaginary part) |\n", "| ``bool`` | ``x = True`` | Boolean: True/False values |\n", "| ``str`` | ``x = 'abc'`` | String: characters or text |\n", "| ``NoneType``| ``x = None`` | Special object indicating nulls |\n", "\n", "Let's check this:" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Data types\n", "====================\n", "None \n", "123498298457982 \n", "1.0 \n", "(10+2.8j) \n", "Image Processing \n" ] } ], "source": [ "print('\\nData types')\n", "print('=' * 20)\n", "x = None\n", "print(x, type(x))\n", "\n", "x = 123498298457982\n", "print(x, type(x))\n", "\n", "x = 1.0\n", "print(x, type(x))\n", "\n", "x = 10 + 2.8J\n", "#print(1j*1j)\n", "print(x, type(x))\n", "\n", "x = \"Image\" + ' ' + 'Processing'\n", "print(x, type(x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Compound Built-In Types\n", " \n", "| Type Name | Example |Description |\n", "|-----------|---------------------------|---------------------------------------|\n", "| ``list`` | ``[1, 2, 3]`` | Ordered collection |\n", "| ``tuple`` | ``(1, 2, 3)`` | Immutable ordered collection |\n", "| ``dict`` | ``{'a':1, 'b':2, 'c':3}`` | Unordered (key,value) mapping |\n", "| ``set`` | ``{1, 2, 3}`` | Unordered collection of unique values |\n", "\n", "As you can see, round, square, and curly brackets have distinct meanings when it comes to the type of collection produced." ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 'b'] \n", "('a', 'b') \n", "{'b', 'a'} \n", "{'a': 0, 'b': 1.0} \n" ] } ], "source": [ "x = ['a', 'b']\n", "print(x, type(x))\n", "\n", "y = ('a', 'b')\n", "print(y, type(y))\n", "\n", "z = {'a', 'b'}\n", "print(z, type(z))\n", "\n", "x = {'a': 0, 'b': 1.0}\n", "print(x, type(x))\n" ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "(1, 2, 3, 4, 5, 6, 7, 'ads', 1.4, None, [12, 23], [[1, 2], 1])\n", "1\n", "2\n", "[[1, 2], 1]\n", "[12, 23]\n" ] } ], "source": [ "a = [1, 2, 3, 4, 5, 6, 7]\n", "# i'm overwriting the variable 'a' at this point\n", "a = list('imageprocessing in python')\n", "a = '+'.join(a)\n", "a = (1, 2, 3, 4, 5, 6, 7, 'ads', 1.4, None, [12, 23], [[1,2],1])\n", "\n", "print(type(a))\n", "print(a)\n", "print(a[0])\n", "print(a[1])\n", "print(a[-1])\n", "print(a[-2])" ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[245, 'a', 10]\n", "(1, 'a')\n" ] } ], "source": [ "a = [1,'a']\n", "b = tuple(a)\n", "a[0] = 245\n", "# this doesn't work\n", "# b[0] = 245\n", "# because tuples are immutable\n", "a.append(10)\n", "print(a)\n", "print(b)\n" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "variables are pointers\n", "Is x y? True: 140298159230768 140298159230768\n", "1.0 2.0\n", "Is x y? False: 140298159230768 140298127656304\n" ] } ], "source": [ "print('\\nvariables are pointers')\n", "x = 1.\n", "y = x\n", "print('Is x y? {}:'.format(x is y), id(x), id(y))\n", "\n", "# creates a new pointer\n", "y = y + 1.\n", "print(x, y)\n", "print('Is x y? {}:'.format(x is y), id(x), id(y))\n", "\n" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Is x y? True: 140298127202816 140298127202816\n", "Is x y? True: 140298127202816 140298127202816\n", "['c', 'b', 'a'] ['c', 'b', 'a']\n" ] } ], "source": [ "# not true for lists\n", "x = ['c', 'b']\n", "y = x\n", "print('Is x y? {}:'.format(x is y), id(x), id(y))\n", "\n", "y.append('a')\n", "print('Is x y? {}:'.format(x is y), id(x), id(y))\n", "print(x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Integers\n", "\n", "Python integers don't overflow" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6668014432879854274079851790721257797144758322315908160396257811764037237817632071521432200871554290742929910593433240445888801654119365080363356052330830046095157579514014558463078285911814024728965016135886601981690748037476461291163877376\n", "number of digits: 241\n", "6668014432879854274079851790721257797144758322315908160396257811764037237817632071521432200871554290742929910593433240445888801654119365080363356052330830046095157579514014558463078285911814024728965139577117636164085619276963590675883115847\n" ] } ], "source": [ "x = 2**800\n", "y = 123441231034182394871239487129384719238471\n", "z = x + y\n", "print(x)\n", "print('number of digits: {}'.format(len(str(x))))\n", "print(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Floating point precision\n", "\n", "Float represents a real number with double precision." ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "0.1 = 1.00000e-01\n", "0.2 = 2.0000000000000001110223024625156540423631668090820312e-01\n", "0.2 + 0.1 = 3.0000000000000004440892098500626161694526672363281250e-01\n", "0.3 = 2.9999999999999998889776975374843459576368331909179688e-01\n", "\n", "largest floating point number\n", "1.7976931348623157e+308 \n", "sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)\n", "True\n" ] } ], "source": [ "print(0.1 + 0.2 == 0.3)\n", "\n", "print(\"0.1 = {0:.5e}\".format(0.1))\n", "print(\"0.2 = {0:.52e}\".format(0.2))\n", "print(\"0.2 + 0.1 = {0:.52e}\".format(0.1 + 0.2))\n", "print(\"0.3 = {0:.52e}\".format(0.3))\n", "\n", "nfrac = 52\n", "nexp = 11\n", "emax = 2**(nexp-1)\n", "\n", "# to avoid overflow we first subtract 1 from emax and then\n", "# add it back by multiplying with 2\n", "fmax = (1 - 2**-(nfrac+1)) * 2**(emax-1) * 2 \n", "\n", "print('\\nlargest floating point number')\n", "print(fmax, type(fmax))\n", "\n", "# compare with float_info from system module\n", "import sys\n", "print(sys.float_info)\n", "print(sys.float_info.max == fmax)" ] } ], "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.7.6" } }, "nbformat": 4, "nbformat_minor": 1 }