Пример #1
0
def test_properties():

    temp = PCSO({('0', '0'): 1, ('0', 1): 2})
    assert temp.offset == 1

    d = PCSO()
    d[(0, )] += 1
    d[(1, )] += 2
    assert d == d.to_quso() == {(0, ): 1, (1, ): 2}
    assert d.mapping == d.reverse_mapping == {0: 0, 1: 1}

    d.set_mapping({1: 0, 0: 1})
    assert d.to_quso() == {(1, ): 1, (0, ): 2}
    assert d.mapping == d.reverse_mapping == {0: 1, 1: 0}

    assert d.constraints == {}
    temp = d.copy()
    d.add_constraint_eq_zero(temp)
    assert d.constraints == {'eq': [temp]}

    # an old bug
    d = PCSO()
    d.set_mapping({0: 0})
    d[(0, )] += 1
    assert d.num_binary_variables == 1
    assert d.variables == {0}
Пример #2
0
def test_symbols():

    a, b = Symbol('a'), Symbol('b')
    d = PCSO()
    d[(0, )] -= a
    d[(0, 1)] += 2
    d[(1, )] += b
    assert d == {(0, ): -a, (0, 1): 2, (1, ): b}
    assert d.subs(a, 2) == {(0, ): -2, (0, 1): 2, (1, ): b}
    assert d.subs(b, 1) == {(0, ): -a, (0, 1): 2, (1, ): 1}
    assert d.subs({a: -3, b: 4}) == {(0, ): 3, (0, 1): 2, (1, ): 4}

    d.add_constraint_eq_zero({(0, ): a, (1, ): -b}, bounds=(-1, 1))
    d.simplify()
    assert d == {
        (0, ): -1. * a,
        (0, 1): -2. * a * b + 2.,
        (1, ): 1. * b,
        (): 1. * a**2 + 1. * b**2
    }
    assert d.subs(a, 0) == {(0, 1): 2, (1, ): 1. * b, (): 1. * b**2}
    assert d.subs({a: 0, b: 2}) == {(0, 1): 2, (1, ): 2, (): 4}
Пример #3
0
def test_pcso_eq_constraint():

    lam = Symbol('lam')

    H = PCSO(
        pubo_to_puso({
            ('a', ): -1,
            ('b', ): 2,
            ('a', 'b'): -3,
            ('b', 'c'): -4,
            (): -2
        }))
    H.add_constraint_eq_zero(pubo_to_puso({
        ('a', ): 1,
        ('b', ): 1,
        ('b', 'c'): -1
    }),
                             lam=lam)
    solution = boolean_to_spin({'c': 1, 'b': 1, 'a': 0})
    obj = -4

    problem = H.subs(lam, 1)
    sol = problem.solve_bruteforce()
    assert all((problem.is_solution_valid(sol), sol == solution))

    e, sol = solve_pubo_bruteforce(problem.to_pubo())
    sol = problem.convert_solution(sol, False)
    assert all((not problem.is_solution_valid(sol), sol != solution,
                not allclose(e, obj)))

    problem = H.subs(lam, 10)
    sol = problem.solve_bruteforce()
    assert all((problem.is_solution_valid(sol), sol == solution))

    e, sol = solve_pubo_bruteforce(problem.to_pubo())
    sol = problem.convert_solution(sol)
    assert all(
        (problem.is_solution_valid(sol), sol == solution, allclose(e, obj)))