metro_model.py 18.6 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
229
230
231
232
233
        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()
        lFT = wf_interpolated_data.get_matrix_col('Time').tolist()
        lPI = wf_interpolated_data.get_matrix_col('PI').tolist()
        lSC = wf_interpolated_data.get_matrix_col('SC').tolist()

        # Number of 30 seconds step.
234
        npFT = wf_interpolated_data.get_matrix_col('Time')
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        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()

        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')\
250
                 .astype(numpy.int32)
251
        npSWO2 = observation.get_attribute('AT_VALID_INTERPOLATED')\
252
                 .astype(numpy.int32)
253
        npSWO3 = observation.get_attribute('TD_VALID_INTERPOLATED')\
254
                 .astype(numpy.int32)
255
        npSWO4 = observation.get_attribute('WS_VALID_INTERPOLATED')\
256
257
                 .astype(numpy.int32)
        npSWO = numpy.zeros(4*metro_constant.nNL)
258
        # Put all the arrays in one for the fortran code.
259
        for i in range(0,len(npSWO1)):
260
261
262
263
            npSWO[4*i] = npSWO1[i]
            npSWO[4*i+1] = npSWO2[i]
            npSWO[4*i+2] = npSWO3[i] 
            npSWO[4*i+3] = npSWO4[i] 
264
        lSWO = npSWO.astype(numpy.int32).tolist()
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
        
        bNoObs = observation.get_attribute('NO_OBS')
        
        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()

        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"))
296
297

        bEchec = []
298
        macadam.Do_Metro(bFlat,\
299
                         fLat, fLon, \
300
301
302
                         lLayerThick, nNbrOfLayer, lLayerType, \
                         lAT, lQP, lWS, lAP, lSF, lIR, lFT, lPI, lSC,\
                         lAT_obs,lST_obs, lSST_obs, \
303
                         lAH, lTime_obs, lSWO, bNoObs,\
304
305
                         fDeltaTMetroObservation, nLenObservation, \
                         nNbrTimeSteps, bSilent)
306
307
308
309
310
311
312
313
314
        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"))
315
316
317

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

        # Creation of the Metro_data object for the roadcast
320
321
322
323
        lStandard_items = metro_config.get_value( \
            'XML_ROADCAST_PREDICTION_STANDARD_ITEMS')
        lExtended_items = metro_config.get_value( \
            'XML_ROADCAST_PREDICTION_EXTENDED_ITEMS')        
324
325
326
        lItems = lStandard_items # + lExtended_items

        #FFTODO append all lExtended_items to metrodata        
327
        roadcast = metro_data.Metro_data(lItems)
328
        
Miguel Tremblay's avatar
Miguel Tremblay committed
329
        # Extraction of forecast data used to create the roadcasts.
330
331
332
        wf_data = forecast.get_interpolated_data()
                
        #
Miguel Tremblay's avatar
Miguel Tremblay committed
333
        # Generate the header of roadcast
334
335
        #

Miguel Tremblay's avatar
Miguel Tremblay committed
336
        # extraction of informations
337
338
339
340
341
        sRoadcast_version = \
            metro_config.get_value('FILE_ROADCAST_CURRENT_VERSION')
        sRoadcast_station = station.get_station_name()
        fRoadcast_production_date = time.time()
        
342
    
Miguel Tremblay's avatar
Miguel Tremblay committed
343
344
        #
        # Generate the roadcast matrix of data
345
346
        #

Miguel Tremblay's avatar
Miguel Tremblay committed
347
        # Extraction of data used by metro_core in the computation
348
349
350
351
352
        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
353
        # Extraction of roadcast data computed by metro_core
354
355
356
357
358
359
360
361
362
363
364
365
        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]
        lFA = (macadam.get_fa())[:iNb_timesteps]
        lFG = (macadam.get_g())[:iNb_timesteps]
        lBB = (macadam.get_bb())[:iNb_timesteps]
        lFP = (macadam.get_fp())[:iNb_timesteps]
366
        lSST =  (macadam.get_sst())[:iNb_timesteps]
367

368
369
370
371
372
373
374
375
376
377
378
        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])
           
379
380
381
382
        # 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)
383
384
385
386
        roadcast.set_header_value('LATITUDE', station.get_header()\
                                  ['COORDINATE'][0])
        roadcast.set_header_value('LONGITUDE', station.get_header()\
                                  ['COORDINATE'][1])
387
        roadcast.set_header_value('FILETYPE','roadcast')
388
389
390

        if metro_config.get_value('TL') == True:
            roadcast.set_header_value('VERTICAL_LEVELS',lDepth)
391
  
392
393
394
395
396

        # 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.
397
398
399
400
        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]
401
        # 3.6 is to convert from m/s to km/h
402
403
404
405
406
        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]
407
408


409
        roadcast.init_matrix(iNb_timesteps, roadcast.get_real_nb_matrix_col())
410

Miguel Tremblay's avatar
Miguel Tremblay committed
411
        # Data added to the roadcast matrix
412
413
414
415
        roadcast.set_matrix_col('RA', lRA)
        roadcast.set_matrix_col('SN', lSN)
        roadcast.set_matrix_col('RC', lRC)
        roadcast.set_matrix_col('ST', lST)
416
417
418
419
420
421
422
        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)
423
424
425
426
427
428
429
430
        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('FA', lFA)
        roadcast.set_matrix_col('FG', lFG)
        roadcast.set_matrix_col('BB', lBB)
        roadcast.set_matrix_col('FP', lFP)
431
        roadcast.set_matrix_col('CC', npCC)
432
        roadcast.set_matrix_col('SST', lSST)
433
434
435
436
437

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

        
Miguel Tremblay's avatar
Miguel Tremblay committed
438
        # Creation of the object Metro_data_collection for the roadcast
439
440
441
442
443
444
445
446
447
448
449
        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
450
        # Writing of data needed for the roadcast.
451
452
453
454
455
456
457
458
        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