Skip to content

Commit a971040

Browse files
authored
PR for #18: Update package structure for compatability with Shiny (#21)
* WIP for #18 * lots of changes for #18 * a working shiny app for #18 * draft 1 for #18 * fix for #18 * makes deployable for #18 * removes app for #18 * updates version for #18 * removes fixed test for #18 * unbumps version for #18
1 parent 2cfe33c commit a971040

File tree

4 files changed

+61
-61
lines changed

4 files changed

+61
-61
lines changed

examples/examples.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
""" Test examples """
22
import sys, os, re
3-
sys.path.append('/'.join(re.split('/|\\\\', os.path.dirname( __file__ ))[0:-1]) + '/src/BootstrapReport')
3+
sys.path.append('/'.join(re.split('/|\\\\', os.path.dirname( __file__ ))[0:-1]))
44
import timeit
5-
from main import ObjectOfInterest
5+
from src.BootstrapReport import ObjectOfInterest
66
import pandas as pd
77

88
def gamma_example():

src/BootstrapReport/helpers.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -209,9 +209,8 @@ def select_bandwidth(rot_se, max_grid, min_grid, num_gridpoints,
209209

210210
return implied_normal_pdf, best_bandwidth, best_bandwidth_index, avg_tvd_list, expansion_count
211211

212-
def plot_min_crossings(outfile, optimal_path, crossings, alpha, replicates, estimate, std, upper_cb, lower_cb, left_upper_cb, **kwargs):
212+
def plot_min_crossings(optimal_path, crossings, alpha, replicates, estimate, std, upper_cb, lower_cb, left_upper_cb, plt_set):
213213
""" Create the plot for `get_crossings` of ObjectOfInterest
214-
:param outfile: destination for the plot
215214
:param optimal_path: nx2 numpy.array. First column contains x values, and second column contains y values of optimal path.
216215
:param crossings: number of crossings, or changes in direction
217216
:param alpha: 1 - alpha = confidence level for number of crossings
@@ -222,19 +221,18 @@ def plot_min_crossings(outfile, optimal_path, crossings, alpha, replicates, esti
222221
:param lower_cb: function that returns the difference between the lower confidence bound and the cdf of the implied normal
223222
:param left_upper_cb: function that returns the left-handed limit of the difference between the upper confidence bound
224223
and the cdf of the implied normal
224+
:param plt_set: dictionary of plot options
225225
"""
226-
plt_set = {'fontsize': 18, 'legend_fontsize': 20, 'labelsize': 28, 'linecolor': '#f9665e', 'bandcolor': '#a8d9ed', 'linewidth': 2, 'dpi': 100}
227-
for key, value in kwargs.items():
228-
plt_set[key] = value
229-
mpl.rcParams['axes.spines.bottom'] = False
230-
plt.rcParams.update({'font.size': plt_set['fontsize']})
231-
plt.rcParams.update({'legend.fontsize': plt_set['legend_fontsize']})
232-
plt.rcParams.update({'axes.labelsize': plt_set['labelsize']})
226+
plt.rc('font', size = plt_set['fontsize'])
227+
plt.rc('legend', fontsize = plt_set['legend_fontsize'])
228+
plt.rc('axes', labelsize = plt_set['labelsize'])
229+
fig, ax = plt.subplots(figsize = (10, 10))
230+
ax.spines.bottom.set_visible(False)
233231

234232
num_rep, x, y = len(replicates), optimal_path[-1, 0], optimal_path[-1, 1]
235233
plot_data = ('Num. crossings = %d' % crossings)
236234
props = dict(boxstyle = 'round, pad = 0.75, rounding_size = 0.3', facecolor = 'white', alpha = 0.7)
237-
plt.plot(optimal_path[:, 0], optimal_path[:, 1], color = plt_set['linecolor'], label = 'Optimal path', linewidth = plt_set['linewidth'])
235+
ax.plot(optimal_path[:, 0], optimal_path[:, 1], color = plt_set['linecolor'], label = 'Optimal path', linewidth = plt_set['linewidth'])
238236

239237
zero_null_rej = stats.norm.ppf(np.sqrt(np.log(2/alpha)/(2 * num_rep)), loc = estimate, scale = std)
240238
if zero_null_rej < replicates[0]:
@@ -258,24 +256,22 @@ def plot_min_crossings(outfile, optimal_path, crossings, alpha, replicates, esti
258256
else:
259257
postline = np.array([[replicates[-1], optimal_path[-1, 1]], [end + 0.5 * std, 0], [end + std, 0]])
260258

261-
plt.plot(preline[:, 0], preline[:, 1], color = plt_set['linecolor'], linewidth = plt_set['linewidth'])
262-
plt.plot(postline[:, 0], postline[:, 1], color = plt_set['linecolor'], linewidth = plt_set['linewidth'])
259+
ax.plot(preline[:, 0], preline[:, 1], color = plt_set['linecolor'], linewidth = plt_set['linewidth'])
260+
ax.plot(postline[:, 0], postline[:, 1], color = plt_set['linecolor'], linewidth = plt_set['linewidth'])
263261
x_axis = np.concatenate([np.linspace(replicates[r], replicates[r + 1], 10) for r in range(num_rep - 1)], axis = None)
264262
x_axis = np.append(np.linspace(preline[0, 0], replicates[0], 15), x_axis)
265263
x_axis = np.append(x_axis, np.linspace(replicates[-1], postline[-1, 0], 15))
266264
upper_band, lower_band = [upper_cb(x) for x in x_axis], [lower_cb(x) for x in x_axis]
267265
lbound, rbound = x_axis[0] + 0.25 * std, x_axis[-1] - 0.25 * std
268266
topbound = np.max(upper_band) + 0.025 * (np.max(upper_band) - np.min(lower_band))
269267
botbound = np.min(lower_band) - 0.025 * (np.max(upper_band) - np.min(lower_band))
270-
plt.xlim(lbound, rbound)
271-
plt.ylim(botbound, topbound)
272-
plt.hlines(y = botbound, xmin = lbound, xmax = replicates[0], color = 'k', lw = 2, linestyle = (1.5, (1.5, 1)))
273-
plt.hlines(y = botbound, xmin = replicates[0], xmax = replicates[-1], color = 'k', lw = 2)
274-
plt.hlines(y = botbound, xmin = replicates[-1], xmax = rbound, color = 'k', lw = 2, linestyle = (1.5, (1.5, 1)))
275-
plt.fill_between(x_axis, lower_band, upper_band, color = plt_set['bandcolor'], label = 'Confidence band', alpha = 0.25)
276-
plt.legend(edgecolor = 'k', loc = 'upper left')
277-
plt.text(rbound - 0.04 * (rbound - lbound), botbound + 0.07 * (topbound - botbound), plot_data,
268+
ax.set_xlim(lbound, rbound)
269+
ax.set_ylim(botbound, topbound)
270+
ax.hlines(y = botbound, xmin = lbound, xmax = replicates[0], color = 'k', lw = 2, linestyle = (1.5, (1.5, 1)))
271+
ax.hlines(y = botbound, xmin = replicates[0], xmax = replicates[-1], color = 'k', lw = 2)
272+
ax.hlines(y = botbound, xmin = replicates[-1], xmax = rbound, color = 'k', lw = 2, linestyle = (1.5, (1.5, 1)))
273+
ax.fill_between(x_axis, lower_band, upper_band, color = plt_set['bandcolor'], label = 'Confidence band', alpha = 0.25)
274+
ax.legend(edgecolor = 'k', loc = 'upper left')
275+
ax.text(rbound - 0.04 * (rbound - lbound), botbound + 0.07 * (topbound - botbound), plot_data,
278276
fontsize = plt_set['legend_fontsize'], verticalalignment = 'bottom', horizontalalignment='right', bbox = props)
279-
plt.savefig(outfile, transparent = True, dpi = plt_set['dpi'])
280-
plt.clf()
281-
mpl.rcParams.update(mpl.rcParamsDefault)
277+
return fig

src/BootstrapReport/main.py

Lines changed: 40 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ def get_crossings(self, alpha = 0.05, outfile = None, **kwargs):
110110
:param alpha: 1 - alpha = confidence level for confidence bands
111111
:param outfile: path to output figure displaying algorithm
112112
"""
113+
plt_set = {'fontsize': 18, 'legend_fontsize': 20, 'labelsize': 28, 'linecolor': '#f9665e', 'bandcolor': '#a8d9ed', 'linewidth': 2, 'dpi': 100}
114+
for key, value in kwargs.items():
115+
plt_set[key] = value
116+
113117
rep = self.replicates/self.se
114118
est = self.estimate/self.se
115119
num_rep, crossings = len(rep), 0
@@ -167,8 +171,11 @@ def left_upper_cb(x):
167171
self.crossings = crossings
168172

169173
if not outfile == None:
170-
helpers.plot_min_crossings(outfile, optimal_path, self.crossings, alpha, rep, est,
171-
1, upper_cb, lower_cb, left_upper_cb, **kwargs)
174+
fig = helpers.plot_min_crossings(optimal_path, self.crossings, alpha, rep, est,
175+
1, upper_cb, lower_cb, left_upper_cb, plt_set)
176+
if type(outfile) == str:
177+
fig.savefig(outfile, transparent = True, dpi = plt_set['dpi'])
178+
return fig
172179

173180
def pp_plot(self, confidence_band = True, alpha = 0.05, outfile = None, **kwargs):
174181
""" create the pp plot
@@ -180,6 +187,7 @@ def pp_plot(self, confidence_band = True, alpha = 0.05, outfile = None, **kwargs
180187
plt_set = {'fontsize': 18, 'legend_fontsize': 20, 'labelsize': 28, 'pointsize': 7, 'pointcolor': '#f9665e', 'bandcolor': '#a8d9ed', 'dpi': 100}
181188
for key, value in kwargs.items():
182189
plt_set[key] = value
190+
183191
num_replicates = len(self.replicates)
184192

185193
replicates_eval_normcdf = norm.cdf(self.replicates, self.estimate, self.se)
@@ -197,28 +205,27 @@ def pp_plot(self, confidence_band = True, alpha = 0.05, outfile = None, **kwargs
197205
'Neg. distance = %.3f' % self.neg_dist))
198206
props = dict(boxstyle = 'round, pad = 0.75, rounding_size = 0.3', facecolor = 'white', alpha = 0.86)
199207

200-
plt.rcParams.update({'font.size': plt_set['fontsize']})
201-
plt.rcParams.update({'legend.fontsize': plt_set['legend_fontsize']})
202-
plt.rcParams.update({'axes.labelsize': plt_set['labelsize']})
203-
204-
plt.figure(figsize=(10, 10))
208+
plt.rc('font', size = plt_set['fontsize'])
209+
plt.rc('legend', fontsize = plt_set['legend_fontsize'])
210+
plt.rc('axes', labelsize = plt_set['labelsize'])
211+
fig, ax = plt.subplots(figsize = (10, 10))
212+
205213
if confidence_band == True:
206-
plt.fill_between(dkw_xgrid, dkw_lbound, dkw_ubound, color = plt_set['bandcolor'], label = 'Confidence band', alpha = 0.35)
207-
plt.scatter(replicates_eval_normcdf, replicate_ecdf, s = plt_set['pointsize'],
214+
ax.fill_between(dkw_xgrid, dkw_lbound, dkw_ubound, color = plt_set['bandcolor'], label = 'Confidence band', alpha = 0.35)
215+
ax.scatter(replicates_eval_normcdf, replicate_ecdf, s = plt_set['pointsize'],
208216
c = plt_set['pointcolor'], label='Bootstrap replicates')
209-
plt.xlabel("CDF of normal distribution")
210-
plt.ylabel("CDF of bootstrap distribution")
211-
plt.legend(edgecolor = 'k', loc = 'upper left')
212-
plt.axline((0, 0), (1, 1), color="black", linestyle=(0, (5, 5)))
213-
plt.text(0.52, 0.06, plot_data, fontsize = plt_set['legend_fontsize'], \
217+
ax.set_xlabel("CDF of normal distribution")
218+
ax.set_ylabel("CDF of bootstrap distribution")
219+
ax.legend(edgecolor = 'k', loc = 'upper left')
220+
ax.axline((0, 0), (1, 1), color="black", linestyle=(0, (5, 5)))
221+
ax.text(0.52, 0.06, plot_data, fontsize = plt_set['legend_fontsize'], \
214222
verticalalignment = 'bottom', horizontalalignment='left', bbox = props)
215-
plt.ylim(0, 1)
216-
plt.xlim(0, 1)
223+
ax.set_ylim(0, 1)
224+
ax.set_xlim(0, 1)
217225

218226
if not outfile == None:
219-
plt.savefig(outfile, transparent = True, dpi = plt_set['dpi'])
220-
plt.clf()
221-
mpl.rcParams.update(mpl.rcParamsDefault)
227+
fig.savefig(outfile, transparent = True, dpi = plt_set['dpi'])
228+
return fig
222229

223230

224231
def density_plot(self, bounds = None, bandwidth = None, outfile = None, **kwargs):
@@ -230,6 +237,7 @@ def density_plot(self, bounds = None, bandwidth = None, outfile = None, **kwargs
230237
plt_set = {'fontsize': 18, 'legend_fontsize': 20, 'labelsize': 28, 'linecolor': '#f9665e', 'linewidth': 1, 'dpi': 100}
231238
for key, value in kwargs.items():
232239
plt_set[key] = value
240+
233241
if not bandwidth:
234242
bandwidth = self.best_bandwidth_value
235243
if bounds != None:
@@ -238,25 +246,24 @@ def density_plot(self, bounds = None, bandwidth = None, outfile = None, **kwargs
238246
lbound, ubound = self.replicates[0] - 2*self.best_bandwidth_value, self.replicates[-1] + 2*self.best_bandwidth_value
239247

240248
pdf_from_kde = helpers.get_kde(self.replicates, bandwidth)
241-
242-
xgrid = np.linspace(lbound, ubound, len(self.replicates) * 100)
249+
xgrid = np.linspace(lbound, ubound, plt_set['dpi'] * 2)
243250
density = [pdf_from_kde(x) for x in xgrid]
244251

245-
plt.rcParams.update({'font.size': plt_set['fontsize']})
246-
plt.rcParams.update({'legend.fontsize': plt_set['legend_fontsize']})
247-
plt.rcParams.update({'axes.labelsize': plt_set['labelsize']})
252+
plt.rc('font', size = plt_set['fontsize'])
253+
plt.rc('legend', fontsize = plt_set['legend_fontsize'])
254+
plt.rc('axes', labelsize = plt_set['labelsize'])
255+
fig, ax = plt.subplots()
248256

249-
plt.xlim(lbound, ubound)
250-
plt.xlabel('Value of object of interest')
251-
plt.ylabel('Density')
252-
plt.plot(xgrid, density, linewidth = plt_set['linewidth'], color = plt_set['linecolor'])
253-
plt.plot([self.replicates[0], self.replicates[-1]], [0.0001, 0.0001], '|k', markeredgewidth = 1, label = 'Range of bootstrap replicates')
254-
plt.legend(loc = 'best', fontsize = 'x-small', markerscale = 0.75)
257+
ax.set_xlim(lbound, ubound)
258+
ax.set_xlabel('Value of object of interest')
259+
ax.set_ylabel('Density')
260+
ax.plot(xgrid, density, linewidth = plt_set['linewidth'], color = plt_set['linecolor'])
261+
ax.plot([self.replicates[0], self.replicates[-1]], [0.0001, 0.0001], '|k', markeredgewidth = 1, label = 'Range of bootstrap replicates')
262+
ax.legend(loc = 'best', fontsize = 'x-small', markerscale = 0.75)
255263

256264
if not outfile == None:
257-
plt.savefig(outfile, transparent = True, dpi = plt_set['dpi'])
258-
plt.clf()
259-
mpl.rcParams.update(mpl.rcParamsDefault)
265+
fig.savefig(outfile, transparent = True, dpi = plt_set['dpi'])
266+
return fig
260267

261268
def get_tv_min(self, init_values = None, optimization_bounds = None, bounds_of_integration = np.inf):
262269
"""

tests/test_BootstrapReport.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,6 @@ def test_crossings():
4242
test_replicates = pd.read_csv('examples/gamma_replicates.csv')['replicate_value'].values
4343
estimate, standard_error = 0, 1
4444
test = ObjectOfInterest(estimate = estimate, se = standard_error, replicates = test_replicates)
45-
# Test function makes it to `savefig` when plotting outfile
46-
with pytest.raises(AttributeError):
47-
test.get_crossings(outfile = True)
4845
test = ObjectOfInterest(estimate = estimate, se = standard_error, \
4946
replicates = norm.ppf(np.linspace(0.01, 1, 100), loc = estimate, scale = standard_error))
5047
test.get_crossings()

0 commit comments

Comments
 (0)