コード例 #1
0
        ##        if org=='ox':label = filelist[i][63+ddd:69+ddd]
        ##        if org=='oxanox':label = filelist[i][67+ddd:73+ddd]
        label = str(flx[i])
        plt.plot(data_lys[j, i, :, 5],
                 data_lys[j, i, :, 0],
                 '-x',
                 c=color[i],
                 label=label)
##    if rr == '0_0E0':plt.legend(facecolor='None',edgecolor='None',title=title)
    ax = plt.gca()
    ax.set_xlim(0, 90)
    ax.set_ylim(-40, 40)
    ax.set_xticks([0, 45, 90])
    ax.yaxis.set_ticks_position('both')
    ax.xaxis.set_ticks_position('both')
    ax.xaxis.set_minor_locator(MultipleLocator(15))
    ax.yaxis.set_minor_locator(MultipleLocator(5))

    if j != 0:
        ax.set_xticks([45, 90])
        ax.set_yticklabels([])
    fig.subplots_adjust(bottom=0.2)

    ##    if org=='ox':label = filelist[0][70+ddd:76+ddd]
    ##    if org=='oxanox':label = filelist[0][74+ddd:80+ddd]

    ##outfilename = Workdir+'lys_'+label+'.svg'
    ##plt.savefig(outfilename, transparent=True)
    ##subprocess.call('"C:\Program Files\Inkscape\inkscape.exe" -z -f ' \
    ##                + outfilename + ' --export-emf '+outfilename+\
    ##                '.emf',shell=True)
コード例 #2
0
                         "r-",
                         marker="^",
                         linewidth=2,
                         label="$Basic\ PDR$")
    stepFirstErrAxe.plot(aifiStepT1ErrorArray[:, 0],
                         aifiStepT1ErrorArray[:, 1],
                         "b-",
                         marker="o",
                         linewidth=2,
                         label="$AiFiMatch$")
    stepFirstErrAxe.set_xlabel("$\sigma_s(m)$", fontdict=firstFont)
    stepFirstErrAxe.set_ylabel("$Position\ Error(m)$", fontdict=firstFont)
    stepFirstErrAxe.set_title("$(a)$", fontdict=firstFont)
    stepFirstErrAxe.set_xlim(0.0, 0.6)
    stepFirstErrAxe.set_ylim(0, 8)
    stepFirstErrAxe.yaxis.set_major_locator(MultipleLocator(2))
    stepFirstErrAxe.yaxis.set_minor_locator(MultipleLocator(1))
    plt.xticks(fontsize=tickFontSize)
    plt.yticks(fontsize=tickFontSize)
    stepFirstErrAxe.grid(True)
    stepFirstErrAxe.legend(loc=2, fontsize=tickFontSize)

    stepSecondErrAxe = plt.subplot(232)
    stepSecondErrAxe.plot(pdrStepT2ErrorArray[:, 0],
                          pdrStepT2ErrorArray[:, 1],
                          "r-",
                          marker="^",
                          linewidth=2,
                          label="$Basic\ PDR$")
    stepSecondErrAxe.plot(aifiStepT2ErrorArray[:, 0],
                          aifiStepT2ErrorArray[:, 1],
コード例 #3
0
left_axis.tick_params(axis='both',
                      which='minor',
                      direction='inout',
                      length=minor_grid_tick_length)
#
###
#
# axis domain and range
#
plot.xlim(xmin, xmax)
left_axis.axis(ymin=ymin, ymax=ymax)
###
#
# axis ticks
#
left_axis.xaxis.set_major_locator(MultipleLocator(xmajortick))
left_axis.xaxis.set_minor_locator(MultipleLocator(xminortick))
left_axis.yaxis.set_major_locator(MultipleLocator(ymajortick))
left_axis.yaxis.set_minor_locator(MultipleLocator(yminortick))
#
###
#
# log scale option
# xmin,ymin !=0 for log scale
#
#left_axis.set_xscale('log')
left_axis.set_yscale('log')
#
###
#
# annotation
コード例 #4
0
ファイル: Plots.py プロジェクト: cing/ChannelAnalysis
def plot_rotamer_2dhistograms(rotamer_2dhisto,
                              state_dividers,
                              label_stats,
                              plot_title="Rotamer-Rotamer Histograms",
                              prefix=None):

    # Initialize the figure and compute the number of rows that will
    # be needed in the figure to capture all the data.
    fig = plt.figure()

    rot_histo = rotamer_2dhisto[0]
    rot_xs = rotamer_2dhisto[1]
    rot_ys = rotamer_2dhisto[2]

    # For labelling purposes, generate the same combinations that
    # will be used to title the plots
    ion_name_def = ["R", "G", "B", "P"]

    ax = fig.add_subplot(1, 1, 1)
    extent = [rot_xs[0], rot_xs[-1], rot_ys[0], rot_ys[-1]]

    cax = ax.imshow(rot_histo.transpose(),
                    extent=extent,
                    origin="lower",
                    interpolation='nearest',
                    cmap=mpl.cm.CMRmap)
    ax.autoscale(False)

    # This prints a divider line based on the inputted state_divider
    # variables.
    for divider_val in state_dividers:
        ax.plot(range(int(rot_xs[0]), int(rot_xs[-1])),
                [divider_val] * (rot_xs[-1] - rot_xs[0]),
                linewidth=2.0,
                color='k')

    # This prints text on the 2D histogram that indictes the percentage
    # data in that dihedral space defined between the dividers
    num_regions = len(state_dividers) + 1

    # This iterates over the state divider limits (top and bottom)
    # in order to position text within those boundaries.
    all_dividers = [rot_ys[0]] + state_dividers + [rot_ys[-1]]
    for range_id, range_vals in enumerate(window(all_dividers)):
        y_position = ((range_vals[0] + range_vals[1]) / 2) / rot_ys[-1]
        plt.text(
            0.90,
            y_position,
            r"{:.1f}%".format(100 * label_stats[range_id]),
            #weight="bold",
            ha='center',
            va='center',
            transform=ax.transAxes,
            bbox=dict(facecolor='white', alpha=0.5))

    ax.yaxis.set_major_locator(MultipleLocator(60))
    ax.yaxis.set_minor_locator(MultipleLocator(30))
    ax.xaxis.set_major_locator(MultipleLocator(60))
    ax.xaxis.set_minor_locator(MultipleLocator(30))
    ax.set_axisbelow(True)
    ax.yaxis.grid(True, 'minor')
    ax.yaxis.grid(True, 'major', linewidth=0.5, linestyle='-')
    ax.xaxis.grid(True, 'minor')
    ax.xaxis.grid(True, 'major', linewidth=0.5, linestyle='-')

    ax.set_xlabel("Chi1 (degrees)")
    ax.set_ylabel("Chi2 (degrees)")

    #ax.set_title(plot_title)
    plt.subplots_adjust(hspace=0.2,
                        wspace=0.02,
                        left=0.1,
                        bottom=0.08,
                        right=0.8,
                        top=0.90)
    plt.suptitle(plot_title)

    cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    fig.colorbar(cax, cax=cbar_ax, ticks=[0, 1, 2, 3, 4, 5, 6, 7])
    #cbar_ax.set_yticklabels(['free energy (kcal/mol)'], rotation=90)
    cbar_ax.set_ylabel('free energy (kcal/mol)', rotation=270)

    if prefix != None:
        plt.savefig(prefix + ".pdf")
    else:
        plt.show()

    return True
コード例 #5
0
ax1.set_xlabel(r'$x_p$')
ax1.set_ylabel(r'$y_p$')
#ax1.set_zlabel(r'$Q(x_p,y_p)$')
ax1.text(X.min() * 1.1, Y.min() * 1.1, Z.max() * 1.1, r'$Q(x_p,y_p)$')
ax1.xaxis.set_rotate_label(False)
ax1.yaxis.set_rotate_label(False)
ax1.zaxis.set_rotate_label(False)
ax1.set_zlim(contourz, Z.max() * 1.1)
ax1.view_init(elev=10, azim=135)
ax1.grid(False)
ax1.xaxis.pane.set_edgecolor('black')
ax1.yaxis.pane.set_edgecolor('black')
ax1.xaxis.pane.fill = False
ax1.yaxis.pane.fill = False
ax1.zaxis.pane.fill = False
ax1.xaxis.set_major_locator(MultipleLocator(2))
ax1.yaxis.set_major_locator(MultipleLocator(2))
ax1.zaxis.set_major_locator(MultipleLocator(0.01))
[t.set_va('center') for t in ax1.get_yticklabels()]
[t.set_ha('left') for t in ax1.get_yticklabels()]
[t.set_va('center') for t in ax1.get_xticklabels()]
[t.set_ha('right') for t in ax1.get_xticklabels()]
[t.set_va('center') for t in ax1.get_zticklabels()]
[t.set_ha('left') for t in ax1.get_zticklabels()]
ax1.xaxis._axinfo['tick']['inward_factor'] = 0
ax1.xaxis._axinfo['tick']['outward_factor'] = 0.4
ax1.yaxis._axinfo['tick']['inward_factor'] = 0
ax1.yaxis._axinfo['tick']['outward_factor'] = 0.4
ax1.zaxis._axinfo['tick']['inward_factor'] = 0
ax1.zaxis._axinfo['tick']['outward_factor'] = 0.4
ax1.zaxis._axinfo['tick']['outward_factor'] = 0.4
コード例 #6
0
ファイル: DeReddenSpec.py プロジェクト: sPaMFouR/RedPipe
            ls='-.',
            lw=0.8,
            label='F99 - E(B-V)={0}'.format(ebv_array[index]))
    data_df, popt, pcov = fit_specarr((wave_data, fpkflux))
    ax.plot(data_df['Wavelength'],
            calc_flux(data_df['Wavelength'], *popt),
            ls='-.',
            lw=1.5,
            label='Blackbody Fit')

# ax.set_yticklabels([])
ax.set_ylim(0, 40)
ax.legend(frameon=False, markerscale=10, fontsize=14)
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_ticks_position('both')
ax.xaxis.set_major_locator(MultipleLocator(1000))
ax.xaxis.set_minor_locator(MultipleLocator(100))
ax.yaxis.set_major_locator(MultipleLocator(10))
ax.yaxis.set_minor_locator(MultipleLocator(2))
ax.set_xlabel(r'Wavelength [$\rm \AA$]', fontsize=16)
ax.set_ylabel(r'Flux $\rm [erg\ s^{-1}\ cm^{-2}\ {\AA}^{-1}]$', fontsize=16)

ax.tick_params(which='major',
               direction='in',
               width=1.2,
               length=7,
               labelsize=14)
ax.tick_params(which='minor',
               direction='in',
               width=0.8,
               length=4,
コード例 #7
0
    axes[0,0].scatter([i for i in range(len(pnl['N_Trade']))], pnl['N_Trade'], s=2, c='k')
    axes[0,0].set_ylabel('Total Number of Trades at Each Index')

    axes[0,1].scatter([i for i in range(len(pnl['Trade_Profit']))], pnl['Trade_Profit'], s=2, c='k')
    axes[0,1].set_ylabel('Profit Associated with the Total Trades')

    axes[1,0].scatter([i for i in range(len(pnl['Cost']))], pnl['Cost'], s=2, c='k')
    axes[1,0].set_ylabel('Cost Associated with the Total Trades')  

    axes[1,1].scatter([i for i in range(len(pnl['PnL']))], pnl['PnL'], s=2, c='k')
    axes[1,1].set_ylabel('Profit and Loss (PnL)'); 

    for i in range(0,nrows_):
        for j in range(ncols_):
            axes[i,j].set_xlabel('Time Index'); 
            axes[i,j].xaxis.set_major_locator(MultipleLocator(5000)); axes[i,j].xaxis.set_minor_locator(MultipleLocator(2500))
            #axes[i,j].yaxis.set_major_locator(MultipleLocator(200)); axes[i,j].yaxis.set_minor_locator(MultipleLocator(100))
            axes[i,j].tick_params(direction='in', length=6, width=1, colors='k', grid_color='k', grid_alpha=0.5, which='major', labelsize=FontSize)
            axes[i,j].tick_params(direction='in', length=3, width=0.5, colors='k', grid_color='k', grid_alpha=0.5, which='minor', labelsize=FontSize)
    plt.tight_layout()
    #plt.suptitle('Pairs:' + x_lab + ', ' + y_lab)
    fig.savefig(r'Results\plotpnl')

if plot_act_evolution:
    open_file = open(r'Results\net_act_evolution', "rb")
    net_act_evolution = pickle.load(open_file)
    open_file.close()
    for curr_epi in range(len(net_act_evolution)):
        parameter = 'n_hist'
        #parameter = 'n_forward'
        list_for_this_para = [curr_dic[parameter] for curr_dic in net_act_evolution[curr_epi]]
コード例 #8
0
def StarObsPlot(year=None,
                targets=None,
                observatory=None,
                period=None,
                hover=False,
                sunless_hours=None,
                remove_watermark=False):
    """
    Plot the visibility of target.

    Parameters
    ----------
    year: int
        The year for which to calculate the visibility.
    targets: list
        List of targets.
        Each target should be a dictionary with keys 'name' and 'coord'.
        The key 'name' is a string, 'coord' is a SkyCoord object.
    observatory: string
        Name of the observatory that pyasl.observatory can resolve.
        Basically, any of pyasl.listObservatories().keys()
    period: string, optional
        ESO period for which to calculate the visibility. Overrides `year`.
    hover: boolean, optional
        If True, color visibility lines when mouse over.
    sunless_hours: float, optional
        If not None, plot sunless hours above this airmass
  """
    date = year
    from mpl_toolkits.axes_grid1 import host_subplot
    from matplotlib.ticker import MultipleLocator
    from matplotlib.font_manager import FontProperties
    from matplotlib import rcParams
    rcParams['xtick.major.pad'] = 12
    font0 = FontProperties()
    font1 = font0.copy()
    font0.set_family('sans-serif')
    font0.set_weight('light')
    font1.set_family('sans-serif')
    font1.set_weight('medium')

    # set the observatory
    if isinstance(observatory, dict):
        obs = observatory
    else:
        obs = pyasl.observatory(observatory)

    fig = plt.figure(figsize=(15, 10))
    fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88)

    # watermak
    if not remove_watermark:
        fig.text(0.99,
                 0.99,
                 'Created with\ngithub.com/iastro-pt/ObservationTools',
                 fontsize=10,
                 color='gray',
                 ha='right',
                 va='top',
                 alpha=0.5)

    # plotting sunless hours?
    shmode = False
    if sunless_hours is not None:
        shmode = True
        # limit in airmass (assumed plane-parallel atm)
        shairmass = sunless_hours
        # correspoing limit in altitude
        from scipy.optimize import bisect
        shalt = 90 - bisect(lambda alt: pyasl.airmassPP(alt) - shairmass, 0,
                            89)

    if shmode:
        fig.subplots_adjust(hspace=0.35)
        ax = host_subplot(211)
        axsh = host_subplot(212)
        plt.text(0.5,
                 0.47,
                 "- sunless hours above airmass {:.1f} - \n".format(shairmass),
                 transform=fig.transFigure,
                 ha='center',
                 va='bottom',
                 fontsize=12)
        plt.text(0.5, 0.465,
              "the thick line above the curves represents the total sunless hours "\
              "for each day of the year",
              transform=fig.transFigure, ha='center', va='bottom', fontsize=10)

    else:
        ax = host_subplot(111)

    for n, target in enumerate(targets):

        target_coord = target['coord']
        target_ra = target_coord.ra.deg
        target_dec = target_coord.dec.deg

        if period is not None:
            jd_start, jd_end = get_ESO_period(period)
        else:
            jd_start = pyasl.jdcnv(dt.datetime(year, 1, 1))
            jd_end = pyasl.jdcnv(dt.datetime(year, 12, 31))

        jdbinsize = 1  # every day
        each_day = np.arange(jd_start, jd_end, jdbinsize)
        jds = []

        ## calculate the mid-dark times
        sun = ephem.Sun()
        for day in each_day:
            date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]])
            s = ephem.Observer()
            s.date = date_formatted
            s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])])
            s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])])
            jds.append(ephem.julian_date(s.next_antitransit(sun)))

        jds = np.array(jds)

        # Get JD floating point
        jdsub = jds - np.floor(jds[0])

        # Get alt/az of object
        altaz = pyasl.eq2hor(jds, np.ones_like(jds)*target_ra, np.ones_like(jds)*target_dec, \
                            lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude'])
        ax.plot(jdsub, altaz[0], '-', color='k')

        # label for each target
        plabel = "[{0:2d}]  {1!s}".format(n + 1, target['name'])

        # number of target at the top of the curve
        ind_label = np.argmax(altaz[0])
        # or at the bottom if the top is too close to the corners
        # if jdsub[ind_label] < 5 or jdsub[ind_label] > jdsub.max()-5:
        #   ind_label = np.argmin(altaz[0])
        ax.text( jdsub[ind_label], altaz[0][ind_label], str(n+1), color="b", fontsize=14, \
                 fontproperties=font1, va="bottom", ha="center")

        if n + 1 == 29:
            # too many?
            ax.text(1.1, 1.0-float(n+1)*0.04, "too many targets", ha="left", va="top", transform=ax.transAxes, \
                    fontsize=10, fontproperties=font0, color="r")
        else:
            ax.text(1.1, 1.0-float(n+1)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \
                    fontsize=12, fontproperties=font0, color="b")

    if shmode:
        sunless_hours = []
        for day in each_day:
            date_formatted = '/'.join([str(i) for i in pyasl.daycnv(day)[:-1]])
            s = ephem.Observer()
            s.date = date_formatted
            s.lat = ':'.join([str(i) for i in decdeg2dms(obs['latitude'])])
            s.lon = ':'.join([str(i) for i in decdeg2dms(obs['longitude'])])
            # hours from sunrise to sunset
            td = pyasl.daycnv(ephem.julian_date(s.next_setting(sun)), mode='dt') \
                  - pyasl.daycnv(ephem.julian_date(s.next_rising(sun)), mode='dt')
            sunless_hours.append(24 - td.total_seconds() / 3600)

        days = each_day - np.floor(each_day[0])
        axsh.plot(days, sunless_hours, '-', color='k', lw=2)
        axsh.set(
            ylim=(0, 15),
            yticks=range(1, 15),
            ylabel='Useful hours',
            yticklabels=[r'${}^{{\rm h}}$'.format(n) for n in range(1, 15)])


    ax.text(1.1, 1.03, "List of targets", ha="left", va="top", transform=ax.transAxes, \
            fontsize=12, fontproperties=font0, color="b")

    axrange = ax.get_xlim()

    if period is None:
        months = range(1, 13)
        ndays = [0] + [calendar.monthrange(date, m)[1] for m in months]
        ax.set_xlim([0, 366])
        ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
        ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                           fontsize=10)
        if shmode:
            axsh.set_xlim([0, 366])
            axsh.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
            axsh.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                                 fontsize=10)
    else:
        if int(period) % 2 == 0:
            # even ESO period, Oct -> Mar
            months = [10, 11, 12, 1, 2, 3]
            ndays = [0] + [calendar.monthrange(date, m)[1] for m in months]
            ax.set_xlim([0, 181])
            ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
            ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                               fontsize=10)
            if shmode:
                axsh.set_xlim([0, 181])
                axsh.set_xticks(
                    np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
                axsh.set_xticklabels(map(calendar.month_abbr.__getitem__,
                                         months),
                                     fontsize=10)
        else:
            # odd ESO period, Apr -> Sep
            months = range(4, 10)
            ndays = [0] + [calendar.monthrange(date, m)[1] for m in months]
            ax.set_xlim([0, 182])
            ax.set_xticks(np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
            ax.set_xticklabels(map(calendar.month_abbr.__getitem__, months),
                               fontsize=10)
            if shmode:
                axsh.set_xlim([0, 182])
                axsh.set_xticks(
                    np.cumsum(ndays)[:-1] + (np.array(ndays) / 2.)[1:])
                axsh.set_xticklabels(map(calendar.month_abbr.__getitem__,
                                         months),
                                     fontsize=10)

    if axrange[1] - axrange[0] <= 1.0:
        jdhours = np.arange(0, 3, 1.0 / 24.)
        utchours = (np.arange(0, 72, dtype=int) + 12) % 24
    else:
        jdhours = np.arange(0, 3, 1.0 / 12.)
        utchours = (np.arange(0, 72, 2, dtype=int) + 12) % 24

    # Make ax2 responsible for "top" axis and "right" axis
    ax2 = ax.twin()
    # Set upper x ticks
    ax2.set_xticks(np.cumsum(ndays))
    ax2.set_xlabel("Day")

    # plane-parallel airmass
    airmass_ang = np.arange(10, 81, 5)
    geo_airmass = pyasl.airmass.airmassPP(airmass_ang)[::-1]
    ax2.set_yticks(airmass_ang)
    airmassformat = []
    for t in range(geo_airmass.size):
        airmassformat.append("{0:2.2f}".format(geo_airmass[t]))
    ax2.set_yticklabels(airmassformat)  #, rotation=90)
    ax2.set_ylabel("Relative airmass", labelpad=32)
    ax2.tick_params(axis="y", pad=6, labelsize=8)
    plt.text(1.02,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \
             va='top', fontsize=10, rotation=90)

    ax22 = ax.twin()
    ax22.set_xticklabels([])
    ax22.set_frame_on(True)
    ax22.patch.set_visible(False)
    ax22.yaxis.set_ticks_position('right')
    ax22.yaxis.set_label_position('right')
    ax22.spines['right'].set_position(('outward', 30))
    ax22.spines['right'].set_color('k')
    ax22.spines['right'].set_visible(True)
    airmass2 = list(
        map(
            lambda ang: pyasl.airmass.airmassSpherical(90. - ang, obs[
                'altitude']), airmass_ang))
    ax22.set_yticks(airmass_ang)
    airmassformat = []
    for t in range(len(airmass2)):
        airmassformat.append(" {0:2.2f}".format(airmass2[t]))
    ax22.set_yticklabels(airmassformat, rotation=90)
    ax22.tick_params(axis="y", pad=8, labelsize=8)
    plt.text(1.05,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \
             fontsize=10, rotation=90)

    ax.set_ylim([0, 91])
    ax.yaxis.set_major_locator(MultipleLocator(15))
    ax.yaxis.set_minor_locator(MultipleLocator(5))
    yticks = ax.get_yticks()
    ytickformat = []
    for t in range(yticks.size):
        ytickformat.append(str(int(yticks[t])) + r"$^\circ$")
    ax.set_yticklabels(ytickformat, fontsize=16)
    ax.set_ylabel("Altitude", fontsize=18)
    yticksminor = ax.get_yticks(minor=True)
    ymind = np.where(np.array(yticksminor) % 15. != 0.)[0]
    yticksminor = [yticksminor[i] for i in ymind]
    yticksminor = np.array(yticksminor)
    ax.set_yticks(yticksminor, minor=True)
    m_ytickformat = []
    for t in range(yticksminor.size):
        m_ytickformat.append(str(int(yticksminor[t])) + r"$^\circ$")
    ax.set_yticklabels(m_ytickformat, minor=True)
    ax.set_ylim([0, 91])

    ax.yaxis.grid(color='gray', linestyle='dashed')
    ax.yaxis.grid(color='gray', which="minor", linestyle='dotted')
    ax2.xaxis.grid(color='gray', linestyle='dotted')

    if period is not None:
        plt.text(
            0.5,
            0.95,
            "Visibility over P{0!s}\n - altitudes at mid-dark time -".format(
                period),
            transform=fig.transFigure,
            ha='center',
            va='bottom',
            fontsize=12)
    else:
        plt.text(
            0.5,
            0.95,
            "Visibility over {0!s}\n - altitudes at mid-dark time -".format(
                date),
            transform=fig.transFigure,
            ha='center',
            va='bottom',
            fontsize=12)

    obsco = "Obs coord.: {0:8.4f}$^\circ$, {1:8.4f}$^\circ$, {2:4f} m".format(
        obs['longitude'], obs['latitude'], obs['altitude'])

    plt.text(0.01,
             0.97,
             obsco,
             transform=fig.transFigure,
             ha='left',
             va='center',
             fontsize=10)
    plt.text(0.01,
             0.95,
             obs['name'],
             transform=fig.transFigure,
             ha='left',
             va='center',
             fontsize=10)

    # interactive!
    if hover:
        main_axis = fig.axes[0]
        all_lines = set(main_axis.get_lines())

        def on_plot_hover(event):
            for line in main_axis.get_lines():
                if line.contains(event)[0]:
                    line.set_color('red')  # make this line red
                    # and all others black
                    all_other_lines = all_lines - set([line])
                    for other_line in all_other_lines:
                        other_line.set_color('black')
                    fig.canvas.draw_idle()

        fig.canvas.mpl_connect('motion_notify_event', on_plot_hover)

    return fig
コード例 #9
0
def VisibilityPlot(date=None,
                   targets=None,
                   observatory=None,
                   plotLegend=True,
                   showMoonDist=True,
                   print2file=False,
                   remove_watermark=False):
    """
    Plot the visibility of target.

    Parameters
    ----------
    date: datetime
        The date for which to calculate the visibility.
    targets: list
        List of targets.
        Each target should be a dictionary with keys 'name' and 'coord'.
        The key 'name' is aa string, 'coord' is a SkyCoord object.
    observatory: string
        Name of the observatory that pyasl.observatory can resolve.
        Basically, any of pyasl.listObservatories().keys()
    plotLegend: boolean, optional
        If True (default), show a legend.
    showMoonDist : boolean, optional
        If True (default), the Moon distance will be shown.
  """

    from mpl_toolkits.axes_grid1 import host_subplot
    from matplotlib.ticker import MultipleLocator
    from matplotlib.font_manager import FontProperties
    from matplotlib import rcParams
    rcParams['xtick.major.pad'] = 12

    if isinstance(observatory, dict):
        obs = observatory
    else:
        obs = pyasl.observatory(observatory)

    fig = plt.figure(figsize=(15, 10))
    fig.subplots_adjust(left=0.07, right=0.8, bottom=0.15, top=0.88)

    # watermak
    if not remove_watermark:
        fig.text(0.99,
                 0.99,
                 'Created with\ngithub.com/iastro-pt/ObservationTools',
                 fontsize=10,
                 color='gray',
                 ha='right',
                 va='top',
                 alpha=0.5)

    ax = host_subplot(111)

    font0 = FontProperties()
    font1 = font0.copy()
    font0.set_family('sans-serif')
    font0.set_weight('light')
    font1.set_family('sans-serif')
    font1.set_weight('medium')

    for n, target in enumerate(targets):

        target_coord = target['coord']
        target_ra = target_coord.ra.deg
        target_dec = target_coord.dec.deg

        # JD array
        jdbinsize = 1.0 / 24. / 20.
        # jds = np.arange(allData[n]["Obs jd"][0], allData[n]["Obs jd"][2], jdbinsize)
        jd = pyasl.jdcnv(date)
        jd_start = pyasl.jdcnv(date) - 0.5
        jd_end = pyasl.jdcnv(date) + 0.5
        jds = np.arange(jd_start, jd_end, jdbinsize)
        # Get JD floating point
        jdsub = jds - np.floor(jds[0])
        # Get alt/az of object
        altaz = pyasl.eq2hor(jds, np.ones(jds.size)*target_ra, np.ones(jds.size)*target_dec, \
                            lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude'])
        # Get alt/az of Sun
        sun_position = pyasl.sunpos(jd)
        sun_ra, sun_dec = sun_position[1], sun_position[2]
        sunpos_altaz = pyasl.eq2hor(jds, np.ones(jds.size)*sun_ra, np.ones(jds.size)*sun_dec, \
                                    lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude'])

        # Define plot label
        plabel = "[{0:2d}]  {1!s}".format(n + 1, target['name'])

        # Find periods of: day, twilight, and night
        day = np.where(sunpos_altaz[0] >= 0.)[0]
        twi = np.where(
            np.logical_and(sunpos_altaz[0] > -18., sunpos_altaz[0] < 0.))[0]
        night = np.where(sunpos_altaz[0] <= -18.)[0]

        if (len(day) == 0) and (len(twi) == 0) and (len(night) == 0):
            print
            print("VisibilityPlot - no points to draw")
            print

        mpos = pyasl.moonpos(jds)
        # mpha = pyasl.moonphase(jds)
        # mpos_altaz = pyasl.eq2hor(jds, mpos[0], mpos[1],
        #                            lon=obs['longitude'], lat=obs['latitude'], alt=obs['altitude'])
        # moonind = np.where( mpos_altaz[0] > 0. )[0]

        if showMoonDist:
            mdist = pyasl.getAngDist(mpos[0], mpos[1], np.ones(jds.size)*target_ra, \
                                    np.ones(jds.size)*target_dec)
            bindist = int((2.0 / 24.) / jdbinsize)
            firstbin = np.random.randint(0, bindist)
            for mp in range(0, int(len(jds) / bindist)):
                bind = firstbin + mp * bindist
                if altaz[0][bind] - 1. < 5.: continue
                ax.text(jdsub[bind], altaz[0][bind]-1., str(int(mdist[bind]))+r"$^\circ$", ha="center", va="top", \
                        fontsize=8, stretch='ultra-condensed', fontproperties=font0, alpha=1.)

        if len(twi) > 1:
            # There are points in twilight
            linebreak = np.where(
                (jdsub[twi][1:] - jdsub[twi][:-1]) > 2.0 * jdbinsize)[0]
            if len(linebreak) > 0:
                plotrjd = np.insert(jdsub[twi], linebreak + 1, np.nan)
                plotdat = np.insert(altaz[0][twi], linebreak + 1, np.nan)
                ax.plot(plotrjd, plotdat, "-", color='#BEBEBE', linewidth=1.5)
            else:
                ax.plot(jdsub[twi],
                        altaz[0][twi],
                        "-",
                        color='#BEBEBE',
                        linewidth=1.5)

        ax.plot(jdsub[night], altaz[0][night], '.k', label=plabel)
        ax.plot(jdsub[day], altaz[0][day], '.', color='#FDB813')

        altmax = np.argmax(altaz[0])
        ax.text( jdsub[altmax], altaz[0][altmax], str(n+1), color="b", fontsize=14, \
                 fontproperties=font1, va="bottom", ha="center")

        if n + 1 == 29:
            ax.text( 1.1, 1.0-float(n+1)*0.04, "too many targets", ha="left", va="top", transform=ax.transAxes, \
                    fontsize=10, fontproperties=font0, color="r")
        else:
            ax.text( 1.1, 1.0-float(n+1)*0.04, plabel, ha="left", va="top", transform=ax.transAxes, \
                    fontsize=12, fontproperties=font0, color="b")

    ax.text( 1.1, 1.03, "List of targets", ha="left", va="top", transform=ax.transAxes, \
            fontsize=12, fontproperties=font0, color="b")

    axrange = ax.get_xlim()
    ax.set_xlabel("UT [hours]")

    if axrange[1] - axrange[0] <= 1.0:
        jdhours = np.arange(0, 3, 1.0 / 24.)
        utchours = (np.arange(0, 72, dtype=int) + 12) % 24
    else:
        jdhours = np.arange(0, 3, 1.0 / 12.)
        utchours = (np.arange(0, 72, 2, dtype=int) + 12) % 24
    ax.set_xticks(jdhours)
    ax.set_xlim(axrange)
    ax.set_xticklabels(utchours, fontsize=18)

    # Make ax2 responsible for "top" axis and "right" axis
    ax2 = ax.twin()
    # Set upper x ticks
    ax2.set_xticks(jdhours)
    ax2.set_xticklabels(utchours, fontsize=18)
    ax2.set_xlabel("UT [hours]")

    # Horizon angle for airmass
    airmass_ang = np.arange(5., 90., 5.)
    geo_airmass = pyasl.airmass.airmassPP(90. - airmass_ang)
    ax2.set_yticks(airmass_ang)
    airmassformat = []
    for t in range(geo_airmass.size):
        airmassformat.append("{0:2.2f}".format(geo_airmass[t]))
    ax2.set_yticklabels(airmassformat, rotation=90)
    ax2.set_ylabel("Relative airmass", labelpad=32)
    ax2.tick_params(axis="y", pad=10, labelsize=10)
    plt.text(1.015,-0.04, "Plane-parallel", transform=ax.transAxes, ha='left', \
             va='top', fontsize=10, rotation=90)

    ax22 = ax.twin()
    ax22.set_xticklabels([])
    ax22.set_frame_on(True)
    ax22.patch.set_visible(False)
    ax22.yaxis.set_ticks_position('right')
    ax22.yaxis.set_label_position('right')
    ax22.spines['right'].set_position(('outward', 25))
    ax22.spines['right'].set_color('k')
    ax22.spines['right'].set_visible(True)
    airmass2 = list(
        map(
            lambda ang: pyasl.airmass.airmassSpherical(90. - ang, obs[
                'altitude']), airmass_ang))
    ax22.set_yticks(airmass_ang)
    airmassformat = []
    for t in airmass2:
        airmassformat.append("{0:2.2f}".format(t))
    ax22.set_yticklabels(airmassformat, rotation=90)
    ax22.tick_params(axis="y", pad=10, labelsize=10)
    plt.text(1.045,-0.04, "Spherical+Alt", transform=ax.transAxes, ha='left', va='top', \
             fontsize=10, rotation=90)

    ax3 = ax.twiny()
    ax3.set_frame_on(True)
    ax3.patch.set_visible(False)
    ax3.xaxis.set_ticks_position('bottom')
    ax3.xaxis.set_label_position('bottom')
    ax3.spines['bottom'].set_position(('outward', 50))
    ax3.spines['bottom'].set_color('k')
    ax3.spines['bottom'].set_visible(True)

    ltime, ldiff = pyasl.localtime.localTime(
        utchours, np.repeat(obs['longitude'], len(utchours)))
    jdltime = jdhours - ldiff / 24.
    ax3.set_xticks(jdltime)
    ax3.set_xticklabels(utchours)
    ax3.set_xlim([axrange[0], axrange[1]])
    ax3.set_xlabel("Local time [hours]")

    ax.set_ylim([0, 91])
    ax.yaxis.set_major_locator(MultipleLocator(15))
    ax.yaxis.set_minor_locator(MultipleLocator(5))
    yticks = ax.get_yticks()
    ytickformat = []
    for t in range(yticks.size):
        ytickformat.append(str(int(yticks[t])) + r"$^\circ$")
    ax.set_yticklabels(ytickformat, fontsize=16)
    ax.set_ylabel("Altitude", fontsize=18)
    yticksminor = ax.get_yticks(minor=True)
    ymind = np.where(np.array(yticksminor) % 15. != 0.)[0]
    yticksminor = [yticksminor[i] for i in ymind]
    yticksminor = np.array(yticksminor)
    ax.set_yticks(yticksminor, minor=True)
    m_ytickformat = []
    for t in range(yticksminor.size):
        m_ytickformat.append(str(int(yticksminor[t])) + r"$^\circ$")
    ax.set_yticklabels(m_ytickformat, minor=True)
    ax.set_ylim([0, 91])

    ax.yaxis.grid(color='gray', linestyle='dashed')
    ax.yaxis.grid(color='gray', which="minor", linestyle='dotted')
    ax2.xaxis.grid(color='gray', linestyle='dotted')

    plt.text(0.5,0.95,"Visibility on {0!s}".format(date.date()), \
             transform=fig.transFigure, ha='center', va='bottom', fontsize=20)

    if plotLegend:
        line1 = matplotlib.lines.Line2D((0, 0), (1, 1),
                                        color='#FDB813',
                                        linestyle="-",
                                        linewidth=2)
        line2 = matplotlib.lines.Line2D((0, 0), (1, 1),
                                        color='#BEBEBE',
                                        linestyle="-",
                                        linewidth=2)
        line3 = matplotlib.lines.Line2D((0, 0), (1, 1),
                                        color='k',
                                        linestyle="-",
                                        linewidth=2)

        lgd2 = plt.legend((line1,line2,line3),("day","twilight","night",), \
                            bbox_to_anchor=(0.88, 0.13), loc='best', borderaxespad=0.,prop={'size':12}, fancybox=True)
        lgd2.get_frame().set_alpha(.5)

    obsco = "Obs coord.: {0:8.4f}$^\circ$, {1:8.4f}$^\circ$, {2:4f} m".format(
        obs['longitude'], obs['latitude'], obs['altitude'])

    plt.text(0.01,
             0.97,
             obsco,
             transform=fig.transFigure,
             ha='left',
             va='center',
             fontsize=10)
    plt.text(0.01,
             0.95,
             obs['name'],
             transform=fig.transFigure,
             ha='left',
             va='center',
             fontsize=10)

    return fig
コード例 #10
0
ax.tick_params(axis='x', pad=15)  # distance between axis and text
ax.tick_params(axis='y', pad=15)
#--------------------------------------------------------------------
ax.spines['left'].set_linewidth(3.0)
ax.spines['right'].set_linewidth(3.0)
ax.spines['top'].set_linewidth(3.0)
ax.spines['bottom'].set_linewidth(3.0)

#===================================================================================
plt.minorticks_on()
plt.tick_params(which='major', direction='in', width=3.0, length=12)  #
plt.tick_params(which='minor', direction='in', width=3.0, length=5)
plt.xticks(fontsize=40)
plt.yticks(fontsize=40)

ax.tick_params(axis='x', pad=10)  # distance between axis and text
ax.tick_params(axis='y', pad=10)

#-----------------------------------------------------------------------------------
#plt.xlabel('[110]'+r'($\mathrm{\AA}$)', fontsize='45')
#plt.ylabel(r'$[1\bar{1}0](\mathrm{\AA})$', fontsize='45')
plt.xlabel(r'$[1\overline{1}0]/b$', fontsize='45')
plt.ylabel(r'$[001]/a$', fontsize='45')

plt.xlim(0, 101)
plt.ylim(0, 20)
ymajorLocator = MultipleLocator(5)
ax.yaxis.set_major_locator(ymajorLocator)

plt.savefig("superjogII_chargeDensity.pdf", bbox_inches="tight")
plt.show()
コード例 #11
0
ax.plot(xAxis, Conv_02_H20_MA, c='#2980B9', linewidth=1.5)
ax.plot(xAxis, Conv_02_H1, '--', c='#E74C3C', linewidth=0.75)
ax.plot(xAxis, Conv_02_H2, '--', c='#F1C40F', linewidth=0.75)
ax.plot(xAxis, Conv_02_H4, '--', c='#F39C12', linewidth=0.75)
ax.plot(xAxis, Conv_02_H10, '--', c='#27AE60', linewidth=0.75)
ax.plot(xAxis, Conv_02_H20, '--', c='#2980B9', linewidth=0.75)
ax.tick_params(labelsize=16)
ax.legend(['New Lower Bound',
           'Original Lower Bound',
           'Original Upper Bound',
           '$H = 1$',
           '$H = 2$',
           '$H = 4$',
           '$H = 10$',
           '$H = 20$'])
ax.xaxis.set_minor_locator(MultipleLocator(50))
ax.yaxis.set_minor_locator(MultipleLocator(0.05))
ax.grid(which='minor', axis='both', linestyle='--')
plt.xlabel('Iteration Times', fontsize=16)
plt.ylabel('$\mu^*$', fontsize=16)
plt.xlim([0, timeSlotNum])
# plt.ylim([0, 1])
plt.show()

# plot results when \lambda = 0.4
xAxis = np.arange(0, timeSlotNum, 1)
fig = plt.figure(figsize=(10, 5))
ax = fig.gca()
ax.plot(xAxis, newLowerBound_04, '--', c='#9B59B6', linewidth=1.5)
ax.plot(xAxis, originLowerBound_04, '--', c='#2C3E50', linewidth=1.5)
ax.plot(xAxis, originUpperBound_04, '--', c='#7F8C8D', linewidth=1.5)
コード例 #12
0
    pl.plot(np.log10(theta), enc_int_norm, lw=3.0)

### add legend
legend = pl.legend(
    ([r"$%.2f$" % j for j in plaw_exp]),
    frameon=False,
    loc='upper left',
    handlelength=1.5,
    title="$\mathrm{power}$-$\mathrm{law}$ \n $\mathrm{exponent}$")
pl.setp(legend.get_title(), fontsize='xx-small')

### add line marking enclosed intensity at theta = 1 deg
pl.axvline(np.log10(1.), color='k', linestyle='--', lw=1.5)

### minor ticks
xminticks = MultipleLocator(0.1)
yminticks = MultipleLocator(0.05)
pl.gca().xaxis.set_minor_locator(xminticks)
pl.gca().yaxis.set_minor_locator(yminticks)

pl.xlim([-2., 2.])

pl.xlabel(r'$\mathrm{log}(\theta) \ [\mathrm{deg}]$')
pl.ylabel(r'$\mathrm{Normalized \ Enclosed \ Intensity}$')
#pl.title(r'$\mathrm{%i \ Layer \ Luneburg \ Lens}$'%layers)

print ""
print ">>> Saving enclosed intensity plot to " + os.path.join(
    savedir, figoutfile)
print ""
pl.savefig(os.path.join(savedir, figoutfile))
def plot_theory_data_binding_energy(name,
                                    IP_surface,
                                    IP_bulk,
                                    EA_surface,
                                    EA_bulk,
                                    IP_bar,
                                    EA_bar,
                                    IP_vac,
                                    EA_vac,
                                    binding_lims,
                                    workfunction,
                                    ylim=[0, 10]):
    fig, ax = plt.subplots(figsize=(10, 5))
    ax2 = ax.twiny()
    binding_energy_lims = binding_lims
    vac_energy_lims = np.array(binding_energy_lims) - workfunction

    IP_plt, = ax.bar(IP_bar[0],
                     height=10,
                     width=IP_bar[1],
                     label="IP",
                     color="C0",
                     alpha=0.6)
    EA_plt, = ax.bar(EA_bar[0],
                     10,
                     width=EA_bar[1],
                     label="EA",
                     color="C1",
                     alpha=0.6)
    ax.vlines([IP_surface, EA_surface],
              ylim[0],
              ylim[1],
              colors="black",
              linestyles="dashdot")
    ax.vlines([IP_bulk, EA_bulk],
              ylim[0],
              ylim[1],
              colors="black",
              linestyles="dotted")
    #vac
    ax.vlines([IP_vac, IP_vac],
              ylim[0],
              ylim[1],
              colors="grey",
              linestyles="solid")
    ax.vlines([EA_vac, EA_vac],
              ylim[0],
              ylim[1],
              colors="grey",
              linestyles="solid")

    #secax = ax.secondary_xaxis('top', functions=(vac_to_binding, vac_to_binding_inv))
    #secax.minorticks_on()
    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax.xaxis.set_minor_locator(MultipleLocator(0.2))
    ax2.xaxis.set_major_locator(MultipleLocator(1))
    ax2.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax2.xaxis.set_minor_locator(MultipleLocator(0.2))

    plt.ylim(ylim)
    ax.set_yticks([])
    ax.set_xlim(vac_energy_lims)
    ax2.set_xlim(binding_energy_lims)
    #    secax.set_xlabel("Binding energy [eV]")
    ax.set_xlabel("Energy w.r.t. the vacuum level/eV")
    ax2.set_xlabel("Binding energy/eV")
    ax.set_ylabel("Intensity/a.u.")
    custom_lines = [
        Line2D([0], [0], color="black", lw=2), IP_plt, EA_plt,
        Line2D([0], [0], linestyle="dashdot", color="black", lw=2),
        Line2D([0], [0], linestyle="dotted", color="black", lw=2),
        Line2D([0], [0], linestyle="solid", color="grey", lw=2)
    ]
    if name == "NPD":
        plt.legend(custom_lines,
                   ["UPS and IPES", "IP", "EA", "Surface", "Bulk", "Vacuum"],
                   loc="upper left")  #
    else:
        plt.legend(
            custom_lines,
            ["UPS and IPES", "IP", "EA", "Surface", "Bulk", "Vacuum"])  #
    #plt.legend()
    plt.savefig("{}.png".format(name))
コード例 #14
0
def get_SS(params, bvec_guess, SS_graphs):
    start_time = time.clock()
    beta, sigma, nvec, A, alpha, delta, SS_tol, fert_rates, mort_rates, imm_rates, omega_SS, gn_SS, g_y = params
    b = opt.root(utils.EulerSys_ss,
                 bvec_guess,
                 args=(beta, sigma, nvec, A, alpha, delta, gn_SS, g_y,
                       omega_SS, mort_rates, imm_rates),
                 tol=SS_tol)
    if b.success:
        b_ss = b.x
        # iterations=b.nit

    K_ss = utils.get_K(b_ss, omega_SS, gn_SS, imm_rates)
    L = utils.get_L(nvec, omega_SS)
    w_ss = utils.get_w(K_ss, L, alpha, A)
    r_ss = utils.get_r(K_ss, L, alpha, delta, A)
    Y_ss = utils.get_Y(K_ss, L, (A, alpha))
    c_ss, c_cnstr = utils.get_cvec_ss(r_ss, w_ss, b_ss, nvec, gn_SS, g_y,
                                      omega_SS, mort_rates)
    EulErr_ss = utils.EulerSys_ss(b_ss, beta, sigma, nvec, A, alpha, delta,
                                  gn_SS, g_y, omega_SS, mort_rates, imm_rates)
    C_ss = utils.get_C(c_ss, omega_SS)
    RCerr_ss = Y_ss - C_ss - (
        (1 + gn_SS) * np.exp(g_y) - 1 + delta) * K_ss + np.exp(g_y) * (
            imm_rates * omega_SS * np.append(b_ss, [0]))
    BQ_ss = utils.get_BQ(b_ss, r_ss, gn_SS, omega_SS, mort_rates)

    ss_time = time.clock() - start_time
    ss_output = {
        'b_ss': b_ss,
        'c_ss': c_ss,
        'w_ss': w_ss,
        'r_ss': r_ss,
        'K_ss': K_ss,
        'Y_ss': Y_ss,
        'C_ss': C_ss,
        'EulErr_ss': EulErr_ss,
        'RCerr_ss': RCerr_ss,
        'BQ_ss': BQ_ss,
        'ss_time': ss_time
    }

    # print('\n Savings: \t\t\t {} \n Capital and Labor: \t\t {} \n Wage and Interest rate: \t {} \n Consumption: \t\t\t {}'.format(
    #         b_ss, np.array([K_ss, L]), np.array([w_ss, r_ss]), c_ss))
    #
    # print('Euler errors: ', EulErr_ss)
    # print('Resource Constraint error: ', RCerr_ss)
    # print('Time needed: ', ss_time)
    # print ('It took {iterations} iterations to get the solution.')
    if SS_graphs:
        cur_path = os.path.split(os.path.abspath(__file__))[0]
        output_fldr = "images_ss_tpi"
        output_dir = os.path.join(cur_path, output_fldr)
        if not os.access(output_dir, os.F_OK):
            os.makedirs(output_dir)

        age = np.arange(21, 101)
        fig, ax = plt.subplots()
        plt.plot(age, c_ss, marker='D', label='Consumption')
        plt.plot(age, np.append([0], b_ss), marker='D', label='Savings')
        minorLocator = MultipleLocator(1)
        ax.xaxis.set_minor_locator(minorLocator)
        plt.grid(b=True, which='major', color='0.65', linestyle='-')
        plt.title('Steady-state consumption and savings')
        plt.xlabel('Age')
        plt.ylabel('Consumption units')
        plt.legend()
        output_path = os.path.join(output_dir, 'ss_bc')
        plt.savefig(output_path)
        # plt.show()
        plt.close()

    return ss_output
コード例 #15
0
def Plot_Log_Sim(log, show=True):
    '''
    Plot ALR simulation log

    log - xarray.Dataset from alr wrapper (n_sim already selected)
    '''

    # plot figure
    #fig = plt.figure(figsize=(_faspect*_fsize, _fsize))
    fig = plt.figure(figsize=[18.5, 9])

    # figure gridspec
    gs1 = gridspec.GridSpec(4, 1)
    ax1 = fig.add_subplot(gs1[0])
    ax2 = fig.add_subplot(gs1[1], sharex=ax1)
    ax3 = fig.add_subplot(gs1[2], sharex=ax1)
    ax4 = fig.add_subplot(gs1[3], sharex=ax1)

    # Plot evbmus values
    ax1.plot(log.time,
             log.evbmus_sims,
             ':',
             linewidth=0.5,
             color='grey',
             marker='.',
             markersize=3,
             markerfacecolor='crimson',
             markeredgecolor='crimson')

    ax1.yaxis.set_major_locator(MultipleLocator(4))
    ax1.grid(which='major', linestyle=':', alpha=0.5)
    ax1.set_xlim(log.time[0], log.time[-1])
    ax1.set_ylabel('Bmus', fontsize=12)

    # Plot evbmus probabilities
    z = np.diff(np.column_stack(
        ([np.zeros([len(log.time), 1]), log.probTrans.values])),
                axis=1)
    z1 = np.column_stack((z, z[:, -1])).T
    z2 = np.column_stack((z1, z1[:, -1]))
    p1 = ax2.pcolor(np.append(log.time, log.time[-1]),
                    np.append(log.n_clusters, log.n_clusters[-1]),
                    z2,
                    cmap='PuRd',
                    edgecolors='grey',
                    linewidth=0.05)
    ax2.set_ylabel('Bmus', fontsize=12)

    # TODO: gestionar terminos markov
    # TODO: no tengo claro si el primero oel ultimo
    alrt0 = log.alr_terms.isel(mk=0)

    # Plot Terms
    for v in range(len(log.terms)):
        if log.terms.values[v].startswith('ss'):
            ax3.plot(log.time, alrt0[:, v], label=log.terms.values[v])

        if log.terms.values[v].startswith('PC'):
            ax4.plot(log.time, alrt0[:, v], label=log.terms.values[v])

        if log.terms.values[v].startswith('MJO'):
            ax4.plot(log.time, alrt0[:, v], label=log.terms.values[v])

    # TODO: plot terms markov??

    ax3.set_ylim(-1.8, 1.2)
    handles, labels = ax3.get_legend_handles_labels()
    ax3.legend(loc='lower left', ncol=len(handles))
    ax3.set_ylabel('Seasonality', fontsize=12)

    handles, labels = ax4.get_legend_handles_labels()
    ax4.legend(loc='lower left', ncol=len(handles))
    ax4.set_ylabel('Covariates', fontsize=12)
    # cbar=plt.colorbar(p1,ax=ax2,pad=0)
    # cbar.set_label('Transition probability')

    gs1.tight_layout(fig, rect=[0.05, [], 0.95, []])

    # custom colorbar for probability
    gs2 = gridspec.GridSpec(1, 1)
    ax1 = fig.add_subplot(gs2[0])
    plt.colorbar(p1, cax=ax1)
    ax1.set_ylabel('Probability')
    gs2.tight_layout(fig, rect=[0.935, 0.52, 0.99, 0.73])

    # show and return figure
    if show: plt.show()
    return fig
コード例 #16
0
def make_plots(allConclusions):

    matplotlib.rcParams.update({'font.size': 18})

    # fig = plt.figure()
    # ax = fig.add_subplot(111)    # The big subplot
    # ax1 = fig.add_subplot(211)
    # ax2 = fig.add_subplot(212)
    # ax3 = fig.add_subplot(213)

    fig, axes = plt.subplots(3, 1, sharey='col')
    dummy = Rectangle((0, 0),
                      1,
                      1,
                      fc="w",
                      fill=False,
                      edgecolor='none',
                      linewidth=0)
    red_rec = Rectangle((0, 0), 1, 1, fc="r")
    leg = fig.legend(handles=[dummy, dummy, dummy, dummy, red_rec],
                     labels=[
                         '$U$    Unknown Downstream Traffic       ',
                         '$L$    Left Movement', '$T$    Through Movement',
                         '$R$    Right Movement', 'Queue Spillback'
                     ],
                     loc='upper center',
                     fontsize=16,
                     ncol=3,
                     bbox_to_anchor=(0.5, 1))

    plt.setp(axes,
             yticks=[0, 1, 2, 3, 4, 5],
             yticklabels=[
                 '   No Information', '   Uncongested', '   Light',
                 '   Moderate', '   Heavy', '   Lane Blockage'
             ])

    plt.sca(axes[0])
    x = [0, 3600, 7200, 10800, 14400, 18000, 21600]
    plt.xticks(x, ('12 AM', '1 AM', '2 AM', '3 AM', '4 AM', '5 AM', '6 AM'))
    minorLocator = MultipleLocator(1800)
    axes[0].xaxis.set_minor_locator(minorLocator)
    plt.ylim([0, 5.5])
    plt.grid(which='major', linestyle='--')
    plt.grid(which='minor', axis='x')

    plt.sca(axes[1])
    x = [21600, 25200, 28800, 32400, 36000, 39600, 43200]
    plt.xticks(x, ('6 AM', '7 AM', '8 AM', '9 AM', '10 AM', '11 AM', '12 PM'))
    plt.ylim([0, 5.5])
    minorLocator = MultipleLocator(1800)
    axes[1].xaxis.set_minor_locator(minorLocator)
    axes[1].set_ylabel('Congestion Level')
    plt.grid(which='major', linestyle='--')
    plt.grid(which='minor', axis='x')

    plt.sca(axes[2])
    x = [43200, 46800, 50400, 54000, 57600, 61200, 64800]
    plt.xticks(x, ('12 PM', '1 PM', '2 PM', '3 PM', '4 PM', '5 PM', '6 PM'))
    plt.ylim([0, 5.5])
    minorLocator = MultipleLocator(1800)
    axes[2].xaxis.set_minor_locator(minorLocator)
    axes[2].set_xlabel('Time')
    plt.grid(which='major', linestyle='--')
    plt.grid(which='minor', axis='x')

    for concl in allConclusions:
        color = 'r' if concl.QSB != None else 'k'
        if concl.curr_time < 22200:
            plt.sca(axes[0])
        elif concl.curr_time < 43800:
            plt.sca(axes[1])
        else:
            plt.sca(axes[2])

        plt.scatter(concl.curr_time,
                    concl.congestionNumber,
                    s=150 * (len(concl.marker.replace('$', ''))),
                    marker=concl.marker,
                    edgecolors=color,
                    facecolors='k')

    plt.show()
コード例 #17
0
        #raw_input()
        #pylab.semilogy(Tp_trans,press_p,color = 'brown',\
        #	basey = 10, linewidth = 2, linestyle = 'dashed')
        baraxis = []
        # Need this -3 to the list to stop them from going off the top
        for n in range(len(u_wind_kts[:-5])):
            baraxis.append(45.)
        pylab.plot([45, 45], [100, 1000], linewidth=.75, color='k')
        bb = pylab.barbs(baraxis,actual_wind_levs[:-5],u_wind_kts[:-5],v_wind_kts[:-5],\
         linewidth = .75)
        bb.set_clip_box(None)
        ax = pylab.gca()
        #ax.set_ylim(ax.get_ylim()[::-1])
        ax.set_ylim([1000, 100])
        ax.set_xlim([-40, 50])
        majorLocator = MultipleLocator(100.)
        majorFormatter = FormatStrFormatter('%4.0f')
        ax.yaxis.set_major_locator(majorLocator)
        ax.yaxis.set_major_formatter(majorFormatter)

        stemps = sfcT[time, point_y,
                      point_x] + 6.5 * ncsfc.variables['HGT'][time, point_y,
                                                              point_x] / 1000.
        mslp = sfcP[time, point_y, point_x] * np.exp(
            9.81 / (287.0 * stemps) *
            ncsfc.variables['HGT'][time, point_y, point_x]) * 0.01 + (
                6.7 * ncsfc.variables['HGT'][time, point_y, point_x] / 1000)

        # Convert Celsius Temps to Fahrenheit
        ftemp = (9. / 5.) * (sfcT[time, point_y, point_x] - 273) + 32
コード例 #18
0
def seasonality_analysis(ticker, provider, start, end, plot_vs, plot_label,
                         monthly, verbose):
    click.echo("Seasonality for {}".format(ticker))

    context = Context(start, end, ticker, None, provider, verbose)
    dataframes = context.data_frames

    if len(dataframes) == 0:
        click.echo("Found no data for {}. Exiting.".format(ticker))
        return
    else:
        df = dataframes[0]

    if monthly:
        rebased_dataframes = [
            df for df in seasonality.seasonality_monthly_returns(df)
        ]

        fig = plt.figure()
        fig.suptitle("{0} montly seasonality".format(ticker), fontsize=16)
        for i, data in enumerate(rebased_dataframes):
            ax = fig.add_subplot(4, 3, i + 1)
            ax.plot(data)
            ax.set_title(data.columns[0])
            # ax.set_xticks(data.index)
            ax.set_yticks([])

        plt.tight_layout()
        plt.show()

    else:
        seasonlity_data = seasonality.seasonality_returns(df).apply(
            seasonality.rebase)

        fig, ax = plt.subplots()
        if plot_label == 'calendar':
            ax.plot(seasonlity_data,
                    label="{0} {1}-{2}".format(ticker, df.index[0].year,
                                               df.index[-1].year))
            # months = mdates.MonthLocator()  # every month
            yearsFmt = mdates.DateFormatter('%b')
            ax.xaxis.set_major_formatter(yearsFmt)
            # ax.xaxis.set_minor_locator(months)
            days = mdates.DayLocator()
            ax.xaxis.set_minor_locator(days)
            fig.autofmt_xdate()
            title = "{0} Seasonality".format(ticker)

            if plot_vs:
                plot_vs_start = "{0}-01-01".format(
                    datetime.datetime.now().year)
                plot_vs_end = datetime.datetime.strftime(
                    datetime.datetime.now(), "%Y-%m-%d")
                plot_vs_df = context.data_provider.get_data([plot_vs],
                                                            plot_vs_start,
                                                            plot_vs_end)
                if len(plot_vs_df) == 0:
                    click.echo("No dataframe for {}. Exiting.".format(plot_vs))
                    return
                plot_vs_df_close = plot_vs_df[0]['Close']

                # Reindex the the plot_vs data to seasonality_data datetimes
                new_index = seasonlity_data.index[0:len(plot_vs_df_close)]
                col = "{} {} to {}".format(plot_vs, plot_vs_start,
                                           plot_vs_df_close.index[-1].date())
                df = pd.DataFrame(plot_vs_df_close.values,
                                  index=new_index,
                                  columns=[col])
                df = seasonality.normalize(df).apply(seasonality.rebase)

                ax.plot(df, label=col)

                minorLocator = MultipleLocator(1)
                ax.xaxis.set_minor_locator(minorLocator)
                title = "{0} Seasonality vs {0}".format(ticker)

        elif plot_label == 'day':
            # days = range(1,len(plot_data)-1)
            # plot_data_days = pd.DataFrame({ticker:plot_data[ticker].values}).reindex(days)

            seasonality_data_days = seasonality.trading_day_reindex(
                seasonlity_data, ticker, ticker)
            seasonality_data_days = seasonality.normalize(
                seasonality_data_days).apply(seasonality.rebase_days)
            ax.plot(seasonality_data_days,
                    label="{0} {1}-{2}".format(ticker, df.index[0].year,
                                               df.index[-1].year))

            minorLocator = MultipleLocator(1)
            ax.xaxis.set_minor_locator(minorLocator)
            ax.set_xlabel("trading day")
            title = "{0} Seasonality".format(ticker)

            if plot_vs:
                plot_vs_start = "{0}-01-01".format(
                    datetime.datetime.now().year)
                plot_vs_end = datetime.datetime.strftime(
                    datetime.datetime.now(), "%Y-%m-%d")
                plot_vs_df = context.data_provider.get_data([plot_vs],
                                                            plot_vs_start,
                                                            plot_vs_end)
                if len(plot_vs_df) == 0:
                    click.echo("No dataframe for {}. Exiting.".format(plot_vs))
                    return

                plot_vs_df = plot_vs_df[0]
                df = seasonality.trading_day_reindex(plot_vs_df, ticker,
                                                     'Close')
                df = seasonality.normalize(df).apply(seasonality.rebase_days)

                col = "{} {} to {}".format(plot_vs, plot_vs_start,
                                           plot_vs_df.index[-1].date())
                ax.plot(df, label=col)
                title = "{0} Seasonality vs {0}".format(ticker)

        legend = ax.legend(loc='upper left', shadow=False, fontsize=12)
        plt.title(title)
        plt.show()
コード例 #19
0
ファイル: DeReddenSpec.py プロジェクト: sPaMFouR/RedPipe
def plot_fit(file_name, fits=False, smooth=True, sp=3):
    """
    Args:
        file_name   : Name of the 1-D spectrum file to be fit
        fits        : Whether or not the file is a FITS file
        smooth      : Whether or not to smooth the spectra
        sp          : Smoothing parameter to be used if smooth=True
    Returns:
        data_df     : Pandas DataFrame containing 1-D spectra
        popt        : Optimal fit parameters
        pcov        : Covariance of the fit parameters
    """
    if fits:
        data_df, popt, pcov = fit_specfits(file_name, smooth=smooth, sp=sp)
    else:
        data_df, popt, pcov = fit_specdat(file_name, smooth=smooth, sp=sp)

    temp_fit = popt[1]
    temp_err = pcov[1, 1]

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111)

    ax.plot(data_df['Wavelength'],
            data_df['Flux'],
            ls='steps-mid',
            lw=1,
            c='r',
            label=name_SN)
    ax.plot(data_df['Wavelength'],
            calc_flux(data_df['Wavelength'], *popt),
            c='g',
            ls='-.',
            lw=1.5,
            label='Blackbody Fit')

    ax.set_yticklabels([])
    ax.legend(frameon=False, markerscale=3, fontsize=14)
    ax.yaxis.set_ticks_position('both')
    ax.xaxis.set_ticks_position('both')
    ax.xaxis.set_major_locator(MultipleLocator(1000))
    ax.xaxis.set_minor_locator(MultipleLocator(100))
    ax.yaxis.set_major_locator(MultipleLocator(0.2e-14))
    ax.yaxis.set_minor_locator(MultipleLocator(0.05e-14))
    ax.set_xlabel(r'Wavelength [$\rm \AA$]', fontsize=16)
    ax.set_ylabel(r'Flux $\rm [erg\ s^{-1}\ cm^{-2}\ {\AA}^{-1}]$',
                  fontsize=16)
    ax.set_title('Best Fit Temp = {0:.2f} +/- {1:.2f}'.format(
        popt[1], pcov[1, 1]))

    ax.tick_params(which='major',
                   direction='in',
                   width=1.2,
                   length=7,
                   labelsize=14)
    ax.tick_params(which='minor',
                   direction='in',
                   width=0.8,
                   length=4,
                   labelsize=14)

    #     fig.savefig('PLOT_BlackbodyFit.pdf', format='pdf', dpi=2000, bbox_inches='tight')
    plt.show()
    plt.close(fig)
コード例 #20
0
                                                       ])['VIN'].count()
acc2011 = df[(df['MODEL_YEAR'] == 2011)
             & (df['MODEL_NAME'] == 'ACCORD')
             & (df['ENGINE_CYLINDERS'] == 4)].groupby(['RO_YR_MTH'
                                                       ])['VIN'].count()

d = {
    '2008': pandas.Series(acc2008.values, index=acc2008.index),
    '2009': pandas.Series(acc2009.values, index=acc2009.index),
    '2010': pandas.Series(acc2010.values, index=acc2010.index),
    '2011': pandas.Series(acc2011.values, index=acc2011.index),
}

data = pandas.DataFrame(d)

major_ticks = MultipleLocator(20)
minor_ticks = MultipleLocator(10)

xv = np.arange(0, len(data.index), 1)
plt.bar(xv, data['2008'].values, width=0.25, color='red', label='2008')
plt.bar(xv + 0.25, data['2009'].values, width=0.25, color='blue', label='2009')
plt.bar(xv + 0.5,
        data['2010'].values,
        width=0.25,
        color='yellow',
        label='2010')
plt.bar(xv + 0.75,
        data['2011'].values,
        width=0.25,
        color='green',
        label='2011')
コード例 #21
0
test['duration'] = test.apply(
    lambda x: duration(x['site_lon_lat'], x['clinic_lon_lat']), axis=1)

# %%
## histogram of computed travel times
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
matplotlib.rcParams.update({'font.size': 11})

x = (test[test['duration'] != 'error']['duration']).astype(int)

fig, ax = plt.subplots(1, 1, figsize=(12, 5))
#ax.hist(x, density=False, bins=np.arange(min(x), max(x) + 50, 50))  # density=False would make counts
ax.hist(x, density=False, bins=20)
ax.set_ylabel('Number of sites')
ax.set_xlabel('Travel time (minutes)')
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_formatter('{x:.0f}')
ax.set_title(
    'Calculated travel time (by foot) between IDP sites and health facilities - Mozambique'
)

#fig.savefig(f"distance.svg", format="svg", transparent=True, bbox_inches='tight', pad_inches=0)
#fig.savefig(f"distance.png", format="png", transparent=True, bbox_inches='tight', pad_inches=0)

# %%
fig, ax = plt.subplots(1, 1, figsize=(12, 5))
ax.hist(test['health_facility_distance'], density=False, bins=20)

# %%
test = test[test['duration'] != 'error'].copy()
test['ki_duration_code'] = test['health_facility_distance'].replace([
コード例 #22
0
     'k',
     lw=1.2,
     linestyle="--",
     label="VMC, TDL")
# plot([0, N_ele.max()], [0.242, 0.242], 'k', lw=1.2, linestyle="-.")
# plot([0, N_ele.max()], [0.0945, 0.0945], 'k', lw=1.2, linestyle="-")

#     Legend
leg = legend(loc='upper left', labelspacing=0.1)
fr_leg = leg.get_frame()
fr_leg.set_lw(0.6)

#     Set minor and major ticks
#majorLocatorX = MultipleLocator(50)
#minorLocatorX = MultipleLocator(10)
majorLocatorY = MultipleLocator(0.02)
minorLocatorY = MultipleLocator(0.01)
axis = fig.gca()
#axis.xaxis.set_major_locator(majorLocatorX)
#axis.xaxis.set_minor_locator(minorLocatorX)
axis.yaxis.set_major_locator(majorLocatorY)
axis.yaxis.set_minor_locator(minorLocatorY)

xticks([0.0, 1. / 50, 1. / 98, 1. / 162, 1. / 394], [
    r'$\infty^{-1}$', r'$50^{-1}$', r'$98^{-1}$', r'$162^{-1}$', r'$394^{-1}$'
])
#yticks([-0.217], [-0.217])

#     Limits on axes
#xlim(nShellsCCD.min(), nShellsCCD.max())
#xlim(0.0, orbitsSRG.max())
コード例 #23
0
max_value_1667 = np.amax(max_signal_1667)
sliced_1667=np.argmax(max_signal_1667, axis=0)
#print(sliced_1665,sliced_1667)
#a=sliced_1665 - abs(sliced_1665-sliced_1667)-200
#b=sliced_1665 + abs(sliced_1665-sliced_1667)+100
#sliced_1665=1416
a=sliced_1665-200
b=sliced_1665+200


# In[59]:


import matplotlib.patches as mpatches
#Set the minor axis counters
majorLocator = MultipleLocator(5)
majorFormatter = FormatStrFormatter('%d')
minorLocator = MultipleLocator(0.5)
        
#Make a spectra        
bigfig_1=plt.figure(figsize=(12,5))
ax1=bigfig_1.add_subplot(111)
ax1.step(vels_1665[0:2998],signal_1665[0:2998],color='black',label='1665')
ax1.step(vels_1665[0:2998],signal_1667[0:2998],color='red', label='1667')
#ax1.step(xvals[0:2000],signal[0:2000],color='red')
ax1.set_title("G"+gala, fontsize=24)
ax1.set_xlabel("Velocity (km/s)",fontsize=12)
ax1.set_xlim(vels_1665[a],vels_1665[b])
ax1.set_ylabel("Flux Density (Jy)",fontsize=12)
ax1.tick_params(labelsize=12, labelbottom=True)
ax1.ticklabel_format(useOffset=False)
コード例 #24
0
def MDU_n_stitch(nvec, params, graph=False):
    '''
    --------------------------------------------------------------------
    Generate marginal disutility(ies) of labor with elliptical
    disutility of labor function and stitched functions at lower bound
    and upper bound of labor supply such that the new hybrid function is
    defined over all labor supply on the real line but the function has
    similar properties to the Inada conditions at the upper and lower
    bounds.

    v'(n) = (b / l_tilde) * ((n / l_tilde) ** (upsilon - 1)) *
            ((1 - ((n / l_tilde) ** upsilon)) ** ((1-upsilon)/upsilon))
            if n >= eps_low <= n <= eps_high
          = g_low'(n)  = 2 * b2 * n + b1 if n < eps_low
          = g_high'(n) = 2 * d2 * n + d1 if n > eps_high

        such that g_low'(eps_low) = u'(eps_low)
        and g_low''(eps_low) = u''(eps_low)
        and g_high'(eps_high) = u'(eps_high)
        and g_high''(eps_high) = u''(eps_high)

        v(n) = -b *(1 - ((n/l_tilde) ** upsilon)) ** (1/upsilon)
        g_low(n)  = b2 * (n ** 2) + b1 * n + b0
        g_high(n) = d2 * (n ** 2) + d1 * n + d0
    --------------------------------------------------------------------
    INPUTS:
    nvec   = scalar or (p,) vector, labor supply value or labor supply
             values over remaining periods of lifetime
    params = length 3 tuple, (l_tilde, b_ellip, upsilon)
    graph  = Boolean, =True if want plot of stitched marginal disutility
             of labor function

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    l_tilde       = scalar > 0, time endowment for each agent each per
    b_ellip       = scalar > 0, scale parameter for elliptical utility
                    of leisure function
    upsilon       = scalar > 1, shape parameter for elliptical utility
                    of leisure function
    eps_low       = scalar > 0, positive value close to zero
    eps_high      = scalar > 0, positive value just less than l_tilde
    n_s           = scalar, individual labor supply
    n_s_low       = boolean, =True for n_s < eps_low
    n_s_high      = boolean, =True for n_s > eps_high
    n_s_uncstr    = boolean, =True for n_s >= eps_low and
                    n_s <= eps_high
    MDU_n         = scalar or (p,) vector, marginal disutility or
                    marginal utilities of labor supply
    b1            = scalar, intercept value in linear marginal
                    disutility of labor at lower bound
    b2            = scalar, slope coefficient in linear marginal
                    disutility of labor at lower bound
    d1            = scalar, intercept value in linear marginal
                    disutility of labor at upper bound
    d2            = scalar, slope coefficient in linear marginal
                    disutility of labor at upper bound
    p             = integer >= 1, number of periods remaining in life
    nvec_s_low    = boolean, =True for n_s < eps_low
    nvec_s_high   = boolean, =True for n_s > eps_high
    nvec_s_uncstr = boolean, =True for n_s >= eps_low and
                    n_s <= eps_high

    FILES CREATED BY THIS FUNCTION:
        MDU_n_stitched.png

    RETURNS: MDU_n
    --------------------------------------------------------------------
    '''
    l_tilde, b_ellip, upsilon = params
    eps_low = 0.000001
    eps_high = l_tilde - 0.000001
    # This if is for when nvec is a scalar
    if np.ndim(nvec) == 0:
        n_s = nvec
        n_s_low = n_s < eps_low
        n_s_high = n_s > eps_high
        n_s_uncstr = (n_s >= eps_low) and (n_s <= eps_high)
        if n_s_uncstr:
            MDU_n = \
                ((b_ellip / l_tilde) * ((n_s / l_tilde) **
                 (upsilon - 1)) * ((1 - ((n_s / l_tilde) ** upsilon)) **
                 ((1 - upsilon) / upsilon)))
        elif n_s_low:
            b2 = (0.5 * b_ellip * (l_tilde**(-upsilon)) * (upsilon - 1) *
                  (eps_low**(upsilon - 2)) *
                  ((1 - ((eps_low / l_tilde)**upsilon))**(
                      (1 - upsilon) / upsilon)) *
                  (1 + ((eps_low / l_tilde)**upsilon) *
                   ((1 - ((eps_low / l_tilde)**upsilon))**(-1))))
            b1 = ((b_ellip / l_tilde) * ((eps_low / l_tilde)**(upsilon - 1)) *
                  ((1 - ((eps_low / l_tilde)**upsilon))**(
                      (1 - upsilon) / upsilon)) - (2 * b2 * eps_low))
            MDU_n = 2 * b2 * n_s + b1
        elif n_s_high:
            d2 = (0.5 * b_ellip * (l_tilde**(-upsilon)) * (upsilon - 1) *
                  (eps_high**(upsilon - 2)) *
                  ((1 - ((eps_high / l_tilde)**upsilon))**(
                      (1 - upsilon) / upsilon)) *
                  (1 + ((eps_high / l_tilde)**upsilon) *
                   ((1 - ((eps_high / l_tilde)**upsilon))**(-1))))
            d1 = ((b_ellip / l_tilde) * ((eps_high / l_tilde)**(upsilon - 1)) *
                  ((1 - ((eps_high / l_tilde)**upsilon))**(
                      (1 - upsilon) / upsilon)) - (2 * d2 * eps_high))
            MDU_n = 2 * d2 * n_s + d1
    # This if is for when nvec is a one-dimensional vector
    elif np.ndim(nvec) == 1:
        p = nvec.shape[0]
        nvec_low = nvec < eps_low
        nvec_high = nvec > eps_high
        nvec_uncstr = np.logical_and(~nvec_low, ~nvec_high)
        MDU_n = np.zeros(p)
        MDU_n[nvec_uncstr] = ((b_ellip / l_tilde) *
                              ((nvec[nvec_uncstr] / l_tilde)**(upsilon - 1)) *
                              ((1 -
                                ((nvec[nvec_uncstr] / l_tilde)**upsilon))**(
                                    (1 - upsilon) / upsilon)))
        b2 = (0.5 * b_ellip * (l_tilde**(-upsilon)) * (upsilon - 1) *
              (eps_low**(upsilon - 2)) *
              ((1 -
                ((eps_low / l_tilde)**upsilon))**((1 - upsilon) / upsilon)) *
              (1 + ((eps_low / l_tilde)**upsilon) *
               ((1 - ((eps_low / l_tilde)**upsilon))**(-1))))
        b1 = ((b_ellip / l_tilde) * ((eps_low / l_tilde)**(upsilon - 1)) *
              ((1 -
                ((eps_low / l_tilde)**upsilon))**((1 - upsilon) / upsilon)) -
              (2 * b2 * eps_low))
        MDU_n[nvec_low] = 2 * b2 * nvec[nvec_low] + b1
        d2 = (0.5 * b_ellip * (l_tilde**(-upsilon)) * (upsilon - 1) *
              (eps_high**(upsilon - 2)) *
              ((1 -
                ((eps_high / l_tilde)**upsilon))**((1 - upsilon) / upsilon)) *
              (1 + ((eps_high / l_tilde)**upsilon) *
               ((1 - ((eps_high / l_tilde)**upsilon))**(-1))))
        d1 = ((b_ellip / l_tilde) * ((eps_high / l_tilde)**(upsilon - 1)) *
              ((1 -
                ((eps_high / l_tilde)**upsilon))**((1 - upsilon) / upsilon)) -
              (2 * d2 * eps_high))
        MDU_n[nvec_high] = 2 * d2 * nvec[nvec_high] + d1

    if graph:
        '''
        ----------------------------------------------------------------
        cur_path    = string, path name of current directory
        output_fldr = string, folder in current path to save files
        output_dir  = string, total path of images folder
        output_path = string, path of file name of figure to be saved
        nvec_ellip  = (1000,) vector, support of n including values
                      between 0 and eps_low and between eps_high and
                      l_tilde
        MU_CRRA     = (1000,) vector, CRRA marginal utility of
                      consumption
        cvec_stitch = (500,) vector, stitched support of consumption
                      including negative values up to epsilon
        MU_stitch   = (500,) vector, stitched marginal utility of
                      consumption
        ----------------------------------------------------------------
        '''
        # Create directory if images directory does not already exist
        cur_path = os.path.split(os.path.abspath(__file__))[0]
        output_fldr = "images"
        output_dir = os.path.join(cur_path, output_fldr)
        if not os.access(output_dir, os.F_OK):
            os.makedirs(output_dir)

        # Plot steady-state consumption and savings distributions
        nvec_ellip = np.linspace(eps_low / 2,
                                 eps_high + ((l_tilde - eps_high) / 5), 1000)
        MDU_ellip = ((b_ellip / l_tilde) *
                     ((nvec_ellip / l_tilde)**(upsilon - 1)) *
                     ((1 - ((nvec_ellip / l_tilde)**upsilon))**(
                         (1 - upsilon) / upsilon)))
        n_stitch_low = np.linspace(-0.05, eps_low, 500)
        MDU_stitch_low = 2 * b2 * n_stitch_low + b1
        n_stitch_high = np.linspace(eps_high, l_tilde + 0.000005, 500)
        MDU_stitch_high = 2 * d2 * n_stitch_high + d1
        fig, ax = plt.subplots()
        plt.plot(nvec_ellip,
                 MDU_ellip,
                 ls='solid',
                 color='black',
                 label='$v\'(n)$: Elliptical')
        plt.plot(n_stitch_low,
                 MDU_stitch_low,
                 ls='dashed',
                 color='red',
                 label='$g\'(n)$: low stitched')
        plt.plot(n_stitch_high,
                 MDU_stitch_high,
                 ls='dotted',
                 color='blue',
                 label='$g\'(n)$: high stitched')
        # for the minor ticks, use no labels; default NullFormatter
        minorLocator = MultipleLocator(1)
        ax.xaxis.set_minor_locator(minorLocator)
        plt.grid(b=True, which='major', color='0.65', linestyle='-')
        plt.title('Marginal utility of consumption with stitched ' +
                  'function',
                  fontsize=14)
        plt.xlabel(r'Labor $n$')
        plt.ylabel(r'Marginal disutility $v\'(n)$')
        plt.xlim((-0.05, l_tilde + 0.01))
        # plt.ylim((-1.0, 1.15 * (b_ss.max())))
        plt.legend(loc='upper left')
        output_path = os.path.join(output_dir, "MDU_n_stitched")
        plt.savefig(output_path)
        # plt.show()

    return MDU_n
コード例 #25
0
X = np.linspace(0.5, 3.5, 100)
Y1 = 3 + np.cos(X)
Y2 = 1 + np.cos(1 + X / 0.75) / 2
Y3 = np.random.uniform(Y1, Y2, len(X))

fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1, aspect=1)


def minor_tick(x, pos):
    if not x % 1.0:
        return ""
    return "%.2f" % x


ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)

ax.tick_params(which='major', width=1.0)
ax.tick_params(which='major', length=10)
ax.tick_params(which='minor', width=1.0, labelsize=10)
ax.tick_params(which='minor', length=5, labelsize=10, labelcolor='0.25')

ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
コード例 #26
0
def MU_c_stitch(cvec, sigma, graph=False):
    '''
    --------------------------------------------------------------------
    Generate marginal utility(ies) of consumption with CRRA consumption
    utility and stitched function at lower bound such that the new
    hybrid function is defined over all consumption on the real
    line but the function has similar properties to the Inada condition.

    u'(c) = c ** (-sigma) if c >= epsilon
          = g'(c) = 2 * b2 * c + b1 if c < epsilon

        such that g'(epsilon) = u'(epsilon)
        and g''(epsilon) = u''(epsilon)

        u(c) = (c ** (1 - sigma) - 1) / (1 - sigma)
        g(c) = b2 * (c ** 2) + b1 * c + b0
    --------------------------------------------------------------------
    INPUTS:
    cvec  = scalar or (p,) vector, individual consumption value or
            lifetime consumption over p consecutive periods
    sigma = scalar >= 1, coefficient of relative risk aversion for CRRA
            utility function: (c**(1-sigma) - 1) / (1 - sigma)
    graph = boolean, =True if want plot of stitched marginal utility of
            consumption function

    OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None

    OBJECTS CREATED WITHIN FUNCTION:
    epsilon    = scalar > 0, positive value close to zero
    c_s        = scalar, individual consumption
    c_s_cnstr  = boolean, =True if c_s < epsilon
    b1         = scalar, intercept value in linear marginal utility
    b2         = scalar, slope coefficient in linear marginal utility
    MU_c       = scalar or (p,) vector, marginal utility of consumption
                 or vector of marginal utilities of consumption
    p          = integer >= 1, number of periods remaining in lifetime
    cvec_cnstr = (p,) boolean vector, =True for values of cvec < epsilon

    FILES CREATED BY THIS FUNCTION:
        MU_c_stitched.png

    RETURNS: MU_c
    --------------------------------------------------------------------
    '''
    epsilon = 0.0001
    if np.ndim(cvec) == 0:
        c_s = cvec
        c_s_cnstr = c_s < epsilon
        if c_s_cnstr:
            b2 = (-sigma * (epsilon**(-sigma - 1))) / 2
            b1 = (epsilon**(-sigma)) - 2 * b2 * epsilon
            MU_c = 2 * b2 * c_s + b1
        else:
            MU_c = c_s**(-sigma)
    elif np.ndim(cvec) == 1:
        p = cvec.shape[0]
        cvec_cnstr = cvec < epsilon
        MU_c = np.zeros(p)
        MU_c[~cvec_cnstr] = cvec[~cvec_cnstr]**(-sigma)
        b2 = (-sigma * (epsilon**(-sigma - 1))) / 2
        b1 = (epsilon**(-sigma)) - 2 * b2 * epsilon
        MU_c[cvec_cnstr] = 2 * b2 * cvec[cvec_cnstr] + b1

    if graph:
        '''
        ----------------------------------------------------------------
        cur_path    = string, path name of current directory
        output_fldr = string, folder in current path to save files
        output_dir  = string, total path of images folder
        output_path = string, path of file name of figure to be saved
        cvec_CRRA   = (1000,) vector, support of c including values
                      between 0 and epsilon
        MU_CRRA     = (1000,) vector, CRRA marginal utility of
                      consumption
        cvec_stitch = (500,) vector, stitched support of consumption
                      including negative values up to epsilon
        MU_stitch   = (500,) vector, stitched marginal utility of
                      consumption
        ----------------------------------------------------------------
        '''
        # Create directory if images directory does not already exist
        cur_path = os.path.split(os.path.abspath(__file__))[0]
        output_fldr = "images"
        output_dir = os.path.join(cur_path, output_fldr)
        if not os.access(output_dir, os.F_OK):
            os.makedirs(output_dir)

        # Plot steady-state consumption and savings distributions
        cvec_CRRA = np.linspace(epsilon / 2, epsilon * 3, 1000)
        MU_CRRA = cvec_CRRA**(-sigma)
        cvec_stitch = np.linspace(-0.00005, epsilon, 500)
        MU_stitch = 2 * b2 * cvec_stitch + b1
        fig, ax = plt.subplots()
        plt.plot(cvec_CRRA, MU_CRRA, ls='solid', label='$u\'(c)$: CRRA')
        plt.plot(cvec_stitch,
                 MU_stitch,
                 ls='dashed',
                 color='red',
                 label='$g\'(c)$: stitched')
        # for the minor ticks, use no labels; default NullFormatter
        minorLocator = MultipleLocator(1)
        ax.xaxis.set_minor_locator(minorLocator)
        plt.grid(b=True, which='major', color='0.65', linestyle='-')
        plt.title('Marginal utility of consumption with stitched ' +
                  'function',
                  fontsize=14)
        plt.xlabel(r'Consumption $c$')
        plt.ylabel(r'Marginal utility $u\'(c)$')
        plt.xlim((-0.00005, epsilon * 3))
        # plt.ylim((-1.0, 1.15 * (b_ss.max())))
        plt.legend(loc='upper right')
        output_path = os.path.join(output_dir, "MU_c_stitched")
        plt.savefig(output_path)
        # plt.show()

    return MU_c
コード例 #27
0
ファイル: favar_bloom.py プロジェクト: yyccxx1991/pymaclab
    ts.Date(freq='M', year=1990, month=7, day=1),
    ts.Date(freq='M', year=1991, month=3, day=1)
])
rdates.append([
    ts.Date(freq='M', year=2001, month=3, day=1),
    ts.Date(freq='M', year=2001, month=11, day=1)
])
rdates.append([
    ts.Date(freq='M', year=2007, month=12, day=1),
    ts.Date(freq='M', year=2009, month=7, day=1)
])

# Before running the VAR, plot the uncertainty data for the paper
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import matplotlib.dates as mdates
majorLocator = MultipleLocator(1)
majorFormatter = FormatStrFormatter('%d')
minorLocator = MultipleLocator(1)
years = mdates.YearLocator()  # every year
months = mdates.MonthLocator()  # every month
yearsFmt = mdates.DateFormatter('%Y')
glopt = modconfig['graph_options']['labels']
gridopt = modconfig['graph_options']['grid']
modconfig['modname']
# Check if directory exists
if modname not in os.listdir('../graphs/'):
    os.mkdir('../graphs/' + modname)
uncert = matd[:, 0]
fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
if gridopt: ax1.grid()
コード例 #28
0
    # figsize(x1, y1), GridSpec(y2, x2) --> To have square plots: x1/x2 =
    # y1/y2 = 2.5
    fig = plt.figure(figsize=(20, 30))  # create the top-level container
    gs = gridspec.GridSpec(12, 8)  # create a GridSpec object

    # Plot most probable members stars.
    ax0 = plt.subplot(gs[4:10, 2:6])
    plt.xlim(max(-0.9, min(data[0][0]) - 0.2), min(3.9, max(data[0][0]) + 0.2))
    plt.ylim(max(data[0][1]) + 1., min(data[0][1]) - 0.5)
    #Set axis labels
    plt.xlabel(r'$(C-T_1)_o$', fontsize=18)
    plt.ylabel(r'$M_{T_1}$', fontsize=18)

    # Set minor ticks and grid.
    ax0.minorticks_on()
    ax0.xaxis.set_major_locator(MultipleLocator(1.0))
    ax0.grid(b=True, which='major', color='gray', linestyle='--', lw=1)

    # Create new list with inverted values so higher prob stars are on top.
    m_p_m_temp = [data[0][0], data[0][1], data[0][2]]
    cm = plt.cm.get_cmap('RdYlBu_r')

    # Sort this list first by the decontamination index from max
    # value (1) to min (0) and then by its magnitude value, from min to max.
    m_p_m_temp_sort = zip(*sorted(zip(*m_p_m_temp), key=lambda x: x[2]))

    # Plot stars.
    plt.scatter(m_p_m_temp_sort[0],
                m_p_m_temp_sort[1],
                marker='o',
                c=m_p_m_temp_sort[2],
コード例 #29
0
			total=data[:,1]
			p_tot=data[:,i]
			s=data[:,i+1]
			p=data[:,i+2]
			d=data[:,i+3]
			f=data[:,i+4]

			fig,ax=plt.subplots()
			#ax.plot(x,total,'black',linewidth=1,label='Total')
			ax.plot(x,p_tot,'black',linewidth=linewidth,label=ats[num]+' total')
			ax.plot(x,s,linewidth=linewidth,label='s')
			ax.plot(x,p,linewidth=linewidth,label='p')
			ax.plot(x,d,linewidth=linewidth,label='d')
			ax.plot(x,f,linewidth=linewidth,label='f')

			ax.yaxis.set_major_locator(MultipleLocator(3))
			ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
			ax.yaxis.set_minor_locator(MultipleLocator(0.5))
			ax.set_ylim(ymin=0)


			if zoom==False:
				#ax.set_xlim(min(x),max(x))
				ax.set_xlim(-0.85,0.85)
				ax.set_ylim(0,25)
				ax.xaxis.set_major_locator(MultipleLocator(0.2))
				ax.xaxis.set_major_formatter(FormatStrFormatter('%1.1f'))
				ax.xaxis.set_minor_locator(MultipleLocator(0.02))

			else:
				ax.set_xlim(-0.08,0.08)
コード例 #30
0
    def plot(self,
             filename="triplot.png",
             doshow=True,
             figsize=(8, 6),
             save=True,
             minimum=None,
             points=None,
             colorbararrow=None):
        '''
        Create the triangle plots as in the optimal frequencies paper.
        '''
        fig = figure(figsize=figsize)
        ax = fig.add_subplot(111)
        if self.frac_bw == False:
            data = np.transpose(np.log10(self.sigmas))
            if self.log == False:
                im = uimshow(
                    data,
                    extent=[self.Cs[0], self.Cs[-1], self.Bs[0], self.Bs[-1]],
                    cmap=cm.inferno_r,
                    ax=ax)

                ax.set_xlabel(r"$\mathrm{Center~Frequency~\nu_0~(GHz)}$")
                ax.set_ylabel(r"$\mathrm{Bandwidth}~B~\mathrm{(GHz)}$")
            else:

                im = uimshow(data,
                             extent=np.log10(
                                 np.array([
                                     self.Cs[0], self.Cs[-1], self.Bs[0],
                                     self.Bs[-1]
                                 ])),
                             cmap=cm.inferno_r,
                             ax=ax)
                cax = ax.contour(data,
                                 extent=np.log10(
                                     np.array([
                                         self.Cs[0], self.Cs[-1], self.Bs[0],
                                         self.Bs[-1]
                                     ])),
                                 colors=self.colors,
                                 levels=self.levels,
                                 linewidths=self.lws,
                                 origin='lower')

                #https://stackoverflow.com/questions/18390068/hatch-a-nan-region-in-a-contourplot-in-matplotlib
                # get data you will need to create a "background patch" to your plot
                xmin, xmax = ax.get_xlim()
                ymin, ymax = ax.get_ylim()
                xy = (xmin, ymin)
                width = xmax - xmin
                height = ymax - ymin
                # create the patch and place it in the back of countourf (zorder!)
                p = patches.Rectangle(xy,
                                      width,
                                      height,
                                      hatch='X',
                                      color='0.5',
                                      fill=None,
                                      zorder=-10)
                ax.add_patch(p)

                ax.set_xlabel(r"$\mathrm{Center~Frequency~\nu_0~(GHz)}$")
                ax.set_ylabel(r"$\mathrm{Bandwidth}~B~\mathrm{(GHz)}$")
                ax.xaxis.set_major_locator(MultipleLocator(0.5))
                ax.yaxis.set_major_locator(MultipleLocator(0.5))
                ax.xaxis.set_major_formatter(noformatter)
                ax.yaxis.set_major_formatter(noformatter)

                ax.text(0.05,
                        0.9,
                        "PSR~%s" % self.psrnoise.name.replace("-", "$-$"),
                        fontsize=18,
                        transform=ax.transAxes,
                        bbox=dict(boxstyle="square", fc="white"))

            if minimum is not None:
                checkdata = np.log10(self.sigmas)
                flatdata = checkdata.flatten()
                #inds = np.where(np.logical_not(np.isnan(flatdata)))[0]
                inds = np.where((~np.isnan(flatdata))
                                & ~(np.isinf(flatdata)))[0]
                MIN = np.min(flatdata[inds])
                INDC, INDB = np.where(checkdata == MIN)
                INDC, INDB = INDC[0], INDB[0]
                MINB = self.Bs[INDB]
                MINC = self.Cs[INDC]
                cax = ax.contour(data,
                                 extent=np.log10(
                                     np.array([
                                         self.Cs[0], self.Cs[-1], self.Bs[0],
                                         self.Bs[-1]
                                     ])),
                                 colors=['b', 'b'],
                                 levels=[
                                     np.log10(1.1 * (10**MIN)),
                                     np.log10(1.5 * (10**MIN))
                                 ],
                                 linewidths=[1, 1],
                                 linestyles=['--', '--'],
                                 origin='lower')
                print("Minimum", MINC, MINB, MIN)
                with open("minima.txt", 'a') as FILE:
                    FILE.write("%s minima %f %f %f\n" %
                               (self.psrnoise.name, MINC, MINB, MIN))
                if self.log:
                    ax.plot(np.log10(MINC),
                            np.log10(MINB),
                            minimum,
                            zorder=50,
                            ms=10)
                else:
                    ax.plot(MINC, MINB, minimum, zorder=50, ms=10)

            if points is not None:
                if type(points) == tuple:
                    points = [points]
                for point in points:
                    x, y, fmt = point
                    nulow = x - y / 2.0
                    nuhigh = x + y / 2.0

                    if self.log:
                        ax.plot(np.log10(x), np.log10(y), fmt, zorder=50, ms=8)
                        nus = np.logspace(np.log10(nulow), np.log10(nuhigh),
                                          self.nchan + 1)[:-1]
                        sigma = np.log10(self.calc_single(nus))
                    else:
                        ax.plot(x, y, fmt, zorder=50, ms=8)
                        nus = np.linspace(nulow, nuhigh, self.nchan +
                                          1)[:-1]  #more uniform sampling?
                        sigma = np.log10(self.calc_single(nus))
                    with open("minima.txt", 'a') as FILE:
                        FILE.write("%s point %f %f %f\n" %
                                   (self.psrnoise.name, x, y, sigma))

            if colorbararrow is not None:
                data = np.log10(self.sigmas)
                flatdata = data.flatten()
                #inds = np.where(np.logical_not(np.isnan(flatdata)))[0]
                inds = np.where((~np.isnan(flatdata))
                                & ~(np.isinf(flatdata)))[0]
                MIN = np.min(flatdata[inds])
                MAX = np.max(flatdata[inds])
                if self.log == True:
                    x = np.log10(self.Cs[-1] * 1.05)  #self.Bs[-1])
                    dx = np.log10(1.2)  #np.log10(self.Cs[-1])#self.Bs[-1]*2)
                    frac = (np.log10(colorbararrow) - MIN) / (MAX - MIN)
                    y = frac * (np.log10(self.Bs[-1]) -
                                np.log10(self.Bs[0])) + np.log10(self.Bs[0])
                    arrow(x,
                          y,
                          dx,
                          0.0,
                          fc='k',
                          ec='k',
                          zorder=50,
                          clip_on=False)

        else:
            if self.log == False:
                pass
            else:
                goodinds = []
                for indf, F in enumerate(self.Fs):
                    if np.any(np.isnan(self.sigmas[:, indf])):
                        continue
                    goodinds.append(indf)
                goodinds = np.array(goodinds)
                data = np.transpose(np.log10(self.sigmas[:, goodinds]))

                im = uimshow(data,
                             extent=np.log10(
                                 np.array([
                                     self.Cs[0], self.Cs[-1],
                                     self.Fs[goodinds][0],
                                     self.Fs[goodinds][-1]
                                 ])),
                             cmap=cm.inferno_r,
                             ax=ax)
                cax = ax.contour(data,
                                 extent=np.log10(
                                     np.array([
                                         self.Cs[0], self.Cs[-1],
                                         self.Fs[goodinds][0],
                                         self.Fs[goodinds][-1]
                                     ])),
                                 colors=COLORS,
                                 levels=LEVELS,
                                 linewidths=LWS,
                                 origin='lower')

                #im = uimshow(data,extent=np.array([np.log10(self.Cs[0]),np.log10(self.Cs[-1]),self.Fs[goodinds][0],self.Fs[goodinds][-1]]),cmap=cm.inferno_r,ax=ax)
                #cax = ax.contour(data,extent=np.array([np.log10(self.Cs[0]),np.log10(self.Cs[-1]),self.Fs[goodinds][0],self.Fs[goodinds][-1]]),colors=COLORS,levels=LEVELS,linewidths=LWS,origin='lower')

                print(self.Fs)
                ax.set_xlabel(r"$\mathrm{Center~Frequency~\nu_0~(GHz)}$")
                #ax.set_ylabel(r"$r~\mathrm{(\nu_{max}/\nu_{min})}$")
                ax.set_ylabel(r"$\mathrm{Fractional~Bandwidth~(B/\nu_0)}$")
                # no log
                #ax.yaxis.set_major_locator(FixedLocator(np.log10(np.arange(0.25,1.75,0.25))))

                ax.xaxis.set_major_formatter(noformatter)
                #ax.yaxis.set_major_formatter(noformatter)

        cbar = fig.colorbar(im)  #,format=formatter)
        cbar.set_label("$\mathrm{TOA~Uncertainty~\sigma_{TOA}~(\mu s)}$")

        # https://stackoverflow.com/questions/6485000/python-matplotlib-colorbar-setting-tick-formator-locator-changes-tick-labels
        cbar.locator = MultipleLocator(1)
        cbar.formatter = formatter
        '''
        MAX = np.max(data[np.where(np.logical_not(np.isnan(data)))])
        if MAX <= np.log10(700):
            cbar.formatter = formatter100
        else:
            cbar.formatter = formatter
        '''
        cbar.update_ticks()
        #if self.log:
        #    cb = colorbar(cax)

        if save:
            savefig(filename)
        if doshow:
            show()
        else:
            close()