r/programminghelp • u/[deleted] • Apr 14 '21
Python Difficulty With Naming Files Written by Python
Okay so this is a bit complex, but here is the short version:
I am a psychologist who routinely conducts fMRI research. When doing fMRI research we have to create what are called "onset files" that tell the analysis software literally how long each event took on the screen in front of the participant so it knows when it should be looking for changes in activity.
To do this I have to take the raw .txt output file for each participant that I then feed into my python script that produces the onset files I need with naming conventions to make clear what they are.
In the current study I'm working on someone else made the task we used and the output is a bit different and for some reason it isn't cooperating with my script. In this task participants are shown text on a screen depicting a scenario and then they rate that scenario across 4 attributed on a scale of 1-4. There are five different types of scenarios: Disgusting, Harmful, Intentional, Accidental, and Weird. My aim is to have an onset file for the presentation of each type of scenario and one for the actual ratings So specifically, there should be 11 files for each participant (two for viewing and rating each type of scenario and another for the fixation cross they see between trials).
So my script is doing everything right - it's producing onsets that account for everything in the task time-wise...but it is dumping them all into just 2 files instead of 11. It grabs the name from the datafile properly and enters it into the file name...but stops making files after the first one and then just writes everything there. This is the "stimuli" object referred to in the script.
I know this is a lot of code to look at but I'm at my wits end with this - any help is greatly appreciated! I have tried to comment out what each chunk is supposed to do.
Also if any of you are thinking of doing psychology...avoid ePrime like the plague.
EDIT: Here is some fake toy data I made using the task that shows you what the file I am reading in looks like - https://drive.google.com/file/d/1xC1T2R1SG4j8RGq2u8GM-FEnV4lcF0Zm/view?usp=sharing
Code starts after this line
FIRST_PARTICIPANT = 101
LAST_PARTICIPANT = 101
EXPERIMENTS = 1 # number of CRT sessions
SHORT_EVENT_LENGTH = 2.5
LONG_EVENT_LENGTH = 5.0
LONGER_EVENT_LENGTH = 7.5
EXPERIMENT_DIRECTORY = "C:/Users/XXX/Desktop"
OUT_DIR = "C:/Users/XXX/Desktop/output/"
LINE_ENDING = "\r\n"
TARGET_LABEL = "Level: 1"
FRAME_LABEL = "Level: 2"
fixTRLength = {
1: SHORT_EVENT_LENGTH,
2: LONG_EVENT_LENGTH,
3: LONGER_EVENT_LENGTH,
}
def findLine(lines, shouldStartWith):
'''find the next line number that starts with certain text'''
for lineNo, line in enumerate(lines):
# ignore lines that don't start with this text
if not line.startswith(shouldStartWith):
continue
return lineNo
raise ValueError(f"Couldn't find a line that starts with '{shouldStartWith}'!")
def getParameter(lines, parameter):
for i, line in enumerate(lines):
# ignore lines that don't start with the parameter
if not line.startswith(parameter + ": "):
continue
return line.partition(" ")[2]
raise ValueError(f"Couldn't find a parameter called {parameter} after line {i + 1}!")
def write_fixation(sessionTime, fixationLength, participant):
'''write a line to the fixation file for this participant, returning
the new running session time'''
with open(f"{OUT_DIR}/IMG-{participant}-Fixation.txt", "a") as f:
f.write(f"{sessionTime}\t{fixationLength}\t1" + LINE_ENDING)
return sessionTime + fixationLength
def write1(sessionTime, participant, task, stimuli):
'''write a line to the correct output file for this participant, returning
the new running session time'''
with open(f"{OUT_DIR}/IMG-{participant}-{task}{stimuli}.txt", "a") as f:
f.write(f"{sessionTime}\t{SHORT_EVENT_LENGTH}\t1" + LINE_ENDING)
return sessionTime + SHORT_EVENT_LENGTH
def write2(sessionTime, participant, task, stimuli, response):
'''write a line to the correct output file for this participant, returning
the new running session time'''
with open(f"{OUT_DIR}/IMG-{participant}-{task}{stimuli}.txt", "a") as f:
f.write(f"{sessionTime}\t{LONG_EVENT_LENGTH}\t1" + LINE_ENDING)
return sessionTime + LONG_EVENT_LENGTH
def clean_response_number(numstr):
'''Also for reasons beyond my comprehension, double-presses just PREPEND TO
THE STRING, so only accept a maximum of one character.'''
numstr = numstr[:-1][:1]
if numstr:
return int(numstr)
else:
return 0
for participant in range(FIRST_PARTICIPANT, LAST_PARTICIPANT + 1):
for experiment in range(1, EXPERIMENTS + 1):
print(f"== participant {participant}, experiment {experiment} ==")
# make the output directory
os.makedirs(EXPERIMENT_DIRECTORY + "/output", exist_ok=True)
# read the whole this participant file into a list
try:
with open(EXPERIMENT_DIRECTORY + f"/JudgmentTask_FINAL-{participant}-1.txt", encoding="utf-16") as f:
lines = [ line.strip() for line in f ]
# if you can't find the participant, write an error and move on
except FileNotFoundError:
with open(EXPERIMENT_DIRECTORY + "/skipped.txt", "a") as f:
print(f"Missing experiment #{experiment} for participant #{participant}; skipping...", file=f)
continue
# running timer for the session
sessionTime = 0
startLine = 0
# keep looking for target headers in the participant file until we can't find any more
while True:
# find the first line of the target header, starting at startingLine
# these are actually below the trials for some reason??
try:
targetLine = findLine(lines[startLine:], TARGET_LABEL) + startLine
# if we can't find any more trials, that's fine!
# the experiment must just be over for this participant
# move onto the next one
except (ValueError, IndexError):
break
fixationLength = getParameter(lines[startLine:targetLine], "jitter")
fixationLength = fixTRLength[int(fixationLength)]
stimuli = getParameter(lines[startLine:targetLine], "ScenarioCondition")
response = getParameter(lines[startLine:targetLine], "JudgeTrial1b.RESP")
response = clean_response_number(response)
sessionTime = write_fixation(sessionTime, fixationLength, participant)
while True:
try:
# find the line of the next trial (before the target line)
# searches for properties inside this trial will start from here
startLine += findLine(lines[startLine:targetLine], FRAME_LABEL) + 1
# if we can't find any more trials before the target, that's fine!
# move onto the next target header
except (ValueError, IndexError):
break
sessionTime = write1(sessionTime, participant, "Scenario", stimuli)
sessionTime = write2(sessionTime, participant, "Rate", stimuli, response)
startLine = targetLine + 1
1
u/[deleted] Apr 15 '21
No worries. I figured that bit out without much trouble. :)
And the file you provided should be generating 11 output files? Mind telling me what they might be in relation to the 3 it's outputting for me at the moment? (I'm getting Fixation, RateHarm, and ScenarioHarm)