<?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 Mandeep Singh on Medium]]></title>
        <description><![CDATA[Stories by Mandeep Singh on Medium]]></description>
        <link>https://medium.com/@mandeep.sco1711?source=rss-a1d883857e5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CXZSDCSDDZTyRh6a-KLjnQ.png</url>
            <title>Stories by Mandeep Singh on Medium</title>
            <link>https://medium.com/@mandeep.sco1711?source=rss-a1d883857e5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:58:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mandeep.sco1711/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[Finding and plotting optimal route using Open Source API in Python]]></title>
            <link>https://medium.com/walmartglobaltech/finding-and-plotting-optimal-route-using-open-source-api-in-python-cdcda596996c?source=rss-a1d883857e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdcda596996c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[route-discovery]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[osrm]]></category>
            <category><![CDATA[openstreetmap]]></category>
            <dc:creator><![CDATA[Mandeep Singh]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 10:49:50 GMT</pubDate>
            <atom:updated>2023-09-18T06:20:02.633Z</atom:updated>
            <content:encoded><![CDATA[<p>While working with geospatial data, many a times we encounter cases where we need to determine the optimal route between a start and end point (latitude and longitude). For example, while trying to understand where to open a new restaurant on a highway or which fuel station will serve most routes, we need to understand the most travelled routes between big cities. While in many use cases, only the drive distance between a set of points is needed, at times we require the details of the entire route with the ability to plot them on the map. This can be done using available Map APIs however those are usually not free. We have open source libraries in python that serve the same purpose like NetworkX and OSMnx, but as the distance between source and destination increases or we move across state / country boundaries, the API tends to take a very long time or crash. Here we propose an open source solution that can give route details even over long distances by combining the capabilities of these two APIs — OSRM (Open Source Routing Machine) &amp; Open Street Map.</p><h4>About the API</h4><ol><li>OSRM (Open Source Routing Machine): It’s an engine for shortest path in road networks. It returns geo nodes which then feeds into Open Street Maps API that returns latitude and longitudes of the points on the route. In OpenStreetMap, a geo node is the fundamental object type carrying geographic positions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*PCJq1sunulOi652DNTUujw.png" /><figcaption>API format</figcaption></figure><p>Various <strong>services</strong> like <em>route</em>, <em>table</em> etc. can be used to output either the shortest route or travel time. In case multiple paths exist between the coordinates, <strong>alternative</strong> option returns those as well. We will be using route service for our use case. <strong>Profile</strong> can be used for customising the mode of transportation to either <em>car</em>, <em>bike</em> or <em>foot</em>. <strong>Coordinates</strong> lets you add comma separated longitudes, latitudes for source and destination. <strong>Format</strong> of the output could either be <em>json</em> or <em>flatbuffers</em>.</p><p>2. Open Street Map: It is an open and free geographic database. API can be used to convert the node (output from OSRM API ) to coordinates. These are generally 100 meters apart. Based on our use case we can optimise the API call by selecting every nth (in our case every third) coordinate to improve the performance of our API. Once we have the list of latitudes longitudes of the route, we can leverage it for either visualisation on the map or calculating distance to nearest fuel station, restaurant etc.</p><h4><strong>Use Case</strong></h4><p>A big retail unit is looking to lease out available space to a restaurant chain (or fuel site). It tries to find best potential site for the new joint from a given set of locations. The goal is to pick a location that is close to major routes, being able to attract a larger customer share.</p><p>In this article we are looking at the following major routes in US. The goal is to identify the best possible locations that serve these routes.</p><p>· New York city to Knoxville</p><p>· Provo to Ogden to Park City</p><p>·. Minneapolis to Milwaukee to Chicago</p><p>We will be plotting the potential locations along with the given routes (extracted from OSRM and Open Street Map APIs) on a map and will be picking the best locations.</p><p>Note — This is a hypothetical use case to show the capability. Similar framework can be leveraged across various use cases involving spatial data.</p><h4>Implementation in Python</h4><p>The code below extracts the coordinates for the first route (New York City to Knoxville). Other routes can be extracted in a similar manner</p><p><strong>Step 1</strong></p><p>Importing the required libraries</p><pre>import numpy as np<br>import pandas as pd<br><br>import requests<br>import xml.etree.ElementTree as ET<br>from tqdm import tqdm<br><br># Plotting<br>import plotly.express as px</pre><p><strong>Step 2</strong></p><p>Here we specify the latitude and longitude of the source and destination points.</p><pre><br># Specify the coordinates (longitude, latitude) of origin and destination<br># first parameter is longitude, second parameter is latitude<br><br>source = (-83.920699, 35.96061) # Knoxville <br>dest  = (-73.973846, 40.71742)  # New York City</pre><p><strong>Step 3</strong></p><p>Get geo nodes (in OpenStreetMap, a geo node is the fundamental object type carrying geographic positions) for the given source and destination points. For this we use an open source API. The API returns a json file with a set of all geo coordinates referred as nodes for the route. The API also works when we have more than two points. The API is pretty quick and we get the response within a couple of seconds.</p><pre>start = &quot;{},{}&quot;.format(source[0], source[1])<br>end = &quot;{},{}&quot;.format(dest[0], dest[1])<br># Service - &#39;route&#39;, mode of transportation - &#39;driving&#39;, without alternatives<br>url = &#39;http://router.project-osrm.org/route/v1/driving/{};{}?alternatives=false&amp;annotations=nodes&#39;.format(start, end)<br><br><br>headers = { &#39;Content-type&#39;: &#39;application/json&#39;}<br>r = requests.get(url, headers = headers)<br>print(&quot;Calling API ...:&quot;, r.status_code) # Status Code 200 is success<br><br><br>routejson = r.json()<br>route_nodes = routejson[&#39;routes&#39;][0][&#39;legs&#39;][0][&#39;annotation&#39;][&#39;nodes&#39;]</pre><p><strong>Step 4</strong></p><p>Converting the nodes from the previous API to latitude and longitude. These nodes are generally very close to each other (0.1 miles apart). Depending on the use case and precision of the route required, we can consider only every nth point. For example, we can consider every third point. This helps us in reducing the response time of the second API as fewer nodes need to be converted to latitude and longitude. This API is slow and might take some time especially for bigger routes. We tested the API for a route of 6000 miles and results were obtained within 30 minutes.</p><pre>### keeping every third element in the node list to optimise time<br>route_list = []<br>for i in range(0, len(route_nodes)):<br>    if i % 3==1:<br>        route_list.append(route_nodes[i])<br><br>coordinates = []<br><br>for node in tqdm(route_list):<br>    try:<br>        url = &#39;https://api.openstreetmap.org/api/0.6/node/&#39; + str(node)<br>        r = requests.get(url, headers = headers)<br>        myroot = ET.fromstring(r.text)<br>        for child in myroot:<br>            lat, long = child.attrib[&#39;lat&#39;], child.attrib[&#39;lon&#39;]<br>        coordinates.append((lat, long))<br>    except:<br>        continue<br>print(coordinates[:10])</pre><p><strong>Step 5</strong></p><p>Now that we have the list of coordinates for the entire route, we will put them in a dataframe and try to visualise the same on a map. For mapping, we are using <em>Plotly</em> library from python.</p><pre>df_out = pd.DataFrame({&#39;Node&#39;: np.arange(len(coordinates))})<br>df_out[&#39;coordinates&#39;] = coordinates<br>df_out[[&#39;lat&#39;, &#39;long&#39;]] = pd.DataFrame(df_out[&#39;coordinates&#39;].tolist(),<br><br># Converting Latitude and Longitude into float<br>df_out[&#39;lat&#39;] = df_out[&#39;lat&#39;].astype(float)<br>df_out[&#39;long&#39;] = df_out[&#39;long&#39;].astype(float)<br><br># Plotting the coordinates on map<br>color_scale = [(0, &#39;red&#39;), (1,&#39;green&#39;)]<br>fig = px.scatter_mapbox(df_out, <br>                        lat=&quot;lat&quot;, <br>                        lon=&quot;long&quot;, <br>                        zoom=8, <br>                        height=600,<br>                        width=900)<br><br><br>fig.update_layout(mapbox_style=&quot;open-street-map&quot;)<br>fig.update_layout(margin={&quot;r&quot;:0,&quot;t&quot;:0,&quot;l&quot;:0,&quot;b&quot;:0})<br>fig.show()</pre><h4>Results</h4><p>Below is the graph obtained after plotting coordinates using plotly. We have also marked potential spots for restaurant near this route. Since location <em>B</em> seems to be most accessible to the commuters between New York and Knoxville; it is the best choice among all the options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*9IaRCi8-kl1QE4yKG714pg.png" /><figcaption>New York City — Knoxville</figcaption></figure><p><strong>Provo to Ogden to Park City</strong></p><p>This example consists of multiple points A, B &amp; C. Location B &amp; C seems to be more relevant compared to A. In context to our earlier use case, the retail chain might prefer to set up the new joints at B or C as it is closer to the route, especially B as it can serve multiple portions of the route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfxL9P-Nu7mTAm9tCl5Jdw.png" /><figcaption>Provo to Ogden to Park City</figcaption></figure><p><strong>Minneapolis to Milwaukee to Chicago</strong></p><p>Location B &amp; C seems to be more relevant compared to A &amp; D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*9GLNtWiQoy7TW0EL-QT9gA.png" /><figcaption>Minneapolis — Milwaukee — Chicago</figcaption></figure><h4>Closing Remarks</h4><p>While there are many Map APIs that can perform the above functionality within seconds, most of these are paid. The combination of the above two APIs do a good job of providing the route details even over long distances. Especially when we are looking for a one time dump of the route details. The APIs can be customised to cater to the use case by letting the user play with options like multiple destinations, vehicle mode, shortest time vs shortest route etc. The APIs are not specific for a particular country and do a decent job across borders. We can optimise the second API to improve the performance depending on the use case we are trying to solve.</p><h4>Written by</h4><ol><li>Mandeep Singh (<a href="https://medium.com/u/a1d883857e5e">Mandeep Singh</a>)— Data Scientist — Walmart Global Tech</li><li>Kartikeya Gupta (<a href="https://medium.com/u/7a770de9f34a">Kartikeya Gupta</a>)- Data Scientist — Walmart Global Tech</li></ol><h4>References</h4><ol><li><a href="https://plotly.com/python/scattermapbox/">https://plotly.com/python/scattermapbox/</a></li><li><a href="https://thomasafink.medium.com/plotting-the-optimal-route-for-data-scientists-in-python-using-the-dijkstra-algorithm-14e3e9383a0a">https://thomasafink.medium.com/plotting-the-optimal-route-for-data-scientists-in-python-using-the-dijkstra-algorithm-14e3e9383a0a</a></li><li><a href="https://towardsdatascience.com/find-and-plot-your-optimal-path-using-plotly-and-networkx-in-python-17e75387b873">https://towardsdatascience.com/find-and-plot-your-optimal-path-using-plotly-and-networkx-in-python-17e75387b873</a></li><li>API 1 — <a href="http://project-osrm.org/docs/v5.24.0/api/#requests">http://project-osrm.org/docs/v5.24.0/api/#requests</a></li><li>API 2 — <a href="https://www.openstreetmap.org/copyright">https://www.openstreetmap.org/copyright</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdcda596996c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/finding-and-plotting-optimal-route-using-open-source-api-in-python-cdcda596996c">Finding and plotting optimal route using Open Source API in Python</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine Tuning Optimization Results with Scenario Planning using Elastic Constraints]]></title>
            <link>https://medium.com/walmartglobaltech/fine-tuning-optimization-results-with-scenario-planning-using-elastic-constraints-1c3129272349?source=rss-a1d883857e5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c3129272349</guid>
            <category><![CDATA[soft-constraint]]></category>
            <category><![CDATA[linear-optimization]]></category>
            <category><![CDATA[python-pulp]]></category>
            <category><![CDATA[scenarioplanning]]></category>
            <category><![CDATA[elastic-constraints]]></category>
            <dc:creator><![CDATA[Mandeep Singh]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 17:53:08 GMT</pubDate>
            <atom:updated>2022-09-30T17:53:08.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHS0sA-0cRk8ZhwdL97oqA.png" /><figcaption><a href="https://pixabay.com/photos/elastic-bands-colour-ball-elastic-2229753/">Credits</a></figcaption></figure><h3>Introduction</h3><p>Linear optimization is a branch of optimization techniques where the goal is to find the best possible outcome based on a linear relationship between some constraints and an objective function. A wide variety of real-world use cases can be easily solved by formulating as a linear optimization problem. Typically, optimization includes finding the maximum or minimum value of an objective function that calculates cost, time, resources, etc. This objective function is evaluated in presence of certain constraints which must not be violated. In most of the cases, these constraints are hard constraints i.e their values are fixed and/or bounded.</p><p>Let us understand this more in detail with a small example. In figure 1, we present a use case where a company wants to assign vendors to carry out certain projects at the lowest possible cost. There are a fixed number of projects, and a fixed capacity and cost per project associated with each vendor. Using simple linear optimization, all the projects can be allocated at a total cost of <strong>$795</strong>. This is an example of using hard constrains — the capacity and cost numbers are fixed, and optimal solution is found within these bounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oWuBV2EUvAFVoSua.png" /></figure><p>However, if we are allowed to play around with these constraints, we might get a different solution. As you can see on the right, if we increase the capacity of Vendor C by 1, we can now do the allocation at a reduced total cost of <strong>$780</strong>. Here, we have made one of the constraints <em>elastic</em> i.e. they are not fixed anymore and can violate their initial bounds by some margin. This is also reflective of what happens in an actual scenario during planning, the company might realize that Vendor C is more cost effective and will try to negotiate more capacity from them.</p><p>Thus, although an out-of-the-box optimization framework might work well for a lot of use-cases, there is always a risk that the optimizer will be restricted by the fixed number of the inputs. This happens because the algorithm is trying to find the optimal solution within the given set of constraints (fixed pre-conditions) such as — project schedule, vendor availability, vendor capacity, costs, etc. However, in real-world situations, these constraints are flexible and can be altered to suit the objective. For e.g., we can always ask a cost-effective vendor to increase their capacity or negotiate price with a long-term vendor to reduce costs.</p><p>Linear Optimization has worked great for a variety of our use-cases at Walmart. One such use-case is assigning 3rd party vendors for construction projects activities across our stores. Here, different vendors submit their bids for the projects and the aim is to assign a vendor to each project so that the overall cost is minimized while also considering factors like vendor ranking, vendor capacity etc. To solve for this, often a linear optimization model is sufficient, but the assignment may not always be perfect. Some of the reasons for this are:</p><ul><li>Cost of project is more than planned budget,</li><li>Number of projects is greater than capacity of vendors,</li><li>Scheduling of projects conflicts with vendor availability, etc.</li></ul><p>In order to find an optimal and a realistic solution, we need to add some flexibility or elasticity to our model constraints. With a little experimentation, the end-user will be able to better understand the optimization results and effectively plan their assignment. Thus, a simple linear optimization framework can be thought of as a scenario planning tool for improved results by having flexible or elastic constraints.</p><p>In this blog, we will introduce the concept of Elastic Constraints in Linear Optimization and implement a toy solution in Python.</p><h3>Math behind it!</h3><p>In linear programming, whenever we are trying to solve constraints, we tend to have hard-bounded constraints. In many situations these constraints can be relaxed slightly depending on the context. We will now look at the math behind how to introduce soft (elastic) constraints into our framework.</p><p>Let us assume we have ’<strong>n</strong>’ stores where n&gt;0 is a natural number. Each store needs to hire a manager from a third-party company. There are various companies providing this service with each company having a capacity (based on previous reputation and actual man resource availability) on how many resources they can provide. Each store needs one manager at most. Every third-party company submits their bid. The goal is to optimally allocate resources to all stores while minimizing the cost considering the capacity of each company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*28t94EXUueswJPTU.png" /></figure><p>Every store should be allocated at most 1 vendor. Here we could have taken an equality constraint. However, if vendor capacity is less than the resources needed, putting equality constraint yields an infeasible solution. To overcome this challenge, we introduce &lt;= constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CMXY9Xecl-4DnE0S.png" /></figure><p>The total assignment to a vendor should be less than or equal to their capacity.</p><p><strong>Elastic Constraints:</strong></p><p>In many situations, it might be interesting to look at how the optimal solution will change if we loosen the constraints slightly. For e.g: If we loosen the vendor capacity by 10 %, by how much can we reduce our total cost? Or if we are unable to get full assignment with existing constraints, how does the assignment change if we loosen the constraints both in terms of resources and cost per project? In many situations this will help business make better decisions regarding the optimal allocation.</p><p>Let us now understand how to add elastic constraints to our optimization framework. We will be using the PuLP library in Python and it has 2 key arguments: <strong>Free Bound </strong>and <strong>Penalty.</strong></p><p><strong>Free bound:</strong></p><p>Free bound represents a region around where we can allow the constraint to deviate freely from its initial fixed bound.</p><p>For example,</p><p>If we have x + y = 200, as a constraint</p><p>With a free bound of 1%, we can permit the value of x + y to be in the interval [198,202].</p><p>These bounds do not have to be symmetric. One can opt for different percentages on either side. This becomes important because we might not want to deviate from the constraint from one side. Let us say we never want to exceed 200, in that case we can set the right hand bound to 0%.</p><p>Any constraint value within this free bound is permissible. The concept can easily be extended to inequality constraints. Note, for inequality constraints one side is always a free bound. Namely, for ‘&lt;=’, left is always a free bound and we can choose the right hand bound. A free bound of 0 indicates we do not allow the constraint to deviate from the value freely.</p><p><strong>Penalty function:</strong></p><p>The penalty function represents a way of introducing soft constraints in Linear Programming. Conceptually whenever we deviate from the constraint value/ free bound region, the solution is penalized by changing the objective function.</p><p>Let ‘p’ represent the unit penalty</p><p><strong>Original Problem:</strong></p><p>Maximize : (2x + 3y)</p><p>Subject to : X + y = 20</p><p><strong>Transformed problem:</strong></p><p>Maximize : (-p* rn + p* rp + 2x + 3y)</p><p>Subject to : x + y + rp + rn = 20</p><p>Where <strong>rp</strong> and <strong>rn</strong> represent continuous variables indicating positive &amp; negative deviation from the constraint value. For every unit deviation r, we penalize the objective function by <strong>p</strong> making the total penalty <strong>r*p</strong>.</p><p>Choosing p becomes a problem specific to the domain and problem statement. If the value of p is large, there is a very high per unit penalty hence making it hard to deviate from the original constraint value. Similarly, a low value of p indicates we can freely deviate from the constraint value.</p><p>As a rule of thumb, when we have a maximization problem, the penalty must be negative. In a minimization problem, the penalty must be positive.</p><p><strong>Sample Elastic Constraints in PuLP:</strong></p><pre>con_1 = LpConstraint(&#39;con_1&#39;,sense=0,rhs=300)<br>elastic_con_1 = con_1.makeElasticSubproblem(penalty=1, proportionFreeBound = [0.02,0.05])</pre><pre>con_2 = LpConstraint(&#39;con_2&#39;,sense=1,rhs=1000)<br>elastic_con_2 = con_2.makeElasticSubproblem(penalty=1,proportionFreeBoundList = 0.02)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VM2JSsHgcA04wS8jwJMPbg.png" /></figure><h3><strong>Python Implementation</strong></h3><p>We will now look at the python implementation of the toy problem we discussed above:</p><pre># Import relevant functions from Pulp<br>from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable, LpConstraint</pre><p><strong>Note:</strong> The original problem was a cost minimization problem where we wanted to assign one resource to every store. However, when we have fewer resources than stores, we will get an infeasible solution. To counter that we can change the equality constraints for stores to inequality (&lt;=) constraints. But this leads to a solution where minimal is achieved by making every selection variable as 0. To ensure we can assign vendors to as many stores as possible, we convert this minimization problem into a maximization problem by changing the cost function. We subtract the bid amount from a large number and then maximize the problem as shown below:</p><pre># Vendor Details<br># We are considering 3 vendors to be assigned to 8 stores<br>vendors = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]capacity = {&#39;A&#39;: 2, <br>         &#39;B&#39;: 3, <br>         &#39;C&#39;: 1}bids = {&#39;A&#39;: 100, <br>         &#39;B&#39;: 105, <br>         &#39;C&#39;: 90}</pre><pre># Subtract bid amount from a large number, in this case: 1000<br>new_bids = {&#39;A&#39;: 900, <br>         &#39;B&#39;: 895, <br>         &#39;C&#39;: 910}</pre><p>Define the variables and the constraints</p><pre>## Assignment Variables<br># 3 vendors x 8 stores = 24 variables<br>x1 = LpVariable(&#39;1A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x2 = LpVariable(&#39;2B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x3 = LpVariable(&#39;3C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x4 = LpVariable(&#39;4A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x5 = LpVariable(&#39;5B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x6 = LpVariable(&#39;6C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x7 = LpVariable(&#39;7A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x8 = LpVariable(&#39;8B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x9 = LpVariable(&#39;9C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x10 = LpVariable(&#39;10A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x11 = LpVariable(&#39;11B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x12 = LpVariable(&#39;12C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x13 = LpVariable(&#39;13A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x14 = LpVariable(&#39;14B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x15 = LpVariable(&#39;15C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x16 = LpVariable(&#39;16A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x17 = LpVariable(&#39;17B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x18 = LpVariable(&#39;18C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x19 = LpVariable(&#39;19A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x20 = LpVariable(&#39;20B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x21 = LpVariable(&#39;21C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x22 = LpVariable(&#39;22A&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x23 = LpVariable(&#39;23B&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)<br>x24 = LpVariable(&#39;24C&#39;,lowBound=0, upBound=1, cat=&#39;Integer&#39;)</pre><pre>## Constraints# Store assignment<br># Each Store must have at most 1 vendor assigned<br>model += (x1+x2+x3&lt;=1)<br>model += (x4+x5+x6&lt;=1)<br>model += (x7+x8+x9&lt;=1)<br>model += (x10+x11+x12&lt;=1)<br>model += (x13+x14+x15&lt;=1)<br>model += (x16+x17+x18&lt;=1)<br>model += (x19+x20+x21&lt;=1)<br>model += (x22+x23+x24&lt;=1)</pre><pre># Objective Function<br>model += (900*x1+900*x4+900*x7+900*x10+900*x13+900*x16+900*x19+900*x22+\<br>         895*x2+895*x5+895*x8+895*x11+895*x14+895*x17+895*x20+895*x23+\<br>         910*x3+910*x6+910*x9+910*x12+910*x15+910*x18+910*x21+910*x24)</pre><p>In PuLP, the way to introduce elasticity is to first define the object function and then <em>extend</em> it to include the elastic constraints. This is actually knows as adding soft constraints to the model. Optimization with elastic constraints is equivalent to adding a subproblem to the main objective function with some additional penalty.</p><p><strong>Note: </strong>As explained previously, the choice of free bound region and penalty is use-case specific. For simulating elasticity, select these values such that the optimizer is forced to operate only within the free bound and incurs a heavy penalty if it goes beyond. For our use-case, we select a penalty of -100 for all vendors. As it is a maximization problem, the optimizer stays within the free bound to avoid the reduction in objective function.</p><pre># Adding Elastic Constraints<br># For vendor A, we define an elastic constraints with a free bound range of +50% and penalty of -100<br>els_v1 = lpSum([x1,x4,x7,x10,x13,x16,x19,x22])<br>els_v1_con = LpConstraint(e=els_v1, sense=-1, name=&#39;elastic_v1_con&#39;, rhs=2)<br>els_con1 = els_v1_con.makeElasticSubProblem(penalty=-100, proportionFreeBound = 0.5)</pre><pre># For vendor B, we define an elastic constraints with a free bound range of +50% and penalty of -100<br>els_v2 = lpSum([x2,x5,x8,x11,x14,x17,x20,x23])<br>els_v2_con = LpConstraint(e=els_v2, sense=-1, name=&#39;elastic_v2_con&#39;, rhs=3)<br>els_con2 = els_v2_con.makeElasticSubProblem(penalty=-100, proportionFreeBound = 0.5)</pre><pre># For vendor C, we define an elastic constraints with a free bound range of +100% and penalty of -100<br>els_v3 = lpSum([x3,x6,x9,x12,x15,x18,x21,x24])<br>els_v3_con = LpConstraint(e=els_v3, sense=-1, name=&#39;elastic_v3_con&#39;, rhs=1)<br>els_con3 = els_v3_con.makeElasticSubProblem(penalty=-100, proportionFreeBound = 1)</pre><pre>model.extend(els_con1)<br>model.extend(els_con2)<br>model.extend(els_con3)<br>model</pre><p>Now, solve for optimal solution</p><pre># Solve the problem<br>status = model.solve()</pre><p>Look at the assignment variables</p><pre>print(f&quot;status: {model.status}, {LpStatus[model.status]}&quot;)<br>print(f&quot;objective: {model.objective.value()}&quot;)<br>for var in model.variables():<br>    print(f&quot;{var.name}: {var.value()}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q6BoTAOQCmpzCFQc.png" /></figure><h3>Scenario Planning</h3><p>Let’s circle back to our goal of adding elasticity to our vendor assignment use-case. The two key results of assignment are : <strong>Total Cost</strong>, &amp; <strong>Number of Assignments</strong>. Below is an example of how the optimization works out for a sample of 100 projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VopB2-D1kPToBLL-.png" /><figcaption><strong>Simple Linear Optimization</strong></figcaption></figure><p>We can see that in this base scenario, out of 100 projects, only 90 have been assigned because the total available vendor capacity is low. However, we need to ensure all of our projects are staffed. To achieve this, we can make the vendor capacities elastic and simulate scenarios to see how the assignment changes. Below are 3 examples where both — the cost and the assignment varies between different scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jbGX3uvUVIKntgqC.png" /><figcaption><strong>Scenario #1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*meUuKcsRjZ5mo_tV.png" /><figcaption><strong>Scenario #2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6KdPz93XweeQlyOM.png" /><figcaption><strong>Scenario #3</strong></figcaption></figure><p>As shown in the above examples, playing with vendor capacity can lead to various situations where we can see how the average cost &amp; total assignment changes with a change in the capacity. This helps business make a much more informed decision compared to situation with fixed constraint and one allocation. We can also play with penalty function and free bound to create scenarios and cater to problems according to business needs.</p><h3>Conclusion</h3><p>We introduced the concept of elastic constraints and its implementation in Python. Further, we also looked at how it adds an element of scenario planning to our optimization framework and help plan more efficiently. This is a generic framework that can be introduced in any kind of linear programming problem and has a lot of applications specially in cases where the constraints are man-made and can be flexible. This is also a parametric approach which allows the inputs (essentially free bound and penalty) to be driven and selected by the person running the optimization making it ideal for scenario planning. We hope this blog has given you a fundamental idea on the concept and ideas on adding more power to your optimization use-cases.</p><h4><strong>Written by :</strong></h4><ol><li>Mandeep Singh (<a href="https://medium.com/u/a1d883857e5e">Mandeep Singh</a>)— Data Scientist, Walmart Global Tech</li><li>Sujay Madbhavi (<a href="https://medium.com/u/7386f3ac8e54">Sujay Madbhavi</a>) — Data Scientist, Walmart Global Tech</li></ol><h3><strong>References</strong></h3><ul><li><a href="https://www.coin-or.org/PuLP/pulp.html#pulp.LpConstraint.makeElasticSubProblem">pulp: Pulp classes - PuLP v1.4.6 documentation</a></li><li><a href="https://andrewpwheeler.com/2020/07/28/an-example-of-soft-constraints-in-linear-programming/">An example of soft constraints in linear programming</a></li><li><a href="https://coin-or.github.io/pulp/guides/how_to_elastic_constraints.html">Elastic Constraints - PuLP 2.6.0 documentation</a></li></ul><p>Notes — <a href="https://www.cis.upenn.edu/~danroth/Talks/soft-constraints-ilp-VS-2013.pdf">https://www.cis.upenn.edu/~danroth/Talks/soft-constraints-ilp-VS-2013.pdf</a></p><p>Notes — <a href="https://www.csl.cornell.edu/~zhiruz/pdfs/softsched-iccad2009.pdf">https://www.csl.cornell.edu/~zhiruz/pdfs/softsched-iccad2009.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c3129272349" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/fine-tuning-optimization-results-with-scenario-planning-using-elastic-constraints-1c3129272349">Fine Tuning Optimization Results with Scenario Planning using Elastic Constraints</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>