Skip to content

Commit 6ce74ab

Browse files
committed
Install dependencies and format hfvqe/quickstart
Partially address quantumlib#101. Re-work `molecular_exmaple.py` to support putting these data files elsewhere in the future.
1 parent 80c75fa commit 6ce74ab

File tree

5 files changed

+127
-93
lines changed

5 files changed

+127
-93
lines changed

docs/hfvqe/quickstart.ipynb

Lines changed: 85 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,36 @@
11
{
22
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {
6+
"id": "IafxybMjKfBO"
7+
},
8+
"source": [
9+
"##### Copyright 2020 Google"
10+
]
11+
},
12+
{
13+
"cell_type": "code",
14+
"execution_count": null,
15+
"metadata": {
16+
"cellView": "form",
17+
"id": "pc1aHcGvKmHe"
18+
},
19+
"outputs": [],
20+
"source": [
21+
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
22+
"# you may not use this file except in compliance with the License.\n",
23+
"# You may obtain a copy of the License at\n",
24+
"#\n",
25+
"# https://www.apache.org/licenses/LICENSE-2.0\n",
26+
"#\n",
27+
"# Unless required by applicable law or agreed to in writing, software\n",
28+
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
29+
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
30+
"# See the License for the specific language governing permissions and\n",
31+
"# limitations under the License."
32+
]
33+
},
334
{
435
"cell_type": "markdown",
536
"metadata": {
@@ -11,6 +42,42 @@
1142
"This code tutorial shows how to estimate a 1-RDM and perform variational optimization"
1243
]
1344
},
45+
{
46+
"cell_type": "markdown",
47+
"metadata": {
48+
"id": "FQEYY3gnK51d"
49+
},
50+
"source": [
51+
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
52+
" <td>\n",
53+
" <a target=\"_blank\" href=\"https://www.example.org/cirq/experiments/hfvqe/quickstart\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on QuantumLib</a>\n",
54+
" </td>\n",
55+
" <td>\n",
56+
" <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/ReCirq/blob/master/docs/hfvqe/quickstart.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
57+
" </td>\n",
58+
" <td>\n",
59+
" <a target=\"_blank\" href=\"https://github.com/quantumlib/ReCirq/blob/master/docs/hfvqe/quickstart.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
60+
" </td>\n",
61+
" <td>\n",
62+
" <a href=\"https://storage.googleapis.com/tensorflow_docs/ReCirq/docs/hfvqe/quickstart.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
63+
" </td>\n",
64+
"</table>"
65+
]
66+
},
67+
{
68+
"cell_type": "code",
69+
"execution_count": null,
70+
"metadata": {
71+
"id": "8625de3d3c0d"
72+
},
73+
"outputs": [],
74+
"source": [
75+
"try:\n",
76+
" import recirq\n",
77+
"except ImportError:\n",
78+
" !pip install --quiet git+https://github.com/quantumlib/ReCirq"
79+
]
80+
},
1481
{
1582
"cell_type": "code",
1683
"execution_count": null,
@@ -19,19 +86,17 @@
1986
},
2087
"outputs": [],
2188
"source": [
22-
"# Import library functions and define a helper function\n",
2389
"import numpy as np\n",
2490
"import cirq\n",
2591
"\n",
2692
"from recirq.hfvqe.gradient_hf import rhf_func_generator\n",
2793
"from recirq.hfvqe.opdm_functionals import OpdmFunctional\n",
28-
"from recirq.hfvqe.analysis import (compute_opdm,\n",
29-
" mcweeny_purification,\n",
30-
" resample_opdm,\n",
31-
" fidelity_witness,\n",
32-
" fidelity)\n",
94+
"from recirq.hfvqe.analysis import (\n",
95+
" compute_opdm, mcweeny_purification,\n",
96+
" resample_opdm, fidelity_witness,\n",
97+
" fidelity)\n",
3398
"from recirq.hfvqe.third_party.higham import fixed_trace_positive_projection\n",
34-
"from recirq.hfvqe.molecular_example import make_h6_1_3\n"
99+
"from recirq.hfvqe.molecular_example import make_h6_1_3"
35100
]
36101
},
37102
{
@@ -64,7 +129,8 @@
64129
" constant=molecule.nuclear_repulsion,\n",
65130
" one_body_integrals=obi,\n",
66131
" two_body_integrals=tbi,\n",
67-
" num_electrons=molecule.n_electrons // 2, # only simulate spin-up electrons\n",
132+
" # only simulate spin-up electrons:\n",
133+
" num_electrons=molecule.n_electrons // 2,\n",
68134
" clean_xxyy=True,\n",
69135
" purification=True\n",
70136
" )"
@@ -103,8 +169,7 @@
103169
"measurement_data = opdm_func.calculate_data(parameters)\n",
104170
"\n",
105171
"# 2.\n",
106-
"opdm, var_dict = compute_opdm(measurement_data,\n",
107-
" return_variance=True)\n",
172+
"opdm, var_dict = compute_opdm(measurement_data, return_variance=True)\n",
108173
"opdm_pure = mcweeny_purification(opdm)\n",
109174
"\n",
110175
"# 3.\n",
@@ -117,7 +182,9 @@
117182
"nocc = molecule.n_electrons // 2\n",
118183
"nvirt = molecule.n_orbitals - nocc\n",
119184
"initial_fock_state = [1] * nocc + [0] * nvirt\n",
120-
"for _ in range(1000): # 1000 repetitions of the measurement\n",
185+
"\n",
186+
"# 1000 repetitions of the measurement\n",
187+
"for _ in range(1000): \n",
121188
" new_opdm = resample_opdm(opdm, var_dict)\n",
122189
" raw_energies.append(opdm_func.energy_from_opdm(new_opdm))\n",
123190
" raw_fidelity_witness.append(\n",
@@ -142,7 +209,6 @@
142209
" fidelity(target_unitary=true_unitary,\n",
143210
" measured_opdm=new_opdm_pure)\n",
144211
" )\n",
145-
"print('\\n\\n\\n\\n')\n",
146212
"print(\"Canonical Hartree-Fock energy \", molecule.hf_energy)\n",
147213
"print(\"True energy \", energy(parameters))\n",
148214
"print(\"Raw energy \", opdm_func.energy_from_opdm(opdm),\n",
@@ -154,7 +220,7 @@
154220
"print(\"Purified fidelity witness \", np.mean(purified_fidelity_witness).real,\n",
155221
" \"+- \", np.std(purified_fidelity_witness))\n",
156222
"print(\"Purified fidelity \", np.mean(purified_fidelity).real,\n",
157-
" \"+- \", np.std(purified_fidelity))\n"
223+
" \"+- \", np.std(purified_fidelity))"
158224
]
159225
},
160226
{
@@ -163,7 +229,7 @@
163229
"id": "669a320cb246"
164230
},
165231
"source": [
166-
"This should print out the various energies estimated from the 1-RDM along with error bars. Generated from resampling the 1-RDM based on the estimated covariance."
232+
"This prints out the various energies estimated from the 1-RDM along with error bars. Generated from resampling the 1-RDM based on the estimated covariance."
167233
]
168234
},
169235
{
@@ -202,7 +268,7 @@
202268
"source": [
203269
"from recirq.hfvqe.mfopt import moving_frame_augmented_hessian_optimizer\n",
204270
"from recirq.hfvqe.opdm_functionals import RDMGenerator\n",
205-
"import matplotlib.pyplot as plt\n",
271+
"\n",
206272
"rdm_generator = RDMGenerator(opdm_func, purification=True)\n",
207273
"opdm_generator = rdm_generator.opdm_generator\n",
208274
"\n",
@@ -213,7 +279,7 @@
213279
" verbose=True, delta=0.03,\n",
214280
" max_iter=20,\n",
215281
" hessian_update='diagonal',\n",
216-
" rtol=0.50E-2)\n"
282+
" rtol=0.50E-2)"
217283
]
218284
},
219285
{
@@ -235,13 +301,15 @@
235301
},
236302
"outputs": [],
237303
"source": [
304+
"import matplotlib.pyplot as plt\n",
305+
"\n",
238306
"plt.semilogy(range(len(result.func_vals)),\n",
239307
" np.abs(np.array(result.func_vals) - energy(parameters)),\n",
240308
" 'C0o-')\n",
241309
"plt.xlabel(\"Optimization Iterations\", fontsize=18)\n",
242310
"plt.ylabel(r\"$|E - E^{*}|$\", fontsize=18)\n",
243311
"plt.tight_layout()\n",
244-
"plt.show()\n"
312+
"plt.show()"
245313
]
246314
}
247315
],
@@ -253,18 +321,6 @@
253321
"kernelspec": {
254322
"display_name": "Python 3",
255323
"name": "python3"
256-
},
257-
"language_info": {
258-
"codemirror_mode": {
259-
"name": "ipython",
260-
"version": 3
261-
},
262-
"file_extension": ".py",
263-
"mimetype": "text/x-python",
264-
"name": "python",
265-
"nbconvert_exporter": "python",
266-
"pygments_lexer": "ipython3",
267-
"version": "3.6.12"
268324
}
269325
},
270326
"nbformat": 4,

recirq/hfvqe/analysis_test.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@
1919
from recirq.hfvqe.analysis import (trace_distance, kdelta, energy_from_opdm,
2020
fidelity_witness, fidelity,
2121
mcweeny_purification)
22-
from recirq.hfvqe.molecular_example import make_h6_1_3
23-
from recirq.hfvqe.molecular_example_odd_qubits import (make_h3_2_5)
22+
from recirq.hfvqe.molecular_example import make_h6_1_3, make_h3_2_5
2423
from recirq.hfvqe.gradient_hf import rhf_func_generator
2524

2625

recirq/hfvqe/molecular_example.py

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,17 @@
2323
from recirq.hfvqe.objective import (RestrictedHartreeFockObjective,
2424
generate_hamiltonian)
2525

26+
_MOLECULAR_DATA_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) + '/molecular_data'
2627

27-
def make_h6_1_3() -> Tuple[RestrictedHartreeFockObjective, of.MolecularData, np.
28-
ndarray, np.ndarray, np.ndarray]:
29-
# load the molecule from moelcular data
30-
import recirq.hfvqe as hfvqe
31-
h6_1_3_path = os.path.join(
32-
hfvqe.__path__[0],
33-
'molecular_data/hydrogen_chains/h_6_sto-3g/bond_distance_1.3')
3428

35-
molfile = os.path.join(h6_1_3_path, 'H6_sto-3g_singlet_linear_r-1.3.hdf5')
29+
def make_h6_1_3(molecular_data_directory=None) \
30+
-> Tuple[RestrictedHartreeFockObjective, of.MolecularData,
31+
np.ndarray, np.ndarray, np.ndarray]:
32+
if molecular_data_directory is None:
33+
molecular_data_directory = _MOLECULAR_DATA_DIRECTORY
34+
35+
h6_1_3_path = f'{molecular_data_directory}/hydrogen_chains/h_6_sto-3g/bond_distance_1.3'
36+
molfile = f'{h6_1_3_path}/H6_sto-3g_singlet_linear_r-1.3.hdf5'
3637
molecule = of.MolecularData(filename=molfile)
3738
molecule.load()
3839

@@ -52,3 +53,31 @@ def make_h6_1_3() -> Tuple[RestrictedHartreeFockObjective, of.MolecularData, np.
5253
scipy_result = rhf_minimization(rhf_objective)
5354

5455
return rhf_objective, molecule, scipy_result.x, obi, tbi
56+
57+
58+
def make_h3_2_5(molecular_data_directory=None) \
59+
-> Tuple[RestrictedHartreeFockObjective, of.MolecularData,
60+
np.ndarray, np.ndarray, np.ndarray]:
61+
if molecular_data_directory is None:
62+
molecular_data_directory = _MOLECULAR_DATA_DIRECTORY
63+
64+
h3_2_5_path = f'{molecular_data_directory}/hydrogen_chains/h_3_p_sto-3g/bond_distance_2.5'
65+
molfile = f'{h3_2_5_path}/H3_plus_sto-3g_singlet_linear_r-2.5.hdf5'
66+
molecule = of.MolecularData(filename=molfile)
67+
molecule.load()
68+
69+
S = np.load(os.path.join(h3_2_5_path, 'overlap.npy'))
70+
Hcore = np.load(os.path.join(h3_2_5_path, 'h_core.npy'))
71+
TEI = np.load(os.path.join(h3_2_5_path, 'tei.npy'))
72+
73+
_, X = sp.linalg.eigh(Hcore, S)
74+
obi = of.general_basis_change(Hcore, X, (1, 0))
75+
tbi = np.einsum('psqr', of.general_basis_change(TEI, X, (1, 0, 1, 0)))
76+
molecular_hamiltonian = generate_hamiltonian(obi, tbi,
77+
molecule.nuclear_repulsion)
78+
79+
rhf_objective = RestrictedHartreeFockObjective(molecular_hamiltonian,
80+
molecule.n_electrons)
81+
82+
scipy_result = rhf_minimization(rhf_objective)
83+
return rhf_objective, molecule, scipy_result.x, obi, tbi

recirq/hfvqe/molecular_example_odd_qubits.py

Lines changed: 0 additions & 54 deletions
This file was deleted.

setup.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,8 @@
3333
description="",
3434
long_description=open('README.md', encoding='utf-8').read(),
3535
packages=find_packages(),
36+
package_data={'recirq': [
37+
# https://github.com/quantumlib/ReCirq/issues/101
38+
'hfvqe/molecular_data/hydrogen_chains/*/*/*',
39+
]},
3640
)

0 commit comments

Comments
 (0)