Repository navigation
Expand file tree
/
Copy pathvalidate
More file actions
executable file
·138 lines (109 loc) · 5.4 KB
/
Copy pathvalidate
File metadata and controls
executable file
·138 lines (109 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/bin/env python2
#
# Copyright (c) 2018 Jonathan Weyn <jweyn@uw.edu>
#
# See the file LICENSE for your rights.
#
"""
Perform cross-validation of the MOS-X model for a range of dates specified in the config.
"""
import mosx
import os
import sys
import numpy as np
from optparse import OptionParser
from datetime import datetime
import pickle
# Suppress warnings
import warnings
warnings.filterwarnings("ignore")
def get_command_options():
parser = OptionParser()
parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', default=False,
help='Overwrite any existing BUFR, obs, and verification files')
parser.add_option('-t', '--naive-rain-correction', dest='tune_rain', action='store_true', default=False,
help='Use the raw precipitation from GFS/NAM to override or average with MOS-X')
parser.add_option('-r', '--rain-post-average', dest='avg_rain', action='store_true', default=False,
help='If using a RainTuningEstimator, this will average the raw estimation from an ensemble'
'with that of the rain tuning post-processor')
parser.add_option('-w', '--write', dest='write_flag', action='store_true', default=False, help='Write a CSV file')
default_file = './MOSX_CV.csv'
parser.add_option('-f', '--write-file', dest='write_file', action='store', type='string', default=default_file,
help=('If -w is enabled, write to this file (default %s)' % default_file))
(opts, args) = parser.parse_args()
return opts, args
# Figure out the date
options, arguments = get_command_options()
overwrite, write_flag, write_file = options.overwrite, options.write_flag, options.write_file
try:
config_file = arguments[0]
except IndexError:
print('Required argument (config file) not provided.')
sys.exit(1)
config = mosx.util.get_config(config_file)
cycle = '18'
start_date = datetime.strptime(config['Validate']['start_date'], '%Y%m%d')
end_date = datetime.strptime(config['Validate']['end_date'], '%Y%m%d')
# Override the INFILE values
new_start_date = datetime.strftime(start_date, '%Y%m%d')
new_end_date = datetime.strftime(end_date, '%Y%m%d')
config['data_start_date'] = new_start_date
config['data_end_date'] = new_end_date
# Retrieve data
bufr_file = '%s/%s_CV_%s_bufr.pkl' % (config['SITE_ROOT'], config['station_id'], new_end_date)
print('\n--- MOS-X validate: retrieving BUFR data...\n')
if os.path.isfile(bufr_file) and not overwrite:
print('Using existing BUFR file %s' % bufr_file)
print('If issues occur, delete this file and try again')
else:
print('Using model cycle %sZ' % cycle)
mosx.bufr.bufr(config, bufr_file, cycle=cycle)
obs_file = '%s/%s_CV_%s_obs.pkl' % (config['SITE_ROOT'], config['station_id'], new_end_date)
print('\n--- MOS-X validate: retrieving OBS data...\n')
if os.path.isfile(obs_file) and not overwrite:
print('Using existing obs file %s' % obs_file)
print('If issues occur, delete this file and try again')
else:
mosx.obs.obs(config, obs_file, use_nan_sounding=False)
verif_file = '%s/%s_CV_%s_verif.pkl' % (config['SITE_ROOT'], config['station_id'], new_end_date)
print('\n--- MOS-X validate: retrieving VERIF data...\n')
if os.path.isfile(verif_file) and not overwrite:
print('Using existing verif file %s' % verif_file)
print('If issues occur, delete this file and try again')
else:
mosx.verification.verification(config, verif_file, use_climo=config['Obs']['use_climo_wind'],
use_cf6=config['Obs']['use_climo_wind'])
with open(verif_file, 'rb') as handle:
verif = pickle.load(handle)
# Format data
predictor_file = '%s/%s_CV_%s_predictors.pkl' % (config['SITE_ROOT'], config['station_id'], new_end_date)
print('\n--- MOS-X validate: formatting predictor data...\n')
all_dates = mosx.model.format_predictors(config, bufr_file, obs_file, verif_file, predictor_file,
return_dates=True)
# Make a prediction!
predicted = mosx.model.predict(config, predictor_file,naive_rain_correction=options.tune_rain)
if options.avg_rain:
print('Using average of raw and rain-tuned precipitation forecasts')
no_tuned_predictions = mosx.model.predict(config, predictor_file, naive_rain_correction=options.tune_rain,
rain_tuning=False)
predicted = np.mean([predicted, no_tuned_predictions], axis=0)
# Print forecasts!
print("\nRain forecast type: '%s'" % config['Model']['rain_forecast_type'])
print('\nDay,verification,forecast')
for day in range(len(all_dates)):
date = all_dates[day]
day_verif = [verif[date][v] for v in ['Tmax', 'Tmin', 'Wind', 'Rain']]
verif_str = '%0.0f/%0.0f/%0.0f/%0.2f' % tuple(day_verif)
fcst_str = '%0.0f/%0.0f/%0.0f/%0.2f' % tuple(predicted[day, :4])
print('%s,%s,%s' % (date, verif_str, fcst_str))
# Write the forecast, if requested
if write_flag:
print('\nForecast write requested, writing to file %s' % write_file)
with open(write_file, 'w') as f:
print >> f, 'date,verification,forecast'
for day in range(len(all_dates)):
date = all_dates[day]
day_verif = [verif[date][v] for v in ['Tmax', 'Tmin', 'Wind', 'Rain']]
verif_str = '%0.0f/%0.0f/%0.0f/%0.2f' % tuple(day_verif)
fcst_str = '%0.0f/%0.0f/%0.0f/%0.2f' % tuple(predicted[day, :4])
print >> f, ('%s,%s,%s' % (date, verif_str, fcst_str))