Code ergonomics: Create SparseObservable from QkObs

未关闭
#162 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
58/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
冷清
技术栈
c, cpp

调研方向

Start at the SparseObservable API and inspect the existing constructors alongside the QkObs accessors used in the proposal. Implement the conversion entry point so it preserves qubit count, coefficients, boundaries, bit terms, and indices, then verify the multi-bit-term example and the error path from qk_obs_term.

由索引模型根据 Issue 内容生成。

描述

What should we add?

Hello, I wanted to propose an alternative from method for creating SparseObservable objects.

The idea would be to receive a C QkObs pointer where it's extracted its data in order to construct a new SparseObservable object. This would be beneficial if it's wanted to construct observables where the terms have more than one bit_term.

I believe the implementation could be something like the following:

static SparseObservable from_obs(QkObs *obs)
{
    QkComplex64 *c_coeffs = qk_obs_coeffs(obs);
    size_t *c_boundaries = qk_obs_boundaries(obs);
    
    size_t terms_len = qk_obs_num_terms(obs);

    std::vector<size_t> boundaries(terms_len + 1);
    std::vector<std::complex<double>> coeffs(terms_len);
    
    std::vector<QkBitTerm> bit_terms;
    reg_t indices;

    QkObsTerm term;
    for (size_t i = 0; i < terms_len + 1; i++)
    {
        boundaries[i] = c_boundaries[i];
        if (i < terms_len)
        {
            if (qk_obs_term(obs, i, &term) != QkExitCode_Success) {
                throw std::runtime_error("Error while obtaining term from observable.");
            }
            coeffs[i] = std::complex<double>(term.coeff.re, term.coeff.im);
            for (size_t j = 0; j < term.len; j++)
            {
                bit_terms.push_back(term.bit_terms[j]);
                indices.push_back(term.indices[j]);
            }
        }
    }

    return SparseObservable(qk_obs_num_qubits(obs), coeffs, bit_terms, indices, boundaries);
}

And the usage could be something like the following:

size_t num_qubits = 3;
QkObs *obs = qk_obs_zero(num_qubits);

QkBitTerm zz[2] = {QkBitTerm_Z, QkBitTerm_Z};
uint32_t zz_q[2] = {0, 1};
QkObsTerm zz_term = {{1, 0.}, 2, zz, zz_q, num_qubits};
qk_obs_add_term(obs, &zz_term);

QkBitTerm x[1] = {QkBitTerm_X};
uint32_t x_q[1] = {2};
QkObsTerm x_term = {{1, 0.}, 1, x, x_q, num_qubits};
qk_obs_add_term(obs, &x_term);

auto cpp_obs = SparseObservable::from_obs(obs);

qk_obs_free(obs);
主要语言
C++
星标
41
派生
26
平均合并
1 天 15 小时
30 天内合并 PR
1

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 有 Pull Request 模板
  • 没有贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

Qiskit/qiskit-cpp 的其他 Issue

查看 Qiskit/qiskit-cpp 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。