Exemplo n.º 1
0
class AnalyticalFunction( HasTraits ):
    
    expression = Expression('x**2', auto_set = False, enter_set = True )
    refresh = Button('redraw')
    def _refresh_fired(self):
        xdata = linspace(0.001,10,10000)
        fneval = frompyfunc( lambda x: eval( self.expression ), 1, 1 )
        ydata = fneval( xdata )
        self.mfn.set( xdata = xdata, ydata = ydata )
        self.mfn.data_changed = True
        
    mfn = Instance( MFnLineArray )
    def _mfn_default( self ):
        return MFnLineArray()
    
    @on_trait_change('expression' )
    def update_mfn(self):
        self._refresh_fired()
    
    view_mpl = View( HGroup( Item( 'expression' ), Item('refresh' ) ),
                 Item( 'mfn', editor = MFnMatplotlibEditor( adapter = a ), 
                       show_label = False ),
                 resizable = True,
                 scrollable = True,
                 height = 0.5, width = 0.5
                    )
    
    view_chaco = View( HGroup( Item( 'expression' ), Item('refresh' ) ),
                 Item( 'mfn', editor = MFnChacoEditor( adapter = a ), 
                       resizable = True, show_label = False ),
                 resizable = True,
                 scrollable = True,
                 height = 0.3, width = 0.3
                    )
Exemplo n.º 2
0
    class STree(HasTraits):
        title = Str
        company = Instance(SPIRRIDUI)

        # The main view
        view = View(
                   Group(
                       Item(
                            name = 'company',
                            id = 'company',
                            editor = tree_editor,
                            resizable = True,
                            show_label = False ),
                        orientation = 'vertical',
                        show_labels = True,
                        show_left = True, ),
                    title = 'SPIRRID',
                    id = \
                     'tree_editor_spirrid',
                    dock = 'horizontal',
                    drop_class = HasTraits,
                    buttons = [ 'Undo', 'OK', 'Cancel' ],
                    resizable = True,
                    width = .3,
                    height = .3 )
Exemplo n.º 3
0
class Demo(HasTraits):
    '''Demo class for response functions'''

    fiber_tt_2p = Instance(SPIRRIDLAB)

    def _fiber_tt_2p_default(self):
        return fiber_tt_2p.create_demo_object()

    fiber_tt_5p = Instance(SPIRRIDLAB)

    def _fiber_tt_5p_default(self):
        return fiber_tt_5p.create_demo_object()

    fiber_po_8p = Instance(SPIRRIDLAB)

    def _fiber_po_8p_default(self):
        return fiber_po_8p.create_demo_object()


#
#    fiber_cb_8p = Instance(SPIRRIDLAB)
#    def _fiber_cb_8p_default(self):
#        return fiber_cb_8p.create_demo_object()

    traits_view = View(
        Item('fiber_tt_2p', show_label=False),
        Item('fiber_tt_5p', show_label=False),
        Item('fiber_po_8p', show_label=False),
        #Item('fiber_cb_8p', show_label = False),
        width=0.2,
        height=0.2,
        buttons=['OK', 'Cancel'])
Exemplo n.º 4
0
class MKPullOutParamDistribs(SimDBClass):

    phi = Instance(IPDistrib)
    theta = Instance(IPDistrib)
    ell = Instance(IPDistrib)

    traits_view = View(Item('phi@'), Item('theta@'), Item('ell@'))
Exemplo n.º 5
0
class S(YMBSource):

    yarn_type = Enum('__TEST__',
                     changed_source=True,
                     editor=EnumEditor(values=['__TEST__']))
    root_dir = Str('')

    view = View(Item('yarn_type'))
Exemplo n.º 6
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 ]
        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
Exemplo n.º 7
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)
Exemplo n.º 8
0
 def default_traits_view( self ):
     return View( HGroup( Item( 'n_int', visible_when = 'random', label = 'NIP',
                                     ),
                              Spring(),
                              show_border = True,
                              label = 'Variable name: %s' % self.varname
                              ),
                 Item( 'pd@', show_label = False ),
                 resizable = True,
                 id = 'rid_variable',
                 height = 800 )
Exemplo n.º 9
0
class RVModelView(ModelView):
    '''
    ModelView class for displaying the table of parameters and
    set the distribution parameters of random variables
    '''

    title = Str('randomization setup')

    model = Instance(SPIRRID)

    rv_list = List(RIDVariable)

    @on_trait_change('model.rf')
    def get_rv_list(self):
        self.rv_list = [
            RIDVariable(s=self.model,
                        rf=self.model.rf,
                        varname=nm,
                        trait_value=st) for nm, st in
            zip(self.model.rf.param_keys, self.model.rf.param_values)
        ]

    selected_var = Instance(RIDVariable)

    def _selected_var_default(self):
        return self.rv_list[0]

    title = Str('random variable editor')

    selected_var = Instance(RIDVariable)

    traits_view = View(VSplit(
        HGroup(
            Item('rv_list', editor=rv_list_editor, show_label=False),
            id='rid.tview.randomization.rv',
            label='Model variables',
        ),
        HGroup(
            Item('selected_var@', show_label=False, resizable=True),
            id='rid.tview.randomization.distr',
            label='Distribution',
        ),
        scrollable=True,
        id='rid.tview.tabs',
        dock='tab',
    ),
                       title='RANDOM VARIABLES',
                       id='rid.ridview',
                       dock='tab',
                       resizable=True,
                       height=1.0,
                       width=1.0)
Exemplo n.º 10
0
class SimplyRatio(HasTraits):
    '''
    Class specifying explicitly the reinforcement. 
    '''
    rho = Float(
        0.032,
        auto_set=False,
        enter_set=True,  # [-]
        desc='the reinforcement ratio [-]',
        modified=True)

    traits_view = View(
        Item('rho', label='reinforcement ratio'),
        resizable=True,
    )
Exemplo n.º 11
0
    class Test( HasTraits ):

        figure = Instance( Figure, () )

        view = View( Item( 'figure', editor = MPLFigureEditor(),
                                show_label = False ),
                        width = 400,
                        height = 300,
                        resizable = True )

        def __init__( self ):
            super( Test, self ).__init__()
            axes = self.figure.add_subplot( 111 )
            t = linspace( 0, 2 * pi, 200 )
            axes.plot( sin( t ) * ( 1 + 0.5 * cos( 11 * t ) ), cos( t ) * ( 1 + 0.5 * cos( 11 * t ) ) )
Exemplo n.º 12
0
class Demo(HasTraits):
    '''Demo class for response functions'''

    fiber_tt_2p = Instance(SPIRRIDLAB)

    def _fiber_tt_2p_default(self):
        return fiber_tt_2p.create_demo_object()

    fiber_tt_5p = Instance(SPIRRIDLAB)

    def _fiber_tt_5p_default(self):
        return fiber_tt_5p.create_demo_object()

    fiber_po_8p = Instance(SPIRRIDLAB)

    def _fiber_po_8p_default(self):
        return fiber_po_8p.create_demo_object()

    fiber_cb_8p = Button()

    def _fiber_cb_8p_fired(self):
        return fiber_cb_8p.create_demo_object()

    mask_arr_b = Button()

    def _mask_arr_b_fired(self):
        return mask_arr.main()

    numexpr_b = Button()

    def _numexpr_b_fired(self):
        return numexpr_test.main()

    script_b = Button()

    def _script_b_fired(self):
        return script.main()

    traits_view = View(Item('fiber_tt_2p', show_label=False),
                       Item('fiber_tt_5p', show_label=False),
                       Item('fiber_po_8p', show_label=False),
                       Item('fiber_cb_8p', show_label=False),
                       Item('mask_arr_b', show_label=False),
                       Item('numexpr_b', show_label=False),
                       Item('script_b', show_label=False),
                       width=0.2,
                       height=0.3,
                       buttons=['OK', 'Cancel'])
Exemplo n.º 13
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'])
Exemplo n.º 14
0
class LCC(HasTraits):

    lcc_id = Int

    # lcc_table = WeakRef()

    ls_table = Instance(LSTable)

    assess_value = Property()

    def _get_assess_value(self):
        return self.ls_table.assess_value

    traits_view = View(Item('ls_table@', show_label=False),
                       resizable=True,
                       scrollable=True)
Exemplo n.º 15
0
 def default_traits_view(self):
     '''
     Generates the view from the param items.
     '''
     param_items = [Item(name) for name in self.param_keys]
     ctrl_items = [Item(name) for name in self.ctrl_keys]
     view = View(VGroup(*param_items, id='stats.spirrid.rf.params'),
                 VGroup(*ctrl_items, id='stats.spirrid.rf.ctrl'),
                 kind='modal',
                 height=0.3,
                 width=0.2,
                 scrollable=True,
                 resizable=True,
                 buttons=['OK', 'Cancel'],
                 id='stats.spirrid.rf')
     return view
Exemplo n.º 16
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
Exemplo n.º 17
0
class YMBAutoCorrel(HasTraits):

    data = Instance(IYMBData)

    var_enum = Trait('radius',
                      var_dict)

    input_change = Event
    @on_trait_change('var_enum, data.input_change')
    def _set_input_change(self):
        print 'YMBAutoCorrel input change'
        self.input_change = True

    corr_arr = Property(Array, depends_on='var_enum, data.input_change')
    @cached_property
    def _get_corr_arr(self):
        corr_data = getattr(self.data, self.var_enum_)
        # @kelidas: return small differences between ma and numpy corrcoef
        # print MatSpearman( corr_data )
        # return ma.corrcoef( corr_data, rowvar = False, allow_masked = True )
        return MatSpearman(corr_data)


    fit_correl = Property()
    def _get_fit_correl(self):
        x_coor = self.data.x_coord
        var_data = self.corr_arr
        x = []
        y = []
        for i in range(0, var_data.shape[1]):
            x.append(x_coor[i:] - x_coor[i])
            y.append(var_data[i, (i):])
        x = hstack(x)
        y = hstack(y)
        p0 = [1., 1., 1., 1.]
        plsq = leastsq(self.residual_ls, p0, args=(y, x))
        return plsq[0]

    def residual_ls(self, p, y, x):
        err = y - self.peval(x, p)
        return err

    def peval(self, x, p):
        return  p[0] * x ** 3 + p[1] * x ** 2 + p[2] * x + p[3]

    traits_view = View(Item('var_enum', label='Variable'))
Exemplo n.º 18
0
    def default_traits_view(self):
        '''checks the number of shape parameters of the distribution and adds them to
        the view instance'''
        label = str(self.distribution.name)
        if self.distribution.shapes == None:
            params = Item()
            if self.mean == infty:
                moments = Item(label='No finite moments defined')
            else:
                moments = Item('mean', label='mean'), \
                            Item('variance', label='variance'), \
                            Item('stdev', label='st. deviation', style='readonly')

        elif len(self.distribution.shapes) == 1:
            params = Item('shape', label='shape')
            if self.mean == infty:
                moments = Item(label='No finite moments defined')
            else:
                moments = Item('mean', label='mean'), \
                            Item('variance', label='variance'), \
                            Item('stdev', label='st. deviation', style='readonly'), \
                            Item('skewness', label='skewness'), \
                            Item('kurtosis', label='kurtosis'),
        else:
            params = Item()
            moments = Item()

        view = View(VGroup(Label(label, emphasized=True),
                           Group(params,
                                 Item('loc', label='location'),
                                 Item('scale', label='scale'),
                                 Item('loc_zero', label='loc = 0.0'),
                                 show_border=True,
                                 label='parameters',
                                 id='pdistrib.distribution.params'),
                           Group(
                               moments,
                               id='pdistrib.distribution.moments',
                               show_border=True,
                               label='moments',
                           ),
                           id='pdistrib.distribution.vgroup'),
                    kind='live',
                    resizable=True,
                    id='pdistrib.distribution.view')
        return view
Exemplo n.º 19
0
class SPIRRID( Randomization ):

    #---------------------------------------------------------------------------------------------
    # Range of the control process variable epsilon
    # Define particular control variable points with
    # the cv array or an equidistant range with (min, max, n)
    #---------------------------------------------------------------------------------------------

    cv = Array( eps_range = True )
    min_eps = Float( 0.0, eps_range = True )
    max_eps = Float( 0.0, eps_range = True )
    n_eps = Float( 80, eps_range = True )

    eps_arr = Property( depends_on = 'eps_change' )
    @cached_property
    def _get_eps_arr( self ):

        # @todo: !!! 
        # This is a side-effect in a property - CRIME !! [rch]
        # No clear access interface points - naming inconsistent.
        # define a clean property with a getter and setter
        # 
        # if the array of control variable points is not given
        if len( self.cv ) == 0:

            n_eps = self.n_eps
            min_eps = self.min_eps
            max_eps = self.max_eps

            return linspace( min_eps, max_eps, n_eps )
        else:
            return self.cv

    #------------------------------------------------------------------------------------
    # Configuration of the algorithm
    #------------------------------------------------------------------------------------
    # 
    # cached_dG_grid:
    # If set to True, the cross product between the pdf values of all random variables
    # will be precalculated and stored in an n-dimensional grid
    # otherwise the product is performed for every epsilon in the inner loop anew
    # 
    cached_dG = Bool( True, alg_option = True )

    # compiled_eps_loop:
    # If set True, the loop over the control variable epsilon is compiled
    # otherwise, python loop is used.
    compiled_eps_loop = Bool( False, alg_option = True )

    # compiled_QdG_loop:
    # If set True, the integration loop over the product between the response function
    # and the pdf . theta product is performed in c
    # otherwise the numpy arrays are used.
    compiled_QdG_loop = Bool( False, alg_option = True )
    def _compiled_QdG_loop_changed( self ):
        '''If the inner loop is not compiled, the outer loop 
        must not be compiled as well.
        '''
        if self.compiled_QdG_loop == False:
            self.compiled_eps = False

    arg_list = Property( depends_on = 'rf_change, rand_change, conf_change' )
    @cached_property
    def _get_arg_list( self ):

        arg_list = []
        # create argument string for inline function
        if self.compiled_eps_loop:
            arg_list += [ 'mu_q_arr', 'e_arr' ]
        else:
            arg_list.append( 'e' )

        arg_list += ['%s_flat' % name for name in self.rv_keys ]

        if self.cached_dG:
            arg_list += [ 'dG_grid' ]
        else:
            arg_list += [ '%s_pdf' % name for name in self.rv_keys ]

        return arg_list

    dG_C_code = Property( depends_on = 'rf_change, rand_change, conf_change' )
    @cached_property
    def _get_dG_C_code( self ):
        if self.cached_dG: # q_g - blitz matrix used to store the grid
            code_str = '\tdouble pdf = dG_grid(' + \
                       ','.join( [ 'i_%s' % name
                                  for name in self.rv_keys ] ) + \
                       ');\n'
        else: # qg
            code_str = '\tdouble pdf = ' + \
                       '*'.join( [ ' *( %s_pdf + i_%s)' % ( name, name )
                                  for name in self.rv_keys ] ) + \
                       ';\n'
        return code_str

    #------------------------------------------------------------------------------------
    # Configurable generation of C-code for mean curve evaluation
    #------------------------------------------------------------------------------------
    C_code = Property( depends_on = 'rf_change, rand_change, conf_change, eps_change' )
    @cached_property
    def _get_C_code( self ):

        code_str = ''
        if self.compiled_eps_loop:

            # create code string for inline function
            #
            code_str += 'for( int i_eps = 0; i_eps < %g; i_eps++){\n' % self.n_eps

            if self.cached_dG:

                # multidimensional index needed for dG_grid 
                # blitz arrays must be used also for other arrays
                #
                code_str += 'double eps = e_arr( i_eps );\n'

            else:
                # pointer access possible for single dimensional arrays 
                # use the pointer arithmetics for accessing the pdfs
                code_str += '\tdouble eps = *( e_arr + i_eps );\n'

        else:

            # create code string for inline function
            #
            code_str += 'double eps = e;\n'

        code_str += 'double mu_q(0);\n'
        code_str += 'double q(0);\n'

        code_str += '#line 100\n'
        # create code for constant params
        for name, value in list(self.const_param_dict.items()):
            code_str += 'double %s = %g;\n' % ( name, value )

        # generate loops over random params

        for rv in self.rv_list:

            name = rv.name
            n_int = rv.n_int

            # create the loop over the random variable
            #
            code_str += 'for( int i_%s = 0; i_%s < %g; i_%s++){\n' % ( name, name, n_int, name )
            if self.cached_dG:

                # multidimensional index needed for pdf_grid - use blitz arrays
                #
                code_str += '\tdouble %s = %s_flat( i_%s );\n' % ( name, name, name )
            else:

                # pointer access possible for single dimensional arrays 
                # use the pointer arithmetics for accessing the pdfs
                code_str += '\tdouble %s = *( %s_flat + i_%s );\n' % ( name, name, name )

        if len( self.rv_keys ) > 0:
            code_str += self.dG_C_code
            code_str += self.rf.C_code + \
                       '// Store the values in the grid\n' + \
                       '\tmu_q +=  q * pdf;\n'
        else:
            code_str += self.rf.C_code + \
                       '\tmu_q += q;\n'

        # close the random loops
        #
        for name in self.rv_keys:
            code_str += '};\n'

        if self.compiled_eps_loop:
            if self.cached_dG: # blitz matrix
                code_str += 'mu_q_arr(i_eps) = mu_q;\n'
            else:
                code_str += '*(mu_q_arr + i_eps) = mu_q;\n'
            code_str += '};\n'
        else:
            code_str += 'return_val = mu_q;'
        return code_str

    compiler_verbose = Int( 0 )
    compiler = Str( 'gcc' )

    # Option of eval that induces the calculation of variation
    # in parallel with the mean value so that interim values of Q_grid 
    # are directly used for both.
    #
    implicit_var_eval = Bool( False, alg_option = True )

    def _eval( self ):
        '''Evaluate the integral based on the configuration of algorithm.
        '''
        if self.cached_dG == False and self.compiled_QdG_loop == False:
            raise NotImplementedError('Configuration for pure Python integration is too slow and is not implemented')

        self._set_compiler()
        # prepare the array of the control variable discretization
        #
        eps_arr = self.eps_arr
        mu_q_arr = zeros_like( eps_arr )

        # prepare the variable for the variance
        var_q_arr = None
        if self.implicit_var_eval:
            var_q_arr = zeros_like( eps_arr )

        # prepare the parameters for the compiled function in 
        # a separate dictionary
        c_params = {}

        if self.compiled_eps_loop:

            # for compiled eps_loop the whole input and output array must be passed to c
            #
            c_params['e_arr'] = eps_arr
            c_params['mu_q_arr'] = mu_q_arr
            #c_params['n_eps' ] = n_eps

        if self.compiled_QdG_loop:

            # prepare the lengths of the arrays to set the iteration bounds
            #
            for rv in self.rv_list:
                c_params[ '%s_flat' % rv.name ] = rv.theta_arr

        if len( self.rv_list ) > 0:
            if self.cached_dG:
                c_params[ 'dG_grid' ] = self.dG_grid
            else:
                for rv in self.rv_list:
                    c_params['%s_pdf' % rv.name] = rv.dG_arr
        else:
                c_params[ 'dG_grid' ] = self.dG_grid

        if self.cached_dG:
            conv = converters.blitz
        else:
            conv = converters.default

        t = time.clock()

        if self.compiled_eps_loop:

            # C loop over eps, all inner loops must be compiled as well
            #
            if self.implicit_var_eval:
                raise NotImplementedError('calculation of variance not available in the compiled version')

            inline( self.C_code, self.arg_list, local_dict = c_params,
                    type_converters = conv, compiler = self.compiler,
                    verbose = self.compiler_verbose )

        else:

            # Python loop over eps
            #
            for idx, e in enumerate( eps_arr ):

                if self.compiled_QdG_loop:

                    if self.implicit_var_eval:
                        raise NotImplementedError('calculation of variance not available in the compiled version')

                    # C loop over random dimensions
                    #
                    c_params['e'] = e # prepare the parameter
                    mu_q = inline( self.C_code, self.arg_list, local_dict = c_params,
                                   type_converters = conv, compiler = self.compiler,
                                   verbose = self.compiler_verbose )
                else:

                    # Numpy loops over random dimensions
                    #
                    # get the rf grid for all combinations of
                    # parameter values
                    #          
                    Q_grid = self.rf( e, **self.param_dict )

                    # multiply the response grid with the contributions
                    # of pdf distributions (weighted by the delta of the
                    # random variable disretization)
                    #

                    if not self.implicit_var_eval:
                        # only mean value needed, the multiplication can be done
                        # in-place
                        Q_grid *= self.dG_grid
                        # sum all the values to get the integral 
                        mu_q = sum( Q_grid )
                    else:
                        # get the square values of the grid
                        Q_grid2 = Q_grid ** 2
                        # make an inplace product of Q_grid with the weights
                        Q_grid *= self.dG_grid
                        # make an inplace product of the squared Q_grid with the weights
                        Q_grid2 *= self.dG_grid
                        # sum all values to get the mean
                        mu_q = sum( Q_grid )
                        # sum all squared values to get the variance
                        var_q = sum( Q_grid2 ) - mu_q ** 2

                # add the value to the return array
                mu_q_arr[idx] = mu_q

                if self.implicit_var_eval:
                    var_q_arr[idx] = var_q

        duration = time.clock() - t
        return  mu_q_arr, var_q_arr, duration

    def eval_i_dG_grid( self ):
        '''Get the integral of the pdf * theta grid.
        '''
        return sum( self.dG_grid )

    #---------------------------------------------------------------------------------------------
    # Output properties
    #---------------------------------------------------------------------------------------------

    # container for the data obtained in the integration
    #
    # This is not only the mean curve but also variance and 
    # execution statistics. Such an implementation 
    # concentrates the critical part of the algorithmic 
    # evaluation and avoids duplication of code and 
    # repeated calls. The results are cached in the tuple.
    # They are accessed by the convenience properties defined
    # below. 
    #  
    results = Property( depends_on = 'rand_change, conf_change, eps_change' )
    @cached_property
    def _get_results( self ):
        return self._eval()

    #---------------------------------------------------------------------------------------------
    # Output accessors
    #---------------------------------------------------------------------------------------------
    # the properties that access the cached results and give them a name

    mu_q_arr = Property()
    def _get_mu_q_arr( self ):
        '''mean of q at eps'''
        return self.results[0]

    var_q_arr = Property()
    def _get_var_q_arr( self ):
        '''variance of q at eps'''
        # switch on the implicit evaluation of variance 
        # if it has not been the case so far
        if not self.implicit_var_eval:
            self.implicit_var_eval = True

        return self.results[1]

    exec_time = Property()
    def _get_exec_time( self ):
        '''Execution time of the last evaluation.
        '''
        return self.results[2]

    mean_curve = Property()
    def _get_mean_curve( self ):
        '''Mean response curve.
        '''
        return MFnLineArray( xdata = self.eps_arr, ydata = self.mu_q_arr )

    var_curve = Property()
    def _get_var_curve( self ):
        '''variance of q at eps'''
        return MFnLineArray( xdata = self.eps_arr, ydata = self.var_q_arr )

    #---------------------------------------------------------------------------------------------
    # Auxiliary methods
    #---------------------------------------------------------------------------------------------
    def _set_compiler( self ):
        '''Catch eventual mismatch between scipy.weave and compiler 
        '''
        try:
            uname = os.uname()[3]
        except:
            # it is not Linux - just let it go and suffer
            return

        #if self.compiler == 'gcc':
            #os.environ['CC'] = 'gcc-4.1'
            #os.environ['CXX'] = 'g++-4.1'
            #os.environ['OPT'] = '-DNDEBUG -g -fwrapv -O3'

    traits_view = View( Item( 'rf@', show_label = False ),
                        width = 0.3, height = 0.3,
                        resizable = True,
                        scrollable = True,
                        )
Exemplo n.º 20
0
class ResultView(HasTraits):

    spirrid_view = Instance(SPIRRIDModelView)

    title = Str('result plot')

    n_samples = Int(10)

    figure = Instance(Figure)

    def _figure_default(self):
        figure = Figure(facecolor='white')
        #figure.add_axes( [0.08, 0.13, 0.85, 0.74] )
        return figure

    data_changed = Event(True)

    clear = Button

    def _clear_fired(self):
        axes = self.figure.axes[0]
        axes.clear()
        self.data_changed = True

    def get_rvs_theta_arr(self, n_samples):
        rvs_theta_arr = array([
            repeat(value, n_samples)
            for value in self.spirrid_view.model.rf.param_values
        ])
        for idx, name in enumerate(self.spirrid_view.model.rf.param_keys):
            rv = self.spirrid_view.model.rv_dict.get(name, None)
            if rv:
                rvs_theta_arr[idx, :] = rv.get_rvs_theta_arr(n_samples)
        return rvs_theta_arr

    sample = Button(desc='Show samples')

    def _sample_fired(self):
        n_samples = 20

        self.spirrid_view.model.set(
            min_eps=0.00,
            max_eps=self.spirrid_view.max_eps,
            n_eps=self.spirrid_view.n_eps,
        )

        # get the parameter combinations for plotting
        rvs_theta_arr = self.get_rvs_theta_arr(n_samples)

        eps_arr = self.spirrid_view.model.eps_arr

        figure = self.figure
        axes = figure.gca()

        for theta_arr in rvs_theta_arr.T:
            q_arr = self.spirrid_view.model.rf(eps_arr, *theta_arr)
            axes.plot(eps_arr, q_arr, color='grey')

        self.data_changed = True

    @on_trait_change('spirrid_view.data_changed')
    def _redraw(self):

        figure = self.figure
        axes = figure.gca()

        mc = self.spirrid_view.model.mean_curve
        xdata = mc.xdata
        mean_per_fiber = mc.ydata
        # total expectation for independent variables = product of marginal expectations
        mean = mean_per_fiber * self.spirrid_view.mean_parallel_links

        axes.set_title(self.spirrid_view.plot_title, weight='bold')
        axes.plot(xdata, mean, linewidth=2, label=self.spirrid_view.run_legend)

        if self.spirrid_view.stdev:
            # get the variance at x from SPIRRID
            variance = self.spirrid_view.model.var_curve.ydata

            # evaluate variance for the given mean and variance of parallel links
            # law of total variance D[xy] = E[x]*D[y] + D[x]*[E[y]]**2
            variance = self.spirrid_view.mean_parallel_links * variance + \
                    self.spirrid_view.stdev_parallel_links ** 2 * mean_per_fiber ** 2
            stdev = sqrt(variance)

            axes.plot(xdata,
                      mean + stdev,
                      linewidth=2,
                      color='black',
                      ls='dashed',
                      label='stdev')
            axes.plot(xdata,
                      mean - stdev,
                      linewidth=2,
                      ls='dashed',
                      color='black')
            axes.fill_between(xdata,
                              mean + stdev,
                              mean - stdev,
                              color='lightgrey')

        axes.set_xlabel(self.spirrid_view.label_x, weight='semibold')
        axes.set_ylabel(self.spirrid_view.label_y, weight='semibold')
        axes.legend(loc='best')

        if xdata.any() == 0.:
            self.figure.clear()

        self.data_changed = True

    traits_view = View(
        HGroup(Item('n_samples', label='No of samples'),
               Item('sample', show_label=False, resizable=False),
               Item('clear', show_label=False, resizable=False,
                    springy=False)),
        Item('figure', show_label=False, editor=MPLFigureEditor()))
Exemplo n.º 21
0
class RunTable(SimDBClass):
    '''Manage the combinations of exec configurations and randomization patterns.
    '''

    name = Str(simdb=True)

    memsize = Float(1e4, simdb=True)

    s = Property(Instance(SPIRRID), depends_on='rf')

    @cached_property
    def _get_s(self):
        return SPIRRID(rf=self.rf,
                       min_eps=0.00,
                       max_eps=1.0,
                       n_eps=20,
                       compiler_verbose=0)

    rf = Instance(IRF, simdb=True)

    config_list = List(config=True)

    def _config_list_default(self):
        return ['I', 'IV']

    config_dict = Property(depends_on='config_list')

    @cached_property
    def _get_config_dict(self):
        cd = {}
        for config_idx in self.config_list:
            cd[config_idx] = config_dict[config_idx]
        return cd

    rand_list = List(rand=True)

    run_arr = Property(Array, depends_on='+rand,+config')

    @cached_property
    def _get_run_arr(self):
        # generate the runs to be performed
        run_table = [[
            SingleRun(run_table=self, config=config, rand_idx_arr=rand_idx_arr)
            for rand_idx_arr in self.rand_list
        ] for config in self.config_dict.items()]

        return array(run_table)

    exec_time_arr = Array
    n_int_arr = Array
    real_memsize_arr = Array

    calculate = Button()

    def _calculate_fired(self):
        s = self.run_arr.shape
        self.exec_time_arr = array(
            [run.exec_time for run in self.run_arr.flatten()]).reshape(s)
        self.n_int_arr = array([run.n_int
                                for run in self.run_arr.flatten()]).reshape(s)
        self.real_memsize_arr = array(
            [run.real_memsize for run in self.run_arr.flatten()]).reshape(s)
        self.save()
        self._redraw_fired()

    clear = Button()

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

    figure = Instance(Figure, transient=True)

    def _figure_default(self):
        figure = Figure(facecolor='white')
        #figure.add_axes( [0.08, 0.13, 0.85, 0.74] )
        return figure

    data_changed = Event(True)

    normalized_numpy = Bool(True)
    c_code = Bool(False)

    redraw = Button()

    def _redraw_fired(self):
        figure = self.figure
        axes = figure.gca()
        self.plot(axes)
        self.data_changed = True

    redraw_in_window = Button()

    def _redraw_in_window_fired(self):
        figure = plt.figure(0)
        axes = figure.gca()
        self.plot(axes)
        plt.show()

    def plot(self, ax):

        exec_time_arr = self.exec_time_arr
        n_int_arr = self.n_int_arr[0, :]
        real_memsize_arr = self.real_memsize_arr[0, :]

        rand_arr = arange(len(self.rand_list)) + 1
        width = 0.45

        if exec_time_arr.shape[0] == 1:
            shift = width / 2.0
            ax.bar(rand_arr - shift,
                   exec_time_arr[0, :],
                   width,
                   color='lightgrey')

        elif self.exec_time_arr.shape[0] == 2:
            max_exec_time = nmax(exec_time_arr)

            ax.set_ylabel('$\mathrm{execution \, time \, [sec]}$', size=20)
            ax.set_xlabel(
                '$n_{\mathrm{rnd}}  \;-\; \mathrm{number \, of \, random \, parameters}$',
                size=20)

            ax.bar(rand_arr - width,
                   exec_time_arr[0, :],
                   width,
                   hatch='/',
                   color='white',
                   label='C')  # , color = 'lightgrey' )
            ax.bar(rand_arr,
                   exec_time_arr[1, :],
                   width,
                   color='lightgrey',
                   label='numpy')

            yscale = 1.25
            ax_xlim = rand_arr[-1] + 1
            ax_ylim = max_exec_time * yscale

            ax.set_xlim(0, ax_xlim)
            ax.set_ylim(0, ax_ylim)

            ax2 = ax.twinx()
            ydata = exec_time_arr[1, :] / exec_time_arr[0, :]
            ax2.plot(rand_arr,
                     ydata,
                     '-o',
                     color='black',
                     linewidth=1,
                     label='numpy/C')

            ax2.plot([rand_arr[0] - 1, rand_arr[-1] + 1], [1, 1], '-')
            ax2.set_ylabel(
                '$\mathrm{time}(  \mathsf{numpy}  ) / \mathrm{ time }(\mathsf{C}) \; [-]$',
                size=20)
            ax2_ylim = nmax(ydata) * yscale
            ax2_xlim = rand_arr[-1] + 1
            ax2.set_ylim(0, ax2_ylim)
            ax2.set_xlim(0, ax2_xlim)

            ax.set_xticks(rand_arr)
            ax.set_xticklabels(rand_arr, size=14)
            xticks = ['%.2g' % n_int for n_int in n_int_arr]
            ax3 = ax.twiny()
            ax3.set_xlim(0, rand_arr[-1] + 1)
            ax3.set_xticks(rand_arr)
            ax3.set_xlabel('$n_{\mathrm{int}}$', size=20)
            ax3.set_xticklabels(xticks, rotation=30)

            'set the tick label size of the lower X axis'
            X_lower_tick = 14
            xt = ax.get_xticklabels()
            for t in xt:
                t.set_fontsize(X_lower_tick)

            'set the tick label size of the upper X axis'
            X_upper_tick = 12
            xt = ax3.get_xticklabels()
            for t in xt:
                t.set_fontsize(X_upper_tick)

            'set the tick label size of the Y axes'
            Y_tick = 14
            yt = ax2.get_yticklabels() + ax.get_yticklabels()
            for t in yt:
                t.set_fontsize(Y_tick)

            'set the legend position and font size'
            leg_fontsize = 16
            leg = ax.legend(loc=(0.02, 0.83))
            for t in leg.get_texts():
                t.set_fontsize(leg_fontsize)
            leg = ax2.legend(loc=(0.705, 0.90))
            for t in leg.get_texts():
                t.set_fontsize(leg_fontsize)

    traits_view = View(Item('name'),
                       Item('memsize'),
                       Item('rf'),
                       Item('config_dict'),
                       Item('rand_list'),
                       HGroup(
                           Item('calculate', show_label=False),
                           Item('redraw', show_label=False),
                           Item('clear', show_label=False),
                           Item('redraw_in_window', show_label=False),
                       ),
                       Item('figure',
                            editor=MPLFigureEditor(),
                            resizable=True,
                            show_label=False),
                       buttons=['OK', 'Cancel'])
Exemplo n.º 22
0
                     '%4.2f' % t,
                     horizontalalignment=align,
                     verticalalignment='center',
                     color=clr)  #, weight = 'bold')

        ax4 = ax3.twinx()
        ax3.plot([1, 1], [0, n_tests], 'k--')
        ax4.set_yticks([0] + list(pos) + [n_tests])
        ax4.set_yticklabels([''] + ['%4.2f s' % s for s in list(times)] + [''])
        ax4.set_xticks([0, 1] + range(5, x_max_plt + 1, 5))
        ax4.set_xticklabels(
            ['%i' % s for s in ([0, 1] + range(5, x_max_plt + 1, 5))])

    traits_view = View(Item('sampling_structure_btn', show_label=False),
                       Item('sampling_efficiency_btn', show_label=False),
                       Item('language_efficiency_btn', show_label=False),
                       width=0.2,
                       height=0.2,
                       buttons=['OK', 'Cancel'])


if __name__ == '__main__':

    from stats.spirrid.rv import RV
    from scipy.special import erf
    import math

    # response function
    def fiber_tt_2p(e, la, xi):
        ''' Response function of a single fiber '''
        return la * e * Heaviside(xi - e)
Exemplo n.º 23
0
class POShortFiber(RF):
    '''
    Pullout of fiber from a stiff matrix;
    stress criterion for debonding, free fiber end
    '''

    implements(IRF)

    title = Str('pullout - short fiber with constant friction')
    image = Image('pics/cb_short_fiber.jpg')

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

    E_f = Float(200e+3,
                auto_set=False,
                enter_set=True,
                desc='filament stiffness [N/mm2]',
                distr=['uniform', 'norm'],
                scale=210e3,
                shape=0)

    D_f = Float(0.3,
                auto_set=False,
                enter_set=True,
                desc='filament diameter [mm]',
                distr=['uniform', 'norm'],
                scale=0.5,
                shape=0)

    le = Float(8.5,
               auto_set=False,
               enter_set=True,
               desc='embedded lentgh [mm]',
               distr=['uniform'],
               scale=8.5,
               shape=0)

    L_f = Float(17.0,
                auto_set=False,
                enter_set=True,
                desc='fiber length [mm]',
                distr=['uniform', 'norm'],
                scale=30,
                shape=0)

    tau = Float(1.76,
                auto_set=False,
                enter_set=True,
                desc='bond shear stress [N/mm2]',
                distr=['norm', 'uniform'],
                scale=1.76,
                shape=0.5)

    f = Float(0.03,
              auto_set=False,
              enter_set=True,
              desc='snubbing coefficient',
              distr=['uniform', 'norm'],
              scale=0.05,
              shape=0)

    phi = Float(0.0,
                auto_set=False,
                enter_set=True,
                desc='inclination angle',
                distr=['sin2x', 'sin_distr'],
                scale=1.0,
                shape=0)

    l = Float(0.0,
              auto_set=False,
              enter_set=True,
              distr=['uniform'],
              desc='free length')

    theta = Float(0.01,
                  auto_set=False,
                  enter_set=True,
                  distr=['uniform', 'norm'],
                  desc='slack')

    u = Float(ctrl_range=(0, 0.01, 100), auto_set=False, enter_set=True)

    x_label = Str('displacement [mm]', enter_set=True, auto_set=False)
    y_label = Str('force [N]', enter_set=True, auto_set=False)

    C_code = ''

    def __call__(self, u, tau, L_f, D_f, E_f, le, phi, f, l, theta, xi):

        l = l * (1 + theta)
        u = u - theta * l
        T = tau * pi * D_f
        E = E_f
        A = D_f**2 / 4. * pi

        # debonding stage
        q_deb = -l * T + sqrt((l * T)**2 + 2 * E * A * T * u * H(u))

        # displacement at which debonding is finished
        u0 = le * T * (le + 2 * l) / 2 / E_f / A

        q_pull = le * T * ((u0 - u) / (le - u0) + 1)
        q = q_deb * H(le * T - q_deb) + q_pull * H(q_deb - le * T)

        # include inclination influence
        q = q * H(q) * e**(f * phi)

        # include breaking strain
        q = q * H(A * E_f * xi - q)
        return q

    def get_q_x(self, u, x, tau, L_f, D_f, E_f, z, phi, f, l, theta, xi):
        q = self.__call__(u, tau, L_f, D_f, E_f, z, phi, f, l, theta, xi)
        l = l * (1 + theta)
        T = tau * pi * D_f
        qfree = q
        qbond = q - T * (x - l)

        return qfree * H(l - x) + qbond * H(x - l)

    traits_view = View(Item('E_f', label='fiber E-mod'),
                       Item('D_f', label='fiber diameter'),
                       Item('f', label='snubbing coef.'),
                       Item('phi', label='inclination angle'),
                       Item('le', label='embedded length'),
                       Item('tau', label='frictional coef.'),
                       resizable=True,
                       scrollable=True,
                       height=0.8,
                       width=0.8,
                       buttons=[OKButton, CancelButton])
Exemplo n.º 24
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'])
Exemplo n.º 25
0
class ExpST(ExType):
    '''Experiment: Slab Test
    '''
#    label = Str('slab test')
    implements(IExType)

    #--------------------------------------------------------------------
    # register a change of the traits with metadata 'input'
    #--------------------------------------------------------------------

    input_change = Event
    @on_trait_change('+input, ccs.input_change, +ironing_param')
    def _set_input_change(self):
        self.input_change = True

    #--------------------------------------------------------------------------------
    # specify inputs:
    #--------------------------------------------------------------------------------

    edge_length = Float(1.25, unit='m', input=True, table_field=True,
                           auto_set=False, enter_set=True)
    thickness = Float(0.06, unit='m', input=True, table_field=True,
                           auto_set=False, enter_set=True)

    # age of the concrete at the time of testing
    age = Int(28, unit='d', input=True, table_field=True,
                             auto_set=False, enter_set=True)
    loading_rate = Float(2.0, unit='mm/min', input=True, table_field=True,
                            auto_set=False, enter_set=True)

    #--------------------------------------------------------------------------
    # composite cross section
    #--------------------------------------------------------------------------

    ccs = Instance(CompositeCrossSection)
    def _ccs_default(self):
        '''default settings correspond to
        setup '7u_MAG-07-03_PZ-0708-1'
        '''
        fabric_layout_key = '2D-05-11'
#        fabric_layout_key = 'MAG-07-03'
#        fabric_layout_key = '2D-02-06a'
#        concrete_mixture_key = 'PZ-0708-1'
#        concrete_mixture_key = 'FIL-10-09'
#        concrete_mixture_key = 'barrelshell'
        concrete_mixture_key = 'PZ-0708-1'
#        orientation_fn_key = 'all0'
        orientation_fn_key = '90_0'
        n_layers = 2
        s_tex_z = 0.015 / (n_layers + 1)
        ccs = CompositeCrossSection (
                    fabric_layup_list=[
                            plain_concrete(0.035),
#                            plain_concrete(s_tex_z * 0.5),
                            FabricLayUp (
                                   n_layers=n_layers,
                                   orientation_fn_key=orientation_fn_key,
                                   s_tex_z=s_tex_z,
                                   fabric_layout_key=fabric_layout_key
                                   ),
#                            plain_concrete(s_tex_z * 0.5)
                            plain_concrete(0.5)
                                        ],
                    concrete_mixture_key=concrete_mixture_key
                    )
        return ccs

    #--------------------------------------------------------------------------
    # Get properties of the composite
    #--------------------------------------------------------------------------

    # E-modulus of the composite at the time of testing
    E_c = Property(Float, unit='MPa', depends_on='input_change', table_field=True)
    def _get_E_c(self):
        return self.ccs.get_E_c_time(self.age)

    # E-modulus of the composite after 28 days
    E_c28 = DelegatesTo('ccs', listenable=False)

    # reinforcement ration of the composite
    rho_c = DelegatesTo('ccs', listenable=False)

    #--------------------------------------------------------------------------------
    # define processing
    #--------------------------------------------------------------------------------

    # put this into the ironing procedure processor
    #
    jump_rtol = Float(0.1,
                      auto_set=False, enter_set=True,
                      ironing_param=True)


    data_array_ironed = Property(Array(float),
                                  depends_on='data_array, +ironing_param, +axis_selection')
    @cached_property
    def _get_data_array_ironed(self):
        '''remove the jumps in the displacement curves
        due to resetting the displacement gauges.
        '''
        print '*** curve ironing activated ***'

        # each column from the data array corresponds to a measured parameter
        # e.g. displacement at a given point as function of time u = f(t))
        #
        data_array_ironed = copy(self.data_array)

        for idx in range(self.data_array.shape[1]):

            # use ironing method only for columns of the displacement gauges.
            #
            if self.names_and_units[0][ idx ] != 'Kraft' and \
                self.names_and_units[0][ idx ] != 'Bezugskanal' and \
                self.names_and_units[0][ idx ] != 'Weg':

                # 1d-array corresponding to column in data_array
                data_arr = copy(data_array_ironed[:, idx])

                # get the difference between each point and its successor
                jump_arr = data_arr[1:] - data_arr[0:-1]

                # get the range of the measured data
                data_arr_range = max(data_arr) - min(data_arr)

                # determine the relevant criteria for a jump
                # based on the data range and the specified tolerances:
                jump_crit = self.jump_rtol * data_arr_range

                # get the indexes in 'data_column' after which a
                # jump exceeds the defined tolerance criteria
                jump_idx = where(fabs(jump_arr) > jump_crit)[0]

                print 'number of jumps removed in data_arr_ironed for', self.names_and_units[0][ idx ], ': ', jump_idx.shape[0]
                # glue the curve at each jump together
                for jidx in jump_idx:
                    # get the offsets at each jump of the curve
                    shift = data_arr[jidx + 1] - data_arr[jidx]
                    # shift all succeeding values by the calculated offset
                    data_arr[jidx + 1:] -= shift

                data_array_ironed[:, idx] = data_arr[:]

        return data_array_ironed


    @on_trait_change('+ironing_param')
    def process_source_data(self):
        '''read in the measured data from file and assign
        attributes after array processing.

        NOTE: if center displacement gauge ('WA_M') is missing the measured
        displacement of the cylinder ('Weg') is used instead.
        A minor mistake is made depending on how much time passes
        before the cylinder has contact with the slab.
        '''
        print '*** process source data ***'

        self._read_data_array()
        # curve ironing:
        #
        self.processed_data_array = self.data_array_ironed

        # set attributes:
        #
        self._set_array_attribs()

        if 'WA_M' not in self.factor_list:
            print '*** NOTE: Displacement gauge at center ("WA_M") missing. Cylinder displacement ("Weg") is used instead! ***'
            self.WA_M = self.Weg


    #--------------------------------------------------------------------------------
    # plot templates
    #--------------------------------------------------------------------------------

    plot_templates = {'force / deflection (all)' : '_plot_force_deflection',
#                      'force / average deflection (c; ce; e) interpolated'    : '_plot_force_deflection_avg_interpolated',
#                      'force / deflection (center)'               : '_plot_force_center_deflection',
#                      'smoothed force / deflection (center)'      : '_plot_force_center_deflection_smoothed',
#                      'force / deflection (edges)'                : '_plot_force_edge_deflection',
#                      'force / deflection (center-edges)'         : '_plot_force_center_edge_deflection',
#                      'force / average deflection (edges)'        : '_plot_force_edge_deflection_avg',
#                      'force / average deflection (center-edges)' : '_plot_force_center_edge_deflection_avg',
#                      'force / average deflection (c; ce; e)'     : '_plot_force_deflection_avg',
#                      'force / deflection (center) interpolated'  : '_plot_force_center_deflection_interpolated',
#                      'force / deflection (corner)'               : '_plot_force_corner_deflection',
#                      'edge_deflection_avg (front/back) / edge_deflection_avg (left/right)' : '_plot_edge_deflection_edge_deflection_avg',

                     }

    default_plot_template = 'force / deflection (center)'


    n_fit_window_fraction = Float(0.1)

    # get only the ascending branch of the response curve
    #
    max_force_idx = Property(Int)
    def _get_max_force_idx(self):
        '''get the index of the maximum force'''
        return argmax(-self.Kraft)

    f_asc = Property(Array)
    def _get_f_asc(self):
        '''get only the ascending branch of the response curve'''
        return -self.Kraft[:self.max_force_idx + 1]

    w_asc = Property(Array)
    def _get_w_asc(self):
        '''get only the ascending branch of the response curve'''
        return -self.WA_M[:self.max_force_idx + 1]

    n_points = Property(Int)
    def _get_n_points(self):
        return int(self.n_fit_window_fraction * len(self.w_asc))

    f_smooth = Property()
    def _get_f_smooth(self):
        return smooth(self.f_asc, self.n_points, 'flat')

    w_smooth = Property()
    def _get_w_smooth(self):
        return smooth(self.w_asc, self.n_points, 'flat')

    def _plot_force_deflection(self, axes, offset_w=0., color='blue', linewidth=1.5, linestyle='-'):
        '''plot the F-w-diagramm for all displacement gauges including maschine displacement
        '''
        xkey = 'deflection [mm]'
        ykey = 'force [kN]'

        max_force_idx = self.max_force_idx
#        max_force_idx = -2
        f_asc = -self.Kraft[:max_force_idx + 1]

        print 'self.factor_list', self.factor_list
        header_string = ''
        for i in self.factor_list[2:]:
            header_string = header_string + i + '; '
            T_arr = -getattr(self, i)
            T_asc = T_arr[:max_force_idx + 1]
            axes.plot(T_asc, f_asc, label=i)

        axes.legend()

        img_dir = os.path.join(simdb.exdata_dir, 'img_dir')
        # check if directory exist otherwise create
        #
        if os.path.isdir(img_dir) == False:
            os.makedirs(img_dir)
        test_series_dir = os.path.join(img_dir, 'slab_test_astark')
        # check if directory exist otherwise create
        #
        if os.path.isdir(test_series_dir) == False:
            os.makedirs(test_series_dir)
        out_file = os.path.join(test_series_dir, self.key)

        np.savetxt(out_file, self.processed_data_array, delimiter=';')

        # workaround for old numpy.savetxt version:
        f = open(out_file, 'r')
        temp = f.read()
        f.close()

        f = open(out_file, 'w')
        f.write(header_string)

        f.write(temp)
        f.close()



    def _plot_force_center_deflection(self, axes, offset_w=0., color='blue', linewidth=1.5, linestyle='-'):
        '''plot the F-w-diagramm for the center (c) deflection
        '''
        xkey = 'deflection [mm]'
        ykey = 'force [kN]'
        xdata = -self.WA_M
        ydata = -self.Kraft

        xdata += offset_w
#        axes.set_xlabel('%s' % (xkey,))
#        axes.set_ylabel('%s' % (ykey,))
        axes.plot(xdata, ydata, color=color, linewidth=linewidth, linestyle=linestyle)

    def _plot_force_corner_deflection(self, axes):
        '''plot the F-w-diagramm for the corner deflection (at the center of one of the supports)
        '''
        xkey = 'deflection [mm]'
        ykey = 'force [kN]'
        xdata = -self.WA_Eck
        ydata = -self.Kraft

#        axes.set_xlabel('%s' % (xkey,))
#        axes.set_ylabel('%s' % (ykey,))
        axes.plot(xdata, ydata
                       # color = c, linewidth = w, linestyle = s
                       )

    def _plot_force_center_deflection_smoothed(self, axes):
        '''plot the F-w-diagramm for the center (c) deflection (smoothed curves)
        '''
        axes.plot(self.w_smooth, self.f_smooth, color='blue', linewidth=1)
#        secant_stiffness_w10 = (f_smooth[10] - f_smooth[0]) / (w_smooth[10] - w_smooth[0])
#        w0_lin = array([0.0, w_smooth[10] ], dtype = 'float_')
#        f0_lin = array([0.0, w_smooth[10] * secant_stiffness_w10 ], dtype = 'float_')
        # axes.plot( w0_lin, f0_lin, color = 'black' )

    def _plot_force_center_deflection_interpolated(self, axes, linestyle='-', linewidth=1.5, plot_elastic_stiffness=True):
        '''plot the F-w-diagramm for the center (c) deflection (interpolated initial stiffness)
        '''
        # get the index of the maximum stress
        max_force_idx = argmax(-self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = -self.Kraft[:max_force_idx + 1]
        w_m = -self.WA_M[:max_force_idx + 1]

#        w_m -= 0.17
#        axes.plot(w_m, f_asc, color = 'blue', linewidth = 1)

        # move the starting point of the center deflection curve to the point where the force starts
        # (remove offset in measured displacement where there is still no force measured)
        #
        idx_0 = np.where(f_asc > 0.0)[0][0]

        f_asc_cut = np.hstack([f_asc[ idx_0: ]])
        w_m_cut = np.hstack([w_m[ idx_0: ]]) - w_m[ idx_0 ]
#        print 'f_asc_cut.shape', f_asc_cut.shape
#        fw_arr = np.hstack([f_asc_cut[:, None], w_m_cut[:, None]])
#        print 'fw_arr.shape', fw_arr.shape
#        np.savetxt('ST-6c-2cm-TU_bs2_f-w_asc.csv', fw_arr, delimiter=';')
        axes.plot(w_m_cut, f_asc_cut, color='k', linewidth=linewidth, linestyle=linestyle)

        # composite E-modulus
        #
        E_c = self.E_c
        print 'E_c', E_c

        if self.thickness == 0.02 and self.edge_length == 0.80 and plot_elastic_stiffness == True:
            K_linear = E_c / 24900. * 1.056  # [MN/m]=[kN/mm] bending stiffness with respect to center force
            max_f = f_asc_cut[-1]
            w_linear = np.array([0., max_f / K_linear])
            f_linear = np.array([0., max_f])
            axes.plot(w_linear, f_linear, linewidth=linewidth, linestyle='--', color='k')
        if self.thickness == 0.03 and self.edge_length == 1.25 and plot_elastic_stiffness == True:
            K_linear = E_c / 24900. * 1.267  # [MN/m]=[kN/mm] bending stiffness with respect to center force
            max_f = f_asc_cut[-1]
            w_linear = np.array([0., max_f / K_linear])
            f_linear = np.array([0., max_f])
            axes.plot(w_linear, f_linear, linewidth=linewidth, linestyle='--', color='k')
        if self.thickness == 0.06 and self.edge_length == 1.25 and plot_elastic_stiffness == True:
            K_linear = E_c / 24900. * 10.14  # [MN/m]=[kN/mm] bending stiffness with respect to center force
            max_f = f_asc_cut[-1]
            w_linear = np.array([0., max_f / K_linear])
            f_linear = np.array([0., max_f])
            axes.plot(w_linear, f_linear, linewidth=linewidth, linestyle='--', color='k')

    def _plot_force_edge_deflection(self, axes):
        '''plot the F-w-diagramm for the edge (e) deflections
        '''
        max_force_idx = self.max_force_idx
        f_asc = self.f_asc
        w_v_asc = -self.WA_V[:max_force_idx + 1]
        w_h_asc = -self.WA_H[:max_force_idx + 1]
        w_l_asc = -self.WA_L[:max_force_idx + 1]
        w_r_asc = -self.WA_R[:max_force_idx + 1]
        axes.plot(w_v_asc, f_asc, color='blue', linewidth=1)
        axes.plot(w_h_asc, f_asc, color='blue', linewidth=1)
        axes.plot(w_l_asc, f_asc, color='green', linewidth=1)
        axes.plot(w_r_asc, f_asc, color='green', linewidth=1)

    def _plot_force_edge_deflection_avg(self, axes):
        '''plot the average F-w-diagramm for the edge (e) deflections
        '''
        max_force_idx = self.max_force_idx
        f_asc = self.f_asc
        w_v_asc = -self.WA_V[:max_force_idx + 1]
        w_h_asc = -self.WA_H[:max_force_idx + 1]
        w_l_asc = -self.WA_L[:max_force_idx + 1]
        w_r_asc = -self.WA_R[:max_force_idx + 1]
        # get the average displacement values of the corresponding displacement gauges
        w_vh_asc = (w_v_asc + w_h_asc) / 2
        w_lr_asc = (w_l_asc + w_r_asc) / 2
        axes.plot(w_vh_asc, f_asc, color='blue', linewidth=1, label='w_vh')
        axes.plot(w_lr_asc, f_asc, color='blue', linewidth=1, label='w_lr')
        axes.legend()

    def _plot_edge_deflection_edge_deflection_avg(self, axes):
        '''plot the average edge (e) deflections for the front/back and left/right
        '''
        max_force_idx = self.max_force_idx
        w_v_asc = -self.WA_V[:max_force_idx + 1]
        w_h_asc = -self.WA_H[:max_force_idx + 1]
        w_l_asc = -self.WA_L[:max_force_idx + 1]
        w_r_asc = -self.WA_R[:max_force_idx + 1]
        # get the average displacement values of the corresponding displacement gauges
        w_vh_asc = (w_v_asc + w_h_asc) / 2
        w_lr_asc = (w_l_asc + w_r_asc) / 2
        axes.plot(w_vh_asc, w_lr_asc, color='blue', linewidth=1, label='w_vh / w_lr')
        axes.plot(np.array([0, w_vh_asc[-1]]), np.array([0, w_vh_asc[-1]]), color='k', linewidth=1, linestyle='-')
        axes.legend()

    def _plot_force_center_edge_deflection(self, axes):
        '''plot the F-w-diagramm for the center-edge (ce) deflections
        '''
        max_force_idx = argmax(-self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = -self.Kraft[:max_force_idx + 1]
        w_ml_asc = -self.WA_ML[:max_force_idx + 1]
        w_mr_asc = -self.WA_MR[:max_force_idx + 1]
        axes.plot(w_ml_asc, f_asc, color='blue', linewidth=1, label='w_ml')
        axes.plot(w_mr_asc, f_asc, color='blue', linewidth=1, label='w_mr')
        axes.legend()

    def _plot_force_center_edge_deflection_avg(self, axes):
        '''plot the average F-w-diagramm for the center-edge (ce) deflections
        '''
        # get the index of the maximum stress
        max_force_idx = argmax(-self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = -self.Kraft[:max_force_idx + 1]
        w_ml_asc = -self.WA_ML[:max_force_idx + 1]
        w_mr_asc = -self.WA_MR[:max_force_idx + 1]
        # get the average displacement values of the corresponding displacement gauges
        w_mlmr_asc = (w_ml_asc + w_mr_asc) / 2
        axes.plot(w_mlmr_asc, f_asc, color='blue', linewidth=1)

    def _plot_force_deflection_avg(self, axes):
        '''plot the average F-w-diagramms for the center(c), center-edge (ce) and edge(vh) and edge (lr) deflections
        '''
        # get the index of the maximum stress
        max_force_idx = argmax(-self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = -self.Kraft[:max_force_idx + 1]

        w_m = -self.WA_M[:max_force_idx + 1]
        axes.plot(w_m, f_asc, color='blue', linewidth=1)

        # ## center-edge deflection (ce)
        w_ml_asc = -self.WA_ML[:max_force_idx + 1]
        w_mr_asc = -self.WA_MR[:max_force_idx + 1]
        # get the average displacement values of the corresponding displacement gauges
        w_mlmr_asc = (w_ml_asc + w_mr_asc) / 2
        axes.plot(w_mlmr_asc, f_asc, color='red', linewidth=1)

        # ## edge deflections (e)
        w_v_asc = -self.WA_V[:max_force_idx + 1]
        w_h_asc = -self.WA_H[:max_force_idx + 1]
        w_l_asc = -self.WA_L[:max_force_idx + 1]
        w_r_asc = -self.WA_R[:max_force_idx + 1]
        # get the average displacement values of the corresponding displacement gauges
        w_vh_asc = (w_v_asc + w_h_asc) / 2
        w_lr_asc = (w_l_asc + w_r_asc) / 2
        axes.plot(w_vh_asc, f_asc, color='green', linewidth=1, label='w_vh')
        axes.plot(w_lr_asc, f_asc, color='blue', linewidth=1, label='w_lr')

#        # set axis-labels
#        xkey = 'deflection [mm]'
#        ykey = 'force [kN]'
#        axes.set_xlabel('%s' % (xkey,))
#        axes.set_ylabel('%s' % (ykey,))

    def _plot_force_deflection_avg_interpolated(self, axes, linewidth=1):
        '''plot the average F-w-diagrams for the center(c), center-edge (ce) and edge(vh) and edge (lr) deflections
        NOTE: center deflection curve is cut at its starting point in order to remove offset in the dispacement meassurement
        '''
        # get the index of the maximum stress
        max_force_idx = argmax(-self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = -self.Kraft[:max_force_idx + 1]
        w_m = -self.WA_M[:max_force_idx + 1]

#        w_m -= 0.17
#        axes.plot(w_m, f_asc, color = 'blue', linewidth = 1)

        # move the starting point of the center deflection curve to the point where the force starts
        # (remove offset in measured displacement where there is still no force measured)
        #
        idx_0 = np.where(f_asc > 0.05)[0][0]

        f_asc_cut = f_asc[ idx_0: ]
        w_m_cut = w_m[ idx_0: ] - w_m[ idx_0 ]
        axes.plot(w_m_cut, f_asc_cut, color='k', linewidth=linewidth)

        # plot machine displacement (hydraulic cylinder)
        #
#        Weg_asc = -self.Weg[ :max_force_idx + 1 ]
#        axes.plot(Weg_asc, f_asc, color='k', linewidth=1.5)

        # ## center-edge deflection (ce)
        w_ml_asc = -self.WA_ML[:max_force_idx + 1]
        w_mr_asc = -self.WA_MR[:max_force_idx + 1]
        # get the average displacement values of the corresponding displacement gauges
        w_mlmr_asc = (w_ml_asc + w_mr_asc) / 2
#        axes.plot(w_mlmr_asc, f_asc, color='red', linewidth=1)
        axes.plot(w_ml_asc, f_asc, color='k', linewidth=linewidth)
        axes.plot(w_mr_asc, f_asc, color='k', linewidth=linewidth)

        # ## edge deflections (e)
        w_v_asc = -self.WA_V[:max_force_idx + 1]
        w_h_asc = -self.WA_H[:max_force_idx + 1]
        w_l_asc = -self.WA_L[:max_force_idx + 1]
        w_r_asc = -self.WA_R[:max_force_idx + 1]
        axes.plot(w_v_asc, f_asc, color='grey', linewidth=linewidth)
        axes.plot(w_h_asc, f_asc, color='grey', linewidth=linewidth)
        axes.plot(w_l_asc, f_asc, color='k', linewidth=linewidth)
        axes.plot(w_r_asc, f_asc, color='k', linewidth=linewidth)

        # get the average displacement values of the corresponding displacement gauges
#        w_vh_asc = (w_v_asc + w_h_asc) / 2
#        w_lr_asc = (w_l_asc + w_r_asc) / 2
#        axes.plot(w_vh_asc, f_asc, color='green', linewidth=1, label='w_vh')
#        axes.plot(w_lr_asc, f_asc, color='blue', linewidth=1, label='w_lr')

        # save 'F-w-arr_m-mlmr-vh-lr' in directory "/simdb/simdata/exp_st"
#        simdata_dir = os.path.join(simdb.simdata_dir, 'exp_st')
#        if os.path.isdir(simdata_dir) == False:
#            os.makedirs(simdata_dir)
#        filename = os.path.join(simdata_dir, 'F-w-arr_m-mlmr-vh-lr_' + self.key + '.csv')
#        Fw_m_mlmr_vh_lr_arr = np.hstack([f_asc[:, None], w_m[:, None] - w_m[ idx_0 ], w_mlmr_asc[:, None], w_vh_asc[:, None], w_lr_asc[:, None]])
#        print 'Fw_m_mlmr_vh_lr_arr'
#        np.savetxt(filename, Fw_m_mlmr_vh_lr_arr, delimiter=';')
#        print 'F-w-curves for center, middle, edges saved to file %s' % (filename)

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

    traits_view = View(VGroup(
                         Group(
                              Item('jump_rtol', format_str="%.4f"),
                              label='curve_ironing'
                              ),
                         Group(
                              Item('thickness', format_str="%.3f"),
                              Item('edge_length', format_str="%.3f"),
                              label='geometry'
                              ),
                         Group(
                              Item('loading_rate'),
                              Item('age'),
                              label='loading rate and age'
                              ),
                         Group(
                              Item('E_c', show_label=True, style='readonly', format_str="%.0f"),
                              Item('ccs@', show_label=False),
                              label='composite cross section'
                              )
                         ),
                        scrollable=True,
                        resizable=True,
                        height=0.8,
                        width=0.6
                        )
Exemplo n.º 26
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'])
Exemplo n.º 27
0
class ExpSH(ExType):
    '''Experiment: Shell Test
    '''
#    label = Str('slab test')
    implements(IExType)

    #--------------------------------------------------------------------
    # register a change of the traits with metadata 'input'
    #--------------------------------------------------------------------

    input_change = Event
    @on_trait_change('+input, ccs.input_change, +ironing_param')
    def _set_input_change(self):
        self.input_change = True

    #--------------------------------------------------------------------------------
    # specify inputs:
    #--------------------------------------------------------------------------------

    edge_length = Float(1.25, unit = 'm', input = True, table_field = True,
                           auto_set = False, enter_set = True)
    thickness = Float(0.03, unit = 'm', input = True, table_field = True,
                           auto_set = False, enter_set = True)

    # age of the concrete at the time of testing
    age = Int(28, unit = 'd', input = True, table_field = True,
                             auto_set = False, enter_set = True)
    loading_rate = Float(0.50, unit = 'mm/min', input = True, table_field = True,
                            auto_set = False, enter_set = True)

    #--------------------------------------------------------------------------
    # composite cross section
    #--------------------------------------------------------------------------

    ccs = Instance(CompositeCrossSection)
    def _ccs_default(self):
        '''default settings correspond to 
        setup '7u_MAG-07-03_PZ-0708-1'
        '''
        fabric_layout_key = 'MAG-07-03'
#        fabric_layout_key = '2D-02-06a'
        concrete_mixture_key = 'PZ-0708-1'
#        concrete_mixture_key = 'FIL-10-09'
#        orientation_fn_key = 'all0'                                           
        orientation_fn_key = '90_0'
        n_layers = 10
        s_tex_z = 0.030 / (n_layers + 1)
        ccs = CompositeCrossSection (
                    fabric_layup_list = [
                            plain_concrete(s_tex_z * 0.5),
                            FabricLayUp (
                                   n_layers = n_layers,
                                   orientation_fn_key = orientation_fn_key,
                                   s_tex_z = s_tex_z,
                                   fabric_layout_key = fabric_layout_key
                                   ),
                            plain_concrete(s_tex_z * 0.5)
                                        ],
                    concrete_mixture_key = concrete_mixture_key
                    )
        return ccs

    #--------------------------------------------------------------------------
    # Get properties of the composite 
    #--------------------------------------------------------------------------

    # E-modulus of the composite at the time of testing 
    E_c = Property(Float, unit = 'MPa', depends_on = 'input_change', table_field = True)
    def _get_E_c(self):
        return self.ccs.get_E_c_time(self.age)

    # E-modulus of the composite after 28 days
    E_c28 = DelegatesTo('ccs', listenable = False)

    # reinforcement ration of the composite 
    rho_c = DelegatesTo('ccs', listenable = False)

    #--------------------------------------------------------------------------------
    # define processing
    #--------------------------------------------------------------------------------

    # put this into the ironing procedure processor
    #
    jump_rtol = Float(1,
                      auto_set = False, enter_set = True,
                      ironing_param = True)


    data_array_ironed = Property(Array(float),
                                  depends_on = 'data_array, +ironing_param, +axis_selection')
    @cached_property
    def _get_data_array_ironed(self):
        '''remove the jumps in the displacement curves 
        due to resetting the displacement gauges. 
        '''
        print '*** curve ironing activated ***'

        # each column from the data array corresponds to a measured parameter 
        # e.g. displacement at a given point as function of time u = f(t))
        #
        data_array_ironed = copy(self.data_array)

        for idx in range(self.data_array.shape[1]):

            # use ironing method only for columns of the displacement gauges.
            #
            if self.names_and_units[0][ idx ] != 'Kraft' and \
                self.names_and_units[0][ idx ] != 'Bezugskanal' and \
                self.names_and_units[0][ idx ] != 'D_1o'and \
                self.names_and_units[0][ idx ] != 'D_2o'and \
                self.names_and_units[0][ idx ] != 'D_3o'and \
                self.names_and_units[0][ idx ] != 'D_4o'and \
                self.names_and_units[0][ idx ] != 'D_1u'and \
                self.names_and_units[0][ idx ] != 'D_2u'and \
                self.names_and_units[0][ idx ] != 'D_3u'and \
                self.names_and_units[0][ idx ] != 'D_4u'and \
                self.names_and_units[0][ idx ] != 'W30_vo'and \
                self.names_and_units[0][ idx ] != 'W30_hi':

                # 1d-array corresponding to column in data_array
                data_arr = copy(data_array_ironed[:, idx])

                # get the difference between each point and its successor
                jump_arr = data_arr[1:] - data_arr[0:-1]

                # get the range of the measured data 
                data_arr_range = max(data_arr) - min(data_arr)

                # determine the relevant criteria for a jump
                # based on the data range and the specified tolerances:
                jump_crit = self.jump_rtol * data_arr_range

                # get the indexes in 'data_column' after which a 
                # jump exceeds the defined tolerance criteria
                jump_idx = where(fabs(jump_arr) > jump_crit)[0]

                print 'number of jumps removed in data_arr_ironed for', self.names_and_units[0][ idx ], ': ', jump_idx.shape[0]
                # glue the curve at each jump together
                for jidx in jump_idx:
                    # get the offsets at each jump of the curve
                    shift = data_arr[jidx + 1] - data_arr[jidx]
                    # shift all succeeding values by the calculated offset
                    data_arr[jidx + 1:] -= shift

                data_array_ironed[:, idx] = data_arr[:]

        return data_array_ironed


    @on_trait_change('+ironing_param')
    def process_source_data(self):
        '''read in the measured data from file and assign
        attributes after array processing.        
        
        NOTE: if center displacement gauge ('WA_M') is missing the measured 
        displacement of the cylinder ('Weg') is used instead.
        A minor mistake is made depending on how much time passes
        before the cylinder has contact with the slab.
        '''
        print '*** process source data ***'

        self._read_data_array()
        # curve ironing:
        #
        self.processed_data_array = self.data_array_ironed

        # set attributes:
        #
        self._set_array_attribs()

    #--------------------------------------------------------------------------------
    # plot templates
    #--------------------------------------------------------------------------------

    plot_templates = {'force / time' : '_plot_force_time',
                      'force / deflections center' : '_plot_force_deflection_center',
                      'force / smoothed deflections center' : '_plot_smoothed_force_deflection_center',
                      'force / deflections' : '_plot_force_deflections',
                      'force / eps_t' : '_plot_force_eps_t',
                      'force / eps_c' : '_plot_force_eps_c',
                      'force / w_elastomer' : '_plot_force_w_elastomer',
                      'time / deflections' : '_plot_time_deflections'
                     }
    default_plot_template = 'force / time'

    def _plot_force_w_elastomer(self, axes):

        xkey = 'displacement [mm]'
        ykey = 'force [kN]'
        W_vl = self.W_vl
        W_vr = self.W_vr
        W_hl = self.W_hl
        W_hr = self.W_hr
        force = self.Kraft

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))
        axes.plot(W_vl, force)
        axes.plot(W_vr, force)
        axes.plot(W_hl, force)
        axes.plot(W_hr, force)


    def _plot_force_time(self, axes):

        xkey = 'time [s]'
        ykey = 'force [kN]'
        xdata = self.Bezugskanal
        ydata = self.Kraft

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))
        axes.plot(xdata, ydata
                       # color = c, linewidth = w, linestyle = s 
                       )

    def _plot_force_deflection_center(self, axes):

        xkey = 'deflection [mm]'
        ykey = 'force [kN]'
        xdata = -self.WD4
        ydata = self.Kraft

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))
        axes.plot(xdata, ydata
                       # color = c, linewidth = w, linestyle = s 
                       )

    n_fit_window_fraction = Float(0.1)

    def _plot_smoothed_force_deflection_center(self, axes):

        xkey = 'deflection [mm]'
        ykey = 'force [kN]'

        # get the index of the maximum stress
        max_force_idx = argmax(self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = self.Kraft[:max_force_idx + 1]
        w_asc = -self.WD4[:max_force_idx + 1]

        f_max = f_asc[-1]
        w_max = w_asc[-1]

        n_points = int(self.n_fit_window_fraction * len(w_asc))
        f_smooth = smooth(f_asc, n_points, 'flat')
        w_smooth = smooth(w_asc, n_points, 'flat')

        axes.plot(w_smooth, f_smooth, color = 'blue', linewidth = 2)

        secant_stiffness_w10 = (f_smooth[10] - f_smooth[0]) / (w_smooth[10] - w_smooth[0])
        w0_lin = array([0.0, w_smooth[10] ], dtype = 'float_')
        f0_lin = array([0.0, w_smooth[10] * secant_stiffness_w10 ], dtype = 'float_')

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))


    def _plot_force_deflections(self, axes):

        xkey = 'displacement [mm]'
        ykey = 'force [kN]'

        # get the index of the maximum stress
        max_force_idx = argmax(self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = self.Kraft[:max_force_idx + 1]

        WD1 = -self.WD1[:max_force_idx + 1]
        WD2 = -self.WD2[:max_force_idx + 1]
        WD3 = -self.WD3[:max_force_idx + 1]
        WD4 = -self.WD4[:max_force_idx + 1]
        WD5 = -self.WD5[:max_force_idx + 1]
        WD6 = -self.WD6[:max_force_idx + 1]
        WD7 = -self.WD7[:max_force_idx + 1]

        axes.plot(WD1, f_asc, color = 'blue', linewidth = 1 )
        axes.plot(WD2, f_asc, color = 'green', linewidth = 1 )
        axes.plot(WD3, f_asc, color = 'red', linewidth = 1 )
        axes.plot(WD4, f_asc, color = 'black', linewidth = 3 )
        axes.plot(WD5, f_asc, color = 'red', linewidth = 1 )
        axes.plot(WD6, f_asc, color = 'green', linewidth = 1 )
        axes.plot(WD7, f_asc, color = 'blue', linewidth = 1 )

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))


    def _plot_time_deflections(self, axes):

        xkey = 'time [s]'
        ykey = 'deflections [mm]'

        time = self.Bezugskanal

        WD1 = -self.WD1
        WD2 = -self.WD2
        WD3 = -self.WD3
        WD4 = -self.WD4
        WD5 = -self.WD5
        WD6 = -self.WD6
        WD7 = -self.WD7

        axes.plot(time, WD1, color = 'blue', linewidth = 1 )
        axes.plot(time, WD2, color = 'green', linewidth = 1 )
        axes.plot(time, WD3, color = 'red', linewidth = 1 )
        axes.plot(time, WD4, color = 'black', linewidth = 3 )
        axes.plot(time, WD5, color = 'red', linewidth = 1 )
        axes.plot(time, WD6, color = 'green', linewidth = 1 )
        axes.plot(time, WD7, color = 'blue', linewidth = 1 )

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))


    def _plot_force_eps_c(self, axes):

        xkey = 'force [kN]'
        ykey = 'strain [mm/m]'

        # get the index of the maximum stress
        max_force_idx = argmax(self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = self.Kraft[:max_force_idx + 1]
        
        D_1u = -self.D_1u[:max_force_idx + 1]
        D_2u = -self.D_2u[:max_force_idx + 1]
        D_3u = -self.D_3u[:max_force_idx + 1]
        D_4u = -self.D_4u[:max_force_idx + 1]
        
        D_1o = -self.D_1o[:max_force_idx + 1]
        D_2o = -self.D_2o[:max_force_idx + 1]
        D_3o = -self.D_3o[:max_force_idx + 1]
        D_4o = -self.D_4o[:max_force_idx + 1]

        axes.plot(f_asc, D_1u, color = 'blue', linewidth = 1 )
        axes.plot(f_asc, D_2u, color = 'blue', linewidth = 1 )
        axes.plot(f_asc, D_3u, color = 'blue', linewidth = 1 )
        axes.plot(f_asc, D_4u, color = 'blue', linewidth = 1 )

        axes.plot(f_asc, D_1o, color = 'red', linewidth = 1 )
        axes.plot(f_asc, D_2o, color = 'red', linewidth = 1 )
        axes.plot(f_asc, D_3o, color = 'red', linewidth = 1 )
        axes.plot(f_asc, D_4o, color = 'red', linewidth = 1 )

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))


    def _plot_force_eps_t(self, axes):

        xkey = 'strain [mm/m]'
        ykey = 'force [kN]'

        # get the index of the maximum stress
        max_force_idx = argmax(self.Kraft)
        # get only the ascending branch of the response curve
        f_asc = self.Kraft[:max_force_idx + 1]

        eps_vo = -self.W30_vo[:max_force_idx + 1] / 300. 
        eps_hi = -self.W30_hi[:max_force_idx + 1] / 300. 

        axes.plot(eps_vo, f_asc, color = 'blue', linewidth = 1 )
        axes.plot(eps_hi, f_asc, color = 'green', linewidth = 1 )

        axes.set_xlabel('%s' % (xkey,))
        axes.set_ylabel('%s' % (ykey,))


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

    traits_view = View(VGroup(
                         Group(
                              Item('jump_rtol', format_str = "%.4f"),
                              label = 'curve_ironing'
                              ),
                         Group(
                              Item('thickness', format_str = "%.3f"),
                              Item('edge_length', format_str = "%.3f"),
                              label = 'geometry'
                              ),
                         Group(
                              Item('loading_rate'),
                              Item('age'),
                              label = 'loading rate and age'
                              ),
                         Group(
                              Item('E_c', show_label = True, style = 'readonly', format_str = "%.0f"),
                              Item('ccs@', show_label = False),
                              label = 'composite cross section'
                              )
                         ),
                        scrollable = True,
                        resizable = True,
                        height = 0.8,
                        width = 0.6
                        )
Exemplo n.º 28
0
class InfoShellMngr( HasTraits ):
    '''Assessment tool
    '''
    #------------------------------------------
    # specify default data input files:
    #------------------------------------------

    # raw input file for thicknesses (and coordinates)
    #
    geo_data_file = Str
    def _geo_data_file_default( self ):
        return 'input_geo_data.csv'

    # raw input file for element numbers, coordinates, and stress_resultants
    #
    state_data_file = Str
    def _state_data_file_default( self ):
        return 'input_state_data.csv'

    info_shell_uls = Property( Instance( LSTable ),
                               depends_on = 'state_data_file' )
    @cached_property
    def _get_info_shell_uls( self ):
        return LSTable( geo_data = self.geo_data,
                          state_data = self.state_data,
                          ls = 'ULS' )

    info_shell_sls = Property( Instance( LSTable ),
                               depends_on = 'state_data_file' )
    @cached_property
    def _get_info_shell_sls( self ):
        return LSTable( geo_data = self.geo_data,
                          state_data = self.state_data,
                          ls = 'SLS' )

    #------------------------------------------
    # read the geometry data from file 
    # (corrds and thickness):
    #------------------------------------------

    def _read_geo_data( self, file_name ):
        '''to read the stb-thickness save the xls-worksheet 
        to a csv-file using ';' as filed delimiter and ' ' (blank)
        as text delimiter.
        '''
        # get the column headings defined in the second row 
        # of the csv thickness input file
        # "Nr.;X;Y;Z;[mm]"
        #
        file = open( file_name, 'r' )
        first_line = file.readline()
        second_line = file.readline()
        column_headings = second_line.split( ';' )
        # remove '\n' from last string element in list
        column_headings[-1] = column_headings[-1][:-1]
        column_headings_arr = array( column_headings )
        elem_no_idx = where( 'Nr.' == column_headings_arr )[0]
        X_idx = where( 'X' == column_headings_arr )[0]
        Y_idx = where( 'Y' == column_headings_arr )[0]
        Z_idx = where( 'Z' == column_headings_arr )[0]
        thickness_idx = where( '[mm]' == column_headings_arr )[0]
        # read the float data:
        #
        input_arr = loadtxt( file_name, delimiter = ';', skiprows = 2 )

        # element number:
        #
        elem_no = input_arr[:, elem_no_idx]

        # coordinates [m]:
        #
        X = input_arr[:, X_idx]
        Y = input_arr[:, Y_idx]
        Z = input_arr[:, Z_idx]

        # element thickness [mm]:
        #
        thickness = input_arr[:, thickness_idx]

        return  {'elem_no':elem_no,
                 'X':X, 'Y':Y, 'Z':Z,
                 'thickness':thickness }

    # coordinates and element thickness read from file:
    # 
    geo_data = Property( Dict, depends_on = 'geo_data_file' )
    @cached_property
    def _get_geo_data( self ):
        return self._read_geo_data( self.geo_data_file )

    #------------------------------------------
    # read the state data from file 
    # (elem_no, coords, moments and normal forces):
    #------------------------------------------

    def _Xread_state_data( self, file_name ):
        '''to read the stb-stress_resultants save the xls-worksheet 
        to a csv-file using ';' as filed delimiter and ' ' (blank)
        as text delimiter.
        '''
        ######################################################
        # this method returns only the MAXIMUM VALUES!!!
        # @todo: dublicate the elem number and coordinates and add also the minimum values
        ######################################################

        # get the column headings defined in the second row 
        # of the csv soliciotations input file
        #
#        column_headings = array(["Nr.","Punkt","X","Y","Z","mx","my","mxy","vx","vy","nx","ny","nxy"])
        file = open( file_name, 'r' )
        lines = file.readlines()
        column_headings = lines[1].split( ';' )
        # remove '\n' from last string element in list
        column_headings[-1] = column_headings[-1][:-1]
        column_headings_arr = array( column_headings )
        elem_no_idx = where( 'Nr.' == column_headings_arr )[0]
        X_idx = where( 'X' == column_headings_arr )[0]
        Y_idx = where( 'Y' == column_headings_arr )[0]
        Z_idx = where( 'Z' == column_headings_arr )[0]
        mx_idx = where( 'mx' == column_headings_arr )[0]
        my_idx = where( 'my' == column_headings_arr )[0]
        mxy_idx = where( 'mxy' == column_headings_arr )[0]
        nx_idx = where( 'nx' == column_headings_arr )[0]
        ny_idx = where( 'ny' == column_headings_arr )[0]
        nxy_idx = where( 'nxy' == column_headings_arr )[0]

        # define arrays containing the information from the raw input file
        #

        # @todo: check how loadtxt can be used directly
        #        instead of reading lines line by line?
        # input_arr = loadtxt( file_name , delimiter=';', skiprows = 2 )

        # read max-values (=first row of each double-line):
        # read stress_resultant csv-input file line by line in steps of two
        # starting in the third line returning an data array.
        #
        n_columns = len( lines[2].split( ';' ) )
        # auxiliary line in array sliced off in input array
        data_array = zeros( n_columns )
        for n in range( 2, len( lines ), 2 ):
            line_split = lines[n].split( ';' )
            line_array = array( line_split, dtype = float )
            data_array = vstack( [ data_array, line_array ] )
        input_arr = data_array[1:, :]

        # element number:
        #
        elem_no = input_arr[:, elem_no_idx]

        # coordinates [m]:
        #
        X = input_arr[:, X_idx]
        Y = input_arr[:, Y_idx]
        Z = input_arr[:, Z_idx]

        # moments [kNm/m]
        #
        mx = input_arr[:, mx_idx]
        my = input_arr[:, my_idx]
        mxy = input_arr[:, mxy_idx]

        # normal forces [kN/m]:
        #
        nx = input_arr[:, nx_idx]
        ny = input_arr[:, ny_idx]
        nxy = input_arr[:, nxy_idx]

        return { 'elem_no':elem_no, 'X':X, 'Y':Y, 'Z':Z,
                 'mx':mx, 'my':my, 'mxy':mxy,
                 'nx':nx, 'ny':ny, 'nxy':nxy }


    def _read_state_data( self, file_name ):
        '''to read the stb-stress_resultants save the xls-worksheet 
        to a csv-file using ';' as filed delimiter and ' ' (blank)
        as text delimiter.
        '''
        ######################################################
        # this method returns only the MAXIMUM VALUES!!!
        # @todo: dublicate the elem number and coordinates and add also the minimum values
        ######################################################

        # get the column headings defined in the second row 
        # of the csv solicitations input file
        #
#        column_headings = array(["Nr.","Punkt","X","Y","Z","mx","my","mxy","vx","vy","nx","ny","nxy"])
        file = open( file_name, 'r' )
        lines = file.readlines()
        column_headings = lines[1].split( ';' )
        # remove '\n' from last string element in list
        column_headings[-1] = column_headings[-1][:-1]
        column_headings_arr = array( column_headings )
        elem_no_idx = where( 'Nr.' == column_headings_arr )[0]
        X_idx = where( 'X' == column_headings_arr )[0]
        Y_idx = where( 'Y' == column_headings_arr )[0]
        Z_idx = where( 'Z' == column_headings_arr )[0]
        m1_idx = where( 'm1' == column_headings_arr )[0]
        m2_idx = where( 'm2' == column_headings_arr )[0]
        n1_idx = where( 'n1' == column_headings_arr )[0]
        n2_idx = where( 'n2' == column_headings_arr )[0]

        # define arrays containing the information from the raw input file
        #

        # @todo: check how loadtxt can be used directly
        #        instead of reading lines line by line?
        # input_arr = loadtxt( file_name , delimiter=';', skiprows = 2 )

        # read max-values (=first row of each double-line):
        # read stress_resultant csv-input file line by line in steps of two
        # starting in the third line returning an data array.
        #
        n_columns = len( lines[2].split( ';' ) )
        # auxiliary line in array sliced off in input array
        data_array = zeros( n_columns )
        for n in range( 2, len( lines ), 2 ):
            line_split = lines[n].split( ';' )
            line_array = array( line_split, dtype = float )
            data_array = vstack( [ data_array, line_array ] )
        input_arr = data_array[1:, :]

        # element number:
        #
        elem_no = input_arr[:, elem_no_idx]

        # coordinates [m]:
        #
        X = input_arr[:, X_idx]
        Y = input_arr[:, Y_idx]
        Z = input_arr[:, Z_idx]

        # moments [kNm/m]
        #
        mx = input_arr[:, m1_idx]
        my = input_arr[:, m2_idx]
        mxy = zeros_like( input_arr[:, m1_idx] )

        # normal forces [kN/m]:
        #
        nx = input_arr[:, n1_idx]
        ny = input_arr[:, n2_idx]
        nxy = zeros_like( input_arr[:, m1_idx] )

        return { 'elem_no':elem_no, 'X':X, 'Y':Y, 'Z':Z,
                 'mx':mx, 'my':my, 'mxy':mxy,
                 'nx':nx, 'ny':ny, 'nxy':nxy }

    # ------------------------------------------------------------
    # Read state data from file and assign attributes 
    # ------------------------------------------------------------

    # coordinates and stress_resultants read from file:
    # 
    state_data = Property( Dict, depends_on = 'state_data_file' )
    @cached_property
    def _get_state_data( self ):
        return self._read_state_data( self.state_data_file )


    # ------------------------------------------------------------
    # check input files for consistency
    # ------------------------------------------------------------

    @on_trait_change( 'geo_data_file, state_data_file' )
    def _check_input_files_for_consistency( self ):
        '''check if the element order of the thickness input file is 
        identical to the order in the stress_resultant input file
        '''
        if not all( self.geo_data['X'] ) == all( self.state_data['X'] ) or \
            not all( self.geo_data['Y'] ) == all( state_data['Y'] ) or \
            not all( self.geo_data['Z'] ) == all( state_data['Z'] ):
            raise ValueError, 'coordinates in file % s and file % s are not identical. Check input files for consistency ! ' \
                    % ( self.geo_data_file, self.state_data_file )
        else:
            print ' *** input files checked for consistency ( OK ) *** '
            return True


    # ------------------------------------------------------------
    # View 
    # ------------------------------------------------------------

    traits_view = View( VGroup( 
                              Item( 'state_data_file',
                              label = 'Evaluated input file for stress_resultants ',
                              style = 'readonly', emphasized = True ),

                        Item( 'geo_data_file',
                              label = 'Evaluated input file for thicknesses ',
                               style = 'readonly', emphasized = True ),
                        Tabbed( 
                        Group( 
                        Item( 'info_shell_sls@', show_label = False ),
                            label = 'SLS' ),
                        Group( 
                        Item( 'info_shell_uls@', show_label = False ),
                            label = 'ULS' ),
                            ),
                        ),
                      resizable = True,
                      scrollable = True,
                      height = 1000,
                      width = 1100
                      )
Exemplo n.º 29
0
class ECBMatrixCrossSection(ECBCrossSectionComponent):
    '''Cross section characteristics needed for tensile specimens.
    '''

    n_cj = Float(30, auto_set=False, enter_set=True, geo_input=True)
    '''Number of integration points.
    '''

    f_ck = Float(55.7, auto_set=False, enter_set=True, cc_input=True)
    '''Ultimate compression stress  [MPa]
    '''

    eps_c_u = Float(0.0033, auto_set=False, enter_set=True, cc_input=True)
    '''Strain at failure of the matrix in compression [-]
    '''

    height = Float(0.4, auto_set=False, enter_set=True, geo_input=True)
    '''height of the cross section [m]
    '''

    width = Float(0.20, auto_set=False, enter_set=True, geo_input=True)
    '''width of the cross section [m]
    '''

    x = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE)
    '''Height of the compressive zone
    '''
    @cached_property
    def _get_x(self):
        eps_lo = self.state.eps_lo
        eps_up = self.state.eps_up
        if eps_up == eps_lo:
            # @todo: explain
            return (abs(eps_up) / (abs(eps_up - eps_lo * 1e-9)) * self.height)
        else:
            return (abs(eps_up) / (abs(eps_up - eps_lo)) * self.height)

    z_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE)
    '''Discretizaton of the  compressive zone
    '''

    @cached_property
    def _get_z_ti_arr(self):
        if self.state.eps_up <= 0:  # bending
            zx = min(self.height, self.x)
            return np.linspace(0, zx, self.n_cj)
        elif self.state.eps_lo <= 0:  # bending
            return np.linspace(self.x, self.height, self.n_cj)
        else:  # no compression
            return np.array([0], dtype='f')

    eps_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE)
    '''Compressive strain at each integration layer of the compressive zone [-]:
    '''

    @cached_property
    def _get_eps_ti_arr(self):
        # for calibration us measured compressive strain
        # @todo: use mapped traits instead
        #
        height = self.height
        eps_up = self.state.eps_up
        eps_lo = self.state.eps_lo
        eps_j_arr = (eps_up + (eps_lo - eps_up) * self.z_ti_arr / height)
        return (-np.fabs(eps_j_arr) + eps_j_arr) / 2.0

    zz_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE)
    '''Distance of reinforcement layers from the bottom
    '''

    @cached_property
    def _get_zz_ti_arr(self):
        return self.height - self.z_ti_arr

    #===========================================================================
    # Compressive concrete constitutive law
    #===========================================================================

    cc_law_type = Trait('constant',
                        dict(constant=CCLawBlock,
                             linear=CCLawLinear,
                             quadratic=CCLawQuadratic,
                             quad=CCLawQuad),
                        cc_input=True)
    '''Selector of the concrete compression law type
    ['constant', 'linear', 'quadratic', 'quad']'''

    cc_law = Property(Instance(CCLawBase), depends_on='+cc_input')
    '''Compressive concrete law corresponding to cc_law_type'''

    @cached_property
    def _get_cc_law(self):
        return self.cc_law_type_(f_ck=self.f_ck, eps_c_u=self.eps_c_u, cs=self)

    show_cc_law = Button
    '''Button launching a separate view of the compression law.
    '''

    def _show_cc_law_fired(self):
        cc_law_mw = ConstitutiveLawModelView(model=self.cc_law)
        cc_law_mw.edit_traits(kind='live')
        return

    cc_modified = Event

    #===========================================================================
    # Calculation of compressive stresses and forces
    #===========================================================================

    sig_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE)
    '''Stresses at the j-th integration point.
    '''

    @cached_property
    def _get_sig_ti_arr(self):
        return -self.cc_law.mfn_vct(-self.eps_ti_arr)

    f_ti_arr = Property(depends_on=ECB_COMPONENT_AND_EPS_CHANGE)
    '''Layer force corresponding to the j-th integration point.
    '''

    @cached_property
    def _get_f_ti_arr(self):
        return self.width * self.sig_ti_arr * self.unit_conversion_factor

    def _get_N(self):
        return np.trapz(self.f_ti_arr, self.z_ti_arr)

    def _get_M(self):
        return np.trapz(self.f_ti_arr * self.z_ti_arr, self.z_ti_arr)

    modified = Event

    @on_trait_change('+geo_input')
    def set_modified(self):
        self.modified = True

    view = View(HGroup(
        Group(Item('height', springy=True),
              Item('width'),
              Item('n_layers'),
              Item('n_rovings'),
              Item('A_roving'),
              label='Geometry',
              springy=True),
        springy=True,
    ),
                resizable=True,
                buttons=['OK', 'Cancel'])
Exemplo n.º 30
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)