-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWoodberry_Distillation.py
584 lines (406 loc) · 16.3 KB
/
Woodberry_Distillation.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
"""
Wood-Berry Distillation Column Simulation
By: Rui Nian
Date of Last Edit: March 7th, 2019
The MIT License (MIT)
Copyright © 2019 Rui Nian
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above
copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import random
from copy import deepcopy
from scipy.integrate import odeint
import gc
import warnings
import sys
gc.enable()
sns.set()
sns.set_style('white')
class WoodBerryDistillation:
"""
Attributes
-----
Nsim: Length of simulation
x0: Initial conditions for states, x ~ X
u0: Initial conditions for inputs, u ~ U
xs: Optimal steady state states, x_s
us: Optimal steady state inputs, u_s
step_size: Size of each step for integration purposes, 1 represents 1 second in simulation time
y: Outputs of the system at different time steps, [X_D, X_B, Water_D, Water, B]
x: States of the system at different time steps
u: Inputs to the system at different time steps
A: System matrix
B: Input matrix
C: Output matrix
D: Feedforward matrix
timestep: Sequential time steps for the whole simulation
setpoint: System set-point change
action_list: RL set-points
time_list: Corresponds to the changes RL created
Methods
-----
ode: Ordinary differential equations of the system. Contains 4 states and 2 inputs
step: Simulates one step of the simulation using odeint from Scipy
reset: Reset current simulation
"""
# Plotting formats
fonts = {"family": "serif",
"weight": "normal",
"size": "12"}
plt.rc('font', **fonts)
plt.rc('text', usetex=True)
# Random Seeding
random.seed(1)
np.random.seed(1)
def __repr__(self):
return "WoodBerryDistillation({}, {}, {})".format(self.nsim, self.x0, self.u0)
def __str__(self):
return "Wood-Berry distillation simulation object."
def __init__(self, nsim, x0, u0, xs=np.array([2.6219, 1.7129, 1.113, 0.7632]), us=np.array([15.7, 5.337]),
step_size=1):
self.Nsim = nsim
self.x0 = x0
self.u0 = u0
self.xs = xs
self.us = us
self.step_size = step_size
# State space model
self.A = np.array([[-0.0599, 0, 0, 0], [0, -0.0917, 0, 0], [0, 0, -0.0476, 0], [0, 0, 0, -0.0694]])
self.B = np.array([[1, 0], [1, 0], [0, 1], [0, 1]])
self.C = np.array([[0.7665, 0, -0.9, 0], [0, 0.6055, 0, -1.3472]])
self.D = 0
# Output, state, and input trajectories
self.y = np.zeros((nsim + 1, 2))
self.x = np.zeros((nsim + 1, 4))
self.u = np.zeros((nsim + 1, 2))
# Populate the initial states
self.x[:] = x0
self.u[:] = u0
self.y[:, 0] = self.C[0, 0] * self.x[0, 0] + self.C[0, 2] * self.x[0, 2]
self.y[:, 1] = self.C[1, 1] * self.x[0, 1] + self.C[1, 3] * self.x[0, 3]
# Timeline of simulation
self.timestep = np.linspace(0, self.Nsim * self.step_size, self.Nsim + 1)
# Setpoint changes
self.set_point = np.zeros(nsim + 1)
# RL Set-points
self.action_list = []
self.time_list = []
def ode(self, state, t, inputs):
"""
Description
-----
MIMO state space model of the Wood-Berry Distillation Tower. Contains 4 states and 2 actions. The dxdts
may be able to be optimized through dot product?
Inputs
-----
state: States of the system at time t - 1. Current states has no physical meaning. [x1, x2, x3, x4]
t: Limits of integration for sp.odeint. [t - 1, t]
inputs: Control inputs into the ordinary differential equations. [u1, u2]
Returns
-----
dxdt: All the equations of the state space model
"""
x1 = state[0]
x2 = state[1]
x3 = state[2]
x4 = state[3]
u11 = inputs[0]
u12 = inputs[1]
u21 = inputs[2]
u22 = inputs[3]
dxdt1 = self.A[0, 0] * x1 + self.B[0, 0] * u11
dxdt2 = self.A[1, 1] * x2 + self.B[1, 0] * u12
dxdt3 = self.A[2, 2] * x3 + self.B[2, 1] * u21
dxdt4 = self.A[3, 3] * x4 + self.B[3, 1] * u22
dxdt = [dxdt1, dxdt2, dxdt3, dxdt4]
return dxdt
def step(self, inputs, time, setpoint, noise=False, economics='distillate', w_y1=0.8, w_y2=0.2):
"""
Description
-----
Inputs
-----
Returns
-----
"""
self.set_point[time] = setpoint
# Account for delay of the models
delay_u = np.array([self.u[time - 1, 0], self.u[time - 7, 0], self.u[time - 3, 1], self.u[time - 3, 1]])
# Integrate the states to calculate for the next states
x_next = odeint(self.ode, self.x[time - 1], [self.timestep[time - 1], self.timestep[time]], args=(delay_u, ))
# odeint outputs the current time and the last time's x, so x_next[-1] is taken.
# State, input, and output trajectories
self.x[time, :] = x_next[-1]
self.u[time, :] = inputs[0]
if noise:
self.y[time, 0] = self.C[0, 0] * self.x[time, 0] + self.C[0, 2] * self.x[time, 2] + np.random.normal(0, 0.2)
self.y[time, 1] = self.C[1, 1] * self.x[time, 1] + self.C[1, 3] * self.x[time, 3] + np.random.normal(0, 0.2)
else:
self.y[time, 0] = self.C[0, 0] * self.x[time, 0] + self.C[0, 2] * self.x[time, 2]
self.y[time, 1] = self.C[1, 1] * self.x[time, 1] + self.C[1, 3] * self.x[time, 3]
# Ensure compositions are always between 0 and 100
# for i, comp in enumerate(self.y[time, :]):
# if comp > 100:
# self.y[time, i] = 100
# elif comp < 0:
# self.y[time, i] = 0
# else:
# pass
new_state = deepcopy(self.y[time, :])
if time == (self.Nsim - 1):
done = True
else:
done = False
if len(self.action_list) < 2:
# If its the first action, no penalty on input
reward = self.reward_calculator(setpoint, time, economics=economics)
else:
# Penalty on input
reward = self.reward_calculator(setpoint, time, d_input=np.abs(self.action_list[-1] - self.action_list[-2]),
economics=economics, w_y1=w_y1, w_y2=w_y2)
info = "placeholder"
return new_state, reward, done, info
def reward_calculator(self, setpoint, time, economics='distillate', d_input=0, w_y1=0.8, w_y2=0.2):
"""
Description
-----
Inputs
-----
d_input: Change in input
Returns
-----
"""
if economics == 'distillate':
error_y1 = abs(self.y[time, 0] - setpoint)
reward = -error_y1
elif economics == 'bottoms':
error_y2 = abs(self.y[time, 1] - setpoint)
reward = -error_y2
elif economics == 'all':
error_y1 = np.square(abs(self.y[time, 0] - setpoint[0]))
error_y2 = np.square(abs(self.y[time, 1] - setpoint[1]))
reward = -(error_y1 + error_y2) - d_input
elif economics == 'mixed':
assert(w_y1 + w_y2 == 1)
error_y1 = w_y1 * np.square(abs(self.y[time, 0] - setpoint[0]))
error_y2 = w_y2 * np.square(abs(self.y[time, 1] - setpoint[1]))
# Tracking error + change in input cost
reward = -(error_y1 + error_y2) - (abs(d_input) * 5)
else:
raise ValueError('Improper type selected')
return reward
def actuator_fault(self, actuator_num, actuator_value, time, noise=False):
"""
Description
-----
Inputs
-----
Returns
-----
"""
# If actuator 1 is selected
if actuator_num == 1:
self.u[time - 1, 0] = actuator_value
# If noise is enabled for actuator 1
if noise:
self.u[time - 1, 0] += np.random.normal(0, 0.3)
# If actuator 2 is selected
if actuator_num == 2:
self.u[time - 1, 1] = actuator_value
# If noise is enabled for actuator 2
if noise:
self.u[time - 1, 1] += np.random.normal(0, 0.3)
def sensor_fault(self, sensor_num, sensor_value):
"""
Description
-----
Currently a dummy placeholder
Inputs
-----
Returns
-----
"""
if sensor_num == 1:
self.u = self.u
pass
if sensor_num == 2:
pass
return sensor_value
def reset(self, rand_init=False):
"""
Description
-----
Inputs
-----
Returns
-----
"""
# Output, state, and input trajectories
self.y = np.zeros((self.Nsim + 1, 2))
self.x = np.zeros((self.Nsim + 1, 4))
self.u = np.zeros((self.Nsim + 1, 2))
# Populate the initial states, if rand_init, add white noise sampled from uniform distribution.
if rand_init:
self.x[:] = self.x0 + np.random.uniform(-20, 20, size=(1, 2))
self.u[:] = self.u0 + np.random.uniform(-3, 3, size=(1, 2))
else:
self.x[:] = self.x0
self.u[:] = self.u0
self.y[:, 0] = self.C[0, 0] * self.x[0, 0]
self.y[:, 1] = self.C[1, 1] * self.x[0, 1]
# Setpoint changes
self.set_point = np.zeros((self.Nsim + 1, 2))
def plots(self, timestart=50, timestop=550):
"""
Description
-----
Plots the %MeOH in the distillate and bottoms as a function of time.
Inputs
-----
timestart: What time (in simulation time) to start plotting
timestop: What time (in simulation time) to stop plotting
"""
plt.plot(self.timestep[timestart:timestop], self.y[timestart:timestop, 0], label='$X_D$')
plt.plot(self.timestep[timestart:timestop], self.y[timestart:timestop, 1], label='$X_B$')
plt.xlabel(r'Time, \textit{t} (min)')
plt.ylabel(r'\%MeOH, \textit{X} (wt. \%)')
plt.legend(loc=0, prop={'size': 12}, frameon=False)
plt.show()
def cost_function(self, output='distillate', error_type='ISE', dead_period=15):
"""
Description
-----
Inputs
-----
error:
dead_period:
Returns
-----
error:
"""
error = 0
# Integral of absolute error evaluation
if error_type == "IAE":
if output == 'distillate':
error = abs(self.y[dead_period:, 0].reshape(-1, 1) - self.set_point[dead_period:])
error = sum(error) / (self.Nsim - dead_period)
elif output == 'bottoms':
error = abs(self.y[dead_period:, 1].reshape(-1, 1) - self.set_point[dead_period:])
error = sum(error) / (self.Nsim - dead_period)
# Integral of squared error evaluation
elif error_type == "ISE":
if output == 'distillate':
error = np.power(self.y[dead_period:, 0].reshape(-1, 1) - self.set_point[dead_period:], 2)
error = sum(error) / (self.Nsim - dead_period)
elif output == 'bottoms':
error = np.power(self.y[dead_period:, 1].reshape(-1, 1) - self.set_point[dead_period:], 2)
error = sum(error) / (self.Nsim - dead_period)
else:
raise ValueError('Improper error evaluation selected.')
return error
class DiscretePIDControl:
"""
"""
def __repr__(self):
return "DiscretePIDControl({}, {}, {})".format(self.Kp, self.Ki, self.Kd)
def __str__(self):
return "Discrete-Time PID Controller"
def __init__(self, kp, ki, kd):
"""
Descriptions
-----
Class for a discrete Proportional-Integral-Derivative Controller.
Original form: du = Kp * (ek - ek_1) + Kp * h / Ti * ek + Kp * Td / h * (ek - 2 * ek_1 + ek_2)
Modifications: Ki = Kp * h / Ti
Kd = Kp ( Td / h)
New form: du = Kp * (ek - ek_1) + Ki * ek + Kd * (ek - 2 * ek_1 + ek_2)
Attributes
-----
kp: Controller proportional gain
ki: Controller integral gain
kd: Controller derivative gain
"""
# Controller parameters
self.Kp = kp
self.Ki = ki
self.Kd = kd
# Controls from the digital controller
self.u = []
self.error = []
def __call__(self, setpoint, x_cur, x_1, x_2, eval_time=4):
"""
Description
-----
Inputs
-----
Returns
-----
"""
ek = setpoint - x_cur
ek_1 = setpoint - x_1
ek_2 = setpoint - x_2
self.error.append(ek)
du = self.Kp * (ek - ek_1) + self.Ki * ek + self.Kd * (ek - 2 * ek_1 + ek_2)
# Constraints on output of PID
# control_action = max(0, min(last_u + du, 20))
control_action = self.u[-1] + du
# Used to synchronize PID inputs with plant outputs if plant and PID are evaluated at different time periods
for _ in range(eval_time):
self.u.append(control_action)
return control_action
def reset(self):
"""
Description
-----
Resets the PID input trajectory.
"""
self.u = []
if __name__ == "__main__":
# Build PID Objects
PID1 = DiscretePIDControl(kp=1.31, ki=0.21, kd=0)
PID2 = DiscretePIDControl(kp=-0.28, ki=-0.06, kd=0)
# Set initial conditions
PID1.u = [3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9]
PID2.u = [0, 0, 0, 0, 0, 0, 0, 0]
init_state = np.array([65.13, 42.55, 0.0, 0.0])
init_input = np.array([3.9, 0.0])
env = WoodBerryDistillation(nsim=2000, x0=init_state, u0=init_input)
# Starting at time 7 because the largest delay is 7
input_1 = env.u[0, 0]
input_2 = env.u[0, 1]
set_point1 = 100
set_point2 = 0
episodes = 1
for episode in range(episodes):
# Resetting environment and PID controllers, add terms to overcome time delay
env.reset(rand_init=False)
PID1.u = [3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9]
PID2.u = [0, 0, 0, 0, 0, 0, 0, 0]
input_1 = env.u[0, 0]
input_2 = env.u[0, 1]
for t in range(7, env.Nsim + 1):
if t % 4 == 0:
# input_1 = PID1(set_point1, env.y[t - 1, 0], env.y[t - 2, 0], env.y[t - 3, 0])
# input_2 = PID2(set_point2, env.y[t - 1, 1], env.y[t - 2, 1], env.y[t - 3, 1])
input_1 = 15.7
input_2 = 5.337
control_input = np.array([[input_1, input_2]])
# Set-point change
# if t == 350:
# set_point1 = 90
# set_point2 = 10
# Disturbance
# if 1400 < t < 1450:
# env.x[t - 1, :] = env.x[t - 1, :] + np.random.normal(0, 0.7, size=(1, 4))
# Actuator Faults
# if 1000 < t:
# env.actuator_fault(actuator_num=1, actuator_value=9, time=t, noise=False)
# Simulate next time
next_state, Reward, Done, Info = env.step(control_input, t, setpoint=[set_point1, set_point2], noise=False)
env.plots(timestart=0, timestop=2000)