-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add hop gate ansatz and apply_unitary protocol (#49)
* add hop gate ansatz and apply_unitary protocol * remove type annotation syntax that only works on python 3.10+ * Revert "remove type annotation syntax that only works on python 3.10+" This reverts commit a1cd941. * from __future__ import annotations * format * lint * fix docs
- Loading branch information
Showing
16 changed files
with
402 additions
and
72 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,147 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"# Entanglement forging\n", | ||
"\n", | ||
"In this tutorial, we show how to simulate entanglement forging for a water molecule at equilibrium." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"import pyscf\n", | ||
"import pyscf.mcscf\n", | ||
"import ffsim\n", | ||
"import math\n", | ||
"import numpy as np\n", | ||
"\n", | ||
"# Build a water molecule\n", | ||
"radius_1 = 0.958 # position for the first H atom\n", | ||
"radius_2 = 0.958 # position for the second H atom\n", | ||
"bond_angle_deg = 104.478 # bond angles.\n", | ||
"\n", | ||
"h1_x = radius_1\n", | ||
"h2_x = radius_2 * math.cos(math.pi / 180 * bond_angle_deg)\n", | ||
"h2_y = radius_2 * math.sin(math.pi / 180 * bond_angle_deg)\n", | ||
"\n", | ||
"mol = pyscf.gto.Mole()\n", | ||
"mol.build(\n", | ||
" atom=[\n", | ||
" [\"O\", (0, 0, 0)],\n", | ||
" [\"H\", (h1_x, 0, 0)],\n", | ||
" [\"H\", (h2_x, h2_y, 0)],\n", | ||
" ],\n", | ||
" basis=\"sto-6g\",\n", | ||
" symmetry=\"c2v\",\n", | ||
")\n", | ||
"hartree_fock = pyscf.scf.RHF(mol)\n", | ||
"hartree_fock.kernel()\n", | ||
"\n", | ||
"# Define active space\n", | ||
"active_space = [1, 2, 4, 5, 6]\n", | ||
"norb = len(active_space)\n", | ||
"n_electrons = int(sum(hartree_fock.mo_occ[active_space]))\n", | ||
"n_alpha = (n_electrons + hartree_fock.mol.spin) // 2\n", | ||
"n_beta = (n_electrons - hartree_fock.mol.spin) // 2\n", | ||
"nelec = (n_alpha, n_beta)\n", | ||
"\n", | ||
"# Compute FCI energy\n", | ||
"cas = pyscf.mcscf.CASCI(hartree_fock, ncas=len(active_space), nelecas=nelec)\n", | ||
"mo = cas.sort_mo(active_space, base=0)\n", | ||
"energy_fci = cas.kernel(mo)[0]\n", | ||
"\n", | ||
"# Get molecular data and molecular Hamiltonian (one- and two-body tensors)\n", | ||
"mol_data = ffsim.MolecularData.from_hartree_fock(\n", | ||
" hartree_fock, active_space=active_space\n", | ||
")\n", | ||
"mol_hamiltonian = mol_data.hamiltonian" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"import numpy as np\n", | ||
"\n", | ||
"n_reps = 1\n", | ||
"\n", | ||
"# Construct ansatz operator\n", | ||
"interaction_pairs = [(0, 1), (3, 4), (1, 4), (0, 2), (3, 4)]\n", | ||
"thetas = np.zeros(n_reps * len(interaction_pairs))\n", | ||
"operator = ffsim.HopGateAnsatzOperator(interaction_pairs, thetas=thetas)\n", | ||
"\n", | ||
"# Construct ansatz state\n", | ||
"reference_occupations_spatial = [(0, 1, 2), (1, 2, 3), (1, 2, 4)]\n", | ||
"reference_occupations = list(\n", | ||
" zip(reference_occupations_spatial, reference_occupations_spatial)\n", | ||
")\n", | ||
"hamiltonian = ffsim.linear_operator(mol_hamiltonian, norb=norb, nelec=nelec)\n", | ||
"ansatz_state = ffsim.multireference_state(\n", | ||
" hamiltonian, operator, reference_occupations, norb=norb, nelec=nelec\n", | ||
")\n", | ||
"\n", | ||
"# Compute the energy ⟨ψ|H|ψ⟩ of the ansatz state\n", | ||
"energy = np.real(np.vdot(ansatz_state, hamiltonian @ ansatz_state))\n", | ||
"print(f\"Energy at initialialization: {energy}\")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"import scipy.optimize\n", | ||
"\n", | ||
"\n", | ||
"def fun(x):\n", | ||
" # Initialize the ansatz operator from the parameter vector\n", | ||
" operator = ffsim.HopGateAnsatzOperator(interaction_pairs, x)\n", | ||
" # Compute ansatz state\n", | ||
" ansatz_state = ffsim.multireference_state(\n", | ||
" hamiltonian, operator, reference_occupations, norb=norb, nelec=nelec\n", | ||
" )\n", | ||
" # Compute the energy ⟨ψ|H|ψ⟩ of the ansatz state\n", | ||
" return np.real(np.vdot(ansatz_state, hamiltonian @ ansatz_state))\n", | ||
"\n", | ||
"\n", | ||
"result = scipy.optimize.minimize(\n", | ||
" fun, x0=operator.thetas, method=\"COBYLA\", options=dict(maxiter=100)\n", | ||
")\n", | ||
"\n", | ||
"print(f\"Number of parameters: {len(result.x)}\")\n", | ||
"print(result)" | ||
] | ||
} | ||
], | ||
"metadata": { | ||
"kernelspec": { | ||
"display_name": "ffsim-a58AE6yt", | ||
"language": "python", | ||
"name": "python3" | ||
}, | ||
"language_info": { | ||
"codemirror_mode": { | ||
"name": "ipython", | ||
"version": 3 | ||
}, | ||
"file_extension": ".py", | ||
"mimetype": "text/x-python", | ||
"name": "python", | ||
"nbconvert_exporter": "python", | ||
"pygments_lexer": "ipython3", | ||
"version": "3.10.13" | ||
}, | ||
"orig_nbformat": 4 | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 2 | ||
} |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
# (C) Copyright IBM 2023. | ||
# | ||
# This code is licensed under the Apache License, Version 2.0. You may | ||
# obtain a copy of this license in the LICENSE.txt file in the root directory | ||
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. | ||
# | ||
# Any modifications or derivative works of this code must retain this | ||
# copyright notice, and modified files need to carry a notice indicating | ||
# that they have been altered from the originals. | ||
|
||
"""Apply unitary protocol.""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Any, Protocol | ||
|
||
import numpy as np | ||
|
||
|
||
class SupportsApplyUnitary(Protocol): | ||
"""An object that can apply a unitary transformation to a vector.""" | ||
|
||
def _apply_unitary_( | ||
self, vec: np.ndarray, norb: int, nelec: tuple[int, int], copy: bool | ||
) -> np.ndarray: | ||
"""Apply a unitary transformation to a vector. | ||
Args: | ||
vec: The vector to apply the unitary transformation to. | ||
norb: The number of spatial orbitals. | ||
nelec: The number of alpha and beta electrons. | ||
copy: Whether to copy the vector before operating on it. | ||
- If ``copy=True`` then this function always returns a newly allocated | ||
vector and the original vector is left untouched. | ||
- If ``copy=False`` then this function may still return a newly | ||
allocated vector, but the original vector may have its data overwritten. | ||
It is also possible that the original vector is returned, | ||
modified in-place. | ||
Returns: | ||
The transformed vector. | ||
""" | ||
|
||
|
||
def apply_unitary( | ||
vec: np.ndarray, obj: Any, norb: int, nelec: tuple[int, int], copy: bool = True | ||
) -> np.ndarray: | ||
"""Apply a unitary transformation to a vector. | ||
Args: | ||
vec: The vector to apply the unitary transformation to. | ||
obj: The object with a unitary effect. | ||
norb: The number of spatial orbitals. | ||
nelec: The number of alpha and beta electrons. | ||
copy: Whether to copy the vector before operating on it. | ||
- If ``copy=True`` then this function always returns a newly allocated | ||
vector and the original vector is left untouched. | ||
- If ``copy=False`` then this function may still return a newly | ||
allocated vector, but the original vector may have its data overwritten. | ||
It is also possible that the original vector is returned, | ||
modified in-place. | ||
Returns: | ||
The transformed vector. | ||
""" | ||
method = getattr(obj, "_apply_unitary_", None) | ||
if method is not None: | ||
return method(vec, norb=norb, nelec=nelec, copy=copy) | ||
|
||
raise TypeError(f"Object of type {type(obj)} has no _apply_unitary_ method.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# (C) Copyright IBM 2023. | ||
# | ||
# This code is licensed under the Apache License, Version 2.0. You may | ||
# obtain a copy of this license in the LICENSE.txt file in the root directory | ||
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. | ||
# | ||
# Any modifications or derivative works of this code must retain this | ||
# copyright notice, and modified files need to carry a notice indicating | ||
# that they have been altered from the originals. | ||
|
||
"""Hop gate ansatz.""" | ||
|
||
from __future__ import annotations | ||
|
||
import itertools | ||
from dataclasses import dataclass | ||
|
||
import numpy as np | ||
|
||
from ffsim.gates import apply_hop_gate | ||
|
||
|
||
@dataclass | ||
class HopGateAnsatzOperator: | ||
r"""A hop gate ansatz operator.""" | ||
|
||
interaction_pairs: list[tuple[int, int]] | ||
thetas: np.ndarray | ||
|
||
def _apply_unitary_( | ||
self, vec: np.ndarray, norb: int, nelec: tuple[int, int], copy: bool | ||
) -> np.ndarray: | ||
"""Apply the operator to a vector.""" | ||
if copy: | ||
vec = vec.copy() | ||
for target_orbs, theta in zip( | ||
itertools.cycle(self.interaction_pairs), self.thetas | ||
): | ||
vec = apply_hop_gate( | ||
vec, theta, target_orbs=target_orbs, norb=norb, nelec=nelec, copy=False | ||
) | ||
return vec |
Oops, something went wrong.