from netCDF4 import Dataset
from datetime import timedelta, datetime
import os
import pandas as pd
from wrf import getvar
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt



def get_para_data(para_name, time_range, file):
para_data = []
for i in time_range:
z = getvar(file, para_name, timeidx=i, meta=False) # meta默认true : cat,false :join
z = z[:, row, col]
para_data.extend(z)
return para_data


def plot_uv(p, u, v, save_path):
time_ids = [0, 3, 6, 9, 12, 15, 18, 21]
plt.figure(figsize=(14, 8))
for k in range(8):
ax = plt.subplot(2, 4, k + 1)
pp = p[time_ids[k] * 30:(time_ids[k] + 1) * 30]
xx = pp * 0
uu = u[time_ids[k] * 30:(time_ids[k] + 1) * 30]
vv = v[time_ids[k] * 30:(time_ids[k] + 1) * 30]
plt.sca(ax)
Q = plt.quiver(xx, pp, uu, vv, units='x', scale=3.5)
plt.quiverkey(Q, 0.25, 1.03, 5, '5 m/s', labelpos='W')
plt.ylim(0, 1500)
plt.xlim(-10, 10)
plt.xticks([0], [""])
plt.text(-8, 150, str(time_ids[k]) + " BJT")
if k in [0, 4]:
plt.ylabel("Height (m)")
plt.tight_layout()
plt.savefig(save_path)
plt.close()


def plot_temp(p, t, save_path):
time_ids = [0, 3, 6, 9, 12, 15, 18, 21]
plt.figure(figsize=(14, 8))
for k in range(8):
ax = plt.subplot(2, 4, k + 1)
pp = p[time_ids[k] * 30:(time_ids[k] + 1) * 30]
tt = t[time_ids[k] * 30:(time_ids[k] + 1) * 30]
plt.sca(ax)
plt.plot(tt, pp, '-ok')
plt.ylim(0, 1500)
plt.xlim(-10, 10)
plt.text(-8, 150, str(time_ids[k]) + " BJT")
if k in [0, 4]:
plt.ylabel("Height (m)")
if k > 3:
plt.xlabel("Temp ($^o$C)")
plt.tight_layout()
plt.savefig(save_path)
plt.close()


if __name__ == '__main__':
# ------------------------------------------显示目录-----------------------------------------------------
nc_dir = r'/home/share/model/CMAQ_new/output/wrfout'
save_dir = r'/home/gzblue/xgx/1205/1220/data'
# -----------------------------------------获取时间信息------------------------------------------------
tomorrow = datetime.now() + timedelta(days=1)
after_tomorrow = datetime.now() + timedelta(days=2)
tomorrow, after_tomorrow = tomorrow.strftime('%Y%m%d'), after_tomorrow.strftime('%Y%m%d')
today = datetime.now().strftime('%Y%m%d')
# print(today,tomorrow,after_tomorrow)
print('Lastest modified time:', today, '!')
# -----------------------------------------获得nc文件路径------------------------------------------------
nc_path = os.path.join(nc_dir, today, [i for i in os.listdir(os.path.join(nc_dir, today)) if 'd03' in i][0])
print(nc_path)
if not os.path.exists(nc_path):
print('Today\'s NC file is not found!')
raise IOError
# ------------------------------------------获得存图路径------------------------------------------------
save_png_dir = os.path.join(save_dir, today)
if not os.path.exists(save_png_dir):
os.makedirs(save_png_dir)
# ------------------------------------------当csv不存在时------------------------------------------------
csv_path = os.path.join(save_png_dir, 'data.csv')
print(csv_path)
if not os.path.exists(csv_path):
data = pd.DataFrame()
file = Dataset(nc_path)
row, col = 268, 144 # 固定点的索引
time_range = list(range(28, 76, 3))
para_names = ['z', 'ua', 'va', 'tc']
for para_name in para_names:
data[para_name] = get_para_data(para_name, time_range, file)
file.close()
data.to_csv(csv_path)
print('CSV is saved!')
# ------------------------------------------读csv画图------------------------------------------------
data = pd.read_csv(csv_path)
data_z = data['z'].values
data_ua = data['ua'].values
data_va = data['va'].values
data_tc = data['tc'].values
save_uv_path = os.path.join(save_png_dir, tomorrow + '_UV_19.png')
save_t_path = os.path.join(save_png_dir, tomorrow + '_T_19.png')
p = data_z[:24 * 30] # 30层
u = data_ua[:24 * 30]
v = data_va[:24 * 30]
t = data_tc[:24 * 30]
plot_uv(p, u, v, save_uv_path)
plot_temp(p, t, save_t_path)
print(tomorrow, 'is OK!')
save_uv_path = os.path.join(save_png_dir, after_tomorrow + '_UV_19.png')
save_t_path = os.path.join(save_png_dir, after_tomorrow + '_T_19.png')
p = data_z[24 * 30:]
u = data_ua[24 * 30:]
v = data_va[24 * 30:]
t = data_tc[24 * 30:]
plot_uv(p, u, v, save_uv_path)
plot_temp(p, t, save_t_path)
print(after_tomorrow, 'is OK!')