sircuitenum package

Submodules

sircuitenum.enumeration module

enumeration.py: Contains the core functionality for enumerating circuits

sircuitenum.enumeration.find_equiv_cir_series(db_file: str, circuit: list, edges: list) str[source]

Searches the database for circuits that are equivalent to the given one, up to a reduction of series linear circuit elements.

Parameters

db_filestr

Path to the SQLite database file that has been preprocessed for the given number of nodes.

circuitlist of list of str

A list representing the circuit elements. Example: [["J"], ["L", "J"], ["C"]].

edgeslist of tuple of int

A list of edge connections that define the circuit’s connectivity. Example: [(0,1), (0,2), (1,2)].

Returns

str

The unique key of the equivalent circuit found in the non-isomorphic set. Returns “” if no equivalent circuit is found.

sircuitenum.enumeration.find_unique_ground_placements(circuit: list, edges: list) tuple[int][source]

Uses component graph isomorphism to determine the unique ground node placements for a given circuit.

Parameters

circuitlist of list of str

A list representing the elements of the desired circuit. Example: [["J"], ["L", "J"], ["C"]].

edgeslist of tuple of int

A list of edge connections for the desired circuit. Example: [(0,1), (0,2), (1,2)].

Returns

tuple of int

A tuple containing integers representing the unique ground node placements for the given circuit.

sircuitenum.enumeration.gen_hamiltonian(circuit: list, edges: list, symmetric: bool = False, cob: MutableDenseMatrix = None, var_class: dict = None, return_combos: bool = False, basis_completion: str = 'heuristic') tuple[source]

Generate a SymPy Hamiltonian for the specified circuit.

This function uses scqubits to determine an appropriate variable transformation.

Note

External fluxes and charges are not currently supported.

Parameters

circuitlist

A list of element labels defining the desired circuit. Example: [["J"], ["L", "J"], ["C"]].

edgeslist

A list of edge connections defining the circuit topology. Example: [(0,1), (0,2), (1,2)].

symmetricbool, optional

Whether to set all capacitances, inductances, and Josephson energies equal. This may result in the loss of some terms. Default is False.

cobsympy.Matrix, optional

An optional variable transformation matrix. If not provided, the Z transformation matrix from scqubits is used.

var_classdict, optional

Required if providing a custom variable transformation. Should be a dictionary similar to scqubits’s var_categories, with keys “free”, “frozen”, “periodic”, and “extended” to classify the variables.

return_combosbool, optional

Whether to return the combinations of variables present. Default is False.

basis_completionstr, optional

Basis completion option for scqubits.

Returns

A tuple containing:

  • hamiltonian: sympy.Add

    Symbolic Hamiltonian where periodic modes are labeled by n and extended variables by q.

  • transformation_matrix: numpy.ndarray

    Coordinate transformation matrix (expressing new variables in terms of node variables).

  • hamiltonian_class: sympy.Add

    Hamiltonian with all constants removed.

  • optionally combinations of variables present

sircuitenum.enumeration.generate_all_circuits(db_file: str = 'circuits.db', n_nodes_start: int = 2, n_nodes_stop: int = 4, base: int = None, n_workers: int = 1, resume: bool = False, quiet: bool = True) None[source]

Generate all circuits with node counts between n_nodes_start and n_nodes_stop.

This function generates circuits with varying numbers of nodes, removes duplicate circuits, and stores both the full set and the deduplicated set in an SQL database.

Parameters

filestr

Path to the SQL database file where the generated circuits will be stored.

n_nodes_startint

Minimum number of nodes to generate circuits for.

n_nodes_stopint

Maximum number of nodes to generate circuits for.

baseint, optional

The number of possible edge types. Defaults to 7, corresponding to: J, C, L, JL, CL, JC, JCL.

n_workersint, optional

The number of workers to use for circuit generation. Defaults to 1.

sircuitenum.enumeration.generate_graphs_node(db_file: str, n_nodes: int, base: int, return_vals: bool = False) DataFrame | None[source]

Generate circuits for all graphs with a given number of nodes and store them in an SQL database.

This function generates circuits for all possible graphs with n_nodes nodes and stores them in a table within the specified SQL database. The table is labeled as CIRCUITS_<n_nodes>_NODES.

Parameters

n_nodesint

The number of nodes for which circuits will be generated and stored.

baseint, optional

The number of possible edge types. Defaults to 7, corresponding to: J, C, L, JL, CL, JC, JCL.

db_filestr

Path to the SQL database file where the circuits will be stored.

return_valsbool, optional

If True, returns the generated circuits as a Pandas DataFrame. Defaults to False.

Returns

pandas.DataFrame or None

If return_vals is True, returns a DataFrame containing the generated circuits. Otherwise, returns None.

sircuitenum.enumeration.num_possible_circuits(base: int, n_nodes: int, quiet: bool = True) int[source]

Estimate the number of possible circuits for a given number of edges and vertices.

This function calculates the number of possible circuits for a graph with n_nodes vertices and base possible edge types. The estimate may be an overestimation.

Parameters

baseint, optional

The number of possible edge types. Defaults to 7, corresponding to: J, C, L, JL, CL, JC, JCL.

n_nodesint

The number of vertices (nodes) in the graph.

quietbool, optional

If False, prints the estimated number of circuits. Defaults to True.

Returns

int

The estimated number of possible circuits.

sircuitenum.enumeration.trim_graph_node(db_file: str, n_nodes: int, base: int = None, n_workers: int = 1) None[source]

Mark circuits in the database based on Josephson junctions, series linear components, and non-isomorphism.

This function updates the database to indicate whether each circuit contains Josephson junctions (JJs), series linear components, and belongs to a non-isomorphic set of circuits. If a circuit is not in the non-isomorphic set, an equivalent circuit that is in the set is recorded.

All three conditions must be met for inclusion in the final set.

Parameters

db_filestr

Path to the SQL database file where circuits are stored.

n_nodesint

The number of nodes to consider.

baseint, optional

The number of possible edge types. Defaults to 7, corresponding to: J, C, L, JL, CL, JC, JCL.

n_workersint, optional

The number of workers to use for processing. Defaults to 1.

sircuitenum.optimize module

optimization.py: Contains functions used to optimize circuit performance as a function of underlying circuit parameters

sircuitenum.optimize.gen_param_dict_anyq(circuit: list, edges: list, param_sets: list, cj: float = 10.0) dict[source]

Generate a dictionary of parameter values for use in the qpackage interface.

This function constructs a dictionary containing parameter values corresponding to a given circuit, formatted for compatibility with the qpackage interface.

Parameters

circuitlist

A list of element labels defining the desired circuit. Example: [("J",), ("L", "J"), ("C",)].

edgeslist

A list of edge connections defining the circuit topology. Example: [(0,1), (0,2), (1,2)].

param_setslist

A list of parameter values in GHz. Values are assigned in the order they appear in the circuit list.

cjfloat

Junction capacitance in GHz. Pass 0 to ignore this parameter.

Returns

dict

A dictionary containing the parameter values for the circuit. Maps (edge, elem) -> (value, unit)

sircuitenum.optimize.get_ngate_mc(param_set: list, *args, **kwargs)[source]

Objective function to be minimized for optimization.

This function is designed to be used in the optimization process. It returns the negative of the number of ngates performed by the circuit for a given set of parameters. The function evaluates the circuit based on the parameters and samples from a Gaussian distribution centered on the provided values.

Parameters

param_setlist of float

A list of parameter values in GHz. The values are given in the order they appear in the circuit.

argslist

A list of extra arguments required for the circuit evaluation, including:

  • circuit (list of tuple of str): The list of elements that form the circuit.

  • edges (list of tuple of int): The list of edges for the circuit.

  • ground_node (int): The index of the ground node.

  • trunc_num (int or list of int): The truncation number(s) used in the evaluation.

  • offset_integer (bool): Whether the offset integer is enabled.

  • cj (float): The value for junction capacitance in GHz. Pass 0 to include none.

  • ntrial (int): The number of trials to perform.

  • amp_param (float): Amplitude of random noise for sampling the parameters.

  • amp_offset (float): Amplitude of random noise for sampling the offsets.

  • return_std (bool): Whether to return the standard deviation of the samples.

  • workers (int): The number of workers to use for parallel computation.

kwargsdict, optional

Additional keyword arguments for customization.

Returns

float

The negative mean ngates performed by the circuit, or if return_std is True, a tuple containing:

  • float: The mean ngates performed.

  • float: The standard deviation of the ngates computed from the sampled values.

Notes

  • The objective function is intended to be used with optimization algorithms such as differential evolution.

  • The circuit’s performance is evaluated multiple times using Gaussian-distributed noise to estimate the average performance.

sircuitenum.optimize.optimize_diff_evol(circuit: list, edges: list, ground_node: int, ranges: list = None, offset_integer: bool = False, optim_func=<function _timed_out>, trials: list = [1, 100], amps: dict = {'elem': [0, 0.025], 'offset': [0, 1e-06]}, trunc_num: int | list = -1, cj: float = 10.0, quiet: bool = False, package: str = 'sq', trunc_est_n: int = 200, **kwargs) dict[source]

Optimize a circuit’s performance using differential evolution.

This function optimizes a circuit’s parameters by running differential evolution on the given circuit and edge configuration. It estimates the truncation number if not provided, and uses a set of user-defined or default parameters for the optimization process. The function returns the best parameters and final evaluation results.

Parameters

circuitlist of list of str

A list representing the elements of the desired circuit. Example: [["J"], ["L", "J"], ["C"]].

edgeslist of tuple of int

A list of edge connections for the desired circuit. Example: [(0, 1), (0, 2), (1, 2)].

ground_nodeint

The index of the ground node in the circuit.

rangeslist of tuple of float, optional

A list of parameter ranges for each element. If not provided, the ranges are automatically generated based on the circuit and edge configuration.

offset_integerbool, optional

Whether the offset integer is enabled. Default is False.

optim_funcfunction, optional

Function to optimize, must match the inputs of get_ngate_mc().

trialslist of int, optional

A list containing the number of trials for optimization. Default is [1, 100].

ampsdict, optional

A dictionary defining the amplitude ranges for elements and offset. Default is {"elem": [0, 0.025], "offset": [0, 1e-06]}.

trunc_numint or list of int, optional

The truncation number. If set to -1, it will be estimated automatically. Default is -1.

cjfloat, optional

The coefficient for truncation estimation. Default is 10.0.

quietbool, optional

If set to True, suppresses the output during the optimization process. Default is False.

packagestr, optional

The package used for truncation estimation. Options are "sq" or "sc". Default is "sq".

trunc_est_nint, optional

The number of trials for truncation estimation. Default is 200.

**kwargskeyword arguments, optional

Additional parameters for the differential evolution optimization process. Default values are provided if not specified, including disp, popsize, callback, workers, tol, init, and maxiter.

Returns

dict

A dictionary containing the results of the optimization process:

  • ngate: The final optimized value.

  • param_best: The best parameters found during optimization.

  • ngate_mean: The mean value from the Monte Carlo evaluation.

  • ngate_std: The standard deviation of the Monte Carlo evaluation.

Notes

  • Uses scipy.optimize.differential_evolution() for the optimization process.

  • Truncation numbers are automatically estimated if not provided.

  • Detailed progress is shown if quiet is set to False.

sircuitenum.optimize.sweep_params(circuit: list, edges: list, params: list, ground_node: int = 0, workers: int = 4, n_eig: int = 5, extras: dict = {}, trunc_num: int | list = -1, cj: float = 10.0, just_spec: bool = False, quiet: bool = False, package: str = 'sq') dict[source]

Perform parameter sweeps on quantum circuits using SQcircuit.

This function executes parameter sweeps over a quantum circuit using the SQcircuit package, allowing for evaluation of circuit properties over a range of parameter values.

Parameters

circuitlist

A list of element labels defining the desired quantum circuit. Example: [("J",), ("L", "J"), ("C",)].

edgeslist

A list of edge connections defining the circuit topology. Example: [(0, 1), (0, 2), (1, 2)].

paramslist

A list of parameter values in GHz. Float entries are fixed, while iterable fields are swept over during the simulation.

ground_nodeint, optional

The ground node index. If None, small capacitive coupling is added for each node to ground. Defaults to 0.

workersint, optional

The number of parallel workers to use for evaluation. Defaults to 1.

n_eigint, optional

The number of eigenvalues to compute and save. Defaults to compute all available eigenvalues.

extrasdict, optional

A dictionary of additional fields to compute, where each key is a string and each value is either a function that takes an SQcircuit object (for scalar values) or a tuple containing the dimensions and a function (for non-scalar values).

trunc_numint or list, optional

Truncation number for each mode. Defaults to no truncation.

cjfloat

Junction capacitance in GHz. Pass 0 to ignore this parameter.

just_specbool

If True, only calculates the energy spectrum to save time. Defaults to False.

quietbool

If True, suppresses messages during the sweep. Defaults to False.

packagestr

Specifies the package to use for the circuit simulation: "sq" for SQcircuit or "sc" for scqubits.

Returns

dict

A dictionary containing arrays for the following quantities:

  • eigenvalues (last dimension is n_eig)

  • rates (a dictionary mapping to arrays of decay rates)

  • gate_time

  • anharmonicity (alpha)

  • t1

  • tphi

  • tg

  • tgate

  • ngate

sircuitenum.qpackage_interface module

qpackage_interface.py: contains functions that interface with scqubits and sqcircuit

sircuitenum.qpackage_interface.add_explicit_ground_node(circuit: list, edges: list, params: dict, ecg: float = 20, rand_amp=0.0)[source]

Add an explicit ground node to the circuit and modify the edges.

This function takes a circuit and its edges and returns a modified version with an explicit ground node (node 0) added. If node 0 was already present in the edges, the function increments all node labels by 1.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [("J"), ("L", "J"), ("C")].

edgeslist

A list of edge connections for the desired circuit. Example: [(0, 1), (0, 2), (1, 2)].

paramsdict

A dictionary containing parameter values for the circuit elements. The dictionary should include entries for C, L, J, and CJ, which represent the values for capacitors, inductors, Josephson junctions, and coupling capacitances, respectively. Additionally, it may include units for these parameters as C_units, L_units, J_units, and CJ_units.

ecgfloat

The EC (charging energy) for capacitors coupling to the ground, in GHz.

Returns

tuple

A tuple containing the modified version of the circuit and edges with capacitive coupling to a ground node added.

sircuitenum.qpackage_interface.find_loops(circuit, edges, ind_elem=['J', 'L'])[source]

Generate a list of loops for a given circuit.

This function returns a list of loops for the specified circuit by identifying the loops formed by the inductive elements and edge connections.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [("J",), ("L", "J"), ("C",)].

edgeslist

A list of edge connections for the desired circuit. Example: [(0, 1), (0, 2), (1, 2)].

ind_elemlist, optional

A list of symbols that define inductive elements. The default is ["J", "L"] for Josephson junctions and inductors.

Returns

tuple

A tuple containing: - loop_lst (list): A list of loops in the circuit. - circuit (list): The input circuit list. - edges (list): The input edges list.

sircuitenum.qpackage_interface.to_SCqubits(circuit: list, edges: list, trunc_num: int | list = 50, cutoff: int | list = 101, **kwargs) Circuit[source]

Convert a circuit from a list of labels and edges to an SCqubits-formatted circuit network.

This function converts the input circuit, specified by a list of element labels and edge connections, into a circuit network compatible with the SCqubits package.

Note: This function only supports values in GHz.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [("J",), ("L", "J"), ("C",)].

edgeslist

A list of edge connections for the desired circuit. Example: [(0, 1), (0, 2), (1, 2)].

trunc_numint or list

The number of eigenstates to consider for each mode in a composite circuit. For more details, refer to: SCqubits Custom Circuit Guide.

cutoffint or list

The number of points to use in the underlying position space for each mode.

paramsdict, optional

A dictionary with entries for the circuit parameters, including: - C, L, J, and CJ for the circuit elements. - Optional entries for units: C_units, L_units, J_units, and CJ_units. If no parameters are provided, default values from utils.ELEM_DICT are used.

Returns

scqubits.Circuit

The input circuit, converted to the SCqubits circuit format.

sircuitenum.qpackage_interface.to_SQcircuit(circuit: list, edges: list, trunc_num: int | list = 50, **kwargs) Circuit[source]

Convert a circuit from a list of labels and edges to an SQcircuit-formatted circuit network.

This function converts the input circuit, specified by a list of element labels and edge connections, into a circuit network compatible with the SQcircuit package.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [["J"], ["L", "J"], ["C"]].

edgeslist

A list of edge connections for the desired circuit. Example: [(0, 1), (0, 2), (1, 2)].

trunc_numint or list

The truncation number for each mode in the circuit.

paramsdict, optional

A dictionary containing the parameters for the circuit elements, including: - C, L, J, and CJ for the circuit components. - Optional entries for units: C_units, L_units, J_units, and CJ_units. If no parameters are provided, default values from utils.ELEM_DICT will be used.

Returns

SQcircuit.Circuit

The input circuit, converted to the SQcircuit format.

sircuitenum.quantize module

quantize.py: contains functions used to produce symbolic hamiltonians

sircuitenum.quantize.gen_cap_mat(circuit, edges)[source]

Generates a capacitance matrix using Sympy for the given circuit. Energy C = Q_vec @ ind_mat @ Q_vec

Args:
circuit (list): a list of element labels for the desired circuit

e.g. [[“J”],[“L”, “J”], [“C”]]

edges (list): a list of edge connections for the desired circuit

e.g. [(0,1), (0,2), (1,2)]

Returns:

sym.Matrix of the capacitance matrix

sircuitenum.quantize.gen_ind_mat(circuit, edges)[source]

Generates an inductor matrix using Sympy for the given circuit. Defined so Energy L = Phi_vec @ ind_mat @ Phi_vec

Args:
circuit (list): a list of element labels for the desired circuit

e.g. [[“J”],[“L”, “J”], [“C”]]

edges (list): a list of edge connections for the desired circuit

e.g. [(0,1), (0,2), (1,2)]

Returns:

sym.Matrix of the capacitance matrix

sircuitenum.quantize.gen_junc_pot(circuit, edges, flux_vars, cob=None, eps=1e-10) MutableDenseMatrix[source]

Generate the junction potential terms, optionally applying a change of basis.

This function generates the junction potential terms for the given circuit and optionally performs a change of basis to transform the flux variables based on a provided transformation matrix.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [["J"], ["L", "J"], ["C"]].

edgeslist

A list of edge connections for the desired circuit. Example: [(0, 1), (0, 2), (1, 2)].

flux_varssym.Matrix

A vector of flux variables for the circuit.

cobsym.Matrix

A change of basis matrix used to transform the node flux variables.

Returns

sym.Matrix

The capacitance matrix as a symbolic matrix, representing the junction potential terms.

sircuitenum.quantize.quantize_circuit(circuit, edges, Cv=None, V=None, cob=None, periodic=[], extended=[], free=[], frozen=[], sigma=[], return_mats=False, return_vars=False, return_H_class: bool = False, return_combos: bool = False, collect_phase: bool = True)[source]

Perform a symbolic circuit quantization for the given circuit.

This function performs symbolic quantization of a given circuit. The quantized variables are categorized as: - Periodic variables are represented by hat{n} / hat{θ}. - Extended variables are represented by hat{q} / hat{ϕ}. - Node variables are represented by hat{q} / hat{φ}.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [["J"], ["L", "J"], ["C"]].

edgeslist

A list of edge connections for the desired circuit. Example: [(0, 1), (0, 2), (1, 2)].

Cvsym.Matrix, optional

Coupling matrix representing the interaction between nodes in the circuit and fixed voltage nodes.

Vsym.Matrix, optional

A matrix of fixed voltages applied in the circuit.

cobsym.Matrix, optional

A change of basis matrix that transforms node variables to new variables. This matrix corresponds to the Z transformation of scqubits. If the new variables are expressed in terms of the old, this should be the inverse.

periodiclist of int, optional

A list of mode numbers (indexed from 1) indicating which coordinates are periodic.

extendedlist of int, optional

A list of mode numbers (indexed from 1) indicating which coordinates are extended.

freelist of int, optional

A list of mode numbers (indexed from 1) indicating which coordinates are free.

frozenlist of int, optional

A list of mode numbers (indexed from 1) indicating which coordinates are frozen.

return_matsbool, optional

If True, return the capacitance and inductance matrices along with the Hamiltonian.

return_varsbool, optional

If True, return the sympy variables used to construct the Hamiltonian.

return_H_classbool, optional

If True, return the Hamiltonian with all coefficients removed.

return_combosbool, optional

If True, return the combination of variables present in the Hamiltonian.

collect_phasebool, optional

If True, skip collecting phase terms for faster execution (results in slightly less precision).

Returns

tuple

A tuple containing: - The Hamiltonian of the circuit (sympy expression). - Optionally, the capacitance matrix and inductance matrix. - Optionally, the sympy variables used to construct the Hamiltonian. - Optionally, the Hamiltonian class with coefficients removed. - Optionally, the combinations of variables present in the Hamiltonian.

sircuitenum.reduction module

reduction.py: Contains functions used to identify redundant or duplicate circuits

sircuitenum.reduction.convert_circuit_to_component_graph(circuit: list, edges: list, ground_nodes: list = [], ground_color: int = -1, comp_map: dict = None) Graph[source]

Encodes a circuit as a colored component graph.

This representation follows the method described in “Enumeration of Architectures with Perfect Matchings” (Herber, Guo, Allison).

### Assumptions: - All circuit elements are two-port symmetric devices. - Component type isomorphism is assumed, meaning identical components are treated as the same. - Ground edges are automatically removed if placed between labeled ground nodes. - Differs from port graphs by representing each node and device as a single vertex instead of treating ports separately.

Parameters

circuitlist of list of str

A list of element labels for the desired circuit. Example: [['J'], ['L', 'J'], ['C']].

edgeslist of tuple of int

A list of edge connections for the desired circuit. Example: [(0,1), (0,2), (1,2)].

ground_nodeslist of int, optional

A list of nodes that are grounded. Example: [0, 1].

ground_colorint, optional

Color assigned to ground nodes. Defaults to -1.

comp_mapdict, optional

A dictionary mapping components to colors for the colored graph. Ensures consistency between different circuits.

Returns

networkx.Graph

A NetworkX graph representation of the component graph.

sircuitenum.reduction.isomorphic_circuit_in_set(circuit: list, edges: list, c_set: list, e_set=None, return_index=False) int | bool[source]

Check if a circuit that is isomorphic to the given circuit exists in a set of circuits.

This function determines whether a circuit, represented as a list or tuple of tuples, has an isomorphic counterpart in a given set of circuits.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [("J"), ("L", "J"), ("C")].

edgeslist

A list of edge connections for the circuit. If e_set is not provided, this is assumed to be the edge set for all circuits in c_set. Example: [(0,1), (0,2), (1,2)].

c_setlist of list

A list of circuit-like elements representing different circuits.

e_setlist of list, optional

A list of edge sets corresponding to the circuits in c_set. If None, the edges parameter is used as the edge set.

return_indexbool, optional

If True, return the index of the isomorphic circuit in c_set. If no match is found, returns nan.

Returns

bool or int - True if an isomorphic circuit is present in c_set, False otherwise. - If return_index is True, returns the index of the isomorphic circuit, or nan if not found.

sircuitenum.reduction.mark_non_isomorphic_set(df: DataFrame, **kwargs)[source]

Reduces a set of circuits to contain only those whose port graphs are not isomorphic to each other.

Args:
df (pd.DataFrame): Dataframe where each row represents a

specific circuit. Assumes that every entry has the same number of nodes, and comes from the same basegraph

to_consider (np.array, optional): logical array that marks

rows to consider. For use when some have already been eliminated for other reasons. Defaults to considering all.

Returns:

None, fills in the ‘in_non_iso_set’ and ‘equiv_circuit’ columns of df

sircuitenum.utils module

utils.py: Contains utilities used in other files in the package

sircuitenum.utils.edges_to_graph_index(edges: list, return_mapping: bool = False) int[source]

Matches a given set of edges to an isomorphic base graph.

This function finds a base graph that is isomorphic to the input edge set.

Parameters

edgeslist of tuple of int

A list of edge connections representing the desired circuit. Example: [(0,1), (0,2), (1,2)].

return_mappingbool, optional

If True, returns the mapping of edges to the base graph. Defaults to False.

Returns

int

The index of the graph matching the given edges within the set of graphs with the same number of nodes.

dict, optional

If return_mapping=True, also returns a dictionary mapping edges to the base graph.

sircuitenum.utils.find_circuit_in_db(db_file: str, circuit: list, edges: list)[source]

Finds the database entry for a given circuit/edges combination

Args:
db_file (str): sqlite db_file to look in.

Defaults to “circuits.db”

circuit (list): a list of element labels for the desired circuit

e.g. [[“J”],[“L”, “J”], [“C”]]

edges (list): a list of edge connections for the desired circuit

e.g. [(0,1), (0,2), (1,2)]

sircuitenum.utils.get_circuit_data_batch(db_file: str, n_nodes: int, char_mapping: dict = None, filter_str: str = '') DataFrame[source]

Retrieve all circuits from the database for a specified number of nodes, with optional filtering criteria.

Parameters

db_filestr, optional

Path to the SQLite database file. Defaults to "circuits.db".

n_nodesint

Number of nodes in the circuit.

char_mappingdict, optional

A mapping from characters to lists of circuit elements.

filtersstr, optional

SQL filter statement for refining the query. Example: "WHERE circuit_index = 100".

Returns

pandas.DataFrame

A DataFrame where each row represents a circuit matching the query.

sircuitenum.utils.get_equiv_circuits(db_file: str, circuit: list, edges: list) DataFrame | None[source]

Finds all circuits in the database that are equivalent to a given circuit.

Parameters

db_filestr

Path to the SQLite database file. Defaults to “circuits.db”.

circuitlist

A list of element labels defining the desired circuit. Example: [[“J”], [“L”, “J”], [“C”]]

edgeslist

A list of edge connections defining how circuit elements are connected. Example: [(0,1), (0,2), (1,2)]

Returns

pandas.DataFrame or None

A DataFrame containing all equivalent circuits found in the database. Returns None if no equivalent circuits are found.

sircuitenum.utils.get_equiv_circuits_uid(db_file: str, unique_key: str) DataFrame[source]

Finds all circuits in the database that match a given unique key or are equivalent to it.

This function searches for circuits in an SQLite database that either: - Have the specified unique_key, or - Are considered equivalent circuits by component-like isomorphism.

Parameters

db_filestr

Path to the SQLite database file. Defaults to “circuits.db”.

unique_keystr

The unique identifier for the circuit.

Returns

pandas.DataFrame

A DataFrame containing all matching circuits.

sircuitenum.utils.graph_index_to_edges(graph_index: int, n_nodes: int)[source]

Returns a list of edges [(from, to), (from, to)] for the specified base graph

Args:

graph_index (int): base graph number n_nodes (int): number of nodes in the base graph

Returns:

list of len 2 tuples where each tuple represents the starting and ending nodes for an edge in the graph [(from, to), (from, to),…]

sircuitenum.visualize module

visualize.py: Contains functions to visualize circuits and draw diagrams

sircuitenum.visualize.draw_basegraph(G: Graph, title: str = '', savename: str = None, **kwargs)[source]

Plots unlabeled graphs from graph list returned from get_graphs_from_file() function

Args:

G (nx.graph): networkx graph to plot title (str): title for plot savename (str): location to save the plots pos (dict): dictionary of node labels -> positions

Returns:

tuple: figure, positioning (x, y) of nodes

sircuitenum.visualize.draw_circuit_diagram(circuit: list, edges: list, out: str = '', scale: float = 4.0, layout: str = 'fixed', spread: float = 0.4, graph_index: int = None) None[source]

Draw the circuit diagram using schemdraw.

For parallel elements, connections are split 1/4 of the way along and fan out to display parallel elements. Non-planar graphs are not adjusted to avoid overlap.

Parameters

circuitlist

A list of element labels for the desired circuit. Example: [["J"], ["L", "J"], ["C"]].

edgeslist

A list of edge connections for the desired circuit. Example: [(0,1), (0,2), (1,2)].

outstr

Filename to save the plot. If an empty string ("") is provided, the plot is displayed interactively.

scalefloat

Scaling factor for the networkx positions to spread out the plots if needed.

layoutstr

Options for graph layouts. “spring” produces aesthetically pleasing circuits but may lead to overlapping elements, even for planar graphs.

spreadfloat

Fraction of edge length used to fan out parallel components.

graph_indexint

Graph number for a fixed layout. Can also be inferred from edges.

Returns

None

Displays the plot interactively if out == “”.

Examples

>>> draw_circuit_diagram(
>>>     circuit=[["J"], ["L", "J"], ["C"]],
>>>     edges=[(0,1), (0,2), (1,2)],
>>>     out="circuit.png",
>>>     layout="spring",
>>>     scale=1.5
>>> )
sircuitenum.visualize.draw_circuit_graph(circuit: list, edges: list, gtype: str = 'component', out='', node_size: float = 10000, scale: float = 6, font_size: int = 30) Figure | None[source]

Draws the port or component graph representation of a given circuit.

This function visualizes a quantum circuit as either a port graph or a component graph using NetworkX and Matplotlib. The generated graph can be displayed interactively or saved as an image file.

Parameters

circuitlist of list of str

A nested list representing the circuit elements. Example: [[‘C’], [‘C’], [‘L’], [‘C’, ‘J’]]

edgeslist of tuple of int

A list of edge connections specifying how circuit elements are connected. Example: [(0,1), (1,2), (2,3), (3,0)]

gtypestr, optional

Type of graph to draw. Options are: - ‘component’ : Draws a component-level circuit graph. - ‘port’ : Draws a port-level circuit graph. Default is ‘component’.

outstr, optional

Filename (with extension) to save the plot. If “” (empty string), the graph is displayed interactively. Default is “circuit_graph.png”.

node_sizefloat, optional

Size parameter for nodes in the plotted graph.

scalefloat, optional

Scaling factor for overall spacing of nodes.

font_sizeint, optional

Font size for node labels.

Returns

matplotlib.figure.Figure or None
  • If out=””, returns a Matplotlib figure object for interactive viewing.

  • Otherwise, saves the figure to out and returns None.

Examples

>>> draw_circuit_graph(
>>>    circuit=[['C'], ['C'], ['L'], ['C', 'J']],
>>>    edges=[(0,1), (1,2), (2,3), (3,0)],
>>>    gtype="component",
>>>    out="circuit.png"
>>> )

Module contents