-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateWeather.py
More file actions
executable file
·424 lines (340 loc) · 14.1 KB
/
GenerateWeather.py
File metadata and controls
executable file
·424 lines (340 loc) · 14.1 KB
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
#==============================================================================
#Title :GenerateWeatherData.py
#Description :
#
# :This is used to generate weather data using python
#Author :Mohamed Asimulla S
#Date :22/04/2017
#Version :1.0
#Usage :GenerateWeather.py <Location>
#Output :Out_Weather_Report.txt
#Notes :
#Limitation: :Desgined to work with one input variable
# :Generate weather information based on location
# :Melbourne
# List of locations details : Adelaide, Perth, London, Melbourne,Moscow, Ottawa, Paris, Seoul, Shanghai, Singapore, Sydney, Tokyo,Toronto
#==============================================================================
import time
import random
import sys
import string
import os
import datetime
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
import geocoder
from random import choice
from time import sleep
import pytz
'''
Function: to Initialise weather condition
'''
def init_weather_condition(temperature_range=[],location_temperature=[],humidity_range=[],location_humidity=[]):
# Range of temperature, simulate cold, warm and hot areas temperature ranges. Using dictionary.
temperature_range['cold']="-11,24"
temperature_range['warm']="12,30"
temperature_range['hot']="18,40"
# Type of locations. Classify locations areas by cold, warm & hot. Using dictionary.
location_temperature['Adelaide']="hot"
location_temperature['Perth']="hot"
location_temperature['London']="cold"
location_temperature['Melbourne']="cold"
location_temperature['Moscow']="cold"
location_temperature['Ottawa']="cold"
location_temperature['Paris']="cold"
location_temperature['Seoul']="cold"
location_temperature['Shanghai']="warm"
location_temperature['Singapore']="hot"
location_temperature['Sydney']="cold"
location_temperature['Tokyo']="warm"
location_temperature['Toronto']="cold"
# Range of humidity, simulate seaside & non-seaside areas humidity. Using dictionary.
humidity_range['seaside']="65,100"
humidity_range['notseaside']="33,80"
# Type of locations. Classify locations areas by seaside & non-seaside. Using dictionary.
location_humidity['Adelaide']="seaside"
location_humidity['Melbourne']="notseaside"
location_humidity['Brisbane']="notseaside"
location_humidity['Sydney']="seaside"
location_humidity['Perth']="seaside"
location_humidity['London']="notseaside"
location_humidity['Miami']="notseaside"
location_humidity['Moscow']="notseaside"
location_humidity['New_York']="notseaside"
location_humidity['Ottawa']="notseaside"
location_humidity['Paris']="notseaside"
location_humidity['Seoul']="notseaside"
location_humidity['Shanghai']="seaside"
location_humidity['Singapore']="seaside"
location_humidity['Tokyo']="seaside"
location_humidity['Toronto']="notseaside"
'''
Function: to generator lantitude & longtitude based on city name
'''
def perform_geocode(geolocator,address):
try:
if "_" in address:
address = string.replace(address,'_',' ')
sleep(1)
return geolocator.geocode(address,timeout=None)
except GeocoderTimedOut:
print ("GeoPy API policy restriction on query frequency. Wait 1s to re-try.")
return perform_geocode(geolocator,address)
except:
print ("Error: geocode has failed on input %s with message %s" %(address, sys.exc_info()[0]))
exit(3)
'''
Function: to Initialise location values
'''
def init_location_values(location_label=[],timezone_location=[],city=[]):
'''
Initialise location labels
'''
location_label['Adelaide']="Adelaide"
location_label['Perth']="Perth"
location_label['London']="London"
location_label['Melbourne']="Melbourne"
location_label['Moscow']="Moscow"
location_label['Ottawa']="Ottawa"
location_label['Paris']="Paris"
location_label['Seoul']="Seoul"
location_label['Shanghai']="Shanghai"
location_label['Singapore']="Singapore"
location_label['Sydney']="Sydney"
location_label['Tokyo']="Tokyo"
location_label['Toronto']="Toronto"
'''
Initialise TimeZone details
'''
timezone_location['Adelaide']="Australia/Adelaide"
timezone_location['Perth']="Etc/GMT+8"
timezone_location['London']="Etc/GMT+1"
timezone_location['Melbourne']="Australia/Melbourne"
timezone_location['Moscow']="Etc/GMT+3"
timezone_location['Ottawa']="Etc/GMT-4"
timezone_location['Paris']="Etc/GMT+2"
timezone_location['Seoul']="Etc/GMT+9"
timezone_location['Shanghai']="Asia/Shanghai"
timezone_location['Singapore']="Asia/Singapore"
timezone_location['Sydney']="Australia/Sydney"
timezone_location['Tokyo']="Etc/GMT+9"
timezone_location['Toronto']="Etc/GMT+9"
weather_data_structure=location_label.get(city) + "|"
return weather_data_structure
'''
Function: to get location
'''
def get_location(weather_data_structure=[],location_label=[],city=[]):
'''
Begin to prepare the weather data structure
'''
weather_data_structure=location_label.get(city) + "|"
return weather_data_structure
'''
Function: to get geo location
'''
def get_geolocaiton(weather_data_structure=[],Out_Location_File=[],city=[]):
'''
In order to generate city's lantitude and longtitude information.
python GeoPy package is required.
'''
# Get this python program full path to let use can program anywhere.
absolute_directory_path = os.path.dirname(os.path.abspath(sys.argv[0]))
geolocations_file_data = absolute_directory_path + Out_Location_File
# Initial geolocation dictionary to store written data.
geolocaiton = {}
'''
Instead of calling GeoPy use policy everytime
we will write location into a file. In the next
query request, the program will read the data from the file directly.
Format in the file: [city],[lantitude],[longtitude]
'''
# Check whether the file exist or not
if os.path.isfile(geolocations_file_data):
filereaderlocation = open(geolocations_file_data,'r')
for line in filereaderlocation:
temp = line.strip().split(',')
geolocaiton[temp[0]] = temp[1] + "," + temp[2]
filereaderlocation.close()
# Check whether the input city exists in the location file.
if not geolocaiton.has_key(city):
filewriterlocation = open(geolocations_file_data,'a')
geolocator = Nominatim()
location = perform_geocode(geolocator,city.lower())
lan = location.latitude
lon = location.longitude
filewriterlocation.write(city + "," + str(round(float(lan),2)) + "," + str(round(float(lon),2)) + "\n")
filewriterlocation.close()
else:
location = geolocaiton.get(city)
lan = location.split(',')[0]
lon = location.split(',')[1]
# Write into the weather data structure
weather_data_structure = weather_data_structure + str(round(float(lan),2)) + "," + str(round(float(lon),2)) + ","
'''
The following part generate city's altitude.
geocoder package required.
'''
g = geocoder.elevation([lan,lon])
alt = g.meters
# Write into the weather data structure
weather_data_structure = weather_data_structure + str(int(alt)) + "|"
return weather_data_structure
'''
Function: to get local time
'''
def get_local_time(weather_data_structure=[],timezone_location=[],city=[]):
'''
Get current time using standard format
'''
ts = time.time()
st = datetime.datetime.fromtimestamp(ts,pytz.timezone(timezone_location.get(city))).strftime('%Y-%m-%dT%H:%M:%SZ')
# Write into the weather data structure
weather_data_structure = weather_data_structure + st + "|"
return weather_data_structure
'''
Function: to get weather condition
'''
def get_weather_condition(weather_data_structure=[],conditions=[]):
'''
Randomly get weather conditions
'''
weather_data_structure = weather_data_structure + choice(conditions) + "|"
return weather_data_structure
'''
Function: to get temperature
'''
def get_temperature( weather_data_structure=[],temperature_range=[],location_temperature=[],city=[]):
'''
Randomly get temperature details
'''
range_temperature = temperature_range.get(location_temperature.get(city))
low_temperature = int(range_temperature.split(',')[0])
high_temperature = int(range_temperature.split(',')[1])
weather_data_structure = weather_data_structure + str(round(random.uniform(low_temperature,high_temperature),1)) + "|"
return weather_data_structure
'''
Function: to get pressure
'''
def get_pressure( weather_data_structure=[]):
'''
Randomly get pressure data
'''
# Range of pressure, high & low as int.
high=1200
low=800
weather_data_structure = weather_data_structure + str(round(random.uniform(low,high),1)) + "|"
return weather_data_structure
'''
Function: to get humidity
'''
def get_humidity( weather_data_structure=[],humidity_range=[],location_humidity=[],city=[]):
'''
Randomly get humidity data
'''
range_humidity = humidity_range.get(location_humidity.get(city))
low_humidity = float(range_humidity.split(',')[0])
high_humidity = float(range_humidity.split(',')[1])
weather_data_structure = weather_data_structure + str(int(random.uniform(low_humidity,high_humidity)))
return weather_data_structure
'''
Function: to prepare in memory data structures
'''
def prepareData(Out_Location_File,temperature_range=[], location_temperature=[],humidity_range=[],location_humidity=[],location_label=[],timezone_location=[],city=[],weather_data_structure=[],conditions=[]):
# Get location data
weather_data_structure_Loc=get_location(weather_data_structure,location_label,city)
# Get city's lantitude and longtitude.
weather_data_structure_geo=get_geolocaiton(weather_data_structure_Loc,Out_Location_File,city)
# Get current time using standard format
weather_data_structure_time=get_local_time(weather_data_structure_geo,timezone_location,city)
# Get Weather Condition
weather_data_structure_cond=get_weather_condition(weather_data_structure_time,conditions)
# Get Temperature
weather_data_structure_temp=get_temperature(weather_data_structure_cond,temperature_range,location_temperature,city)
# Get Pressure
weather_data_structure_press=get_pressure(weather_data_structure_temp)
# Get humidity
weather_data_structure_humidit=get_humidity(weather_data_structure_press,humidity_range,location_humidity,city)
return weather_data_structure_humidit
'''
Function: to flush memory data structure into a file
'''
def writeData_to_File(Out_Weather_Report_File, weather_data_structure=[],location_label=[],city=[]):
weather_infomation = {}
absolute_directory_path = os.path.dirname(os.path.abspath(sys.argv[0]))
# Specify the file name and path of the output
file_path = absolute_directory_path + Out_Weather_Report_File
if os.path.isfile(file_path):
filereader = open(file_path,'r')
'''
Check if there is any historic city weather information data that can be used.
'''
for line in filereader:
temp = line.split('|')
weather_infomation[temp[0]] = line.strip()
# Update the latest information
weather_infomation[location_label.get(city)] = weather_data_structure
#close the file reader pointer
filereader.close()
# Writing data into table format
filewriter = open(file_path,'w')
if len(weather_infomation.keys()) == 0:
filewriter.write( weather_data_structure + "\n")
else:
for key in weather_infomation:
filewriter.write(weather_infomation[key] + "\n")
#close the file writer pointer
filewriter.close()
'''
Function: to release rescources to OS
'''
def cleanup():
print("...")
def is_input_args_valid(city=[]):
# Verify the arguments
if len(sys.argv) != 2:
print ("The no. of arguments specified are not correct. Please check and retry.")
print ("Usage: python WeatherGenerator.py <Location>")
print ("List of locations: Adelaide, Perth, London, Melbourne, Moscow, Ottawa, Paris, Seoul, Shanghai, Singapore, Sydney, Tokyo,Toronto")
exit(1)
# List of locations, which can generate weather report
list_of_loctions=['Adelaide', 'Perth', 'London', 'Melbourne', 'Moscow', 'Ottawa', 'Paris', 'Seoul', 'Shanghai', 'Singapore', 'Sydney', 'Tokyo','Toronto']
# Verify the city, which user is going to input
city=sys.argv[1]
if not city in list_of_loctions:
print ("%s is not recognized. Please choose from list of locations specified below." %city)
print ("Usage: python WeatherGenerator.py <Location>")
print ("List of valid locations: Adelaide, Perth, London, Melbourne, Moscow, Ottawa, Paris, Seoul, Shanghai, Singapore, Sydney, Tokyo,Toronto")
exit(2)
return city
'''
Main Function:
'''
def main():
#input file
InputFile = ""
#Output files
Out_Weather_Report_File = "/Out_Weather_Report.txt"
Out_Location_File = "/Location.txt"
# Initalise data variables
conditions=['Rain','Snow','Sunny']
temperature_range={}
location_temperature={}
humidity_range={}
location_humidity={}
location_label={}
timezone_location={}
city=[]
#Validate input args
city=is_input_args_valid(city)
# Initalise the data set.
weather_data_structure=init_location_values(location_label,timezone_location,city)
# Initalise the data set.
init_weather_condition(temperature_range,location_temperature,humidity_range,location_humidity)
# Prepare the data set with in memory data structure
weather_data_structure_result=prepareData(Out_Location_File,temperature_range, location_temperature,humidity_range,location_humidity, location_label,timezone_location,city, weather_data_structure,conditions)
# Load the data set to a Persistant file system
writeData_to_File(Out_Weather_Report_File,weather_data_structure_result,location_label,city)
#release the OS resources
cleanup()
main()