metro_model.py 19.1 KB
Newer Older
1
2
3
#
# METRo : Model of the Environment and Temperature of Roads
# METRo is Free and is proudly provided by the Government of Canada
Miguel Tremblay's avatar
Miguel Tremblay committed
4
# Copyright (C) Her Majesty The Queen in Right of Canada, Environment Canada, 2006
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

#  Questions or bugs report: metro@ec.gc.ca
#  METRo repository: https://gna.org/projects/metro/
#  Documentation: http://documentation.wikia.com/wiki/METRo
#
#
# Code contributed by:
#  Miguel Tremblay - Canadian meteorological center
#  Francois Fortin - Canadian meteorological center
#
#  $LastChangedDate$
#  $LastChangedRevision$
#
########################################################################
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#
#

from metro_module import Metro_module

import string
import time
40
import numpy
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

import metro_logger
import metro_config
from toolbox import metro_util
from toolbox import metro_date
from toolbox import metro_constant
from data_module import metro_data_collection_output
from data_module import metro_data
from data_module import metro_infdata

_ = metro_util.init_translation('metro_model')

# To call the C function.
from model import macadam

class Metro_model(Metro_module):

    def get_receive_type( self ):
        return Metro_module.DATATYPE_DATA_IN

    def get_send_type( self ):
        return Metro_module.DATATYPE_DATA_OUT

    def start( self ):
        Metro_module.start(self)

        pForecast = self.get_infdata_reference('FORECAST')
        forecast_data = pForecast.get_data_collection()
        pObservation = self.get_infdata_reference('OBSERVATION')
        observation_data = pObservation.get_data_collection()
        pStation = self.get_infdata_reference('STATION')
        station_data = pStation.get_data()

        if metro_config.get_value('T_BYPASS_CORE') == False:

            self.__send_data_to_metro_core(forecast_data,
                                           observation_data,
                                           station_data )
            
            roadcast_data = self.__create_roadcast_collection(forecast_data,
                                                              observation_data,
                                                              station_data)
        else:
            roadcast_data = None
            metro_logger.print_message(
                metro_logger.LOGGER_MSG_INFORMATIVE,
                _("Bypassing METRo core, roadcast not created."))

        pForecast.set_data_collection(forecast_data)
        pObservation.set_data_collection(observation_data)
        pStation.set_data(station_data)

        # creer et ajouter infdata
Miguel Tremblay's avatar
Miguel Tremblay committed
94
        # Creation and adding infdata
95
96
97
98
99
100
101
102
103
104
105
        infdata_roadcast = metro_infdata.Metro_infdata(
            'ROADCAST', metro_infdata.DATATYPE_METRO_DATA_COLLECTION)
        infdata_roadcast.set_data_collection(roadcast_data)
        self.add_infdata(infdata_roadcast)
        
            
    def stop( self ):
        Metro_module.stop(self)

    def __get_nb_timesteps( self, forecast ):
        wf_data = forecast.get_interpolated_data()
106
        npFT = wf_data.get_matrix_col('Time')
107

108
        return len(npFT)
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124


    def __get_observation_lenght( self, observation ):
        obs_data = observation.get_interpolated_data()
        lTime_obs = obs_data.get_matrix_col('Time').tolist()
        return len(lTime_obs)        

    def __get_observation_delta_t( self, observation ):
        return observation.get_attribute('DELTA_T')        
        
    def __send_data_to_metro_core( self, forecast, observation, station ):

        wf_data = forecast.get_interpolated_data()
        ro_data = observation.get_interpolated_data()
        cs_data = station

125
126
        # Start time from model is the last observation
        sStart_time = metro_config.get_value('DATA_ATTRIBUTE_LAST_OBSERVATION')
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
        fStart_time = metro_date.parse_date_string(sStart_time)


        iModel_start_y = metro_date.get_year(fStart_time)
        sMessage = _("year: [%s]") % (iModel_start_y)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        iModel_start_m = metro_date.get_month(fStart_time)
        sMessage = _("month: [%s]") % (iModel_start_m)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        iModel_start_d = metro_date.get_day(fStart_time)
        sMessage = _("day: [%s]") % (iModel_start_d)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        iModel_start_h = metro_date.get_hour(fStart_time)
        sMessage = _("hour: [%s]") % (iModel_start_h)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        dStation_header = cs_data.get_header()

Miguel Tremblay's avatar
Miguel Tremblay committed
152
        # test observation
153
154
155
156
157
158
159
160
        dObservation_header = ro_data.get_header()
        lObservation_data   = ro_data.get_matrix()
        sMessage = "Observation_header=" + str(dObservation_header)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                  sMessage)        
        sMessage = "Observation_data=" + str(lObservation_data)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)
Miguel Tremblay's avatar
Miguel Tremblay committed
161
162
        
        # test forecast
163
164
165
166
167
168
169
170
171
172
        dForecast_header = wf_data.get_header()
        lForecast_data   = wf_data.get_matrix()

        sMessage = "Forecast_header=" + str(dForecast_header)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)        
        sMessage = "Forecast_data=" +  str(lForecast_data)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

Miguel Tremblay's avatar
Miguel Tremblay committed
173
        # start roadlayer MATRIX
174
175
        npLayerType  = cs_data.get_matrix_col('TYPE')
        lLayerType = npLayerType.astype(numpy.int32).tolist()
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        lLayerThick = cs_data.get_matrix_col('THICKNESS').tolist()
        nNbrOfLayer = len(lLayerType)

        sMessage = _("Number of layer=") +  str(nNbrOfLayer)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        # Append an empty box for the manuel mode
        lLayerType.append(0)
        lLayerThick.append(0.0)
        

        sMessage = _("roadlayer type=") + str(lLayerType)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)
        sMessage = _("roadlayer thick=") + str(lLayerThick)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)
Miguel Tremblay's avatar
Miguel Tremblay committed
194
        # end roadlayer MATRIX
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

        fTime =  dStation_header['PRODUCTION_DATE']
        fTimeForecast = dForecast_header['PRODUCTION_DATE']
        sTimeZone = dStation_header['TIME_ZONE']
        sMessage = _("timezone=") + sTimeZone
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)
        
        fIssue_time = fStart_time
        
        sMessage = _("issue time=") + time.ctime(fIssue_time)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        
        wforiginal = forecast.get_original_data()

        ft = wforiginal.get_matrix_col('FORECAST_TIME')


        ##################################################################
        # Forecast
        #  Get the interpolated values.
        wf_interpolated_data =  forecast.get_interpolated_data()
219
220
        npAT =  wf_interpolated_data.get_matrix_col('AT')
        lAT = npAT.tolist()
221
        lQP = wf_interpolated_data.get_matrix_col('QP').tolist()
222
223
224
225
        npWS = wf_interpolated_data.get_matrix_col('WS')
        lWS = npWS.tolist()
        npTD = wf_interpolated_data.get_matrix_col('TD') 
        lTD = npTD.tolist()
226
227
228
        lAP = wf_interpolated_data.get_matrix_col('AP').tolist()
        lSF = wf_interpolated_data.get_matrix_col('SF').tolist()
        lIR = wf_interpolated_data.get_matrix_col('IR').tolist()
229
230
        npFA = wf_interpolated_data.get_matrix_col('FA')
        lFA = npFA.tolist()
231
232
233
        lPI = wf_interpolated_data.get_matrix_col('PI').astype(numpy.int32).tolist()
        lSC = wf_interpolated_data.get_matrix_col('SC').astype(numpy.int32).tolist()
        
234
235

        # Number of 30 seconds step.
236
        npFT = wf_interpolated_data.get_matrix_col('Time')
237
238
239
240
241
242
243
244
245
        nNbrTimeSteps = self.__get_nb_timesteps(forecast)
        lAH = wf_interpolated_data.get_matrix_col('AH').tolist()

        # Observation data ###############################################
        ro_interpolated_data = observation.get_interpolated_data()
        lAT_obs = ro_interpolated_data.get_matrix_col('AT').tolist()
        lST_obs =  ro_interpolated_data.get_matrix_col('ST').tolist()
        lSST_obs =  ro_interpolated_data.get_matrix_col('SST').tolist()
        lTime_obs = ro_interpolated_data.get_matrix_col('Time').tolist()
246
247
248
        # Deep soil value given in command line
        bDeepTemp = metro_config.get_value('DEEP_SOIL_TEMP')
        dDeepTemp =  float(metro_config.get_value('DEEP_SOIL_TEMP_VALUE'))
249
250
251
252
253
254

        nLenObservation = self.__get_observation_lenght(observation)        
        fDeltaTMetroObservation = self.__get_observation_delta_t(observation)
        
        # Concatenate the information to send it to C.
        npSWO1 = observation.get_attribute('SST_VALID_INTERPOLATED')\
255
                 .astype(numpy.int32)
256
        npSWO2 = observation.get_attribute('AT_VALID_INTERPOLATED')\
257
                 .astype(numpy.int32)
258
        npSWO3 = observation.get_attribute('TD_VALID_INTERPOLATED')\
259
                 .astype(numpy.int32)
260
        npSWO4 = observation.get_attribute('WS_VALID_INTERPOLATED')\
261
262
                 .astype(numpy.int32)
        npSWO = numpy.zeros(4*metro_constant.nNL)
263
        # Put all the arrays in one for the fortran code.
264
        for i in range(0,len(npSWO1)):
265
266
267
268
            npSWO[4*i] = npSWO1[i]
            npSWO[4*i+1] = npSWO2[i]
            npSWO[4*i+2] = npSWO3[i] 
            npSWO[4*i+3] = npSWO4[i] 
269
        lSWO = npSWO.astype(numpy.int32).tolist()
270
        
271
        bNoObs = observation.get_attribute('NO_OBS')
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        
        sMessage = _( "------------station config START---------------------")
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)
                
        sShort_time_zone = metro_date.get_short_time_zone\
                           (fIssue_time,sTimeZone)

        sMessage = _( "Short time zone = ") + sShort_time_zone
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        tLatlon = dStation_header['COORDINATE']
        fLat = tLatlon[0]
        fLon = tLatlon[1]
        sMessage = _( "lat,lon: ")+ "(" + str(fLat) + ", " + str(fLon) + ")"
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

        bFlat = cs_data.get_station_type()

293
294
295
296
297
298
        dSstDepth = cs_data.get_sst_depth()

        sMessage = _( "SST sensor depth: ") + str(dSstDepth)
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)

299
300
301
302
303
304
305
306
        sMessage = _("------------station config END---------------------")
        metro_logger.print_message(metro_logger.LOGGER_MSG_DEBUG,
                                   sMessage)
        
        bSilent = not metro_config.get_value('INIT_LOGGER_SHELL_DISPLAY')

        metro_logger.print_message(metro_logger.LOGGER_MSG_EXECPRIMARY,
                                   _("Start sending data to METRo core"))
307
308

        bEchec = []
309

310
311
312
313
314
315
316
        macadam.Do_Metro(bFlat, fLat, fLon, lLayerThick, \
                         nNbrOfLayer, lLayerType, lAT, lQP, \
                         lWS, lAP, lSF, lIR, \
                         lFA, lPI, lSC, lAT_obs, \
                         lST_obs, lSST_obs, lAH, lTime_obs, \
                         lSWO, bNoObs, fDeltaTMetroObservation, \
                         nLenObservation, nNbrTimeSteps, bSilent, \
317
                         dSstDepth, bDeepTemp, dDeepTemp)
318
319
320
321
322
323
324
325
326
        bEchec = (macadam.get_echec())[0]
        # Check if the execution of the model was a succes:
        if bEchec != 0:
            sError_message = _("Fatal error in METRo physical model.") 
            metro_logger.print_message(metro_logger.LOGGER_MSG_STOP,
                                       sError_message)
        else:
            metro_logger.print_message(metro_logger.LOGGER_MSG_EXECPRIMARY,
                                       _("End of METRo core"))
327
328
329

    def __create_roadcast_collection( self, forecast, observation, station ):
        
Miguel Tremblay's avatar
Miguel Tremblay committed
330
331

        # Creation of the Metro_data object for the roadcast
332
333
334
335
        lStandard_items = metro_config.get_value( \
            'XML_ROADCAST_PREDICTION_STANDARD_ITEMS')
        lExtended_items = metro_config.get_value( \
            'XML_ROADCAST_PREDICTION_EXTENDED_ITEMS')        
336
337
338
        lItems = lStandard_items # + lExtended_items

        #FFTODO append all lExtended_items to metrodata        
339
        roadcast = metro_data.Metro_data(lItems)
340
        
Miguel Tremblay's avatar
Miguel Tremblay committed
341
        # Extraction of forecast data used to create the roadcasts.
342
343
344
        wf_data = forecast.get_interpolated_data()
                
        #
Miguel Tremblay's avatar
Miguel Tremblay committed
345
        # Generate the header of roadcast
346
347
        #

Miguel Tremblay's avatar
Miguel Tremblay committed
348
        # extraction of informations
349
350
351
352
353
        sRoadcast_version = \
            metro_config.get_value('FILE_ROADCAST_CURRENT_VERSION')
        sRoadcast_station = station.get_station_name()
        fRoadcast_production_date = time.time()
        
354
    
Miguel Tremblay's avatar
Miguel Tremblay committed
355
356
        #
        # Generate the roadcast matrix of data
357
358
        #

Miguel Tremblay's avatar
Miguel Tremblay committed
359
        # Extraction of data used by metro_core in the computation
360
361
362
363
364
        iObservation_len = self.__get_observation_lenght(observation)
        fObservation_delta_t = self.__get_observation_delta_t(observation)
        iNb_timesteps = self.__get_nb_timesteps(forecast)


Miguel Tremblay's avatar
Miguel Tremblay committed
365
        # Extraction of roadcast data computed by metro_core
366
367
368
369
370
371
372
373
374
375
376
        lRA = (macadam.get_ra())[:iNb_timesteps]
        lSN = (macadam.get_sn())[:iNb_timesteps]
        lRC = (macadam.get_rc())[:iNb_timesteps]
        lST = (macadam.get_rt())[:iNb_timesteps]
        lFV = (macadam.get_fv())[:iNb_timesteps]
        lSF = (macadam.get_sf())[:iNb_timesteps]
        lIR = (macadam.get_ir())[:iNb_timesteps]
        lFC = (macadam.get_fc())[:iNb_timesteps]
        lFG = (macadam.get_g())[:iNb_timesteps]
        lBB = (macadam.get_bb())[:iNb_timesteps]
        lFP = (macadam.get_fp())[:iNb_timesteps]
377
        lSST =  (macadam.get_sst())[:iNb_timesteps]
378

379
380
381
382
383
384
385
386
387
388
389
        if metro_config.get_value('TL') == True:
            # Temperature of levels under the ground.
            nNbrVerticalLevel = macadam.get_nbr_levels()
            lDepth = (macadam.get_depth())[:nNbrVerticalLevel]
            lTmpTL = (macadam.get_lt())[:nNbrVerticalLevel*iNb_timesteps]
            lTL = []        
            for i in range(0,iNb_timesteps):
                begin = i * nNbrVerticalLevel
                end = begin + nNbrVerticalLevel
                lTL.append(lTmpTL[begin:end])
           
390
391
392
393
        # Adding the informations to the header
        roadcast.set_header_value('VERSION',sRoadcast_version)
        roadcast.set_header_value('ROAD_STATION',sRoadcast_station)
        roadcast.set_header_value('PRODUCTION_DATE',fRoadcast_production_date)
394
395
396
397
        roadcast.set_header_value('LATITUDE', station.get_header()\
                                  ['COORDINATE'][0])
        roadcast.set_header_value('LONGITUDE', station.get_header()\
                                  ['COORDINATE'][1])
398
        roadcast.set_header_value('FILETYPE','roadcast')
399
400
401

        if metro_config.get_value('TL') == True:
            roadcast.set_header_value('VERTICAL_LEVELS',lDepth)
402
  
403
404
405
406
407

        # TODO MT: Le +30 est la pour que l'output soit au bon moment.
        #  Il y a eu un probleme dans la conversion entre le C et le fortran
        #  qui fait en sorte qu'il y a un decalage d'un indice.  Il faudra que
        #  ce soit corrige.
408
409
410
411
        npRT = wf_data.get_matrix_col('FORECAST_TIME')[:iNb_timesteps]
        npRT = npRT + 30
        npHH = wf_data.get_matrix_col('Time')[:iNb_timesteps]
        npAT = wf_data.get_matrix_col('AT')[:iNb_timesteps]
412
        npFA = wf_data.get_matrix_col('FA')[:iNb_timesteps]
413
        # 3.6 is to convert from m/s to km/h
414
415
416
417
418
        npWS = wf_data.get_matrix_col('WS')[:iNb_timesteps]*3.6
        npTD = wf_data.get_matrix_col('TD')[:iNb_timesteps]
        npQP_SN = wf_data.get_matrix_col('SN')[:iNb_timesteps]
        npQP_RA = wf_data.get_matrix_col('RA')[:iNb_timesteps]
        npCC = wf_data.get_matrix_col('CC')[:iNb_timesteps]
419
420


421
        roadcast.init_matrix(iNb_timesteps, roadcast.get_real_nb_matrix_col())
422

Miguel Tremblay's avatar
Miguel Tremblay committed
423
        # Data added to the roadcast matrix
424
425
426
427
        roadcast.set_matrix_col('RA', lRA)
        roadcast.set_matrix_col('SN', lSN)
        roadcast.set_matrix_col('RC', lRC)
        roadcast.set_matrix_col('ST', lST)
428
429
430
431
432
433
434
        roadcast.set_matrix_col('ROADCAST_TIME', npRT)
        roadcast.set_matrix_col('HH', npHH)
        roadcast.set_matrix_col('AT', npAT)
        roadcast.set_matrix_col('WS', npWS)
        roadcast.set_matrix_col('TD', npTD)
        roadcast.set_matrix_col('QP-SN', npQP_SN)
        roadcast.set_matrix_col('QP-RA', npQP_RA)
435
436
437
438
439
        roadcast.set_matrix_col('IR', lIR)
        roadcast.set_matrix_col('SF', lSF)
        roadcast.set_matrix_col('FV', lFV)
        roadcast.set_matrix_col('FC', lFC)
        roadcast.set_matrix_col('FG', lFG)
440
        roadcast.set_matrix_col('FA', npFA.tolist())
441
442
        roadcast.set_matrix_col('BB', lBB)
        roadcast.set_matrix_col('FP', lFP)
443
        roadcast.set_matrix_col('CC', npCC)
444
        roadcast.set_matrix_col('SST', lSST)
445
446
447
448
449

        if metro_config.get_value('TL') == True:
            roadcast.append_matrix_multiCol('TL', lTL)

        
Miguel Tremblay's avatar
Miguel Tremblay committed
450
        # Creation of the object Metro_data_collection for the roadcast
451
452
453
454
455
456
457
458
459
460
461
        lStandard_attributes = metro_config.get_value( \
            'DATA_ATTRIBUTE_ROADCAST_STANDARD')
        lExtended_attributes = metro_config.get_value( \
            'DATA_ATTRIBUTE_ROADCAST_EXTENDED')        
        lAttributes = lStandard_attributes + lExtended_attributes
        
        roadcast_collection = \
            metro_data_collection_output.\
            Metro_data_collection_output(roadcast,lAttributes)

        
Miguel Tremblay's avatar
Miguel Tremblay committed
462
        # Writing of data needed for the roadcast.
463
464
465
466
467
468
469
470
        roadcast_collection.set_attribute('OBSERVATION_LENGTH',
                                          iObservation_len)
        roadcast_collection.set_attribute('OBSERVATION_DELTAT_T',
                                          fObservation_delta_t)
        roadcast_collection.set_attribute('FORECAST_NB_TIMESTEPS',
                                          iNb_timesteps)

        return roadcast_collection