<?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 Shivaditya Meduri on Medium]]></title>
        <description><![CDATA[Stories by Shivaditya Meduri on Medium]]></description>
        <link>https://medium.com/@mvenkatashivaditya?source=rss-65dcb782d994------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Bh6qWGTdpJE1SjphETdQSA.jpeg</url>
            <title>Stories by Shivaditya Meduri on Medium</title>
            <link>https://medium.com/@mvenkatashivaditya?source=rss-65dcb782d994------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:34:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mvenkatashivaditya/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[SSL/TLS connection issues in Python in the context of Enterprise VPNs]]></title>
            <link>https://medium.com/@mvenkatashivaditya/ssl-tls-connection-issues-in-python-in-the-context-of-enterprise-vpns-a360aed277f3?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/a360aed277f3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 10:15:33 GMT</pubDate>
            <atom:updated>2025-12-23T10:45:14.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*j36lYSjN2pDBwbDdYArjWQ.png" /></figure><h4>TL;DR</h4><ul><li>Enterprise VPNs can make it difficult to make HTTPS requests using Python. Most common error concerns self signed certificates.</li><li>Python by default relies on certifi trust store which will not have your enterprise VPN’s certificates causing Python to return an error.</li><li>This error can be fixed by configuring python to use a trust store with your enterprise VPNs Certs.</li></ul><h4><strong>Intro</strong></h4><pre>certificate verify failed: self-signed certificate in certificate chain</pre><ul><li>Did you ever experience SSL Errors in Python especially when enterprise VPN is enabled?</li><li>Usually in order to tackle this problem, people default to setting verify=False.</li><li>Putting aside the security/privacy issues, this hack is not always effective. If you are using an external library in Python for example which relies on making API calls to the internet. You can’t easily apply verify=False unless by changing the library’s code. Many libraries don’t offer verify parameter for obvious reasons.</li></ul><p>I relied on hacks like this and one day I decided to solve this problem once and for all by understanding what is the root cause and how to fix it.</p><p>In this article, I would like to share everything that I learned and how I finally stopped using verify=False.</p><h4><strong>HTTP/HTTPS &amp; VPN flow quickly explained (Skip if already familiar)</strong></h4><ul><li>When a client sends a message (POST/GET/PUT/..) to the server using HTTP, the data is not encrypted and can be read by middle men.</li><li>HTTPS (HTTP + TLS) enables secure client to server communication by encrypting the HTTP messages</li><li>To start the encrypted communication, the client needs to first verify the public key and certificate of the server and share a symmetric key to encrypt the messages. This is done by a TLS handshake.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*osQd2lLFNWcqPUYf2gzl_g.png" /><figcaption>TLS Handshake</figcaption></figure><ul><li>Even though the content (Request body, headers, cookies,..) are encrypted, middle men can still see the source IP, destination IP and content size</li><li>This is where a VPN comes in which hides the source IP, destination IP and other information not encrypted by HTTPS</li></ul><pre>HTTP:<br>Client ──► Server<br><br>HTTPS:<br>Client ──TLS──► Server<br><br>HTTPS + VPN commercial:<br>Client ──TLS──► [ VPN tunnel ] ──► Server<br><br>HTTPS + VPN entreprise:<br>Client ──TLS──► Proxy ──TLS──► Server</pre><ul><li>It is important to note that commercial VPNs (Nord VPN, Proton VPN,..) work differently from Enterprise VPNs (Cisco AnyConnect, PaloAlto GlobalConnect, …)</li></ul><h4>Trust Store : Place where all the trusted certificates are stored</h4><ul><li>During the TLS handshake process, the client verifies if the “Public Key + Certificate” shared by the server by checking it’s presence in the trust store</li><li>In Linux systems, the trust store is usually located at the path: “/etc/ssl/certs/ca-certificates.crt”</li><li>In windows systems, the trust store can be found by searching certlm.msc (Machine trust store) and certmgr.msc (User trust store)</li><li>Browsers have their own trust stores as well and can be found in the settings</li></ul><h4>Python’s way of doing TLS handshake</h4><ul><li>Unlike other languages like JavaScript, Python doesn’t rely on OS trust store by default and it has it’s own trust store called <a href="https://github.com/certifi/python-certifi">certifi</a></li></ul><pre># Execute this code to see the trust store used by your Python<br>import requests, requests.certs<br>print(requests.certs.where())</pre><ul><li>Some Pythons are configured to use the system trust store, so run the above code to check if your python is using system’s or certifi’s trust store</li></ul><h4>Why does Python scream in case of Enterprise VPNs but not commercial VPNs?</h4><ul><li>Enterprise VPNs work differently compared to Commercial VPNs</li></ul><pre>HTTPS + commercial VPN:<br>Client ──TLS──► [ VPN tunnel ] ──► Server<br><br>HTTPS + enterprise VPN:<br>Client ──TLS──► Proxy ──TLS──► Server</pre><ul><li>Enterprise VPNs use an HTTPS proxy and can clearly see the content of your messages unlike commercial VPNs . This is done to abide to company’s policies.</li><li>In short, with commercial VPNs the client performs a TLS handshake with the server and with enterprise VPNs, the client performs a TLS handshake with VPN’s HTTPS proxy and then later the VPN performs a TLS handshake with the Server.</li><li>The problem is not HTTPS. The problem is where TLS is terminated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*0Kb8Bykk6DMlAUG_oIQOWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*u0IUZXVjlP-jMLZ3tKlVwQ.png" /></figure><ul><li>Your company ensures that the VPN’s certificates are added to your OS’s trust store but they don’t have any control over the certs in certifi trust store</li><li>It is possible that your python is configured to use your OS’s trust store in which case Python won’t scream when it sees your VPN’s certificate</li></ul><h4>How to make Python using the right trust store with your company VPN’s certificate?</h4><ul><li>Quick reminder, the reason why the browser in your company laptop is able to make API calls and access websites via HTTPS with VPN enterprise enabled is because it is using a trust store with your enterprise VPNs certificates</li><li>We can export these certificates into a file which we can later use for Python</li><li>This is a pragmatic workaround. Ideally, only the enterprise root CA should be trusted, but extracting it can be difficult without IT support.</li></ul><pre>your browser ──► settings ──► security settings ──► <br>Manage certificates ──► Export certificates</pre><ul><li>Follow the above steps to export the certificates into a file (Base 64 encoded format)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Vv5aD4C0KArQcHij_itmw.png" /><figcaption>Make sure to select Base 64 encoded format type</figcaption></figure><ul><li>Copy the exported file path and now, you can configure your python to use this trust store instead of certifi</li></ul><pre># Global trust store reconfiguration<br>import os<br>os.environ[&quot;SSL_CERT_FILE&quot;] = &quot;trusted_certs.crt&quot;<br>os.environ[&quot;REQUESTS_CA_BUNDLE&quot;] = &quot;trusted_certs.crt&quot;<br>import requests # Requests needs to be imported post env vars declaration<br>r = requests.get(&quot;https://www.example.com&quot;)</pre><pre># One-time trust store reconfiguration<br>import requests<br>r = requests.get(&quot;https://www.example.com&quot;, verify=&quot;trusted_certs.crt&quot;)</pre><ul><li>You can configure the trust store usage globally or just for one-time usage</li><li>Once configured, you can can verify if your SSL/TLS certificates problem is solved</li></ul><p>It is important to note that trusting too many certificates can lead to security issues in the future and expose you to “Man in the Middle” attacks.</p><h4>Badly formed certificates Python error</h4><pre>certificate verify failed: Missing Authority Key Identifier</pre><ul><li>Sometimes, even though Python is referencing the right trust store, you will still get SSL/TLS errors</li><li>These errors could be related to certificates not respecting the SSL guidelines</li></ul><pre>import ssl<br>print(ssl.OPENSSL_VERSION)</pre><ul><li>Try printing the SSL version that your python is using and verify if your VPNs certificates are not following the formatting rules enforced by that particular SSL version</li><li>In order to fix this, you need to find a Python which has been built with the compatible SSL version for your VPN’s certificates. Try using a Python built with a downgraded SSL version which might fix the problem</li><li>This process of finding the right version can be quite ardous. The best thing to do is to check with your IT department if you don’t manage to find a compatible SSL version</li></ul><h4>References</h4><ul><li>SSL/TLS Explained : <a href="https://youtu.be/j9QmMEWmcfo?si=PH_ZC__FkstdYHpc">YouTube</a></li><li>VPNs explained : <a href="https://youtu.be/R-JUOpCgTZc?si=A9-kd-kkkb1gR47Q">YouTube</a></li><li>Python Requests + SSL : <a href="https://requests.readthedocs.io/en/latest/user/advanced/">Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a360aed277f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can You Store Images, Audio Files, Documents, and More in SQL/NoSQL Databases?]]></title>
            <link>https://levelup.gitconnected.com/can-you-store-images-audio-files-documents-and-more-in-sql-nosql-databases-da0932b766dc?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/da0932b766dc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 16:17:49 GMT</pubDate>
            <atom:updated>2025-07-09T16:17:49.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*yVF2J2sE1H9yvuP4" /></figure><p>Databases — SQL or NoSQL — easily store numbers, text, booleans and dates. But what about files like photos, audio or PDFs? Most teams work around this by saving the file itself on disk or in an object store (S3, Azure Blob) and only keeping its path in the database. In this article, you’ll see how a simple Base64‐encoding trick lets you embed any file — image, audio or document — directly in your database’s text (or BLOB) field, no extra storage service needed.</p><h3>Standard approach to store unstructured assets</h3><p>Most web apps handle photos, audio and documents by offloading the raw file to a dedicated store (disk or object storage) and keeping only a tiny pointer in the database. Let’s see it in action with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eBxPp_EZ4rYbRJjz" /></figure><p>Let’s take Instagram for example. When a user creates a post in Instagram with the an image and post description (Caption, location, Time, etc), Instagram behind the scenes stores the image in AWS S3 Object Store which returns a URL for the image which along with the other post data is stored in a row of a PostGres table.</p><p>This is the same approach used by many other web applications to store unstructured assets.</p><h4>Drawbacks:</h4><ul><li>Scaling and back-up becomes complicated</li><li>Implementation is quite complex</li><li>Requires maintainance of both the database and the object data store</li></ul><p>If we can store these unstructured assets as well in SQL/NoSQL databases, we can store all data in a single place which makes versioning and backup a lot easier.</p><h3>Base64 Encoding</h3><p>Using Base64 encoding, we can convert Binary data into ASCII only Strings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wrIW7NSvU9tuAhS4" /></figure><p>Every file on disk (images, audio, PDFs, etc.) is just a stream of bytes under the hood, and Base64 gives you a way to turn those bytes into a plain-text string.</p><h4>How does Base64 Encoding convert Binary data to ASCII Strings?</h4><p>You can read the binary data of any file in python using the following code:</p><pre>with open(file_path, &quot;rb&quot;) as f:<br>    raw_bytes = f.read()<br>bits = &#39;&#39;.join(format(byte, &#39;08b&#39;) for byte in raw_bytes)<br>print(bits)</pre><p><strong><em>Algorithm to convert Binary bit data into ASCII string using Base64:</em></strong></p><ol><li>Let’s consider an example bit stream : 0x4D 0x61 0x6E -&gt; 01001101 01100001 01101110</li><li>Split it into buckets of 6-bit values -&gt; 010011 010110 000101 101110</li><li>If the number of bits is not a multiple of 6, then you add zero-bit padding</li><li>Map each 6-bit number to an ASCII character using the Base64 mapping</li></ol><pre>Index:   0 … 25   26 … 51   52 … 61   62   63   \0(padding)<br>Chars:   A–Z      a–z       0–9       +    /    =</pre><p>5. Applying the above mapping, we get TWFu (ASCII string)</p><p>That is pretty much the algorithm to convert any file into ASCII strings using Base64 encoding.</p><p>Here is the python code to convert a file to base64 encoding and then decode it back to the original file:</p><pre>import base64<br>with open(file_path, &quot;rb&quot;) as f:<br>    raw_bytes = f.read()<br># Encoding<br>b64 = base64.b64encode(raw_bytes)  <br>ascii_string = b64.decode(&#39;ascii&#39;)<br># Decoding<br>decoded = base64.b64decode(ascii_string)</pre><h3>Store unstructured assets (Images, Audio files, PDFs, etc) into databases</h3><p>Now, Using base64, we can simply convert the image in the above instagram system flow into ASCII string and store it right in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zUsRa_FEOLSXb2Z3" /></figure><p>All the data uploaded by the user including unstructured assets can be stored directly in the database instead of uploading the data to server hard disk or Object store and storing that path in the database.</p><p><strong>Drawbacks of Base64:</strong></p><ol><li>Base64 turns 3 bytes (3 x 8 bits = 24 bits) into 4 ASCII characters (24/6) and each ASCII character needs 1 byte storage. So, 3 bytes data is stored as 4 bytes in ASCII which is a 33% increase of file size</li><li>Base64 Encoding/Decoding conumes additional CPU resources</li><li>SQL/NoSQL engines have size limits on the max string that can be stored, so we have a max file size beyond which base64 into database solution becomes invalid</li></ol><h3>Example standard and base64 based web application</h3><p>To make things clearer, I deployed 2 versions of the same Flask application where a user can upload images and all the uploaded images will be shown in the site.</p><ol><li>Standard approach : Uploaded files stored in server hard disk and the pointer is pushed to the SQLite database (<a href="https://github.com/shivaditya-meduri/Articles/blob/main/unstructuredAssetsInDatabases/classic/app.py">GitHub</a>)</li><li>Base64 approach : Uploaded files are converted to Base64 encoding and is stored directly in the database (<a href="https://github.com/shivaditya-meduri/Articles/blob/main/unstructuredAssetsInDatabases/base64based/app.py">GitHub</a>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-EEmHLdCQMfxKeogrUTcg.png" /><figcaption>Preview of the application</figcaption></figure><p><strong>Classic upload function of the Flask app</strong></p><pre>@app.route(&#39;/upload&#39;, methods=[&#39;POST&#39;])<br>def upload():<br>    f = request.files.get(&#39;file&#39;)<br>    desc = request.form.get(&#39;description&#39;, &#39;&#39;)<br>    if not f:<br>        return redirect(url_for(&#39;index&#39;))<br><br>    ext = os.path.splitext(f.filename)[1]<br>    unique_name = f&quot;{uuid.uuid4().hex}{ext}&quot;<br>    save_path = os.path.join(app.config[&#39;UPLOAD_FOLDER&#39;], unique_name)<br>    f.save(save_path)<br><br>    session = Session()<br>    rec = FileRecord(filename=unique_name, description=desc)<br>    session.add(rec)<br>    session.commit()<br>    session.close()<br><br>    return redirect(url_for(&#39;index&#39;))</pre><p>In the classic approach, as you can see we first store the file in the server’s hard disk and then store the path in the SQLite database.</p><p><strong>Base64 based upload function of the Flask app:</strong></p><pre>@app.route(&#39;/upload&#39;, methods=[&#39;POST&#39;])<br>def upload():<br>    upload = request.files.get(&#39;file&#39;)<br>    desc   = request.form.get(&#39;description&#39;, &#39;&#39;)<br><br>    if not upload:<br>        return redirect(url_for(&#39;index&#39;))<br><br>    raw = upload.read()<br>    b64  = base64.b64encode(raw).decode(&#39;ascii&#39;)<br>    rec  = FileRecord(<br>        filename=upload.filename,<br>        mimetype=upload.mimetype,<br>        data=b64,<br>        description=desc<br>    )<br><br>    session = Session()<br>    session.add(rec)<br>    session.commit()<br>    session.close()<br><br>    return redirect(url_for(&#39;index&#39;))</pre><p>In the base64 based approach, the file is directly being stored in the SQLite database.</p><h3><strong>Conclusion</strong></h3><p>Many SQL/NoSQL databases offer native binary (BLOB/BinData) columns, but support — and APIs — aren’t standardized everywhere.</p><p>• Big media at scale: Keep files in disk or object stores (S3, Azure Blob, etc.) and save only the URL/pointer in your DB for performance, CDN-caching and easy scaling.</p><p>• Tiny assets or quick demos: Base64-encode and store directly in your TEXT/BLOB column (with the trade-off of ~33% extra storage) when spinning up an object store feels overkill.</p><p>Thanks for reading, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da0932b766dc" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/can-you-store-images-audio-files-documents-and-more-in-sql-nosql-databases-da0932b766dc">Can You Store Images, Audio Files, Documents, and More in SQL/NoSQL Databases?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Optimization Algorithm That Saves Lives, Delivers Pizza, and Streams Video Faster]]></title>
            <link>https://levelup.gitconnected.com/the-optimization-algorithm-that-saves-lives-delivers-pizza-and-streams-video-faster-61bb67d74905?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/61bb67d74905</guid>
            <category><![CDATA[operations-research]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 20:02:51 GMT</pubDate>
            <atom:updated>2025-07-09T14:23:55.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*oN_BkwQG1HLt4D1LOKtqCg.png" /></figure><p>Have you ever wondered how a pizza can arrive at your door in under 30 minutes? Or how a movie streams instantly on your phone with no buffering? Or, most critically, how an ambulance can reach a person in distress in just a few precious minutes?</p><p>The answer to all these questions isn’t just good service — it’s a brilliant application of mathematics. The ability to provide these services quickly and efficiently depends entirely on solving one of the most important logistical puzzles in business and public safety: <strong>the facility location problem</strong>. Getting the location right can mean the difference between a hot meal and a cold one, a happy customer and a lost one, and even life and death.</p><p>In this article, we’ll explore the science of “where.” We will break down a common facility location problem, learn how to frame it as a mathematical model, and understand the powerful algorithm industries use to find the single best spot.</p><h3>Facility Location Problem</h3><p>Facility location problem involves deciding where exactly to position facilities (Ambulance Centers, Pizzerias, Data Centers,…) to serve the demand hotspots while optimizing a metric (Average delivery time, worst case response time, transportation costs, etc).</p><p>The problem involves not only deciding where to place the facilities, but also deciding which facility will be allocated to which demand hotspot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRZt6y65xzj7G9giay_aMg.png" /></figure><p>The starting point to formulate and solve the optimization problem is to gather the demand data. This data consists of various demand hotspots and the actual demand for each of the hotspots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*L7C8xbBAcnPzg6vDGdSTMw.png" /><figcaption>Example demand data</figcaption></figure><p>The weight column which represents the actual demand depends upon the use case. Below, you can find a few examples:</p><ol><li>Ambulance Centers : Average no. of emergency calls per hour/day</li><li>Pizzerias : Average no. of orders per hour/day</li><li>Internet Companies : Average no. of active users per hour/day</li><li>Population Density in case of no historical data</li></ol><p>Once we have this data, we can start working on finding the optimal facility locations.</p><p>If we don’t already have the possible facility locations, we assume that the demand locations are the possible facility locations.</p><h4>Mathematical formulation of the Facility Location Problem</h4><p><strong><em>Parameters:<br></em></strong>1. p: Max number of facilities that can be opened (Budget constraints)<br>2. h_i​: The demand or “weight” at location<br>3. d_ij​: The distance, cost, or travel time between demand location i and facility location j (Haversine distance)</p><p><strong><em>Decision Variables:<br></em></strong>1. y_j​ (Binary Variable) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*A2vyRO0Xkxj6pkA0wjPFxA.png" /></figure><p>2. x_ij (Binary Variable)​ :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*N8UUBmF5pxNDFybyb-v1HQ.png" /></figure><p><strong><em>Objective Function &amp; Constraints:<br></em></strong>The objective function to be optimized and the constraints depends upon the use case. For Pizzerias or Internet companies, we might be interested in the average response time but for ambulance centers we would like to optimize the worst case response time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJsUku57WSAyr3ARtbTZxw.png" /><figcaption>Minimize Average Response Time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGCBM2Hr2l2beDSVpVS4dw.png" /><figcaption>Minimize worst case response time</figcaption></figure><p>As we can see from the formulations, the objective function and all the constraints are linear expressions of the decision variables. Furthermore, the decision variables are not all continuous; some are restricted to be integers (specifically, binary 0 or 1).</p><p>Because these models feature a linear objective, linear constraints, and a mix of integer and continuous variables, they belong to a class of problems known as <strong>Mixed-Integer Linear Programming (MILP)</strong>.</p><h4>Algorithm to solve Mixed Integer Linear Programming Problems</h4><p>The algorithm that is used in the industry to solve Mixed Integer Linear Programming problems is the <strong>Branch and Cut</strong> algorithm.</p><p>There are several solvers available including but not limited to Microsoft Excel’s inbuilt solver, CPLEX, Gurobi, Google OR-tools, etc which are used by companies to apply Branch and Cut algorithm to find the optimal facility locations for their use-cases.</p><p>We also have a Python library <a href="https://pypi.org/project/PuLP/">PuLP</a> which we can use. Below is an example on how one can use PuLP for the facility location problem on some random data.</p><p>Below is the code to generate some random demand data.</p><pre>import numpy as np<br>import pandas as pd<br><br># Generate synthetic “Paris” demand<br>np.random.seed(1)<br>n = 30<br>demand = pd.DataFrame({<br>    &#39;id&#39;:     range(n),<br>    &#39;lat&#39;:    np.random.uniform(48.80, 48.90, n),<br>    &#39;lon&#39;:    np.random.uniform(2.25, 2.40, n),<br>    &#39;weight&#39;: np.random.randint(5, 50, n)    # orders per hour<br>})<br># Candidate sites = same centroids<br>sites = demand.rename(columns={&#39;id&#39;:&#39;site_id&#39;})<br><br># Haversine function<br>def haversine(lat1, lon1, lat2, lon2, R=6371):<br>    φ1, φ2 = np.radians(lat1), np.radians(lat2)<br>    Δφ     = φ2 - φ1<br>    Δλ     = np.radians(lon2 - lon1)<br>    a = np.sin(Δφ/2)**2 + np.cos(φ1)*np.cos(φ2)*np.sin(Δλ/2)**2<br>    return 2*R*np.arcsin(np.sqrt(a))<br><br># Precompute distances<br>dist = {<br>    (i,j): haversine(demand.loc[i,&#39;lat&#39;], demand.loc[i,&#39;lon&#39;],<br>                     sites.loc[j,&#39;lat&#39;],  sites.loc[j,&#39;lon&#39;])<br>    for i in demand.id<br>    for j in sites.site_id<br>}</pre><p>Now that we have the data, we can use PuLP’s LpProblem class to find the optimal locations. <br>Here is the code to find the optimal facility locations using PuLP on the above data:</p><pre>import pulp<br>def solve(p):<br>    # 1. Initialize Model<br>    prob = pulp.LpProblem(&quot;facilityLocationProblem&quot;, pulp.LpMinimize)<br><br>    # 2. Define Variables<br>    x = pulp.LpVariable.dicts(&quot;x&quot;, sites.site_id, cat=&#39;Binary&#39;)<br>    y = pulp.LpVariable.dicts(&quot;y&quot;, [(i,j) for i in demand.id for j in sites.site_id], cat=&#39;Binary&#39;)<br><br>    # 3. Objective Function<br>    prob += pulp.lpSum(<br>        demand.loc[i,&#39;weight&#39;] * dist[(i,j)] * y[(i,j)]<br>        for i in demand.id for j in sites.site_id<br>    )<br><br>    # 4. Constraints<br>    # Exactly p facilities open<br>    prob += pulp.lpSum(x[j] for j in sites.site_id) == p<br><br>    # Assignment and linking constraints<br>    for i in demand.id:<br>        # Each demand point must be assigned to exactly one site<br>        prob += pulp.lpSum(y[(i,j)] for j in sites.site_id) == 1<br>        for j in sites.site_id:<br>            # A demand point can only be assigned to an open site<br>            prob += y[(i,j)] &lt;= x[j]<br><br>    # 5. Solve<br>    prob.solve(pulp.PULP_CBC_CMD(msg=0))<br><br>    # 6. Get Results<br>    obj = pulp.value(prob.objective)<br>    opened = [j for j in sites.site_id if x[j].varValue &gt; 0.5]<br>    return obj, opened</pre><p>You can find the complete code here : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/facilityLocationMILP/usingPuLP.py">GitHub</a></p><p>We can plot the best result as a function of the number of facilities to see how the objective function changes as the number of facilities change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rs4YOCbWpkh0LRbIrOyNSQ.png" /></figure><p>We can see that the drop is not linear. After 4–5 facilities, adding new facilities will not drop the average weighted distance significantly.</p><p>To learn more about PuLP, you can chekout the documentation : <a href="https://coin-or.github.io/pulp/">link</a></p><h4>Branch and Cut Algorithm Explained</h4><p>Even though, we have a lot of libraries we can use to run the branch and cut optimization algorithm, It can also be beneficial to understand how this algorithm works.</p><p>The brute force approach to solve the above optimization problem is to test every possible combination of the decision variables (y_j and x_ij).<br>If we consider that we are analyzing d demand locations and f facility locations, then the number of possible combinations that we need to test is 2^(d*f). The time complexity is exponential.</p><p>Even though, we can reduce the search space with branch and cut, the time complexity is still exponential.</p><p><strong>It has been proven mathematically that Integer Linear Programming is an NP-Hard problem.</strong></p><p>Before we understand how the branch and cut algorithm reduces the exponential search space, it is a prerequisite to understand the Simplex Algorithm.</p><h4>Simplex Algorithm Explained</h4><p>When we have continuous decision variables, linear constraints and linear objective functions, we can use the geometric method (≤ 2 decision variables) or the simplex method (&gt;2 decision variables) which can give us the optimum solution quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*OPNvRKdBfQSZMRYo.png" /><figcaption>Example of solving a Linear Programming problem using the geometric method</figcaption></figure><p><strong><em>Geometric method:<br></em></strong><em>1. Draw the curves for the linear contraints in a graph<br>2. Find the feasible region which is the intersection of acceptable search space for all the constraints<br>3. The objective function maximum/minimum should lie in one of the vertices, so if we check all the vertices, we should find the global maximum/minimum<br>4. The global optimum can be found on one of the vertices because when we sweep the objective function vector in the desired direction, it stops at a vertex or an edge with vertices in the feasible region beyond which it is no longer in the feasible region</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FY7e7DCsDUMY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DY7e7DCsDUMY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FY7e7DCsDUMY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/44cf21ef9ff3332f5f458f6894aa86e3/href">https://medium.com/media/44cf21ef9ff3332f5f458f6894aa86e3/href</a></iframe><p>Geometric method cannot be applied if the number of decision variables is greater than 2 as it is not convenient to draw 3D, 4D, 5D, etc graphs to visualize the feasible region and find the vertices.</p><p><strong><em>Simplex Algorithm:<br>1. Prepare the Problem:</em></strong><em> Start by converting all inequality constraints into equalities by adding &quot;slack variables.&quot; This sets up our starting point.<br>2. </em><strong><em>Start at a Vertex:</em></strong><em> The algorithm begins at a starting feasible corner point, which is usually the origin (where all main variables are zero).<br>3.</em><strong><em> Find the Best Move:</em></strong><em> The algorithm now intelligently decides where to go next.</em></p><ul><li><strong><em>A) Find the Best Direction:</em></strong><em> It checks which variable, if increased, will improve the objective function the most. This identifies the best &quot;path&quot; to take away from the current corner.</em></li><li><strong><em>B) Find How Far to Go:</em></strong><em> It calculates the maximum amount it can travel in that direction before hitting another boundary (constraint) of the problem.</em></li></ul><p><strong><em>4. Move to the Next Vertex:</em></strong><em> The algorithm &quot;pivots&quot; to the new corner point identified in the previous step. This new corner is guaranteed to have a better or equal objective value.<br>5. </em><strong><em>Check for Optimality:</em></strong><em> Once at the new vertex, the algorithm checks again: is there any direction to move that will improve the objective further?</em></p><ul><li><em>If </em><strong><em>YES</em></strong><em>, it repeats from Step 3.</em></li><li><em>If </em><strong><em>NO</em></strong><em>, it means we are at the optimal corner. The algorithm stops and returns the current solution as the final, best answer.</em></li></ul><p>The algorithm is quite complex and beautiful. To understand it much better, I highly recommend watching the following video.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FE72DWgKP_1Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DE72DWgKP_1Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FE72DWgKP_1Y%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aba16e14fba9c54b442177a1bea3d2e/href">https://medium.com/media/4aba16e14fba9c54b442177a1bea3d2e/href</a></iframe><p>Implementation of the simplex algorithm in python : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/facilityLocationMILP/simplex.py">GitHub</a></p><p><strong><em>Branch and Cut Algorithm:<br>1. Relax:</em></strong><em> Take the integer problem, relax the integer constraints to be continuous, and solve this LP to get a fractional solution and a “best-case” bound.<br>2. </em><strong><em>Cut:</em></strong><em> Add special constraints called “cuts” that slice off the current fractional solution without removing any valid integer solutions, then re-solve the LP.<br>3. </em><strong><em>Branch:</em></strong><em> If the solution is still fractional, pick a fractional variable and create two new subproblems, one where the variable is forced to </em><em>0 and one where it&#39;s forced to </em><em>1.<br>4. </em><strong><em>Prune:</em></strong><em> As you solve these subproblems, discard any branch whose “best-case” bound is worse than the best integer solution you’ve found so far.<br>5. </em><strong><em>Repeat:</em></strong><em> Continue this process of relaxing, cutting, branching, and pruning until all branches have been explored or pruned. The best integer solution found is the proven optimum.</em></p><p>Simply put, instead of exploring the whole search space, we guide the search space exploration with the power of Simplex Algorithm and relaxing the integer constraints until we find the optimum.</p><p>I also recommend going through this video which explains how to implement Branch and Cut to solve an Integer Linear Programming Problem.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FupcsrgqdeNQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DupcsrgqdeNQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FupcsrgqdeNQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4a5dbd18c9a0555b1f8551f7792ccac/href">https://medium.com/media/c4a5dbd18c9a0555b1f8551f7792ccac/href</a></iframe><p>Implementation of the Branch and Cut algorithm in Python : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/facilityLocationMILP/branchAndCut.py">GitHub</a></p><h4>Closing remarks</h4><p>In this article, we’ve laid out the classic foundations for solving the Facility Location Problem, from its formulation as a MILP to the elegant logic of the Simplex and Branch and Cut algorithms. These methods are the bedrock of industrial optimization and have been for decades.</p><p>So, the next time you stream a video without buffering or see an emergency vehicle racing to the scene, you’ll know it’s not just good luck — it’s the power of optimization. These algorithms, running silently in the background, are the unsung heroes of efficiency, turning complex mathematical theory into a faster, safer, and more convenient reality for us all.</p><p>Thank you for reading my article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61bb67d74905" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-optimization-algorithm-that-saves-lives-delivers-pizza-and-streams-video-faster-61bb67d74905">The Optimization Algorithm That Saves Lives, Delivers Pizza, and Streams Video Faster</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide to Lossless Compression Algorithms]]></title>
            <link>https://medium.com/@mvenkatashivaditya/the-ultimate-guide-to-lossless-compression-algorithms-2b040976a6ee?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b040976a6ee</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 19:55:18 GMT</pubDate>
            <atom:updated>2025-06-01T19:55:18.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*sChJ6mXJ7MiC9uIupCsu-w.png" /></figure><ol><li>What happens behind the scenes when you compress a file/folder?</li><li>How to choose between different compression types : .zip, .xz, .gz, .bz2,..?</li><li>What happens when you compress an already compressed file?</li></ol><p>These are some of the questions that I was curious about and in this article, I would like to explore the world of lossless compression algorithms and answer the above questions.</p><h4>Types of compression algorithms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6NxuZdyjRhn2tcbumkf6g.png" /></figure><p>As the topic of discussion is quite vast, for this article I am sticking to only lossless compression algorithms. In the future, I am also planning to publish an article concerning lossy compression algorithms.</p><h4>Archiver &amp; Compressor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRwydiosTuHimyLZKouiEA.png" /></figure><p>Archiver: Bundles multiple files into a single container</p><p>Compressor: Applies compression algorithms to data to make it smaller</p><p>It is important to note that a directory or a set of files needs to be archived before being compressed, but a standalone file can be compressed directly without archiving.</p><h4>Most used compression tools</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ce277ce98a7cd437c3b1b88e579b040/href">https://medium.com/media/2ce277ce98a7cd437c3b1b88e579b040/href</a></iframe><p>.zip and .7z offer in-built archivers and we don’t need to separately archive a directory. .xz, .bz2 and .gz don’t have built in archivers, therefore the directories need to be archived if multiple. If it is a stand-alone file, then we don’t have to archive it.</p><p>.tar is just an archiver and it is not a compressor. It is used to archive a set of files which can later be compressed with a compressor especially the ones that don’t have built-in archivers.</p><h3>Compression Algorithms</h3><p>Behind the scenes, most formats just share one of three engines:</p><ol><li>DEFLATE : powers both .zip and .gz</li><li>LZMA2 : powers both .7z and .xz</li><li>Burrows-Wheeler Transform + Run-length Encoding + Huffman : powers .bz2</li></ol><h3><strong>DEFLATE</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_ci2RgdrbUKMUuRs4k8Ow.png" /></figure><p>Deflate under-the-hood isa combination of LZ77 compression followed by Huffman coding.</p><p><strong>LZ77 compression</strong></p><p>LZ77 compression algorithm was introduced by Lempel-Ziv in the year 1977. Here is the link to their original paper : <a href="https://courses.cs.duke.edu/spring03/cps296.5/papers/ziv_lempel_1977_universal_algorithm.pdf">link</a></p><p>The core idea of LZ77 is to find repitions of a sequence of data and replace them by references to previous occurences.</p><p>Here is a very simple example of the idea:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*DWxUtFmnY22WbycPRntnUg.png" /><figcaption>Demonstration of core idea of LZ77</figcaption></figure><p>In the above example, instead of repeating the “ bbbb”, we can just refer to it’s first occurrence and the length for which it has to be repeated.</p><p><strong>LZ77 algorithm</strong></p><p>We scan the input data stream with a sliding window. <br>The sliding window has 2 components : Search Buffer + Look Ahead Buffer</p><ol><li>Initialize: Empty search buffer, fill lookahead buffer.</li><li><strong>Find Longest Match:</strong> Search for the longest sequence in the lookahead buffer that also exists in the search buffer.</li><li>If a match is found: Output a <strong>(distance, length, next_character)</strong> triplet.<br>distance: How far back in the search buffer the match starts.<br>length: The length of the matched sequence.<br>next_character: The character in the lookahead buffer immediately following the match.</li><li>If no match is found: Output a <strong>(0, 0, first_character_in_lookahead)</strong> triplet.</li><li><strong>Slide Window:</strong> Shift the search buffer window forward by length + 1 characters.</li><li>Repeat from step 2 until the lookahead buffer is empty.</li></ol><p>Below, you will find the dry run of LZ77 compression algorithm on the input data stream “ABABCBCBAABCABe” with search buffer size = 4 and look ahead buffer size = 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*Mq12iuhpd9-Aaj64R54xkw.png" /></figure><p>“<strong>ABABCBCBAABCABe</strong>” is compressed to:<br><strong>(0,0,A),(0,0,B),(2,2,C),(2,3,A),(1,1,B),(0,0,C),(3,2,e)</strong></p><p>LZ77 is more effective on input data which has a lot of repition. On random data without any repition like an already compressed file, LZ77 will increase the file size as it adds distance and length information for each pointer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2lOyTBsZuLSYGC3EpIEuQ.png" /></figure><p>In the above image, I tried to compress an already gzip compressed csv file and you can see that the file size increased from 1173 bytes to 1208 bytes.</p><p>Python implementation of LZ77 algorithm : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/lossLessCompressionAlgorithms/lz77.py">GitHub</a></p><p><strong>Huffman Coding</strong></p><p>Huffman coding algorithm was introduced by David A Huffman in the year 1952. Here is the link to his original paper : <a href="https://compression.ru/download/articles/huff/huffman_1952_minimum-redundancy-codes.pdf">link</a></p><p>The core idea of huffman coding is to represent high frequency characters with smaller codes when compared to lower frequency characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJ5jB1W6dwnKBVNt1_mDCg.png" /><figcaption>Huffman Coding Example</figcaption></figure><p><strong>Huffman Coding Algorithm</strong></p><ol><li>Calculate frequency of each character in the input text</li><li>Create a priority queue (min‐heap) where each entry is (frequency, node)<br>• Initially, each node is a leaf labeled with one character</li><li>While the queue has more than one node:<br> a. Remove the two nodes with the smallest frequency from the queue<br> b. Create a new internal node:<br> • frequency = sum of the two removed nodes’ frequencies<br> • left child = first removed node<br> • right child = second removed node<br> c. Insert the new internal node back into the queue</li><li>The single remaining node in the queue is the root of the Huffman tree</li><li>Generate binary codes for each character by traversing the tree:<br> • assign “0” to each left edge, “1” to each right edge<br> • when you reach a leaf, record its path as that character’s code<br> • (if there is only one unique character, assign it code “0”)</li><li>Encode the input text by replacing each character with its binary code, producing one long bit‐string</li><li>return the encoded bit‐string and the Huffman tree (or code table) for decoding</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLY2Xdh3mEoNGgSo4HiYcA.png" /><figcaption>Dryrun of Huffman Coding on an example data stream</figcaption></figure><p>Python implementation of Huffman Coding algorithm : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/lossLessCompressionAlgorithms/huffmanEncoding.py">GitHub</a></p><p><strong>Deflate = LZ77 + Huffman</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4Du_jgiua9RcDZX0PEOsg.png" /></figure><p>In Deflate, we first run LZ77 compression and then we build 2 huffman trees, one for Literals + Length and other for distances, encode the data and return the output data stream.</p><p>The is what is happening behind the scenes for .zip and .gz compression formats.</p><h3>LZMA2</h3><p>LZMA 2 stands for Lempel–Ziv–Markov chain algorithm and it is the algorithm that powers .xz and .7z compression formats.</p><p>In LZMA 2, the input file is divided into chunks and we apply the LZMA algorithm for each chunk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udQb0OCdKpTei-2hMjztYA.png" /></figure><p>LZMA algorithm under-the-hood applies LZ77 compression that we discussed earlier and then applies Range Coding instead of Huffman Coding.</p><p><strong>Range Coding</strong></p><p>Huffman coding, though efficient is not perfect.</p><p><strong><em>Ideal Number of bits for each symbol:</em></strong><em><br></em>Let’s assume that we have N equally likely symbols where the probability of each symbol is p(s) = 1/N. To be able to give a unique binary code for each of the N different symbols, we need log₂(N) bits. So, to represent a symbol with p(s) probability, we need log₂(1/p(s)) bits ideally.</p><p>Claude Shannon, in his foundational work on information theory, established that the ideal measure of information content for a symbol s with probability P(s) is given by -log₂(P(s)) bits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7_N916Y3Ryev3uijCqbzQ.png" /><figcaption>Example showing Huffman Coding is not ideal</figcaption></figure><p>In the above example, we can see that for probability distributions which are not powers of 1/2 , huffman codes are not the most efficient.<br>We need to be able to assign fractional bits to each symbol in that case which we can do with the help of Range Coding.</p><p><strong><em>Range Coding Algorithm:</em></strong></p><ol><li><strong>Initialization:</strong></li></ol><ul><li>Start with a current range, let’s say low = 0 and high = 1.</li><li>Have the probability (or frequency count) for each possible symbol in your data.</li></ul><p><strong>2. Encoding Symbol by Symbol:</strong></p><ul><li>For each symbol in your input:</li><li>Calculate the portion of the current range that this symbol occupies based on its probability.</li><li>range_width = high - low</li><li>Update high to low + range_width * (cumulative probability up to and including the current symbol).</li><li>Update low to low + range_width * (cumulative probability up to but not including the current symbol).</li><li>This new low and high define a smaller interval.</li></ul><p><strong>3. Final Output:</strong></p><ul><li>After processing all symbols, the final low value (or any number within the final [low, high) interval) uniquely represents the entire sequence of symbols. This value, expressed with enough precision, is your encoded message.</li></ul><p><strong><em>Range Coding Example</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7vfqhoJVwuc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7vfqhoJVwuc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7vfqhoJVwuc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9234cc3e58c1f06f2e99271b246a1b8f/href">https://medium.com/media/9234cc3e58c1f06f2e99271b246a1b8f/href</a></iframe><p>I recommend watching the above video which clearly walksthrough an example of Range Encoding.</p><p><strong><em>Complete LZMA flow</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*gkAKkzr2Wgjl8Qj9PpLB9g.png" /></figure><p>LZMA takes LZ77 outputs (literals or length/distance pairs) and decomposes them into a sequence of many smaller, context-dependent binary decisions, each of which is then individually range encoded using a highly specific probability for that decision’s context.</p><h4>Compression Levels for LZMA and Deflate</h4><ol><li><strong>Lower Levels (Faster, Less Compression):</strong></li></ol><ul><li>Spend less time searching for matches.</li><li>May use simpler or predefined probability models (e.g., static Huffman tables in Deflate).</li><li>Use smaller dictionary sizes or search windows.</li><li>Faster processing speed.</li><li>Lower memory usage.</li><li>Results in larger compressed output.</li></ul><p><strong>2. Higher Levels (Slower, More Compression):</strong></p><ul><li>Perform more exhaustive searches for longer and/or more distant matches.</li><li>Often compute custom probability models (e.g., dynamic Huffman tables in Deflate) tailored to the specific data.</li><li>Use larger dictionary sizes or search windows.</li><li>Slower processing speed.</li><li>Higher memory usage (both for compression and sometimes for decompression).</li><li>Results in smaller compressed output.</li></ul><h4>Burrows-Wheeler Transform (BWT)</h4><p>Before explaining BWT, It is important to understand Run Length Encoding.</p><p><strong><em>Run Length Encoding:<br></em></strong>It is an extremely simple compression method where we replace a symbol with multiple occurences in a data stream with the symbol and it’s count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OadWFvSUg6askPgJXvESEA.png" /></figure><p>It works well when the data is sorted as similar symbols are grouped together.</p><p><strong><em>BWT Algorithm</em></strong></p><p>The core idea of BWT is to convert the data stream to a sorted data where similar characters are grouped together for efficient run length encoding along with the position information being preserved.</p><ul><li><strong>Create Rotations:</strong> Take all possible cyclic rotations of the input string.</li><li><strong>Sort Rotations:</strong> Sort these rotations lexicographically (alphabetically).</li><li><strong>Extract Last Column:</strong> The BWT output is the last character of each sorted rotation.</li><li><strong>Store Original Index:</strong> You also need to store the index of the original string in the sorted list of rotations. This index is crucial for reversing the transform.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGYbCttCF25A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGYbCttCF25A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGYbCttCF25A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d75b51bf7de47d1c33d1a8466f29ee88/href">https://medium.com/media/d75b51bf7de47d1c33d1a8466f29ee88/href</a></iframe><p>I recommend watching the above video from computerphile that goes through an example of BWT compression.</p><p>BWT algorithm implementation Python : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/lossLessCompressionAlgorithms/bwt.py">GitHub</a></p><h3>The Combined Process (BWT + RLE + Huffman)</h3><ol><li><strong>BWT:</strong> The input string is transformed using BWT. This groups identical characters together.</li></ol><ul><li>The BWT output string and the original index are produced.</li></ul><p><strong>2. RLE:</strong> The BWT output string is then encoded using RLE. This compresses the runs of identical characters created by BWT.</p><ul><li>The RLE output is a list of (character, count) tuples.</li></ul><p><strong>3. Huffman Coding:</strong> The RLE output (or symbols derived from it) is then encoded using Huffman coding.</p><ul><li>Frequencies of the RLE symbols are calculated.</li><li>Huffman codes are generated and used to encode the RLE output into a compact binary string.</li><li>The Huffman table (or information to reconstruct it) and the original BWT index must be stored alongside the compressed data to allow decompression.</li></ul><p><strong>Decompression:</strong> The process is reversed:</p><ol><li>Huffman Decode (using the stored Huffman table).</li><li>RLE Decode.</li><li>Inverse BWT (using the stored original index).</li></ol><h4><strong>Comparing different Compression Formats:</strong></h4><p>I created a simple test Python benchmark to measure the compression rates and the time taken for the compression formats gzip, lzma and bz2 on some dummy data.</p><p>Python Benchmark comparing Compression Algorithms : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/lossLessCompressionAlgorithms/comparingCompressionAlgos.py">GitHub</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*OFcfCa12Xn6oMm3T4n0FAQ.png" /></figure><p>In terms of compression speed: <br>gzip(Deflate) &gt; lzma(LZMA) &gt; bz2(BWT+RLE+Huffman)</p><p>In terms of compression rates, it is important to note that the compression ratio really depends on the nature of the data which is being compressed. The above benchmark is not representative of the order of the expected compression ratios for a given dataset.</p><p>I hope this article was able to give you an idea of what the frequently used loss less compression algorithms do behind the scenes. If you have any questions/comments, feel free to post them in the comment section below.</p><p>Thank you for reading my article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b040976a6ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linkedin Zip Puzzle Solver (Python)]]></title>
            <link>https://medium.com/@mvenkatashivaditya/linkedin-zip-puzzle-solver-python-953be08daab3?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/953be08daab3</guid>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[puzzle]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Sat, 24 May 2025 21:00:12 GMT</pubDate>
            <atom:updated>2025-05-24T21:00:12.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c5QtAWXGdk3OnflxqtULg.png" /></figure><p>Recently, I started playing the daily zip puzzle game on LinkedIn and I am quite enjoying it. I was curious to see if I can create a python code that can solve the zip puzzles instantly giving me an edge over the other players😉.</p><h3>Data Structures for the grid and the barriers</h3><p>Grid: 2D array | Barriers : List of sets of barrier adjacent cell positions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3iHVkDYBojI3Jclpak28Q.png" /></figure><p>The 2D array part is self explanatory. For the barriers part, I think it would be easier to understand with an example. For the above example, the first set of the barrier bricks list {(1, 2), (1,3)} just simply denotes the adjacent cells of a barrier brick and the same is repeated for all the barrier bricks.</p><h3>Zip Solver Algorithm</h3><p>The problem is essentially a path finding problem with some path constraints. One way to solve problems like this is with backtracking.</p><p>If you are not familiar with backtracking, you will find a lot of articles and videos on the internet explaining the concept.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgBC_Fd8EE8A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgBC_Fd8EE8A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgBC_Fd8EE8A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/20a83fb8f6e3a853bc72b1ee27a0f42d/href">https://medium.com/media/20a83fb8f6e3a853bc72b1ee27a0f42d/href</a></iframe><p><strong>Path Constraints</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*HcliHDNqaUMOP38-acdH1g.png" /></figure><p><strong>Zip Solver backtracking pseudo code</strong></p><pre>1. Set the current position to the starting cell (number = 1)<br>2. Check all the neighbours and satisfy path constraints:<br>    a. neighbour cell should be part of the grid<br>    b. no barrier between current cell and the neighbour cell<br>    c. if numbered cell, then it&#39;s number should be 1 more than the last number<br>3. For each valid neighbour, update the parameters and recursively call the function<br>4. if the end cell is reached and all the cells are covered, then return</pre><p>The exploration of the grid with a backtracking approach is being done in depth first search order.</p><p><strong>Python function of the above algorithm</strong></p><pre>def dfsBackTrack(currNum, currPos, currPath):<br>    if currPos == endLoc:<br>        if len(currPath) == num_cells:<br>            paths.append(currPath.copy())<br>            return<br>    for diff_h, diff_w in [[0,-1],[0,1],[1,0],[-1,0]]:<br>        newPos = (currPos[0]+diff_h, currPos[1]+diff_w)<br>        if newPos in currPath:<br>            continue<br>        if 0&lt;=newPos[0]&lt;height and 0&lt;=newPos[1]&lt;width:<br>            if {currPos, newPos} not in barriers:<br>                if grid[newPos[0]][newPos[1]] is not None:<br>                    if grid[newPos[0]][newPos[1]] == currNum+1:<br>                        dfsBackTrack(currNum+1, newPos, currPath+[newPos])<br>                else:<br>                    dfsBackTrack(currNum, newPos, currPath+[newPos])</pre><p>You can find the complete code here : <a href="https://github.com/shivaditya-meduri/Articles/blob/main/zipSolver.py">https://github.com/shivaditya-meduri/Articles/blob/main/zipSolver.py</a></p><p><strong>Test case without barriers:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0c7655KSe-nA3vRyvj-NA.png" /></figure><p><strong>Testcase with barriers:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4dmNvzlkx1_EUBPqLAZAg.png" /></figure><p>In both the cases tested, the python code returned solution matches the expected solution 😁</p><p>Hopefully, this helps me climb up the leaderboard but I am sure it won’t as the task of converting the given puzzle to a 2D array and barriers list is quite time taking 😅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=953be08daab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Python Strings Are Immutable — and Why It Matters]]></title>
            <link>https://medium.com/@mvenkatashivaditya/why-are-strings-immutable-in-python-bfdbf1c1199a?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfdbf1c1199a</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[complexity-analysis]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Sun, 11 May 2025 09:53:03 GMT</pubDate>
            <atom:updated>2025-05-13T05:56:25.636Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR — Python strings are immutable so that their hash value can be cached and to enable safe, efficient use as dict/set keys</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7mSiGrUGs1fpw7H5xcEeQ.png" /></figure><p>If you ever tried to modify a string, you probably encountered this error in Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*E0Y3Bysg95GS4vBcCI5cSw.png" /><figcaption>String Objects can’t be modified</figcaption></figure><p>String objects once defined in Python cannot be modified. Even if it sometimes appears like you are modifying strings, you are in fact creating a new string object with the intended modification.</p><p>This is particularly important to consider when doing complexity analysis of Python code dealing with strings.</p><p><strong>Here is a simple example to illustrate this in action:</strong></p><p>Let’s consider a simple problem where we would like to change the first letter of a string to “B”</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>int main() {<br>    std::string s = &quot;apple&quot;;<br>    s[0] = &#39;b&#39;; //O(1) space time operation<br>    std::cout &lt;&lt; s &lt;&lt; &quot;\n&quot;;<br>    return 0;<br>}</pre><p>The above C++ code is a constant time operation i.e. no matter the size of the input string s, the time taken by the line of code s[0] = ‘b’; is constant.</p><pre>s = &quot;apple&quot;<br>s = &quot;b&quot; + s[1:] # O(n) space time operation<br>print(s)</pre><p>The python code to solve the same problem has a complexity of O(n) space time. There is no simple way in Python to solve the problem in constant time. Under the hood, it is doing 2 things:</p><ol><li>Slicing: s[1:] creates a new string object in memory with the content “pple”</li><li>Concatenation: you create another string object of size len(s) with first character b and the characters of s[1:]</li></ol><p>In total, there are 2 linear passes of the string s being performed and 2 new string objects are being created which are later discarded which is very costly.</p><h4>What is immutability?</h4><blockquote><em>If you are already familiar with the concept of immutability, you can skip this section.</em></blockquote><p>Immutable objects cannot be modified and mutable objects can be modified. It is as simple as that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*8QitHTYrdPRTtsCvN87PHA.png" /><figcaption>Most used Python Data types and their mutability statuses</figcaption></figure><p>You might be even surprised to see objects like int, float and bool are immutable.</p><p>In Python (Cpython), using the id() in-built function, we can get the memory address where the variable is being stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfWvPZnYhcMfRUXAT4Xpew.png" /><figcaption>Checking the mutability of list and integer datatypes in python</figcaption></figure><p>In the above example, you can see that when a list has been created and we modify the list, the memory address where the variable is stored remains the same. But in case of integer variable, the memory address changed.</p><p>This is because integer in Python is immutable and list is mutable.</p><blockquote>The only way to modify variables of immutable object data types is by creating a new object with the modified value.</blockquote><h4>Why are some object classes immutable?</h4><p>As discussed above, working with immutable objects is very inefficient in terms of both memory and CPU time. This begs the question, why are some classes designed to be immutable in Python? Wouldn’t Python be more efficient if they were designed as mutable classes like in C++?</p><p>This is because immutable classes offer some advantages that mutable classes don’t.</p><p><strong><em>Biggest advantage of immutable classes</em></strong></p><p>Hashability</p><p>You probably are already familiar with the Python data structures dictionary and set. Both these data structures are basically hash tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*0vFjeFUIIOYW0j2J2sgg_A.png" /><figcaption>Simple illustration of Python Dictionary (Hash Table)</figcaption></figure><p>Behind the scenes, Python computes the hash value of the key and calculates the modulo of bucket size to get the index where the value is stored. Since we don’t have to go through the whole table to find the value for a given key, it enables O(1) look-ups and inserts.</p><p>The concept is similar for Sets, but instead of values being stored, we store True/False indicating whether that value exists in the set or not.</p><blockquote>Python only allows hashable objects as keys and for an object to be hashable, it needs to be immutable. Since strings are used as keys quite frequently, strings are made to be immutable in python to make them hashable.</blockquote><p><strong><em>Why does an object need to be immutable to be hashable?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzTd5jN9mo1X24p1HC7xTg.png" /><figcaption>Using unhashableobjects as keys of a dictionary is not possible</figcaption></figure><p>Have you ever wondered why the hash() function of a string object is O(1)? I mean, wouldn’t it depend on the number of characters of the string object?</p><p>The reason is because, Python caches the hash value of the string object internally once it is computed, so the second hash look-up is O(1).</p><p>This can be tested by computing the time to compute the hash value the first time and the second time of a very big string object.</p><pre>import time<br><br>a = &quot;a&quot; * 1_000_000_000<br><br># 2) First hash: forces full content scan + caches result<br>start = time.perf_counter()<br>h1 = hash(a)<br>t1 = time.perf_counter() - start<br><br># 3) Second hash: reads cached field<br>start = time.perf_counter()<br>h2 = hash(a)<br>t2 = time.perf_counter() - start<br><br>print(f&quot;first hash took  {t1:.6f}s&quot;)<br>print(f&quot;second hash took {t2:.6f}s&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*ngs88Vsk4Ynzt4QAwWCgIw.png" /><figcaption>1st Hash = 0.386 secs | 2nd Hash 0.000028 secs</figcaption></figure><p>This caching of hash is only possible if the object is immutable. Imagine if a string object is changing, then it’s cached hash becomes useless and we will no longer have O(1) look-ups.</p><p>The fact that string objects are immutable helps us cache the hash values and make it hashable which will make dictionaries and sets highly efficient with O(1) look-ups and inserts.</p><p>Dictionaries are also used for things like lru_cache which enables caching of function calls.</p><p>There you go, this is why strings are designed to be immutable in Python and only hashable objects can be used as keys of hash tables (dictionaries &amp; sets)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfdbf1c1199a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ever wondered how a computer generates random numbers following a certain distribution?]]></title>
            <link>https://medium.com/@mvenkatashivaditya/ever-wondered-how-a-computer-generates-random-numbers-following-a-certain-distribution-b8226dd8da9?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8226dd8da9</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 10:27:20 GMT</pubDate>
            <atom:updated>2022-06-06T20:39:02.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS1cmB252v-gvlpc9LmVkQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@svi_designs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sergi Viladesau</a> on <a href="https://unsplash.com/s/photos/shuffling-cards?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Have you ever wondered, how a computer generates random numbers following a certain distribution? It is a fair question. It has always alluded scientists how can we generate randomness. In this blog, we will be exploring the question and discuss the algorithms used by computers to generate random variables following a certain probability distribution.</p><h4>Applications of Random Number Generators</h4><p>Before we start discussing algorithms, it is good to understand the need for generating random numbers. Here mentioned are few applications of random number generating methods(RNGs).</p><ol><li>Monte Carlo method: This method is used to understand the outcomes of uncertain events. It is vital in this method to generate inputs randomly from a probability distribution over a domain. We need RNGs to use this method.</li><li>Regularization in Deep Learning: Most common method of regularization of deep learning models is through using drop-outs. Dropout is a technique where randomly selected neurons are ignored during training. The random distribution used to achieve drop-out has an important effect on the performance of the model, and using RNGs we can select the best distribution for the best performance.</li><li>Cryptography: For example, in public-key|private-key encryption, when we need to generate random public and private key pairs for a user, we require RNGs. It is important to understand that the deterministic nature of Pseudo Random Number Generators can effect the security of the encryption method.</li></ol><h4>Procedure to generate a sample following a certain probability distribution</h4><p>Let’s say, we would like a sample of n elements from a distribution with the cumulative distribution function of 𝐹(𝑥). We can sample n elements from U(0.0, 1.0) and use 𝐹−1(𝑈(0.0,1.0)) i.e. the inverse of the cumulative distribution function to create a sample from the desired distribution. This method is called the <strong>Inverse CDF method</strong>.</p><p>So, firstly to apply this method, we require a function that can generate samples from a uniform distribution between the bounds 0.0 and 1.0.</p><p><strong>Generating a sample from Uniform distribution with bounds 0.0 and 1.0</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*JBRSuuCyZ9UHj3TB1t1yHQ.png" /><figcaption>Histogram of the Sample generated using the below function</figcaption></figure><p>We will use a simple technique to generate a sample from U(0.0, 1.0). The function used to generate random numbers is (ax+b)mod(10^k)/10^k. where a and b are arbitrary and k is the number of decimal places that we are looking to get from each observation. Initially, a random seed is provided as input and the above function is applied to the seed and this is added to the sample list. Now, we use the newly generated number as the seed to the above function again and generate another random number. This method is auto-regressive, and also deterministic in nature, making it infeasable for certain applications. We keep on auto-regressively generating numbers until we have the desired number of elements. You can find the Python function for the above method coded below.</p><pre>def random_generator(n, seed=10):<br>    &#39;&#39;&#39;<br>    This function will generate random numbers<br>    between 0.0 and 1.0. The function uses the <br>    seed value to generate a number and feeds the result back<br>    to the generator as the new seed. The function used to<br>    generate random numbers is (ax+b)mod(m) <br>    &#39;&#39;&#39;<br>    rands = []<br>    for i in range(n):<br>        ## a = 16 &amp; b=232<br>        rn = (16*seed + 232)%(10**9)<br>        seed = rn<br>        rands.append(rn/(10**9))<br>    return rands</pre><p>Now, we have a function that can generate a sample of n elements between 0.0 and 1.0. We can apply the inverse CDF method to generate samples from a few well-known distributions.</p><p><strong>Normal Distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*s3z0ESqdSf-OFCyRK1B5jA.png" /><figcaption>PDF of Normal Distribution(Wikipedia)</figcaption></figure><p>Normal distribution has 2 parameters, which are the mean and the standard deviation. We can get the inverse CDF function of normal distribution from the scipy module. This will be used to generate the normal distribution sample</p><pre>from scipy.stats import norm</pre><pre>### Inverse Cumulative Distribution Function of Norm : norm.ppf()</pre><pre>def normal_distribution(n, mean, std):<br>    &#39;&#39;&#39;<br>    This function returns a sample of n elements <br>    following the normal distribution : N(mean, std)<br>    &#39;&#39;&#39;<br>    base = random_generator(n)<br>    return [norm.ppf(i, loc=mean, scale=std) for i in base]</pre><p>Using the above function, we can generate n observations from a sample of a mean and a standard deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*_Dpv8aklj-uUNlDsCFMIzA.png" /><figcaption>Histogram of the generated sample Norm(m=100, std=10)</figcaption></figure><p><strong>Exponential Distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*G5xBb8ECLkmz_AY3NMCcYw.png" /><figcaption>PDF of exponential distribution(Wikipedia)</figcaption></figure><p>Exponential distribution has a parameter lambda which effects the decay of the distribution. We can get the inverse CDF of exponential distribution from the scipy module.</p><pre>from scipy.stats import expon</pre><pre>### Inverse Cumulative Distribution Function of expon: expon.ppf()</pre><pre>def exponential_distribution(n, loc, lam):<br>    &#39;&#39;&#39;<br>    Generates a sample of n elements following<br>    the distribution Exp(lam)<br>    &#39;&#39;&#39;<br>    sc = 1/lam ## Controls the rate of decay of the distribution<br>    base = random_generator(n)<br>    return [expon.ppf(i, loc=loc, scale=sc) for i in base]</pre><p>Using the above function, we will generate a sample from the exponential distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*WHVLayhVFZX6N1SFGtdQvA.png" /><figcaption>Histogram of the generated sample(Exp(lambda=10))</figcaption></figure><p><strong>Chi-Squared distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*i1i9qwwkj25tzY_qgd_Z8g.png" /><figcaption>PDF of chi-squared distribution(Wikipedia)</figcaption></figure><p>Chi-Squared distribution has a parameter : degrees of freedom which affects the shape of the graph. We can get the inverse CDF of chi-squared distribution from the scipy module.</p><pre>from scipy.stats import chi2<br>### Inverse CDF of chi-squared: chi2.ppf()</pre><pre>def chi2_distribution(n, df):<br>    &#39;&#39;&#39;<br>    Generates a sample of n elements following<br>    the distribution chi-squared distribution with degrees freedom<br>    &#39;&#39;&#39;<br>    base = random_generator(n)<br>    return [chi2.ppf(i, df=df) for i in base]</pre><p>Using the above function, we will generate a sample from the Chi-Squared distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*zVB58p5gLOK-FeJnduLRAQ.png" /><figcaption>Histogram of the generated sample chi2(df=10)</figcaption></figure><p><strong>Conclusion</strong></p><p>Finally, all we need is a function that can generate a uniform distribution sample between bouds 0.0 and 1.0, and an inverse cumulative distribution function of the desired distribution and we can use the Inverse-CDF method to generate the sample from the desired distribution.</p><p>Thank you for your attention!</p><p>GitHub : <a href="https://github.com/shivaditya-meduri/Articles/blob/1b8c12bbfae7231fd75d225fbc61dd4da64ee96b/PRNG.py">https://github.com/shivaditya-meduri/Articles/blob/1b8c12bbfae7231fd75d225fbc61dd4da64ee96b/PRNG.py</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8226dd8da9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve data processing speeds while using numpy arrays in Python through vectorization]]></title>
            <link>https://medium.com/analytics-vidhya/improve-data-processing-speeds-while-using-numpy-arrays-in-python-through-vectorization-49ea6cc9004e?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/49ea6cc9004e</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vectorization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 20:29:52 GMT</pubDate>
            <atom:updated>2021-09-21T04:47:04.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1vuFJg5UotXqRKVlUtWrA.jpeg" /><figcaption><a href="https://medium.com/u/2053395ac335">Unsplash</a></figcaption></figure><p>Many internet companies nowadays use python in their backend server applications. When dealing with huge amounts of data, for example,an application that creates dashboards for large datasets given by the user, it is important to note that data processing is the bottleneck in serving the user fast responses. Also in data science applications while pre-processing the data and running feature generation functions or cleaning operations through out the records of the dataset can be time consuming for large number of records. Vectorization is what gives python performance speeds parlelling C programming language, literally, because numpy’s vectorized functions uses optimized precompiled C code under the hood.</p><h3>What is vectorization?</h3><p>Python is a dynamically typed programming language, meaning that type checking of data happens at runtime. C is a statically typed programming languages, so the type checking happens during compile time. Type checking during execution is a time consuming process and is the reason behind python’s slow performance when compared to C, especially in for-loops. Numpy’s vectorized functions don’t perform explicit type checks for each iteration saving valuable CPU and GPU resource time. Vectorization essentially means that function is now applied paralelly on many values of the iterable unlike traditional for-loops. CPUs use SIMD (Single Instruction Multiple Data) to achieve faster speeds taking advantage of more number of cores and parallelism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZ5ZAHRxhSYZaw3w8a8JNw.jpeg" /><figcaption><a href="https://medium.com/u/2053395ac335">Unsplash</a></figcaption></figure><p>In this article I will discuss the most popular vectorized functions available in numpy library, compare the speeds in my local computer when compared to traditional for-loops, and how we can vectorize a custom function</p><h3>Vectorization of transformation operations</h3><p>Transforming data is an essential part of data preprocessing. For example, scaling the images pixel values between 0 and 1 for Neural Nets, log transformations of certain features of the dataset before applying the regression model, Normalization of features of a dataset, and many more.</p><p>Let us compare the speeds of traditional for-loops and vectorization using the dataset of MNIST from the sklearn library. MNIST data in sklearn has the shape 1797x64. Each image is stored in 1d numpy array of length of 64</p><pre>Scaling images between 0 and 1 for deep learning applications</pre><pre>#######################################################</pre><pre>#Using traditional for-loops<br>s = mnist.shape<br>tic = time.time()<br>for i in range(s[0]):<br>    for j in range(s[1]):<br>        mnist[i][j] = mnist[i][j]/255<br>toc = time.time()<br>print(&quot;Time taking with training loop is : {0}ms&quot;.format((toc-tic)*1000))</pre><pre>Output - Time taking with training loop is : 96.99487686157227ms</pre><pre>#Using vectorization<br>tic = time.time()<br>mnist = mnist/255<br>toc = time.time()<br>print(&quot;Time taking with Vectorization is : {0}ms&quot;.format((toc-tic)*1000))</pre><pre>Output - Time taking with Vectorization is : 6.717443466186523ms</pre><p>We can clearly see that there is 10x improvement in time-taken for scaling. The rate of improvement will depend on your local computer, but you will definitely witness a significant improvement in execution time</p><p>+, -, *, / operations vectorized versions can be performed by directly performing the operation on the numpy array</p><pre>print(arr * 3) #Multiply array by a number<br>print((arr/4+100)*3) #Divide each element by 4, then +100 and /3<br>#Performing vectorized operations on 2 arrays<br>print(arr1 + arr2) # Element wise addition<br>print(arr1 * arr2) # Element wise multiplication<br>print((arr1-arr2)**2) # Eucledian distance<br>#Ensure the 2 arrays have the same shape</pre><p>We can save lines of code and execution time for the basic operations by applying them directly between arrays and scalars(int, float objects).</p><p>Now let’s see about log transformations. Log transformations are essential while performing regression especially in case of skewed data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*jNR8-LxO4ySbzao9G8RISQ.png" /><figcaption>Boston housing data features pairwise plot</figcaption></figure><p>Let’s apply log transformations of Boston housing data(Can be found in Kaggle) Log transformation essentially means apply log to each and every item in the dataset</p><pre>#Using traditional for-loop<br>s = data.shape<br>tic = time.time()<br>for i in range(s[0]):<br>    for j in range(s[1]):<br>        data[i][j] = math.log(data[i][j])<br>toc = time.time()<br>print(&quot;Time taken with For-loop: {0}ms&quot;.format((toc-tic)*1000))<br>Output - Time taken with For-loop : 2.0296573638916016ms<br>#Using vectorized numpy function<br>tic = time.time()<br>data = np.log(data)<br>toc = time.time()<br>print(&quot;Time taken with vectorization: {0}ms&quot;.format((toc-tic)*1000))<br>Output - Time taken with Vectorization : 0.0ms</pre><p>Vectorized version of log barely took any time, it was so fast the smallest unit of time.time() is not able to measure the difference. Try it out in your own computer to see the difference</p><p>Numpy provides a range of vectorized transformation functions. All of them can be found in the link <a href="https://numpy.org/doc/stable/reference/routines.math.html">https://numpy.org/doc/stable/reference/routines.math.html</a></p><h3>Vectorization of Linear Algebra operations</h3><p>Linear Algebra operations like Matrix Multiplication is used in various applications like neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*0OKKMDca4XVOOxUr" /><figcaption>Inputs passing through a layer of neural net is nothing but matrix multiplication</figcaption></figure><p>In neural net applications using vectorized functions will significantly reduce train time and execution time in production as well.</p><pre>A = np.random.randn(10000).reshape((100, 100))<br>B = np.random.randn(10000).reshape((100, 100))<br>C = np.zeros((100, 100))<br>tic = time.time()<br>#Using traditional For-Loops<br>for i in range(100):<br>    for j in range(100):<br>        for k in range(100):<br>            C[i][j] += A[i][k]*B[k][j]<br>toc = time.time()<br>print(&quot;Time taken by For-Loop: {0}ms&quot;.format((toc - tic)*1000))</pre><pre>Output - Time taken by For-Loop: 1195.0178146362305ms</pre><pre>#Using vectorized function of numpy<br>tic = time.time()<br>C = np.dot(A, B)<br>toc = time.time()<br>print(&quot;Time taken by vectorization: {0}ms&quot;.format((toc - tic)*1000))</pre><pre>Output - Time taken by vectorization: 1.0304450988769531ms</pre><p>It is a huge improvement using the vectorized function. We can clearly see why deep learning applications prefer to vectorize the code, it can save a lot of time model training and deployment</p><p>Visit <a href="https://numpy.org/doc/stable/reference/routines.linalg.html">https://numpy.org/doc/stable/reference/routines.linalg.html</a> to see all the linalg functions provided by the numpy library</p><h3>Vectorizing a custom function</h3><p>Though there are a lot of vectorized functions provided by the numpy library, we will need to apply a custom function for our application throughout the dataset which is not available in the numpy library. There is a way through which we can vectorize custom functions using numpy library</p><p>Break down the custom function into vectorized functions available in the numpy library. For example,</p><pre>A = np.random.randn(1000)<br>B = np.zeros(1000)<br>def func(a):<br>    return a**2 + 5*a +35 <br>for i in range(1000):<br>    B[i] = func(A[i])</pre><pre>#We can vectorize the above func as follows</pre><pre>B = A**2 + 5*A +35</pre><p>If we are unable to break the custom function to vectorized functions in numpy, we can also use the numpy.vectorize function</p><pre>A= np.random.randn(10000)<br>C = np.zeros(10000)<br>def f(a):<br>    if a&gt;10:<br>        return a**2<br>    else:<br>        return a<br>tic = time.time() #Using for-loops<br>for i in range(10000):<br>    C[i] = f(A[i])<br>toc = time.time()<br>print(&quot;Time taken: {0}ms&quot;.format((toc-tic)*1000))</pre><pre>Output - 10ms</pre><pre>v = np.vectorize(f) #Vectorizing the function<br>tic = time.time()<br>C = v(A)<br>toc = time.time()<br>print(&quot;Time taken: {0}ms&quot;.format((toc-tic)*1000))</pre><pre>Output - 2ms</pre><h3>Conclusion</h3><p>While preprocessing numerical data, where speed is a priority, it is recommended to use numpy functions which are generally vectorized, and use precompiled C code for superior performance. This will improve your backend APIs response time significantly when there is a huge amount of data involved.</p><p>Find the jupyter notebook for this article in the following link: <a href="https://github.com/shivaditya-meduri/Articles/blob/ac614ff77bad275834b211813ae0fa2f946aa3e1/Vectorization.ipynb">https://github.com/shivaditya-meduri/Articles/blob/ac614ff77bad275834b211813ae0fa2f946aa3e1/Vectorization.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49ea6cc9004e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/improve-data-processing-speeds-while-using-numpy-arrays-in-python-through-vectorization-49ea6cc9004e">Improve data processing speeds while using numpy arrays in Python through vectorization</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gaussian denoising for time series location data]]></title>
            <link>https://medium.com/@mvenkatashivaditya/gaussian-denoising-for-time-series-location-data-25a43c450ecb?source=rss-65dcb782d994------2</link>
            <guid isPermaLink="false">https://medium.com/p/25a43c450ecb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[geolocation]]></category>
            <dc:creator><![CDATA[Shivaditya Meduri]]></dc:creator>
            <pubDate>Thu, 05 Aug 2021 19:54:43 GMT</pubDate>
            <atom:updated>2021-09-10T20:34:03.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ny_esgC-cbBfXfi6ABytPQ.jpeg" /><figcaption><a href="https://medium.com/u/2053395ac335">Unsplash</a></figcaption></figure><h3>Time series location data</h3><p>Consider a vehicle moving from a starting location to an ending location. GPS data tracked by the smartphone is not always reliable because of a lot of factors like network problems, environmental noise, etc. In this article, we will be trying to denoise the time-series location data using a gaussian filter.</p><h3>Data Source</h3><p>The following data is taken from the Google decimeter challenge<br>Fu, Guoyu (Michael), Khider, Mohammed, van Diggelen, Frank, (2021, May), Google Smartphone Decimeter Challenge. <br>Retrieved from</p><p><a href="https://www.kaggle.com/c/google-smartphone-decimeter-challenge/data">Google Smartphone Decimeter Challenge</a></p><h3>Understanding the data</h3><p>In the dataset there are various collectionNames, each collectionName represents a tour taken between a start and an end point, Multiple devices are fixed in the vehicle, so for 1 collectionName you can find many phoneNames. We will be applying gaussian smoothing technique for the time series location data of 1 unique phone in a collectionName so that all the confounding variables remain the same</p><ul><li>(latTrue, lngTrue) is the true location</li><li>(latDeg, lngDeg) is the measured location data</li><li>phone is the amalgamation of collectionName and phoneName</li></ul><p>Explore the data more to understand it and also follow the google explanation to understand it even further</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etgRVHYFxjBbAJOV3L8vqQ.png" /><figcaption>Visualizing location data corresponding to the collection 2020–05–14-US-MTV-1</figcaption></figure><p>The mean absolute error before applying Gaussian smoothing is : 5.36e-08</p><h3>Understanding the gaussian smoothing procedure</h3><p>In smoothing we use the neighbouring data points of the time series data to create a smooth data point. When we apply smoothing with a gaussian kernel, it is called gaussian smoothing. For each data point we generate a new value that is some function of the original value at that point and the surrounding data points.With Gaussian smoothing, the function that is used is our Gaussian curve</p><h3>Gaussian Kernel</h3><p>a Gaussian function, often simply referred to as a Gaussian, is a function of the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*B-U1-DfZUY_p-EvS66f6FA.png" /><figcaption>Gaussian function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKmD04xJ9PgXyFxUdFxd4w.png" /><figcaption>Mean squared error after Gaussian smoothing is: 9.457588974464937e-09</figcaption></figure><h3>Finding the optimal sigmas for gaussian smoothing</h3><p>A most simple way of finding the sigmas is through trial and error, keep checking how the smoothing worked for each sigma. In the following cell, I’ve used a Nelder mead approach to find an optimum of the sigma values. Nelder-Mead is very sensitive to initial x, but 1 advantage is we do not have to provide a gradient vector as it is a geometric optimization algorithm</p><p>Ref: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html">https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZwYoJHII2qGufPp5DNg-A.png" /></figure><h3>Final results</h3><p>Gaussian smoothing seemed to have worked well as the MSE reduced from 5.36e-08 to 9.45e-09.</p><p>Advanced gaussian smoothing methods include trying 2 different sigmas for small and large noise and then creating an ensemble of both the filters.</p><p>Code : <a href="https://github.com/shivaditya-meduri/Articles/blob/76f9f743be4a19c193f93890f4d812ee6de637f3/Gaussian%20smoothing%20for%20time%20series%20data.ipynb">https://github.com/shivaditya-meduri/Articles/blob/76f9f743be4a19c193f93890f4d812ee6de637f3/Gaussian%20smoothing%20for%20time%20series%20data.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a43c450ecb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>