Skip to content

Commit 1fc9616

Browse files
committed
only have water source shares for withdrawal; fix queries; hack to capture transnational basins within the USA
1 parent 4e93953 commit 1fc9616

3 files changed

Lines changed: 31 additions & 24 deletions

File tree

tethys/datareader/easy_query.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import gcamreader
22

33

4-
def easy_query(variable, year_axis=None, **kwargs):
4+
def easy_query(variable, year_axis=None, replace_filters=False, **kwargs):
55
"""Build a query for a GCAM database
66
77
kwargs act as filters on nodes, eg. "sector='Beef'" is converted to the xpath "[@type='sector' and @name='Beef']"
@@ -24,10 +24,11 @@ def easy_query(variable, year_axis=None, **kwargs):
2424
:return: gcamreader Query object
2525
"""
2626

27-
if not kwargs:
28-
filters = dict(sector=None) # match nodes where @type='sector' by default if no filters are specified
27+
if replace_filters:
28+
filters = kwargs
2929
else:
30-
filters = kwargs # update the filters with user-provided kwargs
30+
filters = dict(sector=None) # match nodes where @type='sector' by default
31+
filters.update(kwargs) # update the filters with user-provided kwargs
3132

3233
# filters are separated by "//*" to match any descendant
3334
xpath = "*" + "//*".join(handle_filter(k, v) for k, v in filters.items()) + f"//{variable}/node()"

tethys/model.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ def downscale(self, distribution, inputs, region_masks):
206206

207207
return out
208208

209-
def disaggregate_source(self, downscaled):
209+
def disaggregate_source(self):
210210
"""Disaggregate water demand by source (runoff, groundwater, desal)"""
211211

212212
print('Disaggregating Source')
@@ -221,11 +221,7 @@ def disaggregate_source(self, downscaled):
221221
# apply shares to the gridded region masks
222222
gridded_shares = get_shares.generate_gridded_shares(shares_df)
223223

224-
# disaggregate water supply source for each downscaled demand in each grid cell
225-
downscaled_disaggregated_sw = (downscaled * gridded_shares['runoff']).compute()
226-
downscaled_disaggregated_gw = (downscaled * gridded_shares['groundwater']).compute()
227-
228-
return gridded_shares, downscaled_disaggregated_sw, downscaled_disaggregated_gw
224+
return gridded_shares
229225

230226

231227
def run_model(self):
@@ -238,6 +234,17 @@ def run_model(self):
238234
self._load_region_masks()
239235
self._load_inputs()
240236

237+
# disaggregate water supply source
238+
if self.source_disaggregation:
239+
gshares = self.disaggregate_source()
240+
241+
# store the disaggregated results
242+
self.griddedshares = gshares
243+
244+
if self.output_dir is not None:
245+
filename = os.path.join(self.output_dir, f'gridded_runoff_shares.nc')
246+
gshares['runoff'].to_netcdf(filename)
247+
241248
for supersector, rules in self.downscaling_rules.items():
242249

243250
print(f'Downscaling {supersector}')
@@ -284,16 +291,6 @@ def run_model(self):
284291
downscaled.to_dataset(dim='sector').to_netcdf(filename, encoding=encoding)
285292
downscaled = xr.open_dataset(filename).to_array(dim='sector') # hopefully this keeps dask happy
286293

287-
# disaggregate water supply source and update the objects
288-
if self.source_disaggregation:
289-
gshares, sw, gw = self.disaggregate_source(downscaled)
290-
291-
# store the disaggregated results
292-
self.griddedshares = gshares
293-
self.disaggregated_sw = sw
294-
self.disaggregated_gw = gw
295-
296-
297294
if self.temporal_config is not None:
298295
# calculate the monthly distributions (share of annual) for each year
299296

@@ -315,7 +312,7 @@ def run_model(self):
315312
if self.output_dir is not None:
316313
filename = os.path.join(self.output_dir, f'{supersector}_{self.demand_type}_monthly.nc')
317314
encoding = {sector: {'zlib': True, 'complevel': 5} for sector in downscaled.sector.data}
318-
downscaled.to_dataset(dim='sector').to_netcdf(filename, encoding=encoding)
315+
downscaled.to_dataset(dim='sector').compute().to_netcdf(filename, encoding=encoding)
319316
downscaled = xr.open_dataset(filename).to_array(dim='sector') # hopefully this keeps dask happy
320317

321318
self.outputs.update(downscaled.to_dataset(dim='sector'))

tethys/utils/source_disaggregation.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ def calculate_shares(self):
3434
3535
:return: Processed DataFrame with calculated shares.
3636
"""
37-
# query GCAM database for water used by source for the demand type (W or C)
38-
query_type = f'*_water {self.demand_type}'
39-
shares_df = self.conn.runQuery(easy_query('production', resource=query_type))
37+
# query GCAM database for water used by source for the demand type (W only)
38+
query_type = f'*_water withdrawals'
39+
shares_df = self.conn.runQuery(easy_query('production', replace_filters=True, resource=query_type))
4040

4141
# extract and clean resource names (e.g., remove '_water withdrawals')
4242
shares_df['resource'] = shares_df['resource'].apply(extract_resource_name)
@@ -54,6 +54,15 @@ def calculate_shares(self):
5454
['scenario', 'region', 'region_resourcemap', 'year']
5555
)['value'].transform(lambda x: x / x.sum() if x.sum() != 0 else 0)
5656

57+
# capture basins that are mostly belonging to other countries
58+
if basin_name_mapping == 'basin_name_mapping_im3':
59+
shares_df = shares_df.replace({'region_resourcemap': {
60+
'Canada_FraserR': 'USA_FraserR',
61+
'Canada_GreatLakes': 'USA_GreatLakes',
62+
'Mexico_MexCstNW': 'USA_MexCstNW',
63+
'Canada_NelsonR': 'USA_NelsonR',
64+
}})
65+
5766
# filter shares based on the region masks from the config file, otherwise all regions would be included
5867
shares_df = shares_df[shares_df['region_resourcemap'].isin(self.region_masks.region.values)]
5968

0 commit comments

Comments
 (0)