-
-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathswitch.py
More file actions
106 lines (71 loc) · 2.88 KB
/
switch.py
File metadata and controls
106 lines (71 loc) · 2.88 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
#########################################################################################
##
## SWITCH BLOCK
## (blocks/switch.py)
##
#########################################################################################
# IMPORTS ===============================================================================
from ._block import Block
# BLOCK DEFINITION ======================================================================
class Switch(Block):
"""Switch block that selects between its inputs.
Example
-------
The block is initialized like this:
.. code-block:: python
#default None -> no passthrough
s1 = Switch()
#selecting port 2 as passthrough
s2 = Switch(2)
#change the state of the switch to port 3
s2.select(3)
Sets block output depending on `self.switch_state` like this:
.. code-block::
switch_state == None -> outputs[0] = 0
switch_state == 0 -> outputs[0] = inputs[0]
switch_state == 1 -> outputs[0] = inputs[1]
switch_state == 2 -> outputs[0] = inputs[2]
...
Parameters
----------
switch_state : int, None
state of the switch
"""
input_port_labels = None
output_port_labels = {"out":0}
def __init__(self, switch_state=None):
super().__init__()
self.switch_state = switch_state
def __len__(self):
"""Algebraic passthrough only possible if switch_state is defined"""
return 0 if (self.switch_state is None or not self._active) else 1
def select(self, switch_state=0):
"""
This method is unique to the `Switch` block and intended
to be used from outside the simulation level for selecting
the input ports for the switch state.
This can be achieved for example with the event management
system and its callback/action functions.
Parameters
---------
switch_state : int, None
switch state / input port selection
"""
self.switch_state = switch_state
def to_checkpoint(self, prefix, recordings=False):
json_data, npz_data = super().to_checkpoint(prefix, recordings=recordings)
json_data["switch_state"] = self.switch_state
return json_data, npz_data
def load_checkpoint(self, prefix, json_data, npz):
super().load_checkpoint(prefix, json_data, npz)
self.switch_state = json_data.get("switch_state", None)
def update(self, t):
"""Update switch output depending on inputs and switch state.
Parameters
----------
t : float
evaluation time
"""
#early exit without error control
if self.switch_state is None: self.outputs[0] = 0.0
else: self.outputs[0] = self.inputs[self.switch_state]