#program to plot pv diagram for otto cycle and thermal efficiency of the cycle
import math
import matplotlib.pyplot as plt
def engine_kinematics(bore, stroke, con_rod, cr, crank_start,crank_end):
#inputs
bore = 0.1
stroke = 0.1
con_rod = 0.15
cr = 12
#crank pin radius
a = stroke /2
R = con_rod / a
# volume trace
v_s = math.pi* (1/4) * pow(bore,2) * stroke
v_c = v_s/(cr-1)
n_theta = 50
sc = math.radians(crank_start)
ec = math.radians(crank_end)
dtheta = (ec - sc)/(n_theta -1)
v = []
for i in range(0,n_theta):
theta = sc + i * dtheta
term1 = 0.5 *(cr-1)
term2 = R + 1 - math.cos(theta)
term3 = pow(R,2) - pow(math.sin(theta),2)
term3 = pow(term3,0.5)
v.append((1 + term1 * (term2 - term3)) * v_c)
return v
# inputs
p1 = 100.325
t1 = 500
gamma = 1.4
t3 = 2300
#geometric parameters
bore = 0.1
stroke = 0.1
con_rod = 0.15
cr = 12
#volume calculations
v_s = math.pi/4 * pow(bore,2) * stroke
v_c = v_s/(cr - 1)
v1 = v_s + v_c
#state 2
v2 = v_c
p2 = p1 * pow(v1,gamma)/pow(v2,gamma)
rhs = (p1 * v1)/t1
t2 = (p2 * v2)/rhs
constant = p1 * pow(v1,gamma)
v_compression = engine_kinematics(bore,stroke,con_rod,cr,180,0)
p_compression = []
for v in v_compression:
p_compression.append(constant/pow(v,gamma))
#state 3
v3 = v2
p3 = p2 * (t3/t2)
constant = p3 * pow(v3,gamma)
v_expansion = engine_kinematics(bore,stroke,con_rod,cr,0,180)
p_expansion = []
for v in v_expansion:
p_expansion.append(constant/pow(v,gamma))
#state 4
v4 = v1
rhs = p3 * v3/t3
p4 = p3 * pow(v3,gamma)/pow(v4,gamma)
t4 = p4 * v4/rhs
#thermal efficiency
te = (1 -(1/pow(cr,gamma - 1))) * 100
print(f'the thermal efficiency of the engine is: {te} %')
plt.plot([v2,v3],[p2,p3])
plt.plot(v_compression,p_compression)
plt.plot(v_expansion,p_expansion)
plt.plot([v4,v1],[p4,p1])
plt.xlabel('Volume')
plt.ylabel('pressure')
plt.show()