Esempio n. 1
0
def scatter_plot(P, L, pcIdx1, pcIdx2, letterList, rev):
    fig = plt.figure()
    # following the convention in lecture note ScatterPlot.html
    colors = ["r", "lime", "b", "y", "c", "m", "k", "tan", "pink", "darkred"]
    for i, letter in enumerate(letterList):
        plt.scatter(P[L == letter, pcIdx2],
                    P[L == letter, pcIdx1],
                    s=0.1,
                    c=colors[i],
                    label=letter)
    plt.axes().set_aspect('equal')
    #plt.axes().set_aspect('equal', 'datalim')
    plt.xlabel("Principle Component {}".format(pcIdx2))
    plt.ylabel("Principle Component {}".format(pcIdx1))
    plt.axhline(0, color='grey')
    plt.axvline(0, color='grey')
    plt.ylim([-5000, 5000])
    plt.xlim([-5000, 5000])
    plt.legend()
    plt.gca().invert_yaxis()
    fig.set_size_inches(8, 8)
    fName = os.path.join(
        pDir, 'scatter_PC{}_PC{}_{}_{}.png'.format(pcIdx1, pcIdx2,
                                                   "".join(letterList), rev))
    savefig(fName, bbox_inches='tight')
    plt.show()
 def showModeless(self):
     fig = figure(1)
     ax = axes([0.025, 0.5-len(self.checkStates)*.05*.5, 0.14, len(self.checkStates)*.05])
     self.yBtns = CheckButtons(ax, self.names, [self.checkStates[name] for name in self.names])
     self.yBtns.on_clicked(self.onItemselected)
     axes([0.2, 0.1, 0.75, 0.85])
     self.plot()
     
     manager = get_current_fig_manager()
     self.loadSetting(manager.window)
     self.registerCallbacks(fig, manager.window)
Esempio n. 3
0
def Plot_Circle(c_list):
    plt.figure()
    plt.axes().set_aspect('equal')
    plt.xlim([-1, 1])
    plt.ylim([-1, 1])
    theta = np.linspace(0, 2 * np.pi, 90)
    for c in c_list:
        x = c.x
        y = c.y
        r = c.radius
        plt.plot(x + r * np.cos(theta), y + r * np.sin(theta), 'r')
    plt.show()
    def showModeless(self):
        fig = figure(1)
        ax = axes([
            0.025, 0.5 - len(self.checkStates) * .05 * .5, 0.14,
            len(self.checkStates) * .05
        ])
        self.yBtns = CheckButtons(
            ax, self.names, [self.checkStates[name] for name in self.names])
        self.yBtns.on_clicked(self.onItemselected)
        axes([0.2, 0.1, 0.75, 0.85])
        self.plot()

        manager = get_current_fig_manager()
        self.loadSetting(manager.window)
        self.registerCallbacks(fig, manager.window)
def feature_PCA():
    my_arrays = load_data(0, get_avg=True)
    for i in range(1, 89):
        my_arrays = np.concatenate((my_arrays, load_data(i, get_avg=True)),
                                   axis=0)
    my_tensor = torch.from_numpy(my_arrays)
    my_labels = np.loadtxt('hist/rotation.txt')
    color_choice = ['b', 'g', 'r', 'yellow']
    pca = PCA(n_components=3)
    x_numpy = my_tensor.data.cpu().numpy()
    x_pca = pca.fit_transform(x_numpy)

    plt.figure()
    ax = plt.axes(projection='3d')
    for i in range(x_pca.shape[0]):
        color_index = int(my_labels[i])
        # plt.plot(x_pca[i, 0], x_pca[i, 1], 'o', color=color_choice[color_index])
        ax.scatter(x_pca[i, 0],
                   x_pca[i, 1],
                   x_pca[i, 2],
                   color=color_choice[color_index])
        # plt.text(X_norm[i, 0], X_norm[i, 1], str(y[i]), color=plt.cm.Set1(y[i]),
        #          fontdict={'weight': 'bold', 'size': 9})
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    plt.show()
Esempio n. 6
0
 def __save(self,n,plot,sfile):
     p.figure(figsize=sfile)
     p.xlabel(plot.xlabel)
     p.ylabel(plot.ylabel)
     p.xscale(plot.xscale)
     p.yscale(plot.yscale)
     p.grid()
     for curve in plot.curves: 
         if curve[1] == None: p.plot(curve[0],curve[2], label=curve[3])
         else: p.plot(curve[0],  curve[1], curve[2], label=curve[3])
     p.rc('legend', fontsize='small')
     p.legend(shadow=0, loc='best')
     p.axes().set_aspect(plot.aspect)
     if not plot.dir: plot.dir = './plots/'
     if not plot.name: plot.name = self.__global_name+'_%0*i'%(2,n)
     if not os.path.isdir(plot.dir): os.mkdir(plot.dir)
     if plot.pgf: p.savefig(plot.dir+plot.name+'.pgf')
     else: p.savefig(plot.dir+plot.name+'.pdf', bbox_inches='tight')
     p.close()
    def __init__(self):
        QWidget.__init__(self)
        self.fig = plt.figure()
        self.canvas = FigureCanvas(self.fig)
        self.ax = plt.axes(projection='3d')

        self.affichageCourbe('Maillage\Rectangular_HULL_Normals_Outward.stl')
        self.canvas.draw()

        layout = QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)
def dimension_reduction(method, dimension):
    my_arrays = load_data(0, get_avg=True)
    for i in range(1, 89):
        my_arrays = np.concatenate((my_arrays, load_data(i, get_avg=True)),
                                   axis=0)
    # print(my_arrays.shape)
    my_tensor = torch.from_numpy(my_arrays)
    my_labels = np.loadtxt('hist/rotation.txt')
    print(my_labels.shape)
    # time.sleep(30)
    color_choice = ['b', 'g', 'r', 'yellow']
    # print(my_tensor)
    if method == 'tsne':
        module = manifold.TSNE(n_components=dimension,
                               init='random',
                               random_state=500,
                               early_exaggeration=5,
                               method='exact')
    elif method == 'PCA':
        module = PCA(n_components=3)
    x_numpy = my_tensor.data.cpu().numpy()
    x_reduced = module.fit_transform(x_numpy)
    print(x_reduced.shape)
    print(x_reduced)
    plt.figure()
    if dimension == 2:
        for i in range(x_reduced.shape[0]):
            color_index = int(my_labels[i])
            plt.plot(x_reduced[i, 0],
                     x_reduced[i, 1],
                     'o',
                     color=color_choice[color_index])
        plt.xticks()
        plt.yticks()

    elif dimension == 3:
        ax = plt.axes(projection='3d')
        for i in range(x_reduced.shape[0]):
            color_index = int(my_labels[i])
            ax.scatter(x_reduced[i, 0],
                       x_reduced[i, 1],
                       x_reduced[i, 2],
                       color=color_choice[color_index])
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

    plt.savefig('plots/{}-24bin-{}d.pdf'.format(method, dimension))
    plt.show()
def feature_visualization(method, dimension):
    color_choice = ['b', 'g', 'r', 'yellow']
    x_numpy = np.loadtxt('experiments/features.txt')
    my_labels = np.loadtxt('experiments/features_labels.txt')
    print(x_numpy.shape)
    time.sleep(30)
    if method == 'tsne':
        module = manifold.TSNE(n_components=dimension,
                               init='pca',
                               random_state=500,
                               early_exaggeration=20,
                               method='exact')
    elif method == 'PCA':
        module = PCA(n_components=3)
    x_reduced = module.fit_transform(x_numpy)
    print(x_reduced.shape)
    print(x_reduced)
    plt.figure()
    if dimension == 2:
        for i in range(x_reduced.shape[0]):
            color_index = int(my_labels[i])
            if my_labels[i] == 0:
                status = 'Died'
            else:
                status = 'Survived'
            plt.plot(x_reduced[i, 0],
                     x_reduced[i, 1],
                     'o',
                     color=color_choice[color_index],
                     label=status)
        plt.xticks()
        plt.yticks()

    elif dimension == 3:
        ax = plt.axes(projection='3d')
        for i in range(x_reduced.shape[0]):
            color_index = int(my_labels[i])
            ax.scatter(x_reduced[i, 0],
                       x_reduced[i, 1],
                       x_reduced[i, 2],
                       color=color_choice[color_index])
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

    plt.legend(loc="lower right")
    plt.savefig('experiments/{}_{}.pdf'.format(method, dimension))
    plt.show()
Esempio n. 10
0
def plot_cov(qstack):
    fig = plt.figure()
    ax = plt.axes(None, label=str(qstack.bin_size))
    flux_corr = np.corrcoef(qstack.fs_boot, rowvar=False)
    flux_covar = qstack.flux_covar
    im = ax.pcolormesh(qstack.wave_grid,
                       qstack.wave_grid,
                       flux_corr,
                       vmin=-1,
                       vmax=1)
    plt.ylim(qstack.wave_grid[-1], qstack.wave_grid[0])
    cbar = fig.colorbar(im, ax=ax)
    cbar.set_label('Correlation')
    #plt.title("Continuum Normalized Flux Covariance Matrix Across Wavelength Bins")
    plt.xlabel("Wavelength Bin (Angstroms)")
    plt.ylabel("Wavelength Bin (Angstroms)")
Esempio n. 11
0
def plot_std(qstack):
    plt.figure()
    flux_covar = qstack.flux_covar

    std = np.sqrt(np.diagonal(flux_covar))
    ax = plt.axes(None, label=str(bin_size))
    plt.plot(qstack.wave_stack, qstack.flux_stack, label='Stacked Flux')
    ax.fill_between(qstack.wave_stack,
                    qstack.flux_stack - std,
                    qstack.flux_stack + std,
                    alpha=0.25,
                    label="1-$\\sigma$ Uncertainty Range")
    #plt.title("Stacked Continuum Normalized Flux Near Ly-$\\alpha$ Transition")
    plt.xlabel("Wavelength (Angstroms)")
    plt.ylabel("Stacked Continuum Normalized Flux")
    plt.axvline(x=1215.67, color='red', linestyle='--')
    plt.legend()
Esempio n. 12
0
def glm_scatter(x,
                y,
                pdf_path=None,
                title=None,
                x_label='x',
                y_label='y',
                formula='y ~ x',
                show_sum=False):
    """Creates a scatter plot with a GLM model running through the data

    :param x:
    :param y:
    :param pdf_name:
    :param title:
    :param x_label:
    :param y_label:
    :param formula:
    :param show_sum:
    :return:
    """
    # Make the plotting grid
    a = plt.axes(title=title)
    a.set_xlabel(x_label)
    a.set_ylabel(y_label)

    # Prepare data and model
    scatter_df = pd.DataFrame({'x': x, 'y': y}).sort_values('x')
    mod = smf.ols(formula=formula, data=scatter_df).fit()
    scatter_df['pred'] = mod.predict(scatter_df['x'])
    scatter_df.plot('x', 'y', kind='scatter', ax=a)
    scatter_df.plot('x', 'pred', ax=a, color='r')

    # Show plot
    plt.show()

    if pdf_path:
        pdf_path = add_filetype(pdf_path, '.pdf')
        with PdfPages(pdf_path) as pdf:
            plt.savefig(pdf, format='pdf')

    plt.close('all')
    if show_sum:
        print(mod.summary())
    breaks()
Esempio n. 13
0
def plot_boot(qstack):
    plt.figure()
    flux_covar = qstack.flux_covar

    std = np.sqrt(np.diagonal(flux_covar))
    ax = plt.axes(None, label=str(bin_size))

    num = 100
    ws_boot = qstack.ws_boot[:100]
    fs_boot = qstack.fs_boot[:100]

    plt.plot(ws_boot.T, fs_boot.T, alpha=0.1, color='orange')
    plt.plot(ws_boot[0],
             fs_boot[0],
             alpha=0.1,
             color='orange',
             label='Bootstrap Samples')
    plt.plot(qstack.wave_stack, qstack.flux_stack, label='Stacked Flux')
    #plt.title("Stacked Continuum Normalized Flux Near Ly-$\\alpha$ Transition")
    plt.xlabel("Wavelength (Angstroms)")
    plt.ylabel("Stacked Continuum Normalized Flux")
    plt.axvline(x=1215.67, color='red', linestyle='--')
    plt.legend()
    fluo_paths = []
    for i in xrange(len(paths)):
        emissions = [v_inf_mean[t] for t in paths[i]]
        f_cp = np.convolve(kernel[::-1], emissions, mode='full')
        f_cp = f_cp[w:-w + 1]
        fluo_paths.append(f_cp)

    #plt.plot(np.array(fluo_paths[-1]))
    #plt.plot(fluo_states[0])
    #plt.show()

    #--------------------------------------Generate Animation--------------------------------------------------------------#
    # First set up the figure, the axis, and the plot element we want to animate
    fig = plt.figure()
    ax = plt.axes(xlim=(0, len(fluo_states[0])),
                  ylim=(0, np.max(fluo_states[0])))
    ax.plot(range(len(fluo_states[0])), fluo_states[0])
    line, = ax.plot([], [], lw=4)

    # initialization function: plot the background of each frame
    def init():
        line.set_data([], [])
        return line,

    # animation function.  This is called sequentially
    def animate(i):
        y = np.array(fluo_paths[i])
        x = np.arange(0, len(y))
        line.set_data(x, y)
        return line,
Esempio n. 15
0
s = Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
s.plot()
plt.save('Figure_14.png')
df
df = DataFrame(np.random.randn(10,4).cumsum(0),
               columns=['A','B','C','D'],
               index=np.arange(0,100,10))
               
df.plot
df = DataFrame(np.random.randn(10,4).cumsum(0),
               columns=['A','B','C','D'],
               index=np.arange(0,100,10))
               
df.plot()
plt.axes
plt.axes()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2,1)
data = Series(np.random.randn(16),index=list('abcdefghijklmnop'))
data.plot(kind='bar', ax=axes[0],color='k', alpha=0.7)
data = Series(np.random.rand(16),index=list('abcdefghijklmnop'))
data.plot(kind='bar', ax=axes[0],color='k', alpha=0.7)
fig, axes = plt.subplots(2,1)
data = Series(np.random.rand(16),index=list('abcdefghijklmnop'))
data.plot(kind='bar', ax=axes[0],color='k', alpha=0.7)
data.plot(kind='barh', ax=axes[1],color='k', alpha=0.7)
fig.savefig('Figure_16.png')
df = DataFrame(np.random.rand(6,4),)
df = DataFrame(np.random.rand(6,4),
               index=['r1','r2','r4','r5','r6'],
               columns=pd.Index(['A','B','C','D'],name='Genus'))
Esempio n. 16
0
chetty.e_rank_b.plot.hist()

# In[22]:

chetty.shape

# In[23]:

low_100 = chetty.sort_values(by="e_rank_b").head(100)
high_100 = chetty.sort_values(by="e_rank_b", ascending=False).head(100)

# In[25]:

imagery = img_tiles.GoogleTiles()

ax = mpl.axes(projection=imagery.crs)

#x0, x1, y0, y1
maps_limits = (-71.38, -70.77, 42.03, 42.47)
ax.set_extent(maps_limits)

ax.add_image(imagery, 10)

mpl.plot(low_100.LON,
         low_100.LAT,
         transform=ccrs.Geodetic(),
         marker='.',
         markersize=10,
         color="red",
         linewidth=0,
         alpha=0.5)
Esempio n. 17
0
plot(x, Psi0.conj().imag, 'y--', label=r"${\Psi_{0}}_{imag}$")
legend()
plt.show()

# In[3]:

from matplotlib import pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

# initializing a figure in
# which the graph will be plotted
fig = plt.figure()

# marking the x-axis and y-axis
axis = plt.axes(xlim=(-50, 50), ylim=(-0.5, 1))
plt.plot(x, v(x) * 0.1)
# initializing a line variable
line = axis.plot(x, p[0].real**2 + p[0].imag**2, lw=2)[0]


# data which the line will
# contain (x, y)
def init():
    line.set_data([], [])
    return line


def animate(i):
    # plots a sine graph
    line.set_ydata(p[i].real**2 + p[i].imag**2)
Esempio n. 18
0
# In[33]:

plotter.plot({'Basic': history}, metric="mae")
plt.ylabel('MAE [Deaths]')

# In[34]:

plotter.plot({'Basic': history}, metric="mse")
plt.ylabel('MSE [Deaths^2]')

# In[35]:

test_predictions = model.predict(normed_test_data).flatten()

a = plt.axes(aspect='equal')
plt.scatter(test_labels, test_predictions)
plt.xlabel('True Values [Deaths]')
plt.ylabel('Predictions [Deaths]')

# In[36]:

error = test_predictions - test_labels
plt.hist(error, bins=25)
plt.xlabel("Prediction Error [Deaths]")
_ = plt.ylabel("Count")

# In[37]:

import plotly
import plotly.figure_factory as ff
def feature_visualization_remake(vectors, labels, method, dimension, figname):
    class_num = int(np.max(labels) + 1)
    print('there are {} classes'.format(class_num))
    # time.sleep(30)
    color_choice = ['g', 'r', 'b', 'yellow']
    x_numpy = vectors
    my_labels = labels
    print('my_labels {}'.format(my_labels))

    my_labels = np.reshape(my_labels, (my_labels.shape[0], 1))
    mydata = np.concatenate((my_labels, x_numpy), axis=1)
    np.random.shuffle(mydata)
    x_numpy = mydata[:, 1:]
    my_labels = mydata[:, 0]

    print('Size of vectors {}'.format(x_numpy.shape))
    print('Size of labels {}'.format(my_labels.shape))

    if method == 'tsne':
        module = manifold.TSNE(n_components=dimension,
                               init='random',
                               random_state=10,
                               early_exaggeration=20,
                               method='barnes_hut')
    elif method == 'pca':
        module = PCA(n_components=100)
    x_reduced = module.fit_transform(x_numpy)

    plt.figure()
    plt.xticks([])
    plt.yticks([])
    plt.legend(loc="upper right")
    plt.tight_layout()

    if dimension == 2:
        for class_index in range(0, class_num):
            this_index = np.where(my_labels == class_index)
            class_vectors = x_reduced[this_index]
            plt.plot(class_vectors[:, 0],
                     class_vectors[:, 1],
                     'o',
                     color=color_choice[class_index],
                     alpha=0.5,
                     label='Class {}'.format(class_index))
            if class_index == 1:
                plt.legend(loc="upper right")
                plt.savefig('experiments/{}_{}_{}_2.png'.format(
                    method, dimension, figname))

    elif dimension == 3:
        ax = plt.axes(projection='3d')
        for class_index in range(0, class_num):
            this_index = np.where(my_labels == class_index)
            class_vectors = x_reduced[this_index]
            ax.scatter(class_vectors[:, 0],
                       class_vectors[:, 1],
                       class_vectors[:, 2],
                       color=color_choice[class_index],
                       label='Class {}'.format(class_index))

        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

    # plt.title('t-SNE Visualization of Patch-34 Feature Vectors')
    # plt.legend(loc="upper right")
    # plt.savefig('experiments/{}_{}_{}.pdf'.format(method, dimension))
    plt.savefig('experiments/{}_{}_{}_3.png'.format(method, dimension,
                                                    figname))
def feature_visualization2(method, dimension, point_num=1700):
    color_choice = ['b', 'g', 'r', 'yellow']
    x_numpy = np.loadtxt('data/gt_vectors.txt')
    my_labels = np.loadtxt('data/gt_labels.txt')
    print('my_labels {}'.format(my_labels))

    my_labels = np.reshape(my_labels, (my_labels.shape[0], 1))
    mydata = np.concatenate((my_labels, x_numpy), axis=1)
    np.random.shuffle(mydata)
    x_numpy = mydata[:, 1:]
    my_labels = mydata[:, 0]
    x_numpy = x_numpy[:point_num, :]
    my_labels = my_labels[:point_num]

    print('Size of vectors {}'.format(x_numpy.shape))
    print('Size of labels {}'.format(my_labels.shape))
    # print('labels {}'.format(my_labels))
    died_index = np.where(my_labels == 0)
    survived_index = np.where(my_labels == 1)
    if method == 'tsne':
        module = manifold.TSNE(n_components=dimension,
                               init='pca',
                               random_state=10,
                               early_exaggeration=20,
                               method='barnes_hut')
    elif method == 'pca':
        module = PCA(n_components=100)
    x_reduced = module.fit_transform(x_numpy)
    died_vector = x_reduced[died_index]
    survived_vector = x_reduced[survived_index]
    plt.figure()
    if dimension == 2:
        plt.plot(died_vector[:, 0],
                 died_vector[:, 1],
                 'o',
                 color='tomato',
                 alpha=0.5,
                 label='Deceased')
        plt.plot(survived_vector[:, 0],
                 survived_vector[:, 1],
                 'o',
                 color='limegreen',
                 alpha=0.5,
                 label='Survived')
        # plt.plot(x_reduced[i, 0], x_reduced[i, 1], 'o', color=color_choice[color_index])
        plt.xticks([])
        plt.yticks([])

    elif dimension == 3:
        ax = plt.axes(projection='3d')
        ax.scatter(died_vector[:, 0],
                   died_vector[:, 1],
                   died_vector[:, 2],
                   color='r',
                   label='Died')
        ax.scatter(survived_vector[:, 0],
                   survived_vector[:, 1],
                   survived_vector[:, 2],
                   color='g',
                   label='Survived')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

    # plt.title('t-SNE Visualization of Patch-34 Feature Vectors')
    plt.legend(loc="upper right")
    plt.tight_layout()
    plt.savefig('experiments/{}_{}.pdf'.format(method, dimension))
    plt.savefig('experiments/{}_{}.png'.format(method, dimension))
    plt.show()
Esempio n. 21
0
                           n_redundant=0,
                           random_state=42)

train_X, test_X, train_y, test_y = train_test_split(X, y, random_state=42)

model = LogisticRegression(random_state=42)

model.fit(train_X, train_y)

pred_y = model.predict(test_X)
print(np.where(pred_y == 1, True, False))
print(np.where(pred_y == 1))

# In[162]:

XI = np.linspace(-10, 10)  #-10~10사이에 난수 생성, 이 때 간격은 거의 동일하다.
Y = -model.coef_[0][0] / model.coef_[0][
    1] * XI - model.intercept_ / model.coef_[0][1]
plt.plot(XI, Y)
plt.xlim(min(X[:, 0]) - 0.5, max(X[:, 0]) + 0.5)
plt.ylim(min(X[:, 1]) - 0.5, max(X[:, 1]) + 0.5)

plt.axes().set_aspect('equal', 'datalim')

# In[171]:

model.coef_[0, 0]
model.intercept_

# In[ ]:
def feature_visualization3(method, dimension, fold):
    color_choice = ['b', 'g', 'r', 'yellow']
    x_numpy = np.loadtxt('experiments/features.txt')
    x_numpy = x_numpy[54 * fold:54 * (fold + 1)]
    my_labels = np.loadtxt('experiments/features_labels.txt')
    my_labels = my_labels[54 * fold:54 * (fold + 1)]
    print('Size of labels {}'.format(my_labels.shape))
    # print('labels {}'.format(my_labels))
    died_index = np.where(my_labels == 0)
    survived_index = np.where(my_labels == 1)
    if method == 'tsne':
        module = manifold.TSNE(n_components=dimension,
                               init='pca',
                               random_state=100,
                               early_exaggeration=2000,
                               method='exact')
    elif method == 'PCA':
        module = PCA(n_components=10)
    x_reduced = module.fit_transform(x_numpy)
    died_vector = x_reduced[died_index]
    survived_vector = x_reduced[survived_index]
    print(x_reduced)
    # plt.subplot(2, 5, i+1, figsize=(15, 15))
    plt.figure(figsize=(5, 5))
    if dimension == 2:
        plt.plot(died_vector[:, 0],
                 died_vector[:, 1],
                 'o',
                 color='r',
                 alpha=0.5,
                 label='Deceased')
        plt.plot(survived_vector[:, 0],
                 survived_vector[:, 1],
                 'o',
                 color='g',
                 alpha=0.5,
                 label='Survived')
        # axs[i//5, i%5].plot(died_vector[:, 0], died_vector[:, 1], 'o', color='r', alpha=0.5, label='Died')
        # axs[i//5, i%5].plot(survived_vector[:, 0], survived_vector[:, 1], 'o', color='g', alpha=0.5, label='Survived')
        # axs[i // 5, i % 5].axis('off')
        # axs[i // 5, i % 5].set_xticks([])
        # axs[i // 5, i % 5].set_yticks([])
        # plt.plot(x_reduced[i, 0], x_reduced[i, 1], 'o', color=color_choice[color_index])
        plt.xticks([])
        plt.yticks([])

    elif dimension == 3:
        ax = plt.axes(projection='3d')
        ax.scatter(died_vector[:, 0],
                   died_vector[:, 1],
                   died_vector[:, 2],
                   color='r',
                   label='Died')
        ax.scatter(survived_vector[:, 0],
                   survived_vector[:, 1],
                   survived_vector[:, 2],
                   color='g',
                   label='Survived')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

    # plt.title('t-SNE Visualization of Patch-34 Feature Vectors')
    plt.legend(loc="lower right")
    plt.savefig('experiments/tsne/{}_{}_{}.pdf'.format(method, dimension,
                                                       fold))
    plt.savefig('experiments/tsne/{}_{}_{}.jpg'.format(method, dimension,
                                                       fold))
    plt.show()
plt.figure(figsize=(8, 6))
plt.pie(values,
        labels=pollutants,
        explode=explode,
        autopct='%1.1f%%',
        shadow=True)

plt.title('Air pollutants and their probable amount in atmosphere [India]')

plt.axis('equal')
plt.show()

# # showing INDIA AQI on world map using cartopy

# In[82]:

import cartopy.crs as ccrs

# In[83]:

geo = data['city']['geo']

fig = plt.figure(figsize=(12, 10))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()

plt.scatter(geo[1], geo[0], color='blue')
plt.text(geo[1] + 3, geo[0] - 2, f'{name} AQI \n    {aqi}', color='red')

plt.show()
Esempio n. 24
0
velocities = np.array(list(zip(np.sin(angles), np.cos(angles))))


def apply_boundary_conditions(self):
    """apply boundary conditions"""
    edge_buffer_radius = 2.0
    for position in self.positions:
        x = position[0]
        y = position[1]

        if x > width + edge_buffer_radius:
            x = -edge_buffer_radius
        elif x < -edge_buffer_radius:
            x = width + edge_buffer_radius

        if y > height + edge_buffer_radius:
            y = -edge_buffer_radius
        elif y < -edge_buffer_radius:
            y = height + edge_buffer_radius

        position[0] = x
        position[1] = y


figure = plt.figure()
axes = plt.axes(xlim=(0, width), ylim=(0, height))

bird_bodies, = axes.plot([], [], markersize=10, c='k', marker='o', ls='None')

#TODO Pick up here from page 76, code line 2 beak == bird_beak
    skeleton = np.array(skeleton) - 1

    for i in skeleton:
        if pose_3d[i[0]][2] != 0 and pose_3d[i[1]][2]:
            x = np.array([pose_3d[i[0]][0], pose_3d[i[1]][0]])
            y = np.array([pose_3d[i[0]][1], pose_3d[i[1]][1]])
            z = np.array([pose_3d[i[0]][2], pose_3d[i[1]][2]])
            ax.plot3D(x, y, z, 'red')

def add_point(pose_3d, ax):
    x, y, z = pose_3d[:, 0], pose_3d[:, 1], pose_3d[:, 2]
    ax.scatter3D(x, y, z, cmap='Greens')

import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
plt.ion()
i = 0
for pose_3d in pose_3d_all:

    add_line(pose_3d, ax)

    add_point(pose_3d, ax)

    square_x = np.array([-2000, 1000])
    square_y = np.array([-1000, 2000])
    square_z = np.array([500, 3500])
    ax.scatter3D(square_x, square_y, square_z, color='whitesmoke')

    plt.draw()
Esempio n. 26
0
    ax.set(aspect=1)
    #----------------- drawing box -------------------------------#
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    box_x = [xlim[0], xlim[1], xlim[1], xlim[0], xlim[0]]
    box_y = [ylim[0], ylim[0], ylim[1], ylim[1], ylim[0]]
    ax.add_patch(
        patches.Rectangle((box_x[0], box_y[0]),
                          xlim[1] - xlim[0],
                          ylim[1] - ylim[0],
                          fill=True,
                          facecolor='white',
                          clip_on=False,
                          zorder=0.8))
    ax.plot(box_x, box_y, color='blue', linewidth=5.0)
    plt.axes(ax)

    # 0 1
    # ax = plt.subplot()
    # dy = (inverse((1, 0)) - inverse((1, -0.1)))[1]
    #xy = transform((j+0.8, energydif[j]))
    # print(dy, xy)
    # ax = plt.axes([xy[0], xy[1]-(dy)/2.6, 0.170, 0.170])
    cell = atoms.get_cell()
    img = atoms.copy()
    plot_conf(ax, img, colorlenth, rot=True)
    ax.set_xlim([centreofmass[0] - 11.5, centreofmass[0] + 11.5])
    ax.set_ylim([centreofmass[1] - 10.5, centreofmass[1] + 11.0])
    ax.set_yticks([])
    ax.set_xticks([])
    ax.set(aspect=1)
Esempio n. 27
0
def plotFeatureArrays(featureVecs,
                      array_shape,
                      n_figs=10,
                      tiled=True,
                      tiles_shape=(2, 5),
                      tile_psn=(.1, .125, .4, .4),
                      xlims=None,
                      ylims=None,
                      titles=None,
                      xlabel=None,
                      ylabel=None,
                      noise_floor=None,
                      extent=None,
                      origin=None,
                      colorbar=True):

    n_samples = featureVecs.shape[0]

    if tiled:
        sample_idxs = np.array(random.sample(range(n_samples)),
                               np.prod(tiles_shape)).reshape(tiles_shape)

        plt.figure()

        for r in range(tiles_shape[0]):
            for c in range(tiles_shape[1]):
                idx = sample_idxs[r, c]
                arr = featureVecs[idx, :].reshape(array_shape)

                # set signal limits
                maxSig = arr.max()
                if noise_floor is not None:
                    minSig = magSig - noise_floor
                    arr[arr < minSig] = minSig
                minSig = arr.min()

                left = tile_psn[0] * (c + 1) + tile_psn[2] * c
                bottom = tile_psn[1] * (r + 1) + tile_psn[3] * r

                plt.axes((left, bottom, tile_psn[2], tile_psn[3]))

                plt.imshow(arr,
                           extent=extent,
                           aspect='auto',
                           interpolation='nearest',
                           origin=origin,
                           cmap='binary',
                           vmin=minSig,
                           vmax=maxSig)

                if colorbar:
                    plt.colorbar()

                if xlims is not None:
                    plt.xlim(xlims)

                if ylims is not None:
                    plt.ylim(ylims)

                if xlabel is not None and r == 0:
                    plt.xlabel(xlabel)
                else:
                    plt.xticks([])

                if ylabel is not None and c == 0:
                    plt.ylabel(ylabel)
                else:
                    plt.yticks([])

                if titles is not None:
                    plt.title(title[idx])

                plt.show()

    else:
        sample_idxs = np.array(random.sample(range(n_samples)), n_figs)

        for idx in sample_idxs:
            arr = featureVecs[idx, :].reshape(array_shape)

            # set signal limits
            maxSig = arr.max()
            if noise_floor is not None:
                minSig = magSig - noise_floor
                arr[arr < minSig] = minSig
            minSig = arr.min()

            plt.figure()
            plt.axes(tile_psn)

            plt.imshow(arr,
                       extent=extent,
                       aspect='auto',
                       interpolation='nearest',
                       origin=origin,
                       cmap='binary',
                       vmin=minSig,
                       vmax=maxSig)

            if colorbar:
                plt.colorbar()

            if xlims is not None:
                plt.xlim(xlims)

            if ylims is not None:
                plt.ylim(ylims)

            if xlabel is not None and r == 0:
                plt.xlabel(xlabel)
            else:
                plt.xticks([])

            if ylabel is not None and c == 0:
                plt.ylabel(ylabel)
            else:
                plt.yticks([])

            if titles is not None:
                plt.title(title[idx])

            plt.show()
ages = user_fields.map(lambda x: int(x[1])).collect()
hist(ages, bins=20, color='lightblue', normed=True)
fig = plt.pyplot.gcf()
fig.set_size_inches(16, 10)

count_by_occupation = user_fields.map(lambda fields: (fields[3], 1)).reduceByKey(lambda x, y: x + y).collect()
x_axis1 = np.array([c[0] for c in count_by_occupation])
y_axis1 = np.array([c[1] for c in count_by_occupation])

x_axis = x_axis1[np.argsort(y_axis1)]
y_axis = y_axis1[np.argsort(y_axis1)]

pos = np.arange(len(x_axis))
width = 1.0
ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(x_axis)
plt.bar(pos, y_axis, width, color='lightblue')
plt.xticks(rotation=30)
fig = plt.pyplot.gcf()
fig.set_size_inches(16, 10)

count_by_occupation2 = user_fields.map(lambda fields: fields[3]).countByValue()
print "Map-reduce approach:"
print dict(count_by_occupation2)
print ""
print "countByValue approach:"
print dict(count_by_occupation)

'''
Esempio n. 29
0
#Define v_jhat_t  - as v[1](y) multiplied by transformed vector jhat

v_jhat_t = v[1] * jhat_t

#TODO 3.:Define transformed vector v(v_t) as
#vector v_ihat_t added to vector v_jhat_t

v_t = None

#Plot that graphically shows vector v (color = 'skyblue') can be transformed
#into transformed vector v(v_trfm - color ='b') by adding v[0]*transformed
#vector ihat to v[0]*transformed vector jhat

#Creates axes of plot referenced 'ax'

ax = plt.axes()

#Plots red dot at origin (0,0)
ax.plot(0, 0, 'or')

#Plots vector v_ihat as dotted green arrow starting at origin 0,0
ax.arrow(0,
         0 * v_ihat,
         color='g',
         linestyle='dotted',
         linewidth=2.5,
         head_width=0.30,
         head_length=0.35)

#Plots vector v_jhat_t as dotted red arrow starting at origin defined by v_ihat
ax.arrow(v_ihat - t[0],
Esempio n. 30
0
    def create_surface(self):  #create initial surface to 'erode'
        veclength = self.length * self.width  #create vector with enough numbers to fill a length*width matrix
        mean, sd = 0, self.height  #height is standard deviation around mean height of zero
        heightlist = np.random.normal(
            mean, sd, veclength
        )  #samples the proper number of random heights, around a mean of 0, with sd defined by 'height'
        heightlist = np.around(
            heightlist,
            2)  #rounds the heights to the nearest two decimal places
        heightlist = heightlist.reshape(
            (self.width, self.length)
        )  #turns the heights into a matrix with the proper dimensions for length and width
        print(heightlist)
        xlist = []  #creates empty list to hold x values (correspond to width)
        ylist = []  #creates empty list to hold y values (correspond to length)
        zlist = []  #creates empty list to hold z values (correspond to height)
        for y in range(self.length):  #for each y value from 0 to the length...
            for x in range(
                    self.width):  #for each x value from 0 to the width...
                xlist.append(x)  #add that x value in to a list of x values
                ylist.append(y)  #add that y value to a list of y values
                z = heightlist[
                    x,
                    y]  #find the z value (already in the matrix) for that [x,y] pair
                print('Z: ', str(z))
                zlist.append(z)  #add that z value to the list of z values
        print('XLIST: ', xlist)
        print('LENXLST', str(len(xlist)))
        print('YLIST: ', ylist)
        print('LENYLIST: ', str(len(ylist)))
        print('ZLIST: ', zlist)
        print('LENZLIST: ', str(len(zlist)))

        #TODO turn length and width into meshgrid
        lengthlist, widthlist = np.arange(self.length), np.arange(
            self.width
        )  #create arrays containing all possible numbers in length and width values
        meshlength, meshwidth = np.meshgrid(
            lengthlist,
            widthlist)  #create meshgrid for those length and width arrays
        print('MESHLENGTH:')
        print(meshlength)
        print('MESHWIDTH:')
        print(meshwidth)

        #TODO select random points out of length, width and height
        num_sampled = math.floor(
            len(xlist) / 4
        )  #use around 1/4 of the points in the matrix as sample points for extrapolation
        sample_points = random.sample(
            range(len(xlist)), num_sampled
        )  #knowing the number of points to be sampled, chose the sample point indices
        print('SAMPLE POINTS: ', sample_points)
        xlist, ylist, zlist = np.asarray(xlist), np.asarray(ylist), np.asarray(
            zlist)  #turn the x,y, and z lists into np arrays
        xsamples, ysamples, zsamples = xlist[[sample_points]], ylist[[
            sample_points
        ]], zlist[[
            sample_points
        ]]  #choose the sample points from the arrays based on predetermined indices (same for each)
        print('XSAMPLES: ', xsamples)
        print('XYZsamples done')
        print('XSAMPLES TYPE: ', type(xsamples))
        print('YSAMPLES TYPE: ', type(ysamples))
        print('ZSAMPLES TYPE: ', type(zsamples))
        gridz0 = griddata(
            (xsamples, ysamples), zsamples,
            (meshwidth, meshlength
             ))  #apply griddata to extrapolate the rest of the height values
        print('GRIDZ0: ', gridz0)
        fig = plt.figure()
        ax = plt.axes(projection='3d')  #create 3D projection
        ax.plot_surface(
            meshwidth, meshlength, gridz0
        )  #plot it using meshwidth as X, meshlength as Y, and gridz0 as Z
        plt.show()
Esempio n. 31
0
def feature_visualization2(method, dimension):
    color_choice = ['b', 'g', 'r', 'yellow']

    x1 = np.load('./ChaData/feature1.npy')
    print(x1.shape)
    #    y1 = np.ones_like(x1)

    x2 = np.load('./MyData/feature1.npy')
    print(x2.shape)
    #    y2 = np.zeros_like(x2)

    #    x2 = x2[100:x2.shape[0]]
    x_numpy = np.zeros((x1.shape[0] + x2.shape[0], 4096))
    my_labels = np.zeros((x1.shape[0] + x2.shape[0]))

    x_numpy[0:x1.shape[0]] = x1
    x_numpy[x1.shape[0]:x1.shape[0] + x2.shape[0]] = x2

    my_labels[0:x1.shape[0]] = 1
    my_labels[x1.shape[0]:x1.shape[0] + x2.shape[0]] = 0
    #    x_numpy = np.load('./ChaData/feature.npy')
    #    my_labels = np.load('./ChaData/label.npy')
    print('Size of data {}'.format(x_numpy.shape))
    print('Size of labels {}'.format(my_labels.shape))
    died_index = np.where(my_labels == 0)
    survived_index = np.where(my_labels == 1)
    if method == 'tsne':
        module = manifold.TSNE(n_components=dimension,
                               init='pca',
                               random_state=100,
                               early_exaggeration=20,
                               method='exact')
    elif method == 'PCA':
        module = PCA(n_components=10)
    x_reduced = module.fit_transform(x_numpy)
    print(x_reduced)
    died_vector = x_reduced[died_index]
    survived_vector = x_reduced[survived_index]
    plt.figure()
    if dimension == 2:
        plt.plot(died_vector[:, 0],
                 died_vector[:, 1],
                 'ro',
                 label='Target Domain')  #alpha=0.4

        plt.plot(survived_vector[:, 0],
                 survived_vector[:, 1],
                 'b^',
                 label='Source Domain')  #, alpha=0.4
        # plt.plot(x_reduced[i, 0], x_reduced[i, 1], 'o', color=color_choice[color_index])
        plt.xticks()
        plt.yticks()

#        fig = plt.gcf()
#        dna1name='tsne'+'.png'
#        fig.savefig(dna1name,dpi=100)

    elif dimension == 3:
        ax = plt.axes(projection='3d')
        ax.scatter(died_vector[:, 0],
                   died_vector[:, 1],
                   died_vector[:, 2],
                   color='r',
                   label='Target Domain')
        ax.scatter(survived_vector[:, 0],
                   survived_vector[:, 1],
                   survived_vector[:, 2],
                   color='g',
                   label='Source Domain')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')


#    plt.title('t-SNE Visualization of Source And Target Domain Feature Vectors')
    plt.legend(loc="upper right")
    plt.savefig('tsne1.png', dpi=300)
    plt.show()

    return x_reduced
Esempio n. 32
0
    u_var = one_sig_upper - tqmed
    l_var = tqmed - one_sig_lower

    print("{0} stack, bin size = {1}, tq =".format(stack, bin_size), tqmed,
          '+', u_var, '-', l_var)

    #tqmed = 5.9

    cov_interp = interpol.interp1d(tqs, mod_covars, axis=0)

    #flux_covar = cov_interp(8.7)
    flux_covar = cov_interp(tqmed)

    fig = plt.figure()
    ax = plt.axes(None, label=str(k))
    corr = flux_covar / np.sqrt(
        np.outer(np.diag(flux_covar), np.diag(flux_covar)))
    im = ax.pcolormesh(qstack.wave_grid[:last_in + 1],
                       qstack.wave_grid[:last_in + 1], corr)
    plt.ylim(qstack.wave_grid[-2], qstack.wave_grid[0])
    cbar = fig.colorbar(im, ax=ax)
    cbar.set_label('Correlation')
    #plt.title("Continuum Normalized Flux Covariance Matrix Across Wavelength Bins")
    plt.xlabel("Wavelength Bin (Angstroms)")
    plt.ylabel("Wavelength Bin (Angstroms)")
    plt.savefig('model/corr_{1}_tq{0:.2f}.pdf'.format(tqmed, bin_size))

    plt.figure()
    std = np.sqrt(np.diagonal(flux_covar))
    mean_mod = model(waves, tqmed)
Esempio n. 33
0
Qs=abs((masses[2]-masses[1])/(masses[1]-masses[0]))
Qs_target=abs((drs[2]**order-drs[1]**order)/(drs[1]**order-drs[0]**order))
print 'Qs =',Qs,'Qs target =',Qs_target


# PLOT RESULTS ------------------------------------------------------------------

ls=['-.','--','-'] #line styles

#plot masses, pressures, density for best resolution run
r=arange(0.,drs[-1]*isurf/1e5,drs[-1]/1e5) # in km
rect=[0.1,0.1,0.8,0.8]

print r[-1], tovs[-1][isurf,3]/msun

a1=axes(rect)
a1.yaxis.tick_left()
plot(r,tovs[-1][:isurf,1]/pressc,'r',  # plot pressure
     r,tovs[-1][:isurf,0]/rhoc,'g')    #   and density
ylim([0,1.05])
xscale('log')
ylabel('Pressure (P_c), Density (rho_c)')
xlabel('Radius (km)')

a2=axes(rect,frameon=False)
a2.yaxis.tick_right()
plot([0],[0],'r',[0],[0],'g',r,tovs[-1][:isurf,3]/msun,'b') # plot mass
a2.yaxis.set_label_position('right')
ylabel('Mass (Msun)')
a2.set_xticks([])