예제 #1
0
 def test_decode2(self):
     x = Matrix("x", n_row=2, n_col=2)
     exp = Constraint(-(x[1, 1] - x[0, 1])**2, label="const")
     model = exp.compile()
     self.assertRaises(
         ValueError,
         lambda: model.decode_solution([1, 0], var_type="binary"))
예제 #2
0
 def test_decode2(self):
     x = Array.create("x", (2, 2), vartype="BINARY")
     exp = Constraint(-(x[1, 1] - x[0, 1])**2, label="const")
     model = exp.compile()
     self.assertRaises(
         ValueError,
         lambda: model.decode_solution([1, 0], vartype="BINARY"))
def Create_Qubo(N, _lambda, P, A, returns, sigma):

    x = Array.create("vector", 2 * N, "BINARY")
    term1 = 0
    H = 0
    for i in range(N):
        for j in range(N):
            H += (
                _lambda
                * (sigma[i][j])
                * (x[2 * i] + x[2 * i + 1] - 1)
                * (x[2 * j] + x[2 * j + 1] - 1)
            )
    term1 += Constraint(H, label="Sigma")

    term2 = 0
    H = 0
    for i in range(N):
        H -= (1 - _lambda) * returns[i] * (x[2 * i] + x[2 * i + 1] - 1)
    term2 = Constraint(H, label="Returns")

    H = 0
    for i in range(N):
        H += x[2 * i] + x[2 * i + 1] - 1
    H -= A
    H = H ** 2
    H *= P
    select_n = Constraint(H, label="select_n_projects")

    model = H.compile()
    return model.to_qubo()
 def test_equality_of_express_with_const(self):
     a, b = Qbit("a"), Spin("b")
     exp = a + b - 1 + Constraint(a * b, label="const")
     expected_exp = AddList(
         [a, Num(-1.0), b,
          Constraint(Mul(a, b), label="const")])
     self.assertTrue(exp == expected_exp)
예제 #5
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
예제 #6
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
예제 #7
0
 def test_equality_of_const(self):
     c1 = Constraint(Qbit("a"), label="c1")
     c2 = Constraint(Qbit("b"), label="c1")
     c3 = Constraint(Qbit("a"), label="c3")
     c4 = Constraint(Qbit("a"), label="c1")
     self.assertTrue(c1 == c4)
     self.assertFalse(c1 != c4)
     self.assertTrue(hash(c1) == hash(c4))
     self.assertTrue(c1 != c2)
     self.assertTrue(c1 != c3)
     self.assertTrue(c1 != Qbit("a"))
예제 #8
0
    def test_constraint(self):
        sampler = dimod.ExactSolver()
        x = Array.create('x', shape=(3), vartype="BINARY")
        H = Constraint(x[0] * x[1] * x[2], label="C1")
        model = H.compile()
        bqm = model.to_bqm()
        responses = sampler.sample(bqm)
        solutions = model.decode_sampleset(responses)

        for sol in solutions:
            if sol.energy == 1.0:
                self.assertEqual(sol.subh['C1'], 1.0)
예제 #9
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})
예제 #10
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
예제 #11
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})
예제 #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 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()
예제 #14
0
 def test_compile_constraint(self):
     a, b, c = Binary("a"), Binary("b"), Binary("c")
     exp = Constraint(a * b * c, label="constraint")
     # expected_qubo = {('a', '0*1'): -10.0, ('b', '0*1'): -10.0, ('0*1', '0*1'): 15.0, ('a', 'a'): 0.0, ('a', 'b'): 5.0, ('c', '0*1'): 1.0, ('b', 'b'): 0.0, ('c', 'c'): 0.0}
     expected_qubo = {
         ('a', 'a * b'): -10.0,
         ('b', 'a * b'): -10.0,
         ('a * b', 'a * b'): 15.0,
         ('a', 'b'): 5.0,
         ('c', 'a * b'): 1.0
     }
     expected_offset = 0
     self.compile_check(exp, expected_qubo, expected_offset, feed_dict={})
예제 #15
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
예제 #16
0
def dijkstra_solver(G, node1, node2, lagrange):
    H = 0
    pq_vars = {}

    # Constraints
    # Find the complete set of edges, and create PyQUBO variables
    for edge in G.edges():
        edge_label = sorted(edge)[0] + sorted(edge)[1]
        pq_vars[edge_label] = Binary(edge_label)

    for node in G:
        neighbors = G.edges(node)
        incident_edges = [
            pq_vars[sorted(edge)[0] + sorted(edge)[1]] for edge in neighbors
        ]
        if node == node1 or node == node2:
            # Starting or ending node - 1 in N condition
            H += lagrange * Constraint(
                (sum(incident_edges) - 1)**2, label=' special ' + node)
        else:
            # Other node - may be 0 or 2 in N
            # In QUBO, the 0 case does not contribute, assuming the sum is
            # 0 (valid solution)
            sum_z = sum(incident_edges)
            for n in range(2, len(incident_edges) + 1):
                for c in combinations(incident_edges, n):
                    m_prod = np.prod(c)
                    sum_z += qubo_c(n) * m_prod
            H += lagrange * Constraint(sum_z, ' usual ' + node)

    # Objective terms
    for edge in G.edges():
        edge_label = sorted(edge)[0] + sorted(edge)[1]
        H += pq_vars[edge_label] * G[sorted(edge)[0]][sorted(edge)
                                                      [1]]['weight']

    model = H.compile()
    return model
예제 #17
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")
예제 #18
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
예제 #19
0
    def __init__(self, label, value_range, strength):
        lower, upper = value_range
        assert upper > lower, "upper value should be larger than lower value"
        assert isinstance(lower, int)
        assert isinstance(upper, int)
        assert isinstance(strength, int) or isinstance(strength, float) or\
            isinstance(strength, Placeholder)

        self._num_variables = (upper - lower + 1)
        self.array = Array.create(label, shape=self._num_variables, vartype='BINARY')
        self.constraint = Constraint((sum(self.array)-1)**2, label=label+"_const", condition=lambda x: x==0)

        express = SubH(lower + sum(i*x for i, x in enumerate(self.array)), label=label)
        penalty = self.constraint * strength

        super().__init__(
            label=label,
            value_range=value_range,
            express=express,
            penalty=penalty)
    
    max_coeff = abs(np.max(list(qubo.values())))
    min_coeff = abs(np.min(list(qubo.values())))
    norm = max_coeff if max_coeff - min_coeff > 0 else min_coeff
    
    return exp / norm

# Cost function
exp_origin = sum(distances[origin][others[i]]*1*q[i][0] + 
             distances[others[i]][origin]*q[i][N-2]*1 for i in range(N-1))
exp_others = sum(distances[others[i]][others[j]]*q[i][t]*q[j][t+1]
              for i in range(N-1) for j in range(N-1) for t in range(N-2))
H_cost = normalize(exp_origin + exp_others)

# Constraint
H_city = Constraint(normalize(sum((sum(q[i][t] for t in range(N-1))-1)**2 for i in range(N-1))), 'city')
H_time = Constraint(normalize(sum((sum(q[i][t] for i in range(N-1))-1)**2 for t in range(N-1))), 'time')

# Express objective function and compile it to model
H = H_cost + Placeholder('lam') * (H_city + H_time)
model = H.compile()


# --- Solve QUBO ---

# Get the QUBO matrix from the model
feed_dict = {'lam':5.0}  # the value of constraint
qubo, offset = model.to_qubo(feed_dict=feed_dict)

# Run QUBO on Leap's Hybrid Solver (hybrid_v1)
sampler = LeapHybridSampler(token='') 
예제 #21
0
    def test_decode(self):
        x = Matrix("x", n_row=2, n_col=2)
        exp = Constraint((x[1, 1] - x[0, 1])**2, label="const")
        model = exp.compile()

        # check __repr__ of CompiledQubo
        expected_repr = "CompiledQubo({('x[0][1]', 'x[0][1]'): 1.0,\n" \
            " ('x[0][1]', 'x[1][1]'): -2.0,\n" \
            " ('x[1][1]', 'x[1][1]'): 1.0}, offset=0.0)"
        self.assertEqual(repr(model.compiled_qubo), expected_repr)

        # check __repr__ of Model
        expected_repr = "Model(CompiledQubo({('x[0][1]', 'x[0][1]'): 1.0,\n"\
                        " ('x[0][1]', 'x[1][1]'): -2.0,\n"\
                        " ('x[1][1]', 'x[1][1]'): 1.0}, offset=0.0), "\
                        "structure={'x[0][0]': ('x', 0, 0),\n"\
                        " 'x[0][1]': ('x', 0, 1),\n"\
                        " 'x[1][0]': ('x', 1, 0),\n"\
                        " 'x[1][1]': ('x', 1, 1)})"
        self.assertEqual(repr(model), expected_repr)

        # when the constraint is not broken

        # type of solution is dict[label, bit]
        decoded_sol, broken, energy = model.decode_solution(
            {
                'x[0][1]': 1.0,
                'x[1][1]': 1.0
            }, var_type="binary")
        self.assertTrue(decoded_sol == {'x': {0: {1: 1}, 1: {1: 1}}})
        self.assertTrue(len(broken) == 0)
        self.assertTrue(energy == 0)

        # type of solution is list[bit]
        decoded_sol, broken, energy = model.decode_solution([1, 1],
                                                            var_type="binary")
        self.assertTrue(decoded_sol == {'x': {0: {1: 1}, 1: {1: 1}}})
        self.assertTrue(len(broken) == 0)
        self.assertTrue(energy == 0)

        # type of solution is dict[index_label(int), bit]
        decoded_sol, broken, energy = model.decode_solution({
            0: 1.0,
            1: 1.0
        },
                                                            var_type="binary")
        self.assertTrue(decoded_sol == {'x': {0: {1: 1}, 1: {1: 1}}})
        self.assertTrue(len(broken) == 0)
        self.assertTrue(energy == 0)

        # when the constraint is broken

        # type of solution is dict[label, bit]
        decoded_sol, broken, energy = model.decode_solution(
            {
                'x[0][1]': 0.0,
                'x[1][1]': 1.0
            }, var_type="binary")
        self.assertTrue(decoded_sol == {'x': {0: {1: 0}, 1: {1: 1}}})
        self.assertTrue(len(broken) == 1)
        self.assertTrue(energy == 1)

        # type of solution is dict[label, spin]
        decoded_sol, broken, energy = model.decode_solution(
            {
                'x[0][1]': 1.0,
                'x[1][1]': -1.0
            }, var_type="spin")
        self.assertTrue(decoded_sol == {'x': {0: {1: 1}, 1: {1: -1}}})
        self.assertTrue(len(broken) == 1)
        self.assertTrue(energy == 1)

        # invalid solution
        self.assertRaises(
            ValueError,
            lambda: model.decode_solution([1, 1, 1], var_type="binary"))
        self.assertRaises(
            ValueError, lambda: model.decode_solution(
                {
                    'x[0][2]': 1.0,
                    'x[1][1]': 0.0
                }, var_type="binary"))
        self.assertRaises(
            TypeError, lambda: model.decode_solution(
                (1, 1), var_type="binary"))

        # invalid var_type
        self.assertRaises(AssertionError,
                          lambda: model.decode_solution([1, 1], var_type="sp"))
예제 #22
0
margin = 2
#ペナルティ
alpha = 1

#荷物の入れる/入れない
x = Array.create('x', n, 'BINARY')
#スラック変数
s = Array.create('s', margin, 'BINARY')

#価値
total_value = sum(x_i * v_1 for x_i, v_1 in zip(x, values))
#重さ
total_weight = sum(x_i * w_1 for x_i, w_1 in zip(x, weights))
#ハミルトニアン
H = -1 * total_value + alpha * Constraint(
    (total_weight - weight_limit + sum(s_i for s_i in s))**2,
    label='weight_limit')
#quboモデル
model = H.compile()
qubo, offset = model.to_qubo()

# OpenJijで解く
#--------------------------------------
sampler = oj.SASampler()
response = sampler.sample_qubo(qubo, num_reads=1000)
plt.hist(-(response.energies + offset))
## エネルギーが一番低い状態を取り出します。
dict_solution = response.first.sample
## デコードします。
decoded_solution, broken, energy = model.decode_solution(dict_solution,
                                                         vartype="BINARY")
예제 #23
0
import dimod
from pyqubo import Constraint, Array

exactsolver = dimod.ExactSolver()

# Set up variables
x = Array.create('x', shape=5, vartype='BINARY')

# Set up the QUBO. Start with the equation insisting that there are 3
# numbers turned on, and then the equation insisting that they sum up to 8.
H = Constraint((sum(x) - 3)**2, label='3_hot')
H += Constraint(
    (x[0] + (2 * x[1]) + (3 * x[2]) + (4 * x[3]) + (5 * x[4]) - 8)**2,
    label='8_sum')

# Compile the model, and turn it into a QUBO object
model = H.compile()
Q = model.to_qubo()
bqm = dimod.BinaryQuadraticModel.from_qubo(Q[0], offset=Q[1])

# solve the problem
results = exactsolver.sample(bqm)

# print the results
for sample, energy in results.data(['sample', 'energy']):
    _, broken, _ = model.decode_solution(sample, vartype='BINARY')
    if not broken:
        print(sample, energy)
예제 #24
0
routes[7] = [1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0]
routes[8] = [1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0]
routes[9] = [0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0]

# Extra parameter
K = 3

# Initialize variable vector
size_of_variable_array = N + K * M

var = Array.create('vector', size_of_variable_array, 'BINARY')

# Defining constraints in the Model
minimize_costs = 0
minimize_costs += Constraint(Sum(0, N, lambda i: var[i] *
                                 (c_t[i] - c_b[i]) + c_b[i]),
                             label="minimize_transport_costs")

capacity_constraint = 0
for j in range(M):
    capacity_constraint += Constraint(
        (Sum(0, N, lambda i: (1 - var[i]) * routes[i][j]) +
         Sum(0, K, lambda i: var[N + j * K + i] * (2**(i))) - v[j])**2,
        label="capacity_constraints")

teller = 0

while teller < 1:
    teller = teller + 1

    # parameter values
예제 #25
0
    4: (0, 1)
}

# Plot cities
plot_city(cities)
plt.savefig(path + '/venv/results/test/test_simulator_empty.png')
plt.close()

n_city = len(cities)
# x is array of binary variables c[i][j] = 1 when city j is visited at time i and 0 otherwise
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):
    time_const += Constraint((Sum(0, n_city, lambda j: x[i, j]) - 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(0, n_city, lambda i: x[i, j]) - 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):
            d_ij = dist(i, j, cities)
            distance += d_ij * x[k, i] * x[(k+1)%n_city, j]

예제 #26
0
#定義上書き!
x = Array.create('x', shape=(n, m), vartype="BINARY")
#不等号表現用の補助スピン
y = []
for i in range(n):
    #y.append(OneHotEncInteger(f"y{i}",lower=0,upper=JOB_SIZE*2,strength=Placeholder("IntChain")))
    y.append(LogEncInteger(f"y{i}", lower=0, upper=JOB_SIZE * 2))

#目的関数定義相当
H1 = Sum(0, m, lambda j: Sum(0, n, lambda i: x[i][j] * c[i, j]))

#エージェントの利用可能資源量を超えない
H2 = Sum(
    0, n, lambda i: Constraint(
        Sum(0, m, lambda j: x[
            (i, j)] * a[i, j] + y[i] - b[i])**2, f"Agent Resource {i}"))
#H2 = Sum(0,n,lambda i: Sum(0,m,lambda j: x[(i,j)]*a[i,j] - b[i])**2)

#全ての仕事をエージェントに割り振る
H3 = Sum(0, m,
         lambda j: Constraint(Sum(0, n, lambda i: x[i][j] - 1)**2, f"Job{j}"))

H = Placeholder("balancer1") * H1 + Placeholder(
    "balancer2") * H2 + Placeholder("balancer3") * H3

model = H.compile()

#パラメータ探索
study = optuna.create_study(storage='sqlite:///example.db',
                            study_name=f"m{m}n{n}_DW2000Q",
예제 #27
0
def _get_cost(edges: list, epsilon: float = 0.01):
    """Get the cost associated to the input graph.

    :param edges:  edges defining the input graph
    :param epsilon: small number used for the penalties

    :return: the corresponding cost

    """
    vertices = get_vertices(edges)
    cost = 0

    for edge in edges:
        cost += -Binary(str(tuple(edge)))**2

    penalty_constants = _get_penalty_constants(edges, epsilon)

    constraint_one_out = 0
    constraint_one_in = 0
    constraint_min_three = 0
    for v in vertices:
        # max one out
        edges_out_v = get_edges_out_for_vertex(edges, v)
        edges_out_v_pairs = [tuple(c) for c in combinations(edges_out_v, 2)]
        cross_products_out = sum([
            Binary(str((e[0]))) * Binary(str((e[1])))
            for e in edges_out_v_pairs
        ])
        if cross_products_out:
            constraint_one_out += penalty_constants[v][0] * Constraint(
                cross_products_out, label=f'one out for vertex: {v}')

        # max one in
        edges_in_v = get_edges_in_for_vertex(edges, v)
        edges_in_v_pairs = [tuple(c) for c in combinations(edges_in_v, 2)]
        cross_products_in = sum([
            Binary(str((e[0]))) * Binary(str((e[1]))) for e in edges_in_v_pairs
        ])
        if cross_products_in:
            constraint_one_in += penalty_constants[v][1] * Constraint(
                cross_products_in, label=f'one in for vertex: {v}')

        edges_v = get_edges_for_vertex(edges, v)
        edges_v_pairs = [tuple(c) for c in combinations(edges_v, 2)]
        # cycle length at least three
        cross_products_length_2_cycles = sum([
            Binary(str((e[0]))) * Binary(str((e[1]))) for e in edges_v_pairs
            if e[0][0] == e[1][1] and e[0][1] == e[1][0]
        ])
        if cross_products_length_2_cycles:
            # the factor 0.5 is to avoid double counting as each pair will be
            # present twice as we are looping through the vertices
            constraint_min_three += 0.5 * penalty_constants[v][2] * Constraint(
                cross_products_length_2_cycles,
                label=f'min three cycle length for vertex: {v}')

    cost += constraint_one_out
    cost += constraint_one_in
    cost += constraint_min_three

    return cost
예제 #28
0
K += 1

x = Array.create('arr', N + K, 'BINARY')

# Constraints in our model
#x' Sigmax
min_sigx = 0

H = 0
#temp hamiltonian for the Constraint

for i in range(N):
    for j in range(N):
        H += x[i] * x[j] * sigma[i][j]

min_sigx += Constraint(H, label="min_portfolio")

H = 0
#temp hamiltonian for the Constraint
for i in range(N):
    H += x[i]
H -= n
H = H**2

select_n = Constraint(H, label="select_n_projects")

H = 0
#temp hamiltonian for the Constraint

for i in range(N):
    H += returns[i] * x[i]
예제 #29
0
chainstrength = 70
numruns = 100

# Problem size
N_CARS = 2
N_ROUTES = 3

# Form the pyqubo binary variables representing (Car, Route)
q = Array.create('q', shape=(N_CARS, N_ROUTES), vartype='BINARY')

gamma = Placeholder('gamma')

# Constraints, one for each Car
H = 0
for i in range(N_CARS):
    H += gamma * Constraint((sum(q[i, j] for j in range(N_ROUTES)) - 1) ** 2, label=str(i))

# Cost functions
# Be sure to count them once for each segment
# s0 and s3
H += 2 * ((q[0, 0] + q[0, 1] + q[1, 0] + q[1, 1]) ** 2)
# s2 and s7 and s10
H += 3 * ((q[0, 2] + q[1, 2]) ** 2)
# s6 and s9
H += 2 * ((q[0, 0] + q[1, 0]) ** 2)
# s8
H += (q[0, 1] + q[1, 1]) ** 2
# s11
H += (q[0, 1] + q[0, 2] + q[1, 1] + q[1, 2]) ** 2

# Compile the model, and turn it into a QUBO object
예제 #30
0
vertices = list(range(N))
edges = [
    (0, 1),
    (0, 4),
    (0, 5),
    (1, 2),
    (1, 3),
    (3, 4),
    (4, 5),
]

# binary variable
x = Array.create("x", shape=N, vartype="BINARY")

# energy function (QUBO)
H_cover = Constraint(sum((1 - x[u]) * (1 - x[v]) for (u, v) in edges), "cover")
H_vertices = sum(x)
H = H_vertices + Placeholder("cover") * H_cover

model = H.compile()

feed_dict = {"cover": 1.0}
qubo, offset = model.to_qubo(feed_dict=feed_dict)

# search answer using SA
raw_solution = solve_qubo(qubo)

# decode answer
decoded_solution, broken, energy = model.decode_solution(raw_solution,
                                                         vartype="BINARY",
                                                         feed_dict=feed_dict)