コード例 #1
0
ファイル: mmalphabeta.py プロジェクト: bmerrison/morphforge
    def plot_state_curve_summary(cls,  alphabeta_chl, state, figsize):
        fig = QuantitiesFigure(figsize=figsize)
        fig.suptitle("AlphaBeta Channel - %s : %s"%(alphabeta_chl.name, state))
        ax1 = fig.add_subplot(221)
        ax2 = fig.add_subplot(222)
        cls.plot_alpha_beta_curves(ax1, ax2, alphabeta_chl, state)

        ax3 = fig.add_subplot(223)
        ax4 = fig.add_subplot(224)
        cls.plot_inf_tau_curves(ax3, ax4, alphabeta_chl, state)
        return fig
コード例 #2
0
ファイル: summarisier.py プロジェクト: bmerrison/morphforge
        def plot_state_curve_summary(cls,  alphabeta_chl, state, figsize):
            fig = QuantitiesFigure(figsize=figsize)
            fig.suptitle("InfTauInterpolated Channel - %s : %s"%(alphabeta_chl.name, state))
            ax1 = fig.add_subplot(221)
            ax2 = fig.add_subplot(222)
            cls.plot_inf_tau_curves(ax1, ax2, alphabeta_chl, state)

            ax3 = fig.add_subplot(223)
            ax4 = fig.add_subplot(224)
            cls.plot_alpha_beta_curves(ax3, ax4, alphabeta_chl, state)
            return fig
コード例 #3
0
ファイル: mmalphabeta.py プロジェクト: unidesigner/morphforge
 def PlotStateCurveSummary(cls,  alphaBetaChl, state, figsize):
     fig = QuantitiesFigure(figsize=figsize)
     fig.suptitle("AlphaBeta Channel - %s : %s"%(alphaBetaChl.name, state))
     ax1 = fig.add_subplot(221)
     ax2 = fig.add_subplot(222)
     cls.PlotAlphaBetaCurves(ax1, ax2, alphaBetaChl,state )
     
     ax3 = fig.add_subplot(223)
     ax4 = fig.add_subplot(224)
     cls.PlotInfTauCurves(ax3, ax4, alphaBetaChl,state )
     return fig
コード例 #4
0
 def summarise_KeyTraces(self):
     from reportlab.platypus import Paragraph, PageBreak
     if not self.make_graphs:
         return []
         
     localElements = []
     localElements.append( Paragraph("Key-Traces", self.reportlabconfig.styles['Heading1'] ) )
     
     for traceSetName, keyTraces in self.keyTraceSets:
         localElements.append( Paragraph("TraceSet: %s"%traceSetName, self.reportlabconfig.styles['Heading2'] ) )
         
         
         
         f = QuantitiesFigure(figsize=self.reportlabconfig.imagesize)
         width,height =self.reportlabconfig.imagesize
         ax = f.add_subplot(111, xUnit="ms", ylabel="?", xlabel="time")
         for trName in keyTraces:
             tr = self.simulation.result.getTrace(trName)
             ax.plotTrace( tr )
         ax.legend()
         localElements.append( self.reportlabconfig.saveMPLToRLImage( f, "KeyTrace") )
         
     
     localElements.append( PageBreak() ) 
     return localElements
コード例 #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 PlotGHKMaxCurrentFlow(cls, calciumAlphaBetaBetaChannel, figsize):
            V = StdLimits.get_default_voltage_array().rescale("mV")
            # Plot the
            fig = QuantitiesFigure(figsize=figsize)
            ax1 = fig.add_subplot(221, xUnit="mV", yUnit="pA/cm2", xlabel="Voltage", ylabel="")


            #Plot the 'I_ca' as defined in Biophysics of Computations:
            chl = calciumAlphaBetaBetaChannel
            nmp = (chl.CaZ * chl.F) / (chl.R * chl.T)
            nmpV = (nmp * V).rescale("")

            iCa = chl.permeability * nmpV * chl.F * (chl.intracellular_concentration - chl.extracellular_concentration * np.exp(-1.0 * nmpV)) / (1.0 - np.exp(-1.0 * nmpV))

            iCa.rescale("pA/cm2")


            ax1.plot(V, iCa)
コード例 #7
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) * units.mV
        i = morphforge.units.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 = qty('1:pA').units
        v_units = qty('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
        import scipy.stats as stats
        (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,'o-', 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)
コード例 #8
0
ファイル: traces_100.py プロジェクト: bmerrison/morphforge
def test_trace_method_traceout(src_trace, method_name, method_functor):
    f = QuantitiesFigure(figsize=(6, 4))
    f.suptitle("Testing Method: %s" % method_name)
    ax1 = f.add_subplot(211)
    ax2 = f.add_subplot(212)

    ax1.plotTrace(src_trace, label="Original")

    for (conv_type, conv_functor) in conversions:
        tr_new = conv_functor(src_trace)

        if not mf.TraceMethodCtrl.has_method(conv_type, method_name):
            continue
        ax2.plotTrace(method_functor(tr_new), label="%s:%s" % (conv_type.__name__, method_name))

    ax1.legend()
    ax2.legend()

    return mrd.Section("Test: %s" % method_name, mrd.Image(f.fig, auto_adjust=False))
コード例 #9
0
ファイル: traces_100.py プロジェクト: bmerrison/morphforge
def test_trace_method_traceout(src_trace, method_name, method_functor):
    f = QuantitiesFigure(figsize=(6, 4))
    f.suptitle('Testing Method: %s' % method_name)
    ax1 = f.add_subplot(211)
    ax2 = f.add_subplot(212)

    ax1.plotTrace(src_trace, label='Original')

    for (conv_type, conv_functor) in conversions:
        tr_new = conv_functor(src_trace)

        if not mf.TraceMethodCtrl.has_method(conv_type, method_name):
            continue
        ax2.plotTrace(method_functor(tr_new),
                      label='%s:%s' % (conv_type.__name__, method_name))

    ax1.legend()
    ax2.legend()

    return mrd.Section('Test: %s' % method_name,
                       mrd.Image(f.fig, auto_adjust=False))
コード例 #10
0
    def plot_traces(self, ax=None):
        title = '%s: (Voltage Responses to Current Injections)' \
            % self.cell_description
        if not ax:
            f = QuantitiesFigure()
            f.suptitle(title)
            ax = f.add_subplot(1, 1, 1)
            ax.set_xlabel('Time')
            ax.set_ylabel('Voltage')

        # Plot the traces
        for i_inj in self.currents:
            ax.plotTrace(self.get_trace(i_inj), label='i_inj: %s'
                         % i_inj)

        # Add the regions:
        ax.axvspan(self.tSteaddyStateStart, self.tSteaddyStateStop, facecolor='g', alpha=0.25)
        ax.legend()

        from mreorg.scriptplots import PM
        PM.save_figure(figname=title)
コード例 #11
0
    def PlotGHKMaxCurrentFlow(cls, calciumAlphaBetaBetaChannel, figsize):
        V = StdLimits.get_default_voltage_array().rescale("mV")
        # Plot the
        fig = QuantitiesFigure(figsize=figsize)
        ax1 = fig.add_subplot(221,
                              xUnit="mV",
                              yUnit="pA/cm2",
                              xlabel="Voltage",
                              ylabel="")

        #Plot the 'I_ca' as defined in Biophysics of Computations:
        chl = calciumAlphaBetaBetaChannel
        nmp = (chl.CaZ * chl.F) / (chl.R * chl.T)
        nmpV = (nmp * V).rescale("")

        iCa = chl.permeability * nmpV * chl.F * (
            chl.intracellular_concentration - chl.extracellular_concentration *
            np.exp(-1.0 * nmpV)) / (1.0 - np.exp(-1.0 * nmpV))

        iCa.rescale("pA/cm2")

        ax1.plot(V, iCa)
コード例 #12
0
    def plot_traces(self, ax=None):
        title = '%s: (Voltage Responses to Current Injections)' \
            % self.cell_description
        if not ax:
            f = QuantitiesFigure()
            f.suptitle(title)
            ax = f.add_subplot(1, 1, 1)
            ax.set_xlabel('Time')
            ax.set_ylabel('Voltage')

        # Plot the traces
        for i_inj in self.currents:
            ax.plotTrace(self.get_trace(i_inj), label='i_inj: %s' % i_inj)

        # Add the regions:
        ax.axvspan(self.tSteaddyStateStart,
                   self.tSteaddyStateStop,
                   facecolor='g',
                   alpha=0.25)
        ax.legend()

        from mreorg.scriptplots import PM
        PM.save_figure(figname=title)
コード例 #13
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
コード例 #14
0
class CellAnalysis_IVCurve(object):


    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
        self.fig=None
        #Previously = qty("-30:mV")

        self.sim_kwargs = sim_kwargs or {}

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

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

        self.traces = {}

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

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

        if plot_all:
            self.plot_all()

    def plot_all(self):
        self.plot_traces()
        self.plot_iv_curve()

    def _get_cc_simulation_trace(self, current):

        if self.cell_functor:
            env = NEURONEnvironment()
            sim = env.Simulation(**self.sim_kwargs)
            cell = self.cell_functor(sim=sim)
        else:
            assert False

        soma_loc = cell.get_location('soma')

        cc = sim.create_currentclamp(name='cclamp', amp=current,
                dur=self.tCurrentInjStop - self.tCurrentInjStart,
                delay=self.tCurrentInjStart, cell_location=soma_loc)
        sim.record(cell, name='SomaVoltage', cell_location=soma_loc,
                   what=Cell.Recordables.MembraneVoltage,
                   description='Response to i_inj=%s ' % current)

        res = sim.run()

        return res.get_trace('SomaVoltage')

    def get_trace(self, i_inj):
        if not i_inj in self.traces:
            self.traces[i_inj] = self._get_cc_simulation_trace(i_inj)
        return self.traces[i_inj]

    def get_iv_point_steaddy_state(self, i_inj):
        return self.get_trace(i_inj).window(time_window=(self.tSteaddyStateStart, self.tSteaddyStateStop)).Mean()


    def plot_traces(self, ax=None):
        title = '%s: (Voltage Responses to Current Injections)' \
            % self.cell_description
        if not ax:
            self.fig = QuantitiesFigure()
            self.fig.suptitle(title)
            ax = self.fig.add_subplot(1, 1, 1)
            ax.set_xlabel('Time')
            ax.set_ylabel('Voltage')

        # Plot the traces
        for i_inj in self.currents:
            ax.plotTrace(self.get_trace(i_inj), label='i_inj: %s'
                         % i_inj)

        # Add the regions:
        ax.axvspan(self.tSteaddyStateStart, self.tSteaddyStateStop, facecolor='g', alpha=0.25)
        ax.legend()

        from mreorg.scriptplots import PM
        PM.save_figure(figname=title)

    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) * units.mV
        i = morphforge.units.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 = qty('1:pA').units
        v_units = qty('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
        import scipy.stats as stats
        (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,'o-', 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
ファイル: traces_090.py プロジェクト: bmerrison/morphforge
import morphforge.stdimports as mf
from morphforge.traces.generation import TraceStringParser
import quantities as pq

from mhlibs.quantities_plot import QuantitiesFigure

t = """{d:pA} FLAT(1) FOR 100ms THEN RAMPTO(50) UNTIL 130ms THEN FLAT(0) THEN AT 150ms FLAT(120) FOR 20ms THEN  FLAT(0) UNTIL 180ms"""

tr = TraceStringParser.Parse(t)

trFix = tr.convert_to_fixed(dt=01. * pq.ms)

print 't1:', tr.integrate()
print 't2:', trFix.integrate()

f = QuantitiesFigure()
ax1 = f.add_subplot(211)
ax2 = f.add_subplot(212)

trFixSquared = trFix**2
print trFixSquared.integrate()

print(tr**2).integrate()

ax1.plotTrace(trFix)
ax2.plotTrace(trFixSquared)

import pylab
pylab.show()
コード例 #16
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()
コード例 #17
0
class TagViewer(object):

    MPL_AUTO_SHOW = True

    _default_plot_specs = (
        DefaultTagPlots.Voltage,
        DefaultTagPlots.CurrentDensity,
        DefaultTagPlots.Current,
        DefaultTagPlots.Conductance,
        DefaultTagPlots.ConductanceDensity,
        DefaultTagPlots.StateVariable,
        DefaultTagPlots.StateVariableTau,
        DefaultTagPlots.StateVariableInf,
        DefaultTagPlots.Event,
    )

    _default_fig_kwargs = {'figsize': (12, 8)}

    _options_show_xlabel = ('only-once', 'all', False)
    _options_show_xticklabels = ('only-once', 'all', False)
    _options_show_xticklabels_with_units = (True, False)
    _options_show_xaxis_position = ('bottom', 'top')

    def __init__(self,
                 srcs,
                 plots=None,
                 additional_plots=None,
                 figtitle=None,
                 fig_kwargs=None,
                 show=True,
                 linkage=None,
                 timerange=None,
                 mpl_tight_bounds=False,
                 share_x_labels=True,
                 nxticks=4,
                 show_xlabel='only-once',
                 show_xticklabels='only-once',
                 show_xticklabels_with_units=True,
                 show_xaxis_position='bottom',
                 xticks=None):
        """Plot a set of traces.

        Keyword arguments:
        plots -- 
        srcs --
        plots --
        additional_plots -- 
        figtitle --
        fig_kwargs --
        show --
        linkage --
        timerange -- 
        mpl_tight_bounds --
        share_x_labels --

        nxticks=4, 
        show_xlabel -- which plots should the x-axis be displayed on.
        show_xticklabels --
        show_xticklabels_with_units -- 
        show_xaxis_position --
        xticks -- 
        """

        if fig_kwargs is None:
            fig_kwargs = self._default_fig_kwargs

        self.linkage = linkage

        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),
            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 = xticks
        assert self.show_xlabel in self._options_show_xlabel, 'Invalid'
        assert self.show_xticklabels in self._options_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 * pq.ms for xtick in self.xticks]
        assert self.xticks is None or isinstance(
            self.xticks, int) or (is_iterable(self.xticks)
                                  and [unit(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()

    def create_figure(self):
        self.fig = QuantitiesFigure(**self.fig_kwargs)

        # Add a title to the plot:
        if self.figtitle:
            self.fig.suptitle(self.figtitle)

        # Work out what traces are on what graphs:
        plotspec_to_traces = dict([(plot_spec, [
            tr for tr in self.all_trace_objs
            if plot_spec.addtrace_predicate(tr)
        ]) for plot_spec in self.plot_specs])
        if self.linkage:
            self.linkage.process(plotspec_to_traces)

        n_plots = len(self.plot_specs)

        for (i, plot_spec) in enumerate(self.plot_specs):

            # Create the axis:
            ax = self.fig.add_subplot(n_plots, 1, i + 1)
            ax.set_xunit(pq.millisecond)
            ax.set_xmargin(0.05)
            ax.set_ymargin(0.05)

            ax.set_xaxis_maxnlocator(self.nxticks)

            # Leave the plotting to the tag-plot object
            plot_spec.plot(
                ax=ax,
                all_traces=self.all_trace_objs,
                all_eventsets=self.all_event_set_objs,
                time_range=self.timerange,
                linkage=self.linkage,
                #plot_xaxis_details=plot_xaxis_details,
                show_xlabel=self.show_xlabel,
                show_xticklabels=self.show_xticklabels,
                show_xticklabels_with_units=self.show_xticklabels_with_units,
                show_xaxis_position=self.show_xaxis_position,
                is_top_plot=(i == 0),
                is_bottom_plot=(i == n_plots - 1),
                xticks=self.xticks)

            # Save the Axis:
            self.subaxes.append(ax)

        if self.mpl_tight_bounds:
            import pylab
            try:
                pylab.tight_layout()
            except AttributeError:
                pass  # This is version specfic
            except ValueError:
                pass  # Top can't be less than bottom
コード例 #18
0
ファイル: tagviewer.py プロジェクト: bmerrison/morphforge
class TagViewer(object):

    MPL_AUTO_SHOW = True

    _default_plot_specs = (
        DefaultTagPlots.Voltage,
        DefaultTagPlots.CurrentDensity,
        DefaultTagPlots.Current,
        DefaultTagPlots.Conductance,
        DefaultTagPlots.ConductanceDensity,
        DefaultTagPlots.StateVariable,
        DefaultTagPlots.StateVariableTau,
        DefaultTagPlots.StateVariableInf,
        DefaultTagPlots.Event,
       )

    _default_fig_kwargs = {'figsize': (12, 8) }

    _options_show_xlabel = ('only-once','all',  False)
    _options_show_xticklabels=('only-once','all', False)
    _options_show_xticklabels_with_units=(True,False)
    _options_show_xaxis_position = ('bottom','top')

    def __init__(
        self,
        srcs,
        plots=None,
        additional_plots=None,
        figtitle=None,
        fig_kwargs=None,
        show=True,
        linkage=None,
        timerange=None,
        mpl_tight_bounds=False,

        share_x_labels=True,

        nxticks=4, 
        show_xlabel='only-once',
        show_xticklabels='only-once',
        show_xticklabels_with_units=True,
        show_xaxis_position='bottom',
        xticks=None

        ):
        """Plot a set of traces.

        Keyword arguments:
        plots -- 
        srcs --
        plots --
        additional_plots -- 
        figtitle --
        fig_kwargs --
        show --
        linkage --
        timerange -- 
        mpl_tight_bounds --
        share_x_labels --

        nxticks=4, 
        show_xlabel -- which plots should the x-axis be displayed on.
        show_xticklabels --
        show_xticklabels_with_units -- 
        show_xaxis_position --
        xticks -- 
        """

        if fig_kwargs is None:
            fig_kwargs = self._default_fig_kwargs

        self.linkage = linkage


        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),
            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=xticks
        assert self.show_xlabel in self._options_show_xlabel, 'Invalid'
        assert self.show_xticklabels in self._options_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*pq.ms for xtick in self.xticks]
        assert self.xticks is None or isinstance(self.xticks, int) or ( is_iterable(self.xticks) and [ unit(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()

    def create_figure(self):
        self.fig = QuantitiesFigure(**self.fig_kwargs)

        # Add a title to the plot:
        if self.figtitle:
            self.fig.suptitle(self.figtitle)

        # Work out what traces are on what graphs:
        plotspec_to_traces = dict([(plot_spec, [tr for tr in self.all_trace_objs if plot_spec.addtrace_predicate(tr)]) for plot_spec in self.plot_specs ])
        if self.linkage:
            self.linkage.process(plotspec_to_traces)

        n_plots = len(self.plot_specs)

        for (i, plot_spec) in enumerate(self.plot_specs):

            # Create the axis:
            ax = self.fig.add_subplot(n_plots, 1, i + 1)
            ax.set_xunit(pq.millisecond)
            ax.set_xmargin(0.05)
            ax.set_ymargin(0.05)

            ax.set_xaxis_maxnlocator(self.nxticks)

            # Leave the plotting to the tag-plot object
            plot_spec.plot( ax=ax, 
                            all_traces=self.all_trace_objs, 
                            all_eventsets=self.all_event_set_objs, 
                            time_range=self.timerange, 
                            linkage=self.linkage, 
                            #plot_xaxis_details=plot_xaxis_details,

                            show_xlabel = self.show_xlabel,
                            show_xticklabels = self.show_xticklabels,
                            show_xticklabels_with_units = self.show_xticklabels_with_units,
                            show_xaxis_position = self.show_xaxis_position,
                            is_top_plot = (i==0),
                            is_bottom_plot = (i==n_plots-1),
                            xticks = self.xticks

                            )


            # Save the Axis:
            self.subaxes.append(ax)

        if self.mpl_tight_bounds:
            import pylab
            try:
                pylab.tight_layout()
            except AttributeError:
                pass  # This is version specfic
            except ValueError:
                pass # Top can't be less than bottom
コード例 #19
0
exp_eta = np.exp(-eta.rescale(pq.dimensionless))
print exp_eta




ungated_ica = pca * z * eta * F * (Cai - Cao * exp_eta)/(1-exp_eta)
ungated_ica = ungated_ica.rescale(  pq.milliamp / pq.centimeter**2)

ungated_ica = ungated_ica* SA

g = np.gradient(ungated_ica) / np.gradient(V) 
g = g.rescale( mfu.pS)
R = (1/g).rescale(mfu.MOhm)
#print g


erev = V - (ungated_ica /g)
print erev


f = QuantitiesFigure()
ax1 = f.add_subplot(3,1,1)
ax2 = f.add_subplot(3,1,2)
ax3 = f.add_subplot(3,1,3)
ax1.plot( V, ungated_ica)
ax2.plot( V, R)
ax3.plot( V, erev)

pl.show()
コード例 #20
0
ファイル: traces_090.py プロジェクト: NeuroArchive/morphforge
from morphforge import units

from mhlibs.quantities_plot import QuantitiesFigure

t = """{d:pA} FLAT(1) FOR 100ms THEN RAMPTO(50) UNTIL 130ms THEN FLAT(0) THEN AT 150ms FLAT(120) FOR 20ms THEN  FLAT(0) UNTIL 180ms"""

tr = TraceStringParser.Parse(t)


trFix = tr.convert_to_fixed(dt=01.*units.ms)

print 't1:', tr.integrate()
print 't2:', trFix.integrate()

f = QuantitiesFigure()
ax1 = f.add_subplot(211)
ax2 = f.add_subplot(212)


trFixSquared = trFix ** 2
print trFixSquared.integrate()

print (tr**2).integrate()


ax1.plotTrace(trFix)
ax2.plotTrace(trFixSquared)



コード例 #21
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()