コード例 #1
0
ファイル: FemVisualization.py プロジェクト: Marko-Petek/Fluid
        alpha=0.85,
        antialiased=True)


def AddGaussiansToAxes(ax, x, y, x0s, y0s, stds, strides, cmaps):
    for i in range(len(x0s)):
        AddGaussianToAxes(ax, x, y, x0s[i], y0s[i], stds[i], strides[i],
                          cmaps[i])


#%%
fig = Plt.figure(num=0, figsize=(6, 6), dpi=72)
axes3d = fig.gca(projection='3d', xlim=(0, 100), ylim=(0, 100))
axes3d.set_proj_type('ortho')
axes3d.view_init(40, 45)
axes3d.xaxis.set_major_locator(LinearLocator(5))  # Remove ticks.
axes3d.yaxis.set_major_locator(LinearLocator(5))
axes3d.zaxis.set_major_locator(LinearLocator(3))
x = np.arange(0, 100, 0.25)
y = np.arange(0, 100, 0.25)
(x, y) = np.meshgrid(x, y)
centralNodes = [nodes[5], nodes[6], nodes[9],
                nodes[10]]  # Plot Gaussians on top of four middle nodes.
centralNodesT = Transpose(centralNodes)
stds = [20.0, 12.0, 16.0, 24.0]  # Standard deviations of node functions.
strides = [5, 3, 4, 6]
cmaps = [
    cm.get_cmap('Blues', 20),
    cm.get_cmap('Reds', 20),
    cm.get_cmap('Greens', 20),
    cm.get_cmap('Purples', 20)
コード例 #2
0
Y = np.arange(1, 203, 1)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = R

infile=open("out_serial","r")
data=infile.readlines()
k=0
for d in data[1:] :
	d=d.split()
	j=0
	for v in d:
		Z[j][k]=float(v)
		j=j+1
	k=k+1


surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.rainbow,
                       linewidth=0, antialiased=False)
#ax.set_zlim(0,256)
ax.set_zlim(0,0.5e8)

ax.zaxis.set_major_locator(LinearLocator(11))
#ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
ax.zaxis.set_major_formatter(FormatStrFormatter('%3.2e'))

fig.colorbar(surf, shrink=0.5, aspect=5)

#plt.show()
plt.savefig("out_serial"+".png")
コード例 #3
0
def sample_histograms(
        input_sample,
        names,
        levels,
        outpath,
        outname,
        param_dict,
        plot_cfg=None  # type: PlotConfig
):
    """Plot histograms as subplot.

    Args:
        input_sample:
        names:
        levels:
        outpath:
        outname:
        param_dict:
        plot_cfg:

    Returns:
        subplot list.
    """
    fig = plt.figure()
    if plot_cfg is not None:
        plt.rcParams['font.family'] = plot_cfg.font_name
    num_vars = len(names)
    row, col = cal_row_col_num(num_vars)
    for var_idx in range(num_vars):
        ax = fig.add_subplot(row, col, var_idx + 1)
        print('%s: %.3f - %.3f, mean: %.3f' %
              (names[var_idx], min(
                  input_sample[:, var_idx]), max(input_sample[:, var_idx]),
               numpy.average(input_sample[:, var_idx])))
        ax.hist(input_sample[:, var_idx],
                bins=levels,
                density=False,
                label=None,
                **param_dict)
        ax.get_yaxis().set_major_locator(LinearLocator(numticks=5))
        ax.get_xaxis().set_major_locator(LinearLocator(numticks=5))
        ax.set_title('%s' % (names[var_idx]), fontsize=plot_cfg.title_fsize)
        ax.tick_params(
            axis='x',  # changes apply to the x-axis
            which='both',  # both major and minor ticks are affected
            bottom=True,  # ticks along the bottom edge are off
            top=False,  # ticks along the top edge are off
            labelbottom=True  # labels along the bottom edge are off
        )
        ax.tick_params(
            axis='y',  # changes apply to the y-axis
            which='major',  # both major and minor ticks are affected
            length=3,
            right=False)
        if var_idx % col:  # labels along the left edge are off
            ax.tick_params(axis='y', labelleft=False)
    plt.tight_layout()
    save_png_eps(plt, outpath, outname, plot_cfg)
    # close current plot in case of 'figure.max_open_warning'
    plt.cla()
    plt.clf()
    plt.close()
コード例 #4
0
def plot_surface_width_noise(width,noise):

    a,m = np.meshgrid(width,noise)
    aa = a.flatten()
    mm = m.flatten()
    
    target_norm = norm.pdf(range(0,400),200,40)
    target_norm = np.random.normal(target_norm, scale=0)
    len_target = target_norm.shape[0] - 2
    window = 1000
    euc = []
    init_euc = []
    background = 0
    GM = []
    
    for mesh in zip(aa, mm):
        np.random.seed(0)
        global_norm = 1*norm.pdf(range(0,400),200,mesh[0])
        global_norm = np.random.normal(global_norm, scale=0*mesh[1])
        global_Maxx = max(abs(global_norm))
        GM.append(global_Maxx)
        
    global_max = max(GM)    
    
    ii = 0
    
    for mesh in zip(aa, mm):
        np.random.seed(0)
        euclidean, init_euclidean = test(1,200,mesh[0],mesh[1],background,target_norm,len_target,window,global_max,ii)
        euc.append(euclidean)
        init_euc.append(init_euclidean.sum()) 
        ii = ii + 1
    
    euc = np.array(euc)
    
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    
    # Make data.
    X = a
    Y = m
    Z = euc.reshape(len(noise),len(width))
    
    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z, cmap='hot_r',
                           linewidth=0, antialiased=False)
    
    # Customize the z axis.
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.set_xlabel('standard deviation')
    ax.set_ylabel('noise')
    ax.set_zlabel('exponential correction')
    
    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5, label='exponential correction')
    
    plt.show()  
    
    
    
    
    C = ['#000000','#FF0000','#FFFF00','#008000','#0000FF','#FF00FF','#C0C0C0','#800000','#808000','#00FFFF','#800080','#808080','#00FF00','#008080','#000080']

    
    objects = ['5','10','15','20','25','30','35','40','45','50','55','60','65','70','75']
    
    y_pos = np.arange(len(objects))
    
    performance = np.ones(15)
    
    
    plt.figure(1)
    plt.bar(y_pos,performance,align='center',color=C)
    plt.xticks(y_pos,objects)
    plt.xlabel('standard deviation')
    plt.title('Colour Key')
コード例 #5
0
        ax1 = fig.add_subplot(2, 2, 1, projection='3d')

        surf = ax1.plot_surface(X,
                                Y,
                                Z2,
                                rstride=1,
                                cstride=1,
                                cmap=cm.coolwarm,
                                linewidth=0,
                                antialiased=False)
        ax1.scatter(X, Y, Z, c='r', marker='^')
        ax1.set_zlim(-5.01, 5.01)
        ax1.set_title("fitted surface PolyFit2D")

        ax1.zaxis.set_major_locator(LinearLocator(10))
        ax1.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

        ax2 = fig.add_subplot(2, 2, 3, projection='3d')

        surf = ax2.plot_surface(X,
                                Y,
                                Z3,
                                rstride=1,
                                cstride=1,
                                cmap=cm.coolwarm,
                                linewidth=0,
                                antialiased=False)
        ax2.scatter(X, Y, Z, c='r', marker='^')
        ax2.set_zlim(-5.01, 5.01)
        ax2.set_title("fitted surface PolyFitND")
コード例 #6
0
ファイル: show_directions.py プロジェクト: jiaojiashuang/RPN
vname_to_clevs = {
    FACC: [10 ** p for p in range(1, 8)],
    LAKE_FRACTION: np.arange(0, 1.1, 0.1)
}


vname_to_units = {
    FACC: r"km$^2$",
    LAKE_FRACTION: ""

}

vname_to_cbar_ticks = {
    FACC: LogLocator(),
    LAKE_FRACTION: LinearLocator(),
}



def format_ticks_ten_pow(x, pos):
    return r"10$^{{{:.0f}}}$".format(np.log10(x))

vname_to_cbar_format = {
    FACC: FuncFormatter(format_ticks_ten_pow),
    LAKE_FRACTION: None
}


@main_decorator
def main():
コード例 #7
0
fig = plt.figure()
ax = fig.gca(projection='3d')
X = numpy.arange(-5, 5, 0.1)
Y = numpy.arange(-5, 5, 0.1)
X, Y = numpy.meshgrid(X, Y)
Z = numpy.sin(X) * numpy.sin(Y) + 0.2 * X

colortuple = ('w', 'b')
colors = numpy.empty(X.shape, dtype=str)
for x in range(len(X)):
    for y in range(len(Y)):
        colors[x, y] = colortuple[(x + y) % 2]

surf = ax.plot_surface(X,
                       Y,
                       Z,
                       rstride=1,
                       cstride=1,
                       facecolors=colors,
                       linewidth=0)

ax.set_xlim3d(-5, 5)
ax.set_ylim3d(-5, 5)
ax.set_zlim3d(-2, 2)
ax.w_xaxis.set_major_locator(LinearLocator(3))
ax.w_yaxis.set_major_locator(LinearLocator(3))
ax.w_zaxis.set_major_locator(LinearLocator(3))

plt.show()
コード例 #8
0
ファイル: Illustrations.py プロジェクト: zk20/AUVResearch
def showoptimalcontrol(path, show=False):  # model scheme with basic notation
    fig = plt.figure(figsize=(10, 6), dpi=200)
    ax = fig.gca(projection='3d')
    ax.view_init(31, 26)

    # set good viewpoint
    drawPoint(ax, [1.1, 1.1, 1.1], color='white', s=0)

    s = 0.1
    XNk = np.array([0.5, 0.3, 0.5])
    XNk1 = np.array([0.2, 0.7, 0.8])
    Xk = np.array([0.7, 0.5, 0.2])

    #points
    drawPoint(ax, XNk)
    drawPoint(ax, XNk1)
    drawPoint(ax, Xk)
    textAtPoint(ax, XNk, '$\mathring{\mathbf{X}}_k$', [0, 0, s])
    textAtPoint(ax, XNk1, '$\mathring{\mathbf{X}}_{k+1}$', [0, 0, s])
    textAtPoint(ax, Xk, '${\mathbf{X}}_{k}$', [0, -s, -s])

    #XNk1 projections
    drawLine(ax, XNk1, PZ(XNk1), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(XNk1), Y(XNk1), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(XNk1), X(XNk1), linestyle=':', linewidth=0.5)

    #Xk projections
    drawLine(ax, Xk, PZ(Xk), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(Xk), Y(Xk), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(Xk), X(Xk), linestyle=':', linewidth=0.5)

    #Xk to XNk1 and projections
    drawLine(ax, PZ(Xk), PZ(XNk1), linestyle=':', linewidth=0.5)
    drawLine(ax, Xk, [XNk1[0], XNk1[1], Xk[2]], linestyle=':', linewidth=0.5)
    drawLine(ax, 0.5 * (Xk + XNk1), XNk1, linestyle=':', linewidth=0.5)

    #deltas
    drawLine(ax, PZ(Xk), [Xk[0], XNk1[1], 0], linestyle='-', linewidth=0.5)
    drawLine(ax, PZ(XNk1), [Xk[0], XNk1[1], 0], linestyle='-', linewidth=0.5)
    drawLine(ax, XNk1, [XNk1[0], XNk1[1], Xk[2]], linestyle='-', linewidth=0.5)
    textAtPoint(ax, [0.7 * Xk[0] + 0.3 * XNk1[0], XNk1[1], 0.0],
                '$\Delta \mathring{X}_k + \Delta t \mathring{V}^X_k$',
                [0.0, s, 0.0])
    textAtPoint(ax, [Xk[0], 0.8 * Xk[1] + 0.2 * XNk1[1], 0.0],
                '$\Delta \mathring{Y}_k + \Delta t \mathring{V}^Y_k$',
                [2.0 * s, 0.0, -0.5 * s])
    textAtPoint(ax, [XNk1[0], XNk1[1], 0.5 * Xk[2] + 0.5 * XNk1[2]],
                '$\Delta \mathring{Z}_k + \Delta t \mathring{V}^Z_k$',
                [0.0, 0.5 * s, 0.0])

    #vectors
    drawArrow(ax, Xk, XNk)
    drawArrow(ax, XNk, XNk1)
    drawArrow(ax, Xk, 0.5 * (Xk + XNk1))
    textAtPoint(ax, 0.5 * (Xk + XNk1), '${\mathbf{V}}_k^*$',
                [0.0, -0.5 * s, 0.0])

    #angles
    drawArcScale(ax, Xk, XNk1, [XNk1[0], XNk1[1], Xk[2]], scale=0.10)
    textAtPoint(ax, Xk, '$\gamma^*_k$', [0.0, s, 0.0])

    drawArcScale(ax, [XNk1[0], XNk1[1], 0.0], [Xk[0], Xk[1], 0.0],
                 [Xk[0], XNk1[1], 0.0],
                 scale=0.15)
    drawArcScale(ax, [XNk1[0], XNk1[1], 0.0], [Xk[0], Xk[1], 0.0],
                 [Xk[0], XNk1[1], 0.0],
                 scale=0.18)
    textAtPoint(ax, PZ(XNk1), '$\\theta^*_k$', [1.5 * s, -s, 0])

    #axes
    drawArrow(ax, [-0.01, 0.0, 0.0], [1.0, 0.0, 0.0])
    drawArrow(ax, [0.0, -0.01, 0.0], [0.0, 1.0, 0.0])
    drawArrow(ax, [0.0, 0.0, -0.01], [0.0, 0.0, 1.0])
    textAtPoint(ax, [1.0, 0.05, 0.0], '$x$')
    textAtPoint(ax, [0.1, 1.0, 0.0], '$y$')
    textAtPoint(ax, [0.05, 0.05, 1.0], '$z$')

    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.set_axis_off()
    fig.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig(path)
コード例 #9
0
def demo_run(t):
    ########################################
    #### MLP - Function approximation  #####
    ########################################

    n_hidden = t
    split = 0.6

    # hidden_nodes = [1, 2, 3, 5, 8, 10, 15, 20, 22, 25, 100]
    # hidden_nodes = list(range(1, 25 + 1)) + [100]
    hidden_nodes = [n_hidden]
    # eta_values = [0.002, 0.005, 0.01, 0.05, 0.1, 0.25, 1, 10]
    eta_values = [0.25, 0.5]
    epochs = 1000  # max number of epochs
    early_stop = 400000000  # no early stopping
    batch = True
    shuffle = False
    loops = 4
    debug = True
    momentum = 0
    show_plots = False

    step = 0.25
    np.random.seed(72)
    x = np.arange(-5, 5, step)
    y = np.arange(-5, 5, step)
    x, y = np.meshgrid(x, y)
    z = np.exp(-(x**2 + y**2) / 10) - 0.5
    xy = np.concatenate((x.reshape(-1, 1), y.reshape(-1, 1)), axis=1)
    dataset = xy.copy(), z.reshape(-1, 1).copy()

    n = dataset[0].shape[0]
    shuffler = np.random.permutation(n)
    shuffled_dataset = dataset[0][shuffler], dataset[1][shuffler]
    train = shuffled_dataset[0][0:int(n * split
                                      )], shuffled_dataset[1][0:int(n * split)]
    # valid = shuffled_dataset[0][int(n * split):], shuffled_dataset[1][int(n * split):]
    valid = shuffled_dataset

    metrics = ["pocket_epoch", "train_loss", "valid_loss"]

    i = 100
    batch_size = train[0].shape[0] if batch else 1
    results = {}  # results[n_hidden][eta][metric]
    for n_hidden_nodes in hidden_nodes:
        print(f"x-----> {n_hidden_nodes} hidden nodes <-----x")
        results[n_hidden_nodes] = {}
        for eta in reversed(eta_values):
            print(f"ETA is {eta}")
            results[n_hidden_nodes][eta] = {}
            accumulated_metrics = {}
            for m in metrics:
                accumulated_metrics[m] = []
            print(f"Loop starting. {loops} loops left to go.")
            for loop_idx in range(loops):
                name = f"MLP{i:05}_GAUSS" \
                       f"_h-{n_hidden_nodes}" \
                       f"_eta-{eta}" \
                       f"_b-{batch_size}{'' if momentum == 0 else 'momentum:' + str(momentum)}".replace(".", ",")
                i += 1
                print(name)
                net = MLP(train[0],
                          train[1],
                          n_hidden_nodes,
                          momentum=momentum,
                          outtype="linear")
                train_losses, valid_losses, _, _, pocket_epoch = net.train(
                    train[0],
                    train[1],
                    valid[0],
                    valid[1],
                    eta,
                    epochs,
                    early_stop_count=early_stop,
                    shuffle=shuffle,
                    batch_size=batch_size)
                train_loss, valid_loss = train_losses[
                    pocket_epoch], valid_losses[pocket_epoch]
                print(f"pocket epoch: {pocket_epoch}\n"
                      f"train_loss:{train_loss}\n"
                      f"valid_loss:{valid_loss}")
                for m in metrics:
                    accumulated_metrics[m].append(locals()[m])
                if debug:

                    save_prefix = os.path.join(save_folder,
                                               str(n_hidden_nodes))
                    ensure_dir(save_prefix)
                    save_prefix = os.path.join(save_prefix, str(eta))
                    ensure_dir(save_prefix)
                    save_prefix = os.path.join(save_prefix, str(batch_size))
                    ensure_dir(save_prefix)
                    save_prefix = os.path.join(save_prefix, name)

                    fig, ax1 = plt.subplots()
                    plt.title(name + " Learning curve")
                    x_values = np.arange(len(train_losses))
                    ax1.set_xlabel('Epoch')
                    ax1.set_ylabel('Log MSE loss')
                    ax1.plot(x_values,
                             np.log(train_losses),
                             color='tab:red',
                             label="Training loss",
                             linewidth=2)
                    ax1.plot(x_values,
                             np.log(valid_losses),
                             color='tab:orange',
                             label="Validation loss")
                    ax1.scatter(pocket_epoch,
                                np.log(valid_loss),
                                color="green")
                    ax1.tick_params(axis='y')
                    fig.legend(bbox_to_anchor=(0.85, 0.7), loc="upper right")
                    plt.savefig(f"{save_prefix}_learning_curve.png", dpi=300)
                    if show_plots:
                        plt.show()
                    plt.close()

                    def f(inputs):
                        net.forward(inputs)
                        n = np.int(np.sqrt(inputs.shape[0]))
                        return net.outputs.reshape((n, n))

                    fig = plt.figure()
                    ax = fig.gca(projection='3d')
                    surf = ax.plot_surface(x,
                                           y,
                                           f(xy),
                                           cmap=cm.coolwarm,
                                           linewidth=0,
                                           antialiased=False,
                                           alpha=0.8)

                    # Customize the z axis.
                    ax.set_zlim(-1.01, 1.01)
                    ax.zaxis.set_major_locator(LinearLocator(10))
                    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

                    # Add a color bar which maps values to colors.
                    fig.colorbar(surf, shrink=0.5, aspect=5)
                    plt.savefig(f"{save_prefix}_function_approx.png", dpi=300)
                    if show_plots:
                        plt.show()
                    plt.close()

            print("\n\n")
            for m in metrics:
                results[n_hidden_nodes][eta][m] = np.array(
                    accumulated_metrics[m]).mean(), np.array(
                        accumulated_metrics[m]).std()

    results_filename = f"results m:{momentum}" \
                       f" etas:{eta_values}" \
                       f" nh:{hidden_nodes}" \
                       f" time:{datetime.datetime.now()}" \
                       f".txt"
    with open(os.path.join(save_folder, results_filename), "w") as f:
        print(
            os.path.join(save_folder,
                         "results " + str(datetime.datetime.now()) + ".txt"))
        print(results)
        f.write(f"{results_filename}\n{results}")
    print(results)
    print(".\n.\n.")

    sep = ","
    for metric in metrics:
        for metric_idx in range(2):  # 0-->mean 1-->std
            # print table name
            print(f"Metric: {metric} {'mean' if metric_idx == 0 else 'std'}")

            # first row - table header
            print("eta", end="")
            for eta in eta_values:
                print(sep + str(eta), end="")
            print()

            # other rows - one for each number of hidden nodes
            for nh in hidden_nodes:
                print(nh, end="")
                for eta in eta_values:
                    print(sep + str(results[nh][eta][metric][metric_idx]),
                          end="")
                print()
            print()
        print()
        print()
コード例 #10
0
ファイル: Illustrations.py プロジェクト: zk20/AUVResearch
def showbearing(path, show=False):  # model scheme with basic notation
    fig = plt.figure(figsize=(10, 6), dpi=200)
    ax = fig.gca(projection='3d')
    ax.view_init(31, 26)

    # set good viewpoint
    drawPoint(ax, [1.1, 1.1, 1.1], color='white', s=0)

    s = 0.1
    Xk = np.array([0.7, 0.2, 0.4])
    XB = np.array([0.2, 0.5, 0.81])
    xx = np.array([XB[0], Xk[1], 0.0])

    #points
    drawPoint(ax, Xk)
    drawPoint(ax, XB)
    textAtPoint(ax, Xk, '${\mathbf{X}}_{k}$', [0, -0.7 * s, 0.2 * s])
    textAtPoint(ax, XB, '${\mathbf{X}}_{B}$ (beacon)', [0, -0.7 * s, 0])

    #Xk projections
    drawLine(ax, Xk, PZ(Xk), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(Xk), Y(Xk), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(Xk), X(Xk), linestyle=':', linewidth=0.5)

    #XB projections
    drawLine(ax, XB, PZ(XB), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(XB), Y(XB), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(XB), X(XB), linestyle=':', linewidth=0.5)

    #Xk to XB and projections
    drawLine(ax, Xk, XB, linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(Xk), PZ(XB), linestyle=':', linewidth=0.5)
    drawLine(ax, Xk, [XB[0], XB[1], Xk[2]], linestyle=':', linewidth=0.5)

    #deltas
    drawLine(ax, PZ(Xk), xx, linestyle='-', linewidth=0.5)
    drawLine(ax, PZ(XB), xx, linestyle='-', linewidth=0.5)
    drawLine(ax, XB, [XB[0], XB[1], Xk[2]], linestyle='-', linewidth=0.5)
    textAtPoint(ax, 0.5 * (PZ(Xk) + xx), '$X_B - X_k$', [0, -1.3 * s, 0])
    textAtPoint(ax, 0.5 * (PZ(XB) + xx), '$Y_B - Y_k$', [0.0, -0.4 * s, 0])
    textAtPoint(ax, 0.5 * (PZ(XB) + XB), '$Z_B - Z_k$', [0, 0.2 * s, 1.3 * s])

    sX = np.arange(-0.1, 1.1, 1.0 / 100.0)
    sY = np.arange(-0.1, 1.05, 1.0 / 100.0)
    sX, sY = np.meshgrid(sX, sY)
    sZ = XB[2] + np.random.normal(0.0, 0.005, sX.shape)
    # Plot the surface.
    surf = ax.plot_surface(sX,
                           sY,
                           sZ,
                           cmap=cm.Blues,
                           linewidth=0,
                           antialiased=False,
                           alpha=0.1)
    ax.text(-0.1, 0.6, XB[2], 'sea surface', (0, 1, 0.1))

    #angles
    drawArcScale(ax, Xk, XB, [XB[0], XB[1], Xk[2]], scale=0.10)
    textAtPoint(ax, Xk, '$\lambda_k$', [-1.1 * s, 0.4 * s, 0.0])

    drawArcScale(ax, PZ(Xk), PZ(XB), [XB[0], Xk[1], 0], scale=0.15)
    drawArcScale(ax, PZ(Xk), PZ(XB), [XB[0], Xk[1], 0], scale=0.18)
    textAtPoint(ax, PZ(Xk), '$\\varphi_k$', [0.3 * s, 0.8 * s, 0])

    #axes
    drawArrow(ax, [-0.01, 0.0, 0.0], [1.0, 0.0, 0.0])
    drawArrow(ax, [0.0, -0.01, 0.0], [0.0, 1.0, 0.0])
    drawArrow(ax, [0.0, 0.0, -0.01], [0.0, 0.0, 1.0])
    textAtPoint(ax, [1.0, 0.05, 0.0], '$x$')
    textAtPoint(ax, [0.1, 1.0, 0.0], '$y$')
    textAtPoint(ax, [0.05, 0.05, 1.0], '$z$')

    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.set_axis_off()
    fig.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig(path)
コード例 #11
0
ファイル: Illustrations.py プロジェクト: zk20/AUVResearch
def showsonarmodel(path, show=False):  # model scheme with basic notation
    fig = plt.figure(figsize=(10, 6), dpi=200)
    ax = fig.gca(projection='3d')
    ax.view_init(31, 26)

    # set good viewpoint
    drawPoint(ax, [1.1, 1.1, 1.1], color='white', s=0)

    s = 0.1
    Xk = np.array([0.2, 0.3, 0.7])
    v = np.array([-0.05, 0.1, 0.05])
    x = np.array([0.7, 0.8, 0.2])

    #points
    drawPoint(ax, Xk)
    drawPoint(ax, x)
    textAtPoint(ax, Xk, '${\mathbf{X}}_{k}$', [0, -0.7 * s, 0])
    textAtPoint(ax, (x + Xk) * 0.5, '$L_{k}^{ij}$', [0, 0.2 * s, 0])
    textAtPoint(ax, x, '$\mathbf{x}_{k}^{ij}$', [0, 0.2 * s, 0])
    for i in range(-2, 3):
        for j in range(-2, 3):
            drawPoint(ax,
                      x + np.array([i * 0.05, j * 0.05, 0]),
                      'black',
                      10,
                      alpha=0.1)
            drawLine(ax,
                     Xk,
                     x + np.array([i * 0.05, j * 0.05, 0]),
                     'black',
                     linestyle=':',
                     linewidth=0.5,
                     alpha=0.2)

    #Xk projections
    drawLine(ax, Xk, PZ(Xk), linestyle=':', linewidth=0.5)
    drawLine(ax, [x[0], Xk[1], 0], Y(Xk), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(Xk), X(Xk), linestyle=':', linewidth=0.5)

    #x projections
    drawLine(ax, x, PZ(x), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(x), Y(x), linestyle=':', linewidth=0.5)
    drawLine(ax, PZ(x), X(x), linestyle=':', linewidth=0.5)

    #Xk to x and projections
    drawLine(ax, PZ(Xk), PZ(x), linestyle=':', linewidth=0.5)
    drawLine(ax, Xk, [x[0], x[1], Xk[2]], linestyle=':', linewidth=0.5)

    sX = np.arange(-0.1, 1.1, 1.0 / 100.0)
    sY = np.arange(-0.1, 1.05, 1.0 / 100.0)
    sX, sY = np.meshgrid(sX, sY)
    sZ = x[2] + np.random.normal(0.0, 0.005, sX.shape)
    # Plot the surface.
    surf = ax.plot_surface(sX,
                           sY,
                           sZ,
                           cmap=cm.copper,
                           linewidth=0,
                           antialiased=False,
                           alpha=0.1)
    ax.text(-0.1, 0.6, x[2], 'seabed', (0, 1, 0.1))

    #vectors
    drawArrow(ax, Xk, Xk + v)
    textAtPoint(ax, Xk + v, '${\mathbf{V}}_k^*$', [0.0, -0.5 * s, 0.0])
    drawLine(ax, Xk, x)

    #angles
    drawArcScale(ax, Xk, x, [x[0], x[1], Xk[2]], scale=0.10)
    textAtPoint(ax, Xk, '$\gamma_k + \gamma^i$', [s, s, 0.0])

    drawArcScale(ax, PZ(Xk), PZ(x), [x[0], Xk[1], 0], scale=0.15)
    drawArcScale(ax, PZ(Xk), PZ(x), [x[0], Xk[1], 0], scale=0.18)
    textAtPoint(ax, PZ(Xk), '$\\theta_k + \\theta^j$', [2.5 * s, 0.5 * s, 0])

    #axes
    drawArrow(ax, [-0.01, 0.0, 0.0], [1.0, 0.0, 0.0])
    drawArrow(ax, [0.0, -0.01, 0.0], [0.0, 1.0, 0.0])
    drawArrow(ax, [0.0, 0.0, -0.01], [0.0, 0.0, 1.0])
    textAtPoint(ax, [1.0, 0.05, 0.0], '$x$')
    textAtPoint(ax, [0.1, 1.0, 0.0], '$y$')
    textAtPoint(ax, [0.05, 0.05, 1.0], '$z$')

    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.set_axis_off()
    fig.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig(path)
コード例 #12
0
ファイル: Illustrations.py プロジェクト: zk20/AUVResearch
def shownominal3d(path,
                  nominal,
                  XB,
                  show=False):  # model scheme with basic notation
    XB = np.array(XB)
    fig = plt.figure(figsize=(10, 6), dpi=200)
    ax = fig.gca(projection='3d')
    ax.view_init(65, 57)
    ax.set_aspect('equal')

    # set good viewpoint
    #drawPoint(ax, [1.1, 1.1, 1.1], color = 'white', s = 0)

    bndX = [XB[:, 0].min() - 150, XB[:, 0].max() + 150]
    bndY = [XB[:, 1].min() - 50, XB[:, 1].max() + 50]
    bndZ = [-30, 5.0]
    dX = bndX[1] - bndX[0]
    dY = bndY[1] - bndY[0]
    dZ = bndZ[1] - bndZ[0]

    _ = ax.plot(nominal[:, 0],
                nominal[:, 1],
                nominal[:, 2],
                color='black',
                linewidth=4.0,
                alpha=0.5)

    for i in range(0, XB.shape[0]):
        drawPoint(ax, XB[i], color='blue')

    #axes
    drawArrow(ax,
              [bndX[0] - dX / 10.0, bndY[0] - dY / 20.0, bndZ[0] - dZ / 20.0],
              [bndX[1] + dX / 20.0, bndY[0] - dY / 20.0, bndZ[0] - dZ / 20.0])
    drawArrow(ax,
              [bndX[0] - dX / 20.0, bndY[0] - dY / 15.0, bndZ[0] - dZ / 20.0],
              [bndX[0] - dX / 20.0, bndY[1] + dY / 10.0, bndZ[0] - dZ / 20.0])
    drawArrow(ax,
              [bndX[0] - dX / 20.0, bndY[0] - dY / 20.0, bndZ[0] - dZ / 10.0],
              [bndX[0] - dX / 20.0, bndY[0] - dY / 20.0, bndZ[1] + dZ / 10.0])
    textAtPoint(ax, [bndX[1] + dX / 20.0, bndY[0] + dY / 20.0, bndZ[0]], '$x$')
    textAtPoint(ax, [bndX[0] + dX / 100.0, bndY[1] + dY / 10.0, bndZ[0]],
                '$y$')
    textAtPoint(ax, [bndX[0] + dX / 100.0, bndY[0], bndZ[1] + dZ / 10.0],
                '$z$')

    #seabed
    X = np.arange(bndX[0], bndX[1], dX / 100)
    Y = np.arange(bndY[0], bndY[1], dX / 100)
    X, Y = np.meshgrid(X, Y)
    Zsb = np.random.normal(-30.0, 0.2, X.shape)
    surf = ax.plot_surface(X,
                           Y,
                           Zsb,
                           cmap=cm.copper,
                           linewidth=0,
                           antialiased=False,
                           alpha=0.1)

    #surface
    Zsf = np.random.normal(0.0, 0.1, X.shape)
    surf = ax.plot_surface(X,
                           Y,
                           Zsf,
                           cmap=cm.Blues,
                           linewidth=0,
                           antialiased=False,
                           alpha=0.1)

    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.set_axis_off()
    set_axes_aspect(ax, [1.0, 1.5, 15.0])

    fig.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig(path)
コード例 #13
0
    def plot_waterfall(self, fig=None, ax=None):
        """"""
        if fig is None:
            fig, ax = plt.subplots()

        z_min = -100

        # Window
        window_duration = 0.01  # TODO
        nfft = min(int(self.fs * window_duration), int(len(self.data) / 10))
        noverlap = int(nfft * 0.9)  # 90% overlap TODO
        ascend_ms = 10  # 10 ms ascending window
        ascend = int(ascend_ms / 1000 * self.fs)
        plateu = int((nfft - ascend) * 3 / 4)  # 75%
        descend = nfft - ascend - plateu  # 25%
        window = np.concatenate([
            signal.hann(ascend * 2)[:ascend],
            np.ones(plateu),
            signal.hann(descend * 2)[descend:]
        ])

        # Crop from 10ms before peak to start of tail
        peak_ind, tail_ind, noise_floor, _ = self.decay_params()
        start = max(int(peak_ind - self.fs * 0.01), 0)
        # Stop index is greater of 1s after peak or 1 FFT window after tail
        stop = min(int(round(max(peak_ind + self.fs * 1, tail_ind + nfft))),
                   len(self.data))
        data = self.data[start:stop]

        # Get spectrogram data
        spectrum, freqs, t = specgram(data,
                                      Fs=self.fs,
                                      NFFT=nfft,
                                      noverlap=noverlap,
                                      mode='magnitude',
                                      window=window)

        # Remove 0 Hz component
        spectrum = spectrum[1:, :]
        freqs = freqs[1:]

        # Interpolate to logaritmic frequency scale
        f_max = self.fs / 2
        f_min = 10
        step = 1.03
        f = np.array([
            f_min * step**i
            for i in range(int(np.log(f_max / f_min) / np.log(step)))
        ])
        log_f_spec = np.ones((len(f), spectrum.shape[1]))
        for i in range(spectrum.shape[1]):
            interpolator = interpolate.InterpolatedUnivariateSpline(
                np.log10(freqs), spectrum[:, i], k=1)
            log_f_spec[:, i] = interpolator(np.log10(f))
        z = log_f_spec
        f = np.log10(f)

        # Normalize and turn to dB scale
        z /= np.max(z)
        z = np.clip(z, 10**(z_min / 20), np.max(z))
        z = 20 * np.log10(z)

        # Smoothen
        z = ndimage.uniform_filter(z, size=3, mode='constant')
        t, f = np.meshgrid(t, f)

        # Smoothing creates "walls", remove them
        t = t[1:-1, :-1] * 1000  # Milliseconds
        f = f[1:-1, :-1]
        z = z[1:-1, :-1]

        # Surface plot
        ax.plot_surface(t,
                        f,
                        z,
                        rcount=len(t),
                        ccount=len(f),
                        cmap='magma',
                        antialiased=True,
                        vmin=z_min,
                        vmax=0)

        # Z axis
        ax.set_zlim([z_min, 0])
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

        # X axis
        ax.set_xlim([0, None])
        ax.set_xlabel('Time (ms)')

        # Y axis
        ax.set_ylim(np.log10([20, 20000]))
        ax.set_ylabel('Frequency (Hz)')
        ax.yaxis.set_major_formatter(
            FuncFormatter(lambda x, p: f'{10 ** x:.0f}'))

        # Orient
        ax.view_init(30, 30)

        return fig, ax
ax1.plot(NF_80mm_exp['time'][:, 0] * 1000,
         NF_80mm_exp['pressure'][:, 4, 0] / 1e6,
         'grey',
         label='Exp: theta 0')
ax1.plot(Apollo_gauges_z80mm_chosenmesh[0][:, 0] * 1000,
         Apollo_gauges_z80mm_chosenmesh[0][:, 1] / 1e6,
         'r',
         lw=1)

ax1.set_xlim(0, 0.15)
ax1.set_ylim(-50, 250)
ax1.set_xlabel('Time (ms)')
ax1.set_ylabel('Overpressure (MPa)')
plt.tight_layout()
ax.xaxis.set_major_locator(LinearLocator(4))
ax.yaxis.set_major_locator(LinearLocator(6))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax1.xaxis.set_major_locator(LinearLocator(4))
ax1.yaxis.set_major_locator(LinearLocator(4))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
handles, labels = ax.get_legend_handles_labels()
ax1.minorticks_on()
ax1.grid(which='major', ls='-', color=[0.15, 0.15, 0.15], alpha=0.15)
ax1.grid(which='minor',
         ls=':',
         dashes=(1, 5, 1, 5),
         color=[0.1, 0.1, 0.1],
         alpha=0.25)
コード例 #15
0
ファイル: 3dplot.py プロジェクト: seanhxx/schoolwork
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.arange(-5, 5, 0.1)
Y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(X, Y)
Z = np.sin(X + Y) + 1

surf = ax.plot_surface(X,
                       Y,
                       Z,
                       cmap=cm.coolwarm,
                       linewidth=0,
                       antialiased=False)

ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.set_zlim(-0.5, 2.5)
ax.xaxis.set_major_locator(LinearLocator(5))
ax.yaxis.set_major_locator(LinearLocator(5))
ax.zaxis.set_major_locator(LinearLocator(7))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

plt.show()
コード例 #16
0
def plot3d(aero, name, parameters):
    """
    Creates a 3D plot of the coefficient values corresponding to the given parameters.
    In the case of any constant parameters this plot represents a slice of a higher dimentional plot.
    :param aero: The aero file.
    :param name: The name of the coefficient.
    :param parameters: List of parameters.
    :return:
    """
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    #find the X and Y axis (the two non constant axis)
    found = 0
    for parameter in parameters:
        if (len(parameter.scope) == 3):  #if not constant
            if found == 0:
                X = parameter.axis
                parameter.X = True
                found += 1
            if found == 1:
                Y = parameter.axis
                parameter.Y = True
            else:
                print("error, too many non constant variables")

    Z = np.zeros((len(Y), len(X)))
    X, Y = np.meshgrid(X, Y)

    i = 0
    j = 0
    while i < X.shape[1]:
        j = 0
        while j < Y.shape[0]:
            # prepare list of values
            values = []
            for parameter in parameters:
                if parameter.X == True:  #if its the X axis
                    values.append(X[0, i])
                    xlabel = parameter.name
                elif parameter.Y == True:  #if its the Y axis
                    values.append(Y[j, 0])
                    ylabel = parameter.name
                else:
                    values.append(parameter.axis[i]
                                  )  # get the i'th value of all parameters

            Z[j, i] = aero.coefficients[name].get_coefficient(*values)
            j += 1
        i += 1

    # Plot the surface.
    surf = ax.plot_surface(X,
                           Y,
                           Z,
                           cmap=cm.coolwarm,
                           vmin=np.nanmin(Z),
                           vmax=np.nanmax(Z),
                           linewidth=0,
                           antialiased=False)

    # Customize the z axis.
    ax.set_zlim(np.nanmin(Z), np.nanmax(Z))
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.xaxis.set_label_text(xlabel)
    ax.yaxis.set_label_text(ylabel)
    ax.zaxis.set_label_text(name)

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show()
コード例 #17
0
def DrawFigure(xvalues, yvalues, legend_labels, x_label, y_label, x_min, x_max,
               filename, allow_legend):
    # you may change the figure size on your own.
    fig = plt.figure(figsize=(10, 3))
    figure = fig.add_subplot(111)

    FIGURE_LABEL = legend_labels

    if not os.path.exists(FIGURE_FOLDER):
        os.makedirs(FIGURE_FOLDER)

    x_values = xvalues
    y_values = yvalues

    lines = [None] * (len(FIGURE_LABEL))
    for i in range(len(y_values)):
        lines[i], = figure.plot(x_values, y_values[i], color=LINE_COLORS[i], \
                                linewidth=LINE_WIDTH, marker=MARKERS[i], \
                                markersize=MARKER_SIZE, label=FIGURE_LABEL[i],
                                markeredgewidth=2, markeredgecolor='k')

    # sometimes you may not want to draw legends.
    if allow_legend == True:
        plt.legend(
            lines,
            FIGURE_LABEL,
            prop=LEGEND_FP,
            loc='upper center',
            ncol=3,
            #                     mode='expand',
            bbox_to_anchor=(0.55, 1.5),
            shadow=False,
            columnspacing=0.1,
            frameon=True,
            borderaxespad=0.0,
            handlelength=1.5,
            handletextpad=0.1,
            labelspacing=0.1)
    # plt.xscale('log')
    # plt.yscale('log')
    plt.xticks(x_values)
    # you may control the limits on your own.
    # plt.xlim(x_min, x_max)
    # plt.ylim(0, 10000)
    plt.ylim(bottom=0)
    yfmt = ScalarFormatterForceFormat()
    yfmt.set_powerlimits((0, 0))
    figure.get_yaxis().set_major_formatter(yfmt)
    plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
    plt.grid(axis='y', color='gray')
    figure.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    figure.yaxis.set_major_locator(LinearLocator(3))
    # figure.xaxis.set_major_locator(FixedLocator(x_values, nbins=len(x_values)))
    # figure.yaxis.set_major_locator(LogLocator(base=10))
    # figure.xaxis.set_major_locator(LogLocator(base=10))
    # figure.xaxis.set_major_locator(MaxNLocator(integer=True))

    # figure.get_xaxis().set_tick_params(direction='in', pad=10)
    # figure.get_yaxis().set_tick_params(direction='in', pad=10)

    plt.xlabel(x_label, fontproperties=LABEL_FP)
    plt.ylabel(y_label, fontproperties=LABEL_FP)
    plt.savefig(FIGURE_FOLDER + "/" + filename + ".pdf", bbox_inches='tight')
コード例 #18
0
x = np.arange(0, len(terrain1[0]))
x, y = np.meshgrid(x, y)

#Plotting the 3D figure
ter = plt.figure()
ax = ter.gca(projection='3d')
surf = ax.plot_surface(x,
                       y,
                       terrain1,
                       cmap=cm.coolwarm,
                       linewidth=0,
                       antialiased=False)

#Customize the axes.
plt.xlabel('X')
ax.xaxis.set_major_locator(LinearLocator(4))
plt.ylabel('Y')
ax.yaxis.set_major_locator(LinearLocator(4))
ax.set_zlim(0, 1900)
ax.set_zticks(np.arange(0, 2375, 475, dtype=int))
ax.set_title("Stavanger Terrain Height")
ax.pbaspect = [1., .33, 0.5]
ax.view_init(elev=35., azim=-70)
ax.yaxis.set_rotate_label(False)
ax.yaxis.label.set_rotation(0)
ax.zaxis.set_rotate_label(False)
ax.zaxis.label.set_rotation(0)
ax.dist = 10.5
ter.colorbar(surf, shrink=0.6, aspect=10)
plt.show()
コード例 #19
0
def DrawFigure(x_values, y_values, legend_labels, x_label, y_label, y_min,
               y_max, filename, allow_legend):
    # you may change the figure size on your own.
    fig = plt.figure(figsize=(9, 3))
    figure = fig.add_subplot(111)

    FIGURE_LABEL = legend_labels

    if not os.path.exists(FIGURE_FOLDER):
        os.makedirs(FIGURE_FOLDER)

    # values in the x_xis
    index = np.arange(len(x_values))
    # the bar width.
    # you may need to tune it to get the best figure.
    width = 0.15
    # draw the bars
    bars = [None] * (len(FIGURE_LABEL))
    for i in range(len(y_values)):
        bars[i] = plt.bar(index + i * width + width / 2,
                          y_values[i],
                          width,
                          hatch=PATTERNS[i],
                          color=LINE_COLORS[i],
                          label=FIGURE_LABEL[i],
                          edgecolor='black',
                          linewidth=3)

    # sometimes you may not want to draw legends.
    if allow_legend == True:
        leg = plt.legend(
            bars,
            FIGURE_LABEL,
            prop=LEGEND_FP,
            ncol=3,
            #                     mode='expand',
            #                     shadow=False,
            bbox_to_anchor=(0.5, 1.4),
            columnspacing=0.25,
            handletextpad=0.2,
            #                     bbox_transform=ax.transAxes,
            #                     frameon=False,
            #                     columnspacing=5.5,
            #                     handlelength=2,
            loc='upper center')
        leg.get_frame().set_linewidth(2)
        leg.get_frame().set_edgecolor("black")
    #    plt.xticks(rotation=35)

    # you may need to tune the xticks position to get the best figure.
    plt.xticks(index + 2.4 * width, x_values)

    # plt.xlim(0,)
    plt.ylim(y_min, y_max)

    plt.grid(axis='y', color='gray')
    figure.yaxis.set_major_locator(LinearLocator(6))

    figure.get_xaxis().set_tick_params(direction='in', pad=10)
    figure.get_yaxis().set_tick_params(direction='in', pad=10)

    plt.xlabel(x_label, fontproperties=LABEL_FP)
    plt.ylabel(y_label, fontproperties=LABEL_FP)

    plt.savefig(FIGURE_FOLDER + "/" + filename + ".pdf", bbox_inches='tight')
コード例 #20
0
def show_landscape(
    adata,
    Xgrid,
    Ygrid,
    Zgrid,
    basis="umap",
    save_show_or_return='show',
    save_kwargs={},
):
    """Plot the quasi-potential landscape.

    Parameters
    ----------
        adata: :class:`~anndata.AnnData`
            AnnData object that contains Xgrid, Ygrid and Zgrid data for visualizing potential landscape.
        Xgrid: `numpy.ndarray`
            x-coordinates of the Grid produced from the meshgrid function.
        Ygrid: `numpy.ndarray`
                y-coordinates of the Grid produced from the meshgrid function.
        Zgrid: `numpy.ndarray`
                z-coordinates or potential at each of the x/y coordinate.
        basis: `str` (default: umap)
            The method of dimension reduction. By default it is trimap. Currently it is not checked with Xgrid and Ygrid.
        save_show_or_return: {'show', 'save', 'return'} (default: `show`)
            Whether to save, show or return the figure.
        save_kwargs: `dict` (default: `{}`)
            A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
            will use the {"path": None, "prefix": 'show_landscape', "dpi": None, "ext": 'pdf', "transparent": True, "close":
            True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
            according to your needs.

    Returns
    -------
        A 3D plot showing the quasi-potential of each cell state.

    """

    if "grid_Pot_" + basis in adata.uns.keys():
        Xgrid_, Ygrid_, Zgrid_ = (
            adata.uns["grid_Pot_" + basis]["Xgrid"],
            adata.uns["grid_Pot_" + basis]["Ygrid"],
            adata.uns["grid_Pot_" + basis]["Zgrid"],
        )

    Xgrid = Xgrid_ if Xgrid is None else Xgrid
    Ygrid = Ygrid_ if Ygrid is None else Ygrid
    Zgrid = Zgrid_ if Zgrid is None else Zgrid

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    from matplotlib.colors import LightSource

    fig = plt.figure()
    ax = fig.gca(projection="3d")

    # Plot the surface.
    ls = LightSource(azdeg=0, altdeg=65)
    # Shade data, creating an rgb array.
    rgb = ls.shade(Zgrid, plt.cm.RdYlBu)
    surf = ax.plot_surface(
        Xgrid,
        Ygrid,
        Zgrid,
        cmap=cm.coolwarm,
        rstride=1,
        cstride=1,
        facecolors=rgb,
        linewidth=0,
        antialiased=False,
    )
    # Customize the z axis.
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter("%.02f"))

    # Add a color bar which maps values to colors.
    # fig.colorbar(surf, shrink=0.5, aspect=5)
    ax.set_xlabel(basis + "_1")
    ax.set_ylabel(basis + "_2")
    ax.set_zlabel("U")

    if save_show_or_return == "save":
        s_kwargs = {
            "path": None,
            "prefix": 'show_landscape',
            "dpi": None,
            "ext": 'pdf',
            "transparent": True,
            "close": True,
            "verbose": True
        }
        s_kwargs = update_dict(s_kwargs, save_kwargs)

        save_fig(**s_kwargs)
    elif save_show_or_return == "show":
        plt.tight_layout()
        plt.show()
    elif save_show_or_return == "return":
        return ax
コード例 #21
0
ファイル: Test.py プロジェクト: punk95/sitnshop
ylen = len(Y)

X, Y = np.meshgrid(X, Y)

colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
    for x in range(xlen):
        colors[x, y] = colortuple[(x + y) % len(colortuple)]

# Plot the surface with face colors taken from the array we made.
surf = ax.plot_surface(X, Y, mean.T, facecolors=colors, linewidth=0)

# Customize the z axis.

ax.w_zaxis.set_major_locator(LinearLocator(6))
plt.title("GPSARASA Value function Map for a grid with path and 5 0 -1 reward")
plt.xlabel("x")
plt.ylabel('y')

#plt.savefig("GP_SARAS_-1_0_reward.png")

print("D_len = ", G.D_len)
plt.show()

start = [0, 0]
x = start[0]
y = start[1]
R = -1
steps = 0
コード例 #22
0
ファイル: Ridge_FF.py プロジェクト: lgcharpe/FYS-STK4155
def Ridge_FF(X, Y, F, lam=0.01, k=1, graph=True):

    x_data = X.ravel()
    y_data = Y.ravel()
    f_data = F.ravel()

    xb = gen_def_matrix(x_data, y_data, k)
    beta = gen_beta(xb, f_data, lam)
    sklridge = Ridge(alpha=lam)
    sklridge.fit(xb, f_data)

    xnew = np.linspace(0, 1, np.size(X, 0))
    ynew = np.linspace(0, 1, np.size(X, 1))
    Xnew, Ynew = np.meshgrid(xnew, ynew)
    F_true = FrankeFunction(Xnew, Ynew)

    xn = Xnew.ravel()
    yn = Ynew.ravel()

    xb_new = gen_def_matrix(xn, yn, k)
    f_predict = xb_new.dot(beta)
    F_predict = f_predict.reshape(F.shape)
    sklridge_pred = sklridge.predict(xb_new)
    sklridge_pred = sklridge_pred.reshape(F.shape)

    MSE = mean_squared_error(F_true, F_predict)
    R2 = r2_score(F_true, F_predict)

    skl_MSE = mean_squared_error(F_true, sklridge_pred)
    skl_R2 = r2_score(F_true, sklridge_pred)

    diff_MSE = MSE - skl_MSE
    diff_R2 = R2 - skl_R2

    sigma2 = 0

    for i in range(np.size(F_true, 0)):
        for j in range(np.size(F_true, 1)):
            sigma2 = sigma2 + (F_predict[i, j] - F_true[i, j])**2
    sigma2 = sigma2 / (f_predict.size - beta.size)

    var = np.diag(np.linalg.inv(xb_new.T.dot(xb_new))) * sigma2

    if (graph):
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        surf = ax.plot_surface(Xnew,
                               Ynew,
                               F_predict,
                               cmap='coolwarm',
                               linewidth=0,
                               antialiased=False)
        ax.set_zlim(-0.10, 1.40)
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
        plt.title("Ridge Regression polynomial order %d with lambda %.04f" %
                  (k, lam))
        plt.xlabel('X')
        plt.ylabel('Y')
        fig.colorbar(surf, shrink=0.5, aspect=0.5)
        plt.show()

    return MSE, R2, var  #, diff_MSE, diff_R2
コード例 #23
0
ファイル: plot3D.py プロジェクト: fabianlachmann/mainPlot
def plot3D(data, k):
    fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

    # Make data.
    # X = np.arange(-5, 5, 0.25)
    # Y = np.arange(-5, 5, 0.25)
    # X, Y = np.meshgrid(X, Y)
    # R = np.sqrt(X ** 2 + Y ** 2)
    # Z = np.sin(R)
    # print(X)
    # print(Y)
    # print(Z)
    #data = data[153:193]
    x = []
    X = []
    y = []
    Y = []
    z = []
    Z = []

    for row in data:
        x.append(
            float(row[k - 3]) + (float(row[k - 2]) / 30) + (float(row[k - 1]) /
                                                            (30 * 24)))

    #for i in range(len(data)):
    #    x.append(i)

    for entry in size:
        X.append(x)

    for i in range(len(data[0][3:19])):
        z = []
        for row in data:
            z.append(float(row[i + k]) * 1000)
        Z.append(z)

    for entry in Messgrössen:
        y = []
        for row in data:
            y.append(entry[0])
        Y.append(y)

    X = np.array(X)
    Y = np.array(Y)
    Z = np.array(Z)

    # Plot the surface.
    surf = ax.plot_surface(X,
                           np.log10(Y),
                           Z,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=False)

    # Customize the z axis.
    #ax.set_zlim(-1.01, 1.01)
    ax.zaxis.set_major_locator(LinearLocator(10))
    # A StrMethodFormatter is used automatically
    ax.zaxis.set_major_formatter('{x:.02f}')

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show()
コード例 #24
0
    def get_graph(self, destination, width, height):
        """
            - This service returns a PNG image with the given width and height
            - The PNG contains a graph of the results belonging to the
              result_id and sobek_ids
        input:
            widht and height of returning image
            array of shape_ids which will be shown
            presentationlayer_id

        return:
            png
        """
        # Opmerking Bastiaan: caching van his-object geeft weinig tijdwinst

        #Get information from request
        graph_width = width
        graph_height = height

        #Set dpi
        graph_dpi = 55

        #Create figure and subplot to draw on
        fig = plt.figure(facecolor='white',
                         edgecolor='white',
                         figsize=(graph_width / graph_dpi,
                                  graph_height / graph_dpi),
                         dpi=graph_dpi)

        #Add axes 'manually' (not via add_subplot(111) to have control
        #over the position This is necessary as we use long labels
        ax_left = 0.11
        ax_bottom = 0.21
        ax = fig.add_axes(
            [ax_left, ax_bottom, 0.95 - ax_left, 0.95 - ax_bottom])

        #Read Sobek data and plot it
        plots = dict()  # dictionary necessary for creating the legend
        # at the end of this method

        # get values
        table = self.get_waterlevels(-0.25 * self.tsim, 1.25 * self.tsim)

        time_steps = [obj['time'] * 24 for obj in table]
        if 'stormlevel' in table[0]:
            use_stormlevel = True
            stormlevel = [obj['stormlevel'] for obj in table]
        else:
            use_stormlevel = False
            stormlevel = [0]
        waterlevel = [obj['waterlevel'] for obj in table]

        min_level = min(min(stormlevel), min(waterlevel))
        max_level = max(max(stormlevel), max(waterlevel))

        max_for_timeperiod = max_level + (max_level - min_level) * 0.05
        simperiod_levels = [
            min_level, max_for_timeperiod, max_for_timeperiod, min_level
        ]
        simperiod_times = [0, 0, self.tsim * 24, self.tsim * 24]

        plot_simperiod = ax.plot(simperiod_times,
                                 simperiod_levels,
                                 '-',
                                 linewidth=3)
        if use_stormlevel:
            plot_stormlevel = ax.plot(time_steps, stormlevel, '-', linewidth=3)
        plot_waterlevel = ax.plot(time_steps, waterlevel, '-', linewidth=3)

        plots['waterlevel'] = plot_waterlevel
        if use_stormlevel:
            plots['stormlevel'] = plot_stormlevel
        plots['simulatie periode'] = plot_simperiod

        #temp fix for locators
        dt = time_steps[-1] - time_steps[0] / len(time_steps)

        if dt > 50:
            dt = 10
        else:
            dt = 1

        [min_locator,
         maj_locator] = get_time_step_locators(len(time_steps), dt)

        #Set formatting of the x-axis and y-axis
        ax.xaxis.set_major_formatter(TimestepFormatter())
        ax.xaxis.set_major_locator(maj_locator)
        ax.xaxis.set_minor_locator(min_locator)
        fig.autofmt_xdate()

        ax.yaxis.set_major_locator(LinearLocator())
        ax.yaxis.set_major_formatter(FormatStrFormatter('%0.2f'))

        ax.grid(True, which='major')
        ax.grid(True, which='minor')

        #Set labels
        plt.xlabel("Tijdstip")
        plt.ylabel("waterstand [mNAP]")
        ax.set_title("waterstandsverloop")

        #Set legend
        ax.legend((v for k, v in plots.iteritems()),
                  (k for k, v in plots.iteritems()),
                  'upper right',
                  shadow=True)

        #Return figure as png-file
        log.debug('start making picture')
        canvas = FigureCanvas(fig)
        canvas.print_png(destination)
        log.debug('ready making picture')
        return destination
コード例 #25
0
ファイル: qca2.py プロジェクト: pja35/QW-Gravitons
def meaned_QW(mean,
              N=None,
              it_number=None,
              th=None,
              r=None,
              halved=True,
              gauss=False,
              affreg=False,
              freq=None,
              disp=True,
              creat=True,
              ignore=True,
              affiche=False,
              d3=True):

    X = [[] for _ in range(mean)]
    Z0 = [[] for _ in range(mean)]
    T = np.array(range(it_number))
    for m in range(mean):
        X[m], Z0[m] = basic_QW(N=N,
                               it_number=it_number,
                               th=th,
                               r=r,
                               halved=halved,
                               gauss=gauss,
                               affreg=affreg,
                               freq=freq,
                               disp=disp,
                               creat=creat,
                               ignore=ignore,
                               affiche=affiche,
                               d3=d3)
    Xa = np.empty(it_number)
    for t in range(it_number):
        Xa[t] = np.sum([X[i][t] for i in range(mean)]) / mean

    if d3:
        #print(Z0[0])
        Z = np.zeros((len(Z0[0]), len(Z0[0][0])))
        for k in range(len(Z0[0])):
            for t in range(len(Z0[0][0])):
                Z[k, t] = np.sum([Z0[i][k][t] for i in range(mean)]) / mean
        fig = plt.figure()
        #ax = fig.add_subplot(111, projection='3d')
        ax = fig.gca(projection='3d')
        X = np.arange(0, int(Xa[0]) + len(Xa) + 1, 1)
        T = np.arange(0, len(Xa), 1)
        print(np.shape(T))
        X, T = np.meshgrid(X, T)
        print(np.shape(X))
        print(np.shape(T))
        print(np.shape(Z))
        surf = ax.plot_surface(X,
                               T,
                               Z,
                               rstride=1,
                               cstride=1,
                               cmap=cm.coolwarm,
                               linewidth=0,
                               antialiased=False)
        ax.set_zlim(-0.01, 1.01)
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

        fig.colorbar(surf, shrink=0.5, aspect=5)
    else:
        #print(Xa)
        plt.plot(T, Xa)
        plt.grid()
    plt.show()

    ffnorm = open("norms.txt", "w")
    ffnorm.write("")
    ffnorm.close()
    ffnorm = open("norms.txt", "a")
    ffnorm.write("Xh = " + str(Xa))
    ffnorm.close()
コード例 #26
0
def DrawFigure(x_values, y_values, legend_labels, x_label, y_label, y_min, y_max, filename, allow_legend):
    # you may change the figure size on your own.
    fig = plt.figure(figsize=(9, 3))
    figure = fig.add_subplot(111)

    FIGURE_LABEL = legend_labels

    if not os.path.exists(FIGURE_FOLDER):
        os.makedirs(FIGURE_FOLDER)

    # values in the x_xis
    index = np.arange(len(x_values))
    # the bar width.
    # you may need to tune it to get the best figure.
    width = 0.4
    # draw the bars
    bars = [None] * (len(FIGURE_LABEL))
    for i in range(len(y_values)):
        bars[i] = plt.bar(index + i * width + width / 2, y_values[i], width, hatch=PATTERNS[i], color=LINE_COLORS[i],
                          label=FIGURE_LABEL[i], edgecolor='black', linewidth=3)

    # you may need to tune the xticks position to get the best figure.
    plt.xticks(index + 1 * width, x_values)
    # sometimes you may not want to draw legends.

    # sometimes you may not want to draw legends.
    if allow_legend == True:
        plt.legend(bars, FIGURE_LABEL,
                   #                     mode='expand',
                   #                     shadow=False,
                   #                     columnspacing=0.25,
                   #                     labelspacing=-2.2,
                   #                     borderpad=5,
                   #                     bbox_transform=ax.transAxes,
                   frameon=True,
                   #                     columnspacing=5.5,
                   #                     handlelength=2,
                   )
        # if we want to reorder the sequence.
        # handles, labels = figure.get_legend_handles_labels()
        # handles[::-1], labels[::-1]
        leg = plt.legend(
            loc='center',
            prop=LEGEND_FP,
            ncol=1,
            # bbox_to_anchor=(0.5, 1.3),
            bbox_to_anchor=(1.25, 0.5),
            handletextpad=0.2,
            borderaxespad=0.0,
            handlelength=1.8,
            labelspacing=0.3,
            columnspacing=0.3,
        )
        leg.get_frame().set_linewidth(2)
        leg.get_frame().set_edgecolor("black")


    yfmt = ScalarFormatterForceFormat()
    yfmt.set_powerlimits((0,0))
    figure.get_yaxis().set_major_formatter(yfmt)
    # plt.xlim(0,)
    # plt.ylim(y_min, y_max)
    # plt.yscale('log')
    plt.ticklabel_format(axis="y", style="sci", scilimits=(0,0), useMathText=True)
    plt.grid(axis='y', color='gray')
    figure.yaxis.set_major_locator(LinearLocator(3))
    # figure.yaxis.set_major_locator(LinearLocator(6))
    # figure.yaxis.set_major_locator(LogLocator(base=10))

    figure.get_xaxis().set_tick_params(direction='in', pad=10)
    figure.get_yaxis().set_tick_params(direction='in', pad=10)

    plt.xlabel(x_label, fontproperties=LABEL_FP)
    plt.ylabel(y_label, fontproperties=LABEL_FP)

    size = fig.get_size_inches()
    dpi = fig.get_dpi()

    plt.savefig(FIGURE_FOLDER + "/" + filename + ".pdf", bbox_inches='tight')
コード例 #27
0
def empirical_cdf(out_values,
                  subsections,
                  input_sample,
                  names,
                  levels,
                  outpath,
                  outname,
                  param_dict,
                  plot_cfg=None):
    """Visualize the empirical cumulative distribution function(CDF)
    of the given variable (x) and subsections of y.

    """
    # prepare data
    if not isinstance(out_values, numpy.ndarray):
        out_values = numpy.array(out_values)
    out_max = numpy.max(out_values)
    out_min = numpy.min(out_values)
    if isinstance(subsections, int):
        if subsections <= 0:
            raise ValueError(
                'subsections MUST be a integer greater than 0, or list.')
        step = (out_max - out_min) / subsections
        subsections = numpy.arange(out_min, out_max + step, step)
    if isinstance(subsections, list) and len(subsections) == 1:  # e.g., [0]
        section_pt = subsections[0]
        if out_min < section_pt < out_max:
            subsections = [out_min, section_pt, out_max]
        else:
            subsections = [out_min, out_max]
    labels = list()
    new_input_sample = list()
    for i in range(1, len(subsections)):
        decimal1 = 0 if int(subsections[i - 1]) == float(subsections[i -
                                                                     1]) else 2
        decimal2 = 0 if int(subsections[i]) == float(subsections[i]) else 2
        if out_max == subsections[i] and out_min == subsections[i - 1]:
            labels.append('%s=<y<=%s' %
                          ('{0:.{1}f}'.format(subsections[i - 1], decimal1),
                           '{0:.{1}f}'.format(subsections[i], decimal2)))
            zone = numpy.where((subsections[i - 1] <= out_values)
                               & (out_values <= subsections[i]))
        elif out_max == subsections[i]:
            labels.append('y>=%s' %
                          '{0:.{1}f}'.format(subsections[i - 1], decimal1))
            zone = numpy.where(subsections[i - 1] <= out_values)
        elif out_min == subsections[i - 1]:
            labels.append('y<%s' %
                          ('{0:.{1}f}'.format(subsections[i], decimal2)))
            zone = numpy.where(out_values < subsections[i])
        else:
            labels.append('%s=<y<%s' %
                          ('{0:.{1}f}'.format(subsections[i - 1], decimal1),
                           '{0:.{1}f}'.format(subsections[i], decimal2)))
            zone = numpy.where((subsections[i - 1] <= out_values)
                               & (out_values < subsections[i]))
        new_input_sample.append(input_sample[zone, :][0])

    if plot_cfg is None:
        plot_cfg = PlotConfig()
    plt.rcParams['font.family'] = plot_cfg.font_name
    fig = plt.figure()

    num_vars = len(names)
    row, col = cal_row_col_num(num_vars)
    for var_idx in range(num_vars):
        ax = fig.add_subplot(row, col, var_idx + 1)
        for ii in range(len(labels) - 1, -1, -1):
            ax.hist(new_input_sample[ii][:, var_idx],
                    bins=levels,
                    density=True,
                    cumulative=True,
                    label=labels[ii],
                    **param_dict)
        ax.get_yaxis().set_major_locator(LinearLocator(numticks=5))
        ax.set_ylim(0, 1)
        ax.set_title('%s' % (names[var_idx]), fontsize=plot_cfg.title_fsize)
        ax.get_xaxis().set_major_locator(LinearLocator(numticks=3))
        ax.tick_params(
            axis='x',  # changes apply to the x-axis
            which='both',  # both major and minor ticks are affected
            bottom=True,  # ticks along the bottom edge are off
            top=False,  # ticks along the top edge are off
            labelbottom=True  # labels along the bottom edge are off
        )
        ax.tick_params(
            axis='y',  # changes apply to the y-axis
            which='major',  # both major and minor ticks are affected
            length=3,
            right=False)
        if var_idx % col:  # labels along the left edge are off
            ax.tick_params(axis='y', labelleft=False)
        if var_idx == 0:
            ax.legend(loc='lower right',
                      fontsize=plot_cfg.legend_fsize,
                      framealpha=0.8,
                      bbox_to_anchor=(1, 0),
                      borderaxespad=0.2,
                      fancybox=True)
    plt.tight_layout()
    save_png_eps(plt, outpath, outname, plot_cfg)
    # close current plot in case of 'figure.max_open_warning'
    plt.cla()
    plt.clf()
    plt.close()
コード例 #28
0
def plot_2D_marginal_probs(marginals,
                           bins,
                           sample_set,
                           filename="file",
                           lam_ref=None,
                           plot_surface=False,
                           interactive=False,
                           lambda_label=None,
                           file_extension=".png"):
    """
    This makes plots of every pair of marginals (or joint in 2d case) of
    input probability measure on a rectangular grid.
    If the sample_set object is a discretization object, we assume
    that the probabilities to be plotted are from the input space.

    .. note::

        Do not specify the file extension in the file name.

    :param marginals: 2D marginal probabilities
    :type marginals: dictionary with tuples of 2 integers as keys and
        :class:`~numpy.ndarray` of shape (nbins+1,) as values 
    :param bins: Endpoints of bins used in calculating marginals
    :type bins: :class:`~numpy.ndarray` of shape (nbins+1,2)
    :param sample_set: Object containing samples and probabilities
    :type sample_set: :class:`~bet.sample.sample_set_base` 
        or :class:`~bet.sample.discretization`
    :param filename: Prefix for output files.
    :type filename: str
    :param lam_ref: True parameters.
    :type lam_ref: :class:`~numpy.ndarray` of shape (ndim,) or None
    :param interactive: Whether or not to display interactive plots.
    :type interactive: bool
    :param lambda_label: Label for each parameter for plots.
    :type lambda_label: list of length nbins of strings or None
    :param string file_extension: file extenstion

    """
    if isinstance(sample_set, sample.discretization):
        sample_obj = sample_set._input_sample_set
    elif isinstance(sample_set, sample.sample_set_base):
        sample_obj = sample_set
    else:
        raise bad_object("Improper sample object")

    if lam_ref is None:
        lam_ref = sample_obj._reference_value

    lam_domain = sample_obj.get_domain()

    from matplotlib import cm
    if plot_surface:
        from mpl_toolkits.mplot3d import Axes3D
        from matplotlib.ticker import LinearLocator, FormatStrFormatter
    if comm.rank == 0:
        pairs = copy.deepcopy(list(marginals.keys()))
        pairs.sort()
        for k, (i, j) in enumerate(pairs):
            fig = plt.figure(k)
            ax = fig.add_subplot(111)
            boxSize = (bins[i][1] - bins[i][0]) * (bins[j][1] - bins[j][0])
            quadmesh = ax.imshow(marginals[(i, j)].transpose() / boxSize,
                                 interpolation='bicubic',
                                 cmap=cm.CMRmap_r,
                                 extent=[
                                     lam_domain[i][0], lam_domain[i][1],
                                     lam_domain[j][0], lam_domain[j][1]
                                 ],
                                 origin='lower',
                                 vmax=marginals[(i, j)].max() / boxSize,
                                 vmin=0,
                                 aspect='auto')
            if lam_ref is not None:
                ax.plot(lam_ref[i], lam_ref[j], 'wo', markersize=10)
            if lambda_label is None:
                label1 = r'$\lambda_{' + str(i + 1) + '}$'
                label2 = r'$\lambda_{' + str(j + 1) + '}$'
            else:
                label1 = lambda_label[i]
                label2 = lambda_label[j]
            ax.set_xlabel(label1, fontsize=20)
            ax.set_ylabel(label2, fontsize=20)
            ax.tick_params(axis='both', which='major', labelsize=14)
            label_cbar = r'$\rho_{\lambda_{' + str(i + 1) + '}, '
            label_cbar += r'\lambda_{' + str(j + 1) + '}' + '}$ (Lebesgue)'
            cb = fig.colorbar(quadmesh, ax=ax, label=label_cbar)
            cb.ax.tick_params(labelsize=14)
            cb.set_label(label_cbar, size=20)
            plt.axis([
                lam_domain[i][0], lam_domain[i][1], lam_domain[j][0],
                lam_domain[j][1]
            ])
            plt.tight_layout()
            fig.savefig(filename + "_2D_" + str(i) + "_" + str(j) +
                        file_extension,
                        transparent=True)
            if interactive:
                plt.show()
            else:
                plt.close()

        if plot_surface:
            for k, (i, j) in enumerate(pairs):
                fig = plt.figure(k)
                ax = fig.gca(projection='3d')
                X = bins[i][:-1] + np.diff(bins[i]) / 2
                Y = bins[j][:-1] + np.diff(bins[j]) / 2
                X, Y = np.meshgrid(X, Y, indexing='ij')
                surf = ax.plot_surface(X,
                                       Y,
                                       marginals[(i, j)],
                                       rstride=1,
                                       cstride=1,
                                       cmap=cm.coolwarm,
                                       linewidth=0,
                                       antialiased=False)
                ax.zaxis.set_major_locator(LinearLocator(10))
                ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
                ax.set_xlabel(r'$\lambda_{' + str(i + 1) + '}$')
                ax.set_ylabel(r'$\lambda_{' + str(j + 1) + '}$')
                ax.set_zlabel(r'$P$')
                plt.backgroundcolor = 'w'
                fig.colorbar(surf, shrink=0.5, aspect=5, label=r'$P$')
                plt.tight_layout()
                fig.savefig(filename + "_surf_" + str(i) + "_" + str(j) +
                            file_extension,
                            transparent=True)

                if interactive:
                    plt.show()
                else:
                    plt.close()
                plt.clf()
    comm.barrier()
コード例 #29
0
        result = minimize(fun=RiskParity_objective,
                          x0=x0,
                          constraints=constraints,
                          options=options)
        return (result.x)

    w_RP[w - smonth] = RiskParity(covmatr)

    r_rp[w - smonth] = np.multiply(weekly_return[w, :], w_RP[w - smonth, :])
    retRP[w - smonth] = sum(r_rp[w - smonth])
    #print(retRP)

mx = np.amax(w_RP)
mn = np.amin(w_RP)

fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.arrange(0, T2, 1)
Y = np.arrange(0, N, 1)
X, Y = np.meshgrid(X, Y)
Z = np.transpose(w_RP)

surf = ax.plot_surface(X, Y, Z, cmap=cm.Reds_r, linewidth=0, antialised=False)

ax.set_zlim(mn - .02, mx + .05)
axzaxis.set_major_locator(LinearLocator(10))
axzaxis.set_major_formatter(FormatStrFormatter('%.03f'))
plt.show()  # eje x será el mes, eje y activo, z peso activo del portafolio
コード例 #30
0
def main():
    """
    Performs Data analysis on the Franke function with noise, using OLS, Ridge
    and Lasso with crossvalidation.
    """

    UnitTest()  #Performs the Unit Test

    np.random.seed(42)  #The meaning of live

    #Parameters, could have been arranged as input arguments
    n = 50
    noise = 0.1
    test_S = 0.3
    degree = 26
    k = 5
    deg_max = 12  #20
    lmb = 0.0001
    gamma = 0.0001

    #Testing a range of lambdas and polynimials
    lmb_range = lmb * np.ones(13)
    for i in range(1, len(lmb_range)):
        lmb_range[i] = np.sqrt(10) * lmb_range[i - 1]

    #Parameters of the model
    x = np.sort(np.random.uniform(0, 1, n))
    y = np.sort(np.random.uniform(0, 1, n))
    x, y = np.meshgrid(x, y)
    x_1 = np.ravel(x)
    y_1 = np.ravel(y)

    #The dataset
    z = FrankeFunction(x, y, n, noise)
    z_true = FrankeFunction(x, y, n, noise, False)
    z_1 = np.ravel(z)
    plotting_function(x, y, z, n)

    #Generating the Design Matrix
    X_DM = X_DesignMatrix(x_1, y_1, degree)

    print(
        "Points = %s, Degree = %s, Noise = %s, $\\lambda$ = %s, $\\gamma$ = %s"
        % (n * n, degree, noise, lmb, gamma))

    #Calls for solving tasks with OLS
    B = Coeff(X_DM, z_1)
    z_predict = np.dot(X_DM, B).reshape(n, n)
    r2_score = metrics.r2_score(z_true, np.reshape(z_predict, (n, n)))
    MSE = metrics.mean_squared_error(z_true, np.reshape(z_predict, (n, n)))
    #r2_score = metrics.r2_score(z,np.reshape(z_predict,(n,n)))
    #MSE = metrics.mean_squared_error(z,np.reshape(z_predict,(n,n)))
    print("MSE = %s, R2 score = %s" % (MSE, r2_score))
    plotting_function(x, y, z_predict, n)

    #Finding the confidence interval for OLS
    B_max, B_min = ConfInterval(B, X_DM)
    plt.figure()
    plt.plot(range(len(B)), B, label="$ \\beta $")
    plt.plot(range(len(B)), B_max, label="$ \\beta_{max} $")
    plt.plot(range(len(B)), B_min, label="$ \\beta_{min} $")
    plt.xlabel("$\\beta_{i}$")
    plt.legend()

    #Calls for solving tasks with Ridge
    B_ridge = CoeffRidge(X_DM, z_1, lmb)
    z_ridge = np.dot(X_DM, B_ridge).reshape(n, n)
    r2_score_ridge = metrics.r2_score(z_true, np.reshape(z_ridge, (n, n)))
    MSE_ridge = metrics.mean_squared_error(z_true, np.reshape(z_ridge, (n, n)))
    #r2_score_ridge = metrics.r2_score(z,np.reshape(z_ridge,(n,n)))
    #MSE_ridge = metrics.mean_squared_error(z,np.reshape(z_ridge,(n,n)))
    print("MSE ridge = %s, R2 score ridge = %s" % (MSE_ridge, r2_score_ridge))
    plotting_function(x, y, z_ridge, n)

    #Calls for solving tasks with Lasso
    clf_lasso = skl.Lasso(alpha=gamma, max_iter=10e4, tol=0.01).fit(X_DM, z_1)
    z_lasso = clf_lasso.predict(X_DM)
    r2_score_lasso = metrics.r2_score(z_true, np.reshape(z_lasso, (n, n)))
    MSE_lasso = metrics.mean_squared_error(z_true, np.reshape(z_lasso, (n, n)))
    print("MSE lasso = %s, R2 score lasso = %s" % (MSE_lasso, r2_score_lasso))
    plotting_function(x, y, z_lasso, n)

    #x_train, x_test, y_train, y_test, z_train, z_test = train_test_split(x_1,y_1,z_1,test_size=test_S)
    #r2_score, MSE_test, MSE_train, bias, variance = kCrossValidation(x_train,y_train,z_train,deg_max,k)
    r2_score, MSE_test, MSE_train, bias, variance = kCrossValidation(
        x_1, y_1, z_1, deg_max, k)

    #Crossvalidation on OLS
    degs = range(0, deg_max + 1)
    plt.figure()
    plt.plot(degs, (MSE_test), label="test MSE")
    plt.plot(degs, (MSE_train), label="train MSE")
    plt.plot(degs, (bias), label="Bias")
    plt.plot(degs, (variance), label="Variance")
    plt.legend()

    #Crossvalidation of Ridge + Plotting
    i = 0
    MSE_test_ridge = np.zeros((len(lmb_range), deg_max + 1))
    MSE_train_ridge = np.zeros((len(lmb_range), deg_max + 1))
    for l in lmb_range:
        sys.stdout.write("\rCrossvalidation with ridge completion: %d %%" %
                         (100 * (i + 1) / len(lmb_range)))
        r2_score_ridge, MSE_test_ridge[i, :], MSE_train_ridge[
            i, :], bias_ridge, variance_ridge = kCrossValidation(
                x_1, y_1, z_1, deg_max, k, l)
        i += 1
        sys.stdout.flush()
    sys.stdout.flush()

    #fig = plt.figure()
    #ax = fig.add_subplot(111, projection='3d')
    #ax.add_collection3d(lmb_range,MSE_test_ridge)
    msx, msy = np.meshgrid(lmb_range, degs)
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    surf = ax.plot_surface(np.log10(msx),
                           msy, (MSE_test_ridge),
                           label="Test MSE",
                           linewidth=0,
                           antialiased=False)
    surf = ax.plot_surface(np.log10(msx),
                           msy, (MSE_train_ridge),
                           label="Train MSE",
                           linewidth=0,
                           antialiased=False)

    ax.set_zlim(np.min((MSE_test_ridge)), np.max((MSE_test_ridge)))
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    plt.title("Crossvalidation of Ridge")
    plt.xlabel("$Log10(\\lambda)$")
    plt.ylabel("degrees")

    fig.colorbar(surf, shrink=0.5, aspect=5)