Beispiel #1
0
 def __init__(self, fmt, set_label_fun=None, label_fmt=None, unit=None):
     FormatStrFormatter.__init__(self, fmt)
     self.engfmt = EngFormatter(unit="", places=2)
     self.set_label_fun = set_label_fun
     self.default_unit = unit
     self._label_unit = None
     self.set_label_fmt(label_fmt)
     self.label_template = None
Beispiel #2
0
 def __call__(self, x, pos=None):
     locs = [abs(y) for y in self.locs if abs(y) != 0]
     if locs and max(locs) / min(locs) <= 10000:
         _, exponent = _help_format_sci(max(locs), 2)
         div = 10 ** exponent
         for dig in range(3):
             digs = [abs((int((elem / div) * 10 ** dig) -
                         (elem / div) * 10 ** dig)) for elem in self.locs]
             if max(digs) < 0.001:
                 self.fmt = "%%.%df" % dig
                 break
         else:
             self.fmt = "%%.%df" % self.digs
         if self.set_label_fun and self.label_template:
             prefix = si_exp_to_prefixes.get(exponent, "q")
             if prefix == "q":
                 prefix = ""
                 div = 1
                 self.fmt = "%%.%de" % self.digs
             xlabel = self.label_template % dict(prefix=prefix,
                                                 powerprefix=exponent)
             self.set_label_fun(xlabel)
         return FormatStrFormatter.__call__(self, x / div, pos)
     else:
         self.engfmt.locs = self.locs
         return self.engfmt(x, pos)
Beispiel #3
0
 def __call__(self, x, pos=None):
     div = 1
     prefix = ""
     for dig in range(3):
         digs = [abs((int((elem / div) * 10 ** dig) -
                     (elem / div) * 10 ** dig)) for elem in self.locs]
         if max(digs) < 0.001:
             self.fmt = "%%.%df" % dig
             break
     else:
         self.fmt = "%.3f"
     if self.set_label_fun and self.label_template:
         xlabel = self.label_template % dict(prefix=prefix)
         self.set_label_fun(xlabel)
     return FormatStrFormatter.__call__(self, x / div, pos)
def plot_hist_w_stats(ax, x_data, x_name, x_units, res=50, norm=1.0,
                      weights=None, cum=False, htype="bar", align="mid",
                      rwidth=None, n_label="Fractional Counts", xmin=None,
                      xmax=None, nmin=None, nmax=None, xinc=6, ninc=6,
                      color="b", title=None, tloc="t", xl=True, xt=True,
                      yl=True, yt=True, moments=4, quartiles=3, modes=False,
                      sloc="il", *args, **kwargs):
    '''
    Creates a single histogram plot with a text box showing the desired stats.

    Input: ax        = axis handle
           x_data    = list or numpy array containing x-axis data
           x_name    = Label name of x-axis
           x_units   = Units for x-axis
           res       = Histogran bin resolution. A sequence can be used to
                       provide unequally spaced bins. (default=50)
           norm      = Histogram normalization (eg False, 100), (default=1.0)
           weights   = list or numpy array of the same dimention as x_data to
                       weight each x point contribution. (default=None)
           cum       = Cumulative or not? (default=False)
           htype     = Histogram type: bar, barstacked, step, stepfilled
                       (default="bar")
           align     = Bar alignment: left, mid, right (default="mid")
           rwidth    = Specifies the bar width for htype=bar,barstacked
                       (default=None)  
           n_label   = y-axis label
           xmin      = minimum value for x axis (default=None)
           xmax      = maximum value for x axis (default=None)
           nmin      = minimum value for y axis (default=None)
           nmax      = maximum value for y axis (default=None)
           xinc      = number of tick incriments for x variable (default 6)
           ninc      = number of tick incriments for y variable (default 6)
           color     = Color value (default="b", blue)
           title     = plot title (default is none)
           tloc      = title location: t=top, r=right, l=left, b=bottom
                       (default="t")
           xl        = Include x label (default is True)
           xt        = Include x ticks (default is True)
           yl        = Include y label (default is True)
           yt        = Include y ticks (default is True)
           moments   = Include moments (mean, standard deviation, skew,
                       kurtosis) of the distribution.  The number corresponds
                       to the maximum moment that will be included.  3, for
                       example, will include the mean, standard deviation, and
                       skew. (default=4)
           quartiles = Include quartiles (1st, 2nd=median, 3rd). 1=median only,
                       2=1st and 3rd only, 3=all (default=3)
           modes     = Include mode(s) (default=False)
           sloc      = Text location requires two specifiers. The first letter
                       may be i=inside plot, o=outside plot.  The second letter
                       may be r=right, l=left, b=bottom, t=top. (default="il")
    '''
    # Add histogram to specified subplot
    n,bins,patches=ax.hist(x_data, res, normed=norm, weights=weights,
                           cumulative=cum, histtype=htype, align=align,
                           rwidth=rwidth, color=color)

    # Set the x, and y ranges if desired
    if(xmin is None):
        xmin = np.nanmin(x_data)
    if(xmax is None):
        xmax = np.nanmax(x_data)

    if(nmin is None):
        nmin = np.nanmin(n)
    if(nmax is None):
        nmax = np.nanmax(n)

    # Configure axis
    if yt:
        width = (nmax - nmin) / ninc
        
	if width > 0.0:
    	    ytics = MultipleLocator(width)
            ax.yaxis.set_major_locator(ytics)
            if norm == 1.0:
                ax.yaxis.set_major_formatter(FormatStrFormatter("%1.2f"))
            elif norm == 100.0:
                ax.yaxis.set_major_formatter(FormatStrFormatter("%3.1f"))
    else:
        ax.yaxis.set_major_formatter(FormatStrFormatter(""))

    if yl:
        ax.set_ylabel(n_label)
    plt.ylim(nmin, nmax)

    if xt:
        width = (xmax - xmin) / xinc

	if width > 0.0:
	    xtics = MultipleLocator(width)
            ax.xaxis.set_major_locator(xtics)
    else:
        ax.xaxis.set_major_formatter(FormatStrFormatter(""))

    if xl:
        ax.set_xlabel(r'%s ($%s$)' % (x_name, x_units))
    plt.xlim(xmin, xmax)
           
    # Set the title
    if title:
        rot  = 'horizontal'
        yloc = 1.02
        xloc = 0.5

        if tloc == "b":
            yloc = -.1
        elif tloc == "t":
            yloc = .99
        else:
            rot  = 'vertical'
            yloc = 0.5
            xloc = -.2

            if tloc == "r":
                xloc = 1.1

        title = ax.set_title(title, x=xloc, y=yloc, size='medium', rotation=rot)
 
    # Add the statistics, if desired
    s, st = add_stat_box(ax, x_data, x_units, moments=moments,
                         quartiles=quartiles, modes=modes, loc=sloc)
    return(s, st)
Beispiel #5
0
root_path = os.path.dirname(os.path.abspath('__file__'))
# root_path = os.path.abspath(os.path.join(root_path,os.path.pardir)) # For run in CMD
graphs_path = root_path + '/results_analysis/graphs/'

huxian_vmd = pd.read_csv(root_path + '/Huaxian_vmd/data/VMD_TRAIN_K9.csv')
xianyang_vmd = pd.read_csv(root_path + '/Xianyang_vmd/data/VMD_TRAIN_K9.csv')
zhangjiashan_vmd = pd.read_csv(root_path +
                               '/Zhangjiashan_vmd/data/VMD_TRAIN_K8.csv')

T = huxian_vmd.shape[0]
t = np.arange(start=1, stop=T + 1, step=1, dtype=np.float) / T
freqs = t - 0.5 - 1 / T

plt.figure(figsize=(3.54, 2.0))
ax1 = plt.subplot(2, 2, 1)
ax1.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
# plt.xlabel('Time(month)')
plt.ylabel(r'$S_8$')
plt.plot(huxian_vmd['IMF8'], color='b', label='', linewidth=0.8)

plt.subplot(2, 2, 2)
# plt.title('IMF8',loc='left')
plt.plot(freqs, abs(fft(huxian_vmd['IMF8'])), c='b', lw=0.8)
plt.ylabel('Amplitude')

plt.subplot(2, 2, 3)
plt.xlabel('Time(month)')
plt.ylabel(r'$S_9$')
plt.plot(huxian_vmd['IMF9'], color='b', label='', linewidth=0.8)

plt.subplot(2, 2, 4)
def PlotOutlier(data, unit_period_length, img_save_path, boundary):

    num_period = int(len(data) / unit_period_length)
    print(num_period)
    #actually not every period has meaningful data which makes a need to filter out some undesired data periods in calculating mean and std
    valid_start_idx, valid_end_idx = int(num_period * 0.1), int(num_period *
                                                                0.4)
    ######

    skew_list = []
    kurtosis_list = []
    std_list = []

    for period_idx in range(num_period):

        skew_list.append(
            skew(data[period_idx * unit_period_length:(period_idx + 1) *
                      unit_period_length]))
        kurtosis_list.append(
            kurtosis(data[period_idx * unit_period_length:(period_idx + 1) *
                          unit_period_length]))
        std_list.append(data[period_idx * unit_period_length:(period_idx + 1) *
                             unit_period_length].max())

    sk_uppder, sk_lower = np.array(
        skew_list
    )[valid_start_idx:valid_end_idx].mean(
    ) + boundary * np.array(skew_list)[valid_start_idx:valid_end_idx].std(
    ), np.array(skew_list)[valid_start_idx:valid_end_idx].mean(
    ) - boundary * np.array(skew_list)[valid_start_idx:valid_end_idx].std()
    kur_uppder, kur_lower = np.array(kurtosis_list)[
        valid_start_idx:valid_end_idx].mean() + boundary * np.array(
            kurtosis_list)[valid_start_idx:valid_end_idx].std(), np.array(
                kurtosis_list)[valid_start_idx:valid_end_idx].mean(
                ) - boundary * np.array(
                    kurtosis_list)[valid_start_idx:valid_end_idx].std()
    std_uppder, std_lower = np.array(
        std_list)[valid_start_idx:valid_end_idx].mean(
        ) + boundary * np.array(std_list)[valid_start_idx:valid_end_idx].std(
        ), np.array(std_list)[valid_start_idx:valid_end_idx].mean(
        ) - boundary * np.array(std_list)[valid_start_idx:valid_end_idx].std()

    fig, ax = plt.subplots()

    #plot the patterns in a given data sequence
    ax.plot(data)
    #mark the std of each data period in scatter plot
    #boundary: 96% trust region
    ax.scatter(range(50, 50 + unit_period_length * num_period,
                     unit_period_length),
               std_list,
               color='g',
               label='STD')
    ax.hlines(np.array(std_list)[valid_start_idx:valid_end_idx].mean(),
              xmin=0,
              xmax=len(data),
              colors='g')
    ax.hlines(std_lower,
              xmin=0,
              xmax=len(data),
              colors='g',
              linestyles='dashed')
    ax.hlines(std_uppder,
              xmin=0,
              xmax=len(data),
              colors='g',
              linestyles='dashed')
    ax.set_yticks([data.min(), data.max()])
    #ax.set_xlim([0, 3000])

    #kurtosis
    ax2 = ax.twinx()
    ax2.scatter(range(50, 50 + unit_period_length * num_period,
                      unit_period_length),
                kurtosis_list,
                color='r')
    ax.scatter(50, kurtosis_list[0], color='r', label='Kurtosis')
    ax2.hlines(np.array(kurtosis_list)[valid_start_idx:valid_end_idx].mean(),
               xmin=0,
               xmax=len(data),
               colors='r')
    ax2.hlines(kur_uppder,
               xmin=0,
               xmax=len(data),
               colors='r',
               linestyles='dashed')
    ax2.hlines(kur_lower,
               xmin=0,
               xmax=len(data),
               colors='r',
               linestyles='dashed')

    #skewness
    ax2.scatter(range(50, 50 + unit_period_length * num_period,
                      unit_period_length),
                skew_list,
                color='c')
    ax.scatter(50, skew_list[0], color='c', label='Skewness')
    ax2.hlines(np.array(skew_list)[valid_start_idx:valid_end_idx].mean(),
               xmin=0,
               xmax=len(data),
               colors='c')
    ax2.hlines(sk_uppder,
               xmin=0,
               xmax=len(data),
               colors='c',
               linestyles='dashed')
    ax2.hlines(sk_lower,
               xmin=0,
               xmax=len(data),
               colors='c',
               linestyles='dashed')

    ax.legend()

    valid_img_save_path = os.path.join(img_save_path, 'valid_cycle')

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

    plt.savefig(os.path.join(valid_img_save_path, str(user_idx) + '.png'))
    plt.close()

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(skew_list, kurtosis_list, std_list)

    sk_range = [sk_lower, sk_uppder]
    kur_range = [kur_lower, kur_uppder]
    std_range = [std_lower, std_uppder]

    def x_y_edge(x_range, y_range, z_range):

        xx, yy = np.meshgrid(x_range, y_range)

        for value in [0, 1]:
            output = np.array([z_range[value]] * 4).reshape(2, 2)
            ax.plot_wireframe(xx, yy, output, color="r")

    def y_z_edge(x_range, y_range, z_range):

        yy, zz = np.meshgrid(y_range, z_range)

        for value in [0, 1]:
            output = np.array([x_range[value]] * 4).reshape(2, 2)
            ax.plot_wireframe(output, yy, zz, color="r")

    def x_z_edge(x_range, y_range, z_range):

        xx, zz = np.meshgrid(x_range, z_range)

        for value in [0, 1]:
            output = np.array([y_range[value]] * 4).reshape(2, 2)
            ax.plot_wireframe(xx, output, zz, color="r")

    x_y_edge(sk_range, kur_range, std_range)
    y_z_edge(sk_range, kur_range, std_range)
    x_z_edge(sk_range, kur_range, std_range)
    ax.set_xticks(np.linspace(min(skew_list), max(skew_list), 4))
    ax.set_yticks(np.linspace(min(kurtosis_list), max(kurtosis_list), 4))
    ax.set_zticks(np.linspace(min(std_list), max(std_list), 4))
    ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    ax.set_xlabel('Skew', fontsize=15)
    ax.set_ylabel('Kurtosis', fontsize=15)
    ax.set_zlabel('STD', fontsize=15)

    ax.xaxis.set_tick_params(labelsize=12)
    ax.yaxis.set_tick_params(labelsize=12)
    ax.zaxis.set_tick_params(labelsize=12)
    plt.tight_layout()
    plt.savefig(os.path.join(valid_img_save_path, str(user_idx) + '_3D.png'))
    plt.close()
Beispiel #7
0
def plot_posterior_single(miso_f,
                          axvar,
                          posterior_bins,
                          showXaxis=True,
                          showYaxis=True,
                          show_ylabel=True,
                          font_size=6,
                          bar_posterior=False):
    """
    Plot a posterior probability distribution for a MISO event.
    """
    posterior_bins = int(posterior_bins)
    psis = []
    for line in open(miso_f):
        if not line.startswith("#") and not line.startswith("sampled"):
            psi, logodds = line.strip().split("\t")
            psis.append(float(psi.split(",")[0]))

    ci = .95
    alpha = 1 - ci
    lidx = int(round((alpha / 2) * len(psis)) - 1)
    # the upper bound is the (1-alpha/2)*n nth smallest sample, where n is
    # the number of samples
    hidx = int(round((1 - alpha / 2) * len(psis)) - 1)
    psis.sort()
    clow, chigh = [psis[lidx], psis[hidx]]

    nyticks = 4

    if not bar_posterior:
        y, x, p = hist(psis, linspace(0, 1, posterior_bins),\
            normed=True, facecolor='k', edgecolor='w', lw=.2)
        axvline(clow,
                ymin=.33,
                linestyle='--',
                dashes=(1, 1),
                color='#CCCCCC',
                lw=.5)
        axvline(chigh,
                ymin=.33,
                linestyle='--',
                dashes=(1, 1),
                color='#CCCCCC',
                lw=.5)
        axvline(mean(psis), ymin=.33, color='r')

        ymax = max(y) * 1.5
        ymin = -.5 * ymax
        #             "$\Psi$ = %.2f\n$\Psi_{0.05}$ = %.2f\n$\Psi_{0.95}$ = %.2f" %\

        text(1, ymax,
             "$\Psi$ = %.2f\n[%.2f, %.2f]" % \
             (mean(psis), clow, chigh),
             fontsize=font_size,
             va='top',
             ha='left')

        ylim(ymin, ymax)
        axvar.spines['left'].set_bounds(0, ymax)
        axvar.spines['right'].set_color('none')
        axvar.spines['top'].set_color('none')
        axvar.spines['bottom'].set_position(('data', 0))
        axvar.xaxis.set_ticks_position('bottom')
        axvar.yaxis.set_ticks_position('left')
        if showYaxis:
            yticks(linspace(0, ymax, nyticks),\
                ["%d"%(y) for y in linspace(0, ymax, nyticks)],\
                fontsize=font_size)
        else:
            yticks([])
        if show_ylabel:
            ylabel("Frequency", fontsize=font_size, ha='right', va='center')
    else:
        ##
        ## Plot a horizontal bar version of the posterior distribution,
        ## showing only the mean and the confidence bounds.
        ##
        mean_psi_val = mean(psis)
        clow_err = mean_psi_val - clow
        chigh_err = chigh - mean_psi_val
        errorbar([mean_psi_val], [1],
                 xerr=[[clow_err], [chigh_err]],
                 fmt='o',
                 ms=4,
                 ecolor='k',
                 markerfacecolor="#ffffff",
                 markeredgecolor="k")
        text(1, 1,
             "$\Psi$ = %.2f\n[%.2f, %.2f]" % \
             (mean(psis), clow, chigh),
             fontsize=font_size,
             va='top',
             ha='left')
        yticks([])

    # Use same x-axis for all subplots
    # but only show x-axis labels for the bottom plot
    xlim([0, 1])
    psi_axis_fontsize = font_size - (font_size * 0.3)
    xticks([0, .2, .4, .6, .8, 1], fontsize=psi_axis_fontsize)

    if (not bar_posterior) and showYaxis:
        axes_to_show = ['bottom', 'left']
    else:
        axes_to_show = ['bottom']

    # Adjust x-axis to be lighter
    axis_size = 0.2
    tick_size = 1.2
    axis_color = "k"
    for shown_axis in axes_to_show:
        if shown_axis in axvar.spines:
            print "Setting color on %s axis" % (shown_axis)
            axvar.spines[shown_axis].set_linewidth(axis_size)
            axvar.xaxis.set_tick_params(size=tick_size, color=axis_color)
    if showXaxis:
        from matplotlib.ticker import FormatStrFormatter
        majorFormatter = FormatStrFormatter('%g')
        axvar.xaxis.set_major_formatter(majorFormatter)

        [label.set_visible(True) for label in axvar.get_xticklabels()]
        xlabel("MISO $\Psi$", fontsize=font_size)
        show_spines(axvar, axes_to_show)
    else:
        show_spines(axvar, axes_to_show)
        [label.set_visible(False) for label in axvar.get_xticklabels()]
Beispiel #8
0
    R = np.matrix([[140.6324, 130.6976], [130.4807, 140.7038]])
    Q = np.matrix([[2.1668, -0.0846, 0.4526, 1.3870, 0.6935],
                   [-0.0846, 2.0430, 0.8917, -0.7040, -0.3520],
                   [0.4526, 0.8917, 1.0000, 0.0000, 0.0000],
                   [1.3870, -0.7040, 0.0000, 2.0000, 1.0000],
                   [0.6935, -0.3520, 0.0000, 1.0000, 1.0000]]) * 1e-4
    # kalman_filter = KalmanFilter(Q=Q, R=R)
    kalman_filter = ExtendedKalmanFilter(Q=Q, R=R)
    measured_positions, filtered_positions, errors, true_positions = run_filter(
        kalman_filter, test_target, starting_point=None)

    # Plot trajectories on top graph
    ax1.scatter(*zip(*measured_positions), s=2, label='Измеренное положение')
    ax1.plot(*zip(*filtered_positions),
             linewidth=.6,
             label='Отфильтрованное положение')
    ax1.plot(*zip(*true_positions), linewidth=2, label='Истиное положение')
    ax1.legend()

    # Plot errors on bottom
    ax2.plot(errors)

    # Format output
    ax2.set_yscale('log')
    ax2.yaxis.set_major_formatter(FormatStrFormatter('%g'))
    ax2.yaxis.set_minor_formatter(FormatStrFormatter('%g'))
    ax2.tick_params(which='minor', labelsize=8)
    ax2.grid(which='both')
    # ax2.legend()
    plt.show()
Beispiel #9
0
def plot_all_tr_val_nL_surface_XXXXXXXXX (nHs,nLs, aves_OMN, aves_OMN_tr):
        # Plots the training and Validation score of a realization

    N_neurons = len(aves_OMN)
    
    X = np.array(nHs)
    Y = np.array(nLs)
    X, Y = np.meshgrid(X, Y)
    
#    print X
#    print Y
    Z = mu.convert_to_matrix(aves_OMN).T
#    Z2 = mu.convert_to_matrix(aves_OMN_tr).T
#    Z = Z.flatten()
    
#    print X.shape, Y.shape
#    print Z.shape
    
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    
    """ VAL """
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    
    ax.set_zlim(np.min(Z.flatten()), np.max(Z.flatten()))
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    
    plt.xlabel('Hidden neurons')
    plt.ylabel('Number of Layers')
    fig.colorbar(surf, shrink=0.5, aspect=5)
 
    """ TR """
#    surf = ax.plot_surface(X, Y, Z2, rstride=1, cstride=1, cmap=cm.coolwarm,
#                           linewidth=0, antialiased=False)
#    
#    ax.set_zlim(np.min(Z2.flatten()), np.max(Z2.flatten()))
#    ax.zaxis.set_major_locator(LinearLocator(10))
#    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
#    
#    plt.xlabel('Hidden neurons')
#    plt.ylabel('Number of Layers')
#    fig.colorbar(surf, shrink=0.5, aspect=5)
#    
#    plt.show()


#==============================================================================
#     X = np.array(nHs)
#     Y = np.array(nLs)
# #    X, Y = np.meshgrid(nHs, nLs)
#     
#     print X
#     print Y
#     Z = convert_to_matrix(aves_OMN)
# #    Z = Z.flatten()
#     
#     print X.shape, Y.shape
#     print Z.shape
# 
#     from mpl_toolkits.mplot3d import Axes3D
#     import matplotlib.pyplot as plt
#     
#     
#     fig = plt.figure()
#     ax = fig.add_subplot(111, projection='3d')
#     
#     for x in range(X.size):
#         for y in range(Y.size):
#             ax.scatter(X[x], Y[y], Z[x,y])
#     
#     ax.set_xlabel('X Label')
#     ax.set_ylabel('Y Label')
#==============================================================================
    ax.set_zlabel('Z Label')
    
    plt.show()
        
Beispiel #10
0
def plot_franke(x,
                y,
                franke_=False,
                noise=False,
                scalor=0.05,
                method='ols',
                seed1=8172,
                lambda_=0.005,
                absolute_error=False):
    """
    Plots the franke function.Franke's function has two Gaussian peaks of different heights, 
    and a smaller dip. It is used as a test function in interpolation problems.
    The function is evaluated on the square xi ∈ [0, 1], for all i = 1, 2.
    
    Reference: Franke, R. (1979). A critical comparison of some methods for interpolation of 
    scattered data (No. NPS53-79-003). NAVAL POSTGRADUATE SCHOOL MONTEREY CA.
    
    
    Arguments:
    x:  1-dimensional numpy array (1D np.array)
    y:  1-dimensional numpy array (1D np.array)
    franke_: binary argument with inputs True/False. If 'True', plots the franke function
    noise: binary argument with inputs True/False. If 'True', plots the franke function with added noise. 
           Activated only when franke_ == True.
    scalor: float type,  controls the amount of noise to be added to the franke function. Activated only when
            noise == True.
    method: character input accepting 'ols', 'ridge', 'lasso'. Plots the corresponding model fit.
    seed1: float type. used for reproducable output
    lambda_: float type. Activated only when method = 'ridge' or 'lasso'. Controls the amount of shrinkage of the
             parameters. Higher number indicates higher shrinkage.
    absolute_error: Binary type with inputs True/False. If 'True', outputs a plot of absolute deviation of the true
                    franke values and the fit of the corresponding model. Activated only when method is either 'ols',
                    'ridge' or 'lasso
    """
    x, y = np.meshgrid(x, y)
    f = franke(x, y)  ##true franke values

    if (noise):  ##noisy franke values
        f = franke(x, y) + scalor * np.random.normal(0, 1, franke(x, y).shape)

    if method == 'ols':  ##fit and predict ols
        np.random.seed(seed1)
        x_new = np.random.rand(500)
        y_new = np.random.rand(500)
        xn = x_new.ravel()
        yn = y_new.ravel()
        fn = franke(xn, yn)
        X = designMatrix(xn, yn)
        scaler = StandardScaler()
        scaler.fit(X)
        X = scaler.transform(X)
        X[:, 0] = 1
        linreg = linregOwn(method='ols')
        beta = linreg.fit(X, fn)

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

        xn = Xnew.ravel()
        yn = Ynew.ravel()
        xb_new = designMatrix(xn, yn)
        scaler = StandardScaler()
        scaler.fit(xb_new)
        xb_new = scaler.transform(xb_new)
        xb_new[:, 0] = 1

        f_predict = np.dot(xb_new, beta)
        F_predict = f_predict.reshape(F_true.shape)

    if method == 'ridge':  ##fit and predict ridge
        np.random.seed(seed1)
        x_new = np.random.rand(500)
        y_new = np.random.rand(500)
        xn = x_new.ravel()
        yn = y_new.ravel()
        fn = franke(xn, yn)
        X = designMatrix(xn, yn)
        scaler = StandardScaler()
        scaler.fit(X)
        X = scaler.transform(X)
        X[:, 0] = 1
        linreg = linregOwn(method='ridge')
        beta = linreg.fit(X, fn, lambda_=0.1)

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

        xn = Xnew.ravel()
        yn = Ynew.ravel()
        xb_new = designMatrix(xn, yn)
        scaler = StandardScaler()
        scaler.fit(xb_new)
        xb_new = scaler.transform(xb_new)
        xb_new[:, 0] = 1

        f_predict = np.dot(xb_new, beta)
        F_predict = f_predict.reshape(F_true.shape)

    if method == 'lasso':  ##fit and predict lasso
        np.random.seed(seed1)
        x_new = np.random.rand(500)
        y_new = np.random.rand(500)
        xn = x_new.ravel()
        yn = y_new.ravel()
        fn = franke(xn, yn)
        X = designMatrix(xn, yn)
        scaler = StandardScaler()
        scaler.fit(X)
        X = scaler.transform(X)
        X[:, 0] = 1
        linreg = linregOwn(method='lasso')
        beta = linreg.fit(X, fn, lambda_=0.1)

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

        xn = Xnew.ravel()
        yn = Ynew.ravel()
        xb_new = designMatrix(xn, yn)
        scaler = StandardScaler()
        scaler.fit(xb_new)
        xb_new = scaler.transform(xb_new)
        xb_new[:, 0] = 1

        f_predict = np.dot(xb_new, beta)
        F_predict = f_predict.reshape(F_true.shape)

    #Plot the Franke Function
    fig = plt.figure()
    ax = fig.gca(projection='3d')  ##get current axis
    ## antialiased controls the transparency of the surface

    if method == 'ols':
        if absolute_error == True:
            surf = ax.plot_surface(Xnew,
                                   Ynew,
                                   abs(F_predict - F_true),
                                   cmap=cm.coolwarm,
                                   linewidth=0,
                                   antialiased=False)
        else:
            surf = ax.plot_surface(Xnew,
                                   Ynew,
                                   F_predict,
                                   cmap=cm.coolwarm,
                                   linewidth=0,
                                   antialiased=False)
    if method == 'ridge':
        if absolute_error == True:
            surf = ax.plot_surface(Xnew,
                                   Ynew,
                                   abs(F_predict - F_true),
                                   cmap=cm.coolwarm,
                                   linewidth=0,
                                   antialiased=False)
        else:
            surf = ax.plot_surface(Xnew,
                                   Ynew,
                                   F_predict,
                                   cmap=cm.coolwarm,
                                   linewidth=0,
                                   antialiased=False)
    if method == 'lasso':
        if absolute_error == True:
            surf = ax.plot_surface(Xnew,
                                   Ynew,
                                   abs(F_predict - F_true),
                                   cmap=cm.coolwarm,
                                   linewidth=0,
                                   antialiased=False)
        else:
            surf = ax.plot_surface(Xnew,
                                   Ynew,
                                   F_predict,
                                   cmap=cm.coolwarm,
                                   linewidth=0,
                                   antialiased=False)

    #Customize z axis
    if franke_ == True:
        surf = ax.plot_surface(x,
                               y,
                               f,
                               cmap='coolwarm',
                               linewidth=0,
                               antialiased=False)  ## colormap is coolwarm,
        ax.set_title('Franke function without noise')
        if (noise):
            ax.set_title('Franke function with noise')

    ax.set_zlim(-0.10, 1.4)
    ax.zaxis.set_major_locator(LinearLocator(5))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    ax.view_init(30, 45)
    #Labeling axes and title

    if method == 'ols':
        ax.set_title('OLS Fit')
    if method == 'ridge':
        ax.set_title('Ridge Fit')
    if method == 'lasso':
        ax.set_title('Lasso Fit')

    ax.set_xlabel('X')
    ax.set_ylabel('Y')

    #Add colour bar
    fig.colorbar(surf, shrink=0.5, aspect=0.5)
    #plt.savefig(os.path.join(os.path.dirname(__file__), 'Plots', 'franke_abs_lasso.png'), transparent=True, bbox_inches='tight')
    return plt.show()
grid_ax.spines["top"].set_visible(False)
grid_ax.spines["right"].set_visible(False)
grid_ax.spines["left"].set_visible(False)
grid_ax.spines["bottom"].set_visible(False)

sca(grid_ax)
ylabel('Grid')
xlim(x_min, x_max)

## Classification graph formatting:
sca(class_ax)
xlim(x_min, x_max)
ylabel("$p_i$")
ylim(0.1, 0.7)
xticks(grid_radii)
class_ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
yticks([0.2, 0.3, 0.4, 0.5, 0.6])
class_ax.tick_params(axis='x', which='minor', bottom='off', top="off")
class_ax.xaxis.set_ticklabels([])

sca(temp_ax)
xlim(x_min, x_max)
temp_ax.invert_yaxis()
ylabel("$\\beta$")
ylim(0.8, -0.8)
locator_params(axis='y', nbins=4)
temp_ax.tick_params(axis='x', which='minor', bottom='off', top="off")
axhline(y=0, c='k', ls='--', zorder=-1)
xticks(grid_radii)
temp_ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
temp_ax.xaxis.set_ticklabels([])
Beispiel #12
0
def main():

    print(sys.version_info[0])

    # METHODS being benchmarked -- Add new METHOD[S] here
    if sys.version_info[0] >= 3:
        #methods = ["lapjv_lapjv", "lap_lapjv", "scipy", "lapsolver", "hungarian", "munkres", "laptools_clap"]
        methods = [
            "lapjv_lapjv", "lap_lapjv", "scipy", "lapsolver", "laptools_clap",
            "munkres"
        ]
    else:
        methods = ["lap_lapjv", "scipy", "hungarian", "munkres"]

    minimum = int(np.floor(np.log2(args.min)))  # 2^min =  8x8 cost matrix
    maximum = int(np.ceil(np.log2(args.max)))  # 2^max
    ncyc = int(args.ncyc)  # number of cycle

    # LIMITS - add limit for new METHOD[S] here
    # The size of the matrix to be solved is limited to 2^{limit['method']}
    # for each method to ensure quick termination of the benchmarking
    # exercise. Munkres and Scipy are considerably slower, making it
    # necessary to limit them to smaller
    # matrices
    limit = {}
    limit['munkres'] = min(7, maximum)
    #limit['hungarian'] = min(12,maximum)
    limit['scipy'] = maximum
    limit['lap_lapjv'] = maximum
    limit['lapjv_lapjv'] = maximum
    limit['lapsolver'] = maximum
    limit['laptools_clap'] = maximum
    print("Solving matrices of sizes up to 2^{n} where n is " + str(limit))

    # arrays to store data
    t_methods = ["t_" + i for i in methods]
    for i in range(len(methods)):
        t_methods[i] = np.empty((0, 2), float)
    label_methods = ["label_" + i for i in methods]
    run_methods = ["run_" + i for i in methods]

    base = 2  # will build matrices of size base^n and solve them

    # for matrices of size 2^{min} - 2^{max}
    for i in range(minimum, maximum):
        matrix_size = pow(base, i)
        print(("\n\n" + str(matrix_size) + " x " + str(matrix_size) + " ... "))
        methods_data = np.zeros(len(methods), float)
        # Generate n_cyc random matrices and solve them using different methods
        for j in range(ncyc):
            cost_matrix = matrix_size * \
                np.random.random((matrix_size, matrix_size))
            #cost_matrix=mat.astype(str(datatype))
            #cost_matrix=recast_mat(mat, str(datatype))
            #print((str(j) + " "), end=" ")
            print("\nCycle ", (str(j) + " "), end=' ')
            # print("\n")
            # print(cost_matrix)
            for method in range(len(methods)):
                # print '%20s\t' %(methods[method])
                if methods[method] == 'munkres' and i <= limit[
                        methods[method]]:
                    methods_data[method] += run_munkres(
                        cost_matrix, args.printcost)
                elif methods[method] == 'scipy' and i <= limit[
                        methods[method]]:
                    real_time = run_scipy(cost_matrix, args.printcost)
                    methods_data[method] += real_time
                elif methods[method] == 'hungarian' and i <= limit[
                        methods[method]]:
                    methods_data[method] += run_hungarian(
                        cost_matrix, args.printcost)
                elif methods[method] == 'lap_lapjv' and i <= limit[
                        methods[method]]:
                    methods_data[method] += run_lap_lapjv(
                        cost_matrix, args.printcost)
                elif methods[method] == 'lapjv_lapjv' and i <= limit[
                        methods[method]]:
                    methods_data[method] += run_lapjv_lapjv(
                        cost_matrix, args.printcost)
                elif methods[method] == 'lapsolver' and i <= limit[
                        methods[method]]:
                    methods_data[method] += run_lapsolver(
                        cost_matrix, args.printcost)
                elif methods[method] == 'laptools_clap' and i <= limit[
                        methods[method]]:
                    methods_data[method] += run_laptools_clap(
                        cost_matrix, args.printcost)
                    # If you want to benchmark a new METHOD, add another ELIF statement here
                else:
                    pass

        # average the timing information from n_cyc cycles
        for method in range(len(methods)):
            if methods_data[
                    method] != 0:  # to make sure there is timing information
                t_methods[method] = np.append(
                    t_methods[method],
                    np.array([[matrix_size, methods_data[method] / ncyc]]),
                    axis=0)

    #Print version information
    print("\n\nPackage Versions for the current run")
    print("Python - ", sys.version)
    for method in methods:
        tmp = method.split("_")
        # hungarian and lapjv don't print version numbers
        if tmp[0] != 'hungarian':
            if tmp[0] != 'lapjv':
                ptmp = __import__(tmp[0])
                method_version = ptmp.__version__
                print(tmp[0], " - ", ptmp.__version__)

    # print timing information to screen
    dimensions = t_methods[0][:, [0]]
    dimensions = dimensions.flatten()
    print("\n")
    print("  %12s " % ("Matrix_size"), end=" ")
    np.set_printoptions(suppress=True, precision=5, linewidth=100)
    for i in range(len(dimensions)):
        print('%6d ' % (dimensions[i]), end=" ")
    print(" ")

    np.set_printoptions(suppress=True, precision=5, linewidth=100)
    for method in range(len(methods)):
        print('%12s ' % (methods[method]), end=" ")
        timings = t_methods[method][:, [1]]
        timings = timings.flatten()
        print(timings)

    # generate a plot (by default), unless 'no plot' option is selection
    if args.noplot:
        pass
    else:
        markers = []
        markers = ['o', 'v', 's', 'D', 'P', '+', '*', '0', '1', '2']
        marker_size = [50]
        fig, ax = plt.subplots()
        for method in range(len(methods)):
            plt.scatter(t_methods[method][:, [0]],
                        t_methods[method][:, [1]],
                        s=marker_size,
                        label=methods[method],
                        marker=markers[method])
            plt.loglog(t_methods[method][:, [0]],
                       t_methods[method][:, [1]],
                       basex=2,
                       basey=10)

        plt.grid(True, which="both")
        ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
        plt.xlabel('Matrix dimension (2^n)', fontsize=18)
        plt.ylabel('Real time to solution (seconds)', fontsize=18)
        plt.title('Time to solve LAPs using different modules', fontsize=20)
        plt.legend(fontsize=14)
        fig_filename = "timing-LAPs-py3-" + \
            str(pow(2, minimum)) + "-" + str(pow(2, maximum)) + ".png"
        print("Figure saved to file %18s" % (fig_filename))
        fig.set_size_inches(11, 8.5)
        plt.savefig(fig_filename, bbox_inches='tight', dpi=150)
        if args.showplot:
            plt.show()
Beispiel #13
0
  #tics inside
  axarr[y].tick_params(direction='in', which='both', top=1, right=1)
  #minor tics
  axarr[y].xaxis.set_minor_locator(AutoMinorLocator())
  axarr[y].yaxis.set_minor_locator(AutoMinorLocator())
  #labels and tics font size
  for item in ([axarr[y].xaxis.label, axarr[y].yaxis.label] + axarr[y].get_xticklabels() + axarr[y].get_yticklabels()):
    item.set_fontsize(8)
  # subplot numbering
#    if y < nploty - nemptyplots or x < (nplotx - 1):
 #     axarr[y].text(0.8, 0.9, labeldict[y + x*nploty], fontsize=8, transform=axarr[y].transAxes)
  axarr[y].text(0.05, 0.85, labeldict[y], fontsize=8, transform=axarr[y].transAxes)

axarr[1].set_ylabel('')
axarr[2].set_ylabel('')
axarr[0].yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
#axarr[1].yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
#axarr[2].yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
axarr[1].yaxis.set_major_formatter(NullFormatter())
axarr[2].yaxis.set_major_formatter(NullFormatter())
axarr[0].xaxis.set_major_locator(MaxNLocator(integer=True))

## show legends
#for x in np.arange(nplotx):
#  for y in np.arange(nploty):
#    axarr[x,y].legend(loc="upper center")

#single legend for the whole figure
handles, labels = axarr[1].get_legend_handles_labels()
lgd = fig.legend(handles, labels, handlelength=4, loc='lower center', bbox_to_anchor=(0.45,0))
Beispiel #14
0
         zorder=8,
         label=r"Box")
#mark_inset(ax2, ax3, loc1=3, loc2=1, fc="none", ec='0.5') # Mark the region corresponding to the inset

# add this for consistent representation of images in ax1 to ax3
# ax1.set_aspect('equal')
# ax2.set_aspect('equal')
# ax3.set_aspect('equal')
# hack: aspect=equal is default for imshow, but destroys my gridspec
ax1.set_aspect('auto')
ax2.set_aspect('auto')
ax3.set_aspect('auto')

# plot common colour bar
axc = plt.axes([0.76, 0.515, 0.035, 0.355])
fmt = FormatStrFormatter('%4.1f')
cb1 = plt.colorbar(im1, cax=axc, format=fmt, orientation="vertical")
cb1.ax.set_ylabel(r"$C_{u^{\prime}_{z}\Pi_{<0}}$")
cb1.set_ticks([-amcc, 0.0, +amcc])
axc.axhline(y=-clm,
            color=Vermillion)  # mark negative contour level in colourbar
axc.axhline(y=+clm, color=Blue)  # mark positive contour level in colourbar

# plot mode interactive or pdf
if plot != 2:
    #plt.tight_layout()
    plt.show()
else:
    #fig.tight_layout()
    fnam = str.replace(fnam, '.dat', '.pdf')
    fnam = str.replace(fnam, 'piCorrThZStreaksBox2d',
        s_arr["lon"],
        s_arr["lat"] + 0.004,
        s_arr["station"][2:],
        horizontalalignment="center",
        verticalalignment="baseline",
        fontdict={"size": fs},
    )
im = plt.imread(image_fn)
ax.imshow(im,
          aspect="equal",
          origin="upper",
          extent=(-119.11, -118.75, 37.8, 37.95))  #

ax.set_xlabel("Longitude (deg)", fontdict={"size": fs + 2, "weight": "bold"})
ax.set_ylabel("Latitude (deg)", fontdict={"size": fs + 2, "weight": "bold"})
ax.xaxis.set_major_formatter(FormatStrFormatter("%.2f"))
ax.yaxis.set_major_formatter(FormatStrFormatter("%.2f"))
ax.xaxis.set_major_locator(MultipleLocator(0.05))
ax.yaxis.set_major_locator(MultipleLocator(0.05))
# ax.grid(which='major', color=(.75, .75, .75), linewidth=.75)

ax.set_xlim(-119.11, -118.75)
ax.set_ylim(37.8, 37.95)

# for line in ax.lines:
#    line.set_zorder(10)
plt.show()

fig.savefig(r"c:\Users\jpeacock-pr\Google Drive\JVG\mb_station_map.pdf",
            dpi=300)
Beispiel #16
0
def plot_sat_gitm_comp(sat_datetime,
                       sat_data,
                       gtrack,
                       gkey,
                       skey,
                       tkey,
                       bkey,
                       title,
                       tmin=None,
                       tmax=None,
                       ymin=None,
                       ymax=None,
                       dmin=None,
                       dmax=None,
                       pmin=None,
                       pmax=None,
                       figname=None,
                       draw=True,
                       fsize=14,
                       sc='#0039A6',
                       gc='#ffcc00',
                       *args,
                       **kwargs):
    '''
    A routine to plot satellite and GITM data to show how a single physical
    quantity varies over the orbit.  Four panels are included; the top panel
    shows the raw satellite data and the GITM data along the track.  The second
    panel shows the matched GITM/satellite data.  The third panel shows the
    difference between the satellite and GITM data.  The fourth panel shows the
    percent difference 100*(sat-GITM)/sat.

    Input:
    sat_datetime = Satellite datetime numpy array: dim(nsat,)
    sat_data     = Satelite data numpy array: dim(nsat,)
    gtrack       = GitmTime structure with GITM data along satellite
                   track and the matching satellite measurements
    gkey         = GITM data key
    skey         = Matched satellite data key
    tkey         = Matched satellite top errorbar key (or None)
    bkey         = Matched satellite bottom errorbar key (or None)
    title        = Plot title

    tmin = UT Minimum (default None)
    tmax = UT Maximum (default None)
    ymin = Dependent variable minimum (default None)
    ymax = Dependent variable maximum (default None)
    dmin = Difference minimum (default None)
    dmax = Difference maximum (default None)
    pmin = Percent difference minimum (default None)
    pmax = Percent difference maximum (default None)

    figname = Output file name (must be .png, default None)
    draw    = Draw to screen? (default is True)

    fsize = Font size (defualt=14)
    sc    = satellite color (default Michigan Blue)
    gc    = GITM color (default Michigan Maize)
    '''
    # Change fontsize, marker size, and line width
    mpl.rc('xtick', labelsize=fsize)
    mpl.rc('ytick', labelsize=fsize)
    mpl.rc('font', size=fsize)
    ms = 8
    lw = 3

    # Initialize the figure
    f = plt.figure(figsize=(12, 12))
    if not tmin:
        tmin = gtrack['time'][0]
    if not tmax:
        tmax = gtrack['time'][-1]

    # Create the first subplot, showing the raw satellite data and model data
    ax1 = f.add_subplot(411)
    con1 = ax1.plot_date(sat_datetime, sat_data, color=sc, fmt="-")
    con1 = ax1.plot_date(gtrack['time'],
                         gtrack[gkey][:, 0, 0, 0],
                         fmt="o",
                         color=gc,
                         markersize=ms)
    plt.xlim(tmin, tmax)
    if type(ymin) is float and type(ymax) is float:
        plt.ylim(ymin, ymax)

    # Create the second subplot, showing the matched satellite and model data
    ax2 = f.add_subplot(412)
    con2 = ax2.plot_date(gtrack['time'],
                         gtrack[gkey][:, 0, 0, 0],
                         color=gc,
                         fmt="o",
                         markersize=ms)
    if gtrack.has_key(tkey) and gtrack.has_key(bkey):
        con2 = ax2.errorbar(
            gtrack['time'],
            gtrack[skey][:, 0, 0, 0],
            yerr=[gtrack[bkey][:, 0, 0, 0], gtrack[tkey][:, 0, 0, 0]],
            color=sc,
            fmt="+",
            markersize=ms,
            linewidth=lw)
    else:
        con2 = ax2.plot_date(gtrack['time'],
                             gtrack[skey][:, 0, 0, 0],
                             color=sc,
                             marker="+",
                             markersize=ms,
                             linewidth=lw)
    plt.xlim(tmin, tmax)
    if type(ymin) is float and type(ymax) is float:
        plt.ylim(ymin, ymax)

    # Create the third subplot, showing the difference between the satellite
    # and model data
    ax3 = f.add_subplot(413)
    sdiff = gtrack[skey][:, 0, 0, 0] - gtrack[gkey][:, 0, 0, 0]
    szero = np.zeros(shape=gtrack['time'].shape)

    if gtrack.has_key(tkey) and gtrack.has_key(bkey):
        con3 = ax3.errorbar(
            gtrack['time'],
            sdiff,
            yerr=[gtrack[bkey][:, 0, 0, 0], gtrack[tkey][:, 0, 0, 0]],
            color=sc,
            fmt="o",
            markersize=ms,
            linewidth=lw)
    else:
        con3 = ax3.plot_date(gtrack['time'],
                             sdiff,
                             color=sc,
                             fmt="o",
                             markersize=ms,
                             linewidth=lw)
    con3 = ax3.plot_date(gtrack['time'], szero, "k-")
    plt.xlim(tmin, tmax)
    if type(dmin) is float and type(dmax) is float:
        plt.ylim(dmin, dmax)

    # Create the fourth subplot, showing the difference between the satellite
    # and model data
    ax4 = f.add_subplot(414)
    sperc = 100.0 * sdiff / gtrack[skey][:, 0, 0, 0]

    if gtrack.has_key(tkey) and gtrack.has_key(bkey):
        bperc = 100.0 * gtrack[bkey][:, 0, 0, 0] / gtrack[skey][:, 0, 0, 0]
        tperc = 100.0 * gtrack[tkey][:, 0, 0, 0] / gtrack[skey][:, 0, 0, 0]
        con4 = ax4.errorbar(gtrack['time'],
                            sperc,
                            yerr=[bperc, tperc],
                            color=sc,
                            fmt="o",
                            markersize=ms,
                            linewidth=lw)
    else:
        con4 = ax4.plot_date(gtrack['time'],
                             sperc,
                             color=sc,
                             fmt="o",
                             markersize=ms,
                             linewidth=lw)
    con4 = ax4.plot_date(gtrack['time'], szero, "k-")
    plt.xlim(tmin, tmax)
    if type(pmin) is float and type(pmax) is float:
        plt.ylim(pmin, pmax)

    # Set the labels, title, and tick intervals
    f.suptitle(title)
    ylabel1 = "{:s} (${:s}$)".format(gtrack[gkey].attrs['name'],
                                     gtrack[gkey].attrs['units'])
    ax1.set_ylabel(ylabel1)
    ax2.set_ylabel(ylabel1)
    ax3.set_ylabel("Obs$-$GITM {:s}".format(ylabel1))
    ax4.set_ylabel(r"% Diff {:s}".format(ylabel1))

    dtics, dmtics, dfmt = pybats.smart_timeticks(
        [gtrack['time'][0], gtrack['time'][-1]])
    ax1.xaxis.set_major_locator(dtics)
    ax2.xaxis.set_major_locator(dtics)
    ax3.xaxis.set_major_locator(dtics)
    ax4.xaxis.set_major_locator(dtics)
    ax1.xaxis.set_minor_locator(dmtics)
    ax2.xaxis.set_minor_locator(dmtics)
    ax3.xaxis.set_minor_locator(dmtics)
    ax4.xaxis.set_minor_locator(dmtics)

    xfmt1 = FormatStrFormatter("")
    xfmt2 = FuncFormatter(gtrack.sat_dateloc_ticks)
    ax1.xaxis.set_major_formatter(xfmt1)
    ax2.xaxis.set_major_formatter(xfmt1)
    ax3.xaxis.set_major_formatter(xfmt1)
    ax4.xaxis.set_major_formatter(xfmt2)

    gitm_time.set_sat_dateloc_label(ax4, gtrack.has_key("Magnetic Latitude"))
    plt.subplots_adjust(hspace=0.1, top=.94, bottom=.2, right=.9)

    # Output the plots to the screen and/or file as desired
    if draw:
        # Draw to screen.
        if plt.isinteractive():
            plt.draw()  #In interactive mode, you just "draw".
        else:
            # W/o interactive mode, "show" stops the user from typing more
            # at the terminal until plots are drawn.
            plt.show()

    # Save output file
    if figname is not None:
        plt.savefig(figname)

    return f
                       s.shape[0] // 2 * spatial_sampling, s.shape[0])

    return freq[s.shape[0] // 2:], s[s.shape[0] // 2:]


if __name__ == '__main__':

    from matplotlib import pyplot as plt
    from felpy.model.src.coherent import construct_SA1_pulse

    from felpy.utils.vis_utils import Grids
    from matplotlib.ticker import FormatStrFormatter

    wfr = construct_SA1_pulse(512, 512, 2, 5, 1)

    ef = wfr.as_complex_array().sum(-1)
    ef *= np.random.rand(512, 512)

    freq, s = power_spectral_density(ef,
                                     spatial_sampling=wfr.dx,
                                     pulse_duration=wfr.pulse_duration)

    grid = Grids()
    grid.create_grid(1, 1)
    ax = grid.axes
    ax.semilogy(freq, s)

    ax.xaxis.set_major_formatter(FormatStrFormatter('%.e'))

    ax.set_ylabel("Power Spectral Density (W$m^{-3}s^{-1}$)")
    grid.set_fontsize(22)
Beispiel #18
0
for i, sf in enumerate(a):
    rho = [500 / ccl.omega_x(c, sf, "matter") for c in cosmo]
    mf = [ccl.massfunc(c, M, sf, overdensity=r) for c, r in zip(cosmo, rho)]
    mfr[i] = mf[0] / mf[1]

mfr = np.array(mfr)

cmap = truncate_colormap(cm.Reds, 0.2, 1.0)
col = [cmap(i) for i in np.linspace(0, 1, len(a))]

fig, ax = plt.subplots()
ax.set_xlim(M.min(), M.max())
ax.axhline(y=1, ls="--", color="k")
[ax.loglog(M, R, c=c, label="%s" % red) for R, c, red in zip(mfr, col, z)]

ax.yaxis.set_major_formatter(FormatStrFormatter("$%.1f$"))
ax.yaxis.set_minor_formatter(FormatStrFormatter("$%.1f$"))

sm = plt.cm.ScalarMappable(cmap=cmap,
                           norm=plt.Normalize(vmin=z.min(), vmax=z.max()))
sm._A = []
cbar = fig.colorbar(sm)
ticks = cbar.get_ticks()
cbar.ax.invert_yaxis()
cbar.set_ticks(ticks[::-1])

ax.set_xlabel(r"$M_{500c} \mathrm{/ M_{\odot}}$", fontsize=17)
ax.set_ylabel(r"$n_{\mathrm{T}08}(M) / n_{\mathrm{T}10}(M)$", fontsize=17)
ax.tick_params(which="both", labelsize="large")

cbar.set_label("$z$", rotation=0, labelpad=15, fontsize=17)
Beispiel #19
0
    text += "$MAE_{4}$ = {5:0.2f} $\pm$ {6:0.3f}"
    text = text.format('{train}', MAE_train, MAE_train_std, '\n', '{test}',
                       MAE_test, MAE_test_std)
    plt.text(0.62,
             0.15,
             text,
             ha='center',
             va='center',
             fontsize=10,
             bbox=dict(facecolor='w',
                       edgecolor='black',
                       boxstyle='round',
                       pad=1),
             transform=ax.transAxes)
    if i == 4:
        ax.xaxis.set_major_formatter(FormatStrFormatter('%g'))
        ax.xaxis.set_ticks(np.arange(-2.5, 2, 1))
        ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
        ax.yaxis.set_ticks(np.arange(-2.5, 2, 1))
    '''
    if i == 2:
        ax.xaxis.set_major_formatter(FormatStrFormatter('%g'))
        ax.xaxis.set_ticks(np.arange(-4, 4, 1))
        ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
        ax.yaxis.set_ticks(np.arange(-4, 4, 1))
    '''
plt.subplots_adjust(left=0.1,
                    bottom=0.1,
                    right=0.9,
                    top=0.9,
                    wspace=0.3,
Beispiel #20
0
    def plot_uc_histogram(self,
                          info_list,
                          legend_list,
                          extra_title=None,
                          xsize=10,
                          ysize=10,
                          high_vis=False,
                          iqr_ratio=1.5,
                          ranges=None,
                          title=None):
        """
    Plot a 3x3 grid of plots showing unit cell dimensions.
    @param info list of lists of dictionaries. The outer list groups seperate lists
    of cells to be plotted in the same graph, where each dictionary describes one cell.
    @param extra_title will be added to the title of the plot
    @param xsize if class initialized with not interacive, this is the x size of the
    plot to save in inches
    @param ysize as xsize
    @param iqr_ratio Inter-quartile range multiplier for rejecting outliers
    @param ranges Limits for the a, b and c axes. Tuple of 6 doubles, low then high in pairs for each.
    @return if not interactive, returns the path of the saved image, otherwise None
    """
        if ranges is not None:
            assert len(ranges) == 6
            alim = ranges[0:2]
            blim = ranges[2:4]
            clim = ranges[4:6]
        else:
            alim = blim = clim = None

        plot_ratio = max(min(xsize, ysize) / 2.5, 3)
        if high_vis:
            text_ratio = plot_ratio * 4
            separator = "\n"
        else:
            text_ratio = plot_ratio * 3
            separator = "\n"

        # Initialize figure
        fig = plt.figure(figsize=(xsize, ysize))
        gsp = GridSpec(3, 4)
        legend_sub_a = fig.add_subplot(gsp[3])
        legend_sub_b = fig.add_subplot(gsp[7])
        legend_sub_c = fig.add_subplot(gsp[11])
        sub_ba = fig.add_subplot(gsp[0])
        sub_cb = fig.add_subplot(gsp[1])
        sub_ac = fig.add_subplot(gsp[2])
        sub_a = fig.add_subplot(gsp[4])
        sub_b = fig.add_subplot(gsp[5], sharey=sub_a)
        sub_c = fig.add_subplot(gsp[6], sharey=sub_a)
        sub_alpha = fig.add_subplot(gsp[8])
        sub_beta = fig.add_subplot(gsp[9], sharey=sub_alpha)
        sub_gamma = fig.add_subplot(gsp[10], sharey=sub_alpha)
        total = 0
        abc_hist_ylim = 0

        legend_sub_a.axis('off')
        legend_sub_b.axis('off')
        legend_sub_c.axis('off')

        for legend, info in zip(legend_list, info_list):
            if len(info) == 0:
                continue
            # Extract uc dimensions from info list
            a = flex.double([i['a'] for i in info])
            b = flex.double([i['b'] for i in info])
            c = flex.double([i['c'] for i in info])
            alpha = flex.double([i['alpha'] for i in info])
            beta = flex.double([i['beta'] for i in info])
            gamma = flex.double([i['gamma'] for i in info])
            if ranges is not None:
                sel = (a >= alim[0]) & (a <= alim[1]) & (b >= blim[0]) & (
                    b <= blim[1]) & (c >= clim[0]) & (c <= clim[1])
                a = a.select(sel)
                b = b.select(sel)
                c = c.select(sel)
                alpha = alpha.select(sel)
                beta = beta.select(sel)
                gamma = gamma.select(sel)

            accepted = flex.bool(len(a), True)
            for d in [a, b, c, alpha, beta, gamma]:
                outliers = self.reject_outliers(d, iqr_ratio)
                accepted &= ~outliers

            a = a.select(accepted)
            b = b.select(accepted)
            c = c.select(accepted)
            alpha = alpha.select(accepted)
            beta = beta.select(accepted)
            gamma = gamma.select(accepted)

            total += len(a)
            nbins = int(np.sqrt(len(a))) * 2
            n_str = "N: %d " % len(a)

            from matplotlib.ticker import FormatStrFormatter
            hists = []
            for name, dimension, sub, lim in \
              [('a', a, sub_a, alim), ('b', b, sub_b, blim), ('c', c, sub_c, clim)]:
                stats = flex.mean_and_variance(dimension)
                mean = stats.mean()
                try:
                    stddev = stats.unweighted_sample_standard_deviation()
                except RuntimeError:
                    raise Exception("Not enough data to produce a histogram")
                varstr = "%.2f +/- %.2f" % (mean, stddev)
                if len(legend) > 0:
                    dim_legend = legend + separator + varstr
                else:
                    dim_legend = varstr
                if len(info_list) > 1 and name == "a":
                    dim_legend = n_str + dim_legend
                hist = sub.hist(dimension,
                                nbins,
                                alpha=0.75,
                                histtype='stepfilled',
                                label=dim_legend,
                                range=lim)
                sub.set_xlabel("%s-edge (%s $\AA$)" %
                               (name, varstr)).set_fontsize(text_ratio)
                xloc = plt.MaxNLocator(5)
                if not high_vis:
                    sub.xaxis.set_major_locator(xloc)
                    sub.xaxis.set_major_formatter(FormatStrFormatter("%5.1f"))
                if name == 'a':
                    sub.set_ylabel('Number of images').set_fontsize(text_ratio)
                else:
                    self.plt.setp(sub.get_yticklabels(), visible=False)
                hists.append(hist)

            abc_hist_ylim = max(1.2 * max([max(h[0]) for h in hists]),
                                abc_hist_ylim)
            sub_a.set_ylim([0, abc_hist_ylim])

            for (n1, n2, d1, d2, lim1, lim2, sub) in \
              [('a', 'b', a, b, alim, blim, sub_ba),
               ('b', 'c', b, c, blim, clim, sub_cb),
               ('c', 'a', c, a, clim, alim, sub_ac)]:
                if len(info_list) == 1:
                    sub.hist2d(
                        d1,
                        d2,
                        bins=100,
                        range=[lim1, lim2] if ranges is not None else None)
                else:
                    sub.plot(d1.as_numpy_array(),
                             d2.as_numpy_array(),
                             '.',
                             alpha=0.1,
                             markeredgewidth=0,
                             markersize=2)
                    if ranges is not None:
                        sub.set_xlim(lim1)
                        sub.set_ylim(lim2)
                sub.set_xlabel("%s axis" % n1).set_fontsize(text_ratio)
                sub.set_ylabel("%s axis" % n2).set_fontsize(text_ratio)
                # plt.setp(sub.get_yticklabels(), visible=False)

            for ax in (sub_a, sub_b, sub_c, sub_alpha, sub_beta, sub_gamma):
                ax.tick_params(axis='both',
                               which='both',
                               left='off',
                               right='off')
                ax.set_yticklabels([])
            for ax in (sub_ba, sub_cb, sub_ac):
                ax.tick_params(axis='both',
                               which='both',
                               bottom='off',
                               top='off',
                               left='off',
                               right='off')
                ax.set_xticklabels([])
                ax.set_yticklabels([])

            for (name, angle, sub) in \
              [(r'$\alpha$', alpha, sub_alpha),
               (r'$\beta$', beta, sub_beta),
               (r'$\gamma$', gamma, sub_gamma)]:
                sub.hist(angle, nbins, alpha=0.75, histtype='stepfilled')
                stats = flex.mean_and_variance(angle)
                mean = stats.mean()
                stddev = stats.unweighted_sample_standard_deviation()
                sub.set_xlabel(r'%s (%.2f +/- %.2f$^\circ$)' %
                               (name, mean, stddev)).set_fontsize(text_ratio)
                xloc = plt.MaxNLocator(5)
                if not high_vis:
                    sub.xaxis.set_major_locator(xloc)
                    sub.xaxis.set_major_formatter(FormatStrFormatter("%5.1f"))
                if name == '\alpha':
                    sub.set_ylabel('Number of images').set_fontsize(text_ratio)
                else:
                    self.plt.setp(sub.get_yticklabels(), visible=False)

        sub_b.xaxis.get_major_ticks()[0].label1.set_visible(False)
        sub_b.xaxis.get_major_ticks()[-1].label1.set_visible(False)
        sub_c.xaxis.get_major_ticks()[0].label1.set_visible(False)
        sub_c.xaxis.get_major_ticks()[-1].label1.set_visible(False)
        sub_ba.xaxis.get_major_ticks()[0].label1.set_visible(False)
        sub_ba.xaxis.get_major_ticks()[-1].label1.set_visible(False)
        sub_cb.xaxis.get_major_ticks()[0].label1.set_visible(False)
        sub_cb.xaxis.get_major_ticks()[-1].label1.set_visible(False)
        sub_ac.xaxis.get_major_ticks()[0].label1.set_visible(False)
        sub_ac.xaxis.get_major_ticks()[-1].label1.set_visible(False)
        sub_beta.xaxis.get_major_ticks()[0].label1.set_visible(False)
        sub_beta.xaxis.get_major_ticks()[-1].label1.set_visible(False)
        sub_gamma.xaxis.get_major_ticks()[0].label1.set_visible(False)
        sub_gamma.xaxis.get_major_ticks()[-1].label1.set_visible(False)

        h, l = sub_a.get_legend_handles_labels()
        legend_sub_a.legend(h, l, fontsize=text_ratio)
        h, l = sub_b.get_legend_handles_labels()
        legend_sub_b.legend(h, l, fontsize=text_ratio)
        h, l = sub_c.get_legend_handles_labels()
        legend_sub_c.legend(h, l, fontsize=text_ratio)

        # if len(legend_list) > 0:
        #   import matplotlib.patches as mpatches
        #   rgb_alphas = [a_hist[2][i] for i in range(len(a_hist[2]))]
        #   assert len(legend_list) == len(rgb_alphas)
        #   patches = [mpatches.Patch(
        #     color=rgb_alphas[i].get_facecolor(),
        #     label=legend_list[i])
        #   for i in range(len(rgb_alphas))]
        #   fig.legend(patches, 'upper right')

        gsp.update(wspace=0)
        if title is None: title = "Unit cell distribution"
        fig.suptitle(title + " (%d xtals)" % total)

        if not self.interactive:
            fig.set_size_inches(xsize * 1.05 + .5, ysize * .95)
            fig.savefig("ucell_tmp.png", bbox_inches='tight', dpi=100)
            plt.close(fig)
            return "ucell_tmp.png"
Beispiel #21
0
def plot_stability(xData=None,
                   xData_err=None,
                   data_datasets=None,
                   mc_datasets=None,
                   data_errorsets=None,
                   mc_errorsets=None,
                   label='',
                   category='',
                   path="",
                   evenX=False,
                   xVar='',
                   iovs=None,
                   showMC=False,
                   names=None,
                   style='ggplot',
                   oldStyle=False,
                   colours=None):

    plt.style.use(style)

    left, width = 0.1, 1.0
    bottom, height = 0.1, 0.5
    rect_hist = [left + width + 0.01, bottom, 0.2, height]
    rect_plot = [left, bottom, width, height]

    nullfmt = NullFormatter()

    fig = plt.figure()

    ax_plot = plt.axes(rect_plot)
    ax_hist = plt.axes(rect_hist)
    for k, spine in ax_plot.spines.items():
        spine.set_zorder(10)
    for k, spine in ax_hist.spines.items():
        spine.set_zorder(10)

    ax_hist.yaxis.set_major_formatter(nullfmt)

    xPlaceholder = range(1, 1 + len(xData), 1)

    for data_dataset, data_errorset, colour in zip(data_datasets,
                                                   data_errorsets, colours):
        if evenX:
            if oldStyle:
                ax_plot.errorbar(xPlaceholder,
                                 data_dataset,
                                 yerr=data_errorset,
                                 capthick=0,
                                 marker='o',
                                 ms=4,
                                 c=colour,
                                 ls='none')
            else:
                ax_plot.errorbar(xPlaceholder,
                                 data_dataset,
                                 yerr=data_errorset,
                                 capthick=0,
                                 marker='.',
                                 ms=4,
                                 ls='solid',
                                 c=colour)
        else:
            if oldStyle:
                ax_plot.errorbar(xData,
                                 data_dataset,
                                 yerr=data_errorset,
                                 capthick=0,
                                 marker='o',
                                 ms=4,
                                 c=colour,
                                 ls='none')
            else:
                ax_plot.errorbar(xData,
                                 data_dataset,
                                 yerr=data_errorset,
                                 capthick=0,
                                 marker='.',
                                 ms=4,
                                 ls='solid',
                                 c=colour)

    # customise the axes
    xDataVar = xData.name
    if xDataVar == 'time':
        ax_plot.xaxis.set_minor_locator(dates.DayLocator(interval=10))
        ax_plot.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
        ax_plot.xaxis.set_major_locator(dates.MonthLocator())
        ax_plot.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
    elif (xDataVar == 'run_max' or xDataVar == 'run_min') and not evenX:
        majorLocator = MultipleLocator(125)
        minorLocator = MultipleLocator(62.5)
        ax_plot.xaxis.set_major_locator(majorLocator)
        ax_plot.xaxis.set_minor_locator(minorLocator)
        majorFormatter = FormatStrFormatter('%d')
        ax_plot.xaxis.set_major_formatter(majorFormatter)
        xlabels = ax_plot.get_xticklabels()
        plt.setp(xlabels, rotation=90, fontsize=10)
    elif (xDataVar == 'run_max' or xDataVar == 'run_min') and evenX:
        majorLocator = MultipleLocator(2)
        minorLocator = MultipleLocator(1)
        ax_plot.xaxis.set_major_locator(majorLocator)
        ax_plot.xaxis.set_minor_locator(minorLocator)
        xlabels = ax_plot.get_xticks().tolist()

        for i in range(2, len(xData), 2):
            xlabels[i / 2 + 1] = xData.tolist()[i - 1]
        for i in range(len(xlabels)):
            if xlabels[i] < 200000: xlabels[i] = ''
        for index, row in iovs.iterrows():
            for j in range(0, len(xData) - 1):
                if row['run'] >= xData[j] and row['run'] < xData[j + 1]:
                    if 'Run' in row['info']:
                        ax_plot.axvline(x=j + 1,
                                        color='#EBAF3C',
                                        ls='--',
                                        zorder=5)
                    else:
                        ax_plot.axvline(x=j + 1,
                                        color='#1072C3',
                                        ls='--',
                                        zorder=5)
        ax_plot.set_xticklabels(xlabels)
        xlabels = ax_plot.get_xticklabels()
        plt.setp(xlabels, rotation=90, fontsize=10)

    ax_plot.xaxis.grid(True, which="minor")
    ax_plot.yaxis.grid()
    ax_hist.xaxis.grid(True, which="minor")
    ax_hist.yaxis.grid()
    ax_hist.xaxis.set_ticks([])

    #Get and set the limits for the histogram
    ymin = 9999
    ymax = -9999
    for data_dataset, mc_dataset in zip(data_datasets, mc_datasets):
        if (len(mc_dataset) > 0):
            ymintemp = round(min(data_dataset.min(), mc_dataset.min())) - 1
            ymaxtemp = round(max(data_dataset.max(), mc_dataset.max())) + 1
            if ymintemp < ymin: ymin = ymintemp
            if ymaxtemp > ymax: ymax = ymaxtemp
        else:
            ymintemp = round(data_dataset.min()) - 1
            ymaxtemp = round(data_dataset.max()) + 1
            if ymintemp < ymin: ymin = ymintemp
            if ymaxtemp > ymax: ymax = ymaxtemp

    ax_plot.set_ylim((ymin, ymax))
    ax_hist.set_ylim((ymin, ymax))

    ax_plot.set_ylabel(label)

    nbin = 30

    hmaxes = []
    for data_dataset, colour in zip(data_datasets, colours):
        y, _, _ = ax_hist.hist(data_dataset,
                               bins=nbin,
                               orientation='horizontal',
                               histtype='stepfilled',
                               alpha=0.5,
                               color=colour)
        hmaxes.append(y.max())
    hmax = max(hmaxes)
    ax_hist.set_xlim((0, hmax * 1.1))

    ax_plot.set_title(region_labels[category] + "    " + label)

    #Annotate with mean and std dev
    step = 0.05
    for data_dataset, name, colour in zip(data_datasets, names, colours):
        npVals = np.asarray(data_dataset)
        name_gap = ' ' * len(name)
        ax_hist.annotate('{:s}:\n$\mu$ = {:3.3f}, $\sigma$ = {:3.3f}'.format(
            name, np.mean(npVals), np.std(npVals)),
                         (hmax * 1.15, ymax - (ymax - ymin) * (0.1 + step)),
                         fontsize=11,
                         annotation_clip=False,
                         xycoords='data',
                         color=colour)
        step += 0.14

    #Add line for the MC
    mc_dataset = mc_datasets[0]
    mc_errorset = mc_errorsets[0]
    if (len(mc_dataset) > 0):
        if evenX:
            if oldStyle:
                ax_plot.errorbar(xPlaceholder,
                                 mc_dataset,
                                 yerr=mc_errorset,
                                 capthick=0,
                                 marker='o',
                                 ms=4,
                                 ls='solid',
                                 c='Black')
            else:
                ax_plot.errorbar(xPlaceholder,
                                 mc_dataset,
                                 yerr=mc_errorset,
                                 capthick=0,
                                 marker='',
                                 ms=4,
                                 ls='dotted',
                                 c='Black')
        else:
            if oldStyle:
                ax_plot.errorbar(xData,
                                 mc_dataset,
                                 yerr=mc_errorset,
                                 capthick=0,
                                 marker='o',
                                 ms=4,
                                 ls='solid',
                                 c='Black')
            else:
                ax_plot.errorbar(xData,
                                 mc_dataset,
                                 yerr=mc_errorset,
                                 capthick=0,
                                 marker='',
                                 ms=4,
                                 ls='dotted',
                                 c='Black')

        if evenX:
            xNP = np.asarray(xPlaceholder)
        else:
            xNP = np.asarray(xData.tolist())

        mcNP = np.asarray(mc_dataset.tolist())
        mcErrNP = np.asarray(mc_errorset.tolist())

        ax_plot.fill_between(xNP, mcNP - mcErrNP, mcNP + mcErrNP, alpha=0.5)

        if xVar == '':
            ax_hist.annotate(
                'MC = {:3.3f} $\pm$ {:3.3f}'.format(mc_dataset[1],
                                                    mc_errorset[1]),
                (hmax * 1.15, ymax - (ymax - ymin) * (0.05 + step)),
                fontsize=11,
                annotation_clip=False,
                xycoords='data')

    #Legend
    legend = ax_plot.legend(loc='lower left', numpoints=1, prop={'size': 9})
    if (len(mc_datasets[0]) > 0):
        for i, name in enumerate(names):
            legend.get_texts()[i].set_text(name)
        legend.get_texts()[len(names)].set_text('MC')
    else:
        for i, name in enumerate(names):
            legend.get_texts()[i].set_text(name)
    legend.get_frame().set_alpha(0.5)
    legend.get_frame().set_linewidth(0.0)
    ax_hist.grid(which='major',
                 color='0.7',
                 linestyle='--',
                 dashes=(5, 1),
                 zorder=0)
    ax_plot.grid(which='major',
                 color='0.7',
                 linestyle='--',
                 dashes=(5, 1),
                 zorder=0)
    ax_plot.grid(which='minor',
                 color='0.85',
                 linestyle='--',
                 dashes=(5, 1),
                 zorder=0)

    #Save
    if evenX:
        xDataVar = xDataVar + '_even'

    if not os.path.exists(path + '/' + xDataVar):
        os.makedirs(path + '/' + xDataVar)

    fileName = category + '_' + re.sub(r'[\\@#$/{}^]', '', label)
    fileName = re.sub(r'[ ]', '_', fileName)

    for fType in format_fig_output:
        print 'Saving plot: ' + path + xDataVar + '/' + fileName + '.' + fType
        plt.savefig(path + xDataVar + '/' + fileName + '.' + fType,
                    format=fType,
                    orientation='landscape',
                    dpi=200,
                    papertype='a4',
                    pad_inches=0.1,
                    bbox_inches='tight')

    plt.close(fig)
Beispiel #22
0
def main():

    bar_colors = [
        colors.cnames['hotpink'], colors.cnames['deepskyblue'],
        colors.cnames['cornflowerblue']
    ]
    bar_labels = ['optimized', 'fixed1', 'fixed2']

    fig = plt.figure(figsize=(30, 10), dpi=220)

    plt.subplots_adjust(wspace=0.4)
    plt.rcParams['font.family'] = 'arial'
    rc('font', weight='bold')

    # 左のグラフの描画
    plt.subplot(1, 3, 1)

    method_num = 3
    user_num = 2

    raw_data = [[[] for i in range(user_num)] for j in range(method_num)]
    data = [[] for i in range(method_num)]
    yerr = [[] for i in range(method_num)]

    with open('experiment_data.csv', 'r') as f:
        reader = csv.reader(f)
        next(reader)

        for row in reader:
            for i in range(method_num):
                for j in range(user_num):
                    raw_data[i][j].append(row[8 + i + j * method_num])

        for i in range(method_num):
            for q in raw_data[i]:
                q_data = [int(x) for x in q]
                data[i].append(statistics.mean(q_data))
                yerr[i].append(
                    statistics.pstdev(q_data) / math.sqrt(len(q_data)))

    x = np.arange(user_num)
    bar_width = 0.2

    plt.grid(which='major', axis='y', color='black', linestyle='--', alpha=0.3)
    plt.tick_params(bottom=False)

    for i in range(method_num):
        plt.bar(x + i * bar_width,
                data[i],
                color=bar_colors[i],
                width=bar_width,
                yerr=yerr[i],
                capsize=6,
                label=bar_labels[i],
                align='center')

    plt.ylim([50, 90])
    plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    plt.ylabel('Mean accuracy rate [%]', fontsize=44, weight='bold')
    plt.yticks([50.00, 60.00, 70.00, 80.00, 90.00], fontsize=44)

    plt.xlabel('(a)', fontsize=44, weight='bold')
    plt.xticks(x + bar_width, ['main user', 'bystander'], fontsize=44)

    plt.legend(bbox_to_anchor=(0.6, 1.2),
               loc='upper left',
               borderaxespad=0,
               fontsize=44,
               ncol=3)

    # 中央のグラフの描画
    plt.subplot(1, 3, 2)

    raw_data = [[] for i in range(method_num)]
    with open('experiment_data.csv', 'r') as f:
        reader = csv.reader(f)
        next(reader)

        for row in reader:
            for i in range(method_num):
                raw_data[i].append(int(row[14 + i]) / 1000)

    data = []
    yerr = []
    for i in range(method_num):
        data.append(statistics.mean(raw_data[i]))
        yerr.append(
            statistics.pstdev(raw_data[i]) / math.sqrt(len(raw_data[i])))

    x = np.arange(method_num)
    bar_width = 1.0

    plt.grid(which='major', axis='y', color='black', linestyle='--', alpha=0.3)
    plt.tick_params(bottom=False)

    plt.bar(x,
            data,
            color=bar_colors,
            width=bar_width,
            yerr=yerr,
            capsize=6,
            align='center')

    plt.ylim([130, 180])
    plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%d'))
    plt.ylabel('Mean time [s]', fontsize=44, weight='bold')
    plt.yticks([130, 140, 150, 160, 170, 180], fontsize=44)

    dummy = ['a'] * method_num
    plt.xlim([-3, 5])
    plt.xlabel('(b)', fontsize=44, weight='bold')
    plt.xticks(x, dummy, fontsize=44, color=colors.cnames['white'])

    # 右のグラフの描画
    plt.subplot(1, 3, 3)

    raw_data = [[] for i in range(method_num)]
    with open('experiment_data.csv', 'r') as f:
        reader = csv.reader(f)
        next(reader)

        for row in reader:
            for i in range(method_num):
                raw_data[i].append(int(row[17 + i]))

    data = []
    yerr = []
    for i in range(method_num):
        data.append(statistics.mean(raw_data[i]))
        yerr.append(
            statistics.pstdev(raw_data[i]) / math.sqrt(len(raw_data[i])))

    plt.grid(which='major', axis='y', color='black', linestyle='--', alpha=0.3)
    plt.tick_params(bottom=False)

    plt.bar(x,
            data,
            color=bar_colors,
            width=bar_width,
            yerr=yerr,
            capsize=6,
            align='center')
    plt.ylim([10, 50])
    plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%d'))
    plt.ylabel('Mean # of item selections', fontsize=44, weight='bold')
    plt.yticks([10, 20, 30, 40, 50], fontsize=44)

    plt.xlim([-3, 5])
    plt.xlabel('(c)', fontsize=44, weight='bold')
    plt.xticks(x, dummy, fontsize=44, color=colors.cnames['white'])

    add_asterisk(0, 2, x, bar_width, data, yerr)
    add_asterisk(1, 2, x, bar_width, data, yerr)

    output_file_name = 'task_variables_result.eps'
    plt.savefig(output_file_name, bbox_inches='tight', pad_inches=0.2)

    # latexでのずれを防ぐため,一度pdfにしてepsに戻すスクリプトを実行
    subprocess.run(['./epsbound.sh', output_file_name])
    def plot_data(self):
        fig = 0
        # plot data in two and one-d
        if np.shape(self.x)[1] < 2:
            # construct figure
            fig, axs = plt.subplots(2, 1, figsize=(4, 4))
            gs = gridspec.GridSpec(2, 1, height_ratios=[6, 1])
            ax1 = plt.subplot(gs[0], aspect='equal')
            ax2 = plt.subplot(gs[1], sharex=ax1)

            # set plotting limits
            xmax = copy.deepcopy(max(self.x))
            xmin = copy.deepcopy(min(self.x))
            xgap = (xmax - xmin) * 0.2
            xmin -= xgap
            xmax += xgap

            ymax = max(self.y)
            ymin = min(self.y)
            ygap = (ymax - ymin) * 0.5
            ymin -= ygap
            ymax += ygap

            ### plot in 2-d
            ax1.scatter(self.x,
                        self.y,
                        color='k',
                        edgecolor='w',
                        linewidth=0.9,
                        s=40)

            # clean up panel
            ax1.set_xlim([xmin, xmax])
            ax1.set_ylim([ymin, ymax])
            ax1.axhline(linewidth=0.5, color='k', zorder=1)

            ### plot in 1-d
            ind0 = np.argwhere(self.y == +1)
            ax2.scatter(self.x[ind0],
                        np.zeros((len(self.x[ind0]))),
                        s=55,
                        color=self.colors[0],
                        edgecolor='k',
                        zorder=3)

            ind1 = np.argwhere(self.y == -1)
            ax2.scatter(self.x[ind1],
                        np.zeros((len(self.x[ind1]))),
                        s=55,
                        color=self.colors[1],
                        edgecolor='k',
                        zorder=3)
            ax2.set_yticks([0])
            ax2.axhline(linewidth=0.5, color='k', zorder=1)

            ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
            ax2.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))

        if np.shape(self.x)[1] == 2:
            # construct figure
            fig, axs = plt.subplots(1, 2, figsize=(9, 4))

            # create subplot with 2 panels
            gs = gridspec.GridSpec(1, 2)
            ax2 = plt.subplot(gs[1], aspect='equal')
            ax1 = plt.subplot(gs[0], projection='3d')

            # scatter points
            self.scatter_pts(ax1, self.x)

            ### from above
            ax2.set_xlabel(r'$x_1$', fontsize=15)
            ax2.set_ylabel(r'$x_2$', fontsize=15, rotation=0, labelpad=20)
            ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
            ax2.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))

            # plot points in 2d and 3d
            C = len(np.unique(self.y))
            if C == 2:
                ind0 = np.argwhere(self.y == +1)
                ax2.scatter(self.x[ind0, 0],
                            self.x[ind0, 1],
                            s=55,
                            color=self.colors[0],
                            edgecolor='k')

                ind1 = np.argwhere(self.y == -1)
                ax2.scatter(self.x[ind1, 0],
                            self.x[ind1, 1],
                            s=55,
                            color=self.colors[1],
                            edgecolor='k')
            else:
                for c in range(C):
                    ind0 = np.argwhere(self.y == c)
                    ax2.scatter(self.x[ind0, 0],
                                self.x[ind0, 1],
                                s=55,
                                color=self.colors[c],
                                edgecolor='k')

            self.move_axis_left(ax1)
            ax1.set_xlabel(r'$x_1$', fontsize=12, labelpad=5)
            ax1.set_ylabel(r'$x_2$', rotation=0, fontsize=12, labelpad=5)
            ax1.set_zlabel(r'$y$', rotation=0, fontsize=12, labelpad=-3)
Vtt = (Vt * (rho * ik)) / (2 * np.pi * l)

print("Número de elementos por eje:", np.count_nonzero(Xa))
aa = np.where(np.amax(Vtt) == Vtt)
print("Valor máximo de tensión:", round(Vtt[::].max(),
                                        3), "[V], en posición: (",
      round(Xa[aa[0][0]], 2), ",", round(Ya[aa[1][0]], 2), ")")
bb = np.where(np.amin(Vtt) == Vtt)
print("Valor mínimo de tensión:", round(Vtt[::].min(),
                                        3), "[V], en posición: (",
      round(Xa[bb[0][0]], 2), ",", round(Ya[bb[1][0]], 2), ")")
print("Número de elemmentos de Vt:", np.count_nonzero(Vtt))
print("Elementos de Xa al cuadrado:", np.count_nonzero(Xa)**2)
X, Y = np.meshgrid(Xa, Ya)
print("Nuevo número de elementos de X y Y:", np.count_nonzero(X))

surf = axx.plot_surface(X,
                        Y,
                        Vtt,
                        cmap=cm.get_cmap("Spectral"),
                        linewidth=0,
                        antialiased=False)

# Customize the z axis.
axx.set_zlim(300, 1800)
axx.zaxis.set_major_locator(LinearLocator(10))
axx.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
def con_con_comparison(args):
    """
    cross conservation comparison

    :param args:
    :return:
    """
    rp = args.concon_reference  # reference ligand name
    prot = args.ligands[rp]  # reference ligand
    seq = prot.get_ref_seq()  # reference ligand sequence
    msta = args.msta  # multiple structure alignment
    msa = args.msa  # multiple sequence alignment
    contest = args.conservation_test  # conservation test type
    algtest = args.alignment_test  # conservation for ligand alignment type

    # data preparation
    cs = pd.DataFrame()
    # add separating variable when it is 7 lumps of data
    sepvar = 0
    if algtest == "id":
        sepvar = 0.04
    cs["MSA"] = [round(x, 2) + sepvar for x in msa.get_cons_scores(algtest)]
    cs["MSTA"] = [round(x, 2) - sepvar for x in msta.get_cons_scores(algtest)]
    cs[prot.name] = prot.get_cons_scores(contest)
    cs.insert(0, 'POS', [str(x) + seq[x - 1] for x in range(1, 1 + len(cs))])

    # plotting
    fig, ax = plt.subplots()
    fig.set_size_inches(11.7, 8.27)  # A4 size

    def plotter(fig, ax, alg_label, colour, pname):
        #scatter plot
        sb.regplot(alg_label,
                   pname,
                   cs,
                   scatter=True,
                   fit_reg=False,
                   ax=ax,
                   label=alg_label)

        # labels
        dpos = set()

        def label_point(x, y, val, ax, dpos):
            a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
            for i, point in a.iterrows():
                point['x'] += 0.01
                i = 0
                while (point['x'], point['y']) in dpos:
                    if i == 1:
                        point['x'] -= 0.04
                        point['y'] -= 0.01
                        i = -1
                    if i == 1 and round(point['x'], 2) == 1:
                        point['x'] -= 0.04
                        point['y'] -= 0.01
                        i = -1
                    i += 1
                    point['x'] += 0.02
                dpos.add((point['x'], point['y']))
                ax.text(point['x'],
                        point['y'],
                        str(point['val']),
                        fontsize=5,
                        color=colour)

        label_point(cs[alg_label], cs[prot.name], cs.POS, plt.gca(), dpos)

    plotter(fig, ax, "MSA", "black", prot.name)
    plotter(fig, ax, "MSTA", "red", prot.name)

    # plot diagonal line
    lims = [
        np.min([ax.get_xlim(), ax.get_ylim()]),
        np.max([ax.get_xlim(), ax.get_ylim()]),
    ]
    ax.plot(lims, lims, ls="--", c=".3")
    # in case it is 7 lumps of X axis
    if algtest == "id":  # it is 7 blocks
        ax.xaxis.set_major_formatter(
            FormatStrFormatter('%.2f'))  # float representation to 2 decimals
        ax.bar(np.arange(0, 1.01, 1 / 6), [ax.get_ylim()[1]] * 7,
               width=[0.15] * 7,
               color="grey",
               alpha=0.3)  # backgroun bars
        plt.xticks(np.arange(0, 1.01, 1 / 6))  # ligands xticks
    # labels
    plt.ylabel("Evolutionary Conservation")
    plt.xlabel("Ligands Alignments Conservation")
    plt.legend(loc=4)

    # saving
    plt.savefig("{}/{}concon.svg".format(args.output_path, prot.name),
                format='svg',
                dpi=1200)
    # save text output also
    with open("{}/{}concon.csv".format(args.output_path, prot.name),
              "w") as outfile:
        cs.to_csv(outfile, sep="\t")
Beispiel #26
0
grid of the minor ticks for a given axis, use for example

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

Note, you should not use the same locator between different Axis
because the locator stores references to the Axis data and view limits

"""

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
                               AutoMinorLocator)

majorLocator = MultipleLocator(20)
majorFormatter = FormatStrFormatter('%d')
minorLocator = MultipleLocator(5)

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)

fig, ax = plt.subplots()
plt.plot(t, s)

ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)

# for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)

plt.show()
Beispiel #27
0
 def __init__(self, factor):
     FormatStrFormatter.__init__(self, '%g')
     self._factor = factor
    def plot_InducedCurrent_cos(self, ax1, ax2, Ire, Iim, Is, phi, f, t):

        FS = 20

        # Numerical Values
        w = 2 * np.pi * f
        I0 = self.I * np.cos(w * t)
        Ipmax = self.I
        Ismax = np.max(Is)
        Iremax = np.max(Ire)
        Iimmax = np.max(Iim)
        T = 1 / f

        tL_phase = np.array([2 * T, 2 * T])
        IL_phase = np.array([Ipmax, 1.25 * Ipmax])
        tR_phase = np.array([2 * T - phi / w, 2 * T - phi / w])
        IR_phase = np.array([Ismax, 4.1 * Ismax])
        zero_line = 0 * t

        xTicks = (np.max(t) / 8) * np.linspace(0, 8, 9)
        xLabels = ["0", "T/2", "T", "3T/2", "2T", "5T/2", "3T", "7T/2", "4T"]

        ax1.grid("both", linestyle="-", linewidth=0.8, color=[0.8, 0.8, 0.8])
        ax1.plot(t, zero_line, color="k", linewidth=2)
        ax1.plot(t, I0, color="k", linewidth=4)
        ax1.plot(tL_phase, IL_phase, color="k", ls=":", linewidth=8)
        ax1.set_xbound(0, np.max(t))
        ax1.set_ybound(1.55 * np.min(I0), 1.55 * np.max(I0))
        ax1.set_xlabel("Time", fontsize=FS + 2)
        ax1.set_ylabel("Primary Current [A]", fontsize=FS + 2)
        ax1.tick_params(labelsize=FS - 2)

        ax1b = ax1.twinx()
        ax1b.plot(t, Is, color="g", linewidth=4)
        ax1b.plot(tR_phase, IR_phase, color="k", ls=":", linewidth=8)
        ax1b.set_xbound(0, np.max(t))
        ax1b.set_ybound(5.01 * np.min(Is), 5.01 * np.max(Is))
        ax1b.set_ylabel("Secondary Current [A]", fontsize=FS + 2, color="g")
        ax1b.tick_params(labelsize=FS - 2)
        ax1b.tick_params(axis="y", colors="g")
        ax1b.xaxis.set_ticks(xTicks)
        ax1b.xaxis.set_ticklabels(xLabels)
        ax1b.yaxis.set_major_formatter(FormatStrFormatter("%.2e"))

        T_str = "{:.3e}".format(T)
        Ip_str = "{:.3e}".format(self.I)
        Is_str = "{:.3e}".format(np.max(Is))
        phi_str = "{:.1f}".format(-180 * phi / np.pi)
        ax1.text(0.05 * T,
                 1.3 * Ipmax,
                 "Period = " + T_str + " s",
                 fontsize=FS - 2)
        ax1.text(
            0.05 * T,
            -1.24 * Ipmax,
            "$I_p$ Amplitude = " + Ip_str + " A",
            fontsize=FS - 2,
        )
        ax1.text(
            0.05 * T,
            -1.45 * Ipmax,
            "$I_s$ Amplitude = " + Is_str + " A",
            fontsize=FS - 2,
            color="g",
        )
        ax1.text(
            1.7 * T,
            1.3 * Ipmax,
            "Phase Lag ($\phi$) = " + phi_str + "$^o$",
            fontsize=FS,
            color="k",
        )

        ax2.grid("both", linestyle="-", linewidth=0.8, color=[0.8, 0.8, 0.8])
        ax2.plot(t, zero_line, color="k", linewidth=2)
        ax2.plot(t, Ire, color="b", linewidth=4)
        ax2.plot(t, Iim, color="r", linewidth=4)
        ax2.set_xbound(0, np.max(t))
        ax2.set_ybound(1.61 * np.min(Is), 1.61 * np.max(Is))
        ax2.set_xlabel("Time", fontsize=FS + 2)
        ax2.set_ylabel("Secondary Current [A]", fontsize=FS + 2)
        ax2.tick_params(labelsize=FS - 2)
        ax2.xaxis.set_ticks(xTicks)
        ax2.xaxis.set_ticklabels(xLabels)
        ax2.yaxis.set_major_formatter(FormatStrFormatter("%.2e"))

        Ire_str = "{:.3e}".format(Iremax)
        Iim_str = "{:.3e}".format(Iimmax)
        ax2.text(
            0.05 * T,
            -1.25 * Ismax,
            "$I_{phase}$ Amplitude = " + Ire_str + " A",
            fontsize=FS - 2,
            color="b",
        )
        ax2.text(
            0.05 * T,
            -1.52 * Ismax,
            "$I_{quad}$ Amplitude = " + Iim_str + " A",
            fontsize=FS - 2,
            color="r",
        )

        return ax1, ax1b, ax2
Beispiel #29
0
# Trimming trailing xticks zeros with matplotlib
from matplotlib.ticker import FormatStrFormatter
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%g'))
    def static_N2_simple(self, w_best, runner, **kwargs):
        cost = runner.cost
        predict = runner.model
        full_predict = runner.full_model
        feat = runner.feature_transforms
        normalizer = runner.normalizer
        inverse_nornalizer = runner.inverse_normalizer
        x_train = inverse_nornalizer(runner.x_train).T
        y_train = runner.y_train

        x_test = inverse_nornalizer(runner.x_test).T
        y_test = runner.y_test

        # or just take last weights
        self.w = w_best

        # construct figure
        fig, axs = plt.subplots(1, 1, figsize=(9, 4))

        # create subplot with 2 panels
        gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
        ax2 = plt.subplot(gs[0], aspect='equal')
        ax3 = plt.subplot(gs[1])
        ax3.axis('off')

        ### create boundary data ###
        xmin1 = np.min(self.x[:, 0])
        xmax1 = np.max(self.x[:, 0])
        xgap1 = (xmax1 - xmin1) * 0.05
        xmin1 -= xgap1
        xmax1 += xgap1

        xmin2 = np.min(self.x[:, 1])
        xmax2 = np.max(self.x[:, 1])
        xgap2 = (xmax2 - xmin2) * 0.05
        xmin2 -= xgap2
        xmax2 += xgap2

        # plot boundary for 2d plot
        r1 = np.linspace(xmin1, xmax1, 300)
        r2 = np.linspace(xmin2, xmax2, 300)
        s, t = np.meshgrid(r1, r2)
        s = np.reshape(s, (np.size(s), 1))
        t = np.reshape(t, (np.size(t), 1))
        h = np.concatenate((s, t), axis=1)

        # compute model on train data
        z1 = predict(normalizer(h.T), self.w)
        z1 = np.sign(z1)

        # reshape it
        s.shape = (np.size(r1), np.size(r2))
        t.shape = (np.size(r1), np.size(r2))
        z1.shape = (np.size(r1), np.size(r2))

        ### loop over two panels plotting each ###
        for ax in [ax2]:
            # plot training points
            ind0 = np.argwhere(y_train == +1)
            ind0 = [v[1] for v in ind0]
            ax.scatter(x_train[ind0, 0],
                       x_train[ind0, 1],
                       s=55,
                       color=self.colors[0],
                       edgecolor='k',
                       linewidth=2.5,
                       zorder=3)

            ind1 = np.argwhere(y_train == -1)
            ind1 = [v[1] for v in ind1]
            ax.scatter(x_train[ind1, 0],
                       x_train[ind1, 1],
                       s=55,
                       color=self.colors[1],
                       edgecolor='k',
                       linewidth=2.5,
                       zorder=3)

            # plot testing points
            ind0 = np.argwhere(y_test == +1)
            ind0 = [v[1] for v in ind0]
            ax.scatter(x_test[ind0, 0],
                       x_test[ind0, 1],
                       s=55,
                       color=self.colors[0],
                       edgecolor=[1, 0.8, 0.5],
                       linewidth=2.5,
                       zorder=3)

            ind1 = np.argwhere(y_test == -1)
            ind1 = [v[1] for v in ind1]
            ax.scatter(x_test[ind1, 0],
                       x_test[ind1, 1],
                       s=55,
                       color=self.colors[1],
                       edgecolor=[1, 0.8, 0.5],
                       linewidth=2.5,
                       zorder=3)

            #### plot contour, color regions ####
            ax.contour(s,
                       t,
                       z1,
                       colors='k',
                       linewidths=2.5,
                       levels=[0],
                       zorder=2)
            ax.contourf(s,
                        t,
                        z1,
                        colors=[self.colors[1], self.colors[0]],
                        alpha=0.15,
                        levels=range(-1, 2))

            # cleanup panel
            ax.set_xlabel(r'$x_1$', fontsize=15)
            ax.set_ylabel(r'$x_2$', fontsize=15, rotation=0, labelpad=20)
            ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
            ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
Beispiel #31
0
    def acsPlots(self):
        for plot_number in range(1, self.numberFrequencyGroups() + 1):

            matplotlib.rcParams['xtick.direction'] = 'out'
            matplotlib.rcParams['ytick.direction'] = 'out'
            figure = matplotlib.pyplot.figure(1, figsize=(10, 6))
            acs = figure.add_subplot(111)

            for i in range(0, self.numberModes()):
                if self.frequencyGroups()[i][1] == plot_number:
                    acs.plot(numpy.arange(0, 1 + self.stepSize(),
                                          self.stepSize()),
                             numpy.transpose(self.data())[i],
                             linewidth=1.,
                             color=self.normalModeSymmetryColors()[i])
            acs.set_xlabel("Scaling Factor \(\lambda\)")
            acs.set_ylabel(
                "Local Mode Frequenices \(\omega_{a}\)[cm\(^{-1}\)]")
            acs.text(
                1.01,
                ((matplotlib.pyplot.ylim()[1] - matplotlib.pyplot.ylim()[0]) /
                 2) + matplotlib.pyplot.ylim()[0],
                "Normal Mode Frequencies \(\omega_{\mu}\)[cm\(^{-1}\)]",
                rotation='vertical',
                verticalalignment='center')
            figure.suptitle(str(self.__file_name_root).replace('_', '\_'))

            # Generate local mode labels
            deltaValue = 0.06
            i = 0
            while i < self.numberModes():
                delta = 0.
                average = 0.
                text = ""
                j = 0
                while delta <= deltaValue:
                    if j >= 1:
                        text = text + ","
                    text = text + "\(\omega_{a}\)(" + str(
                        self.__data_arrangement[i + j][1] + 1) + ")"
                    average += self.localModeFrequencies()[i + j]
                    j += 1
                    if j + i >= self.numberModes():
                        break
                    else:
                        delta = ((self.localModeFrequencies()[i + j] -
                                  self.localModeFrequencies()[i]) /
                                 (matplotlib.pyplot.ylim()[1] -
                                  matplotlib.pyplot.ylim()[0]))
                average = average / j
                if self.frequencyGroups()[i][1] == plot_number:
                    # if (i + 1) == (i + j):
                    #     text = text = "\(\omega_{a}\)(" + str(i + 1) + ")"
                    # else:
                    #     text = "\(\omega_{a}\)(" + str(i + 1) + "-" + str(i + j) + ")"
                    acs.text(-0.14,
                             average,
                             text,
                             verticalalignment='center',
                             horizontalalignment='right')
                i = i + j

            # Generate normal mode labels
            i = 0
            while i < self.numberModes():
                delta = 0.
                average = 0.
                text = ""
                j = 0
                while delta <= deltaValue:
                    if j >= 1:
                        text = text + ","
                    text = text + "\(\omega_{" + str(
                        i + j + 1) + "}\)(" + latexSymmetry(
                            self.normalModeSymmetries()[i + j]) + ")"
                    average += self.normalModeFrequencies()[i + j]
                    j += 1
                    if j + i >= self.numberModes():
                        break
                    else:
                        delta = ((self.normalModeFrequencies()[i + j] -
                                  self.normalModeFrequencies()[i]) /
                                 (matplotlib.pyplot.ylim()[1] -
                                  matplotlib.pyplot.ylim()[0]))
                average = average / j
                if self.frequencyGroups()[i][1] == plot_number:
                    acs.text(1.06,
                             average,
                             text,
                             verticalalignment='center',
                             horizontalalignment='left')
                i = i + j

            matplotlib.pyplot.xlim([0, 1])
            acs.xaxis.set_major_locator(MaxNLocator(10))
            acs.xaxis.set_minor_locator(MaxNLocator(100))
            acs.yaxis.set_major_locator(MaxNLocator(10))
            acs.yaxis.set_minor_locator(MaxNLocator(100))
            acs.yaxis.set_major_formatter(FormatStrFormatter('%0.0f'))

            sizeOfFont = 18
            fontProperties = {
                'family': 'sans-serif',
                'sans-serif': ['Helvetica'],
                'weight': 'normal',
                'size': sizeOfFont
            }
            matplotlib.rc('font', **fontProperties)
            matplotlib.rc('text', usetex=True)
            a = matplotlib.pyplot.gca()
            a.set_xticklabels(a.get_xticks(), fontProperties)
            #a.set_yticklabels(a.get_yticks(), fontProperties)

            figure.savefig(str(self.__file_name_root) + "-" +
                           str(plot_number) + ".pdf",
                           bbox_inches='tight')
            matplotlib.pyplot.close()
Beispiel #32
0
def graphsviewbar(request, tester_name, param_name, model, side):
    import django
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    import matplotlib.pyplot as plt
    from matplotlib.figure import Figure
    from matplotlib import pyplot as plt
    import numpy as np

    fig = plt.Figure()
    ax = fig.add_subplot(211)  #211 ,111
    ay = fig.add_subplot(212)
    #fig.tight_layout()
    fig.tight_layout(pad=2, w_pad=0.5, h_pad=4.0)
    #get limit
    from spc.models import ParamSetting
    ps = ParamSetting.objects.get(tester_name=tester_name,
                                  param_name=param_name,
                                  model=model,
                                  control_side=side)
    titletxt = 'IR chart : %s - %s (%s)' % (tester_name, param_name, side)

    pd = PerformingDetail.objects.filter(
        param_name=param_name,
        perform_id__tester_name=tester_name).order_by('-datetime')[:50]

    minvalue_list = pd.values_list('min_value', flat=True)[::-1]
    maxvalue_list = pd.values_list('max_value', flat=True)[::-1]
    date_list = pd.values_list('datetime', flat=True)[::-1]

    n = pd.count()
    cl = np.empty(n)
    ucl = np.empty(n)
    ucl1s = np.empty(n)
    ucl2s = np.empty(n)
    lcl = np.empty(n)
    lcl1s = np.empty(n)
    lcl2s = np.empty(n)

    cl.fill(ps.cl)
    ucl.fill(ps.ucl)
    lcl.fill(ps.lcl)
    ucl1s.fill(ps.ucl1s)
    lcl1s.fill(ps.lcl1s)
    ucl2s.fill(ps.ucl2s)
    lcl2s.fill(ps.lcl2s)

    #x=np.arange(1,n+1)
    #ax.set_xlim(1, 50)
    dim = np.arange(0, n + 1)
    x = np.arange(1, n + 1)
    #x=date_list
    #y = np.full(n, 1)
    #y = np.full(n, ps.lcl*0.6)
    y = minvalue_list if side == 'MIN' else maxvalue_list

    box_plot(ay, y, '')

    #Center Line (CL)
    ax.plot(x, cl, linestyle='-', color='black', linewidth=2)
    ax.text(1,
            ps.cl,
            ps.cl.__format__('0.3'),
            ha='left',
            verticalalignment='bottom',
            color='black',
            wrap=True,
            bbox={
                'facecolor': 'gray',
                'alpha': 0.5,
                'pad': 1
            })

    #1Sigma Upper line (1ucl)
    ax.plot(x, ucl1s, linestyle='--', color='green', linewidth=1)
    ax.text(1,
            ps.ucl1s,
            ps.ucl1s.__format__('0.3'),
            ha='left',
            verticalalignment='bottom',
            color='black',
            wrap=True,
            bbox={
                'facecolor': 'green',
                'alpha': 0.5,
                'pad': 1
            })

    #1Sigma Lower line (1lcl)
    ax.plot(x, lcl1s, linestyle='--', color='green', linewidth=1)
    ax.text(1,
            ps.lcl1s,
            ps.lcl1s.__format__('0.3'),
            ha='left',
            verticalalignment='bottom',
            color='black',
            wrap=True,
            bbox={
                'facecolor': 'green',
                'alpha': 0.5,
                'pad': 1
            })

    #2Sigma Upper line (2ucl)
    ax.plot(x, ucl2s, linestyle='--', color='orange', linewidth=1)
    ax.text(1,
            ps.ucl2s,
            ps.ucl2s.__format__('0.3'),
            ha='left',
            verticalalignment='bottom',
            color='black',
            wrap=True,
            bbox={
                'facecolor': 'orange',
                'alpha': 0.5,
                'pad': 1
            })

    #2Sigma Upper line (2lcl)
    ax.plot(x, lcl2s, linestyle='--', color='orange', linewidth=1)
    ax.text(1,
            ps.lcl2s,
            ps.lcl2s.__format__('0.3'),
            ha='left',
            verticalalignment='bottom',
            color='black',
            wrap=True,
            bbox={
                'facecolor': 'orange',
                'alpha': 0.5,
                'pad': 1
            })

    #3Sigma Upper line (3ucl)
    ax.plot(x, ucl, linestyle='-', color='red', linewidth=2)
    ax.text(1,
            ps.ucl,
            ps.ucl.__format__('0.3'),
            ha='left',
            verticalalignment='bottom',
            color='black',
            wrap=True,
            bbox={
                'facecolor': 'red',
                'alpha': 0.5,
                'pad': 1
            })

    #3Sigma lower line (3lcl)
    ax.plot(x, lcl, linestyle='-', color='red', linewidth=2)
    ax.text(1,
            ps.lcl,
            ps.lcl.__format__('0.3'),
            ha='left',
            verticalalignment='bottom',
            color='black',
            wrap=True,
            bbox={
                'facecolor': 'red',
                'alpha': 0.5,
                'pad': 1
            })

    #xlabels = [newdate.strftime('%b-%d %I:%M %p') if True else newdate for newdate in date_list]#'%b-%d'
    from django.utils import timezone
    xlabels = [
        timezone.localtime(newdate,
                           timezone.get_default_timezone()).strftime('%b-%d')
        if True else newdate for newdate in date_list
    ]  #'%b-%d'

    from matplotlib.ticker import MultipleLocator, FormatStrFormatter
    majorLocator = MultipleLocator(1)
    majorFormatter = FormatStrFormatter('%d')
    minorLocator = MultipleLocator(1)
    minorFormatter = FormatStrFormatter('%d')

    ax.xaxis.set_major_locator(majorLocator)
    ax.xaxis.set_major_formatter(majorFormatter)
    ax.xaxis.set_minor_locator(minorLocator)
    ax.xaxis.set_major_formatter(minorFormatter)

    ax.plot(x, y, 'o-')
    #fig.xticks(dim)
    #fig.grid()
    #ax.set_xticks(date_list)
    labels = [
        '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a1',
        'b2', 'c3', 'd4', 'e5', 'f6', 'g7', 'h8', 'i9', 'j10', 'k11', 'l12',
        'm13', 'n14', 'o15', 'p16', 'q17', 'r18', 's19', 't20', 'u21', 'v22',
        'w23', 'x24'
    ]
    labels = ['0'] + xlabels
    ax.set_xticklabels(labels, rotation=70, ha='right')

    #for label in ax.get_xticklabels():
    #    label.set_rotation('vertical')

    #ax.plot(r.date, r.close)

    # rotate and align the tick labels so they look better
    #fig.autofmt_xdate()

    # use a more precise date string for the x axis locations in the
    # toolbar
    #plt.title('fig.autofmt_xdate fixes the labels')

    ax.set_title(titletxt)

    #ax.set_xticks(date_list)

    #ax.set_xticks(date_list)
    #ax.set_xticklabels(xlable , rotation=45) #Working but need to fix format

    #ax.set_xticklabels(date_list)
    #ax.set_minor_formatter(FormatStrFormatter("%b"))
    ax.set_ylim([(ps.lcl + (ps.lcl1s - ps.cl)), (ps.ucl + (ps.ucl1s - ps.cl))])

    ax.xaxis.grid(True, 'major', linewidth=1)
    ax.tick_params(axis='x', pad=8)
    #ax.xaxis.grid(True,'minor')
    #fig.tight_layout()

    #fig.autofmt_xdate()
    # rotate and align the tick labels so they look better
    #fig.autofmt_xdate()

    # use a more precise date string for the x axis locations in the
    # toolbar

    #plt.title('fig.autofmt_xdate fixes the labels')
    #ax.imshow(X, cmap=cm.jet)

    fig.set_size_inches(13, 8, forward=True)
    #plt.savefig("image.png",bbox_inches='tight',dpi=100)
    canvas = FigureCanvas(fig)
    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Beispiel #33
0
                         (bkg_eff / np.interp(sig_eff, xref, yref))**(-1),
                         color="#AE3135",
                         marker="o",
                         markersize=5)

                k = k + 1

            # Styling the plot
            ax1.set_ylabel(r'Background efficiency [%]')

            ax2.set_xlabel(r'Signal efficiency [%]')
            ax2.set_ylabel(r'Ratio')

            ax1.set_ylim(0.101, 100)
            ax2.set_ylim(0.201, 1.09)

            ax1.legend(loc="upper left", ncol=1)

            ax1.yaxis.set_major_formatter(FormatStrFormatter("%.0f"))

            plt.savefig(join(plot_dir,
                             "ROC/2017_{0}_{1}.pdf".format(location, ptrange)),
                        bbox_inches='tight')
            #         plt.savefig(join(plot_dir, "ROC/2017_{0}_{1}.eps".format(location, ptrange)), bbox_inches='tight')
            plt.savefig(join(plot_dir,
                             "ROC/2017_{0}_{1}.png".format(location, ptrange)),
                        bbox_inches='tight')
            #         os.system("convert -density 150 -quality 100 " + join(plot_dir, "roc/2017_{0}_{1}.eps".format(location, ptrange)) + " "
            #                                                        + join(plot_dir, "roc/2017_{0}_{1}.png".format(location, ptrange)))

            plt.close()
Beispiel #34
0
 def __call__(self, v, i=0):
     return FormatStrFormatter.__call__(self, v*self._factor, i)
Beispiel #35
0
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

plt.rcParams['font.sans-serif'] = ['SimHei']

x1 = range(1, 21)
y1 = [15] * 20
x2 = range(1, 21)
y2 = [74.96] * 20

xmajorLocator = MultipleLocator(1)
xmajorFormatter = FormatStrFormatter('%2d')
xminorLocator = MultipleLocator(0.5)

ymajorLocator = MultipleLocator(10)
ymajorFormatter = FormatStrFormatter('%3d')
yminorLocator = MultipleLocator(5)

ax = plt.subplot(111)

ax.xaxis.set_major_formatter(xmajorFormatter)
ax.xaxis.set_major_locator(xmajorLocator)

ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)

ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_minor_locator(yminorLocator)

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