Example #1
0
def plot_distribution(axes, X, y, hist_nbins=50, title="",
                      x0_label="", x1_label=""):
    ax, hist_X1, hist_X0 = axes

    ax.set_title(title)
    ax.set_xlabel(x0_label)
    ax.set_ylabel(x1_label)

    # The scatter plot
    colors = cm.plasma_r(y)
    ax.scatter(X[:, 0], X[:, 1], alpha=0.5, marker='o', s=5, lw=0, c=colors)

    # Removing the top and the right spine for aesthetics
    # make nice axis layout
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    ax.spines['left'].set_position(('outward', 10))
    ax.spines['bottom'].set_position(('outward', 10))

    # Histogram for axis X1 (feature 5)
    hist_X1.set_ylim(ax.get_ylim())
    hist_X1.hist(X[:, 1], bins=hist_nbins, orientation='horizontal',
                 color='grey', ec='grey')
    hist_X1.axis('off')

    # Histogram for axis X0 (feature 0)
    hist_X0.set_xlim(ax.get_xlim())
    hist_X0.hist(X[:, 0], bins=hist_nbins, orientation='vertical',
                 color='grey', ec='grey')
    hist_X0.axis('off')
Example #2
0
def pm10cmap():
    # This function returns the colormap and bins for the NO2/NO/NOx spatial plots
    # this is designed to have a vmin =0 and vmax = 140
    # return cmap,bins
    colors1 = cm.viridis(linspace(0, 1, 128))
    colors2 = cm.plasma_r(linspace(.042, .75, 128))
    colors = vstack((colors1, colors2))
    return mcolors.LinearSegmentedColormap.from_list('noxcmap',
                                                     colors), arange(
                                                         0, 150.5, .5)
Example #3
0
def plot_one_spheroid(omega):
    n = 100

    def get_one_T(omega, theta):
        r, g, T, F = solve_ELR(omega, theta)
        return T

    Re = 1.0
    Rp = Rp_div_Re(omega) * Re

    # Set of all spherical angles:
    phi = linspace(-pi, pi, n)
    nu = linspace(-pi / 2, pi / 2, n)

    angles = outer(ones_like(phi), nu)
    T = outer(ones_like(phi), ones_like(nu))
    for j in range(n):
        theta = angles[0, j]
        T[:, j] = get_one_T(omega, theta)

    if (Rp == Re):  #spherical
        a = Re
        x = a * outer(cos(phi), cos(nu))
        y = a * outer(sin(phi), cos(nu))
        z = a * outer(ones_like(phi), sin(nu))

        T = outer(ones_like(phi), ones_like(nu))

    else:  #spheroidal
        mu = arctanh(Rp / Re)
        a = sqrt(Re * Re - Rp * Rp)

        # Cartesian coordinates that correspond to the spherical angles:
        # (this is the equation of an ellipsoid):
        x = a * cosh(mu) * outer(cos(phi), cos(nu))
        y = a * cosh(mu) * outer(sin(phi), cos(nu))
        z = a * sinh(mu) * outer(ones_like(phi), sin(nu))

        Tmin = T.min()
        Tmax = T.max()
        T = (T - Tmin) / (Tmax - Tmin)

    fig = figure(figsize=figaspect(1))  # Square figure
    ax = fig.add_subplot(111, projection='3d', aspect='equal')
    ax.plot_surface(x, y, z, rstride=4, cstride=4, facecolors=cm.plasma_r(T))
    ax.set_xlim(-1, 1)
    ax.set_ylim(-1, 1)
    ax.set_zlim(-1, 1)
    title(r'$\omega$=' + str(omega))
    show()
Example #4
0
File: coda.py Project: zisserj/coda
    def plot_hmm(self, comparison=True, val_column='pred', fname=False):
        self._log(
            0,
            f'plot_hmm(comparison={comparison}, val_column="{val_column}", fname="{fname}")'
        )

        COLORS = ["magenta", "turquoise", "lightgreen", "cyan"]
        names = pd.unique(self._data.chrm)
        seq_count = len(names)
        max_x = self._data.end.max()
        y_lim = self._data.val.max()

        if comparison:  # Two columns view
            fig = plt.figure(dpi=100, figsize=(15, 2 * seq_count + 2))
        else:
            fig = plt.figure(dpi=100, figsize=(15, 4 * seq_count + 2))

        title = "{} (cov = {})\ndatapoints per bin  = {}, smoothing interval = {}".format(
            self._sample_name, self._avg_cov, self._group_count,
            self._smooth_window)
        fig.suptitle(title, fontsize=16)

        for n, chrm in enumerate(names):
            cur_seq = self._data_predictions[self._data_predictions.chrm ==
                                             chrm]
            # Plot input values
            if comparison:
                col = n // (seq_count / 2)
                ax1 = plt.subplot(seq_count, 2,
                                  1 + ((n % (seq_count / 2)) * 4) + col)
            else:
                ax1 = plt.subplot(seq_count * 2, 1, (n + 1) * 2 - 1)
            ax1.set_ylabel('Read count')

            ax1.scatter(cur_seq.start,
                        cur_seq.val,
                        color=cm.plasma_r((cur_seq.val * 240).astype(int)),
                        linestyle='--')
            ax1.set_xlim((-max_x / 40, max_x + max_x / 40))
            ax1.set_ylim((-y_lim / 8, y_lim + y_lim / 8))

            if len(names) > 0:
                ax1.set_title(names[n])

            # Filter predictions to each state
            masks = [
                cur_seq[val_column] == i
                for i in np.arange(self.HMM.n_components)
            ]

            if comparison:
                ax2 = plt.subplot(seq_count, 2,
                                  3 + ((n % (seq_count / 2)) * 4) + col)
            else:
                ax2 = plt.subplot(seq_count * 2, 1, (n + 1) * 2)

            for i, mask in enumerate(masks):
                ax2.fill_between(cur_seq.start,
                                 i + 0.1,
                                 y2=0,
                                 where=mask,
                                 color=COLORS[i])
                # if len(self.scores) > 0:
                #     ax2.set_title("Score = {}".format(self.scores[n]))
                ax2.set_xlim((-max_x / 40, max_x + max_x / 40))
                ax2.set_ylim((-0.2, len(masks) - 0.8))
            ax2.set_ylabel('Prediction')
            ax2.set_yticks([0, 1, 2])
            ax2.set_yticklabels([0, 1, 2])

            # Plot centromere
            if self._flags['cent_data']:
                cent = self._context_table.loc[(n % (seq_count // 2)) + 1]
                ax1.axvspan(cent.start,
                            cent.end,
                            facecolor='blue',
                            alpha=0.2,
                            linewidth=0)
                ax2.axvspan(cent.start,
                            cent.end,
                            facecolor='blue',
                            alpha=0.2,
                            linewidth=0)

            ax1.xaxis.set_major_formatter(ticker.EngFormatter())
            ax2.xaxis.set_major_formatter(ticker.EngFormatter())
        # plt.figlegend()
        plt.tight_layout(rect=[0, 0.02, 1,
                               0.96])  # Rect to account for figure title

        if not fname:
            plt.show()
        else:
            plt.savefig(fname)
Example #5
0
    reload  # Python 2.7
except NameError:
    try:
        from importlib import reload  # Python 3.4+
    except ImportError:
        from imp import reload  # Python

pff = reload(pff)
KAD = reload(KAD)
noise = reload(noise)
decays = reload(decays)
solvers = reload(solvers)
ACactions = reload(ACactions)
Class_deque = reload(Class_deque)

colors = iter(cm.plasma_r(np.arange(600)))

plt.figure("Evolution de Loss sur un episodes vs iteration STEP = 100")
plt.pause(0.01)


#----------------------------------------------
def samples_memories(BATCH_SIZE):
    indices = np.random.permutation(deque_obj.size())[:BATCH_SIZE]
    # cols[0] : state
    # cols[1] : action
    # cols[2] : reward
    # cols[3] : next_state
    # cols[4] : done
    cols = [[], [], [], [], []]
Example #6
0
state_size = 50
action_size = 50
BATCH_SIZE = 64
TAU = 0.001
lr_actor = 0.001
lr_critics = 0.0001
gamma = 0.96

trainnum = 0

noiselevel = 0.5

episodes = 5000  # Nombre d'episodes
train_times = 1000  # Nombre d'iterations

colors = iter(cm.plasma_r(np.arange(train_times)))

HIDDEN1_UNITS = 40
HIDDEN2_UNITS = 20

training_start = 100

buffer_size = 50 * 400

actor = KAD.ActorNetwork(sess, state_size, action_size, BATCH_SIZE, TAU,
                         lr_actor, HIDDEN1_UNITS, HIDDEN2_UNITS)
critics = KAD.CriticNetwork(sess, state_size, action_size, BATCH_SIZE, TAU,
                            lr_critics, HIDDEN1_UNITS, HIDDEN2_UNITS)

X = np.linspace(0, np.pi / 2., 50)
# -------------------
# We can now loop through the frequencies of interest and compute the wavenumbers for the slit
wavenumber_slit = []
frequencies = range(100, 2000, 50)
m, n = 0, 0

for f in frequencies:
    wavenumber_slit.append(slit_duct.get_wavenumber(m, n, f))
# %%
# 4. Plot
# ----
# We want to compare the wavenumbers of the slit to the wavenumbers of a rectangular duct with different ratios of
# slit length and slit width and plot the results
ratio_values = [1, 3, 5, 10, 20]
plt.figure()
colors = cm.plasma_r(numpy.linspace(0, 1, len(ratio_values) + 1))

for rIndx, ratio in enumerate(ratio_values):
    rect_duct = acdecom.WaveGuide(cross_section="rectangular",
                                  dimensions=(slit_width, slit_width * ratio),
                                  damping="stinson")
    wavenumber_rect = []
    for f in frequencies:
        wavenumber_rect.append(rect_duct.get_wavenumber(m, n, f))

    plt.plot(frequencies,
             numpy.imag(wavenumber_rect),
             color=colors[rIndx],
             ls="--",
             label="Rect. b/a = " + str(ratio))
Example #8
0
#########################################################################################################
df_concat_nuba = pd.concat((df_348_nuba, df_350_nuba, df_975_nuba))
df_nuba_Prom = df_concat_nuba.groupby(df_concat_nuba.index).mean()

df_concat_Anomal = pd.concat((Anomal_df_348, Anomal_df_350, Anomal_df_975))
df_Anomal_Prom = df_concat_Anomal.groupby(df_concat_Anomal.index).mean()
df_Total =  pd.concat([df_Anomal_Prom, df_nuba_Prom, df_Fractal], axis=1)

x_month = np.arange(1, 13)

##--------------------------------GRAFICA  DIM FRACTAL MENSUAL------------------------------##
#Month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Month = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']

df_Fractal_Month_MintoMax = df_Fractal_Month.sort_values('Dim_Fractal', axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
colors = cm.plasma_r(np.linspace(0, 1, len(df_Fractal_Month)))
df_colors = pd.DataFrame(np.nan, columns =["Color"], index =np.arange(12))
df_colors = df_colors.astype(object)
for i in range(len(colors)):
    df_colors.at[i, 'Color'] = colors[i].tolist()
df_colors['Dim_Fractal'] = df_Fractal_Month_MintoMax['Dim_Fractal'].values
df_colors.index = df_Fractal_Month_MintoMax.index
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

plt.close('all')
fig = plt.figure(figsize=(30,10))
for i in range(1, 13):
    ax = fig.add_subplot(2, 6, i)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.scatter(df_Total['Anomalia'][df_Total.index.month ==i].values, df_Total['Radiacias'][df_Total.index.month ==i].values, s=80, c= df_colors['Color'][i],  alpha=0.5, marker = ".")