Skip to content

Python Circuits

Everything you can build in the GUI can also be built in Python. This is useful for automated tests of a design, for generating waveforms, or for mixing a simulated circuit with ordinary Python code.

Install DigSim into a virtual environment first, see Installation. The runnable examples referenced on this page are in the examples folder of the repository. Run them from the repository root.

A first circuit

This example connects two push buttons to an SR latch and an LED, and writes all signals to sr.vcd (examples/example_sr.py):

from digsim.circuit import Circuit
from digsim.circuit.components import SR, Led, PushButton


def led_callback(comp):
    state = "ON" if comp.ports[0].value == 1 else "OFF"
    print(f"{comp.circuit.time_ns:9}: LED '{comp.name()}' is {state}")


circuit = Circuit(vcd="sr.vcd")

set_button = PushButton(circuit, "S-Button")
reset_button = PushButton(circuit, "R-Button")
latch = SR(circuit)
led = Led(circuit, "D1", callback=led_callback)

set_button.O.wire = latch.S
reset_button.O.wire = latch.R
latch.Q.wire = led.I

circuit.init()
circuit.run(ms=10)

set_button.push()
circuit.run(ms=10)
set_button.release()
circuit.run(ms=10)

circuit.vcd_close()

Run it and look at the result:

python examples/example_sr.py
gtkwave sr.vcd

Concepts

The circuit

Circuit holds all components and the simulation time.

Method Description
Circuit(name=None, vcd=None) Create a circuit, optionally writing a VCD file
init() Initialize the circuit, after adding and connecting components
run(s=, ms=, us=, ns=) Run the simulation for a period of time
run_until(s=, ms=, us=, ns=) Run the simulation until an absolute time
run_until_edge(rising=clock) / (falling=clock) Run through the next edge of a Clock, to just before its next edge (the logic has settled), to drive a test bench by its clock. With a port instead of a clock, run to the edge of the port.
run_within(seconds, s=, ms=, us=, ns=) Run like run(), but for at most seconds on the clock, see Oscillating circuits
oscillating_ports(ns=200) The output ports of the top-level components that oscillate
process_single_event(stop_time_ns=None) Process only the next event, to step through a simulation. Returns two booleans: if an event was processed (not if there were none, or the next one is after stop_time_ns), and if it was on a port of a top-level component rather than inside one, like a Yosys component.
time_ns The current simulation time in nanoseconds
get_component(name) Look up a component by name
vcd(filename, timescale="1 ns") / vcd_close() Start or finish writing a VCD file, timescale is the time of a simulated nanosecond in the file
to_json_file(filename) Save the circuit. File paths in it, like a Verilog file, are stored relative to the file.
from_json_file(filename, folder=None) Load a circuit, also a circuit file saved by the GUI, with the connections of its wires. Relative file paths in it are read from the file's folder, or from folder if it is given.

Oscillating circuits

A circuit that oscillates, like a ring of gates, makes an event every nanosecond or so, and a run() of a few milliseconds can then take minutes. run_within() runs for at most a time on the clock, and says if it ran all of the time:

result = circuit.run_within(0.5, ms=50)
if not result.complete:
    for port in circuit.oscillating_ports():
        print(f"{port.parent().name()}.{port.name()} oscillates")

It runs the same events as run(), in slices of the time, so a run that is continued with more calls has the same events as one long run. oscillating_ports() runs the circuit for a short while, 200 ns by default, and counts how often each output changes.

Simulation engines

DigSim simulates with its native engine, digsim-native, which is installed with DigSim on Linux (x86_64 and arm64), Windows and macOS. Elsewhere, or with DIGSIM_ENGINE=python, it simulates in Python. Both give the same settled values.

The native engine simulates a Verilog (Yosys) component as one compiled block, like a compiled simulator: its cells are evaluated in order, once each when an input changes, without delays between them, so its outputs change 1 ns after an input. This makes it 50 to 100 times faster than the Python engine. The other components, and a clock without a GUI, work as in Python. A VCD file therefore shows no delays and no glitches inside a Verilog component, and is not the same as with the Python engine. With DIGSIM_BLOCKS=0 the native engine simulates every cell with its delay, and writes the same VCD file as Python. A netlist with a combinational loop, tristate buffers or inout ports always keeps its cells and their delays.

Components and ports

Components live in digsim.circuit.components. Each component is created with the circuit as its first argument and an optional name. Ports are attributes on the component, for example latch.S or led.I.

Connect an output port to an input port by assigning to .wire:

button.O.wire = gate.A

Read a port's current value with .value. Inputs that are not driven by another component can be set directly, which is handy in testbenches:

dut.clk.value = 1
circuit.run(ms=1)
print(dut.cnt.value)

A clock input is simpler to drive with a Clock. circuit.run_until_edge(rising=clock) runs through the next rising edge of the clock to just before its falling edge, when the logic after the edge has settled, and inputs set then are there at the next edge:

clock = Clock(circuit, frequency=500)
clock.O.wire = dut.clk
circuit.init()
for _ in range(10):
    circuit.run_until_edge(rising=clock)
    print(dut.cnt.value)

Several outputs can drive the same input. It then has the value that they drive, and "X" (undefined) if they drive different values or one of them drives "X". A tristate output, like the output of a TristateBuffer or a Verilog output that can be 'bz, is "Z" (high impedance) when it doesn't drive, and the other outputs decide:

first.Y.wire = led.I
second.Y.wire = led.I  # Both are TristateBuffer outputs
button.O.wire = led.I  # Its value, unless an enabled buffer drives another one

An inout port of a Verilog component is both an output and an input, see Inout ports. Two of them on one bus drive each other: a.data.wire = b.data and b.data.wire = a.data.

Interactive components have methods for controlling them, such as PushButton.push() and .release(). Output components such as Led accept a callback that is called whenever their value changes.

The available components are:

Category Components
Inputs PushButton, OnOffSwitch, DipSwitch, Clock, StaticValue, VDD, GND
Outputs Led, LedBar, HexDigit, SevenSegment, HD44780, Buzzer, LogicAnalyzer
Gates AND, OR, NOT, XOR, XNOR, NAND, NOR, MUX, Decoder, Demultiplexer
Flip-flops DFF, SR, FlipFlop, SRFF, ClockedSRFF, ClockedJKFF, ClockedTFF, Counter
Arithmetic Adder, Subtractor, Multiplier, Comparator, Negator
Buses Bus2Wires, Wires2Bus, Splitter, TristateBuffer, LabelWireIn, LabelWireOut
Memory RAM, ROM, MemStdOut
Circuit ports CircuitInput, CircuitOutput, CircuitInOut, SubCircuit
Complex IntegratedCircuit, VerilogComponent

Verilog components

A VerilogComponent can be created straight from a Verilog file or from a Yosys JSON netlist (it is a YosysComponent, the name the GUI saves). Its ports get the names of the Verilog module's ports (examples/yosys_counter):

from digsim.circuit import Circuit
from digsim.circuit.components import VDD, PushButton, VerilogComponent

circuit = Circuit(vcd="counter.vcd")
counter = VerilogComponent(circuit, path="examples/yosys_counter/counter.v")
clk = PushButton(circuit, "clk")
vdd = VDD(circuit)

clk.O.wire = counter.clk
vdd.wire = counter.up

circuit.init()

A file with several modules makes a component of its top module, the one that no other module instantiates. module="half_adder" chooses another module, also when the file has several top modules. See Verilog and Yosys for more about synthesis.

Subcircuits

A circuit file can be used as a component of another circuit: a SubCircuit. Its ports are the circuit ports of the file, CircuitInput, CircuitOutput and CircuitInOut, named by their labels, in the order they are in the file from top to bottom. The components of the file are parts of the subcircuit, connected like in the file:

from digsim.circuit import Circuit
from digsim.circuit.components import AND, XOR, CircuitInput, CircuitOutput, SubCircuit

half_adder = Circuit(name="half_adder")
a = CircuitInput(half_adder, label="a")
b = CircuitInput(half_adder, label="b")
s = CircuitOutput(half_adder, label="s")
c = CircuitOutput(half_adder, label="c")
xor = XOR(half_adder)
carry = AND(half_adder)
for gate in (xor, carry):
    a.port("a").wire = gate.A
    b.port("b").wire = gate.B
xor.Y.wire = s.port("s")
carry.Y.wire = c.port("c")
half_adder.to_json_file("half_adder.circuit")

circuit = Circuit()
adder = SubCircuit(circuit, "half_adder.circuit")
print(adder.interface())  # {'a': ('in', 1), 'b': ('in', 1), 'c': ('out', 1), 's': ('out', 1)}

A subcircuit can use other subcircuits, their files relative to its file, but not itself. reload() builds the parts again after the file has changed, with the same ports.

Testbenches with pytest

Because circuits are plain Python, a Verilog design can be tested with pytest: synthesize the design in a fixture, then drive its inputs and assert on its outputs. See Verilog Testbench with pytest.

More examples

See Python Examples for a walkthrough of every example, with circuit diagrams, expected output and waveforms.

Example Shows
example_sr.py Buttons, an SR latch, an LED callback and VCD output
example_clock.py Using a clock component
load_save Saving and loading circuits as JSON
synthesis Running Yosys synthesis from Python
yosys_counter A Verilog counter, from a netlist or straight from Verilog
yosys_6502 A synthesized 6502 CPU running a program from memory
yosys_fsm A SystemVerilog state machine, with the names of its states in the VCD file
pytest_tb pytest testbenches for Verilog designs