PennyLaneAI / pennylane

PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
https://pennylane.ai
Apache License 2.0
2.27k stars 585 forks source link

Raise correct error when no shots are set when getting `counts` #2931

Closed Qottmann closed 2 years ago

Qottmann commented 2 years ago

Ideally, when a user wants to return counts but forgets to set counts, the error message would point to that. Currently the error message is somewhat cryptic:

dev = qml.device("default.qubit", wires=range(3)) # , shots=1000
@qml.qnode(dev, diff_method="parameter-shift")
def qnode(x):
    qml.RX(x,1)
    return qml.counts()

>>> qnode(0.5)
(..)
File ~/anaconda3/envs/pennylane/lib/python3.8/site-packages/pennylane/_qubit_device.py:1479, in QubitDevice.sample.<locals>._samples_to_counts(samples, no_observable_provided)
   1463 """Group the obtained samples into a dictionary.
   1464 
   1465 **Example**
   (...)
   1472     {'111':1, '001':2}
   1473 """
   1474 if no_observable_provided:
   1475     # If we describe a state vector, we need to convert its list representation
   1476     # into string (it's hashable and good-looking).
   1477     # Before converting to str, we need to extract elements from arrays
   1478     # to satisfy the case of jax interface, as jax arrays do not support str.
-> 1479     samples = ["".join([str(s.item()) for s in sample]) for sample in samples]
   1481 states, counts = np.unique(samples, return_counts=True)
   1482 return dict(zip(states, counts))

TypeError: 'NoneType' object is not iterable

I didnt know right away where to raise this error in qubit device because as I understand there are cases for sample where infinite shots are allowed?

AlbertMitjans commented 2 years ago

This should be fixed by PR https://github.com/PennyLaneAI/pennylane/pull/2928. Closing issue.