-
Notifications
You must be signed in to change notification settings - Fork 369
/
conversions.py
387 lines (330 loc) · 15.6 KB
/
conversions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy
from openfermion.config import EQ_TOLERANCE
from openfermion.ops.operators import FermionOperator
from openfermion.ops.representations import (
DiagonalCoulombHamiltonian,
InteractionOperator,
InteractionOperatorError,
)
from openfermion.transforms.opconversions import check_no_sympy, normal_ordered
from openfermion.ops.representations.quadratic_hamiltonian import (
QuadraticHamiltonian,
QuadraticHamiltonianError,
)
from openfermion.chem import MolecularData
# for breaking cyclic imports
from openfermion.utils import operator_utils as op_utils
def get_quadratic_hamiltonian(
fermion_operator, chemical_potential=0.0, n_qubits=None, ignore_incompatible_terms=False
):
r"""Convert a quadratic fermionic operator to QuadraticHamiltonian.
Args:
fermion_operator(FermionOperator): The operator to convert.
chemical_potential(float): A chemical potential to include in
the returned operator
n_qubits(int): Optionally specify the total number of qubits in the
system
ignore_incompatible_terms(bool): This flag determines the behavior
of this method when it encounters terms that are not quadratic
that is, terms that are not of the form a^\dagger_p a_q.
If set to True, this method will simply ignore those terms.
If False, then this method will raise an error if it encounters
such a term. The default setting is False.
Returns:
quadratic_hamiltonian: An instance of the QuadraticHamiltonian class.
Raises:
TypeError: Input must be a FermionOperator.
TypeError: FermionOperator does not map to QuadraticHamiltonian.
Warning:
Even assuming that each creation or annihilation operator appears
at most a constant number of times in the original operator, the
runtime of this method is exponential in the number of qubits.
"""
if not isinstance(fermion_operator, FermionOperator):
raise TypeError('Input must be a FermionOperator.')
check_no_sympy(fermion_operator)
if n_qubits is None:
n_qubits = op_utils.count_qubits(fermion_operator)
if n_qubits < op_utils.count_qubits(fermion_operator):
raise ValueError('Invalid number of qubits specified.')
# Normal order the terms and initialize.
fermion_operator = normal_ordered(fermion_operator)
constant = 0.0
combined_hermitian_part = numpy.zeros((n_qubits, n_qubits), complex)
antisymmetric_part = numpy.zeros((n_qubits, n_qubits), complex)
# Loop through terms and assign to matrix.
for term in fermion_operator.terms:
coefficient = fermion_operator.terms[term]
# Ignore this term if the coefficient is zero
if abs(coefficient) < EQ_TOLERANCE:
# not testable because normal_ordered kills
# fermion terms lower than EQ_TOLERANCE
continue # pragma: no cover
if len(term) == 0:
# Constant term
constant = coefficient
elif len(term) == 2:
ladder_type = [operator[1] for operator in term]
p, q = [operator[0] for operator in term]
if ladder_type == [1, 0]:
combined_hermitian_part[p, q] = coefficient
elif ladder_type == [1, 1]:
# Need to check that the corresponding [0, 0] term is present
conjugate_term = ((p, 0), (q, 0))
if conjugate_term not in fermion_operator.terms:
raise QuadraticHamiltonianError(
'FermionOperator does not map ' 'to QuadraticHamiltonian (not Hermitian).'
)
else:
matching_coefficient = -fermion_operator.terms[conjugate_term].conjugate()
discrepancy = abs(coefficient - matching_coefficient)
if discrepancy > EQ_TOLERANCE:
raise QuadraticHamiltonianError(
'FermionOperator does not map '
'to QuadraticHamiltonian (not Hermitian).'
)
antisymmetric_part[p, q] += 0.5 * coefficient
antisymmetric_part[q, p] -= 0.5 * coefficient
else:
# ladder_type == [0, 0]
# Need to check that the corresponding [1, 1] term is present
conjugate_term = ((p, 1), (q, 1))
if conjugate_term not in fermion_operator.terms:
raise QuadraticHamiltonianError(
'FermionOperator does not map ' 'to QuadraticHamiltonian (not Hermitian).'
)
else:
matching_coefficient = -fermion_operator.terms[conjugate_term].conjugate()
discrepancy = abs(coefficient - matching_coefficient)
if discrepancy > EQ_TOLERANCE:
raise QuadraticHamiltonianError(
'FermionOperator does not map '
'to QuadraticHamiltonian (not Hermitian).'
)
antisymmetric_part[p, q] -= 0.5 * coefficient.conjugate()
antisymmetric_part[q, p] += 0.5 * coefficient.conjugate()
elif not ignore_incompatible_terms:
# Operator contains non-quadratic terms
raise QuadraticHamiltonianError(
'FermionOperator does not map '
'to QuadraticHamiltonian '
'(contains non-quadratic terms).'
)
# Compute Hermitian part
hermitian_part = combined_hermitian_part + chemical_potential * numpy.eye(n_qubits)
# Check that the operator is Hermitian
if not op_utils.is_hermitian(hermitian_part):
raise QuadraticHamiltonianError(
'FermionOperator does not map ' 'to QuadraticHamiltonian (not Hermitian).'
)
# Form QuadraticHamiltonian and return.
discrepancy = numpy.max(numpy.abs(antisymmetric_part))
if discrepancy < EQ_TOLERANCE:
# Hamiltonian conserves particle number
quadratic_hamiltonian = QuadraticHamiltonian(
hermitian_part, constant=constant, chemical_potential=chemical_potential
)
else:
# Hamiltonian does not conserve particle number
quadratic_hamiltonian = QuadraticHamiltonian(
hermitian_part, antisymmetric_part, constant, chemical_potential
)
return quadratic_hamiltonian
def get_diagonal_coulomb_hamiltonian(
fermion_operator, n_qubits=None, ignore_incompatible_terms=False
):
r"""Convert a FermionOperator to a DiagonalCoulombHamiltonian.
Args:
fermion_operator(FermionOperator): The operator to convert.
n_qubits(int): Optionally specify the total number of qubits in the
system
ignore_incompatible_terms(bool): This flag determines the behavior
of this method when it encounters terms that are not represented
by the DiagonalCoulombHamiltonian class, namely, terms that are
not quadratic and not quartic of the form
a^\dagger_p a_p a^\dagger_q a_q. If set to True, this method will
simply ignore those terms. If False, then this method will raise
an error if it encounters such a term. The default setting is False.
"""
if not isinstance(fermion_operator, FermionOperator):
raise TypeError('Input must be a FermionOperator.')
check_no_sympy(fermion_operator)
if n_qubits is None:
n_qubits = op_utils.count_qubits(fermion_operator)
if n_qubits < op_utils.count_qubits(fermion_operator):
raise ValueError('Invalid number of qubits specified.')
fermion_operator = normal_ordered(fermion_operator)
constant = 0.0
one_body = numpy.zeros((n_qubits, n_qubits), complex)
two_body = numpy.zeros((n_qubits, n_qubits), float)
for term, coefficient in fermion_operator.terms.items():
# Ignore this term if the coefficient is zero
if abs(coefficient) < EQ_TOLERANCE:
# not testable because normal_ordered kills
# fermion terms lower than EQ_TOLERANCE
continue # pragma: no cover
if len(term) == 0:
constant = coefficient
else:
actions = [operator[1] for operator in term]
if actions == [1, 0]:
p, q = [operator[0] for operator in term]
one_body[p, q] = coefficient
elif actions == [1, 1, 0, 0]:
p, q, r, s = [operator[0] for operator in term]
if p == r and q == s:
if abs(numpy.imag(coefficient)) > EQ_TOLERANCE:
raise ValueError(
'FermionOperator does not map to '
'DiagonalCoulombHamiltonian (not Hermitian).'
)
coefficient = numpy.real(coefficient)
two_body[p, q] = -0.5 * coefficient
two_body[q, p] = -0.5 * coefficient
elif not ignore_incompatible_terms:
raise ValueError(
'FermionOperator does not map to '
'DiagonalCoulombHamiltonian '
'(contains terms with indices '
'{}).'.format((p, q, r, s))
)
elif not ignore_incompatible_terms:
raise ValueError(
'FermionOperator does not map to '
'DiagonalCoulombHamiltonian (contains terms '
'with action {}.'.format(tuple(actions))
)
# Check that the operator is Hermitian
if not op_utils.is_hermitian(one_body):
raise ValueError(
'FermionOperator does not map to DiagonalCoulombHamiltonian ' '(not Hermitian).'
)
return DiagonalCoulombHamiltonian(one_body, two_body, constant)
def get_interaction_operator(fermion_operator, n_qubits=None):
r"""Convert a 2-body fermionic operator to InteractionOperator.
This function should only be called on fermionic operators which
consist of only a_p^\dagger a_q and a_p^\dagger a_q^\dagger a_r a_s
terms. The one-body terms are stored in a matrix, one_body[p, q], and
the two-body terms are stored in a tensor, two_body[p, q, r, s].
Returns:
interaction_operator: An instance of the InteractionOperator class.
Raises:
TypeError: Input must be a FermionOperator.
TypeError: FermionOperator does not map to InteractionOperator.
Warning:
Even assuming that each creation or annihilation operator appears
at most a constant number of times in the original operator, the
runtime of this method is exponential in the number of qubits.
"""
if not isinstance(fermion_operator, FermionOperator):
raise TypeError('Input must be a FermionOperator.')
check_no_sympy(fermion_operator)
if n_qubits is None:
n_qubits = op_utils.count_qubits(fermion_operator)
if n_qubits < op_utils.count_qubits(fermion_operator):
raise ValueError('Invalid number of qubits specified.')
# Normal order the terms and initialize.
fermion_operator = normal_ordered(fermion_operator)
constant = 0.0
one_body = numpy.zeros((n_qubits, n_qubits), complex)
two_body = numpy.zeros((n_qubits, n_qubits, n_qubits, n_qubits), complex)
# Loop through terms and assign to matrix.
for term in fermion_operator.terms:
coefficient = fermion_operator.terms[term]
# Ignore this term if the coefficient is zero
if abs(coefficient) < EQ_TOLERANCE:
# not testable because normal_ordered kills
# fermion terms lower than EQ_TOLERANCE
continue # pragma: no cover
# Handle constant shift.
if len(term) == 0:
constant = coefficient
elif len(term) == 2:
# Handle one-body terms.
if [operator[1] for operator in term] == [1, 0]:
p, q = [operator[0] for operator in term]
one_body[p, q] = coefficient
else:
raise InteractionOperatorError(
'FermionOperator does not map ' 'to InteractionOperator.'
)
elif len(term) == 4:
# Handle two-body terms.
if [operator[1] for operator in term] == [1, 1, 0, 0]:
p, q, r, s = [operator[0] for operator in term]
two_body[p, q, r, s] = coefficient
else:
raise InteractionOperatorError(
'FermionOperator does not map ' 'to InteractionOperator.'
)
else:
# Handle non-molecular Hamiltonian.
raise InteractionOperatorError(
'FermionOperator does not map ' 'to InteractionOperator.'
)
# Form InteractionOperator and return.
interaction_operator = InteractionOperator(constant, one_body, two_body)
return interaction_operator
def get_molecular_data(
interaction_operator,
geometry=None,
basis=None,
multiplicity=None,
n_electrons=None,
reduce_spin=True,
data_directory=None,
):
"""Output a MolecularData object generated from an InteractionOperator
Args:
interaction_operator(InteractionOperator): two-body interaction
operator defining the "molecular interaction" to be simulated.
geometry(string or list of atoms):
basis(string): String denoting the basis set used to discretize the
system.
multiplicity(int): Spin multiplicity desired in the system.
n_electrons(int): Number of electrons in the system
reduce_spin(bool): True if one wishes to perform spin reduction on
integrals that are given in interaction operator. Assumes
spatial (x) spin structure generically.
Returns:
molecule(MolecularData):
Instance that captures the
interaction_operator converted into the format that would come
from an electronic structure package adorned with some meta-data
that may be useful.
"""
n_spin_orbitals = interaction_operator.n_qubits
# Introduce bare molecular operator to fill
molecule = MolecularData(
geometry=geometry, basis=basis, multiplicity=multiplicity, data_directory=data_directory
)
molecule.nuclear_repulsion = interaction_operator.constant
# Remove spin from integrals and put into molecular operator
if reduce_spin:
reduction_indices = list(range(0, n_spin_orbitals, 2))
else:
reduction_indices = list(range(n_spin_orbitals))
molecule.n_orbitals = len(reduction_indices)
molecule.one_body_integrals = interaction_operator.one_body_tensor[
numpy.ix_(reduction_indices, reduction_indices)
]
molecule.two_body_integrals = interaction_operator.two_body_tensor[
numpy.ix_(reduction_indices, reduction_indices, reduction_indices, reduction_indices)
]
# Fill in other metadata
molecule.overlap_integrals = numpy.eye(molecule.n_orbitals)
molecule.n_qubits = n_spin_orbitals
molecule.n_electrons = n_electrons
molecule.multiplicity = multiplicity
return molecule