from psychopy import visual, core, event
import numpy as np

"""
Explanation: Lecture notes from week 5
Programming for the Behavioral Sciences
An introduction to PsychoPy
End of explanation
"""


win = visual.Window()
core.wait(1)
win.close()

"""
Explanation: Example 1
Create a window, and remove it after 1 s
End of explanation
"""


# Create a window and a circle
win = visual.Window() 
circle = visual.Circle(win, radius=0.1)

# Show the circle until keypress
circle.draw()
win.flip()
event.waitKeys()

# Close the window
win.close()

"""
Explanation: Example 2
A slightly more advanced example, where
 - A window is opened
 - A circle is shown until the participant presses any key
End of explanation
"""


# Parameters in the experiment
nTrials = 5
reaction_times = []

# Create a window and the circle
win = visual.Window() 
circle = visual.Circle(win, radius=0.1)

# Run the trials
for t in np.arange(nTrials):
    
    # Show an empty screen for 1 second
    win.flip()
    core.wait(1)
    
    # Show the circle until keypress  
    circle.draw()
    win.flip()
    keypressed = False
    t0 = core.getTime()
    while not keypressed:  
        k = event.getKeys()
        if k:
            reaction_times.append(core.getTime() - t0)
            break

# Close the window
win.close()
print(np.array(reaction_times) * 1000) # in ms

"""
Explanation: Example 3 - Reaction time test
Press space as soon as you circle appears. Reaction times are stored.
End of explanation
"""


import time
import matplotlib.pyplot as plt

# Run nLoops iterations
nLoops = 10000

loop_times = []
for i in range(nLoops):
    loop_times.append(time.time())
    
# The difference between two values are the loop-times (in microseconds)
loop_dur = np.diff(loop_times) * 1000000 

# Plot the results as a histogram (in milliseconds). Set the axis to [-1, +1] ms
plt.hist(loop_dur, bins=100, range = (-1, 1))
plt.show()    

# Compute the M \pm SD of loop-time
print('%.2f %.2f' % (np.mean(loop_dur), np.std(loop_dur)))

"""
Explanation: Question from class
How fast is one loop in  while/for loop?
End of explanation
"""


