-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice_control.rb
320 lines (271 loc) · 8.61 KB
/
device_control.rb
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
module DeviceControl
# There is a pattern for how both Controllers (e.g. thermostat) and Devices
# (e.g. heater) operate.
# They each have an _input_ varying over time which determines the _output_.
# A thermostat (Controller) listens for temperature and tells the heater how
# high to turn it up (or just on / off). A heater (Device) listens to its
# control knob and yields heat as an output.
#
# We capture this pattern with a single method: _update_. It accepts the
# latest input and provides an _output_ based on the input. When the input
# is read in, perhaps some internal state is changed on
# the processor which will affect the _output_.
#
# Any class which mixes in Updateable can define its own _input=_ method,
# which may update any ivars. Any such class must define an _output_ method.
#
module Updateable
def update(val)
self.input = val
self.output
end
end
# A Device is like a heater. It has a control knob, maybe on/off or perhaps
# a variable control. Its output (maybe on/off) depends on the control knob.
class Device
include Updateable
attr_reader :knob
def initialize
@knob = 0.0
end
def input=(val)
@knob = val.to_f
end
alias_method :knob=, :input=
def output
@knob # do nothing by default
end
def to_s
format("Knob: %.3f\tOutput: %.3f", @knob, self.output)
end
end
# Alright, fine, let's make a Heater
# Input is the control knob (turned far enough to on, else off)
# Output is watts
class Heater < Device
# convert electricity into thermal output
EFFICIENCY = 0.999
attr_reader :watts
def initialize(watts, threshold: 0)
super()
@watts = watts
@threshold = threshold
end
# output is all or none
def output
@knob > @threshold ? (@watts * self.class::EFFICIENCY) : 0
end
def to_s
format("Power: %d W\tKnob: %.1f\tThermal: %.1f W",
@watts, @knob, self.output)
end
end
class Cooler < Heater
# not nearly as efficient as a heater at turning electrons into therms
EFFICIENCY = 0.35
end
# A Controller is like a thermostat. It has a setpoint, and it reads a
# measurement from the environment, and it adjusts its output to try to make
# the measurement match the setpoint.
class Controller
include Updateable
attr_reader :measure
attr_accessor :setpoint
def initialize(setpoint)
@setpoint, @measure = setpoint, 0.0
end
def input=(val)
@measure = val.to_f
end
alias_method :measure=, :input=
# just output the error
def output
@setpoint - @measure
end
def to_s
format("Setpoint: %.3f\tMeasure: %.3f", @setpoint, @measure)
end
end
class Thermostat < Controller
# true or false; can drive a Heater or a Cooler
# true means input below setpoint; false otherwise
def output
@setpoint - @measure > 0
end
end
# now consider e.g.
# h = Heater.new(1000)
# ht = Thermostat.new(20)
# c = Cooler.new(1000)
# ct = Thermostat.new(25)
# temp = 26.4
# heat_knob = ht.update(temp) ? 1 : 0
# heating_watts = h.update(heat_knob)
# cool_knob = ct.update(temp) ? 0 : 1
# cooling_watts = c.update(cool_knob)
# etc
class Flexstat < Thermostat
def self.cold_val(hot_val)
case hot_val
when true, false
!hot_val
when 0,1
hot_val == 0 ? 1 : 0
when Numeric
0
when :on, :off
hot_val == :on ? :off : :on
else
raise "#{hot_val.inspect} not recognized"
end
end
attr_reader :cold_val, :hot_val
def initialize(setpoint, hot_val: false, cold_val: nil)
super(setpoint)
@hot_val = hot_val
@cold_val = cold_val.nil? ? self.class.cold_val(hot_val) : cold_val
end
def output
super ? @cold_val : @hot_val
end
end
# A PIDController is a Controller that tracks its error over time
# in order to calculate:
# Proportion (current error)
# Integral (accumulated error)
# Derivative (error slope, last_error)
# The sum of these terms is the output
#
class PIDController < Controller
HZ = 1000
TICK = Rational(1) / HZ
# Ziegler-Nichols method for tuning PID gain knobs
# https://en.wikipedia.org/wiki/Ziegler%E2%80%93Nichols_method
ZN = {
# Kp Ti Td Ki Kd
# Var: Ku Tu Tu Ku/Tu Ku*Tu
'P' => [1/2r],
'PI' => [9/20r, 4/5r, nil, 27/50r],
'PD' => [ 4/5r, nil, 1/8r, nil, 1/10r],
'PID' => [ 3/5r, 1/2r, 1/8r, 6/5r, 3/40r],
'PIR' => [7/10r, 2/5r, 3/20r, 7/4r, 21/200r],
# less overshoot than standard PID
'some' => [ 1/3r, 1/2r, 1/3r, 2/3r, 1/11r],
'none' => [ 1/5r, 1/2r, 1/3r, 2/5r, 2/30r],
}
# _ku_ = ultimate gain, _tu_ = oscillation period
# output includes ti and td, which are not necessary
# typically kp, ki, and kd are used
def self.tune(type, ku, tu)
record = ZN[type.downcase] || ZN[type.upcase] || ZN.fetch(type)
kp, ti, td, ki, kd = *record
kp *= ku if kp
ti *= tu if ti
td *= tu if td
ki *= (ku / tu) if ki
kd *= (ku * tu) if kd
{ kp: kp, ti: ti, td: td, ki: ki, kd: kd }
end
attr_accessor :dt, :low_pass_ticks,
:error, :last_error, :sum_error,
:kp, :ki, :kd,
:p_range, :i_range, :d_range, :o_range, :e_range
attr_reader :mavg
def initialize(setpoint, dt: TICK, low_pass_ticks: 0)
super(setpoint)
@dt = dt
@error, @last_error, @sum_error = 0.0, 0.0, 0.0
if low_pass_ticks > 0
@mavg = MovingAverage.new(low_pass_ticks)
else
@mavg = nil
end
# gain / multipliers for PID; tunables
@kp, @ki, @kd = 1.0, 1.0, 1.0
# optional clamps for PID terms and output
@p_range = (-Float::INFINITY..Float::INFINITY)
@i_range = (-Float::INFINITY..Float::INFINITY)
@d_range = (-Float::INFINITY..Float::INFINITY)
@o_range = (-Float::INFINITY..Float::INFINITY)
@e_range = (-Float::INFINITY..Float::INFINITY)
yield self if block_given?
end
# update @error, @last_error, and @sum_error
def input=(val)
@measure = val
@last_error = @error
@error = @setpoint - @measure
# Incorporate @ki here for better behavior when @ki is updated
# It's a good idea to clamp the accumulated error so that if we start
# way under setpoint, we don't accumulate so much error that we spend
# too much time overshooting to counteract it
@sum_error =
(@sum_error + @ki * @error * @dt).clamp(@e_range.begin, @e_range.end)
# update mavg here to ensure only one update per PID input
@mavg.input = self.derivative if @mavg
end
def output
drv = @mavg ? @mavg.output : self.derivative
(self.proportion +
self.integral +
drv).clamp(@o_range.begin, @o_range.end)
end
def proportion
(@kp * @error).clamp(@p_range.begin, @p_range.end)
end
# It may seem funny to clamp both @sum_error and the integral term, but
# we may want different values for these clamps. @e_range is just to
# make sure we don't create a mountain to chew through. @i_range gives
# additional flexibility for balancing P I & D
def integral
@sum_error.clamp(@i_range.begin, @i_range.end)
end
def derivative
(@kd * (@error - @last_error) / @dt).clamp(@d_range.begin, @d_range.end)
end
def to_s
[super,
format("Error: %+.3f\tLast: %+.3f\tSum: %+.3f",
@error, @last_error, @sum_error),
format(" Gain:\t%.3f\t%.3f\t%.3f",
@kp, @ki, @kd),
format(" PID:\t%+.3f\t%+.3f\t%+.3f\t= %.5f",
self.proportion, self.integral, self.derivative, self.output),
].join("\n")
end
end
class MovingAverage
include Updateable
attr_reader :size, :idx, :storage
def initialize(size = 2)
@size = size
@idx = 0
@storage = Array.new(@size, 0)
end
# never grow @storage; just use modmath to track what to replace
def input=(val)
@storage[@idx % @size] = val
@idx += 1
end
def output
return 0 if @idx == 0
@storage.sum / (@idx > @size ? @size : @idx).to_f
end
end
class RateLimiter
include Updateable
attr_accessor :val
def initialize(max_step, val: 0)
@max_step = max_step
@val = val
end
# never allow @val to grow / shrink more than @max_step
def input=(val)
diff = val - @val
@val += diff.clamp(-1 * @max_step, @max_step)
end
def output
@val
end
end
end