diff --git a/LearningPhysics-Programming.ipynb b/LearningPhysics-Programming.ipynb index c4866da..192c8da 100644 --- a/LearningPhysics-Programming.ipynb +++ b/LearningPhysics-Programming.ipynb @@ -1,1127 +1,1210 @@ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Workshop \"Teaching Sciences and Engineering with Jupyter Notebooks\" 2021\n", "C. Hardebolle, CC BY-NC-SA 4.0 Int.\n", "\n", "
\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", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "# Learning goals\n", + "
\n", + "\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 calculations\n", - "\n", - "

\n", + "* Use Python to make mathematical calculations and write simple functions\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. The problem\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", "\n", - "\"suspended\n", + "\"suspended\n", + "

Figure 1: The suspended jeans situation

\n", "\n", - "
\n", - " Activity
\n", - " \n", - "Execute the cell below, then **use the interactive question to vote for the answer you think is correct** among the following:
\n", - " A. 1.5 kg
\n", - " B. 3 kg
\n", - " C. 6 kg
\n", - " D. 20 kg
\n", - " E. 50 kg or more\n", - "
\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. " ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "metadata": {}, - "outputs": [], "source": [ - "from IPython.display import IFrame\n", - "IFrame('https://speakup.epfl.ch/ng/room/27058', 600, 600)" + "
\n", + " Activity
\n", + " \n", + "Before starting, it is useful to note down **which counterweight you think allows to suspend the jeans in the expected position** (i.e. your answer to the clicker question). \n", + "Simply use the cell below for note taking.\n", + "
" ] }, { - "cell_type": "markdown", + "cell_type": "raw", "metadata": {}, "source": [ - "
\n", - "\n", - "**The goal of the activities in this notebook is to help you find out the correct answer** by exploring how the counterweight affects the position of the jeans suspended on the cable." + "Just note down your answer here (this cell is for note taking):" ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": false }, "source": [ "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": false }, "source": [ "# 2. 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", + "\"sketch\"\n", + "

Figure 2: 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", "\n", "However we need to figure out where the angle $\\alpha$ is. \n" ] }, { "cell_type": "markdown", "metadata": { "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", "\n", - "\"sketch\"\n", + "\"sketch\"\n", + "

Figure 3: Angle and forces in the suspended jeans situation

\n", + "\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", "\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. \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$..." + "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 in [Figure 1 above](#fig1), we can guess that $\\alpha$ is probably quite small, but how small?\n", + "\n", + "\n", + "
\n", + " Activity
\n", + "\n", + "**Make a guess for the value of $\\alpha$** and note it down in the cell below.\n", + " \n", + "
" + ] + }, + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "Just note down your answer here (this cell is for note taking):" ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": false }, "source": [ - "## How much is the angle $\\alpha$?\n", - "\n", - "From the sketch in the original question, we can guess that $\\alpha$ is probably quite small, but how small?\n", + "## How does the angle $\\alpha$ influence the forces on the jeans?\n", "\n", - "One option would be to guess a value, but of course this depends somewhat on the geometry of the installation. \n", - "In the following, we are going to consider a situation with poles 1.5 meters high, separated by a 5 meter distance, and we are going to use the ``suspendedobjects`` library to visualize concretely what a particular value for $\\alpha$ means in this configuration.\n", "\n", - "But first, we need to import some useful Python libraries. \n", + "In the following, we are going to use the ``suspendedobjects`` library to visualize concretely what a particular value for $\\alpha$ means in this configuration. \n", + "For this, we need to import some useful Python libraries. \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.suspendedobjects import *\n", + "from lib.suspendedobject import *\n", "\n", "# And display a message once it is defined\n", "print(\"Libraries imported.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now we can start to use Python for visualizing our angle $\\alpha$." + "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." ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": false }, "source": [ "
\n", " Activity
\n", " \n", - "Execute the code cell below to generate the visualization with the object suspended on the cable.
\n", - "Then **change the value of ``alpha`` and experiment with multiple values**, to decide which value best reflects the angle in the original question above.\n", + "Execute the code cell below to generate the visualization with the jeans suspended on the cable.
\n", + "Then **change the value of ``alpha`` and experiment with multiple values**, to decide which value best reflects the angle in [Figure 1 above](#fig1).\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 = SuspendedObjectsLab(m_object = 3, height = 1.5, distance = 5)\n", + "lab = SuspendedObjectLab(m_object = 3, height = 1.5, distance = 5)\n", "\n", "# Visualize the angle\n", "lab.visualize_angle(alpha);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "So, which value do you think we should use for $\\alpha$?
\n", + "Now that you have chosen a value for $\\alpha$, the question is: **how does it affect the forces on the jeans?**
\n", "\n", "
\n", " Activity
\n", "\n", - "Execute the code cell below and **post a message in the chat with the value you suggest for $\\alpha$**.
\n", - "If someone already posted the value you were thinking about, simply vote for it (thumb-up icon on the left). \n", + "Compare the forces on the jeans with $\\alpha$ = 20$^\\circ$ and with the value you have chosen for $\\alpha$. \n", + "**What do you observe?** \n", + "Execute the code cell below and **post a message in the chat** with the value you suggest for $\\alpha$ and a description of how you think the angle influences the forces on the jeans.
\n", + "\n", "*You might need to accept the cookies to see the text box where to post your message.*\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import IFrame\n", "IFrame('https://speakup.epfl.ch/ng/room/50676', 600, 600)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Computing the tension in the cable with Python\n", "\n", - "Now that we have a value for $\\alpha$, we can 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 tension in the cable using the equation from the mini-lecture:\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": {}, "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 and in which we are going to vary $\\alpha$:\n", - "* The function takes one input parameters, `alpha`, which is the angle that the cable makes with the horizon. \n", - "* It returns the value of the mass of the counterweight as computed with the equation: \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", - "For this function to work, we need to define the values of two constants in the above equation:\n", - "- $m$ the mass of the suspended object, which is 3 kg in the case of the jeans\n", - "- $g$ the gravity of earth, which is 9.81 m.s$^{-2}$\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", "* multiplication: ``*``\n", "* division: ``/``\n", "* sinus function $sin(x)$: ``np.sin(x)``\n", "\n", - "You can also use parentheses as you wish.\n", + "You can also use parentheses to indicate the order of operations.\n", " \n", "Check your answer with the solution by clicking on the \"...\" below. \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": [ - "# Let's define the mass of the jeans\n", - "m = 3\n", - "\n", - "# And the value of gravity\n", - "g = 9.81\n", - "\n", "# Then let's define the function\n", - "def tension_norm(alpha):\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": { "jupyter": { "source_hidden": true } }, "source": [ "
\n", " Solution
\n", "\n", "Your function should look like the following:\n", "\n", - "def tension_norm(alpha):\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": [ "## 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 and prints the result." + "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", "\n", "# Then convert it to radians\n", "alpha_radians = degrees_to_radians(alpha)\n", "\n", - "# Then compute the tension using our equation\n", - "T = tension_norm(alpha_radians)\n", + "# Then compute the tension using our equation with g = 9.81 m.s-2 and m = 3 kg\n", + "T = tension_norm(9.81, 3, alpha_radians)\n", "\n", - "# And print the result with a pretty format\n", - "display(Math(r'$\\lvert\\vec{T}\\rvert = $'+' {:8.0f} $N $'.format(T)))" + "# 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$ in the code cell above, then execute it** to see the value of the corresponding tension force $\\lvert\\vec{T}\\rvert$, expressed in Newtons. \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", " \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)." + "Just note down your answer here (this cell is for note taking):" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true } }, "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", " \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", + "\"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}.\\lvert\\vec{F}\\rvert}{sin(\\alpha)}\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", "\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", "\n", "Again we can use python to make this simple computation, using the values ``T`` and ``g`` computed earlier." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Activity
\n", "\n", "**Complete the code cell below** to compute the mass of the counterweight according to the equation above.\n", "\n", "Check your answer with the solution by clicking on the \"...\" below. \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", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "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: {:.1f} kg\".format(m_cw))" + "print(\"Mass of the counterweight: m =\", m_cw, \"kg\")" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true } }, "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", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "So let's come back to our question: which counterweight do you think would allow to suspend the jeans (3kg) on the cable in the position illustrated below? \n", - "Did your opinion change after doing the activities above (you can check what you voted on the interactive question above in the notebook) ?\n", + "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 [at the beginning of this notebook](#Before-anything)? \n", "\n", - "\"suspended\n", + "\"suspended\n", "\n", "\n", "
\n", " Activity
\n", "\n", - "Execute the code cell below and **post a message in the chat with the counterweight you think is necessary** to suspend the jeans in the desired position. \n", - "If someone already posted the value you were thinking about, simply vote for it (thumb-up icon on the left).\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 description of how it compares to your estimation [at the beginning of this notebook](#Before-anything). \n", + "\n", + "*Note that this chat is completely anonymous.*\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import IFrame\n", "IFrame('https://speakup.epfl.ch/ng/room/241665', 600, 600)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 4. Going further: 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", "\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", "\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(a_rad)\n", + "t = tension_norm(9.81, 3, 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": { "jupyter": { "source_hidden": true } }, "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": [ "

\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 5. What have you learned so far?\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", " \n", "
" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "- \n", "- " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\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", "
" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "- \n", "- " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once you are finished with the above questions, **check-in with the instructor**.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "



\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Additional exercises (optional)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What happens to the tension when $\\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, where we compute the tension using our ``tension_norm`` function, change the value of `alpha` to $0$ and re-execute the cell. \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", "\n", "You can check your answer with the solution by clicking on the \"...\" below. \n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ - "# First choose an angle alpha\n", - "alpha = 20 # CHANGE THE VALUE HERE\n", - "\n", - "# Then convert it to radians\n", - "alpha_radians = degrees_to_radians(alpha)\n", - "\n", - "# Then compute the tension using our equation\n", - "T = tension_norm(alpha_radians)\n", + "# 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 HERE\n", "\n", - "# And print the result with a pretty format\n", - "display(Math(r'$\\lvert\\vec{T}\\rvert = $'+' {:8.0f} $N $'.format(T)))" + "# And print the result\n", + "print(\"Norm of the tension in the cable: T =\", T, \"N\")" ] }, { "cell_type": "markdown", "metadata": { "jupyter": { "source_hidden": true } }, "source": [ "
\n", " Solution
\n", "\n", "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", "\n", "You can check your answer with the solution by clicking on the \"...\" below. \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": { "jupyter": { "source_hidden": true } }, "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. \n", + "If your function works correctly, the result of 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", + "T = tension_norm_degrees(9.81, 3, 20) \n", + "print(\"Tension norm: T =\", T, \"N\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "jupyter": { + "source_hidden": true + } + }, + "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 ``alpha`` as an input and returns the mass of the counterweight as computed by the equation above. \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", - "Of course you can reuse code from the previous activities as a model.\n", + "You should find a counterweight of approximately 57 kg.\n", "\n", - "You can find the complete solution in the [solution section of the notebook](#Numerical-application).\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": {}, "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 one input parameters, `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(alpha):\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": [ + "# Define the mass of the jeans\n", + "m = 3\n", + "\n", "# 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(alpha_radians)\n", + "m_cw = counterweight_mass(m, alpha_radians)\n", "\n", "# And print the result\n", - "print('{:.02f} kg'.format(m_cw))" + "print(\"Mass of the counterweight: m_cw =\", m_cw, \"kg\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.9" }, "toc-autonumbering": false }, "nbformat": 4, "nbformat_minor": 4 } diff --git a/lib/suspendedobjects.py b/lib/suspendedobjects.py deleted file mode 100644 index 8ee1ad5..0000000 --- a/lib/suspendedobjects.py +++ /dev/null @@ -1,513 +0,0 @@ -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 SuspendedObjectsLab: - """ - 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) - - # 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.m_counterweight_input = VBox([HBox([self.m_counterweight_label, self.m_counterweight_widget], layout=Layout(margin='0px')), self.m_counterweight_note]) - - # Linking widgets to handlers - self.m_counterweight_widget.observe(self.m_counterweight_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) - - 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', - 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 - 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], - 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])) - - - # Event handlers - def m_counterweight_event_handler(self, change): - # get new value of counterweight mass - self.m_counterweight = 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) - - 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], - 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=-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)) - - ###--- 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 - - :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