from qiskit import *

# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0);

# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
measure_x.h(0)
measure_x.measure(0,0);

qc = QuantumCircuit(1)

qc.h(0) # the hadamard

qc.x(0) # x gate

qc.y(0) # y gate

qc.z(0) # z gate

# for the following, replace theta by any number
theta = 3.14159/4
qc.ry(theta,0); # y axis rotation

shots = 2**14 # number of samples used for statistics

uncertainty = 0
for measure_circuit in [measure_z, measure_x]:

    # run the circuit with a the selected measurement and get the number of samples that output each bit value
    counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts()

    # calculate the probabilities for each bit value
    probs = {}
    for output in ['0','1']:
        if output in counts:
            probs[output] = counts[output]/shots
        else:
            probs[output] = 0
            
    uncertainty += ( probs['0'] -  probs['1'] )**2

# print the total uncertainty
print('The total uncertainty is',uncertainty )

# for the following, replace theta by any number
theta = 3.14159/2
qc.rx(theta,0); # x axis rotation

# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
measure_y.sdg(0)
measure_y.h(0)
measure_y.measure(0,0);

shots = 2**14 # number of samples used for statistics

uncertainty = 0
for measure_circuit in [measure_z, measure_x, measure_y]:

    # run the circuit with a the selected measurement and get the number of samples that output each bit value
    counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts()

    # calculate the probabilities for each bit value
    probs = {}
    for output in ['0','1']:
        if output in counts:
            probs[output] = counts[output]/shots
        else:
            probs[output] = 0
            
    uncertainty += ( probs['0'] -  probs['1'] )**2

# print the total uncertainty
print('The total uncertainty is',uncertainty )

