def openJSONFile(filename, sessionObject):

    global jsonObject, saveFilename

    #Open file, extract contents into string, and close the file
    try:
        sessionFile = open(file=filename, mode="r")

        if sessionObject:
            saveFilename = filename

        jsonString = sessionFile.read()

        sessionFile.close()

    except Exception:
        return "The file cannot be opened."

    #Convert string into python dictionary
    try:

        theJSONObject = json.loads(jsonString)

        if sessionObject:
            jsonObject = theJSONObject

    except Exception:
        return "The file is not in JSON format despite file extension."

    #Recreate session (or parameter) object using the settings in the header of the json file
    try:

        if sessionObject:
            ts.currentSession = ts.TheSession(mainWindow,
                                              theJSONObject["header"])
        else:
            loadedParameters = ts.TheSession(mainWindow,
                                             theJSONObject["header"])
            loadedParameters.outputSettingsToGUI(mainWindow)

    except KeyError:
        errorMessage = "The JSON file does not have all applicable information.\n"
        if sessionObject:
            errorMessage += "Was this session created in an older version of the program?"
        else:
            errorMessage += "Was this parameter file created in an older version of the program?"
        return errorMessage

    if sessionObject and len(theJSONObject["trials"]) == 0:
        return "This appears to be a parameter file, not a session file!"

    #Execution is finished and error-free so return empty quotes indicating no error message
    return ""
def saveAsParameterFile():

    #Pop up "Save As" window to retrieve file name and type to save as
    parameterFileName = QtGui.QFileDialog.getSaveFileName(
        parent=mainWindow.centralwidget,
        caption="Save As Parameter File",
        directory=getParameterFileDirectory(createIfNonexistent=True),
        filter="JSON (*.json)")[0]

    #Save parameter file if user didn't click cancel
    if len(parameterFileName) > 0:

        #Get parameters to save
        #Can't use ts.acquisitionParameters b/c need to be able to save in playback as well...
        #and ts.acquisitionParameters only updates when play mode is changed
        toSave = ts.TheSession(mainWindow)

        #Convert to JSON object
        paramJSONObject = toSave.outputSettingsToJSON()

        #Convert to string
        jsonString = json.dumps(paramJSONObject)

        #Open new file in write mode (overwrites any preexisting file with same name)
        sessionFile = open(parameterFileName, "w")

        #Write string to file
        sessionFile.write(jsonString)

        #Close file
        sessionFile.close()
Example #3
0
def setPlayMode(newPlayMode):

    global playMode

    #Can only change the play mode when there is no ongoing session
    if ts.currentSession:
        return

    #On program start, this is called to set the initial play mode...
    #which also initializes singleton instance of acquisition parameters
    if not playMode:
        ts.acquisitionParameters = ts.TheSession(mainWindow)

    #Before switching, perform necessary clean up for previous play mode
    #i.e. remember latest data acquisition mode parameters
    #ts.currentSession is wiped when done running session, but this remains
    elif playMode == PlayMode.ACQUISITION:
        ts.acquisitionParameters.readInSettingsFromGUI(mainWindow)

    #Remember new play mode
    playMode = newPlayMode

    #Update text that indicates play mode
    updateSessionInfoLabel()

    #Show buttons that belong to that play mode and hide buttons that do not. Also do hide before show so that the layout doesn't get stretched from excess shown buttons
    if playMode == PlayMode.ACQUISITION:
        mainWindow.previousButton.hide()
        mainWindow.nextButton.hide()
        mainWindow.lockButton.show()
        mainWindow.playButton.show()

    else:
        mainWindow.lockButton.hide()
        mainWindow.playButton.hide()
        mainWindow.previousButton.show()
        mainWindow.nextButton.show()

    #Enabled/disable menu actions that only work for a particular play mode
    mainWindow.actionRe_Analyze_Session.setEnabled(
        playMode == PlayMode.PLAYBACK)
    mainWindow.actionGenerate_Matrix_View.setEnabled(
        playMode == PlayMode.PLAYBACK)
    mainWindow.actionGoToTrial.setEnabled(playMode == PlayMode.PLAYBACK)

    #Lock settings in playback, unlock settings in data acquisition (session cannot be ongoing)
    mainWindow.lockButton.setEnabled(playMode == PlayMode.ACQUISITION)
    setLockModeForSettings(playMode == PlayMode.PLAYBACK)

    #Playback immediately opens session (so stop should be accessible), but opposite for acquisition
    mainWindow.stopButton.setEnabled(playMode == PlayMode.PLAYBACK)

    #When entering data acquisition, restore data acquisition parameters
    if playMode == PlayMode.ACQUISITION:
        ts.acquisitionParameters.outputSettingsToGUI(mainWindow)
Example #4
0
def setPlaying(play):

    #No pause/play in playback
    if playMode == PlayMode.PLAYBACK:
        return

    #Creates a session if there's not one already (there must be a current session)
    if not ts.currentSession:

        #Create session
        ts.currentSession = ts.TheSession(mainWindow,
                                          generatePseudoOrdering=True)

        #Perform set up specific to data acquisition...

        #Prepare session saving module
        JSONConverter.startDataAcquisition()

        #Display trial info label
        mainWindow.trialInfoLabel.setText("RUNNING TRIAL")
        mainWindow.trialInfoLabel.show()

    #Sets whether or not the graph is playing based off of the value of play
    tg.setPlaying(play)

    #Update play button icon
    if play:
        mainWindow.playButton.setIcon(pauseIcon)
    else:
        mainWindow.playButton.setIcon(playIcon)

    #Update trial info label
    if not tg.duringITI:
        if play:
            mainWindow.trialInfoLabel.setText("RUNNING TRIAL")
        else:
            mainWindow.trialInfoLabel.setText("TRIAL PAUSED")

    #Any interaction with play button means you cannot unlock the settings
    #...because a session must already be running
    mainWindow.lockButton.setEnabled(False)

    #The session can be stopped if the play button is interacted with
    #...because a session must already be running
    mainWindow.stopButton.setEnabled(True)
Example #5
0
def initialSetUp(theMainWindow):

    global programCrashing, settingsLocked, mainWindow, playMode, popUpFont
    global playIcon, pauseIcon, unlockedIcon, lockedIcon

    #Used when intercepting a window close event to determine what to do
    programCrashing = False

    #If false you can change the trial, session or system settings
    settingsLocked = False

    #Get reference to the main window
    mainWindow = theMainWindow

    #Set play and unlocked icons
    playIcon = mainWindow.playButton.icon()
    unlockedIcon = mainWindow.lockButton.icon()

    #Sets the icon for the pause button
    pauseIcon = QtGui.QIcon()
    pauseIcon.addPixmap(QtGui.QPixmap("Images/Pause Button.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)

    #Sets the icon for the locked button
    lockedIcon = QtGui.QIcon()
    lockedIcon.addPixmap(QtGui.QPixmap("Images/Locked Button.png"),
                         QtGui.QIcon.Normal, QtGui.QIcon.Off)

    #Define the font used in pop up windows
    popUpFont = QtGui.QFont()
    popUpFont.setPointSize(14)

    #Default play mode is data acquisition
    playMode = None
    setPlayMode(PlayMode.ACQUISITION)

    #Initialize visibility of paradigm parameters
    paradigmDropdownChanged(ts.Paradigm(0))

    connectButtons()
Example #6
0
def setPlaying(play):

    #Gets the current session
    if not ts.currentSession:
        ts.currentSession = ts.TheSession(mainWindow)

    #Sets whether or not the graph is playing based off of the value of play
    tg.setPlaying(play)

    #If play is true change the icon to the pause Icon
    if play:
        mainWindow.playButton.setIcon(pauseIcon)

    #Otherwise set the icon to the play icon
    else:
        mainWindow.playButton.setIcon(playIcon)

    #Any interaction with play button means you cannot unlock the settings
    mainWindow.lockButton.setEnabled(False)

    #The session can be stopped if the play button is interacted with
    mainWindow.stopButton.setEnabled(True)
Example #7
0
def paradigmDropdownChanged(newParadigmIndex):
    newParadigm = ts.Paradigm(newParadigmIndex)

    #ISI only for TRACE
    if newParadigm == ts.Paradigm.TRACE:
        mainWindow.isiImprovSpacer.show()
        mainWindow.interstimulusIntervalSpinBox.show()
        mainWindow.interstimulusIntervalLabel.show()
    else:
        mainWindow.isiImprovSpacer.hide()
        mainWindow.interstimulusIntervalSpinBox.hide()
        mainWindow.interstimulusIntervalLabel.hide()

    #US not part of EXTINCT
    if newParadigm == ts.Paradigm.EXTINCT:
        mainWindow.usImprovSpacer.hide()

        mainWindow.usNameLineEdit.hide()
        mainWindow.usNameLabel.hide()

        mainWindow.usDurationSpinBox.hide()
        mainWindow.usDurationLabel.hide()

        mainWindow.usDelaySpinBox.hide()
        mainWindow.usDelayLabel.hide()
    else:
        mainWindow.usImprovSpacer.show()

        mainWindow.usNameLineEdit.show()
        mainWindow.usNameLabel.show()

        mainWindow.usDurationSpinBox.show()
        mainWindow.usDurationLabel.show()

        mainWindow.usDelaySpinBox.show()
        mainWindow.usDelayLabel.show()
def verifySettingsValid():

    global params

    #Create temporary session object from parameter panel for easy access to parameters
    params = ts.TheSession(im.mainWindow)

    settingsValidityText = "Current settings are invalid for the following reasons:\n\n"
    invalidSettings = False

    paradigm = params.paradigm

    if paradigm == ts.Paradigm.PSEUDO:
        if not pseudoDurationIsValid():
            invalidSettings = True
            settingsValidityText += "Trial duration must be >= baseline + CS and baseline + US for pseudo paradigm\n"

        if not (params.trialCount % 2 == 0):
            invalidSettings = True
            settingsValidityText += "Number of trials must be even for pseudo paradigm\n"

    elif paradigm == ts.Paradigm.TRACE:
        if not traceDurationIsValid():
            invalidSettings = True
            settingsValidityText += "Trial duration must be >= baseline + CS + ISI + US for trace paradigm\n"

    elif paradigm == ts.Paradigm.EXTINCT:
        if not extinctDurationIsValid():
            invalidSettings = True
            settingsValidityText += "Trial duration must be >= baseline + CS for extinction paradigm\n"

    elif paradigm == ts.Paradigm.DELAY:
        if not extinctDurationIsValid(): #Extinction and delay have same duration check
            invalidSettings = True
            settingsValidityText += "Trial duration must be >= baseline + CS for delay paradigm\n"

        if params.usDuration > params.csDuration:
            invalidSettings = True
            settingsValidityText += "US duration must be <= CS duration for delay paradigm\n"

    if params.trialDuration < 100:
        invalidSettings = True
        settingsValidityText += "Trial duration must be >= 100 ms\n"

    if params.baselineDuration < 100:
        invalidSettings = True
        settingsValidityText += "Baseline duration must be >= 100 ms\n"

    if not usSignalStartIsValid():
        invalidSettings = True
        settingsValidityText += "US start - US signal delay must be >= 0\n"

    if not sessionNameIsValid():
        invalidSettings = True
        settingsValidityText += "Session name may not contain any of the following characters: \\ / : * ? \" < > |\n"

    if invalidSettings:
        invalidSettingsNotice = QMessageBox()
        invalidSettingsNotice.setText(settingsValidityText)
        invalidSettingsNotice.setWindowTitle("Invalid Settings")
        invalidSettingsNotice.setStandardButtons(QMessageBox.Ok)
        invalidSettingsNotice.setIcon(QMessageBox.Warning)
        invalidSettingsNotice.setFont(im.popUpFont)
        invalidSettingsNotice.exec()

    return not invalidSettings