Skip to content

Customize the Hamiltonian

There may be situations where you want to modify the terms in the Hamiltonian; for example, to reduce the number of measurements during the VQE execution. The number of measurements required to obtain the energy expectation value grows with the number of Pauli terms in the Hamiltonian.

The following example ignores terms in the Hamiltonian with a coefficient smaller than 0.05.

from classiq import Model
from classiq.builtin_functions import UCC, HartreeFock
from classiq.builtin_functions.exponentiation import PauliOperator

from classiq.applications.chemistry import (
    Molecule,
    MoleculeProblem,
    GroundStateSolver,
    GroundStateOptimizer,
)
from classiq.execution import IBMBackendPreferences

molecule = Molecule(
    atoms=[
        ("H", (0.0, 0.0, 0.0)),
        ("H", (0.0, 0.0, 0.735)),
    ],
)
gs_problem = MoleculeProblem(
    molecule=molecule,
    mapping="jordan_wigner",
)

hamiltonian = gs_problem.generate_hamiltonian()
gs_problem = gs_problem.update_problem(hamiltonian.num_qubits)

# keep only the terms with coefficients larger than 0.05
custom_hamiltonian = PauliOperator(
    pauli_list=[p for p in hamiltonian.pauli_list if abs(p[1]) > 0.05]
)

model = Model()

hf_params = HartreeFock(gs_problem=gs_problem)
output_dict = model.HartreeFock(params=hf_params)
hf_output = output_dict["OUT"]

ucc_params = UCC(gs_problem=gs_problem, excitations=[1, 2], max_depth=100)

model.UCC(params=ucc_params, in_wires={"IN": hf_output})
circuit = model.synthesize()

optimizer_preferences = GroundStateOptimizer(
    max_iteration=30,
    num_shots=1000,
)
backend_preferences = IBMBackendPreferences(
    backend_service_provider="IBM Quantum", backend_name="aer_simulator"
)

gs_solver = GroundStateSolver(
    ground_state_problem=gs_problem,
    ansatz=circuit,
    optimizer_preferences=optimizer_preferences,
    backend_preferences=backend_preferences,
    hamiltonian=custom_hamiltonian,
)

result = gs_solver.solve()