1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| import numpy as np import matplotlib.pyplot as plt from scipy.optimize import linprog from matplotlib.patches import Polygon
def plot_constraints(x_range, constraints, ax=None): """Plot the constraints and feasible region""" if ax is None: ax = plt.gca() x = np.linspace(x_range[0], x_range[1], 1000) colors = ['b', 'g', 'r', 'c', 'm'] for i, (a, b, c) in enumerate(constraints): if b != 0: y = (c - a*x) / b ax.plot(x, y, f'{colors[i%len(colors)]}--', label=f'Constraint {i+1}') else: ax.axvline(x=c/a, color=colors[i%len(colors)], linestyle='--', label=f'Constraint {i+1}') vertices = [] n = len(constraints) for i in range(n): for j in range(i+1, n): a1, b1, c1 = constraints[i] a2, b2, c2 = constraints[j] A = np.array([[a1, b1], [a2, b2]]) b = np.array([c1, c2]) try: x, y = np.linalg.solve(A, b) if all((a*x + b*y <= c) for a, b, c in constraints): vertices.append([x, y]) except np.linalg.LinAlgError: continue for x_val in x_range: for (a, b, c) in constraints: if b != 0: y = (c - a*x_val) / b if all((a2*x_val + b2*y <= c2) for a2, b2, c2 in constraints): vertices.append([x_val, y]) if vertices: vertices = np.array(vertices) hull = [vertices[0]] current = vertices[0] vertices = vertices[vertices[:, 0].argsort()] while len(hull) < len(vertices): distances = np.linalg.norm(vertices - current, axis=1) next_point = vertices[np.argmax(distances)] if not np.array_equal(next_point, hull[0]): hull.append(next_point) current = next_point else: break hull = np.array(hull) ax.add_patch(Polygon(hull, alpha=0.3, color='gray', label='Feasible Region'))
""" Maximize: z = 3x + 4y Subject to: 2x + y ≤ 20 x + 2y ≤ 20 x, y ≥ 0 """
c = [-3, -4] A = [[2, 1], [1, 2]] b = [20, 20] x_bounds = (0, None) y_bounds = (0, None)
result = linprog(c, A_ub=A, b_ub=b, bounds=[x_bounds, y_bounds], method='simplex')
plt.figure(figsize=(12, 8))
constraints = [ [2, 1, 20], [1, 2, 20], [1, 0, 0], [0, 1, 0] ] plot_constraints([0, 25], constraints)
x_opt, y_opt = result.x plt.plot(x_opt, y_opt, 'r*', markersize=15, label='Optimal Solution')
x = np.linspace(0, 25, 100) y = np.linspace(0, 25, 100) X, Y = np.meshgrid(x, y) Z = 3*X + 4*Y plt.contour(X, Y, Z, levels=15, alpha=0.5, colors='orange')
plt.grid(True) plt.xlabel('x') plt.ylabel('y') plt.title('Linear Optimization Problem Visualization') plt.legend() plt.axis([0, 25, 0, 25])
optimal_value = -result.fun plt.text(0.02, 0.98, f'Optimal Solution:\nx = {x_opt:.2f}\ny = {y_opt:.2f}\nMax Value = {optimal_value:.2f}', transform=plt.gca().transAxes, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
plt.show()
|