diff --git a/LearningPhysics.ipynb b/LearningPhysics.ipynb index 615b321..f7f96fd 100644 --- a/LearningPhysics.ipynb +++ b/LearningPhysics.ipynb @@ -1,1326 +1,1551 @@ { "cells": [ { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": true }, "source": [ "\n", - "# Workshop \"Teaching Sciences and Engineering with Jupyter Notebooks\" 2022\n", - "C. Hardebolle, [CC-BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n", + "# Workshop \"Teaching Sciences and Engineering with Jupyter Notebooks\" 2022-2023\n", + "C. Hardebolle, [CC-BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "tags": [], + "toc-hr-collapsed": true + }, + "source": [ + "What is this notebook about?\n", + "\n", + "This notebook is a demonstration example, to illustrate the different possibilities allowed by the technology, as well as best practices to maximize learning for students.\n", "\n", + "This notebook is meant to be used as if you were a student. \n", + "To get a realistic experience, I advise you to **really try to perform the activities** (there are only 4 activities, this should take you something like 20 minutes maximum)." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "toc-hr-collapsed": true + }, + "source": [ "
\n", " How to use this notebook?
\n", - " This notebook is made of text cells and code cells. The code cells have to be executed to see the result of the program.
To execute a cell, simply select it and click on the \"play\" button () in the tool bar just above the notebook, or type shift + enter.
It is important to execute the code cells in their order of appearance in the notebook.\n", + "
Simply read the text and follow the instructions.
\n", + " This notebook contains some code cells, which have to be executed to see the result of the program. To execute a cell, select it and click on the \"play\" button () in the tool bar just above the notebook, or type shift + enter. It is important to execute the code cells in their order of appearance in the notebook.\n", "
" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# The physics of suspended objects\n", + "\n", + "In this notebook, you will learn about the physical principles that apply when suspending objects (forces in static equilibrium) and you will apply them to a concrete problem using Python. " + ] + }, { "cell_type": "markdown", "metadata": { + "tags": [], "toc-hr-collapsed": true }, "source": [ - "
\n", - "\n", - "# Learning goals\n", + "## Learning goals\n", "\n", "After using this notebook, you should be able to:\n", - "* Analyze how the position of the cable influences the tension force in the jeans problem\n", - "* Describe how the counterweight influences the position of the cable in the jeans problem\n", - "* Use Python to make mathematical calculations and write simple functions\n", - "\n" + "* Identify the forces involved when suspending an object with a cable\n", + "* Analyze how the position of the cable influences the tension force\n", + "* Use Python to make mathematical calculations and write simple functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "
\n", + "## Introductory mini-lecture\n", + "\n", + "The video below reviews the forces exerted on an object when suspended with one and two cables, while in static equilibrium. \n", + "**Watch this video if you need a refresher on the tension force $\\vec{T}$**. Otherwise you can jump straight to the application problem.\n", + "\n", + "
\n", + " Activity
\n", + "\n", + "**Execute the code cell below** to load the video and click on the play button to watch it.\n", + " \n", + "
" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from IPython.display import IFrame\n", + "IFrame('https://tube.switch.ch/embed/niV45RmFnr', 640, 360)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "toc-hr-collapsed": false + }, + "source": [ + "

\n", "\n", "---" ] }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "tags": [] + }, "source": [ - "# The problem\n", + "# Application problem: suspended jeans\n", + "\n", + "
\n", "\n", - "The question we are trying to answer in this notebook is the following: \n", - "**Estimate which counterweight allows to suspend wet jeans (3kg) on the cable in the position illustrated below.**\n", + "The question we want to answer in this notebook is the following: \n", + "**Which counterweight allows to suspend wet jeans (3kg) on the cable in the position illustrated below?**\n", "\n", "\"suspended\n", - "\n", + "" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "tags": [] + }, + "source": [ + "
\n", + "\n", + "The activities below will guide you to find out the answer to this question by exploring how the counterweight affects the position of the jeans suspended on the cable. \n", "\n", + "But before diving into the problem, it is interesting to figure out if you have the correct intuition about the answer. \n", + "Research on problem solving has shown that knowing the extent and limits of your intuition plays a role in problem solving expertise. \n", + "Therefore the first activity in this notebook is to try to **guess the correct answer** without solving the problem." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + " Activity
\n", + "\n", + "**Execute the code cell below to display the poll**, then **vote for the answer you think is correct**. \n", + "This poll is completely anonymous, you will not see the answers of the others (and you will not see if your answer is correct or not either). \n", + "The goal here is only for you to commit to an answer.\n", "\n", - "The activities below allow you to find out the answer to this question by exploring how the counterweight affects the position of the jeans suspended on the cable. " + "*You will need to accept the cookies to be able to vote.*\n", + "
\n" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from IPython.display import IFrame\n", + "IFrame('https://speakup.epfl.ch/room/join/14804', 400, 600)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the following, you are guided to solve this problem step by step, using Python." ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": false }, "source": [ - "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Analyzing the problem\n", "\n", "Our first step, as with any problem, should be to analyze the question into more details and this includes:\n", "* Identifying assumptions we can make to simplify the question\n", "* Making a sketch \n", "* Identifying the parameters of the problem" ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": false }, "source": [ "## How can we simplify the problem?\n", "We can make the assumption that the jeans do not move on the cable, i.e. the whole system is in static equilibrium. \n", "In that case, it is like the cable is attached to fixed points on both sides, we can ignore the pulley. Let's make a sketch.\n", "\n", "\"sketch\"\n", "

Figure 1: Simplified suspended jeans situation

\n", "\n", "\n", - "Therefore we are in a situation which is **identical to the one seen in the mini-lecture**.
\n", - "The only difference is that the cable is attached to poles instead of the ceiling but this doesn't change anything in terms of the forces applied to the jeans, which are:\n", - "* the weight $\\vec{F}$ \n", - "* the tensions $\\vec{T}$ on both sides of the cable, which are identical in norm if we assume that the jeans are suspended right in the middle of the cable\n", + "Therefore we are in a situation which is identical to the one seen in the mini-lecture: it's like **the jeans are suspended with two identical cables on both sides**.
\n", + "The only difference is that the cables are attached to poles instead of the ceiling but this doesn't change anything in terms of the forces applied to the jeans, which are:\n", + "* The **weight** $\\vec{F}$ ;\n", + "* The two **tensions** $\\vec{T}$ on both sides, which are identical in norm if we assume that the jeans are suspended right in the middle of the cable. \n", + " These two tensions add up to a vertical **resulting tension** $\\vec{T}_r$\n", + "\n", + "If we draw a line that represents the horizon, we see that the cable makes an **angle $\\alpha$ with the horizon**.
\n", + "Let's add the forces and the angle to our sketch.\n", "\n", - "However we need to figure out where the angle $\\alpha$ is. \n" + "\"sketch\"\n", + "

Figure 2: Angle and forces in the suspended jeans situation

\n", + "\n", + "
\n", + "\n", + "Now from there, how do we get to the counterweight? \n", + "Intuitively, we can predict that **the higher the tension in the cable, the heavier the counterweight needed** to keep the cable taught. \n", + "Therefore our next step should be to compute the tension in the cable.\n" ] }, { "cell_type": "markdown", "metadata": { "tags": [], "toc-hr-collapsed": false }, "source": [ - "## Where is the angle $\\alpha$?\n", - "If we draw a line that represents the horizon, then **the angle $\\alpha$ is the angle between the cable and the horizon**.
\n", - "Let's add the forces and the angle to our sketch.\n", + "## Computing the tension in the cable\n", "\n", - "\"sketch\"\n", - "

Figure 2: Angle and forces in the suspended jeans situation

\n", + "In static equilibrium, the resulting tension $\\vec{T}_r$ compensates the weight $\\vec{F}$ (Newton's law), which we write $ \\lvert\\vec{T}_r\\rvert = \\lvert\\vec{F}\\rvert$. \n", + "\n", + "The resulting tension $\\vec{T}_r$ is the vectorial sum of the two tension forces on both sides of the jeans, $\\vec{T}_r = 2.\\vec{T}$. \n", + "When projecting the two tensions $\\vec{T}$ on the vertical axis we get that $\\lvert\\vec{T}_r\\rvert = 2.\\lvert\\vec{T}\\rvert.sin(\\alpha)$. \n", "\n", + "By combining the two previous equations we get that $\\lvert\\vec{F}\\rvert = 2.\\lvert\\vec{T}\\rvert.sin(\\alpha)$. \n", + "And since $\\lvert\\vec{F}\\rvert = m.g$ we get that $m.g = 2.\\lvert\\vec{T}\\rvert.sin(\\alpha)$.\n", "\n", - "We can therefore **use the equation seen in the mini-lecture, which gives the tension in the cable** depending on the mass $m$ of the suspended object, the angle $\\alpha$ that the cable makes with the horizon and the gravity of earth $g$:\n", + "This allows us to figure out the **tension in the cable** $\\lvert\\vec{T}\\rvert$ as a function of the mass $m$ of the suspended object, the angle $\\alpha$ that the cable makes with the horizon and the gravity of earth $g$:\n", "\n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = \\frac{\\frac{1}{2}.m.g}{sin(\\alpha)}\n", "\\end{align}\n", "$\n", "\n", - "Computing the tension in the cable will help us figure out the counterweight necessary to maintain the cable taught: intuitively, we can predict that **the higher the tension in the cable, the heavier the counterweight needed** to keep the cable taught. " + "Now, while the parameters $m$ and $g$ are fixed and known, the angle $\\alpha$ is not. According to the above equation, we can see that the tension in the cable will depend on how much we want the cable taught. Let's explore the influence of the angle $\\alpha$ on $\\lvert\\vec{T}\\rvert$.\n", + "\n", + "" ] }, { "cell_type": "markdown", "metadata": { "tags": [], "toc-hr-collapsed": false }, "source": [ - "## How does the angle $\\alpha$ influence the forces on the jeans?\n", + "## How does the angle $\\alpha$ influence the tension force?\n", "\n", "\n", - "Now, we know that the mass of the jeans is $m =$ 3kg and that the gravity of earth is $g =$ 9.81m.s$^{-2}$, but we don't know the value of $\\alpha$. \n", - "From the sketch in the original question, which we show again below, we can guess that $\\alpha$ is probably quite small, but how small?\n", - "\n", - "\"suspended\n", - "

Figure 3: The suspended jeans situation in the original question

\n", - "\n", - "In the following, we are going to use the `suspendedobjects` library to visualize concretely what a particular value for $\\alpha$ means. \n", + "In the following, we are going to use the `suspendedobjects` library to visualize concretely how the angle $\\alpha$ influences the tension force. \n", "For this, we need to import some useful Python libraries. \n", "\n", "
\n", " Activity
\n", "\n", "**Execute the code cell below** so that the necessary libraries get imported.\n", " \n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# We need Numpy for some mathematical functions (e.g. sinus)\n", "import numpy as np\n", "\n", "# We will do some plotting with Bokeh\n", "from bokeh.plotting import figure\n", "\n", "# We will use a custom library with visualizations developed for this exercise\n", "from lib.suspendedobject import *\n", "\n", "# And display a message once all libraries are imported\n", "print(\"Libraries imported.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now we can start to use Python for visualizing our angle $\\alpha$. \n", - "The `suspendedobjects` library generates a situation with poles 1.5 meters high, separated by a 5 meter distance, and shows the angle $\\alpha$ as well as the forces on the jeans. \n", - "**Which value should $\\alpha$ be to reflect appropriately the angle in the original question (see [Figure 3 above](#fig1) above)?**" + "Now we can start to use Python for visualizing the influence of our angle $\\alpha$. \n", + "The `suspendedobjects` library generates a situation with poles 1.5 meters high, separated by a 5 meter distance, and shows the angle $\\alpha$ as well as the forces on the jeans." ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": false }, "source": [ "
\n", " Activity
\n", " \n", - "Execute the code cell below to generate the visualization with the jeans suspended on the cable.
\n", - "**Make a guess for the value of $\\alpha$** that would reflect appropriately the angle in [Figure 3 above](#fig1) then **replace the value of ``alpha`` with the value you have chosen** and execute the cell to see the result.
\n", - "If your guess does not seem to reflect completely the angle in the original question (see [Figure 3 above](#fig1)), feel free to change it and execute the cell again until you are satisfied.\n", + "Execute the code cell below to launch the interactive visualization with the jeans suspended on the cable.
\n", + "Then use the slider at the bottom to vary the value of $\\alpha$ and **compare the tension $\\vec{T}$ in the cable** with $\\alpha$ = 20$^\\circ$ and with $\\alpha$ = 5$^\\circ$. \n", + "**What do you observe?** \n", + "\n", + "You can check your answer against the solution below the visualization.\n", + " \n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "# Choose a value for alpha, in degrees\n", - "alpha = 20 # CHANGE THE VALUE HERE\n", - "\n", "# Build a concrete situation where poles measure 1.5 meters and are distant from 5 meters\n", "lab = SuspendedObjectLab(m_object = 3, height = 1.5, distance = 5)\n", "\n", - "# Visualize the angle\n", - "lab.visualize_angle(alpha);" + "# Launch the interactive visualization\n", + "lab.launch();" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now that you have chosen a value for $\\alpha$, the question is: **how does it affect the tension in the cable?**
\n", - "\n", - "
\n", - " Activity
\n", - "\n", - "Compare the tension in the cable with $\\alpha$ = 20$^\\circ$ and with the value you have chosen for $\\alpha$. \n", - "**What do you observe?** \n", - "**Execute the code cell below to display the chat**, then **post a message** with the value you suggest for $\\alpha$ and a description of how you think the angle influences the tension in the cable.

\n", - "You can compare with what others have written and vote for the best explanation using the \"thumb up\" icon.\n", + "
\n", "\n", - "*This chat is completely anonymous.* \n", - "*You might need to accept the cookies to see the text box where to post your message.*\n", - "
\n" + "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", + " \n", + "
" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "cell_type": "markdown", + "metadata": { + "jupyter": { + "source_hidden": true + }, + "tags": [] + }, "source": [ - "from IPython.display import IFrame\n", - "IFrame('https://speakup.epfl.ch/room/76017', 400, 500)" + "
\n", + " Solution
\n", + "\n", + "\n", + "We can clearly see with the red arrows that the tension $\\vec{T}$ is much smaller when $\\alpha$ = 20$^\\circ$ than when $\\alpha$ = 5$^\\circ$. \n", + "The smaller the angle, the higher the tension in the cable.\n", + " \n", + "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Computing the tension in the cable with Python\n", "\n", - "To get a more precise view of what is happening, we will now compute the tension in the cable using the equation from the mini-lecture:\n", + "To get a more precise view of what is happening, we will now compute the value of the tension in the cable using the equation we obtained:\n", "\n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = \\frac{\\frac{1}{2}.m.g}{sin(\\alpha)}\n", "\\end{align}\n", "$\n", "\n", "In the following we are going to use Python to **compute the tension in the cable** for **different values of the angle $\\alpha$**." ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "## Defining the constants of our physics problem\n", "\n", "In the above equation we have two constants:\n", "- $g$ the gravity of earth, which is 9.81m.s$^{-2}$\n", "- $m$ the mass of the suspended object, which is 3 kg in the case of the jeans\n", "\n", "
\n", " Activity
\n", "\n", "**Execute the code cell below** so that these two constants get defined in Python.\n", " \n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's define the value of gravity\n", "g = 9.81\n", "\n", "# And the mass of the jeans\n", "m = 3\n", "\n", "# Display the value of the constants to check they are well defined\n", - "print(\"gravity:\", g, \", jeans_mass:\", m)" + "print(\"gravity:\", g, \", jeans mass:\", m)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"lightbulb\"\n", + "Why bother defining these constants instead of using numerical values directly in our computations? Giving names to numerical values is actually a good programming practice: in the case you need to change one of these values at some point, you can do it in one place only, instead of replacing the values everywhere in your code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating a function to compute the tension in the cable\n", "\n", "Let's define a Python function that represents the equation of the tension. \n", "Its input parameters are:\n", "* `g`: the gravity of earth\n", "* `m`: the mass of the jeans\n", "* `alpha`:the angle that the cable makes with the horizon\n", "\n", "It returns the value of the mass of the counterweight as computed with the equation $\n", "\\begin{align}\n", "\\frac{\\frac{1}{2}.m.g}{sin(\\alpha)}\n", "\\end{align}\n", "$\n", "\n", "
\n", " Activity
\n", "\n", "In the code cell below, **complete the code of the function `tension_norm`** by implementing the equation above. \n", "Here is some syntax you will need:\n", "* variables: you can use `g`, `m` and `alpha`\n", "* multiplication: `*`\n", "* division: `/`\n", "* sinus function $sin(x)$: `np.sin(x)`\n", "\n", "You can also use parentheses to indicate the order of operations.\n", " \n", "Then **execute the code cell** so that this function gets defined in Python.\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Then let's define the function\n", "def tension_norm(g, m, alpha):\n", " tension = 1 # REPLACE \"1\" BY YOUR EQUATION HERE\n", " return tension\n", "\n", "# And display a message once it is defined\n", "print(\"Function defined.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "source": [ "
\n", " Solution
\n", "\n", "Your function should look like the following:\n", "\n", "def tension_norm(g, m, alpha):\n", " tension = (1/2 * m * g) / np.sin(alpha)\n", " return tension\n", "\n", "\n", "
" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\"lightbulb\"\n", + "Why bother defining a function instead of doing the computation directly? This is actually a good programming practice: by defining a function that computes the norm of the tension like this, we can reuse it several times in the notebook instead of copy-pasting the same computation several times. Functions make code reusable. In addition, if we make a mistake or need to do a modification, we can do it in one place only, instead of having to find all the places where we have written the same code." + ] + }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "## Computing the tension in the cable using our function\n", "\n", "Now let's use this Python function to compute the norm of the tension in the cable for a given angle of $\\alpha$.\n", "\n", "Because our function takes the sinus of our angle $\\alpha$, we first need to convert it from degrees into radians. \n", "This is where the library we have imported gets useful as it provides us with a function `degrees_to_radians` which we can use to convert our angle.\n", "\n", "The code cell below defines a value for $\\alpha$ in degrees, converts it to radians, then computes the tension on the cable using our previously defined function with `g` = 9.81 m.s$^{-2}$ and `m` = 3 kg and prints the result." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "# First choose an angle alpha\n", - "alpha = 20 # CHANGE THE VALUE HERE\n", + "# First choose an angle alpha in degrees\n", + "alpha = 2\n", "\n", "# Then convert it to radians\n", "alpha_radians = degrees_to_radians(alpha)\n", "\n", - "# Then compute the tension using our equation with g = 9.81 m.s-2 and m = 3 kg\n", + "# Then compute the tension using our equation with the values we have defined for g, m and alpha (in radians)\n", "T = tension_norm(g, m, alpha_radians)\n", "\n", "# And print the result\n", "print(\"Norm of the tension in the cable: T =\", T, \"N\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Activity
\n", "\n", - "**Change the value of $\\alpha$ with the value you have chosen, then execute the code cell** to see the value of the corresponding tension force $\\lvert\\vec{T}\\rvert$, expressed in Newtons. \n", - " \n", - "You can compare the value you obtain to the force exerted by earth gravity on the jeans, which weight 3 kg: $\\lvert\\vec{F}\\rvert = $ 29 $N$ \n", - "Is the tension in the cable bigger or smaller than the weight of the jeans on the cable? Why?\n", + "**Execute the code cell** to see the value of the tension force $\\lvert\\vec{T}\\rvert$ corresponding to an angle $\\alpha$ of 2$^\\circ$, expressed in Newtons. \n", " \n", + "**Compare the value you obtain** to the force exerted by earth gravity on the jeans, which weight 3 kg: $\\lvert\\vec{F}\\rvert = $ 29 $N$ \n", + "Is the tension in the cable bigger or smaller than the weight of the jeans on the cable? Why? \n", "Note down your answer in the cell below, then you can check the solution by clicking on the \"...\" below.\n", "\n", + "*NB: feel free to change the value of $\\alpha$ in the code cell above and then execute the cell again to see the corresponding values for the tension force.*\n", + " \n", "
" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "Just note down your answer here (this cell is for note taking):\n", "..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "source": [ "
\n", " Solution
\n", "\n", - "If you have chosen an angle $\\alpha$ smaller than 30$^\\circ$ (which is quite likely), then you will notice that the tension $\\lvert\\vec{T}\\rvert$ is bigger than the weight of the jeans.\n", + "For an angle $\\alpha$ of 2$^\\circ$, you can observe that the tension $\\lvert\\vec{T}\\rvert$ is more than 10 times bigger than the weight of the jeans.\n", " \n", "This is because such small angles make the cable more horizontal whereas the weight of the jeans is purely vertical, therefore a higher tension will be necessary to create the vertical resulting force that compensates for the weight of the jeans.\n", " \n", "\"sketch\"\n", "\n", "Mathematically speaking, remember that the tension is defined by the following equation: \n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = \\frac{\\frac{1}{2}.m.g}{sin(\\alpha)}\n", "\\end{align}\n", "$\n", "\n", "Because the weight of the jeans is $\\lvert\\vec{F}\\rvert = m.g$, the tension can also be written: \n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = \\frac{\\frac{1}{2}}{sin(\\alpha)}.\\lvert\\vec{F}\\rvert\n", "\\end{align}\n", "$\n", "\n", "As a consequence:\n", "* For angles between 0$^\\circ$ and 30$^\\circ$, $sin(\\alpha)$ will be between 0 and $\\frac{1}{2}$ and therefore we will have $\\lvert\\vec{T}\\rvert > \\lvert\\vec{F}\\rvert$\n", "* For angles between 30$^\\circ$ and 90$^\\circ$ (although such high values do not really make sense in the real situation), $sin(\\alpha)$ will be between $\\frac{1}{2}$ and 1 and therefore we will have $\\lvert\\vec{T}\\rvert < \\lvert\\vec{F}\\rvert$\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. From the tension to the counterweight\n", "\n", "Now how can we relate this tension to the counterweight in our original question? \n", "A key here is to understand that **the tension is transmitted in the cable to the counterweight**, and that **the pulley only changes the direction of the force**, it does not affect its value.\n", "\n", "Therefore the weight $\\vec{F_{cw}}$ of the counterweight will have to compensate exactly the tension $\\vec{T}$ in the cable, as indicated on the sketch below.\n", "\n", "\"sketch\"\n", "

Figure 4: Forces on the counterweight

\n", "\n", "We can write this as an equation: \n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = \\lvert\\vec{F_{cw}}\\rvert\n", "\\end{align}\n", "$\n", "\n", "Since the weight of the counterweight is $\\lvert\\vec{F_{cw}}\\rvert = m_{cw}.g$, we can therefore write: \n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = m_{cw}.g\n", "\\end{align}\n", "$\n", "\n", "From there we can find the mass of the counterweight $m_{cw}$: \n", "$\n", "\\begin{align}\n", "m_{cw} = \\frac{\\lvert\\vec{T}\\rvert}{g}\n", "\\end{align}\n", - "$\n", - "\n", + "$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Python for the computation\n", "\n", "Again we can use python to make this simple computation, using the values `T` and `g` computed earlier." ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "
\n", " Activity
\n", "\n", "**Complete the code cell below** to compute the mass of the counterweight according to the equation above. \n", - "Then **execute the code cell** to see which counterweight would allow the jeans to be suspended with the angle $\\alpha$ you have chosen earlier.\n", + "You can use the variables `T` and `g` that we have defined earlier. \n", + "Then **execute the code cell** to see which counterweight would allow the jeans to be suspended with the angle $\\alpha$ chosen earlier.\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# Let's compute the mass of the counterweight to compensate for the tension in the cable\n", "m_cw = 1 # REPLACE \"1\" WITH YOUR EQUATION HERE\n", "\n", "# And print the result\n", "print(\"Mass of the counterweight: m =\", m_cw, \"kg\")" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "
\n", "\n", "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "source": [ "
\n", " Solution
\n", "\n", "Your code should look like the following:\n", "\n", "m_cw = T / g\n", " \n", - "Of course, if you are at ease with Python you can write this as a function, which could also call the ``tension_norm`` function defined earlier instead of using ``T``...\n", + "Of course, if you are at ease with Python you can write this as a function, which could also call the ``tension_norm`` function defined earlier instead of using ``T``, which would be a better programming design...\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "So now let's come back to our original question: \"which counterweight do you think would allow to suspend the jeans (3kg) on the cable in the position illustrated below?\" \n", - "How does the result you obtained just above compare to your estimation before using this notebook?
\n", - "More importantly, **can you explain why**?\n", + "## Back to the original question\n", + "\n", + "Let's come back to our original question: \"which counterweight do you think would allow to suspend the jeans (3kg) on the cable in the position illustrated below?\" \n", "\n", "\"suspended\n", "\n", + "**How does the result you obtained just above compare to your guess at the beginning of this notebook?** \n", + "This is an opportunity to look back at your intuition: was it correct or not? Why?\n", "\n", "
\n", " Activity
\n", "\n", - "Execute the code cell below and **post a message in the chat** with the value you found for the mass of the counterweight and a brief explanation of why the mass of the counterweight differs from the mass of the jeans. \n", + "Just note down your thoughts in the cell below. \n", "\n", "
\n" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "raw", "metadata": {}, - "outputs": [], "source": [ - "from IPython.display import IFrame\n", - "IFrame('https://speakup.epfl.ch/room/82969', 400, 500)" + "Just note down your answer here (this cell is for note taking):\n", + "..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. What have you learned so far?\n", "\n", + "You have now spent some time doing a number of activities. \n", + "However, research shows that it is very hard to learn from **doing** things, and that we actually learn from **reflecting** on what we have done. \n", + "This is why the last activities in this notebook are designed to help you identify what you have learned from doing all of this and where it could apply.\n", + "\n", "
\n", " Activity
\n", "\n", - "Write **2 things you have learned** about the **tension force** in a cable that is used to suspend an object:\n", + "Write **2 things you have learned** about the **tension force** in a cable that is used to suspend an object: \n", " \n", "
" ] }, { "cell_type": "raw", "metadata": {}, "source": [ + "Just note down your answer here (this cell is for note taking):\n", "- \n", "- " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", + " Activity
\n", "\n", "Can you identify **other real-life situations** in which cables are used to suspend objects or in which cables are taut between poles? \n", - "Write 2 ideas:\n", + "\n", + "**Execute the code cell below to display the forum**, then **post a message** with your idea.
\n", + "You see what others have written and vote for the ideas you find interesting using the \"thumb up\" icon.
\n", + "*This forum is completely anonymous.* \n", "\n", "
" ] }, { - "cell_type": "raw", + "cell_type": "code", + "execution_count": 3, "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "\n", + " \n", + " " + ], + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "- \n", - "- " + "from IPython.display import IFrame\n", + "IFrame('https://speakup.epfl.ch/room/45263', 400, 400)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", - "Congratulations, you have completed the activities!\n", + "Congratulations, you have completed the activities! \n", + "You can continue with the optional exercises below if you want.\n", + "\n", "\n", "\n", - "Execute the code cell below and click on the \"A\" button to indicate to the instructor that you have completed all the activities.
\n", - "You can then continue with the optional exercises below if you want.\n", + "" ] }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from IPython.display import IFrame\n", - "IFrame('https://speakup.epfl.ch/room/45263', 400, 400)" - ] - }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", + "---\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Additional exercises (optional)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Looking at how the tension in the cable evolves with the angle $\\alpha$\n", "\n", "Now we want to look at **how the tension evolves** when the angle $\\alpha$ changes. \n", - "Thanks to our previously defined Python function, we are going to compute the tension in the cable for 100 different values of $\\alpha$, from 20$^\\circ$ to 0$^\\circ$, and plot the result on a graph. \n", + "Thanks to our previously defined Python function, we are going to compute the tension in the cable for 100 different values of $\\alpha$, from 30$^\\circ$ to 0$^\\circ$, and plot the result on a graph. \n", "\n", "
\n", " Activity
\n", "\n", "**Execute the code cell below** to see the resulting graph.\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's define the boundaries of the graph\n", - "a_start = 20 # start the angle at 20°\n", - "a_stop = 0 # stop at O°\n", + "a_start = 30 # start the angle at 30°\n", + "a_stop = 0 # stop at O° (excluded)\n", "\n", "# Now we generate 100 possible values for the angle alpha between a_start and a_stop (excluded)\n", "a_deg = np.linspace(start=a_start, stop=a_stop, num=100, endpoint = False)\n", "print(\"The 100 different values for the angle alpha:\\n\", a_deg, \"\\n\")\n", "\n", "# Since our previously defined function works with angles expressed in radians, we first convert our list of angles from degrees to radians\n", "a_rad = degrees_to_radians(a_deg)\n", "\n", "# Then we compute the value of the tension for all the 100 possible angles alpha using our previously defined function\n", "t = tension_norm(g, m, a_rad)\n", "print(\"The corresponding values for the tension in the cable:\\n\", t)\n", "\n", "# Finally we generate the plot and customize its appearance\n", "fig = figure(title='Tension in the cable', x_axis_label = 'Angle ⍺ (°)', y_axis_label = 'Tension T (N)', x_range=(a_deg[0],0), width=500, height=400, toolbar_location=None)\n", "fig.line(a_deg, t, color=\"red\", line_width=2)\n", "show(fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Activity
\n", "\n", "What happens to the tension when the angle $\\alpha$ gets closer to 0$^\\circ$? \n", "Could we ever have $\\alpha$ = 0$^\\circ$, i.e. **could we ever pull the cable taught completely horizontally**?\n", " \n", "Note down your answer in the cell below, then you can check the solution by clicking on the \"...\" below.\n", "
\n" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "Just note down your answer here (this cell is for note taking)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "source": [ "
\n", " Solution
\n", "\n", "The curve on the graph indicates that the tension in the cable is getting infinitely big as the angle $\\alpha$ gets closer to 0$^\\circ$. \n", "This means that we will never be able to pull the cable taught horizontally as this would mean an infinite tension (the cable would break before that).\n", "\n", " \n", "From a mathematical point of view, remember that the tension is defined by the following equation: \n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = \\frac{\\frac{1}{2}.m.g}{sin(\\alpha)}\n", "\\end{align}\n", "$\n", "\n", "When $\\alpha$ tends toward 0, $sin(\\alpha)$ also tends toward 0, therefore the limit of the expression defining the tension in the cable is:\n", "\n", "$\n", "\\begin{align}\n", "\\lim_{\\alpha\\to0}\\; \\lvert\\vec{T}\\rvert = \\lim_{\\alpha\\to0}\\;\\frac{\\frac{1}{2}.m.g}{sin(\\alpha)} = +\\infty\n", "\\end{align}\n", "$\n", "\n", "You can find out the detailed answer to this question below, in the [solution section of the notebook](#Solution:-Is-it-possible-to-pull-the-cable-taut-completely-horizontally?).\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How does our Python function behave with $\\alpha$ = 0?\n", "\n", "What happens with our piece of Python code when we say that the cable it taut completely horizontal, i.e. the angle $\\alpha$ = 0$^\\circ$, which is actually impossible in real life? \n", "\n", "
\n", " Activity
\n", "\n", "In the cell below, call your ``tension_norm`` function with a value of $0$ for `alpha` and execute the cell. \n", "What happens? \n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute the tension with g = 9.81 m.s-2, m = 3 kg and alpha = 0°\n", "T = 1 # REPLACE 1 WITH THE CALL TO YOUR FUNCTION tension_norm HERE\n", "\n", "# And print the result\n", "print(\"Norm of the tension in the cable: T =\", T, \"N\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "source": [ "
\n", " Solution
\n", "\n", "Here is how to call your function:\n", "T = tension_norm(g, m, 0)\n", " \n", "When you execute this code, two things happen:\n", "* You get a warning message which says `RuntimeWarning: divide by zero encountered in double_scalars`\n", "* The function nonetheless returns a value which is `inf`\n", "\n", "When the angle $\\alpha$ = 0 then $sin(\\alpha)$ = 0 and therefore we divide `(.5 * jeans_mass * gravity)` by 0 so on one hand, mathematically speaking, we know that the result should be $+\\infty$. On the other hand, we also know that usually division by 0 is not well supported by computers.\n", "\n", "Actually, division by 0 is not supported in standard Python. \n", "You can create a code cell (click on the `+` icon in the toolbar above) and try to execute the following computation to see what happens: ``(0.5 * 3 * 9.81)/0``\n", " \n", "Now, because in the calculation we use the function `np.sin()` from the Numpy library, our data is automatically converted to Numpy types, which support division by zero and returns the \"real\" result which is $+\\infty$. \n", "By convention, Numpy also generates a warning message but this can be deactivated when not necessary. \n", "If you are curious, you can take a look at [the errors generated by Numpy for floating-point calculations](https://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html#numpy.seterr).\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What are the consequences?\n", "\n", "It is important to know that high tension in a cable is very dangerous and can lead to serious accidents, especially when the cable is not well adapted for its intended use (i.e. not strong enough) or when the cable is progressively deteriorating with use. \n", "\n", "
\n", " Activity
\n", "\n", "Execute the cell below to see the video and watch the first minute (sound is not necessary). \n", "What happens at time 0:53? Why?\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import YouTubeVideo\n", "YouTubeVideo('KIbd5zBek5s', 600, 337, start=45, mute=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "source": [ "
\n", " Solution
\n", "\n", "At time 0:53, the cable desintegrates completely. This is probably because it has grown weaker and weaker after repeated use until it cannot withstand the high tension anymore.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Improving the `tension_norm` function\n", "\n", "As you have noticed, each time you want to call your `tension_norm` function with an angle expressed in degrees, you have first to convert your angle from degrees to radians. \n", "A better design would be to do the conversion of the angle inside the function so that you can pass it angles in degrees directly.\n", "\n", "
\n", " Activity
\n", "\n", "Define a new function `tension_norm_degrees` which converts `alpha` from degrees to radians using the `degrees_to_radians` function, then calls the `tension_norm` function to compute the norm of the tension and returns the result. \n", " \n", "Then **execute the code cell** so that this function gets defined and then tested with an angle $\\alpha$ of 20$^\\circ$. \n", "If your function works correctly, the result of the execution should be `Tension norm: T = 43.023781748399834 N`.
\n", "You can further check your answer with the solution by clicking on the \"...\" below. \n", "\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define your function\n", "def tension_norm_degrees(g, m, alpha):\n", " # WRITE YOUR CODE HERE\n", " return\n", "\n", "# Let's test it: the execution of these lines should give T = 43.023781748399834 N\n", "alpha = 20\n", "T = tension_norm_degrees(g, m, alpha) \n", "print(\"Tension norm: T =\", T, \"N\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Solution** - you can check your answer with the solution by clicking on the \"...\" below.\n", " \n", "
" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true }, "tags": [] }, "source": [ "
\n", " Solution
\n", "\n", "Your function could look like the following:\n", "\n", "def tension_norm_degrees(g, m, alpha):\n", " apha_rad = degrees_to_radians(alpha)\n", " tension = tension_norm(g, m, apha_rad)\n", " return tension\n", "\n", "\n", "Of course the three lines in this function can be combined into just one: \n", "\n", "def tension_norm_degrees(g, m, alpha):\n", " return tension_norm(g, m, degrees_to_radians(alpha))\n", "\n", " \n", "
Note: Another way to test such a function would be to use [Python assertions](https://zetcode.com/python/assert/). \n", "
However, comparing float values can get tricky. These can be made simpler by the use of more elaborate libraries such as ``pytest``, which support [approximations](https://randycoulman.com/blog/2018/06/19/comparing-floats-in-tests/).\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A function that computes the mass of the counterweight\n", "\n", "From the exercises above, we have learned that \n", "$\n", "\\begin{align}\n", "\\lvert\\vec{T}\\rvert = \\frac{\\frac{1}{2}.m.g}{sin(\\alpha)}\n", "\\end{align}\n", "$ and that\n", "$\n", "\\begin{align}\n", "m_{cw} = \\frac{\\lvert\\vec{T}\\rvert}{g}\n", "\\end{align}\n", "$\n", "\n", "From there, we can write the equation for the mass of the counterweight as a function of $\\alpha$:\n", "\n", "$\n", "\\begin{align}\n", "m_{cw} = \\frac{\\frac{1}{2}.m}{sin(\\alpha)}\n", "\\end{align}\n", "$\n", "\n", "
\n", " Activity
\n", "\n", "In the code cell below, write a function `counterweight_mass` that takes `m` and `alpha` as an inputs and returns the mass of the counterweight as computed by the equation above. \n", "Of course you can reuse code from the previous activities as a model. \n", " \n", "Then use this function to compute the counterweight necessary so that the cable makes an angle of 1.5$^\\circ$ with the horizon. \n", "You should find a counterweight of approximately 57 kg.\n", "\n", "You can find the complete solution in the [detailed solution section below](#Numerical-application).\n", "\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Write your code here\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "



\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": true, "toc-nb-collapsed": true }, "source": [ "# Solution: Is it possible to pull the cable taut completely horizontally?\n", "\n", "In this section we demonstrate the physical and mathematical reasoning to answer this question.\n", "\n", "### Goal\n", "\n", "For the cable to be taut completely horizontally means that the angle $\\alpha$ that the cable makes with the horizon is 0$^\\circ$. \n", "In other words, the question could be reframed as: which mass $m_{cw}$ should we put as a counterweight to get $\\alpha$ = 0$^\\circ$?\n", "If we can find a 'reasonable' value for the counterweight then it will mean that it is possible to pull the cable taut completely horizontally.\n", "\n", "To answer this question, we therefore look for an expression relating the **mass of the counterweight $m_{cw}$** and the **angle $\\alpha$** that the cable makes with the horizon.\n", "\n", "\n", "### Method\n", "\n", "Given that the system is in static equilibrium, the sum of external forces exerted on the system will be zero, so using Newton's second law should be easy. The force that the counterweight exerts on the system will involve the mass of the counterweight so we should be able to rewrite Newton's second law to get an expression of the form $m_{cw} = ...$.\n", "\n", "### Hypotheses and simplifications\n", "\n", "We make the following assumptions and simplifications:\n", "* the jeans are considered as positioned exactly mid-way between the poles so the tension is equal on both sides of the cable\n", "* we represent the jeans by the point at which they are suspended\n", "* the cable is considered as rigid (not bended), with a negligible mass\n", "* the pulley is considered as perfect, without mass nor friction\n", "* we consider the static equilibrium obtained after changing the weight, once the system is stabilized\n", "\n", "### Resolution\n", "\n", "First, let's draw a diagram and represent the different forces involved.\n", "\n", "\n", "The *forces applied on the jeans* are:\n", "* the weight: $\\vec F_j = m_j \\vec g$ \n", "* the force exerted by the cable on each side of the jeans: assuming the jeans are suspended at the exact center of the cable, then the tension applied on each of the two sides is equally distributed with two tensions of equal magnitude $T$ on each side but with opposite directions on the $x$ axis, which combine into a vertical resulting tension $\\vec T_r$\n", "\n", "From Newton's second law in a static equilibrium we can write: $\\sum \\vec F_j = \\vec 0$ \n", "With the forces on the jeans we get: $\\vec F_j + \\vec T_r = 0$ \n", "\n", "If we project on $x$ and $y$ axes, we get: \n", "$\\left\\{\\begin{matrix} F_{jx} + T_{rx} = 0 \\\\ F_{jy} + T_{ry} = 0\\end{matrix}\\right. $\n", "\n", "Since $\\vec T_r$ is the result of two tensions of same magnitude $T$ on both sides of the jeans but of opposite directions on the $x$ axis, we can decompose $T_{rx}$ and $T_{ry}$ into the $x$ and $y$ components of $T$: \n", "$\\left\\{\\begin{matrix} T_{rx} = T_{x} - T_{x} \\\\ T_{ry} = 2.T_{y} \\end{matrix}\\right. $\n", "\n", "\n", "Now we can use this in our previous equations, which gives: \n", "$\\left\\{\\begin{matrix} F_{jx} + T_{x} - T_{x} = 0 \\\\ F_{jy} + 2.T_{y} = 0\\end{matrix}\\right. $\n", "\n", "\n", "Since the two $T_{x}$ cancel out we cannot know their value yet and so we focus on the second equation: \n", "$\\begin{align} F_{jy} + 2.T_y = 0 \\end{align}$\n", "\n", "The component of the weight on the y axis is $F_{jy} = - m_j.g$, which gives us: \n", "$\\begin{align} - m_j.g + 2.T_y = 0 \\end{align}$\n", "\n", "Using the angle $\\alpha$ we can get the tension $T_y$ expressed as a function of T since $sin(\\alpha) = \\frac{T_y}{T}$, therefore $T_y = T.sin(\\alpha)$\n", "\n", "By replacing $T_y$ by this expression in the above equation we get: \n", "$\\begin{align} - m_j.g + 2.T.sin(\\alpha) = 0 \\end{align}$\n", "\n", "From there we can get $T$, and this is equation number $(1)$: \n", "\n", "$\n", "\\begin{align}\n", "T = \\frac{m_j.g}{2.sin(\\alpha)}\n", "\\end{align}\n", "$\n", "\n", " \n", "\n", "We now want to make the mass of the counterweight appear in this expression. \n", "So we will now look at the forces applied on the *counterweight*.\n", "\n", " \n", "\n", "The forces applied on the *counterweight* are:\n", "* the weight: $\\vec F_{cw} = m_{cw} \\vec g$ \n", "* the force exerted by the cable: a simple pulley simply changes the direction of the tension so the tension applied on the counterweight is therefore of the same magnitude $T$ as before but with a different direction - we will note it $\\vec T$\n", "\n", "From Newton's second law in a static equilibrium we can write: $\\sum \\vec F_{cw} = \\vec 0$ \n", "With the forces involved in our problem : $\\vec F_{cw} + \\vec T = \\vec 0$ \n", "\n", "All forces being vertical, there is no need to project on $x$ so we get: $- F_{cw} + T = 0$ \n", "We replace the weight by its detailed expression: $-m_{cw}.g + T = 0$ \n", "Now we can express $T$ as a function of the other parameters, which is equation number $(2)$: $T = m_{cw}.g$ \n", "\n", " \n", "\n", "Let's now summarize what we have so far with equations $(1)$ and $(2)$: \n", "\n", "$\n", "\\begin{align}\n", "\\left\\{\\begin{matrix}T = \\frac{m_j.g}{2.sin(\\alpha)} \\\\ T = m_{cw}.g\\end{matrix}\\right. \n", "\\end{align}\n", "$\n", "\n", "These two equations combined give us:\n", "\n", "$\n", "\\begin{align}\n", "\\frac{m_j.g}{2.sin(\\alpha)} = m_{cw}.g\n", "\\end{align}\n", "$\n", "\n", "This allow us to find the mass of the counterweight as a function of the *mass of the jeans* and of the *angle that the cable makes with the horizon*: \n", "\n", "
\n", "\n", "$$m_{cw} = \\frac{m_j}{2.sin(\\alpha)}$$\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conclusion\n", "\n", "When the cable approaches the horizon, $\\alpha$ is really small i.e. really close to zero. \n", "This means that $sin(\\alpha)$ is also close to zero, which means in turn that $m_{cw}$ is very big.\n", "Therefore, **the more we want the cable to be close to the horizon, the bigger $m_{cw}$ we will need!**\n", "\n", "Mathematically speaking, the limit of the expression defining the mass of the counterweight when alpha tends to 0 is:\n", "\n", "$\n", "\\begin{align}\n", "\\lim_{\\alpha\\to0}m_{cw} = \\lim_{\\alpha\\to0}\\frac{m_j}{2.sin(\\alpha)} = +\\infty\n", "\\end{align}\n", "$\n", "\n", "So basically, we would need to put an **infinitely heavy counterweight** to make the angle null and that is why it is impossible to get the cable taut so that it is absolutely straight (the cable would break before that!)..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Numerical application\n", "\n", "We have already defined above the constant `m` which represents the mass of our jeans (3 kg).\n", "\n", "Let's define a Python function that represents the above equation. \n", "The function takes two input parameters, `m` which represents the mass of our jeans and `alpha`, the angle that the cable makes with the horizon. \n", "It returns the mass of the counterweight as computed with the equation above." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the function\n", "def counterweight_mass(m, alpha):\n", " return m / (2 * np.sin(alpha))\n", "\n", "# And display a message once it is defined\n", "print(\"Function defined.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For an angle $\\alpha$ of $1.5^\\circ$, we need to put a counterweight of:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Choose a value for angle alpha\n", "alpha = 1.5\n", "\n", "# Then convert it to radians\n", "alpha_radians = degrees_to_radians(alpha)\n", "\n", "# Compute the mass of the counterweight using our function\n", "m_cw = counterweight_mass(m, alpha_radians)\n", "\n", "# And print the result\n", "print(\"Mass of the counterweight: m_cw =\", m_cw, \"kg\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.10" }, "toc-autonumbering": false, "toc-showcode": false, "toc-showmarkdowntxt": false }, "nbformat": 4, "nbformat_minor": 4 } diff --git a/README.md b/README.md index df0bb93..6a3f770 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # Workshop "Teaching Sciences and Engineering with Jupyter Notebooks" 2022 -This repository contains the notebooks for the EPFL workshop "Teaching Sciences and Engineering with Jupyter Notebooks" 2022. +This repository contains the notebooks for the EPFL workshop "Teaching Sciences and Engineering with Jupyter Notebooks" 2022-2023. + +The contents of this repository are available under a CC BY-NC-SA 4.0 license, unless stated otherwise. For any enquiries relating to this template or this repository, please contact: [noto-support@groupes.epfl.ch](mailto:noto-support@groupes.epfl.ch) This repository is available at: https://c4science.ch/source/notebooks-workshop/ diff --git a/figs/epfl-innovation1.png b/figs/epfl-innovation1.png new file mode 100644 index 0000000..7c7b495 Binary files /dev/null and b/figs/epfl-innovation1.png differ diff --git a/lib/suspendedobject.py b/lib/suspendedobject.py index 7380fc8..f8ea5ed 100644 --- a/lib/suspendedobject.py +++ b/lib/suspendedobject.py @@ -1,559 +1,461 @@ import numpy as np from operator import add from ipywidgets import interact, interactive, fixed, interact_manual from ipywidgets import HBox, VBox, Label, Layout import ipywidgets as widgets import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') # global style for plotting from IPython.display import IFrame from IPython.display import set_matplotlib_formats, display, Math, Markdown, Latex, HTML set_matplotlib_formats('svg') from bokeh.io import push_notebook, show, output_notebook, curdoc from bokeh.plotting import figure from bokeh.models import Legend, ColumnDataSource, Slider, Span, LegendItem from bokeh.models import Arrow, OpenHead, NormalHead, VeeHead, LabelSet from bokeh.models.glyphs import Wedge, Bezier from bokeh.layouts import gridplot, row, column output_notebook(hide_banner=True) class SuspendedObjectLab: """ This class embeds all the necessary code to create a virtual lab to study the static equilibrium of an object suspended on a clothesline with a counterweight. """ def __init__(self, m_object = 3, distance = 5, height = 1.5, x_origin = 0, y_origin = 0): ''' Initiates and displays the virtual lab on suspended objects. :m_object: mass of the suspended object :distance: horizontal distance between the two poles :height: height of the poles (same height for both) :x_origin: x coordinate of the bottom of the left pole (origin of the coordinate system) :y_origin: y coordinate of the bottom of the left pole (origin of the coordinate system) ''' ###--- Static parameters of the situation self.m_object = m_object # mass of the wet object, in kg self.distance = distance # distance between the poles, in m self.height = height # height of the poles, in m self.x_origin = x_origin # x coordinate of point of origin of the figure = x position of the left pole, in m self.y_origin = y_origin # y coordinate of point of origin of the figure = y position of the lower point (ground), in m # Parameters for drawing forces self.gravity = 9.81 self.force_scaling = .01 self.forces_nb = 4 # parameters for sliders - self.m_counterweight_min = 0.0 - self.m_counterweight_max = 100.0 - self.m_counterweight = self.m_counterweight_min # initial mass of the counterweight (0 by default, no counterweight at the beginning) + self.alpha_slider_min = 0.5 + self.alpha_slider_max = 30 + self.alpha_degrees = 20 # initial angle # parameter to draw the angle self.radius=0.3 def launch(self): ###--- Elements of the ihm: # IHM input elements - self.m_counterweight_label = Label('Mass of the counterweight ($kg$):', layout=Layout(margin='0px 5px 0px 0px')) - self.m_counterweight_widget = widgets.FloatSlider(min=self.m_counterweight_min,max=self.m_counterweight_max,step=0.5,value=self.m_counterweight, layout=Layout(margin='0px')) - self.m_counterweight_note = Label('[Note: once you have clicked on the slider (the circle becomes blue), you can use the arrows from your keyboard to make it move.]', layout=Layout(margin='0px 0px 15px 0px')) + self.alpha_slider_label = Label('Angle α (°):', layout=Layout(margin='0px 5px 0px 0px')) + self.alpha_slider_widget = widgets.FloatSlider(min=self.alpha_slider_min,max=self.alpha_slider_max,step=0.5,value=self.alpha_degrees, layout=Layout(margin='0px')) + self.alpha_slider_note = Label('[Note: once you have clicked on the slider (the circle becomes blue), you can use the arrows from your keyboard to make it move.]', layout=Layout(margin='0px 0px 15px 0px')) - self.m_counterweight_input = VBox([HBox([self.m_counterweight_label, self.m_counterweight_widget], layout=Layout(margin='0px')), self.m_counterweight_note]) + self.alpha_slider_input = VBox([HBox([self.alpha_slider_label, self.alpha_slider_widget], layout=Layout(margin='0px')), self.alpha_slider_note]) # Linking widgets to handlers - self.m_counterweight_widget.observe(self.m_counterweight_event_handler, names='value') + self.alpha_slider_widget.observe(self.alpha_slider_event_handler, names='value') - # IHM output element for moodle quiz - self.quiz_output = widgets.Output() - - ###--- Compute variables dependent with the counterweight selected by the user - alpha = self.get_angle(self.m_counterweight) - alpha_degrees = radians_to_degrees(alpha) - alpha_text = '⍺ = {:.2f} °'.format(alpha_degrees) + ###--- Compute variables dependent with alpha + alpha = degrees_to_radians(self.alpha_degrees) + alpha_text = '⍺ = {:.2f} °'.format(self.alpha_degrees) coord_object = self.get_object_coords(alpha) height_text = 'h = {:.2f} m'.format(coord_object[1]) ###--- Create the figure ---### # LIMITATIONS of Bokeh (BokehJS 1.4.0) # - labels: impossible to use LaTeX formatting in labels # - arc: impossible to take into account figure ratio when dynamic rescaling is activated # - forces/vectors: impossible to adjust the line_color and line_dash of OpenHead according to datasource ###--- First display the clothesline # Fix graph to problem boundaries ymargin = .05 xmargin = .2 - fig_object = figure(title='Suspended object ({} kg)'.format(self.m_object), #plot_width=600, plot_height=400, sizing_mode='stretch_height', + fig_object = figure(title='Suspended object ({} kg)'.format(self.m_object), plot_width=800, plot_height=400, #plot_width=600, plot_height=400, sizing_mode='stretch_height', y_range=(self.y_origin-ymargin,self.y_origin+self.height+ymargin), x_range=(self.x_origin-xmargin,self.x_origin+self.distance+xmargin), background_fill_color='#ffffff', toolbar_location=None) fig_object.title.align = "center" fig_object.yaxis.axis_label = 'Height (m)' # Customize graph style so that it doesn't look too much like a graph fig_object.ygrid.visible = False fig_object.xgrid.visible = False fig_object.outline_line_color = None - # trick to keep the three graphs aligned, while having auto scaling + # Indicate the horizontal scale fig_object.xaxis.axis_label = "Distance (m) " - #fig_object.xaxis.axis_line_color = "white" - #fig_object.xaxis.axis_label_text_color = "white" - #fig_object.xaxis.major_label_text_color = "white" - #fig_object.xaxis.major_tick_line_color = "white" - #fig_object.xaxis.minor_tick_line_color = "white" # Draw the horizon line fig_object.add_layout(Span(location=self.height, dimension='width', line_color='gray', line_dash='dashed', line_width=1)) # Draw the poles fig_object.line([self.x_origin, self.x_origin], [self.y_origin, self.y_origin+self.height], color="black", line_width=8, line_cap="round") fig_object.line([self.x_origin+self.distance, self.x_origin+self.distance], [self.y_origin, self.y_origin+self.height], color="black", line_width=8, line_cap="round") # Draw the ground fig_object.add_layout(Span(location=self.x_origin, dimension='width', line_color='black', line_width=1)) fig_object.hbar(y=self.y_origin-ymargin, height=ymargin*2, left=self.x_origin-xmargin, right=self.x_origin+self.distance+xmargin, color="white", line_color="white", hatch_pattern="/", hatch_color="gray") # --DYN-- Draw the point at which the object is suspended (this data source also used for the other graphs) self.object_source = ColumnDataSource(data=dict( x=[coord_object[0]], y=[coord_object[1]], - m_counterweight=[self.m_counterweight], - alpha_degrees=[alpha_degrees], + alpha_degrees=[self.alpha_degrees], height_text=[height_text], alpha_text=[alpha_text] )) fig_object.circle(source=self.object_source, x='x', y='y', size=8, fill_color="black", line_color='black', line_width=2) fig_object.add_layout(LabelSet(source=self.object_source, x='x', y='y', text='height_text', level='glyph', x_offset=8, y_offset=-20)) # --DYN-- Draw the hanging cable self.cable_source = ColumnDataSource(data=dict( x=[self.x_origin, coord_object[0], self.x_origin+self.distance], y=[self.y_origin+self.height, coord_object[1], self.y_origin+self.height] )) fig_object.line(source=self.cable_source, x='x', y='y', color="black", line_width=2, line_cap="round") # --DYN-- Draw the angle between the hanging cable and horizonline # Trick here: we use a straight line because the Arc glyph doesn't support dynamic figure ratio ratio=1.5 x0=self.x_origin+ratio*self.radius y0=self.y_origin+self.height x1=(self.x_origin+self.radius*np.cos(alpha)) y1=(self.y_origin+self.height-self.radius*np.sin(alpha)) self.alpha_arc = fig_object.line([x0, x1], [y0, y1], color="gray", line_width=1, line_dash=[2,2]) fig_object.add_layout(LabelSet(source=self.object_source, x=self.x_origin, y=self.y_origin+self.height, text='alpha_text', level='glyph', x_offset=50, y_offset=-20)) # --DYN-- Draw the force vectors # Weight Fy = self.m_object*self.gravity*self.force_scaling # Tension Tx = ((self.m_object*self.gravity) / (2*np.tan(alpha)))*self.force_scaling Ty = .5*self.m_object*self.gravity*self.force_scaling self.forces_x_start = [coord_object[0]]*self.forces_nb self.forces_y_start = [coord_object[1]]*self.forces_nb self.forces_x_mag = [0, Tx, 0, -Tx] self.forces_y_mag = [-Fy, Ty, Fy, Ty] self.forces_source = ColumnDataSource(data=dict( x_start=self.forces_x_start, y_start=self.forces_y_start, x_end=list(map(add, self.forces_x_start, self.forces_x_mag)), y_end=list(map(add, self.forces_y_start, self.forces_y_mag)), name=["F", "T", "Tr", "T"], color=["blue", "red", "gray", "red"], dash=["solid", "solid", [2,2], "solid"], x_offset=[8, 25, 8, -35], y_offset=[-45, 6, 45, 6] )) # Draw the arrows forces_arrows = Arrow(source=self.forces_source, x_start='x_start', y_start='y_start', x_end='x_end', y_end='y_end', line_color='color', line_width=2, end=OpenHead(line_width=2, size=12, line_color='black')) fig_object.add_layout(forces_arrows) # Add the labels forces_labels = LabelSet(source=self.forces_source, x='x_start', y='y_start', text='name', text_color='color', level='glyph', x_offset='x_offset', y_offset='y_offset', render_mode='canvas') fig_object.add_layout(forces_labels) # --DYN-- Draw the tension projection lines self.proj_source = ColumnDataSource(data=dict( x=self.forces_source.data["x_end"][1:4], y=self.forces_source.data["y_end"][1:4] )) fig_object.line(source=self.proj_source, x='x', y='y', color="gray", line_width=1, line_dash="dashed") - ###--- Then display the angle and the height as functions from the mass of the counterweight - # Create all possible values of the mass of the counterweight - m_cw_list = np.linspace(self.m_counterweight_min, self.m_counterweight_max, 100) - - # Compute the angle (in degrees) and height for all these values - angle_list = [] - height_list = [] - for m in m_cw_list: - a = self.get_angle(m) - angle_list.append(radians_to_degrees(a)) - - c = self.get_object_coords(a) - height_list.append(c[1]) - - - ### Create the graph for height - fig_height = figure(title='Height (m)', #plot_height=400, plot_width=200, - y_range=(-ymargin,self.height+ymargin), x_range=(0,102), - background_fill_color='#ffffff', toolbar_location=None) - fig_height.title.align = "center" - fig_height.xaxis.axis_label = 'Mass of the counterweight (kg)' - fig_height.grid.grid_line_color = 'lightgray' - fig_height.grid.minor_grid_line_color = 'gainsboro' - - # Draw the curve of the function - fig_height.line(m_cw_list, height_list, color="green", line_width=1) - - # Draw the horizon line - fig_height.add_layout(Span(location=self.height, dimension='width', line_color='gray', line_dash='dashed', line_width=1)) - - # --DYN-- Add the current height from the counterweight selected by the user - fig_height.circle(source=self.object_source, x='m_counterweight', y='y', size=8, fill_color="black", line_color='black', line_width=2, legend_field="height_text") - fig_height.legend.location = "bottom_right" - fig_height.legend.label_text_font_size = '12pt' - - - ### Create the graph for angle - fig_alpha = figure(title='Angle ⍺ (°)', #plot_height=400, plot_width=400, - y_range=(-1,angle_list[0]+1), x_range=(0,102), - background_fill_color='#ffffff', toolbar_location=None) - fig_alpha.title.align = "center" - fig_alpha.xaxis.axis_label = 'Mass of the counterweight (kg)' - fig_alpha.grid.grid_line_color = 'lightgray' - fig_alpha.grid.minor_grid_line_color = 'gainsboro' - - # Draw the curve of the function - c = fig_alpha.line(m_cw_list, angle_list, color="green", line_width=1) - - # Draw the horizon line - fig_alpha.add_layout(Span(location=0, dimension='width', line_color='gray', line_dash='dashed', line_width=1)) - - # --DYN-- Add the current angle from the counterweight selected by the user - fig_alpha.circle(source=self.object_source, x='m_counterweight', y='alpha_degrees', size=8, fill_color="black", line_color='black', line_width=2, legend_field="alpha_text") - fig_alpha.legend.location = "top_right" - fig_alpha.legend.label_text_font_size = '12pt' - - - ###--- Add a quiz from Moodle - iframe_quiz = ''' - - - ''' - widget_quiz = widgets.HTML(value=iframe_quiz) - - ###--- Display the whole interface - show(row(column(children=[fig_object], sizing_mode='stretch_height'), fig_alpha, fig_height, sizing_mode='scale_both'), notebook_handle=True) - #display(VBox([self.m_counterweight_input, widget_quiz])) - display(VBox([self.m_counterweight_input])) + show(row(children=[fig_object]), notebook_handle=True) + display(VBox([self.alpha_slider_input])) # Event handlers - def m_counterweight_event_handler(self, change): + def alpha_slider_event_handler(self, change): # get new value of counterweight mass - self.m_counterweight = change.new + self.alpha_degrees = change.new - # compute all problem values - alpha = self.get_angle(self.m_counterweight) - alpha_degrees = radians_to_degrees(alpha) - alpha_text = '⍺ = {:.2f} °'.format(alpha_degrees) + # compute the variables depending on alpha + alpha = degrees_to_radians(self.alpha_degrees) + alpha_text = '⍺ = {:.2f} °'.format(self.alpha_degrees) coord_object = self.get_object_coords(alpha) height_text = 'h = {:.2f} m'.format(coord_object[1]) self.forces_y_start = [coord_object[1]]*self.forces_nb Tx = ((self.m_object*self.gravity) / (2*np.tan(alpha)))*self.force_scaling self.forces_x_mag = [0, Tx, 0, -Tx] # update the object representation on all graphs (coordinates+labels) self.object_source.data = dict( x=[coord_object[0]], y=[coord_object[1]], - m_counterweight=[self.m_counterweight], - alpha_degrees=[alpha_degrees], + alpha_degrees=[self.alpha_degrees], height_text=[height_text], alpha_text=[alpha_text] ) # update line representing the angle alpha self.alpha_arc.data_source.patch({ 'x' : [(1, self.x_origin+self.radius*np.cos(alpha))], 'y' : [(1, self.y_origin+self.height-self.radius*np.sin(alpha))] }) # update the point where the object is attached on cable self.cable_source.patch({ 'x' : [(1, coord_object[0])], 'y' : [(1, coord_object[1])] }) # update point of start for all forces, update Tx and Ty for T self.forces_source.patch({ 'y_start' : [(slice(self.forces_nb), self.forces_y_start)], 'x_end' : [(slice(self.forces_nb), list(map(add, self.forces_x_start, self.forces_x_mag)))], 'y_end' : [(slice(self.forces_nb), list(map(add, self.forces_y_start, self.forces_y_mag)))], }) # update the tension projection lines self.proj_source.patch({ 'x' : [(slice(3), self.forces_source.data["x_end"][1:4])], 'y' : [(slice(3), self.forces_source.data["y_end"][1:4])] }) push_notebook() - - - - def visualize_counterweight(self, m_counterweight = 0): - ### first let's validate the counterweight - # it cannot be negative - if m_counterweight < 0: - print("\033[1m\x1b[91m The mass of the counterweight cannot be negative. \x1b[0m\033[0m") - return - - # update attribute with new value - self.m_counterweight = m_counterweight - # compute the angle given by this counterweight - alpha = self.get_angle(self.m_counterweight) - alpha_degrees = radians_to_degrees(alpha) - - # visualize the situation - self.visualize_angle(alpha_degrees) - def visualize_angle(self, angle_degrees): ### first let's validate the angle # it cannot be null (i.e. cable horizontal) or negative if angle_degrees <= 0: print("\033[1m\x1b[91m The angle cannot be null or negative. \x1b[0m\033[0m") return # it cannot be more than the default angle given the parameters of the situation alpha_default = np.arctan(self.height / (self.distance / 2)) alpha_default_degrees = radians_to_degrees(alpha_default) if angle_degrees > alpha_default_degrees: print(f"\033[1m\x1b[91m The angle cannot be greater than {alpha_default_degrees:.2f} degrees given the parameters of this situation (poles of {self.height} meters, distant by {self.distance} meters). \x1b[0m\033[0m") angle_degrees = alpha_default_degrees # compute variables dependent with the angle selected by the user alpha_degrees = angle_degrees alpha = degrees_to_radians(alpha_degrees) alpha_text = '⍺ = {:.2f} °'.format(alpha_degrees) coord_object = self.get_object_coords(alpha) height_text = 'h = {:.2f} m'.format(coord_object[1]) ###--- Create the figure ---### # LIMITATIONS of Bokeh (BokehJS 1.4.0) # - labels: impossible to use LaTeX formatting in labels # - arc: impossible to take into account figure ratio when dynamic rescaling is activated # - forces/vectors: impossible to adjust the line_color and line_dash of OpenHead according to datasource ###--- First display the clothesline # Fix graph to problem boundaries ymargin = .05 xmargin = .2 fig_object = figure(title='Suspended object ({} kg)'.format(self.m_object), plot_width=800, plot_height=400, #sizing_mode='scale_both', y_range=(self.y_origin-ymargin,self.y_origin+self.height+ymargin), x_range=(self.x_origin-xmargin,self.x_origin+self.distance+xmargin), background_fill_color='#ffffff', toolbar_location=None) fig_object.title.align = "center" fig_object.yaxis.axis_label = 'Height (m)' fig_object.xaxis.axis_label = "Distance (m)" # Customize graph style so that it doesn't look too much like a graph fig_object.ygrid.visible = False fig_object.xgrid.visible = False fig_object.outline_line_color = None # Draw the horizon line fig_object.add_layout(Span(location=self.height, dimension='width', line_color='gray', line_dash='dashed', line_width=1)) # Draw the poles fig_object.line([self.x_origin, self.x_origin], [self.y_origin, self.y_origin+self.height], color="black", line_width=8, line_cap="round") fig_object.line([self.x_origin+self.distance, self.x_origin+self.distance], [self.y_origin, self.y_origin+self.height], color="black", line_width=8, line_cap="round") # Draw the ground fig_object.add_layout(Span(location=self.x_origin, dimension='width', line_color='black', line_width=1)) fig_object.hbar(y=self.y_origin-ymargin, height=ymargin*2, left=self.x_origin-xmargin, right=self.x_origin+self.distance+xmargin, color="white", line_color="white", hatch_pattern="/", hatch_color="gray") # --DYN-- Draw the point at which the object is suspended (this data source also used for the other graphs) self.object_source = ColumnDataSource(data=dict( x=[coord_object[0]], y=[coord_object[1]], - m_counterweight=[self.m_counterweight], alpha_degrees=[alpha_degrees], height_text=[height_text], alpha_text=[alpha_text] )) fig_object.circle(source=self.object_source, x='x', y='y', size=8, fill_color="black", line_color='black', line_width=2) fig_object.add_layout(LabelSet(source=self.object_source, x='x', y='y', text='height_text', level='glyph', x_offset=8, y_offset=-35)) # --DYN-- Draw the hanging cable self.cable_source = ColumnDataSource(data=dict( x=[self.x_origin, coord_object[0], self.x_origin+self.distance], y=[self.y_origin+self.height, coord_object[1], self.y_origin+self.height] )) fig_object.line(source=self.cable_source, x='x', y='y', color="black", line_width=2, line_cap="round") # --DYN-- Draw the angle between the hanging cable and horizonline # Trick here: we use a straight line because the Arc glyph doesn't support dynamic figure ratio ratio=1.5 x0=self.x_origin+ratio*self.radius y0=self.y_origin+self.height x1=(self.x_origin+self.radius*np.cos(alpha)) y1=(self.y_origin+self.height-self.radius*np.sin(alpha)) self.alpha_arc = fig_object.line([x0, x1], [y0, y1], color="gray", line_width=1, line_dash=[2,2]) fig_object.add_layout(LabelSet(source=self.object_source, x=self.x_origin, y=self.y_origin+self.height, text='alpha_text', level='glyph', x_offset=50, y_offset=-20)) # --DYN-- Draw the force vectors # Weight Fy = self.m_object*self.gravity*self.force_scaling # Tension Tx = ((self.m_object*self.gravity) / (2*np.tan(alpha)))*self.force_scaling Ty = .5*self.m_object*self.gravity*self.force_scaling self.forces_x_start = [coord_object[0]]*self.forces_nb self.forces_y_start = [coord_object[1]]*self.forces_nb self.forces_x_mag = [0, Tx, 0, -Tx] self.forces_y_mag = [-Fy, Ty, Fy, Ty] self.forces_source = ColumnDataSource(data=dict( x_start=self.forces_x_start, y_start=self.forces_y_start, x_end=list(map(add, self.forces_x_start, self.forces_x_mag)), y_end=list(map(add, self.forces_y_start, self.forces_y_mag)), name=["F", "T", "Tr", "T"], color=["blue", "red", "gray", "red"], dash=["solid", "solid", [2,2], "solid"], x_offset=[8, 15, 8, -25], y_offset=[-64, -16, 45, -16] )) # Draw the arrows ### Bokeh issue here: with a datasource, it is not possible to specify the color of the openhead so it remains black forces_arrows = Arrow(source=self.forces_source, x_start='x_start', y_start='y_start', x_end='x_end', y_end='y_end', line_color='color', line_width=2, end=OpenHead(line_width=2, size=12)) fig_object.add_layout(forces_arrows) # Add the labels forces_labels = LabelSet(source=self.forces_source, x='x_start', y='y_start', text='name', text_color='color', level='glyph', x_offset='x_offset', y_offset='y_offset', render_mode='canvas') fig_object.add_layout(forces_labels) # --DYN-- Draw the tension projection lines self.proj_source = ColumnDataSource(data=dict( x=self.forces_source.data["x_end"][1:4], y=self.forces_source.data["y_end"][1:4] )) fig_object.line(source=self.proj_source, x='x', y='y', color="gray", line_width=1, line_dash="dashed") ###--- Display the whole interface show(row(children=[fig_object]), notebook_handle=True) #, sizing_mode="scale_both" # Utility functions def get_angle(self, m_counterweight): """ Computes the angle that the cable makes with the horizon depending on the counterweight chosen: - if the counterweight is sufficient: angle = arcsin(1/2 * m_object / m_counterweight) - else (object on the ground): alpha = arctan(height / (distance / 2)) :m_counterweight: mass of the chosen counterweight :returns: angle that the cable makes with the horizon (in rad) """ # Default alpha value i.e. object is on the ground alpha_default = np.arctan(self.height / (self.distance / 2)) alpha = alpha_default # Let's check that there is actually a counterweight if m_counterweight > 0: # Then we compute the ratio of masses ratio = 0.5 * self.m_object / m_counterweight # Check that the ratio of masses is in the domain of validity of arcsin ([-1;1]) if abs(ratio) < 1: alpha = np.arcsin(ratio) return min(alpha_default, alpha) def get_object_coords(self, angle): """ Computes the position of the object on the cable taking into account the angle determined by the counterweight and the dimensions of the hanging system. By default: - the object is supposed to be suspended exactly in the middle of the cable - the object is considered on the ground for all values of the angle which give a delta height higher than the height of the poles - :angle: angle that the cable makes with the horizon + :angle: angle that the cable makes with the horizon, in radians :returns: coordinates of the point at which the object are hanged """ # the jean is midway between the poles x_object = self.x_origin + 0.5 * self.distance # default y value: the jean is on the ground y_object = self.y_origin # we check that the angle is comprised between horizontal (greater than 0) and vertical (smaller than pi/2) if angle > 0 and angle < (np.pi / 2): # we compute the delta between the horizon and the point given by the angle delta = (0.5 * self.distance * np.tan(angle)) # we check that the delta is smaller than the height of the poles (otherwise it just means the jean is on the ground) if delta <= self.height: y_object = self.y_origin + self.height - delta return [x_object, y_object] def degrees_to_radians(angle_degrees): return angle_degrees * np.pi / 180 def radians_to_degrees(angle_radians): return angle_radians * 180 / np.pi # EOF