def __init__(self, name, conductance, reversalpotential, mechanism_id=None): if not mechanism_id: mechanism_id = "StdLeakChl" MembraneMechanism.__init__(self, mechanism_id=mechanism_id) self.name = name self.conductance = unit(conductance) self.reversalpotential = unit(reversalpotential)
def __getitem__(self, time): if isinstance(time, tuple): assert len(time) == 2 start = unit(time[0]) stop = unit(time[1]) if start < self._time[0]: assert False, 'Time out of bounds' if stop > self._time[-1]: assert False, 'Time out of bounds' #print start #print stop mask = np.logical_and((start < self._time), (self._time < stop)) #print np.nonzero(mask)[0] if len(np.nonzero(mask)[0]) < 2: assert False return Trace_FixedDT(time=self._time[ np.nonzero(mask)[0] ], data=self._data[ np.nonzero(mask)[0] ] ) assert isinstance(time, pq.quantity.Quantity), "Times Shoudl be quanitity. Found: %s %s"%(time, type(time) ) # Rebase the Time: time.rescale(self._time.units) interpolator = interp1d(self._time.magnitude, self._data.magnitude) dMag = interpolator(time.magnitude) return dMag * self._data.units
def plot_curve(cls, ax, curve, chl, state, infpower=None, *args, **kwargs): V = np.linspace(-80,50)*unit('mV') #V = StdLimits.get_default_voltage_array().rescale('mV') (alpha, beta) = chl.get_alpha_beta_at_voltage(V, state) (inf, tau) = InfTauCalculator.alpha_beta_to_inf_tau(alpha, beta) infpower = (np.power(inf, infpower) if infpower else None) plot_what_lut = { Curve.Alpha: (alpha, 'Rate Constant', None), Curve.Beta: (beta, 'Rate Constant', None), Curve.Inf: (inf, 'Steady-State', None), Curve.InfPowered: (infpower, 'Steady-State', None), Curve.Tau: (tau, 'Time-Constant', 'ms'), } (plot_what, y_label, y_unit) = plot_what_lut[curve] # print kwargs if isinstance(ax, QuantitiesAxisNew): ax.plot(V, plot_what, *args, **kwargs) ax.set_xlabel('Voltage') ax.set_ylabel(y_label) if y_unit: ax.set_yunit(unit(y_unit)) else: ax.plot(V, plot_what, *args, **kwargs) ax.set_xlabel('Voltage (mV)') ax.set_ylabel(y_label)
def __init__(self, name, ion, equation, conductance, reversalpotential, mechanism_id, statevars={}): MembraneMechanism.__init__(self, mechanism_id=mechanism_id) self.name = name self.ion = ion self.eqn = equation self.conductance = unit(conductance) self.statevars = dict([ (s, (sDict['alpha'], sDict['beta'])) for s, sDict in statevars.iteritems()]) self.reversalpotential = unit(reversalpotential)
def __init__(self, ion, equation, conductance, reversalpotential, statevars_new={}, **kwargs): super(MM_InfTauInterpolatedChannel, self).__init__(**kwargs) self.ion = ion self.eqn = equation self.conductance = unit(conductance) self.reversalpotential = unit(reversalpotential) self.statevars_new = statevars_new.copy()
def getDefaults(cls): defs = { NeuronSimulationSettings.dt: unit("0.01:ms"), NeuronSimulationSettings.tstop: unit("500:ms"), NeuronSimulationSettings.cvode: True } # Check we have defaults for all parameters: for p in NeuronSimulationSettings.allparams: assert p in defs return defs
def get_defaults(cls): defs = {NEURONSimulationSettings.dt: unit('0.01:ms'), NEURONSimulationSettings.tstop: unit('500:ms'), NEURONSimulationSettings.cvode: True} # Check we have defaults for all parameters: for parameter in NEURONSimulationSettings.allparams: assert parameter in defs return defs
def linspace(cls, start, stop, num, endpoint=True): start = unit(start) stop = unit(stop) # Lets us the same base unit: stop = 1.0 * stop stop.units = start.units vals = np.linspace(start.magnitude, stop.magnitude, num=num, endpoint=endpoint) return vals * start.units
def linspace(cls, start, stop, num, endpoint=True): from morphforge.core.quantities import unit start = unit(start) stop = unit(stop) # Lets us the same base unit: stop = 1.0 * stop stop.units = start.units vals = np.linspace(start.magnitude, stop.magnitude, num=num, endpoint=endpoint) return vals * start.units
def get_defaults(cls): defs = { NEURONSimulationSettings.dt: unit('0.01:ms'), NEURONSimulationSettings.tstop: unit('500:ms'), NEURONSimulationSettings.cvode: True } # Check we have defaults for all parameters: for parameter in NEURONSimulationSettings.allparams: assert parameter in defs return defs
def arange(cls, start, stop, step): # print start, stop, step start = unit(start) stop = unit(stop) step = unit(step) # Lets us the same base unit: stop = 1.0 * stop step = 1.0 * step stop.units = start.units step.units = start.units vals = np.arange(start.magnitude, stop.magnitude, step=step.magnitude) return vals * start.units
def __init__(self, name, ion, equation, conductance, reversalpotential, statevars=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 = unit(conductance) self.statevars = dict([(s, (sDict['alpha'], sDict['beta'])) for s, sDict in statevars.iteritems()]) self.reversalpotential = unit(reversalpotential) self.conductance = self.conductance.rescale('S/cm2') self.reversalpotential = self.reversalpotential.rescale('mV')
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 = unit(conductance) self.beta2threshold = unit(beta2threshold) self.statevars = dict( [(s, (sDict["alpha"], sDict["beta1"], sDict["beta2"])) for s, sDict in statevars.iteritems()] ) self.reversalpotential = unit(reversalpotential)
def arange(cls, start, stop, step): #print start, stop, step start = unit(start) stop = unit(stop) step = unit(step) # Lets us the same base unit: stop = 1.0 * stop step = 1.0 * step stop.units = start.units step.units = start.units vals = np.arange(start.magnitude, stop.magnitude, step=step.magnitude) return vals * start.units
def arange(cls, start, stop, step): from morphforge.core.quantities import unit start = unit(start) stop = unit(stop) step = unit(step) # Lets us the same base unit: stop = 1.0 * stop step = 1.0 * step stop.units = start.units step.units = start.units vals = np.arange(start.magnitude, stop.magnitude, step=step.magnitude) return vals * start.units
def __init__(self, name, ion, equation, conductance, reversalpotential, statevars, beta2threshold, mechanism_id): MembraneMechanism.__init__(self, mechanism_id=mechanism_id) self.name = name self.ion = ion self.eqn = equation self.conductance = unit(conductance) self.beta2threshold = unit(beta2threshold) self.statevars = dict( [(s, (sDict["alpha"], sDict["beta1"], sDict["beta2"])) for s, sDict in statevars.iteritems()] ) self.reversalpotential = unit(reversalpotential)
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 = unit(conductance) self.beta2threshold = unit(beta2threshold) self.statevars = dict([(s, (sDict['alpha'], sDict['beta1'], sDict['beta2'])) for s, sDict in statevars.iteritems()]) self.reversalpotential = unit(reversalpotential)
def PlotCurve(cls, ax, curve, chl, state, infpower=None, *args, **kwargs): V = StdLimits.getDefaultVoltageArray().rescale("mV") alpha,beta = chl.getAlphaBetaAtVoltage(V, state) inf,tau = InfTauCalculator.AlphaBetaToInfTau(alpha,beta) infpower = np.power(inf, infpower) if infpower else None plot_what_LUT = { Curve.Alpha : ( alpha, "Rate Constant", None ), Curve.Beta : ( beta, "Rate Constant", None ), Curve.Inf : ( inf, "Steady-State", None ), Curve.InfPowered :( infpower, "Steady-State", None ), Curve.Tau : ( tau, "Time-Constant", "ms" ), } plot_what, y_label, y_unit = plot_what_LUT[curve] #print kwargs if isinstance(ax, QuantitiesAxisNew): ax.plot(V,plot_what, *args,**kwargs) ax.set_xlabel("Voltage") ax.set_ylabel(y_label) if y_unit: ax.set_yunit( unit(y_unit) ) else: ax.plot(V,plot_what, *args,**kwargs) ax.set_xlabel("Voltage (mV)") ax.set_ylabel(y_label)
def summarise_Overview(self): from reportlab.platypus import Paragraph, Table, PageBreak localElements = [] localElements.append( Paragraph("Overview", self.reportlabconfig.styles['Heading1'] ) ) # Cells: ######## localElements.append( Paragraph("Cells", self.reportlabconfig.styles['Heading2'] ) ) tableHeader = ['Cell', 'Total Surface Area', 'Sections', 'Segments','Active Channels (id,[Name])'] data = [tableHeader, ] for cell in self.simulation.getCells(): a = sum([ s.getArea() for s in cell.morphology]) * unit("1:um2") nSections = len( cell.morphology ) nSegments = sum( [cell.getSegmenter().getNumSegments(section) for section in cell.morphology] ) activeMechs = cell.getBiophysics().getAllMechanismsAppliedToCell() activeChlList = "\n".join( ["%s [%s]"%(am.getMechanismID(), am.name) for am in activeMechs] ) data.append( [ cell.name, a, nSections, nSegments, activeChlList ] ) localElements.append( Table(data, style=self.reportlabconfig.defaultTableStyle) ) # Stimulae: CC ############### if self.simulation.getCurrentClamps(): localElements.append( Paragraph("Current Clamps", self.reportlabconfig.styles['Heading2'] ) ) tableHeader = ['Name', 'Location', 'Delay', 'Amplitude', 'Duration'] data = [tableHeader, ] for cc in self.simulation.getCurrentClamps(): cellname = cc.celllocation.cell.name data.append( [ cc.name, cellname, cc.delay, cc.amp, cc.dur ] ) localElements.append( Table(data, style=self.reportlabconfig.defaultTableStyle) ) # Stimulae: VC ############### if self.simulation.getVoltageClamps(): localElements.append( Paragraph("Voltage Clamps", self.reportlabconfig.styles['Heading2'] ) ) tableHeader = ['Name', 'Location', 'Dur1', 'Dur2', 'Dur3', 'Amp1','Amp2','Amp3'] data = [tableHeader, ] for vc in self.simulation.getVoltageClamps(): cellname = vc.celllocation.cell.name data.append( [ vc.name, cellname, vc.dur1, vc.dur2, vc.dur3, vc.amp1, vc.amp2, vc.amp3 ] ) localElements.append( Table(data, style=self.reportlabconfig.defaultTableStyle) ) # Finish Up: localElements.append( PageBreak() ) return localElements
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 = unit(permeability) self.intracellular_concentration = unit(intracellular_concentration) self.extracellular_concentration = unit(extracellular_concentration) self.eqn = equation self.statevars = dict([(s, (sDict['alpha'], sDict['beta1'], sDict['beta2'])) for s, sDict in statevars.iteritems()]) self.beta2threshold = unit(beta2threshold) self.F = unit('96485.3365:C/mol') self.R = unit('8.314421:J/(K mol)') self.CaZ = unit('2:') self.T = unit(temperature)
class TraceMethodCtrl(object): registered_methods = {} # A list of method names that can be used for anytrace # if a specific method is not available for a type of trace fallback_to_fixedtrace_methods = {} default_fallback_resolution = unit('0.1:ms') @classmethod def register(cls, trace_cls, method_name, method_functor, can_fallback_to_fixed_trace=False, fallback_resolution=None): # print 'Registering method', trace_cls, method_name key = (trace_cls, method_name) assert not key in cls.registered_methods cls.registered_methods[key] = method_functor # Can we fallback to fixed_dt traces to use this operation if can_fallback_to_fixed_trace: fallback_resolution = fallback_resolution or cls.default_fallback_resolution assert trace_cls == TraceFixedDT cls.fallback_to_fixedtrace_methods[method_name] = fallback_resolution @classmethod def has_method(cls, trace_cls, method_name): if (trace_cls, method_name) in cls.registered_methods: return True if method_name in cls.fallback_to_fixedtrace_methods: return True return False @classmethod def get_method(cls, trace_cls, method_name): key = (trace_cls, method_name) if key in cls.registered_methods: return cls.registered_methods[key] # Fallback to FixedDT if method_name in cls.fallback_to_fixedtrace_methods: method = cls.registered_methods[(TraceFixedDT, method_name)] dt = cls.fallback_to_fixedtrace_methods[method_name] return _prepend_conversion_to_fixed_trace_to_function(method, fixed_trace_dt=dt) # Error! assert False
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 = unit(permeability) self.intracellular_concentration = unit(intracellular_concentration) self.extracellular_concentration = unit(extracellular_concentration) self.eqn = equation self.statevars = dict([(s, (sDict['alpha'], sDict['beta1'], sDict['beta2'])) for s, sDict in statevars.iteritems()]) self.beta2threshold = unit(beta2threshold) self.F = unit('96485.3365:C/mol') self.R = unit('8.314421:J/(K mol)') self.CaZ = unit('2:') self.T = unit(temperature)
def get_voltage_clamp_trace(cls, V, chl, duration, cell_area, t=np.arange(0, 300, 0.1) * unit("1:ms")) : from scipy.integrate import odeint import sympy v_in_mv = V.rescale('mV').magnitude state_names = chl.statevars.keys() n_states = len(state_names) (m_inf, m_tau) = InfTauCalculator.evaluate_inf_tau_for_v(chl.statevars[state_names[0]], V) m_tau_ms = m_tau.rescale('ms').magnitude inf_taus = [InfTauCalculator.evaluate_inf_tau_for_v(chl.statevars[stateName], V) for stateName in state_names] inf_taus_ms = [(inf, tau.rescale("ms").magnitude) for (inf, tau) in inf_taus] state_to_index = dict([(state, index) for state, index in enumerate(state_names)]) def odeFunc(y, t0): res = [None] * n_states for i in range(0, n_states): state_inf, state_tau = inf_taus_ms[i] state_val = y[i] d_state = (state_inf - state_val) / state_tau res[i] = d_state return res # run the ODE for each variable: t = t.rescale('ms').magnitude y0 = np.zeros((n_states)) res = odeint(func=odeFunc, y0=y0, t=t) state_functor = sympy.lambdify(state_names, sympy.sympify(chl.eqn)) state_data = [res[:, i] for i in range(0, n_states)] state_equation_evaluation = state_functor(*state_data) cell_density = chl.conductance * cell_area i_chl = chl.conductance * cell_area * state_equation_evaluation * (V - chl.reversalpotential) return TraceFixedDT(time=t * unit('1:ms'), data=i_chl.rescale('pA'))
def get_voltage_clamp_trace(cls, V, chl, duration, cell_area, t=np.arange(0, 300, 0.1) * unit("1:ms")): from scipy.integrate import odeint import sympy v_in_mv = V.rescale("mV").magnitude state_names = chl.statevars.keys() n_states = len(state_names) (m_inf, m_tau) = InfTauCalculator.evaluate_inf_tau_for_v(chl.statevars[state_names[0]], V) m_tau_ms = m_tau.rescale("ms").magnitude inf_taus = [InfTauCalculator.evaluate_inf_tau_for_v(chl.statevars[stateName], V) for stateName in state_names] inf_taus_ms = [(inf, tau.rescale("ms").magnitude) for (inf, tau) in inf_taus] state_to_index = dict([(state, index) for state, index in enumerate(state_names)]) def odeFunc(y, t0): res = [None] * n_states for i in range(0, n_states): state_inf, state_tau = inf_taus_ms[i] state_val = y[i] d_state = (state_inf - state_val) / state_tau res[i] = d_state return res # run the ODE for each variable: t = t.rescale("ms").magnitude y0 = np.zeros((n_states)) res = odeint(func=odeFunc, y0=y0, t=t) state_functor = sympy.lambdify(state_names, sympy.sympify(chl.eqn)) state_data = [res[:, i] for i in range(0, n_states)] state_equation_evaluation = state_functor(*state_data) cell_density = chl.conductance * cell_area i_chl = chl.conductance * cell_area * state_equation_evaluation * (V - chl.reversalpotential) return TraceFixedDT(time=t * unit("1:ms"), data=i_chl.rescale("pA"))
def getVoltageClampTrace(cls, V, chl, duration, cellArea, t=np.arange(0,300,0.1) * unit("1:ms"), ) : from scipy.integrate import odeint vInMv = V.rescale("mV").magnitude stateNames = chl.statevars.keys() nStates = len(stateNames) m_inf, m_tau = InfTauCalculator.evaluateInfTauForV( chl.statevars[stateNames[0]], V) m_tauMS = m_tau.rescale("ms").magnitude infTaus = [ InfTauCalculator.evaluateInfTauForV( chl.statevars[stateName], V) for stateName in stateNames ] infTausMS = [ (inf, tau.rescale("ms").magnitude) for (inf,tau) in infTaus ] stateToIndex = dict( [ (state,index) for state,index in enumerate(stateNames) ] ) def odeFunc(y,t0): res = [None] * nStates for i in range(0,nStates): stateInf,stateTau = infTausMS[i] stateVal = y[i] dState = ( stateInf - stateVal ) / stateTau res[i] = dState return res # Run the ODE for each variable: t = t.rescale("ms").magnitude y0 = np.zeros( (nStates, ) ) res = odeint(func=odeFunc, y0=y0, t= t ) stateFunctor = sympy.lambdify( stateNames, sympy.sympify(chl.eqn) ) stateData = [ res[:,i] for i in range(0,nStates) ] stateEquationEvaluation = stateFunctor( *stateData ) cellDensity = (chl.conductance * cellArea) iChl = (chl.conductance * cellArea) * stateEquationEvaluation * (V- chl.reversalpotential) return Trace_FixedDT( time=t * unit("1:ms"), data=iChl.rescale("pA") )
def build_voltageclamp_soma_simulation(env, V, mech_builder, morphology): sim = env.Simulation(name='SimXX') cell = sim.create_cell(name='Cell1', morphology=morphology) cell.apply_channel( channel=mech_builder(env=sim.environment)) sim.record( cell, what=cell.Recordables.MembraneVoltage, name='SomaVoltage' , cell_location=cell.soma) vc = sim.create_voltageclamp( name='Stim1', amp1=unit('-81.5:mV'), amp2=unit(V), amp3=unit('-81.5:mV'), dur1=unit('100:ms'), dur2=unit('100:ms'), dur3=unit('100:ms'), cell_location=cell.soma, ) sim.record(vc, what=vc.Recordables.Current, name='VCCurrent') return sim
def build_voltageclamp_soma_simulation(env, V, mech_builder, morphology): sim = env.Simulation(name='SimXX') cell = sim.create_cell(name='Cell1', morphology=morphology) cell.apply_channel(channel=mech_builder(env=sim.environment)) sim.record(cell, what=cell.Recordables.MembraneVoltage, name='SomaVoltage', cell_location=cell.soma) vc = sim.create_voltageclamp( name='Stim1', amp1=unit('-81.5:mV'), amp2=unit(V), amp3=unit('-81.5:mV'), dur1=unit('100:ms'), dur2=unit('100:ms'), dur3=unit('100:ms'), cell_location=cell.soma, ) sim.record(vc, what=vc.Recordables.Current, name='VCCurrent') return sim
def get_unit(self): return unit('nA')
def get_unit(self): return unit('uS')
def generate_ramp(cls, value_start, value_stop, time_start=unit('0:ms'), time_stop=unit('100:ms'), npoints=200): return Trace_FixedDT( NpPqWrappers.linspace(time_start, time_stop, num=npoints), NpPqWrappers.linspace(value_start, value_stop, num=npoints) )
def get_unit(self): return unit('mV')
def get_prefered_units(self): return {'gScale': pq.dimensionless, 'pca': unit('cm/sec')}
def generate_flat(cls, value, time_start=unit('0:ms'), time_stop=unit('100:ms'), npoints=200): return Trace_FixedDT( NpPqWrappers.linspace(time_start, time_stop, num=npoints), np.ones(npoints) * unit(value), )
def __init__(self, conductance, reversalpotential, **kwargs): super(StdChlLeak, self).__init__(**kwargs) self.conductance = unit(conductance) self.reversalpotential = unit(reversalpotential)
def getUnit(self): return unit("nA")
def p_unit_definiton(p): """ unit_def : CURLY_LBRACE D COLON ID CURLY_RBRACE """ p[0] = unit(p[4])
def get_unit(self): return unit('ms')
def get_defaults(self): return {'gBar': self.conductance, 'e_rev': self.reversalpotential, 'gScale': unit('1.0')}
def get_defaults(self): return {'gScale': unit('1.0'), 'pca': self.permeability}
def get_unit(self): return unit('1')
def getUnit(self): return unit("S/cm2")
def getUnit(self): return unit("ms")
def get_unit(self): return unit('S/cm2')
class NeuronSimulationConstants(object): TimeVectorName = 'rect' TimeUnit = unit('1:ms')
def get_voltage_clamp_trace(cls, V, chl, duration, cell_area, t=np.arange(0, 300, 0.1) * unit("1:ms")) : raise NotImplementedError()