Example #1
0
def plot_optimisation_history(fitnessvalueshist, optparamshist, optparamsinit):
    """Plot the history of fitness values and each optimised parameter values for the optimisation.

    Args:
        fitnessvalueshist (list): History of fitness values
        optparamshist (dict): Name of parameters to optimise and history of their values
    """

    import matplotlib.pyplot as plt

    # Plot history of fitness values
    fig, ax = plt.subplots(subplot_kw=dict(xlabel='Iterations', ylabel='Fitness value'), num='History of fitness values', figsize=(20, 10), facecolor='w', edgecolor='w')
    iterations = np.arange(1, len(fitnessvalueshist) + 1)
    ax.plot(iterations, fitnessvalueshist, 'r', marker='.', ms=15, lw=1)
    ax.set_xlim(1, len(fitnessvalueshist))
    ax.grid()

    # Plot history of optimisation parameters
    p = 0
    for key, value in optparamshist.items():
        fig, ax = plt.subplots(subplot_kw=dict(xlabel='Iterations', ylabel='Parameter value'), num='History of ' + key + ' parameter', figsize=(20, 10), facecolor='w', edgecolor='w')
        ax.plot(iterations, optparamshist[key], 'r', marker='.', ms=15, lw=1)
        ax.set_xlim(1, len(fitnessvalueshist))
        ax.set_ylim(optparamsinit[p][1][0], optparamsinit[p][1][1])
        ax.grid()
        p += 1
    plt.show()
Example #2
0
    def test_dendrogram_ticklabel_rotation(self):
        f, ax = plt.subplots(figsize=(2, 2))
        mat.dendrogram(self.df_norm, ax=ax)

        for t in ax.get_xticklabels():
            nt.assert_equal(t.get_rotation(), 0)

        plt.close(f)

        df = self.df_norm.copy()
        df.columns = [str(c) * 10 for c in df.columns]
        df.index = [i * 10 for i in df.index]

        f, ax = plt.subplots(figsize=(2, 2))
        mat.dendrogram(df, ax=ax)

        for t in ax.get_xticklabels():
            nt.assert_equal(t.get_rotation(), 90)

        plt.close(f)

        f, ax = plt.subplots(figsize=(2, 2))
        mat.dendrogram(df.T, axis=0, rotate=True)
        for t in ax.get_yticklabels():
            nt.assert_equal(t.get_rotation(), 0)
        plt.close(f)
Example #3
0
def histograma_confianza(promedios_1, promedios_2, lim_min_1, lim_max_1,
                         lim_min_2, lim_max_2):
    '''
    grafica los dos histogramas para pendiente y coeficiente de posicion
    es una funcion circunstancial, se puede mejorar para graficar de forma
    generica
    '''
    fig2, ax2 = plt.subplots()
    plt.hist(promedios_1, bins=40)
    plt.axvline(aprox1[0], color='r', label="Pendiente del Ajuste")
    plt.axvline(lim_min_1, color='g', label="Intervalo de Confianza")
    plt.axvline(lim_max_1, color='g')
    plt.legend()
    ax2.set_xlabel("Pendiente")
    ax2.set_ylabel("Frecuencia")
    plt.savefig("histograma_parte3_pendiente.png")
    fig3, ax3 = plt.subplots()
    plt.hist(promedios_2, bins=40)
    plt.axvline(aprox1[1], color='r', label="Coef de Posicion del Ajuste")
    plt.axvline(lim_min_2, color='g', label="Intervalo de Confianza")
    plt.axvline(lim_max_2, color='g')
    plt.legend(loc=2)
    ax3.set_xlabel("Coeficiente de Posicion")
    ax3.set_ylabel("Frecuencia")
    plt.savefig("histograma_parte3_coefdeposicion.png")
Example #4
0
def test_plot_surf_stat_map():
    mesh = _generate_surf()
    rng = np.random.RandomState(0)
    bg = rng.randn(mesh[0].shape[0], )
    data = 10 * rng.randn(mesh[0].shape[0], )

    # Plot mesh with stat map
    plot_surf_stat_map(mesh, stat_map=data)
    plot_surf_stat_map(mesh, stat_map=data, colorbar=True)
    plot_surf_stat_map(mesh, stat_map=data, alpha=1)

    # Plot mesh with background and stat map
    plot_surf_stat_map(mesh, stat_map=data, bg_map=bg)
    plot_surf_stat_map(mesh, stat_map=data, bg_map=bg,
                       bg_on_data=True, darkness=0.5)
    plot_surf_stat_map(mesh, stat_map=data, bg_map=bg, colorbar=True,
                       bg_on_data=True, darkness=0.5)

    # Apply threshold
    plot_surf_stat_map(mesh, stat_map=data, bg_map=bg,
                       bg_on_data=True, darkness=0.5,
                       threshold=0.3)
    plot_surf_stat_map(mesh, stat_map=data, bg_map=bg, colorbar=True,
                       bg_on_data=True, darkness=0.5,
                       threshold=0.3)

    # Change vmax
    plot_surf_stat_map(mesh, stat_map=data, vmax=5)
    plot_surf_stat_map(mesh, stat_map=data, vmax=5, colorbar=True)

    # Change colormap
    plot_surf_stat_map(mesh, stat_map=data, cmap='cubehelix')
    plot_surf_stat_map(mesh, stat_map=data, cmap='cubehelix', colorbar=True)

    # Plot to axes
    axes = plt.subplots(ncols=2, subplot_kw={'projection': '3d'})[1]
    for ax in axes.flatten():
        plot_surf_stat_map(mesh, stat_map=data, ax=ax)
    axes = plt.subplots(ncols=2, subplot_kw={'projection': '3d'})[1]
    for ax in axes.flatten():
        plot_surf_stat_map(mesh, stat_map=data, ax=ax, colorbar=True)

    fig = plot_surf_stat_map(mesh, stat_map=data, colorbar=False)
    assert len(fig.axes) == 1
    # symmetric_cbar
    fig = plot_surf_stat_map(
        mesh, stat_map=data, colorbar=True, symmetric_cbar=True)
    assert len(fig.axes) == 2
    yticklabels = fig.axes[1].get_yticklabels()
    first, last = yticklabels[0].get_text(), yticklabels[-1].get_text()
    assert float(first) == - float(last)
    # no symmetric_cbar
    fig = plot_surf_stat_map(
        mesh, stat_map=data, colorbar=True, symmetric_cbar=False)
    assert len(fig.axes) == 2
    yticklabels = fig.axes[1].get_yticklabels()
    first, last = yticklabels[0].get_text(), yticklabels[-1].get_text()
    assert float(first) != - float(last)
    # Save execution time and memory
    plt.close()
Example #5
0
    def test_heatmap_ticklabel_rotation(self):

        f, ax = plt.subplots(figsize=(2, 2))
        mat.heatmap(self.df_norm, ax=ax)

        for t in ax.get_xticklabels():
            nt.assert_equal(t.get_rotation(), 0)

        for t in ax.get_yticklabels():
            nt.assert_equal(t.get_rotation(), 90)

        plt.close(f)

        df = self.df_norm.copy()
        df.columns = [str(c) * 10 for c in df.columns]
        df.index = [i * 10 for i in df.index]

        f, ax = plt.subplots(figsize=(2, 2))
        mat.heatmap(df, ax=ax)

        for t in ax.get_xticklabels():
            nt.assert_equal(t.get_rotation(), 90)

        for t in ax.get_yticklabels():
            nt.assert_equal(t.get_rotation(), 0)

        plt.close(f)
Example #6
0
    def test_regplot_scatter_kws_alpha(self):

        f, ax = plt.subplots()
        color = np.array([[0.3, 0.8, 0.5, 0.5]])
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color})
        nt.assert_is(ax.collections[0]._alpha, None)
        nt.assert_equal(ax.collections[0]._facecolors[0, 3], 0.5)

        f, ax = plt.subplots()
        color = np.array([[0.3, 0.8, 0.5]])
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color})
        nt.assert_equal(ax.collections[0]._alpha, 0.8)

        f, ax = plt.subplots()
        color = np.array([[0.3, 0.8, 0.5]])
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color,
                                                        'alpha': 0.4})
        nt.assert_equal(ax.collections[0]._alpha, 0.4)

        f, ax = plt.subplots()
        color = 'r'
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color})
        nt.assert_equal(ax.collections[0]._alpha, 0.8)

        plt.close("all")
def test_cursor_data():
    from matplotlib.backend_bases import MouseEvent

    fig, ax = plt.subplots()
    im = ax.imshow(np.arange(100).reshape(10, 10), origin='upper')

    x, y = 4, 4
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) == 44

    # Now try for a point outside the image
    # Tests issue #4957
    x, y = 10.1, 4
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) is None

    # Hmm, something is wrong here... I get 0, not None...
    # But, this works further down in the tests with extents flipped
    #x, y = 0.1, -0.1
    #xdisp, ydisp = ax.transData.transform_point([x, y])
    #event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    #z = im.get_cursor_data(event)
    #assert z is None, "Did not get None, got %d" % z

    ax.clear()
    # Now try with the extents flipped.
    im = ax.imshow(np.arange(100).reshape(10, 10), origin='lower')

    x, y = 4, 4
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) == 44

    fig, ax = plt.subplots()
    im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5])

    x, y = 0.25, 0.25
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) == 55

    # Now try for a point outside the image
    # Tests issue #4957
    x, y = 0.75, 0.25
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) is None

    x, y = 0.01, -0.01
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) is None
    def setupPlots(self):

        #Set up plot axes and figure positions
        self.figurerow, self.axrow = plt.subplots()
	#self.figurerow.gca().set_position([0,0,1,1])

        self.figurecolumn, self.axcolumn = plt.subplots()
	#self.figurecolumn.gca().set_position([0,0,1,1])

	#Create line objects for fast plot redrawing
        self.linesrow, = self.axrow.plot([],[],linewidth=2,color='purple')
        self.linesrowfit, = self.axrow.plot([],[],linestyle='--',linewidth=2,color='yellow')

        self.linescolumn, = self.axcolumn.plot([],[],linewidth=2,color='purple')
	self.linescolumnfit, = self.axcolumn.plot([],[],linestyle='--',linewidth=2,color='yellow')

        self.axrow.set_xlim(0, self.imageres[0])
	self.axrow.set_ylim(0,300)

        self.axcolumn.set_xlim(0, 300)
	self.axcolumn.set_ylim(0,self.imageres[1])

	self.axrow.xaxis.set_ticks_position('none')
	self.axrow.yaxis.set_ticks_position('none')
	self.axrow.get_xaxis().set_visible(False)
	self.axrow.get_yaxis().set_visible(False)
	self.axrow.patch.set_visible(False)

	self.axcolumn.xaxis.set_ticks_position('none')
	self.axcolumn.yaxis.set_ticks_position('none')
	self.axcolumn.get_xaxis().set_visible(False)
	self.axcolumn.get_yaxis().set_visible(False)
	self.axcolumn.patch.set_visible(False)
Example #9
0
def accuracy(target, prediction, label="Classifier", c=np.zeros((0,0))):
    correct = (target == prediction)
    correct = np.array((correct, correct))
    compare = np.array((target, prediction))
    
    showC = c != np.zeros((0,0))
    
    if (showC):
        fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
    else:
        fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(6,8))
    
    dim = [0,compare.shape[1],0,compare.shape[0]]
    ax1.imshow(compare, extent=dim, aspect='auto', interpolation='nearest')
    ax1.set_title(label + ": Prediction vs. Target")
    
    imgPlt = ax2.imshow(correct, extent=dim, aspect='auto', interpolation='nearest')
    imgPlt.set_cmap('RdYlGn')
    ax2.set_title(label + " Prediction Accuracy")
    
    if (showC):
        ax3.plot(c)
        ax3.set_title("Concentration")
        ax3.set_yscale('log')
        ax3.set_ylim(0.02,0.7)
    
    plt.draw()
Example #10
0
def check_output_distribution(yt_unscl, yt_scl, yp_unscl, yp_scl, lat, lev,
                              figpath):
    # For unscaled variables
    fig, ax = plt.subplots(2, 2)
    x1, x2, bins = _plot_distribution(unpack(yt_unscl, 'T'), lat, lev, fig,
                                      ax[0, 0], './figs/',
                                      r'$\Delta$T true [K/day]', '')
    _plot_distribution(unpack(yp_unscl, 'T'), lat, lev, fig,
                       ax[0, 1], './figs/', r'$\Delta$T pred [K/day]', '', x1,
                       x2, bins)
    x1, x2, bins = _plot_distribution(unpack(yt_unscl, 'q'), lat, lev, fig,
                                      ax[1, 0], './figs/',
                                      r'$\Delta$q true [g/kg/day]', '')
    _plot_distribution(unpack(yp_unscl, 'q'), lat, lev, fig, ax[1, 1],
                       './figs/', r'$\Delta$q pred [g/kg/day]', '', x1, x2,
                       bins)
    fig.savefig(figpath + 'output_compare_true_pred_unscaled.png',
                bbox_inches='tight', dpi=450)
    plt.close()
    # For scaled variables
    fig, ax = plt.subplots(2, 2)
    x1, x2, bins = _plot_distribution(unpack(yt_scl, 'T'), lat, lev, fig,
                                      ax[0, 0], './figs/',
                                      r'$\Delta$T true (scld) []', '')
    _plot_distribution(unpack(yp_scl, 'T'), lat, lev, fig, ax[0, 1], './figs/',
                       r'$\Delta$T pred (scld) []', '', x1, x2, bins)
    x1, x2, bins = _plot_distribution(unpack(yt_scl, 'q'), lat, lev, fig,
                                      ax[1, 0], './figs/',
                                      r'$\Delta$q true (scld) []', '')
    _plot_distribution(unpack(yp_scl, 'q'), lat, lev, fig, ax[1, 1], './figs/',
                       r'$\Delta$q pred (scld) []', '', x1, x2, bins)
    fig.savefig(figpath + 'output_compare_true_pred_scaled.png',
                bbox_inches='tight', dpi=450)
    plt.close()
Example #11
0
 def decode_uniform_samples_from_latent_space(_):
     fig, ax = plt.subplots()
     nx = ny = 20
     extent_x = extent_y = [-3, 3]
     extent = numpy.array(extent_x + extent_y)
     x_values = numpy.linspace(*(extent_x + [nx]))
     y_values = numpy.linspace(*(extent_y + [nx]))
     full_extent = extent * (nx + 1) / float(nx)
     canvas = numpy.empty((28 * ny, 28 * nx))
     for ii, yi in enumerate(x_values):
         for j, xi in enumerate(y_values):
             n = ii * nx + j + 1
             sys.stdout.write("\rsampling p(X|z), sample %d/%d" % (n, nx*ny))
             sys.stdout.flush()
             np_z = numpy.array([[xi, yi]])
             x_mean = sess.run(prior_model(latent=numpy.reshape(np_z, newshape=(1, LATENT_DIM)))[0])
             canvas[(nx - ii - 1) * 28:(nx - ii) * 28, j * 28:(j + 1) * 28] = x_mean[0].reshape(28, 28)
     with seaborn.axes_style('ticks'):
         seaborn.set_context(context='notebook', font_scale=1.75)
         fig, ax = plt.subplots(figsize=(12, 9))
     ax.imshow(canvas, extent=full_extent)
     ax.xaxis.set_ticks(numpy.linspace(*(extent_x + [nx])))
     ax.yaxis.set_ticks(numpy.linspace(*(extent_y + [ny])))
     ax.set_xlabel('z_1')
     ax.set_ylabel('z_2')
     ax.set_title('P(X|z); decoding latent space; (CONV, BNAE, IND_ERROR) = (%d,%d,%d)' % (CONV, BNAE, IND_ERROR))
     plt.show()
     plt.savefig(os.path.join(FLAGS.viz_dir, 'P(X|z).png'))
     return fig, ax
Example #12
0
def get_axis(figsize, size, aspect, ax):
    import matplotlib as mpl
    import matplotlib.pyplot as plt

    if figsize is not None:
        if ax is not None:
            raise ValueError('cannot provide both `figsize` and '
                             '`ax` arguments')
        if size is not None:
            raise ValueError('cannot provide both `figsize` and '
                             '`size` arguments')
        _, ax = plt.subplots(figsize=figsize)
    elif size is not None:
        if ax is not None:
            raise ValueError('cannot provide both `size` and `ax` arguments')
        if aspect is None:
            width, height = mpl.rcParams['figure.figsize']
            aspect = width / height
        figsize = (size * aspect, size)
        _, ax = plt.subplots(figsize=figsize)
    elif aspect is not None:
        raise ValueError('cannot provide `aspect` argument without `size`')

    if ax is None:
        ax = plt.gca()

    return ax
Example #13
0
def check_scaling_distribution(x_unscl, x_scl, y_unscl, y_scl, lat, lev,
                               figpath):
    # For input variables
    fig, ax = plt.subplots(2, 2)
    _plot_distribution(unpack(x_unscl, 'T'), lat, lev, fig, ax[0, 0],
                       './figs/', 'T (unscaled) [K]', '')
    _plot_distribution(unpack(x_scl, 'T'), lat, lev, fig, ax[0, 1],
                       './figs/', 'T (scaled) []', '')
    _plot_distribution(unpack(x_unscl, 'q'), lat, lev, fig, ax[1, 0],
                       './figs/', 'q (unscaled) [g/kg]', '')
    _plot_distribution(unpack(x_scl, 'q'), lat, lev, fig, ax[1, 1],
                       './figs/', 'q (scaled) []', '')
    fig.savefig(figpath + 'input_scaling_check.png', bbox_inches='tight',
                dpi=450)
    plt.close()
    # For output variables
    fig, ax = plt.subplots(2, 2)
    _plot_distribution(unpack(y_unscl, 'T'), lat, lev, fig, ax[0, 0],
                       './figs/', 'T tend (unscaled) [K/day]', '')
    _plot_distribution(unpack(y_scl, 'T'), lat, lev, fig, ax[0, 1],
                       './figs/', 'T tend (scaled) []', '')
    _plot_distribution(unpack(y_unscl, 'q'), lat, lev, fig, ax[1, 0],
                       './figs/', 'q tend (unscaled) [g/kg/day]', '')
    _plot_distribution(unpack(y_scl, 'q'), lat, lev, fig, ax[1, 1],
                       './figs/', 'q tend(scaled) []', '')
    fig.savefig(figpath + 'output_scaling_check.png', bbox_inches='tight',
                dpi=450)
    plt.close()
Example #14
0
def test_cursor_data():
    from matplotlib.backend_bases import MouseEvent

    fig, ax = plt.subplots()
    im = ax.imshow(np.arange(100).reshape(10, 10), origin='upper')

    x, y = 4, 4
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) == 44

    ax.clear()
    im = ax.imshow(np.arange(100).reshape(10, 10), origin='lower')

    x, y = 4, 4
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) == 44

    fig, ax = plt.subplots()
    im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5])

    x, y = 0.25, 0.25
    xdisp, ydisp = ax.transData.transform_point([x, y])

    event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
    assert im.get_cursor_data(event) == 55
def main():
    from matplotlib import pyplot as plt
    
    fig, ax = plt.subplots()

    L = 80. # granule cell layer thickness in um
    r_values = np.arange(0.1, 160, 0.02)
    rho = 6.6e-4 # glom density in um^-3

    for l in np.arange(4.65, 4.8, 0.01):
        d_values = np.array([d(r,l,L) for r in r_values])
        mean = (d_values * r_values).sum() / d_values.sum()
        fraction_above_30 = d_values[r_values>30].sum() / d_values.sum()
        fraction_above_40 = d_values[r_values>39.5].sum() / d_values.sum()

        #print l, mean, fraction_above_30, fraction_above_40
        ax.plot(r_values, d_values)
    
    l = 5.
    k_palkovits = 4.17

    n_dendrites_range = np.arange(1.,8.,1.)
    degree_distribution = np.array([poisson(k_palkovits, n) for n in n_dendrites_range])
    fig, ax = plt.subplots()
    print degree_distribution
    ax.bar(n_dendrites_range, degree_distribution)
        
    plt.show()
Example #16
0
def plot_images_as_subplots(list_of_plot_args, plot_name, width, height,
                            invert_y=False, invert_x=False,
                            figsize=None, turn_on_agg=True):
    if turn_on_agg:
        import matplotlib
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    lengths = [len(a) for a in list_of_plot_args]
    if len(list(filter(lambda x: x != lengths[0], lengths))) > 0:
        raise ValueError("list_of_plot_args has elements of different lengths!")

    if figsize is None:
        f, axarr = plt.subplots(lengths[0], len(lengths))
    else:
        f, axarr = plt.subplots(lengths[0], len(lengths), figsize=figsize)
    for n, v in enumerate(list_of_plot_args):
        for i, X_i in enumerate(v):
            axarr[i, n].matshow(X_i.reshape(width, height), cmap="gray", interpolation="none")
            axarr[i, n].axis('off')
            if invert_y:
                axarr[i, n].set_ylim(axarr[i, n].get_ylim()[::-1])
            if invert_x:
                axarr[i, n].set_xlim(axarr[i, n].get_xlim()[::-1])
    plt.tight_layout()
    plt.savefig(plot_name + ".png")
Example #17
0
def plot_gens(images, rowlabels, losses):
    '''
    From great jupyter notebook by Tim Sainburg:
    http://github.com/timsainb/Tensorflow-MultiGPU-VAE-GAN
    '''
    examples = 8
    fig, ax = plt.subplots(nrows=len(images), ncols=examples, figsize=(18, 8))
    for i in range(examples):
        for j in range(len(images)):
            ax[(j, i)].imshow(create_image(images[j][i]), cmap=plt.cm.gray,
                              interpolation='nearest')
            ax[(j, i)].axis('off')
    title = ''
    for i in rowlabels:
        title += ' {}, '.format(i)
    fig.suptitle('Top to Bottom: {}'.format(title))
    plt.show()
    #fig.savefig(''.join(['imgs/test_',str(epoch).zfill(4),'.png']),dpi=100)
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 10), linewidth = 4)

    D_plt, = plt.semilogy((losses['discriminator']), linewidth=4, ls='-',
                          color='b', alpha=.5, label='D')
    G_plt, = plt.semilogy((losses['generator']), linewidth=4, ls='-',
                          color='k', alpha=.5, label='G')

    plt.gca()
    leg = plt.legend(handles=[D_plt, G_plt],
                     fontsize=20)
    leg.get_frame().set_alpha(0.5)
    plt.show()
Example #18
0
def test_marker_cycle():
    fig, ax = plt.subplots()
    ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) +
                      cycler('marker', ['.', '*', 'x']))
    xs = np.arange(10)
    ys = 0.25 * xs + 2
    ax.plot(xs, ys, label='red dot', lw=4, ms=16)
    ys = 0.45 * xs + 3
    ax.plot(xs, ys, label='green star', lw=4, ms=16)
    ys = 0.65 * xs + 4
    ax.plot(xs, ys, label='yellow x', lw=4, ms=16)
    ys = 0.85 * xs + 5
    ax.plot(xs, ys, label='red2 dot', lw=4, ms=16)
    ax.legend(loc='upper left')

    fig, ax = plt.subplots()
    # Test keyword arguments, numpy arrays, and generic iterators
    ax.set_prop_cycle(c=np.array(['r', 'g', 'y']),
                      marker=iter(['.', '*', 'x']))
    xs = np.arange(10)
    ys = 0.25 * xs + 2
    ax.plot(xs, ys, label='red dot', lw=4, ms=16)
    ys = 0.45 * xs + 3
    ax.plot(xs, ys, label='green star', lw=4, ms=16)
    ys = 0.65 * xs + 4
    ax.plot(xs, ys, label='yellow x', lw=4, ms=16)
    ys = 0.85 * xs + 5
    ax.plot(xs, ys, label='red2 dot', lw=4, ms=16)
    ax.legend(loc='upper left')
def noiseFilter(data_in):

	N = int(np.ceil((4 / b)))
	if not N % 2: N += 1  # Make sure that N is odd.
	n = np.arange(N)
	 
	# Compute a low-pass filter with cutoff frequency fH.
	hlpf = np.sinc(2 * fH * (n - (N - 1) / 2.))
	hlpf *= np.blackman(N)
	hlpf = hlpf / np.sum(hlpf)
	 
	# Compute a high-pass filter with cutoff frequency fL.
	hhpf = np.sinc(2 * fL * (n - (N - 1) / 2.))
	hhpf *= np.blackman(N)
	hhpf = hhpf / np.sum(hhpf)
	hhpf = -hhpf
	hhpf[(N - 1) / 2] += 1
	 
	# Convolve both filters.
	h = np.convolve(hlpf, hhpf)
	s = np.convolve(data_in, hlpf)

	fig, ax = plt.subplots()
	ax.plot(data_in)
	plt.show()
	fig1, ax1 = plt.subplots()
	ax1.plot(s)
	plt.show()
	return s
Example #20
0
def plot(args):
    from pickle import load
    from sys import stdin
    import matplotlib.pyplot as plt
    from itertools import starmap
    from numpy.random import seed, random
    from coherent_point_drift.geometry import rigidXform, RMSD

    seed(4) # For color choice
    reference = load(stdin.buffer)

    rmsds = []
    fig, ax = plt.subplots(1, 1)
    for degradation, fit in loadAll(stdin.buffer):
        color = random(3)
        degraded = degrade(reference, *degradation)
        ax.scatter(degraded[:, 0], degraded[:, 1], marker='o', color=color, alpha=0.2)
        fitted = rigidXform(degraded, *fit)
        ax.scatter(fitted[:, 0], fitted[:, 1], marker='+', color=color)
        rmsds.append(RMSD(reference, fitted))
    ax.scatter(reference[:, 0], reference[:, 1], marker='D', color='black')
    ax.set_xticks([])
    ax.set_yticks([])

    if len(rmsds) > 1:
        fig, ax = plt.subplots(1, 1)
        ax.violinplot(rmsds)
        ax.set_ylabel("RMSD")

    plt.show()
Example #21
0
    def __init__(self, plotname):
        self.plotname = plotname
        
        self.att_fig, self.att_ax = plt.subplots(3,1, sharex=True)
        self.att_ax[0].grid()
        self.att_ax[1].grid()
        self.att_ax[2].grid()
        self.att_ax[2].set_xlabel('Time (sec)', weight='bold')

        self.vel_fig, self.vel_ax = plt.subplots(3,1, sharex=True)
        self.vel_ax[0].grid()
        self.vel_ax[1].grid()
        self.vel_ax[2].grid()
        self.vel_ax[2].set_xlabel('Time (sec)', weight='bold')

        self.pos_fig, self.pos_ax = plt.subplots(3,1, sharex=True)
        self.pos_ax[0].grid()
        self.pos_ax[1].grid()
        self.pos_ax[2].grid()
        self.pos_ax[2].set_xlabel('Time (sec)', weight='bold')

        self.bias_fig, self.bias_ax = plt.subplots(3,2, sharex=True)

        # turn on interactive mode
        plt.ion()
Example #22
0
def test_continuous_distortion():

	#load unlensed image from png file
	image_unlensed = plt.imread(os.path.join(dataExtern(),"lensing/lens.png"))[:,:,0]
	pos_original = (np.array(np.where(image_unlensed>0)) * 2.0/image_unlensed.shape[0]) * deg
	pos_original = np.roll(pos_original,1,axis=0)
	pos_original[1] *= -1
	pos_original[1] += 2.0*deg

	#Perform forward ray tracing with grid interpolation to compute the image distortion
	pos_apparent = tracer.shootForward(pos_original,z=2.0,save_intermediate=True)

	#Plot some of the distorted images
	fig,ax = plt.subplots(2,5,figsize=(40,16))
	for i in range(2):
		for j in range(5):
			ax[i,j].scatter(pos_apparent[(5*i + j)*4,0],pos_apparent[(5*i + j)*4,1]) 
			ax[i,j].set_xlabel(r"$x$({0})".format(pos_original.unit.to_string()))
			ax[i,j].set_ylabel(r"$y$({0})".format(pos_original.unit.to_string()))
			ax[i,j].set_title("z={0:.2f}".format(tracer.redshift[(5*i + j)*4]))

	#Save the figure
	fig.tight_layout()
	fig.savefig("lens_distortion_continuous.png")

	#Plot each single frame
	fig,ax = plt.subplots()
	scatterplot = ax.scatter(pos_original[0],pos_original[1])
	ax.set_xlabel(r"$x$({0})".format(pos_original.unit.to_string()))
	ax.set_ylabel(r"$y$({0})".format(pos_original.unit.to_string()))
	
	for n in range(pos_apparent.shape[0]):
		scatterplot.set_offsets(pos_apparent[n].transpose())
		ax.set_title("z={:.2f}".format(tracer.redshift[n]))	
		fig.savefig("distortion{0}.png".format(n))	 
Example #23
0
def plot_toy_data(algo_name, features, labels, thetas):
    """
    Plots the toy data in 2D.
    Arguments:
    * features - an Nx2 ndarray of features (points)
    * labels - a length-N vector of +1/-1 labels
    * thetas - the tuple (theta, theta_0) that is the output of the learning algorithm
    * algorithm - the string name of the learning algorithm used
    """
    # plot the points with labels represented as colors
    plt.subplots()
    colors = ['b' if label == 1 else 'r' for label in labels]
    plt.scatter(features[:, 0], features[:, 1], s=40, c=colors)
    xmin, xmax = plt.axis()[:2]

    # plot the decision boundary
    theta, theta_0 = thetas
    xs = np.linspace(xmin, xmax)
    ys = -(theta[0]*xs + theta_0) / (theta[1] + 1e-16)
    plt.plot(xs, ys, 'k-')

    # show the plot
    algo_name = ' '.join((word.capitalize() for word in algo_name.split(' ')))
    plt.suptitle('Classified Toy Data ({})'.format(algo_name))
    plt.show()
Example #24
0
def save_plot_data(interval,data_1, data_2, data_3, names, style, p_title, s_title, format):
  close='all'
  if ( style == 0): 
    
    fig, ax = plt.subplots()
    ax.plot(interval,data_1, color='black', label=names[1])
    ax.plot(interval,data_2, color='red' , label=names[2])
    ax.plot(interval,data_3, color='blue',linestyle='-', label=names[3])
    ax.set_yscale('symlog')
    plt.title(p_title)
    plt.xlabel('Liquid') #das r hier markiert, dass jetz latex code kommt
    plt.ylabel('Amount of particles')
    plt.xlim(0.5,4)
    #plt.ylim([-0.5,2])
    plt.legend(loc=1, prop={'size':12})   
    
    save(s_title, ext=format, close=False, verbose=True)
  elif (style == 1):
  
    width = 0.05
    opacity=0.7
    fig, ax = plt.subplots()
    ax.bar(interval,data_2,width, color='red', label=names[2])
    ax.bar(interval,data_3,width, color='black', alpha=opacity, label=names[3])
    plt.title('First plot')
    plt.xlabel('Liquid') #das r hier markiert, dass jetz latex code kommt
    plt.ylabel('Amount of particles')
    plt.xlim(0.5,2)
    #plt.ylim([-0.5,2])
    plt.legend(loc=1, prop={'size':12})   
    
    save(s_title, ext='pdf', close=False, verbose=True)
Example #25
0
def test_add_background_image():
    """Test adding background image to a figure."""
    rng = np.random.RandomState(0)
    for ii in range(2):
        f, axs = plt.subplots(1, 2)
        x, y = rng.randn(2, 10)
        im = rng.randn(10, 10)
        axs[0].scatter(x, y)
        axs[1].scatter(y, x)
        for ax in axs:
            ax.set_aspect(1)

        # Background without changing aspect
        if ii == 0:
            ax_im = add_background_image(f, im)
            return
            assert (ax_im.get_aspect() == 'auto')
            for ax in axs:
                assert (ax.get_aspect() == 1)
        else:
            # Background with changing aspect
            ax_im_asp = add_background_image(f, im, set_ratios='auto')
            assert (ax_im_asp.get_aspect() == 'auto')
            for ax in axs:
                assert (ax.get_aspect() == 'auto')
        plt.close('all')

    # Make sure passing None as image returns None
    f, axs = plt.subplots(1, 2)
    assert (add_background_image(f, None) is None)
    plt.close('all')
def create_plots(params, w_holder, rate_holder):
    print("Creating plots..")
    N_inh_neurons = rate_holder.shape[0]
#    # all spikes
#    plt.figure()
#    plt.plot(SpikeMon.t/ms, SpikeMon.i, '.k', markersize=.1)
#    plt.xlabel("Time (ms)")
#    plt.ylabel("Neuron index")
    
    rate_interval = params["rate_interval"]
    rho_0 = params["rho_0"]
    simtime = params["simtime"]
    dt = params["dt"]

    
    avg_w_stream = np.average(w_holder, axis=0)

    r_idxes = np.random.uniform(rate_holder.shape[0], size=plot_n_rates)
    r_idxes = r_idxes.astype(int)    
    r_stream = rate_holder[r_idxes, :]
    avg_r_stream = np.average(rate_holder, axis=0)

    r_times = np.arange(rate_interval/ms, simtime/ms, rate_interval/ms) * ms  
    w_times = np.arange(0, simtime/ms, rate_interval/ms) * ms

    fig, axes = plt.subplots(2, figsize=(15, 10))
    axes[0].plot(r_times/second, r_stream.T, color="red",
                 alpha=.2, linewidth=.3)
    axes[0].plot(r_times/second, avg_r_stream, color="red", linewidth=2,
                 label="firing_rate")
    axes[0].hlines(rho_0, 0, r_times[-1], linestyles="--")
    axes[0].set_xlim([0, r_times[-1]])
    axes[0].set_xlabel("time [s]")
    axes[0].set_ylabel("firing rate [Hz]")
    axes[0].set_title(str(plot_n_rates) + \
                      " randomly selected firing rates estimated every " + \
                      str(rate_interval))
    axes[1].plot(w_times/second, w_holder.T, color="gray", alpha=.2,
                 linewidth=.3)
    axes[1].plot(w_times/second, avg_w_stream, color="black")
    axes[1].hlines(0, 0, w_times[-1], linestyles="--")
    axes[1].set_ylim([-1, np.amax(w_holder)+10])
    axes[1].set_xlim([0, w_times[-1]])
    axes[1].set_xlabel("time [s]")
    axes[1].set_ylabel("Inh to exc weight")
    axes[1].set_title(str(w_holder.shape[0]) + \
                      " randomly selected inh-to-exc weights")

    
    # firing rate plot as matrix
    rate_vector = rate_holder[:, -1]
    matrix_axis = np.floor(np.sqrt(len(rate_vector)))
    rate_vector = rate_vector[:matrix_axis**2]
    rate_mat = np.reshape(rate_vector, (int(np.sqrt(N_inh_neurons)), -1))
    fig, ax = plt.subplots()
    ax.pcolor(rate_mat, cmap="Reds")
    plt.title("Inh firing rate estimated with counting spikes")
    plt.xticks([]); plt.yticks([]);
    
    plt.show()
def execute(model, data, savepath, *args, **kwargs):

    fluence_divisions = [3.3E18, 3.3E19, 3.3E20]
    flux_divisions = [5e11,2e11,1e11]

    fig, ax = plt.subplots(1,3, figsize = (30,10))
    for x in range(len(fluence_divisions)):
        model = model
        data.remove_all_filters()
        data.add_inclusive_filter("fluence n/cm2", '<', fluence_divisions[x])
        l_train = len(data.get_y_data())
        model.fit(data.get_x_data(), np.array(data.get_y_data()).ravel())

        data.remove_all_filters()
        data.add_inclusive_filter("fluence n/cm2", '>=', fluence_divisions[x])
        l_test = len(data.get_y_data())
        Ypredict = model.predict(data.get_x_data())
        RMSE = np.sqrt(mean_squared_error(Ypredict, np.array(data.get_y_data()).ravel()))

        matplotlib.rcParams.update({'font.size': 26})
        ax[x].scatter(data.get_y_data(), Ypredict, color='black', s=10)
        ax[x].plot(ax[x].get_ylim(), ax[x].get_ylim(), ls="--", c=".3")
        ax[x].set_xlabel('Measured ∆sigma (Mpa)')
        ax[x].set_ylabel('Predicted ∆sigma (Mpa)')
        ax[x].set_title('Testing Fluence > {}'.format(fluence_divisions[x]))
        ax[x].text(.1, .88, 'RMSE: {:.3f}'.format(RMSE),fontsize = 30, transform=ax[x].transAxes)
        ax[x].text(.1, .83, 'Train: {}, Test: {}'.format(l_train, l_test), transform=ax[x].transAxes)

    fig.tight_layout()
    plt.subplots_adjust(bottom = .2)
    fig.savefig(savepath.format("fluence_extrapolation"), dpi=150, bbox_inches='tight')
    plt.close()

    fig, ax = plt.subplots(1, 3, figsize=(30, 10))
    for x in range(len(flux_divisions)):
        model = model
        data.remove_all_filters()
        data.add_inclusive_filter("flux n/cm2/s", '>', flux_divisions[x])
        l_train = len(data.get_y_data())
        model.fit(data.get_x_data(), np.array(data.get_y_data()).ravel())

        data.remove_all_filters()
        data.add_inclusive_filter("flux n/cm2/s", '<=', flux_divisions[x])
        l_test = len(data.get_y_data())
        Ypredict = model.predict(data.get_x_data())
        RMSE = np.sqrt(mean_squared_error(Ypredict, np.array(data.get_y_data()).ravel()))

        matplotlib.rcParams.update({'font.size': 26})
        ax[x].scatter(data.get_y_data(), Ypredict, color='black', s=10)
        ax[x].plot(ax[x].get_ylim(), ax[x].get_ylim(), ls="--", c=".3")
        ax[x].set_xlabel('Measured ∆sigma (Mpa)')
        ax[x].set_ylabel('Predicted ∆sigma (Mpa)')
        ax[x].set_title('Testing Flux < {:.0e}'.format(flux_divisions[x]))
        ax[x].text(.1, .88, 'RMSE: {:.3f}'.format(RMSE), fontsize=30, transform=ax[x].transAxes)
        ax[x].text(.1, .83, 'Train: {}, Test: {}'.format(l_train, l_test), transform=ax[x].transAxes)

    fig.tight_layout()
    plt.subplots_adjust(bottom=.2)
    fig.savefig(savepath.format("flux_extrapolation"), dpi=150, bbox_inches='tight')
    plt.close()
Example #28
0
def _get_axes(dim, axes=None, triangle=False, subplots_kwargs=dict()):
    """
    Parameters
    ----------
    dim : int
        Dimensionality of the orbit.
    axes : array_like (optional)
        Array of matplotlib Axes objects.
    triangle : bool (optional)
        Make a triangle plot instead of plotting all projections in a single row.
    subplots_kwargs : dict (optional)
        Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.
    """

    import matplotlib.pyplot as plt

    if dim == 3:
        if triangle and axes is None:
            figsize = subplots_kwargs.pop('figsize', (8,8))
            sharex = subplots_kwargs.pop('sharex', True)
            sharey = subplots_kwargs.pop('sharey', True)
            fig,axes = plt.subplots(2,2,figsize=figsize, sharex=sharex, sharey=sharey,
                                    **subplots_kwargs)
            axes[0,1].set_visible(False)
            axes = axes.flat
            axes = [axes[0],axes[2],axes[3]]

        elif triangle and axes is not None:
            try:
                axes = axes.flat
            except:
                pass

            if len(axes) == 4:
                axes = [axes[0],axes[2],axes[3]]

        elif not triangle and axes is None:
            figsize = subplots_kwargs.pop('figsize', (10,3.5))
            fig,axes = plt.subplots(1, 3, figsize=figsize, **subplots_kwargs)

    elif dim <= 2:
        if axes is not None:
            try:
                len(axes)
            except TypeError:  # single axes object
                axes = [axes]

        else:
            if dim ==1:
                figsize = subplots_kwargs.pop('figsize', (14,8))
            elif dim == 2:
                figsize = subplots_kwargs.pop('figsize', (8,8))

            fig,axes = plt.subplots(1, 1, figsize=figsize, **subplots_kwargs)
            axes = [axes]

    else:
        raise ValueError("Orbit must have dimensions <= 3.")

    return axes
Example #29
0
def main():
    
    Lx = 1.
    Ly = 1.
    V = Lx*Ly
    N = 101
    dk = (2.*np.pi)/Lx
    
    #-----------------------------------------#
    #-- Generate Gaussian random field -------#
    #-----------------------------------------#
    
    kspace_field = gen_2Dgauss(N, Lx, Ly, model0)
    
    config_field = np.fft.ifft2(kspace_field)*kspace_field.size**0.5
    
    fig, ax = pl.subplots()
    im = ax.imshow(config_field.real, cmap=pl.cm.jet)
    fig.colorbar(im, ax=ax)
    pl.title("field.real, config_space")
    pl.show()
    
    fig, ax = pl.subplots()
    im = ax.imshow(config_field.imag, cmap=pl.cm.jet)
    fig.colorbar(im, ax=ax)
    pl.title("field.imag, config_space")
    pl.show()
def main2():
    print(__file__ + " start!!")

    dl = 1.0  # course tick
    cx, cy, cyaw, ck = get_straight_course3(dl)

    sp = calc_speed_profile(cx, cy, cyaw, TARGET_SPEED)

    initial_state = State(x=cx[0], y=cy[0], yaw=0.0, v=0.0)

    t, x, y, yaw, v, d, a = do_simulation(
        cx, cy, cyaw, ck, sp, dl, initial_state)

    if show_animation:  # pragma: no cover
        plt.close("all")
        plt.subplots()
        plt.plot(cx, cy, "-r", label="spline")
        plt.plot(x, y, "-g", label="tracking")
        plt.grid(True)
        plt.axis("equal")
        plt.xlabel("x[m]")
        plt.ylabel("y[m]")
        plt.legend()

        plt.subplots()
        plt.plot(t, v, "-r", label="speed")
        plt.grid(True)
        plt.xlabel("Time [s]")
        plt.ylabel("Speed [kmh]")

        plt.show()
Example #31
0
result.

"""

from skimage.filter.rank import autolevel_percentile

image = data.camera()

selem = disk(20)
loc_autolevel = autolevel(image, selem=selem)
loc_perc_autolevel0 = autolevel_percentile(image, selem=selem, p0=.00, p1=1.0)
loc_perc_autolevel1 = autolevel_percentile(image, selem=selem, p0=.01, p1=.99)
loc_perc_autolevel2 = autolevel_percentile(image, selem=selem, p0=.05, p1=.95)
loc_perc_autolevel3 = autolevel_percentile(image, selem=selem, p0=.1, p1=.9)

fig, axes = plt.subplots(nrows=3, figsize=(7, 8))
ax0, ax1, ax2 = axes
plt.gray()

ax0.imshow(np.hstack((image, loc_autolevel)))
ax0.set_title('Original / auto-level')

ax1.imshow(np.hstack((loc_perc_autolevel0, loc_perc_autolevel1)),
           vmin=0,
           vmax=255)
ax1.set_title('Percentile auto-level 0%,1%')
ax2.imshow(np.hstack((loc_perc_autolevel2, loc_perc_autolevel3)),
           vmin=0,
           vmax=255)
ax2.set_title('Percentile auto-level 5% and 10%')
stop_iter_list_1 = []
stop_iter_list_2 = []
f_newstop_list = []
for eps, eta in zip(eps_list, eta_list):

    u, v, info_1 = sinkhorn_uot(C, a.reshape(nr,1), b.reshape(nc,1), eta=eta, t1=tau, t2=tau, n_iter=20000, early_stop=False, eps=eps, opt_val=prob.value)
    u, v, info_2 = sinkhorn_uot_newstop(C, a.reshape(nr,1), b.reshape(nc,1), eta=eta, t1=tau, t2=tau, n_iter=20000, early_stop=False, eps=eps, opt_val=prob.value)
    stop_iter_list_1.append(info_1['stop_iter'])
    stop_iter_list_2.append(info_2['stop_iter'])
    f_newstop_list.append(info_2['unreg_f_val_list'][-1])
    
# print(info_2['unreg_f_val_list'])
# print(stop_iter_list_2)
# plt.plot([0, 1000], [prob.value, prob.value], c='red')
fig, ax = plt.subplots(3,1)
xs = np.arange(n_eps)
ax[0].plot(xs, stop_iter_list_1, label=f'empirical (main), opt val={prob.value:.3f}')
ax[0].plot(xs, stop_iter_list_2, label=f'new stopping rule')
eps_list_str = ['{:.2f}'.format(x) for x in eps_list]
ax[0].set_xticklabels(eps_list_str)

ax[0].set_xlabel('epsilon')
ax[0].set_ylabel('k (iteration)')
inv_eps = 1 / eps_list
# inv_eps = stop_iter_list[0] / inv_eps[0] * inv_eps

inv_eps_2 = 1 / eps_list**2
# inv_eps_2 = stop_iter_list[0] / inv_eps_2[0] * inv_eps_2

# inv_eps_log = 1 / eps_list * np.log(1 / eps_list)
Example #33
0
def lineplot(X,y):
    _, ax = plt.subplots()
    ax.plot(X, y, lw = 2, color = '#539caf', alpha = 1)
# Going to store the sum of the slice areas here.
int_val_arr = [[] for xx in range(len(x_arr))]
int_val_arr[0] = 0  # Again, first term 0, so zero will be plotted

summ = float(0)

for xx in range(len(x_arr) - 1):  # length minus one because in the indexing,
    # we beed to call xx + 1
    a = x_arr[xx]  # Setting the lower boundary
    b = x_arr[xx + 1]  # Setting the upper boundary

    little_areas[xx + 1] = int_steps(a, b, N)  # Storing the area calculated
    # from between the two edges

    summ += little_areas[xx + 1]  # Adding this value to a sum of the full area

    int_val_arr[xx + 1] = summ  # Putting the sum in an array for future plot

int_val_arr = array(int_val_arr)

fig, ax = plt.subplots()
ax.plot(x_arr, int_val_arr, color="purple")
ax.set_xlabel("x-value")
ax.set_ylabel("E(x): Area under the curve up to this point")
ax.set_title("Plot of E(x)")

plt.tight_layout()
plt.show()

# END PROGRAM
Example #35
0
#
# Zdrojový kód tohoto skriptu ve stylu literate programming
# https://tisnik.github.io/presentations/appendix/lit_sources/parametric/Bezier_quadric_basis.html
#

import numpy as np
import matplotlib.pyplot as plt

# hodnoty parametru t
t = np.linspace(0, 1, 50)

# Bernsteinovy polynomy pro Bézierovu kvadriku
B = [1 * (1 - t)**2, 2 * t * (1 - t), 1 * t**2]

# rozměry grafu při uložení: 640x480 pixelů
fig, ax = plt.subplots(1, figsize=(6.4, 4.8))

# titulek grafu
fig.suptitle('Bázové polynomy', fontsize=15)

# určení rozsahů na obou souřadných osách
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

# bázové polynomy
ax.plot(t, B[0], 'r-', label='b0,2')
ax.plot(t, B[1], 'g-', label='b1,2')
ax.plot(t, B[2], 'b-', label='b2,2')

# zobrazení legendy
ax.legend()
  feature_names[1] = 'HT_all_maybe_copy'

with open('../../Data/'+data_from, 'rb') as f:
    data_insts = pickle.load(f)
    data_labels = pickle.load(f)
    data_name = pickle.load(f)

source_insts = data_insts[0].toarray()[:1000]
source_labels = data_labels[0].flatten()[:1000]
print(source_insts.shape)
dic = {key: value for key, value in zip(range(1,1+len(feature_names)), feature_names)}
print(dic)
print(np.corrcoef(np.transpose(source_insts)))
X2 = np.transpose(source_insts)
corr = (100 * np.corrcoef(np.transpose(source_insts))).astype(int)
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10,10))
sns.heatmap(corr, ax=axes, xticklabels=range(1, source_insts.shape[1]+1),yticklabels=range(1,source_insts.shape[1]+1), annot=True, fmt = '.3g')
axes.set_xlabel('Features',fontsize=15)
axes.set_ylabel('Features',fontsize=15)
axes.set_title('Correlation',fontsize=20)
plt.show()

'''
for i, f_name_i in zip(range(len(feature_names)), feature_names):
  for j, f_name_j in zip(range(len(feature_names)), feature_names):
    if i > j:
      plt.scatter(source_insts[source_labels==1,i], source_insts[source_labels==1, j], alpha = 0.5, color = 'b', label = 'sgnl')
      plt.scatter(source_insts[source_labels==0,i], source_insts[source_labels==0, j], alpha = 0.5, color = 'red', label ='bkg1')
      plt.xlabel(f_name_i)
      plt.ylabel(f_name_j)
      plt.legend(loc='upper right')
def viz_ref_points(img_virtual,
                   img_lowMag,
                   img_aligned,
                   transf,
                   pos_img_virtual,
                   pos_img_lM,
                   r,
                   circles=True):
    _, axes = plt.subplots(2, 2, figsize=(10, 10))

    colors = ['r', 'g', 'b', 'y', 'cyan', 'w', 'm']

    axes[0, 0].imshow(img_virtual,
                      cmap='gray',
                      interpolation='none',
                      vmin=0,
                      vmax=255)
    axes[0, 0].axis('off')
    axes[0, 0].set_title("Source Image")
    if circles == True:
        for (xp, yp), c in zip(pos_img_virtual[:len(colors)], colors):
            circ = plt.Circle((xp, yp),
                              r,
                              fill=False,
                              edgecolor=c,
                              linewidth=2)
            axes[0, 0].add_patch(circ)

    axes[0, 1].imshow(img_lowMag,
                      cmap='gray',
                      interpolation='none',
                      vmin=0,
                      vmax=255)
    axes[0, 1].axis('off')
    axes[0, 1].set_title("Target Image")
    if circles == True:
        for (xp, yp), c in zip(pos_img_lM[:len(colors)], colors):
            circ = plt.Circle((xp, yp),
                              r * transf.scale,
                              fill=False,
                              edgecolor=c,
                              linewidth=2)
            axes[0, 1].add_patch(circ)

    axes[1, 1].imshow(img_aligned,
                      cmap='gray',
                      interpolation='none',
                      vmin=0,
                      vmax=255)
    axes[1, 1].axis('off')
    axes[1, 1].set_title("Source Image aligned with Target")
    if circles == True:
        for (xp, yp), c in zip(pos_img_lM[:len(colors)], colors):
            circ = plt.Circle((xp, yp),
                              r * transf.scale,
                              fill=False,
                              edgecolor=c,
                              linewidth=2)
            axes[1, 1].add_patch(circ)

    axes[1, 0].axis('off')

    plt.tight_layout()
    plt.show()
    print("Training finished, took {:.2f}s".format(time.time() -
                                                   training_start_time))


if __name__ == '__main__':
    np.random.seed(0)
    T.manual_seed(0)
    dataX = T.load('time_series_x_100x.pt')
    dataY = T.load('time_series_y_100x.pt')

    model = TempConv(20)
    model.double()

    trainNet(model, 20, 1, 0.001, dataX, dataY)

    # Visualize conv1 filters
    kernels = model.conv1.weight.detach()
    fig, axarr = plt.subplots(kernels.size(0))
    for idx in range(kernels.size(0)):
        print(kernels[idx].squeeze())
        axarr[idx].plot(list(range(100)), kernels[idx].squeeze().numpy())
    plt.show()

    # Visualize conv2 filters
    kernels = model.conv2.weight.detach()
    fig, axarr = plt.subplots(kernels.size(0))
    for idx in range(kernels.size(0)):

        axarr[idx].plot(list(range(50)), kernels[idx].numpy().transpose())
    plt.show()
#
###
#
# font sizes
#
matplotlib.rcParams.update({'font.size': 48})  #axis numbers
#
title_fontsize = 54  #plot title
axis_fontsize = 48  #axis labels
annotate_fontsize = 48  #annotation
#
###
#
# set up for two y axis
#
fig, left_axis = plot.subplots()
# right_axis=left_axis.twinx()
#
###
#
# plot text
#
title = 'Dose rate - Top plate'
xtitle = 'Wall thickness [cm]'
ytitle = 'Dose rate [$\mu$Sv/h]'
#
###
#
# legend
# add linecolorN for each plot_dataN
# add curve_textN for each plot_dataN
Example #40
0
DATA_DIR = Path("data")

if __name__ == "__main__":
    epochs = list(range(1, 21))

    tr_loss = pd.read_csv(DATA_DIR / "ddc_loss_training.csv")["Value"].values
    va_loss = pd.read_csv(DATA_DIR / "ddc_loss_validation.csv")["Value"].values

    ax = plt.axes(xlabel="Epoch", ylabel="Binary cross entropy loss")
    ax.plot(epochs, tr_loss, 'o-', label="Training loss")
    ax.plot(epochs, va_loss, 'o-', label="Validation loss")
    ax.set_xticks(epochs)
    ax.legend()

    plt.savefig("ddc_losses.pdf")

    mmd = np.sqrt(pd.read_csv(DATA_DIR / "ddc_loss_mmd.csv")["Value"].values)
    no_mmd = pd.read_csv(DATA_DIR / "ddc_no-mmd-loss_mmd.csv")["Value"].values

    fig, axs = plt.subplots(nrows=2, sharex=True)
    axs[0].plot(epochs, no_mmd, 'o-', label="No MMD loss")
    axs[1].plot(epochs, mmd, 'o-', label="MMD loss")
    axs[1].set_xticks(epochs)
    for ax in axs:
        ax.legend()
        ax.set_ylabel("MMD")
    axs[1].set_xlabel("Epoch")

    plt.savefig("ddc_mmds.pdf")
Example #41
0
# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap
sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns)

#%% Boxplots
plots = list()
num_boxplots = df_numeric_nonan.shape[1]
#num_boxplots = 2

fig, ax = plt.subplots(
    nrows=num_boxplots,
    ncols=1,
    figsize=(20, 40),
    #figsize=(20,10),
    sharex=False,
    sharey=False)

for colnum in range(num_boxplots):

    # The data
    data_series = df_numeric_nonan.iloc[:, colnum]
    this_mean = data_series.describe()['mean']
    this_median = data_series.describe()['50%']
    this_std = data_series.describe()['std']
    this_min = data_series.describe()['min']
    this_max = data_series.describe()['max']

    # Boxplot
Example #42
0
        ypoints=DataSums[:z]
ylistsdf = pd.DataFrame(ylists, index=['S','E','I','R'])

# =============================================================================
# Plots and Prints
# =============================================================================
GraphStartDate= '5/10/20'
GraphEndDate= '6/30/20'
GraphStartDateObj=datetime.strptime(GraphStartDate,'%m/%d/%y')
GraphEndDateObj=datetime.strptime(GraphEndDate,'%m/%d/%y')
StartRange = (GraphStartDateObj-StartDateObj).days
EndRange = (GraphEndDateObj-StartDateObj).days
# =============================================================================
# ActiveInfsRange = range(len(ActiveInfs))
# =============================================================================
fig, axes = plt.subplots(1, 1, figsize=(15,9))
# Plotting [S, E, I, R]
labels = ["pSusceptible", "pExposed", "pInfected", "pRecovered"]
for y_arr, label in zip(ylists, labels):
    if label in ["pInfected", "pRecovered", "pExposed"]:
        plt.plot(tlists.T[StartRange:EndRange], y_arr[StartRange:EndRange], label=label)
plt.plot(tlists.T[StartRange:EndRange], ylists[2][StartRange:EndRange]+ylists[3][StartRange:EndRange], label="Cumulative Predicted Cases (I+R)")
plt.plot(tSpaceT[StartRange:EndRange], ypoints[StartRange:EndRange], label="Cumulative Reported Cases (I+R)")
# =============================================================================
# plt.plot(ActiveInfsRange[StartRange:EndRange], ActiveInfs[StartRange:EndRange], label="Active Infections")
# plt.plot(ActiveInfsRange[StartRange:EndRange], Recovered[StartRange:EndRange], label="Actual Recovered")
# plt.plot(range(times[numOfParts]+1), ActiveInfs[:times[numOfParts]+1], label="Actual Active Infections")
# plt.plot(range(times[numOfParts]+1), totalIR2[:times[numOfParts]+1], label="totalIR2")
#plt.plot(range(times[numOfParts]+1), RecoveredList[:times[numOfParts]+1], label="Actual Recovered")
# plt.plot(range(times[numOfParts]+1), Recovered2[:times[numOfParts]+1], label="Actual Recovered")
# =============================================================================
    diversity = int(len(uniques))
    print('The exceedances, upper: ' + str(upper_exceedances) + ' lower: ' +
          str(lower_exceedances))
    print('The diversity is: ' + str(diversity))

    # More efficient and elegant pyplot
    plt.style.use(['science', 'no-latex'])
    rcParams['axes.titlepad'] = 10
    rcParams['ytick.labelsize'] = 20
    rcParams['xtick.labelsize'] = 16

    textstr = '\n'.join((r'Upper exceedances$=%.0f$' % (upper_exceedances, ),
                         r'Lower exceedances$=%.0f$' % (lower_exceedances, ),
                         r'Diversity$=%.0f$' % (diversity)))

    fig, ax = plt.subplots(1, figsize=(10, 10), dpi=300)
    ax.plot_date(dates_EONIA[20:], upper, 'b-', color='#0C5DA5')
    ax.plot_date(dates_EONIA[20:], lower, 'b-', color='#00B945')
    ax.plot_date(dates_EONIA[20:], differences, 'b-', color='#FF9500')
    plt.title('20-day VaR(99%) for EONIA after ' + str(epoch) + ' epochs',
              fontsize=24,
              fontweight='roman')
    plt.xlabel(r'Time $t$', fontsize=20, fontweight='roman', labelpad=10)
    plt.ylabel(r'$\Delta r_t$', fontsize=20, fontweight='roman', labelpad=10)
    plt.legend(['upper 99%-VaR', 'lower 99%-VaR', 'EONIA'],
               loc='lower left',
               prop={'size': 24})

    # Add a line to distinguish between the train and test set
    ax.axvline(x=dates_EONIA[250], ymin=0, ymax=1, ls='--', color='red')
Example #44
0
def plot_two_profiles(vprofile,
                      rprofile,
                      hz=1.0,
                      hr=1.0,
                      outfig=False,
                      units='m_p cm^-2',
                      title=False,
                      rmin='4 kpc',
                      rmax='10 kpc',
                      zmin='0 kpc',
                      zmax='4 kpc'):
    import matplotlib.pyplot as plt

    if outfig: plt.ioff()
    else: plt.ion()
    f, ax = plt.subplots(1, 2)

    if isinstance(rmin, str): rmin = un.Unit(rmin).in_units('kpc')
    if isinstance(rmax, str): rmax = un.Unit(rmax).in_units('kpc')
    if isinstance(zmin, str): zmin = un.Unit(zmin).in_units('kpc')
    if isinstance(zmax, str): zmax = un.Unit(zmax).in_units('kpc')

    vrad = vprofile['rbins'].in_units('kpc')
    vpmass = vprofile['mass'].in_units('Msol')

    dz = vprofile['rbins'].in_units('kpc')[1] - vprofile['rbins'].in_units(
        'kpc')[0]
    vbinsize = math.pi * (rmax * rmax - rmin * rmin) * dz

    vN_0 = (np.sum(vpmass / vbinsize * dz) /
            (2.0 * hz *
             (math.tanh(zmax / (2.0 * hz)) - math.tanh(zmin / (2.0 * hz)))))

    ax[0].errorbar(
        vrad,
        vpmass / vbinsize,
        yerr=vpmass / vbinsize / np.sqrt(vprofile['n']),
        fmt='o')
    ax[0].semilogy(
        vrad,
        vN_0 * (np.cosh(vrad / (2.0 * hz))**-2),
        label='h: %2.1f kpc; $N_0$: %2.1f' % (hz, vN_0),
        linestyle='dashed')
    if title: ax[0].set_title(title)
    ax[0].set_xlabel('Z [kpc]')
    ax[0].set_ylabel('Density [M$_\odot$ kpc$^{-3}$]')
    ax[0].legend(loc=0)

    rrad = rprofile['rbins'].in_units('kpc')
    rpmass = rprofile['mass'].in_units('Msol')

    rbinsize = rprofile._binsize.in_units('kpc^2') * (zmax - zmin)
    rN_0 = (np.sum(rpmass / rbinsize * rprofile['dr'].in_units('kpc')) /
            (2.0 * math.pi * hr *
             (-math.exp(-rmax / hr) * (hr + rmax) + math.exp(-rmin / hr) *
              (hr + rmin))))

    ax[1].errorbar(
        rrad,
        rpmass / rbinsize,
        yerr=rpmass / rbinsize / np.sqrt(rprofile['n']),
        fmt='o')
    ax[1].semilogy(
        rrad,
        rN_0 * (np.exp(-rrad / hr)),
        label='h: %2.1f kpc; $N_0$: %2.1f' % (hr, rN_0),
        linestyle='dashed')
    ax[1].set_xlabel('R [kpc]')
    ax[1].set_ylabel('Density [M$_\odot$ kpc$^{-3}$]')
    ax[1].legend(loc=0)
    if outfig:
        plt.savefig(outfig + '.png')
    plt.clf()
    plt.close()
Example #45
0
X_test.shape

y_train.shape

y_test.shape

"""# STEP #3: DATA VISUALIZATION"""

i = 300
plt.imshow(X_train[i])
print(y_train[i])

W_grid = 4
L_grid = 4

fig, axes = plt.subplots(L_grid, W_grid, figsize = (15, 15))
axes = axes.ravel()

n_training = len(X_train)

for i in np.arange(0, L_grid * W_grid):
    index = np.random.randint(0, n_training) # pick a random number
    axes[i].imshow(X_train[index])
    axes[i].set_title(y_train[index])
    axes[i].axis('off')
    
plt.subplots_adjust(hspace = 0.4)

n_training

"""# STEP#4: DATA PREPARATION"""
Example #46
0
from sklearn import svm

iris = datasets.load_iris()

X = iris.data
y = iris.target
dim = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
y_dim = [dim[i] for i in y]
target_names = iris.target_names
feature_names = iris.feature_names

colors = ['navy', 'turquoise', 'darkorange', 'purple']

# Plot the 4 features of Iris dataset: sepal length, sepal width, petal length,
# and petal width.
fig, g = plt.subplots(2, 2)
subplots = [g[0][0], g[0][1], g[1][0], g[1][1]]
for idx, feature in enumerate(feature_names):
    plot = subplots[idx]
    for color, i, target_name in zip(colors, [0, 1, 2], target_names):
        plot.scatter(X[y == i, idx], y[y == i], color=color, alpha=.8,
                     label=target_name)
    plot.legend(loc='best', shadow=False, scatterpoints=1)
    plot.title.set_text('Feature %s' % feature)

# Linear Regression used for classification
regr = LinearRegression()
regr.fit(X, y_dim)
y_pred = regr.predict(X)
print('\n')
print('Features: %s' % feature_names)
Example #47
0
import os
PANDAS_WIDTH = 150
pd.set_option('display.width', PANDAS_WIDTH)

if __name__ == '__main__':
    chosen_folder = APARTMENT_WALKS_RICCI
    files = os.listdir(chosen_folder)
    for csv_file in files:
        name, ext = os.path.splitext(csv_file)
        if ext != '.csv':
            continue

        csv_file = os.path.join(chosen_folder, csv_file)
        sensordata = SensorData(csv_file)
        print name, sensordata.magnetic().shape

        fig, axs = plt.subplots(2, 2, sharex=True)
        axs[0, 0].plot(sensordata.orient())
        axs[0, 0].set_title('Orient')
        axs[1, 0].plot(sensordata.lin_acc())
        axs[1, 0].set_title('Lin Acc')
        axs[1, 1].plot(sensordata.gyro())
        axs[1, 1].set_title('Gyro')
        axs[0, 1].plot(sensordata.magnetic())
        axs[0, 1].set_title('Mag')

        plt.suptitle("%s \n Measurements" % (name))

        plt.legend()
        plt.show()
Example #48
0
correl = new_data.corr()
class_correl = correl[['Class']]
negative = class_correl[class_correl.Class< -0.5]
positive = class_correl[class_correl.Class> 0.5]
print("negative")
print(negative)
print("positive")
print(positive)


# # visualizing the features with high negative correlation

# In[22]:


f, axes = plt.subplots(nrows=2, ncols=4, figsize=(26,16))

f.suptitle('Features With High Negative Correlation', size=35)
sns.boxplot(x="Class", y="V3", data=new_data, ax=axes[0,0])
sns.boxplot(x="Class", y="V9", data=new_data, ax=axes[0,1])
sns.boxplot(x="Class", y="V10", data=new_data, ax=axes[0,2])
sns.boxplot(x="Class", y="V12", data=new_data, ax=axes[0,3])
sns.boxplot(x="Class", y="V14", data=new_data, ax=axes[1,0])
sns.boxplot(x="Class", y="V16", data=new_data, ax=axes[1,1])
sns.boxplot(x="Class", y="V17", data=new_data, ax=axes[1,2])
f.delaxes(axes[1,3])


# # visualizing the features with high positive correlation

# In[23]:
def setup_axe(axe,df,title):
    df['emotion'].value_counts(sort=False).plot(ax=axe, kind='bar', rot=0)
    axe.set_xticklabels(emotion_labels)
    axe.set_xlabel("Emotions")
    axe.set_ylabel("Number")
    axe.set_title(title)
    
    # set individual bar lables using above list
    for i in axe.patches:
        # get_x pulls left or right; get_height pushes up or down
        axe.text(i.get_x()-.05, i.get_height()+100, \
                str(round((i.get_height()), 2)), fontsize=11, color='dimgrey',
                    rotation=0)

   
fig, axes = plt.subplots(1,3, figsize=(16,8), sharey=True)
setup_axe(axes[0],data_train,'train')
setup_axe(axes[1],data_val,'validation')
setup_axe(axes[2],data_test,'test')
plt.show()

#initilize parameters
num_classes = 7 
width, height = 48, 48
num_epochs = 50
batch_size = 64
num_features = 64


"""
CRNO stands for Convert, Reshape, Normalize, One-hot encoding
Example #50
0
    def plot_segment(self, segment_name, data_name):
        """ Plot results for a segment.

        matplotlib can't plot after vtk grabs the event queue so forget this.
        """
        return
        self.logger.info("---------- Plot segment ----------")
        title = segment_name 
        min_time = self.params.time_range[0]
        max_time = self.params.time_range[1]

        segment = self.segments[segment_name]
        if not segment:
            self.logger.error("No segment names: %s" % segment_name)
            return

        self.logger.info("Segment name: %s" % segment_name)
        self.logger.info("Data name: %s" % data_name)
        self.logger.info("Min time: %f" % min_time)
        self.logger.info("Max time: %f" % max_time)

        for data_name in self.params.data_names:
            self.logger.info("Data name: %s" % data_name)
            times = self.params.times
            plot_values = [] 
            plot_names = [] 
            fig, ax = plt.subplots()
            ylabel = data_name
            data_list = segment.data[data_name]
            data = data_list[-1]

            values = []
            plot_times = [] 
            for i,time in enumerate(times):
                if (time > min_time) and (time <= max_time):
                    values.append(data[i])
                    plot_times.append(time)
            #__for i,time in enumerate(times)
            plot_values.append(values)
            ax.plot(plot_times, values, label=data_name)

            ax.set(xlabel='time (s)', ylabel=ylabel, title=title)
            ax.grid()
            #chartBox = ax.get_position()
            #ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
            #ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
        #__for data_name in self.params.data_names

        # Set the figure window position.
        plt.get_current_fig_manager().window.wm_geometry("+200+100")

        # Add key events.
        cid = plt.gcf().canvas.mpl_connect('key_press_event', self.press_key)

        ## If displaying geometry then don't block.
        if self.params.display_geometry:
            plt.ion()
            plt.show()
            plt.pause(0.001)
        else:
            plt.show()
Example #51
0
MergedData=pd.merge(TempDF,NSAIL,left_index=True,right_index=True,how='left')
MergedData=MergedData.set_index(['Day'])
curr=0
for i in range(30,-1,-1):
    if not(np.isnan(MergedData.iloc[i,1])):
        curr=MergedData.iloc[i,1]
    else:
        MergedData.iloc[i,1]=curr
    #print(MergedData.iloc[i,1])

plt.scatter(MergedData['AvgTemp'],MergedData['Close'])
corr,p_value_corr = stats.spearmanr(MergedData['AvgTemp'],MergedData['Close'])
t_test,p_value_ttest = stats.ttest_rel(MergedData['AvgTemp'],MergedData['Close'])

fig, ax1 = plt.subplots()
color = 'tab:blue'
ax1.set_xlabel('Day of December 2019')
ax1.set_ylabel('Daily average temperature', color=color)
ax1.set_xlim([-1,31])
ax1.set_ylim([0,25])
ax1.plot(MergedData['AvgTemp'], color=color,alpha=0.5,linewidth=2,marker='o')
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
color = 'tab:red'
ax2.set_ylabel('Daily close price(NATNSTEEL.NS)', color=color)  # we already handled the x-label with ax1
ax2.set_ylim([0,2.5])
ax2.plot(MergedData['Close'], color=color,alpha=0.5,linewidth=2,marker='o')
ax2.tick_params(axis='y', labelcolor=color)
ax1.text(20, 2, 'Correlation cofficient:  {}  p-value :{}\nT-test score              :{}  p-value :{}'.format(

# Set variables for edges of the strikezone
sz_top = sz_height_stats['mean'] + 2*sz_height_stats['std']
sz_bot = sz_height_stats['mean'] - 2*sz_height_stats['std']
sz_right = sz_width_stats['mean'] - 2*sz_width_stats['std']
sz_left = sz_width_stats['mean'] + 2*sz_width_stats['std']

print(sz_top, sz_bot, sz_right, sz_left)


# In[36]:


# Plot pitches with general strikezone
fig, ax = plt.subplots(figsize=(10, 10))
_ = ax.scatter(called_strikes_no_outliers['pitch_locx'], called_strikes_no_outliers['pitch_locy'])
_ = ax.axvspan(sz_right, sz_left, 
               ymin = sz_bot/4,
               ymax = sz_top/4,
               color='red', alpha=0.5)


# As shown above in the shaded red area, the "strikezone" covers the corners of the cluster of called strikes. This is the area pitchers should aim for in the hopes of getting a called strike. Although there's still variance here and pitches that were called strikes outside the "strikezone", but that's possibly due to the umpire calling the game and their error, but generally speaking, if a pitcher threw a pitch in the "strikezone", it'll most likely be called a strike and that's what the goal was.
# 
# Next is to classify the location of the pitch depending where it's thrown and if it's a ball or strike.

# In[37]:


# Break strikezone into 9 zones
Example #53
0
def height_MP(mp_args):
    args,f = mp_args
    imager,neighbors,day = args

    #for f in flist:
    basename=f[-23:-4]
    #if os.path.isfile(tmpfs+f[-18:-10]+'/'+basename+'.hkl') and (~REPROCESS):  ######already processed, skip
    #    return          
    
    print('Processing', basename)
    print("Full name: %s" % tmpfs+f[-18:-10]+'/'+basename+'*pkl')
    fpickle = glob.glob(tmpfs+f[-18:-10]+'/'+basename+'*pkl')
    img=None
    #print("len(fpickle)=%i" % len(fpickle))
    if len(fpickle)<=0:
        print("\tPreprocessing\n")
        img=cam.preprocess(imager,f,tmpfs);
    else:
        with open(fpickle[0],'rb') as input:
            try:
                img=pickle.load(input);
            except EOFError:
                img=None                    
    if img is None or img.red is None:
        return
    if img.layers<=0:
        img.dump_img(tmpfs+f[-18:-10]+'/'+f[-23:-4]+'.hkl');
        return;

    if img.layers>=1:
        h = [np.nan]*img.layers
        for inghb,neighbor in enumerate(neighbors):
            bname=basename.replace(imager.camID,neighbor.camID);
            fp_nb = glob.glob(tmpfs+f[-18:-10]+'/'+bname+'*pkl')  
            img1=None;
            if len(fp_nb)<=0:
                fnb=f.replace(imager.camID,neighbor.camID) 
                img1=cam.preprocess(neighbor,fnb,tmpfs);  ###img object contains four data fields: rgb, red, rbr, and cm 
            else:
                with open(fp_nb[0],'rb') as input:
                    try:
                        img1=pickle.load(input);
                    except EOFError:
                        img1=None
                            
            if img1 is None or img1.red is None:
                continue                           
            
            distance = 6367e3*geo.distance_sphere(img.lat,img.lon,img1.lat,img1.lon)
            for ih in range(img.layers):
                if np.isfinite(h[ih]):
                    continue
                if (ih>=1) and (distance<500):
                    break;
                res=cam.cloud_height(img,img1,layer=ih+1, distance=distance)
                if np.isfinite(res) and res<20*distance and res>0.5*distance:
                    h[ih]=int(res);
                    print('Cloud height computed for', f[-23:]);
                    print('Cloud layer',ih+1,':',res,' computed with cameras ',img.camID,img1.camID,'(distance:',distance,'m)')

                    #if not SAVE_FIG:
                    fig,ax=plt.subplots(2,2,figsize=(10,10),sharex=True,sharey=True);
                    ax[0,0].imshow(img.rgb); ax[0,1].imshow(img1.rgb); 
                    ax[0,0].set_title(img.camID); ax[0,1].set_title(img1.camID)
                    ax[1,0].imshow(img.cm); ax[1,1].imshow(img1.cm); 
                    ax[1,0].set_title(str(6367e3*geo.distance_sphere(img.lat,img.lon,img1.lat,img1.lon)))  
                    plt.tight_layout(); 
                    plt.show();                     
        
            if np.isfinite(h[-1]):                
                break                               
#             img.height+=[h];
        img.height=h;
    
    img.dump_img(tmpfs+f[-18:-10]+'/'+f[-23:-4]+'.hkl');
Example #54
0
def print_confusion_matrix(confusion_matrix,
                           class_names,
                           title,
                           modelname,
                           figsize=(10, 7),
                           fontsize=14):
    """Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a seaborn heatmap.
    Saves confusion matrix file to jpg file.
    

    Parameters
    ----------
    confusion_matrix : sklearn.metrics.confusion_matrix
    class_names : String
    title : string
        The title of the confusion matrix
    modelname : string
        The name of the model.
    figsize : touple, optional
        The default is (10, 7).
    fontsize : TYPE, optional
        The default is 14.

    Raises
    ------
    ValueError
        DESCRIPTION.

    Returns
    -------
    None.

    """
    df_cm = pd.DataFrame(
        confusion_matrix,
        index=class_names,
        columns=class_names,
    )
    fig, ax = plt.subplots(1, 1, figsize=figsize)
    try:
        heatmap = sns.heatmap(df_cm,
                              annot=True,
                              ax=ax,
                              fmt="d",
                              cmap=plt.cm.Oranges)
    except ValueError:
        raise ValueError("Confusion matrix values must be integers.")

    heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(),
                                 rotation=0,
                                 ha='right',
                                 fontsize=fontsize)
    heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(),
                                 rotation=45,
                                 ha='right',
                                 fontsize=fontsize)
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.title(title)
    plt.tight_layout()
    b, t = plt.ylim()
    b += 0.5
    t -= 0.5
    plt.ylim(b, t)
    plt.savefig('model/' + modelname + '_' + title + '_confusion_matrix.png')

    return
Example #55
0
                 'other': {
                         'charging_type' : 'if_needed_sunday',
                         'charging_power' : 7.2}}}
ev_data3 = {'dumb': {'type' : 'dumb',
                 'n_ev' : 1000,
                 'other': {
                         'charging_type': 'all_days',
                         'charging_power' : 7.2}}}
names=['if3.6','all3.6', 'if7.2', 'all7.2']
grids = [evmodel.Grid(ndays=ndays, step=step, name=i) for i in names]
# create evs
for i in range(4):
    grids[i].add_evs(nameset='evs', n_evs=nev, ev_type=types[i], **ev_data[i])
    
#f, ([ax1, ax2],  [ax3, ax4]) = plt.subplots(2,2)
f, (ax1, ax2) = plt.subplots(1, 2)
ylim = 3.7*1000
grid1.plot_evload(ax=ax1, ylim=ylim, title='Dumb, 3.6kW, All days')
grid2.plot_evload(ax=ax2, ylim=ylim, title='Dumb, 3.6kW, If needed')
#grid4.plot_evload(ax=ax3, ylim=ylim, title='Dumb, 7.2kW, All days')
#grid3.plot_evload(ax=ax4, ylim=ylim, title='Dumb, 7.2kW, If needed')
f, (ax1, ax2) = plt.subplots(1, 2)
grid1.plot_flex_pot(ax=ax1,title='Dumb, 3.6kW, All days')
grid2.plot_flex_pot(ax=ax2, title='Dumb, 3.6kW, If needed')
# Plot up and dn flex
f, (ax1) = plt.subplots(1, 1)
ax1.plot(grid1.ev_up_flex['Total'] - grid1.ev_mean_flex['Total'], label='Systematic, Up flexibility', linestyle='-', color='b')
ax1.plot(grid1.ev_dn_flex['Total'] - grid1.ev_mean_flex['Total'], label='Systematic, Down flexibility', linestyle='-', color='c')
ax1.plot(grid2.ev_up_flex['Total'] - grid2.ev_mean_flex['Total'], label='Non-systematic, Up flexibility', linestyle='-', color='r')
ax1.plot(grid2.ev_dn_flex['Total'] - grid2.ev_mean_flex['Total'], label='Non-systematic, Down flexibility', linestyle='-', color='orange')
ax1.legend(loc=2)
Example #56
0
            X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)
            sess.run(optimizer,
                     feed_dict={
                         x: X_batch,
                         y: y_batch,
                         keep_prob: 1.
                     })
            loss, acc = sess.run([cost, accuracy],
                                 feed_dict={
                                     x: X_batch,
                                     y: y_batch,
                                     keep_prob: 1.
                                 })
            if epochs % display_step == 0:
                print("Epoch:", "%04d" % (epoch + 1), "cost=",
                      "{:.9f}".format(loss), "Training_accuracy",
                      "{:.5f}".format(acc))
    print("optimization completed")

    y1 = sess.run(pred, feed_dict={x: X_test, y: y_test, keep_prob: 1})
    test_classes = np.argmax(y1, 1)
    print(
        "Testing Accuracy:",
        sess.run(accuracy,
                 feed_dict={
                     x: X_test[:256],
                     y: y_test[:256],
                     keep_prob: 1
                 }))
    f, a = plt.subplots(1, 10, figsize=(10, 2))
Example #57
0
'''
# To plot histogram
directory = os.chdir("data/")
file_name = [
    "truckstrategy_0_ofat_truck_strategy___repli_1000__dist_samp_1.csv",
    "truckstrategy_1_ofat_truck_strategy___repli_1000__dist_samp_1.csv",
    "truckstrategy_2_ofat_truck_strategy___repli_1000__dist_samp_1.csv",
    "truckstrategy_3_ofat_truck_strategy___repli_1000__dist_samp_1.csv",
    "truckstrategy_4_ofat_truck_strategy___repli_1000__dist_samp_1.csv"
]

for i in file_name:

    data = pd.read_csv(i)

    f, axs = plt.subplots(1, figsize=(10, 7))


    if i =='truckstrategy_0_ofat_truck_strategy___repli_1000__dist_samp_1.csv' or \
            i=='truckstrategy_4_ofat_truck_strategy___repli_1000__dist_samp_1.csv':

        hist = data["On Fire"].hist(range=(0.90, 1))

    else:
        hist = data["On Fire"].hist()

    hist.set_xlabel("Burnt ", fontweight='bold', fontsize=20)
    hist.set_ylabel("Occurrence (#)", fontweight='bold', fontsize=20)
    axs.xaxis.set_tick_params(labelsize=20)
    axs.yaxis.set_tick_params(labelsize=20)
    plt.xlim(0, 1)
Example #58
0

import matplotlib.ticker as ticker
def fmt(x, pos):
    a, b = '{:.1f}'.format(100*x).split('.')
    return r'{:}.{:} \%'.format(a, b)


levels = [0, 0.001, 0.005, 0.01, 0.05]

# nicely distinguisable from set1 categorical
_colors = ['#984ea3', '#4daf4a', '#377eb8', '#ff7f00', '#e41a1c']


dpi = 100
fig, axes = pl.subplots(nrows=3, ncols=3, sharex=False, sharey=False, figsize=(14,12), dpi=dpi)
fig.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.05, hspace=0.5)

for ix,iy in np.ndindex((x1,x2)):
    i = ix*x2 + iy
    f = fs[i]
    axs = axes[ix, iy]
    cp = axs.contourf(Rs*2e6, Rs*2e6, err_S[i], levels, colors=_colors)

    if np.abs(f-ff1)<0.01:
        # dot with thick outline achieved by stacking 2 circle of different radius
        cc_gt_outer = Circle((RR2*2e6, RR1*2e6), radius=0.14, color='black')
        axs.add_patch(cc_gt_outer)
        cc_gt_inner = Circle((RR2*2e6, RR1*2e6), radius=0.06, color='white')
        axs.add_patch(cc_gt_inner)
Example #59
0
# volume of sphere with radius r
def vol(r):
    return 4/3 * np.pi * np.power(r, 3)
vol = np.vectorize(vol)

# mean density of sphere of radius r
def mean_density(r):
    return menc(r) / vol(r)
mean_density = np.vectorize(mean_density)

x = np.arange(40)
y1 = local_density(x)
y2 = menc(x)
y3 = mean_density(x)


fig, ax = plt.subplots(3, sharex=True, figsize=(12, 12))
ax[0].plot(x, y1)
ax[0].set_title('local density')
ax[0].set_ylabel('$M_\odot\,kpc^{-3}$')
ax[1].plot(x, y2)
ax[1].set_title('mass enclosed')
ax[1].set_ylabel('$M_\odot$')
ax[2].plot(x, y3)
ax[2].set_title('mean density')
ax[2].set_ylabel('$M_\odot\,kpc^{-3}$')
plt.xlabel('distance from center of galaxy (kpc)')
plt.show()

Example #60
0
                     np.mean(Mfluxz), np.std(Mfluxz)
                 ))

triangle.corner(np.transpose(np.asarray([M.trace('X')[:],
                                         M.trace('Y')[:],
                                         M.trace('Z')[:],
                                         M.trace('phi_0')[:]])),
                labels=['$\lambda_x$ (m)', '$\lambda_y$ (m)',
                        '$\lambda_z$ (m)', '$\phi_0$ (m$^2$ s$^{-2}$)'])
fig = plt.gcf()
pf.my_savefig(fig, save_string, 'MCMC_triangle', sdir, ftype='png',
              fsize='double_col')
plt.close()

# Plot fit comparison.
fig, axs = plt.subplots(1, 5, sharey=True, figsize=(6.5, 3))
axs[0].plot(100.*U, z, color='black')
axs[0].set_xlabel('$u$ (cm s$^{-1}$)')
axs[0].set_ylabel('$z$ (m)')
axs[1].plot(100.*V, z, color='black')
axs[1].set_xlabel('$v$ (cm s$^{-1}$)')
axs[2].plot(100.*W, z, color='black')
axs[2].set_xlabel('$w$ (cm s$^{-1}$)')
axs[3].plot(10000.*B, z, color='black')
axs[3].set_xlabel('$b$ ($10^{-4}$ m s$^{-2}$)')
axs[4].plot(100.*PP, z, color='black')
axs[4].set_xlabel('$\phi$ ($10^{-2}$ m$^2$ s$^{-2}$)')

Ns = (samples - burn)/thin

for i in xrange(0, Ns, 40):