コード例 #1
0
def make_cell(sim, cell_name, cell_chl_functor):
    m1 = mf.MorphologyBuilder.get_single_section_soma(area=mf.unit("1:um2"))
    cell = sim.create_cell(name=cell_name, morphology=m1)
    for chl in cell_chl_functor():
        cell.apply_channel( chl, parameter_multipliers={'gmax':random.uniform(0.9, 1.1)})
    cell.set_passive( mf.PassiveProperty.SpecificCapacitance, mf.unit('4:pF/um2'))
    return cell
コード例 #2
0
    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):
            from morphforge.stdimports import unit
            x0 = unit(x0)
        if x1 is not None and isinstance(x1, basestring):
            from morphforge.stdimports import unit
            x1 = unit(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)
コード例 #3
0
    def _setxyUnitDisplay(self, unitX=None, unitY=None):
        from morphforge.stdimports import unit
        if unitX is not None:
            unitX = (unit(unitX) if isinstance(unitX, basestring) else unitX)
        if unitY is not None:
            unitY = (unit(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)
            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)
            self.ax.yaxis.set_major_formatter(yFormatterFunc)

        # Update the labels
        self._update_labels()
コード例 #4
0
    def simulate(self, current_base, current_rebound):

        sim = self.env.Simulation(**self.sim_kwargs)
        cell = self.cell_functor(sim=sim)

        soma_loc = cell.get_location('soma')

        cc1 = sim.create_currentclamp(name="cclamp", amp=current_base, dur="100:ms", delay="50:ms", cell_location=soma_loc)
        cc2 = sim.create_currentclamp(name="cclamp2", amp=-1*current_rebound, dur="5:ms", delay="80:ms", cell_location=soma_loc)
        cc3 = sim.create_currentclamp(name="cclamp3", amp=-1*current_rebound, dur="5:ms", delay="120:ms", cell_location=soma_loc)

        sim.record(cc1, name="Current1",      what=CurrentClamp.Recordables.Current,  description="CurrentClampCurrent")
        sim.record(cc2, name="Current2",      what=CurrentClamp.Recordables.Current,  description="CurrentClampCurrent")
        sim.record(cc3, name="Current3",      what=CurrentClamp.Recordables.Current,  description="CurrentClampCurrent")

        sim.record(cell, name="SomaVoltage", cell_location=soma_loc,  what=Cell.Recordables.MembraneVoltage,  description="Response to iInj1=%s iInj2=%s"%(current_base, current_rebound))

        res = sim.run()


        #SimulationSummariser(res, "/home/michael/Desktop/ForRoman.pdf")

        i = res.get_trace('Current1').convert_to_fixed(unit("0.5:ms")) + res.get_trace('Current2').convert_to_fixed(unit("0.5:ms")) + res.get_trace('Current3').convert_to_fixed(unit("0.5:ms"))

        i = TraceConverter.rebase_to_fixed_dt(res.get_trace('Current1'
               ), dt=unit('0.5:ms')) \
            + TraceConverter.rebase_to_fixed_dt(res.get_trace('Current2'
               ), dt=unit('0.5:ms')) \
            + TraceConverter.rebase_to_fixed_dt(res.get_trace('Current3'
               ), dt=unit('0.5:ms'))
        i.tags = [StandardTags.Current]
        return (res.get_trace('SomaVoltage'), i)
コード例 #5
0
    def plot_iv_curve(self, ax=None):
        # pylint: disable=E1103
        title = '%s: IV Curve' % (self.cell_description or None)
        if not ax:
            f = QuantitiesFigure()
            f.suptitle(title)
            ax = f.add_subplot(1, 1, 1)
            ax.set_xlabel('Injected Current')
            ax.set_ylabel('SteadyStateVoltage')

        V_in_mV = [
            self.get_iv_point_steaddy_state(c).rescale('mV').magnitude
            for c in self.currents
        ]
        v = np.array(V_in_mV) * pq.mV
        i = factorise_units_from_list(self.currents)

        low_v = V_in_mV < self.v_regressor_limit if self.v_regressor_limit else range(
            len(V_in_mV))

        print 'i[low_v]', i[low_v]
        print 'v[low_v]', v[low_v]
        ax.plot(
            i[low_v],
            v[low_v],
        )
        ax.plot(
            i[np.logical_not(low_v)],
            v[np.logical_not(low_v)],
        )
        ax.plot(
            i[np.logical_not(low_v)],
            v[np.logical_not(low_v)],
        )

        # Plot the regressor:
        i_units = unit('1:pA').units
        v_units = unit('1:mV').units
        iv = np.vstack(
            (i.rescale(i_units).magnitude, v.rescale(v_units).magnitude)).T

        if not len(iv[low_v, 0]):
            return
        (a_s, b_s, r, tt, stderr) = stats.linregress(iv[low_v, 0], iv[low_v,
                                                                      1])
        input_resistance = (a_s * (v_units / i_units)).rescale('MOhm')
        reversal_potential = b_s * v_units

        self.input_resistance = input_resistance
        self.reversal_potential = reversal_potential

        ax.plot(
            i,
            i * input_resistance + reversal_potential,
            label="Fit: [V(mV) = %2.3f * I(pA)  + %2.3f]" % (a_s, b_s) +
            " \n[Input Resistance: %2.2fMOhm  Reversal Potential: %2.2f mV" %
            (input_resistance, reversal_potential))
        ax.legend()

        PM.save_figure(figname=title)
コード例 #6
0
    def __init__(self,
                 cell_functor,
                 currents,
                 cell_description=None,
                 sim_functor=None,
                 v_regressor_limit=None,
                 sim_kwargs=None,
                 plot_all=False):
        self.cell_functor = cell_functor
        self.v_regressor_limit = v_regressor_limit
        #Previously = unit("-30:mV")

        self.sim_kwargs = sim_kwargs or {}

        self.tCurrentInjStart = unit('50:ms')
        self.tCurrentInjStop = unit('200:ms')

        self.tSteaddyStateStart = unit('100:ms')
        self.tSteaddyStateStop = unit('151:ms')

        self.traces = {}

        self.currents = currents
        self.cell_description = cell_description or 'Unknown Cell'

        self.input_resistance = unit('-1:MOhm')

        if plot_all:
            self.plot_all()
コード例 #7
0
def build_presynaptic_mech( env, cell):
    return env.PreSynapticMechanism(
                mfc.PreSynapticMech_VoltageThreshold,
                cell_location = cell.soma,
                voltage_threshold = mf.unit("0:mV"),
                delay = mf.unit("1:ms"),
                #,
               )
コード例 #8
0
    def _setxyUnitBase(self, unitX=None, unitY=None):
        from morphforge.stdimports import unit
        if unitX is not None:
            unitX = (unit(unitX) if isinstance(unitX, basestring) else unitX)
        if unitY is not None:
            unitY = (unit(unitY) if isinstance(unitY, basestring) else unitY)

        if unitX is not None:
            assert self.xyUnitBase[0] == None
            unitX = (unit(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 = (unit(unitY) if isinstance(unitY, basestring) else unitY)
            self.xyUnitBase[1] = unitY.units.simplified.units
コード例 #9
0
    def _setxyUnitBase(self, unitX=None, unitY=None):
        from morphforge.stdimports import unit
        if unitX is not None:
            unitX = (unit(unitX) if isinstance(unitX, basestring) else unitX)
        if unitY is not None:
            unitY = (unit(unitY) if isinstance(unitY, basestring) else unitY)

        if unitX is not None:
            assert self.xyUnitBase[0] == None
            unitX = (unit(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 = (unit(unitY) if isinstance(unitY, basestring) else unitY)
            self.xyUnitBase[1] = unitY.units.simplified.units
コード例 #10
0
def load_ka_channel():
    ka_param_names = """
    ka_gmax ka_erev
    ka_m_a1 ka_m_a2 ka_m_a3 ka_m_a4 ka_m_a5
    ka_m_b1 ka_m_b2 ka_m_b3 ka_m_b4 ka_m_b5
    ka_h_a1 ka_h_a2 ka_h_a3 ka_h_a4 ka_h_a5
    ka_h_b1 ka_h_b2 ka_h_b3 ka_h_b4 ka_h_b5
    """

    ka_param_units = """
    nS/um2; mV;
    ms-1; mV-1 ms-1; ;mV; mV;
    ms-1; mV-1 ms-1; ;mV; mV;
    ms-1; mV-1 ms-1; ;mV; mV;
    ms-1; mV-1 ms-1; ;mV; mV;
    """
    ka_param_str = """
    30   -80
    12.025   0   0.5 -10.01  -12.56
    14.325   0   1    -8.01    9.69
    0.0001   0   1    15.88   26.0
    10.000   0   500 -22.09  -10.21
    """

    nrn_params = dict([(p, mf.unit("%s:%s"%(v, u.strip()))) for (p, u, v) in zip(ka_param_names.split(), ka_param_units.split(';'), ka_param_str.split())])
    nrn_params_ka = extract_params(nrn_params, prefix='ka_')
    print nrn_params_ka
    eqnsetka = mf.neurounits.NeuroUnitParser.EqnSet(na_eqnset_txt.replace("sautois", "saut2"))
    kaChls = mfc.Neuron_NeuroUnitEqnsetMechanism(name="Chl5", eqnset=eqnsetka,  default_parameters = nrn_params_ka)
    return kaChls
コード例 #11
0
def test_cell_current(cell_name, cell_chl_functor, current):
    sim = mf.NEURONEnvironment().Simulation()

    m1 = mf.MorphologyBuilder.get_single_section_soma(area=mf.unit("1:um2"))
    cell = sim.create_cell(name=cell_name, morphology=m1)
    cc = sim.create_currentclamp(name="CC1", delay=100*mf.ms, dur=400*mf.ms, amp=current * mf.pA, cell_location=cell.soma)

    for chl in cell_chl_functor():
        mf.cell.apply_channel( chl)

    mf.cell.set_passive( mf.PassiveProperty.SpecificCapacitance, mf.unit('4:pF/um2'))

    sim.record(cell, what=mf.Cell.Recordables.MembraneVoltage)
    sim.record(cc, what=mf.CurrentClamp.Recordables.Current)

    res =sim.run()
    return res
コード例 #12
0
def simulate_chl_all(chl):
    #res = {}
    return [
        #simulate_chl_vclamp(chl, unit("-80:mV")),
        #simulate_chl_vclamp(chl, unit("-50:mV")),
        #simulate_chl_vclamp(chl, unit("-20:mV")),
        #simulate_chl_vclamp(chl, unit("10:mV")),
        simulate_chl_vclamp(chl, unit("40:mV")),
       ]
コード例 #13
0
def dual_driver(sim, presynaptic, postsynaptic, ampa_scale, nmda_scale):
    ampa = sim.create_synapse(
            presynaptic_mech = build_presynaptic_mech( env, presynaptic),
            postsynaptic_mech = excite_ampa_syn_tmpl.instantiate(
                                        cell_location = postsynaptic.soma,
                                        parameter_multipliers = {'scale':ampa_scale * pq.dimensionless },
                                        weight = mf.unit("1:nS")
                                       )
           )
    nmda = sim.create_synapse(
            presynaptic_mech = build_presynaptic_mech( env, presynaptic),
            postsynaptic_mech = excite_nmda_syn_tmpl.instantiate(
                                        cell_location = postsynaptic.soma,
                                        parameter_multipliers = {'scale':nmda_scale * pq.dimensionless },
                                        weight = mf.unit("1:nS")
                                       )
           )
    return [ampa, nmda]
コード例 #14
0
    def plot_iv_curve(self, ax=None):
        # pylint: disable=E1103
        title = '%s: IV Curve' % (self.cell_description or None)
        if not ax:
            f = QuantitiesFigure()
            f.suptitle(title)
            ax = f.add_subplot(1, 1, 1)
            ax.set_xlabel('Injected Current')
            ax.set_ylabel('SteadyStateVoltage')

        V_in_mV = [self.get_iv_point_steaddy_state(c).rescale('mV').magnitude for c in self.currents]
        v = np.array(V_in_mV) * pq.mV
        i = factorise_units_from_list(self.currents)

        low_v = V_in_mV < self.v_regressor_limit if self.v_regressor_limit else range( len(V_in_mV))



        print 'i[low_v]', i[low_v]
        print 'v[low_v]', v[low_v]
        ax.plot(i[low_v], v[low_v], )
        ax.plot(i[np.logical_not(low_v)], v[np.logical_not(low_v)], )
        ax.plot(i[np.logical_not(low_v)], v[np.logical_not(low_v)], )

        # Plot the regressor:
        i_units = unit('1:pA').units
        v_units = unit('1:mV').units
        iv = np.vstack((i.rescale(i_units).magnitude,
                       v.rescale(v_units).magnitude)).T

        if not len(iv[low_v, 0]):
            return
        (a_s, b_s, r, tt, stderr) = stats.linregress(iv[low_v, 0], iv[low_v, 1])
        input_resistance = (a_s * (v_units / i_units)).rescale('MOhm')
        reversal_potential = b_s * v_units

        self.input_resistance = input_resistance
        self.reversal_potential = reversal_potential

        ax.plot(i, i*input_resistance + reversal_potential, label = "Fit: [V(mV) = %2.3f * I(pA)  + %2.3f]"%(a_s, b_s) + " \n[Input Resistance: %2.2fMOhm  Reversal Potential: %2.2f mV"%(input_resistance, reversal_potential)  )
        ax.legend()

        PM.save_figure(figname=title)
コード例 #15
0
def onto_driver(sim, postsynaptic, times):
    return sim.create_synapse(
            presynaptic_mech =  env.PreSynapticMechanism(
                                        mfc.PreSynapticMech_TimeList,
                                        time_list =   times,
                                        ),
            postsynaptic_mech = driver_syn_tmpl.instantiate(
                                        cell_location = postsynaptic.soma,
                                        parameter_multipliers = {'scale':1.0 },
                                        weight = mf.unit("1:nS")
                                       )
           )
コード例 #16
0
    def simulate(self, current_base, current_rebound):

        sim = self.env.Simulation(**self.sim_kwargs)
        cell = self.cell_functor(sim=sim)

        soma_loc = cell.get_location('soma')

        cc1 = sim.create_currentclamp(name="cclamp",
                                      amp=current_base,
                                      dur="100:ms",
                                      delay="50:ms",
                                      cell_location=soma_loc)
        cc2 = sim.create_currentclamp(name="cclamp2",
                                      amp=-1 * current_rebound,
                                      dur="5:ms",
                                      delay="80:ms",
                                      cell_location=soma_loc)
        cc3 = sim.create_currentclamp(name="cclamp3",
                                      amp=-1 * current_rebound,
                                      dur="5:ms",
                                      delay="120:ms",
                                      cell_location=soma_loc)

        sim.record(cc1,
                   name="Current1",
                   what=CurrentClamp.Recordables.Current,
                   description="CurrentClampCurrent")
        sim.record(cc2,
                   name="Current2",
                   what=CurrentClamp.Recordables.Current,
                   description="CurrentClampCurrent")
        sim.record(cc3,
                   name="Current3",
                   what=CurrentClamp.Recordables.Current,
                   description="CurrentClampCurrent")

        sim.record(cell,
                   name="SomaVoltage",
                   cell_location=soma_loc,
                   what=Cell.Recordables.MembraneVoltage,
                   description="Response to iInj1=%s iInj2=%s" %
                   (current_base, current_rebound))

        res = sim.run()

        #SimulationSummariser(res, "/home/michael/Desktop/ForRoman.pdf")

        i = res.get_trace('Current1').convert_to_fixed(
            unit("0.5:ms")) + res.get_trace('Current2').convert_to_fixed(
                unit("0.5:ms")) + res.get_trace('Current3').convert_to_fixed(
                    unit("0.5:ms"))

        i = TraceConverter.rebase_to_fixed_dt(res.get_trace('Current1'
               ), dt=unit('0.5:ms')) \
            + TraceConverter.rebase_to_fixed_dt(res.get_trace('Current2'
               ), dt=unit('0.5:ms')) \
            + TraceConverter.rebase_to_fixed_dt(res.get_trace('Current3'
               ), dt=unit('0.5:ms'))
        i.tags = [StandardTags.Current]
        return (res.get_trace('SomaVoltage'), i)
コード例 #17
0
def simulate_chl_vclamp(chl, voltage_level):
    env = NEURONEnvironment()

    # Create the simulation:
    sim = env.Simulation(tstop=unit("1500:ms"))

    # Create a cell:
    morphDict1 = {'root': {'length': 18.8, 'diam': 18.8, 'id':'soma'} }
    m1 = MorphologyTree.fromDictionary(morphDict1)
    cell = sim.create_cell(morphology=m1, segmenter=CellSegmenter_SingleSegment())

    # Setup the HH-channels on the cell:
    #chl = chl_applicator_functor(env, cell, sim)
    cell.apply_channel( chl)






    # Setup passive channels:
    cell.set_passive( PassiveProperty.SpecificCapacitance, unit('1.0:uF/cm2'))





    # Create the stimulus and record the injected current:
    #cc = sim.create_currentclamp(name="Stim1", amp=unit("10:pA"), dur=unit("100:ms"), delay=unit("300:ms") * R.uniform(0.95, 1.0), cell_location=cell.soma)

    cc = sim.create_voltageclamp(name="Stim1",
                                   dur1=unit("200:ms"), amp1=unit("-60:mV"),
                                   #dur2=unit("500:ms")* R.uniform(0.95, 1.0), amp2=voltage_level,
                                   dur2=unit("500:ms"), amp2=voltage_level,
                                   #dur3=unit("500:ms")* R.uniform(0.95, 1.0), amp3=unit("-50:mV"),
                                   dur3=unit("500:ms"), amp3=unit("-50:mV"),
                                   cell_location=cell.soma,
                                  )


    # Define what to record:
    sim.record(cell, what=StandardTags.Voltage, name="SomaVoltage", cell_location = cell.soma)
    sim.record(cc, what=StandardTags.Current, name="CurrentClamp")




    # run the simulation
    results = sim.run()




    return results
コード例 #18
0
    def __init__(self, cell_functor, currents, cell_description=None, sim_functor=None, v_regressor_limit=None, sim_kwargs=None, plot_all=False):
        self.cell_functor = cell_functor
        self.v_regressor_limit = v_regressor_limit
        #Previously = unit("-30:mV")

        self.sim_kwargs = sim_kwargs or {}

        self.tCurrentInjStart = unit('50:ms')
        self.tCurrentInjStop = unit('200:ms')

        self.tSteaddyStateStart = unit('100:ms')
        self.tSteaddyStateStop = unit('151:ms')

        self.traces = {}

        self.currents = currents
        self.cell_description = cell_description or 'Unknown Cell'

        self.input_resistance = unit('-1:MOhm')

        if plot_all:
            self.plot_all()
コード例 #19
0
    def _setxyUnitDisplay(self, unitX=None, unitY=None):
        from morphforge.stdimports import unit
        if unitX is not None:
            unitX = (unit(unitX) if isinstance(unitX, basestring) else unitX)
        if unitY is not None:
            unitY = (unit(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)
            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)
            self.ax.yaxis.set_major_formatter(yFormatterFunc)

        # Update the labels
        self._update_labels()
コード例 #20
0
    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):
            from morphforge.stdimports import unit
            x0 = unit(x0)
        if x1 is not None and isinstance(x1, basestring):
            from morphforge.stdimports import unit
            x1 = unit(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)
コード例 #21
0
    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):
            from morphforge.stdimports import unit
            x0 = unit(x0)
        if x1 is not None and isinstance(x1, basestring):
            from morphforge.stdimports import unit
            x1 = unit(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)
コード例 #22
0
    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):
            from morphforge.stdimports import unit
            x0 = unit(x0)
        if x1 is not None and isinstance(x1, basestring):
            from morphforge.stdimports import unit
            x1 = unit(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)
コード例 #23
0
def load_std_channels(param_str):
    nrn_params = dict([(p, mf.unit("%s:%s"%(v, u.strip()))) for (p, u, v) in zip(param_names.split(), param_units.split(';'), param_str.split())])
    nrn_params_na = extract_params(nrn_params, prefix='na_')
    nrn_params_lk = extract_params(nrn_params, prefix='lk_')
    nrn_params_ks = extract_params(nrn_params, prefix='ks_', replace_prefix='k_')
    nrn_params_kf = extract_params(nrn_params, prefix='kf_', replace_prefix='k_')
    nrn_params_ks = remap_keys(nrn_params_ks, {'k_gmax':'gmax', 'k_erev':'erev'})
    nrn_params_kf = remap_keys(nrn_params_kf, {'k_gmax':'gmax', 'k_erev':'erev'})
    eqnsetna = mf.neurounits.NeuroUnitParser.EqnSet(na_eqnset_txt)
    eqnsetlk = mf.neurounits.NeuroUnitParser.EqnSet(lk_eqnset_txt)
    eqnsetk = mf.neurounits.NeuroUnitParser.EqnSet(k_eqnset_txt)

    na_chl = mfc.Neuron_NeuroUnitEqnsetMechanism(name="Chl1", eqnset=eqnsetna, default_parameters = nrn_params_na)
    lk_chl = mfc.Neuron_NeuroUnitEqnsetMechanism(name="Chl2", eqnset=eqnsetlk, default_parameters = nrn_params_lk)
    ksChls = mfc.Neuron_NeuroUnitEqnsetMechanism(name="Chl3", eqnset=eqnsetk,  default_parameters = nrn_params_ks)
    kfChls = mfc.Neuron_NeuroUnitEqnsetMechanism(name="Chl4", eqnset=eqnsetk,  default_parameters = nrn_params_kf)

    chls =  [na_chl, lk_chl, ksChls, kfChls]
    return chls
コード例 #24
0
ファイル: test1.py プロジェクト: bmerrison/morphforge
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------

import morphforge.stdimports as mf
from mhlibs.quantities_plot import QuantitiesFigure
import pylab

from morphforge.stdimports import unit, reduce_to_variable_dt_trace

t1 = mf.TraceGenerator.generate_flat(value='1:mV')
#t2 = mf.TraceGenerator.generate_flat(value='0.0015:V')
t2 = mf.TraceGenerator.generate_ramp(value_start='0.0015:V',
                                     value_stop='2.5:mV',
                                     npoints=20)

f = QuantitiesFigure()
ax = f.add_subplot(111)
ax.plotTrace(t1, marker='x')
ax.plotTrace(t2, marker='o')
ax.plotTrace(t1 + t2, marker='<')
ax.plotTrace((t2 + t2) * 3.0 + unit('0.03:V'), marker='<')

t1 = mf.fixed_to_variable_dt_trace(t1, '0.01:mV')
ax.plotTrace(t1, marker='>')
ax.legend()

pylab.show()
コード例 #25
0
ファイル: neuron.py プロジェクト: bmerrison/morphforge
 def get_unit(self):
     return unit('')
コード例 #26
0
ファイル: neuron.py プロジェクト: bmerrison/morphforge
 def get_unit(self):
     return unit('')
コード例 #27
0
def compareNeuroMLChl(xmlFile):
    model, chl_type = os.path.splitext(xmlFile)[0].split("/")[-2:]
    print model, chl_type

    op_dir = LocMgr.ensure_dir_exists(Join(html_output_dir, model, chl_type))
    op_html = Join(op_dir, "index.html")
    c = ComparisonResult(xmlfile=xmlFile, op_file = op_html, same_chl=True, exception=None)

    try:

        # Make the NeuroUnits channel:
        chl_neuro = NeuroML_Via_NeuroUnits_ChannelNEURON(xml_filename=xmlFile,  )
        c.chl_neurounits = chl_neuro


        op_pdf_file = Join(op_dir, 'Op1.pdf')
        #WriteToPDF(eqnset = chl_neuro.eqnset, filename = op_pdf_file)
        c.chl_neurounits_pdf = op_pdf_file


        # Make the NeuroML channel:
        xsl_file = "/home/michael/srcs/neuroml/CommandLineUtils/ChannelMLConverter/ChannelML_v1.8.1_NEURONmod.xsl"
        chl_xsl = NeuroML_Via_XSL_ChannelNEURON(xml_filename=xmlFile, xsl_filename=xsl_file,  )
        c.chl_xsl = chl_xsl
        c.chl_xsl_hoc = []


        chl_neuro_res = simulate_chl_all(chl_neuro)
        chl_xsl_res = simulate_chl_all(chl_xsl)
        c.chl_neurounit_hoc = []


        for i, (rN, rX) in enumerate(zip(chl_neuro_res, chl_xsl_res)):

            c.chl_neurounit_hoc.append(rN.hocfilename )
            c.chl_xsl_hoc.append(rX.hocfilename )

            tN = rN.get_trace("CurrentClamp").convert_to_fixed(dt=unit("1.01:ms"))
            tX = rX.get_trace("CurrentClamp").convert_to_fixed(dt=unit("1.01:ms"))

            # Compare current traces:
            tN._data[np.fabs(tN.time_pts_ms - 0) <0.05] *=0
            tX._data[np.fabs(tX.time_pts_ms - 0) <0.05] *=0
            tN._data[np.fabs(tN.time_pts_ms - 200) <0.05] *=0
            tX._data[np.fabs(tX.time_pts_ms - 200) <0.05] *=0
            tN._data[np.fabs(tN.time_pts_ms - 700) <0.05] *=0
            tX._data[np.fabs(tX.time_pts_ms - 700) <0.05] *=0
            print "TR1"
            f = QuantitiesFigure()
            ax1 = f.add_subplot(4, 1, 1)
            ax2 = f.add_subplot(4, 1, 2)
            ax3 = f.add_subplot(4, 1, 3)
            ax4 = f.add_subplot(4, 1, 4)
            ax1.plotTrace(tN, color='b')
            ax1.plotTrace(tX, color='g', linewidth=20, alpha=0.2)
            ax2.plotTrace(tN.window((200, 250)*pq.ms), color='b')
            ax2.plotTrace(tX.window((200, 250)*pq.ms), color='g', linewidth=20, alpha=0.2)

            num = (tN-tX)
            denom = (tN+tX)
            diff = num/denom
            ax3.plotTrace(diff, color='r')

            ax4.plotTrace(rN.get_trace('SomaVoltage'), color='m')
            ax4.plotTrace(rX.get_trace('SomaVoltage'), color='m', linewidth=20, alpha=0.2)

            if num.max()[1] > unit("0.1:pA"):
                c.same_chl = False

            out_im = Join(op_dir, "out_im%03d" % i)
            pylab.savefig(out_im+".png")
            pylab.savefig(out_im+".pdf")
            c.output_image_files.append(out_im)
            pylab.close()

        c.finished_ok=True



    except NeuroUnitsImportNeuroMLNotImplementedException, e:
        print 'Exception caught:', e

        s = StringIO.StringIO()
        traceback.print_exc(file=s)
        c.exception_long=s.getvalue()
        c.exception="%s (%s)"%(str(e), str(type(e)))
        c.same_chl = False
        c.finished_ok=False
コード例 #28
0
ファイル: test1.py プロジェクト: bmerrison/morphforge
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------


import morphforge.stdimports as mf
from mhlibs.quantities_plot import QuantitiesFigure
import pylab

from morphforge.stdimports import unit, reduce_to_variable_dt_trace


t1 = mf.TraceGenerator.generate_flat(value="1:mV")
# t2 = mf.TraceGenerator.generate_flat(value='0.0015:V')
t2 = mf.TraceGenerator.generate_ramp(value_start="0.0015:V", value_stop="2.5:mV", npoints=20)


f = QuantitiesFigure()
ax = f.add_subplot(111)
ax.plotTrace(t1, marker="x")
ax.plotTrace(t2, marker="o")
ax.plotTrace(t1 + t2, marker="<")
ax.plotTrace((t2 + t2) * 3.0 + unit("0.03:V"), marker="<")

t1 = mf.fixed_to_variable_dt_trace(t1, "0.01:mV")
ax.plotTrace(t1, marker=">")
ax.legend()

pylab.show()