Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_qubit_unitary(self, tol):
"""Test that an arbitrary unitary operation works"""
dev = qml.device("forest.numpy_wavefunction", wires=3)
@qml.qnode(dev)
def circuit():
"""Test QNode"""
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
qml.QubitUnitary(U2, wires=[0, 1])
return qml.expval(qml.PauliZ(0))
out_state = U2 @ np.array([1, 0, 0, 1]) / np.sqrt(2)
obs = np.kron(np.array([[1, 0], [0, -1]]), I)
self.assertAllAlmostEqual(circuit(), np.vdot(out_state, obs @ out_state), delta=tol)
def test_gaussian_state(self, tol):
"""Test that the GaussianState gate works correctly"""
V = np.array([[0.5, 0], [0, 2]])
r = np.array([0, 0])
wires = [0]
gate_name = "GaussianState"
operation = qml.GaussianState
dev = qml.device("strawberryfields.gaussian", wires=2)
sf_operation = dev._operation_map[gate_name]
assert dev.supports_operation(gate_name)
@qml.qnode(dev)
def circuit(*args):
qml.TwoModeSqueezing(0.1, 0, wires=[0, 1])
operation(*args, wires=wires)
def circuit(x, y, z):
"""Test QNode"""
qml.BasisState(np.array([1]), wires=0)
qml.Hadamard(wires=0)
qml.Rot(x, y, z, wires=0)
return qml.expval(qml.PauliZ(0))
def test_qubit_unitary(self, tol):
"""Test that an arbitrary unitary operation works"""
dev = qml.device("forest.numpy_wavefunction", wires=3)
@qml.qnode(dev)
def circuit():
"""Test QNode"""
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
qml.QubitUnitary(U2, wires=[0, 1])
return qml.expval(qml.PauliZ(0))
out_state = U2 @ np.array([1, 0, 0, 1]) / np.sqrt(2)
obs = np.kron(np.array([[1, 0], [0, -1]]), I)
self.assertAllAlmostEqual(circuit(), np.vdot(out_state, obs @ out_state), delta=tol)
def test_basis_state_on_subsystem(self):
"""Test BasisState with preparations on subsystems."""
if self.devices is None:
return
self.logTestName()
for device in self.devices:
for bits_to_flip in [np.array([0, 0, 0]),
np.array([1, 0, 0]),
np.array([0, 1, 1]),
np.array([1, 1, 0]),
np.array([1, 1, 1])]:
@qml.qnode(device)
def circuit():
qml.BasisState(bits_to_flip, wires=list(range(self.num_subsystems-1)))
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(3))
self.assertAllAlmostEqual([1]*(self.num_subsystems-1)-2*bits_to_flip, np.array(circuit()[:-1]), delta=self.tol)
def test_squeezing_heisenberg(phi, mag):
"""ops: Tests the Heisenberg representation of the Squeezing gate."""
r = mag
matrix = cv.Squeezing._heisenberg_rep([r, phi])
true_matrix = np.array(
[
[1, 0, 0],
[0, np.cosh(r) - np.cos(phi) * np.sinh(r), -np.sin(phi) * np.sinh(r)],
[0, -np.sin(phi) * np.sinh(r), np.cosh(r) + np.cos(phi) * np.sinh(r)],
]
)
assert np.allclose(matrix, true_matrix)
dev = plf.QVMDevice(device="2q-qvm", shots=shots)
dev.apply("RX", wires=[0], par=[theta])
dev.apply("RX", wires=[1], par=[phi])
dev.apply("CNOT", wires=[0, 1], par=[])
O = qml.Identity
name = "Identity"
dev._obs_queue = [O(wires=[0], do_queue=False), O(wires=[1], do_queue=False)]
res = dev.pre_measure()
res = np.array([dev.expval(name, [0], []), dev.expval(name, [1], [])])
# below are the analytic expectation values for this circuit (trace should always be 1)
self.assertAllAlmostEqual(res, np.array([1, 1]), delta=3 / np.sqrt(shots))
"Cost after step {:5d}: {: .7f} | Variables: [{: .5f},{: .5f}]".format(
it + 1, cost(var), var[0], var[1]
)
)
##############################################################################
# We can plot the path that the variables took during gradient descent. To
# make the plot more clear, we will shorten the range for :math:`v_2`.
fig = plt.figure(figsize=(6, 4))
ax = fig.gca(projection="3d")
X = np.linspace(-3, np.pi / 2, 20)
Y = np.linspace(-3, 3, 20)
xx, yy = np.meshgrid(X, Y)
Z = np.array([[cost([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)
path_z = [cost(var) + 1e-8 for var in var_gd]
path_x = [v[0] for v in var_gd]
path_y = [v[1] for v in var_gd]
ax.plot(path_x, path_y, path_z, c="green", marker=".", label="graddesc", zorder=10)
ax.set_xlabel("v1")
ax.set_ylabel("v2")
ax.zaxis.set_major_locator(MaxNLocator(nbins=5, prune="lower"))
plt.legend()
plt.show()
radius (float: radius of the circle
Returns:
Xvals (array[tuple]): coordinates of points
Xvals (array[int]): classification labels
"""
Xvals, yvals = [], []
for i in range(samples):
x = 2 * (np.random.rand(2)) - 1
y = 0
if np.linalg.norm(x - center) < radius:
y = 1
Xvals.append(x)
yvals.append(y)
return np.array(Xvals), np.array(yvals)
# load Iris data and normalise feature vectors
data = np.loadtxt("data/iris_classes1and2_scaled.txt")
X = data[:, 0:2]
# pad the vectors to size 2^2 with constant values
padding = 0.3 * np.ones((len(X), 1))
X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1)) ]
# normalize each input
normalization = np.sqrt(np.sum(X_pad ** 2, -1))
X_norm = (X_pad.T / normalization).T
# angles for state preparation are new features
features = np.array([get_angles(x) for x in X_norm])
Y = data[:, -1]
# split into training and validation set
np.random.seed(0)
num_data = len(Y)
num_train = int(0.75 * num_data)
index = np.random.permutation(range(num_data))
feats_train = features[index[:num_train]]
Y_train = Y[index[:num_train]]
feats_val = features[index[num_train:]]
Y_val = Y[index[num_train:]]
# initialize weight layers
num_qubits = 2
num_layers = 6