q5m.js - Quantum Computing Library - v0.1.1
    Preparing search index...

    Class Circuit

    Extended Circuit class with comprehensive quantum gate library.

    Hierarchy

    • BaseCircuit
      • Circuit
    Index

    Constructors

    • Creates a new quantum circuit with specified number of qubits.

      Initializes an empty quantum circuit ready for gate operations and measurements. The circuit automatically optimizes memory usage for large qubit systems and provides comprehensive validation for all operations.

      Circuit Capabilities:

      • Supports 1 to 30+ qubits (memory-dependent)
      • Automatic sparse optimization for >12 qubits
      • Fluent API for intuitive gate sequencing
      • Built-in measurement support for all bases
      • Comprehensive error checking and validation

      Parameters

      • numQubits: number

        Number of quantum units in the circuit (must be positive integer)

      • Optional_optimizeMemory: boolean

        Memory optimization hint (currently auto-determined, reserved for future use)

      Returns Circuit

      If numQubits is not a positive integer

    Methods

    • Get the number of qubits in the circuit.

      Returns the total number of quantum bits (qubits) that this circuit operates on. This value is set during circuit construction and may be automatically expanded when gates are applied to higher-indexed qubits.

      Returns number

      The number of qubits in the circuit

    • Returns a copy of all instructions in this circuit.

      Provides access to the complete list of quantum operations (gates and measurements) that have been added to this circuit. The returned array is a shallow copy, so modifications to the array will not affect the circuit, but modifications to individual instruction objects will affect the original circuit.

      Returns CircuitInstruction[]

      A copy of the circuit's instruction list

    • Run the quantum circuit starting from a given initial state.

      This method applies all circuit instructions to the provided initial state and returns the resulting quantum state. It supports both pure quantum evolution and measurement-based computations with full state control.

      Key Features:

      • Custom initial state support (not just |000...0⟩)
      • State validation ensures compatibility
      • Supports both dense and sparse quantum states
      • Handles measurements with proper state collapse
      • Memory-efficient execution for large circuits

      State Validation:

      • Initial state must have same number of quantum units as circuit
      • State vector dimensions must match 2^numQubits for qubit systems
      • Supports both pure states and sparse state representations

      Parameters

      • initialState: Q5mState

        The initial quantum state to start from

      Returns ExecutionResult

      The final quantum state after applying all circuit instructions

      If circuit execution fails or state compatibility issues occur

      If initialState has different number of quantum units than circuit

    • Resets the circuit to its initial empty state.

      Removes all gates, measurements, and instructions from the circuit while preserving the number of quantum units. This allows reusing the circuit object for different quantum algorithm implementations without creating a new instance.

      What gets reset:

      • All quantum gates and measurements
      • Circuit instruction history
      • Classical register contents (if implemented)

      What stays unchanged:

      • Number of quantum units
      • Circuit configuration and optimization settings

      Returns BaseCircuit

      This circuit instance for method chaining

    • Add a gate at a specific column position in the circuit.

      Parameters

      • gateName: string

        Name of the gate

      • wire: number | number[]

        Qubit indices (Q5mIndex or array of Q5mIndex)

      • column: number

        Column position to place the gate

      • Optionaloptions: GateOptions

        Gate options

      Returns BaseCircuit

      This circuit for chaining

    • Delete a gate at a specific column position for given wire(s).

      This method removes a gate at the specified column position on the target wire(s), serving as the counterpart to addGate() for column-based gate manipulation.

      Key behaviors:

      • Deletes gate at specific column position on target wire(s)
      • For multi-qubit gates, finds gate that affects any of the specified wires
      • Column out of range: does nothing and returns circuit unchanged
      • No gate at column: does nothing and returns circuit unchanged
      • Subsequent gates automatically shift forward to fill the gap

      Multi-qubit gate handling:

      • Treats multi-qubit gates as occupying the same column
      • Deletes the entire multi-qubit gate if any target wire matches
      • Column position is determined by the gate's position in the wire sequence

      Parameters

      • wire: number | number[]

        Target wire(s) to look for gates on (Q5mIndex or array of Q5mIndex)

      • column: number

        Column position to delete gate from (0-based)

      Returns BaseCircuit

      This circuit instance for method chaining

    • Helper method to count gates in a specific column for given wires. Used for column-based gate positioning logic.

      Parameters

      • wires: number[]
      • column: number

      Returns number

    • Helper method to find the instruction index at a specific column for given wires. Returns -1 if no gate exists at that column.

      Parameters

      • wires: number[]
      • column: number

      Returns number

    • Helper method to calculate the maximum column position for multi-qubit gates. For multi-qubit gates, aligns to the largest column position among all wires.

      Parameters

      • wires: number[]

      Returns number

    • Helper method to shift gates at and after a specific position backward by one. Used when inserting gates in the middle of the circuit.

      Parameters

      • _fromIndex: number

      Returns void

    • Insert a gate at a specific position in the instruction sequence.

      This method allows precise placement of gates within the circuit based on instruction index, enabling fine-grained control over gate ordering.

      Key behaviors:

      • Inserts at exact index position (0-based)
      • Existing gates at and after index are shifted backward
      • Index out of range: does nothing and returns circuit unchanged
      • Multi-qubit gates are treated as single instructions

      Parameters

      • index: number

        Instruction index where to insert the gate (0-based)

      • gateName: string

        Name of the gate to insert

      • wire: number | number[]

        Target qubit(s) for the gate

      • Optionaloptions: GateOptions

        Optional gate parameters and options

      Returns BaseCircuit

      This circuit instance for method chaining

    • Remove a gate at a specific position in the instruction sequence.

      This method removes the instruction at the given index position, allowing precise control over circuit modifications.

      Key behaviors:

      • Removes instruction at exact index position (0-based)
      • Subsequent instructions shift forward to fill the gap
      • Index out of range: does nothing and returns circuit unchanged
      • Safe operation that never throws errors for invalid indices

      Parameters

      • index: number

        Instruction index to remove (0-based)

      Returns BaseCircuit

      This circuit instance for method chaining

    • Replace a gate at a specific position with a new gate.

      This method replaces the instruction at the given index with a new gate, maintaining the same position in the circuit while changing the operation.

      Key behaviors:

      • Replaces instruction at exact index position (0-based)
      • New gate can target different qubits than the original
      • Index out of range: does nothing and returns circuit unchanged
      • Atomic operation - either succeeds completely or makes no changes

      Parameters

      • index: number

        Instruction index to replace (0-based)

      • gateName: string

        Name of the new gate

      • wire: number | number[]

        Target qubit(s) for the new gate

      • Optionaloptions: GateOptions

        Optional gate parameters and options

      Returns BaseCircuit

      This circuit instance for method chaining

    • Computes the unitary matrix representation of the circuit.

      This method calculates the complete unitary transformation matrix that represents the entire circuit's quantum operations. The matrix is built by multiplying all gate matrices in sequence.

      Important notes:

      • Only works for circuits without measurements
      • Matrix size is 2^n × 2^n for n qubits
      • Memory intensive for large circuits (exponential growth)
      • Returns the composed unitary U = U_n × ... × U_2 × U_1

      Parameters

      • Optionaltolerance: number

        Optional numerical tolerance for matrix operations (when omitted, uses high precision mode)

      Returns Matrix

      The unitary matrix as a 2D array of Complex numbers

      If circuit contains measurement gates

      If memory requirements are too large (>16 qubits)

    • Computes the matrix representation of the circuit.

      Alias for toUnitary() for convenience. Returns the same unitary transformation matrix representing the circuit.

      Parameters

      • Optionaltolerance: number

        Optional numerical tolerance for matrix operations (when omitted, uses high precision mode)

      Returns Matrix

      The circuit's unitary matrix

      If circuit contains measurements

      If circuit is too large (>16 qubits)

    • Returns a human-readable string representation of the circuit.

      The string includes the number of quantum units and a detailed list of all instructions with their applied quantum units. This is useful for debugging, logging, and understanding the circuit structure.

      Output format:

      • Header with quantum units count
      • Numbered list of instructions
      • Gate names with target quantum unit
      • Empty circuit indication when no instructions

      Returns string

      A string representation of the circuit structure

    • Serializes the circuit to simple internal format (save/load).

      Creates a simple representation using the internal instruction array format for efficient storage and loading. This format is optimized for performance and direct reconstruction of the circuit without conversion overhead.

      Simple format features:

      • Direct instruction array serialization
      • Minimal overhead
      • Fast load/reconstruction
      • Internal format compatibility

      Returns SimpleCircuitData

      Simple circuit data for efficient storage

    • Loads circuit data from simple internal format.

      Reconstructs the circuit from data created by save(). This method overwrites the current circuit content with the loaded data.

      Parameters

      Returns BaseCircuit

      This circuit instance for method chaining

      If data format is invalid

    • Serializes the circuit to JSON interchange format.

      Creates a comprehensive JSON representation suitable for long-term storage, cross-platform interchange, and future compatibility. This format includes versioning, metadata, and detailed gate parameter preservation.

      JSON format features:

      • Version compatibility tracking
      • Complete gate parameter preservation
      • Extensible metadata support
      • Cross-platform interchange
      • Future-proof format design

      Parameters

      Returns SerializedCircuit

      JSON-compatible circuit representation

    • Extract clean gate name without parameter info. E.g., "RX(0.785)" -> "RX", "CNOT" -> "CNOT"

      Parameters

      • gateName: string

      Returns string

    • Extract parameters from gate name or properties. Handles parametrized gates like RX, RY, RZ, Phase, etc.

      Parameters

      • gate: { name: string; [key: string]: unknown }

      Returns SerializedGateParameters

    • Creates the initial quantum state for circuit execution.

      Parameters

      • numQuantum: number

      Returns QubitState

    • Apply Controlled-Phase (CP) gate.

      Parameters

      • control: number
      • target: number
      • phi: number

      Returns Circuit

    • Apply Controlled-Unitary (CU) gate.

      Parameters

      • control: number
      • target: number
      • name: string
      • alpha: Complex
      • beta: Complex
      • Optionaltheta: number

      Returns Circuit

    • Measure qubit in specified basis. Acts as a unified interface for all measurement operations:

      • 'z': Z-basis measurement (computational basis, default) - equivalent to mz()
      • 'x': X-basis measurement - equivalent to mx()
      • 'y': Y-basis measurement - equivalent to my()
      • 'phase': Custom phase basis measurement - equivalent to mp()

      Parameters

      • qubit: number

      Returns Circuit

    • Measure qubit in specified basis. Acts as a unified interface for all measurement operations:

      • 'z': Z-basis measurement (computational basis, default) - equivalent to mz()
      • 'x': X-basis measurement - equivalent to mx()
      • 'y': Y-basis measurement - equivalent to my()
      • 'phase': Custom phase basis measurement - equivalent to mp()

      Parameters

      • qubit: number
      • basis: "x" | "y" | "z"

      Returns Circuit

    • Measure qubit in specified basis. Acts as a unified interface for all measurement operations:

      • 'z': Z-basis measurement (computational basis, default) - equivalent to mz()
      • 'x': X-basis measurement - equivalent to mx()
      • 'y': Y-basis measurement - equivalent to my()
      • 'phase': Custom phase basis measurement - equivalent to mp()

      Parameters

      • qubit: number
      • basis: "phase"
      • theta: number
      • phi: number
      • Optionalname: string

      Returns Circuit

    • Measure qubit in custom phase basis.

      Parameters

      • qubit: number
      • theta: number
      • phi: number
      • Optionalname: string

      Returns Circuit

    • Override base circuit's getGateFactory to provide concrete gate implementations.

      Parameters

      • gateName: string

      Returns undefined | GateFactory

    • Append a gate to the end of the circuit by name.

      Parameters

      • gateName: string
      • wire: number | number[]
      • Optionaloptions: GateOptions

      Returns Circuit

    • Get the current memory usage of the circuit's quantum state.

      Returns number

    • Deserializes a Circuit from JSON interchange format.

      Creates a new Circuit instance from JSON data created by toJSON(). Supports version compatibility and parameter restoration.

      Parameters

      Returns Circuit

      New Circuit instance

      If data format is invalid or incompatible

    Properties

    numQubits: number
    instructions: CircuitInstruction[]