Multiple measurements on a single wire

Hi, I had some trouble getting measurements of the quantum circuit.
I want to get measurements for a single wire.

My Pennylane version is

Name: PennyLane
Version: 0.32.0
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: https://github.com/PennyLaneAI/pennylane
Author: 
Author-email: 
License: Apache License 2.0
Location: c:\users\user1\anaconda3\envs\qsvdd\lib\site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml, typing-extensions
Required-by: PennyLane-Lightning

Platform info:           Windows-10-10.0.22621-SP0
Python version:          3.9.16
Numpy version:           1.23.5
Scipy version:           1.10.0
Installed devices:
- default.gaussian (PennyLane-0.28.0)
- default.mixed (PennyLane-0.28.0)
- default.qubit (PennyLane-0.28.0)
- default.qubit.autograd (PennyLane-0.28.0)
- default.qubit.jax (PennyLane-0.28.0)
- default.qubit.tf (PennyLane-0.28.0)
- default.qubit.torch (PennyLane-0.28.0)
- default.qutrit (PennyLane-0.28.0)
- null.qubit (PennyLane-0.28.0)
- lightning.qubit (PennyLane-Lightning-0.30.0)

The code I’m struggling with is

dev = qml.device("default.qubit", wires=4)

@qml.qnode(dev)
def circuit():
    qml.Hadamard(wires=0)
    return qml.expval(qml.PauliX(0)), qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))

print(circuit())

This yields the error about

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[191], line 8
      5     qml.Hadamard(wires=0)
      6     return qml.expval(qml.PauliX(0)), qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(0))
----> 8 print(circuit())

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\qnode.py:847, in QNode.__call__(self, *args, **kwargs)
    843     self._update_original_device()
    845     return res
--> 847 res = qml.execute(
    848     [self.tape],
    849     device=self.device,
    850     gradient_fn=self.gradient_fn,
    851     interface=self.interface,
    852     gradient_kwargs=self.gradient_kwargs,
    853     override_shots=override_shots,
    854     **self.execute_kwargs,
    855 )
    857 if old_interface == "auto":
    858     self.interface = "auto"

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\interfaces\execution.py:619, in execute(tapes, device, gradient_fn, interface, mode, gradient_kwargs, cache, cachesize, max_diff, override_shots, expand_fn, max_expansion, device_batch_transform)
    617 if device_batch_transform:
    618     dev_batch_transform = set_shots(device, override_shots)(device.batch_transform)
--> 619     tapes, batch_fn = qml.transforms.map_batch_transform(dev_batch_transform, tapes)
    620 else:
    621     batch_fn = lambda res: res

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\transforms\batch_transform.py:471, in map_batch_transform(transform, tapes)
    465 tape_counts = []
    467 for t in tapes:
    468     # Preprocess the tapes by applying batch transforms
    469     # to each tape, and storing corresponding tapes
    470     # for execution, processing functions, and list of tape lengths.
--> 471     new_tapes, fn = transform(t)
    472     execution_tapes.extend(new_tapes)
    473     batch_fns.append(fn)

File c:\Users\user1\anaconda3\envs\qsvdd\lib\contextlib.py:79, in ContextDecorator.__call__..inner(*args, **kwds)
     76 @wraps(func)
     77 def inner(*args, **kwds):
     78     with self._recreate_cm():
---> 79         return func(*args, **kwds)

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\_device.py:769, in Device.batch_transform(self, circuit)
    758     circuits, hamiltonian_fn = qml.transforms.sum_expand(circuit)
    760 elif (
    761     len(circuit._obs_sharing_wires) > 0
    762     and not hamiltonian_in_obs
   (...)
    767     # Check for case of non-commuting terms and that there are no Hamiltonians
    768     # TODO: allow for Hamiltonians in list of observables as well.
--> 769     circuits, hamiltonian_fn = qml.transforms.split_non_commuting(circuit)
    771 else:
    772     # otherwise, return the output of an identity transform
    773     circuits = [circuit]

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\transforms\batch_transform.py:331, in batch_transform.__call__(self, *targs, **tkwargs)
    326     return self._device_wrapper(*targs, **tkwargs)(qnode)
    328 if isinstance(qnode, qml.tape.QuantumScript):
    329     # Input is a quantum tape.
    330     # tapes, fn = some_transform(tape, *transform_args)
--> 331     return self._tape_wrapper(*targs, **tkwargs)(qnode)
    333 if isinstance(qnode, (qml.QNode, qml.ExpvalCost)):
    334     # Input is a QNode:
    335     # result = some_transform(qnode, *transform_args)(*qnode_args)
    336     wrapper = self.qnode_wrapper(qnode, targs, tkwargs)

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\transforms\batch_transform.py:421, in batch_transform._tape_wrapper..(tape)
    420 def _tape_wrapper(self, *targs, **tkwargs):
--> 421     return lambda tape: self.construct(tape, *targs, **tkwargs)

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\transforms\batch_transform.py:403, in batch_transform.construct(self, tape, *args, **kwargs)
    400 if expand and self.expand_fn is not None:
    401     tape = self.expand_fn(tape, *args, **kwargs)
--> 403 tapes, processing_fn = self.transform_fn(tape, *args, **kwargs)
    405 if processing_fn is None:
    407     def processing_fn(x):

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\transforms\split_non_commuting.py:160, in split_non_commuting(tape)
    157 obs_list = tape.observables
    159 # If there is more than one group of commuting observables, split tapes
--> 160 groups, group_coeffs = qml.pauli.group_observables(obs_list, range(len(obs_list)))
    161 if len(groups) > 1:
    162     # make one tape per commuting group
    163     tapes = []

File c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\pauli\grouping\group_observables.py:227, in group_observables(observables, coefficients, grouping_type, method)
    183 """Partitions a list of observables (Pauli operations and tensor products thereof) into
    184 groupings according to a binary relation (qubit-wise commuting, fully-commuting, or
    185 anticommuting).
   (...)
    223 [[0.97, 4.21], [1.43]]
    224 """
    226 if coefficients is not None:
--> 227     if qml.math.shape(coefficients)[0] != len(observables):
    228         raise IndexError(
    229             "The coefficients list must be the same length as the observables list."
    230         )
    232 pauli_grouping = PauliGroupingStrategy(
    233     observables, grouping_type=grouping_type, graph_colourer=method
    234 )

IndexError: tuple index out of range

The other code I implemented is

dev = qml.device("default.qubit", wires=4)

@qml.qnode(dev)
def circuit():
    qml.Hadamard(wires=0)
    return qml.expval(qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0))

print(circuit())

The error by this code is

Unexpected exception formatting exception. Falling back to standard exception
Traceback (most recent call last):
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\interactiveshell.py", line 3505, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "C:\Users\user1\AppData\Local\Temp\ipykernel_4752\1396563536.py", line 8, in <module>
    print(circuit())
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\qnode.py", line 800, in __call__
    return "adjoint", {}, device
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\qnode.py", line 711, in construct
    Returns:
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\pennylane\tape\qscript.py", line 1346, in wrapper
  File "C:\Users\user1\AppData\Local\Temp\ipykernel_4752\1396563536.py", line 6, in circuit
    return qml.expval(qml.PauliX(0), qml.PauliY(0), qml.PauliZ(0))
TypeError: expval() takes 1 positional argument but 3 were given

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\interactiveshell.py", line 2102, in showtraceback
    stb = self.InteractiveTB.structured_traceback(
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\ultratb.py", line 1310, in structured_traceback
    return FormattedTB.structured_traceback(
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\ultratb.py", line 1199, in structured_traceback
    return VerboseTB.structured_traceback(
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\ultratb.py", line 1052, in structured_traceback
    formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\ultratb.py", line 978, in format_exception_as_a_whole
    frames.append(self.format_record(record))
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\ultratb.py", line 878, in format_record
    frame_info.lines, Colors, self.has_colors, lvals
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\IPython\core\ultratb.py", line 712, in lines
    return self._sd.lines
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\stack_data\utils.py", line 145, in cached_property_wrapper
    value = obj.__dict__[self.func.__name__] = self.func(obj)
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\stack_data\core.py", line 698, in lines
    pieces = self.included_pieces
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\stack_data\utils.py", line 145, in cached_property_wrapper
    value = obj.__dict__[self.func.__name__] = self.func(obj)
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\stack_data\core.py", line 649, in included_pieces
    pos = scope_pieces.index(self.executing_piece)
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\stack_data\utils.py", line 145, in cached_property_wrapper
    value = obj.__dict__[self.func.__name__] = self.func(obj)
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\stack_data\core.py", line 628, in executing_piece
    return only(
  File "c:\Users\user1\anaconda3\envs\qsvdd\lib\site-packages\executing\executing.py", line 164, in only
    raise NotOneValueFound('Expected one value, found 0')
executing.executing.NotOneValueFound: Expected one value, found 0

I think the measurement values for commuting variables (e.g., Pauli observables) for a single wire can be calculated. However, I cannot get the values by implementing the above codes.
Actually, I was calculating the measurements on a single wire using variational parameters with an 8-qubit device. I made it simple for debugging.
Furthermore, is there any available Pennylane version for multiple measurements on a single wire? I used to make multiple measurements on a single wire before.
Thanks!

Hi @leo, welcome to the Forum!

I’m being able to run your first snippet of code with no problems. It’s strange but your PennyLane version seems right, however your device versions are not updated. This might be causing the issue you’re seeing.

I would recommend that you try the following options until default.qubit (in your installed devices) is PennyLane-0.32.0. Then run your first snippet of code again and please let me know if it now works.

  • Run python -m pip install pennylane --upgrade
  • Run python -m pip install --upgrade --force-reinstall pennylane
  • Create a new virtual environment with conda create --name <your_env_name> python=3.10 and activate it with conda activate <your_env_name>. Then python -m pip install pennylane

Please let me know if none of these work for you.

Your second code snippet won’t work because expval only takes one argument.

Let me know if you have any additional questions.

Also, we have a new PennyLane survey. Let us know your thoughts about PennyLane in order to keep bringing you amazing features :sparkles:.

Hi @CatalinaAlbornoz, thanks for your kind reply.
I was able to run the code with new virtual environment.
Thanks!

2 Likes