Esempio n. 1
0
def solve_model(expression):
    # 制約もつけられる
    model = IsingQuadraticModel(*expression)
    solver = Solver(client)
    result = solver.solve(model)
    print("energy: ", result[0].energy)
    # print("time(ms): ", solver.client_result.annealing_time_ms)
    return result[0].values
Esempio n. 2
0
def by_amplify(qubits, model, token, timeout=5000):
    client = FixstarsClient()
    client.token = token
    client.parameters.timeout = timeout
    solver = Solver(client)
    solver.filter_solution = False
    result = solver.solve(model)
    values = result[0].values
    q_values = decode_solution(qubits, values, 1)
    return np.where(np.array(q_values) == 1)[1]
Esempio n. 3
0
    def solve(self):
        q = gen_symbols(BinaryPoly, *self.board.get_size(), len(self.pieces),
                        8)

        # 制約(a) 重複する置き方のピースは除外する
        for y in range(self.board.get_size()[0]):
            for x in range(self.board.get_size()[1]):
                for i in range(len(self.pieces)):
                    for j in range(self.pieces[i].placement_count, 8):
                        q[y][x][i][j] = BinaryPoly(0)

        # 制約(b) ピースはボードから外に出ない
        for y in range(self.board.get_size()[0]):
            for x in range(self.board.get_size()[1]):
                for i in range(len(self.pieces)):
                    for j in range(self.pieces[i].placement_count):
                        if len(self.pieces[i].get_blocks(j, (x, y)) -
                               self.board.get_blocks()) > 0:
                            q[y][x][i][j] = BinaryPoly(0)

        # 制約(c) ピース同士は重ならずボードを全て埋める
        s = dict()
        for b in self.board.get_blocks():
            s[b] = BinaryPoly()
        for y in range(self.board.get_size()[0]):
            for x in range(self.board.get_size()[1]):
                for i in range(len(self.pieces)):
                    for j in range(self.pieces[i].placement_count):
                        for p in self.pieces[i].get_blocks(
                                j, (x, y)) & self.board.get_blocks():
                            s[p] += q[y][x][i][j]
        board_constraints = [equal_to(q, 1) for q in s.values()]

        # 制約(d) 全てのピースは一度ずつ使われる
        piece_constraints = [
            equal_to(
                sum(q[y][x][i][j] for y in range(self.board.get_size()[0])
                    for x in range(self.board.get_size()[1])
                    for j in range(8)), 1) for i in range(len(self.pieces))
        ]

        constraints = (sum(board_constraints) + sum(piece_constraints))

        solver = Solver(self.client)

        model = BinaryQuadraticModel(constraints)
        result = solver.solve(model)
        if len(result) == 0:
            raise RuntimeError("Any one of constaraints is not satisfied.")

        solution = result[0]
        values = solution.values
        q_values = decode_solution(q, values)
        Visualizer().visualize(self.pieces, self.board, q_values)
Esempio n. 4
0
def solve_problem(model):
    # set client and parameters
    client = FixstarsClient()
    client.token = "lJLkgFpKzukTUGnr8F3tjrPJZlO8N0bX"
    client.parameters.timeout = 5000
    # set solver
    solver = Solver(client)
    # get result
    result = solver.solve(model)
    # extract value of objective function and binary variables
    obj, values = result[0].energy, result[0].values
    # get values of constraints
    broken = model.check_constraints(values)
    return obj, values, broken
Esempio n. 5
0
    def solve(self,
              c_weight: float = 3,
              timeout: int = 1000,
              num_unit_step: int = 10) -> Setlist:
        """

        Args:
            c_weight (float): 時間制約の強さ
            timeout (int, optional): Fixstars AE のタイムアウト[ms] (デフォルト: 10000)
            num_unit_step (int, optional): Fixstars AE のステップ数 (デフォルト: 10)

        Returns:
            Setlist: セットリスト
        """
        self.q = gen_symbols(BinaryPoly, self.num_tracks)
        energy_function = self.energy(c_weight)
        model = BinaryQuadraticModel(energy_function)

        fixstars_client = FixstarsClient()
        fixstars_client.token = os.environ.get("FIXSTARS_API_TOKEN")
        fixstars_client.parameters.timeout = timeout
        fixstars_client.parameters.num_unit_steps = num_unit_step

        amplify_solver = Solver(fixstars_client)
        amplify_solver.filter_solution = False
        result = amplify_solver.solve(model)

        q_values = decode_solution(self.q, result[0].values)
        tracks = [self.candidates[i] for i, v in enumerate(q_values) if v == 1]

        total_time = 0
        user_scores = np.zeros(self.num_users)
        for track in tracks:
            user_scores += np.array(track.p)
            total_time += track.duration_ms

        return Setlist(tracks=tracks,
                       scores=user_scores.tolist(),
                       score_sum=user_scores.sum(),
                       score_avg=user_scores.mean(),
                       score_var=user_scores.var(),
                       total_time=total_time)
    for i in range(1, num_steps + 1):
        w_a = i * w_step
        for j in range(1, num_steps + 1):
            w_b = j * w_step
            # 最終的なエネルギー関数
            energy_function = w_a * constraint + w_b * cost_function

            num_optimum = 0  # 最適解が導かれた回数
            sum_exe_time = 0.0  # 実行時間の総和
            num_skip = 0  # RuntimeError でスキップされた回数
            for _ in range(num_execution):
                try:
                    # 通信時間を含む計算実行時間の計測
                    start_time = time.perf_counter()
                    result = solver.solve(energy_function)
                    end_time = time.perf_counter()

                    sum_exe_time += end_time - start_time
                except RuntimeError as e:
                    num_skip += 1
                    print(e)
                    continue
                # 結果出力
                str_spin, result_is_optimum = utils.print_solver_result(
                    N, result)
                #print(str_spin)
                if result_is_optimum:
                    num_optimum += 1
            # 最適回答率
            percentage_of_optimum = (num_optimum /
Esempio n. 7
0
# イジング変数を生成
s = gen_symbols(IsingPoly, n)

# 目的関数の構築: イジング
f = IsingPoly()

for i in range(n):
    f += s[i] * A[i]

f = f ** 2

# ソルバーの構築
solver = Solver(client)

# 問題を入力してマシンを実行
result = solver.solve(f)

# 解が得られなかった場合、len(result) == 0
if len(result) == 0:
    raise RuntimeError("No solution was found")

print("Number of results = ",len(result))

energy = result[0].energy
values = result[0].values

partitions = set()

for sol in result:
    solution = decode_solution(s, sol.values)
    
            obj_pa_diff_j -= pa_diff_data[i][2][j][1] * q[i]

        obj_pa_diff += coef**2 * obj_pa_diff_j**2

    H = 1.0 * const_onehot + 1.0 * obj_pa + 1.0 * obj_pa_diff

    # クライアントの設定
    client = FixstarsClient()
    client.parameters.timeout = 1000
    # client.token = ""

    # ソルバーの構築
    solver = Solver(client)

    # 問題を入力してマシンを実行
    result = solver.solve(H)

    # 出力
    for sol in result:
        solution = decode_solution(q, sol.values)

    count = 0
    index = -1
    for i in range(len(pa_diff_data)):
        if solution[i] == 1:
            count += 1
            index = i

    if count == 0:
        print('count = 0 !!')
    elif count > 1:
Esempio n. 9
0
    equal_to(sum_poly([q[i][c] for c in range(num_colors)]), 1)
    for i in range(num_region)
]

# 隣接する領域間の制約
adj_constraints = [
    # 都道府県コードと配列インデックスは1ずれてるので注意
    penalty(q[i][c] * q[j - 1][c]) for i in range(num_region)
    for j in jm.adjacent(i + 1)  # j: 隣接している都道府県コード
    if i + 1 < j for c in range(num_colors)
]

constraints = sum(reg_constraints) + sum(adj_constraints)

model = BinaryQuadraticModel(constraints)
result = solver.solve(model)
if len(result) == 0:
    raise RuntimeError("Any one of constraints is not satisfied.")

values = result[0].values
q_values = decode_solution(q, values, 1)

color_indices = np.where(np.array(q_values) == 1)[1]
color_map = {
    jm.pref_names[i + 1]: colors[color_indices[i]]
    for i in range(len(color_indices))
}

plt.rcParams["figure.figsize"] = 6, 6
plt.imshow(jm.picture(color_map))
plt.show()
Esempio n. 10
0
def quantum_solver_approx(N, M,
                          query):  # solve with Amplify (approximate version)
    q = gen_symbols(BinaryPoly, M, N, N)  # represent the solution

    ##########   constraints   ##########

    # each layer doesn't have 2+ same values
    one_hot_constraints_layer = [
        # m -> layer
        # n -> qubit
        # v -> value of qubit
        equal_to(sum(q[m][n][v] for n in range(N)), 1) for m in range(M)
        for v in range(N)
    ]

    # each qubit doesn't have 2+ values
    one_hot_constraints_num = [
        # m -> layer
        # n -> qubit
        # v -> value of qubit
        equal_to(sum(q[m][n][v] for v in range(N)), 1) for m in range(M)
        for n in range(N)
    ]

    # every CX gate must be applied for 2 adjacent qubits
    CXgate_constraints = []
    for m in range(M):
        for g0 in range(0, len(query[m]), 2):
            v0, v1 = query[m][g0], query[m][g0 + 1]

            # v0 and v1 must be adjacent each other
            for i in range(N):
                for j in range(i + 2, N):
                    CXgate_constraints.append(
                        penalty(q[m][i][v0] * q[m][j][v1]))
                    CXgate_constraints.append(
                        penalty(q[m][i][v1] * q[m][j][v0]))

    constraints = (sum(one_hot_constraints_layer) +
                   sum(one_hot_constraints_num) + sum(CXgate_constraints))

    cost = sum_poly(
        M - 1, lambda m: sum_poly(
            N, lambda i: sum_poly(
                N, lambda j: sum_poly(N, lambda v: q[m][i][v] * q[m + 1][j][v])
                * ((N - 1) * (i + j) - 2 * i * j) / N)))

    ##########   solve   ##########

    solver = Solver(client)
    model = BinaryQuadraticModel(constraints * constraintWeight + cost)

    result = solver.solve(model)
    if len(result) == 0:
        raise RuntimeError("Any one of constraints is not satisfied.")

    values = result[0].values
    q_values = decode_solution(q, values, 1)

    # print(q_values_main)

    ##########   decode the result into string   ##########

    ans = [[-1 for n in range(N)] for m in range(M)]
    for m in range(M):
        for n in range(N):
            for v in range(N):
                if (q_values[m][n][v] > 0.5):
                    ans[m][n] = v

    cost = 0
    for m in range(M - 1):
        cost += calcCost(ans[m], ans[m + 1])

    return cost, ans
Esempio n. 11
0
def quantum_solver_strict(N, M, query):  # solve by Amplify (strict version)
    q_all = gen_symbols(BinaryPoly,
                        M * N * N + (M - 1) * N * N * N + (M - 1) * N * N)

    q = q_all[:M * N * N]  # represent the solution
    q_sub = q_all[M * N * N:M * N * N + (M - 1) * N * N *
                  N]  # q_sub[m][i][j][v] = q[m][i][v] * q[m+1][j][v]
    q_C_matrix = q_all[
        M * N * N + (M - 1) * N * N *
        N:]  # q_C_matrix[m][i][j] = sum(q_sub[m][i][j][v] for v)

    ##########   constraints   ##########

    # each layer doesn't have 2+ same values
    one_hot_constraints_layer = [
        # m -> layer
        # n -> physical qubit
        # v -> logical qubit
        equal_to(sum(q[(m * N + n) * N + v] for n in range(N)), 1)
        for m in range(M) for v in range(N)
    ]

    # each qubit doesn't have 2+ values
    one_hot_constraints_num = [
        # m -> layer
        # n -> physical qubit
        # v -> logical qubit
        equal_to(sum(q[(m * N + n) * N + v] for v in range(N)), 1)
        for m in range(M) for n in range(N)
    ]

    # every CX gate must be applied for 2 adjacent qubits
    CXgate_constraints = []
    for m in range(M):
        for g0 in range(0, len(query[m]), 2):
            v0, v1 = query[m][g0], query[m][g0 + 1]

            # v0 and v1 must be adjacent each other
            for i in range(N):
                for j in range(i + 2, N):
                    CXgate_constraints.append(
                        penalty(q[(m * N + i) * N + v0] *
                                q[(m * N + j) * N + v1]))
                    CXgate_constraints.append(
                        penalty(q[(m * N + i) * N + v1] *
                                q[(m * N + j) * N + v0]))

    # q_sub[m][i][j][v] = q[m][i][v] * q[m+1][j][v]
    sub_gate_constraints = []
    for _idx in range((M - 1) * N**3):
        idx = _idx
        m = idx // (N**3)
        idx %= N**3
        i = idx // (N**2)
        idx %= N**2
        j = idx // N
        idx %= N
        v = idx

        sub_gate_constraints.append(
            penalty(3 * q_sub[((m * N + i) * N + j) * N + v] +
                    q[(m * N + i) * N + v] * q[((m + 1) * N + j) * N + v] -
                    2 * q_sub[((m * N + i) * N + j) * N + v] *
                    (q[(m * N + i) * N + v] + q[((m + 1) * N + j) * N + v])))

    # q_C_matrix[m][i][j] = sum(q_sub[m][i][j][v] for v)
    C_matrix_sum_constraints = []
    for _idx in range((M - 1) * N**2):
        idx = _idx
        m = idx // (N**2)
        idx %= N**2
        i = idx // N
        idx %= N
        j = idx

        C_matrix_sum_constraints.append(
            equal_to(
                q_C_matrix[(m * N + i) * N + j] -
                sum(q_sub[((m * N + i) * N + j) * N + v] for v in range(N)),
                0))

    constraints = (sum(one_hot_constraints_layer) +
                   sum(one_hot_constraints_num) + sum(CXgate_constraints) +
                   sum(sub_gate_constraints) + sum(C_matrix_sum_constraints))

    cost = []
    for m in range(M - 1):
        for i1 in range(N):
            for j1 in range(i1):  # i1 > j1
                for i2 in range(N):
                    for j2 in range(i2 + 1, N):  # i2 < j2
                        cost.append(q_C_matrix[(m * N + i1) * N + j1] *
                                    q_C_matrix[(m * N + i2) * N + j2])

            for j1 in range(i1 + 1, N):  # i1 < j1
                for i2 in range(N):
                    for j2 in range(i2):  # i2 > j2
                        cost.append(q_C_matrix[(m * N + i1) * N + j1] *
                                    q_C_matrix[(m * N + i2) * N + j2])

    # print(constraints)
    # print(cost)

    ##########   solve   ##########

    solver = Solver(client)
    model = BinaryQuadraticModel(constraints * constraintWeight + sum(cost))

    result = solver.solve(model)
    if len(result) == 0:
        raise RuntimeError("Any one of constraints is not satisfied.")

    values = result[0].values
    q_values = decode_solution(q_all, values, 1)

    # print(q_values_main)

    ##########   decode the result into string   ##########

    ans = [[-1 for n in range(N)] for m in range(M)]
    for m in range(M):
        for n in range(N):
            for v in range(N):
                if (q_values[(m * N + n) * N + v] > 0.5):
                    ans[m][n] = v

    cost = 0
    for m in range(M - 1):
        cost += calcCost(ans[m], ans[m + 1])

    return cost, ans
Esempio n. 12
0
# Isinbg 変数を生成
s = gen_symbols(IsingPoly, n)

# 目的関数の構築
f = IsingPoly()

for i in range(n):
    f += s[i] * A[i]

f = f**2

# ソルバーの構築
solver = Solver(client)  # ソルバーに使用するクライアントを設定

# 問題を入力してマシンを実行
result = solver.solve(f)  # 問題を入力してマシンを実行

# 解が得られなかった場合、len(result) == 0
if len(result) == 0:
    raise RuntimeError("No solution was found")

partitions = set()

for sol in result:
    solution = decode_solution(s, sol.values)

    A0 = tuple(sorted([A[idx] for idx, val in enumerate(solution)
                       if val != 1]))
    A1 = tuple(sorted([A[idx] for idx, val in enumerate(solution)
                       if val == 1]))
Esempio n. 13
0
# バイナリ変数:要素数2
q = gen_symbols(BinaryPoly, 2)

###########################################################
# NAND制約を与える多項式
g_NAND = q[0] * q[1]

# NAND制約をペナルティ制約条件に変換
p_NAND = penalty(g_NAND)

print("NAND")
print(f"p_NAND = {p_NAND}")

# 制約条件を満たす解を求める
result = solver.solve(p_NAND)
for sol in result:
    energy = sol.energy
    values = sol.values

    print(f"energy = {energy}, {q} = {decode_solution(q, values)}")

###########################################################
# OR制約を与える多項式
g_OR = q[0] * q[1] - q[0] - q[1] + 1
p_OR = penalty(g_OR)

print("OR")
print(f"p_OR = {p_OR}")

# 制約条件を満たす解を求める