<?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 Afjal Chowdhury on Medium]]></title>
        <description><![CDATA[Stories by Afjal Chowdhury on Medium]]></description>
        <link>https://medium.com/@afjal.nc?source=rss-c53bb8cc6501------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r_zIt0rgBg-_NvdAEyaMUw.png</url>
            <title>Stories by Afjal Chowdhury on Medium</title>
            <link>https://medium.com/@afjal.nc?source=rss-c53bb8cc6501------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:38:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afjal.nc/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[Using RandSVD and piDMD to optimise Dynamic Mode Decomposition]]></title>
            <link>https://medium.com/data-science-collective/using-randsvd-and-pidmd-to-optimise-dynamic-mode-decomposition-9f345f7865e1?source=rss-c53bb8cc6501------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f345f7865e1</guid>
            <category><![CDATA[dynamical-systems]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[Afjal Chowdhury]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 03:18:39 GMT</pubDate>
            <atom:updated>2025-12-16T21:26:18.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Dynamic Mode Decomposition (DMD) is a data driven technique used to analyse dynamical systems, where matrix decompositions are employed to discover a matrix, <strong>A</strong>,<strong> </strong>that advances the state of a system forwards in time. I detail the derivation and intuition behind DMD in a separate post.</p><p><a href="https://medium.com/data-science-collective/analysing-dynamical-systems-with-dynamic-mode-decomposition-756a95e3a296">Analysing Dynamical Systems with Dynamic Mode Decomposition</a></p><p>In this post, I explore two distinct ways to optimise DMD, by reducing computational complexity and enforcing physics equations for accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ao-XULt8pFzfE2NQ_uICHA.png" /><figcaption><strong>Fig 1.</strong> AP = Q; DMD involves finding a matrix A that is able to advance ’old’ data into ‘new’</figcaption></figure><p>Above is the main idea behind dynamic mode decomposition; calculating a matrix <strong>A </strong>that sends <strong>P</strong> (old data) directly to <strong>Q</strong> (updated version of <strong>P</strong>). <strong>A</strong>, derived from this data, encodes useful information about a dynamical system. In practice however, <strong>A </strong>doesn’t always exist, namely when the problem is <em>over constrained</em>. This is apparent when <strong>P </strong>and <strong>Q </strong>are very long snapshots, which contain a very detailed log about how a system is moving. Intuitively, <strong>A</strong>, which might have 50x50 entries, wouldn’t have enough information to represent ~10,000 developments in a system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1yMt3N9J_Lt9Tq_Q.png" /><figcaption>Minimisation Problem to find <strong>A</strong></figcaption></figure><p>Instead, A is the solution to this minimisation/ least squares problem. Here, <strong><em>F </em></strong>denotes the <a href="https://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm">Frobenius norm</a>, which is a measure of the size of a matrix. Essentially this finds the matrix <strong>A </strong>such that <strong>AP </strong>is as close as possible to <strong>Q</strong>, where “closeness” is the size of the error between <strong>AP</strong> and <strong>Q</strong>. This formulation is very common in optimisation problems, and is synonymous to “<strong>AP</strong> ≈ <strong>Q</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*GtUutbivTNST8qk3.png" /><figcaption>Analytical solution to the Minimisation Problem.</figcaption></figure><p>This problem has an analytical solution, which is in terms of the SVD (singular value decomposition) of <strong>P</strong>. <em>Note: Analytical here means that it is proven to be the optimal solution to the minimisation, see (Eckhart 1936). This is also the analytical solution for when the L2 and spectral matrix norms are used.</em></p><h3>Procrustes Problem</h3><p>When running DMD in practice, the analytical/optimal solution <strong>A</strong> might take a lot of computational resources to find. This is especially frustrating in cases where <strong>P </strong>and <strong>Q </strong>are noisy, where having a fully precise, expensive solution is just as good as an approximate solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*swpcbIWnA03nvRHf.png" /><figcaption><strong>A </strong>is any matrix vs <strong>A</strong> is a special type of matrix</figcaption></figure><p>We can instead enforce A to lie in a manifold (special set) of computationally “convenient” matrices. The optimisation techniques discussed rely on this crucial concept, called <strong>Manifold Constraint</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*gDNKOpHT7JQKg2ow.jpeg" /><figcaption>Theseus and Procrustes on Procrustes’ Bed (<a href="https://www.greecehighdefinition.com/blog/the-myth-of-procrustes-bed-the-absurdity-of-equality">source</a>)</figcaption></figure><p>Problems under this kind of constraint are called <strong>Procrustes Problems</strong>, which is derived from a Greek myth where people are stretched or cut to fit the dimensions of a bed. In this case, a manifold constraint is being enforced on Theseus.</p><h3>Randomised SVD (RandSVD)</h3><p>A very common manifold constraint for optimisation is enforcing <strong>low rank</strong>. This quantifies the idea of a matrix being “less detailed”, and allows large matrices to be stored and applied efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_-dLHeVNMP0zedbv.png" /></figure><p>One way to derive a low rank A is to use a rank k approximation of <strong>P</strong>, that then limits rank(<strong>A</strong>) ≤ k also. This can be done by using <strong>truncated SVD</strong>, where the traditional SVD of <strong>P </strong>is calculated, then all but the first k rows/columns of the decomposed matrices are discarded to grant a low rank approximation of <strong>P</strong>. This approximation is proven be the optimal solution to the minimisation problem on rank k matrices <em>(Eckhart 1936)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*3Ef2NrnLXjOAxTuZSCidLA.png" /><figcaption>Thin matrices approximate <strong>X</strong> as <strong>X-k</strong> quite well, <strong>k</strong> = 3</figcaption></figure><p>Storing <strong>X-k</strong> is clearly cheaper than storing <strong>X</strong>, however finding <strong>X-k</strong> still involves performing a singular value decomposition; finding the truncated SVD has the same computational cost as the traditional SVD. Instead, the RandSVD algorithm calculates these thin truncations of the SVD directly, and probabilistically ie. the truncated SVD is approximated.</p><p>Assuming that the system does indeed have low-rank structure (so a low rank approximation can be made), the columns of <strong>P</strong> must have a low dimensional span (colspace of <strong>P</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*OyhRXvozlMl6mXKe.png" /></figure><p>One can randomly sample elements of <strong>P</strong>s colspace (called sketching) and apply the Gram-Schmidt procedure to find a k-sized “approximate basis” of <strong>P</strong>s colspace.</p><pre>1: Draw random sketching matrix Ω ∈ R^{n×k}<br><br>2: Y ← P · Ω<br>   // Y is a random sample/sketch of the column space<br><br>3: P&#39; ← Gram-Schmidt(Y)</pre><p>This new <strong>P’</strong> has similar properties to <strong>P </strong>while being much smaller. In particular, by proceeding to take the SVD of <strong>P’</strong>, the approximate truncated SVD can be found almost directly [see (Halko 2010) for full derivation], and very efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*6TcyZAkRQs4Gv4qx.png" /><figcaption>for e.g. <strong>n</strong> masses, <strong>m </strong>timesteps, rank-<strong>k </strong>approximation</figcaption></figure><p>This reduces the computational complexity with respect to the number of time snapshots <strong><em>m </em></strong>from quadratic to linear, which typically dominates the cost of DMD.</p><h3>Physics Informed DMD (piDMD)</h3><p>Since <strong>A</strong> encodes information on how a system advances, if we know information about the physics of a system, it makes sense that <strong>A</strong> might also have certain constraints. We can encode this again using a manifold constrain, but in this case, the constraints are more creative.</p><p>We have already discussed low-rank constraints that enforce k modes of oscillation. Peter Baddoo’s paper <em>“Physics-informed dynamic mode decomposition (piDMD)”</em> details many more manifold constraints that can be applied to enforce other physical properties onto <strong>A</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*vmEMYgGoO-lXqfHazKf1BQ.png" /><figcaption><em>Physics-informed dynamic mode decomposition </em>(Baddoo 2021)</figcaption></figure><p>For example, in a long spring mass chain like the <strong>FPUT Problem</strong>, locality can be enforced by making sure that <strong>A</strong> is tridiagonal. This ensures that the forces acting on a mass are only from neighbouring masses. This is instead of every mass in the chain, which an unconstrained DMD might incorrectly find. Certainly, ensuring that the laws of physics in a system are conserved results in a more realistic operator <strong>A</strong>, granting more accurate inferences downstream. This even allows inferences to be made on noisy data, since noise in this data often contradicts physical laws; enforcing these laws “undoes” the noise to an extent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*fcA5_Pa0E0BXs1MP.png" /><figcaption>Spring Mass system, which has “locality”</figcaption></figure><p>I recommend reading Baddoo’s paper for further examples.</p><h4>Conclusion</h4><p>These techniques can be used when implementing DMD to make it more efficient and robust. This post is meant to provide a more scientific computational perspective on DMD, giving the intuition behind these very power optimisations. I hope to somewhat demystify optimisation in general, to show that optimising a problem for a computer requires as much attention as constructing the problem in the first place.</p><p>This is an extension of content I wanted to include in my end of year project I did on DMD for the FPUT Dynamical System for my degree, but didn’t have space for on my poster! I’m very happy to say that that project was awarded as the best in the year, and all of this work on numerical linear algebra has inspired a lot of the projects that I am doing at the moment, which I will hopefully post about soon.</p><p><em>By Afjal Chowdhury</em></p><h4>Bibliography</h4><p>Eckart, C. and Young, G. (1936). <strong><em>The approximation of one matrix by another of lower rank.</em></strong> <em>Psychometrika</em>, 1(3), pp.211–218. doi:https://doi.org/10.1007/bf02288367</p><p>Halko, N., Martinsson, P.-G. and Tropp, J.A. (2010). <strong><em>Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix</em></strong><em> decompositions</em>. arXiv.org. doi:https://doi.org/10.48550/arXiv.0909.4061</p><p>Murray, R., Demmel, J., Mahoney, M.W., et al. (2023). <strong><em>Randomized Numerical Linear Algebra : A Perspective on the Field With an Eye to Software.</em></strong> arXiv.org. <a href="https://arxiv.org/abs/2302.11474.">https://arxiv.org/abs/2302.11474</a></p><p>Baddoo, P.J., Herrmann, B., McKeon, B.J., Nathan, K.J. and Brunton, S.L. (2021). <strong><em>Physics-informed dynamic mode decomposition (piDMD)</em></strong>. arXiv.org. Available at: <a href="https://arxiv.org/abs/2112.04307.">https://arxiv.org/abs/2112.04307</a></p><p>E. Fermi, J. R. Pasta, S. Ulam, and M. Tsingou (1955) <strong><em>Studies of Nonlinear Problems, I</em></strong> Los Alamos Report LA-1940</p><p>Unless stated otherwise, all images by author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f345f7865e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/using-randsvd-and-pidmd-to-optimise-dynamic-mode-decomposition-9f345f7865e1">Using RandSVD and piDMD to optimise Dynamic Mode Decomposition</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maths’ Mystery Integrator]]></title>
            <link>https://medium.com/data-science/maths-mystery-integrator-4a4f51a5ee93?source=rss-c53bb8cc6501------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a4f51a5ee93</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Afjal Chowdhury]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 13:30:14 GMT</pubDate>
            <atom:updated>2025-08-17T13:30:14.337Z</atom:updated>
            <content:encoded><![CDATA[<p>On November 13th 2013, Laila Podlesny consulted the Maths StackExchange for help with a particularly difficult integral:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*x0fIdtcICwj3tfqPXVJqSg.png" /></figure><p>Whether you’re a mathematician or not, it probably wouldn’t come as a surprise that the solution to this spans several pages. The actual solution involves <em>a creative transformation to an 8th degree polynomial, applying Cauchy’s residue theorem over singularities, using imaginary numbers to create a contour</em> —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*nDYYWWnd9NYyzw1lw99IxQ.png" /></figure><p>— 2 hours later, StackExchange user “Cleo” posts the exact solution to the integral. The only caveat was that her solution was only 10 characters long, with the only context she provided being an ominous link to the Wikipedia article about the golden ratio, almost taunting the other users on the platform who took another 2 years to come to a complete the proof of the result. Cleo then went on to solve 38 more similar highly complex integrals, all with the same abrupt style, in the same timely fashion.</p><p>Naturally, the Math Stack Exchange community descended into chaos. Threads exploded with speculation, debates raged over whether Cleo was a savant, a troll, or a collective hallucination, and users meticulously dissected every one of her posts in a desperate attempt to unmask this mystery integrator. Some of the potential suspects for who Cleo was included Fields Medalists like Terence Tao and Maryam Mirzakhani, the famously reclusive Grigori Perelman, and even Stephen Hawking.</p><p>But as the speculation grew, so did a more fundamental question — was Cleo’s approach to mathematics even legitimate? One of the biggest discussions that emerged from this saga was whether unjustified, proofless solutions were useful. The commonly accepted view of most mathematicians (and probably every maths teacher) is that they aren’t- working from the philosophy that a result without justification is meaningless, as mathematics is built on rigorous reasoning rather than blind acceptance.</p><p><a href="https://math.meta.stackexchange.com/questions/11723/are-answers-that-have-no-explanations-useful">On another post</a>, Ukrainian mathematician Vladimir Reshetnikov raised compelling arguments to the contrary. He pointed out that many users, particularly applied scientists like chemists and physicists, often just need a correct result rather than a detailed derivation. He also argued that knowing the form of a potential answer is useful to give a direction towards eventually deriving a solution.</p><p>Amidst this rife, Cleo put out a statement that she has “a medical condition that makes it very difficult for [her] to engage in conversations, or post long answers”, and that was that. Cleo disappeared without a trace. Over time, people accepted that Cleo would forever remain out of reach, and people instead celebrated her prowess where she later received recognition on the subreddit /r/math as the “Master of Integration”. Cleo would be forever remembered as one of math’s greatest unsolved mysteries.</p><p>For over a decade, Cleo’s identity remained one of the greatest unsolved mysteries in the online mathematics community. It wasn’t until January 2025, 11 years since Cleo’s last activity, that Youtuber Joe McCann released a video investigating Cleo’s identity.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7gQ9DnSYsXg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7gQ9DnSYsXg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7gQ9DnSYsXg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/42405162b1a874ac0d79127b4ec4f0cb/href">https://medium.com/media/42405162b1a874ac0d79127b4ec4f0cb/href</a></iframe><p>This followed recent investigations on Reddit where, perhaps quite dubiously, a user tried to access Cleo’s recovery email only to find that it was linked to other accounts that had been suspiciously active on the same threads. Further investigation led to the shocking discovery that Cleo was none other than Vladimir Reshetnikov!</p><p>One might wonder why Reshetnikov went to such extreme lengths to orchestrate such an elaborate scheme instead of posting under his own account- according to him, the answer was simple. Engagement.</p><p>As a hobby, Reshetnikov solves complex integrals that he creates through a process he calls “integral reverse-engineering”. This process is where you subtly modify an existing integral, to then carefully track the corresponding change in the integral’s value. The problem with this is that integrals are notoriously unpredictable- a slight adjustment can completely alter the problem, warranting a completely different method to solve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/0*ncgl5D3WlJ7HPssE" /><figcaption>Image from r/mathmemes on <a href="https://www.reddit.com/r/mathmemes/comments/m7bnmf/1_scary/">Reddit</a></figcaption></figure><p>Each new integral was plugged into Mathematica, which is a solving program that essentially sifts through all known integration techniques, until he found an integral the computer couldn’t solve. He would then work to solve these integrals, with the exact solution in mind too, and when he hit a wall, he turned to Math StackExchange for help. The problem was that very few people were interested in helping, and he was often met with condescending responses questioning the need to solve these random, complicated integrals versus using approximations.</p><p>It is then that Reshetnikov had the idea to use Cleo as a stunt, to simply just state the exact solutions to integrals that he posts on different accounts, sparking far more curiosity than any typical question ever could. Cleo’s cryptic responses rallied mathematicians, eager to prove or disprove the result.</p><p>In fact, all 39 of Cleo’s answers were eventually proven by stack exchange users. So, in spite of all of the controversy regarding Cleo’s antics, Reshetnikov proved many of the up-tight mathematicians on the stack exchange wrong. He (somewhat unconventionally) demonstrated the usefulness of incomplete proof- something that he had been arguing far before Cleo’s unmasking.</p><p>Reshetnikov closing remarks in his interview with Joe McCann were that “I hope it created more fun and entertainment than hurt feelings and misgivings… I sincerely apologise if I hurt anyone.”. It was clear that Reshetnikov was fearful about coming out as Cleo, and he thought it easier to brush Cleo under the rug instead of unspinning himself from his web of fake accounts and internet fame. He did also mention that he forgot the password to the Cleo account, so perhaps that also partly explains his relucatance.</p><p>Despite his fear, Reshetnikov ultimately drove innovation in the field, encouraging unconventional solutions and perspectives that mirrored his unconventional ploy.</p><blockquote>“Remember, you are not locked into a single axiom system. You may invent your own, whenever you wish — just use your intuition and imagination.” — Cleo</blockquote><p>Cleo’s story sheds light on the fascinating dynamics of online communities, not only in maths. People are led by curiosity, competition, and the allure of the unknown. The mystery of Cleo captivated the Math Stack Exchange community for over a decade, not only because of the intrigue surrounding her identity, but because it challenged users to think differently, to push boundaries, and to question assumptions.</p><p>In the end, Cleo’s legacy is one of inspiration. It reminds us that mathematics is not just about finding answers but about the journey of discovery, and that the traditional framework of rigour and completeness is only second to the pursuit of understanding. And while the whole mystery of Cleo has been solved, and the curiosity she sparked will continue to resonate in the mathematical community for years to come.</p><blockquote>“The idea of Cleo is what matters, not whether she exists… like Jesus.” — @MaxMynter</blockquote><p>by Afjal Chowdhury</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a4f51a5ee93" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/maths-mystery-integrator-4a4f51a5ee93">Maths’ Mystery Integrator</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysing Dynamical Systems with Dynamic Mode Decomposition]]></title>
            <link>https://medium.com/data-science-collective/analysing-dynamical-systems-with-dynamic-mode-decomposition-756a95e3a296?source=rss-c53bb8cc6501------2</link>
            <guid isPermaLink="false">https://medium.com/p/756a95e3a296</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[dynamics]]></category>
            <dc:creator><![CDATA[Afjal Chowdhury]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 01:46:37 GMT</pubDate>
            <atom:updated>2025-12-16T03:30:28.774Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I outline the data-driven DMD algorithm, and apply it to a simple dynamical system: a chain of spring-masses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDBo3ZRVf3OfjwTfRdmdyw.png" /></figure><p>When analysing complex dynamical systems, there are various methods that can be used to quantify behaviour. <strong>Analytical methods</strong> focus on the mathematical structure of the system, typically working directly with the differential equations that govern its evolution. In contrast, <strong>data-driven</strong> <strong>methods </strong>can extract this information from observed data, without the need to know the underlying mechanics of a system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ICK5KrI6NcqZJA3SrE3RpA.gif" /><figcaption><strong>Fig 1.</strong> Example simulation</figcaption></figure><p>In this case, while I know the equations that govern my system, I simulate the system instead since it is too complex to analyse analytically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OLLzMZVKhCwFXs6C.png" /></figure><p>By first decoupling this system of N 2nd order ODEs into 2N 1st order ODEs, we can simulate this system efficiently using <a href="https://docs.sciml.ai/DiffEqDocs/stable/solvers/ode_solve/">Julia’s ODE solvers</a>. Initially, the system is already slightly perturbed (i.e. not at zero displacement), and after each timestep, the system shifts and the state of the system is concatenated into an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*VZZj36MFXk09QvPApEDvsA.png" /><figcaption><strong>Fig 2.</strong> Heatmap of simulation, constructed by concatenating system state after every timestep (time on x-axis) to form an image where low/high displacements are represented by dark/light colouring. N = 10,000</figcaption></figure><h3>DMD Derivation</h3><p>This image forms large matrix, where each column (of pixel values) represents the state of the system after a certain amount of time, up to m timesteps. This data, known as the <strong>snapshot matrix</strong>, is what we will use to perform DMD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*peicbXBh_YEj697V.png" /></figure><p>The first step in DMD is to consider 2 submatrices of X, called P &amp; Q. You form these matrices by shaving off the last/first k columns of X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iov25WlTPPPmyFXp.png" /></figure><p>Note that the first column of Q is the first column of P advanced by k timesteps, and same with the 2nd, 3rd, etc… Now consider a transformation matrix, called A, that solves the equation AP = Q</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ao-XULt8pFzfE2NQ_uICHA.png" /><figcaption><strong>Fig 3. </strong>A advances matrix P (left) to Q, sending P ahead in time</figcaption></figure><p>The matrix A here encodes the transition between a column in P to its corresponding column in Q. Instinctively, A must represent come sort of advancement in the system. This intuition is correct, and in particular, A’s <em>spectrum </em>contains a lot of interesting information regarding the system.</p><p>Now, given the matrix P &amp; Q, we can solve for the matrix A. However, since P isn’t necessarily square, P doesn’t have a traditional inverse. We take a “generalised inverse”, called the Moore-Penrose pseudoinverse (denoted as dagger) to find A. This involves factorising P into 3 different matrices using an algorithm called Singular Value Decomposition (SVD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GtUutbivTNST8qk3.png" /></figure><p>Note that we already have matrix Q, from our simulation data X. Matrices V, Sigma and U can be found/approximated using various algorithms applied to matrix P, which we also have from our simulation. We therefore have all we need to transform our simulation data X into the time-shift operator A.</p><p>When actually running these simulations, finding A using this procedure is sometimes slow, and vulnerable to noise. In the post below, I detail different optimisations for DMD.</p><p><a href="https://medium.com/@afjal.nc/using-randsvd-and-pidmd-to-optimise-dynamic-mode-decomposition-9f345f7865e1">Using RandSVD and piDMD to optimise Dynamic Mode Decomposition</a></p><h3>Making inferences from DMD</h3><p>The primary advantage of using DMD over other techniques like Fourier analysis (using FFT) is that you can identify information beyond a simple frequency spectrum. Energy (which is conserved) is split between the different modes of oscillation in the system. Essentially, we can analyse the frequencies present at a given time to identify how the energy is allocated in the system. DMD allows identification of the modes, like in FFT, but also if the mode is gaining or losing energy at an instance.</p><p>To make the most effective use of DMD, the data is segmented into several chunks, where a new linear operator A can be calculated for each part. This is essential since this system is non-linear, so using only 1 chunk is a massive simplification. Instead, different linear approximations of the system are identified at each chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*6j09KL9cze0cW2KD8gIJYw.png" /><figcaption><strong>Fig 4.</strong> Example of segmented data for DMD</figcaption></figure><p>One can then find the spectrum of each operator A. In particular, the eigenvectors of A represent the structures within each system state that grow/shrink under an A, i.e. the periodic components of each complicated system state. We can use these components to reconstruct each state, to then make sense of what the eigenvalues of the system represents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7kjxQBhwW_w3E9nN.png" /><figcaption>The system state X is reconstructed as a sum over e.vectors. Application of A &lt;=&gt; multiplication by e.value, which when written in mod-arg form, can be easily interpreted to identify behaviour over time.</figcaption></figure><p>This is the linear approximation of the system at a specific time in the system’s progression. Looking specifically at the eigenvalues, the modulus of an eigenvalue represents its growth/decay, and its argument represents the frequency of which it oscillates (since e^ix is 2π periodic).</p><p>To aid interpretation, one can apply a logarithmic transformation on the eigenvalues such that the “information of interest” (i.e. the frequency and decay constants) is represented on the x-y axes, not as the modulus &amp; argument of a point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3aRTQyI2Gf_bX3Mfidv1A.png" /><figcaption><strong>Fig 5.1/5.2.</strong> Eigenvalues of DMD operators over time, using data from (Fig 2).</figcaption></figure><p><em>Note that growth/decay of a mode is characterised by its relation to the unit circle in </em><strong><em>fig 5.1</em></strong><em>, and to the imaginary line in </em><strong><em>fig 5.2</em></strong><em>.</em></p><p>One can identify clusters of red and blue points, which indicate that an energy is present and stable, since the mode is present throughout time. Clustering algorithms can be used to identify specific instances of mode stability/transitions of energy between modes.</p><h4>Conclusion</h4><p>In summary, DMD can be used to analyse complex systems using simulated/experimental data. DMD captures really interesting dynamics in systems like these, without any knowledge of the equations that govern them. This makes DMD particularly useful in fields like fluid mechanics, where extremely intricate systems can be simulated and processed to make efficient and insightful inference from inherently complex systems.</p><p><em>References:</em></p><p>All images created by author, see G<a href="https://github.com/afjal4/DMD-in-FPUT-Simulations">ithub </a>for more details.</p><p>Benettin, G.; Christodoulidi, H.; Ponno, A. (2013). <strong>The Fermi-Pasta-Ulam Problem and Its Underlying Integrable Dynamics.</strong> <em>Journal of Statistical Physics</em>. <strong>152</strong> (2): 195–212. <a href="https://en.wikipedia.org/wiki/Doi_(identifier)">doi</a>:<a href="https://doi.org/10.1007%2Fs10955-013-0760-6">10.1007/s10955–013–0760–6</a></p><p>Tu, J. H., Rowley, C. W., Luchtenburg, D. M., Brunton, S. L., &amp; Kutz, J. N. (2014). <strong>On dynamic mode decomposition: Theory and applications.</strong> <em>Journal of Computational Dynamics</em>, <em>1</em>(2), 391–421. <a href="https://doi.org/10.3934/jcd.2014.1.39">https://doi.org/10.3934/jcd.2014.1.39</a>1</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=756a95e3a296" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/analysing-dynamical-systems-with-dynamic-mode-decomposition-756a95e3a296">Analysing Dynamical Systems with Dynamic Mode Decomposition</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Sets Are So Useful in Programming]]></title>
            <link>https://medium.com/data-science/why-sets-are-so-useful-in-programming-b1157532f7e5?source=rss-c53bb8cc6501------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1157532f7e5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Afjal Chowdhury]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 18:36:32 GMT</pubDate>
            <atom:updated>2025-01-20T12:35:13.871Z</atom:updated>
            <content:encoded><![CDATA[<h4>And how you can use them to boost your code performance</h4><p>A <em>set </em>is a simple structure defined as a <em>collection of distinct elements</em>. Sets are most commonly seen in fields like mathematics or logic, but they’re also useful in programming for writing efficient code. In this article, I detail cases where sets outperform alternative data types like <em>lists</em>, and the underlying implementation of sets which makes them so useful to programmers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eBoxhveWkwuWSUeX" /><figcaption>Bolts that form a Set by <a href="https://unsplash.com/@robert2301?utm_source=medium&amp;utm_medium=referral">Robert Ruggiero</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A set is an example of a container; these are used to store several elements under one variable. When looking for a container datatype, lists (typically defined with square brackets [ ]) are the go-to choice, being used extensively in almost all programming languages. Sets bear a lot of similarity to lists, most notably as they are both <strong>dynamic</strong>, allowing their size to grow or shrink as needed. The only differences lie in that lists preserve order of elements and allow duplicates, whereas sets do neither, offering a unique advantage in certain scenarios. By knowing when to choose sets over lists, you can greatly enhance the performance of your programs and improve code readability.</p><p>In Python, sets can be declared using curly braces, or by using the set constructor.</p><pre>set_a = {1, 4, 9, 16}<br>set_b = set([1,2,3]) #coverting list to set<br>empty_set = set()</pre><h3>Sets do not contain duplicates</h3><p>A defining property of a set is that each element is distinct, or unique, so there are no repeated entries. A simple application of this could be to <strong>remove all duplicate entries</strong> in a list by converting the list into a set.</p><pre>#LIST Implementation O(n^2)<br>def remove_duplicate_entries(list input_list):<br>    output_list = []<br>    for element in input_list:<br>        if element in output_list: <br>             output_list.append(element)<br>    return output_list</pre><pre>#SET Implementation O(n)<br>def remove_duplicate_entries(list input_list):<br>    return list(set(input_list))</pre><p>Because a set is used here, the order of the list is not preserved. Use an implementation like the first one if order matters.</p><p>The next function <strong>identifies if a list contains any duplicates;</strong> the order of elements is not here important, only the <em>occurrence </em>of duplicates. The set implementation is much more desirable as operations on sets are typically much faster than on lists (this is explained in more detail later).</p><pre>#LIST Implementation<br>def has_duplicates(list input_list):<br>    unique_elements = []<br>    for element in input_list:<br>        if element in unique_elements: <br>             return True<br>        else:<br>             unique_elements.append(element)<br>    return False</pre><pre>#SET Implementation<br>def has_duplicates(list input_list): <br>    return len(input_list) != len(set(input_list))</pre><p><em>Note: In cases where a duplicate element appears early, the first implementation can outperform the second as it catches the duplicate early and returns False without checking every entry, whereas the second implementation always iterates through every element. A more optimal solution would involve a similar method to the first implementation but using a </em><strong><em>set </em></strong><em>as the unique_elements container.</em></p><pre>def has_duplicates(list input_list) -&gt; bool:<br>    unique_elements = set() #**modified here<br>    for element in input_list:<br>        if element in unique_elements: <br>             return True<br>        else:<br>             unique_elements.add(element)<br>    return False</pre><p>Even if these applications seem quite crude or simplistic, there are countless uses built upon the principle of “removing duplicates” that take some creativity to see. For example, <a href="https://leetcode.com/problems/check-if-the-sentence-is-pangram/">Leetcode 1832</a> ‘<em>Check if the Sentence is a Pangram</em>’- where you need to detects if all 26 letters have been used in an input sentence- can be elegantly solved using a set comprehension.</p><pre>def is_pangram(str sentence) -&gt; bool:<br>    present_letters = {letter for letter in sentence}<br>    return len(present_letters) == 26</pre><p>Without sets, this problem would need to utilise nested looping which is both harder to write, and less efficient with a complexity of O(n^2).</p><p>The key to identifying cases where sets are useful is by considering:</p><ul><li>If we <strong>only care about an occurrence</strong>, like in this problem if the sentence contained the word ‘eel’, we only care that the letter ‘e’ occurred, not that it occurred twice so we can discard the second and any future ‘e’s.</li><li>Building on this principal, in cases where a list is <strong>very large</strong>, it may be desirable to remove duplicate elements to continue processing on a much smaller list.</li><li>If <strong>we don’t care about the order</strong> of elements. In cases where maintaining order is important, like in a priority queue, lists should instead be used.</li></ul><h3>Hash maps and lack of order</h3><p>Taking a step back, it might seem that easy duplicate removal is the only benefit of using sets. We previously discussed how sets have no order; arrays have indexed element which could simply ignored and treated like a set. It appears that arrays can do the same job as a set, if not more.</p><p>However, this simplification enforced by sets opens way to <strong>different underlying implementations</strong>. In lists, elements are assigned indices to give each element a place in the order. Sets have no need to assign indices, so they instead implement a different approach of referencing: hash mapping. These operate by (pseudo)randomly allocating addresses to elements, as opposed to storing them in a row. The allocation is governed by hashing functions, which use the element as an input to output an address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*0B53I_a_wWN6QkozJ0sunw.png" /><figcaption>Hashing does not preserve order</figcaption></figure><p><em>H(x) is deterministic, so the same input always gives the same output, ie. there is no RNG within the function H, so H(4) = 6 always in this case.</em></p><p>Running this function takes the same amount of time regardless of the size of the set, ie. hashing has O(1) time complexity. This means that the time taken to hash is independent of the size of the list, and remains at a constant, quick speed.</p><h3>Set operations</h3><p>Because hashing is generally quick, a whole host of operations that are typically slow on large arrays can be executed very efficiently on a set.</p><h4><strong>Search or Membership Testing</strong></h4><p>Searching for elements in an array utilises an algorithm called <em>Linear Search</em>, by<em> </em>checking each item in the list one by one. In the worst case, where the item being searched for does not exist in the list, the algorithm traverses every element of the list (<em>O(n)</em>). In a very large list, this process takes a long time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*PsTRnymqJ-onqNxVXD6Eag.png" /><figcaption>Linear search on average needs n/2 operations, img by author</figcaption></figure><p>However, as hashing is O(1), Python hashes the item to be found, and either returns where it is in memory, or that it doesn’t exist- in a very small amount of time.</p><pre>number_list = range(random.randint(1,000,000))<br>number_set = set(number_list)<br><br>#Line 1<br>#BEGIN TIMER<br>print(-1 in number_list)<br>#END TIMER<br><br>#Line 2<br>#BEGIN TIMER<br>print(-1 in number_set)<br>#END TIMER<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*SknHV8e9G9J2qutxAiCUSA@2x.png" /><figcaption>Comparison of search times in lists vs sets</figcaption></figure><p><em>Note: Searching using a hashmap has an </em><strong><em>amortized</em></strong><em> time complexity of O(1). This means that in the average case, it runs at constant time but technically, in the worst case, searching is O(n). However, this is extremely unlikely and comes down to the hashing implementation having a chance of collisions, which is when multiple elements in a hashmap/set are hashed to the same address.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*FMqRsPYePW2gVvM4PBYqog.png" /><figcaption>Collisions are rare</figcaption></figure><h4>Deletion</h4><p>Deleting an element from a list first involves a search to locate the element, and then removing reference to the element by clearing the address. In an array, after the O(n) time search, the index of every element following the deleted element needs to be shifted down one. This itself is another O(n) process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*EBd0WzsntAQgfG50u7_UPA.png" /><figcaption>Deletion in a list requires roughly n operations</figcaption></figure><p>Deleting an element from a set involves the O(1) lookup, and then erasure of the memory address which is an O(1) process so deletion also operates in constant time. Sets also have more ways to delete elements, such that errors are not raised, or such that multiple elements can be removed concisely.</p><pre>#LIST<br>numbers = [1, 3, 4, 7, 8, 11]<br><br>numbers.remove(4)<br>numbers.remove(5) #Raises ERROR as 5 is not in list<br>numbers.pop(0) #Deletes number at index 0, ie. 1<br><br>#SET<br>numbers = {1, 3, 4, 7, 8, 11}<br><br>numbers.remove(4)<br>numbers.remove(5) #Raises ERROR as 5 is not in set<br>numbers.discard(5) #Does not raise error if 5 is not in the set<br>numbers -= {1,2,3} #Performs set difference, ie. 1, 3 are discarded<br></pre><h4>Insertion</h4><p>Both appending to a list and adding elements to a set are constant operations; adding to a specified index in a list (.insert) however comes with the added time to shift elements around.</p><pre>num_list = [1,2,3]<br>num_set = {1,2,3}<br><br>num_list.append(4)<br>num_set.add(4)<br><br>num_list += [5,6,7]<br>num_set += {5,6,7}<br></pre><h4>Advanced Set Operations</h4><p>Additionally, all the mathematical operations that can be performed on sets have implementation in python also. These operations are once again time consuming to manually perform on a list, and are once again optimised using hashing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*xFxQBuBEDtibcC_GFhn65A@2x.png" /><figcaption>Set Operations</figcaption></figure><pre>A = {1, 2, 3, 5, 8, 13}<br>B = {2, 3, 5, 7, 13, 17}<br><br># A n B<br>AintersectB = A &amp; B<br># A U B<br>AunionB = A | B<br># A \ B<br>AminusB = A - B<br># A U B - A n B or A Delta B<br>AsymmetricdiffB = A ^ B<br></pre><p>This also includes comparison operators, namely proper and relaxed subsets and supersets. These operations once again run much faster than their list counterparts, operating in O(n) time, where n is the larger of the 2 sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*IxuLUu4KgM5hd4kyG1Qtyg@2x.png" /><figcaption>Subset</figcaption></figure><pre>A &lt;= B #A is a proper subset of B<br>A &gt; B #A is a superset of B<br></pre><h4>Frozen Sets</h4><p>A final small, but underrated feature in python is the <em>frozen set</em>, which is essentially a read-only or <strong>immutable</strong> set. These offer greater memory efficiency and could be useful in cases where you frequently test membership in a tuple.</p><h4>Conclusion</h4><p>The essence of using sets to boost performance is encapsulated by the principle of <strong>optimisation by reduction</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*UIkpSwWtahA254FrVr4wFg.png" /></figure><p>Data structures like lists have the most functionality- being indexed and dynamic- but come at the cost of comparatively lower efficiency: speed and memory-wise. Identifying which features are essential vs unused to inform what data type to use will result in code that runs faster and reads better.</p><p><em>All technical diagrams by author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1157532f7e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-sets-are-so-useful-in-programming-b1157532f7e5">Why Sets Are So Useful in Programming</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>