/
gapfill_weather_algorithm2.py
1935 lines (1444 loc) · 72.2 KB
/
gapfill_weather_algorithm2.py
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright © 2014-2018 GWHAT Project Contributors
# https://github.com/jnsebgosselin/gwhat
#
# This file is part of GWHAT (Ground-Water Hydrograph Analysis Toolbox).
# Licensed under the terms of the GNU General Public License.
from __future__ import division, unicode_literals
# ---- Standard library imports
import csv
import os
import os.path as osp
from time import strftime
from copy import copy
from time import clock
from itertools import product
# ---- Third party imports
import numpy as np
from xlrd.xldate import xldate_from_date_tuple
from xlrd import xldate_as_tuple
from PyQt5.QtCore import pyqtSignal as QSignal
from PyQt5.QtCore import QObject
# import statsmodels.api as sm
# import statsmodels.regression as sm_reg
# from statsmodels.regression.linear_model import OLS
# from statsmodels.regression.quantile_regression import QuantReg
# ---- Local imports
from gwhat.common.utils import save_content_to_csv
from gwhat.common.utils import calc_dist_from_coord
from gwhat.meteo.weather_viewer import FigWeatherNormals
from gwhat.meteo.gapfill_weather_postprocess import PostProcessErr
import gwhat.meteo.weather_reader as wxrd
from gwhat.meteo.weather_reader import open_weather_datafile
from gwhat import __namever__
# =============================================================================
class GapFillWeather(QObject):
"""
This class manage all that is related to the gap-filling of weather data
records, including reading the data file on the disk.
Parameters
----------
NSTAmax : int
limitDist : float
limitAlt : float
regression_mode : int
add_ETP : bool
full_error_analysis : bool
"""
# Definition of signals that can be used to easily add a Graphical User
# Interface with Qt on top of this algorithm and to start some of the
# method from an independent thread.
ProgBarSignal = QSignal(int)
ConsoleSignal = QSignal(str)
GapFillFinished = QSignal(bool)
def __init__(self, parent=None):
super(GapFillWeather, self).__init__(parent)
# -------------------------------------------------- Required Inputs --
self.time_start = None
self.time_end = None
self.WEATHER = WeatherData()
self.TARGET = TargetStationInfo()
self.outputDir = None
self.inputDir = None
self.STOP = False # Flag used to stop the algorithm from a GUI
self.isParamsValid = False
# ---------------------------------------- Define Parameters Default --
# if *regression_mode* = 1: Ordinary Least Square
# if *regression_mode* = 0: Least Absolute Deviations
# if *add_ETP* is *True*: computes ETP from daily mean temperature
# time series with the function *calculate_ETP* from module *meteo*
# and adds the results to the output datafile.
# if *full_error_analysis* is *True*: a complete analysis of the
# estimation errors is conducted with a cross-validation procedure.
self.NSTAmax = 4
self.limitDist = 100
self.limitAlt = 350
self.regression_mode = 1
self.add_ETP = False
self.full_error_analysis = False
self.leave_one_out = False
# leave_one_out: flag to control if data are removed from the
# dataset in the cross-validation procedure.
self.fig_format = PostProcessErr.SUPPORTED_FIG_FORMATS[0]
self.fig_language = PostProcessErr.SUPPORTED_LANGUAGES[0]
# =========================================================================
# Maximum number of neighboring stations that will be used to fill
# the missing data in the target station
@property
def NSTAmax(self):
return self.__NSTAmax
@NSTAmax.setter
def NSTAmax(self, x):
if type(x) != int or x < 1:
raise ValueError('!WARNING! NSTAmax must be must be an integer'
' with a value greater than 0.')
self.__NSTAmax = x
# =========================================================================
def load_data(self):
# This method scans the input directory for valid weather data files
# and instruct the "WEATHER" instance to load the data from the file
# and to generate a summary. The results are saved in a structured
# numpy array in binary format, so that loading time is improved on
# subsequent runs. Some checks are made to be sure the binary match
# with the current data files in the folder.
if not self.inputDir:
print('Please specify a valid input data file directory.')
return []
if not os.path.exists(self.inputDir):
print('Data Directory path does not exists.')
return []
binfile = os.path.join(self.inputDir, 'fdata.npy')
if not os.path.exists(binfile):
return self.reload_data()
# ---- Scan input folder for changes
# If one of the csv data file contained within the input data directory
# has changed since last time the binary file was created, the
# data will be reloaded from the csv files and a new binary file
# will be generated.
A = np.load(binfile)
fnames = A['fnames']
bmtime = os.path.getmtime(binfile)
count = 0
for f in os.listdir(self.inputDir):
if f.endswith('.csv'):
count += 1
fmtime = os.path.getmtime(os.path.join(self.inputDir, f))
if f not in fnames or fmtime > bmtime:
return self.reload_data()
# Force a reload of the data if some input files were deleted.
if len(fnames) != count:
return self.reload_data()
# ---- Load data from binary ------------------------------------------
print('\nLoading data from binary file :\n')
self.WEATHER.load_from_binary(self.inputDir)
self.WEATHER.generate_summary(self.outputDir)
self.TARGET.index = -1
return self.WEATHER.STANAME
def reload_data(self):
"""
Read the csv files in the input data directory folder, format
the datasets and save the results in a binary file.
"""
paths = []
for f in os.listdir(self.inputDir):
if f.endswith('.csv'):
fname = os.path.join(self.inputDir, f)
paths.append(fname)
n = len(paths)
print('\n%d valid weather data files found in Input folder.' % n)
print('Loading data from csv files...')
self.WEATHER.load_and_format_data(paths)
self.WEATHER.save_to_binary(self.inputDir)
print('Data loaded sucessfully.')
self.WEATHER.generate_summary(self.outputDir)
self.TARGET.index = -1
return self.WEATHER.STANAME
# =========================================================================
def set_target_station(self, index):
# Update information for the target station.
self.TARGET.index = index
self.TARGET.name = self.WEATHER.STANAME[index]
# calculate correlation coefficient between data series of the
# target station and each neighboring station for every
# weather variable
self.TARGET.CORCOEF = compute_correlation_coeff(
self.WEATHER.DATA, index)
# Calculate horizontal distance and altitude difference between
# the target station and each neighboring station.
self.TARGET.HORDIST, self.TARGET.ALTDIFF = \
alt_and_dist_calc(self.WEATHER, index)
def read_summary(self):
return self.WEATHER.read_summary(self.outputDir)
# except:
# print(self.outputDir)
# self.WEATHER.generate_summary(self.outputDir)
# summary = self.WEATHER.read_summary(self.outputDir)
# return summary
# =========================================================================
def fill_data(self):
# This is the main routine that fills the missing data for the target
# station
tstart = clock()
# ------------------------------------------- Assign Local Variables --
# ---- Time Related Variables ---- #
DATE = np.copy(self.WEATHER.DATE)
YEAR, MONTH, DAY = DATE[:, 0], DATE[:, 1], DATE[:, 2]
TIME = np.copy(self.WEATHER.TIME)
index_start = np.where(TIME == self.time_start)[0][0]
index_end = np.where(TIME == self.time_end)[0][0]
# ---- Weather Stations Related Variables ---- #
DATA = np.copy(self.WEATHER.DATA) # Daily Weather Data
VARNAME = np.copy(self.WEATHER.VARNAME) # Weather variable names
STANAME = np.copy(self.WEATHER.STANAME) # Weather station names
CORCOEF = np.copy(self.TARGET.CORCOEF) # Correlation Coefficients
nVAR = len(VARNAME) # Number of weather variables
# ---- Method Parameters ---- #
limitDist = self.limitDist
limitAlt = self.limitAlt
# -------------------------------------------- Target Station Header --
tarStaIndx = self.TARGET.index
target_station_name = self.TARGET.name
target_station_prov = self.WEATHER.PROVINCE[tarStaIndx]
target_station_lat = self.WEATHER.LAT[tarStaIndx]
target_station_lon = self.WEATHER.LON[tarStaIndx]
target_station_alt = self.WEATHER.ALT[tarStaIndx]
target_station_clim = self.WEATHER.ClimateID[tarStaIndx]
# ---------------------------------------------------------------------
msg = 'Data completion for station %s started' % target_station_name
print('--------------------------------------------------')
print(msg)
print('--------------------------------------------------')
self.ConsoleSignal.emit('<font color=black>%s</font>' % msg)
# ------------------------------------------ Init Container Matrices --
# Save the weather data series of the target station in a new
# 2D matrix named <Y2fill>. The NaN values contained in this matrix
# will be filled during the data completion process
# When *full_error_analysis* is activated, an additional empty
# 2D matrix named <YpFULL> is created. This matrix will be completely
# filled with estimated data during the gap-filling process. The
# content of this matrix will be used to produce *.err* file.
Y2fill = np.copy(DATA[:, tarStaIndx, :])
YXmFILL = np.zeros(np.shape(DATA)) * np.nan
log_RMSE = np.zeros(np.shape(Y2fill)) * np.nan
log_Ndat = np.zeros(np.shape(Y2fill)).astype(str)
log_Ndat[:] = 'nan'
if self.full_error_analysis:
print('\n!A full error analysis will be performed!\n')
YpFULL = np.copy(Y2fill) * np.nan
YXmFULL = np.zeros(np.shape(DATA)) * np.nan
# -------------------------------------------- CHECK CUTOFF CRITERIA --
# Remove the neighboring stations that do not respect the distance
# or altitude difference cutoff criteria.
# Note : If cutoff limits are set to a negative number, all stations
# are kept regardless of their distance or altitude difference
# with the target station.
HORDIST = self.TARGET.HORDIST
ALTDIFF = np.abs(self.TARGET.ALTDIFF)
if limitDist > 0:
check_HORDIST = HORDIST < limitDist
else:
check_HORDIST = np.zeros(len(HORDIST)) == 0
if limitAlt > 0:
check_ALTDIFF = ALTDIFF < limitAlt
else:
check_ALTDIFF = np.zeros(len(ALTDIFF)) == 0
check_ALL = check_HORDIST * check_ALTDIFF
index_ALL = np.where(check_ALL == True)[0] # nopep8
# Keeps only the stations that respect all the treshold values
STANAME = STANAME[index_ALL]
DATA = DATA[:, index_ALL, :]
CORCOEF = CORCOEF[:, index_ALL]
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# WARNING : From here on, STANAME has changed. A new index must
# be determined.
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
tarStaIndx = np.where(STANAME == self.TARGET.name)[0][0]
# -------------------------------- Checks Variables With Enough Data --
# NOTE: When a station does not have enough data for a given variable,
# its correlation coefficient is set to NaN in CORCOEF. If all
# the stations have a value of nan in the correlation table for
# a given variable, it means there is not enough data available
# overall to estimate and fill missing data for it.
var2fill = np.sum(~np.isnan(CORCOEF[:, :]), axis=1)
var2fill = np.where(var2fill > 1)[0]
for var in range(nVAR):
if var not in var2fill:
msg = ('!Variable %d/%d won''t be filled because there ' +
'is not enough data!') % (var+1, nVAR)
print(msg)
self.ConsoleSignal.emit('<font color=red>%s</font>' % msg)
# ----------------------------------------------- Init Gap-Fill Loop --
# If some missing data can't be completed because all the neighboring
# stations are empty, a flag is raised and a comment is issued at the
# end of the completion process.
FLAG_nan = False
nbr_nan_total = np.isnan(Y2fill[index_start:index_end+1, var2fill])
nbr_nan_total = np.sum(nbr_nan_total)
# ---- Variable for the progression of the routine ---- #
# *progress_total* and *fill_progress* are used to display the
# progression of the gap-filling procedure on a UI progression bar.
if self.full_error_analysis:
progress_total = np.size(Y2fill[:, var2fill])
else:
progress_total = np.copy(nbr_nan_total)
fill_progress = 0
# ---- Init. variable for .log file ---- #
AVG_RMSE = np.zeros(nVAR).astype('float')
AVG_NSTA = np.zeros(nVAR).astype('float')
# -------------------------------------------------------- FILL LOOP --
# OUTER LOOP: iterates over all the weather variables with enough
# measured data.
for var in var2fill:
print('Data completion for variable %d/%d in progress...' %
(var+1, nVAR))
# ---- Memory Variables ---- #
colm_memory = [] # Column sequence memory matrix
RegCoeff_memory = [] # Regression coefficient memory matrix
RMSE_memory = [] # RMSE memory matrix
Ndat_memory = [] # Nbr. of data used for the regression
# Sort station in descending correlation coefficient order.
# The index of the *target station* is pulled at index 0.
# <Sta_index> refers to the indices of the columns of the matrices
# <DATA>, <STANAME>, and <CORCOEF>.
Sta_index = self.sort_sta_corrcoef(CORCOEF[var, :], tarStaIndx)
# Data for the current weather variable <var> are stored in a
# 2D matrix where the rows are the daily weather data and the
# columns are the weather stations, ordered in descending
# correlation order. The data series of the *target station* is
# contained at j = 0.
YX = np.copy(DATA[:, Sta_index, var])
# Finds rows where data are missing between the date limits
# at the time indexes <index_start> and <index_end>.
row_nan = np.where(np.isnan(YX[:, 0]))[0]
row_nan = row_nan[row_nan >= index_start]
row_nan = row_nan[row_nan <= index_end]
# counter used in the calculation of average RMSE and NSTA values.
it_avg = 0
if self.full_error_analysis:
# All the data of the time series between the specified
# time indexes will be estimated.
row2fill = range(index_start, index_end+1)
else:
row2fill = row_nan
# INNER LOOP: iterates over all the days with missing values.
for row in row2fill:
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# This block of code is used only to stop the gap-filling
# routine from a UI by setting the <STOP> flag attributes to
# *True*.
if self.STOP is True:
msg = ('Completion process for station %s stopped.' %
target_station_name)
print(msg)
self.ConsoleSignal.emit('<font color=red>%s</font>' % msg)
self.STOP = False
self.GapFillFinished.emit(False)
return
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Find neighboring stations with valid entries at
# row <row> in <YX>. The *Target station* is stored at index 0.
#
# WARNING: Note that the target station is not considered in
# the `np.where` call. It will be added back later
# on in the code.
colm = np.where(~np.isnan(YX[row, 1:]))[0]
if np.size(colm) == 0:
# Impossible to fill variable because all neighboring
# stations are empty.
if self.full_error_analysis:
YpFULL[row, var] = np.nan
if row in row_nan:
Y2fill[row, var] = np.nan
FLAG_nan = True
# A warning comment will be issued at the end of the
# the completion process.
else:
# Determines the number of neighboring stations to
# include in the regression model.
NSTA = min(len(colm), self.NSTAmax)
# Remove superflux station from <colm>.
colm = colm[:NSTA]
# Adds back an index 0 at index 0 to include the target
# station and add 1 to the indexes of the neighboring
# stations
colm = colm + 1
colm = np.insert(colm, 0, 0)
# Stores the values of the independent variables
# (neighboring stations) for this row in a new array.
# An intercept term is added if <var> is temperature type
# variable, but not if it is precipitation type.
if var in (0, 1, 2):
X_row = np.hstack((1, YX[row, colm[1:]]))
else:
X_row = YX[row, colm[1:]]
# Elements of the <colm> array are put back to back
# in a single string. For example, a [2, 7, 11] array
# would end up as '020711'. This allow to assign a
# unique number ID to a column combination. Each
# column correspond to a unique weather station.
colm_seq = ''
for i in range(len(colm)):
colm_seq += '%02d' % colm[i]
# A check is made to see if the current combination
# of neighboring stations has been encountered
# previously in the routine. Regression coefficients
# are calculated only once for a given neighboring
# station combination.
if colm_seq not in colm_memory:
# First time this neighboring station combination
# is encountered in the routine, regression
# coefficients are then calculated.
#
# The memory is activated only if the option
# 'full_error_analysis' is not active. Otherwise, the
# memory remains empty and a new MLR model is built
# for each value of the data series.
if self.leave_one_out is False:
colm_memory.append(colm_seq)
# Columns of DATA for the variable VAR are sorted
# in descending correlation coefficient and the
# information is stored in a 2D matrix (The data for
# the target station are included at index j=0).
YXcolm = np.copy(YX)
YXcolm = YXcolm[:, colm]
# Force the value of the target station to a NaN value
# for this row. This should only have an impact when
# the option "full_error_analysis" is activated. This
# is to actually remove the data being estimated from
# the dataset like it should properly be done in a
# cross-validation procedure.
if self.leave_one_out is False:
YXcolm[row, 0] = np.nan
# ---- Removes Rows with NaN ----
# Removes row for which a data is missing in the
# target station data series
YXcolm = YXcolm[~np.isnan(YXcolm[:, 0])]
ntot = np.shape(YXcolm)
# All rows containing at least one nan for the
# neighboring stations are removed
YXcolm = YXcolm[~np.isnan(YXcolm).any(axis=1)]
nreg = np.shape(YXcolm)
Ndat = '%d/%d' % (nreg[0], ntot[0])
# Rows for which precipitation of the target station
# and all the neighboring stations is 0 are removed.
# Only applicable for precipitation, not air
# temperature.
if var == 3:
YXcolm = YXcolm[~(YXcolm == 0).all(axis=1)]
Y = YXcolm[:, 0] # Dependant variable (target)
X = YXcolm[:, 1:] # Independant variables (neighbors)
# Add a unitary array to X for the intercept term if
# variable is a temperature type data.
# (though this was questionned by G. Flerchinger)
if var in (0, 1, 2):
X = np.hstack((np.ones((len(Y), 1)), X))
# ------------------------------- Generate MLR Model --
# print(STANAME[Sta_index[colm]], len(X))
A = self.build_MLR_model(X, Y)
# ------------------------------------- Compute RMSE --
# Calculate a RMSE between the estimated and
# measured values of the target station.
# RMSE with 0 value are not accounted for
# in the calcultation.
Yp = np.dot(A, X.transpose())
RMSE = (Y - Yp)**2 # MAE = np.abs(Y - Yp)
RMSE = RMSE[RMSE != 0] # MAE = MAE[MAE!=0]
RMSE = np.mean(RMSE)**0.5 # MAE = np.mean(MAE)
# ------------------------------------ Add to Memory --
RegCoeff_memory.append(A)
RMSE_memory.append(RMSE)
Ndat_memory.append(Ndat)
else:
# Regression coefficients and RSME are recalled
# from the memory matrices.
index_memory = colm_memory.index(colm_seq)
A = RegCoeff_memory[index_memory]
RMSE = RMSE_memory[index_memory]
Ndat = Ndat_memory[index_memory]
# ----------------------------- MISSING VALUE ESTIMATION --
# Calculate missing value of Y at row <row>.
Y_row = np.dot(A, X_row)
# Limit precipitation based variable to positive values.
# This may happens when there is one or more negative
# regression coefficients in A
if var in (3, 4, 5):
Y_row = max(Y_row, 0)
# ---------------------------------------- STORE RESULTS --
log_RMSE[row, var] = RMSE
log_Ndat[row, var] = Ndat
if self.full_error_analysis:
YpFULL[row, var] = Y_row
# Gets the indexes of the stations that were used for
# estimating the data at <row>. <Sta_index_row> relates
# to the colums of <DATA>, <STANAME>, and <CORCOEF>.
# Note also that the first index corresponds to the
# target station, in other words:
#
# tarStaIndx == Sta_index_row[0]
Sta_index_row = Sta_index[colm]
# Gets the measured value for the target station for
# <var> at <row>.
ym_row = DATA[row, Sta_index_row[0], var]
# There is a need to take into account that a intercept
# term has been added for temperature-like variables.
if var in (0, 1, 2):
YXmFULL[row, Sta_index_row[0], var] = ym_row
YXmFULL[row, Sta_index_row[1:], var] = X_row[1:]
else:
YXmFULL[row, Sta_index_row[0], var] = ym_row
YXmFULL[row, Sta_index_row[1:], var] = X_row
if row in row_nan:
Y2fill[row, var] = Y_row
Sta_index_row = Sta_index[colm]
if var in (0, 1, 2):
YXmFILL[row, Sta_index_row[0], var] = Y_row
YXmFILL[row, Sta_index_row[1:], var] = X_row[1:]
else:
YXmFILL[row, Sta_index_row[0], var] = Y_row
YXmFILL[row, Sta_index_row[1:], var] = X_row
AVG_RMSE[var] += RMSE
AVG_NSTA[var] += NSTA
it_avg += 1
fill_progress += 1.
self.ProgBarSignal.emit(fill_progress/progress_total * 100)
# ----------------- Calculate Estimation Error for this variable --
if it_avg > 0:
AVG_RMSE[var] /= it_avg
AVG_NSTA[var] /= it_avg
else:
AVG_RMSE[var] = np.nan
AVG_NSTA[var] = np.nan
print('Data completion for variable %d/%d completed.' %
(var+1, nVAR))
# --------------------------------------------------- End of Routine --
msg = ('Data completion for station %s completed successfully ' +
'in %0.2f sec.') % (target_station_name, (clock() - tstart))
self.ConsoleSignal.emit('<font color=black>%s</font>' % msg)
print('\n' + msg)
print('Saving data to files...')
print('--------------------------------------------------')
if FLAG_nan:
self.ConsoleSignal.emit(
'<font color=red>WARNING: Some missing data were not ' +
'completed because all neighboring station were empty ' +
'for that period</font>')
# =====================================================================
# WRITE DATA TO FILE
# =====================================================================
# ---- Check dirname ----
# Check if the characters "/" or "\" are present in the station
# name and replace these characters by "-" if applicable.
clean_tarStaName = target_station_name.replace('\\', '_')
clean_tarStaName = clean_tarStaName.replace('/', '_')
folder_name = "%s (%s)" % (clean_tarStaName, target_station_clim)
dirname = os.path.join(self.outputDir, folder_name)
if not os.path.exists(dirname):
os.makedirs(dirname)
# --------------------------------------------------------- Header ----
HEADER = [['Station Name', target_station_name],
['Province', target_station_prov],
['Latitude', target_station_lat],
['Longitude', target_station_lon],
['Elevation', target_station_alt],
['Climate Identifier', target_station_clim],
[],
['Created by', __namever__],
['Created on', strftime("%d/%m/%Y")],
[]]
# ------------------------------------------------------ .log file ----
# Info Data Post-Processing :
XYinfo = self.postprocess_fillinfo(STANAME, YXmFILL, tarStaIndx)
Yname, Ypre = XYinfo[0], XYinfo[1]
Xnames, Xmes = XYinfo[2], XYinfo[3]
Xcount_var, Xcount_tot = XYinfo[4], XYinfo[5]
# Yname: name of the target station
# Ypre: Value predicted with the model for the target station
# Xnames: names of the neighboring station to estimate Ypre
# Xmes: Value of the measured data used to predict Ypre
# Xcount_var: Number of times each neighboring station was used to
# predict Ypre, weather variable wise.
# Xcount_tot: Number of times each neighboring station was used to
# predict Ypre for all variables.
# ---- Gap-Fill Info Summary ----
record_date_start = '%04d/%02d/%02d' % (YEAR[index_start],
MONTH[index_start],
DAY[index_start])
record_date_end = '%04d/%02d/%02d' % (YEAR[index_end],
MONTH[index_end],
DAY[index_end])
fcontent = copy(HEADER)
fcontent.extend([['*** FILL PROCEDURE INFO ***'], []])
if self.regression_mode == True:
fcontent.append(['MLR model', 'Ordinary Least Square'])
elif self.regression_mode == False:
fcontent.append(['MLR model', 'Least Absolute Deviations'])
fcontent.extend([['Precip correction', 'Not Available'],
['Wet days correction', 'Not Available'],
['Max number of stations', str(self.NSTAmax)],
['Cutoff distance (km)', str(limitDist)],
['Cutoff altitude difference (m)', str(limitAlt)],
['Date Start', record_date_start],
['Date End', record_date_end],
[], [],
['*** SUMMARY TABLE ***'],
[],
['CLIMATE VARIABLE', 'TOTAL MISSING',
'TOTAL FILLED', '', 'AVG. NBR STA.', 'AVG. RMSE',
'']])
fcontent[-1].extend(Xnames)
# ---- Missing Data Summary ----
total_nbr_data = index_end - index_start + 1
nbr_fill_total = 0
nbr_nan_total = 0
for var in range(nVAR):
nbr_nan = np.isnan(DATA[index_start:index_end+1, tarStaIndx, var])
nbr_nan = float(np.sum(nbr_nan))
nbr_nan_total += nbr_nan
nbr_nofill = np.isnan(Y2fill[index_start:index_end+1, var])
nbr_nofill = np.sum(nbr_nofill)
nbr_fill = nbr_nan - nbr_nofill
nbr_fill_total += nbr_fill
nan_percent = round(nbr_nan / total_nbr_data * 100, 1)
if nbr_nan != 0:
nofill_percent = round(nbr_nofill / nbr_nan * 100, 1)
fill_percent = round(nbr_fill / nbr_nan * 100, 1)
else:
nofill_percent = 0
fill_percent = 100
nbr_nan = '%d (%0.1f %% of total)' % (nbr_nan, nan_percent)
nbr_nofill = '%d (%0.1f %% of missing)' % (nbr_nofill,
nofill_percent)
nbr_fill_txt = '%d (%0.1f %% of missing)' % (nbr_fill,
fill_percent)
fcontent.append([VARNAME[var], nbr_nan, nbr_fill_txt, '',
'%0.1f' % AVG_NSTA[var],
'%0.2f' % AVG_RMSE[var], ''])
for i in range(len(Xnames)):
if nbr_fill == 0:
pc = 0
else:
pc = Xcount_var[i, var] / float(nbr_fill) * 100
fcontent[-1].append('%d (%0.1f %% of filled)' %
(Xcount_var[i, var], pc))
# ---- Total Missing ----
pc = nbr_nan_total / (total_nbr_data * nVAR) * 100
nbr_nan_total = '%d (%0.1f %% of total)' % (nbr_nan_total, pc)
# ---- Total Filled ----
try:
pc = nbr_fill_total/nbr_nan_total * 100
except TypeError:
pc = 0
nbr_fill_total_txt = '%d (%0.1f %% of missing)' % (nbr_fill_total, pc)
fcontent.extend([[],
['TOTAL', nbr_nan_total, nbr_fill_total_txt,
'', '---', '---', '']])
for i in range(len(Xnames)):
pc = Xcount_tot[i] / nbr_fill_total * 100
text2add = '%d (%0.1f %% of filled)' % (Xcount_tot[i], pc)
fcontent[-1].append(text2add)
# ---- Info Detailed ----
fcontent.extend([[], [],
['*** DETAILED REPORT ***'],
[],
['VARIABLE', 'YEAR', 'MONTH', 'DAY', 'NBR STA.',
'Ndata', 'RMSE', Yname]])
fcontent[-1].extend(Xnames)
for var in var2fill:
for row in range(index_start, index_end+1):
yp = Ypre[row, var]
ym = DATA[row, tarStaIndx, var]
xm = ['' if np.isnan(i) else '%0.1f' % i for i in
Xmes[row, :, var]]
nsta = len(np.where(~np.isnan(Xmes[row, :, var]))[0])
# Write the info only if there is a missing value in
# the data series of the target station.
if np.isnan(ym):
fcontent.append([VARNAME[var],
'%d' % YEAR[row],
'%d' % MONTH[row],
'%d' % DAY[row],
'%d' % nsta,
'%s' % log_Ndat[row, var],
'%0.2f' % log_RMSE[row, var],
'%0.1f' % yp])
fcontent[-1].extend(xm)
# ---- Save File ----
YearStart = str(int(YEAR[index_start]))
YearEnd = str(int(YEAR[index_end]))
fname = '%s (%s)_%s-%s.log' % (clean_tarStaName,
target_station_clim,
YearStart, YearEnd)
output_path = os.path.join(dirname, fname)
self.save_content_to_file(output_path, fcontent)
self.ConsoleSignal.emit(
'<font color=black>Info file saved in %s.</font>' % output_path)
# ------------------------------------------------------ .out file ----
# Prepare Header :
fcontent = copy(HEADER)
fcontent.append(['Year', 'Month', 'Day'])
fcontent[-1].extend(VARNAME)
# Add Data :
for row in range(index_start, index_end+1):
fcontent.append(['%d' % YEAR[row],
'%d' % MONTH[row],
'%d' % DAY[row]])
y = ['%0.1f' % i for i in Y2fill[row, :]]
fcontent[-1].extend(y)
# Save Data :
fname = '%s (%s)_%s-%s.out' % (clean_tarStaName,
target_station_clim,
YearStart, YearEnd)
output_path = os.path.join(dirname, fname)
self.save_content_to_file(output_path, fcontent)
msg = 'Meteo data saved in %s.' % output_path
self.ConsoleSignal.emit('<font color=black>%s</font>' % msg)
# Add ETP to file :
if self.add_ETP:
wxrd.add_PET_to_weather_datafile(output_path)
# Produces Weather Normals Graph :
filename = 'weather_normals.'+self.fig_format
print('Generating %s...' % filename)
wxdset = wxrd.WXDataFrame(output_path)
fig = FigWeatherNormals()
fig.plot_monthly_normals(wxdset['normals'])
fig.set_lang(self.fig_language)
fig.figure.savefig(os.path.join(dirname, filename))
# ------------------------------------------------------ .err file ----
if self.full_error_analysis:
# ---- Info Data Post-Processing ----
XYinfo = self.postprocess_fillinfo(STANAME, YXmFULL, tarStaIndx)
Yname, Ym = XYinfo[0], XYinfo[1]
Xnames, Xmes = XYinfo[2], XYinfo[3]
# ---- Prepare Header ----
fcontent = copy(HEADER)
fcontent.append(['', '', '', '', '', '',
'Est. Err.', Yname, Yname])
fcontent[-1].extend(Xnames)
fcontent.append(['VARIABLE', 'YEAR', 'MONTH', 'DAY', 'Ndata',
'RMSE', 'Ypre-Ymes', 'Ypre', 'Ymes'])
for i in range(len(Xnames)):
fcontent[-1].append('X%d' % i)
# ---- Add Data to fcontent ----
for var in range(nVAR):
for row in range(index_start, index_end+1):
yp = YpFULL[row, var]
ym = Ym[row, var]
xm = ['' if np.isnan(i) else '%0.1f' % i for i in
Xmes[row, :, var]]
# Write the info only if there is a measured value in
# the data series of the target station.
if not np.isnan(ym):
fcontent.append([VARNAME[var],
'%d' % YEAR[row],
'%d' % MONTH[row],
'%d' % DAY[row],
'%s' % log_Ndat[row, var],
'%0.2f' % log_RMSE[row, var],
'%0.1f' % (yp - ym),