def test_logical_model_variables_append(initial_shape, additional_shape, expected_shape):
    model = LogicalModel(mtype="ising")
    model.variables("x", shape=initial_shape)
    assert "x" in model.get_variables()
    assert model.get_variables_by_name("x").shape == initial_shape

    model.append("x", shape=additional_shape)
    assert model.get_variables_by_name("x").shape == expected_shape
Example #2
0
def test_sawatabi_solver_with_initial_states_reverse():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(6,))
    for i in range(6):
        model.add_interaction(x[i], coefficient=10.0)

    solver = SawatabiSolver()
    initial_states = [
        {
            "x[0]": -1,
            "x[1]": -1,
            "x[2]": -1,
            "x[3]": -1,
            "x[4]": -1,
            "x[5]": -1,
        },
    ]
    sampleset = solver.solve(
        model.to_physical(),
        num_reads=1,
        num_sweeps=10,
        initial_states=initial_states,
        reverse_options={"reverse_period": 5, "reverse_temperature": 10.0},
        seed=12345,
    )

    assert len(sampleset.record) == 1

    # Check the ground state
    assert np.array_equal(sampleset.record[0].sample, [1, 1, 1, 1, 1, 1])
    assert sampleset.record[0].energy == -60.0
    assert sampleset.record[0].num_occurrences == 1
def test_logical_model_to_physical(mtype):
    model = LogicalModel(mtype=mtype)
    x = model.variables("x", shape=(2,))
    model.add_interaction(x[0], coefficient=1.0)
    model.add_interaction((x[0], x[1]), coefficient=-1.0)
    model._update_interactions_dataframe_from_arrays()  # Update the interactions DataFrame for debug

    assert model._interactions[model._interactions["name"] == "x[0]"]["dirty"].values[0]
    assert model._interactions[model._interactions["name"] == "x[0]*x[1]"]["dirty"].values[0]

    physical = model.to_physical()
    model._update_interactions_dataframe_from_arrays()  # Update the interactions DataFrame for debug

    assert physical.get_mtype() == mtype
    assert len(physical._raw_interactions[constants.INTERACTION_LINEAR]) == 1
    assert len(physical._raw_interactions[constants.INTERACTION_QUADRATIC]) == 1
    assert physical._raw_interactions[constants.INTERACTION_LINEAR]["x[0]"] == 1.0
    assert physical._raw_interactions[constants.INTERACTION_QUADRATIC][("x[0]", "x[1]")] == -1.0
    assert not model._interactions[model._interactions["name"] == "x[0]"]["dirty"].values[0]
    assert not model._interactions[model._interactions["name"] == "x[0]*x[1]"]["dirty"].values[0]

    assert physical._label_to_index["x[0]"] == 0
    assert physical._label_to_index["x[1]"] == 1
    assert len(physical._label_to_index) == 2
    assert physical._index_to_label[0] == "x[0]"
    assert physical._index_to_label[1] == "x[1]"
    assert len(physical._index_to_label) == 2
Example #4
0
def physical():
    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(2, ))
    model.add_interaction(x[0], coefficient=1.0)
    model.add_interaction((x[0], x[1]), coefficient=-1.0)
    physical = model.to_physical()
    return physical
Example #5
0
def test_local_solver_sa_ising():
    model = LogicalModel(mtype="ising")
    s = model.variables("s", shape=(2,))
    model.add_interaction(s[0], coefficient=1.0)
    model.add_interaction(s[1], coefficient=2.0)
    model.add_interaction((s[0], s[1]), coefficient=-3.0)
    model.offset(10.0)

    solver = LocalSolver()
    sampleset1 = solver.solve(model.to_physical(), seed=12345)

    assert sampleset1.variables == ["s[0]", "s[1]"]
    assert len(sampleset1.record) == 1

    # Check the ground state
    assert np.array_equal(sampleset1.record[0].sample, [-1, 1])
    assert sampleset1.record[0].energy == 6.0
    assert sampleset1.record[0].num_occurrences == 1

    # Check the second solve with the same solver instance
    sampleset2 = solver.solve(model.to_physical(), seed=54321)

    assert sampleset2.variables == ["s[0]", "s[1]"]
    assert len(sampleset2.record) == 1

    # Check the ground state
    assert np.array_equal(sampleset2.record[0].sample, [-1, 1])
    assert sampleset2.record[0].energy == 6.0
    assert sampleset2.record[0].num_occurrences == 1
def ising_x44():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(4, 4))
    model.add_interaction(x[0, 0], coefficient=20.0)
    model.add_interaction((x[1, 1], x[2, 2]), coefficient=21.0, attributes={"foo2": "bar2"})
    model.add_interaction(x[3, 3], coefficient=22.0, scale=2.0, timestamp=12345, attributes={"myattr": "mymymymy"})
    return model
Example #7
0
def test_sawatabi_solver_with_initial_states_qubo():
    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(6,))
    for i in range(6):
        model.add_interaction(x[i], coefficient=-1.0)

    solver = SawatabiSolver()
    initial_states = [
        {
            "x[0]": 1,
            "x[1]": 0,
            "x[2]": 1,
            "x[3]": 0,
            "x[4]": 1,
            "x[5]": 0,
        },
    ]
    sampleset = solver.solve(model.to_physical(), num_reads=1, num_sweeps=10, cooling_rate=0.5, initial_states=initial_states, seed=12345)

    assert len(sampleset.record) == 1

    # Check the ground state
    assert np.array_equal(sampleset.record[0].sample, [0, 0, 0, 0, 0, 0])
    assert sampleset.record[0].energy == 0.0
    assert sampleset.record[0].num_occurrences == 1
Example #8
0
def test_sawatabi_solver_with_initial_states_ising():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(12,))
    for i in range(12):
        model.add_interaction(x[i], coefficient=-1.0)

    solver = SawatabiSolver()
    initial_states = [
        {
            "x[0]": 1,
            "x[1]": -1,
            "x[2]": -1,
            "x[3]": -1,
            "x[4]": -1,
            "x[5]": -1,
            "x[6]": -1,
            "x[7]": -1,
            "x[8]": -1,
            "x[9]": -1,
            "x[10]": -1,
            "x[11]": -1,
        },
    ]
    sampleset = solver.solve(model.to_physical(), num_reads=1, num_sweeps=1, pickup_mode="sequential", initial_temperature=1e-9, initial_states=initial_states)

    assert len(sampleset.record) == 1

    # Check the ground state
    assert np.array_equal(sampleset.record[0].sample, [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1])
    assert sampleset.record[0].energy == -12.0
    assert sampleset.record[0].num_occurrences == 1
Example #9
0
def _create_ising_model_for_eq():
    model = LogicalModel(mtype="ising")
    x = model.variables(name="x", shape=(3, ))
    model.delete_variable(x[0])
    model.add_interaction(x[1], coefficient=1.0)
    model.add_interaction(x[2], coefficient=2.0)
    model.add_interaction((x[1], x[2]), coefficient=3.0)
    return model.to_physical()
Example #10
0
def qubo():
    model = LogicalModel(mtype="qubo")
    x = model.variables(name="x", shape=(3, ))
    model.delete_variable(x[0])
    model.add_interaction(x[1], coefficient=1.0)
    model.add_interaction(x[2], coefficient=2.0)
    model.add_interaction((x[1], x[2]), coefficient=3.0)
    return model.to_physical()
Example #11
0
def test_optigan_solver_with_ising_model_fails():
    model = LogicalModel(mtype="ising")
    s = model.variables("s", shape=(2, ))
    model.add_interaction((s[0], s[1]), coefficient=-1.0)
    physical = model.to_physical()
    solver = OptiganSolver()
    with pytest.raises(ValueError):
        solver.solve(physical)
Example #12
0
def test_optigan_solver_with_empty_config_fails():
    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(2, ))
    model.add_interaction((x[0], x[1]), coefficient=-1.0)
    physical = model.to_physical()
    solver = OptiganSolver(config="/tmp/.optigan.yml")
    with pytest.raises(FileNotFoundError):
        solver.solve(physical)
Example #13
0
def test_sawatabi_solver_invalid_pickup_mode():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(2,))
    for i in range(2):
        model.add_interaction(x[i], coefficient=-1.0)
    solver = SawatabiSolver()

    with pytest.raises(ValueError):
        solver.solve(model.to_physical(), pickup_mode="invalid")
Example #14
0
def test_logical_model_variables_from_pyqubo(vartype, mtype):
    x = pyqubo.Array.create("x", shape=(2, 3), vartype=vartype)
    model = LogicalModel(mtype=mtype)
    x_when_applied = model.variables(x)
    x_from_model = model.get_variables_by_name("x")
    assert id(x) == id(x_when_applied)
    assert x == x_when_applied
    assert id(x) == id(x_from_model)
    assert x == x_from_model
Example #15
0
def test_local_solver_default_beta_range():
    model = LogicalModel(mtype="ising")
    s = model.variables("s", shape=(2,))
    model.add_interaction(s[0], coefficient=1.0)
    model.add_interaction(s[1], coefficient=2.0)
    model.add_interaction((s[0], s[1]), coefficient=-3.0)

    solver = LocalSolver()
    beta_range = solver.default_beta_range(model.to_physical())
    assert beta_range == [0.13862943611198905, 4.605170185988092]
Example #16
0
def test_sawatabi_solver_with_initial_states_fails():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(2,))
    for i in range(2):
        model.add_interaction(x[i], coefficient=-1.0)
    solver = SawatabiSolver()
    initial_states = [{"x[0]": 1, "x[1]": 1}]

    with pytest.raises(ValueError):
        solver.solve(model.to_physical(), num_reads=2, initial_states=initial_states)
Example #17
0
def test_logical_model_multi_variables(shape):
    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape)
    assert len(model.get_variables()) == 1
    assert "x" in model.get_variables()
    assert "y" not in model.get_variables()
    assert model.get_variables_by_name("x") == x
    assert id(model.get_variables_by_name("x")) == id(x)
    with pytest.raises(KeyError):
        model.get_variables_by_name("y")

    y = model.variables("y", shape=shape)
    assert len(model.get_variables()) == 2
    assert "x" in model.get_variables()
    assert "y" in model.get_variables()
    assert y.shape == shape
    assert isinstance(y, pyqubo.Array)
    assert model.get_variables_by_name("y") == y
    assert id(model.get_variables()["y"]) == id(y)
Example #18
0
def _create_n_variable_random_complete_model(n=4, seed=None):
    if seed is not None:
        random.seed(seed)

    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(n, ))
    for i in range(n):
        model.add_interaction(x[i], coefficient=random.random())
    for i in range(n - 1):
        for j in range(i + 1, n):
            model.add_interaction((x[i], x[j]), coefficient=random.random())
Example #19
0
def test_logical_model_variables(shape):
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=shape)

    assert len(model.get_variables()) == 1
    assert "x" in model.get_variables()
    assert x.shape == shape
    assert isinstance(x, pyqubo.Array)
    assert model.get_variables_by_name("x") == x
    assert id(model.get_variables_by_name("x")) == id(x)
    assert id(model.get_variables()["x"]) == id(x)
Example #20
0
def test_sawatabi_solver_invalid_reverse_options():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(2,))
    for i in range(2):
        model.add_interaction(x[i], coefficient=-1.0)
    solver = SawatabiSolver()

    with pytest.raises(ValueError):
        solver.solve(model.to_physical(), reverse_options={"reverse_period": 5})

    with pytest.raises(ValueError):
        solver.solve(model.to_physical(), reverse_options={"reverse_temperature": 10.0})
Example #21
0
def test_sawatabi_solver_with_stats():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(2,))
    for i in range(2):
        model.add_interaction(x[i], coefficient=-1.0)
    solver = SawatabiSolver()

    sampleset, stats = solver.solve(model.to_physical(), num_reads=1, num_sweeps=10, cooling_rate=0.5, seed=12345, need_stats=True)

    assert stats[0]["acceptance_history"][-1] == 0
    assert stats[0]["energy_history"][-1] == -2.0
    assert stats[0]["temperature_history"] == [100.0, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625, 0.78125, 0.390625, 0.1953125]
def test_logical_model_empty(mtype):
    model = LogicalModel(mtype=mtype)
    x = model.variables("x", shape=(10, 10))
    model.add_interaction(x[0, 0], coefficient=10.0)

    empty_model = model.empty()
    assert empty_model.get_mtype() == mtype
    assert len(empty_model._variables) == 0
    assert len(empty_model._interactions_array) == len(empty_model._default_keys)
    for k, v in empty_model._interactions_array.items():
        assert len(v) == 0
    assert empty_model._interactions_length == 0
Example #23
0
def test_sawatabi_solver_n_hot_ising_with_deleting(n, s, i):
    # n out of (s - 1) variables should be 1
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(s,))
    model.add_constraint(NHotConstraint(variables=x, n=n))
    model.delete_variable(x[i])

    solver = SawatabiSolver()
    sampleset = solver.solve(model.to_physical(), seed=12345)

    result = np.array(sampleset.record[0].sample)
    assert np.count_nonzero(result == 1) == n
    assert np.count_nonzero(result == -1) == s - n - 1
Example #24
0
def test_sawatabi_solver_reuse_solver_instance():
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(2,))
    for i in range(2):
        model.add_interaction(x[i], coefficient=-1.0)
    solver = SawatabiSolver()

    sampleset_1 = solver.solve(model.to_physical(), num_reads=1, num_sweeps=10, cooling_rate=0.5, seed=12345)
    assert np.array_equal(sampleset_1.record[0].sample, [-1, -1])
    assert sampleset_1.record[0].energy == -2.0

    sampleset_2 = solver.solve(model.to_physical(), num_reads=1, num_sweeps=10, cooling_rate=0.5, seed=12345)
    assert np.array_equal(sampleset_2.record[0].sample, [-1, -1])
    assert sampleset_2.record[0].energy == -2.0
Example #25
0
def test_sawatabi_solver_n_hot_qubo(n, s):
    # n out of s variables should be 1
    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(s,))
    model.add_constraint(NHotConstraint(variables=x, n=n))

    solver = SawatabiSolver()
    sampleset = solver.solve(model.to_physical(), seed=12345)

    result = np.array(sampleset.record[0].sample)
    assert np.count_nonzero(result == 1) == n
    assert np.count_nonzero(result == 0) == s - n

    # Execution time should be within practical seconds (20 sec).
    assert sampleset.info["timing"]["execution_sec"] <= 20.0
def _create_ising_model_for_eq():
    model = LogicalModel(mtype="ising")
    x = model.variables(name="x", shape=(4,))
    z = model.variables(name="z", shape=(4,))
    model.add_interaction(target=x[0], coefficient=1.1)
    model.add_interaction(target=(x[0], x[1]), coefficient=2.2, scale=3.3, attributes={"foo": "bar"})

    model.add_interaction(target=x[2], coefficient=4.4)
    model.add_interaction(target=x[3], coefficient=5.5)
    model.remove_interaction(target=x[2])
    model.fix_variable(target=x[3], value=1)

    model.add_constraint(NHotConstraint(variables=z, n=1))

    return model
Example #27
0
def _create_nxn_random_lattice_model(n=4, seed=None):
    if seed is not None:
        random.seed(seed)

    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(n, n))
    for i in range(n):
        for j in range(n):
            model.add_interaction(x[i, j], coefficient=random.random())
            if 0 < i:
                model.add_interaction((x[i - 1, j], x[i, j]),
                                      coefficient=random.random())
            if 0 < j:
                model.add_interaction((x[i, j - 1], x[i, j]),
                                      coefficient=random.random())
Example #28
0
def test_local_solver_zero_or_one_hot_qubo(n):
    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(n,))
    model.add_constraint(ZeroOrOneHotConstraint(variables=x))

    solver = LocalSolver()
    physical = model.to_physical()
    for seed in [11, 22, 33, 44, 55]:
        sampleset = solver.solve(physical, seed=seed)

        result = np.array(sampleset.record[0].sample)
        assert np.count_nonzero(result == 1) in [0, 1]

        # Execution time should be within practical seconds (20 sec).
        assert sampleset.info["timing"]["execution_sec"] <= 20.0
def test_logical_model_to_physical_with_n_hot_constraint_qubo(n, s):
    # n out of s variables should be 1
    model = LogicalModel(mtype="qubo")
    x = model.variables("x", shape=(s,))
    model.add_constraint(NHotConstraint(x, n=n))
    physical = model.to_physical()

    for i in range(s):
        assert physical._raw_interactions[constants.INTERACTION_LINEAR][f"x[{i}]"] == 2 * n - 1.0
    for i in range(s):
        for j in range(s):
            l1 = f"x[{i}]"
            l2 = f"x[{j}]"
            if l1 < l2:
                assert physical._raw_interactions[constants.INTERACTION_QUADRATIC][(l1, l2)] == -2.0
Example #30
0
def test_local_solver_n_hot_ising(n, s):
    # n out of s spins should be +1
    model = LogicalModel(mtype="ising")
    x = model.variables("x", shape=(s,))
    model.add_constraint(NHotConstraint(variables=x, n=n))

    solver = LocalSolver()
    physical = model.to_physical()
    for seed in [11, 22, 33, 44, 55]:
        sampleset = solver.solve(physical, seed=seed)

        result = np.array(sampleset.record[0].sample)
        assert np.count_nonzero(result == 1) == n
        assert np.count_nonzero(result == -1) == s - n

        # Execution time should be within practical seconds (20 sec).
        assert sampleset.info["timing"]["execution_sec"] <= 20.0