regulator.py 23.6 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
95
96
    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

    _SUB_CLASS = {"inputs": Input, "outputs": Output, "ctrl_loops": Loop}

97
98
    def __init__(self, config):
        self._objects = {}
99
100
101
102
        self.__lock = lock.RLock()
        self.__initialized_obj = {}
        self.__hw_controller_initialized = False

103
104
105
106
107
108
109
110
111
112
113
114
115
116
        super().__init__(config)

    def _create_sub_item(self, name, cfg, parent_key):
        """ Create/get and return an object which has a config name and which is owned by this controller
            This method is called by the Bliss Controller Plugin and is called after the controller __init__().
            This method is called only once per item on the first config.get('item_name') call (see plugin).

            args:
                'name': sub item name
                'cfg' : sub item config
                'parent_key': the config key under which the sub item was found (ex: 'counters').

            return: the sub item object      
        """
117

118
        new_obj = self._SUB_CLASS[parent_key](self, cfg)
119
120
121
122
123

        # --- store the new object
        self._objects[new_obj.name] = new_obj

        # --- For custom attributes and commands.
124
        set_custom_members(self, new_obj, self.init_obj)  # really needed ???????
125

126
127
        return new_obj

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
    def _load_config(self):
        """ Read and apply the YML configuration """
        print("=== _load_config")
        pass

    def _build_counters(self):
        """ Build the CounterControllers and associated Counters"""
        print("=== _build_counters")
        self._counter_controllers["scc"] = self.SCC("scc", self)
        self._counter_controllers["scc"].max_sampling_frequency = self.config.get(
            "max_sampling_frequency", 1
        )

        for k in self._SUB_CLASS:
            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
                )

    def _build_axes(self):
        """ Build the Axes (real and pseudo) """
        print("=== _build_axes")
        pass

    @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):
        # return counter_namespace(self._motor_controller.axes)
        pass

166
167
168
169
170
    def init_obj(self, obj):
        """ Initialize objects under the controller. Called by @lazy_init. """

        with self.__lock:

171
            # ========= INIT HW, DEVICE AND CHILD DEVICE IF ANY =======================
172

173
            if not self.__hw_controller_initialized:
174
                self.initialize_controller()
175
                print("=== initialize_controller")
176
                self.__hw_controller_initialized = True
177

178
179
            if self.__initialized_obj.get(obj):
                return
180

181
            if isinstance(obj, Loop):
182

183
                self.__initialized_obj[obj] = True
184

185
186
187
188
                if not self.__initialized_obj.get(obj.input):
                    self.__initialized_obj[obj.input] = True
                    obj.input.load_base_config()
                    self.initialize_input(obj.input)
189
                    print("=== initialize_input")
190

191
192
193
194
                if not self.__initialized_obj.get(obj.output):
                    self.__initialized_obj[obj.output] = True
                    obj.output.load_base_config()
                    self.initialize_output(obj.output)
195
                    print("=== initialize_output")
196

197
198
                obj.load_base_config()
                self.initialize_loop(obj)
199
                print("=== initialize_loop")
200

201
202
203
204
205
            else:
                self.__initialized_obj[obj] = True
                obj.load_base_config()
                if isinstance(obj, Input):
                    self.initialize_input(obj)
206
                    print("=== initialize_input")
207
208
                elif isinstance(obj, Output):
                    self.initialize_output(obj)
209
                    print("=== initialize_output")
210
211
212
213
214
215
216
217
218
219
220
221
222
223

    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))
        return self._objects.get(name)

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
    @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
            for name, obj in self._objects.items()
            if isinstance(obj, class_type)
        }

243
    # ------ init methods ------------------------
244

245
    def initialize_controller(self):
246
        """ 
247
        Initializes the controller (including hardware).
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
        """
        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

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

    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

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

    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.
419
        It must NOT start the ramp, use 'start_ramp' to do so.
420
421
422
423
424
425
426
427
428
429
430
        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.
431
        It must NOT stop the ramp, use 'stop_ramp' to do so.
432
433
434
435
436
437
438
439
        Raises NotImplementedError if not defined by inheriting class

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

440
    # ------ setpoint methods ------------------------
441
442
443
444

    def set_setpoint(self, tloop, sp, **kwargs):
        """
        Set the current setpoint (target value).
445
        It must NOT start the PID process, use 'start_regulation' to do so.
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
        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

470
471
472
473
474
475
476
477
478
479
480
481
482
483
    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

484
    # ------ setpoint ramping methods (optional) ------------------------
485
486
487
488

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

492
493
494
        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.

495
496
497
498
499
500
501
502
503
504
505
        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
506
        It must NOT stop the PID process, use 'stop_regulation' to do so.
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
        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

607
    # ------ raw methods (optional) ------------------------
608

609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
    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) ------------------------
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682

    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

683
684
    # --- controller method to set the Output to a given value (optional) -----------

685
686
687
688
689
690
691
692
693
694
695
    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
696

697
698
699
    # --- controller methods to handle the ramping on the Output (optional) -----------

    def start_output_ramp(self, toutput, value, **kwargs):
700
701
702
703
        """
        Start ramping on the output
        Raises NotImplementedError if not defined by inheriting class

704
705
706
        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.

707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
        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

726
    def is_output_ramping(self, toutput):
727
728
729
730
731
732
733
734
735
736
        """
        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.
        """
737
        log_info(self, "Controller:is_output_ramping: %s" % (toutput))
738
739
        raise NotImplementedError

740
    def set_output_ramprate(self, toutput, rate):
741
742
743
744
745
746
747
748
749
750
751
        """
        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

752
    def get_output_ramprate(self, toutput):
753
754
755
756
757
758
759
760
761
762
763
764
        """
        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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787


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