def _plot_image(self, index):

        # Setup figure
        fig = plt.figure(figsize=(20.0, 8.0), dpi=80)
        fig.subplots_adjust(wspace=0, hspace=0)
        ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
        ax2 = plt.subplot2grid((3, 1), (2, 0))

        # Get time array
        time_array = np.arange(self.waveforms.shape[1]) * 1 / self.graph.network.hyper_params['fs']

        # Get labels
        label = self.labels[index]

        # Get logits
        logits = self.logits[index, :]

        # Get softmax
        sigmoid = expit(logits)

        # Get prediction
        prediction = int(np.squeeze(np.argmax(sigmoid)))

        # Get non-zero-pad indices
        non_zero_index = np.where(self.waveforms[index, :, 0] != 0)[0]
Beispiel #2
0
    def hrd(self, z='Nstars', bins=200):
        ax1 = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2)
        ax2 = plt.subplot2grid((3, 3), (0, 0), colspan=2)
        ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
        l = ax1.scatter(data1['LOG_TE'],
                        data1['LOG_L'],
                        c=data1['MASS'],
                        edgecolors='none',
                        cmap=plt.cm.Blues)

        if z != 'Nstars':
            N, xe, ye = self.bs2d('LOG_TE', 'LOG_L', z, bins=bins)
            l = ax.imshow(N.T,
                          extent=[xe[-1], xe[0], ye[-1], ye[0]],
                          cmap=plt.cm.Blues,
                          interpolation='nearest',
                          aspect=0.1)
            cb = plt.colorbar(l)
        else:
            pass

        ax.set_xlabel(r'$\log\ T_{\rm{eff}}\ \rm{(K)}$', fontsize=20)
        ax.set_ylabel(r'$\log\ L\ {\rm{(L_\odot)}}$', fontsize=20)
        ax.set_title(r'$Z=%.4f\ \log {\rm{Age:}} %g-%g$' %
                     (self.logz, self.lagei, self.lagef),
                     fontsize=12)
        ax.set_xlim(ax.get_xlim()[::-1])
        ax.set_ylim(ax.get_ylim()[::-1])
        cb.set_label('$%s$' % z, fontsize=16)
        return ax
Beispiel #3
0
def plot_figure5():
    """ Plot Figure 5, see text for more details regarding Figure 3.
    """
    N, M = 10000, 70000  # Temporal window - get rid of transient

    # Load data
    base = "../data/"
    t = np.load(base + "Fig5_V.npy")[N:, 0]
    v = np.load(base + "Fig5_V.npy")[N:, 1]
    h = np.load(base + "Fig5_V.npy")[N:, 2]

    # Plot phase plane
    fig = plt.figure(figsize=(8, 10))
    fig.subplots_adjust(wspace=1., hspace=1.)
    ax = plt.subplot2grid((7, 3), (0, 0), colspan=3, rowspan=4)
    ax.plot(h, v, 'k', lw=1)
    ax.set_ylim([-80, 20])
    ax.set_xlim([0, 0.1])
    ax.set_ylabel("V (mV)", fontsize=16, weight='bold')
    ax.set_xlabel("h", fontsize=15, weight='bold')
    ticks = ax.get_xticks()
    ax.set_xticklabels(ticks, fontsize=15, weight='bold')
    ticks = ax.get_yticks()
    ax.set_yticklabels(ticks, fontsize=15, weight='bold')

    # Plot membrane potential
    ax = plt.subplot2grid((7, 3), (4, 0), colspan=3, rowspan=2)
    ax.plot(t, v, 'k', lw=1)
    ax.set_ylim([-80, 20])
    ax.set_xticks([])
    ax.set_ylabel("V (mV)", fontsize=16, weight='bold')
    ticks = ax.get_yticks().astype('i')
    ax.set_yticklabels(ticks, fontsize=15, weight='bold')
    ax.get_yaxis().set_tick_params(which='both', direction='out')
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    # Plot h
    ax = plt.subplot2grid((7, 3), (6, 0), colspan=3, rowspan=1)
    ax.plot(t, h, 'b', lw=1)
    ax.set_ylim([0.017, 0.077])
    ax.set_xlabel("Time (s)", fontsize=16, weight='bold')
    ax.set_ylabel("h", fontsize=16, weight='bold')
    ticks = ax.get_xticks().astype('i')
    ticks = [i / 1000 for i in ticks]
    ax.set_xticklabels(ticks, fontsize=15, weight='bold')
    ax.set_yticks([0.02, 0.07])
    ticks = ax.get_yticks()
    ax.set_yticklabels(ticks, fontsize=15, weight='bold')
    ax.get_xaxis().set_tick_params(which='both', direction='out')
    ax.get_yaxis().set_tick_params(which='both', direction='out')
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    plt.savefig('../article/figs/Figure5.pdf', axis='tight')
Beispiel #4
0
def quicklook_wf(wfo, logAmp=True, show=True):

    after_dm = proper.prop_get_amplitude(wfo)
    phase_afterdm = proper.prop_get_phase(wfo)

    fig = plt.figure(figsize=(14, 10))
    ax1 = plt.subplot2grid((3, 2), (0, 0), rowspan=2)
    ax2 = plt.subplot2grid((3, 2), (0, 1), rowspan=2)
    ax3 = plt.subplot2grid((3, 2), (2, 0))
    ax4 = plt.subplot2grid((3, 2), (2, 1))
    if logAmp:
        ax1.imshow(after_dm, origin='lower', cmap="YlGnBu_r", norm=LogNorm())
    else:
        ax1.imshow(after_dm, origin='lower', cmap="YlGnBu_r")
    ax2.imshow(phase_afterdm, origin='lower',
               cmap="YlGnBu_r")  #, vmin=-0.5, vmax=0.5)

    ax3.plot(after_dm[int(tp.grid_size / 2)])
    ax3.plot(np.sum(np.eye(tp.grid_size) * after_dm, axis=1))

    # plt.plot(np.sum(after_dm,axis=1)/after_dm[128,128])

    ax4.plot(phase_afterdm[int(tp.grid_size / 2)])
    # ax4.plot(np.sum(np.eye(tp.grid_size)*phase_afterdm,axis=1))
    plt.xlim([0, proper.prop_get_gridsize(wfo)])
    fig.set_tight_layout(True)
    if show == True:
        plt.show()
Beispiel #5
0
    def render(self, state):
        width = self.resolution[0] / self.dpi
        height = self.resolution[1] / self.dpi
        fig = plt.figure(0, figsize=(width, height), dpi=self.dpi)

        current, wait, backlog, time = state
        lines = current.shape[0]

        # Axes {{{
        axs_current = [
            plt.subplot2grid((lines, 3), (i, 0)) for i in range(lines)
        ]
        axs_wait = [plt.subplot2grid((lines, 3), (i, 1)) for i in range(lines)]
        ax_backlog = plt.subplot2grid((lines, 3), (0, 2), rowspan=lines)
        # End of Axes }}}

        for i, (ax_current, ax_wait) in enumerate(zip(axs_current, axs_wait)):
            self.plot_substate(ax_current, f'Current resources {i}',
                               current[i])
            self.plot_substate(ax_wait, f'Waiting jobs stack {i}',
                               np.mean(wait[i], axis=0))
        self.plot_substate(ax_backlog, 'Backlog', backlog, True)

        fig.tight_layout()
        canvas = agg.FigureCanvasAgg(fig)
        canvas.draw()
        renderer = canvas.get_renderer()
        raw_data = renderer.tostring_rgb()
        size = canvas.get_width_height()
        plt.close(fig)

        return np.frombuffer(raw_data, dtype=np.uint8).reshape(
            (size[0], size[1], 3))
Beispiel #6
0
def plotPriceAndTradeSignals(valData):
    fig = plt.figure(figsize=(12, 8))
    #plt.figure(figsize=(9,4))
    #plt.title('Comparison of beLong vs. Predicted beLong')
    plt.subplots_adjust(hspace=0.05)
    fig.suptitle('Comparison of beLong vs. Predicted beLong')
    #plt.title('Comparison of beLong vs. Predicted beLong')
    ax1 = plt.subplot2grid((5, 1), (0, 0), rowspan=3, colspan=1)
    ax2 = plt.subplot2grid((5, 1), (3, 0), rowspan=1, colspan=1)
    ax3 = plt.subplot2grid((5, 1), (4, 0), rowspan=1, colspan=1)

    ax2.plot(valData['valBeLong'], color='green', alpha=0.6)
    ax1.plot(valData['Close'])
    ax3.plot(valData['beLong'], color='purple', alpha=0.6)

    ax1.label_outer()
    ax2.label_outer()
    ax2.tick_params(axis='x', which='major', bottom=True)

    axes = [ax1, ax2, ax3]
    for x in range(len(axes)):
        axes[x].grid(True, which='major', color='k', linestyle='-', alpha=0.6)
        axes[x].grid(True, which='minor', color='r', linestyle='-', alpha=0.2)
        axes[x].minorticks_on()
        axes[x].legend(loc='upper left', frameon=True, fontsize=10)
        axes[x].label_outer()
    plt.show(block=True)
Beispiel #7
0
def survival_and_stats(feature, surv, upper_lim=5, axs=None, figsize=(7, 5), title=None,
                       order=None, colors=None, **args):
    if axs is None:
        fig = plt.figure(figsize=figsize)
        ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=2)
        ax2 = plt.subplot2grid((3, 3), (2, 0), colspan=2)
        ax3 = plt.subplot2grid((3, 3), (2, 2))
    else:
        ax1, ax2, ax3 = axs
        fig = plt.gcf()
    if feature.dtype != str:
        feature = feature.astype(str)
    if colors is None:
        colors = colors_global
    
    t = get_surv_fit(surv, feature)
    if order is None:
        t = t.sort([('5y Survival', 'Surv')], ascending=True)
    else:
        t = t.ix[order]
    survival_stat_plot(t, axs=[ax2, ax3], upper_lim=upper_lim, colors=colors)
    r = pd.Series({s:i for i, s in enumerate(t.index)})
    color_lookup = {c: colors[i % len(colors)] for i, c in enumerate(t.index)}
    
    draw_survival_curve(feature, surv, ax=ax1, colors=color_lookup, **args)
    ax1.legend().set_visible(False)
    if title:
        ax1.set_title(title)
    
    fig.tight_layout()
Beispiel #8
0
    def show_results(self, ag_attr='language', step=None,
                     plot_results=True, plot_type='imshow', save_fig=False):

        grid_size = (3, 5)
        self.create_agents_attrs_data(ag_attr)

        data_2_plot = self.datacollector.get_model_vars_dataframe()[:step]
        data_2D = self.df_attrs_avg.reset_index()

        ax1 = plt.subplot2grid(grid_size, (0, 3), rowspan=1, colspan=2)
        data_2_plot[["count_bil", "count_cat", "count_spa"]].plot(ax=ax1, title='lang_groups')
        ax1.xaxis.tick_bottom()
        ax1.legend(loc='best', prop={'size': 8})
        ax2 = plt.subplot2grid(grid_size, (1, 3), rowspan=1, colspan=2)
        data_2_plot['total_num_agents'].plot(ax=ax2, title='num_agents')
        ax3 = plt.subplot2grid(grid_size, (2, 3), rowspan=1, colspan=2)
        data_2_plot[['biling_evol_h', 'biling_evol_s']].plot(ax=ax3, title='biling_quality')
        ax3.legend(loc='best', prop={'size': 8})
        ax4 = plt.subplot2grid(grid_size, (0, 0), rowspan=3, colspan=3)
        if plot_type == 'imshow':
            s = ax4.imshow(self.df_attrs_avg.unstack('x'), vmin=0, vmax=2, cmap='viridis',
                           interpolation='nearest', origin='lower')
        else:
            s = ax4.scatter(data_2D['x'],
                            data_2D['y'],
                            c=data_2D['values'],
                            vmin=0, vmax=2, s=35,
                            cmap='viridis')
        ax4.text(0.02, 0.95, 'time = %.1f' % self.schedule.steps, transform=ax4.transAxes)
        plt.colorbar(s)
        plt.tight_layout()
        if save_fig:
            plt.savefig('step' + str(step) + '.png')
        if plot_results:
            plt.show()
Beispiel #9
0
def quicklook_IQ(wfo, logAmp=False, show=True):
    I = np.real(wfo.wfarr)
    Q = np.imag(wfo.wfarr)

    print(np.sum(I), np.sum(Q))

    I = proper.prop_shift_center(I)
    Q = proper.prop_shift_center(Q)

    fig = plt.figure(figsize=(14, 10))
    ax1 = plt.subplot2grid((3, 2), (0, 0), rowspan=2)
    ax2 = plt.subplot2grid((3, 2), (0, 1), rowspan=2)
    ax3 = plt.subplot2grid((3, 2), (2, 0))
    ax4 = plt.subplot2grid((3, 2), (2, 1))
    if logAmp:
        ax1.imshow(I, origin='lower', cmap="YlGnBu_r", norm=LogNorm())
    else:
        ax1.imshow(I, origin='lower', cmap="YlGnBu_r")
    ax2.imshow(Q, origin='lower', cmap="YlGnBu_r")  # , vmin=-0.5, vmax=0.5)

    ax3.plot(I[int(tp.grid_size / 2)])
    ax3.plot(np.sum(np.eye(tp.grid_size) * I, axis=1))

    # plt.plot(np.sum(after_dm,axis=1)/after_dm[128,128])

    ax4.plot(Q[int(tp.grid_size / 2)])
    # ax4.plot(np.sum(np.eye(tp.grid_size)*phase_afterdm,axis=1))
    plt.xlim([0, proper.prop_get_gridsize(wfo)])
    fig.set_tight_layout(True)
    if show == True:
        plt.show()
Beispiel #10
0
    def __init__(self):

        self.fig = plt.figure()


        # размер поля для графика
        egrid = (4, 2)

        #Описание осей для графиков
        self.ax1 = plt.subplot2grid(egrid, (0, 0), colspan=2, rowspan=2)
        self.ax1.set_title("Курсы валют")
        self.ax1.set_ylabel("Стоимость в рублях")
        self.ax1.set_xlabel("Дата формата м-д")
        self.ax1.grid()


        self.ax2 = plt.subplot2grid(egrid, (2, 0))
        self.ax2.set_ylabel("--> USD")
        self.ax2.set_xlabel("Дата формата м-д")
        self.ax2.grid()

        self.ax3 = plt.subplot2grid(egrid, (2, 1))
        self.ax3.set_ylabel("--> EUR")
        self.ax3.set_xlabel("Дата формата м-д")
        self.ax3.grid()

        self.ax4 = plt.subplot2grid(egrid, (3, 0))
        self.ax4.set_ylabel("--> CNY")
        self.ax4.set_xlabel("Дата формата м-д")
        self.ax4.grid()

        self.ax5 = plt.subplot2grid(egrid, (3, 1))
        self.ax5.set_ylabel("--> JPY")
        self.ax5.set_xlabel("Дата формата м-д")
        self.ax5.grid()
Beispiel #11
0
def pretty_fig(spks, states, t_stop=1000):
    spikes = np.zeros((4, t_stop))
    spks = spks.astype('i')

    for i in range(4):
        idx = spks[0, spks[1, :] == i]
        if len(idx) > 0:
            spikes[i, idx] = 1

    spikes[spikes == 0] = np.nan

    K = 5000
    ax1 = plt.subplot2grid((5, 5), (0, 0), colspan=5, rowspan=1)
    for i in range(4):
        if i == 3:
            col = (0.192, 0.647, 0.796)
            al = 1
        else:
            col = (0.847, 0, 0.329)
            al = 1 - i*0.2
        ax1.plot(spikes[i, :K]+i, '|', c=col, ms=20, mew=3, alpha=al)

    ax1.set_ylim([0, 5])
    ax1.set_xticks([])
    ax1.spines['right'].set_visible(False)
    ax1.spines['top'].set_visible(False)
    ax1.spines['bottom'].set_visible(False)
    ax1.yaxis.set_ticks_position('left')
    ax1.set_ylabel("Neuron", fontsize=22, weight='bold')
    ax1.set_yticklabels(ax1.get_yticks().astype('i'),
                        fontsize=18,
                        weight='bold')

    for i in range(1, 5):
        if i == 1:
            col = (0.192, 0.647, 0.796)
            al = 1
        else:
            col = (0.847, 0, 0.329)
            al = 0.2 + i*0.2
        ax2 = plt.subplot2grid((5, 5), (i, 0), colspan=5, rowspan=1)
        ax2.plot(states[:K, 4-i, 0], c=col, alpha=al)
        ax2.set_ylim([-500, 200])
        ax2.set_yticklabels(ax2.get_yticks().astype('i'),
                            fontsize=18,
                            weight='bold')
        ax2.set_ylabel("V", fontsize=18, weight='bold')
        ax2.spines['top'].set_visible(False)
        ax2.spines['right'].set_visible(False)
        ax2.yaxis.set_ticks_position('left')
        ax2.xaxis.set_ticks_position('bottom')
        if i != 4:
            ax2.spines['right'].set_visible(False)
            ax2.spines['bottom'].set_visible(False)
            ax2.set_xticks([])
        else:
            ax2.set_xlabel("Time (ticks)", fontsize=18, weight='bold')
            ax2.set_xticklabels(ax2.get_xticks().astype('i'),
                                fontsize=18,
                                weight='bold')
Beispiel #12
0
def plot_data(tag):
    data_array = tag.references[0]
    voltage = np.zeros(data_array.data.shape)
    data_array.data.read_direct(voltage)

    x_axis = data_array.dimensions[0]
    time = x_axis.axis(data_array.data_extent[0])

    spike_times = tag.positions[:]

    feature_data_array = tag.features[0].data
    snippets = tag.features[0].data[:]
    single_snippet = tag.retrieve_feature_data(3, 0)[:]

    snippet_time_dim = feature_data_array.dimensions[1]
    snippet_time = snippet_time_dim.axis(feature_data_array.data_extent[1])

    response_axis = plt.subplot2grid((2, 2), (0, 0), rowspan=1, colspan=2)
    single_snippet_axis = plt.subplot2grid((2, 2), (1, 0), rowspan=1, colspan=1)
    average_snippet_axis = plt.subplot2grid((2, 2), (1, 1), rowspan=1, colspan=1)

    response_axis.plot(time, voltage, color="dodgerblue", label=data_array.name)
    response_axis.scatter(spike_times, np.ones(spike_times.shape) * np.max(voltage), color="red", label=tag.name)
    response_axis.set_xlabel(x_axis.label + ((" [" + x_axis.unit + "]") if x_axis.unit else ""))
    response_axis.set_ylabel(data_array.label + ((" [" + data_array.unit + "]") if data_array.unit else ""))
    response_axis.set_title(data_array.name)
    response_axis.set_xlim(0, np.max(time))
    response_axis.set_ylim((1.2 * np.min(voltage), 1.2 * np.max(voltage)))
    response_axis.legend()

    single_snippet_axis.plot(snippet_time, single_snippet.T, color="red", label=("snippet No 4"))
    single_snippet_axis.set_xlabel(
        snippet_time_dim.label + ((" [" + snippet_time_dim.unit + "]") if snippet_time_dim.unit else "")
    )
    single_snippet_axis.set_ylabel(
        feature_data_array.label + ((" [" + feature_data_array.unit + "]") if feature_data_array.unit else "")
    )
    single_snippet_axis.set_title("single stimulus snippet")
    single_snippet_axis.set_xlim(np.min(snippet_time), np.max(snippet_time))
    single_snippet_axis.set_ylim((1.2 * np.min(snippets[3, :]), 1.2 * np.max(snippets[3, :])))
    single_snippet_axis.legend()

    mean_snippet = np.mean(snippets, axis=0)
    std_snippet = np.std(snippets, axis=0)
    average_snippet_axis.fill_between(
        snippet_time, mean_snippet + std_snippet, mean_snippet - std_snippet, color="red", alpha=0.5
    )
    average_snippet_axis.plot(snippet_time, mean_snippet, color="red", label=(feature_data_array.name + str(4)))
    average_snippet_axis.set_xlabel(
        snippet_time_dim.label + ((" [" + snippet_time_dim.unit + "]") if snippet_time_dim.unit else "")
    )
    average_snippet_axis.set_ylabel(
        feature_data_array.label + ((" [" + feature_data_array.unit + "]") if feature_data_array.unit else "")
    )
    average_snippet_axis.set_title("spike-triggered average")
    average_snippet_axis.set_xlim(np.min(snippet_time), np.max(snippet_time))
    average_snippet_axis.set_ylim((1.2 * np.min(mean_snippet - std_snippet), 1.2 * np.max(mean_snippet + std_snippet)))

    plt.subplots_adjust(left=0.15, top=0.875, bottom=0.1, right=0.98, hspace=0.35, wspace=0.25)
    plt.show()
Beispiel #13
0
def triple_plot(cccsum, cccsum_hist, trace, threshold, save=False,
                savefile=''):
    r"""Main function to make a triple plot with a day-long seismogram, \
    day-long correlation sum trace and histogram of the correlation sum to \
    show normality.

    :type cccsum: numpy.ndarray
    :param cccsum: Array of the cross-channel cross-correlation sum
    :type cccsum_hist: numpy.ndarray
    :param cccsum_hist: cccsum for histogram plotting, can be the same as \
        cccsum but included if cccsum is just an envelope.
    :type trace: obspy.Trace
    :param trace: A sample trace from the same time as cccsum
    :type threshold: float
    :param threshold: Detection threshold within cccsum
    :type save: bool, optional
    :param save: If True will svae and not plot to screen, vice-versa if False
    :type savefile: str, optional
    :param savefile: Path to save figure to, only required if save=True
    """
    if len(cccsum) != len(trace.data):
        print('cccsum is: ' +
              str(len(cccsum))+' trace is: '+str(len(trace.data)))
        msg = ' '.join(['cccsum and trace must have the',
                        'same number of data points'])
        raise ValueError(msg)
    df = trace.stats.sampling_rate
    npts = trace.stats.npts
    t = np.arange(npts, dtype=np.float32) / (df * 3600)
    # Generate the subplot for the seismic data
    ax1 = plt.subplot2grid((2, 5), (0, 0), colspan=4)
    ax1.plot(t, trace.data, 'k')
    ax1.axis('tight')
    ax1.set_ylim([-15 * np.mean(np.abs(trace.data)),
                  15 * np.mean(np.abs(trace.data))])
    # Generate the subplot for the correlation sum data
    ax2 = plt.subplot2grid((2, 5), (1, 0), colspan=4, sharex=ax1)
    # Plot the threshold values
    ax2.plot([min(t), max(t)], [threshold, threshold], color='r', lw=1,
             label="Threshold")
    ax2.plot([min(t), max(t)], [-threshold, -threshold], color='r', lw=1)
    ax2.plot(t, cccsum, 'k')
    ax2.axis('tight')
    ax2.set_ylim([-1.7 * threshold, 1.7 * threshold])
    ax2.set_xlabel("Time after %s [hr]" % trace.stats.starttime.isoformat())
    # ax2.legend()
    # Generate a small subplot for the histogram of the cccsum data
    ax3 = plt.subplot2grid((2, 5), (1, 4), sharey=ax2)
    ax3.hist(cccsum_hist, 200, normed=1, histtype='stepfilled',
             orientation='horizontal', color='black')
    ax3.set_ylim([-5, 5])
    fig = plt.gcf()
    fig.suptitle(trace.id)
    fig.canvas.draw()
    if not save:
        plt.show()
        plt.close()
    else:
        plt.savefig(savefile)
    return
Beispiel #14
0
def plot(X,
         Y,
         x,
         y,
         acquisition=None,
         next_X=None,
         f=None,
         title=None,
         output=None):
    # Plot posterior samples and their mean, target function, and observations.
    fig = plt.figure()
    if acquisition is not None:
        axs0 = plt.subplot2grid((4, 1), (0, 0), rowspan=3, colspan=1, fig=fig)
    else:
        axs0 = plt.subplot2grid((4, 1), (0, 0), rowspan=4, colspan=1, fig=fig)

    if y is not None:
        num_results = y.shape[0]
        axs0.plot(np.stack([x[:, 0]] * num_results).T, y.T, c='r', alpha=.01)
        mean = np.mean(y, axis=0)
        var = np.var(y, axis=0)
        axs0.plot(x[:, 0], mean, c='k')
        axs0.fill_between(x[:, 0],
                          mean - 2 * np.sqrt(var),
                          mean + 2 * np.sqrt(var),
                          color='C0',
                          alpha=0.2)

    if acquisition is not None:
        axs1 = plt.subplot2grid((4, 1), (3, 0), rowspan=1, colspan=1, fig=fig)
        axs1.plot(x, acquisition)
        axs1.set_yticks([])
        axs1.set_xticks([])
        axs1.set_xlim(axs0.get_xlim())

        if next_X is not None:
            axs1.axvline(x=next_X, color='k', linestyle='--')

    if next_X is not None:
        axs0.axvline(x=next_X, color='k', linestyle='--')

    if f is not None:
        axs0.plot(x[:, 0], f(x))

    axs0.scatter(X[:, 0], Y, zorder=1200)

    if title is not None:
        plt.suptitle(title)

    if output is not None:
        plt.savefig(output)

    plt.tight_layout()

    plt.show()
    plt.close()
Beispiel #15
0
def plot_state_timeseries(state, length):

    ax_main = pylab.subplot2grid((8, 8), (0, 0), colspan=4, rowspan=4)
    ax_main.grid(1)
    plot_state(ax_main, state, 10, length)

    for si, s in enumerate(["x", "y", "phi", "theta"]):
        ax_i = pylab.subplot2grid((8, 8), (4 + si, 0), colspan=8)
        ax_i.plot(state[s])
        ax_i.grid(1)
Beispiel #16
0
def plot_state_timeseries(state, length):

    ax_main = pylab.subplot2grid((8, 8), (0, 0), colspan=4, rowspan=4)
    ax_main.grid(1)
    plot_state(ax_main, state, 10, length)

    for si, s in enumerate(['x', 'y', 'phi', 'theta']):
        ax_i = pylab.subplot2grid((8, 8), (4 + si, 0), colspan=8)
        ax_i.plot(state[s])
        ax_i.grid(1)
Beispiel #17
0
def plots1d(nimages=30,
            nreplicas=4,
            with_hist=True,
            show=True,
            height=5,
            width=8):
    plt.clf()
    fig = plt.gcf()
    fig.set_figheight(height)
    fig.set_figwidth(width)
    if with_hist:
        ncol_hist = 2
    else:
        ncol_hist = 0
    ax_list = [
        plt.subplot2grid((1, nimages + ncol_hist), (0, i),
                         colspan=1,
                         rowspan=nimages) for i in range(nimages)
    ]

    for ax in ax_list:
        ax.set_ylim(0, 1)
        ax.set_xticks([])
        ax.set_yticks([])
        ypos = np.random.uniform(0, 1, nreplicas)
        ymax = ypos.max()
        ax.axhspan(0, ymax, alpha=0.2)
        xpos = np.zeros(nreplicas, )
        ax.scatter(xpos, ypos, c='k', facecolors="none")
        ax.scatter(0, ymax, c='r', linewidths=0, s=40)

    if with_hist:
        ax = plt.subplot2grid((1, nimages + ncol_hist), (0, nimages),
                              colspan=ncol_hist,
                              rowspan=nimages)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_ylim(0, 1)

        n = 100000
        rmax = np.random.beta(nreplicas, 1, size=n)
        ax.hist(rmax,
                bins=old_div(np.sqrt(n), 10),
                orientation='horizontal',
                normed=True)

        if False:
            y = np.arange(1, 0, -.01)
            x = y**(nreplicas - 1)
            x /= x.max()
            ax.plot(x, y)
            ax.relim()

    if show:
        plt.show()
def createRegressionPlots(predictions,performance,coefs,fb_coefs,nfb_coefs,GroupDF,goodsubj,savefig=True):
    f=plt.figure(figsize=(22,12))
    ax1=plt.subplot2grid((2,4),(0,0), colspan=3)
    ax2=plt.subplot2grid((2,4),(0,3))
    ax3=plt.subplot2grid((2,4),(1,0), colspan=2)
    ax4=plt.subplot2grid((2,4),(1,2), colspan=2)

    dmnIdeal=pd.read_csv('/home/jmuraskin/Projects/NFB/analysis/DMN_ideal_2.csv')

    sns.tsplot(data=predictions,time='TR',value='predicted',unit='subj',condition='fb',ax=ax1)
    ax1.plot((dmnIdeal['Wander']-dmnIdeal['Focus'])/3,'k--')
    ax1.set_title('Average Predicted Time Series')

    g=sns.violinplot(data=performance,x='fb',y='R',split=True,bw=.3,inner='quartile',ax=ax2)
    # plt.close(g.fig)

    g=sns.violinplot(data=coefs,x='pe',y='Coef',hue='fb',split=True,bw=.3,inner='quartile',ax=ax3)
    g.plot([-1,len(unique(coefs['pe']))],[0,0],'k--')
    g.set_xlim([-.5,len(unique(coefs['pe']))])
    ylim=g.get_ylim()
    t,p = ttest_1samp(np.array(performance[performance.fb=='FEEDBACK']['R'])-np.array(performance[performance.fb=='NOFEEDBACK']['R']),0)
    ax2.set_title('Mean Subject Time Series Correlations-p=%0.2f' % p)

    t,p = ttest_1samp(np.array(fb_coefs['Coef'].reshape(len(unique(GroupDF[GroupDF.Subject_ID.isin(goodsubj)]['Subject_ID'])),len(unique(coefs['pe'])))),0)
    p05_FB,padj=fdr_correction(p,0.05)
    t,p = ttest_1samp(np.array(nfb_coefs['Coef'].reshape(len(unique(GroupDF[GroupDF.Subject_ID.isin(goodsubj)]['Subject_ID'])),len(unique(coefs['pe'])))),0)
    p05_NFB,padj=fdr_correction(p,0.05)
    for idx,(pFDR_FB,pFDR_NFB) in enumerate(zip(p05_FB,p05_NFB)):
        if pFDR_FB:
            ax3.scatter(idx,ylim[1]-.05,marker='*',s=75)
        if pFDR_NFB:
            ax3.scatter(idx,ylim[0]+.05,marker='*',s=75)


    t,p=ttest_1samp(np.array(fb_coefs['Coef']-nfb_coefs['Coef']).reshape(len(unique(GroupDF[GroupDF.Subject_ID.isin(goodsubj)]['Subject_ID'])),len(unique(coefs['pe']))),0)
    p05,padj=fdr_correction(p,0.05)

    sns.barplot(x=range(len(t)),y=t,ax=ax4,color='Red')
    for idx,pFDR in enumerate(p05):
        if pFDR:
            ax4.scatter(idx,t[idx]+ np.sign(t[idx])*0.2,marker='*',s=75)
    ax4.set_xlim([-0.5,len(unique(coefs['pe']))])
    ax4.set_xlabel('pe')
    ax4.set_ylabel('t-value')
    ax4.set_title('FB vs. nFB PE')

    for ax in [ax1,ax2,ax3,ax4]:
        for item in ([ax.title, ax.xaxis.label, ax.yaxis.label]):
            item.set_fontsize(18)
        for item in (ax.get_xticklabels() + ax.get_yticklabels()):
            item.set_fontsize(12)

    f.tight_layout()
    if savefig:
        f.savefig('%s/RSN_LinearRegPrediction.pdf' % saveFigureLocation,dpi=300)
Beispiel #19
0
def plot_data(tag):
    data_array = tag.references[0]
    voltage = np.zeros(data_array.data.shape)
    data_array.data.read_direct(voltage)

    x_axis = data_array.dimensions[0]
    time = x_axis.axis(data_array.data_extent[0])

    spike_times = tag.positions[:]

    feature_data_array = tag.features[0].data
    snippets = tag.features[0].data[:]

    single_snippet = tag.feature_data(3, 0)[:]

    snippet_time_dim = feature_data_array.dimensions[1]
    snippet_time = snippet_time_dim.axis(feature_data_array.data_extent[1])

    response_axis = plt.subplot2grid((2, 2), (0, 0), rowspan=1, colspan=2)
    single_snippet_axis = plt.subplot2grid((2, 2), (1, 0), rowspan=1, colspan=1)
    average_snippet_axis = plt.subplot2grid((2, 2), (1, 1), rowspan=1, colspan=1)

    response_axis.plot(time, voltage, color='dodgerblue', label=data_array.name)
    response_axis.scatter(spike_times, np.ones(spike_times.shape)*np.max(voltage), color='red', label=tag.name)
    response_axis.set_xlabel(x_axis.label + ((" [" + x_axis.unit + "]") if x_axis.unit else ""))
    response_axis.set_ylabel(data_array.label + ((" [" + data_array.unit + "]") if data_array.unit else ""))
    response_axis.set_title(data_array.name)
    response_axis.set_xlim(0, np.max(time))
    response_axis.set_ylim((1.2 * np.min(voltage), 1.2 * np.max(voltage)))
    response_axis.legend(ncol=2, loc="lower center", fontsize=8)

    single_snippet_axis.plot(snippet_time, single_snippet.T, color="red", label=("snippet No 4"))
    single_snippet_axis.set_xlabel(snippet_time_dim.label + ((" [" + snippet_time_dim.unit + "]") if snippet_time_dim.unit else ""))
    single_snippet_axis.set_ylabel(feature_data_array.label + ((" [" + feature_data_array.unit + "]") if feature_data_array.unit else ""))
    single_snippet_axis.set_title("single stimulus snippet")
    single_snippet_axis.set_xlim(np.min(snippet_time), np.max(snippet_time))
    single_snippet_axis.set_ylim((1.2 * np.min(snippets[3,:]), 1.2 * np.max(snippets[3,:])))
    single_snippet_axis.legend()

    mean_snippet = np.mean(snippets, axis=0)
    std_snippet = np.std(snippets, axis=0)
    average_snippet_axis.fill_between(snippet_time, mean_snippet + std_snippet, mean_snippet - std_snippet, color="tab:red", alpha=0.25)
    average_snippet_axis.plot(snippet_time, mean_snippet, color="red", label=(feature_data_array.name + str(4)))
    average_snippet_axis.set_xlabel(snippet_time_dim.label + ((" [" + snippet_time_dim.unit + "]") if snippet_time_dim.unit else ""))
    average_snippet_axis.set_ylabel(feature_data_array.label + ((" [" + feature_data_array.unit + "]") if feature_data_array.unit else ""))
    average_snippet_axis.set_title("spike-triggered average")
    average_snippet_axis.set_xlim(np.min(snippet_time), np.max(snippet_time))
    average_snippet_axis.set_ylim((1.2 * np.min(mean_snippet - std_snippet), 1.2 * np.max(mean_snippet + std_snippet)))

    plt.subplots_adjust(left=0.15, top=0.875, bottom=0.1, right=0.98, hspace=0.35, wspace=0.25)
    plt.gcf().set_size_inches((5.5, 4.5))
    # plt.savefig("../images/spike_features.png")
    plt.show()
Beispiel #20
0
    def quicklook(self, wf=None, logZ=True, show=True, title=None):
        """
        Produces a figure with an image of amplitude and one of phase as well as 1D slices through these images

        :param wf: optics.Wavefront
        :param logZ: bool logarithmic Z scaling
        :param show: bool display figure now or leave show() to be called by user later on
        :param title: str
        :return:
        """
        if wf == None:
            wf = self.wf_collection[0,0]

        amp_map = proper.prop_get_amplitude(wf)
        phase_map = proper.prop_get_phase(wf)

        fig = plt.figure(figsize=(12, 10))
        ax1 = plt.subplot2grid((1, 2), (0, 0), rowspan=2)  # ((shape of grid to place axis x,y),(location x,y))
        ax2 = plt.subplot2grid((1, 2), (0, 1), rowspan=2)
        # ax3 = plt.subplot2grid((3, 2), (2, 0))
        # ax4 = plt.subplot2grid((3, 2), (2, 1))
        if logZ:
            im1 = ax1.imshow(amp_map, origin='lower', cmap="YlGnBu_r", norm=LogNorm())
        else:
            im1 = ax1.imshow(amp_map, origin='lower', cmap="YlGnBu_r")
        ax1.set_title('Amplitude Map')
        plt.colorbar(im1, ax=ax1)

        im2 = ax2.imshow(phase_map, origin='lower', cmap=sunlight)  # , vmin=-0.5, vmax=0.5)
        ax2.set_title('Phase Map')
        plt.colorbar(im2, ax=ax2)

        # ax3.plot(after_dm[int(sp.grid_size / 2)])
        # ax3.plot(np.sum(np.eye(sp.grid_size) * after_dm, axis=1), label=f'row {int(sp.grid_size / 2)}')
        # ax3.legend()
        #
        # # plt.plot(np.sum(after_dm,axis=1)/after_dm[128,128])
        #
        # ax4.plot(phase_afterdm[int(sp.grid_size / 2)], label=f'row {int(sp.grid_size / 2)}')
        # ax4.legend()
        # # ax4.plot(np.sum(np.eye(ap.grid_size)*phase_afterdm,axis=1))
        # plt.xlim([0, proper.prop_get_gridsize(wf)])
        if not title:
            title = input(f"Always Add A Title\n "
                          f"Please Enter Plane Name:")
            fig.suptitle(f"plane: {title}, lambda: {wf.lamda} m, body: {wf.name}", fontsize=18)
        else:
            fig.suptitle(f"plane: {title}, lambda: {wf.lamda} m, body: {wf.name}", fontsize=18)

        plt.subplots_adjust(top=0.9)

        if show:
            plt.show(block=True)
Beispiel #21
0
def triptych_fitfdiff(tfdata, foci, foci_colors, color_scales, filenames, title=None, lines=True):
    fig = plt.figure(figsize=(28, 8), dpi=200);
    ax1 = plt.subplot2grid((1, 3), (0, 0), colspan=1, rowspan=1)
    panel_fitfdiff(tfdata, title, lines)
    ax1 = plt.subplot2grid((1, 3), (0, 1), colspan=1, rowspan=1)
    panel_mesh_sagittal(foci, foci_colors, color_scales)
    ax1 = plt.subplot2grid((1, 3), (0, 2), colspan=1, rowspan=1)
    panel_mesh_axial(foci, foci_colors, color_scales)
    for filename in filenames:
        plt.savefig(filename, bbox_inches='tight');
    plt.clf();
    plt.close(fig);
Beispiel #22
0
def plot_observed_vs_predicted(observations, predictions, fig=None):
    if fig is None:
        fig = plt.figure(figsize=(9, 9 + 3))
    ax_obs_pred = plt.subplot2grid((3, 4), (0, 1), rowspan=2, colspan=3)
    ax_residuals = plt.subplot2grid((3, 4), (2, 1), colspan=3, sharex=ax_obs_pred)
    ax_residual_kde = plt.subplot2grid((3, 4), (2, 0), sharey=ax_residuals)

    _actual_plot_observed_vs_predicted(observations, predictions, ax=ax_obs_pred)
    plot_residuals(observations, predictions, ax=ax_residuals)
    plot_residual_kde(residuals=observations - predictions, ax=ax_residual_kde)
    ax_residual_kde.set_zorder(-1)
    fig.tight_layout()
    fig.subplots_adjust(hspace=0)
    return fig
Beispiel #23
0
def plot_data(tag):
    data_array = tag.references[0]
    voltage = data_array[:]

    x_axis = data_array.dimensions[0]
    time = x_axis.axis(data_array.data_extent[0])

    stimulus_onset = tag.position
    stimulus_duration = tag.extent

    stimulus = tag.feature_data(0)
    stimulus_array = tag.features[0].data

    stim_time_dim = stimulus_array.dimensions[0]
    stimulus_time = stim_time_dim.axis(stimulus_array.data_extent[0])

    response_axis = plt.subplot2grid((2, 2), (0, 0), rowspan=1, colspan=2)
    response_axis.tick_params(direction='out')
    response_axis.spines['top'].set_color('none')
    response_axis.spines['right'].set_color('none')
    response_axis.xaxis.set_ticks_position('bottom')
    response_axis.yaxis.set_ticks_position('left')

    stimulus_axis = plt.subplot2grid((2, 2), (1, 0), rowspan=1, colspan=2)
    stimulus_axis.tick_params(direction='out')
    stimulus_axis.spines['top'].set_color('none')
    stimulus_axis.spines['right'].set_color('none')
    stimulus_axis.xaxis.set_ticks_position('bottom')
    stimulus_axis.yaxis.set_ticks_position('left')

    response_axis.plot(time, voltage, color='tab:blue', label=data_array.name, zorder=1)
    response_axis.set_xlabel(x_axis.label + ((" [" + x_axis.unit + "]") if x_axis.unit else ""))
    response_axis.set_ylabel(data_array.label + ((" [" + data_array.unit + "]") if data_array.unit else ""))
    response_axis.set_xlim(0, np.max(time))
    response_axis.set_ylim((1.2 * np.min(voltage), 1.2 * np.max(voltage)))
    response_axis.barh((np.max(voltage) - np.min(voltage))/2, stimulus_duration, np.min(voltage) - np.max(voltage),
                       stimulus_onset, color='silver', alpha=0.5, zorder=0, label="stimulus epoch")
    response_axis.legend(fontsize=9, ncol=2, loc=9)

    stimulus_axis.plot(stimulus_time, stimulus[:], color="slategray", label="stimulus")
    stimulus_axis.set_xlabel(stim_time_dim.label + ((" [" + stim_time_dim.unit + "]") if stim_time_dim.unit else ""))
    stimulus_axis.set_ylabel(stimulus_array.label + ((" [" + stimulus_array.unit + "]") if stimulus_array.unit else ""))
    stimulus_axis.set_xlim(np.min(stimulus_time), np.max(stimulus_time))
    stimulus_axis.set_ylim(1.2 * np.min(stimulus), 1.2 * np.max(stimulus))
    stimulus_axis.legend(fontsize=9, loc=1)

    plt.subplots_adjust(left=0.15, top=0.875, bottom=0.1, right=0.98, hspace=0.45, wspace=0.25)
    plt.gcf().set_size_inches((5.5, 5))
    # plt.savefig("../images/untagged_feature.png")
    plt.show()
Beispiel #24
0
def time_freq_plot(t, freqs, data, coefs, xunits='s', yunits=''):
    if xunits == 'ms':
        t = 1e3 * t
    fig = plt.figure(figsize=(12, 6))
    plt.subplots_adjust(wspace=.8, hspace=.5, bottom=.2)
    # signal plot
    plt.subplot2grid((3, 7), (0, 0), colspan=6)
    plt.plot(t, data)
    plt.ylabel(yunits)
    plt.xlim([t[0], t[-1]])
    # time frequency power plot
    plt.subplot2grid((3, 7), (1, 0), rowspan=2, colspan=6)
    c = plt.contourf(t, freqs, coefs, cmap='PRGn', aspect='auto')
    plt.xlabel('time (' + xunits + ')')
    plt.ylabel('frequency (Hz)')
    # mean power plot over intervals
    plt.subplot2grid((3, 7), (1, 6), rowspan=2)
    plt.xlabel('power')
    # max of power over intervals
    plt.subplot2grid((3, 8), (1, 7), rowspan=2)
    plt.barh(freqs, np.power(coefs,2).mean(axis=1),\
             label='mean', height=freqs[-1]-freqs[-2])
    # plt.plot(np.power(coefs,2).max(axis=1), freqs,\
    #          label='max.')
    plt.xlabel(' power')
    plt.legend(prop={'size': 'small'}, loc=(0.1, 1.1))
    return fig
def makeP(pFolder, pName, supDir=supDir):

    csv = os.path.join(pFolder, ''.join(['meanTable_', pName, '.csv']))
    nii = os.path.join(pFolder, ''.join(['tMap_', pName, '.nii']))

    fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(16, 3))

    ax1 = plt.subplot2grid((1, 14), (0, 0), colspan=2)

    ax1.text(0.05, 0.95, pName, size=24)

    ax1 = plotting.plot_stat_map(nii,
                                 display_mode='y',
                                 cut_coords=([15]),
                                 colorbar=False,
                                 threshold=3,
                                 axes=ax1,
                                 bg_img='%s/data/external/ch2better.nii.gz' %
                                 supDir,
                                 black_bg=False,
                                 draw_cross=False)

    ax2 = plt.subplot2grid((1, 14), (0, 2), colspan=5)
    ax2 = plotting.plot_stat_map(nii,
                                 display_mode='x',
                                 cut_coords=(-50, 50),
                                 colorbar=False,
                                 threshold=3,
                                 axes=ax2,
                                 bg_img='%s/data/external/ch2better.nii.gz' %
                                 supDir,
                                 black_bg=False,
                                 draw_cross=False)

    meanPredDf = pd.read_csv(csv, index_col=[0, 1], header=0)

    pGroup = meanPredDf.loc[
        '2d',
        ['left', 'bilateral', 'right', 'inconclusive']].loc['full'].idxmax()

    ax3 = plt.subplot2grid((1, 14), (0, 8), colspan=3)
    ax3 = singlePlot2d(meanPredDf, cDict[pGroup], ax3)

    ax4 = plt.subplot2grid((1, 14), (0, 11), colspan=3)
    ax4 = makeDonut(meanPredDf, ax4)

    figName = '%s/fig_%s.png' % (pFolder, pName)
    plt.savefig(figName, bbox_inches='tight', dpi=300)

    return figName
Beispiel #26
0
def BS_plot(t, sol):
    def plot_p():
        ## Plot pump evolution
        fig_p, ax_p = pl.subplots() 
        for s in a_sol:
            ax_p.plot(t, s[:,2])
            ax_p.plot(t, s[:,3])

    ax_e = pl.subplot2grid((2,2),(1,0), colspan=2)
    ax_s = pl.subplot2grid((2,2),(0,0))
    ax_i = pl.subplot2grid((2,2),(0,1))
    
    plot_t(t, sol, (ax_s,ax_i))
    plot_e(t, sol, ax_e)
def plot_single_cell_sim(data,
                         XTICKS=None,
                         COLORS=[Green, Blue, Red, Orange],
                         savefig=''):
    Model = data['Model']
    Vthre = Model[Model['NRN_KEY'] + '_Vthre']
    fig, N1, N2 = plt.figure(figsize=(4, 5)), 5, 1
    plt.subplots_adjust(left=.15, bottom=.05, top=.96, right=.99)
    ax1 = plt.subplot2grid((N1, N2), (0, 0))
    ax2 = plt.subplot2grid((N1, N2), (1, 0), rowspan=2)
    ax3 = plt.subplot2grid((N1, N2), (3, 0), rowspan=2)
    # presynaptic raster
    j = 0
    for i in range(len(Model['POP_STIM'])):
        prespikes = data['t_prespikes'][i]
        Npre = Model['N_' + Model['POP_STIM'][i]]
        y = j + np.random.randint(Npre, size=len(prespikes))
        ax1.plot(prespikes, y, 'o', color=color(Model['POP_STIM'][i]), ms=2.)
        j += Npre
    ax1.set_yticks([])
    ax1.set_ylabel('presynaptic\n neurons')
    # synaptic currents
    ax2.plot(np.arange(len(data['Vm'][0])) * float(Model['dt']),
             data['Ie'][0],
             lw=1,
             color=Green)
    ax2.plot(np.arange(len(data['Vm'][0])) * float(Model['dt']),
             data['Ii'][0],
             lw=1,
             color=Red)
    ax2.set_ylabel('synaptic\ncurrents (nA)')
    # Vm and spikes
    for i in range(Model['N_SEED']):
        ax3.plot(np.arange(len(data['Vm'][i])) * float(Model['dt']),
                 data['Vm'][i],
                 lw=1.,
                 color='k')
    for t in data['tspikes']:
        ax3.plot([t, t], [Vthre, Vthre + 5], ':', lw=2, color='k')
    for label, func in zip(['time (ms)', '$V_m$ (mV)'],
                           [ax3.set_xlabel, ax3.set_ylabel]):
        func(label)  # labeling
    ax3.set_yticks([-70, -60, -50])
    if XTICKS is not None:
        ax1.set_xticks(XTICKS)
        ax2.set_xticks(XTICKS)
        ax3.set_xticks(XTICKS)
    ax2.set_xticklabels([])
    ax1.set_xticklabels([])
    return fig
def onpick(event):
    ind = event.ind
    #print('onpick scatter event number:', ind)
    #print('Shown index', ind[0])
    #print('length of index', len(ind))
    #print('area of event', ds_child["area_um"][ind[0]])

    #plt.figure(figsize=(10,5))
    samples = ds.config["fluorescence"]["samples per event"]
    sample_rate = ds.config["fluorescence"]["sample rate"]
    t = np.arange(samples) / sample_rate * 1e6

    figure, axes = plt.subplots(nrows=5, sharex=False, sharey=False)
    axes[0] = plt.subplot2grid((5, 3), (0, 0), colspan=5)
    axes[1] = plt.subplot2grid((5, 3), (1, 0), colspan=5)
    axes[2] = plt.subplot2grid((5, 3), (2, 1))
    axes[3] = plt.subplot2grid((5, 3), (3, 1))
    axes[4] = plt.subplot2grid((5, 3), (4, 1))
    axes[0].imshow(ds_child["image"][ind[0]], cmap="gray")
    axes[1].imshow(ds_child["mask"][ind[0]])
    axes[2].plot(t, ds_child["trace"]["fl1_median"][ind[0]], color="#16A422",
         label=ds.config["fluorescence"]["channel 1 name"])
    axes[3].plot(t, ds_child["trace"]["fl2_median"][ind[0]], color="#CE9720",
         label=ds.config["fluorescence"]["channel 2 name"])
    axes[4].plot(t, ds_child["trace"]["fl3_median"][ind[0]], color="#CE2026",
         label=ds.config["fluorescence"]["channel 3 name"])
    
    axes[2].set_xlim(0, 570) #(200, 350)
    axes[2].grid()
    axes[3].set_xlim(0, 570) #(200, 350)
    axes[3].grid()
    axes[4].set_xlim(0, 570) #(200, 350)
    axes[4].grid()

    axes[2].axvline(ds_child["fl1_pos"][ind[0]] + ds_child["fl1_width"][ind[0]]/2, color="gray")
    axes[2].axvline(ds_child["fl1_pos"][ind[0]] - ds_child["fl1_width"][ind[0]]/2, color="gray")
    #axes[2].axvline(350, color="black")
    #axes[2].axvline(200, color="black")
    axes[3].axvline(ds_child["fl2_pos"][ind[0]] + ds_child["fl2_width"][ind[0]]/2, color="gray")
    axes[3].axvline(ds_child["fl2_pos"][ind[0]] - ds_child["fl2_width"][ind[0]]/2, color="gray")
    #axes[3].axvline(350, color="black")
    #axes[3].axvline(200, color="black")
    axes[4].axvline(ds_child["fl3_pos"][ind[0]] + ds_child["fl3_width"][ind[0]]/2, color="gray")
    axes[4].axvline(ds_child["fl3_pos"][ind[0]] - ds_child["fl3_width"][ind[0]]/2, color="gray")
    #axes[4].axvline(350, color="black")
    #axes[4].axvline(200, color="black")
    
    plt.show()
    print(ds_child["trace"][ind[0]])
def plots1d(nimages=30, nreplicas=4, with_hist=True, show=True,
            height=5, width=8):
    plt.clf()
    fig = plt.gcf()
    fig.set_figheight(height)
    fig.set_figwidth(width)
    if with_hist:
        ncol_hist = 2
    else:
        ncol_hist = 0
    ax_list = [plt.subplot2grid((1,nimages+ncol_hist), (0,i), 
                               colspan=1, rowspan=nimages)
               for i in xrange(nimages)]
    
    for ax in ax_list:
        ax.set_ylim(0,1)
        ax.set_xticks([])
        ax.set_yticks([])
        ypos = np.random.uniform(0,1,nreplicas)
        ymax= ypos.max()
        ax.axhspan(0, ymax, alpha=0.2)
        xpos = np.zeros(nreplicas, )
        ax.scatter(xpos, ypos, c='k', facecolors="none")
        ax.scatter(0, ymax, c='r', linewidths=0, s=40)
    
    if with_hist:
        ax = plt.subplot2grid((1,nimages+ncol_hist), (0,nimages), 
                                   colspan=ncol_hist, rowspan=nimages)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_ylim(0,1)

            
        n = 100000
        rmax = np.random.beta(nreplicas, 1, size=n)
        ax.hist(rmax, bins=np.sqrt(n)/10, orientation='horizontal', normed=True)
        
        if False:
            y = np.arange(1,0,-.01)
            x = y**(nreplicas-1)
            x /= x.max()
            ax.plot(x,y)
            ax.relim()
        
            
    
    
    if show:
        plt.show()
Beispiel #30
0
def fig_rv():
    plt.rcParams['lines.markersize'] = 3
    post = ktwo19.keplerian.max_a_posteriori()
    plotter = orbit_plots.GPMultipanelPlot(
        post,
        subtract_orbit_model=False,
        nobin=True,
        phase_nrows=None,
        phase_ncols=3,
    )
    fig = plt.figure(figsize=(8, 5.5))
    ax1 = plt.subplot2grid((2, 3), (0, 0), colspan=3)
    ax2 = plt.subplot2grid(
        (2, 3),
        (1, 0),
    )
    ax3 = plt.subplot2grid(
        (2, 3),
        (1, 1),
    )
    ax4 = plt.subplot2grid(
        (2, 3),
        (1, 2),
    )
    axL = [ax1, ax2, ax3, ax4]
    plt.rc('font', size=9)
    plotter.nobin = True
    plotter.legend = False
    plotter.epoch = 2454833
    plotter.phasetext_size = 'small'
    plt.sca(ax1)
    plotter.plot_timeseries()
    radvel.plot.labelfig(97)

    plt.sca(ax2)
    plotter.plot_phasefold(98, 1)
    plt.sca(ax3)

    plotter.plot_phasefold(99, 2)
    plt.sca(ax4)
    plotter.plot_phasefold(100, 3)

    plt.setp(axL[2:], ylabel='')
    _ = plt.setp(axL[1:],
                 ylim=(-23, 23),
                 yticks=[-20, -15, -10, -5, 0, 5, 10, 15, 20])
    _ = plt.setp(axL[0], ylim=(-38, 38), xlim=(2200, 3300))
    plt.tight_layout(True)
    plt.subplots_adjust(wspace=0.2)
Beispiel #31
0
def plot_data(tag):
    data_array = tag.references[0]
    voltage = data_array[:]
    
    x_axis = data_array.dimensions[0]
    time = x_axis.axis(data_array.data_extent[0])
    
    stimulus_onset = tag.position
    stimulus_duration = tag.extent

    stimulus = tag.retrieve_feature_data(0)
    stimulus_array = tag.features[0].data
    
    stim_time_dim = stimulus_array.dimensions[0]
    stimulus_time = stim_time_dim.axis(stimulus_array.data_extent[0])
   
    response_axis = plt.subplot2grid((2, 2), (0, 0), rowspan=1, colspan=2)
    response_axis.tick_params(direction='out')
    response_axis.spines['top'].set_color('none')
    response_axis.spines['right'].set_color('none')
    response_axis.xaxis.set_ticks_position('bottom')
    response_axis.yaxis.set_ticks_position('left')

    stimulus_axis = plt.subplot2grid((2, 2), (1, 0), rowspan=1, colspan=2)
    stimulus_axis.tick_params(direction='out')
    stimulus_axis.spines['top'].set_color('none')
    stimulus_axis.spines['right'].set_color('none')
    stimulus_axis.xaxis.set_ticks_position('bottom')
    stimulus_axis.yaxis.set_ticks_position('left')
    
    response_axis.plot(time, voltage, color='dodgerblue', label=data_array.name, zorder=1)
    response_axis.set_xlabel(x_axis.label + ((" [" + x_axis.unit + "]") if x_axis.unit else ""))
    response_axis.set_ylabel(data_array.label + ((" [" + data_array.unit + "]") if data_array.unit else ""))
    response_axis.set_xlim(0, np.max(time))
    response_axis.set_ylim((1.2 * np.min(voltage), 1.2 * np.max(voltage)))
    response_axis.barh(1.2 * np.min(voltage), stim_duration, (1.2*np.max(voltage)) - (1.2*np.min(voltage)),
                       stim_onset, color='silver', alpha=0.25, zorder=0, label="stimulus epoch")
    response_axis.legend()
    
    stimulus_axis.plot(stimulus_time, stimulus, color="slategray", label="stimulus")
    stimulus_axis.set_xlabel(stim_time_dim.label + ((" [" + stim_time_dim.unit + "]") if stim_time_dim.unit else ""))
    stimulus_axis.set_ylabel(stimulus_array.label + ((" [" + stimulus_array.unit + "]") if stimulus_array.unit else ""))
    stimulus_axis.set_xlim(np.min(stimulus_time), np.max(stimulus_time))
    stimulus_axis.set_ylim(1.2 * np.min(stimulus), 1.2 * np.max(stimulus))
    stimulus_axis.legend()
    
    plt.subplots_adjust(left=0.15, top=0.875, bottom=0.1, right=0.98, hspace=0.45, wspace=0.25)
    plt.show()
Beispiel #32
0
def makePlot(iFile, title, pltz, c):

	roiMat = []
	for l in iFile:
		roiMat.append(l)
	roiMat = np.array(roiMat)
	roiMat = roiMat.astype(np.float)

	axes = plt.subplot2grid((4,1), (c, 0))
	pltz.append(axes)
	#pltz[c].set_title(title)

	#_#_#_#_#_#

	cmap = plt.get_cmap(lut=np.nanmax(roiMat)-np.nanmin(roiMat)+1)
	pltz[c].matshow(roiMat, aspect='auto', cmap=cmap, vmin=0, vmax=40)
	#pltz[c].colorbar(label='Count')
	if c == 3:	
		pltz[c].set_xlabel('ROI')
	pltz[c].set_ylabel(title)


	if c == 0:
		pltz[c].set_xticks(range(30))
		pltz[c].set_xticklabels(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"])
	else:
		pltz[c].set_xticklabels([])	

	pltz[c].set_yticks(range(7))
	pltz[c].set_yticklabels(["E", "G", "L", "M", "R", "S", "W"], rotation =90)

	for asd, cas in enumerate(roiMat):
		for sdf, c in enumerate(cas):
				plt.text(sdf-.4, asd+.2, int(c), fontsize=8)
Beispiel #33
0
def plot_waveforms(index, waveforms):
    """Plots one univariate time series."""
    # Get file name
    file_name = list(waveforms.keys())[index]

    # Setup plot
    fig = plt.figure(figsize=(15, 6))
    fig.subplots_adjust(hspace=0.25)
    ax1 = plt.subplot2grid((1, 1), (0, 0))
    ax1.set_title('File Name: ' + file_name + '\n'
                  'Label: ' + waveforms[file_name]['label_str'],
                  fontsize=20)

    # Plot waveform
    ax1.plot(waveforms[file_name]['time'],
             waveforms[file_name]['filtered'],
             '-k',
             label='Filtered')
    ax1.vlines(waveforms[file_name]['rpeaks_ts'],
               waveforms[file_name]['filtered'].min() - 0.01,
               waveforms[file_name]['filtered'].max() + 0.01,
               color=[0.7, 0.7, 0.7],
               linewidth=4,
               label='R-Peaks')

    ax1.set_xlabel('Time, seconds', fontsize=25)
    ax1.set_ylabel('Normalized Amplitude', fontsize=25)
    ax1.set_xlim([0, waveforms[file_name]['duration']])
    ax1.set_ylim([
        waveforms[file_name]['filtered'].min() - 0.01,
        waveforms[file_name]['filtered'].max() + 0.01
    ])
    ax1.tick_params(labelsize=18)
Beispiel #34
0
def diff_data(ts_train):
    data_diff = ts_train.diff(1)
    data_diff = data_diff.dropna()

    layout1 = (1, 2)
    data_train_ax = plt.subplot2grid(layout1, (0, 0))
    data_diff_ax = plt.subplot2grid(layout1, (0, 1))
    data_train_ax.plot(ts_train)
    data_train_ax.set_title('原数据')
    data_diff_ax.plot(data_diff)
    data_diff_ax.set_title('一阶差分')
    # fig.tight_layout()
    plt.show()
    sns.despine()
    print(data_diff.shape)
    return data_diff
def plot_waveform(index, labels, waveform_path, fs):

    # Get file name
    file_name = labels.loc[index, 'file_name']

    # Get label
    label = labels.loc[index, 'label']

    # Get waveform
    time, waveform = load_waveform(path=os.path.join(waveform_path,
                                                     file_name + '.mat'),
                                   fs=fs)

    # Setup plot
    fig = plt.figure(figsize=(15, 6))
    fig.subplots_adjust(hspace=0.25)
    ax1 = plt.subplot2grid((1, 1), (0, 0))
    ax1.set_title('File Name: ' + file_name + '\nLabel: ' + label, fontsize=20)

    # Plot waveform
    ax1.plot(time, waveform, '-k')

    # Configure axes
    ax1.set_xlabel('Time, seconds', fontsize=25)
    ax1.set_ylabel('Amplitude, mV', fontsize=25)
    ax1.set_xlim([time[0], time[-1]])
    ax1.tick_params(labelsize=18)
Beispiel #36
0
def multiPlot(myData):    
    ax=plt.subplot2grid((ncol,nrow),(yPanel,xPanel))
    ax.hist(df[quantVar[myData]],alpha=0.5)#alpha??
    ax.set_xlabel(quantVar[myData],fontsize=14,fontweight='bold')
    #ax.set_ylabel('Y',fontsize=14,fontweight='bold',rotation='Vertical')
    plt.locator_params(axis = 'x', nbins = 2)
    ax.tick_params(labelsize=14)
def time_freq_plot(t, freqs, data, coefs):
    """
    a plot to illustrate the output of the wavelet analysis
    """
    dt = t[1] - t[0]
    import matplotlib.pylab as plt

    fig = plt.figure(figsize=(8, 5))
    plt.subplots_adjust(wspace=.8, hspace=.5, bottom=.2)
    # signal plot
    plt.subplot2grid((3, 8), (0, 0), colspan=6)
    plt.plot(1e3 * t, data, 'k-', lw=2)
    plt.ylabel('signal')
    plt.xlim([1e3 * t[0], 1e3 * t[-1]])
    # time frequency power plot
    ax1 = plt.subplot2grid((3, 8), (1, 0), rowspan=2, colspan=6)
    c = plt.contourf(1e3 * t, freqs, coefs, cmap='PRGn', aspect='auto')
    plt.xlabel('time (ms)')
    plt.ylabel('frequency (Hz)')
    # inset with legend
    acb = plt.axes([.4, .4, .02, .2])
    plt.colorbar(c, cax=acb, label='coeffs (a.u.)', ticks=[-1, 0, 1])
    # mean power plot over intervals
    plt.subplot2grid((3, 8), (1, 6), rowspan=2)
    plt.barh(freqs, np.power(coefs, 2).mean(axis=1) * dt)
    plt.xticks([])
    plt.xlabel(' mean \n power \n (a.u.)')
    # max of power over intervals
    plt.subplot2grid((3, 8), (1, 7), rowspan=2)
    plt.barh(freqs, np.power(coefs, 2).max(axis=1) * dt)
    plt.xticks([])
    plt.xlabel(' max. \n power \n (a.u.)')
    return fig
def get_fig(height, n, layout='one_large_three_small'):
    
    import matplotlib.pylab as plt
    
    if layout == 'one_large_three_small':
    
        # Generate a figure
        fig = plt.figure(figsize = (4*height, 3*height))
        
        # Create the four subplots
        ax1 = plt.subplot2grid((3,4), (0,0), colspan=3, rowspan=3)
        ax2 = plt.subplot2grid((3,4), (0,3))
        ax3 = plt.subplot2grid((3,4), (1,3))
        ax4 = plt.subplot2grid((3,4), (2,3))

        # Create your axes list
        ax_list = [ ax1, ax2, ax3, ax4 ]

        fontsizes = [ 10*height, 5*height, 5*height, 5*height ] # Marker sizes
    

    if layout == 'one_row':
        # Generate a figure
        fig = plt.figure(figsize = (n*height, height))
        
        ax_list = []
        for i in range(n):
            ax = plt.subplot2grid((1,n), (0,i))
            ax_list.append(ax)
    
        fontsizes = [ 15, 15, 15, 15, 15, 15, 15, 15 ] # Marker sizes
         
         
    if layout == 'just_one':
        # Generate a figure
        fig = plt.figure(figsize = (height*1.5, height))

        # Add just one subplot
        ax1 = plt.axes()
        
        ax_list = [ ax1 ]
        
        fontsizes = [ 15 ]
            
    return fig, ax_list, fontsizes
Beispiel #39
0
def quadriptych(importances, foci, foci_colors, cluster_means, cluster_predictive_score, cluster_poly_proportion, cid, title, filenames, lines=True):
    
    fig = plt.figure(figsize=(40, 8), dpi=300);
    vlim = np.max([np.abs(np.min(cluster_means)), np.abs(np.max(cluster_means))]) * 1.2

    # overall importances
    ax1 = plt.subplot2grid((2, 8), (0, 0), colspan=2, rowspan=2)
    panel_importance(importances, title, lines)

    # 4 most prominents clusters of activity under the important regions
    ax1 = plt.subplot2grid((2, 8), (0, 2))
    panel_cluster_mean(0, cluster_means, cluster_predictive_score, cluster_poly_proportion, np.sum(foci_colors == 'green'), vlim, 'green', cid, lines=True, xlabels=False, ylabels=True)
    ax1 = plt.subplot2grid((2, 8), (0, 3))
    panel_cluster_mean(1, cluster_means, cluster_predictive_score, cluster_poly_proportion, np.sum(foci_colors == 'blue'), vlim, 'blue', cid, lines=True, xlabels=False, ylabels=False)
    ax1 = plt.subplot2grid((2, 8), (1, 2))
    panel_cluster_mean(2, cluster_means, cluster_predictive_score, cluster_poly_proportion, np.sum(foci_colors == 'red'), vlim, 'red', cid, lines=True, xlabels=True, ylabels=True)
    ax1 = plt.subplot2grid((2, 8), (1, 3))
    panel_cluster_mean(3, cluster_means, cluster_predictive_score, cluster_poly_proportion, np.sum(foci_colors == 'black'), vlim, 'black', cid, lines=True, xlabels=True, ylabels=False)

    # sagittal
    ax1 = plt.subplot2grid((2, 8), (0, 4), colspan=2, rowspan=2)
    panel_mesh_sagittal(foci, foci_colors, {'blue': 0.6, 'black': 0.6, 'red': 0.6, 'green': 0.6, 'whitesmoke': 0.6})

    # axial
    ax1 = plt.subplot2grid((2, 8), (0, 6), colspan=2, rowspan=2)
    panel_mesh_axial(foci, foci_colors, {'blue': 0.6, 'black': 0.6, 'red': 0.6, 'green': 0.6, 'whitesmoke': 0.6})

    # store the figure
    for filename in filenames:
        plt.savefig(filename, bbox_inches='tight');
    plt.clf();
    plt.close(fig);
Beispiel #40
0
def plot_data(tag):
    data_array = tag.references[0]
    voltage = data_array[:]

    x_axis = data_array.dimensions[0]
    time = x_axis.axis(data_array.data_extent[0])

    spike_times = tag.positions[:]

    feature_data_array = tag.features[0].data
    stimulus = feature_data_array[:]

    stim_time_dim = feature_data_array.dimensions[0]
    stimulus_time = stim_time_dim.axis(feature_data_array.data_extent[0])

    response_axis = plt.subplot2grid((2, 2), (0, 0), rowspan=1, colspan=2)
    stimulus_axis = plt.subplot2grid((2, 2), (1, 0), rowspan=1, colspan=2, sharex=response_axis)

    response_axis.plot(time, voltage, color="dodgerblue", label=data_array.name)
    response_axis.scatter(spike_times, np.ones(spike_times.shape) * np.max(voltage), color="red", label=tag.name)
    response_axis.set_xlabel(x_axis.label + ((" [" + x_axis.unit + "]") if x_axis.unit else ""))
    response_axis.set_ylabel(data_array.label + ((" [" + data_array.unit + "]") if data_array.unit else ""))
    response_axis.set_title(data_array.name)
    response_axis.set_xlim(0, np.max(time))
    response_axis.set_ylim((1.2 * np.min(voltage), 1.2 * np.max(voltage)))
    response_axis.legend()

    stimulus_axis.plot(stimulus_time, stimulus, color="black", label="stimulus")
    stimulus_axis.scatter(spike_times, np.ones(spike_times.shape) * np.max(stimulus), color="red", label=tag.name)
    stimulus_axis.set_xlabel(stim_time_dim.label + ((" [" + stim_time_dim.unit + "]") if stim_time_dim.unit else ""))
    stimulus_axis.set_ylabel(
        feature_data_array.label + ((" [" + feature_data_array.unit + "]") if feature_data_array.unit else "")
    )
    stimulus_axis.set_title("stimulus")
    stimulus_axis.set_xlim(np.min(stimulus_time), np.max(stimulus_time))
    stimulus_axis.set_ylim(1.2 * np.min(stimulus), 1.2 * np.max(stimulus))
    stimulus_axis.legend()

    plt.subplots_adjust(left=0.15, top=0.875, bottom=0.1, right=0.98, hspace=0.45, wspace=0.25)
    # plt.savefig('taggedFeature.png')
    plt.show()
Beispiel #41
0
def survival_stat_plot(t, upper_lim=5, axs=None, colors=None):
    """
    t is the DataFrame returned from a get_surv_fit call.
    """
    if axs is None:
        fig = plt.figure(figsize=(6, 1.5))
        ax = plt.subplot2grid((1, 3), (0, 0), colspan=2)
        ax2 = plt.subplot2grid((1, 3), (0, 2))
    else:
        ax, ax2 = axs
        fig = plt.gcf()
    if colors is None:
        colors = colors_global
    for i, (idx, v) in enumerate(t.iterrows()):
        conf_int = v['Median Survival']
        median_surv = v[('Median Survival', 'Median')]
        if (v['Stats']['# Events'] / v['Stats']['# Patients']) < .5:
            median_surv = np.nanmin([median_surv, 20])
            conf_int['Upper'] = np.nanmin([conf_int['Upper'], 20])
        l = ax.plot(*zip(*[[conf_int['Lower'], i], [median_surv, i], [conf_int['Upper'], i]]), lw=3, ls='--',
                    marker='o', dash_joinstyle='bevel', color=colors[i])
        ax.scatter(median_surv, i, marker='s', s=100, color=l[0].get_color(), edgecolors=['black'], zorder=10,
                   label=idx)
    ax.set_yticks(range(len(t)))
    ax.set_yticklabels(['{} ({})'.format(idx, int(t.ix[idx]['Stats']['# Patients'])) 
                        for idx in t.index])
    ax.set_ylim(-.5, i + .5)
    ax.set_xlim(0, upper_lim)
    ax.set_xlabel('Median Survival (Years)')
    
    tt = t['5y Survival']
    (tt['Surv']).plot(kind='barh', ax=ax2,
                      color=[l.get_color() for l in ax.lines],
                      xerr=[tt.Surv - tt.Lower, tt.Upper - tt.Surv],
                      width=.75,
                      ecolor='black')
    ax2.set_ybound(-.5,len(t)-.5)
    ax2.set_xlabel('5Y Survival')
    ax2.set_xticks([0, .5, 1.])
    ax2.set_yticks([])
    fig.tight_layout()
def get_fig(height, layout='one_large_three_small'):
    
    import matplotlib.pylab as plt
    
    if layout == 'one_large_three_small':
    
        # Generate a figure
        fig = plt.figure(figsize = (4*height, 3*height))
        
        # Create the four subplots
        ax1 = plt.subplot2grid((3,4), (0,0), colspan=3, rowspan=3)
        ax2 = plt.subplot2grid((3,4), (0,3))
        ax3 = plt.subplot2grid((3,4), (1,3))
        ax4 = plt.subplot2grid((3,4), (2,3))

        # Create your axes list
        ax = [ ax1, ax2, ax3, ax4 ]

        msizes = [ 50, 15, 15, 15 ] # Marker sizes
    
    if layout == 'four_equal_size_one_row':
        # Generate a figure
        fig = plt.figure(figsize = (4*height, height))
        
        # Create four subplots
        ax1 = plt.subplot2grid((1,4), (0,0))
        ax2 = plt.subplot2grid((1,4), (0,1))
        ax3 = plt.subplot2grid((1,4), (0,2))
        ax4 = plt.subplot2grid((1,4), (0,3))
    
        msizes = [ 5, 5, 5, 5 ] # Marker sizes
        
        # Create your axes list
        ax = [ ax1, ax2, ax3, ax4 ]
        
    if layout == 'just_one':
        # Generate a figure
        fig = plt.figure(figsize = (height*1.5, height))

        # Add just one subplot
        ax1 = plt.axes()
        
        ax = [ ax1 ]
        
        msizes = [ 5 ]
        
    # Set the marker sizes
    msizes = [ m * height for m in msizes ]
    
    return fig, ax, msizes
    def test_step(self):
        """Test function ``step``."""
        figure(); plot_shape = (1, 3)

        #Test SISO system
        A, B, C, D = self.make_SISO_mats()
        sys = ss(A, B, C, D)
        #print(sys)
        #print("gain:", dcgain(sys))

        subplot2grid(plot_shape, (0, 0))
        t, y = step(sys)
        plot(t, y)

        subplot2grid(plot_shape, (0, 1))
        T = linspace(0, 2, 100)
        X0 = array([1, 1])
        t, y = step(sys, T, X0)
        plot(t, y)

        #Test MIMO system
        A, B, C, D = self.make_MIMO_mats()
        sys = ss(A, B, C, D)

        subplot2grid(plot_shape, (0, 2))
        t, y = step(sys)
        plot(t, y)
def plot_update(fig, axarr, data1, data2, round):

    plt.cla()
    dota1 = data1 / STARTING_PCT
    dota2 = data2 / STARTING_PCT
    center_of_mass1 = ndimage.measurements.center_of_mass(dota1)
    center_of_mass2 = ndimage.measurements.center_of_mass(dota2)

    axarr = [plt.subplot(fig[0, 0]), plt.subplot2grid((2, 2), (1, 0), colspan=2), plt.subplot(fig[0, 1])]
    img1 = axarr[0].imshow(
        dota1,
        interpolation="nearest",
        cmap=plt.cm.ocean,
        extent=(0.5, np.shape(dota1)[0] + 0.5, 0.5, np.shape(dota1)[1] + 0.5),
    )
    axarr[0].plot([center_of_mass1[1]], [center_of_mass1[0]], "or")  # adds dot at center of mass
    axarr[0].plot([center_of_mass2[1]], [center_of_mass2[0]], "oy")  # adds dot for other teams c o m
    axarr[0].axis((1, 101, 1, 101))
    axarr[1].plot(avg_deal_data1, color="green")
    axarr[1].set_xlim(0, rounds)
    axarr[1].set_title("Current Round:" + str(round))
    axarr[0].set_title("Player1")
    axarr[2].set_title("Player2")
    axarr[0].set_ylabel("Give")
    axarr[0].set_xlabel("Accept")
    axarr[1].set_ylabel("Average Cash per Deal")
    axarr[1].set_xlabel("Round Number")
    plt.colorbar(img1, ax=axarr[0], label="Prevalence vs. Uniform")

    img2 = axarr[2].imshow(
        dota2,
        interpolation="nearest",
        cmap=plt.cm.ocean,
        extent=(0.5, np.shape(dota2)[0] + 0.5, 0.5, np.shape(dota2)[1] + 0.5),
    )
    axarr[2].plot([center_of_mass2[1]], [center_of_mass2[0]], "or")  # adds dot at center of mass
    axarr[2].plot([center_of_mass1[1]], [center_of_mass1[0]], "oy")  # adds dot for other teams c o m
    axarr[2].axis((1, 101, 1, 101))
    axarr[1].plot(avg_deal_data2, color="purple")

    plt.title("Current Round:" + str(round))
    axarr[2].set_ylabel("Give")
    axarr[2].set_xlabel("Accept")
    plt.colorbar(img2, ax=axarr[2], label="Prevalence vs. Uniform")

    plt.draw()
def plot_init(data1, data2):
    sns.set_style("dark")
    fig = gridspec.GridSpec(2, 2)
    axarr = [plt.subplot(fig[0, 0]), plt.subplot2grid((2, 2), (1, 0), colspan=2), plt.subplot(fig[0, 1])]
    img1 = axarr[0].imshow(
        data1,
        interpolation="nearest",
        cmap=plt.cm.ocean,
        extent=(0.5, np.shape(data1)[0] + 0.5, 0.5, np.shape(data1)[1] + 0.5),
    )
    plt.title("Current Round:" + str(0))
    axarr[0].set_ylabel("Give")
    axarr[0].set_xlabel("Accept")
    axarr[0].set_title("Distribution of Teams")
    axarr[1].plot(avg_deal_data1, color="green")
    axarr[1].set_xlim(0, rounds)
    axarr[1].set_ylabel("Average Cash per Deal")
    axarr[1].set_xlabel("Round Number")
    plt.colorbar(img1, ax=axarr[0], label="Prevalence vs. Uniform")

    img2 = axarr[2].imshow(
        data2,
        interpolation="nearest",
        cmap=plt.cm.ocean,
        extent=(0.5, np.shape(data2)[0] + 0.5, 0.5, np.shape(data2)[1] + 0.5),
    )
    plt.title("Current Round:" + str(0))
    axarr[2].set_ylabel("Give")
    axarr[2].set_xlabel("Accept")
    axarr[2].set_title("Distribution of Teams")
    axarr[1].plot(avg_deal_data2, color="purple")

    plt.colorbar(img2, ax=axarr[2], label="Prevalence vs. Uniform")

    plt.ion()
    mng = plt.get_current_fig_manager()
    mng.window.state("zoomed")
    plt.show()
    return fig, axarr
    def test_initial(self):
        A, B, C, D = self.make_SISO_mats()
        sys = ss(A, B, C, D)

        figure(); plot_shape = (1, 3)

        #X0=0 : must produce line at 0
        subplot2grid(plot_shape, (0, 0))
        t, y = initial(sys)
        plot(t, y)

        #X0=[1,1] : produces a spike
        subplot2grid(plot_shape, (0, 1))
        t, y = initial(sys, X0=matrix("1; 1"))
        plot(t, y)

        #Test MIMO system
        A, B, C, D = self.make_MIMO_mats()
        sys = ss(A, B, C, D)
        #X0=[1,1] : produces same spike as above spike
        subplot2grid(plot_shape, (0, 2))
        t, y = initial(sys, X0=[1, 1, 0, 0])
        plot(t, y)
Beispiel #47
0
        meta_infile = meta_infile[0] 

    d = pickle.load(open(meta_infile, 'r'))
    if 'infile' not in d: # And this gross hack is due to our parametric exploration 
        # of the hypers above, where we directly generate the .data from the raw source=
        orig_processed_data = d
    else:
        very_original_data = d['infile']
        orig_processed_data = pickle.load(open(very_original_data, 'r'))
    canonical_neuron_ordering = orig_processed_data['canonical_neuron_ordering']

    chains = [c for c in chains if type(c['scores']) != int]
    CHAINN = len(chains)

    f = pylab.figure(figsize= (12, 8))
    ax_z = pylab.subplot2grid((2,2), (0, 0))
    ax_score = pylab.subplot2grid((2,2), (0, 1))


    ###### zmatrix
    av = [np.array(d['state']['domains']['d1']['assignment']) for d in chains]
    z = irm.util.compute_zmatrix(av)    

    z_ord = irm.plot.plot_zmatrix(ax_z, z)
    
    ### Plot scores
    for di, d in enumerate(chains):
        subsamp = 4
        s = np.array(d['scores'])[::subsamp]
        t = np.array(d['times'])[::subsamp] - d['times'][0]
        ax_score.plot(t, s, alpha=0.7, c='k')
Beispiel #48
0
    data_filename = exp['data_filename']
    data = pickle.load(open(data_filename))
    data_basename, _ = os.path.splitext(data_filename)
    meta = pickle.load(open(data_basename + ".meta"))

    if 'count_infile' in meta:
        meta_infile = meta['count_infile']
    else:
        meta_infile = meta['infile']


    chains = [c for c in chains if type(c['scores']) != int]
    CHAINN = len(chains)

    f = pylab.figure(figsize= (12, 8))
    ax_z = pylab.subplot2grid((2,2), (0, 0))
    ax_score = pylab.subplot2grid((2,2), (0, 1))
    ax_purity =pylab.subplot2grid((2,2), (1, 0), colspan=2)
    
    ### Plot scores
    for di, d in enumerate(chains):
        subsamp = 4
        s = np.array(d['scores'])[::subsamp]
        print "Scores=", s
        t = np.array(d['times'])[::subsamp] - d['times'][0]
        ax_score.plot(t, s, alpha=0.7, c='k')

    f.tight_layout()

    f.savefig(plot_latent_filename)
Beispiel #49
0
def get_app_phot(coords, image, plot_only=False, store=True, wcsin="world", fwhm=2, plotdir=".", box=15):
    '''
    coords: files: 
    wcsin: can be "world", "logic"
    '''
    # Load packages; splot is in the onedspec package, which is in noao. 
    # The special keyword _doprint=0 turns off displaying the tasks 
    # when loading a package. 
    
    if (not plot_only):
        iraf.noao(_doprint=0)
        iraf.digiphot(_doprint=0)
        iraf.apphot(_doprint=0)
        iraf.unlearn("apphot")

    imdir = os.path.dirname(image)
    imname = os.path.basename(image)
    plotdir = os.path.join(imdir, "photometry")
    
    if not os.path.isdir(plotdir):
        os.makedirs(plotdir)
        
    out_name = os.path.join(plotdir, imname +  ".seq.mag")
    clean_name = os.path.join(plotdir, imname +  ".app.mag")

    
    # Read values from .ec file
    ecfile= image+".ec"
    filter_value=''.join(ecfile).split('.',1)[0]
    
    fwhm_value = fwhm
    
    if (fitsutils.has_par(image, 'FWHM')):
        fwhm_value = fitsutils.get_par(image, 'FWHM')
    if (fitsutils.has_par(image, 'AIRMASS')):
        airmass_value = fitsutils.get_par(image, 'AIRMASS')
    else:
	airmass_value = 1.3
    exptime = fitsutils.get_par(image, 'EXPTIME')
    gain = fitsutils.get_par(image, 'GAIN')

    try:      
        with open(''.join(ecfile),'r') as f:
            for line in f:
                if "airmass" in line:
                    airmass_value = line.split('=',1)[1]
                else:
                    airmass_value = 1
                if "FWHM" in line:
                    print line
                    fwhm_value =  line.split('FWHM=',1)[1]
                    fwhm_value = fwhm_value.rsplit("aperture")[0]
    except:
        pass
    
    print "FWHM", fwhm_value
    aperture_rad = math.ceil(float(fwhm_value)*2)      # Set aperture radius to three times the PSF radius
    sky_rad= math.ceil(aperture_rad)*5
    
    print aperture_rad, sky_rad

    if (not plot_only):

        if os.path.isfile(out_name): os.remove(out_name)
        if os.path.isfile(clean_name): os.remove(clean_name)

        # Check if files in list, otherwise exit
        if not ecfile:
           print "No .ec files in directory, exiting"
           sys.exit()
        
        
   
   
        iraf.noao.digiphot.apphot.qphot(image = image,\
        cbox = box ,\
        annulus = sky_rad ,\
        dannulus = 15. ,\
        aperture = str(aperture_rad),\
        coords = coords ,\
        output = out_name ,\
        plotfile = "" ,\
        zmag = 0. ,\
        exposure = "exptime" ,\
        airmass = "airmass" ,\
        filter = "filters" ,\
        obstime = "DATE" ,\
        epadu = gain ,\
        interactive = "no" ,\
        radplots = "yes" ,\
        verbose = "no" ,\
        graphics = "stdgraph" ,\
        display = "stdimage" ,\
        icommands = "" ,\
        wcsin = wcsin,
        wcsout = "logical",
        gcommands = "") 
        
         
        #iraf.noao.digiphot.apphot.phot(image=image, cbox=5., annulus=12.4, dannulus=10., salgori = "centroid", aperture=9.3,wcsin="world",wcsout="tv", interac = "no", coords=coords, output=out_name)
        iraf.txdump(out_name, "id,image,xcenter,ycenter,xshift,yshift,fwhm,msky,stdev,mag,merr", "yes", Stdout=clean_name)
        
    
    ma = np.genfromtxt(clean_name, comments="#", dtype=[("id","<f4"),  ("image","|S20"), ("X","<f4"), ("Y","<f4"), ("Xshift","<f4"), ("Yshift","<f4"),("fwhm","<f4"), ("ph_mag","<f4"), ("stdev","<f4"), ("fit_mag","<f4"), ("fiterr","<f4")])
    if (ma.size > 0):    
        m = ma[~np.isnan(ma["fit_mag"])]
    else:
        print "Only one object found!"
        m = np.array([ma])
        
    hdulist = pf.open(image)
    prihdr = hdulist[0].header
    img = hdulist[0].data * 1.
    nx, ny = img.shape

    
    
    dimX = int(4)
    dimY = int(np.ceil(len(m)*1./4))
    outerrad = sky_rad+10
    cutrad = outerrad + 15
    
    plt.suptitle("FWHM="+str(fwhm_value))
    k = 0
    for i in np.arange(dimX):
        for j in np.arange(dimY):
            if ( k < len(m)):
                ax = plt.subplot2grid((dimX,dimY),(i, j))
                y1, y2, x1, x2 = m[k]["X"]-cutrad, m[k]["X"]+cutrad, m[k]["Y"]-cutrad, m[k]["Y"]+cutrad
                y1, y2, x1, x2 = int(y1), int(y2), int(x1), int(x2)
                try:
                    zmin, zmax = zscale.zscale(img[x1:x2,y1:y2], nsamples=1000, contrast=0.25)
                except:
                    sh= img[x1:x2,y1:y2].shape
                    if sh[0]>0 and sh[1]>0:
                        zmin = np.nanmin(img[x1:x2,y1:y2])
                        zmax = np.nanmax(img[x1:x2,y1:y2])
                        continue
                    else:
                        continue
                ax.imshow(img[x1:x2,y1:y2], aspect="equal", extent=(-cutrad, cutrad, -cutrad, cutrad), origin="lower", cmap=matplotlib.cm.gray_r, interpolation="none", vmin=zmin, vmax=zmax)
                c1 = plt.Circle( (0, 0), edgecolor="r", facecolor="none", radius=5.)
                c2 = plt.Circle( (0, 0), edgecolor="orange", facecolor="none", radius=sky_rad)
                c3 = plt.Circle( (0, 0), edgecolor="yellow", facecolor="none", radius=sky_rad+10)
                plt.gca().add_artist(c1)
                plt.gca().add_artist(c2)
                plt.gca().add_artist(c3)
                ax.set_xticks([])
                ax.set_yticks([])
        
                plt.text(+5, +5, "%d"%m[k]["id"])
                plt.text(-cutrad, -cutrad, "%.2f$\pm$%.2f"%(m[k]["fit_mag"], m[k]["fiterr"]), color="b")
            k = k+1
    
    plt.savefig(os.path.join(plotdir, imname + "plot.png"))
    plt.clf()
Beispiel #50
0
def plot_chains_hypers(f, chains, data):
    from matplotlib import pylab

    CHAINN = len(chains)
    RELATIONS = data['relations'].keys()
    per_r_hp = {}
    per_r_hp_ax = {}
    hp_n = 0
    for r in RELATIONS:
        m = data['relations'][r]['model']
        per_r_hp[r] = []
        per_r_hp_ax[r] = []
        if m == 'BetaBernoulli':
            per_r_hp[r].append('alpha')
            hp_n +=1 
            per_r_hp[r].append('beta')
            hp_n +=1 

        elif m == 'BetaBernoulliNonConj':
            per_r_hp[r].append('alpha')
            hp_n +=1 
            per_r_hp[r].append('beta')
            hp_n +=1 

        elif m == 'GammaPoisson':
            per_r_hp[r].append('alpha')
            hp_n +=1 
            per_r_hp[r].append('beta')
            hp_n +=1 
        elif m == 'LogisticDistance':
            for p in ['mu_hp', 'lambda_hp', 'p_min', 'p_max']:
                per_r_hp[r].append(p)
                hp_n +=1 
        elif m == 'LogisticDistanceFixedLambda':
            for p in ['mu_hp', 'lambda', 'p_min', 'p_scale_alpha_hp', 'p_scale_beta_hp']:
                per_r_hp[r].append(p)
                hp_n +=1 
        elif m == 'NormalDistanceFixedWidth':
            for p in ['mu_hp', 'p_alpha', 'p_beta', 'p_min', 'width']:
                per_r_hp[r].append(p)
                hp_n +=1 
        elif m == 'SquareDistanceBump':
            for p in ['mu_hp', 'p_alpha', 'p_beta', 'p_min']:
                per_r_hp[r].append(p)
                hp_n +=1 
        elif m == 'ExponentialDistancePoisson':
            for p in ['rate_scale_hp', 'mu_hp']:
                per_r_hp[r].append(p)
                hp_n +=1 
        elif m == 'LogisticDistancePoisson':
            for p in ['rate_scale_hp', 'mu_hp', 'lambda']:
                per_r_hp[r].append(p)
                hp_n +=1 
        elif m == 'NormalInverseChiSq':
            for p in ['mu', 'kappa', 'nu', 'sigmasq']:
                per_r_hp[r].append(p)
                hp_n +=1 
        elif m == 'MixtureModelDistribution':
            for p in ['comp_k', 'dir_alpha', 'var_scale']:
                per_r_hp[r].append(p)
                hp_n +=1 

        else:
            raise RuntimeError("Unknown model'%s'" % m)
    pos = 1
    for r in RELATIONS:   
        per_r_hp_ax[r] = [] 
        for hp_name in per_r_hp[r]:
            per_r_hp_ax[r].append(pylab.subplot2grid((1+hp_n, 1), (pos, 0)))
            pos += 1
    ax_crp_alpha = pylab.subplot2grid((1+hp_n, 1), (0, 0))

    ### Plot scores
    for di, d in enumerate(chains):
        ki = sorted(d['latents'].keys())
        alpha_x_jitter = 0.1
        alpha_y_jitter = 1.0
        alphas = np.array([d['latents'][k]['domains']['d1']['hps']['alpha'] for k in ki])
        y_jitter = np.random.normal(0, alpha_y_jitter, size=len(alphas))
        ax_crp_alpha.scatter(ki, alphas + y_jitter, edgecolor='none', 
                             alpha=0.2)
        ax_crp_alpha.grid(1)
        for ri, rel_name in enumerate(per_r_hp.keys()):
            print "rel_name", rel_name
            for hp_i, hp_name in enumerate(per_r_hp[rel_name]):
                print "hp_name=", hp_name
                ax = per_r_hp_ax[rel_name][hp_i]
                vals = np.array([d['latents'][k]['relations'][rel_name]['hps'][hp_name] for k in ki])
                print vals, ki
                min_val = np.min(vals)
                max_val = np.max(vals)
                range_mid = (min_val + max_val)/2. 
                range_val = max_val - min_val
                #ax.set_ylim(range_mid - range_val, 
                #            range_mid + range_val)
                y_jitter = np.random.normal(0, 1, size=len(vals)) * (range_val * 0.05)

                ax.scatter(ki, vals + y_jitter, edgecolor='none', 
                           alpha=0.2)
                ax.set_ylabel("%s : %s" % (rel_name, hp_name), 
                             fontsize=6)
                ax.grid(1)
                ax.ticklabel_format(style='plain', axis='y', scilimits=(-8, 8))
                for tick in ax.xaxis.get_major_ticks():
                    tick.label.set_fontsize(6) 

                for tick in ax.yaxis.get_major_ticks():
                    tick.label.set_fontsize(6) 
Beispiel #51
0
def _plot_hdf5_model_horizontal(f, component, output_filename,
                                vmin=None, vmax=None):
    import matplotlib.cm
    import matplotlib.pylab as plt

    data = xarray.DataArray(
        f["data"][component][:], [
            ("latitude", 90.0 - f["coordinate_0"][:]),
            ("longitude", f["coordinate_1"][:]),
            ("radius", f["coordinate_2"][:] / 1000.0)])

    plt.style.use('seaborn-pastel')

    from lasif.domain import RectangularSphericalSection
    domain = RectangularSphericalSection(**dict(f["_meta"]["domain"].attrs))

    plt.figure(figsize=(32, 18))

    depth_position_map = {
        50: (0, 0),
        100: (0, 1),
        150: (1, 0),
        250: (1, 1),
        400: (2, 0),
        600: (2, 1)
    }

    for depth, location in depth_position_map.items():
        ax = plt.subplot2grid((3, 5), location)
        radius = 6371.0 - depth

        # set up a map and colourmap
        m = domain.plot(ax=ax, resolution="c", skip_map_features=True)

        import lasif.colors
        my_colormap = lasif.colors.get_colormap(
                "tomo_full_scale_linear_lightness")

        from lasif import rotations

        x, y = np.meshgrid(data.longitude, data.latitude)

        x_shape = x.shape
        y_shape = y.shape

        lat_r, lon_r = rotations.rotate_lat_lon(
                y.ravel(), x.ravel(),
                domain.rotation_axis,
                domain.rotation_angle_in_degree)

        x, y = m(lon_r, lat_r)

        x.shape = x_shape
        y.shape = y_shape

        plot_data = data.sel(radius=radius, method="nearest")
        plot_data = np.ma.masked_invalid(plot_data.data)

        # Overwrite colormap things if given.
        if vmin is not None and vmax is not None:
            min_val_plot = vmin
            max_val_plot = vmax
        else:
            mean = plot_data.mean()
            max_diff = max(abs(mean - plot_data.min()),
                           abs(plot_data.max() - mean))
            min_val_plot = mean - max_diff
            max_val_plot = mean + max_diff
            # Plotting essentially constant models.
            min_delta = 0.001 * abs(max_val_plot)
            if (max_val_plot - min_val_plot) < min_delta:
                max_val_plot = max_val_plot + min_delta
                min_val_plot = min_val_plot - min_delta

        # Plot.
        im = m.pcolormesh(
                x, y, plot_data,
                cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot,
                shading="gouraud")

        # make a colorbar and title
        m.colorbar(im, "right", size="3%", pad='2%')
        plt.title(str(depth) + ' km')


    # Depth based statistics.
    plt.subplot2grid((3, 5), (0, 4), rowspan=3)
    plt.title("Depth statistics")
    mean = data.mean(axis=(0, 1))
    std = data.std(axis=(0, 1))
    _min = data.min(axis=(0, 1))
    _max = data.max(axis=(0, 1))

    plt.fill_betweenx(data.radius, mean - std, mean + std,
                      label="std", color="#FF3C83")
    plt.plot(mean, data.radius, label="mean", color="k", lw=2)
    plt.plot(_min, data.radius, color="grey", label="min")
    plt.plot(_max, data.radius, color="grey", label="max")
    plt.legend(loc="best")
    plt.xlabel("Value")
    plt.ylabel("Radius")

    plt.hlines(data.radius, plt.xlim()[0], plt.xlim()[1], color="0.8",
               zorder=-10, linewidth=0.5)

    # Roughness plots.
    plt.subplot2grid((3, 5), (0, 2))
    _d = np.abs(data.diff("latitude", n=1)).sum("latitude").data
    plt.title("Roughness in latitude direction, Total: %g" % _d.sum())
    plt.pcolormesh(data.longitude.data, data.radius.data,
                   _d.T, cmap=matplotlib.cm.viridis)
    try:
        plt.colorbar()
    except:
        pass
    plt.xlabel("Longitude")
    plt.ylabel("Radius")

    plt.subplot2grid((3, 5), (1, 2))
    _d = np.abs(data.diff("longitude", n=1)).sum("longitude").data
    plt.title("Roughness in longitude direction. Total: %g" % data.sum())
    plt.pcolormesh(data.latitude.data, data.radius.data, _d.T,
                   cmap=matplotlib.cm.viridis)
    try:
        plt.colorbar()
    except:
        pass
    plt.xlabel("Latitude")
    plt.ylabel("Radius")

    plt.subplot2grid((3, 5), (2, 2))
    _d = np.abs(data.diff("radius", n=1)).sum("radius").data
    plt.title("Roughness in radius direction. Total: %g" % _d.sum())
    plt.pcolormesh(data.longitude.data, data.latitude.data,
                   _d, cmap=matplotlib.cm.viridis)
    try:
        plt.colorbar()
    except:
        pass
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")

    # L2
    plt.subplot2grid((3, 5), (0, 3))
    _d = (data ** 2).sum("latitude").data
    plt.title("L2 Norm in latitude direction, Total: %g" % _d.sum())
    plt.pcolormesh(data.longitude.data, data.radius.data,
                   _d.T, cmap=matplotlib.cm.viridis)
    try:
        plt.colorbar()
    except:
        pass
    plt.xlabel("Longitude")
    plt.ylabel("Radius")

    plt.subplot2grid((3, 5), (1, 3))
    _d = (data ** 2).sum("longitude").data
    plt.title("L2 Norm in longitude direction, Total: %g" % _d.sum())
    plt.pcolormesh(data.latitude.data, data.radius.data, _d.T,
                   cmap=matplotlib.cm.viridis)
    try:
        plt.colorbar()
    except:
        pass
    plt.xlabel("Latitude")
    plt.ylabel("Radius")

    plt.subplot2grid((3, 5), (2, 3))
    _d = (data ** 2).sum("radius").data
    plt.title("L2 Norm in radius direction, Total: %g" % _d.sum())
    plt.pcolormesh(data.longitude.data, data.latitude.data,
                   _d, cmap=matplotlib.cm.viridis)
    try:
        plt.colorbar()
    except:
        pass
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")

    plt.suptitle("Component %s - File %s" % (component, output_filename),
                 fontsize=20)

    plt.tight_layout(rect=(0, 0, 1, 0.95))

    plt.savefig(output_filename, dpi=150)
    plt.close()
Beispiel #52
0
def plot_pose(data, filename=None, gitsha1=None):
    t = pose.get_time_vector(data)
    ts = data['timestamp']
    dt = (ts - np.roll(ts, 1))[1:] # length is now 1 shorter than data

    # convert from system ticks to us
    t = t.astype('int') * 1000 * 1000 / 10000
    dt = dt.astype('int') * 1000 * 1000 / 10000

    rows = round((len(data.dtype.names) + 4) / 2)
    cols = 2
    names = data.dtype.names
    colors = sns.color_palette('husl', len(names))
    fig, axes = plt.subplots(rows, cols, sharex=True)
    axes = axes.ravel()

    base_title = 'bicycle pose'
    if filename is not None:
        base_title += ' (file \'{}\''.format(filename)
        if gitsha1 is not None:
            base_title += ', {}'.format(gitsha1)
        base_title += ')'

    title_size = mpl.rcParams['font.size'] + 2

    def set_title_func(f, x):
        title = base_title
        if x > 0:
            title = '{}\ndecimation factor {}'.format(base_title, x)
        f.suptitle(title, size=title_size)

    # convert angle data from radians to degrees
    angle_names = ('pitch', 'yaw', 'roll', 'steer', 'rear_wheel')
    data_np = []
    for name in names:
        if name in angle_names:
            data_np.append(data[name] * 180/np.pi)
        #elif name == 'timestamp':
        #    continue
        else:
            data_np.append(data[name])
        print('appending', name, 'to data')

    # plot objects to be added later
    dd_display = DecimatingDisplay(data_np, t, dt, set_title_func,
                                   None, None, None, None)

    full_time_range = (t.min(), t.max()) # start with full range of data
    td, datad, dfactor, indices = dd_display.decimate(full_time_range)
    set_title_func(fig, dfactor)

    lines = []
    for n, dd in enumerate(datad):
        axes_index = n + 4
        name = names[n]

        if name in angle_names:
            labelname = name + ' [°]'
        elif name in ('x', 'y'):
            labelname = name + ' [m]'
        elif name == 'v':
            labelname = name + ' [m/s]'
        elif name == 'timestamp':
            labelname = name + ' [system ticks @ 10 kHz]'
        elif name == 'computation_time':
            labelname = name + ' [us]'
        else:
            labelname = name
        print('creating line for', name)

        ax = axes[axes_index]
        lines.append(ax.plot(td, dd, label=labelname, color=colors[n])[0])
        ax.legend()
        ax.set_autoscale_on(False)
        ax.callbacks.connect('xlim_changed', dd_display.ax_update)
        if name == 'y':
            ax.invert_yaxis()

    # create dt plot
    ax = axes[3]
    lines.append(ax.plot(t[:-1], dt[indices[:-1]],
                 label='dt [us]', color=colors[-1])[0])
    ax.legend()
    ax.set_autoscale_on(False)
    ax.callbacks.connect('xlim_changed', dd_display.ax_update)

    axes[-1].set_xlabel('time [us]')
    axes[-2].set_xlabel('time [us]')

    # display trajectory plot
    ax = plt.subplot2grid((rows, cols), (0, 0), rowspan=2, sharey=axes[5])
    husl100 = mpl.colors.ListedColormap(sns.color_palette('husl', 100))
    lc, markers = _plot_trajectory(ax, data['x'][::100], data['y'][::100],
                                   t[::100], xpos='top', yinvert=True,
                                   cmap=husl100)
    axes[0] = ax # overwrite original axes

    # display histogram of sample time
    ax = plt.subplot2grid((rows, cols), (0, 1))
    histf = lambda dt: _plot_histogram(
            ax, dt, logscale=True, color=colors[-1],
            label='loop time [us]\nmax time = {}'.format(dt.max()))
    histf(dt)
    axes[1] = ax

    dd_display.lines = lines
    dd_display.lc = lc
    dd_display.markers = markers
    dd_display.histf = histf
    fig._timeseries_display = dd_display
    return fig
                                            radial_step=radial_step, clip=clip,
                                            threshold=threshold)) 

# angular_integration - direct from `linbasex` transform
radial = LIM.radial
speed  = LIM.Beta[0]

# normalize to max intensity peak
speed /= speed[200:].max()  # exclude transform noise near centerline of image

# PAD - photoelectron angular distribution  - direct from `linbasex` transform
beta = LIM.Beta[1]

# plots of the analysis
fig = plt.figure(figsize=(16, 4))
ax1 = plt.subplot2grid((1, 3), (0, 0))
ax2 = plt.subplot2grid((1, 3), (0, 1))
ax3 = plt.subplot2grid((1, 3), (0, 2), sharex=ax2)

# join 1/2 raw data : 1/2 inversion image
inv_IM = LIM.transform
cols = inv_IM.shape[1]
c2 = cols//2 + cols % 2
vmax = IM[:, :c2-100].max()
inv_IM *= vmax/inv_IM[:, c2+100:].max()
JIM = np.concatenate((IM[:, :c2], inv_IM[:, c2:]), axis=1)

# Prettify the plot a little bit:
# Plot the raw data
im1 = ax1.imshow(JIM, origin='lower', aspect='auto', vmin=0, vmax=vmax)
#fig.colorbar(im1, ax=ax1, fraction=.1, shrink=0.9, pad=0.03)
def getdata(*args):
	'''if not firsttime:
		xlims=ax2.xlim()
		ylims=ax2.ylim()'''
		
	#import IR data
	# set up some constants
	MDB = 'C:\DLOG2\IR\IR' + today + '.mdb'; DRV = '{Microsoft Access Driver (*.mdb)}'; PWD = ''
	if os.path.isfile(MDB):
		pass
	else:
		MDB = 'C:\DLOG2\BackupIR\IR' + today + '.mdb'; DRV = '{Microsoft Access Driver (*.mdb)}'; PWD = ''
	OESMDB = 'C:\DLOG2\OES\OES' + today + '.mdb'; DRV = '{Microsoft Access Driver (*.mdb)}'; PWD = ''

	# connect to db
	filefound=False
	for i in range(tries):
		if os.path.isfile(MDB) and os.path.isfile(OESMDB):
			con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,MDB,PWD))
			cur = con.cursor()
			filefound=True
		else:
			if istoday:
				print ""
				print "Data file not found (takes a few minutes for new data to register)...trying again in 20s..."
				time.sleep(20)
	if not filefound:
		if istoday:
			print ""
			print "hmm...something is wonky here...it...must be the apocalypse! RUN!"
			print ""
			time.sleep(1.6)
			print "Actually, wait.  Double check that the TCO Monitor program is open and you have \"Save Data\" checked, and try again."
			print ""
		else:
			print ""
			print "Data file not found.  Double check that you entered the date correctly."
			print ""
			time.sleep(2.5)
			print "self destructing in:"
			print ""
			time.sleep(1)
			for k in range(11):
				print 10-k
				time.sleep(2)
			print "BOOM!"
			time.sleep(2.7)
		try:
			input('press enter key to exit')
			exit()
		except SyntaxError:
			exit()

	# run a query and get the results 
	SQL = 'SELECT DT, IR_Reflection_0, IR_Reflection_1, ABSORPTION FROM IRLOG;' # your query goes here
	rows = cur.execute(SQL).fetchall()
	cur.close()
	con.close()
	data=numpy.array(rows)
	datetimes=data[:,0]
	IR_0=data[:,1]
	IR_1=data[:,2]
	ABSORPTION=data[:,3]
	abs_mvgavg=pandas.rolling_mean(ABSORPTION,20)

	IRdates = matplotlib.dates.date2num(datetimes)

	#import OES data

	# connect to db
	con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,OESMDB,PWD))
	cur = con.cursor()

	# run a query and get the results 
	SQL = 'SELECT DT, V2, FOS1, FOS2, FOS3, FOS4, FOS5, FOS6, FOS7, FOS8, FOS9, FOS10, FOS11, FOS12 FROM OESLOG;'
	rows = cur.execute(SQL).fetchall()
	cur.close()
	con.close()
	data=numpy.array(rows)
	datetimes=data[:,0]
	OESdates = matplotlib.dates.date2num(datetimes)

	Z1A=data[:,2]
	Z1B=data[:,3]
	Z2A=data[:,4]
	Z2B=data[:,5]
	Z3A=data[:,6]
	Z3B=data[:,7]
	Z4A=data[:,8]
	Z4B=data[:,9]
	Z5A=data[:,10]
	Z5B=data[:,11]
	Z6A=data[:,12]
	Z6B=data[:,13]

	In_OES=numpy.empty([len(Z1A)/8,12])
	In_OESdates=[]
	counter=0
	for each in range(len(Z1A)):
		if data[each,1]=='In_451':
			In_OESdates.append(datetimes[each])
			In_OES[counter,0]=Z1A[each]
			In_OES[counter,1]=Z1B[each]
			In_OES[counter,2]=Z2A[each]
			In_OES[counter,3]=Z2B[each]
			In_OES[counter,4]=Z3A[each]
			In_OES[counter,5]=Z3B[each]
			In_OES[counter,6]=Z4A[each]
			In_OES[counter,7]=Z4B[each]
			In_OES[counter,8]=Z5A[each]
			In_OES[counter,9]=Z5B[each]
			In_OES[counter,10]=Z6A[each]
			In_OES[counter,11]=Z6B[each]
			counter+=1
			
	O2_OES=numpy.empty([len(Z1A)/8,12])
	counter=0
	for each in range(len(Z1A)):
		if data[each,1]=='O2_777':
			O2_OES[counter,0]=Z1A[each]
			O2_OES[counter,1]=Z1B[each]
			O2_OES[counter,2]=Z2A[each]
			O2_OES[counter,3]=Z2B[each]
			O2_OES[counter,4]=Z3A[each]
			O2_OES[counter,5]=Z3B[each]
			O2_OES[counter,6]=Z4A[each]
			O2_OES[counter,7]=Z4B[each]
			O2_OES[counter,8]=Z5A[each]
			O2_OES[counter,9]=Z5B[each]
			O2_OES[counter,10]=Z6A[each]
			O2_OES[counter,11]=Z6B[each]
			counter+=1
			
	H2_OES=numpy.empty([len(Z1A)/8,12])
	counter=0
	for each in range(len(Z1A)):
		if data[each,1]=='H2_656':
			H2_OES[counter,0]=Z1A[each]
			H2_OES[counter,1]=Z1B[each]
			H2_OES[counter,2]=Z2A[each]
			H2_OES[counter,3]=Z2B[each]
			H2_OES[counter,4]=Z3A[each]
			H2_OES[counter,5]=Z3B[each]
			H2_OES[counter,6]=Z4A[each]
			H2_OES[counter,7]=Z4B[each]
			H2_OES[counter,8]=Z5A[each]
			H2_OES[counter,9]=Z5B[each]
			H2_OES[counter,10]=Z6A[each]
			H2_OES[counter,11]=Z6B[each]
			counter+=1
	
	OESdates=matplotlib.dates.date2num(In_OESdates)


	ax2 = plt.subplot2grid((4,4), (1,0), colspan=4)
	ax1 = plt.subplot2grid((4,4), (0,0), colspan=4, sharex=ax2)
	ax4 = plt.subplot2grid((4,4), (2, 2), colspan=2, sharex=ax2)
	ax5 = plt.subplot2grid((4,4), (3, 0), colspan=2, sharex=ax2)
	ax6 = plt.subplot2grid((4,4), (3, 2), colspan=2, sharex=ax2)
	ax3 = plt.subplot2grid((4,4), (2, 0), colspan=2, sharex=ax2)
	ax1.plot_date(IRdates, ABSORPTION, color='DarkMagenta')
	ax1.set_ylabel('Absorption')
	ax1.set_ylim([0,60])
	ax1.axhline(45,ls='--',color='Red',linewidth=4)
	ax1.plot_date(IRdates, abs_mvgavg,'-', color='Orange', linewidth=4)
	ax1.grid()
	ax2.grid()
	ax3.grid()
	ax4.grid()
	ax5.grid()
	ax6.grid()
	
	#start, end = ax1.get_xlim() #can be used to get axes min and max
	ax1.yaxis.set_ticks(numpy.arange(0, 70, 10))
	
	plt.setp(ax1.get_xticklabels(), visible=False)
	
	ax2.plot_date(IRdates, IR_0, color="Blue", label="IR0")#, fmt='-', linewidth=4)
	ax2.plot_date(IRdates, IR_1, color="Red", label="IR1")#, fmt='-', linewidth=4)
	ax2.set_ylabel('IR reflection')
	ax2.set_ylim([0,30])
	ax2.yaxis.set_ticks(numpy.arange(0, 30, 10))
	
	legend2 = ax2.legend(bbox_to_anchor=(1.1, -0.45), loc='lower right', borderaxespad=0., shadow=True, labelspacing=0, numpoints=1)
	# The frame is matplotlib.patches.Rectangle instance surrounding the legend.
	frame2 = legend2.get_frame()
	frame2.set_facecolor('0.90')
		# Set the fontsize
	for label in legend2.get_texts():
		label.set_fontsize('25')
	
	
	ax3.plot_date(OESdates, O2_OES[:,0], color='DarkRed', fmt='-', linewidth=4, label='Z1A')
	ax3.plot_date(OESdates, O2_OES[:,1], color='Crimson', fmt='--', linewidth=4, label='Z1B')
	ax3.plot_date(OESdates, O2_OES[:,2], color='OrangeRed', fmt='-', linewidth=4, label='Z2A')
	ax3.plot_date(OESdates, O2_OES[:,3], color='DarkOrange', fmt='--', linewidth=4, label='Z2B')
	ax3.plot_date(OESdates, O2_OES[:,4], color='cadetblue', fmt='-', linewidth=4, label='Z3A')
	ax3.plot_date(OESdates, O2_OES[:,5], color='chartreuse', fmt='--', linewidth=4, label='Z3B')
	ax3.plot_date(OESdates, O2_OES[:,6], color='DarkGreen', fmt='-', linewidth=4, label='Z4A')
	ax3.plot_date(OESdates, O2_OES[:,7], color='ForestGreen', fmt='--', linewidth=4, label='Z4B')
	ax3.plot_date(OESdates, O2_OES[:,8], color='Navy', fmt='-', linewidth=4, label='Z5A')
	ax3.plot_date(OESdates, O2_OES[:,9], color='Blue', fmt='--', linewidth=4, label='Z5B')
	ax3.plot_date(OESdates, O2_OES[:,10], color='Purple', fmt='-', linewidth=4, label='Z6A')
	ax3.plot_date(OESdates, O2_OES[:,11], color='MediumPurple', fmt='--', linewidth=4, label='Z6B')
	
	ax3.yaxis.set_ticks(numpy.arange(0, 10, 2))
	ax3.set_ylabel('O2 OES')
	
	legend = ax3.legend(bbox_to_anchor=(2.3, 0.65), loc='upper right', borderaxespad=0., shadow=True, labelspacing=0, numpoints=1)
	# The frame is matplotlib.patches.Rectangle instance surrounding the legend.
	frame = legend.get_frame()
	frame.set_facecolor('0.90')
		# Set the fontsize
	for label in legend.get_texts():
		label.set_fontsize('25')

	#ax4.plot_date(OESdates, In_OES[:,0], color='DarkRed', fmt='-', linewidth=4, label='Z1A')
	#ax4.plot_date(OESdates, In_OES[:,1], color='Crimson', fmt='--', linewidth=4, label='Z1B')
	#ax4.plot_date(OESdates, In_OES[:,2], color='OrangeRed', fmt='-', linewidth=4, label='Z2A')
	#ax4.plot_date(OESdates, In_OES[:,3], color='DarkOrange', fmt='--', linewidth=4, label='Z2B')
	#ax4.plot_date(OESdates, In_OES[:,4], color='cadetblue', fmt='-', linewidth=4, label='Z3A')
	#ax4.plot_date(OESdates, In_OES[:,5], color='chartreuse', fmt='--', linewidth=4, label='Z3B')	
	ax4.plot_date(OESdates, In_OES[:,6], color='DarkGreen', fmt='-', linewidth=4, label='Z4A')
	ax4.plot_date(OESdates, In_OES[:,7], color='ForestGreen', fmt='--', linewidth=4, label='Z4B')
	ax4.plot_date(OESdates, In_OES[:,8], color='Navy', fmt='-', linewidth=4, label='Z5A')
	ax4.plot_date(OESdates, In_OES[:,9], color='Blue', fmt='--', linewidth=4, label='Z5B')
	ax4.plot_date(OESdates, In_OES[:,10], color='Purple', fmt='-', linewidth=4, label='Z6A')
	ax4.plot_date(OESdates, In_OES[:,11], color='MediumPurple', fmt='--', linewidth=4, label='Z6B')
	ax4.yaxis.set_ticks(numpy.arange(0, 100, 20))
	ax4.set_ylabel('In OES')
	
	ax5.plot_date(OESdates, H2_OES[:,0], color='DarkRed', fmt='-', linewidth=4, label='Z1A')
	ax5.plot_date(OESdates, H2_OES[:,1], color='Crimson', fmt='-', linewidth=4, label='Z1B')
	ax5.plot_date(OESdates, H2_OES[:,2], color='OrangeRed', fmt='-', linewidth=4, label='Z2A')
	ax5.plot_date(OESdates, H2_OES[:,3], color='DarkOrange', fmt='-', linewidth=4, label='Z2B')
	ax5.plot_date(OESdates, H2_OES[:,4], color='cadetblue', fmt='-', linewidth=4, label='Z3A')
	ax5.plot_date(OESdates, H2_OES[:,5], color='chartreuse', fmt='--', linewidth=4, label='Z3B')	
	ax5.plot_date(OESdates, H2_OES[:,6], color='DarkGreen', fmt='-', linewidth=4, label='Z4A')
	ax5.plot_date(OESdates, H2_OES[:,7], color='ForestGreen', fmt='-', linewidth=4, label='Z4B')
	ax5.plot_date(OESdates, H2_OES[:,8], color='Navy', fmt='-', linewidth=4, label='Z5A')
	ax5.plot_date(OESdates, H2_OES[:,9], color='Blue', fmt='-', linewidth=4, label='Z5B')
	ax5.plot_date(OESdates, H2_OES[:,10], color='Purple', fmt='-', linewidth=4, label='Z6A')
	ax5.plot_date(OESdates, H2_OES[:,11], color='MediumPurple', fmt='-', linewidth=4, label='Z6B')
	ax5.yaxis.set_ticks(numpy.arange(0, 18, 2))
	ax5.set_ylabel('H2 OES')

	#ax6.plot_date(OESdates, In_OES[:,0]/O2_OES[:,0], color='DarkRed', fmt='-', linewidth=4, label='Z1A')
	#ax6.plot_date(OESdates, In_OES[:,1]/O2_OES[:,1], color='Crimson', fmt='--', linewidth=4, label='Z1B')
	#ax6.plot_date(OESdates, In_OES[:,2]/O2_OES[:,2], color='OrangeRed', fmt='-', linewidth=4, label='Z2A')
	#ax6.plot_date(OESdates, In_OES[:,3]/O2_OES[:,3], color='DarkOrange', fmt='--', linewidth=4, label='Z2B')
	#ax6.plot_date(OESdates, In_OES[:,4]/O2_OES[:,4], color='cadetblue', fmt='-', linewidth=4, label='Z3A')
	#ax6.plot_date(OESdates, In_OES[:,5]/O2_OES[:,5], color='chartreuse', fmt='--', linewidth=4, label='Z3B')	
	ax6.plot_date(OESdates, In_OES[:,6]/O2_OES[:,6], color='DarkGreen', fmt='-', linewidth=4, label='Z4A')
	ax6.plot_date(OESdates, In_OES[:,7]/O2_OES[:,7], color='ForestGreen', fmt='--', linewidth=4, label='Z4B')
	ax6.plot_date(OESdates, In_OES[:,8]/O2_OES[:,8], color='Navy', fmt='-', linewidth=4, label='Z5A')
	ax6.plot_date(OESdates, In_OES[:,9]/O2_OES[:,9], color='Blue', fmt='--', linewidth=4, label='Z5B')
	ax6.plot_date(OESdates, In_OES[:,10]/O2_OES[:,10], color='Purple', fmt='-', linewidth=4, label='Z6A')
	ax6.plot_date(OESdates, In_OES[:,11]/O2_OES[:,11], color='MediumPurple', fmt='--', linewidth=4, label='Z6B')
	ax6.set_ylabel('In:O2 OES')
	
	ax6.set_ylim([0,40])
	ax6.yaxis.set_ticks(numpy.arange(0, 50, 10))
	ax2.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
	ax3.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
	plt.setp(ax3.get_xticklabels(), visible=False)
	plt.setp(ax4.get_xticklabels(), visible=False)
	ax5.set_xlabel('time')
	ax6.set_xlabel('time')
	'''if not firsttime:
Beispiel #55
0
 p.show()
 
 # Encode the filter output v=u*h with an IAF neuron
 # -------------------------------------------------
 # Specify parameters of the Ideal IAF neuron
 delta = 0.007                              # set the threshold
 bias  = 0.28                               # set the bias
 kappa = 1.                                 # set capacitance
 # # Encode the filter output
 spk_train, vol_trace = cim.iaf_encode(dt, t_proper, v_proper, b=bias, d=delta, C=kappa)
 run_time('Initialization time:',tic_init)  # display the initialization time 
 
 # Plot the voltage trace and the associated spike train
 p.figure(4)
 ax1 = p.subplot2grid((7, 1), (0, 0),rowspan=5,xlim=(0., 1.0),
         ylabel='Amplitude', ylim=(min(vol_trace), delta*1.1),
         title='Output of the [Filter]-[Ideal IAF] neural circuit')
 p.setp(ax1.get_xticklabels(), visible=False)
 ax2 = p.subplot2grid((7, 1), (5, 0),rowspan=2,sharex=ax1,
         xlabel='Time, [s]', ylim=(0., 1.1),xlim=(0., 1.0),
         yticks = (),yticklabels = ())
 ax1.plot(t_proper-t_proper[0],vol_trace,'b-',
          label='Membrane voltage $v\qquad$')
 ax1.plot((0, t_proper[-1]-t_proper[0]),(delta,delta),'--r',
          label='Threshold $\delta=' + repr(delta) + '$')
 ax1.plot(spk_train-t_proper[0],delta*np.ones_like(spk_train),'ro',
          label= '$v(t)=\delta$')
 ax1.legend(loc='lower right')
 ax2.stem(spk_train-t_proper[0],np.ones_like(spk_train),
          linefmt='k-', markerfmt='k^', label='$(t_k)_{k\in Z}$')
 ax2.legend(loc='lower right')
Beispiel #56
0
  grid_i = flex.int(flex.grid(grid.all()))
  for i, g in enumerate(grid):
    grid_i[i] = int(g)

  mask_normal = discriminate_normal(grid_i)
  mask_poisson = discriminate_poisson(grid_i)

  normal_pixels = flex.select(grid, flags=(mask_normal == 1))
  poisson_pixels = flex.select(grid, flags=(mask_poisson == 1))
  all_pixels = list(grid)

  line = grid.as_numpy_array()[15,:]

  from matplotlib import pylab
  pylab.subplot2grid((3, 3), (0, 0))
  pylab.hist(all_pixels, bins=20)
  pylab.subplot2grid((3, 3), (0, 1))
  pylab.hist(normal_pixels, bins=20)
  pylab.subplot2grid((3, 3), (0, 2))
  pylab.hist(poisson_pixels, bins=20)
  pylab.subplot2grid((3, 3), (1, 0), colspan=3)
  pylab.plot(line)
  pylab.subplot2grid((3, 3), (2, 0))
  pylab.imshow(grid.as_numpy_array(), interpolation='none')
  pylab.subplot2grid((3, 3), (2, 1))
  pylab.imshow(mask_normal.as_numpy_array(), interpolation='none')
  pylab.subplot2grid((3, 3), (2, 2))
  pylab.imshow(mask_poisson.as_numpy_array(), interpolation='none')
  pylab.show()
                plt.plot(d.extra['scores'], label='Scores')
                plt.twinx() 
                plt.plot(d.extra['counts'], label='Counts')
                plt.legend(fontsize='xx-small', framealpha=0.2)
                plt.savefig(os.path.join(feature_dir, 'scores-and-counts.png'))
                plt.close()

            parts_dir = os.path.join(feature_dir, 'parts')
            os.mkdir(parts_dir)

            originals = d.extra.get('originals')
            for pi in xrange(d.num_features):
                #plt.clf()
                f = plt.figure()
                # Look inside view_bkg_stack.py for code to go here.            
                plt.subplot2grid((7,10), (0, 0), colspan=4, rowspan=4).set_axis_off()
                plt.imshow(d.visparts[pi], interpolation='nearest', cmap=plt.cm.gray) 

                for i in xrange(4):
                    plt.subplot2grid((7,10), (2* (i//2), 6+(i%2)*2), colspan=2, rowspan=2).set_axis_off()
                    plt.imshow(d.parts[pi,...,i], interpolation='nearest', vmin=0, vmax=1)
                    plt.title(EDGE_TITLES[i])
                    #if i == 3:

                if False and originals:
                    for i in xrange(min(20, len(originals))):
                        plt.subplot2grid((7,10), (5+i//10, i%10)).set_axis_off()
                        plt.imshow(originals[pi][i], interpolation='nearest', vmin=0, vmax=1, cmap=plt.cm.gray)
                        if i == 4:
                            plt.title('Original background parts')
Beispiel #58
0
bins=[0,0,0,0,0]

for m in range(0,len(mags)):
	if ((mags[m] >= 4) and (mags[m] < 5)):
		bins[0] += 1
	elif ((mags[m] >= 5) and (mags[m] < 6)):
		bins[1] += 1
	elif ((mags[m] >= 6) and (mags[m] < 7)):
		bins[2] += 1
	elif ((mags[m] >= 7) and (mags[m] < 8)):
		bins[3] += 1
	elif (mags[m] >=8):
		bins[4] += 1
print(bins)

ax1 = plt.subplot2grid((1, 10), (0, 0), colspan=7)
ax1.axhline(4, linewidth=.3, color='k')
ax1.axhline(5, linewidth=.3, color='k')
ax1.axhline(6, linewidth=.3, color='k')
ax1.axhline(7, linewidth=.3, color='k')
ax1.axhline(8, linewidth=.3, color='k')
ax1.scatter(dist_deg, mags, s=0.3, c='k', edgecolor='k')
ax1.set_xlabel(u'epicentral distance [°]', fontsize=11, labelpad=3)
ax1.set_ylabel('moment magnitude', fontsize=11)
ax1.set_xlim(-40,180)
ax1.set_ylim(3,9.2)
ax1.set_yticks([4,5,6,7,8,9])
ax1.set_xticks([0,30,60,90,120,150])
ax1.text(s='# events', x=-35, y=9.0, fontsize=9)
ax1.text(s=str(bins[0]), x=-35, y=4.35, fontsize=9)
ax1.text(s=str(bins[1]), x=-35, y=5.35, fontsize=9)
    def test_lsim(self):
        A, B, C, D = self.make_SISO_mats()
        sys = ss(A, B, C, D)

        figure(); plot_shape = (2, 2)

        #Test with arrays
        subplot2grid(plot_shape, (0, 0))
        t = linspace(0, 1, 100)
        u = r_[1:1:50j, 0:0:50j]
        y, _t, _x = lsim(sys, u, t)
        plot(t, y, label='y')
        plot(t, u/10, label='u/10')
        legend(loc='best')

        #Test with U=None - uses 2nd algorithm which is much faster.
        subplot2grid(plot_shape, (0, 1))
        t = linspace(0, 1, 100)
        x0 = [-1, -1]
        y, _t, _x = lsim(sys, U=None, T=t, X0=x0)
        plot(t, y, label='y')
        legend(loc='best')

        #Test with U=0, X0=0
        #Correct reaction to zero dimensional special values
        subplot2grid(plot_shape, (0, 1))
        t = linspace(0, 1, 100)
        y, _t, _x = lsim(sys, U=0, T=t, X0=0)
        plot(t, y, label='y')
        legend(loc='best')

        #Test with matrices
        subplot2grid(plot_shape, (1, 0))
        t = matrix(linspace(0, 1, 100))
        u = matrix(r_[1:1:50j, 0:0:50j])
        x0 = matrix("0.; 0")
        y, t_out, _x = lsim(sys, u, t, x0)
        plot(t_out, y, label='y')
        plot(t_out, asarray(u/10)[0], label='u/10')
        legend(loc='best')

        #Test with MIMO system
        subplot2grid(plot_shape, (1, 1))
        A, B, C, D = self.make_MIMO_mats()
        sys = ss(A, B, C, D)
        t = matrix(linspace(0, 1, 100))
        u = array([r_[1:1:50j, 0:0:50j],
                   r_[0:1:50j, 0:0:50j]])
        x0 = [0, 0, 0, 0]
        y, t_out, _x = lsim(sys, u, t, x0)
        plot(t_out, y[0], label='y[0]')
        plot(t_out, y[1], label='y[1]')
        plot(t_out, u[0]/10, label='u[0]/10')
        plot(t_out, u[1]/10, label='u[1]/10')
        legend(loc='best')


        #Test with wrong values for t
        #T is None; - special handling: Value error
        self.assertRaises(ValueError, lsim(sys, U=0, T=None, x0=0))
        #T="hello" : Wrong type
        #TODO: better wording of error messages of ``lsim`` and
        #      ``_check_convert_array``, when wrong type is given.
        #      Current error message is too cryptic.
        self.assertRaises(TypeError, lsim(sys, U=0, T="hello", x0=0))
        #T=0; - T can not be zero dimensional, it determines the size of the
        #       input vector ``U``
        self.assertRaises(ValueError, lsim(sys, U=0, T=0, x0=0))
        #T is not monotonically increasing
        self.assertRaises(ValueError, lsim(sys, U=0, T=[0., 1., 2., 2., 3.], x0=0))