Ejemplo n.º 1
0
def dtc_to_rheo(dtc):
    from neuronunit.models.reduced import ReducedModel
    from neuronunit.optimization import get_neab
    from neuronunit.optimization import evaluate_as_module
    model = ReducedModel(get_neab.LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')

    model.set_attrs(dtc.attrs)
    #dtc.cell_name = model._backend.cell_name
    #dtc.current_src_name = model._backend.current_src_name
    dtc.scores = None
    dtc.scores = {}
    dtc.differences = None
    dtc.differences = {}
    score = get_neab.tests[0].judge(model,
                                    stop_on_error=False,
                                    deep_error=True)
    observation = score.observation
    prediction = score.prediction
    delta = evaluate_as_module.difference(observation, prediction)
    dtc.differences[str(get_neab.tests[0])] = delta
    dtc.scores[str(get_neab.tests[0])] = score.sort_key
    dtc.rheobase = score.prediction
    return dtc
Ejemplo n.º 2
0
def nunit_evaluation(tuple_object):
    # Inputs single data transport container modules, and neuroelectro observations that
    # inform test error error_criterion
    # Outputs Neuron Unit evaluation scores over error criterion
    dtc, tests = tuple_object
    dtc = copy.copy(dtc)
    dtc.model_path = path_params['model_path']
    LEMS_MODEL_PATH = path_params['model_path']
    assert dtc.rheobase is not None
    tests = [t for t in tests if str('RheobaseTestP') not in str(t)]

    #for t in tests:
    #    dtc.scores[str(t)] = 1.0

    for k, t in enumerate(tests):
        t.params = dtc.vtest[k]
        score = None
        model = None
        model = ReducedModel(LEMS_MODEL_PATH,
                             name=str('vanilla'),
                             backend=('NEURON', {
                                 'DTC': dtc
                             }))
        model.set_attrs(dtc.attrs)
        score = t.judge(model, stop_on_error=False, deep_error=False)

        if type(score.sort_key) is not type(None):
            dtc.scores[str(t)] = 1 - score.sort_key
            dtc = score_proc(dtc, t, copy.copy(score))
        else:
            dtc.scores[str(t)] = 1.0
    dtc.get_ss()
    return dtc
    '''
Ejemplo n.º 3
0
def bind_score_to_dtc(dtc):
    #import evaluate_as_module
    from neuronunit.optimization import evaluate_as_module

    #from neuronunit.models import backends
    from neuronunit.models.reduced import ReducedModel
    import quantities as pq
    import numpy as np
    from neuronunit.optimization import get_neab

    model = ReducedModel(get_neab.LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURONMemory')

    model.set_attrs(dtc.attrs)
    get_neab.tests[0].prediction = dtc.rheobase
    model.rheobase = dtc.rheobase['value']
    if dtc.rheobase['value'] <= 0.0:
        return dtc

    for k, t in enumerate(get_neab.tests):
        if k > 0:

            t.params = dtc.vtest[k]
            score = t.judge(model, stop_on_error=False, deep_error=False)
            #import pdb; pdb.set_trace()
            dtc.scores[str(t)] = score.sort_key
            try:
                observation = score.observation
                prediction = score.prediction
                delta = evaluate_as_module.difference(observation, prediction)
                dtc.differences[str(t)] = delta
            except:
                pass
    return dtc
Ejemplo n.º 4
0
def nunit_evaluation(dtc,error_criterion):
    # Inputs single data transport container modules, and neuroelectro observations that
    # inform test error error_criterion
    # Outputs Neuron Unit evaluation scores over error criterion

    dtc.model_path = path_params['model_path']
    LEMS_MODEL_PATH = path_params['model_path']
    assert dtc.rheobase is not None
    from neuronunit.models.reduced import ReducedModel
    #from neuronunit.optimization import get_neab
    tests = error_criterion
    model = ReducedModel(LEMS_MODEL_PATH,name=str('vanilla'),backend=('NEURON',{'DTC':dtc}))
    model.set_attrs(dtc.attrs)
    tests[0].prediction = dtc.rheobase
    model.rheobase = dtc.rheobase['value']
    from dask import dataframe as dd
    if dtc.score is None:
        dtc.score = {}

    for k,t in enumerate(tests[1:-1]):
        t.params = dtc.vtest[k]
        print(t.params)
        score = None
        score = t.judge(model,stop_on_error = False, deep_error = False)
        if score.sort_key is not None:
            # dtc.scores.get(str(t), score.sort_key)
            # dtc.score.get(str(t), score.sort_key-1)
            dtc.scores[str(t)] = 1.0 - score.sort_key
            print(str(t),score.sort_key)
            if not hasattr(dtc,'score'):
                dtc.score = {}
            dtc.score[str(t)] = score.sort_key
        else:
            pass
    return dtc
Ejemplo n.º 5
0
def nunit_evaluation(tuple_object):  #,backend=None):
    # Inputs single data transport container modules, and neuroelectro observations that
    # inform test error error_criterion
    # Outputs Neuron Unit evaluation scores over error criterion
    dtc, tests = tuple_object
    dtc = copy.copy(dtc)
    dtc.model_path = path_params['model_path']
    LEMS_MODEL_PATH = path_params['model_path']
    assert dtc.rheobase is not None
    backend = dtc.backend
    if backend == 'glif':

        model = glif.GC(
        )  #ReducedModel(LEMS_MODEL_PATH,name=str('vanilla'),backend=('NEURON',{'DTC':dtc}))
        tests[0].prediction = dtc.rheobase
        model.rheobase = dtc.rheobase['value']
    else:
        model = ReducedModel(LEMS_MODEL_PATH,
                             name=str('vanilla'),
                             backend=('NEURON', {
                                 'DTC': dtc
                             }))
        model.set_attrs(dtc.attrs)
        tests[0].prediction = dtc.rheobase
        model.rheobase = dtc.rheobase['value']

    for k, t in enumerate(tests[1:-1]):
        t.params = dtc.vtest[k]
        score = None
        score = t.judge(model, stop_on_error=False, deep_error=False)
        dtc.score[str(t)] = {}
        dtc.score[str(t)]['value'] = copy.copy(score.sort_key)

        if hasattr(score, 'prediction'):

            if type(score.prediction) is not type(None):

                dtc.score[str(t)][str('prediction')] = score.prediction
                dtc.score[str(t)][str('observation')] = score.observation

                if 'mean' in score.observation.keys(
                ) and 'mean' in score.prediction.keys():
                    print(score.observation.keys())
                    dtc.score[str(t)][str('agreement')] = np.abs(
                        score.observation['mean'] - score.prediction['mean'])
        else:
            print(score, type(score))
        if score.sort_key is not None:
            ##
            # This probably does something different to what I thought.
            ##
            #dtc.scores.get(str(t), 1.0 - score.sort_key)

            dtc.scores[str(t)] = 1.0 - score.sort_key
        else:
            dtc.scores[str(t)] = 1.0
    return dtc
Ejemplo n.º 6
0
        def check_current(ampl, dtc):
            '''
            Inputs are an amplitude to test and a virtual model
            output is an virtual model with an updated dictionary.
            '''
            import copy
            import os
            import quantities
            from neuronunit.models.reduced import ReducedModel
            import neuronunit
            LEMS_MODEL_PATH = str(neuronunit.__path__[0]) + str(
                '/models/NeuroML2/LEMS_2007One.xml')
            dtc.model_path = LEMS_MODEL_PATH
            model = ReducedModel(dtc.model_path,
                                 name='vanilla',
                                 backend=(str(dtc.backend), {
                                     'DTC': dtc
                                 }))

            import copy
            model.set_attrs(dtc.attrs)

            DELAY = 100.0 * pq.ms
            DURATION = 1000.0 * pq.ms
            params = {
                'injected_square_current': {
                    'amplitude': 100.0 * pq.pA,
                    'delay': DELAY,
                    'duration': DURATION
                }
            }

            dtc = copy.copy(dtc)
            ampl = float(ampl)
            #print(dtc.lookup)
            if ampl not in dtc.lookup or len(dtc.lookup) == 0:
                current = params.copy()['injected_square_current']
                uc = {'amplitude': ampl}
                current.update(uc)
                current = {'injected_square_current': current}
                dtc.run_number += 1
                model.set_attrs(dtc.attrs)
                model.inject_square_current(current)
                dtc.previous = ampl
                n_spikes = model.get_spike_count()
                dtc.lookup[float(ampl)] = n_spikes
                if n_spikes == 1:
                    dtc.rheobase = float(ampl)
                    dtc.boolean = True
                    return dtc

                return dtc
            if float(ampl) in dtc.lookup:
                return dtc
Ejemplo n.º 7
0
 def test_frp(self):
     from neuronunit.models.reduced import ReducedModel
     from neuronunit.optimization import get_neab
     model = ReducedModel(get_neab.LEMS_MODEL_PATH,name=str('vanilla'),backend=('NEURON'))
     attrs = {'a':0.02, 'b':0.2, 'c':-65+15*0.5, 'd':8-0.5**2 }
     from neuronunit.optimization.data_transport_container import DataTC
     dtc = DataTC()
     from neuronunit.tests import fi
     model.set_attrs(attrs)
     from neuronunit.optimization import get_neab
     rtp = get_neab.tests[0]
     rheobase = rtp.generate_prediction(model)
     self.assertTrue(float(rheobase['value']))
Ejemplo n.º 8
0
        def check_current(dtc):
            '''
            Inputs are an amplitude to test and a virtual model
            output is an virtual model with an updated dictionary.
            '''

            LEMS_MODEL_PATH = str(neuronunit.__path__[0]) + str(
                '/models/NeuroML2/LEMS_2007One.xml')
            dtc.model_path = LEMS_MODEL_PATH

            model = ReducedModel(dtc.model_path,
                                 name='vanilla',
                                 backend=(dtc.backend, {
                                     'DTC': dtc
                                 }))

            dtc.current_src_name = model._backend.current_src_name
            assert type(dtc.current_src_name) is not type(None)
            dtc.cell_name = model._backend._cell_name
            #model.set_attrs(dtc.attrs)

            DELAY = 100.0 * pq.ms
            DURATION = 1000.0 * pq.ms
            params = {
                'injected_square_current': {
                    'amplitude': 100.0 * pq.pA,
                    'delay': DELAY,
                    'duration': DURATION
                }
            }

            ampl = float(dtc.ampl)
            if ampl not in dtc.lookup or len(dtc.lookup) == 0:
                current = params.copy()['injected_square_current']
                uc = {'amplitude': ampl}
                current.update(uc)
                current = {'injected_square_current': current}
                dtc.run_number += 1
                model.set_attrs(dtc.attrs)
                model.inject_square_current(current)
                #dtc.previous = ampl
                n_spikes = model.get_spike_count()
                dtc.lookup[float(ampl)] = n_spikes
                if n_spikes == 1:
                    dtc.rheobase = float(ampl)
                    dtc.boolean = True
                    return dtc

                return dtc
            if float(ampl) in dtc.lookup:
                return dtc
Ejemplo n.º 9
0
def dtc_to_rheo(dtc):
    from neuronunit.optimization import get_neab
    dtc.scores = {}
    from neuronunit.models.reduced import ReducedModel
    model = ReducedModel(get_neab.LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')
    model.set_attrs(dtc.attrs)
    rbt = get_neab.tests[0]
    score = rbt.judge(model, stop_on_error=False, deep_error=True)
    dtc.scores[str(rbt)] = score.sort_key
    observation = score.observation
    dtc.rheobase = score.prediction
    return dtc
Ejemplo n.º 10
0
        def check_current(ampl, dtc):
            '''
            Inputs are an amplitude to test and a virtual model
            output is an virtual model with an updated dictionary.
            '''
            ampl = float(ampl)
            import os
            #from neuronunit.models import reduced
            from neuronunit.models.reduced import ReducedModel
            #assert os.path.isfile(dtc.model_path), "%s is not a file" % dtc.model_path
            model = ReducedModel(dtc.model_path,
                                 name='vanilla',
                                 backend='NEURON')
            #print(model)
            #import pdb; pdb.set_trace()
            DELAY = 100.0 * pq.ms
            DURATION = 1000.0 * pq.ms
            params = {
                'injected_square_current': {
                    'amplitude': 100.0 * pq.pA,
                    'delay': DELAY,
                    'duration': DURATION
                }
            }

            if ampl not in dtc.lookup or len(dtc.lookup) == 0:
                current = params.copy()['injected_square_current']
                uc = {'amplitude': ampl}
                current.update(uc)
                current = {'injected_square_current': current}
                dtc.run_number += 1
                #import ipyparallel as ipp
                #model = ipp.Reference('model')
                model.set_attrs(dtc.attrs)
                model.name = dtc.attrs
                model.inject_square_current(current)
                dtc.previous = ampl
                n_spikes = model.get_spike_count()
                dtc.lookup[float(ampl)] = n_spikes
                #name = str('rheobase {0} parameters {1}'.format(str(current),str(model.params)))

                if n_spikes == 1:
                    dtc.rheobase = float(ampl)
                    dtc.boolean = True
                    return dtc

                return dtc
            if float(ampl) in dtc.lookup:
                return dtc
Ejemplo n.º 11
0
def dtc_to_rheo(xargs):
    dtc,rtest = xargs
    dtc.model_path = path_params['model_path']
    LEMS_MODEL_PATH = path_params['model_path']
    model = ReducedModel(LEMS_MODEL_PATH,name=str('vanilla'),backend='NEURON')
    model.set_attrs(dtc.attrs)
    dtc.scores = {}
    dtc.score = {}
    score = rtest.judge(model,stop_on_error = False, deep_error = True)
    #if bool(model.get_spike_count() == 1 or model.get_spike_count() == 0)
    if score.sort_key is not None:
        dtc.scores[str(rtest)] = 1 - score.sort_key #pd.DataFrame([ ])
    dtc.rheobase = score.prediction
    #assert dtc.rheobase is not None
    return dtc
Ejemplo n.º 12
0
def use_dtc_to_plotting(dtcpop, minimagr):
    from neuronunit.capabilities import spike_functions
    import matplotlib.pyplot as plt
    import numpy as np
    plt.clf()
    plt.style.use('ggplot')
    fig, axes = plt.subplots(figsize=(10, 10), facecolor='white')
    stored_min = []
    stored_max = []
    for dtc in dtcpop[1:-1]:
        plt.plot(dtc.tvec, dtc.vm0, linewidth=3.5, color='grey')
        stored_min.append(np.min(dtc.vm0))
        stored_max.append(np.max(dtc.vm0))

    from neuronunit.models.reduced import ReducedModel
    from neuronunit.optimization.get_neab import tests as T
    from neuronunit.optimization import get_neab
    from neuronunit.optimization import evaluate_as_module
    from neuronunit.optimization.evaluate_as_module import pre_format
    model = ReducedModel(get_neab.LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')
    import neuron
    model._backend.reset_neuron(neuron)
    model.set_attrs(minimagr.attrs)
    model.rheobase = minimagr.rheobase['value']
    minimagr = pre_format(minimagr)
    parameter_list = list(minimagr.vtest.values())
    model.inject_square_current(parameter_list[0])
    model._backend.local_run()
    assert model.get_spike_count() == 1
    print(model.get_spike_count(), bool(model.get_spike_count() == 1))
    brute_best = list(model.results['vm'])

    plt.plot(dtcpop[0].tvec,
             brute_best,
             linewidth=1,
             color='blue',
             label='best candidate via grid')  #+str(mini.scores))
    plt.plot(dtcpop[0].tvec,
             dtcpop[0].vm0,
             linewidth=1,
             color='red',
             label='best candidate via GA')  #+str(miniga.scores))
    plt.legend()
    plt.ylabel('$V_{m}$ mV')
    plt.xlabel('ms')
    plt.show()
Ejemplo n.º 13
0
def dtc_to_rheo(xargs):
    dtc, rtest, backend = xargs
    LEMS_MODEL_PATH = path_params['model_path']

    model = ReducedModel(LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')
    model.set_attrs(dtc.attrs)
    dtc.scores = {}
    dtc.score = {}
    score = rtest.judge(model, stop_on_error=False, deep_error=True)
    if score.sort_key is not None:
        dtc.scores.get(str(rtest), 1 - score.sort_key)
        dtc.scores[str(rtest)] = 1 - score.sort_key
    dtc.rheobase = score.prediction
    return dtc
Ejemplo n.º 14
0
def parallel_method(item_of_iter_list):

    from neuronunit.optimization import get_neab
    get_neab.LEMS_MODEL_PATH = '/home/jovyan/neuronunit/neuronunit/optimization/NeuroML2/LEMS_2007One.xml'
    #from neuronunit.models import backends
    from neuronunit.models.reduced import ReducedModel
    model = ReducedModel(get_neab.LEMS_MODEL_PATH,name=str('vanilla'),backend='NEURON')
    model.set_attrs(item_of_iter_list)
    get_neab.tests[0].prediction = dtc.rheobase
    model.rheobase = dtc.rheobase['value']
    scores = []
    for k,t in enumerate(get_neab.tests):
        if k>1:
            t.params = dtc.vtest[k]
            score = t.judge(model,stop_on_error = False, deep_error = True)
            scores.append(score.sort_key,score)
    return scores
Ejemplo n.º 15
0
def hack_judge(test_and_models):
    (test, attrs) = test_and_models
    model = None
    obs = test.observation
    LEMS_MODEL_PATH = path_params['model_path']

    model = ReducedModel(LEMS_MODEL_PATH, name=str('vanilla'), backend=('RAW'))
    model.set_attrs(attrs)
    test.generate_prediction(model)
    pred = test.generate_prediction(model)
    score = test.compute_score(obs, pred)
    try:
        print(obs['value'], pred['value'])
    except:
        print(obs['mean'], pred['mean'])

    return score
Ejemplo n.º 16
0
        def check_current(ampl,dtc):
            '''
            Inputs are an amplitude to test and a virtual model
            output is an virtual model with an updated dictionary.
            '''
            import copy
            import os
            import quantities
            from neuronunit.models.reduced import ReducedModel
            import neuronunit
            LEMS_MODEL_PATH = str(neuronunit.__path__[0])+str('/models/NeuroML2/LEMS_2007One.xml')
            dtc.model_path = LEMS_MODEL_PATH
            model = ReducedModel(dtc.model_path,name='vanilla', backend=(str(dtc.backend), {'DTC':dtc}))

            import copy
            model.set_attrs(dtc.attrs)

            DELAY = 100.0*pq.ms
            DURATION = 1000.0*pq.ms
            params = {'injected_square_current':
                      {'amplitude':100.0*pq.pA, 'delay':DELAY, 'duration':DURATION}}

            dtc = copy.copy(dtc)
            ampl = float(ampl)
            #print(dtc.lookup)
            if ampl not in dtc.lookup or len(dtc.lookup) == 0:
                current = params.copy()['injected_square_current']
                uc = {'amplitude':ampl}
                current.update(uc)
                current = {'injected_square_current':current}
                dtc.run_number += 1
                model.set_attrs(dtc.attrs)
                model.inject_square_current(current)
                dtc.previous = ampl
                n_spikes = model.get_spike_count()
                dtc.lookup[float(ampl)] = n_spikes
                if n_spikes == 1:
                    dtc.rheobase = float(ampl)
                    dtc.boolean = True
                    return dtc

                return dtc
            if float(ampl) in dtc.lookup:
                return dtc
Ejemplo n.º 17
0
def dtc_to_rheo(dtc):
    from neuronunit.models.reduced import ReducedModel
    from neuronunit.optimization import get_neab
    dtc.model_path = get_neab.LEMS_MODEL_PATH
    dtc.LEMS_MODEL_PATH = get_neab.LEMS_MODEL_PATH
    model = ReducedModel(dtc.LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')
    model.set_attrs(dtc.attrs)
    dtc.scores = {}
    dtc.score = {}
    score = get_neab.tests[0].judge(model,
                                    stop_on_error=False,
                                    deep_error=True)
    #if bool(model.get_spike_count() == 1 or model.get_spike_count() == 0)
    if score.sort_key is not None:
        dtc.scores[str(
            get_neab.tests[0])] = 1 - score.sort_key  #pd.DataFrame([ ])
    dtc.rheobase = score.prediction
    #assert dtc.rheobase is not None
    return dtc
Ejemplo n.º 18
0
def plot_vm(hof,ax,key):
    ax.cla()
    best_dtc = hof[1].dtc
    best_rh = hof[1].dtc.rheobase
    print( [ h.dtc.rheobase for h in hof ])
    
    neuron = None
    model = ReducedModel(path_params['model_path'],name = str('regular_spiking'),backend =('NEURON',{'DTC':best_dtc}))
    params = {'injected_square_current':
            {'amplitude': best_rh['value'], 'delay':DELAY, 'duration':DURATION}}
    model.set_attrs(hof[0].dtc.attrs)
    results = model.inject_square_current(params)
    print(model.attrs,best_dtc.attrs,best_rh)
    vm = model.get_membrane_potential()
    times = vm.times
    ax.plot(times,vm)
    #ax.xlabel('ms')
    #ax.ylabel('mV')
    #ax.set_xlim(np.min(x),np.max(x))
    #ax.set_ylim(np.min(z),np.max(z))
    return ax
Ejemplo n.º 19
0
def sanity_check_score(pop, td, tests):
    '''
    Used for debugging with fake models
    '''
    dtcpop = update_dtc_pop(pop, td)
    for dtc in dtcpop:
        dtc.scores = None
        dtc.scores = {}

    for t in tests:
        for dtc in dtcpop:
            LEMS_MODEL_PATH = path_params['model_path']
            model = ReducedModel(LEMS_MODEL_PATH,
                                 name=str('vanilla'),
                                 backend='NEURON')
            model.set_attrs(dtc.attrs)
            score = t.judge(model)
            dtc.scores.get(str(t), 1.0)

            if score.sort_key is not None:
                dtc.scores[str(t)] = 1 - score.sort_key
    return dtcpop
Ejemplo n.º 20
0
def nunit_evaluation(tuple_object):#,backend=None):
    # Inputs single data transport container modules, and neuroelectro observations that
    # inform test error error_criterion
    # Outputs Neuron Unit evaluation scores over error criterion
    dtc,tests = tuple_object
    dtc.model_path = path_params['model_path']
    LEMS_MODEL_PATH = path_params['model_path']
    assert dtc.rheobase is not None
    backend = dtc.backend
    if backend == 'glif':

        model = glif.GC()#ReducedModel(LEMS_MODEL_PATH,name=str('vanilla'),backend=('NEURON',{'DTC':dtc}))
        tests[0].prediction = dtc.rheobase
        model.rheobase = dtc.rheobase['value']
    else:
        model = ReducedModel(LEMS_MODEL_PATH,name = str('vanilla'),backend = ('NEURON',{'DTC':dtc}))
        model.set_attrs(dtc.attrs)
        tests[0].prediction = dtc.rheobase
        model.rheobase = dtc.rheobase['value']


    for k,t in enumerate(tests[1:-1]):
        t.params = dtc.vtest[k]
        score = t.judge(model,stop_on_error = False, deep_error = False)
        dtc.score.get(str(t), score)
        dtc.score[str(t)][str('prediction')] = score.prediction
        dtc.score[str(t)][str('observation')] = score.observation

        if score.sort_key is not None:
            if not hasattr(dtc,'score'):
                dtc.score = score
                print(dtc.score.prediction)
                print(dtc.score.observation)

            dtc.scores.get(str(t), 1.0 - score.sort_key)
        else:
            dtc.scores[str(t)] = 1.0
    return dtc
Ejemplo n.º 21
0
def dtc_to_rheo(xargs):
    dtc, rtest, backend = xargs
    LEMS_MODEL_PATH = path_params['model_path']
    model = ReducedModel(LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')
    model.set_attrs(dtc.attrs)
    dtc.scores = {}
    dtc.score = {}
    score = rtest.judge(model, stop_on_error=False, deep_error=False)
    dtc.scores.get(str(rtest), 1.0)

    if hasattr(score, 'prediction'):
        has_pred = bool(type(score.prediction) is not type(None))
        has_zf = bool(type(score.sort_key) is not type(None))
        if has_zf and has_pred:
            dtc.scores[str(rtest)] = 1 - score.sort_key
            dtc = score_proc(dtc, rtest, score)
            dtc.rheobase = score.prediction
    else:
        dtc.rheobase = None

    return dtc
Ejemplo n.º 22
0
def hack_judge(test_and_models):
    LEMS_MODEL_PATH = path_params['model_path']
    (test, attrs) = test_and_models
    model = None
    obs = test.observation
    model = ReducedModel(LEMS_MODEL_PATH, name=str('vanilla'), backend=('RAW'))
    model.set_attrs(attrs)
    #test.generate_prediction(model)
    pred = test.generate_prediction(model)
    print('gets here a')
    score = test.compute_score(obs, pred)
    print('gets here b')

    import pdb
    pdb.set_trace()
    print(score)
    print('gets here c')

    #try:
    #    print(obs['value'],pred['value'])
    #except:
    #    print(obs['mean'],pred['mean'])

    return score, pred
Ejemplo n.º 23
0
def parallel_method(dtc):

    from neuronunit.models.reduced import ReducedModel
    #try:
    from neuronunit.optimization import get_neab
    tests = get_neab.tests
    #dtc.cell_name
    #dtc.current_src_name
    #model = ReducedModel(get_neab.LEMS_MODEL_PATH,name=str('vanilla'),backend='NEURON',cell_name = dtc.cell_name, current_src_name = dtc.current_src_name)

    model = ReducedModel(get_neab.LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')
    model.set_attrs(dtc.attrs)
    tests[0].prediction = dtc.rheobase
    model.rheobase = dtc.rheobase['value']
    from neuronunit.optimization import evaluate_as_module
    dtc = evaluate_as_module.pre_format(dtc)
    for k, t in enumerate(tests):
        if k > 0 and float(dtc.rheobase['value']) > 0:
            t.params = dtc.vtest[k]
            score = t.judge(model, stop_on_error=False, deep_error=False)
            dtc.scores[str(t)] = score.sort_key
    return dtc
Ejemplo n.º 24
0
def dtc_to_plotting(dtc):
    '''
    Inputs a data transport container, containing either no recording vectors,
    or existing recording vectors that are intended to be over written with fresh ones.
    outputs a data transport container with recording vectors added.
    '''
    import copy
    dtc = copy.copy(dtc)
    dtc.t = None
    from neuronunit.models.reduced import ReducedModel
    from neuronunit.optimization import get_neab
    model = ReducedModel(get_neab.LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend=('NEURON', {
                             'DTC': dtc
                         }))
    model.set_attrs(dtc.attrs)
    model.rheobase = dtc.rheobase['value']
    score = get_neab.tests[-1].judge(model,
                                     stop_on_error=False,
                                     deep_error=True)
    dtc.vm = list(model.results['vm'])
    dtc.t = list(model.results['time'])
    return dtc
Ejemplo n.º 25
0
LEMS_MODEL_PATH = path_params['model_path']
import neuronunit.optimization as opt
import quantities as pq
fig = plt.figure()

plt.clf()

from neuronunit.optimization.data_transport_container import DataTC
model = ReducedModel(LEMS_MODEL_PATH,name = str('vanilla'),backend = ('RAW'))
for i in npcl['pf'][0:2]:
    iparams = {}
    iparams['injected_square_current'] = {}
    iparams['injected_square_current']['amplitude'] =i.dtc.rheobase
    model = None
    model = ReducedModel(LEMS_MODEL_PATH,name = str('vanilla'),backend = ('RAW'))
    model.set_attrs(i.dtc.attrs)

    #['amplitude']  = dtc.vtest[k]['injected_square_current']['amplitude']
    DELAY = 100.0*pq.ms
    DURATION = 1000.0*pq.ms
    iparams['injected_square_current']['delay'] = DELAY
    iparams['injected_square_current']['duration'] = int(DURATION)
    model.inject_square_current(iparams)
    n_spikes = len(model.get_spike_train())
    if n_spikes:
        print(n_spikes)
        #print(i[0].scores['RheobaseTestP']*pq.pA)
        plt.plot(model.get_membrane_potential().times,model.get_membrane_potential())#,label='ground truth')
        plt.legend()

#gca().set_axis_off()
Ejemplo n.º 26
0
modelp = ReducedModel(path_params['model_path'],
                      name=str('regular_spiking'),
                      backend=('NEURON', {
                          'DTC': dtc
                      }))
observations = {}
predictions = {}

scores = {}
import dask.bag as db
for t in tests:
    LEMS_MODEL_PATH = path_params['model_path']
    model = ReducedModel(LEMS_MODEL_PATH,
                         name=str('vanilla'),
                         backend='NEURON')
    model.set_attrs(dtc.attrs)
    score = t.judge(model)
    scores[str(t)] = score
    observations[str(t)] = score.observation
    predictions[str(t)] = score.prediction


def dic_reductions(observations, predictions):

    simple_pa = {
        k: v['value']
        for k, v in predictions.items() if 'value' in v.keys()
    }
    simple_pa.update(
        {k: v['mean']
         for k, v in predictions.items() if 'mean' in v.keys()})
Ejemplo n.º 27
0
class TestBackend(unittest.TestCase):
    def setUp(self):
        self.predictions = None
        self.predictionp = None
        self.score_p = None
        self.score_s = None
        from neuronunit.models.reduced import ReducedModel
        from neuronunit.optimization import get_neab
        print(get_neab.LEMS_MODEL_PATH)
        #def create_model():
        # cannot be pickled.
        self.model = ReducedModel(get_neab.LEMS_MODEL_PATH, backend='NEURON')
        self.model = None
        #print(self.model)

    def get_observation(self, cls):
        print(cls.__name__)
        neuron = {'nlex_id': 'nifext_50'}  # Layer V pyramidal cell
        return cls.neuroelectro_summary_observation(neuron)

    def test_0import(self):
        import ipyparallel as ipp
        return True

    def check_parallel_path_consistency(self):
        '''
        import paths and test for consistency
        '''
        from neuronunit import models
        return models.__file__

    def test_1_check_paths(self):
        path_serial = self.check_parallel_path_consistency()
        paths_parallel = dview.apply_async(
            self.check_parallel_path_consistency).get_dict()
        self.assertEqual(path_serial, paths_parallel[0])

    def backend_inheritance(self):
        from neuronunit.models.reduced import ReducedModel
        from neuronunit.optimization import get_neab
        print(get_neab.LEMS_MODEL_PATH)
        model = ReducedModel(get_neab.LEMS_MODEL_PATH, backend='NEURON')
        ma = list(dir(model))

        #self.assertTrue('get_spike_train' in method_methods_avail)
        if 'get_spike_train' in ma and 'rheobase' in ma:
            return True
        else:
            return False

    def test_3_backend_inheritance(self):
        boolean = self.backend_inheritance()
        self.assertTrue(boolean)

    def test_4_backend_inheritance_parallel(self):
        booleans = self.backend_inheritance()
        booleanp = dview.apply_sync(self.backend_inheritance)
        self.assertEqual(booleans, booleanp[0])

    def try_hard_coded0(self):
        params0 = {
            'C': '0.000107322241995',
            'a': '0.177922330376',
            'b': '-5e-09',
            'c': '-59.5280130394',
            'd': '0.153178745992',
            'k': '0.000879131572692',
            'v0': '-73.3255584633',
            'vpeak': '34.5214177196',
            'vr': '-71.0211905343',
            'vt': '-46.6016774842'
        }
        #rheobase = {'value': array(131.34765625) * pA}
        return params0

    def try_hard_coded1(self):
        params1 = {
            'C': '0.000106983591242',
            'a': '0.480856799107',
            'b': '-5e-09',
            'c': '-57.4022276619',
            'd': '0.0818117582621',
            'k': '0.00114004749537',
            'v0': '-58.4899756601',
            'vpeak': '36.6769758895',
            'vr': '-63.4080852004',
            'vt': '-44.1074682812'
        }
        #rheobase = {'value': array(106.4453125) * pA}131.34765625
        return params1

    def difference(self, observation, prediction):  # v is a tesst
        import quantities as pq
        import numpy as np

        # The trick is.
        # prediction always has value. but observation 7 out of 8 times has mean.

        if 'value' in prediction.keys():
            unit_predictions = prediction['value']
            if 'mean' in observation.keys():
                unit_observations = observation['mean']
            elif 'value' in observation.keys():
                unit_observations = observation['value']

        if 'mean' in prediction.keys():
            unit_predictions = prediction['mean']
            if 'mean' in observation.keys():
                unit_observations = observation['mean']
            elif 'value' in observation.keys():
                unit_observations = observation['value']

        to_r_s = unit_observations.units
        unit_predictions = unit_predictions.rescale(to_r_s)
        #unit_observations = unit_observations.rescale(to_r_s)
        unit_delta = np.abs(
            np.abs(unit_observations) - np.abs(unit_predictions))

        ##
        # Repurposed from from sciunit/sciunit/scores.py
        # line 156
        ##
        assert type(observation) in [dict, float, int, pq.Quantity]
        assert type(prediction) in [dict, float, int, pq.Quantity]
        ratio = unit_predictions / unit_observations
        unit_delta = np.abs(
            np.abs(unit_observations) - np.abs(unit_predictions))
        return unit_delta, ratio

    def run_test(self, cls, pred=None):
        observation = self.get_observation(cls)
        test = cls(observation=observation)
        params0 = self.try_hard_coded0()
        #params1 = self.try_hard_coded1()
        #params = [params0,params1]
        #self.model.prediction =
        self.model.set_attrs(params0)

        score0 = test.judge(self.model, stop_on_error=True, deep_error=True)
        return score0
        #df, html = self.bar_char_out(score,str(test),params0)
        #self.model.set_attrs(params1)
        #score1 = test.judge(self.model,stop_on_error = True, deep_error = True)
        #score.summarize()
        #return [score0,score1]
    def test_13inputresistance(self):
        #from neuronunit.optimization import data_transport_container

        from neuronunit.tests.passive import InputResistanceTest as T
        score = self.run_test(T)
        #self.assertTrue(-0.6 < score < -0.5)

    def test_14restingpotential(self):
        #from neuronunit.optimization import data_transport_container

        from neuronunit.tests.passive import RestingPotentialTest as T
        score = self.run_test(T)
        #self.assertTrue(1.2 < score < 1.3)

    def test_15capacitance(self):
        #from neuronunit.optimization import data_transport_container

        from neuronunit.tests.passive import CapacitanceTest as T
        score = self.run_test(T)
        #self.assertTrue(-0.15 < score < -0.05)

    def test_16timeconstant(self):
        #from neuronunit.optimization import data_transport_container

        from neuronunit.tests.passive import TimeConstantTest as T
        score = self.run_test(T)
        #self.assertTrue(-1.45 < score < -1.35)

    def test_17rheobase_parallel(self):
        #from neuronunit.optimization import data_transport_container

        from neuronunit.tests.fi import RheobaseTest as T
        #super(TestsWaveformTestCase,self).prediction = score.prediction
        #self.model.prediction = score.prediction
        #pred =
        score = self.run_test(T)
        #self.prediction = score.prediction
        print(self.model.prediction, 'is prediction being updated properly?')

        self.assertTrue(score.prediction['value'] == 106.4453125
                        or score.prediction['value'] == 131.34765625)

    def test_18rheobase_serial(self):
        from neuronunit.optimization import data_transport_container

        from neuronunit.tests.fi import RheobaseTest as T
        score = self.run_test(T)
        super(TestsWaveformTestCase, self).prediction = score.prediction
        #self.prediction = score.prediction
        self.assertTrue(
            int(score.prediction['value']) == int(106)
            or int(score.prediction['value']) == int(131))

    def update_amplitude(self, test):
        rheobase = self.model.prediction[
            'value']  #first find a value for rheobase
        test.params['injected_square_current']['amplitude'] = rheobase * 1.01

    def test_19ap_width(self):
        #from neuronunit.optimization import data_transport_container

        from neuronunit.tests.waveform import InjectedCurrentAPWidthTest as T
        self.update_amplitude(T)
        score = self.run_test(T)
        #self.assertTrue(-0.6 < score < -0.5)

    def test_20ap_amplitude(self):
        #from neuronunit.optimization import data_transport_container
        from neuronunit.tests.waveform import InjectedCurrentAPAmplitudeTest as T

        self.update_amplitude(T)

        score = self.run_test(T)
        #self.assertTrue(-1.7 < score < -1.6)

    def test_21ap_threshold(self):
        #from neuronunit.optimization import data_transport_container

        from neuronunit.tests.waveform import InjectedCurrentAPThresholdTest as T

        self.update_amplitude(T)

        score = self.run_test(T)
Ejemplo n.º 28
0
        def check_current(dtc):
            '''
            Inputs are an amplitude to test and a virtual model
            output is an virtual model with an updated dictionary.
            '''
            dtc.boolean = False

            LEMS_MODEL_PATH = str(neuronunit.__path__[0]) + str(
                '/models/NeuroML2/LEMS_2007One.xml')
            dtc.model_path = LEMS_MODEL_PATH
            model = ReducedModel(dtc.model_path,
                                 name='vanilla',
                                 backend=(dtc.backend, {
                                     'DTC': dtc
                                 }))
            if dtc.backend is str('NEURON') or dtc.backend is str('jNEUROML'):
                dtc.current_src_name = model._backend.current_src_name
                assert type(dtc.current_src_name) is not type(None)
                dtc.cell_name = model._backend.cell_name

            params = {
                'injected_square_current': {
                    'amplitude': 100.0 * pq.pA,
                    'delay': DELAY,
                    'duration': DURATION
                }
            }

            ampl = float(dtc.ampl)
            if ampl not in dtc.lookup or len(dtc.lookup) == 0:
                uc = {'amplitude': ampl, 'duration': DURATION, 'delay': DELAY}

                dtc.run_number += 1
                model.set_attrs(**dtc.attrs)
                model.inject_square_current(uc)
                n_spikes = model.get_spike_count()

                dtc.previous = ampl

                if dtc.use_diff == True:
                    from neuronunit.tests import druckman2013 as dm
                    DM = dm.Druckmann2013Test()

                    #vm = model.get_membrane_potential()
                    spike_train = DM.get_APs(model)
                    #diff = diff(vm)
                    #spike_train = threshold_detection(diff,threshold= 0.000193667327364)
                    n_spikes = len(spike_train)

                    if n_spikes >= 1:
                        dtc.negative_spiker = None
                        dtc.negative_spiker = True

                else:
                    n_spikes = model.get_spike_count()

                if float(ampl) < -1.0:
                    dtc.rheobase = None
                    dtc.boolean = True
                    return dtc

                if n_spikes == 1:
                    dtc.lookup[float(ampl)] = 1
                    dtc.rheobase = float(ampl) * pq.pA
                    dtc.boolean = True
                    return dtc

                dtc.lookup[float(ampl)] = n_spikes
            return dtc