40 lines
No EOL
999 B
Text
40 lines
No EOL
999 B
Text
import numpy as np
|
|
from scipy.optimize import minimize
|
|
import matplotlib.pyplot as plt
|
|
|
|
def m(x):
|
|
# Material used for packaging
|
|
return np.sum(x * np.array([3, 2, 4]))
|
|
|
|
def optimize_box(W_b):
|
|
# Initial guess for fractions x
|
|
x0 = np.ones(3) / 3
|
|
|
|
# Define the objective function
|
|
def obj(x):
|
|
return -m(x)
|
|
|
|
# Define the constraints
|
|
cons = ({'type': 'ineq', 'fun': lambda x: W_b - np.sum(x * np.array([3, 2, 4]))},
|
|
{'type': 'ineq', 'fun': lambda x: x})
|
|
|
|
# Minimize the objective function
|
|
res = minimize(obj, x0, method='SLSQP', constraints=cons)
|
|
|
|
return res.x
|
|
|
|
# Example values
|
|
W_b = 15 # box weight capacity
|
|
|
|
x_opt = optimize_box(W_b)
|
|
|
|
print("Optimal fractions:", x_opt)
|
|
print("Minimum material used:", m(x_opt))
|
|
|
|
# Plotting the graph
|
|
labels = ['Item X', 'Item Y', 'Item Z']
|
|
plt.bar(labels, x_opt, color='skyblue')
|
|
plt.xlabel('Items')
|
|
plt.ylabel('Fraction in the Box')
|
|
plt.title('Optimal Fractions of Items Packed into the Box')
|
|
plt.show() |