#🔒 How to improve efficiency of Largest Change Rule code

6 messages · Page 1 of 1 (latest)

wise jolt
#

I need to improve the efficiency of my code so I can create an Excel Spreadsheet and download it.

def find_pivot_largest_change(tableau):
    M, N = tableau.shape
    m = M-1  # Number of constraints
    n = N-1  # Number of variables

    # Largest Change Rule: find the column index that changes the objective function by the largest amount
    s = np.argmin(tableau[0, 1:n+1])
    delta_max = -np.inf
    for j in range(1, n+1):
        if tableau[0, j] < 0:
            theta_star = min([tableau[i, 0] / tableau[i, j] for i in range(1, m+1) if tableau[i, j] > 0])
            delta = -tableau[0, j] * theta_star
            if delta > delta_max:
                delta_max = delta
                s = j

    # Minimum ratio test plus Bland's rule:
    # find the (first) row i minimizing b_i / a_{is}, a_{is} > 0
    r = 0
    theta_star = np.inf
    for i in range(1, m+1):
        if tableau[i, s] > 0:
            if tableau[i, 0] / tableau[i, s] < theta_star:
                r = i
                theta_star = tableau[i, 0] / tableau[i, s]
    return r, s
winter emberBOT
#

@wise jolt

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

subtle niche
#

I have an idea. Could you provide a data sample?

raw shore
# wise jolt I need to improve the efficiency of my code so I can create an Excel Spreadsheet...

That fact you're looping over a numpy should key you in that there's a better way to do this. https://realpython.com/numpy-array-programming/

For example your first for loop could be converted into something along the lines of (untested, just giving the idea):

ratios = tableau[1:m+1, 0] / tableau[1:m+1, 1:n+1]
ratios[tableau[1:m+1, 1:n+1] <= 0] = np.inf  # To make sure <= 0 values are excluded from the min on the next line.
theta_stars = ratios.min(axis=0)
deltas = -tableau[0, 1:n+1] * theta_stars
s = np.argmax(deltas)
delta_max = deltas[s]

How to take advantage of vectorization and broadcasting so you can use NumPy to its full capacity. In this tutorial you'll see step-by-step how these advanced features in NumPy help you writer faster code.

winter emberBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.