def circuit_native_pennylane(): qml.QubitStateVector(np.array(prob_amplitudes), wires=[0]) return qml.expval(qml.PauliZ(0))
def circuit(x): qml.Displacement(x, 0, wires=0) return qml.expval(qml.FockStateProjector(np.array([2]), wires=0))
def circuit(r, phi): qml.Squeezing(r, 0, wires=0) qml.Rotation(phi, wires=0) return qml.var(qml.PolyXP(np.array([0, 1, 0]), wires=0))
qml.RY(a[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RY(a[2], wires=1) qml.PauliX(wires=0) qml.CNOT(wires=[0, 1]) qml.RY(a[3], wires=1) qml.CNOT(wires=[0, 1]) qml.RY(a[4], wires=1) qml.PauliX(wires=0) ############################################################################## # Let’s test if this routine actually works. x = np.array([0.53896774, 0.79503606, 0.27826503, 0.0]) ang = get_angles(x) @qml.qnode(dev) def test(angles=None): statepreparation(angles) return qml.expval(qml.PauliZ(0)) test(angles=ang) print("x : ", x) print("angles : ", ang)
This is a template variational quantum circuit containing a fixed layout of gates with variable parameters. To be used as a QNode, it must either be wrapped with the @qml.qnode decorator or converted using the qml.QNode function (as shown above). The output of this circuit is the expectation value of a Hamiltonian. An unknown Hamiltonian will be used to judge your solution. Args: params (np.ndarray): An array of optimizable parameters of shape (30,) """ parameters = params.reshape((LAYERS, WIRES, 3)) qml.templates.StronglyEntanglingLayers(parameters, wires=range(WIRES)) return qml.expval(qml.Hermitian(hamiltonian, wires=[0, 1])) if __name__ == "__main__": # DO NOT MODIFY anything in this code block # Load and process Hamiltonian data hamiltonian = sys.stdin.read() hamiltonian = hamiltonian.split(",") hamiltonian = np.array(hamiltonian, float).reshape((2**WIRES, 2**WIRES)) # Generate random initial parameters np.random.seed(1967) initial_params = np.random.random(NUM_PARAMETERS) minimized_circuit = optimize_circuit(initial_params) print(f"{minimized_circuit:.6f}")
class TestTake: """Tests for the qml.take function""" take_data = [ np.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), torch.tensor([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), onp.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), tf.constant([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), tf.Variable([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), jnp.asarray([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), ] @pytest.mark.parametrize("t", take_data) def test_flattened_indexing(self, t): """Test that indexing without the axis argument will flatten the tensor first""" indices = 5 res = fn.take(t, indices) assert fn.allclose(res, 1) @pytest.mark.parametrize("t", take_data) def test_array_indexing(self, t): """Test that indexing with a sequence properly extracts the elements from the flattened tensor""" indices = [0, 2, 3, 6, -2] res = fn.take(t, indices) assert fn.allclose(res, [1, 3, 4, 5, 2]) @pytest.mark.parametrize("t", take_data) def test_multidimensional_indexing(self, t): """Test that indexing with a multi-dimensional sequence properly extracts the elements from the flattened tensor""" indices = [[0, 1], [3, 2]] res = fn.take(t, indices) assert fn.allclose(res, [[1, 2], [4, 3]]) @pytest.mark.parametrize("t", take_data) def test_array_indexing_along_axis(self, t): """Test that indexing with a sequence properly extracts the elements from the specified tensor axis""" indices = [0, 1, -2] res = fn.take(t, indices, axis=2) expected = np.array([ [[ 1, 2, 1], [ 3, 4, 3], [-1, 1, -1]], [[ 5, 6, 5], [ 0, -1, 0], [ 2, 1, 2]] ]) assert fn.allclose(res, expected) @pytest.mark.parametrize("t", take_data) def test_multidimensional_indexing_along_axis(self, t): """Test that indexing with a sequence properly extracts the elements from the specified tensor axis""" indices = np.array([[0, 0], [1, 0]]) res = fn.take(t, indices, axis=1) expected = np.array( [ [ [[ 1, 2], [ 1, 2]], [[ 3, 4], [ 1, 2]] ], [ [[ 5, 6], [ 5, 6]], [[ 0, -1], [ 5, 6]] ] ] ) assert fn.allclose(res, expected)
# This cost defines the following landscape: # # *Note: To run the following cell you need the matplotlib library.* import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import MaxNLocator fig = plt.figure(figsize=(6, 4)) ax = fig.gca(projection="3d") X = np.linspace(-3.0, 3.0, 20) Y = np.linspace(-3.0, 3.0, 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) ax.set_xlabel("v1") ax.set_ylabel("v2") ax.zaxis.set_major_locator(MaxNLocator(nbins=5, prune="lower")) plt.show() ############################################################################## # Optimization # ~~~~~~~~~~~~ # # We create a GradientDescentOptimizer and use it to optimize the cost # function.
def test_apply(self, gate, apply_unitary, shots, qvm, compiler): """Test the application of gates""" dev = plf.QVMDevice(device="3q-qvm", shots=shots) try: # get the equivalent pennylane operation class op = getattr(qml.ops, gate) except AttributeError: # get the equivalent pennylane-forest operation class op = getattr(plf, gate) # the list of wires to apply the operation to w = list(range(op.num_wires)) obs = qml.expval(qml.PauliZ(0)) if op.par_domain == "A": # the parameter is an array if gate == "QubitUnitary": p = np.array(U) w = [0] state = apply_unitary(U, 3) elif gate == "BasisState": p = np.array([1, 1, 1]) state = np.array([0, 0, 0, 0, 0, 0, 0, 1]) w = list(range(dev.num_wires)) circuit_graph = CircuitGraph([op(p, wires=w)] + [obs], {}, dev.wires) else: p = [0.432_423, 2, 0.324][:op.num_params] fn = test_operation_map[gate] if callable(fn): # if the default.qubit is an operation accepting parameters, # initialise it using the parameters generated above. O = fn(*p) else: # otherwise, the operation is simply an array. O = fn # calculate the expected output state = apply_unitary(O, 3) # Creating the circuit graph using a parametrized operation if p: circuit_graph = CircuitGraph([op(*p, wires=w)] + [obs], {}, dev.wires) # Creating the circuit graph using an operation that take no parameters else: circuit_graph = CircuitGraph([op(wires=w)] + [obs], {}, dev.wires) dev.apply(circuit_graph.operations, rotations=circuit_graph.diagonalizing_gates) dev._samples = dev.generate_samples() res = dev.expval(obs) expected = np.vdot(state, np.kron(np.kron(Z, I), I) @ state) # verify the device is now in the expected state # Note we have increased the tolerance here, since we are only # performing 1024 shots. self.assertAllAlmostEqual(res, expected, delta=3 / np.sqrt(shots))
def circuit(x, y, z): """Reference 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_transform(dev_name, diff_method, monkeypatch, tol): """Test an example transform""" monkeypatch.setattr(qml.operation.Operation, "do_check_domain", False) dev = qml.device(dev_name, wires=1) @qnode(dev, interface="autograd", diff_method=diff_method) def circuit(weights): # the following global variables are defined simply for testing # purposes, so that we can easily extract the operations for verification. global op1, op2 op1 = qml.RY(weights[0], wires=0) op2 = qml.RX(weights[1], wires=0) return qml.expval(qml.PauliZ(wires=0)) weights = np.array([0.32, 0.543], requires_grad=True) a = np.array(0.5, requires_grad=True) def loss(weights, a): # the following global variable is defined simply for testing # purposes, so that we can easily extract the transformed QNode # for verification. global new_circuit # transform the circuit QNode with trainable weight 'a' new_circuit = qtransform(circuit, a) # evaluate the transformed QNode res = new_circuit(weights) # evaluate the original QNode with pre-processed parameters res2 = circuit(np.sin(weights)) # return the sum of the two QNode evaluations return res + res2 res = loss(weights, a) # verify that the transformed QNode has the expected operations assert circuit.qtape.operations == [op1, op2] # RY(y) gate is transformed to RX(-a*cos(y)) assert new_circuit.qtape.operations[0] == t_op[0] # RX gate is is not transformed assert new_circuit.qtape.operations[1].name == op2.name assert new_circuit.qtape.operations[1].wires == op2.wires # check that the incident gate arguments of both QNode tapes are correct assert np.all(np.array(circuit.qtape.get_parameters()) == np.sin(weights)) assert np.all( np.array(new_circuit.qtape.get_parameters()) == [-a * np.cos(weights[0]), weights[1]]) # verify that the gradient has the correct shape grad = qml.grad(loss)(weights, a) assert len(grad) == 2 assert grad[0].shape == weights.shape assert grad[1].shape == a.shape # compare against the expected values assert np.allclose(res, 1.8244501889992706, atol=tol, rtol=0) assert np.allclose(grad[0], [-0.26610258, -0.47053553], atol=tol, rtol=0) assert np.allclose(grad[1], 0.06486032, atol=tol, rtol=0)
#%% Imports from pennylane import numpy as np # get pennylane's numpy wrapper import pennylane as qml from pennylane import expval, var from multiprocessing import Process #%% # ----------------- ## COMPUTE TRUE MINIMUM # SECTION 1: SINGLE VQE PROBLEM - QNG, SGD, ADAM etc. GO THROUGH EACH OF THE GRADIENT BASED UPDATE METHODS """ SETUP VARIATONAL CIRCUIT: TAKEN FROM https://pennylane.ai/qml/demos/tutorial_quantum_natural_gradient.html""" DENSITY = 100 SHOTRANGE = np.linspace(10, 1000, DENSITY) STEPS = 500 init_params = np.array([0.432, -0.123, 0.543, 0.233]) GD_COST = np.zeros((DENSITY, STEPS)) ROTO_COST = np.zeros((DENSITY, STEPS)) ADAM_COST = np.zeros((DENSITY, STEPS)) QNG_COST = np.zeros((DENSITY, STEPS)) def initialize(shotnum): dev = qml.device("default.qubit", wires=3, analytic=False, shots=shotnum) @qml.qnode(dev) def circuit(params): # |psi_0>: state preparation qml.RY(np.pi / 4, wires=0) qml.RY(np.pi / 3, wires=1) qml.RY(np.pi / 7, wires=2) # V0(theta0, theta1): Parametrized layer 0
def test_chained_gradient_value(self, dev_name, diff_method, tol): """Test that the returned gradient value for two chained qubit QNodes is correct.""" dev1 = qml.device(dev_name, wires=3) @qml.qnode(dev1, diff_method=diff_method) def circuit1(a, b, c): qml.RX(a, wires=0) qml.RX(b, wires=1) qml.RX(c, wires=2) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[1, 2]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(2)) dev2 = qml.device("default.qubit", wires=2) @qml.qnode(dev2, diff_method=diff_method) def circuit2(data, weights): qml.RX(data[0], wires=0) qml.RX(data[1], wires=1) qml.CNOT(wires=[0, 1]) qml.RZ(weights[0], wires=0) qml.RZ(weights[1], wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliX(0) @ qml.PauliY(1)) def cost(a, b, c, weights): return circuit2(circuit1(a, b, c), weights) grad_fn = qml.grad(cost) # Set the first parameter of circuit1 as non-differentiable. a = np.array(0.4, requires_grad=False) # The remaining free parameters are all differentiable. b = 0.5 c = 0.1 weights = np.array([0.2, 0.3]) res = grad_fn(a, b, c, weights) # Output should have shape [dcost/db, dcost/dc, dcost/dw], # where b,c are scalars, and w is a vector of length 2. assert len(res) == 3 assert res[0].shape == tuple() # scalar assert res[1].shape == tuple() # scalar assert res[2].shape == (2, ) # vector cacbsc = np.cos(a) * np.cos(b) * np.sin(c) expected = np.array([ # analytic expression for dcost/db -np.cos(a) * np.sin(b) * np.sin(c) * np.cos(cacbsc) * np.sin(weights[0]) * np.sin(np.cos(a)), # analytic expression for dcost/dc np.cos(a) * np.cos(b) * np.cos(c) * np.cos(cacbsc) * np.sin(weights[0]) * np.sin(np.cos(a)), # analytic expression for dcost/dw[0] np.sin(cacbsc) * np.cos(weights[0]) * np.sin(np.cos(a)), # analytic expression for dcost/dw[1] 0 ]) # np.hstack 'flattens' the ragged gradient array allowing it # to be compared with the expected result assert np.allclose(np.hstack(res), expected, atol=tol, rtol=0) if diff_method != "backprop": # Check that the gradient was computed # for all parameters in circuit2 assert circuit2.qtape.trainable_params == {0, 1, 2, 3} # Check that the parameter-shift rule was not applied # to the first parameter of circuit1. assert circuit1.qtape.trainable_params == {1, 2}
def test_differentiable_expand(self, dev_name, diff_method, mocker, tol): """Test that operation and nested tapes expansion is differentiable""" mock = mocker.patch.object(qml.operation.Operation, "do_check_domain", False) class U3(qml.U3): def expand(self): theta, phi, lam = self.data wires = self.wires with JacobianTape() as tape: qml.Rot(lam, theta, -lam, wires=wires) qml.PhaseShift(phi + lam, wires=wires) return tape dev = qml.device(dev_name, wires=1) a = np.array(0.1, requires_grad=False) p = np.array([0.1, 0.2, 0.3], requires_grad=True) @qnode(dev, diff_method=diff_method, interface="autograd") def circuit(a, p): qml.RX(a, wires=0) U3(p[0], p[1], p[2], wires=0) return qml.expval(qml.PauliX(0)) res = circuit(a, p) if diff_method == "finite-diff": assert circuit.qtape.trainable_params == {1, 2, 3, 4} elif diff_method == "backprop": # For a backprop device, no interface wrapping is performed, and JacobianTape.jacobian() # is never called. As a result, JacobianTape.trainable_params is never set --- the ML # framework uses its own backprop logic and its own bookkeeping re: trainable parameters. assert circuit.qtape.trainable_params == {0, 1, 2, 3, 4} assert [i.name for i in circuit.qtape.operations ] == ["RX", "Rot", "PhaseShift"] if diff_method == "finite-diff": assert np.all(circuit.qtape.get_parameters() == [p[2], p[0], -p[2], p[1] + p[2]]) elif diff_method == "backprop": # In backprop mode, all parameters are returned. assert np.all(circuit.qtape.get_parameters() == [a, p[2], p[0], -p[2], p[1] + p[2]]) expected = np.cos(a) * np.cos(p[1]) * np.sin( p[0]) + np.sin(a) * (np.cos(p[2]) * np.sin(p[1]) + np.cos(p[0]) * np.cos(p[1]) * np.sin(p[2])) assert np.allclose(res, expected, atol=tol, rtol=0) res = qml.grad(circuit)(a, p) expected = np.array([ np.cos(p[1]) * (np.cos(a) * np.cos(p[0]) - np.sin(a) * np.sin(p[0]) * np.sin(p[2])), np.cos(p[1]) * np.cos(p[2]) * np.sin(a) - np.sin(p[1]) * (np.cos(a) * np.sin(p[0]) + np.cos(p[0]) * np.sin(a) * np.sin(p[2])), np.sin(a) * (np.cos(p[0]) * np.cos(p[1]) * np.cos(p[2]) - np.sin(p[1]) * np.sin(p[2])), ]) assert np.allclose(res, expected, atol=tol, rtol=0)
def circuit(params): qml.RX(np.array(np.pi / 4, requires_grad=False), wires=[0]) qml.Rot(params[1], params[0], 2 * params[0], wires=[0]) return qml.expval(qml.PauliX(0))
class TestSum: """Tests for the summation function""" def test_array(self): """Test that sum, called without the axis arguments, returns a scalar""" t = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) res = fn.sum_(t) assert isinstance(res, np.ndarray) assert fn.allclose(res, 2.1) def test_tensorflow(self): """Test that sum, called without the axis arguments, returns a scalar""" t = tf.Variable([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) res = fn.sum_(t) assert isinstance(res, tf.Tensor) assert fn.allclose(res, 2.1) def test_torch(self): """Test that sum, called without the axis arguments, returns a scalar""" t = torch.tensor([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) res = fn.sum_(t) assert isinstance(res, torch.Tensor) assert fn.allclose(res, 2.1) def test_jax(self): """Test that sum, called without the axis arguments, returns a scalar""" t = jnp.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) res = fn.sum_(t) assert fn.allclose(res, 2.1) @pytest.mark.parametrize("t1", [ np.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), torch.tensor([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), tf.constant([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), jnp.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), ]) def test_sum_axis(self, t1): """Test that passing the axis argument allows for summing along a specific axis""" res = fn.sum_(t1, axis=(0, 2)) # if tensorflow or pytorch, extract view of underlying data if hasattr(res, "numpy"): res = res.numpy() assert fn.allclose(res, np.array([14, 6, 3])) assert res.shape == (3,) @pytest.mark.parametrize("t1", [ np.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), torch.tensor([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), tf.constant([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), jnp.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]) ]) def test_sum_axis_keepdims(self, t1): """Test that passing the axis argument allows for summing along a specific axis, while keepdims avoids the summed dimensions from being removed""" res = fn.sum_(t1, axis=(0, 2), keepdims=True) # if tensorflow or pytorch, extract view of underlying data if hasattr(res, "numpy"): res = res.numpy() assert fn.allclose(res, np.array([[[14], [6], [3]]])) assert res.shape == (1, 3, 1)
qml.RY(params[1], wires=1) qml.RZ(params[2], wires=2) non_parametrized_layer() qml.RX(params[3], wires=0) qml.RY(params[4], wires=1) qml.RZ(params[5], wires=2) @qml.qnode(dev) def qnode(params): """A PennyLane QNode that pairs the variational_circuit with an expectation value measurement. # DO NOT MODIFY anything in this function! It is used to judge your solution. """ variational_circuit(params) return qml.expval(qml.PauliX(1)) if __name__ == "__main__": # DO NOT MODIFY anything in this code block # Load and process inputs params = sys.stdin.read() params = params.split(",") params = np.array(params, float) updated_params = natural_gradient(params) print(*updated_params, sep=",")
def test_array(self): """Test that sum, called without the axis arguments, returns a scalar""" t = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) res = fn.sum_(t) assert isinstance(res, np.ndarray) assert fn.allclose(res, 2.1)
def gradient(params): """Returns the gradient of the above circuit""" da = -np.sin(params[0]) * np.cos(params[1]) db = -np.cos(params[0]) * np.sin(params[1]) return np.array([da, db])
def test_where(t): """Test that the where function works as expected""" res = fn.where(t < 0, 100 * fn.ones_like(t), t) expected = np.array([[[1, 2], [3, 4], [100, 1]], [[5, 6], [0, 100], [2, 1]]]) assert fn.allclose(res, expected)
def gradient(params): """Returns the gradient""" da = -np.sin(params[0]) * (np.cos(params[1]) + np.sin(params[1])) db = np.cos(params[0]) * (np.cos(params[1]) - np.sin(params[1])) return np.array([da, db])
def circuit(weights): for i in range(len(weights)): qml.RX(weights[i, 0], wires=0) qml.RY(weights[i, 1], wires=1) qml.RZ(weights[i, 2], wires=2) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[1, 2]) qml.CNOT(wires=[2, 0]) return qml.expval(qml.PauliY(0) @ qml.PauliZ(2)) gradient = np.zeros_like(weights) # QHACK # gradient = qml.grad(circuit) # QHACK # return gradient(weights)[0] if __name__ == "__main__": # DO NOT MODIFY anything in this code block weights = sys.stdin.read() weights = np.array([row.split(",") for row in weights.split("S") if row], dtype=np.float64) gradient = np.round(parameter_shift(weights), 10) output_array = gradient.flatten() print(",".join([str(val) for val in output_array]))
def test_supported_gates(self): """Test that all supported gates work correctly""" self.logTestName() a = 0.312 b = 0.123 dev = qml.device("default.qubit", wires=2) for g, qop in dev._operation_map.items(): log.debug("\tTesting gate %s...", g) self.assertTrue(dev.supported(g)) dev.reset() op = getattr(qml.ops, g) if op.num_wires == 0: if g == "BasisState": wires = [0, 1] else: wires = [0] else: wires = list(range(op.num_wires)) @qml.qnode(dev) def circuit(*x): """Reference quantum function""" op(*x, wires=wires) return qml.expval(qml.PauliX(0)) # compare to reference result def reference(*x): """reference circuit""" if callable(qop): # if the default.qubit is an operation accepting parameters, # initialise it using the parameters generated above. O = qop(*x) else: # otherwise, the operation is simply an array. O = qop # calculate the expected output if op.num_wires == 1 or g == "QubitUnitary": out_state = np.kron(O @ np.array([1, 0]), np.array([1, 0])) elif g == "QubitStateVector": out_state = x[0] elif g == "BasisState": out_state = np.array([0, 0, 0, 1]) else: out_state = O @ dev._state expectation = out_state.conj() @ np.kron( X, np.identity(2)) @ out_state return expectation if g == "QubitStateVector": p = np.array([1, 0, 0, 1]) / np.sqrt(2) self.assertAllEqual(circuit(p), reference(p)) elif g == "BasisState": p = np.array([1, 1]) self.assertAllEqual(circuit(p), reference(p)) elif g == "QubitUnitary": self.assertAllEqual(circuit(U), reference(U)) elif op.num_params == 1: self.assertAllEqual(circuit(a), reference(a)) elif op.num_params == 2: self.assertAllEqual(circuit(a, b), reference(a, b))
matplotlib = pytest.importorskip("matplotlib") import matplotlib.pyplot as plt from pennylane import numpy as np from pennylane.fourier.visualize import _validate_coefficients from pennylane.fourier.visualize import ( violin, bar, box, panel, radial_box, ) coeffs_1D_valid_1 = np.array([0.5, 0, 0.25j, 0.25j, 0]) coeffs_1D_valid_2 = [0.5, 0.1j, -0.25j, 0.25j, -0.1j] coeffs_1D_invalid = np.array([0.5, 0, 0.25j, 0.25j]) coeffs_1D_valid_list = [coeffs_1D_valid_1, coeffs_1D_valid_2] coeffs_2D_valid_1 = np.array([ [ 0.07469786 + 0.0000e00j, 0.0 + 4.3984e-04j, 0.00101184 - 0.0000e00j, 0.00101184 + 0.0000e00j, 0.0 - 4.3984e-04j, ], [ -0.03973803 - 1.9390e-03j,
assert res.interface == "autograd" def test_return_numpy_box(self): """Test that NumPy is correctly identified as the dispatching library.""" x = onp.array([1.0, 2.0, 3.0]) y = [0.5, 0.1] res = fn._get_multi_tensorbox([y, x]) assert res.interface == "numpy" test_abs_data = [ (1, -2, 3 + 4j), [1, -2, 3 + 4j], onp.array([1, -2, 3 + 4j]), np.array([1, -2, 3 + 4j]), torch.tensor([1, -2, 3 + 4j], dtype=torch.complex128), tf.Variable([1, -2, 3 + 4j], dtype=tf.complex128), tf.constant([1, -2, 3 + 4j], dtype=tf.complex128), ] @pytest.mark.parametrize("t", test_abs_data) def test_abs(t): """Test that the absolute function works for a variety of input""" res = fn.abs_(t) assert fn.allequal(res, [1, 2, 5])
""" import pytest import strawberryfields as sf import pennylane as qml from pennylane import numpy as np from pennylane.wires import Wires from scipy.special import factorial as fac psi = np.array([ 0.08820314 + 0.14909648j, 0.32826940 + 0.32956027j, 0.26695166 + 0.19138087j, 0.32419593 + 0.08460371j, 0.02984712 + 0.30655538j, 0.03815006 + 0.18297214j, 0.17330397 + 0.2494433j, 0.14293477 + 0.25095202j, 0.21021125 + 0.30082734j, 0.23443833 + 0.19584968j, ]) one_mode_single_real_parameter_gates = [ ("ThermalState", qml.ThermalState), ("Kerr", qml.Kerr), ("QuadraticPhase", qml.QuadraticPhase), ("Rotation", qml.Rotation), ("CubicPhase", qml.CubicPhase), ] two_modes_single_real_parameter_gates = [
class TestDot: """Tests for the dot product function""" scalar_product_data = [ [2, 6], [np.array(2), np.array(6)], [torch.tensor(2), onp.array(6)], [torch.tensor(2), torch.tensor(6)], [tf.Variable(2), onp.array(6)], [tf.constant(2), onp.array(6)], [tf.Variable(2), tf.Variable(6)], [jnp.array(2), jnp.array(6)], ] @pytest.mark.parametrize("t1, t2", scalar_product_data) def test_scalar_product(self, t1, t2): """Test that the dot product of two scalars results in a scalar""" res = fn.dot(t1, t2) assert fn.allequal(res, 12) vector_product_data = [ [[1, 2, 3], [1, 2, 3]], [np.array([1, 2, 3]), np.array([1, 2, 3])], [torch.tensor([1, 2, 3]), onp.array([1, 2, 3])], [torch.tensor([1, 2, 3]), torch.tensor([1, 2, 3])], [tf.Variable([1, 2, 3]), onp.array([1, 2, 3])], [tf.constant([1, 2, 3]), onp.array([1, 2, 3])], [tf.Variable([1, 2, 3]), tf.Variable([1, 2, 3])], [jnp.array([1, 2, 3]), jnp.array([1, 2, 3])], ] @pytest.mark.parametrize("t1, t2", vector_product_data) def test_vector_product(self, t1, t2): """Test that the dot product of two vectors results in a scalar""" res = fn.dot(t1, t2) assert fn.allequal(res, 14) matrix_vector_product_data = [ [[[1, 2], [3, 4]], [6, 7]], [np.array([[1, 2], [3, 4]]), np.array([6, 7])], [torch.tensor([[1, 2], [3, 4]]), onp.array([6, 7])], [torch.tensor([[1, 2], [3, 4]]), torch.tensor([6, 7])], [tf.Variable([[1, 2], [3, 4]]), onp.array([6, 7])], [tf.constant([[1, 2], [3, 4]]), onp.array([6, 7])], [tf.Variable([[1, 2], [3, 4]]), tf.Variable([6, 7])], [jnp.array([[1, 2], [3, 4]]), jnp.array([6, 7])], [np.array([[1, 2], [3, 4]]), jnp.array([6, 7])], ] @pytest.mark.parametrize("t1, t2", matrix_vector_product_data) def test_matrix_vector_product(self, t1, t2): """Test that the matrix-vector dot product of two vectors results in a vector""" res = fn.dot(t1, t2) assert fn.allequal(res, [20, 46]) @pytest.mark.parametrize("t1, t2", matrix_vector_product_data) def test_vector_matrix_product(self, t1, t2): """Test that the vector-matrix dot product of two vectors results in a vector""" res = fn.dot(t2, t1) assert fn.allequal(res, [27, 40]) @pytest.mark.parametrize("t1, t2", matrix_vector_product_data) def test_matrix_matrix_product(self, t1, t2): """Test that the matrix-matrix dot product of two vectors results in a matrix""" res = fn.dot(t1, t1) assert fn.allequal(res, np.array([[7, 10], [15, 22]])) multidim_product_data = [ [np.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), np.array([[[1, 1], [3, 3]], [[3, 1], [3, 2]]])], [torch.tensor([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), onp.array([[[1, 1], [3, 3]], [[3, 1], [3, 2]]])], [torch.tensor([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), torch.tensor([[[1, 1], [3, 3]], [[3, 1], [3, 2]]])], [onp.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), tf.Variable([[[1, 1], [3, 3]], [[3, 1], [3, 2]]])], [tf.constant([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), onp.array([[[1, 1], [3, 3]], [[3, 1], [3, 2]]])], [tf.Variable([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), tf.constant([[[1, 1], [3, 3]], [[3, 1], [3, 2]]])], [jnp.array([[[1, 2], [3, 4], [-1, 1]], [[5, 6], [0, -1], [2, 1]]]), jnp.array([[[1, 1], [3, 3]], [[3, 1], [3, 2]]])], ] @pytest.mark.parametrize("t1, t2", multidim_product_data) def test_multidimensional_product(self, t1, t2): """Test that the multi-dimensional dot product reduces across the last dimension of the first tensor, and the second-to-last dimension of the second tensor.""" res = fn.dot(t1, t2) expected = np.array([[[[ 7, 7], [ 9, 5]], [[15, 15], [21, 11]], [[ 2, 2], [ 0, 1]]], [[[23, 23], [33, 17]], [[-3, -3], [-3, -2]], [[ 5, 5], [ 9, 4]]]] ) assert fn.allequal(res, expected)
def circuit(x): qml.Squeezing(x, 0, wires=0) return qml.expval( qml.FockStateProjector(np.array([2, 0]), wires=[0, 1]))
def test_matrix_matrix_product(self, t1, t2): """Test that the matrix-matrix dot product of two vectors results in a matrix""" res = fn.dot(t1, t1) assert fn.allequal(res, np.array([[7, 10], [15, 22]]))
import cmath # pylint: disable=protected-access,cell-var-from-loop import math import pytest import pennylane as qml from pennylane import numpy as np from pennylane.plugins.default_qubit import (CRot3, CRotx, CRoty, CRotz, Rot3, Rotx, Roty, Rotz, Rphi, Z, hermitian, spectral_decomposition, unitary) U = np.array( [ [0.83645892 - 0.40533293j, -0.20215326 + 0.30850569j], [-0.23889780 - 0.28101519j, -0.88031770 - 0.29832709j], ] ) U2 = np.array( [ [ -0.07843244 - 3.57825948e-01j, 0.71447295 - 5.38069384e-02j, 0.20949966 + 6.59100734e-05j, -0.50297381 + 2.35731613e-01j, ], [ -0.26626692 + 4.53837083e-01j, 0.27771991 - 2.40717436e-01j,
def circuit(x, weights, w=None): """In this example, a mixture of scalar arguments, array arguments, and keyword arguments are used.""" qml.QubitStateVector(1j * np.array([1, -1]) / np.sqrt(2), wires=w) operation(x, weights[0], weights[1], wires=w) return qml.expval(qml.PauliX(w))