К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

Qiskit — скилл для Claude Code: квантовые схемы и IBM QPU

Скилл для разработки квантовых алгоритмов: строит схемы, транспилирует их под конкретное железо, запускает на симуляторах или реальных квантовых процессорах IBM. Нужен Python 3.10+ и опциональные компоненты в зависимости от задачи.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add K-Dense-AI/scientific-agent-skills --skill qiskit -a claude-code
Открыть на GitHub

Что делает qiskit

Работает с Qiskit 2.x и V2 примитивами (Sampler, Estimator). Позволяет строить параметризованные схемы, оптимизировать их один раз под выбранный бэкенд, а затем исполнять с разными параметрами через PUB (Primitive Unified Blocs). Поддерживает локальное моделирование через StatevectorSampler и StatevectorEstimator, высокопроизводительную симуляцию через Qiskit Aer, запуск на IBM квантовых процессорах через qiskit-ibm-runtime с сессиями и батчами, применение техник шумного моделирования и коррекции ошибок.

Для локальных рабочих потоков требуется только qiskit с плагином [visualization]. Для симуляции с шумом нужна qiskit-aer. Для доступа к IBM QPU обязательны qiskit-ibm-runtime, учётная запись на IBM Quantum Platform, API-ключ и сетевой доступ. Скилл ориентирован на аппаратно-совместимые ISA-схемы: сначала транспилируешь параметризованную схему один раз, затем подставляешь значения параметров в батч исполнений.

Проверен 2026-10-01 локально на Qiskit 2.5.2, Runtime 0.50.0 и Aer 0.17.2. Важно помнить, что Runtime 0.50 переместил SamplerV2 и EstimatorV2 в executor_sampler и executor_estimator, а не в топ-уровень пакета — новый код должен импортировать оттуда.

Какие задачи решает

  • Запустить параметризованный квантовый алгоритм на IBM QPU
  • Смоделировать квантовую схему с классическими регистрами и получить корреляции битов
  • Транспилировать и оптимизировать схему под конкретный бэкенд
  • Применить коррекцию ошибок и шумное моделирование при исполнении

Примеры запросов агенту

  • Напиши скилл для построения Bell-пары, её симуляции и вывода распределения битов
  • Создай параметризованную схему с параметром theta, вычисли ожидаемое значение оператора ZZ для трёх значений theta на IBM QPU
  • Транспилируй мою схему под доступный бэкенд, примени оптимизацию и запусти с 1024 шотами

Как установить qiskit

1Через Skills CLI (Vercel)

npx skills add K-Dense-AI/scientific-agent-skills --skill qiskit -a claude-code

2Вручную: положить файлы

~/.claude/skills/qiskit/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/qiskit/

Из того же набора120

Весь набор →
scientific-visualization K-Dense-AI Помогает создавать и проверять научные графики для публикаций в Matplotlib, Seaborn и Plotly с соблюдением требований к данным и контрасту. Claude Code CX Codex Cursor +1 2 400установок scientific-writing K-Dense-AI Скилл помогает писать и проверять научные рукописи и отчёты, связывая утверждения с проверенными источниками. Пригодится перед аудитом, подготовкой разделов и подачей статьи. Claude Code CX Codex Cursor +1 2 400установок statistical-analysis K-Dense-AI Проводит статистические тесты с проверкой предпосылок, расчётом размера эффекта и отчётом в формате APA. Покрывает t-тесты, ANOVA, корреляцию, регрессию, непараметрику и байесовские методы. Claude Code CX Codex Cursor +1 2 300установок scientific-brainstorming K-Dense-AI Скилл структурирует научный мозговой штурм: от независимой генерации идей до состязательного ревью и журнала решений. Помогает отобрать направления исследований без преждевременных выводов. Claude Code CX Codex Cursor +1 2 300установок literature-review K-Dense-AI Скилл ищет и систематизирует научные публикации, проверяет цитаты и помогает собрать обзор в Markdown или PDF. Подходит для воспроизводимого поиска и скрининга. Claude Code CX Codex Cursor +1 2 300установок scientific-critical-thinking K-Dense-AI Скилл для оценки научных утверждений, методологии исследований и качества доказательств. Применяет фреймворки GRADE и Cochrane Risk of Bias. Claude Code CX Codex Cursor +1 2 300установок scientific-schematics K-Dense-AI Создаёт черновики научных схем в PNG и проверяет их качество через отдельную модель. Пригодится для архитектур нейросетей, блок-схем и биологических путей. Claude Code CX Codex Cursor +1 2 200установок scikit-learn K-Dense-AI Скилл для задач машинного обучения на Python: классификация, регрессия, кластеризация, препроцессинг и сборка ML-пайплайнов с библиотекой scikit-learn 1.9.1. Claude Code CX Codex Cursor +1 2 200установок

Похожие

azure-architecture-autopilot официальный github Скилл проектирует архитектуру Azure по запросу или анализирует существующие ресурсы, затем помогает создать и проверить Bicep перед развёртыванием. Пригодится для нового проекта и изменений в текущей инфраструктуре. GitHub Copilot 1 500установок agent-owasp-compliance официальный github Проверяет кодовую базу AI-агента по 10 рискам OWASP ASI. Подойдёт для аудита перед production и подготовки отчёта по безопасности. GitHub Copilot 1 500установок rag-architect https://github.com/Jeffallan Проектирует RAG-системы: разбивает документы на чанки, генерирует эмбеддинги, настраивает векторные базы, строит гибридный поиск и оценивает качество извлечения контекста. Claude Code CX Codex Cursor +1 4 700установок ads-microsoft AgriciDaniel Проверяет кампании Microsoft Ads, Bing Ads, UET и аудиторий сети: измерения, конверсии, импорты из Google, ключевые слова, креативы, ставки и бюджеты. Только чтение; изменения делает ads-optimize. Claude Code CX Codex Cursor +1 3 800установок azure-speech-to-text calesthio Транскрибирует аудио в текст через REST API Azure AI Speech с таймкодами слов и разделением по спикерам. Помогает собирать субтитры в пайплайнах OpenMontage без долгой локальной обработки. Claude Code CX Codex Cursor +1 763установок langgraph-persistence langchain-ai Скилл по персистентности LangGraph: как подключить checkpointer, развести диалоги по thread_id и откатиться к прошлому состоянию графа. Claude Code CX Codex Cursor +1 18 000установок skill-creator официальный anthropics Помогает создать новый скилл, доработать существующий и проверить результат через тестовые промпты и оценки. Claude Code Claude.ai 414 180установок writing-for-agents Matt Pocock Помогает писать скиллы и документы с инструкциями для агентов. Пригодится при правках AGENTS.md, CLAUDE.md и связанных справочных файлов. Claude Code 466 719установок

Вопросы о qiskit

Как установить Qiskit в Claude Code?

Выполни npx skills add K-Dense-AI/scientific-agent-skills --skill qiskit -a claude-code, затем скилл будет доступен в ~/.claude/skills/qiskit/SKILL.md.

Что делает Qiskit скилл?

Строит квантовые схемы, оптимизирует их под аппаратное обеспечение, исполняет через локальные симуляторы или IBM квантовые процессоры, применяет коррекцию ошибок и возвращает результаты с метаданными.

Какие зависимости нужны для работы с IBM QPU?

Обязательны qiskit-ibm-runtime==0.50.0, активная учётная запись на IBM Quantum Platform, API-ключ и доступ в сеть. Для локального моделирования достаточно основного qiskit пакета.

Исходный текст

SKILL.md · Apache-2.0
---
name: qiskit
description: Builds, simulates, transpiles, and executes quantum circuits with Qiskit and IBM Quantum Runtime. Use for Qiskit 2.x circuits and operators, V2 Sampler or Estimator primitives, target-aware transpilation, local or noisy simulation, IBM QPU execution, Runtime sessions or batches, error mitigation, and Qiskit ecosystem packages.
license: Apache-2.0
compatibility: Python 3.10+ on a supported 64-bit platform. Local SDK workflows need qiskit; noisy simulation needs qiskit-aer; IBM QPU access needs qiskit-ibm-runtime, network access, an IBM Quantum Platform account, and an API key.
metadata:
  version: "2.3"
  last-reviewed: "2026-10-01"
  skill-author: K-Dense Inc.
---

# Qiskit

Use current Qiskit 2.x APIs to build circuits, prepare hardware-compatible instruction set architecture (ISA) circuits, and execute them through V2 primitives.

Reviewed **2026-10-01** with local tests on `qiskit==2.5.2`, `qiskit-ibm-runtime==0.50.0`, and `qiskit-aer==0.17.2`. IBM account, QPU, session, and batch examples are illustrative and documentation/source-checked; no remote workloads were submitted. See [references/sources.md](references/sources.md) for the verification boundary.

Runtime 0.50 deprecates the top-level `SamplerV2`/`EstimatorV2` implementations. New code imports `Sampler` from `qiskit_ibm_runtime.executor_sampler` and `Estimator` from `qiskit_ibm_runtime.executor_estimator`. These still implement the V2 PUB interface, using client-side processing and `Executor`. Use option models from `qiskit_ibm_runtime.options_models`.

## Choose the Right Path

| Goal | Recommended interface |
|---|---|
| Ideal evolution with finite-shot sampling | `qiskit.primitives.StatevectorSampler` |
| Exact local expectation values | `qiskit.primitives.StatevectorEstimator` |
| High-performance or noisy simulation | Qiskit Aer |
| IBM QPU sampling | `qiskit_ibm_runtime.executor_sampler.Sampler` |
| IBM QPU expectation values and mitigation | `qiskit_ibm_runtime.executor_estimator.Estimator` |
| Backend without native primitives | `BackendSamplerV2` or `BackendEstimatorV2` |
| Open-system or master-equation dynamics | Prefer QuTiP |
| Differentiable quantum machine learning | Prefer PennyLane unless Qiskit integration is required |

## Installation

Create an isolated environment and install only the components needed:

```bash
uv venv --python 3.13
source .venv/bin/activate

# Core SDK plus plotting support
uv pip install "qiskit[visualization]==2.5.2"

# Add only when needed
uv pip install "qiskit-ibm-runtime==0.50.0"
uv pip install "qiskit-aer==0.17.2"
```

Do not install `qiskit-terra`; it was superseded by the `qiskit` distribution. Qiskit Runtime, Aer, Nature, Machine Learning, Optimization, and Algorithms are separate distributions.

For IBM account setup, CI-safe credential handling, optional packages, and environment repair, read [references/setup.md](references/setup.md).

## Core Workflow

Follow this sequence for every hardware-oriented workload:

1. **Map** the problem to a circuit and, for Estimator, one or more observables.
2. **Optimize** the parameterized circuit once for the selected backend.
3. **Apply the layout** to every observable.
4. **Execute** ISA circuits through a V2 primitive using Primitive Unified Blocs (PUBs).
5. **Analyze** register-aware results, metadata, uncertainty, and resource usage.

Do not bind and retranspile a parameterized circuit inside every optimizer iteration. Transpile the parameterized circuit once, then pass parameter arrays in PUBs.

## Quick Local Sampling

```python
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler

circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()  # creates the classical register named "meas"

sampler = StatevectorSampler(seed=7)
pub_result = sampler.run([circuit], shots=1024).result()[0]
counts = pub_result.data.meas.get_counts()
print(counts)
```

Sampler V2 preserves shots and classical-register structure. Access the register by its actual name; `measure_all()` uses `meas`.

For circuits with multiple classical registers, each register’s counts are a marginal distribution. Preserve shot alignment when computing cross-register correlations; multiplying marginal frequencies destroys those correlations. Use `SamplerPubResult.join_data` with an explicit register order for joint bitstrings and record that order in the result labels. Qiskit 2.5.2 puts the first joined `BitArray` register in the least-significant bits, contrary to the current docstring; verify with an asymmetric state. See [references/primitives.md](references/primitives.md).

## Quick Local Estimation

```python
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.primitives import StatevectorEstimator
from qiskit.quantum_info import SparsePauliOp

theta = Parameter("theta")
circuit = QuantumCircuit(2)
circuit.ry(theta, 0)
circuit.cx(0, 1)

observable = SparsePauliOp.from_list([("ZZ", 1.0), ("XX", 0.5)])
parameter_values = [[0.0], [np.pi / 4], [np.pi / 2]]

estimator = StatevectorEstimator(seed=7)
pub = (circuit, observable, parameter_values)
pub_result = estimator.run([pub]).result()[0]
print(pub_result.data.evs)
```

Estimator circuits should not contain final measurements. PUB arrays broadcast; verify circuit parameter order before constructing large sweeps.

## IBM QPU Sampling

This example assumes credentials were saved securely as described in [references/setup.md](references/setup.md). It never embeds or prints an API key.

```python
from qiskit import QuantumCircuit
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime.executor_sampler import Sampler

service = QiskitRuntimeService()
backend = service.least_busy(
    operational=True,
    simulator=False,
    min_num_qubits=2,
)

circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()

pass_manager = generate_preset_pass_manager(
    backend=backend,
    optimization_level=1,
    seed_transpiler=7,
)
isa_circuit = pass_manager.run(circuit)

sampler = Sampler(mode=backend)
job = sampler.run([isa_circuit], shots=1024)
print("job_id:", job.job_id())
counts = job.result()[0].data.meas.get_counts()
```

Save the job ID before waiting for results so the job can be retrieved later.

## IBM QPU Estimation

Runtime Estimator requires both an ISA circuit and observables mapped through the transpiler layout:

```python
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.transpiler import generate_preset_pass_manager
from qiskit_ibm_runtime.executor_estimator import Estimator

circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
observable = SparsePauliOp.from_list([("ZZ", 1.0)])

pass_manager = generate_preset_pass_manager(
    backend=backend,
    optimization_level=1,
    seed_transpiler=7,
)
isa_circuit = pass_manager.run(circuit)
isa_observable = observable.apply_layout(isa_circuit.layout)

estimator = Estimator(
    mode=backend,
    options={"resilience_level": 1},
)
pub_result = estimator.run(
    [(isa_circuit, isa_observable)],
    precision=0.02,
).result()[0]
print(pub_result.data.evs, pub_result.data.stds)
```

Error mitigation is not guaranteed to improve every workload and increases cost. Record finalized options (`estimator.finalize_options().model_dump()`), result metadata, and usage. A Runtime `dry_run=True` call is a server submission returning randomized mock data, not a local simulator or scientific validation.

## Non-Negotiable Qiskit 2.x Rules

- Use V2 primitive interfaces and PUB inputs. Do not write new V1 `Sampler`, `Estimator`, or `QuantumInstance` code.
- Runtime primitives accept ISA circuits; they do not perform layout, routing, and basis translation for you.
- Apply the transpiler layout to Estimator observables with `observable.apply_layout(isa_circuit.layout)`.
- Use `mode=backend`, `mode=session`, or `mode=batch` for Runtime primitives.
- Use the Runtime client-side `Estimator` for resilience levels and expectation-value mitigation. Sampler has different noise-management options and no Estimator-style resilience levels.
- Treat `BackendV2.target`, `backend.operation_names`, `backend.coupling_map`, and direct backend attributes as the source of hardware constraints. Do not use `backend.configuration()` or `BackendProperties`.
- Read Sampler output by classical register name. Bitstrings are displayed most-significant bit first; Qiskit qubit 0 is conventionally the least-significant bit.
- Use a fixed `seed_transpiler` when comparing compilation settings. A simulator seed does not make QPU results deterministic.
- `qiskit.pulse` was removed in Qiskit 2.0. Use supported fractional gates for IBM hardware. Qiskit Dynamics is archived; isolate legacy pulse-model research and verify its dependency stack separately.
- QPY is the Qiskit-native circuit serialization format. Do not use Python pickle for untrusted circuit artifacts.

See [references/migration.md](references/migration.md) for a detailed old-to-current API map.

## Execution Modes

Choose based on workload shape and account plan:

- **Job mode**: one-off work; instantiate a primitive with `mode=backend`.
- **Batch mode**: independent jobs submitted together; available on the Open Plan.
- **Session mode**: iterative jobs that benefit from prioritized follow-on execution; unavailable on the Open Plan.

```python
from qiskit_ibm_runtime import Batch
from qiskit_ibm_runtime.executor_sampler import Sampler

with Batch(backend=backend, max_time="10m") as batch:
    sampler = Sampler(mode=batch)
    jobs = [sampler.run([circuit], shots=1024) for circuit in isa_circuits]

results = [job.result() for job in jobs]
```

Close sessions and batches after submission. Exiting their context stops new submissions but allows accepted jobs to finish, subject to service limits.

## Reference Map

Read only the files needed for the current task:

| Topic | Reference |
|---|---|
| Versions, installation, authentication, CI | [references/setup.md](references/setup.md) |
| Circuits, parameters, control flow, QPY | [references/circuits.md](references/circuits.md) |
| V2 PUBs, broadcasting, local and Runtime results | [references/primitives.md](references/primitives.md) |
| Targets, ISA circuits, layouts, pass managers | [references/transpilation.md](references/transpilation.md) |
| IBM backends, modes, jobs, Aer, mitigation | [references/backends.md](references/backends.md) |
| End-to-end map/optimize/execute/analyze patterns | [references/patterns.md](references/patterns.md) |
| Algorithms, addons, Nature, ML, Optimization | [references/algorithms.md](references/algorithms.md) |
| Circuit, result, state, and backend plots | [references/visualization.md](references/visualization.md) |
| Qiskit 0.x/1.x and Runtime migration | [references/migration.md](references/migration.md) |
| Testing, reproducibility, and troubleshooting | [references/testing.md](references/testing.md) |
| Upstream docs, release notes, and version baseline | [references/sources.md](references/sources.md) |

## Bundled Scripts

Run from the skill directory:

```bash
# Installed-package and legacy-environment checks; no network or credential reads
python scripts/check_environment.py

# Runnable V2 local Sampler and Estimator example
python scripts/run_local_primitives.py --shots 1024 --seed 7

# Read-only IBM backend capability inspection; uses saved credentials
python scripts/inspect_runtime.py --min-qubits 5
```

The Runtime inspection script selects or inspects a backend but never submits a quantum job.

## Final Checklist

Before returning Qiskit code:

1. Confirm package versions and Python compatibility.
2. Run locally with statevector primitives or Aer.
3. Verify parameter order, observable qubit count, and classical-register names.
4. Transpile against the exact `BackendV2` target and inspect depth and two-qubit operations.
5. Apply the final layout to every observable.
6. Estimate QPU cost and choose job, batch, or session mode.
7. Save job IDs, package versions, seeds, backend name, primitive options, and result metadata.
8. Never expose API keys in source, logs, notebooks, or version control.

## Citing Scientific Agent Skills

This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a
manuscript, report, presentation, or code release, add the paper to the references or
software section and tell the user you did so:

> Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent
> Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065.
> https://doi.org/10.48550/arXiv.2609.00065

Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
latest arXiv version, so never append a version suffix such as `v1`. When network access is
available, fetch https://arxiv.org/abs/2609.00065 (or
http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
the author list, year, and version from that record. If the record lists a journal reference
or publisher DOI, cite the published version instead.

© K-Dense-AI · Apache-2.0 · K-Dense-AI/scientific-agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой