<?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 Maxwell Conradt on Medium]]></title>
        <description><![CDATA[Stories by Maxwell Conradt on Medium]]></description>
        <link>https://medium.com/@mhconradt?source=rss-83d4d263c80e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hYdqmkm8cmAzD6PPRZVd7g.jpeg</url>
            <title>Stories by Maxwell Conradt on Medium</title>
            <link>https://medium.com/@mhconradt?source=rss-83d4d263c80e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:08:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mhconradt/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[Image Compression From Scratch in Python]]></title>
            <link>https://medium.com/@mhconradt/image-compression-from-scratch-in-python-ee357fea3f9e?source=rss-83d4d263c80e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee357fea3f9e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maxwell Conradt]]></dc:creator>
            <pubDate>Tue, 23 Aug 2022 13:11:42 GMT</pubDate>
            <atom:updated>2022-08-23T13:11:42.704Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I walk through an image compression and decompression pipeline in Python. It uses linear algebra operations to transform an image into a sparse matrix and then uses the inverse operations to re-create the original image. I’ve published <a href="https://github.com/mhconradt/image-compression">the source code from the examples</a> to Github, so feel free to follow along and do some hacking of your own.</p><h3>Mathematical Background</h3><p>Before we get into the code, we’ll explore the math behind it. The first step is modeling an image as a two-dimensional matrix. This allows us to use linear algebra to transform the image. The values of the matrix represent the brightness of each pixel and are integers between 0 (black) and 255 (white). If we used color images, we would represent them as three-dimensional matrices, the extra dimension representing the intensities of different components, i.e. red, green, and blue.</p><p>The algorithm we’ll use requires the matrix have the same number of rows and columns. Additionally, each stage of the encoding combines pairs of inputs, so the dimensions of the matrix need to be powers of two. Both of these requirements can be satisfied by padding with zeros.</p><p>The pipeline uses a Haar wavelet transform to iteratively encode the image as a set of “averages” and “details”. Basically, it summarizes large areas or patterns in the image (averages) along with the values needed to reconstruct the original from the averages (details). Some averages will be of details from an earlier step, which allows summarizing patterns in the differences in an image. Conversely, some details will be differences in the averages from earlier steps.</p><p>To the extent pixel values in any quadrant of the image (recursively defined) are either close to the average of the pixel values in their parent quadrant or have similar patterns to other quadrants with the same parent, the transformation will encode the image into a sparse matrix (one with a lot of zeros). The base case, the input image, is modeled as the averages of single pixel values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*o7_-uFGFJkWVL5dtEUWf-w.jpeg" /><figcaption>Alfréd Haar (Wikipedia)</figcaption></figure><p>We’ll walk through the algorithm using this 4x4 example “image”, labelled with the pixel values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*J77V7aQd6sPL1n79Fow5iw.png" /></figure><p>The first encoding step needs the following properties:</p><ol><li>The first and second output columns are the average of the first and second and third and fourth columns, respectively. We can do this with B[i][0] = (A[i][0] + A[i][1]) / 2 and B[i][1] = (A[i][2] + A[i][3]) / 2 .</li><li>The third and fourth columns of the output are the difference between the first input column and the first output column, and the difference between the third input column and the second output column, respectively. This simplifies to B[i][2] = (A[i][0] — A[i][1]) / 2 and B[i][3] = (A[i][2] — A[i][3]) / 2 .</li></ol><p>We’ll use a matrix multiplication for the transformation. This allows us to efficiently compose and invert transformations. The matrix looks like this:</p><pre>T1 = np.array([[ 0.5,  0. ,  0.5,  0. ],<br>               [ 0.5,  0. , -0.5,  0. ],<br>               [ 0. ,  0.5,  0. ,  0.5],<br>               [ 0. ,  0.5,  0. , -0.5]])</pre><p>After applying the transformation (multiplying the input image and transformation matrix), we get this matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*JkxtbiEPwoYarYGDEFH8-g.png" /></figure><p>Next, we’ll multiply this output by the transpose of the last transformation, on the left this time, which produces the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ty8vCGAlU6WOrxxsfsdaoQ.png" /></figure><p>What’s going on here?</p><ol><li>The top-left quadrant contains the averages of each quadrant, maintaining the relative positions of the quadrants.</li><li>The top-right quadrant contains details. It represents the difference between the average of the left half of each quadrant and the average of the entire quadrant, which is always -8.5. This makes sense, because the original pixel values were increasing by 17 along the x-dimension.</li><li>The bottom-left quadrant also contains details. It represents the difference between the average of the top half of each quadrant and the average of the entire quadrant, which is always -34. This also makes sense, because the values were increasing by 68 along the y-dimension.</li><li>The bottom-right quadrant tells us the difference between the top left value in each quadrant and the average plus the x-detail and the y-detail (the values mentioned in #2 and #3, respectively). This is always zero, because the values follow a common pattern: A[i][j] = 68 * i + 17 * j. If the values weren’t a linear combination of the row and column, i.e. i * j or i ** 2 , this quadrant would not be empty.</li></ol><p>The next and final row transformation needs the following properties:</p><ol><li>The first column of each output row is the average of the first two columns of each input row. This is equivalent to B[i][0] = (A[i][0] + A[i][1]) / 2.</li><li>The second column of each output row is the difference between the first column and the average of the first and second column. This is equivalent to B[i][1] = (A[i][0] - A[i][1]) / 2.</li><li>Columns three and four of the output have the same values as columns three and four of the input.</li></ol><p>This is the transformation that satisfies both properties:</p><pre>T2 = np.array([[0.5, 0.5, 0.0, 0.0],<br>              [0.5, -.5, 0.0, 0.0],<br>              [0.0, 0.0, 1.0, 0.0],<br>              [0.0, 0.0, 0.0, 1.0]])</pre><p>This is similar to the previous transformation, but only operates on the first two columns of each row. The rest of the information needs to be preserved in order to reconstruct the original image. After applying the transpose of this on the left, only the bottom-right quadrant will be left unchanged . This quadrant had only zeros in our example, so any linear combination of these values would not change them.</p><p>Applying this transformation to the output of the previous one, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*aBF7CciyoPnsOwDKNu0Pug.png" /></figure><p>Next, we apply the transpose of this transformation on the left, to get the final encoded image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*gEkVkG-lB8HKSt-mOqwSnQ.png" /></figure><p>What’s going on here?</p><ol><li>The top-left value is the average of all the input values.</li><li>The value in the first row and second column is the difference between the average of the values in the two leftmost quadrants and the average of the entire image’s values.</li><li>The value in the second row and first column is the difference between the average of the values in the two topmost quadrants and the average of the entire image’s values.</li><li>The values not in the first row or column are zero. This is because the values are a linear combination of the row and column. Even in a much larger matrix, if this is the case only the values in the first row and column will be nonzero.</li><li>In the original, 15 values were nonzero, and now only 7 are nonzero. This would reduce the storage footprint of the image, or allow effectively using <a href="https://docs.scipy.org/doc/scipy/reference/sparse.html">SciPy sparse matrices</a>.</li></ol><p>Before moving on to decoding, let’s look at a couple other examples, which step through the transformations in the same order as above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8ZCfVv6Op2UCik3-A5wAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2w7o3dF_yf_Ludlr1JICmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1qYF3-8zPBgCtJ8Jf-_9Q.png" /></figure><p>Try to grok those examples before moving on. If you were paying close attention you may have noticed the third input and output are the sum of the first and second inputs and outputs, respectively. This is because matrix multiplications have the distributive property.</p><p>We’ll apply the inverses of the encoding matrices in reverse order to get the original matrix. The inverses of linear transformations cancel out the transformations, leaving us with the original values.</p><p>This is the inverse of the second encoding transformation:</p><pre>array([[ 1.,  1.,  0.,  0.],<br>       [ 1., -1., -0., -0.],<br>       [ 0.,  0.,  1.,  0.],<br>       [ 0.,  0.,  0.,  1.]])</pre><p>This is the inverse of the first encoding transformation:</p><pre>array([[ 1.,  1.,  0.,  0.],<br>       [ 0.,  0.,  1.,  1.],<br>       [ 1., -1., -0., -0.],<br>       [-0., -0.,  1., -1.]])</pre><p>For brevity, we’ll just directly use the inverses, but if we hand-crafted our own transformations that logically undid the encoding transformations by the logic of combining averages and details, we would create exactly these matrices.</p><p>Comparing the decoding transformations with the encoding transformations, they invert the original combinations of the inputs. If this were not possible, the matrix would not be invertible. It’s no coincidence that the Haar wavelet transformation is a lossless encoding and the transformations we’ve used are invertible.</p><p>The intuition behind this is instead of storing brightness values in each cell, we store linear combinations of the brightness values. These linear combinations are crafted to be invertible (it’s not much use otherwise) and likely to be zero if the image has certain properties. This is isomorphic to how we can add and subtract equations from one another to find a unique solution for a variable if the system of equations has certain properties. I won’t go on or else this post would become “Everything Max Knows About Linear Algebra”, but I highly recommend checking out <a href="https://brilliant.org/ref/dbN6KPK2b7/">Brilliant.org</a>’s courses on the topic if you’re interested in learning more.</p><p>Here’s a step-by-step decoding of the encoded image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLiqYlJ2ghvBBPiCdG23dA.png" /></figure><p>And the step-by-step process of decoding the other two examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUdi-0OxM-y8aozhaJQjwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HsXaHepG2p5PibF05no3A.png" /></figure><h3>Algorithm</h3><p>Hello, welcome to the code part of this article. In this section, we’ll create a general purpose algorithm for encoding and decoding any image (but especially cat images without copyrights).</p><p>We’ll use <a href="https://pillow.readthedocs.io/en/stable/">Pillow</a> for image I/O, padding the images, and converting them to grayscale. We’ll also use NumPy for our linear algebra routines.</p><p>First, we create a function that pre-processes the image:</p><pre>from PIL import Image, ImageOps<br><br><br>def preprocess_image(image: Image) -&gt; Image:<br>    <em>&quot;&quot;&quot;<br>    Create a square matrix with side length that&#39;s a power of 2.<br>    &quot;&quot;&quot;<br>    </em>image = ImageOps.grayscale(image)  # convert to grayscale first so padding is less expensive, might be a large image<br>    dim = max(image.size)  # Find the largest dimension<br>    new_dim = 2 ** int(math.ceil(math.log(dim, 2)))  # Find the next power of 2<br>    return ImageOps.pad(image, (new_dim, new_dim))</pre><p>Then, we’ll use this function to get each of our Haar wavelet transformations. This generalizes the logic we used to create the example transformations:</p><pre>def get_haar_step(i: int, k: int) -&gt; np.ndarray:<br>    transform = np.zeros((2 ** k, 2 ** k))<br>    # Averages (1)<br>    for j in range(2 ** (k - i - 1)):<br>        transform[2 * j, j] = 0.5<br>        transform[2 * j + 1, j] = 0.5<br>    # Details (2)<br>    offset = 2 ** (k - i - 1)<br>    for j in range(offset): <br>        transform[2 * j, offset + j] = 0.5<br>        transform[2 * j + 1, offset + j] = -0.5<br>    # Identity (3)<br>    for j in range(2 ** (k - i), 2 ** k):<br>        transform[j, j] = 1<br>    return transform</pre><ol><li>Step through the columns that will contain “averages” in the output of the transformation. Since each column is the average of two consecutive values, we increment the rows by 2. The weights in the matrix above were both 1/2 for the average, since each output column is the average of two input columns.</li><li>Step through the columns that will contain the details of the averages in the input of this step (remember the input image is all averages). We’re subtracting 1/2 of the second input average from 1/2 of the first input average.</li><li>Step through the columns to leave unchanged. To do this, we set this part of the matrix’s diagonal to one.</li></ol><p>It’s interesting to note the individual transformations will be sparse, unless we compose them.</p><p>Now, we compose the inputs:</p><pre>def get_haar_transform(k: int) -&gt; np.ndarray:<br>    transform = np.eye(2 ** k)<br>    for i in range(k):<br>        transform = transform @ get_haar_step(i, k)<br>    return transform</pre><p>This composes the row transformations from each step in the order we want (most detailed to least detailed). Thanks to <a href="https://brilliant.org/wiki/matrices/#transpose-and-determinant">a useful matrix property</a>, the transpose of the row transformation is equal to the column transformation, leaving us with this function:</p><pre>def haar_encode(a: np.ndarray) -&gt; np.ndarray:<br>    k = int(np.ceil(np.log2(len(a))))<br>    assert a.shape == (k, k)<br>    row_encoder = get_haar_transform(k)<br>    return row_encoder.T @ a @ row_encoder</pre><p>Applying this to our earlier example, we see it does the same thing:</p><pre># Code</pre><pre>A = np.array([[0., 17., 34., 51.],<br>              [68., 85., 102., 119.],<br>              [136., 153., 170., 187.],<br>              [204., 221., 238., 255.]])<br>E = haar_encode(A)<br>print(E)</pre><pre># Output</pre><pre>[[127.5 -17.   -8.5  -8.5]<br> [-68.    0.    0.    0. ]<br> [-34.    0.    0.    0. ]<br> [-34.    0.    0.    0. ]]</pre><p>To decode the image, we use np.linalg.inv to invert the input transformation:</p><pre>def haar_decode(a: np.ndarray) -&gt; np.ndarray:<br>    k = int(np.ceil(np.log2(len(a))))<br>    assert a.shape == (k, k)<br>    row_decoder = np.linalg.inv(get_haar_transform(k))<br>    return row_decoder.T @ a @ row_decoder</pre><p>Let’s try it out:</p><pre># Code</pre><pre>&gt;&gt;&gt; A = np.array([[0., 17., 34., 51.],<br>              [68., 85., 102., 119.],<br>              [136., 153., 170., 187.],<br>              [204., 221., 238., 255.]])<br>&gt;&gt;&gt; E = haar_encode(A)<br>&gt;&gt;&gt; D = haar_decode(E)<br>&gt;&gt;&gt; print(D)</pre><pre>[[  0.  17.  34.  51.]<br> [ 68.  85. 102. 119.]<br> [136. 153. 170. 187.]<br> [204. 221. 238. 255.]]</pre><pre>&gt;&gt;&gt; print(D == A)</pre><pre>[[ True  True  True  True]<br> [ True  True  True  True]<br> [ True  True  True  True]<br> [ True  True  True  True]]</pre><p>The code works! Notice that the pipeline’s output is <em>exactly</em> equal to the input. We’re going to change that, to get even better compression. First let’s test it out on a cat picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AcO56XTbmmgYfuGmkbcDcQ.jpeg" /><figcaption><strong>Jan Kopřiva (Unsplash)</strong></figcaption></figure><p>We’ll use this function that truncates small nonzero values in the encoded matrix to zero, in order to better compress the matrix.</p><pre>def truncate_values(a: np.ndarray, threshold: float):<br>    return np.where(np.abs(a) &lt; threshold, 0, a)</pre><p>Thresholds in the range of 1–8 (the units of the threshold are brightness values) seem to give reasonable combinations of compression and image quality.</p><p>Here is the final pipeline:</p><pre>im = preprocess_image(im)<br>A = np.array(im)<br>E = haar_encode(A)<br>threshold = 8<br>E = truncate_values(E, threshold)<br>D = haar_decode(E)</pre><p>Here are some examples of images after they’ve been encoded, lossily truncated, and decoded using different thresholds for truncation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*orEoYc7XKn6TOHVLpX6dzQ.png" /></figure><p>12 is the highest tolerance that’s recognizable as a cat, but not necessarily the one in the picture. It achieves a 52:1 compression ratio. Here’s the decoded image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*TQU6i-LLFEnaD8CGxStYcw.png" /></figure><h3>Conclusion</h3><p>In this post we did a deep dive into the math behind the Haar wavelet transform and created a respectable image compression and decompression suite. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee357fea3f9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Lesser Known Python Features]]></title>
            <link>https://medium.com/@mhconradt/3-lesser-known-python-features-d676ee2589fd?source=rss-83d4d263c80e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d676ee2589fd</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Maxwell Conradt]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 19:05:41 GMT</pubDate>
            <atom:updated>2021-11-22T19:05:41.547Z</atom:updated>
            <content:encoded><![CDATA[<p>This post describes some nice functionality of Python’s list , set , and tuple data types. I recently learned about these, found them interesting, and wanted to share them with you, my fellow programmer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XGWc5pe0OpKiF2fD" /><figcaption>Photo by <a href="https://unsplash.com/@universaleye?utm_source=medium&amp;utm_medium=referral">Universal Eye</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Sets</h3><p>This is the most interesting part. We’ll learn about what the operators &lt;, &lt;=, &gt;, &gt;= do with set operands. It’s somewhat obvious what the == operator does with sets, but there’s interesting behavior when we venture into ordering sets. If you haven’t thought about this before, try guessing how the comparison operators work before reading further.</p><pre>{&#39;bread&#39;} &lt;= {&#39;bread&#39;, &#39;butter&#39;} <br># True </pre><pre>{&#39;bread&#39;, &#39;jam&#39;} &lt;= {&#39;bread&#39;, &#39;butter&#39;} <br># False </pre><pre>{&#39;bread&#39;} &lt;= {&#39;bread&#39;} <br># True</pre><p>That’s right! &lt;= is overloaded with issubset on set. There’s a slightly different behavior defined on the &lt; operator:</p><pre>{&#39;bread&#39;} &lt; {&#39;bread&#39;, &#39;butter&#39;}<br># True</pre><pre>{&#39;bread&#39;} &lt; {&#39;bread&#39;}<br># False</pre><p>The difference is &lt; defines whether the left operand is a <em>strict</em> subset of the right operand. This means the left operand is a subset of, but not equal to, the right operand. This can be a useful distinction, especially since there are not isstrictsubset or isstrictsuperset methods on set .</p><p>I wont go into the behavior of &gt; and &gt;= in quite as much detail, because you can more or less replace subset with superset and do the algebraic equivalent of multiplying by -1 in the above section. Let’s do just that:</p><pre>{&#39;bread&#39;, &#39;butter&#39;} &gt;= {&#39;bread&#39;}<br># True</pre><pre>{&#39;bread&#39;, &#39;jam&#39;} &gt;= {&#39;bread&#39;, &#39;butter&#39;}<br># False</pre><pre>{&#39;bread&#39;} &gt;= {&#39;bread&#39;}<br># True</pre><pre>{&#39;bread&#39;, &#39;butter&#39;} &gt; {&#39;bread&#39;}<br># True</pre><pre>{&#39;bread&#39;} &gt; {&#39;bread&#39;}<br># False</pre><p>Now you can chain comparisons on sets:</p><pre>{&#39;bread&#39;} &lt;= {&#39;bread&#39;, &#39;butter&#39;} &lt;= {&#39;bread&#39;, &#39;butter&#39;, &#39;eggs&#39;}<br># True</pre><p>Here I’ve gratuitously added the equivalent code using issubset to show how far we’ve come:</p><pre>{&#39;bread&#39;}.issubset({&#39;bread&#39;, &#39;butter&#39;}) and {&#39;bread&#39;, &#39;butter&#39;}.issubset({&#39;bread&#39;, &#39;butter&#39;, &#39;eggs&#39;})</pre><h4>Bonus</h4><p>The humble ^ operator, which is overloaded with the symmetric difference. What does it mean? It’s the set of elements that appear in one, but not both of the left and right operands:</p><pre>def symmetric_difference(a: set, b: set) -&gt; set:    <br>    return {elt for elt in a | b if (elt in a) ^ (elt in b)} </pre><pre>symmetric_difference({&#39;bread&#39;, &#39;butter&#39;}, {&#39;bread&#39;, &#39;jam&#39;})<br># {&#39;butter&#39;, &#39;jam&#39;} </pre><pre>{&#39;bread&#39;, &#39;butter&#39;} ^ {&#39;bread&#39;, &#39;jam&#39;}<br># {&#39;butter&#39;, &#39;jam&#39;}</pre><p>Note the ^ in the set comprehension. It’s XOR all the way down!</p><h3>Lists, Tuples, Strings, oh my!</h3><p>Comparison operators on lists, tuples and strings work the same way. The operators &lt;, &lt;=, &gt;, &gt;= define a <a href="https://en.wikipedia.org/wiki/Lexicographic_order">lexicographic order</a>, which is a way of ordering sequences of objects based on an ordering of their elements. It’s the concept of alphabetical ordering, generalized to sequences containing any type of object with &lt; and &gt; operators defined. This is where things get weird!</p><p>Let’s start with strings:</p><pre>&#39;01&#39; == &#39;01&#39;<br># True</pre><pre>&#39;01&#39; &lt; &#39;10&#39;<br># True</pre><pre>&#39;11&#39; &lt; &#39;2&#39;<br># True</pre><pre>&#39;2&#39; &gt; &#39;10&#39; &gt; &#39;1&#39;<br># True</pre><p>Note this works the same way with lists:</p><pre>[0, 1] == [0, 1]<br># True</pre><pre>[0, 1] &lt; [1, 0]<br># True</pre><pre>[1, 1] &lt; [2]<br># True</pre><pre>[2] &gt; [1, 0] &gt; [1]<br># True</pre><p>And tuples:</p><pre>(0, 1) == (0, 1)<br># True</pre><pre>(0, 1) &lt; (1, 0)<br># True</pre><pre>(1, 1) &lt; (2,)<br># True</pre><pre>(2,) &gt; (1, 0) &gt; (1,)<br># True</pre><h4>Bonus</h4><p>You can even compare lists of heterogenous types:</p><pre>[2, &#39;a&#39;] &lt; [2, &#39;b&#39;]<br># True</pre><pre>[2, [1, 0]] &lt; [2, [2, 1]] # (:<br># True</pre><p>Just make sure the types match element-wise:</p><pre>[3, 4] &lt; [3, &#39;a&#39;]<br># TypeError: &#39;&lt;&#39; not supported between instances of &#39;int&#39; and &#39;str&#39;</pre><h3>Conclusion</h3><p>I hope this exploration got you thinking about what your programming language <em>can</em> and <em>should</em> do, as opposed to reusing snippets you’ve already seen. Next time you think of something and wonder if it works, try it out!</p><p>If you know of any quirky behavior of operators in Python or any other programming language, please share in the comments!</p><p><strong>Thanks</strong> to Spencer Finkel and Cole Willenbring for reading drafts of this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d676ee2589fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Weather Data Platform]]></title>
            <link>https://medium.com/weather-20-20-tech-blog/how-to-build-a-weather-data-platform-d496d0d6e96b?source=rss-83d4d263c80e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d496d0d6e96b</guid>
            <category><![CDATA[data-platforms]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Maxwell Conradt]]></dc:creator>
            <pubDate>Sun, 11 Apr 2021 23:06:36 GMT</pubDate>
            <atom:updated>2021-04-13T18:29:46.575Z</atom:updated>
            <content:encoded><![CDATA[<p>Climate change has increased the <em>frequency</em> and <em>severity</em> of extreme weather events around the world. Although this trend is just beginning, extreme weather is already wreaking havoc on billion-dollar businesses. Consequently, business leaders are scrambling to understand how the weather impacts their businesses and prevent the next catastrophe.</p><p>The challenge of integrating weather data into these organizations naturally falls to engineering teams. Many organizations are adding business logic surrounding weather forecasts to existing applications. Estimates of weather-related risk are becoming critical components of business intelligence suites. Mature data teams already have weather-driven predictive models in production. Software is eating the world, and weather is eating software.</p><p>While petabytes of weather datasets have been published by climate agencies over recent decades, this data is geared towards climate researchers and requires specific expertise and tooling. Hundreds of variables are available and documented <em>at length</em>, but this documentation is tailored towards meteorologists, not software engineers. Climate-specific data formats and services are not compatible with mainstream data tools, such as Pandas or Apache Spark. As a result, working directly with these datasets is time-consuming and error-prone. A well-architected weather data platform will allow software engineers, data scientists and analysts to be immediately productive with weather data.</p><p>Data platforms must provide insights into the weather’s impact on each affected department. Using weather forecasts, agriculture companies estimate crop yields, hedge market risk, and predict demand for their products. Each use case might focus on different locations and variables. A well-architected weather data platform will satisfy multiple use cases and evolve as new ones emerge.</p><p>To serve these use cases, weather data can be consumed in many ways. Let’s consider a logistics firm’s usage of weather data. First, it trains a machine learning model to predict delivery times using historical weather and operational data. It then uses weather forecasts as inputs to the model during inference. Finally, it analyzes historical data to learn how the weather actually impacted operations. Using the same systems to serve each of these use cases is a recipe for disaster.</p><p>I built Weather 20/20’s data platform and have navigated these challenges with our expert meteorologists. This post outlines the most important factors and tradeoffs in designing a weather data platform. I recommend considering how these affect your use cases and will be discussing Weather 20/20’s choices in parallel.</p><h3>Variables</h3><p>Each variable captures information about the state of the climate at a particular point in or interval of time, i.e. the temperature at a certain time or snowfall on a particular day. It’s important to understand which variables impact both current and potential use cases as long-term data ingestion is both time-consuming and costly when dealing with large weather datasets.</p><h4><strong>Choices</strong></h4><p>The most commonly used variables are temperature, precipitation, humidity, air pressure, and wind speed and direction. However, this only scratches the surface. Agriculture operations are especially concerned with solar radiation, evapotranspiration, soil temperature, and soil moisture. Weather forecasting systems calculate how much solar radiation is trapped by the atmosphere using many variables, including snow <a href="https://en.wikipedia.org/wiki/Albedo">albedo</a> and cloud cover. Airlines and militaries are not only interested in surface conditions, but also conditions at various levels in the atmosphere. Take some time to discuss with domain experts which variables might matter to your use cases.</p><h4><strong>Tradeoffs</strong></h4><p>Having access to the necessary variables is important. Without this, your users will be frustrated and you will struggle to gain adoption of your weather data platform. Adding the desired variables could take awhile depending on the scope of your platform. However, having too many variables can be expensive and confusing. In sum, explore variables that potentially impact your use case, curate datasets for each use case, but don’t confuse your data platform’s users with extraneous variables.</p><h4><strong>Caveat</strong></h4><p>A deep neural network can perform “automated feature engineering” on a weather data set. While this is an appealing shortcut, it could reduce your model’s ability to predict the most extreme events since with limited examples your model could over-attribute the severity to an extraneous variable.</p><h4>How We Do It</h4><p>At Weather 20/20 we ingest variables that are used by our weather model: temperature, precipitation, pressure, humidity, cloud-cover, wind speed and wind direction. We’re also interested in ingesting data relevant to agriculture such as soil temperature, soil moisture and evapotranspiration.</p><h3>Spatial Coverage</h3><p>Spatial coverage is the geographical region you’re interested in. This might consist of a set of points, countries, continents, or even the entire world. This factor has a bearing on data availability and total cost of ownership (TCO).</p><h4>Choices</h4><p>You might limit the dataset to regions or even countries in which the business operates, perhaps ingesting some unnecessary data as a result. Alternatively, you could ingest data for known points-of-interest, such as an agriculture company ingesting data for specific farms, potentially spanning the globe.</p><h4>Tradeoffs</h4><p>Spatial coverage is proportional to the size of your dataset. Different departments might be interested in totally different regions (i.e. a chain of cafés has locations in the United States and Canada, but coffee farms in South America and Southeast Asia). The spatial coverage necessary to satisfy all use cases is liable to change, and your data platform must respond in a proportional timely manner. This means data will be consistently available within agreed-upon boundaries, which can expand upon request within a sprint or so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*Ou4zJP9sfqz2vDQmFzXe3Q.png" /><figcaption>Uber’s H3 discrete global grid (Source: Uber)</figcaption></figure><h4>How We Do It</h4><p>We have a global data platform and organize our data into a <a href="https://en.wikipedia.org/wiki/Discrete_global_grid">hierarchical discrete global grid</a> comprising 2,016,842 cells. This allows modeling <a href="https://www.cpc.ncep.noaa.gov/data/teledoc/teleintro.shtml">interactions of weather patterns over long distances</a> and also quickly serving new international use cases. However, if you want to know about sandstorms on Mars, you’ll have to wait.</p><h3>Spatial Resolution</h3><p>Spatial resolution is the distance between points in a dataset. The Earth’s (spherical) shape makes understanding spatial resolution a bit more difficult. Here’s your relevant xkcd:</p><h4>Choices</h4><p>Gridded datasets come in all different shapes and sizes, but most are 1˚, 0.5˚, 0.25˚ or 0.1˚, meaning the points are that far apart in both latitude and longitude. Ground station datasets do not follow this pattern except for <a href="https://madis.ncep.noaa.gov/madis_RSAS.shtml">a subset of stations in North and Central America</a>.</p><h4>Tradeoffs</h4><p>There are two major tradeoffs: precision and data size. Certain variables, particularly precipitation, are more geographically variable than others. Depending on your platform’s spatial coverage, the irregular resolution of ground station datasets could cause insufficient precision. Think about how big of a change could affect your use case. If you’re deciding how much dry ice to ship your ice cream with, a few degrees warmer could cause an enormous loss.</p><p>Data size increases proportionally to the inverse square of spatial resolution. Consequently, the marginal cost of increasing resolution can become staggering. For example, a 1˚ global grid contains 64,800 data points, but a 0.1˚ grid contains 6,480,000 — a 100-fold increase in data size for a 10-fold reduction in spatial resolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*tBxdYD_ieg-qTQrxp0Ur3w.png" /><figcaption>Map projections (Source: xkcd)</figcaption></figure><h4>Caveat</h4><p>Your organization cares about how relevant the data you have is. The distance between points is a directionally correct indicator of this. The spatial resolution of the dataset does not translate to distance between points, since the resolution in kilometers of a “uniform” coordinate grid varies by latitude and the arc of each degree of longitude is shorter the arc of each degree of latitude. Absolutely higher latitudes have lower real spatial resolution than lower latitudes, due to the Mercator Projection. Weather 20/20 ultimately provides a more uniformly spatially distributed dataset by using the H3 grid, which is based on the “Dymaxion” map projection (the one that looks like a stegosaurus).</p><h4>How We Do It</h4><p>We ingest gridded data at 0.1˚ and 0.25˚ resolution and project this data onto the H3 grid.</p><h3>Temporal Coverage</h3><p>Temporal coverage is the time interval of data your users have access to, often beginning at a fixed point in the past and extending to the present, or alternatively the present plus a fixed interval when using forecasts. It’s especially important when working with historical data as it could be the difference between working with gigabytes and terabytes of weather data.</p><h4>Choices</h4><p>Many popular weather datasets extend to the 1980s, with some station datasets extending to the 19th century, albeit with comparatively limited spatial resolution and granularity. Climate agencies provide forecasts up to sixteen days in advance. At Weather 20/20 we provide a 100+ day forecast by using an alternative forecasting methodology.</p><h4>Tradeoffs</h4><p>The marginal benefit curve here depends on the depth of comparative data sources. If you only have sales data going back to 2012, you cannot use weather data from 2010 to better understand the impact of weather on your sales, much less train a machine learning model. Extreme weather events are rare, so deeper historical coverage will allow you to better understand the impact of rare weather events. It’s best to use at least 10 years if you have matching operational data.</p><h4>How We Do It</h4><p>Our historical dataset extends to 1980. This allows us to improve our weather forecasts by analyzing global climate trends and patterns to the extent reliable data exists. It also allows us to satisfy even the most extensive customer demands for historical data analysis.</p><p>Our forecasts dataset is one of the longest range in the industry, calculated on a rolling 365-day basis.</p><h3>Temporal Resolution</h3><p>Temporal resolution is the frequency of data your platform provides. You might provide data at multiple frequencies, allowing users to choose the best frequency for their use case. You can down-sample one high-frequency time series to provide lower frequency data to users, but cannot turn a low-frequency time series of weather data into a higher one with 100% accuracy.</p><h4>Choices</h4><p>Hourly, daily and monthly data are broadly available. Your platform might provide several or all of those.</p><h4>Tradeoffs</h4><p>The size of your dataset is proportional to the frequency of your time series. Hourly data is 24 times as large as daily data. This can have a large impact on storage and computing costs.</p><p>The right frequency depends on your use case’s sensitivity to intra-day climate variability. For example, a delivery service might experience especially high traffic when there’s a lot of rain between 5pm and 7pm local time and need to increase supply of drivers during that window. If the rain actually arrives between 7pm and 9pm, the delivery service will have wasted money and frustrated its drivers. However, if your use case varies more on a narrative such as “people buy ice cream when it’s warm and sunny”, it might not matter.</p><p>Hourly data can be aggregated into daily data, but if users want hourly data but you only have daily data, you’ll need to ingest a new dataset.</p><h4>How We Do It</h4><p>We store and ingest both hourly and daily data, but analyze and forecast on a daily resolution to be more cost-effective. We are working towards providing hourly forecasts based on location-specific patterns of intra-day variability.</p><h3>Origin</h3><p>There are several types of weather datasets, and understanding which should be used in your data platform is critical. While I tried to make these factors as orthogonal as possible, this one depends on the rest.</p><h4>Choices</h4><p>The three categories are ground-stations, satellites, and re-analysis. You may end up using all three data sources in your platform.</p><p>Ground stations contain instruments including, but not limited to barometers, anemometers and rain gauges. Some measurements, such as visibility or cloud cover, are manually recorded by a human at the station. I’m sure they’re great at their jobs, but am not a big fan of having a human in the loop there. Ground stations are concentrated around populated areas and airports, meaning your point-of-interest could be over one hundred miles from the nearest station. This can be problematic since small-scale, high-impact weather events could go completely undetected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BszmDu42iHvTNuaO4hLCPg.jpeg" /><figcaption>Precipitation varies a lot on small scales (Credit: NASA/JAXA)</figcaption></figure><p>Since the Space Race, the collection of weather data via satellites has revolutionized meteorology. Climate agencies around the world have weather satellites in orbit, constantly monitoring electromagnetic radiation reflected from the Earth. Variables such as precipitation and cloud cover can be calculated from the raw data, and then post-processed to yield a uniform grid. These satellite data are the backbone of modern weather forecasting systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*sYZvAnE5wixy03yY.jpg" /><figcaption>Temperature uncertainty estimates the in ERA5 re-analysis (Source: Copernicus)</figcaption></figure><p>Re-analysis datasets are one level above the satellite datasets, using similar machinery as numerical weather forecasting models to yield a dataset with additional variables, and a higher spatial and temporal resolution. The bad news is this process inevitably adds some error. The good news is this error is random so you should not see the sum of errors dramatically accumulate over time.</p><h4>Tradeoffs</h4><p>Ground stations are only sufficient if your points-of-interest are near at least one station, but preferably multiple stations as this data has gaps, say if coffee gets spilled on the equipment. All but the most popular ground station datasets require extensive data munging due to <a href="https://www.ncei.noaa.gov/data/global-hourly/doc/isd-format-document.pdf">archaic formatting choices</a>. Beyond a minimal baseline of temperature and precipitation variables, the set of variables differs among ground stations, so <strong>variables corresponding to a particular location in your output dataset could originate from different stations</strong>, which can also be problematic.</p><p>For example, if:</p><ol><li>The nearest stations reporting high and low temperatures are different. And,</li><li>The reported low temperature is higher than the reported high temperature.</li><li>Voila, there is a bug in your dataset.</li></ol><p>Satellite and re-analysis datasets tend to be more productive to work with due to their uniformity, consistency and often wide range of variables. It’s also nice that these datasets stretch all the way back to the 1980s (with work being done to extend them even further). There’s a specific toolset developed for working with this gridded weather data, but it does not play very nice with the modern data stack. There’s some added uncertainty when using re-analysis data, especially earlier on in the temporal coverage of the dataset. Some industries with strict auditing requirements (think electricity trading) also require data to be traced back to a ground station.</p><h4>How We Do It</h4><p>We use a combination of station, satellite and re-analysis datasets to provide a unified spatially and temporally gapless historical dataset, choosing which values to use based on a combination of proximity and quality control indicators (easier said than done). Using satellite and re-analysis data allows maintaining a gapless, uniform global grid.</p><h3>Conclusion</h3><p>By now, the contours of your weather data platform and Weather 20/20’s data platform have begun to take shape. The factors outlined in this post influence the components and characteristics of your data platform, especially evolvability, time to operationalization, and TCO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-xMTHtnsYhHHsazSGlV7g.png" /><figcaption>Weather 20/20’s International Dashboard (Image by Author)</figcaption></figure><p>If you think Weather 20/20 might be a good fit for your organization you can contact us through <a href="http://weather2020.com/">our website</a>. Even if not, we would love to provide guidance and hear about your weather data use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d496d0d6e96b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weather-20-20-tech-blog/how-to-build-a-weather-data-platform-d496d0d6e96b">How to Build a Weather Data Platform</a> was originally published in <a href="https://medium.com/weather-20-20-tech-blog">Weather 20/20 Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>