cg-code 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cg_code/__init__.py +4 -0
- cg_code/hci/__init__.py +10 -0
- cg_code/hci/hci_p1.py +22 -0
- cg_code/hci/hci_p10.py +25 -0
- cg_code/hci/hci_p2.py +19 -0
- cg_code/hci/hci_p3.py +13 -0
- cg_code/hci/hci_p4.py +14 -0
- cg_code/hci/hci_p5.py +18 -0
- cg_code/hci/hci_p6.py +20 -0
- cg_code/hci/hci_p7.py +12 -0
- cg_code/hci/hci_p8.py +22 -0
- cg_code/hci/hci_p9.py +39 -0
- cg_code/nlp/__init__.py +0 -0
- cg_code/om/__init__.py +15 -0
- cg_code/om/om_all.py +801 -0
- cg_code/om/om_p1_1.py +81 -0
- cg_code/om/om_p1_2.py +43 -0
- cg_code/om/om_p1_3.py +58 -0
- cg_code/om/om_p1_4.py +38 -0
- cg_code/om/om_p2_1.py +56 -0
- cg_code/om/om_p3_1.py +49 -0
- cg_code/om/om_p3_4.py +52 -0
- cg_code/om/om_p4_1.py +101 -0
- cg_code/om/om_p_2_2.py +36 -0
- cg_code/om/om_p_2_3.py +25 -0
- cg_code/om/om_p_3_2.py +21 -0
- cg_code/om/om_p_3_3.py +28 -0
- cg_code/om/om_p_4_2.py +51 -0
- cg_code/qc/__init__.py +10 -0
- cg_code/qc/qc_p1.py +32 -0
- cg_code/qc/qc_p10.py +40 -0
- cg_code/qc/qc_p2.py +25 -0
- cg_code/qc/qc_p3.py +25 -0
- cg_code/qc/qc_p4.py +42 -0
- cg_code/qc/qc_p5.py +37 -0
- cg_code/qc/qc_p6.py +32 -0
- cg_code/qc/qc_p7.py +35 -0
- cg_code/qc/qc_p8.py +42 -0
- cg_code/qc/qc_p9.py +24 -0
- cg_code-0.1.0.dist-info/METADATA +12 -0
- cg_code-0.1.0.dist-info/RECORD +44 -0
- cg_code-0.1.0.dist-info/WHEEL +5 -0
- cg_code-0.1.0.dist-info/licenses/LICENSE +15 -0
- cg_code-0.1.0.dist-info/top_level.txt +1 -0
cg_code/om/om_all.py
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
code = '''
|
|
4
|
+
OPTIMIZATION METHOD PRACTICAL FILE
|
|
5
|
+
|
|
6
|
+
Name: Bratadipta Mondal
|
|
7
|
+
Roll No.: 24
|
|
8
|
+
Subject: Optimization Methods
|
|
9
|
+
Course & Semester: M.Sc. Computer Science & 1st sem
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
Code Question 1.1:
|
|
13
|
+
Practical 1.1
|
|
14
|
+
Statement: A local travel agent is planning a charter trip to a major sea resort. The eight-day seven-night package includes the fare for round-trip travel, surface transportation, board and lodging and selected tour options. The charter trip is restricted to 200 persons and past experience indicates that there will not be any problem for getting 200 persons. The problem for the travel agent is to determine the number of Deluxe, Standard, and Economy tour packages to offer for this charter. These three plans each differ according to seating and service for the flight, quality of accommodation, meal plans and tour options. The following table summarizes the estimated prices for the three packages and the corresponding expenses for the travel agent. The travel agent has hired an air craft for the flat fee of Rs. 2,00,000 for the entire trip.
|
|
15
|
+
Price and Costs for four packages per person
|
|
16
|
+
Tour plan Price (Rs.) Hotel costs (Rs.) Meals & other expenses (Rs.)
|
|
17
|
+
Deluxe 10,000 3,000 4,750
|
|
18
|
+
Standard 7,000 2,200 2,500
|
|
19
|
+
Economy 6,500 1,900 2,200
|
|
20
|
+
In planning the trip, the following considerations must be taken into account:a. At least 10 per cent of the packages must be of the deluxe type.b. At least 35 per cent but not more than 70 per cent must be of the standard type.c. At least 30 per cent must be of the economy type.d. The maximum number of deluxe packages available in any air craft is restricted to 60.
|
|
21
|
+
e. The hotel desires that at least 120 of the tourists should be on the deluxe and standard packages together.
|
|
22
|
+
The travel agent wishes to determine the number of packages to offer in each type so as to maximize the total profit. i. Formulate the above as a linear programming problem. ii. Restate the above linear programming problem in terms of two decision variables, taking advantage of the fact that 200 packages will be sold. iii. Find the optimum solution using graphical methods for the restated linear programming problem and interpret your results. iv. Write the all associated program/codes in Python
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import matplotlib.pyplot as plt
|
|
26
|
+
from scipy.optimize import linprog
|
|
27
|
+
|
|
28
|
+
# Max Z = 280000 - 150*x1 - 100*x2
|
|
29
|
+
c = [150,100]
|
|
30
|
+
|
|
31
|
+
# inequality constraints (A_ub *x <= b_ub)
|
|
32
|
+
# 1. x1 + x2 <= 140
|
|
33
|
+
# 2. -(x1+x2) = -120
|
|
34
|
+
|
|
35
|
+
A_ub = [
|
|
36
|
+
[1,1],
|
|
37
|
+
[-1,-1]
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
b_ub = [140,-120]
|
|
41
|
+
|
|
42
|
+
# Bounds decision variables
|
|
43
|
+
# 1. 20 <= x1 <= 60
|
|
44
|
+
# 2. 70 <= x2 <= 140
|
|
45
|
+
x1_bounds = (20,60)
|
|
46
|
+
x2_bounds = (70,140)
|
|
47
|
+
|
|
48
|
+
# Solve linear program
|
|
49
|
+
result = linprog(c,A_ub,b_ub,bounds=[x1_bounds,x2_bounds])
|
|
50
|
+
|
|
51
|
+
# extract optimal values
|
|
52
|
+
opt_x1 = round(result.x[0])
|
|
53
|
+
opt_x2 = round(result.x[1])
|
|
54
|
+
opt_x3 = 200 - opt_x1 - opt_x2
|
|
55
|
+
max_profit = 280000 - result.fun
|
|
56
|
+
|
|
57
|
+
print("OPTIMAL TOUR PACKAGE PLAN")
|
|
58
|
+
print(f"Deluxe Packages (x1) : {opt_x1}")
|
|
59
|
+
print(f"Standard Packages (x2) : {opt_x2}")
|
|
60
|
+
print(f"Economy Packages (x3) : {opt_x3}")
|
|
61
|
+
print(f"Total Packages : {opt_x1 + opt_x2 + opt_x3}")
|
|
62
|
+
print(f"Maximum Net Profit : Rs. {max_profit:,.2f}")
|
|
63
|
+
|
|
64
|
+
x1_vals = np.linspace(0,90,400)
|
|
65
|
+
|
|
66
|
+
# Constraint lines for x2
|
|
67
|
+
y_sum_140 = 140 - x1_vals # x1 + x2 = 140
|
|
68
|
+
y_sum_120 = 120 - x1_vals # x1 + x2 = 120
|
|
69
|
+
|
|
70
|
+
plt.figure(figsize=(9,7))
|
|
71
|
+
|
|
72
|
+
# plot boundary lines
|
|
73
|
+
plt.axvline(x=20,color="blue",linestyle="--",label="x1 = 20 (min)")
|
|
74
|
+
plt.axvline(x=60,color="purple",linestyle="--",label="x1 = 60 (max)")
|
|
75
|
+
plt.axhline(y=70,color="orange",linestyle="--",label="x2 = 70 (min)")
|
|
76
|
+
plt.axhline(y=140,color="brown",linestyle="--",label="x2 = 140 (max)")
|
|
77
|
+
|
|
78
|
+
plt.plot(x1_vals,y_sum_140,color="green",linewidth=2,label="x1+x2=140")
|
|
79
|
+
plt.plot(x1_vals,y_sum_120,color="red",linewidth=2,label="x1+x2=120")
|
|
80
|
+
|
|
81
|
+
# Define the 5 corner points of the feasible region in order
|
|
82
|
+
corner_x1 = [20,20,60,60,50]
|
|
83
|
+
corner_x2 = [100,120,80,70,70]
|
|
84
|
+
labels = ['A(20,100)','B(20,120)',"C(60,80)","D(60,70)","E(50,70)"]
|
|
85
|
+
|
|
86
|
+
plt.fill(corner_x1,corner_x2,color="skyblue",alpha=0.5,label="Feasible Region")
|
|
87
|
+
|
|
88
|
+
# plot and annotate corner points
|
|
89
|
+
plt.scatter(corner_x1,corner_x2,color="black",zorder=5)
|
|
90
|
+
for i, txt in enumerate(labels):
|
|
91
|
+
plt.annotate(txt,(corner_x1[i]+1.2, corner_x2[i]+1.2),fontsize=9,fontweight="bold")
|
|
92
|
+
|
|
93
|
+
plt.scatter([opt_x1],[opt_x2],color="red",s=120,zorder=5,label=f'Optimal Point A({opt_x1},{opt_x2})')
|
|
94
|
+
|
|
95
|
+
plt.xlim(0,85)
|
|
96
|
+
plt.ylim(40,155)
|
|
97
|
+
plt.xlabel("Deluxe Packages (x1)",fontsize=11)
|
|
98
|
+
plt.ylabel("Standard Packages (x2)",fontsize=11)
|
|
99
|
+
plt.title("Graphical Solution: Travel Agent Charter Tour LPP",fontsize=11)
|
|
100
|
+
plt.grid(True,linestyle=":",alpha=0.7)
|
|
101
|
+
plt.legend(loc="upper right",fontsize=8.5)
|
|
102
|
+
plt.tight_layout()
|
|
103
|
+
plt.show()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
Code Question 1.2
|
|
111
|
+
Practical 1.2
|
|
112
|
+
Statement: A Boats company makes three different kinds of boats. All can be made profitably in this company, but the company's monthly production is constrained by the limited amount of labor, wood and screws available each month. The director will choose the combination of boats that maximizes his revenue in view of the information given in the following table:
|
|
113
|
+
Input Row Boat Canoe Kayak Monthly Availability
|
|
114
|
+
Labor (in Hours) 12 7 9 1,260
|
|
115
|
+
Wood (in Board feet) 22 18 16 1,900
|
|
116
|
+
Screws (in Kg.) 2 4 3 300
|
|
117
|
+
Selling price (in Rs.) 4,000 2,000 5,000 —
|
|
118
|
+
a) Formulate the above as a linear programming problem. b) Solve it by simplex method. From the optimal table of the solved linear programming problem, answer the following questions: c) How many boats of each type will be produced and what will be the resulting revenue? d) Which, if any, of the resources are not fully utilized? If so, how much of spare capacity is left? e) How much wood will be used to make all of the boats given in the optimal solution? f) Write the all associated program/codes in Python
|
|
119
|
+
|
|
120
|
+
import numpy as np
|
|
121
|
+
from scipy.optimize import linprog
|
|
122
|
+
|
|
123
|
+
# Max z = 4000*x1 + 2000*x2 + 5000*x3
|
|
124
|
+
c = [-4000,-2000,-5000]
|
|
125
|
+
|
|
126
|
+
# Constraints
|
|
127
|
+
# Labour: 12*x1 + 7*x2 + 9*x3 <= 1260
|
|
128
|
+
# Wood: 22*x1 + 18*x2 + 16*x3 <= 19008
|
|
129
|
+
# Screws: 2*x1 + 4*x2 + 3*x3 <= 396
|
|
130
|
+
A_ub = [
|
|
131
|
+
[12,7,9],
|
|
132
|
+
[22,18,16],
|
|
133
|
+
[2,4,3]
|
|
134
|
+
]
|
|
135
|
+
|
|
136
|
+
b_ub = [1260,19008,396]
|
|
137
|
+
|
|
138
|
+
# Non-negative values: x1,x2,x3 >= 0
|
|
139
|
+
bounds = [(0,None),(0,None),(0,None)]
|
|
140
|
+
|
|
141
|
+
result = linprog(c,A_ub,b_ub,bounds=bounds)
|
|
142
|
+
|
|
143
|
+
# extract optimal decision variables
|
|
144
|
+
x1, x2, x3 = result.x
|
|
145
|
+
max_revenue = -result.fun
|
|
146
|
+
|
|
147
|
+
# Calculate resources_usage and sparse capacity
|
|
148
|
+
resources_usage = np.dot(A_ub,result.x)
|
|
149
|
+
sparse_capacity = np.array(b_ub) - resources_usage
|
|
150
|
+
|
|
151
|
+
print("Optimal Boat Production and Revenue")
|
|
152
|
+
print(f"Row Boats: {x1:.2f} units")
|
|
153
|
+
print(f"Canoe: {x2:.2f} units")
|
|
154
|
+
print(f"Kayak: {x3:.2f} units")
|
|
155
|
+
|
|
156
|
+
print("SPARSE UTILIZATION AND SPARSE CAPACITY")
|
|
157
|
+
resources_name = ["Labour (in hours)","Wood (Board feet)","Screws (kg.)"]
|
|
158
|
+
for name, avail, used, slack in zip(resources_name,b_ub,resources_usage,sparse_capacity):
|
|
159
|
+
status = "Not fully utilize" if slack > 1e-5 else "Fully Utilized"
|
|
160
|
+
print(f"{name:<18} | Available: {avail:<10} | Used: {used:<8} | Spare: {slack:<10}")
|
|
161
|
+
|
|
162
|
+
print(f"Total wood used: {resources_usage[1]:.2f} board feet")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
Code Question 1.3
|
|
170
|
+
Practical 1.3
|
|
171
|
+
Statement: A Company wishes to determine an investment strategy for each of the next four years. Five investment types have been selected, investment capital has been allocated for each of the coming four years, and maximum investment levels have been established for each investment type. An assumption is that the amounts invested in any year will remain invested until the end of the planning horizon of four years. The following table summarizes the data for this problem. The values in the body of the table represent net return on investment of one rupee upto the end of the planning horizon. For example, a rupee invested in investment type B at the beginning of year will grow to Rs. 1.90 by the end of the fourth year, yielding a net return of Rs. 0.90.
|
|
172
|
+
Investment made at the beginning of year A B C D E Rs. Available (in 000's)
|
|
173
|
+
1 0.80 0.90 0.60 0.75 1.00 500
|
|
174
|
+
2 0.55 0.65 0.40 0.50 0.60 600
|
|
175
|
+
3 0.30 0.25 0.30 0.20 0.50 750
|
|
176
|
+
4 0.15 0.12 0.25 0.10 0.35 800
|
|
177
|
+
Maximum Rupees Investment (in 000's) 750 600 500 800 1000 —
|
|
178
|
+
The objective in this problem is to determine the amount to be invested at the beginning of each year in an investment type so as to maximize the net rupee return for the four-year period. Solve the above transportation problem and get an optimal solution. Also calculate the net return on investment for the planning horizon of four-year period. Write the all associated program/codes in Python.
|
|
179
|
+
|
|
180
|
+
import numpy as np
|
|
181
|
+
from scipy.optimize import linprog
|
|
182
|
+
|
|
183
|
+
years = [f"Years {i}" for i in range(1,5)]
|
|
184
|
+
types = [f"Types {chr(65+i)}" for i in range(6)]
|
|
185
|
+
|
|
186
|
+
returns = np.array([
|
|
187
|
+
[0.80, 0.90, 0.60, 0.75, 1.00],
|
|
188
|
+
[0.55, 0.65, 0.40, 0.60, 0.50],
|
|
189
|
+
[0.30, 0.25, 0.30, 0.50, 0.20],
|
|
190
|
+
[0.15, 0.12, 0.25, 0.35, 0.10]
|
|
191
|
+
])
|
|
192
|
+
|
|
193
|
+
supply = [500,600,750,800]
|
|
194
|
+
demand = [750,600,500,800,1000]
|
|
195
|
+
|
|
196
|
+
num_years, num_types = returns.shape
|
|
197
|
+
|
|
198
|
+
c = -returns.flatten()
|
|
199
|
+
|
|
200
|
+
# Equality constraint
|
|
201
|
+
A_eq = []
|
|
202
|
+
b_eq = []
|
|
203
|
+
for i in range(num_years):
|
|
204
|
+
row = np.zeros((num_years,num_types))
|
|
205
|
+
row[i,:] = 1
|
|
206
|
+
A_eq.append(row.flatten())
|
|
207
|
+
b_eq.append(supply[i])
|
|
208
|
+
|
|
209
|
+
# Ineqality constraint
|
|
210
|
+
A_ub = []
|
|
211
|
+
b_ub = []
|
|
212
|
+
for j in range(num_types):
|
|
213
|
+
row = np.zeros((num_years,num_types))
|
|
214
|
+
row[:,j] = 1
|
|
215
|
+
A_ub.append(row.flatten())
|
|
216
|
+
b_ub.append(demand[j])
|
|
217
|
+
|
|
218
|
+
res = linprog(c,A_ub,b_ub,A_eq,b_eq,bounds=(0,None))
|
|
219
|
+
|
|
220
|
+
allocation = res.x.reshape((num_years,num_types))
|
|
221
|
+
max_net_returns = -res.fun
|
|
222
|
+
|
|
223
|
+
print("OPTIMAL INVESTMENT SCHEDULE (IN RS. 000s)")
|
|
224
|
+
header = f"{'Year \\ Type':>12}" + "".join([f"{t:>10}" for t in types]) + "{'Total':>10}"
|
|
225
|
+
print(header)
|
|
226
|
+
print("-"*len(header))
|
|
227
|
+
|
|
228
|
+
for i,y in enumerate(years):
|
|
229
|
+
row_str = f"{y:.12}" + "".join([f"{allocation[i,j]:>10.2f}" for j in range(num_types)])
|
|
230
|
+
row_str += f"{np.sum(allocation[i,:]):10.2f}"
|
|
231
|
+
print(row_str)
|
|
232
|
+
|
|
233
|
+
print("-"*len(header))
|
|
234
|
+
col_totals = f"{'Invested':<12}" + "".join([f"{np.sum(allocation[:,j]):>10.2f}" for j in range(num_types)])
|
|
235
|
+
col_totals += f"{np.sum(allocation):>10.2f}"
|
|
236
|
+
print(col_totals)
|
|
237
|
+
print(f"Maximum Net Profit Return: Rs. {max_net_returns*1000}")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
Code Question 1.4
|
|
244
|
+
Practical 1.4
|
|
245
|
+
Statement: A private firm employs typists on hourly piece rate basis for their daily work. Five typists are working in that firm and their charges and speeds are different. On the basis of some earlier understanding, only one job is given to one typist and the typist is paid for full hours even when he or she works for a fraction of an hour. Find the least cost allocation for the following data and also write all associated program/codes in Python.
|
|
246
|
+
Typist Details:
|
|
247
|
+
Typist Rate per hour (Rs.) Number of pages typed per hr.
|
|
248
|
+
A 5 12
|
|
249
|
+
B 6 14
|
|
250
|
+
C 3 8
|
|
251
|
+
D 4 10
|
|
252
|
+
E 4 11
|
|
253
|
+
Job Details:
|
|
254
|
+
Job No. of pages
|
|
255
|
+
P 199
|
|
256
|
+
Q 175
|
|
257
|
+
R 145
|
|
258
|
+
S 298
|
|
259
|
+
T 178
|
|
260
|
+
|
|
261
|
+
import numpy as np
|
|
262
|
+
import math
|
|
263
|
+
from scipy.optimize import linear_sum_assignment
|
|
264
|
+
|
|
265
|
+
typist = ['A','B','C','D','E']
|
|
266
|
+
rates = [5,6,3,4,4]
|
|
267
|
+
speeds = [12,14,8,10,11]
|
|
268
|
+
|
|
269
|
+
jobs = ['P','Q','R','S','T']
|
|
270
|
+
pages = [199,175,145,298,178]
|
|
271
|
+
|
|
272
|
+
num_typist = len(typist)
|
|
273
|
+
num_jobs = len(jobs)
|
|
274
|
+
|
|
275
|
+
# Cost Matrix
|
|
276
|
+
cost_matrix = np.zeros((num_typist,num_jobs),dtype=int)
|
|
277
|
+
for i in range(num_typist):
|
|
278
|
+
for j in range(num_jobs):
|
|
279
|
+
hours = math.ceil(pages[j]/speeds[i])
|
|
280
|
+
cost_matrix[i,j] = hours*rates[i]
|
|
281
|
+
|
|
282
|
+
print("COMPUTE COST MATRIX")
|
|
283
|
+
header = f"{"Typist \\ Job":<14}" + "".join([f"{job:<6}" for job in jobs])
|
|
284
|
+
print(header)
|
|
285
|
+
print("-"*len(header))
|
|
286
|
+
for i,t in enumerate(typist):
|
|
287
|
+
row_str = f"{t:<14}" + "".join([f"{cost_matrix[i,j]:<6}" for j in range(num_jobs)])
|
|
288
|
+
print(row_str)
|
|
289
|
+
|
|
290
|
+
row_ind,col_ind = linear_sum_assignment(cost_matrix)
|
|
291
|
+
total_min_cost = cost_matrix[row_ind,col_ind].sum()
|
|
292
|
+
|
|
293
|
+
print("OPTIMAL LEAST-COST ALLOCATION")
|
|
294
|
+
for r,c in zip(row_ind,col_ind):
|
|
295
|
+
hrs = math.ceil(pages[c]/speeds[r])
|
|
296
|
+
print(f"Typist {typist[r]} -> Job {jobs[c]} ({pages[c]} pages | {hrs} hours @ Rs.{rates[r]}/hr) = Rs. {cost_matrix[r,c]}")
|
|
297
|
+
|
|
298
|
+
print(f"Minimum Total Cost : Rs.{total_min_cost}")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
Code Question 2.1
|
|
305
|
+
Practical 2.1
|
|
306
|
+
Statement: Player A can choose his strategies from {A_1,A_2,A_3 } only, while B can choose from the set {B_1,B_2 } only. The rules of the game state that the payments should be made in accordance with the selection of strategies:
|
|
307
|
+
Strategy Pair Selected Payments to be Made Strategy Pair Selected Payments to be Made
|
|
308
|
+
(A_1,B_1 ) Player A pays Rs. 1 to Player B (A_2,B_2 ) Player B pays Rs. 4 to Player A
|
|
309
|
+
(A_1,B_2 ) Player B pays Rs. 6 to Player A (A_3,B_1 ) Player A pays Rs. 2 to Player B
|
|
310
|
+
(A_2,B_1 ) Player B pays Rs. 2 to Player A (A_3,B_2 ) Player A pays Rs. 6 to Player B
|
|
311
|
+
What strategies should A and B play in order to get the optimum benefit of the play? Write the all associated program/codes in Python.
|
|
312
|
+
|
|
313
|
+
import numpy as np
|
|
314
|
+
import matplotlib.pyplot as plt
|
|
315
|
+
|
|
316
|
+
payoff = np.array([[-1, 6], [2, 4], [-2, -6]])
|
|
317
|
+
|
|
318
|
+
strategies_A = ["A1", "A2", "A3"]
|
|
319
|
+
strategies_B = ["B1", "B2"]
|
|
320
|
+
|
|
321
|
+
# Check saddle point (Maximin and Minimax)
|
|
322
|
+
row_mins = np.min(payoff, axis=1) # Maximin
|
|
323
|
+
col_max = np.max(payoff, axis=0) # Minimax
|
|
324
|
+
|
|
325
|
+
maximin = np.max(row_mins)
|
|
326
|
+
minimax = np.min(col_max)
|
|
327
|
+
|
|
328
|
+
print("PAYOFF MATRIX (PLAYER A)")
|
|
329
|
+
print(payoff)
|
|
330
|
+
print(f"\nRows Minimum: {row_mins} --> Maximin: {maximin}")
|
|
331
|
+
print(f"Column Maximum: {col_max} --> Minimax: {minimax}")
|
|
332
|
+
|
|
333
|
+
if maximin == minimax:
|
|
334
|
+
opt_row = np.argmax(row_mins)
|
|
335
|
+
opt_col = np.argmin(col_max)
|
|
336
|
+
print(f"Saddle Point Found at ({strategies_A[opt_row]}, {strategies_B[opt_col]})")
|
|
337
|
+
print(f"Optimal Strategy for Player A : {strategies_A[opt_row]}")
|
|
338
|
+
print(f"Optimal Strategy for Player B : {strategies_B[opt_col]}")
|
|
339
|
+
print(f"value of the Game (V): Rs.{maximin}")
|
|
340
|
+
else:
|
|
341
|
+
print("No any Saddle Point found")
|
|
342
|
+
|
|
343
|
+
# Graphical Verification
|
|
344
|
+
q = np.linspace(0, 1, 200)
|
|
345
|
+
# E_An = B1*q + B2*(1-q)
|
|
346
|
+
E_A1 = -1 * q + 6 * (1 - q)
|
|
347
|
+
E_A2 = 2 * q + 4 * (1 - q)
|
|
348
|
+
E_A3 = -2 * q - 6 * (1 - q)
|
|
349
|
+
|
|
350
|
+
plt.figure(figsize=(8,5))
|
|
351
|
+
plt.plot(q,E_A1,label='A1: -1q + 6(1-q)',linewidth=2)
|
|
352
|
+
plt.plot(q,E_A2,label='A2: 2q + 4(1-q)',linewidth=2)
|
|
353
|
+
plt.plot(q,E_A3,label='A3: -2q - 6(1-q)',linewidth=2)
|
|
354
|
+
|
|
355
|
+
upper_env = np.maximum.reduce([E_A1,E_A2,E_A3])
|
|
356
|
+
plt.plot(q,upper_env,'k--',linewidth=2.5,label="Upper Envolpe (Max Payoff)")
|
|
357
|
+
|
|
358
|
+
plt.scatter([1],[2],color='red',s=100,zorder=5,label=f'Saddle Point (q=1 -> {strategies_A[np.argmax(row_mins)]},{strategies_B[np.argmin(col_max)]},V=2)')
|
|
359
|
+
|
|
360
|
+
plt.xlabel("Probability q of Player B playing B1")
|
|
361
|
+
plt.ylabel("Expected Payoff to Player A (Rs.)")
|
|
362
|
+
plt.title("Graphical Verification of 3x2 Game")
|
|
363
|
+
plt.grid(True,linestyle=":")
|
|
364
|
+
plt.legend()
|
|
365
|
+
plt.tight_layout()
|
|
366
|
+
plt.show()
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
Code Question 2.2
|
|
372
|
+
Practical 2.2
|
|
373
|
+
Statement: Six jobs go first over machine I and then over II. The order of completion of jobs has no significance. The following table gives the machine times in hours for six jobs and the two machines:
|
|
374
|
+
Job No. 1 2 3 4 5 6
|
|
375
|
+
Machine I 5 9 4 7 8 6
|
|
376
|
+
Machine II 7 4 8 3 9 5
|
|
377
|
+
Find the sequence of the jobs that minimizes the total elapsed time to complete the jobs. Find the minimum time. Write the all associated program/codes in Python.
|
|
378
|
+
|
|
379
|
+
jobs = [1, 2, 3, 4, 5, 6]
|
|
380
|
+
m1 = [5, 9, 4, 7, 8, 6]
|
|
381
|
+
m2 = [7, 4, 8, 3, 9, 5]
|
|
382
|
+
|
|
383
|
+
# Johnson's Algorithm for optimal sequence
|
|
384
|
+
rem = list(range(len(jobs)))
|
|
385
|
+
left, right = [], []
|
|
386
|
+
|
|
387
|
+
while rem:
|
|
388
|
+
best_val, idx, mach = float('inf'), -1, 1
|
|
389
|
+
for i in rem:
|
|
390
|
+
if m1[i] < best_val:
|
|
391
|
+
best_val, idx, mach = m1[i], i, 1
|
|
392
|
+
if m2[i] < best_val:
|
|
393
|
+
best_val, idx, mach = m2[i], i, 2
|
|
394
|
+
if mach == 1:
|
|
395
|
+
left.append(idx)
|
|
396
|
+
else:
|
|
397
|
+
right.insert(0, idx)
|
|
398
|
+
rem.remove(idx)
|
|
399
|
+
|
|
400
|
+
seq = left + right
|
|
401
|
+
print("Optimal Sequence:", " -> ".join(str(jobs[i]) for i in seq))
|
|
402
|
+
|
|
403
|
+
# In-Out time calculation
|
|
404
|
+
m1_out = m2_out = idle_m2 = 0
|
|
405
|
+
for i in seq:
|
|
406
|
+
m1_in = m1_out
|
|
407
|
+
m1_out = m1_in + m1[i]
|
|
408
|
+
m2_in = max(m1_out, m2_out)
|
|
409
|
+
idle_m2 += (m2_in - m2_out)
|
|
410
|
+
m2_out = m2_in + m2[i]
|
|
411
|
+
|
|
412
|
+
print(f"Minimum Total Elapsed Time : {m2_out} hours")
|
|
413
|
+
print(f"Idle Time on Machine I : {m2_out - m1_out} hours")
|
|
414
|
+
print(f"Idle Time on Machine II : {idle_m2} hours")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
Code Question 2.3
|
|
420
|
+
Practical 2.3
|
|
421
|
+
Statement: The owner of a ready-made garments stores two types of shirts known as Zee-shirts and Button-down shirts. He makes a profit of Re. 1 and Rs. 4 per shirt on Zee-shirts and Button-down shirts respectively. He has two Tailors (A and B) at his disposal to stitch the shirts. Tailor A and Tailor B can devote at the most 7 hours and 15 hours per-day respectively. Both these shirts are to be stitched by both the tailors. Tailor A and Tailor B spend two hours and five hours respectively in stitching Zee-shirt, and four hours and three hours respectively in stitching a Button-down shirt. How many shirts of both the types should be stitched in order to maximize daily profit? a) Set-up and solve the linear programming problem. b) If the optimal solution is not integer-valued, use Gomory's technique to derive the optimal integer solution. c) Write the all associated program/codes in Python.
|
|
422
|
+
|
|
423
|
+
import numpy as np
|
|
424
|
+
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
|
|
425
|
+
|
|
426
|
+
# Objective: Maximize Z = 1*x1 + 4*x2 -> Minimize (-1*x1 - 4*x2)
|
|
427
|
+
c = np.array([-1.0, -4.0])
|
|
428
|
+
A = np.array([
|
|
429
|
+
[2.0, 4.0], # Tailor A: 2*x1 + 4*x2 <= 7
|
|
430
|
+
[5.0, 3.0] # Tailor B: 5*x1 + 3*x2 <= 15
|
|
431
|
+
])
|
|
432
|
+
b = np.array([7.0, 15.0])
|
|
433
|
+
|
|
434
|
+
# (a) Continuous LPP solution
|
|
435
|
+
res_lp = linprog(c, A_ub=A, b_ub=b, bounds=(0, None), method='highs')
|
|
436
|
+
print("=== (a) Continuous LPP Solution ===")
|
|
437
|
+
print(f"Zee-shirts (x1) = {res_lp.x[0]:.2f}, Button-down (x2) = {res_lp.x[1]:.2f}, Max Profit = Rs. {-res_lp.fun:.2f}")
|
|
438
|
+
|
|
439
|
+
# (b) Integer LPP solution (Gomory Cut equivalent)
|
|
440
|
+
constraints = LinearConstraint(A, -np.inf, b)
|
|
441
|
+
integrality = np.ones_like(c)
|
|
442
|
+
res_ip = milp(c=c, integrality=integrality, bounds=Bounds(0, np.inf), constraints=constraints)
|
|
443
|
+
|
|
444
|
+
print("\n=== (b) Optimal Integer Solution ===")
|
|
445
|
+
print(f"Zee-shirts (x1) = {int(round(res_ip.x[0]))}")
|
|
446
|
+
print(f"Button-down (x2)= {int(round(res_ip.x[1]))}")
|
|
447
|
+
print(f"Maximum Profit = Rs. {int(round(-res_ip.fun))}")
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
Code Question 3.1
|
|
453
|
+
Practical 3.1
|
|
454
|
+
Statement: A road transport company has one reservation clerk on duty at a time. She handles information of bus schedules and makes reservations. Customers arrive at a rate of 8 per hour and the clerk can service 12 customers on an average per hour. After stating your assumptions, answer the following: a) What is the average number of customers waiting for the service of the clerk? b) What is the average time a customer has to wait before getting service? c) The management is contemplating to install a computer system to handle the information and reservations. This is expected to reduce the service time from 5 to 3 minutes. The additional cost of having the new system works out to be 12 paise per minute spent waiting before being served, should the company install the computer system? Assume 8-hour working day.
|
|
455
|
+
|
|
456
|
+
arrival_rate = 8.0 # lambda = 8 customers per hour
|
|
457
|
+
service_rate_old = 12.0 # mu_1 = 12 customers per hour (5 mins per customer)
|
|
458
|
+
working_hours = 8.0 # 8-hour working day
|
|
459
|
+
cost_per_wait_min = 0.12 # 12 paise = Rs. 0.12 per minute
|
|
460
|
+
|
|
461
|
+
def mm1_metrics(lam,mu):
|
|
462
|
+
rho = lam/mu # Utlization Factor
|
|
463
|
+
Lq = (lam**2)/(mu*(mu-lam)) # Avg customers waiting in queue
|
|
464
|
+
Ls = lam / (mu-lam) # Avg customers in system
|
|
465
|
+
Wq_hours = lam/(mu*(mu-lam)) # Avg waiting time is queue (hours)
|
|
466
|
+
Wq_mins = Wq_hours*60 # Avg waiting time in queue (minutes)
|
|
467
|
+
Ws_mins = (1/(mu-lam))*60 # Avg time spent in system (minutes)
|
|
468
|
+
return rho,Lq,Ls,Wq_mins,Ws_mins
|
|
469
|
+
|
|
470
|
+
rho1,Lq1,Ls1,Wq1_mins,Ws1_mins = mm1_metrics(arrival_rate,service_rate_old)
|
|
471
|
+
|
|
472
|
+
print("CURRENT SYSTEM PERFORMANCE")
|
|
473
|
+
print(f"Traffic Intensity (rho) :{rho1:.4f}")
|
|
474
|
+
print(f"(a) Avg Customers Waiting (Lq) :{Lq1:.2f} customers")
|
|
475
|
+
print(f"(b) Avg Waiting Time in Queue (Wq) :{Wq1_mins:.2f} minutes")
|
|
476
|
+
|
|
477
|
+
service_time_new = 3.0 # 3 minutes per customer
|
|
478
|
+
service_rate_new = 60.0 / service_time_new # mu_2 = 20 customers per hour
|
|
479
|
+
|
|
480
|
+
rho2,Lq2,Ls2,Wq2_mins,Ws2_mins = mm1_metrics(arrival_rate,service_rate_new)
|
|
481
|
+
|
|
482
|
+
customers_per_day = arrival_rate*working_hours
|
|
483
|
+
total_wait_old = customers_per_day * Wq1_mins
|
|
484
|
+
total_wait_new = customers_per_day * Wq2_mins
|
|
485
|
+
time_saved_mins = total_wait_old - total_wait_new
|
|
486
|
+
|
|
487
|
+
cost_old = total_wait_old * cost_per_wait_min
|
|
488
|
+
cost_new = total_wait_new * cost_per_wait_min
|
|
489
|
+
net_savings = cost_old - cost_new
|
|
490
|
+
|
|
491
|
+
print("NEW COMPUTER SYSTEM COMPARISION (8-HOURS DAY)")
|
|
492
|
+
print(f"New Service Rate (mu_2) : {service_rate_new:.2f} customers/hour")
|
|
493
|
+
print(f"New Avg Customers Waiting (Lq2) : {Lq2:.2f} customers")
|
|
494
|
+
print(f"New Waiting Time (Wq2) : {Wq2_mins:.2f} minutes")
|
|
495
|
+
print(f"Total Customers per day : {int(customers_per_day)} customers")
|
|
496
|
+
print(f"Daily Waiting time (Old vs New) : {total_wait_old} vs {total_wait_new} minutes")
|
|
497
|
+
print(f"Daily Waiting time saved : {time_saved_mins} minutes")
|
|
498
|
+
print(f"Daily Waiting cost (old vs new) : Rs. {cost_old} vs Rs. {cost_new}")
|
|
499
|
+
print(f"New Daily saving : ₹ {net_savings}")
|
|
500
|
+
|
|
501
|
+
if net_savings > 0:print("Decision: INSTALL the computer system")
|
|
502
|
+
else:print("Decision: DO NOT INSTALL the computer system")
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
Code Question 3.2
|
|
508
|
+
Practical 3.2
|
|
509
|
+
Statement: The rate of arrival of customers at a public telephone booth follows Poisson distribution, with an average time of 10 minutes between one customer and the next. The duration of a phone call is assumed to follow exponential distribution, with mean time of 3 minutes. a) What is the probability that a person arriving at the booth will have to wait? b) What is the average length of the non-empty queues that form from time to time? c) The Mahanagar Telephone Nigam Ltd. will install a second booth when it is convinced that the customers would expect waiting for at least 3 minutes for their turn to make a call. By how much time should the flow of customers' increase in order to justify a second booth? d) Estimate the fraction of a day that the phone will be in use.
|
|
510
|
+
|
|
511
|
+
lam = 1 / 10 # 0.10 customers/min (6/hr)
|
|
512
|
+
mu = 1 / 3 # 0.3333 customers/min (20/hr)
|
|
513
|
+
|
|
514
|
+
# (a) Probability customer has to wait
|
|
515
|
+
prob_wait = lam / mu
|
|
516
|
+
|
|
517
|
+
# (b) Average length of non-empty queues
|
|
518
|
+
avg_non_empty = mu / (mu - lam)
|
|
519
|
+
|
|
520
|
+
# (c) New arrival rate for Wq = 3 mins -> lam_new / (mu * (mu - lam_new)) = 3
|
|
521
|
+
target_wq = 3.0
|
|
522
|
+
lam_new = (target_wq * mu**2) / (1 + target_wq * mu)
|
|
523
|
+
increase_per_hr = (lam_new - lam) * 60
|
|
524
|
+
|
|
525
|
+
# (d) Fraction of day phone is in use
|
|
526
|
+
busy_fraction = lam / mu
|
|
527
|
+
|
|
528
|
+
print(f"(a) Probability of waiting : {prob_wait:.2f} (30%)")
|
|
529
|
+
print(f"(b) Avg non-empty queue length : {avg_non_empty:.2f} customers")
|
|
530
|
+
print(f"(c) Required arrival increase : {increase_per_hr:.2f} customers/hour")
|
|
531
|
+
print(f"(d) Fraction of day phone is in use : {busy_fraction:.2f} (30%)")
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
Code Question 3.3
|
|
538
|
+
Practical 3.3
|
|
539
|
+
Statement: A dealer supplies you the following information with regard to a product dealt in by her: Annual demand: 10,000 units; ordering cost: Rs. 10 per order; price: Rs. 20 per unit. Inventory carrying cost: 20% of the value of inventory per year. The dealer is considering the possibility of allowing some back order (stock out) to occur. He has estimated that the annual cost of backordering will be 25% of the value of inventory. a) What should be the optimum number of units of the product he should buy in one lot? b) What quantity of the product should be allowed to be back-ordered, if any? c) What would be the maximum quantity of inventory at any time of the year? d) Would you recommend to allow back-ordering? If so, what would be the annual cost saving by adopting the policy of back-ordering.
|
|
540
|
+
|
|
541
|
+
import math
|
|
542
|
+
|
|
543
|
+
D = 10000.0
|
|
544
|
+
Co = 10.0
|
|
545
|
+
price = 20.0
|
|
546
|
+
Ch = 0.20 * price # Rs. 4 per unit/year
|
|
547
|
+
Cb = 0.25 * price # Rs. 5 per unit/year
|
|
548
|
+
|
|
549
|
+
# (a) Optimal lot size with backorders
|
|
550
|
+
Q_opt = math.sqrt((2 * D * Co / Ch) * ((Ch + Cb) / Cb))
|
|
551
|
+
|
|
552
|
+
# (b) Optimal backorder quantity
|
|
553
|
+
S_opt = Q_opt * (Ch / (Ch + Cb))
|
|
554
|
+
|
|
555
|
+
# (c) Maximum inventory level
|
|
556
|
+
I_max = Q_opt - S_opt
|
|
557
|
+
|
|
558
|
+
# (d) Cost comparison & annual savings
|
|
559
|
+
tc_without_bo = math.sqrt(2 * D * Co * Ch)
|
|
560
|
+
tc_with_bo = math.sqrt(2 * D * Co * Ch * (Cb / (Ch + Cb)))
|
|
561
|
+
savings = tc_without_bo - tc_with_bo
|
|
562
|
+
|
|
563
|
+
print(f"(a) Optimum Order Quantity (Q*) : {Q_opt:.2f} units")
|
|
564
|
+
print(f"(b) Optimum Backorder Qty (S*) : {S_opt:.2f} units")
|
|
565
|
+
print(f"(c) Maximum Inventory Level (Imax) : {I_max:.2f} units")
|
|
566
|
+
print(f"(d) Cost without Backorders : Rs. {tc_without_bo:.2f}")
|
|
567
|
+
print(f" Cost with Backorders : Rs. {tc_with_bo:.2f}")
|
|
568
|
+
print(f" Annual Cost Saving : Rs. {savings:.2f} -> Recommend Backordering")
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
Code Question 3.4
|
|
576
|
+
Practical 3.4
|
|
577
|
+
Statement: Purchase Manager has decided to place order to a minimum quantity of 500 numbers of a particular item in order to get a discount of 10%. From the past records, it was found out that in the last year, 8 orders each of size 200 units were placed. Given the ordering cost: Rs. 500 per order, inventory carrying cost of 40% of the inventory value and the price of the item of Rs. 400 per unit. Is the Purchase Manager justified in his decision? What is the effect of his decision to the company?
|
|
578
|
+
|
|
579
|
+
import math
|
|
580
|
+
|
|
581
|
+
past_orders = 8
|
|
582
|
+
past_order_size = 200
|
|
583
|
+
D = past_orders * past_order_size # Annual Demand = 1600 units
|
|
584
|
+
|
|
585
|
+
Co = 500.0 # Ordering cost per order
|
|
586
|
+
P_normal = 400.0 # Normal price per unit
|
|
587
|
+
carrying_rate = 0.40 # 40% inventory carrying cost rate
|
|
588
|
+
|
|
589
|
+
discount_rate = 0.10 # 10% discount
|
|
590
|
+
Q_discount = 500 # Minimum order quantity for discount
|
|
591
|
+
P_discount = P_normal * (1 - discount_rate) # ₹360 per unit
|
|
592
|
+
def total_annual_cost(D, Q, P, Co, i):
|
|
593
|
+
Ch = i * P
|
|
594
|
+
purchase_cost = D*P
|
|
595
|
+
ordering_cost = (D/Q)*Co
|
|
596
|
+
carrying_cost = (Q/2)*Ch
|
|
597
|
+
total = purchase_cost + ordering_cost + carrying_cost
|
|
598
|
+
return purchase_cost, ordering_cost, carrying_cost,total
|
|
599
|
+
|
|
600
|
+
Ch_normal = carrying_rate * P_normal
|
|
601
|
+
Q = math.sqrt((2*D*Co)/Ch_normal)
|
|
602
|
+
|
|
603
|
+
# Optimal EOQ without discount
|
|
604
|
+
p1, o1, c1, total_eoq = total_annual_cost(D,Q,P_normal,Co,carrying_rate)
|
|
605
|
+
|
|
606
|
+
# Managers proposal (500 units with 10% discount)
|
|
607
|
+
p2, o2, c2, total_disc = total_annual_cost(D,Q_discount,P_discount, Co,carrying_rate)
|
|
608
|
+
|
|
609
|
+
# Past policy (200 units without discount)
|
|
610
|
+
p3, o3, c3, total_past = total_annual_cost(D,past_order_size,P_normal,Co,carrying_rate)
|
|
611
|
+
|
|
612
|
+
print(f"Annual Demand (D) : {D} units")
|
|
613
|
+
print(f"Normal EOQ (Without Discount) : {Q:.0f} units\n")
|
|
614
|
+
|
|
615
|
+
print("=== COST COMPARISON SUMMARY ===")
|
|
616
|
+
print(f"1. Past Policy (Q=200 @ Rs.400) : Rs. {total_past:,.2f}")
|
|
617
|
+
print(f"2. Optimal EOQ (Q=100 @ Rs.400) : Rs. {total_eoq:,.2f}")
|
|
618
|
+
print(f"3. Manager Offer (Q=500 @ Rs.360) : Rs. {total_disc:,.2f}\n")
|
|
619
|
+
|
|
620
|
+
savings_vs_eoq = total_eoq - total_disc
|
|
621
|
+
savings_vs_past = total_past - total_disc
|
|
622
|
+
|
|
623
|
+
if total_disc < total_eoq:
|
|
624
|
+
print("Decision: Purchase Manager IS JUSTIFIED.")
|
|
625
|
+
print(f"Net Annual Savings vs EOQ Policy : Rs. {savings_vs_eoq:,.2f}")
|
|
626
|
+
print(f"Net Annual Savings vs Past Policy : Rs. {savings_vs_past:,.2f}")
|
|
627
|
+
else:
|
|
628
|
+
print("Decision: Purchase Manager is NOT justified.")
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
Code Question 4.1
|
|
635
|
+
Practical 4.1
|
|
636
|
+
Statement: Apply Wolfe's method for solving the quadratic programming problem:
|
|
637
|
+
"Max. " z_x=4x_1+6x_2-2x_1^2-2x_1 x_2-2x_2^2," subject to"
|
|
638
|
+
x_1+2x_2≤2," and " x_1,x_2≥0
|
|
639
|
+
|
|
640
|
+
import numpy as np
|
|
641
|
+
from fractions import Fraction
|
|
642
|
+
from scipy.optimize import minimize
|
|
643
|
+
|
|
644
|
+
# ==========================================================
|
|
645
|
+
# PART 1: WOLFE'S METHOD (EXACT SIMPLEX WITH RESTRICTED ENTRY)
|
|
646
|
+
# ==========================================================
|
|
647
|
+
# KKT Equations with Artificial Variables A1, A2:
|
|
648
|
+
# 1) 4*x1 + 2*x2 + 1*lam1 - 1*v1 + 0*v2 + 0*s1 + 1*A1 + 0*A2 = 4
|
|
649
|
+
# 2) 2*x1 + 4*x2 + 2*lam1 + 0*v1 - 1*v2 + 0*s1 + 0*A1 + 1*A2 = 6
|
|
650
|
+
# 3) 1*x1 + 2*x2 + 0*lam1 + 0*v1 + 0*v2 + 1*s1 + 0*A1 + 0*A2 = 2
|
|
651
|
+
|
|
652
|
+
var_names = ['x1', 'x2', 'lam1', 'v1', 'v2', 's1', 'A1', 'A2']
|
|
653
|
+
|
|
654
|
+
# Complementary pairs (indices): (x1, v1) -> (0, 3), (x2, v2) -> (1, 4), (lam1, s1) -> (2, 5)
|
|
655
|
+
comp_partner = {0: 3, 3: 0, 1: 4, 4: 1, 2: 5, 5: 2}
|
|
656
|
+
|
|
657
|
+
# Initial Simplex Tableau: [x1, x2, lam1, v1, v2, s1, A1, A2 | RHS]
|
|
658
|
+
tableau = np.array([
|
|
659
|
+
[4, 2, 1, -1, 0, 0, 1, 0, 4],
|
|
660
|
+
[2, 4, 2, 0, -1, 0, 0, 1, 6],
|
|
661
|
+
[1, 2, 0, 0, 0, 1, 0, 0, 2]
|
|
662
|
+
], dtype=object)
|
|
663
|
+
|
|
664
|
+
# Convert entries to exact Fractions
|
|
665
|
+
for r in range(tableau.shape[0]):
|
|
666
|
+
for c in range(tableau.shape[1]):
|
|
667
|
+
tableau[r, c] = Fraction(int(tableau[r, c]), 1)
|
|
668
|
+
|
|
669
|
+
basis = [6, 7, 5] # Initial basic variables: A1, A2, s1
|
|
670
|
+
cost_c = [Fraction(0)] * 6 + [Fraction(-1), Fraction(-1)] # Maximize -A1 - A2
|
|
671
|
+
|
|
672
|
+
while True:
|
|
673
|
+
# Compute Zj - Cj for non-artificial columns (0..5)
|
|
674
|
+
zj_cj = []
|
|
675
|
+
for j in range(6):
|
|
676
|
+
zj = sum(cost_c[basis[i]] * tableau[i, j] for i in range(3))
|
|
677
|
+
zj_cj.append(zj - cost_c[j])
|
|
678
|
+
|
|
679
|
+
# Find eligible entering variable with most negative Zj - Cj
|
|
680
|
+
entering = -1
|
|
681
|
+
min_val = Fraction(0)
|
|
682
|
+
for j in range(6):
|
|
683
|
+
if zj_cj[j] < min_val:
|
|
684
|
+
partner = comp_partner[j]
|
|
685
|
+
# Restricted Entry Rule: partner must NOT be in the basis with positive value
|
|
686
|
+
if partner not in basis or tableau[basis.index(partner), -1] == 0:
|
|
687
|
+
min_val = zj_cj[j]
|
|
688
|
+
entering = j
|
|
689
|
+
|
|
690
|
+
if entering == -1:
|
|
691
|
+
break # Optimal solution reached
|
|
692
|
+
|
|
693
|
+
# Minimum ratio test for leaving variable
|
|
694
|
+
leaving_row = -1
|
|
695
|
+
min_ratio = None
|
|
696
|
+
for i in range(3):
|
|
697
|
+
if tableau[i, entering] > 0:
|
|
698
|
+
ratio = tableau[i, -1] / tableau[i, entering]
|
|
699
|
+
if min_ratio is None or ratio < min_ratio:
|
|
700
|
+
min_ratio = ratio
|
|
701
|
+
leaving_row = i
|
|
702
|
+
|
|
703
|
+
# Pivot operations
|
|
704
|
+
pivot = tableau[leaving_row, entering]
|
|
705
|
+
tableau[leaving_row, :] = tableau[leaving_row, :] / pivot
|
|
706
|
+
for i in range(3):
|
|
707
|
+
if i != leaving_row:
|
|
708
|
+
factor = tableau[i, entering]
|
|
709
|
+
tableau[i, :] = tableau[i, :] - factor * tableau[leaving_row, :]
|
|
710
|
+
|
|
711
|
+
basis[leaving_row] = entering
|
|
712
|
+
|
|
713
|
+
# Extract solution
|
|
714
|
+
sol = {name: Fraction(0) for name in var_names}
|
|
715
|
+
for i, b_idx in enumerate(basis):
|
|
716
|
+
sol[var_names[b_idx]] = tableau[i, -1]
|
|
717
|
+
|
|
718
|
+
x1_opt = sol['x1']
|
|
719
|
+
x2_opt = sol['x2']
|
|
720
|
+
z_max = 4*x1_opt + 6*x2_opt - 2*(x1_opt**2) - 2*x1_opt*x2_opt - 2*(x2_opt**2)
|
|
721
|
+
|
|
722
|
+
print("=== WOLFE'S METHOD OPTIMAL SOLUTION (EXACT) ===")
|
|
723
|
+
print(f"x1* = {x1_opt} ({float(x1_opt):.4f})")
|
|
724
|
+
print(f"x2* = {x2_opt} ({float(x2_opt):.4f})")
|
|
725
|
+
print(f"lambda_1* = {sol['lam1']}")
|
|
726
|
+
print(f"Maximum Z_x* = {z_max} ({float(z_max):.4f})")
|
|
727
|
+
|
|
728
|
+
# ==========================================================
|
|
729
|
+
# PART 2: NUMERICAL VERIFICATION USING SCIPY SLSQP
|
|
730
|
+
# ==========================================================
|
|
731
|
+
def objective(x):
|
|
732
|
+
# Negate Z_x for minimization
|
|
733
|
+
return -(4*x[0] + 6*x[1] - 2*x[0]**2 - 2*x[0]*x[1] - 2*x[1]**2)
|
|
734
|
+
|
|
735
|
+
constraints = ({'type': 'ineq', 'fun': lambda x: 2 - (x[0] + 2*x[1])})
|
|
736
|
+
bounds = [(0, None), (0, None)]
|
|
737
|
+
|
|
738
|
+
res = minimize(objective, [0, 0], method='SLSQP', bounds=bounds, constraints=constraints)
|
|
739
|
+
print("\n=== SCIPY VERIFICATION ===")
|
|
740
|
+
print(f"x1 = {res.x[0]:.4f}, x2 = {res.x[1]:.4f}, Max Z_x = {-res.fun:.4f}")
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
Code Question 4.2
|
|
744
|
+
Practical 4.2
|
|
745
|
+
Statement: (Non-linear objective function and linear constraints).
|
|
746
|
+
"Minimize " z=x_1^2+x_2^2," subject to the constraints :"
|
|
747
|
+
x_1+x_2≥4, 2x_1+x_2≥5, "and " x_1,x_2≥0
|
|
748
|
+
|
|
749
|
+
import numpy as np
|
|
750
|
+
import matplotlib.pyplot as plt
|
|
751
|
+
from scipy.optimize import minimize
|
|
752
|
+
|
|
753
|
+
# Objective: Minimize z = x1^2 + x2^2
|
|
754
|
+
def objective(x):
|
|
755
|
+
return x[0]**2 + x[1]**2
|
|
756
|
+
|
|
757
|
+
# Constraints in scipy 'ineq' format (fun(x) >= 0)
|
|
758
|
+
constraints = [
|
|
759
|
+
{'type': 'ineq', 'fun': lambda x: x[0] + x[1] - 4}, # x1 + x2 >= 4
|
|
760
|
+
{'type': 'ineq', 'fun': lambda x: 2*x[0] + x[1] - 5} # 2*x1 + x2 >= 5
|
|
761
|
+
]
|
|
762
|
+
bounds = [(0, None), (0, None)]
|
|
763
|
+
|
|
764
|
+
res = minimize(objective, [1, 1], method='SLSQP', bounds=bounds, constraints=constraints)
|
|
765
|
+
x1_opt, x2_opt = res.x
|
|
766
|
+
|
|
767
|
+
print("=== OPTIMAL SOLUTION (KUHN-TUCKER / SLSQP) ===")
|
|
768
|
+
print(f"x1* = {x1_opt:.4f}")
|
|
769
|
+
print(f"x2* = {x2_opt:.4f}")
|
|
770
|
+
print(f"Minimum z = {res.fun:.4f}")
|
|
771
|
+
|
|
772
|
+
# Graphical visualization
|
|
773
|
+
x1 = np.linspace(0, 6, 300)
|
|
774
|
+
y1 = 4 - x1 # x1 + x2 = 4
|
|
775
|
+
y2 = 5 - 2 * x1 # 2*x1 + x2 = 5
|
|
776
|
+
|
|
777
|
+
plt.figure(figsize=(7, 6))
|
|
778
|
+
plt.plot(x1, y1, 'b-', label='x1 + x2 = 4')
|
|
779
|
+
plt.plot(x1, y2, 'g-', label='2x1 + x2 = 5')
|
|
780
|
+
|
|
781
|
+
# Shade feasible region (above both lines)
|
|
782
|
+
y_lower = np.maximum(np.maximum(y1, y2), 0)
|
|
783
|
+
plt.fill_between(x1, y_lower, 6, color='lightgreen', alpha=0.4, label='Feasible Region')
|
|
784
|
+
|
|
785
|
+
# Plot objective circle z = 8 (radius = sqrt(8))
|
|
786
|
+
theta = np.linspace(0, np.pi/2, 200)
|
|
787
|
+
r = np.sqrt(res.fun)
|
|
788
|
+
plt.plot(r * np.cos(theta), r * np.sin(theta), 'r--', label='Objective Circle: x1^2 + x2^2 = 8')
|
|
789
|
+
|
|
790
|
+
plt.scatter([x1_opt], [x2_opt], color='red', s=90, zorder=5, label=f'Optimum ({x1_opt:.1f}, {x2_opt:.1f})')
|
|
791
|
+
plt.xlim(0, 6)
|
|
792
|
+
plt.ylim(0, 6)
|
|
793
|
+
plt.xlabel('x1')
|
|
794
|
+
plt.ylabel('x2')
|
|
795
|
+
plt.title('Graphical Verification: Min z = x1^2 + x2^2')
|
|
796
|
+
plt.grid(True, linestyle=':')
|
|
797
|
+
plt.legend()
|
|
798
|
+
plt.tight_layout()
|
|
799
|
+
plt.show()
|
|
800
|
+
|
|
801
|
+
'''
|