Beispiel #1
0
    def build_traces(cls, header_info, data_array):
        n_cols = data_array.shape[1]

        # Get the time column:
        time_data_raw = data_array[:, 0]
        time_unit = unit(str(header_info.column_data[0]['unit']))
        time_data = time_data_raw * time_unit

        # Do we build as fixed or variable array:
        trace_builder = (TraceFixedDT
                         if TraceFixedDT.is_array_fixed_dt(time_data) else
                         TraceVariableDT)

        trcs = []
        for i in range(1, n_cols):
            d_i = data_array[:, i]
            column_metadict = header_info.column_data[i]
            dataUnit = unit(str(column_metadict.get('unit', '')))
            data_label = str(column_metadict.get('label', 'Column%d' % i))
            data_tags = str(column_metadict.get('tags', '')).split(',')
            d = d_i * dataUnit

            tr = trace_builder(time_data, d, name=data_label, tags=data_tags)
            trcs.append(tr)
        return trcs
Beispiel #2
0
def get_sample_k(env):
    kStateVars = {'n': {'alpha': [-0.55, -0.01, -1.00, 55.0, -10.00],
                  'beta': [0.125, 0, 0, 65, 80]}}
    k_chl = env.Channel(
        StdChlAlphaBeta,
        name='KChl',
        ion='k',
        equation='n*n*n*n',
        conductance=unit('36:mS/cm2'),
        reversalpotential=unit('-77:mV'),
        statevars=kStateVars,
        )
    return k_chl
    def reduce_to_variable_dt_trace(cls, original_trace, epsilon):
        assert isinstance(original_trace, TracePointBased)
        epsilon = unit(epsilon)

        time_units = original_trace.time_unit
        time_data = original_trace.time_pts_np

        data_units = original_trace.data_unit
        data_data = original_trace.data_pts_np


        pts = zip(time_data.tolist(), data_data.tolist())

        newpts = _simplify_points(pts, epsilon)
        (new_time, new_data) = zip(*newpts)

        new_trace = TraceVariableDT(np.array(new_time) * time_units,
                                    np.array(new_data) * data_units,
                                    name=original_trace.name,
                                    comment=original_trace.comment,
                                    tags=original_trace.tags)

        print 'Simplified from N=%d to N=%d' % (original_trace.get_n(),
                new_trace.get_n())
        return new_trace
Beispiel #4
0
def build_hh_cell(sim, cell_area=None):

    if cell_area is None:
        cell_area = unit('5000:um2')

    morphology = MorphologyBuilder.get_single_section_soma(area=cell_area)
    cell = sim.create_cell(morphology=morphology)

    # Apply the channels uniformly over the cell
    env = sim.environment
    modelsrc = StandardModels.HH52
    cell.apply_channel(
        ChannelLibrary.get_channel(modelsrc=modelsrc,
                                   celltype=None,
                                   channeltype="Na",
                                   env=env))
    cell.apply_channel(
        ChannelLibrary.get_channel(modelsrc=modelsrc,
                                   celltype=None,
                                   channeltype="K",
                                   env=env))
    cell.apply_channel(
        ChannelLibrary.get_channel(modelsrc=modelsrc,
                                   celltype=None,
                                   channeltype="Lk",
                                   env=env))

    return cell
Beispiel #5
0
    def __init__(self,  morphology=None, area=None, segmenter=None, initial_voltage=None, cell_tags=None, cell_type=None, **kwargs):

        if area is not None:
            assert morphology is None
            morphology = MorphologyBuilder.get_single_section_soma(area=area)

        if cell_tags == None:
            cell_tags = []

        from morphforge.simulation.base.segmentation.cellsegmenter import CellSegmenter_MaxCompartmentLength
        super(Cell, self).__init__(**kwargs)

        self.morphology = morphology
        self._cell_type = cell_type

        self.cell_segmenter = (segmenter if segmenter else CellSegmenter_MaxCompartmentLength())
        self.cell_segmenter.connect_to_cell(self)

        self.biophysics = CellBiophysics(self)

        self.initial_voltage = initial_voltage or unit('-51:mV')

        self.cell_tags = cell_tags

        if self.name:
            self.cell_tags = self.cell_tags + [self.name]

        self.population = None
Beispiel #6
0
def get_sample_na(env):
    na_state_vars = { 'm': {
                          'alpha': [-4.00,-0.10,-1.00,40.00,-10.00],
                          'beta':  [4.00, 0.00, 0.00,65.00, 18.00]},
                    'h': {
                            'alpha': [0.07,0.00,0.00,65.00,20.00],
                            'beta':  [1.00,0.00,1.00,35.00,-10.00]}
                      }

    na_chl = env.Channel(
        StdChlAlphaBeta,
        name='NaChl',
        ion='na',
        equation='m*m*m*h',
        conductance=unit('120:mS/cm2'),
        reversalpotential=unit('50:mV'),
        statevars=na_state_vars, 
        )
        
    return na_chl
def _convert_to_unit(o, default_unit):

    assert not isinstance(default_unit, pq.quantity.Quantity)

    if isinstance(o, pq.quantity.Quantity):
        return o.rescale(default_unit)
    elif is_float(o) or is_int(o):
        return o * morphforge.core.quantities.unit_string_parser.parse(default_unit).rescale(default_unit)
    elif isinstance(o, (str, unicode)) and ':' in o:
        return unit(o).rescale(default_unit)
    else:
        raise ValueError()
Beispiel #8
0
    def plot(self, ax, all_traces,  all_eventsets,  time_range=None, linkage=None ) :

        # Which traces are we plotting (rely on a mixon class):
        trcs = [tr for tr in all_traces if self.addtrace_predicate(tr)]
        eventsets = [tr for tr in  all_eventsets if self.addeventset_predicate(tr)] 
        
               
        # Sort and plot:
        for index, trace in enumerate( self.sort_traces(trcs) ): 
            color = linkage.color_allocations.get(trace, None) if linkage else None
            self.plot_trace( trace, time_range=time_range, ax=ax, index=index, color=color)
        
            
        for index, event_set in enumerate( self.sort_eventsets(eventsets) ): 
            self.plot_eventset( event_set, time_range=time_range, ax=ax, index=index+len(trcs) )
            
            #ax.set_ylim( ( (-0.5) * pq.dimensionless, (len(eventsets)+0.5) * pq.dimensionless ) )
        
        
        if len(trcs) == 0:
            padding =0.5
            ax.set_yunit( 1*pq.dimensionless )
            ax.set_ylim( ( (-padding) * pq.dimensionless, (len(eventsets)-1+padding) * pq.dimensionless ) )
        
        #Legend:
        if self.legend_labeller is not None:
            import math
            import __builtin__ as BI
            ncols = BI.max( int( math.floor( len(trcs) / 10.0) ), 1)
            ax.legend(ncol=ncols)

        if self.title:
            ax.set_title( self.title )
            
        # Label up the axis:        
        ax.set_xlabel('Time')
        ax.set_xunit( unit('ms') )
        
        ax.set_ylabel( self.get_selector_ylabel() )
        
        if time_range is not None:
            print 'Setting Time Range', time_range
            ax.set_xlim( time_range )
        if self.yrange is not None:
            ax.set_ylim( self.yrange )

        if self.yunit is not None:
            print 'Setting Yunit', self.yunit
            ax.set_display_unit(y=self.yunit)
        
        # Turn the grid on:
        ax.grid('on')
Beispiel #9
0
    def build_traces(cls, header_info, data_array):
        nCols = data_array.shape[1]

        # Get the time column:
        timeDataRaw  = data_array[:,0]
        timeUnit  = unit( str(header_info.column_data[0]['unit'] ) )
        timeData = timeDataRaw * timeUnit
        
        # Do we build as fixed or variable array:
        tBuilder = Trace_FixedDT if Trace_FixedDT.isArrayFixedDT(timeData) else Trace_VariableDT 
        
        trcs = []
        for i in range(1,nCols):
            d_i = data_array[:,i]
            column_metadict = header_info.column_data[i]
            dataUnit  = unit( str(column_metadict.get('unit',"") ) )
            dataLabel  = str( column_metadict.get('label','Column%d'%i) ) 
            dataTags  = str( column_metadict.get('tags','') ).split(',') 
            d = d_i * dataUnit
            
            tr = tBuilder(timeData, d, name=dataLabel, tags=dataTags)
            trcs.append(tr)
        return trcs
Beispiel #10
0
def build_hh_cell(sim, cell_area=None):
    
    if cell_area is None:
        cell_area = unit('5000:um2')
    
    morphology = MorphologyBuilder.get_single_section_soma(area = cell_area)
    cell = sim.create_cell(morphology=morphology)

    # Apply the channels uniformly over the cell
    env = sim.environment
    modelsrc=StandardModels.HH52
    cell.apply_channel( ChannelLibrary.get_channel(modelsrc=modelsrc, celltype=None, channeltype="Na", env=env) )
    cell.apply_channel( ChannelLibrary.get_channel(modelsrc=modelsrc, celltype=None, channeltype="K", env=env)  )
    cell.apply_channel( ChannelLibrary.get_channel(modelsrc=modelsrc, celltype=None, channeltype="Lk", env=env) )

    return cell
Beispiel #11
0
        def newFunctor(
                env,
                _voltage_interpolation_values=voltage_interpolation_values):

            old_chl = chl_functor(env)
            assert isinstance(
                old_chl, (StdChlAlphaBeta, StdChlAlphaBetaBeta
                          ))  # or issubclass(StdChlAlphaBetaBeta, old_chl)

            # New Name
            if new_name is not None:
                chl_name = new_name
            else:
                chl_name = old_chl.name + clone_name_suffix

            # Interpolation voltages:
            # voltage_interpolation_values=voltage_interpolation_values
            if _voltage_interpolation_values is None:
                _voltage_interpolation_values = linspace(-80, 60,
                                                         10) * unit('mV')

                # Copy the state variables
            new_state_vars = {}
            for state_var in old_chl.get_state_variables():
                alpha, beta = old_chl.get_alpha_beta_at_voltage(
                    statevar=state_var, V=_voltage_interpolation_values)
                inf, tau = InfTauCalculator.alpha_beta_to_inf_tau(alpha, beta)
                V = _voltage_interpolation_values.rescale('mV').magnitude
                inf = inf.rescale(pq.dimensionless).magnitude
                tau = tau.rescale('ms').magnitude
                new_state_vars[state_var] = InfTauInterpolation(V=V,
                                                                inf=inf,
                                                                tau=tau)

            chl = env.Channel(
                MM_InfTauInterpolatedChannel,
                name=chl_name,
                ion=old_chl.ion,
                equation=old_chl.eqn,
                conductance=old_chl.conductance,
                reversalpotential=old_chl.reversalpotential,
                statevars_new=new_state_vars,
            )
            return chl
Beispiel #12
0
        def newFunctor(env, _voltage_interpolation_values=voltage_interpolation_values):



            old_chl = chl_functor(env)
            assert isinstance(old_chl, (StdChlAlphaBeta,
                              StdChlAlphaBetaBeta))  # or issubclass(StdChlAlphaBetaBeta, old_chl)

            # New Name
            if new_name is not None:
                chl_name = new_name
            else:
                chl_name = old_chl.name + clone_name_suffix

            # Interpolation voltages:
            # voltage_interpolation_values=voltage_interpolation_values
            if _voltage_interpolation_values is None:
                _voltage_interpolation_values = linspace(-80, 60, 10) * unit('mV')

                        # Copy the state variables
            new_state_vars = {}
            for state_var in old_chl.get_state_variables():
                alpha, beta = old_chl.get_alpha_beta_at_voltage(statevar=state_var, V=_voltage_interpolation_values)
                inf, tau = InfTauCalculator.alpha_beta_to_inf_tau(alpha, beta)
                V = _voltage_interpolation_values.rescale('mV').magnitude
                inf = inf.rescale(pq.dimensionless).magnitude
                tau = tau.rescale('ms').magnitude
                new_state_vars[state_var] = InfTauInterpolation(V=V, inf=inf, tau=tau)


            chl = env.Channel(
                MM_InfTauInterpolatedChannel,
                name=chl_name,
                ion=old_chl.ion,
                equation=old_chl.eqn,
                conductance=old_chl.conductance,
                reversalpotential=old_chl.reversalpotential,
                statevars_new=new_state_vars,
               )
            return chl
Beispiel #13
0
    def __init__(self,
                 dur1,
                 amp1,
                 dur2='0:ms',
                 dur3='0:ms',
                 amp2='0:mV',
                 amp3='0:mV',
                 rs='0.1:MOhm',
                 **kwargs):

        super(VoltageClampStepChange, self).__init__(**kwargs)

        self.dur1 = unit(dur1)
        self.dur2 = unit(dur2)
        self.dur3 = unit(dur3)

        self.amp1 = unit(amp1)
        self.amp2 = unit(amp2)
        self.amp3 = unit(amp3)
        self.rs = unit(rs)
Beispiel #14
0
    def __init__(self,    morphology, simulation, name= None, segmenter=None, initial_voltage=None, cell_tags = [], **kwargs):
        from morphforge.simulation.core.segmentation.cellsegmenter import DefaultCellSegementer
        
        
        

        self.simulation = simulation
        self.name = name if name else ObjectLabeller.getNextUnamedObjectName(Cell, 'AnonCell_')
        self.morphology = morphology 
        
        self.cellSegmenter = segmenter if segmenter else DefaultCellSegementer()
        self.cellSegmenter.connectToCell(self)
        
        
        self.biophysics = CellBiophysics()
    
        self.initial_voltage = initial_voltage or unit("-51:mV")
        
        
        self.cell_tags = cell_tags 
        
        if self.name:
            self.cell_tags = self.cell_tags +  [self.name]
 def reduce_to_variable_dt_trace(cls, original_trace, epsilon):
     assert isinstance(original_trace, Trace_PointBased)
     epsilon = unit(epsilon)
     
     
     time_units = original_trace._time.units
     time_data = original_trace._time.magnitude
     
     data_units = original_trace._data.units
     data_data = original_trace._data.magnitude
     
     ep = epsilon
     
     pts = zip(time_data.tolist(), data_data.tolist())
     
     
     newpts = simplify_points(pts, ep)     
     new_time, new_data = zip(*newpts)
     
     newTrace = Trace_VariableDT(np.array(new_time) * time_units, np.array(new_data) * data_units, name=original_trace.name, comment=original_trace.comment, tags=original_trace.tags)
     
     print 'Simplified from N=%d to N=%d' % (original_trace.getN(), newTrace.getN())
     return newTrace
Beispiel #16
0
    def __init__(
        self,
        dur1,
        amp1,
        dur2='0:ms',
        dur3='0:ms',
        amp2='0:mV',
        amp3='0:mV',
        rs='0.1:MOhm',
        **kwargs
        ):

        super(VoltageClampStepChange, self).__init__(**kwargs)

        self.dur1 = unit(dur1)
        self.dur2 = unit(dur2)
        self.dur3 = unit(dur3)

        self.amp1 = unit(amp1)
        self.amp2 = unit(amp2)
        self.amp3 = unit(amp3)
        self.rs = unit(rs)
    def reduce_to_variable_dt_trace(cls, original_trace, epsilon):
        assert isinstance(original_trace, TracePointBased)
        epsilon = unit(epsilon)

        time_units = original_trace.time_unit
        time_data = original_trace.time_pts_np

        data_units = original_trace.data_unit
        data_data = original_trace.data_pts_np

        pts = zip(time_data.tolist(), data_data.tolist())

        newpts = _simplify_points(pts, epsilon)
        (new_time, new_data) = zip(*newpts)

        new_trace = TraceVariableDT(np.array(new_time) * time_units,
                                    np.array(new_data) * data_units,
                                    name=original_trace.name,
                                    comment=original_trace.comment,
                                    tags=original_trace.tags)

        print 'Simplified from N=%d to N=%d' % (original_trace.get_n(),
                                                new_trace.get_n())
        return new_trace
 def get_unit(self):
     return unit('')
Beispiel #19
0
 def get_unit(self):
     return unit('nA')
Beispiel #20
0
 def __init__(self, amp, dur, delay, **kwargs):
     super(CurrentClampStepChange, self).__init__(**kwargs)
     self.amp = unit(amp)
     self.dur = unit(dur)
     self.delay = unit(delay)
Beispiel #21
0
 def __init__(self, amp, dur, delay, **kwargs):
     super(CurrentClampStepChange, self).__init__(**kwargs)
     self.amp = unit(amp)
     self.dur = unit(dur)
     self.delay = unit(delay)
Beispiel #22
0
def get_sample_lk(env):
    lk_chl = env.Channel(StdChlLeak, name='LkChl',
            conductance=unit('0.3:mS/cm2'),
            reversalpotential=unit('-54.3:mV') )

    return lk_chl
        t_m = t_marker.match(st)
        if not t_m:
            assert False, "Can't parse: %s" % st

        g = t_m.groupdict()
        (t0, t1, d0, d1) = (g['t0'], g['t1'], g['d0'], g['d1'])
        t0 = (int(t0) * xunit if t0 else None)
        t1 = (int(t1) * xunit if t1 else None)
        d0 = (int(d0) * yunit if d0 else None)
        d1 = (int(d1) * yunit if d1 else None)
        return LevelSelector(data_selector=DataSelector(d0, d1),
                             time_selector=TimeSelector(t0, t1))



l1 = TracePiecewise(pieces = [
                                TracePieceFunctionFlat(time_window=(0, 50)*pq.ms, x=unit("0:pA")),
                                TracePieceFunctionFlat(time_window=(50, 150)*pq.ms, x=unit("110:pA")),
                                TracePieceFunctionFlat(time_window=(150, 350)*pq.ms, x=unit("0:pA")),
                                   ])



sel1 = LevelSelectorGroup(" A, { 10:65 @ -1:1 }, B, { 10: @ 90:111 }, C", xunit=unit("ms"), yunit=unit("pA"))

matches = sel1.matchall(l1)
for m in matches:
    print m

            marker = r_m.groupdict()['name']
            return LevelToken(symbol=marker)

        t_m = t_marker.match(st)
        if not t_m:
            assert False, "Can't parse: %s" % st

        g = t_m.groupdict()
        (t0, t1, d0, d1) = (g['t0'], g['t1'], g['d0'], g['d1'])
        t0 = (int(t0) * xunit if t0 else None)
        t1 = (int(t1) * xunit if t1 else None)
        d0 = (int(d0) * yunit if d0 else None)
        d1 = (int(d1) * yunit if d1 else None)
        return LevelSelector(data_selector=DataSelector(d0, d1),
                             time_selector=TimeSelector(t0, t1))


l1 = TracePiecewise(pieces=[
    TracePieceFunctionFlat(time_window=(0, 50) * pq.ms, x=unit("0:pA")),
    TracePieceFunctionFlat(time_window=(50, 150) * pq.ms, x=unit("110:pA")),
    TracePieceFunctionFlat(time_window=(150, 350) * pq.ms, x=unit("0:pA")),
])

sel1 = LevelSelectorGroup(" A, { 10:65 @ -1:1 }, B, { 10: @ 90:111 }, C",
                          xunit=unit("ms"),
                          yunit=unit("pA"))

matches = sel1.matchall(l1)
for m in matches:
    print m