I am working with a Pandas dataFrame of an experiment that describes hand and head coordinates in VR (just_trials). In each trial, a virtual environment appears, then a black screen, and then again a virtual environment.
I have a column that describes the trial number ("staircaseCounterIndex", and another column that describes what the subject sees: a room or a black screen ("SceneName").
For example:
Because the data set shows me millisecond coordinates of motion, the values in SceneName, and in staircaseCounterIndex do not change as long as the scene has not changed or the trial is over, respectively.
I want to add a new column to the data set that will count me the times the subject has seen the room (i.e. after a room has appeared when previously there was a black screen will add +1 to the count).
Below is the code:
step_index = []
first_step = -2
step_num = 0
for i in range(2, np.shape(just_trials)[0]):
print(i)
if (first_step == just_trials['staircaseCounterIndex'][i]) and (just_trials['SceneName'][i] == 'Room'): # and just_trials['SceneName'][i-1] == 'Room': ## **Here is the error** ##
step_index.append(step_num)
elif just_trials['SceneName'][i] == 'BlackScreen':
step_index.append(0)
else:
step_num += 1
first_step = just_trials['staircaseCounterIndex'][i]
step_index.append(step_num)
My problem is that when I try to run the code pycharm encounters an error in the third iteration of the For loop:
the line where the error occurs is marked in the code above.
But when I run the debugger, everything works just fine.
Would be thankful for your help,
Paz.
Try with .iloc for indexing.
just_trials['staircaseCounterIndex'].iloc[i]
Related
I'm making an evolution simulator using python 3.8.1 in windows 10.
In the code a matrix called temperatures (storing temperature of every cell in the world matrix) is imported and initialised to contain only 0s, it is also never called in the code except for where the problem arose.
world_data = load_progress()
## other parameters ##
temperatures = world_data["temperatures"]
code to import the matrix ^^
def late_update():
global temperatures
## other updates ##
for row in temperatures:
for tempr in row:
tempr += 1
function where the matrix is modified ^^
while run:
## just some keyboard controls ##
update()
late_update()
updateGFX()
mainloop ^^
(as you can see the temperatures are the last to be updated because updateGFX updates another matrix)
If i exit the mainloop and check the value of temperatures every unit in the matrix is 0 (whenever i kill the code) instead of a positive number. Whereas if i print the output like this :
for row in temperatures:
for tempr in row:
tempr += 1
print(tempr)
in the console only 1s will appear (i waited 20 minutes and checked so i'm quite sure) pointing out that right after the loop the temperatures will reset (also if i print the matrix after the loop it's just 0 so it's confirmed).
I tried to update temperatures directly in the mainloop outside late_update but it was the same.
I also tried making a copy of the matrix with the copy module like this:
temperatures_copy = copy.deepcopy(temperatures)
for row in temperatures_copy:
for tempr in row:
tempr += 1
temperatures = copy.deepcopy(temperatures_copy)
Then literally before posting the question i remembered about list comprehensions and changed the code to:
temperatures = [[tempr + 1 for tempr in row] for row in temperatures]
and it worked.
Since this may be also a problem for future development though, i'll still ask the question about
why a list matrix can't be modified in an annidated loop (inside another loop) but can be if the annidated loop is turned into a list comprehension.
Thanks for your patience.
I'm working on a data science project to make some prediction, and I need to calculate a new column based on other column values.
All is working fine, except that my Jupyter-lab is printing me blank lines in my output and I don't know why.
Here's the code :
# Calcul A :
pas = 1500
TailleTotal = len(df)
limite=TailleTotal-pas
df['A'] = np.empty(TailleTotal, dtype = float)
index=0
while index < limite :
A_temp = 0
A_temp = np.sqrt((df['X'][index]**2)+(df['Y'][index]**2)+(df['Z'][index]**2))
df['A'][index]=A_temp
index = index+1
And when I run it, I have a blank line for every iteration.. My files is making more than 1M lines, I have to scroll all over in my code it's very annoying.
But it's more that I really don't understand why it does this, I have no print function or anything that is supposed to show me something.. So why Python have this need to show me empty lines ? It's because I have no "return" in my loop ?
Edit : It appears to be a "output memory" problem from Jupyter-lab. Right clicking and "clear all output" is resolving my issue
You have an infinite loop, first change the while and try to do maybe 1 or 2 iterations and check if the problem is the same. I'm prety sure that dissapears. The kernel should be consuming resources for your loop.
I am fairly new to the python language and psychopy. I am practicing it by creating dummy experiments. Here, I am trying to create an experiment about bayesian brain. Non-vertical lines will be presented to the participant while no respond is expected from the participants, just exposure. Then for the last trial (it stays on the monitor for longer period of time to be responded), it is expected from the participant to judge whether the last line trial is vertical or not? (after exposing to non-vertical lines, I am expecting to see a change in perception of verticality).
However, there are so many things that I couldn't learn from the web. I am pretty sure you guys can help me easily.
My primary problem is; how to set up the orientation of the line? I found out the stim.ori but not sure how to use it on 'line' stimuli. Below I've attached the codes that I made so far. Also, I have added some extra questions with #.
I tried to be clear as much as I can. Sorry for my bad english.
Thank you!
from psychopy import visual, core, event #import some libraries from PsychoPy
import random
#create a window
mywin = visual.Window([800,600],monitor="testMonitor", units="deg")
#stimuli
lineo = visual.Line(mywin, start=(-5, -1), end=(-5, 1))
fixation = visual.GratingStim(mywin, size=0.2, pos=[0,0], color = 'black')
#draw the stimuli and update the window
n = 5 # trial number
i = 0
while i < n:
#fixation
fixation.draw()
mywin.flip()
presses = event.waitKeys(1)
# stimulus
orientationlist = [20,30,40,50,60] # I want to draw the orientation info from this list
x = random.choice(orientationlist)
lineo.ori((x)) #
lineo.draw()
mywin.flip()
presses= event.waitKeys(2)
i +=1
if i == 5: # how do I change the number into the length of the trial; len(int(n) didnt work.
lineo.draw()
mywin.flip()
presses = event.waitKeys(4)
#quiting
# I dont know how to command psychopy for quiting the
# experiment when 'escape' is pressed.
#cleanup
mywin.close()
core.quit()
There's a few things that you would want to do differently. I've updated your code and marked changes with the comment "CHANGE". Changing the orientation of a stimulus is pretty consistent in psychopy, so it's no different for Line than any other visual stimulus type.
from psychopy import visual, core, event #import some libraries from PsychoPy
import random
#create a window
mywin = visual.Window([800,600],monitor="testMonitor", units="deg")
#stimuli
lineo = visual.Line(mywin, start=(-5, -1), end=(-5, 1))
fixation = visual.GratingStim(mywin, size=0.2, pos=[0,0], color = 'black')
orientationlist = [20,30,40,50,60] # CHANGED. No need to redefine on every iteration of the while-loop.
#draw the stimuli and update the window
n = 5 # trial number
for i in range(n): # CHANGED. This is much neater in your case than a while loop. No need to "manually" increment i.
#fixation
fixation.draw()
mywin.flip()
event.waitKeys(1) # CHANGED. No need to assign output to anything if it isn't used.
# stimulus
lineo.ori = random.choice(orientationlist) # CHANGED. Alternative: lineo.setOri(random.choice(orientationlist)).
lineo.draw()
mywin.flip()
event.waitKeys(2)
# At this point, all the stimuli have been shown. So no need to do an if-statement within the loop. The following code will run at the appropriate time
lineo.draw()
mywin.flip()
event.waitKeys(keyList=['escape']) # CHANGED. Listen for escape, do not assign to variable
# CHANGED. No need to call core.quit() or myWin.close() here since python automatically cleans everything up on script end.
In my experiment I'm showing a random generated stimulus 'x', which I need to compare to a key that's been giving in by the user of the experiment.
Basically, I have two lists:
one with the stimuli
and one with the correct answers (the keys they should give)
The order is the same, by which I mean that stimulus 1 should get the key that's at 'place 1' in the list with answers.
I've searched several topics on how to compare these two lists but so far it hasn't been working.
These are the options I've tried:
Answerruning = True
while Answerrunning:
if event.getKeys(keyList):
ReactionTime.getTime()
Keys = event.waitKeys()
for givenKey in Keys:
if givenKey == keyList:
answer_stimulus = 2
Answerrunning = False
window.flip(clearBuffer = True)
else:
answer_stimulus = 0
And this option but I think the other one is better:
keyList = []
givenKey = event.getKeys(keyList)
Answerrunning = True
while Answerrunning:
for x in stimulus:
if givenKey in keyList:
ReactionTime.getTime()
answer_stimulus = 2
Answerrunning = False
window.flip(clearBuffer = True)
else:
answer_stimulus = 0
I hope one of you can give me a hint on the problem how to compare those two en from there on my window will clear en the experiment can go on.
You don't mention this, but you really need to be using a TrialHandler object http://www.psychopy.org/api/data.html which will handle the variables for you, stepping through your conditions file (.xlsx or .csv) a row at a time for each trial. i.e. don't put the stimulus and correct response values in lists: put them in an external file, and let PsychoPy do the housekeeping of managing them trial by trial.
If you have a column in that file called correctResponse, another called stimulusText, and a TrialHandler called trials, then some pseudo-code would look like this:
trialClock = core.Clock() # just create this once, & reset as needed
# trials is a TrialHandler object, constructed by linking to an
# external file giving the details for each trial:
for trial in trials:
# update the stimulus for this trial.
# the stimulusText variable is automatically populated
# from the corresponding column in your conditions file:
yourTextStimulus.setText(stimulusText)
# start the next trial:
trialClock.reset()
answerGiven = False
while not answerGiven:
# refresh the stimuli and flip the window
stimulus_1.draw() # and whatever other stimuli you have
win.flip() # code pauses here until the screen is drawn
# i.e. meaning we are checking for a keypress at say, 60 Hz
response = event.getKeys() # returns a list
if len(response) > 0: # if so, there was a response
reactionTime = trialClock.getTime()
# was it correct?
if correctResponse in response:
answer = True
else:
answer = False
# store some data
trials.addData('Keypress', response)
trials.addData('KeypressRT', reactionTime)
trials.addData('KeypressCorrect', answer)
# can now move on to next trial
answerGiven = True
PsychoPy code is generally constructed around a cycle of drawing to the screen on every refresh, so the code above shows how within each trial, the stimulus is updated once but redrawn to the screen on every refresh. In this cycle, the keyboard is also checked once every time the screen is redrawn.
In your code, you are mixing getKeys(), which checks the instantaneous state of the keyboard, and waitKeys(), which pauses until a response is given (and hence breaks the screen refresh cycle). So gerenally avoid the latter. Also, when you use getKeys(), you have to assign the result to a variable, as this function clears the buffer. Above, you use getKeys() and then follow up by checking the keyboard again. In that case, the initial response will have disappeared, as it wasn't stored.
Clear as mud?
I'm a student learning to program, and my current assignment is to write a graphing calculator using the Simple Graphics library. I got everything working, except for coloring the lines. The first line should be red, the second should be green and the third one blue, then they repeat. Here is the code I added for the colors:
if count % 3 == 1:
print("red")
setColor = ("red")
elif count % 3 == 2:
print("green")
setColor = ("green")
else:
print("blue")
setColor = ("blue")
Earlier in the code, I set count = 1 and at the end of my drawing loop, I have count = count + 1.
Whenever I try to use the program, all the lines appear black. When I look at the terminal, I see "red", "green" and "blue" all being printed successfully at the right times. Using RGB values to define the color doesn't help either.
Does anyone have any idea of what I could be doing wrong? I can post the entire code for drawing the lines, but I thought people wouldn't want to sift through 30 lines.
setColor = ("color") should just be setColor("color"). setColor is a function, that takes in input and performs an action. If it was a variable, which is just a name for some data that you will provide, your code would be correct. (Variables almost never have verbs in their names.)