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,764 @@
1
+ # Copyright (c) Fredrik Andersson, 2023-2026
2
+ # All rights reserved
3
+
4
+ """
5
+ Module that handles the circuit simulation of components
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import heapq
11
+ import os
12
+ import time
13
+ from collections.abc import Iterator
14
+ from contextlib import contextmanager
15
+ from pathlib import Path, PureWindowsPath
16
+ from types import TracebackType
17
+ from typing import TYPE_CHECKING, Any, NamedTuple, Self
18
+
19
+ from digsim.storage_model import CircuitDataClass, CircuitFileDataClass
20
+
21
+ from . import _native
22
+ from ._waves_writer import WavesWriter
23
+ from .components._clock import Clock
24
+ from .components.atoms import (
25
+ VALUE_TYPE,
26
+ Component,
27
+ DigsimException,
28
+ Port,
29
+ PortInOut,
30
+ PortMultiBitWire,
31
+ PortOutDelta,
32
+ )
33
+ from .components.atoms._port import connection_generation
34
+
35
+
36
+ if TYPE_CHECKING:
37
+ from .components._circuit_port import CircuitPort
38
+
39
+
40
+ EventPort = PortOutDelta | PortMultiBitWire | PortInOut
41
+
42
+
43
+ class CircuitError(DigsimException):
44
+ """A circuit error class"""
45
+
46
+
47
+ class RunResult(NamedTuple):
48
+ """
49
+ How a run with a time limit ended (see Circuit.run_within()): if it stopped for a
50
+ single step, and if it ran all the time it was asked to
51
+ """
52
+
53
+ single_step: bool
54
+ complete: bool
55
+
56
+
57
+ # The slices of simulated time that run_within() runs, between its looks at the clock: it
58
+ # starts small, so that a circuit that oscillates gets a look soon, and grows while the
59
+ # slices are fast, to at most MAX_SLICE_NS
60
+ START_SLICE_NS = 1_000
61
+ MAX_SLICE_NS = 1_000_000
62
+
63
+
64
+ class CircuitEvent(float):
65
+ """
66
+ The circuit event class for storing the
67
+ delta events in the simulation.
68
+
69
+ An event is its time as a float, so that the event queue compares events in C
70
+ instead of calling a Python __lt__ for every comparison. The comparisons give the
71
+ same results, so events at the same time keep their order.
72
+ """
73
+
74
+ __slots__ = ("_port", "_time_ns", "_value")
75
+
76
+ _port: EventPort
77
+ _time_ns: int
78
+ _value: VALUE_TYPE
79
+
80
+
81
+ class Circuit:
82
+ """
83
+ A circuit: holds the components and runs the simulation. Use it in a with statement,
84
+ `with Circuit(vcd="waves.vcd") as circuit:`, to close the VCD file at the end.
85
+
86
+ Args:
87
+ name: The circuit name, needed to save the circuit.
88
+ vcd: A VCD file to write waveforms to, from init().
89
+ """
90
+
91
+ def __init__(self, name: str | None = None, vcd: str | None = None) -> None:
92
+ self._components: dict[str, Component] = {}
93
+ self._circuit_events: list[CircuitEvent] = []
94
+ self._events_by_port: dict[EventPort, CircuitEvent] = {}
95
+ self._name: str | None = name
96
+ self._time_ns: int = 0
97
+ self._folder: str = "."
98
+ self._vcd: WavesWriter | None = None
99
+ # The slice of run_within()
100
+ self._slice_ns = START_SLICE_NS
101
+ # The native engine, see _native.py
102
+ self._engine: _native.NativeEngine | None = None
103
+
104
+ if vcd is not None:
105
+ self._vcd = WavesWriter(filename=vcd)
106
+
107
+ @property
108
+ def name(self) -> str | None:
109
+ """Get the circuit name"""
110
+ return self._name
111
+
112
+ @property
113
+ def time_ns(self) -> int:
114
+ """Get the current simulation time (ns)"""
115
+ if self._engine is not None:
116
+ return int(self._engine.engine.time)
117
+ return self._time_ns
118
+
119
+ @property
120
+ def components(self) -> list[Component]:
121
+ """Get the components in this circuit"""
122
+ return list(self._components.values())
123
+
124
+ def load_path(self, path: str | Path) -> str:
125
+ """Get the load path relative to the circuit path, empty for no path"""
126
+ if not str(path):
127
+ return ""
128
+ if "\\" in str(path):
129
+ # Stored with backslashes on Windows by an older version, read on all systems
130
+ path = PureWindowsPath(path).as_posix()
131
+ load_path = Path(path)
132
+ if not load_path.is_absolute():
133
+ load_path = Path(self._folder) / load_path
134
+ return str(load_path)
135
+
136
+ def store_path(self, path: str | Path) -> str:
137
+ """Get the store path relative to the circuit path, empty for no path"""
138
+ if not str(path):
139
+ return ""
140
+ store_path = Path(path).resolve(strict=False)
141
+ folder_path = Path(self._folder).resolve(strict=False)
142
+ try:
143
+ store_path = Path(os.path.relpath(store_path, folder_path))
144
+ except ValueError:
145
+ pass # No relative path (another drive on Windows), keep the absolute path
146
+ # '/' also on Windows, so that the circuit file can be loaded on all systems
147
+ return store_path.as_posix()
148
+
149
+ @contextmanager
150
+ def adding_components(self) -> Iterator[None]:
151
+ """
152
+ Context for creating components: if the block raises an exception, the components
153
+ it added to the circuit before failing are removed again
154
+ """
155
+ names_before = set(self._components)
156
+ try:
157
+ yield
158
+ except BaseException:
159
+ for name in set(self._components) - names_before:
160
+ del self._components[name]
161
+ raise
162
+
163
+ def delete_component(self, component: Component) -> None:
164
+ """Delete a component, and the components it is built from, from the circuit"""
165
+ for comp in list(self._components.values()):
166
+ part: Component | None = comp
167
+ while part is not None and part is not component:
168
+ part = part.parent
169
+ if part is component:
170
+ del self._components[comp.name()]
171
+ component.remove_connections()
172
+
173
+ def get_toplevel_components(self) -> list[Component]:
174
+ """Get toplevel components in the circuit"""
175
+ return [comp for comp in self._components.values() if comp.is_toplevel()]
176
+
177
+ def ports(self) -> list[CircuitPort]:
178
+ """
179
+ The circuit ports of the circuit (CircuitInput, CircuitOutput and CircuitInOut), its
180
+ interface when it is used as a subcircuit, in the order they were added
181
+ """
182
+ # Imported here: the components import the circuit
183
+ from digsim.circuit.components._circuit_port import circuit_ports
184
+
185
+ return circuit_ports(self)
186
+
187
+ def init(self) -> None:
188
+ """
189
+ Initialize the circuit: set the time to 0 and all ports to "X", then let the
190
+ components set their default state. Call it after adding and connecting components.
191
+ """
192
+ self._stop_engine(keep_events=False)
193
+ self._time_ns = 0
194
+ self._circuit_events = []
195
+ self._events_by_port = {}
196
+ self._slice_ns = START_SLICE_NS
197
+ if self._vcd is not None:
198
+ self._vcd_init()
199
+ for comp in self._components.values():
200
+ comp.init()
201
+ if _native.mode() == "native":
202
+ self._engine = _native.NativeEngine(self, self._time_ns)
203
+ native = self._engine
204
+ if native is not None:
205
+ # The events that ports added in their init() (an inout port drives "Z"), in
206
+ # the order of the heap, which pushed in that order is the same heap
207
+ for event in self._circuit_events:
208
+ native.engine.add_event(native.nid(event._port), event._value, event._time_ns)
209
+ self._circuit_events = []
210
+ self._events_by_port = {}
211
+ for comp in self._components.values():
212
+ # The engine sets the state of the components it simulates
213
+ if native is None or not native.default_state(comp):
214
+ comp.default_state()
215
+ self.run_until(ns=0) # Handle all time zero events
216
+
217
+ def clear(self) -> None:
218
+ """Remove all components, and the events of their ports"""
219
+ self._stop_engine(keep_events=False)
220
+ for comp in self._components.values():
221
+ comp.clear()
222
+ self._components = {}
223
+ self._circuit_events = []
224
+ self._events_by_port = {}
225
+
226
+ def vcd(self, filename: str) -> None:
227
+ """
228
+ Start writing waveforms to a VCD file, for GTKWave or another viewer.
229
+
230
+ Raises:
231
+ CircuitError: If a VCD file is already open.
232
+ OSError: If the file can't be opened.
233
+ """
234
+ if self._vcd is not None:
235
+ raise CircuitError("VCD already started")
236
+ self._vcd = WavesWriter(filename=filename)
237
+ try:
238
+ self._vcd_init()
239
+ except BaseException:
240
+ # The file could not be opened, don't keep a writer without a file
241
+ self._vcd = None
242
+ raise
243
+
244
+ def vcd_close(self) -> None:
245
+ """Finish and close the VCD file, if one is open"""
246
+ if self._vcd is not None:
247
+ self._vcd.close()
248
+ self._vcd = None
249
+
250
+ def _vcd_init(self) -> None:
251
+ if self._vcd is None:
252
+ return
253
+ ports = []
254
+ for comp in self._components.values():
255
+ ports.extend(comp.ports)
256
+ self._vcd.init(ports)
257
+
258
+ # Dump initial state in vcd
259
+ for comp in self._components.values():
260
+ for port in comp.ports:
261
+ self._vcd.write(port, self._time_ns)
262
+
263
+ def _time_to_ns(
264
+ self,
265
+ s: float | None = None,
266
+ ms: float | None = None,
267
+ us: float | None = None,
268
+ ns: float | None = None,
269
+ ) -> int:
270
+ time_ns: float = 0
271
+ time_ns += s * 1e9 if s is not None else 0
272
+ time_ns += ms * 1e6 if ms is not None else 0
273
+ time_ns += us * 1e3 if us is not None else 0
274
+ time_ns += ns if ns is not None else 0
275
+ # Rounded, since a time like 1.001 µs is 1000.9999999999999 ns as a float
276
+ return round(time_ns)
277
+
278
+ def __enter__(self) -> Self:
279
+ return self
280
+
281
+ def __exit__(
282
+ self,
283
+ exc_type: type[BaseException] | None,
284
+ exc_value: BaseException | None,
285
+ exc_traceback: TracebackType | None,
286
+ ) -> None:
287
+ self.vcd_close()
288
+
289
+ def _stop_engine(self, keep_events: bool = True) -> None:
290
+ """Go back to the Python engine, with the events and the time of the native one"""
291
+ native = self._engine
292
+ if native is None:
293
+ return
294
+ self._engine = None
295
+ events, latest, time_ns, after = native.close()
296
+ if not keep_events:
297
+ return
298
+ self._time_ns = time_ns
299
+ self._circuit_events = []
300
+ self._events_by_port = {}
301
+ for event_time_ns, seq, port, value in events:
302
+ event = CircuitEvent(event_time_ns)
303
+ event._time_ns = event_time_ns
304
+ event._port = port # type: ignore[assignment]
305
+ event._value = value
306
+ # In the order of the native heap, which is the same heap
307
+ self._circuit_events.append(event)
308
+ if latest.get(id(port)) == seq:
309
+ self._events_by_port[port] = event # type: ignore[index]
310
+ for call in after:
311
+ call()
312
+
313
+ def _native_engine(self) -> Any:
314
+ """The native engine, if the circuit has one and its wires haven't changed"""
315
+ native = self._engine
316
+ if native is not None and native.generation != connection_generation.value:
317
+ self._stop_engine()
318
+ return None
319
+ return None if native is None else native.engine
320
+
321
+ def process_single_event(self, stop_time_ns: int | None = None) -> tuple[bool, bool]:
322
+ """
323
+ Process only the next event, to step through a simulation.
324
+
325
+ Args:
326
+ stop_time_ns: Don't process an event after this time, keep it for later.
327
+
328
+ Returns:
329
+ If an event was processed (False if there were none, or the next one is after
330
+ stop_time_ns), and if it was on a port of a top-level component, rather than
331
+ inside one like a Yosys component.
332
+ """
333
+ engine = self._native_engine()
334
+ if engine is not None:
335
+ processed, toplevel = engine.process_single_event(stop_time_ns, self._vcd)
336
+ self._time_ns = engine.time
337
+ return processed, toplevel
338
+ events = self._circuit_events
339
+ events_by_port = self._events_by_port
340
+ while events:
341
+ event = heapq.heappop(events)
342
+ port = event._port
343
+ latest = events_by_port.get(port)
344
+ if latest is not event and (
345
+ latest is None
346
+ or latest._time_ns != event._time_ns
347
+ or latest._value != event._value
348
+ ):
349
+ # A stale event, a later event for the same port replaced it
350
+ continue
351
+ if stop_time_ns is not None and event._time_ns > stop_time_ns:
352
+ # Put the event back if it's after the stop time
353
+ heapq.heappush(events, event)
354
+ return False, False
355
+ del events_by_port[port]
356
+ self._time_ns = event._time_ns
357
+ port.delta_cycle(event._value)
358
+ if self._vcd is not None:
359
+ self._vcd.write(port, self._time_ns)
360
+ return True, port.parent().is_toplevel()
361
+ return False, False
362
+
363
+ def run(
364
+ self,
365
+ s: float | None = None,
366
+ ms: float | None = None,
367
+ us: float | None = None,
368
+ ns: float | None = None,
369
+ single_step: bool = False,
370
+ ) -> bool:
371
+ """
372
+ Run the simulation for a period of time. The times are added together, so
373
+ run(ms=1, us=500) runs for 1.5 ms.
374
+
375
+ Args:
376
+ s: Seconds.
377
+ ms: Milliseconds.
378
+ us: Microseconds.
379
+ ns: Nanoseconds.
380
+ single_step: Stop after the first event on a port of a top-level component,
381
+ at the end of its time (the GUI's Single Step).
382
+
383
+ Returns:
384
+ True if the run stopped for a single step.
385
+ """
386
+ native = self._engine
387
+ if native is not None and native.generation == connection_generation.value:
388
+ # The native engine: it runs to the stop time (also after its last event)
389
+ engine = native.engine
390
+ if s is None and ms is None and us is None and ns is not None:
391
+ stop_time_ns = engine.time + round(ns)
392
+ else:
393
+ stop_time_ns = engine.time + self._time_to_ns(s=s, ms=ms, us=us, ns=ns)
394
+ vcd = self._vcd
395
+ single_step_stop = engine.run(stop_time_ns, single_step, vcd)
396
+ self._time_ns = engine.time
397
+ if vcd is not None:
398
+ vcd.flush()
399
+ return bool(single_step_stop)
400
+ stop_time_ns = self.time_ns + self._time_to_ns(s=s, ms=ms, us=us, ns=ns)
401
+ engine = self._native_engine()
402
+ if engine is not None:
403
+ single_step_stop = engine.run(stop_time_ns, single_step, self._vcd)
404
+ self._time_ns = max(engine.time, stop_time_ns)
405
+ engine.time = self._time_ns
406
+ if self._vcd is not None:
407
+ self._vcd.flush()
408
+ return bool(single_step_stop)
409
+ single_step_stop = False
410
+ # The loop in process_single_event(), inlined since it runs for every event
411
+ events = self._circuit_events
412
+ events_by_port = self._events_by_port
413
+ heappop = heapq.heappop
414
+ vcd = self._vcd
415
+ while events and self._time_ns <= stop_time_ns:
416
+ event = heappop(events)
417
+ port = event._port
418
+ latest = events_by_port.get(port)
419
+ if latest is not event and (
420
+ latest is None
421
+ or latest._time_ns != event._time_ns
422
+ or latest._value != event._value
423
+ ):
424
+ # A stale event, a later event for the same port replaced it
425
+ continue
426
+ time_ns = event._time_ns
427
+ if time_ns > stop_time_ns:
428
+ # Put the event back if it's after the stop time
429
+ heapq.heappush(events, event)
430
+ break
431
+ del events_by_port[port]
432
+ self._time_ns = time_ns
433
+ port.delta_cycle(event._value)
434
+ if vcd is not None:
435
+ vcd.write(port, time_ns)
436
+ if single_step and port.parent().is_toplevel():
437
+ # Finish the events at this time, then stop
438
+ stop_time_ns = time_ns
439
+ single_step_stop = True
440
+ self._time_ns = max(self._time_ns, stop_time_ns)
441
+ if vcd is not None:
442
+ vcd.flush()
443
+ return single_step_stop
444
+
445
+ def run_within(
446
+ self,
447
+ seconds: float,
448
+ s: float | None = None,
449
+ ms: float | None = None,
450
+ us: float | None = None,
451
+ ns: float | None = None,
452
+ single_step: bool = False,
453
+ ) -> RunResult:
454
+ """
455
+ Run the simulation like run(), but for at most a time on the clock: a circuit that
456
+ oscillates makes so many events that a run could take minutes. It runs slices of
457
+ the time with run(), and stops after the slice that takes it past the limit. The
458
+ events are the same as with one run(), only where it stops can be earlier.
459
+
460
+ Args:
461
+ seconds: The most time on the clock it runs (a slice can take more).
462
+ s: Seconds of simulated time.
463
+ ms: Milliseconds.
464
+ us: Microseconds.
465
+ ns: Nanoseconds.
466
+ single_step: Stop after the first event on a port of a top-level component,
467
+ like run().
468
+
469
+ Returns:
470
+ If it stopped for a single step, and if it ran all the time.
471
+ """
472
+ stop_time_ns = self.time_ns + self._time_to_ns(s=s, ms=ms, us=us, ns=ns)
473
+ deadline = time.perf_counter() + seconds
474
+ while self.time_ns < stop_time_ns:
475
+ start = time.perf_counter()
476
+ step_ns = min(self._slice_ns, stop_time_ns - self.time_ns)
477
+ if self.run(ns=step_ns, single_step=single_step):
478
+ return RunResult(single_step=True, complete=True)
479
+ now = time.perf_counter()
480
+ # Longer slices while they are fast, shorter when they are slow
481
+ if now - start < seconds / 20:
482
+ self._slice_ns = min(MAX_SLICE_NS, self._slice_ns * 2)
483
+ elif now - start > seconds / 5:
484
+ self._slice_ns = max(1, self._slice_ns // 2)
485
+ if now >= deadline and self.time_ns < stop_time_ns:
486
+ return RunResult(single_step=False, complete=False)
487
+ return RunResult(single_step=False, complete=True)
488
+
489
+ def restart_slices(self) -> None:
490
+ """
491
+ Start run_within() with a short slice again, like after an input changed: it can
492
+ start an oscillation, which a long slice would run for long
493
+ """
494
+ self._slice_ns = START_SLICE_NS
495
+
496
+ def oscillating_ports(
497
+ self, ns: int = 200, changes: int = 10, max_seconds: float | None = None
498
+ ) -> list[Port]:
499
+ """
500
+ The ports of the top-level components that oscillate: it runs the simulation for a
501
+ while, a nanosecond at a time, and counts how often each output changes. A port
502
+ that changes at least 'changes' times in 'ns' nanoseconds oscillates. Run it while
503
+ the inputs of the circuit don't change. The ones that change the most come first.
504
+
505
+ Args:
506
+ ns: How long it runs, in nanoseconds.
507
+ changes: How many changes make an oscillation.
508
+ max_seconds: Stop after this long on the clock, with the changes counted so
509
+ far, in a circuit where a nanosecond takes long.
510
+ """
511
+ ports = [
512
+ port
513
+ for component in self.get_toplevel_components()
514
+ for port in component.ports
515
+ if port.is_output()
516
+ ]
517
+ counts = dict.fromkeys(ports, 0)
518
+ values = [port.value for port in ports]
519
+ deadline = None if max_seconds is None else time.perf_counter() + max_seconds
520
+ for _ in range(ns):
521
+ if deadline is not None and time.perf_counter() > deadline:
522
+ break
523
+ self.run(ns=1)
524
+ for number, port in enumerate(ports):
525
+ value = port.value
526
+ if value != values[number]:
527
+ counts[port] += 1
528
+ values[number] = value
529
+ found = [port for port in ports if counts[port] >= changes]
530
+ return sorted(found, key=lambda port: -counts[port])
531
+
532
+ def run_until(
533
+ self,
534
+ s: float | None = None,
535
+ ms: float | None = None,
536
+ us: float | None = None,
537
+ ns: float | None = None,
538
+ ) -> None:
539
+ """
540
+ Run the simulation until an absolute time, nothing happens if it has passed.
541
+ The times are added together.
542
+
543
+ Args:
544
+ s: Seconds.
545
+ ms: Milliseconds.
546
+ us: Microseconds.
547
+ ns: Nanoseconds.
548
+ """
549
+ stop_time_ns = self._time_to_ns(s=s, ms=ms, us=us, ns=ns)
550
+ if stop_time_ns >= self.time_ns:
551
+ self.run(ns=stop_time_ns - self.time_ns)
552
+
553
+ def run_until_edge(
554
+ self,
555
+ rising: Clock | Port | None = None,
556
+ falling: Clock | Port | None = None,
557
+ max_ns: int = 1_000_000_000,
558
+ ) -> bool:
559
+ """
560
+ Run the simulation through the next rising (or falling) edge of a clock or a port,
561
+ to drive a simulation by its clock instead of setting a clock port:
562
+
563
+ circuit.init()
564
+ circuit.run_until_edge(rising=clock) # The flip-flops have their new values
565
+ counter.up.value = 0 # Set inputs for the next edge
566
+ circuit.run_until_edge(rising=clock)
567
+
568
+ With a Clock (or its output), the run stops just before the clock's next edge,
569
+ half a period later, so that what the edge started has settled. With another port,
570
+ it stops after the events at the time of the edge (the port went from 0 to 1, or
571
+ from 1 to 0).
572
+
573
+ Args:
574
+ rising: The clock or port of a rising edge.
575
+ falling: The clock or port of a falling edge (instead of rising).
576
+ max_ns: The most time it runs to find the edge of a port.
577
+
578
+ Returns:
579
+ If there was an edge (False if a port had none in max_ns).
580
+
581
+ Raises:
582
+ CircuitError: Without one of rising and falling.
583
+ DigsimException: If the clock doesn't run (before init()).
584
+ """
585
+ if (rising is None) == (falling is None):
586
+ raise CircuitError("run_until_edge() needs rising or falling, one of them")
587
+ target = rising if rising is not None else falling
588
+ level = 1 if rising is not None else 0
589
+ assert target is not None
590
+ if isinstance(target, Port):
591
+ parent = target.parent()
592
+ if isinstance(parent, Clock) and target is parent.port("O"):
593
+ target = parent
594
+ if isinstance(target, Clock):
595
+ stop_ns = target.next_edge_ns(rising=level == 1) + target.half_period_ns - 1
596
+ time_ns = self.time_ns
597
+ if stop_ns >= time_ns:
598
+ self.run(ns=stop_ns - time_ns)
599
+ return True
600
+ limit = self.time_ns + max_ns
601
+ old = target.value
602
+ while True:
603
+ processed, _ = self.process_single_event(stop_time_ns=limit)
604
+ if not processed:
605
+ self.run_until(ns=limit)
606
+ return False
607
+ new = target.value
608
+ if old == 1 - level and new == level:
609
+ # The other events at the time of the edge
610
+ self.run_until(ns=self.time_ns)
611
+ return True
612
+ old = new
613
+
614
+ def next_event_ns(self, port: EventPort) -> int | None:
615
+ """The time of the next event of a port, None if it has none"""
616
+ native = self._engine
617
+ if native is not None and native.generation == connection_generation.value:
618
+ return native.next_event_ns(port)
619
+ event = self._events_by_port.get(port)
620
+ return None if event is None else event._time_ns
621
+
622
+ def delay_changed(self, port: PortOutDelta) -> None:
623
+ """A port got a new delay, see PortOutDelta.set_delay_ns()"""
624
+ if self._engine is not None:
625
+ self._engine.delay_changed(port)
626
+
627
+ def add_event(self, port: EventPort, value: VALUE_TYPE, propagation_delay_ns: int) -> None:
628
+ """Add an event for a port, used by the components"""
629
+ native = self._engine
630
+ if native is not None:
631
+ if native.generation == connection_generation.value:
632
+ nid = getattr(port, "_nid", None)
633
+ if nid is None:
634
+ nid = native.nid(port)
635
+ native.engine.add_event(nid, value, propagation_delay_ns)
636
+ return
637
+ self._stop_engine()
638
+ event_time_ns = self._time_ns + propagation_delay_ns
639
+ # Set without an __init__, to save a Python call for every event
640
+ event = CircuitEvent(event_time_ns)
641
+ event._time_ns = event_time_ns
642
+ event._port = port
643
+ event._value = value
644
+ self._events_by_port[port] = event
645
+ heapq.heappush(self._circuit_events, event)
646
+
647
+ def add_component(self, component: Component) -> None:
648
+ """Add a component to the circuit, components do it when they are created"""
649
+ name_id = 1
650
+ namebase = component.name()
651
+ while component.name() in self._components:
652
+ component.set_name(f"{namebase}_{name_id}", update_circuit=False)
653
+ name_id += 1
654
+ self._components[component.name()] = component
655
+
656
+ def change_component_name(self, component: Component, name: str) -> None:
657
+ """Change component name"""
658
+ comp = self._components[component.name()]
659
+ del self._components[component.name()]
660
+ other = self._components.get(name)
661
+ if other is not None and comp.is_toplevel() and not other.is_toplevel():
662
+ # The name of a part of another component (like a gate of an SR) is not saved,
663
+ # the part gets another name: the wires of a loaded file are to the component
664
+ del self._components[name]
665
+ comp.set_name(name, update_circuit=False)
666
+ self._components[name] = comp
667
+ self.add_component(other)
668
+ return
669
+ comp.set_name(name, update_circuit=False)
670
+ self.add_component(comp)
671
+
672
+ def get_component(self, component_name: str) -> Component:
673
+ """
674
+ Get a component by its name.
675
+
676
+ Raises:
677
+ CircuitError: If the circuit has no component with the name.
678
+ """
679
+ comp = self._components.get(component_name)
680
+ if comp is not None:
681
+ return comp
682
+ raise CircuitError(f"Component '{component_name}' not found")
683
+
684
+ def to_dataclass(self, folder: str = ".") -> CircuitDataClass:
685
+ """
686
+ The circuit as a data class, used when saving it.
687
+
688
+ Args:
689
+ folder: File paths, like a Verilog file, are stored relative to this folder.
690
+ """
691
+ if self._name is None:
692
+ raise CircuitError("Circuit must have a name")
693
+ self._folder = folder
694
+ return CircuitDataClass.from_circuit(self)
695
+
696
+ def from_dataclass(
697
+ self,
698
+ circuit_dc: CircuitDataClass,
699
+ folder: str = "",
700
+ component_exceptions: bool = True,
701
+ connect_exceptions: bool = True,
702
+ ) -> list[str]:
703
+ """
704
+ Replace the circuit's components with the ones in a data class.
705
+
706
+ Args:
707
+ circuit_dc: The circuit data class, for example from a loaded file.
708
+ folder: The folder that relative file paths are read from.
709
+ component_exceptions: Raise when a component can't be created, otherwise
710
+ skip it and report it in the returned list.
711
+ connect_exceptions: Raise when a wire can't be connected, otherwise skip it
712
+ and report it in the returned list.
713
+
714
+ Returns:
715
+ The errors for the skipped components and wires.
716
+ """
717
+ self._folder = folder
718
+ self.clear()
719
+
720
+ exception_str_list = []
721
+ for component in circuit_dc.components:
722
+ try:
723
+ with self.adding_components():
724
+ component.create(self)
725
+ except (DigsimException, FileNotFoundError) as exc:
726
+ if component_exceptions:
727
+ raise
728
+ exception_str_list.append(f"{exc.__class__.__name__}:{exc!s}")
729
+ for wire in circuit_dc.wires:
730
+ try:
731
+ wire.connect(self)
732
+ except DigsimException as exc:
733
+ if connect_exceptions:
734
+ raise
735
+ exception_str_list.append(f"{exc.__class__.__name__}:{exc!s}")
736
+
737
+ return exception_str_list
738
+
739
+ def to_json_file(self, filename: str | Path) -> None:
740
+ """
741
+ Save the circuit in a JSON file. File paths in it, like a Verilog file, are stored
742
+ relative to the file's folder. The circuit needs a name.
743
+ """
744
+ circuitfile_dc = CircuitFileDataClass(
745
+ circuit=self.to_dataclass(str(Path(filename).parent))
746
+ )
747
+ circuitfile_dc.save(filename)
748
+
749
+ def from_json_file(self, filename: str | Path, folder: str | None = None) -> None:
750
+ """
751
+ Load a circuit from a JSON file, replacing the circuit's components.
752
+
753
+ Args:
754
+ filename: The file.
755
+ folder: The folder that relative file paths in the file are read from, by
756
+ default the file's folder (where to_json_file() stores them relative to).
757
+ """
758
+ file_dc = CircuitFileDataClass.load(filename)
759
+ if folder is None:
760
+ folder = str(Path(filename).parent)
761
+ self.from_dataclass(file_dc.circuit, folder)
762
+ # A GUI circuit file has the connections in its lines
763
+ for line in file_dc.lines:
764
+ line.connect(self)