def plot_spectra_grid(
    hi_velocity_axis_list=None,
    hi_spectrum_list=None,
    hi_vel_range_list=None,
    co_spectrum_list=None,
    co_velocity_axis_list=None,
    hi_std_list=None,
    title=None,
    limits=None,
    savedir='./',
    filename=None,
    show=True,
    spectra_names='',
):

    # Import external modules
    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.pyplot as plt
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    plt.close
    plt.clf()

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 3.6))
    ax = fig.add_subplot(111)

    myplt.set_color_cycle(num_colors=3)

    for i in xrange(len(hi_velocity_axis_list)):

        # create axes
        spectra_names[i] = spectra_names[i].replace('1', ' 1')
        spectra_names[i] = spectra_names[i].replace('2', ' 2')

        ax.plot(
            co_velocity_axis_list[i],
            co_spectrum_list[i],
            #color='k',
            drawstyle='steps-mid',
            label=spectra_names[i].capitalize(),
        )

        ax.set_xlabel('Velocity [km/s]')
        ax.set_ylabel(r'T$_b$ [K]')

    ax.legend(loc='upper left')

    # plot limits
    if limits is not None:
        ax.set_xlim(limits[0], limits[1])
        ax.set_ylim(limits[2], limits[3])

    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight', dpi=100)
def calc_model_color_cycle(df):

    phi_cnm_max = np.max(df['phi_cnm'])
    phi_cnm_min = np.min(df['phi_cnm'])

    color_cycle = myplt.set_color_cycle(num_colors=len(df['phi_cnm']),
                                        cmap=plt.cm.gnuplot2,
                                        )
def plot_spectra_grid(hi_velocity_axis_list=None, hi_spectrum_list=None,
        hi_vel_range_list=None, co_spectrum_list=None,
        co_velocity_axis_list=None, hi_std_list=None, title=None, limits=None,
        savedir='./', filename=None, show=True, spectra_names='',):

    # Import external modules
    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.pyplot as plt
    import myplotting as myplt

    # Set up plot aesthetics
    # ----------------------
    plt.close;plt.clf()

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 3.6))
    ax = fig.add_subplot(111)

    myplt.set_color_cycle(num_colors=3)

    for i in xrange(len(hi_velocity_axis_list)):

        # create axes
        spectra_names[i] = spectra_names[i].replace('1', ' 1')
        spectra_names[i] = spectra_names[i].replace('2', ' 2')

        ax.plot(co_velocity_axis_list[i],
                co_spectrum_list[i],
                #color='k',
                drawstyle = 'steps-mid',
                label=spectra_names[i].capitalize(),
                )

        ax.set_xlabel('Velocity [km/s]')
        ax.set_ylabel(r'T$_b$ [K]')

    ax.legend(loc='upper left')

    # plot limits
    if limits is not None:
        ax.set_xlim(limits[0],limits[1])
        ax.set_ylim(limits[2],limits[3])

    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight', dpi=100)
def calc_model_color_cycle(df):

    phi_cnm_max = np.max(df['phi_cnm'])
    phi_cnm_min = np.min(df['phi_cnm'])

    color_cycle = myplt.set_color_cycle(
        num_colors=len(df['phi_cnm']),
        cmap=plt.cm.gnuplot2,
    )
def plot_planck_vs_2mass(
        av_k09,
        av_pl,
        filename=None,
        av_error=None,
        contour_plot=True,
        levels=10,
        plot_median=True,
        limits=None,
        labels=['', ''],
        scale=('linear', 'linear'),
        title='',
        fit_labels=['', ''],
        gridsize=(100, 100),
):

    # import external modules
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    from matplotlib import cm
    from astroML.plotting import scatter_contour
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid
    import myplotting as myplt

    # set up plot aesthetics
    # ----------------------
    plt.close
    plt.clf()

    # color map
    myplt.set_color_cycle(num_colors=3)

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 3.6))

    axes = AxesGrid(
        fig,
        (1, 1, 1),
        nrows_ncols=(1, 1),
        ngrids=1,
        axes_pad=0.25,
        aspect=False,
        label_mode='L',
        share_all=True,
        #cbar_mode='single',
        cbar_pad=0.1,
        cbar_size=0.2,
    )

    # Drop the NaNs from the images
    if type(av_error) is float or av_error is None:
        indices = np.where((av_pl == av_pl) &\
                           (av_k09 == av_k09)
                           )

    av_pl = av_pl[indices]
    av_k09 = av_k09[indices]

    # Create plot
    ax = axes[0]

    if limits is None:
        xmin = np.min(av_k09)
        ymin = np.min(av_k09)
        xmax = np.max(av_pl)
        ymax = np.max(av_pl)
        xscalar = 0.15 * xmax
        yscalar = 0.15 * ymax
        limits = [
            xmin - xscalar, xmax + xscalar, ymin - yscalar, ymax + yscalar
        ]

    if contour_plot:

        contour_range = ((limits[0], limits[1]), (limits[2], limits[3]))

        cmap = myplt.truncate_colormap(plt.cm.binary, 0.2, 1, 1000)

        l1 = myplt.scatter_contour(
            av_k09,
            av_pl,
            threshold=3,
            log_counts=1,
            levels=levels,
            ax=ax,
            histogram2d_args=dict(bins=30, range=contour_range),
            plot_args=dict(marker='o',
                           linestyle='none',
                           color='black',
                           alpha=0.3,
                           markersize=2),
            contour_args=dict(
                #cmap=plt.cm.binary,
                cmap=cmap,
                #cmap=cmap,
            ),
        )

    else:
        image = ax.errorbar(nhi_nonans.ravel(),
                            av_nonans.ravel(),
                            yerr=(av_error_nonans.ravel()),
                            alpha=0.2,
                            color='k',
                            marker='^',
                            ecolor='k',
                            linestyle='None',
                            markersize=3)

    # Plot sensitivies
    #av_limit = np.median(av_errors[0])
    #ax.axvline(av_limit, color='k', linestyle='--')

    # Plot 1 to 1 pline
    if 1:
        x_fit = np.linspace(-5, 200, 1000)
        p, V = \
                np.polyfit(av_k09, av_pl, deg=1,
                           #w=np.abs(1.0/av_error_nonans.ravel()),
                           cov=True
                           )

        y_poly_fit = p[0] * x_fit + p[1]
    if 1:
        ax.plot(x_fit,
                y_poly_fit,
                color='r',
                linestyle='dashed',
                linewidth=2,
                label=\
                    'Poly fit: \n' + \
                    fit_labels[0] + ' = ' + '{0:.1f}'.format(p[0]) + \
                    r'$\times$ ' + fit_labels[1] + \
                    ' + {0:.1f} mag'.format(p[1]),
                alpha=0.7,
                )
    if 0:
        from scipy.interpolate import UnivariateSpline

        spl = UnivariateSpline(av_k09, av_pl)
        ax.plot(x_fit, spl(x_fit), linewidth=3, alpha=0.5)

    if 0:
        print('Bootstrapping...')
        # bootstrap conf intervals
        import scipy as sp
        bootindex = sp.random.random_integers
        nboot = 20
        x_fit = av_k09
        y_fit = p[0] * x_fit + p[1]
        r = av_pl - y_fit
        for i in xrange(
                nboot):  # loop over n bootstrap samples from the resids
            pc = sp.polyfit(av_k09, y_fit + r[bootindex(0,
                                                        len(r) - 1, len(r))],
                            1)
            ax.plot(x_fit,
                    sp.polyval(pc, x_fit),
                    'k-',
                    linewidth=2,
                    alpha=1.0 / float(nboot))

    # Annotations
    anno_xpos = 0.95

    ax.set_xscale(scale[0], nonposx='clip')
    ax.set_yscale(scale[1], nonposy='clip')

    ax.set_xlim(limits[0], limits[1])
    ax.set_ylim(limits[2], limits[3])

    # Adjust asthetics
    #ax.set_xlabel(r'$A_{V,{\rm K+09}}$ [mag]')
    #ax.set_ylabel(r'$A_{V,{\rm Planck}}$ [mag]')
    ax.set_xlabel(labels[0])
    ax.set_ylabel(labels[1])
    ax.set_title(title)
    ax.legend(loc='best')

    if filename is not None:
        plt.savefig(filename)
def plot_density_cdfs(core_dict, df):

    import myplotting as myplt
    import matplotlib.pyplot as plt
    import mystats
    import myscience

    # load Stanimirovic temps
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_temps.npy'
    stani_temps = np.loadtxt(filename)
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_temp_errors.npy'
    stani_temp_errors = np.loadtxt(filename)
    stani_temp_errors = np.array((stani_temp_errors, stani_temp_errors)).T
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_int_temps.npy'
    stani_tempKs = np.loadtxt(filename)

    # load the dict
    with open('/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
              'stanimirovic14_temps.pickle', 'rb') as f:
        temp_dict = pickle.load(f)

    # concatenate the temps from each cloud
    Ts_list = []
    Ts_error_list = []
    Ts_avg_list = []
    Ts_avg_error_list = []
    for cloud in temp_dict:
        for Ts in temp_dict[cloud]['Ts_list']:
            Ts_list.append(Ts)
        for Ts_error in temp_dict[cloud]['Ts_error_list']:
            Ts_error_list.append(Ts_error)
        for Ts_avg in temp_dict[cloud]['Ts_avg_list']:
            #for Ts_avg in temp_dict[cloud]['Tk_list']:
            Ts_avg_list.append(Ts_avg)
        for Ts_avg_error in temp_dict[cloud]['Ts_avg_error_list']:
            #for Ts_avg_error in temp_dict[cloud]['Tk_error_list']:
            Ts_avg_error_list.append(Ts_avg_error)

    Ts_list = np.array(Ts_list)
    Ts_error_list = np.array(Ts_error_list)
    Ts_avg_list = np.array(Ts_avg_list)
    Ts_avg_error_list = np.array(Ts_avg_error_list)

    print '\nNumber of LOS:', len(Ts_avg_list)

    # collect data
    T_cnms = np.empty(len(core_dict))
    T_Hs = np.empty(len(core_dict))
    T_cnm_errors = np.empty((len(core_dict), 2))
    T_H_errors = np.empty((len(core_dict), 2))
    n_cnms = np.empty(len(core_dict))
    n_Hs = np.empty(len(core_dict))
    n_cnm_errors = np.empty((len(core_dict), 2))
    n_H_errors = np.empty((len(core_dict), 2))

    for i, core_name in enumerate(core_dict):
        core = core_dict[core_name]
        T_cnms[i] = core['T_cnm']
        T_Hs[i] = core['T_H'] * 1000.0
        T_cnm_errors[i] = core['T_cnm_error']
        T_H_errors[i] = core['T_H_error'] * 1000.0
        n_cnms[i] = core['n_cnm']
        n_Hs[i] = core['n_H']
        n_cnm_errors[i] = core['n_cnm_error']
        n_H_errors[i] = core['n_H_error']

    # Make plot
    #plt.close;plt.clf()

    # Create figure instance
    fig = plt.figure(figsize=(3.5, 2.5))
    ax = fig.add_subplot(111)
    c_cycle = myplt.set_color_cycle(4, cmap_limits=(0.0, 0.9))

    #data_list = [stani_temps, stani_tempKs, T_cnms, T_Hs]
    data_list = [Ts_list, Ts_avg_list, T_cnms, T_Hs]
    data_error_list = [
        stani_temp_errors,
        np.array(((5), )), T_cnm_errors, T_H_errors
    ]
    if 1:
        data_names = [
            r'Stanimirovic+14 $n_{\rm s}$', r'Stanimirovic+14 $<n_s>$',
            r'$n_{\rm CNM}$', r'$n_H$'
        ]
    else:
        data_names = [
            r'Stanimirovi$\acute{c}$+14' + '\n' + r'$T_{\rm s}$',
            r'Stanimirovi$\acute{c}$+14' + '\n' + r'$<T_{\rm s}>$',
            r'$T_{\rm CNM}$', r'$T_H$'
        ]

    linestyles = ['--', '-.', ':', '-']

    # Plot MC sim of error?
    include_errors = True

    # Define pressures
    P = 3700.
    P_error = [1200., 1200.]
    P_low = P - P_error[0]
    P_hi = P + P_error[1]

    for i, data in enumerate(data_list):
        data = np.array(data)
        if i < 2:
            include_errors = True
        else:
            include_errors = True

        if include_errors:
            if i == 0:
                #n = P / data
                T = Ts_list
                T_error = Ts_error_list
                n, n_error = myscience.calc_density(
                    T_H=T,
                    pressure=P,
                    pressure_error=P_error[0],
                    T_H_error=T_error,
                    calc_error=True,
                )
            elif i == 1:
                #n = P / data
                T = Ts_avg_list
                T_error = Ts_avg_error_list
                n, n_error = myscience.calc_density(
                    T_H=T,
                    pressure=P,
                    pressure_error=P_error[0],
                    T_H_error=T_error,
                    calc_error=True,
                )
            elif i == 2:
                n = n_cnms
                n_error = n_cnm_errors[:, 0]
                T = T_cnms
                T_error = T_cnm_errors[:, 0]
            elif i == 3:
                n = n_Hs
                n_error = n_H_errors[:, 0]
                T = T_Hs
                T_error = T_H_errors[:, 0]
            if 0:
                n_sim = 100
                alpha = 1.0 / n_sim
                alpha = 0.1
                for j in xrange(n_sim):
                    if 0:
                        error = data_error_list[i]
                        data_sim = data + np.random.normal(scale=error[:, 0])
                    else:
                        pressure = P + np.random.normal(scale=(P - P_low),
                                                        size=data.size)
                        data_sim = pressure / (n + np.random.normal(n_error))

                    x = myplt.plot_cdf(
                        data_sim,
                        ax=ax,
                        plot_kwargs={  #'label': label,
                            'color': c_cycle[i],
                            'alpha': alpha
                        })
            else:
                linestyle = linestyles[i]
                label = data_names[i]
                alpha = 0.3
                nbins = 20
                error = n_error
                data = n
                n_sim = 100000
                mask = (error > data)
                data = data[~mask]
                error = error[~mask]
                if 1:
                    myplt.plot_cdf_confint(data,
                                           data_error=error,
                                           ax=ax,
                                           nsim=n_sim,
                                           nbins=nbins,
                                           bin_limits=[-20, 300],
                                           plot_kwargs_line={'color': c_cycle[i],
                                                             'linestyle': linestyle,
                                                             'label': label,
                                                             'linewidth' : 1.5,
                                                             },
                                           plot_kwargs_fill_between=\
                                                   {'color': c_cycle[i],
                                                    'alpha': alpha,
                                                    'linewidth': 0,
                                                    },
                                           )
        #if i < 2:
        if 0:
            x = myplt.plot_cdf(data[data > 0],
                               ax=ax,
                               plot_kwargs={
                                   'label': data_names[i],
                                   'color': c_cycle[i],
                                   'linestyle': linestyles[i],
                                   'linewidth': 2,
                                   'zorder': 1000
                               })
        else:
            if 0:
                x = myplt.plot(
                    (0, 0),
                    ax=ax,
                    plot_kwargs={
                        'label': data_names[i],
                        'color': c_cycle[i],
                        'linestyle': linestyles[i]
                    })

    ax.legend(loc='best')
    if 1:
        ax.set_xscale('linear')
        ax.set_xlim([-10, 200])
    else:
        ax.set_xscale('log')
        ax.set_xlim([7 * 10**-1, 10**4])
    ax.set_ylim([0, 1])

    ax.set_xlabel(r'Neutral Gas Density [cm$^{-3}$]')
    ax.set_ylabel('Cumulative Distribution')

    #plt.savefig('/d/bip3/ezbc/multicloud/figures/temps/temps_cdf.png')
    plt.savefig('/d/bip3/ezbc/multicloud/figures/temps/density_cdf.pdf')
def plot_dust_histogram(dust_temps, limits=None, filename=None):

    # Import external modules
    import numpy as np
    import matplotlib.pyplot as plt
    import myplotting as myplt
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    # ----------------------
    plt.close;plt.clf()

    font_scale = 9
    params = {
              'figure.figsize': (3.5, 6),
              #'figure.titlesize': font_scale,
             }
    plt.rcParams.update(params)

    myplt.set_color_cycle(num_colors=1, cmap_limits=[0, 0.6])

    # Create figure instance
    fig = plt.figure()

    axes = AxesGrid(fig, (1,1,1),
                    nrows_ncols=(3, 1),
                    ngrids=3,
                    axes_pad=0.1,
                    aspect=False,
                    label_mode='L',
                    share_all=True)


    def hist(data, normalize=True):
        # Derive the histograms
        n_bins = 300
        #bin_edges = np.logspace(-3, 3, num=n_bins, base=base)
        bin_edges = np.linspace(np.min(data), np.max(data),
                                num=n_bins)
        n = np.zeros(n_bins - 1)
        for i in xrange(n_bins - 1):
            bin_count = len(data[(data > bin_edges[i]) & \
                                 (data < bin_edges[i + 1])])
            n[i] = bin_count

        bin_centers = 0.5*(bin_edges[1:] + bin_edges[:-1])

        n = np.append(n, 0)
        bin_centers = np.append(bin_centers,
                bin_centers[-1] + (bin_centers[-1] - bin_centers[-2]))

        if limits is not None:
            bin_size = (bin_centers[-1] - bin_centers[-2])
            while bin_centers[-1] < limits[0][1]:
                print 'end bin:', bin_centers[-1]
                n = np.append(n, 0)
                bin_centers = np.append(bin_centers,
                                        bin_centers[-1] + bin_size)
            while bin_centers[0] > limits[0][0]:
                print ':', bin_centers[0]
                n = np.append(0, n)
                bin_centers = np.append(bin_centers[0] - bin_size,
                                        bin_centers,
                                        )

        # Normalize the bins
        if normalize:
            n /= np.max(n)

        return n, bin_centers

    for i, cloud_name in enumerate(['california', 'perseus', 'taurus']):

        cloud_props = dust_temps[cloud_name]['dust_temps']

        n, bin_centers = hist(cloud_props)

        ax = axes[i]
        ax.locator_params(nbins = 6)

        ax.errorbar(
            bin_centers,
            n,
            #yerr = n**0.5,
            marker = '',
            #label=r'',
            linewidth=1.5,
            color='k',
            drawstyle = 'steps-mid'
        )

        ax.annotate(cloud_name.capitalize(),
                    xytext=(0.96, 0.9),
                    xy=(0.96, 0.9),
                    textcoords='axes fraction',
                    xycoords='axes fraction',
                    size=10,
                    color='k',
                    bbox=dict(boxstyle='square',
                              facecolor='w',
                              alpha=1),
                    horizontalalignment='right',
                    verticalalignment='top',
                    )
        # legend!
        if i == 2:
            ax.legend(loc='upper left')

        # plot limits
        if limits is not None:
            ax.set_xlim(limits[0][0],limits[0][1])
            ax.set_ylim(limits[1][0],limits[1][1])

        ax.set_xlabel(r'$T_{\rm dust}$ [K]')
        ax.set_ylabel('PDF')

    if filename is not None:
        plt.draw()
        plt.savefig(filename,
                    bbox_inches='tight', dpi=100)
def plot_density_cdfs(core_dict, df):

    import myplotting as myplt
    import matplotlib.pyplot as plt
    import mystats
    import myscience

    # load Stanimirovic temps
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_temps.npy'
    stani_temps = np.loadtxt(filename)
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_temp_errors.npy'
    stani_temp_errors = np.loadtxt(filename)
    stani_temp_errors = np.array((stani_temp_errors, stani_temp_errors)).T
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_int_temps.npy'
    stani_tempKs = np.loadtxt(filename)

    # load the dict
    with open('/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
              'stanimirovic14_temps.pickle', 'rb') as f:
        temp_dict = pickle.load(f)

    # concatenate the temps from each cloud
    Ts_list = []
    Ts_error_list = []
    Ts_avg_list = []
    Ts_avg_error_list = []
    for cloud in temp_dict:
        for Ts in temp_dict[cloud]['Ts_list']:
            Ts_list.append(Ts)
        for Ts_error in temp_dict[cloud]['Ts_error_list']:
            Ts_error_list.append(Ts_error)
        for Ts_avg in temp_dict[cloud]['Ts_avg_list']:
        #for Ts_avg in temp_dict[cloud]['Tk_list']:
            Ts_avg_list.append(Ts_avg)
        for Ts_avg_error in temp_dict[cloud]['Ts_avg_error_list']:
        #for Ts_avg_error in temp_dict[cloud]['Tk_error_list']:
            Ts_avg_error_list.append(Ts_avg_error)

    Ts_list = np.array(Ts_list)
    Ts_error_list = np.array(Ts_error_list)
    Ts_avg_list = np.array(Ts_avg_list)
    Ts_avg_error_list = np.array(Ts_avg_error_list)

    print '\nNumber of LOS:', len(Ts_avg_list)

    # collect data
    T_cnms = np.empty(len(core_dict))
    T_Hs = np.empty(len(core_dict))
    T_cnm_errors = np.empty((len(core_dict), 2))
    T_H_errors = np.empty((len(core_dict), 2))
    n_cnms = np.empty(len(core_dict))
    n_Hs = np.empty(len(core_dict))
    n_cnm_errors = np.empty((len(core_dict), 2))
    n_H_errors = np.empty((len(core_dict), 2))

    for i, core_name in enumerate(core_dict):
        core = core_dict[core_name]
        T_cnms[i] = core['T_cnm']
        T_Hs[i] = core['T_H'] * 1000.0
        T_cnm_errors[i] = core['T_cnm_error']
        T_H_errors[i] = core['T_H_error'] * 1000.0
        n_cnms[i] = core['n_cnm']
        n_Hs[i] = core['n_H']
        n_cnm_errors[i] = core['n_cnm_error']
        n_H_errors[i] = core['n_H_error']

    # Make plot
    #plt.close;plt.clf()

    # Create figure instance
    fig = plt.figure(figsize=(3.5, 2.5))
    ax = fig.add_subplot(111)
    c_cycle = myplt.set_color_cycle(4, cmap_limits=(0.0, 0.9))

    #data_list = [stani_temps, stani_tempKs, T_cnms, T_Hs]
    data_list = [Ts_list, Ts_avg_list, T_cnms, T_Hs]
    data_error_list = [stani_temp_errors, np.array(((5),)),
                       T_cnm_errors, T_H_errors]
    if 1:
        data_names = [r'Stanimirovic+14 $n_{\rm s}$',
                      r'Stanimirovic+14 $<n_s>$',
                      r'$n_{\rm CNM}$',
                      r'$n_H$']
    else:
        data_names = [r'Stanimirovi$\acute{c}$+14' + '\n' + r'$T_{\rm s}$',
                      r'Stanimirovi$\acute{c}$+14' + '\n' + r'$<T_{\rm s}>$',
                      r'$T_{\rm CNM}$',
                      r'$T_H$']

    linestyles = ['--', '-.', ':', '-']

    # Plot MC sim of error?
    include_errors = True

    # Define pressures
    P = 3700.
    P_error = [1200., 1200.]
    P_low = P - P_error[0]
    P_hi = P + P_error[1]

    for i, data in enumerate(data_list):
        data = np.array(data)
        if i < 2:
            include_errors = True
        else:
            include_errors = True

        if include_errors:
            if i == 0:
                #n = P / data
                T = Ts_list
                T_error = Ts_error_list
                n, n_error = myscience.calc_density(T_H=T,
                                                    pressure=P,
                                                    pressure_error=P_error[0],
                                                    T_H_error=T_error,
                                                    calc_error=True,
                                                    )
            elif i == 1:
                #n = P / data
                T = Ts_avg_list
                T_error = Ts_avg_error_list
                n, n_error = myscience.calc_density(T_H=T,
                                                    pressure=P,
                                                    pressure_error=P_error[0],
                                                    T_H_error=T_error,
                                                    calc_error=True,
                                                    )
            elif i == 2:
                n = n_cnms
                n_error = n_cnm_errors[:, 0]
                T = T_cnms
                T_error = T_cnm_errors[:, 0]
            elif i == 3:
                n = n_Hs
                n_error = n_H_errors[:, 0]
                T = T_Hs
                T_error = T_H_errors[:, 0]
            if 0:
                n_sim = 100
                alpha = 1.0 / n_sim
                alpha = 0.1
                for j in xrange(n_sim):
                    if 0:
                        error = data_error_list[i]
                        data_sim = data + np.random.normal(scale=error[:, 0])
                    else:
                        pressure = P + np.random.normal(scale=(P - P_low),
                                                        size=data.size)
                        data_sim = pressure / (n + np.random.normal(n_error))

                    x = myplt.plot_cdf(data_sim,
                                       ax=ax,
                                       plot_kwargs={#'label': label,
                                                    'color': c_cycle[i],
                                                    'alpha': alpha})
            else:
                linestyle = linestyles[i]
                label = data_names[i]
                alpha = 0.3
                nbins = 20
                error = n_error
                data = n
                n_sim = 100000
                mask = (error > data)
                data = data[~mask]
                error = error[~mask]
                if 1:
                    myplt.plot_cdf_confint(data,
                                           data_error=error,
                                           ax=ax,
                                           nsim=n_sim,
                                           nbins=nbins,
                                           bin_limits=[-20, 300],
                                           plot_kwargs_line={'color': c_cycle[i],
                                                             'linestyle': linestyle,
                                                             'label': label,
                                                             'linewidth' : 1.5,
                                                             },
                                           plot_kwargs_fill_between=\
                                                   {'color': c_cycle[i],
                                                    'alpha': alpha,
                                                    'linewidth': 0,
                                                    },
                                           )
        #if i < 2:
        if 0:
            x = myplt.plot_cdf(data[data > 0],
                               ax=ax,
                               plot_kwargs={'label': data_names[i],
                                            'color': c_cycle[i],
                                            'linestyle': linestyles[i],
                                            'linewidth': 2,
                                            'zorder': 1000})
        else:
            if 0:
                x = myplt.plot((0,0),
                                ax=ax,
                                plot_kwargs={'label': data_names[i],
                                             'color': c_cycle[i],
                                             'linestyle': linestyles[i]})

    ax.legend(loc='best')
    if 1:
        ax.set_xscale('linear')
        ax.set_xlim([-10, 200])
    else:
        ax.set_xscale('log')
        ax.set_xlim([7*10**-1, 10**4])
    ax.set_ylim([0,1])

    ax.set_xlabel(r'Neutral Gas Density [cm$^{-3}$]')
    ax.set_ylabel('Cumulative Distribution')

    #plt.savefig('/d/bip3/ezbc/multicloud/figures/temps/temps_cdf.png')
    plt.savefig('/d/bip3/ezbc/multicloud/figures/temps/density_cdf.pdf')
def plot_av_vs_beta_grid(plot_dict,
         filename=None, levels=7,
        limits=None, poly_fit=False, contour=True,
        scale=['linear','linear']):

    ''' Plots a heat map of likelihoodelation values as a function of velocity
    width and velocity center.

    Parameters
    ----------
    cloud : cloudpy.Cloud
        If provided, properties taken from cloud.props.


    '''

    # Import external modules
    import numpy as np
    import matplotlib.pyplot as plt
    import myplotting as myplt
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid

    # Set up plot aesthetics
    # ----------------------
    plt.close;plt.clf()

    font_scale = 9
    params = {
              'figure.figsize': (3.6, 8),
              #'figure.titlesize': font_scale,
             }
    plt.rcParams.update(params)

    # Create figure instance
    fig = plt.figure()

    axes = AxesGrid(fig, (1,1,1),
                    nrows_ncols=(3, 1),
                    ngrids=3,
                    axes_pad=0.1,
                    aspect=False,
                    label_mode='L',
                    share_all=True)

    for i, cloud_name in enumerate(plot_dict):
        x = plot_dict[cloud_name]['av']
        y = plot_dict[cloud_name]['beta']

        ax = axes[i]

        if 'log' not in scale:
            ax.locator_params(nbins = 6)

        # Drop the NaNs from the images
        indices = np.where((x == x) &\
                           (y == y)
                           )
        x_nonans = x[indices]
        y_nonans = y[indices]

        ax = axes[i]

        if contour:
            if i == 0:
                if limits is None:
                    xmin = np.min(x_nonans)
                    ymin = np.min(y_nonans)
                    xmax = np.max(x_nonans)
                    ymax = np.max(y_nonans)
                    xscalar = 0.15 * xmax
                    yscalar = 0.15 * ymax
                    limits = [xmin - xscalar, xmax + xscalar,
                              ymin - yscalar, ymax + yscalar]

            contour_range = ((limits[0], limits[1]),
                             (limits[2], limits[3]))

            cmap = myplt.truncate_colormap(plt.cm.binary, 0.2, 1, 1000)

            l1 = myplt.scatter_contour(x_nonans.ravel(),
                                 y_nonans.ravel(),
                                 threshold=2,
                                 log_counts=1,
                                 levels=levels,
                                 ax=ax,
                                 #errors=x_error_nonans.ravel(),
                                 histogram2d_args=dict(bins=40,
                                                       range=contour_range),
                                 plot_args=dict(marker='o',
                                                linestyle='none',
                                                color='black',
                                                alpha=0.3,
                                                markersize=2),
                                 contour_args=dict(
                                                   #cmap=plt.cm.binary,
                                                   cmap=cmap,
                                                   #cmap=cmap,
                                                   ),
                                 )
        else:
            image = ax.errorbar(
                                x_nonans.ravel()[::100],
                                y_nonans.ravel()[::100],
                                yerr=(x_error_nonans.ravel()[::100]),
                                alpha=0.2,
                                color='k',
                                marker='^',
                                ecolor='k',
                                linestyle='None',
                                markersize=3
                                )

        c_cycle = myplt.set_color_cycle(num_colors=2, cmap_limits=[0.5, 0.7])

        if poly_fit:
            from scipy.optimize import curve_fit

            p = np.polyfit(x_nonans, y_nonans, 1)

            x_fit = np.linspace(-10, 100, 100)
            y_poly_fit = p[0] * x_fit + p[1]
            ax.plot(x_fit,
                    y_poly_fit,
                    color=c_cycle[1],
                    linestyle='-',
                    linewidth=2,
                    label=\
                        'Polynomial fit: \n' + \
                        r'$\beta$ = {0:.2f}'.format(p[0] * 100.0) + \
                        r'$\frac{{A_V}}{{100 \rm mag}}$ + {0:.2f}'.format(p[1]) + \
                        r'',
                    alpha=0.7,
                    )
        # Annotations
        #anno_xpos = 0.95

        ax.set_xscale(scale[0], nonposx = 'clip')
        ax.set_yscale(scale[1], nonposy = 'clip')

        ax.set_xlim(limits[0],limits[1])
        ax.set_ylim(limits[2],limits[3])

        # Adjust asthetics
        ax.set_ylabel(r'$\beta$')
        ax.set_xlabel(r'$A_V$ [mag]')

        if 1:
            loc = 'lower right'
        elif i == 0:
            loc = 'upper left'
        else:
            loc = 'lower left'

        ax.legend(loc=loc)

        ax.annotate(cloud_name.capitalize(),
                    #xytext=(0.96, 0.9),
                    xy=(0.96, 0.96),
                    textcoords='axes fraction',
                    xycoords='axes fraction',
                    size=10,
                    color='k',
                    bbox=dict(boxstyle='square',
                              facecolor='w',
                              alpha=1),
                    horizontalalignment='right',
                    verticalalignment='top',
                    )

    if filename is not None:
        plt.draw()
        plt.savefig(filename, bbox_inches='tight', dpi=400)
def plot_planck_vs_2mass(av_k09, av_pl, filename=None, av_error=None,
        contour_plot=True, levels=10, plot_median=True, limits=None,
        labels=['',''], scale=('linear','linear'), title = '',
        fit_labels=['',''], gridsize=(100,100),):

    # import external modules
    import numpy as np
    import math
    import matplotlib.pyplot as plt
    import matplotlib
    from matplotlib import cm
    from astroML.plotting import scatter_contour
    from mpl_toolkits.axes_grid1.axes_grid import AxesGrid
    import myplotting as myplt

    # set up plot aesthetics
    # ----------------------
    plt.close;plt.clf()

    # color map
    myplt.set_color_cycle(num_colors=3)

    # Create figure instance
    fig = plt.figure(figsize=(3.6, 3.6))

    axes = AxesGrid(fig, (1,1,1),
                 nrows_ncols=(1, 1),
                 ngrids=1,
                 axes_pad=0.25,
                 aspect=False,
                 label_mode='L',
                 share_all=True,
                 #cbar_mode='single',
                 cbar_pad=0.1,
                 cbar_size=0.2,
                 )

    # Drop the NaNs from the images
    if type(av_error) is float or av_error is None:
        indices = np.where((av_pl == av_pl) &\
                           (av_k09 == av_k09)
                           )

    av_pl = av_pl[indices]
    av_k09 = av_k09[indices]

    # Create plot
    ax = axes[0]

    if limits is None:
        xmin = np.min(av_k09)
        ymin = np.min(av_k09)
        xmax = np.max(av_pl)
        ymax = np.max(av_pl)
        xscalar = 0.15 * xmax
        yscalar = 0.15 * ymax
        limits = [xmin - xscalar, xmax + xscalar,
                  ymin - yscalar, ymax + yscalar]

    if contour_plot:

        contour_range = ((limits[0], limits[1]),
                         (limits[2], limits[3]))

        cmap = myplt.truncate_colormap(plt.cm.binary, 0.2, 1, 1000)

        l1 = myplt.scatter_contour(av_k09,
                             av_pl,
                             threshold=3,
                             log_counts=1,
                             levels=levels,
                             ax=ax,
                             histogram2d_args=dict(bins=30,
                                                   range=contour_range),
                             plot_args=dict(marker='o',
                                            linestyle='none',
                                            color='black',
                                            alpha=0.3,
                                            markersize=2),
                             contour_args=dict(
                                               #cmap=plt.cm.binary,
                                               cmap=cmap,
                                               #cmap=cmap,
                                               ),
                             )

    else:
        image = ax.errorbar(nhi_nonans.ravel(),
                av_nonans.ravel(),
                yerr=(av_error_nonans.ravel()),
                alpha=0.2,
                color='k',
                marker='^',
                ecolor='k',
                linestyle='None',
                markersize=3
                )

    # Plot sensitivies
    #av_limit = np.median(av_errors[0])
    #ax.axvline(av_limit, color='k', linestyle='--')

    # Plot 1 to 1 pline
    if 1:
        x_fit = np.linspace(-5, 200, 1000)
        p, V = \
                np.polyfit(av_k09, av_pl, deg=1,
                           #w=np.abs(1.0/av_error_nonans.ravel()),
                           cov=True
                           )

        y_poly_fit = p[0] * x_fit + p[1]
    if 1:
        ax.plot(x_fit,
                y_poly_fit,
                color='r',
                linestyle='dashed',
                linewidth=2,
                label=\
                    'Poly fit: \n' + \
                    fit_labels[0] + ' = ' + '{0:.1f}'.format(p[0]) + \
                    r'$\times$ ' + fit_labels[1] + \
                    ' + {0:.1f} mag'.format(p[1]),
                alpha=0.7,
                )
    if 0:
        from scipy.interpolate import UnivariateSpline

        spl = UnivariateSpline(av_k09, av_pl)
        ax.plot(x_fit, spl(x_fit), linewidth=3, alpha=0.5)


    if 0:
        print('Bootstrapping...')
        # bootstrap conf intervals
        import scipy as sp
        bootindex = sp.random.random_integers
        nboot = 20
        x_fit = av_k09
        y_fit = p[0] * x_fit  + p[1]
        r = av_pl - y_fit
        for i in xrange(nboot): # loop over n bootstrap samples from the resids
            pc = sp.polyfit(av_k09,  y_fit + r[bootindex(0, len(r)-1, len(r))], 1)
            ax.plot(x_fit, sp.polyval(pc,x_fit), 'k-', linewidth=2, alpha=1.0/float(nboot))


    # Annotations
    anno_xpos = 0.95

    ax.set_xscale(scale[0], nonposx = 'clip')
    ax.set_yscale(scale[1], nonposy = 'clip')

    ax.set_xlim(limits[0],limits[1])
    ax.set_ylim(limits[2],limits[3])

    # Adjust asthetics
    #ax.set_xlabel(r'$A_{V,{\rm K+09}}$ [mag]')
    #ax.set_ylabel(r'$A_{V,{\rm Planck}}$ [mag]')
    ax.set_xlabel(labels[0])
    ax.set_ylabel(labels[1])
    ax.set_title(title)
    ax.legend(loc='best')

    if filename is not None:
        plt.savefig(filename)
示例#11
0
def plot_phi_cnm_vs_gdist(cloud_dict, limits=None, savedir='./', filename=None,
        show=True, scale=['linear', 'linear'], title='', core_names=''):

    # Import external modules
    import numpy as np
    import math
    import pyfits as pf
    import matplotlib.pyplot as plt
    import matplotlib
    import myplotting as myplt
    from mpl_toolkits.axes_grid1 import ImageGrid

    # Set up plot aesthetics
    # ----------------------
    plt.close;plt.clf()

    # Create figure instance
    fig = plt.figure()

    # Create plot
    ax = fig.add_subplot(111)

    color_cycle = myplt.set_color_cycle(num_colors=3)
    markers = ['^', 's', 'o', 'd', 'x']

    for i, cloud in enumerate(cloud_dict):

        glats = []
        phi_cnms = []
        phi_cnm_errors = []
        T_cnms = []
        T_cnm_errors = []
        core_plot_count = 0

        for j, core in enumerate(cloud_dict[cloud]['cores']):
            core_dict = cloud_dict[cloud]['cores'][core]
            glat = core_dict['center_wcs']['gal'][1]
            D = cloud_dict[cloud]['distance']

            try:
                phi_cnm = core_dict['krumholz_results']['phi_cnm']
                phi_cnm_error = core_dict['krumholz_results']['phi_cnm_error']
                T_cnm = core_dict['krumholz_results']['T_cnm']
                T_cnm_error = np.array(core_dict['krumholz_results']['T_cnm_error'])
                T_cnm_error = np.copy((T_cnm_error,)).T
                phi_cnm_error = np.copy((phi_cnm_error,)).T

                if core_plot_count == 0:
                    label = cloud.capitalize()
                else:
                    label = None


                # Height of sun above galactic plane = 10.0 pc
                # see
                # http://ezbc.me/research/2015/03/23/Adding-More-Cores/
                # for more info
                gdist = D * np.sin(np.deg2rad(glat)) - 10.0

                image = ax.errorbar(
                                phi_cnm,
                                gdist,
                                xerr=phi_cnm_error,
                                alpha=0.8,
                                color=color_cycle[i],
                                marker=markers[i],
                                ecolor=color_cycle[i],
                                linestyle='none',
                                markersize=4,
                                label=label,
                                )
                core_plot_count += 1

            except KeyError:
                pass

    ax.set_xscale(scale[0], nonposx = 'clip')
    ax.set_yscale(scale[1], nonposy = 'clip')

    if limits is not None:
        ax.set_xlim(limits[0],limits[1])
        ax.set_ylim(limits[2],limits[3])

    # Adjust asthetics
    ax.set_xlabel(r'$\phi_{\rm CNM}$ [K]',)
    ax.set_ylabel(r'Distance from Galactic Plane [pc]',)

    ax.legend(loc='best', numpoints=1)

    if filename is not None:
        plt.savefig(savedir + filename, bbox_inches='tight')
def plot_cdfs(core_dict, df):

    import myplotting as myplt
    import matplotlib.pyplot as plt
    import mystats


    # load Stanimirovic temps
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_temps.npy'
    stani_temps = np.loadtxt(filename)
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_temp_errors.npy'
    stani_temp_errors = np.loadtxt(filename)
    stani_temp_errors = np.array((stani_temp_errors, stani_temp_errors)).T
    filename = \
            '/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
            'stanimirovic14_int_temps.npy'
    stani_tempKs = np.loadtxt(filename)

    # load the dict
    with open('/d/bip3/ezbc/multicloud/data/python_output/tables/' + \
              'stanimirovic14_temps.pickle', 'rb') as f:
        temp_dict = pickle.load(f)

    # concatenate the temps from each cloud
    Ts_list = []
    Ts_avg_list = []
    for cloud in temp_dict:
        for Ts in temp_dict[cloud]['Ts_list']:
            Ts_list.append(Ts)
        for Ts_avg in temp_dict[cloud]['Ts_avg_list']:
            Ts_avg_list.append(Ts_avg)

    # collect data
    T_cnms = np.empty(len(core_dict))
    T_Hs = np.empty(len(core_dict))
    T_cnm_errors = np.empty((len(core_dict), 2))
    T_H_errors = np.empty((len(core_dict), 2))
    n_cnms = np.empty(len(core_dict))
    n_Hs = np.empty(len(core_dict))
    n_cnm_errors = np.empty((len(core_dict), 2))
    n_H_errors = np.empty((len(core_dict), 2))

    for i, core_name in enumerate(core_dict):
        core = core_dict[core_name]
        T_cnms[i] = core['T_cnm']
        T_Hs[i] = core['T_H'] * 1000.0
        T_cnm_errors[i] = core['T_cnm_error']
        T_H_errors[i] = core['T_H_error'] * 1000.0
        n_cnms[i] = core['n_cnm']
        n_Hs[i] = core['n_H']
        n_cnm_errors[i] = core['n_cnm_error']
        n_H_errors[i] = core['n_H_error']

    # Make plot
    plt.close;plt.clf()

    # Create figure instance
    fig = plt.figure(figsize=(3.5, 3.5))
    ax = fig.add_subplot(111)
    c_cycle = myplt.set_color_cycle(4, cmap_limits=(0.0, 0.9))

    #data_list = [stani_temps, stani_tempKs, T_cnms, T_Hs]
    data_list = [Ts_list, Ts_avg_list, T_cnms, T_Hs]
    data_error_list = [stani_temp_errors, np.array(((5),)),
                       T_cnm_errors, T_H_errors]
    if 0:
        data_names = [r'Stanimirovic+14 $T_{\rm spin}$',
                      r'Stanimirovic+14 $T_K$',
                      r'$T_{\rm CNM}$',
                      r'$T_H$']
    else:
        data_names = ['Stanimirovic+14\n' + r'$T_{\rm s}$',
                      'Stanimirovic+14\n' + r'$<T_{\rm s}>$',
                      r'$T_{\rm CNM}$',
                      r'$T_H$']
    linestyles = ['--', '-.', '-', '-']

    # Plot MC sim of error?
    include_errors = True
    P_low = 1960
    P = 3000.
    P_hi = 4810

    for i, data in enumerate(data_list):
        data = np.array(data)
        if i < 2:
            include_errors = False
        else:
            include_errors = True
        if include_errors:
            if i < 2:
                n = 3000 / data
            elif i == 2:
                n = n_cnms
                n_error = n_cnm_errors[:, 0]
            elif i ==3:
                n = n_Hs
                n_error = n_H_errors[:, 0]

            n_sim = 1000
            alpha = 1.0 / n_sim
            alpha = 0.005
            for j in xrange(n_sim):
                if 0:
                    error = data_error_list[i]
                    data_sim = data + np.random.normal(scale=error[:, 0])
                else:
                    #pressure = np.random.uniform(P_low, P_hi, size=data.size)
                    pressure = P + np.random.normal(scale=(P - P_low),
                                                    size=data.size)
                    data_sim = pressure / (n + np.random.normal(n_error))

                x = myplt.plot_cdf(data_sim,
                                   ax=ax,
                                   plot_kwargs={#'label': label,
                                                'color': c_cycle[i],
                                                'alpha': alpha})
        if i < 2:
            x = myplt.plot_cdf(data,
                               ax=ax,
                               plot_kwargs={'label': data_names[i],
                                            'color': c_cycle[i],
                                            'linestyle': linestyles[i],
                                            'linewidth': 2,
                                            'zorder': 1000})
        else:
            x = myplt.plot_cdf((0,0),
                               ax=ax,
                               plot_kwargs={'label': data_names[i],
                                            'color': c_cycle[i],
                                            'linestyle': linestyles[i]})

        if 0:
            sort_indices = np.argsort(data)
            data_error = data_error_list[i][sort_indices]
            data_low = data - data_error[:, 0]
            data_hi = data + data_error[:, 1]

            cdf_low = mystats.calc_cdf(data_low)
            cdf_hi = mystats.calc_cdf(data_hi)

        if 0:
            ax.fill_between(x,
                            cdf_hi,
                            cdf_low,
                            #where=where,
                            facecolor=c_cycle[i],
                            edgecolor='none',
                            alpha=0.3,
                            interpolate=True,
                            zorder=0,
                            )

    ax.legend(loc='best')
    ax.set_xscale('log')
    ax.set_xlim([0, 10**4])
    ax.set_ylim([0,1])

    plt.savefig('/d/bip3/ezbc/multicloud/figures/temps/temps_cdf.png')