# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import pennylane as qml
from pennylane import numpy as np
# import numpy as np

dev = qml.device(name = 'default.qubit', wires = 3, shots = 1000)


@qml.qnode(dev, interface=None)
def circuit(w):
    for i in range(3):
        qml.RX(w[i], wires=i)

    qml.CNOT(wires=[0, 1])
    qml.CNOT(wires=[1, 2])
    qml.CNOT(wires=[2, 0])

    qml.RY(w[3], wires=1)

    qml.CNOT(wires=[0, 1])
    qml.CNOT(wires=[1, 2])
    qml.CNOT(wires=[2, 0])

    qml.RX(w[4], wires=2)

    return qml.expval(qml.PauliZ(0) @ qml.PauliZ(2))


# +
weights = '0.1,0.2,0.1,0.2,0.7'
weights = weights.split(",")
weights = np.array(weights, float)
print(weights)

print(circuit(weights))
print(circuit.draw())


# -

def psr(qnode, weights, i):
    param1 = weights.copy()
    param2 = weights.copy()
    s = np.pi/2
    
    # Forward shift
    param1[i] = param1[i] + (np.pi/2)
    forward_shift = qnode(param1)
    
    # Backward Shift
    param2[i] = param2[i] - (np.pi/2)
    backward_shift = qnode(param2)
    
    gradient = (forward_shift - backward_shift) / (2*np.sin(np.pi/2))

    return gradient


def hess(qnode, weights, i, j):
    param = weights.copy()
    param2 = weights.copy()
    s = np.pi/2
    
    # Forward shift
    param[j] = param[j] + (np.pi/2)
    forward_shift = qnode(param)
    
    # Backward Shift
    param2[j] = param2[j] - (np.pi/2)
    backward_shift = qnode(param2)
    
    return (forward_shift - backward_shift) / (2*np.sin(np.pi/2))


def main(qnode, weights):
    gradient = np.zeros([5], dtype=np.float64)
    gradient2 = np.zeros([5], dtype=np.float64)
    jacobian = np.zeros([5, 5], dtype=np.float64)
    hessian = np.zeros([5, 5], dtype=np.float64)
    
    for i in range(len(weights)):
        gradient[i] = psr(qnode, weights, i)
        
    print(gradient)   
    
    return hessian


print(main(circuit, weights))

# +
0.0012756024,-0.7668909241,-0.1890228368,-0.0374176229,-0.7914937431,

0.012713476,0.0,0.012713476,0.0062927444,0.0015144486,
0.0,-0.6210429671,0.0769457494,0.1248084389,-0.6036371367,
0.012713476,0.0769457494,-0.6083294911,-0.6276219392,-0.0725364203,
0.0062927444,0.1248084389,-0.6276219392,0.1375219149,-0.0444237671,
0.0015144486,-0.6036371367,-0.0725364203,-0.0444237671,-0.6083294911,

51

# -



StarcoderdataJupyterScriptsDedupFiltered