Skip to content

Commit f5d1050

Browse files
committed
Make table of percent correct
1 parent 96741fb commit f5d1050

File tree

1 file changed

+99
-19
lines changed

1 file changed

+99
-19
lines changed

utils/Wetlands.py

+99-19
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def __init__(self, path_results, z_thresh=3.75):
88
super(Wetlands, self).__init__(path_results)
99
self.path_res = path_results
1010
self.z_thresh = 3.75
11-
self.mat_dtw, self.mat_dtw_masked = self._make_dtw()
11+
self.mat_dtw, self.mask_z = self._make_dtw()
1212
self.df_wets, self.mat_wets = self._ccap_wetlands()
1313
self.mask_wet = np.isnan(self.mat_wets.reshape(-1))
1414
# highest values (closest to 0) = most hours with lowest DTW
@@ -25,7 +25,14 @@ def _ccap_wetlands(self):
2525
mat_wetlands = np.where(((mat_landcover < 13) | (mat_landcover > 18)),
2626
np.nan, mat_landcover)
2727

28+
29+
30+
31+
2832
df_wet = df_subs[((df_subs.Majority >= 13) & (df_subs.Majority < 19))].iloc[:, :3]
33+
34+
35+
2936
return (df_wet, mat_wetlands)
3037

3138
def _make_dtw(self, slr=0.0):
@@ -58,8 +65,8 @@ def make_indicator(self, dtw_inc=0.01, hrs_per=50, masked=True, seasonal=False):
5865
start = time.time()
5966
if masked:
6067
### chop off cells whose elevation is too high
61-
mat_dtw = self.mat_dtw[self.mat_dtw_masked]
62-
mask_wet = self.mask_wet[self.mat_dtw_masked]
68+
mat_dtw = self.mat_dtw[self.mask_z]
69+
mask_wet = self.mask_wet[self.mask_z]
6370
names = ['dtw_hrs_wet_dry_masked.npy', 'dtw_hrs_wet_dry_masked.df']
6471
else:
6572
mat_dtw = self.mat_dtw
@@ -81,7 +88,8 @@ def make_indicator(self, dtw_inc=0.01, hrs_per=50, masked=True, seasonal=False):
8188
mat_dry_dtw = df_dry_dtw.values.T
8289
## fix this to add to previously made name
8390
names = ['{}_summer'.format(n) for n in names]
84-
91+
print ('Wetlands shape: {}'.format(mat_wet_dtw.shape))
92+
print ('Uplands shape: {}'.format(mat_dry_dtw.shape))
8593
## to view the amount of wetlands and drylands working with
8694
print ('Finding optimum criteria; will take a bit')
8795
dtw_tests = np.arange(0, 1, dtw_inc)
@@ -133,14 +141,12 @@ def apply_indicator(self, z=True, seasonal=False):
133141
perDry_thresh = 0.35
134142
elif z and not seasonal:
135143
names = ['dtw_hrs_wet_dry_masked.npy', 'dtw_hrs_wet_dry_masked.df']
136-
perWet_thresh = 0.7
137-
perDry_thresh = 0.4
144+
perWet_thresh = 0.616
145+
perDry_thresh = 0.33
138146

139147
mat_all = np.load(op.join(self.path_data, names[0]))
140148
df_all = pd.read_pickle(op.join(self.path_data, names[1]))
141-
print (df_all.shape)
142-
return
143-
# print (df_all.head(25))
149+
df_all = df_all[df_all.hrs_thresh>4000]
144150
## do some cropping
145151
df_new = (df_all[((df_all.hrs_thresh > df_all.hrs_thresh.max()/2.) &
146152
(df_all.perWet > perWet_thresh) &
@@ -151,11 +157,15 @@ def apply_indicator(self, z=True, seasonal=False):
151157
### can get about 1/2 the wetlands and 1/4 of the uplands
152158
### best for all is ~ 65% wetlands, 35% of drylands
153159
### best for summer is ~ 61% wetlands and 34.4% of drylands
160+
### best for z of 3.5 m is ~ 61% / 33%
154161
BB.print_all(df_new)
155162

156-
def find_cells(self, dtw_thresh=0.05, hrs_thresh=4442):
163+
def find_cells(self, dtw_thresh=0.08, hrs_thresh=5185, one_slr=False):
157164
""" Find locations that meet the threshold conditions """
158165
slr_dict = OrderedDict()
166+
if one_slr:
167+
self.slr_sh = [0.0]
168+
159169
for slr in self.slr_sh:
160170
mat_dtw = self._make_dtw(slr)[0]
161171

@@ -180,8 +190,8 @@ def find_cells(self, dtw_thresh=0.05, hrs_thresh=4442):
180190
# return df_passed_wets, df_passed_drys
181191
return slr_dict
182192

183-
def plot_wets_drys(self, test=False):
184-
slr_dict = self.find_cells(dtw_thresh=0.05, hrs_thresh=4442)
193+
def plot_wets_drys(self, dtw_thresh=0.08, hrs_thresh=5185, test=False):
194+
slr_dict = self.find_cells(dtw_thresh, hrs_thresh)
185195

186196
fig, axes = plt.subplots(ncols=3, sharey=True)
187197
axe = axes.ravel()
@@ -191,14 +201,13 @@ def plot_wets_drys(self, test=False):
191201
## change value for cells not considered (visualization purposes)
192202
df_subs['dry'] = df_subs.index.map(lambda x: df.loc[x, 'dry']
193203
if x in df.index.values else 1)
204+
n_wets = df_subs[df_subs['dry']<0].shape[0] + df_subs[df_subs['dry']==0].shape[0]
194205
## converts dfs to matrixes
195206
mat_lows = res_base.fill_grid(df_subs.dry, fill_value=-2)
196207
## plot
197208
im = axe[i].imshow(mat_lows.reshape(self.nrows, self.ncols), cmap=cm)
198209
axe[i].set(title='SLR: {} m'.format(slr),
199-
xlabel='# Wetlands: {}'.format(
200-
df[((df['dry']==0) | (df['dry']==1))].shape[0]),
201-
)
210+
xlabel='# Wetlands: {}'.format(n_wets))
202211
if test: break
203212

204213
cbar_ax = fig.add_axes([0.945, 0.12, 0.025, 0.75])
@@ -214,6 +223,73 @@ def plot_wets_drys(self, test=False):
214223
fig.subplots_adjust(left=0.05, right=0.915, wspace=0.25, hspace=0.25)
215224
plt.show()
216225

226+
def check_performance(self, dtw_thresh=0.08, hrs_thresh=5185):
227+
""" Check number of cells / percentages to create table of performance """
228+
df = pd.read_pickle(op.join(self.path_data, 'dtw_hrs_wet_dry_masked.df'))
229+
df_passed = df[((df.dtw_thresh<=dtw_thresh) & (df.hrs_thresh >= hrs_thresh))].iloc[0, :]
230+
231+
### this should be encapsulated in fn; used here and make_indicator
232+
mat_dtw = self.mat_dtw[self.mask_z]
233+
mask_wet = self.mask_wet[self.mask_z]
234+
mat_wet_dtw = mat_dtw[~mask_wet]
235+
mat_nonwet_dtw = mat_dtw[mask_wet]
236+
mat_dry_dtw = mat_nonwet_dtw[~np.isnan(mat_nonwet_dtw)].reshape(
237+
-1, mat_nonwet_dtw.shape[1])
238+
total_ccap = mat_wet_dtw.shape[0]
239+
total_nonccap = mat_dry_dtw.shape[0]
240+
total_wets = df_passed.loc['n_wet'] + df_passed.loc['n_dry']
241+
total_subs = self.df_swmm.shape[0]
242+
df_raw = pd.DataFrame(np.zeros([4, 3]), columns=['sim_wet', 'true_wet', 'per_covering'], index=['A', 'B', 'C', 'D'])
243+
244+
df_raw.loc['A', :] = ['Yes', 'Yes', round(df_passed.loc['n_wet']/total_subs*100, 2)] # correct
245+
df_raw.loc['B', :] = ['No', 'Yes', round((total_ccap - total_wets) / total_subs*100, 2)] # pretty sure correct
246+
df_raw.loc['C', :] = ['Yes', 'No', round(df_passed.loc['n_dry']/total_subs*100, 2)] # correct
247+
df_raw.loc['D', :] = ['No', 'No', round((total_subs-total_wets) / total_subs*100, 2)]
248+
print df_raw
249+
print (df_raw.iloc[:, 2].sum())
250+
251+
252+
253+
254+
return
255+
256+
def overlay_sim_true(self, dtw_thresh=0.08, hrs_thresh=5185):
257+
""" Compare the simulated/nonsimulated wetlands vs ccap """
258+
df = pd.read_pickle(op.join(self.path_data, 'dtw_hrs_wet_dry_masked.df'))
259+
df_passed = df[((df.dtw_thresh<=dtw_thresh) & (df.hrs_thresh >= hrs_thresh))].iloc[0, :]
260+
df_dtw = self.find_cells(dtw_thresh, hrs_thresh, one_slr=True)[0.0]
261+
df_subs = pd.DataFrame(index=self.df_swmm.index)
262+
## change value for cells not considered (visualization purposes)
263+
df_subs['dry'] = df_subs.index.map(lambda x: df_dtw.loc[x, 'dry']
264+
if x in df_dtw.index.values else 1)
265+
n_wets = df_subs[df_subs['dry']<0].shape[0] + df_subs[df_subs['dry']==0].shape[0]
266+
## converts dfs to matrix of wetland types
267+
## -2: inactive | -1: wetland (ccap) | 0: wetland(nonccap) | 1: upland
268+
mat_lows = res_base.fill_grid(df_subs.dry, fill_value=-2)
269+
mask_in_ccap = ~self.mask_wet & self.mask_z
270+
df_lows = pd.DataFrame(mat_lows.reshape(-1), columns=['type'])
271+
df_lows['true'] = mask_in_ccap
272+
# return
273+
df_lows['sim'] = df_lows['type'].apply(lambda x: True if x == -1 or x == 0 else False)
274+
## get rid of inactive cells
275+
df_lows = df_lows[df_lows['type']>-2]
276+
277+
## make cases
278+
total_subs = df_lows.shape[0]
279+
a = float(np.count_nonzero((df_lows['sim']) & (df_lows['true'])))
280+
b = float(np.count_nonzero((~df_lows['sim']) & (df_lows['true'])))
281+
c = float(np.count_nonzero((df_lows['sim']) & (~df_lows['true'])))
282+
d = float(np.count_nonzero((~df_lows['sim']) & (~df_lows['true'])))
283+
284+
df_raw = pd.DataFrame(np.zeros([4, 3]), columns=['sim_wet', 'true_wet', 'per_covering'], index=['A', 'B', 'C', 'D'])
285+
df_raw.loc['A', :] = ['Yes', 'Yes', round(a/total_subs*100, 2)]
286+
df_raw.loc['B', :] = ['No', 'Yes', round(c/total_subs*100, 2)]
287+
df_raw.loc['C', :] = ['Yes', 'No', round(b/total_subs*100, 2)]
288+
df_raw.loc['D', :] = ['No', 'No', round(d/total_subs*100, 2)]
289+
290+
print (df_raw)
291+
print (df_raw.iloc[:, 2].sum())
292+
217293
##### not using below this
218294
def optimize(self, increment=1):
219295
""" Maximize the percent correctly identiified """
@@ -342,7 +418,6 @@ def comp_histograms(self, kind='avg', plot=True):
342418
### probably useless
343419
def dtw_wet_avg_ann(self):
344420
""" Subset dtw df (all cells, annual average to just wetland cells """
345-
346421
## avg annual dtw
347422
df_dtw = dtw(self.path_res).df_year
348423
df_dtw.columns = [str(col) for col in df_dtw.columns]
@@ -355,10 +430,15 @@ def dtw_wet_avg_ann(self):
355430
'WNC', 'Wetlands_Paper', 'Results_Default')
356431
res = Wetlands(PATH_res, z_thresh=3.75)
357432
# res.optimize(increment=10)
358-
res.make_indicator(dtw_inc=0.01, hrs_per=50, masked=True, seasonal=False)
433+
# res.make_indicator(dtw_inc=0.01, hrs_per=50, masked=True, seasonal=False)
434+
# res.apply_indicator(0.08, hrs_thresh=5182)
435+
res.check_performance()
436+
res.overlay_sim_true()
359437

360-
## nonseasonal indicators: dtw < 0.05; hrs_thresh>4443 --------- best
438+
## wetland masked, nonseasonal: dtw <= 0.08; hrs_thesh >=5182 ------- best
439+
## nonseasonal indicators: dtw < 0.05; hrs_thresh>4443
361440
## seasonal indicators : dtw < 0.17; hrs_thresh > 1211
362441

363-
# res.find_cells(0.05, hrs_thresh=4442)
442+
# res.find_cells(0.08, hrs_thresh=5182)
364443
# res.plot_wets_drys()
444+
# print len(res.ts_day)

0 commit comments

Comments
 (0)