def set_ylim(self, *args, **kwargs):
        x0 = x1 = None
        if args is not None:
            if len(args) == 1:
                x0, x1 = args[0]
            else:
                x0, x1 = args
        else:
            x0 = kwargs.get('bottom', None)
            x1 = kwargs.get('top', None)

        # So we can forward arguments:
        if 'bottom' in kwargs:
            del kwargs['bottom']
        if 'top' in kwargs:
            del kwargs['top']

        #Convert strings to units
        if x0 is not None and isinstance(x0, basestring):
            x0 = qty(x0)
        if x1 is not None and isinstance(x1, basestring):
            x1 = qty(x1)


        # Are the baseunits set? If not, then lets set them:
        if self.xyUnitBase[1] is None:
            self._setxyUnitDisplay(unitY=x0)

        # Set the limits
        if x0 is not None:
            self.ax.set_ylim(bottom = x0.rescale(self.xyUnitBase[1]).magnitude, **kwargs)
        if x1 is not None:
            self.ax.set_ylim(top =  x1.rescale(self.xyUnitBase[1]).magnitude, **kwargs)
    def __getitem__(self, time):
        from scipy.interpolate import interp1d
        from morphforge.traces.tracetypes.tracefixeddt import TraceFixedDT

        if isinstance(time, tuple):
            assert len(time) == 2
            start = qty(time[0])
            stop = qty(time[1])

            if start < self._time[0]:
                assert False, 'Time out of bounds'
            if stop > self._time[-1]:
                assert False, 'Time out of bounds'

            mask = np.logical_and(start < self.time_pts, self._time < stop)

            if len(np.nonzero(mask)[0]) < 2:
                assert False
            return TraceFixedDT(time=self._time[np.nonzero(mask)[0]],
                                data=self.data_pts[np.nonzero(mask)[0]])


        assert isinstance(time, units.quantity.Quantity), "Times should be quantity. Found: %s %s"%(time, type(time))
        # Rebase the Time:
        time.rescale(self._time.units)
        interpolator = interp1d(self.time_pts_np,
                                self.data_pts_np)
        d_mag = interpolator(time.magnitude)
        return d_mag * self.data_unit
    def _setxyUnitDisplay(self, unitX=None, unitY=None):
        if unitX is not None:
            unitX = (qty(unitX) if isinstance(unitX, basestring) else unitX)
        if unitY is not None:
            unitY = (qty(unitY) if isinstance(unitY, basestring) else unitY)


        # Set the base units, if they are not already set:
        if unitX is not None and self.xyUnitBase[0] is None:
            self._setxyUnitBase(unitX=unitX)
        if unitY is not None and self.xyUnitBase[1] is None:
            self._setxyUnitBase(unitY=unitY)


        if unitX is not None:
            self.xyUnitDisplay[0] = unitX.units

            # Update the axis ticks:
            symbol = self.getSymbolFromUnit(self.xyUnitDisplay[0])
            scaling = (self.xyUnitBase[0]/self.xyUnitDisplay[0]).rescale(pq.dimensionless)
            xFormatterFunc = self.xTickFormatGenerator(scaling=scaling, symbol=symbol, ticklabel_quantisation=None)
            self.ax.xaxis.set_major_formatter(xFormatterFunc)

        if unitY is not None:

            self.xyUnitDisplay[1] = unitY.units

            symbol = self.getSymbolFromUnit(self.xyUnitDisplay[1])
            scaling = (self.xyUnitBase[1]/self.xyUnitDisplay[1]).rescale(pq.dimensionless)
            yFormatterFunc = self.yTickFormatGenerator(scaling=scaling, symbol=symbol, ticklabel_quantisation=None)
            self.ax.yaxis.set_major_formatter(yFormatterFunc)

        # Update the labels
        self._update_labels()
    def set_xlim(self, *args, **kwargs):
        x0 = x1 = None
        if args is not None:
            if len(args) == 1:
                x0, x1 =args[0]
            else:
                x0, x1 = args
        else:
            x0 = kwargs.get('left', None)
            x1 = kwargs.get('right', None)

        # So we can forward arguments:
        if 'left' in kwargs:
            del kwargs['left']
        if 'left' in kwargs:
            del kwargs['left']


        #
        if x0 is not None and isinstance(x0, basestring):
            x0 = qty(x0)
        if x1 is not None and isinstance(x1, basestring):
            x1 = qty(x1)

        # Are the baseunits set? If not, then lets set them:
        if self.xyUnitBase[0] is None:
            self._setxyUnitDisplay(unitX=x0)


        # Set the limits
        if x0 is not None:
            self.ax.set_xlim(left = x0.rescale(self.xyUnitBase[0]).magnitude, **kwargs)
        if x1 is not None:
            self.ax.set_xlim(right =  x1.rescale(self.xyUnitBase[0]).magnitude, **kwargs)
Exemple #5
0
    def __init__(self, equation, conductance, reversalpotential, statevars_new={}, **kwargs):
        super(MM_InfTauInterpolatedChannel, self).__init__(**kwargs)


        self.eqn = equation
        self.conductance = qty(conductance)
        self.reversalpotential = qty(reversalpotential)
        self.statevars_new = statevars_new.copy()
    def __init__(self, name, ion, equation, conductance, reversalpotential, statevars, beta2threshold, **kwargs):
        super(StdChlAlphaBetaBeta, self).__init__(name=name,  **kwargs)

        #self.name = name
        self.ion = ion
        self.eqn = equation
        self.conductance = qty(conductance)

        self.beta2threshold = qty(beta2threshold)

        self.statevars = dict([(s, (sDict['alpha'], sDict['beta1'], sDict['beta2'])) for s, sDict in statevars.iteritems()])
        self.reversalpotential = qty(reversalpotential)
Exemple #7
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=qty('36:mS/cm2'),
        reversalpotential=qty('-77:mV'),
        statevars=kStateVars,
        )
    return k_chl
    def _setxyUnitBase(self, unitX=None, unitY=None):
        if unitX is not None:
            unitX = (qty(unitX) if isinstance(unitX, basestring) else unitX)
        if unitY is not None:
            unitY = (qty(unitY) if isinstance(unitY, basestring) else unitY)

        if unitX is not None:
            assert self.xyUnitBase[0] == None
            unitX = (qty(unitX) if isinstance(unitX, basestring) else unitX)
            self.xyUnitBase[0] = unitX.units.simplified.units
        if unitY is not None:
            assert self.xyUnitBase[1] == None
            unitY = (qty(unitY) if isinstance(unitY, basestring) else unitY)
            self.xyUnitBase[1] = unitY.units.simplified.units
    def __init__(self, equation, conductance, reversalpotential, statevars=None, name=None, ion=None, **kwargs):
        super(StdChlAlphaBeta, self).__init__(name=name, **kwargs)
        # TODO: FIXED DEFAULT PARAMETER 'statevars'
        if statevars is None:
            statevars = {}
        
        self.ion = ion
        self.eqn = equation
        self.conductance = qty(conductance)
        self.statevars = dict([(s, (sDict['alpha'], sDict['beta'])) for s, sDict in statevars.iteritems()])
        self.reversalpotential = qty(reversalpotential)

        self.conductance = self.conductance.rescale('S/cm2')
        self.reversalpotential = self.reversalpotential.rescale('mV')
def main():
	l1 = TracePiecewise(pieces = [
		                            TracePieceFunctionFlat(time_window=(0, 50)*units.ms, x=qty("0:pA")),
		                            TracePieceFunctionFlat(time_window=(50, 150)*units.ms, x=qty("110:pA")),
		                            TracePieceFunctionFlat(time_window=(150, 350)*units.ms, x=qty("0:pA")),
		                               ])



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

	matches = sel1.matchall(l1)
	for m in matches:
		print m
    def reduce_to_variable_dt_trace(cls, original_trace, epsilon):
        assert isinstance(original_trace, TracePointBased)
        epsilon = qty(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
Exemple #12
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 qty('-51:mV')

        self.cell_tags = cell_tags

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

        self.population = None
    def get_defaults(cls):
        defs = {NEURONSimulationSettings.dt: qty('0.01:ms'),
                NEURONSimulationSettings.tstop: qty('500:ms'),
                NEURONSimulationSettings.reltol: 0.0,
                NEURONSimulationSettings.abstol: 1e-2,
                #NEURONSimulationSettings.reltol: 1e-12,
                #NEURONSimulationSettings.abstol: 1e-12,
                NEURONSimulationSettings.cvode: True,
                NEURONSimulationSettings.strict_modlunit: True,
                # This options automatically simplifies traces after recoding,
                # which can make intermediate files much smaller.
                NEURONSimulationSettings.simplify_traces: None
                }

        # Check we have defaults for all parameters:
        for parameter in NEURONSimulationSettings.allparams:
            assert parameter in defs

        return defs
Exemple #14
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=qty('120:mS/cm2'),
        reversalpotential=qty('50:mV'),
        statevars=na_state_vars, 
        )
        
    return na_chl
def _convert_to_unit(o, default_unit):

    assert not isinstance(default_unit, units.Quantity)

    if isinstance(o, units.Quantity):
        return o.rescale(default_unit)
    elif is_float(o) or is_int(o):
        return o * morphforge.units.parse_unit_str(default_unit)#.rescale(default_unit)
    elif isinstance(o, (str, unicode)) and ':' in o:
        return qty(o).rescale(default_unit)
    else:
        raise ValueError()
Exemple #16
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 = qty(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 = qty(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
def build_passive_cell(sim, input_resistance, capacitance=None, area=None, name=None, reversalpotential=None):
    import morphforgecontrib.stdimports as mfc

    env = sim.environment

    if area is None:
        area = qty('1000:um2')

    if capacitance is None:
        capacitance = qty('10:pF')

    if reversalpotential is None:
        reversalpotential = qty('-60:mV')

    lk = env.Channel( mfc.StdChlLeak,
            conductance = ((1/input_resistance) / area ),
            reversalpotential = reversalpotential,
            )

    cell = sim.create_cell(area=area, name=name, initial_voltage=reversalpotential)
    cell.apply_channel(lk)
    cell.set_passive(mf.PassiveProperty.SpecificCapacitance, capacitance / area)

    return cell
    def __init__(self, name, ion, equation, permeability, intracellular_concentration, extracellular_concentration, temperature, beta2threshold,  statevars, **kwargs):
        super( StdChlCalciumAlphaBetaBeta, self).__init__(name=name, **kwargs)

        self.ion = ion

        self.permeability = qty(permeability)
        self.intracellular_concentration = qty(intracellular_concentration)
        self.extracellular_concentration = qty(extracellular_concentration)

        self.eqn = equation
        self.statevars = dict([(s, (sDict['alpha'], sDict['beta1'], sDict['beta2'])) for s, sDict in statevars.iteritems()])
        self.beta2threshold = qty(beta2threshold)

        self.F = qty('96485.3365:C/mol')
        self.R = qty('8.314421:J/(K mol)')
        self.CaZ = qty('2.0:')
        self.T = qty(temperature)
Exemple #19
0
def build_hh_cell(sim, cell_area=None, name=None):
    
    if cell_area is None:
        cell_area = qty('5000:um2')
    
    morphology = MorphologyBuilder.get_single_section_soma(area = cell_area)
    cell = sim.create_cell(morphology=morphology,name=name)

    # 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
Exemple #20
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 = np.linspace(-80, 60, 10) * qty("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(units.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
def build_voltageclamp_soma_simulation(env, V, channel_functor, morphology):
    sim = env.Simulation(name='SimXX', cvode=False, dt= qty('0.01:ms'))
    cell = sim.create_cell(name='Cell1', morphology=morphology)

    cell.apply_channel( channel=channel_functor(env=sim.environment))


    sim.record( cell, what=cell.Recordables.MembraneVoltage, name='SomaVoltage' , cell_location=cell.soma)

    vc = sim.create_voltageclamp(
        name='Stim1',
        amp1=qty('-81.5:mV'),
        amp2=qty(V),
        amp3=qty('-81.5:mV'),
        dur1=qty('100:ms'),
        dur2=qty('100:ms'),
        dur3=qty('100:ms'),
        cell_location=cell.soma,
        )
    sim.record(vc, what=vc.Recordables.Current, name='VCCurrent')
    return sim
Exemple #22
0
    def __init__(
        self,
        dur1,
        amp1,
        dur2='0:ms',
        dur3='0:ms',
        amp2='0:mV',
        amp3='0:mV',
        rs='0.01:MOhm',
        **kwargs
        ):

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

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

        self.amp1 = qty(amp1)
        self.amp2 = qty(amp2)
        self.amp3 = qty(amp3)
        self.rs = qty(rs)
 def get_unit(self):
     return qty('')
def p_unit_definiton(p):
    """ unit_def : CURLY_LBRACE D COLON ID CURLY_RBRACE """
    p[0] = qty(p[4])
Exemple #25
0
    def __init__(
        self,
        srcs,
        plots=None,
        additional_plots=None,
        figtitle=None,
        fig_kwargs=None,
        show=True,
        linkage=None,
        timerange=None,
        mpl_tight_bounds=False,
        decimate_points=False,

        share_x_labels=True,

        nxticks=4,
        show_xlabel='only-once',
        show_xticklabels='only-once',
        show_xticklabels_with_units=True,
        show_xaxis_position='bottom',
        xticklabel_quantisation = False,
        xticks=None,
        xlabel='Time'
        ):

        self.xlabel = xlabel

        if fig_kwargs is None:
            fig_kwargs = self._default_fig_kwargs

        self.linkage = linkage
        self.decimate_points = decimate_points


        if not is_iterable(srcs):
            srcs = [srcs]

        # For each type of input (in 'srcs'); this should return a list of traces:
        self.all_trace_objs = []
        self.all_event_set_objs = []
        trace_extractors = {
            SimulationResult:   lambda obj: (self.all_trace_objs.extend(obj.traces),self.all_event_set_objs.extend(obj.evsets)),
            TraceFixedDT:       lambda obj: self.all_trace_objs.append(obj),
            TraceVariableDT:    lambda obj: self.all_trace_objs.append(obj),
            TracePiecewise:     lambda obj: self.all_trace_objs.append(obj),
            EventSet:           lambda obj: self.all_event_set_objs.append(obj)
                            }

        for obj in srcs:
            tr_extractor = trace_extractors[type(obj)]
            tr_extractor(obj)

        # Use the new PlotSpec architecture:
        # Filter out which plots are actually going to display something,
        # and filter out the rest:
        plots = plots if plots is not None else TagViewer._default_plot_specs

        if additional_plots:
            plots = tuple(list(plots) + list(additional_plots))

        self.plot_specs = [plotspec for plotspec in plots if
                            [tr for tr in self.all_trace_objs if plotspec.addtrace_predicate(tr)] or  \
                            [evset for evset in self.all_event_set_objs if plotspec.addeventset_predicate(evset)] \
                          ]


        self.fig_kwargs = fig_kwargs
        self.figtitle = figtitle
        self.mpl_tight_bounds = mpl_tight_bounds

        self.timerange = timerange
        #self.share_x_labels = share_x_labels
        self.nxticks = nxticks


        # X-axis configuration:
        self.show_xlabel = show_xlabel
        self.show_xticklabels = show_xticklabels
        self.show_xticklabels_with_units = show_xticklabels_with_units
        self.show_xaxis_position = show_xaxis_position
        #self.xticks_as_ints = xticks_as_ints
        self.xticklabel_quantisation = xticklabel_quantisation
        self.xticks=xticks
        assert self.show_xlabel in self._options_show_xlabel, 'Invalid'
        assert self.show_xticklabels in self._options_show_xticklabels, 'Invalid: %s' % show_xticklabels
        assert self.show_xticklabels_with_units in self._options_show_xticklabels_with_units
        assert self.show_xaxis_position in self._options_show_xaxis_position
        if is_iterable( self.xticks ) and all( [isinstance(xtick, (int, float)) for xtick in self.xticks]):
            self.xticks = [ xtick*units.ms for xtick in self.xticks]
        assert self.xticks is None or isinstance(self.xticks, int) or ( is_iterable(self.xticks) and [ qty(xtick) for xtick in self.xticks] )


        self.fig = None
        self.subaxes = []
        self.create_figure()


        if TagViewer.MPL_AUTO_SHOW and show:
            import pylab
            pylab.show()
Exemple #26
0
def get_sample_lk(env):
    lk_chl = env.Channel(StdChlLeak, name='LkChl',
            conductance=qty('0.3:mS/cm2'),
            reversalpotential=qty('-54.3:mV') )

    return lk_chl
Exemple #27
0
    def __init__(self, conductance, reversalpotential, **kwargs):

        super(StdChlLeak, self).__init__(**kwargs)
        self.conductance = qty(conductance)
        self.reversalpotential = qty(reversalpotential)
 def get_defaults(self):
     return {'gBar': self.conductance,
             'e_rev': self.reversalpotential, 
             'gScale': qty('1.0')}
 def get_unit(self):
     return qty('S/cm2')
Exemple #30
0
 def __init__(self, amp, dur, delay, **kwargs):
     super(CurrentClampStepChange, self).__init__(**kwargs)
     self.amp = qty(amp)
     self.dur = qty(dur)
     self.delay = qty(delay)