Skip to content

Customize The Hamiltonian

In some cases one would like to modify the terms in the Hamiltonian, for example in order 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. In the following example we neglect terms in the Hamiltonian with coefficient smaller than 0.05.

from classiq import ModelDesigner
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_designer = ModelDesigner()

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

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

model_designer.UCC(params=ucc_params, in_wires={"IN": hf_output})
circuit = model_designer.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()