示例#1
0
文件: rf_view.py 项目: simvisage/bmcs
    def default_traits_view(self):
        '''
        Generates the view from the param items.
        '''
        #rf_param_items = [ Item( 'model.' + name, format_str = '%g' ) for name in self.model.param_keys ]
        D2_plot_param_items = [
            VGroup(Item('max_x', label='max x value'),
                   Item('x_points', label='No of plot points'))
        ]

        if hasattr(self.rf, 'get_q_x'):
            D3_plot_param_items = [
                VGroup(Item('min_x', label='min x value'),
                       Item('max_x', label='max x value'),
                       Item('min_y', label='min y value'),
                       Item('max_y', label='max y value'))
            ]
        else:
            D3_plot_param_items = []

        control_items = [
            Item('show', show_label=False),
            Item('clear', show_label=False),
        ]
        view = View(
            HSplit(
                VGroup(Item('@rf', show_label=False),
                       label='Function parameters',
                       id='stats.spirrid_bak.rf_model_view.rf_params',
                       scrollable=True),
                VGroup(HGroup(*D2_plot_param_items),
                       label='plot parameters',
                       id='stats.spirrid_bak.rf_model_view.2Dplot_params'),
                #                            VGroup( HGroup( *D3_plot_param_items ),
                #                                     label = '3D plot parameters',
                #                                     id = 'stats.spirrid_bak.rf_model_view.3Dplot_params' ),
                VGroup(
                    Item('model.comment', show_label=False, style='readonly'),
                    label='Comment',
                    id='stats.spirrid_bak.rf_model_view.comment',
                    scrollable=True,
                ),
                VGroup(HGroup(*control_items),
                       Item('figure',
                            editor=MPLFigureEditor(),
                            resizable=True,
                            show_label=False),
                       label='Plot',
                       id='stats.spirrid_bak.rf_model_view.plot'),
                dock='tab',
                id='stats.spirrid_bak.rf_model_view.split'),
            kind='modal',
            resizable=True,
            dock='tab',
            buttons=[OKButton],
            id='stats.spirrid_bak.rf_model_view')
        return view
示例#2
0
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)
示例#3
0
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'])
示例#4
0
 def default_traits_view(self):
     '''
     Generates the view from the param items.
     '''
     rf_param_items = [
         Item('model.' + name, format_str='%g')
         for name in self.model.param_keys
     ]
     plot_param_items = [
         Item('eps_max'),
         Item('n_eps'),
         Item('x_name', label='x-axis'),
         Item('y_name', label='y-axis')
     ]
     control_items = [
         Item('show', show_label=False),
         Item('clear', show_label=False),
     ]
     view = View(HSplit(
         VGroup(*rf_param_items,
                label='Function Parameters',
                id='stats.spirrid_bak.rf_model_view.rf_params',
                scrollable=True),
         VGroup(*plot_param_items,
                label='Plot Parameters',
                id='stats.spirrid_bak.rf_model_view.plot_params'),
         VGroup(
             Item('model.comment', show_label=False, style='readonly'),
             label='Comment',
             id='stats.spirrid_bak.rf_model_view.comment',
             scrollable=True,
         ),
         VGroup(HGroup(*control_items),
                Item('figure',
                     editor=MPLFigureEditor(),
                     resizable=True,
                     show_label=False),
                label='Plot',
                id='stats.spirrid_bak.rf_model_view.plot'),
         dock='tab',
         id='stats.spirrid_bak.rf_model_view.split'),
                 kind='modal',
                 resizable=True,
                 dock='tab',
                 buttons=['Ok', 'Cancel'],
                 id='stats.spirrid_bak.rf_model_view')
     return view
示例#5
0
class SimCrackLoc( IBVModel ):
    '''Model assembling the components for studying the restrained crack localization.
    '''
    shape = Int( 1, desc = 'Number of finite elements',
                   ps_levsls = ( 10, 40, 4 ) )
    length = Float( 1, desc = 'Length of the simulated region' )

    #-------------------------------------------------------
    # Material model for the matrix
    #-------------------------------------------------------
    mats_m = Instance( MATS1DCrackLoc )
    def _mats_m_default( self ):
        E_m = 1
        mats_m = MATS1DCrackLoc( E = E_m,
                                 R = 0.5,
                                 epsilon_0 = 0.001,
                                 epsilon_f = 0.01 )
        return mats_m

    mats_f = Instance( MATS1DElastic )
    def _mats_f_default( self ):
        E_f = 0
        mats_f = MATS1DElastic( E = E_f )
        return mats_f

    mats_b = Instance( MATS1DElastic )
    def _mats_b_default( self ):
        E_b = 0
        mats_b = MATS1DElastic( E = E_b )
        return mats_b

    mats = Instance( MATS1D5Bond )
    def _mats_default( self ):

        # Material model construction
        mats = MATS1D5Bond( mats_phase1 = self.mats_m,
                            mats_phase2 = self.mats_f,
                            mats_ifslip = self.mats_b,
                            mats_ifopen = MATS1DElastic( E = 0 )   # elastic function of open - inactive
                            )
        return mats
    #-------------------------------------------------------
    # Finite element type
    #-------------------------------------------------------
    fets = Instance( FETSEval )
    def _fets_default( self ):
        #return FETS1D52L8ULRH( mats_eval = self.mats )        
        return FETS1D52L4ULRH( mats_eval = self.mats )
        #return FETS1D2L3U( mats_eval = self.mats ) 

    run = Button

    @on_trait_change( 'run' )
    def peval( self ):
        '''Evaluation procedure.
        '''
        #mv = MATS1DDamageView( model = mats_eval )
        #mv.configure_traits()

        self.mats_m.reset_state()
        # Discretization
        #
        length = self.length
        domain = FEGrid( coord_min = ( 0., length / 5. ),
                          coord_max = ( length, 0. ),
                          shape = ( self.shape, 1 ),
                          fets_eval = self.fets )

        right_dofs = domain[-1, -1, -1, :].dofs[0, :, 0]
        print 'concrete_dofs', id( domain ), domain[:, 0, :, 0].dofs
        # Response tracers
        self.stress_strain = RTraceGraph( name = 'Fi,right over u_right (iteration)' ,
                                   var_y = 'F_int', idx_y = right_dofs[0],
                                   var_x = 'U_k', idx_x = right_dofs[0] )
        self.eps_m_field = RTraceDomainListField( name = 'eps_m' , position = 'int_pnts',
                                           var = 'eps1', idx = 0,
                                           warp = True )

        self.eps_f_field = RTraceDomainListField( name = 'eps_f' , position = 'int_pnts',
                                           var = 'eps2', idx = 0,
                                           warp = True )

        # Response tracers
        self.sig_m_field = RTraceDomainListField( name = 'sig_m' , position = 'int_pnts',
                                              var = 'mats_phase1_sig_app', idx = 0 )
        self.sig_f_field = RTraceDomainListField( name = 'sig_f' , position = 'int_pnts',
                                              var = 'mats_phase2_sig_app', idx = 0 )
        self.omega_m_field = RTraceDomainListField( name = 'omega_m' , position = 'int_pnts',
                                           var = 'mats_phase1_omega', idx = 0,
                                           warp = True )
        # 

        damage_onset_displ = self.mats_m.epsilon_0 * self.length
        go_behind = 1.5
        finish_displ = go_behind * damage_onset_displ
        n_steps = 20
        step_size = ( finish_displ - damage_onset_displ ) / n_steps
        tmax = 1 + n_steps

        def ls( t ):
            if t <= 1:
                return t
            else:
                return 1.0 + ( t - 1.0 ) / n_steps * ( go_behind - 1 )

        ts = TSCrackLoc( 
                 dof_resultants = True,
                 on_update = self.plot,
                 sdomain = domain,
                 bcond_list = [# define the left clamping 
                                BCSlice( var = 'u', value = 0., dims = [0], slice = domain[ 0, 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 = finish_displ, dims = [0], slice = domain[-1,-1,-1, 0],
#                                         time_function = ls ),
                                # 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 = domain[ :, :, :, :] )
                                ],
                 rtrace_list = [ self.stress_strain,
                                  self.eps_m_field,
                                  self.eps_f_field,
                                  self.sig_m_field,
                                  self.sig_f_field,
                                  self.omega_m_field ]
                )

        # Add the time-loop control
        tloop = TLoop( tstepper = ts, KMAX = 200, debug = True, tolerance = 1e-5,
                       tline = TLine( min = 0.0, step = 1.0, max = 1.0 ) )

        print ts.rte_dict.keys()
        U = tloop.eval()

        self.plot()

        return array( [ U[right_dofs[-1]] ], dtype = 'float_' )

    #---------------------------------------------------------------
    # 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_omega = Instance( Figure )
    def _figure_omega_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

    def plot( self ):
        self.stress_strain.refresh()
        t = self.stress_strain.trace
        ax = self.figure_ld.axes[0]
        ax.clear()
        ax.plot( t.xdata, t.ydata, linewidth = 2, color = 'blue' )

        ax = self.figure_eps.axes[0]
        ax.clear()

        ef = self.eps_m_field.subfields[0]
        xdata = ef.vtk_X[:, 0]
        ydata = ef.field_arr[:, 0]
        idata = argsort( xdata )
        ax.plot( xdata[idata], ydata[idata], linewidth = 2, color = 'grey' )

        ef = self.eps_f_field.subfields[0]
        xdata = ef.vtk_X[:, 0]
        ydata = ef.field_arr[:, 0]
        idata = argsort( xdata )
        ax.plot( xdata[idata], ydata[idata], linewidth = 2, color = 'red' )
        ax.legend( ['eps_m', 'eps_f'] )

        ax = self.figure_sig.axes[0]
        ax.clear()

        ef = self.sig_m_field.subfields[0]
        xdata = ef.vtk_X[:, 0]
        ydata = ef.field_arr[:, 0]
        idata = argsort( xdata )
        ax.plot( xdata[idata], ydata[idata], linewidth = 2, color = 'grey' )

        ef = self.sig_f_field.subfields[0]
        xdata = ef.vtk_X[:, 0]
        ydata = ef.field_arr[:, 0]
        idata = argsort( xdata )
        ax.plot( xdata[idata], ydata[idata], linewidth = 2, color = 'red' )
        ax.legend( ['sig_m', 'sig_f'] )


        ax = self.figure_omega.axes[0]
        ax.clear()

        ef = self.omega_m_field.subfields[0]
        xdata = ef.vtk_X[:, 0]
        ydata = ef.field_arr[:, 0]
        idata = argsort( xdata )
        ax.plot( xdata[idata], ydata[idata], linewidth = 2, color = 'brown' )
        ax.legend( ['omega_m'] )


        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' ) ]

    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_sjteps' ),
                                 Item( 'length' ),
                                 label = 'parameters',
                                 id = 'crackloc.viewmodel.factor.geometry',
                                 dock = 'tab',
                                 scrollable = True,
                                 ),
                            VGroup( 
                                 Item( 'mats_m@', show_label = False ),
                                 label = 'Matrix',
                                 dock = 'tab',
                                 id = 'crackloc.viewmodel.factor.matrix',
                                 scrollable = True
                                 ),
                            VGroup( 
                                 Item( 'mats_f@', show_label = False ),
                                 label = 'Fiber',
                                 dock = 'tab',
                                 id = 'crackloc.viewmodel.factor.fiber',
                                 scrollable = True
                                 ),
                            VGroup( 
                                 Item( 'mats_b@', show_label = False ),
                                 label = 'Bond',
                                 dock = 'tab',
                                 id = 'crackloc.viewmodel.factor.bond',
                                 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_omega', editor = MPLFigureEditor(),
                                             resizable = True, show_label = False ),
                                             label = 'omega profile',
                                            id = 'crackloc.viewmode.figure_omega_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] )
示例#6
0
class SPIRRIDModelView(ModelView):

    title = Str('spirrid exec ctrl')

    model = Instance(SPIRRID)

    ins = Instance(NoOfFibers)

    def _ins_default(self):
        return NoOfFibers()

    eval = Button

    def _eval_fired(self):

        Specimen_Volume = self.ins.Lx * self.ins.Ly * self.ins.Lz
        self.no_of_fibers_in_specimen = (
            Specimen_Volume * self.ins.Fiber_volume_fraction / 100) / (
                pi *
                (self.ins.Fiber_diameter / 20)**2 * self.ins.Fiber_Length / 10)
        prob_crackbridging_fiber = (self.ins.Fiber_Length /
                                    (10 * 2)) / self.ins.Lx
        self.mean_parallel_links = prob_crackbridging_fiber * self.no_of_fibers_in_specimen
        self.stdev_parallel_links = (prob_crackbridging_fiber *
                                     self.no_of_fibers_in_specimen *
                                     (1 - prob_crackbridging_fiber))**0.5

    run = Button(desc='Run the computation')

    def _run_fired(self):
        self.evaluate()

    run_legend = Str('mean response',
                     desc='Legend to be added to the plot of the results')

    min_eps = Float(0.0, desc='minimum value of the control variable')

    max_eps = Float(1.0, desc='maximum value of the control variable')

    n_eps = Int(100, desc='resolution of the control variable')

    plot_title = Str('response', desc='diagram title')

    label_x = Str('epsilon', desc='label of the horizontal axis')

    label_y = Str('sigma', desc='label of the vertical axis')

    stdev = Bool(True)

    mean_parallel_links = Float(1.,
                                desc='mean number of parallel links (fibers)')
    stdev_parallel_links = Float(
        0., desc='stdev of number of parallel links (fibers)')
    no_of_fibers_in_specimen = Float(
        0.,
        desc='Number of Fibers in the specimen',
    )

    data_changed = Event(True)

    def evaluate(self):
        self.model.set(
            min_eps=0.00,
            max_eps=self.max_eps,
            n_eps=self.n_eps,
        )

        # evaluate the mean curve
        self.model.mean_curve

        # evaluate the variance if the stdev bool is True
        if self.stdev:
            self.model.var_curve
        self.data_changed = True

    traits_view = View(VGroup(
        HGroup(
            Item('run_legend',
                 resizable=False,
                 label='Run label',
                 width=80,
                 springy=False), Item('run', show_label=False,
                                      resizable=False)),
        Tabbed(
            VGroup(
                Item('model.cached_dG',
                     label='Cached weight factors',
                     resizable=False,
                     springy=False),
                Item('model.compiled_QdG_loop',
                     label='Compiled loop over the integration product',
                     springy=False),
                Item('model.compiled_eps_loop',
                     enabled_when='model.compiled_QdG_loop',
                     label='Compiled loop over the control variable',
                     springy=False),
                scrollable=True,
                label='Execution configuration',
                id='spirrid.tview.exec_params',
                dock='tab',
            ),
            VGroup(
                HGroup(Item('min_eps',
                            label='Min',
                            springy=False,
                            resizable=False),
                       Item('max_eps',
                            label='Max',
                            springy=False,
                            resizable=False),
                       Item('n_eps', label='N', springy=False,
                            resizable=False),
                       label='Simulation range',
                       show_border=True),
                HGroup(Item('stdev', label='plot standard deviation'), ),
                HSplit(
                    HGroup(
                        VGroup(
                            Item('mean_parallel_links',
                                 label='mean No of fibers'),
                            Item('stdev_parallel_links',
                                 label='stdev No of fibers'),
                        )),
                    VGroup(
                        Item('@ins',
                             label='evaluate No of fibers',
                             show_label=False),
                        VGroup(
                            HGroup(
                                Item('eval',
                                     show_label=False,
                                     resizable=False,
                                     label='Evaluate No of Fibers'),
                                Item('no_of_fibers_in_specimen',
                                     label='No of Fibers in specimen',
                                     style='readonly')))),
                    label='number of parralel fibers',
                    show_border=True,
                    scrollable=True,
                ),
                VGroup(
                    Item('plot_title',
                         label='title',
                         resizable=False,
                         springy=False),
                    Item('label_x', label='x', resizable=False, springy=False),
                    Item('label_y', label='y', resizable=False, springy=False),
                    label='title and axes labels',
                    show_border=True,
                    scrollable=True,
                ),
                label='Execution control',
                id='spirrid.tview.view_params',
                dock='tab',
            ),
            scrollable=True,
            id='spirrid.tview.tabs',
            dock='tab',
        ),
    ),
                       title='SPIRRID',
                       id='spirrid.viewmodel',
                       dock='tab',
                       resizable=True,
                       height=1.0,
                       width=1.0)
示例#7
0
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)
示例#8
0
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])
示例#9
0
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'])
示例#10
0
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'])
示例#11
0
class DoublePulloutSym(RF):

    implements(IRF)

    title = Str('symetrical yarn pullout')

    xi = Float(0.0179,
               auto_set=False,
               enter_set=True,
               input=True,
               distr=['weibull_min', 'uniform'])

    tau_fr = Float(2.5,
                   auto_set=False,
                   enter_set=True,
                   input=True,
                   distr=['uniform', 'norm'])
    # free length
    l = Float(0.0,
              auto_set=False,
              enter_set=True,
              input=True,
              distr=['uniform'])

    d = Float(26e-3,
              auto_set=False,
              input=True,
              enter_set=True,
              distr=['uniform', 'weibull_min'])

    E_mod = Float(72.0e3,
                  auto_set=False,
                  enter_set=True,
                  input=True,
                  distr=['uniform'])
    # slack
    theta = Float(0.01,
                  auto_set=False,
                  enter_set=True,
                  input=True,
                  distr=['uniform', 'norm'])

    phi = Float(1.,
                auto_set=False,
                enter_set=True,
                input=True,
                distr=['uniform', 'norm'])

    # embedded length
    L = Float(1.,
              auto_set=False,
              enter_set=True,
              input=True,
              distr=['uniform'])

    free_fiber_end = Bool(True, input=True)

    w = Float(enter_set=True, input=True, ctrl_range=(0, 1, 10))

    weave_code = '''
        '''

    def __call__(self, w, tau_fr, l, d, E_mod, theta, xi, phi, L):
        '''Return the force for a prescribed crack opening displacement w.
        '''
        A = pi * d**2 / 4.
        l = l * (1 + theta)
        w = w - theta * l
        Tau = tau_fr * phi * d * pi
        P_ = 0.5 * (-l * Tau +
                    sqrt(l**2 * Tau**2 + 4 * w * H(w) * E_mod * A * Tau))
        # one sided pullout P_ = ( -l * Tau + sqrt( l ** 2 * Tau ** 2 + 2 * w * H( w ) * E_mod * A * Tau ) )

        if self.free_fiber_end:
            # ------ FREE LENGTH -------

            # frictional force along the bond length
            P_fr = Tau * (L - l)

            # if pullout_criterion positive - embedded
            # otherwise pulled out
            #
            pull_out_criterion = P_fr - P_
            P_ = P_ * H(pull_out_criterion) + P_fr * H(-pull_out_criterion)
        else:
            # --------------------------
            # ------ clamped fiber end ---------
            v = L * (l * Tau + Tau * L) / E_mod / A
            P_ = P_ * H(Tau * L - P_) + (Tau * L + (w - v) /
                                         (l + 2 * L) * A * E_mod) * H(P_ -
                                                                      Tau * L)
            # ----------------------------------
        P = P_ * H(A * E_mod * xi - P_)
        return P

    figure = Instance(Figure)

    def _figure_default(self):
        figure = Figure(facecolor='white')
        return figure

    changed = Event

    @on_trait_change('+input')
    def _set_changed(self):
        self.changed = True

    data_changed = Event

    @on_trait_change('+input')
    def refresh(self):
        figure = self.figure
        figure.clear()
        axes = figure.gca()

        P_fn = lambda w: self.__call__(w, self.tau_fr, self.l, self.d, self.
                                       E_mod, self.theta, self.xi, self.phi,
                                       self.L)
        pyF = frompyfunc(P_fn, 1, 1)

        w_arr = linspace(0.0, 1.0, 100)
        P_arr = array(pyF(w_arr), dtype='float_')

        axes.plot(w_arr, P_arr, lw=1.0, color='blue')

        self.data_changed = True

    group_attribs = VGroup(
        Item('tau_fr'),
        Item('l'),
        Item('d'),
        Item('E_mod'),
        Item('theta'),
        Item('xi'),
        Item('phi'),
        Item('L'),
        Item('free_fiber_end'),
    ),

    traits_view = View(
        group_attribs,
        scrollable=True,
        resizable=True,
        id='mk.figure.attribs',
        dock='tab',
    )

    traits_view_diag = View(HSplit(
        group_attribs,
        VGroup(Item('figure',
                    editor=MPLFigureEditor(),
                    show_label=False,
                    resizable=True),
               id='mk.figure.view'),
    ),
                            id='mk.view',
                            buttons=['OK', 'Cancel'],
                            resizable=True,
                            width=600,
                            height=400)
示例#12
0
class MKYarnPDistrib(HasTraits):

    implements(IPDistrib)

    n_int = Int(50, auto_set=False, enter_set=True, input=True)
    p_s = Float(0.0, auto_set=False, enter_set=True, input=True)
    p_c = Float(0.0, auto_set=False, enter_set=True, input=True)
    k_s = Float(0.0, auto_set=False, enter_set=True, input=True)
    k_c = Float(0.0, auto_set=False, enter_set=True, input=True)

    x_array = Property(depends_on='+input')

    @cached_property
    def _get_x_array(self):
        a = min(self.p_s, self.p_c)
        b = max(self.p_s, self.p_c)
        return linspace(a, b, self.n_int)

    polynom = Property(depends_on='+input')

    @cached_property
    def _get_polynom(self):
        p_c = self.p_c
        p_s = self.p_s
        k_s = self.k_s
        k_c = self.k_c
        a = min(self.p_s, self.p_c)
        b = max(self.p_s, self.p_c)
        xi = linspace(-0.2, 1.2, 1000)
        x = (p_c - p_s) * ((k_s + k_c - 2) * xi**3 +
                           (3 - 2 * k_s - k_c) * xi**2 + k_s * xi) + p_s
        x = sort(x)
        xi = sort(xi)
        return MFnLineArray(xdata=x, ydata=xi)

    cdf_array = Property(depends_on='+input')

    @cached_property
    def _get_cdf_array(self):
        line = self.polynom
        X = self.x_array
        pyCDF = frompyfunc(line.get_value, 1, 1)
        return array(pyCDF(X), dtype='float_')

    pdf_array = Property(depends_on='+input')

    @cached_property
    def _get_pdf_array(self):
        line = self.polynom
        X = self.x_array
        pyf = frompyfunc(line.get_diff, 1, 1)
        PDF = array(pyf(X), dtype='float_')
        return PDF

    dx = Property()

    def _get_dx(self):
        return abs(self.p_c - self.p_s) / (self.n_int - 1)

    def get_pdf_array(self, x_array):
        line = self.polynom
        X = x_array
        pyf = frompyfunc(line.get_diff, 1, 1)
        PDF = array(pyf(X), dtype='float_')
        return PDF

    def integ(self):
        return trapz(self.pdf_array, x=self.x_array)

    data_mean = Property(Float, depends_on='+input')

    @cached_property
    def _get_data_mean(self):
        X = self.x_array
        x = linspace(X[0], X[-1], 300)
        PDF = self.get_pdf_array(x)
        data_mean = trapz(x * PDF, x=x)
        return data_mean

    data_stdev = Property(Float, depends_on='+input')

    @cached_property
    def _get_data_stdev(self):
        X = self.x_array
        x = linspace(X[0], X[-1], 300)
        PDF = self.get_pdf_array(x)
        data_stdev = sqrt(trapz(x**2 * PDF, x=x) - self.data_mean**2)
        return data_stdev

    figure = Instance(Figure)

    def _figure_default(self):
        figure = Figure(facecolor='white')
        return figure

    data_changed = Event

    @on_trait_change('+input')
    def refresh(self):
        figure = self.figure
        figure.clear()
        axes = figure.gca()
        # plot PDF and CDF
        X = self.x_array
        x = linspace(X[0], X[-1], 300)
        PDF = self.get_pdf_array(x)
        line = self.polynom
        pyCDF = frompyfunc(line.get_value, 1, 1)
        CDF = pyCDF(x)
        axes.plot(x, PDF, lw=1.0, color='blue', \
                  label='PDF')
        axes2 = axes.twinx()
        # plot CDF on a separate axis (tick labels left)
        axes2.plot(x, CDF, lw=2, color='red', \
                  label='CDF')
        # fill the unity area given by integrating PDF along the X-axis
        axes.fill_between(x, 0, PDF, color='lightblue', alpha=0.8, linewidth=2)

        # plot mean
        mean = self.data_mean
        axes.plot([mean, mean], [0.0, self.get_pdf_array(mean)],
                  lw=1.5,
                  color='black',
                  linestyle='-')

        # plot stdev
        stdev = self.data_stdev
        axes.plot([mean - stdev, mean - stdev],
                  [0.0, self.get_pdf_array(mean - stdev)],
                  lw=1.5,
                  color='black',
                  linestyle='--')
        axes.plot([mean + stdev, mean + stdev],
                  [0.0, self.get_pdf_array(mean + stdev)],
                  lw=1.5,
                  color='black',
                  linestyle='--')

        axes.legend(loc='upper center')
        axes2.legend(loc='upper 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(PDF) * 1.15)
        axes2.set_ylim(0.0, 1.15)
        axes.set_xlim(X[0], X[-1])
        axes2.set_xlim(X[0], X[-1])

        self.data_changed = True

    traits_view = View(HSplit(
        VGroup(Item('p_c'), Item('p_s'), Item('k_c'), Item('k_s'),
               Item('data_mean', label='mean', style='readonly'),
               Item('data_stdev', label='stdev', style='readonly')),
        VGroup(Item('figure',
                    editor=MPLFigureEditor(),
                    show_label=False,
                    resizable=True),
               id='mk.figure.view'),
    ),
                       id='mk.view',
                       buttons=[OKButton, CancelButton],
                       resizable=True,
                       width=600,
                       height=400)
示例#13
0
class MKPullOut(HasTraits):

    rf = Instance(DoublePulloutSym)

    def _rf_default(self):
        return DoublePulloutSym(tau_fr=3.14,
                                l=0.0,
                                d=25.5e-3,
                                E_mod=70.0e3,
                                theta=0.0,
                                xi=0.0179,
                                phi=1.,
                                L=30.0)

    #--------------------------------------------------------------------------------
    # select the concrete mixture from the concrete database:
    #--------------------------------------------------------------------------------

    param_distribs_key = Enum(MKPullOutParamDistribs.db.keys(),
                              simdb=True,
                              input=True,
                              auto_set=False,
                              enter_set=True)

    param_distribs_ref = Property(Instance(SimDBClass),
                                  depends_on='param_distribs_key')

    @cached_property
    def _get_param_distribs_ref(self):
        return MKPullOutParamDistribs.db[self.param_distribs_key]

    po = Property(Instance(YarnPullOut), depends_on='param_distribs_key')

    @cached_property
    def _get_po(self):
        pd = self.param_distribs_ref
        return YarnPullOut(rf=self.rf,
                           pdf_phi=pd.phi,
                           pdf_phi_on=True,
                           pdf_theta=pd.theta,
                           pdf_theta_on=True,
                           pdf_l=pd.ell,
                           pdf_ell_on=True,
                           n_f=1743,
                           w_max=1.2)

    #--------------------------------------------------------------------------------
    # view
    #--------------------------------------------------------------------------------

    traits_view = View(
        VSplit(
            VGroup(
                Spring(),
                Item('param_distribs_key', label='parameters'),
                Spring(),
                Item('param_distribs_ref@', show_label=False),
                Spring(),
                id='mkpo.split.pd',
                label='parameter distributions',
                dock='tab',
            ),
            HSplit(
                Item('po@', show_label=False),
                label='Pull Out',
                id='mkpo.split.pu',
                scrollable=True,
                dock='tab',
            ),
            dock='tab',
            id='mkpo.split',
            orientation='vertical',
        ),
        dock='tab',
        id='mkpo',
        scrollable=True,
        resizable=True,
        height=0.4,
        width=0.5,
        buttons=['OK', 'Cancel'],
    )
示例#14
0
class ECBLCalibHistModelView(ModelView):
    '''Model in a viewable window.
    '''
    model = Instance(ECBLCalibHist)

    def _model_default(self):
        return ECBLCalibHist()

    cs_states = Property(List(Instance(ECBCrossSectionState)),
                         depends_on='model')

    @cached_property
    def _get_cs_states(self):
        return self.model.cs_states

    current_cs_state = Instance(ECBCrossSectionState)

    def _current_cs_default(self):
        self.model.cs_states[0]

    def _current_cs_state_changed(self):
        self._replot_fired()

    eps_range = Property

    def _get_eps_range(self):
        eps_arr = [[cs_state.eps_up, cs_state.eps_lo]
                   for cs_state in self.cs_states]
        eps_range = np.asarray(eps_arr)
        print 'eps_range', eps_range
        return (-np.max(eps_range[:, 1]), -np.min(eps_range[:, 0]))

    f_range = Property

    def _get_f_range(self):
        f_arr = [[np.max(cs_state.f_ti_arr),
                  np.min(cs_state.f_cj_arr)] for cs_state in self.cs_states]
        f_range = np.asarray(f_arr)
        print 'eps_range', f_range
        return (-np.max(f_range[:, 0]), -np.min(f_range[:, 1]))

    data_changed = Event

    figure = Instance(Figure)

    def _figure_default(self):
        figure = Figure(facecolor='white')
        return figure

    replot = Button()

    def _replot_fired(self):
        if self.current_cs_state:
            cs = self.current_cs_state
        else:
            cs = self.cs_states[0]
        cs.plot(self.figure, eps_range=self.eps_range, f_range=self.f_range)
        self.data_changed = True

    clear = Button()

    def _clear_fired(self):
        self.figure.clear()
        self.data_changed = True

    view = View(HSplit(
        VGroup(
            Item('cs_states',
                 editor=cs_states_editor,
                 label='Cross section',
                 show_label=False),
            Item('model@', show_label=False),
        ),
        Group(
            HGroup(
                Item('replot', show_label=False),
                Item('clear', show_label=False),
            ),
            Item('figure',
                 editor=MPLFigureEditor(),
                 resizable=True,
                 show_label=False),
            id='simexdb.plot_sheet',
            label='plot sheet',
            dock='tab',
        ),
    ),
                width=0.8,
                height=0.7,
                buttons=['OK', 'Cancel'],
                resizable=True)
示例#15
0
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',
    )
示例#16
0
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)
示例#17
0
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)
示例#18
0
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'])
示例#19
0
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)