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_p1_1.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
from scipy.optimize import linprog
|
|
4
|
+
|
|
5
|
+
# Max Z = 280000 - 150*x1 - 100*x2
|
|
6
|
+
c = [150,100]
|
|
7
|
+
|
|
8
|
+
# inequality constraints (A_ub *x <= b_ub)
|
|
9
|
+
# 1. x1 + x2 <= 140
|
|
10
|
+
# 2. -(x1+x2) = -120
|
|
11
|
+
|
|
12
|
+
A_ub = [
|
|
13
|
+
[1,1],
|
|
14
|
+
[-1,-1]
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
b_ub = [140,-120]
|
|
18
|
+
|
|
19
|
+
# Bounds decision variables
|
|
20
|
+
# 1. 20 <= x1 <= 60
|
|
21
|
+
# 2. 70 <= x2 <= 140
|
|
22
|
+
x1_bounds = (20,60)
|
|
23
|
+
x2_bounds = (70,140)
|
|
24
|
+
|
|
25
|
+
# Solve linear program
|
|
26
|
+
result = linprog(c,A_ub,b_ub,bounds=[x1_bounds,x2_bounds])
|
|
27
|
+
|
|
28
|
+
# extract optimal values
|
|
29
|
+
opt_x1 = round(result.x[0])
|
|
30
|
+
opt_x2 = round(result.x[1])
|
|
31
|
+
opt_x3 = 200 - opt_x1 - opt_x2
|
|
32
|
+
max_profit = 280000 - result.fun
|
|
33
|
+
|
|
34
|
+
print("OPTIMAL TOUR PACKAGE PLAN")
|
|
35
|
+
print(f"Deluxe Packages (x1) : {opt_x1}")
|
|
36
|
+
print(f"Standard Packages (x2) : {opt_x2}")
|
|
37
|
+
print(f"Economy Packages (x3) : {opt_x3}")
|
|
38
|
+
print(f"Total Packages : {opt_x1 + opt_x2 + opt_x3}")
|
|
39
|
+
print(f"Maximum Net Profit : Rs. {max_profit:,.2f}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
x1_vals = np.linspace(0,90,400)
|
|
43
|
+
|
|
44
|
+
# Constraint lines for x2
|
|
45
|
+
y_sum_140 = 140 - x1_vals # x1 + x2 = 140
|
|
46
|
+
y_sum_120 = 120 - x1_vals # x1 + x2 = 120
|
|
47
|
+
|
|
48
|
+
plt.figure(figsize=(9,7))
|
|
49
|
+
|
|
50
|
+
# plot boundary lines
|
|
51
|
+
plt.axvline(x=20,color="blue",linestyle="--",label="x1 = 20 (min)")
|
|
52
|
+
plt.axvline(x=60,color="purple",linestyle="--",label="x1 = 60 (max)")
|
|
53
|
+
plt.axhline(y=70,color="orange",linestyle="--",label="x2 = 70 (min)")
|
|
54
|
+
plt.axhline(y=140,color="brown",linestyle="--",label="x2 = 140 (max)")
|
|
55
|
+
|
|
56
|
+
plt.plot(x1_vals,y_sum_140,color="green",linewidth=2,label="x1+x2=140")
|
|
57
|
+
plt.plot(x1_vals,y_sum_120,color="red",linewidth=2,label="x1+x2=120")
|
|
58
|
+
|
|
59
|
+
# Define the 5 corner points of the feasible region in order
|
|
60
|
+
corner_x1 = [20,20,60,60,50]
|
|
61
|
+
corner_x2 = [100,120,80,70,70]
|
|
62
|
+
labels = ['A(20,100)','B(20,120)',"C(60,80)","D(60,70)","E(50,70)"]
|
|
63
|
+
|
|
64
|
+
plt.fill(corner_x1,corner_x2,color="skyblue",alpha=0.5,label="Feasible Region")
|
|
65
|
+
|
|
66
|
+
# plot and annotate corner points
|
|
67
|
+
plt.scatter(corner_x1,corner_x2,color="black",zorder=5)
|
|
68
|
+
for i, txt in enumerate(labels):
|
|
69
|
+
plt.annotate(txt,(corner_x1[i]+1.2, corner_x2[i]+1.2),fontsize=9,fontweight="bold")
|
|
70
|
+
|
|
71
|
+
plt.scatter([opt_x1],[opt_x2],color="red",s=120,zorder=5,label=f'Optimal Point A({opt_x1},{opt_x2})')
|
|
72
|
+
|
|
73
|
+
plt.xlim(0,85)
|
|
74
|
+
plt.ylim(40,155)
|
|
75
|
+
plt.xlabel("Deluxe Packages (x1)",fontsize=11)
|
|
76
|
+
plt.ylabel("Standard Packages (x2)",fontsize=11)
|
|
77
|
+
plt.title("Graphical Solution: Travel Agent Charter Tour LPP",fontsize=11)
|
|
78
|
+
plt.grid(True,linestyle=":",alpha=0.7)
|
|
79
|
+
plt.legend(loc="upper right",fontsize=8.5)
|
|
80
|
+
plt.tight_layout()
|
|
81
|
+
plt.show()
|
cg_code/om/om_p1_2.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.optimize import linprog
|
|
3
|
+
|
|
4
|
+
# Max z = 4000*x1 + 2000*x2 + 5000*x3
|
|
5
|
+
c = [-4000,-2000,-5000]
|
|
6
|
+
|
|
7
|
+
# Constraints
|
|
8
|
+
# Labour: 12*x1 + 7*x2 + 9*x3 <= 1260
|
|
9
|
+
# Wood: 22*x1 + 18*x2 + 16*x3 <= 19008
|
|
10
|
+
# Screws: 2*x1 + 4*x2 + 3*x3 <= 396
|
|
11
|
+
A_ub = [
|
|
12
|
+
[12,7,9],
|
|
13
|
+
[22,18,16],
|
|
14
|
+
[2,4,3]
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
b_ub = [1260,19008,396]
|
|
18
|
+
|
|
19
|
+
# Non-negative values: x1,x2,x3 >= 0
|
|
20
|
+
bounds = [(0,None),(0,None),(0,None)]
|
|
21
|
+
|
|
22
|
+
result = linprog(c,A_ub,b_ub,bounds=bounds)
|
|
23
|
+
|
|
24
|
+
# extract optimal decision variables
|
|
25
|
+
x1, x2, x3 = result.x
|
|
26
|
+
max_revenue = -result.fun
|
|
27
|
+
|
|
28
|
+
# Calculate resources_usage and sparse capacity
|
|
29
|
+
resources_usage = np.dot(A_ub,result.x)
|
|
30
|
+
sparse_capacity = np.array(b_ub) - resources_usage
|
|
31
|
+
|
|
32
|
+
print("Optimal Boat Production and Revenue")
|
|
33
|
+
print(f"Row Boats: {x1:.2f} units")
|
|
34
|
+
print(f"Canoe: {x2:.2f} units")
|
|
35
|
+
print(f"Kayak: {x3:.2f} units")
|
|
36
|
+
|
|
37
|
+
print("SPARSE UTILIZATION AND SPARSE CAPACITY")
|
|
38
|
+
resources_name = ["Labour (in hours)","Wood (Board feet)","Screws (kg.)"]
|
|
39
|
+
for name, avail, used, slack in zip(resources_name,b_ub,resources_usage,sparse_capacity):
|
|
40
|
+
status = "Not fully utilize" if slack > 1e-5 else "Fully Utilized"
|
|
41
|
+
print(f"{name:<18} | Available: {avail:<10} | Used: {used:<8} | Spare: {slack:<10}")
|
|
42
|
+
|
|
43
|
+
print(f"Total wood used: {resources_usage[1]:.2f} board feet")
|
cg_code/om/om_p1_3.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.optimize import linprog
|
|
3
|
+
|
|
4
|
+
years = [f"Years {i}" for i in range(1,5)]
|
|
5
|
+
types = [f"Types {chr(65+i)}" for i in range(6)]
|
|
6
|
+
|
|
7
|
+
returns = np.array([
|
|
8
|
+
[0.80, 0.90, 0.60, 0.75, 1.00],
|
|
9
|
+
[0.55, 0.65, 0.40, 0.60, 0.50],
|
|
10
|
+
[0.30, 0.25, 0.30, 0.50, 0.20],
|
|
11
|
+
[0.15, 0.12, 0.25, 0.35, 0.10]
|
|
12
|
+
])
|
|
13
|
+
|
|
14
|
+
supply = [500,600,750,800]
|
|
15
|
+
demand = [750,600,500,800,1000]
|
|
16
|
+
|
|
17
|
+
num_years, num_types = returns.shape
|
|
18
|
+
|
|
19
|
+
c = -returns.flatten()
|
|
20
|
+
|
|
21
|
+
# Equality constraint
|
|
22
|
+
A_eq = []
|
|
23
|
+
b_eq = []
|
|
24
|
+
for i in range(num_years):
|
|
25
|
+
row = np.zeros((num_years,num_types))
|
|
26
|
+
row[i,:] = 1
|
|
27
|
+
A_eq.append(row.flatten())
|
|
28
|
+
b_eq.append(supply[i])
|
|
29
|
+
|
|
30
|
+
# Ineqality constraint
|
|
31
|
+
A_ub = []
|
|
32
|
+
b_ub = []
|
|
33
|
+
for j in range(num_types):
|
|
34
|
+
row = np.zeros((num_years,num_types))
|
|
35
|
+
row[:,j] = 1
|
|
36
|
+
A_ub.append(row.flatten())
|
|
37
|
+
b_ub.append(demand[j])
|
|
38
|
+
|
|
39
|
+
res = linprog(c,A_ub,b_ub,A_eq,b_eq,bounds=(0,None))
|
|
40
|
+
|
|
41
|
+
allocation = res.x.reshape((num_years,num_types))
|
|
42
|
+
max_net_returns = -res.fun
|
|
43
|
+
|
|
44
|
+
print("OPTIMAL INVESTMENT SCHEDULE (IN RS. 000s)")
|
|
45
|
+
header = f"{'Year \\ Type':>12}" + "".join([f"{t:>10}" for t in types]) + "{'Total':>10}"
|
|
46
|
+
print(header)
|
|
47
|
+
print("-"*len(header))
|
|
48
|
+
|
|
49
|
+
for i,y in enumerate(years):
|
|
50
|
+
row_str = f"{y:.12}" + "".join([f"{allocation[i,j]:>10.2f}" for j in range(num_types)])
|
|
51
|
+
row_str += f"{np.sum(allocation[i,:]):10.2f}"
|
|
52
|
+
print(row_str)
|
|
53
|
+
|
|
54
|
+
print("-"*len(header))
|
|
55
|
+
col_totals = f"{'Invested':<12}" + "".join([f"{np.sum(allocation[:,j]):>10.2f}" for j in range(num_types)])
|
|
56
|
+
col_totals += f"{np.sum(allocation):>10.2f}"
|
|
57
|
+
print(col_totals)
|
|
58
|
+
print(f"Maximum Net Profit Return: Rs. {max_net_returns*1000}")
|
cg_code/om/om_p1_4.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import math
|
|
3
|
+
from scipy.optimize import linear_sum_assignment
|
|
4
|
+
|
|
5
|
+
typist = ['A','B','C','D','E']
|
|
6
|
+
rates = [5,6,3,4,4]
|
|
7
|
+
speeds = [12,14,8,10,11]
|
|
8
|
+
|
|
9
|
+
jobs = ['P','Q','R','S','T']
|
|
10
|
+
pages = [199,175,145,298,178]
|
|
11
|
+
|
|
12
|
+
num_typist = len(typist)
|
|
13
|
+
num_jobs = len(jobs)
|
|
14
|
+
|
|
15
|
+
# Cost Matrix
|
|
16
|
+
cost_matrix = np.zeros((num_typist,num_jobs),dtype=int)
|
|
17
|
+
for i in range(num_typist):
|
|
18
|
+
for j in range(num_jobs):
|
|
19
|
+
hours = math.ceil(pages[j]/speeds[i])
|
|
20
|
+
cost_matrix[i,j] = hours*rates[i]
|
|
21
|
+
|
|
22
|
+
print("COMPUTE COST MATRIX")
|
|
23
|
+
header = f"{"Typist \\ Job":<14}" + "".join([f"{job:<6}" for job in jobs])
|
|
24
|
+
print(header)
|
|
25
|
+
print("-"*len(header))
|
|
26
|
+
for i,t in enumerate(typist):
|
|
27
|
+
row_str = f"{t:<14}" + "".join([f"{cost_matrix[i,j]:<6}" for j in range(num_jobs)])
|
|
28
|
+
print(row_str)
|
|
29
|
+
|
|
30
|
+
row_ind,col_ind = linear_sum_assignment(cost_matrix)
|
|
31
|
+
total_min_cost = cost_matrix[row_ind,col_ind].sum()
|
|
32
|
+
|
|
33
|
+
print("OPTIMAL LEAST-COST ALLOCATION")
|
|
34
|
+
for r,c in zip(row_ind,col_ind):
|
|
35
|
+
hrs = math.ceil(pages[c]/speeds[r])
|
|
36
|
+
print(f"Typist {typist[r]} -> Job {jobs[c]} ({pages[c]} pages | {hrs} hours @ Rs.{rates[r]}/hr) = Rs. {cost_matrix[r,c]}")
|
|
37
|
+
|
|
38
|
+
print(f"Minimum Total Cost : Rs.{total_min_cost}")
|
cg_code/om/om_p2_1.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
|
|
4
|
+
payoff = np.array([[-1, 6], [2, 4], [-2, -6]])
|
|
5
|
+
|
|
6
|
+
strategies_A = ["A1", "A2", "A3"]
|
|
7
|
+
strategies_B = ["B1", "B2"]
|
|
8
|
+
|
|
9
|
+
# Check saddle point (Maximin and Minimax)
|
|
10
|
+
row_mins = np.min(payoff, axis=1) # Maximin
|
|
11
|
+
col_max = np.max(payoff, axis=0) # Minimax
|
|
12
|
+
|
|
13
|
+
maximin = np.max(row_mins)
|
|
14
|
+
minimax = np.min(col_max)
|
|
15
|
+
|
|
16
|
+
print("PAYOFF MATRIX (PLAYER A)")
|
|
17
|
+
print(payoff)
|
|
18
|
+
print(f"\nRows Minimum: {row_mins} --> Maximin: {maximin}")
|
|
19
|
+
print(f"Column Maximum: {col_max} --> Minimax: {minimax}")
|
|
20
|
+
|
|
21
|
+
if maximin == minimax:
|
|
22
|
+
opt_row = np.argmax(row_mins)
|
|
23
|
+
opt_col = np.argmin(col_max)
|
|
24
|
+
print(f"Saddle Point Found at ({strategies_A[opt_row]}, {strategies_B[opt_col]})")
|
|
25
|
+
print(f"Optimal Strategy for Player A : {strategies_A[opt_row]}")
|
|
26
|
+
print(f"Optimal Strategy for Player B : {strategies_B[opt_col]}")
|
|
27
|
+
print(f"value of the Game (V): Rs.{maximin}")
|
|
28
|
+
else:
|
|
29
|
+
print("No any Saddle Point found")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Graphical Verification
|
|
33
|
+
q = np.linspace(0, 1, 200)
|
|
34
|
+
# E_An = B1*q + B2*(1-q)
|
|
35
|
+
E_A1 = -1 * q + 6 * (1 - q)
|
|
36
|
+
E_A2 = 2 * q + 4 * (1 - q)
|
|
37
|
+
E_A3 = -2 * q - 6 * (1 - q)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
plt.figure(figsize=(8,5))
|
|
41
|
+
plt.plot(q,E_A1,label='A1: -1q + 6(1-q)',linewidth=2)
|
|
42
|
+
plt.plot(q,E_A2,label='A2: 2q + 4(1-q)',linewidth=2)
|
|
43
|
+
plt.plot(q,E_A3,label='A3: -2q - 6(1-q)',linewidth=2)
|
|
44
|
+
|
|
45
|
+
upper_env = np.maximum.reduce([E_A1,E_A2,E_A3])
|
|
46
|
+
plt.plot(q,upper_env,'k--',linewidth=2.5,label="Upper Envolpe (Max Payoff)")
|
|
47
|
+
|
|
48
|
+
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)')
|
|
49
|
+
|
|
50
|
+
plt.xlabel("Probability q of Player B playing B1")
|
|
51
|
+
plt.ylabel("Expected Payoff to Player A (Rs.)")
|
|
52
|
+
plt.title("Graphical Verification of 3x2 Game")
|
|
53
|
+
plt.grid(True,linestyle=":")
|
|
54
|
+
plt.legend()
|
|
55
|
+
plt.tight_layout()
|
|
56
|
+
plt.show()
|
cg_code/om/om_p3_1.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
arrival_rate = 8.0 # lambda = 8 customers per hour
|
|
4
|
+
service_rate_old = 12.0 # mu_1 = 12 customers per hour (5 mins per customer)
|
|
5
|
+
working_hours = 8.0 # 8-hour working day
|
|
6
|
+
cost_per_wait_min = 0.12 # 12 paise = Rs. 0.12 per minute
|
|
7
|
+
|
|
8
|
+
def mm1_metrics(lam,mu):
|
|
9
|
+
rho = lam/mu # Utlization Factor
|
|
10
|
+
Lq = (lam**2)/(mu*(mu-lam)) # Avg customers waiting in queue
|
|
11
|
+
Ls = lam / (mu-lam) # Avg customers in system
|
|
12
|
+
Wq_hours = lam/(mu*(mu-lam)) # Avg waiting time is queue (hours)
|
|
13
|
+
Wq_mins = Wq_hours*60 # Avg waiting time in queue (minutes)
|
|
14
|
+
Ws_mins = (1/(mu-lam))*60 # Avg time spent in system (minutes)
|
|
15
|
+
return rho,Lq,Ls,Wq_mins,Ws_mins
|
|
16
|
+
|
|
17
|
+
rho1,Lq1,Ls1,Wq1_mins,Ws1_mins = mm1_metrics(arrival_rate,service_rate_old)
|
|
18
|
+
|
|
19
|
+
print("CURRENT SYSTEM PERFORMANCE")
|
|
20
|
+
print(f"Traffic Intensity (rho) :{rho1:.4f}")
|
|
21
|
+
print(f"(a) Avg Customers Waiting (Lq) :{Lq1:.2f} customers")
|
|
22
|
+
print(f"(b) Avg Waiting Time in Queue (Wq) :{Wq1_mins:.2f} minutes")
|
|
23
|
+
|
|
24
|
+
service_time_new = 3.0 # 3 minutes per customer
|
|
25
|
+
service_rate_new = 60.0 / service_time_new # mu_2 = 20 customers per hour
|
|
26
|
+
|
|
27
|
+
rho2,Lq2,Ls2,Wq2_mins,Ws2_mins = mm1_metrics(arrival_rate,service_rate_new)
|
|
28
|
+
|
|
29
|
+
customers_per_day = arrival_rate*working_hours
|
|
30
|
+
total_wait_old = customers_per_day * Wq1_mins
|
|
31
|
+
total_wait_new = customers_per_day * Wq2_mins
|
|
32
|
+
time_saved_mins = total_wait_old - total_wait_new
|
|
33
|
+
|
|
34
|
+
cost_old = total_wait_old * cost_per_wait_min
|
|
35
|
+
cost_new = total_wait_new * cost_per_wait_min
|
|
36
|
+
net_savings = cost_old - cost_new
|
|
37
|
+
|
|
38
|
+
print("NEW COMPUTER SYSTEM COMPARISION (8-HOURS DAY)")
|
|
39
|
+
print(f"New Service Rate (mu_2) : {service_rate_new:.2f} customers/hour")
|
|
40
|
+
print(f"New Avg Customers Waiting (Lq2) : {Lq2:.2f} customers")
|
|
41
|
+
print(f"New Waiting Time (Wq2) : {Wq2_mins:.2f} minutes")
|
|
42
|
+
print(f"Total Customers per day : {int(customers_per_day)} customers")
|
|
43
|
+
print(f"Daily Waiting time (Old vs New) : {total_wait_old} vs {total_wait_new} minutes")
|
|
44
|
+
print(f"Daily Waiting time saved : {time_saved_mins} minutes")
|
|
45
|
+
print(f"Daily Waiting cost (old vs new) : Rs. {cost_old} vs Rs. {cost_new}")
|
|
46
|
+
print(f"New Daily saving : ₹ {net_savings}")
|
|
47
|
+
|
|
48
|
+
if net_savings > 0:print("Decision: INSTALL the computer system")
|
|
49
|
+
else:print("Decision: DO NOT INSTALL the computer system")
|
cg_code/om/om_p3_4.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
past_orders = 8
|
|
4
|
+
past_order_size = 200
|
|
5
|
+
D = past_orders * past_order_size # Annual Demand = 1600 units
|
|
6
|
+
|
|
7
|
+
Co = 500.0 # Ordering cost per order
|
|
8
|
+
P_normal = 400.0 # Normal price per unit
|
|
9
|
+
carrying_rate = 0.40 # 40% inventory carrying cost rate
|
|
10
|
+
|
|
11
|
+
discount_rate = 0.10 # 10% discount
|
|
12
|
+
Q_discount = 500 # Minimum order quantity for discount
|
|
13
|
+
P_discount = P_normal * (1 - discount_rate) # ₹360 per unit
|
|
14
|
+
|
|
15
|
+
def total_annual_cost(D, Q, P, Co, i):
|
|
16
|
+
Ch = i * P
|
|
17
|
+
purchase_cost = D*P
|
|
18
|
+
ordering_cost = (D/Q)*Co
|
|
19
|
+
carrying_cost = (Q/2)*Ch
|
|
20
|
+
total = purchase_cost + ordering_cost + carrying_cost
|
|
21
|
+
return purchase_cost, ordering_cost, carrying_cost,total
|
|
22
|
+
|
|
23
|
+
Ch_normal = carrying_rate * P_normal
|
|
24
|
+
Q = math.sqrt((2*D*Co)/Ch_normal)
|
|
25
|
+
|
|
26
|
+
# Optimal EOQ without discount
|
|
27
|
+
p1, o1, c1, total_eoq = total_annual_cost(D,Q,P_normal,Co,carrying_rate)
|
|
28
|
+
|
|
29
|
+
# Managers proposal (500 units with 10% discount)
|
|
30
|
+
p2, o2, c2, total_disc = total_annual_cost(D,Q_discount,P_discount, Co,carrying_rate)
|
|
31
|
+
|
|
32
|
+
# Past policy (200 units without discount)
|
|
33
|
+
p3, o3, c3, total_past = total_annual_cost(D,past_order_size,P_normal,Co,carrying_rate)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
print(f"Annual Demand (D) : {D} units")
|
|
37
|
+
print(f"Normal EOQ (Without Discount) : {Q:.0f} units\n")
|
|
38
|
+
|
|
39
|
+
print("=== COST COMPARISON SUMMARY ===")
|
|
40
|
+
print(f"1. Past Policy (Q=200 @ Rs.400) : Rs. {total_past:,.2f}")
|
|
41
|
+
print(f"2. Optimal EOQ (Q=100 @ Rs.400) : Rs. {total_eoq:,.2f}")
|
|
42
|
+
print(f"3. Manager Offer (Q=500 @ Rs.360) : Rs. {total_disc:,.2f}\n")
|
|
43
|
+
|
|
44
|
+
savings_vs_eoq = total_eoq - total_disc
|
|
45
|
+
savings_vs_past = total_past - total_disc
|
|
46
|
+
|
|
47
|
+
if total_disc < total_eoq:
|
|
48
|
+
print("Decision: Purchase Manager IS JUSTIFIED.")
|
|
49
|
+
print(f"Net Annual Savings vs EOQ Policy : Rs. {savings_vs_eoq:,.2f}")
|
|
50
|
+
print(f"Net Annual Savings vs Past Policy : Rs. {savings_vs_past:,.2f}")
|
|
51
|
+
else:
|
|
52
|
+
print("Decision: Purchase Manager is NOT justified.")
|
cg_code/om/om_p4_1.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from fractions import Fraction
|
|
3
|
+
from scipy.optimize import minimize
|
|
4
|
+
|
|
5
|
+
# ==========================================================
|
|
6
|
+
# PART 1: WOLFE'S METHOD (EXACT SIMPLEX WITH RESTRICTED ENTRY)
|
|
7
|
+
# ==========================================================
|
|
8
|
+
# KKT Equations with Artificial Variables A1, A2:
|
|
9
|
+
# 1) 4*x1 + 2*x2 + 1*lam1 - 1*v1 + 0*v2 + 0*s1 + 1*A1 + 0*A2 = 4
|
|
10
|
+
# 2) 2*x1 + 4*x2 + 2*lam1 + 0*v1 - 1*v2 + 0*s1 + 0*A1 + 1*A2 = 6
|
|
11
|
+
# 3) 1*x1 + 2*x2 + 0*lam1 + 0*v1 + 0*v2 + 1*s1 + 0*A1 + 0*A2 = 2
|
|
12
|
+
|
|
13
|
+
var_names = ['x1', 'x2', 'lam1', 'v1', 'v2', 's1', 'A1', 'A2']
|
|
14
|
+
|
|
15
|
+
# Complementary pairs (indices): (x1, v1) -> (0, 3), (x2, v2) -> (1, 4), (lam1, s1) -> (2, 5)
|
|
16
|
+
comp_partner = {0: 3, 3: 0, 1: 4, 4: 1, 2: 5, 5: 2}
|
|
17
|
+
|
|
18
|
+
# Initial Simplex Tableau: [x1, x2, lam1, v1, v2, s1, A1, A2 | RHS]
|
|
19
|
+
tableau = np.array([
|
|
20
|
+
[4, 2, 1, -1, 0, 0, 1, 0, 4],
|
|
21
|
+
[2, 4, 2, 0, -1, 0, 0, 1, 6],
|
|
22
|
+
[1, 2, 0, 0, 0, 1, 0, 0, 2]
|
|
23
|
+
], dtype=object)
|
|
24
|
+
|
|
25
|
+
# Convert entries to exact Fractions
|
|
26
|
+
for r in range(tableau.shape[0]):
|
|
27
|
+
for c in range(tableau.shape[1]):
|
|
28
|
+
tableau[r, c] = Fraction(int(tableau[r, c]), 1)
|
|
29
|
+
|
|
30
|
+
basis = [6, 7, 5] # Initial basic variables: A1, A2, s1
|
|
31
|
+
cost_c = [Fraction(0)] * 6 + [Fraction(-1), Fraction(-1)] # Maximize -A1 - A2
|
|
32
|
+
|
|
33
|
+
while True:
|
|
34
|
+
# Compute Zj - Cj for non-artificial columns (0..5)
|
|
35
|
+
zj_cj = []
|
|
36
|
+
for j in range(6):
|
|
37
|
+
zj = sum(cost_c[basis[i]] * tableau[i, j] for i in range(3))
|
|
38
|
+
zj_cj.append(zj - cost_c[j])
|
|
39
|
+
|
|
40
|
+
# Find eligible entering variable with most negative Zj - Cj
|
|
41
|
+
entering = -1
|
|
42
|
+
min_val = Fraction(0)
|
|
43
|
+
for j in range(6):
|
|
44
|
+
if zj_cj[j] < min_val:
|
|
45
|
+
partner = comp_partner[j]
|
|
46
|
+
# Restricted Entry Rule: partner must NOT be in the basis with positive value
|
|
47
|
+
if partner not in basis or tableau[basis.index(partner), -1] == 0:
|
|
48
|
+
min_val = zj_cj[j]
|
|
49
|
+
entering = j
|
|
50
|
+
|
|
51
|
+
if entering == -1:
|
|
52
|
+
break # Optimal solution reached
|
|
53
|
+
|
|
54
|
+
# Minimum ratio test for leaving variable
|
|
55
|
+
leaving_row = -1
|
|
56
|
+
min_ratio = None
|
|
57
|
+
for i in range(3):
|
|
58
|
+
if tableau[i, entering] > 0:
|
|
59
|
+
ratio = tableau[i, -1] / tableau[i, entering]
|
|
60
|
+
if min_ratio is None or ratio < min_ratio:
|
|
61
|
+
min_ratio = ratio
|
|
62
|
+
leaving_row = i
|
|
63
|
+
|
|
64
|
+
# Pivot operations
|
|
65
|
+
pivot = tableau[leaving_row, entering]
|
|
66
|
+
tableau[leaving_row, :] = tableau[leaving_row, :] / pivot
|
|
67
|
+
for i in range(3):
|
|
68
|
+
if i != leaving_row:
|
|
69
|
+
factor = tableau[i, entering]
|
|
70
|
+
tableau[i, :] = tableau[i, :] - factor * tableau[leaving_row, :]
|
|
71
|
+
|
|
72
|
+
basis[leaving_row] = entering
|
|
73
|
+
|
|
74
|
+
# Extract solution
|
|
75
|
+
sol = {name: Fraction(0) for name in var_names}
|
|
76
|
+
for i, b_idx in enumerate(basis):
|
|
77
|
+
sol[var_names[b_idx]] = tableau[i, -1]
|
|
78
|
+
|
|
79
|
+
x1_opt = sol['x1']
|
|
80
|
+
x2_opt = sol['x2']
|
|
81
|
+
z_max = 4*x1_opt + 6*x2_opt - 2*(x1_opt**2) - 2*x1_opt*x2_opt - 2*(x2_opt**2)
|
|
82
|
+
|
|
83
|
+
print("=== WOLFE'S METHOD OPTIMAL SOLUTION (EXACT) ===")
|
|
84
|
+
print(f"x1* = {x1_opt} ({float(x1_opt):.4f})")
|
|
85
|
+
print(f"x2* = {x2_opt} ({float(x2_opt):.4f})")
|
|
86
|
+
print(f"lambda_1* = {sol['lam1']}")
|
|
87
|
+
print(f"Maximum Z_x* = {z_max} ({float(z_max):.4f})")
|
|
88
|
+
|
|
89
|
+
# ==========================================================
|
|
90
|
+
# PART 2: NUMERICAL VERIFICATION USING SCIPY SLSQP
|
|
91
|
+
# ==========================================================
|
|
92
|
+
def objective(x):
|
|
93
|
+
# Negate Z_x for minimization
|
|
94
|
+
return -(4*x[0] + 6*x[1] - 2*x[0]**2 - 2*x[0]*x[1] - 2*x[1]**2)
|
|
95
|
+
|
|
96
|
+
constraints = ({'type': 'ineq', 'fun': lambda x: 2 - (x[0] + 2*x[1])})
|
|
97
|
+
bounds = [(0, None), (0, None)]
|
|
98
|
+
|
|
99
|
+
res = minimize(objective, [0, 0], method='SLSQP', bounds=bounds, constraints=constraints)
|
|
100
|
+
print("\n=== SCIPY VERIFICATION ===")
|
|
101
|
+
print(f"x1 = {res.x[0]:.4f}, x2 = {res.x[1]:.4f}, Max Z_x = {-res.fun:.4f}")
|
cg_code/om/om_p_2_2.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
jobs = [1, 2, 3, 4, 5, 6]
|
|
2
|
+
m1 = [5, 9, 4, 7, 8, 6]
|
|
3
|
+
m2 = [7, 4, 8, 3, 9, 5]
|
|
4
|
+
|
|
5
|
+
# Johnson's Algorithm for optimal sequence
|
|
6
|
+
rem = list(range(len(jobs)))
|
|
7
|
+
left, right = [], []
|
|
8
|
+
|
|
9
|
+
while rem:
|
|
10
|
+
best_val, idx, mach = float('inf'), -1, 1
|
|
11
|
+
for i in rem:
|
|
12
|
+
if m1[i] < best_val:
|
|
13
|
+
best_val, idx, mach = m1[i], i, 1
|
|
14
|
+
if m2[i] < best_val:
|
|
15
|
+
best_val, idx, mach = m2[i], i, 2
|
|
16
|
+
if mach == 1:
|
|
17
|
+
left.append(idx)
|
|
18
|
+
else:
|
|
19
|
+
right.insert(0, idx)
|
|
20
|
+
rem.remove(idx)
|
|
21
|
+
|
|
22
|
+
seq = left + right
|
|
23
|
+
print("Optimal Sequence:", " -> ".join(str(jobs[i]) for i in seq))
|
|
24
|
+
|
|
25
|
+
# In-Out time calculation
|
|
26
|
+
m1_out = m2_out = idle_m2 = 0
|
|
27
|
+
for i in seq:
|
|
28
|
+
m1_in = m1_out
|
|
29
|
+
m1_out = m1_in + m1[i]
|
|
30
|
+
m2_in = max(m1_out, m2_out)
|
|
31
|
+
idle_m2 += (m2_in - m2_out)
|
|
32
|
+
m2_out = m2_in + m2[i]
|
|
33
|
+
|
|
34
|
+
print(f"Minimum Total Elapsed Time : {m2_out} hours")
|
|
35
|
+
print(f"Idle Time on Machine I : {m2_out - m1_out} hours")
|
|
36
|
+
print(f"Idle Time on Machine II : {idle_m2} hours")
|
cg_code/om/om_p_2_3.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
|
|
3
|
+
|
|
4
|
+
# Objective: Maximize Z = 1*x1 + 4*x2 -> Minimize (-1*x1 - 4*x2)
|
|
5
|
+
c = np.array([-1.0, -4.0])
|
|
6
|
+
A = np.array([
|
|
7
|
+
[2.0, 4.0], # Tailor A: 2*x1 + 4*x2 <= 7
|
|
8
|
+
[5.0, 3.0] # Tailor B: 5*x1 + 3*x2 <= 15
|
|
9
|
+
])
|
|
10
|
+
b = np.array([7.0, 15.0])
|
|
11
|
+
|
|
12
|
+
# (a) Continuous LPP solution
|
|
13
|
+
res_lp = linprog(c, A_ub=A, b_ub=b, bounds=(0, None), method='highs')
|
|
14
|
+
print("=== (a) Continuous LPP Solution ===")
|
|
15
|
+
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}")
|
|
16
|
+
|
|
17
|
+
# (b) Integer LPP solution (Gomory Cut equivalent)
|
|
18
|
+
constraints = LinearConstraint(A, -np.inf, b)
|
|
19
|
+
integrality = np.ones_like(c)
|
|
20
|
+
res_ip = milp(c=c, integrality=integrality, bounds=Bounds(0, np.inf), constraints=constraints)
|
|
21
|
+
|
|
22
|
+
print("\n=== (b) Optimal Integer Solution ===")
|
|
23
|
+
print(f"Zee-shirts (x1) = {int(round(res_ip.x[0]))}")
|
|
24
|
+
print(f"Button-down (x2)= {int(round(res_ip.x[1]))}")
|
|
25
|
+
print(f"Maximum Profit = Rs. {int(round(-res_ip.fun))}")
|
cg_code/om/om_p_3_2.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
lam = 1 / 10 # 0.10 customers/min (6/hr)
|
|
2
|
+
mu = 1 / 3 # 0.3333 customers/min (20/hr)
|
|
3
|
+
|
|
4
|
+
# (a) Probability customer has to wait
|
|
5
|
+
prob_wait = lam / mu
|
|
6
|
+
|
|
7
|
+
# (b) Average length of non-empty queues
|
|
8
|
+
avg_non_empty = mu / (mu - lam)
|
|
9
|
+
|
|
10
|
+
# (c) New arrival rate for Wq = 3 mins -> lam_new / (mu * (mu - lam_new)) = 3
|
|
11
|
+
target_wq = 3.0
|
|
12
|
+
lam_new = (target_wq * mu**2) / (1 + target_wq * mu)
|
|
13
|
+
increase_per_hr = (lam_new - lam) * 60
|
|
14
|
+
|
|
15
|
+
# (d) Fraction of day phone is in use
|
|
16
|
+
busy_fraction = lam / mu
|
|
17
|
+
|
|
18
|
+
print(f"(a) Probability of waiting : {prob_wait:.2f} (30%)")
|
|
19
|
+
print(f"(b) Avg non-empty queue length : {avg_non_empty:.2f} customers")
|
|
20
|
+
print(f"(c) Required arrival increase : {increase_per_hr:.2f} customers/hour")
|
|
21
|
+
print(f"(d) Fraction of day phone is in use : {busy_fraction:.2f} (30%)")
|
cg_code/om/om_p_3_3.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
D = 10000.0
|
|
4
|
+
Co = 10.0
|
|
5
|
+
price = 20.0
|
|
6
|
+
Ch = 0.20 * price # Rs. 4 per unit/year
|
|
7
|
+
Cb = 0.25 * price # Rs. 5 per unit/year
|
|
8
|
+
|
|
9
|
+
# (a) Optimal lot size with backorders
|
|
10
|
+
Q_opt = math.sqrt((2 * D * Co / Ch) * ((Ch + Cb) / Cb))
|
|
11
|
+
|
|
12
|
+
# (b) Optimal backorder quantity
|
|
13
|
+
S_opt = Q_opt * (Ch / (Ch + Cb))
|
|
14
|
+
|
|
15
|
+
# (c) Maximum inventory level
|
|
16
|
+
I_max = Q_opt - S_opt
|
|
17
|
+
|
|
18
|
+
# (d) Cost comparison & annual savings
|
|
19
|
+
tc_without_bo = math.sqrt(2 * D * Co * Ch)
|
|
20
|
+
tc_with_bo = math.sqrt(2 * D * Co * Ch * (Cb / (Ch + Cb)))
|
|
21
|
+
savings = tc_without_bo - tc_with_bo
|
|
22
|
+
|
|
23
|
+
print(f"(a) Optimum Order Quantity (Q*) : {Q_opt:.2f} units")
|
|
24
|
+
print(f"(b) Optimum Backorder Qty (S*) : {S_opt:.2f} units")
|
|
25
|
+
print(f"(c) Maximum Inventory Level (Imax) : {I_max:.2f} units")
|
|
26
|
+
print(f"(d) Cost without Backorders : Rs. {tc_without_bo:.2f}")
|
|
27
|
+
print(f" Cost with Backorders : Rs. {tc_with_bo:.2f}")
|
|
28
|
+
print(f" Annual Cost Saving : Rs. {savings:.2f} -> Recommend Backordering")
|
cg_code/om/om_p_4_2.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
from scipy.optimize import minimize
|
|
4
|
+
|
|
5
|
+
# Objective: Minimize z = x1^2 + x2^2
|
|
6
|
+
def objective(x):
|
|
7
|
+
return x[0]**2 + x[1]**2
|
|
8
|
+
|
|
9
|
+
# Constraints in scipy 'ineq' format (fun(x) >= 0)
|
|
10
|
+
constraints = [
|
|
11
|
+
{'type': 'ineq', 'fun': lambda x: x[0] + x[1] - 4}, # x1 + x2 >= 4
|
|
12
|
+
{'type': 'ineq', 'fun': lambda x: 2*x[0] + x[1] - 5} # 2*x1 + x2 >= 5
|
|
13
|
+
]
|
|
14
|
+
bounds = [(0, None), (0, None)]
|
|
15
|
+
|
|
16
|
+
res = minimize(objective, [1, 1], method='SLSQP', bounds=bounds, constraints=constraints)
|
|
17
|
+
x1_opt, x2_opt = res.x
|
|
18
|
+
|
|
19
|
+
print("=== OPTIMAL SOLUTION (KUHN-TUCKER / SLSQP) ===")
|
|
20
|
+
print(f"x1* = {x1_opt:.4f}")
|
|
21
|
+
print(f"x2* = {x2_opt:.4f}")
|
|
22
|
+
print(f"Minimum z = {res.fun:.4f}")
|
|
23
|
+
|
|
24
|
+
# Graphical visualization
|
|
25
|
+
x1 = np.linspace(0, 6, 300)
|
|
26
|
+
y1 = 4 - x1 # x1 + x2 = 4
|
|
27
|
+
y2 = 5 - 2 * x1 # 2*x1 + x2 = 5
|
|
28
|
+
|
|
29
|
+
plt.figure(figsize=(7, 6))
|
|
30
|
+
plt.plot(x1, y1, 'b-', label='x1 + x2 = 4')
|
|
31
|
+
plt.plot(x1, y2, 'g-', label='2x1 + x2 = 5')
|
|
32
|
+
|
|
33
|
+
# Shade feasible region (above both lines)
|
|
34
|
+
y_lower = np.maximum(np.maximum(y1, y2), 0)
|
|
35
|
+
plt.fill_between(x1, y_lower, 6, color='lightgreen', alpha=0.4, label='Feasible Region')
|
|
36
|
+
|
|
37
|
+
# Plot objective circle z = 8 (radius = sqrt(8))
|
|
38
|
+
theta = np.linspace(0, np.pi/2, 200)
|
|
39
|
+
r = np.sqrt(res.fun)
|
|
40
|
+
plt.plot(r * np.cos(theta), r * np.sin(theta), 'r--', label='Objective Circle: x1^2 + x2^2 = 8')
|
|
41
|
+
|
|
42
|
+
plt.scatter([x1_opt], [x2_opt], color='red', s=90, zorder=5, label=f'Optimum ({x1_opt:.1f}, {x2_opt:.1f})')
|
|
43
|
+
plt.xlim(0, 6)
|
|
44
|
+
plt.ylim(0, 6)
|
|
45
|
+
plt.xlabel('x1')
|
|
46
|
+
plt.ylabel('x2')
|
|
47
|
+
plt.title('Graphical Verification: Min z = x1^2 + x2^2')
|
|
48
|
+
plt.grid(True, linestyle=':')
|
|
49
|
+
plt.legend()
|
|
50
|
+
plt.tight_layout()
|
|
51
|
+
plt.show()
|