# %% Import: import numpy as np import matplotlib.pyplot as plt # %% Def of objective function: def fun_f(x, y): f = -(60*x + 150*y) if not(y <= fun_g1(x)): f = np.inf # Constraint if not(y <= fun_g2(x)): f = np.inf # Constraint return f def fun_g1(x): y = -x/3 + 30 return y def fun_g2(x): y = -2*x/3 + 40 return y # %% Initialization: x_lb = 0 x_ub = 60 x_array = np.arange(x_lb, x_ub+1) y_lb = 0 y_ub = 40 y_array = np.arange(y_lb, y_ub+1,) f_min = np.inf x_opt = 0 y_opt = 0 # %% Grid optim: for x in x_array: for y in y_array: f = fun_f(x, y) # Value of objective function if (f <= f_min): # Improvement of solution f_min = f x_opt = x y_opt = y h_max = -f_min # %% Displaying results: print(f'h_max = {h_max:.0f}') print(f'x_opt = {x_opt:.0f}') print(f'y_opt = {y_opt:.0f}') # %% Plotting: g1_array = fun_g1(x_array) # Constraint fun g1(x) g2_array = fun_g2(x_array) # Constraint fun g2(x) plt.close('all') plt.figure(1) plt.grid() plt.plot(x_opt, y_opt, 'ro', label='optimum') plt.plot(x_array, g1_array, 'b', label='g1') plt.plot(x_array, g2_array, 'g', label='g2') plt.legend() plt.xlabel('x') plt.ylabel('y') # plt.savefig('prog_optim_lin_fuglekasser.pdf') plt.show()