station.py 16.5 KB
Newer Older
1 2 3 4 5
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 29 10:35:29 2019

@author: Gerrit Erichsen
6 7 8 9 10 11 12 13 14 15
@brief: class to evaluate weather data
@details: This class is meant to be compact data holder and method collection
          for the analysis done in evaluate.py.
          It holds both the data of climate data center and the model data. from
          the model data, the data at the cell assigned. For qulaity measures
          the rmse, mae, and mbe are implemented. As the evaluation somewhat
          depends on the type, this distinction is made as well.
@remarks: This is neither well-coded, well-commented, nor pretty, as it was
          hastily implemented. You're welcome to make changes as you like.
@license: BSD license
16 17 18
"""

import h5py
19 20 21
import math
import numpy as np
import matplotlib.pyplot as plt
22 23

class WeatherStation:
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    # member variables ---------------------
    name = ""
    identifier = ""
    latitude = ""
    longitude = ""
    latitudeId = 0
    longitudeId = 0
    observationData = []
    modelData = []
    minuteIndicator = []
    mae = 0.
    mbe = 0.
    rmse = 0.
    obsMax = 0.
    obsMin = 0.
    obsAvg = 0.
    error = 0.2
    type = 'temperature'
42
    
43
    # constructor --------------------------------------------------------------
44
    def __init__(self, name, identifier, lat, lon, dataType = 'temperature'):
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
        self.name = name
        self.identifier = identifier
        self.latitude = lat
        self.longitude = lon
        self.latitudeId = -1
        self.longitudeId = -1
        self.observationData = []
        self.modelData = []
        self.minuteIndicator = []
        self.mae = 0.
        self.mbe = 0.
        self.rmse = 0.
        self.obsMax = 0.
        self.obsMin = 0.
        self.obsAvg = 0.
        self.error = 0.2
        self.type = dataType
    
    # some simple get functions to access members (out of habit, not needed) ---
64
    def getName(self):
65
        return self.name
66
    def getIdentifier(self):
67
        return self.identifier
68
    def getLatitude(self):
69
        return float(self.latitude)
70
    def getLongitude(self):
71
        return float(self.longitude)
72
    def getLatId(self):
73
        return self.latitudeId
74
    def getLonId(self):
75
        return self.longitudeId
76
    def getMeasuredData(self):
77
        return self.observationData
78
    def getRMSE(self):
79
        return self.rmse
80
    def getMAE(self):
81
        return self.mae
82
    def getMBE(self):
83
        return self.mbe
84 85
    def getModelData(self):
        data = []
86
        for element in self.modelData:
87
                data.append(element)
88
        return data
89
    def getModelDataLen(self):
90
        return len(self.modelData)
91
    def getModelDataAtIndex(self, index):
92 93
        if index >= 0 and index < len(self.modelData):
            return self.modelData[index]
94
        return 0.
95 96
    
    # starting to caluclate things
97
    def getDifferences(self):
98 99 100 101
        """(void) -> ([float])
            function calculates the differences between observed and model data.
            afterwards returns the resulting array. this is needed for the statistical
            analysis."""
102
        differences = []
103 104 105
        totalLength = len(self.observationData)
        if (len(self.modelData) < totalLength):
            totalLength = len(self.modelData)
106
        for i in range(0, totalLength):
107 108 109 110
            if (self.observationData[i] > -500. and
                self.observationData[i] < 2000.):
                value = self.observationData[i] - self.modelData[i]
                if (self.type == 'windDirection'):
111
                    if value > 180. :
112
                        value -= 360.
113
                    elif value < -180. :
114
                        value += 360.
115 116 117 118 119 120 121
                elif self.type == 'solar' \
                     or self.type == 'diffuseIrridiation' \
                     or self.type == 'globalIrridiation':
                     # observation data is given in j/cm^2 and model data in
                     # W/m^2, both at hourly resolution. the hard coded values
                     # correspond to conversion of theses too
                     # i.e. 10,000 cm^2 == m^2 and 3600 J == 1 Wh
122
                    joulePerCm2ToWhPerM2 = 1. * 10000. / 3600.
123
                    observed = self.observationData[i] * joulePerCm2ToWhPerM2
124
                    modeled = 0.
125 126 127 128
                    # the solar CDC data is given in true local time, which
                    # results in odd numbers in a normal time format (UTC).
                    # therefore the values of CDC need to be interpolated
                    # for "normal" time format
129
                    if i > 0 :
130 131 132 133
                        modeled = self.modelData[i] * self.minuteIndicator[i] \
                                  / 60.\
                                  + self.modelData[i - 1] \
                                  * (60 - self.minuteIndicator[i - 1]) / 60.
134 135
                    value = observed - modeled
                differences.append(value)
136
        return differences;
137 138
    
    # translating heights, as it is necessary with the wind data
139
    def getHeightIndices(height):
140 141 142
        """(float) -> (str, str)
            function returns indices of COSMO-DE's main planes, that lie
            around the specified height"""
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
        lower = ''
        upper = ''
        if height <= 10.:
            lower = '50'
        elif height < 35.72:
            lower = '50'
            upper = '49'
        elif height == 35.72:
            lower = '49'
        elif height < 73.03:
            lower = '49'
            upper = '48'
        elif height == 73.03:
            lower = '48'
        elif height < 122.32:
            lower = '48'
            upper = '47'
        elif height == 122.32:
            lower = '47'
        elif height < 183.93:
            lower = '47'
            upper = '46'
        elif height == 183.93:
            lower = '46'
        elif height < 258.21:
            lower = '46'
            upper = '45'
        elif height == 258.21:
            lower = '45'
        elif height < 345.53:
            lower = '45'
            upper = '44'
        elif height >= 345.53:
            lower = '44'
        return lower, upper
178
        
179
    def getHeightFromIndex(index):
180 181
        """(str) -> (float) 
            function returns height of COSMO-DE's main plane with index index"""
182 183 184 185 186 187 188 189 190 191 192 193 194 195
        if index == '50':
            return 10.
        elif index == '49':
            return 35.72
        elif index == '48':
            return 73.03
        elif index == '47':
            return 122.32
        elif index == '46':
            return 183.93
        elif index == '45':
            return 258.21
        else:
            return 345.53
196 197 198 199 200
    # clearing data arrays -----------------------------------------------------
    def clear(self):
        self.observationData = []
        self.modelData = []
        self.minuteIndicator = []
201
    
202
    def setLatLonIds(self, indexLat, indexLon):
203 204
        self.latitudeId = indexLat
        self.longitudeId = indexLon
205 206
    def setModelData(self, data):
        if len(data) > 0:
207 208
            self.modelData = []
            self.modelData = data
209
    def setType(self, dataType):
210
        self.type = dataType
211 212
    
    def readInCdcFile(self, fileName,  targetYear, column):
213
        self.m_measureData = [] #clear history -> expercience shows to be necessary
214 215 216 217
        file = open(fileName, "r")
        content = file.readlines()
        file.close()
        lastHour = 23 #entry that was before current one, needed for missing data
218
        counter = 0
219 220 221
        for line in content:
            entries = line.split(';')
            if entries[1].startswith(targetYear):
222 223 224
                if self.type == 'solar'\
                   or self.type == 'diffuseIrridiation' \
                   or self.type == 'globalIrridiation':
225
                    hour = int(entries[1][-5:-3])
226
                    self.minuteIndicator.append(int(entries[1][-2:]))
227 228
                else:
                    hour = int(entries[1][-2:])
229 230 231 232
                if hour > lastHour + 1:
                    i = 0
                    diff = hour - lastHour - 1
                    while i < diff:
233
                        self.observationData.append(-999.)
234 235 236 237 238 239
                        i += 1
                elif hour < lastHour and not(hour == 0 and lastHour == 23):
                    #assuming that there is never an entire day missing
                    i = 0
                    diff = 24 - lastHour + hour - 1
                    while i < diff:
240
                        self.observationData.append(-999.)
241
                        i += 1
242 243 244
                self.observationData.append(float(entries[column]))
                if self.type == 'windDirection' and counter == 0:
                    print(self.type, column, entries[column], self.observationData)
245
                lastHour = hour
246
            counter += 1
247 248 249
        supposedLength = 8760
        if (int(targetYear) % 4 == 0):
            supposedLength = 8784
250
        if len(self.observationData) < supposedLength:
251
            print(self.name, 'only has', len(self.observationData))
252
            self.observationData = []
253
                
254 255
    def readInModelFile(self, h5FileName, dataType, targetYear, \
                        h5FileName2 = '', height = 10.):
256
        self.modelData = []
257 258
        if h5FileName2 == '':
            with h5py.File(h5FileName, 'r') as h5File:
259
                self.modelData =h5File[dataType][:,self.latitudeId,self.longitudeId]
260 261 262 263 264 265
        else:
            data1 = []
            data2 = []
            height1 = WeatherStation.getHeightFromIndex(h5FileName[-5:-3])
            height2 = WeatherStation.getHeightFromIndex(h5FileName2[-5:-3])
            with h5py.File(h5FileName, 'r') as h5File1:
266
                data1 = h5File1[dataType][:,self.latitudeId,self.longitudeId]
267
            with h5py.File(h5FileName2, 'r') as h5File2:
268 269
                data2 = h5File2[dataType][:,self.latitudeId,self.longitudeId]
            self.modelData = []
270
            for lower, upper in zip(data1, data2):
271
                self.modelData.append(np.interp(height, [height1, height2], \
272
                                                  [lower, upper]))
273 274 275 276 277 278
        supposedLength = 8760
        if (int(targetYear) % 4 == 0):
            supposedLength = 8784
        if len(self.modelData) < supposedLength:
            print(self.name, 'only has', len(self.modelData))
            self.modelData = []
279
        
280
    # calculating all the statistics needed ------------------------------------
281
    def calculateStats(self):
282 283 284 285 286
        """(void) -> (void)
            kicks of calculation process. call-stack is:
                -getDifferences()
                -calculateMAE() | calculateMBE() | calculateRMSE()
            afterwards operations on solar data and some min/max analysis"""
287
        differences = self.getDifferences();
288 289 290
        self.mae = WeatherStation.calculateMAE(differences);
        self.mbe = WeatherStation.calculateMBE(differences);
        self.rmse = WeatherStation.calculateRMSE(differences);
291
        values = []
292
        for element in self.observationData:
293 294
            if (element > -500. and element < 2000.):
                values.append(element);
295 296 297
                if self.type == 'solar' \
                   or self.type == 'diffuseIrridiation' \
                   or self.type == 'globalIrridiation':
298
                    joulePerCm2ToWhPerM2 = 1. * 10000. / 3600.
299
                    values[-1] *= joulePerCm2ToWhPerM2     
300
        valueArray = np.array(values);
301 302 303 304
        self.obsMin = valueArray.min()
        self.obsMax = valueArray.max()
        self.obsAvg = valueArray.mean()
        
305
    def calculateMAE(differences):
306 307
        """([float]) -> (np.array)
            function returns mean of absolutes of float array"""
308 309 310
        return abs(np.array(differences)).mean()

    def calculateMBE(differences):
311 312
        """([float]) -> (np.array)
            function returns mean of float array"""
313 314 315
        return np.array(differences).mean()

    def calculateRMSE(differences):
316 317
        """([float]) -> (np.array)
            function returns mean of square-roots of squares of float array"""
318 319
        return math.sqrt(np.square(np.array(differences)).mean())
    
320
    # making plots -------------------------------------------------------------
321
    def createPlots(self, fig, printAxis = False):
322 323 324 325 326 327
        """(matplotlib.axes, bool) -> (void)
            creates a scatter plot of obersvation data and model data (x and y,
            repsectively). the scatter plot is added to the matplotlib axes given
            at function call.
            @remark: this re-uses some code of the differences() function. may be
            this can be done less verbose and more well structed"""
328 329 330 331 332 333
        differences = self.getDifferences();
        valuesObs = []
        valuesObsBounds = []
        valuesMod = []
        xAxis = []
        i = 0
334 335 336 337 338
        total = len(self.observationData)
        if (len(self.modelData) < total): total = len(self.modelData)
        if self.type == 'solar' \
                 or self.type == 'diffuseIrridiation' \
                 or self.type == 'globalIrridiation':
339
            for i in range(0, total):
340 341 342 343 344 345 346 347
                if (self.observationData[i] > -500. \
                    and self.observationData[i] < 2000.):
                    valuesObs.append(self.observationData[i])
                    valuesObsBounds.append(self.error)
                    valueMod = self.modelData[i]
                    if self.type == 'solar' \
                         or self.type == 'diffuseIrridiation' \
                         or self.type == 'globalIrridiation':
348 349 350 351
                        joulePerCm2ToWhPerM2 = 1. * 10000. / 3600.
                        valuesObs[-1] *= joulePerCm2ToWhPerM2
                        valueMod = 0.
                        if i > 0 :
352 353 354 355
                            valueMod= self.modelData[i]       \
                                      * self.minuteIndicator[i] / 60. \
                                      + self.modelData[i - 1] \
                                      * (60 - self.minuteIndicator[i - 1]) / 60.
356 357 358 359
                    valuesMod.append(valueMod)
                    xAxis.append(i)
        else:
            for i in range(0, total):
360 361 362 363
                if (self.observationData[i] > -500. \
                    and self.observationData[i] < 2000.):
                    valuesObs.append(self.observationData[i])
                    valuesMod.append(self.modelData[i])
364 365 366 367 368 369
        # plt.plot(differences, label = "diff")
        # plt.plot(valuesObs, label = "measure")
        # plt.plot(valuesMod, label = "model")
        # upper = np.array(valuesObs) + np.array(valuesObsBounds)
        # lower = np.array(valuesObs) - np.array(valuesObsBounds)
        # plt.fill_between(xAxis, lower, upper)
370
        # plt.title(self.getName() + ' ' + self.type + ' Run')
371 372 373
        # plt.legend()
        # plt.show()
        # plt.figure()
374 375 376 377 378 379 380 381
        if self.type == 'temperature':
            fig.scatter(valuesObs, valuesMod, s=0.5, color="tab:red")
        elif self.type == 'solar' \
                     or self.type == 'diffuseIrridiation' \
                     or self.type == 'globalIrridiation':
            fig.scatter(valuesObs, valuesMod, s=0.5, color="tab:orange")
        else:
            fig.scatter(valuesObs, valuesMod, s=0.5, color="tab:blue")
382
        fig.plot(valuesObs, valuesObs, color='k')
383 384 385 386 387
        maxY = max(np.array(valuesObs).max(), np.array(valuesMod).max())
        annotation = 'RMSE:    %.1f\n' \
                     'MAE:     %.1f\n' \
                     'MBE:     %.1f\n' \
                     'Range:   %.1f\n' \
388 389 390 391
                     'Avg:     %.1f' % (self.rmse, self.mae, self.mbe, \
                                        self.obsMax - self.obsMin, \
                                        self.obsAvg)
        if self.type == 'temperature':
392 393 394 395 396 397 398
            fig.annotate(annotation, (np.array(valuesObs).min(),
                                      maxY * 0.5), fontsize=8,
                                      fontweight='bold')
        else:
            fig.annotate(annotation, (0,maxY * 0.75), fontsize=8,
                                      fontweight='bold')
        fig.set_title(self.getName())
399 400 401
        if self.type == 'temperature':
            fig.set_xlabel("° C")
            if printAxis:
402
                fig.set_ylabel("° C")
403 404 405 406 407
        elif self.type == 'solar' \
                 or self.type == 'diffuseIrridiation' \
                 or self.type == 'globalIrridiation':
            fig.set_xlabel('W / m$^2$')
            if printAxis:
408
                fig.set_ylabel('W / m$^2$')
409 410 411
        elif self.type == 'windDirection':
            fig.set_xlabel('Deg')
            if printAxis:
412
                fig.set_ylabel('Deg')
413 414 415
        else:
            fig.set_xlabel('m / s')
            if printAxis:
416
                fig.set_ylabel('m / s')