예제 #1
0
    def test_array_subtract(self):
        array1 = Array.create('x', (2, 2), 'BINARY')
        array2 = Array.create('y', (2, 2), 'BINARY')
        expected = Array([[
            Binary('x[0][0]') - Binary('y[0][0]'),
            Binary('x[0][1]') - Binary('y[0][1]')
        ],
                          [
                              Binary('x[1][0]') - Binary('y[1][0]'),
                              Binary('x[1][1]') - Binary('y[1][1]')
                          ]])
        self.assertTrue(array1 - array2 == expected)

        expected2 = Array([[Binary('x[0][0]') - 1,
                            Binary('x[0][1]') - 1],
                           [Binary('x[1][0]') - 1,
                            Binary('x[1][1]') - 1]])
        self.assertTrue(array1 - 1 == expected2)
        # expected3 = Array([[1 - Binary('x[0][0]'), 1 - Binary('x[0][1]')],
        #                    [1 - Binary('x[1][0]'), 1 - Binary('x[1][1]')]])
        expected3 = Array(
            [[Binary('x[0][0]') * -1 + 1,
              Binary('x[0][1]') * -1 + 1],
             [Binary('x[1][0]') * -1 + 1,
              Binary('x[1][1]') * -1 + 1]])
        self.assertTrue(1 - array1 == expected3)
        self.assertTrue(array1 - np.ones((2, 2)) == expected2)
예제 #2
0
    def __init__(self,
                 vartype: str,
                 variables: List[Variable],
                 constants: List[Constant] = []):
        if len(variables) == 0:
            raise ParserInitArgumentsError(code=1001,
                                           message="variable is required.")

        self.vartype = vartype

        # set variables
        for variable in variables:
            if len(variable["symbol"]) != 1:
                raise ParserInitArgumentsError(
                    code=1002,
                    message="variable symbol must be one character.")

            if variable["dimension"] == 0:
                if variable["type"] == "SPIN":
                    var = Spin(variable["symbol"])
                else:
                    var = Binary(variable["symbol"])
            elif variable["dimension"] == 1:
                if isinstance(variable["size"], int):
                    var = Array.create(variable["symbol"], variable["size"],
                                       variable["type"])
                else:
                    raise ParserInitArgumentsError(
                        code=1004,
                        message=
                        "if variable dimension is 1, variable size must be int.",
                    )
            elif variable["dimension"] >= 2:
                if isinstance(variable["size"], list):
                    var = Array.create(variable["symbol"],
                                       tuple(variable["size"]),
                                       variable["type"])
                else:
                    raise ParserInitArgumentsError(
                        code=1005,
                        message=
                        "if variable dimension is larger than 1, variable size must be list.",
                    )
            else:
                raise ParserInitArgumentsError(
                    code=1003,
                    message="variable dimension must be positive integer.")
            exec("self.{} = var".format(variable["symbol"]))

        # set constants
        for constant in constants:
            if isinstance(constant["values"], (int, float)):
                const = float(constant["values"])
            elif isinstance(constant["values"], list):
                const = np.array(constant["values"])
            exec("self.{} = const".format(constant["symbol"]))
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()
예제 #4
0
    def test_work_with_dimod(self):
        S = Array.create('S', 3, "SPIN")
        H = 0.8 * S[0] * S[1] + S[1] * S[2] + 1.1 * S[2] * S[0] + 0.5 * S[0]
        model = H.compile()

        # with index_label=False
        binary_bqm = model.to_bqm(index_label=False)
        sampler = dimod.ExactSolver()
        sampleset = sampler.sample(binary_bqm)
        decoded_samples = model.decode_sampleset(sampleset)
        best_sample = min(decoded_samples, key=lambda s: s.energy)
        self.assertTrue(best_sample.array("S", 0) == 0)
        self.assertTrue(best_sample.array("S", 1) == 0)
        self.assertTrue(best_sample.array("S", 2) == 1)
        self.assertTrue(np.isclose(best_sample.energy, -1.8))

        # with index_label=True
        binary_bqm = model.to_bqm(index_label=True)
        sampler = dimod.ExactSolver()
        sampleset = sampler.sample(binary_bqm)
        decoded_samples = model.decode_sampleset(sampleset)
        best_sample = min(decoded_samples, key=lambda s: s.energy)
        self.assertTrue(best_sample.array("S", 0) == 0)
        self.assertTrue(best_sample.array("S", 1) == 0)
        self.assertTrue(best_sample.array("S", 2) == 1)
        self.assertTrue(np.isclose(best_sample.energy, -1.8))
예제 #5
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
예제 #6
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")
예제 #7
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
예제 #8
0
def qubo_fy_eldan(wind_speeds, prob_l, n, aggregated_coef, m):
    matrix = np.zeros((n, n))
    # scaling if needed due to embedding considerations
    scaling = 50  # 0
    arr_x = []
    X = Array.create("x", n, 'BINARY')

    for i in range(n):
        matrix[i, i] = 0.33 * np.dot(prob_l, pow(wind_speeds, 3))

    for i in range(n):
        for j in range(i, n):
            matrix[i, j] -= aggregated_coef[i, j]
            matrix[j, i] -= matrix[i, j]

    lam_ = 10500
    # computing sum of decision variables

    for (i, j) in Epsilon:
        matrix[i, j] -= lam_

    expr = lam_ * (sum(X) - m)**2
    # constraint on the number of turbines
    constr_coeffs, constr_constant = expr.compile().to_qubo()
    for i in range(n):
        for j in range(i, n):
            val = max(constr_coeffs.get((X[i].label, X[j].label), 0),
                      constr_coeffs.get((X[j].label, X[i].label), 0))
            matrix[i, j] -= val

    return matrix, constr_constant
예제 #9
0
def make_qubo(particles, theta):
    # Create an array os spin variables
    n_part = len(particles)
    s = Array.create('s', shape=n_part, vartype='BINARY')

    # Create an array of zeroes for qubo matrix coefficients
    coeff = [[0] * n_part for _ in range(n_part)]
    #theta = np.pi/4.

    for i in range(0, n_part):
        for j in range(0, n_part):
            coeff[i][j] = (particles[i]['px'] * particles[j]['px'] +
                           particles[i]['py'] * particles[j]['py'] +
                           particles[i]['pz'] * particles[j]['pz'] -
                           particles[i]['E'] * particles[j]['E'] *
                           np.cos(theta)) / (1 - np.cos(theta))

    # Construct Hamiltonian
    H = sum([
        -1.0 * coeff[i][j] * s[i] * s[j] for i in range(0, n_part)
        for j in range(0, n_part)
    ])

    # Compile model using pyqubo

    model = H.compile()
    qubo, offset = model.to_qubo()

    return qubo, offset
예제 #10
0
def generate_test_case(size, num_terms, var_type="BINARY"):
    x = Array.create('x', size, var_type)
    numerator, divisor = [], []
    for i in range(num_terms):
        numerator.append(np.random.randint(1, 10, size))
        divisor.append(np.random.randint(1, 10, size))
    return x, numerator, divisor
예제 #11
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"))
예제 #12
0
def model_variables_pyqubo():
    print("\n=== model (variables via pyqubo) ===")
    x = Array.create("x", shape=(2, 3), vartype="SPIN")
    model = sawatabi.model.LogicalModel(mtype="ising")
    model.variables(x)

    print("\nCheck the variables below.")
    _print_utf8(model)
예제 #13
0
    def test_array_dot(self):

        # inner product of 1-D arrays
        array_a = Array([Binary('a'), Binary('b')])
        array_b = Array([Binary('c'), Binary('d')])
        expected = ((Binary('a') * Binary('c')) + (Binary('b') * Binary('d')))
        self.assertTrue(expected == array_a.dot(array_b))

        # dot product of 1-D array and N-D array
        array_a = Array([[Binary('a'), Binary('b')],
                         [Binary('c'), Binary('d')]])
        array_b = Array([Binary('e'), Binary('f')])
        expected = Array([
            ((Binary('a') * Binary('e')) + (Binary('b') * Binary('f'))),
            ((Binary('c') * Binary('e')) + (Binary('d') * Binary('f')))
        ])
        self.assertTrue(expected == array_a.dot(array_b))

        # both are 2-D arrays
        array_a = Array([[Binary('a'), Binary('b')],
                         [Binary('c'), Binary('d')]])
        array_b = Array([[Binary('e'), Binary('f')],
                         [Binary('g'), Binary('h')]])
        expected = Array(
            [[((Binary('a') * Binary('e')) + (Binary('b') * Binary('g'))),
              ((Binary('a') * Binary('f')) + (Binary('b') * Binary('h')))],
             [((Binary('c') * Binary('e')) + (Binary('d') * Binary('g'))),
              ((Binary('c') * Binary('f')) + (Binary('d') * Binary('h')))]])
        self.assertTrue(expected == array_a.dot(array_b))

        # array_a is a  N-D array and array_b is an M-D array (where N, M>=2)
        array_a = Array.create('a', shape=(3, 2, 4), vartype='BINARY')
        array_b = Array.create('b', shape=(5, 4, 3), vartype='BINARY')
        i, j, k, m = (1, 1, 3, 2)
        self.assertTrue(
            array_a.dot(array_b)[i, j, k, m] == sum(array_a[i, j, :] *
                                                    array_b[k, :, m]))

        # array_a is 1-D array and array_b is a list
        array_a = Array([Binary('a'), Binary('b')])
        array_b = [3, 4]
        self.assertTrue((Binary('a') * 3 +
                         (Binary('b') * 4)) == array_a.dot(array_b))

        # test validation
        self.assertRaises(TypeError, lambda: array_a.dot(1))
예제 #14
0
 def test_array_transpose(self):
     array = Array.create('x', (2, 3), 'BINARY')
     expected = Array([[Binary('x[0][0]'),
                        Binary('x[1][0]')],
                       [Binary('x[0][1]'),
                        Binary('x[1][1]')],
                       [Binary('x[0][2]'),
                        Binary('x[1][2]')]])
     self.assertTrue(array.T == expected)
예제 #15
0
    def test_array_division(self):
        array1 = Array.create('x', (2, 2), 'BINARY')
        expected = Array([[Binary('x[0][0]') / 2.0,
                           Binary('x[0][1]') / 2.0],
                          [Binary('x[1][0]') / 2.0,
                           Binary('x[1][1]') / 2.0]])
        self.assertTrue(array1 / 2.0 == expected)

        self.assertRaises(ValueError, lambda: 1 / array1)
        self.assertRaises(ValueError, lambda: array1 / array1)
예제 #16
0
def QUBOConstruct_goldenref(NM, MDM, P_i, P_e, IO_blocks, CLB_blocks, IO_sites,
                            CLB_sites):
    # use pyqubo to generate qubo matrix as a golden reference
    N = MDM.shape[0]
    X = Array.create('X', shape=(N, N), vartype='BINARY')
    print(N)

    # generate quadratic objective function
    obj = 0
    for i in trange(N, desc='Creating quadratic objective'):
        for j in range(N):
            obj += NM[i, j] * X[i, :].dot(MDM).dot(X[j, :].T)

    constr = 0

    # generate implicit constraints
    for i in trange(N, desc='Creating row implicit constraints'):
        C = 0
        for j in range(N):
            C += X[i, j]
        constr += P_i * (C - 1)**2
    for j in trange(N, desc='Creating col implicit constraints'):
        C = 0
        for i in range(N):
            C += X[i, j]
        constr += P_i * (C - 1)**2

    # generate explicit constraints
    for (i, j) in tqdm([(io_block, clb_site) for io_block in IO_blocks
                        for clb_site in CLB_sites],
                       desc='Creating explicit constraint type 1'):
        constr += P_e * (X[i, j]**2)
    for (i, j) in tqdm([(clb_block, io_site) for clb_block in CLB_blocks
                        for io_site in IO_sites],
                       desc='Creating explicit constraint type 2'):
        constr += P_e * (X[i, j]**2)

    H = obj + constr
    model = H.compile()
    qubo_dict, offset = model.to_qubo()

    qubo_mat = np.zeros((N**2, N**2))
    for (key, val) in qubo_dict.items():
        src_x, src_y = re.findall(r'\d+', key[0])
        dst_x, dst_y = re.findall(r'\d+', key[1])
        qubo_mat[int(src_x) * N + int(src_y),
                 int(dst_x) * N + int(dst_y)] = val

    # convert to upper triangle matrix
    for (i, j) in tqdm([(i, j) for i in range(N**2)
                        for j in range(i + 1, N**2)],
                       desc='Converting to upper triangle matrix'):
        qubo_mat[i, j], qubo_mat[j, i] = qubo_mat[i, j] + qubo_mat[j, i], 0

    return coo_matrix(qubo_mat), offset
예제 #17
0
    def test_array_matmul(self):

        # the either of the arguments is 1-D array,
        array_a = Array([[Binary('a'), Binary('b')],
                         [Binary('c'), Binary('d')]])
        array_b = Array([Binary('e'), Binary('f')])
        expected = Array([
            ((Binary('a') * Binary('e')) + (Binary('b') * Binary('f'))),
            ((Binary('c') * Binary('e')) + (Binary('d') * Binary('f')))
        ])
        self.assertTrue(array_a.matmul(array_b) == expected)

        # both arguments are 2-D array
        array_a = Array([[Binary('a'), Binary('b')],
                         [Binary('c'), Binary('d')]])
        array_b = Array([[Binary('e'), Binary('f')],
                         [Binary('g'), Binary('h')]])
        expected = Array(
            [[((Binary('a') * Binary('e')) + (Binary('b') * Binary('g'))),
              ((Binary('a') * Binary('f')) + (Binary('b') * Binary('h')))],
             [((Binary('c') * Binary('e')) + (Binary('d') * Binary('g'))),
              ((Binary('c') * Binary('f')) + (Binary('d') * Binary('h')))]])
        self.assertTrue(array_a.matmul(array_b) == expected)

        # either argument is N-D (where N > 2)
        array_a = Array.create('a', shape=(2, 2, 3), vartype='BINARY')
        array_b = Array.create('b', shape=(3, 2), vartype='BINARY')
        self.assertTrue(
            (array_a.matmul(array_b))[0] == array_a[0].matmul(array_b))

        # array_a is 2-D array and array_b is a list
        array_a = Array([[Binary('a'), Binary('b')],
                         [Binary('c'), Binary('d')]])
        array_b = [3, 4]
        expected = Array([((Binary('a') * Num(3)) + (Binary('b') * Num(4))),
                          ((Binary('c') * Num(3)) + (Binary('d') * Num(4)))])
        self.assertTrue(expected == array_a.matmul(array_b))

        # test validation
        array_a = Array.create('a', shape=(2, 2, 3), vartype='BINARY')
        array_b = Array.create('b', shape=(3, 3, 2), vartype='BINARY')
        self.assertRaises(AssertionError, lambda: array_a.matmul(array_b))
예제 #18
0
    def test_array_multiply(self):
        array1 = Array.create('x', (2, 2), 'BINARY')
        array2 = Array.create('y', (2, 2), 'BINARY')
        expected = Array([[
            Binary('x[0][0]') * Binary('y[0][0]'),
            Binary('x[0][1]') * Binary('y[0][1]')
        ],
                          [
                              Binary('x[1][0]') * Binary('y[1][0]'),
                              Binary('x[1][1]') * Binary('y[1][1]')
                          ]])
        self.assertTrue(array1 * array2 == expected)

        expected2 = Array([[Binary('x[0][0]') * 2,
                            Binary('x[0][1]') * 2],
                           [Binary('x[1][0]') * 2,
                            Binary('x[1][1]') * 2]])
        self.assertTrue(array1 * 2 == expected2)
        self.assertTrue(2 * array1 == expected2)
        self.assertTrue(array1 * (2 * np.ones((2, 2))) == expected2)
예제 #19
0
 def test_array_reshape(self):
     array = Array.create('a', shape=(2, 3), vartype='BINARY')
     reshaped = array.reshape((3, 2))
     self.assertTrue(reshaped.shape == (3, 2))
     expected = Array([[Binary('a[0][0]'),
                        Binary('a[0][1]')],
                       [Binary('a[0][2]'),
                        Binary('a[1][0]')],
                       [Binary('a[1][1]'),
                        Binary('a[1][2]')]])
     self.assertTrue(reshaped == expected)
예제 #20
0
 def test_compile_vector_spin(self):
     x = Array.create('x', 2, 'SPIN')
     exp = x[1] * x[0] + x[0]
     expected_qubo = {
         ('x[1]', 'x[1]'): -2.0,
         ('x[0]', 'x[0]'): 0.0,
         ('x[0]', 'x[1]'): 4.0
     }
     expected_offset = 0.0
     expected_structure = {'x[0]': ('x', 0), 'x[1]': ('x', 1)}
     self.compile_check(exp, expected_qubo, expected_offset,
                        expected_structure)
예제 #21
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)
예제 #22
0
 def test_work_with_dimod(self):
     S = Array.create('S', 3, "SPIN")
     H = 0.8 * S[0] * S[1] + S[1] * S[2] + 1.1 * S[2] * S[0] + 0.5 * S[0]
     model = H.compile()
     binary_bqm = model.to_bqm()
     sampler = dimod.ExactSolver()
     sampleset = sampler.sample(binary_bqm)
     sol = model.decode_sampleset(sampleset)
     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))
예제 #23
0
 def test_compile_matrix_spin(self):
     x = Array.create("x", (2, 2), "SPIN")
     exp = x[1, 1] * x[0, 0] + x[0, 0]
     expected_qubo = {
         ('x[1][1]', 'x[1][1]'): -2.0,
         ('x[0][0]', 'x[0][0]'): 0.0,
         ('x[0][0]', 'x[1][1]'): 4.0
     }
     expected_offset = 0.0
     expected_structure = {'x[0][0]': ('x', 0, 0), 'x[1][1]': ('x', 1, 1)}
     self.compile_check(exp, expected_qubo, expected_offset,
                        expected_structure)
예제 #24
0
    def test_sum(self):
        x = Array.create('x', 2, "BINARY")
        exp = (Sum(0, 2, lambda i: x[i]) - 1)**2

        expected_qubo = {
            ('x[0]', 'x[0]'): -1.0,
            ('x[1]', 'x[1]'): -1.0,
            ('x[0]', 'x[1]'): 2.0
        }
        expected_offset = 1.0
        expected_structure = {'x[0]': ('x', 0), 'x[1]': ('x', 1)}
        self.compile_check(exp, expected_qubo, expected_offset,
                           expected_structure)
예제 #25
0
    def __init__(
        self,
        _cost_list,
        _value_list,
        _threshold,
    ):
        """
            constructor
        """
        self.THRESHOLD = _threshold
        self.COST_LIST = _cost_list
        self.VALUE_LIST = _value_list

        _max = 0.0
        for cost in self.COST_LIST:
            if _max < cost:
                _max = cost
        self.LAMBDA = 2.0 * _max

        # QUBO variables
        self.N = len(self.COST_LIST)
        self.q = Array.create('q', shape=self.N, vartype='BINARY')
        self.y = Array.create('y', shape=self.THRESHOLD, vartype='BINARY')
예제 #26
0
    def create_prob_instance(self):
        N = 15
        K = 3
        numbers = [4.8097315016016315, 4.325157567810298, 2.9877429101815127,
                   3.199880179616316, 0.5787939511978596, 1.2520928214246918,
                   2.262867466401502, 1.2300003067401255, 2.1601079352817925,
                   3.63753899583021, 4.598232793833491, 2.6215815162575646,
                   3.4227134835783364, 0.28254151584552023, 4.2548151473817075]

        q = Array.create('q', N, 'BINARY')
        H = sum(numbers[i] * q[i] for i in range(N)) + 5.0 * (sum(q) - K)**2
        model = H.compile()
        Q, offset = model.to_qubo(index_label=True)
        return dimod.BinaryQuadraticModel.from_qubo(Q, offset)
예제 #27
0
파일: test_array.py 프로젝트: w40141/pyqubo
 def test_array_repr(self):
     array = Array.create('x', shape=(3, 3, 3), vartype='BINARY')
     expected_string =\
         'Array([[[Binary(x[0][0][0]), Binary(x[0][0][1]), Binary(x[0][0][2])],\n'\
         '        [Binary(x[0][1][0]), Binary(x[0][1][1]), Binary(x[0][1][2])],\n'\
         '        [Binary(x[0][2][0]), Binary(x[0][2][1]), Binary(x[0][2][2])]],\n'\
         '\n'\
         '       [[Binary(x[1][0][0]), Binary(x[1][0][1]), Binary(x[1][0][2])],\n'\
         '        [Binary(x[1][1][0]), Binary(x[1][1][1]), Binary(x[1][1][2])],\n'\
         '        [Binary(x[1][2][0]), Binary(x[1][2][1]), Binary(x[1][2][2])]],\n'\
         '\n'\
         '       [[Binary(x[2][0][0]), Binary(x[2][0][1]), Binary(x[2][0][2])],\n'\
         '        [Binary(x[2][1][0]), Binary(x[2][1][1]), Binary(x[2][1][2])],\n'\
         '        [Binary(x[2][2][0]), Binary(x[2][2][1]), Binary(x[2][2][2])]]])'
     self.assertTrue(repr(array) == expected_string)
예제 #28
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))
예제 #29
0
    def test_array_add(self):
        array1 = Array.create('x', (2, 2), 'BINARY')
        array2 = Array.create('y', (2, 2), 'BINARY')
        expected = Array([[
            Binary('x[0][0]') + Binary('y[0][0]'),
            Binary('x[0][1]') + Binary('y[0][1]')
        ],
                          [
                              Binary('x[1][0]') + Binary('y[1][0]'),
                              Binary('x[1][1]') + Binary('y[1][1]')
                          ]])
        self.assertTrue(array1 + array2 == expected)

        expected2 = Array([[Binary('x[0][0]') + 1,
                            Binary('x[0][1]') + 1],
                           [Binary('x[1][0]') + 1,
                            Binary('x[1][1]') + 1]])
        self.assertTrue(array1 + 1 == expected2)
        self.assertTrue(1 + array1 == expected2)
        self.assertTrue(array1 + np.ones((2, 2)) == expected2)

        self.assertRaises(TypeError, lambda: array1 + "str")
        array3 = Array.create('z', (2, 3), 'BINARY')
        self.assertRaises(ValueError, lambda: array1 + array3)
예제 #30
0
 def test_compile_vector(self):
     x = Array.create('x', 5, 'BINARY')
     a = Binary('a')
     exp = x[1] * (x[0] + 2 * a + 1)
     expected_qubo = {
         ('a', 'a'): 0.0,
         ('a', 'x[1]'): 2.0,
         ('x[0]', 'x[0]'): 0.0,
         ('x[0]', 'x[1]'): 1.0,
         ('x[1]', 'x[1]'): 1.0
     }
     expected_offset = 0.0
     expected_structure = {'a': ('a', ), 'x[0]': ('x', 0), 'x[1]': ('x', 1)}
     self.compile_check(exp, expected_qubo, expected_offset,
                        expected_structure)