Skip to main content

QCOS API Reference

Complete API documentation for the QCOS library.

Core Module

softqcos.Optimizer

The main optimization class for quantum circuit optimization.

from softqcosimport Optimizer

optimizer = Optimizer(
backend: Backend,
num_qubits: int,
seed: int | None = None
)

Parameters

ParameterTypeDescription
backendBackendQuantum backend for circuit execution
num_qubitsintNumber of qubits in the circuit
seedint | NoneRandom seed for reproducibility

Methods

optimize()
def optimize(
max_iters: int = 100,
neighbors: int = 8,
cost_function: Callable | None = None,
callback: Callable | None = None,
early_stop_threshold: float | None = None,
) -> OptimizationResult

Run general optimization with custom cost function.

Parameters:

ParameterTypeDefaultDescription
max_itersint100Maximum iterations
neighborsint8Neighbors to evaluate per iteration
cost_functionCallableNoneCustom cost function
callbackCallableNoneProgress callback
early_stop_thresholdfloatNoneStop when cost below threshold

Returns: OptimizationResult

optimize_ghz()
def optimize_ghz(
max_iters: int = 100,
neighbors: int = 8,
callback: Callable | None = None,
) -> OptimizationResult

Optimize for GHZ state preparation.

optimize_vqe()
def optimize_vqe(
hamiltonian: Any,
max_iters: int = 100,
neighbors: int = 8,
callback: Callable | None = None,
) -> OptimizationResult

Optimize for VQE with given Hamiltonian.


softqcos.OptimizationResult

Dataclass containing optimization results.

@dataclass
class OptimizationResult:
fidelity: float
final_cost: float
total_evaluations: int
iterations: int
converged: bool
optimal_params: np.ndarray
history: list[tuple[float, float]]

Attributes

AttributeTypeDescription
fidelityfloatFinal state fidelity (0-1)
final_costfloatFinal cost function value
total_evaluationsintTotal circuit evaluations
iterationsintNumber of iterations completed
convergedboolWhether optimization converged
optimal_paramsnp.ndarrayOptimal parameter values
historylist(cost, fidelity) per iteration

Backends Module

Base Backend Protocol

from typing import Protocol

class Backend(Protocol):
def execute(self, circuit: Any, shots: int = 1024) -> dict[str, int]:
"""Execute circuit and return counts."""
...

def get_statevector(self, circuit: Any) -> np.ndarray:
"""Get statevector from circuit."""
...

@property
def num_qubits(self) -> int:
"""Number of qubits."""
...

softqcos.AerBackend

Qiskit Aer backend for statevector and sampling simulation.

from softqcosimport AerBackend

backend = AerBackend(
num_qubits: int,
method: str = "statevector",
shots: int = 1024,
device: str = "CPU",
)

Parameters

ParameterTypeDefaultDescription
num_qubitsint-Number of qubits
methodstr"statevector"Simulation method
shotsint1024Number of shots for sampling
devicestr"CPU"Device ("CPU" or "GPU")

Supported methods: "statevector", "density_matrix", "stabilizer", "extended_stabilizer", "matrix_product_state"


softqcos.AerMPSBackend

Matrix Product State backend for large circuits (50+ qubits).

from softqcosimport AerMPSBackend

backend = AerMPSBackend(
num_qubits: int,
bond_dimension: int = 64,
shots: int = 1024,
)

Parameters

ParameterTypeDefaultDescription
num_qubitsint-Number of qubits
bond_dimensionint64MPS bond dimension
shotsint1024Number of shots

Note: Higher bond_dimension = more accurate but slower/more memory.


softqcos.backends.CirqBackend

Google Cirq backend adapter.

from softqcos.backends import CirqBackend

backend = CirqBackend(
num_qubits: int,
noise_model: Any | None = None,
)

softqcos.backends.PennyLaneBackend

PennyLane backend adapter.

from softqcos.backends import PennyLaneBackend

backend = PennyLaneBackend(
num_qubits: int,
device: str = "default.qubit",
)

Supported devices: "default.qubit", "default.mixed", "lightning.qubit", etc.


softqcos.backends.BraketBackend

Amazon Braket backend adapter.

from softqcos.backends import BraketBackend

backend = BraketBackend(
num_qubits: int,
device: str = "local",
s3_bucket: str | None = None,
)

Supported devices:

  • "local" - Local simulator
  • "sv1" - AWS SV1 simulator
  • "tn1" - AWS TN1 simulator
  • "dm1" - AWS DM1 density matrix

Backend Factory

from softqcos.backends import get_backend

# Get backend by name
backend = get_backend(
name: str,
num_qubits: int,
**kwargs
)

Available names: "aer", "aer-mps", "cirq", "pennylane", "braket"


Cost Functions Module

Available Functions

from softqcos.core.cost_functions import (
correlation_cost,
bitstring_cost,
hybrid_cost,
energy_cost,
get_cost_function,
COST_FUNCTIONS,
)

correlation_cost

def correlation_cost(
counts: dict[str, int],
num_qubits: int,
target: str = "ghz",
) -> float

Dense correlation-based cost using ⟨Z_i Z_j⟩ expectations.

Best for: GHZ states (recommended default)


bitstring_cost

def bitstring_cost(
counts: dict[str, int],
num_qubits: int,
target: str = "ghz",
) -> float

Sparse bitstring matching cost.

Best for: Specific target state preparation


hybrid_cost

def hybrid_cost(
counts: dict[str, int],
num_qubits: int,
target: str = "ghz",
alpha: float = 0.7,
) -> float

Hybrid cost: α × correlation + (1-α) × parity.

Best for: General purpose optimization


energy_cost

def energy_cost(
counts: dict[str, int],
num_qubits: int,
hamiltonian: Any,
) -> float

Energy expectation value for VQE.

Best for: VQE problems with Hamiltonians


Cost Function Registry

# Get function by name
cost_fn = get_cost_function("correlation")
cost_fn = get_cost_function("bitstring")
cost_fn = get_cost_function("hybrid")
cost_fn = get_cost_function("energy")

# List available functions
print(list(COST_FUNCTIONS.keys()))
# ['correlation', 'bitstring', 'hybrid', 'energy']

CLI Module

Commands

softqcosrun

Run optimization.

softqcosrun ghz [OPTIONS]

Options:
--qubits INTEGER Number of qubits [default: 10]
--max-iters INTEGER Maximum iterations [default: 100]
--neighbors INTEGER Neighbors per iteration [default: 8]
--backend TEXT Backend name [default: aer]
--seed INTEGER Random seed
--output PATH Output file (JSON)
--verbose / --quiet Verbosity level

softqcosbenchmark

Run benchmark suite.

softqcosbenchmark [OPTIONS]

Options:
--qubits TEXT Qubit counts (comma-separated) [default: 5,10,20]
--max-iters INTEGER Max iterations per run [default: 100]
--backends TEXT Backends to test [default: aer]
--output PATH Output file (JSON)

softqcosinfo

Show system information.

softqcosinfo

softqcosversion

Show version.

softqcosversion

API Server Module

Endpoints

GET /health

Health check endpoint.

Response:

{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z"
}

GET /info

System information.

Response:

{
"version": "0.1.0",
"python_version": "3.11.0",
"backends": ["aer", "aer-mps", "cirq", "pennylane", "braket"]
}

POST /jobs

Submit async optimization job.

Request:

{
"num_qubits": 10,
"problem_type": "ghz",
"max_iters": 100,
"backend": "aer"
}

Response:

{
"job_id": "abc123",
"status": "pending",
"created_at": "2024-01-15T10:30:00Z"
}

GET /jobs/{job_id}

Get job status and results.

POST /optimize

Run synchronous optimization (blocking).

Request:

{
"num_qubits": 10,
"problem_type": "ghz",
"max_iters": 100,
"backend": "aer"
}

Response:

{
"fidelity": 0.9876,
"final_cost": 0.0124,
"total_evaluations": 150,
"iterations": 45,
"converged": true
}

POST /benchmarks

Run benchmark suite.


Utilities Module

Logging

from softqcos.utils.logging import setup_logging, get_logger

# Setup logging
setup_logging(level="INFO", format="rich")

# Get logger
logger = get_logger(__name__)
logger.info("Starting optimization")

Type Hints

QCOS is fully typed. Import types:

from softqcosimport (
Optimizer,
OptimizationResult,
Backend,
AerBackend,
AerMPSBackend,
)

from softqcos.backends import (
BackendConfig,
BaseBackend,
)

from softqcos.core.cost_functions import CostFunction