def subPlotter_4(df, i):
    a = ['Study-1', 'Study-2', 'Study-3', 'Study-4']
    #a = ['Ballast','Subballast','Subgrade']
    axs[i]
    axs[i].set_title(a[i])
    axs[i].set_xticks([100, 200, 400, 600])
    axs[i].tick_params(direction="in", labelsize=8)
    axs[i].plot(df.iloc[:, 0],
                df.iloc[:, 1],
                marker='',
                markerfacecolor='blue',
                markersize=2,
                color='black',
                linewidth=2,
                linestyle=':',
                label="Ballast")
    axs[i].plot(df.iloc[:, 0],
                df.iloc[:, 2],
                marker='',
                markerfacecolor='blue',
                markersize=2,
                color='black',
                linewidth=2,
                linestyle='--',
                label="Subballast")
    axs[i].plot(df.iloc[:, 0],
                df.iloc[:, 3],
                marker='',
                markerfacecolor='blue',
                markersize=2,
                color='black',
                linewidth=2,
                linestyle='-.',
                label="Subgrade")
    axs[i].yaxis.set_major_formatter(fsf('%.2f'))
def create_chart(x_pos, y_afr, y_amr, y_asn, y_eur, x_label, y_label,
                 sourcefile, cur_chr_num):

    #Построение диаграммы из четырёх наборов координат.
    plt.scatter(x_pos, y_afr, label='afr')
    plt.scatter(x_pos, y_amr, label='amr')
    plt.scatter(x_pos, y_asn, label='asn')
    plt.scatter(x_pos, y_eur, label='eur')

    #Главные деления (major ticks) по оси X будут обозначаться целыми числами.
    plt.gca().xaxis.set_major_formatter(fsf('%d'))

    #Устанавливаем такой размер шрифта подписей к делениям, чтобы после сохранения методом savefig() они не наползали друг на друга.
    plt.gca().tick_params(labelsize=5)

    #Сетка, соответствующая главным делениям.
    plt.grid(True)

    #Названия осей, взятые из шапки HaploReg-таблицы.
    plt.xlabel(x_label)
    plt.ylabel(y_label)

    #Формирование легенды из "лейблов", указанных в качестве аргумента функции построения диаграммы.
    #Легенда будет расположена внизу слева относительно области рисования.
    #Задаём такой шрифт, чтобы легенда не срезалась и не наползла на область рисования.
    plt.legend(loc=(-0.15, 0.0), fontsize=5)

    #Заголовок графика будет содержать название текущего HaploReg-файла и текущий номер хромосомы.
    plt.title(os.path.basename(sourcefile) + '; Хромосома ' + str(cur_chr_num))

    #Сохранение графика в формате svg.
    targetfile = sourcefile.split('.')[0] + '_chr' + str(cur_chr_num) + '.svg'
    plt.savefig(os.path.join(targetdir, targetfile), format='svg')
    plt.close()
Beispiel #3
0
def setup_subplot():
    r"""
	Setup a matplotlib subplot to plot on
	"""
    plt.clf()
    fig = plt.figure(figsize=(6, 6), facecolor="white")
    ax = fig.add_subplot(111)
    ax.set_xlabel(r"M$_\text{ZAMS}$ [M$_\odot$]")
    ax.set_ylabel(r"$\tau$ [Gyr]")
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.xaxis.set_major_formatter(fsf("%g"))
    ax.yaxis.set_major_formatter(fsf("%g"))
    ax.set_xlim([0.07, 150])
    ax.set_ylim([1.e-3, 1.e+3])
    ax.set_xticks([0.1, 1, 10, 100])
    ax.set_yticks([10**_ for _ in range(-3, 4)])
    return ax
Beispiel #4
0
def xticklabel_formatter(ax):
    r"""
	Format the x-tick labels to '%g'

	Parameters
	----------
	ax : subplot
		The subplot to apply the formatting to.
	"""
    ax.xaxis.set_major_formatter(fsf("%g"))
def subPlotter_4(df, i, j):
    #plott = plt.figure()
    #plt.figure()
    a = ['BC-1', 'BC-2', 'BC-3']
    b = ['Ballast', 'Subballast', 'Subgrade']
    axs[i, j]
    axs[i, j].set_title(a[i] + ', ' + b[j])
    axs[i, j].set_xticks([100, 200, 400, 600])
    #axs[i, j].set_ylim(0,0.4)
    #axs[i, j].set_yticks([0,0.1,0.2,0.3])
    axs[i, j].tick_params(direction="in", labelsize=8)
    axs[i, j].plot(df.iloc[:, 0],
                   df.iloc[:, 1],
                   marker='',
                   markerfacecolor='blue',
                   markersize=2,
                   color='black',
                   linewidth=2,
                   linestyle=':',
                   label="Case 1")
    axs[i, j].plot(df.iloc[:, 0],
                   df.iloc[:, 2],
                   marker='',
                   markerfacecolor='blue',
                   markersize=2,
                   color='black',
                   linewidth=2,
                   linestyle='--',
                   label="Case 2")
    axs[i, j].plot(df.iloc[:, 0],
                   df.iloc[:, 3],
                   marker='',
                   markerfacecolor='blue',
                   markersize=2,
                   color='black',
                   linewidth=2,
                   linestyle='-.',
                   label="Case 3")
    axs[i, j].plot(df.iloc[:, 0],
                   df.iloc[:, 4],
                   marker='',
                   markerfacecolor='black',
                   markersize=3,
                   color='black',
                   linewidth=1,
                   linestyle='-',
                   label="Case 4")
    axs[i, j].yaxis.set_major_formatter(fsf('%.2f'))
def subPlotter_8(df, i, axs):
    a = ['Ballast', 'Subballast',
         'Subgrade']  #['Study-1','Study-2','Study-3','Study-4']
    axs[i]
    axs[i].set_title(a[i])
    axs[i].set_xticks([0, 25, 50, 75, 100, 125, 150, 175, 200])
    axs[i].tick_params(direction="in", labelsize=8)
    axs[i].plot(df.iloc[:, 0],
                df.iloc[:, 1],
                marker='',
                markerfacecolor='blue',
                markersize=2,
                color='black',
                linewidth=2,
                linestyle=':',
                label="Study-1")
    axs[i].plot(df.iloc[:, 0],
                df.iloc[:, 2],
                marker='',
                markerfacecolor='blue',
                markersize=2,
                color='black',
                linewidth=2,
                linestyle='--',
                label="Study-2")
    axs[i].plot(df.iloc[:, 0],
                df.iloc[:, 3],
                marker='',
                markerfacecolor='blue',
                markersize=2,
                color='black',
                linewidth=2,
                linestyle='-.',
                label="Study-3")
    axs[i].plot(df.iloc[:, 0],
                df.iloc[:, 3],
                marker='',
                markerfacecolor='black',
                markersize=3,
                color='black',
                linewidth=1,
                linestyle='-',
                label="Study-4")
    axs[i].yaxis.set_major_formatter(fsf('%.2f'))
Beispiel #7
0
                    label=r"$N\Delta t^{-2}$ expected fit")[0]
    ax.legend(loc=1, ncol=1, frameon=False, bbox_to_anchor=(0.98, 0.98))
    dummy.remove()


def best_fit(nelem):
    """ 
	Obtain the expected fit for a given number of elements 
	"""
    return lambda t: 4.2 * nelem * (1.e-3 / t)**2


if __name__ == "__main__":
    ax = setup_subplot()
    for i in range(len(N)):
        draw(OUTPUTS[i], ax, COLORS[i], N[i])
    legend(ax)
    ax.text(0.01,
            300,
            "T = 10 Gyr",
            fontsize=25,
            color=mpl.colors.get_named_colors_mapping()["black"])
    ax.set_xlim([3.3e-4, 0.06])
    ax.set_ylim([0.025, 1500])
    ax.xaxis.set_major_formatter(fsf("%g"))
    ax.yaxis.set_major_formatter(fsf("%g"))
    plt.tight_layout()
    plt.savefig("timer.pdf")
    plt.savefig("timer.png")
    plt.clf()
    def calculate_AMF(self, w, w_pmids, AMF_G, lat, lon, plotname=None, debug_levels=False):
        '''
        Return AMF calculated using normalized shape factors
        uses both S_z and S_sigma integrations

        Determines
            AMF_z = \int_0^{\infty} { w(z) S_z(z) dz }
            AMF_s = \int_0^1 { w(s) S_s(s) ds } # this one uses sigma dimension
            AMF_Chris = \Sigma_i (Shape(P_i) * \omega(P_i) * \Delta P_i) /  \Sigma_i (Shape(P_i) * \omega(P_i) )

        update:20161109
            Chris AMF calculated, along with normal calculation without AMF_G
            lowest level fix now moved to a function to make this method more readable
        update:20160905
            Fix lowest level of both GC box and OMI pixel to match the pressure
            of the least low of the two levels, and remove any level which is
            entirely below the other column's lowest level.
        update:20160829
            LEFT AND RIGHT NOW SET TO 0 ()
        OLD:
            Determine AMF_z using AMF_G * \int_0^{\infty} { w(z) S_z(z) dz }
            Determine AMF_sigma using AMF_G * \int_0^1 { w(s) S_s(s) ds }

        '''
        # column index, pressures, altitudes, sigmas:
        #
        lati, loni=self.get_latlon_inds(lat,lon)
        S_pmids=self.pmids[:,lati,loni].copy()  # Pressures (hPa)

        S_zmids=self.zmids[:,lati,loni]         # Altitudes (m)
        S_smids=self.sigmas[:,lati,loni]        # Sigmas
        h=self.boxH[:,lati,loni]                # box heights (m)
        S_pedges=self.pedges[:,lati,loni].copy()# Pressure edges(hPa)

        # The shape factors!
        S_z=self.Shape_z[:,lati,loni].copy()
        S_s=self.Shape_s[:,lati,loni].copy()

        # Interpolate the shape factors to these new pressure levels:
        # S_s=np.interp(S_pmids, S_pmids_init[::-1], S_s[::-1])
        # also do S_z? currently I'm leaving this for comparison. AMF_z will be sanity check

        # calculate sigma edges
        S_sedges = (S_pedges - S_pedges[-1]) / (S_pedges[0]-S_pedges[-1])
        dsigma = S_sedges[0:-1]-S_sedges[1:]  # change in sigma at each level

        # Default left,right values (now zero)
        lv,rv=0.,0.

        # sigma midpoints for interpolation
        w_smids = (w_pmids - S_pedges[-1])/ (S_pedges[0]-S_pedges[-1])

        # convert w(press) to w(z) and w(s), on GEOS-Chem's grid
        #
        w_zmids = np.interp(w_pmids, S_pmids[::-1], S_zmids[::-1])
        w_z     = np.interp(S_zmids, w_zmids, w,left=lv,right=rv) # w_z does not account for differences between bottom levels of GC vs OMI pixel
        w_s     = np.interp(S_smids, w_smids[::-1], w[::-1],left=lv,right=rv)
        w_s_2   = np.interp(S_smids, w_smids[::-1], w[::-1]) # compare without fixed edges!

        # Integrate w(z) * S_z(z) dz using sum(w(z) * S_z(z) * height(z))
        AMF_z = np.sum(w_z * S_z * h)
        AMF_s= np.sum(w_s * S_s * dsigma)

        # Calculations with bottom relevelled
        # match he bottom levels in the pressure midpoints dimension
        w_pmids_new,S_pmids_new,w_new,S_s_new = match_bottom_levels(w_pmids,S_pmids,w,S_s)
        S_pedges_new = S_pedges.copy()
        for i in range(1,len(S_pedges_new)-1):
            S_pedges_new[i]=(S_pmids_new[i-1]*S_pmids_new[i]) ** 0.5
        S_sedges_new = (S_pedges_new - S_pedges_new[-1]) / (S_pedges_new[0]-S_pedges_new[-1])
        dsigma_new = S_sedges_new[0:-1]-S_sedges_new[1:]
        w_smids_new = (w_pmids_new - S_pedges_new[-1])/ (S_pedges_new[0]-S_pedges_new[-1])
        S_smids_new=(S_pmids_new - S_pedges_new[-1]) / (S_pedges_new[0]-S_pedges_new[-1])
        w_s_new     = np.interp(S_smids_new, w_smids_new[::-1], w_new[::-1], left=lv, right=rv)
        AMF_s_new = np.sum(w_s_new * S_s_new * dsigma_new)

        if plotname is not None:
            integral_s_old=np.sum(w_s_2 * S_s * dsigma)
            AMF_s_old= AMF_G * integral_s_old

            f,axes=plt.subplots(2,2,figsize=(14,12))
            # omega vs pressure, interpolated and not interpolated
            plt.sca(axes[0,0])
            plt.plot(w, w_pmids, linestyle='-',marker='o', linewidth=2, label='original',color='k')
            plt.title('$\omega$')
            plt.ylabel('p(hPa)'); plt.ylim([1015, 0.01]); plt.yscale('log')
            ax=plt.twinx(); ax.set_ylabel('z(m)'); plt.sca(ax)
            plt.plot(w_z, S_zmids, linestyle='-',marker='x', label='$\omega$(z)',color='fuchsia')
            # add legend from both axes
            h1,l1 = axes[0,0].get_legend_handles_labels()
            h2,l2 = ax.get_legend_handles_labels()
            ax.legend(h1+h2, l1+l2,loc=0)

            # omega vs sigma levels
            plt.sca(axes[0,1])
            plt.plot(w_s, S_smids, '.')
            plt.title('$\omega(\sigma)$')
            plt.ylabel('$\sigma$')
            plt.yscale('log')
            plt.ylim(1.01, 0.001)
            axes[0,1].yaxis.tick_right()
            axes[0,1].yaxis.set_label_position("right")
            # add AMF value to plot
            for yy,lbl in zip([0.6, 0.7, 0.8, 0.9], ['AMF$_z$=%5.2f'%AMF_z, 'AMF$_{\sigma}$=%5.2f'%AMF_s, 'AMF$_{\sigma}$(pre-fix)=%5.2f'%AMF_s_old, 'AMF$_{\sigma relevelled}$=%5.2f'%AMF_s_new]):
                plt.text(.1,yy,lbl,transform=axes[0,1].transAxes,fontsize=16)

            # shape factor z plots
            plt.sca(axes[1,0])
            plt.plot(S_z, S_pmids, '.',label='S$_z$(p)', color='k')
            plt.ylim([1015,0.01])
            plt.title('Shape')
            plt.ylabel('p(hPa)')
            plt.yscale('log')
            plt.xlabel('m$^{-1}$')
            # overplot omega*shape factor on second y axis
            ax=plt.twinx(); ax.set_ylabel('z(m)'); plt.sca(ax)
            plt.plot(S_z*w_z, S_zmids,label='$S_z(z) * \omega(z)$',color='fuchsia')
            # legend
            h1,l1 = axes[1,0].get_legend_handles_labels()
            h2,l2 = ax.get_legend_handles_labels()
            ax.legend(h1+h2,l1+l2,loc=0)
            axes[1,0].xaxis.set_major_formatter(fsf('%2.1e'))

            # sigma shape factor plots
            plt.sca(axes[1,1]);
            plt.title('Shape$_\sigma$')
            plt.plot(S_s, S_smids, label='S$_\sigma$', color='k')
            plt.plot(S_s*w_s, S_smids, label='S$_\sigma * \omega_\sigma$', color='fuchsia')
            plt.plot(S_s_new*w_s_new, S_smids_new, label='new S$_\sigma * \omega_\sigma$', color='orange')
            plt.plot(S_s*w_s_2, S_smids, '--', label='old product', color='cyan')
            plt.legend(loc=0)
            plt.ylim([1.05,-0.05])
            plt.ylabel('$\sigma$')
            plt.xlabel('unitless')

            plt.suptitle('amf calculation factors')
            f.savefig(plotname)
            print('%s saved'%plotname)
            plt.close(f)
        return (AMF_s, AMF_z)
def display_simulated_ef_with_random(results, weights_list, names):
    plt.style.use('fivethirtyeight')
    num_stocks = len(names)
    num_port = len(weights_list) - num_stocks

    max_sharpe_idx = np.argmax(results[2])
    sdp, rp = results[0, max_sharpe_idx], results[1, max_sharpe_idx]
    sharpe_max_weights = weights_list[max_sharpe_idx]
    data_list = {'allocation': sharpe_max_weights}
    sharpe_max_frame = pd.DataFrame(data_list, index=names)
    sharpe_max_frame.allocation = [
        round(i * 100, 2) for i in sharpe_max_frame.allocation
    ]
    sharpe_max_frame = sharpe_max_frame.T

    min_vol_idx = np.argmin(results[0])
    sdp_min, rp_min = results[0, min_vol_idx], results[1, min_vol_idx]
    sd_min_weights = weights_list[min_vol_idx]
    data_2_list = {'allocation': sd_min_weights}
    sd_min_frame = pd.DataFrame(data_2_list, index=names)
    sd_min_frame.allocation = [
        round(i * 100, 2) for i in sd_min_frame.allocation
    ]
    sd_min_frame = sd_min_frame.T

    print("=" * 50)
    print('\033[0;35;0m' + "Maximum Sharpe Ratio Portfolio Allocation\n" +
          '\033[0m')
    print("Annualised Return:", round(rp, 2), '% EAR')
    print("Annualised Volatility:", round(sdp, 5))
    print("\n")
    print(sharpe_max_frame)

    print("-" * 50)
    print('\033[0;35;0m' + "Minimum Volatility Portfolio Allocation\n" +
          '\033[0m')
    print("Annualised Return:", round(rp_min, 2), '% EAR')
    print("Annualised Volatility:", round(sdp_min, 5))
    print("\n")
    print(sd_min_frame)
    print("=" * 50 + '\n')

    time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' (CDT)'
    y_format = fsf('%1.1f')
    fig, ax = plt.subplots(figsize=(10, 7))
    # fig.text(5.0, 5.0, time_str, size=10, color='r')
    hb = ax.scatter(results[0, :],
                    results[1, :],
                    c=results[2, :],
                    cmap='YlGnBu',
                    marker='o',
                    s=10,
                    alpha=0.3)
    cbar = fig.colorbar(hb)
    cbar.ax.tick_params(labelsize=10)
    ax.scatter(sdp,
               rp,
               marker='x',
               color='r',
               s=150,
               label='Maximum Sharpe ratio')
    ax.scatter(sdp_min,
               rp_min,
               marker='x',
               color='limegreen',
               s=150,
               label='Minimum volatility')
    for i in range(num_stocks):
        ax.scatter(results[0, num_port + i],
                   results[1, num_port + i],
                   marker='o',
                   s=200,
                   color='dodgerblue')
        ax.annotate(names[i],
                    (results[0, num_port + i], results[1, num_port + i]),
                    xytext=(10, 0),
                    textcoords='offset points',
                    fontsize=10)
    ax.annotate(time_str, (max(results[0, :num_port]), min(results[1, :])),
                xytext=(10, 0),
                textcoords='offset points',
                fontsize=10,
                color='grey')
    ax.set_title('Portfolio Optimization based on Efficient Frontier\n',
                 fontdict={
                     'weight': 'normal',
                     'size': 15
                 })
    ax.set_xlabel('Annualised volatility', fontsize=13)
    ax.set_ylabel('Annualised returns', fontsize=13)
    ax.yaxis.set_major_formatter(y_format)
    ax.tick_params(labelsize=10)
    ax.legend(labelspacing=0.8, fontsize=10)

    plt.show()

    return sharpe_max_weights, sd_min_weights