class YMBCrossCorrel(HasTraits): data = Instance(IYMBData) # convert the dictionary keys to an ordered list. var_name_list = Property(List) @cached_property def _get_var_name_list(self): return sorted(var_dict.keys()) # list of data arrays in the order of the var_name_list var_arr_list = Property(List, depends_on='data.input_change') @cached_property def _get_var_arr_list(self): return [ getattr(self.data, var_dict[var_name]).flatten()[:, None] for var_name in self.var_name_list ] corr_arr = Property(Array, depends_on='data.input_change') @cached_property def _get_corr_arr(self): print 'redrawing cross correl' # get the list of names and sort them alphabetically corr_data = ma.hstack(self.var_arr_list) # @kelidas: return small differences between ma and numpy corrcoef # return ma.corrcoef( corr_data, rowvar = False, allow_masked = True ) return MatSpearman(corr_data) figure = Instance(Figure) def _figure_default(self): figure = Figure() figure.add_axes([0.1, 0.1, 0.8, 0.8]) return figure data_changed = Event(True) @on_trait_change('data, data.input_change') def _redraw(self): figure = self.figure figure.clear() var_data = self.corr_arr figure.add_axes([0.1, 0.1, 0.8, 0.8]) axes = figure.axes[0] axes.clear() x_coor = arange(var_data.shape[1]) axes.grid() for i in range(0, var_data.shape[1]): axes.plot(x_coor[i:] - x_coor[i], var_data[i, (i):], '-x') axes.set_xlabel('$\mathrm{x}\, [\mu\mathrm{m}]$', fontsize=16) axes.set_ylabel('$\mathrm{correlation}$', fontsize=16) axes.set_ylim(-1, 1) self.data_changed = True traits_view_mpl = View( Group( # Group( Item( 'figure', style = 'custom', # editor = MPLFigureEditor(), # show_label = False ) # , id = 'figure.view' ), Item('corr_arr', show_label=False, style='readonly', editor=TabularEditor(adapter=ArrayAdapter()))), resizable=True, ) traits_view = View(Item('corr_arr', editor=tabular_editor, show_label=False), resizable=True, scrollable=True, buttons=['OK', 'Cancel'], width=1.0, height=0.5)
class RFView3D(ModelView): model = Instance(IRF) scalar_arr = Property(depends_on='var_enum') @cached_property def _get_scalar_arr(self): return getattr(self.data, self.var_enum_) color_map = Str('blue-red') scene = Instance(MlabSceneModel, ()) plot = Instance(PipelineBase) # When the scene is activated or parameters change the scene is updated @on_trait_change('model.') def update_plot(self): x_arrr, y_arrr, z_arrr = self.data.cut_data[0:3] scalar_arrr = self.scalar_arr mask = y_arrr > -1 x = x_arrr[mask] y = y_arrr[mask] z = z_arrr[mask] scalar = scalar_arrr[mask] connections = -ones_like(x_arrr) mesk = x_arrr.filled() > -1 connections[mesk] = list(range(0, len(connections[mesk]))) connections = connections[self.start_fib:self.end_fib + 1, :].filled() connection = connections.astype(int).copy() connection = connection.tolist() # TODO: better for i in range(0, self.data.n_cols + 1): for item in connection: try: item.remove(-1) except: pass if self.plot is None: print('plot 3d -- 1') #self.scene.parallel_projection = False pts = self.scene.mlab.pipeline.scalar_scatter( array(x), array(y), array(z), array(scalar)) pts.mlab_source.dataset.lines = connection self.plot = self.scene.mlab.pipeline.surface( self.scene.mlab.pipeline.tube( # fig.scene.mlab.pipeline.stripper( pts, figure=self.scene.mayavi_scene, # ), tube_sides=10, tube_radius=0.015, ), ) self.plot.actor.mapper.interpolate_scalars_before_mapping = True self.plot.module_manager.scalar_lut_manager.show_scalar_bar = True self.plot.module_manager.scalar_lut_manager.show_legend = True self.plot.module_manager.scalar_lut_manager.shadow = True self.plot.module_manager.scalar_lut_manager.label_text_property.italic = False self.plot.module_manager.scalar_lut_manager.scalar_bar.orientation = 'horizontal' self.plot.module_manager.scalar_lut_manager.scalar_bar_representation.position2 = array( [0.61775334, 0.17]) self.plot.module_manager.scalar_lut_manager.scalar_bar_representation.position = array( [0.18606834, 0.08273163]) self.plot.module_manager.scalar_lut_manager.scalar_bar.width = 0.17000000000000004 self.plot.module_manager.scalar_lut_manager.lut_mode = self.color_map #'black-white' self.plot.module_manager.scalar_lut_manager.data_name = self.var_enum self.plot.module_manager.scalar_lut_manager.label_text_property.font_family = 'times' self.plot.module_manager.scalar_lut_manager.label_text_property.shadow = True self.plot.module_manager.scalar_lut_manager.title_text_property.color = ( 0.0, 0.0, 0.0) self.plot.module_manager.scalar_lut_manager.label_text_property.color = ( 0.0, 0.0, 0.0) self.plot.module_manager.scalar_lut_manager.title_text_property.font_family = 'times' self.plot.module_manager.scalar_lut_manager.title_text_property.shadow = True #fig.scene.parallel_projection = True self.scene.scene.background = (1.0, 1.0, 1.0) self.scene.scene.camera.position = [ 16.319534155794827, 10.477447863842627, 6.1717943847883232 ] self.scene.scene.camera.focal_point = [ 3.8980860486356859, 2.4731178194274621, 0.14856957086692035 ] self.scene.scene.camera.view_angle = 30.0 self.scene.scene.camera.view_up = [ -0.27676100729835512, -0.26547169369097656, 0.92354107904740446 ] self.scene.scene.camera.clipping_range = [ 7.7372124315754673, 26.343575352248056 ] self.scene.scene.camera.compute_view_plane_normal() #fig.scene.reset_zoom() axes = Axes() self.scene.engine.add_filter(axes, self.plot) axes.label_text_property.font_family = 'times' axes.label_text_property.shadow = True axes.title_text_property.font_family = 'times' axes.title_text_property.shadow = True axes.property.color = (0.0, 0.0, 0.0) axes.title_text_property.color = (0.0, 0.0, 0.0) axes.label_text_property.color = (0.0, 0.0, 0.0) axes.axes.corner_offset = .1 axes.axes.x_label = 'x' axes.axes.y_label = 'y' axes.axes.z_label = 'z' else: print('plot 3d -- 2') #self.plot.mlab_source.dataset.reset() #self.plot.mlab_source.set( x = x, y = y, z = z, scalars = scalar ) #self.plot.mlab_source.dataset.points = array( [x, y, z] ).T self.plot.mlab_source.scalars = scalar self.plot.mlab_source.dataset.lines = connection self.plot.module_manager.scalar_lut_manager.data_name = self.var_enum # The layout of the dialog created view = View( Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=250, width=300, show_label=False), Group( '_', 'start_fib', 'end_fib', 'var_enum', ), resizable=True, )
class SimCrackLoc(IBVModel): '''Model assembling the components for studying the restrained crack localization. ''' geo_transform = Instance(FlawCenteredGeoTransform) def _geo_transform_default(self): return FlawCenteredGeoTransform() shape = Int(10, desc='Number of finite elements', ps_levsls=(10, 40, 4), input=True) length = Float(1000, desc='Length of the simulated region', unit='mm', input=True) flaw_position = Float(500, input=True, unit='mm') flaw_radius = Float(100, input=True, unit='mm') reduction_factor = Float(0.9, input=True) elastic_fraction = Float(0.9, input=True) avg_radius = Float(400, input=True, unit='mm') # tensile strength of concrete f_m_t = Float(3.0, input=True, unit='MPa') epsilon_0 = Property(unit='-') def _get_epsilon_0(self): return self.f_m_t / self.E_m epsilon_f = Float(10, input=True, unit='-') h_m = Float(10, input=True, unit='mm') b_m = Float(8, input=True, unit='mm') A_m = Property(unit='m^2') def _get_A_m(self): return self.b_m * self.h_m E_m = Float(30.0e5, input=True, unit='MPa') E_f = Float(70.0e6, input=True, unit='MPa') A_f = Float(1.0, input=True, unit='mm^2') s_crit = Float(0.009, input=True, unit='mm') P_f = Property(depends_on='+input') @cached_property def _get_P_f(self): return sqrt(4 * self.A_f * pi) K_b = Property(depends_on='+input') @cached_property def _get_K_b(self): return self.T_max / self.s_crit tau_max = Float(0.0, input=True, unit='MPa') T_max = Property(depends_on='+input', unit='N/mm') @cached_property def _get_T_max(self): return self.tau_max * self.P_f rho = Property(depends_on='+input') @cached_property def _get_rho(self): return self.A_f / (self.A_f + self.A_m) #------------------------------------------------------- # Material model for the matrix #------------------------------------------------------- mats_m = Property(Instance(MATS1DDamageWithFlaw), depends_on='+input') @cached_property def _get_mats_m(self): mats_m = MATS1DDamageWithFlaw(E=self.E_m * self.A_m, flaw_position=self.flaw_position, flaw_radius=self.flaw_radius, reduction_factor=self.reduction_factor, epsilon_0=self.epsilon_0, epsilon_f=self.epsilon_f) return mats_m mats_f = Instance(MATS1DElastic) def _mats_f_default(self): mats_f = MATS1DElastic(E=self.E_f * self.A_f) return mats_f mats_b = Instance(MATS1DEval) def _mats_b_default(self): mats_b = MATS1DElastic(E=self.K_b) mats_b = MATS1DPlastic(E=self.K_b, sigma_y=self.T_max, K_bar=0., H_bar=0.) # plastic function of slip return mats_b mats_fb = Property(Instance(MATS1D5Bond), depends_on='+input') @cached_property def _get_mats_fb(self): # Material model construction return MATS1D5Bond( mats_phase1=MATS1DElastic(E=0), mats_phase2=self.mats_f, mats_ifslip=self.mats_b, mats_ifopen=MATS1DElastic( E=0) # elastic function of open - inactive ) #------------------------------------------------------- # Finite element type #------------------------------------------------------- fets_m = Property(depends_on='+input') @cached_property def _get_fets_m(self): fets_eval = FETS1D2L(mats_eval=self.mats_m) #fets_eval = FETS1D2L3U( mats_eval = self.mats_m ) return fets_eval fets_fb = Property(depends_on='+input') @cached_property def _get_fets_fb(self): return FETS1D52L4ULRH(mats_eval=self.mats_fb) #return FETS1D52L6ULRH( mats_eval = self.mats_fb ) #return FETS1D52L8ULRH( mats_eval = self.mats_fb ) #-------------------------------------------------------------------------------------- # Mesh integrator #-------------------------------------------------------------------------------------- fe_domain_structure = Property(depends_on='+input') @cached_property def _get_fe_domain_structure(self): '''Root of the domain hierarchy ''' elem_length = self.length / float(self.shape) fe_domain = FEDomain() fe_m_level = FERefinementGrid(name='matrix domain', domain=fe_domain, fets_eval=self.fets_m) fe_grid_m = FEGrid(name='matrix grid', coord_max=(self.length, ), shape=(self.shape, ), level=fe_m_level, fets_eval=self.fets_m, geo_transform=self.geo_transform) fe_fb_level = FERefinementGrid(name='fiber bond domain', domain=fe_domain, fets_eval=self.fets_fb) fe_grid_fb = FEGrid(coord_min=(0., length / 5.), coord_max=(length, 0.), shape=(self.shape, 1), level=fe_fb_level, fets_eval=self.fets_fb, geo_transform=self.geo_transform) return fe_domain, fe_grid_m, fe_grid_fb, fe_m_level, fe_fb_level fe_domain = Property def _get_fe_domain(self): return self.fe_domain_structure[0] fe_grid_m = Property def _get_fe_grid_m(self): return self.fe_domain_structure[1] fe_grid_fb = Property def _get_fe_grid_fb(self): return self.fe_domain_structure[2] fe_m_level = Property def _get_fe_m_level(self): return self.fe_domain_structure[3] fe_fb_level = Property def _get_fe_fb_level(self): return self.fe_domain_structure[4] #--------------------------------------------------------------------------- # Load scaling adapted to the elastic and inelastic regime #--------------------------------------------------------------------------- final_displ = Property(depends_on='+input') @cached_property def _get_final_displ(self): damage_onset_displ = self.mats_m.epsilon_0 * self.length return damage_onset_displ / self.elastic_fraction step_size = Property(depends_on='+input') @cached_property def _get_step_size(self): n_steps = self.n_steps return 1.0 / float(n_steps) time_function = Property(depends_on='+input') @cached_property def _get_time_function(self): '''Get the time function so that the elastic regime is skipped in a single step. ''' step_size = self.step_size elastic_value = self.elastic_fraction * 0.98 * self.reduction_factor inelastic_value = 1.0 - elastic_value def ls(t): if t <= step_size: return (elastic_value / step_size) * t else: return elastic_value + (t - step_size) * (inelastic_value) / ( 1 - step_size) return ls def plot_time_function(self, p): '''Plot the time function. ''' n_steps = self.n_steps mats = self.mats step_size = self.step_size ls_t = linspace(0, step_size * n_steps, n_steps + 1) ls_fn = frompyfunc(self.time_function, 1, 1) ls_v = ls_fn(ls_t) p.subplot(321) p.plot(ls_t, ls_v, 'ro-') final_epsilon = self.final_displ / self.length kappa = linspace(mats.epsilon_0, final_epsilon, 10) omega_fn = frompyfunc(lambda kappa: mats._get_omega(None, kappa), 1, 1) omega = omega_fn(kappa) kappa_scaled = (step_size + (1 - step_size) * (kappa - mats.epsilon_0) / (final_epsilon - mats.epsilon_0)) xdata = hstack([array([0.0], dtype=float), kappa_scaled]) ydata = hstack([array([0.0], dtype=float), omega]) p.plot(xdata, ydata, 'g') p.xlabel('regular time [-]') p.ylabel('scaled time [-]') run = Button @on_trait_change('run') def peval(self): '''Evaluation procedure. ''' #mv = MATS1DDamageView( model = mats_eval ) #mv.configure_traits() right_dof_m = self.fe_grid_m[-1, -1].dofs[0, 0, 0] right_dof_fb = self.fe_grid_fb[-1, -1, -1, -1].dofs[0, 0, 0] # Response tracers A = self.A_m + self.A_f self.sig_eps_m = RTraceGraph(name='F_u_m', var_y='F_int', idx_y=right_dof_m, var_x='U_k', idx_x=right_dof_m, transform_y='y / %g' % A) # Response tracers self.sig_eps_f = RTraceGraph(name='F_u_f', var_y='F_int', idx_y=right_dof_fb, var_x='U_k', idx_x=right_dof_fb, transform_y='y / %g' % A) self.eps_m_field = RTraceDomainListField(name='eps_m', position='int_pnts', var='eps_app', warp=False) self.eps_f_field = RTraceDomainListField(name='eps_f', position='int_pnts', var='mats_phase2_eps_app', warp=False) # Response tracers self.sig_m_field = RTraceDomainListField(name='sig_m', position='int_pnts', var='sig_app') self.sig_f_field = RTraceDomainListField(name='sig_f', position='int_pnts', var='mats_phase2_sig_app') self.omega_m_field = RTraceDomainListField(name='omega_m', position='int_pnts', var='omega', warp=False) self.shear_flow_field = RTraceDomainListField(name='shear flow', position='int_pnts', var='shear_flow', warp=False) self.slip_field = RTraceDomainListField(name='slip', position='int_pnts', var='slip', warp=False) avg_processor = None if self.avg_radius > 0.0: n_dofs = self.fe_domain.n_dofs avg_processor = RTUAvg(sd=self.fe_m_level, n_dofs=n_dofs, avg_fn=QuarticAF(radius=self.avg_radius)) ts = TStepper( u_processor=avg_processor, dof_resultants=True, sdomain=self.fe_domain, bcond_list=[ # define the left clamping BCSlice(var='u', value=0., dims=[0], slice=self.fe_grid_fb[0, 0, 0, :]), # BCSlice( var = 'u', value = 0., dims = [0], slice = self.fe_grid_m[ 0, 0 ] ), # loading at the right edge # BCSlice( var = 'f', value = 1, dims = [0], slice = domain[-1, -1, -1, 0], # time_function = ls ), BCSlice(var='u', value=self.final_displ, dims=[0], slice=self.fe_grid_fb[-1, -1, -1, :], time_function=self.time_function), # BCSlice( var = 'u', value = self.final_displ, dims = [0], slice = self.fe_grid_m[-1, -1], # time_function = self.time_function ), # fix horizontal displacement in the top layer # BCSlice( var = 'u', value = 0., dims = [0], slice = domain[:, -1, :, -1] ), # fix the vertical displacement all over the domain BCSlice(var='u', value=0., dims=[1], slice=self.fe_grid_fb[:, :, :, :]), # # Connect bond and matrix domains BCDofGroup(var='u', value=0., dims=[0], get_link_dof_method=self.fe_grid_fb.get_bottom_dofs, get_dof_method=self.fe_grid_m.get_all_dofs, link_coeffs=[1.]) ], rtrace_list=[ self.sig_eps_m, self.sig_eps_f, self.eps_m_field, self.eps_f_field, self.sig_m_field, self.sig_f_field, self.omega_m_field, self.shear_flow_field, self.slip_field, ]) # Add the time-loop control tloop = TLoop(tstepper=ts, KMAX=300, tolerance=1e-5, debug=False, verbose_iteration=True, verbose_time=False, tline=TLine(min=0.0, step=self.step_size, max=1.0)) tloop.on_accept_time_step = self.plot U = tloop.eval() self.sig_eps_f.refresh() max_sig_m = max(self.sig_eps_m.trace.ydata) return array([U[right_dof_m], max_sig_m], dtype='float_') #-------------------------------------------------------------------------------------- # Tracers #-------------------------------------------------------------------------------------- def plot_sig_eps(self, p): p.set_xlabel('control displacement [mm]') p.set_ylabel('stress [MPa]') self.sig_eps_m.refresh() self.sig_eps_m.trace.plot(p, 'o-') self.sig_eps_f.refresh() self.sig_eps_f.trace.plot(p, 'o-') p.plot(self.sig_eps_m.trace.xdata, self.sig_eps_m.trace.ydata + self.sig_eps_f.trace.ydata, 'o-') def plot_eps(self, p): eps_m = self.eps_m_field.subfields[0] xdata = eps_m.vtk_X[:, 0] ydata = eps_m.field_arr[:, 0, 0] idata = argsort(xdata) p.plot(xdata[idata], ydata[idata], 'o-') eps_f = self.eps_f_field.subfields[1] xdata = eps_f.vtk_X[:, 0] ydata = eps_f.field_arr[:, 0, 0] idata = argsort(xdata) p.plot(xdata[idata], ydata[idata], 'o-') p.set_ylim(ymin=0) p.set_xlabel('bar axis [mm]') p.set_ylabel('strain [-]') def plot_omega(self, p): omega_m = self.omega_m_field.subfields[0] xdata = omega_m.vtk_X[:, 0] ydata = omega_m.field_arr[:] idata = argsort(xdata) p.fill(xdata[idata], ydata[idata], facecolor='gray', alpha=0.2) print 'max omega', max(ydata[idata]) p.set_ylim(ymin=0, ymax=1.0) p.set_xlabel('bar axis [mm]') p.set_ylabel('omega [-]') def plot_sig(self, p): sig_m = self.sig_m_field.subfields[0] xdata = sig_m.vtk_X[:, 0] ydata = sig_m.field_arr[:, 0, 0] idata = argsort(xdata) ymax = max(ydata) p.plot(xdata[idata], ydata[idata], 'o-') sig_f = self.sig_f_field.subfields[1] xdata = sig_f.vtk_X[:, 0] ydata = sig_f.field_arr[:, 0, 0] idata = argsort(xdata) p.plot(xdata[idata], ydata[idata], 'o-') xdata = sig_f.vtk_X[:, 0] ydata = sig_f.field_arr[:, 0, 0] + sig_m.field_arr[:, 0, 0] p.plot(xdata[idata], ydata[idata], 'ro-') p.set_ylim(ymin=0) # , ymax = 1.2 * ymax ) p.set_xlabel('bar axis [mm]') p.set_ylabel('stress [MPa]') def plot_shear_flow(self, p): shear_flow = self.shear_flow_field.subfields[1] xdata = shear_flow.vtk_X[:, 0] ydata = shear_flow.field_arr[:, 0] / self.P_f idata = argsort(xdata) ymax = max(ydata) p.plot(xdata[idata], ydata[idata], 'o-') p.set_xlabel('bar axis [mm]') p.set_ylabel('shear flow [N/m]') def plot_slip(self, p): slip = self.slip_field.subfields[1] xdata = slip.vtk_X[:, 0] ydata = slip.field_arr[:, 0] idata = argsort(xdata) ymax = max(ydata) p.plot(xdata[idata], ydata[idata], 'ro-') p.set_xlabel('bar axis [mm]') p.set_ylabel('slip [N/m]') def plot_tracers(self, p=p): p.subplot(221) self.plot_sig_eps(p) p.subplot(223) self.plot_eps(p) p.subplot(224) self.plot_sig(p) #--------------------------------------------------------------- # PLOT OBJECT #------------------------------------------------------------------- figure_ld = Instance(Figure) def _figure_ld_default(self): figure = Figure(facecolor='white') figure.add_axes([0.12, 0.13, 0.85, 0.74]) return figure #--------------------------------------------------------------- # PLOT OBJECT #------------------------------------------------------------------- figure_eps = Instance(Figure) def _figure_eps_default(self): figure = Figure(facecolor='white') figure.add_axes([0.12, 0.13, 0.85, 0.74]) return figure #--------------------------------------------------------------- # PLOT OBJECT #------------------------------------------------------------------- figure_shear_flow = Instance(Figure) def _figure_shear_flow_default(self): figure = Figure(facecolor='white') figure.add_axes([0.12, 0.13, 0.85, 0.74]) return figure #--------------------------------------------------------------- # PLOT OBJECT #------------------------------------------------------------------- figure_sig = Instance(Figure) def _figure_sig_default(self): figure = Figure(facecolor='white') figure.add_axes([0.12, 0.13, 0.85, 0.74]) return figure #--------------------------------------------------------------- # PLOT OBJECT #------------------------------------------------------------------- figure_shear_flow = Instance(Figure) def _figure_shear_flow_default(self): figure = Figure(facecolor='white') figure.add_axes([0.12, 0.13, 0.85, 0.74]) return figure def plot(self): self.figure_ld.clear() ax = self.figure_ld.gca() self.plot_sig_eps(ax) self.figure_eps.clear() ax = self.figure_eps.gca() self.plot_eps(ax) ax2 = ax.twinx() self.plot_omega(ax2) self.figure_sig.clear() ax = self.figure_sig.gca() self.plot_sig(ax) ax2 = ax.twinx() self.plot_omega(ax2) self.figure_shear_flow.clear() ax = self.figure_shear_flow.gca() self.plot_shear_flow(ax) ax2 = ax.twinx() self.plot_slip(ax2) self.data_changed = True def get_sim_outputs(self): ''' Specifies the results and their order returned by the model evaluation. ''' return [ SimOut(name='right end displacement', unit='m'), SimOut(name='peak load', uni='MPa') ] data_changed = Event toolbar = ToolBar(Action(name="Run", tooltip='Start computation', image=ImageResource('kt-start'), action="start_study"), Action(name="Pause", tooltip='Pause computation', image=ImageResource('kt-pause'), action="pause_study"), Action(name="Stop", tooltip='Stop computation', image=ImageResource('kt-stop'), action="stop_study"), image_size=(32, 32), show_tool_names=False, show_divider=True, name='view_toolbar'), traits_view = View(HSplit( VSplit( Item('run', show_label=False), VGroup( Item('shape'), Item('n_steps'), Item('length'), label='parameters', id='crackloc.viewmodel.factor.geometry', dock='tab', scrollable=True, ), VGroup(Item('E_m'), Item('f_m_t'), Item('avg_radius'), Item('h_m'), Item('b_m'), Item('A_m', style='readonly'), Item('mats_m', show_label=False), label='Matrix', dock='tab', id='crackloc.viewmodel.factor.matrix', scrollable=True), VGroup(Item('E_f'), Item('A_f'), Item('mats_f', show_label=False), label='Fiber', dock='tab', id='crackloc.viewmodel.factor.fiber', scrollable=True), VGroup(Group( Item('tau_max'), Item('s_crit'), Item('P_f', style='readonly', show_label=True), Item('K_b', style='readonly', show_label=True), Item('T_max', style='readonly', show_label=True), ), Item('mats_b', show_label=False), label='Bond', dock='tab', id='crackloc.viewmodel.factor.bond', scrollable=True), VGroup(Item('rho', style='readonly', show_label=True), label='Composite', dock='tab', id='crackloc.viewmodel.factor.jcomposite', scrollable=True), id='crackloc.viewmodel.left', label='studied factors', layout='tabbed', dock='tab', ), VSplit( VGroup( Item('figure_ld', editor=MPLFigureEditor(), resizable=True, show_label=False), label='stress-strain', id='crackloc.viewmode.figure_ld_window', dock='tab', ), VGroup( Item('figure_eps', editor=MPLFigureEditor(), resizable=True, show_label=False), label='strains profile', id='crackloc.viewmode.figure_eps_window', dock='tab', ), VGroup( Item('figure_sig', editor=MPLFigureEditor(), resizable=True, show_label=False), label='stress profile', id='crackloc.viewmode.figure_sig_window', dock='tab', ), VGroup( Item('figure_shear_flow', editor=MPLFigureEditor(), resizable=True, show_label=False), label='bond shear and slip profiles', id='crackloc.viewmode.figure_shear_flow_window', dock='tab', ), id='crackloc.viewmodel.right', ), id='crackloc.viewmodel.splitter', ), title='SimVisage Component: Crack localization', id='crackloc.viewmodel', dock='tab', resizable=True, height=0.8, width=0.8, buttons=[OKButton])
class CBView(ModelView): def __init__(self, **kw): super(CBView, self).__init__(**kw) self.on_trait_change(self.refresh, 'model.+params') self.refresh() model = Instance(Model) figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') return figure figure2 = Instance(Figure) def _figure2_default(self): figure = Figure(facecolor='white') return figure data_changed = Event def plot(self, fig, fig2): figure = fig figure.clear() axes = figure.gca() # plot PDF axes.plot(self.model.w, self.model.model_rand, lw=2.0, color='blue', \ label='model') axes.plot(self.model.w, self.model.interpolate_experiment(self.model.w), lw=1.0, color='black', \ label='experiment') axes.legend(loc='best') # figure2 = fig2 # figure2.clear() # axes = figure2.gca() # # plot PDF # axes.plot(self.model.w2, self.model.model_extrapolate, lw=2.0, color='red', \ # label='model') # axes.legend() def refresh(self): self.plot(self.figure, self.figure2) self.data_changed = True traits_view = View(HSplit(VGroup( Group( Item('model.tau_scale'), Item('model.tau_shape'), Item('model.tau_loc'), Item('model.m'), Item('model.sV0'), Item('model.Ef'), Item('model.w_min'), Item('model.w_max'), Item('model.w_pts'), Item('model.n_int'), Item('model.w2_min'), Item('model.w2_max'), Item('model.w2_pts'), Item('model.sigmamu'), ), id='pdistrib.distr_type.pltctrls', label='Distribution parameters', scrollable=True, ), Tabbed( Group( Item('figure', editor=MPLFigureEditor(), show_label=False, resizable=True), scrollable=True, label='Plot', ), label='Plot', id='pdistrib.figure.params', dock='tab', ), Tabbed( Group( Item('figure2', editor=MPLFigureEditor(), show_label=False, resizable=True), scrollable=True, label='Plot', ), label='Plot', id='pdistrib.figure2', dock='tab', ), dock='tab', id='pdistrib.figure.view'), id='pdistrib.view', dock='tab', title='Statistical distribution', buttons=[OKButton, CancelButton], scrollable=True, resizable=True, width=600, height=400)
class PDistrib(HasTraits): implements = IPDistrib def __init__(self, **kw): super(PDistrib, self).__init__(**kw) self.on_trait_change(self.refresh, 'distr_type.changed,quantile,n_segments') self.refresh() # puts all chosen continuous distributions distributions defined # in the scipy.stats.distributions module as a list of strings # into the Enum trait # distr_choice = Enum(distr_enum) distr_choice = Enum('sin2x', 'weibull_min', 'sin_distr', 'uniform', 'norm', 'piecewise_uniform', 'gamma') distr_dict = { 'sin2x': sin2x, 'uniform': uniform, 'norm': norm, 'weibull_min': weibull_min, 'sin_distr': sin_distr, 'piecewise_uniform': piecewise_uniform, 'gamma': gamma } # instantiating the continuous distributions distr_type = Property(Instance(Distribution), depends_on='distr_choice') @cached_property def _get_distr_type(self): return Distribution(self.distr_dict[self.distr_choice]) # change monitor - accumulate the changes in a single event trait changed = Event @on_trait_change('distr_choice, distr_type.changed, quantile, n_segments') def _set_changed(self): self.changed = True #------------------------------------------------------------------------ # Methods setting the statistical modments #------------------------------------------------------------------------ mean = Property def _get_mean(self): return self.distr_type.mean def _set_mean(self, value): self.distr_type.mean = value variance = Property def _get_variance(self): return self.distr_type.mean def _set_variance(self, value): self.distr_type.mean = value #------------------------------------------------------------------------ # Methods preparing visualization #------------------------------------------------------------------------ quantile = Float(1e-14, auto_set=False, enter_set=True) range = Property(Tuple(Float), depends_on=\ 'distr_type.changed, quantile') @cached_property def _get_range(self): return (self.distr_type.distr.ppf(self.quantile), self.distr_type.distr.ppf(1 - self.quantile)) n_segments = Int(500, auto_set=False, enter_set=True) dx = Property(Float, depends_on=\ 'distr_type.changed, quantile, n_segments') @cached_property def _get_dx(self): range_length = self.range[1] - self.range[0] return range_length / self.n_segments #------------------------------------------------------------------------- # Discretization of the distribution domain #------------------------------------------------------------------------- x_array = Property(Array('float_'), depends_on=\ 'distr_type.changed,'\ 'quantile, n_segments') @cached_property def _get_x_array(self): '''Get the intrinsic discretization of the distribution respecting its bounds. ''' return linspace(self.range[0], self.range[1], self.n_segments + 1) #=========================================================================== # Access function to the scipy distribution #=========================================================================== def pdf(self, x): return self.distr_type.distr.pdf(x) def cdf(self, x): return self.distr_type.distr.cdf(x) def rvs(self, n): return self.distr_type.distr.rvs(n) def ppf(self, e): return self.distr_type.distr.ppf(e) #=========================================================================== # PDF - permanent array #=========================================================================== pdf_array = Property(Array('float_'), depends_on=\ 'distr_type.changed,'\ 'quantile, n_segments') @cached_property def _get_pdf_array(self): '''Get pdf values in intrinsic positions''' return self.distr_type.distr.pdf(self.x_array) def get_pdf_array(self, x_array): '''Get pdf values in externally specified positions''' return self.distr_type.distr.pdf(x_array) #=========================================================================== # CDF permanent array #=========================================================================== cdf_array = Property(Array('float_'), depends_on=\ 'distr_type.changed,'\ 'quantile, n_segments') @cached_property def _get_cdf_array(self): '''Get cdf values in intrinsic positions''' return self.distr_type.distr.cdf(self.x_array) def get_cdf_array(self, x_array): '''Get cdf values in externally specified positions''' return self.distr_type.distr.cdf(x_array) #------------------------------------------------------------------------- # Randomization #------------------------------------------------------------------------- def get_rvs_array(self, n_samples): return self.distr_type.distr.rvs(n_samples) figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') return figure data_changed = Event def plot(self, fig): figure = fig figure.clear() axes = figure.gca() # plot PDF axes.plot(self.x_array, self.pdf_array, lw=1.0, color='blue', \ label='PDF') axes2 = axes.twinx() # plot CDF on a separate axis (tick labels left) axes2.plot(self.x_array, self.cdf_array, lw=2, color='red', \ label='CDF') # fill the unity area given by integrating PDF along the X-axis axes.fill_between(self.x_array, 0, self.pdf_array, color='lightblue', alpha=0.8, linewidth=2) # plot mean mean = self.distr_type.distr.stats('m') axes.plot([mean, mean], [0.0, self.distr_type.distr.pdf(mean)], lw=1.5, color='black', linestyle='-') # plot stdev stdev = sqrt(self.distr_type.distr.stats('v')) axes.plot([mean - stdev, mean - stdev], [0.0, self.distr_type.distr.pdf(mean - stdev)], lw=1.5, color='black', linestyle='--') axes.plot([mean + stdev, mean + stdev], [0.0, self.distr_type.distr.pdf(mean + stdev)], lw=1.5, color='black', linestyle='--') axes.legend(loc='center left') axes2.legend(loc='center right') axes.ticklabel_format(scilimits=(-3., 4.)) axes2.ticklabel_format(scilimits=(-3., 4.)) # plot limits on X and Y axes axes.set_ylim(0.0, max(self.pdf_array) * 1.15) axes2.set_ylim(0.0, 1.15) range = self.range[1] - self.range[0] axes.set_xlim(self.x_array[0] - 0.05 * range, self.x_array[-1] + 0.05 * range) axes2.set_xlim(self.x_array[0] - 0.05 * range, self.x_array[-1] + 0.05 * range) def refresh(self): self.plot(self.figure) self.data_changed = True icon = Property(Instance(ImageResource), depends_on='distr_type.changed,quantile,n_segments') @cached_property def _get_icon(self): fig = plt.figure(figsize=(4, 4), facecolor='white') self.plot(fig) tf_handle, tf_name = tempfile.mkstemp('.png') fig.savefig(tf_name, dpi=35) return ImageResource(name=tf_name) traits_view = View(HSplit(VGroup( Group( Item('distr_choice', show_label=False), Item('@distr_type', show_label=False), ), id='pdistrib.distr_type.pltctrls', label='Distribution parameters', scrollable=True, ), Tabbed( Group( Item('figure', editor=MPLFigureEditor(), show_label=False, resizable=True), scrollable=True, label='Plot', ), Group(Item('quantile', label='quantile'), Item('n_segments', label='plot points'), label='Plot parameters'), label='Plot', id='pdistrib.figure.params', dock='tab', ), dock='tab', id='pdistrib.figure.view'), id='pdistrib.view', dock='tab', title='Statistical distribution', buttons=['Ok', 'Cancel'], scrollable=True, resizable=True, width=600, height=400)
class ECBLMNDiagram(HasTraits): # calibrator supplying the effective material law calib = Instance(ECBLCalib) def _calib_default(self): return ECBLCalib(notify_change=self.set_modified) def _calib_changed(self): self.calib.notify_change = self.set_modified modified = Event def set_modified(self): print 'MN:set_modifeid' self.modified = True # cross section cs = DelegatesTo('calib') calibrated_ecb_law = Property(depends_on='modified') @cached_property def _get_calibrated_ecb_law(self): print 'NEW CALIBRATION' return self.calib.calibrated_ecb_law eps_cu = Property() def _get_eps_cu(self): return -self.cs.cc_law.eps_c_u eps_tu = Property() def _get_eps_tu(self): return self.calibrated_ecb_law.eps_tex_u n_eps = Int(5, auto_set=False, enter_set=True) eps_range = Property(depends_on='n_eps') @cached_property def _get_eps_range(self): eps_c_space = np.linspace(self.eps_cu, 0, self.n_eps) eps_t_space = np.linspace(0, self.eps_tu, self.n_eps) eps_ccu = 0.8 * self.eps_cu #eps_cc = self.eps_cu * np.ones_like(eps_c_space) eps_cc = np.linspace(eps_ccu, self.eps_cu, self.n_eps) eps_ct = self.eps_cu * np.ones_like(eps_t_space) eps_tc = self.eps_tu * np.ones_like(eps_c_space) eps_tt = self.eps_tu * np.ones_like(eps_t_space) eps1 = np.vstack([eps_c_space, eps_cc]) eps2 = np.vstack([eps_t_space, eps_ct]) eps3 = np.vstack([eps_tc, eps_c_space]) eps4 = np.vstack([eps_tt, eps_t_space]) return np.hstack([eps1, eps2, eps3, eps4]) n_eps_range = Property(depends_on='n_eps') @cached_property def _get_n_eps_range(self): return self.eps_range.shape[1] #=========================================================================== # MN Diagram #=========================================================================== def _get_MN_fn(self, eps_lo, eps_up): self.cs.set(eps_lo=eps_lo, eps_up=eps_up) return (self.cs.M, self.cs.N) MN_vct = Property(depends_on='modified') def _get_MN_vct(self): return np.vectorize(self._get_MN_fn) MN_arr = Property(depends_on='modified') @cached_property def _get_MN_arr(self): return self.MN_vct(self.eps_range[0, :], self.eps_range[1, :]) #=========================================================================== # f_eps Diagram #=========================================================================== current_eps_idx = Int(0) # , auto_set = False, enter_set = True) def _current_eps_idx_changed(self): self._clear_fired() self._replot_fired() current_eps = Property(depends_on='current_eps_idx') @cached_property def _get_current_eps(self): return self.eps_range[(0, 1), self.current_eps_idx] current_MN = Property(depends_on='current_eps_idx') @cached_property def _get_current_MN(self): return self._get_MN_fn(*self.current_eps) #=========================================================================== # Plotting #=========================================================================== 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 clear = Button def _clear_fired(self): self.figure.clear() self.data_changed = True replot = Button def _replot_fired(self): ax = self.figure.add_subplot(2, 2, 1) ax.plot(-self.eps_range, [0, 0.06], color='black') ax.plot(-self.current_eps, [0, 0.06], lw=3, color='red') ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.spines['left'].set_smart_bounds(True) ax.spines['bottom'].set_smart_bounds(True) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax = self.figure.add_subplot(2, 2, 2) ax.plot(self.MN_arr[0], -self.MN_arr[1], lw=2, color='blue') ax.plot(self.current_MN[0], -self.current_MN[1], 'g.', markersize=20.0, color='red') ax.spines['left'].set_position('zero') ax.spines['bottom'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.spines['left'].set_smart_bounds(True) ax.spines['bottom'].set_smart_bounds(True) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.grid(b=None, which='major') self.cs.set(eps_lo=self.current_eps[0], eps_up=self.current_eps[1]) ax = self.figure.add_subplot(2, 2, 3) self.cs.plot_eps(ax) ax = self.figure.add_subplot(2, 2, 4) self.cs.plot_sig(ax) self.data_changed = True view = View(HSplit( Group( HGroup( Group(Item('n_eps', springy=True), label='Discretization', springy=True), springy=True, ), HGroup( Group(VGroup( Item( 'cs', label='Cross section', show_label=False, springy=True, editor=InstanceEditor(kind='live'), ), Item( 'calib', label='Calibration', show_label=False, springy=True, editor=InstanceEditor(kind='live'), ), springy=True, ), label='Cross sectoin', springy=True), springy=True, ), scrollable=True, ), Group( HGroup( Item('replot', show_label=False), Item('clear', show_label=False), ), Item( 'current_eps_idx', editor=RangeEditor( low=0, high_name='n_eps_range', format='(%s)', mode='slider', auto_set=False, enter_set=False, ), show_label=False, ), Item('figure', editor=MPLFigureEditor(), resizable=True, show_label=False), id='simexdb.plot_sheet', label='plot sheet', dock='tab', ), ), width=1.0, height=0.8, resizable=True, buttons=['OK', 'Cancel'])
class YMBView2D(HasTraits): data = Instance(YMBData) zero = Constant(0) slider_max = Property() def _get_slider_max(self): return self.data.n_cuts - 1 var_enum = Trait('radius', var_dict, modified=True) cut_slider = Range('zero', 'slider_max', mode='slider', auto_set=False, enter_set=True, modified=True) circle_diameter = Float(20, enter_set=True, auto_set=False, modified=True) underlay = Bool(False, modified=True) variable = Property(Array, depends_on='var_enum') @cached_property def _get_variable(self): return getattr(self.data, self.var_enum_) figure = Instance(Figure) def _figure_default(self): figure = Figure() figure.add_axes([0.1, 0.1, 0.8, 0.8]) return figure data_changed = Event(True) @on_trait_change('+modified, data.input_changed') def _redraw(self): # TODO: set correct ranges, fix axis range (axes.xlim) self.figure.clear() self.figure.add_axes([0.1, 0.1, 0.8, 0.8]) figure = self.figure axes = figure.axes[0] axes.clear() y_arr, z_arr = self.data.cut_data[1:3] y_raw_arr, z_raw_arr = self.data.cut_raw_data[0:2] offset = hstack([0, self.data.cut_raw_data[5]]) scalar_arr = self.variable mask = y_arr[:, self.cut_slider] > -1 axes.scatter( y_raw_arr[offset[self.cut_slider]:offset[self.cut_slider + 1]], z_raw_arr[offset[self.cut_slider]:offset[self.cut_slider + 1]], s=self.circle_diameter, color='k', marker='x', label='identified filament in cut') scat = axes.scatter(y_arr[:, self.cut_slider][mask], z_arr[:, self.cut_slider][mask], s=self.circle_diameter, c=scalar_arr[:, self.cut_slider][mask], cmap=my_cmap_lin, label='connected filaments') axes.set_xlabel('$y\, [\mathrm{mm}]$', fontsize=16) axes.set_ylabel('$z\, [\mathrm{mm}]$', fontsize=16) axes.set_xlim([0, ceil(max(y_arr))]) axes.set_ylim([0, ceil(max(z_arr))]) axes.legend() figure.colorbar(scat) if self.underlay == True: axes.text(axes.get_xlim()[0], axes.get_ylim()[0], 'That\'s all at this moment :-)', color='red', fontsize=20) self.data_changed = True traits_view = View( Group( Item('var_enum'), Item('cut_slider', springy=True), Item('circle_diameter', springy=True), Item('underlay', springy=True), ), Item('figure', style='custom', editor=MPLFigureEditor(), show_label=False), resizable=True, )
class YMBAutoCorrelView(HasTraits): correl_data = Instance(YMBAutoCorrel) axes_adjust = List([0.1, 0.1, 0.8, 0.8]) data = Property def _get_data(self): return self.correl_data.data zero = Constant(0) slider_max = Property() def _get_slider_max(self): return self.data.n_cuts - 1 cut_slider = Range('zero', 'slider_max', mode='slider', auto_set=False, enter_set=True, modified=True) vcut_slider = Range('zero', 'slider_max', mode='slider', auto_set=False, enter_set=True, modified=True) cut_slider_on = Bool(False, modified=True) color = Str('blue') figure = Instance(Figure) def _figure_default(self): figure = Figure() figure.add_axes(self.axes_adjust) return figure data_changed = Event(True) @on_trait_change('correl_data.input_change, +modified') def _redraw(self): # TODO: set correct ranges, fix axis range (axes.xlim) print 'redrawing xxxx' figure = self.figure figure.clear() var_data = self.correl_data.corr_arr id = self.cut_slider if self.cut_slider_on == True: i = self.cut_slider j = self.vcut_slider plot_data = getattr(self.data, self.correl_data.var_enum_) # plot_data = vstack( [plot_data[:, i], plot_data[:, j]] ).T # plot only values > -1 # plot_data = plot_data[prod( plot_data >= 0, axis = 1, dtype = bool )] plot_data_x = plot_data[:, i] plot_data_y = plot_data[:, j] plot_data_corr = min(corrcoef(plot_data_x, plot_data_y)) plot_data_corr_spear = spearmanr(plot_data_x, plot_data_y)[0] left, width = 0.1, 0.65 bottom, height = 0.1, 0.65 bottom_h = left_h = left + width + 0.02 rect_scatter = [left, bottom, width, height] rect_histx = [left, bottom_h, width, 0.2] rect_histy = [left_h, bottom, 0.2, height] axScatter = figure.add_axes(rect_scatter) axHistx = figure.add_axes(rect_histx) axHisty = figure.add_axes(rect_histy) axScatter.clear() axHistx.clear() axHisty.clear() from matplotlib.ticker import NullFormatter axHistx.xaxis.set_major_formatter(NullFormatter()) axHisty.yaxis.set_major_formatter(NullFormatter()) axScatter.scatter(plot_data_x, plot_data_y) # binwidth = 0.25 # xymax = max( [max( abs( self.data.cf[:, j] ) ), max( abs( self.data.cf[:, i] ) )] ) # lim = ( int( xymax / binwidth ) + 1 ) * binwidth # axScatter.set_xlim( ( -lim, lim ) ) # axScatter.set_ylim( ( -lim, lim ) ) # bins = arange( -lim, lim + binwidth, binwidth ) axHistx.hist(plot_data_x.compressed(), bins=40) axHisty.hist(plot_data_y.compressed(), bins=40, orientation='horizontal') axHistx.set_xlim(axScatter.get_xlim()) axHisty.set_ylim(axScatter.get_ylim()) axScatter.set_xlabel('$\mathrm{cut\, %i}$' % self.cut_slider, fontsize=16) axScatter.set_ylabel('$\mathrm{cut\, %i}$' % self.vcut_slider, fontsize=16) axScatter.text(axScatter.get_xlim()[0], axScatter.get_ylim()[0], 'actual set correlation %.3f (Pearson), %.3f (Spearman)' % (plot_data_corr, plot_data_corr_spear), color='r') if self.cut_slider_on == False: figure.add_axes(self.axes_adjust) axes = figure.axes[0] axes.clear() x_coor = self.data.x_coord axes.grid() for i in range(0, var_data.shape[1]): axes.plot(x_coor[i:] - x_coor[i], var_data[i, (i):], '-x', color=self.color) # approximate by the polynomial (of the i-th order) # axes.plot( x_coor, self.correl_data.peval( x_coor, self.correl_data.fit_correl ), 'b', linewidth = 3 ) setp(axes.get_xticklabels(), position=(0, -.025)) axes.set_xlabel('$x \, [\mathrm{mm}]$', fontsize=15) axes.set_ylabel('$\mathrm{correlation}$', fontsize=15) axes.set_ylim(-1, 1) self.data_changed = True traits_view = View(Group(Item('correl_data', show_label=False, style='custom'), HGroup( Item('cut_slider_on', label='Scatter'), Item('cut_slider', show_label=False, springy=True, enabled_when='cut_slider_on == True'), Item('vcut_slider', show_label=False, springy=True, enabled_when='cut_slider_on == True'), ), Group(Item('figure', style='custom', editor=MPLFigureEditor(), show_label=False) , id='figure.view'), ), resizable=True, )
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 ImageProcessing(HasTraits): def __init__(self, **kw): super(ImageProcessing, self).__init__(**kw) self.on_trait_change(self.refresh, '+params') self.refresh() image_path = Str def rgb2gray(self, rgb): return np.dot(rgb[..., :3], [0.299, 0.587, 0.144]) filter = Bool(False, params=True) block_size = Range(1, 100, params=True) offset = Range(1, 20, params=True) denoise = Bool(False, params=True) denoise_spatial = Range(1, 100, params=True) processed_image = Property def _get_processed_image(self): # read image image = mpimg.imread(self.image_path) mask = image[:, :, 1] > 150. image[mask] = 255. #plt.imshow(image) #plt.show() # convert to grayscale image = self.rgb2gray(image) # crop image image = image[100:1000, 200:1100] mask = mask[100:1000, 200:1100] image = image - np.min(image) image[mask] *= 255. / np.max(image[mask]) if self.filter == True: image = denoise_bilateral(image, sigma_spatial=self.denoise_spatial) if self.denoise == True: image = threshold_adaptive(image, self.block_size, offset=self.offset) return image, mask edge_detection_method = Enum('canny', 'sobel', 'roberts', params=True) canny_sigma = Range(2.832, 5, params=True) canny_low = Range(5.92, 100, params=True) canny_high = Range(0.1, 100, params=True) edges = Property def _get_edges(self): img_edg, mask = self.processed_image if self.edge_detection_method == 'canny': img_edg = canny(img_edg, sigma=self.canny_sigma, low_threshold=self.canny_low, high_threshold=self.canny_high) elif self.edge_detection_method == 'roberts': img_edg = roberts(img_edg) elif self.edge_detection_method == 'sobel': img_edg = sobel(img_edg) img_edg = img_edg > 0.0 return img_edg radii = Int(80, params=True) radius_low = Int(40, params=True) radius_high = Int(120, params=True) step = Int(2, params=True) hough_circles = Property def _get_hough_circles(self): hough_radii = np.arange(self.radius_low, self.radius_high, self.step)[::-1] hough_res = hough_circle(self.edges, hough_radii) centers = [] accums = [] radii = [] # For each radius, extract num_peaks circles num_peaks = 3 for radius, h in zip(hough_radii, hough_res): peaks = peak_local_max(h, num_peaks=num_peaks) centers.extend(peaks) print 'circle centers = ', peaks accums.extend(h[peaks[:, 0], peaks[:, 1]]) radii.extend([radius] * num_peaks) im = mpimg.imread(self.image_path) # crop image im = im[100:1000, 200:1100] for idx in np.arange(len(centers)): center_x, center_y = centers[idx] radius = radii[idx] cx, cy = circle_perimeter(center_y, center_x, radius) mask = (cx < im.shape[0]) * (cy < im.shape[1]) im[cy[mask], cx[mask]] = (220., 20., 20.) return im eval_edges = Button def _eval_edges_fired(self): edges = self.figure_edges edges.clear() axes_edges = edges.gca() axes_edges.imshow(self.edges, plt.gray()) self.data_changed = True eval_circles = Button def _eval_circles_fired(self): circles = self.figure_circles circles.clear() axes_circles = circles.gca() axes_circles.imshow(self.hough_circles, plt.gray()) self.data_changed = True figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') return figure figure_edges = Instance(Figure) def _figure_edges_default(self): figure = Figure(facecolor='white') return figure figure_circles = Instance(Figure) def _figure_circles_default(self): figure = Figure(facecolor='white') return figure data_changed = Event def plot(self, fig, fig2): figure = fig figure.clear() axes = figure.gca() img, mask = self.processed_image axes.imshow(img, plt.gray()) def refresh(self): self.plot(self.figure, self.figure_edges) self.data_changed = True traits_view = View(HGroup( Group(Item('filter', label='filter'), Item('block_size'), Item('offset'), Item('denoise', label='denoise'), Item('denoise_spatial'), label='Filters'), Group( Item('figure', editor=MPLFigureEditor(), show_label=False, resizable=True), scrollable=True, label='Plot', ), ), Tabbed( VGroup(Item('edge_detection_method'), Item('canny_sigma'), Item('canny_low'), Item('canny_high'), Item('eval_edges', label='Evaluate'), Item('figure_edges', editor=MPLFigureEditor(), show_label=False, resizable=True), scrollable=True, label='Plot_edges'), ), Tabbed( VGroup(Item('radii'), Item('radius_low'), Item('radius_high'), Item('step'), Item('eval_circles'), Item('figure_circles', editor=MPLFigureEditor(), show_label=False, resizable=True), scrollable=True, label='Plot_circles'), ), id='imview', dock='tab', title='Image processing', scrollable=True, resizable=True, width=600, height=400)
class ECBLCalibModelView(ModelView): '''Model in a viewable window. ''' model = Instance(ECBLCalib) def _model_default(self): return ECBLCalib() cs_state = Property(Instance(ECBCrossSection), depends_on='model') @cached_property def _get_cs_state(self): return self.model.cs 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 YMBHist(HasTraits): slider = Instance(YMBSlider) figure = Instance(Figure) bins = Int(20, auto_set=False, enter_set=True, modified=True) xlimit_on = Bool(False, modified=True) ylimit_on = Bool(False, modified=True) xlimit = Float(100, auto_set=False, enter_set=True, modified=True) ylimit = Float(100, auto_set=False, enter_set=True, modified=True) multi_hist_on = Bool(False, modified=True) stats_on = Bool(False, modified=True) normed_on = Bool(False, modified=True) normed_hist = Property(depends_on='+modified, slider.input_change') @cached_property def _get_normed_hist(self): data = self.slider.stat_data h, b = histogram(data, bins=self.bins, normed=True) return h, b range = Property def _get_range(self): h, b = self.normed_hist return (min(b), max(b)) bin_width = Property def _get_bin_width(self): return (self.range[1] - self.range[0]) / self.bins def _figure_default(self): figure = Figure() figure.add_axes(self.axes_adjust) return figure edge_color = Str(None) face_color = Str(None) axes_adjust = List([0.1, 0.1, 0.8, 0.8]) data_changed = Event(True) @on_trait_change('+modified, slider.input_change') def _redraw(self): figure = self.figure axes = figure.axes[0] axes.clear() if self.multi_hist_on == True: histtype = 'step' lw = 3 plot_data = getattr(self.slider.data, self.slider.var_enum_) for i in range(0, plot_data.shape[1]): axes.hist(plot_data[:, i].compressed(), bins=self.bins, histtype=histtype, color='gray') if self.multi_hist_on == False: histtype = 'bar' lw = 1 var_data = self.slider.stat_data axes.hist(var_data, bins=self.bins, histtype=histtype, linewidth=lw, \ normed=self.normed_on, edgecolor=self.edge_color, facecolor=self.face_color) if self.stats_on == True: xint = axes.xaxis.get_view_interval() yint = axes.yaxis.get_view_interval() axes.text( xint[0], yint[0], 'mean = %e, std = %e' % (mean(var_data), sqrt(var(var_data)))) # redefine xticks labels # inter = axes.xaxis.get_view_interval() # axes.set_xticks( linspace( inter[0], inter[1], 5 ) ) axes.set_xlabel(self.slider.var_enum) axes.set_ylabel('frequency') # , fontsize = 16 setp(axes.get_xticklabels(), position=(0, -.025)) if self.xlimit_on == True: axes.set_xlim(0, self.xlimit) if self.ylimit_on == True: axes.set_ylim(0, self.ylimit) self.data_changed = True view = View( Group( Item('figure', style='custom', editor=MPLFigureEditor(), show_label=False, id='figure.view'), HGroup( Item('bins'), Item('ylimit_on', label='Y limit'), Item('ylimit', enabled_when='ylimit_on == True', show_label=False), Item('stats_on', label='stats'), Item('normed_on', label='norm'), Item('multi_hist_on', label='multi')), label='histogram', dock='horizontal', id='yarn_hist.figure', ), Group( Item('slider', style='custom', show_label=False), label='yarn data', dock='horizontal', id='yarn_hist.config', ), id='yarn_structure_view', resizable=True, scrollable=True, # width = 0.8, # height = 0.4 )
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', )
class YarnPullOut(HasTraits): '''Idealization of the double sided pullout using the SPIRRID statistical integration tool. ''' rf = Instance(DoublePulloutSym) def _rf_default(self): return DoublePulloutSym(tau_fr=2.6, l=0.0, d=25.5e-3, E_mod=72.0e3, theta=0.0, xi=0.0179, phi=1., L=30.0, free_fiber_end=True) # return DoublePulloutSym( tau_fr = 2.5, l = 0.01, d = 25.5e-3, E_mod = 70.0e3, # theta = 0.01, xi = 0.0179, phi = 1., n_f = 1723 ) figure = Instance(Figure) def _figure_default(self): figure = Figure(facecolor='white') figure.add_axes([0.08, 0.13, 0.85, 0.74]) return figure pdf_theta_on = Bool(True) pdf_l_on = Bool(True) pdf_phi_on = Bool(True) pdf_xi_on = Bool(True) pdf_xi = Instance(IPDistrib) def _pdf_xi_default(self): pd = PDistrib(distr_choice='weibull_min', n_segments=30) pd.distr_type.set(shape=4.54, scale=0.017) return pd n_f = Float(1, auto_set=False, enter_set=True, desc='Number of filaments in the yarn') pdf_theta = Instance(IPDistrib) pdf_l = Instance(IPDistrib) pdf_phi = Instance(IPDistrib) run = Button def _run_fired(self): self._redraw() clear = Button def _clear_fired(self): axes = self.figure.axes[0] axes.clear() self.data_changed = True w_max = Float(1.0, enter_set=True, auto_set=False) n_w_pts = Int(100, enter_set=True, auto_set=False) n_G_ipts = Int(30, enter_set=True, auto_set=False) e_arr = Property(Array, depends_on='w_max, n_w_pts') def _get_e_arr(self): return linspace(0.00, self.w_max, self.n_w_pts) lab = Str(' ', enter_set=True, auto_set=False) data_changed = Event(True) def _redraw(self): s = SPIRRID( q=self.rf, sampling_type='LHS', e_arr=self.e_arr, n_int=self.n_G_ipts, theta_vars=dict(tau_fr=2.6, l=0.0, d=25.5e-3, E_mod=72.0e3, theta=0.0, xi=0.0179, phi=1., L=30.0), # codegen_type='weave' ) # construct the random variables if self.pdf_xi_on: s.theta_vars['xi'] = RV( 'weibull_min', shape=4.54, scale=0.017 ) # RV( pd = self.pdf_xi, name = 'xi', n_int = self.n_G_ipts ) print self.pdf_theta.interp_ppf([0.01, 0.02]) print YMB_RV('theta', distr=self.pdf_theta, n_int=self.n_G_ipts).distr.interp_ppf([0.01, 0.02]) if self.pdf_theta_on: s.theta_vars['theta'] = YMB_RV('theta', distr=self.pdf_theta, n_int=self.n_G_ipts) if self.pdf_l_on: s.theta_vars['l'] = YMB_RV('l', distr=self.pdf_l, n_int=self.n_G_ipts) if self.pdf_phi_on: s.theta_vars['phi'] = YMB_RV('phi', distr=self.pdf_phi, n_int=self.n_G_ipts) # print 'checking unity', s.mu_q_arr() mu = s.mu_q_arr axes = self.figure.axes[0] # TODO: axes.plot(self.e_arr, mu * self.n_f, linewidth=2, label=self.lab) axes.set_xlabel('crack opening w[mm]') axes.set_ylabel('force P[N]') axes.legend(loc='best') self.data_changed = True view = View(HSplit( Group(Item('rf@', show_label=False), label='Response function'), Tabbed( Group( Item('pdf_theta_on', show_label=False), Item('pdf_theta@', show_label=False), label='Slack', ), Group( Item('pdf_l_on', show_label=False), Item('pdf_l@', show_label=False), label='Contact free length', ), Group( Item('pdf_phi_on', show_label=False), Item('pdf_phi@', show_label=False), label='Contact fraction', ), Group( Item('pdf_xi_on', show_label=False), Item('pdf_xi@', show_label=False), label='Strength', ), label='yarn data', scrollable=True, id='ymb.pullout.dist', dock='tab', ), Group( HGroup(Item('run', show_label=False, springy=True), Item('clear', show_label=False, springy=True)), HGroup( Item('w_max', show_label=True, springy=True, tooltip='maximum crack-opening displacement'), Item('n_w_pts', show_label=True, springy=True, tooltip='number of points for crack-opening'), Item('n_G_ipts', show_label=True, springy=True, tooltip= 'number of integration points for the random variables'), Item('lab', show_label=True, springy=True, tooltip='label of pull-out curve'), ), Item('figure', style='custom', editor=MPLFigureEditor(), show_label=False), label='Pull-out response', id='ymb.pullout.figure', dock='tab', ), id='ymb.pullout.split', dock='tab', ), id='ymb.pullout', resizable=True, scrollable=True, dock='tab', width=0.8, height=0.4)