python类xlabel()的实例源码

mesa.py 文件源码 项目:NuGridPy 作者: NuGrid 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def hrd_key(self, key_str):
        """
        plot an HR diagram

        Parameters
        ----------
        key_str : string
            A label string

        """

        pyl.plot(self.data[:,self.cols['log_Teff']-1],\
                 self.data[:,self.cols['log_L']-1],label = key_str)
        pyl.legend()
        pyl.xlabel('log Teff')
        pyl.ylabel('log L')
        x1,x2=pl.xlim()
        if x2 > x1:
            self._xlimrev()
compare_image_entropy.py 文件源码 项目:NuGridPy 作者: NuGrid 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def compare_images(path = '.'):
     S_limit = 10.
     file_list = glob.glob(os.path.join(path, 'Abu*'))
     file_list_master = glob.glob(os.path.join(path, 'MasterAbu*'))
     file_list.sort()
     file_list_master.sort()
     S=[]
     print("Identifying images with rmq > "+'%3.1f'%S_limit)
     ierr_count = 0
     for i in range(len(file_list)):
         this_S,fimg1,fimg2 = compare_entropy(file_list[i],file_list_master[i])
         if this_S > S_limit:
              warnings.warn(file_list[i]+" and "+file_list_master[i]+" differ by "+'%6.3f'%this_S)
              ierr_count += 1
              S.append(this_S)
     if ierr_count > 0:
          print("Error: at least one image differs by more than S_limit")
          sys.exit(1)
     #print ("S: ",S)
     #plb.plot(S,'o')
     #plb.xlabel("image number")
     #plb.ylabel("modified log KL-divergence to previous image")
     #plb.show()
volcanoStats.py 文件源码 项目:TSS_detection 作者: ueser 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def plot_volcano(logFC,p_val,sample_name,saveName,logFC_thresh):
    fig=pl.figure()
    ## To plot and save
    pl.scatter(logFC[(p_val>0.05)|(abs(logFC)<logFC_thresh)],-np.log10(p_val[(p_val>0.05)|(abs(logFC)<logFC_thresh)]),color='blue',alpha=0.5);
    pl.scatter(logFC[(p_val<0.05)&(abs(logFC)>logFC_thresh)],-np.log10(p_val[(p_val<0.05)&(abs(logFC)>logFC_thresh)]),color='red');
    pl.hlines(-np.log10(0.05),min(logFC),max(logFC))
    pl.vlines(-logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
    pl.vlines(logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
    pl.xlim(-3,3)
    pl.xlabel('Log Fold Change')
    pl.ylabel('-log10(p-value)')
    pl.savefig(saveName)
    pl.close(fig)


# def plot_histograms(df_peaks,pntr_list):
#
#     for pntr in pntr_list:
#         colName =pntr[2]+'_Intragenic_position'
#         pl.hist(df_peaks[colName])
#         pl.xlabel(colName)
#         pl.ylabel()
#         pl.show()
lms.py 文件源码 项目:Spherical-robot 作者: Evan-Zhao 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def plot(l, x1, x2, y, e):
    # Plot
    time_range = numpy.arange(0, l)
    pl.figure(1)
    pl.subplot(221)
    pl.plot(time_range, x1)
    pl.title("Input signal")
    pl.subplot(222)
    pl.plot(time_range, x2, c="r")
    pl.plot(time_range, y, c="b")
    pl.title("Reference signal")
    pl.subplot(223)
    pl.plot(time_range, e, c="r")
    pl.title("Noise")
    pl.xlabel("time")
    pl.show()
visual.py 文件源码 项目:Spherical-robot 作者: Evan-Zhao 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def make_fft_graph(fft, corre):
    fft_np = numpy.array(fft).swapaxes(0, 1).swapaxes(1, 2)
    channel_N, freq_N, sample_N = fft_np.shape
    if (channel_N > 6):  # We don't have space for more than 6 channels
        return
    fig, axes = plt.subplots(2, 3)
    fig.subplots_adjust(hspace=0.3, wspace=0.05)
    for ax, mat, i in zip(axes.flat, fft_np, range(1, channel_N + 1)):
        fft_abs = numpy.abs(mat)
        fft_less_row = fft_abs[0::20]
        n = freq_N / 20
        fft_sqr = numpy.repeat(fft_less_row, int(n / sample_N)).reshape([n, n])
        ax.matshow(fft_sqr, cmap='viridis')
        plt.xlabel('time')
        plt.ylabel('freq')
        ax.set_title('Channel {0}'.format(i))
    plt.show()
    print("Plotted.")
trajectory.py 文件源码 项目:notebook-molecular-visualization 作者: Autodesk 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def plot(traj, x, y, **kwargs):
    """ Create a matplotlib plot of property x against property y

    Args:
        x,y (str): names of the properties
        **kwargs (dict): kwargs for :meth:`matplotlib.pylab.plot`

    Returns:
        List[matplotlib.lines.Lines2D]: the lines that were plotted

    """
    from matplotlib import pylab
    xl = yl = None
    if type(x) is str:
        strx = x
        x = getattr(traj, x)
        xl = '%s / %s' % (strx, getattr(x, 'units', 'dimensionless'))
    if type(y) is str:
        stry = y
        y = getattr(traj, y)
        yl = '%s / %s' % (stry, getattr(y, 'units', 'dimensionless'))
    plt = pylab.plot(x, y, **kwargs)
    pylab.xlabel(xl); pylab.ylabel(yl); pylab.grid()
    return plt
exp_utils.py 文件源码 项目:gcForest 作者: kingfengji 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plot_confusion_matrix(cm, label_list, title='Confusion matrix', cmap=None):
    from matplotlib import pylab
    cm = np.asarray(cm, dtype=np.float32)
    for i, row in enumerate(cm):
        cm[i] = cm[i] / np.sum(cm[i])
    #import matplotlib.pyplot as plt
    #plt.ion()
    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(label_list)))
    ax.set_xticklabels(label_list, rotation='vertical')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_yticks(range(len(label_list)))
    ax.set_yticklabels(label_list)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.xlabel('Predicted class')
    pylab.ylabel('True class')
    pylab.grid(False)
    pylab.savefig('test.jpg')
    pylab.show()
test_imu_state.py 文件源码 项目:prototype 作者: chutsu 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def plot_position(self, pos_true, pos_est):
        N = pos_est.shape[1]
        pos_true = pos_true[:, :N]
        pos_est = pos_est[:, :N]

        # Figure
        plt.figure()
        plt.suptitle("Position")

        # Ground truth
        plt.plot(pos_true[0, :], pos_true[1, :],
                 color="red", marker="o", label="Grouth truth")

        # Estimated
        plt.plot(pos_est[0, :], pos_est[1, :],
                 color="blue", marker="o", label="Estimated")

        # Plot labels and legends
        plt.xlabel("East (m)")
        plt.ylabel("North (m)")
        plt.axis("equal")
        plt.legend(loc=0)
Drawing.py 文件源码 项目:options 作者: mcmachado 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def plotLine(self, x_vals, y_vals, x_label, y_label, title, filename=None):
        plt.clf()

        plt.xlabel(x_label)
        plt.xlim(((min(x_vals) - 0.5), (max(x_vals) + 0.5)))
        plt.ylabel(y_label)
        plt.ylim(((min(y_vals) - 0.5), (max(y_vals) + 0.5)))

        plt.title(title)
        plt.plot(x_vals, y_vals, c='k', lw=2)
        #plt.plot(x_vals, len(x_vals) * y_vals[0], c='r', lw=2)

        if filename == None:
            plt.show()
        else:
            plt.savefig(self.outputPath + filename)
demo_mi.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def plot_entropy():
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))

    title = "Entropy $H(X)$"
    pylab.title(title)
    pylab.xlabel("$P(X=$coin will show heads up$)$")
    pylab.ylabel("$H(X)$")

    pylab.xlim(xmin=0, xmax=1.1)
    x = np.arange(0.001, 1, 0.001)
    y = -x * np.log2(x) - (1 - x) * np.log2(1 - x)
    pylab.plot(x, y)
    # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
    # [0,1,2,3,4]])

    pylab.autoscale(tight=True)
    pylab.grid(True)

    filename = "entropy_demo.png"
    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
plot_kmeans_example.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def plot_clustering(x, y, title, mx=None, ymax=None, xmin=None, km=None):
    pylab.figure(num=None, figsize=(8, 6))
    if km:
        pylab.scatter(x, y, s=50, c=km.predict(list(zip(x, y))))
    else:
        pylab.scatter(x, y, s=50)

    pylab.title(title)
    pylab.xlabel("Occurrence word 1")
    pylab.ylabel("Occurrence word 2")

    pylab.autoscale(tight=True)
    pylab.ylim(ymin=0, ymax=1)
    pylab.xlim(xmin=0, xmax=1)
    pylab.grid(True, linestyle='-', color='0.75')

    return pylab
utils.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot_confusion_matrix(cm, genre_list, name, title):
    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(genre_list)))
    ax.set_xticklabels(genre_list)
    ax.xaxis.set_ticks_position("bottom")
    ax.set_yticks(range(len(genre_list)))
    ax.set_yticklabels(genre_list)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.show()
    pylab.xlabel('Predicted class')
    pylab.ylabel('True class')
    pylab.grid(False)
    pylab.savefig(
        os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight")
utils.py 文件源码 项目:Building-Machine-Learning-Systems-With-Python-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def plot_roc(auc_score, name, tpr, fpr, label=None):
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))
    pylab.grid(True)
    pylab.plot([0, 1], [0, 1], 'k--')
    pylab.plot(fpr, tpr)
    pylab.fill_between(fpr, tpr, alpha=0.5)
    pylab.xlim([0.0, 1.0])
    pylab.ylim([0.0, 1.0])
    pylab.xlabel('False Positive Rate')
    pylab.ylabel('True Positive Rate')
    pylab.title('ROC curve (AUC = %0.2f) / %s' %
                (auc_score, label), verticalalignment="bottom")
    pylab.legend(loc="lower right")
    filename = name.replace(" ", "_")
    pylab.savefig(
        os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight")
kNN.py 文件源码 项目:statistical-learning-methods-note 作者: ysh329 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plotKChart(self, misClassDict, saveFigPath):
        kList = []
        misRateList = []
        for k, misClassNum in misClassDict.iteritems():
            kList.append(k)
            misRateList.append(1.0 - 1.0/k*misClassNum)

        fig = plt.figure(saveFigPath)
        plt.plot(kList, misRateList, 'r--')
        plt.title(saveFigPath)
        plt.xlabel('k Num.')
        plt.ylabel('Misclassified Rate')
        plt.legend(saveFigPath)
        plt.grid(True)
        plt.savefig(saveFigPath)
        plt.show()

################################### PART3 TEST ########################################
# ??
__init__.py 文件源码 项目:mlprojects-py 作者: srinathperera 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def show_feature_importance(gbdt, feature_names=None):
    importance = gbdt.get_fscore(fmap='xgb.fmap')
    importance = sorted(importance.items(), key=operator.itemgetter(1))

    df = pd.DataFrame(importance, columns=['feature', 'fscore'])
    df['fscore'] = df['fscore'] / df['fscore'].sum()
    print "feature importance", df

    if feature_names is not None:
        used_features = df['feature']
        unused_features = [f for f in feature_names if f not in used_features]
        print "[IDF]Unused features:", str(unused_features)

    plt.figure()
    df.plot()
    df.plot(kind='barh', x='feature', y='fscore', legend=False, figsize=(6, 10))
    plt.title('XGBoost Feature Importance')
    plt.xlabel('relative importance')
    plt.gcf().savefig('feature_importance_xgb.png')
backtest.py 文件源码 项目:marketcrush 作者: basaks 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def backtest(config_file, day_trade):
    cfg = config.Config(config_file)
    cfg.day_trade = day_trade
    dfs = load_data(config_file)
    trender = strategies[cfg.strategy](**cfg.strategy_parameters)
    res = []
    for df in dfs:
        res.append(trender.backtest(data_frame=df))
    final_panel = pd.Panel({os.path.basename(p['path']): df for p, df in
                            zip(cfg.data_path, res)})
    profit_series = final_panel.sum(axis=0)['total_profit'].cumsum()
    final_panel.to_excel(cfg.output_file)

    if cfg.show:
        profit_series.plot()
        plt.xlabel('Time')
        plt.ylabel('Profit')
        plt.legend('Profit')
        plt.show()
fit_logic_standalone.py 文件源码 项目:qudi 作者: Ulm-IQO 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def fit_data():
    data=np.loadtxt('data.dat')
    print(data)
    params = dict()
    params["c"] = {"min" : -np.inf,"max" : np.inf}
    result = qudi_fitting.make_lorentzian_fit(axis=data[:,0], data=data[:,3], add_parameters=params)
    print(result.fit_report())
    plt.plot(data[:,0],-data[:,3]+2,"b-o",label="data mean")
#    plt.plot(data[:,0],data[:,1],label="data")
#    plt.plot(data[:,0],data[:,2],label="data")
    plt.plot(data[:,0],-result.best_fit+2,"r-",linewidth=2.,label="fit")
#    plt.plot(data[:,0],result.init_fit,label="init")
    plt.xlabel("time (ns)")
    plt.ylabel("polarization transfer (arb. u.)")
    plt.legend(loc=1)
#    plt.savefig("pol20_24repetition_pol.pdf")
#    plt.savefig("pol20_24repetition_pol.png")
    plt.show()
    savedata=[[data[ii,0],-data[ii,3]+2,-result.best_fit[ii]+2] for ii in range(len(data[:,0]))]
    np.savetxt("pol_data_fit.csv",savedata)
#    print(result.params)

    print(result.params)
tools.py 文件源码 项目:learning-class-invariant-features 作者: sbelharbi 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def plot_penalty_vl(debug, tag, fold_exp):
    plt.close("all")
    vl = np.array(debug["penalty"])
    fig = plt.figure(figsize=(15, 10.8), dpi=300)
    names = debug["names"]
    for i in range(vl.shape[1]):
        if vl.shape[1] > 1:
            plt.plot(vl[:, i], label="layer_"+str(names[i]))
        else:
            plt.plot(vl[:], label="layer_"+str(names[i]))
    plt.xlabel("mini-batchs")
    plt.ylabel("value of penlaty")
    plt.title(
        "Penalty value over layers:" + "_".join([str(k) for k in names]) +
        ". tag:" + tag)
    plt.legend(loc='upper right', fancybox=True, shadow=True, prop={'size': 8})
    plt.grid(True)
    fig.savefig(fold_exp+"/penalty.png", bbox_inches='tight')
    plt.close('all')
    del fig
tutorial_helpers.py 文件源码 项目:ml_sampler 作者: facebookincubator 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def plot_roc(y_test, y_pred, label=''):
    """Compute ROC curve and ROC area"""

    fpr, tpr, _ = roc_curve(y_test, y_pred)
    roc_auc = auc(fpr, tpr)

    # Plot of a ROC curve for a specific class
    plt.figure()
    plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
    plt.plot([0, 1], [0, 1], 'k--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic' + label)
    plt.legend(loc="lower right")
    plt.show()
utils.py 文件源码 项目:genrec 作者: kkanellis 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def plot_confusion_matrix(cm, plot_title, filename, genres=None):
    if not genres:
        genres = GENRES

    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=100.0)

    axes = pylab.axes()
    axes.set_xticks(range(len(genres)))
    axes.set_xticklabels(genres, rotation=45)

    axes.set_yticks(range(len(genres)))
    axes.set_yticklabels(genres)
    axes.xaxis.set_ticks_position("bottom")

    pylab.title(plot_title, fontsize=14)
    pylab.colorbar()
    pylab.xlabel('Predicted class', fontsize=12)
    pylab.ylabel('Correct class', fontsize=12)
    pylab.grid(False)
    #pylab.show()
    pylab.savefig(os.path.join(PLOTS_DIR, "cm_%s.eps" % filename), bbox_inches="tight")
exp_utils.py 文件源码 项目:gcforest 作者: w821881341 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def plot_confusion_matrix(cm, label_list, title='Confusion matrix', cmap=None):
    from matplotlib import pylab
    cm = np.asarray(cm, dtype=np.float32)
    for i, row in enumerate(cm):
        cm[i] = cm[i] / np.sum(cm[i])
    #import matplotlib.pyplot as plt
    #plt.ion()
    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(label_list)))
    ax.set_xticklabels(label_list, rotation='vertical')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_yticks(range(len(label_list)))
    ax.set_yticklabels(label_list)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.xlabel('Predicted class')
    pylab.ylabel('True class')
    pylab.grid(False)
    pylab.savefig('test.jpg')
    pylab.show()
RunBenchmark.py 文件源码 项目:bnpy 作者: bnpy 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def plotSpeedupFigure(AllInfo, maxWorker=1, **kwargs):
    pylab.figure(2)
    xs = AllInfo['nWorker']
    ts_mono = AllInfo['t_monolithic']

    xgrid = np.linspace(0, maxWorker + 0.1, 100)
    pylab.plot(xgrid, xgrid, 'y--', label='ideal parallel')

    for method in getMethodNames(**kwargs):
        speedupRatio = ts_mono / AllInfo['t_' + method]
        pylab.plot(xs, speedupRatio, 'o-',
                   label=method,
                   color=ColorMap[method],
                   markeredgecolor=ColorMap[method])

    pylab.xlim([-0.2, maxWorker + 0.5])
    pylab.ylim([0, maxWorker + 0.5])
    pylab.legend(loc='upper left')
    pylab.xlabel('Number of Workers')
    pylab.ylabel('Speedup over Monolithic')
TestSurrogateBound.py 文件源码 项目:bnpy 作者: bnpy 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def plotBoundVsAlph(alphaVals=np.linspace(.001, 3, 1000),
                    beta1=0.5):
    exactVals = cD_exact(alphaVals, beta1)
    boundVals = cD_bound(alphaVals, beta1)

    assert np.all(exactVals >= boundVals)
    pylab.plot(alphaVals, exactVals, 'k-', linewidth=LINEWIDTH)
    pylab.plot(alphaVals, boundVals, 'r--', linewidth=LINEWIDTH)
    pylab.xlabel("alpha", fontsize=FONTSIZE)
    pylab.ylabel("  ", fontsize=FONTSIZE)
    pylab.xlim([np.min(alphaVals) - 0.1, np.max(alphaVals) + 0.1])
    pylab.ylim([np.min(exactVals) - 0.05, np.max(exactVals) + 0.05])
    pylab.xticks(np.arange(np.max(alphaVals) + 1))

    pylab.legend(['c_D exact',
                  'c_D surrogate'],
                 fontsize=LEGENDSIZE,
                 loc='lower right')
    pylab.tick_params(axis='both', which='major', labelsize=TICKSIZE)
code.py 文件源码 项目:COMSW4721_MachineLearning_HomeWork 作者: aarshayj 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def nmf(fdoc, fvocab):
    T = 100

    nmf = NMF(fdoc, fvocab)
    nmf.train(T)
    nmf.get_words()
    # print(mf.R)

    plt.figure()
    plt.plot(range(1,T+1),nmf.objective)
    plt.xticks(np.linspace(1,T,10))
    plt.xlabel('Iterations')
    plt.ylabel('Objective')
    plt.title('Variation of objective with iterations')
    plt.savefig('hw5_2a.png')
    plt.show()
code.py 文件源码 项目:COMSW4721_MachineLearning_HomeWork 作者: aarshayj 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def gp_partd(Xtrain,ytrain,Xtest,ytest):
    gp = gaussian_process(Xtrain[:,3],ytrain,Xtrain[:,3],ytrain)


    gp.init_kernel_matrices(b=5,var=2)
    gp.predict_test()

    x = np.asarray(Xtrain[:,3]).flatten()
    xsortind = np.argsort(x)
    y1 = np.asarray(ytrain).flatten()
    y2 = np.asarray(gp.test_predictions).flatten()
    plt.figure()
    plt.scatter(x[xsortind],y1[xsortind])
    plt.plot(x[xsortind],y2[xsortind],'b-')
    plt.xlabel('Car Weight (Dimension 4)')
    plt.ylabel('Outcome')
    plt.title('Visualizing model through single dimension')
    plt.savefig('hw3_gaussian_dim4_viz')
    plt.show()
mesa.py 文件源码 项目:NuGridPy 作者: NuGrid 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def energy_profile(self,ixaxis):
        """
            Plot radial profile of key energy generations eps_nuc,
            eps_neu etc.

            Parameters
            ----------
            ixaxis : 'mass' or 'radius'
        """

        mass = self.get('mass')
        radius = self.get('radius') * ast.rsun_cm
        eps_nuc = self.get('eps_nuc')
        eps_neu = self.get('non_nuc_neu')

        if ixaxis == 'mass':
            xaxis = mass
            xlab = 'Mass / M$_\odot$'
        else:
            xaxis = old_div(radius, 1.e8) # Mm
            xlab = 'radius / Mm'

        pl.plot(xaxis, np.log10(eps_nuc),
                'k-',
                label='$\epsilon_\mathrm{nuc}>0$')
        pl.plot(xaxis, np.log10(-eps_nuc),
                'k--',
                label='$\epsilon_\mathrm{nuc}<0$')
        pl.plot(xaxis, np.log10(eps_neu),
                'r-',
                label='$\epsilon_\\nu$')

        pl.xlabel(xlab)
        pl.ylabel('$\log(\epsilon_\mathrm{nuc},\epsilon_\\nu)$')
        pl.legend(loc='best').draw_frame(False)
mesa.py 文件源码 项目:NuGridPy 作者: NuGrid 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def hrd_new(self, input_label="", skip=0):
        """
        plot an HR diagram with options to skip the first N lines and
        add a label string

        Parameters
        ----------
        input_label : string, optional
            Diagram label.  The default is "".
        skip : integer, optional
            Skip the first n lines.  The default is 0.

        """
        xl_old=pyl.gca().get_xlim()
        if input_label == "":
            my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])
        else:
            my_label="M="+str(self.header_attr['initial_mass'])+", Z="+str(self.header_attr['initial_z'])+"; "+str(input_label)

        pyl.plot(self.data[skip:,self.cols['log_Teff']-1],self.data[skip:,self.cols['log_L']-1],label = my_label)
        pyl.legend(loc=0)
        xl_new=pyl.gca().get_xlim()
        pyl.xlabel('log Teff')
        pyl.ylabel('log L')
        if any(array(xl_old)==0):
            pyl.gca().set_xlim(max(xl_new),min(xl_new))
        elif any(array(xl_new)==0):
            pyl.gca().set_xlim(max(xl_old),min(xl_old))
        else:
            pyl.gca().set_xlim([max(xl_old+xl_new),min(xl_old+xl_new)])
mesa.py 文件源码 项目:NuGridPy 作者: NuGrid 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def t_lumi(self,num_frame,xax):
        """
        Luminosity evolution as a function of time or model.

        Parameters
        ----------
        num_frame : integer
            Number of frame to plot this plot into.
        xax : string
            Either model or time to indicate what is to be used on the
            x-axis

        """

        pyl.figure(num_frame)

        if xax == 'time':
            xaxisarray = self.get('star_age')
        elif xax == 'model':
            xaxisarray = self.get('model_number')
        else:
            print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"')


        logLH   = self.get('log_LH')
        logLHe  = self.get('log_LHe')

        pyl.plot(xaxisarray,logLH,label='L_(H)')
        pyl.plot(xaxisarray,logLHe,label='L(He)')
        pyl.ylabel('log L')
        pyl.legend(loc=2)


        if xax == 'time':
            pyl.xlabel('t / yrs')
        elif xax == 'model':
            pyl.xlabel('model number')
mesa.py 文件源码 项目:NuGridPy 作者: NuGrid 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def t_surf_parameter(self, num_frame, xax):
        """
        Surface parameter evolution as a function of time or model.

        Parameters
        ----------
        num_frame : integer
            Number of frame to plot this plot into.
        xax : string
            Either model or time to indicate what is to be used on the
            x-axis

        """

        pyl.figure(num_frame)

        if xax == 'time':
            xaxisarray = self.get('star_age')
        elif xax == 'model':
            xaxisarray = self.get('model_number')
        else:
            print('kippenhahn_error: invalid string for x-axis selction. needs to be "time" or "model"')


        logL    = self.get('log_L')
        logTeff    = self.get('log_Teff')

        pyl.plot(xaxisarray,logL,'-k',label='log L')
        pyl.plot(xaxisarray,logTeff,'-k',label='log Teff')
        pyl.ylabel('log L, log Teff')
        pyl.legend(loc=2)


        if xax == 'time':
            pyl.xlabel('t / yrs')
        elif xax == 'model':
            pyl.xlabel('model number')
selftest.py 文件源码 项目:NuGridPy 作者: NuGrid 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_abu_evolution(self):
        from nugridpy import ppn, utils
        import matplotlib
        matplotlib.use('agg')
        import matplotlib.pylab as mpy
        import os

        # Perform tests within temporary directory
        with TemporaryDirectory() as tdir:
            # wget the data for a ppn run from the CADC VOspace
            os.system("wget -q --content-disposition --directory '" + tdir +  "' "\
                          + "'http://www.canfar.phys.uvic.ca/vospace/synctrans?TARGET="\
                          + "vos%3A%2F%2Fcadc.nrc.ca%21vospace%2Fnugrid%2Fdata%2Fprojects%2Fppn%2Fexamples%2F"\
                          + "ppn_Hburn_simple%2Fx-time.dat&DIRECTION=pullFromVoSpace&PROTOCOL"\
                          + "=ivo%3A%2F%2Fivoa.net%2Fvospace%2Fcore%23httpget'")

            #nugrid_dir= os.path.dirname(os.path.dirname(ppn.__file__))
            #NuPPN_dir= nugrid_dir + "/NuPPN"
            #test_data_dir= NuPPN_dir + "/examples/ppn_Hburn_simple/RUN_MASTER"

            symbs=utils.symbol_list('lines2')
            x=ppn.xtime(tdir)
            specs=['PROT','HE  4','C  12','N  14','O  16']
            i=0
            for spec in specs:
                x.plot('time',spec,logy=True,logx=True,shape=utils.linestyle(i)[0],show=False,title='')
                i += 1
            mpy.ylim(-5,0.2)
            mpy.legend(loc=0)
            mpy.xlabel('$\log t / \mathrm{min}$')
            mpy.ylabel('$\log X \mathrm{[mass fraction]}$')
            abu_evol_file = 'abu_evolution.png'
            mpy.savefig(abu_evol_file)
            self.assertTrue(os.path.exists(abu_evol_file))


问题


面经


文章

微信
公众号

扫码关注公众号