예제 #1
0
    def test_equality(self):
        self.assertEqual(Binary("a"), Binary("a"))
        self.assertNotEqual(Binary("a"), Binary("b"))

        exp1 = Binary("a") + 2
        exp2 = Binary("a") + 2
        exp3 = Binary("b") + 2
        self.assertEqual(exp1, exp2)
        self.assertNotEqual(exp1, exp3)

        mul1 = Placeholder("p") * Binary("b")
        mul2 = Placeholder("p") * Binary("b")
        mul3 = Placeholder("p") * Binary("a")
        self.assertEqual(mul1, mul2)
        self.assertNotEqual(mul1, mul3)

        class CustomPenalty(WithPenalty):
            def __init__(self, hamiltonian, penalty, label="label"):
                super().__init__(hamiltonian, penalty, label)

        a, b = Binary("a"), Binary("b")
        p1 = 1 + CustomPenalty(a + b, a * b)
        p2 = 1 + CustomPenalty(a + b, a * b)
        p3 = 1 + CustomPenalty(a * b, a + b)
        self.assertEqual(p1, p2)
        self.assertNotEqual(p1, p3)

        subh1 = SubH(a + b, label="c1")
        subh2 = SubH(a + b, label="c1")
        subh3 = SubH(a + b, label="c2")
        self.assertEqual(subh1, subh2)
        self.assertNotEqual(subh1, subh3)
예제 #2
0
  def build_solver(self,member_num,expectation_member_capacity):
    X = Array.create('X', (self.department_num,self.term_num, member_num), 'BINARY')
    # Term_Member Once Constraint
    C_TM_Once = 0.0
    for t in range(self.term_num):
      for m in range(member_num):
        C_TM_Once += Constraint(
            (Sum(start_index=0,end_index=self.department_num,func=lambda d:X[d,t,m]) - 1)**2
            , label=f"TM_Once_{t},{m}") 
    # Department_Member Once Constraint
    C_DM_Once = 0.0
    for d in range(self.department_num):
      for m in range(member_num):
        C_DM_Once += Constraint(
            (Sum(start_index=0,end_index=self.term_num,func=lambda t:X[d,t,m]) - 1)**2
            , label=f"DM_Once_{t},{m}") 
    # Member Capacity Constraint
    C_MC = 0.0
    for d in range(self.department_num):
      for t in range(self.term_num):
        C_MC += Constraint(
            (Sum(start_index=0,end_index=member_num,func=lambda m:X[d,t,m]) - expectation_member_capacity[d,t])**2
            , label=f"MC_{d},{t}") 

    P_TM_Once = Placeholder("PTMO")
    P_DM_Once = Placeholder("PDMO")
    P_MC = Placeholder("PMC")

    H = P_TM_Once*C_TM_Once + P_DM_Once*C_DM_Once + P_MC*C_MC
    model = H.compile()
    return model
예제 #3
0
 def test_equality_of_placeholder(self):
     p1 = Placeholder("p1")
     p2 = Placeholder("p2")
     p3 = Placeholder("p1")
     self.assertTrue(p1 == p3)
     self.assertTrue(hash(p1) == hash(p3))
     self.assertTrue(p1 != p2)
     self.assertTrue(p1 != Qbit("a"))
예제 #4
0
 def test_compile_placeholder(self):
     a, b = Binary("a"), Binary("b")
     p, q, r = Placeholder("p"), Placeholder("q"), Placeholder("r")
     exp = r * (q * p * (a + b)**2 + q)
     expected_qubo = {('a', 'a'): 12.0, ('a', 'b'): 24.0, ('b', 'b'): 12.0}
     expected_offset = 4
     feed_dict = {"p": 3, "q": 2, "r": 2}
     q, offset = exp.compile().to_qubo(feed_dict=feed_dict)
     self.compile_check(exp, expected_qubo, expected_offset, feed_dict)
예제 #5
0
 def test_one_hot_enc_integer_equal(self):
     a = OneHotEncInteger("a", (0, 4), strength=Placeholder("s"))
     b = OneHotEncInteger("b", (0, 4), strength=Placeholder("s"))
     M = 2.0
     H = (a + b - 5)**2 + M * (a.equal_to(3) - 1)**2
     model = H.compile()
     q, offset = model.to_qubo(feed_dict={"s": 10.0})
     sampleset = dimod.ExactSolver().sample_qubo(q)
     decoded = model.decode_sampleset(sampleset, feed_dict={"s": 10.0})[0]
     self.assertTrue(decoded.subh["a"] == 3)
     self.assertTrue(decoded.subh["b"] == 2)
     self.assertTrue(decoded.subh["a_const"] == 0)
     self.assertTrue(decoded.subh["b_const"] == 0)
     self.assertEqual(len(decoded.constraints(only_broken=True)), 0)
예제 #6
0
 def test_compile_placeholder2(self):
     a, b, w, v = Qbit("a"), Qbit("b"), Placeholder("w"), Placeholder("v")
     exp = v * w * (a + b - 2) + v
     expected_qubo = {('a', 'a'): 15.0, ('b', 'b'): 15.0}
     expected_offset = -25
     expected_structure = {'a': ('a', ), 'b': ('b', )}
     self.compile_check(exp,
                        expected_qubo,
                        expected_offset,
                        expected_structure,
                        feed_dict={
                            "w": 3.0,
                            "v": 5.0
                        })
예제 #7
0
    def test_placeholders(self):

        S = Array.create('S', 3, "SPIN")
        p1, p2 = Placeholder("p1"), Placeholder("p2")
        H = p1 * S[0] * S[1] + S[1] * S[2] + p2 * S[2] * S[0] + 0.5 * S[0]
        model = H.compile()
        feed_dict = {"p1": 0.8, "p2": 1.1}
        binary_bqm = model.to_bqm(feed_dict=feed_dict)
        sampler = dimod.ExactSolver()
        sampleset = sampler.sample(binary_bqm)
        sol = model.decode_sampleset(sampleset, feed_dict=feed_dict)
        self.assertTrue(sol[0].array("S", 0) == 0)
        self.assertTrue(sol[0].array("S", 1) == 0)
        self.assertTrue(sol[0].array("S", 2) == 1)
        self.assertTrue(np.isclose(sol[0].energy, -1.8))
예제 #8
0
 def test_one_hot_enc_integer_equal(self):
     a = OneHotEncInteger("a", 0, 4, strength=Placeholder("s"))
     b = OneHotEncInteger("b", 0, 4, strength=Placeholder("s"))
     M = 2.0
     H = (a + b - 5) ** 2 + M*(a.equal_to(3)-1)**2
     model = H.compile()
     q, offset = model.to_qubo(feed_dict={"s": 10.0})
     sampleset = dimod.ExactSolver().sample_qubo(q)
     response, broken, e = model.decode_dimod_response(
         sampleset, topk=1, feed_dict={"s": 10.0})[0]
     self.assertTrue(response["a"][0] == 0)
     self.assertTrue(response["a"][1] == 0)
     self.assertTrue(response["a"][2] == 0)
     self.assertTrue(response["a"][3] == 1)
     self.assertTrue(response["a"][4] == 0)
예제 #9
0
def make_energy(num_city, distance):
    # set binary variables
    x = Array.create('x', shape=(num_city, num_city), vartype='BINARY')
    # # fix variables for preprocess
    # x = np.array(x)
    # x[0][0] = 1
    # for i in range(1, num_city):
    #     x[0][i] = 0
    # for t in range(1, num_city):
    #     x[t][0] = 0
    # set hyperparameters
    lambda_a = []
    lambda_b = []
    for i in range(num_city):
        lambda_a.append(Placeholder('h_a_{}'.format(i)))
        lambda_b.append(Placeholder('h_b_{}'.format(i)))
    lambda_c = Placeholder('h_c')
    # set one-hot encoding for time
    h_a = []
    for t in range(num_city):
        tmp = sum([x[t][i] for i in range(num_city)]) - 1
        h_a.append(tmp)
    # set one-hot encoding for city
    h_b = []
    for i in range(num_city):
        tmp = sum([x[t][i] for t in range(num_city)]) - 1
        h_b.append(tmp)
    # set function for augmented lagrangian function
    h_c = sum([h_a[i]**2 for i in range(num_city)])
    h_c += sum([h_b[i]**2 for i in range(num_city)])
    # convert to constraint
    for i in range(num_city):
        h_a[i] = Constraint(h_a[i], label='h_a_{}'.format(i))
        h_b[i] = Constraint(h_b[i], label='h_b_{}'.format(i))
    h_c = Constraint(h_c, label='h_c')
    # set objective function
    obj = 0
    for t in range(num_city):
        for i in range(num_city):
            for j in range(num_city):
                obj += distance[i][j] * x[t][i] * x[(t + 1) % num_city][j]
    # compute total energy
    hamiltonian = obj + lambda_c / 2 * h_c
    hamiltonian += sum([lambda_a[i] * h_a[i] for i in range(num_city)])
    hamiltonian += sum([lambda_b[i] * h_b[i] for i in range(num_city)])
    # compile
    model = hamiltonian.compile()
    return model
예제 #10
0
    def test_one_hot_enc_integer(self):
        a = OneHotEncInteger("a", 0, 4, strength=Placeholder("s"))
        H = (a - 3) ** 2
        model = H.compile()
        q, offset = model.to_qubo(feed_dict={"s": 10.0})
        sampleset = dimod.ExactSolver().sample_qubo(q)
        response, broken, e = model.decode_dimod_response(
            sampleset, topk=1, feed_dict={"s": 10.0})[0]
        self.assertTrue(response["a"][0] == 0)
        self.assertTrue(response["a"][1] == 0)
        self.assertTrue(response["a"][2] == 0)
        self.assertTrue(response["a"][3] == 1)
        self.assertTrue(response["a"][4] == 0)
        self.assertTrue(a.interval == (0, 4))

        expected_q = {('a[0]', 'a[1]'): 40.0,
             ('a[0]', 'a[2]'): 40.0,
             ('a[0]', 'a[3]'): 40.0,
             ('a[0]', 'a[4]'): 40.0,
             ('a[1]', 'a[2]'): 44.0,
             ('a[1]', 'a[3]'): 46.0,
             ('a[1]', 'a[4]'): 48.0,
             ('a[2]', 'a[3]'): 52.0,
             ('a[2]', 'a[4]'): 56.0,
             ('a[3]', 'a[4]'): 64.0,
             ('a[0]', 'a[0]'): -20.0,
             ('a[1]', 'a[1]'): -25.0,
             ('a[2]', 'a[2]'): -28.0,
             ('a[3]', 'a[3]'): -29.0,
             ('a[4]', 'a[4]'): -28.0}
        assert_qubo_equal(q, expected_q)
예제 #11
0
def get_qubo(num_nodes, num_colors, edges):
    x = Array.create('x', (num_nodes, num_colors), "BINARY")
    adjacent_const = 0.0
    for (i, j) in edges:
        for k in range(num_colors):
            adjacent_const += Constraint(x[i, k] * x[j, k],
                                         label="adjacent({},{})".format(i, j))
    onecolor_const = 0.0
    for i in range(num_nodes):
        onecolor_const += Constraint(
            (Sum(0, num_colors, lambda j: x[i, j]) - 1)**2,
            label="onecolor{}".format(i))
    # combine the two components
    alpha = Placeholder("alpha")
    H = alpha * onecolor_const + adjacent_const
    model = H.compile()
    alpha = 1.0
    # search for an alpha for which each node has only one color
    print("Broken constraints")
    while True:
        qubo, offset = model.to_qubo(feed_dict={"alpha": alpha})
        solution = solve_qubo(qubo)
        decoded_solution, broken_constraints, energy = model.decode_solution(
            solution, vartype="BINARY", feed_dict={"alpha": alpha})
        print(len(broken_constraints))
        if not broken_constraints:
            break
        for (key, value) in broken_constraints.items():
            if 'o' == key[0]:  # onecolor
                alpha += 0.1
                break
        if 'a' == key[0]:  # adjacent
            break
    return qubo, decoded_solution
예제 #12
0
    def optimize_leap(self):
        from pyqubo import Array,Constraint,Placeholder,UnaryEncInteger,Sum #LogEncInteger
        from dwave.system import LeapHybridSampler

        x = Array.create("x",shape=(self.num),vartype="BINARY")
        #y = LogEncInteger("y",lower=0,upper=5)
        y = UnaryEncInteger("y",lower=0,upper=5)

        #価値が最大になるように(符号を反転させる)
        H1 = -Sum(0,self.num,lambda i :x[i]*self.p[i].get_value() )
        #H1 = -sum([x[i]*self.p[i].get_value() for i in range(self.num)])

        #重さが目的の重量になるように
        H2 = Constraint((self.limit_weight -sum([x[i]*p_i.get_weight() for i,p_i in enumerate(self.p)]) - y*10)**2,"Const Weight")

        H = H1 + H2*Placeholder("balancer")
        model = H.compile()
        balance_dict = {"balancer":1.0}
        bqm = model.to_dimod_bqm(feed_dict=balance_dict)
        sampler = LeapHybridSampler()
        responses = sampler.sample(bqm,time_limit=3)

        solutions = model.decode_dimod_response(responses,feed_dict=balance_dict)

        if len(solutions[0][1]) == 0:
            print(f" y= { sum(2**i*y_i for i,y_i in enumerate(solutions[0][0]['y']))}")
            print("## LeapHybridSolver Optimized Result")
            self.print([int(solutions[0][0]['x'][i]) for i in range(self.num)])
        else:
            print("## LeapHybridSolver Optimizing Failed")
예제 #13
0
    def test_one_hot_enc_integer(self):
        a = OneHotEncInteger("a", (0, 4), strength=Placeholder("s"))
        H = (a - 3) ** 2
        model = H.compile()
        q, offset = model.to_qubo(feed_dict={"s": 10.0})
        sampleset = dimod.ExactSolver().sample_qubo(q)
        decoded = model.decode_sampleset(
            sampleset, feed_dict={"s": 10.0})
        best = min(decoded, key=lambda x: x.energy)
        self.assertTrue(best.subh["a"]==3)
        self.assertTrue(a.value_range == (0, 4))

        expected_q = {('a[0]', 'a[1]'): 20.0,
             ('a[0]', 'a[2]'): 20.0,
             ('a[0]', 'a[3]'): 20.0,
             ('a[0]', 'a[4]'): 20.0,
             ('a[1]', 'a[2]'): 24.0,
             ('a[1]', 'a[3]'): 26.0,
             ('a[1]', 'a[4]'): 28.0,
             ('a[2]', 'a[3]'): 32.0,
             ('a[2]', 'a[4]'): 36.0,
             ('a[3]', 'a[4]'): 44.0,
             ('a[0]', 'a[0]'): -10.0,
             ('a[1]', 'a[1]'): -15.0,
             ('a[2]', 'a[2]'): -18.0,
             ('a[3]', 'a[3]'): -19.0,
             ('a[4]', 'a[4]'): -18.0}
        expected_offset = 19
        assert_qubo_equal(q, expected_q)
        self.assertTrue(offset == expected_offset)        
예제 #14
0
 def parse_to_pyqubo_model(
     self,
     objectives: List[ObjectiveTerm] = [],
     constraints: List[ConstraintTerm] = [],
 ) -> pyqubo.Model:
     parsed_objectives = [
         Placeholder(o["label"]) * self.parse_mathjson(o["tex"])
         for o in objectives
     ]
     parsed_constraints = [
         Placeholder(c["label"]) *
         Constraint(self.parse_mathjson(c["tex"]), label=c["label"])
         for c in constraints
     ]
     H = cast(Express, sum(parsed_objectives) + sum(parsed_constraints))
     pyqubo_model = H.compile()
     return pyqubo_model
예제 #15
0
 def test_compile_subh(self):
     a, b = Binary("a"), Binary("b")
     p = Placeholder("p")
     exp = p * SubH((a + b - 1)**2, label="subh") + a * b
     expected_qubo = {('a', 'a'): -3.0, ('a', 'b'): 7.0, ('b', 'b'): -3.0}
     expected_offset = 3
     feed_dict = {"p": 3}
     self.compile_check(exp, expected_qubo, expected_offset, feed_dict)
def pyqubo_response(df, param_a, param_b, param_c, num_reads, do_qbsolve):
    t_list = calc_marginals(df)

    #make H
    N = len(df)
    Y = Array.create('Y', shape=N, vartype='BINARY')
    ysum = sum(y for y in Y)
    H_0 = (ysum - t_list[0])**2

    sex = df['SEX'].values.tolist()
    sex_array = sum(s * y for s, y in zip(sex, Y))
    H_1 = (sex_array - t_list[1])**2

    aop = df['AOP'].values.tolist()
    aop_array = sum(a * y for a, y in zip(aop, Y))
    H_2 = (aop_array - t_list[2])**2

    alpha = Placeholder("alpha")
    beta = Placeholder("beta")
    gamma = Placeholder("gamma")

    H = alpha * H_0 + beta * H_1 + gamma * H_2

    #パラメータ
    feed_dict = {'alpha': param_a, 'beta': param_b, 'gamma': param_c}

    #QUBOのコンパイル
    model = H.compile()
    qubo, offset = model.to_qubo(feed_dict=feed_dict)

    if do_qbsolve == True:
        res = QBSolv().sample_qubo(qubo, num_reads=num_reads)
    else:
        s3_destination_folder = ('amazon-braket-ecc806acea4c',
                                 'qaExactLogisticRegression_ssato')
        dw = BraketDWaveSampler(
            s3_destination_folder,
            device_arn='arn:aws:braket:::device/qpu/d-wave/DW_2000Q_6')
        qa_sampler = AutoEmbeddingComposite(dw)
        res = qa_sampler.sample(bqm,
                                chain_strength=chain_strength,
                                auto_scale=True,
                                chain_break_fraction=True,
                                num_reads=num_reads)
    return res
예제 #17
0
    def test_placeholders(self):
        a, b, p = Binary("a"), Binary("b"), Placeholder("p")
        feed_dict = {'p': 2.0}
        exp = p * (1 + a * b + a)
        model = exp.compile()
        qubo, offset = model.to_qubo(index_label=False, feed_dict=feed_dict)
        dict_solution = {'a': 1, 'b': 0}
        dict_energy = model.energy(dict_solution,
                                   vartype="BINARY",
                                   feed_dict=feed_dict)
        list_solution = [1, 0]
        list_energy = model.energy(list_solution,
                                   vartype="BINARY",
                                   feed_dict=feed_dict)
        assert_qubo_equal(qubo, {
            ('a', 'b'): 2.0,
            ('a', 'a'): 2.0,
            ('b', 'b'): 0.0
        })
        self.assertEqual(offset, 2.0)
        self.assertTrue(dict_energy, 2.0)
        self.assertTrue(list_energy, 2.0)

        # Test that `decode_dimod_response` accepts the `feed_dict` arg
        import numpy as np
        import dimod
        n = 10
        p = Placeholder("p")
        feed_dict = {'p': 2}
        A = [np.random.randint(-50, 50) for _ in range(n)]
        S = Array.create('S', n, "BINARY")
        H = sum(p * A[i] * S[i] for i in range(n))**2
        model = H.compile()
        binary_bqm = model.to_dimod_bqm(feed_dict=feed_dict)
        sa = dimod.reference.SimulatedAnnealingSampler()
        response = sa.sample(binary_bqm, num_reads=10, num_sweeps=5)
        # Confirm that decode_dimod_response() accecpts a feed_dict. Test of accuracy delegated to decode_solution()
        decoded_solutions = model.decode_dimod_response(response,
                                                        topk=2,
                                                        feed_dict=feed_dict)
        for (decoded_solution, broken, energy) in decoded_solutions:
            assert isinstance(decoded_solution, dict)
            assert isinstance(broken, dict)
            assert isinstance(energy, float)
예제 #18
0
def model_from_pyqubo_model():
    print("\n=== from pyqubo compiled model ===")
    model = sawatabi.model.LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(4, 2))
    y = model.variables("y", shape=(4, 2))

    sum_x = sum(x[i, 0] for i in range(4))
    sum_y = sum(y[i, 0] for i in range(4))
    hamiltonian = Placeholder("A") * (sum_x - sum_y)**2 + 10.0
    pyqubo_model = hamiltonian.compile()

    model.from_pyqubo(pyqubo_model)

    print("\nInteractions are set with pyqubo expression.")
    _print_utf8(model)

    print("\nCheck also the physical model after placeholder resolves.")
    physical = model.to_physical({"A": 2.0})
    _print_utf8(physical)
예제 #19
0
 def test_sub_qubo(self):
     a, b, c = Binary("a"), Binary("b"), Placeholder("c")
     exp = 1 + a * b + c * (a - 2)
     model = exp.compile()
     var_set = VarSetFromVarLabels([b])
     sample_sol = {'a': 0, 'b': 1}
     sub_qubo, offset = model.sub_qubo(var_set,
                                       sample_sol,
                                       feed_dict={'c': 3.0})
     self.assertTrue(sub_qubo == {("b", "b"): 0.0})
     self.assertTrue(offset == -5.0)
예제 #20
0
 def test_compile_placeholder3(self):
     a, v = Qbit("a"), Placeholder("v")
     exp = v * v * a + v
     expected_qubo = {('a', 'a'): 25.0}
     expected_offset = 5
     expected_structure = {'a': ('a', )}
     self.compile_check(exp,
                        expected_qubo,
                        expected_offset,
                        expected_structure,
                        feed_dict={"v": 5.0})
예제 #21
0
 def test_one_hot_enc_integer(self):
     a = OneHotEncInteger("a", (0, 4), strength=Placeholder("s"))
     H = (a - 3) ** 2
     model = H.compile()
     q, offset = model.to_qubo(feed_dict={"s": 10.0})
     sampleset = dimod.ExactSolver().sample_qubo(q)
     decoded = model.decode_sampleset(
         sampleset, feed_dict={"s": 10.0})
     best = min(decoded, key=lambda x: x.energy)
     self.assertTrue(best.subh["a"]==3)
     self.assertTrue(a.value_range == (0, 4))
예제 #22
0
    def define_model(self):
        '''
        pyqubo.Modelインスタンス作成。モデル作成結果はself.modelに格納
        H1(距離 目的関数)、H2,H3(都市、順序のワンホット制約) 
        parameters
        -----
            なし

        returns
        -----
            なし
        '''

        city_num = self.size

        #変数定義
        x = Array.create('x', shape=(city_num, city_num), vartype="BINARY")

        #距離のペナルティ
        H1 = 0
        #i番目に都市j、i+1番目に都市kを訪れる
        for i, j in product(range(city_num), range(city_num)):
            for k in range(city_num):
                H1 += self.dist(j, k) * x[i][j] * x[(i + 1) % city_num][k]

        #ある時刻には訪れる都市は1つだけ
        H2 = 0
        for i in range(city_num):
            H2 += Constraint((Sum(0, city_num, lambda j: x[i][j]) - 1)**2,
                             label=f"Constraint one hot for time{i}")

        #ある都市に訪れるのは1度だけ
        H3 = 0
        for i in range(city_num):
            H3 += Constraint((Sum(0, city_num, lambda j: x[j][i]) - 1)**2,
                             label=f"Constraint one hot for city {i}")

        H = Placeholder("H1") * H1 + H2 + H3

        #モデル作成
        self.model = H.compile()
예제 #23
0
 def test_sub_ising(self):
     a, b, c = Binary("a"), Binary("b"), Placeholder("c")
     exp = 1 + a * b + c * (a - 2)
     model = exp.compile()
     var_set = VarSetFromVarLabels([b])
     sample_sol = {'a': 0, 'b': 1}
     linear, quad, offset = model.sub_ising(var_set,
                                            sample_sol,
                                            feed_dict={'c': 3.0})
     self.assertTrue(linear == {'b': 0.0})
     self.assertTrue(quad == {})
     self.assertTrue(offset == -5.0)
예제 #24
0
    def test_compile_with_penalty(self):
        class CustomPenalty(WithPenalty):
            def __init__(self, hamiltonian, penalty, label):
                super().__init__(hamiltonian, penalty, label)

        a, b = Binary("a"), Binary("b")
        p = Placeholder("p")
        custom_penalty = p * CustomPenalty(a + b, a * b, "label")
        expected_qubo = {('a', 'a'): 2.0, ('a', 'b'): 1.0, ('b', 'b'): 2.0}
        expected_offset = 0.0
        feed_dict = {"p": 2}
        self.compile_check(custom_penalty, expected_qubo, expected_offset,
                           feed_dict)
예제 #25
0
 def test_compile_const(self):
     a, b, w = Qbit("a"), Qbit("b"), Placeholder("w")
     exp = Constraint(Constraint(w * (a + b - 1), label="const1") +
                      Constraint((a + b - 1)**2, label="const2"),
                      label="const_all")
     expected_qubo = {('a', 'a'): 2.0, ('a', 'b'): 2.0, ('b', 'b'): 2.0}
     expected_offset = -2.0
     expected_structure = {'a': ('a', ), 'b': ('b', )}
     self.compile_check(exp,
                        expected_qubo,
                        expected_offset,
                        expected_structure,
                        feed_dict={"w": 3.0})
예제 #26
0
def model_convert_with_placeholder():
    print("\n=== convert with placeholder ===")
    model = sawatabi.model.LogicalModel(mtype="ising")

    print("\nSet variables x to shape (7,) and add interactions.")
    x = model.variables("x", shape=(7, ))
    model.add_interaction(x[0], coefficient=Placeholder("a"))
    model.add_interaction(x[1], coefficient=Placeholder("b") + 1.0)
    model.add_interaction(x[2], coefficient=2.0)
    model.add_interaction(x[2], name="x[2]-2", coefficient=Placeholder("c"))
    model.add_interaction(x[3],
                          coefficient=2 * Placeholder("d") +
                          3 * Placeholder("e"))
    model.add_interaction(x[4], coefficient=Placeholder("f"), scale=3.0)
    model.add_interaction(x[5], coefficient=4.0, scale=Placeholder("g"))
    model.add_interaction(x[6],
                          coefficient=Placeholder("h"),
                          scale=Placeholder("i") * 5.0)
    model._offset = Placeholder("j")
    _print_utf8(model)

    print("\nConvert to Physical model with placeholders.")
    physical_model = model.to_physical(
        placeholder={
            "a": 1.0,
            "b": 2.0,
            "c": 3.0,
            "d": 4.0,
            "e": -5.0,
            "f": 6.0,
            "g": -7.0,
            "h": 8.0,
            "i": 9.0,
            "j": 10.0
        })
    _print_utf8(physical_model)
예제 #27
0
    def optimize_advantage(self,count=False,Best=0,balancer=1.0):
        from pyqubo import Array,Constraint,Placeholder,UnaryEncInteger,Sum #LogEncInteger
        from dwave.system import EmbeddingComposite,DWaveSampler

        x = Array.create("x",shape=(self.num),vartype="BINARY")
        #y = LogEncInteger("y",lower=0,upper=5)
        y = UnaryEncInteger("y",lower=0,upper=5)

        #価値が最大になるように(符号を反転させる)
        #H1 = -sum([x[i]*self.p[i].get_value() for i in range(self.num)])
        H1 = -Sum(0,self.num,lambda i :x[i]*self.p[i].get_value() )

        #重さが目的の重量になるように
        #H2 = Constraint((self.limit_weight -sum([x[i]*p_i.get_weight() for i,p_i in enumerate(self.p)]) - y*10)**2,"Const Weight")
        H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()) - y*10)**2,"Const Weight")
        #H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()))**2,"Const Weight")

        H = H1 + H2*Placeholder("balancer")
        model = H.compile()
        balance_dict = {"balancer":balancer}
        bqm = model.to_dimod_bqm(feed_dict=balance_dict)
        sampler = EmbeddingComposite(DWaveSampler(solver="Advantage_system1.1"))
        #sampler = EmbeddingComposite(DWaveSampler(solver="DW_2000Q_6"))
        responses = sampler.sample(bqm,num_reads=1000)

        solutions = model.decode_dimod_response(responses,feed_dict=balance_dict)
        #Optuna用 バランス調査
        if count == True:
            counter = 0
            for idx,sol in enumerate(solutions):
                const_str = sol[1]
                val = sum(int(sol[0]['x'][i])*self.p[i].get_value()  for i in range(self.num))
                weight = sum(int(sol[0]['x'][i])*self.p[i].get_weight()  for i in range(self.num))
                #重量が制限以下、かつ価値が最適解の9割以上をカウント
                if len(const_str) == 0 and val > Best*0.9 and weight <= self.limit_weight:
                    counter += responses.record[idx][2]

            del H1,H2,H,model,bqm,responses,solutions
            gc.collect()

            return counter

        if len(solutions[0][1]) == 0:
            print(f" y= { sum(2**i*y_i for i,y_i in enumerate(solutions[0][0]['y']))}")
            print("## Advantage Solver Optimized Result")
            self.print([int(solutions[0][0]['x'][i]) for i in range(self.num)])
        else:
            print("## Advantage Solver Optimizing Failed")
예제 #28
0
 def test_placeholder_in_constraint(self):
     a = Binary("a")
     exp = Constraint(2 * Placeholder("c") + a, "const1")
     m = exp.compile()
     sol, broken, energy = m.decode_solution({"a": 1},
                                             vartype="BINARY",
                                             feed_dict={"c": 1})
     self.assertEqual(energy, 3.0)
     self.assertEqual(broken,
                      {'const1': {
                          'result': {
                              'a': 1
                          },
                          'penalty': 3.0
                      }})
     self.assertEqual(sol, {'a': 1})
예제 #29
0
 def test_order_enc_integer(self):
     a = OrderEncInteger("a", (0, 4), strength=Placeholder("s"))
     model = ((a - 3)**2).compile()
     q, offset = model.to_qubo(feed_dict={"s": 10.0})
     expected_q = {
         ('a[3]', 'a[2]'): -8.0,
         ('a[0]', 'a[1]'): -8.0,
         ('a[3]', 'a[0]'): 2.0,
         ('a[2]', 'a[0]'): 2.0,
         ('a[1]', 'a[1]'): 5.0,
         ('a[3]', 'a[1]'): 2.0,
         ('a[2]', 'a[1]'): -8.0,
         ('a[3]', 'a[3]'): 5.0,
         ('a[0]', 'a[0]'): -5.0,
         ('a[2]', 'a[2]'): 5.0
     }
     response = dimod.ExactSolver().sample_qubo(q)
     decoded = model.decode_sampleset(response, feed_dict={"s": 10.0})[0]
     self.assertTrue(decoded.subh["a"] == 3)
     self.assertTrue(a.value_range == (0, 4))
     assert_qubo_equal(q, expected_q)
예제 #30
0
    def tsp(n_city):
        t0 = time.time()
        x = Array.create('c', (n_city, n_city), 'BINARY')

        # Constraint not to visit more than two cities at the same time.
        time_const = 0.0
        for i in range(n_city):
            # If you wrap the hamiltonian by Const(...), this part is recognized as constraint
            time_const += Constraint(
                (sum(x[i, j] for j in range(n_city)) - 1)**2,
                label="time{}".format(i))

        # Constraint not to visit the same city more than twice.
        city_const = 0.0
        for j in range(n_city):
            city_const += Constraint(
                (sum(x[i, j] for i in range(n_city)) - 1)**2,
                label="city{}".format(j))

        # distance of route
        distance = 0.0
        for i in range(n_city):
            for j in range(n_city):
                for k in range(n_city):
                    # we set the constant distance
                    d_ij = 10
                    distance += d_ij * x[k, i] * x[(k + 1) % n_city, j]

        # Construct hamiltonian
        A = Placeholder("A")
        H = distance + A * (time_const + city_const)

        # Compile model
        t1 = time.time()
        model = H.compile()
        qubo, offset = model.to_qubo(index_label=True, feed_dict={"A": 2.0})
        t2 = time.time()

        return t1 - t0, t2 - t1