regulator.py 22.9 KB
Newer Older
1
2
3
4
# -*- coding: utf-8 -*-
#
# This file is part of the bliss project
#
Benoit Formet's avatar
Benoit Formet committed
5
# Copyright (c) 2015-2020 Beamline Control Unit, ESRF
6
7
8
9
10
11
12
13
14
15
# Distributed under the GNU LGPLv3. See LICENSE for more info.

"""
Controller class

Class to be inherited by regulation controllers

Example of .yml file for a mockup temperature controller
with the mandatory fields:

Valentin Valls's avatar
Valentin Valls committed
16
.. code-block::
17

18
19
    class: Mockup
    module: temperature.mockup
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    host: lid42
    inputs:
        - 
            name: thermo_sample
            channel: A
            unit: deg
        - 
            name: sensor
            channel: B

    outputs: 
        -
            name: heater
            channel: A 
            unit: Volt
35
36
37
            low_limit: 0.0          # <-- minimum device value [unit]
            high_limit: 100.0       # <-- maximum device value [unit]
            ramprate: 0.0           # <-- ramprate to reach the output value [unit/s].
38
39
40
41
42
43
44
45
46

    ctrl_loops:
        -
            name: sample_regulation
            input: $thermo_sample
            output: $heater
            P: 0.5
            I: 0.3
            D: 0.0
47
48
            low_limit: 0.0          # <-- low limit of the PID output value. Usaually equal to 0 or -1.
            high_limit: 1.0         # <-- high limit of the PID output value. Usaually equal to 1.
49
50
51
            frequency: 10.0
            deadband: 0.4
            deadband_time: 1.5
52
            ramprate: 4.0           # <-- ramprate to reach the setpoint value [input_unit/s]
53
54
55
56


"""

57
from gevent import lock
58
from itertools import chain
59
from bliss.common.regulation import Input, Output, Loop
60
from bliss.common.utils import set_custom_members
61
from bliss.common.logtools import log_info
62
63
from bliss.common.protocols import counter_namespace
from bliss.common.utils import autocomplete_property
64
import time
65

66
67
68
from bliss.controllers.bliss_controller import BlissController
from bliss.common.counter import SamplingCounter
from bliss.controllers.counter import SamplingCounterController
69

70
71

class Controller(BlissController):
72
    """
73
        Regulation controller base class
74

75
76
77
78
        The 'Controller' class should be inherited by controller classes that are linked to an hardware 
        which has internal PID regulation functionnalities and optionally ramping functionnalities (on setpoint or output value) .
        
        If controller hardware does not have ramping capabilities, the Loop objects associated to the controller will automatically use a SoftRamp.
79
80
81

    """

82
83
84
85
86
87
88
89
90
91
92
93
94
    class SCC(SamplingCounterController):
        def __init__(self, name, bctrl):
            super().__init__(name)
            self.bctrl = bctrl

        def read_all(self, *counters):
            values = []
            for cnt in counters:
                item = self.bctrl.get_object(cnt.name)
                if item is not None:
                    values.append(item.read())
            return values

95
    def __init__(self, config):
96
97
98
99
        self.__lock = lock.RLock()
        self.__initialized_obj = {}
        self.__hw_controller_initialized = False

100
101
        super().__init__(config)

102
103
    def _get_subitem_default_module(self, class_name, cfg, parent_key):
        return "bliss.common.regulation"
104

105
106
107
    def _get_subitem_default_class_name(self, cfg, parent_key):
        item_classes = {"inputs": "Input", "outputs": "Output", "ctrl_loops": "Loop"}
        return item_classes[parent_key]
108

109
110
111
    def _create_subitem_from_config(
        self, name, cfg, parent_key, item_class, item_obj=None
    ):
112
        item = item_class(self, cfg)
113
        # --- For custom attributes and commands.
114
115
        set_custom_members(self, item, self.init_obj)  # really needed ???????
        return item
116

117
    def _load_config(self):
118
119
        # print("=== _build_counters")
        self._counter_controllers = {}
120
121
122
123
124
        self._counter_controllers["scc"] = self.SCC("scc", self)
        self._counter_controllers["scc"].max_sampling_frequency = self.config.get(
            "max_sampling_frequency", 1
        )

125
126
        # create counters now
        for k in ["inputs", "outputs", "ctrl_loops"]:
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
            for cfg in self.config.get(k, []):
                name = cfg["name"]
                mode = cfg.get("mode", "SINGLE")
                unit = cfg.get("unit")

                self._counter_controllers["scc"].create_counter(
                    SamplingCounter, name, unit=unit, mode=mode
                )

    @autocomplete_property
    def counters(self):
        cnts = [ctrl.counters for ctrl in self._counter_controllers.values()]
        return counter_namespace(chain(*cnts))

    @autocomplete_property
    def axes(self):
        pass

145
146
147
148
149
    def init_obj(self, obj):
        """ Initialize objects under the controller. Called by @lazy_init. """

        with self.__lock:

150
            # ========= INIT HW, DEVICE AND CHILD DEVICE IF ANY =======================
151

152
            if not self.__hw_controller_initialized:
153
                self.initialize_controller()
154
                print("=== initialize_controller", self)
155
                self.__hw_controller_initialized = True
156

157
158
            if self.__initialized_obj.get(obj):
                return
159

160
            if isinstance(obj, Loop):
161

162
                self.__initialized_obj[obj] = True
163

164
165
166
167
                if not self.__initialized_obj.get(obj.input):
                    self.__initialized_obj[obj.input] = True
                    obj.input.load_base_config()
                    self.initialize_input(obj.input)
168
                    print("=== initialize_input", obj.input)
169

170
171
172
173
                if not self.__initialized_obj.get(obj.output):
                    self.__initialized_obj[obj.output] = True
                    obj.output.load_base_config()
                    self.initialize_output(obj.output)
174
                    print("=== initialize_output", obj.output)
175

176
177
                obj.load_base_config()
                self.initialize_loop(obj)
178
                print("=== initialize_loop", obj)
179

180
181
182
183
184
            else:
                self.__initialized_obj[obj] = True
                obj.load_base_config()
                if isinstance(obj, Input):
                    self.initialize_input(obj)
185
                    print("=== initialize_input", obj)
186
187
                elif isinstance(obj, Output):
                    self.initialize_output(obj)
188
                    print("=== initialize_output", obj)
189
190
191
192
193
194
195
196
197
198
199
200

    def get_object(self, name):
        """
        get object by name

        Args:
           name:  name of an object

        Returns:
           the object
        """
        log_info(self, "Controller:get_object: %s" % (name))
201
        return self._get_subitem(name)
202

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    @property
    def inputs(self):
        return self._object_filter(Input)

    @property
    def outputs(self):
        return self._object_filter(Output)

    @property
    def loops(self):
        return self._object_filter(Loop)

    def _object_filter(self, class_type):
        return {
            name: obj
218
            for name, obj in self._subitems.items()
219
220
221
            if isinstance(obj, class_type)
        }

222
    # ------ init methods ------------------------
223

224
    def initialize_controller(self):
225
        """ 
226
        Initializes the controller (including hardware).
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
        """
        pass

    def initialize_input(self, tinput):
        """
        Initializes an Input class type object

        Args:
           tinput:  Input class type object          
        """
        pass

    def initialize_output(self, toutput):
        """
        Initializes an Output class type object

        Args:
           toutput:  Output class type object          
        """
        pass

    def initialize_loop(self, tloop):
        """
        Initializes a Loop class type object

        Args:
           tloop:  Loop class type object          
        """
        pass

257
    # ------ get methods ------------------------
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

    def read_input(self, tinput):
        """
        Reads an Input class type object
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tinput:  Input class type object 

        Returns:
           read value  (in input unit)    
        """
        log_info(self, "Controller:read_input: %s" % (tinput))
        raise NotImplementedError

    def read_output(self, toutput):
        """
        Reads an Output class type object
        Raises NotImplementedError if not defined by inheriting class

        Args:
           toutput:  Output class type object 

        Returns:
           read value (in output unit)         
        """
        log_info(self, "Controller:read_output: %s" % (toutput))
        raise NotImplementedError

    def state_input(self, tinput):
        """
        Return a string representing state of an Input object.
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tinput:  Input class type object

        Returns:
           object state string. This is one of READY/RUNNING/ALARM/FAULT
        """
        log_info(self, "Controller:state_input: %s" % (tinput))
        raise NotImplementedError

    def state_output(self, toutput):
        """
        Return a string representing state of an Output object.
        Raises NotImplementedError if not defined by inheriting class

        Args:
           toutput:  Output class type object

        Returns:
           object state string. This is one of READY/RUNNING/ALARM/FAULT
        """
        log_info(self, "Controller:state_output: %s" % (toutput))
        raise NotImplementedError

315
    # ------ PID methods ------------------------
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

    def set_kp(self, tloop, kp):
        """
        Set the PID P value
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object 
           kp: the kp value
        """
        log_info(self, "Controller:set_kp: %s %s" % (tloop, kp))
        raise NotImplementedError

    def get_kp(self, tloop):
        """
        Get the PID P value
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object 
        
        Returns:
           kp value
        """
        log_info(self, "Controller:get_kp: %s" % (tloop))
        raise NotImplementedError

    def set_ki(self, tloop, ki):
        """
        Set the PID I value
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object 
           ki: the ki value
        """
        log_info(self, "Controller:set_ki: %s %s" % (tloop, ki))
        raise NotImplementedError

    def get_ki(self, tloop):
        """
        Get the PID I value
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object 
        
        Returns:
           ki value
        """
        log_info(self, "Controller:get_ki: %s" % (tloop))
        raise NotImplementedError

    def set_kd(self, tloop, kd):
        """
        Set the PID D value
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object 
           kd: the kd value
        """
        log_info(self, "Controller:set_kd: %s %s" % (tloop, kd))
        raise NotImplementedError

    def get_kd(self, tloop):
        """
        Reads the PID D value
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Output class type object 
        
        Returns:
           kd value
        """
        log_info(self, "Controller:get_kd: %s" % (tloop))
        raise NotImplementedError

    def start_regulation(self, tloop):
        """
        Starts the regulation process.
398
        It must NOT start the ramp, use 'start_ramp' to do so.
399
400
401
402
403
404
405
406
407
408
409
        Raises NotImplementedError if not defined by inheriting class

        Args: 
           tloop:  Loop class type object
        """
        log_info(self, "Controller:start_regulation: %s" % (tloop))
        raise NotImplementedError

    def stop_regulation(self, tloop):
        """
        Stops the regulation process.
410
        It must NOT stop the ramp, use 'stop_ramp' to do so.
411
412
413
414
415
416
417
418
        Raises NotImplementedError if not defined by inheriting class

        Args: 
           tloop:  Loop class type object
        """
        log_info(self, "Controller:stop_regulation: %s" % (tloop))
        raise NotImplementedError

419
    # ------ setpoint methods ------------------------
420
421
422
423

    def set_setpoint(self, tloop, sp, **kwargs):
        """
        Set the current setpoint (target value).
424
        It must NOT start the PID process, use 'start_regulation' to do so.
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object
           sp:     setpoint (in tloop.input unit)
           **kwargs: auxilliary arguments
        """
        log_info(self, "Controller:set_setpoint: %s %s" % (tloop, sp))
        raise NotImplementedError

    def get_setpoint(self, tloop):
        """
        Get the current setpoint (target value)
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object

        Returns:
           (float) setpoint value (in tloop.input unit).
        """
        log_info(self, "Controller:get_setpoint: %s" % (tloop))
        raise NotImplementedError

449
450
451
452
453
454
455
456
457
458
459
460
461
462
    def get_working_setpoint(self, tloop):
        """
        Get the current working setpoint (setpoint along ramping)
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object

        Returns:
           (float) working setpoint value (in tloop.input unit).
        """
        log_info(self, "Controller:get_working_setpoint: %s" % (tloop))
        raise NotImplementedError

463
    # ------ setpoint ramping methods (optional) ------------------------
464
465
466
467

    def start_ramp(self, tloop, sp, **kwargs):
        """
        Start ramping to a setpoint
468
        It must NOT start the PID process, use 'start_regulation' to do so.
469
470
        Raises NotImplementedError if not defined by inheriting class

471
472
473
        Replace 'Raises NotImplementedError' by 'pass' if the controller has ramping but doesn't have a method to explicitly starts the ramping.
        Else if this function returns 'NotImplementedError', then the Loop 'tloop' will use a SoftRamp instead.

474
475
476
477
478
479
480
481
482
483
484
        Args:
           tloop:  Loop class type object
           sp:       setpoint (in tloop.input unit)
           **kwargs: auxilliary arguments
        """
        log_info(self, "Controller:start_ramp: %s %s" % (tloop, sp))
        raise NotImplementedError

    def stop_ramp(self, tloop):
        """
        Stop the current ramping to a setpoint
485
        It must NOT stop the PID process, use 'stop_regulation' to do so.
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
585
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object
        """
        log_info(self, "Controller:stop_ramp: %s" % (tloop))
        raise NotImplementedError

    def is_ramping(self, tloop):
        """
        Get the ramping status.
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object

        Returns:
           (bool) True if ramping, else False.
        """
        log_info(self, "Controller:is_ramping: %s" % (tloop))
        raise NotImplementedError

    def set_ramprate(self, tloop, rate):
        """
        Set the ramp rate
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object
           rate:   ramp rate (in input unit per second)
        """
        log_info(self, "Controller:set_ramprate: %s %s" % (tloop, rate))
        raise NotImplementedError

    def get_ramprate(self, tloop):
        """
        Get the ramp rate
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object
        
        Returns:
           ramp rate (in input unit per second)
        """
        log_info(self, "Controller:get_ramprate: %s" % (tloop))
        raise NotImplementedError

    def set_dwell(self, tloop, dwell):
        """
        Set the dwell value (for ramp stepping mode)
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object
           dwell
       """
        log_info(self, "Controller:set_dwell: %s %s" % (tloop, dwell))
        raise NotImplementedError

    def get_dwell(self, tloop):
        """
        Get the dwell value (for ramp stepping mode)
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object
        
        Returns:
           dwell value
        """
        log_info(self, "Controller:get_dwell: %s" % (tloop))
        raise NotImplementedError

    def set_step(self, tloop, step):
        """
        Set the step value (for ramp stepping mode)
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object 
           step
       """
        log_info(self, "Controller:set_step: %s %s" % (tloop, step))
        raise NotImplementedError

    def get_step(self, tloop):
        """
        Get the dwell value (for ramp stepping mode)
        Raises NotImplementedError if not defined by inheriting class

        Args:
           tloop:  Loop class type object 
        
        Returns:
           step value
        """
        log_info(self, "Controller:get_step: %s" % (tloop))
        raise NotImplementedError

586
    # ------ raw methods (optional) ------------------------
587

588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    def Wraw(self, string):
        """
        A string to write to the controller
        Raises NotImplementedError if not defined by inheriting class

        Args:
           string:  the string to write
        """
        log_info(self, "Controller:Wraw:")
        raise NotImplementedError

    def Rraw(self):
        """
        Reading the controller
        Raises NotImplementedError if not defined by inheriting class

        returns:
           answer from the controller
        """
        log_info(self, "Controller:Rraw:")
        raise NotImplementedError

    def WRraw(self, string):
        """
        Write then Reading the controller
        Raises NotImplementedError if not defined by inheriting class

        Args:
           string:  the string to write
        returns:
           answer from the controller
        """
        log_info(self, "Controller:WRraw:")
        raise NotImplementedError

    # --- controller methods to customize the PID algo (optional) ------------------------
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661

    def get_sampling_frequency(self, tloop):
        """
        Get the sampling frequency (PID)
        Raises NotImplementedError if not defined by inheriting class

        Args: 
           tloop:  Loop class type object
        """
        log_info(self, "Controller:get_sampling_frequency: %s" % (tloop))
        raise NotImplementedError

    def set_sampling_frequency(self, tloop, value):
        """
        Set the sampling frequency (PID)
        Raises NotImplementedError if not defined by inheriting class

        Args: 
           tloop: Loop class type object
           value: the sampling frequency [Hz] 
        """
        log_info(self, "Controller:set_sampling_frequency: %s %s" % (tloop, value))
        raise NotImplementedError

    def get_pid_range(self, tloop):
        """
        Get the PID range (PID output value limits)
        """
        log_info(self, "Controller:get_pid_range: %s" % (tloop))
        raise NotImplementedError

    def set_pid_range(self, tloop, pid_range):
        """
        Set the PID range (PID output value limits)
        """
        log_info(self, "Controller:set_pid_range: %s %s" % (tloop, pid_range))
        raise NotImplementedError

662
663
    # --- controller method to set the Output to a given value (optional) -----------

664
665
666
667
668
669
670
671
672
673
674
    def set_output_value(self, toutput, value):
        """
        Set the value on the Output device.
        Raises NotImplementedError if not defined by inheriting class

        Args:
           toutput: Output class type object 
           value: value for the output device (in output unit)      
        """
        log_info(self, "Controller:set_output_value: %s %s" % (toutput, value))
        raise NotImplementedError
675

676
677
678
    # --- controller methods to handle the ramping on the Output (optional) -----------

    def start_output_ramp(self, toutput, value, **kwargs):
679
680
681
682
        """
        Start ramping on the output
        Raises NotImplementedError if not defined by inheriting class

683
684
685
        Replace 'Raises NotImplementedError' by 'pass' if the controller has output ramping but doesn't have a method to explicitly starts the output ramping.
        Else if this function returns 'NotImplementedError', then the output 'toutput' will use a SoftRamp instead.

686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
        Args:
           toutput:  Output class type object 
           value:    target value for the output ( in output unit )
           **kwargs: auxilliary arguments
        """
        log_info(self, "Controller:start_output_ramp: %s %s" % (toutput, value))
        raise NotImplementedError

    def stop_output_ramp(self, toutput):
        """
        Stop the current ramping on the output
        Raises NotImplementedError if not defined by inheriting class

        Args:
           toutput:  Output class type object 
        """
        log_info(self, "Controller:stop_output_ramp: %s" % (toutput))
        raise NotImplementedError

705
    def is_output_ramping(self, toutput):
706
707
708
709
710
711
712
713
714
715
        """
        Get the output ramping status.
        Raises NotImplementedError if not defined by inheriting class

        Args:
           toutput:  Output class type object

        Returns:
           (bool) True if ramping, else False.
        """
716
        log_info(self, "Controller:is_output_ramping: %s" % (toutput))
717
718
        raise NotImplementedError

719
    def set_output_ramprate(self, toutput, rate):
720
721
722
723
724
725
726
727
728
729
730
        """
        Set the output ramp rate
        Raises NotImplementedError if not defined by inheriting class

        Args:
           toutput:  Output class type object 
           rate:     ramp rate (in output unit per second)
        """
        log_info(self, "Controller:set_output_ramprate: %s %s" % (toutput, rate))
        raise NotImplementedError

731
    def get_output_ramprate(self, toutput):
732
733
734
735
736
737
738
739
740
741
742
743
        """
        Get the output ramp rate
        Raises NotImplementedError if not defined by inheriting class

        Args:
           toutput:  Output class type object 
        
        Returns:
           ramp rate (in output unit per second)
        """
        log_info(self, "Controller:get_output_ramprate: %s" % (toutput))
        raise NotImplementedError
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766


def send_limit(func):
    """
    Limit number of commands per second

    lakeshore 331/340 supports at most 20 commands per second
    """

    last_call = time.time()

    def f(*args, **kwargs):

        nonlocal last_call
        delta_t = time.time() - last_call
        if delta_t <= 0.15:
            time.sleep(0.15 - delta_t)
        try:
            return func(*args, **kwargs)
        finally:
            last_call = time.time()

    return f