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 STree(HasTraits): title = Str company = Instance(SPIRRIDUI) # The main view view = View( Group( Item( name = 'company', id = 'company', editor = tree_editor, resizable = True, show_label = False ), orientation = 'vertical', show_labels = True, show_left = True, ), title = 'SPIRRID', id = \ 'tree_editor_spirrid', dock = 'horizontal', drop_class = HasTraits, buttons = [ 'Undo', 'OK', 'Cancel' ], resizable = True, width = .3, height = .3 )
def default_traits_view(self): '''checks the number of shape parameters of the distribution and adds them to the view instance''' label = str(self.distribution.name) if self.distribution.shapes == None: params = Item() if self.mean == infty: moments = Item(label='No finite moments defined') else: moments = Item('mean', label='mean'), \ Item('variance', label='variance'), \ Item('stdev', label='st. deviation', style='readonly') elif len(self.distribution.shapes) == 1: params = Item('shape', label='shape') if self.mean == infty: moments = Item(label='No finite moments defined') else: moments = Item('mean', label='mean'), \ Item('variance', label='variance'), \ Item('stdev', label='st. deviation', style='readonly'), \ Item('skewness', label='skewness'), \ Item('kurtosis', label='kurtosis'), else: params = Item() moments = Item() view = View(VGroup(Label(label, emphasized=True), Group(params, Item('loc', label='location'), Item('scale', label='scale'), Item('loc_zero', label='loc = 0.0'), show_border=True, label='parameters', id='pdistrib.distribution.params'), Group( moments, id='pdistrib.distribution.moments', show_border=True, label='moments', ), id='pdistrib.distribution.vgroup'), kind='live', resizable=True, id='pdistrib.distribution.view') return view
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 ECBReinfTexUniform(ECBReinfComponent): '''Cross section characteristics needed for tensile specimens ''' height = DelegatesTo('matrix_cs') '''height of reinforced cross section ''' n_layers = Int(12, auto_set=False, enter_set=True, geo_input=True) '''total number of reinforcement layers [-] ''' n_rovings = Int(23, auto_set=False, enter_set=True, geo_input=True) '''number of rovings in 0-direction of one composite layer of the bending test [-]: ''' A_roving = Float(0.461, auto_set=False, enter_set=True, geo_input=True) '''cross section of one roving [mm**2]''' def convert_eps_tex_u_2_lo(self, eps_tex_u): '''Convert the strain in the lowest reinforcement layer at failure to the strain at the bottom of the cross section''' eps_up = self.state.eps_up return eps_up + (eps_tex_u - eps_up) / self.z_ti_arr[0] * self.height def convert_eps_lo_2_tex_u(self, eps_lo): '''Convert the strain at the bottom of the cross section to the strain in the lowest reinforcement layer at failure''' eps_up = self.state.eps_up return (eps_up + (eps_lo - eps_up) / self.height * self.z_ti_arr[0]) '''Convert the MN to kN ''' #=========================================================================== # material properties #=========================================================================== sig_tex_u = Float(1216., auto_set=False, enter_set=True, tt_input=True) '''Ultimate textile stress measured in the tensile test [MPa] ''' #=========================================================================== # Distribution of reinforcement #=========================================================================== s_tex_z = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''spacing between the layers [m]''' @cached_property def _get_s_tex_z(self): return self.height / (self.n_layers + 1) z_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''property: distance of each reinforcement layer from the top [m]: ''' @cached_property def _get_z_ti_arr(self): return np.array([ self.height - (i + 1) * self.s_tex_z for i in range(self.n_layers) ], dtype=float) zz_ti_arr = Property '''property: distance of reinforcement layers from the bottom ''' def _get_zz_ti_arr(self): return self.height - self.z_ti_arr #=========================================================================== # Discretization conform to the tex layers #=========================================================================== eps_i_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Strain at the level of the i-th reinforcement layer ''' @cached_property def _get_eps_i_arr(self): # ------------------------------------------------------------------------ # geometric params independent from the value for 'eps_t' # ------------------------------------------------------------------------ height = self.height eps_lo = self.state.eps_lo eps_up = self.state.eps_up # strain at the height of each reinforcement layer [-]: # return eps_up + (eps_lo - eps_up) * self.z_ti_arr / height eps_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Tension strain at the level of the i-th layer of the fabrics ''' @cached_property def _get_eps_ti_arr(self): return (np.fabs(self.eps_i_arr) + self.eps_i_arr) / 2.0 eps_ci_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Compression strain at the level of the i-th layer. ''' @cached_property def _get_eps_ci_arr(self): return (-np.fabs(self.eps_i_arr) + self.eps_i_arr) / 2.0 #=========================================================================== # Effective crack bridge law #=========================================================================== ecb_law_type = Trait('fbm', dict(fbm=ECBLFBM, cubic=ECBLCubic, linear=ECBLLinear, bilinear=ECBLBilinear), tt_input=True) '''Selector of the effective crack bridge law type ['fbm', 'cubic', 'linear', 'bilinear']''' ecb_law = Property(Instance(ECBLBase), depends_on='+tt_input') '''Effective crack bridge law corresponding to ecb_law_type''' @cached_property def _get_ecb_law(self): return self.ecb_law_type_(sig_tex_u=self.sig_tex_u, cs=self) show_ecb_law = Button '''Button launching a separate view of the effective crack bridge law. ''' def _show_ecb_law_fired(self): ecb_law_mw = ConstitutiveLawModelView(model=self.ecb_law) ecb_law_mw.edit_traits(kind='live') return tt_modified = Event sig_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Stresses at the i-th fabric layer. ''' @cached_property def _get_sig_ti_arr(self): return self.ecb_law.mfn_vct(self.eps_ti_arr) f_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''force at the height of each reinforcement layer [kN]: ''' @cached_property def _get_f_ti_arr(self): sig_ti_arr = self.sig_ti_arr n_rovings = self.n_rovings A_roving = self.A_roving return sig_ti_arr * n_rovings * A_roving / self.unit_conversion_factor 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 replot = Button def _replot_fired(self): self.figure.clear() ax = self.figure.add_subplot(2, 2, 1) self.plot_eps(ax) ax = self.figure.add_subplot(2, 2, 2) self.plot_sig(ax) ax = self.figure.add_subplot(2, 2, 3) self.cc_law.plot(ax) ax = self.figure.add_subplot(2, 2, 4) self.ecb_law.plot(ax) self.data_changed = True def plot_eps(self, ax): #ax = self.figure.gca() d = self.height # eps ti ax.plot([-self.eps_lo, -self.eps_up], [0, self.height], color='black') ax.hlines(self.zz_ti_arr, [0], -self.eps_ti_arr, lw=4, color='red') # eps cj ec = np.hstack([self.eps_cj_arr] + [0, 0]) zz = np.hstack([self.zz_cj_arr] + [0, self.height]) ax.fill(-ec, zz, color='blue') # reinforcement layers eps_range = np.array([max(0.0, self.eps_lo), min(0.0, self.eps_up)], dtype='float') z_ti_arr = np.ones_like(eps_range)[:, None] * self.z_ti_arr[None, :] ax.plot(-eps_range, z_ti_arr, 'k--', color='black') # neutral axis ax.plot(-eps_range, [d, d], 'k--', color='green', lw=2) 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') def plot_sig(self, ax): d = self.height # f ti ax.hlines(self.zz_ti_arr, [0], -self.f_ti_arr, lw=4, color='red') # f cj f_c = np.hstack([self.f_cj_arr] + [0, 0]) zz = np.hstack([self.zz_cj_arr] + [0, self.height]) ax.fill(-f_c, zz, color='blue') f_range = np.array( [np.max(self.f_ti_arr), np.min(f_c)], dtype='float_') # neutral axis ax.plot(-f_range, [d, d], 'k--', color='green', lw=2) 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') view = View(HSplit( Group( HGroup( Group(Item('height', springy=True), Item('width'), Item('n_layers'), Item('n_rovings'), Item('A_roving'), label='Geometry', springy=True), Group(Item('eps_up', label='Upper strain', springy=True), Item('eps_lo', label='Lower strain'), label='Strain', springy=True), springy=True, ), HGroup( Group(VGroup(Item('cc_law_type', show_label=False, springy=True), Item('cc_law', label='Edit', show_label=False, springy=True), Item('show_cc_law', label='Show', show_label=False, springy=True), springy=True), Item('f_ck', label='Compressive strength'), Item('n_cj', label='Discretization'), label='Concrete', springy=True), Group(VGroup( Item('ecb_law_type', show_label=False, springy=True), Item('ecb_law', label='Edit', show_label=False, springy=True), Item('show_ecb_law', label='Show', show_label=False, springy=True), springy=True, ), label='Reinforcement', springy=True), springy=True, ), Group( Item('s_tex_z', label='vertical spacing', style='readonly'), label='Layout', ), Group(HGroup( Item('M', springy=True, style='readonly'), Item('N', springy=True, style='readonly'), ), label='Stress resultants'), scrollable=True, ), Group( Item('replot', 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, resizable=True, buttons=['OK', 'Cancel'])
class ECBMatrixCrossSection(ECBCrossSectionComponent): '''Cross section characteristics needed for tensile specimens. ''' n_cj = Float(30, auto_set=False, enter_set=True, geo_input=True) '''Number of integration points. ''' f_ck = Float(55.7, auto_set=False, enter_set=True, cc_input=True) '''Ultimate compression stress [MPa] ''' eps_c_u = Float(0.0033, auto_set=False, enter_set=True, cc_input=True) '''Strain at failure of the matrix in compression [-] ''' height = Float(0.4, auto_set=False, enter_set=True, geo_input=True) '''height of the cross section [m] ''' width = Float(0.20, auto_set=False, enter_set=True, geo_input=True) '''width of the cross section [m] ''' x = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Height of the compressive zone ''' @cached_property def _get_x(self): eps_lo = self.state.eps_lo eps_up = self.state.eps_up if eps_up == eps_lo: # @todo: explain return (abs(eps_up) / (abs(eps_up - eps_lo * 1e-9)) * self.height) else: return (abs(eps_up) / (abs(eps_up - eps_lo)) * self.height) z_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Discretizaton of the compressive zone ''' @cached_property def _get_z_ti_arr(self): if self.state.eps_up <= 0: # bending zx = min(self.height, self.x) return np.linspace(0, zx, self.n_cj) elif self.state.eps_lo <= 0: # bending return np.linspace(self.x, self.height, self.n_cj) else: # no compression return np.array([0], dtype='f') eps_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Compressive strain at each integration layer of the compressive zone [-]: ''' @cached_property def _get_eps_ti_arr(self): # for calibration us measured compressive strain # @todo: use mapped traits instead # height = self.height eps_up = self.state.eps_up eps_lo = self.state.eps_lo eps_j_arr = (eps_up + (eps_lo - eps_up) * self.z_ti_arr / height) return (-np.fabs(eps_j_arr) + eps_j_arr) / 2.0 zz_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Distance of reinforcement layers from the bottom ''' @cached_property def _get_zz_ti_arr(self): return self.height - self.z_ti_arr #=========================================================================== # Compressive concrete constitutive law #=========================================================================== cc_law_type = Trait('constant', dict(constant=CCLawBlock, linear=CCLawLinear, quadratic=CCLawQuadratic, quad=CCLawQuad), cc_input=True) '''Selector of the concrete compression law type ['constant', 'linear', 'quadratic', 'quad']''' cc_law = Property(Instance(CCLawBase), depends_on='+cc_input') '''Compressive concrete law corresponding to cc_law_type''' @cached_property def _get_cc_law(self): return self.cc_law_type_(f_ck=self.f_ck, eps_c_u=self.eps_c_u, cs=self) show_cc_law = Button '''Button launching a separate view of the compression law. ''' def _show_cc_law_fired(self): cc_law_mw = ConstitutiveLawModelView(model=self.cc_law) cc_law_mw.edit_traits(kind='live') return cc_modified = Event #=========================================================================== # Calculation of compressive stresses and forces #=========================================================================== sig_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Stresses at the j-th integration point. ''' @cached_property def _get_sig_ti_arr(self): return -self.cc_law.mfn_vct(-self.eps_ti_arr) f_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE) '''Layer force corresponding to the j-th integration point. ''' @cached_property def _get_f_ti_arr(self): return self.width * self.sig_ti_arr * self.unit_conversion_factor def _get_N(self): return np.trapz(self.f_ti_arr, self.z_ti_arr) def _get_M(self): return np.trapz(self.f_ti_arr * self.z_ti_arr, self.z_ti_arr) modified = Event @on_trait_change('+geo_input') def set_modified(self): self.modified = True view = View(HGroup( Group(Item('height', springy=True), Item('width'), Item('n_layers'), Item('n_rovings'), Item('A_roving'), label='Geometry', springy=True), springy=True, ), resizable=True, buttons=['OK', 'Cancel'])
class ExpSH(ExType): '''Experiment: Shell Test ''' # label = Str('slab test') implements(IExType) #-------------------------------------------------------------------- # register a change of the traits with metadata 'input' #-------------------------------------------------------------------- input_change = Event @on_trait_change('+input, ccs.input_change, +ironing_param') def _set_input_change(self): self.input_change = True #-------------------------------------------------------------------------------- # specify inputs: #-------------------------------------------------------------------------------- edge_length = Float(1.25, unit = 'm', input = True, table_field = True, auto_set = False, enter_set = True) thickness = Float(0.03, unit = 'm', input = True, table_field = True, auto_set = False, enter_set = True) # age of the concrete at the time of testing age = Int(28, unit = 'd', input = True, table_field = True, auto_set = False, enter_set = True) loading_rate = Float(0.50, unit = 'mm/min', input = True, table_field = True, auto_set = False, enter_set = True) #-------------------------------------------------------------------------- # composite cross section #-------------------------------------------------------------------------- ccs = Instance(CompositeCrossSection) def _ccs_default(self): '''default settings correspond to setup '7u_MAG-07-03_PZ-0708-1' ''' fabric_layout_key = 'MAG-07-03' # fabric_layout_key = '2D-02-06a' concrete_mixture_key = 'PZ-0708-1' # concrete_mixture_key = 'FIL-10-09' # orientation_fn_key = 'all0' orientation_fn_key = '90_0' n_layers = 10 s_tex_z = 0.030 / (n_layers + 1) ccs = CompositeCrossSection ( fabric_layup_list = [ plain_concrete(s_tex_z * 0.5), FabricLayUp ( n_layers = n_layers, orientation_fn_key = orientation_fn_key, s_tex_z = s_tex_z, fabric_layout_key = fabric_layout_key ), plain_concrete(s_tex_z * 0.5) ], concrete_mixture_key = concrete_mixture_key ) return ccs #-------------------------------------------------------------------------- # Get properties of the composite #-------------------------------------------------------------------------- # E-modulus of the composite at the time of testing E_c = Property(Float, unit = 'MPa', depends_on = 'input_change', table_field = True) def _get_E_c(self): return self.ccs.get_E_c_time(self.age) # E-modulus of the composite after 28 days E_c28 = DelegatesTo('ccs', listenable = False) # reinforcement ration of the composite rho_c = DelegatesTo('ccs', listenable = False) #-------------------------------------------------------------------------------- # define processing #-------------------------------------------------------------------------------- # put this into the ironing procedure processor # jump_rtol = Float(1, auto_set = False, enter_set = True, ironing_param = True) data_array_ironed = Property(Array(float), depends_on = 'data_array, +ironing_param, +axis_selection') @cached_property def _get_data_array_ironed(self): '''remove the jumps in the displacement curves due to resetting the displacement gauges. ''' print '*** curve ironing activated ***' # each column from the data array corresponds to a measured parameter # e.g. displacement at a given point as function of time u = f(t)) # data_array_ironed = copy(self.data_array) for idx in range(self.data_array.shape[1]): # use ironing method only for columns of the displacement gauges. # if self.names_and_units[0][ idx ] != 'Kraft' and \ self.names_and_units[0][ idx ] != 'Bezugskanal' and \ self.names_and_units[0][ idx ] != 'D_1o'and \ self.names_and_units[0][ idx ] != 'D_2o'and \ self.names_and_units[0][ idx ] != 'D_3o'and \ self.names_and_units[0][ idx ] != 'D_4o'and \ self.names_and_units[0][ idx ] != 'D_1u'and \ self.names_and_units[0][ idx ] != 'D_2u'and \ self.names_and_units[0][ idx ] != 'D_3u'and \ self.names_and_units[0][ idx ] != 'D_4u'and \ self.names_and_units[0][ idx ] != 'W30_vo'and \ self.names_and_units[0][ idx ] != 'W30_hi': # 1d-array corresponding to column in data_array data_arr = copy(data_array_ironed[:, idx]) # get the difference between each point and its successor jump_arr = data_arr[1:] - data_arr[0:-1] # get the range of the measured data data_arr_range = max(data_arr) - min(data_arr) # determine the relevant criteria for a jump # based on the data range and the specified tolerances: jump_crit = self.jump_rtol * data_arr_range # get the indexes in 'data_column' after which a # jump exceeds the defined tolerance criteria jump_idx = where(fabs(jump_arr) > jump_crit)[0] print 'number of jumps removed in data_arr_ironed for', self.names_and_units[0][ idx ], ': ', jump_idx.shape[0] # glue the curve at each jump together for jidx in jump_idx: # get the offsets at each jump of the curve shift = data_arr[jidx + 1] - data_arr[jidx] # shift all succeeding values by the calculated offset data_arr[jidx + 1:] -= shift data_array_ironed[:, idx] = data_arr[:] return data_array_ironed @on_trait_change('+ironing_param') def process_source_data(self): '''read in the measured data from file and assign attributes after array processing. NOTE: if center displacement gauge ('WA_M') is missing the measured displacement of the cylinder ('Weg') is used instead. A minor mistake is made depending on how much time passes before the cylinder has contact with the slab. ''' print '*** process source data ***' self._read_data_array() # curve ironing: # self.processed_data_array = self.data_array_ironed # set attributes: # self._set_array_attribs() #-------------------------------------------------------------------------------- # plot templates #-------------------------------------------------------------------------------- plot_templates = {'force / time' : '_plot_force_time', 'force / deflections center' : '_plot_force_deflection_center', 'force / smoothed deflections center' : '_plot_smoothed_force_deflection_center', 'force / deflections' : '_plot_force_deflections', 'force / eps_t' : '_plot_force_eps_t', 'force / eps_c' : '_plot_force_eps_c', 'force / w_elastomer' : '_plot_force_w_elastomer', 'time / deflections' : '_plot_time_deflections' } default_plot_template = 'force / time' def _plot_force_w_elastomer(self, axes): xkey = 'displacement [mm]' ykey = 'force [kN]' W_vl = self.W_vl W_vr = self.W_vr W_hl = self.W_hl W_hr = self.W_hr force = self.Kraft axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) axes.plot(W_vl, force) axes.plot(W_vr, force) axes.plot(W_hl, force) axes.plot(W_hr, force) def _plot_force_time(self, axes): xkey = 'time [s]' ykey = 'force [kN]' xdata = self.Bezugskanal ydata = self.Kraft axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) axes.plot(xdata, ydata # color = c, linewidth = w, linestyle = s ) def _plot_force_deflection_center(self, axes): xkey = 'deflection [mm]' ykey = 'force [kN]' xdata = -self.WD4 ydata = self.Kraft axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) axes.plot(xdata, ydata # color = c, linewidth = w, linestyle = s ) n_fit_window_fraction = Float(0.1) def _plot_smoothed_force_deflection_center(self, axes): xkey = 'deflection [mm]' ykey = 'force [kN]' # get the index of the maximum stress max_force_idx = argmax(self.Kraft) # get only the ascending branch of the response curve f_asc = self.Kraft[:max_force_idx + 1] w_asc = -self.WD4[:max_force_idx + 1] f_max = f_asc[-1] w_max = w_asc[-1] n_points = int(self.n_fit_window_fraction * len(w_asc)) f_smooth = smooth(f_asc, n_points, 'flat') w_smooth = smooth(w_asc, n_points, 'flat') axes.plot(w_smooth, f_smooth, color = 'blue', linewidth = 2) secant_stiffness_w10 = (f_smooth[10] - f_smooth[0]) / (w_smooth[10] - w_smooth[0]) w0_lin = array([0.0, w_smooth[10] ], dtype = 'float_') f0_lin = array([0.0, w_smooth[10] * secant_stiffness_w10 ], dtype = 'float_') axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) def _plot_force_deflections(self, axes): xkey = 'displacement [mm]' ykey = 'force [kN]' # get the index of the maximum stress max_force_idx = argmax(self.Kraft) # get only the ascending branch of the response curve f_asc = self.Kraft[:max_force_idx + 1] WD1 = -self.WD1[:max_force_idx + 1] WD2 = -self.WD2[:max_force_idx + 1] WD3 = -self.WD3[:max_force_idx + 1] WD4 = -self.WD4[:max_force_idx + 1] WD5 = -self.WD5[:max_force_idx + 1] WD6 = -self.WD6[:max_force_idx + 1] WD7 = -self.WD7[:max_force_idx + 1] axes.plot(WD1, f_asc, color = 'blue', linewidth = 1 ) axes.plot(WD2, f_asc, color = 'green', linewidth = 1 ) axes.plot(WD3, f_asc, color = 'red', linewidth = 1 ) axes.plot(WD4, f_asc, color = 'black', linewidth = 3 ) axes.plot(WD5, f_asc, color = 'red', linewidth = 1 ) axes.plot(WD6, f_asc, color = 'green', linewidth = 1 ) axes.plot(WD7, f_asc, color = 'blue', linewidth = 1 ) axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) def _plot_time_deflections(self, axes): xkey = 'time [s]' ykey = 'deflections [mm]' time = self.Bezugskanal WD1 = -self.WD1 WD2 = -self.WD2 WD3 = -self.WD3 WD4 = -self.WD4 WD5 = -self.WD5 WD6 = -self.WD6 WD7 = -self.WD7 axes.plot(time, WD1, color = 'blue', linewidth = 1 ) axes.plot(time, WD2, color = 'green', linewidth = 1 ) axes.plot(time, WD3, color = 'red', linewidth = 1 ) axes.plot(time, WD4, color = 'black', linewidth = 3 ) axes.plot(time, WD5, color = 'red', linewidth = 1 ) axes.plot(time, WD6, color = 'green', linewidth = 1 ) axes.plot(time, WD7, color = 'blue', linewidth = 1 ) axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) def _plot_force_eps_c(self, axes): xkey = 'force [kN]' ykey = 'strain [mm/m]' # get the index of the maximum stress max_force_idx = argmax(self.Kraft) # get only the ascending branch of the response curve f_asc = self.Kraft[:max_force_idx + 1] D_1u = -self.D_1u[:max_force_idx + 1] D_2u = -self.D_2u[:max_force_idx + 1] D_3u = -self.D_3u[:max_force_idx + 1] D_4u = -self.D_4u[:max_force_idx + 1] D_1o = -self.D_1o[:max_force_idx + 1] D_2o = -self.D_2o[:max_force_idx + 1] D_3o = -self.D_3o[:max_force_idx + 1] D_4o = -self.D_4o[:max_force_idx + 1] axes.plot(f_asc, D_1u, color = 'blue', linewidth = 1 ) axes.plot(f_asc, D_2u, color = 'blue', linewidth = 1 ) axes.plot(f_asc, D_3u, color = 'blue', linewidth = 1 ) axes.plot(f_asc, D_4u, color = 'blue', linewidth = 1 ) axes.plot(f_asc, D_1o, color = 'red', linewidth = 1 ) axes.plot(f_asc, D_2o, color = 'red', linewidth = 1 ) axes.plot(f_asc, D_3o, color = 'red', linewidth = 1 ) axes.plot(f_asc, D_4o, color = 'red', linewidth = 1 ) axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) def _plot_force_eps_t(self, axes): xkey = 'strain [mm/m]' ykey = 'force [kN]' # get the index of the maximum stress max_force_idx = argmax(self.Kraft) # get only the ascending branch of the response curve f_asc = self.Kraft[:max_force_idx + 1] eps_vo = -self.W30_vo[:max_force_idx + 1] / 300. eps_hi = -self.W30_hi[:max_force_idx + 1] / 300. axes.plot(eps_vo, f_asc, color = 'blue', linewidth = 1 ) axes.plot(eps_hi, f_asc, color = 'green', linewidth = 1 ) axes.set_xlabel('%s' % (xkey,)) axes.set_ylabel('%s' % (ykey,)) #-------------------------------------------------------------------------------- # view #-------------------------------------------------------------------------------- traits_view = View(VGroup( Group( Item('jump_rtol', format_str = "%.4f"), label = 'curve_ironing' ), Group( Item('thickness', format_str = "%.3f"), Item('edge_length', format_str = "%.3f"), label = 'geometry' ), Group( Item('loading_rate'), Item('age'), label = 'loading rate and age' ), Group( Item('E_c', show_label = True, style = 'readonly', format_str = "%.0f"), Item('ccs@', show_label = False), label = 'composite cross section' ) ), scrollable = True, resizable = True, height = 0.8, width = 0.6 )
class GridReinforcement(HasTraits): ''' Class delivering reinforcement ratio for a grid reinforcement of a cross section ''' h = Float( 30, auto_set=False, enter_set=True, # [mm] desc='the height of the cross section', modified=True) w = Float( 100, auto_set=False, enter_set=True, # [mm] desc='the width of the cross section', modified=True) n_f_h = Float( 9, auto_set=False, enter_set=True, # [-] desc='the number of fibers in the height direction', modified=True) n_f_w = Float( 12, auto_set=False, enter_set=True, # [-] desc='the number of fibers in the width direction', modified=True) a_f = Float( 0.89, auto_set=False, enter_set=True, # [m] desc='the cross sectional area of a single fiber', modified=True) A_tot = Property(Float, depends_on='+modified') def _get_A_tot(self): return self.h * self.w A_f = Property(Float, depends_on='+modified') def _get_A_f(self): n_f = self.n_f_h * self.n_f_w a_f = self.a_f return a_f * n_f rho = Property(Float, depends_on='+modified') @cached_property def _get_rho(self): return self.A_f / self.A_tot traits_view = View( VGroup( Group(Item('h', label='height'), Item('w', label='width'), label='cross section dimensions', orientation='vertical'), Group(Item('a_f', label='area of a single fiber'), Item('n_f_h', label='# in height direction'), Item('n_f_w', label='# in width direction'), label='layout of the fiber grid', orientation='vertical'), Item('rho', label='current reinforcement ratio', style='readonly', emphasized=True), # label = 'Cross section parameters', id='scm.cs.params', ), id='scm.cs', dock='horizontal', resizable=True, height=0.8, width=0.8)
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 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 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 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 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 ExpEM(ExType): '''Experiment: Elastic Modulus Test ''' # label = Str('three point bending test') implements(IExType) file_ext = 'TRA' #-------------------------------------------------------------------- # register a change of the traits with metadata 'input' #-------------------------------------------------------------------- input_change = Event @on_trait_change('+input, ccs.input_change, +ironing_param') def _set_input_change(self): self.input_change = True #-------------------------------------------------------------------------------- # specify inputs: #-------------------------------------------------------------------------------- edge_length = Float(0.06, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) height = Float(0.12, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) gauge_length = Float(0.10, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) # age of the concrete at the time of testing age = Int(39, unit='d', input=True, table_field=True, auto_set=False, enter_set=True) loading_rate = Float(0.6, unit='MPa/s', input=True, table_field=True, auto_set=False, enter_set=True) #-------------------------------------------------------------------------- # composite cross section #-------------------------------------------------------------------------- ccs = Instance(CompositeCrossSection) def _ccs_default(self): '''default settings correspond to setup '7u_MAG-07-03_PZ-0708-1' ''' # fabric_layout_key = 'MAG-07-03' # fabric_layout_key = '2D-02-06a' fabric_layout_key = '2D-05-11' # concrete_mixture_key = 'PZ-0708-1' concrete_mixture_key = 'FIL-10-09' orientation_fn_key = 'all0' # orientation_fn_key = 'all90' # orientation_fn_key = '90_0' n_layers = 12 s_tex_z = 0.060 / (n_layers + 1) ccs = CompositeCrossSection(fabric_layup_list=[ plain_concrete(s_tex_z * 0.5), FabricLayUp(n_layers=n_layers, orientation_fn_key=orientation_fn_key, s_tex_z=s_tex_z, fabric_layout_key=fabric_layout_key), plain_concrete(s_tex_z * 0.5) ], concrete_mixture_key=concrete_mixture_key) return ccs #-------------------------------------------------------------------------- # Get properties of the composite #-------------------------------------------------------------------------- # E-modulus of the composite at the time of testing E_c = Property(Float, unit='MPa', depends_on='input_change', table_field=True) def _get_E_c(self): return self.ccs.get_E_c_time(self.age) # E-modulus of the composite after 28 days E_c28 = DelegatesTo('ccs', listenable=False) # reinforcement ration of the composite rho_c = DelegatesTo('ccs', listenable=False) #-------------------------------------------------------------------------------- # define processing #-------------------------------------------------------------------------------- def _read_data_array(self): ''' Read the experiment data. ''' print 'READ FILE' _data_array = np.loadtxt(self.data_file, delimiter=';', skiprows=2, usecols=(4, 5, 10, 17, 20)) self.data_array = _data_array names_and_units = Property @cached_property def _get_names_and_units(self): ''' Set the names and units of the measured data. ''' names = ['delta_u1', 'delta_u2', 'w', 'F', 'time'] units = ['mm', 'mm', 'mm', 'kN', 's'] return names, units #0#"Arbeit"; #1#"Dehn. abs"; #2#"Dehn. abs (2. Kanal)"; #3#"Dehnung"; #4#"Dehnung (1. Kanal)"; #5#"Dehnung (2. Kanal)"; #6#"Dehnung nominell"; #7#"DeltaE"; #8#"E1 korr"; #9#"E2 korr"; #10#"Kolbenweg"; #11#"Kolbenweg abs."; #12#"Lastrahmen"; #13#"LE-Kanal"; #14#"PrXXXfzeit"; #15#"Querdehnung"; #16#"S korr"; #17#"Standardkraft"; #18#"Vorlaufzeit"; #19#"Weg"; #20#"Zeit"; #21#"Zyklus" # #"Nm"; #"mm"; #"mm"; #"mm"; #"mm"; #"mm"; #"mm"; #"%"; #"mm"; #" "; #"mm"; #"mm"; #" "; #"mm"; #"s"; #"mm"; #" "; #"N"; #"s"; #"mm"; #"s"; #" " #-------------------------------------------------------------------------------- # plot templates #-------------------------------------------------------------------------------- plot_templates = { 'force / displacement': '_plot_force_displacement', 'stress / strain': '_plot_stress_strain', 'stress / time': '_plot_stress_time', } default_plot_template = 'force / displacement' def _plot_force_displacement(self, axes): xkey = 'deflection [mm]' ykey = 'force [kN]' xdata = self.w ydata = self.F / 1000. # convert from [N] to [kN] axes.set_xlabel('%s' % (xkey, )) axes.set_ylabel('%s' % (ykey, )) axes.plot(xdata, ydata # color = c, linewidth = w, linestyle = s ) def _plot_stress_strain(self, axes): sig = (self.F / 1000000.) / (self.edge_length**2 ) # convert from [N] to [MN] eps1 = (self.delta_u1 / 1000.) / self.gauge_length eps2 = (self.delta_u2 / 1000.) / self.gauge_length eps_m = (eps1 + eps2) / 2. axes.plot(eps_m, sig, color='blue', linewidth=2) def _plot_stress_time(self, axes): sig = (self.F / 1000000.) / (self.edge_length**2 ) # convert from [N] to [MN] axes.plot(self.time, sig, color='blue', linewidth=2) def _plot_displ_time(self, axes): axes.plot(self.time, self.displ, color='blue', linewidth=2) #-------------------------------------------------------------------------------- # view #-------------------------------------------------------------------------------- traits_view = View(VGroup( Group(Item('edge_length', format_str="%.3f"), Item('height', format_str="%.3f"), Item('gauge_length', format_str="%.3f"), label='geometry'), Group(Item('loading_rate'), Item('age'), label='loading rate and age'), Group(Item('E_c', show_label=True, style='readonly', format_str="%.0f"), Item('ccs@', show_label=False), label='composite cross section')), scrollable=True, resizable=True, height=0.8, width=0.6)
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 ExpBT3PT(ExType): '''Experiment: Bending Test Three Point ''' # label = Str('three point bending test') implements(IExType) file_ext = 'raw' #-------------------------------------------------------------------- # register a change of the traits with metadata 'input' #-------------------------------------------------------------------- input_change = Event @on_trait_change('+input, ccs.input_change, +ironing_param') def _set_input_change(self): self.input_change = True #-------------------------------------------------------------------------------- # specify inputs: #-------------------------------------------------------------------------------- length = Float(0.46, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) width = Float(0.1, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) thickness = Float(0.02, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) # age of the concrete at the time of testing age = Int(33, unit='d', input=True, table_field=True, auto_set=False, enter_set=True) loading_rate = Float(4.0, unit='mm/min', input=True, table_field=True, auto_set=False, enter_set=True) #-------------------------------------------------------------------------- # composite cross section #-------------------------------------------------------------------------- ccs = Instance(CompositeCrossSection) def _ccs_default(self): '''default settings ''' # fabric_layout_key = 'MAG-07-03' # fabric_layout_key = '2D-02-06a' fabric_layout_key = '2D-05-11' # fabric_layout_key = '2D-09-12' # concrete_mixture_key = 'PZ-0708-1' # concrete_mixture_key = 'FIL-10-09' concrete_mixture_key = 'barrelshell' orientation_fn_key = 'all0' # orientation_fn_key = 'all90' # orientation_fn_key = '90_0' n_layers = 6 s_tex_z = 0.020 / (n_layers + 1) ccs = CompositeCrossSection(fabric_layup_list=[ plain_concrete(s_tex_z * 0.5), FabricLayUp(n_layers=n_layers, orientation_fn_key=orientation_fn_key, s_tex_z=s_tex_z, fabric_layout_key=fabric_layout_key), plain_concrete(s_tex_z * 0.5) ], concrete_mixture_key=concrete_mixture_key) return ccs #-------------------------------------------------------------------------- # Get properties of the composite #-------------------------------------------------------------------------- # E-modulus of the composite at the time of testing E_c = Property(Float, unit='MPa', depends_on='input_change', table_field=True) def _get_E_c(self): return self.ccs.get_E_c_time(self.age) # E-modulus of the composite after 28 days E_c28 = DelegatesTo('ccs', listenable=False) # reinforcement ration of the composite rho_c = DelegatesTo('ccs', listenable=False) #-------------------------------------------------------------------------------- # define processing #-------------------------------------------------------------------------------- # flag distinguishes weather data from a displacement gauge is available # stored in a separate ASC-file with a corresponding file name # flag_ASC_file = Bool(False) def _read_data_array(self): ''' Read the experiment data. ''' if exists(self.data_file): print 'READ FILE' file_split = self.data_file.split('.') # first check if a '.csv' file exists. If yes use the # data stored in the '.csv'-file and ignore # the data in the '.raw' file! # file_name = file_split[0] + '.csv' if not os.path.exists(file_name): file_name = file_split[0] + '.raw' if not os.path.exists(file_name): raise IOError, 'file %s does not exist' % file_name print 'file_name', file_name _data_array = loadtxt_bending(file_name) self.data_array = _data_array # check if a '.ASC'-file exists. If yes append this information # to the data array. # file_name = file_split[0] + '.ASC' if not os.path.exists(file_name): print 'NOTE: no data from displacement gauge is available (no .ASC file)' self.flag_ASC_file = False else: print 'NOTE: additional data from displacement gauge for center deflection is available (.ASC-file loaded)!' self.flag_ASC_file = True # add data array read in from .ASC-file; the values are assigned by '_set_array_attribs' based on the # read in values in 'names_and_units' read in from the corresponding .DAT-file # self.data_array_ASC = loadtxt(file_name, delimiter=';') else: print 'WARNING: data_file with path %s does not exist == False' % ( self.data_file) names_and_units = Property(depends_on='data_file') @cached_property def _get_names_and_units(self): '''names and units corresponding to the returned '_data_array' by 'loadtxt_bending' ''' names = ['w_raw', 'eps_c_raw', 'F_raw'] units = ['mm', '1*E-3', 'N'] print 'names, units from .raw-file', names, units return names, units names_and_units_ASC = Property(depends_on='data_file') @cached_property def _get_names_and_units_ASC(self): ''' Extract the names and units of the measured data. The order of the names in the .DAT-file corresponds to the order of the .ASC-file. ''' file_split = self.data_file.split('.') file_name = file_split[0] + '.DAT' data_file = open(file_name, 'r') lines = data_file.read().split() names = [] units = [] for i in range(len(lines)): if lines[i] == '#BEGINCHANNELHEADER': name = lines[i + 1].split(',')[1] unit = lines[i + 3].split(',')[1] names.append(name) units.append(unit) print 'names, units extracted from .DAT-file', names, units return names, units factor_list_ASC = Property(depends_on='data_file') def _get_factor_list_ASC(self): return self.names_and_units_ASC[0] def _set_array_attribs(self): '''Set the measured data as named attributes defining slices into the processed data array. ''' for i, factor in enumerate(self.factor_list): self.add_trait( factor, Array(value=self.processed_data_array[:, i], transient=True)) if self.flag_ASC_file: for i, factor in enumerate(self.factor_list_ASC): self.add_trait( factor, Array(value=self.data_array_ASC[:, i], transient=True)) elastomer_law = Property(depends_on='input_change') @cached_property def _get_elastomer_law(self): elastomer_path = os.path.join(simdb.exdata_dir, 'bending_tests', 'three_point', '2011-06-10_BT-3PT-12c-6cm-0-TU_ZiE', 'elastomer_f-w.raw') _data_array_elastomer = loadtxt_bending(elastomer_path) # force [kN]: # NOTE: after conversion 'F_elastomer' is a positive value # F_elastomer = -0.001 * _data_array_elastomer[:, 2].flatten() # displacement [mm]: # NOTE: after conversion 'w_elastomer' is a positive value # w_elastomer = -1.0 * _data_array_elastomer[:, 0].flatten() mfn_displacement_elastomer = MFnLineArray(xdata=F_elastomer, ydata=w_elastomer) return frompyfunc(mfn_displacement_elastomer.get_value, 1, 1) w_wo_elast = Property(depends_on='input_change') @cached_property def _get_w_wo_elast(self): # use the machine displacement for the center displacement: # subtract the deformation of the elastomer cushion between the cylinder # and change sign in positive values for vertical displacement [mm] # return self.w_raw - self.elastomer_law(self.F_raw) M_ASC = Property(Array('float_'), depends_on='input_change') @cached_property def _get_M_ASC(self): return self.F_ASC * self.length / 4.0 M_raw = Property(Array('float_'), depends_on='input_change') @cached_property def _get_M_raw(self): return self.F_raw * self.length / 4.0 # # get only the ascending branch of the response curve # # # max_force_idx = Property(Int) # def _get_max_force_idx(self): # '''get the index of the maximum force''' # return argmax(-self.Kraft) # # f_asc = Property(Array) # def _get_f_asc(self): # '''get only the ascending branch of the response curve''' # return -self.Kraft[:self.max_force_idx + 1] K_bending_elast = Property(Array('float_'), depends_on='input_change') @cached_property def _get_K_bending_elast(self): '''calculate the analytical bending stiffness of the beam (3 point bending) ''' t = self.thickness w = self.width L = self.length # coposite E-modulus # E_c = self.E_c # moment of inertia # I_yy = t**3 * w / 12. delta_11 = (L**3) / 48 / E_c / I_yy # [MN/m]=[kN/mm] bending stiffness with respect to a force applied at center of the beam # K_bending_elast = 1 / delta_11 # print 'K_bending_elast', K_bending_elast return K_bending_elast F_cr = Property(Array('float_'), depends_on='input_change') @cached_property def _get_F_cr(self): '''calculate the analytical cracking load of the beam ''' t = self.thickness w = self.width L = self.length # approx. flectural tensile strength # f_cfl = 6. # MPa # resistant moment # W_yy = t**2 * w / 6. # analytical cracking load of the beam # corresponds to l = 0.46m and f_cfl = approx. 8.4 MPa# # F_cr = W_yy * f_cfl * 1000. / L # [kN] return F_cr def process_source_data(self): '''read in the measured data from file and assign attributes after array processing. ''' super(ExpBT3PT, self).process_source_data() #--------------------------------------------- # process data from .raw file (machine data) #--------------------------------------------- # convert machine force [N] to [kN] and return only positive values # self.F_raw *= -0.001 # convert machine displacement [mm] to positive values # and remove offset # self.w_raw *= -1.0 self.w_raw -= self.w_raw[0] # convert [permille] to [-] and return only positive values # self.eps_c_raw *= -0.001 # access the derived arrays to initiate their processing # self.w_wo_elast self.M_raw #--------------------------------------------- # process data from .ASC file (displacement gauge) #--------------------------------------------- # only if separate ASC.-file with force-displacement data from displacement gauge is available # if self.flag_ASC_file == True: self.F_ASC = -1.0 * self.Kraft # remove offset and change sign to return positive displacement values # if hasattr(self, "WA50"): self.WA50 *= -1 self.WA50 -= self.WA50[0] WA50_avg = np.average(self.WA50) if hasattr(self, "W10_u"): self.W10_u *= -1 self.W10_u -= self.W10_u[0] W10_u_avg = np.average(self.W10_u) # check which displacement gauge has been used depending on weather two names are listed in .DAT file or only one # and assign values to 'w_ASC' # if hasattr(self, "W10_u") and hasattr(self, "WA50"): if W10_u_avg > WA50_avg: self.w_ASC = self.W10_u print 'self.W10_u assigned to self.w_ASC' else: self.w_ASC = self.WA50 print 'self.WA50 assigned to self.w_ASC' elif hasattr(self, "W10_u"): self.w_ASC = self.W10_u print 'self.W10_u assigned to self.w_ASC' elif hasattr(self, "WA50"): self.w_ASC = self.WA50 print 'self.WA50 assigned to self.w_ASC' # convert strain from [permille] to [-], # switch to positive values for compressive strains # and remove offset # self.eps_c_ASC = -0.001 * self.DMS_l self.eps_c_ASC -= self.eps_c_ASC[0] # access the derived arrays to initiate their processing # self.M_ASC #-------------------------------------------------------------------------------- # plot templates #-------------------------------------------------------------------------------- plot_templates = { 'force / machine displacement (incl. w_elast)': '_plot_force_machine_displacement', 'force / machine displacement (without w_elast)': '_plot_force_machine_displacement_wo_elast', 'force / machine displacement (without w_elast, interpolated)': '_plot_force_machine_displacement_wo_elast_interpolated', 'force / machine displacement (analytical offset)': '_plot_force_machine_displacement_wo_elast_analytical_offset', 'force / gauge displacement': '_plot_force_gauge_displacement', 'force / gauge displacement (analytical offset)': '_plot_force_gauge_displacement_with_analytical_offset', 'force / gauge displacement (interpolated)': '_plot_force_gauge_displacement_interpolated', # 'smoothed force / gauge displacement' : '_plot_smoothed_force_gauge_displacement', # 'smoothed force / machine displacement' : '_plot_smoothed_force_machine_displacement_wo_elast', # 'moment / eps_c (ASC)': '_plot_moment_eps_c_ASC', 'moment / eps_c (raw)': '_plot_moment_eps_c_raw', # # 'smoothed moment / eps_c (ASC)' : '_plot_smoothed_moment_eps_c_ASC', # 'smoothed moment / eps_c (raw)' : '_plot_smoothed_moment_eps_c_raw', # # 'analytical bending stiffness' : '_plot_analytical_bending_stiffness' } default_plot_template = 'force / deflection (displacement gauge)' def _plot_analytical_bending_stiffness(self, axes, color='red', linewidth=1., linestyle='--'): '''plot the analytical bending stiffness of the beam (3 point bending) ''' t = self.thickness w = self.width L = self.length # composite E-modulus # E_c = self.E_c # moment of inertia # I_yy = t**3 * w / 12. delta_11 = L**3 / 48 / E_c / I_yy K_linear = 1 / delta_11 # [MN/m] bending stiffness with respect to a force applied at center of the beam w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., K_linear]) axes.plot(w_linear, F_linear, linestyle='--') def _plot_force_machine_displacement_wo_elast(self, axes, color='blue', linewidth=1., linestyle='-'): # get the index of the maximum stress # max_force_idx = argmax(self.F_raw) # get only the ascending branch of the response curve # f_asc = self.F_raw[:max_force_idx + 1] w_asc = self.w_wo_elast[:max_force_idx + 1] axes.plot(w_asc, f_asc, color=color, linewidth=linewidth, linestyle=linestyle) # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') # xkey = 'deflection [mm]' # ykey = 'force [kN]' # axes.set_xlabel('%s' % (xkey,)) # axes.set_ylabel('%s' % (ykey,)) def _plot_force_machine_displacement_wo_elast_interpolated( self, axes, color='green', linewidth=1., linestyle='-'): # get the index of the maximum stress # max_force_idx = argmax(self.F_raw) # get only the ascending branch of the response curve # f_asc = self.F_raw[:max_force_idx + 1] w_asc = np.copy(self.w_wo_elast[:max_force_idx + 1]) # interpolate the starting point of the center deflection curve based on the slope of the curve # (remove offset in measured displacement where there is still no force measured) # idx_10 = np.where(f_asc > f_asc[-1] * 0.10)[0][0] idx_8 = np.where(f_asc > f_asc[-1] * 0.08)[0][0] f8 = f_asc[idx_8] f10 = f_asc[idx_10] w8 = w_asc[idx_8] w10 = w_asc[idx_10] m = (f10 - f8) / (w10 - w8) delta_w = f8 / m w0 = w8 - delta_w * 0.9 # print 'w0', w0 f_asc_interpolated = np.hstack([0., f_asc[idx_8:]]) w_asc_interpolated = np.hstack([w0, w_asc[idx_8:]]) # print 'type( w_asc_interpolated )', type(w_asc_interpolated) w_asc_interpolated -= float(w0) axes.plot(w_asc_interpolated, f_asc_interpolated, color=color, linewidth=linewidth, linestyle=linestyle) # fw_arr = np.hstack([f_asc_interpolated[:, None], w_asc_interpolated[:, None]]) # print 'fw_arr.shape', fw_arr.shape # np.savetxt('BT-3PT-12c-6cm-TU_f-w_interpolated.csv', fw_arr, delimiter=';') # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') def _plot_force_machine_displacement_wo_elast_analytical_offset( self, axes, color='green', linewidth=1., linestyle='-'): # get the index of the maximum stress # max_force_idx = argmax(self.F_raw) # get only the ascending branch of the response curve # f_asc = self.F_raw[:max_force_idx + 1] w_asc = np.copy(self.w_wo_elast[:max_force_idx + 1]) M_asc = f_asc * self.length / 4. eps_c_asc = self.eps_c_raw[:max_force_idx + 1] t = self.thickness w = self.width # coposite E-modulus # E_c = self.E_c # resistant moment # W_yy = t**2 * w / 6. K_I_analytic = W_yy * E_c # [MN/m] bending stiffness with respect to center moment K_I_analytic *= 1000. # [kN/m] bending stiffness with respect to center moment # interpolate the starting point of the center deflection curve based on the slope of the curve # (remove offset in measured displacement where there is still no force measured) # idx_lin = np.where(M_asc <= K_I_analytic * eps_c_asc)[0][0] idx_lin = int(idx_lin * 0.7) # idx_lin = 50 # idx_lin = np.where(M_asc - M_asc[0] / eps_c_asc <= 0.90 * K_I_analytic)[0][0] print 'idx_lin', idx_lin print 'F_asc[idx_lin]', f_asc[idx_lin] print 'M_asc[idx_lin]', M_asc[idx_lin] print 'w_asc[idx_lin]', w_asc[idx_lin] w_lin_epsc = w_asc[idx_lin] w_lin_analytic = f_asc[idx_lin] / self.K_bending_elast f_asc_offset_analytic = f_asc[idx_lin:] w_asc_offset_analytic = w_asc[idx_lin:] w_asc_offset_analytic -= np.array([w_lin_epsc]) w_asc_offset_analytic += np.array([w_lin_analytic]) axes.plot(w_asc_offset_analytic, f_asc_offset_analytic, color=color, linewidth=linewidth, linestyle=linestyle) # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') def _plot_force_machine_displacement(self, axes, color='black', linewidth=1., linestyle='-'): xdata = self.w_raw ydata = self.F_raw axes.plot(xdata, ydata, color=color, linewidth=linewidth, linestyle=linestyle) # xkey = 'deflection [mm]' # ykey = 'force [kN]' # axes.set_xlabel('%s' % (xkey,)) # axes.set_ylabel('%s' % (ykey,)) # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') def _plot_force_gauge_displacement_with_analytical_offset( self, axes, color='black', linewidth=1., linestyle='-'): # skip the first values (= first seconds of testing) # and start with the analytical bending stiffness instead to avoid artificial offset of F-w-diagram # # w_max = np.max(self.w_ASC) # cut_idx = np.where(self.w_ASC > 0.001 * w_max)[0] cut_idx = np.where(self.w_ASC > 0.01)[0] print 'F_cr ', self.F_cr # cut_idx = np.where(self.F_ASC > 0.6 * self.F_cr)[0] print 'cut_idx', cut_idx[0] print 'w_ASC[cut_idx[0]]', self.w_ASC[cut_idx[0]] xdata = np.copy(self.w_ASC[cut_idx]) ydata = np.copy(self.F_ASC[cut_idx]) # specify offset if force does not start at the origin with value 0. F_0 = ydata[0] print 'F_0 ', F_0 offset_w = F_0 / self.K_bending_elast xdata -= xdata[0] xdata += offset_w f_asc_interpolated = np.hstack([0, ydata]) w_asc_interpolated = np.hstack([0, xdata]) # fw_arr = np.hstack([f_asc_interpolated[:, None], w_asc_interpolated[:, None]]) # print 'fw_arr.shape', fw_arr.shape # np.savetxt('BT-3PT-6c-2cm-TU_f-w_interpolated.csv', fw_arr, delimiter=';') xdata = self.w_raw ydata = self.F_raw axes.plot(xdata, ydata, color='blue', linewidth=linewidth, linestyle=linestyle) axes.plot(w_asc_interpolated, f_asc_interpolated, color=color, linewidth=linewidth, linestyle=linestyle) # xkey = 'deflection [mm]' # ykey = 'force [kN]' # axes.set_xlabel('%s' % (xkey,)) # axes.set_ylabel('%s' % (ykey,)) # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') def _plot_force_gauge_displacement(self, axes, offset_w=0., color='black', linewidth=1., linestyle='-'): xdata = self.w_ASC ydata = self.F_ASC # specify offset if force does not start at the origin xdata += offset_w axes.plot(xdata, ydata, color=color, linewidth=linewidth, linestyle=linestyle) # xkey = 'deflection [mm]' # ykey = 'force [kN]' # axes.set_xlabel('%s' % (xkey,)) # axes.set_ylabel('%s' % (ykey,)) # fw_arr = np.hstack([xdata[:, None], ydata[:, None]]) # print 'fw_arr.shape', fw_arr.shape # np.savetxt('BT-3PT-6c-2cm-TU-80cm-V3_f-w_asc.csv', fw_arr, delimiter=';') # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') def _plot_smoothed_force_gauge_displacement(self, axes): # get the index of the maximum stress # max_force_idx = argmax(self.F_ASC) # get only the ascending branch of the response curve # F_asc = self.F_ASC[:max_force_idx + 1] w_asc = self.w_ASC[:max_force_idx + 1] n_points = int(self.n_fit_window_fraction * len(w_asc)) F_smooth = smooth(F_asc, n_points, 'flat') w_smooth = smooth(w_asc, n_points, 'flat') axes.plot(w_smooth, F_smooth, color='blue', linewidth=2) def _plot_force_gauge_displacement_interpolated(self, axes, color='green', linewidth=1., linestyle='-'): '''get only the ascending branch of the meassured load-displacement curve)''' # get the index of the maximum stress # max_force_idx = argmax(self.F_ASC) # get only the ascending branch of the response curve # f_asc = self.F_ASC[:max_force_idx + 1] w_asc = self.w_ASC[:max_force_idx + 1] # interpolate the starting point of the center deflection curve based on the slope of the curve # (remove offset in measured displacement where there is still no force measured) # idx_10 = np.where(f_asc > f_asc[-1] * 0.10)[0][0] idx_8 = np.where(f_asc > f_asc[-1] * 0.08)[0][0] f8 = f_asc[idx_8] f10 = f_asc[idx_10] w8 = w_asc[idx_8] w10 = w_asc[idx_10] m = (f10 - f8) / (w10 - w8) delta_w = f8 / m w0 = w8 - delta_w * 0.9 print 'w0', w0 f_asc_interpolated = np.hstack([0., f_asc[idx_8:]]) w_asc_interpolated = np.hstack([w0, w_asc[idx_8:]]) print 'type( w_asc_interpolated )', type(w_asc_interpolated) w_asc_interpolated -= float(w0) # w_offset = f_asc[idx_10] / self.K_bending_elast # f_asc_interpolated = np.hstack([0., f_asc[ idx_10: ]]) # w_asc_interpolated = np.hstack([0, w_asc[ idx_10: ] - w_asc[idx_10] + w_offset]) axes.plot(w_asc_interpolated, f_asc_interpolated, color=color, linewidth=linewidth, linestyle=linestyle) # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') def _plot_smoothed_force_machine_displacement_wo_elast(self, axes): # get the index of the maximum stress # max_force_idx = argmax(self.F_raw) # get only the ascending branch of the response curve # F_asc = self.F_raw[:max_force_idx + 1] w_asc = self.w_wo_elast[:max_force_idx + 1] n_points = int(self.n_fit_window_fraction * len(w_asc)) F_smooth = smooth(F_asc, n_points, 'flat') w_smooth = smooth(w_asc, n_points, 'flat') axes.plot(w_smooth, F_smooth, color='blue', linewidth=2) # plot analytical bending stiffness # w_linear = 2 * np.array([0., 1.]) F_linear = 2 * np.array([0., self.K_bending_elast]) axes.plot(w_linear, F_linear, linestyle='--') # secant_stiffness_w10 = ( f_smooth[10] - f_smooth[0] ) / ( w_smooth[10] - w_smooth[0] ) # w0_lin = array( [0.0, w_smooth[10] ], dtype = 'float_' ) # f0_lin = array( [0.0, w_smooth[10] * secant_stiffness_w10 ], dtype = 'float_' ) # axes.plot( w0_lin, f0_lin, color = 'black' ) def _plot_moment_eps_c_ASC(self, axes): xkey = 'compressive strain [1*E-3]' ykey = 'moment [kNm]' xdata = self.eps_c_ASC ydata = self.M_ASC axes.set_xlabel('%s' % (xkey, )) axes.set_ylabel('%s' % (ykey, )) axes.plot(xdata, ydata) # plot stiffness in uncracked state t = self.thickness w = self.width # composite E-modulus # E_c = self.E_c # resistant moment # W_yy = t**2 * w / 6. max_M = np.max(self.M_raw) K_linear = W_yy * E_c # [MN/m] bending stiffness with respect to center moment K_linear *= 1000. # [kN/m] bending stiffness with respect to center moment w_linear = np.array([0., max_M / K_linear]) M_linear = np.array([0., max_M]) axes.plot(w_linear, M_linear, linestyle='--') def _plot_moment_eps_c_raw(self, axes, color='black', linewidth=1.5, linestyle='-'): xkey = 'compressive strain [1*E-3]' ykey = 'moment [kNm]' xdata = self.eps_c_raw ydata = self.M_raw axes.set_xlabel('%s' % (xkey, )) axes.set_ylabel('%s' % (ykey, )) axes.plot(xdata, ydata, color=color, linewidth=linewidth, linestyle=linestyle) # plot stiffness in uncracked state t = self.thickness w = self.width # composite E-modulus # E_c = self.E_c # resistant moment # W_yy = t**2 * w / 6. max_M = np.max(self.M_raw) K_linear = W_yy * E_c # [MN/m] bending stiffness with respect to center moment K_linear *= 1000. # [kN/m] bending stiffness with respect to center moment w_linear = np.array([0., max_M / K_linear]) M_linear = np.array([0., max_M]) axes.plot(w_linear, M_linear, linestyle='--') n_fit_window_fraction = Float(0.1) smoothed_M_eps_c_ASC = Property(depends_on='input_change') @cached_property def _get_smoothed_M_eps_c_ASC(self): # get the index of the maximum stress max_idx = argmax(self.M_ASC) # get only the ascending branch of the response curve m_asc = self.M_ASC[:max_idx + 1] eps_c_asc = self.eps_c_ASC[:max_idx + 1] n_points = int(self.n_fit_window_fraction * len(eps_c_asc)) m_smoothed = smooth(m_asc, n_points, 'flat') eps_c_smoothed = smooth(eps_c_asc, n_points, 'flat') return m_smoothed, eps_c_smoothed smoothed_eps_c_ASC = Property def _get_smoothed_eps_c_ASC(self): return self.smoothed_M_eps_c_ASC[1] smoothed_M_ASC = Property def _get_smoothed_M_ASC(self): return self.smoothed_M_eps_c_ASC[0] def _plot_smoothed_moment_eps_c_ASC(self, axes): axes.plot(self.smoothed_eps_c_ASC, self.smoothed_M_ASC, color='blue', linewidth=2) smoothed_M_eps_c_raw = Property(depends_on='input_change') @cached_property def _get_smoothed_M_eps_c_raw(self): # get the index of the maximum stress max_idx = argmax(self.M_raw) # get only the ascending branch of the response curve m_asc = self.M_raw[:max_idx + 1] eps_c_asc = self.eps_c_raw[:max_idx + 1] n_points = int(self.n_fit_window_fraction * len(eps_c_asc)) m_smoothed = smooth(m_asc, n_points, 'flat') eps_c_smoothed = smooth(eps_c_asc, n_points, 'flat') return m_smoothed, eps_c_smoothed smoothed_eps_c_raw = Property def _get_smoothed_eps_c_raw(self): return self.smoothed_M_eps_c_raw[1] smoothed_M_raw = Property def _get_smoothed_M_raw(self): return self.smoothed_M_eps_c_raw[0] def _plot_smoothed_moment_eps_c_raw(self, axes): axes.plot(self.smoothed_eps_c_raw, self.smoothed_M_raw, color='blue', linewidth=2) #-------------------------------------------------------------------------------- # view #-------------------------------------------------------------------------------- traits_view = View(VGroup( Group(Item('length', format_str="%.3f"), Item('width', format_str="%.3f"), Item('thickness', format_str="%.3f"), label='geometry'), Group(Item('loading_rate'), Item('age'), label='loading rate and age'), Group(Item('E_c', show_label=True, style='readonly', format_str="%.0f"), Item('ccs@', show_label=False), label='composite cross section')), scrollable=True, resizable=True, height=0.8, width=0.6)
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 YMBMicro(HasTraits): ''' Yarn-Matrix-Bond Microstructure analysis ''' data = Instance(IYMBData) view_3d = Property(Instance(YMBView3D)) @cached_property def _get_view_3d(self): return YMBView3D(data=self.data) cut_view = Property(Instance(YMBView2D)) @cached_property def _get_cut_view(self): return YMBView2D(data=self.data) slider = Property(Instance(YMBSlider), depends_on='data.input_change') @cached_property def _get_slider(self): return YMBSlider(data=self.data) histogram = Property(Instance(YMBHist), depends_on='data.input_change') @cached_property def _get_histogram(self): return YMBHist(slider=self.slider) auto_correl_data = Property(Instance(YMBAutoCorrel), depends_on='data.input_change') @cached_property def _get_auto_correl_data(self): return YMBAutoCorrel(data=self.data) auto_correl = Property(Instance(YMBAutoCorrelView), depends_on='data.input_change') @cached_property def _get_auto_correl(self): return YMBAutoCorrelView(correl_data=self.auto_correl_data) cross_correl = Property(Instance(YMBCrossCorrel), depends_on='data.input_change') @cached_property def _get_cross_correl(self): return YMBCrossCorrel(data=self.data) pullout = Instance(YMBPullOut) def _pullout_default(self): return YMBPullOut(data=self.data) ymb_tree = Property(Instance(YMBTree)) @cached_property def _get_ymb_tree(self): return YMBTree(ymb_micro=self) # The main view view = View( VGroup( Group(Item('data@', show_label=False), label='Data source'), Group( Item(name='ymb_tree', id='ymb_tree', editor=tree_editor, show_label=False, resizable=True), orientation='vertical', show_labels=True, show_left=True, ), dock='tab', id='qdc.ymb.split', ), id='qdc.ymb', dock='horizontal', drop_class=HasTraits, # handler = TreeHandler(), resizable=True, scrollable=True, title='Yarn-Matrix-Bond Microstructure Lab', handler=TitleHandler(), width=.8, height=.5)
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 PDistribView(ModelView): def __init__(self, **kw): super(PDistribView, self).__init__(**kw) self.on_trait_change( self.refresh, 'model.distr_type.changed, model.quantile, model.n_segments') self.refresh() model = Instance(PDistrib) 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.model.x_array, self.model.pdf_array, lw=1.0, color='blue', label='PDF') axes2 = axes.twinx() # plot CDF on a separate axis (tick labels left) axes2.plot(self.model.x_array, self.model.cdf_array, lw=2, color='red', label='CDF') # fill the unity area given by integrating PDF along the X-axis axes.fill_between(self.model.x_array, 0, self.model.pdf_array, color='lightblue', alpha=0.8, linewidth=2) # plot mean mean = self.model.distr_type.distr.stats('m') axes.plot([mean, mean], [0.0, self.model.distr_type.distr.pdf(mean)], lw=1.5, color='black', linestyle='-') # plot stdev stdev = sqrt(self.model.distr_type.distr.stats('v')) axes.plot([mean - stdev, mean - stdev], [0.0, self.model.distr_type.distr.pdf(mean - stdev)], lw=1.5, color='black', linestyle='--') axes.plot([mean + stdev, mean + stdev], [0.0, self.model.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.model.pdf_array) * 1.15) axes2.set_ylim(0.0, 1.15) range = self.model.range[1] - self.model.range[0] axes.set_xlim(self.model.x_array[0] - 0.05 * range, self.model.x_array[-1] + 0.05 * range) axes2.set_xlim(self.model.x_array[0] - 0.05 * range, self.model.x_array[-1] + 0.05 * range) def refresh(self): self.plot(self.figure) self.data_changed = True icon = Property( Instance(ImageResource), depends_on='model.distr_type.changed, model.quantile, model.n_segments' ) @cached_property def _get_icon(self): import matplotlib.pyplot as plt 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('model.distr_choice', show_label=False), Item('@model.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('model.quantile', label='quantile'), Item('model.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=[OKButton, CancelButton], scrollable=True, resizable=True, width=600, height=400)
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 InfoShellMngr( HasTraits ): '''Assessment tool ''' #------------------------------------------ # specify default data input files: #------------------------------------------ # raw input file for thicknesses (and coordinates) # geo_data_file = Str def _geo_data_file_default( self ): return 'input_geo_data.csv' # raw input file for element numbers, coordinates, and stress_resultants # state_data_file = Str def _state_data_file_default( self ): return 'input_state_data.csv' info_shell_uls = Property( Instance( LSTable ), depends_on = 'state_data_file' ) @cached_property def _get_info_shell_uls( self ): return LSTable( geo_data = self.geo_data, state_data = self.state_data, ls = 'ULS' ) info_shell_sls = Property( Instance( LSTable ), depends_on = 'state_data_file' ) @cached_property def _get_info_shell_sls( self ): return LSTable( geo_data = self.geo_data, state_data = self.state_data, ls = 'SLS' ) #------------------------------------------ # read the geometry data from file # (corrds and thickness): #------------------------------------------ def _read_geo_data( self, file_name ): '''to read the stb-thickness save the xls-worksheet to a csv-file using ';' as filed delimiter and ' ' (blank) as text delimiter. ''' # get the column headings defined in the second row # of the csv thickness input file # "Nr.;X;Y;Z;[mm]" # file = open( file_name, 'r' ) first_line = file.readline() second_line = file.readline() column_headings = second_line.split( ';' ) # remove '\n' from last string element in list column_headings[-1] = column_headings[-1][:-1] column_headings_arr = array( column_headings ) elem_no_idx = where( 'Nr.' == column_headings_arr )[0] X_idx = where( 'X' == column_headings_arr )[0] Y_idx = where( 'Y' == column_headings_arr )[0] Z_idx = where( 'Z' == column_headings_arr )[0] thickness_idx = where( '[mm]' == column_headings_arr )[0] # read the float data: # input_arr = loadtxt( file_name, delimiter = ';', skiprows = 2 ) # element number: # elem_no = input_arr[:, elem_no_idx] # coordinates [m]: # X = input_arr[:, X_idx] Y = input_arr[:, Y_idx] Z = input_arr[:, Z_idx] # element thickness [mm]: # thickness = input_arr[:, thickness_idx] return {'elem_no':elem_no, 'X':X, 'Y':Y, 'Z':Z, 'thickness':thickness } # coordinates and element thickness read from file: # geo_data = Property( Dict, depends_on = 'geo_data_file' ) @cached_property def _get_geo_data( self ): return self._read_geo_data( self.geo_data_file ) #------------------------------------------ # read the state data from file # (elem_no, coords, moments and normal forces): #------------------------------------------ def _Xread_state_data( self, file_name ): '''to read the stb-stress_resultants save the xls-worksheet to a csv-file using ';' as filed delimiter and ' ' (blank) as text delimiter. ''' ###################################################### # this method returns only the MAXIMUM VALUES!!! # @todo: dublicate the elem number and coordinates and add also the minimum values ###################################################### # get the column headings defined in the second row # of the csv soliciotations input file # # column_headings = array(["Nr.","Punkt","X","Y","Z","mx","my","mxy","vx","vy","nx","ny","nxy"]) file = open( file_name, 'r' ) lines = file.readlines() column_headings = lines[1].split( ';' ) # remove '\n' from last string element in list column_headings[-1] = column_headings[-1][:-1] column_headings_arr = array( column_headings ) elem_no_idx = where( 'Nr.' == column_headings_arr )[0] X_idx = where( 'X' == column_headings_arr )[0] Y_idx = where( 'Y' == column_headings_arr )[0] Z_idx = where( 'Z' == column_headings_arr )[0] mx_idx = where( 'mx' == column_headings_arr )[0] my_idx = where( 'my' == column_headings_arr )[0] mxy_idx = where( 'mxy' == column_headings_arr )[0] nx_idx = where( 'nx' == column_headings_arr )[0] ny_idx = where( 'ny' == column_headings_arr )[0] nxy_idx = where( 'nxy' == column_headings_arr )[0] # define arrays containing the information from the raw input file # # @todo: check how loadtxt can be used directly # instead of reading lines line by line? # input_arr = loadtxt( file_name , delimiter=';', skiprows = 2 ) # read max-values (=first row of each double-line): # read stress_resultant csv-input file line by line in steps of two # starting in the third line returning an data array. # n_columns = len( lines[2].split( ';' ) ) # auxiliary line in array sliced off in input array data_array = zeros( n_columns ) for n in range( 2, len( lines ), 2 ): line_split = lines[n].split( ';' ) line_array = array( line_split, dtype = float ) data_array = vstack( [ data_array, line_array ] ) input_arr = data_array[1:, :] # element number: # elem_no = input_arr[:, elem_no_idx] # coordinates [m]: # X = input_arr[:, X_idx] Y = input_arr[:, Y_idx] Z = input_arr[:, Z_idx] # moments [kNm/m] # mx = input_arr[:, mx_idx] my = input_arr[:, my_idx] mxy = input_arr[:, mxy_idx] # normal forces [kN/m]: # nx = input_arr[:, nx_idx] ny = input_arr[:, ny_idx] nxy = input_arr[:, nxy_idx] return { 'elem_no':elem_no, 'X':X, 'Y':Y, 'Z':Z, 'mx':mx, 'my':my, 'mxy':mxy, 'nx':nx, 'ny':ny, 'nxy':nxy } def _read_state_data( self, file_name ): '''to read the stb-stress_resultants save the xls-worksheet to a csv-file using ';' as filed delimiter and ' ' (blank) as text delimiter. ''' ###################################################### # this method returns only the MAXIMUM VALUES!!! # @todo: dublicate the elem number and coordinates and add also the minimum values ###################################################### # get the column headings defined in the second row # of the csv solicitations input file # # column_headings = array(["Nr.","Punkt","X","Y","Z","mx","my","mxy","vx","vy","nx","ny","nxy"]) file = open( file_name, 'r' ) lines = file.readlines() column_headings = lines[1].split( ';' ) # remove '\n' from last string element in list column_headings[-1] = column_headings[-1][:-1] column_headings_arr = array( column_headings ) elem_no_idx = where( 'Nr.' == column_headings_arr )[0] X_idx = where( 'X' == column_headings_arr )[0] Y_idx = where( 'Y' == column_headings_arr )[0] Z_idx = where( 'Z' == column_headings_arr )[0] m1_idx = where( 'm1' == column_headings_arr )[0] m2_idx = where( 'm2' == column_headings_arr )[0] n1_idx = where( 'n1' == column_headings_arr )[0] n2_idx = where( 'n2' == column_headings_arr )[0] # define arrays containing the information from the raw input file # # @todo: check how loadtxt can be used directly # instead of reading lines line by line? # input_arr = loadtxt( file_name , delimiter=';', skiprows = 2 ) # read max-values (=first row of each double-line): # read stress_resultant csv-input file line by line in steps of two # starting in the third line returning an data array. # n_columns = len( lines[2].split( ';' ) ) # auxiliary line in array sliced off in input array data_array = zeros( n_columns ) for n in range( 2, len( lines ), 2 ): line_split = lines[n].split( ';' ) line_array = array( line_split, dtype = float ) data_array = vstack( [ data_array, line_array ] ) input_arr = data_array[1:, :] # element number: # elem_no = input_arr[:, elem_no_idx] # coordinates [m]: # X = input_arr[:, X_idx] Y = input_arr[:, Y_idx] Z = input_arr[:, Z_idx] # moments [kNm/m] # mx = input_arr[:, m1_idx] my = input_arr[:, m2_idx] mxy = zeros_like( input_arr[:, m1_idx] ) # normal forces [kN/m]: # nx = input_arr[:, n1_idx] ny = input_arr[:, n2_idx] nxy = zeros_like( input_arr[:, m1_idx] ) return { 'elem_no':elem_no, 'X':X, 'Y':Y, 'Z':Z, 'mx':mx, 'my':my, 'mxy':mxy, 'nx':nx, 'ny':ny, 'nxy':nxy } # ------------------------------------------------------------ # Read state data from file and assign attributes # ------------------------------------------------------------ # coordinates and stress_resultants read from file: # state_data = Property( Dict, depends_on = 'state_data_file' ) @cached_property def _get_state_data( self ): return self._read_state_data( self.state_data_file ) # ------------------------------------------------------------ # check input files for consistency # ------------------------------------------------------------ @on_trait_change( 'geo_data_file, state_data_file' ) def _check_input_files_for_consistency( self ): '''check if the element order of the thickness input file is identical to the order in the stress_resultant input file ''' if not all( self.geo_data['X'] ) == all( self.state_data['X'] ) or \ not all( self.geo_data['Y'] ) == all( state_data['Y'] ) or \ not all( self.geo_data['Z'] ) == all( state_data['Z'] ): raise ValueError, 'coordinates in file % s and file % s are not identical. Check input files for consistency ! ' \ % ( self.geo_data_file, self.state_data_file ) else: print ' *** input files checked for consistency ( OK ) *** ' return True # ------------------------------------------------------------ # View # ------------------------------------------------------------ traits_view = View( VGroup( Item( 'state_data_file', label = 'Evaluated input file for stress_resultants ', style = 'readonly', emphasized = True ), Item( 'geo_data_file', label = 'Evaluated input file for thicknesses ', style = 'readonly', emphasized = True ), Tabbed( Group( Item( 'info_shell_sls@', show_label = False ), label = 'SLS' ), Group( Item( 'info_shell_uls@', show_label = False ), label = 'ULS' ), ), ), resizable = True, scrollable = True, height = 1000, width = 1100 )
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 ExpST(ExType): '''Experiment: Slab Test ''' # label = Str('slab test') implements(IExType) #-------------------------------------------------------------------- # register a change of the traits with metadata 'input' #-------------------------------------------------------------------- input_change = Event @on_trait_change('+input, ccs.input_change, +ironing_param') def _set_input_change(self): self.input_change = True #-------------------------------------------------------------------------------- # specify inputs: #-------------------------------------------------------------------------------- edge_length = Float(1.25, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) thickness = Float(0.06, unit='m', input=True, table_field=True, auto_set=False, enter_set=True) # age of the concrete at the time of testing age = Int(28, unit='d', input=True, table_field=True, auto_set=False, enter_set=True) loading_rate = Float(2.0, unit='mm/min', input=True, table_field=True, auto_set=False, enter_set=True) #-------------------------------------------------------------------------- # composite cross section #-------------------------------------------------------------------------- ccs = Instance(CompositeCrossSection) def _ccs_default(self): '''default settings correspond to setup '7u_MAG-07-03_PZ-0708-1' ''' fabric_layout_key = '2D-05-11' # fabric_layout_key = 'MAG-07-03' # fabric_layout_key = '2D-02-06a' # concrete_mixture_key = 'PZ-0708-1' # concrete_mixture_key = 'FIL-10-09' # concrete_mixture_key = 'barrelshell' concrete_mixture_key = 'PZ-0708-1' # orientation_fn_key = 'all0' orientation_fn_key = '90_0' n_layers = 2 s_tex_z = 0.015 / (n_layers + 1) ccs = CompositeCrossSection ( fabric_layup_list=[ plain_concrete(0.035), # plain_concrete(s_tex_z * 0.5), FabricLayUp ( n_layers=n_layers, orientation_fn_key=orientation_fn_key, s_tex_z=s_tex_z, fabric_layout_key=fabric_layout_key ), # plain_concrete(s_tex_z * 0.5) plain_concrete(0.5) ], concrete_mixture_key=concrete_mixture_key ) return ccs #-------------------------------------------------------------------------- # Get properties of the composite #-------------------------------------------------------------------------- # E-modulus of the composite at the time of testing E_c = Property(Float, unit='MPa', depends_on='input_change', table_field=True) def _get_E_c(self): return self.ccs.get_E_c_time(self.age) # E-modulus of the composite after 28 days E_c28 = DelegatesTo('ccs', listenable=False) # reinforcement ration of the composite rho_c = DelegatesTo('ccs', listenable=False) #-------------------------------------------------------------------------------- # define processing #-------------------------------------------------------------------------------- # put this into the ironing procedure processor # jump_rtol = Float(0.1, auto_set=False, enter_set=True, ironing_param=True) data_array_ironed = Property(Array(float), depends_on='data_array, +ironing_param, +axis_selection') @cached_property def _get_data_array_ironed(self): '''remove the jumps in the displacement curves due to resetting the displacement gauges. ''' print '*** curve ironing activated ***' # each column from the data array corresponds to a measured parameter # e.g. displacement at a given point as function of time u = f(t)) # data_array_ironed = copy(self.data_array) for idx in range(self.data_array.shape[1]): # use ironing method only for columns of the displacement gauges. # if self.names_and_units[0][ idx ] != 'Kraft' and \ self.names_and_units[0][ idx ] != 'Bezugskanal' and \ self.names_and_units[0][ idx ] != 'Weg': # 1d-array corresponding to column in data_array data_arr = copy(data_array_ironed[:, idx]) # get the difference between each point and its successor jump_arr = data_arr[1:] - data_arr[0:-1] # get the range of the measured data data_arr_range = max(data_arr) - min(data_arr) # determine the relevant criteria for a jump # based on the data range and the specified tolerances: jump_crit = self.jump_rtol * data_arr_range # get the indexes in 'data_column' after which a # jump exceeds the defined tolerance criteria jump_idx = where(fabs(jump_arr) > jump_crit)[0] print 'number of jumps removed in data_arr_ironed for', self.names_and_units[0][ idx ], ': ', jump_idx.shape[0] # glue the curve at each jump together for jidx in jump_idx: # get the offsets at each jump of the curve shift = data_arr[jidx + 1] - data_arr[jidx] # shift all succeeding values by the calculated offset data_arr[jidx + 1:] -= shift data_array_ironed[:, idx] = data_arr[:] return data_array_ironed @on_trait_change('+ironing_param') def process_source_data(self): '''read in the measured data from file and assign attributes after array processing. NOTE: if center displacement gauge ('WA_M') is missing the measured displacement of the cylinder ('Weg') is used instead. A minor mistake is made depending on how much time passes before the cylinder has contact with the slab. ''' print '*** process source data ***' self._read_data_array() # curve ironing: # self.processed_data_array = self.data_array_ironed # set attributes: # self._set_array_attribs() if 'WA_M' not in self.factor_list: print '*** NOTE: Displacement gauge at center ("WA_M") missing. Cylinder displacement ("Weg") is used instead! ***' self.WA_M = self.Weg #-------------------------------------------------------------------------------- # plot templates #-------------------------------------------------------------------------------- plot_templates = {'force / deflection (all)' : '_plot_force_deflection', # 'force / average deflection (c; ce; e) interpolated' : '_plot_force_deflection_avg_interpolated', # 'force / deflection (center)' : '_plot_force_center_deflection', # 'smoothed force / deflection (center)' : '_plot_force_center_deflection_smoothed', # 'force / deflection (edges)' : '_plot_force_edge_deflection', # 'force / deflection (center-edges)' : '_plot_force_center_edge_deflection', # 'force / average deflection (edges)' : '_plot_force_edge_deflection_avg', # 'force / average deflection (center-edges)' : '_plot_force_center_edge_deflection_avg', # 'force / average deflection (c; ce; e)' : '_plot_force_deflection_avg', # 'force / deflection (center) interpolated' : '_plot_force_center_deflection_interpolated', # 'force / deflection (corner)' : '_plot_force_corner_deflection', # 'edge_deflection_avg (front/back) / edge_deflection_avg (left/right)' : '_plot_edge_deflection_edge_deflection_avg', } default_plot_template = 'force / deflection (center)' n_fit_window_fraction = Float(0.1) # get only the ascending branch of the response curve # max_force_idx = Property(Int) def _get_max_force_idx(self): '''get the index of the maximum force''' return argmax(-self.Kraft) f_asc = Property(Array) def _get_f_asc(self): '''get only the ascending branch of the response curve''' return -self.Kraft[:self.max_force_idx + 1] w_asc = Property(Array) def _get_w_asc(self): '''get only the ascending branch of the response curve''' return -self.WA_M[:self.max_force_idx + 1] n_points = Property(Int) def _get_n_points(self): return int(self.n_fit_window_fraction * len(self.w_asc)) f_smooth = Property() def _get_f_smooth(self): return smooth(self.f_asc, self.n_points, 'flat') w_smooth = Property() def _get_w_smooth(self): return smooth(self.w_asc, self.n_points, 'flat') def _plot_force_deflection(self, axes, offset_w=0., color='blue', linewidth=1.5, linestyle='-'): '''plot the F-w-diagramm for all displacement gauges including maschine displacement ''' xkey = 'deflection [mm]' ykey = 'force [kN]' max_force_idx = self.max_force_idx # max_force_idx = -2 f_asc = -self.Kraft[:max_force_idx + 1] print 'self.factor_list', self.factor_list header_string = '' for i in self.factor_list[2:]: header_string = header_string + i + '; ' T_arr = -getattr(self, i) T_asc = T_arr[:max_force_idx + 1] axes.plot(T_asc, f_asc, label=i) axes.legend() img_dir = os.path.join(simdb.exdata_dir, 'img_dir') # check if directory exist otherwise create # if os.path.isdir(img_dir) == False: os.makedirs(img_dir) test_series_dir = os.path.join(img_dir, 'slab_test_astark') # check if directory exist otherwise create # if os.path.isdir(test_series_dir) == False: os.makedirs(test_series_dir) out_file = os.path.join(test_series_dir, self.key) np.savetxt(out_file, self.processed_data_array, delimiter=';') # workaround for old numpy.savetxt version: f = open(out_file, 'r') temp = f.read() f.close() f = open(out_file, 'w') f.write(header_string) f.write(temp) f.close() def _plot_force_center_deflection(self, axes, offset_w=0., color='blue', linewidth=1.5, linestyle='-'): '''plot the F-w-diagramm for the center (c) deflection ''' xkey = 'deflection [mm]' ykey = 'force [kN]' xdata = -self.WA_M ydata = -self.Kraft xdata += offset_w # axes.set_xlabel('%s' % (xkey,)) # axes.set_ylabel('%s' % (ykey,)) axes.plot(xdata, ydata, color=color, linewidth=linewidth, linestyle=linestyle) def _plot_force_corner_deflection(self, axes): '''plot the F-w-diagramm for the corner deflection (at the center of one of the supports) ''' xkey = 'deflection [mm]' ykey = 'force [kN]' xdata = -self.WA_Eck ydata = -self.Kraft # axes.set_xlabel('%s' % (xkey,)) # axes.set_ylabel('%s' % (ykey,)) axes.plot(xdata, ydata # color = c, linewidth = w, linestyle = s ) def _plot_force_center_deflection_smoothed(self, axes): '''plot the F-w-diagramm for the center (c) deflection (smoothed curves) ''' axes.plot(self.w_smooth, self.f_smooth, color='blue', linewidth=1) # secant_stiffness_w10 = (f_smooth[10] - f_smooth[0]) / (w_smooth[10] - w_smooth[0]) # w0_lin = array([0.0, w_smooth[10] ], dtype = 'float_') # f0_lin = array([0.0, w_smooth[10] * secant_stiffness_w10 ], dtype = 'float_') # axes.plot( w0_lin, f0_lin, color = 'black' ) def _plot_force_center_deflection_interpolated(self, axes, linestyle='-', linewidth=1.5, plot_elastic_stiffness=True): '''plot the F-w-diagramm for the center (c) deflection (interpolated initial stiffness) ''' # get the index of the maximum stress max_force_idx = argmax(-self.Kraft) # get only the ascending branch of the response curve f_asc = -self.Kraft[:max_force_idx + 1] w_m = -self.WA_M[:max_force_idx + 1] # w_m -= 0.17 # axes.plot(w_m, f_asc, color = 'blue', linewidth = 1) # move the starting point of the center deflection curve to the point where the force starts # (remove offset in measured displacement where there is still no force measured) # idx_0 = np.where(f_asc > 0.0)[0][0] f_asc_cut = np.hstack([f_asc[ idx_0: ]]) w_m_cut = np.hstack([w_m[ idx_0: ]]) - w_m[ idx_0 ] # print 'f_asc_cut.shape', f_asc_cut.shape # fw_arr = np.hstack([f_asc_cut[:, None], w_m_cut[:, None]]) # print 'fw_arr.shape', fw_arr.shape # np.savetxt('ST-6c-2cm-TU_bs2_f-w_asc.csv', fw_arr, delimiter=';') axes.plot(w_m_cut, f_asc_cut, color='k', linewidth=linewidth, linestyle=linestyle) # composite E-modulus # E_c = self.E_c print 'E_c', E_c if self.thickness == 0.02 and self.edge_length == 0.80 and plot_elastic_stiffness == True: K_linear = E_c / 24900. * 1.056 # [MN/m]=[kN/mm] bending stiffness with respect to center force max_f = f_asc_cut[-1] w_linear = np.array([0., max_f / K_linear]) f_linear = np.array([0., max_f]) axes.plot(w_linear, f_linear, linewidth=linewidth, linestyle='--', color='k') if self.thickness == 0.03 and self.edge_length == 1.25 and plot_elastic_stiffness == True: K_linear = E_c / 24900. * 1.267 # [MN/m]=[kN/mm] bending stiffness with respect to center force max_f = f_asc_cut[-1] w_linear = np.array([0., max_f / K_linear]) f_linear = np.array([0., max_f]) axes.plot(w_linear, f_linear, linewidth=linewidth, linestyle='--', color='k') if self.thickness == 0.06 and self.edge_length == 1.25 and plot_elastic_stiffness == True: K_linear = E_c / 24900. * 10.14 # [MN/m]=[kN/mm] bending stiffness with respect to center force max_f = f_asc_cut[-1] w_linear = np.array([0., max_f / K_linear]) f_linear = np.array([0., max_f]) axes.plot(w_linear, f_linear, linewidth=linewidth, linestyle='--', color='k') def _plot_force_edge_deflection(self, axes): '''plot the F-w-diagramm for the edge (e) deflections ''' max_force_idx = self.max_force_idx f_asc = self.f_asc w_v_asc = -self.WA_V[:max_force_idx + 1] w_h_asc = -self.WA_H[:max_force_idx + 1] w_l_asc = -self.WA_L[:max_force_idx + 1] w_r_asc = -self.WA_R[:max_force_idx + 1] axes.plot(w_v_asc, f_asc, color='blue', linewidth=1) axes.plot(w_h_asc, f_asc, color='blue', linewidth=1) axes.plot(w_l_asc, f_asc, color='green', linewidth=1) axes.plot(w_r_asc, f_asc, color='green', linewidth=1) def _plot_force_edge_deflection_avg(self, axes): '''plot the average F-w-diagramm for the edge (e) deflections ''' max_force_idx = self.max_force_idx f_asc = self.f_asc w_v_asc = -self.WA_V[:max_force_idx + 1] w_h_asc = -self.WA_H[:max_force_idx + 1] w_l_asc = -self.WA_L[:max_force_idx + 1] w_r_asc = -self.WA_R[:max_force_idx + 1] # get the average displacement values of the corresponding displacement gauges w_vh_asc = (w_v_asc + w_h_asc) / 2 w_lr_asc = (w_l_asc + w_r_asc) / 2 axes.plot(w_vh_asc, f_asc, color='blue', linewidth=1, label='w_vh') axes.plot(w_lr_asc, f_asc, color='blue', linewidth=1, label='w_lr') axes.legend() def _plot_edge_deflection_edge_deflection_avg(self, axes): '''plot the average edge (e) deflections for the front/back and left/right ''' max_force_idx = self.max_force_idx w_v_asc = -self.WA_V[:max_force_idx + 1] w_h_asc = -self.WA_H[:max_force_idx + 1] w_l_asc = -self.WA_L[:max_force_idx + 1] w_r_asc = -self.WA_R[:max_force_idx + 1] # get the average displacement values of the corresponding displacement gauges w_vh_asc = (w_v_asc + w_h_asc) / 2 w_lr_asc = (w_l_asc + w_r_asc) / 2 axes.plot(w_vh_asc, w_lr_asc, color='blue', linewidth=1, label='w_vh / w_lr') axes.plot(np.array([0, w_vh_asc[-1]]), np.array([0, w_vh_asc[-1]]), color='k', linewidth=1, linestyle='-') axes.legend() def _plot_force_center_edge_deflection(self, axes): '''plot the F-w-diagramm for the center-edge (ce) deflections ''' max_force_idx = argmax(-self.Kraft) # get only the ascending branch of the response curve f_asc = -self.Kraft[:max_force_idx + 1] w_ml_asc = -self.WA_ML[:max_force_idx + 1] w_mr_asc = -self.WA_MR[:max_force_idx + 1] axes.plot(w_ml_asc, f_asc, color='blue', linewidth=1, label='w_ml') axes.plot(w_mr_asc, f_asc, color='blue', linewidth=1, label='w_mr') axes.legend() def _plot_force_center_edge_deflection_avg(self, axes): '''plot the average F-w-diagramm for the center-edge (ce) deflections ''' # get the index of the maximum stress max_force_idx = argmax(-self.Kraft) # get only the ascending branch of the response curve f_asc = -self.Kraft[:max_force_idx + 1] w_ml_asc = -self.WA_ML[:max_force_idx + 1] w_mr_asc = -self.WA_MR[:max_force_idx + 1] # get the average displacement values of the corresponding displacement gauges w_mlmr_asc = (w_ml_asc + w_mr_asc) / 2 axes.plot(w_mlmr_asc, f_asc, color='blue', linewidth=1) def _plot_force_deflection_avg(self, axes): '''plot the average F-w-diagramms for the center(c), center-edge (ce) and edge(vh) and edge (lr) deflections ''' # get the index of the maximum stress max_force_idx = argmax(-self.Kraft) # get only the ascending branch of the response curve f_asc = -self.Kraft[:max_force_idx + 1] w_m = -self.WA_M[:max_force_idx + 1] axes.plot(w_m, f_asc, color='blue', linewidth=1) # ## center-edge deflection (ce) w_ml_asc = -self.WA_ML[:max_force_idx + 1] w_mr_asc = -self.WA_MR[:max_force_idx + 1] # get the average displacement values of the corresponding displacement gauges w_mlmr_asc = (w_ml_asc + w_mr_asc) / 2 axes.plot(w_mlmr_asc, f_asc, color='red', linewidth=1) # ## edge deflections (e) w_v_asc = -self.WA_V[:max_force_idx + 1] w_h_asc = -self.WA_H[:max_force_idx + 1] w_l_asc = -self.WA_L[:max_force_idx + 1] w_r_asc = -self.WA_R[:max_force_idx + 1] # get the average displacement values of the corresponding displacement gauges w_vh_asc = (w_v_asc + w_h_asc) / 2 w_lr_asc = (w_l_asc + w_r_asc) / 2 axes.plot(w_vh_asc, f_asc, color='green', linewidth=1, label='w_vh') axes.plot(w_lr_asc, f_asc, color='blue', linewidth=1, label='w_lr') # # set axis-labels # xkey = 'deflection [mm]' # ykey = 'force [kN]' # axes.set_xlabel('%s' % (xkey,)) # axes.set_ylabel('%s' % (ykey,)) def _plot_force_deflection_avg_interpolated(self, axes, linewidth=1): '''plot the average F-w-diagrams for the center(c), center-edge (ce) and edge(vh) and edge (lr) deflections NOTE: center deflection curve is cut at its starting point in order to remove offset in the dispacement meassurement ''' # get the index of the maximum stress max_force_idx = argmax(-self.Kraft) # get only the ascending branch of the response curve f_asc = -self.Kraft[:max_force_idx + 1] w_m = -self.WA_M[:max_force_idx + 1] # w_m -= 0.17 # axes.plot(w_m, f_asc, color = 'blue', linewidth = 1) # move the starting point of the center deflection curve to the point where the force starts # (remove offset in measured displacement where there is still no force measured) # idx_0 = np.where(f_asc > 0.05)[0][0] f_asc_cut = f_asc[ idx_0: ] w_m_cut = w_m[ idx_0: ] - w_m[ idx_0 ] axes.plot(w_m_cut, f_asc_cut, color='k', linewidth=linewidth) # plot machine displacement (hydraulic cylinder) # # Weg_asc = -self.Weg[ :max_force_idx + 1 ] # axes.plot(Weg_asc, f_asc, color='k', linewidth=1.5) # ## center-edge deflection (ce) w_ml_asc = -self.WA_ML[:max_force_idx + 1] w_mr_asc = -self.WA_MR[:max_force_idx + 1] # get the average displacement values of the corresponding displacement gauges w_mlmr_asc = (w_ml_asc + w_mr_asc) / 2 # axes.plot(w_mlmr_asc, f_asc, color='red', linewidth=1) axes.plot(w_ml_asc, f_asc, color='k', linewidth=linewidth) axes.plot(w_mr_asc, f_asc, color='k', linewidth=linewidth) # ## edge deflections (e) w_v_asc = -self.WA_V[:max_force_idx + 1] w_h_asc = -self.WA_H[:max_force_idx + 1] w_l_asc = -self.WA_L[:max_force_idx + 1] w_r_asc = -self.WA_R[:max_force_idx + 1] axes.plot(w_v_asc, f_asc, color='grey', linewidth=linewidth) axes.plot(w_h_asc, f_asc, color='grey', linewidth=linewidth) axes.plot(w_l_asc, f_asc, color='k', linewidth=linewidth) axes.plot(w_r_asc, f_asc, color='k', linewidth=linewidth) # get the average displacement values of the corresponding displacement gauges # w_vh_asc = (w_v_asc + w_h_asc) / 2 # w_lr_asc = (w_l_asc + w_r_asc) / 2 # axes.plot(w_vh_asc, f_asc, color='green', linewidth=1, label='w_vh') # axes.plot(w_lr_asc, f_asc, color='blue', linewidth=1, label='w_lr') # save 'F-w-arr_m-mlmr-vh-lr' in directory "/simdb/simdata/exp_st" # simdata_dir = os.path.join(simdb.simdata_dir, 'exp_st') # if os.path.isdir(simdata_dir) == False: # os.makedirs(simdata_dir) # filename = os.path.join(simdata_dir, 'F-w-arr_m-mlmr-vh-lr_' + self.key + '.csv') # Fw_m_mlmr_vh_lr_arr = np.hstack([f_asc[:, None], w_m[:, None] - w_m[ idx_0 ], w_mlmr_asc[:, None], w_vh_asc[:, None], w_lr_asc[:, None]]) # print 'Fw_m_mlmr_vh_lr_arr' # np.savetxt(filename, Fw_m_mlmr_vh_lr_arr, delimiter=';') # print 'F-w-curves for center, middle, edges saved to file %s' % (filename) #-------------------------------------------------------------------------------- # view #-------------------------------------------------------------------------------- traits_view = View(VGroup( Group( Item('jump_rtol', format_str="%.4f"), label='curve_ironing' ), Group( Item('thickness', format_str="%.3f"), Item('edge_length', format_str="%.3f"), label='geometry' ), Group( Item('loading_rate'), Item('age'), label='loading rate and age' ), Group( Item('E_c', show_label=True, style='readonly', format_str="%.0f"), Item('ccs@', show_label=False), label='composite cross section' ) ), scrollable=True, resizable=True, height=0.8, width=0.6 )
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 ECBCrossSection(ECBCrossSectionState): '''Cross section characteristics needed for tensile specimens ''' matrix_cs = Instance(ECBMatrixCrossSection) def _matrix_cs_default(self): return ECBMatrixCrossSection() reinf = List(ECBReinfComponent) '''Components of the cross section including the matrix and reinforcement. ''' matrix_cs_with_state = Property(depends_on='matrix_cs') @cached_property def _get_matrix_cs_with_state(self): self.matrix_cs.state = self return self.matrix_cs reinf_components_with_state = Property(depends_on='reinf') '''Components linked to the strain state of the cross section ''' @cached_property def _get_reinf_components_with_state(self): for r in self.reinf: r.state = self r.matrix_cs = self.matrix_cs return self.reinf height = DelegatesTo('matrix_cs') unit_conversion_factor = Constant(1000.0) '''Convert the MN to kN ''' #=========================================================================== # State management #=========================================================================== changed = Event '''Notifier of a changed in some component of a cross section ''' @on_trait_change('+eps_input') def _notify_eps_change(self): self.changed = True self.matrix_cs.eps_changed = True for c in self.reinf: c.eps_changed = True #=========================================================================== # Cross-sectional stress resultants #=========================================================================== N = Property(depends_on='changed') '''Get the resulting normal force. ''' @cached_property def _get_N(self): N_matrix = self.matrix_cs_with_state.N return N_matrix + np.sum([c.N for c in self.reinf_components_with_state]) M = Property(depends_on='changed') '''Get the resulting moment. ''' @cached_property def _get_M(self): M_matrix = self.matrix_cs_with_state.M M = M_matrix + np.sum([c.M for c in self.reinf_components_with_state]) return M - self.N * self.height / 2. 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 replot = Button def _replot_fired(self): self.figure.clear() ax = self.figure.add_subplot(2, 2, 1) self.plot_eps(ax) ax = self.figure.add_subplot(2, 2, 2) self.plot_sig(ax) ax = self.figure.add_subplot(2, 2, 3) self.cc_law.plot(ax) ax = self.figure.add_subplot(2, 2, 4) self.ecb_law.plot(ax) self.data_changed = True def plot_eps(self, ax): # ax = self.figure.gca() d = self.thickness # eps ti ax.plot([-self.eps_lo, -self.eps_up], [0, self.thickness], color='black') ax.hlines(self.zz_ti_arr, [0], -self.eps_ti_arr, lw=4, color='red') # eps cj ec = np.hstack([self.eps_cj_arr] + [0, 0]) zz = np.hstack([self.zz_cj_arr] + [0, self.thickness ]) ax.fill(-ec, zz, color='blue') # reinforcement layers eps_range = np.array([max(0.0, self.eps_lo), min(0.0, self.eps_up)], dtype='float') z_ti_arr = np.ones_like(eps_range)[:, None] * self.z_ti_arr[None, :] ax.plot(-eps_range, z_ti_arr, 'k--', color='black') # neutral axis ax.plot(-eps_range, [d, d], 'k--', color='green', lw=2) 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') def plot_sig(self, ax): d = self.thickness # f ti ax.hlines(self.zz_ti_arr, [0], -self.f_ti_arr, lw=4, color='red') # f cj f_c = np.hstack([self.f_cj_arr] + [0, 0]) zz = np.hstack([self.zz_cj_arr] + [0, self.thickness ]) ax.fill(-f_c, zz, color='blue') f_range = np.array([np.max(self.f_ti_arr), np.min(f_c)], dtype='float_') # neutral axis ax.plot(-f_range, [d, d], 'k--', color='green', lw=2) 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') view = View(HSplit(Group( HGroup( Group(Item('thickness', springy=True), Item('width'), Item('n_layers'), Item('n_rovings'), Item('A_roving'), label='Geometry', springy=True ), Group(Item('eps_up', label='Upper strain', springy=True), Item('eps_lo', label='Lower strain'), label='Strain', springy=True ), springy=True, ), HGroup( Group(VGroup( Item('cc_law_type', show_label=False, springy=True), Item('cc_law', label='Edit', show_label=False, springy=True), Item('show_cc_law', label='Show', show_label=False, springy=True), springy=True ), Item('f_ck', label='Compressive strength'), Item('n_cj', label='Discretization'), label='Concrete', springy=True ), Group(VGroup( Item('ecb_law_type', show_label=False, springy=True), Item('ecb_law', label='Edit', show_label=False, springy=True), Item('show_ecb_law', label='Show', show_label=False, springy=True), springy=True, ), label='Reinforcement', springy=True ), springy=True, ), Group(Item('s_tex_z', label='vertical spacing', style='readonly'), label='Layout', ), Group( HGroup(Item('M', springy=True, style='readonly'), Item('N', springy=True, style='readonly'), ), label='Stress resultants' ), scrollable=True, ), Group(Item('replot', 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, resizable=True, buttons=['OK', 'Cancel'])
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)