Skip to content

Commit 3a27def

Browse files
authored
Fix a number of CodeQL code-scanning alerts (#1074)
This addresses a number of alerts by CodeQL. Many more remain, but at least it's a start.
1 parent fc05585 commit 3a27def

16 files changed

Lines changed: 68 additions & 34 deletions

File tree

setup.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,28 @@
1111
# limitations under the License.
1212

1313
import os
14+
import runpy
1415

1516
from setuptools import find_packages, setup
1617

1718
# This reads the __version__ variable from openfermion/_version.py
18-
__version__ = ''
19-
exec(open('src/openfermion/_version.py').read())
19+
__version__ = runpy.run_path('src/openfermion/_version.py')['__version__']
20+
assert __version__, 'Version string cannot be empty'
2021

21-
# Readme file as long_description:
22+
# The readme file is used as the long_description:
2223
long_description = '===========\n' + 'OpenFermion\n' + '===========\n\n'
2324
with open('README.rst', 'r', encoding='utf-8') as readme:
2425
long_description += readme.read()
2526

26-
# Read in package requirements.txt
27-
requirements = open('dev_tools/requirements/deps/runtime.txt').readlines()
27+
# Read in package requirements.txt.
28+
with open('dev_tools/requirements/deps/runtime.txt') as r:
29+
requirements = r.readlines()
2830
requirements = [r.strip() for r in requirements]
2931
requirements = [r for r in requirements if not r.startswith('#')]
30-
# Resource estimates requirements.
31-
resource_requirements = open(
32-
'dev_tools/requirements/deps/resource_estimates_runtime.txt'
33-
).readlines()
32+
33+
# Read in resource estimates requirements.
34+
with open('dev_tools/requirements/deps/resource_estimates_runtime.txt') as r:
35+
resource_requirements = r.readlines()
3436
resource_requirements = [r.strip() for r in resource_requirements]
3537
resource_requirements = [r for r in resource_requirements if not r.startswith('#')]
3638

src/openfermion/chem/molecular_data.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,7 @@ def save(self):
841841
try:
842842
os.remove("{}.hdf5".format(self.filename))
843843
except OSError:
844+
# Nothing to do but carry on.
844845
pass
845846

846847
shutil.move("{}.hdf5".format(tmp_name), "{}.hdf5".format(self.filename))

src/openfermion/chem/molecular_data_test.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,7 @@ def test_name_molecule(self):
8181

8282
# Check errors in naming
8383
with self.assertRaises(TypeError):
84-
test_molecule = MolecularData(
85-
self.geometry, self.basis, self.multiplicity, description=5
86-
)
84+
MolecularData(self.geometry, self.basis, self.multiplicity, description=5)
8785
correct_name = str('H2_sto-3g_singlet')
8886
test_molecule = self.molecule = MolecularData(
8987
self.geometry, self.basis, self.multiplicity, data_directory=DATA_DIRECTORY
@@ -222,11 +220,9 @@ def test_active_space(self):
222220
"""Test simple active space truncation features"""
223221

224222
# Start w/ no truncation
225-
(
226-
core_const,
227-
one_body_integrals,
228-
two_body_integrals,
229-
) = self.molecule.get_active_space_integrals(active_indices=[0, 1])
223+
(core_const, one_body_integrals, two_body_integrals) = (
224+
self.molecule.get_active_space_integrals(active_indices=[0, 1])
225+
)
230226

231227
self.assertAlmostEqual(core_const, 0.0)
232228
self.assertAlmostEqual(

src/openfermion/circuits/gates/four_qubit_gates.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,10 @@ def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.Circ
120120
if args.use_unicode_characters:
121121
wire_symbols = ('⇅', '⇅', '⇵', '⇵')
122122
else:
123-
# pylint: disable=anomalous-backslash-in-string
124-
wire_symbols = (r'/\ \/', r'/\ \/', '\/ /\\', '\/ /\\')
123+
up_down = r'/\ \/'
124+
# Split up this string to avoid SyntaxError in Python 3.12.
125+
down_up = r'\/ /' + '\\'
126+
wire_symbols = (up_down, up_down, down_up, down_up)
125127
return cirq.CircuitDiagramInfo(
126128
wire_symbols=wire_symbols, exponent=self._diagram_exponent(args)
127129
)

src/openfermion/circuits/primitives/optimal_givens_decomposition_test.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ def test_col_eliminate():
106106
# mixing U[1, 0] and U[0, 0]
107107
unitary_original = unitary.copy()
108108
gmat = givens_matrix_elements(unitary[0, 0], unitary[1, 0], which='right')
109-
vec = numpy.array([[unitary[0, 0]], [unitary[1, 0]]])
110109
fullgmat = create_givens(gmat, 0, 1, 3)
111110
zeroed_unitary = fullgmat.dot(unitary)
112111

src/openfermion/linalg/erpa.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Code to generate the eigenvalue problem for the ERPA equations"""
2+
23
from typing import Dict, Tuple, Union
34
from itertools import product
45
import numpy
@@ -11,7 +12,7 @@
1112
def erpa_eom_hamiltonian(
1213
h_ijkl: numpy.ndarray, tpdm: numpy.ndarray, p: int, q: int, r: int, s: int
1314
) -> Union[float, complex]:
14-
"""
15+
r"""
1516
Evaluate $\sum_{a,b,c,d}h_{a, b, d, c}<\psi[p^ q, [a^ b^ c d, r^ s]]\psi>$
1617
1718
Args:

src/openfermion/linalg/sparse_tools.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1162,6 +1162,8 @@ def single_quad_op_sparse(n_modes, mode, quadrature, hbar, trunc):
11621162
op = numpy.sqrt(hbar / 2) * (b + b.conj().T)
11631163
elif quadrature == 'p':
11641164
op = -1j * numpy.sqrt(hbar / 2) * (b - b.conj().T)
1165+
else:
1166+
raise ValueError(f'Invalid value {quadrature} for quadrature parameter.')
11651167

11661168
Id = [scipy.sparse.identity(trunc, dtype=complex, format='csc')]
11671169
operator_list = Id * mode + [op] + Id * (n_modes - mode - 1)

src/openfermion/linalg/sparse_tools_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,6 +1192,11 @@ def test_single_quad_two_mode(self):
11921192
expected = numpy.kron(self.Id, self.p)
11931193
self.assertTrue(numpy.allclose(res, expected))
11941194

1195+
def test_single_quad_op_sparse_invalid_quadrature(self):
1196+
"""Test ValueError for invalid quadrature in single_quad_op_sparse."""
1197+
with self.assertRaisesRegex(ValueError, "Invalid value x for quadrature parameter."):
1198+
single_quad_op_sparse(n_modes=1, mode=0, quadrature='x', hbar=1.0, trunc=2)
1199+
11951200
def test_boson_operator_sparse_trunc(self):
11961201
op = BosonOperator('0')
11971202
with self.assertRaises(ValueError):

src/openfermion/linalg/wave_fitting.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def fit_known_frequencies(
4040

4141

4242
def prony(signal: numpy.ndarray) -> Tuple[numpy.ndarray, numpy.ndarray]:
43-
"""Estimates amplitudes and phases of a sparse signal using Prony's method.
43+
r"""Estimates amplitudes and phases of a sparse signal using Prony's method.
4444
4545
Single-ancilla quantum phase estimation returns a signal
4646
$g(k)=\sum (aj*exp(i*k*phij))$, where aj and phij are the amplitudes

src/openfermion/linalg/wedge_product.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def generate_parity_permutations(seq):
6767

6868

6969
def wedge(left_tensor, right_tensor, left_index_ranks, right_index_ranks):
70-
"""
70+
r"""
7171
Implement the wedge product between left_tensor and right_tensor
7272
7373
The wedge product is defined as

0 commit comments

Comments
 (0)