Skip to content

qemcmc

qemcmc

BaseCircuitMaker

BaseCircuitMaker(model)

Constructs and simulates quantum circuits used to generate QeMCMC proposals.

This class builds the Hamiltonian corresponding to a given energy model and simulates its time evolution using PennyLane. Starting from a classical bitstring configuration, the circuit performs Trotterised quantum evolution and samples a new configuration from the resulting quantum state.

The generated sample serves as the proposal state in the quantum-enhanced MCMC algorithm.

Parameters:

Name Type Description Default
model EnergyModel

Energy model defining the problem Hamiltonian.

required
Source code in src/qemcmc/circuits/basecircuitmaker.py
def __init__(self, model: EnergyModel):
    self.model = model
    self.n_qubits = model.n
    self.dev = qml.device("lightning.qubit", wires=self.n_qubits)

    self.model_type = model.model_type
    self.devices = {}  # cache devices for dynamic subgroup sizes if needed

get_problem_hamiltonian

get_problem_hamiltonian(couplings, sign=1)

Construct the problem Hamiltonian from symmetric coupling tensors.

This method supports both 'ising' (-1/+1) and 'binary' (0/1) models.

Parameters:

Name Type Description Default
couplings List[BinaryPolynomial]

A list of coupling polynomials.

required
sign int

A sign to apply to the Hamiltonian. Default is 1.

1

Returns:

Type Description
Hamiltonian

The problem Hamiltonian.

Source code in src/qemcmc/circuits/basecircuitmaker.py
def get_problem_hamiltonian(self, couplings: List[np.ndarray], sign: int = 1) -> qml.Hamiltonian:
    """
    Construct the problem Hamiltonian from symmetric coupling tensors.

    This method supports both 'ising' (-1/+1) and 'binary' (0/1) models.

    Parameters
    ----------
    couplings : List[dimod.BinaryPolynomial]
        A list of coupling polynomials.
    sign : int, optional
        A sign to apply to the Hamiltonian. Default is ``1``.

    Returns
    -------
    qml.Hamiltonian
        The problem Hamiltonian.
    """
    total_hamiltonian = 0.0 * qml.Identity(0)
    for coupling_poly in couplings:
        for indices, coeff in coupling_poly.items():
            if coeff == 0.0:
                continue

            order = len(indices)
            if order == 0:
                continue

            # Ensure strict increasing order to match previous behavior if needed,
            # though dimod already canonicalizes tuples.
            indices = tuple(sorted(indices))

            # Z |0> = |0>, Z |1> = - |1>. 
            # For ising models, bit=0 -> spin=-1, which corresponds to +1 Z eigenvalue. So spin_i = -Z_i.
            # Therefore a term with k spins has a factor of (-1)^k.
            spin_sign = (-1) ** order if self.model_type == "ising" else 1

            if self.model_type == "ising":
                term = qml.PauliZ(indices[0])
                for q in indices[1:]:
                    term = term @ qml.PauliZ(q)
                total_hamiltonian += (sign * spin_sign * coeff) * term

            elif self.model_type == "binary":
                # 0.5 * (I - Z) for first variable
                #term = 0.5 * (qml.Identity(index_tuple[0]) + qml.PauliZ(index_tuple[0]))
                term = 0.5 * (qml.Identity(indices[0]) - qml.PauliZ(indices[0]))
                # multiply by 0.5 * (I - Z) for rest
                for q in indices[1:]:
                    next_var = 0.5 * (qml.Identity(q) - qml.PauliZ(q))
                    #next_var = 0.5 * (qml.Identity(q) + qml.PauliZ(q))
                    term = term @ next_var

                total_hamiltonian += (sign * coeff) * term

    simplified_H = qml.simplify(total_hamiltonian)

    coeffs, ops = simplified_H.terms()
    return qml.Hamiltonian(coeffs, ops)

get_mixer_hamiltonian

get_mixer_hamiltonian(num_wires=None)

Constructs the Mixer Hamiltonian: Σ X_i.

This can be for the full system or a subgroup.

Parameters:

Name Type Description Default
num_wires int

The number of wires (qubits) for the mixer. If None, uses the total number of qubits.

None

Returns:

Type Description
Hamiltonian

The mixer Hamiltonian.

Source code in src/qemcmc/circuits/basecircuitmaker.py
def get_mixer_hamiltonian(self, num_wires: int | None = None) -> qml.Hamiltonian:
    """
    Constructs the Mixer Hamiltonian: Σ X_i.

    This can be for the full system or a subgroup.

    Parameters
    ----------
    num_wires : int, optional
        The number of wires (qubits) for the mixer. If None, uses the total number of qubits.

    Returns
    -------
    qml.Hamiltonian
        The mixer Hamiltonian.
    """
    if num_wires is None:
        num_wires = self.n_qubits
    return qml.Hamiltonian([1.0] * num_wires, [qml.PauliX(i) for i in range(num_wires)])

check_Hamiltonian

check_Hamiltonian(
    basis_states_ints=None, couplings=None, plot=False
)

Utility function to print the Energy of the Hamiltonian to be simulated. Naturally, for a classical problem, the energy of the Hamiltonian wrt to some basis state b H|b> = E|b> should equal the energy of the corresponding state in the classical model. This is a useful sanity check to ensure that the Hamiltonian is being constructed correctly from the coupling tensors.

Source code in src/qemcmc/circuits/basecircuitmaker.py
def check_Hamiltonian(self, basis_states_ints: list[str] | None = None, couplings: list[np.ndarray] | None = None, plot=False) -> None:
    """
    Utility function to print the Energy of the Hamiltonian to be simulated. Naturally, for a classical problem, the energy of the Hamiltonian wrt to some basis state b H|b> = E|b> should equal the energy of the corresponding state in the classical model. This is a useful sanity check to ensure that the Hamiltonian is being constructed correctly from the coupling tensors.


    """

    # Get hamiltonian (not normalised)
    Hamiltonian = self.get_problem_hamiltonian(couplings)
    energies = []
    quantum_energies = []
    # Evaluate the Hamiltonian on some randomly chosen bitstring states, and compare to the classical energy of those states in the model
    for state in basis_states_ints:
        print("state int: ", state)
        state = bin(state)[2:].zfill(self.n_qubits)
        classical_energy = self.model.get_energy(state)

        dev = qml.device("lightning.qubit", wires=self.n_qubits)

        @qml.qnode(dev)
        def evaluate_energy(basis_state):
            # Prepares the state |1, 0> if basis_state=[1, 0]
            # print(basis_state)
            # print(len(bin(state)[2:].zfill(self.n_qubits)))
            # qml.BasisState(, wires=range(self.n_qubits))

            for i, bit in enumerate(basis_state):
                if bit == "1":
                    qml.PauliX(i)
            return qml.expval(Hamiltonian)

        quantum_energy = evaluate_energy(state)

        if type(self.model) is ConstraintModel:
            constraint_energy = self.model.get_constraint_energy(state)
            print(
                f"State: {state}, Classical Energy: {np.round(classical_energy, 2)}, Quantum Hamiltonian Energy: {np.round(quantum_energy, 2)}, Constraint energu {np.round(constraint_energy, 2)},Constraint Satisfaction: {self.model.constraint_func(state)}"
            )
        else:
            print(f"State: {state}, Classical Energy: {np.round(classical_energy, 2)}, Quantum Hamiltonian Energy: {np.round(quantum_energy, 2)}")
        energies.append(classical_energy)
        quantum_energies.append(quantum_energy)
    if plot:
        plt.scatter(energies, quantum_energies)
        plt.xlabel("Classical Energy")
        plt.ylabel("Quantum Energy")
        plt.show()
        plt.plot(np.arange(0, 2**self.n_qubits), np.array(energies), label="classical")
        plt.plot(np.arange(0, 2**self.n_qubits), np.array(quantum_energies), label="quantum")
        plt.show()

QuenchCircuitMaker

QuenchCircuitMaker(model)

Bases: BaseCircuitMaker

The total Hamiltonian simulated by the circuit is

``H = γ H_mixer + (1 - γ) α H_problem``

where H_problem encodes the classical energy model and H_mixer corresponds to a transverse-field term. The evolution time t and number of Trotter steps r are passed per call, giving an effective Trotter step size of δt = t / r. The evolution is approximated using Trotterisation via qml.ApproxTimeEvolution.

Source code in src/qemcmc/circuits/quenchcircuitmaker.py
def __init__(self, model: EnergyModel):
    super().__init__(model)
    self.method = "quench_quantum"

get_state_vector

get_state_vector(s, weights, time, r, mix_weight)

Evolve the initial state and return the final state vector.

Parameters:

Name Type Description Default
s str

Input bitstring representing the initial state.

required
weights list of float

Coefficients for the problem Hamiltonian terms.

required
time float

Total evolution time.

required
r int

Number of Trotter steps for the approximate time evolution.

required
mix_weight float

Coefficient for the mixer Hamiltonian.

required

Returns:

Type Description
ndarray

The final state vector.

Notes

The total Hamiltonian simulated by the circuit is a weighted sum of the problem Hamiltonian terms and the mixer Hamiltonian:

In Ferguson et al. (2025) [arXiv:2506.19538], we use gammas to weight the entire problem Hamiltonian vs the mixer vs the constraint Hamiltonian, such that the total Hamiltonian is:

H = g_p * H_p + g_m * H_m + g_c * H_c

but here we allow for separate weights for each coupling tensor term, as well as a separate gamma for the mixer. The total Hamiltonian is then:

H = (w_b1*H_b1 + w_b2*H_b2 + ... + w_b2*H_bm) + g_m * H_m

In other words, the constraint hamiltonian is absorbed in the coupling list, and weighted by the corresponding gamma in the gammas list. This allows for more flexible weighting of different terms, and also allows us to use the same code for both constrained and unconstrained problems (by simply including or excluding the constraint Hamiltonian in the coupling list and adjusting the gammas accordingly).

Note that it is assumed that each term is already normalised appropriately, so the gammas can be interpreted as the relative weights of each term in the total Hamiltonian.

Source code in src/qemcmc/circuits/quenchcircuitmaker.py
def get_state_vector(self, s: str, weights: list[float], time: float, r: int, mix_weight: float) -> np.ndarray:
    """
    Evolve the initial state and return the final state vector.

    Parameters
    ----------
    s : str
        Input bitstring representing the initial state.
    weights : list of float
        Coefficients for the problem Hamiltonian terms.
    time : float
        Total evolution time.
    r : int
        Number of Trotter steps for the approximate time evolution.
    mix_weight : float
        Coefficient for the mixer Hamiltonian.

    Returns
    -------
    np.ndarray
        The final state vector.


    Notes
    -----
    The total Hamiltonian simulated by the circuit is a weighted sum of the problem Hamiltonian terms and the mixer Hamiltonian:

    In Ferguson et al. (2025) [arXiv:2506.19538], we use gammas to weight the entire problem Hamiltonian vs the mixer vs the constraint Hamiltonian, such that the total Hamiltonian is:

    ``H = g_p * H_p + g_m * H_m + g_c * H_c``

    but here we allow for separate weights for each coupling tensor term, as well as a separate gamma for the mixer. The total Hamiltonian is then:

    ``H = (w_b1*H_b1 + w_b2*H_b2 + ... + w_b2*H_bm) + g_m * H_m``

    In other words, the constraint hamiltonian is absorbed in the coupling list, and weighted by the corresponding gamma in the gammas list.
    This allows for more flexible weighting of different terms, and also allows us to use the same code for both constrained and unconstrained problems (by simply including or excluding the constraint Hamiltonian in the coupling list and adjusting the gammas accordingly).

    Note that it is assumed that each term is already normalised appropriately, so the gammas can be interpreted as the relative weights of each term in the total Hamiltonian.

    """

    num_wires = len(s)
    dev = self._get_device(num_wires)

    # if mix_weight < 0 or mix_weight > 1:
    #    raise ValueError(f"mix_weight must be between 0 and 1. Got {mix_weight}")

    # if np.any(np.array(weights) < 0):
    #    raise ValueError(f"Weights must be non-negative. Got {weights}")

    coeff_mixer = mix_weight
    coeff_problem = weights

    H_total = qml.Hamiltonian(
        [coeff_mixer] + list(np.ones(len(self.model.normalised_couplings))),
        [self.get_mixer_hamiltonian(num_wires)]
        + [self.get_problem_hamiltonian(couplings=[self.model.normalised_couplings[i]], sign=coeff_problem[i]) for i in range(len(self.model.normalised_couplings))],
    )

    @qml.qnode(dev)
    def quantum_evolution(input_string):
        for i, bit in enumerate(input_string):
            if bit == "1":
                qml.PauliX(i)
        qml.ApproxTimeEvolution(H_total, time, r)
        return qml.state()

    state_vector = quantum_evolution(s)
    return state_vector

get_sample

get_sample(
    s_cg, time, r, mix_weight, local_couplings, weights=None
)

Generate a single sample by evolving the system and measuring.

Parameters:

Name Type Description Default
s_cg str

Input bitstring for the subgroup.

required
time float

Total evolution time.

required
r int

Number of Trotter steps for the approximate time evolution.

required
mix_weight float

Coefficient for the mixer Hamiltonian.

required
local_couplings list

Coupling tensors for the subgroup.

required
weights list of float

Coefficients for the problem Hamiltonian terms. Defaults to ones.

None

Returns:

Type Description
str

A single bitstring sample.

Source code in src/qemcmc/circuits/quenchcircuitmaker.py
def get_sample(self, s_cg: str, time: float, r: int, mix_weight: float, local_couplings: list, weights: list[float] | None = None) -> str:
    """
    Generate a single sample by evolving the system and measuring.

    Parameters
    ----------
    s_cg : str
        Input bitstring for the subgroup.
    time : float
        Total evolution time.
    r : int
        Number of Trotter steps for the approximate time evolution.
    mix_weight : float
        Coefficient for the mixer Hamiltonian.
    local_couplings : list
        Coupling tensors for the subgroup.
    weights : list of float, optional
        Coefficients for the problem Hamiltonian terms. Defaults to ones.

    Returns
    -------
    str
        A single bitstring sample.
    """
    if weights is None:
        weights = np.ones(len(local_couplings))

    num_wires = len(s_cg)
    dev = self._get_device(num_wires)

    # if mix_weight < 0 or mix_weight > 1:
    #    raise ValueError(f"mix_weight must be between 0 and 1. Got {mix_weight}")

    # if np.any(np.array(weights) < 0):
    #    raise ValueError(f"Weights must be non-negative. Got {weights}")

    coeff_mixer = mix_weight
    coeff_problem = weights

    # coeff_problem = [coeff for i, coeff in enumerate(coeff_problem) if local_couplings[i].ndim > 0 and np.any(local_couplings[i] != 0)]
    # local_couplings = [coupling for coupling in local_couplings if coupling.ndim > 0 and np.any(coupling != 0)]
    if len(local_couplings) == 0:
        # If there are no local couplings, just return the input state
        print("no non-zero local couplings, skipping evolution and returning input state")
        return s_cg

    H_total = qml.Hamiltonian(
        [coeff_mixer] + list(np.ones(len(local_couplings))),
        [self.get_mixer_hamiltonian(num_wires)] + [self.get_problem_hamiltonian(couplings=[local_couplings[i]], sign=coeff_problem[i]) for i in range(len(local_couplings))],
    )

    # set qnode to use our device with dynamically chosen wires
    @qml.qnode(dev, shots=1)
    def quantum_evolution(input_string):
        for i, bit in enumerate(input_string):
            if bit == "1":
                qml.PauliX(i)
        qml.ApproxTimeEvolution(H_total, time, r)
        return qml.sample()

    """print(f"Simulating quantum circuit with {num_wires} qubits, time={time}, num_trotter_steps={num_trotter_steps}")
    compiled_circuit = qml.compile(quantum_evolution)

    specs_dict = qml.specs(compiled_circuit)(s_cg)
    specs_dict = specs_dict['resources']
    # 3. Print the relevant metrics
    print(f"Circuit Depth: {specs_dict['depth']}")
    print(f"Total Gates:   {specs_dict['num_gates']}")

    # To see the count of two-qubit gates specifically:
    two_qubit_gates = specs_dict['gate_sizes'].get(2, 0)
    print(f"Two-qubit Gates: {two_qubit_gates}")

    # To see the breakdown by gate type (e.g., CNOT, RZ, etc.)
    print("\nGate Breakdown:")
    for gate, count in specs_dict['gate_types'].items():
        print(f"- {gate}: {count}")"""

    # This is slow!
    # Get the first shot from the sample
    # compiled_circuit = qml.compile(quantum_evolution)
    # sample = compiled_circuit(s_cg)[0]

    sample = quantum_evolution(s_cg)[0]
    bitstring = "".join(str(int(b)) for b in sample)
    return bitstring

update

update(s, subgroup_choice, local_couplings, gamma, time, r)

Update a bitstring by evolving a subgroup.

This performs a time evolution on a coarse-grained Hamiltonian to get s' from s.

Parameters:

Name Type Description Default
s str

The initial bitstring.

required
subgroup_choice list of int

Indices of the subgroup to evolve.

required
local_couplings list

Coupling tensors for the subgroup.

required
gamma float

Mixing parameter.

required
time float

Evolution time.

required
r int

Number of Trotter steps for the approximate time evolution.

required

Returns:

Type Description
str

The updated bitstring s'.

Source code in src/qemcmc/circuits/quenchcircuitmaker.py
def update(self, s: str, subgroup_choice: list[int], local_couplings: list, gamma: float, time: float, r: int) -> str:
    """
    Update a bitstring by evolving a subgroup.

    This performs a time evolution on a coarse-grained Hamiltonian to get s' from s.

    Parameters
    ----------
    s : str
        The initial bitstring.
    subgroup_choice : list of int
        Indices of the subgroup to evolve.
    local_couplings : list
        Coupling tensors for the subgroup.
    gamma : float
        Mixing parameter.
    time : float
        Evolution time.
    r : int
        Number of Trotter steps for the approximate time evolution.

    Returns
    -------
    str
        The updated bitstring s'.
    """

    self._validate_bitstring(s)
    # Get s_cg' for the subgroup and reconstruct full s' using s and s_cg'
    s_cg = "".join([s[i] for i in subgroup_choice])
    s_cg_prime = self.get_sample(s_cg, time, r, gamma, local_couplings)
    s_list = list(s)
    for i, global_index in enumerate(subgroup_choice):
        s_list[global_index] = s_cg_prime[i]
    return "".join(s_list)

AdiabaticCircuitMaker

AdiabaticCircuitMaker(model)

Bases: BaseCircuitMaker

Constructs and simulates adiabatic quantum circuits for QeMCMC proposals.

The total time-dependent Hamiltonian simulated by the circuit is:

``H(t) = h(t) * mix_weight * H_mixer + H_problem``

where H_problem encodes the classical energy model and H_mixer corresponds to a transverse-field term. The dimensionless schedule function h(t) ramps linearly from 0 to 1 over ramp duration alpha, remains at 1 for plateau duration kappa, and ramps down from 1 to 0 over duration alpha (total duration 2 * alpha + kappa).

The time-dependent evolution is approximated using second-order Trotterisation via qml.ApproxTimeEvolution over r = max(1, round((2 * alpha + kappa) / dt)) steps.

Parameters:

Name Type Description Default
model EnergyModel

Energy model defining the target Boltzmann distribution.

required
Source code in src/qemcmc/circuits/adiabaticcircuitmaker.py
def __init__(self, model: EnergyModel):
    super().__init__(model)
    self.method = "adiabatic_quantum"

get_sample

get_sample(
    s_cg,
    alpha,
    kappa,
    mix_weight,
    local_couplings,
    weights=None,
    dt=0.3,
)

Generate a single sample by evolving the system under a time-dependent Hamiltonian and measuring.

Parameters:

Name Type Description Default
s_cg str

Input bitstring for the subgroup.

required
alpha float

Duration of the adiabatic ramp.

required
kappa float

Duration of the plateau.

required
mix_weight float

Coefficient for the mixer Hamiltonian.

required
local_couplings list

Coupling tensors for the subgroup.

required
weights list of float

Coefficients for the problem Hamiltonian terms. Defaults to ones.

None
dt float

Timestep size for second order Trotter evolution. Defaults to 0.3.

0.3

Returns:

Type Description
str

A single bitstring sample.

Source code in src/qemcmc/circuits/adiabaticcircuitmaker.py
def get_sample(
    self,
    s_cg: str,
    alpha: float,
    kappa: float,
    mix_weight: float,
    local_couplings: list,
    weights: list[float] | None = None,
    dt: float = 0.3,
) -> str:
    """
    Generate a single sample by evolving the system under a time-dependent Hamiltonian and measuring.

    Parameters
    ----------
    s_cg : str
        Input bitstring for the subgroup.
    alpha : float
        Duration of the adiabatic ramp.
    kappa : float
        Duration of the plateau.
    mix_weight : float
        Coefficient for the mixer Hamiltonian.
    local_couplings : list
        Coupling tensors for the subgroup.
    weights : list of float, optional
        Coefficients for the problem Hamiltonian terms. Defaults to ones.
    dt : float, optional
        Timestep size for second order Trotter evolution. Defaults to 0.3.

    Returns
    -------
    str
        A single bitstring sample.
    """
    if weights is None:
        weights = np.ones(len(local_couplings))

    num_wires = len(s_cg)
    dev = self._get_device(num_wires)

    coeff_mixer = mix_weight
    coeff_problem = weights

    if len(local_couplings) == 0:
        # If there are no local couplings, just return the input state
        print("no non-zero local couplings, skipping evolution and returning input state")
        return s_cg

    H_m = self.get_mixer_hamiltonian(num_wires)
    H_p = [
        self.get_problem_hamiltonian(couplings=[local_couplings[i]], sign=coeff_problem[i])
        for i in range(len(local_couplings))
    ]

    r = max(1, int(round((alpha * 2 + kappa) / dt)))

    @qml.qnode(dev, shots=1)
    def quantum_evolution(input_string):
        # state prep
        for i, bit in enumerate(input_string):
            if bit == "1":
                qml.PauliX(i)

        # manually slice up evolution
        for step in range(r):
            # choose midpoint
            t_mid = (step + 0.5) * dt

            # Find instantaneous Hamiltonian
            h = self.linear_schedule(t_mid, alpha, kappa)
            H_step = qml.Hamiltonian(
                [h * coeff_mixer] + list(np.ones(len(local_couplings))),
                [H_m] + H_p,
            )

            # compute step
            qml.ApproxTimeEvolution(H_step, dt, 2)

        return qml.sample()

    sample = quantum_evolution(s_cg)[0]
    bitstring = "".join(str(int(b)) for b in sample)
    return bitstring

linear_schedule

linear_schedule(t, alpha, kappa)

Calculates the linear ramp factor h(t) with a plateau of duration kappa and ramp duration alpha.

The schedule satisfies h(t): 0 -> 1 -> 1 -> 0 as t: 0 -> alpha -> alpha + kappa -> 2 * alpha + kappa.

Parameters:

Name Type Description Default
t float

Current time during the evolution.

required
alpha float

Duration of the linear ramp.

required
kappa float

Duration of the constant plateau.

required

Returns:

Type Description
float

The instantaneous mixer weight factor in [0, 1].

Source code in src/qemcmc/circuits/adiabaticcircuitmaker.py
def linear_schedule(self, t: float, alpha: float, kappa: float) -> float:
    """
    Calculates the linear ramp factor h(t) with a plateau of duration kappa and ramp duration alpha.

    The schedule satisfies h(t): 0 -> 1 -> 1 -> 0 as
    t: 0 -> alpha -> alpha + kappa -> 2 * alpha + kappa.

    Parameters
    ----------
    t : float
        Current time during the evolution.
    alpha : float
        Duration of the linear ramp.
    kappa : float
        Duration of the constant plateau.

    Returns
    -------
    float
        The instantaneous mixer weight factor in [0, 1].
    """
    total_time = alpha * 2

    if total_time == 0:
        return 1.0
    elif t <= 0:
        return 0.0
    elif t <= alpha:
        return t / alpha
    elif t <= alpha + kappa:
        return 1.0
    elif t < total_time + kappa:
        return (total_time + kappa - t) / alpha
    else:
        return 0.0

get_state_vector

get_state_vector(
    s_cg, alpha, kappa, mix_weight, weights=None, dt=0.3
)

Evolve the initial state under the adiabatic Hamiltonian and return the final state vector.

Parameters:

Name Type Description Default
s_cg str

Input bitstring for the subgroup.

required
alpha float

Duration of the adiabatic ramp.

required
kappa float

Duration of the plateau.

required
mix_weight float

Coefficient for the mixer Hamiltonian.

required
weights list of float

Coefficients for the problem Hamiltonian terms. Defaults to ones.

None
dt float

Timestep size for second order Trotter evolution. Defaults to 0.3.

0.3

Returns:

Type Description
ndarray

The final quantum state vector.

Source code in src/qemcmc/circuits/adiabaticcircuitmaker.py
def get_state_vector(
    self,
    s_cg: str,
    alpha: float,
    kappa: float,
    mix_weight: float,
    weights: list[float] | None = None,
    dt: float = 0.3,
) -> np.ndarray:
    """
    Evolve the initial state under the adiabatic Hamiltonian and return the final state vector.

    Parameters
    ----------
    s_cg : str
        Input bitstring for the subgroup.
    alpha : float
        Duration of the adiabatic ramp.
    kappa : float
        Duration of the plateau.
    mix_weight : float
        Coefficient for the mixer Hamiltonian.
    weights : list of float, optional
        Coefficients for the problem Hamiltonian terms. Defaults to ones.
    dt : float, optional
        Timestep size for second order Trotter evolution. Defaults to 0.3.

    Returns
    -------
    np.ndarray
        The final quantum state vector.
    """
    local_couplings = self.model.normalised_couplings

    if weights is None:
        weights = np.ones(len(local_couplings))

    num_wires = len(s_cg)
    dev = self._get_device(num_wires)

    coeff_mixer = mix_weight
    coeff_problem = weights

    if len(local_couplings) == 0:
        # If there are no local couplings, just return the input state
        print("no non-zero local couplings, skipping evolution and returning input state")
        return s_cg

    H_m = self.get_mixer_hamiltonian(num_wires)
    H_p = [
        self.get_problem_hamiltonian(couplings=[local_couplings[i]], sign=coeff_problem[i])
        for i in range(len(local_couplings))
    ]

    r = max(1, int(round((alpha * 2 + kappa) / dt)))

    @qml.qnode(dev)
    def quantum_evolution(input_string):
        # state prep
        for i, bit in enumerate(input_string):
            if bit == "1":
                qml.PauliX(i)

        # manually slice up evolution
        for step in range(r):
            # choose midpoint
            t_mid = (step + 0.5) * dt

            # Find instantaneous Hamiltonian
            h = self.linear_schedule(t_mid, alpha, kappa)
            H_step = qml.Hamiltonian(
                [h * coeff_mixer] + list(np.ones(len(local_couplings))),
                [H_m] + H_p,
            )

            # compute step
            qml.ApproxTimeEvolution(H_step, dt, 2)

        return qml.state()

    state_vector = quantum_evolution(s_cg)
    return state_vector

update

update(
    s,
    subgroup_choice,
    local_couplings,
    gamma,
    alpha,
    kappa,
    dt=0.3,
)

Update a bitstring by evolving a subgroup.

This performs a time evolution on a coarse-grained Hamiltonian to get s' from s.

Parameters:

Name Type Description Default
s str

The initial bitstring.

required
subgroup_choice list of int

Indices of the subgroup to evolve.

required
local_couplings list

Coupling tensors for the subgroup.

required
gamma float

Mixing parameter.

required
alpha float

Adiabatic ramp time.

required
kappa float

Plateau time.

required
dt float

Trotter step size for the approximate time evolution. Defaults to 0.3.

0.3

Returns:

Type Description
str

The updated bitstring s'.

Source code in src/qemcmc/circuits/adiabaticcircuitmaker.py
def update(
    self,
    s: str,
    subgroup_choice: list[int],
    local_couplings: list,
    gamma: float,
    alpha: float,
    kappa: float,
    dt: float = 0.3,
) -> str:
    """
    Update a bitstring by evolving a subgroup.

    This performs a time evolution on a coarse-grained Hamiltonian to get s' from s.

    Parameters
    ----------
    s : str
        The initial bitstring.
    subgroup_choice : list of int
        Indices of the subgroup to evolve.
    local_couplings : list
        Coupling tensors for the subgroup.
    gamma : float
        Mixing parameter.
    alpha : float
        Adiabatic ramp time.
    kappa : float
        Plateau time.
    dt : float, optional
        Trotter step size for the approximate time evolution. Defaults to 0.3.

    Returns
    -------
    str
        The updated bitstring s'.
    """
    self._validate_bitstring(s)
    # Get s_cg' for the subgroup and reconstruct full s' using s and s_cg'
    s_cg = "".join([s[i] for i in subgroup_choice])
    s_cg_prime = self.get_sample(s_cg, alpha, kappa, gamma, local_couplings, dt=dt)
    s_list = list(s)
    for i, global_index in enumerate(subgroup_choice):
        s_list[global_index] = s_cg_prime[i]
    return "".join(s_list)

CoarseGraining

CoarseGraining(
    n,
    subgroups=None,
    subgroup_probs=None,
    repeated=True,
    m=1,
)

CoarseGraining class to generate partitions of spins for quantum proposals.

Parameters:

Name Type Description Default
n int

Number of spins in the system.

required
subgroups list[list[int]]

A list of subgroups, where each subgroup is a list of spin indices. If None, the entire set of spins is treated as one subgroup.

None
subgroup_probs list[float]

A list of probabilities corresponding to each subgroup, used for weighted random selection. Must sum to 1. If None, subgroups are selected uniformly at random.

None
repeated bool

If True, then multiple subgroups are run on the quantum computer in serial, if not then only one subgroup is selected at random and run on the quantum computer. Default is True.

True
m int

The number of partitions to generate. Ignored if user-specified subgroups are provided.

1
Source code in src/qemcmc/coarse_grain.py
def __init__(self, n, subgroups=None, subgroup_probs=None, repeated=True, m: int = 1):

    if not isinstance(m, int):
        raise TypeError("m must be an integer.")

    self._user_specified = subgroups is not None



    if subgroups is not None:
        if subgroup_probs is None:
            subgroup_probs = [1.0 / len(subgroups)] * len(subgroups)
        if m is not None:
            print("Cannot provide m and subgroups for course graining. Ignoring m")
    if self._user_specified:
        validate_subgroups(subgroups=subgroups, subgroup_probs=subgroup_probs, n_spins=n)

    self.m = m
    self.n = n
    self.subgroups = subgroups
    self.subgroup_probs = subgroup_probs
    self.repeated = repeated

    if self.repeated and self._user_specified:
        if not np.all([len(s) == len(subgroups[0]) for s in subgroups]):
            raise NotImplementedError("If providing own subgroups, repeated must be set to False as it is not obvious how one performs repeated coarse-graining without knowledge of the subgroups. If length, l, of each subrgoup is equal, we continue assuming l = n//m.")
        else:
            print("Provided subgroups are all of same length, so repeated coarse-graining will be performed accross a random choice of subgroups. This means that the same variables may be chosen multiple times within the same proposal.")

sample

sample()

Randomly samples a subgroup according to the specified probability distribution.

Source code in src/qemcmc/coarse_grain.py
def sample(self) -> list[int]:
    """
    Randomly samples a subgroup according to the specified probability distribution.
    """
    idx = np.random.choice(len(self.subgroups), p=self.subgroup_probs)
    return self.subgroups[idx]

get_partitions

get_partitions()

Returns partitions of spins for sequential quantum updates.

If the user provided explicit subgroups at initialisation, those are sampled accordingly. returned directly (all if repeated=True, otherwise just the first). If no subgroups were specified, random disjoint partitions of approximate size n/m are generated.

Source code in src/qemcmc/coarse_grain.py
def get_partitions(self) -> list[list[int]]:
    """
    Returns partitions of spins for sequential quantum updates.

    If the user provided explicit subgroups at initialisation, those are sampled accordingly.
    returned directly (all if ``repeated=True``, otherwise just the first).
    If no subgroups were specified, random disjoint partitions of
    approximate size n/m are generated.


    """

    if self._user_specified:

        if self.repeated:
            number_of_subgroups_that_fit = self.n//np.max([len(sg) for sg in self.subgroups])

            choices = np.random.choice(np.arange(0,len(self.subgroups)), size = number_of_subgroups_that_fit, p = self.subgroup_probs, replace=False)

            chosen_subgroups = []
            for choice in choices:
                chosen_subgroups.append(self.subgroups[choice])
            return chosen_subgroups
        else:
            chosen_subgroup = np.random.choice(self.subgroups, p=self.subgroup_probs)

            return [chosen_subgroup]
    else:
        spins = np.arange(self.n)
        np.random.shuffle(spins)
        # array_split handles uneven divisions gracefully
        chunks = [list(chunk) for chunk in np.array_split(spins,self.m)]
        if self.repeated:
            return chunks
        else:
            return [chunks[0]]

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

ClassicalProposal

ClassicalProposal(model, method='uniform')

Bases: Proposal

Classical Markov Chain Monte Carlo proposer.

This class implements purely classical proposal mechanisms for MCMC. New candidate states are generated either by sampling a completely random (uniform) configuration, or by performing a local single-spin or two-spin flip.

Parameters:

Name Type Description Default
model EnergyModel

Energy model defining the target Boltzmann distribution.

required
method str

Proposal mechanism used to generate candidate states.

  • "uniform" : propose a completely random spin configuration.
  • "local" : flip a single randomly chosen spin.
  • "2-local" : flip two randomly chosen spins.

Default is "uniform".

'uniform'
Source code in src/qemcmc/sampler/classical_proposal.py
def __init__(self, model: EnergyModel, method: str = "uniform"):
    if method not in self.METHODS:
        raise ValueError(f"Method '{method}' is not supported. Choose from 'uniform', 'local', or '2-local'.")
    super().__init__(model)
    self.method = method

update_uniform

update_uniform(current_state_bitstring)

Proposes a new state by generating a random bitstring.

Parameters:

Name Type Description Default
current_state_bitstring str

The current state represented as a bitstring (not used, but required by the API).

required

Returns:

Type Description
str

A new random state bitstring of the same length.

Source code in src/qemcmc/sampler/classical_proposal.py
def update_uniform(self, current_state_bitstring: str) -> str:
    """
    Proposes a new state by generating a random bitstring.

    Parameters
    ----------
    current_state_bitstring : str
        The current state represented as a bitstring (not used, but required by the API).

    Returns
    -------
    str
        A new random state bitstring of the same length.
    """

    return get_random_state(len(current_state_bitstring))

update_local

update_local(current_state_bitstring)

Proposes a new state by flipping a single randomly chosen spin.

Parameters:

Name Type Description Default
current_state_bitstring str

The current state represented as a bitstring.

required

Returns:

Type Description
str

The new state bitstring after flipping one spin.

Source code in src/qemcmc/sampler/classical_proposal.py
def update_local(self, current_state_bitstring: str) -> str:
    """
    Proposes a new state by flipping a single randomly chosen spin.

    Parameters
    ----------
    current_state_bitstring : str
        The current state represented as a bitstring.

    Returns
    -------
    str
        The new state bitstring after flipping one spin.
    """

    # Randomly choose which spin to flip
    choice = np.random.randint(0, self.n_spins)

    # Flip the chosen spin
    c_s = list(current_state_bitstring)
    c_s[choice] = str(int(c_s[choice]) ^ 1)

    # Return the new state as a bitstring
    return "".join(c_s)

update_2local

update_2local(current_state_bitstring)

Proposes a new state by flipping two randomly chosen spins.

Parameters:

Name Type Description Default
current_state_bitstring str

The current state represented as a bitstring.

required

Returns:

Type Description
str

The new state bitstring after flipping two spins.

Source code in src/qemcmc/sampler/classical_proposal.py
def update_2local(self, current_state_bitstring: str) -> str:
    """
    Proposes a new state by flipping two randomly chosen spins.

    Parameters
    ----------
    current_state_bitstring : str
        The current state represented as a bitstring.

    Returns
    -------
    str
        The new state bitstring after flipping two spins.
    """
    # Randomly choose which two spins to flip
    choices = np.random.choice(self.n_spins, size=2, replace=False)

    # Flip the chosen spins
    c_s = list(current_state_bitstring)
    for choice in choices:
        c_s[choice] = str(int(c_s[choice]) ^ 1)

    # Return the new state as a bitstring
    return "".join(c_s)

Proposal

Proposal(model)

Bases: ABC

Abstract base class for producing proposals for Markov Chain Monte Carlo algorithms.

Subclasses implement the proposal mechanism by defining an update(state) method that generates a candidate state from the current one (e.g. single-spin flips, block updates, or quantum proposals).

Parameters:

Name Type Description Default
model EnergyModel

Energy model defining the target distribution over spin configurations.

required
Source code in src/qemcmc/sampler/proposal.py
def __init__(self, model: EnergyModel):
    self.model = model
    self.n_spins = model.n_spins

update abstractmethod

update(state)

Generate a candidate state from the current state using the proposal mechanism.

This method should be implemented by subclasses to define the specific proposal strategy (e.g., single-spin flips, block updates, or quantum proposals).

Parameters:

Name Type Description Default
state MCMCState

The current state of the Markov chain.

required

Returns:

Type Description
MCMCState

A new candidate state.

Source code in src/qemcmc/sampler/proposal.py
@abstractmethod
def update(self, state: MCMCState) -> MCMCState:
    """
    Generate a candidate state from the current state using the proposal mechanism.

    This method should be implemented by subclasses to define the specific proposal strategy
    (e.g., single-spin flips, block updates, or quantum proposals).

    Parameters
    ----------
    state : MCMCState
        The current state of the Markov chain.

    Returns
    -------
    MCMCState
        A new candidate state.
    """

QuenchProposal

QuenchProposal(
    model,
    gamma,
    time,
    r=None,
    delta_t=None,
    coarse_graining=None,
    coupling_weights=None,
)

Bases: Proposal

Quantum-enhanced Markov Chain Monte Carlo proposer.

This class implements the proposal mechanism of the quantum-enhanced MCMC by Layden et al.. Candidate states are generated by simulating the quantum time evolution of a transverse-field Hamiltonian.

The quantum proposal circuit is constructed using :class:QuenchCircuitMaker and can optionally operate on coarse-grained subgroups of spins to improve scalability.

Parameters:

Name Type Description Default
model EnergyModel

Energy model defining the target Boltzmann distribution.

required
gamma float | tuple[float, float]

Transverse field strength (Γ). If a tuple is provided, a value is sampled uniformly from the range [min, max] at each step.

required
time float | tuple[float, float]

Total evolution time. If a tuple is provided, a value is sampled uniformly from the range [min, max] at each step.

required
r int | None

Number of Trotter steps. Mutually exclusive with delta_t. If provided, the Trotter step size is derived as Δt = t / r and r stays fixed while Δt varies with t. A warning is issued at init if the resulting Δt range falls outside [0.1, 2.0]. By default None.

None
delta_t float | None

Trotter step size. Mutually exclusive with r. If provided, the number of Trotter steps is derived as r = floor(t / Δt) per step, so r varies with t while Δt stays fixed. A warning is issued if Δt falls outside [0.1, 2.0]. By default None.

None
coarse_graining CoarseGraining | None

A coarse-graining scheme to define spin subgroups. If None, no coarse-graining is used. By default None.

None
coupling_weights list[float | tuple[float, float]] | None

Weights for the coupling tensors. If a tuple is provided, a weight is sampled uniformly from the range. This allows for dynamic adjustment of the influence of different terms in the Hamiltonian during the proposal step. By default None. Note that this is further adjusted by (1 - gamma) to balance the influence of the problem Hamiltonian with the mixer term. Divide by (1 - gamma) if needed. Also, note that the coupling weights should include the mixing term.

None
Notes

The proposal step simulates the time evolution under a transverse-field Hamiltonian defined by the energy model and measures the resulting state to produce a candidate configuration. This proposal is then accepted or rejected using the Metropolis criterion to ensure convergence to the target Boltzmann distribution.

Exactly one of r or delta_t should be passed in as an argument. If neither is given, a default Δt of 0.8 is used.

Source code in src/qemcmc/sampler/quenchproposal.py
def __init__(
    self,
    model: EnergyModel,
    gamma: float | tuple[float, float],
    time: float | tuple[float, float],
    r: int | None = None,
    delta_t: float | None = None,
    coarse_graining: CoarseGraining | None = None,
    coupling_weights: list[float | tuple[float, float]] | None = None,
):

    super().__init__(model)

    if coupling_weights is not None:
        if len(coupling_weights) != len(model.normalised_couplings):
            raise ValueError(
                f"Length of coupling_weights ({len(coupling_weights)}) must match the number of couplings in the model ({len(model.normalised_couplings)}), including constraint terms."
            )
        self.coupling_weights = coupling_weights
    else:
        self.coupling_weights = list(np.ones(len(model.normalised_couplings)))

    self.gamma = self._validate_gamma(gamma)
    self.time = self._validate_time(time)
    self.r = self._validate_r(r)
    self.delta_t = self._validate_delta_t(delta_t)
    self._validate_trotter_params()
    self.method = "quantum"

    self.CM = QuenchCircuitMaker(self.model)

    self.cg = coarse_graining or CoarseGraining(model.n_spins)

update

update(current_state)

Perform sequential quantum updates across non-overlapping subgroups.

Parameters:

Name Type Description Default
current_state str

Current state of the system as a bitstring.

required

Returns:

Type Description
str

Updated state of the system as a bitstring.

Source code in src/qemcmc/sampler/quenchproposal.py
def update(self, current_state: str) -> str:
    """
    Perform sequential quantum updates across non-overlapping subgroups.

    Parameters
    ----------
    current_state : str
        Current state of the system as a bitstring.

    Returns
    -------
    str
        Updated state of the system as a bitstring.
    """

    if not isinstance(current_state, str):
        raise TypeError(f"Bitstring must be of type str, got {type(current_state)}: {current_state!r}")

    # Generate disjoint partitions of the spins
    partitions = self.cg.get_partitions()

    final_coupling_weights, g, t, r = self.sample_hyperparams()

    working_state = current_state
    for subgroup in partitions:
        # Recalculate local couplings as spins outside the subgroup may have flipped
        local_couplings = self.model.get_subgroup_couplings(subgroup=subgroup, current_state=working_state, coupling_weights=final_coupling_weights)
        working_state = self.CM.update(s=working_state, subgroup_choice=subgroup, local_couplings=local_couplings, gamma=g, time=t, r=r)
    return working_state

sample_hyperparams

sample_hyperparams()

Sample hyperparameters (coupling weights, gamma, time, r) for the current proposal step.

Returns:

Type Description
tuple[list[float], float, float, int]

(final_coupling_weights, gamma, time, r) for this proposal step.

Source code in src/qemcmc/sampler/quenchproposal.py
def sample_hyperparams(self) -> tuple[list[float], float, float, int]:
    """
    Sample hyperparameters (coupling weights, gamma, time, r) for the current proposal step.

    Returns
    -------
    tuple[list[float], float, float, int]
        (final_coupling_weights, gamma, time, r) for this proposal step.
    """

    # Sample gamma and time once per full proposal step
    g = self.gamma if not isinstance(self.gamma, tuple) else np.random.uniform(*self.gamma)
    t = self.time if not isinstance(self.time, tuple) else np.random.uniform(*self.time)

    # Determine r (number of Trotter steps) for this step
    if self.r is not None:
        # Fixed r mode: r stays constant, Δt varies with t
        r = self.r
        dt = t / r
    else:
        # Fixed Δt mode (explicit or default): r varies with t
        dt = self.delta_t if self.delta_t is not None else DEFAULT_DELTA_T
        r = max(1, int(np.floor(t / dt)))

    # Pre-sample weights for all unique coupling weight settings (tuples or floats)
    unique_items = sorted(set(self.coupling_weights), key=str)
    unique_index = [[i for i, x in enumerate(self.coupling_weights) if x == item] for item in unique_items]

    sampled_weights = np.ones(len(unique_items), dtype=float)
    for i, item in enumerate(unique_items):
        if isinstance(item, (int, float)):
            sampled_weights[i] = item
        elif isinstance(item, tuple):
            sampled_weights[i] = np.random.uniform(*item)

    # Adjust the sampled weights by (1 - gamma) to balance their influence with the mixer term in the Hamiltonian
    sampled_weights_adjusted_by_gamma = (1 - g) * sampled_weights  # Adjust weights by (1 - gamma) to balance with the mixer term

    # Construct the final list of coupling weights for this update step
    final_coupling_weights = np.ones(len(self.coupling_weights))
    for i, indices in enumerate(unique_index):
        for index in indices:
            final_coupling_weights[index] = sampled_weights_adjusted_by_gamma[i]

    return final_coupling_weights, g, t, r

AdiabaticProposal

AdiabaticProposal(
    model,
    gamma,
    alpha,
    kappa,
    delta_t=None,
    coarse_graining=None,
    coupling_weights=None,
)

Bases: Proposal

Quantum-enhanced Markov Chain Monte Carlo proposer with adiabatic dressing.

This class implements the adiabatic dressing proposal mechanism for quantum-enhanced MCMC (Ferguson & Wallden / Hsieh et al., arXiv:2603.28076). Candidate states are generated by simulating the quantum time evolution of a time-dependent transverse-field Hamiltonian:

``H(t) = h(t) * gamma * H_mixer + H_problem``

The schedule function h(t) ramps the transverse field up from 0 to 1 over ramp duration alpha, holds it at 1 for plateau duration kappa, and ramps it down from 1 to 0 over duration alpha (total duration 2 * alpha + kappa). For long evolution times, adiabaticity preserves the ground/eigenstates, whereas for intermediate times diabatic transitions induce proposals concentrated near the target energy levels.

The quantum proposal circuit is constructed using :class:AdiabaticCircuitMaker and can optionally operate on coarse-grained subgroups of spins to improve scalability.

Parameters:

Name Type Description Default
model EnergyModel

Energy model defining the target Boltzmann distribution.

required
gamma float | tuple[float, float]

Transverse field strength. If a tuple is provided, a value is sampled uniformly from the range [min, max] at each step.

required
alpha float | tuple[float, float]

Duration of the linear adiabatic ramp. If a tuple is provided, a value is sampled uniformly from the range [min, max] at each step.

required
kappa float | tuple[float, float]

Duration of the constant plateau. If a tuple is provided, a value is sampled uniformly from the range [min, max] at each step.

required
delta_t float | None

Trotter step size for the approximate time evolution. The number of Trotter steps is derived as r = max(1, round((2 * alpha + kappa) / delta_t)). Defaults to 0.8 if None.

None
coarse_graining CoarseGraining | None

A coarse-graining scheme to define spin subgroups. If None, no coarse-graining is used. Defaults to None.

None
coupling_weights list[float | tuple[float, float]] | None

Weights for the coupling tensors. If a tuple is provided, a weight is sampled uniformly from the range. Defaults to ones.

None
Notes

The proposal step simulates time evolution under a time-dependent transverse-field Hamiltonian and measures the resulting state to produce a candidate configuration. This proposal is then accepted or rejected using the Metropolis criterion to ensure convergence to the target Boltzmann distribution.

Source code in src/qemcmc/sampler/adiabaticproposal.py
def __init__(
    self,
    model: EnergyModel,
    gamma: float | tuple[float, float],
    alpha: float | tuple[float, float],
    kappa: float | tuple[float, float],
    delta_t: float | None = None,
    coarse_graining: CoarseGraining | None = None,
    coupling_weights: list[float | tuple[float, float]] | None = None,
):
    super().__init__(model)

    if coupling_weights is not None:
        if len(coupling_weights) != len(model.normalised_couplings):
            raise ValueError(
                f"Length of coupling_weights ({len(coupling_weights)}) must match the number of couplings in the model ({len(model.normalised_couplings)}), including constraint terms."
            )
        self.coupling_weights = coupling_weights
    else:
        self.coupling_weights = list(np.ones(len(model.normalised_couplings)))

    self.gamma = self._validate_gamma(gamma)
    self.alpha = self._validate_alpha(alpha)
    self.delta_t = self._validate_delta_t(delta_t)
    self.kappa = self._validate_kappa(kappa)

    self.method = "adiabatic_quantum"

    self.CM = AdiabaticCircuitMaker(self.model)

    self.cg = coarse_graining or CoarseGraining(model.n_spins)

update

update(current_state)

Perform sequential quantum updates across non-overlapping subgroups.

Parameters:

Name Type Description Default
current_state str

Current state of the system as a bitstring.

required

Returns:

Type Description
str

Updated state of the system as a bitstring.

Source code in src/qemcmc/sampler/adiabaticproposal.py
def update(self, current_state: str) -> str:
    """
    Perform sequential quantum updates across non-overlapping subgroups.

    Parameters
    ----------
    current_state : str
        Current state of the system as a bitstring.

    Returns
    -------
    str
        Updated state of the system as a bitstring.
    """
    if not isinstance(current_state, str):
        raise TypeError(f"Bitstring must be of type str, got {type(current_state)}: {current_state!r}")

    # Generate disjoint partitions of the spins
    partitions = self.cg.get_partitions()

    final_coupling_weights, g, alpha, kappa = self.sample_hyperparams()

    working_state = current_state
    for subgroup in partitions:
        # Recalculate local couplings as spins outside the subgroup may have flipped
        local_couplings = self.model.get_subgroup_couplings(
            subgroup=subgroup,
            current_state=working_state,
            coupling_weights=final_coupling_weights,
        )
        working_state = self.CM.update(
            s=working_state,
            subgroup_choice=subgroup,
            local_couplings=local_couplings,
            gamma=g,
            alpha=alpha,
            kappa=kappa,
            dt=self.delta_t if self.delta_t is not None else DEFAULT_DELTA_T,
        )
    return working_state

sample_hyperparams

sample_hyperparams()

Sample hyperparameters (coupling weights, gamma, alpha, kappa) for the current proposal step.

Returns:

Type Description
tuple[list[float], float, float, float]

(final_coupling_weights, gamma, alpha, kappa) for this proposal step.

Source code in src/qemcmc/sampler/adiabaticproposal.py
def sample_hyperparams(self) -> tuple[list[float], float, float, float]:
    """
    Sample hyperparameters (coupling weights, gamma, alpha, kappa) for the current proposal step.

    Returns
    -------
    tuple[list[float], float, float, float]
        (final_coupling_weights, gamma, alpha, kappa) for this proposal step.
    """
    # Sample gamma, alpha, and kappa once per full proposal step
    g = self.gamma if not isinstance(self.gamma, tuple) else np.random.uniform(*self.gamma)
    alpha = self.alpha if not isinstance(self.alpha, tuple) else np.random.uniform(*self.alpha)
    kappa = self.kappa if not isinstance(self.kappa, tuple) else np.random.uniform(*self.kappa)

    # Pre-sample weights for all unique coupling weight settings (tuples or floats)
    unique_items = sorted(set(self.coupling_weights), key=str)
    unique_index = [[i for i, x in enumerate(self.coupling_weights) if x == item] for item in unique_items]

    sampled_weights = np.ones(len(unique_items), dtype=float)
    for i, item in enumerate(unique_items):
        if isinstance(item, (int, float)):
            sampled_weights[i] = item
        elif isinstance(item, tuple):
            sampled_weights[i] = np.random.uniform(*item)

    # Adjust the sampled weights by (1 - gamma) to balance their influence with the mixer term in the Hamiltonian
    #sampled_weights_adjusted_by_gamma = (1 - g) * sampled_weights  # Adjust weights by (1 - gamma) to balance with the mixer term
    # we no longer do this, as we are in the other convention

    # Construct the final list of coupling weights for this update step
    final_coupling_weights = np.ones(len(self.coupling_weights))
    for i, indices in enumerate(unique_index):
        for index in indices:
            final_coupling_weights[index] = sampled_weights[i]

    return final_coupling_weights, g, alpha, kappa

SpectralGap

SpectralGap(proposal, model, temp=1.0)

Bases: Runner

Class that finds the spectral gap, and the acceptance and proposal matrices for a given mcmc.

Source code in src/qemcmc/spectralgap.py
def __init__(self, proposal: Proposal, model: EnergyModel, temp: float = 1.0):
    self.proposal = proposal
    self.model = model
    self.temp = temp

find_acceptance_matrix

find_acceptance_matrix()

Function to find the acceptance matrix for a given model instance.

Returns: A (np.ndarray): The acceptance matrix for the mcmc

Source code in src/qemcmc/spectralgap.py
def find_acceptance_matrix(self):
    """
    Function to find the acceptance matrix for a given model instance.

    Returns:
        A (np.ndarray): The acceptance matrix for the mcmc

    """

    num_states = 2**self.proposal.n_spins

    A = np.zeros((num_states, num_states))

    energies = self.model.get_all_energies()

    for i in range(num_states):
        for j in range(num_states):
            if i != j:
                A[i][j] = self.get_acceptance_probability(energies[i], energies[j], temperature=self.temp)
            else:
                A[i][j] = 0

    return A

find_proposal_matrix_local

find_proposal_matrix_local()

Function to find the proposal matrix for a given local chain.

Returns: Q (np.ndarray): The Q matrix for local proposal

Source code in src/qemcmc/spectralgap.py
def find_proposal_matrix_local(self):
    """
    Function to find the proposal matrix for a given local chain.

    Returns:
        Q (np.ndarray): The Q matrix for local proposal
    """

    possible_states = ["".join(i) for i in itertools.product("01", repeat=self.model.n_spins)]

    Q = np.zeros((2**self.model.n_spins, 2**self.model.n_spins))

    # loop throguh and find the difference in bitstrings.
    # When the ith bitstring is different (by a valua of 1) from the jth bitstring add 1 to Q[i,j]
    for i in range(2**self.model.n_spins):
        for j in range(2**self.model.n_spins):
            diff_count = 0
            for k in range(self.model.n_spins):
                diff_count += abs(int(possible_states[i][k]) - int(possible_states[j][k]))

            # ie if the number of different strings is the size of the cluster (= 1 for local)
            if diff_count == 1:
                Q[i, j] = 1

    row_sums = Q.sum(axis=1)
    Q = Q / row_sums[:, np.newaxis]

    return Q

find_proposal_matrix_uniform

find_proposal_matrix_uniform()

Function to find the proposal matrix for a given uniform chain.

Returns: Q (np.ndarray): The Q matrix for uniform proposal

Source code in src/qemcmc/spectralgap.py
def find_proposal_matrix_uniform(self):
    """
    Function to find the proposal matrix for a given uniform chain.

    Returns:
        Q (np.ndarray): The Q matrix for uniform proposal
    """

    Q = np.ones((2**self.model.n_spins, 2**self.model.n_spins)) / (self.proposal.n_spins**2 - 1)
    row_sums = Q.sum(axis=1)
    Q = Q / row_sums[:, np.newaxis]

    return Q

find_proposal_matrix_quantum

find_proposal_matrix_quantum()

Function to find the proposal matrix for a given QeMCMCChain object.

Returns: Q (np.ndarray): The Q matrix for quantum proposal

Source code in src/qemcmc/spectralgap.py
def find_proposal_matrix_quantum(self):
    """
    Function to find the proposal matrix for a given QeMCMCChain object.

    Returns:
        Q (np.ndarray): The Q matrix for quantum proposal
    """
    if not isinstance(self.proposal.gamma, (int, float)):
        raise ValueError("gamma must be a float to find the proposal matrix for quantum proposal, not a tuple. Got: ", self.proposal.gamma, "of type: ", type(self.proposal.gamma))
    if not isinstance(self.proposal.time, (int, float)):
        raise ValueError("time must be a number to find the proposal matrix for quantum proposal, not a tuple. Got: ", self.proposal.time, "of type: ", type(self.proposal.time))

    # Determine r to compute spectral gap
    if self.proposal.r is not None:
        r = self.proposal.r
    else:
        dt = self.proposal.delta_t if self.proposal.delta_t is not None else DEFAULT_DELTA_T
        r = max(1, int(np.floor(self.proposal.time / dt)))

    Q = np.zeros((2**self.model.n_spins, 2**self.model.n_spins))

    for i in range(2**self.model.n_spins):
        Q[i, :] += abs(self.proposal.CM.get_state_vector(self.model.S[i], self.proposal.coupling_weights, self.proposal.time, r, self.proposal.gamma)) ** 2
        # get_output_statevector(self.proposal.model.S[i])

    return Q

find_proposal_matrix_adiabatic

find_proposal_matrix_adiabatic()

Function to find the proposal matrix for a given QeMCMCChain object.

Returns: Q (np.ndarray): The Q matrix for quantum proposal

Source code in src/qemcmc/spectralgap.py
def find_proposal_matrix_adiabatic(self):
    """
    Function to find the proposal matrix for a given QeMCMCChain object.

    Returns:
        Q (np.ndarray): The Q matrix for quantum proposal
    """
    final_coupling_weights, g, alpha, kappa= self.proposal.sample_hyperparams()



    Q = np.zeros((2**self.model.n_spins, 2**self.model.n_spins))
    for i in range(2**self.model.n_spins):
        Q[i, :] += abs(self.proposal.CM.get_state_vector(self.model.S[i], alpha, kappa, g, self.proposal.coupling_weights)) ** 2
        # get_output_statevector(self.proposal.model.S[i])

    return Q

find_proposal_matrix

find_proposal_matrix()

Function to find the proposal matrix for a given mcmc. This is not done by brute force

Source code in src/qemcmc/spectralgap.py
def find_proposal_matrix(self):
    """
    Function to find the proposal matrix for a given mcmc.
    This is not done by brute force
    """

    if self.proposal.method == "local":
        Q = self.find_proposal_matrix_local()
    elif self.proposal.method == "uniform":
        Q = self.find_proposal_matrix_uniform()
    elif self.proposal.method == "quantum":
        Q = self.find_proposal_matrix_quantum()
    elif self.proposal.method == "adiabatic_quantum":
        Q = self.find_proposal_matrix_adiabatic()
    else:
        raise ValueError("Method not recognised. Only 'local', 'uniform' or 'quantum' proposal methods are implimented in find_proposal_method.")

    return Q

find_spectral_gap

find_spectral_gap(A=None, Q=None)

Function to find the spectral gap of a given mcmc.

Parameters:

Name Type Description Default
A

The acceptance matrix for the mcmc (optional, if not given, will be calculated)

None
Q

The proposal matrix for the mcmc (optional, if not given, will be calculated)

None
Source code in src/qemcmc/spectralgap.py
def find_spectral_gap(self, A=None, Q=None):
    """
    Function to find the spectral gap of a given mcmc.

    Parameters
    ----------
    A (np.ndarray):
        The acceptance matrix for the mcmc (optional, if not given, will be calculated)
    Q (np.ndarray):
        The proposal matrix for the mcmc (optional, if not given, will be calculated)
    """

    if A is None:
        A = self.find_acceptance_matrix()
    if Q is None:
        Q = self.find_proposal_matrix()
        # Q = self.find_proposal_matrix_brute_force(multiple = 10*2**self.mcmc.n_spins)

    P = np.multiply(Q, A)

    # account for rejected swaps to add to s = s' matrix element
    for i in range(P.shape[0]):
        s = np.sum(P[i, :]) - P[i, i]
        P[i, i] = 1 - s

    # find eigenvalues
    e_vals, _e_vecs = sp.linalg.eig(P)
    e_vals = np.flip(np.sort(abs(e_vals)))

    # find spectral gap
    delta = e_vals[1]
    delta = 1 - delta

    return delta

MCMCChain dataclass

MCMCChain(states=None, name='MCMC')

Container for the sequence of states produced during an MCMC run.

This class records all proposed states, tracks accepted configurations, and provides helper methods for extracting trajectories, energies, and empirical distributions from the Markov chain.

Source code in src/qemcmc/utils/helpers.py
def __init__(self, states: list[MCMCState] | None = None, name: str | None = "MCMC"):
    self.name = name

    if states is None:
        self._states: list[MCMCState] = []
        self._current_state: MCMCState = None
        self._states_accepted: list[MCMCState] = []
        self.markov_chain: list[str] = []

    else:
        self._states = states
        self._current_state: MCMCState = next((s for s in self._states[::-1] if s.accepted), None)
        self._states_accepted: list[MCMCState] = [state for state in states if state.accepted]
        self.markov_chain: list[str] = self.get_list_markov_chain()

MCMCState dataclass

MCMCState(bitstring, accepted, energy=None, position=None)

Represents a single step in an MCMC trajectory.

Stores the proposed configuration, whether it was accepted by the Metropolis rule, its energy, and the position of the step in the chain.

get_all_possible_states

get_all_possible_states(num_spins)

Returns all possible binary strings of length n=num_spins

Paremeters: num_spins: n length of the bitstring Returns: list: A list of all possible binary strings of length num_spins.

Source code in src/qemcmc/utils/helpers.py
def get_all_possible_states(num_spins: int) -> list:
    """
    Returns all possible binary strings of length n=num_spins

    Paremeters:
        num_spins: n length of the bitstring
    Returns:
        list: A list of all possible binary strings of length num_spins.
    """

    num_possible_states = 2 ** (num_spins)
    possible_states = [f"{k:0{num_spins}b}" for k in range(num_possible_states)]
    return possible_states

get_random_state

get_random_state(num_spins)

Generate a random state for a given number of spins.

Parameters: num_spins (int): The number of spins in the system. Returns: str: A bitstring representing the random state.

Source code in src/qemcmc/utils/helpers.py
def get_random_state(num_spins: int) -> str:
    """
    Generate a random state for a given number of spins.

    Parameters:
        num_spins (int): The number of spins in the system.
    Returns:
        str: A bitstring representing the random state.
    """

    next_state = np.random.randint(0, 2, size=num_spins, dtype=np.int8)
    # s_prime = f"{next_state:0{num_spins}b}"
    s_prime = "".join(str(bit) for bit in next_state)
    return s_prime