from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram

#Set up the quantum and classical registers, and combine them into a circuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)

qc.h(qr[0]) #Create a superposition on the single quantum bit
qc.measure(qr[0], cr[0]) #Measure the single bit, and store its value in the clasical bit

from qiskit import register, available_backends, get_backend

#Import the config file (Qconfig.py) to retrieve the API token and API url
try:
    import sys
    sys.path.append('../') #Parent directory
    import Qconfig
    qx_config = {
        'APItoken': Qconfig.APItoken,
        'url': Qconfig.config['url']}
except Exception as e:
    print(e)
    qx_config = {
        'APItoken':'YOUR_TOKEN_HERE',
        'url':'https://quantumexperience.ng.bluemix.net/api'}

#Setup API
register(qx_config['APItoken'], qx_config['url'])

backend = 'ibmq_qasm_simulator' #Replace 'ibmq_qasm_simulator' with 'ibmqx5' to run on the quantum computer
shots_sim = 100 #Adjust this number as desired, with effects as described above

job_sim = execute(qc, backend, shots=shots_sim) #Run job on chosen backend for chosen number of shots
stats_sim = job_sim.result().get_counts() #Retrieve results

#Select '0' to represent 'laurel'
if '0' not in stats_sim.keys():
    stats_sim['laurel'] = 0
else:
    stats_sim['laurel'] = stats_sim.pop('0')

#Which leaves '1' to represent 'yanny'
if '1' not in stats_sim.keys():
    stats_sim['yanny'] = 0
else:
    stats_sim['yanny'] = stats_sim.pop('1')

plot_histogram(stats_sim)

from pydub import AudioSegment
from pydub.playback import play

#Import two tracks
laurel = AudioSegment.from_wav('laurel_or_yanny_audio_files/laurel.wav')
yanny = AudioSegment.from_wav('laurel_or_yanny_audio_files/yanny.wav')

play(laurel) #Listen to the laurel-specific track

play(yanny) #Listen to the yanny-specific track

#Modify the volumes based on the results of the experiment
laurel = laurel + ((100*stats_sim['laurel']/shots_sim)-50) #Laurel
yanny = yanny + ((100*stats_sim['yanny']/shots_sim)-50) #Yanny

#Mix the two together and play the result
mixed = laurel.overlay(yanny)
play(mixed)

mixed.export('laurel_or_yanny_audio_files/quantumLaurelYanny.wav', format='wav')

print("Installed packages are as the following")
!python --version
print()
!conda list 'qiskit|IBMQuantumExperience|numpy|scipy'