{ "cells": [ { "cell_type": "markdown", "id": "9965f1b0", "metadata": { "nbgrader": { "grade": false, "grade_id": "cell-3b587ecf818e3119", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "# Exercises\n", "\n", "In most of the exercises in this page, we don't specify which Python package you need to use for plotting (Matplotlib or seaborn) or for importing the data (when working with files, NumPy or pandas). It's up to you to make a choice of package. The choice can be based on the applicability (remember - for what type of data can you use NumPy?) or personal preferences (Matplotlib vs. seaborn).\n", "\n", "Each exercise carries the difficulty level indication:\n", "- [*] Easy\n", "- [**] Moderate\n", "- [***] Advanced\n", "\n", "The highest difficulty level is meant for students who wish to challenge themselves and/or have previous experience in programming." ] }, { "cell_type": "markdown", "id": "97601eca", "metadata": {}, "source": [ "`````{exercise} [*] Plotting polynomial functions\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/04_Plotting_function.py>`\n", "\n", "In this exercise you will practise how to plot functions with Python. \n", "Plotting functions is used, for example, to predict data trends or visualise \n", "mathematical results. The first exercise will be done for you as an example.\n", "\n", "**Example**: A polynomial function\n", "\n", "$f(x) = 3x^5 - 2x^2 - 3 $ in the interval [-1, 1].\n", "\n", "Solution steps: \n", "1. Define the function you want to plot.\n", "2. Define the values for the *x*-axis.\n", "3. Calculate the *y*-values using your function.\n", "4. Use Matplotlib to visualise the results. Don't forget to give the plot a \n", "title and annotate the axes.\n", "\n", "```\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "def polynomial(x): # We first define the function to be plotted\n", " return 3*x**5 - 2*x**2 - 3\n", "\n", "x_axis = np.linspace(-1,1,100) # Define the x-axis within the limits\n", "\n", "y_values = polynomial(x_axis) # Calculate the y-values\n", "\n", "plt.plot(x_axis,y_values) # Plot the function\n", "plt.title(\"Plot of a polynomial function\") # Give the plot a title\n", "plt.xlabel(\"x-values\") # x-axis label\n", "plt.ylabel(\"y-values\") # y-axis label\n", "```\n", "\n", "\n", "**Exercise A**: A polynomial function - Do it yourself\n", "\n", "Plot the polynomial function $a\\cdot x^3 + b$ for three values of `a` or `b`, \n", "between -1 and 1. How does your chosen parameter influence the function? \n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "\n", "**Exercise B**: Two functions in the same plot\n", "\n", "Take the functions $f(x) = 3-2x$ and $f(x)=2+3x$, plot them in the same plot \n", "and find the intersection point by looking at the graph. Determine for \n", "yourself the appropriate *x* and *y* bounds such that the point of intersection is easy to read.\n", "\n", "Remember to add a legend, a title and axis labels. You can add a legend by \n", "including `label = \"3 - 2x\"` in the parameters for `plt.plot()` \n", "(so `plt.plot(*plotting parameters*,label = \"3 - 2x\")`) and then adding a line\n", "`plt.legend()`.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "26722355", "metadata": {}, "source": [ "`````{exercise} [**] Plotting different functions in nanobiology\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/05_Plotting_Nanobio.py>`\n", "\n", "\n", "**Exercise A1**: Cell movement - MSD\n", "\n", "A freely moving cell in 2D approximately follows the diffusion formula, which \n", "gives the mean squared distance (MSD) from the origin:\n", "\n", "$$ d(t)^2 = 4\\cdot D\\cdot t $$\n", "\n", "with $D$ the so-called diffusion constant. Let $D$ = 1 m2/s. Calculate and plot \n", "the MSD for the first 100 seconds of movement. \n", "Note that the unit of $d(t)^2$ is m2.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise A2**: Cell movement - Fuhrt\n", "\n", "A more accurate representation of a 2D moving cell is Fuhrt's formula, \n", "\n", "$$ d(t)^2 = 4\\cdot D \\cdot (t-P\\cdot(1-e^{-t/P})) $$\n", "\n", "where $D$ and $P$ are the diffusion and persistence constants. For our \n", "purposes, we assume $D$ = 1 m2/s and $P$ = 15 s. \n", "\n", "Calculate and plot the MSD for the first 100 s of movement. \n", "Compare with the previous plot. \n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "\n", "**Exercise B**: The ideal gas law\n", "\n", "The ideal gas law is as follows:\n", "\n", "$$ p\\cdot V = N \\cdot k_{B} \\cdot T $$\n", "\n", "with $p$ the pressure, $V$ the volume of the gas, $N$ the particle number,\n", "$k_B$ the Boltzmann constant, and $T$ the temperature.\n", "\n", "1. Write a function for the volume depending on the pressure and temperature \n", "(keeping the particle number as a constant).\n", "\n", "2. Let $N$ = 1 and $k_B$ = 1.4 $\\cdot$ 10-23 J/K. Assume 1 atm pressure (101325 Pa). Plot the volume between 100 K and 1,000K. Is the relationship as expected from the equation?\n", "\n", "3. Let $N$ = 1 and $k_B$ = 1.4 $\\cdot$ 10-23 J/K. Assume room temperature (about 300 K). Plot the volume as a function of pressure between 1,000 Pa and 10,000 Pa. Is the relationship as expected?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "\n", "**Exercise C**: Michaelis-Menten\n", "\n", "Remember the Michaelis-Menten equation describing an enzymatic reaction:\n", "\n", "$$ v =\\frac{ V_{max}[S] }{K_M + [S]} $$\n", "\n", "with $V_{max}=k_2 \\cdot [E_{tot}]$ and $K_M = \\frac{k_1+k_2}{k_{-1}}$. The variables here represent the reaction rate constants $k_1$, $k_{-1}$ and $k_2$, the total enzyme concentration $[E_{tot}]$, the substrate concentration $[S]$ and the maximum reaction velocity $V_{max}$. \n", "\n", "1. Create a function for the Michaelis-Menten equation depending on substrate concentration $[S]$ and reaction constant $k_1$. \n", "\n", "2. Compute and plot the reaction velocity as a function of $[S] \\in \\{0,10\\}$ [mmol] for $k_1$ = 2 /s, $k_2$ = 1 mmol/s, $k_{-1}$ = 1 mmol/s and $E_{tot}$ = 2 mmol. Don't forget to properly annotate the axes and give the correct units.\n", "\n", "3. Now keep the substrate concentration constant at a value of $4mmol$ and plot the Michaelis-Menten equation as a function of $k_1 \\in \\{0,5\\}$. How does $k_1$ influence the reaction velocity?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "7b8b211b", "metadata": {}, "source": [ "`````{exercise} [**] Random walk (making plots pretty)\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/06_Pretty_plots.py>`\n", "\n", "Matplotlib provides some possibilities of personalising your plots. In this \n", "exercise, we will explore some of these options.\n", "\n", "We will work with a function $f(x)= \\sqrt{4Dt}$ for the root mean squared \n", "distance (in micrometers) of a random walk, and two averaged measurements of \n", "particles, which will have deviations from the ideal mathematical function. \n", "We will create the data using the `np.random.normal()` command, which \n", "will introduce noise into our perfect function. `np.random.normal()` \n", "creates a random number, where the probability of a number being chosen is \n", "determined by a normal distribution.\n", "\n", "```\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "\n", "time = np.linspace(0, 50, 50)\n", "calculated_rmsd = np.sqrt(4 * 15 * time)\n", "measured_1 = calculated_rmsd + np.random.normal(0, 2, len(time))\n", "measured_2 = calculated_rmsd + np.random.normal(0, 2, len(time))\n", "```\n", "\n", "First, create a regular plot of the three trajectories. Don't forget to label \n", "the axes and create a legend.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "There are several ways to enhance this plot.\n", "\n", "1. Plot size: You can specify plot size using the command \n", "`plt.figure(figsize=(a,b))` before plotting, where (a,b) gives the size of \n", "each edge. Experiment with the size of your plot and choose an appropriate \n", "sizing for your plot.\n", "\n", "2. Alter colour by adding `color = \"colour name\"` to the `plt.plot()` command. \n", "Check the list of [named colours in matplotlib](https://matplotlib.org/stable/gallery/color/named_colors.html).\n", "\n", "3. Alter linewidth by adding `linewidth = a` to the `plt.plot()` command, where\n", "`a` gives the width of the line in points.\n", "\n", "4. Change the linestyle using `linestyle = \"style\"` to the `plt.plot()` command. \n", "Check the list of [linestyles](https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html).\n", "\n", "5. Introducing special characters in axis labels: In this example, the \n", "*y*-axis has been labelled using `plt.ylabel(\"distance [um]\")` to indicate that\n", "the axis measures distance, in micrometers. However, we can also make the label \n", "show the character for micro (or almost any other character). \n", "For that, we use `plt.ylabel(r\"distance $[\\mu m]$\")`. Here, we put the special \n", "characters between dollar signs (`$`), and then use `\\mu` to get the greek letter \n", "mu. Similarly, we can use any other Greek letter. For those familiar with LaTeX, \n", "we can also put equations into labels using LaTeX formalism.\n", "\n", "```\n", "# Your code for pretty matplotlib plot\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "3ec79e31", "metadata": {}, "source": [ "`````{exercise} [**] Types of plots\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/07_Types_of_plots.py>`\n", "\n", "In this exercise we will explore Matplotlib and the types of plots that can be \n", "produced. Chosing the correct plot to represent your data is an important skill, \n", "and knowing the available plot types helps to make a good decision. The plot \n", "types we will discuss are: scatterplot, histogram, bar plot, boxplots, and \n", "adding errorbars.\n", "\n", "**Exercise A**: Scatterplot\n", "\n", "Make a scatterplot of the first ten Fibonacci numbers.\n", "Why is a scatterplot an appropriate plot to visualise these?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise B**: Histogram and bar plot\n", "\n", "A research group takes a questionnaire. The scientists are interested in the \n", "age distribution of the correspondents. The ages are \n", "[14, 14, 15, 16, 17, 19, 19, 20, 22, 22, 25, 26, 27, 27, 27, 30, 33, 33, 34, 34, \n", "34, 35, 36, 37, 37, 39, 42, 42, 43, 44, 45, 45, 45, 47, 49, 50, 50, 51, 52, 53, \n", "55, 56, 56, 56, 56, 57, 58, 85, 60, 63, 64, 66, 66, 69, 70, 73, 74, 76].\n", "\n", "*Part I*. Make a histogram of the age distributions, with one bin each for ages 10 - 19, \n", "20 - 29, etc. until 70 - 79. Which age group was most represented in this research?\n", "\n", "*Part II*. For this data, also create a bar plot. Note that for a bar plot, you need \n", "to give the heights of the bars yourself! If you want an extra challenge, write a \n", "function that counts the number of participants in their respective age groups for \n", "you. Else, use your histogram or count by hand. \n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise C**: Boxplot\n", "\n", "*Part I*. In Python, we can generate a random integer between 10 and 79 using the\n", "command `np.random.randint(10, 80)`.\n", "Using a `for` loop, create a dataset of 50 participants with random ages between \n", "10 and 80. Make a boxplot of this distribution.\n", "\n", "*Part II*. Now, repeat this process to create four datasets of randomly distributed \n", "ages, and plot them as boxplots in the same plot. \n", "Compare the results - are they as expected given that we used a random generating \n", "process? Increase the number of participants to 2,000. Are these results more \n", "or less like what you expected? What does this tell you about the reliability \n", "between participant number in a study, and reliability of the study results?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise D**: Lineplot with errorbars\n", "\n", "A researcher measures the deviation of the temperature from room temperature of\n", "a reaction over time. They measure every second, starting at 0 and ending at 20. \n", "Their results are (in K):\n", "\n", "[304.1, 306.6, 308.7, 310.7, 313.2, 316.8, 320.4, 323.8, 326.3, 329.3, 331.1, \n", "332.1, 333.3, 332.1, 331.1, 329.3, 326.3, 323.8, 320.4, 316.8, 313.2]\n", "\n", "The machine used for measurements has an error of 5 %. Create a plot of the \n", "measured data and add errorbars to the measurement points. \n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "92fb0e78", "metadata": {}, "source": [ "`````{exercise} [**] Puromycin\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Nina/04_Puromycin.zip>`\n", "\n", "\n", "Puromycin is an antibiotic that acts as a protein synthesis inhibitor.\n", "With this exercise, you received [data](https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/Puromycin.html) of the reaction velocity depending on\n", "the substrate concentration in an enzymatic reaction, involving cells that \n", "were either untreated (control) or treated with puromycin. We will investigate\n", "the effect of puromycin in this experiment.\n", "\n", "**Exercise A**: The data\n", "\n", "You received data file \"Puromycin.csv\" with this exercise.\n", "Use the terminal to explore its contents. Depending on what you discover in the \n", "file, choose an appropriate Python package and import the data in Python.\n", "\n", "How many measurements points are there in total? Is it same for both\n", "puromycin-treated and untreated cells? \n", "\n", "Use Python to come up with these counts and make print statements to inform \n", "about your findings.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise B**: Plotting\n", "\n", "Now you have a better idea what's in your dataset, however, it's still \n", "not straightforward to compare the two conditions (treated and untreated)\n", "from looking at a table. So let's plot the data to see how reaction velocity\n", "(rate) depending on substrate concentration is affected by puromycin.\n", "\n", "You have a few choices to make: \n", "* Which Python plotting package to use?\n", "* What is the best type of graph for this comparison?\n", "\n", "You can also explore different options of packages and graphs. Independent\n", "of your coding choices, your graph should be well labelled. It should also \n", "be easy to read, i.e., it should be obvious from your graph what the effect\n", "of puromycin is.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "9e8a608e", "metadata": {}, "source": [ "`````{exercise} [**] Diffusing particles (multiple plots in one)\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/08_Multiple_plots_in_one.py>`\n", "\n", "**Exercise A**: Mean squared distance\n", "\n", "The mean squared distance of a diffusing particle (random motion) in 2D can be \n", "calculated by\n", "\n", "$$ d(t)^2 = 4 \\cdot D \\cdot t $$\n", "\n", "Plot the **root** mean squared distance ( $\\sqrt{d(t)^2}$ ) for $D$ = 10 m2/s, $D$ = 20 m2/s and $D$ = 30 m2/s for the first 100 s. Use a legend to annotate which particle is which. \n", "\n", "What is the advantage of using one plot over multiple plots to visualise this?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise B**: Subplots\n", "\n", "Take the function:\n", "\n", "$ f(x) = 3x^4 + \\frac{4}{x} $.\n", "\n", "1. Plot the function and the first, the second, and the third derivative in one \n", "plot, with -1 < x < 1. What do you see: are there any issues with this plot?\n", "\n", "2. Instead, now plot the function and it's first to third derivative in a \n", "total of four subplots. What are the advantages of using subplots in this case?\n", "\n", "Tip: you can use `fig.tight_layout()` to prevent overlap between subplot titles.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "ecc4912e", "metadata": {}, "source": [ "`````{exercise} [**] Beavers II\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Nina/05_Beavers_II.py>`\n", "\n", "```{figure} ../Coding_exercises/Week_4/Nina/American_Beaver.jpg\n", "---\n", "height: 200px\n", "name: beavers\n", "---\n", "[Photo source](https://www.whatismissing.org/timeline/american-beaver-timeline).\n", "```\n", "\n", "This exercise builds on the beavers exercise from the previous chapter ([data source](https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/beavers.html)).\n", "\n", "As a reminder:\n", "We are working with a small part of a study of the long-term temperature \n", "dynamics of beaver *Castor canadensis* in north-central Wisconsin. Body \n", "temperature was measured by telemetry every 10 minutes for four females, but \n", "data from one period of less than a day of two animals is used here.\n", "\n", "In the previous beavers exercise, you combined the data of two beavers into one\n", "table, which you saved on your computer. This file you previously prepared is the\n", "starting point of this exercise.\n", "\n", "**Exercise A**: Import data into Python\n", "\n", "Load your table that combines the data of two beavers into Python and perform some\n", "preliminary data exploration using Python:\n", "* Which columns are in the data? What types of values do they contain?\n", "* How many different animals' data do you have?\n", "* How many different values are possible for activity outside retreat, and how \n", "many of each do you have in the data?\n", "* How many different days and timepoints are in the data?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise B**: Exploratory plotting\n", "\n", "No matter the dataset you're handling, after getting acquainted with your \n", "dataset (like you just did in Exercise A) the next thing you will always want \n", "to do is exploratory data analysis via plotting.\n", "\n", "In this exercise, we are not giving you specific directions for plots you \n", "need to make. Instead, knowing what data you have in your beavers table,\n", "think about what plots could be interesting and make them using Python.\n", "\n", "Based on your plots, what can you learn about beavers? Try to learn as much as\n", "possible about these cute rodents from your data.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "5fb9190d", "metadata": {}, "source": [ "`````{exercise} [**] Air quality\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Nina/07_Air_quality.zip>`\n", "\n", "With this exercise, you received a file \"airquality.csv\", containing\n", "daily air quality measurements in New York, May to September 1973 ([source](https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/airquality.html)).\n", "\n", "Check the data in the terminal, then import the file into Python and perform \n", "exploratory analysis of data contents. \n", "\n", "Based on what you learn, decide which plots would be useful to learn more \n", "about the data and make them in Python. Go to the source of the data to \n", "learn more about the units of data in each column. Before plotting, transform \n", "your data such that it's in units commonly used in Europe.\n", "\n", "What can you learn about this data with plotting?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "2befd8ca", "metadata": {}, "source": [ "`````{exercise} [**] Hair and eye color statistics\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Nina/06_HairEyeColor.zip>`\n", "\n", "With this exercise, you received a file \"HairEyeColor.csv\", containing \n", "distribution of hair and eye color in statistics students. The table \n", "comes from a survey of students at the University of Delaware ([source](https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/HairEyeColor.html)).\n", "\n", "Check the data in the terminal, then import the file into Python and perform \n", "exploratory analysis of data contents. Based on what you learn, decide \n", "which plots would be useful to learn more about the data and make them\n", "in Python. \n", "\n", "What can you learn about this data with plotting?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "e68f3e49", "metadata": {}, "source": [ "`````{exercise} [**] Cell location\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/03_Cell_location.zip>`\n", "\n", "In this exercise on data analysis you will practice importing data to Python, \n", "using simple mathematical commands on matrices and data frames. \n", "\n", "Import \"cell_location.txt\" data into Python and print the first ten rows.\n", "\n", "This dataset follows a single simulated cell as it diffuses. \n", "The two rows represent the *x* and *y* coordinate of the cell, respectively.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "As you can see, the *x* and *y* coordinates are offset. Subtract this offset \n", "from the dataset and save the new data to a file called \"cell_location_new.txt\".\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "Now, plot the trajectory of the cell from your new cell position data. \n", "Don't forget to annotate the axes and generally make a visually pleasing plot.\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "What is the total distance travelled by the cell? \n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "bcbdb681", "metadata": {}, "source": [ "`````{exercise} [**] Radioactive decay\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/09_Radioactive_decay.py>`\n", "\n", "In this exercise you will simulate the radioactive decay of polonium, with a \n", "half-life of 388 years. Start with 1,000 radioactive atoms and follow the \n", "decay for 4,000 years, indexing the current number of atoms every ten years. \n", "\n", "**Exercise A**: Exponential \n", "\n", "Plot the number of radioactive polonium molecules versus time, using \n", "that $N(t) = N_0(\\frac{1}{2})^{t/t_{\\frac{1}{2}}}$, where:\n", "* $N(t)$: The number of radioactive atoms remaining at time t\n", "* $N_0$: The initial number of radioactive atoms\n", "* $t$: Time elapsed\n", "* $t_{1/2}$: The half-life of the substance\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise B**: Stochastic\n", "\n", "Radioactive decay is a stochastical process. Instead of following a nice \n", "exponential, each atom has a 1/388 chance to decay per year. \n", "\n", "Write a `for` loop, in which `np.random.rand()` is used to simulate how many \n", "molecules decay within those ten years. Then, plot the amount of molecules every\n", "ten years as well as the theoretical result in one plot. \n", "\n", "Don't forget to add a legend. \n", "Add a second, zoomed in plot of a section (use subplots!).\n", "\n", "Note: `np.random.rand()` gives a random number between 0 and 1 from a uniform \n", "distribution. We can use it to simulate stochastic events by writing code that\n", "effectively says \"do x only if np.random.rand() < 1/388\".\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] }, { "cell_type": "markdown", "id": "cb3cc006", "metadata": {}, "source": [ "`````{exercise} [**] DIY plotting\n", ":class: dropdown\n", "\n", "If you want to challenge yourself further with importing, manipulating, and plotting data, you can download a lot of interesting public datasets from [Kaggle's website](https://www.kaggle.com/datasets). \n", "`````" ] }, { "cell_type": "markdown", "id": "41e3d84c", "metadata": {}, "source": [ "`````{exercise} [***] Projectile motion\n", ":class: dropdown\n", "{download}`Download this exercise.<../Coding_exercises/Week_4/Verena/10_Projectile_motion.py>`\n", "\n", "Although it is nice (and valuable) to calculate the range of projectile \n", "motion by hand, it is much more convenient to write a program that allows you \n", "to study this motion and do various calculations within a few seconds. \n", "The basic equations are:\n", "\n", "$$x = v_x \\cdot t = v \\cdot \\cos(\\theta) \\cdot t $$\n", "$$y = v_y \\cdot t - 1/2 \\cdot g \\cdot t^2 = v \\cdot \\sin(\\theta) \\cdot t - 1/2 \\cdot g \\cdot t^2 $$\n", "\n", "where $x$ and $y$ are the respective position components, $g$ is the gravitational constant, $t$ indicates time, $v$ is the velocity of the throw and $\\theta$ is the angle the ball was thrown at.\n", "\n", "**Exercise A**: \n", "\n", "Plot the projectile motion for $\\theta$ = $\\pi/3$ and $v$ = 100 m/s and plot the ($x,y$)-position for 15 seconds. \n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "**Exercise B**: \n", "\n", "The above plot shows the projectile motion, but does not stop at $x$ = 0. You can solve these equations for $t_{max}$ and $x_{max}$:\n", "\n", "\n", "$$t_{max} = \\frac{2 v_y}{g} = \\frac{2 v \\sin(\\theta)}{g} $$\n", "$$x_{max} = v_x t_{max}=\\frac{2 v_x v_y}{g} = \\frac{2 v^2 \\cos(\\theta) \\sin(\\theta)}{g}$$\n", "\n", "\n", "* Write a function which returns $x_{max}$ as a function of inputs $\\theta$ and $v$. \n", "* Make an array with 20 evenly spaced angles $\\theta$ in the $[0,\\pi/2]$ domain, using `numpy.linspace`.\n", "* Plot $x_{max}$ as a function of $\\theta$ for $v=10$ m/s. \n", "* Additionally, plot $x_{max}$ as a function of $\\theta$ for $v=20$ m/s. \n", "\n", "From the two plots, which angle is the best to reach the maximal $x_{max}$?\n", "\n", "```\n", "# Your code here\n", "```\n", "\n", "`````" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5 }