db_weather.html
001| '''Weather Database Table classes.
001|
001| classes:
001| dbWeather (dbTable)
001|
001| '''
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from datetime import datetime
006| from os import path, rename
007| from logger import logger, info, debug, trace
008| from files import csvfile
009| from dates import CST
010| from dbsql import dbTable
011|
012| BasePath = r'C:\CJS\prj\Python\app\weather'
013| DataPath = path.join(BasePath, 'dat')
014| Log = logger('dbWeather')
015|
016|
017|
018| FirstYear = 1960
019| LastYear = 2024
020|
021|
022| FileNames = [
023| 'lcd_1960-1969.csv',
024| 'lcd_1970-1979.csv',
025| 'lcd_1980-1989.csv',
026| 'lcd_1990-1999.csv',
027| 'lcd_2000-2009.csv',
028| 'lcd_2010-2019.csv',
029| 'lcd_2020-2024.csv',
030| ]
031|
032|
033| Columns = [
034| "STATION","DATE","REPORT_TYPE","SOURCE","AWND",
035| "BackupDirection",
036| "BackupDistance",
037| "BackupDistanceUnit",
038| "BackupElements",
039| "BackupElevation",
040| "BackupElevationUnit",
041| "BackupEquipment",
042| "BackupLatitude",
043| "BackupLongitude",
044| "BackupName",
045| "CDSD","CLDD","DSNW","DYHF","DYTS",
046|
047| "DailyAverageDewPointTemperature",
048| "DailyAverageDryBulbTemperature",
049| "DailyAverageRelativeHumidity",
050| "DailyAverageSeaLevelPressure",
051| "DailyAverageStationPressure",
052| "DailyAverageWetBulbTemperature",
053| "DailyAverageWindSpeed",
054|
055| "DailyCoolingDegreeDays",
056| "DailyDepartureFromNormalAverageTemperature",
057| "DailyHeatingDegreeDays",
058| "DailyMaximumDryBulbTemperature",
059| "DailyMinimumDryBulbTemperature",
060| "DailyPeakWindDirection",
061| "DailyPeakWindSpeed",
062| "DailyPrecipitation",
063| "DailySnowDepth",
064| "DailySnowfall",
065| "DailySustainedWindDirection",
066| "DailySustainedWindSpeed",
067| "DailyWeather",
068|
069| "HDSD",
070| "HTDD",
071| "HourlyAltimeterSetting",
072| "HourlyDewPointTemperature",
073| "HourlyDryBulbTemperature",
074| "HourlyPrecipitation",
075| "HourlyPresentWeatherType",
076| "HourlyPressureChange",
077| "HourlyPressureTendency",
078| "HourlyRelativeHumidity",
079| "HourlySeaLevelPressure",
080| "HourlySkyConditions",
081| "HourlyStationPressure",
082| "HourlyVisibility",
083| "HourlyWetBulbTemperature",
084| "HourlyWindDirection",
085| "HourlyWindGustSpeed",
086| "HourlyWindSpeed",
087|
088| "MonthlyAverageRH",
089| "MonthlyDaysWithGT001Precip",
090| "MonthlyDaysWithGT010Precip",
091| "MonthlyDaysWithGT32Temp",
092| "MonthlyDaysWithGT90Temp",
093| "MonthlyDaysWithLT0Temp",
094| "MonthlyDaysWithLT32Temp",
095| "MonthlyDepartureFromNormalAverageTemperature",
096| "MonthlyDepartureFromNormalCoolingDegreeDays",
097| "MonthlyDepartureFromNormalHeatingDegreeDays",
098| "MonthlyDepartureFromNormalMaximumTemperature",
099| "MonthlyDepartureFromNormalMinimumTemperature",
100| "MonthlyDepartureFromNormalPrecipitation",
101| "MonthlyDewpointTemperature",
102| "MonthlyGreatestPrecip",
103| "MonthlyGreatestPrecipDate",
104| "MonthlyGreatestSnowDepth",
105| "MonthlyGreatestSnowDepthDate",
106| "MonthlyGreatestSnowfall",
107| "MonthlyGreatestSnowfallDate",
108| "MonthlyMaxSeaLevelPressureValue",
109| "MonthlyMaxSeaLevelPressureValueDate",
110| "MonthlyMaxSeaLevelPressureValueTime",
111| "MonthlyMaximumTemperature",
112| "MonthlyMeanTemperature",
113| "MonthlyMinSeaLevelPressureValue",
114| "MonthlyMinSeaLevelPressureValueDate",
115| "MonthlyMinSeaLevelPressureValueTime",
116| "MonthlyMinimumTemperature",
117| "MonthlySeaLevelPressure",
118| "MonthlyStationPressure",
119| "MonthlyTotalLiquidPrecipitation",
120| "MonthlyTotalSnowfall",
121| "MonthlyWetBulb",
122|
123| "NormalsCoolingDegreeDay",
124| "NormalsHeatingDegreeDay",
125| "REM",
126| "REPORT_TYPE",
127| "SOURCE",
128|
129| "ShortDurationEndDate005",
130| "ShortDurationEndDate010",
131| "ShortDurationEndDate015",
132| "ShortDurationEndDate020",
133| "ShortDurationEndDate030",
134| "ShortDurationEndDate045",
135| "ShortDurationEndDate060",
136| "ShortDurationEndDate080",
137| "ShortDurationEndDate100",
138| "ShortDurationEndDate120",
139| "ShortDurationEndDate150",
140| "ShortDurationEndDate180",
141| "ShortDurationPrecipitationValue005",
142| "ShortDurationPrecipitationValue010",
143| "ShortDurationPrecipitationValue015",
144| "ShortDurationPrecipitationValue020",
145| "ShortDurationPrecipitationValue030",
146| "ShortDurationPrecipitationValue045",
147| "ShortDurationPrecipitationValue060",
148| "ShortDurationPrecipitationValue080",
149| "ShortDurationPrecipitationValue100",
150| "ShortDurationPrecipitationValue120",
151| "ShortDurationPrecipitationValue150",
152| "ShortDurationPrecipitationValue180",
153|
154| "Sunrise",
155| "Sunset",
156| "WindEquipmentChangeDate"
157| ]
158| GetColIndex = lambda n: Columns.index(n)
159|
160| csvColNames = [
161| 'DATE',
162| 'REPORT_TYPE',
163| "Sunrise",
164| "Sunset",
165| 'DailyMinimumDryBulbTemperature',
166| 'DailyMaximumDryBulbTemperature',
167| 'DailyAverageDryBulbTemperature',
168| 'DailyAverageWetBulbTemperature',
169| 'DailyAverageDewPointTemperature',
170| 'DailyAverageRelativeHumidity',
171| "DailyAverageStationPressure",
172| 'DailyPrecipitation',
173| 'DailySnowfall',
174|
175| "HourlyDryBulbTemperature",
176| "HourlyWetBulbTemperature",
177| "HourlyDewPointTemperature",
178| "HourlyRelativeHumidity",
179| "HourlyStationPressure",
180| "HourlyPrecipitation",
181| ]
182| csvReportTypes = {
183| 'SAO': {'n': 218346, 'fs':['Hourly']},
184| 'SOD': {'n': 10338, 'fs':['Backup', 'Daily', 'Sun']},
185| 'SOM': {'n': 328, 'fs':['Backup', 'Monthly']},
186| 'FM-12': {'n': 29281, 'fs':['Backup', 'Hourly']},
187| 'FM-15': {'n': 243025, 'fs':['Backup', 'Hourly']},
188| 'FM-16': {'n': 58210, 'fs':['Backup', 'Hourly']},
189| 'SHEF': {'n': 572, 'fs':['Backup', 'ChangeDate']},
190| 'SY-SA': {'n': 31439, 'fs':['Hourly']},
191| 'SY-MT': {'n': 11069, 'fs':['Hourly']},
192| 'AUTO': {'n': 2, 'fs':[]}
193| }
194|
195|
196|
197| class dbWeather (dbTable):
198| '''LCD Weather Data for KMSP (WBAN:14922).'''
199| dbName = 'lcd_kmsp.sqlite'
200| dataPath = DataPath
201| tabName = 'LCD'
202| tabCols = [ '"line_date" TEXT NOT NULL',
203| '"line_type" TEXT NOT NULL',
204| '"sunrise" TEXT DEFAULT NULL',
205| '"sunset" TEXT DEFAULT NULL',
206| '"daily_min_temp" TEXT DEFAULT NULL',
207| '"daily_max_temp" TEXT DEFAULT NULL',
208| '"daily_avg_temp" TEXT DEFAULT NULL',
209| '"daily_wet_bulb" TEXT DEFAULT NULL',
210| '"daily_dew_point" TEXT DEFAULT NULL',
211| '"daily_humidity" TEXT DEFAULT NULL',
212| '"daily_pressure" TEXT DEFAULT NULL',
213| '"daily_rain_fall" TEXT DEFAULT NULL',
214| '"daily_snow_fall" TEXT DEFAULT NULL',
215|
216| '"hourly_temp" TEXT DEFAULT NULL',
217| '"hourly_web_bulb" TEXT DEFAULT NULL',
218| '"hourly_dew_point" TEXT DEFAULT NULL',
219| '"hourly_humidity" TEXT DEFAULT NULL',
220| '"hourly_pressure" TEXT DEFAULT NULL',
221| '"hourly_precip" TEXT DEFAULT NULL',
222| ]
223| tabData = []
224|
225| def __init__(self):
226| super().__init__(path.join(DataPath,self.dbName), self.tabName, self.tabCols)
227|
228| def create_table (self):
229| self.Log.info('Create Table')
230| cxs = [GetColIndex(n) for n in csvColNames]
231|
232| for fname in FileNames:
233| fn = path.join(DataPath, fname)
234| fo = csvfile(fn, log=self.Log)
235| fo.load()
236| print(f'loaded: {fname}, {len(fo)} records ({len(fo.hdrs)} columns)')
237| nrcds = 0
238| for line in fo:
239| rcd = [line[cx] for cx in cxs]
240| if rcd[1] in ['SAO','FM-12','FM-15','FM-16','SOD','SY-MT','SY-SA']:
241| self.tabData.append(rcd)
242| nrcds += 1
243| print(f'selected: {nrcds} records')
244| print(f'updating: {len(self.tabData)} records.')
245|
246|
247| self.db_create()
248| self.db_insert_many(self.tabData)
249|
250| def destroy_table (self):
251| super().destroy_table('Destroy Table')
252|
253| def list_to_file (self, fname='lcd_kmsp.list', fpath=dataPath):
254| self.Log.debug('db[%s] ListToFile' % self.name)
255| sql = 'SELECT * FROM "%s" ORDER BY "line_date"' % self.name
256| fn = path.join(fpath, fname)
257| fp = open(fn, mode='w', encoding='utf-8')
258| try:
259| rs = self.db_query(sql)
260| if not rs: Log.warn('No data!'); return []
261| for r in rs:
262| print(r, file=fp)
263| print(file=fp)
264| self.Log.info('wrote: %s' % fn)
265| except:
266| raise
267| finally:
268| fp.close()
269|
270|
271|
272| def do_table_make (**kwargs):
273| '''CMND: DB Table Make.'''
274| Log.info('table-make:: %s' % str(list(kwargs.keys())))
275|
276|
277| dbname_old = path.join(dbWeather.dataPath, dbWeather.dbName)
278| if path.exists(dbname_old) and path.isfile(dbname_old):
279| now = datetime.now(tz=CST())
280| sdt = now.strftime('%Y%d%m%H%M')
281| dbname_new = dbname_old.replace('.sqlite', f'_{sdt}.sqlite')
282| rename(dbname_old, dbname_new)
283|
284|
285| tbl = dbWeather()
286| tbl.create_table()
287| return 'Done'
288|
289| def do_table_drop (**kwargs):
290| '''CMND: DB Table Drop.'''
291| Log.info('table-drop:: %s' % str(list(kwargs.keys())))
292| tbl = dbWeather()
293| tbl.destroy_table()
294| return 'Done'
295|
296| def do_table_list (**kwargs):
297| '''CMND: DB Table List.'''
298| Log.info('table-list:: %s' % str(list(kwargs.keys())))
299| fpath = kwargs['fpath'] if 'fpath' in kwargs else BasePath
300| fname = kwargs['fname'] if 'fname' in kwargs else 'weather.list'
301| tbl = dbWeather()
302| tbl.list_to_file(fname=fname, fpath=fpath)
303| return 'Done'
304|
305|
306| def do_chart (**kwargs):
307| '''CMND: Chart.'''
308| Log.info('table-chart:: %s' % str(list(kwargs.keys())))
309| fpath = kwargs['fpath'] if 'fpath' in kwargs else BasePath
310| fname = kwargs['fname'] if 'fname' in kwargs else 'weather.png'
311| tbl = dbWeather()
312|
313| return 'Done'
314|
315|
316| SQL = '''
316| SELECT
316| "line_date", "line_type", "hourly_temp"
316| FROM "%s"
316| WHERE ("line_type" = 'SAO')
316| OR (substr("line_type",1,2) = 'FM')
316| OR (substr("line_type",1,2) = 'SY')
316| ORDER BY "line_date"
316| '''
317|
318| def do_query (**kwargs):
319| '''CMND: Query.'''
320| Log.info('query:: %s' % str(list(kwargs.keys())))
321| fpath = kwargs['fpath'] if 'fpath' in kwargs else BasePath
322| fname = kwargs['fname'] if 'fname' in kwargs else 'query.list'
323| tbl = dbWeather()
324|
325| fn = path.join(fpath, fname)
326| fp = open(fn, mode='w', encoding='utf-8')
327| try:
328| rs = tbl.db_query(SQL % tbl.name)
329| if not rs: Log.warn('No data!'); return []
330| for r in rs:
331| sdt = r[0]
332| stemp = r[2]
333| if (len(stemp) == 0) or (stemp == '*'):
334| continue
335| dt = datetime.fromisoformat(sdt)
336| temp = int(stemp[:-1] if stemp.endswith('s') else stemp)
337| print(f'{dt:%Y-%m-%d} {temp:+4d}', file=fp)
338| print(file=fp)
339| Log.info('wrote: %s' % fn)
340| except:
341| raise
342| finally:
343| fp.close()
344|
345| return 'Done'
346|
347|
348| def do_test (**kwargs):
349| Log.info('test:: %s' % str(list(kwargs.keys())))
350| fpath = kwargs['fpath'] if 'fpath' in kwargs else BasePath
351| fname = kwargs['fname'] if 'fname' in kwargs else 'test.list'
352| tbl = dbWeather()
353|
354| return 'Done'
355|
356| def dispatch (cmd, **kwargs):
357| Log.info('command: %s' % cmd)
358| for kw in kwargs:
359| Log.info('argument[%s]: %s' % (kw,kwargs[kw]))
360| Log.info()
361| if cmd == 'query': return do_query(**kwargs)
362|
363| if cmd == 'list': return do_table_list(**kwargs)
364| if cmd == 'make': return do_table_make(**kwargs)
365| if cmd == 'drop': return do_table_drop(**kwargs)
366|
367| if cmd == 'test': return do_test(**kwargs)
368| return 'Nothing to do!'
369|
370| if __name__ == '__main__':
371| print('autorun: %s' % argv[0])
372| Log.start(path.join(BasePath,'db_weather.log'))
373| Log.level(trace())
374| cmd = argv[1] if 1 < len(argv) else ''
375| kwargs = {}
376| for a in argv[2:]:
377| nv = a.split('=', 1)
378| kwargs[nv[0]] = nv[1] if 1 < len(nv) else ''
379| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
380| try:
381| obj = dispatch(cmd, **kwargs)
382| print(obj)
383| Log.info(obj)
384| except:
385| etype, evalue, tb = exc_info()
386| ts = extract_tb(tb)
387| Log.error()
388| Log.error('%s: %s' % (etype.__name__,str(evalue)))
389| for t in ts[-5:]:
390| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
391| Log.error(' %s' % t[3])
392| raise
393| finally:
394| Log.end()
395|
396| '''eof'''
397|