Exemplo n.º 1
0
    def calculate_feature(self, responses, raise_warnings=False):
        """Calculate feature value"""

        if self.efel_feature_name.startswith(
                'bpo_'):  # check if internal feature
            feature_value = self.get_bpo_feature(responses)
        else:
            efel_trace = self._construct_efel_trace(responses)

            if efel_trace is None:
                feature_value = None
            else:
                self._setup_efel()

                import efel
                values = efel.getMeanFeatureValues(
                    [efel_trace], [self.efel_feature_name],
                    raise_warnings=raise_warnings)
                feature_value = values[0][self.efel_feature_name]

                efel.reset()

        logger.debug('Calculated value for %s: %s', self.name,
                     str(feature_value))

        return feature_value
Exemplo n.º 2
0
    def calculate_feature(self, responses, raise_warnings=False):
        """Calculate feature value"""

        efel_trace = self._construct_efel_trace(responses)

        if efel_trace is None:
            feature_value = None
        else:
            self._setup_efel()

            import efel

            values = efel.getMeanFeatureValues(
                [efel_trace],
                [self.efel_feature_name],
                raise_warnings=raise_warnings,
            )
            feature_value = values[0][self.efel_feature_name]

            efel.reset()

        logger.debug(
            "Calculated value for %s: %s", self.name, str(feature_value)
        )

        return feature_value
Exemplo n.º 3
0
def test_getmeanfeaturevalues():
    """basic: Test getMeanFeatureValues"""

    import efel
    efel.reset()

    stim_start = 500.0
    stim_end = 900.0

    time = efel.io.load_fragment('%s#col=1' % meanfrequency1_url)
    voltage = efel.io.load_fragment('%s#col=2' % meanfrequency1_url)

    trace = {}

    trace['T'] = time
    trace['V'] = voltage
    trace['stim_start'] = [stim_start]
    trace['stim_end'] = [stim_end]

    feature_values = \
        efel.getFeatureValues(
            [trace],
            ['AP_amplitude', 'BPAPHeightLoc1'], raise_warnings=False)

    mean_feature_values = efel.getMeanFeatureValues(
        [trace], [
            'AP_amplitude', 'BPAPHeightLoc1'], raise_warnings=False)

    nt.assert_equal(numpy.mean(feature_values[0]['AP_amplitude']),
                    mean_feature_values[0]['AP_amplitude'])
Exemplo n.º 4
0
    def calculate_feature(self, responses, raise_warnings=False):
        """Calculate feature value"""

        efel_trace = self._construct_efel_trace(responses)

        if efel_trace is None:
            feature_value = None
        else:
            self._setup_efel()

            import efel
            values = efel.getMeanFeatureValues(
                [efel_trace],
                [self.efel_feature_name],
                raise_warnings=raise_warnings)
            feature_value = values[0][self.efel_feature_name]

            efel.reset()

        logger.debug(
            'Calculated value for %s: %s',
            self.name,
            str(feature_value))

        return feature_value
Exemplo n.º 5
0
def test_getmeanfeaturevalues():
    """basic: Test getMeanFeatureValues"""

    import efel
    efel.reset()

    import numpy

    stim_start = 500.0
    stim_end = 900.0

    time = efel.io.load_fragment('%s#col=1' % meanfrequency1_url)
    voltage = efel.io.load_fragment('%s#col=2' % meanfrequency1_url)

    trace = {}

    trace['T'] = time
    trace['V'] = voltage
    trace['stim_start'] = [stim_start]
    trace['stim_end'] = [stim_end]

    feature_values = \
        efel.getFeatureValues(
            [trace],
            ['AP_amplitude', 'BPAPHeightLoc1'], raise_warnings=False)

    mean_feature_values = efel.getMeanFeatureValues(
        [trace], [
            'AP_amplitude', 'BPAPHeightLoc1'], raise_warnings=False)

    nt.assert_equal(numpy.mean(feature_values[0]['AP_amplitude']),
                    mean_feature_values[0]['AP_amplitude'])
Exemplo n.º 6
0
    def calculate_feature(self, responses):
        """Calculate feature value"""

        efel_trace = self._construct_efel_trace(responses)

        import efel
        return efel.getMeanFeatureValues(
            [efel_trace],
            [self.efel_feature_name],
            raise_warnings=False)[0][self.efel_feature_name]
Exemplo n.º 7
0
            def feature_function(time, values, info):
                disable = False
                logger = get_logger(self)

                if "stimulus_start" not in info:
                    if strict:
                        raise ValueError(
                            "Efel features require info['stimulus_start']. "
                            "No 'stimulus_start' found in info, "
                            "Set 'stimulus_start', or set strict to "
                            "False to use initial time as stimulus start")
                    else:
                        info["stimulus_start"] = time[0]
                        logger.warning(
                            "Efel features require info['stimulus_start']. "
                            "No 'stimulus_start' found in info, "
                            "setting stimulus start as initial time")

                if "stimulus_end" not in info:
                    if strict:
                        raise ValueError(
                            "Efel features require info['stimulus_end']. "
                            "No 'stimulus_end' found in info, "
                            "Set 'stimulus_start', or set strict to "
                            "False to use end time as stimulus end")
                    else:
                        info["stimulus_end"] = time[-1]
                        logger.warning(
                            "Efel features require info['stimulus_start']. "
                            "No 'stimulus_end' found in info, "
                            "setting stimulus end as end time")

                if info["stimulus_start"] >= info["stimulus_end"]:
                    raise ValueError("stimulus_start >= stimulus_end.")

                trace = {}
                trace["T"] = time
                trace["V"] = values
                trace["stim_start"] = [info["stimulus_start"]]
                trace["stim_end"] = [info["stimulus_end"]]

                # Disable decay_time_constant_after_stim if no time points left
                # in simulation after stimulation has ended.
                # Otherwise it throws an error
                if feature_name == "decay_time_constant_after_stim":
                    if info["stimulus_end"] >= time[-1]:
                        return None, None

                result = efel.getMeanFeatureValues([trace], [feature_name],
                                                   raise_warnings=False)

                return None, result[0][feature_name]
Exemplo n.º 8
0
    def calculate_feature(self, responses, raise_warnings=False):
        """Calculate feature value"""

        efel_trace = self._construct_efel_trace(responses)

        if efel_trace is None:
            feature_value = None
        else:

            import efel
            values = efel.getMeanFeatureValues(
                [efel_trace],
                [self.efel_feature_name],
                raise_warnings=raise_warnings)
            feature_value = values[0][self.efel_feature_name]

        return feature_value
Exemplo n.º 9
0
    def calculate_feature(self, responses, raise_warnings=False):
        """Calculate feature value"""

        efel_trace = self._construct_efel_trace(responses)

        if efel_trace is None:
            feature_value = None
        else:

            import efel
            efel.reset()

            values = efel.getMeanFeatureValues([efel_trace],
                                               [self.efel_feature_name],
                                               raise_warnings=raise_warnings)
            feature_value = values[0][self.efel_feature_name]

            efel.reset()

        return feature_value
Exemplo n.º 10
0
def test_getmeanfeaturevalues():
    """basic: Test getMeanFeatureValues"""

    import efel
    efel.reset()
    import numpy

    stim_start = 500.0
    stim_end = 900.0

    test_data_path = joinp(testdata_dir, 'basic', 'mean_frequency_1.txt')
    data = numpy.loadtxt(test_data_path)

    time = data[:, 0]
    voltage = data[:, 1]

    trace = {}

    trace['T'] = time
    trace['V'] = voltage
    trace['stim_start'] = [stim_start]
    trace['stim_end'] = [stim_end]

    import warnings
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        feature_values = \
            efel.getFeatureValues(
                [trace],
                ['AP_amplitude', 'BPAPHeightLoc1'])

        mean_feature_values = efel.getMeanFeatureValues(
            [trace], [
                'AP_amplitude', 'BPAPHeightLoc1'])

    nt.assert_equal(numpy.mean(feature_values[0]['AP_amplitude']),
                    mean_feature_values[0]['AP_amplitude'])
def getMeasures(inhsyn, excsyn, inhspikes, excspikes, examplenum, repnum,
                modfreq, modfreqnum, currentstep, yind):
    print 'Exc Num = ' + str(excsyn) + ', Inh Num = ' + str(
        inhsyn) + ', Exc Rate = ' + str(
            excspikes / 10) + ', Inh Rate = ' + str(inhspikes / 10)
    # rep = int(repnum)
    # example = int(examplenum)
    # modfreq = int(modfreq)
    # modfreqnum = int(modfreqnum)
    # currentstep = currhold + repnum*0.0025 - 0.0025
    # t_vec = h.Vector()
    # t_vec.record(h._ref_t)
    # v_vec = h.Vector()
    # v_vec.record(h.soma[0](0.5)._ref_v)

    saverep = repnum
    savemod = modfreqnum
    savemodfreq = modfreq
    savecurstep = currentstep
    # h.randomize_syns(1,1) # Randomizes synapse location with a different seed on each repetition
    h.f(0, 0, 0, 0, 0, 1, 1, 0, 0, 30, 0, modfreq, 0, currentstep,
        int(yind))  # Runs Simulation
    h.run()
    # data1 = numpy.array(t_vec)
    # data = numpy.array(v_vec)
    # timevec = data1[10001:len(data1)]
    data = numpy.array(h.recV[int(yind)], dtype=numpy.float)
    timevec = numpy.arange(1000, int(tstop), dt, dtype=numpy.float)
    voltage = data[10001:len(
        data
    )]  # Cut out first second of simulation since there are transient effects still present
    trace = {}
    trace['T'] = timevec
    trace['V'] = voltage
    trace['stim_start'] = [1000]
    trace['stim_end'] = [10000]
    traces = [trace]

    traces_results = efel.getFeatureValues(
        traces, ['AP_begin_indices', 'AP_end_indices'])
    traces_mean_results = efel.getMeanFeatureValues(
        traces, ['AP_amplitude', 'ISI_CV', 'Spikecount', 'mean_frequency'])
    SpikeRates_i3 = traces_mean_results[0]['mean_frequency']

    #### Create Trace Where Spikes Are Removed ####
    AP_begin = traces_results[0]['AP_begin_indices']
    AP_end = traces_results[0]['AP_end_indices']
    spikecut_voltage = []

    ## Create spiketime 0/1 vector using acptimes and compute PSD using pwelch function
    apctimes = numpy.array(h.apctimes[int(yind)])
    apctimes = apctimes[apctimes > 1000]
    NumSpikes_i2 = len(apctimes)
    if NumSpikes_i2 > 0:
        SpikeRates_i2 = NumSpikes_i2 / ((apctimes[-1:][0] - 1000) / 1000)
    else:
        SpikeRates_i2 = 0

    HC_SpikeTimes = numpy.zeros((len(voltage), ), dtype=numpy.float)
    for i in range(0, len(apctimes)):
        HC_SpikeTimes[int(apctimes[i] / dt) - 10001] = 1  # apctimes[i]
    f1, Pxx_den1 = signal.welch(
        HC_SpikeTimes, fs=1 / (dt / 1000), scaling='density',
        nperseg=20000)  # fs/nperseg = frequency resolution
    e0Hz = Pxx_den1[f1 == 0]
    e0Hz = e0Hz[0]
    e05Hz = Pxx_den1[f1 == 0.5]
    e05Hz = e05Hz[0]
    e1Hz = Pxx_den1[f1 == 1]
    e1Hz = e1Hz[0]
    e2Hz = Pxx_den1[f1 == 2]
    e2Hz = e2Hz[0]
    e3Hz = Pxx_den1[f1 == 3]
    e3Hz = e3Hz[0]
    e4Hz = Pxx_den1[f1 == 4]
    e4Hz = e4Hz[0]
    e5Hz = Pxx_den1[f1 == 5]
    e5Hz = e5Hz[0]
    e8Hz = Pxx_den1[f1 == 8]
    e8Hz = e8Hz[0]
    e9Hz = Pxx_den1[f1 == 9]
    e9Hz = e9Hz[0]
    e10Hz = Pxx_den1[f1 == 10]
    e10Hz = e10Hz[0]
    e12Hz = Pxx_den1[f1 == 12]
    e12Hz = e12Hz[0]
    e15Hz = Pxx_den1[f1 == 15]
    e15Hz = e15Hz[0]
    e16Hz = Pxx_den1[f1 == 16]
    e16Hz = e16Hz[0]
    e20Hz = Pxx_den1[f1 == 20]
    e20Hz = e20Hz[0]
    e25Hz = Pxx_den1[f1 == 25]
    e25Hz = e25Hz[0]
    e30Hz = Pxx_den1[f1 == 30]
    e30Hz = e30Hz[0]
    # print e0Hz
    # print e05Hz
    # print e1Hz
    # print e2Hz
    # print e3Hz
    # print e4Hz
    # print e5Hz
    # print e8Hz
    # print e9Hz
    # print e10Hz
    # print e12Hz
    # print e15Hz
    # print e16Hz
    # print e20Hz
    # print e25Hz
    # print e30Hz

    if AP_begin is not None:
        for i in range(0, len(AP_begin)):
            # Cut out action potentials + 100 index points preceding each spike
            if i == 0:
                spikecut_tempvoltage = voltage[0:AP_begin[i] - 80]
                spikecut_voltage.append(spikecut_tempvoltage)
            elif i == len(AP_begin):
                spikecut_tempvoltage = [
                    voltage[AP_end[i - 1]:AP_begin[i]] - 80,
                    voltage[AP_end[i]:len(voltage)]
                ]
                spikecut_voltage.append(spikecut_tempvoltage)
            else:
                spikecut_tempvoltage = voltage[AP_end[i - 1]:AP_begin[i] - 80]
                spikecut_voltage.append(spikecut_tempvoltage)
            # Find lengths of appended arrays and rebuild voltage trace array
            x = []
            for i in range(0, len(spikecut_voltage)):
                newlength = len(spikecut_voltage[i])
                x.append(newlength)
            totallength = numpy.sum(x)
            spv = numpy.zeros((totallength, ), dtype=numpy.int)
            count = 0
            for i in range(0, len(spikecut_voltage)):
                for j in range(0, len(spikecut_voltage[i])):
                    spv[count] = spikecut_voltage[i][j]
                    count = count + 1
    else:
        spv = voltage

    spv = spv[spv < -50]  # Remove all voltage instinces greater than -50 mV
    spt = numpy.arange(0, len(spv),
                       1) * 0.1  # Build new tvec for trace with spike cut

    ### Generate Measurements ###
    if len(spv) == 0:
        StdVolt_i = 0
        MeanVolt_i = -50  # i.e. set to highest possible average if all data points get cut
    else:
        StdVolt_i = numpy.std(spv)
        MeanVolt_i = numpy.mean(spv)
    NumSpikes_i = traces_mean_results[0]['Spikecount']
    SpikeRates_i = NumSpikes_i / 9
    if traces_mean_results[0]['AP_amplitude'] is not None:
        MeanAPamp_i = traces_mean_results[0]['AP_amplitude']
    else:
        MeanAPamp_i = 0
    if traces_mean_results[0]['ISI_CV'] is not None:
        ISICV_i = traces_mean_results[0]['ISI_CV']
    else:
        ISICV_i = 0
        print 'FAILED AT I = ' + str(currentstep) + ' nA & Mod = ' + str(
            modfreq) + ' Hz'
        reload(
            efel
        )  # added due to previous error following which all models had ISICV values of 0 regardless of spikes

    if modfreq == 0:
        fig = pyplot.figure()
        pyplot.plot(timevec, voltage)
        pyplot.savefig('Plots_' + Cell_Name + '/' + Case + '_Mod_' +
                       str(h.synfreqINH) + 'Hz_NEURONSpikeRateEstimate_' +
                       str(SpikeRates_i2) + 'Hz_I_' + str(currentstep) +
                       'nA_yind_' + str(yind) + '.png')
        pyplot.gcf().clear()
        pyplot.cla()
        pyplot.clf()
        pyplot.close()

    AvgPot_Thresh = -70.588
    StdPot_Thresh = 2.2
    ISICV_Thresh = 0.8
    AMP_DB_Thresh = 40
    Rate_maxthresh = 25  # Greater than ~3 Hz and less than ~25 Hz during resting (Varga et al, 2012 - though up to 50 Hz during runs; Katona et al, 2014)
    Rate_minthresh = 3  # Greater than ~3 Hz and less than ~25 Hz during resting (Varga et al, 2012 - though up to 50 Hz during runs; Katona et al, 2014)
    HC_Metric = 0
    HC_Metric = HC_Metric + (MeanVolt_i >= AvgPot_Thresh) + (
        StdVolt_i >= StdPot_Thresh) + (ISICV_i >= ISICV_Thresh) + (
            (SpikeRates_i <= Rate_maxthresh) &
            (SpikeRates_i >= Rate_minthresh)) - 5 * (
                (MeanAPamp_i <= AMP_DB_Thresh) & (NumSpikes_i > 0))
    print 'IRepNum = ' + str(repnum) + ', IRepNum_OG = ' + str(
        saverep) + ', I = ' + str(currentstep) + ' nA, I_OG = ' + str(
            savecurstep) + ' nA, I_NEURON = ' + str(
                h.ic_hold.amp
            ) + ' nA, ModNum = ' + str(modfreqnum) + ', ModNum_OG = ' + str(
                savemod) + ', Mod = ' + str(modfreq) + ' Hz, Mod_OG = ' + str(
                    savemodfreq) + ' Hz, Mod_NEURON = ' + str(
                        h.synfreqINH) + ' Hz, Spike Rate = ' + str(
                            SpikeRates_i) + ', Spike Rate 2 = ' + str(
                                SpikeRates_i2) + ', Spike Rate 3 = ' + str(
                                    SpikeRates_i3)
    outputresults = [
        int(repnum), HC_Metric, modfreq, SpikeRates_i,
        int(modfreqnum), e0Hz, e05Hz, e1Hz, e2Hz, e3Hz, e4Hz, e5Hz, e8Hz, e9Hz,
        e10Hz, e12Hz, e15Hz, e16Hz, e20Hz, e25Hz, e30Hz, currentstep,
        SpikeRates_i2, ISICV_i, SpikeRates_i3
    ]
    return outputresults
def getMeasures(inhsyn, excsyn, inhspikes, excspikes, examplenum, repnum,
                modfreq, modfreqnum):
    print 'Exc Num = ' + str(excsyn) + ', Inh Num = ' + str(
        inhsyn) + ', Exc Rate = ' + str(
            excspikes / 10) + ', Inh Rate = ' + str(inhspikes / 10)
    rep = int(repnum)
    example = int(examplenum)
    modfreqnum = int(modfreqnum)
    h.randomize_syns(
        example, rep
    )  # Randomizes synapse location with a different seed on each repetition
    h.f(int(inhsyn), int(excsyn), int(inhspikes), int(excspikes), 0, example,
        rep, exccommon, inhcommon, 30, 0, modfreq, 0)  # Runs Simulation
    # for p in range(0,int(tstop/dt+1)): data[p] = h.recV[p]
    data = numpy.array(h.recV, dtype=numpy.float)
    timevec = numpy.arange(1000, int(tstop), dt, dtype=numpy.float)
    voltage = data[10001:len(
        data
    )]  # Cut out first second of simulation since there are transient effects still present
    trace = {}
    trace['T'] = timevec
    trace['V'] = voltage
    trace['stim_start'] = [1000]
    trace['stim_end'] = [10000]
    traces = [trace]

    traces_results = efel.getFeatureValues(traces, [
        'AP_amplitude', 'ISI_CV', 'Spikecount', 'AP_begin_indices',
        'AP_end_indices'
    ])
    traces_mean_results = efel.getMeanFeatureValues(
        traces, ['AP_amplitude', 'ISI_CV', 'Spikecount'])

    #### Create Trace Where Spikes Are Removed ####
    AP_begin = traces_results[0]['AP_begin_indices']
    AP_end = traces_results[0]['AP_end_indices']
    spikecut_voltage = []

    ## Create spiketime 0/1 vector using acptimes and compute PSD using pwelch function
    apctimes = numpy.array(h.apctimes)
    apctimes = apctimes[apctimes > 1000]
    NumSpikes_i2 = len(apctimes)
    if NumSpikes_i2 > 0:
        SpikeRates_i2 = NumSpikes_i2 / ((apctimes[-1:][0] - 1000) / 1000)
    else:
        SpikeRates_i2 = 0

    HC_SpikeTimes = numpy.zeros((len(voltage), ), dtype=numpy.float)
    for i in range(0, len(apctimes)):
        HC_SpikeTimes[int(apctimes[i] / dt) - 10001] = 1  # apctimes[i]
    f1, Pxx_den1 = signal.welch(
        HC_SpikeTimes, fs=1 / (dt / 1000), scaling='density',
        nperseg=20000)  # fs/nperseg = frequency resolution
    e0Hz = Pxx_den1[f1 == 0]
    e0Hz = e0Hz[0]
    e05Hz = Pxx_den1[f1 == 0.5]
    e05Hz = e05Hz[0]
    e1Hz = Pxx_den1[f1 == 1]
    e1Hz = e1Hz[0]
    e2Hz = Pxx_den1[f1 == 2]
    e2Hz = e2Hz[0]
    e3Hz = Pxx_den1[f1 == 3]
    e3Hz = e3Hz[0]
    e4Hz = Pxx_den1[f1 == 4]
    e4Hz = e4Hz[0]
    e5Hz = Pxx_den1[f1 == 5]
    e5Hz = e5Hz[0]
    e8Hz = Pxx_den1[f1 == 8]
    e8Hz = e8Hz[0]
    e9Hz = Pxx_den1[f1 == 9]
    e9Hz = e9Hz[0]
    e10Hz = Pxx_den1[f1 == 10]
    e10Hz = e10Hz[0]
    e12Hz = Pxx_den1[f1 == 12]
    e12Hz = e12Hz[0]
    e15Hz = Pxx_den1[f1 == 15]
    e15Hz = e15Hz[0]
    e16Hz = Pxx_den1[f1 == 16]
    e16Hz = e16Hz[0]
    e20Hz = Pxx_den1[f1 == 20]
    e20Hz = e20Hz[0]
    e25Hz = Pxx_den1[f1 == 25]
    e25Hz = e25Hz[0]
    e30Hz = Pxx_den1[f1 == 30]
    e30Hz = e30Hz[0]
    # print e0Hz
    # print e05Hz
    # print e1Hz
    # print e2Hz
    # print e3Hz
    # print e4Hz
    # print e5Hz
    # print e8Hz
    # print e9Hz
    # print e10Hz
    # print e12Hz
    # print e15Hz
    # print e16Hz
    # print e20Hz
    # print e25Hz
    # print e30Hz

    if AP_begin is not None:
        for i in range(0, len(AP_begin)):
            # Cut out action potentials + 100 index points preceding each spike
            if i == 0:
                spikecut_tempvoltage = voltage[0:AP_begin[i] - 80]
                spikecut_voltage.append(spikecut_tempvoltage)
            elif i == len(AP_begin):
                spikecut_tempvoltage = [
                    voltage[AP_end[i - 1]:AP_begin[i]] - 80,
                    voltage[AP_end[i]:len(voltage)]
                ]
                spikecut_voltage.append(spikecut_tempvoltage)
            else:
                spikecut_tempvoltage = voltage[AP_end[i - 1]:AP_begin[i] - 80]
                spikecut_voltage.append(spikecut_tempvoltage)
            # Find lengths of appended arrays and rebuild voltage trace array
            x = []
            for i in range(0, len(spikecut_voltage)):
                newlength = len(spikecut_voltage[i])
                x.append(newlength)
            totallength = numpy.sum(x)
            spv = numpy.zeros((totallength, ), dtype=numpy.int)
            count = 0
            for i in range(0, len(spikecut_voltage)):
                for j in range(0, len(spikecut_voltage[i])):
                    spv[count] = spikecut_voltage[i][j]
                    count = count + 1
    else:
        spv = voltage

    spv = spv[spv < -50]  # Remove all voltage instinces greater than -50 mV
    spt = numpy.arange(0, len(spv),
                       1) * 0.1  # Build new tvec for trace with spike cut

    ### Generate Measurements ###
    if len(spv) == 0:
        StdVolt_i = 0
        MeanVolt_i = -50  # i.e. set to highest possible average if all data points get cut
    else:
        StdVolt_i = numpy.std(spv)
        MeanVolt_i = numpy.mean(spv)
    NumSpikes_i = traces_mean_results[0]['Spikecount']
    SpikeRates_i = NumSpikes_i / 9
    if traces_mean_results[0]['AP_amplitude'] is not None:
        MeanAPamp_i = traces_mean_results[0]['AP_amplitude']
    else:
        MeanAPamp_i = 0
    if traces_mean_results[0]['ISI_CV'] is not None:
        ISICV_i = traces_mean_results[0]['ISI_CV']
    else:
        ISICV_i = 0
        reload(
            efel
        )  # added due to previous error following which all models had ISICV values of 0 regardless of spikes
    AvgPot_Thresh = -70.588
    StdPot_Thresh = 2.2
    ISICV_Thresh = 0.8
    AMP_DB_Thresh = 40
    Rate_maxthresh = 25  # Greater than ~3 Hz and less than ~25 Hz during resting (Varga et al, 2012 - though up to 50 Hz during runs; Katona et al, 2014)
    Rate_minthresh = 3  # Greater than ~3 Hz and less than ~25 Hz during resting (Varga et al, 2012 - though up to 50 Hz during runs; Katona et al, 2014)
    HC_Metric = 0
    HC_Metric = HC_Metric + (MeanVolt_i >= AvgPot_Thresh) + (
        StdVolt_i >= StdPot_Thresh) + (ISICV_i >= ISICV_Thresh) + (
            (SpikeRates_i <= Rate_maxthresh) &
            (SpikeRates_i >= Rate_minthresh)) - 5 * (
                (MeanAPamp_i <= AMP_DB_Thresh) & (NumSpikes_i > 0))
    print 'Vm = ' + str(MeanVolt_i) + ', Vm STD = ' + str(
        StdVolt_i) + ', Spike Rate = ' + str(
            SpikeRates_i2) + ', ISICV = ' + str(ISICV_i) + ', Amp = ' + str(
                MeanAPamp_i) + ', HC = ' + str(HC_Metric)
    outputresults = [
        rep, HC_Metric, modfreq, SpikeRates_i2, modfreqnum, e0Hz, e05Hz, e1Hz,
        e2Hz, e3Hz, e4Hz, e5Hz, e8Hz, e9Hz, e10Hz, e12Hz, e15Hz, e16Hz, e20Hz,
        e25Hz, e30Hz
    ]
    return outputresults
def three_feature_sets_on_static_models(model,
                                        unit_test=False,
                                        challenging=False):
    '''
    Conventions:
        variables ending with 15 refer to 1.5 current injection protocols.
        variables ending with 30 refer to 3.0 current injection protocols.
    Inputs:
        NML-DB models, a method designed to be called inside an iteration loop, where a list of
        models is iterated over, and on each iteration a new model is supplied to this method.

    Outputs:
        A dictionary of dataframes, for features sought according to: Druckman, EFEL, AllenSDK

    '''

    ##
    # wrangle data in preperation for computing
    # Allen Features
    ##

    #import pdb; pdb.set_trace()
    if type(model) is type(DataTC()):
        model = model.dtc_to_model()
    if not hasattr(model, 'vm30'):
        model.inject_square_current(model.rheobase * 3.0)
        model.vm30 = model.get_membrane_potential()
        ['amplitude']
        model.inject_square_current()
        model.vm15 = model.get_membrane_potential()

    times = np.array([float(t) for t in model.vm30.times])
    volts = np.array([float(v) for v in model.vm30])
    try:
        import asciiplotlib as apl
        fig = apl.figure()
        fig.plot(times,
                 volts,
                 label="V_{m} (mV), versus time (ms)",
                 width=100,
                 height=80)
        fig.show()
    except:
        pass
    ##
    # Allen Features
    ##
    #frame_shape,frame_dynamics,per_spike_info, meaned_features_overspikes
    all_allen_features30, allen_features30 = allen_format(
        volts, times, optional_vm=model.vm30)
    #if frame30 is not None:
    #    frame30['protocol'] = 3.0
    ##

    # wrangle data in preperation for computing
    # Allen Features
    ##
    times = np.array([float(t) for t in model.vm15.times])
    volts = np.array([float(v) for v in model.vm15])

    ##
    # Allen Features
    ##

    all_allen_features15, allen_features15 = allen_format(
        volts, times, optional_vm=model.vm15)
    ##
    # Get Druckman features, this is mainly handled in external files.
    ##
    #if model.ir_currents
    DMTNMLO = dm_test_interoperable.DMTNMLO()

    if hasattr(model,
               'druckmann2013_input_resistance_currents') and not hasattr(
                   model, 'allen'):
        DMTNMLO.test_setup(None, None, model=model)

    else:
        DMTNMLO.test_setup(None, None, model=model, ir_current_limited=True)
    dm_test_features = DMTNMLO.runTest()
    ##
    # Wrangle data to prepare for EFEL feature calculation.
    ##
    trace3 = {}
    trace3['T'] = [float(t) for t in model.vm30.times.rescale('ms')]
    trace3['V'] = [float(v) for v in model.vm30.magnitude]  #temp_vm
    trace3['stimulus_current'] = [model.druckmann2013_strong_current]
    if not hasattr(model, 'allen'):
        trace3['stim_end'] = [trace3['T'][-1]]
        trace3['stim_start'] = [float(model.protocol['Time_Start'])]

    else:
        trace3['stim_end'] = [float(model.protocol['Time_End']) * 1000.0]
        trace3['stim_start'] = [float(model.protocol['Time_Start']) * 1000.0]

    traces3 = [
        trace3
    ]  # Now we pass 'traces' to the efel and ask it to calculate the feature# values

    trace15 = {}
    trace15['T'] = [float(t) for t in model.vm15.times.rescale('ms')]
    trace15['V'] = [float(v) for v in model.vm15.magnitude]  #temp_vm

    if not hasattr(model, 'allen'):
        trace15['stim_end'] = [trace15['T'][-1]]
        trace15['stim_start'] = [float(model.protocol['Time_Start'])]
    else:
        trace15['stim_end'] = [float(model.protocol['Time_End']) * 1000.0]
        trace15['stim_start'] = [float(model.protocol['Time_Start']) * 1000.0]
    trace15['stimulus_current'] = [model.druckmann2013_standard_current]
    trace15['stim_end'] = [trace15['T'][-1]]
    traces15 = [
        trace15
    ]  # Now we pass 'traces' to the efel and ask it to calculate the feature# values

    ##
    # Compute
    # EFEL features (HBP)
    ##
    efel.reset()

    if len(threshold_detection(model.vm15, threshold=0)):
        #pass
        threshold = float(
            np.max(model.vm15.magnitude) -
            0.5 * np.abs(np.std(model.vm15.magnitude)))

        print(len(threshold_detection(model.vm15, threshold=threshold)))
        print(threshold, 'threshold', np.max(model.vm15.magnitude),
              np.min(model.vm15.magnitude))

        #efel_15 = efel.getMeanFeatureValues(traces15,list(efel.getFeatureNames()))#
    else:
        threshold = float(
            np.max(model.vm15.magnitude) -
            0.2 * np.abs(np.std(model.vm15.magnitude)))

        efel.setThreshold(threshold)
        print(len(threshold_detection(model.vm15, threshold=threshold)))
        print(threshold, 'threshold', np.max(model.vm15.magnitude))

    if np.min(model.vm15.magnitude) < 0:
        efel_15 = efel.getMeanFeatureValues(traces15,
                                            list(efel.getFeatureNames()))
    else:
        efel_15 = None
    efel.reset()

    if len(threshold_detection(model.vm30, threshold=0)):
        threshold = float(
            np.max(model.vm30.magnitude) -
            0.5 * np.abs(np.std(model.vm30.magnitude)))

        print(len(threshold_detection(model.vm30, threshold=threshold)))
        print(threshold, 'threshold', np.max(model.vm30.magnitude),
              np.min(model.vm30.magnitude))

    #efel_30 = efel.getMeanFeatureValues(traces3,list(efel.getFeatureNames()))

    else:
        threshold = float(
            np.max(model.vm30.magnitude) -
            0.2 * np.abs(np.std(model.vm30.magnitude)))
        efel.setThreshold(threshold)
        print(len(threshold_detection(model.vm15, threshold=threshold)))
        print(threshold, 'threshold', np.max(model.vm15.magnitude))

    if np.min(model.vm30.magnitude) < 0:
        efel_30 = efel.getMeanFeatureValues(traces3,
                                            list(efel.getFeatureNames()))
    else:
        efel_30 = None

    efel.reset()

    if hasattr(model, 'information'):
        return {
            'model_id': model.name,
            'model_information': model.information,
            'efel_15': efel_15,
            'efel_30': efel_30,
            'dm': dm_test_features,
            'allen_15': all_allen_features15,
            'allen_30': all_allen_features30
        }
    else:
        return {
            'model_id': model.name,
            'model_information': 'allen_data',
            'efel_15': efel_15,
            'efel_30': efel_30,
            'dm': dm_test_features,
            'allen_15': all_allen_features15,
            'allen_30': all_allen_features30
        }