{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
Dr. Pietro Giampa
\n", "\n", "
TRIUMF
\n", "\n", "
2020 Winter Term
\n", "\n", "
Lecture 1/3
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Outline\n", " \n", " 1) Why Do We Need Programing in Physics?\n", " 2) Basic Variables and Operations\n", " 3) Building Loops (for, while)\n", " 4) Set Conditional Statements (if, elif, else)\n", " 5) Contructing Functions\n", " 6) Exercises " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Why Do We Need Programing in Physics?\n", "Programming is used to perform operations that would otherwise too cumbersome to do by hand:\n", "\n", " * Multi-step calculations\n", " * Data-streaming\n", " * Data-handling\n", " * Data-visualization\n", " * Simulations\n", " \n", "Python is lately gaining more and more traction in physics because is a great \"high level\" programming language. Most of the \"annoying\" things from other languages like C++ or java are automated or smoothed out in Python. Moreover, Python has a very large range of available libraries for all sorts of actions and functionality (machine learning techniques, data-visualization libraries, multiple simulation packages, etc.). \n", "\n", "Examples of Python Applications at TRIUMF:\n", "\n", " * Beam monitoring software \n", " * Different experiments data analysis\n", " * Theoretical calculations\n", " * Optical simulations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Basic Variables and Operations\n", "One of the advantages of Python is that the list of variables types is reduced to a minimum to help users. Fundamentally there are three types of variables:\n", "\n", " * NUMBERS (10, 23.89, 0x100, 3.1j)\n", " * STRINGS ('Hello World','Type Here','I am a string example')\n", " * BOOLEAN (true, false)\n", " \n", "Strings and Boolean are a simple set, while with numbers you have multiple options:\n", "\n", " * INTEGER - signed integer - [0, 1, 2, 3 .... etc]\n", " * LONG - long integer, octal and hexadecimal - [51924361L, 0x19323L .... etc]\n", " * FLOAT - floating point real values - [0.32, 100.2, 54.67899 .... etc]\n", " * COMPLEX - standard complex numbers - [7.12j, 0.876j, 23j ... etc]\n", " \n", "Let's run some examples. As mentioned before, the vast range of Python libraries is what makes Python GREAT. In today's lecture, we are introducing a library called NumPy, which is a compilation of mathematical functions and arrays (or vectors) operations (addition, subtraction, multiplication, sqrt, pow, ... etc). To import libraries you need to tell Python to fetch a given library and give it a tag name.\n", "\n", "Example: import 'library-name' as 'tag-name'\n", "\n", "NB: Please note that all the libraries that we are going to use in this course are already installed in Jupyter, however, if you need a library that is not already set you will need to install that library first. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "### Import Needed Libraries ###\n", "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 1.2.1\n", "You are on a plane from Vancouver to Ottawa and you know the avg cruising speed (1024.0 [km/h]) and the length of the travel (3.8 [h]) and you want to estimate the distance you travelled.\n", "\n", "PS: Air Canada removed distance travelled from their interactive Map (very annoying)." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First Method\n", "3891.2 [km]\n", "Second Method\n", "3891.2 [km]\n" ] } ], "source": [ "########################################################\n", "## Example 1.2.1 ##\n", "## Introduction to Scinetific Programming with Python ##\n", "## ##\n", "## Your Name, Institution Name, Year ##\n", "## Pietro Giampa, TRIUMF, 2019 ##\n", "########################################################\n", "\n", "### Import Needed Libraries ###\n", "import numpy as np\n", "\n", "### Define Variables ###\n", "avg_speed = 1024.0 # [km/Hour]\n", "travel_time = 3.8 # [Hour]\n", "\n", "# Direct operation with individual variables\n", "# Treat variables as single numbers\n", "distance_travel = avg_speed*travel_time\n", "\n", "### Print Results ###\n", "print('First Method')\n", "print(distance_travel, '[km]')\n", "\n", "# Operation via numpy\n", "# Treats variables as objects not just numbers (Great for Arrays)\n", "distance_travel_v2 = np.multiply(avg_speed,travel_time)\n", "\n", "### Print Results ###\n", "print('Second Method')\n", "print(distance_travel_v2, '[km]')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 1.2.2 \n", "You are running an experiment and you have to monitor a given observable, let's say the level of the LN2 dewar you are using for cooling your experiment. You want to write a small program that lets you input an LN2 level in % and convert that number into litres (100% = 255 L, assume linearity)." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter Current LN2 Level [%]32.4\n", "LN2 Level - 82.62 [Liters]\n" ] } ], "source": [ "########################################################\n", "## Example 1.2.2 ##\n", "## Introduction to Scinetific Programming with Python ##\n", "## ##\n", "## Pietro Giampa, TRIUMF, 2019 ##\n", "########################################################\n", "\n", "### Prompt Keyboard Input ###\n", "Level = input('Enter Current LN2 Level [%]')\n", "\n", "### Convert from String to Float\n", "Level = float(Level)\n", "\n", "### From percentage to fraction\n", "Level = Level/100.\n", "\n", "### Convert % to Liters ####\n", "Liters_Converter = 255.\n", "Level_L = Level*Liters_Converter\n", "\n", "### Print Results ###\n", "print('LN2 Level -',Level_L,'[Liters]')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Building Loops\n", "Loops are a fundamental block in programming. While we are gonna focus on Python, the basic concept of loops is the same for basically all programming languages (C++, Java .... etc). \n", "\n", "#### FOR-LOOP:\n", "A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string)." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T\n", "R\n", "I\n", "U\n", "M\n", "F\n" ] } ], "source": [ "for x in 'TRIUMF':\n", " print(x)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### WHILE-LOOP:\n", "With the while loop we can execute a set of statements as long as a condition is true." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "counter = 0\n", "while counter < 5:\n", " print(counter)\n", " counter = counter + 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 1.3.1\n", "Let's use Poisson statistics as an example. Say you have an experiment with an average event rate of 3.2 events every hour. You want to estimate the probability of getting either 0, 1, 2, 3, 4, and 5 events in the one hour span.\n", "\n", "Recall the Poisson distribution:\n", "\n", "$P(k, \\lambda) = \\frac{\\lambda^{k} \\cdot e^{-\\lambda}}{k!}$\n", "\n", "Where k is the expected number of events and $\\lambda$ is the average event rate of the experiment." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 - 0.04076220397836621\n", "1 - 0.1304390527307719\n", "2 - 0.20870248436923505\n", "3 - 0.22261598332718405\n", "4 - 0.17809278666174724\n", "5 - 0.11397938346351824\n" ] } ], "source": [ "########################################################\n", "## Example 1.3.1 ##\n", "## Introduction to Scinetific Programming with Python ##\n", "## ##\n", "## Pietro Giampa, TRIUMF, 2019 ##\n", "########################################################\n", "\n", "### Define Variables ###\n", "lambda_value = 3.2 # [events/hour]\n", "\n", "### Initiate FOR loop ###\n", "for k in range(6):\n", " Probability = (np.power(lambda_value,k)*np.exp(-lambda_value))/(np.math.factorial(k)) \n", " print(k,'-',Probability)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Set Conditional Statements\n", "Conditional statements, alongside loops, are the absolute basics of programming. Similar to loops, we will focus on the Python syntax, however, the basic consepts of consitinoal statements holds true for most langueges (C++, Jave .... etc). \n", "\n", "Decision making is required when we want to execute a code only if a certain condition is satisfied. \n", "\n", "#### CONDITIONS\n", "\n", " < - Less than ...\n", " > - Bigger than ...\n", " <= - Less or equal to ...\n", " >= - Bigger or equal to ...\n", " == - Equal to ...\n", " != - Different than ...\n", " and - and option\n", " or - or option\n", "\n", "#### IF STATEMENT:\n", "Python makes a decision based on a test expression. if the requirement is passed the subsequent actions are taken, if not the program skips ahead." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Requirement Matched\n" ] } ], "source": [ "if 3<5:\n", " print('Requirement Matched')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ELSE STATEMENT:\n", "The else statement must follows an if statement. The structure works as follows: if the requirement is passed the subsequent actions are taken, if not the program excecutes the actions from the else statement" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Requirement Not Matched\n" ] } ], "source": [ "if 'test'=='run':\n", " print('Requirement Matched')\n", "else:\n", " print('Requirement Not Matched')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ELIF STATEMENT:\n", "Sometimes multiple if-statements in consecutive order are necessary (imagine a desicion tree). In that case, IF is only used for the first itertion, while elif brings the second conditional. " ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Second Requirement Matched\n" ] } ], "source": [ "if 'test'=='run':\n", " print('First Requirement Matched')\n", "elif 'run'=='run':\n", " print('Second Requirement Matched')\n", "else:\n", " print('Requirement Not Matched')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 1.4.1\n", "Generate two random numbers between 0 and 1. Check if both numbers are less than 0.5 multiply them together, if only one of the is less than 0.5 add them together, and if they are both bigger or equal than 0.5 subtract them. Print the result on the screen (include both random numbers)." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-0.12373790811193852 0.7662768517599072 0.8900147598718458\n" ] } ], "source": [ "########################################################\n", "## Example 1.4.1 ##\n", "## Introduction to Scinetific Programming with Python ##\n", "## ##\n", "## Pietro Giampa, TRIUMF, 2019 ##\n", "########################################################\n", "\n", "### Define Variables ###\n", "number1 = np.random.rand()\n", "number2 = np.random.rand()\n", "result = 0.0 # initialize result\n", "\n", "### Check Conditionals ###\n", "if number1<0.5 and number2<0.5:\n", " result = np.multiply(number1,number2)\n", "elif number1<0.5 or number2<0.5:\n", " result = np.add(number1,number2)\n", "else:\n", " result = np.subtract(number1,number2)\n", " \n", "### Print Results ###\n", "print(result, number1, number2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Contructing Functions\n", "Some actions, calculations or conditionals might be used recurrently in a given program, in those cases functioncs are the best way to go. \n", "\n", "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.\n", "\n", "functions can generate actions (like print()) or return values (individual or arrays)." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "def linear_function(x,m,c):\n", " y = m*x + c\n", " return y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example 1.5.1\n", "Contruct a function to model radioactive decays by following the standard radioactive decay law:\n", "\n", "$N(t) = N_{0} \\cdot e^{-\\lambda \\cdot t}$\n", "\n", "Where $N(t)$ is the number of remaining daugthers at time t, $N_{0}$ is the starting daugthers concentration and $\\lambda$ is the half-life.\n", "\n", "If you inject 4.6x10$^{15}$ Nuclei of $^{222}$Rn in your detector, write a program that determines how many Rn daugthers you will measure after 1 day, 4 days and 9 days. " ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "After 1.0 days: 100716695707085.75\n", "After 4.0 days: 1057139696.6123526\n", "After 9.0 days: 5.319252034262702\n" ] } ], "source": [ "########################################################\n", "## Example 1.5.1 ##\n", "## Introduction to Scinetific Programming with Python ##\n", "## ##\n", "## Pietro Giampa, TRIUMF, 2019 ##\n", "########################################################\n", "\n", "### Set Decay Law as Function ###\n", "def DecayLaw(N0, lmbd, t):\n", " Nt = N0*np.exp(-lmbd*t)\n", " return Nt\n", "\n", "### Define Variables ###\n", "time1 = 1. # [days]\n", "time2 = 4. # [days]\n", "time3 = 9. # [days]\n", "lmbd = 3.8215 # [days]\n", "N0 = 4.6E15 # [nuclei]\n", "\n", "### Do Some Math ###\n", "Nt1 = DecayLaw(N0,lmbd,time1)\n", "Nt2 = DecayLaw(N0,lmbd,time2)\n", "Nt3 = DecayLaw(N0,lmbd,time3)\n", "\n", "### Print Results ###\n", "print('After',time1,'days:',Nt1)\n", "print('After',time2,'days:',Nt2)\n", "print('After',time3,'days:',Nt3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercises\n", "\n", "#### Problem 1\n", "Write a code capable of determining the force of repulsion ($F_{r}$) between two atoms. Estimate $F_{r}$ for the following cases:\n", " * Two Argon Atoms, Separated By: 0.1, 1.0, and 10.0 [nm]\n", " * Two Xenon Atoms, Separated By: 0.1, 1.0, and 10.0 [nm]\n", " * One Argon and One Xenone Atom, Separated By: 0.1, 1.0, 10.0 [nm]\n", "\n", "Your code should accept keyboard-input to receive the three cases. Using a loop and a conditinal, print on the screen the results for when d bigger than 0.5 [nm], for all three cases. Also, still using loops and conditionals, print out which combination yield the strongest repulsion.\n", "\n", "Recall that the Argon atomic number is 18, and the Xenon atomic number is 54. Also, remember that the repulsion force between atoms can be described by Coulumb's law:\n", "\n", "$F_{r} = \\frac{1}{4\\cdot \\pi \\epsilon_{0}} \\cdot \\frac{q_{1}q_{2}}{d^{2}}$ \n", "\n", "Where $F_{r}$ is the repulsion force, $\\epsilon_{0}$ is the permittivity of free space ($8.85x10^{-12} [N\\cdot m^{2}/C^{2}]$), $q_{1}$ is first charge, $q_{2}$ is the second charge and $d$ is the distance between them. \n", "\n", "NOTE: Your code should include at least 2 function and 2 loops (all results must be printed on the screen with clear labling).\n", "\n", "#### Problem 2\n", "For this exercise we are going to work with the Photoelectric effect. As a reminder, the Photoelectric effect is the emission of charge (electrons) when a material is hit by light of a certain wavelength.\n", "\n", "$E(\\lambda) = \\left( \\frac{\\hbar \\cdot c}{\\lambda} \\right) - \\psi$\n", "\n", "Where $E(\\lambda)$ is the energy of the released electron, $\\hbar$ is the Plack constant ($4.136×10^{−15}$ [eVs]), $c$ is the speed of light, $\\lambda$ is the wavelength of the incoming photon, and $\\psi$ is the work function of the material.\n", "\n", "You have to design an experiment that relies on the production of electrons via the Photoelectric effect, with different materials. Say you have 2 lasers in your lab (properties below) and you want to select the laser that work best with all material. \n", " * Write a code that asks you to select a material (via keyboard input) between the following: Si, Al, Au, and Ti.\n", " * Write a function that given your selection returns the appropiate work function (see table below for numbers). \n", " * Write another function that reproduces the output spectrum from the lasers (Assume it's Gaussian). \n", " * In the main body, use loops and conditional statements to compare lasers.\n", " * Print your results on the screen with clear labels.\n", " \n", "Work functions table:\n", " * Si - 4.60 [eV]\n", " * Al - 4.26 [eV]\n", " * Au - 5.10 [eV]\n", " * Ti - 4.33 [eV]\n", "\n", "Lasers Properties:\n", " * Laser 1: $\\mu$ = 950 [nm], $\\sigma$ = 285 [nm]\n", " * Laser 2: $\\mu$ = 750 [nm], $\\sigma$ = 300 [nm]\n", "\n", "#### Problem 3\n", "write a code that generates 500 random numbers following the Gaussian distribution from Problem 2 (Laser 1). In your code (via loops and conditionals) estimate how many numbers have been generated within 1$\\sigma$, 2$\\sigma$ and 3$\\sigma$. Compare your results with the thoretical expectation. " ] } ], "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" } }, "nbformat": 4, "nbformat_minor": 2 }