-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassignment0.py
107 lines (90 loc) · 2.28 KB
/
assignment0.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
class ModelPredictiveControl:
def __init__(self):
self.horizon = 40
def plant_model(self, u, prev_temp):
knob_angle = u
# Knob angle to temperature
knob_temp = knob_angle * 0.5
# Calculate dT or change in temperature.
tau = 6
dT = 0
# new temp = current temp + change in temp.
return prev_temp + dT
def cost_function(self, u):
cost = 0.0
temp = 0.0
for i in range(0, self.horizon):
temp = self.plant_model(u[i], temp)
return cost
mpc = ModelPredictiveControl()
# Set bounds.
bounds = []
for i in range(mpc.horizon):
bounds += [[0, 180]]
# Create Inputs to be filled.
u = np.ones(mpc.horizon)
# Non-linear optimization.
u_solution = minimize(mpc.cost_function,
x0=u,
method='SLSQP',
bounds=bounds,
tol = 1e-8)
# --------------------------
# Calculate data for Plot 1.
knob_angle_list = []
water_temp_list = []
t_list = []
knob_angle = 80
water_temp = 0.0
for t in range(40):
t_list += [t]
knob_angle_list += [knob_angle]
water_temp_list += [water_temp]
water_temp = mpc.plant_model(knob_angle, water_temp)
# Create Plot 1 - Constant Input
# Subplot 1
plt.figure(figsize=(8,8))
plt.subplot(211)
plt.title("Constant Input")
plt.ylabel("Knob Angle")
# Enter Data
plt.plot(t_list, knob_angle_list, 'k')
plt.ylim(0,180)
# Subplot 2
plt.subplot(212)
plt.ylabel("Water Temp")
# Enter Data
plt.plot(t_list, water_temp_list, 'ro')
plt.ylim(0,50)
plt.show()
# --------------------------
# Calculate data for Plot 2.
knob_angle_list = []
water_temp_list = []
t_list = []
water_temp = 0.0
for t in range(40):
t_list += [t]
knob_angle = u_solution.x[t]
knob_angle_list += [knob_angle]
water_temp_list += [water_temp]
water_temp = mpc.plant_model(knob_angle, water_temp)
# Plot 2 - MPC
# Subplot 1
plt.figure(figsize=(8,8))
plt.subplot(211)
plt.title("MPC")
plt.ylabel("Knob Angle")
# Enter data
plt.plot(t_list, knob_angle_list, 'k')
plt.ylim(0,180)
# Subplot 2
plt.subplot(212)
plt.ylabel("Water Temp")
# Enter data
plt.plot(t_list, water_temp_list, 'ro')
plt.ylim(0,50)
plt.show()