Exemplo n.º 1
0
def ExtractEvent():
doc = nex.GetActiveDocument()
#extract events
#please refer to the arduino file
doc["TrialEnd"] = nex.MarkerExtract(doc, "Strobed", "=242,EOF,END")
doc["TrialStart"] = nex.MarkerExtract(doc, "Strobed", "=2,EOF,END")
doc["Cue"] = nex.MarkerExtract(doc, "Strobed", "=6,OR,=12,EOF,END")
doc["Incorrect"] = nex.MarkerExtract(doc, "Strobed", "=48,EOF,END")
doc["correct"] = nex.MarkerExtract(doc, "Strobed", "=10,OR,=64,EOF,END")
doc["stim"] = nex.MarkerExtract(doc, "Strobed", "=84,OR,=68,OR,=124,OR,=70,EOF,END")
doc["Choice"] = nex.MarkerExtract(doc, "Strobed", "=26,OR,=4,EOF,END")


#make trials
#The interval include (trial start -2s) to Trial end(Choice or omission or early termination)
doc["Trial"] = nex.MakeIntFromStart(doc["TrialStart"], doc["TrialEnd"],  - 2, 0)


#seperate trials into correct/incorrect/early/omission

doc["CorrectTrial"] = nex.IntFind(doc["Trial"], doc["correct"])
doc["inCorrectTrial"] = nex.IntFind(doc["Trial"], doc["Incorrect"])
#doc["EarlyTrial"] = IntFind(doc["Trial"], doc["Early"])
#doc["OmissionTrial"] = IntFind(doc["Trial"], doc["Omission"])

#check correct algorithm


def MergeFile(InputPl2path,OutputNexPath,InputUnitspath)
Exemplo n.º 2
0
def Calculate():
    '''
    the main calculate function for Python analysis in NeuroExplorer
    - unpacks parameters
    - calls SyncIndex or SyncIndexPhase
    - generate results for NeuroExplorer
    '''

    doc = nex.GetActiveDocument()
    if not doc:
        raise ValueError('open data file first')
    inputJson = doc.GetPythonAnalysisInput()
    if not inputJson:
        raise ValueError('this script should be run from Python analysis only')

    inputPars = json.loads(inputJson)

    phaseMethod = int(inputPars['ScriptParameters']['PhaseMethod'])
    binSize = float(inputPars['ScriptParameters']['Bin (Seconds)'])
    numShuffles = int(inputPars['ScriptParameters']['Number of Shuffles'])
    K = float(inputPars['ScriptParameters']['K threshold'])

    variableNames = inputPars['Variables']
    if not variableNames:
        raise ValueError('no variables selected')

    theVars = []
    for v in variableNames:
        theVars.append(doc[v['Name']])

    if not theVars:
        raise ValueError('no variables selected')
    if len(theVars) < 2:
        raise ValueError('only one variable selected')

    if phaseMethod == 0:
        synIndex = SyncIndex(doc, theVars, numShuffles, binSize, K)
    else:
        synIndex = SyncIndexPhase(doc, theVars, numShuffles, binSize, K)

    globalSI = max(synIndex)
    result = {}
    result['XAxisLabel'] = 'Sync. Index Number'
    result['YAxisLabel'] = 'Sync. Index Value'
    xvalues = np.arange(1, len(synIndex) + 1, 1).tolist()
    result['XValues'] = xvalues
    result['YValues'] = synIndex.tolist()

    graphicsCommands = []
    text = 'Global Synch. Index = {:.5f}'.format(globalSI)
    middleX = min(xvalues) + (max(xvalues) - min(xvalues)) / 2 - 0.5
    textY = globalSI
    if textY == 0:
        textY = 1
    graphicsCommands.append(MakeText(0, middleX, textY, text, 10))

    doc.SetPythonAnalysisOutput(json.dumps(result))
    doc.SetProperty('AdditionalGraphicsCommands', graphicsCommands)
Exemplo n.º 3
0
def Calculate():
    doc = nex.GetActiveDocument()
    # get the variable info and values of script parameters
    inputJson = doc.GetPythonAnalysisInput()
    inputPars = json.loads(inputJson)

    # get all analysis parameters (we need to get data selection options)
    parsJson = doc.GetAllAnalysisParameters()
    pars = json.loads(parsJson)

    variable = inputPars['Variable']

    if variable['Type'] != 'Continuous':
        raise ValueError('This analysis can only analyze Continuous variables')

    filteredVar = IntervalFilterVarIfNeeded(doc, doc[variable['Name']], pars)

    v = filteredVar.ContinuousValues()
    numberOfContValues = len(v)
    if numberOfContValues > 100000:
        raise ValueError('Too many Continuous values')

    freqFrom = float(inputPars['ScriptParameters']['Show Frequency From'])
    freqTo = float(inputPars['ScriptParameters']['Show Frequency To'])
    samplingRate = float(variable['SamplingRate'])

    spectrumStep = samplingRate / numberOfContValues
    spectrum = nex.Spectrum(v)
    s = sum(spectrum)

    result = {}
    result['XAxisLabel'] = 'Frequency (Hz)'
    result['YAxisLabel'] = 'Spectrum (%)'
    result['XValues'] = []
    result['YValues'] = []
    for i in range(len(spectrum)):
        freq = i * spectrumStep
        if freq >= freqFrom and freq <= freqTo:
            result['XValues'].append(freq)
            result['YValues'].append(100.0 * spectrum[i] / s)

    if len(result['XValues']) == 0:
        raise ValueError('Frequency range is too narrow: frequency step = ' +
                         str(spectrumStep))

    doc.SetPythonAnalysisOutput(json.dumps(result))
Exemplo n.º 4
0
# converted from NexScript 'C:\Users\309i7\Documents\NeuroExplorer 5\Scripts\Shifting\ExtractEvents.nsc'
from __future__ import division
import nex
import math
import sys
import json

doc = nex.GetActiveDocument()
filename = nex.GetDocTitle(doc)
print('You are extracting steady trials from this file: ' + filename)

#usually the first channel is 1st_Anti_AfterPro
#The second channel is 1st_Pro_AfterAnti
first_Anti_AfterSwitch = nex.GetVarByName(doc,
                                          '1st_Anti_AfterPro').Timestamps()
first_Pro_AfterSwitch = nex.GetVarByName(doc, '1st_Pro_AfterAnti').Timestamps()
ProTs = nex.GetVarByName(doc, 'Pro').Timestamps()
AntiTs = nex.GetVarByName(doc, 'Anti').Timestamps()

Num_Pro_Steady = len(first_Anti_AfterSwitch)
Num_Anti_Steady = len(first_Pro_AfterSwitch)
print('Steady Trials in Pro Task has ' + str(Num_Pro_Steady) + ' blocks')
print('Steady Trials in Anti Task has ' + str(Num_Anti_Steady) + ' blocks')


#This is event based on pro and anti cue.
def GetSteadyBlock(Num_Steady, TrialTs, first_AfterSwitch, TrialType):
    #Get steady block from pro/anti trials
    for i in range(Num_Steady):
        steady_all_ts = [ts for ts in TrialTs if ts <= first_AfterSwitch[i]]
        steady_ts = steady_all_ts[-20:]
Exemplo n.º 5
0
def FindPeaksAndAddColumnsAndGraphicsCommands():
    doc = nex.GetActiveDocument()

    deltaPercentString = doc.GetPostProcessingScriptParameter()
    try:
        deltaPercent = float(deltaPercentString)
    except:
        deltaPercent = 25

    res = doc.GetAllNumericalResults()
    resNames = doc.GetNumResColumnNames()

    if len(resNames) < 2:
        raise ValueError(
            'Numerical Results table need to have at least 2 columns (x an y)')

    # the first column should contain X axis values
    if not resNames[0] in [
            'Bin Left', 'Bin Middle', 'Bin Right', 'Frequency Value', 'Time'
    ]:
        raise ValueError('No x data in Numerical Results')

    # select only columns with real graph names
    # (we may have columns with confidence, standard deviation, etc.)
    sumNumRes = doc.GetAllNumResSummaryData()
    # real graph names are specified in the first column
    # of summary of numerical results
    realGraphNames = sumNumRes[0]
    graphIndexes = []
    for i in range(len(resNames)):
        if resNames[i] in realGraphNames:
            graphIndexes.append(i)

    numResults = len(graphIndexes)
    # first column of numerical results contains x values
    x = res[0]
    xRange = max(x) - min(x)
    # we may need to adjust x to draw peak center at bin center
    step = x[1] - x[0]
    xAdjustment = 0
    if resNames[0] == 'Bin Left':
        xAdjustment = step * 0.5
    if resNames[0] == 'Bin Right':
        xAdjustment = -step * 0.5

    # prepare empty columns with peak info
    columns = []
    # we will report up to 5 peaks
    maxNumPeaks = 5
    for i in range(maxNumPeaks):
        columns.append(MakeEmptyColumn('PeakValue' + str(i + 1), numResults))
        columns.append(MakeEmptyColumn('PeakPosition' + str(i + 1),
                                       numResults))

    graphicsCommands = []
    # for each graph, find peaks and add columns and graphical commands
    for igraph in range(len(graphIndexes)):
        y = res[graphIndexes[igraph]]
        yRange = max(y) - min(y)
        if yRange > 0:
            delta = yRange * deltaPercent / 100.0
            peaks = PeakDetect(x, y, delta)
            for ip in range(len(peaks)):
                xp = peaks[ip][0] + xAdjustment
                yp = peaks[ip][1]
                if ip < maxNumPeaks:
                    # fill extra columns
                    columns[ip * 2]['values'][igraph] = '%.6f' % (yp)
                    columns[ip * 2 + 1]['values'][igraph] = '%.6f' % (xp)
                # add graphics commands
                dx = xRange * 0.010
                dy = yRange * 0.015
                # add graphics commands to draw 'x' (red diagonal lines) at each peak
                graphicsCommands.append(
                    MakeLine(igraph, xp - dx, yp - dy, xp + dx, yp + dy, 2.0,
                             '(255;0;0)'))
                graphicsCommands.append(
                    MakeLine(igraph, xp - dx, yp + dy, xp + dx, yp - dy, 2.0,
                             '(255;0;0)'))
                # add text command showing x value of the peak
                # if you want both x and y, use
                # peakText = '(%.3f,%.3f)'%(xp,yp)
                peakText = '%.3f' % (xp)
                graphicsCommands.append(
                    MakeText(igraph, xp, yp + dy, peakText + ' s', 7,
                             '(0;0;255)'))

    doc.SetProperty('AdditionalNumResColumns', columns)
    doc.SetProperty('AdditionalGraphicsCommands', graphicsCommands)
Exemplo n.º 6
0
            for w in range(2, len(tempVar0)):  # For all waveforms
                tempVar1 = tempVar0[w][:
                                       -3]  # Keep points for a single waveform
                tempVar2 = str.split(
                    tempVar1,
                    ', ')  # Split waveform points whereever ", " exists
                wavePoints = []  # To hold float type points
                for q in range(len(tempVar2)):  # For all waveform points
                    wavePoints.append(
                        float(tempVar2[q]) / 1000
                    )  # Convert from string to float. Then divide by 1,000 to convert from V to mV
                waves[w - 2] = [
                    b[w - 2][1], wavePoints
                ]  # Append the timestamp indexing and all waveforms for neuron
            waves.sort()
            for q in range(len(waves)):
                waves[q] = waves[q][1]
            try:
                doc.CreateWaveformVariable(waveName, 40000, spkTimes,
                                           waves)  # Create waveform variable
            except:
                continue

        nexName = "%s.nex" % fileName  # Create neueroexoporer file name
        print(nexName)
        nex.SaveDocumentAs(doc, nexName)  # Save Nex file
        ndoc = nex.GetActiveDocument()  # Select Nex file
        nex.CloseDocument(ndoc)  # Close Nex file

print("All files have been converted to nex files.")