Esempio n. 1
0
def demo_locatable_axes_hard(fig):
    from mpl_toolkits.axes_grid1 import SubplotDivider, Size
    from mpl_toolkits.axes_grid1.mpl_axes import Axes
    divider = SubplotDivider(fig, 2, 2, 2, aspect=True)

    # axes for image
    ax = Axes(fig, divider.get_position())

    # axes for colorbar
    ax_cb = Axes(fig, divider.get_position())
    h = [
        Size.AxesX(ax),  # main axes
        Size.Fixed(0.05),  # padding, 0.1 inch
        Size.Fixed(0.2),  # colorbar, 0.3 inch
    ]
    v = [Size.AxesY(ax)]
    divider.set_horizontal(h)
    divider.set_vertical(v)
    ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
    ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0))
    fig.add_axes(ax)
    fig.add_axes(ax_cb)
    ax_cb.axis["left"].toggle(all=False)
    ax_cb.axis["right"].toggle(ticks=True)
    Z, extent = get_demo_image()
    im = ax.imshow(Z, extent=extent, interpolation="nearest")
    plt.colorbar(im, cax=ax_cb)
    plt.setp(ax_cb.get_yticklabels(), visible=False)
Esempio n. 2
0
def fix_sz_fig(width, height, width_ext=2, padding=.5):
    # These code is to make fixed size article
    # Makesure matplotlib can draw Chinese characters
    plt.rcParams['font.sans-serif'] = ['SimHei']
    # Init figure
    fig = plt.figure(figsize=(width + 2 * padding + width_ext,
                              height + 2 * padding))
    # The first items are for padding and the second items are for the axes.
    # Article width and height
    w = [Size.Fixed(padding), Size.Fixed(width)]
    h = [Size.Fixed(padding), Size.Fixed(height)]
    divider = Divider(fig, (0.0, 0.0, 1., 1.), w, h, aspect=False)
    # the width and height of the rectangle is ignored.
    ax = Axes(fig, divider.get_position())
    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
    fig.add_axes(ax)

    return fig, ax
Esempio n. 3
0
def create_plot(two_sided=False,
                colors=[
                    '#6F4C9B', '#5568B8', '#4D8AC6', '#60AB9E', '#77B77D',
                    '#A6BE54', '#D1B541', '#E49C39', '#DF4828', '#990D38'
                ],
                markers=['o', 'v', '^', 's', 'D', '*'],
                figsize=(5, 3.4)):
    """
    Crée un environnement de plot

    Parameters
    ----------
    twosided : bool
        allows to change the size of the figure accordingly.
    colors : list of strings
        a default list exists but this allows to change it if u want
    markers : list of strings
        a default list of markers exists, but u can change it if needed
    Returns
    -------
    fig, ax : matplotlib objects to be used as normal

    """
    color = cycle(colors)
    marker = cycle(markers)
    if two_sided:
        fig = plt.figure(figsize=(3.4, 3.4))
    else:
        fig = plt.figure(figsize=figsize)
    # The first & third items are for padding and the second items are for the
    # axes. Sizes are in inches.
    h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2)]
    v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]

    divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
    # the width and height of the rectangle is ignored.

    ax = Axes(fig, divider.get_position())
    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))

    fig.add_axes(ax)
    return fig, ax, color, marker
Esempio n. 4
0
def add_cbar(mappable, ax):
    """ 
    Append colorbar to axes
    Copied from DaViTPy: https://github.com/vtsuperdarn/davitpy/blob/1b578ea2491888e3d97d6e0a8bc6d8cc7c9211fb/davitpy/utils/plotUtils.py#L674
    """
    from mpl_toolkits.axes_grid1 import SubplotDivider, Size
    from mpl_toolkits.axes_grid1.mpl_axes import Axes
    import matplotlib.pyplot as plt

    fig1 = ax.get_figure()
    divider = SubplotDivider(fig1, *ax.get_geometry(), aspect=True)

    # axes for colorbar
    cbax = Axes(fig1, divider.get_position())

    h = [
        Size.AxesX(ax),  # main axes
        Size.Fixed(0.1),  # padding
        Size.Fixed(0.2)
    ]  # colorbar
    v = [Size.AxesY(ax)]

    _ = divider.set_horizontal(h)
    _ = divider.set_vertical(v)

    _ = ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
    _ = cbax.set_axes_locator(divider.new_locator(nx=2, ny=0))

    _ = fig1.add_axes(cbax)

    _ = cbax.axis["left"].toggle(all=False)
    _ = cbax.axis["top"].toggle(all=False)
    _ = cbax.axis["bottom"].toggle(all=False)
    _ = cbax.axis["right"].toggle(ticklabels=True, label=True)

    _ = plt.colorbar(mappable, cax=cbax)

    return cbax
Esempio n. 5
0
def demo_locatable_axes_hard(fig1):

    from mpl_toolkits.axes_grid1 import SubplotDivider, Size
    from mpl_toolkits.axes_grid1.mpl_axes import Axes

    divider = SubplotDivider(fig1, 2, 2, 2, aspect=True)

    # axes for image
    ax = Axes(fig1, divider.get_position())

    # axes for colorbar
    ax_cb = Axes(fig1, divider.get_position())

    h = [Size.AxesX(ax),  # main axes
         Size.Fixed(0.05),  # padding, 0.1 inch
         Size.Fixed(0.2),  # colorbar, 0.3 inch
         ]

    v = [Size.AxesY(ax)]

    divider.set_horizontal(h)
    divider.set_vertical(v)

    ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
    ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0))

    fig1.add_axes(ax)
    fig1.add_axes(ax_cb)

    ax_cb.axis["left"].toggle(all=False)
    ax_cb.axis["right"].toggle(ticks=True)

    Z, extent = get_demo_image()

    im = ax.imshow(Z, extent=extent, interpolation="nearest")
    plt.colorbar(im, cax=ax_cb)
    plt.setp(ax_cb.get_yticklabels(), visible=False)
Esempio n. 6
0
def demo_fixed_pad_axes():
    fig = plt.figure(figsize=(6, 6))

    # The first & third items are for padding and the second items are for the
    # axes. Sizes are in inches.
    h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2)]
    v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]

    divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
    # the width and height of the rectangle is ignored.

    ax = Axes(fig, divider.get_position())
    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))

    fig.add_axes(ax)

    ax.plot([1, 2, 3])
def demo_fixed_size_axes():
    fig1 = plt.figure(1, (6, 6))

    # The first items are for padding and the second items are for the axes.
    # sizes are in inch.
    h = [Size.Fixed(1.0), Size.Fixed(4.5)]
    v = [Size.Fixed(0.7), Size.Fixed(5.)]

    divider = Divider(fig1, (0.0, 0.0, 1., 1.), h, v, aspect=False)
    # the width and height of the rectangle is ignored.

    ax = Axes(fig1, divider.get_position())
    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))

    fig1.add_axes(ax)

    ax.plot([1, 2, 3])
Esempio n. 8
0
all_cell_p = all_cell_p[~np.isnan(fr_diff)]
fr_diff = fr_diff[~np.isnan(fr_diff)]
cell_hyp_sig_fr = fr_diff[all_cell_p < 0.05]
cell_hyp_no_fr = fr_diff[(all_dVm < 0) & (all_cell_p >= 0.05)]
cell_dep_sig_fr = fr_diff[all_cell_p > 0.95]
cell_dep_no_fr = fr_diff[(all_dVm > 0) & (all_cell_p <= 0.95)]
# Event-based correlation between dVm and dFR - all true spikes
#fig, ax = plt.subplots(1, figsize=[1.9, 1.8])
# create a figure with axes of defined size
fig = plt.figure(figsize=[2, 2])
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(0.5), Size.Fixed(1.2)]
v = [Size.Fixed(0.5), Size.Fixed(1.2)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
n = 0
for i in np.arange(len(data)):
    for j in np.arange(data[i][state + '_start'].size):
        x = data[i][state + '_dVm'][j]
        fr_bef = np.logical_and(
            data[i][state + '_spike'][j] > states[l]['bef'],
            data[i][state + '_spike'][j] <
            states[l]['bef'] + states[l]['samp_time'])
        fr_bef = np.sum(fr_bef) / states[l]['samp_time']
        fr_aft = np.logical_and(
            data[i][state + '_spike'][j] > states[l]['aft'],
            data[i][state + '_spike'][j] <
            states[l]['aft'] + states[l]['samp_time'])
Esempio n. 9
0
    def delay_avg_svg(self, ttype, b64encode=True):
        fig = pyplot.figure(figsize=self.FIGSIZE)

        h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)]
        v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]

        divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
        plt = Axes(fig, divider.get_position())
        plt.set_axes_locator(divider.new_locator(nx=1, ny=1))

        fig.add_axes(plt)

        result = self.result
        runinfo = result.runinfo

        # ----
        # The X limits are -rampupMins, runMins
        # ----
        plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins']))
        plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1)

        # ----
        # offset the timestamps by -rampupMins so that the graph
        # starts with negative minutes elapsed and switches to
        # positive when the measurement begins.
        # ----
        offset = (int(runinfo['rampupMins'])) * 60.0

        # ----
        # ttype transaction delay. First get the timestamp
        # and delay numbers from the result data.
        # The X vector then is the sorted unique timestamps rounded
        # to an interval.
        # ----
        interval = 10
        data = numpy.array([[(int(tup[0] / interval) * interval - offset) / 60,
                             tup[1], tup[5]]
                            for tup in result.result_ttype[ttype]])
        x = sorted(numpy.unique(data[:, 0]))

        # ----
        # The Y vector is the sums of transactions delay divided by
        # the sums of the count, grouped by X.
        # ----
        y = []
        for ts in x:
            tmp = data[numpy.where(data[:, 0] == ts)]
            y.append(numpy.sum(tmp[:, 2]) / (numpy.sum(tmp[:, 1]) + 0.000001))

        # ----
        # Plot the ttype delay and add all the decorations
        # ----
        plt.plot(x, y, 'r', label='Delay')

        # ----
        # Now do the same aggregation for the latency
        # ----
        data = numpy.array([[(int(tup[0] / interval) * interval - offset) / 60,
                             tup[1], tup[2]]
                            for tup in result.result_ttype[ttype]])

        # ----
        # The Y vector is similar by based on latency
        # ----
        y = []
        for ts in x:
            tmp = data[numpy.where(data[:, 0] == ts)]
            y.append(numpy.sum(tmp[:, 2]) / (numpy.sum(tmp[:, 1]) + 0.000001))
        plt.plot(x, y, 'b', label='Latency')

        plt.set_title("{} Average Latency and Delay".format(ttype))
        plt.set_xlabel("Elapsed Minutes")
        plt.set_ylabel("Latency/Delay in ms")
        plt.legend(loc='upper left')
        plt.grid()

        buf = io.StringIO()
        pyplot.savefig(buf, format='svg')

        if not b64encode:
            return buf.getvalue()
        return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
Esempio n. 10
0
    def memory_svg(self,
                   host=None,
                   title="Memory Usage",
                   unit="Bytes",
                   factor=1.0,
                   b64encode=True):
        fig = pyplot.figure(figsize=self.FIGSIZE)

        h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)]
        v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]

        divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
        plt = Axes(fig, divider.get_position())
        plt.set_axes_locator(divider.new_locator(nx=1, ny=1))

        fig.add_axes(plt)

        result = self.result
        runinfo = result.runinfo

        # ----
        # The X limits are -rampupMins, runMins
        # ----
        plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins']))
        plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1)

        x, y_used = self._get_metric_xy({
            'host': host,
            'metric': 'memory.memory-used',
            'factor': factor,
        })
        _, y_cached = self._get_metric_xy(
            {
                'host': host,
                'metric': 'memory.memory-cached',
                'factor': factor,
            }, x)
        _, y_buffered = self._get_metric_xy(
            {
                'host': host,
                'metric': 'memory.memory-buffered',
                'factor': factor,
            }, x)
        _, y_free = self._get_metric_xy(
            {
                'host': host,
                'metric': 'memory.memory-free',
                'factor': factor,
            }, x)

        # ----
        # It is possible that the mqtt based metric collector produces
        # CSV files with different numbers of lines. We cut all of them
        # to a combined minimum length.
        # ----
        min_len = min(len(x), len(y_used), len(y_cached), len(y_buffered),
                      len(y_free))
        x = x[:min_len]
        y_used = y_used[:min_len]
        y_cached = y_cached[:min_len]
        y_buffered = y_buffered[:min_len]
        y_free = y_free[:min_len]

        plt.stackplot(x,
                      y_used,
                      y_cached,
                      y_buffered,
                      y_free,
                      colors=[
                          'b',
                          'y',
                          'g',
                          'gray',
                      ],
                      labels=[
                          'Used',
                          'Cached',
                          'Buffered',
                          'Free',
                      ])

        # ----
        # Title and labels
        # ----
        plt.set_title(title)
        plt.set_xlabel("Elapsed Minutes")
        plt.set_ylabel(unit)
        plt.legend(loc='upper left')
        plt.grid()

        # ----
        # Now turn this into an in-memory SVG and return it as requested
        # (raw or b64-encoded)
        # ----
        buf = io.StringIO()
        pyplot.savefig(buf, format='svg')

        if not b64encode:
            return buf.getvalue()
        return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
Esempio n. 11
0
    def cpu_svg(self,
                host=None,
                title="CPU Usage",
                ylabel="Percent",
                b64encode=True):
        fig = pyplot.figure(figsize=self.FIGSIZE)

        h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)]
        v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]

        divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
        plt = Axes(fig, divider.get_position())
        plt.set_axes_locator(divider.new_locator(nx=1, ny=1))

        fig.add_axes(plt)

        result = self.result
        runinfo = result.runinfo

        # ----
        # The X limits are -rampupMins, runMins, Y limits are 0..100
        # ----
        plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins']))
        plt.set_ylim(0, 100)
        plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1)

        # ----
        # Gather all the relevant data
        # ----
        x, y_user = self._get_metric_xy({
            'host': host,
            'metric': 'cpu.percent-user',
        })
        _, y_sys = self._get_metric_xy(
            {
                'host': host,
                'metric': 'cpu.percent-system',
            }, x)
        _, y_wait = self._get_metric_xy(
            {
                'host': host,
                'metric': 'cpu.percent-wait',
            }, x)
        _, y_intr = self._get_metric_xy(
            {
                'host': host,
                'metric': 'cpu.percent-interrupt',
            }, x)
        _, y_softirq = self._get_metric_xy(
            {
                'host': host,
                'metric': 'cpu.percent-softirq',
            }, x)
        _, y_idle = self._get_metric_xy(
            {
                'host': host,
                'metric': 'cpu.percent-idle',
            }, x)

        # ----
        # It is possible that the mqtt based metric collector produces
        # CSV files with different numbers of lines. We cut all of them
        # to a combined minimum length.
        # ----
        min_len = min(len(x), len(y_user), len(y_sys), len(y_wait),
                      len(y_intr), len(y_softirq), len(y_idle))
        x = x[:min_len]
        y_user = y_user[:min_len]
        y_sys = y_sys[:min_len]
        y_wait = y_wait[:min_len]
        y_intr = y_intr[:min_len]
        y_softirq = y_softirq[:min_len]
        y_idle = y_idle[:min_len]

        # ----
        # Plot the CPU usage
        # ----
        plt.stackplot(x,
                      y_user,
                      y_sys,
                      y_wait,
                      y_intr,
                      y_softirq,
                      y_idle,
                      colors=[
                          'g',
                          'b',
                          'r',
                          'c',
                          'm',
                          'y',
                      ],
                      labels=[
                          'User',
                          'System',
                          'Wait',
                          'Interrupt',
                          'SoftIrq',
                          'Idle',
                      ])

        # ----
        # Title and labels
        # ----
        plt.set_title(title)
        plt.set_xlabel("Elapsed Minutes")
        plt.set_ylabel(ylabel)
        plt.legend(loc='upper left')
        plt.grid()

        # ----
        # Now turn this into an in-memory SVG and return it as requested
        # (raw or b64-encoded)
        # ----
        buf = io.StringIO()
        pyplot.savefig(buf, format='svg')

        if not b64encode:
            return buf.getvalue()
        return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
Esempio n. 12
0
    def metric_svg(self,
                   host=None,
                   title="undefined",
                   ylabel="undefined",
                   metrics=[],
                   b64encode=True):
        fig = pyplot.figure(figsize=self.FIGSIZE)

        h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)]
        v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]

        divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
        plt = Axes(fig, divider.get_position())
        plt.set_axes_locator(divider.new_locator(nx=1, ny=1))

        fig.add_axes(plt)

        result = self.result
        runinfo = result.runinfo

        # ----
        # The X limits are -rampupMins, runMins
        # ----
        plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins']))
        plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1)

        # ----
        # Draw all the requested graphs
        # ----
        x = None
        for m in metrics:
            if x is None:
                x, y = self._get_metric_tree(m)
            else:
                _, y = self._get_metric_tree(m, x)

            plt.plot(x, y, m['color'], label=m['label'])

        # ----
        # Title and labels
        # ----
        plt.set_title(title)
        plt.set_xlabel("Elapsed Minutes")
        plt.set_ylabel(ylabel)
        plt.legend(loc='upper left')
        plt.grid()

        # ----
        # Now turn this into an in-memory SVG and return it as requested
        # (raw or b64-encoded)
        # ----
        buf = io.StringIO()
        pyplot.savefig(buf, format='svg')

        if not b64encode:
            return buf.getvalue()
        return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
Esempio n. 13
0
    def tpmc_svg(self, b64encode=True):
        fig = pyplot.figure(figsize=self.FIGSIZE)

        h = [Size.Fixed(1.2), Size.Scaled(1.), Size.Fixed(.2)]
        v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]

        divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
        plt = Axes(fig, divider.get_position())
        plt.set_axes_locator(divider.new_locator(nx=1, ny=1))

        fig.add_axes(plt)

        result = self.result
        runinfo = result.runinfo

        # ----
        # The X limits are -rampupMins, runMins
        # ----
        plt.set_xlim(-int(runinfo['rampupMins']), int(runinfo['runMins']))
        plt.axvspan(-int(runinfo['rampupMins']), 0, facecolor='0.2', alpha=0.1)

        # ----
        # offset the timestamps by -rampupMins so that the graph
        # starts with negative minutes elapsed and switches to
        # positive when the measurement begins.
        # ----
        offset = (int(runinfo['rampupMins'])) * 60.0

        # ----
        # NEW_ORDER transactions per minute. First get the timestamp
        # and number of transactions from the result data.
        # The X vector then is the sorted unique timestamps rounded
        # to an interval.
        # ----
        interval = 10
        data = numpy.array([[(int(tup[0] / interval) * interval - offset) / 60,
                             tup[1] * (60 / interval)]
                            for tup in result.result_ttype['NEW_ORDER']])
        x = sorted(numpy.unique(data[:, 0]))

        # ----
        # The Y vector is the sums of transactions grouped by X
        # ----
        y = []
        for ts in x:
            tmp = data[numpy.where(data[:, 0] == ts)]
            y.append(numpy.sum(tmp[:, 1]))

        # ----
        # Plot the NOPM and add all the decorations
        # ----
        plt.plot(x, y, 'b')
        plt.set_title("NEW_ORDER Transactions per Minute (tpmC)")
        plt.set_xlabel("Elapsed Minutes")
        plt.set_ylabel("tpmC")
        plt.grid()

        buf = io.StringIO()
        pyplot.savefig(buf, format='svg')

        if not b64encode:
            return buf.getvalue()
        return base64.b64encode(buf.getvalue().encode('utf-8')).decode('utf-8')
Esempio n. 14
0
    # rgba = colors.hsv_to_rgb(hsv)
    # rgba = np.dstack([rgba, alpha])
    # # else:
    # hsv[:, :, 2] = alpha.clip(min=0.2, max=value)
    # rgba_l = colors.hsv_to_rgb(hsv)
    # alpha_l = np.abs(1 - alpha).clip(min=value, max=1)
    # hsv[:, :, 2] = alpha_l
    # rgba_lr = colors.hsv_to_rgb(hsv)

    cmap = colors.ListedColormap(cmap, name='test1')

fig = plt.figure(1, figsize=(12, 8))
h = [Size.Fixed(0.), Size.Fixed(6.5)]
v = [Size.Fixed(0.5), Size.Fixed(3.25)]
win = Divider(fig, (0.1, 0.1, 0.8, 0.8), h, v, aspect=False)
ax = Axes(fig, win.get_position())
ax.set_axes_locator(win.new_locator(nx=1, ny=1))
fig.add_axes(ax)
# fig = plt.gcf()
for ii in range(1, 2):
    if ii == 0:
        to_plot = rgb
        title = 'Model'
    elif ii == 1:
        to_plot = rgba
        title = 'Model + Resolution (Transparency)'
    elif ii == 2:
        to_plot = rgba_l
        title = 'Model + Resolution (Lightness)'
    else:
        to_plot = rgba_lr
x = x[no_nans]
y = y[no_nans]
var_p = var_p[no_nans]
all_cell_p = all_cell_p[no_nans]
all_dVm = all_dVm[no_nans]
# make the scatter
s_cell = 20
#fig, ax = plt.subplots(1, 1, figsize=[1.75, 1.75])
# create a figure with axes of defined size
fig = plt.figure(figsize=[2.5, 2.5])
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(0.75), Size.Fixed(1.4)]
v = [Size.Fixed(0.75), Size.Fixed(1.4)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
ax.scatter(x[all_cell_p < 0.05],
           y[all_cell_p < 0.05],
           s=10,
           facecolors='none',
           edgecolors=c_hyp,
           zorder=3)
ax.scatter(x[(all_cell_p < 0.05) & (var_p < 0.05)],
           y[(all_cell_p < 0.05) & (var_p < 0.05)],
           s=s_cell,
           facecolors=c_hyp,
           edgecolors=c_hyp,
           zorder=3)
ax.scatter(x[all_cell_p > 0.95],
if measure == 'duration':
    bins = np.arange(0, 30, 0.01)
if measure == 'pupil':
    bins = np.arange(0, 50, 0.1)
if measure == 'norm_pupil':  # use this one
    bins = np.arange(1, 3, 0.001)
if measure == 'theta_delta':
    bins = np.arange(-2, 4, 0.01)
# create a figure with axes of defined size
fig = plt.figure(figsize=[1.6, 1.6])
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(0.5), Size.Fixed(0.9)]
v = [Size.Fixed(0.5), Size.Fixed(0.8)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
if measure == 'norm_pupil':
    ax.hist([states[0][measure][np.isnan(states[0][measure]) == 0],
              states[1][measure][np.isnan(states[1][measure]) == 0],
              states[2][measure][np.isnan(states[2][measure]) == 0],
              states[3][measure][np.isnan(states[3][measure]) == 0]],
             bins=bins, color=[c_grn, c_run_theta, c_bwn, c_mgry], density=True,
             label=['run theta', 'rest theta', 'LIA', 'nost'], histtype='step',
             cumulative=True)
else:
    ax.hist([states[0][measure][np.isnan(states[0][measure]) == 0],
              states[1][measure][np.isnan(states[1][measure]) == 0],
              states[2][measure][np.isnan(states[2][measure]) == 0]],
             bins=bins, color=[c_grn, c_run_theta, c_bwn], density=True,
#    fig.tight_layout()
#    plt.savefig(os.path.join(fig_folder, 'Rin_scatter_'+state[l]+'.png'),
#                             transparent=True)

# make a stack and bar plot of Rin (change from nost) - theta only
l = 0
s_cell = 40
#fig, ax = plt.subplots(1, figsize=[0.8, 1.5])
# create a figure with axes of defined size
fig = plt.figure(figsize=[2, 2])
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(0.5), Size.Fixed(0.6)]
v = [Size.Fixed(0.5), Size.Fixed(1.1)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
for i in np.arange(len(data)):
    cell_Rin_nost = np.nanmean(data[i]['Rin'][data[i]['nost_Rin']])
    cell_Rin_state = np.nanmean(data[i]['Rin'][data[i][state[l] + '_Rin']])
    cell_Rin_state = (cell_Rin_state - cell_Rin_nost) / cell_Rin_nost
    if state_Rin_t_p[i, l] < 0.05:
        ax.scatter(random.uniform(0, 1),
                   cell_Rin_state,
                   facecolors=c_state[l],
                   edgecolors=c_state[l],
                   zorder=2,
                   s=s_cell)
    else:
        ax.scatter(random.uniform(0, 1),
    'axes.titlesize': 30,
    'xtick.labelsize': 30,
    'ytick.labelsize': 30,
    'legend.fontsize': 30
}
plt.rcParams.update(params)

fig = plt.figure(figsize=(11, 9))

h = [Size.Fixed(1.8), Size.Fixed(8.5)]
v = [Size.Fixed(1.2), Size.Fixed(7.5)]

divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
# the width and height of the rectangle is ignored.

ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))

fig.add_axes(ax)

ax.set_yscale('log')
ax.set_xlim(-500, 10000)
ax.set_ylim(bottom=1e-4, top=1e4)
ax.set_xlabel('Iteration')
ax.set_ylabel('Imitation Loss')
ax.tick_params(axis='both', which='major')
ax.set_facecolor('#E6E6E6')
ax.grid()
ax.set_position([1, 1, 10, 6])

# load inverse kkt results
Esempio n. 19
0
def segtrends(x, segments=2, charts=True):
    """
    Turn minitrends to iterative process more easily adaptable to
    implementation in simple trading systems; allows backtesting functionality.
    :param x: One-dimensional data set
    :param window: How long the trendlines should be. If window < 1, then it
                   will be taken as a percentage of the size of the data
    :param charts: Boolean value saying whether to print chart to screen
    """

    import numpy as np
    y = np.array(x['Close'])
    #    for i in range(len(y),1200):
    #        y = np.append(y, y[len(y)-1])

    # Implement trendlines
    segments = int(segments)
    maxima = np.ones(segments)
    minima = np.ones(segments)
    segsize = int(len(y) / segments)
    for i in range(1, segments + 1):
        ind2 = i * segsize
        ind1 = ind2 - segsize
        maxima[i - 1] = max(y[ind1:ind2])
        minima[i - 1] = min(y[ind1:ind2])

    # Find the indexes of these maxima in the data
    x_maxima = np.ones(segments)
    x_minima = np.ones(segments)
    for i in range(0, segments):
        x_maxima[i] = np.where(y == maxima[i])[0][0]
        x_minima[i] = np.where(y == minima[i])[0][0]

    if charts:
        import matplotlib.pyplot as plt
        plt.rc('font', size=6)
        fig = plt.figure(figsize=(8, 6))
        h = [Size.Fixed(0.5), Size.Fixed(7.)]
        v = [Size.Fixed(0.7), Size.Fixed(5.)]
        divider = Divider(fig, (0.0, 0.0, 0., 0.), h, v, aspect=False)
        ax = Axes(fig, divider.get_position())
        ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
        fig.add_axes(ax)
        plt.plot(y, linewidth=1)
        plt.grid(True)

    for i in range(0, segments - 1):
        maxslope = (maxima[i + 1] - maxima[i]) / (x_maxima[i + 1] -
                                                  x_maxima[i])
        a_max = maxima[i] - (maxslope * x_maxima[i])
        b_max = maxima[i] + (maxslope * (len(y) + 300 - x_maxima[i]))
        maxline = np.linspace(a_max, b_max, len(y) + 300)

        minslope = (minima[i + 1] - minima[i]) / (x_minima[i + 1] -
                                                  x_minima[i])
        a_min = minima[i] - (minslope * x_minima[i])
        b_min = minima[i] + (minslope * (len(y) + 300 - x_minima[i]))
        minline = np.linspace(a_min, b_min, len(y) + 300)

        if charts:
            plt.plot(maxline, 'g', linewidth=0.15)
            plt.plot(minline, 'r', linewidth=.15)

    if charts:
        #plt.show()
        plt.ylim(min(y[-120:] * .9), max(y[-120:] * 1.1))
        plt.rc('xtick', labelsize=6)
        plt.xticks(range(0, 1200, 4), x.index[range(0, 910, 4)], rotation=90)
        plt.rc('xtick', labelsize=6)
        plt.xlim(800, 1000)
        #        plt.xlim(datetime.datetime(2016,1,1),datetime.datetime(2022,1,1))
        plt.savefig('C:/git/TRADE/chart.png', dpi=750)
        plt.close()

    # OUTPUT
    return x_maxima, maxima, x_minima, minima
        # remove outliers
        values = data[i]['th_dist'][data[i][ntl[l] + '_thresh_bool']]
        values = values[np.logical_and(values > -15, values < 0)]
        measure[i, l] = -1 * np.nanmedian(values)
# remove unwanted cells
measure = measure[keep_cells_thresh, :]
# make the plot
#fig, ax = plt.subplots(1, figsize=[1.5, 1.75])
# create a figure with axes of defined size
fig = plt.figure(figsize=[2, 2])
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(0.5), Size.Fixed(1.1)]
v = [Size.Fixed(0.5), Size.Fixed(1.2)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
line_x = np.array([1.75, 3.25])
bar_x = np.array([1, 4])
y = measure[:, d_l]
dVm = states[d_l[-1] - 1]['cell_dVm'][keep_cells_thresh]
for i in np.arange(y.shape[0]):
    ax.plot(line_x, y[i, :], color=c_lgry, zorder=1)
    if dVm[i] == -1:
        ax.plot(line_x, y[i, :], color=c_hyp, zorder=2)
    elif dVm[i] == 1:
        ax.plot(line_x, y[i, :], color=c_dep, zorder=2)
for l in np.arange(y.shape[1]):
    # remove nans
    no_nan = y[:, l]
Esempio n. 21
0
def plot_it():
    # fig = plt.figure(1, figsize=(8, 4.5))
    fig = plt.figure(1, figsize=(16, 12))
    # h = [Size.Fixed(0.), Size.Fixed(6.5)]
    # v = [Size.Fixed(0.5), Size.Fixed(3.25)]
    h = [Size.Fixed(0.), Size.Fixed(13)]
    v = [Size.Fixed(0.5), Size.Fixed(7)]
    win = Divider(fig, (0.1, 0.08, 0.8, 0.8), h, v, aspect=False)
    ax = Axes(fig, win.get_position())
    ax.set_axes_locator(win.new_locator(nx=1, ny=1))
    fig.add_axes(ax)
    # fig = plt.figure(figsize=(16, 12))
    # ax = fig.add_subplot(111)
    for ii, ellipse in enumerate(ellipses):
        ax.fill(ellipse[0], ellipse[1], color=cmap(norm_vals[ii]), zorder=0)
        ax.plot(ellipse[0], ellipse[1], 'k-', linewidth=0.2)
    ax.invert_yaxis()
    plt.xlabel('Northing (km)', fontsize=16)
    plt.ylabel(r'$\log_{10}$ Period (s)', fontsize=16)
    # ax.set_aspect(1)
    ax.tick_params(axis='both', labelsize=14)
    # locs, labels = plt.xticks()
    # plt.xticks(locs, [int(x * 10) for x in locs])
    fake_vals = np.linspace(lower, upper, len(fill_vals))
    fake_im = ax.scatter(loc, periods, c=fake_vals, cmap=cmap)
    fake_im.set_visible(False)
    # ax.set_ylim([-2.6, 3.25])
    # ax.set_xlim([526.5, 538.2])
    # ax.invert_yaxis()
    # cb = plt.colorbar(mappable=fake_im)
    #############################################
    # Colour bar and site labelling
    # cbaxes = fig.add_axes([0.925, 0.1351, 0.015, 0.72])
    # cb = plt.colorbar(fake_im)
    # if 'phi' in fill_param[:3]:
    #     label = r'${}{}(\degree)$'.format('\phi', fill_param[-2:])
    # else:
    #     label = r'$\{}(\degree)$'.format(fill_param)
    # cb.set_label(label,
    #              rotation=270,
    #              labelpad=20,
    #              fontsize=18)
    # ax.tick_params(axis='both', labelsize=14)
    # ax.set_xlim(x_lim)
    # for ii, site in enumerate(main_sites):
    #     txt = site[-4:-1]
    #     if linear_xaxis:
    #         ax.text(linear_site[ii],
    #                 label_offset, site, rotation=45)  # 3.6
    #     else:
    #         ax.text(main_transect.sites[site].locations['X'],
    #                 label_offset, site, rotation=45)  # 3.6

    plt.show()
    return fig
Esempio n. 22
0
l = 0

# scatter dVm vs Vm0 for theta and LIA
# prep the bools to separate events with and without holding current
Ih0 = (np.abs(events[l]['Ih']) < 10)
# make the scatter
#fig, ax = plt.subplots(1, 1, figsize=[2.2, 1.8])
# create a figure with axes of defined size
fig = plt.figure(figsize=[2, 2])
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(0.5), Size.Fixed(1.3)]
v = [Size.Fixed(0.5), Size.Fixed(1.1)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
ax.scatter(events[l]['Vm0'][Ih0],
           events[l]['dVm'][Ih0],
           s=10,
           facecolors=c_state[l],
           edgecolors=c_state[l])
ax.set_ylim([-15, 15])
ax.set_xlim([-70, -20])
ax.set_yticks([-15, 0, 15])
ax.set_xticks([-60, -40, -20])
ax.tick_params(top=False, right=False, length=6)
ax.spines['left'].set_bounds(-15, 15)
ax.set_xlabel('initial Vm (mV)')
ax.set_ylabel(r'$\Delta$ Vm (mV)', labelpad=0)
Esempio n. 23
0
    sumFinalAnalysisTE = np.matmul(-np.transpose(npTE), lstFinalAnalysis)
    A = np.array([[ndados, sumTE], [sumTE, prodTE]])
    B = np.array([[sumFinalAnalysis], [sumFinalAnalysisTE]])
    invA = np.linalg.inv(A)
    P = np.matmul(invA, B)
    T2[indexValue] = (P[1][0])

for i, t in enumerate(T2):
    T2[i] = math.inf if t[0] == 0 else 1000 / t[0]

T2Star = np.reshape(T2, (400, 400))
fig = plt.figure(figsize=(6, 6))
h = [Size.Fixed(1.0), Size.Fixed(5.)]
v = [Size.Fixed(1.0), Size.Fixed(5.)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
plt.pcolor(np.flip(T2Star, 0), cmap=jet_combined, vmin=0, vmax=180)
toc = time.perf_counter()
print(f"Executed in {toc - tic:0.4f} seconds")

# toggle_selector.RS = RectangleSelector(ax, line_select_callback,
#                                        drawtype='box', useblit=True,
#                                        button=[1, 3],  # don't use middle button
#                                        minspanx=5, minspany=5,
#                                        spancoords='pixels',
#                                        interactive=True)

# plt.connect('key_press_event', toggle_selector)
plt.show()
S = np.full([len(all_cells), 2], np.nan)
for i in np.arange(len(all_cells)):
    values = df[measure][(df['cell_id'] == all_cells[i])]
    S[i, 0] = np.nanmean(values)
    values = th_df[measure][(th_df['cell_id'] == all_cells[i])]
    S[i, 1] = np.nanmean(values)
      
#fig, ax = plt.subplots(1, figsize=[1.5, 1.5])
# create a figure with axes of defined size
fig = plt.figure(figsize=[2, 2])
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(0.5), Size.Fixed(1.1)]
v = [Size.Fixed(0.5), Size.Fixed(1.3)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
bar_x = np.array([1, 4])
line_x = np.array([0.75, 2.25])
for i in np.arange(S.shape[0]):
    for l in np.arange(S.shape[1]-1):
        ax.plot(bar_x[l]+line_x, S[i, l:l+2], color=c_small, zorder=1)
    if measure == 'amplitude':
        if S[i, 0] > 5:
            ax.plot(bar_x[l]+line_x, S[i, l:l+2], color=c_big, zorder=2)
        ax.set_yticks([0, 10, 20, 30, 40, 50, 60])
        ax.set_yticklabels([0, '', 20, '', 40, '', 60])
        ax.set_ylim([0, 60])
        ax.set_ylabel('amplitude (mV)')
    if measure == 'rise_time':