Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[アイデア]「2個の量子ビットを降順にする」を簡単に実装する #41

Open
derwind opened this issue Jul 11, 2023 · 0 comments

Comments

@derwind
Copy link
Contributor

derwind commented Jul 11, 2023

[温度計パズル] を見ていて、覚えたら良いだけですが、「2個の量子ビットを降順にする」の内容がすんなりと頭に入らないなと思いました。これを踏まえて、以下のようなヘルパークラスを考えてみました。まだ汎用性はないのですが、「8bit表現」のケースも受け付けられるようにできれば、そこそこコーディングが楽になりそうな気もします。

from __future__ import annotations
import enum
from tytan.symbol import sympy_symbols

# 不等式の制約条件のタイプ
class CondType(enum.IntEnum):
    UNKNOWN = 0
    GREATER_THAN = enum.auto()
    GREATER_THAN_OR_EQUAL_TO = enum.auto()

# 不等式の制約条件の生成器
class Cond:
    def __init__(self, q: sympy_symbols, followers: list[tuple[sympy_symbols, CondType]] | None = None):
        self._q = q
        if followers is not None:
            self._followers = followers
        else:
            self._followers = []

    def greater_than(self, other: sympy_symbols, or_equal_to: bool = False) -> Cond:
        if or_equal_to:
            return Cond(self._q, self._followers + [(other, CondType.GREATER_THAN_OR_EQUAL_TO)])
        else:
            return Cond(self._q, self._followers + [(other, CondType.GREATER_THAN)])

    def __call__(self):
        constraint = 0
        cur_q = self._q
        for next_q, typ in self._followers:
            if typ == CondType.GREATER_THAN_OR_EQUAL_TO:
                constraint += (1 - cur_q) * next_q
            elif typ == CondType.GREATER_THAN:
                constraint += (1 - cur_q) + next_q
            cur_q = next_q
        return constraint

●使用例 (温度計パズル)

H += Cond(q08).greater_than(q04, or_equal_to=True).greater_than(q00, or_equal_to=True)() #8→4→0の連鎖
H += Cond(q05).greater_than(q01, or_equal_to=True)()
H += Cond(q03).greater_than(q02, or_equal_to=True)()
H += Cond(q07).greater_than(q06, or_equal_to=True)()
H += Cond(q11).greater_than(q10, or_equal_to=True).greater_than(q09, or_equal_to=True)() #11→10→9の連鎖
H += Cond(q13).greater_than(q12, or_equal_to=True)()
H += Cond(q15).greater_than(q14, or_equal_to=True)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant