# Rotations parameters dimension error while trying to plot cost landscape using np.array (Parameters with ndims (2,) passed, (0,) expected.)

I’m trying to plot some cost landscapes using numpy arrays, but everytime I try to calculate the values of the cost function, I get the error on the dimension of the parameters. I’m used to calculate the cost landscapes using lists, but sometimes the runtime gets too high, then I’m considering the use of arrays. The problem I’m solving is how to obtain the \Phi^+ Bell state using this circuit, then the cost function is 1-(Fidelity between the circuit obtained state and the Bell state). The phip state is defined in another instance. The code I’m using and the error I get are the following:

wires = 2 #number of qubits
dev = qml.device(“default.qubit”, wires=wires, shots=None)

def ansatz1(angles):
qml.RY(angles[0],wires=[0])
qml.RY(angles[1],wires=[1])
qml.CZ(wires=[0,1])
return qml.state()

circuit1 = qml.QNode(ansatz1, dev)

def cost1(angles):
state = circuit1(angles)
return 1 - np.abs( np.dot(state, phipstate) )**2

X, Y = np.meshgrid(np.arange(-np.pi, np.pi, 0.25),np.arange(-np.pi, np.pi, 0.25))
Z = cost1(np.array([X,Y]))

ValueError Traceback (most recent call last)
Input In [5], in <cell line: 2>()
1 X, Y = np.meshgrid(np.arange(-np.pi, np.pi, 0.25),np.arange(-np.pi, np.pi, 0.25))
----> 2 Z = cost1(np.array([X,Y]))

Input In [4], in cost1(angles)
1 def cost1(angles):
----> 2 state = circuit1(angles)
3 return 1 - np.abs( np.dot(state, phipstate) )**2

File ~/.local/lib/python3.10/site-packages/pennylane/qnode.py:609, in QNode.call(self, *args, **kwargs)
608 # construct the tape
→ 609 self.construct(args, kwargs)
611 cache = self.execute_kwargs.get(“cache”, False)
612 using_custom_cache = (
613 hasattr(cache, “getitem”)
614 and hasattr(cache, “setitem”)
615 and hasattr(cache, “delitem”)
616 )

File ~/.local/lib/python3.10/site-packages/pennylane/qnode.py:526, in QNode.construct(self, args, kwargs)
523 self._tape = qml.tape.QuantumTape()
525 with self.tape:
→ 526 self._qfunc_output = self.func(*args, **kwargs)
527 self._tape._qfunc_output = self._qfunc_output
529 params = self.tape.get_parameters(trainable_only=False)

Input In [2], in ansatz1(angles)
3 def ansatz1(angles):
----> 4 qml.RY(angles[0],wires=[0])
5 qml.RY(angles[1],wires=[1])
6 qml.CZ(wires=[0,1])

File ~/.local/lib/python3.10/site-packages/pennylane/ops/qubit/parametric_ops.py:165, in RY.init(self, phi, wires, do_queue, id)
164 def init(self, phi, wires, do_queue=True, id=None):
→ 165 super().init(phi, wires=wires, do_queue=do_queue, id=id)

File ~/.local/lib/python3.10/site-packages/pennylane/operation.py:1452, in Operation.init(self, wires, do_queue, id, *params)
1449 def init(self, *params, wires=None, do_queue=True, id=None):
1451 self._inverse = False
→ 1452 super().init(*params, wires=wires, do_queue=do_queue, id=id)
1454 # check the grad_recipe validity
1456 # Make sure grad_recipe is an iterable of correct length instead of None

File ~/.local/lib/python3.10/site-packages/pennylane/operation.py:883, in Operator.init(self, wires, do_queue, id, *params)
877 if self.num_wires not in {AllWires, AnyWires} and len(self._wires) != self.num_wires:
878 raise ValueError(
879 f"{self.name}: wrong number of wires. "
880 f"{len(self._wires)} wires given, {self.num_wires} expected."
881 )
→ 883 self._check_batching(params)
885 self.data = list(params) #: list[Any]: parameters of the operator
887 if do_queue:

File ~/.local/lib/python3.10/site-packages/pennylane/operation.py:924, in Operator.check_batching(self, params)
919 ndims_matches = [
920 (ndim == exp_ndim, ndim == exp_ndim + 1)
921 for ndim, exp_ndim in zip(ndims, self.ndim_params)
922 ]
923 if not all(correct or batched for correct, batched in ndims_matches):
→ 924 raise ValueError(
925 f"{self.name}: wrong number(s) of dimensions in parameters. "
926 f"Parameters with ndims {ndims} passed, {self.ndim_params} expected."
927 )
929 first_dims = [
930 qml.math.shape(p)[0] for (
, batched), p in zip(ndims_matches, params) if batched
931 ]
932 if not qml.math.allclose(first_dims, first_dims[0]):

ValueError: RY: wrong number(s) of dimensions in parameters. Parameters with ndims (2,) passed, (0,) expected.

Hi @GICorrer, welcome to the forum!

It looks like meshgrid isn’t creating the right size for your array. In our Rotoselect demo we have an example of how to use meshgrid.

``````from matplotlib import cm
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 4))

X = np.arange(-np.pi, np.pi, 0.25)
Y = np.arange(-np.pi, np.pi, 0.25)
xx, yy = np.meshgrid(X, Y)
Z = np.array([[cost1([x, y]) for x in X] for y in Y]).reshape(len(Y), len(X))
surf = ax.plot_surface(xx, yy, Z, cmap=cm.coolwarm, antialiased=False)

plt.show()
``````

Remember that you can always check the size of your inputs by using `print(X.shape)` or `print(Y.shape)`. This can help you debug in the future.

I hope this helps!

1 Like

Thank you so much for your attention and help, Catalina!

No problem @GICorrer!