def getGraph():
    for i, clf in enumerate((svm, rbf_svc, rbf_svc_tunning)):
        # Se grafican las fronteras
        plt.subplot(2, 2, i + 1)
        plt.subplots_adjust(wspace=0.4, hspace=0.4)

        Z = clf.predict(np.c_[x_matrizSetEntrenamientoVect, y_clases])

        #Color en las gráficas
        Z = Z.reshape(x_matrizSetEntrenamientoVect.shape)
        plt.contourf(x_matrizSetEntrenamientoVect,
                     y_clases,
                     Z,
                     cmap=plt.cm.Paired,
                     alpha=0.8)

        #Puntos de entrenamiento
        plt.scatter(x_matrizSetEntrenamientoVect[:, 0],
                    x_matrizSetEntrenamientoVect[:, 1],
                    c=y_clases,
                    cmap=plt.cm.Paired)
        plt.xlabel('Longitud Sepal')
        plt.ylabel('Peso Sepal')
        plt.xlim(x_matrizSetEntrenamientoVect.min(),
                 x_matrizSetEntrenamientoVect.max())
        plt.ylim(y_clases.min(), y_clases.max())
        plt.xticks(())
        plt.yticks(())
        plt.title(titles[i])

    plt.show()
Example #2
0
def _plot_x_label(df):
    from matplotlib.pylab import plt
    import datetime
    plt.scatter([
        datetime.datetime.fromtimestamp(x.timestamp())
        for x in df['datetime'][df['label'] == 1]
    ],
                df['close'][df['label'] == 1],
                color='red',
                s=1)
    plt.scatter([
        datetime.datetime.fromtimestamp(x.timestamp())
        for x in df['datetime'][df['label'] == -1]
    ],
                df['close'][df['label'] == -1],
                color='green',
                s=1)
    plt.scatter([
        datetime.datetime.fromtimestamp(x.timestamp())
        for x in df['datetime'][df['label'] == 0]
    ],
                df['close'][df['label'] == 0],
                color='yellow',
                s=1)
    plt.show()
Example #3
0
    def __init__(self,
                 dir_name='/home/steve/Data/FusingLocationData/0010/'):
        if not dir_name[-1] is '/':
            dir_name = dir_name + '/'

        imu_left = np.loadtxt(dir_name + 'LEFT_FOOT.data', delimiter=',')
        imu_right = np.loadtxt(dir_name + 'RIGHT_FOOT.data', delimiter=',')
        imu_head = np.loadtxt(dir_name + 'HEAD.data', delimiter=',')

        uwb_head = np.loadtxt(dir_name + 'uwb_result.csv', delimiter=',')
        beacon_set = np.loadtxt(dir_name + 'beaconSet.csv', delimiter=',')

        print('average time interval of left:',
              float(imu_left[-1, 1] - imu_left[0, 1]) / float(imu_left.shape[0]))
        print('average time interval of right:',
              float(imu_right[-1, 1] - imu_right[0, 1]) / float(imu_right.shape[0]))

        print('average time interval of head:',
              float(imu_head[-1, 1] - imu_head[0, 1]) / float(imu_head.shape[0]))

        plt.figure()
        plt.plot(imu_left[1:, 1] - imu_left[:-1, 1], label='time left')
        plt.plot(imu_right[1:, 1] - imu_right[:-1, 1], label='time right')
        # time_diff = imu_left[1:,1] - imu_left[:-1,1]
        # plt.plot(time_diff-time_diff.mean(),label='time diff')
        plt.plot(imu_head[1:, 1] - imu_head[:-1, 1], label=' time head')

        plt.grid()
        plt.legend()
        plt.show()
Example #4
0
def GenerateWpaGraph(GamePck):
    """Returns a list of the homeTeam wPA and generates the Win probability graph of a specified game """
    game = get('game_winProbability', {'ver': 'v1', 'gamePk': GamePck})

    atbat = [0]
    home = 50

    homeL = [50]

    for item in game:
        for key, val in item.items():
            if key == 'atBatIndex':
                atbat.append(val)

            if key == 'homeTeamWinProbabilityAdded':

                home += val
                homeL.append(home)

    c = ['g' if a >= 50 else 'r' for a in homeL]
    lines = [
        ((x0, y0), (x1, y1))
        for x0, y0, x1, y1 in zip(atbat[:], homeL[:], atbat[1:], homeL[1:])
    ]
    coloredLines = LineCollection(lines, colors=c, linewidths=(2, ))
    fig, ax = plt.subplots(1)
    ax.add_collection(coloredLines)
    ax.autoscale_view()
    plt.show()
    return homeL
Example #5
0
def plot_us_women_win_ratio():
    """This function plots the win ratio of US women over 120 years of Olympics
    :param medal_winners: dataframe object"""
    assert isinstance(
        medal_winners,
        pd.DataFrame), "medal_winners must be of type pd.DataFrame"

    female_winners = medal_winners.loc[medal_winners['Gender'] == 'Women']
    male_winners = medal_winners.loc[medal_winners['Gender'] == 'Men']
    female_winners_usa = female_winners.loc[female_winners['Country'] ==
                                            'USA'].groupby("Year").count()
    male_winners_usa = male_winners.loc[male_winners['Country'] ==
                                        'USA'].groupby("Year").count()
    win_ratio_usa = female_winners_usa / (female_winners_usa +
                                          male_winners_usa)
    win_ratio_usa = win_ratio_usa.fillna(0)
    win_ratio_usa = win_ratio_usa.reset_index()

    ax = sns.lineplot(x="Year",
                      y="Medal",
                      markers=True,
                      color="red",
                      dashes=False,
                      data=win_ratio_usa)
    ax.set(xlabel='Year', ylabel='Medal Win Ratio')
    plt.show()
Example #6
0
def bbfold(P):
    

    # Trial Data:
    tbase = 90.
    f,t = keptoy.lightcurve(tbase=tbase,s2n=5,P=10.1)
    
    o = pbls.blswrap(t,f,blsfunc=blsw.blsw)
    farr = linspace(min(o['farr']),max(o['farr']),100)
    sig = zeros(len(f)) + std(f)

 #   for fq in farr:

    tfold = mod(t,P) # Fold according to trial period.
    sidx = argsort(tfold)
    tfold = tfold[sidx]
    ffold = f[sidx]

    last,val = find_blocks.pt(tfold,ffold,sig,ncp=8)

    fig = plt.gcf()
    fig.clf()

    ax = fig.add_subplot(111)
    ax.plot(tfold,ffold,'o',ms=1,alpha=0.5)

    cp = unique(last)
    n = len(t)
    idxlo = cp                    # index of left side of region
    idxhi = append(cp[1:],n)-1 # index of right side of region         
    ax.hlines(val[idxhi],tfold[idxlo],tfold[idxhi],'red',lw=5)
    ax.set_ylabel('Flux (normalized)')

    plt.show()
Example #7
0
    def display(self, current=None, target=None):
        """
        Plots the state of the task. If <show> = False, doesn't plot
        anything and the simulation can run faster.
        """

        if not self.show:
            return

        # Scatter plot of points, color coded by class
        pts = self.points
        size = 35
        for cluster, color in cluster_colors.iteritems():
            class_points = [x for x in pts if x.cluster == cluster]
            plt.scatter([p.x for p in class_points], [p.y for p in class_points], c=color, s=size)

        # Draw the connections
        if self.connectivity_matrix is not None:
            for start_ix, connections in enumerate(self.connectivity_matrix):
                for connect_ix, connected in enumerate(connections):
                    if connected and connect_ix != start_ix:
                        plt.plot(*zip(
                            (pts[start_ix].x, pts[start_ix].y),
                            (pts[connect_ix].x, pts[connect_ix].y)),
                            c='k', linewidth=0.5)

        # Show where the message is going and where it currently is
        if current and target:
            plt.scatter(pts[current].x, pts[current].y, c='m', s=150)
            plt.scatter(pts[target].x,  pts[target].y,  c='y', s=190)

        plt.show()
Example #8
0
def plot_sex_ratio_year_wise():
    """
    This function plots the female to male participation ratio summed for all countries year wise
    :param female_athletes: dataframe object
    :param male_athletes: dataframe object
    """

    assert isinstance(
        female_athletes,
        pd.DataFrame), "female_athletes must be of type pd.DataFrame"
    assert isinstance(
        male_athletes,
        pd.DataFrame), "male_athletes must be of type pd.DataFrame"

    female_count_year_wise = female_athletes[["NOC", "Sex",
                                              "Year"]].groupby("Year").count()
    male_count_year_wise = male_athletes[["NOC", "Sex",
                                          "Year"]].groupby("Year").count()

    sex_ratio_year_wise = female_count_year_wise["Sex"] / (
        female_count_year_wise["Sex"] + male_count_year_wise["Sex"])
    sex_ratio_year_wise = sex_ratio_year_wise.reset_index()
    sex_ratio_year_wise = sex_ratio_year_wise.fillna(0)

    ax = sns.lineplot(x="Year",
                      y="Sex",
                      markers=True,
                      dashes=False,
                      data=sex_ratio_year_wise)
    ax.set(xlabel='Year', ylabel='Sex Ratio')
    plt.show()
def main():
    # prepare data
    trainingSet = []
    testSet = []
    split = 0.80
    # path = r'C:/Users/ASUS/PycharmProjects/knntest/iris'
    loadDataset("C:\\Users\\ASUS\\Desktop\\mnist_test_1.csv", split,
                trainingSet, testSet)
    print('Train set: ' + repr(len(trainingSet)))
    print('Test set: ' + repr(len(testSet)))
    # generate predictions
    predictions = []
    k = 5
    xvalues = []
    pred = []
    actual = []
    for x in range(len(testSet)):
        neighbors = getNeighbors(trainingSet, testSet[x], k)
        # print(neighbors)
        result = getResponse(neighbors)
        predictions.append(result)
        print('> predicted=' + repr(result) + ', actual=' +
              repr(testSet[x][-1]))
        xvalues.append(x)
        pred.append(result)
        actual.append(testSet[x][-1])

        #plt.plot(x,repr(testSet[x][-1]),color="chocolate",label="Actual Values")
    accuracy = getAccuracy(testSet, predictions)
    plt.plot(xvalues, pred, ".", color="r", label="Predicted Values")
    plt.plot(xvalues, actual, ".", color="b", label="Actual Values")

    plt.show()
    print('Accuracy: ' + repr(accuracy) + '%')
Example #10
0
def p2d(p,farr,ph):
    """
    Shows the power for the BLS 2D spectrum
    """

    # first index is plotted as y,this should be the other way around
    

    p = np.swapaxes(p,0,1)
    f = plt.gcf()
    f.clf()

    # create two axes, one for the image, the other for the profile.
    r1d = [0.1,0.75,0.8,0.2]
    r2d = [0.1,0.1,0.8,0.65]

    ax1d = plt.axes(r1d)
    ax2d = plt.axes(r2d,sharex=ax1d)

    power = np.max(p,axis=0)
    ax1d.plot(farr,power)
    ax1d.set_ylabel('Power') 


    ax2d.pcolorfast(farr,ph,p)
    ax2d.set_xlabel('frequency days^-1') 
    ax2d.set_ylabel('phase of trans / 2 pi') 


    plt.show()
Example #11
0
def AddRegressor():
    rng = np.random.RandomState(1)  # 和random_state的用法一致   在这可以固定生成的随机数
    x = np.sort(5 * rng.rand(80, 1),
                axis=0)  # rng.rand(80,1)  生成80行1列的随机数 乘以5就是生成0-5的随机数
    y = np.sin(x).ravel()  # ravel()降维
    y[::5] += 0.3 * (0.5 - rng.rand(16))

    # plt.show()
    reg1 = tree.DecisionTreeRegressor(max_depth=2)
    reg2 = tree.DecisionTreeRegressor(max_depth=5)
    reg1.fit(x, y)
    reg2.fit(x, y)

    test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
    y1 = reg1.predict(test)
    y2 = reg2.predict(test)
    #plt.figure()
    plt.figure()
    plt.scatter(x, y, label='dian')
    plt.plot(test, y1, color='red', label='max_depth=2')
    plt.plot(test, y2, color='yellow', label="max_depth=5")
    plt.xlabel('data')
    plt.ylabel('target')
    plt.legend(loc='upper right')
    plt.show()
def plot_data():
    fig, axs = plt.subplots(2)
    fig.tight_layout(pad=3.0)

    for key in sorted(data_dict.keys()):
        X_data = data_dict[key][0]
        Y_data = data_dict[key][1]
        axs[0].plot(X_data, Y_data)

    axs[0].set_xlabel('X-coordinate')
    axs[0].set_xlim(0, 250)
    axs[0].set_ylabel('Y-coordinate')
    axs[0].set_ylim(250, 0)
    axs[0].set_title('Mitochondrial Tracking')

    for key in sorted(data_dict.keys()):
        X_data = data_dict[key][0]
        Y_data = data_dict[key][1]
        if (determine_direction(Y_data[0], Y_data[-1])):
            axs[1].plot(X_data, Y_data, 'b')
            print('Blue ', key)
        else:
            axs[1].plot(X_data, Y_data, 'y')
            print('Gold', key)

    axs[1].set_xlabel('X-coordinate')
    axs[1].set_xlim(0, 250)
    axs[1].set_ylabel('Y-coordinate')
    axs[1].set_ylim(
        250, 0
    )  #Inverts the y-axis to match the numbering system in Fiji Manual Tracking
    axs[1].set_title('Mitochondrial Directionality')

    plt.show()
Example #13
0
def run(plotIt=True, nx=5, ny=5):
    """

        Utils: surface2ind_topo
        =======================

        Here we show how to use :code:`Utils.surface2ind_topo` to identify cells below
        a topographic surface.

    """

    mesh = Mesh.TensorMesh([nx,ny], x0='CC') # 2D mesh
    xtopo = np.linspace(mesh.gridN[:,0].min(), mesh.gridN[:,0].max())
    topo = 0.4*np.sin(xtopo*5) # define a topographic surface

    Topo = np.hstack([Utils.mkvc(xtopo,2), Utils.mkvc(topo,2)]) #make it an array

    indcc = surface2ind_topo(mesh, Topo, 'CC')

    if plotIt:
        from matplotlib.pylab import plt
        from scipy.interpolate import interp1d
        fig, ax = plt.subplots(1,1, figsize=(6,6))
        mesh.plotGrid(ax=ax, nodes=True, centers=True)
        ax.plot(xtopo,topo,'k',linewidth=1)
        ax.plot(mesh.vectorCCx, interp1d(xtopo,topo)(mesh.vectorCCx),'--k',linewidth=3)

        aveN2CC = Utils.sdiag(mesh.aveN2CC.T.sum(1))*mesh.aveN2CC.T
        a = aveN2CC * indcc
        a[a > 0] = 1.
        a[a < 0.25] = np.nan
        a = a.reshape(mesh.vnN, order='F')
        masked_array = np.ma.array(a, mask=np.isnan(a))
        ax.pcolor(mesh.vectorNx,mesh.vectorNy,masked_array.T, cmap=plt.cm.gray, alpha=0.2)
        plt.show()
Example #14
0
def example_image(graph, filename, layout='spring', edge_labels=False,
                  node_labels=False, show=False):
    """Generates example image with graph.

    Uses nx.draw_networkx_* methods, and matplotlib to draw and save the
    image.

    """
    # positions for all nodes
    pos = LAYOUT_DICT[layout](graph)

    # configure the image
    plt.figure(figsize=(2, 2))
    plt.axis('off')

    # draw all of the things!
    nx.draw_networkx_nodes(graph, pos, nodelist=graph.nodes(), node_color='r')
    nx.draw_networkx_edges(graph, pos, width=1.0, alpha=0.5, arrows=True)

    if node_labels:
        nlabels = {node: str(node) for node in graph.nodes()}
        nx.draw_networkx_labels(graph, pos, nlabels, font_size=16)

    if edge_labels:
        elabels = {edge: str(idx) for idx, edge in enumerate(graph.edges())}
        nx.draw_networkx_edge_labels(graph, pos, elabels)

    # place the file where it belongs
    path = os.path.join(os.environ['ERDOS_PATH'], "content/images", filename)
    plt.savefig(path)

    if show:
        plt.show()
Example #15
0
    def show(self, w):
        """
        illustrate the learning curve

        Parameters
        ----------
        w : int, window size for smoothing the curve
        """

        # plot data
        plt.subplot(121)
        plt.plot(self.tn_it, self.tn_err, 'b.', alpha=0.2)
        plt.plot(self.tt_it, self.tt_err, 'r.', alpha=0.2)
        # plot smoothed line
        xne,yne = self._smooth( self.tn_it, self.tn_err, w )
        xte,yte = self._smooth( self.tt_it, self.tt_err, w )
        plt.plot(xne, yne, 'b')
        plt.plot(xte, yte, 'r')
        plt.xlabel('iteration'), plt.ylabel('cost energy')

        plt.subplot(122)
        plt.plot(self.tn_it, self.tn_cls, 'b.', alpha=0.2)
        plt.plot(self.tt_it, self.tt_cls, 'r.', alpha=0.2)
        # plot smoothed line
        xnc, ync = self._smooth( self.tn_it, self.tn_cls, w )
        xtc, ytc = self._smooth( self.tt_it, self.tt_cls, w )
        plt.plot(xnc, ync, 'b', label='train')
        plt.plot(xtc, ytc, 'r', label='test')
        plt.xlabel('iteration'), plt.ylabel( 'classification error' )
        plt.legend()
        plt.show()
        return
def test_psv_dataset_tfm_segmentation_cropped():
    from psv.ptdataset import PsvDataset, TFM_SEGMENTATION_CROPPED

    ds = PsvDataset(transform=TFM_SEGMENTATION_CROPPED)

    assert len(ds) == 956, "The dataset should have this many entries"

    mb = ds[0]
    image = mb['image']
    mask = mb['mask']
    assert isinstance(image, torch.Tensor)
    assert isinstance(mask, torch.Tensor)

    assert mask.shape[-2:] == image.shape[-2:]

    # Hard to test due to randomness....

    PLOT=True
    if PLOT:
        from matplotlib.pylab import plt
        import torchvision.transforms.functional as F
        a = ds.get_annotation(0)
        plt.figure()
        plt.suptitle('Visualizing test_psv_dataset_tfm_segmentation_cropped, close if ok')
        plt.subplot(121)
        plt.imshow(F.to_pil_image(image))
        plt.title('image')

        plt.subplot(122)
        plt.imshow(a.colors[mask.numpy()])
        plt.title('mask')
        plt.show()
Example #17
0
def plotting(sim_context1,sim_context2,diff,data_df,total_samples):

    plt.plot(sim_context1,label="Context 1")
    plt.plot(sim_context2,label="Context 2")


    x_labels_word1 = data_df["word1"]
    x_labels_word2 = data_df["word2"]

    xlabels = [0] * total_samples
    xticks_x = [0] * total_samples


    for wp in range (total_samples):
        xlabels[wp] = x_labels_word1[wp]+ "\n"+x_labels_word2[wp]
        xticks_x[wp] = wp+1

    plt.plot(diff,label="Difference")

    plt.legend(loc='center right')

    # Add title and x, y labels
    plt.title("Elmo Embedding Model Results", fontsize=16, fontweight='bold')

    plt.xlabel("Word")
    plt.ylabel("Similarity")

    plt.xticks(xticks_x, xlabels)
    plt.show()
Example #18
0
    def show(self, w):
        """
        illustrate the learning curve

        Parameters
        ----------
        w : int, window size for smoothing the curve
        """

        # plot data
        plt.subplot(121)
        plt.plot(self.tn_it, self.tn_err, 'b.', alpha=0.2)
        plt.plot(self.tt_it, self.tt_err, 'r.', alpha=0.2)
        # plot smoothed line
        xne, yne = self._smooth(self.tn_it, self.tn_err, w)
        xte, yte = self._smooth(self.tt_it, self.tt_err, w)
        plt.plot(xne, yne, 'b')
        plt.plot(xte, yte, 'r')
        plt.xlabel('iteration'), plt.ylabel('cost energy')

        plt.subplot(122)
        plt.plot(self.tn_it, self.tn_cls, 'b.', alpha=0.2)
        plt.plot(self.tt_it, self.tt_cls, 'r.', alpha=0.2)
        # plot smoothed line
        xnc, ync = self._smooth(self.tn_it, self.tn_cls, w)
        xtc, ytc = self._smooth(self.tt_it, self.tt_cls, w)
        plt.plot(xnc, ync, 'b', label='train')
        plt.plot(xtc, ytc, 'r', label='test')
        plt.xlabel('iteration'), plt.ylabel('classification error')
        plt.legend()
        plt.show()
        return
def plot_histogram(entries):
    n, bins, patches = plt.hist(entries.values(), 50, normed=1, facecolor='green', alpha=0.75)

    plt.xlabel('Time (h)')
    plt.ylabel('Probability')
    plt.grid(True)
    plt.show()
Example #20
0
def MRI():

    T1 = 800*10**-3
    T2 = 100*10**-3
    a = pi/2
    t = np.linspace(0, 1, 100)

    # Initalize and Rotate
    M = np.array([0,0,1])
    R = np.array([[1, 0,       0],
                  [0, cos(a),  sin(a)],
                  [0, -sin(a), cos(a)]])
    M = R.dot(M)

    # T1/T2 Relaxationq
    M_z = 1 + (M[2] - 1) * np.exp(-t/T1)
    M_x = M[0]*np.exp(-t/T2)
    M_y = M[1]*np.exp(-t/T2)
    M_xy = np.sqrt(M_x*M_x + M_y*M_y)

    plt.subplot(121)
    plt.plot(t, M_xy)
    plt.subplot(122)
    plt.plot(t, M_z)
    plt.show()
Example #21
0
def plot_events(real,pred,meta,real_,pred_, label=None):
    from matplotlib.pylab import plt
    import random
    fig,ax = plt.subplots(figsize=(15, .8))
    ax.set_title(label)
    plt.xlim(0,max(meta[1],10))
    ax.set_xticks(np.arange(0,max(real[-1][1],10),.1),minor=True)
    maxsize=20
# random.random()/4
    for i in range(min(maxsize,len(pred_))):
        d = pred_[i]
        plt.axvspan(d[0], d[1], 0, 0.6,linewidth=0,edgecolor='k',facecolor='#edb4b4', alpha=.6)
        plt.text((d[1] + d[0]) / 2, 0.2,f'{i}' , horizontalalignment='center', verticalalignment='center')
    for i in range(min(maxsize,len(pred))):
        d = pred[i]
        plt.axvspan(d[0], d[1], 0.0, 0.6,linewidth=0,edgecolor='k',facecolor='#a31f1f', alpha=.6)
        plt.text((d[1] + d[0]) / 2, 0.2,f'{i}' , horizontalalignment='center', verticalalignment='center')
#     maxsize=len(real)
    for i in range(min(maxsize,len(real_))):
        gt = real_[i]
        plt.axvspan(gt[0], gt[1], 0.4, 1,linewidth=0,edgecolor='k',facecolor='#d2f57a', alpha=.6)
        plt.text((gt[1] + gt[0]) / 2, 0.8,f'{i}' , horizontalalignment='center', verticalalignment='center')
        
    for i in range(min(maxsize,len(real))):
        gt = real[i]
        plt.axvspan(gt[0], gt[1], 0.4, 1,linewidth=0,edgecolor='k',facecolor='#1fa331', alpha=.6)
        plt.text((gt[1] + gt[0]) / 2, 0.8,f'{i}' , horizontalalignment='center', verticalalignment='center')
    # plt.grid(True)
    plt.minorticks_on()
    ax.set(yticks=[.25,.75], yticklabels=['P','R'])
    # plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
    plt.show()
Example #22
0
def plot_country_sex_ratio(country):
    """
    This function plots the sex ratio of input country over the years
    :param female_athletes: dataframe object
    :param male_athletes: dataframe object
    :param country: Country name whose sex ratio we want to plot
    """
    assert isinstance(
        female_athletes,
        pd.DataFrame), "female_athletes must be of type pd.DataFrame"
    assert isinstance(
        male_athletes,
        pd.DataFrame), "male_athletes must be of type pd.DataFrame"
    assert isinstance(country, str), "Country name must be an integer"

    country_ratios_year = female_athletes[["NOC", "Sex", "Year"]].groupby(["NOC", "Year"]).count() / \
                      (female_athletes[["NOC", "Sex", "Year"]].groupby(["NOC", "Year"]).count() +
                       male_athletes[["NOC", "Sex", "Year"]].groupby(["NOC", "Year"]).count())

    country_ratios_year = country_ratios_year.reset_index()

    country_plot = country_ratios_year.loc[country_ratios_year["NOC"] ==
                                           country]
    country_plot = country_plot.fillna(0)

    ax = sns.lineplot(x="Year",
                      y="Sex",
                      markers=True,
                      dashes=False,
                      data=country_plot)
    ax.set(xlabel='Year', ylabel='Sex Ratio')
    plt.show()
Example #23
0
def plot_four(plot_data):
    
    fig = plt.figure(figsize=(20, 10))
    
#    gs = gridspec.GridSpec(1, 2, height_ratios=[1, 2]) 
    
    ax = fig.add_subplot(223, projection='3d')
    ax.scatter(plot_data['sx'],  plot_data['sy'], plot_data['sz'])
    ax.plot(plot_data['sx'],  plot_data['sy'], plot_data['sz'], color='b')
    ax.view_init(azim=0, elev=90) #xy plane
    plt.xticks(fontsize=10)
    ax.set_title('Displacement Projection in xy Plane',size=20)

    ax2 = fig.add_subplot(224, projection='3d')
    ax2.scatter(plot_data['sx'],  plot_data['sy'], plot_data['sz'])
    ax2.plot(plot_data['sx'],  plot_data['sy'], plot_data['sz'], color='b')
    ax2.view_init(azim=0, elev=45) 
    ax2.set_title('Displacement',size=20)

    ax3 = fig.add_subplot(221)
    # 50 represents number of points to make between T.min and T.max
    xnew = np.linspace(0,8,50) 
    spl = make_interp_spline(pd.Series(range(9)), plot_data['tilt1'], k=3)  # type: BSpline
    x = spl(xnew)
    spl = make_interp_spline(pd.Series(range(9)), plot_data['tilt2'], k=3)  # type: BSpline
    y = spl(xnew)
    spl = make_interp_spline(pd.Series(range(9)), plot_data['compass'], k=3)  # type: BSpline
    z = spl(xnew)
    ax3.plot(x,"b-",label='tilt1')
    ax3.plot(y,"r-",label='tilt2')
    ax3.plot(z,"g-",label='compass')
    ax3.legend(loc="lower left",prop={'size': 20})
    ax3.set_title('Orientation Plot (degree)',size=20)
    ax3.tick_params(labelsize=20)
    
    ax4 = fig.add_subplot(222)
#    x = gaussian_filter1d(plot_data['ax'], sigma=1)    
#    y = gaussian_filter1d(plot_data['ay'], sigma=1)   
#    z = gaussian_filter1d(plot_data['az'], sigma=1)   
#    mag = gaussian_filter1d(plot_data['accelerometer'], sigma=1)   
    spl = make_interp_spline(pd.Series(range(9)), plot_data['ax'], k=3)  # type: BSpline
    x = spl(xnew)
    spl = make_interp_spline(pd.Series(range(9)), plot_data['ay'], k=3)  # type: BSpline
    y = spl(xnew)
    spl = make_interp_spline(pd.Series(range(9)), plot_data['az'], k=3)  # type: BSpline
    z = spl(xnew)
    spl = make_interp_spline(pd.Series(range(9)), plot_data['accelerometer'], k=3)  # type: BSpline
    mag = spl(xnew)
    ax4.plot(x/1000,"c--",label='ax')
    ax4.plot(y/1000,"g--",label='ay')
    ax4.plot(z/1000,"b--",label='az')
    ax4.plot(mag,"r-",label='Acc')

    ax4.legend(loc="lower left",prop={'size': 20})
    ax4.set_title('Acceleration Plot (g)',size=20)
    ax4.tick_params(labelsize=20)
    
    plt.tight_layout()
    plt.show()
    fig.savefig('FourInOne.png')
Example #24
0
def plot_single(df_metrics):
    """
    APFD plot for single Embedding Neural Network model
    :param df_metrics:
    :return:
    """
    apfd = df_metrics['apfd']

    miu = np.round(np.mean(apfd), 2)
    sigma = np.round(np.std(apfd), 2)
    label = 'regression' + '\n $\mu$ - ' + str(miu) + ' $\sigma$ - ' + str(
        sigma)

    sns.distplot(apfd,
                 kde=True,
                 bins=int(180 / 5),
                 color=sns.color_palette()[0],
                 hist_kws={'edgecolor': 'black'},
                 kde_kws={
                     'linewidth': 4,
                     'clip': (0.0, 1.0)
                 },
                 label=label)

    plt.legend(frameon=True, loc='upper left', prop={'size': 20})
    plt.xlabel('APFD')

    #plt.title('APFD Distribution - 100 revisions ')
    plt.show()
def plot():
    plt.figure(figsize=(20, 10))
    width = 0.5
    index = np.arange(26)

    print 'SUM PLOT 1', sum(row[0] for row in data)
    print 'SUM PLOT 2', sum(row[1] for row in data)
    print 'SUM PLOT 3', sum(row[2] for row in data)

    print data[0]
    
    p0 = plt.bar(index, data[0], width, color='y')  # people
    p1 = plt.bar(index, data[1], width, color='g')  # nature
    p2 = plt.bar(index, data[2], width, color='r')  # activity
    p3 = plt.bar(index, data[3], width, color='b')  # food
    p4 = plt.bar(index, data[4], width, color='c')  # symbols
    p5 = plt.bar(index, data[5], width, color='m')  # objects
    p6 = plt.bar(index, data[6], width, color='k')  # flags
    p7 = plt.bar(index, data[7], width, color='w')  # uncategorized


    plt.ylabel('Usage')
    plt.title('Emoji category usage per city')
    plt.xticks(index + width/2.0, cities)
    plt.yticks(np.arange(0, 1, 0.1))
    plt.legend((p0[0], p1[0], p2[0], p3[0], p4[0], p5[0], p6[0], p7[0]), categories_names)

    plt.show()
Example #26
0
def plot_roc(res, title=''):
    """Given a modeler result plot an ROC curves

    Parameters
    ----------
    res : list
        list of tuples: (name, auc, (fpr, tpf, threshold))
    title : string
        Title of the figure
    """
    from matplotlib.pylab import plt
    from math import ceil
    from functional import add
    colors = [ 'r-','g-', 'b-', 'c-', 'm-','y-', 'rx-','gx-', 'bx-', 'cx-', 'mx-', 'ro-','go-', 'bo-', 'co-', 'mo-', 'r.', 'g.', 'b.', 'c.', 'm.'   ]
    colors*=int(1+ceil(20 / len(colors) ))
    idx = list( np.argsort([np.mean(auc) for _, auc, _ in res]) )
    values = reduce(add,( [fpr,tpr,colors.pop(0)] for fpr, tpr, thr in (d[0] for _, _, d in (res[i] for i in reversed(idx))) ),[])
    names =  list( u'%s [auc=%.2f\u00b1%.2f]'%(n,np.mean(auc),np.std(auc)) for n, auc, _ in (res[i] for i in reversed(idx)) )
    plt.subplots_adjust(left=.1, bottom=.1, right=.90, top=.90, wspace=.4, hspace=.4)
    ax1 = plt.subplot2grid((5,1), (1, 0), rowspan=4)
    ax2 = plt.subplot2grid((5,1), (0, 0),frameon=False,xticks=[],yticks=[])
    ln = ax1.plot( *values )
    ax1.fill_between( [0,1],[0,0],[0,1],facecolor='red',alpha=0.15 )
    ax1.set_xlabel('false positive rate')
    ax1.set_ylabel('true positive rate')
    ax1.set_xlim((0,1))
    ax1.set_ylim((0,1))
    ax2.legend(ln, names, loc=10, ncol = 1, mode='expand', prop={'size': 10})
    plt.show()
Example #27
0
    def display(self, current=None, target=None):
        """
        Plots the state of the task. If <show> = False, doesn't plot
        anything and the simulation can run faster.
        """

        if not self.show:
            return

        # Scatter plot of points, color coded by class
        pts = self.points
        size = 35
        for cluster, color in cluster_colors.iteritems():
            class_points = [x for x in pts if x.cluster == cluster]
            plt.scatter([p.x for p in class_points],
                        [p.y for p in class_points],
                        c=color,
                        s=size)

        # Draw the connections
        if self.connectivity_matrix is not None:
            for start_ix, connections in enumerate(self.connectivity_matrix):
                for connect_ix, connected in enumerate(connections):
                    if connected and connect_ix != start_ix:
                        plt.plot(*zip((pts[start_ix].x, pts[start_ix].y),
                                      (pts[connect_ix].x, pts[connect_ix].y)),
                                 c='k',
                                 linewidth=0.5)

        # Show where the message is going and where it currently is
        if current and target:
            plt.scatter(pts[current].x, pts[current].y, c='m', s=150)
            plt.scatter(pts[target].x, pts[target].y, c='y', s=190)

        plt.show()
 def plot_error(self, train_errors):
     n = len(train_errors)
     training, = plt.plot(range(n), train_errors, label="Training Error")
     plt.legend(handles=[training])
     plt.title("Error Plot")
     plt.ylabel('Error')
     plt.xlabel('Iterations')
     plt.show()
def test_psv_dataset_crop_and_pad():
    import psv.ptdataset as P


    TFM_SEGMENTATION_CROPPED = psv.transforms.Compose(
        psv.transforms.ToSegmentation(),

        # Crop in on the facades
        psv.transforms.SetCropToFacades(pad=20, pad_units='percent', skip_unlabeled=True, minsize=(512, 512)),
        psv.transforms.ApplyCrop('image'),
        psv.transforms.ApplyCrop('mask'),
        
        # Resize the height to fit in the net (with some wiggle room)
        # THIS is the test case -- the crops will not usually fit anymore
        psv.transforms.Resize('image', height=400),
        psv.transforms.Resize('mask', height=400, interpolation=P.Image.NEAREST),

        # Reandomly choose a subimage
        psv.transforms.SetRandomCrop(512, 512),
        psv.transforms.ApplyCrop('image'),
        psv.transforms.ApplyCrop('mask', fill=24), # 24 should be unlabeled
        
        psv.transforms.DropKey('annotation'),
        psv.transforms.ToTensor('image'),
        psv.transforms.ToTensor('mask', preserve_range=True),
        ) 

    ds = P.PsvDataset(transform=TFM_SEGMENTATION_CROPPED)

    assert len(ds) == 956, "The dataset should have this many entries"

    mb = ds[0]
    image = mb['image']
    mask = mb['mask']
    assert isinstance(image, torch.Tensor)
    assert isinstance(mask, torch.Tensor)

    assert mask.shape[-2:] == image.shape[-2:]

    # Hard to test due to randomness....

    PLOT=True
    if PLOT:
        from matplotlib.pylab import plt
        import torchvision.transforms.functional as F
        a = ds.get_annotation(0)
        plt.figure()
        plt.suptitle('Visualizing test_psv_dataset_tfm_segmentation_cropped,\n'
                     'close if ok \n '
                     'confirm boundary is  marked unlabeled')
        plt.subplot(121)
        plt.imshow(F.to_pil_image(image))
        plt.title('image')

        plt.subplot(122)
        plt.imshow(a.colors[mask.numpy()])
        plt.title('mask')
        plt.show()
def display_digit(X_data, y_data=None, i=0):
    """Display the Xi image, optionally with the corresponding yi label."""
    plt.close('all')
    Xi = X_data[i]
    side = np.sqrt(Xi.size).astype(int)
    data = np.array(Xi).reshape((side, side))
    plt.imshow(data, cmap='Greys', interpolation='nearest')
    plt.title("y = " + str(y_data[i]))
    plt.show()
Example #31
0
def Test2():
    t = np.linspace(0,10,100)
    x = np.sin(t)

    plt.plot(t, x)
    plt.title('sin(x)')
    plt.xlabel('time (s)')
    plt.ylabel('magnitude')
    plt.show()
 def plot_accuracy(self, train_acc, test_acc):
     n = len(train_acc)
     plt.plot(range(n), train_acc, label="train")
     plt.plot(range(n), test_acc, label="test")
     plt.legend(loc='lower right')
     plt.title("Overfit")
     plt.ylabel('accuracy')
     plt.xlabel('epoch')
     plt.show()
Example #33
0
def blsbb():
    """
    Simulate a time series.  Compare two bls spectra.

    1. Normal BLS
    2. Blocks returned by BB

    Also plot the timeseries.

    """


    s2n = logspace(0.5,2,8)

    for i in range( len(s2n) ):

        f,t = keptoy.lightcurve(s2n = s2n[i],tbase=600)

        sig = zeros(len(t)) + std(f)
        last,val =  find_blocks.pt(t,f,sig,ncp=5)
        fb = bb.get_blocks(f,last,val)

        o = pbls.blswrap(t,f,blsfunc=blsw.blsw,nf=1000)
        ob = pbls.blswrap(t,fb,blsfunc=blsw.blsw,nf=1000)

        fig = plt.gcf()
        fig.clf()


        ax = fig.add_subplot(211)


        ax.plot(t,f+1,'o',ms=1,alpha=0.5)
        
        cp = unique(last)
        n = len(t)
        idxlo = cp                    # index of left side of region
        idxhi = append(cp[1:],n)-1 # index of right side of region         
        ax.hlines(val[idxhi],t[idxlo],t[idxhi],'red',lw=5)
        ax.set_ylabel('Flux (normalized)')
        ax.set_xlabel('Flux (normalized)')



        ax = fig.add_subplot(212)
        ax.plot(o['farr'],o['p']    ,label = 'BLS')
        ax.plot(ob['farr'],ob['p']  ,label = 'BLS + BB')
        ax.set_xlabel('Frequency days^-1')
        ax.set_ylabel('SR')
        ax.legend()

        fig.text(0.9,0.9, "S/N - %.1e" % (s2n[i]) ,
                 ha="center",fontsize=36,
                 bbox=dict(boxstyle="round", fc="w", ec="k"))

        fig.savefig('frames/blsbb%02d.png' % i)
        plt.show()
Example #34
0
File: panda.py Project: kataev/bkz
    def show(self):
        marks = sorted(dict(mark_c).keys())
        defects = {'gost': 'o', u'<20': '-', u'>20': '+', u'no_cont': 'x'}

        data = read_csv('../pandas.csv', delimiter=';', quoting=csv.QUOTE_NONE)
        d = data.ix[:, ['forming_density', 'batch_flexion', 'batch_pressure']]
        colors = [[round(x / 255., 4) for x in colorbrewer.Paired[7][marks.index(mark)]] for mark in data.batch_mark]
        # defects = [ (1, 1, 0) for defect in data.part_defect]
        scatter_matrix(d, alpha=1, diagonal='kde', c=colors, edgecolors='none')#, marker=defects)
        plt.show()
Example #35
0
 def f(self, **kwargs):
     kwargs['always_apply'] = True
     print(kwargs)
     aug = self.tfms(**kwargs)
     #         Just copy all images, next step will be for continious albus
     image = aug(image=self.image.copy())['image']
     plt.figure(figsize=(10, 10))
     plt.imshow(image)
     plt.axis('off')
     plt.show()
Example #36
0
def plot_histogram(entries):
    n, bins, patches = plt.hist(entries.values(),
                                50,
                                normed=1,
                                facecolor='green',
                                alpha=0.75)

    plt.xlabel('Time (h)')
    plt.ylabel('Probability')
    plt.grid(True)
    plt.show()
Example #37
0
 def plotMagnitudePhaseImage(self, image):
     mag = absolute(image).astype('float')
     phase = angle(image).astype('float')
     
     plt.subplot(211)
     plt.imshow(mag, cmap = cm.Greys_r)
     plt.axis('off')
     plt.subplot(212)
     plt.imshow(phase, cmap = cm.Greys_r)
     plt.axis('off')
     plt.show()
Example #38
0
def test_mtuidim_multivariate_normal():
    from matplotlib.pylab import plt
    x, y = np.mgrid[-5:5:.1, -5:5:.1]
    pos = np.array([x.ravel(), y.ravel()])
    rv = MultivariateNormal([0, 0], np.sqrt(np.array([[0.25, 0.3], [0.3, 1.0]])))

    z = rv.pdf(pos)

    cs = plt.contour(x, y, z.reshape((100, 100)))
    CB = plt.colorbar(cs, shrink=0.8, extend='both')
    plt.show()
Example #39
0
    def _build_plot_static(self, metric_group):
        metrics = self.get_metrics_history()
        if metric_group not in metrics:
            raise ValueError("can't find metric group")
        for name, values in metrics[metric_group].items():
            plt.plot(values, label=name)
        plt.legend(loc='best')
        plt.title(metric_group, fontsize=16, fontweight='bold')
        plt.xlabel("Generations")
        plt.show()

        return None
Example #40
0
 def plot_graph(self, auroc_results, y_label: str):
     for ad_key, ad_label in AD_NAMES.items():
         plt.plot(self.x_axis,
                  numpy.asarray(auroc_results[ad_key], ),
                  label=ad_label)
     plt.legend(loc='lower left')
     plt.xlabel(self.x_axis_label)
     plt.ylabel(ylabel=y_label)
     to_print = plt.gcf()
     plt.show()
     file_name_with_metric = y_label + "-" + self.file_name
     to_print.savefig(file_name_with_metric, bbox_inches='tight')
Example #41
0
def perfind2():
    
    P = 200.
    tbase = 1000.
    nf = 5000


    s2n = logspace( log10(3),log10(15),5 )
    print "S/N sig-noise noise-noise" 
    for s in s2n:
        # Generate a lightcurve.
        f,t = keptoy.lightcurve(P=P,tbase=tbase,s2n=s)
        o = blsw.blswrap(t,f,nf=nf,fmax=1/50.)

        # Subtract off the trend
        o['p'] -= median_filter(o['p'],size=200)

        # Find the highest peak.
        mxid = argmax(o['p'])
        mxpk = o['p'][mxid]

        # Find all the peaks        
        mxt,mnt = peakdet(o['p'],delta=1e-3*mxpk,x=o['parr'])
        mxt = array(mxt)

        # Restrict attention to the highest 100 but leaving off top 10
        t1id = where( (mxt[::,1] > sort( mxt[::,1] )[-100]) &
                      (mxt[::,1] < sort( mxt[::,1] )[-10]) )



        fig = plt.gcf()
        fig.clf()
        ax = fig.add_subplot(111)
        ax.plot(o['parr'],o['p'],label='Signal')
        ax.scatter( mxt[t1id,0],mxt[t1id,1],label='Tier 1' )
        
        # tpyical values of the highest 100 peaks.
        hair = median(mxt[t1id,1]) 


        left  = min(o['parr'])
        right  = max(o['parr'])
        ax.hlines(hair,left,right)

        if mxpk > 3*hair:
            print "Peroid is %.2f" % (o['parr'][mxid])
        else:
            print "No signal"
        
        ax.legend()
        plt.show()
Example #42
0
def update_data(args, show_seconds=20, subsampling=10):

    # load previous
    metadata1 = np.load(os.path.join(args.session1, 'metadata.npy'), allow_pickle=True).item()
    data1 = np.load(os.path.join(args.session1, 'NIdaq.npy'), allow_pickle=True).item()
    t1 = np.arange(len(data1['analog'][0,:]))/metadata1['NIdaq-acquisition-frequency']
    
    metadata2 = np.load(os.path.join(args.session2, 'metadata.npy'), allow_pickle=True).item()
    data2 = np.load(os.path.join(args.session2, 'NIdaq.npy'), allow_pickle=True).item()
    t2 = np.arange(len(data2['analog'][0,:]))/metadata1['NIdaq-acquisition-frequency']


    metadata = np.load(os.path.join(args.session1, 'metadata.npy'), allow_pickle=True).item()
    data = np.load(os.path.join(args.session, 'NIdaq.npy'), allow_pickle=True).item()
    t = np.arange(len(data['analog'][0,:]))/metadata1['NIdaq-acquisition-frequency']

    tstart = np.min([t.max(), t1.max(), t2.max()])-show_seconds # showing the last 5 seconds


    # checking that the two realisations are the same:
    plt.figure(figsize=(7,5))

    plt.plot(t1[t1>tstart][::subsampling],
             data1[args.type][args.channel,t1>tstart][::subsampling], label='session #1')
    
    plt.plot(t2[t2>tstart][::subsampling],
             data2[args.type][args.channel,t2>tstart][::subsampling], label='session #2')

    plt.plot(t[t>tstart][::subsampling],
             data[args.type][args.channel,t>tstart][::subsampling], label='session')
    
    plt.legend()
    plt.show()


    y = input('  /!\ ----------------------- /!\ \n  Confirm that you want to replace\n the "%s" data of channel "%s" in session:\n "%s"\n by the data of session #1 ? [yes/No]' % (args.type, args.channel, args.session))
    if y in ['y', 'Y', 'yes', 'Yes']:
        
        temp = str(tempfile.NamedTemporaryFile().name)+'.npy'
        print("""
        ---> moving the old data to the temporary file directory as: "%s" [...]
        """ % temp)
        shutil.move(os.path.join(args.session, 'NIdaq.npy'), temp)
        print('applying changes [...]')
        data[args.type][args.channel,:] = data1[args.type][args.channel,:len(data[args.type][args.channel,:])]
        np.save(os.path.join(args.session, 'NIdaq.npy'), data)
        print('done !')

    else:
        print('--> data update aborted !! ')
Example #43
0
def random_tensor(shape=None,
                  sparsity=0.5,
                  seed=1234,
                  distributed='normal',
                  normal=None,
                  uniform=None,
                  plot=True):
    np.random.seed(seed)
    tensor_size = prod(shape)
    if distributed == 'normal':
        mean, std = normal
        data = np.random.normal(mean, std, tensor_size)

        if plot == True:
            n, bins, patches = plt.hist(data,
                                        30,
                                        normed=True,
                                        facecolor='blue',
                                        alpha=0.5)
            y = mlab.normpdf(bins, mean, std)
            plt.plot(bins, y, 'r--')
            plt.xlabel('Expectation')
            plt.ylabel('Probability')
            plt.title('Histogram of Normal Distribution:$\mu =' + str(mean) +
                      '$, $\sigma=' + str(std) + '$')
            plt.axvline(norm.ppf(sparsity) * std + mean)
            plt.show()

        data[data <= norm.ppf(sparsity) * std + mean] = 0

    if distributed == 'uniform':
        low, high = uniform
        data = np.random.uniform(low, high, size=tensor_size)

        if plot == True:
            n, bins, patches = plt.hist(data,
                                        30,
                                        normed=True,
                                        facecolor='blue',
                                        alpha=0.5)
            plt.xlabel('Expectation')
            plt.ylabel('Probability')
            plt.title('Histogram of Uniform Distribution:$low =' + str(low) +
                      '$, $high =' + str(high) + '$')
            plt.axvline((high - low) * sparsity)
            plt.show()

        data[data <= (high - low) * sparsity] = 0

    return tensor(data.reshape(shape))
Example #44
0
def filter_show(filters, nx=8, margin=3, scale=10):
    FN, C, FH, FW = filters.shape
    ny = int(np.ceil(FN / nx))
    fig = plt.figure()
    fig.subplots_adjust(left=0,
                        right=1,
                        bottom=0,
                        top=1,
                        hspace=0.05,
                        wspace=0.05)

    for i in range(FN):
        ax = fig.add_subplot(ny, nx, i + 1, xticks=[], yticks=[])
        ax.imshow(filters[i, 0], cmap=plt.cm.gray_r, interpolation='nearest')
    plt.show()
Example #45
0
def time_test():
    t = []
    draw_one_laser_with_obs_vec = np.vectorize(draw_one_laser_with_obs)
    delta = [j / 18 * np.pi for j in range(36)]
    for i in range(1500):
        t1 = time()
        draw_laser(ax)  # for迭代
        # draw_one_laser_with_obs_vec(ax, delta) #  向量化
        t2 = time()
        t.append(t2 - t1)

    del t[np.argmax(t)]
    print(" sum:{:.5f}\n avg:{:.15f}\n min:{:.5f}\n max:{:.5f}\n".format(
        sum(t), np.average(t), min(t), max(t)))
    plt.show()
Example #46
0
    def showMagPhasePlot(self, t, x):
        mag = absolute(x)
        phase = angle(x)
    
        plt.subplot(211)
        plt.plot(t, mag)
        plt.ylabel('Magitude')
        plt.title('SSPF Sequence')
        plt.grid(True)

        plt.subplot(212)
        plt.plot(t, phase)
        plt.xlabel('Off-Resonance (Hz)')
        plt.ylabel('Phase')
        plt.grid(True)
        plt.show()
Example #47
0
def phasemov():

    parr=np.linspace(0,2*pi,30)
    for i in range(len(parr)):
        f,t = keptoy.lightcurve(s2n=1000,P=10.,phase=parr[i])

        nf,fmin,df,nb,qmi,qma,n = pbls.blsinit(t,f,nf=1000)
        p,farr,ph = blsw.blswph(t,f,nf,fmin,df,nb,qmi,qma,n)
        p2d(p,farr,ph)

        f = plt.gcf()
        f.text(0.8,0.7, "EEBLS Phase %.2f" % (parr[i]) ,ha="center",
               bbox=dict(boxstyle="round", fc="w", ec="k"))
        f.savefig('frames/ph%02d.png' % i)
        
        plt.show()
Example #48
0
    def drawSurfacePlot(self, f1):
        """
            Method to draw a surface plot for test spec
            using Word Rank | Tf-Idf Score | PI

        """
        test_doc = {}
        f1.next()
        for row in f1:
            test_doc[row[0]] = [row[1], row[2]]
        sorted_test_doc = sorted(test_doc.items(),
                                 key=lambda e: e[1][0],
                                 reverse=True)

        word_rank = []
        PI_list = []
        tf_idf_list = []

        for i, word in enumerate(sorted_test_doc):
            word_rank.append(i + 1)
            PI_list.append(word[1][0])
            tf_idf_list.append(word[1][1])

        PI_list = [float(pi) for pi in PI_list]
        tf_idf_list = [float(tf_idf) for tf_idf in tf_idf_list]
        fig = plt.figure()
        ax = Axes3D(fig)
        X = word_rank
        X_clone = word_rank
        Y = tf_idf_list
        X, Y = np.meshgrid(X, Y)
        print X
        # Z should be a function of X and Y
        Z = PI_list
        X_clone, Z = np.meshgrid(X_clone, Z)
        ax.plot_surface(X,
                        Y,
                        Z,
                        rstride=10,
                        cstride=10,
                        cmap=plt.cm.RdBu,
                        alpha=None)
        #ax.contour(X, Y, Z, zdir='x', offset=-4, cmap=cm.hsv)
        #ax.contour(Y, Y, Z, zdir='y', offset=4, cmap=cm.hsv)
        #ax.contour(Y, Y, Z, zdir='z', offset=-2, cmap=cm.hsv)
        #ax.set_zlim(0, 1)
        plt.show()
Example #49
0
def phasemov():
    ph=linspace(0,2*pi,30)
    for i in range(len(ph)):
        f,t = keptoy.lightcurve(s2n=1000,P=10.,phase=ph[i])

        nf,fmin,df,nb,qmi,qma,n = pbls.blsinit(t,f,nf=1000)
        p = blswph(t,f,nf,fmin,df,nb,qmi,qma,n)
        f = plt.gcf()
        f.clf()
        ax = f.add_subplot(111)
        ax.imshow(p,aspect='auto')

        ax.set_xlabel('bin number of start of transit')
        ax.set_ylabel('frequency')
        ax.set_title('2D BLS spectrum - phase %.2f' % ph[i])
        f.savefig('frames/ph%02d.png' % i)

        plt.show()
Example #50
0
def perfind():
    """
    Test how good the KS test is at descriminating a real planet from
    a none.    
    """

    P = 200.
    tbase = 1000.
    nf = 500

    s2n = logspace( log10(3),log10(15),5 )
    print "S/N sig-noise noise-noise" 
    for s in s2n:
        # Generate a lightcurve.
        f,t = keptoy.lightcurve(P=P,tbase=tbase,s2n=s)
        o = blsw.blswrap(t,f,nf=nf,fmax=1/50.)

        # Generate a null lightcurve
        fn = std(f)*random.randn(len(f))
        on = blsw.blswrap(t,fn,nf=nf,fmax=1/50.)

        # Generate another null lightcurve
        fn2 = std(f)*random.randn(len(f))
        on2 = blsw.blswrap(t,fn2,nf=nf,fmax=1/50.)

        o['p'] -= median_filter(o['p'],size=200)
        on['p'] -= median_filter(on['p'],size=200)
        on2['p'] -= median_filter(on2['p'],size=200)
        
        print "%.2f %.2e %.2e %.2f" % \
            (s,(ks_2samp(o['p'],on['p']))[1],(ks_2samp(o['p'],on2['p']))[1],
             o['parr'][argmax(o['p'])])
        

        fig = plt.gcf()
        fig.clf()
        ax = fig.add_subplot(111)
        ax.plot(o['parr'],o['p'],label='Signal')
        ax.plot(o['parr'],on['p'],label='Noise')        
        ax.plot(o['parr'],on2['p'],label='Noise2')
        ax.legend()
        plt.show()
Example #51
0
def visualize(img, G, vertices):
    plt.imshow(img, cmap='gray')

    # draw edges by pts
    for (s, e) in G.edges():
        vals = flatten([[v] for v in G[s][e].values()])
        for val in vals:
            ps = val.get('pts', [])
            plt.plot(ps[:, 1], ps[:, 0], 'green')

    # draw node by o
    node, nodes = G.node(), G.nodes
    # deg = G.degree
    # ps = np.array([node[i]['o'] for i in nodes])
    ps = np.array(vertices)
    plt.plot(ps[:, 1], ps[:, 0], 'r.')

    # title and show
    plt.title('Build Graph')
    plt.show()
Example #52
0
def blocks(t,f,last,val):
    """
    Plot lines for the Bayesian Blocks Algorithm
    """

    fig = plt.gcf()
    fig.clf()
    ax = fig.add_subplot(111)

    ax.plot(t,f,'o',ms=1,alpha=0.5)

    cp = unique(last)
    n = len(t)
    idxlo = cp                    # index of left side of region
    idxhi = append(cp[1:],n)-1 # index of right side of region 

    ax.hlines(val[idxhi],t[idxlo],t[idxhi],'red',lw=5)
    ax.set_xlabel('Time (days)')
    ax.set_ylabel('Flux (normalized)')

    plt.show()
Example #53
0
def ncp(s2n):
    """
    Explore the output of BB as we change the prior on the number of
    change points
    """
    
    nncp = logspace(0.5,1.5,9)
    
    f,t = keptoy.lightcurve(s2n=s2n)
    sig = zeros(len(t)) + std(f)

    for i in range( len(nncp) ):
        last,val = find_blocks.pt( t,f,sig,ncp=nncp[i] )
        blocks(t,f,last,val)
        
        ax = plt.gca()
        ax.set_title('s2n - %.1e, cpts prior - %.2e' % (s2n,nncp[i]) )
        fig = plt.gcf()

        fig.savefig('frames/s2n-%.1e_%02d.png' % (s2n,i) )
        plt.show()
Example #54
0
    def drawSurfacePlot(self, f1):
        """
            Method to draw a surface plot for test spec
            using Word Rank | Tf-Idf Score | PI

        """
        test_doc = {}
        f1.next()
        for row in f1:
            test_doc[row[0]] = [row[1], row[2]]
        sorted_test_doc = sorted(test_doc.items(), key=lambda e: e[1][0], reverse=True)

        word_rank = []
        PI_list = []
        tf_idf_list = []

        for i, word in enumerate(sorted_test_doc):
            word_rank.append(i + 1)
            PI_list.append(word[1][0])
            tf_idf_list.append(word[1][1])

        PI_list = [float(pi) for pi in PI_list]
        tf_idf_list = [float(tf_idf) for tf_idf in tf_idf_list]
        fig = plt.figure()
        ax = Axes3D(fig)
        X = word_rank
        X_clone = word_rank
        Y = tf_idf_list
        X, Y = np.meshgrid(X, Y)
        print X
        # Z should be a function of X and Y
        Z = PI_list
        X_clone, Z = np.meshgrid(X_clone, Z)
        ax.plot_surface(X, Y, Z, rstride=10, cstride=10, cmap=plt.cm.RdBu, alpha=None)
        #ax.contour(X, Y, Z, zdir='x', offset=-4, cmap=cm.hsv)
        #ax.contour(Y, Y, Z, zdir='y', offset=4, cmap=cm.hsv)
        #ax.contour(Y, Y, Z, zdir='z', offset=-2, cmap=cm.hsv)
        #ax.set_zlim(0, 1)
        plt.show()
Example #55
0
def SSFP():
    T1 = 800*10**-3
    T2 = 100*10**-3
    a = pi/2
    Tr = .01
    t = np.linspace(0, Tr, 100)
    M = np.array([0,0,1])
    R = np.array([[1, 0, 0], [0, cos(a), sin(a)], [0, -sin(a), cos(a)]])

    Mx = []
    My = []
    Mz = []

    Nr = 10
    for n in range(Nr):

        # Initalize and Rotate
        M = R.dot(M)
        # T1/T2 Relaxationq
        M_z = 1 + (M[2] - 1) * np.exp(-t/T1)
        M_x = M[0]*np.exp(-t/T2)
        M_y = M[1]*np.exp(-t/T2)
        M_xy = np.sqrt(M_x*M_x + M_y*M_y)
        M[0] = M_x[-1]
        M[1] = M_y[-1]
        M[2] = M_z[-1]

        Mx = np.append(Mx, M_x)
        My = np.append(My, M_y)
        Mz = np.append(Mz, M_z)

    tnew = np.linspace(0, 10*Tr, 1000)
    plt.subplot(131)
    plt.plot(tnew, Mx)
    plt.subplot(132)
    plt.plot(tnew, My)
    plt.subplot(133)
    plt.plot(tnew, Mz)
    plt.show()
Example #56
0
    def saveWaterFatImage(self, filename):
        mag = np.absolute(self.water).astype('float')
        phase = np.angle(self.water).astype('float')
        mag2 = np.absolute(self.fat).astype('float')
        phase2 = np.angle(self.fat).astype('float')

        plt.subplot(221)
        plt.imshow(mag, cmap=cm.Greys_r)
        plt.title('Water Magnitude')
        plt.axis('off')
        plt.subplot(222)
        plt.imshow(phase, cmap=cm.Greys_r)
        plt.title('Water Phase')
        plt.axis('off')
        plt.subplot(223)
        plt.imshow(mag2, cmap=cm.Greys_r)
        plt.title('Fat Magnitude')
        plt.axis('off')
        plt.subplot(224)
        plt.imshow(phase2, cmap=cm.Greys_r)
        plt.title('Fat Phase')
        plt.axis('off')
        plt.show()
def getGraph():
    for i, clf in enumerate((svm, rbf_svc, rbf_svc_tunning)):
     # Se grafican las fronteras 
     plt.subplot(2, 2, i + 1)
     plt.subplots_adjust(wspace=0.4, hspace=0.4)
    
     Z = clf.predict(np.c_[x_matrizSetEntrenamientoVect, y_clases])
    
     #Color en las gráficas
     Z = Z.reshape(x_matrizSetEntrenamientoVect.shape)
     plt.contourf(x_matrizSetEntrenamientoVect, y_clases, Z, cmap=plt.cm.Paired, alpha=0.8)
    
     #Puntos de entrenamiento
     plt.scatter(x_matrizSetEntrenamientoVect[:, 0], x_matrizSetEntrenamientoVect[:, 1], c=y_clases, cmap=plt.cm.Paired)
     plt.xlabel('Longitud Sepal')
     plt.ylabel('Peso Sepal')
     plt.xlim(x_matrizSetEntrenamientoVect.min(), x_matrizSetEntrenamientoVect.max())
     plt.ylim(y_clases.min(), y_clases.max())
     plt.xticks(())
     plt.yticks(())
     plt.title(titles[i])
    
    plt.show()
Example #58
0
    def surfMagnitudePhaseImage(self, image):
        import numpy as np
        
        X = np.linspace(-1, 1, 64)
        Y = np.linspace(-1, 1, 64)
        X, Y = np.meshgrid(X, Y)
        mag = absolute(image).astype('float')
        phase = angle(image).astype('float')

        
        fig = plt.figure()
        ax = fig.add_subplot(211, projection='3d')
        Z = mag
        surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,
                               linewidth=0, antialiased=True)
        ax.set_zlim3d(np.min(Z), np.max(Z))
        fig.colorbar(surf)
        ax = fig.add_subplot(212, projection='3d')
        Z = phase
        surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,
                               linewidth=0, antialiased=True)
        ax.set_zlim3d(np.min(Z), np.max(Z))
        fig.colorbar(surf)
        plt.show()
def test_1():
	d = pkunit.data_dir()
	## Testing actual SRW calculations 
	
	##Reading SRW data SPECTRUM
	IFileName="Spectrum.txt"
	f=open(str(d.join(IFileName)),"r")#,1000)
	e_p=[]
	I_rad=[]
	for line in f.readlines():
	    words = line.split()
	    e_p.append(words[0])
	    I_rad.append(words[1])	
	I_radf=map(float,I_rad)
	maxI=max(I_radf)
	pkdc(I_radf)
	print('Spectral Amplitude, ph/s/mrad2',maxI)
	pkdc(I_radf.index(max(I_radf)))
	maxIn=maxelements(I_radf)
	(maxV, maxI)=FindingArrayMaxima(I_radf,5)
	print(maxI, maxV)
	f.close()

	##Reading SRW data TRAJECTORY
	IFileName="Trajectory.txt"
	f=open(str(d.join(IFileName)),"r")#,10000)
	z_dist=[]
	x_traj=[]
	for line in f.readlines():
	    words = line.split()
	    z_dist.append(words[0])
	    x_traj.append(words[1])
	x_trajectory=map(float, x_traj)
	z_distance=map(float, z_dist)
	minX=min(x_trajectory)
	maxX=max(x_trajectory)
	minZ=min(z_distance)
	maxZ=max(z_distance)
	print ('Length of ID, m', maxZ-minZ)
	print('Oscillation Amplitude, mm',(maxX-minX)/2)
	L_trajectory=Path_Length(z_distance, x_trajectory)
	print('Length of Trajectory, m', L_trajectory)
	f.close()

	##Plotting
	plot(e_p,I_rad)
	j=0
	for i in maxI:
		plt.scatter(e_p[i], maxV[j], color='red')
		j=j+1
	#    title(TitleP)
	#    xlabel(Xlab)
	#    ylabel(Ylab)
	
	grid()
	plt.show()
	plot(z_dist,x_trajectory,'.b',linestyle="-")
	(maxVt, maxIt)=FindingArrayMaxima(map(float,x_trajectory),20)
	pkdc(maxIt, maxVt)
	j=0
	for i in maxIt:
		plt.scatter(z_dist[i], maxVt[j], color='red')
		j=j+1
	grid()
	plt.show()
Example #60
0
# Allocate memory
u = copy.deepcopy(u0)
v = copy.deepcopy(v0)
h = copy.deepcopy(h0)

# Prepare plotting
if plot_progress:
    fig = plt.figure(1)
    ax = fig.add_subplot(111, projection="3d")
    # plt.clf()
    # plt.grid(True)
    plt.ion()
    plt.hold(False)
    plt.draw()
    plt.show()

# Measurement
h_meas = []

# Simulate once to generate "measurements"
for k in range(num_measurements):
    # Visualize the pool
    if plot_progress:
        # plt.ioff()
        # print h[::numboxes_per_plot]
        ax.cla()
        surf = ax.plot_surface(
            X[::numboxes_per_plot],
            Y[::numboxes_per_plot],
            h[::numboxes_per_plot],