-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtasks.py
More file actions
368 lines (294 loc) · 13.3 KB
/
Copy pathtasks.py
File metadata and controls
368 lines (294 loc) · 13.3 KB
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
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 11:24:33 2018
@author: joan-fss
"""
#%%
from time import sleep, monotonic
from pyInstruments.instruments import keysight34461A, agilentE36XXA # This the module I created
from pyInstruments.pid import Pid
import datetime
from numpy import sqrt, isclose, nan
from threading import Lock
today = datetime.date.today().strftime("%d%m%Y")
from pathlib import Path
from pyInstruments import __file__ as module_folder
tempfile = Path(module_folder).parent / Path('temp/temp.dat')
def calc_temperature(R, R0 = 100.0, alpha = 3.9083e-3, beta = -5.7750e-7):
"""Returns the temperature in °C according to the Standard Class B Pt100/1000, default is Pt100"""
return (-alpha + sqrt(alpha**2-4 * beta * (1-R / R0))) / 2 / beta
#%%
class TemperatureController(object):
def __init__(self):
"""
Initializes the pid.
"""
# Initialize some variables
self.setpoint = nan
self.current_T = nan
# Creates a lock class to block the access to the temperature writing
self.lock = Lock()
# Files to store and read the setpoint and Treal
self.log_file = tempfile
self.heating_ramp = 20 # limit the heating in K/min
self.cooling_ramp = 60 # Limits the cooling K/min
def configurate(self, setpoint = 20.0, heating = True, max_poutput = 12.00,\
multimeter_addr = 'GPIB0::23::INSTR',\
sourcemeter_addr = 'GPIB0::5::INSTR',\
R0 = 100 ):
"""
Configures the pid
Parameters
----------
setpoint : float, optional
Setpoint in °C. The default is 20.0.
heating : bool, optional
Whether to heat or to cool, important for the Peltier polarity and pid action calculation. The default is True.
max_poutput : float, optional
Max. action allowed from the pid, in this case, in Volts. The default is 12.
multimeter_addr : str, optional
Adress of the multimeter, which reads the temperature. The default is 'GPIB0::23::INSTR'.
sourcemeter_addr : TYPE, optional
Adress of the power supply, which powers the heating/cooling element. The default is 'GPIB0::5::INSTR'.
R0 : int, optional
The R0 pf the RTD sensor used, typically either 100 or 1000. The default is 100.
Returns
-------
None.
"""
# Initialize the properties of the class
self.setpoint = setpoint
self.heating = heating
self.pid_running = False
self.max_poutput = max_poutput
self.R0 = R0
# Configuration of the sourcemeter and measurement devices
self.mult = keysight34461A(multimeter_addr)
self.supply = agilentE36XXA(sourcemeter_addr)
if R0 == 100:
# Range to read a Pt100
self.mult.config_ohms(rang = 1000, nplc = 1, count = 5)
else:
# Range to read a Pt1000
self.mult.config_ohms(rang = 10000, nplc = 1, count = 5)
terminal = 'default'
if heating:
# terminal = 'P25V'
self.pmin = 0.0
self.pmax = self.max_poutput
else:
# terminal = 'N25V'
self.pmin = -1.0 * self.max_poutput
self.pmax = 0.0
self.supply.config_volt(0.0, output = terminal)
def run(self, sleeping_time = 0.5):
"""
Starts the temperature control.
Parameters
----------
sleeping_time : float, optional
Time interval in which teh pid algorithm is fed. The default is 0.5.
Returns
-------
None.
"""
# PID setup (parameters for Peltier and working well and tested for dt = 0.25 to 1 s)
Kp = 1.0
Ki = 0.05
Kd = 0.0
pid = Pid(Kp,Ki,Kd, ulimit = self.pmax, llimit = self.pmin)
pid.clear() # Not really necessary now, but it is a good practice. It resets all the values of the pid.
# Read and write the current temperature
self.current_T = calc_temperature(self.mult.read(), self.R0).mean(axis = 0)
pid.set_setpoint(self.current_T) # Initialize the setpoint to a the current temperature
while self.pid_running:
try:
time1 = monotonic()
# Turn the Power supply on OBS! i CAN DELETED THAT ONE, i THINK, DOUBLE CHECK
if not self.supply.outpstate():
print('INFO: Turning on the Power supply')
self.supply.outpon()
if self.heating:
pid.ulimit = self.max_poutput
else:
pid.llimit = -1.0 * self.max_poutput
T = calc_temperature(self.mult.read(), self.R0).mean(axis = 0)
# Update the action value to steadily reach the setpoint based on how close is from the final value
if self.heating:
if isclose(T, self.setpoint, 0, 0.5) or (T >= self.setpoint + 0.5):
# If it is already close to the final setpoint, no need to do the ramp
action = pid.update(T, self.setpoint)
else:
# If it is far from the final setpoint, increase steadily theat 20 °C/min
action = pid.update(T, pid.setpoint + self.heating_ramp/60.0 * pid.dt)
else:
if isclose(T, self.setpoint, 0, 0.5) or (T <= self.setpoint - 0.5):
action = pid.update(T, self.setpoint)
else:
action = pid.update(T, pid.setpoint - self.cooling_ramp/60.0*pid.dt)
action = abs(action)
self.supply.set_volt(action)
self.current_T = T
self.current_action = action
self.current_voltage = action
self.current_intensity = self.supply.read_value(value = 'curr')
with self.lock:
with open(self.log_file, 'w') as f:
f.write(f'{T:5.2f}')
# Check the pid status
while (monotonic() - time1) < sleeping_time:
sleep(0.01)
except KeyboardInterrupt:
print('INFO: Pid program interrupted in a safe way\n')
break
except Exception as e:
# In case of ANY error turn off the source anyway and stop the program while printing the error
print(e)
break
pid.clear()
self.supply.set_volt(0.0)
self.supply.outpoff()
return None
def pid_on(self):
"""
Sets the pid to the on status.
"""
self.pid_running = True
def pid_off(self):
"""
Sets the pid to the off status.
"""
self.pid_running = False
with self.lock:
with open(self.log_file,'w') as f:
f.write('nan')
def set_setpoint(self, value, min_value = -20, max_value = 100):
"""
Re-sets the setpoint of the pid task, considering the min and max value.
Parameters
----------
value : float
Setpoint in Celsius degrees.
min_value : TYPE, optional
Min value of the temperature allowed in °C. The default is -20.
max_value : TYPE, optional
Max value of the temperature allowed in °C. The default is 100.
"""
if value > max_value:
value = max_value
print(f'INFO: Temperature beyong the established limits of {min_value:.2f} and {max_value:.2f} °C\n')
elif value < min_value:
value = min_value
print(f'INFO: Temperature beyong the established limits of {min_value:.2f} and {max_value:.2f} °C\n')
self.setpoint= value
class TemperatureControllerBipolar(object):
def __init__(self):
self.setpoint = nan
self.current_T = nan
self.lock = Lock()
self.log_file = tempfile
self.heating_ramp = 20 # K/min, used when current_T < setpoint
self.cooling_ramp = 60 # K/min, used when current_T > setpoint
# CHANGED: removed `heating` argument -- direction is now decided per-step
# by the sign of (setpoint - T). Added current_limit since both channels
# need explicit limits in bipolar mode.
def configurate(self, setpoint=20.0, max_poutput=6.00, current_limit=1.2,
multimeter_addr='GPIB0::23::INSTR',
sourcemeter_addr='GPIB0::5::INSTR',
R0=100):
"""
Parameters
----------
setpoint : float
Target temperature in °C.
max_poutput : float
Maximum |voltage| applied to the Peltier, in volts. Symmetric.
current_limit : float
Current limit (A) on each ±25V channel. Peltier needs ~1 A.
"""
self.setpoint = setpoint
self.pid_running = False
self.max_poutput = max_poutput
self.R0 = R0
self.mult = keysight34461A(multimeter_addr)
self.supply = agilentE36XXA(sourcemeter_addr)
if R0 == 100:
self.mult.config_ohms(rang=1000, nplc=1, count=5)
else:
self.mult.config_ohms(rang=10000, nplc=1, count=5)
# CHANGED: symmetric limits. No more pmin/pmax tied to a heating flag.
self.pmin = -1.0 * self.max_poutput
self.pmax = +1.0 * self.max_poutput
# CHANGED: bipolar configuration of the supply
self.supply.config_bipolar(voltage=0.0, current_limit_p6v=current_limit,current_limit_p25v=current_limit)
def run(self, sleeping_time=0.5):
Kp = 1.0
Ki = 0.05
Kd = 0.0
pid = Pid(Kp, Ki, Kd, ulimit=self.pmax, llimit=self.pmin)
pid.clear()
self.current_T = calc_temperature(self.mult.read(), self.R0).mean(axis=0)
pid.set_setpoint(self.current_T)
while self.pid_running:
try:
time1 = monotonic()
# CHANGED: use bipolar output-state check / enable
if not self.supply.outpstate_bipolar():
print('INFO: Turning on the Power supply (bipolar)')
self.supply.outpon_bipolar()
# Keep the PID limits in sync with the user-visible max_poutput
pid.ulimit = +1.0 * self.max_poutput
pid.llimit = -1.0 * self.max_poutput
T = calc_temperature(self.mult.read(), self.R0).mean(axis=0)
# CHANGED: ramp direction now dispatched on (setpoint - T),
# not on a global heating/cooling flag. This means the controller
# naturally handles "user changed the setpoint downward mid-run".
error = self.setpoint - T
if isclose(T, self.setpoint, 0, 0.5):
# Close enough -- use the real setpoint
action = pid.update(T, self.setpoint)
elif error > 0:
# Need to heat: ramp the intermediate setpoint upward
action = pid.update(T, pid.setpoint + self.heating_ramp / 60.0 * pid.dt)
else:
# Need to cool: ramp the intermediate setpoint downward
action = pid.update(T, pid.setpoint - self.cooling_ramp / 60.0 * pid.dt)
# CHANGED: signed action goes straight to the supply. No abs().
self.supply.set_volt_bipolar(action)
self.current_T = T
self.current_action = action
self.current_voltage = action # now signed
self.current_intensity = self.supply.read_value_bipolar(value='curr')
with self.lock:
with open(self.log_file, 'w') as f:
f.write(f'{T:5.2f}')
while (monotonic() - time1) < sleeping_time:
sleep(0.01)
except KeyboardInterrupt:
print('INFO: Pid program interrupted in a safe way\n')
break
except Exception as e:
print(e)
break
pid.clear()
# CHANGED: bring both rails to zero, then disable
self.supply.set_volt_bipolar(0.0)
self.supply.outpoff_bipolar()
return None
def pid_on(self):
self.pid_running = True
def pid_off(self):
self.pid_running = False
with self.lock:
with open(self.log_file, 'w') as f:
f.write('nan')
def set_setpoint(self, value, min_value=-20, max_value=100):
if value > max_value:
value = max_value
print(f'INFO: Temperature beyond the established limits of {min_value:.2f} and {max_value:.2f} °C\n')
elif value < min_value:
value = min_value
print(f'INFO: Temperature beyond the established limits of {min_value:.2f} and {max_value:.2f} °C\n')
self.setpoint = value
if __name__ == '__main__':
print('Functions for the pid loaded \n')