digsim-engine 1.13.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. digsim/circuit/__init__.py +7 -0
  2. digsim/circuit/_circuit.py +764 -0
  3. digsim/circuit/_native.py +1029 -0
  4. digsim/circuit/_waves_writer.py +131 -0
  5. digsim/circuit/components/__init__.py +52 -0
  6. digsim/circuit/components/_arithmetic.py +266 -0
  7. digsim/circuit/components/_bus_bits.py +103 -0
  8. digsim/circuit/components/_button.py +61 -0
  9. digsim/circuit/components/_buzzer.py +64 -0
  10. digsim/circuit/components/_circuit_port.py +293 -0
  11. digsim/circuit/components/_clock.py +105 -0
  12. digsim/circuit/components/_counter.py +147 -0
  13. digsim/circuit/components/_decoder.py +140 -0
  14. digsim/circuit/components/_dip_switch.py +91 -0
  15. digsim/circuit/components/_flip_flops.py +162 -0
  16. digsim/circuit/components/_gates.py +408 -0
  17. digsim/circuit/components/_hd44780.py +451 -0
  18. digsim/circuit/components/_hd44780_rom.py +118 -0
  19. digsim/circuit/components/_hexdigit.py +107 -0
  20. digsim/circuit/components/_ic.py +96 -0
  21. digsim/circuit/components/_label_wire.py +204 -0
  22. digsim/circuit/components/_led.py +66 -0
  23. digsim/circuit/components/_led_bar.py +67 -0
  24. digsim/circuit/components/_logic_analyzer.py +111 -0
  25. digsim/circuit/components/_memory.py +517 -0
  26. digsim/circuit/components/_memstdout.py +60 -0
  27. digsim/circuit/components/_note.py +40 -0
  28. digsim/circuit/components/_on_off_switch.py +64 -0
  29. digsim/circuit/components/_probe.py +90 -0
  30. digsim/circuit/components/_seven_segment.py +47 -0
  31. digsim/circuit/components/_splitter.py +214 -0
  32. digsim/circuit/components/_static_level.py +54 -0
  33. digsim/circuit/components/_static_value.py +97 -0
  34. digsim/circuit/components/_subcircuit.py +439 -0
  35. digsim/circuit/components/_tristate_buffer.py +81 -0
  36. digsim/circuit/components/_verilog_component.py +26 -0
  37. digsim/circuit/components/_yosys_atoms.py +1373 -0
  38. digsim/circuit/components/_yosys_component.py +1126 -0
  39. digsim/circuit/components/_yosys_functional.py +1714 -0
  40. digsim/circuit/components/atoms/__init__.py +28 -0
  41. digsim/circuit/components/atoms/_component.py +329 -0
  42. digsim/circuit/components/atoms/_digsim_exception.py +8 -0
  43. digsim/circuit/components/atoms/_port.py +708 -0
  44. digsim/circuit/components/ic/4017.json +1062 -0
  45. digsim/circuit/components/ic/4021.json +286 -0
  46. digsim/circuit/components/ic/4029.json +1447 -0
  47. digsim/circuit/components/ic/4094.json +584 -0
  48. digsim/circuit/components/ic/4511.json +1071 -0
  49. digsim/circuit/components/ic/74138.json +763 -0
  50. digsim/circuit/components/ic/74139.json +610 -0
  51. digsim/circuit/components/ic/74148.json +1368 -0
  52. digsim/circuit/components/ic/74151.json +303 -0
  53. digsim/circuit/components/ic/74157.json +248 -0
  54. digsim/circuit/components/ic/74161.json +674 -0
  55. digsim/circuit/components/ic/74162.json +631 -0
  56. digsim/circuit/components/ic/74163.json +673 -0
  57. digsim/circuit/components/ic/74164.json +267 -0
  58. digsim/circuit/components/ic/74165.json +319 -0
  59. digsim/circuit/components/ic/74173.json +403 -0
  60. digsim/circuit/components/ic/74181.json +2002 -0
  61. digsim/circuit/components/ic/74182.json +893 -0
  62. digsim/circuit/components/ic/74193.json +1386 -0
  63. digsim/circuit/components/ic/74194.json +919 -0
  64. digsim/circuit/components/ic/74245.json +466 -0
  65. digsim/circuit/components/ic/74283.json +732 -0
  66. digsim/circuit/components/ic/74374.json +395 -0
  67. digsim/circuit/components/ic/7448.json +834 -0
  68. digsim/circuit/components/ic/74574.json +395 -0
  69. digsim/circuit/components/ic/74595.json +603 -0
  70. digsim/circuit/components/ic/7485.json +1042 -0
  71. digsim/storage_model/__init__.py +19 -0
  72. digsim/storage_model/_app.py +159 -0
  73. digsim/storage_model/_circuit.py +266 -0
  74. digsim/synth/__init__.py +12 -0
  75. digsim/synth/__main__.py +111 -0
  76. digsim/synth/_synthesis.py +529 -0
  77. digsim/utils/__init__.py +25 -0
  78. digsim/utils/_netlist_graph.py +199 -0
  79. digsim/utils/_yosys_netlist.py +251 -0
  80. digsim/verilog/__init__.py +19 -0
  81. digsim/verilog/__main__.py +78 -0
  82. digsim/verilog/_formatter.py +225 -0
  83. digsim/verilog/_lexer.py +218 -0
  84. digsim_engine-1.13.0.dist-info/METADATA +59 -0
  85. digsim_engine-1.13.0.dist-info/RECORD +88 -0
  86. digsim_engine-1.13.0.dist-info/WHEEL +5 -0
  87. digsim_engine-1.13.0.dist-info/licenses/LICENSE.md +32 -0
  88. digsim_engine-1.13.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,293 @@
1
+ # Copyright (c) Fredrik Andersson, 2026
2
+ # All rights reserved
3
+
4
+ """The ports of a circuit: its inputs, outputs and inout ports, its interface"""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING, ClassVar
9
+
10
+ from .atoms import (
11
+ VALUE_TYPE,
12
+ CallbackComponent,
13
+ ComponentException,
14
+ Parameter,
15
+ PortIn,
16
+ PortInOut,
17
+ PortOutDelta,
18
+ )
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from digsim.circuit import Circuit
23
+
24
+ MAX_WIDTH = 32
25
+
26
+
27
+ def circuit_ports(circuit: Circuit) -> list[CircuitPort]:
28
+ """The circuit ports of a circuit (not of its subcircuits), in the order they were added"""
29
+ return [
30
+ component
31
+ for component in circuit.get_toplevel_components()
32
+ if isinstance(component, CircuitPort)
33
+ ]
34
+
35
+
36
+ def free_label(base: str, taken: list[str]) -> str:
37
+ """The base name, or with a number (in2, in3, ...) if it is taken"""
38
+ if base not in taken:
39
+ return base
40
+ number = 2
41
+ while f"{base}{number}" in taken:
42
+ number += 1
43
+ return f"{base}{number}"
44
+
45
+
46
+ class CircuitPort(CallbackComponent):
47
+ """
48
+ The base class of the circuit ports, named by their label. The labels are unique in a
49
+ circuit, a subcircuit of it gets a port with each label.
50
+ """
51
+
52
+ # "in", "out" or "inout"
53
+ DIRECTION: ClassVar[str] = ""
54
+ # The label of a new port, with a number when it is taken
55
+ DEFAULT_LABEL: ClassVar[str] = ""
56
+
57
+ def __init__(self, circuit: Circuit, name: str | None, label: str, width: int) -> None:
58
+ # Checked before the component is added to the circuit
59
+ if not label.isidentifier():
60
+ raise ComponentException(f"The circuit port name '{label}' is not a name")
61
+ if label in [port.label() for port in circuit_ports(circuit)]:
62
+ raise ComponentException(f"The circuit has a port '{label}' already")
63
+ if not 1 <= width <= MAX_WIDTH:
64
+ raise ComponentException(f"The width must be 1 to {MAX_WIDTH}")
65
+ super().__init__(circuit, name)
66
+ self._label = label
67
+ self._width = width
68
+ self.parameter_set("label", label)
69
+ self.parameter_set("width", width)
70
+
71
+ def label(self) -> str:
72
+ """The name of the port"""
73
+ return self._label
74
+
75
+ @property
76
+ def width(self) -> int:
77
+ """The number of bits"""
78
+ return self._width
79
+
80
+ @property
81
+ def value(self) -> VALUE_TYPE:
82
+ """The value of the port, see the classes of the ports"""
83
+ raise NotImplementedError
84
+
85
+ @classmethod
86
+ def _port_parameters(cls, labels: list[str]) -> dict[str, Parameter]:
87
+ return {
88
+ "label": {
89
+ "type": "str",
90
+ "single_line": True,
91
+ "default": free_label(cls.DEFAULT_LABEL, labels),
92
+ "description": "Port name",
93
+ "invalid_list": labels,
94
+ },
95
+ "width": {
96
+ "type": "int",
97
+ "min": 1,
98
+ "max": MAX_WIDTH,
99
+ "default": 1,
100
+ "description": "Bitwidth of the port",
101
+ },
102
+ }
103
+
104
+ @classmethod
105
+ def get_parameters(cls) -> dict[str, Parameter]:
106
+ return cls._port_parameters([])
107
+
108
+ @classmethod
109
+ def get_circuit_parameters(cls, circuit: Circuit) -> dict[str, Parameter]:
110
+ return cls._port_parameters([port.label() for port in circuit_ports(circuit)])
111
+
112
+
113
+ class CircuitInput(CircuitPort):
114
+ """
115
+ An input of the circuit. In the circuit itself it drives a value, 0 at the start, that
116
+ set_value() sets. In a subcircuit, its input with the label takes its place.
117
+
118
+ Ports:
119
+ <label>: Output, named like the label, `width` bits.
120
+
121
+ Args:
122
+ circuit: The circuit to add the component to.
123
+ name: The component name, the class name if not given.
124
+ label: The name of the port.
125
+ width: The number of bits, 1 to 32.
126
+ """
127
+
128
+ DIRECTION = "in"
129
+ DEFAULT_LABEL = "in"
130
+
131
+ def __init__(
132
+ self, circuit: Circuit, name: str | None = None, label: str = "in", width: int = 1
133
+ ) -> None:
134
+ super().__init__(circuit, name, label, width)
135
+ self._value = 0
136
+ self._output = PortOutDelta(self, label, width=width, delay_ns=0)
137
+ self._output.update_parent(True)
138
+ self.add_port(self._output)
139
+
140
+ def default_state(self) -> None:
141
+ self._value = 0
142
+ self._output.value = 0
143
+
144
+ def set_value(self, value: int) -> None:
145
+ """
146
+ Drive a value.
147
+
148
+ Args:
149
+ value: The value, 0 to 2^width - 1.
150
+ """
151
+ if not 0 <= value < 1 << self._width:
152
+ raise ComponentException(f"{value} does not fit in {self._width} bits")
153
+ self._value = value
154
+ self._output.value = value
155
+
156
+ @property
157
+ def value(self) -> int:
158
+ """The value it drives"""
159
+ return self._value
160
+
161
+ def onpress(self) -> None:
162
+ # A 1-bit input toggles, like a switch
163
+ if self._width == 1:
164
+ self.set_value(1 - self._value)
165
+
166
+ @property
167
+ def has_action(self) -> bool:
168
+ return self._width == 1
169
+
170
+ @property
171
+ def active(self) -> bool:
172
+ return self._value != 0
173
+
174
+
175
+ class CircuitOutput(CircuitPort):
176
+ """
177
+ An output of the circuit, it shows the value of its input. In a subcircuit, its output
178
+ with the label takes its place.
179
+
180
+ Ports:
181
+ <label>: Input, named like the label, `width` bits.
182
+
183
+ Args:
184
+ circuit: The circuit to add the component to.
185
+ name: The component name, the class name if not given.
186
+ label: The name of the port.
187
+ width: The number of bits, 1 to 32.
188
+ """
189
+
190
+ DIRECTION = "out"
191
+ DEFAULT_LABEL = "out"
192
+
193
+ def __init__(
194
+ self, circuit: Circuit, name: str | None = None, label: str = "out", width: int = 1
195
+ ) -> None:
196
+ super().__init__(circuit, name, label, width)
197
+ self._input = PortIn(self, label, width=width)
198
+ self.add_port(self._input)
199
+
200
+ @property
201
+ def value(self) -> VALUE_TYPE:
202
+ """The value of the input"""
203
+ return self._input.value
204
+
205
+ @property
206
+ def active(self) -> bool:
207
+ return self._input.value not in (0, "X", "Z")
208
+
209
+
210
+ class CircuitInOut(CircuitPort):
211
+ """
212
+ An inout port of the circuit: it shows the value of its wire, and drives a value that
213
+ set_value() sets, or nothing ("Z") as at the start. In a subcircuit, its inout port with
214
+ the label takes its place.
215
+
216
+ Ports:
217
+ <label>: Inout port, named like the label, `width` bits.
218
+
219
+ Args:
220
+ circuit: The circuit to add the component to.
221
+ name: The component name, the class name if not given.
222
+ label: The name of the port.
223
+ width: The number of bits, 1 to 32.
224
+ """
225
+
226
+ DIRECTION = "inout"
227
+ DEFAULT_LABEL = "io"
228
+
229
+ def __init__(
230
+ self, circuit: Circuit, name: str | None = None, label: str = "io", width: int = 1
231
+ ) -> None:
232
+ super().__init__(circuit, name, label, width)
233
+ self._value: VALUE_TYPE = "Z"
234
+ self._inout = PortInOut(self, label, width=width)
235
+ self._inout.set_tristate()
236
+ self.add_port(self._inout)
237
+ # A driver for each bit of the port, and an input for each bit it reads, that
238
+ # updates the component (for the GUI)
239
+ self._drivers: list[PortOutDelta] = []
240
+ self._readers: list[PortIn] = []
241
+ for bit_id in range(width):
242
+ driver = PortOutDelta(self, f"{label}_driver_{bit_id}", delay_ns=0)
243
+ driver.set_tristate()
244
+ driver.wire = self._inout.get_drive_bit(bit_id)
245
+ self._drivers.append(driver)
246
+ reader = PortIn(self, f"{label}_reader_{bit_id}")
247
+ self._inout.get_bit(bit_id).wire = reader
248
+ self._readers.append(reader)
249
+
250
+ def init(self) -> None:
251
+ super().init()
252
+ for port in [*self._drivers, *self._readers]:
253
+ port.init()
254
+
255
+ def default_state(self) -> None:
256
+ self._drive("Z")
257
+
258
+ def _drive(self, value: VALUE_TYPE) -> None:
259
+ self._value = value
260
+ for bit_id, driver in enumerate(self._drivers):
261
+ driver.value = (value >> bit_id) & 1 if isinstance(value, int) else value
262
+
263
+ def set_value(self, value: int | str) -> None:
264
+ """
265
+ Drive a value on the wire, or nothing ("Z").
266
+
267
+ Args:
268
+ value: The value, 0 to 2^width - 1, or "Z".
269
+ """
270
+ if value != "Z" and not (isinstance(value, int) and 0 <= value < 1 << self._width):
271
+ raise ComponentException(f"{value} does not fit in {self._width} bits")
272
+ self._drive(value if isinstance(value, int) else "Z")
273
+
274
+ @property
275
+ def drive(self) -> VALUE_TYPE:
276
+ """The value it drives, "Z" when it doesn't"""
277
+ return self._value
278
+
279
+ @property
280
+ def value(self) -> VALUE_TYPE:
281
+ """The value of the wire, what it drives resolved with what the others drive"""
282
+ return self._inout.read_value()
283
+
284
+ @property
285
+ def active(self) -> bool:
286
+ return self.value not in (0, "X", "Z")
287
+
288
+
289
+ # The type names of the circuit ports in a circuit file, and their directions
290
+ CIRCUIT_PORT_TYPES = {
291
+ f"digsim.circuit.components.{port_class.__name__}": port_class.DIRECTION
292
+ for port_class in (CircuitInput, CircuitOutput, CircuitInOut)
293
+ }
@@ -0,0 +1,105 @@
1
+ # Copyright (c) Fredrik Andersson, 2023-2026
2
+ # All rights reserved
3
+
4
+ """Clock component module"""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING
9
+
10
+ from .atoms import (
11
+ CallbackComponent,
12
+ DigsimException,
13
+ Parameter,
14
+ PortOutDelta,
15
+ PortOutImmediate,
16
+ )
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from digsim.circuit import Circuit
21
+
22
+
23
+ # The highest frequency in the GUI, a half period of 5 ns
24
+ MAX_FREQUENCY = 100_000_000
25
+
26
+
27
+ class Clock(CallbackComponent):
28
+ """
29
+ A clock, its output is a square wave. It starts low at init(), and rises half a period
30
+ later. A test bench can drive a circuit by its edges, see Circuit.run_until_edge().
31
+
32
+ Ports:
33
+ O: Output.
34
+
35
+ Args:
36
+ circuit: The circuit to add the component to.
37
+ name: The component name, the class name if not given.
38
+ frequency: The frequency in Hz.
39
+ """
40
+
41
+ def __init__(self, circuit: Circuit, name: str | None = None, frequency: int = 1) -> None:
42
+ super().__init__(circuit, name)
43
+ self._feedback = PortOutDelta(self, "feedback")
44
+ portout = PortOutImmediate(self, "O")
45
+ self.add_port(portout)
46
+ self._feedback.update_parent(True)
47
+ self._half_period_ns = 1
48
+ self.parameter_set("frequency", frequency)
49
+ self.reconfigure()
50
+
51
+ def default_state(self) -> None:
52
+ self.O.value = 0
53
+ self._feedback.value = 1
54
+
55
+ def update(self) -> None:
56
+ if self._feedback.value == 1:
57
+ self.O.value = 1
58
+ self._feedback.value = 0
59
+ else:
60
+ self.O.value = 0
61
+ self._feedback.value = 1
62
+ super().update()
63
+
64
+ def next_edge_ns(self, rising: bool = True) -> int:
65
+ """
66
+ The time of the next rising (or falling) edge of the output, in nanoseconds.
67
+
68
+ Raises:
69
+ DigsimException: If the circuit isn't initialized (the clock doesn't run).
70
+ """
71
+ # The output changes at the next event of the feedback
72
+ edge = self.circuit.next_event_ns(self._feedback)
73
+ if edge is None:
74
+ raise DigsimException("The clock runs from Circuit.init()")
75
+ if (self.O.value == 1) == rising:
76
+ # The next change is the other edge
77
+ edge += self._half_period_ns
78
+ return edge
79
+
80
+ @property
81
+ def half_period_ns(self) -> int:
82
+ """The time between two edges of the output, in nanoseconds"""
83
+ return self._half_period_ns
84
+
85
+ def reconfigure(self) -> None:
86
+ self._half_period_ns = int(1000000000 / (self.parameter_get("frequency") * 2))
87
+ self._feedback.set_delay_ns(self._half_period_ns)
88
+ self.circuit.delay_changed(self._feedback)
89
+
90
+ @property
91
+ def active(self) -> bool:
92
+ return self.O.value == 1
93
+
94
+ @classmethod
95
+ def get_parameters(cls) -> dict[str, Parameter]:
96
+ return {
97
+ "frequency": {
98
+ "type": "frequency",
99
+ "min": 1,
100
+ "max": MAX_FREQUENCY,
101
+ "default": 1,
102
+ "description": "Clock frequency",
103
+ "reconfigurable": True,
104
+ },
105
+ }
@@ -0,0 +1,147 @@
1
+ # Copyright (c) Fredrik Andersson, 2026
2
+ # All rights reserved
3
+
4
+ """Counter component module"""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING
9
+
10
+ from .atoms import (
11
+ VALUE_TYPE,
12
+ Component,
13
+ ComponentException,
14
+ Parameter,
15
+ PortIn,
16
+ PortOutDelta,
17
+ PortWire,
18
+ )
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ from digsim.circuit import Circuit
23
+
24
+ MAX_WIDTH = 32
25
+
26
+
27
+ class Counter(Component):
28
+ """
29
+ A binary counter: Q counts up (or down) by one on each rising edge of clk, and wraps
30
+ around. It starts at 0.
31
+
32
+ Ports:
33
+ clk: Clock input.
34
+ R: Reset input, 1 sets Q to 0 at once.
35
+ EN: Clock enable input, the clock edge is ignored while it is 0 (only with
36
+ `enable`).
37
+ UP: Direction input, 1 counts up and 0 down (only with `up_down`).
38
+ LD: Load input, 1 loads D on the clock edge instead of counting (only with `load`).
39
+ D: Data input to load, `width` bits (only with `load`).
40
+ Q: Output, `width` bits.
41
+ CO: Carry output, 1 at the last count before Q wraps around: the highest value
42
+ counting up, 0 counting down.
43
+
44
+ Args:
45
+ circuit: The circuit to add the component to.
46
+ name: The component name, the class name if not given.
47
+ width: The number of bits, 1 to 32.
48
+ enable: Add the clock enable input EN.
49
+ up_down: Add the direction input UP, otherwise it counts up.
50
+ load: Add the load inputs LD and D.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ circuit: Circuit,
56
+ name: str | None = None,
57
+ width: int = 4,
58
+ enable: bool = False,
59
+ up_down: bool = False,
60
+ load: bool = False,
61
+ ) -> None:
62
+ super().__init__(circuit, name)
63
+ if not 1 <= width <= MAX_WIDTH:
64
+ raise ComponentException(f"The width must be 1 to {MAX_WIDTH}")
65
+ self._enable = enable
66
+ self._up_down = up_down
67
+ self._load = load
68
+ self._mask = (1 << width) - 1
69
+ self._count: VALUE_TYPE = 0
70
+ self.add_port(PortIn(self, "clk"))
71
+ self.add_port(PortIn(self, "R"))
72
+ if enable:
73
+ self.add_port(PortWire(self, "EN"))
74
+ if up_down:
75
+ self.add_port(PortIn(self, "UP"))
76
+ if load:
77
+ self.add_port(PortWire(self, "LD"))
78
+ self.add_port(PortWire(self, "D", width=width))
79
+ self.add_port(PortOutDelta(self, "Q", width=width))
80
+ self.add_port(PortOutDelta(self, "CO"))
81
+ self.parameter_set("width", width)
82
+ self.parameter_set("enable", enable)
83
+ self.parameter_set("up_down", up_down)
84
+ self.parameter_set("load", load)
85
+
86
+ def default_state(self) -> None:
87
+ self._set_count(0)
88
+
89
+ def _counts_up(self) -> VALUE_TYPE:
90
+ return self.UP.value if self._up_down else 1
91
+
92
+ def _set_count(self, count: VALUE_TYPE) -> None:
93
+ self._count = count
94
+ self.Q.value = count
95
+ self._carry_out()
96
+
97
+ def _carry_out(self) -> None:
98
+ up = self._counts_up()
99
+ if not isinstance(self._count, int) or not isinstance(up, int):
100
+ self.CO.value = "X"
101
+ else:
102
+ self.CO.value = int(self._count == (self._mask if up else 0))
103
+
104
+ def update(self) -> None:
105
+ rising_edge = self.clk.is_rising_edge()
106
+ if self.R.value == 1:
107
+ if self._count != 0:
108
+ self._set_count(0)
109
+ return
110
+ if not rising_edge:
111
+ # The direction changed: the carry output follows it
112
+ self._carry_out()
113
+ return
114
+ if self._enable and self.EN.value == 0:
115
+ return
116
+ if self._load and self.LD.value == 1:
117
+ data = self.D.value
118
+ self._set_count(data if isinstance(data, int) else "X")
119
+ return
120
+ up = self._counts_up()
121
+ if not isinstance(self._count, int) or not isinstance(up, int):
122
+ self._set_count("X")
123
+ return
124
+ self._set_count((self._count + (1 if up else -1)) & self._mask)
125
+
126
+ @classmethod
127
+ def get_parameters(cls) -> dict[str, Parameter]:
128
+ return {
129
+ "width": {
130
+ "type": "int",
131
+ "min": 1,
132
+ "max": MAX_WIDTH,
133
+ "default": 4,
134
+ "description": "Bitwidth of the counter",
135
+ },
136
+ "enable": {"type": "bool", "default": False, "description": "Clock enable input EN"},
137
+ "up_down": {
138
+ "type": "bool",
139
+ "default": False,
140
+ "description": "Count up or down, direction input UP",
141
+ },
142
+ "load": {
143
+ "type": "bool",
144
+ "default": False,
145
+ "description": "Load inputs LD and D",
146
+ },
147
+ }
@@ -0,0 +1,140 @@
1
+ # Copyright (c) Fredrik Andersson, 2026
2
+ # All rights reserved
3
+
4
+ """Decoder and demultiplexer components"""
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING
9
+
10
+ from .atoms import Component, ComponentException, Parameter, PortIn, PortOutDelta
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from digsim.circuit import Circuit
15
+
16
+ # The most select bits, for 16 outputs
17
+ MAX_SELECT = 4
18
+
19
+
20
+ def _select_parameter(default: int) -> Parameter:
21
+ return {
22
+ "type": "int",
23
+ "min": 1,
24
+ "max": MAX_SELECT,
25
+ "default": default,
26
+ "description": "Select bits (2^bits outputs)",
27
+ }
28
+
29
+
30
+ class _Selector(Component):
31
+ """The base class of the decoder and the demultiplexer: outputs Y0, Y1, ... by S"""
32
+
33
+ def __init__(self, circuit: Circuit, name: str | None, select: int) -> None:
34
+ super().__init__(circuit, name)
35
+ if not 1 <= select <= MAX_SELECT:
36
+ raise ComponentException(f"The select bits must be 1 to {MAX_SELECT}")
37
+ self.parameter_set("select", select)
38
+
39
+ def _add_outputs(self, select: int, width: int) -> None:
40
+ self._outputs = [
41
+ PortOutDelta(self, f"Y{index}", width=width) for index in range(1 << select)
42
+ ]
43
+ for port in self._outputs:
44
+ self.add_port(port)
45
+
46
+
47
+ class Decoder(_Selector):
48
+ """
49
+ A decoder: the output that S selects is 1, the others are 0.
50
+
51
+ Ports:
52
+ S: Select input, `select` bits.
53
+ EN: Enable input, all outputs are 0 while it is 0 (only with `enable`).
54
+ Y0, Y1, ...: Outputs, one for each value of S.
55
+
56
+ Args:
57
+ circuit: The circuit to add the component to.
58
+ name: The component name, the class name if not given.
59
+ select: The number of select bits, 1 to 4 (2 to 16 outputs).
60
+ enable: Add the enable input EN.
61
+ """
62
+
63
+ def __init__(
64
+ self, circuit: Circuit, name: str | None = None, select: int = 2, enable: bool = False
65
+ ) -> None:
66
+ super().__init__(circuit, name, select)
67
+ self._enable = enable
68
+ self.add_port(PortIn(self, "S", width=select))
69
+ if enable:
70
+ self.add_port(PortIn(self, "EN"))
71
+ self._add_outputs(select, 1)
72
+ self.parameter_set("enable", enable)
73
+
74
+ def update(self) -> None:
75
+ select = self.S.value
76
+ enable = self.EN.value if self._enable else 1
77
+ if enable == 0:
78
+ for port in self._outputs:
79
+ port.value = 0
80
+ elif not isinstance(select, int) or enable != 1:
81
+ for port in self._outputs:
82
+ port.value = "X"
83
+ else:
84
+ for index, port in enumerate(self._outputs):
85
+ port.value = int(index == select)
86
+
87
+ @classmethod
88
+ def get_parameters(cls) -> dict[str, Parameter]:
89
+ return {
90
+ "select": _select_parameter(2),
91
+ "enable": {"type": "bool", "default": False, "description": "Enable input EN"},
92
+ }
93
+
94
+
95
+ class Demultiplexer(_Selector):
96
+ """
97
+ A demultiplexer: the output that S selects is I, the others are 0.
98
+
99
+ Ports:
100
+ I: Input, `width` bits.
101
+ S: Select input, `select` bits.
102
+ Y0, Y1, ...: Outputs, `width` bits, one for each value of S.
103
+
104
+ Args:
105
+ circuit: The circuit to add the component to.
106
+ name: The component name, the class name if not given.
107
+ select: The number of select bits, 1 to 4 (2 to 16 outputs).
108
+ width: The number of bits of I and the outputs, 1 to 32.
109
+ """
110
+
111
+ def __init__(
112
+ self, circuit: Circuit, name: str | None = None, select: int = 1, width: int = 1
113
+ ) -> None:
114
+ super().__init__(circuit, name, select)
115
+ self.add_port(PortIn(self, "I", width=width))
116
+ self.add_port(PortIn(self, "S", width=select))
117
+ self._add_outputs(select, width)
118
+ self.parameter_set("width", width)
119
+
120
+ def update(self) -> None:
121
+ select = self.S.value
122
+ if not isinstance(select, int):
123
+ for port in self._outputs:
124
+ port.value = "X"
125
+ return
126
+ for index, port in enumerate(self._outputs):
127
+ port.value = self.I.value if index == select else 0
128
+
129
+ @classmethod
130
+ def get_parameters(cls) -> dict[str, Parameter]:
131
+ return {
132
+ "select": _select_parameter(1),
133
+ "width": {
134
+ "type": "int",
135
+ "min": 1,
136
+ "max": 32,
137
+ "default": 1,
138
+ "description": "Bitwidth of the input and the outputs",
139
+ },
140
+ }