Repository: PennyLaneAI/pennylane
Pull request #3364 (2022-11-15 23:33:13)

Add string representation for Molecule class
**Context:** Adds string representation for the molecule via `__repr__` method

**Description of the Change:**
```
>>> symbols  = ['H', 'H']
>>> geometry = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]], requires_grad = False)
>>> mol = qml.qchem.Molecule(symbols, geometry)
<Molecule = H2 charge: 0 basis: STO-3G n_orbs: 4 n_elec: 2>
```


github-actions[bot]: Hello. You may have forgotten to update the changelog!
Please edit [`doc/releases/changelog-dev.md`](/PennyLaneAI/pennylane/blob/master/doc/releases/changelog-dev.md) with:
* A one-to-two sentence description of the change. You may include a small working example for new features.
* A link back to this PR.
* Your name (or GitHub username) in the contributors section.
codecov[bot]: # [Codecov](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3364?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) Report
> Merging [#3364](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3364?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) (03d90f3) into [master](https://codecov.io/gh/PennyLaneAI/pennylane/commit/3144cced0e7ff5698b92411eb4f366ea786c542a?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) (3144cce) will **increase** coverage by `0.00%`.
> The diff coverage is `100.00%`.

```diff
@@           Coverage Diff           @@
##           master    #3364   +/-   ##
=======================================
  Coverage   99.70%   99.70%           
=======================================
  Files         299      299           
  Lines       26146    26154    +8     
=======================================
+ Hits        26068    26076    +8     
  Misses         78       78           
```


| [Impacted Files](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3364?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI) | Coverage Δ | |
|---|---|---|
| [pennylane/qchem/molecule.py](https://codecov.io/gh/PennyLaneAI/pennylane/pull/3364/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI#diff-cGVubnlsYW5lL3FjaGVtL21vbGVjdWxlLnB5) | `100.00% <100.00%> (ø)` | |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PennyLaneAI)


Patch:
diff --git a/doc/releases/changelog-dev.md b/doc/releases/changelog-dev.md
index 2d2daad84..2aeff87e8 100644
--- a/doc/releases/changelog-dev.md
+++ b/doc/releases/changelog-dev.md
@@ -9,6 +9,9 @@
 
 <h3>Improvements</h3>
 
+* A representation has been added to the `Molecule` class.
+  [#3364](https://github.com/PennyLaneAI/pennylane/pull/3364)
+
 <h3>Breaking changes</h3>
 
 <h3>Deprecations</h3>
diff --git a/pennylane/qchem/molecule.py b/pennylane/qchem/molecule.py
index 5ea852ca8..402effb46 100644
--- a/pennylane/qchem/molecule.py
+++ b/pennylane/qchem/molecule.py
@@ -18,6 +18,7 @@ the necessary information to perform a Hartree-Fock calculation for a given mole
 """
 # pylint: disable=too-few-public-methods, too-many-arguments, too-many-instance-attributes
 import itertools
+import collections
 
 from pennylane import numpy as np
 
@@ -130,6 +131,17 @@ class Molecule:
 
         self.mo_coefficients = None
 
+    def __repr__(self):
+        """Returns the molecule representation in string format"""
+
+        elements, counter, flags = set(self.symbols), collections.Counter(self.symbols), []
+        if counter["C"]:  # Hill Notation
+            flags = ["C", "H"] if counter["H"] else ["C"]
+        ordered_elems = flags + list(sorted(elements.difference(set(flags))))
+        formula = "".join([x + str(counter[x]) if counter[x] > 1 else x for x in ordered_elems])
+
+        return f"<Molecule = {formula}, Charge: {self.charge}, Basis: {self.basis_name.upper()}, Orbitals: {self.n_orbitals}, Electrons: {self.n_electrons}>"
+
     def atomic_orbital(self, index):
         r"""Return a function that evaluates an atomic orbital at a given position.
 


Test patch:
diff --git a/tests/qchem/test_molecule.py b/tests/qchem/test_molecule.py
index 42a4cbbc0..d9523fa41 100644
--- a/tests/qchem/test_molecule.py
+++ b/tests/qchem/test_molecule.py
@@ -253,3 +253,26 @@ class TestMolecule:
         mo_value = mo(x, y, z)
 
         assert np.allclose(mo_value, ref_value)
+
+    def test_repr(self):
+        """Test that __repr__ for Molecule returns correct representation."""
+
+        symbols, geometry = (
+            ["H", "H", "H"],
+            np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 2.0]]),
+        )
+        mol = qchem.Molecule(symbols, geometry, 1)
+        assert repr(mol) == "<Molecule = H3, Charge: 1, Basis: STO-3G, Orbitals: 3, Electrons: 2>"
+
+        symbols, geometry = (
+            ["H", "C", "O"],
+            np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 2.0]]),
+        )
+        mol = qchem.Molecule(symbols, geometry, 0)
+        assert (
+            repr(mol) == "<Molecule = CHO, Charge: 0, Basis: STO-3G, Orbitals: 11, Electrons: 15>"
+        )
+
+        symbols, geometry = (["C", "O"], np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]))
+        mol = qchem.Molecule(symbols, geometry, 0)
+        assert repr(mol) == "<Molecule = CO, Charge: 0, Basis: STO-3G, Orbitals: 10, Electrons: 14>"