.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples/architecture/comparison_select_architecture.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_examples_architecture_comparison_select_architecture.py: ===================================================== 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. .. GENERATED FROM PYTHON SOURCE LINES 16-35 .. code-block:: Python 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, ) .. GENERATED FROM PYTHON SOURCE LINES 36-44 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. .. GENERATED FROM PYTHON SOURCE LINES 44-57 .. code-block:: Python 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)) ] .. GENERATED FROM PYTHON SOURCE LINES 58-60 Add the two boolean results directly as integer zero/one. The integer path is independent of the algorithm's eventual numeric representation. .. GENERATED FROM PYTHON SOURCE LINES 60-75 .. code-block:: Python 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. .. image-sg:: /examples/architecture/images/sphx_glr_comparison_select_architecture_001.png :alt: comparison select architecture :srcset: /examples/architecture/images/sphx_glr_comparison_select_architecture_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 76-78 Verify the outputs, including the strict threshold boundary: a sample equal to 0.5 is replaced with zero and is not counted. .. GENERATED FROM PYTHON SOURCE LINES 78-90 .. code-block:: Python 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) .. rst-class:: sphx-glr-script-out .. code-block:: none Gated samples and number passing per pair: [[0. 0. 1.5 2. ] [0. 3. 0.75 0. ] [0. 1. 2. 1. ]] .. GENERATED FROM PYTHON SOURCE LINES 91-103 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. .. GENERATED FROM PYTHON SOURCE LINES 103-136 .. code-block:: Python 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") .. image-sg:: /examples/architecture/images/sphx_glr_comparison_select_architecture_002.png :alt: Two samples per ten-cycle period :srcset: /examples/architecture/images/sphx_glr_comparison_select_architecture_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 137-144 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. .. GENERATED FROM PYTHON SOURCE LINES 144-166 .. code-block:: Python 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 .. GENERATED FROM PYTHON SOURCE LINES 167-171 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. .. GENERATED FROM PYTHON SOURCE LINES 171-184 .. code-block:: Python 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) ) .. rst-class:: sphx-glr-script-out .. code-block:: none 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 .. GENERATED FROM PYTHON SOURCE LINES 185-189 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. .. GENERATED FROM PYTHON SOURCE LINES 189-191 .. code-block:: Python arch # noqa: B018 - Sphinx-Gallery captures the architecture and its multiplexers. .. image-sg:: /examples/architecture/images/sphx_glr_comparison_select_architecture_003.png :alt: comparison select architecture :srcset: /examples/architecture/images/sphx_glr_comparison_select_architecture_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.337 seconds) .. _sphx_glr_download_examples_architecture_comparison_select_architecture.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: comparison_select_architecture.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: comparison_select_architecture.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: comparison_select_architecture.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_