<?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 Prathamesh Mohite on Medium]]></title>
        <description><![CDATA[Stories by Prathamesh Mohite on Medium]]></description>
        <link>https://medium.com/@prathamesh-mohite96?source=rss-5215051ec5c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fMm9qht3k74GQGpmxseqWQ@2x.jpeg</url>
            <title>Stories by Prathamesh Mohite on Medium</title>
            <link>https://medium.com/@prathamesh-mohite96?source=rss-5215051ec5c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:01:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prathamesh-mohite96/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[The Seat That “Almost” Wasn’t There: Building an Airline Revenue Forecasting System from Scratch]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/analytics-vidhya/the-seat-that-almost-wasnt-there-building-an-airline-revenue-forecasting-system-from-scratch-99121b80e152?source=rss-5215051ec5c5------2"><img src="https://cdn-images-1.medium.com/max/2085/1*xufrgmeJpS3qRcmQ6lWuMg.png" width="2085"></a></p><p class="medium-feed-snippet">Every revenue manager faces the same question dozens of times a day:</p><p class="medium-feed-link"><a href="https://medium.com/analytics-vidhya/the-seat-that-almost-wasnt-there-building-an-airline-revenue-forecasting-system-from-scratch-99121b80e152?source=rss-5215051ec5c5------2">Continue reading on Analytics Vidhya »</a></p></div>]]></description>
            <link>https://medium.com/analytics-vidhya/the-seat-that-almost-wasnt-there-building-an-airline-revenue-forecasting-system-from-scratch-99121b80e152?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/99121b80e152</guid>
            <category><![CDATA[aviation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[revenue-management]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 20:08:58 GMT</pubDate>
            <atom:updated>2026-04-03T20:08:58.635Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Stochastic Routing Under Traffic Uncertainty: Findings from a Real-World Pharmaceutical Delivery…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/analytics-vidhya/stochastic-routing-under-traffic-uncertainty-findings-from-a-real-world-pharmaceutical-delivery-6dda89d1709f?source=rss-5215051ec5c5------2"><img src="https://cdn-images-1.medium.com/max/2085/1*MDIxMkBMcM3KnBCrvPMaZA.png" width="2085"></a></p><p class="medium-feed-snippet">A production-quality CVRPTW analysis across 78 delivery nodes in the Attica region, incorporating three-scenario travel-time modeling&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/analytics-vidhya/stochastic-routing-under-traffic-uncertainty-findings-from-a-real-world-pharmaceutical-delivery-6dda89d1709f?source=rss-5215051ec5c5------2">Continue reading on Analytics Vidhya »</a></p></div>]]></description>
            <link>https://medium.com/analytics-vidhya/stochastic-routing-under-traffic-uncertainty-findings-from-a-real-world-pharmaceutical-delivery-6dda89d1709f?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dda89d1709f</guid>
            <category><![CDATA[vehicle-routing-problem]]></category>
            <category><![CDATA[mathematical-modeling]]></category>
            <category><![CDATA[operations-research]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 13:42:27 GMT</pubDate>
            <atom:updated>2026-03-22T13:44:43.134Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Optimizing Streaming Content Caching: A Fresh Take on Multi-Cell Optimization]]></title>
            <link>https://medium.com/analytics-vidhya/optimizing-streaming-content-caching-a-fresh-take-on-multi-cell-optimization-62f95ff95d07?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f95ff95d07</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[operations-research]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 04:36:31 GMT</pubDate>
            <atom:updated>2025-02-05T04:36:31.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tmI9JWX5JwlvPef9nxmSsA.jpeg" /></figure><p>Picture this: You’ve had a long day at work, and all you want to do is sit back, relax and binge-watch the latest season of <em>The Witcher</em> on Netflix. You press play, and — boom — it starts instantly in glorious 4K, without buffering, without a hitch. Feels like magic, isn’t it? But behind this seamless streaming experience lies an incredibly complex optimization algorithm being solved in real-time — optimizing which content is stored on distributed edge servers, balancing storage constraints, freshness of content, and network costs.</p><h3>🎬<strong> The Evolution of Content Caching: Why Popularity Alone Isn’t Enough?</strong></h3><p>Traditional caching strategies focus solely on content popularity by frequently watched titles on Content Delivery Network (CDN) servers closest to users. It follows a simple popularity-driven approach by:</p><ol><li>Storing the most frequently accessed titles at CDN edge servers</li><li>Evicting less popular titles as the demand shifts over time</li></ol><p>While these techniques are effective in situations where the viewing trends are relatively stable, we might have to consider a more dynamic approach where the content popularity changes rapidly. For example, we might see a situation wherein a new blockbuster series (e.g. The Crown Season 3) suddenly surges in demand and requires a high cache hit rate. While older content (e.g. Breaking Bad) still has demand but should be refreshed strategically than continuously stored. This is where we come up with a fresh problem statement:</p><blockquote>“What if we go beyond popularity and optimize for both freshness and cost efficiency</blockquote><h3>🔍 The Core Problem: What to Store, Where, and When?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*smngZpDDo5tgI9X3FJeMfw.png" /><figcaption>Fig 1. Basic CDN Distribution Network</figcaption></figure><p>Similar to the above diagram, streaming services like Netflix maintains thousands of edge servers worldwide, each with limited storage capacity. Each of these servers caches a subset of Netflix’s vast content library, ensuring that the most in-demand titles are available instantly. But here’s the catch. CDN servers have finite storage — you can’t store <em>everything</em>. Plus, popularity of a title shifts dynamically — last month’s hit may be irrelevant now. Last but the least, updating content incurs network cost — fetching a title from central storage is expensive.</p><p>We need a dynamic optimization model that ensures:</p><ol><li>Highly requested content is cached close to users.</li><li>Cache updates are efficient and cost-effective.</li><li>Total storage never exceeds capacity.</li></ol><h3><strong>📊 The Optimization Model: Smarter Caching with Dynamic Demand Forecasting</strong></h3><p>Instead of storing content based purely on past popularity, we’ll design a more realistic caching system that:</p><ul><li><strong>Predicts </strong>demand dynamically based on recent user interactions.</li><li><strong>Balances </strong>storage constraints across multiple CDN servers.</li><li><strong>Minimizes </strong>update costs by avoiding unnecessary replacements.</li></ul><h3>🧠 Decision Variables:</h3><p>Let’s define our core decision variables:</p><ul><li>x(<em>i, h</em>) → <strong>Binary variable</strong>: 1 if title ‘i’ is cached at edge server ‘h’, 0 otherwise.</li><li>u(<em>i, h</em>)​ → <strong>Binary variable</strong>: 1 if title ‘i’ is updated (fetched from central cloud storage) at server ‘h’.</li><li>d(<em>i, h</em>) → <strong>Forecasted demand</strong>: Expected number of requests for title ‘i’ at server ‘h’.</li><li>s(<em>i</em>) → <strong>Size of the title</strong> ‘i’ in GB (Larger content incurs higher bandwidth costs)</li><li>C(<em>h</em>) → <strong>Max Storage Limit</strong> in GB at server ‘h’</li><li>λ → <strong>Penalty factor to update costs: </strong>controls trade-off between demand fulfillment and network load</li></ul><pre>import matplotlib.pyplot as plt<br>import networkx as nx<br><br># Create a network graph representation of the CDN system<br>G = nx.DiGraph()<br><br># Define node categories<br>cloud_node = &quot;Central Cloud&quot;<br>edge_nodes = [f&quot;CDN Server {h}&quot; for h in range(num_servers)]<br>user_nodes = [f&quot;User {i}&quot; for i in range(15)]  # Simulating 15 users<br><br># Add nodes to the graph<br>G.add_node(cloud_node, color=&#39;red&#39;, size=1000)  # Cloud server<br>for edge in edge_nodes:<br>    G.add_node(edge, color=&#39;lightblue&#39;, size=700)  # CDN servers<br>for user in user_nodes:<br>    G.add_node(user, color=&#39;green&#39;, size=500)  # Users<br><br># Connect cloud to CDN servers<br>for edge in edge_nodes:<br>    G.add_edge(cloud_node, edge, weight=2)<br><br># Connect CDN servers to users<br>for user in user_nodes:<br>    assigned_server = np.random.choice(edge_nodes)  # Assign each user a random CDN server<br>    G.add_edge(assigned_server, user, weight=1)<br><br># Extract node colors and sizes<br>node_colors = [G.nodes[node][&#39;color&#39;] for node in G.nodes]<br>node_sizes = [G.nodes[node][&#39;size&#39;] for node in G.nodes]<br><br># Draw the network graph<br>plt.figure(figsize=(10, 6))<br>pos = nx.spring_layout(G, seed=42)  # Position nodes in a visually pleasing layout<br>nx.draw(<br>    G, pos, <br>    with_labels=True, <br>    node_color=node_colors, <br>    node_size=node_sizes, <br>    edge_color=&#39;gray&#39;, <br>    font_size=8<br>)<br>plt.title(&quot;Netflix CDN Network Representation&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*mja687nviHqYwsrtKoXUwA.png" /><figcaption>Fig 2. Sample CDN Network Representation</figcaption></figure><h3>🎯 Objective Function: A Supply-Demand Balancing Act</h3><p>Maximize ∑d(<em>i, h</em>)*x(<em>i, h</em>) — λ∑u(<em>i, h</em>)*s(<em>i</em>)</p><p>The objective function here aims to optimize content caching by maintaining a healthy balance between 2 key forces:</p><ol><li><strong>Maximizing demand fulfillment,</strong> ∑d(<em>i, h</em>)*x(<em>i, h</em>): Think of this as a retailer stocking high-demand products at multiple store locations. A well-stocked store (CDN server) ensures that customers (users) always find what they need.</li><li><strong>Minimizing Costly Restocking (Cache Updates)</strong>, λ∑u(<em>i, h</em>)*s(<em>i</em>): This term penalizes unnecessary updates, ensuring we don’t waste bandwidth fetching content from central storage when it’s not needed. By tuning λ, we control how much weight we give to cache updates vs. demand fulfillment, creating a dynamic balance between supply (cached content) and demand (user requests).</li></ol><h3><strong>📏 Constraints:</strong></h3><ol><li>Cache Capacity Limit: Each CDN server has a fixed storage limit C(<em>h</em>) i.e. ∑s(<em>i</em>)*x(<em>i, h</em>) ≤ C(<em>h</em>) ∀h</li><li>Cache Update Limit: Content fetching should be strategic to avoid excessive network overhead i.e. ∑u(<em>i</em>)*h(<em>i, h</em>) ≤ B(<em>h</em>) ∀h</li></ol><p>We will now proceed to model a toy dataset for the optimization problem. The entire code is written in Python PuLP module:</p><pre># Function to update visualizations based on cache capacity and bandwidth limit while keeping other parameters constant<br>def update_dashboard(cache_capacity, bandwidth_limit):<br>    num_titles = 20  # Keeping titles constant<br>    num_servers = 5  # Keeping servers constant<br><br>    # Re-run the optimization model with the new cache capacity and bandwidth limit<br>    model = pulp.LpProblem(&quot;NetflixCaching&quot;, pulp.LpMaximize)<br><br>    # Decision variables<br>    x = pulp.LpVariable.dicts(<br>        &quot;Cache&quot;, <br>        ((i, h) <br>        for i in range(num_titles) <br>        for h in range(num_servers)), <br>        cat=&quot;Binary&quot;<br>        )<br><br>    u = pulp.LpVariable.dicts(<br>        &quot;Update&quot;, <br>        ((i, h) <br>        for i in range(num_titles) <br>        for h in range(num_servers)),<br>        cat=&quot;Binary&quot;<br>        )<br><br>    # Forecasted demand per server<br>    # Generate synthetic Netflix demand data (Zipf distribution)<br>    # np.random.seed(42)<br>    popularity = np.random.zipf(a=1.3, size=num_titles)<br>    popularity = popularity / popularity.sum()<br><br>    # Generate synthetic content sizes<br>    sizes = np.random.uniform(2.0, 10.0, num_titles)<br>    demand = { (i, h): int(popularity[i] * np.random.randint(1000, 10000)) <br>            for i in range(num_titles) for h in range(num_servers)}<br>    <br>    # Objective function remains the same<br>    model += pulp.lpSum(<br>        demand[i, h] * x[i, h] for i in range(num_titles) <br>        for h in range(num_servers)<br>        ) - \<br>             0.5 * pulp.lpSum(u[i, h] * sizes[i] <br>             for i in range(num_titles) for h in range(num_servers)<br>             )<br><br>    # Constraints updated based on cache capacity and bandwidth limit<br>    for h in range(num_servers):<br>        # Cache capacity constraint<br>        model += pulp.lpSum(sizes[i] * x[i, h] for i in range(num_titles)) &lt;= cache_capacity<br><br>        # Bandwidth limit now scales dynamically<br>        model += pulp.lpSum(sizes[i] * u[i, h] for i in range(num_titles)) &lt;= bandwidth_limit<br><br>    # Solve the updated optimization problem<br>    model.solve()<br><br>    # Extract results again<br>    selected_titles = []<br>    for i in range(num_titles):<br>        for h in range(num_servers):<br>            if pulp.value(x[i, h]) == 1:<br>                selected_titles.append((i, h, sizes[i], demand[i, h]))<br><br>    # Convert results to DataFrame<br>    df_results = pd.DataFrame(<br>        selected_titles, <br>        columns=[&quot;Title ID&quot;, &quot;Server&quot;, &quot;Size (GB)&quot;, &quot;Demand Served&quot;]<br>        )<br><br>    # Aggregate demand served per server<br>    server_demand_summary = df_results.groupby(&quot;Server&quot;)[&quot;Demand Served&quot;].sum().reset_index()<br>    server_demand_summary.columns = [&quot;Server&quot;, &quot;Total Demand Served&quot;]<br><br>    # Aggregate total storage used per server<br>    server_storage_summary = df_results.groupby(&quot;Server&quot;)[&quot;Size (GB)&quot;].sum().reset_index()<br>    server_storage_summary.columns = [&quot;Server&quot;, &quot;Total Storage Used (GB)&quot;]<br><br>    # Merge summaries<br>    server_summary = pd.merge(server_demand_summary, server_storage_summary, on=&quot;Server&quot;)<br><br>    # Dashboard plots<br>    fig, axes = plt.subplots(2, 2, figsize=(15, 10))<br><br>    # Plot 1: Demand Served per CDN Server<br>    sns.barplot(<br>        x=&quot;Server&quot;, <br>        y=&quot;Total Demand Served&quot;, <br>        data=server_summary, <br>        palette=&quot;coolwarm&quot;, <br>        ax=axes[0, 0]<br>)<br>    axes[0, 0].set_title(f&quot;Total Demand Served per CDN Server&quot;)<br>    axes[0, 0].set_xlabel(&quot;CDN Server&quot;)<br>    axes[0, 0].set_ylabel(&quot;Demand Served&quot;)<br><br>    # Plot 2: Storage Used per CDN Server<br>    sns.barplot(<br>        x=&quot;Server&quot;, <br>        y=&quot;Total Storage Used (GB)&quot;, <br>        data=server_summary, <br>        palette=&quot;Blues&quot;, <br>        ax=axes[0, 1]<br>        )<br>    axes[0, 1].set_title(f&quot;Total Storage Used per CDN Server&quot;)<br>    axes[0, 1].set_xlabel(&quot;CDN Server&quot;)<br>    axes[0, 1].set_ylabel(&quot;Storage Used (GB)&quot;)<br><br>    # Plot 3: Heatmap of Cached Content Across Servers<br>    cache_matrix = df_results.pivot(<br>        index=&quot;Title ID&quot;, <br>        columns=&quot;Server&quot;, values=&quot;Size (GB)&quot;<br>    ).fillna(0)<br>    sns.heatmap(<br>        cache_matrix, <br>        cmap=&quot;YlGnBu&quot;, <br>        linewidths=0.5, <br>        annot=False, <br>        cbar=True, <br>        ax=axes[1, 0]<br>    )<br>    axes[1, 0].set_title(f&quot;Heatmap of Cached Content Across CDN Servers&quot;)<br>    axes[1, 0].set_xlabel(&quot;CDN Server&quot;)<br>    axes[1, 0].set_ylabel(&quot;Title ID&quot;)<br><br>    # Plot 4: Demand vs Storage Trade-off<br>    sns.scatterplot(<br>        x=&quot;Total Storage Used (GB)&quot;, <br>        y=&quot;Total Demand Served&quot;, <br>        data=server_summary, <br>        hue=&quot;Server&quot;, <br>        palette=&quot;Dark2&quot;, <br>        s=100, <br>        ax=axes[1, 1]<br>    )<br>    axes[1, 1].set_title(f&quot;Trade-off Between Storage and Demand Served per CDN Server&quot;)<br>    axes[1, 1].set_xlabel(&quot;Total Storage Used (GB)&quot;)<br>    axes[1, 1].set_ylabel(&quot;Total Demand Served&quot;)<br>    axes[1, 1].legend(title=&quot;CDN Server&quot;)<br><br>    plt.tight_layout()<br>    plt.show()<br><br># Interactive Widget for Cache Capacity and Bandwidth Sensitivity Analysis<br>interact(<br>    update_dashboard,<br>    <br>    cache_capacity=widgets.IntSlider(<br>        min=500, <br>        max=5000, <br>        step=500, <br>        value=1000, <br>        description=&quot;Cache Limit&quot;<br>    ),<br>    <br>    bandwidth_limit=widgets.IntSlider(<br>        min=500, <br>        max=5000, <br>        step=500, <br>        value=2000, <br>        description=&quot;Max Bandwidth (GB)&quot;<br>    )<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QOaZrfNiKnc1N_nTrgi1ug.gif" /></figure><h3>Sensitivity Analysis: Evaluating the Impact of Cache Capacity and Bandwidth Limits</h3><p>In a large-scale content distribution network, infrastructure constraints play a significant role in determining the efficiency of content delivery. To understand how variations in <strong>cache capacity</strong> and <strong>bandwidth availability</strong> affect content placement and demand fulfillment, we conducted a sensitivity analysis, holding all other parameters constant.</p><h4>1️⃣ Impact of Cache Capacity Adjustments</h4><p>Increasing cache capacity allows for greater content storage at edge servers, reducing dependency on central storage and improving response times. Higher cache sizes lead to:</p><ul><li>Greater demand fulfillment, as more users can access content locally.</li><li>Reduced bandwidth consumption, since fewer requests require fetching from central storage.</li><li>Lower frequency of cache replacement, decreasing operational overhead.</li></ul><p>Conversely, reducing cache capacity results in more frequent evictions of less popular content, higher reliance on central storage, and an increase in network bandwidth usage due to repeated content retrievals.</p><h4>2️⃣ Impact of Bandwidth Limit Adjustments</h4><p>A higher bandwidth allocation enables more frequent updates to cached content, ensuring that trending or newly released content remains readily accessible. This leads to:</p><ul><li>Greater adaptability to shifting user demand, as content can be refreshed more frequently.</li><li>Less reliance on preloaded content, reducing the risk of outdated recommendations.</li></ul><p>In contrast, lower bandwidth constraints limit content updates, increasing the likelihood of stale content remaining in cache, which may not align with user preferences. This can impact the overall quality of content recommendations and create potential service delays during periods of high demand.</p><h3>Implications for the Content Distribution Industry</h3><p>The findings from this sensitivity analysis highlight the importance of optimizing storage and bandwidth constraints to balance cost, efficiency, and user experience. These insights are particularly relevant for companies managing large-scale content distribution networks, as they inform strategic decisions such as:</p><ul><li>How much storage to allocate at regional content delivery nodes.</li><li>When and how often to refresh cached content without exceeding bandwidth limits.</li><li>How to optimize infrastructure to maximize content availability while minimizing operational costs.</li></ul><p>By carefully calibrating these variables, companies can reduce content delivery costs, improve streaming performance, and enhance infrastructure resilience.</p><h3>Conclusion</h3><p>The ability to balance storage efficiency and content freshness is a critical factor in the success of any content distribution system. As user demand patterns continue to evolve, adaptive caching strategies must be continuously refined to maintain both efficiency and customer satisfaction. A data-driven approach to content distribution enables organizations to scale their infrastructure effectively while ensuring a seamless and responsive user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f95ff95d07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/optimizing-streaming-content-caching-a-fresh-take-on-multi-cell-optimization-62f95ff95d07">Optimizing Streaming Content Caching: A Fresh Take on Multi-Cell Optimization</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[Braess’s Paradox and the Indian Highway Network: Why More Roads Can Mean More Traffic]]></title>
            <link>https://medium.com/analytics-vidhya/braesss-paradox-and-the-indian-highway-network-why-more-roads-can-mean-more-traffic-c48a412d55ce?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48a412d55ce</guid>
            <category><![CDATA[operations-research]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 23:00:15 GMT</pubDate>
            <atom:updated>2025-02-02T23:00:15.074Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Traffic congestion remains one of Mumbai’s most intractable urban challenges, despite years of significant investment in infrastructure. The city’s roads, including some of its most iconic highways and expressways, have expanded in both scope and capacity, yet gridlocks persist. In fact, some of these expansions have paradoxically worsened congestion, rather than alleviating it.</p><p>This phenomenon, known as <strong>Braess’s Paradox</strong>, was first proposed by Dietrich Braess in 1968. It suggests that adding additional roads to an already congested traffic network can increase overall travel times, rather than reducing them. The key to understanding this paradox lies in the behavior of individual drivers. Each driver, seeking the shortest route, may inadvertently contribute to a systemic slowdown, with the cumulative effect being more traffic and longer delays.</p><h3>Real-World Case Study: The Mumbai Traffic Nightmare</h3><p>Mumbai provides a compelling real-world case for Braess’s Paradox. The city’s <strong>Eastern Freeway</strong>, designed to relieve traffic congestion between South Mumbai and the eastern suburbs, is a prime example. Initially, the new freeway was hailed as a solution to the city’s notorious traffic jams. However, after its completion, more and more drivers began to use the freeway, leading to severe congestion at key entry and exit points, which were not designed to handle the increased traffic volume.</p><p>Similarly, the expansion of the <strong>Western Express Highway</strong> and <strong>Eastern Express Highway</strong> also followed this pattern. While adding lanes and widening the roads was expected to alleviate congestion, the reality was far from being different. As more drivers flocked to these newly expanded routes, the system as a whole became increasingly saturated, with new bottlenecks forming at critical junctions. What was meant to be a relief for the traffic-weary turned into yet another point of gridlock.</p><p>The paradoxical outcome in Mumbai highlights the need for a deeper understanding of traffic flow and network dynamics. Expanding infrastructure without considering the collective behavior of drivers can exacerbate, rather than solve, congestion problems.</p><h3>Modeling Mumbai’s Road Network</h3><p>We’ll focus on a specific area in Mumbai to illustrate this phenomenon. Using the OSMnx library, we can extract and visualize the road network of the selected region.</p><p><strong>Step 1: Extracting the Road Network</strong></p><p>We’ll use OSMnx to download the road network data for a particular area in Mumbai.</p><pre># Define city<br>place_name = &quot;Mumbai, India&quot;<br><br># Get the drive network of the entire city<br>G = ox.graph_from_place(<br>    place_name, <br>    network_type=&quot;drive&quot;, <br>    retain_all=True<br>    )<br><br># Project the graph for better alignment and visualization<br>G = ox.project_graph(G)<br><br># Plot the network<br>fig, ax = plt.subplots(figsize=(25, 25), facecolor=&quot;black&quot;)<br><br>ox.plot_graph(<br>    G, <br>    ax=ax, <br>    bgcolor=&quot;black&quot;, <br>    node_color=&quot;black&quot;, <br>    node_size=2, <br>    edge_color=&quot;black&quot;, <br>    edge_linewidth=0.4, <br>    show=False, <br>    close=False<br>)<br><br># Add north arrow<br>arrow = FancyArrow(0.9, 0.9, 0, 0.05, width=0.01, color=&#39;red&#39;, transform=ax.transAxes)<br>ax.add_patch(arrow)<br>ax.text(0.9, 0.87, &#39;N&#39;, transform=ax.transAxes, color=&#39;black&#39;, fontsize=20, ha=&#39;center&#39;)<br><br>plt.show()</pre><figure><img alt="A visual representation of Mumbai’s road network" src="https://cdn-images-1.medium.com/max/1024/1*01Bf_qf2FyBCUE8WcMCfMA.png" /><figcaption>Fig 1. Visual representation of Mumbai’s road network</figcaption></figure><h4>Step 2: Mathematical Formulation</h4><p>Consider a road network with three main paths between an origin and a destination. Each path has a <strong>travel time function</strong> dependent on traffic flow.</p><p>Let:</p><ol><li><em>weh, eeh, bwsl, shortcut </em>represent the routes to commute from North to South of Mumbai i.e. the Western Express Highway, Eastern Express Highway, Bandra Worli Sea Link and a <strong>new proposed underground route</strong>, respectively.</li><li><em>f(weh), f(eeh), f(bwsl), f(shortcut)</em> be the number of vehicles using different paths.</li><li><em>T(weh), T(eeh), T(bwsl), T(shortcut)</em> be the time taken to travel each path based on traffic flow.</li><li>N represents the projected demand of total number of vehicles on all the above routes after inclusion of the proposed shortcut route</li></ol><h3>Objective Function</h3><p>The goal is to minimize the total travel time across all routes:</p><p><em>Minimize ∑ T(f(i)) * f(i)</em></p><p>which is the travel time function for route , dependent on traffic flow</p><h3>Constraints</h3><p>The optimization problem is subject to:</p><ol><li><strong>Flow Conservation across all routes to meet the projected demand: </strong><em>f(weh) + f(eeh) + f(bwsl) + f(shortcut) = N</em></li><li><strong>Minimum Flow Constraints: </strong><em>f(weh)≥1000 ; f(eeh)≥1200; f(bwsl)≥800; f(shortcut)≥500</em></li><li><strong>Non-Negativity Constraint: </strong><em>f(i) ≥ 0</em></li></ol><h3>Initial Network (Before Adding a Road)</h3><p>The travel time as a function of available paths:</p><ol><li><em>T(weh, x) = 15 + 0.0001(x**2)</em></li><li><em>T(eeh, x) = 20 + 0.00001(x**2)</em></li><li><em>T(bwsl, x) = 10 + 0.00012(x**2)</em></li></ol><p>Where ‘<em>x’</em> represents the traffic <strong>flow variable</strong> for a given route. It determines how many vehicles take a specific path</p><h3>After adding a new underground shortcut route (Connecting North to South Mumbai)</h3><p>Now, drivers have a fourth option using the shortcut:</p><p><em>T(shortcut, x) = g (</em>fixed travel time for shortcut)</p><p>Next, we will try to assess how selfish routing leads to a new equilibrium, often worsening traffic flow.</p><h4>Step 3: Iterative Selfish Routing Approach</h4><p>To accurately model real-world traffic conditions, we use an <strong>iterative self-optimization model</strong> where vehicles dynamically redistribute based on perceived travel time.</p><p>This approach is rooted in the principles of <strong>User Equilibrium (UE)</strong>, a fundamental concept in transportation planning and Operations Research. At equilibrium, no driver can reduce their travel time by unilaterally changing routes. Essentially, each vehicle chooses the fastest available route, but as traffic redistributes, congestion increases, dynamically shifting travel times across the network. Over successive iterations, the system approaches an equilibrium state, similar to a Nash equilibrium in game theory., where each driver chooses the fastest route available at each iteration. Over time, this process stabilizes at an <strong>equilibrium</strong> where <strong>no single driver can improve their travel time by switching routes</strong>.</p><p>The iterative process follows a <strong>gradient-based redistribution model</strong> inspired by proportional routing dynamics in traffic assignment models. The sequence of operations is as follows:</p><ol><li>Compute travel times for all routes based on current traffic flow.</li><li>Identify the fastest route and shift traffic proportionally towards it.</li><li>Repeat until flow changes are insignificant.</li></ol><pre>import numpy as np<br>import networkx as nx<br>import matplotlib.pyplot as plt<br>import ipywidgets as widgets<br>from ipywidgets import interact<br><br>def selfish_routing_optimized(new_road_time):<br>    total_demand = 15000<br>    max_iterations = 50  # Limit iterations for faster convergence<br>    alpha = 0.5  # Step size for gradual redistribution<br><br>    # Travel time functions<br>    def travel_time_weh(flow):<br>        return 15 + 0.0001 * flow**2<br><br>    def travel_time_eeh(flow):<br>        return 20 + 0.00008 * flow**2<br><br>    def travel_time_bws(flow):<br>        return 10 + 0.00012 * flow**2<br><br>    def travel_time_underground(flow):<br>        return new_road_time  # Constant travel time for underground road<br><br>    # Initialize equal distribution of traffic<br>    flows = np.array([total_demand / 4] * 4)<br><br>    for _ in range(max_iterations):<br>        travel_times = np.array([<br>            travel_time_weh(flows[0]),<br>            travel_time_eeh(flows[1]),<br>            travel_time_bws(flows[2]),<br>            travel_time_underground(flows[3])<br>        ])<br>        <br>        # Redistribute flow towards lowest travel time route<br>        best_time = np.min(travel_times)<br>        probabilities = np.exp(-2 * (travel_times - best_time))<br>        probabilities /= probabilities.sum()<br>        <br>        # Adjust flow gradually for stability<br>        new_flows = alpha * probabilities * total_demand + (1 - alpha) * flows<br>        if np.allclose(new_flows, flows, atol=1e-2):  # Stop if small changes<br>            break<br>        flows = new_flows<br><br>    # Compute final travel times<br>    final_travel_times = [<br>        travel_time_weh(flows[0]),<br>        travel_time_eeh(flows[1]),<br>        travel_time_bws(flows[2]),<br>        travel_time_underground(flows[3])<br>    ]<br><br>    # Print results<br>    print(f&quot;Equilibrium Flows &amp; Travel Times:&quot;)<br>    print(<br>        f&quot;  WEH: {flows[0]:.2f} vehicles, <br>        Travel Time: {final_travel_times[0]:.2f} min&quot;<br>        )<br>    print(<br>        f&quot;  EEH: {flows[1]:.2f} vehicles, <br>        Travel Time: {final_travel_times[1]:.2f} min&quot;<br>        )<br>    print(<br>        f&quot;  BWSL: {flows[2]:.2f} vehicles, <br>        Travel Time: {final_travel_times[2]:.2f} min&quot;<br>        )<br>    print(<br>        f&quot;  Underground: {flows[3]:.2f} vehicles, <br>        Travel Time: {final_travel_times[3]:.2f} min&quot;<br>        )<br><br>    # Create network visualization with separate edges for each route<br>    G = nx.DiGraph()<br>    G.add_edges_from([<br>        (<br>            &#39;North Mumbai&#39;, <br>            &#39;South Mumbai (WEH)&#39;,<br>            {&#39;travel_time&#39;: final_travel_times[0], &#39;route&#39;: &#39;WEH&#39;}<br>         ),<br>        (<br>            &#39;North Mumbai&#39;, <br>            &#39;South Mumbai (EEH)&#39;, {&#39;travel_time&#39;: final_travel_times[1], &#39;route&#39;: &#39;EEH&#39;}),<br>        (<br>            &#39;North Mumbai&#39;, <br>            &#39;South Mumbai (BWSL)&#39;, <br>            {&#39;travel_time&#39;: final_travel_times[2], &#39;route&#39;: &#39;BWSL&#39;}<br>        ),<br>        (<br>            &#39;North Mumbai&#39;, <br>            &#39;South Mumbai (Underground)&#39;, <br>            {&#39;travel_time&#39;: final_travel_times[3], &#39;route&#39;: &#39;Underground&#39;}<br>        )<br>    ])<br>    <br>    # Define distinct positions for each route to avoid overlap<br>    pos = nx.spring_layout(G)<br><br>    plt.figure(figsize=(10, 5))<br>    edge_labels = nx.get_edge_attributes(G, &#39;travel_time&#39;)<br>    formatted_labels = {<br>        k: f&quot;{v:.2f} min (<br>        {G.edges[k][&#39;route&#39;]})&quot; for k, v in edge_labels.items()}<br>    <br>    nx.draw(<br>        G, <br>        pos, <br>        with_labels=True, <br>        node_color=&#39;lightblue&#39;, <br>        edge_color=&#39;gray&#39;,<br>        node_size=3000, <br>        font_size=10, <br>        arrows=True<br>        )<br>    <br>    nx.draw_networkx_edge_labels(<br>        G, <br>        pos, <br>        edge_labels=formatted_labels, <br>        font_size=8<br>        )<br>    <br>    plt.title(&quot;Optimized Traffic Network with Multiple Routes&quot;)<br>    plt.show()<br>    <br>    return f&quot;Total equilibrium travel time: {sum(final_travel_times) * total_demand:.2f} vehicle-minutes&quot;<br><br># Interactive widget for underground road travel time<br>interact(<br>    selfish_routing_optimized, <br>    new_road_time = widgets.FloatSlider(<br>        min=0, <br>        max=30, <br>        step=1, <br>        value=5, <br>        description=&quot;New Rd Time&quot;<br>        )<br>        );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bcpzS0lII5YV1WSV4XwDIg.gif" /></figure><h3>Conclusion and Key Takeaways</h3><p>The implementation of <strong>iterative selfish routing</strong> demonstrates how <strong>self-interested decision-making</strong> can lead to unintended inefficiencies in a transportation network. This study, inspired by <strong>Braess’s Paradox</strong>, reveals the paradoxical effect that adding infrastructure does not always improve system-wide performance. Instead, congestion effects and <strong>user equilibrium dynamics</strong> can lead to <strong>increased travel times</strong> for everyone.</p><h3>Key Takeaways:</h3><ol><li><strong>Selfish Routing &amp; Equilibrium:</strong> Traffic naturally redistributes towards the lowest-cost routes until equilibrium is reached.</li><li><strong>Infrastructure Additions Can Backfire:</strong> Introducing a new road can increase congestion instead of reducing it.</li><li><strong>Optimization Is Necessary:</strong> Coordinated interventions, such as tolling or optimized routing, could mitigate inefficiencies caused by selfish behavior.</li><li><strong>Real-World Implications:</strong> This model applies not only to urban road networks but also to <strong>internet traffic, energy distribution, and supply chains</strong> where competing agents optimize independently.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48a412d55ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/braesss-paradox-and-the-indian-highway-network-why-more-roads-can-mean-more-traffic-c48a412d55ce">Braess’s Paradox and the Indian Highway Network: Why More Roads Can Mean More Traffic</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[Celestial Synchronization: An Optimization Based Approach to Maximize…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/operations-research-bit/celestial-synchronization-part-1-of-2-an-optimization-based-approach-to-maximize-d8f4741a1e52?source=rss-5215051ec5c5------2"><img src="https://cdn-images-1.medium.com/max/1600/1*5o0LsTfkdcGS4uLTZJbi7g.jpeg" width="1600"></a></p><p class="medium-feed-snippet">Introduction
In the boundless expanse of space, a captivating dance unfolds&#x200A;&#x2014;&#x200A;a synchronization of satellites and ground stations, each&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/operations-research-bit/celestial-synchronization-part-1-of-2-an-optimization-based-approach-to-maximize-d8f4741a1e52?source=rss-5215051ec5c5------2">Continue reading on Operations Research Bit »</a></p></div>]]></description>
            <link>https://medium.com/operations-research-bit/celestial-synchronization-part-1-of-2-an-optimization-based-approach-to-maximize-d8f4741a1e52?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8f4741a1e52</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[operations-research]]></category>
            <category><![CDATA[space]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[satellite-technology]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 21:50:54 GMT</pubDate>
            <atom:updated>2026-04-14T19:24:46.315Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mathematical Scheduling of Operating Rooms — How Analytics Enable Smoother Hospital  Shifts and…]]></title>
            <link>https://medium.com/analytics-vidhya/mathematical-scheduling-of-operating-rooms-how-analytics-enable-smoother-hospital-shifts-and-501c7edf1120?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/501c7edf1120</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[operations-research]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 19:15:41 GMT</pubDate>
            <atom:updated>2021-01-12T16:09:28.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mathematical Scheduling of Operating Rooms — How Analytics Enable Smoother Hospital Shifts and Stays</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*YACZ_Vbhy71vnydLooHxQw.jpeg" /><figcaption>Image courtesy : <a href="https://www.timesofisrael.com/">https://www.timesofisrael.com/</a></figcaption></figure><h3>Overview</h3><p>Being a data scientist in the healthcare domain and a true mathematician at heart, I have always been fascinated with how complex systems such as that of hospitals efficiently utilize optimization algorithms to make the maximum use of their skilled manpower ensuring highest standards of patient care. This article is based on a case study taken from Cedars-Sinai Hospital in Los Angeles, CA and how they enabled their organization in determining an efficient weekly schedule to assign operating rooms (ORs) to different departments in a hospital with limited resources.</p><h3>Challenges</h3><p>In most hospitals around the country, surgeons are paid based the number of surgeries they perform i.e. ‘<em>fee-for-service</em>’ basis. Unplanned alteration of the OR schedule can directly affect their income. Thus creating an efficient schedule eventually becomes a highly political process within hospitals. Further, each department sets their own targets in terms of number of surgery hours per week which is likely to create internal clashes if the management fails to create an efficient schedule. This calls for the need to apply a mathematical acumen to present an optimized plan that strikes a healthy balance between all departments in the hospital without jeopardizing the quality of treatment. Let us now have a closer look at the sample problem.</p><h3>Problem Definition</h3><p>Cedars-Sinai hospital has 10 operating rooms staffed from Monday to Friday for 8 hours each day. That is,</p><p>10 ORs * 5 days * 8 hours = 400 surgery hours to be efficiently divided among 5 major departments in the hospital namely:</p><ol><li>Department of Gynecology</li><li>Department of Cardiology</li><li>Department of Neurosurgery</li><li>Department of Orthopedics, and</li><li>Department of General Surgery</li></ol><p>We will be solving the above case study by formulating an LPP in Python. All codes and data used in this article can be accessed via my Git repo (<a href="https://github.com/mohiteprathamesh1996/Hospital-OR-Scheduling">https://github.com/mohiteprathamesh1996/Hospital-OR-Scheduling</a>).</p><p>Importing the necessary dependencies,</p><pre>import pandas as pd<br>import numpy as np<br>import itertools<br>from pulp import *<br></pre><pre>from IPython.core.display import display, HTML</pre><pre>def display_side_by_side(dfs:list, captions:list):<br>    &quot;&quot;&quot;Display tables side by side to save vertical space<br>    Input:<br>        dfs: list of pandas.DataFrame<br>        captions: list of table captions<br>    &quot;&quot;&quot;<br>    output = &quot;&quot;<br>    combined = dict(zip(captions, dfs))<br>    for caption, df in combined.items():<br>        output += df.style.set_table_attributes(&quot;style=&#39;display:inline&#39;&quot;).set_caption(caption)._repr_html_()<br>        output += &quot;\xa0\xa0\xa0&quot;<br>    display(HTML(output))</pre><pre><br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><p>As discussed earlier, each department has set the target for number surgery hours for the week as follows:</p><pre>target_hours_per_week = pd.read_excel(&quot;OR Scheduling.xlsx&quot;,         sheet_name=&quot;Target Hours per Week&quot;)</pre><pre>target_hours_per_week.set_index([&quot;Department&quot;], inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*0vCms3G8h4Xo9d5spXVq5Q.png" /></figure><p>Now, each department has a limited number of surgery teams available each day as:</p><pre>teams_available_per_week = pd.read_excel(&quot;OR Scheduling.xlsx&quot;, sheet_name=&quot;Available teams per week&quot;)</pre><pre>teams_available_per_week.set_index([&quot;Department&quot;], inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*5Dkr-BneTMimrhzqiv0RDw.png" /></figure><p>Further, every department can have a maximum daily requirement on the number of ORs for the week as:</p><pre>max_daily_OR_requirement = pd.read_excel(&quot;OR Scheduling.xlsx&quot;, sheet_name=&quot;Max Daily OR requirements&quot;)</pre><pre>max_daily_OR_requirement.set_index([&quot;Department&quot;], inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*ChYvNa2SxhpWY6x2a7R9wg.png" /></figure><h3>Deciding Factors</h3><p>Based on the above available information, the hospital management has to decide how many ORs should each department be assigned on each day for the entire week?</p><p>Let the decision variable in this case be:</p><blockquote><strong>X (j, k) = Number of ORs allocated to department ‘j’ on day ‘k’ (WILL BE AN INTEGER!)</strong></blockquote><p>where j <em>∈ (</em>‘Genecology’, ‘Cardiology’, ‘Neurosurgery’, ‘Orthopedics’,<br> ‘General Surgery’<em>)</em></p><p><em>and k ∈ (</em>‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’<em>)</em></p><pre>teams = teams_available_per_week.index.to_list()<br>day_of_week = teams_available_per_week.columns.to_list()</pre><pre>var_dict = LpVariable.dicts(<br>            &quot;Allotment&quot;,<br>            [(dept, day) for dept in teams for day in day_of_week], <br>            lowBound = 0, <br>            cat = &quot;Integer&quot;)</pre><h3>Objective Function</h3><p>The objective of the hospital management is to assign ORs so as to maximize the proportion of target number of surgery hours per week for each department. That is, if department ‘j’ is aiming for ‘t(j)’ hours of surgery for that week then we have to <strong>Maximize:</strong> <strong>Σ(8 * X(j, k))/t(j)</strong> summed over all departments for the week. This ensures maximum utilization!</p><pre>model = LpProblem(<br>&quot;Optimized Allocation of Hospital Operating Rooms&quot;, <br>LpMaximize)</pre><pre><br>model += lpSum(<br>[8*var_dict[(team,days)]/target_hours_per_week.loc[team, &quot;Target_Hours&quot;] for team in teams for days in day_of_week])</pre><h3>Constraints</h3><p>At any given day, the hospital has at the most 10 ORs available which should be scheduled for surgery across these 5 departments.</p><p>Thus ,</p><p><strong>0 ≤ Σ X (j, k) ≤ 10</strong></p><p>where ‘j’ <em>∈ (</em>‘Genecology’, ‘Cardiology’, ‘Neurosurgery’, ‘Orthopedics’,<br> ‘General Surgery’<em>) </em>and ‘k’ is held constant for that day of the week.</p><pre>for day in day_of_week:<br>    model += lpSum([var_dict[(team, day)] for team in teams]) &lt;= 10</pre><p>Next, the number of allocated ORs for a department cannot exceed the number of available teams that day for that department.</p><p>That is,</p><p><strong>0 ≤ X (j, k) ≤ Number of teams available for department ‘j’ on day ‘k’</strong></p><pre>for team in teams:<br>    for day in day_of_week:<br>        model += var_dict[(team, day)] &lt;= teams_available_per_week.loc[team, day]</pre><p>Lastly, we must satisfy the daily maximum requirement of each department.</p><p>Therefore,</p><p><strong>0 ≤ X (j, k) ≤ Maximum ORs required by department ‘j’ on day ‘k’</strong></p><pre>for team in teams:<br>    for day in day_of_week:<br>        model += var_dict[(team, day)] &lt;= max_daily_OR_requirement.loc[team, day]</pre><h3>Optimal Solution</h3><p>Now that we have defined the decision variables, formulated the objective function along with the constraints, we can obtain the optimal solution as follows. The code below outputs the most mathematically efficient OR schedule!</p><pre>model.solve()</pre><pre><br>if LpStatus[model.status]==&quot;Optimal&quot;:<br>    optimal_soln = pd.DataFrame(<br>[(v.name, <br>int(v.varValue)) for v in model.variables() if v.varValue!=0],<br>columns=[&quot;Decisions&quot;, &quot;# ORs Allocated&quot;])</pre><pre><br>display_side_by_side(dfs = [optimal_soln[optimal_soln[&quot;Decisions&quot;].str.contains(d)].reset_index(drop=True) for d in day_of_week],<br>captions = [&quot;Operating Room Schedule for &quot;+i for i in day_of_week])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yXA0Kri0g7T9HwgNOJbTA.png" /></figure><p>Feel free to drop in your comments or suggestions if you’ve enjoyed reading this article! Thank you for your time.</p><p>Let’s connect on LinkedIn! <a href="https://www.linkedin.com/in/prathameshmohite96/">https://www.linkedin.com/in/prathameshmohite96/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=501c7edf1120" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/mathematical-scheduling-of-operating-rooms-how-analytics-enable-smoother-hospital-shifts-and-501c7edf1120">Mathematical Scheduling of Operating Rooms — How Analytics Enable Smoother Hospital  Shifts and…</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[The Perfect Match!]]></title>
            <link>https://medium.com/analytics-vidhya/the-perfect-match-57c253c8b9b3?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/57c253c8b9b3</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[organ-donation]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[operations-research]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Sun, 03 Jan 2021 21:21:32 GMT</pubDate>
            <atom:updated>2021-01-04T16:44:27.180Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Perfect Match: Pairing Organ Donors and Recipients using Multi-Objective Linear Optimization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*6bdnlF2lLq_be_InKTdezA.jpeg" /><figcaption>Image courtesy: <a href="https://www.fairtransplant.org/thelogo/">https://www.fairtransplant.org/thelogo/</a></figcaption></figure><p>If you’ve ever been enthralled by the idea of having life after death, there’s a high probability of you encountering a person who is living a second life. Thanks to the phenomenal efforts made by medical researchers around the globe, that have given rise to advanced surgical procedures and finally made organ donation and transplantation a reality. However, despite having 90 percent of US adults support for organ donation, less than 60 percent of them actually sign up as a registered donor. Further statistics indicate the increasing rate of waiting list of recipients by 1 person every 9 minutes, with an average of 17 deaths per day the lives which could have been saved had they received the transplant at the right moment.</p><p>This article is an attempt to utilize the potential of large scale multi-objective optimization to devise a mechanism that efficiently pairs potential donors with their recipients ensuring maximum compatibility in a minimum timeframe and a high post-surgical survival rate.</p><blockquote>All codes and data can be found via my GitHub repo: <a href="https://github.com/mohiteprathamesh1996/Heart-Donor-Pairing">https://github.com/mohiteprathamesh1996/Heart-Donor-Pairing</a></blockquote><h3>Importing necessary dependencies</h3><pre>import random<br>import pandas as pd<br>from tqdm import tqdm<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import itertools<br>import re<br>from pulp import *</pre><pre>from IPython.core.display import display, HTML</pre><pre>def display_side_by_side(dfs:list, captions:list):<br>    &quot;&quot;&quot;Display tables side by side to save vertical space<br>    Input:<br>        dfs: list of pandas.DataFrame<br>        captions: list of table captions<br>    &quot;&quot;&quot;<br>    output = &quot;&quot;<br>    combined = dict(zip(captions, dfs))<br>    for caption, df in combined.items():<br>        output += df.style.set_table_attributes(&quot;style=&#39;display:inline&#39;&quot;).set_caption(caption)._repr_html_()<br>        output += &quot;\xa0\xa0\xa0&quot;<br>    display(HTML(output))</pre><pre>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><h3>Data Description</h3><p>For the purpose of this problem statement, I have created a sample dataset for recipients awaiting a heart transplant.</p><ol><li><em>Pre-Surgical donor compatibility with recipient:</em></li></ol><pre>compatibility = pd.read_excel(&quot;donor_recepient_information.xlsx&quot;, sheet_name=&quot;pre_surgical_compatibility&quot;)</pre><pre>compatibility.set_index([&quot;Donor&quot;], inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*dUf26TzkqVBWjbaMwXrtlA.png" /></figure><p>This overall compatibility of heart transplant from Donor ‘i’ to Recipient ‘j’ is based on how well the donor’s heart fits comfortably inside the rib cage of the recipient.</p><p>2. <em>Time to reach from donor to recipient (in hours):</em></p><pre>time_to_reach = pd.read_excel(&quot;donor_recepient_information.xlsx&quot;, sheet_name=&quot;TimeToReach&quot;)</pre><pre>time_to_reach.set_index([&quot;Donor&quot;], inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*MSF5fO9PC1bxgUNnNlcI8g.png" /></figure><p>The entire transplantation procedure must occur within 4 to 6 hours after a registered donor has officially died or has been declared brain dead. The above data indicates how much time (in hours) would it take to reach a prospective donor from it’s recipient.</p><p>3. <em>Post-Surgical Survival Rate:</em></p><pre>survival = pd.read_excel(&quot;donor_recepient_information.xlsx&quot;, sheet_name=&quot;post_surgical_survival_rate&quot;)</pre><pre>survival.set_index([&quot;Donor&quot;], inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*YtndyfL-NTkmpvNFUpDUrQ.png" /></figure><p>This dataset reveals information about the projected survival rate of the recipient 4 to 5 years after receiving the transplant. Modern transplantation procedures have enabled to boost this metric to a range of 60–90%.</p><h3>Decision Variables</h3><p>Here we can define the binary decision variable, <em>X(i, j)</em> such that</p><blockquote><em>X (i, j) = 1 if Donor ‘i’ is paired with Recipient ‘j’</em></blockquote><blockquote><em>and 0 otherwise, For all i ∈ [1,…,20] and j ∈ [1,…,20]</em></blockquote><pre># List of donors<br>donor_list = compatibility.index.to_list()</pre><pre># List of recipients<br>recipient_list = compatibility.columns.to_list()</pre><pre># Dictionary of binary decision variables<br>var_dict = LpVariable.dicts(<br>name = &quot;Match Found&quot;,<br>indexs = [(d, r) for d in donor_list for r in recipient_list], <br>cat = &quot;Binary&quot;)</pre><h3>Defining the Objective Functions</h3><p>As mentioned earlier, our task now is to optimize 3 objective functions all at once i.e.:</p><ol><li>Maximize -&gt; Overall pre-surgical compatibility:</li></ol><blockquote><strong>Maximize, Objective_1 = Σ Σ Compatibility(i, j) * X (i, j)</strong></blockquote><blockquote><strong><em>For all i ∈ [1,…,20] and j ∈ [1,…,20]</em></strong></blockquote><p>2. Minimize -&gt; Overall time to reach potential donor</p><blockquote><strong>Minimize, Objective_2 = Σ Σ Time(i, j) * X (i, j)</strong></blockquote><blockquote><strong><em>For all i ∈ [1,…,20] and j ∈ [1,…,20]</em></strong></blockquote><p>3. Maximize -&gt; Overall survival rate of all recipients post-surgery</p><blockquote><strong>Maximize, Objective_3 = Σ Σ Survival Rate(i, j) * X (i, j)</strong></blockquote><blockquote><strong><em>For all i ∈ [1,…,20] and j ∈ [1,…,20]</em></strong></blockquote><pre># Objective 1: Maximize donor compatibility<br>objective_1 = lpSum(<br>[compatibility.loc[d, r]*var_dict[(d, r)] \<br>for d in donor_list for r in recipient_list])<br></pre><pre># Objective 2: Minimize time to reach the nearest donor<br>objective_2 = lpSum(<br>[time_to_reach.loc[d, r]*var_dict[(d, r)] \<br>for d in donor_list for r in recipient_list])<br></pre><pre># Objective 3: Maximize post surgery survival probability<br>objective_3 = lpSum(<br>[survival.loc[d, r]*var_dict[(d, r)]\<br> for d in donor_list for r in recipient_list])</pre><p>When it comes to a multi-objective optimization problem, the most general technique would be to adopt a weighted sum approach, i.e. we basically assign weights to each of the objective functions and formulate a single-objective LP such as,</p><p><strong>Maximize, Z = W1*Objective_1 + W2*(-Objective_2) + W3*Objective_3</strong></p><p>Where W1, W2 and W3 are the weights assigned to each objective such that</p><p>W1, W2, W3 ∈ [0, 1] and W1 +W2 + W3</p><p>*In order to define the single objective function as a maximization problem, it’s important to have all independent objective functions in the same direction which is why you can see why I have multiplied the Objective_2, which is supposed to be a minimization problem, with a minus sign.</p><h3>Constraints</h3><p>The pairing must be done in a way such that each recipient can receive transplantation from <strong>exactly 1</strong> donor and likewise every donor can donate to <strong>exactly 1</strong> prospective recipient.</p><p>That is,</p><p><strong>Σ X (i, j) = 1 where i (the donors) is a constant and j (the recipients)<em>∈ [1,…,20]</em></strong></p><p><strong>Σ X (i, j) = 1 where j (the recipients) is a constant and i (the donors)<em>∈ [1,…,20]</em></strong></p><h3>Obtaining the feasible space and corner point of optimality</h3><p>Let us now formulate the above LP with the single objective function and including all constraints as a Python code and iterate over multiple combinations of weights and obtain a feasible space of optimal solutions. We will be running the code to obtain a new solutions for about 1000 iterations:</p><pre>solutions = []</pre><pre>for num in tqdm(range(1000)):<br>    weights = np.array([random.random(), random.random(), random.random()])</pre><pre># Ensuring sum of all weights adds up to 1<br>    weights = weights/sum(weights)</pre><pre># Define the maximization LPP<br>    model = LpProblem(&quot;Best Match&quot;, LpMaximize)</pre><pre># Define single objective<br>    model += (weights[0] * objective_1) + (weights[1] * -objective_2) + (weights[2] * objective_3)</pre><pre># LP constraints<br>    #----Constraint_1 -&gt; A donor can donate to only one recipient<br>    for d in donor_list:<br>        model += lpSum([var_dict[(d, r)] for r in recipient_list]) == 1</pre><pre>#----Constraint_2 -&gt; A recipient can recieve from only 1 donor<br>    for r in recipient_list:<br>        model += lpSum([var_dict[(d, r)] for d in donor_list]) == 1</pre><pre># Solving the LP<br>    model.solve()</pre><pre># Saving results<br>    solutions.append([objective_1.value(), <br>                      -objective_2.value(),<br>                      objective_3.value(), <br>                      value(model.objective),<br>                      [(v.name,v.varValue) for v in model.variables() if v.varValue!=0]])</pre><pre># Save optimized results as a dataframe<br>df_optimal = pd.DataFrame(solutions, columns=[&quot;Objective_1&quot;, <br>                                              &quot;Objective_2&quot;,<br>                                              &quot;Objective_3&quot;,<br>                                              &quot;Single_Objective&quot;,<br>                                              &quot;Optimal_Solution&quot;])</pre><pre>df_optimal.sort_values(by=[&quot;Single_Objective&quot;], ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*hY1NRxktKzyXYrS-jpMTZQ.png" /></figure><h3>Visualizing the 3-Dimensional feasible space</h3><pre>from mpl_toolkits.mplot3d import Axes3D<br>import matplotlib.pyplot as plt</pre><pre>%matplotlib notebook<br>plt.rcParams[&quot;figure.figsize&quot;] = (8, 5)<br>fig = plt.figure()<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)</pre><pre>ax.scatter(df_optimal[df_optimal[&quot;Single_Objective&quot;]!=max(df_optimal[&quot;Single_Objective&quot;])][&quot;Objective_1&quot;], <br>           df_optimal[df_optimal[&quot;Single_Objective&quot;]!=max(df_optimal[&quot;Single_Objective&quot;])][&quot;Objective_2&quot;],<br>           df_optimal[df_optimal[&quot;Single_Objective&quot;]!=max(df_optimal[&quot;Single_Objective&quot;])][&quot;Objective_3&quot;], <br>           c=&#39;green&#39;,<br>           marker=&#39;+&#39;,<br>           label = &quot;Feasible solutions&quot;)</pre><pre>ax.scatter(df_optimal[df_optimal[&quot;Single_Objective&quot;]==max(df_optimal[&quot;Single_Objective&quot;])][&quot;Objective_1&quot;], <br>           df_optimal[df_optimal[&quot;Single_Objective&quot;]==max(df_optimal[&quot;Single_Objective&quot;])][&quot;Objective_2&quot;],<br>           df_optimal[df_optimal[&quot;Single_Objective&quot;]==max(df_optimal[&quot;Single_Objective&quot;])][&quot;Objective_3&quot;], <br>           c=&#39;red&#39;,<br>           s=100,<br>           marker=&#39;*&#39;, <br>           label = &quot;Net Optimal Solution&quot;)</pre><pre>ax.set_xlabel(&#39;Objective 1&#39;)<br>ax.set_ylabel(&#39;Objective 2&#39;)<br>ax.set_zlabel(&#39;Objective 3&#39;)</pre><pre>plt.legend()</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*n3rdZ7GKm8SYjELLTDvMnQ.png" /></figure><p>We have finally arrived with our set of feasible solutions. The corner point (red star) is where you can find your optimal solution! The 3-dimensional surface formed as a result of all feasible solutions is also known as the Pareto Optimal Frontier named after the Italian engineer and economist <a href="https://en.wikipedia.org/wiki/Vilfredo_Pareto">Vilfredo Pareto</a> (1848–1923).</p><h3>Finding the best match</h3><p>The ideal pair of the most compatible Donor s and Recipients can be obtained based on the optimal corner point in the above figure.</p><pre>best_pair = df_optimal[df_optimal[&quot;Single_Objective&quot;]==max(df_optimal[&quot;Single_Objective&quot;])]</pre><pre>status = pd.DataFrame(list(best_pair[&quot;Optimal_Solution&quot;])[0], columns = [&quot;Decisions&quot;,&quot;Compatibility&quot;])</pre><pre>status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*CcPNFwWCOxMesIhT5CKRHw.png" /></figure><p>I really hope you have enjoyed reading this article. Feel free to drop in your comments or suggestions. Thank you for your time!</p><p>Feel free to connect with me on LinkedIn :) <a href="https://www.linkedin.com/in/prathameshmohite96/">https://www.linkedin.com/in/prathameshmohite96/</a></p><h3>References</h3><ol><li><a href="https://www.organdonor.gov/statistics-stories/statistics.html">https://www.organdonor.gov/statistics-stories/statistics.html</a></li><li><a href="https://www.donatelife.net/types-of-donation/heart-donation/#:~:text=When%20a%20donor%20heart%20becomes,matching%20process%20for%20all%20organs">https://www.donatelife.net/types-of-donation/heart-donation/#:~:text=When%20a%20donor%20heart%20becomes,matching%20process%20for%20all%20organs</a>.</li><li>Dimitris Bertsimas. <em>15.071 The Analytics Edge. </em>Spring 2017. Massachusetts Institute of Technology: MIT OpenCourseWare, <a href="https://ocw.mit.edu/courses/sloan-school-of-management/15-071-the-analytics-edge-spring-2017">https://ocw.mit.edu</a>. License: <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons BY-NC-SA</a>.</li><li><a href="https://www.youtube.com/channel/UCTNr86XHH__llwylQ62QdZw/videos">https://www.youtube.com/channel/UCTNr86XHH__llwylQ62QdZw/videos</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57c253c8b9b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/the-perfect-match-57c253c8b9b3">The Perfect Match!</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[Crude Blending — Gaining a Competitive Edge in the Oil & Gas Industry through Linear Programming]]></title>
            <link>https://medium.com/analytics-vidhya/crude-blending-gaining-a-competitive-edge-in-the-oil-gas-industry-through-linear-programming-32c0709c5d6a?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/32c0709c5d6a</guid>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 02:32:57 GMT</pubDate>
            <atom:updated>2021-01-03T16:44:17.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crude Blending — Gaining a Competitive Edge in the Oil &amp; Gas Industry through Linear Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*imvKXoINaLDrBpIdkHI6BQ.jpeg" /><figcaption>Image Courtesy: <a href="https://finfeed.com/features/oil-and-gas-juniors-looking-goods/">https://finfeed.com/features/oil-and-gas-juniors-looking-goods/</a></figcaption></figure><p>The Oil &amp; Gas sector is globally regarded as the 3rd largest industry after Health Insurance and Pension Funds, generating a revenue close to USD $3.3 trillion over the last 5 years. It is widely considered as the lifeline to sustain the businesses of major industries such as Defense, Aviation and Transportation.</p><p>Crude oil, commonly known as “black gold” is a scarce resource which when carefully distilled in a refinery passing through series of chemical processes, synthesizes to produce useful products that run our daily lives such as Petrol (or Motor Spirit), Diesel, Kerosene, Paraffins, Jet Fuel, etc. It is due to this global scarcity of crude combined with several geographic, technical and socio-political challenges of setting up complexed processes in a refinery that makes oil companies around the globe to lock horns with each other in order to gain worldwide dominance.</p><h3>Overview of Crude Blending</h3><p>One of the ways for an already constrained organization, to gain a competitive edge over other candidates in the Oil &amp; Gas industry is through ‘crude blending’ or simply stated, the process of combining different grades of crude oil in varying ratios to produce products for distribution by maximizing it’s profit margin and satisfying their customers’ daily demand without compromising the quality of product or causing any significant impact to the environment. Through this article, we will try to gain a basic step-by-step understanding of how blending operations in a refinery can be modelled as a linear programming problem in Python and solve it to obtain the optimal blending proportions.</p><h3>Defining a problem for a fictitious oil refinery</h3><p>Importing required libraries.</p><pre>import pandas as pd<br>import numpy as np<br>import itertools<br>from tqdm import tqdm<br>from pulp import *<br>import matplotlib.pyplot as plt<br>from IPython.core.display import display, HTML</pre><pre>def display_side_by_side(dfs:list, captions:list):<br>    &quot;&quot;&quot;Display tables side by side to save vertical space<br>    Input:<br>        dfs: list of pandas.DataFrame<br>        captions: list of table captions<br>    &quot;&quot;&quot;<br>    output = &quot;&quot;<br>    combined = dict(zip(captions, dfs))<br>    for caption, df in combined.items():<br>        output += df.style.set_table_attributes(&quot;style=&#39;display:inline&#39;&quot;).set_caption(caption)._repr_html_()<br>        output += &quot;\xa0\xa0\xa0&quot;<br>    display(HTML(output))</pre><pre>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><blockquote>All data and code used in this article can be accessed through my GitHub repository: <a href="https://github.com/mohiteprathamesh1996/Crude-Blending.git">https://github.com/mohiteprathamesh1996/Crude-Blending.git</a></blockquote><p>Let’s read the files have a look at the data,</p><pre>raw_crude_df = pd.read_excel(&quot;Crude Blending.xlsx&quot;, sheet_name=&quot;Raw Crude&quot;)<br>raw_crude_df.set_index([&quot;Crude Type&quot;], inplace=True)</pre><pre>products_df = pd.read_excel(&quot;Crude Blending.xlsx&quot;, sheet_name=&quot;Products&quot;)<br>products_df.set_index([&quot;Product Name&quot;], inplace=True)</pre><pre># Display data<br>display_side_by_side(dfs=[raw_crude_df, products_df], <br>                     captions=[&quot;Raw Crude&quot;, &quot;Blended Products from Raw Crude&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*ks32Er7ayvjqvn5OylA4yg.png" /></figure><p>We can see we that the oil refinery produces 3 types of petroleum products namely Fuel_1, Fuel_2 and Fuel_3 by blending 5 different types of crude oil i.e. West Texas Intermediate, Brent, Saharan Blend and BCF-17. Through a linear programming approach, we have to build a model that maximize the net operational revenue of the refinery’s operations.</p><h3>Decision Variables</h3><p>Let us define the decision variable</p><blockquote>X(c, p) = Number of barrels of crude type ‘c’ required to make petroleum product ‘p’ for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></blockquote><pre># List of crude types<br>crude_types = raw_crude_df.index.to_list()</pre><pre># List of petroleum products<br>products = products_df.index.to_list()</pre><pre># Dictionary of decision variables<br>var_dict = LpVariable.dicts(&quot;Blends&quot;, <br>[(crude, product) <br>for crude in crude_types <br>        for product in products], <br>                            lowBound=0, <br>                            cat=&quot;Integer&quot;)</pre><pre># Display decision variables<br>print(var_dict)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*l1N7zO-2X6uSxflGyyTnyw.png" /></figure><h3>Defining the Objective Function</h3><p>Framing the above LP as a maximization problem, we can define out objective function as :</p><blockquote><strong>Maximize, Z = Selling Price — (Purchasing Cost + Conversion cost)</strong></blockquote><p>Where,</p><p><strong>Purchasing Cost</strong> <strong>for each type of crude oil = Σ Cost(c)*Σ(X(c, p))</strong> for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><p>Assuming a $4 cost of converting each barrel of crude oil to finished product,</p><p><strong>Conversion cost</strong> <strong>= Σ(X(c, p))</strong> for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><p><strong>Selling Price</strong> <strong>for each finished petroleum product =</strong> <strong>Σ Cost(p)*Σ(X(c, p))</strong> for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><pre># Model initialization<br>model = LpProblem(&quot;Optimized Blending of Crude Oil Types&quot;, LpMaximize)</pre><pre># Objective Function<br>purchasing_cost = lpSum(<br>[raw_crude_df.loc[c, &quot;Purchasing Price Per Barrel&quot;] * var_dict[(c,p)]for c in crude_types for p in products])</pre><pre>conversion_cost = lpSum(<br>[4 * var_dict[(c, p)] for c in crude_types for p in products])</pre><pre>selling_price = lpSum(<br>[products_df.loc[p, &quot;Selling Price per Barrel&quot;] * var_dict[(c, p)] \<br>        for p in products for c in crude_types])</pre><pre><br>model += selling_price - (purchasing_cost + conversion_cost)</pre><h3>Setting Constraints</h3><p>Let’s say that the above refinery has budget to purchase at most 7,500 barrels per day of each type of crude oil, i.e.</p><p><strong>ΣX(c, p1)+ΣX(c, p2)+….+ΣX(c, pN) ≤ 7,500</strong> for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><pre>#1 Upto 7500 barrels of each crude type can be purchased per day<br>for c in crude_types:<br>    model += lpSum([var_dict[(c, p)] for p in products]) &lt;= 7500</pre><p>Next, we must ensure that each blended finished product has to satisfy the minimum Octane rating, i.e.</p><p><strong>Σ(Octane Rating (c)*X(c, p)) ≥ Octane Rating (p)*ΣX(c,p) </strong>for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><pre>#2 Fuel quality based on Octane number<br>for p in products:<br>    model += lpDot(<br>[var_dict[(c,p)] for c in crude_types],<br>[raw_crude_df.loc[c, &quot;Octane Number&quot;] for c in crude_types])\<br>               &gt;= products_df.loc[p, &quot;Octane Number&quot;] * lpSum([var_dict[(c, p)] for c in crude_types])</pre><p>Further, the refinery is constrained by its labor laws and other internal logistical hassles to produce at most 50,000 barrels per day of finished products, i.e.</p><p><strong>ΣX(c,p) ≤ 50,000 </strong>for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><pre>#3 Maximum production capacity of 50000 barrels per day<br>model += lpSum(<br>[var_dict[(c, p)] for c in crude_types for p in products]) &lt;= 50000</pre><p>The refinery must also satisfy the daily customer demand of specific number of barrels per day, i.e.</p><p><strong>ΣX(c1, p)+ΣX(c2, p)+….+ΣX(cN, p) = Demand(p) </strong>for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><pre>#4 Fulfill daily customer demand <br>for p in products:<br>    model += lpSum([var_dict[(c,p)] for c in crude_types]) == products_df.loc[p, &quot;Demand&quot;]</pre><p>Lastly, the finished product must adhere to certain environmental norms so as to limit it’s sulfur concentration, i.e.</p><p><strong>Σ(Sulfur Content(c)*X(c, p)) ≤ Sulfur Content(p)*ΣX(c,p) </strong>for all c<em>∈(</em>West Texas Intermediate, Brent, Saharan Blend and BCF-17<em>) and p∈(</em>Fuel_1, Fuel_2 and Fuel_3<em>)</em></p><pre>#5 Sulfur content limitations<br>for p in products:<br>    model += lpDot(<br>[var_dict[(c,p)] for c in crude_types],<br>[raw_crude_df.loc[c, &quot;Sulfur content (%)&quot;] for c in crude_types])\<br>               &lt;= products_df.loc[p, &quot;Allowable Sulfur (%)&quot;] * lpSum([var_dict[(c, p)] for c in crude_types])</pre><h3>Optimal Solution</h3><p>Last step, we solve the above LP problem and obtain the optimal blending proportions for each type of crude oil to produce finished products.</p><pre># Solve the mode<br>model.solve()</pre><pre># Saving the optimal solution results<br>if LpStatus[model.status]==&quot;Optimal&quot;:<br>    optimal_soln = pd.DataFrame(<br>[(v.name, <br>int(v.varValue)) for v in model.variables() if v.varValue!=0],<br>                        columns=[&quot;Decisions&quot;, &quot;Number of Barrels&quot;])</pre><p>The optimal solution obtained is as follows.</p><pre>print(&quot;Total Profit : USD $ {}&quot;.format(round(value(model.objective), 2)))</pre><pre>display_side_by_side(<br>    dfs=[round(100 * np.divide(optimal_soln[optimal_soln[&quot;Decisions&quot;].str.contains(p)]\<br>                   .set_index(&quot;Decisions&quot;),<br>                   optimal_soln[optimal_soln[&quot;Decisions&quot;].str.contains(p)]\<br>                   .set_index(&quot;Decisions&quot;).sum()), 2).rename(columns={&quot;Number of Barrels&quot;:&quot;Blend_Perc (%)&quot;})\<br>         for p in products], <br>    captions=[&quot;Optimal Blending Proportions for &quot;+i for i in products])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*9L6_gVkBTmX9yc8tLmJRZw.png" /></figure><h3>References</h3><ol><li><a href="https://finfeed.com/features/oil-and-gas-juniors-looking-goods/">https://finfeed.com/features/oil-and-gas-juniors-looking-goods/</a></li><li><a href="https://ocw.mit.edu/courses/sloan-school-of-management/15-071-the-analytics-edge-spring-2017/integer-optimization/">https://ocw.mit.edu/courses/sloan-school-of-management/15-071-the-analytics-edge-spring-2017/integer-optimization/</a></li><li><a href="https://www.ibisworld.com/global/industry-trends/biggest-industries-by-revenue/">https://www.ibisworld.com/global/industry-trends/biggest-industries-by-revenue/</a></li><li><a href="https://medium.com/syncedreview/how-ai-can-help-the-oil-industry-b853dda86be6">https://medium.com/syncedreview/how-ai-can-help-the-oil-industry-b853dda86be6</a></li><li><a href="https://www.sensiaglobal.com/Measurement/Types/Blending/Crude-Oil-Condensate-Blending#:~:text=Overview,minimum%20higher%20cost%20crude%20oil">https://www.sensiaglobal.com/Measurement/Types/Blending/Crude-Oil-Condensate-Blending#:~:text=Overview,minimum%20higher%20cost%20crude%20oil</a>.</li><li><a href="https://medium.com/protoil-tank-farm/oil-blending-d2503ea91cfd">https://medium.com/protoil-tank-farm/oil-blending-d2503ea91cfd</a></li></ol><p>I really hope you have enjoyed reading this article. Feel free to drop in your comments or suggestions. Thanks.</p><p>Let’s connect on LinkedIn: https://www.linkedin.com/in/prathameshmohite96/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32c0709c5d6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/crude-blending-gaining-a-competitive-edge-in-the-oil-gas-industry-through-linear-programming-32c0709c5d6a">Crude Blending — Gaining a Competitive Edge in the Oil &amp; Gas Industry through Linear Programming</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[Optimized Allocation of Streams to Heat Exchangers — Framing a Minimization Problem using Python’s…]]></title>
            <link>https://medium.com/analytics-vidhya/optimized-allocation-of-streams-to-heat-exchangers-framing-a-minimization-problem-using-pythons-b7c936f9a6b5?source=rss-5215051ec5c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7c936f9a6b5</guid>
            <category><![CDATA[oil-and-gas]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[algebra]]></category>
            <category><![CDATA[operations-research]]></category>
            <dc:creator><![CDATA[Prathamesh Mohite]]></dc:creator>
            <pubDate>Mon, 28 Dec 2020 00:28:45 GMT</pubDate>
            <atom:updated>2021-01-03T16:49:42.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimized Allocation of Streams to Heat Exchangers — Framing a Minimization Problem using Python’s PuLP module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzYYi3PcwTUc7-khR2C7Ig.jpeg" /><figcaption><em>Source: </em><a href="https://www.fluor.com/projects/esso-refinery-epc"><em>https://www.fluor.com/projects/esso-refinery-epc</em></a></figcaption></figure><h3>Introduction</h3><p>If you’ve spent a considerable amount of time working in an oil refinery, chances are you might have come across these systematically arranged gigantic structures like the ones above. In mechanical terms, this system is that of a ‘shell-and-tube’ type heat exchangers primarily deployed for the purpose of transferring or exchanging heat from a stream of high temperature fluid to another stream of low temperature fluid or vice versa.</p><p>An optimized arrangement of heat exchangers can enable an efficient channel for industrial fluids to be re-directed in other processes or ensure proper discharge in adjacent water bodies without causing significant environmental impact. Through this article, we will try to formulate a linear programming problem using Python’s PuLP module in systematically assigning streams of fluid outlets from multiple sources to a set of heat exchangers ensuring minimal wastage of raw materials and preventing intermixing of fluids with an objective to minimize the overall installation cost.</p><h3>Problem definition</h3><p>Importing required libraries</p><pre>import pandas as pd<br>import numpy as np<br>import itertools<br>from pulp import *</pre><pre>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><blockquote>All the data and code used for this article can be accessed via my GitHub repo: <a href="https://github.com/mohiteprathamesh1996/Heat-Exchanger-Assignment-">https://github.com/mohiteprathamesh1996/Heat-Exchanger-Assignment-</a></blockquote><p>Now let’s have a look at the data available:</p><pre>df = pd.read_excel(&quot;Heat Exchanger Assignment Optimization.xlsx&quot;, sheet_name=&quot;Installation Costs&quot;)</pre><pre>df.set_index(&quot;Streams&quot;, inplace=True)</pre><pre>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76mmPSI0X9a6Qvc4x6huZQ.png" /></figure><p>The above table shows the various costs (in USD $) associated with assigning outputs from 10 fluid streams to 10 different heat exchangers. The actual cost of assigning stream i where i <strong>∈ (</strong>1,…,10) to heat exchanger j where j <strong>∈ </strong>(1,…,10) may vary depending on several factors like the length of pipe used, distance from exchanger stations, raw materials and manpower required, etc. Our objective now is “to assign each of these streams to their respective exchangers at the least possible cost such that each stream goes to exactly 1 exchanger and conversely each exchanger receives its input from exactly 1 stream.”</p><h3>Decision Variables</h3><p>In this problem we define the binary decision variable, X(i, j) such that</p><blockquote>X (i, j) = 1 if stream ‘i’ is assigned for exchanger ‘j’ else 0 for all i∈ (1,..10)and j ∈ (1,…10)</blockquote><pre># Create a list of stream indexes<br>streams = df.index.to_list()<br>print(&quot;Streams : {} \n&quot;.format(streams))</pre><pre># Create a list of indexes for exchangers<br>exchanger_stations = df.columns.to_list()<br>print(&quot;Heat Exchangers : {} \n&quot;.format(exchanger_stations))</pre><pre># Create a dictionary of binary type decision variables<br>var_dict = LpVariable.dicts(<br>    name=&quot;assign&quot;,<br>    indexs=[(i, j) for i in streams for j in exchanger_stations], <br>    lowBound=0,<br>    cat=&quot;Binary&quot;)</pre><pre># Display first 5 decision variables<br>[var_dict[(i,j)] for i in streams for j in exchanger_stations][:5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*KqhK1QcUL0C5jnG9en7-ag.png" /></figure><h3>Defining the Objective Function</h3><p>Framing the above LP as a minimization problem, we can define out objective function as :</p><p><strong>Minimize, Z = 949*X(1,1) + 1176*X(1,2)+….+1055*X(10,9) + 1175*X(10,10)</strong></p><p>Mathematically,</p><p>Minimize, <strong>Z = Σ C(i,j)*X(i,j)</strong> where C (i, j) is the cost of assigning stream ‘i’ to exchanger ‘j’, for all i <strong>∈ (</strong>1,…,10) and j <strong>∈ </strong>(1,…,10) as seen in the above table.</p><pre># Define the LP Minimization problem<br>model = LpProblem(&quot;Minimize Installation Costs&quot;, LpMinimize)<br></pre><pre># Adding the objective function <br>model += lpSum([df.loc[(i,j)]*var_dict[(i,j)] \<br>                for i in streams \<br>                        for j in exchanger_stations])</pre><h3>Constraints</h3><p>As discussed earlier, the LP is constrained such that the outlet of each stream goes to exactly 1 exchanger and conversely each exchanger receives its input from exactly 1 stream.</p><p>First, the constraint on the streams. Here we treat the stream index ‘i’ as a constant and iterate over every exchanger station. Mathematically, <strong>Σ X(j)=1</strong></p><pre># Each stream must be assigned to exactly 1 heat exchanger<br>for i in streams:<br>    model += lpSum([var_dict[(i, j)] \<br>                          for j in exchanger_stations]) == 1</pre><p>Next, the constraint on the exchangers. Here we treat the exchanger index ‘j’ as a constant and iterate over the stream outlets. Mathematically, <strong>Σ X(i)=1</strong></p><pre># Every heat exchanger must receive input from exactly 1 stream    <br>for j in exchanger_stations:<br>    model += lpSum([var_dict[(i, j)] \<br>                          for i in streams]) == 1</pre><h3>Optimal Solution</h3><p>In this last step, we solve the above LP and obtain the optimal pattern of stream assignment.</p><pre># Solve the mode<br>model.solve()</pre><pre># Saving the optimal solution results<br>if LpStatus[model.status]==&quot;Optimal&quot;:<br>    optimal_soln = pd.DataFrame(<br>[(v.name, v.varValue) for v in model.variables() if v.varValue==1],<br>                                columns=[&quot;Assignment&quot;, &quot;Status&quot;])</pre><pre>print(&quot;Total installation cost : $ {}&quot;.format(value(model.objective)))</pre><pre>optimal_soln</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLjnHeIBNloPAsUKITCxfg.png" /></figure><pre>pd.DataFrame(<br>[(optimal_soln[optimal_soln[c]==1].index.values[0], c)\<br>  for c in optimal_soln.columns],<br>             columns = [&quot;ConnectionFrom&quot;, &quot;ConnectionTo&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*IojjpNYrO_5eG7huNtQ3Og.png" /></figure><p>Finally we have achieved our objective in obtaining the appropriate assignment pattern of streams to their respective heat exchangers at the lowest possible installation cost. The above sequence of code can be reused in case the dimensions of the above dataset change.</p><h3>References</h3><ol><li>Edgar, T.F., Himmelblau, D.M. and Lasdon, L.S., 2001. <em>Optimization of chemical processes</em>. McGraw-Hill,.</li><li>Mitchell, S., OSullivan, M. and Dunning, I., 2011. PuLP: a linear programming toolkit for python. <em>The University of Auckland, Auckland, New Zealand</em>.</li><li><a href="https://www.explainthatstuff.com/how-heat-exchangers-work.html">https://www.explainthatstuff.com/how-heat-exchangers-work.html</a></li></ol><p>PS: Feel free to comment in case you want me to make any edits or any in general suggestions. Thanks for your time!</p><p>Let’s connect on LinkedIn: <a href="https://www.linkedin.com/in/prathameshmohite96/">https://www.linkedin.com/in/prathameshmohite96/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7c936f9a6b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/optimized-allocation-of-streams-to-heat-exchangers-framing-a-minimization-problem-using-pythons-b7c936f9a6b5">Optimized Allocation of Streams to Heat Exchangers — Framing a Minimization Problem using Python’s…</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>
    </channel>
</rss>