From f5a59c7ec7e0fc268af5eaa12ed40464a307f3aa Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Wed, 14 Apr 2021 16:32:27 -0400 Subject: [PATCH] Fix 128 (Initialization with multi term FermionicOp) (#131) (#137) * fix 128 * add release note Co-authored-by: Manoel Marques Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> (cherry picked from commit 625939eb4014717ed9abf76b7c1e7899e8dfdc6c) Co-authored-by: Ikko Hamamura --- .../operators/second_quantization/fermionic_op.py | 2 +- .../bugfix-fermionicop-init-4005d72e38ba67f4.yaml | 5 +++++ .../operators/second_quantization/test_fermionic_op.py | 10 ++++++++-- 3 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 releasenotes/notes/bugfix-fermionicop-init-4005d72e38ba67f4.yaml diff --git a/qiskit_nature/operators/second_quantization/fermionic_op.py b/qiskit_nature/operators/second_quantization/fermionic_op.py index 7e0424047f..935cfb481d 100644 --- a/qiskit_nature/operators/second_quantization/fermionic_op.py +++ b/qiskit_nature/operators/second_quantization/fermionic_op.py @@ -205,8 +205,8 @@ def __init__( if invalid_labels: raise ValueError(f"Invalid labels for sparse labels are given: {invalid_labels}") list_label = [["I"] * self._register_length for _ in labels] - prev_index: Optional[int] = None for term, label in enumerate(labels): + prev_index: Optional[int] = None for split_label in label.split(): op_label, index_str = split_label.split("_", 1) index = int(index_str) diff --git a/releasenotes/notes/bugfix-fermionicop-init-4005d72e38ba67f4.yaml b/releasenotes/notes/bugfix-fermionicop-init-4005d72e38ba67f4.yaml new file mode 100644 index 0000000000..69a98bde57 --- /dev/null +++ b/releasenotes/notes/bugfix-fermionicop-init-4005d72e38ba67f4.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixed an issue where :class:`~qiskit_nature.operators.FermionicOp` raises + unwanted `ValueError` when initialized with some list of sparse label. diff --git a/test/operators/second_quantization/test_fermionic_op.py b/test/operators/second_quantization/test_fermionic_op.py index 09ca477f30..78f77468a5 100644 --- a/test/operators/second_quantization/test_fermionic_op.py +++ b/test/operators/second_quantization/test_fermionic_op.py @@ -95,8 +95,14 @@ def test_init_invalid_label(self, label, register_length): def test_init_multiterm(self): """Test __init__ with multi terms""" - labels = [("N", 2), ("-", 3.14)] - self.assertListEqual(FermionicOp(labels).to_list(), labels) + with self.subTest("Test 1"): + labels = [("N", 2), ("-", 3.14)] + self.assertListEqual(FermionicOp(labels).to_list(), labels) + + with self.subTest("Test 2"): + labels = [("+-", 1), ("-+", -1)] + op = FermionicOp([("+_0 -_1", 1.0), ("-_0 +_1", -1.0)], register_length=2) + self.assertListEqual(op.to_list(), labels) def test_init_multiple_digits(self): """Test __init__ for sparse label with multiple digits"""