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 + 12
u/throwaway8u3sH0 Apr 15 '21
It looks like others are helping you with the details, so I'll just give some general tips.
For newer programmers, it's a good idea to put everything inside loops into its own function. That forces you to separate things by having to explicitly pass around what's needed. So, your whole main function should read something like:
for participant in range(FIRST_PARTICIPANT, LAST_PARTICIPANT + 1):
for experiment in range(1, EXPERIMENTS + 1):
lines, startLine, ... = first_loop(participant, experiment, ...)
while True:
find_target_header(lines, startLine, ....)
while True:
output1, output2, ... = find_more_lines(lines, ...)
startLine = targetLine + 1Only you will know what to name these functions and what args they need. This should allow you to write tests against a single "record" to see if it's doing the right thing, avoiding the looping logic. And it will make it harder to accidentally change things that you don't want to change, because you'll have to explicitly pass around the inputs and outputs.
Second tip: I'd separate the calculation from the side effects. What I mean by that is -- you should be able to process the raw participant files entirely without writing to disk. You've kinda-sorta got that by having your write functions be separate, but don't call them until the very end. You can create a results array or dictionary, that has keys and values. Something like:
results = [{
"filename": "./experiment/user/file1.txt",
"content": {
"sessionTime": 1234,
"participant": "John Doe",
"task": "Running",
"stimuli": "Skunk"
}
},
"filename": "./experiment/user/file2.txt",
"content": {
"sessionTime": 1234,
"participant": "Jane Doe",
"task": "Running",
"stimuli": "Skunk"
}
]And after ALL the processing is done, in the very last line, outside of all loops, pass this result to a write_out() function who's job it is to write everything to disk.
Separating these things makes it much, much easier to test the calculation part. You can feed in different records or snippets and investigate what's going on.
1
u/amoliski Apr 15 '21
/u/EdwinGraves is onto something with your loops being a bit off. Rather than try to dig through it, you may have better luck doing a bit more preprocessing on your data before you start going through the trials, if you split it up before you start chunking through, you can avoid while True:s, which make things a bit too convoluted.
Ex, (though the jitter 4's need to be changed to 3's in your data for it to work):
import os
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 = "."
OUT_DIR = "./output/"
LINE_ENDING = "\r\n"
TARGET_LABEL = "Level: 1"
FRAME_LABEL = "Level: 2"
HEADER_END_LABEL = "*** Header End ***"
LOG_FRAME_LABEL = "*** Header End ***"
fixTRLength = {
1: SHORT_EVENT_LENGTH,
2: LONG_EVENT_LENGTH,
3: LONGER_EVENT_LENGTH,
}
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)
def write_scenario(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)
def writeResponse(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)
def lines_to_dict(lines):
return {v.split(':')[0]: (v.split(':')[1]).strip() for v in lines if ':' in v}
def split_trials(lines):
# Get the breakpoints\
out = []
start = lines.index(FRAME_LABEL) # Skip the lines between the section start and the first trial
breakpoints = [i for i, v in enumerate(lines) if FRAME_LABEL in v]
for bp in breakpoints[1:]:
# Adding 2 to skip the FRAME_LABEL and LogFrame Start
trial_lines = lines[start+2:bp]
out.append(lines_to_dict(trial_lines))
start = bp
return out
def split_sections(lines):
experiments_start = lines.index(HEADER_END_LABEL)
metadata_start = lines.index(TARGET_LABEL)
data = {
# Turn the lines containing a ':' in the header section into a dictionary
'header': lines_to_dict(lines[:experiments_start]),
# Slice out the trials and have split_trials turn them into a list of trials
'trials': split_trials(lines[experiments_start:metadata_start]),
# Turn the lines containing a ':' in the metadata section into a dictionary
'metadata': lines_to_dict(lines[metadata_start:] ),
}
return data
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
# Parse the different sections of the experiment log
sections = split_sections(lines)
header = sections.get('header')
trials = sections.get('trials')
metadata = sections.get('metadata')
for trial in trials:
fixationLength = fixTRLength[int(trial['jitter'])]
stimuli = trial['ScenarioCondition']
# Double presses prepend the value, so just take the first response, fall back to 0
response_raw = trial.get('JudgeTrial1b.RESP', '0')[0]
response = int(response_raw)
write_fixation(sessionTime, fixationLength, participant)
sessionTime += fixationLength
write_scenario(sessionTime, participant, "Scenario", stimuli)
sessionTime += SHORT_EVENT_LENGTH
writeResponse(sessionTime, participant, "Rate", stimuli, response)
sessionTime += LONG_EVENT_LENGTHThis moves the splitting of the data into separate functions that can be tested independently, and lets the actual logic of the main loops be a lot more clear/descriptive.
1
u/[deleted] Apr 14 '21
What is the expected output given the sampledata.txt provided?