<commit_before># ============================================================================
# test_for_complex_bursts.py
#
# created  10 October 2017 Lungsi
# modified
#
# ============================================================================

import os

import sciunit
import quantities as pq
from elephant.statistics import mean_firing_rate as mfr
from elephant.statistics import fanofactor

from cerebunit.file_manager import get_folder_path_and_name as gfpan
from cerebunit.score_manager import BinaryScore
from cerebunit.capabilities.cells.response import ProducesSpikeTrain


class ComplexBurstingTest(sciunit.Test, BinaryScore):
    '''
    The Complex Bursting Test is a test comparing the observed spiking frequency in real animal to those generated by the model (from soma, "vm_soma"). This is done by comparing the mean spike frequencies.
    '''
    required_capabilities = (ProducesSpikeTrain,)
    score_type = BinaryScore
    #
    def generate_prediction(self, model, verbose=False):
        '''
        Generates spike train from various cell regions.
        Default cell_regions = {"vm_soma": 0.0, "vm_NOR3": 0.0}
        The value of each key is the threshold defined for
        spiking.
        The function is automatically called by sciunit.Test
        which this test is a child of.
        Therefore as part of sciunit generate_prediction is
        mandatory.
        '''
        # Inject current >= 2 nA
        self.inj_current = \
                { "current1":
                    {"amp": 2.0, "dur": 1000.0, "delay": 500.0} }
        model.set_stimulation_properties( self.inj_current )
        #
        setup_parameters = { "dt": 0.025,   "celsius": 37,
                             "tstop": 2500, "v_init": -65 }
        model.cell_regions = {"vm_soma": 0.0}
        model.set_simulation_properties(setup_parameters)
        #
        model.produce_spike_train()
        #self.process_prediction(model)
        return model

    def get_spike_train_for_current(self, model):
        '''
        The model.produce_spike_train() results in spike train for
        the initial (no injection), injection and later (no inject)
        This function slices the spike train during injection alone.
        ======================Use Case============================
        spike_train = get_spike_train_for_current(model)
        ===========================================================
        This function is called by process_prediction
        '''
        # get all the spike train for desired cell region
        all_spike_train = \
                model.predictions["spike_train"]["vm_soma"]
        # set the time boundaries for the spike train
        current_key = self.inj_current.keys()[0] # for only 1 current
        spike_start = \
                self.inj_current[current_key]["delay"]
        spike_stop = spike_start \
                + self.inj_current[current_key]["dur"]
        # slice spike train for current injection
        return all_spike_train.time_slice(spike_start, spike_stop)


    def process_prediction(self, model):
        '''
        Once the model has run, this function can be used to
        process the spike_train prediction to get the  mean
        firing rate from soma during injection alone.
        '''
        spike_train = self.get_spike_train_for_current(model)
        return spike_train, mfr(spike_train).rescale(pq.Hz)


    def compute_score(self, observation, model, verbose=False):
        '''
        This function like generate_pediction is called automatically
        by sciunit which SpontaneousFiringTest is a child of.
        This function must be named compute_score
        This function calls the function process_prediction to return
        the mean firing reate of spike trains from all the cell_regions
        Off al the cell_regions our region of interest is "vm_soma".
        The prediction processed from "vm_soma" is then compared against
        the experimental_data to get the binary score; 0 if the
        prediction correspond with experiment, else 1.
        '''
        spike_train, a_prediction = self.process_prediction(model)
        x = BinaryScore.compute( observation,
                                 a_prediction  )
        score = BinaryScore(x)
        score.description = "The spontaneous firing test defined by the mean firing rate of the model = " + str(a_prediction) + " compared against the observed experimental data " + str(observation) + " whose " + str(score)
        if score.score==1:
            ans = "The model " + model.name + " passed the " + self.__class__.__name__ + ". The mean firing rate of the model = " + str(a_prediction) + " and the validation data is " + str(observation)
        else:
            ans = "The model " + model.name + " failed the " + self.__class__.__name__ + ". The mean firing rate of the model = " + str(a_prediction) + " and the validation data is " + str(observation)
        print ans
        print fanofactor(spike_train)
        return score


<commit_msg>Initial Commit<commit_after># ============================================================================
# test_for_complex_bursts.py
#
# created  10 October 2017 Lungsi
# modified
#
# ============================================================================

import os

import numpy as np
import sciunit
import quantities as pq
from elephant.statistics import mean_firing_rate as mfr
from elephant.statistics import isi

from cerebunit.file_manager import get_folder_path_and_name as gfpan
from cerebunit.score_manager import BinaryScore
from cerebunit.capabilities.cells.response import ProducesSpikeTrain


class ComplexBurstingTest(sciunit.Test, BinaryScore):
    '''
    The Complex Bursting Test is a test comparing the observed spiking frequency in real animal to those generated by the model (from soma, "vm_soma"). This is done by comparing the mean spike frequencies.
    '''
    required_capabilities = (ProducesSpikeTrain,)
    score_type = BinaryScore
    #
    def generate_prediction(self, model, verbose=False):
        '''
        Generates spike train from various cell regions.
        Default cell_regions = {"vm_soma": 0.0, "vm_NOR3": 0.0}
        The value of each key is the threshold defined for
        spiking.
        The function is automatically called by sciunit.Test
        which this test is a child of.
        Therefore as part of sciunit generate_prediction is
        mandatory.
        '''
        # Inject current >= 2 nA
        self.inj_current = \
                { "current1":
                    {"amp": 2.0, "dur": 4000.0, "delay": 1000.0} }
        model.set_stimulation_properties( self.inj_current )
        #
        setup_parameters = { "dt": 0.025,   "celsius": 37,
                             "tstop": 4000, "v_init": -65 }
        model.cell_regions = {"vm_soma": 0.0}
        model.set_simulation_properties(setup_parameters)
        #
        model.produce_spike_train()
        #self.process_prediction(model)
        return model

    def get_spike_train_for_current(self, model):
        '''
        The model.produce_spike_train() results in spike train for
        the initial (no injection), injection and later (no inject)
        This function slices the spike train during injection alone.
        ======================Use Case============================
        spike_train = get_spike_train_for_current(model)
        ===========================================================
        This function is called by process_prediction
        '''
        # get all the spike train for desired cell region
        all_spike_train = \
                model.predictions["spike_train"]["vm_soma"]
        # set the time boundaries for the spike train
        current_key = self.inj_current.keys()[0] # for only 1 current
        spike_start = \
                self.inj_current[current_key]["delay"]
        spike_stop = spike_start \
                + self.inj_current[current_key]["dur"]
        # slice spike train for current injection
        sliced_spike_train = \
                all_spike_train.time_slice(spike_start, spike_stop)
        #
        sliced_indices = []
        for i, j in enumerate(all_spike_train):
            if j >= spike_start:
                sliced_indices.append(i)
        #
        return all_spike_train, sliced_spike_train, sliced_indices


    def process_prediction(self, model):
        '''
        Once the model has run, this function can be used to
        process the spike_train prediction to get the  mean
        firing rate from soma during injection alone.
        '''
        # get the spike trains
        all_spike_train, sliced_spike_train, sliced_indices = \
                self.get_spike_train_for_current(model)
        # compute the mean freq for spike train with injection
        freq = mfr(sliced_spike_train).rescale(pq.Hz)
        #
        all_isi = isi(all_spike_train)
        sliced_isi = all_isi(sliced_indices[0]:sliced_indices[-1])
        return freq, sliced_isi

    def compute_score(self, observation, model, verbose=False):
        '''
        This function like generate_pediction is called automatically
        by sciunit which SpontaneousFiringTest is a child of.
        This function must be named compute_score
        This function calls the function process_prediction to return
        the mean firing reate of spike trains from all the cell_regions
        Off al the cell_regions our region of interest is "vm_soma".
        The prediction processed from "vm_soma" is then compared against
        the experimental_data to get the binary score; 0 if the
        prediction correspond with experiment, else 1.
        '''
        a1_prediction, sliced_isi = self.process_prediction(model)
        coeff_variation = np.std(sliced_isi)/np.mean(sliced_isi)
        a2_prediction = coeff_variation.item()
        x = BinaryScore.compute( observation,
                                 a_prediction  )
        score = BinaryScore(x)
        score.description = "The spontaneous firing test defined by the mean firing rate of the model = " + str(a_prediction) + " compared against the observed experimental data " + str(observation) + " whose " + str(score)
        if score.score==1:
            ans = "The model " + model.name + " passed the " + self.__class__.__name__ + ". The mean firing rate of the model = " + str(a_prediction) + " and the validation data is " + str(observation)
        else:
            ans = "The model " + model.name + " failed the " + self.__class__.__name__ + ". The mean firing rate of the model = " + str(a_prediction) + " and the validation data is " + str(observation)
        print ans
        print a1_prediction
        print a2_prediction
        #print fanofactor(spike_train)
        return score



{'fraction_non_alphanumeric': 0.11648960739030023, 'fraction_numerical': 0.00859122401847575, 'mean_word_length': 2.6848196051735873, 'pattern_counts': {'":': 22, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3635061', 'n_tokens_mistral': 3050, 'n_tokens_neox': 2833, 'n_words': 920}