Example #1
0
    def plot_RECa124_tc(self):
        self.get_args()
        data = pd.read_csv(self.file_list[0])
        data = data.dropna(how="any")
        print(data)

        fig, ax = plt.subplots(figsize=(7, 5))

        norm = Normalize(vmin=data['ionic_radius'].min(), vmax=1.08)
        cmap = get_cmap('seismic')
        mappable = ScalarMappable(cmap=cmap, norm=norm)
        mappable._A = []

        re = ['Y', "Dy", "Gd", "Eu", "Sm"]
        re_ir = [1.019, 1.027, 1.053, 1.066, 1.079]
        re_ir = [0, 0.2, 0.6, 0.7, 0.9]

        for r, rir in zip(re, re_ir):
            print(rir)
            data2 = data[data['RE'] == r]
            print(data2)
            x = data2['Ca_x'].values.reshape(-1, 1)
            y = data2["Tc_onset"].values.reshape(-1, 1)
            # lr = LinearRegression()
            lr = GaussianProcessRegressor()
            lr.fit(x, y)
            # print(lr.coef_)
            # print(lr.intercept_)
            print(lr.score(x, y))
            lrx = np.linspace(0, 0.15, 1000).reshape(-1, 1)
            ax.plot(lrx,
                    lr.predict(lrx),
                    color=cmap(rir),
                    zorder=-1,
                    alpha=0.5,
                    lw=5)
        # =======================================================

        ax.scatter(data['Ca_x'],
                   data["Tc_onset"],
                   marker='o',
                   s=200,
                   c=data['ionic_radius'],
                   cmap=cmap)
        fig.colorbar(mappable).set_label(r"$RE^{3+}$ ionic radius / $\rm\AA$")
        ax.set_xlim(0, 0.1)
        ax.set_ylim(70, 95)
        ax.set_yticks(range(70, 96, 5))
        ax.set_xticks([0, 0.05, 0.10])
        ax.tick_params(length=5, pad=8)
        ax.tick_params(right=True, top=True)
        ax.set_xlabel(r"$\it{x}$")
        ax.set_ylabel(r"$\it{T}_{\mathsf{c}}$ / K")
        # plt.gca().spines['left'].set_visible(False)
        # plt.gca().spines['right'].set_visible(False)
        # plt.tick_range()
        fig.tight_layout()
        plt.show()
Example #2
0
def w_value_2d_heatmap(f, w_store, _t_max, title="w value"):
    w_store = np.array(w_store)
    w_star = f.w_star
    grid_x_min = min(w_store.T[0].min(), w_star[0]) - 1
    grid_x_max = max(w_store.T[0].max(), w_star[0]) + 1
    grid_y_min = min(w_store.T[1].min(), w_star[1]) - 1
    grid_y_max = max(w_store.T[1].max(), w_star[1]) + 1
    xvals = np.arange(grid_x_min, grid_x_max, 0.1)
    yvals = np.arange(grid_y_min, grid_y_max, 0.1)
    X, Y = np.meshgrid(xvals, yvals)
    Z = f.f_opt([X, Y])

    fig, axes = plt.subplots(1, 1, figsize=(6, 6))
    axes.pcolor(X, Y, Z, cmap=plt.cm.rainbow)
    # wの軌跡
    axes.plot(w_store.T[0], w_store.T[1], c="k", alpha=0.2, linewidth=1)
    c = np.linspace(0, _t_max, len(w_store))
    axes.scatter(w_store.T[0],
                 w_store.T[1],
                 c=c,
                 cmap=plt.cm.hot,
                 linewidths=0.01,
                 alpha=1,
                 s=10)

    # 始点(黄色)、終点(緑)、真値(赤)
    axes.plot(*w_store[0], 'ks', markersize=5, label="start")
    axes.plot(*w_store[-1], 'gs', markersize=5, label="finish")
    axes.plot(*w_star, 'r*', markersize=8, label="true value")
    axes.set_title(title)

    # カラーバーの設定
    axpos = axes.get_position()
    cbar_ax = fig.add_axes([0.9, axpos.y0, 0.03, axpos.height])
    norm = colors.Normalize(vmin=Z.min(), vmax=Z.max())
    mappable = ScalarMappable(cmap=plt.cm.rainbow, norm=norm)
    mappable._A = []
    fig.colorbar(mappable, cax=cbar_ax)

    # 余白の調整
    plt.subplots_adjust(right=0.85)
    plt.subplots_adjust(wspace=0.1)

    plt.show()
def Make_animation(npy_file, PSO):
    all_particle_data_with_cost = np.load(npy_file)
    n_iterations = all_particle_data_with_cost.shape[0]
    n_particles = all_particle_data_with_cost.shape[1]
    all_particle_data_with_cost = all_particle_data_with_cost.T
    range_max = [100, 100, 100, 100, 100000000]

    nfr = n_iterations  # Number of frames
    fps = 3  # Frame per sec
    xs = []
    ys = []
    zs = []
    ws = []
    vs = []

    us = []
    for iteration in range(n_iterations):
        xs.append(all_particle_data_with_cost[0].T[iteration] / 1000)
        ys.append(all_particle_data_with_cost[1].T[iteration])
        zs.append(all_particle_data_with_cost[2].T[iteration])
        ws.append(all_particle_data_with_cost[3].T[iteration])
        vs.append(all_particle_data_with_cost[4].T[iteration])
        us.append(all_particle_data_with_cost[5].T[iteration])

    def Convert_int(ndarray):
        return ndarray.astype(np.int32)

    vs = list(map(Convert_int, vs))
    us = list(map(Convert_int, us))

    # %% Create Color Map
    cmap = get_cmap('jet')
    # y_tick_max = ceil(np.max(vs), 1e+7)
    y_tick_max = ceil(np.min(us) + (1e+7), 1e+7)
    y_tick_min = floor(np.min(us), 1e+7) + (5e+6)
    # norm = matplotlib.colors.LogNorm(vmin=y_tick_min, vmax=y_tick_max)
    norm = matplotlib.colors.Normalize(vmin=y_tick_min, vmax=y_tick_max)
    mappable = ScalarMappable(cmap=cmap, norm=norm)
    mappable._A = []

    fig = plt.figure(figsize=(24, 13))

    ax1 = fig.add_subplot(232, projection=Axes3D.name)
    ax2 = fig.add_subplot(233, projection=Axes3D.name)
    ax3 = fig.add_subplot(235, projection=Axes3D.name)
    ax4 = fig.add_subplot(236, projection=Axes3D.name)

    def update(ifrm, xa, ya, za, wa, va, ua):
        ax1.cla()
        ax2.cla()
        ax3.cla()
        ax4.cla()
        for particle in range(n_particles):
            # ax1
            ax1.scatter(xa[ifrm][particle],
                        ya[ifrm][particle],
                        za[ifrm][particle],
                        s=100,
                        color=cmap(norm(va[ifrm][particle])),
                        marker='o')
            ax1.set_title('Particle XYZ iterations = ' + str(ifrm + 1) +
                          " Global best =" + str(np.max(ua[ifrm])),
                          y=1.0)
            ax1.set_xlim(0, range_max[0])
            ax1.set_ylim(0, range_max[1])
            ax1.set_zlim(0, range_max[2])
            ax1.set_xlabel('PV capacity[kW]')
            ax1.set_ylabel('Wind capacity[kW]')
            ax1.set_zlabel('Battery capacity[kW]')
            # ax2
            ax2.scatter(xa[ifrm][particle],
                        ya[ifrm][particle],
                        wa[ifrm][particle],
                        s=100,
                        color=cmap(norm(va[ifrm][particle])),
                        marker='o')
            ax2.set_title('Particle movement XYW iterations = ' +
                          str(ifrm + 1) + " Global best =" +
                          str(np.max(ua[ifrm])),
                          y=1.0)
            ax2.set_xlim(0, range_max[0])
            ax2.set_ylim(0, range_max[1])
            ax2.set_zlim(0, range_max[3])
            ax2.set_xlabel('PV capacity[kW]')
            ax2.set_ylabel('Wind capacity[kW]')
            ax2.set_zlabel('Diesel capacity[kW]')
            # ax3
            ax3.scatter(xa[ifrm][particle],
                        za[ifrm][particle],
                        wa[ifrm][particle],
                        s=100,
                        color=cmap(norm(va[ifrm][particle])),
                        marker='o')
            ax3.set_title('Particle movement XZW iterations = ' +
                          str(ifrm + 1) + " Global best =" +
                          str(np.max(ua[ifrm])),
                          y=1.0)
            ax3.set_xlim(0, range_max[0])
            ax3.set_ylim(0, range_max[2])
            ax3.set_zlim(0, range_max[3])
            ax3.set_xlabel('PV capacity[kW]')
            ax3.set_ylabel('Battery capacity[kW]')
            ax3.set_zlabel('Diesel capacity[kW]')

            # ax4
            ax4.scatter(ya[ifrm][particle],
                        za[ifrm][particle],
                        wa[ifrm][particle],
                        s=100,
                        color=cmap(norm(va[ifrm][particle])),
                        marker='o')
            ax4.set_title('Particle movement YZW iterations = ' +
                          str(ifrm + 1) + " Global best =" +
                          str(np.max(ua[ifrm])),
                          y=1.0)
            ax4.set_xlim(0, range_max[1])
            ax4.set_ylim(0, range_max[2])
            ax4.set_zlim(0, range_max[3])
            ax4.set_xlabel('Wind capacity[kW]')
            ax4.set_ylabel('Battery capacity[kW]')
            ax4.set_zlabel('Diesel capacity[kW]')

    colorbar_ax = fig.add_axes([0.3, 0.1, 0.05, 0.7])
    colorbar = fig.colorbar(mappable, cax=colorbar_ax, shrink=0.5)
    colorbar.set_label('Objective function[yen]')

    ani = animation.FuncAnimation(fig,
                                  update,
                                  nfr,
                                  fargs=(xs, ys, zs, ws, vs, us),
                                  interval=1000 / fps)

    # Set up formatting for the movie files
    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=fps / 2, metadata=dict(artist='Yuichiro'))

    ani.save("Result/" + str(PSO.Multiprocessing_parameters["state_name"]) +
             'plot_3d_scatter_funcanimation.mp4',
             writer=writer)
    ani.save("Result/" + str(PSO.Multiprocessing_parameters["state_name"]) +
             'plot_3d_scatter_funcanimation.gif',
             writer="imagemagick")

    s = ani.to_jshtml()
    with open(
            "Result/" + str(PSO.Multiprocessing_parameters["state_name"]) +
            'plot_3d_scatter_funcanimation.html', 'w') as f:
        f.write(s)
Example #4
0
                marker=marks[num],alpha = alptmp,label=regionsE[num])
        else:
            if depthc == 'on':
                ax1.scatter(tmpXY[xptype],tmpXY[yptype],c=tmpXY['Depth'],\
                marker=marks[num],label=regionsE[num],vmin=vmin,vmax=vmax,cmap=cm.jet,alpha = alptmp)
            else:
                ax1.scatter(tmpXY[xptype],tmpXY[yptype],\
                marker=marks[num],alpha = alptmp,label=regionsE[num])

        ax1.set_xlim(xlim)
        ax1.set_ylim(ylim)
        ax1.set_xscale(xscale)
        ax1.set_yscale(yscale)

        num = num + 1

    ax1.set_title(xptype + '(X) vs ' + yptype + '(Y)')

    mappable = ScalarMappable(cmap='jet', norm=Normalize(vmin=vmin, vmax=vmax))
    mappable._A = []

    if depthc == 'on':
        fig1.colorbar(mappable).set_label('Depth (km)')

    plt.tight_layout()
    plt.grid()
    plt.legend()
    fig1.savefig(path + 'Figs/ken' + str(numi) + '.png')

plt.show()
def plot_tree(tree, feature, outputpath, font_size=14, line_type="-", vt_line_width=0.5, hz_line_width=0.2,
              max_circle_size=20, min_circle_size=4):
    node_list = tree.iter_descendants(strategy='postorder')
    node_list = chain(node_list, [tree])
    print(feature + "\n" + outputpath)
    vlinec, vlines, vblankline, hblankline, nodes, nodex, nodey = [], [], [], [], [], [], []

    if len(tree) < 50:
        fig = plt.figure(figsize=(16, 9))
    elif len(tree) < 70:
        fig = plt.figure(figsize=(16, 12))
    else:
        fig = plt.figure(figsize=(16, 16))
    ax = fig.add_subplot(111)

    min_annot = min(get_annot(n, feature) for n in tree.iter_leaves() if feature in n.features)
    max_annot = max(get_annot(n, feature) for n in tree.iter_leaves() if feature in n.features)

    cmap = plt.get_cmap("inferno")
    norm = colors.LogNorm(vmin=min_annot, vmax=max_annot)
    color_map = ScalarMappable(norm=norm, cmap=cmap)

    node_pos = dict((n2, i) for i, n2 in enumerate(tree.get_leaves()[::-1]))

    max_name_size = max(len(n.name) for n in tree)
    # draw tree
    rows = []
    for n in node_list:
        x = sum(n2.dist for n2 in n.iter_ancestors()) + n.dist

        min_node_annot, max_node_annot = False, False
        if (feature + "_min" in n.features) and (feature + "_max" in n.features):
            min_node_annot = get_annot(n, feature + "_min")
            max_node_annot = get_annot(n, feature + "_max")

        if n.is_leaf():
            y = node_pos[n]

            node_name = " " + n.name
            row = {"Taxon": n.name}
            if len(n.name) != max_name_size:
                node_name += " " * (max_name_size - len(n.name))
            if feature in n.features:
                node_name += " " + format_float(get_annot(n, feature))
                row[feature] = get_annot(n, feature)
            if min_node_annot and max_node_annot:
                node_name += " [{0},{1}]".format(format_float(min_node_annot), format_float(max_node_annot))
                row[feature + "Lower"] = min_node_annot
                row[feature + "Upper"] = max_node_annot
            ax.text(x, y, node_name, va='center', size=font_size, name="Latin Modern Mono")
            rows.append(row)
        else:
            y = np.mean([node_pos[n2] for n2 in n.children])
            node_pos[n] = y

            if feature in n.features:
                node_annot = get_annot(n, feature)
                # draw vertical line
                vlinec.append(((x, node_pos[n.children[0]]), (x, node_pos[n.children[-1]])))
                vlines.append(node_annot)

                # draw horizontal lines
                for child in n.children:
                    child_annot = get_annot(child, feature)
                    h = node_pos[child]
                    xs = [[x, x], [x + child.dist, x + child.dist]]
                    ys = [[h - hz_line_width, h + hz_line_width], [h - hz_line_width, h + hz_line_width]]
                    zs = [[node_annot, node_annot], [child_annot, child_annot]]
                    ax.pcolormesh(xs, ys, zs, cmap=cmap, norm=norm, shading="gouraud")
            else:
                vblankline.append(((x, node_pos[n.children[0]]), (x, node_pos[n.children[-1]])))
                for child in n.children:
                    h = node_pos[child]
                    hblankline.append(((x, h), (x + child.dist, h)))

        nodex.append(x)
        nodey.append(y)

    pd.DataFrame(rows).to_csv(outputpath[:-4] + ".tsv", index=None, header=rows[0].keys(), sep='\t')
    vline_col = LineCollection(vlinec, colors=[color_map.to_rgba(l) for l in vlines],
                               linestyle=line_type,
                               linewidth=vt_line_width * 2)
    ax.add_collection(LineCollection(hblankline, colors='black', linestyle=line_type, linewidth=hz_line_width * 2))
    ax.add_collection(LineCollection(vblankline, colors='black', linestyle=line_type, linewidth=vt_line_width * 2))
    ax.add_collection(vline_col)

    # scale line
    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()
    diffy = ymax - ymin
    dist = round((xmax - xmin) / 4, 1)
    padding = 200.
    ymin -= diffy / padding
    ax.plot([xmin, xmin + dist], [ymin, ymin], color='k')
    ax.plot([xmin, xmin], [ymin - diffy / padding, ymin + diffy / padding], color='k')
    ax.plot([xmin + dist, xmin + dist], [ymin - diffy / padding, ymin + diffy / padding],
            color='k')
    ax.text((xmin + xmin + dist) / 2, ymin - diffy / padding, dist, va='top',
            ha='center', size=font_size)

    ax.set_axis_off()
    # plt.tight_layout()
    color_map._A = []
    ticks = "PopulationSize" in feature or "MutationRatePerTime" in feature or "Omega" in feature
    cbar = fig.colorbar(color_map, ticks=(
        [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20,
         50] if ticks else None),
                        orientation='horizontal', pad=0, shrink=0.6)
    cbar.ax.xaxis.set_tick_params('major', labelsize=font_size * 1.8)
    cbar.ax.xaxis.set_tick_params('minor', labelsize=font_size)
    if ticks:
        cbar.ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
    cbar.ax.set_xlabel(label_transform(feature), labelpad=5, size=font_size * 1.8)
    plt.tight_layout()
    for o in fig.findobj():
        o.set_clip_on(False)
    plt.savefig(outputpath, format=outputpath[outputpath.rfind('.') + 1:], bbox_inches='tight')
    plt.close("all")