Alterlab cirq

From AlterLab-IEU/AlterLab-Academic-Skills · View interactive version

Alterlab cirq is an AI agent skill from the GitHub repository AlterLab-IEU/AlterLab-Academic-Skills. Builds, simulates, and runs quantum circuits with Cirq, Google Quantum AI's framework for NISQ hardware, noise-aware low-level circuit design, and noise characterization. Use when targeting Google Quantum AI processors or their Quantum Virtual Machine models (Willow, Sycamore-class Rainbow/Weber), I

How to use this skill

Skill file

Cirq - Quantum Computing with Python

Cirq is Google Quantum AI's open-source framework for designing, simulating, and running quantum circuits on quantum computers and simulators.

Keyless by default. The core of this skill — building circuits, exact and noisy simulation (cirq.Simulator, cirq.DensityMatrixSimulator), parameter sweeps, characterization experiments, and the noisy Quantum Virtual Machine — runs entirely offline with no account or token. Real-hardware submission (the providers below) is an optional add-on that uses the provider's own credentials; when a hardware token is absent, design and validate the circuit and run it on the simulator/QVM first.

When to Use This Skill

Use this skill when the user wants to:

Does NOT Trigger

| Scenario | Use Instead |

|----------|-------------|

| IBM Quantum hardware, Qiskit Runtime primitives, or Qiskit transpilation | alterlab-qiskit |

| Gradient-trained quantum ML / hybrid models with autodiff | alterlab-pennylane |

| Lindblad master equations, decoherence, or cavity-QED dynamics (no circuits) | alterlab-qutip |

Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-qiskit) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.

Installation

uv pip install cirq          # Python ≥ 3.11; current 1.7.x as of 2026-09

The cirq package is a meta-package that already pulls in cirq-core, cirq-google,

cirq-ionq, cirq-aqt, cirq-pasqal, and cirq-web; install cirq-core alone for a

lightweight simulation-only environment. Optional extras:

# OpenQASM import (cirq.contrib.qasm_import needs `ply`), quimb tensor-network tools
uv pip install "cirq-core[contrib]"

# Azure Quantum — its `cirq` extra pins cirq-core 1.6.x, so use a separate environment
uv pip install "azure-quantum[cirq]"

Quick Start

Basic Circuit

import cirq
import numpy as np

# Create qubits
q0, q1 = cirq.LineQubit.range(2)

# Build circuit
circuit = cirq.Circuit(
    cirq.H(q0),              # Hadamard on q0
    cirq.CNOT(q0, q1),       # CNOT with q0 control, q1 target
    cirq.measure(q0, q1, key='result')
)

print(circuit)

# Simulate
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=1000)

# Display results
print(result.histogram(key='result'))

Parameterized Circuit

import sympy

# Define symbolic parameter
theta = sympy.Symbol('theta')

# Create parameterized circuit
circuit = cirq.Circuit(
    cirq.ry(theta)(q0),
    cirq.measure(q0, key='m')
)

# Sweep over parameter values
sweep = cirq.Linspace('theta', start=0, stop=2*np.pi, length=20)
results = simulator.run_sweep(circuit, params=sweep, repetitions=1000)

# Process results
for params, result in zip(sweep, results):
    theta_val = params['theta']
    counts = result.histogram(key='m')
    print(f"θ={theta_val:.2f}: {counts}")

Core Capabilities

Circuit Building

For comprehensive information about building quantum circuits, including qubits, gates, operations, custom gates, and circuit patterns, see:

Common topics:

Simulation

For detailed information about simulating quantum circuits, including exact simulation, noisy simulation, parameter sweeps, and the Quantum Virtual Machine, see:

Common topics:

Circuit Transformation

For information about optimizing, compiling, and manipulating quantum circuits, see:

Common topics:

Hardware Integration

For information about running circuits on real quantum hardware from various providers, see:

Supported providers:

Topics include device representation, qubit selection, authentication, job management, and circuit optimization for hardware.

Noise Modeling

For information about modeling noise, noisy simulation, characterization, and error mitigation, see:

Common topics:

Quantum Experiments

For information about designing experiments, parameter sweeps, data collection, and using the ReCirq framework, see:

Common topics:

Common Patterns

Variational Algorithm Template

import scipy.optimize

def variational_algorithm(ansatz, cost_function, initial_params):
    """Template for variational quantum algorithms."""

    def objective(params):
        circuit = ansatz(params)
        simulator = cirq.Simulator()
        result = simulator.simulate(circuit)
        return cost_function(result)

    # Optimize
    result = scipy.optimize.minimize(
        objective,
        initial_params,
        method='COBYLA'
    )

    return result

# Define ansatz
def my_ansatz(params):
    q = cirq.LineQubit(0)
    return cirq.Circuit(
        cirq.ry(params[0])(q),
        cirq.rz(params[1])(q)
    )

# Define cost function
def my_cost(result):
    state = result.final_state_vector
    # Calculate cost based on state
    return np.real(state[0])

# Run optimization
result = variational_algorithm(my_ansatz, my_cost, [0.0, 0.0])

Hardware Execution Template

def run_on_hardware(circuit, provider='google', device_name='<processor_id>',
                    device_config='<config_name>', target='ionq.simulator',
                    repetitions=1000):
    """Template for running on quantum hardware."""

    if provider == 'google':
        # Approved Quantum Engine users only; otherwise use the Quantum Virtual Machine
        # (cirq_google.engine.create_default_noisy_quantum_virtual_machine).
        import cirq_google
        engine = cirq_google.get_engine()          # uses GOOGLE_CLOUD_PROJECT
        processor = engine.get_processor(device_name)
        # cirq-google 1.7: device_config_name is required (see processor.list_configs())
        # and run() returns a cirq.Result directly.
        return processor.run(circuit, device_config_name=device_config,
                             repetitions=repetitions)

    elif provider == 'ionq':
        import cirq_ionq
        service = cirq_ionq.Service()              # reads IONQ_API_KEY
        return service.run(circuit, repetitions=repetitions, target='qpu')

    elif provider == 'azure':
        from azure.quantum.cirq import AzureQuantumService
        # Setup workspace...
        service = AzureQuantumService(workspace)
        # Target names are system-specific (e.g. 'ionq.qpu.forte-1'); see service.targets()
        return service.run(circuit, repetitions=repetitions, target=target)

    else:
        raise ValueError(f"Unknown provider: {provider}")

Noise Study Template

def noise_comparison_study(circuit, noise_levels):
    """Compare circuit performance at different noise levels."""

    results = {}

    for noise_level in noise_levels:
        # Create noisy circuit
        noisy_circuit = circuit.with_noise(cirq.depolarize(p=noise_level))

        # Simulate
        simulator = cirq.DensityMatrixSimulator()
        result = simulator.run(noisy_circuit, repetitions=1000)

        # Analyze
        results[noise_level] = {
            'histogram': result.histogram(key='result'),
            'dominant_state': max(
                result.histogram(key='result').items(),
                key=lambda x: x[1]
            )
        }

    return results

# Run study
noise_levels = [0.0, 0.001, 0.01, 0.05, 0.1]
results = noise_comparison_study(circuit, noise_levels)

Best Practices

  1. Circuit Design
  1. Simulation
  1. Hardware Execution
  1. Circuit Optimization
  1. Noise Modeling
  1. Experiments

Additional Resources

Common Issues

Circuit too deep for hardware:

Memory issues with simulation:

Device validation errors:

Part of the AlterLab Academic Skills suite.

Noisy simulation too slow:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.