Example #1
0
def test_LogFormatterExponent():
    class FakeAxis(object):
        """Allow Formatter to be called without having a "full" plot set up."""
        def get_view_interval(self):
            return 1, 10

    i = np.arange(-3, 4, dtype=float)
    expected_result = ['-3', '-2', '-1', '0', '1', '2', '3']
    for base in [2, 5, 10, np.pi, np.e]:
        formatter = mticker.LogFormatterExponent(base=base)
        formatter.axis = FakeAxis()
        vals = base**i
        labels = [formatter(x, pos) for (x, pos) in zip(vals, i)]
        nose.tools.assert_equal(labels, expected_result)

    # Should be a blank string for non-integer powers if labelOnlyBase=True
    formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True)
    formatter.axis = FakeAxis()
    nose.tools.assert_equal(formatter(10**0.1), '')

    # Otherwise, non-integer powers should be nicely formatted
    locs = np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001])
    i = range(len(locs))
    expected_result = ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']
    for base in [2, 5, 10, np.pi, np.e]:
        formatter = mticker.LogFormatterExponent(base, labelOnlyBase=False)
        formatter.axis = FakeAxis()
        vals = base**locs
        labels = [formatter(x, pos) for (x, pos) in zip(vals, i)]
        nose.tools.assert_equal(labels, expected_result)
Example #2
0
def plot_var_hist_hr_ht(ax):
    data_usp = core.get_data('fig6/histogram_hr_ht.npy')   


    ax.set_ylim([0.,20.])
    ax.set_xlim([0.,5.])
    
    
    
    counts,bins,patches=ax.hist(data_usp,bins=np.arange(0.,25.,.5),log=1,orientation="horizontal",density=1,rwidth=1.,color=core.label_to_color["hr_ht"])
    ax.set_xlim(ax.get_xlim()[::-1])
   
    ax.spines['left'].set_position(('axes', 1.))
    ax.tick_params(axis="y",direction="in", pad=-15.)
    ax.tick_params(axis="x",direction="out", pad=-0.3)
   
    core.show_axis(ax)
    core.make_spines(ax)
    tick_formatter =ticker.LogFormatterExponent()
    ax.xaxis.set_major_formatter(tick_formatter)

    
    ax.set_xlabel(core.x_labels["hist"],labelpad=-2.)
    
    
    
    pass
Example #3
0
 def test_basic(self, labelOnlyBase, base, exponent, locs, positions,
                expected):
     formatter = mticker.LogFormatterExponent(base=base,
                                              labelOnlyBase=labelOnlyBase)
     formatter.axis = FakeAxis(1, base**exponent)
     vals = base**locs
     labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)]
     assert labels == expected
Example #4
0
    def scatter_simple(self, count_x: pd.Series, count_y: pd.Series, log_norm=False, **kwargs) -> plt.Axes:
        """Creates a simple scatter plot of counts.

        Args:
            count_x: A pandas dataframe/series of counts per feature (X axis)
            count_y: A pandas dataframe/series of counts per feature (Y axis)
            log_norm: Plot on log scale rather than linear scale
            kwargs: Additional keyword arguments to pass to pyplot.Axes.scatter()

        Returns:
            ax: A simple scatter plot of counts
        """

        # Retrieve axis and styles for this plot type
        fig, ax = self.reuse_subplot("scatter")
        ax: plt.Axes

        # log2 normalize data if requested
        if log_norm:
            # Set log2 scale
            ax.set_xscale('log', base=2)
            ax.set_yscale('log', base=2)

            # Unset default formatters
            for axis in [ax.xaxis, ax.yaxis]:
                axis.set_major_formatter(tix.LogFormatterExponent(base=2))
                axis.set_minor_formatter(tix.NullFormatter())

            ax.scatter(count_x, count_y, edgecolor='none', **kwargs)

            # Draw y = x, x +/- 1 lines (log2 scale) using point pairs for the 3 lines
            for p1,p2 in [((1, 2), (2, 4)), ((1, 1), (2, 2)), ((1, 0.5), (2, 1))]:
                ax.axline(p1, p2, color='#CCCCCC', label='_nolegend_')
        else:
            # Set linear scale
            ax.set_xscale('linear')
            ax.set_yscale('linear')

            # Set up axis ticks and labels
            for axis in [ax.xaxis, ax.yaxis]:
                axis.set_major_locator(tix.MaxNLocator(6))
                axis.set_major_formatter(tix.ScalarFormatter())

            ax.scatter(count_x, count_y, **kwargs)

            # Draw y = x, x +/- 1 lines using point pairs for the 3 lines
            for p1,p2 in [((0, 1), (1, 2)), ((0, 0), (1, 1)), ((0,-1), (1, 0))]:
                ax.axline(p1, p2, color='#CCCCCC', label='_nolegend_')

        return ax
Example #5
0
def test_LogFormatterExponent():
    class FakeAxis(object):
        """Allow Formatter to be called without having a "full" plot set up."""
        def __init__(self, vmin=1, vmax=10):
            self.vmin = vmin
            self.vmax = vmax

        def get_view_interval(self):
            return self.vmin, self.vmax

    i = np.arange(-3, 4, dtype=float)
    expected_result = ['-3', '-2', '-1', '0', '1', '2', '3']
    for base in [2, 5.0, 10.0, np.pi, np.e]:
        formatter = mticker.LogFormatterExponent(base=base)
        formatter.axis = FakeAxis(1, base**4)
        yield _logfe_helper, formatter, base, i, i, expected_result

    # Should be a blank string for non-integer powers if labelOnlyBase=True
    formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True)
    formatter.axis = FakeAxis()
    nose.tools.assert_equal(formatter(10**0.1), '')

    # Otherwise, non-integer powers should be nicely formatted
    locs = np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001])
    i = range(len(locs))
    expected_result = ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']
    for base in [2, 5, 10, np.pi, np.e]:
        formatter = mticker.LogFormatterExponent(base, labelOnlyBase=False)
        formatter.axis = FakeAxis(1, base**10)
        yield _logfe_helper, formatter, base, locs, i, expected_result

    expected_result = ['3', '5', '12', '42']
    locs = np.array([3, 5, 12, 42], dtype='float')
    for base in [2, 5.0, 10.0, np.pi, np.e]:
        formatter = mticker.LogFormatterExponent(base, labelOnlyBase=False)
        formatter.axis = FakeAxis(1, base**50)
        yield _logfe_helper, formatter, base, locs, i, expected_result
Example #6
0
 def test_blank(self):
     # Should be a blank string for non-integer powers if labelOnlyBase=True
     formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True)
     formatter.axis = FakeAxis()
     assert formatter(10**0.1) == ''
Example #7
0
    def _set_ticker(self, a):
        try:
            if not isiterable(self.ticks):
                if self.scale == 'linear':
                    a.set_major_locator(mticker.AutoLocator())
                elif self.scale == 'log':
                    a.set_major_locator(mticker.LogLocator(self.base))
                elif self.scale == 'symlog':
                    from matplotlib.scale import SymmetricalLogScale
                    if isMPL33:
                        scale = SymmetricalLogScale(
                            a,
                            base=self.base,
                            linthresh=self.symloglin,
                            linscale=self.symloglinscale)
                    else:
                        scale = SymmetricalLogScale(
                            a,
                            basex=self.base,
                            linthreshx=self.symloglin,
                            linscalex=self.symloglinscale)
                    a.set_major_locator(
                        mticker.SymmetricalLogLocator(scale.get_transform()))


#                    scale.set_default_locators_and_formatters(a)

                else:
                    a.set_major_locator(mticker.AutoLocator())
                #a.get_axes().locator_params(self.name[0], nbins = 10)
                if self.ticks is not None:
                    value = self.ticks
                else:
                    #figpage = a.get_axes().figobj.get_figpage()
                    figpage = a.axes.figobj.get_figpage()
                    if self.name[0] == 'x':
                        value = figpage.getp('nticks')[0]
                    elif self.name[0] == 'y':
                        value = figpage.getp('nticks')[1]
                    elif self.name[0] == 'z':
                        value = figpage.getp('nticks')[2]
                    else:
                        pass
                try:
                    # this works onlyfor MaxNLocator
                    #a.get_axes().locator_params(self.name[0], nbins = value)
                    a.axes.locator_params(self.name[0], nbins=value)
                except BaseException:
                    # for Symlog and LogLocator
                    a.get_major_locator().numticks = value
            else:
                a.set_ticks(self.ticks)

            if self.format == 'default':
                if self.scale == 'linear':
                    a.set_major_formatter(mticker.ScalarFormatter())
                elif self.scale == 'log':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                elif self.scale == 'symlog':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                else:
                    a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar':
                a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar(mathtext)':
                a.set_major_formatter(
                    mticker.ScalarFormatter(useOffset=True, useMathText=True))
                a.get_major_formatter().get_offset()
            elif self.format == 'log':
                a.set_major_formatter(mticker.LogFormatter(self.base))
            elif self.format == 'log(mathtext)':
                a.set_major_formatter(mticker.LogFormatterMathtext(self.base))
            elif self.format == 'log(exp)':
                a.set_major_formatter(mticker.LogFormatterExponent(self.base))
            elif self.format == 'none':
                a.set_major_formatter(mticker.NullFormatter())
            else:
                a.set_major_formatter(mticker.FormatStrFormatter(self.format))
        except BaseException:
            import traceback
            traceback.print_exc()
Example #8
0
from helpers import get_structure_map, plot_pt_line, plot_heatmap

FILE_DIR = os.path.dirname(os.path.realpath(__file__))
TOP_DIR = os.path.join(FILE_DIR, '..', '..')

INPUT_JSON = os.path.join(TOP_DIR, 'input.json')
OUTPUT_FILE = os.path.join(FILE_DIR, 'regional_matrix.png')

STRUCTURE_LABELS = ["Iso-\ncortex", "OLF", "HPF", "CTXsp", "STR", "PAL",
                    "Thal", "Hypo-\nthal", "Mid-\nbrain", "Pons", "Medulla", "CB"]

FIGSIZE = (10, 5.5)
SAVEFIG_KWARGS = dict(dpi=200, transparent=True, bbox_inches='tight')
CBAR_KWS = dict(ticks=[1e-5, 1e-4, 1e-3], orientation='horizontal', fraction=0.5,
                format=ticker.LogFormatterExponent())
GRID_KWS = dict(nrows=3,
                ncols=3,
                wspace=0.0,
                hspace=0.0,
                height_ratios=(0.03, 0.10, 0.87),
                width_ratios=(0.06, 0.01, 0.93))
HEATMAP_KWS = dict(vmin=1e-5,
                   vmax=10**-2.5,
                   cmap="CMRmap",
                   norm="LogNorm",
                   epsilon=1e-10,
                   alpha=0.85,
                   cbar=True,
                   xticklabels=0,
                   yticklabels=0)
Example #9
0
def comp_props(dolines,
               dotypes=['med_8u'],
               clouds=None,
               markers=None,
               indir=None,
               leaves=False,
               cmap_name='gist_rainbow',
               mec='gray',
               xplot=['rad_pc'],
               yplot=['vrms_k'],
               xlims=[[-1, 1.5]],
               ylims=[[-2, 1.5]],
               pltname=['rdv'],
               slope=[0.5],
               pad=[0.03]):

    global axes
    params = {'mathtext.default': 'regular'}
    plt.rcParams.update(params)
    cmap = plt.get_cmap(cmap_name)

    # Table of cloud-averaged properties
    cldtab = Table(names=('cld', 'med_8u', 'med_co', 'avg_st', 'med_24'),
                   dtype=('S6', 'f4', 'f4', 'f4', 'f4'))
    cldtab.add_row(('30Dor', 36.8732, 2.0518, 0.8101, 386.8365))
    cldtab.add_row(('N59C', 8.1936, 3.0875, 0.3671, 12.8014))
    cldtab.add_row(('A439', 2.6004, 3.2009, 0.6587, 1.2010))
    cldtab.add_row(('GMC104', 1.5529, 4.4368, 1.7162, 0.6574))
    cldtab.add_row(('GMC1', 1.1792, 2.0274, 0.3059, 0.5231))
    cldtab.add_row(('PCC', 0.7974, 1.4606, 0.5502, 0.1617))
    # Convert stellar surf density to Msol/pc^2
    cldtab['avg_st'] = cldtab['avg_st'] * 62.5

    # Generate plots
    for i in range(len(xplot)):
        for line in dolines:
            for type in dotypes:
                fig, axes = plt.subplots()
                for j, reg in enumerate(clouds):
                    dir = indir.replace('CLOUD', reg)
                    if os.path.isfile(dir + reg + '_' + line +
                                      '_physprop_add.txt'):
                        infile = dir + reg + '_' + line + '_physprop_add.txt'
                    else:
                        infile = dir + reg + '_' + line + '_physprop.txt'
                    if type in ['8um_avg', 'siglum']:
                        if type == 'siglum' and line == '12':
                            norm = LogNorm(vmin=10, vmax=1000)
                        else:
                            norm = LogNorm(vmin=1, vmax=100)
                        plot_ecsv(infile,
                                  xplot[i],
                                  yplot[i],
                                  zaxis=type,
                                  cmap=cmap,
                                  mark=markers[j],
                                  mec=mec,
                                  msize=8,
                                  zorder=i,
                                  label=reg,
                                  leaves=leaves,
                                  norm=norm)
                    else:
                        if type == 'med_co':
                            norm = Normalize(vmin=min(cldtab[type]),
                                             vmax=max(cldtab[type]))
                        else:
                            norm = LogNorm(vmin=min(cldtab[type]),
                                           vmax=max(cldtab[type]))
                        colr = np.array(cmap(norm(cldtab[type][j])))
                        plot_ecsv(infile,
                                  xplot[i],
                                  yplot[i],
                                  col=colr,
                                  mark=markers[j],
                                  mec=mec,
                                  msize=8,
                                  zorder=i,
                                  label=reg,
                                  leaves=leaves)
                axes.set_xlim(10**xlims[i][0], 10**xlims[i][1])
                axes.set_ylim(10**ylims[i][0], 10**ylims[i][1])
                logfmt = ticker.LogFormatterExponent(base=10.0,
                                                     labelOnlyBase=True)
                axes.xaxis.set_major_formatter(logfmt)
                axes.yaxis.set_major_formatter(logfmt)
                axes.minorticks_off()
                # Reference slopes
                xmod = np.logspace(xlims[i][0], xlims[i][1], 100)
                ymod = xmod**slope[i]
                if xplot[i] == 'rad_pc' and yplot[i] == 'vrms_k':
                    ymod = ymod * 0.72
                    axes.plot(xmod,
                              ymod,
                              linestyle='-',
                              color='r',
                              lw=4,
                              alpha=0.5,
                              zorder=-1)
                    axes.text(10**(xlims[i][1] - 0.05),
                              10**(ylims[i][1] - 0.8),
                              'S87',
                              horizontalalignment='right',
                              color='r',
                              rotation=30)
                else:
                    # Plot nominal R(12/13) of 8
                    if xplot[i] == 'flux12' and yplot[i] == 'flux13':
                        ymod = ymod / 8
                    # Plot nominal Sigma_mol of 100 Msol/pc^2
                    if xplot[i].startswith('area') and yplot[i].startswith(
                            'm'):
                        ymod = ymod * 100
                    axes.plot(xmod, ymod, '--', marker=None, color='k')
                # Lines of constant external pressure
                if xplot[i].startswith('sig') and yplot[i] == 'sigvir':
                    ymod = xmod + (20 / (3 * np.pi * 21.1)) * 1.e4 / xmod
                    axes.plot(xmod, ymod, linestyle='-', color='g', lw=1)
                    axes.text(10**-0.97,
                              10**3.5,
                              '$P_{ext}$ = $10^4$ cm$^{-3}$ K',
                              color='g',
                              rotation=-45)
                    ymod2 = xmod + (20 / (3 * np.pi * 21.1)) * 1.e2 / xmod
                    axes.plot(xmod, ymod2, linestyle='-', color='m', lw=1)
                    axes.text(10**-0.97,
                              10**2.1,
                              '$P_{ext}$ = $10^2$ cm$^{-3}$ K',
                              color='m',
                              rotation=-45)
                    axes.text(10**-0.95,
                              10**-0.25,
                              'Virial Eq',
                              color='k',
                              rotation=45)
                # Legend and colorbar
                plt.legend(loc='lower right',
                           fontsize='small',
                           numpoints=1,
                           markerscale=2)
                cax = fig.add_axes([pad[i] + 0.7, 0.11, 0.02, 0.77])
                formatter = ticker.LogFormatter(10,
                                                labelOnlyBase=False,
                                                minor_thresholds=(4, 3))
                if type == 'med_co':
                    cbar = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)
                else:
                    cbar = mpl.colorbar.ColorbarBase(
                        cax,
                        cmap=cmap,
                        norm=norm,
                        format=formatter,
                        ticks=[1, 2, 5, 10, 20, 50, 100, 200, 500, 1000])
                cbar.ax.tick_params(labelsize=9)
                if type == 'med_8u':
                    cbar.set_label('cloud median 8$\mu$m intensity [MJy/sr]',
                                   rotation=90)
                elif type == 'med_co':
                    cbar.set_label('cloud median CO intensity [K km/s]',
                                   rotation=90)
                elif type == 'avg_st':
                    cbar.set_label(
                        'cloud mean $\Sigma_{*}$ [$M_\odot$ $pc^{-2}$]',
                        rotation=90)
                elif type == 'med_24':
                    cbar.set_label('cloud mean 24$\mu$m intensity [MJy/sr]',
                                   rotation=90)
                elif type == '8um_avg':
                    cbar.set_label('local mean 8$\mu$m intensity [MJy/sr]',
                                   rotation=90)
                elif type == 'siglum':
                    cbar.set_label(
                        'local mean $\Sigma_{mol}$ [$M_\odot$ $pc^{-2}$]',
                        rotation=90)
                plt.savefig('comp_' + line + '_' + pltname[i] + '_' + type +
                            '.pdf',
                            bbox_inches='tight')
                plt.close()
    return
Example #10
0
# coding: utf8
import json

import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

logfmt = ticker.LogFormatterExponent(base=10.0, labelOnlyBase=True)

import matplotlib as mpl

mpl.rcParams['lines.linewidth'] = 4.0
params = {
    'axes.labelsize': 'x-large',
    'axes.titlesize': 'x-large',
    'xtick.labelsize': 'x-large',
    'ytick.labelsize': 'x-large',
    'lines.markersize': 7,
    'font.size': 20
}
mpl.rcParams.update(params)

__color_rotation__ = [
    'red', 'gold', 'coral', 'darkturquoise', 'royalblue', 'darkblue', 'm',
    'hotpink', 'lightpink', 'dimgrey'
]
__marker_rotation__ = ['o', '^', 's', 'H', '+', '.', 'D', 'x', 'o', 'H', 's']
__linestyle_rotation__ = ['--', ':', '-', '-.']
Example #11
0
def create_mesh(fig, ax, filepath, filename, field, setup, cbaxes, vmin = None, vmax = None, 
                log=False, forder=False, rcmap = False, cmap='magma',
                rmax= 0.0,
                ):
    
    field_dict = {}
    with h5py.File(filepath + filename, 'r+') as hf:
        
        ds = hf.get("sim_info")
        
        rho         = hf.get("rho")[:]
        v1          = hf.get("v1")[:]
        v2          = hf.get("v2")[:]
        p           = hf.get("p")[:]
        nx          = ds.attrs["NX"]
        ny          = ds.attrs["NY"]
        t           = ds.attrs["current_time"]
        xmax        = ds.attrs["xmax"]
        xmin        = ds.attrs["xmin"]
        ymax        = ds.attrs["ymax"]
        ymin        = ds.attrs["ymin"]
        
        
        rho = rho.reshape(ny, nx)
        v1  = v1.reshape(ny, nx)
        v2  = v2.reshape(ny, nx)
        p   = p.reshape(ny, nx)
        
        if forder:
            rho = rho[1:-1, 1: -1]
            v1  = v1 [1:-1, 1: -1]
            v2  = v2 [1:-1, 1: -1]
            p   = p  [1:-1, 1: -1]
            xactive = nx - 2
            yactive = ny - 2
        else:
            rho = rho[2:-2, 2: -2]
            v1  = v1 [2:-2, 2: -2]
            v2  = v2 [2:-2, 2: -2]
            p   = p  [2:-2, 2: -2]
            xactive = nx - 4
            yactive = ny - 4
            
        W    = 1/np.sqrt(1 - v1**2 + v2**2)
        beta = np.sqrt(v1**2 + v2**2)
        
        e = 3*p/rho 
        c = const.c.cgs.value
        a = (4 * const.sigma_sb.cgs.value / c)
        m = const.m_p.cgs.value
        T = (3 * p * c ** 2  / a)**(1./4.)
        
        
        field_dict["rho"]         = rho
        field_dict["v1"]          = v1 
        field_dict["v2"]          = v2 
        field_dict["p"]           = p
        field_dict["gamma_beta"]  = W*beta
        field_dict["temperature"] = T
        
        
    ynpts, xnpts = rho.shape 

    if (log):
        r = np.logspace(np.log10(xmin), np.log10(xmax), xactive)
    else:
        r = np.linspace(xmin, xmax, xactive)
        
    # r = np.logspace(np.log10(0.01), np.log10(0.5), xnpts)
    theta = np.linspace(ymin, ymax, yactive)
    theta_mirror = - theta[::-1]
    theta_mirror[-1] *= -1.
    
    rr, tt = np.meshgrid(r, theta)
    rr, t2 = np.meshgrid(r, theta_mirror)
    
    norm  = colors.LogNorm(vmin = vmin, vmax = vmax)
    
    if rcmap:
        color_map = (plt.cm.get_cmap(cmap)).reversed()
    else:
        color_map = plt.cm.get_cmap(cmap)


    c1 = ax.pcolormesh(tt, rr, field_dict[field], cmap=color_map, shading='auto', norm = norm)
    c2 = ax.pcolormesh(t2[::-1], rr, field_dict[field],  cmap=color_map, shading='auto', norm = norm)


    if log:
        logfmt = tkr.LogFormatterExponent(base=10.0, labelOnlyBase=True)
        cbar = fig.colorbar(c2, orientation='vertical', cax=cbaxes, format=logfmt)
    else:
        cbar = fig.colorbar(c2, orientation='horizontal', cax=cbaxes)
        
    fig.suptitle('SIMBI: {} at t = {:.2f} s'.format(setup, t), fontsize=20, y=0.95)
    
    # ax.set_position( [0.1, -0.18, 0.8, 1.43])
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    ax.yaxis.grid(True, alpha=0.1)
    ax.xaxis.grid(True, alpha=0.1)
    ax.tick_params(axis='both', labelsize=10)
    cbaxes.tick_params(axis='x', labelsize=10)
    ax.axes.xaxis.set_ticklabels([])
    ax.set_rmax(xmax) if rmax == 0.0 else ax.set_rmax(rmax)
    
    ymd = int( np.ceil(ymax * 180/np.pi) )
    ax.set_thetamin(-ymd)
    ax.set_thetamax(ymd)

    # Change the format of the field
    if   field == "rho":
        field_str = r'$\rho$'
    elif field == "gamma_beta":
        field_str = r"$\Gamma \ \beta$"
    else:
        field_str = field
    
    if log:
        cbar.ax.set_xlabel('Log [{}]'.format(field_str), fontsize=20)
    else:
        cbar.ax.set_xlabel('[{}]'.format(field), fontsize=20)
        
    return ax
Example #12
0
def main():
    parser = argparse.ArgumentParser(
        description='Plot a 2D Figure From a File (H5).',
        epilog="This Only Supports H5 Files Right Now")

    parser.add_argument('filename',
                        metavar='Filename',
                        nargs='+',
                        help='A Data Source to Be Plotted')

    parser.add_argument(
        'setup',
        metavar='Setup',
        nargs='+',
        type=str,
        help='The name of the setup you are plotting (e.g., Blandford McKee)')

    parser.add_argument(
        '--field',
        dest="field",
        metavar='Field Variable',
        nargs='?',
        help='The name of the field variable you\'d like to plot',
        choices=field_choices,
        default="rho")
    parser.add_argument('--rmax',
                        dest="rmax",
                        metavar='Radial Domain Max',
                        default=0.0,
                        help='The domain range')

    parser.add_argument('--cbar_range',
                        dest="cbar",
                        metavar='Range of Color Bar',
                        default='None, None',
                        help='The colorbar range you\'d like to plot')

    parser.add_argument('--cmap',
                        dest="cmap",
                        metavar='Color Bar Colarmap',
                        default='magma',
                        help='The colorbar cmap you\'d like to plot')

    parser.add_argument('--log',
                        dest='log',
                        action='store_true',
                        default=False,
                        help='Logarithmic Radial Grid Option')

    parser.add_argument('--first_order',
                        dest='forder',
                        action='store_true',
                        default=False,
                        help='True if this is a grid using RK1')

    parser.add_argument('--rev_cmap',
                        dest='rcmap',
                        action='store_true',
                        default=False,
                        help='True if you want the colormap to be reversed')

    parser.add_argument('--save',
                        dest='save',
                        action='store_true',
                        default=False,
                        help='True if you want save the fig')

    args = parser.parse_args()
    vmin, vmax = eval(args.cbar)
    field_dict = {}
    with h5py.File(args.filename[0], 'r+') as hf:

        ds = hf.get("sim_info")

        rho = hf.get("rho")[:]
        v1 = hf.get("v1")[:]
        v2 = hf.get("v2")[:]
        p = hf.get("p")[:]
        nx = ds.attrs["NX"]
        ny = ds.attrs["NY"]
        t = ds.attrs["current_time"]
        xmax = ds.attrs["xmax"]
        xmin = ds.attrs["xmin"]
        ymax = ds.attrs["ymax"]
        ymin = ds.attrs["ymin"]

        rho = rho.reshape(ny, nx)
        v1 = v1.reshape(ny, nx)
        v2 = v2.reshape(ny, nx)
        p = p.reshape(ny, nx)

        if args.forder:
            rho = rho[1:-1, 1:-1]
            v1 = v1[1:-1, 1:-1]
            v2 = v2[1:-1, 1:-1]
            p = p[1:-1, 1:-1]
            xactive = nx - 2
            yactive = ny - 2
        else:
            rho = rho[2:-2, 2:-2]
            v1 = v1[2:-2, 2:-2]
            v2 = v2[2:-2, 2:-2]
            p = p[2:-2, 2:-2]
            xactive = nx - 4
            yactive = ny - 4

        W = 1 / np.sqrt(1 - (v1**2 + v2**2))
        beta = np.sqrt(v1**2 + v2**2)

        e = 3 * p / rho
        c = const.c.cgs.value
        a = (4 * const.sigma_sb.cgs.value / c)
        k = const.k_B.cgs
        m = const.m_p.cgs.value
        T = (3 * p * c**2 / a)**(1. / 4.)

        field_dict["rho"] = rho
        field_dict["v1"] = v1
        field_dict["v2"] = v2
        field_dict["p"] = p
        field_dict["gamma_beta"] = W * beta
        field_dict["temperature"] = T

    ynpts, xnpts = rho.shape

    if (args.log):
        r = np.logspace(np.log10(xmin), np.log10(xmax), xactive)
        norm = colors.LogNorm(vmin=rho.min(), vmax=3. * rho.min())
    else:
        r = np.linspace(xmin, xmax, xactive)
        # norm = colors.LinearNorm(vmin=None, vmax=None)

    # r = np.logspace(np.log10(0.01), np.log10(0.5), xnpts)
    theta = np.linspace(ymin, ymax, yactive)
    theta_mirror = -theta[::-1]
    # theta_mirror[-1] *= -1.

    rr, tt = np.meshgrid(r, theta)
    rr, t2 = np.meshgrid(r, theta_mirror)

    ad_gamma = 4 / 3
    D = rho * W
    h = 1 + ad_gamma * p / (rho * (ad_gamma - 1))
    tau = rho * h * W**2 - p - rho * W
    S1 = D * h * W**2 * v1
    S2 = D * h * W**2 * v2
    S = np.sqrt(S1**2 + S2**2)
    E = tau + D
    # E[:, np.where(r > 0.16)] = E[0][]
    norm = colors.LogNorm(vmin=vmin, vmax=vmax)
    vnorm = colors.LogNorm(vmin=W.min(), vmax=W.max())
    enorm = colors.LogNorm(vmin=1, vmax=9e1)
    snorm = colors.LogNorm(vmin=1.e-5, vmax=1e2)

    if args.rcmap:
        color_map = (plt.cm.get_cmap(args.cmap)).reversed()
    else:
        color_map = plt.cm.get_cmap(args.cmap)

    fig, ax = plt.subplots(1,
                           1,
                           figsize=(15, 8),
                           subplot_kw=dict(projection='polar'),
                           constrained_layout=False)

    tend = t
    c1 = ax.pcolormesh(tt,
                       rr,
                       field_dict[args.field],
                       cmap=color_map,
                       shading='auto',
                       norm=norm)
    c2 = ax.pcolormesh(t2[::-1],
                       rr,
                       field_dict[args.field],
                       cmap=color_map,
                       shading='auto',
                       norm=norm)

    fig.suptitle('SIMBI: {} at t = {:.2f} s'.format(args.setup[0], t),
                 fontsize=20,
                 y=0.95)

    # divider = make_axes_locatable(ax)
    # cbaxes  = divider.append_axes('right', size='5%', pad=0.1)
    # cbar    = fig.colorbar(c2, orientation='vertical')
    # cbaxes  = fig.add_axes([0.2, 0.1, 0.6, 0.04])

    if ymax < np.pi:
        ax.set_position([0.1, -0.18, 0.8, 1.43])
        cbaxes = fig.add_axes([0.2, 0.1, 0.6, 0.04])
        cbar_orientation = "horizontal"
    else:
        cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8])
        cbar_orientation = "vertical"

    if args.log:
        logfmt = tkr.LogFormatterExponent(base=10.0, labelOnlyBase=True)
        cbar = fig.colorbar(c2,
                            orientation=cbar_orientation,
                            cax=cbaxes,
                            format=logfmt)
    else:
        cbar = fig.colorbar(c2, orientation='horizontal', cax=cbaxes)

    # ax.set_position( [0.1, -0.18, 0.8, 1.43])
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    ax.yaxis.grid(True, alpha=0.1)
    ax.xaxis.grid(True, alpha=0.1)
    ax.tick_params(axis='both', labelsize=10)
    # cbaxes.tick_params(axis='x', labelsize=10)
    ax.axes.xaxis.set_ticklabels([])
    ax.set_rmax(xmax) if args.rmax == 0.0 else ax.set_rmax(args.rmax)

    ymd = int(np.ceil(ymax * 180 / np.pi))
    ax.set_thetamin(-ymd)
    ax.set_thetamax(ymd)

    # Change the format of the field
    if args.field == "rho":
        field_str = r'$\rho$'
    elif args.field == "gamma_beta":
        field_str = r"$\Gamma \ \beta$"
    else:
        field_str = args.field

    if args.log:
        cbar.ax.set_xlabel('Log [{}]'.format(field_str), fontsize=20)
    else:
        cbar.ax.set_xlabel('[{}]'.format(args.field), fontsize=20)

    plt.show()

    if args.save:
        fig.savefig("plots/2D/SR/{}.png".format(args.setup[0].replace(
            " ", "_")),
                    dpi=300)