<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben de Vries on Medium]]></title>
        <description><![CDATA[Stories by Ben de Vries on Medium]]></description>
        <link>https://medium.com/@bldevries?source=rss-dce4f76788e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b68HjHgKc3TNZBP2fqouiw.jpeg</url>
            <title>Stories by Ben de Vries on Medium</title>
            <link>https://medium.com/@bldevries?source=rss-dce4f76788e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 23:29:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bldevries/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Intimate relations — conservation of momentum and the 3rd law of Newton]]></title>
            <link>https://medium.com/@bldevries/intimate-relations-conservation-of-momentum-and-the-3rd-law-of-newton-64eb0be62b61?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64eb0be62b61</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[astronomy]]></category>
            <category><![CDATA[theoretical-physics]]></category>
            <category><![CDATA[mechanics]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 11:58:17 GMT</pubDate>
            <atom:updated>2024-07-12T11:58:17.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intimate relations — conservation of momentum and the 3rd law of Newton</h3><p>One of the reasons that I choose physics in college was to know a little bit more about how things fundamentally work. I was driven by an interest to dig to the most fundamental laws and have a bottom-up structure of physical laws in my head. One or a few laws at its base and all the rest can be deduced from them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*XgLhMR55dx7j2_tCKa-Vfw.png" /></figure><p>Another way of looking at physical laws was introduced to me by Feynman. In one of his lectures, he describes how it can be arbitrary in maths and physics to determine what is an axiom and what can be derived from those axioms. He concludes it can be more efficient to see things sort of as a web of knowledge. One can go from one piece of knowledge in the web to another in different ways through the many different connections. If you know one piece in the web, you can reconstruct other parts of the web which you might have forgotten. <em>Oeps!</em></p><p>Right now, I am in danger of babbeling on about these philosophical thoughts, but I want to try and make this idea of a web more concrete by looking at specific physics. In this blog I will start with two points in our web and the connection between them: the third law of Newton and conservation of momentum. We start the third law of Newton (action = reaction) and travel to the conservation of momentum from there. This direction is arbitrary and can just as well be done in the other way around.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQ6jFZxJtsBDXt-BR-Mxlw.png" /></figure><p>There are many branching paths from these two points in the web. Think of potential energy, conservative forces, principle of least action and the Lagrangian, <em>etcetera!</em> but we will restrict ourselves, in the web of physics one can quickly get lost. If you are already dizzy and lost, do not be deterred, I am sure things will become clear in bit ;)</p><h3>Third law of Newton</h3><p>You might remember it from high school, the third law of Newton states that if body number one applies a force to body number two (let’s call this <strong>F</strong>₂₁), body number two also applies a force equal in strength to body number one, but in the opposite direction (we call it F₁₂). This can be summarized as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*QY0Oew3KVk8GUUow1fDeNQ.png" /></figure><p>Note that the forces are in bold with which I communicate that they are vectors. I always find the thrid law a very logical law and a strange one at the same time. If I push a wall, I kind of feel it push back, right? But is the ‘reaction’ force really a reaction, or does nature just function in a way that forces always come in pairs that happen to be equal in strength but opposite? Many questions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*URWhFM4j1Cs7Wk64WFMc8Q.png" /></figure><p>Let’s try and understand this law a bit better and what often helps is to leave Earth behind and think about it in empty space. Doing this we eliminate gravity and drag due to air or contact forces. Let’s imagine we are astronauts, and we want to stay fit. We will take our barbell to outer space and we will <a href="https://en.wikipedia.org/wiki/Overhead_press">press</a> it above our heads. Floating in space with the barbell on our chest we will apply a force to it to get it above our heads. We can use the second law of Newton to get the equation of motion of the barbell and of you. Remember what the 2nd law states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*xM1POhH0MP2Kox5KPA2nsw.png" /></figure><p>So, if we apply <strong>F_</strong>barbell to the barbell, the barbell will apply <strong>F</strong>_you on you, and the third law states that <strong>F</strong>_barbell = -<strong>F</strong>_you. Lets just call the size of the force F. Then the second law gives us the acceleration of you and of the barbell:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*2Q0Z3Q7yQjZtn6BWtJ95Gg.png" /></figure><p>Here we have defined positive to be in the direction where you push the barbell. So the barbell accelerates upwards and you accelerate downwards. The amount of acceleration depends on the mass. If you and the barbell are of equal mass, both of you accelerate away from each other with equal acceleration.</p><p>A funny thought is that, when you are pressing the barbell in the gym on Earth, the barbell is accelerating upwards, but you seem to stay in place. But since you are connected to the ground with your feet, you form one body with the Earth and the reaction force is accelerating you and the Earth away from the barbell. But since the Earth is so massive compared to the barbell, the acceleration of you and the Earth is negligible. But next time you press, you can feel mighty strong pushing the Earth around!</p><h3>Conservation of Momentum</h3><p>Let’s connect the third law of Newton to conservation of momentum. In classical mechanics momentum is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Nx9cudjytS3k36JIDfHWcg.png" /></figure><p>Momentum is the mass of a body times its velocity. Intuitively you could think of this as how much ‘movement’ is in a body. For example, if a body is very massive and/or moves very fast, it has a lot of momentum, and you can imagine it is difficult to stop (or get moving). Stopping a body would amount to changing the momentum of a body over time, so let’s see what the derivative of the momentum looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*IiujMThZcg1mV-pXT0y3DA.png" /></figure><p><em>Hey!</em> We know this one, this is just the second law of Newton, and we see that the change of momentum of a body over time equals the net force on the body:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*R-a_N1f5IsSzTe9yr1aF_g.png" /></figure><p>Let’s look at this a bit more, but not in the most general case, let’s keep it simple and look at only two bodies. These bodies could be two stars that pull on each other with the gravitational force or two electrons that repel each other due to the Coulomb force. But we will isolate these two bodies so there are no forces from other bodies acting on them. The third law of Newton for these bodies is <strong>F</strong>₁₂ = — <strong>F</strong>₂₁. And this can now be written in terms of momentum as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*UGm4CtysOLdE7UkDGlp3zw.png" /></figure><p>And <em>wham!</em> we have just shown that the total momentum of the two bodies together is constant. Or in other words, it is conserved! What we see is that Newtons third law makes sure that if p₁ is decreased, p₂ is increased by the same amount to keep the total constant. Or the other way around. So, no momentum can magically be created in the system! <em>No magic!</em></p><h3>To the conclusion!</h3><p>In a way the conservation of momentum belongs to the basics, and you might have used it often. But the basics often hold interesting fundamental properties of how nature works. With this blog I wanted to show you the close connection between the law of conservation momentum and the third law of Newton. What do you think, are these laws equivalent? Is one more fundamental than the other? How do they both translate to the relativistic regime of high velocities? Let me know in the <em>comments!</em> below.</p><p>We will cover many of these topics in due time, but in a next blog we will first look at another way to arrive at the conservation of momentum. Namely through the Euler-Lagrange equation and we will explore how conservation of momentum is related to symmetries is space. The Lagrange equations are very interesting, since they seem to pop-up in so many branches of physics. <em>Stay tuned!</em></p><p>Did you like this article and do you want more? Consider <em>Clapping!</em> and <em>Following!</em> me here on Medium for more.</p><p>PS: We have shown conservation of momentum for two particles, but you can also proof this in just the same way for multiple particles. You will just have to juggle a bunch of summations. John R. Taylor does this wonderfully in his book on Classical mechanics. This is a great book to have in your collection!</p><ul><li><a href="https://medium.com/@bldevries/prelude-to-chaos-solving-non-linear-differential-equations-with-solve-ivp-and-scipy-2f287453d734">Prelude to chaos: solving non-linear differential equations with solve_ivp and scipy</a></li><li><a href="https://medium.com/@bldevries/calculating-lengths-in-curved-spaces-using-sympys-symbolic-mathematics-python-and-matplotlib-7c18da99fd7b">Calculating lengths in curved spaces using SymPy’s symbolic mathematics, Python and Matplotlib</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64eb0be62b61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prelude to chaos: solving non-linear differential equations with solve_ivp and scipy]]></title>
            <link>https://medium.com/@bldevries/prelude-to-chaos-solving-non-linear-differential-equations-with-solve-ivp-and-scipy-2f287453d734?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f287453d734</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[differential-equations]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 18:01:20 GMT</pubDate>
            <atom:updated>2024-06-14T18:21:13.465Z</atom:updated>
            <content:encoded><![CDATA[<h4>Welcome to this blog where we will use solve_ivp and Python to solve a non-linear differential equation. Non-linear differential equations often describe chaotic behaviour. In this blog we will solve a non-linear differential equation which is very interesting but not quite chaotic yet. This will help us to learn solve_ivp and scipy better and prepare for some full chaotic behaviour in a next blog.</h4><p><a href="https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d">Simply solving differential equations using Python, scipy and solve_ivp</a></p><h3>Recap of simple harmonic motion</h3><p>In my previous <a href="https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d">blog</a> we solved the differential equation for simple harmonic oscillations using scipy, solve_ivp and Python. Remember that the equation of motion looked like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*LpC94NuEJ6dwLdNCatCJqw.png" /></figure><p>One of the systems this equation describes is the motion of a mass 𝑚 on a spring with a spring constant 𝑘. You can see that the acceleration 𝑑²𝑥/𝑑𝑡² is always in the direction of the equilibrium, 𝑥 = 0. This is a so-called restoring force. Because the mass will overshoot the equilibrium, it will start oscillating. And with no friction, it will oscillate indefinitely.</p><p>The equation for harmonic motion we covered in the previous <a href="https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d">blog</a> can be solved analytically and the solutions are sine and cosine functions (try and plug those into the equation of motion). So, solving such an equation numerically was just an exercise. In this blog we will solve a more difficult equation that cannot be solved analytically (in other words, the solution cannot be formulated in elementary functions like sine, cosine, logarithms, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCUY_dle68MatjKHyumQhw.png" /><figcaption>Figure 1: schematic depiction of a pendulum and the force of gravity acting on the mass m. The component of the gravitational force acting in the theta direction is shown.</figcaption></figure><h3>Forces that make a pendulum swing</h3><p>The equation we will solve today belongs to a pendulum that can rotate around a point of rotation. The pendulum we will study has all its mass at one point and is connected to the point of rotation through a rigid, mass-less, rod. In Fig. 1 you see a schematic depiction of the situation. We defined 𝜃 as the angle between the rod and the vertical at the point of rotation. We will take 𝜃 to be positive to the left.</p><p><a href="https://medium.com/@bldevries/calculating-lengths-in-curved-spaces-using-sympys-symbolic-mathematics-python-and-matplotlib-7c18da99fd7b">Calculating lengths in curved spaces using SymPy’s symbolic mathematics, Python and Matplotlib</a></p><p>To write down the equation of motion for the pendulum we will first need to analyse the forces acting on the pendulum. The only force that will contribute to the movement is the gravitational force (is it a force? Check my <a href="https://medium.com/@bldevries/calculating-lengths-in-curved-spaces-using-sympys-symbolic-mathematics-python-and-matplotlib-7c18da99fd7b">blog</a> on curved spaces and general relativity if you are interested). The gravitational force of gravity is pointing downwards, but the component of the force in the 𝜃 direction (see Fig. 1) is what we are interested in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*dSu2B3njsVSxRjUVxVIGmw.png" /></figure><p>You can see that it points in the negative 𝜃 direction when 𝜃 is positive and it will therefor function as a restoring force, just as with the <a href="https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d">harmonic oscillations of a mass on a spring</a>. Thus, the solutions we find will possibly resemble harmonic motion. But let’s not get ahead of ourselves :)</p><h3>The non-linear equation of motion</h3><p>Before we can write down our equation of motion, we need to talk about a trick to make things more easy for ourselves. Even though our pendulum moves in two dimensions, the problem really is one dimensionally. The only free variable is the angle 𝜃. If we manage to write our equation of motion in terms of this variable, we will be of to a good start.</p><p>First we will look at the acceleration and how it translates into changes in 𝜃. The mass and the rod that holds it can only move in a circle around the point where the rod is fixed. We take 𝑥 to be the length travelled on this circle and 𝑎 the acceleration with which the mass m travels on this circle. Now we can write the following: 𝑥=𝑙 𝜃, where 𝑙 is the length of the rod. This makes sence since if we move one whole rotation we have 𝜃 = 2𝜋 and then x = 2𝜋𝑙, the circumference of a circle with radius 𝑙. We can thus write:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*NiiSTwmks8D2sXM-PWW_NA.png" /></figure><p>The equation of motion now becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*BAm1xNa203MTCL1a_2ffCQ.png" /></figure><p>If we rearrange things a bit and define</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*JHAA25BW_jL34uwsIaKpDA.png" /></figure><p>we will end up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*x8cP2IJs-Q2Yuxlp69C-kg.png" /></figure><p>This equation looks very similar to the equation of motion of a mass m on a spring, with only one exception: on the right hand side we now have sin(𝜃) instead of just 𝜃. And this makes a difference!</p><h3>An approximation that makes our equation of motion linear</h3><p>Now we have a nice differential equation in terms of the angle 𝜃 and the time 𝑡. That we have a sin(𝜃) on the right instead of a 𝜃 makes for a non-linear differential equation. The equation of harmonic motion is linear in because the second derivative 𝑑²𝜃/𝑑𝑡² is directly proportional to the function 𝜃(t) itself. Now for our pendulum the second derivative 𝑑²𝜃/𝑑𝑡² is not proportional to 𝜃(𝑡), but to the sin(𝜃). Analytically solving non-linear differential equations is another game and more often than not, impossible analytically. But we are armed with numerical options and we will not be deterred!</p><p>Before we tackle the non-linear equation of motion we can first study it in the special case where it is linear. If we keep to small values of 𝜃, we can approximate 𝜃 ≈ sin(𝜃), which gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*DQn4tdVYfkqGJQUKRN0a3g.png" /></figure><p>From this we learn that at small deviations we just have harmonic motion and we know that the solution of this is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*An12XLRZ3NWUoL_6JDvW4A.png" /></figure><p>Where <em>𝐴</em> and <em>𝐵</em> are constants that are determined by the starting conditions and our solution becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*IuS1wkvKtsUZyha2EvnUgA.png" /></figure><p>Lets plot some examples of this approximation using the following code:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br># We make a function to calculate the linear version<br>def theta_linear(t = np.arange(0, 1, 0.001), omega = 9.8/1, th_0 = 0.01):<br>    return t, np.array([th_0*np.cos(omega*t_i) for t_i in t])<br><br># We plot the linear solution for three pendulum lengths<br>for omega in [9.8/0.5, 9.8/1.0, 9.8/2.0]:<br>    plt.plot(*theta_linear(omega=omega), label = &quot;$\\omega$ = &quot;+str(omega)+&quot; 1/s&quot;)<br><br>plt.ylim((-0.011, 0.016))<br>plt.legend()<br>plt.ylabel(&#39;$\\theta (t)$ (radians)&#39;)<br>plt.xlabel(&#39;time (seconds)&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*arG_ImrP71MaIsVpPhMDRA.png" /><figcaption>Figure 2: Solutions to the differential equation for a pendulum using the approximation of small displacements which makes it a linear differential equation. The result is simple harmonic motion. Plotted are solutions for three differen omega values corresponding to pendulum lengths of 0.5, 1.0 and 2.0 m respectively.</figcaption></figure><p>In Fig. 2 you can see you get harmonics oscillations with increasing period when you increase the length of the pendulum. Lets make an interesting animation of our solution using the following code:</p><pre>import matplotlib.animation as animation<br>from matplotlib import rc<br>rc(&#39;animation&#39;, html=&#39;jshtml&#39;, embed_limit=500)<br><br>def plotPendulum(t, th, l, start_at_frame = 0, interval = 100, \<br>                 ani_name = &quot;Pendulum_small_displacement.gif&quot;):<br>    <br>    # We use this function to go from theta to cartesian coordinates<br>    def cartCoords(th, l):<br>        return -l*np.sin(th), -l*np.cos(th)<br><br>    frames = len(t)-start_at_frame<br><br>    # We make a figure with two subplots<br>    fig = plt.figure(figsize=(10,5))<br>    ax1 = fig.add_subplot(121)<br>    ax2 = fig.add_subplot(122)<br><br>    # We add the first data points to the (x,y) plot and <br>    # set the limits<br>    ax1.axvline(0, color=&#39;r&#39;, linestyle=&#39;-&#39;)<br>    x0,y0 = cartCoords(th[0], l)<br>    ax1.set_xlim(-l-0.2, l+0.2)<br>    ax1.set_ylim(-l-0.2, l+0.2)<br>    ax1.set_xlabel(&quot;x (m)&quot;)<br>    ax1.set_ylabel(&quot;y (m)&quot;)<br><br>    # We add a dot and line to the (x,y) plot<br>    dot, = ax1.plot(x0, y0, &quot;ko&quot;)<br>    line,  = ax1.plot([0, x0], [0, y0], &quot;k&quot;)<br><br>    # We make the second plot showing theta as a <br>    # function of time<br>    ax2.plot(t, th, &quot;gray&quot;)<br>    ax2.axhline(y=0, color=&#39;r&#39;, linestyle=&#39;-&#39;)<br>    # We also add a dot for the animation<br>    dot2, = ax2.plot(t[0], th[0], &quot;ko&quot;)<br>    ax2.set_xlabel(&quot;t (sec)&quot;)<br>    ax2.set_ylabel(&quot;$\\theta$ (radians)&quot;)<br>    ax2.yaxis.set_label_position(&quot;right&quot;)<br>    ax2.yaxis.tick_right()<br><br>    # We can alter the start frame if we want<br>    t = t[start_at_frame:]<br>    th = th[start_at_frame:]<br>    <br>    # This function updates the plot for the animation<br>    def update(frame):<br>        # Updating the plots<br>        xi, yi = cartCoords(th[frame], l)<br>        dot.set_data([xi], [yi])<br>        line.set_data([0, xi], [0, yi])<br>        dot2.set_data([t[frame]], [th[frame]])<br><br>    # Create the animation<br>    ani = animation.FuncAnimation(fig=fig, func=update, \<br>                                  frames=frames, interval=interval)<br>    ani.save(ani_name)<br>    plt.close()<br><br>    return ani<br><br>plotPendulum(*theta_linear(t = np.arange(0, 2.0, 0.01), omega=9.81/1, \<br>             th_0 = 0.5), l=1, ani_name=&#39;fig3_pendulum_lin.gif&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*69lCRbAdB__F1JmoSVcVmw.gif" /><figcaption>Figure 3: a solution to the equation of motion for a pendulum using the approximation of small displacements. The solution is for an omega=9.81 s^-1 and an initial displacement in radians of 0.5. On the left you see the pendulum in (x,y) cartesian coordinates. On the right you see the angular displacement as a function of time. In red I have indicated the equilibrium location.</figcaption></figure><p>As you can see in Fig. 3, we have nice harmonic oscillations.</p><h3>Solving the non-linear equation of motion using solve_ivp and scipy</h3><p>Now it is time to solve the real deal without any approximations. For readability here is the equation of motion once more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*Eee4WM0erj47wCcjXyavNA.png" /></figure><p>We will go and solve this equation using scipy’s <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html">solve_ivp</a> function. As you have learned from my previous <a href="https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d)">blog</a> solve_ivp only solves a system of first order differential equations. We need to write our second order differential equation as two coupled first order ones. Like we did in the last <a href="https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d">blog</a> we can write the rate of change of 𝜃, lets call it the 𝜃 velocity, as the first kind of trivial equation :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*GSVma3z7Hl0vybwreQzRFw.png" /></figure><p>Here we used the dot one the 𝜃 to indicate the rate of change in time. Now we write the rate of change of the rate of change ;) of 𝜃 as the second equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*dizm-SrRmgz4qKEok1NJEg.png" /></figure><p>We now need to code a step function that <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html">solve_ivp</a> will call at every integration step to update the values of 𝜃 and d𝜃/dt. This function must have as first parameter the time t and as a second parameter a list containing the new values of 𝜃 and d𝜃/dt. We will call this list U and we will take the first item in the list to be 𝜃 and the second to be d𝜃/dt. This order is determined by the starting values we will give to solve_ivp. Our step function will look like this then:</p><pre>def step(t, U, omega):<br>    th, thDot = U    <br>    U_new = [thDot, -1 * omega**2 * np.sin(th)]<br>    return U_new</pre><p>The step function will return updated values of the values in U. So U[0] is 𝜃 and the step function must give the value of the time derivative of 𝜃 as an update for the integrator. So, U_new[0] will contain thDot, according to Eq. 1. And U[1] will contain d𝜃/dt, so U_new[1] must contain the time derivative of d𝜃/dt, which is −𝜔²sin(𝜃). Summarizing all this gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*GN9z4R8c0GnnMQudtq1WcQ.png" /></figure><p>So the most difficult part of coding solve_ivp is getting the eq. 1 and eq. 2 coded in the 𝑈 and 𝑈_new like above. If you want to see some more examples, check out my previous <a href="https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d">blog</a>. Next, we will make a function that implements solve_ivp and solves the non-linear differential equation:</p><pre>from scipy.integrate import solve_ivp<br><br>def theta_non_linear(th0, thDot0, omega=9.81/1, \<br>                    curve_start = 0, curve_end = 3, nr_points_curve = 100):<br>    # Starting conditions for theta (th0) and the time derivative of <br>    # theta (thDot0)<br>    U0 = [th0, thDot0]<br>    <br>    # The time values for which we want out solution<br>    t_pts = np.linspace(curve_start, curve_end, nr_points_curve)<br>    <br>    # Start the integrator<br>    result = solve_ivp(step, (curve_start, curve_end), U0, \<br>                        t_eval=t_pts, args=(omega,))<br>    <br>    # Return the time values and corresponding theta values (result.y has <br>    # the solutions for theta and thetaDot in the same order as you <br>    # have given them in the starting conditions)<br>    return result.t, result.y[0]</pre><h3>Exploring the solutions of solve_ivp in the non-linear case</h3><p>Let’s have a look at the different possible solutions we can find for the non-linear case and how it compares to the approximate solutions of the linear case. The function below plots four cases for four different starting conditions. With different starting conditions I mean different values of 𝜃_0, so different starting displacements. I keep the starting velocity of the pendulum the same, namely at zero (you just let loose the pendulum at an angle 𝜃_0).</p><pre>def make_compare_plot():<br>    fig = plt.figure(figsize=(10,10))<br>    ax1 = fig.add_subplot(221)<br>    ax2 = fig.add_subplot(222)<br>    ax3 = fig.add_subplot(223)<br>    ax4 = fig.add_subplot(224)<br><br>    ax1.set_title(&#39;$\\theta_0 = 0.05 \pi$&#39;)<br>    ax1.plot(*theta_linear(t = np.arange(0, 3.0, 0.01), omega=9.81/1, th_0 = 0.05), &quot;k&quot;, label=&quot;Linear&quot;)<br>    ax1.plot(*theta_non_linear(th0 = 0.05, thDot0=0.0, omega=9.81/1), &quot;r.&quot;, label=&quot;Non-linear&quot;)<br>    ax1.set_ylabel(&quot;y (m)&quot;)<br>    <br>    ax2.set_title(&#39;$\\theta_0 = 1/2 \pi$&#39;)<br>    ax2.plot(*theta_linear(t = np.arange(0, 3.0, 0.01), omega=9.8/1, th_0 = 1/2*np.pi), &quot;k&quot;)<br>    ax2.plot(*theta_non_linear(th0 = 1/2*np.pi, thDot0=0.0, omega=9.8/1), &quot;r.&quot;)<br>    ax2.set_ylabel(&quot;$\\theta$ (radians)&quot;)<br>    ax2.yaxis.set_label_position(&quot;right&quot;)<br>    ax2.yaxis.tick_right()<br>    <br>    ax3.set_title(&#39;$\\theta_0 = 0.9 \pi$&#39;)<br>    ax3.plot(*theta_linear(t = np.arange(0, 3.0, 0.01), omega=9.8/1, th_0 = 0.9*np.pi), &quot;k&quot;)<br>    ax3.plot(*theta_non_linear(th0 = 0.9*np.pi, thDot0=0.0, omega=9.8/1, curve_end=3, nr_points_curve = 100), &quot;r.&quot;)<br>    ax3.set_xlabel(&quot;x (m)&quot;)<br>    ax3.set_ylabel(&quot;y (m)&quot;)<br>    <br>    ax4.set_title(&#39;$\\theta_0 = \pi$&#39;)<br>    ax4.plot(*theta_linear(t = np.arange(0, 30.0, 0.01), omega=9.8/1, th_0 = np.pi), &quot;k&quot;)<br>    ax4.plot(*theta_non_linear(th0 = np.pi, thDot0=0.0, omega=9.8/1, curve_end=30, nr_points_curve = 1000), &quot;r.&quot;)<br>    ax4.set_xlabel(&quot;t (sec)&quot;)<br>    ax4.set_ylabel(&quot;$\\theta$ (radians)&quot;)<br>    ax4.yaxis.set_label_position(&quot;right&quot;)<br>    ax4.yaxis.tick_right()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*TWH_UtUAai0gFpbJRY6opA.png" /><figcaption>Figure 4: In black solid lines are the linear solutions and in red dots are the non-linear solutions.</figcaption></figure><p>In Fig. 4 you see that at 𝜃_0 = 0.05𝜋 you see there is no difference between the linear and non-linear case. This is understandable because the approximation 𝜃 ≈ sin(𝜃) that we used to get a linear differential equation, is valid at small 𝜃. When we increase 𝜃_0 to 1/2𝜋 we see our approximation breaking down and the linear equation is no longer a good description of the system. At 𝜃_0 = 0.9𝜋 we see the difference even stronger.</p><p>Now the last case in Fig. 4 we put the pendulum upside down at a displacement of 𝜃_0 = 𝜋 . This is a funny case. In this position, it should stay there since there is no force pushing it to the left or right. But it is not a stable solution, only a minute small deviation from exactly 𝜃_0 = 𝜋 and the pendulum will fall and start rotating. So a small rounding error or another numerical effect can throw it off.</p><p>If we run:</p><pre>plotPendulum(*theta_non_linear(th0=np.pi, thDot0=0, omega=9.8/1, \<br>              curve_start = 0, curve_end = 20, nr_points_curve = 500), \<br>              l = 1, start_at_frame = 60, interval = 20)</pre><p>we get the animation of Fig. 5. In this figure you can see an animation of this funny case of an upside down pendulum. For our calculations it is just a minute little numerical deviation from 𝜃_0 = 𝜋 that will throw it off and the rotation starts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*njSg47YVgGyE8pI9klhd-w.gif" /><figcaption>Figure 5:</figcaption></figure><h3>An exercise for you</h3><p>As an exercise for you to get a better feel for the non-linear behaviour of this system, solve the equation for (𝜃_0 = 𝜋) but use very small deviations to the length of the pendulum. For example, for l = 1.0, l = 1.01, l=1.001 and l=1.002. What do you see? Do such small deviations make any impact on the solution? Let me know in the comments below what you find!</p><p>Also, are you working on some fun project for which you need solve_ivp? Let me know in the comments, I would love to know what you are brewing!</p><blockquote>If you’ve enjoyed this post, clap 👏 for the story, leave a comment and follow me for more exciting physics and tutorials on Python and numerical techniques.</blockquote><p>Take care and cheers, <br>Ben</p><p>ps: In a next blog we will use solve_ivp to calculate trajectories of photons around black holes. In preparation you can already have a look at one of my previous blogs on Calculating lengths in curved spaces using SymPy’s symbolic mathematics, Python and Matplotlib.</p><p><a href="https://medium.com/@bldevries/calculating-lengths-in-curved-spaces-using-sympys-symbolic-mathematics-python-and-matplotlib-7c18da99fd7b">Calculating lengths in curved spaces using SymPy’s symbolic mathematics, Python and Matplotlib</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f287453d734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Start your journey in Python scripting & Blender with a Hello World script]]></title>
            <link>https://medium.com/@bldevries/start-your-journey-in-python-scripting-blender-with-a-hello-world-script-8028d5e2f2aa?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8028d5e2f2aa</guid>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[blender]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hello-world]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 13:17:51 GMT</pubDate>
            <atom:updated>2024-03-12T13:17:51.941Z</atom:updated>
            <content:encoded><![CDATA[<p>Good day everyone, this is the day to start scripting in Blender. The Python API in Blender is powerful and useful since you can really do everything in it that you can do by hand in Blender, and it uses the popular (for a reason) scripting language Python. In this blog we are making our first steps by writing a script that simply prints “Hello World!”, a true staple in many programming tutorials!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VXmPAy8J9sW10En523g4g.png" /><figcaption>Figure 1: this figure is to convince you that Python scripting in Blender is very useful :)</figcaption></figure><h4>Opening Blender from the console</h4><p>We start of slightly boring, but we simply must learn how to open Blender from a console. Since Python’s print statements are printed to the console, we simply need the console. Opening the console is different on different operating systems though.</p><p>On Windows it is simple: you open Blender, and you go to <em>Window&gt;Console</em>. On Mac and Linux, you need to open Blender from the console to have the console. This means you first open a console and then you need to find the executable of Blender and start it from the console. And to launch Blender from it you need to know where Blender’s executable is. On my Mac for example, the Blender executable is located at:</p><pre>/Applications/Blender_versions/Blender4.1.app/Contents/MacOS/Blender</pre><p>So simply typing that into the console is enough to start Blender. And all the print statements in Python will now be visible in this console!</p><h4>The workspace for Python scripting</h4><p>Now that we have Blender open with a console active, we will look for the Scripting Workspace. You can find this under the pre-made workspace tabs in the top right (see Fig. 2). This workspace is made up of windows useful for working with the Python API.</p><p>In Fig. 2 the <em>Text Editor</em> is indicated with a number one (Fig. 2–1). You can use this editor to write your scripts or load scripts from your hard drive. The Python console (Fig. 2-2) can be used to execute lines of code on the spot. Using the auto completion in this window is a great way to figure out how to do things in the Python API. Lastly you have the Info window (Fig. 2-3). This window shows the commands Blender is executing in the Python API. And this also shows what is happening when you click something in the interface of Blender. For example when you toggle edit mode in the 3D Viewport using the tab key, it shows the Python command executed in the background: bpy.ops.object.editmode_toggle(). Again, this is useful in figuring out the Python API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4I5EYFFWX6K4ItK5tbvGw.png" /><figcaption>Figure 2: using the scripting workspace in Blender.</figcaption></figure><h4>Your first script</h4><p>Alright, we talked about the scripting workspace, now let’s write our first script. We start by making a new Python file by pressing the New button, see Fig. 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUEolj-aRlykHMvXrquWkA.png" /><figcaption>Figure 3: creating a Python script in the Blender Text Editor.</figcaption></figure><p>We can now type the magic Python code print(“Hello World”) in our new file (Fig. 3-1). Next, we can execute this code by pressing the play button (Fig. 3–2). We can see in the info window that a script is executed (Fig. 3–3). And when we look at the console from which we started Blender, we can see the output of our script: <em>Hello World</em>. Congrats, you wrote your first Blender Python script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3Fi-fzWAL0mRsD2zP68XQ.png" /><figcaption>Figure 4: Executing and seeing the results of your Python script.</figcaption></figure><h4>Using your own editor</h4><p>You probably want to use your own favorite editor to write your Python scripts, right? Well, in Blender you can open an existing file in the editor by clicking on the file icon (Fig. 5–1). If you edit this file in your own editor outside of Blender, the editor in Blender indicates that the file has changed with a red question mark sign (Fig. 5–2). To load the newest version of your file, you can go to <em>Text &gt; Reload</em>, to reload the file before executing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAnuLG-u-9DGmeXWl3FxJQ.png" /><figcaption>Figure 5: loading and executing Python script that you edit outside of Blender.</figcaption></figure><h4>Closing comments</h4><p>There is much more to say about Python scripting in Blender, but this is your start. Remember that Blender is cool since everything you can do in Blender you can do using the Python API in Blender.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8028d5e2f2aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculating lengths in curved spaces using SymPy’s symbolic mathematics, Python and Matplotlib]]></title>
            <link>https://medium.com/@bldevries/calculating-lengths-in-curved-spaces-using-sympys-symbolic-mathematics-python-and-matplotlib-7c18da99fd7b?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c18da99fd7b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[sympy]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[gravity]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 10:12:26 GMT</pubDate>
            <atom:updated>2024-01-17T10:12:26.315Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog we will start our journey in symbolic mathematics in Python using <a href="https://www.sympy.org/en/index.html">SymPy</a>, 3D plotting in <a href="https://matplotlib.org/">matplotlib</a> and General Relativity. The theory of General Relativity describes how energy curves space and how objects move through curved space. Differential Geometry is heavily used in General Relativity and is, roughly speaking, all about studying lengths and differentials in curved spaces. A great curved space to start with is a sphere. In this blog we will use the two-dimensional surface of a sphere and calculate the distance between two points on this sphere. This will help us develop insight and learn mathematical machinery to continue towards calculations in curved four-dimensional space-times :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtAVQk5wzQpwANPDBoWtIA.jpeg" /><figcaption>Figure 1: An <a href="https://en.wikipedia.org/wiki/Strong_gravitational_lensing">Einstein ring</a> around LRG 3–757 as seen by the Hubble Space Telescope. You see how the light from a blue background galaxy moves through the curved space around the Luminous Red Galaxy in the forground.</figcaption></figure><p>We will do our calculations using <a href="https://www.sympy.org/">SymPy</a>, which is a way to do symbolic mathematics in Python. Maybe you are familiar with expensive software like Mathematica? SymPy offers similar capabilities but free and completely integrated into Python. In this blog we will learn how to create symbols, create expressions, vectors and matrices, differentiate these expressions and eventually convert symbolic expressions into numerical values.</p><p>This blog will by quite math heavy and there may be some prerequisites to understanding certain parts. It will be useful if you have some background in linear <a href="https://en.wikipedia.org/wiki/Linear_algebra">algebra</a> (vectors, matrices, <a href="https://en.wikipedia.org/wiki/Basis_(linear_algebra)">basis and coordinate transformations</a>). We will also use parametrized curves, but you can probably follow with some calculus experience. I also briefly touch on tensors, but all calculations are done using matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*IHPLk6QeAs2K66X-PGp7qQ.png" /><figcaption>Figure 2: The four curves on a sphere that we study in this blog.</figcaption></figure><h4>What are we going to calculate</h4><p>Before we dive into our calculations lets see what we are going to calculate. In Fig. 2 you see four differently colored curves drawn over a sphere. The sphere of unit radius is shown as a grey colored grid. In this blog we will calculate the lengths of these curves. For some curves, knowing the circumference of a sphere, it can be done easily (like for curve 𝛾₁ and 𝛾₂). Using some geometry, 𝛾₃ can also readily be calculated. But we want to do it for any curve on a sphere, for example 𝛾₄. Alright, lets get to it.</p><h4>Loading the necessary Python packages</h4><p>First, we need to load sympy for our symbolic calculations. We also need <a href="https://docs.sympy.org/latest/modules/vector/coordsys.html">CoordSys3D</a> from sympy to work with (basis) vectors. Also, we load <a href="https://numpy.org/">numpy</a> and matplotlib. For three dimensional plots we use the Axes3D from <a href="https://matplotlib.org/stable/users/explain/toolkits/mplot3d.html">mpl_toolkits</a>. To get our equations looking nice in jupyter notebooks we can use IPython.display. We also need to initialize sympy’s printing using <a href="https://docs.sympy.org/latest/tutorials/intro-tutorial/printing.html#setting-up-pretty-printing">sp.init_printing()</a>.</p><pre>import sympy as sp<br>from sympy.vector import CoordSys3D<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from mpl_toolkits.mplot3d import Axes3D<br>from IPython.display import display<br><br>sp.init_printing()</pre><h4>Writing symbolic coordinate expressions</h4><p>Our goal is to calculate the length of curves on a sphere. Such curves can naturally be described using spherical coordinates. We use 𝑟 as the distance from the origin of our coordinate system. 𝜃 is the angle from the z-axes and 𝜙 is the angle from the x-axes towards the y-axes (right-handed rotation around the z-axes). In some cases, for example when plotting, we want to convert our spherical coordinates to cartesian coordinates. So, let’s set up the expressions that relate spherical to cartesian coordinates.</p><p>For Sympy to calculate with expressions symbolically we need to create our variables as symbols. We want to write the cartesian coordinates 𝑥, 𝑦 and 𝑧 as functions of the spherical coordinates 𝑟, 𝜃 and 𝜙. So, we need to define the spherical coordinates as symbols.</p><pre>r, th, ph = sp.symbols(&#39;r \\theta \\phi&#39;)</pre><p>Now we can write the cartesian coordinates as a function of the spherical coordinates:</p><pre>x = r * sp.cos(ph) * sp.sin(th)<br>y = r * sp.sin(ph) * sp.sin(th)<br>z = r * sp.cos(th)</pre><p>And you can see that Sympy keeps these functions symnbolic and we can print them pretty like this:</p><pre>display(x, y, z)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*kA8K6SL07jm4rf0Ct7hKXA.png" /></figure><h4>Curves on a sphere</h4><p>Mathematicians will cringe reading the next explanation, but full mathematical rigor is out of the scope of this introduction so I will keep it simple. A two-dimension sphere is a surface that can be described by two numbers (here we will use 𝜃 and 𝜙). We can make a mapping of these two numbers to three numbers. The three numbers here are the coordinates used for the 3-dimensional space in which the surface is embedded. For our sphere these three numbers can be the cartesian coordinates 𝑥, 𝑦 and 𝑧 or the spherical coordinates 𝑟, 𝜃 and 𝜙. So, all points of a sphere of radius 𝑟=1 are given by a function (or a mapping):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*nhzUXgKdf7i2EZlWqZk81A.jpeg" /></figure><p>Or you can write the points of the sphere in three dimensions using the cartesian coordinates 𝑥, 𝑦 and 𝑧:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*FQy2ohusZgtMtlhX_6RDCA.png" /></figure><p>In a similar way a curve on the sphere can be described by only one parameter (a line is a 1-dimensional space). Thus, a curve in three dimensions can be seen as a mapping from one number to three:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*yqWUN4MlP9t6Bveqw6d1KQ.png" /></figure><p>Here 𝛾 gives all the points on the curve and 𝜃(𝜆) and 𝜙(𝜆) are functions that give the 𝜃 and 𝜙 coordinates of those points. 𝜆 is the parameter that covers the curve. A way to think of it is that 𝛾 is the location of a particle while 𝜆 is the time coordinate describing the movement of the particle over the curve.</p><p>Ok let’s write down the description of a curve in Python using Sympy. To work with objects in Sympy that have components, like vectors, we can use coordinate systems. We can define a coordinate system named ’N’ in Sympy like this:</p><pre>N = CoordSys3D(&#39;N&#39;)</pre><p>The curves we will study are parametrized by 𝜆, and as before we will create a symbol for this parameter:</p><pre>lamb = sp.symbols(&#39;\lambda&#39;) </pre><p>In this blog we will study four examples of curves, named 𝛾₁, 𝛾₂, 𝛾₃ and 𝛾₄ (see Fig. 2). Using our Sympy coordinate system N we write the components of the curve as a vector object using the N.i, N.j and N.k objects which, in our case, stand for the basis vectors of r, 𝜃 and 𝜙 components respectively:</p><pre>gam1 = N.i + 1/2*sp.pi* N.j + lamb*N.k # A curve over the equator<br>gam2 = N.i + lamb * N.j + 0 * N.k # A curve over a line of longitude<br>gam3 = N.i + 1/4*sp.pi* N.j + lamb*N.k # A curve at a lattitude above the equator<br>gam4 = N.i + 1/sp.sqrt(2)*lamb * N.j + 1/sp.sqrt(2)*lamb*N.k # A combination<br>display(gam1)<br>display(gam2)<br>display(gam3)<br>display(gam4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*OKFEQnhda2iqS3QOGs3FuQ.png" /></figure><p>You can see that Sympy keeps the curves symbolic.</p><h4>Let’s get numerical</h4><p>We like to work mostly symbolic so that we can see the mathematical form of all the expressions we derive. But we also want to calculate numbers, for example for plotting the curves we defined. Sympy has two ways to calculate numerical values from symbolic expressions. One slow, but easy, way is to use the functions <a href="https://docs.sympy.org/latest/modules/numeric-computation.html">subs()</a> and <a href="https://docs.sympy.org/latest/modules/numeric-computation.html">evalf()</a>. For example, if you want to calculate the x coordinate given some 𝑟, 𝜃, and 𝜙 values, you first substitute those values into the expression:</p><pre>x.subs(r, 1).subs(th, 1).subs(ph, 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*oLhkHLstc1QMvhsTgTyCgg.png" /></figure><p>And then you can evaluate the expression to a numerical value:</p><pre>x.subs(r, 1).subs(th, 1).subs(ph, 2).evalf()</pre><p>Which results in: −0.350175488374015.</p><p>Another, computational more efficient way to calculate numerical values is by converting an expression into a Python function using <a href="https://docs.sympy.org/latest/modules/utilities/lambdify.html">lambdify</a>. For example we want to plot a sphere using the symbolic expressions 𝑥(𝑟,𝜃,𝜙), 𝑦(𝑟,𝜃,𝜙) and 𝑧(𝑟,𝜃,𝜙) that we defined above. Then we can convert those expressions to Python functions using the <a href="https://docs.sympy.org/latest/modules/utilities/lambdify.html">lambdify()</a> function:</p><pre>func_x = sp.lambdify([r, th, ph], x, &quot;numpy&quot;)<br>func_y = sp.lambdify([r, th, ph], y, &quot;numpy&quot;)<br>func_z = sp.lambdify([r, th, ph], z, &quot;numpy&quot;)</pre><p>Now we can get numerical values using those functions:</p><pre>func_x(1, 1, 2)</pre><p>Which also gives −0.350175488374015.</p><p>The subs and evalf functions are useful for a quick calculation or check for a few numbers. If you want to calculate things for many values, you can better use the lambdify function.</p><h4>Plotting our curves</h4><p>To get an idea of what our curves look like we would like to plot them. Luckily matplotlib and the mpl_toolkits have the functionality to make 3D plots. But those functions need numerical value, so we need to convert the expressions for our curves to numerical values. For this we need to separate the 𝑟, 𝜃 and 𝜙 component from our curves. And then we need to calculate the x, y and z values using the func_x, func_y and func_z functions. All these operations have been bundled together in the function getXYZFromCurve:</p><pre>def getXYZFromCurve(gam, lamd_value):<br>    <br>    # We first separate the r, theta and phi coordinates of the curve. <br>    # We can do this using the inner product function dot().<br>    # We need to use vectorize because of this issue in sympy:<br>    # https://github.com/sympy/sympy/issues/5642<br>    r, th, ph = \<br>            np.vectorize(sp.lambdify([lamb], gam.dot(N.i), &quot;numpy&quot;)), \<br>            np.vectorize(sp.lambdify([lamb], gam.dot(N.j), &quot;numpy&quot;)), \<br>            np.vectorize(sp.lambdify([lamb], gam.dot(N.k), &quot;numpy&quot;))<br><br>    # Now we can use our lambdified function to calculate the x, y and z values.<br>    x = func_x(r(lamd_value), th(lamd_value), ph(lamd_value))<br>    y = func_y(r(lamd_value), th(lamd_value), ph(lamd_value))<br>    z = func_z(r(lamd_value), th(lamd_value), ph(lamd_value))<br>    <br>    return x,y,z</pre><p>The last thing before we can plot is that we need to set a start and end value for the parameter 𝜆:</p><pre>lamb_start, lamb_end = 0, np.pi</pre><p>Now we can start making a figure using matplotlib.</p><pre># We add a subplot to the figure which we tell to use the 3d projection <br>fig = plt.figure(figsize=(10,10))<br>ax = fig.add_subplot(projection=&#39;3d&#39;)<br># We set the scaling of the axis to equal<br>ax.set_aspect(&quot;equal&quot;) <br># Lastly we set the viewing angle from which we want to view our 3d scene.<br>ax.view_init(elev=30, azim=45, roll=0)<br><br># Using numpy we make a grid that we use to plot the wireframe<br>theta_w, phi_w =  np.mgrid[0:2*np.pi : 60j ,0:np.pi : 60j]<br><br># We set the radius of the wireframe sphere to 1 and calculate<br># the cartesian coordinates<br>r_w = 1<br>x_w = func_x(r_w, theta_w, phi_w)<br>y_w = func_y(r_w, theta_w, phi_w)<br>z_w = func_z(r_w, theta_w, phi_w)<br><br># We plot the wireframe<br>ax.plot_wireframe(x_w,y_w,z_w, colors= [0,0,0,0.08], linewidths=[0.5])<br><br># Next we make the lambda values for the curves<br>lamb_values = np.array(np.linspace(lamb_start, lamb_end, num=50, endpoint=True))<br><br># For all the curves we calculate the cartesian coordinates<br># using our getXYZFromCurve function and we plot the curve<br>x_line, y_line, z_line = getXYZFromCurve(gam1, lamb_values)<br>ax.plot(x_line, y_line, z_line, label = &quot;$\gamma_1$&quot;)<br><br>x_line, y_line, z_line = getXYZFromCurve(gam2, lamb_values)<br>ax.plot(x_line, y_line, z_line, label = &quot;$\gamma_2$&quot;)<br><br>x_line, y_line, z_line = getXYZFromCurve(gam3, lamb_values)<br>ax.plot(x_line, y_line, z_line, label = &quot;$\gamma_3$&quot;)<br><br>x_line, y_line, z_line = getXYZFromCurve(gam4, lamb_values)<br>ax.plot(x_line, y_line, z_line, label = &quot;$\gamma_4$&quot;)<br><br># Lastly we add labels and a legend<br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;y&quot;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*IHPLk6QeAs2K66X-PGp7qQ.png" /><figcaption>Figure 2: The four curves on a sphere that we study in this blog.</figcaption></figure><h4>Length of a curve</h4><p>I have taken the curves 𝛾₁, 𝛾₂ and 𝛾₃ in such a way that we can calculate their length easily, knowing the circumference of a circle (2𝜋𝑟).</p><p>The blue and orange curve in Fig. 2 ( 𝛾₁, 𝛾₂) must have length 𝑙₁=𝑙₂=𝜋 since the radius of our sphere is 1 and the length of the curve is half that of a circle.</p><p>Curve 𝛾₃ is half of a circle with radius 𝑅 = 𝑟 sin(𝜃) = √2/2, since 𝑟 = 1 and 𝜃 = 1/4 𝜋. So we predict a length of 𝑙₃ = √2/2 𝜋.</p><p>For curve 𝛾₁, 𝛾₂ and 𝛾₃ calculating the length was easy, but in more general cases like 𝛾₄ we would need some mathematical machinery. The strategy is that we cut a curve into segments, calculate the length of a segment, and integrate this over the whole curve. We can differentiate 𝛾 to 𝜆 to get the length of a piece of the curve (𝑑𝛾) when lambda changes a small amount (𝑑𝜆). This quantity is called the tangent or the speed of the curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*Cr_dobnvNoW25UexW-jKAg.png" /></figure><p>You can read this as the change in length of the curve when one changes the parameter 𝜆 by one unit. In physics 𝛾 is often the trajectory of a particle and 𝜆 can be the time and in that case 𝑈 can be seen as the speed. Now, the length of a curve can be calculated in the following way (please read on because this is only valid in certain cases):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*gOORN2tpBK3cwdKjQD1maQ.png" /></figure><p>Where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*8Oq_wn92uEDFq2IyLTXUCQ.png" /></figure><p>is the length of the speed at point 𝜆. Or in other words, U is the length of a piece of the curve when 𝜆 changes by 𝑑𝜆.</p><p>Let’s calculate the tangent for our four curves:</p><pre>U1 = sp.diff(gam1, lamb)<br>U2 = sp.diff(gam2, lamb)<br>U3 = sp.diff(gam3, lamb)<br>U4 = sp.diff(gam4, lamb)<br>display(U1)<br>display(U2)<br>display(U3)<br>display(U4)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*DkAolU1B72tHigsxxELN_Q.png" /></figure><p>Note that i, j, k stand for the directions of r, 𝜃 and 𝜙. Thus, the speed of 𝑈₁ is 1 in magnitude and points in the 𝜙 direction (east direction). Just as 𝑈₃. 𝑈₂ points in the 𝜃 direction (in the longitudinal direction towards the south pole). And 𝑈₄ has both a 𝜃 and 𝜙 component.</p><p>The squared length of the tangent vector U is:</p><pre>U1.dot(U1), U2.dot(U2), U3.dot(U3), U4.dot(U4)</pre><p>Which gives unit length for all tangents.</p><p>Now since 𝑈 is constant and has unit length for all our curves, everything seems simple. The length is simply 𝜆 at the end minus 𝜆 at the start of the curve, which is 𝜋 for curve 𝛾₁ and 𝛾₂, which is right. But it is also 𝜋 for 𝛾₃, which is <strong>wrong</strong>! What is going on?</p><p>Well, to train our intuition, we can see that the longitude lines (the lines connecting the north and south pole) do not stay at equal distance to each other. If you go from the equator to the north pole the distance between the longitudinal lines ‘shrinks’ all the way to zero. More so, these longitudinal lines start parallel to each other at the equator (𝜃 = 90 degrees) but the closer you get to the north pole (𝜃 = 0 degrees) the further away the lines become from parallel.</p><p>We see this ‘shrinkage’ effect influences the length difference between the curve 𝛾₁ and 𝛾₃. They are east-west curves (starting and ending at the same 𝜙 values) but are located at different 𝜃 values (𝜃 = 1/2 𝜋 and 1/4 𝜋 respectively). And things go wrong because we are not considering that the space ‘shrinks’ between two longitudinal lines and this shrinkage dependents on the value of 𝜃. Therefor 𝛾₁ and 𝛾₃ are different in length.</p><p>The ‘shrinkage’, or better called the curvature of space, manifests itself in the basis vectors, something we have ignored until now. We have done our calculation assuming the basis vectors N.i, N.j and N.k are constant and of unit length. This is fine when you are using cartesian coordinates, which have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*UrCHUv5u-k4c0X4MC2VKRg.png" /></figure><p>(in code N.i.dot(N.i) = N.k.dot(N.j) = N.k.dot(N.k) = 1), where <em>𝑒</em> stands for a basis vector. This means that for cartesian coordinates the basis vectors are constant and of unit length. It is an orthonormal basis. But we are using spherical coordinates (a type of <a href="https://en.wikipedia.org/wiki/Curvilinear_coordinates">curvilinear coordinates</a>), where this is not the case! The spherical basis vectors are orthogonal, but not of unit length and not constant. Let’s see what they look like.</p><p>If we write the basis vectors of our spherical coordinates in terms of the cartesian basis vectors, we need to calculate the following basis transformation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*AoV6LIxDeD7h5pvneYJKWA.png" /></figure><p>Using this basis transformation and Sympy we can write the spherical basis vectors in terms of the cartesian ones:</p><pre>e_r = x.diff(r) * N.i + y.diff(r) * N.j + z.diff(r) * N.k<br>e_th = x.diff(th) * N.i + y.diff(th) * N.j + z.diff(th) * N.k<br>e_ph = x.diff(ph) * N.i + y.diff(ph) * N.j + z.diff(ph) * N.k<br>display(e_r)<br>display(e_th)<br>display(e_ph)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*XepDJQvGjrXaDIgdqeHaUw.png" /></figure><p>Here you can see Sympy differentiating an expression and give a symbolic answer, which is pretty nice!</p><p>Now we calculate the squared length of the spherical basis vectors:</p><pre>display(e_r.dot(e_r).simplify())<br>display(e_th.dot(e_th).simplify())<br>display(e_ph.dot(e_ph).simplify())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*m_rnu1rFPQyqn486T9M55w.png" /></figure><p>We see that the r basis vector is one but the other two for 𝜃 and 𝜙 are not. We see that the 𝜙 basis vector is a function of 𝜃. This is exactly what we saw with curve 𝛾₁ and 𝛾₃. Those two curves have a tangent vector that only has a 𝜙 component, but they lie on two different latitudes (different 𝜃 values). Therefor the lengths of their basis vectors are different and if you do not account for this your calculations go wrong!</p><p>We now see that we need to expand our definition of an inner product as a measure of length. We need to incorporate the basis vectors in our calculation of length. The inner product we used only makes sense as a measure of length for vectors on an orthonormal basis (for a basis where the basis vectors have unit length). This holds for the cartesian basis vectors, but not for the spherical basis vectors we have.</p><p>So how should you calculate the length of a line on a curved surface? This is a complicated issue, but to start building our intuition let me briefly show how to do it without too much explanation. If we properly incorporate the basis vectors in our definition of length, we would write the inner product as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*uNBgjoXN0Rln1N4Qm6-A1Q.png" /></figure><p>Here U with super script 𝜇 are the components of the vector 𝑈, for example the r, 𝜃 and 𝜙 components of 𝑈 are respectively 𝑈⁰, 𝑈¹ and 𝑈² in the case of spherical coordinates. The summation indices 𝜇 and 𝜈 thus count over 0, 1 and 2.</p><p>We call 𝑔 the metric tensor, but at this point I will not go into tensors, just keep with me while I work with tensors as if they are matrices :). The basis vectors are encoded into this metric object. In three dimensions the metric has 3x3=9 components and to keep it familiar to most, it can be imagined as a matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*Wm0LIASJt9DlZbC_K6X03Q.png" /></figure><p>The off-diagonal elements of the matrix are zero for spherical coordinates because the basis vectors are orthogonal. Using Sympy and its matrix implementation we can readily calculate the metric:</p><pre>g = sp.Matrix( [ [e_r.dot(e_r).simplify(), 0, 0], \<br>            [0, e_th.dot(e_th).simplify(), 0], \<br>            [0, 0, e_ph.dot(e_ph).simplify()] ])<br>g</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*KsLvc9mnr0SYdJMSKIBdkw.png" /></figure><p>Note that I could calculate the inner product between basis vectors of spherical coordinates because I can write them in terms of the cartesian basis vectors. And the inner product of cartesian vectors can be calculated using our old idea of length. For cartesian coordinates the metric is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*fV1CSuup1nUaQcYJU_lqUQ.png" /></figure><p>And the inner product reduces to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*jeRmA-BUwYdlXeEEb_cE0Q.png" /></figure><p>Which is the inner product we learned in flat space and is nothing more than Pythagoras’s theorem.</p><p>For the length of our curves in spherical coordinates we can now also calculate the inner product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*XOw5YN53GuViekzELEa7gQ.png" /></figure><p>We can do the same calculation in matrix form (considering how matrices are multiplied) and we would write this as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*1gfaYzdzfAXLa-UQUPdPAg.png" /></figure><h4>Length of a curve</h4><p>The length of a curve can now in general be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*xordwUiMiChhJDdfLggpIA.png" /></figure><p>We can implement this formula for the length of a curve in the following Python function:</p><pre>def lengthCurve(gam, g, lamb_start, lamb_end, v=False):<br>    # Get the spherical components r, th and phi of the curve:<br>    r_comp = gam.dot(N.i)<br>    th_comp = gam.dot(N.j)<br>    ph_comp = gam.dot(N.k)<br><br>    # Differentiate gamma to get U<br>    U = sp.diff(gam, lamb)<br>    # Put U in matrix form<br>    U_M = sp.Matrix([U.dot(N.i), U.dot(N.j), U.dot(N.k)])<br><br>    # The following needs to be integrated<br>    l_lamb = sp.sqrt( (U_M.T * g * U_M)[0].subs(r, r_comp).subs(th, th_comp).subs(ph, ph_comp) ).simplify()<br>    <br>    # Do the integral<br>    L = sp.integrate(l_lamb, (lamb, lamb_start, lamb_end))#.simplify()<br>    <br>    return L</pre><p>To start calculating this length for our curves we write the tangent vectors as matrices in Sympy:</p><pre>U1_M = sp.Matrix([U1.dot(N.i), U1.dot(N.j), U1.dot(N.k)])<br>U2_M = sp.Matrix([U2.dot(N.i), U2.dot(N.j), U2.dot(N.k)])<br>U3_M = sp.Matrix([U3.dot(N.i), U3.dot(N.j), U3.dot(N.k)])<br>U4_M = sp.Matrix([U4.dot(N.i), U4.dot(N.j), U4.dot(N.k)])<br>display(U1_M)<br>display(U2_M)<br>display(U3_M)<br>display(U4_M)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*U-fMB0xYFVI01np-cAtTlg.png" /></figure><p>Now finally we can calculate the length of our curves properly:</p><pre>lengthCurve(gam1, g, 0, sp.pi)</pre><p>Which gives 𝜋 as it should. And the next gives the same:</p><pre>lengthCurve(gam2, g, 0, sp.pi)</pre><p>The one that went wrong the last time:</p><pre>lengthCurve(gam3, g, 0, sp.pi)</pre><p>Now correctly gives 𝜋/√2. Yay!</p><p>And lastly the curve for which we could not easily find an answer:</p><pre>L4 = lengthCurve(gam4, g, 0, sp.pi)<br>display(L4)<br>L4.evalf()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*1UNqUGunMzxwsSX_6_M5Ig.png" /></figure><p>Which sympy evaluates to 2.8. But do we know this is correct? Let’s do an extra check.</p><h4>Extra check to see if the length of 𝛾₄ is correct</h4><p>I will plot (using the same code as before) the second and fourth curve again. This time though, we set the end point of 𝛾₄ so that it ends at the south pole.</p><pre>fig = plt.figure(figsize=(7,7))<br>ax = fig.add_subplot(projection=&#39;3d&#39;)<br>ax.set_aspect(&quot;equal&quot;) <br>ax.view_init(elev=30, azim=45, roll=0)<br><br>theta_w, phi_w =  np.mgrid[0:2*np.pi : 60j ,0:np.pi : 60j]<br><br>r_w = 1<br><br>x_w = func_x(r_w, theta_w, phi_w)<br>y_w = func_y(r_w, theta_w, phi_w)<br>z_w = func_z(r_w, theta_w, phi_w)<br><br>ax.plot_wireframe(x_w,y_w,z_w, colors= [0,0,0,0.08], linewidths=[0.5])#color = &quot;grey&quot;)<br><br>lamb_values = np.array(np.linspace(0, np.pi, num=50, endpoint=True))<br>x_line, y_line, z_line = getXYZFromCurve(gam2, lamb_values)<br>ax.plot(x_line, y_line, z_line, label = &quot;gamma2&quot;)<br><br><br>lamb_values = np.array(np.linspace(0, 2*np.pi/np.sqrt(2), num=50, endpoint=True))<br>x_line, y_line, z_line = getXYZFromCurve(gam4, lamb_values)<br>ax.plot(x_line, y_line, z_line, label = &quot;gamma4&quot;)<br><br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;y&quot;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9kiG816lydNH5YZRNqk8hA.png" /><figcaption>Figure 3: an extended version of the fourth curve that now goes from the north pole to the south pole.</figcaption></figure><p>Because both curves end and the south pole, we can compare the length of the curve 𝛾₂ to that of 𝛾₄. In the next blog I will show how we can determine the shortest path between two points in a curved space. This is a very important concept in General Relativity and such a line is called a geodesic. But for now, our intuition probably tells us that 𝛾₂ (together with all the other longitudinal lines) is the shortest path between the poles. So, our calculations should at least show us that the length 𝑙₂&lt;𝑙₄.</p><p>The length of 𝛾₄ with its new end point is now:</p><pre>L4 = lengthCurve(gam4, g, lamb_start=0, lamb_end=2*sp.pi/sp.sqrt(2))<br>display(L4)<br>L4.evalf()</pre><p>Which evaluates to 3.8 and thus we have that indeed 𝑙₂&lt;𝑙₄. Excellent!</p><h4>The end</h4><p>I hope you enjoyed this first voyage into curved spaces and symbolic math with Sympy! In the next blog we will look at how we can calculate the shortest path between two points in a space. These shortest paths are interesting, because there actually is no gravitational <em>force</em>, but particles simply move over the shortest paths through curved space. These shortest paths give the equivalent of straight lines in curved space. But let’s not get ahead of ourselves, see you in the next blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c18da99fd7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simply solving differential equations using Python, scipy and solve_ivp]]></title>
            <link>https://medium.com/@bldevries/simply-solving-differential-equations-using-python-scipy-and-solve-ivp-f6185da2572d?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6185da2572d</guid>
            <category><![CDATA[differential-equations]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[scipy]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 15:35:13 GMT</pubDate>
            <atom:updated>2024-06-14T18:25:24.526Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog we will have a look at how we can use <a href="https://scipy.org/"><em>scipy</em></a> and <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html"><em>solve_ivp</em></a> to numerically solve a second order <a href="https://en.wikipedia.org/wiki/Ordinary_differential_equation">ordinary</a> <a href="https://en.wikipedia.org/wiki/Differential_equation">differential equation</a> (ODE). This is a very useful skill if you are in scientific visualization or any other technical discipline.</p><p>For example, I want to visualize black holes in a physics correct way. For this I am planning to solve the differential equations that govern how light travels in strong gravitational fields. <em>Scipy</em> and <em>solve_ivp</em> can help me do that numerically. But more on that in a later blog.</p><p>For now, we will take a simple differential equation that belongs to harmonic movement. If you are interested in some basic physics, read on, otherwise maybe skip the next section :)</p><p><em>This blog is part of a series, check out the next one also:</em></p><p><a href="https://medium.com/@bldevries/prelude-to-chaos-solving-non-linear-differential-equations-with-solve-ivp-and-scipy-2f287453d734">Prelude to chaos: solving non-linear differential equations with solve_ivp and scipy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*SvoeJs87WfM6fgKCZlkg1w.png" /><figcaption>Figure 1: drawing of a mass connected to a wall with a spring. When the mass gets a displacement x(t) from its equilibrium position (dashed vertical line) it will start oscillating about the equilibrium line. We assume the mass has no friction with the floor.</figcaption></figure><h4><strong>Newtons equations of motion for a harmonic oscillator</strong></h4><p>An example of a physical system that exhibits harmonic oscillations is a mass connected to a spring, see Fig. 1. Assuming no friction with the floor, if we displace the mass <em>m</em> from its equilibrium position and let it go, it will start to oscillate around its rest position. We can describe this movement with a differential equation using Newton’s equations of motion.</p><p>We assume that the force of the spring on the mass is proportional to the displacement (<em>x(t)</em>) and in the opposite direction to the displacement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*EH_bbV3PQhI4y6Ee8wMW5g.png" /><figcaption>Eq. 1</figcaption></figure><p>Where <em>k</em> is the spring constant. The equation of motion now reads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*4zGDBkl7c5bRJSeFBVkHhg.png" /><figcaption>Eq. 2</figcaption></figure><p>And if we realize that the acceleration <em>a</em> is the second derivative of the displacement <em>x</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*1BT8v1DHmMpxnxt698uYOQ.png" /><figcaption>Eq. 3</figcaption></figure><p>And this is the second order ordinary differential equation that we are going to solve using <em>solve_ivp</em> and <em>scipy</em>!</p><h4><strong>Exploring solve_ivp from the scipy package</strong></h4><p><a href="https://scipy.org/"><em>Scipy</em></a> has the great function <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html"><em>solve_ivp</em></a> which can integrate a system of ordinary differential equation for you. You can use it by calling:</p><pre>scipy.integrate.solve_ivp(fun, t_span, y0)</pre><p>The <em>solve_ivp</em> function can take more arguments but these three are necessary. Here fun stands for a <em>Python</em> function that implements the system of differential equations. And t_span is the range over which to integrate the differential equations. For example t_span=(0,1) integrates the system starting at 0 and up to 1. The last is y0 and this is a list of boundary conditions, one for every differential equation in the system.</p><p>Lets practice with <em>solve_ivp</em> and solve the simple differential equation for logarithmic functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*uHSBgEFAFuT9mJIC4L_5Mw.png" /><figcaption>Eq. 4</figcaption></figure><p>We now need to implement the right hand side of the differential equation into the function fun like this:</p><pre>def fun(x, y):<br>  return -y</pre><p>The function fun is given both the value of x and y for the current integration step. You then calculate the new value of dy/dx in fun(x,y) and return it.</p><p>We can solve the equation by first making a list of <em>x</em> values we want:</p><pre>x_pts = np.linspace(0, 10, 11)</pre><p>And then call solve_ivp over the interval x=0 to x=10 and using the boundary condition y(0)=1. We also use the t_eval argument to calculate the solution at the points in t_eval after the system is solved:</p><pre>result = solve_ivp(fun, (0, 10), [1], t_eval=x_pts)</pre><p>We can now print the result object and see that <em>solve_ivp</em> is succesfull:</p><pre>message: The solver successfully reached the end of the integration interval.<br>success: True<br>status: 0<br>t: [ 0.000e+00 1.000e+00 2.000e+00 3.000e+00 4.000e+00<br>5.000e+00 6.000e+00 7.000e+00 8.000e+00 9.000e+00<br>1.000e+01]<br>y: [[ 1.000e+00 3.681e-01 1.355e-01 4.986e-02 1.835e-02<br>6.752e-03 2.486e-03 9.151e-04 3.370e-04 1.241e-04<br>4.572e-05]]<br>sol: None<br>t_events: None<br>y_events: None<br>nfev: 74<br>njev: 0<br>nlu: 0</pre><p>We can now plot our solution together with the analytical solution <em>y(x) = e^-x</em>:</p><pre>plt.plot(result.y[0,:], label = &quot;Numerical solution&quot;)<br>plt.plot(x_pts, [math.e**(-x) for x in x_pts], &quot;o&quot;, \<br>                label=&quot;Analytical solution&quot;)<br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;y(x)&quot;)<br>plt.legend()</pre><p>And as you can see in Fig. 2 we have good agreement between the solution of <em>solve_ivp</em> and the analystical solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*xz1VA4H78XOO0lLOcu2f9g.png" /><figcaption>Figure 2: our numerical solution using solve_ipv and scipy of equation 4 (blue line) and the analytical solution (orange dots).</figcaption></figure><h4><strong>Solving our differential equation for harmonic motion using solve_ivp</strong></h4><p>Now it is time to solve our slightly more complicated differential equation describing harmonic motion. We will rewrite Eq. 3 as a system of coupled differential equations. We do this because the <em>solve_ivp</em> function does not take second order differential equations directly as an input. Now we can write (also setting k/m=1 to keep it simple):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*tSSXUEnGproDb1PSMn6gkg.png" /><figcaption>Eq. 5</figcaption></figure><p>We now have two coupled functions to solve. In this example we can write the function fun as:</p><pre>def fun(t, U):<br>  x, v = U<br>  return [v, -x]</pre><p>Here <em>U = [x(t), v(t)]</em> and it is the current value of <em>x(t)</em> and <em>v(t)</em> that the integrator calculated and passed to fun(t, U). Now we must make sure the function returns the new value for <em>[dx/dt, dv/dt] </em>which is <em>[v, -x]</em> (see Eq. 5).</p><p>We can now calculate our solution like this:</p><pre>U_0 = [0, 1]<br>t_pts = np.linspace(0, 15, 100)<br>result = solve_ivp(fun, (0, 20*math.pi), U_0, t_eval=t_pts)</pre><p>Here we have set our initial conditions to be x(0) = 0 and v(0) = 1. This will lead to a solution <em>x(t) = sin(t)</em>. We plot our solutions in Fig.3.</p><pre>plt.plot(result.y[0,:], label = &quot;Numerical solution&quot;)<br>plt.plot([math.sin(t) for t in x_pts], &quot;o&quot;, label=&quot;Analytical solution&quot;)<br>plt.xlabel(&quot;t&quot;)<br>plt.ylabel(&quot;x(t)&quot;)<br>plt.xlim(0,40)<br>plt.legend()</pre><p>As you can see from Fig. 3, we have found the solution we expected!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*Bqm5PJ75S2j_FslAhusrCw.png" /><figcaption>Figure 3: our numerical solution using solve_ipv and scipy of equation 3 or 5 (blue line) and the analytical solution (orange dots).</figcaption></figure><h4>In conclusion</h4><p>We have solved the second order differential equation describing harmonic motion using <em>solve_ivp</em>, <em>scipy</em> and <em>Python</em>. You see it is not too difficult, its only tricky to translate the second order differential equation to two coupled first order equations that <em>solve_ivp</em> understands. I hope this blog gives you an idea on how to use <em>solve_ivp</em>, <em>scipy</em> and <em>Python</em> to solve your problem! Best of luck and see you in a next blog.</p><p>Are you interested in a more complex example? Check out my new blog:</p><p><a href="https://medium.com/@bldevries/prelude-to-chaos-solving-non-linear-differential-equations-with-solve-ivp-and-scipy-2f287453d734">Prelude to chaos: solving non-linear differential equations with solve_ivp and scipy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6185da2572d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Symphony of Spheres: Animating Spherical Harmonics in Blender with Python and Shape Keys]]></title>
            <link>https://medium.com/@bldevries/a-symphony-of-spheres-animating-spherical-harmonics-in-blender-with-python-and-shape-keys-aa67b7ff3d93?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa67b7ff3d93</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[blender]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[3d]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 11:32:42 GMT</pubDate>
            <atom:updated>2023-10-04T11:32:42.103Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to our journey into the captivating world of scripting in Blender! In this blog, we’ll dive into the art of animating mesh vertices using Blender’s Python API and Shape Keys. But this won’t be your typical tutorial; we’re about to bring mathematics to life. Picture this: spherical harmonic functions breathing life into a seemingly static sphere, making it dance to the rhythm of oscillating modes. Intrigued? Join us as we learn how to make the mesmerizing animation in Fig. 1 using Shape Keys and the Python API in Blender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7W1IWworMqYgfEyJ8uaeA.gif" /><figcaption>Figure 1: an animation of Spherical Harmonics in three different modes. From left to right the modes are (l=3, m=0), (l=10, m=3) and (l=10, m=0)</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Spherical_harmonics">Spherical harmonics</a> are functions defined on the surface of a sphere. They appear in various natural phenomena, such as the mathematical description of the ‘orbit’ of an electron in a hydrogen atom. However, you do not need to know more about these functions to follow along in this blog. We will utilize the spherical harmonics available in the Python package <a href="https://scipy.org/">SciPy</a>. These functions will serve as standing waves on the surface of a sphere (see Fig. 1), similar to standing waves on a guitar string.</p><h3><strong>Start of our script</strong></h3><p>To begin, we will import essential Python packages into our script. We require ‘bpy’ to access the Blender Python API, ‘numpy’ for various mathematical functions, and ‘mathutils’ to work with vectors. Additionally, we need the spherical harmonics module from ‘<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.sph_harm.html">scipy.special</a>’.</p><pre>import bpy<br>import numpy as np<br>from scipy.special import sph_harm <br>import mathutils</pre><p>Much like a string, a sphere can oscillate in different modes. The modes of spherical harmonics are defined using two integers: ‘l’ and ‘m.’ ‘l’ ranges from 0, 1, 2, 3, and so on, and for each ‘l,’ ‘m’ can vary from -l, .., 0, to l. For instance, when ‘l’ is set to 3, ‘m’ can take on the values -3, -2, -1, 0, 1, 2, and 3. We will create two Python variables to define ‘l’ and ‘m.’</p><pre>l, m = 3,1</pre><p>Our objective is to visualize spherical harmonics as standing waves on a sphere. To achieve this, we’ll start by creating a <a href="https://docs.blender.org/api/current/bpy.ops.mesh.html#bpy.ops.mesh.primitive_uv_sphere_add">UV sphere</a> in Blender using the code below. Afterward, we’ll obtain the new sphere object by referencing the active object in Blender and assigning it a distinctive name using ‘obj.name’.</p><pre>radius = 3<br><br>bpy.ops.mesh.primitive_uv_sphere_add(segments=128, ring_count=128, \<br>               radius=radius, calc_uvs=True, enter_editmode=False, \<br>               align=&#39;WORLD&#39;, location=(0.0, 0.0, 0.0), \<br>               rotation=(0.0, 0.0, 0.0), scale=(1.,1.,1.))<br>                                        <br>obj =  bpy.context.active_object<br>obj.name = str(l)+&quot;_&quot;+str(m)</pre><h3>Getting the coordinates to work</h3><p>The spherical harmonic function in SciPy uses polar coordinates, whereas Blender employs Cartesian coordinates. Hence, we must be capable of converting between polar and Cartesian coordinates, as well as performing the reverse conversion. It’s not essential to have a deep understanding of these conversions, particularly the transformation from Cartesian to polar coordinates. (This is tricky near the poles of the sphere and mapping the entire sphere can be challenging, considering that trigonometric functions are defined on only a portion of the sphere.)</p><pre>def getCart(r, theta, phi):<br>    x = r * np.cos(phi) * np.sin(theta)<br>    y = r * np.sin(phi) * np.sin(theta)<br>    z = r * np.cos(theta)<br>    return (x, y, z)<br><br>def getPolar(x, y, z):<br>    # Round out small errors from the trigonometric functions<br>    x, y, z = round(x, 5), round(y, 5), round(z, 5) <br>    <br>    r = np.sqrt(x**2 + y**2 + z**2)<br>    theta = np.arccos(z/r) #[0,pi]<br>    xy = round(r * np.sin(theta), 5)<br>    if xy == 0.0:<br>        phi = 0.0<br>    else:<br>        if x &gt;= 0:<br>            phi = np.arcsin(y/xy) #[-1/2pi, 1/2pi]<br>        else:# x &lt; 0:<br>            phi = np.arcsin(y/xy) #[-1/2pi, 1/2pi]  <br>            phi = np.pi - phi<br>    return (r, theta, phi)</pre><p>In our case, we consider θ as the angle measured from the z-axis, and ϕ as the angle measured from the x-axis. It’s necessary to round off some values because trigonometric functions don’t consistently yield precise zeros. The arccosine function has a range from zero to π, while the arcsine function covers only the range from -1/2 π to 1/2 π. As a result, we need to manually ensure that we account for both sides of the sphere, including the positive and negative sides of the x-axis.</p><h3>Shape Keys</h3><p><a href="https://docs.blender.org/manual/en/latest/animation/shape_keys/introduction.html">Shape Keys</a> are a method to alter the form of an object and are particularly useful for animation. You can access Shape Keys in the Properties editor under the Object Data tab and the Shape Keys tab (see Fig. 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*hr3ebN_tQhSI-86PQie3_g.png" /><figcaption>Figure 2: a screenshot of where the Shape Keys can be found in Blenders interface. The Shape Keys tab is located within the Object Data tab in the Properties Editor.</figcaption></figure><p>Using the ‘+’ button, you can add Keys to the list. The initial Key you add is known as the ‘Basis’, representing the object’s shape when all other Keys are set to zero. Adding additional Keys allows you to define alternative shapes. Ensure that the Key is selected in the Object Data tab and then switch to edit mode. Here, you can make adjustments, such as modifying the location of the vertices (in the next section we will do the same but through code).</p><p>Each Key is associated with a numerical value (called Value in the Shape Key tab, see Fig. 2). When this value is set to zero, the Key has no impact on the object’s shape. Setting it to 1 results in the object taking on the shape defined by that Key. Intermediate values produce shapes that interpolate between the Basis shape and the Key shape.</p><p>You’ll notice that the Value associated with the Key has a dot next to the field. This signifies that you can animate this value, thereby animating the object’s shape.</p><h3>Using Shape Keys in the Python API</h3><p>We’ve created a sphere in Python, and we’ve imported the spherical harmonics from the SciPy library. These spherical harmonic functions provide us with the amplitude (Amp) at every θ and ϕ coordinate of the vertices on the sphere. For the animation, we’ll use these amplitudes within Blender’s Shape Keys.</p><p>First, we need to create the ‘Basis’ and a second Shape Key programmatically in Python. Shape Keys are part of the object’s data and can be added using the ‘obj.shape_key_add(name=’Basis’)’ method. We then specify that we want linear interpolation between these Keys, and we want the Keys to be relative to the ‘Basis’ Key (see the code below). Subsequently, we add a second Shape Key and set its interpolation to linear as well.</p><pre># Make the basis shape key at minimum amplitude<br>sk_basis = obj.shape_key_add(name=&#39;Basis&#39;)<br>sk_basis.interpolation = &#39;KEY_LINEAR&#39;<br>obj.data.shape_keys.use_relative = True#False<br><br># The next shape key is at max amplitude<br>sk2 = obj.shape_key_add(name=&#39;Deform&#39;)<br>sk2.interpolation = &#39;KEY_LINEAR&#39;</pre><p>Next, we proceed to modify the vertices within both Shape Keys. To achieve this, we iterate over the vertices of the object (‘obj.data.vertices’). We convert the Cartesian coordinates of these vertices into polar coordinates and calculate the amplitude using spherical harmonics. Since spherical harmonics are complex functions, it’s crucial to consider either the real or imaginary part of the function.</p><pre>for i in range(len(obj.data.vertices)):<br>    x, y, z = obj.data.vertices[i].co<br><br>    r, theta, phi = getPolar(x, y, z)<br>    <br>    Amp = sph_harm(m, l, phi, theta).imag if m&lt;0 \<br>            else sph_harm(m, l, phi, theta).real<br><br>    VertMin = mathutils.Vector(getCart(r - Amp, theta, phi))<br>    VertMax = mathutils.Vector(getCart(r + Amp, theta, phi))<br>    <br>    sk_basis.data[i].co = VertMin<br>    sk2.data[i].co = VertMax</pre><p>Subsequently, we calculate the vertex positions corresponding to the minimum amplitude (r — Amp) and maximum amplitude (r + Amp). Afterward, we convert these positions back into Cartesian coordinates and update the vertex positions in the ‘Basis’ Key to reflect the minimum values and in the second Key to represent the maximum values. As a result, we’ve successfully created our Shape Keys.</p><p>After running the script, you can navigate to the Object Data properties and adjust the ‘Value’ associated with the second Key (see Fig. 2) to observe the resulting spherical harmonic transformation.</p><h3>Animation</h3><p>In an upcoming blog, I will demonstrate how to automate the animation of these spheres using the Python API. However, for this blog, we will create animations manually in order to achieve what you see in Fig. 1. The simplest way to proceed is by navigating to the Animation Workspace. At the bottom of the interface, you’ll find the ‘Dope Sheet’ (see Fig. 3). I’ll assume you’re already familiar with animating objects; if not, you can refer to our <a href="https://surf-visualization.github.io/blender-course/basics/animation/introduction/">course site</a> for guidance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0SrAw8G-8H1y0sZpa4vWg.png" /><figcaption>Figure 3: the Dope Sheet Editor.</figcaption></figure><p>Begin by setting the current frame to 0. Now select the ‘Deform Shape’ in the Object Data Properties tab and set the ‘Value’ field to zero (see Fig. 2). Use the dot next to the ‘Value’ field (see Fig. 2) to create a keyframe. You’ll notice a keyframe marker appearing at frame 0 on the timeline in the Dope Sheet, indicating the creation of a keyframe.</p><p>Proceed to frame 20, set the ‘Value’ for the Shape Key to 1, and press the diamond-shaped icon (formerly a dot) located next to the ‘Value’ field to create another keyframe. Repeat this process for frame 40, setting the ‘Value’ back to zero. Finally, set the ‘End’ frame of the animation to 40. You can locate this setting at the bottom-right corner of the Dope Sheet (as depicted in Fig. 3). Now, start the animation and enjoy the result.</p><h3>Materials</h3><p>If you’re curious about the type of material I’ve used to create Fig. 1, it’s actually quite straightforward. Navigate to the Shading Workspace and add a Glass BSDF shader. Then, connect it to the output. For information regarding the shader’s settings, see Fig. 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*KSHlN_2yt-i4CH9H1wiYEw.png" /><figcaption>Figure 4: the shader nodes used for the animation in Fig. 1.</figcaption></figure><h3>Conclusion and exercises</h3><p>I hope this blog has helped you understand what Shape Keys and the Python API can do for you in Blender. It would be great if you could apply these techniques to your scientific visualization or any type of visualization project you are working on. I would love to hear from you and see what you have created. In the next blog we will explore how we can automate the animation and shading of these spheres using the Python API in Blender. Until then, keep creating and exploring!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa67b7ff3d93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering with Blender in the background and using the command-line]]></title>
            <link>https://medium.com/@bldevries/rendering-with-blender-in-the-background-and-using-the-command-line-ae3d0f28665d?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae3d0f28665d</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[blender]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 07:37:34 GMT</pubDate>
            <atom:updated>2023-09-26T08:23:24.987Z</atom:updated>
            <content:encoded><![CDATA[<h4>When your scene becomes more complex the rendering becomes more time consuming. Then you want to have more control over where and when you render your shots, you probably also want to render on another more powerful machine. In those cases you want to know how to run Blender from the command-line terminal and in the background. Lets see how easy you can achieve this.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-8cOmXvyF1jmublM7OILQ.png" /></figure><h4>Starting Blender from the console</h4><p>In order to use Blender from the console, you need to know where to find the executable. In my case, on a Mac, the executable is found in the Applications folder:</p><p>/Applications/Blender.app/Contents/MacOS/Blender</p><p>So if I want to open a file in Blender, I could do this:</p><p>/Applications/Blender.app/Contents/MacOS/Blender your_blender_file.blend</p><p>This would open the file your_blender_file.blend in the Blender application.</p><h4>Executing Blender in the background</h4><p>Now if I want to run your Blender file in the background, meaning you do not want see the graphical user interface, I can type:</p><p>Blender -b your_blender_file.blend</p><p>Here the command Blender is an abbreviation for /Applications/Blender.app/Contents/MacOS/Blender, which works for my case on a Mac. Now, this command simply opens Blender and quits it right away, because it runs in the background with nothing to do.</p><h4>Rendering an image from the terminal</h4><p>Now lets say we want to render the third frame of the animation in our Blender file. We could do the following:</p><p>Blender -b your_blender_file.blend -o // -f 3</p><p>This command renders the third frame (-f 3) in the background (-b) and outputs it to the location of the blend file (-o //). Here the double slash // revers to the path relative to the blender file. If you run this, the frame will be rendered, output is written to the path of the blender file, and Blender quits.</p><h4>Arguments are executed in order given</h4><p>Now it is important to know that argements are executed in the order given. For example this command:</p><p>Blender -b your_blender_file.blend -f 10 -o //</p><p>First renders the tenth frame and then the output is set to //. But because the -f comes before the -o, the output of the render is writen to the standard output (or the output location set in the Output Properties in the blend file).</p><p>On the other hand, this command does what you expect and probably want:</p><p>Blender -b your_blender_file.blend -o // -f 10</p><p>Here the output is first specified and then the tenth frame is rendered and written to //.</p><h4>Rendering an animation</h4><p>You can render an animation in a blender file using -a and set start and end frames to render with -s and -e. For example:</p><p>Blender -b your_animation.blend -s 5 -e 35 -a</p><p>This wil render the animation, in the background, from frame 5 to 35 and output the images to the output specified in the blend file.</p><h4>Figuring out more commands</h4><p>If you are looking for other command, for example, specifying which engine to use for rendering, try this command to learn more:</p><p>Blender --help</p><p>Also you can read more on rendering using the terminal at the official <a href="https://docs.blender.org/manual/en/latest/advanced/command_line/render.html">Blender documentation</a>.</p><p><em>Note: this blog is written using Blender version 3.6</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae3d0f28665d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blender, Python and Your Custom Data Part 3: using custom attributes in your shaders]]></title>
            <link>https://medium.com/@bldevries/blender-python-and-your-custom-data-part-3-using-custom-attributes-in-your-shaders-3258b4cc7f38?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3258b4cc7f38</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[blender]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 07:09:46 GMT</pubDate>
            <atom:updated>2023-07-19T07:09:46.330Z</atom:updated>
            <content:encoded><![CDATA[<p>In this third and last part of our blog series we will use our custom attributes in a shader to give the particle shower some color and shine. The <a href="https://medium.com/@bldevries/scientific-data-in-blender-part-1-loading-data-into-attributes-61477414aae6">first part</a> of this serie showed how to use the Python API to read data from a file into attributes in Blender. <a href="https://medium.com/@bldevries/scientific-data-in-blender-part-1-loading-data-into-attributes-61477414aae6">The data we used</a> is from the CERN particle collider, more specifically a particle shower from a calorimeter. Next we used <em>Geometry Nodes</em> in the <a href="https://medium.com/@bldevries/blender-python-and-your-custom-data-part-2-using-custom-attributes-in-geometry-nodes-b37db6984987">second part</a> to alter and change the geometry using our own attributes. Now it is time to shade the particle shower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8lsiuW8C0sqtYZax2-yhA.jpeg" /><figcaption>Figure 1: visualisation of five showers from a particle collider at CERN.</figcaption></figure><p>We start by going to the <em>Shading workspace</em> and we go to the <em>Material Properties</em> tab in the <em>Properties Editor</em> on the right. We click on the +-sign to add a material slot. We link the material slot to the <em>Object</em> (instead of the geometry) using the menu encircled in red in Fig. 2. Now we click the <em>New</em> button to make a new material. We will keep the shader simple and in the <em>Shader Editor</em> we delete the <em>Principled BSDF</em> and instead we add an <a href="https://docs.blender.org/manual/en/latest/render/shader_nodes/shader/emission.html"><em>Emission</em></a> shader (see Fig. 2).</p><p>Now we create an <a href="https://docs.blender.org/manual/en/latest/render/shader_nodes/input/attribute.html"><em>Attribute Node</em></a> and link the color socket to the color socket of the <em>Emission</em> shader. We only need to fill in the name of the Attribute we want to use into the <em>Name</em> field in the node. For some reason Blender does not give a selection menu for this and you need to copy and paste the name of the attribute. One way to find the attribute name is by going to the <em>Object Data Properties</em> tab in the <em>Properties Editor</em> and go to the tab <em>Attributes</em>. Here is a list of custom attributes and we see the <em>myAttributeFloat</em> attribute we made in the <a href="https://medium.com/@bldevries/scientific-data-in-blender-part-1-loading-data-into-attributes-61477414aae6">first blog</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grBY0tmpglAUNKN5Iw4KJA.png" /><figcaption>Figure 2: adding a new material and using our custom attributes to control the Emission shader.</figcaption></figure><p>Now you have the shader shown in Fig. 2 and you see already some grey scaled coloring of the particle shower. Now we want to bring some color to the data. For this we add a <a href="https://docs.blender.org/manual/en/latest/compositing/types/vector/map_range.html"><em>Map Range</em> <em>Node</em></a> to scale the attribute data to a range of zero to one (see Fig. 3). By inspecting the data I know the data in the<em> myAttributeFloat</em> attribute varies roughly between 0 and 13. So we use those values for the <em>From Min</em> and the <em>From Max</em>.</p><p>Lastly, we will add some color by adding a <a href="https://docs.blender.org/manual/en/latest/compositing/types/converter/color_ramp.html"><em>ColorRamp Node</em></a> (see Fig. 3). We select red and blue and we see that the cubes in the shower with low energy values color blue and those with higher energy, color red (see Fig. 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nhr0KGu9a6rVkfJ66hnLVg.png" /><figcaption>Figure 3: adding some color and contrast to the material from Fig. 2.</figcaption></figure><p>This is the basics when using custom attributes in your shaders. I used multiple of the showers from different data sources to make Fig. 1 and the animation in Fig. 4. Pretty nice! I hope this helps and see you next time.</p><p>Cheers,<br>Ben</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5Nck8qKN4IS1Z3Vp3qB8w.gif" /><figcaption>Figure 4: animated version of multiple showers</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3258b4cc7f38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blender Workshop OpenXR 2023]]></title>
            <link>https://medium.com/@bldevries/blender-workshop-openxr-2023-ab29c839c0c5?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab29c839c0c5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[extended-reality]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[blender]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 08:35:02 GMT</pubDate>
            <atom:updated>2023-07-04T08:35:36.497Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there, this blog is to compile all information and files for the workshop I give at the OpenXR 2023 meeting in Delft on the 5th of July.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06M1pglDuW1-w0kxUL186w.jpeg" /></figure><p>The files to follow along can be found here:</p><p><a href="https://surfdrive.surf.nl/files/index.php/s/myryMvhSfJ0fGfz">SURFdrive - A service by SURF</a></p><p>What I demonstrate at the event can also found in these two blogs:</p><ul><li><a href="https://medium.com/@bldevries/scientific-data-in-blender-part-1-loading-data-into-attributes-61477414aae6">Blender, Python and Your Custom Data Part 1: loading data into attributes</a></li><li><a href="https://medium.com/@bldevries/blender-python-and-your-custom-data-part-2-using-custom-attributes-in-geometry-nodes-b37db6984987">Blender, Python and Your Custom Data Part 2: using custom attributes in Geometry Nodes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab29c839c0c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blender, Python and Your Custom Data Part 2: using custom attributes in Geometry Nodes]]></title>
            <link>https://medium.com/@bldevries/blender-python-and-your-custom-data-part-2-using-custom-attributes-in-geometry-nodes-b37db6984987?source=rss-dce4f76788e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b37db6984987</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[3d-modeling]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[blender]]></category>
            <dc:creator><![CDATA[Ben de Vries]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 13:59:14 GMT</pubDate>
            <atom:updated>2023-06-27T09:38:24.811Z</atom:updated>
            <content:encoded><![CDATA[<p>In this second part of our three-part blog series, we will continue using scientific data to make a 3D visualization in Blender 3.5.0. In the first blog of this series, we loaded data into Blender attributes using the Python API. This second part will show you how to use your custom attributes within Geometry Nodes to create, delete and alter geometry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSt6952v_Nv9vsqO_kFn0g.jpeg" /><figcaption>Figure 1: the scene we will make in this three part blog series</figcaption></figure><h4><strong>Recap of what we did in the first blog</strong></h4><p>In the <a href="https://medium.com/@bldevries/scientific-data-in-blender-part-1-loading-data-into-attributes-61477414aae6">previous blog</a> we used particle collision data from the CERN accelerator, and we ended up with many vertices in a cube-like arrangement (see Fig. 3). Furthermore, every vertex has a float value associated with it through the attribute myAttributeFloat (see the spreadsheet in Fig. 3). This value represents the energy recorded by the detector belonging to the vertex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbLQh6IgyhmOoBLsSH3yNg.gif" /><figcaption>Figure 2: animated version of Fig. 1</figcaption></figure><h4><strong>If you are totally new to Geometry Nodes</strong></h4><p>This blog is not meant as an introduction to Geometry Nodes, but is to show an example of how you can use Geometry Nodes to manipulate geometry and your own custom data. If you are new to Geometry Nodes have a look at the <a href="https://studio.blender.org/training/geometry-nodes-from-scratch/">first free video of this course</a> from Blender Studio. That will give you enough background for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rdfdkCu3lvTY9al4V4CAQ.png" /><figcaption>Figure 3: our starting point for this blog. To see how we got here, please read <a href="https://medium.com/@bldevries/scientific-data-in-blender-part-1-loading-data-into-attributes-61477414aae6">part 1</a> in this blog series. Also on the left you see the very useful Spreadsheet editor included in the Geometry Nodes workspace.</figcaption></figure><h4><strong>Three step plan towards the animation in Figure 2</strong></h4><p>In three steps we will create the basis for the animation in Fig. 2.</p><ol><li>We remove detectors/vertices that did not detect anything.</li><li>We replace the detectors/vertices with a cube geometry. We do this so that we can shade them in the next blog.</li><li>We want to be able to make detectors (dis)appear so that we can make the animation as in Fig. 2.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2JhQ2wRBtveJ87Vncq2EA.png" /><figcaption>Figure 4: first version of the Geometry Node modifier we are building. Here we use the attribute ‘myAttributeFloat’ to remove detectors that did not measure any energy from particles.</figcaption></figure><h4><strong>Step 1: removing non-detections.</strong></h4><p>Many vertices seen in Fig. 3 represent detectors that detected no energy from a particle. We want to remove those vertices that have an myAttributeFloat value lower than a certain threshold. We can remove geometry using the <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/geometry/operations/delete_geometry.html"><em>Delete Geometry</em></a> node (see Fig. 4). In this case we want to remove vertices, so we set it to delete <em>Points</em>. We now need to feed in a list of Booleans into the <em>Selection</em> socket, which determines what gets deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYUz3BTyjDWhSHW8-H1w-w.png" /><figcaption>Figure 5: the result from the Geometry Node seen in Fig. 4.</figcaption></figure><p>To get access to the attribute myAttributeFloat we use a <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/geometry/read/named_attribute.html"><em>Named Attribute</em></a> node and fill in the attribute name (see Fig. 4). Next we want to compare the myAttributeFloat value to a threshold and for this we use a <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/utilities/math/compare.html"><em>Compare</em></a> node and set it to <em>Less Than</em> and feed the attribute into socket A and set socket B to a threshold value of 0.1 (see Fig. 4). If we now connect the <em>Delete Geometry</em> node to the <em>Group Output</em> node we see the result as in Fig. 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_njYL3nwXTpyT-1Et-ErA.png" /><figcaption>Figure 6: second version of the Geometry node we are building. We now make instances of cubes from the vertices we had.</figcaption></figure><h4><strong>Step 2: replace vertices with cubes.</strong></h4><p>To be able to shade every detector, we generate a geometry, in this case a cube, at the location of every vertex/detector. We do this by creating an instance of a cube at every vertex using the <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/instances/instance_on_points.html#index-0"><em>Instance on Points</em></a> node (see Fig. 6). But because this node requires a point cloud as input we first convert our vertices into points using the <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/mesh/operations/mesh_to_points.html"><em>Mesh to Points</em></a> node (see Fig. 6). We now add a <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/mesh/primitives/cube.html"><em>Cube</em></a> node which we connect to the <em>Instance</em> socket. The result now looks like that shown in Fig. 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBLWDN9c8ggdaoelmGmKng.png" /><figcaption>Figure 7: here is the result from the Geometry Node in Fig. 6.</figcaption></figure><h4><strong>Step 3: make detectors appear and disappear.</strong></h4><p>To make the animation seen in Fig. 2, we also need to make the cubes appear and disappear. We will make them appear from the center outwards (in the radial direction). Thus, we need to be able to cut away detectors located at a radius larger than a certain threshold. And instead of hardcoding this threshold, we will make a new Geometry Node input for the threshold, which will make it possible to animate the threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cb76SMCsFPZvJJLSK_iKkA.png" /><figcaption>Figure 8: version three of the Geometry Node we are making. We can now also remove detectors at locations on the x axis larger and smaller than a certain threshold.</figcaption></figure><p>We can access the position of the detectors by adding a <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/geometry/read/position.html"><em>Position</em></a> node (see Fig. 8). We use the length of the points using the <a href="https://docs.blender.org/manual/en/latest/render/shader_nodes/converter/vector_math.html"><em>Vector Math</em></a> node and set it to <em>Length</em>. We will feed it into a <em>Compare</em> node (set to Greater than or Equal) which will be fed into a new <em>Delete Geometry</em> node together with the threshold (See Fig. 8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyVLcaTq5eIA-URwK1uDkw.png" /><figcaption>Figure 9: result from the Geometry Node in Fig. 8.</figcaption></figure><p>We now need to implement the threshold that determines which detectors are removed. We will not hard code this threshold like we did for the other <em>Compare</em> and <em>Delete Geometry</em> nodes. We will make a new <a href="https://docs.blender.org/manual/en/latest/interface/controls/nodes/groups.html"><em>Group Input</em></a> node instead and we will use the socket that has no name. If we connect the unnamed socket to the B socket of the <em>Compare </em>node, we will see the unnamed socket is given a default name (for example B).</p><p>The new input also shows up in the <em>Modifier Properties</em> tab in the <em>Properties editor,</em> at the right side of the Blender application (see Fig. 8). You can also press the “n” key in the <em>Geometry Node Editor</em> window to open the <em>Sidebar</em> (or go to the View tab and tick the Sidebar option) and then navigate to the <em>Group</em> tab in the <em>Sidebar</em> to see the list of inputs and outputs of this Geometry Node modifier (also see Fig. 8). Here you will see (and have the possibility to rename) the new input we just created. I named it “Cutoff for animation”. You can see an example result in Fig. 9.</p><p>In the next blog we will use the fact that you can animate the inputs of modifiers. We can click the small dot next to the value of “Cutoff for animation” in the <em>Modifier Properties</em> tab to start animating the threshold. For now, you can play with the value of “Cutoff for animation” to see what it looks like.</p><h4>A last addition to the Geometry Node we made</h4><p>In the next blog we want to give all the detectors/cubes we just made a different color depending on the value of the myAttributeFloat attribute. But now all the cubes are an instance of one and the same cube. We need to make every instance a real geometry and we do this using the <a href="https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/instances/realize_instances.html"><em>Realize Instances</em></a> node (see Fig. 10). Now this does not change how the scene looks, but it is essential for the shading we do in the next blog of this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*8ACpDzbHqPBqrdQv0y-MhQ.png" /><figcaption>Figure 10: we use Realize Instances to turn all the cube instances into real geometry data.</figcaption></figure><h4><strong>Final Thoughts</strong></h4><p>This has turned out to be a longer blog than I thought. It takes some work to explain all steps involved. I hope this gives you an idea of what you can do with attributes and Geometry Nodes. What I did here only touches the surface of what is possible. In the third blog of this series we will shade the geometry we just made and we will see how we can use attributes in the shading. See you then.</p><p>Cheers,<br>Ben</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b37db6984987" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>