예제 #1
0
파일: vqe.py 프로젝트: ryanhill1/pennylane
    def __init__(self, coeffs, observables, simplify=False):

        if len(coeffs) != len(observables):
            raise ValueError(
                "Could not create valid Hamiltonian; "
                "number of coefficients and operators does not match.")

        if any(np.imag(coeffs) != 0):
            raise ValueError("Could not create valid Hamiltonian; "
                             "coefficients are not real-valued.")

        for obs in observables:
            if not isinstance(obs, Observable):
                raise ValueError(
                    "Could not create circuits. Some or all observables are not valid."
                )

        self._coeffs = list(coeffs)
        self._ops = list(observables)

        self.data = []
        self.return_type = None

        if simplify:
            self.simplify()

        self.queue()
    def mt(*params):
        state = qnode(*params)
        rqnode = lambda *params: np.real(qnode(*params))
        iqnode = lambda *params: np.imag(qnode(*params))
        rjac = qml.jacobian(rqnode)(*params)
        ijac = qml.jacobian(iqnode)(*params)

        if isinstance(rjac, tuple):
            out = []
            for rc, ic in zip(rjac, ijac):
                c = rc + 1j * ic
                psidpsi = np.tensordot(np.conj(state), c, axes=([0], [0]))
                out.append(
                    np.real(
                        np.tensordot(np.conj(c), c, axes=([0], [0])) -
                        np.tensordot(np.conj(psidpsi), psidpsi, axes=0)))
            return tuple(out)

        jac = rjac + 1j * ijac
        psidpsi = np.tensordot(np.conj(state), jac, axes=([0], [0]))
        return np.real(
            np.tensordot(np.conj(jac), jac, axes=([0], [0])) -
            np.tensordot(np.conj(psidpsi), psidpsi, axes=0))
n_samples = 100

coeffs = []
for i in range(n_samples):

    weights = random_weights()

    def f(x):
        return np.array([quantum_model(weights, x_) for x_ in x])

    coeffs_sample = fourier_coefficients(f, n_coeffs)
    coeffs.append(coeffs_sample)

coeffs = np.array(coeffs)
coeffs_real = np.real(coeffs)
coeffs_imag = np.imag(coeffs)

######################################################################
# Let's plot the real vs. the imaginary part of the coefficients. As a
# sanity check, the :math:`c_0` coefficient should be real, and therefore
# have no contribution on the y-axis.
#

n_coeffs = len(coeffs_real[0])

fig, ax = plt.subplots(1, n_coeffs, figsize=(15, 4))

for idx, ax_ in enumerate(ax):
    ax_.set_title(r"$c_{}$".format(idx))
    ax_.scatter(coeffs_real[:, idx],
                coeffs_imag[:, idx],