r/programminghelp • • 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
7 Upvotes

8 comments sorted by

View all comments

Show parent comments

1

u/[deleted] Apr 15 '21

Output files should have 3 columns, all numbers. There will technically be 11 output files per single input file, but this is some junk data that may not contain every condition so there may only be like 7 or something. Currently it works but only outputs 3 files - these are in the proper format and contain the right values, they should just be split across more files based on the "StimuliCondition" parameter from the input file.

I also just realized the file name won't work like that. You will need to change the input file name to "JudgementTask_FINAL-101-1.txt" sorry!

1

u/[deleted] Apr 15 '21

I also just realized the file name won't work like that. You will need to change the input file name to "JudgementTask_FINAL-101-1.txt" sorry!

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)

1

u/[deleted] Apr 15 '21

There are 5 stimuli conditions:

Harm Accidental Intentional Weird Disgusting

There should be 2 output files for each one indexing the presentation of the stimuli and one indexing their ratings.

So if you check the file you're reading in to the script you'll see that "Harm" is the condition of the first trial (every time you see "Level: 2" in the input file its a new trial). So it's like the script finds that first condition and then just stops reading in that parameter.

1

u/[deleted] Apr 15 '21 edited Apr 15 '21

Just from looking at this I can tell you that it's looping either 4 or 5 times but since it's never moving past the first stimuli, then it's just writing the same 2 files that many times (over each other).

It looks like the start and target lines are never reset so when it finishes the first stimuli, it thinks it's at the end of the file and can't find anymore markers, so it exits. I'll dig into it, but it may take a while, my plate is a tad full until tomorrow at noon.

EDIT:

Also these lines:

fixationLength = getParameter(lines[startLine:targetLine], "jitter")
fixationLength = fixTRLength[int(fixationLength)]

Get the jitter value (say 3) and find the item in the dict at the top that matches, yes? If so, then when you have values of 4 in the jitter spot, what's going to happen? You only have 3 items in that dict. (The example file has a value of 4 twice)

fixTRLength = {
    1: SHORT_EVENT_LENGTH,
    2: LONG_EVENT_LENGTH,
    3: LONGER_EVENT_LENGTH,
}

2

u/[deleted] Apr 15 '21 edited Apr 15 '21

EDIT -

Thanks so much for the help! I actually got it figured out, it was something silly (as usual).

The FRAME_LABEL and TARGET_LABEL objects tell the script where it should be looking for things and these lines were just wrong. Also many thanks for pointing out the 'jitter' value problem! It works flawlessly now.