<?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 Qayyim Shah on Medium]]></title>
        <description><![CDATA[Stories by Qayyim Shah on Medium]]></description>
        <link>https://medium.com/@qayyim?source=rss-a0aeb9b09d2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bImVMGecVPsUnYs1.jpg</url>
            <title>Stories by Qayyim Shah on Medium</title>
            <link>https://medium.com/@qayyim?source=rss-a0aeb9b09d2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:08:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@qayyim/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[From Chaos to Clarity: Using Integer Programming to Simplify Taxes]]></title>
            <link>https://medium.com/sage-ai/from-chaos-to-clarity-using-integer-programming-to-simplify-taxes-3443c3e164fc?source=rss-a0aeb9b09d2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3443c3e164fc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[numerical-optimization]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Qayyim Shah]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 10:33:14 GMT</pubDate>
            <atom:updated>2025-10-15T12:57:25.027Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-author: <a href="https://uk.linkedin.com/in/mahbub-gani-667a7b1">Dr. Mahbub Gani</a></p><p>Sam has a problem. It’s April 29th and her bakery had one of the busiest months since opening in 2023. By her estimate, she’s sold about 3000 hot cross buns this month which is almost double what she did last year! To celebrate, she took her team out to dinner last night and her pastry chef, Violet, is now excited to add all the new items she perfected after last week’s French pastry course to the summer menu.</p><p>What’s the problem then? Sam’s desk is covered in bills and invoices. Everything from utilities, suppliers and even equipment repairers. Dozens of invoices that she has to go through one by one to enter and upload to keep track of her accounts. For small businesses like Sam’s, ensuring your accounts are up to date at the end of the month is crucial to running a resilient, successful business.</p><p>How she wishes she could rub that lamp on her desk and get a genie to sort this out!</p><p>Much to her delight, Sam is about to discover Sage’s products are now AI-driven and able to automate much of the tedious work in bookkeeping. Every one of those invoices, bills and expenses can be scanned, extracted and entered into the software effortlessly, leaving Sam with time to do the things that really matter to her.</p><h3>Why do businesses care about this?</h3><p>Let’s face it, we’re no different to Sam. None of us like paying taxes and we dislike even more all the paper-pushing that’s involved. But what Sam can’t afford to do is pay more taxes than her business is required to. Thankfully, essential business costs are usually tax-deductible, meaning she can subtract the taxes paid on things like buying ingredients or staff training from her taxable amount. To do this though, she needs to ensure that the invoice tax amounts are accurately recorded. Good thing is she already passed it through her accounting software so all the information on the invoices should be in the software.</p><p>Actually, she’s not out of the woods yet. Her record high hot cross bun turnover meant her regular ingredient supplier couldn’t meet the demand so she supplemented with ingredients from multiple other suppliers. In addition, these folks weren’t kind enough to identify the tax rates for each item so she probably is still going to have to check each invoice and work out which items are tax-deductible and which aren’t. Ah well, shouldn’t be too bad. She opens the Sage software and get’s into the taxes section but, surprisingly, it’s already populated! How come?</p><h3>Here comes the science</h3><p>Every invoice would have a summary of the charges in at least one place and regularly it’s displayed in bold like a headline. We’ll refer to this as the <em>tax header</em>. In most cases, we would see three terms in the header: the subtotal or total without tax, tax amount, and total amount (total with tax).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*W2iapQgakXMjUktDXxt1yg.png" /><figcaption>fig 1: Sample invoice showing the most relevant fields associated with taxes.</figcaption></figure><p>These tax header elements are related as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*humiyfIvNxlRrma9zESRXA.png" /></figure><p>with the tax term <em>T</em>, also determined by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*XJtxZ3kZBHjeeyY2depfew.png" /></figure><p>In the early stage of building our tax extraction enhancements, we focussed on delivering a minimum viable product that allowed us to go to market quickly and get feedback from customers about the value it added. We aimed at getting this right for our customers in the UK and this simplified the tax solution we were able to implement. The UK has three applicable tax rates (0%, 5%, 20%) and in most cases, invoices contain a single tax rate (20%) or at most two rates. With this information and knowing the tax header values, we had sufficient information to resolve the important, customer desired tax fields with a rule based model.</p><p>So as an example, let’s suppose I buy a single T-shirt and the invoice shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*_6r7YIlFHoIeJvxyIciBvQ.png" /></figure><p>The unknown tax rate, <em>r</em>, is solved simply by rearranging equation 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*t2DErT7RlC19W9hDwZRlOw.png" /></figure><h3>Stepping up to multiple rates</h3><p>A single tax rate and one item is straightforward, as we should expect. But what about this invoice shown in<em> fig 1</em>. It’s well-formed so we can determine the information we need easily.</p><p>For the applicable rates, we’d use the header equation applied on a line by line basis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*wByf8mAiTnymgUBdi_VZ8A.png" /></figure><p>Where the subscript <em>i</em> refers to the <em>i-th</em> line item in the invoice and <em>s</em>, <em>t </em>and <em>a </em>are the line subtotal, tax and amount respectively.</p><p>The invoice above is a best case scenario: fairly common, but we need to cater for other plausible scenarios that are less well-formed. Occasionally, you’d see documents that look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*wZ9fUwYyBELpTe3p__764g.png" /><figcaption>fig 2: Simplified reciept with less tax information</figcaption></figure><p>Although, the tax rates are there, there’s still a lot of information that we need to calculate. With the tax header as our anchor however, we still have some ways we can solve this.</p><p>First, we’ll try to find if there is a single rate that matches by dividing the tax by the subtotal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*GEQwtV-bwV0DW-l-bZGq2A.png" /></figure><p>And 14.46% is not in our list of valid UK tax rates so we assume there are multiple tax rates applied to the items purchased. We’ll try two tax rates from the possible three (³<em>C</em>₂) and we should note that when dealing with multiple tax rates, each rate has a taxable subtotal (<em>s</em>ₜ) that sums to the header subtotal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*5miV-hba9bALSyRkW_erkQ.png" /></figure><p>where <em>n </em>is the number of tax rates applied in the invoice.</p><pre>import itertools<br><br>tax_rates = (0.2, 0.05, 0.0) # 20%, 5% and 0%<br><br>tax_pairs = itertools.combinations(tax_rates, 2)<br><br>tax_pairs = [x for x in itertools.combinations(tax_rates, 2)]</pre><pre>tax_pairs<br>&gt;&gt;&gt;&gt;[(0.2, 0.05), (0.2, 0.0), (0.05, 0.0)]</pre><p>Provided that we extract all the numeric amounts (lets call these <em>N</em>) from the document, we can try different combination of tax rates and solve for the taxable subtotals (<em>s</em>ₜ₁, <em>s</em>ₜ₂) that add up to the tax header subtotal.</p><pre>N = set([30.00, 20.00, 11.50, 41.50, 6.00, 47.50])</pre><h4>Scenario 1</h4><p>If we assume one taxable subtotal is in the list <em>N</em>, we can determine the other simply by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*wlOxa1_m77N6gPCPXYgYiQ.png" /></figure><p>and it should follow that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*hNMsziDL9Ityv_O1U1paXw.png" /></figure><pre># Tax header values<br>subtotal = 41.50<br>tax = 6.00<br>total_amount = 47.50<br><br>taxable_subtotals_in_text = set(<br>        [x for x in N if (subtotal - x) in N and x &gt; 0]<br>    )  # guarantees both numbers are in numerics_in_text!</pre><p>Then we can loop through the tax pairs and subtotals to find potential matches that satisfy the equations above using the function below.</p><pre>def find_subtotal_pair_from_text(numerics_in_text, taxable_subtotals_in_text, subtotal, tax, tax_pairs): <br>    solution = []<br>    for tax_subtotal_1 in taxable_subtotals_in_text:<br>        for rate_1, rate_2 in tax_pairs:<br>            tax_subtotal_2 = subtotal - tax_subtotal_1<br>            tax_amount_1 = rate_1 * tax_subtotal_1<br>            tax_amount_2 = rate_2 * tax_subtotal_2<br>            total_tax = tax_amount_1 + tax_amount_2<br>            if total_tax - tax == 0:  # got a hit!<br>                solution = [<br>                    (tax_subtotal_1, tax_amount_1, rate_1), <br>                (tax_subtotal_2, tax_amount_2, rate_2),<br>                ]<br>                return solution<br>    if not solution:<br>        return []</pre><pre>find_subtotal_pair_from_text(N, taxable_subtotals_in_text, subtotal, tax, tax_pairs)<br>&gt;&gt;&gt;&gt;[(30.0, 6.0, 0.2), (11.5, 0.0, 0.0)]</pre><h4>Scenario 2</h4><p>If we don’t know any of the taxable subtotals, it’s a bit trickier but not impossible if we only have two rates (<em>r₁ </em>and <em>r₂)</em>. We’d solve equations 7 and 8 simultaneously for each rate pair:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*KFREVjAZfQfYASpFowYEkA.png" /></figure><pre>import numpy as np<br><br>def solve_dual_rate_simultaneously(<br>    tax,<br>    total_amount,<br>    tax_pairs,<br>):<br>    &quot;&quot;&quot;<br>    Given we know tax and total, we solve for:<br>    - rate1 * taxable1 + rate2 * taxable2 = tax<br>    - (1 + rate1) * taxable1 + (1 + rate2) * taxable2 = total<br>    &quot;&quot;&quot;<br>    solutions = []<br><br>    for rate1, rate2 in tax_pairs:<br>        equations = np.array(<br>            [<br>                [rate1, rate2],<br>                [rate1 + 1, rate2 + 1],<br>            ],<br>            dtype=np.float64,<br>        )<br>        results = np.array([tax, total_amount], dtype=np.float64)<br>        taxable_1, taxable_2 = np.linalg.solve(equations, results)<br>        solutions.append((rate1, rate2, taxable_1, taxable_2))<br><br>    return solutions</pre><p>With <em>Scenario 1</em>; we had reasonable success but those were accompanied by limitations that prevented providing this service to a broader customer base. Firstly, the potential combinations can grow quite significantly if the customer country has more than three potential tax rates to choose from. Tie this to a list of potential taxable subtotals that is non-trivial (&gt;15 numeric values from historic implementation) and this combinatorial problem becomes prohibitively expensive, computationally speaking.</p><p>With <em>Scenario 2</em>; there are different but equally significant limitations. This method is only suitable when there are two potential tax rates (because we’ve only described the system with two equations) and there is only one feasible solution.</p><p>As a result of these limitations with our rule based solver, we needed to dig a bit deeper to find a more principled approach to solving this tax invoice problem.</p><h3>Holiday suitcases vs. tedious taxes</h3><p>My wife and I have two competing philosophies when it comes to holiday packing. When we’re flying to our home in the Caribbean or on a short trip, our luggage allowance is irrelevant and her philosophy is the dominant one. Make sure our essentials are easily accessible on board; items for our daughter of paramount importance and and arrange the remaining items by person per luggage piece. It honestly works really well for those trips!</p><p>On our journey back to the UK though, my philosophy takes precedent. This is now an exercise in stuffing our luggage with as many valuable items (spices, seasonings, scorpion chilli sauce for Dr. Y and dhalpuri) that can fit without exceeding the weight allowance.</p><p>Turns out, this 2nd philosophy is a well-established combinatorial optimisation problem known as the “<em>knapsack problem</em>”. As described in <a href="https://en.wikipedia.org/wiki/Knapsack_problem">Wikipedia</a>:</p><p><em>“Given a set of items, each with a weight and a value, determine which items to include in the collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.”</em></p><p>How does this help with your invoice though? Well, think about it this way: we have three suitcases, namely the tax headers (subtotal, tax, and total amount) and we’re trying to stuff the right numbers from the invoice into these. This can be solved using integer/mixed integer programming as a constrained optimisation problem (Dantzig, 1957). The general form is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*0iIu7dxruueqkPN7jJy4aw.png" /></figure><p><strong>c </strong>refers to the objective function that we are trying to optimise</p><p><strong><em>B</em></strong> refers to a matrix of the constraint equation coefficients</p><p><strong>b</strong>ₗ and <strong>b</strong>ᵤ refer to the is the vectors of lower and upper bounds (constraints)</p><p>And the values <strong>x</strong> are the indicator variables which act as switches that indicate if a value is present when the objective function is at a maximum.</p><h3>Applying combinatorial optimisation to the <em>tax header completion problem</em></h3><p>All this seems a bit abstract, so let’s break it down by applying it to our problem, while bearing in mind we want to make Sam’s life easier.</p><p>Let’s take a look at the receipt in <em>f</em>ig <em>2 </em>from earlier and assume we know the following:</p><ol><li>All the line subtotals</li><li>All possible tax rates (0%, 5%, 20%)</li><li>All header values (subtotal, tax and total amount)</li></ol><p>these are shown in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*8mfAdQUIqFMFdqrFU4TY6g.png" /></figure><p>If we know the lines and the potential rates, <strong>r</strong>, then we can multiply all the rates by all the line subtotals and determine all the possible tax amounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*EiM1iyP5IRg0YJ6DAO3w2A.png" /></figure><p>If we write these as constraints, we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*fQ8SErkij5jiK3wsRqy_yA.png" /></figure><p>where:</p><p><strong><em>i</em></strong> refers to the the line number or line item (item rows in the invoice)</p><p><strong><em>j</em></strong> refers to list of possible tax rates.</p><p>These constraints are very intuitive and somewhat trivial but important to building out the constraint equation matrix <strong><em>B</em></strong>.</p><p>Following from these two equations, we know that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*g5XjLYVeH9icdncoMWmY3A.png" /></figure><p>which gives us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*_Z98fur1WM3qbwXnRc3khg.png" /></figure><p>where<em> aᵢ</em> is unknown at this point so we can restate as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*wH41lmOYcWEvqRQ8FLpU_A.png" /></figure><p>Now, we know that only one tax rate can be present in a row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*7ME1nvdH2g3I_Mu68vxPaA.png" /></figure><p>and the indicator variables are binary (1 if included and 0 if not)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*0E1Z0HVT11JsIjvJuOSfbQ.png" /></figure><p>Finally, all the line amounts with tax must equal the header amount with tax:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*xkJPvbuAfJUiipMz7r1e3w.png" /></figure><p>All these constraints can neatly be encapsulated in matrix form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*ImiS-ArG-RWxHxUHcYgg0Q.png" /></figure><p>which in terms of the original matrix and vectors respectively, <strong><em>B, </em>x</strong> and <strong>b </strong>takes the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*w3UhFgzXzUutfZO8DZLzuA.png" /></figure><p>It bears making explicit exactly what we have achieved. We have characterised an arguably complex problem using a formal mathematical framework which not only enables us to elegantly solve the original problem but also unlocks the solution to a more general class of problems. Going back to our suitcase analogy we’re still trying to “stuff” the numbers into “tax header” sized suitcases but they also need to fit in “row-sized” packing cubes as well.</p><h3>Show me the code!</h3><pre>import numpy as np<br>from scipy.linalg import block_diag<br><br># Tax header values<br>subtotal = 41.50<br>tax = 6.00<br>total_amount = 47.50<br><br>line_subtotal_list = [25.0, 5.0, 11.5]<br>tax_rates = [0.0, 0.05, 0.02]</pre><p>The dimensions of the constraints matrix, <strong><em>B</em></strong> are a function of the lengths of <em>line_subtotal_list</em> and <em>tax_rates:</em></p><pre>row_count = len(line_subtotal_list)<br>column_count = len(tax_rates)</pre><p>First we get the tax amount constraint equations (rows 1–3 in <strong><em>B</em></strong>) in matrix form and the functions below can do this:</p><pre>def _shape_subtotal_matrix(line_subtotal_list, column_count):<br>     shaped_subtotal_matrix = np.repeat(line_subtotal_list, column_count).reshape((-1, column_count))<br>     return shaped_subtotal_matrix<br><br>def _shape_tax_rates_matrix(tax_rates, row_count, column_count):<br>    tax_rates_mat = np.array(tax_rates)<br>    shaped_tax_matrix = np.kron(np.ones(row_count), tax_rates_mat).reshape((row_count, column_count))<br>    return shaped_tax_matrix<br>    <br>def _build_block_diagonal_ones_matrix(row_count, column_count):<br>    block_diag_ones = block_diag(*[np.ones(column_count) for i in range(row_count)])<br>    return block_diag_ones<br><br>def build_tax_amount_constraint_rows(line_subtotal_list, tax_rates, row_count, column_count):<br>    subtotal_matrix = _shape_subtotal_matrix(line_subtotal_list, column_count)<br>    tax_rate_matrix = _shape_tax_rates_matrix(tax_rates, row_count, column_count)<br>    tax_amounts_matrix = subtotal_matrix * tax_rate_matrix<br>    reshaped_tax_amount_matrix = np.kron(np.ones(row_count), tax_mults_mat)<br>    block_daiagonal_ones = _build_block_diagonal_ones_matrix(row_count, column_count)<br>    tax_amount_coefficients = reshaped_tax_amount_matrix * block_daiagonal_ones<br>    <br>    return np.hstack([tax_amount_coefficients, -np.eye(row_count)])</pre><pre>build_tax_amount_constraint_rows(line_subtotal_list, tax_rates, row_count, column_count)<br><br>&gt;&gt;&gt; array([<br>      [ 0.  ,  1.25 ,  5.   ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  ,  0.  , -1.  , -0.  , -0.  ],<br>      [ 0.  ,  0.   ,  0.   ,  0.  ,  0.25,  1.  ,  0.  ,  0.  ,  0.  , -0.  , -1.  , -0.  ],<br>      [ 0.  ,  0.   ,  0.   ,  0.  ,  0.  ,  0.  ,  0.  ,  0.575,  2.3 , -0.  , -0.  , -1.  ]<br>    ])</pre><p>Then generate the line count constraints (rows 3–7):</p><pre>def build_line_constraint_rows(row_count, column_count):<br>    return block_diag(*[np.ones(column_count) for i in range(row_count)], np.ones(row_count))</pre><pre>build_line_constraint_rows(row_count, column_count)<br><br>&gt;&gt;&gt; array([<br>      [ 1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],<br>      [ 0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],<br>      [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.],<br>      [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.]<br>    ])</pre><p>Then combine these two together using this function:</p><pre>def generate_constrate_coefficient_matrix(line_subtotal_list, tax_rates, row_count, column_count):<br>    tax_amount_constraints = build_tax_amount_constraint_rows(line_subtotal_list, tax_rates, row_count, column_count)<br>    line_constraints = build_line_constraint_rows(row_count, column_count)<br>    constraint_coeff_matrix = np.vstack([tax_amount_constraints, line_constraints])<br><br>    return constraint_coeff_matrix</pre><pre>B = generate_constrate_coefficient_matrix(line_subtotal_list, tax_rates, row_count, column_count)<br><br>B<br>&gt;&gt;&gt; array([<br>    [ 0.   ,  1.25 ,  5.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   , -1.   , -0.   , -0.   ],<br>    [ 0.   ,  0.   ,  0.   ,  0.   ,  0.25 ,  1.   ,  0.   ,  0.   ,  0.   , -0.   , -1.   , -0.   ],<br>    [ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.575,  2.3  , -0.   , -0.   , -1.   ],<br>    [ 1.   ,  1.   ,  1.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ],<br>    [ 0.   ,  0.   ,  0.   ,  1.   ,  1.   ,  1.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ],<br>    [ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  1.   ,  1.   ,  1.   ,  0.   ,  0.   ,  0.   ],<br>    [ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  1.   ,  1.   ,  1.   ]<br>])</pre><p>And that’s the constraint coefficient matrix <strong><em>B</em></strong>.</p><p>Now for the bounds vector,<strong> b</strong>, we need the function:</p><pre>def build_bounds_vector(line_subtotal_list, row_count, total_amount):<br>    bounds_vector = np.hstack([line_subtotal_list, np.ones(row_count), [total_amount]])<br>    return bounds_vector</pre><pre>constraints = build_bounds_vector(line_subtotal_list, row_count, total_amount)<br><br>constraints<br>&gt;&gt;&gt; array([-25. ,  -5. , -11.5,   1. ,   1. ,   1. ,  47.5])</pre><p>Next we define the objective function. Although it turns out to be almost trivial in appearance, it’s extremely important in defining the problem. Specifically, the function is a linear combination of the elements of the vector <strong>x </strong>where the vector, c, contains the weights and must have the same dimensionality as <strong>x</strong>. Thus, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*nXQ5sBkux_BsmJt8jmykZQ.png" /></figure><p>The function will eventually be maximised subject to the constraint equations.</p><pre>c = np.hstack([1, np.zeros((column_count*row_count) + row_count - 1)])<br><br>c<br>&gt;&gt;&gt; array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])</pre><p>as a sanity check, confirming matrix dimension consistency:</p><pre>np.shape(B), np.shape(constraints), np.shape(c)<br><br>&gt;&gt;&gt; ((7, 12), (7,), (12,))</pre><h3>Defining the optimisation model</h3><p>The optimisation equations can be solved using the <em>scipy.optimize.milp</em> method; a tutorial can be found <a href="https://docs.scipy.org/doc/scipy/tutorial/optimize.html#tutorial-optimize-milp">here</a> for the knapsack problem.</p><pre>from scipy import optimize<br>from scipy.optimize import milp</pre><p>The <em>integrality</em> defines whether the variable is solved as an integer (1) or non-integer(0) and looking back at the <strong>x</strong> matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*wLWaxhOxm3neHrHuuz2dXw.png" /></figure><p>All values of <strong>x</strong> are binary integers (0 or 1) while the unknown values of <em>a</em> are non-integer as these are the sum of <em>sᵢ</em> and <em>tᵢ</em>.</p><p>We have equality rather than inequality constraints which we can specify in matrix notation by setting the upper bound (<strong>b</strong>ᵤ) equal to the lower bound <strong>(b</strong>ₗ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*OZcl89SNjxePIfD2M09MvQ.png" /></figure><pre>c = np.hstack([1, np.zeros((column_count*row_count) + row_count - 1)])<br>integrality = np.hstack([np.ones(no_of_lines*no_of_rates), np.zeros(no_of_lines)])<br><br>lb = ub = constraints<br><br>res = milp(c=-c, constraints=optimize.LinearConstraint(A=B, lb=lb, ub=ub),<br>           integrality=integrality)<br><br>res<br>&gt;&gt;&gt;         message: Optimization terminated successfully. (HiGHS Status 7: Optimal)<br>        success: True<br>         status: 0<br>            fun: 0.0<br>              x: [ 0.000e+00  0.000e+00  1.000e+00  0.000e+00  0.000e+00<br>                   1.000e+00  1.000e+00  0.000e+00  0.000e+00  3.000e+01<br>                   6.000e+00  1.150e+01]<br> mip_node_count: 0<br> mip_dual_bound: 0.0</pre><p>Cue drum roll, the final results are:</p><pre>res.x<br><br>&gt;&gt;&gt; array([ 0. ,  0. ,  1. ,  0. ,  0. ,  1. ,  1. ,  0. ,  0. , 30. ,  6. , 11.5])</pre><p>How do we interpret this? The last 3 terms in <em>res.x</em> are the values of <em>a₁</em>, <em>a₂</em> and <em>a₃</em>.</p><pre>res.x[-3:]<br><br>&gt;&gt;&gt; array([30. ,  6. , 11.5])</pre><p>while the integer values of 1 correspond to the tax rate that is “switched on” for each row. These correspond to <em>x₁₃</em>, <em>x₂₃</em> and <em>x₃₁</em> which are 20%, 20% and 0% respectively.</p><h3>Is that it?</h3><p>Now we’re nearing the end of this epic tax drama, let’s take stock. We’ve shown how Sam’s invoices were processed by Sage’s software, and it all seemed straightforward, right?</p><p>Well, not quite!</p><p>This example works quite well as there’s only one feasible solution and the optimisation algorithm successfully converges on that solution. However, now imagine a scenario where there are many more lines and tax rates to chose from, it’s highly likely that there will be more than one feasible solution. In<em> </em>terms of our suitcase metaphor, there many more items to pack into the case and no clear best way to do so. How would we choose the right answer then?</p><p>One approach would be to break the tax rates into combinations of two or three and then solve the optimisation problem for all of those combinations, then filter those solutions by the ones with the most numerical values that appear in the invoice. Not completely foolproof admittedly, but much more robust than the ad-hoc rule based method we started with, and significantly faster too!</p><p>What’s also good with this methodology is that it is consistent and robust enough to take partial information from the document and still come to a possible, if not likely solution, or even plug a potential solution into the constraint matrix and test if it solves the original tax problem.</p><p>This principled approach has made parsing numerical content from invoices into our software remarkably smooth.</p><p>No genie, no magic — just some elegant maths.</p><p><em>Finally having prepared her suitcase as a virtuoso packer, Sam takes in a deep breath, smiles and then embarks on her weekend getaway relieved that her dreams will not be visited by the Tax Man.</em></p><h3>Acknowlegdements</h3><p>We would like to thank Dr. Yaqub Alwan for his support with ideation and identifying this approach as a potential solution.</p><h3>References</h3><p>Dantzig, G. B. (1957). Discrete-Variable Extremum Problems. <em>Operations Research</em>, <em>5</em>(2), 266–277. <a href="http://www.jstor.org/stable/167356">http://www.jstor.org/stable/167356</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3443c3e164fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sage-ai/from-chaos-to-clarity-using-integer-programming-to-simplify-taxes-3443c3e164fc">From Chaos to Clarity: Using Integer Programming to Simplify Taxes</a> was originally published in <a href="https://medium.com/sage-ai">Sage Ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>