Repository: quantumlib/OpenFermion
Pull request #569 (2020-03-05 20:29:56)

Reformat lines that are too long

vtomole: @viathor Line covered. PTAL.
vtomole: @kevinsung I still can't merge.
kevinsung: @vtomole I removed you and re-invited you as a collaborator. Let's see if that does anything. If not, I'll complain to GitHub.

Patch:
diff --git a/dev_tools/conf/.pylintrc b/dev_tools/conf/.pylintrc
index ca39551..2cf56b9 100644
--- a/dev_tools/conf/.pylintrc
+++ b/dev_tools/conf/.pylintrc
@@ -6,6 +6,8 @@ output-format=colorized
 score=no
 reports=no
 enable=
+    init-is-generator,
+    line-too-long,
     anomalous-backslash-in-string,
     assert-on-tuple,
     bad-indentation,
diff --git a/src/openfermion/hamiltonians/_general_hubbard.py b/src/openfermion/hamiltonians/_general_hubbard.py
index 2da88b4..c8cf3cb 100644
--- a/src/openfermion/hamiltonians/_general_hubbard.py
+++ b/src/openfermion/hamiltonians/_general_hubbard.py
@@ -211,7 +211,8 @@ class FermiHubbardModel:
 
         where
 
-            - :math:`(a, b)` is the pair of degrees of freedom given by ``dofs``;
+            - :math:`(a, b)` is the pair of degrees
+            of freedom given by ``dofs``;
             - :math:`E^{(\mathrm{edge type})}` is the set of ordered pairs of
               site indices returned by ``lattice.site_pairs_iter(edge_type, a !=
               b)``; and
@@ -222,25 +223,31 @@ class FermiHubbardModel:
         optional, and will default to ``SpinPairs.ALL``. In any case, it is
         ignored for spinless lattices.
 
-        For example, in the spinful model if `dofs` indicates distinct degrees of freedom then the parameter corresponds to the terms
+        For example, in the spinful model if `dofs`
+        indicates distinct degrees of freedom then the
+        parameter corresponds to the terms
 
         .. math::
-
-            U \sum_{(i, j) \in E^{(\mathrm{edge type})}} \sum_{(\sigma, \sigma')}
-            n_{i, a, \sigma} n_{j, b, \sigma'}
+        U \sum_{(i, j) \in E^{(\mathrm{edge type})}} \sum_{(\sigma, \sigma')}
+        n_{i, a, \sigma} n_{j, b, \sigma'}
 
         where
 
-            - :math:`(a, b)` is the pair of degrees of freedom given by ``dofs``;
+            - :math:`(a, b)` is the pair of degrees of
+            freedom given by ``dofs``;
             - :math:`E^{(\mathrm{edge type})}` is the set of ordered pairs of
               site indices returned by ``lattice.site_pairs_iter(edge_type)``;
             - :math:`U` is the ``coefficient``; and
             - :math:`(\sigma, \sigma')` runs over
-                - all four possible pairs of spins if `spin_pairs == SpinPairs.ALL`,
-                - :math:`\{(\uparrow, \downarrow), (\downarrow, \uparrow)\}` if `spin_pairs == SpinPairs.DIFF`, and
-                - :math:`\{(\uparrow, \uparrow), (\downarrow, \downarrow)\}' if 'spin_pairs == SpinPairs.SAME`.
+                - all four possible pairs of spins
+                if `spin_pairs == SpinPairs.ALL`,
+                - :math:`\{(\uparrow, \downarrow), (\downarrow, \uparrow)\}`
+                if `spin_pairs == SpinPairs.DIFF`, and
+                - :math:`\{(\uparrow, \uparrow), (\downarrow, \downarrow)\}'
+                if 'spin_pairs == SpinPairs.SAME`.
 
-        Each potential parameter is a tuple ``(dof, coefficient)``. For example, in the spinful model, it corresponds to the terms
+        Each potential parameter is a tuple ``(dof, coefficient)``.
+        For example, in the spinful model, it corresponds to the terms
 
         .. math::
             -\mu \sum_{i} \sum_{\sigma} n_{i, a, \sigma},
@@ -366,7 +373,8 @@ class FermiHubbardModel:
         for site_index in self.lattice.site_indices:
             for dof in self.lattice.dof_indices:
                 i = self.lattice.to_spin_orbital_index(site_index, dof, Spin.UP)
-                j = self.lattice.to_spin_orbital_index(site_index, dof, Spin.DOWN)
+                j = self.lattice.to_spin_orbital_index(site_index, dof,
+                                                       Spin.DOWN)
                 terms += number_difference_operator(i, j, -self.magnetic_field)
         return terms
 
diff --git a/src/openfermion/measurements/_prony.py b/src/openfermion/measurements/_prony.py
index c12e29f..2ac90af 100644
--- a/src/openfermion/measurements/_prony.py
+++ b/src/openfermion/measurements/_prony.py
@@ -31,8 +31,8 @@ def prony(signal):
         signal(1d complex array): the signal to fit
 
     Returns:
-        amplitudes(list of complex values): the amplitudes a_i, in descending order
-            by their complex magnitude
+        amplitudes(list of complex values): the amplitudes a_i,
+        in descending order by their complex magnitude
         phases(list of complex values): the complex frequencies gamma_i,
             correlated with amplitudes.
     """
diff --git a/src/openfermion/ops/_interaction_operator.py b/src/openfermion/ops/_interaction_operator.py
index e142fd2..4ccb330 100644
--- a/src/openfermion/ops/_interaction_operator.py
+++ b/src/openfermion/ops/_interaction_operator.py
@@ -39,10 +39,12 @@ class InteractionOperator(PolynomialTensor):
             \sum_{p, q, r, s} h_{p, q, r, s} a^\dagger_p a^\dagger_q a_r a_s.
 
     Attributes:
-        one_body_tensor: The coefficients of the one-body terms (:math:`h_{p, q}`).
-            This is an n_qubits x n_qubits numpy array of floats.
+        one_body_tensor: The coefficients of the one-body terms
+        (:math:`h_{p, q}`). This is an n_qubits x n_qubits
+        numpy array of floats.
         two_body_tensor: The coefficients of the two-body terms
-            (:math:`h_{p, q, r, s}`). This is an n_qubits x n_qubits x n_qubits x
+            (:math:`h_{p, q, r, s}`).
+            This is an n_qubits x n_qubits x n_qubits x
             n_qubits numpy array of floats.
     """
 
@@ -53,10 +55,12 @@ class InteractionOperator(PolynomialTensor):
         Args:
             constant: A constant term in the operator given as a
                 float. For instance, the nuclear repulsion energy.
-            one_body_tensor: The coefficients of the one-body terms (:math:`h_{p,q}`).
+            one_body_tensor: The coefficients of the one-body terms
+                (:math:`h_{p,q}`).
                This is an n_qubits x n_qubits numpy array of floats.
             two_body_tensor: The coefficients of the two-body terms
-                (:math:`h_{p, q, r, s}`). This is an n_qubits x n_qubits x n_qubits x
+                (:math:`h_{p, q, r, s}`).
+                This is an n_qubits x n_qubits x n_qubits x
                 n_qubits numpy array of floats.
         """
         # Make sure nonzero elements are only for normal ordered terms.
diff --git a/src/openfermion/transforms/_conversion.py b/src/openfermion/transforms/_conversion.py
index 80fe213..47c46ec 100644
--- a/src/openfermion/transforms/_conversion.py
+++ b/src/openfermion/transforms/_conversion.py
@@ -621,8 +621,10 @@ def get_number_preserving_sparse_operator(
 
     state_array = numpy.asarray(list(_iterate_basis_(
         reference_determinant, excitation_level, spin_preserving)))
-    # Create a 1d array with each determinant encoded as an integer for sorting purposes.
-    int_state_array = state_array.dot(1 << numpy.arange(state_array.shape[1])[::-1])
+    # Create a 1d array with each determinant encoded
+    # as an integer for sorting purposes.
+    int_state_array = state_array.dot(
+        1 << numpy.arange(state_array.shape[1])[::-1])
     sorting_indices = numpy.argsort(int_state_array)
 
     space_size = state_array.shape[0]
@@ -670,7 +672,8 @@ def _iterate_basis_(reference_determinant, excitation_level, spin_preserving):
     """
     if not spin_preserving:
         for order in range(excitation_level + 1):
-            for determinant in _iterate_basis_order_(reference_determinant, order):
+            for determinant in _iterate_basis_order_(reference_determinant,
+                                                     order):
                 yield determinant
 
     else:
@@ -832,8 +835,9 @@ def _build_term_op_(term, state_array, int_state_array, sorting_indices):
     # creation and annihilation operators specified in term.
     maybe_valid_states = numpy.where(
         numpy.logical_and(
-            numpy.all(state_array[:,needs_to_be_occupied], axis=1),
-            numpy.logical_not(numpy.any(state_array[:, needs_to_be_unoccupied], axis=1))))[0]
+            numpy.all(state_array[:, needs_to_be_occupied], axis=1),
+            numpy.logical_not(
+                numpy.any(state_array[:, needs_to_be_unoccupied], axis=1))))[0]
 
     data = []
     row_ind = []
diff --git a/src/openfermion/transforms/_jordan_wigner.py b/src/openfermion/transforms/_jordan_wigner.py
index 15a2e01..ebe2f4a 100644
--- a/src/openfermion/transforms/_jordan_wigner.py
+++ b/src/openfermion/transforms/_jordan_wigner.py
@@ -152,7 +152,8 @@ def jordan_wigner_interaction_op(iop, n_qubits=None):
     # Transform other one-body terms and "diagonal" two-body terms
     for p, q in itertools.combinations(range(n_qubits), 2):
         # One-body
-        coefficient = .5 * (iop[(p, 1), (q, 0)] + iop[(q, 1), (p, 0)].conjugate())
+        coefficient = .5 * (iop[(p, 1), (q, 0)] + iop[(q, 1),
+                                                      (p, 0)].conjugate())
         qubit_operator += jordan_wigner_one_body(p, q, coefficient)
 
         # Two-body
diff --git a/src/openfermion/utils/_davidson.py b/src/openfermion/utils/_davidson.py
index 03eef59..d4a1c5d 100644
--- a/src/openfermion/utils/_davidson.py
+++ b/src/openfermion/utils/_davidson.py
@@ -23,7 +23,9 @@ import scipy.sparse
 import scipy.sparse.linalg
 
 from openfermion.utils._sparse_tools import get_linear_qubit_operator_diagonal
-from openfermion.utils._linear_qubit_operator import generate_linear_qubit_operator
+from openfermion.utils._linear_qubit_operator import \
+    generate_linear_qubit_operator
+
 
 class DavidsonError(Exception):
     """Exceptions."""
@@ -101,7 +103,8 @@ class Davidson(object):
             linear_operator.
 
         Args:
-            n(int): The number of states corresponding to the smallest eigenvalues
+            n(int):
+                The number of states corresponding to the smallest eigenvalues
                 and associated eigenvectors for the linear_operator.
             initial_guess(numpy.ndarray[complex]): Initial guess of eigenvectors
                 associated with the `n` smallest eigenvalues.
@@ -178,8 +181,8 @@ class Davidson(object):
             count_mvs = guess_mv.shape[1]
             guess_v = orthonormalize(guess_v, count_mvs, self.options.eps)
             if guess_v.shape[1] <= count_mvs:
-                guess_v = append_random_vectors(guess_v, n_lowest,
-                                                real_only=self.options.real_only)
+                guess_v = append_random_vectors(
+                    guess_v, n_lowest, real_only=self.options.real_only)
 
 
             # Limits number of vectors to self.options.max_subspace, in this
@@ -309,7 +312,8 @@ class Davidson(object):
                 # search for new directions.
                 continue
 
-            max_trial_error = max(max_trial_error, numpy.linalg.norm(current_error_v))
+            max_trial_error = max(max_trial_error,
+                                  numpy.linalg.norm(current_error_v))
             diagonal_inverse = numpy.ones(origonal_dimension)
             for j in range(origonal_dimension):
                 # Makes sure error vectors are bounded.
diff --git a/src/openfermion/utils/_grid.py b/src/openfermion/utils/_grid.py
index f72a16a..17a2060 100644
--- a/src/openfermion/utils/_grid.py
+++ b/src/openfermion/utils/_grid.py
@@ -218,7 +218,8 @@ class Grid:
         return momentum_vector
 
     def orbital_id(self, grid_coordinates, spin=None):
-        """Return the tensor factor of a orbital with given coordinates and spin.
+        """Return the tensor factor of a orbital
+        with given coordinates and spin.
 
         Args:
             grid_coordinates: List or tuple of ints giving coordinates of grid
diff --git a/src/openfermion/utils/_lattice.py b/src/openfermion/utils/_lattice.py
index e88fc20..563cd71 100644
--- a/src/openfermion/utils/_lattice.py
+++ b/src/openfermion/utils/_lattice.py
@@ -43,7 +43,8 @@ class HubbardLattice(metaclass=abc.ABCMeta):
             sites to themselves.
 
     And the following methods:
-        site_pairs_iter(edge_type: Hashable) -> Iterable[Tuple[int, int]]: Iterable
+        site_pairs_iter(edge_type: Hashable) \\
+            -> Iterable[Tuple[int, int]]: Iterable
             over pairs of sites corresponding to the given edge type.
 
     For 'spinful' lattices, the ``spin_indices`` ``0`` and ``1`` correspond to
@@ -52,7 +53,8 @@ class HubbardLattice(metaclass=abc.ABCMeta):
 
     @abc.abstractproperty
     def n_dofs(self):
-        """The number of degrees of freedom per site (and spin if applicable)."""
+        """The number of degrees of freedom per site
+        (and spin if applicable)."""
 
 
     @abc.abstractproperty
diff --git a/src/openfermion/utils/_operator_utils.py b/src/openfermion/utils/_operator_utils.py
index 3869564..e372752 100644
--- a/src/openfermion/utils/_operator_utils.py
+++ b/src/openfermion/utils/_operator_utils.py
@@ -965,7 +965,8 @@ def group_into_tensor_product_basis_sets(operator, seed=None):
             sub_operator = sub_operators.pop(basis)
             sub_operator += QubitOperator(term, coefficient)
             additions = tuple(op for op in term if op not in basis)
-            basis = tuple(sorted(basis + additions, key=lambda factor: factor[0]))
+            basis = tuple(
+                sorted(basis + additions, key=lambda factor: factor[0]))
             sub_operators[basis] = sub_operator
 
     return sub_operators
@@ -976,8 +977,8 @@ def _commutes(operator1,operator2):
 
 def _non_fully_commuting_terms(hamiltonian):
     terms = list([QubitOperator(key) for key in hamiltonian.terms.keys()])
-    T = [
-    ]  # will contain the subset of terms that do not commute universally in terms
+    T = []  # will contain the subset of terms that do not
+    # commute universally in terms
     for i in range(len(terms)):
         if any(not _commutes(terms[i],terms[j]) for j in range(len(terms))):
             T.append(terms[i])
@@ -996,12 +997,14 @@ def is_contextual(hamiltonian):
         boolean indicating whether hamiltonian is contextual or not.
     """
     T = _non_fully_commuting_terms(hamiltonian)
-    # Search in T for triples in which exactly one pair anticommutes; if any exist, hamiltonian is contextual.
-    for i in range(
-            len(T)
-    ):  # WLOG, i indexes the operator that (putatively) commutes with both others.
+    # Search in T for triples in which exactly one pair anticommutes;
+    # if any exist, hamiltonian is contextual.
+    for i in range(len(T)):  # WLOG, i indexes the operator that (putatively)
+        # commutes with both others.
         for j in range(len(T)):
             for k in range(j + 1, len(T)):  # Ordering of j, k does not matter.
-                if i!=j and i!=k and _commutes(T[i],T[j]) and _commutes(T[i],T[k]) and not _commutes(T[j],T[k]):
+                if i!=j and i!=k and _commutes(T[i],T[j]) \
+                    and _commutes(T[i],T[k]) and \
+                        not _commutes(T[j],T[k]):
                     return True
     return False
diff --git a/src/openfermion/utils/_pubchem.py b/src/openfermion/utils/_pubchem.py
index 6ede28e..dbe61dd 100644
--- a/src/openfermion/utils/_pubchem.py
+++ b/src/openfermion/utils/_pubchem.py
@@ -11,7 +11,7 @@
 #   limitations under the License.
 
 
-def geometry_from_pubchem(name, structure=None):
+def geometry_from_pubchem(name: str, structure: str = None):
     """Function to extract geometry using the molecule's name from the PubChem
     database. The 'structure' argument can be used to specify which structure
     info to use to extract the geometry. If structure=None, the geometry will
@@ -45,11 +45,13 @@ def geometry_from_pubchem(name, structure=None):
             pubchempy_molecule = pubchempy.get_compounds(name, 'name',
                                                         record_type='2d')
     else:
-        raise ValueError('Incorrect value for the argument structure=%s' % structure)
+        raise ValueError('Incorrect value for the argument structure=%s' %
+                         structure)
 
     # Check if pubchempy_molecule is an empty list or None
     if not pubchempy_molecule:
-        print('Unable to find structure info in the PubChem database for the specified molecule "%s".' % name)
+        print("Unable to find structure info in the PubChem database"
+              "for the specified molecule %s." % name)
         return None
 
     pubchempy_geometry = \
diff --git a/src/openfermion/utils/_special_operators.py b/src/openfermion/utils/_special_operators.py
index e2f173b..e086af9 100644
--- a/src/openfermion/utils/_special_operators.py
+++ b/src/openfermion/utils/_special_operators.py
@@ -282,8 +282,10 @@ def number_operator(n_modes, mode=None, coefficient=1., parity=-1):
         mode (int, optional): The mode on which to return the number
             operator. If None, return total number operator on all sites.
         coefficient (float): The coefficient of the term.
-        parity (int): Returns the fermionic number operator if parity=-1 (default),
-            and returns the bosonic number operator if parity=1.
+        parity (int): Returns the fermionic number operator
+                    if parity=-1 (default),
+                    and returns the bosonic number operator
+                    if parity=1.
     Returns:
         operator (BosonOperator or FermionOperator)
     """
diff --git a/src/openfermion/utils/_unitary_cc.py b/src/openfermion/utils/_unitary_cc.py
index 523aaa3..60f59c2 100644
--- a/src/openfermion/utils/_unitary_cc.py
+++ b/src/openfermion/utils/_unitary_cc.py
@@ -77,7 +77,8 @@ def uccsd_generator(single_amplitudes, double_amplitudes, anti_hermitian=True):
 
 
 def uccsd_convert_amplitude_format(single_amplitudes, double_amplitudes):
-    r"""Re-format single_amplitudes and double_amplitudes from ndarrays to lists.
+    r"""Re-format single_amplitudes and double_amplitudes from ndarrays
+        to lists.
 
     Args:
         single_amplitudes(ndarray): [NxN] array storing single excitation
diff --git a/src/openfermion/utils/_wedge_product.py b/src/openfermion/utils/_wedge_product.py
index 4b3b647..e58916f 100644
--- a/src/openfermion/utils/_wedge_product.py
+++ b/src/openfermion/utils/_wedge_product.py
@@ -124,8 +124,10 @@ def wedge(left_tensor, right_tensor, left_index_ranks, right_index_ranks):
         # <a^ b^ c d> = D_{dc}^{ab} in this code.
         n_upper_einsum_chars = upper_order_parities[0][:left_index_ranks[0]]
         m_upper_einsum_chars = upper_order_parities[0][left_index_ranks[0]:]
-        n_lower_einsum_chars = lower_order_parities[0][:left_index_ranks[1]][::-1]
-        m_lower_einsum_chars = lower_order_parities[0][left_index_ranks[1]:][::-1]
+        n_lower_einsum_chars = lower_order_parities[0] \
+            [:left_index_ranks[1]][::-1]
+        m_lower_einsum_chars = lower_order_parities[0] \
+            [left_index_ranks[1]:][::-1]
 
         n_string = "".join(n_upper_einsum_chars + n_lower_einsum_chars)
         m_string = "".join(m_upper_einsum_chars + m_lower_einsum_chars)


Test patch:
diff --git a/src/openfermion/hamiltonians/_general_hubbard_test.py b/src/openfermion/hamiltonians/_general_hubbard_test.py
index 3f2311b..4b5d6cf 100644
--- a/src/openfermion/hamiltonians/_general_hubbard_test.py
+++ b/src/openfermion/hamiltonians/_general_hubbard_test.py
@@ -72,7 +72,8 @@ def random_parameters(lattice, probability=0.5, distinguish_edges=False):
             for dofs in lattice.dof_pairs_iter(edge_type == 'onsite')
             if random.random() <= probability]
 
-    possible_spin_pairs = (SpinPairs.ALL,) if lattice.spinless else (SpinPairs.SAME, SpinPairs.DIFF)
+    possible_spin_pairs = (SpinPairs.ALL,) if lattice.spinless else (
+        SpinPairs.SAME, SpinPairs.DIFF)
     parameters['interaction_parameters'] = [
         (edge_type, dofs, random.uniform(-1, 1), spin_pairs)
         for edge_type in edge_types for spin_pairs in possible_spin_pairs
@@ -113,15 +114,19 @@ def test_fermi_hubbard_bad_parameters():
         FermiHubbardModel(lattice, interaction_parameters=[(0,) * 5])
     with pytest.raises(ValueError):
         interaction_parameters = [('onsite', (0, 0), 1, SpinPairs.SAME)]
-        FermiHubbardModel(lattice, interaction_parameters=interaction_parameters)
+        FermiHubbardModel(lattice,
+                          interaction_parameters=interaction_parameters)
+
+
+lattices = [
+    HubbardSquareLattice(random.randrange(3, 10),
+                         random.randrange(3, 10),
+                         periodic=periodic,
+                         spinless=spinless) for periodic in (False, True)
+    for spinless in (False, True) for _ in range(2)
+]
 
 
-lattices = [HubbardSquareLattice(random.randrange(3, 10), random.randrange(3, 10),
-                                 periodic=periodic, spinless=spinless)
-    for periodic in (False, True)
-    for spinless in (False, True)
-    for _ in range(2)
-    ]
 @pytest.mark.parametrize('lattice,parameters,distinguish_edges', [
     (lattice, random_parameters(lattice, distinguish_edges=distinguish_edges),
      distinguish_edges)
diff --git a/src/openfermion/ops/_interaction_operator_test.py b/src/openfermion/ops/_interaction_operator_test.py
index ff9cf6b..4359b58 100644
--- a/src/openfermion/ops/_interaction_operator_test.py
+++ b/src/openfermion/ops/_interaction_operator_test.py
@@ -79,12 +79,14 @@ class InteractionOperatorTest(unittest.TestCase):
         self.assertEqual(want_str, got_str)
 
     def test_addition(self):
-        interaction_op = InteractionOperator(0, numpy.ones((3, 3)), numpy.ones((3, 3, 3, 3)))
+        interaction_op = InteractionOperator(0, numpy.ones((3, 3)),
+                                             numpy.ones((3, 3, 3, 3)))
         summed_op = interaction_op + interaction_op
         self.assertTrue(numpy.array_equal(summed_op.one_body_tensor,
                                           summed_op.n_body_tensors[(1, 0)]))
-        self.assertTrue(numpy.array_equal(summed_op.two_body_tensor,
-                                          summed_op.n_body_tensors[(1, 1, 0, 0)]))
+        self.assertTrue(
+            numpy.array_equal(summed_op.two_body_tensor,
+                              summed_op.n_body_tensors[(1, 1, 0, 0)]))
 
     def test_neg(self):
         interaction_op = InteractionOperator(
@@ -95,32 +97,41 @@ class InteractionOperatorTest(unittest.TestCase):
                 0, -numpy.ones((3, 3)), -numpy.ones((3, 3, 3, 3)))
 
     def test_zero(self):
-        interaction_op = InteractionOperator(0, numpy.ones((3, 3)), numpy.ones((3, 3, 3, 3)))
-        assert InteractionOperator.zero(interaction_op.n_qubits) == interaction_op * 0
+        interaction_op = InteractionOperator(0, numpy.ones((3, 3)),
+                                             numpy.ones((3, 3, 3, 3)))
+        assert InteractionOperator.zero(
+            interaction_op.n_qubits) == interaction_op * 0
 
     def test_projected(self):
-        interaction_op = InteractionOperator(1, numpy.ones((3, 3)), numpy.ones((3, 3, 3, 3)))
-        projected_two_body_tensor = numpy.zeros_like(interaction_op.two_body_tensor)
+        interaction_op = InteractionOperator(1, numpy.ones((3, 3)),
+                                             numpy.ones((3, 3, 3, 3)))
+        projected_two_body_tensor = numpy.zeros_like(
+            interaction_op.two_body_tensor)
         for i in range(3):
             projected_two_body_tensor[(i,) * 4] = 1
-        projected_op = InteractionOperator(0, numpy.eye(3), projected_two_body_tensor)
+        projected_op = InteractionOperator(0, numpy.eye(3),
+                                           projected_two_body_tensor)
         assert projected_op == interaction_op.projected(1, exact=True)
         projected_op.constant = 1
         assert projected_op == interaction_op.projected(1, exact=False)
 
-        projected_op.one_body_tensor = numpy.zeros_like(interaction_op.one_body_tensor)
+        projected_op.one_body_tensor = numpy.zeros_like(
+            interaction_op.one_body_tensor)
         for pq in itertools.product(range(2), repeat=2):
             projected_op.one_body_tensor[pq] = 1
-        projected_op.two_body_tensor = numpy.zeros_like(interaction_op.two_body_tensor)
+        projected_op.two_body_tensor = numpy.zeros_like(
+            interaction_op.two_body_tensor)
         for pqrs in itertools.product(range(2), repeat=4):
             projected_op.two_body_tensor[pqrs] = 1
         assert projected_op == interaction_op.projected((0, 1), exact=False)
 
         projected_op.constant = 0
-        projected_op.one_body_tensor = numpy.zeros_like(interaction_op.one_body_tensor)
+        projected_op.one_body_tensor = numpy.zeros_like(
+            interaction_op.one_body_tensor)
         projected_op.one_body_tensor[0, 1] = 1
         projected_op.one_body_tensor[1, 0] = 1
-        projected_op.two_body_tensor = numpy.zeros_like(interaction_op.two_body_tensor)
+        projected_op.two_body_tensor = numpy.zeros_like(
+            interaction_op.two_body_tensor)
         for pqrs in itertools.product(range(2), repeat=4):
             if len(set(pqrs)) > 1:
                 projected_op.two_body_tensor[pqrs] = 1
diff --git a/src/openfermion/ops/_interaction_rdm_test.py b/src/openfermion/ops/_interaction_rdm_test.py
index 7ee70dd..379d333 100644
--- a/src/openfermion/ops/_interaction_rdm_test.py
+++ b/src/openfermion/ops/_interaction_rdm_test.py
@@ -68,5 +68,9 @@ class InteractionRDMTest(unittest.TestCase):
 
     def test_addition(self):
         rdm2 = self.rdm + self.rdm
-        self.assertTrue(numpy.array_equal(rdm2.one_body_tensor, rdm2.n_body_tensors[(1, 0)]))
-        self.assertTrue(numpy.array_equal(rdm2.two_body_tensor, rdm2.n_body_tensors[(1, 1, 0, 0)]))
+        self.assertTrue(
+            numpy.array_equal(rdm2.one_body_tensor,
+                              rdm2.n_body_tensors[(1, 0)]))
+        self.assertTrue(
+            numpy.array_equal(rdm2.two_body_tensor,
+                              rdm2.n_body_tensors[(1, 1, 0, 0)]))
diff --git a/src/openfermion/transforms/_conversion_test.py b/src/openfermion/transforms/_conversion_test.py
index fc5f887..4877d02 100644
--- a/src/openfermion/transforms/_conversion_test.py
+++ b/src/openfermion/transforms/_conversion_test.py
@@ -578,9 +578,11 @@ class GetNumberPreservingSparseOperatorIntegrationTestLiH(unittest.TestCase):
             self.molecule.n_electrons,
             spin_preserving=False)
 
-        assert scipy.sparse.linalg.norm(convert_after_adding - sum_sparse_n_op) < 1E-9
+        assert scipy.sparse.linalg.norm(convert_after_adding -
+                                        sum_sparse_n_op) < 1E-9
 
-        assert reference.dot(sum_sparse_n_op.dot(reference)) - self.molecule.n_electrons < 1E-9
+        assert reference.dot(sum_sparse_n_op.dot(reference)) - \
+            self.molecule.n_electrons < 1E-9
 
 
     def test_space_size_correct(self):
@@ -613,12 +615,14 @@ class GetNumberPreservingSparseOperatorIntegrationTestLiH(unittest.TestCase):
 
         sparse_hf_energy = reference.dot(sparse_ham.dot(reference))
 
-        assert numpy.linalg.norm(sparse_hf_energy - self.molecule.hf_energy) < 1E-9
+        assert numpy.linalg.norm(sparse_hf_energy -
+                                 self.molecule.hf_energy) < 1E-9
 
 
     def test_one_body_hf_energy(self):
         one_body_part = self.molecular_hamiltonian
-        one_body_part.two_body_tensor = numpy.zeros_like(one_body_part.two_body_tensor)
+        one_body_part.two_body_tensor = numpy.zeros_like(
+            one_body_part.two_body_tensor)
 
         one_body_fop = get_fermion_operator(one_body_part)
         one_body_regular_sparse_op = get_sparse_operator(one_body_fop)
@@ -630,7 +634,8 @@ class GetNumberPreservingSparseOperatorIntegrationTestLiH(unittest.TestCase):
         hf_state[0] = 1.0
         hf_state = make_hf_sparse_op.dot(hf_state)
 
-        regular_sparse_hf_energy = (hf_state.dot(one_body_regular_sparse_op.dot(hf_state))).real
+        regular_sparse_hf_energy = \
+            (hf_state.dot(one_body_regular_sparse_op.dot(hf_state))).real
 
         one_body_sparse_op = get_number_preserving_sparse_operator(
             one_body_fop,
@@ -644,7 +649,8 @@ class GetNumberPreservingSparseOperatorIntegrationTestLiH(unittest.TestCase):
 
         sparse_hf_energy = reference.dot(one_body_sparse_op.dot(reference))
 
-        assert numpy.linalg.norm(sparse_hf_energy - regular_sparse_hf_energy) < 1E-9
+        assert numpy.linalg.norm(sparse_hf_energy -
+                                 regular_sparse_hf_energy) < 1E-9
 
 
     def test_ground_state_energy(self):
@@ -769,7 +775,8 @@ class GetNumberPreservingSparseOperatorIntegrationTestLiH(unittest.TestCase):
             spin_preserving=True,
             excitation_level=1)
 
-        assert scipy.sparse.linalg.norm(sparse_op - sparse_op_conj.getH()) < 1E-9
+        assert scipy.sparse.linalg.norm(sparse_op -
+                                        sparse_op_conj.getH()) < 1E-9
 
 
     def test_singles_simple_two_body_term_hermitian(self):
@@ -790,7 +797,8 @@ class GetNumberPreservingSparseOperatorIntegrationTestLiH(unittest.TestCase):
             spin_preserving=True,
             excitation_level=1)
 
-        assert scipy.sparse.linalg.norm(sparse_op - sparse_op_conj.getH()) < 1E-9
+        assert scipy.sparse.linalg.norm(sparse_op -
+                                        sparse_op_conj.getH()) < 1E-9
 
 
     def test_singles_repeating_two_body_term_hermitian(self):
@@ -811,7 +819,8 @@ class GetNumberPreservingSparseOperatorIntegrationTestLiH(unittest.TestCase):
             spin_preserving=True,
             excitation_level=1)
 
-        assert scipy.sparse.linalg.norm(sparse_op - sparse_op_conj.getH()) < 1E-9
+        assert scipy.sparse.linalg.norm(sparse_op -
+                                        sparse_op_conj.getH()) < 1E-9
 
 
     def test_singles_ham_hermitian(self):
diff --git a/src/openfermion/utils/_davidson_test.py b/src/openfermion/utils/_davidson_test.py
index 944a613..a0786fd 100644
--- a/src/openfermion/utils/_davidson_test.py
+++ b/src/openfermion/utils/_davidson_test.py
@@ -282,7 +282,8 @@ class DavidsonTest(unittest.TestCase):
         success, eigen_values, _ = self.davidson.get_lowest_n(
             n_lowest, initial_guess, max_iterations=2)
         self.assertTrue(success)
-        self.assertTrue(numpy.allclose(eigen_values, self.eigen_values[:n_lowest]))
+        self.assertTrue(
+            numpy.allclose(eigen_values, self.eigen_values[:n_lowest]))
 
     def test_get_lowest_all(self):
         """Test for get_lowest_n() with n_lowest = 10."""
@@ -292,7 +293,9 @@ class DavidsonTest(unittest.TestCase):
         success, eigen_values, _ = self.davidson.get_lowest_n(
             n_lowest, initial_guess, max_iterations=1)
         self.assertTrue(success)
-        self.assertTrue(numpy.allclose(eigen_values, self.eigen_values[:n_lowest]))
+        self.assertTrue(
+            numpy.allclose(eigen_values, self.eigen_values[:n_lowest]))
+
 
 class QubitDavidsonTest(unittest.TestCase):
     """"Tests for QubitDavidson class with a QubitOperator."""
diff --git a/src/openfermion/utils/_lattice_test.py b/src/openfermion/utils/_lattice_test.py
index fdf73a9..54ffa9c 100644
--- a/src/openfermion/utils/_lattice_test.py
+++ b/src/openfermion/utils/_lattice_test.py
@@ -34,7 +34,9 @@ def test_hubbard_square_lattice(
             n_dofs=n_dofs, spinless=spinless, periodic=periodic)
 
     n_spin_values = 2 - spinless
-    sites = tuple((x, y) for y, x in itertools.product(range(y_dimension), range(x_dimension)))
+    sites = tuple(
+        (x, y)
+        for y, x in itertools.product(range(y_dimension), range(x_dimension)))
     site_indices = tuple(lattice.to_site_index(site) for site in sites)
     assert (sites == tuple(
         lattice.from_site_index(site_index) for site_index in site_indices))
@@ -63,7 +65,8 @@ def test_hubbard_square_lattice(
     for i, j in neighbor_pairs:
         assert sum(lattice.delta_mag(i, j, True)) == 1
 
-    assert len(tuple(lattice.dof_pairs_iter(False))) == n_dofs * (n_dofs + 1) / 2
+    assert len(tuple(lattice.dof_pairs_iter(False))) == \
+        n_dofs * (n_dofs + 1) / 2
     assert len(tuple(lattice.dof_pairs_iter(True))) == n_dofs * (n_dofs - 1) / 2
     spin_pairs_all = tuple(lattice.spin_pairs_iter())
     assert len(spin_pairs_all) == n_spin_values ** 2
diff --git a/src/openfermion/utils/_linear_qubit_operator_test.py b/src/openfermion/utils/_linear_qubit_operator_test.py
index 4a63f62..00b0163 100644
--- a/src/openfermion/utils/_linear_qubit_operator_test.py
+++ b/src/openfermion/utils/_linear_qubit_operator_test.py
@@ -204,7 +204,8 @@ class ParallelLinearQubitOperatorTest(unittest.TestCase):
 
     def test_init(self):
         """Tests __init__()."""
-        self.assertEqual(self.linear_operator.qubit_operator, self.qubit_operator)
+        self.assertEqual(self.linear_operator.qubit_operator,
+                         self.qubit_operator)
         self.assertEqual(self.linear_operator.n_qubits, self.n_qubits)
         self.assertIsNone(self.linear_operator.options.pool)
 
diff --git a/src/openfermion/utils/_operator_utils_test.py b/src/openfermion/utils/_operator_utils_test.py
index c9423db..0d1f84f 100644
--- a/src/openfermion/utils/_operator_utils_test.py
+++ b/src/openfermion/utils/_operator_utils_test.py
@@ -415,7 +415,8 @@ class HermitianConjugatedTest(unittest.TestCase):
             qubit_operator = jordan_wigner(operator)
             conjugate_operator = hermitian_conjugated(operator)
             conjugate_qubit_operator = jordan_wigner(conjugate_operator)
-            assert hermitian_conjugated(qubit_operator) == conjugate_qubit_operator
+            assert hermitian_conjugated(qubit_operator) == \
+                conjugate_qubit_operator
 
     def test_exceptions(self):
         with self.assertRaises(TypeError):
@@ -970,9 +971,15 @@ class IsContextualTest(unittest.TestCase):
         self.assertTrue(is_contextual(self.x1 + self.y1y2 + self.z1 + self.z2))
 
     def test_contextual_hamiltonians_with_extra_terms(self):
-        self.assertTrue(is_contextual(self.x1 + self.x2 + self.z1 + self.z2 + self.x3 + self.x4))
-        self.assertTrue(is_contextual(self.x1 + self.x1x2 + self.z1 + self.z2 + self.x3 + self.x4))
-        self.assertTrue(is_contextual(self.x1 + self.y1y2 + self.z1 + self.z2 + self.x3 + self.x4))
+        self.assertTrue(
+            is_contextual(self.x1 + self.x2 + self.z1 + self.z2 + self.x3 +
+                          self.x4))
+        self.assertTrue(
+            is_contextual(self.x1 + self.x1x2 + self.z1 + self.z2 + self.x3 +
+                          self.x4))
+        self.assertTrue(
+            is_contextual(self.x1 + self.y1y2 + self.z1 + self.z2 + self.x3 +
+                          self.x4))
 
     def test_commuting_hamiltonian(self):
         self.assertFalse(is_contextual(self.x1 + self.x2 + self.x3 + self.x4))
diff --git a/src/openfermion/utils/_pubchem_test.py b/src/openfermion/utils/_pubchem_test.py
index 16a8fb3..a397845 100644
--- a/src/openfermion/utils/_pubchem_test.py
+++ b/src/openfermion/utils/_pubchem_test.py
@@ -88,3 +88,7 @@ class OpenFermionPubChemTest(unittest.TestCase):
         z = 0
         self.assertEqual(z, self.oxygen_z_1)
         self.assertEqual(z, self.oxygen_z_2)
+
+        with pytest.raises(ValueError,
+                           match='Incorrect value for the argument structure'):
+            _ = geometry_from_pubchem('water', structure='foo')
diff --git a/src/openfermion/utils/_sparse_tools_test.py b/src/openfermion/utils/_sparse_tools_test.py
index 321fe04..87c4a6f 100644
--- a/src/openfermion/utils/_sparse_tools_test.py
+++ b/src/openfermion/utils/_sparse_tools_test.py
@@ -119,8 +119,10 @@ class JordanWignerSparseTest(unittest.TestCase):
         qubit_operator = QubitOperator.zero()
         vec_expected = numpy.zeros(8)
 
-        self.assertTrue(numpy.allclose(
-            get_linear_qubit_operator_diagonal(qubit_operator, 3), vec_expected))
+        self.assertTrue(
+            numpy.allclose(
+                get_linear_qubit_operator_diagonal(qubit_operator, 3),
+                vec_expected))
 
     def test_get_linear_qubit_operator_diagonal_zero(self):
         """Get zero diagonals from get_linear_qubit_operator_diagonal."""