Skip to content

Commit f74508a

Browse files
author
Joe Hamman
committed
Merge pull request #35 from jhamman/hotfix.1.0.2
Added the 'SEARCH_FOR_CHANNEL' option...
2 parents d26eac9 + 37b9c47 commit f74508a

File tree

6 files changed

+80
-27
lines changed

6 files changed

+80
-27
lines changed

rvic/core/aggregate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def make_agg_pairs(pour_points, dom_data, fdr_data, config_dict):
103103
log.info('NUMBER OF POINTS TO AGGREGATE TO: %i' % key_count)
104104
log.info('NUMBER OF POUR POINTS AGGREGATED: %i' % pp_count)
105105
log.info('EFFECIENCY OF: %.2f %%' % (100.*pp_count / num))
106-
log.info('UNASSIGNED POUR POINTS: %i \n' % (num-pp_count))
106+
log.info('UNASSIGNED POUR POINTS: %i' % (num-pp_count))
107107
log.info('-------------------------------------------------------------\n')
108108

109109
# ---------------------------------------------------------------- #

rvic/core/param_file.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,14 +124,15 @@ def finish_params(outlets, dom_data, config_dict, directories):
124124
# fractions
125125
area = dom_data[domain['AREA_VAR']]
126126

127-
for source, outlet in enumerate(source2outlet_ind):
128-
if outlet_y_ind.ndim == 0 or outlet_x_ind.ndim == 0:
127+
if outlet_y_ind.ndim == 0 or outlet_x_ind.ndim == 0:
128+
for source, outlet in enumerate(source2outlet_ind):
129129
unit_hydrograph[:, source] *= area[source_y_ind[source],
130130
source_x_ind[source]]
131131
unit_hydrograph[:, source] /= area[outlet_y_ind[()],
132132
outlet_x_ind[()]]
133133
unit_hydrograph[:, source] *= frac_sources[source]
134-
else:
134+
else:
135+
for source, outlet in enumerate(source2outlet_ind):
135136
unit_hydrograph[:, source] *= area[source_y_ind[source],
136137
source_x_ind[source]]
137138
unit_hydrograph[:, source] /= area[outlet_y_ind[outlet],
@@ -412,7 +413,8 @@ def group(outlets, subset_length):
412413
a = 0
413414
for i, (cell_id, outlet) in enumerate(outlets.iteritems()):
414415
b = a + len(outlet.y_source)
415-
log.debug('unit_hydrograph.shape %s', outlet.unit_hydrograph.shape)
416+
log.debug('outlet.unit_hydrograph.shape %s',
417+
outlet.unit_hydrograph.shape)
416418
# -------------------------------------------------------- #
417419
# Point specific values
418420
gd['unit_hydrograph'][:, a:b] = outlet.unit_hydrograph

rvic/core/plots.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
matplotlib_available = True
1414
try:
1515
from mpl_toolkits.basemap import Basemap
16-
basemap_available = False # Core dumping due to Geos Error
16+
basemap_available = False
1717
except:
1818
basemap_available = False
1919
except:
@@ -32,9 +32,9 @@ def uhs(data, title, case_id, plot_dir):
3232
Plot diagnostic plot showing all unit hydrographs
3333
"""
3434
today = date.today().strftime('%Y%m%d')
35-
file_name = "{}_{}_{}.png".format(title.lower().replace(" ", "_"),
36-
case_id.lower().replace(" ", "_"),
37-
today)
35+
file_name = "{0}_{1}_{2}.png".format(title.lower().replace(" ", "_"),
36+
case_id.lower().replace(" ", "_"),
37+
today)
3838
pfname = os.path.join(plot_dir, file_name)
3939

4040
fig = plt.figure()
@@ -56,9 +56,9 @@ def _fractions_grid(data, dom_x, dom_y, title, case_id, plot_dir):
5656
# ---------------------------------------------------------------- #
5757
# Plot Fractions
5858
today = date.today().strftime('%Y%m%d')
59-
file_name = "{}_{}_{}.png".format(title.lower().replace(" ", "_"),
60-
case_id.lower().replace(" ", "_"),
61-
today)
59+
file_name = "{0}_{1}_{2}.png".format(title.lower().replace(" ", "_"),
60+
case_id.lower().replace(" ", "_"),
61+
today)
6262
pfname = os.path.join(plot_dir, file_name)
6363

6464
mask = data <= 0.0
@@ -75,7 +75,7 @@ def _fractions_grid(data, dom_x, dom_y, title, case_id, plot_dir):
7575
plt.title(title)
7676
plt.xlabel('x')
7777
plt.ylabel('y')
78-
plt.gca().invert_yaxis()
78+
# plt.gca().invert_yaxis()
7979
fig.savefig(pfname)
8080
# ---------------------------------------------------------------- #
8181
return pfname
@@ -90,9 +90,9 @@ def _fractions_map(data, dom_x, dom_y, title, case_id, plot_dir):
9090
# ---------------------------------------------------------------- #
9191
# Plot Fractions
9292
today = date.today().strftime('%Y%m%d')
93-
file_name = "{}_{}_{}.png".format(title.lower().replace(" ", "_"),
94-
case_id.lower().replace(" ", "_"),
95-
today)
93+
file_name = "{0}_{1}_{2}.png".format(title.lower().replace(" ", "_"),
94+
case_id.lower().replace(" ", "_"),
95+
today)
9696
pfname = os.path.join(plot_dir, file_name)
9797

9898
fig = plt.figure(figsize=(8, 8))
@@ -109,7 +109,6 @@ def _fractions_map(data, dom_x, dom_y, title, case_id, plot_dir):
109109
# define projection
110110
midx = int(dom_x.shape[1]/2)
111111
midy = int(dom_x.shape[0]/2)
112-
print midx, midy
113112

114113
projection = {'projection': 'stere',
115114
'lon_0': dom_x[-1, midx],
@@ -136,7 +135,6 @@ def _fractions_map(data, dom_x, dom_y, title, case_id, plot_dir):
136135
m.drawmeridians(meridians, labels=[0, 0, 0, 1])
137136

138137
x, y = m(dom_x, dom_y) # compute map proj coordinates.
139-
print 'passed 1'
140138
cs = m.pcolormesh(x, y, data, cmap=cmap)
141139
m.colorbar(cs, location='right', pad="5%")
142140
plt.title(title)

rvic/core/utilities.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,40 @@ def latlon2yx(plats, plons, glats, glons):
5050
# -------------------------------------------------------------------- #
5151

5252

53+
# -------------------------------------------------------------------- #
54+
# Search neighboring grid cells for channel
55+
def search_for_channel(source_area, routys, routxs, search=2, tol=10):
56+
"""Search neighboring grid cells for channel"""
57+
58+
log.debug('serching for channel')
59+
60+
new_ys = np.empty_like(routys)
61+
new_xs = np.empty_like(routxs)
62+
63+
for i, (y, x) in enumerate(zip(routys, routxs)):
64+
area0 = source_area[y, x]
65+
66+
search_area = source_area[y-search:y+search+1, x-search:x+search+1]
67+
68+
if np.any(search_area > area0*tol):
69+
sy, sx = np.unravel_index(search_area.argmax(), search_area.shape)
70+
71+
new_ys[i] = y + sy - search
72+
new_xs[i] = x + sx - search
73+
74+
log.debug('Moving pour point to channel y: '
75+
'{0}->{1}, x: {2}->{3}'.format(y, new_ys[i],
76+
x, new_xs[i]))
77+
log.debug('Source Area has increased from {0}'
78+
' to {1}'.format(area0, source_area[new_ys[i], new_xs[i]]))
79+
else:
80+
new_ys[i] = y
81+
new_xs[i] = x
82+
return new_ys, new_xs
83+
84+
# -------------------------------------------------------------------- #
85+
86+
5387
# -------------------------------------------------------------------- #
5488
# Write rpointer file
5589
def write_rpointer(restart_dir, restart_file, timestamp):

rvic/core/variables.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class Point(object):
2727
'''
2828

2929
def __init__(self, lat=-9999.9, lon=-9999.9, domx=-9999, domy=-9999,
30-
routx=-9999, routy=-9999, name='', cell_id=-9999):
30+
routx=-9999, routy=-9999, name=None, cell_id=-9999):
3131
'''Defines x and y variables'''
3232
self.lat = lat
3333
self.lon = lon
@@ -76,9 +76,9 @@ def __init__(self, param_file, case_name, calendar, out_dir, file_format,
7676
f = Dataset(param_file, 'r')
7777
self.n_sources = len(f.dimensions['sources'])
7878
self.n_outlets = len(f.dimensions['outlets'])
79-
self.subset_length = f.variables['subset_length'][0]
80-
self.full_time_length = f.variables['full_time_length'][0]
81-
self.unit_hydrograph_dt = f.variables['unit_hydrograph_dt'][0]
79+
self.subset_length = int(f.variables['subset_length'][:])
80+
self.full_time_length = int(f.variables['full_time_length'][:])
81+
self.unit_hydrograph_dt = f.variables['unit_hydrograph_dt'][:]
8282
self.source_lon = f.variables['source_lon'][:]
8383
self.source_lat = f.variables['source_lat'][:]
8484
self.source_x_ind = f.variables['source_x_ind'][:]

rvic/parameters.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from core.utilities import make_directories, copy_inputs, strip_invalid_char
1212
from core.utilities import read_netcdf, tar_inputs, latlon2yx
1313
from core.utilities import check_ncvars, clean_file, read_domain
14+
from core.utilities import search_for_channel
1415
from core.aggregate import make_agg_pairs, aggregate
1516
from core.make_uh import rout
1617
from core.share import NcGlobals
@@ -160,6 +161,7 @@ def gen_uh_init(config_file):
160161
fdr_lon = config_dict['ROUTING']['LONGITUDE_VAR']
161162
fdr_vel = config_dict['ROUTING']['VELOCITY']
162163
fdr_dif = config_dict['ROUTING']['DIFFUSION']
164+
fdr_area = config_dict['ROUTING']['SOURCE_AREA_VAR']
163165
try:
164166
fdr_data, fdr_vatts, _ = read_netcdf(fdr_file)
165167
fdr_shape = fdr_data[fdr_var].shape
@@ -169,10 +171,19 @@ def gen_uh_init(config_file):
169171
if fdr_data[fdr_lat][-1] > fdr_data[fdr_lat][0]:
170172
log.debug('Flow Direction inputs came in upside down, flipping '
171173
'everything now.')
172-
var_list = fdr_data.keys()
173-
var_list.remove(fdr_lon)
174-
for var in var_list:
175-
fdr_data[var] = np.flipud(fdr_data[var])
174+
175+
remove_vars = []
176+
177+
for var, data in fdr_data.iteritems():
178+
log.debug('flipping %s', var)
179+
if data.ndim >= 1 and var != fdr_lon:
180+
fdr_data[var] = np.flipud(data)
181+
elif data.ndim == 0:
182+
remove_vars.append(var)
183+
184+
if remove_vars:
185+
for var in remove_vars:
186+
del fdr_data[var]
176187
# ---------------------------------------------------------------- #
177188

178189
# ---------------------------------------------------------------- #
@@ -250,6 +261,14 @@ def gen_uh_init(config_file):
250261
glats=fdr_data[fdr_lat],
251262
glons=fdr_data[fdr_lon])
252263

264+
if options['SEARCH_FOR_CHANNEL']:
265+
routys, routxs = search_for_channel(fdr_data[fdr_area],
266+
routys, routxs,
267+
tol=10, search=2)
268+
# update lats and lons
269+
lats = fdr_data[fdr_lat][routys]
270+
lons = fdr_data[fdr_lon][routxs]
271+
253272
# Find location on domain grid
254273
domys, domxs = latlon2yx(plats=lats,
255274
plons=lons,
@@ -259,7 +278,7 @@ def gen_uh_init(config_file):
259278
for i in xrange(len(lats)):
260279
if 'names' in pour_points.keys():
261280
name = pour_points['names'].values[i]
262-
name = name.replace("'", "").replace(" ", "_")
281+
name = name.replace("'", '').replace(" ", "_")
263282
else:
264283
# fill name filed with p-outlet_num
265284
name = 'p-{0}'.format(i)

0 commit comments

Comments
 (0)