Note
Go to the end to download the full example code.
Threshold gating with comparisons and shared selectors¶
Process two samples per iteration. For each sample, compare it with a threshold and select either the sample or zero. A third output counts how many of the two samples exceeded the threshold. This gives algorithm, boolean, and integer data paths in one statically scheduled architecture.
The two comparisons share one comparison PE and the two selects share one select PE. Stored values are assigned to separate memories according to their logical types.
import matplotlib.pyplot as plt
import numpy as np
from b_asic import (
SFG,
Addition,
Architecture,
Comparison,
Constant,
Input,
Output,
Schedule,
Select,
SignalType,
Simulation,
assign_processing_elements_and_memories,
)
Build the algorithm¶
Comparison(">", ...) is the configurable equivalent of GreaterThan.
Its inputs use the algorithm type, while its result uses boolean
storage and can also feed the integer counter. A select consumes the condition on
input 0 and algorithm values on inputs 1 and 2.
Both data branches are evaluated; only the selected value reaches the output.
threshold = Constant(0.5, name="threshold")
zero = Constant(0, name="zero")
inputs = [Input(name=f"x{i}", signal_type=SignalType.ALGORITHM) for i in range(2)]
conditions = [
Comparison(">", source, threshold, name=f"above{i}")
for i, source in enumerate(inputs)
]
selected = [
Select(condition, source, zero, name=f"gate{i}")
for i, (condition, source) in enumerate(zip(conditions, inputs, strict=True))
]
Add the two boolean results directly as integer zero/one. The integer path is independent of the algorithm’s eventual numeric representation.
count = Addition(*conditions, name="count")
sfg = SFG(
inputs,
[
Output(selected[0], name="y0"),
Output(selected[1], name="y1"),
Output(count, name="n"),
],
name="Two-sample threshold gate",
)
assert sfg.output(0).signal_type is SignalType.ALGORITHM
assert sfg.output(2).signal_type is SignalType.INTEGER
sfg # noqa: B018 - Sphinx-Gallery captures the graph.

Verify the outputs, including the strict threshold boundary: a sample equal to 0.5 is replaced with zero and is not counted.
samples = np.array([[-1.0, 0.5, 1.5, 2.0], [0.5, 3.0, 0.75, -0.25]])
simulation = Simulation(sfg, samples)
simulation.run()
actual = np.array(
[simulation.results[operation.graph_id] for operation in sfg.output_operations]
)
expected = np.vstack((np.where(samples > 0.5, samples, 0), (samples > 0.5).sum(axis=0)))
np.testing.assert_array_equal(actual, expected)
print("Gated samples and number passing per pair:")
print(actual)
Gated samples and number passing per pair:
[[0. 0. 1.5 2. ]
[0. 3. 0.75 0. ]
[0. 1. 2. 1. ]]
Schedule shared hardware¶
Give comparisons, selects, and the integer adder one cycle of latency and one cycle of execution time. The explicit schedule below processes a new pair every ten cycles. Each comparison and each select executes in a separate cycle, so a single PE of each kind is sufficient.
The first condition is ready at cycle 2 and used by its select at cycle 4. The second condition follows one cycle later. Integer indicators are stored until the addition at cycle 6. These lifetimes exercise all three memory types.
for operation_type in (Comparison, Select, Addition):
sfg.set_latency_of_type(operation_type, 1)
sfg.set_execution_time_of_type(operation_type, 1)
start_by_name = {
"threshold": 0,
"zero": 0,
"x0": 0,
"x1": 1,
"above0": 1,
"above1": 2,
"gate0": 4,
"gate1": 5,
"count": 6,
"y0": 7,
"y1": 8,
"n": 9,
}
schedule = Schedule(
sfg,
start_times={
operation.graph_id: start_by_name[operation.name]
for operation in sfg.operations
},
laps={},
schedule_time=10,
cyclic=True,
)
fig, ax = plt.subplots(figsize=(10, 6), layout="constrained")
schedule.plot(ax)
ax.set_title("Two samples per ten-cycle period")

Map to an architecture¶
Use the greedy mux-minimizing assignment, which needs no optional solver. Each RAM has two read ports and one write port. The assignment enforces logical type compatibility even when different values have nonoverlapping accesses. Zero-lifetime transfers, if any, are passed as direct interconnects.
pes, memories, direct = assign_processing_elements_and_memories(
schedule,
strategy="greedy_min_mux",
resources={"cmp": 1, "select": 1, "add": 1, "in": 1, "out": 2},
memory_read_ports=2,
memory_write_ports=1,
memory_total_ports=3,
strat_params={"seed": 0},
)
arch = Architecture(
pes, memories, entity_name="threshold_gate", direct_interconnects=direct
)
arch.validate_ports()
assert {memory.signal_type for memory in memories} == {
SignalType.ALGORITHM,
SignalType.BOOLEAN,
SignalType.INTEGER,
}
for operation_type in (Comparison, Select):
assert sum(pe.operation_type is operation_type for pe in pes) == 1
Inspect the mapping. Each PE signature lists its input and output types. In particular, the shared select PE has a boolean condition port and two algorithm data ports; the shared comparator has algorithm inputs and a boolean output. Memories contain only one logical type, including the integer indicators.
print("Processing element: inputs -> outputs; mapped operations")
for pe in sorted(pes, key=lambda resource: resource.entity_name):
input_types, output_types = pe.processes[0].operation.port_types
signature = f"{[kind.value for kind in input_types]} -> {[kind.value for kind in output_types]}"
print(f"{pe.entity_name}: {signature}; {len(pe.processes)}")
print("Memory: logical type; stored variables")
for memory in sorted(memories, key=lambda resource: resource.entity_name):
print(f"{memory.entity_name}: {memory.signal_type.value}; {len(memory.collection)}")
print(
"Interconnect mux inputs:", arch.get_multiplexer_input_count(multiplexed_only=True)
)
Processing element: inputs -> outputs; mapped operations
add0: ['integer', 'integer'] -> ['integer']; 1
c0: [] -> ['algorithm']; 1
c1: [] -> ['algorithm']; 1
cmp0: ['algorithm', 'algorithm'] -> ['boolean']; 2
in0: [] -> ['algorithm']; 2
out0: ['algorithm'] -> []; 2
out1: ['integer'] -> []; 1
select0: ['boolean', 'algorithm', 'algorithm'] -> ['algorithm']; 2
Memory: logical type; stored variables
memory0: algorithm; 3
memory1: boolean; 2
memory2: algorithm; 2
memory3: algorithm; 1
memory4: integer; 1
Interconnect mux inputs: 2
The architecture drawing includes the interconnect multiplexers needed to feed the shared PEs. These muxes are controlled by the static schedule. The algorithm’s select PE instead chooses a value using the computed condition. Mixed-type VHDL generation is deferred; this example ends at the architecture.
arch # noqa: B018 - Sphinx-Gallery captures the architecture and its multiplexers.

Total running time of the script: (0 minutes 0.337 seconds)