Beispiel #1
0
    def calculate_highest_significant_sync_rate(self, dataframe=None):

        #Use the whole database by default
        if dataframe is None:
            dataframe = self.db

        #Highest significant sync rate
        #TODO: I need to unit test this part
        highestSync = np.empty(len(dataframe))
        for indCell, cell in dataframe.iterrows():
            spikeData, eventData = dataloader.get_session_ephys(cell, 'am')
            bdata = dataloader.get_session_bdata(cell, 'am')
            eventOnsetTimes = eventData.get_event_onset_times(eventChannel=5)
            eventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
                eventOnsetTimes, 0.5)

            if spikeData.samples is not None:

                #NOTE: This is where I am ignoring the onset response. is 50msec sufficient??
                timeRange = [0.05, 0.5]

                freqEachTrial = bdata['currentFreq']
                possibleFreq = np.unique(freqEachTrial)

                (spikeTimesFromEventOnset, trialIndexForEachSpike,
                 indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
                     spikeData.timestamps, eventOnsetTimes, timeRange)
                allRayleighPvals = np.zeros(len(possibleFreq))
                for indFreq, oneFreq in enumerate(possibleFreq):
                    trialsThisFreq = np.flatnonzero(freqEachTrial == oneFreq)
                    spikeTimesThisFreq = spikeTimesFromEventOnset[np.in1d(
                        trialIndexForEachSpike, trialsThisFreq)]

                    #Number of radians in one second for this stimulus frequency
                    radsPerSec = oneFreq * 2 * np.pi
                    period = 1.0 / oneFreq
                    spikeRads = (spikeTimesThisFreq * radsPerSec) % (2 * np.pi)

                    #Compute average vector length and angle
                    strength, phase = signal.vectorstrength(
                        spikeTimesThisFreq, period)

                    #Compute prob for the rayleigh statistic
                    p = self.rayleigh_test(strength, len(spikeTimesThisFreq))
                    allRayleighPvals[indFreq] = p

                if np.any(allRayleighPvals < 0.05):
                    hs = np.max(possibleFreq[allRayleighPvals < 0.05])
                else:
                    hs = 0
                highestSync[indCell] = hs

            else:
                highestSync[indCell] = 0

        dataframe['highestSync'] = highestSync
Beispiel #2
0
    def test_opposite_2dperiod(self):
        events = np.array([0, .25, .5, .75])
        period = [1.] * 10
        targ_strength = [0.] * 10

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_almost_equal(strength, targ_strength)
Beispiel #3
0
    def get_vector_strength(self, times):
        """
        Calculates the vector strength of this run

        returns: (strength, phase)
        """

        period = self.opt_pulse_isi + self.opt_pulse_width
        events = [times[x] for x in self.peaks]
        return vectorstrength(events, period)
Beispiel #4
0
    def test_opposite_2dperiod(self):
        events = np.array([0, .25, .5, .75])
        period = [1.]*10
        targ_strength = [0.]*10

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_almost_equal(strength, targ_strength)
Beispiel #5
0
    def test_single_1dperiod(self):
        events = np.array([.5])
        period = 5.
        targ_strength = 1.
        targ_phase = .1

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 0)
        assert_equal(phase.ndim, 0)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2*np.pi*targ_phase)
Beispiel #6
0
    def test_partial_2dperiod(self):
        events = np.array([.25, .5, .75])
        period = [1., 1., 1., 1.]
        targ_strength = [1. / 3.] * 4
        targ_phase = np.array([.5, .5, .5, .5])

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2 * np.pi * targ_phase)
Beispiel #7
0
    def test_spaced_2dperiod(self):
        events = np.array([.1, 1.1, 2.1, 4.1, 10.1])
        period = [1, .5]
        targ_strength = [1.] * 2
        targ_phase = np.array([.1, .2])

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2 * np.pi * targ_phase)
Beispiel #8
0
    def test_partial_1dperiod(self):
        events = np.array([.25, .5, .75])
        period = 1
        targ_strength = 1. / 3.
        targ_phase = .5

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 0)
        assert_equal(phase.ndim, 0)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2 * np.pi * targ_phase)
Beispiel #9
0
    def test_single_2dperiod(self):
        events = np.array([.5])
        period = [1, 2, 5.]
        targ_strength = [1.] * 3
        targ_phase = np.array([.5, .25, .1])

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_array_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2 * np.pi * targ_phase)
Beispiel #10
0
    def test_spaced_1dperiod(self):
        events = np.array([.1, 1.1, 2.1, 4.1, 10.1])
        period = 1
        targ_strength = 1.
        targ_phase = .1

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 0)
        assert_equal(phase.ndim, 0)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2 * np.pi * targ_phase)
Beispiel #11
0
    def test_single_2dperiod(self):
        events = np.array([.5])
        period = [1, 2, 5.]
        targ_strength = [1.]*3
        targ_phase = np.array([.5, .25, .1])

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_array_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2*np.pi*targ_phase)
Beispiel #12
0
    def test_single_1dperiod(self):
        events = np.array([.5])
        period = 5.
        targ_strength = 1.
        targ_phase = .1

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 0)
        assert_equal(phase.ndim, 0)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2 * np.pi * targ_phase)
Beispiel #13
0
    def test_partial_2dperiod(self):
        events = np.array([.25, .5, .75])
        period = [1., 1., 1., 1.]
        targ_strength = [1./3.]*4
        targ_phase = np.array([.5, .5, .5, .5])

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2*np.pi*targ_phase)
Beispiel #14
0
    def test_partial_1dperiod(self):
        events = np.array([.25, .5, .75])
        period = 1
        targ_strength = 1./3.
        targ_phase = .5

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 0)
        assert_equal(phase.ndim, 0)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2*np.pi*targ_phase)
Beispiel #15
0
    def test_spaced_2dperiod(self):
        events = np.array([.1, 1.1, 2.1, 4.1, 10.1])
        period = [1, .5]
        targ_strength = [1.]*2
        targ_phase = np.array([.1, .2])

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 1)
        assert_equal(phase.ndim, 1)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2*np.pi*targ_phase)
Beispiel #16
0
    def test_spaced_1dperiod(self):
        events = np.array([.1, 1.1, 2.1, 4.1, 10.1])
        period = 1
        targ_strength = 1.
        targ_phase = .1

        strength, phase = vectorstrength(events, period)

        assert_equal(strength.ndim, 0)
        assert_equal(phase.ndim, 0)
        assert_almost_equal(strength, targ_strength)
        assert_almost_equal(phase, 2*np.pi*targ_phase)
def calculate_am_significance_synchronization(amSyncSpikeTimesFromEventOnset,
                                              amSyncTrialIndexForEachSpike,
                                              amCurrentFreq, amUniqFreq):
    """

    Args:
        amSpikeTimes (np.array): Each value is a time when a spike occurred. Obatained from Ephys Data
        amOnsetTimes (np.array): Contains as many values as there were trials with each value being the tme a
        trial started.
        amBaseTime (list): Contains two values that represent the time range for the base firing rate
        amOnsetTime (list): Contains two values that represent the time range for the onset firing rate
        amCurrentFreq (np.array): Contains as many values as there were trials with each value being the am rate
        for a specific trial. Obtained from Behavior Data
        amUniqFreq (np.array): Contains as many values as there were unique am rates presented over the entire session.

    Returns:
        allFreqSyncPVal (np.array): Contains one p-value for each unique am rate presented over the entire session
        allFreqSyncZScore (np.array): Contains one z-value for each unique am rate presented over the entire session
        allFreqVectorStrength (np.array):
        allFreqRal (np.array):

    """
    numFreq = len(amUniqFreq)

    allFreqSyncPVal = np.empty(numFreq)
    allFreqVectorStrength = np.empty(numFreq)
    allFreqRal = np.empty(numFreq)
    allFreqSyncZScore = np.empty(numFreq)

    for indFreq, (freq, spiketimes, trialInds) in enumerate(
            spiketimes_each_frequency(amSyncSpikeTimesFromEventOnset,
                                      amSyncTrialIndexForEachSpike,
                                      amCurrentFreq)):
        strength, phase = signal.vectorstrength(spiketimes, 1.0 / freq)

        radsPerSec = freq * 2 * np.pi
        spikeRads = (spiketimes * radsPerSec) % (2 * np.pi)
        ral = np.array([2 * len(spiketimes) * (strength**2)])

        # NOTE: I checked the math in this function using the text referenced (Mike W. has a copy if needed) - Nick
        zVal, pVal = rayleigh_test(spikeRads)

        allFreqVectorStrength[indFreq] = strength  # Frequency vector strength
        allFreqRal[indFreq] = ral  # Unsure what this is
        allFreqSyncPVal[indFreq] = pVal  # p-value
        allFreqSyncZScore[indFreq] = zVal

    return allFreqSyncPVal, allFreqSyncZScore, allFreqVectorStrength, allFreqRal
def calculate_phase_discrim_accuracy(spikeTimes,
                                     eventOnsetTimes,
                                     currentFreq,
                                     uniqFreq,
                                     shuffle=False):
    SHUFFLE = shuffle

    # Timerange for alignment?
    timeRange = [
        0.05, 0.5
    ]  # Ignoring onset responses TODO: Is this the best way to do this??

    phaseDiscrimAccuracy = {}
    for thisFreq in uniqFreq:

        # Only use events for this frequency
        eventsThisFreq = eventOnsetTimes[currentFreq == thisFreq]

        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             spikeTimes, eventsThisFreq, timeRange)

        # This is really all we need to do to bin things by phase.
        radsPerSec = thisFreq * 2 * np.pi
        spikeRads = (spikeTimesFromEventOnset * radsPerSec) % (2 * np.pi)

        strength, phase = signal.vectorstrength(spikeTimesFromEventOnset,
                                                1.0 / thisFreq)
        phase = (phase + 2 * np.pi) % (2 * np.pi)

        shiftedRads = ((spikeRads - phase) + 2.25 * np.pi)
        if any(shiftedRads < 0):
            raise ValueError("Some shifted rads below 0")
        # shiftedRads = ((spikeRads - phase) + 2.25*np.pi)%(2*np.pi)
        spikeRads = shiftedRads % (2 * np.pi)

        nBins = 4
        binEdges = np.arange(0, 2.01 * np.pi, 2 * np.pi /
                             nBins)  # The 2.01 makes it actually include 2pi
        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeRads, indexLimitsEachTrial, binEdges)

        spikeCountMatCopy = copy.deepcopy(spikeCountMat)
        spikeCountMatShuffle = np.empty(np.shape(spikeCountMatCopy))
        for indMatRow in range(np.shape(spikeCountMatCopy)[0]):
            numRolls = np.random.choice(range(np.shape(spikeCountMatCopy)[1]))
            # numRolls = 0
            spikeCountMatShuffle[indMatRow, :] = np.roll(
                spikeCountMatCopy[indMatRow, :], numRolls)
        if SHUFFLE:
            spikeCountMat = spikeCountMatShuffle

        binMeans = np.mean(spikeCountMat, axis=0)
        prefInd = np.argmax(binMeans)
        nonPrefInd = np.argmin(binMeans)

        spikesPref = spikeCountMat[:, prefInd]
        spikesNonPref = spikeCountMat[:, nonPrefInd]

        maxAccuracy, threshold = linear_discriminator(spikesPref,
                                                      spikesNonPref)

        # dataframe.set_value(indRow, 'phaseAccuracy_{}Hz'.format(int(thisFreq)), maxAccuracy)
        phaseDiscrimAccuracy[int(thisFreq)] = maxAccuracy
    return phaseDiscrimAccuracy
Beispiel #19
0
            dataframe.loc[indRow, 'highestSync'] = np.nan
            print "Breaking, no significant response"
            continue
        ### ------------------------------------------------------------ ###

        ### --- Calculate vector strength and significance --- ###
        timeRange = [0.1, 0.5]  #DONE: Use this to cut out onset responses
        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             spikeTimes, eventOnsetTimes, timeRange)
        freqEachTrial = bdata['currentFreq']
        for indFreq, (freq, spiketimes, trialInds) in enumerate(
                spiketimes_each_frequency(spikeTimesFromEventOnset,
                                          trialIndexForEachSpike,
                                          freqEachTrial)):
            strength, phase = signal.vectorstrength(spiketimes, 1.0 / freq)
            # vsArr = np.concatenate((vsArr, np.array([strength])))

            #TODO: Check the math here
            radsPerSec = freq * 2 * np.pi
            spikeRads = (spiketimes * radsPerSec) % (2 * np.pi)
            ral = np.array([2 * len(spiketimes) * (strength**2)])

            #NOTE: I checked the math in this function using the text referenced (Mike W. has a copy if needed)
            zVal, pVal = rayleigh_test(spikeRads)

            allFreqVS[indFreq] = strength
            allFreqRal[indFreq] = ral
            allFreqPval[indFreq] = pVal

            # # pValArr = np.concatenate((pValArr, np.array([pVal])))
Beispiel #20
0
 def cpu_version(self, events, period):
     return signal.vectorstrength(events, period)