-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfuncs_io.py
575 lines (440 loc) · 17.6 KB
/
funcs_io.py
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# -*- coding: utf-8 -*-
"""
Main functions for processing input/output of tables, files, etc.
@author: Mino Sorribas
"""
import os
import sys
import numpy as np
import pandas as pd
import geopandas as gpd
import pickle
import json
#-----------------------------------------------------------------------------
# FUNCTIONS TO READ MGB TOPOLOGY
#-----------------------------------------------------------------------------
def read_tble_mini(file_mini, mgb_version = 'MGB-AS', set_index = None):
"""
Read mini.xlsx, adjust headers and return as dataframe
Args:
file_mini(str) :: pathfile to 'mini.xlsx' (mini.gtp in MSExcel format)
mgb_version(str) :: version of table for header mapping
set_index(str,optional) :: column name to use as index
Returns:
df_tble_mini(pd.DataFrame) :: table mini with proper headers
Notes:
- mgb_version must be a a key of version_map (dict), which handles
different versions of MGB columns.
"""
# read mini.xlsx
df_tble_mini = pd.read_excel(file_mini)
# adjust 'mini' column name by version
version_map = {
'MGB-AS':{'Mini':'mini'},
'MGB-QGIS':{'Mini_ID':'mini'},
}
# adjust 'mini' reference by version
df_tble_mini = df_tble_mini.rename(columns = version_map[mgb_version])
# adjust headers (make lowercase)
func_str = lambda s: s.lower().replace("/","_").replace("(","").replace(")","")
header_lower = {v:func_str(v) for v in df_tble_mini.columns}
df_tble_mini = df_tble_mini.rename(columns = header_lower)
# optional: column 'mini' as dataframe index
if set_index == 'mini':
df_tble_mini = df_tble_mini.set_index('mini',drop=False)
return df_tble_mini
#-----------------------------------------------------------------------------
# FUNCTIONS TO READ AND FILTER TABLE TYPE 1
#-----------------------------------------------------------------------------
def f_test_area(a_diff_perc, area_to_test):
"""
Function to test if error in area is acceptable for type 1 association
based on table below
ad hoc criteria by Vinicius Siqueira
area_lb area_ub max_error
0 1500 30
1500 3000 25
3000 5000 20
5000 10000 15
10000 20000 10
20000 50000 7
50000 200000 5
200000 500000 3
500000 1000000 2
1000000 6000000 1.5
Args:
a_diff_perc (float) :: relative error in area
area_to_test (float) :: drainage area [km2]
Returns:
accept (bool):: True(False) for accepted (or not)
"""
# sets table - based on MATLAB algorithm for type 1
tble_area_min = [0., 1500., 3000., 5000., 10000., 20000., 50000., 200000., 500000., 1000000.]
tble_area_max = [1500., 3000., 5000., 10000., 20000., 50000., 200000., 500000., 1000000., 6000000.]
tble_area_tol = [30., 25., 20., 15., 10., 7., 5., 3., 2., 1.5]
# begin table search
accept = False
npts = len(tble_area_tol)
for j in range(npts):
# find position in table
if (area_to_test >= tble_area_min[j]) & (area_to_test < tble_area_max[j]):
# test if is acceptable
a_thre = tble_area_tol[j]
accept = a_diff_perc < a_thre
break
return accept
def f_area_acceptable_t1(row, iostat=False):
"""
Row-based function to test area errors as in criteria for type 1 association
Usage:
iaccept = df_tble_t1.apply(f_area_acceptable_t1,axis=1)
Args:
row (pd.Series) :: row of df_tble_t1
iostat (bool) :: true/false to print on screen
Returns:
accept (pd.DataFrame) :: True/False for each row (same index as dataframe)
"""
# get row values from df_tble_t1
area_to_test = row['bho_nuareamont']
a_diff_perc = np.abs(row['diffp_areamont'])
# function to test area
accept = f_test_area(a_diff_perc, area_to_test)
if iostat == True:
if accept:
print(" area {} km² - error {} % < {} %: accepted".format(area_to_test,a_diff_perc, a_thre))
else:
print(" area {} km² - error {} % < {} %: rejected".format(area_to_test,a_diff_perc, a_thre))
return accept
def read_tble_t1(file_tble_t1, sheet_name='Data', tol_t1 = True, tol_diffp = None):
"""
Read and pre-processing of 'tabela_tipo_1.xlsx'
and returns as dataframe
Args:
file_tble_t1 (str) :: pathfile to (table_t1.xlsx) with table 1 data
sheet_name (str) :: sheet_name with data in file_tble_t1
tol_t1 (bool) :: True - apply f_area_acceptable
tol_diffp (float) :: None (default), else apply filter by absolute
error in area <= tol_diffp
Returns:
df_tble_t1(pd.DataFrame) :: table type 1
Notes:
Pre-processing includes
- it adjust headers
- it calculates abs relative error in drainage area
- it removes duplicated 'cotrecho' (priorizes smaller erros)
- it removes rows with above tolerance (tol_diffp)
- check variable header_xls for required column names
TODO: talk to JB/VS to change standard header in file_tble_t1(.xls)
Equivalent of older versions
- funcs_io.read_tble_t1(FILE_TBLE_T1, tol_t1 = False)
- funcs_io.read_tble_t1(FILE_TBLE_T1, tol_t1 = False, tol_diffp = tol_diffp) #old
"""
try: #table from matlab
# required columns
header_xls = ['Mini','cotrecho','codigo_otto','AreaM_BHO','AreaM_MGB',
'Diff(%)','Lat','Lon','Flag_mini_in']
# mapping new headers
header_map = {
'Mini':'mini',
'cotrecho':'bho_cotrecho',
'AreaM_BHO':'bho_nuareamont',
'AreaM_MGB':'mini_areamont',
'Diff(%)':'diffp_areamont',
'Lat':'latitude',
'Lon':'longitude',
'codigo_otto':'codigo_otto',
'Flag_mini_in':'flag_mini_in'
}
# read file and adjust headers
df_tble_t1 = pd.read_excel(file_tble_t1,sheet_name=sheet_name)
df_tble_t1 = df_tble_t1[header_xls]
df_tble_t1 = df_tble_t1.rename(columns=header_map)
print(" -- table 1 from matlab")
except: #table made in python
# required columns
header_xls = ['mini', 'bho_cotrecho', 'codigo_otto', 'bho_nuareamont',
'mini_areamont', 'diffp_areamont', 'latitude', 'longitude',
'flag_mini_in']
df_tble_t1 = pd.read_excel(file_tble_t1)
df_tble_t1 = df_tble_t1[header_xls]
print(" -- table 1 from python")
# calculate relative error in drainage area
# reference to bho (#ms)
#df_tble_t1['abs_diffp2'] = abs(100.*(df_tble_t1['mini_areamont']/df_tble_t1['bho_nuareamont']-1.))
# reference to mgb (like table t1)
df_tble_t1['abs_diffp'] = abs(100.*(df_tble_t1['bho_nuareamont']/df_tble_t1['mini_areamont']-1.))
# remove nulls and duplicates (keep smaller error)
df_tble_t1 = df_tble_t1[df_tble_t1['bho_cotrecho'].notna()]
df_tble_t1 = df_tble_t1.sort_values('abs_diffp').drop_duplicates('bho_cotrecho',keep='first')
# calculate bho/mgb area ratio
df_tble_t1['area_ratio'] = df_tble_t1['bho_nuareamont']/df_tble_t1['mini_areamont']
# filter based on table 1 criteria
if tol_t1:
iaccept = df_tble_t1.apply(f_area_acceptable_t1,axis=1)
df_tble_t1 = df_tble_t1[iaccept]
# optional: remove rows by tol_diffp
if tol_diffp:
df_tble_t1 = df_tble_t1[df_tble_t1['abs_diffp'] <= tol_diffp]
return df_tble_t1
#-----------------------------------------------------------------------------
# FUNCTIONS TO READ BHO GEOPACKAGE OR TABLE
#-----------------------------------------------------------------------------
def read_gdf_bho(file_gdf_bho):
"""
Read geopackage file with BHO drainage (cotrecho)
adjust dtypes and returns as geodataframe
Args:
file_gdf_bho(str) :: pathfile to BHO drainage in .gpkg/shp
Returns:
gdf_tble_bho (gpd.GeoDataFrame) :: table for BHO drainage (polyline)
Notes:
- see required columns in variable 'cols'
"""
gdf_tble_bho = gpd.GeoDataFrame.from_file(file_gdf_bho)
# save crs for later
crs = gdf_tble_bho.crs
# required cols
cols = ['cotrecho','cobacia',
'nucomptrec','nuareacont','nuareamont',
'nutrjus','dedominial','nustrahler',
'nuordemcda','cocursodag','cocdadesag','nudistbact',
'nunivotto',
'geometry',
]
gdf_tble_bho = gdf_tble_bho[cols]
# apply dtypes
bho_dtypes = {
'fid':pd.Int64Dtype(),
'drn_pk':int,
'cotrecho':int,
'noorigem':int,
'nodestino':int,
'cocursodag':str,
'cobacia':str,
'nucomptrec':float,
'nudistbact':float,
'nudistcdag':float,
'nuareacont':float,
'nuareamont':float,
'nogenerico':str,
'noligacao':str,
'noespecif':str,
'noriocomp':str,
'nooriginal':str,
'cocdadesag':str,
'nutrjus':pd.Int32Dtype(),
'nudistbacc':float,
'nuareabacc':float,
'nuordemcda':pd.Int32Dtype(),
'nucompcda':float,
'nunivotto':int,
'nunivotcda':pd.Int32Dtype(),
'nustrahler':pd.Int32Dtype(),
'dedominial':str,
'dsversao':str,
'cobacia_50k':str,
'lat':float,
'lon':float,
}
hmap = {k:v for k,v in bho_dtypes.items() if k in gdf_tble_bho.columns}
gdf_tble_bho = gdf_tble_bho.astype(hmap)
#recover crs
gdf_tble_bho.crs = crs
#make spatial index
gdf_tble_bho.sindex
return gdf_tble_bho
def read_tble_bho(file_tble_bho):
"""
Read BHO table in MSExcel format
adjust dtypes and returns as dataframe
Args:
file_tble_bho(str) :: pathfile (in MSExcel format)
Returns:
df_tble_bho (pd.DataFrame) :: BHO drainage table
Notes:
- see required columns in variable 'cols'
"""
df_tble_bho = pd.read_excel(file_tble_bho)
# required cols
cols = ['cotrecho','cobacia',
'nucomptrec','nuareacont','nuareamont',
'nutrjus','dedominial','nustrahler',
'nuordemcda','cocursodag','cocdadesag','nudistbact',
'nunivotto',
]
df_tble_bho = df_tble_bho[cols]
# apply dtypes
bho_dtypes = {
'fid':pd.Int64Dtype(),
'drn_pk':int,
'cotrecho':int,
'noorigem':int,
'nodestino':int,
'cocursodag':str,
'cobacia':str,
'nucomptrec':float,
'nudistbact':float,
'nudistcdag':float,
'nuareacont':float,
'nuareamont':float,
'nogenerico':str,
'noligacao':str,
'noespecif':str,
'noriocomp':str,
'nooriginal':str,
'cocdadesag':str,
'nutrjus':pd.Int32Dtype(),
'nudistbacc':float,
'nuareabacc':float,
'nuordemcda':pd.Int32Dtype(),
'nucompcda':float,
'nunivotto':int,
'nunivotcda':pd.Int32Dtype(),
'nustrahler':pd.Int32Dtype(),
'dedominial':str,
'dsversao':str,
'cobacia_50k':str,
'lat':float,
'lon':float,
}
hmap = {k:v for k,v in bho_dtypes.items() if k in df_tble_bho.columns}
df_tble_bho = df_tble_bho.astype(hmap)
return df_tble_bho
#-----------------------------------------------------------------------------
# FUNCTIONS TO DUMP AND LOAD THE DOWNSCALING PRE-PROCESSING RESULTS (DICTS)
#-----------------------------------------------------------------------------
def dump_the_dicts(
dict_bho_mini_t1_post,
dict_bho_mini_t2_post,
dict_bho_mini_t3_post,
dict_parameters_t1,
dict_parameters_t2,
dict_parameters_t3,
dict_parameters_t4,
dict_bho_solver,
pathout='./',
):
"""
Save main dictionaries to disk
- cotrecho x mini for type 1, 2 and 3 associations
- cotrecho x parameters for type 1, 2, 3 and 4
- cotrecho x solver/type
Args:
dict_bho_mini_t1_post (dict) :: {cotrecho:mini}
dict_bho_mini_t2_post (dict) :: {cotrecho:mini}
dict_bho_mini_t3_post (dict) :: {cotrecho:mini}
dict_parameters_t1 (dict) :: {cotrecho:{parameters}}
dict_parameters_t2 (dict) :: {cotrecho:{parameters}}
dict_parameters_t3 (dict) :: {cotrecho:{parameters}}
dict_parameters_t4 (dict) :: {cotrecho:{parameters}}
dict_bho_solver (dict) :: {cotrecho:solver}
pathout(str,optional) :: path (folder) where to save pickle files
Returns:
None
Notes:
- 'dict_bho_mini_t<type>_post' area generated at
'def validate_t123'
- 'dict_parameters_t<type>_post' are generated at
'def define_parameter_t<type>'
TODO: declare/adjust path to dump
"""
#dicts of parameters {cotrecho:{params},...}
with open(pathout+'dict_parameters_t1.pickle','wb') as f:
pickle.dump(dict_parameters_t1,f)
with open(pathout+'dict_parameters_t2.pickle','wb') as f:
pickle.dump(dict_parameters_t2,f)
with open(pathout+'dict_parameters_t3.pickle','wb') as f:
pickle.dump(dict_parameters_t3,f)
with open(pathout+'dict_parameters_t4.pickle','wb') as f:
pickle.dump(dict_parameters_t4,f)
#dicts of association {cotrecho:{mini},...}
with open(pathout+'dict_bho_mini_t1_post.pickle','wb') as f:
pickle.dump(dict_bho_mini_t1_post,f)
with open(pathout+'dict_bho_mini_t2_post.pickle','wb') as f:
pickle.dump(dict_bho_mini_t2_post,f) #contains t1 outlets
with open(pathout+'dict_bho_mini_t3_post.pickle','wb') as f:
pickle.dump(dict_bho_mini_t3_post,f)
# type 4 does not have an association with mini
#with open('dict_bho_mini_t4_post.pickle','wb') as f:
# pickle.dump(dict_bho_mini_t4_post,f)
# solver!
with open(pathout+'dict_bho_solver.pickle','wb') as f:
pickle.dump(dict_bho_solver,f)
print(" - the dicts were successfully saved!")
return None
def read_the_dicts(pathin='./'):
"""
Read main dictionaries
- cotrecho x mini for type 1, 2 and 3 associations
- cotrecho x parameters for type 1, 2, 3 and 4
- cotrecho x solver/type
Args:
pathin (str,optional) :: path (folder) from where to read pickle files
Returns:
the_dicts (dict) :: container for the main dictionaries
keys = [
'dict_bho_mini_t1_post',
'dict_bho_mini_t2_post',
'dict_bho_mini_t3_post',
'dict_parameters_t1',
'dict_parameters_t2',
'dict_parameters_t3',
'dict_parameters_t4',
'dict_bho_solver']
Notes:
- files '<name_of_dict>.pickle' compatible with 'def dump_dicts()'
- files '<name_of_dict>.pickle' must be in current path
TODO: declare/adjust input path
"""
# load dicts of association {cotrecho:{mini},...} for type 1,2,3
with open(pathin+'dict_bho_mini_t1_post.pickle','rb') as f:
dict_bho_mini_t1_post = pickle.load(f)
with open(pathin+'dict_bho_mini_t2_post.pickle','rb') as f:
dict_bho_mini_t2_post = pickle.load(f)
with open(pathin+'dict_bho_mini_t3_post.pickle','rb') as f:
dict_bho_mini_t3_post = pickle.load(f)
# load dicts of parameters {cotrecho:{params},...} for type 1,2,3 and 4
with open(pathin+'dict_parameters_t1.pickle','rb') as f:
dict_parameters_t1 = pickle.load(f)
with open(pathin+'dict_parameters_t2.pickle','rb') as f:
dict_parameters_t2 = pickle.load(f)
with open(pathin+'dict_parameters_t3.pickle','rb') as f:
dict_parameters_t3 = pickle.load(f)
with open(pathin+'dict_parameters_t4.pickle','rb') as f:
dict_parameters_t4 = pickle.load(f)
# load dict of solver for types 1,2,3 and 4
with open(pathin+'dict_bho_solver.pickle','rb') as f:
dict_bho_solver = pickle.load(f)
tuple_of_dicts = (
dict_bho_mini_t1_post,
dict_bho_mini_t2_post,
dict_bho_mini_t3_post,
dict_parameters_t1,
dict_parameters_t2,
dict_parameters_t3,
dict_parameters_t4,
dict_bho_solver,
)
print(" - the dicts successfully loaded")
labels = [
'dict_bho_mini_t1_post',
'dict_bho_mini_t2_post',
'dict_bho_mini_t3_post',
'dict_parameters_t1',
'dict_parameters_t2',
'dict_parameters_t3',
'dict_parameters_t4',
'dict_bho_solver',
]
# convert tuples to dicts
the_dicts = dict(zip(labels,tuple_of_dicts))
return the_dicts
#-----------------------------------------------------------------------------
# FUNCTIONS FOR JSON INPUT/OUTPUT
#-----------------------------------------------------------------------------
def dump_json(input_dict, filename):
"""
Dump dictionary to a json file
"""
with open(filename,'w') as f:
json.dump(input_dict,f)