def calc_equil(sst, ft_qv, use_NT=False):
    """Adapted from nicholls_turton.ipynb
       sst, sea surface temperature (K)
       ft_qv, mixed-layer top qv (kg kg^-1)
       use_NT, True or False
       
       outputs data array out_array with equilibrium values:
       ([thetal_m, qt_m, zi, zb, we, LWP, delta_Fr, LTS, dqt])
    """

    run_main(sst, ft_qv, use_NT)

    # grab csv file
    with open('dumpmodel.csv', 'r') as f:
        df_result = pd.read_csv(f)

    # last time step into named tupple
    out = df_result.iloc[-1]
    steady_state = make_tuple(out.to_dict())
    steady_state

    # obtain steady-state values
    dth = steady_state.deltheta
    dqt = steady_state.delqv
    thetal_m = steady_state.theta
    qt_m = steady_state.qv
    h = steady_state.h
    press = tf.find_press(steady_state.h)  #kPa
    thetal_ft = steady_state.theta + dth
    qt_ft = steady_state.qv + dqt
    zb = steady_state.LCL
    zi = steady_state.h
    we = steady_state.went

    # calculate thetal at z = 3000 m (take qt(z = 3000m) = qt(z = h), so delta_qt = dqt)
    gamma = 6e-3
    thetal_3000 = thetal_ft + gamma * (3000 - h)
    LTS = thetal_3000 - steady_state.theta

    # calculate delta_Fr
    delta_Frstar = 82.0  # Wm^-2
    Frlambda = 7.9  # Wm^-2, using with CTL from Gesso
    delta_Fr = delta_Frstar - Frlambda * qt_ft * 1000  # convert qt_ft to g kg^-1

    # calculate LWP
    rho = 1.
    LWP = 0.5 * rho * (zi - zb)**2

    # put all required variables into output array
    out_array = np.array([thetal_m, qt_m, zi, zb, we, LWP, delta_Fr, LTS, dqt])

    return out_array
Esempio n. 2
0
def find_interval(the_func, x, *args):
    """
    starting from a 2% difference, move out from a 
    point until the_func changes sign

    Parameters
    ----------

    the_func : function
               function that returns zero when on root
    
    x : float
        argument to the_func

    *args : tuple
            additional arguments for the_func

    Returns
    -------

    brackets : [left,right]
               left,right  brackets for root 
    """
    if x == 0.:
        dx = 1. / 50.
    else:
        dx = x / 50.

    maxiter = 40
    twosqrt = np.sqrt(2)

    failed = True
    for i in range(maxiter):
        dx = dx * twosqrt
        a = x - dx
        fa = the_func(a, *args)
        b = x + dx
        fb = the_func(b, *args)
        if (fa * fb < 0.):
            failed = False
            break
    if failed:
        #
        # load the debugging information into the BracketError exception as a
        # namedtuple
        #
        extra_info = make_tuple(
            dict(a=a, b=b, fa=fa, fb=fb, x=x, dx=dx, args=args))
        raise BracketError(
            "Couldn't find a suitable range. Providing extra_info",
            extra_info=extra_info)
    return (a, b)
Esempio n. 3
0
def killjobs(args=None):
    """
    kill all processes which contain a string passed from the command line

    Parameters
    ----------

    args: optional -- argparse argument containing  the string
          to search for in args.snip
          if missing then args will be supplied from the command line
    """
    parser = make_parser()
    args = parser.parse_args(args)
    keepit = {}
    keys = ['time', 'name', 'cmdline', 'proc']
    for proc in psutil.process_iter():
        print(f'interating {proc}')
        try:
            the_dict = dict(
                zip(keys,
                    (proc.create_time(), proc.exe(), proc.cmdline(), proc)))
            keepit[proc.pid] = make_tuple(the_dict)
        except (psutil.ZombieProcess, psutil.AccessDenied,
                psutil.NoSuchProcess):
            print('hit exception')
            pass
        except FileNotFoundError:
            print('file not found')
    print('in killjobs.py, looking for {}'.format(args.snip))
    #
    # don't kill this process or the emacs python parser
    #
    proclist = []
    for the_tup in keepit.values():
        string_cmd = ' '.join(the_tup.cmdline)
        if the_tup.name.find(args.snip) > -1 and \
           string_cmd.find('killjobs') == -1 and \
           string_cmd.find('elpy') == -1:
            proclist.append(the_tup)

    proconly = [item.proc for item in proclist]
    print(f'ready to kill {proconly}')
    for item in proconly:
        cmd_string = ' '.join(item.cmdline())
        print('terminating: {}'.format(cmd_string))
    [proc.terminate() for proc in proconly]

    gone, alive = psutil.wait_procs(proconly, timeout=3, callback=on_terminate)

    for p in alive:
        p.kill()
def run_main(sst, ft_qv, use_NT):
    """Adapted from interactive_vaporflux.ipynb
       sst, sea surface temperature (K)
       ft_qv, mixed-layer top qv (kg kg^-1)
       use_NT, True or False
       
       outputs csv and json files with equilibrium values
    """

    dtout = 10.  #minutes
    end_time = 8 * 24.  #hours
    del_time = dtout * 60.  #seconds
    end_time = end_time * 3600.  #seconds
    #sst=297
    D = 5.e-6  #s-1
    U = 7  #m/s
    psfc = 100.  #kPa
    qsfc = tf.qs_tp(sst, psfc)
    ft_intercept = 292  #K
    ft_gamma = 6.e-3  #K/m
    #ft_qv = 2.e-3
    k = 0.2  #entrainment efficiency
    Cd = 1.e-3  #drag coefficient
    tspan = np.arange(0., end_time, del_time)
    vars_init = [285., 400., 8.e-3]  #theta (K), height (m) qv (kg/kg) to start
    the_tup = dict(D=D,
                   U=U,
                   sst=sst,
                   ft_intercept=ft_intercept,
                   ft_gamma=ft_gamma,
                   qsfc=qsfc,
                   ft_qv=ft_qv,
                   k=k,
                   Cd=Cd,
                   radcool=30.,
                   use_NT=use_NT)  # include use_NT
    the_tup = make_tuple(the_tup, 'coeffs')
    output = integrate.odeint(dmixed_vars, vars_init, tspan, (the_tup, ))
    result = pd.DataFrame.from_records(output, columns=['theta', 'h', 'qv'])

    # save time/computation by only doing calculations for the last timestep (equilibrium)
    result['time'] = tspan[-1] / 3600. / 24.  #days
    result['deltheta'] = theta_ft(result['h'].values[-1], ft_intercept,
                                  ft_gamma) - result['theta'].iloc[-1]
    result['delqv'] = ft_qv - result['qv'].iloc[-1]
    result['LCL'] = calc_lcl(result.iloc[-1], psfc)
    result['q_flux_0'] = calc_sfc_qvap_flux(result.iloc[-1], the_tup)
    result['T_flux_0'] = calc_sfc_theta_flux(result.iloc[-1], the_tup)
    result['entflux_theta'] = calc_entflux_theta(result.iloc[-1], the_tup)

    # decide how to calculate entrainment
    the_vars = [
        result['theta'].iloc[-1], result['h'].iloc[-1], result['qv'].iloc[-1]
    ]
    if use_NT:
        result['went'] = calc_went_NT(the_vars, the_tup,
                                      result['deltheta'].iloc[-1],
                                      result['T_flux_0'].iloc[-1],
                                      result['q_flux_0'].iloc[-1])
    else:
        result['went'] = calc_went(result.iloc[-1], the_tup)

    result['entflux_qv'] = calc_entflux_qv(result.iloc[-1], the_tup)

    with open('dumpmodel.csv', 'w') as f:
        result.to_csv(f, index=False)

    return None
Esempio n. 5
0

# In[2]:


df_result.tail()


# ### turn the last timestep values into a named tuple

# In[3]:


out=df_result.iloc[-1]  #final timestep in dataframe
print(out)
steady_state=make_tuple(out.to_dict())


# ### plot the $\theta_l$ and $q_t$  flux profiles at 30 levels

# In[4]:


def flux_prof(z,coeffs):
    Fout=coeffs.Fsfc + (coeffs.Finv - coeffs.Fsfc)*(z/coeffs.zinv)
    return Fout

zvals=np.linspace(0,steady_state.h,30)
coeffs_thetal=make_tuple(dict(Fsfc=steady_state.T_flux_0,Finv=steady_state.entflux_theta,
                       zinv=steady_state.h))
coeffs_qt=make_tuple(dict(Fsfc=steady_state.q_flux_0,Finv=steady_state.entflux_qv,