Skip to content

Commit 63b5b63

Browse files
authored
Api (#125)
* Added functions to load existing StreamCat ftp csv tables to the StreamCat API database * fix to populate tables function * Added function to list published / unpublished metrics in API * Updated delete table function and control table * updates to API * updates for StreamCat_API.py and ControlTable * updated control table * adjusting metric metadata info * channel width additions
1 parent 8c7a3ab commit 63b5b63

File tree

2 files changed

+135
-4
lines changed

2 files changed

+135
-4
lines changed

ControlTable_StreamCat.csv

+3-3
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,8 @@ MTBS_2015,Continuous,MTBS_2015,none,MTBS_2015.tif,,MTBS,Mean,100,0,0,0,,Yes,,Yes
144144
MTBS_2016,Continuous,MTBS_2016,none,MTBS_2016.tif,,MTBS,Mean,100,0,0,0,,Yes,,Yes
145145
MTBS_2017,Continuous,MTBS_2017,none,MTBS_2017.tif,,MTBS,Mean,100,0,0,0,,Yes,,Yes
146146
MTBS_2018,Continuous,MTBS_2018,none,MTBS_2018.tif,,MTBS,Mean,100,0,0,0,,Yes,,Yes
147-
MTBS_Severity_1984,Categorical,lookup/MTBS_severity1984_lookup.csv,none,MTBS_Severity_1984.tif,,MTBS_Severity_1984,Percent,1,0,0,0,,Yes,,Yes
148-
MTBS_Severity_1985,Categorical,lookup/MTBS_severity1985_lookup.csv,none,MTBS_Severity_1985.tif,,MTBS_Severity_1985,Percent,1,0,0,0,,Yes,,Yes
147+
MTBS_Severity_1984,Categorical,lookup/MTBS_severity1984_lookup.csv,none,MTBS_Severity_1984.tif,,MTBS_Severity_1984,Percent,1,0,0,0,,Yes,,
148+
MTBS_Severity_1985,Categorical,lookup/MTBS_severity1985_lookup.csv,none,MTBS_Severity_1985.tif,,MTBS_Severity_1985,Percent,1,0,0,0,,Yes,,
149149
MTBS_Severity_1986,Categorical,lookup/MTBS_severity1986_lookup.csv,none,MTBS_Severity_1986.tif,,MTBS_Severity_1986,Percent,1,0,0,0,,Yes,,
150150
MTBS_Severity_1987,Categorical,lookup/MTBS_severity1987_lookup.csv,none,MTBS_Severity_1987.tif,,MTBS_Severity_1987,Percent,1,0,0,0,,Yes,,
151151
MTBS_Severity_1988,Categorical,lookup/MTBS_severity1988_lookup.csv,none,MTBS_Severity_1988.tif,,MTBS_Severity_1988,Percent,1,0,0,0,,Yes,,
@@ -293,7 +293,7 @@ RdDens_RipBuf100,Continuous,RdDens,Rp100,roadden.tif,,RoadDensityRipBuf100,Mean,
293293
RdCrs,Continuous,RdCrs,none,rdstcrs.tif,SlpWtd,RoadStreamCrossings,Density,0.03,0,0,0,,Yes,,Yes
294294
RockN,Continuous,RockN,none,RockN_USA_USGSproj_1km_kgkm2.tif,,RockN,Mean,1,0,0,0,,Yes,,Yes
295295
Runoff,Continuous,Runoff,none,runoff.tif,,Runoff,Mean,1,0,0,0,,Yes,,Yes
296-
Septic,Continuous,Septic,none,septic1990.tif,,Septic,Mean,0.001,0,0,0,,Yes,,Yes
296+
Septic,Continuous,Septic,none,septic1990.tif,,Septic,Mean,1,0,0,0,,Yes,,Yes
297297
Clay,Continuous,Clay,none,clay.tif,,STATSGO_Set1,Mean,0.01,0,0,0,,Yes,,Yes
298298
Sand,Continuous,Sand,none,sand.tif,,STATSGO_Set1,Mean,0.01,0,0,0,,Yes,,Yes
299299
Om,Continuous,Om,none,om.tif,,STATSGO_Set2,Mean,0.01,0,0,0,,Yes,,Yes

StreamCat_API.py

+132-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from datetime import datetime as dt
1616
import csv
1717
import urllib3
18+
from io import StringIO
1819
from bs4 import BeautifulSoup
1920

2021
def DBtablesAsDF(config_file):
@@ -39,6 +40,7 @@ def DBtablesAsDF(config_file):
3940
df=pd.DataFrame.from_records(json_object)
4041
return df
4142

43+
4244
def ViewDBtable(config_file, table):
4345
"""
4446
__author__ = "Marc Weber <[email protected]>"
@@ -59,8 +61,34 @@ def ViewDBtable(config_file, table):
5961
headers=config.defaults(),
6062
verify=False
6163
)
64+
#json_object = json.loads(r.text)
65+
#df=pd.DataFrame.from_records(json_object)
66+
#return df
6267
pprint(json.loads(r.text))
6368

69+
def ViewMetadatatable(config_file, table):
70+
"""
71+
__author__ = "Marc Weber <[email protected]>"
72+
"Rick Debbout <[email protected]>"
73+
List table info for a specific StreamCat API database
74+
table, using a config file that contains db url,username,
75+
password, and server
76+
77+
Arguments
78+
---------
79+
config_file : configuration file with db configuration parameters
80+
table : database table name
81+
"""
82+
config = configparser.ConfigParser()
83+
config.read(config_file)
84+
r = requests.get(
85+
f"{config['server']['URL']}/StreamCat/admin/manage/tables/{table}/variable_info",
86+
headers=config.defaults(),
87+
verify=False
88+
)
89+
df = pd.read_csv(StringIO(r.content.decode("utf8" , errors="ignore")))
90+
return(df)
91+
6492

6593
def DeleteDBtable(config_file, table, just_data=False):
6694
"""
@@ -145,6 +173,7 @@ def PopulateDBtable(config_file, table, file_loc, temp_file):
145173

146174
counter=0
147175
for file in files:
176+
print(file)
148177
infile = file_loc + '/' + file
149178
df = pd.read_csv(infile)
150179
counter+=len(df)
@@ -224,15 +253,45 @@ def MissingAPImetrics(config_file):
224253
return(published, not_published)
225254

226255

256+
def UpdateMetricMetadata(config_file, table, infile, temp_file):
257+
"""
258+
__author__ = "Marc Weber <[email protected]>"
259+
Modify metric information in the StreamCat API database,
260+
using a config file that contains db url,username, password,
261+
and server. You must provide a fresh list of all variable
262+
info entries for this resource, as it clears out the
263+
existing list and substitutes a new one.
264+
265+
Arguments
266+
---------
267+
config : configuration file with db configuration parameters
268+
table : name of table metadata to load
269+
infile : pandas data frame from ViewMetadatatable function
270+
"""
271+
272+
config = configparser.ConfigParser()
273+
config.read(config_file)
274+
requests.urllib3.disable_warnings()
275+
infile.to_csv(f'{temp_file}', index=False)
276+
filedata = open(f'{temp_file}', "rb")
277+
response = requests.put(f"{config['server']['URL']}/StreamCat/admin/manage/tables/{table}/variable_info",
278+
headers=config.defaults(), verify=False, data=filedata)
279+
return(response)
280+
281+
###############
282+
227283
# Define config file
228284
config_file='E:/GitProjects/NARS/NARS/api/api_config.ini'
285+
# config_file='E:/GitProjects/NARS/NARS/api/api_config_postgres.ini'
286+
229287
# List tables
230288
test = DBtablesAsDF(config_file)
231289
test.head()
232290
test.tail()
233291
test['DSNAME'][0:20]
234292
test['DSNAME'][21:40]
235293
test['DSNAME'][41:60]
294+
test['DSNAME'][61:70]
236295
test['DSNAME'][61:80]
237296
test['DSNAME'][81:120]
238297
# View a particular table
@@ -244,6 +303,7 @@ def MissingAPImetrics(config_file):
244303
# Delete a tables
245304
DeleteDBtable(config_file, table, just_data =True)
246305
# DeleteDBtable(config_file, table, just_data =False)
306+
247307
# Create a table
248308
test = CreateDBtable(config_file, table_params)
249309
print(test)
@@ -255,10 +315,17 @@ def MissingAPImetrics(config_file):
255315
# table='GeoChemPhys2'
256316
table='ImperviousSurfacesRipBuf100'
257317
table='RoadDensityRipBuf100'
318+
table='Dams'
319+
table='predicted_channel_widths_depths'
320+
# file_loc='O:/PRIV/CPHEA/PESD/COR/CORFILES/Geospatial_Library_Projects/StreamCat/FTP_Staging/HydroRegions'
321+
file_loc='O:/PRIV/CPHEA/PESD/COR/CORFILES/Geospatial_Library_Projects/StreamCat/predicted-values/widths-depths_v2'
322+
temp_file='E:/WorkingData/junk.csv'
323+
258324
table='MTBS'
259325
table='WWTP'
260326
file_loc='O:/PRIV/CPHEA/PESD/COR/CORFILES/Geospatial_Library_Projects/StreamCat/FTP_Staging/HydroRegions'
261327
temp_file='E:/WorkingData/junk2.csv'
328+
262329
LoadTime = dt.now()
263330
PopulateDBtable(config_file, table, file_loc, temp_file)
264331
print("Table load complete in : " + str(dt.now() - LoadTime))
@@ -277,6 +344,51 @@ def MissingAPImetrics(config_file):
277344
published, unpublished = MissingAPImetrics(config_file)
278345

279346

347+
# View metadata for a table
348+
table = 'WWTP'
349+
df = ViewMetadatatable(config_file, table)
350+
df.loc[df.METRIC_NAME == 'WWTPAllDens[AOI]', 'METRIC_UNITS'] = "number/ km2"
351+
352+
# Read in .csv file of metadata
353+
table='predicted_channel_widths_depths'
354+
met = pd.read_csv('O:/PRIV/CPHEA/PESD/COR/CORFILES/Geospatial_Library_Projects/StreamCat/MetaData/StreamCatMetrics.csv', encoding='cp1252')
355+
met = met.loc[met['final_table'] == table]
356+
met.columns = met.columns.str.upper()
357+
met = met[df.columns]
358+
temp_file='E:/WorkingData/junk.csv'
359+
UpdateMetricMetadata(config_file, table, met, temp_file)
360+
361+
# Update metadata for a table
362+
# make any adjustments to metrics in table and update
363+
df['SOURCE_URL'].values[0]
364+
df['SOURCE_URL'] = 'https://nadp.slh.wisc.edu/maps-data/ntn-gradient-maps/'
365+
df['SOURCE_URL'].values[0]
366+
367+
# View metadata for a table
368+
table = 'RefStreamTempPred'
369+
df = ViewMetadatatable(config_file, table)
370+
371+
# Update metadata for a table
372+
# make any adjustments to metrics in table and update
373+
df['SOURCE_URL'].values[0]
374+
df['SOURCE_URL'] = 'https://enviroatlas.epa.gov/enviroatlas/DataFactSheets/pdf/Supplemental/PotentialWetlandArea.pdf'
375+
df['SOURCE_URL'].values[0]
376+
temp_file='E:/WorkingData/junk.csv'
377+
UpdateMetricMetadata(config_file, table, df, temp_file)
378+
379+
380+
381+
382+
table_params = {"name": "predicted_channel_widths_depths",
383+
"metrics":[{"name": "wetted_width_m", "display_name": "Predicted wetted width"},
384+
{"name": "thalweg_depth_cm", "display_name": "Predicted Thalweg Depth"},
385+
{"name": "bankfull_width_m", "display_name": "Predicted Bankfull Widthy"},
386+
{"name": "bankfull_depth_m", "display_name": "Predicted Bankfull Depth"}],
387+
"columns": [{"name": "CatPctFull", "type": "number"},{"name": "WsPctFull", "type": "number"},
388+
{"name": "wetted_width_m", "type": "number"},{"name": "thalweg_depth_cm","type": "number"},
389+
{"name": "bankfull_width_m", "type": "number"},{"name": "bankfull_depth_m","type": "number"},]}
390+
391+
280392
table_params = {"name": "AgMidHiSlopes2011",
281393
"metrics":[{"name": "PctAg2011Slp10Cat", "display_name": "Percent of Agriculture on 10% Slope"},
282394
{"name": "PctAg2011Slp20Cat", "display_name": "Percent of Agriculture on 20% Slope"}],
@@ -314,6 +426,24 @@ def MissingAPImetrics(config_file):
314426
{"name": "WWTPAllDensCat", "type": "number"},{"name": "WWTPAllDensWs","type": "number"},]}
315427

316428

429+
430+
table_params = {"name": "MTBS_Severity_1984",
431+
"metrics":[{"name": "pctnofire1984", "display_name": "Percent No Fire Burn Class For Year"},
432+
{"name": "pctundsev1984", "display_name": "Percent Underburned to Low Burn Severity Class For Year"},
433+
{"name": "pctlowsev1984", "display_name": "Percent Low Burn Severity Class For Year"},
434+
{"name": "pctmodsev1984", "display_name": "Percent Moderate Burn Severity Class For Year"},
435+
{"name": "pcthighsev1984", "display_name": "Percent High Burn Severity Class For Year"},
436+
{"name": "pctincvegresp1984", "display_name": "Percent Increased Greenness and Veg Response Class For Year"},
437+
{"name": "pctnonprocmask1984", "display_name": "Percent Non Processing Mask Class For Year"}],
438+
"columns": [{"name": "CatPctFull", "type": "number"},{"name": "WsPctFull", "type": "number"},
439+
{"name": "PctNoFireCat1984Cat", "type": "number"},{"name": "PctNoFire1984Ws","type": "number"},
440+
{"name": "PctUndSev1984Cat", "type": "number"},{"name": "PctUndSev1984Ws","type": "number"},
441+
{"name": "PctLowSev1984Cat", "type": "number"},{"name": "PctLowSev1984Ws","type": "number"},
442+
{"name": "PctModSev1984Cat", "type": "number"},{"name": "PctModSev1984Ws","type": "number"},
443+
{"name": "PctHighSev1984Cat", "type": "number"},{"name": "PctHighSev1984Ws","type": "number"},
444+
{"name": "PctIncVegResp1984Cat", "type": "number"},{"name": "PctIncVegResp1984Ws","type": "number"},
445+
{"name": "PctNonProcMask1984Cat", "type": "number"},{"name": "PctNonProcMask1984Ws","type": "number"}]}
446+
317447
table_params = {"name": "MTBS_Severity_2018",
318448
"metrics":[{"name": "pctnofire2018", "display_name": "Percent No Fire Burn Class For Year"},
319449
{"name": "pctundsev2018", "display_name": "Percent Underburned to Low Burn Severity Class For Year"},
@@ -474,4 +604,5 @@ def MissingAPImetrics(config_file):
474604
{"name": "PctUrbLo2019CatRp100", "type": "number"},{"name": "PctUrbLo2019WsRp100","type": "number"},
475605
{"name": "PctUrbMd2019CatRp100", "type": "number"},{"name": "PctUrbMd2019WsRp100","type": "number"},
476606
{"name": "PctUrbOp2019CatRp100", "type": "number"},{"name": "PctUrbOp2019WsRp100","type": "number"},
477-
{"name": "PctWdWet2019CatRp100", "type": "number"},{"name": "PctWdWet2019WsRp100","type": "number"}]}
607+
{"name": "PctWdWet2019CatRp100", "type": "number"},{"name": "PctWdWet2019WsRp100","type": "number"}]}
608+

0 commit comments

Comments
 (0)