Skip to content

model

qemcmc.model

ConstraintModel

ConstraintModel(
    n,
    constraint_couplings,
    constraint_signs,
    couplings,
    constraint_func,
    **kwargs
)

Bases: EnergyModel

A subclass of EnergyModel that incorporates a constraint function to define valid configurations.

The constraint function takes a state as input and returns True if the state is valid (satisfies the constraint) and False otherwise. The energy of invalid states is set to infinity, effectively excluding them from the Boltzmann distribution.

Parameters:

Name Type Description Default
n int

Number of spins in the model.

required
constraint_couplings list[BinaryPolynomial]

List of coupling tensors (dimod.BinaryPolynomial) defining the constraint.

required
constraint_signs list[float]

Sign convention(s) for the constraint couplings.

required
couplings list[BinaryPolynomial]

List of coupling tensors (dimod.BinaryPolynomial) defining the energy function.

required
constraint_func Callable[[str], bool]

A function that takes a state (string representation of spin configuration) and returns True if the state satisfies the constraint, and False otherwise.

required
name str

Optional label for the model (used in plotting / logging).

required
cost_function_signs list[float]

Sign convention(s) used by downstream components (e.g. proposal/acceptance conventions).

required
model_type str

Type of model, either 'ising' or 'binary'. This determines how the binary states are interpreted and how the energy is calculated. 'ising' models use spin values {-1, +1}, while 'binary' models use binary values {0, 1}.

required
Notes
  • The energy of any state that does not satisfy the constraint is set to infinity, which means such states will have zero probability in the Boltzmann distribution.
  • This class can be used to model systems with hard constraints on the configurations, such as certain combinatorial optimization problems or physical systems with forbidden states.
Source code in src/qemcmc/model/constraint_model.py
def __init__(self, n: int, constraint_couplings: list[dimod.BinaryPolynomial], constraint_signs: list[float], couplings: list[dimod.BinaryPolynomial | np.ndarray], constraint_func: typing.Callable[[str], bool], **kwargs):
    if not callable(constraint_func):
        raise ValueError("constraint_func must be a callable function that takes a state as input and returns True/False.")
    self.constraint_func = constraint_func

    if type(constraint_couplings) is not list:
        raise TypeError(f"Constraint couplings must be a list of dimod.BinaryPolynomial or numpy arrays, but got a {type(constraint_couplings)}")
    self.constraint_couplings = []
    for item in constraint_couplings:
        if type(item) is not dimod.BinaryPolynomial and type(item) is not np.ndarray:
            raise TypeError(f"Constraint couplings must be a list of dimod.BinaryPolynomial objects or numpy arrays, but got an item in the list of type {type(item)}")
        if type(item) is dimod.BinaryPolynomial:
            self.constraint_couplings.append(item)
        else:
            J_bp = np_to_dimod(item)
            self.constraint_couplings.append(J_bp)

    # This model requires a special way to generate initial states that respect the constraint.
    self.get_initial_states = self.get_initial_states_constraint

    if couplings is not None:
        super().__init__(n=n, couplings=couplings, **kwargs)
    else:
        super().__init__(n=n, couplings=[], **kwargs)

    self.constraint_signs = constraint_signs

    # Calculate normalization factors for constraint couplings
    self.constraint_coupling_alpha = self.calculate_alpha(n, self.constraint_couplings)

    # These are the couplings used in quantum proposals
    # Combine and normalize the energy and constraint couplings
    self.normalised_couplings = (
        [dimod.BinaryPolynomial({k: v * self.alpha for k, v in poly.items()}, poly.vartype) for i, poly in enumerate(self.couplings)]
        +
        [dimod.BinaryPolynomial({k: v * self.constraint_coupling_alpha for k, v in poly.items()}, poly.vartype) for i, poly in enumerate(self.constraint_couplings)]
    )

    # Store the un-normalized total couplings
    self.total_couplings = self.couplings + self.constraint_couplings

get_initial_states_constraint

get_initial_states_constraint(num_initial_states)

Generates a list of random initial states that satisfy the constraint function.

Parameters:

Name Type Description Default
num_initial_states int

The number of initial states to generate.

required

Returns:

Name Type Description
list

A list of random initial states that are valid according to the constraint.

Source code in src/qemcmc/model/constraint_model.py
def get_initial_states_constraint(self, num_initial_states: int):
    """
    Generates a list of random initial states that satisfy the constraint function.

    Parameters
    ----------
    num_initial_states:
        The number of initial states to generate.

    Returns
    -------
    list:
        A list of random initial states that are valid according to the constraint.
    """
    init_states = []
    counter = 0
    max_attempts = 1000
    while len(init_states) < num_initial_states and counter < max_attempts:
        state = get_random_state(self.n_spins)
        if self.constraint_func(state):
            init_states.append(state)
        counter += 1

    if len(init_states) < num_initial_states:
        warnings.warn(
            f"Could not find enough valid initial states satisfying the constraint. "
            f"Found {len(init_states)} valid states after {max_attempts} attempts. "
            f"You may want to provide them manually if more are needed."
        )
    return init_states

get_constraint_energy

get_constraint_energy(state)

Calculate the energy contribution from the constraint couplings for a given state.

Parameters:

Name Type Description Default
state str

The state for which to calculate the constraint energy.

required

Returns:

Name Type Description
float float

The energy contribution from the constraint couplings for the given state.

Source code in src/qemcmc/model/constraint_model.py
def get_constraint_energy(self, state: str) -> float:
    """
    Calculate the energy contribution from the constraint couplings for a given state.

    Parameters
    ----------
    state : str
        The state for which to calculate the constraint energy.

    Returns
    -------
    float:
        The energy contribution from the constraint couplings for the given state.
    """
    return self.calculate_energy(state, self.constraint_couplings, self.constraint_signs)

get_total_energy

get_total_energy(state)

Calculate the total energy of a given state, including both the regular energy and the constraint energy.

Parameters:

Name Type Description Default
state str

The state for which to calculate the total energy.

required

Returns:

Name Type Description
float float

The total energy of the given state, including contributions from both the regular couplings and the constraint couplings.

Source code in src/qemcmc/model/constraint_model.py
def get_total_energy(self, state: str) -> float:
    """
    Calculate the total energy of a given state, including both the regular energy and the constraint energy.

    Parameters
    ----------
    state : str
        The state for which to calculate the total energy.

    Returns
    -------
    float:
        The total energy of the given state, including contributions from both the regular couplings and the constraint couplings.
    """
    return self.get_energy(state) + self.get_constraint_energy(state)

EnergyModel

EnergyModel(
    n,
    couplings=[],
    name=None,
    cost_function_signs=[-1, -1],
    model_type="ising",
    manual_get_energy=None,
)

A base class for energy models for a classical energy function over n spins, defined by dimod.BinaryPolynomial coupling tensors.

Parameters:

Name Type Description Default
n int

Number of spins.

required
couplings list of dimod.BinaryPolynomial or list of np.ndarray

List of dimod.BinaryPolynomial representing interaction tensors.

[]
name str

Optional label for the model (used in plotting / logging).

None
cost_function_signs list of float

Sign convention(s) used by downstream components (e.g. proposal/acceptance conventions). For example, [-1, -1] for linear and quadratic terms.

[-1, -1]
model_type str

Type of model, either 'ising' or 'binary'. This determines how the binary states are interpreted and how the energy is calculated. 'ising' models use spin values {-1, +1}, while 'binary' models use binary values {0, 1}.

'ising'
manual_get_energy callable

Optional custom energy function. If provided, this function will be used to calculate energies instead of the default methods. Must agree on energy values with the default method for a sample of states, otherwise a ValueError is raised.

None
Notes
  • Energies are computed by mapping binary states {0,1} to spin values {-1,+1} internally.
  • Brute-force methods such as get_all_energies scale as O(2^n) and are intended only for small systems.
Source code in src/qemcmc/model/energy_model.py
def __init__(self, n: int, couplings: list[dimod.BinaryPolynomial | np.ndarray] = [], name: str = None, cost_function_signs: list = [-1, -1], model_type: str = "ising", manual_get_energy: callable = None):
    self.n = n
    self.n_spins = n
    self.name = name

    self.lowest_energy = None
    if type(couplings) is not list:
        raise TypeError(f"Couplings must be a list of dimod.BinaryPolynomial or numpy arrays, but got {type(couplings)}")
    self.couplings = []
    for item in couplings:
        if type(item) is not dimod.BinaryPolynomial and type(item) is not np.ndarray:
            raise TypeError(f"Couplings must be a list of dimod.BinaryPolynomial or numpy arrays, but got an item in the list of type {type(item)}")
        if type(item) is dimod.BinaryPolynomial:
            self.couplings.append(item)
        else:
            J_bp = np_to_dimod(item)
            self.couplings.append(J_bp)


    self.alpha = self.calculate_alpha(n, self.couplings)
    self.normalised_couplings = [
        dimod.BinaryPolynomial({k: v * self.alpha for k, v in poly.items()}, poly.vartype)
        for i, poly in enumerate(self.couplings)
    ]
    self.cost_function_signs = cost_function_signs if cost_function_signs is not None else [-1, -1]

    if model_type not in ["ising", "binary"]:
        raise ValueError(f"Invalid model_type '{model_type}'. Expected 'ising' or 'binary'.")
    else:
        self.model_type = model_type

    self.initial_state = self.get_initial_states(num_initial_states=100)



    maximum_order = 0
    for poly in self.couplings:
        order = poly.degree
        if order > maximum_order:
            maximum_order = order
    self.maximum_order = maximum_order






    if manual_get_energy is not None:
        # generate a few bitstrings, and test the manual get_energy against the trusted one.
        test_states = self.get_initial_states(num_initial_states=10)
        for state in test_states:
            exact_energy = self.get_energy(state)
            manual_energy = manual_get_energy(state)
            if not math.isclose(exact_energy, manual_energy, rel_tol=1e-5):
                raise ValueError(f"Manual get_energy does not match exact energy for state {state}. Exact: {exact_energy}, Manual: {manual_energy}. Please check your manual_get_energy function. If this is intended functionality, then you may have to make an alternative EnergyModel class. ")
        self.get_energy = manual_get_energy


    elif self.maximum_order <= 2:
        self.quad_h = np.zeros(self.n_spins, dtype=float)
        self.quad_J = np.zeros((self.n_spins, self.n_spins), dtype=float)
        self.offset = 0.0
        for term_index, poly in enumerate(self.couplings):
            sign = self.cost_function_signs[term_index]
            h, J, offset = poly.to_hising()
            # Linear terms
            for i, bias in h.items():
                self.quad_h[i] += sign * bias
            # Quadratic terms: symmetrize for (state @ quad_J @ state) / 2
            for (i, j), coupling in J.items():
                self.quad_J[i, j] += sign * coupling
                self.quad_J[j, i] += sign * coupling
            # Constant offset
            self.offset += sign * offset


        # generate a few bitstrings, and test the faster get_energy against the trusted one.
        test_states = self.get_initial_states(num_initial_states=10)
        for state in test_states:
            exact_energy = self.get_energy(state)
            manual_energy = self.quadratic_get_energy(state)
            if not math.isclose(exact_energy, manual_energy, rel_tol=1e-5):
                raise ValueError(f"quadratic_get_energy does not match exact energy for state {state}. Exact: {exact_energy}, quadratic_get_energy: {manual_energy}. ")
        self.get_energy = self.quadratic_get_energy

get_energy

get_energy(state)

Returns the energy of a given state.

Parameters:

Name Type Description Default
state str

Binary or spin state string.

required

Returns:

Type Description
float

Energy of the state.

Source code in src/qemcmc/model/energy_model.py
def get_energy(self, state: str) -> float:
    """
    Returns the energy of a given state.

    Parameters
    ----------
    state : str
        Binary or spin state string.

    Returns
    -------
    float
        Energy of the state.
    """
    if not isinstance(state, str):
        raise TypeError(f"State must be a string, but got {type(state)}")
    energy = self.calculate_energy(state, self.couplings, self.cost_function_signs)
    return energy

get_initial_states

get_initial_states(num_initial_states)

Generates a list of random initial states.

Parameters:

Name Type Description Default
num_initial_states int

The number of initial states to generate.

required

Returns:

Type Description
list of str

A list of random initial states.

Source code in src/qemcmc/model/energy_model.py
def get_initial_states(self, num_initial_states: int):
    """
    Generates a list of random initial states.

    Parameters
    ----------
    num_initial_states : int
        The number of initial states to generate.

    Returns
    -------
    list of str
        A list of random initial states.
    """

    init_states = []
    while len(init_states) < num_initial_states:
        state = get_random_state(self.n_spins)
        init_states.append(state)
    return init_states

calculate_energy

calculate_energy(
    state, couplings, cost_function_signs=None
)

Calculate the energy of a given state for an arbitrary-order Ising/binary model.

Parameters:

Name Type Description Default
state str, list, tuple, or np.ndarray

State configuration. Can be: - Binary: "011", [0, 1, 1], (0, 1, 1), etc. - Spin: [-1, 1, 1], (-1, 1, 1), etc.

required
couplings list of dimod.BinaryPolynomial

List of coupling polynomials defining the interaction terms.

required
cost_function_signs list of float

Sign convention applied to each coupling term.

None

Returns:

Type Description
float

Total energy of the state.

Source code in src/qemcmc/model/energy_model.py
def calculate_energy(self, state, couplings: list[dimod.BinaryPolynomial], cost_function_signs: list[float] | None = None) -> float:
    """
    Calculate the energy of a given state for an arbitrary-order Ising/binary model.

    Parameters
    ----------
    state : str, list, tuple, or np.ndarray
        State configuration. Can be:
        - Binary: "011", [0, 1, 1], (0, 1, 1), etc.
        - Spin: [-1, 1, 1], (-1, 1, 1), etc.
    couplings : list of dimod.BinaryPolynomial
        List of coupling polynomials defining the interaction terms.
    cost_function_signs : list of float, optional
        Sign convention applied to each coupling term.

    Returns
    -------
    float
        Total energy of the state.
    """
    if isinstance(state, str):
        state = np.array([int(bit) for bit in state])
    if isinstance(state, (list, tuple, np.ndarray)):
        state = np.array(state)
        if state.dtype == np.bool_:
            state = state.astype(int)
    else:
        raise TypeError(f"State must be a string, list, tuple, or numpy array, but got {type(state)}")

    if self.model_type == "binary":
        # Check if strictly binary using bitwise mask
        if np.any(state & ~1): 
            # Fallback check for strictly spin (-1, 1) using absolute value
            if np.any(np.abs(state) != 1):
                raise ValueError("Spin configuration must be in spin (-1/+1) or binary (0/1) format.")
            # Map Spin -> Binary
            state = (state + 1) >> 1 

    elif self.model_type == "ising":
        # Check if strictly spin
        if np.any(np.abs(state) != 1):
            # Fallback check for strictly binary
            if np.any(state & ~1):
                raise ValueError("Spin configuration must be in binary (0/1) or spin (-1/+1) format.")
            # Map Binary -> Spin (Shift left by 1 is 2*x, minus 1)
            state = (state << 1) - 1

    state_dict = {i: int(val) for i, val in enumerate(state)}
    total_energy = 0.0
    for term_index, poly in enumerate(couplings):
        total_energy += cost_function_signs[term_index] * poly.energy(state_dict)

    return total_energy

get_subgroup_couplings

get_subgroup_couplings(
    subgroup, current_state, coupling_weights=None
)

Calculates local couplings for a subgroup of spins.

Spins outside the specified subgroup are treated as frozen constants, and their values are absorbed into the couplings of the subgroup. This is useful for calculating local effective Hamiltonians.

Parameters:

Name Type Description Default
subgroup list of int

A list of indices of the spins in the subgroup.

required
current_state str

The current state of the full system, as a binary string.

required
coupling_weights list of float

Optional weights for the couplings. This can be used to effectively remove certain couplings from the proposal (e.g., constraints) by setting their weight to 0. It is important not to normalize the couplings after applying these weights.

None

Returns:

Type Description
list of dimod.BinaryPolynomial

A new list of coupling polynomials for the subgroup.

Notes

It might seem off to do the reweighting at this point, but here are reasons why I [SF] did it! Basically, when you get the subgroup couplings, the terms jumble up, so the returned local coupling list necessarily does not respect the order etc. of the different terms in the original.

Source code in src/qemcmc/model/energy_model.py
def get_subgroup_couplings(self, subgroup: list[int], current_state: str, coupling_weights: list[float] = None) -> list[dimod.BinaryPolynomial]:
    """
    Calculates local couplings for a subgroup of spins.

    Spins outside the specified subgroup are treated as frozen constants, and their
    values are absorbed into the couplings of the subgroup. This is useful for
    calculating local effective Hamiltonians.

    Parameters
    ----------
    subgroup : list of int
        A list of indices of the spins in the subgroup.
    current_state : str
        The current state of the full system, as a binary string.
    coupling_weights : list of float, optional
        Optional weights for the couplings. This can be used to effectively
        remove certain couplings from the proposal (e.g., constraints) by setting
        their weight to 0. It is important not to normalize the couplings after
        applying these weights.

    Returns
    -------
    list of dimod.BinaryPolynomial
        A new list of coupling polynomials for the subgroup.

    Notes
    -----
    It might seem off to do the reweighting at this point, but here are reasons why I [SF] did it!
    Basically, when you get the subgroup couplings, the terms jumble up, so the returned local
    coupling list necessarily does not respect the order etc. of the different terms in the original.
    """


    if coupling_weights is None:
        coupling_weights = [1.0] * len(self.normalised_couplings)

    subgroup_set = set(subgroup)
    g_to_l = {g_idx: l_idx for l_idx, g_idx in enumerate(subgroup)}

    if self.model_type == "ising":
        state_vals = {i: 1 if b == "1" else -1 for i, b in enumerate(current_state)}
    else:
        state_vals = {i: int(b) for i, b in enumerate(current_state)}

    new_couplings = []

    for couplings_index, poly in enumerate(self.normalised_couplings):
        weight = coupling_weights[couplings_index]
        new_dict = defaultdict(float)
        for indices, coeff in poly.items():
            effective_coeff = coeff * weight
            in_group = []
            multiplier = 1.0

            for i in indices:
                if i in subgroup_set:
                    in_group.append(g_to_l[i])
                else:
                    multiplier *= state_vals[i]

            effective_coeff *= multiplier

            if in_group:
                local_indices = tuple(sorted(in_group))
                new_dict[local_indices] += effective_coeff
            else:
                new_dict[()] += effective_coeff

        clean_dict = {k: v for k, v in new_dict.items() if v != 0}
        new_couplings.append(dimod.BinaryPolynomial(clean_dict, poly.vartype))

    return new_couplings

calculate_alpha

calculate_alpha(n, couplings=None, eps=1e-15)

Compute alpha = sqrt(n) / sqrt(sum of squares of UNIQUE coupling coefficients), assuming coupling tensors are symmetric representations.

Any non-symmetric 2-body input raises ValueError.

Parameters:

Name Type Description Default
n int

Number of spins.

required
couplings list of dimod.BinaryPolynomial

Couplings to use. Defaults to self.couplings if not provided.

None
eps float

Small threshold to avoid division by zero.

1e-15

Returns:

Type Description
float

Normalisation factor for the couplings.

Source code in src/qemcmc/model/energy_model.py
def calculate_alpha(self, n: int, couplings: list | None = None, eps: float = 1e-15) -> float:
    """
    Compute alpha = sqrt(n) / sqrt(sum of squares of UNIQUE coupling coefficients),
    assuming coupling tensors are symmetric representations.

    Any non-symmetric 2-body input raises ValueError.

    Parameters
    ----------
    n : int
        Number of spins.
    couplings : list of dimod.BinaryPolynomial, optional
        Couplings to use. Defaults to self.couplings if not provided.
    eps : float, optional
        Small threshold to avoid division by zero.

    Returns
    -------
    float
        Normalisation factor for the couplings.
    """
    if couplings is None:
        couplings = self.couplings

    norm_sq_arr = np.zeros(len(couplings))
    for T_ind, poly in enumerate(couplings):
        norm_sq = sum(float(c)**2 for c in poly.values())
        norm_sq_arr[T_ind] = norm_sq

    norm_sq_tot = np.sum(norm_sq_arr)
    if norm_sq_tot < eps:
        print("Warning: Couplings are all zero (or very close to zero). Returning alpha=1 to avoid division by zero.")
        print("Input of a zero-coupling may be intended to sample Uniform distributions, however if this is not your intention, please check your couplings.")
        return 1.0

    return float(np.sqrt(n) / np.sqrt(norm_sq_tot))

get_all_energies

get_all_energies()

Calculate the energies for all possible spin states.

This method generates all possible spin states for the system and calculates the energy for each state.

Returns:

Type Description
ndarray

An array containing the energies of all possible spin states.

Source code in src/qemcmc/model/energy_model.py
def get_all_energies(self) -> np.ndarray:
    """
    Calculate the energies for all possible spin states.

    This method generates all possible spin states for the
    system and calculates the energy for each state.

    Returns
    -------
    np.ndarray
        An array containing the energies of all possible spin states.
    """

    self.S = ["".join(i) for i in itertools.product("01", repeat=self.n)]
    all_energies = np.zeros(len(self.S))
    for state in self.S:
        all_energies[int(state, 2)] = self.calculate_energy(state, self.couplings, self.cost_function_signs)
    return all_energies

get_lowest_energies

get_lowest_energies(
    num_states, return_configurations=False
)

Retrieve the lowest energy states and their degeneracies.

This method computes all possible energies and then finds the specified number of lowest energy states along with their degeneracies.

Parameters:

Name Type Description Default
num_states int

The number of lowest energy states to retrieve.

required
return_configurations bool

Whether to also return the corresponding configurations of the lowest energy states. Defaults to False.

False

Returns:

Name Type Description
lowest_energies ndarray

The lowest energy values.

lowest_energy_degeneracy ndarray

The degeneracies of the corresponding energy values.

lowest_configs (list, optional)

List of configurations corresponding to each energy (only returned if return_configurations=True).

Notes

This method is intended for small instances due to its brute-force nature, which is extremely memory intensive and slow.

Source code in src/qemcmc/model/energy_model.py
def get_lowest_energies(self, num_states: int, return_configurations: bool = False) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, list]:
    """
    Retrieve the lowest energy states and their degeneracies.

    This method computes all possible energies and then finds the specified number
    of lowest energy states along with their degeneracies.

    Parameters
    ----------
    num_states : int
        The number of lowest energy states to retrieve.
    return_configurations : bool, optional
        Whether to also return the corresponding configurations of the lowest energy states. Defaults to False.

    Returns
    -------
    lowest_energies : np.ndarray
        The lowest energy values.
    lowest_energy_degeneracy : np.ndarray
        The degeneracies of the corresponding energy values.
    lowest_configs : list, optional
        List of configurations corresponding to each energy (only returned if return_configurations=True).

    Notes
    -----
    This method is intended for small instances due to its brute-force nature, which is extremely memory intensive and slow.
    """
    all_energies = self.get_all_energies()
    lowest_energies, lowest_energy_degeneracy = self.find_lowest_values(all_energies, num_values=num_states)
    if return_configurations:
        lowest_configs = []
        for energy in lowest_energies:
            configs = [self.S[i] for i, e in enumerate(all_energies) if e == energy]
            lowest_configs.append(configs)
        self.lowest_energy = lowest_energies[0]
        return lowest_energies, lowest_energy_degeneracy, lowest_configs
    else:
        self.lowest_energy = lowest_energies[0]
        return lowest_energies, lowest_energy_degeneracy

find_lowest_values

find_lowest_values(arr, num_values=5)

Find the lowest unique values in an array and their degeneracies.

Parameters:

Name Type Description Default
arr ndarray

The input array from which to find the lowest values.

required
num_values int

The number of lowest unique values to find. Defaults to 5.

5

Returns:

Name Type Description
lowest_values ndarray

The lowest unique values in the array.

degeneracy ndarray

The counts of each of the lowest unique values.

Source code in src/qemcmc/model/energy_model.py
def find_lowest_values(self, arr: np.ndarray, num_values: int = 5):
    """
    Find the lowest unique values in an array and their degeneracies.

    Parameters
    ----------
    arr : np.ndarray
        The input array from which to find the lowest values.
    num_values : int, optional
        The number of lowest unique values to find. Defaults to 5.

    Returns
    -------
    lowest_values : np.ndarray
        The lowest unique values in the array.
    degeneracy : np.ndarray
        The counts of each of the lowest unique values.
    """
    unique_values, counts = np.unique(arr, return_counts=True)
    sorted_indices = np.argsort(unique_values)
    unique_values_sorted = unique_values[sorted_indices]
    counts_sorted = counts[sorted_indices]
    lowest_values = unique_values_sorted[:num_values]
    degeneracy = counts_sorted[:num_values]
    return lowest_values, degeneracy

get_lowest_energy

get_lowest_energy()

Calculate and return the lowest energy from all possible energies.

This method uses a brute force approach to find the lowest energy, making it extremely memory intensive and slow. It is recommended to use this method only for small instances.

Returns:

Type Description
float

The lowest energy value.

Notes

If the lowest energy has already been calculated and stored in self.lowest_energy, it will return that value directly to save computation time.

Source code in src/qemcmc/model/energy_model.py
def get_lowest_energy(self):
    """
    Calculate and return the lowest energy from all possible energies.

    This method uses a brute force approach to find the lowest energy,
    making it extremely memory intensive and slow. It is recommended
    to use this method only for small instances.

    Returns
    -------
    float
        The lowest energy value.

    Notes
    -----
    If the lowest energy has already been calculated and stored
    in `self.lowest_energy`, it will return that value directly
    to save computation time.
    """

    if self.lowest_energy is not None:
        return self.lowest_energy
    else:
        all_energies = self.get_all_energies()

    lowest_energy = np.min(all_energies)
    self.lowest_energy = lowest_energy
    return lowest_energy

get_boltzmann_factor

get_boltzmann_factor(state, beta=1.0)

Get un-normalised boltzmann probability of a given state.

Parameters:

Name Type Description Default
state str

Configuration of spins for which probability is to be calculated.

required
beta float

Inverse temperature (1/T) at which the probability is to be calculated. Defaults to 1.0.

1.0

Returns:

Type Description
float

Un-normalised Boltzmann probability of the given state.

Source code in src/qemcmc/model/energy_model.py
def get_boltzmann_factor(self, state: str, beta: float = 1.0) -> float:
    """
    Get un-normalised boltzmann probability of a given state.

    Parameters
    ----------
    state : str
        Configuration of spins for which probability is to be calculated.
    beta : float, optional
        Inverse temperature (1/T) at which the probability is to be calculated. Defaults to 1.0.

    Returns
    -------
    float
        Un-normalised Boltzmann probability of the given state.
    """

    E = self.get_energy(state)
    boltzmann_factor = np.exp(-1 * beta * E, dtype=np.longdouble)
    return boltzmann_factor

get_boltzmann_factor_from_energy

get_boltzmann_factor_from_energy(E, beta=1.0)

Get un-normalized Boltzmann probability for a given energy.

Parameters:

Name Type Description Default
E float

Energy for which the Boltzmann factor is to be calculated.

required
beta float

Inverse temperature (1/T) at which the probability is to be calculated. Defaults to 1.0.

1.0

Returns:

Type Description
float

The un-normalized Boltzmann probability for the given energy.

Source code in src/qemcmc/model/energy_model.py
def get_boltzmann_factor_from_energy(self, E, beta: float = 1.0) -> float:
    """
    Get un-normalized Boltzmann probability for a given energy.

    Parameters
    ----------
    E : float
        Energy for which the Boltzmann factor is to be calculated.
    beta : float, optional
        Inverse temperature (1/T) at which the probability is to be calculated. Defaults to 1.0.

    Returns
    -------
    float
        The un-normalized Boltzmann probability for the given energy.
    """
    return np.exp(-1 * beta * E, dtype=np.longdouble)

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"
    )