Skip to content

model_maker

qemcmc.model.model_maker

FastIsingEnergy

FastIsingEnergy(h_np, J_np)

Globally accessible callable to calculate energy. Extracting this from ModelMaker allows it to be safely pickled for multiprocessing.

Source code in src/qemcmc/model/model_maker.py
def __init__(self, h_np: np.ndarray, J_np: np.ndarray):
    self.h_np = h_np
    self.J_np = J_np

ModelMaker

ModelMaker(
    n_spins, model_type, name, cost_function_signs=None
)

Utility class for constructing standard Ising energy models used in simulations and experiments.

Source code in src/qemcmc/model/model_maker.py
def __init__(self, n_spins: int, model_type: str, name: str, cost_function_signs: list | None = None):
    self.name = name
    self.n_spins = n_spins
    self.cost_function_signs = cost_function_signs or [-1, -1]

    if not isinstance(model_type, str):
        raise TypeError("model_type must be a string")

    if model_type == "Fully Connected Ising":
        self.make_fully_connected_ising()
    elif model_type == "Fully Connected QUBO":
        self.make_fully_connected_binary()
    else:
        raise ValueError(f"Unknown model_type: {model_type}")

make_fully_connected_binary

make_fully_connected_binary()

Transforms the existing Ising couplings into an mathematically equivalent QUBO model via s = 2x - 1.

Source code in src/qemcmc/model/model_maker.py
def make_fully_connected_binary(self):
    """
    Transforms the existing Ising couplings into an mathematically 
    equivalent QUBO model via s = 2x - 1.
    """
    shape_of_J = (self.n_spins, self.n_spins)
    J_np = np.round(np.random.normal(0, 1, shape_of_J), decimals=4)
    J_np = np.tril(J_np, -1) + np.tril(J_np, -1).transpose()
    h_np = np.round(np.random.normal(0, 1, self.n_spins), decimals=4)

    Q_binary_np = 4 * J_np
    q_binary_np = 2 * h_np - 2 * np.sum(J_np, axis=1)

    q_dict = {(i,): float(np.round(q_binary_np[i], 4)) for i in range(self.n_spins) if q_binary_np[i] != 0}
    Q_dict = {(i, j): float(np.round(Q_binary_np[i, j], 4)) for i in range(self.n_spins) for j in range(i + 1, self.n_spins) if Q_binary_np[i, j] != 0}

    q_binary = dimod.BinaryPolynomial(q_dict, dimod.BINARY)
    Q_binary = dimod.BinaryPolynomial(Q_dict, dimod.BINARY)

    binary_couplings = [q_binary, Q_binary]

    self.model = EnergyModel(
        n=self.n_spins, 
        couplings=binary_couplings, 
        name=self.name, 
        cost_function_signs=[-1, -1],
        model_type="binary"
    )