b_asic.sfg

B-ASIC Signal Flow Graph Module.

Contains the signal flow graph operation.

class b_asic.sfg.GraphIDGenerator(id_number_offset: GraphIDNumber = 0)

Bases: object

Generates Graph IDs for objects.

property id_number_offset: GraphIDNumber

Get the graph id number offset of this generator.

next_id(type_name: TypeName, used_ids: MutableSet = {}) → GraphID

Get the next graph id for a certain graph id type.

class b_asic.sfg.SFG(inputs: Input | Sequence[Input] | None = None, outputs: Output | Sequence[Output] | None = None, input_signals: Sequence[Signal] | None = None, output_signals: Sequence[Signal] | None = None, id_number_offset: GraphIDNumber = 0, name: str = '', input_sources: Sequence[SignalSourceProvider | None] | None = None)

Bases: AbstractOperation

Construct an SFG given its inputs and outputs.

Contains a set of connected operations, forming a new operation. Used as a base for simulation, scheduling, etc.

Inputs/outputs may be specified using either Input/Output operations directly with the inputs/outputs parameters, or using signals with the input_signals/output_signals parameters. If signals are used, the corresponding Input/Output operations will be created automatically.

The id_number_offset parameter specifies what number graph IDs will be offset by for each new graph component type. IDs start at 1 by default, so the default offset of 0 will result in IDs like “c1”, “c2”, etc. while an offset of 3 will result in “c4”, “c5”, etc.

Parameters:
inputsInput or sequence of Input, optional
outputsOutput or sequence of Output, optional
input_signalsarray of Signal, optional
output_signalsarray of Signal, optional
id_number_offsetGraphIDNumber, optional
nameName, optional
input_sources
complex_to_real(operations: type[Operation] | GraphID | Iterable[type[Operation] | GraphID] | None = None, **kwargs) → SFG

Return an independent real-arithmetic version of this complex SFG.

Inputs and outputs are ordered real0, imag0, real1, imag1, .... Nested graphs and composite operations are expanded. Delay initial values are split, preserving feedback. Operations marked real_valued=True use only real inputs; imaginary inputs terminate at Sinks and imaginary outputs are zero constants.

Parameters:
operationsOperation type, GraphID, or iterable of either, optional

Convert all operations if None. Otherwise convert only matching types (including subclasses) or graph IDs. Iterators are accepted. Nested operations can be selected by type or hierarchical IDs such as sfg0.mul0. Selecting a nested SFG converts its contents. Unselected operations retain their IDs. Real/complex boundary conversions are inserted as needed and inverse pairs are removed. This permits successive calls with different conversion settings.

multiplication_method{“four”, “three”}, default: “four”

Use four real multiplications, or three with extra additions, for each general complex product, including MAD and MADS.

split_iobool, default: True

Split each external input and output into real/imaginary ports. If False, retain complex Input/Output and MemoryRead/MemoryWrite operations, including their names and memory metadata, and insert ComplexToReal/RealToComplex operations at the graph boundary. Internal arithmetic still uses real signals. With an operation selector, only selected interfaces are split.

**kwargs

All options, including multiplication_method, are forwarded to each operation’s private _complex_to_real hook. Custom operations may define additional options.

Notes

This is an algebraic conversion. Timing and finite-wordlength rounding are not preserved. Real-valued square roots require nonnegative inputs. Unsupported primitives raise NotImplementedError.

property components: list[GraphComponent]

Get all components of this graph in depth-first order.

connect_external_signals_to_components() → bool

Connect any external signals to the internal operations of SFG.

This SFG becomes unconnected to the SFG it is a component off, causing it to become invalid afterwards. Returns True if successful, False otherwise.

constant_propagation(target: type[Operation] | GraphID | Iterable[GraphID] | None = None, *, assume_zero_initial_state: bool = True, decompose: bool = True) → SFG

Return a copy with constant expressions evaluated and propagated.

Operations with all constant inputs are evaluated into one constant per output. Additional algebraic rules repeatedly simplify additions and subtractions with a constant zero input and multiplications with a constant zero input or coefficient. x + 0, 0 + x, and x - 0 become x; 0 - x becomes a negation. A multiplication by zero becomes a constant zero. The rules also apply to AddSub and ConstantMultiplication operations. MAD and MADS pass through their accumulator when the product is zero, and become a multiplication (possibly negated) when the accumulator is zero or disabled. WDF adaptors with zero inputs reduce to arithmetic on the remaining inputs, sharing coefficient multiplications between outputs. Cascaded ConstantMultiplications merge by multiplying their coefficients; a resulting coefficient of one is replaced by direct wiring.

Parameters:
targettype[Operation], GraphID, or iterable of GraphID, optional

Restrict simplification to an operator type (including subclasses), one operation graph ID, or an iterable of operation graph IDs. If omitted, simplify all supported operations. Iterators are consumed once. Unknown IDs raise ValueError; invalid target values raise TypeError. Dead branches are removed after simplification, including unselected operations that no longer feed an output or an explicit Sink.

assume_zero_initial_statebool, default: True

Assume all delays start at zero, overriding their initial values in the returned copy. Prove which feedback signals remain zero and propagate them through all supported operations. A delay driven by a nonzero or time-varying signal is not treated as constant. Set to False to preserve configured initial states and disable this feedback analysis.

decomposebool, default: True

Allow partially simplified operations to become smaller arithmetic networks. If False, only replace operations by constants or direct wiring; retain operations that still require arithmetic, including partially constant WDF adaptors. ConstantMultiplication chains still merge, and identity multipliers are removed, in either mode.

Notes

Input and output ordering and names are preserved, including inputs that become unused. Arithmetic branches that no longer feed an output or an explicit Sink are removed. Sinks and the branches feeding them are retained; use sink_propagation() to remove terminated branches. A constant-fed delay is folded when its initial value matches its input; delays with initial transients remain. The rules apply to operations directly inside this SFG. Each operation supplies its own private _constant_propagation method, returning a replacement SFG with matching port counts or None when no simplification applies.

Scaling of a surviving input is implemented with left/right shifts, preserving input and output scaling order. Imaginary factors are implemented with ImaginaryMultiplication. This is an algebraic transformation intended before scheduling; removed operators’ timing and quantization are not preserved.

copy(*args, **kwargs) → GraphComponent

Get a new instance of this graph component type.

The new instance will have the same name, id, and parameters.

critical_path_time() → int

Return the time of the critical path.

display(info: Literal['none', 'id', 'l1-norm', 'l2-norm'] = 'none', engine: str | None = None, branch_node: bool = True, port_numbering: bool = True, splines: Literal['spline', 'line', 'ortho', 'polyline', 'curved'] = 'spline', input_order: list[GraphID] | None = None, output_order: list[GraphID] | None = None, show_op_params: bool = False, direction: Literal['LR', 'TB'] = 'LR', ranksep: float | None = None, nodesep: float | None = None, size: tuple[float, float] | None = None, force_size: bool = False, fontname: str | None = 'DejaVu Serif', fontsize: float | None = None, *, _interactive: bool = False, colored: bool = False, show_ids: bool = True) → Digraph

Return a Digraph of the SFG.

Can be directly displayed in IPython.

Parameters:
info{“none”, “id”, “l1-norm”, “l2-norm”}, default: “none”
Information to show for each signal in the graph.
  • “none”: Do not show any signal information.

  • “id”: Show the graph_id of each signal.

  • “l1-norm”: Show the L1 norm of the impulse response (worst-case magnitude for inputs in [-1, 1]).

  • “l2-norm”: Show the L2 norm of the impulse response (signal energy for unit-energy inputs).

enginestr, optional

Graphviz layout engine to be used, see https://graphviz.org/documentation/. Most common are “dot” and “neato”. Default is None leading to dot.

branch_nodebool, default: True

Add a branch node in case the fan-out of a signal is two or more.

port_numberingbool, default: True

Show the port number in case the number of ports (input or output) is two or more.

splines{“spline”, “line”, “ortho”, “polyline”, “curved”}, default: “spline”

Spline style, see https://graphviz.org/docs/attrs/splines/ for more info.

input_orderlist of GraphID or operation name, optional

Top-to-bottom ordering of input nodes. Defaults to the SFG’s natural input order.

output_orderlist of GraphID or operation name, optional

Top-to-bottom ordering of output nodes. Defaults to the SFG’s natural output order.

show_op_paramsbool, default: False

Annotate each operation node with its non-default-valued parameters.

direction{“LR”, “TB”}, default: “LR”
Direction of the graph layout.
  • “LR”: Left-to-right (inputs on the left, outputs on the right).

  • “TB”: Top-to-bottom (inputs at the top, outputs at the bottom).

ranksepfloat, optional

Separation between ranks in inches. Default is graphviz’s default (0.5).

nodesepfloat, optional

Minimum separation between nodes in the same rank, in inches. Default is graphviz’s default (0.25).

sizetuple of (float, float), optional

Maximum bounding box of the drawing as (width, height) in inches, e.g. (10, 5).

force_sizebool, default: False

When True, the size bounding box is treated as an exact target and graphviz scales the entire drawing (including fonts) to fill it.

fontnamestr, optional

Font name for all node and edge labels. Defaults to b_asic._preferences.DEFAULT_FONT_FAMILY, None uses Graphviz’s default.

fontsizefloat, optional

Font size (in points) for all node and edge labels. Note: if force_size=True, graphviz will scale fonts along with the rest of the drawing to meet the exact size target.

coloredbool, default: False

Fill input/output, delay, and other operation nodes with distinct colors.

show_idsbool, default: True

Show graph IDs alongside operation names. Unnamed operations always show their graph ID.

edit() → dict[str, SFG]

Edit SFG in GUI.

evaluate(*args, data_type=None) → int | float | complex | DTypeLike | APyFixed | APyCFixed | APyFloat | APyCFloat | list[int | float | complex | DTypeLike | APyFixed | APyCFixed | APyFloat | APyCFloat] | None

Evaluate the operation and generate a list of output values.

Parameters:
*inputs

List of input values.

data_typeDataType, optional

Data type to use for quantization during evaluation.

evaluate_output(index: int, input_values: Sequence[int | float | complex | DTypeLike | APyFixed | APyCFixed | APyFloat | APyCFloat], results: MutableMapping[ResultKey, int | float | complex | DTypeLike | APyFixed | APyCFixed | APyFloat | APyCFloat | None] | None = None, delays: MutableMapping[ResultKey, int | float | complex | DTypeLike | APyFixed | APyCFixed | APyFloat | APyCFloat] | None = None, prefix: str = '', data_type: DataType | None = None) → int | float | complex | DTypeLike | APyFixed | APyCFixed | APyFloat | APyCFloat

Evaluate the output at the given index with the given input values.

Parameters:
indexint

Which output to return the value for.

input_valuesarray of float or complex

The input values.

resultsMutableResultMap, optional

Used to store any results (including intermediate results) for caching.

delaysMutableDelayMap, optional

Used to get the current value of any intermediate delay elements that are encountered, and be updated with their new values.

prefixstr, optional

Used as a prefix for the key string when storing results/delays.

data_typeDataType, optional

Data type to use for quantization during evaluation.

See also

evaluate_outputs, current_output, current_outputs
property expression: str

Get the full (recursively evaluated) expressions defining the SFG.

extract(targets: Iterable[GraphID]) → SFG
find_by_id(graph_id: GraphID) → GraphComponent | None

Find the graph component with the specified ID.

Returns None if the component was not found.

Parameters:
graph_idGraphID

Graph ID of the desired component.

find_by_name(name: str) → Sequence[GraphComponent]

Find all graph components with the specified name.

Returns an empty sequence if no components were found.

Parameters:
nameName

Name of the desired component(s).

find_by_type(component_type: type[GraphComponent]) → list[GraphComponent]

Find all components in this graph with the specified type.

Returns an empty list if no components were found.

Parameters:
component_typetype of GraphComponent

The TypeName of the desired components.

find_by_type_name(type_name: TypeName) → list[GraphComponent]

Find all components in this graph with the specified type name.

Returns an empty list if no components were found.

Parameters:
type_nameTypeName

The TypeName of the desired components.

find_result_keys_by_name(name: str, output_index: int = 0) → Sequence[ResultKey]

Find all graph components with the specified name.

Return a sequence of the keys to use when fetching their results from a simulation.

Parameters:
nameName

Name of the desired component(s).

output_indexint, default: 0

The desired output index to get the result from.

flatten(expand: bool = False) → SFG

Return a new SFG with all sub-SFG operations recursively inlined.

Any operation in this SFG that is itself an SFG will have its internal operations merged into the returned SFG. This is applied recursively until no nested SFGs remain. Sinks and their feeding branches are retained, including branches disconnected from the graph interface.

Parameters:
expandbool, optional

If True, also expand composite operations (e.g. SymmetricTwoportAdaptor) into their primitive sub-operations via their to_sfg() method. Operations whose to_sfg() only wraps themselves (i.e. primitives) are left unchanged.

get_impulse_responses(threshold: float = 1e-12, max_iters: int = -1, all_nodes: bool = False) → dict[str, list[NDArray]]

Return the impulse response for all output ports of all operations in the SFG.

The simulation runs until all output and delay values decay below the threshold. One impulse response is computed for each SFG input.

Parameters:
thresholdfloat, default: 1e-12

The threshold below which output values are considered to have decayed to zero.

all_nodesbool, default: False

If True, impulse responses are collected for all operations. If False, only output operations of the SFG are collected.

max_itersint, default: -1

Maximum number of simulation time steps to prevent infinite loops. If -1, there is no limit.

Returns:
dict[str, list[npt.NDArray]]

Dictionary mapping each operation’s output port key (e.g., “add1.0”, “mul2.0”) to a list of impulse responses (as numpy arrays), one for each SFG input.

get_impulse_responses_from_nodes(nodes: list[GraphID] | None = None, threshold: float = 1e-12, max_iters: int = -1) → dict[str, dict[str, NDArray]]

Return the impulse responses for the specified nodes to the SFG outputs.

Can e.g. be used to compute roundoff noise gains.

The simulation runs until all output and delay values decay below the threshold. Alternatively, a maximum number of iterations can be set to prevent infinite loops.

Parameters:
nodeslist[GraphID], optional

List of operation GraphIDs where impulses should be injected.

thresholdfloat, default: 1e-12

The threshold below which output values are considered to have decayed to zero.

max_itersint, default: -1

Maximum number of simulation time steps to prevent infinite loops. If -1, there is no limit.

Returns:
dict[str, dict[str, npt.NDArray]]

Dictionary mapping each SFG output GraphID (e.g., “out0”, “out1”) to a dictionary that maps operation GraphIDs to their corresponding impulse responses.

get_l1_norms(threshold: float = 1e-12, max_iters: int = -1, all_nodes: bool = False) → dict[str, float]
get_l2_norms(threshold: float = 1e-12, max_iters: int = -1, all_nodes: bool = False) → dict[str, float]
get_operations_topological_order() → Iterable[Operation]

Return operations in evaluation order, treating delays as state sources.

Inputs to delays belong to the next iteration and do not constrain this order. All other operations follow their input sources. Delay states must be updated after evaluating the entire graph. Flatten nested SFGs first when feedback passes through delays inside them.

A cycle without a delay raises RuntimeError. The order is cached.

get_precedence_list() → Sequence[Sequence[OutputPort]]

Return a precedence list of the SFG.

In the precedence list each element in n:th the list consists of elements that are executed in the n:th step. If the precedence list already has been calculated for the current SFG then return the cached version.

get_used_graph_ids() → set[GraphID]

Get a list of all GraphID:s used in the SFG.

get_used_operation_types() → list[type[Operation]]

Get a list of all Operations used in the SFG.

get_used_type_names() → list[TypeName]

Get a list of all TypeNames used in the SFG.

property id_number_offset: GraphIDNumber

Get the graph id number offset of the graph id generator for this SFG.

property input_operations: Sequence[Operation]

Internal input operations in the same order as their respective input ports.

inputs_required_for_output(output_index: int) → Iterable[int]

Return which inputs that the output depends on.

Parameters:
output_indexint

The output index.

Returns:
list[int]

Indices of the SFG inputs required to compute the output at output_index.

insert_operation(component: Operation, output_comp_id: GraphID, port: int | None = None) → SFG

Insert an operation in the SFG after a given source operation.

The source operation output count must match the input count of the operation as well as the output. Then return a new deepcopy of the sfg with the inserted component.

Parameters:
componentOperation

The new component, e.g. Multiplication.

output_comp_idGraphID

The source operation GraphID to connect from. Can use 'id.port' notation to specify a port, e.g. 'sym2p4.1'.

portint, optional

The number of the OutputPort after which the new operation shall be inserted. Overridden by dot notation in output_comp_id.

insert_operation_after(output_comp_id: GraphID, new_operation: Operation, port: int | None = None) → SFG

Insert an operation in the SFG after a given source operation.

Then return a new deepcopy of the sfg with the inserted component.

The graph_id can be an Operation or a Signal. If the operation has multiple outputs, (copies of) the new operation will be inserted on every port. To specify a port use 'graph_id.port_number', e.g., 'sym2p4.1', or the port parameter.

Parameters:
output_comp_idGraphID

The source operation GraphID to connect from. Can use 'id.port' notation to specify a port, e.g. 'sym2p4.1'.

new_operationOperation

The new operation, e.g. Multiplication.

portint, optional

The number of the OutputPort after which the new operation shall be inserted. Overridden by dot notation in output_comp_id.

insert_operation_before(input_comp_id: GraphID, new_operation: Operation, port: int | None = None) → SFG

Insert an operation in the SFG before a given source operation.

Then return a new deepcopy of the sfg with the inserted component.

The graph_id can be an Operation or a Signal. If the operation has multiple inputs, (copies of) the new operation will be inserted on every port. To specify a port use 'graph_id.port_number', e.g., 'sym2p4.1', or the port parameter.

Parameters:
input_comp_idGraphID

The source operation GraphID to connect to. Can use 'id.port' notation to specify a port, e.g. 'sym2p4.0'.

new_operationOperation

The new operation, e.g. Multiplication.

portint, optional

The number of the InputPort before which the new operation shall be inserted. Overridden by dot notation in input_comp_id.

property is_constant: bool

Return True if the output(s) of the operation is(are) constant.

property is_linear: bool

Return True if the operation is linear.

property is_multirate: bool

Whether this graph or a nested graph contains rate-changing operations.

iteration_period_bound() → Fraction

Return the iteration period bound of the SFG.

If -1, the SFG does not have any loops and therefore no iteration period bound. Each loop uses the output offset minus the input offset of the ports traversed at each operation, divided by its number of delays.

Returns:
fractions.Fraction

Iteration period bound, or -1 if the SFG has no recursive loops.

join(target: GraphID, direction: Literal['forward', 'backward']) → SFG

Return a new SFG with the specified operation joined with its predecessor or successor.

Parameters:
targetGraphID

The operation to be joined with its predecessor(s) or successor(s).

direction{“forward”, “backward”}

The direction to join. “forward” joins with the successor(s), “backward” with the predecessor(s).

property loops: list[list[LoopElement]]

Return the recursive loops found in the SFG.

Returns:
list[list[LoopElement]]

Recursive loops as sequences of (graph_id, input_index, output_index) triples. Each sequence repeats its first entry at the end to close the loop. Parallel connections produce separate loops. Loops are rotated to their smallest entry and sorted.

noble_transform(n: int) → SFG

Return a copy with every Delay replaced by a chain of n Delays.

This substitutes z**(-n) for each unit delay, applying recursively to nested SFGs and connected upstream stages while retaining their hierarchy. Each shared upstream operation is transformed once per call. Other operations and the graph interface are preserved. External input and output signals are transferred to the returned replacement, allowing transformed instances to be cascaded without retaining the untransformed instances.

Parameters:
nint

Positive number of delays replacing each original delay. Each delay in a replacement chain has the original delay’s initial value. A factor of one preserves the internal graph.

Returns:
SFG

The transformed graph. The original internal graph is unchanged, but its external connections are moved to the returned graph.

operation_counter() → Counter

Return a Counter with the number of instances for each type.

property operations: list[Operation]

Get all operations of this graph in depth-first order.

property output_operations: Sequence[Operation]

Internal output operations in the same order as their respective output ports.

property precedence_graph: Digraph

The SFG in precedence form in Graphviz format.

This can be rendered in enriched shells.

print_precedence_graph() → None

Print a representation of the SFG precedence list to the standard out.

If the precedence list already has been calculated then it uses the cached version, otherwise it calculates the precedence list and then prints it.

rebalance_summation_trees() → SFG

Return a copy with ordinary addition and subtraction trees balanced.

remove_operation(operation_id: GraphID) → SFG | None

Remove operation.

Returns a version of the SFG where the operation with the specified GraphID removed.

The operation must have the same amount of input- and output ports or a ValueError is raised. If no operation with the entered operation_id is found then returns None and does nothing.

Parameters:
operation_idGraphID

The GraphID of the operation to remove.

replace(target: GraphID, component: Operation) → SFG
resource_lower_bound(type_name: TypeName, schedule_time: int) → int

Return the lowest amount of resources of the given type needed to reach the scheduling time.

Parameters:
type_nameTypeName

Type name of the given resource.

schedule_timeint

Scheduling time to evaluate for.

rewrite(substitute: type[Operation], target: GraphID | type[Operation] | Operation | Iterable[GraphID | type[Operation] | Operation]) → SFG

Return a new SFG with the specified operations rewritten.

The operations specified by target are replaced by the operations specified by substitute.

Parameters:
substituteType[Operation]

The type of operation to replace the target(s) with.

targetOpSpecifier | Iterable[OpSpecifier]

The operation(s) to be replaced.

set_execution_time_of_type(operation_type: type[Operation], execution_time: int) → None

Set the latency of all operations with the given type.

Parameters:
operation_typetype of Operation

The operation type. For example, Addition.

execution_timeint

The execution time of the operation.

set_execution_time_of_type_name(type_name: TypeName, execution_time: int) → None

Set the execution time of all operations with the given type name.

Parameters:
type_nameTypeName

The type name of the operation. For example, obtained as Addition.type_name().

execution_timeint

The execution time of the operation.

set_latency_of_type(operation_type: type[Operation], latency: int) → None

Set the latency of all operations with the given type.

Parameters:
operation_typetype of Operation

The operation type. For example, Addition.

latencyint

The latency of the operation.

set_latency_of_type_name(type_name: TypeName, latency: int) → None

Set the latency of all components with the given type name.

Parameters:
type_nameTypeName

The type name of the operation. For example, obtained as Addition.type_name().

latencyint

The latency of the operation.

set_latency_offsets_of_type(operation_type: type[Operation], latency_offsets: dict[str, int]) → None

Set the latency offsets of all operations with the given type.

Parameters:
operation_typetype of Operation

The operation type. For example, Addition.

latency_offsets{“in1”: int, …}

The latency offsets of the inputs and outputs.

set_latency_offsets_of_type_name(type_name: TypeName, latency_offsets: dict[str, int]) → None

Set the latency offsets of all operations with the given type name.

Parameters:
type_nameTypeName

The type name of the operation. For example, obtained as Addition.type_name().

latency_offsets{“in1”: int, …}

The latency offsets of the inputs and outputs.

show(fmt: str | None = None, info: Literal['none', 'id', 'l1-norm', 'l2-norm'] = 'none', engine: str | None = None, branch_node: bool = True, port_numbering: bool = True, splines: Literal['spline', 'line', 'ortho', 'polyline', 'curved'] = 'spline', input_order: list[GraphID] | None = None, output_order: list[GraphID] | None = None, show_op_params: bool = False, direction: Literal['LR', 'TB'] = 'LR', ranksep: float | None = None, nodesep: float | None = None, size: tuple[float, float] | None = None, force_size: bool = False, fontname: str | None = 'DejaVu Serif', fontsize: float | None = None, colored: bool = False, show_ids: bool = True) → None

Open an interactive SVG of the SFG in the default web browser.

The SVG is stored in a temporary directory. Clicking a signal highlights all branches from the same output port and their connected operations. Clicking an operation highlights it in orange, its connected signals in magenta, and operations on those signals in blue. Click the background or press Escape to clear the selection.

Parameters:
fmtstr, optional

File format of the generated graph. Output formats can be found at https://www.graphviz.org/doc/info/output.html Defaults to an interactive SVG. Explicit “svg” also enables interaction. Other formats use the default system viewer.

enginestr, optional

Graphviz layout engine to be used, see https://graphviz.org/documentation/. Most common are “dot” and “neato”. Default is None leading to dot.

branch_nodebool, default: True

Add a branch node in case the fan-out of a signal is two or more.

port_numberingbool, default: True

Show the port number in case the number of ports (input or output) is two or more.

splines{“spline”, “line”, “ortho”, “polyline”, “curved”}, default: “spline”

Spline style, see https://graphviz.org/docs/attrs/splines/ for more info.

info{“none”, “id”, “l1-norm”, “l2-norm”}, default: “none”
Information to show for each signal in the graph.
  • “none”: Do not show any signal information.

  • “id”: Show the graph_id of each signal.

  • “l1-norm”: Show the L1 norm of the impulse response (worst-case magnitude for inputs bounded by 1).

  • “l2-norm”: Show the L2 norm of the impulse response (signal energy for unit-energy inputs).

input_orderlist of GraphID or operation name, optional

Top-to-bottom ordering of input nodes. Each entry may be a GraphID, an operation name, or a mix of both. See display() for details.

output_orderlist of GraphID or operation name, optional

Top-to-bottom ordering of output nodes. Each entry may be a GraphID, an operation name, or a mix of both. See display() for details.

show_op_paramsbool, default: False

Annotate each operation node with its non-default-valued parameters.

direction{“LR”, “TB”}, default: “LR”
Direction of the graph layout.
  • “LR”: Left-to-right (inputs on the left, outputs on the right).

  • “TB”: Top-to-bottom (inputs at the top, outputs at the bottom).

ranksepfloat, optional

Separation between ranks in inches. Default is graphviz’s default (0.5).

nodesepfloat, optional

Minimum separation between nodes in the same rank, in inches. Default is graphviz’s default (0.25).

sizetuple of (float, float), optional

Maximum bounding box in inches of the drawing as (width, height).

force_sizebool, default: False

When True, the size bounding box is treated as an exact target and graphviz scales the entire drawing (including fonts) to fill it.

fontnamestr, optional

Font name for all node and edge labels. Defaults to b_asic._preferences.DEFAULT_FONT_FAMILY, None uses Graphviz’s default.

fontsizefloat, optional

Font size (in points) for all node and edge labels.

coloredbool, default: False

Fill input/output, delay, and other operation nodes with distinct colors.

show_idsbool, default: True

Show graph IDs alongside operation names. Unnamed operations always show their graph ID.

show_precedence_graph() → None

Display the output of precedence_graph() in the system viewer.

simplify_delay_element_placement() → SFG

Simplify an SFG by removing redundant delay elements.

For example, two signals originating from the same starting point, each connected to a delay element will combine into a single delay element.

Returns a copy of the simplified SFG.

sink_propagation(target: type[Operation] | GraphID | Iterable[GraphID] | None = None, *, assume_zero_initial_state: bool = True, decompose: bool = True) → SFG

Return a copy with unused results propagated backwards from Sink nodes.

An output is unused if it is unconnected or connected only to Sinks. Operations whose results are all unused are replaced by Sinks on their inputs. Operation-specific _sink_propagation hooks can simplify partially used multi-output operations. Computations shared with a required output are retained, including their delay state. WDF adaptor outputs are expanded into only the arithmetic needed for the retained results.

Parameters:
targettype[Operation], GraphID, or iterable of GraphID, optional

Restrict operation replacements as in constant_propagation(). Dead branches that no longer feed a graph output are removed after replacements, including unobservable feedback loops.

assume_zero_initial_statebool, default: True

Use zero initial delay states and proven zero feedback signals as in constant_propagation(). Set to False to preserve configured initial states and disable this feedback analysis.

decomposebool, default: True

Allow partially used operations to become smaller arithmetic networks. If False, retain operations whose remaining outputs still require arithmetic, including butterflies and WDF adaptors. Replacements by constants or direct wiring and removal of fully unused operations are allowed in either mode.

Notes

Input/output ordering and names are preserved. Unused interface inputs and unconnected outputs of retained operators are terminated by Sinks. To discard a graph output, first replace its Output node with a Sink. This is an algebraic transformation intended before scheduling.

split() → Iterable[Operation]

Split the operation into multiple operations.

If splitting is not possible, this may return a list containing only the operation itself.

split_constant_fanout() → SFG

Return a copy with a separate Constant operation for each connection.

This reduces fanout to one connection per operation.

swap_io_of_operation(operation_id: GraphID) → None

Swap the inputs (and outputs) of operation.

Parameters:
operation_idGraphID

The GraphID of the operation to swap.

to_lean() → str

Return Lean 4 code for evaluating the graph over the real numbers.

The code requires import Mathlib. Inputs are curried arguments x0, x1, … in interface order. A single output is a scalar; multiple outputs form a tuple in interface order, and no outputs give (). Shared intermediate results use let bindings.

For a stateful graph, emit a structure State with one Real field per delay, an initialState : State definition, and a step (state : State) (x0 : Real) ... definition returning Prod Outputs State. Fields s0, s1, … follow graph ID order in the flattened graph. Delay updates are simultaneous: all expressions read the current state and the returned record contains the next state. A stateless graph produces just an expression as described above. Nested SFGs are flattened without modifying this graph. Place generated declarations in separate Lean namespaces when exporting multiple graphs.

Supported operations are constants, addition, subtraction, multiplication, division, constant multiplication, negation, absolute value, square root, reciprocal, min/max, comparators, radix-2 butterflies, and real AddSub operations (including their power-of-two scaling). Composite operations without a Lean hook are expanded via to_sfg(); all output ports and any delays inside the expansion are retained.

This models exact real arithmetic, ignoring quantization and scheduling. Finite floats are represented by their exact integer ratios. Division and square root use Mathlib’s total real operations (in particular, division by zero is zero and square root of a negative real is zero). Complex values and operations without a supported real interpretation raise NotImplementedError; non-finite constants and combinational cycles raise ValueError.

Examples

>>> x = Input()
>>> SFG(x, Output(x + 1)).to_lean()
'fun (x0 : Real) =>\n  let v0 : Real := (1 : Real)\n  let v1 : Real := (x0 + v0)\n  v1'
to_sfg() → SFG

Convert the operation into its corresponding SFG.

If the operation is composed by multiple operations, the operation will be split.

to_single_rate() → RateNormalization

Normalize rate changes into phase connections over one common period.

Return a RateNormalization containing an independent single-rate SFG and input, output, and intermediate-result phase mappings. Each input or output is represented by one scalar port per sample in the period, ordered by original port, then phase.

Expansion becomes wiring and zero constants; compression selects phases and terminates unused results with Sinks. Operations are replicated at their local sample rates, including delay state updates. No arithmetic simplification or noble rewrites are applied. Constants may feed several rate domains. Inconsistent rates at reconvergent branches raise ValueError.

to_ss() → StateSpace

Return the state-space representation of the SFG.

Returns:
StateSpace

State-space representation of the SFG.

to_tf()

Return the transfer function representation of the SFG.

Returns:
TransferFunction

Transfer function representation of the SFG.

to_zpk()

Return the zeros, poles, and gain of the SFG.

Returns:
dict

See zpk() for the return format.

classmethod type_name() → TypeName

Get the type name of this graph component.

unfold(factor: int) → SFG

Unfold the SFG factor times. Return a new SFG without modifying the original.

Inputs and outputs are ordered with early inputs first. That is for an SFG with n inputs, the first n inputs are the inputs at time t, the next n inputs are the inputs at time t+1, the next n at t+2 and so on.

Parameters:
factorint

Number of times to unfold.