Esempio n. 1
0
def test_chem_sulfate_formation(data):
    """
    sulfate formation vs water-weighted average pH

    sulfate formed from H2O2 vs sulfate formed from O3
    """

    p = data.variables["p"][-1]
    T = data.variables["T"][-1]
    rhod = data.variables["rhod"][-1]

    # water weighted average pH at the end of the simulation
    r3     = data.variables["radii_m3"][-1,:]
    n_H    = data.variables["chem_H"][-1,:] / cm.M_H

    nom = 0

    for it, val in enumerate(r3):
        if val > 0:
            nom += (n_H[it] / (4./3 * math.pi * val * 1e3)) * val
    den  = np.sum(r3[:])                      # to liters

    pH  = -1 * np.log10(nom / den)

    print " "
    print " "
    print "water weighted average pH = ", pH, " vs 4.82-4.85 from size resolved models "

    s6_ini = data.variables["chemd_S_VI"][0, :]
    s6_end = data.variables["chemd_S_VI"][-1, :]

    sulf_ppt = fn.mix_ratio_to_mole_frac((np.sum(s6_end) - np.sum(s6_ini)), p, cm.M_H2SO4, T, rhod) * 1e12
   
    print " "
    print "sulfate formation (ppt) = ", sulf_ppt, " vs 170-180 from size resolved models"

    ini_O3   = data.variables["O3_g"][0] / cm.M_O3 + \
               data.variables["chemd_O3_a"][0, :].sum() / cm.M_O3

    ini_H2O2 = data.variables["H2O2_g"][0] / cm.M_H2O2 + \
               data.variables["chemd_H2O2_a"][0, :].sum() / cm.M_H2O2


    end_O3   = data.variables["O3_g"][-1] / cm.M_O3 + \
               data.variables["chemd_O3_a"][-1, :].sum() / cm.M_O3

    end_H2O2 = data.variables["H2O2_g"][-1] / cm.M_H2O2 + \
               data.variables["chemd_H2O2_a"][-1, :].sum() / cm.M_H2O2

    sulf_ppt_H2O2 = fn.mix_ratio_to_mole_frac((np.sum(ini_H2O2) - np.sum(end_H2O2)) * cm.M_H2SO4, p, cm.M_H2SO4, T, rhod) * 1e12
    sulf_ppt_O3   = fn.mix_ratio_to_mole_frac((np.sum(ini_O3) - np.sum(end_O3)) * cm.M_H2SO4, p, cm.M_H2SO4, T, rhod) * 1e12

    print " "
    print "sulfate formation from H2O2 (ppt) = ", sulf_ppt_H2O2, " vs 85-105 from size resolved models"
    print "sulfate formation from O3 (ppt)   = ", sulf_ppt_O3, " vs 70-85 from size resolved models"

    print " "
    n_tot = data.variables["acti_m0"][12, 0] * rhod * 1e-6
    print "N of droplets           = ", n_tot, " in cm3"
    print "maximum supersaturation = ", (data.RH_max - 1) * 100, "%"
def test_chem_sulfate_formation(data):
    """
    sulfate formation vs water-weighted average pH

    sulfate formed from H2O2 vs sulfate formed from O3
    """

    p = data.variables["p"][-1]
    T = data.variables["T"][-1]
    rhod = data.variables["rhod"][-1]

    # water weighted average pH at the end of the simulation
    r3     = data.variables["radii_m3"][-1,:]
    n_H    = data.variables["chem_H"][-1,:] / cm.M_H

    nom = 0

    for it, val in enumerate(r3):
        if val > 0:
            nom += (n_H[it] / (4./3 * math.pi * val * 1e3)) * val
    den  = np.sum(r3[:])                      # to liters

    pH  = -1 * np.log10(nom / den)

    print(" ")
    print(" ")
    print("water weighted average pH = ", pH, " vs 4.82-4.85 from size resolved models ")

    s6_ini = data.variables["chemd_S_VI"][0, :]
    s6_end = data.variables["chemd_S_VI"][-1, :]

    sulf_ppt = fn.mix_ratio_to_mole_frac((np.sum(s6_end) - np.sum(s6_ini)), p, cm.M_H2SO4, T, rhod) * 1e12
   
    print(" ")
    print("sulfate formation (ppt) = ", sulf_ppt, " vs 170-180 from size resolved models")

    ini_O3   = data.variables["O3_g"][0] / cm.M_O3 + \
               data.variables["chemd_O3_a"][0, :].sum() / cm.M_O3

    ini_H2O2 = data.variables["H2O2_g"][0] / cm.M_H2O2 + \
               data.variables["chemd_H2O2_a"][0, :].sum() / cm.M_H2O2


    end_O3   = data.variables["O3_g"][-1] / cm.M_O3 + \
               data.variables["chemd_O3_a"][-1, :].sum() / cm.M_O3

    end_H2O2 = data.variables["H2O2_g"][-1] / cm.M_H2O2 + \
               data.variables["chemd_H2O2_a"][-1, :].sum() / cm.M_H2O2

    sulf_ppt_H2O2 = fn.mix_ratio_to_mole_frac((np.sum(ini_H2O2) - np.sum(end_H2O2)) * cm.M_H2SO4, p, cm.M_H2SO4, T, rhod) * 1e12
    sulf_ppt_O3   = fn.mix_ratio_to_mole_frac((np.sum(ini_O3) - np.sum(end_O3)) * cm.M_H2SO4, p, cm.M_H2SO4, T, rhod) * 1e12

    print(" ")
    print("sulfate formation from H2O2 (ppt) = ", sulf_ppt_H2O2, " vs 85-105 from size resolved models")
    print("sulfate formation from O3 (ppt)   = ", sulf_ppt_O3, " vs 70-85 from size resolved models")

    print(" ")
    n_tot = data.variables["acti_m0"][12, 0] * rhod * 1e-6
    print("N of droplets           = ", n_tot, " in cm3")
    print("maximum supersaturation = ", (data.RH_max - 1) * 100, "%")
Esempio n. 3
0
def plot_fig1(data, output_folder = '', output_title = ''):

    import matplotlib
    matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
    import matplotlib.pyplot as plt

    # plot settings
    plt.figure(1)
    plt.rcParams.update({'font.size': 8})
    plots = []
    for i in range(3):
      plots.append(plt.subplot(1,3,i+1))
                             #(rows, columns, number)
    for ax in plots:
      ax.set_ylabel('t [s]')
      ax.set_ylim([0, 2400])
      ax.set_yticks([0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400])

    #plt.tight_layout()
    spn_idx = 0#4

    # read in y-axis (time)
    t   = data.variables["t"][spn_idx:] - data.variables["t"][spn_idx]

    # calculate lwc
    plots[0].set_xlabel('lwc g/kg dry air')
    plots[0].grid()
    #plots[0].set_xlim([0., 2.5])
    #plots[0].set_xticks([0., 0.5, 1, 1.5, 2, 2.5])
    plots[0].plot(np.sum(data.variables["radii_m3"][spn_idx:], axis=1) * 4. / 3 * math.pi * 998.2 * 1e3, t, "b.-")

    # calculate SO2 gas volume concentration
    p    = data.variables["p"][spn_idx:]
    T    = data.variables["T"][spn_idx:]
    rhod = data.variables["rhod"][spn_idx:]

    plots[1].grid()
    plots[1].set_xlabel('gas vol.conc SO2 [ppb]')
    plots[1].set_xticks([0., 0.05, 0.1, 0.15, 0.2])
    plots[1].set_xticklabels(['0', '0.05', '0.1', '0.15', '0.2'])
    plots[1].set_xlim([0., 0.2])
    tmp1 = fn.mix_ratio_to_mole_frac(data.variables["SO2_g"][spn_idx:], p, cm.M_SO2, T, rhod)
    tmp2 = fn.mix_ratio_to_mole_frac(\
      np.squeeze(data.variables["plt_ch_SO2_a"][spn_idx:]), p, cm.M_SO2_H2O, T, rhod)
    #tmp2 = fn.mix_ratio_to_mole_frac(data.variables["SO2_a"][spn_idx:], p, cm.M_SO2_H2O, T, rhod)
    plots[1].plot((tmp1 + tmp2) * 1e9, t, "g.-")
    #plots[1].plot((tmp2) * 1e9, t, "r.-")
    #plots[1].plot((tmp1) * 1e9, t, "b.-")

    # calculate average pH
    # (weighted with volume of cloud droplets)
    plots[2].set_xlabel('average pH')
    plots[2].grid()
    #plots[2].set_xlim([3.8, 5])
    #plots[2].set_xticks([3.8, 4, 4.2, 4.4, 4.6, 4.8, 5])
 
    r3     = data.variables["radii_m3"][spn_idx:]
    n_H    = data.variables["chem_H"][spn_idx:] / cm.M_H
    nom    = np.zeros(t.shape[0])
    den    = np.zeros(t.shape[0])
    for time in range(t.shape[0]): 
        for it, val in enumerate(r3[time,:]):
            if val > 0:
                 nom[time] += (n_H[time, it] / (4./3 * math.pi * val * 1e3)) * val
        den[time] = np.sum(r3[time,:])                                 # to liters

    pH  = -1 * np.log10(nom / den)
    plots[2].plot(pH, t, "b.-")

    plt.savefig(output_folder + output_title + ".pdf")
Esempio n. 4
0
def plot_fig1(data, output_folder = '', output_title = ''):

    # read in data
    spn_idx = 2 * 5
    t    = data.variables["t"][:] #- data.variables["t"][spn_idx]
    p    = data.variables["p"][:]
    T    = data.variables["T"][:]
    rhod = data.variables["rhod"][:]
    r_v  = data.variables["r_v"][:]
    rho  = fn.rho_calc(T, p, r_v)

    import matplotlib
    matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
    import matplotlib.pyplot as plt

    # plot settings
    fig = plt.figure(figsize=(28,13))
    plt.rcParams.update({'font.size': 30})
    y_labels  = [0,   200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400] #time above CB
    y_labels2 = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6,   0.7, 0.8,   0.9,    1, 1.1,  1.2,  1.3 ] #height above CB

    # calculate lwc
    ax = fig.add_subplot(131)
    ax.set_xlim([0., 2.5])
    ax.set_ylim([200, 2600])
    ax.set_yticks([200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600])
    ax.set_yticklabels(y_labels)

    ax.tick_params(axis='x', pad=15)
    ax.tick_params(axis='y', pad=15)

    ax.set_xlabel('LWC [g/kg]')
    ax.set_ylabel('time above cloud base [s]')

    plt.grid()
    plt.plot(data.variables["acti_m3"][:] * 4./3 * math.pi * 999.5 * 1e3 * rhod / rho, t,"b", lw=4.)

    # calculate SO2 gas volume concentration
    tmp1 = fn.mix_ratio_to_mole_frac(data.variables["SO2_g"][:], p, cm.M_SO2, T, rhod)
    tmp2 = fn.mix_ratio_to_mole_frac(\
      np.squeeze(data.variables["plt_ch_SO2_a"][:]), p, cm.M_SO2_H2O, T, rhod)

    ax = fig.add_subplot(132)
    ax.yaxis.set_major_formatter(plt.NullFormatter())

    ax.set_ylim([200, 2600])
    ax.set_yticks([200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600])
 
    ax.set_xlim([0., 0.2])
    ax.set_xticks([0., 0.05, 0.1, 0.15, 0.2])
    ax.set_xticklabels(['0', '0.05', '0.1', '0.15', '0.2'])

    ax.set_xlabel('$\mathrm{SO_2}$ conc. [ppb]') #gas volume concentration

    plt.grid()
    plt.plot((tmp1 + tmp2) * 1e9 * rhod / rho, t, "b", lw=4.)
    print "total % of SO2 that was converted to H2SO4 = ", (1 - (tmp1[-1] + tmp2[-1]) / (tmp1[0] + tmp2[0])) * 100

    # calculate average pH
    # (weighted with volume of cloud droplets)
    r3     = data.variables["radii_m3"][:]
    n_H    = data.variables["chem_H"][:] / cm.M_H
    nom    = np.zeros(t.shape[0])
    den    = np.zeros(t.shape[0])
    for time in range(t.shape[0]): 
        for it, val in enumerate(r3[time,:]):
            if val > 0:
                 nom[time] += (n_H[time, it] / (4./3 * math.pi * val * 1e3)) * val
        den[time] = np.sum(r3[time,:])                                 # to liters

    pH  = -1 * np.log10(nom / den)

    ax = fig.add_subplot(133)

    ax.set_ylim([200, 2600])
    ax.set_yticks([200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600])
    ax.set_yticklabels(y_labels2)
    ax.yaxis.tick_right()

    ax.set_xlabel('average pH')
    ax.set_ylabel('height above cloud base [km]')
    ax.yaxis.set_label_position("right")

    ax.set_xlim([3.6, 5])
    ax.set_xticks([3.8, 4.0, 4.2, 4.4, 4.6, 4.8, 5])

    plt.grid()
    plt.plot(pH, t, "b", lw=4.)

    plt.savefig(output_folder + output_title + ".pdf")
Esempio n. 5
0
def plot_chem(data, output_folder = '', output_title = ''):

    def dn_calc(m_end, m_beg, M):
        return (m_end - m_beg) / M

    import matplotlib
    matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
    import matplotlib.pyplot as plt

    style = "b."     

    #spn_idx = 30
    spn_idx = 0

    #-----------------------------------------------------------------------
    # plot p, T, RH and dry/wet moments
    plt.figure(1, figsize=(18,14))
    plots = []

    for i in range(9):
      plots.append(plt.subplot(3,3,i+1))
                             #(rows, columns, number)
    plots[0].set_xlabel('p [hPa]')
    plots[1].set_xlabel('T [K]')
    plots[2].set_xlabel('RH')

    plots[3].set_xlabel('m0 1/kg dry air ')
    plots[4].set_xlabel('m1 um/kg dry air ')
    plots[5].set_xlabel('lwc g/kg dry air')

    plots[6].set_xlabel('m0_dry 1/kg dry air ')
    plots[7].set_xlabel('m1_dry um/kg dry air ')
    plots[8].set_xlabel('mass cont ug/kg dry air')

    #plots[7].set_xlim([0.02, 0.04])
    #plots[7].set_xticks([0.02, 0.025, 0.03, 0.035, 0.04])

    for ax in plots:
      ax.set_ylabel('t [s]')

    t = data.variables["t"][spn_idx:]

    plots[0].plot(data.variables["p"][spn_idx:] / 100.   , t, style)
    #plots[0].legend(loc='upper right')
    plots[1].plot(data.variables["T"][spn_idx:]          , t, style)
    plots[2].plot(
      data.variables["RH"][spn_idx:]                     , t, style, 
      [data.variables["RH"][spn_idx:].max()] * t.shape[0], t, style
    )
    plots[3].plot(np.squeeze(data.variables["plt_rw_m0"][spn_idx:]), t, style)
    plots[4].plot(\
        np.squeeze(data.variables["plt_rw_m1"][spn_idx:]) / np.squeeze(data.variables["plt_rw_m0"][spn_idx:]) * 1e6, t, style)
    plots[5].plot(\
        np.squeeze(data.variables["plt_rw_m3"][spn_idx:]) * 4. / 3 * math.pi * 998.2 * 1e3, t, style)
 
    plots[6].plot(np.squeeze(data.variables["plt_rd_m0"][spn_idx:]), t, style)
    plots[7].plot(\
        np.squeeze(data.variables["plt_rd_m1"][spn_idx:]) / np.squeeze(data.variables["plt_rd_m0"][spn_idx:]) * 1e6, t, style)
    plots[8].plot(\
        np.squeeze(data.variables["plt_rd_m3"][spn_idx:]) * 4./ 3 * math.pi * getattr(data, 'chem_rho')  * 1e9, t, style)

    plt.savefig(output_folder + output_title + "stat.pdf")

    #-----------------------------------------------------------------------
    # plot non-dissociating chem species
    plt.figure(2, figsize=(18,14))
    plots = []

    for i in range(6):
      plots.append(plt.subplot(2,3,i+1))
                             #(rows, columns, number)

    plots[0].set_xlabel('n O3g 1/kg dry air') 
    plots[1].set_xlabel('n O3a 1/kg dry air')  
    plots[2].set_xlabel('n O3 - init 1/kg dry air')
  
    plots[3].set_xlabel('n H2O2g 1/kg dry air')
    plots[4].set_xlabel('n H2O2a 1/kg dry air')
    plots[5].set_xlabel('n H2O2 - init 1/kg dry air')

    for ax in plots:
      ax.set_ylabel('t [s]')

    t = data.variables["t"][spn_idx:]

    n_o3g   = data.variables["O3_g"][spn_idx:] / cm.M_O3
    n_o3a   = data.variables["O3_a"][spn_idx:] / cm.M_O3
    n_h2o2g = data.variables["H2O2_g"][spn_idx:] / cm.M_H2O2
    n_h2o2a = data.variables["H2O2_a"][spn_idx:] / cm.M_H2O2

    plots[0].plot(n_o3g, t, style)
    #plots[0].legend(loc='upper right')
    plots[1].plot(n_o3a, t, style)
    plots[2].plot(n_o3g + n_o3a - n_o3g[0] - n_o3a[0], t, style)
    plots[3].plot(n_h2o2g, t, style)
    plots[4].plot(n_h2o2a, t, style)
    plots[5].plot(n_h2o2g + n_h2o2a - n_h2o2g[0] - n_h2o2a[0], t, style)

    plt.savefig(output_folder + output_title + "O3_H2O2.pdf")

    #-----------------------------------------------------------------------
    # plot pH , H+, OH-
    plt.figure(3, figsize=(12,8))
    plots = []

    for i in range(3):
      plots.append(plt.subplot(1,3,i+1))
                             #(rows, columns, number)

    plots[0].set_xlabel('average pH')
    plots[1].set_xlabel('n H  1/kg dry air')
    plots[2].set_xlabel('n OH 1/kg dry air')

    plots[2].ticklabel_format(axis = 'x', style='sci', scilimits=(-2,2))

    for ax in plots:
      ax.set_ylabel('t [s]')

    t   = data.variables["t"][spn_idx:]
    n_H = np.squeeze(data.variables["plt_ch_H"][spn_idx:]) / cm.M_H
    vol = np.squeeze(data.variables["plt_rw_m3"][spn_idx:]) * 4/3. * math.pi
    pH  = -1 * np.log10(n_H / vol / 1e3)
                                    # litres
    plots[0].plot(pH,                                                        t, style)
    plots[1].plot(np.squeeze(data.variables["plt_ch_H"][spn_idx:])  / cm.M_H  , t, style)
    plots[2].plot(cm.K_H2O / np.squeeze(data.variables["plt_ch_H"][spn_idx:]) * vol , t, style)

    plt.tight_layout()
    plt.savefig(output_folder + output_title + "pH.pdf")

    #-----------------------------------------------------------------------
    # plot NH3_g, NH3_a, NH4+ 
    plt.figure(4, figsize=(12,8))
    plots = []

    for i in range(3):
      plots.append(plt.subplot(1,3,i+1))
                             #(rows, columns, number)

    plots[0].set_xlabel('n NH3 g 1/kg dry air')
    plots[1].set_xlabel('n N3 aq 1/kg dry air')
    plots[2].set_xlabel('n - init 1/kg dry air')  
 
    for ax in plots:
      ax.set_ylabel('t [s]')

    t    = data.variables["t"][spn_idx:]
    n_nh3g = data.variables["NH3_g"][spn_idx:] / cm.M_NH3
    n_N3 = np.squeeze(data.variables["plt_ch_NH3_a"][spn_idx:]) / cm.M_NH3_H2O

    plots[0].plot(n_nh3g, t, style)
    plots[1].plot(n_N3, t, style)
      
    plots[2].plot(n_nh3g + n_N3 - n_nh3g[0] - n_N3[0], t, style)

    plt.tight_layout()
    plt.savefig(output_folder + output_title  + "NH3.pdf")

    #-----------------------------------------------------------------------
    # plot HNO3_g, NHO3_a, NO3+ 
    plt.figure(5, figsize=(12,8))
    plots = []

    for i in range(3):
      plots.append(plt.subplot(1,3,i+1))
                             #(rows, columns, number)

    plots[0].set_xlabel('n HNO3 g 1/kg dry air')
    plots[1].set_xlabel('n N5 aq  1/kg dry air')
    plots[2].set_xlabel('n - init 1/kg dry air')  

    for ax in plots:
      ax.set_ylabel('t [s]')

    t   = data.variables["t"][spn_idx:]
    n_hno3g = data.variables["HNO3_g"][spn_idx:] / cm.M_HNO3
    n_N5 = np.squeeze(data.variables["plt_ch_HNO3_a"][spn_idx:]) / cm.M_HNO3
 
    plots[0].plot(n_hno3g, t, style)
    plots[1].plot(n_N5,    t, style)
    plots[2].plot(n_hno3g + n_N5 - n_hno3g[0] - n_N5[0], t, style)

    plt.savefig(output_folder + output_title  + "HNO3.pdf")
 
    #-----------------------------------------------------------------------
    # plot CO2_g, CO2_a, HCO3+, CO3--
    plt.figure(6, figsize=(12,8))
    plots = []

    for i in range(3):
      plots.append(plt.subplot(1,3,i+1))
                             #(rows, columns, number)

    plots[0].set_xlabel('n CO2 g 1/kg dry air')
    plots[1].set_xlabel('n C4 aq 1/kg dry air')
    plots[2].set_xlabel('n - int 1/kg dry air')  
 
    for ax in plots:
      ax.set_ylabel('t [s]')

    t   = data.variables["t"][spn_idx:]
    n_co2g = data.variables["CO2_g"][spn_idx:] / cm.M_CO2
    n_C4 = np.squeeze(data.variables["plt_ch_CO2_a"][spn_idx:]) / cm.M_CO2_H2O
 
    plots[0].plot(n_co2g, t, style)
    plots[1].plot(n_C4, t, style)
    plots[2].plot(n_co2g + n_C4 - n_co2g[0] - n_C4[0],  t, style)

    plt.savefig(output_folder + output_title + "CO2.pdf")
 
    #-----------------------------------------------------------------------
    # plot SO2_g, SO2_a, HSO3+, SO3--, HSO4-, SO4--, S_VI
    plt.figure(7, figsize=(18,14))
    plots = []

    for i in range(5):
      plots.append(plt.subplot(2,3,i+1))
                             #(rows, columns, number)

    plots[0].set_xlabel('n SO2 g [1/kg dry air]')
    plots[1].set_xlabel('n S4 aq  1/kg dry air')

    plots[2].set_xlabel('gas vol.conc SO2 [ppb]')
    plots[2].set_xticks([0., 0.05, 0.1, 0.15, 0.2, 0.25, 0.3])
    plots[2].set_xticklabels(['0', '0.05', '0.1', '0.15', '0.2', '0.25', '0.3'])
    plots[2].set_xlim([0., 0.3])

    plots[3].set_xlabel('n S6 [1 / kg dry air]')
    plots[4].set_xlabel('n - init 1/kg dry air')


    for ax in plots:
      ax.set_ylabel('t [s]')

    t    = data.variables["t"][spn_idx:]
    p    = data.variables["p"][spn_idx:]
    T    = data.variables["T"][spn_idx:]
    rhod = data.variables["rhod"][spn_idx:]
  
    n_so2g = data.variables["SO2_g"][spn_idx:] / cm.M_SO2
    n_S4 = np.squeeze(data.variables["plt_ch_SO2_a"][spn_idx:]) / cm.M_SO2_H2O
    n_S6 = np.squeeze(data.variables["plt_ch_S_VI"][spn_idx:])  / cm.M_H2SO4

    plots[0].plot(n_so2g, t, style)
    plots[1].plot(n_S4, t, style)
    plots[2].plot(fn.mix_ratio_to_mole_frac(data.variables["SO2_g"][:], p, cm.M_SO2, T, rhod) * 1e9, t)
    plots[3].plot(n_S6, t, style)
    plots[4].plot(n_so2g + n_S4 + n_S6 - n_so2g[0] - n_S4[0] - n_S6[0],  t, style)

    plt.savefig(output_folder + output_title + "SO2.pdf")
Esempio n. 6
0
def plot_fig1(data, output_folder='', output_title=''):

    # read in data
    spn_idx = 2 * 5
    t = data.variables["t"][:]  #- data.variables["t"][spn_idx]
    p = data.variables["p"][:]
    T = data.variables["T"][:]
    rhod = data.variables["rhod"][:]
    r_v = data.variables["r_v"][:]
    rho = fn.rho_calc(T, p, r_v)

    import matplotlib
    matplotlib.use(
        'Agg')  # Must be before importing matplotlib.pyplot or pylab!
    import matplotlib.pyplot as plt

    # plot settings
    fig = plt.figure(figsize=(28, 13))
    plt.rcParams.update({'font.size': 30})
    y_labels = [
        0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400
    ]  #time above CB
    y_labels2 = [
        0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3
    ]  #height above CB

    # calculate lwc
    ax = fig.add_subplot(131)
    ax.set_xlim([0., 2.5])
    ax.set_ylim([200, 2600])
    ax.set_yticks([
        200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400,
        2600
    ])
    ax.set_yticklabels(y_labels)

    ax.tick_params(axis='x', pad=15)
    ax.tick_params(axis='y', pad=15)

    ax.set_xlabel('LWC [g/kg]')
    ax.set_ylabel('time above cloud base [s]')

    plt.grid()
    plt.plot(data.variables["acti_m3"][:] * 4. / 3 * math.pi * 999.5 * 1e3 *
             rhod / rho,
             t,
             "b",
             lw=4.)

    # calculate SO2 gas volume concentration
    tmp1 = fn.mix_ratio_to_mole_frac(data.variables["SO2_g"][:], p, cm.M_SO2,
                                     T, rhod)
    tmp2 = fn.mix_ratio_to_mole_frac(\
      np.squeeze(data.variables["plt_ch_SO2_a"][:]), p, cm.M_SO2_H2O, T, rhod)

    ax = fig.add_subplot(132)
    ax.yaxis.set_major_formatter(plt.NullFormatter())

    ax.set_ylim([200, 2600])
    ax.set_yticks([
        200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400,
        2600
    ])

    ax.set_xlim([0., 0.2])
    ax.set_xticks([0., 0.05, 0.1, 0.15, 0.2])
    ax.set_xticklabels(['0', '0.05', '0.1', '0.15', '0.2'])

    ax.set_xlabel('$\mathrm{SO_2}$ conc. [ppb]')  #gas volume concentration

    plt.grid()
    plt.plot((tmp1 + tmp2) * 1e9 * rhod / rho, t, "b", lw=4.)
    print("total % of SO2 that was converted to H2SO4 = ",
          (1 - (tmp1[-1] + tmp2[-1]) / (tmp1[0] + tmp2[0])) * 100)

    # calculate average pH
    # (weighted with volume of cloud droplets)
    r3 = data.variables["radii_m3"][:]
    n_H = data.variables["chem_H"][:] / cm.M_H
    nom = np.zeros(t.shape[0])
    den = np.zeros(t.shape[0])
    for time in range(t.shape[0]):
        for it, val in enumerate(r3[time, :]):
            if val > 0:
                nom[time] += (n_H[time, it] /
                              (4. / 3 * math.pi * val * 1e3)) * val
        den[time] = np.sum(r3[time, :])  # to liters

    pH = -1 * np.log10(nom / den)

    ax = fig.add_subplot(133)

    ax.set_ylim([200, 2600])
    ax.set_yticks([
        200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400,
        2600
    ])
    ax.set_yticklabels(y_labels2)
    ax.yaxis.tick_right()

    ax.set_xlabel('average pH')
    ax.set_ylabel('height above cloud base [km]')
    ax.yaxis.set_label_position("right")

    ax.set_xlim([3.6, 5])
    ax.set_xticks([3.8, 4.0, 4.2, 4.4, 4.6, 4.8, 5])

    plt.grid()
    plt.plot(pH, t, "b", lw=4.)

    plt.savefig(output_folder + output_title + ".pdf")
def data(request):

    # copy options from chem_conditions ...
    p_dict = copy.deepcopy(parcel_dict)

    # ... and modify them for the current test
    p_dict['outfile'] = "test_chem_kreidenweis.nc"

    p_dict['chem_dsl'] = True
    p_dict['chem_dsc'] = True
    p_dict['chem_rct'] = True

    p_dict['outfreq'] = 10 / (p_dict['dt'] * p_dict['w'])

    p_dict['out_bin']  =  p_dict['out_bin'][:-1] + \
      ', "chem"  : {"rght": 1e-4, "left": 1e-6,  "drwt": "wet", "lnli": "log", "nbin": 100, "moms": ["H"]},\
         "radii" : {"rght": 1e-4, "left": 1e-6,  "drwt": "wet", "lnli": "log", "nbin": 100, "moms": [3]},\
         "acti"  : {"rght": 1e-3, "left": 1e-6,  "drwt": "wet", "lnli": "log", "nbin": 1,   "moms": [0]},\
         "chemd" : {"rght": 1e-6, "left": 1e-8,  "drwt": "dry", "lnli": "log", "nbin": 100, "moms": ["S_VI" ]}}'

    # create empty lists for storing simulation results
    sd_list = []
    pow_list = []
    RH_max_list = []
    N_drop_list = []
    pH_list = []
    tot_S_list = []

    # run parcel test for super-droplet numbers between 1 and 1024
    for pw in range(11):
        sd_num = pow(2, pw)

        p_dict['sd_conc'] = sd_num
        pp.pprint(p_dict)

        # run parcel
        parcel(**p_dict)

        # save the simulation results ...
        tmp_data = netcdf.netcdf_file(p_dict['outfile'], "r")

        # ... do the initial analysis ...
        p = tmp_data.variables["p"][-1]
        T = tmp_data.variables["T"][-1]
        rhod = tmp_data.variables["rhod"][-1]
        r3 = tmp_data.variables["radii_m3"][-1, :]
        n_H = tmp_data.variables["chem_H"][-1, :] / cm.M_H

        # water weighted average pH at the end of the simulation:
        nom = 0
        for it, val in enumerate(r3):
            if val > 0:
                nom += (n_H[it] / (4. / 3 * math.pi * val * 1e3)) * val
        den = np.sum(r3[:])  # to liters
        pH = -1 * np.log10(nom / den)

        # total sulfate formation:
        s6_ini = tmp_data.variables["chemd_S_VI"][0, :]
        s6_end = tmp_data.variables["chemd_S_VI"][-1, :]

        sulf_ppt = fn.mix_ratio_to_mole_frac(
            (np.sum(s6_end) - np.sum(s6_ini)), p, cm.M_H2SO4, T, rhod) * 1e12

        # number of droplets at RH = max:
        n_tot = tmp_data.variables["acti_m0"][12, 0] * rhod * 1e-6
        #     ^^ TODO - think of something better
        # maximum supersaturation:
        RH_max = (tmp_data.RH_max - 1) * 100

        # ... save the results ...
        sd_list.append(sd_num)
        pow_list.append(pw)
        RH_max_list.append(RH_max)
        N_drop_list.append(n_tot)
        pH_list.append(pH)
        tot_S_list.append(sulf_ppt)

        # ... and remove the simulation data files
        subprocess.call(["rm", p_dict['outfile']])

    # pack all the data into a dictionary
    data = {}
    data['number of super-droplets'] = sd_list
    data['power of two'] = pow_list
    data['cloud droplet conc. at CB'] = N_drop_list
    data['maximum supersaturation'] = RH_max_list
    data['water weighted average pH'] = pH_list
    data['total sulfate production'] = tot_S_list

    return data