{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Informatik 1 - Biomedical Engineering\n", "## Tutor Session 4 - Python Specific Packages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Overview\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lambda functions\n", "" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "grade_list = [('Alex', 3), ('Michi', 5), ('Sasha', 1)]\n", "grade_list.sort(key=lambda person: person[0])\n", "print(\"sorted by name: \", grade_list)\n", "grade_list.sort(key=lambda person: person[1])\n", "print(\"sorted by grade:\", grade_list)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list1 = [3, 4, 5, 6, 7]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(filter(lambda x: x > 5, list1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "[i for i in list1 if i > 5]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f = lambda x: x**x\n", "[f(x) for x in list1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Command Line Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Argparse\n", "\n", "A convenience package for handling command line parameters" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Simulate argv because notebooks have their very own stuff there\n", "\n", "import sys\n", "sys.argv = [\"program.py\", \"-x1\"]\n", "sys.argv = [\"program.py\", \"-x\", \"1\"] # argv are always strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Basic workflow" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# step 0: import the package\n", "import argparse\n", "\n", "# Step 1: instantiate a parser\n", "arg_parser = argparse.ArgumentParser()\n", "\n", "# step 2+: Add our parameters\n", "arg_parser.add_argument(\"-x\", type=int)\n", "\n", "#step 3: Parse the sys.argv (does use sys.argv as default)\n", "parsed_params = arg_parser.parse_args()\n", "\n", "#step 4: extract the variables\n", "cmd_params = vars(parsed_params)\n", "\n", "print(cmd_params)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Further important tricks\n", "##### Long and short forms" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arg_parser = argparse.ArgumentParser()\n", "arg_parser.add_argument(\"-f\", \"--first\", type=int)\n", "arg_parser.add_argument(\"-s\", \"--second\", type=str) # note the second will be a string, even if we provide a number\n", "\n", "\n", "sys.argv = [\"program.py\", \"-f\", \"1\", \"-s\", \"2\"]\n", "cmd_params = vars(arg_parser.parse_args())\n", "print(cmd_params)\n", "\n", "# the name is always defined by -- name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### default values\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arg_parser = argparse.ArgumentParser()\n", "arg_parser.add_argument(\"-x\", type=int, default=1337)\n", "\n", "sys.argv = [\"program.py\", \"-x\", \"1\"]\n", "#sys.argv = [\"program.py\"] # ccomment in to test defaults\n", "cmd_params = vars(arg_parser.parse_args())\n", "print(cmd_params)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### existence checks" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arg_parser = argparse.ArgumentParser()\n", "arg_parser.add_argument(\"--run\", action=\"store_true\")\n", "\n", "#sys.argv = [\"program.py\", \"--run\"]\n", "sys.argv = [\"program.py\"]\n", "cmd_params = vars(arg_parser.parse_args())\n", "print(cmd_params)\n", "\n", "# The param will always be there and you get True of False to see if it was used in the command line" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sys.argv = [\"program.py\", \"-h\"]\n", "#sys.argv = [\"program.py\"]\n", "cmd_params = vars(arg_parser.parse_args())\n", "print(cmd_params)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Operating System (OS) Functionality \n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'nt'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "\n", "os.environ" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "file_location = \"C:/Users/Folder/doc.py\"\n", "os.path.isdir(file_location)\n", "os.path.isfile(file_location)\n", "os.path.exists(file_location)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "os.path.basename(file_location)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'C:/Users/Folder'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.path.dirname(file_location)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is NumPy?\n", "* \"MATLAB in python\"\n", "* provides mathematical functionality for python\n", "* array and matrix datatypes\n", "* element-wise calculations\n", "* faster than lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Cheatsheet:\n", "https://github.com/juliangaal/python-cheat-sheet/blob/master/NumPy/NumPy.md" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basics - Array creation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy\n", "\n", "# or, for convenience:\n", "import numpy as np # you could use any name, but \"np\" is stamdard" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arrays can be created from:\n", "* python lists or sequences\n", "* functions\n", "* strings or files\n", "\n", "They can only contain one data type!\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = np.array([1,2,3,4]) # data type is guessed from the values\n", "b = np.array([5,6,7,8], float) # but can also be specified explicitly\n", "c = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]) # 2D-array (matrix)\n", "d = np.arange(0,15) # like range, but an numpy-array" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(a)\n", "print(b)\n", "print(c)\n", "print(d)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.linspace(0, 2, 9) # (start, end, num_steps)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.zeros((3,2)) # ((rows, cols)) argument has to be a tuple!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arrays work element-wise!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list_a = [1,2,3,4]\n", "list_b = [8,7,6,5]\n", "array_a = np.array(list_a)\n", "array_b = np.array(list_b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_a+array_b\n", "list_a + list_b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_a * 4\n", "list_a * 4" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.dot(array_a, array_b) # dot (scalar) product" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Most functions can be used in two ways:\n", "```python\n", "np.function(array_1, array_2)\n", "array_1.function(array_2)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_1 = np.array((1,2,3,4))\n", "array_2 = np.array((3,4,5,6))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.dot(array_1, array_2) # 1*3 + 2*4 + 3*5 + 4*6 = 50\n", "array_1.dot(array_2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Indexing\n", "very similar to MATLAB" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_a = np.array([[1, 2, 3], [4, 5, 6]])\n", "print(array_a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_a[0,2] # row, col" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array properties\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_a.shape # again, (row, col)\n", "array_a.dtype\n", "array_a.size # total number of elements\n", "array_a.ndim # number of dimensions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "array_b = np.array((1.1, 2.2, 3.8))\n", "array_b.dtype" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matplotlib" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "#from matplotlib import pyplot as plt\n", "\n", "x = [1, 2, 3, 4, 5, 6, 7, 8]\n", "y = [0, 2, 1, 3, 7, 10, 11, 19]\n", "plt.plot(x, y)\n", "plt.scatter(x,y, c=\"r\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "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.6.0" } }, "nbformat": 4, "nbformat_minor": 2 }