Skip to content

Commit

Permalink
Revert "Added back the previous hamiltonian comapre statement for any…
Browse files Browse the repository at this point in the history
… edge case."

This reverts commit 4656d97.
  • Loading branch information
dubeyPraY committed Sep 6, 2023
1 parent 4656d97 commit 8b002da
Show file tree
Hide file tree
Showing 190 changed files with 786 additions and 810 deletions.
7 changes: 2 additions & 5 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,11 @@

<h3>Bug fixes 🐛</h3>

* `hamiltonian comaparison` now also `rounds off the float to 15digit` to remove float point errors. Have just added a line of rounded float comaprison.
[(#4470)](https://github.com/PennyLaneAI/pennylane/issues/4567)

* `convert_to_numpy_parameters` now uses `qml.ops.functions.bind_new_parameters`. This reinitializes the operation and
makes sure everything references the new numpy parameters.

* `tf.function` no longer breaks `ProbabilityMP.process_state` which is needed by new devices.
[(#4575)](https://github.com/PennyLaneAI/pennylane/pull/4470)
[(#4470)](https://github.com/PennyLaneAI/pennylane/pull/4470)

<h3>Contributors ✍️</h3>

Expand All @@ -144,4 +141,4 @@ Lillian M. A. Frederiksen,
Romain Moyard,
Mudit Pandey,
Matthew Silverman
Yash Prabhat Dubey

10 changes: 5 additions & 5 deletions pennylane/_qubit_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,7 @@ def generate_samples(self):
Returns:
array[complex]: array of samples in the shape ``(dev.shots, dev.num_wires)``
"""
number_of_states = 2 ** self.num_wires
number_of_states = 2**self.num_wires

rotated_prob = self.analytic_probability()

Expand Down Expand Up @@ -874,7 +874,7 @@ def generate_basis_states(num_wires, dtype=np.uint32):
array[int]: the sampled basis states
"""
if 2 < num_wires < 32:
states_base_ten = np.arange(2 ** num_wires, dtype=dtype)
states_base_ten = np.arange(2**num_wires, dtype=dtype)
return QubitDevice.states_to_binary(states_base_ten, num_wires, dtype=dtype)

# A slower, but less memory intensive method
Expand Down Expand Up @@ -1147,7 +1147,7 @@ def estimate_probability(self, wires=None, shot_range=None, bin_size=None):
# `self._samples` typically has two axes ((shots, wires)) but can also have three with
# broadcasting ((batch_size, shots, wires)) so that we simply read out the batch_size.
batch_size = self._samples.shape[0] if np.ndim(self._samples) == 3 else None
dim = 2 ** num_wires
dim = 2**num_wires
# count the basis state occurrences, and construct the probability vector
if bin_size is not None:
num_bins = samples.shape[-2] // bin_size
Expand Down Expand Up @@ -1265,7 +1265,7 @@ def marginal_prob(self, prob, wires=None):
Returns:
array[float]: array of the resulting marginal probabilities.
"""
dim = 2 ** self.num_wires
dim = 2**self.num_wires
batch_size = self._get_batch_size(prob, (dim,), dim) # pylint: disable=assignment-from-none

if wires is None:
Expand Down Expand Up @@ -1355,7 +1355,7 @@ def var(self, observable, shot_range=None, bin_size=None):

prob = self.probability(wires=observable.wires)
# In case of broadcasting, `prob` has two axes and these are a matrix-vector products
return self._dot(prob, (eigvals ** 2)) - self._dot(prob, eigvals) ** 2
return self._dot(prob, (eigvals**2)) - self._dot(prob, eigvals) ** 2

# estimate the variance
samples = self.sample(observable, shot_range=shot_range, bin_size=bin_size)
Expand Down
2 changes: 1 addition & 1 deletion pennylane/_qutrit_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def generate_samples(self):
Returns:
array[complex]: array of samples in the shape ``(dev.shots, dev.num_wires)``
"""
number_of_states = 3 ** self.num_wires
number_of_states = 3**self.num_wires

rotated_prob = self.analytic_probability()

Expand Down
4 changes: 2 additions & 2 deletions pennylane/devices/default_gaussian.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ def photon_number(cov, mu, params, hbar=2.0):
"""
# pylint: disable=unused-argument
ex = (np.trace(cov) + mu.T @ mu) / (2 * hbar) - 1 / 2
var = (np.trace(cov @ cov) + 2 * mu.T @ cov @ mu) / (2 * hbar ** 2) - 1 / 4
var = (np.trace(cov @ cov) + 2 * mu.T @ cov @ mu) / (2 * hbar**2) - 1 / 4
return ex, var


Expand Down Expand Up @@ -618,7 +618,7 @@ def fock_expectation(cov, mu, params, hbar=2.0):
ex = fock_prob(cov, mu, params[0], hbar=hbar)

# var[|n><n|] = E[|n><n|^2] - E[|n><n|]^2 = E[|n><n|] - E[|n><n|]^2
var = ex - ex ** 2
var = ex - ex**2
return ex, var


Expand Down
14 changes: 7 additions & 7 deletions pennylane/devices/default_mixed.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def _create_basis_state(self, index):
array[complex]: complex array of shape ``[2] * (2 * num_wires)``
representing the density matrix of the basis state.
"""
rho = qnp.zeros((2 ** self.num_wires, 2 ** self.num_wires), dtype=self.C_DTYPE)
rho = qnp.zeros((2**self.num_wires, 2**self.num_wires), dtype=self.C_DTYPE)
rho[index, index] = 1
return qnp.reshape(rho, [2] * (2 * self.num_wires))

Expand All @@ -243,7 +243,7 @@ def capabilities(cls):
@property
def state(self):
"""Returns the state density matrix of the circuit prior to measurement"""
dim = 2 ** self.num_wires
dim = 2**self.num_wires
# User obtains state as a matrix
return qnp.reshape(self._pre_rotated_state, (dim, dim))

Expand Down Expand Up @@ -279,7 +279,7 @@ def analytic_probability(self, wires=None):
return None

# convert rho from tensor to matrix
rho = qnp.reshape(self._state, (2 ** self.num_wires, 2 ** self.num_wires))
rho = qnp.reshape(self._state, (2**self.num_wires, 2**self.num_wires))

# probs are diagonal elements
probs = self.marginal_prob(qnp.diagonal(rho), wires)
Expand Down Expand Up @@ -508,7 +508,7 @@ def _apply_state_vector(self, state, device_wires):
# get indices for which the state is changed to input state vector elements
ravelled_indices = qnp.ravel_multi_index(unravelled_indices.T, [2] * self.num_wires)

state = qnp.scatter(ravelled_indices, state, [2 ** self.num_wires])
state = qnp.scatter(ravelled_indices, state, [2**self.num_wires])
rho = qnp.outer(state, qnp.conj(state))
rho = qnp.reshape(rho, [2] * 2 * self.num_wires)
self._state = qnp.asarray(rho, dtype=self.C_DTYPE)
Expand All @@ -533,7 +533,7 @@ def _apply_density_matrix(self, state, device_wires):
state = qnp.reshape(state, (-1,))

state_dim = 2 ** len(device_wires)
dm_dim = state_dim ** 2
dm_dim = state_dim**2
if dm_dim != state.shape[0]:
raise ValueError("Density matrix must be of length (2**wires, 2**wires)")

Expand Down Expand Up @@ -574,7 +574,7 @@ def _apply_density_matrix(self, state, device_wires):
transpose_axes = left_axes + right_axes
rho = qnp.transpose(rho, axes=transpose_axes)
assert qnp.allclose(
qnp.trace(qnp.reshape(rho, (2 ** self.num_wires, 2 ** self.num_wires))),
qnp.trace(qnp.reshape(rho, (2**self.num_wires, 2**self.num_wires))),
1.0,
atol=tolerance,
)
Expand Down Expand Up @@ -606,7 +606,7 @@ def _apply_operation(self, operation):

if isinstance(operation, Snapshot):
if self._debugger and self._debugger.active:
dim = 2 ** self.num_wires
dim = 2**self.num_wires
density_matrix = qnp.reshape(self._state, (dim, dim))
if operation.tag:
self._debugger.snapshots[operation.tag] = density_matrix
Expand Down
18 changes: 9 additions & 9 deletions pennylane/devices/default_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,14 +710,14 @@ def _create_basis_state(self, index):
Note: This function does not support broadcasted inputs yet.
"""
state = np.zeros(2 ** self.num_wires, dtype=np.complex128)
state = np.zeros(2**self.num_wires, dtype=np.complex128)
state[index] = 1
state = self._asarray(state, dtype=self.C_DTYPE)
return self._reshape(state, [2] * self.num_wires)

@property
def state(self):
dim = 2 ** self.num_wires
dim = 2**self.num_wires
batch_size = self._get_batch_size(self._pre_rotated_state, (2,) * self.num_wires, dim)
# Do not flatten the state completely but leave the broadcasting dimension if there is one
shape = (batch_size, dim) if batch_size is not None else (dim,)
Expand Down Expand Up @@ -759,10 +759,10 @@ def _apply_state_vector(self, state, device_wires):

if batch_size is not None:
state = self._scatter(
(slice(None), ravelled_indices), state, [batch_size, 2 ** self.num_wires]
(slice(None), ravelled_indices), state, [batch_size, 2**self.num_wires]
)
else:
state = self._scatter(ravelled_indices, state, [2 ** self.num_wires])
state = self._scatter(ravelled_indices, state, [2**self.num_wires])
state = self._reshape(state, output_shape)
self._state = self._asarray(state, dtype=self.C_DTYPE)

Expand Down Expand Up @@ -812,8 +812,8 @@ def _apply_unitary(self, state, mat, wires):
device_wires = self.map_wires(wires)

dim = 2 ** len(device_wires)
mat_batch_size = self._get_batch_size(mat, (dim, dim), dim ** 2)
state_batch_size = self._get_batch_size(state, (2,) * self.num_wires, 2 ** self.num_wires)
mat_batch_size = self._get_batch_size(mat, (dim, dim), dim**2)
state_batch_size = self._get_batch_size(state, (2,) * self.num_wires, 2**self.num_wires)

shape = [2] * (len(device_wires) * 2)
state_axes = device_wires
Expand Down Expand Up @@ -870,7 +870,7 @@ def _apply_unitary_einsum(self, state, mat, wires):
device_wires = self.map_wires(wires)

dim = 2 ** len(device_wires)
batch_size = self._get_batch_size(mat, (dim, dim), dim ** 2)
batch_size = self._get_batch_size(mat, (dim, dim), dim**2)

# If the matrix is broadcasted, it is reshaped to have leading axis of size mat_batch_size
shape = [2] * (len(device_wires) * 2)
Expand Down Expand Up @@ -945,14 +945,14 @@ def analytic_probability(self, wires=None):
if self._state is None:
return None

dim = 2 ** self.num_wires
dim = 2**self.num_wires
batch_size = self._get_batch_size(self._state, [2] * self.num_wires, dim)
flat_state = self._reshape(
self._state, (batch_size, dim) if batch_size is not None else (dim,)
)
real_state = self._real(flat_state)
imag_state = self._imag(flat_state)
return self.marginal_prob(real_state ** 2 + imag_state ** 2, wires)
return self.marginal_prob(real_state**2 + imag_state**2, wires)

def classical_shadow(self, obs, circuit):
"""
Expand Down
2 changes: 1 addition & 1 deletion pennylane/devices/default_qubit_jax.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def sample_basis_states(self, number_of_states, state_probability):

if self._prng_key is None:
# Assuming op-by-op, so we'll just make one.
key = jax.random.PRNGKey(np.random.randint(0, 2 ** 31))
key = jax.random.PRNGKey(np.random.randint(0, 2**31))
else:
key = self._prng_key
if jnp.ndim(state_probability) == 2:
Expand Down
2 changes: 1 addition & 1 deletion pennylane/devices/default_qubit_tf.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,6 @@ def _apply_state_vector(self, state, device_wires):
"vector of a subsystem of the device when using DefaultQubitTF."
)
# The following line is unchanged in the "else"-clause in DefaultQubit's implementation
state = self._scatter(ravelled_indices, state, [2 ** self.num_wires])
state = self._scatter(ravelled_indices, state, [2**self.num_wires])
state = self._reshape(state, output_shape)
self._state = self._asarray(state, dtype=self.C_DTYPE)
6 changes: 3 additions & 3 deletions pennylane/devices/default_qutrit.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def _apply_tclock(self, state, axes, inverse=False):
array[complex]: output state
"""
partial_state = self._apply_phase(state, axes, 1, OMEGA, inverse)
return self._apply_phase(partial_state, axes, 2, OMEGA ** 2, inverse)
return self._apply_phase(partial_state, axes, 2, OMEGA**2, inverse)

def _apply_tadd(self, state, axes, inverse=False):
"""Applies a controlled ternary add gate by slicing along the first axis specified in ``axes`` and
Expand Down Expand Up @@ -363,7 +363,7 @@ def _create_basis_state(self, index):
array[complex]: complex array of shape ``[3]*self.num_wires``
representing the statevector of the basis state
"""
state = np.zeros(3 ** self.num_wires, dtype=np.complex128)
state = np.zeros(3**self.num_wires, dtype=np.complex128)
state[index] = 1
state = self._asarray(state, dtype=self.C_DTYPE)
return self._reshape(state, [3] * self.num_wires)
Expand Down Expand Up @@ -444,5 +444,5 @@ def analytic_probability(self, wires=None):
flat_state = self._flatten(self._state)
real_state = self._real(flat_state)
imag_state = self._imag(flat_state)
prob = self.marginal_prob(real_state ** 2 + imag_state ** 2, wires)
prob = self.marginal_prob(real_state**2 + imag_state**2, wires)
return prob
22 changes: 11 additions & 11 deletions pennylane/devices/experimental/default_qubit_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,14 +259,14 @@ def execute(
results = tuple(simulate(c, rng=self._rng, debugger=self._debugger) for c in circuits)
else:
vanilla_circuits = [convert_to_numpy_parameters(c) for c in circuits]
seeds = self._rng.integers(2 ** 31 - 1, size=len(vanilla_circuits))
seeds = self._rng.integers(2**31 - 1, size=len(vanilla_circuits))
_wrap_simulate = partial(simulate, debugger=None)
with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor:
exec_map = executor.map(_wrap_simulate, vanilla_circuits, seeds)
results = tuple(exec_map)

# reset _rng to mimic serial behavior
self._rng = np.random.default_rng(self._rng.integers(2 ** 31 - 1))
self._rng = np.random.default_rng(self._rng.integers(2**31 - 1))

return results[0] if is_single_circuit else results

Expand Down Expand Up @@ -294,7 +294,7 @@ def compute_derivatives(
res = tuple(exec_map)

# reset _rng to mimic serial behavior
self._rng = np.random.default_rng(self._rng.integers(2 ** 31 - 1))
self._rng = np.random.default_rng(self._rng.integers(2**31 - 1))

return res[0] if is_single_circuit else res

Expand Down Expand Up @@ -325,13 +325,13 @@ def execute_and_compute_derivatives(
)
else:
vanilla_circuits = [convert_to_numpy_parameters(c) for c in circuits]
seeds = self._rng.integers(2 ** 31 - 1, size=len(vanilla_circuits))
seeds = self._rng.integers(2**31 - 1, size=len(vanilla_circuits))

with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor:
results = tuple(executor.map(_adjoint_jac_wrapper, vanilla_circuits, seeds))

# reset _rng to mimic serial behavior
self._rng = np.random.default_rng(self._rng.integers(2 ** 31 - 1))
self._rng = np.random.default_rng(self._rng.integers(2**31 - 1))

results, jacs = tuple(zip(*results))
return (results[0], jacs[0]) if is_single_circuit else (results, jacs)
Expand Down Expand Up @@ -380,7 +380,7 @@ def compute_jvp(
res = tuple(executor.map(adjoint_jvp, vanilla_circuits, tangents))

# reset _rng to mimic serial behavior
self._rng = np.random.default_rng(self._rng.integers(2 ** 31 - 1))
self._rng = np.random.default_rng(self._rng.integers(2**31 - 1))

return res[0] if is_single_circuit else res

Expand Down Expand Up @@ -412,15 +412,15 @@ def execute_and_compute_jvp(
)
else:
vanilla_circuits = [convert_to_numpy_parameters(c) for c in circuits]
seeds = self._rng.integers(2 ** 31 - 1, size=len(vanilla_circuits))
seeds = self._rng.integers(2**31 - 1, size=len(vanilla_circuits))

with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor:
results = tuple(
executor.map(_adjoint_jvp_wrapper, vanilla_circuits, tangents, seeds)
)

# reset _rng to mimic serial behavior
self._rng = np.random.default_rng(self._rng.integers(2 ** 31 - 1))
self._rng = np.random.default_rng(self._rng.integers(2**31 - 1))

results, jvps = tuple(zip(*results))
return (results[0], jvps[0]) if is_single_circuit else (results, jvps)
Expand Down Expand Up @@ -469,7 +469,7 @@ def compute_vjp(
res = tuple(executor.map(adjoint_vjp, vanilla_circuits, cotangents))

# reset _rng to mimic serial behavior
self._rng = np.random.default_rng(self._rng.integers(2 ** 31 - 1))
self._rng = np.random.default_rng(self._rng.integers(2**31 - 1))

return res[0] if is_single_circuit else res

Expand Down Expand Up @@ -501,15 +501,15 @@ def execute_and_compute_vjp(
)
else:
vanilla_circuits = [convert_to_numpy_parameters(c) for c in circuits]
seeds = self._rng.integers(2 ** 31 - 1, size=len(vanilla_circuits))
seeds = self._rng.integers(2**31 - 1, size=len(vanilla_circuits))

with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor:
results = tuple(
executor.map(_adjoint_vjp_wrapper, vanilla_circuits, cotangents, seeds)
)

# reset _rng to mimic serial behavior
self._rng = np.random.default_rng(self._rng.integers(2 ** 31 - 1))
self._rng = np.random.default_rng(self._rng.integers(2**31 - 1))

results, vjps = tuple(zip(*results))
return (results[0], vjps[0]) if is_single_circuit else (results, vjps)
Expand Down
2 changes: 1 addition & 1 deletion pennylane/devices/qubit/sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ def sample_state(

wires_to_sample = wires or state_wires
num_wires = len(wires_to_sample)
basis_states = np.arange(2 ** num_wires)
basis_states = np.arange(2**num_wires)

probs = qml.probs(wires=wires_to_sample).process_state(state, state_wires)

Expand Down
2 changes: 1 addition & 1 deletion pennylane/devices/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def init_state():
"""Fixture to create an n-qubit random initial state vector."""

def _init_state(n):
state = np.random.random([2 ** n]) + np.random.random([2 ** n]) * 1j
state = np.random.random([2**n]) + np.random.random([2**n]) * 1j
state /= np.linalg.norm(state)
return state

Expand Down
2 changes: 1 addition & 1 deletion pennylane/devices/tests/test_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ def circuit():

res = circuit()

expected = np.zeros([2 ** n_wires])
expected = np.zeros([2**n_wires])
expected[np.ravel_multi_index(basis_state, [2] * n_wires)] = 1
assert np.allclose(res, expected, atol=tol(dev.shots))

Expand Down
Loading

0 comments on commit 8b002da

Please sign in to comment.