class ECBLCalibStateModelView(ModelView): '''Model in a viewable window. ''' model = Instance(ECBLCalibState) def _model_default(self): return ECBLCalibState() cs_state = Property(Instance(ECBCrossSectionState), depends_on = 'model') @cached_property def _get_cs_state(self): return self.model.cs_state data_changed = Event figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor = 'white') return figure replot = Button() def _replot_fired(self): ax = self.figure.add_subplot(1, 1, 1) self.model.calibrated_ecb_law.plot(ax) self.data_changed = True clear = Button() def _clear_fired(self): self.figure.clear() self.data_changed = True calibrated_ecb_law = Property(Instance(ECBLBase), depends_on = 'model') @cached_property def _get_calibrated_ecb_law(self): return self.model.calibrated_ecb_law view = View(HSplit(VGroup( Item('cs_state', label = 'Cross section', show_label = False), Item('model@', show_label = False), Item('calibrated_ecb_law@', show_label = False, resizable = True), ), Group(HGroup( Item('replot', show_label = False), Item('clear', show_label = False), ), Item('figure', editor = MPLFigureEditor(), resizable = True, show_label = False), id = 'simexdb.plot_sheet', label = 'plot sheet', dock = 'tab', ), ), width = 0.5, height = 0.4, buttons = ['OK', 'Cancel'], resizable = True)
class Demo(HasTraits): '''Demo class for response functions''' fiber_tt_2p = Instance(SPIRRIDLAB) def _fiber_tt_2p_default(self): return fiber_tt_2p.create_demo_object() fiber_tt_5p = Instance(SPIRRIDLAB) def _fiber_tt_5p_default(self): return fiber_tt_5p.create_demo_object() fiber_po_8p = Instance(SPIRRIDLAB) def _fiber_po_8p_default(self): return fiber_po_8p.create_demo_object() fiber_cb_8p = Button() def _fiber_cb_8p_fired(self): return fiber_cb_8p.create_demo_object() mask_arr_b = Button() def _mask_arr_b_fired(self): return mask_arr.main() numexpr_b = Button() def _numexpr_b_fired(self): return numexpr_test.main() script_b = Button() def _script_b_fired(self): return script.main() traits_view = View(Item('fiber_tt_2p', show_label=False), Item('fiber_tt_5p', show_label=False), Item('fiber_po_8p', show_label=False), Item('fiber_cb_8p', show_label=False), Item('mask_arr_b', show_label=False), Item('numexpr_b', show_label=False), Item('script_b', show_label=False), width=0.2, height=0.3, buttons=['OK', 'Cancel'])
class ConstitutiveLawModelView(ModelView): model = Instance(CLBase) data_changed = Event figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') return figure replot = Button() def _replot_fired(self): ax = self.figure.add_subplot(1, 1, 1) self.model.plot(ax) self.data_changed = True clear = Button() def _clear_fired(self): self.figure.clear() self.data_changed = True traits_view = View(HSplit( Group( Item('model', style='custom', show_label=False, resizable=True), scrollable=True, ), Group( HGroup( Item('replot', show_label=False), Item('clear', show_label=False), ), Item('figure', editor=MPLFigureEditor(), resizable=True, show_label=False), id='simexdb.plot_sheet', label='plot sheet', dock='tab', ), ), width=0.5, height=0.4, resizable=True, buttons=['OK', 'Cancel'])
class AnalyticalFunction( HasTraits ): expression = Expression('x**2', auto_set = False, enter_set = True ) refresh = Button('redraw') def _refresh_fired(self): xdata = linspace(0.001,10,10000) fneval = frompyfunc( lambda x: eval( self.expression ), 1, 1 ) ydata = fneval( xdata ) self.mfn.set( xdata = xdata, ydata = ydata ) self.mfn.data_changed = True mfn = Instance( MFnLineArray ) def _mfn_default( self ): return MFnLineArray() @on_trait_change('expression' ) def update_mfn(self): self._refresh_fired() view_mpl = View( HGroup( Item( 'expression' ), Item('refresh' ) ), Item( 'mfn', editor = MFnMatplotlibEditor( adapter = a ), show_label = False ), resizable = True, scrollable = True, height = 0.5, width = 0.5 ) view_chaco = View( HGroup( Item( 'expression' ), Item('refresh' ) ), Item( 'mfn', editor = MFnChacoEditor( adapter = a ), resizable = True, show_label = False ), resizable = True, scrollable = True, height = 0.3, width = 0.3 )
class ResultView(HasTraits): spirrid_view = Instance(SPIRRIDModelView) title = Str('result plot') n_samples = Int(10) figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') #figure.add_axes( [0.08, 0.13, 0.85, 0.74] ) return figure data_changed = Event(True) clear = Button def _clear_fired(self): axes = self.figure.axes[0] axes.clear() self.data_changed = True def get_rvs_theta_arr(self, n_samples): rvs_theta_arr = array([ repeat(value, n_samples) for value in self.spirrid_view.model.rf.param_values ]) for idx, name in enumerate(self.spirrid_view.model.rf.param_keys): rv = self.spirrid_view.model.rv_dict.get(name, None) if rv: rvs_theta_arr[idx, :] = rv.get_rvs_theta_arr(n_samples) return rvs_theta_arr sample = Button(desc='Show samples') def _sample_fired(self): n_samples = 20 self.spirrid_view.model.set( min_eps=0.00, max_eps=self.spirrid_view.max_eps, n_eps=self.spirrid_view.n_eps, ) # get the parameter combinations for plotting rvs_theta_arr = self.get_rvs_theta_arr(n_samples) eps_arr = self.spirrid_view.model.eps_arr figure = self.figure axes = figure.gca() for theta_arr in rvs_theta_arr.T: q_arr = self.spirrid_view.model.rf(eps_arr, *theta_arr) axes.plot(eps_arr, q_arr, color='grey') self.data_changed = True @on_trait_change('spirrid_view.data_changed') def _redraw(self): figure = self.figure axes = figure.gca() mc = self.spirrid_view.model.mean_curve xdata = mc.xdata mean_per_fiber = mc.ydata # total expectation for independent variables = product of marginal expectations mean = mean_per_fiber * self.spirrid_view.mean_parallel_links axes.set_title(self.spirrid_view.plot_title, weight='bold') axes.plot(xdata, mean, linewidth=2, label=self.spirrid_view.run_legend) if self.spirrid_view.stdev: # get the variance at x from SPIRRID variance = self.spirrid_view.model.var_curve.ydata # evaluate variance for the given mean and variance of parallel links # law of total variance D[xy] = E[x]*D[y] + D[x]*[E[y]]**2 variance = self.spirrid_view.mean_parallel_links * variance + \ self.spirrid_view.stdev_parallel_links ** 2 * mean_per_fiber ** 2 stdev = sqrt(variance) axes.plot(xdata, mean + stdev, linewidth=2, color='black', ls='dashed', label='stdev') axes.plot(xdata, mean - stdev, linewidth=2, ls='dashed', color='black') axes.fill_between(xdata, mean + stdev, mean - stdev, color='lightgrey') axes.set_xlabel(self.spirrid_view.label_x, weight='semibold') axes.set_ylabel(self.spirrid_view.label_y, weight='semibold') axes.legend(loc='best') if xdata.any() == 0.: self.figure.clear() self.data_changed = True traits_view = View( HGroup(Item('n_samples', label='No of samples'), Item('sample', show_label=False, resizable=False), Item('clear', show_label=False, resizable=False, springy=False)), Item('figure', show_label=False, editor=MPLFigureEditor()))
class RunTable(SimDBClass): '''Manage the combinations of exec configurations and randomization patterns. ''' name = Str(simdb=True) memsize = Float(1e4, simdb=True) s = Property(Instance(SPIRRID), depends_on='rf') @cached_property def _get_s(self): return SPIRRID(rf=self.rf, min_eps=0.00, max_eps=1.0, n_eps=20, compiler_verbose=0) rf = Instance(IRF, simdb=True) config_list = List(config=True) def _config_list_default(self): return ['I', 'IV'] config_dict = Property(depends_on='config_list') @cached_property def _get_config_dict(self): cd = {} for config_idx in self.config_list: cd[config_idx] = config_dict[config_idx] return cd rand_list = List(rand=True) run_arr = Property(Array, depends_on='+rand,+config') @cached_property def _get_run_arr(self): # generate the runs to be performed run_table = [[ SingleRun(run_table=self, config=config, rand_idx_arr=rand_idx_arr) for rand_idx_arr in self.rand_list ] for config in self.config_dict.items()] return array(run_table) exec_time_arr = Array n_int_arr = Array real_memsize_arr = Array calculate = Button() def _calculate_fired(self): s = self.run_arr.shape self.exec_time_arr = array( [run.exec_time for run in self.run_arr.flatten()]).reshape(s) self.n_int_arr = array([run.n_int for run in self.run_arr.flatten()]).reshape(s) self.real_memsize_arr = array( [run.real_memsize for run in self.run_arr.flatten()]).reshape(s) self.save() self._redraw_fired() clear = Button() def _clear_fired(self): figure = self.figure figure.clear() self.data_changed = True figure = Instance(Figure, transient=True) def _figure_default(self): figure = Figure(facecolor='white') #figure.add_axes( [0.08, 0.13, 0.85, 0.74] ) return figure data_changed = Event(True) normalized_numpy = Bool(True) c_code = Bool(False) redraw = Button() def _redraw_fired(self): figure = self.figure axes = figure.gca() self.plot(axes) self.data_changed = True redraw_in_window = Button() def _redraw_in_window_fired(self): figure = plt.figure(0) axes = figure.gca() self.plot(axes) plt.show() def plot(self, ax): exec_time_arr = self.exec_time_arr n_int_arr = self.n_int_arr[0, :] real_memsize_arr = self.real_memsize_arr[0, :] rand_arr = arange(len(self.rand_list)) + 1 width = 0.45 if exec_time_arr.shape[0] == 1: shift = width / 2.0 ax.bar(rand_arr - shift, exec_time_arr[0, :], width, color='lightgrey') elif self.exec_time_arr.shape[0] == 2: max_exec_time = nmax(exec_time_arr) ax.set_ylabel('$\mathrm{execution \, time \, [sec]}$', size=20) ax.set_xlabel( '$n_{\mathrm{rnd}} \;-\; \mathrm{number \, of \, random \, parameters}$', size=20) ax.bar(rand_arr - width, exec_time_arr[0, :], width, hatch='/', color='white', label='C') # , color = 'lightgrey' ) ax.bar(rand_arr, exec_time_arr[1, :], width, color='lightgrey', label='numpy') yscale = 1.25 ax_xlim = rand_arr[-1] + 1 ax_ylim = max_exec_time * yscale ax.set_xlim(0, ax_xlim) ax.set_ylim(0, ax_ylim) ax2 = ax.twinx() ydata = exec_time_arr[1, :] / exec_time_arr[0, :] ax2.plot(rand_arr, ydata, '-o', color='black', linewidth=1, label='numpy/C') ax2.plot([rand_arr[0] - 1, rand_arr[-1] + 1], [1, 1], '-') ax2.set_ylabel( '$\mathrm{time}( \mathsf{numpy} ) / \mathrm{ time }(\mathsf{C}) \; [-]$', size=20) ax2_ylim = nmax(ydata) * yscale ax2_xlim = rand_arr[-1] + 1 ax2.set_ylim(0, ax2_ylim) ax2.set_xlim(0, ax2_xlim) ax.set_xticks(rand_arr) ax.set_xticklabels(rand_arr, size=14) xticks = ['%.2g' % n_int for n_int in n_int_arr] ax3 = ax.twiny() ax3.set_xlim(0, rand_arr[-1] + 1) ax3.set_xticks(rand_arr) ax3.set_xlabel('$n_{\mathrm{int}}$', size=20) ax3.set_xticklabels(xticks, rotation=30) 'set the tick label size of the lower X axis' X_lower_tick = 14 xt = ax.get_xticklabels() for t in xt: t.set_fontsize(X_lower_tick) 'set the tick label size of the upper X axis' X_upper_tick = 12 xt = ax3.get_xticklabels() for t in xt: t.set_fontsize(X_upper_tick) 'set the tick label size of the Y axes' Y_tick = 14 yt = ax2.get_yticklabels() + ax.get_yticklabels() for t in yt: t.set_fontsize(Y_tick) 'set the legend position and font size' leg_fontsize = 16 leg = ax.legend(loc=(0.02, 0.83)) for t in leg.get_texts(): t.set_fontsize(leg_fontsize) leg = ax2.legend(loc=(0.705, 0.90)) for t in leg.get_texts(): t.set_fontsize(leg_fontsize) traits_view = View(Item('name'), Item('memsize'), Item('rf'), Item('config_dict'), Item('rand_list'), HGroup( Item('calculate', show_label=False), Item('redraw', show_label=False), Item('clear', show_label=False), Item('redraw_in_window', show_label=False), ), Item('figure', editor=MPLFigureEditor(), resizable=True, show_label=False), buttons=['OK', 'Cancel'])
class SPIRRIDLAB(HasTraits): '''Class used for elementary parametric studies of spirrid. ''' s = Instance(SPIRRID) evars = DelegatesTo('s') tvars = DelegatesTo('s') q = DelegatesTo('s') exact_arr = Array('float') dpi = Int plot_mode = Enum(['subplots', 'figures']) fig_output_dir = Directory('fig') @on_trait_change('fig_output_dir') def _check_dir(self): if os.access(self.fig_output_dir, os.F_OK) == False: os.mkdir(self.fig_output_dir) e_arr = Property def _get_e_arr(self): return self.s.evar_lst[0] hostname = Property def _get_hostname(self): return gethostname() qname = Str def get_qname(self): if self.qname == '': if isinstance(self.q, types.FunctionType): qname = self.q.__name__ else: # if isinstance(self.q, types.ClassType): qname = self.q.__class__.__name__ else: qname = self.qname return qname show_output = False save_output = True plot_sampling_idx = Array(value=[0, 1], dtype=int) def _plot_sampling(self, i, n_col, sampling_type, p=p, ylim=None, xlim=None): '''Construct a spirrid object, run the calculation plot the mu_q / e curve and save it in the subdirectory. ''' s = self.s s.sampling_type = sampling_type plot_idx = self.plot_sampling_idx qname = self.get_qname() # get n randomly selected realizations from the sampling theta = s.sampling.get_samples(500) tvar_x = s.tvar_lst[plot_idx[0]] tvar_y = s.tvar_lst[plot_idx[1]] min_x, max_x, d_x = s.sampling.get_theta_range(tvar_x) min_y, max_y, d_y = s.sampling.get_theta_range(tvar_y) # for vectorized execution add a dimension for control variable theta_args = [t[:, np.newaxis] for t in theta] q_arr = s.q(self.e_arr[None, :], *theta_args) if self.plot_mode == 'figures': f = p.figure(figsize=(7., 6.)) f.subplots_adjust(left=0.15, right=0.97, bottom=0.15, top=0.92) if self.plot_mode == 'subplots': if i == 0: f = p.figure() p.subplot('2%i%i' % (n_col, (i + 1))) p.plot(theta[plot_idx[0]], theta[plot_idx[1]], 'o', color='grey') p.xlabel('$\lambda$') p.ylabel('$\\xi$') p.xlim(min_x, max_x) p.ylim(min_y, max_y) p.title(s.sampling_type) if self.save_output: fname = os.path.join( self.fig_output_dir, qname + '_sampling_' + s.sampling_type + '.png') p.savefig(fname, dpi=self.dpi) if self.plot_mode == 'figures': f = p.figure(figsize=(7., 5)) f.subplots_adjust(left=0.15, right=0.97, bottom=0.18, top=0.91) elif self.plot_mode == 'subplots': p.subplot('2%i%i' % (n_col, (i + 5))) p.plot(self.e_arr, q_arr.T, color='grey') if len(self.exact_arr) > 0: p.plot(self.e_arr, self.exact_arr, label='exact solution', color='black', linestyle='--', linewidth=2) # numerically obtained result p.plot(self.e_arr, s.mu_q_arr, label='numerical integration', linewidth=3, color='black') p.title(s.sampling_type) p.xlabel('$\\varepsilon$ [-]') p.ylabel(r'$q(\varepsilon;\, \lambda,\, \xi)$') if ylim: p.ylim(0.0, ylim) if xlim: p.xlim(0.0, xlim) p.xticks(position=(0, -.015)) p.legend(loc=2) if self.save_output: fname = os.path.join(self.fig_output_dir, qname + '_' + s.sampling_type + '.png') p.savefig(fname, dpi=self.dpi) sampling_structure_btn = Button(label='compare sampling structure') @on_trait_change('sampling_structure_btn') def sampling_structure(self, **kw): '''Plot the response into the file in the fig subdirectory. ''' if self.plot_mode == 'subplots': p.rcdefaults() else: fsize = 28 p.rcParams['font.size'] = fsize rc('legend', fontsize=fsize - 8) rc('axes', titlesize=fsize) rc('axes', labelsize=fsize + 6) rc('xtick', labelsize=fsize - 8) rc('ytick', labelsize=fsize - 8) rc('xtick.major', pad=8) s_lst = ['TGrid', 'PGrid', 'MCS', 'LHS'] for i, s in enumerate(s_lst): self._plot_sampling(i, len(s_lst), sampling_type=s, **kw) if self.show_output: p.show() n_int_range = Array() #=========================================================================== # Output file names for sampling efficiency #=========================================================================== fname_sampling_efficiency_time_nint = Property def _get_fname_sampling_efficiency_time_nint(self): return self.get_qname( ) + '_' + '%s' % self.hostname + '_time_nint' + '.png' fname_sampling_efficiency_error_nint = Property def _get_fname_sampling_efficiency_error_nint(self): return self.get_qname( ) + '_' + '%s' % self.hostname + '_error_nint' + '.png' fname_sampling_efficiency_error_time = Property def _get_fname_sampling_efficiency_error_time(self): return self.get_qname( ) + '_' + '%s' % self.hostname + '_error_time' + '.png' fnames_sampling_efficiency = Property def _get_fnames_sampling_efficiency(self): fnames = [self.fname_sampling_efficiency_time_nint] if len(self.exact_arr) > 0: fnames += [ self.fname_sampling_efficiency_error_nint, self.fname_sampling_efficiency_error_time ] return fnames #=========================================================================== # Run sampling efficiency studies #=========================================================================== sampling_types = Array(value=['TGrid', 'PGrid', 'MCS', 'LHS'], dtype=str) sampling_efficiency_btn = Button(label='compare sampling efficiency') @on_trait_change('sampling_efficiency_btn') def sampling_efficiency(self): ''' Run the code for all available sampling types. Plot the results. ''' def run_estimation(n_int, sampling_type): # instantiate spirrid with samplingetization methods print 'running', sampling_type, n_int self.s.set(n_int=n_int, sampling_type=sampling_type) n_sim = self.s.sampling.n_sim exec_time = np.sum(self.s.exec_time) return self.s.mu_q_arr, exec_time, n_sim # vectorize the estimation to accept arrays run_estimation_vct = np.vectorize(run_estimation, [object, float, int]) #=========================================================================== # Generate the inspected domain of input parameters using broadcasting #=========================================================================== run_estimation_vct([5], ['PGrid']) sampling_types = self.sampling_types sampling_colors = np.array( ['grey', 'black', 'grey', 'black'], dtype=str) # 'blue', 'green', 'red', 'magenta' sampling_linestyle = np.array(['--', '--', '-', '-'], dtype=str) # run the estimation on all combinations of n_int and sampling_types mu_q, exec_time, n_sim_range = run_estimation_vct( self.n_int_range[:, None], sampling_types[None, :]) p.rcdefaults() f = p.figure(figsize=(12, 6)) f.subplots_adjust(left=0.06, right=0.94) #=========================================================================== # Plot the results #=========================================================================== p.subplot(1, 2, 1) p.title('response for %d $n_\mathrm{sim}$' % n_sim_range[-1, -1]) for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.plot(self.e_arr, mu_q[-1, i], color=color, label=sampling, linestyle=linestyle) if len(self.exact_arr) > 0: p.plot(self.e_arr, self.exact_arr, color='black', label='Exact solution') p.legend(loc=1) p.xlabel('e', fontsize=18) p.ylabel('q', fontsize=18) # @todo: get n_sim - x-axis p.subplot(1, 2, 2) for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], exec_time[:, i], color=color, label=sampling, linestyle=linestyle) p.legend(loc=2) p.xlabel('$n_\mathrm{sim}$', fontsize=18) p.ylabel('$t$ [s]', fontsize=18) if self.save_output: basename = self.fname_sampling_efficiency_time_nint fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) #=========================================================================== # Evaluate the error #=========================================================================== if len(self.exact_arr) > 0: er = ErrorEval(exact_arr=self.exact_arr) def eval_error(mu_q, error_measure): return error_measure(mu_q) eval_error_vct = np.vectorize(eval_error) error_measures = np.array( [er.eval_error_max, er.eval_error_energy, er.eval_error_rms]) error_table = eval_error_vct(mu_q[:, :, None], error_measures[None, None, :]) f = p.figure(figsize=(14, 6)) f.subplots_adjust(left=0.07, right=0.97, wspace=0.26) p.subplot(1, 2, 1) p.title('max rel. lack of fit') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], error_table[:, i, 0], color=color, label=sampling, linestyle=linestyle) #p.ylim( 0, 10 ) p.legend() p.xlabel('$n_\mathrm{sim}$', fontsize=18) p.ylabel('$\mathrm{e}_{\max}$ [-]', fontsize=18) p.subplot(1, 2, 2) p.title('rel. root mean square error') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(n_sim_range[:, i], error_table[:, i, 2], color=color, label=sampling, linestyle=linestyle) p.legend() p.xlabel('$n_{\mathrm{sim}}$', fontsize=18) p.ylabel('$\mathrm{e}_{\mathrm{rms}}$ [-]', fontsize=18) if self.save_output: basename = self.fname_sampling_efficiency_error_nint fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) f = p.figure(figsize=(14, 6)) f.subplots_adjust(left=0.07, right=0.97, wspace=0.26) p.subplot(1, 2, 1) p.title('rel. max lack of fit') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(exec_time[:, i], error_table[:, i, 0], color=color, label=sampling, linestyle=linestyle) p.legend() p.xlabel('time [s]', fontsize=18) p.ylabel('$\mathrm{e}_{\max}$ [-]', fontsize=18) p.subplot(1, 2, 2) p.title('rel. root mean square error') for i, (sampling, color, linestyle) in enumerate( zip(sampling_types, sampling_colors, sampling_linestyle)): p.loglog(exec_time[:, i], error_table[:, i, 2], color=color, label=sampling, linestyle=linestyle) p.legend() p.xlabel('time [s]', fontsize=18) p.ylabel('$\mathrm{e}_{\mathrm{rms}}$ [-]', fontsize=18) if self.save_output: basename = self.fname_sampling_efficiency_error_time fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) if self.show_output: p.show() #=========================================================================== # Efficiency of numpy versus C code #=========================================================================== run_lst_detailed_config = Property(List) def _get_run_lst_detailed_config(self): run_lst = [] if hasattr(self.q, 'c_code'): run_lst += [ # ('c', # {'cached_dG' : True, # 'compiled_eps_loop' : True }, # 'go-', # '$\mathsf{C}_{\\varepsilon} \{\, \mathsf{C}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot G[\\theta] \,\}\,\} $ - %4.2f sec', # ), # ('c', # {'cached_dG' : True, # 'compiled_eps_loop' : False }, # 'r-2', # '$\mathsf{Python} _{\\varepsilon} \{\, \mathsf{C}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot G[\\theta] \,\}\,\} $ - %4.2f sec' # ), # ('c', # {'cached_dG' : False, # 'compiled_eps_loop' : True }, # 'r-2', # '$\mathsf{C}_{\\varepsilon} \{\, \mathsf{C}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot g[\\theta_1] \cdot \ldots \cdot g[\\theta_m] \,\}\,\} $ - %4.2f sec' # ), ( 'c', { 'cached_dG': False, 'compiled_eps_loop': False }, 'bx-', '$\mathsf{Python} _{\\varepsilon} \{\, \mathsf{C}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot g[\\theta_1] \cdot \ldots \cdot g[\\theta_m] \,\} \,\} $ - %4.2f sec', ) ] if hasattr(self.q, 'cython_code'): run_lst += [ # ('cython', # {'cached_dG' : True, # 'compiled_eps_loop' : True }, # 'go-', # '$\mathsf{Cython}_{\\varepsilon} \{\, \mathsf{Cython}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot G[\\theta] \,\}\,\} $ - %4.2f sec', # ), # ('cython', # {'cached_dG' : True, # 'compiled_eps_loop' : False }, # 'r-2', # '$\mathsf{Python} _{\\varepsilon} \{\, \mathsf{Cython}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot G[\\theta] \,\}\,\} $ - %4.2f sec' # ), # ('cython', # {'cached_dG' : False, # 'compiled_eps_loop' : True }, # 'r-2', # '$\mathsf{Cython}_{\\varepsilon} \{\, \mathsf{Cython}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot g[\\theta_1] \cdot \ldots \cdot g[\\theta_m] \,\}\,\} $ - %4.2f sec' # ), # ('cython', # {'cached_dG' : False, # 'compiled_eps_loop' : False }, # 'bx-', # '$\mathsf{Python} _{\\varepsilon} \{\, \mathsf{Cython}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot g[\\theta_1] \cdot \ldots \cdot g[\\theta_m] \,\} \,\} $ - %4.2f sec', # ) ] if hasattr(self.q, '__call__'): run_lst += [ # ('numpy', # {}, # 'y--', # '$\mathsf{Python}_{\\varepsilon} \{\, \mathsf{Numpy}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot G[\\theta] \,\} \,\} $ - %4.2f sec' # ) ] return run_lst # number of recalculations to get new time. n_recalc = Int(2) def codegen_efficiency(self): # define a tables with the run configurations to start in a batch basenames = [] qname = self.get_qname() s = self.s legend = [] legend_lst = [] time_lst = [] p.figure() for idx, run in enumerate(self.run_lst_detailed_config): code, run_options, plot_options, legend_string = run s.codegen_type = code s.codegen.set(**run_options) print 'run', idx, run_options for i in range(self.n_recalc): s.recalc = True # automatically proagated within spirrid print 'execution time', s.exec_time p.plot(s.evar_lst[0], s.mu_q_arr, plot_options) # @todo: this is not portable!! #legend.append(legend_string % s.exec_time) #legend_lst.append(legend_string[:-12]) time_lst.append(s.exec_time) p.xlabel('strain [-]') p.ylabel('stress') #p.legend(legend, loc = 2) p.title(qname) if self.save_output: print 'saving codegen_efficiency' basename = qname + '_' + 'codegen_efficiency' + '.png' basenames.append(basename) fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) self._bar_plot(legend_lst, time_lst) p.title('%s' % s.sampling_type) if self.save_output: basename = qname + '_' + 'codegen_efficiency_%s' % s.sampling_type + '.png' basenames.append(basename) fname = os.path.join(self.fig_output_dir, basename) p.savefig(fname, dpi=self.dpi) if self.show_output: p.show() return basenames #=========================================================================== # Efficiency of numpy versus C code #=========================================================================== run_lst_language_config = Property(List) def _get_run_lst_language_config(self): run_lst = [] if hasattr(self.q, 'c_code'): run_lst += [( 'c', { 'cached_dG': False, 'compiled_eps_loop': False }, 'bx-', '$\mathsf{Python} _{\\varepsilon} \{\, \mathsf{C}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot g[\\theta_1] \cdot \ldots \cdot g[\\theta_m] \,\} \,\} $ - %4.2f sec', )] if hasattr(self.q, 'cython_code'): run_lst += [( 'cython', { 'cached_dG': False, 'compiled_eps_loop': False }, 'bx-', '$\mathsf{Python} _{\\varepsilon} \{\, \mathsf{Cython}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot g[\\theta_1] \cdot \ldots \cdot g[\\theta_m] \,\} \,\} $ - %4.2f sec', )] if hasattr(self.q, '__call__'): run_lst += [( 'numpy', {}, 'y--', '$\mathsf{Python}_{\\varepsilon} \{\, \mathsf{Numpy}_{\\theta} \{\, q(\\varepsilon,\\theta) \cdot G[\\theta] \,\} \,\} $ - %4.2f sec' )] return run_lst extra_compiler_args = Bool(True) le_sampling_lst = List(['LHS', 'PGrid']) le_n_int_lst = List([440, 5000]) #=========================================================================== # Output file names for language efficiency #=========================================================================== fnames_language_efficiency = Property def _get_fnames_language_efficiency(self): return [ '%s_codegen_efficiency_%s_extra_%s.png' % (self.qname, self.hostname, extra) for extra in [self.extra_compiler_args] ] language_efficiency_btn = Button(label='compare language efficiency') @on_trait_change('language_efficiency_btn') def codegen_language_efficiency(self): # define a tables with the run configurations to start in a batch home_dir = expanduser("~") # pyxbld_dir = os.path.join(home_dir, '.pyxbld') # if os.path.exists(pyxbld_dir): # shutil.rmtree(pyxbld_dir) python_compiled_dir = os.path.join(home_dir, '.python27_compiled') if os.path.exists(python_compiled_dir): shutil.rmtree(python_compiled_dir) for extra, fname in zip([self.extra_compiler_args], self.fnames_language_efficiency): print 'extra compilation args:', extra legend_lst = [] error_lst = [] n_sim_lst = [] exec_times_sampling = [] meth_lst = zip(self.le_sampling_lst, self.le_n_int_lst) for item, n_int in meth_lst: print 'sampling method:', item s = self.s s.exec_time # eliminate first load time delay (first column) s.n_int = n_int s.sampling_type = item exec_times_lang = [] for idx, run in enumerate(self.run_lst_language_config): code, run_options, plot_options, legend_string = run #os.system('rm -fr ~/.python27_compiled') s.codegen_type = code s.codegen.set(**run_options) if s.codegen_type == 'c': s.codegen.set(**dict(use_extra=extra)) print 'run', idx, run_options exec_times_run = [] for i in range(self.n_recalc): s.recalc = True # automatically propagated exec_times_run.append(s.exec_time) print 'execution time', s.exec_time legend_lst.append(legend_string[:-12]) if s.codegen_type == 'c': # load weave.inline time from tmp file and fix values in time_arr #@todo - does not work on windows import tempfile tdir = tempfile.gettempdir() f = open(os.path.join(tdir, 'w_time'), 'r') value_t = float(f.read()) f.close() exec_times_run[0][1] = value_t exec_times_run[0][2] -= value_t exec_times_lang.append(exec_times_run) else: exec_times_lang.append(exec_times_run) print 'legend_lst', legend_lst n_sim_lst.append(s.sampling.n_sim) exec_times_sampling.append(exec_times_lang) #=========================================================================== # Evaluate the error #=========================================================================== if len(self.exact_arr) > 0: er = ErrorEval(exact_arr=self.exact_arr) error_lst.append((er.eval_error_rms(s.mu_q_arr), er.eval_error_max(s.mu_q_arr))) times_arr = np.array(exec_times_sampling, dtype='d') self._multi_bar_plot(meth_lst, legend_lst, times_arr, error_lst, n_sim_lst) if self.save_output: fname_path = os.path.join(self.fig_output_dir, fname) p.savefig(fname_path, dpi=self.dpi) if self.show_output: p.show() def combination_efficiency(self, tvars_det, tvars_rand): ''' Run the code for all available random parameter combinations. Plot the results. ''' qname = self.get_qname() s = self.s s.set(sampling_type='TGrid') # list of all combinations of response function parameters rv_comb_lst = list(powerset(s.tvars.keys())) p.figure() exec_time_lst = [] for id, rv_comb in enumerate(rv_comb_lst[163:219]): # [1:-1] s.tvars = tvars_det print 'Combination', rv_comb for rv in rv_comb: s.tvars[rv] = tvars_rand[rv] #legend = [] #p.figure() time_lst = [] for idx, run in enumerate(self.run_lst): code, run_options, plot_options, legend_string = run print 'run', idx, run_options s.codegen_type = code s.codegen.set(**run_options) #p.plot(s.evar_lst[0], s.mu_q_arr, plot_options) #print 'integral of the pdf theta', s.eval_i_dG_grid() print 'execution time', s.exec_time time_lst.append(s.exec_time) #legend.append(legend_string % s.exec_time) exec_time_lst.append(time_lst) p.plot(np.array((1, 2, 3, 4)), np.array(exec_time_lst).T) p.xlabel('method') p.ylabel('time') if self.save_output: print 'saving codegen_efficiency' fname = os.path.join( self.fig_output_dir, qname + '_' + 'combination_efficiency' + '.png') p.savefig(fname, dpi=self.dpi) if self.show_output: p.title(s.q.title) p.show() def _bar_plot(self, legend_lst, time_lst): rc('font', size=15) #rc('font', family = 'serif', style = 'normal', variant = 'normal', stretch = 'normal', size = 15) fig = p.figure(figsize=(10, 5)) n_tests = len(time_lst) times = np.array(time_lst) x_norm = times[1] xmax = times.max() rel_xmax = xmax / x_norm rel_times = times / x_norm m = int(rel_xmax % 10) if m < 5: x_max_plt = int(rel_xmax) - m + 10 else: x_max_plt = int(rel_xmax) - m + 15 ax1 = fig.add_subplot(111) p.subplots_adjust(left=0.45, right=0.88) #fig.canvas.set_window_title('window title') pos = np.arange(n_tests) + 0.5 rects = ax1.barh(pos, rel_times, align='center', height=0.5, color='w', edgecolor='k') ax1.set_xlabel('normalized execution time [-]') ax1.axis([0, x_max_plt, 0, n_tests]) ax1.set_yticks(pos) ax1.set_yticklabels(legend_lst) for rect, t in zip(rects, rel_times): width = rect.get_width() xloc = width + (0.03 * rel_xmax) clr = 'black' align = 'left' yloc = rect.get_y() + rect.get_height() / 2.0 ax1.text(xloc, yloc, '%4.2f' % t, horizontalalignment=align, verticalalignment='center', color=clr) #, weight = 'bold') ax2 = ax1.twinx() ax1.plot([1, 1], [0, n_tests], 'k--') ax2.set_yticks([0] + list(pos) + [n_tests]) ax2.set_yticklabels([''] + ['%4.2f s' % s for s in list(times)] + ['']) ax2.set_xticks([0, 1] + range(5, x_max_plt + 1, 5)) ax2.set_xticklabels( ['%i' % s for s in ([0, 1] + range(5, x_max_plt + 1, 5))]) def _multi_bar_plot(self, title_lst, legend_lst, time_arr, error_lst, n_sim_lst): '''Plot the results if the code efficiency. ''' p.rcdefaults() fsize = 14 fig = p.figure(figsize=(15, 3)) rc('font', size=fsize) rc('legend', fontsize=fsize - 2) legend_lst = ['weave', 'cython', 'numpy'] # times are stored in 3d array - dimensions are: n_sampling, n_lang, n_run, n_times = time_arr.shape print 'arr', time_arr.shape times_sum = np.sum(time_arr, axis=n_times) p.subplots_adjust(left=0.1, right=0.95, wspace=0.1, bottom=0.15, top=0.8) for meth_i in range(n_sampling): ax1 = fig.add_subplot(1, n_sampling, meth_i + 1) ax1.set_xlabel('execution time [s]') ytick_pos = np.arange(n_lang) + 1 # ax1.axis([0, x_max_plt, 0, n_lang]) # todo: **2 n_vars if len(self.exact_arr) > 0: ax1.set_title( '%s: $ n_\mathrm{sim} = %s, \mathrm{e}_\mathrm{rms}=%s, \mathrm{e}_\mathrm{max}=%s$' % (title_lst[meth_i][0], self._formatSciNotation('%.2e' % n_sim_lst[meth_i]), self._formatSciNotation('%.2e' % error_lst[meth_i][0]), self._formatSciNotation('%.2e' % error_lst[meth_i][1]))) else: ax1.set_title( '%s: $ n_\mathrm{sim} = %s$' % (title_lst[meth_i][0], self._formatSciNotation('%.2e' % n_sim_lst[meth_i]))) ax1.set_yticks(ytick_pos) if meth_i == 0: ax1.set_yticklabels(legend_lst, fontsize=fsize + 2) else: ax1.set_yticklabels([]) ax1.set_xlim(0, 1.2 * np.max(times_sum[meth_i])) distance = 0.2 height = 1.0 / n_run - distance offset = height / 2.0 colors = ['w', 'w', 'w', 'r', 'y', 'b', 'g', 'm'] hatches = ['/', '\\', 'x', '-', '+', '|', 'o', 'O', '.', '*'] label_lst = ['sampling', 'compilation', 'integration'] for i in range(n_run): pos = np.arange(n_lang) + 1 - offset + i * height end_bar_pos = np.zeros((n_lang, ), dtype='d') for j in range(n_times): if i > 0: label = label_lst[j] else: label = None bar_lengths = time_arr[meth_i, :, i, j] rects = ax1.barh(pos, bar_lengths, align='center', height=height, left=end_bar_pos, color=colors[j], edgecolor='k', hatch=hatches[j], label=label) end_bar_pos += bar_lengths for k in range(n_lang): x_val = times_sum[meth_i, k, i] + 0.01 * np.max(times_sum[meth_i]) ax1.text(x_val, pos[k], '$%4.2f\,$s' % x_val, horizontalalignment='left', verticalalignment='center', color='black') #, weight = 'bold') if meth_i == 0: ax1.text(0.02 * np.max(times_sum[0]), pos[k], '$%i.$' % (i + 1), horizontalalignment='left', verticalalignment='center', color='black', bbox=dict(pad=0., ec="w", fc="w")) p.legend(loc=0) def _formatSciNotation(self, s): # transform 1e+004 into 1e4, for example tup = s.split('e') try: significand = tup[0].rstrip('0').rstrip('.') sign = tup[1][0].replace('+', '') exponent = tup[1][1:].lstrip('0') if significand == '1': # reformat 1x10^y as 10^y significand = '' if exponent: exponent = '10^{%s%s}' % (sign, exponent) if significand and exponent: return r'%s{\cdot}%s' % (significand, exponent) else: return r'%s%s' % (significand, exponent) except IndexError, msg: return s
class SPIRRIDModelView(ModelView): title = Str('spirrid exec ctrl') model = Instance(SPIRRID) ins = Instance(NoOfFibers) def _ins_default(self): return NoOfFibers() eval = Button def _eval_fired(self): Specimen_Volume = self.ins.Lx * self.ins.Ly * self.ins.Lz self.no_of_fibers_in_specimen = ( Specimen_Volume * self.ins.Fiber_volume_fraction / 100) / ( pi * (self.ins.Fiber_diameter / 20)**2 * self.ins.Fiber_Length / 10) prob_crackbridging_fiber = (self.ins.Fiber_Length / (10 * 2)) / self.ins.Lx self.mean_parallel_links = prob_crackbridging_fiber * self.no_of_fibers_in_specimen self.stdev_parallel_links = (prob_crackbridging_fiber * self.no_of_fibers_in_specimen * (1 - prob_crackbridging_fiber))**0.5 run = Button(desc='Run the computation') def _run_fired(self): self.evaluate() run_legend = Str('mean response', desc='Legend to be added to the plot of the results') min_eps = Float(0.0, desc='minimum value of the control variable') max_eps = Float(1.0, desc='maximum value of the control variable') n_eps = Int(100, desc='resolution of the control variable') plot_title = Str('response', desc='diagram title') label_x = Str('epsilon', desc='label of the horizontal axis') label_y = Str('sigma', desc='label of the vertical axis') stdev = Bool(True) mean_parallel_links = Float(1., desc='mean number of parallel links (fibers)') stdev_parallel_links = Float( 0., desc='stdev of number of parallel links (fibers)') no_of_fibers_in_specimen = Float( 0., desc='Number of Fibers in the specimen', ) data_changed = Event(True) def evaluate(self): self.model.set( min_eps=0.00, max_eps=self.max_eps, n_eps=self.n_eps, ) # evaluate the mean curve self.model.mean_curve # evaluate the variance if the stdev bool is True if self.stdev: self.model.var_curve self.data_changed = True traits_view = View(VGroup( HGroup( Item('run_legend', resizable=False, label='Run label', width=80, springy=False), Item('run', show_label=False, resizable=False)), Tabbed( VGroup( Item('model.cached_dG', label='Cached weight factors', resizable=False, springy=False), Item('model.compiled_QdG_loop', label='Compiled loop over the integration product', springy=False), Item('model.compiled_eps_loop', enabled_when='model.compiled_QdG_loop', label='Compiled loop over the control variable', springy=False), scrollable=True, label='Execution configuration', id='spirrid.tview.exec_params', dock='tab', ), VGroup( HGroup(Item('min_eps', label='Min', springy=False, resizable=False), Item('max_eps', label='Max', springy=False, resizable=False), Item('n_eps', label='N', springy=False, resizable=False), label='Simulation range', show_border=True), HGroup(Item('stdev', label='plot standard deviation'), ), HSplit( HGroup( VGroup( Item('mean_parallel_links', label='mean No of fibers'), Item('stdev_parallel_links', label='stdev No of fibers'), )), VGroup( Item('@ins', label='evaluate No of fibers', show_label=False), VGroup( HGroup( Item('eval', show_label=False, resizable=False, label='Evaluate No of Fibers'), Item('no_of_fibers_in_specimen', label='No of Fibers in specimen', style='readonly')))), label='number of parralel fibers', show_border=True, scrollable=True, ), VGroup( Item('plot_title', label='title', resizable=False, springy=False), Item('label_x', label='x', resizable=False, springy=False), Item('label_y', label='y', resizable=False, springy=False), label='title and axes labels', show_border=True, scrollable=True, ), label='Execution control', id='spirrid.tview.view_params', dock='tab', ), scrollable=True, id='spirrid.tview.tabs', dock='tab', ), ), title='SPIRRID', id='spirrid.viewmodel', dock='tab', resizable=True, height=1.0, width=1.0)
class SPIRRIDModelView(ModelView): ''' Size effect depending on the yarn length ''' model = Instance(SPIRRID) def _model_changed(self): self.model.rf = self.rf rf_values = List(IRF) def _rf_values_default(self): return [ Filament() ] rf = Enum(values = 'rf_values') def _rf_default(self): return self.rf_values[0] def _rf_changed(self): # reset the rf in the spirrid model and in the rf_modelview self.model.rf = self.rf self.rf_model_view = RFModelView(model = self.rf) # actually, the view should be reusable but the model switch # did not work for whatever reason # the binding of the view generated by edit_traits does not # react to the change in the 'model' attribute. # # Remember - we are implementing a handler here # that has an associated view. # # self.rf.model_view.model = self.rf rf_model_view = Instance(RFModelView) def _rf_model_view_default(self): return RFModelView(model = self.rf) rv_list = Property(List(RIDVariable), depends_on = 'rf') @cached_property def _get_rv_list(self): return [ RIDVariable(spirrid = self.model, rf = self.rf, varname = nm, trait_value = st) for nm, st in zip(self.rf.param_keys, self.rf.param_values) ] selected_var = Instance(RIDVariable) def _selected_var_default(self): return self.rv_list[0] run = Button(desc = 'Run the computation') def _run_fired(self): self._redraw() sample = Button(desc = 'Show samples') def _sample_fired(self): n_samples = 50 self.model.set( min_eps = 0.00, max_eps = self.max_eps, n_eps = self.n_eps, ) # get the parameter combinations for plotting rvs_theta_arr = self.model.get_rvs_theta_arr(n_samples) eps_arr = self.model.eps_arr figure = self.figure axes = figure.gca() for theta_arr in rvs_theta_arr.T: q_arr = self.rf(eps_arr, *theta_arr) axes.plot(eps_arr, q_arr, color = 'grey') self.data_changed = True run_legend = Str('', desc = 'Legend to be added to the plot of the results') clear = Button def _clear_fired(self): axes = self.figure.axes[0] axes.clear() self.data_changed = True min_eps = Float(0.0, desc = 'minimum value of the control variable') max_eps = Float(1.0, desc = 'maximum value of the control variable') n_eps = Int(100, desc = 'resolution of the control variable') label_eps = Str('epsilon', desc = 'label of the horizontal axis') label_sig = Str('sigma', desc = 'label of the vertical axis') figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor = 'white') #figure.add_axes( [0.08, 0.13, 0.85, 0.74] ) return figure data_changed = Event(True) def _redraw(self): figure = self.figure axes = figure.gca() self.model.set( min_eps = 0.00, max_eps = self.max_eps, n_eps = self.n_eps, ) mc = self.model.mean_curve axes.plot(mc.xdata, mc.ydata, linewidth = 2, label = self.run_legend) axes.set_xlabel(self.label_eps) axes.set_ylabel(self.label_sig) axes.legend(loc = 'best') self.data_changed = True traits_view_tabbed = View( VGroup( HGroup( Item('run_legend', resizable = False, label = 'Run label', width = 80, springy = False), Item('run', show_label = False, resizable = False), Item('sample', show_label = False, resizable = False), Item('clear', show_label = False, resizable = False, springy = False) ), Tabbed( VGroup( Item('rf', show_label = False), Item('rf_model_view@', show_label = False, resizable = True), label = 'Deterministic model', id = 'spirrid.tview.model', ), Group( Item('rv_list', editor = rv_list_editor, show_label = False), id = 'spirrid.tview.randomization.rv', label = 'Model variables', ), Group( Item('selected_var@', show_label = False, resizable = True), id = 'spirrid.tview.randomization.distr', label = 'Distribution', ), VGroup( Item('model.cached_dG' , label = 'Cached weight factors', resizable = False, springy = False), Item('model.compiled_QdG_loop' , label = 'Compiled loop over the integration product', springy = False), Item('model.compiled_eps_loop' , enabled_when = 'model.compiled_QdG_loop', label = 'Compiled loop over the control variable', springy = False), scrollable = True, label = 'Execution configuration', id = 'spirrid.tview.exec_params', dock = 'tab', ), VGroup( HGroup( Item('min_eps' , label = 'Min', springy = False, resizable = False), Item('max_eps' , label = 'Max', springy = False, resizable = False), Item('n_eps' , label = 'N', springy = False, resizable = False), label = 'Simulation range', show_border = True ), VGroup( Item('label_eps' , label = 'x', resizable = False, springy = False), Item('label_sig' , label = 'y', resizable = False, springy = False), label = 'Axes labels', show_border = True, scrollable = True, ), label = 'Execution control', id = 'spirrid.tview.view_params', dock = 'tab', ), VGroup( Item('figure', editor = MPLFigureEditor(), resizable = True, show_label = False), label = 'Plot sheet', id = 'spirrid.tview.figure_window', dock = 'tab', scrollable = True, ), scrollable = True, id = 'spirrid.tview.tabs', dock = 'tab', ), ), title = 'SPIRRID', id = 'spirrid.viewmodel', dock = 'tab', resizable = True, height = 1.0, width = 1.0 )
class ECBLCalibHistModelView(ModelView): '''Model in a viewable window. ''' model = Instance(ECBLCalibHist) def _model_default(self): return ECBLCalibHist() cs_states = Property(List(Instance(ECBCrossSectionState)), depends_on='model') @cached_property def _get_cs_states(self): return self.model.cs_states current_cs_state = Instance(ECBCrossSectionState) def _current_cs_default(self): self.model.cs_states[0] def _current_cs_state_changed(self): self._replot_fired() eps_range = Property def _get_eps_range(self): eps_arr = [[cs_state.eps_up, cs_state.eps_lo] for cs_state in self.cs_states] eps_range = np.asarray(eps_arr) print 'eps_range', eps_range return (-np.max(eps_range[:, 1]), -np.min(eps_range[:, 0])) f_range = Property def _get_f_range(self): f_arr = [[np.max(cs_state.f_ti_arr), np.min(cs_state.f_cj_arr)] for cs_state in self.cs_states] f_range = np.asarray(f_arr) print 'eps_range', f_range return (-np.max(f_range[:, 0]), -np.min(f_range[:, 1])) data_changed = Event figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') return figure replot = Button() def _replot_fired(self): if self.current_cs_state: cs = self.current_cs_state else: cs = self.cs_states[0] cs.plot(self.figure, eps_range=self.eps_range, f_range=self.f_range) self.data_changed = True clear = Button() def _clear_fired(self): self.figure.clear() self.data_changed = True view = View(HSplit( VGroup( Item('cs_states', editor=cs_states_editor, label='Cross section', show_label=False), Item('model@', show_label=False), ), Group( HGroup( Item('replot', show_label=False), Item('clear', show_label=False), ), Item('figure', editor=MPLFigureEditor(), resizable=True, show_label=False), id='simexdb.plot_sheet', label='plot sheet', dock='tab', ), ), width=0.8, height=0.7, buttons=['OK', 'Cancel'], resizable=True)
class YMBReport(HasTraits): body_tex = Str() data = Instance(YMBData, changed=True) yarn = Property(Str, depends_on='+changed') @cached_property def _get_yarn(self): return self.data.source.yarn_type data_dir = Property(Str, depends_on='+changed') def _get_data_dir(self): return join(simdb.exdata_dir, 'trc', 'yarn_structure', self.yarn, 'raw_data') tex_dir = Property(Str, depends_on='+changed') def _get_tex_dir(self): return join(simdb.exdata_dir, 'trc', 'yarn_structure', self.yarn, 'report') fig_dir = Property(Str, depends_on='+changed') def _get_fig_dir(self): return join(simdb.exdata_dir, 'trc', 'yarn_structure', self.yarn, 'report', 'figs') # select data for report plot_3d_on = Bool(True) hist_rad_on = Bool(True) hist_cf_on = Bool(True) hist_bfl_on = Bool(True) hist_slack_on = Bool(True) corr_plot_rad_on = Bool(True) corr_plot_cf_on = Bool(True) corr_plot_bfl_on = Bool(True) corr_plot_slack_on = Bool(True) spirrid_on = Bool(False) hist_axes_adjust = List([0.12, 0.17, 0.68, 0.68]) corr_axes_adjust = List([0.15, 0.17, 0.75, 0.68]) n_bins = Int(40) ################################# # BUILD REPORT ################################# build = Button(label='build report') def _build_fired(self): self._directory_test() # get the yarn type yt = self.data.source.yarn_type if self.plot_3d_on == True: self._save_plot3d_fired() if self.hist_rad_on == True: self._save_rad_fired() if self.hist_cf_on == True: self._save_cf_fired() if self.hist_bfl_on == True: self._save_bfl_fired() if self.hist_slack_on == True: self._save_slack_fired() if self.corr_plot_rad_on == True: self._save_corr_plot_rad_fired() if self.corr_plot_cf_on == True: self._save_corr_plot_cf_fired() if self.corr_plot_bfl_on == True: self._save_corr_plot_bfl_fired() if self.corr_plot_slack_on == True: self._save_corr_plot_slack_fired() print '================' print 'Figure(s) saved' print '================' ################################# # BUILD REPORT ################################# filename = 'ymb_report_' + yt texfile = join(self.tex_dir, filename + '.tex') pdffile = join(self.tex_dir, filename + '.pdf') bodyfile = join(self.tex_dir, texfile) body_out = open(bodyfile, 'w') self.body_tex += 'Yarn with contact fraction limit = %s\n' % self.data.cf_limit if self.plot_3d_on == True: self.body_tex += self.plot3d_tex if self.hist_rad_on == True: self.body_tex += self.rad_tex if self.hist_cf_on == True: self.body_tex += self.cf_tex if self.hist_bfl_on == True: self.body_tex += self.bfl_tex if self.hist_slack_on == True: self.body_tex += self.slack_tex if self.corr_plot_rad_on == True: self.body_tex += self.corr_plot_rad_tex if self.corr_plot_cf_on == True: self.body_tex += self.corr_plot_cf_tex if self.corr_plot_bfl_on == True: self.body_tex += self.corr_plot_bfl_tex if self.corr_plot_slack_on == True: self.body_tex += self.corr_plot_slack_tex body_out.write(start_tex) body_out.write('\section*{ Yarn %s }' % (self.yarn)) body_out.write(self.body_tex) body_out.write(end_tex) body_out.close() os.system('cd ' + self.tex_dir + ';pdflatex -shell-escape ' + texfile) print '==============================' print 'Report written to %s', texfile print '==============================' os.system('acroread ' + pdffile + ' &') ################################# # 3d PLOT ################################# plot3d = Property(Instance(YMBView3D)) @cached_property def _get_plot3d(self): plot3d = YMBView3D(data=self.data, color_map='binary') # black-white return plot3d save_plot3d = Button(label='save plot3d figure') def _save_plot3d_fired(self): self._directory_test() filename = join(self.fig_dir, 'plot3d.png') self.plot3d.scene.save(filename, (1000, 800)) plot3d_tex = Property(Str) @cached_property def _get_plot3d_tex(self): filename = 'plot3d.png' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, '3D yarn plot') else: self._save_plot3d_fired() return fig_tex % (filename, '3D yarn plot') ################################# # HISTOGRAM PLOT AND SAVE ################################# hist_rad = Property(Instance(YMBHist)) # Instance(Figure ) @cached_property def _get_hist_rad(self): histog = YMBHist() histog.set(edge_color='black', face_color='0.75', axes_adjust=self.hist_axes_adjust) slider = YMBSlider(var_enum='radius', data=self.data) return histog.set(slider=slider, bins=self.n_bins, normed_on=True) save_rad = Button(label='save histogram of radius') def _save_rad_fired(self): self._directory_test() filename = join(self.fig_dir, 'radius.pdf') self.hist_rad.figure.savefig(filename, format='pdf') rad_tex = Property(Str) @cached_property def _get_rad_tex(self): filename = 'radius.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Histogram of filament radius') else: self._save_rad_fired() return fig_tex % (filename, 'Histogram of filament radius') hist_cf = Property(Instance(YMBHist)) @cached_property def _get_hist_cf(self): histog = YMBHist() histog.set(edge_color='black', face_color='0.75', axes_adjust=self.hist_axes_adjust) slider = YMBSlider(var_enum='contact fraction', data=self.data) return histog.set(slider=slider, bins=self.n_bins, normed_on=True) save_cf = Button(label='save histogram of contact fraction') def _save_cf_fired(self): self._directory_test() filename = join(self.fig_dir, 'contact_fraction.pdf') self.hist_cf.figure.savefig(filename, format='pdf') cf_tex = Property(Str) @cached_property def _get_cf_tex(self): filename = 'contact_fraction.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Histogram of contact fraction') else: self._save_cf_fired() return fig_tex % (filename, 'Histogram of contact fraction') hist_bfl = Property(Instance(YMBHist)) @cached_property def _get_hist_bfl(self): histog = YMBHist() histog.set(edge_color='black', face_color='0.75', axes_adjust=self.hist_axes_adjust) slider = YMBSlider(var_enum='bond free length', data=self.data) return histog.set(slider=slider, bins=self.n_bins, normed_on=True) save_bfl = Button(label='save histogram of bond free length') def _save_bfl_fired(self): self._directory_test() filename = 'bond_free_length.pdf' self.hist_bfl.figure.savefig(join(self.fig_dir, filename), format='pdf') bfl_tex = Property(Str) @cached_property def _get_bfl_tex(self): filename = 'bond_free_length.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Histogram of bond free length') else: self._save_bfl_fired() return fig_tex % (filename, 'Histogram of bond free length') hist_slack = Property(Instance(YMBHist)) @cached_property def _get_hist_slack(self): histog = YMBHist() histog.set(edge_color='black', face_color='0.75', axes_adjust=self.hist_axes_adjust) slider = YMBSlider(var_enum='slack', data=self.data) return histog.set(slider=slider, bins=self.n_bins, normed_on=True, xlimit_on=True, xlimit=0.03) save_slack = Button(label='save histogram of slack') def _save_slack_fired(self): self._directory_test() filename = join(self.fig_dir, 'slack.pdf') self.hist_slack.figure.savefig(filename, format='pdf') slack_tex = Property(Str) @cached_property def _get_slack_tex(self): filename = 'slack.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Histogram of slack') else: self._save_slack_fired() return fig_tex % (filename, 'Histogram of slack') corr_plot_rad = Property(Instance(YMBAutoCorrel)) @cached_property def _get_corr_plot_rad(self): plot = YMBAutoCorrelView() plot.set(color='black', axes_adjust=self.corr_axes_adjust) return plot.set( correl_data=YMBAutoCorrel(data=data, var_enum='radius')) save_corr_plot_rad = Button(label='save correlation plot of radius') def _save_corr_plot_rad_fired(self): self._directory_test() filename = join(self.fig_dir, 'corr_plot_rad.pdf') self.corr_plot_rad.figure.savefig(filename, format='pdf') corr_plot_rad_tex = Property(Str) @cached_property def _get_corr_plot_rad_tex(self): filename = 'corr_plot_rad.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Autocorrelation of radius') else: self._save_corr_plot_rad_fired() return fig_tex % (filename, 'Autocorrelation of radius') corr_plot_cf = Property(Instance(YMBAutoCorrel)) @cached_property def _get_corr_plot_cf(self): plot = YMBAutoCorrelView() plot.set(color='black', axes_adjust=self.corr_axes_adjust) return plot.set( correl_data=YMBAutoCorrel(data=data, var_enum='contact fraction')) save_corr_plot_cf = Button( label='save correlation plot of contact fraction') def _save_corr_plot_cf_fired(self): self._directory_test() filename = join(self.fig_dir, 'corr_plot_cf.pdf') self.corr_plot_cf.figure.savefig(filename, format='pdf') corr_plot_cf_tex = Property(Str) @cached_property def _get_corr_plot_cf_tex(self): filename = 'corr_plot_cf.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Autocorrelation of contact fraction') else: self._save_corr_plot_cf_fired() return fig_tex % (filename, 'Autocorrelation of contact fraction') corr_plot_bfl = Property(Instance(YMBAutoCorrel)) @cached_property def _get_corr_plot_bfl(self): plot = YMBAutoCorrelView() plot.set(color='black', axes_adjust=self.corr_axes_adjust) return plot.set( correl_data=YMBAutoCorrel(data=data, var_enum='bond free length')) save_corr_plot_bfl = Button(label='save corr plot of bond free length') def _save_corr_plot_bfl_fired(self): self._directory_test() filename = join(self.fig_dir, 'corr_plot_bfl.pdf') self.corr_plot_bfl.figure.savefig(filename, format='pdf') corr_plot_bfl_tex = Property(Str) @cached_property def _get_corr_plot_bfl_tex(self): filename = 'corr_plot_bfl.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Autocorrelation of bond free length') else: self._save_corr_plot_bfl_fired() return fig_tex % (filename, 'Autocorrelation of bond free length') corr_plot_slack = Property(Instance(YMBAutoCorrel)) @cached_property def _get_corr_plot_slack(self): plot = YMBAutoCorrelView() plot.set(color='black', axes_adjust=self.corr_axes_adjust) return plot.set(correl_data=YMBAutoCorrel(data=data, var_enum='slack')) save_corr_plot_slack = Button(label='save corr plot of slack') def _save_corr_plot_slack_fired(self): self._directory_test() filename = join(self.fig_dir, 'corr_plot_slack.pdf') self.corr_plot_slack.figure.savefig(filename, format='pdf') corr_plot_slack_tex = Property(Str) @cached_property def _get_corr_plot_slack_tex(self): filename = 'corr_plot_slack.pdf' if file_test(join(self.fig_dir, filename)) == True: return fig_tex % (filename, 'Autocorrelation of slack') else: self._save_corr_plot_slack_fired() return fig_tex % (filename, 'Autocorrelation of slack') ################################# # CORRELATION PLOT AND TABLE ################################# def corr_plot(self): return 0 ################################# # SPIRRID PLOT ################################# spirrid_plot = Property(Instance(YMBPullOut)) @cached_property def _get_spirrid_plot(self): return YMBPullOut(data=self.data) pdf_theta = Property(Instance(IPDistrib)) def _get_pdf_theta(self): theta = self.spirrid_plot.pdf_theta # theta.set( face_color = '0.75', edge_color = 'black', axes_adjust = [0.13, 0.18, 0.8, 0.7] ) return theta pdf_l = Property(Instance(IPDistrib)) def _get_pdf_l(self): return self.spirrid_plot.pdf_l pdf_phi = Property(Instance(IPDistrib)) def _get_pdf_phi(self): return self.spirrid_plot.pdf_phi pdf_xi = Property(Instance(IPDistrib)) def _get_pdf_xi(self): return self.spirrid_plot.pdf_xi.figure def _directory_test(self): if os.access(self.tex_dir, os.F_OK) == False: os.mkdir(self.tex_dir) if os.access(self.fig_dir, os.F_OK) == False: os.mkdir(self.fig_dir) traits_view = View( HSplit( Group( Item('data@', show_label=False), HGroup( VGrid( Item( 'plot_3d_on', label='plot3d', ), Item('save_plot3d', show_label=False, visible_when='plot_3d_on == True'), Item('_'), Item('hist_rad_on', label='radius_hist'), Item('save_rad', show_label=False, visible_when='hist_rad_on == True'), Item('hist_cf_on', label='cf_hist'), Item('save_cf', show_label=False, visible_when='hist_cf_on == True'), Item('hist_bfl_on', label='bfl_hist'), Item('save_bfl', show_label=False, visible_when='hist_bfl_on == True'), Item('hist_slack_on', label='slack_hist'), Item('save_slack', show_label=False, visible_when='hist_slack_on == True'), Item('_'), Item('corr_plot_rad_on', label='corr_plot_rad'), Item('save_corr_plot_rad', show_label=False, visible_when='hist_slack_on == True'), Item('corr_plot_cf_on', label='corr_plot_cf'), Item('save_corr_plot_cf', show_label=False, visible_when='hist_slack_on == True'), Item('corr_plot_bfl_on', label='corr_plot_bfl'), Item('save_corr_plot_bfl', show_label=False, visible_when='hist_slack_on == True'), Item('corr_plot_slack_on', label='corr_plot_slack'), Item('save_corr_plot_slack', show_label=False, visible_when='hist_slack_on == True'), ), VGrid(Item('spirrid_on'), ), ), Item('build'), label='report', id='report.bool', ), ), VGroup( HGroup( Item('hist_rad@', show_label=False), Item('hist_cf@', show_label=False), ), HGroup( Item('hist_bfl@', show_label=False), Item('hist_slack@', show_label=False), ), label='histograms', id='report.hist', ), VGroup( HGroup( Item('corr_plot_rad@', show_label=False), Item('corr_plot_cf@', show_label=False), ), HGroup( Item('corr_plot_bfl@', show_label=False), Item('corr_plot_slack@', show_label=False), ), label='correlation plot', id='report.corr_plot', ), # HGroup( # Group( # Item( 'pdf_theta@', show_label = False ), # Item( 'pdf_l@', show_label = False ), # ), # Group( # Item( 'pdf_phi@', show_label = False ), # Item( 'pdf_xi@', show_label = False ), # ), # label = 'pdf', # id = 'report.pdf', # #scrollable = True, # ), Group(Item('plot3d@', show_label=False), label='plot3d', id='report.plot3d'), resizable=True, title=u"Yarn name", handler=TitleHandler(), id='report.main', )