loading.py 13.2 KB
Newer Older
sim-baz's avatar
sim-baz committed
1
2
3
4
from cassandra.cluster import Cluster
import csv
import re

sim-baz's avatar
sim-baz committed
5
FILE_NAME = "asos.txt"
sim-baz's avatar
sim-baz committed
6
7
table_name_space = "station"
table_name_date = "date"
sim-baz's avatar
sim-baz committed
8

sim-baz's avatar
sim-baz committed
9
10
numeric_columns = ["lon","lat","tmpf","dwpf","relh","drct","sknt","p01i","alti","mslp","vsby","gust","skyl1","skyl2","skyl3","skyl4","feel","ice_accretion_1hr","ice_accretion_3hr","ice_accretion_6hr","peak_wind_gust","peak_wind_drct","peak_wind_time"]

sim-baz's avatar
sim-baz committed
11
12
13
MIN_DATE = 2001
MAX_DATE = 2010

sim-baz's avatar
sim-baz committed
14
15
16
FIRST_DAY = "2001-01-01"
LAST_DAY = "2010-12-31"

sim-baz's avatar
sim-baz committed
17
18
19
20
21
22
# Country: Finland
# Dates : 2001 to 2010

## datas format:
# station: three or four character site identifier
# valid: timestamp of the observation
sim-baz's avatar
sim-baz committed
23
24
# lon: longitude of the station
# lat: latitude of the station
sim-baz's avatar
sim-baz committed
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
# tmpf: Air Temperature in Fahrenheit, typically @ 2 meters
# dwpf: Dew Point Temperature in Fahrenheit, typically @ 2 meters
# relh: Relative Humidity in %
# drct: Wind Direction in degrees from north
# sknt: Wind Speed in knots
# p01i: One hour precipitation for the period from the observation time to the time of the previous hourly precipitation reset. This varies slightly by site. Values are in inches. This value may or may not contain frozen precipitation melted by some device on the sensor or estimated by some other means. Unfortunately, we do not know of an authoritative database denoting which station has which sensor.
# alti: Pressure altimeter in inches
# mslp: Sea Level Pressure in millibar
# vsby: Visibility in miles
# gust: Wind Gust in knots
# skyc1: Sky Level 1 Coverage
# skyc2: Sky Level 2 Coverage
# skyc3: Sky Level 3 Coverage
# skyc4: Sky Level 4 Coverage
# skyl1: Sky Level 1 Altitude in feet
# skyl2: Sky Level 2 Altitude in feet
# skyl3: Sky Level 3 Altitude in feet
# skyl4: Sky Level 4 Altitude in feet
# wxcodes: Present Weather Codes (space seperated)
# feel: Apparent Temperature (Wind Chill or Heat Index) in Fahrenheit
# ice_accretion_1hr: Ice Accretion over 1 Hour (inches)
# ice_accretion_3hr: Ice Accretion over 3 Hours (inches)
# ice_accretion_6hr: Ice Accretion over 6 Hours (inches)
# peak_wind_gust: Peak Wind Gust (from PK WND METAR remark) (knots)
# peak_wind_drct: Peak Wind Gust Direction (from PK WND METAR remark) (deg)
# peak_wind_time: Peak Wind Gust Time (from PK WND METAR remark)
# metar: unprocessed reported observation in METAR format

sim-baz's avatar
sim-baz committed
53
54
55
56
57
58
59
'''
name: loadata
description: Load datas of the file, by creating a generator
parameters:
    * filename: File name to load
return: generator of dictionaries with value and name of data
'''
sim-baz's avatar
sim-baz committed
60
def loadata(filename):
Oscar Roisin's avatar
Oscar Roisin committed
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
    dateparser = re.compile(
        "(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+) (?P<hour>\d+):(?P<minute>\d+)"
    )
    with open(filename) as f:
        for r in csv.DictReader(f):
            data = {}
            data["station"] = r["station"]
            valid = dateparser.match(r["valid"]).groupdict()

            data["year"] = int(valid["year"])
            data["month"] = int(valid["month"])
            data["day"] = int(valid["day"])
            data["hour"] = int(valid["hour"])
            data["minute"] = int(valid["minute"])

            data["lon"] = float(r["lon"])
            data["lat"] = float(r["lat"])

            if r["tmpf"] == 'null':
                data["tmpf"] = 'null'
            else:
                data["tmpf"] = float(r["tmpf"])

            if r["dwpf"] == 'null':
                data["dwpf"] = 'null'
            else:
                data["dwpf"] = float(r["dwpf"])

            if r["relh"] == 'null':
                data["relh"] = 'null'
            else:
                data["relh"] = float(r["relh"])

            if r["drct"] == 'null':
                data["drct"] = 'null'
            else:
                data["drct"] = float(r["drct"])

            if r["sknt"] == 'null':
                data["sknt"] = 'null'
            else:
                data["sknt"] = float(r["sknt"])

            if r["p01i"] == 'null':
                data["p01i"] = 'null'
            else:
                data["p01i"] = float(r["p01i"])	

            if r["alti"] == 'null':
                data["alti"] = 'null'
            else:
                data["alti"] = float(r["alti"])

            if r["mslp"] == 'null':
                data["mslp"] = 'null'
            else:
                data["mslp"] = float(r["mslp"])

            if r["vsby"] == 'null':
                data["vsby"] = 'null'
            else:
                data["vsby"] = float(r["vsby"])	

            if r["gust"] == 'null':
                data["gust"] = 'null'
            else:
                data["gust"] = float(r["gust"])

            data["skyc1"] = r["skyc1"]
            data["skyc2"] = r["skyc2"]
            data["skyc3"] = r["skyc3"]
            data["skyc4"] = r["skyc4"]

            if r["skyl1"] == 'null':
                data["skyl1"] = 'null'
            else:
                data["skyl1"] = float(r["skyl1"])

            if r["skyl2"] == 'null':
                data["skyl2"] = 'null'
            else:
                data["skyl2"] = float(r["skyl2"])

            if r["skyl3"] == 'null':
                data["skyl3"] = 'null'
            else:
                data["skyl3"] = float(r["skyl3"])

            if r["skyl4"] == 'null':
                data["skyl4"] = 'null'
            else:
                data["skyl4"] = float(r["skyl4"])

            data["wxcodes"] = r["wxcodes"]

            if r["feel"] == 'null':
                data["feel"] = 'null'
            else:
                data["feel"] = float(r["feel"])

            if r["ice_accretion_1hr"] == 'null':
                data["ice_accretion_1hr"] = 'null'
            else:
                data["ice_accretion_1hr"] = float(r["ice_accretion_1hr"])

            if r["ice_accretion_3hr"] == 'null':
                data["ice_accretion_3hr"] = 'null'
            else:
                data["ice_accretion_3hr"] = float(r["ice_accretion_3hr"])

            if r["ice_accretion_6hr"] == 'null':
                data["ice_accretion_6hr"] = 'null'
            else:
                data["ice_accretion_6hr"] = float(r["ice_accretion_6hr"])

            if r["peak_wind_gust"] == 'null':
                data["peak_wind_gust"] = 'null'
            else:
                data["peak_wind_gust"] = float(r["peak_wind_gust"])

            if r["peak_wind_drct"] == 'null':
                data["peak_wind_drct"] = 'null'
            else:
                data["peak_wind_drct"] = float(r["peak_wind_drct"])

            if r["peak_wind_time"] == 'null':
                data["peak_wind_time"] = 'null'
            else:
                data["peak_wind_time"] = float(r["peak_wind_time"])

            data["metar"] = r["metar"]
            
            yield data
sim-baz's avatar
sim-baz committed
194
195

NAME_COLUMNS = """
Oscar Roisin's avatar
Oscar Roisin committed
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
    station 		  ,
    year			  ,
    month 			  ,
    day 			  ,
    hour 			  ,
    minute 			  ,
    lon 			  ,
    lat 			  ,
    tmpf 			  ,
    dwpf 			  ,
    relh 			  ,
    drct 			  ,
    sknt 			  ,
    p01i 			  ,
    alti 			  ,
    mslp 			  ,
    vsby 			  ,
    gust 			  ,
    skyc1 			  ,
    skyc2 			  ,
    skyc3 			  ,
    skyc4 			  ,
    skyl1 			  ,
    skyl2 			  ,
    skyl3 			  ,
    skyl4 			  ,
    wxcodes           ,
    feel              ,
    ice_accretion_1hr ,
    ice_accretion_3hr ,
    ice_accretion_6hr ,
    peak_wind_gust    ,
    peak_wind_drct    ,
    peak_wind_time    ,
    metar             
    """
sim-baz's avatar
sim-baz committed
232

sim-baz's avatar
sim-baz committed
233
234
235
236
237
238
239
'''
name: dropTableQuery
description: Create a cql query to drop the table
parameters:
    * table: Table name to drop
return: query to drop table
'''
sim-baz's avatar
sim-baz committed
240
def dropTableQuery(table):
Oscar Roisin's avatar
Oscar Roisin committed
241
242
243
    return f"""
        DROP TABLE IF EXISTS {table}
    """
sim-baz's avatar
sim-baz committed
244

sim-baz's avatar
sim-baz committed
245
246
247
248
249
250
251
'''
name: createTableQuery
description: Create a cql query to create a table with attributes, partitionned by station
parameters:
    * table: Table name to create
return: query to create table
'''
sim-baz's avatar
sim-baz committed
252
def createTableQuery(table):
Oscar Roisin's avatar
Oscar Roisin committed
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
    query = f"""CREATE TABLE {table}(
            station 			varchar,
            year				int,
            month				int,
            day					int,
            hour				int,
            minute				int,
            lon 				decimal,
            lat 				decimal,
            tmpf 				decimal,
            dwpf 				decimal,
            relh 				decimal,
            drct 				decimal,
            sknt 				decimal,
            p01i 				decimal,
            alti 				decimal,
            mslp 				decimal,
            vsby 				decimal,
            gust 				decimal,
            skyc1 				varchar,
            skyc2 				varchar,
            skyc3 				varchar,
            skyc4 				varchar,
            skyl1 				decimal,
            skyl2 				decimal,
            skyl3 				decimal,
            skyl4 				decimal,
            wxcodes           	varchar,
            feel              	decimal,
            ice_accretion_1hr 	decimal,
            ice_accretion_3hr 	decimal,
            ice_accretion_6hr 	decimal,
            peak_wind_gust    	decimal,
            peak_wind_drct    	decimal,
            peak_wind_time    	decimal,
            metar             	varchar,
            PRIMARY KEY((station), year, month, day, hour, minute)
        )"""
    return query
sim-baz's avatar
sim-baz committed
292

sim-baz's avatar
sim-baz committed
293
294
295
296
297
298
299
300

'''
name: createTableQueryPartitionningByDate
description: Create a cql query to create a table with attributes, partitionned by date
parameters:
    * table: Table name to create
return: query to create table
'''
sim-baz's avatar
sim-baz committed
301
def createTableQueryPartitionningByDate(table):
Oscar Roisin's avatar
Oscar Roisin committed
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
    query = f"""CREATE TABLE {table}(
            station 			varchar,
            year				int,
            month				int,
            day					int,
            hour				int,
            minute				int,
            lon 				decimal,
            lat 				decimal,
            tmpf 				decimal,
            dwpf 				decimal,
            relh 				decimal,
            drct 				decimal,
            sknt 				decimal,
            p01i 				decimal,
            alti 				decimal,
            mslp 				decimal,
            vsby 				decimal,
            gust 				decimal,
            skyc1 				varchar,
            skyc2 				varchar,
            skyc3 				varchar,
            skyc4 				varchar,
            skyl1 				decimal,
            skyl2 				decimal,
            skyl3 				decimal,
            skyl4 				decimal,
            wxcodes           	varchar,
            feel              	decimal,
            ice_accretion_1hr 	decimal,
            ice_accretion_3hr 	decimal,
            ice_accretion_6hr 	decimal,
            peak_wind_gust    	decimal,
            peak_wind_drct    	decimal,
            peak_wind_time    	decimal,
            metar             	varchar,
            PRIMARY KEY((year), month, day, station, hour, minute)
        )"""
    return query
sim-baz's avatar
sim-baz committed
341

sim-baz's avatar
sim-baz committed
342
343
344
345
346
347
348
'''
name: insertQueryData
description: Create a cql query to insert a row 
parameters: 
    * row: values for the attributes
    * table: Table name to create
'''
sim-baz's avatar
sim-baz committed
349
def insertQueryData(row, table):
Oscar Roisin's avatar
Oscar Roisin committed
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
    query = f"""
        INSERT INTO
            {table}(
                {NAME_COLUMNS}
            )
            VALUES(
                '{row["station"]}',
                {row["year"]},
                {row["month"]},
                {row["day"]},
                {row["hour"]},
                {row["minute"]},
                {row["lon"]},
                {row["lat"]},
                {row["tmpf"]},
                {row["dwpf"]},
                {row["relh"]},
                {row["drct"]},
                {row["sknt"]},
                {row["p01i"]},
                {row["alti"]},
                {row["mslp"]},
                {row["vsby"]},
                {row["gust"]},
                '{row["skyc1"]}',
                '{row["skyc2"]}',
                '{row["skyc3"]}',
                '{row["skyc4"]}',
                {row["skyl1"]},
                {row["skyl2"]},
                {row["skyl3"]},
                {row["skyl4"]},
                '{row["wxcodes"]}',
                {row["feel"]},
                {row["ice_accretion_1hr"]},
                {row["ice_accretion_3hr"]},
                {row["ice_accretion_6hr"]},
                {row["peak_wind_gust"]},
                {row["peak_wind_drct"]},
                {row["peak_wind_time"]},
                '{row["metar"]}'
            )
        ;
    """
    return query

sim-baz's avatar
sim-baz committed
396
# Not to execute when importing file
sim-baz's avatar
sim-baz committed
397
if __name__ == '__main__':
Oscar Roisin's avatar
Oscar Roisin committed
398
399
400
401
402
403
404
405
    cluster = Cluster()

    session = cluster.connect()

    session.set_keyspace("bazinsim_roisinos_metar")

    dict = loadata(FILE_NAME)

sim-baz's avatar
Details  
sim-baz committed
406
407
408
409
410
411
412
413
414
415
416
417
    # --------------------------------------------------------
    # A faire seulement 1 fois pour charger les données
    session.execute(dropTableQuery(table_name_space))
    print(f"Table {table_name_space} dropped")
    session.execute(createTableQuery(table_name_space))
    print(f"Table {table_name_space} created")

    print(f"Starting inserting datas into table {table_name_space}")
    for d in dict:
    	session.execute(insertQueryData(d, table_name_space))
    print(f"Datas inserted into {table_name_space}")
    # --------------------------------------------------------
Oscar Roisin's avatar
Oscar Roisin committed
418
419
420
421
422
423
424
425
426
427
428
429
430

    # --------------------------------------------------------
    # A faire seulement 1 fois pour charger les données
    session.execute(dropTableQuery(table_name_date))
    print(f"Table {table_name_date} dropped")
    session.execute(createTableQueryPartitionningByDate(table_name_date))
    print(f"Table {table_name_date} created")

    print(f"Starting inserting datas into table {table_name_date}")
    for d in dict:
        session.execute(insertQueryData(d, table_name_date))
    print(f"Datas inserted into {table_name_date}")
    # --------------------------------------------------------