【shell实现WRF自动化运行】

文章目录

  • 1. 整体流程串起来,手动修改模拟时间start_dt和end_dt
    • run.sh
  • 2. 内部修改 namelist.wps 和 namelist.input
    • createnamelist.sh
  • 3. 日期循环、时间循环
  • 4. wrfout单点单变量数据提取
    • interp.py

1. 整体流程串起来,手动修改模拟时间start_dt和end_dt

run.sh

    export start_dt="yyyy-mm-dd_12:00:00"
    export end_dt="yyyy-mm-dd_17:00:00"
    echo $start_dt
    echo $end_dt
    init_file=${start_dt: 0:4}${start_dt:5:2}${start_dt:8:2}
    echo $init_file
    logdir=/data/log/$start_dt
    mkdir -p $logdir

    echo "run wps"
    cd /data/WPS/
    export outfile=namelist.wps
    sh createnamelist.sh

    rm -rf met_em*
    rm -rf FILE*
    ./link_grib.csh /data/gfs/$init_file/12/*
    time ./ungrib.exe >& log.ungrib
    if [ $? -ne 0 ]; then
        touch $logdir/FAILD
        echo "ungrib FAILD"
        cp log.ungrib $logdir/
    fi
    rm -rf log.metgrid
    time ./metgrid.exe >& log.metgrid
    if [ $? -ne 0 ]; then
        touch $logdir/FAILD
        echo "metgrid FAILD"
        cp metgrid.log $logdir/
    fi

    cd /data/WRF/test/em_real_0/
    echo "create namelist"
    export wrfnamelist=namelist.input
    sh createnamelist.sh
    
    echo "run real"
    rm -rf met_em*
    ln -sf ../../../WPS/met_em* .
    time mpirun -np 48 ./real.exe >& log.real
    if [ $? -ne 0 ]; then
        touch $logdir/FAILD
        exit 1
    else
        tail -n 1 rsl.error.0000
    fi

    echo "start wrf"
    rm -rf wrfout_d01*
    rm -rf wrfout_d02*
    time mpirun -np 48 ./wrf.exe >& log.wrf
    if [ $? -ne 0]; then
        touch $logdir/FAILD
    else
        tail -n 1 rsl.error.0000
    fi
    cd /data/postprocess/
    python interp.py em_real_0 "wrfout_d03_${start_dt}"

2. 内部修改 namelist.wps 和 namelist.input

createnamelist.sh

echo "&share.....
 start_date = '${start_dt}', '${start_dt}', '${start_dt}',
 end_date   = '${end_dt}', '${end_dt}', '${end_dt}',
 ....
 /" > $outfile

3. 日期循环、时间循环


begindate="2022-08-29"
enddate="2022-09-11"
nextdate=${begindate}
echo $begindate
echo $enddate
echo $nextdate

while [ $(date +%s -d "${nextdate}") -le $(date +%s -d "${enddate}") ]
do
    start_dt="${nextdate}_12:00:00"
    end_dt=`date +'%Y-%m-%d_%H:%M:%S' -d "3 day ${nextdate} 17:00:00"`
    echo $start_dt
    echo $end_dt
    nextdate=`date +'%Y-%m-%d' -d "1 day ${nextdate}"`
    这里插入run.sh的内容
done

4. wrfout单点单变量数据提取

interp.py


from __future__ import print_function

from netCDF4 import Dataset
from wrf import getvar, interplevel, ll_to_xy, xy_to_ll
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import sys
import os


class Interp(object):

    def __init__(self, lat, lon, hh):
        self.lat=lat
        self.lon=lon
        self.height=hh

    def main(self, filename):
        self.ncfile = Dataset(filename)
        print(self.ncfile.variables.keys)
        # get time
        self.get_time()
        # extract location
        self.latlon_to_xy()
        return self.get_interpolation()

    def print_lat_lon(self):
        # get size of lat and lon
        nlats, nlons = self.ncfile.dimensions["south_north"].size, self.ncfile.dimensions["west_east"].size
        print(nlats, nlons)

    def get_time(self):
        times=self.ncfile.variables['Times'][:].data
        # change time to string
        # times=nc.num2date(times, 'days since 1891-1-1 00:00:00').data
        timestr=[i.tobytes().decode("utf-8") for i in times]
        self.timestr=self.str_to_dt(timestr)

    def latlon_to_xy(self):
        x_y = ll_to_xy(self.ncfile, self.lat, self.lon)
        self.x, self.y=x_y.data.tolist()

    def str_to_dt(self, data, strtype='%Y-%m-%d_%H:%M:%S'):
        if isinstance(data, list):
            dt=[datetime.strptime(d, strtype) + timedelta(hours=8) for d in data]
        else:
            dt=datetime.strptime(data, strtype) + timedelta(hours=8)
        return dt

    def get_interpolation(self):
        wspd=[]
        wdir=[]
        dts=[]
        for t in range(208, 304):
            # extract values to be interpolated
            uvmet_wspd_wdir = getvar(self.ncfile, "uvmet_wspd_wdir", timeidx=t, units="m s-1", meta=False)
            height = getvar(self.ncfile, "height_agl", timeidx=t, units="m", meta=False)
            p = getvar(self.ncfile, "pressure", timeidx=t, meta=False)

            # compute wind at 85m above ground
            wspd_80m = interplevel(uvmet_wspd_wdir[0], height, self.height, meta=False)
            wdir_80m = interplevel(uvmet_wspd_wdir[1], height, self.height, meta=False)

            wspd.append(wspd_80m[self.x, self.y])
            wdir.append(wdir_80m[self.x, self.y])
            dts.append(self.timestr[t])

        output=pd.DataFrame({'wspd': wspd, 'wdir': wdir}, index=dts)
        return output


if __name__=='__main__':

    case=sys.argv[1]
    filename=sys.argv[2]
    print(case)
    LON=112.20
    LAT=38.50
    HEIGHT=85
    path="../WRF/test/{}/".format(case)
    filename=os.path.join(path, filename)
    ierp=Interp(LAT, LON, HEIGHT)
    data=ierp.main(filename)
    savename="{}/{}/{}.csv".format("results", case, data.index[0].date())
    data.to_csv(savename)
    print('DONE saveing {}'.format(savename))

这里是wrf-python引用https://wrf-python.readthedocs.io/en/latest/

你可能感兴趣的:(python,ssh)