Esempio 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
                    )
Esempio n. 2
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
Esempio n. 3
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)
Esempio n. 4
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)
Esempio n. 5
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 )
Esempio n. 6
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'])
Esempio n. 7
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
Esempio n. 8
0
class ImageProcessing(HasTraits):
    def __init__(self, **kw):
        super(ImageProcessing, self).__init__(**kw)
        self.on_trait_change(self.refresh, '+params')
        self.refresh()

    image_path = Str

    def rgb2gray(self, rgb):
        return np.dot(rgb[..., :3], [0.299, 0.587, 0.144])

    filter = Bool(False, params=True)
    block_size = Range(1, 100, params=True)
    offset = Range(1, 20, params=True)
    denoise = Bool(False, params=True)
    denoise_spatial = Range(1, 100, params=True)

    processed_image = Property

    def _get_processed_image(self):
        # read image
        image = mpimg.imread(self.image_path)
        mask = image[:, :, 1] > 150.
        image[mask] = 255.
        #plt.imshow(image)
        #plt.show()
        # convert to grayscale
        image = self.rgb2gray(image)
        # crop image
        image = image[100:1000, 200:1100]
        mask = mask[100:1000, 200:1100]
        image = image - np.min(image)
        image[mask] *= 255. / np.max(image[mask])
        if self.filter == True:
            image = denoise_bilateral(image,
                                      sigma_spatial=self.denoise_spatial)
        if self.denoise == True:
            image = threshold_adaptive(image,
                                       self.block_size,
                                       offset=self.offset)
        return image, mask

    edge_detection_method = Enum('canny', 'sobel', 'roberts', params=True)
    canny_sigma = Range(2.832, 5, params=True)
    canny_low = Range(5.92, 100, params=True)
    canny_high = Range(0.1, 100, params=True)

    edges = Property

    def _get_edges(self):
        img_edg, mask = self.processed_image
        if self.edge_detection_method == 'canny':
            img_edg = canny(img_edg,
                            sigma=self.canny_sigma,
                            low_threshold=self.canny_low,
                            high_threshold=self.canny_high)
        elif self.edge_detection_method == 'roberts':
            img_edg = roberts(img_edg)
        elif self.edge_detection_method == 'sobel':
            img_edg = sobel(img_edg)
        img_edg = img_edg > 0.0
        return img_edg

    radii = Int(80, params=True)
    radius_low = Int(40, params=True)
    radius_high = Int(120, params=True)
    step = Int(2, params=True)

    hough_circles = Property

    def _get_hough_circles(self):
        hough_radii = np.arange(self.radius_low, self.radius_high,
                                self.step)[::-1]
        hough_res = hough_circle(self.edges, hough_radii)
        centers = []
        accums = []
        radii = []  # For each radius, extract num_peaks circles
        num_peaks = 3
        for radius, h in zip(hough_radii, hough_res):
            peaks = peak_local_max(h, num_peaks=num_peaks)
            centers.extend(peaks)
            print 'circle centers = ', peaks
            accums.extend(h[peaks[:, 0], peaks[:, 1]])
            radii.extend([radius] * num_peaks)

        im = mpimg.imread(self.image_path)
        # crop image
        im = im[100:1000, 200:1100]
        for idx in np.arange(len(centers)):
            center_x, center_y = centers[idx]
            radius = radii[idx]
            cx, cy = circle_perimeter(center_y, center_x, radius)
            mask = (cx < im.shape[0]) * (cy < im.shape[1])
            im[cy[mask], cx[mask]] = (220., 20., 20.)
        return im

    eval_edges = Button

    def _eval_edges_fired(self):
        edges = self.figure_edges
        edges.clear()
        axes_edges = edges.gca()
        axes_edges.imshow(self.edges, plt.gray())
        self.data_changed = True

    eval_circles = Button

    def _eval_circles_fired(self):
        circles = self.figure_circles
        circles.clear()
        axes_circles = circles.gca()
        axes_circles.imshow(self.hough_circles, plt.gray())
        self.data_changed = True

    figure = Instance(Figure)

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

    figure_edges = Instance(Figure)

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

    figure_circles = Instance(Figure)

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

    data_changed = Event

    def plot(self, fig, fig2):
        figure = fig
        figure.clear()
        axes = figure.gca()
        img, mask = self.processed_image
        axes.imshow(img, plt.gray())

    def refresh(self):
        self.plot(self.figure, self.figure_edges)
        self.data_changed = True

    traits_view = View(HGroup(
        Group(Item('filter', label='filter'),
              Item('block_size'),
              Item('offset'),
              Item('denoise', label='denoise'),
              Item('denoise_spatial'),
              label='Filters'),
        Group(
            Item('figure',
                 editor=MPLFigureEditor(),
                 show_label=False,
                 resizable=True),
            scrollable=True,
            label='Plot',
        ),
    ),
                       Tabbed(
                           VGroup(Item('edge_detection_method'),
                                  Item('canny_sigma'),
                                  Item('canny_low'),
                                  Item('canny_high'),
                                  Item('eval_edges', label='Evaluate'),
                                  Item('figure_edges',
                                       editor=MPLFigureEditor(),
                                       show_label=False,
                                       resizable=True),
                                  scrollable=True,
                                  label='Plot_edges'), ),
                       Tabbed(
                           VGroup(Item('radii'),
                                  Item('radius_low'),
                                  Item('radius_high'),
                                  Item('step'),
                                  Item('eval_circles'),
                                  Item('figure_circles',
                                       editor=MPLFigureEditor(),
                                       show_label=False,
                                       resizable=True),
                                  scrollable=True,
                                  label='Plot_circles'), ),
                       id='imview',
                       dock='tab',
                       title='Image processing',
                       scrollable=True,
                       resizable=True,
                       width=600,
                       height=400)
class 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'])
Esempio n. 10
0
class SPIRRIDModelView(ModelView):

    title = Str('spirrid exec ctrl')

    model = Instance(SPIRRID)

    ins = Instance(NoOfFibers)

    def _ins_default(self):
        return NoOfFibers()

    eval = Button

    def _eval_fired(self):

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

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

    def _run_fired(self):
        self.evaluate()

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

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

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

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

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

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

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

    stdev = Bool(True)

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

    data_changed = Event(True)

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

        # evaluate the mean curve
        self.model.mean_curve

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

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

    body_tex = Str()

    data = Instance(YMBData, changed=True)

    yarn = Property(Str, depends_on='+changed')

    @cached_property
    def _get_yarn(self):
        return self.data.source.yarn_type

    data_dir = Property(Str, depends_on='+changed')

    def _get_data_dir(self):
        return join(simdb.exdata_dir, 'trc', 'yarn_structure', self.yarn,
                    'raw_data')

    tex_dir = Property(Str, depends_on='+changed')

    def _get_tex_dir(self):
        return join(simdb.exdata_dir, 'trc', 'yarn_structure', self.yarn,
                    'report')

    fig_dir = Property(Str, depends_on='+changed')

    def _get_fig_dir(self):
        return join(simdb.exdata_dir, 'trc', 'yarn_structure', self.yarn,
                    'report', 'figs')

    # select data for report
    plot_3d_on = Bool(True)
    hist_rad_on = Bool(True)
    hist_cf_on = Bool(True)
    hist_bfl_on = Bool(True)
    hist_slack_on = Bool(True)
    corr_plot_rad_on = Bool(True)
    corr_plot_cf_on = Bool(True)
    corr_plot_bfl_on = Bool(True)
    corr_plot_slack_on = Bool(True)
    spirrid_on = Bool(False)

    hist_axes_adjust = List([0.12, 0.17, 0.68, 0.68])
    corr_axes_adjust = List([0.15, 0.17, 0.75, 0.68])
    n_bins = Int(40)

    #################################
    # BUILD REPORT
    #################################

    build = Button(label='build report')

    def _build_fired(self):
        self._directory_test()

        # get the yarn type
        yt = self.data.source.yarn_type

        if self.plot_3d_on == True:
            self._save_plot3d_fired()
        if self.hist_rad_on == True:
            self._save_rad_fired()
        if self.hist_cf_on == True:
            self._save_cf_fired()
        if self.hist_bfl_on == True:
            self._save_bfl_fired()
        if self.hist_slack_on == True:

            self._save_slack_fired()
        if self.corr_plot_rad_on == True:
            self._save_corr_plot_rad_fired()
        if self.corr_plot_cf_on == True:
            self._save_corr_plot_cf_fired()
        if self.corr_plot_bfl_on == True:
            self._save_corr_plot_bfl_fired()
        if self.corr_plot_slack_on == True:
            self._save_corr_plot_slack_fired()

        print '================'
        print 'Figure(s) saved'
        print '================'

        #################################
        # BUILD REPORT
        #################################

        filename = 'ymb_report_' + yt
        texfile = join(self.tex_dir, filename + '.tex')
        pdffile = join(self.tex_dir, filename + '.pdf')

        bodyfile = join(self.tex_dir, texfile)
        body_out = open(bodyfile, 'w')

        self.body_tex += 'Yarn with contact fraction limit = %s\n' % self.data.cf_limit

        if self.plot_3d_on == True:
            self.body_tex += self.plot3d_tex
        if self.hist_rad_on == True:
            self.body_tex += self.rad_tex
        if self.hist_cf_on == True:
            self.body_tex += self.cf_tex
        if self.hist_bfl_on == True:
            self.body_tex += self.bfl_tex
        if self.hist_slack_on == True:
            self.body_tex += self.slack_tex
        if self.corr_plot_rad_on == True:
            self.body_tex += self.corr_plot_rad_tex
        if self.corr_plot_cf_on == True:
            self.body_tex += self.corr_plot_cf_tex
        if self.corr_plot_bfl_on == True:
            self.body_tex += self.corr_plot_bfl_tex
        if self.corr_plot_slack_on == True:
            self.body_tex += self.corr_plot_slack_tex

        body_out.write(start_tex)
        body_out.write('\section*{ Yarn %s }' % (self.yarn))
        body_out.write(self.body_tex)
        body_out.write(end_tex)
        body_out.close()
        os.system('cd ' + self.tex_dir + ';pdflatex -shell-escape ' + texfile)
        print '=============================='
        print 'Report written to %s', texfile
        print '=============================='
        os.system('acroread ' + pdffile + ' &')

    #################################
    # 3d PLOT
    #################################

    plot3d = Property(Instance(YMBView3D))

    @cached_property
    def _get_plot3d(self):
        plot3d = YMBView3D(data=self.data, color_map='binary')  # black-white
        return plot3d

    save_plot3d = Button(label='save plot3d figure')

    def _save_plot3d_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'plot3d.png')
        self.plot3d.scene.save(filename, (1000, 800))

    plot3d_tex = Property(Str)

    @cached_property
    def _get_plot3d_tex(self):
        filename = 'plot3d.png'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, '3D yarn plot')
        else:
            self._save_plot3d_fired()
            return fig_tex % (filename, '3D yarn plot')

    #################################
    # HISTOGRAM PLOT AND SAVE
    #################################

    hist_rad = Property(Instance(YMBHist))  # Instance(Figure )

    @cached_property
    def _get_hist_rad(self):
        histog = YMBHist()
        histog.set(edge_color='black',
                   face_color='0.75',
                   axes_adjust=self.hist_axes_adjust)
        slider = YMBSlider(var_enum='radius', data=self.data)
        return histog.set(slider=slider, bins=self.n_bins, normed_on=True)

    save_rad = Button(label='save histogram of radius')

    def _save_rad_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'radius.pdf')
        self.hist_rad.figure.savefig(filename, format='pdf')

    rad_tex = Property(Str)

    @cached_property
    def _get_rad_tex(self):
        filename = 'radius.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Histogram of filament radius')
        else:
            self._save_rad_fired()
            return fig_tex % (filename, 'Histogram of filament radius')

    hist_cf = Property(Instance(YMBHist))

    @cached_property
    def _get_hist_cf(self):
        histog = YMBHist()
        histog.set(edge_color='black',
                   face_color='0.75',
                   axes_adjust=self.hist_axes_adjust)
        slider = YMBSlider(var_enum='contact fraction', data=self.data)
        return histog.set(slider=slider, bins=self.n_bins, normed_on=True)

    save_cf = Button(label='save histogram of contact fraction')

    def _save_cf_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'contact_fraction.pdf')
        self.hist_cf.figure.savefig(filename, format='pdf')

    cf_tex = Property(Str)

    @cached_property
    def _get_cf_tex(self):
        filename = 'contact_fraction.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Histogram of contact fraction')
        else:
            self._save_cf_fired()
            return fig_tex % (filename, 'Histogram of contact fraction')

    hist_bfl = Property(Instance(YMBHist))

    @cached_property
    def _get_hist_bfl(self):
        histog = YMBHist()
        histog.set(edge_color='black',
                   face_color='0.75',
                   axes_adjust=self.hist_axes_adjust)
        slider = YMBSlider(var_enum='bond free length', data=self.data)
        return histog.set(slider=slider, bins=self.n_bins, normed_on=True)

    save_bfl = Button(label='save histogram of bond free length')

    def _save_bfl_fired(self):
        self._directory_test()
        filename = 'bond_free_length.pdf'
        self.hist_bfl.figure.savefig(join(self.fig_dir, filename),
                                     format='pdf')

    bfl_tex = Property(Str)

    @cached_property
    def _get_bfl_tex(self):
        filename = 'bond_free_length.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Histogram of bond free length')
        else:
            self._save_bfl_fired()
            return fig_tex % (filename, 'Histogram of bond free length')

    hist_slack = Property(Instance(YMBHist))

    @cached_property
    def _get_hist_slack(self):
        histog = YMBHist()
        histog.set(edge_color='black',
                   face_color='0.75',
                   axes_adjust=self.hist_axes_adjust)
        slider = YMBSlider(var_enum='slack', data=self.data)
        return histog.set(slider=slider,
                          bins=self.n_bins,
                          normed_on=True,
                          xlimit_on=True,
                          xlimit=0.03)

    save_slack = Button(label='save histogram of slack')

    def _save_slack_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'slack.pdf')
        self.hist_slack.figure.savefig(filename, format='pdf')

    slack_tex = Property(Str)

    @cached_property
    def _get_slack_tex(self):
        filename = 'slack.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Histogram of slack')
        else:
            self._save_slack_fired()
            return fig_tex % (filename, 'Histogram of slack')

    corr_plot_rad = Property(Instance(YMBAutoCorrel))

    @cached_property
    def _get_corr_plot_rad(self):
        plot = YMBAutoCorrelView()
        plot.set(color='black', axes_adjust=self.corr_axes_adjust)
        return plot.set(
            correl_data=YMBAutoCorrel(data=data, var_enum='radius'))

    save_corr_plot_rad = Button(label='save correlation plot of radius')

    def _save_corr_plot_rad_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'corr_plot_rad.pdf')
        self.corr_plot_rad.figure.savefig(filename, format='pdf')

    corr_plot_rad_tex = Property(Str)

    @cached_property
    def _get_corr_plot_rad_tex(self):
        filename = 'corr_plot_rad.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Autocorrelation of radius')
        else:
            self._save_corr_plot_rad_fired()
            return fig_tex % (filename, 'Autocorrelation of radius')

    corr_plot_cf = Property(Instance(YMBAutoCorrel))

    @cached_property
    def _get_corr_plot_cf(self):
        plot = YMBAutoCorrelView()
        plot.set(color='black', axes_adjust=self.corr_axes_adjust)
        return plot.set(
            correl_data=YMBAutoCorrel(data=data, var_enum='contact fraction'))

    save_corr_plot_cf = Button(
        label='save correlation plot of contact fraction')

    def _save_corr_plot_cf_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'corr_plot_cf.pdf')
        self.corr_plot_cf.figure.savefig(filename, format='pdf')

    corr_plot_cf_tex = Property(Str)

    @cached_property
    def _get_corr_plot_cf_tex(self):
        filename = 'corr_plot_cf.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Autocorrelation of contact fraction')
        else:
            self._save_corr_plot_cf_fired()
            return fig_tex % (filename, 'Autocorrelation of contact fraction')

    corr_plot_bfl = Property(Instance(YMBAutoCorrel))

    @cached_property
    def _get_corr_plot_bfl(self):
        plot = YMBAutoCorrelView()
        plot.set(color='black', axes_adjust=self.corr_axes_adjust)
        return plot.set(
            correl_data=YMBAutoCorrel(data=data, var_enum='bond free length'))

    save_corr_plot_bfl = Button(label='save corr plot of bond free length')

    def _save_corr_plot_bfl_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'corr_plot_bfl.pdf')
        self.corr_plot_bfl.figure.savefig(filename, format='pdf')

    corr_plot_bfl_tex = Property(Str)

    @cached_property
    def _get_corr_plot_bfl_tex(self):
        filename = 'corr_plot_bfl.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Autocorrelation of bond free length')
        else:
            self._save_corr_plot_bfl_fired()
            return fig_tex % (filename, 'Autocorrelation of bond free length')

    corr_plot_slack = Property(Instance(YMBAutoCorrel))

    @cached_property
    def _get_corr_plot_slack(self):
        plot = YMBAutoCorrelView()
        plot.set(color='black', axes_adjust=self.corr_axes_adjust)
        return plot.set(correl_data=YMBAutoCorrel(data=data, var_enum='slack'))

    save_corr_plot_slack = Button(label='save corr plot of slack')

    def _save_corr_plot_slack_fired(self):
        self._directory_test()
        filename = join(self.fig_dir, 'corr_plot_slack.pdf')
        self.corr_plot_slack.figure.savefig(filename, format='pdf')

    corr_plot_slack_tex = Property(Str)

    @cached_property
    def _get_corr_plot_slack_tex(self):
        filename = 'corr_plot_slack.pdf'
        if file_test(join(self.fig_dir, filename)) == True:
            return fig_tex % (filename, 'Autocorrelation of slack')
        else:
            self._save_corr_plot_slack_fired()
            return fig_tex % (filename, 'Autocorrelation of slack')

    #################################
    # CORRELATION PLOT AND TABLE
    #################################

    def corr_plot(self):
        return 0

    #################################
    # SPIRRID PLOT
    #################################

    spirrid_plot = Property(Instance(YMBPullOut))

    @cached_property
    def _get_spirrid_plot(self):
        return YMBPullOut(data=self.data)

    pdf_theta = Property(Instance(IPDistrib))

    def _get_pdf_theta(self):
        theta = self.spirrid_plot.pdf_theta
        # theta.set( face_color = '0.75', edge_color = 'black', axes_adjust = [0.13, 0.18, 0.8, 0.7] )
        return theta

    pdf_l = Property(Instance(IPDistrib))

    def _get_pdf_l(self):
        return self.spirrid_plot.pdf_l

    pdf_phi = Property(Instance(IPDistrib))

    def _get_pdf_phi(self):
        return self.spirrid_plot.pdf_phi

    pdf_xi = Property(Instance(IPDistrib))

    def _get_pdf_xi(self):
        return self.spirrid_plot.pdf_xi.figure

    def _directory_test(self):
        if os.access(self.tex_dir, os.F_OK) == False:
            os.mkdir(self.tex_dir)
        if os.access(self.fig_dir, os.F_OK) == False:
            os.mkdir(self.fig_dir)

    traits_view = View(
        HSplit(
            Group(
                Item('data@', show_label=False),
                HGroup(
                    VGrid(
                        Item(
                            'plot_3d_on',
                            label='plot3d',
                        ),
                        Item('save_plot3d',
                             show_label=False,
                             visible_when='plot_3d_on == True'),
                        Item('_'),
                        Item('hist_rad_on', label='radius_hist'),
                        Item('save_rad',
                             show_label=False,
                             visible_when='hist_rad_on == True'),
                        Item('hist_cf_on', label='cf_hist'),
                        Item('save_cf',
                             show_label=False,
                             visible_when='hist_cf_on == True'),
                        Item('hist_bfl_on', label='bfl_hist'),
                        Item('save_bfl',
                             show_label=False,
                             visible_when='hist_bfl_on == True'),
                        Item('hist_slack_on', label='slack_hist'),
                        Item('save_slack',
                             show_label=False,
                             visible_when='hist_slack_on == True'),
                        Item('_'),
                        Item('corr_plot_rad_on', label='corr_plot_rad'),
                        Item('save_corr_plot_rad',
                             show_label=False,
                             visible_when='hist_slack_on == True'),
                        Item('corr_plot_cf_on', label='corr_plot_cf'),
                        Item('save_corr_plot_cf',
                             show_label=False,
                             visible_when='hist_slack_on == True'),
                        Item('corr_plot_bfl_on', label='corr_plot_bfl'),
                        Item('save_corr_plot_bfl',
                             show_label=False,
                             visible_when='hist_slack_on == True'),
                        Item('corr_plot_slack_on', label='corr_plot_slack'),
                        Item('save_corr_plot_slack',
                             show_label=False,
                             visible_when='hist_slack_on == True'),
                    ),
                    VGrid(Item('spirrid_on'), ),
                ),
                Item('build'),
                label='report',
                id='report.bool',
            ), ),
        VGroup(
            HGroup(
                Item('hist_rad@', show_label=False),
                Item('hist_cf@', show_label=False),
            ),
            HGroup(
                Item('hist_bfl@', show_label=False),
                Item('hist_slack@', show_label=False),
            ),
            label='histograms',
            id='report.hist',
        ),
        VGroup(
            HGroup(
                Item('corr_plot_rad@', show_label=False),
                Item('corr_plot_cf@', show_label=False),
            ),
            HGroup(
                Item('corr_plot_bfl@', show_label=False),
                Item('corr_plot_slack@', show_label=False),
            ),
            label='correlation plot',
            id='report.corr_plot',
        ),

        #                HGroup(
        #                Group(
        #                Item( 'pdf_theta@', show_label = False ),
        #                Item( 'pdf_l@', show_label = False ),
        #                ),
        #                Group(
        #                Item( 'pdf_phi@', show_label = False ),
        #                Item( 'pdf_xi@', show_label = False ),
        #                ),
        #                label = 'pdf',
        #                id = 'report.pdf',
        #                #scrollable = True,
        #                ),
        Group(Item('plot3d@', show_label=False),
              label='plot3d',
              id='report.plot3d'),
        resizable=True,
        title=u"Yarn name",
        handler=TitleHandler(),
        id='report.main',
    )
Esempio n. 12
0
class ECBLMNDiagram(HasTraits):

    # calibrator supplying the effective material law
    calib = Instance(ECBLCalib)

    def _calib_default(self):
        return ECBLCalib(notify_change=self.set_modified)

    def _calib_changed(self):
        self.calib.notify_change = self.set_modified

    modified = Event

    def set_modified(self):
        print 'MN:set_modifeid'
        self.modified = True

    # cross section
    cs = DelegatesTo('calib')

    calibrated_ecb_law = Property(depends_on='modified')

    @cached_property
    def _get_calibrated_ecb_law(self):
        print 'NEW CALIBRATION'
        return self.calib.calibrated_ecb_law

    eps_cu = Property()

    def _get_eps_cu(self):
        return -self.cs.cc_law.eps_c_u

    eps_tu = Property()

    def _get_eps_tu(self):
        return self.calibrated_ecb_law.eps_tex_u

    n_eps = Int(5, auto_set=False, enter_set=True)
    eps_range = Property(depends_on='n_eps')

    @cached_property
    def _get_eps_range(self):
        eps_c_space = np.linspace(self.eps_cu, 0, self.n_eps)
        eps_t_space = np.linspace(0, self.eps_tu, self.n_eps)

        eps_ccu = 0.8 * self.eps_cu

        #eps_cc = self.eps_cu * np.ones_like(eps_c_space)
        eps_cc = np.linspace(eps_ccu, self.eps_cu, self.n_eps)
        eps_ct = self.eps_cu * np.ones_like(eps_t_space)
        eps_tc = self.eps_tu * np.ones_like(eps_c_space)
        eps_tt = self.eps_tu * np.ones_like(eps_t_space)

        eps1 = np.vstack([eps_c_space, eps_cc])
        eps2 = np.vstack([eps_t_space, eps_ct])
        eps3 = np.vstack([eps_tc, eps_c_space])
        eps4 = np.vstack([eps_tt, eps_t_space])

        return np.hstack([eps1, eps2, eps3, eps4])

    n_eps_range = Property(depends_on='n_eps')

    @cached_property
    def _get_n_eps_range(self):
        return self.eps_range.shape[1]

    #===========================================================================
    # MN Diagram
    #===========================================================================

    def _get_MN_fn(self, eps_lo, eps_up):
        self.cs.set(eps_lo=eps_lo, eps_up=eps_up)
        return (self.cs.M, self.cs.N)

    MN_vct = Property(depends_on='modified')

    def _get_MN_vct(self):
        return np.vectorize(self._get_MN_fn)

    MN_arr = Property(depends_on='modified')

    @cached_property
    def _get_MN_arr(self):
        return self.MN_vct(self.eps_range[0, :], self.eps_range[1, :])

    #===========================================================================
    # f_eps Diagram
    #===========================================================================

    current_eps_idx = Int(0)  # , auto_set = False, enter_set = True)

    def _current_eps_idx_changed(self):
        self._clear_fired()
        self._replot_fired()

    current_eps = Property(depends_on='current_eps_idx')

    @cached_property
    def _get_current_eps(self):
        return self.eps_range[(0, 1), self.current_eps_idx]

    current_MN = Property(depends_on='current_eps_idx')

    @cached_property
    def _get_current_MN(self):
        return self._get_MN_fn(*self.current_eps)

    #===========================================================================
    # Plotting
    #===========================================================================

    figure = Instance(Figure)

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

    data_changed = Event

    clear = Button

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

    replot = Button

    def _replot_fired(self):

        ax = self.figure.add_subplot(2, 2, 1)

        ax.plot(-self.eps_range, [0, 0.06], color='black')

        ax.plot(-self.current_eps, [0, 0.06], lw=3, color='red')

        ax.spines['left'].set_position('zero')
        ax.spines['right'].set_color('none')
        ax.spines['top'].set_color('none')
        ax.spines['left'].set_smart_bounds(True)
        ax.spines['bottom'].set_smart_bounds(True)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')

        ax = self.figure.add_subplot(2, 2, 2)

        ax.plot(self.MN_arr[0], -self.MN_arr[1], lw=2, color='blue')

        ax.plot(self.current_MN[0],
                -self.current_MN[1],
                'g.',
                markersize=20.0,
                color='red')

        ax.spines['left'].set_position('zero')
        ax.spines['bottom'].set_position('zero')
        ax.spines['right'].set_color('none')
        ax.spines['top'].set_color('none')
        ax.spines['left'].set_smart_bounds(True)
        ax.spines['bottom'].set_smart_bounds(True)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        ax.grid(b=None, which='major')

        self.cs.set(eps_lo=self.current_eps[0], eps_up=self.current_eps[1])

        ax = self.figure.add_subplot(2, 2, 3)

        self.cs.plot_eps(ax)

        ax = self.figure.add_subplot(2, 2, 4)

        self.cs.plot_sig(ax)

        self.data_changed = True

    view = View(HSplit(
        Group(
            HGroup(
                Group(Item('n_eps', springy=True),
                      label='Discretization',
                      springy=True),
                springy=True,
            ),
            HGroup(
                Group(VGroup(
                    Item(
                        'cs',
                        label='Cross section',
                        show_label=False,
                        springy=True,
                        editor=InstanceEditor(kind='live'),
                    ),
                    Item(
                        'calib',
                        label='Calibration',
                        show_label=False,
                        springy=True,
                        editor=InstanceEditor(kind='live'),
                    ),
                    springy=True,
                ),
                      label='Cross sectoin',
                      springy=True),
                springy=True,
            ),
            scrollable=True,
        ),
        Group(
            HGroup(
                Item('replot', show_label=False),
                Item('clear', show_label=False),
            ),
            Item(
                'current_eps_idx',
                editor=RangeEditor(
                    low=0,
                    high_name='n_eps_range',
                    format='(%s)',
                    mode='slider',
                    auto_set=False,
                    enter_set=False,
                ),
                show_label=False,
            ),
            Item('figure',
                 editor=MPLFigureEditor(),
                 resizable=True,
                 show_label=False),
            id='simexdb.plot_sheet',
            label='plot sheet',
            dock='tab',
        ),
    ),
                width=1.0,
                height=0.8,
                resizable=True,
                buttons=['OK', 'Cancel'])
Esempio n. 13
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'])
Esempio n. 14
0
class LS(HasTraits):
    '''Limit state class
    '''

    # backward link to the info shell to access the
    # input data when calculating
    # the limit-state-specific values
    #
    ls_table = WeakRef

    # parameters of the limit state
    #
    dir = Enum(DIRLIST)
    stress_res = Enum(SRLIST)

    #-------------------------------
    # ls columns
    #-------------------------------
    # defined in the subclasses
    #
    ls_columns = List
    show_ls_columns = Bool(True)

    #-------------------------------
    # sr columns
    #-------------------------------

    # stress resultant columns - for ULS this is defined in the subclasses
    #
    sr_columns = List(['m', 'n'])
    show_sr_columns = Bool(True)

    # stress resultant columns - generated from the parameter combination
    # dir and stress_res - one of MX, NX, MY, NY
    #
    m_varname = Property(Str)

    def _get_m_varname(self):
        # e.g. mx_N
        appendix = self.dir + '_' + self.stress_res
        return 'm' + appendix

    n_varname = Property(Str)

    def _get_n_varname(self):
        # e.g. nx_N
        appendix = self.dir + '_' + self.stress_res
        return 'n' + appendix

    n = Property(Float)

    def _get_n(self):
        return getattr(self.ls_table, self.n_varname)

    m = Property(Float)

    def _get_m(self):
        return getattr(self.ls_table, self.m_varname)

    #-------------------------------
    # geo columns form info shell
    #-------------------------------

    geo_columns = List(['elem_no', 'X', 'Y', 'Z', 'D_elem'])
    show_geo_columns = Bool(True)

    elem_no = Property(Float)

    def _get_elem_no(self):
        return self.ls_table.elem_no

    X = Property(Float)

    def _get_X(self):
        return self.ls_table.X

    Y = Property(Float)

    def _get_Y(self):
        return self.ls_table.Y

    Z = Property(Float)

    def _get_Z(self):
        return self.ls_table.Z

    D_elem = Property(Float)

    def _get_D_elem(self):
        return self.ls_table.D_elem

    #-------------------------------
    # state columns form info shell
    #-------------------------------


#    state_columns = List( ['mx', 'my', 'mxy', 'nx', 'ny', 'nxy' ] )
    state_columns = List([
        'mx',
        'my',
        'mxy',
        'nx',
        'ny',
        'nxy',
        'sigx_lo',
        'sigy_lo',
        'sigxy_lo',
        'sig1_lo',
        'sig2_lo',
        'alpha_sig_lo',
        'sigx_up',
        'sigy_up',
        'sigxy_up',
        'sig1_up',
        'sig2_up',
        'alpha_sig_up',
    ])

    show_state_columns = Bool(True)

    mx = Property(Float)

    def _get_mx(self):
        return self.ls_table.mx

    my = Property(Float)

    def _get_my(self):
        return self.ls_table.my

    mxy = Property(Float)

    def _get_mxy(self):
        return self.ls_table.mxy

    nx = Property(Float)

    def _get_nx(self):
        return self.ls_table.nx

    ny = Property(Float)

    def _get_ny(self):
        return self.ls_table.ny

    nxy = Property(Float)

    def _get_nxy(self):
        return self.ls_table.nxy

    # evaluate principal stresses
    # upper face:
    #
    sigx_up = Property(Float)

    def _get_sigx_up(self):
        return self.ls_table.sigx_up

    sigy_up = Property(Float)

    def _get_sigy_up(self):
        return self.ls_table.sigy_up

    sigxy_up = Property(Float)

    def _get_sigxy_up(self):
        return self.ls_table.sigxy_up

    sig1_up = Property(Float)

    def _get_sig1_up(self):
        return self.ls_table.sig1_up

    sig2_up = Property(Float)

    def _get_sig2_up(self):
        return self.ls_table.sig2_up

    alpha_sig_up = Property(Float)

    def _get_alpha_sig_up(self):
        return self.ls_table.alpha_sig_up

    # lower face:
    #
    sigx_lo = Property(Float)

    def _get_sigx_lo(self):
        return self.ls_table.sigx_lo

    sigy_lo = Property(Float)

    def _get_sigy_lo(self):
        return self.ls_table.sigy_lo

    sigxy_lo = Property(Float)

    def _get_sigxy_lo(self):
        return self.ls_table.sigxy_lo

    sig1_lo = Property(Float)

    def _get_sig1_lo(self):
        return self.ls_table.sig1_lo

    sig2_lo = Property(Float)

    def _get_sig2_lo(self):
        return self.ls_table.sig2_lo

    alpha_sig_lo = Property(Float)

    def _get_alpha_sig_lo(self):
        return self.ls_table.alpha_sig_lo

    #-------------------------------
    # ls table
    #-------------------------------

    # all columns associated with the limit state including the corresponding
    # stress resultants
    #
    columns = Property(List,
                       depends_on='show_geo_columns, show_state_columns,\
                                             show_sr_columns, show_ls_columns')

    @cached_property
    def _get_columns(self):
        columns = []

        if self.show_geo_columns:
            columns += self.geo_columns

        if self.show_state_columns:
            columns += self.state_columns

        if self.show_sr_columns:
            columns += self.sr_columns

        if self.show_ls_columns:
            columns += self.ls_columns

        return columns

    # select column used for sorting the data in selected sorting order
    #
    sort_column = Enum(values='columns')

    def _sort_column_default(self):
        return self.columns[-1]

    sort_order = Enum('descending', 'ascending', 'unsorted')

    #-------------------------------------------------------
    # get the maximum value of the selected variable
    # 'max_in_column' of the current sheet (only one sheet)
    #-------------------------------------------------------

    # get the maximum value of the chosen column
    #
    max_in_column = Enum(values='columns')

    def _max_in_column_default(self):
        return self.columns[-1]

    max_value = Property(depends_on='max_in_column')

    def _get_max_value(self):
        col = getattr(self, self.max_in_column)[:, 0]
        return max(col)

    #-------------------------------------------------------
    # get the maximum value and the corresponding case of
    # the selected variable 'max_in_column' in all (!) sheets
    #-------------------------------------------------------

    max_value_all = Property(depends_on='max_in_column')

    def _get_max_value_all(self):
        return self.ls_table.max_value_and_case[
            self.max_in_column]['max_value']

    max_case = Property(depends_on='max_in_column')

    def _get_max_case(self):
        return self.ls_table.max_value_and_case[self.max_in_column]['max_case']

    #-------------------------------------------------------
    # get ls_table for View
    #-------------------------------------------------------

    # stack columns together for table used by TabularEditor
    #
    ls_array = Property(
        Array,
        depends_on='sort_column, sort_order, show_geo_columns, \
                                              show_state_columns, show_sr_columns, show_ls_columns'
    )

    @cached_property
    def _get_ls_array(self):

        arr_list = [getattr(self, col) for col in self.columns]

        # get the array currently selected by the sort_column enumeration
        #
        sort_arr = getattr(self, self.sort_column)[:, 0]
        sort_idx = argsort(sort_arr)
        ls_array = hstack(arr_list)

        if self.sort_order == 'descending':
            return ls_array[sort_idx[::-1]]
        if self.sort_order == 'ascending':
            return ls_array[sort_idx]
        if self.sort_order == 'unsorted':
            return ls_array

    #---------------------------------
    # plot outputs in mlab-window
    #---------------------------------

    plot_column = Enum(values='columns')
    plot = Button

    def _plot_fired(self):
        X = self.ls_table.X[:, 0]
        Y = self.ls_table.Y[:, 0]
        Z = self.ls_table.Z[:, 0]
        plot_col = getattr(self, self.plot_column)[:, 0]

        if self.plot_column == 'n_tex':
            plot_col = where(plot_col < 0, 0, plot_col)

        mlab.figure(figure="SFB532Demo",
                    bgcolor=(1.0, 1.0, 1.0),
                    fgcolor=(0.0, 0.0, 0.0))

        mlab.points3d(
            X,
            Y,
            (-1.0) * Z,
            plot_col,
            #                       colormap = "gist_rainbow",
            #                       colormap = "Reds",
            colormap="YlOrBr",
            mode="cube",
            scale_factor=0.15)

        mlab.scalarbar(title=self.plot_column, orientation='vertical')

        mlab.show

    # name of the trait that is used to assess the evaluated design
    #
    assess_name = Str('')

    #-------------------------------
    # ls group
    #-------------------------------

    # @todo: the dynamic selection of the columns to be displayed
    # does not work in connection with the LSArrayAdapter
    ls_group = VGroup(
        HGroup(  #Item( 'assess_name' ),
            Item('max_in_column'),
            Item('max_value', style='readonly', format_str='%6.2f'),
            Item('max_value_all', style='readonly', format_str='%6.2f'),
            Item('max_case', style='readonly', label='found in case: '),
        ),
        HGroup(
            Item('sort_column'),
            Item('sort_order'),
            Item('show_geo_columns', label='show geo'),
            Item('show_state_columns', label='show state'),
            Item('show_sr_columns', label='show sr'),
            Item('plot_column'),
            Item('plot'),
        ),
    )
Esempio n. 15
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'])
Esempio n. 16
0
class ULS(LS):
    '''Ultimate limit state
    '''

    #--------------------------------------------------------
    # ULS: material parameters (Inputs)
    #--------------------------------------------------------

    # gamma-factor
    gamma = Float(1.5, input=True)

    # long term reduction factor
    beta = Float(1.0, input=True)

    # INDEX l: longitudinal direction of the textile (MAG-02-02-06a)
    # characteristic tensile strength of the tensile specimen [N/mm2]
    f_tk_l = Float(537, input=True)

    # design value of the tensile strength of the tensile specimen [N/mm2]
    # containing a gamma-factor of 1.5 and d long term reduction factor of 0.7
    # f_td_l = 251

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

    def _get_f_td_l(self):
        return self.beta * self.f_tk_l / self.gamma

    # cross sectional area of the reinforcement [mm2/m]
    a_t_l = Float(71.65, input=True)

    # INDEX q: orthogonal direction of the textile (MAG-02-02-06a)
    # characteristic tensile strength of the tensile specimen [N/mm2]
    f_tk_q = Float(511, input=True)

    # design value of the tensile strength of the tensile specimen [kN/m]
    # f_td_q = 238
    f_td_q = Property(Float, depends_on='+input')

    def _get_f_td_q(self):
        return self.beta * self.f_tk_q / self.gamma

    # cross sectional area of the reinforcement [mm2/m]
    a_t_q = Float(53.31, input=True)

    # tensile strength of the textile reinforcement [kN/m]
    f_Rtex_l = Property(Float, depends_on='+input')

    def _get_f_Rtex_l(self):
        return self.a_t_l * self.f_td_l / 1000.

    # tensile strength of the textile reinforcement [kN/m]
    f_Rtex_q = Property(Float)

    def _get_f_Rtex_q(self, depends_on='+input'):
        return self.a_t_q * self.f_td_q / 1000.

    # tensile strength of the textile reinforcement [kN/m]
    # as simplification the lower value of 0- and 90-direction is taken
    #
    # sig_composite,exp = 103.4 kN/14cm/6cm = 12.3 MPa
    # f_tex,exp = 103.4 kN/14cm/12layers = 61.5 kN/m
    # f_tex,k = f_tex,exp * 0,81 (EN-DIN 1990) = 0.82*61.5 kN/m = 50.4 kN/m
    # f_tex,d = f_tex,k / 1,5 = 33.6 kN/m
    #
    f_Rtex_l = f_Rtex_q = 34.3
    print 'NOTE: f_Rtex_l = f_Rtex_q = set to %g kN/m !' % (f_Rtex_l)

    k_fl = 7.95 / 6.87
    print 'NOTE: k_fl = set to %g [-] !' % (k_fl)

    # ------------------------------------------------------------
    # ULS - derived params:
    # ------------------------------------------------------------

    # Parameters for the cracked state (GdT):
    # assumptions!

    # (resultierende statische Nutzhoehe)
    #
    d = Property(Float)

    def _get_d(self):
        return 0.75 * self.ls_table.D_elem

    # (Abstand Schwereachse zur resultierende Bewehrungslage)
    # chose the same amount of reinforcement at the top as at the bottom
    # i.e. zs = zs1 = zs2
    #
    zs = Property(Float)

    def _get_zs(self):
        return self.d - self.ls_table.D_elem / 2.

    # (Innerer Hebelarm)
    #
    z = Property(Float)

    def _get_z(self):
        return 0.9 * self.d

    # ------------------------------------------------------------
    # ULS: outputs
    # ------------------------------------------------------------

    ls_columns = List([
        'e', 'm_Eds', 'f_t', 'f_t_sig', 'beta_l', 'beta_q', 'f_Rtex',
        'k_fl_NM', 'n_tex'
    ])

    sr_columns = ['m', 'n', 'alpha', 'd', 'zs', 'z']

    alpha_varname = Property()

    def _get_alpha_varname(self):
        return 'alpha_' + self.stress_res

    alpha = Property

    def _get_alpha(self):
        return getattr(self.ls_table, self.alpha_varname)

    ls_values = Property(depends_on='+input')

    @cached_property
    def _get_ls_values(self):
        '''get the outputs for ULS
        '''
        #-------------------------------------------------
        # VAR 1:use simplified reinforced concrete approach
        #-------------------------------------------------
        n = self.n
        m = self.m
        alpha = self.alpha

        zs = self.zs
        z = self.z
        f_Rtex_l = self.f_Rtex_l
        f_Rtex_q = self.f_Rtex_q

        # (Exzentrizitaet)
        e = abs(m / n)
        e[n == 0] = 1E9  # if normal force is zero set e to very large value

        # moment at the height of the resulting reinforcement layer:
        m_Eds = abs(m) - zs * n

        # tensile force in the reinforcement for bending and compression
        f_t = m_Eds / z + n

        # check if the two conditions are true:
        cond1 = n > 0
        cond2 = e < zs
        bool_arr = cond1 * cond2
        # in case of pure tension in the cross section:
        f_t[bool_arr] = n[bool_arr] * (zs[bool_arr] + e[bool_arr]) / (
            zs[bool_arr] + zs[bool_arr])

        #-------------------------------------------------
        # VAR 2:use principal stresses to calculate the resulting tensile force
        #-------------------------------------------------
        #
        princ_stress_eval = True
        #        princ_stress_eval = False

        f_t_sig = self.sig1_lo * self.D_elem * 1000.
        if princ_stress_eval == True:
            print "NOTE: the principle tensile stresses are used to evaluate 'n_tex'"
            # resulting tensile force of the composite cross section[kN]
            # the entire (!) cross section is used!
            # as the maximum value of the tensile stresses at the top or the bottom
            # i.e. sig1_max = min( 0, max( self.sig1_up, self.sig1_lo ) )

            #---------------------------------------------------------
            # initialize arrays t be filled by case distinction:
            #---------------------------------------------------------
            #
            f_t_sig = zeros_like(self.sig1_up)
            alpha = zeros_like(self.sig1_up)

            k_fl_NM = ones_like(self.sig1_up)
            # absolute value of the bending stress created by mx or my
            sig_b = (abs(self.sig1_lo) + abs(self.sig1_up)) / 2

            #---------------------------------------------------------
            # conditions for case distinction
            #---------------------------------------------------------

            cond_t_up = self.sig1_up > 0.  # compression stress upper side
            cond_t_lo = self.sig1_lo > 0.  # compression stress lower side

            cond_u_gt_l = abs(self.sig1_up) > abs(
                self.sig1_lo
            )  # absolute value of upper stress greater then lower stress
            cond_l_gt_u = abs(self.sig1_lo) > abs(
                self.sig1_up
            )  # absolute value of lower stress greater then lower stress
            cond_u_eq_l = abs(self.sig1_up) == abs(
                self.sig1_lo
            )  # absolute values of upper stress equals lower stress

            cond_b = self.sig1_up * self.sig1_lo < 0  # bending case
            cond_u_gt_0 = self.sig1_up > 0  # value of upper stress greater then 0.
            cond_l_gt_0 = self.sig1_lo > 0  # value of lower stress greater then 0.

            cond_c_up = self.sig1_up < 0.  # compression stress upper side
            cond_c_lo = self.sig1_lo < 0.  # compression stress lower side

            #---------------------------------------------------------
            # tension case:
            #---------------------------------------------------------

            # sig_up > sig_lo
            bool_arr = cond_t_up * cond_t_lo * cond_u_gt_l
            alpha[bool_arr] = self.alpha_sig_up[bool_arr]
            k_fl_NM[bool_arr] = 1.0
            f_t_sig[bool_arr] = self.sig1_up[bool_arr] * self.D_elem[
                bool_arr] * 1000.

            # sig_lo > sig_up
            bool_arr = cond_t_up * cond_t_lo * cond_l_gt_u
            alpha[bool_arr] = self.alpha_sig_lo[bool_arr]
            k_fl_NM[bool_arr] = 1.0
            f_t_sig[bool_arr] = self.sig1_lo[bool_arr] * self.D_elem[
                bool_arr] * 1000.

            # sig_lo = sig_up
            bool_arr = cond_t_up * cond_t_lo * cond_u_eq_l
            alpha[bool_arr] = (self.alpha_sig_lo[bool_arr] +
                               self.alpha_sig_up[bool_arr]) / 2.
            k_fl_NM[bool_arr] = 1.0
            f_t_sig[bool_arr] = self.sig1_lo[bool_arr] * self.D_elem[
                bool_arr] * 1000.

            #---------------------------------------------------------
            # bending case (= different signs)
            #---------------------------------------------------------

            # bending with tension at the lower side
            # AND sig_N > 0 (--> bending and tension; sig1_lo results from bending and tension)
            bool_arr = cond_b * cond_l_gt_0 * cond_l_gt_u
            alpha[bool_arr] = self.alpha_sig_lo[bool_arr]
            k_fl_NM[ bool_arr ] = 1.0 + ( self.k_fl - 1.0 ) * \
                                 ( 1.0 - ( sig_b[ bool_arr ] - abs( self.sig1_up[ bool_arr] ) ) / self.sig1_lo[ bool_arr ] )
            f_t_sig[bool_arr] = self.sig1_lo[bool_arr] * self.D_elem[
                bool_arr] * 1000. / k_fl_NM[bool_arr]

            # bending with tension at the lower side
            # AND sig_N < 0 (--> bending and compression; sig1_lo results only from bending)
            bool_arr = cond_b * cond_l_gt_0 * cond_u_gt_l
            alpha[bool_arr] = self.alpha_sig_lo[bool_arr]
            k_fl_NM[bool_arr] = self.k_fl
            f_t_sig[bool_arr] = self.sig1_lo[bool_arr] * self.D_elem[
                bool_arr] * 1000. / k_fl_NM[bool_arr]

            # bending with tension at the upper side
            # AND sig_N > 0 (--> bending and tension; sig1_up results from bending and tension)
            bool_arr = cond_b * cond_u_gt_0 * cond_u_gt_l
            alpha[bool_arr] = self.alpha_sig_up[bool_arr]
            k_fl_NM[ bool_arr ] = 1.0 + ( self.k_fl - 1.0 ) * \
                                 ( 1.0 - ( sig_b[ bool_arr ] - abs( self.sig1_lo[ bool_arr] ) ) / self.sig1_up[ bool_arr ] )

            f_t_sig[bool_arr] = self.sig1_up[bool_arr] * self.D_elem[
                bool_arr] * 1000. / k_fl_NM[bool_arr]

            # bending with tension at the upper side
            # AND sig_N < 0 (--> bending and compression; sig1_up results only from bending)
            bool_arr = cond_b * cond_u_gt_0 * cond_l_gt_u
            alpha[bool_arr] = self.alpha_sig_up[bool_arr]
            k_fl_NM[bool_arr] = self.k_fl
            f_t_sig[bool_arr] = self.sig1_up[bool_arr] * self.D_elem[
                bool_arr] * 1000. / k_fl_NM[bool_arr]

            #---------------------------------------------------------
            # compression case:
            #---------------------------------------------------------

            bool_arr = cond_c_up * cond_c_lo
            # deflection angle is of minor interest use this simplification
            alpha[bool_arr] = (self.alpha_sig_up[bool_arr] +
                               self.alpha_sig_up[bool_arr]) / 2.
            f_t_sig[bool_arr] = 0.
            k_fl_NM[bool_arr] = 1.0

        #------------------------------------------------------------
        # get angel of deflection of the textile reinforcement
        #------------------------------------------------------------

        # angel of deflection of the textile reinforcement for dimensioning in x-direction
        # distinguished between longitudinal (l) and transversal (q) direction

#        # ASSUMPTION: worst case angle used
#        # as first step use the worst case reduction due to deflection possible (at 55 degrees)
#        beta_l = 55. * pi / 180. * ones_like( alpha )
#        beta_q = ( 90. - 55. ) * pi / 180. * ones_like( alpha )

# @todo: as second step use the value for an alternating layup (i.e. deflection angle)
# @todo: get the correct formula for the demonstrator arrangement
# i.e. the RFEM coordinate system orientation
#        print "NOTE: deflection angle is used to evaluate 'n_tex'"
        beta_l = 90 - abs(alpha)  # [degree]
        beta_q = abs(alpha)  # [degree]

        # resulting strength of the bi-directional textile considering the
        # deflection of the reinforcement in the loading direction:
        f_Rtex = f_Rtex_l * cos( beta_l * pi / 180. ) * ( 1 - beta_l / 90. ) + \
                 f_Rtex_q * cos( beta_q * pi / 180. ) * ( 1 - beta_q / 90. )

        # f_Rtex= 11.65 kN/m corresponds to sig_Rtex = 585 MPa
        #
        #        f_Rtex = 11.65 * ones_like( alpha )

        # f_Rtex= 10.9 kN/m corresponds to sig_Rtex = 678 MPa
        # with 1/3*( 679 + 690 + 667 ) = 678 MPa
        #
        #        f_Rtex = 10.9 * ones_like( alpha )

        # f_Rtex = 10.00 kN/m corresponds to sig_Rtex = 610 MPa
        #
        #        f_Rtex = 10.00 * ones_like( alpha )

        #        print 'NOTE: f_Rtex set to %g kN/m !' % ( f_Rtex[0] )

        if princ_stress_eval == False:
            # necessary number of reinforcement layers
            n_tex = f_t / f_Rtex

            return {
                'e': e,
                'm_Eds': m_Eds,
                'f_t': f_t,
                'f_t_sig': f_t_sig,
                'beta_l': beta_l,
                'beta_q': beta_q,
                'f_Rtex': f_Rtex,
                'n_tex': n_tex
            }

        elif princ_stress_eval == True:
            # NOTE: as the entire (!) cross section is used to calculate 'f_tex_sig'
            # the number of layers is evaluated also directly for the entire (!)
            # cross section!
            #
            n_tex = f_t_sig / f_Rtex

            return {
                'e': e,
                'm_Eds': m_Eds,
                'f_t': f_t,
                'f_t_sig': f_t_sig,
                'beta_l': beta_l,
                'beta_q': beta_q,
                'f_Rtex': f_Rtex,
                'n_tex': n_tex,
                'k_fl_NM': k_fl_NM
            }

    e = Property

    def _get_e(self):
        return self.ls_values['e']

    m_Eds = Property

    def _get_m_Eds(self):
        return self.ls_values['m_Eds']

    f_t = Property

    def _get_f_t(self):
        return self.ls_values['f_t']

    f_t_sig = Property

    def _get_f_t_sig(self):
        return self.ls_values['f_t_sig']

    beta_l = Property

    def _get_beta_l(self):
        return self.ls_values['beta_l']

    beta_q = Property

    def _get_beta_q(self):
        return self.ls_values['beta_q']

    f_Rtex = Property

    def _get_f_Rtex(self):
        return self.ls_values['f_Rtex']

    k_fl_NM = Property

    def _get_k_fl_NM(self):
        return self.ls_values['k_fl_NM']

    n_tex = Property

    def _get_n_tex(self):
        return self.ls_values['n_tex']

    assess_name = 'max_n_tex'
    max_n_tex = Property(depends_on='+input')

    @cached_property
    def _get_max_n_tex(self):
        return ndmax(self.n_tex)


#    assess_name = 'max_sig1_up'
#    max_sig1_up = Property( depends_on = '+input' )
#    @cached_property
#    def _get_max_sig1_up( self ):
#        return ndmax( self.sig1_up )

#    assess_name = 'max_sig1_lo'
#    max_sig1_lo = Property( depends_on = '+input' )
#    @cached_property
#    def _get_max_sig1_lo( self ):
#        return ndmax( self.sig1_lo )

#-------------------------------
# ls view
#-------------------------------

# @todo: the dynamic selection of the columns to be displayed
# does not work in connection with the LSArrayAdapter

    traits_view = View(VGroup(
        HGroup(
            VGroup(Item(name='gamma',
                        label='safety factor material [-]:  gamma '),
                   Item(name='beta',
                        label='reduction long term durability [-]:  beta '),
                   label='safety factors'),
            VGroup(Item(name='f_tk_l',
                        label='characteristic strength textil [MPa]:  f_tk_l ',
                        format_str="%.1f"),
                   Item(name='f_td_l',
                        label='design strength textil [MPa]:  f_td_l ',
                        style='readonly',
                        format_str="%.1f"),
                   Item(name='a_t_l',
                        label='cross sectional area textil [mm^2]:  a_t_l ',
                        style='readonly',
                        format_str="%.1f"),
                   Item(name='f_Rtex_l',
                        label='design strength textil [kN/m]:  f_Rtex_l ',
                        style='readonly',
                        format_str="%.0f"),
                   label='material properties (longitudinal)'),
            VGroup(Item(name='f_tk_q',
                        label='characteristic strength textil [MPa]:  f_tk_q ',
                        format_str="%.1f"),
                   Item(name='f_td_q',
                        label='design strength textil [MPa]:  f_td_q ',
                        style='readonly',
                        format_str="%.1f"),
                   Item(name='a_t_q',
                        label='cross sectional area textil [mm^2]:  a_t_q ',
                        style='readonly',
                        format_str="%.1f"),
                   Item(name='f_Rtex_q',
                        label='design strength textil [kN/m]: f_Rtex_q ',
                        style='readonly',
                        format_str="%.0f"),
                   label='material Properties (transversal)'),
        ),
        VGroup(
            Include('ls_group'),
            Item('ls_array',
                 show_label=False,
                 editor=TabularEditor(adapter=LSArrayAdapter()))),
    ),
                       resizable=True,
                       scrollable=True,
                       height=1000,
                       width=1100)
Esempio n. 17
0
class SLS(LS):
    '''Serviceability limit state
    '''

    # ------------------------------------------------------------
    # SLS: material parameters (Inputs)
    # ------------------------------------------------------------

    # tensile strength [MPa]
    f_ctk = Float(4.0, input=True)

    # flexural tensile strength [MPa]
    f_m = Float(5.0, input=True)

    # ------------------------------------------------------------
    # SLS - derived params:
    # ------------------------------------------------------------

    # area
    #
    A = Property(Float)

    def _get_A(self):
        return self.ls_table.D_elem * 1.

    # moment of inertia
    #
    W = Property(Float)

    def _get_W(self):
        return 1. * self.ls_table.D_elem**2 / 6.

    # ------------------------------------------------------------
    # SLS: outputs
    # ------------------------------------------------------------

    ls_columns = List([
        'sig_n',
        'sig_m',
        'eta_n',
        'eta_m',
        'eta_tot',
    ])

    ls_values = Property(depends_on='+input')

    @cached_property
    def _get_ls_values(self):
        '''get the outputs for SLS
        '''
        n = self.n
        m = self.m

        A = self.A
        W = self.W
        f_ctk = self.f_ctk
        f_m = self.f_m

        sig_n = n / A / 1000.
        sig_m = abs(m / W) / 1000.
        eta_n = sig_n / f_ctk
        eta_m = sig_m / f_m
        eta_tot = eta_n + eta_m

        return {
            'sig_n': sig_n,
            'sig_m': sig_m,
            'eta_n': eta_n,
            'eta_m': eta_m,
            'eta_tot': eta_tot
        }

    sig_n = Property

    def _get_sig_n(self):
        return self.ls_values['sig_n']

    sig_m = Property

    def _get_sig_m(self):
        return self.ls_values['sig_m']

    eta_n = Property

    def _get_eta_n(self):
        return self.ls_values['eta_n']

    eta_m = Property

    def _get_eta_m(self):
        return self.ls_values['eta_m']

    eta_tot = Property

    def _get_eta_tot(self):
        return self.ls_values['eta_tot']

    assess_name = 'max_eta_tot'

    #    assess_name = 'max_sig1_up'
    #
    #    max_sig1_up = Property( depends_on = '+input' )
    #    @cached_property
    #    def _get_max_sig1_up( self ):
    #        return ndmax( self.sig1_up )

    # @todo: make it possible to select the assess value:
    #
    #    assess_name = Enum( values = 'columns' )
    #    def _assess_name_default( self ):
    #        return self.columns[-1]

    max_eta_tot = Property(depends_on='+input')

    @cached_property
    def _get_max_eta_tot(self):
        return ndmax(self.eta_tot)

    #-------------------------------
    # ls view
    #-------------------------------

    # @todo: the dynamic selection of the columns to be displayed
    # does not work in connection with the LSArrayAdapter
    traits_view = View(
        VGroup(
            HGroup(
                Item(name='f_ctk',
                     label='Tensile strength concrete [MPa]: f_ctk '),
                Item(name='f_m',
                     label='Flexural tensile trength concrete [MPa]: f_m ')),
            VGroup(
                Include('ls_group'),

                # @todo: currently LSArrayAdapter must be called both
                #        in SLS and ULS separately to configure columns
                #        arrangement individually
                #
                Item('ls_array',
                     show_label=False,
                     editor=TabularEditor(adapter=LSArrayAdapter()))),
        ),
        resizable=True,
        scrollable=True,
        height=1000,
        width=1100)
Esempio n. 18
0
class SPIRRIDModelView(ModelView):
    '''
    Size effect depending on the yarn length
    '''
    model = Instance(SPIRRID)
    def _model_changed(self):
        self.model.rf = self.rf

    rf_values = List(IRF)
    def _rf_values_default(self):
        return [ Filament() ]

    rf = Enum(values = 'rf_values')
    def _rf_default(self):
        return self.rf_values[0]
    def _rf_changed(self):
        # reset the rf in the spirrid model and in the rf_modelview
        self.model.rf = self.rf
        self.rf_model_view = RFModelView(model = self.rf)
        # actually, the view should be reusable but the model switch
        # did not work for whatever reason
        # the binding of the view generated by edit_traits does not 
        # react to the change in the 'model' attribute.
        #
        # Remember - we are implementing a handler here
        # that has an associated view.
        #
        # self.rf.model_view.model = self.rf

    rf_model_view = Instance(RFModelView)
    def _rf_model_view_default(self):
        return RFModelView(model = self.rf)


    rv_list = Property(List(RIDVariable), depends_on = 'rf')
    @cached_property
    def _get_rv_list(self):
        return [ RIDVariable(spirrid = self.model, rf = self.rf,
                              varname = nm, trait_value = st)
                 for nm, st in zip(self.rf.param_keys, self.rf.param_values) ]

    selected_var = Instance(RIDVariable)
    def _selected_var_default(self):
        return self.rv_list[0]

    run = Button(desc = 'Run the computation')
    def _run_fired(self):
        self._redraw()

    sample = Button(desc = 'Show samples')
    def _sample_fired(self):
        n_samples = 50

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

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

        eps_arr = self.model.eps_arr

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

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

        self.data_changed = True

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

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

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

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

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

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

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

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

    data_changed = Event(True)

    def _redraw(self):

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

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

        mc = self.model.mean_curve

        axes.plot(mc.xdata, mc.ydata,
                   linewidth = 2, label = self.run_legend)

        axes.set_xlabel(self.label_eps)
        axes.set_ylabel(self.label_sig)
        axes.legend(loc = 'best')

        self.data_changed = True

    traits_view_tabbed = View(
                              VGroup(
                              HGroup(
                                    Item('run_legend', resizable = False, label = 'Run label',
                                          width = 80, springy = False),
                                    Item('run', show_label = False, resizable = False),
                                    Item('sample', show_label = False, resizable = False),
                                    Item('clear', show_label = False,
                                      resizable = False, springy = False)
                                ),
                               Tabbed(
                               VGroup(
                                     Item('rf', show_label = False),
                                     Item('rf_model_view@', show_label = False, resizable = True),
                                     label = 'Deterministic model',
                                     id = 'spirrid.tview.model',
                                     ),
                                Group(
                                    Item('rv_list', editor = rv_list_editor, show_label = False),
                                    id = 'spirrid.tview.randomization.rv',
                                    label = 'Model variables',
                                ),
                                Group(
                                    Item('selected_var@', show_label = False, resizable = True),
                                    id = 'spirrid.tview.randomization.distr',
                                    label = 'Distribution',
                                ),
                                VGroup(
                                       Item('model.cached_dG' , label = 'Cached weight factors',
                                             resizable = False,
                                             springy = False),
                                       Item('model.compiled_QdG_loop' , label = 'Compiled loop over the integration product',
                                             springy = False),
                                       Item('model.compiled_eps_loop' ,
                                             enabled_when = 'model.compiled_QdG_loop',
                                             label = 'Compiled loop over the control variable',
                                             springy = False),
                                        scrollable = True,
                                       label = 'Execution configuration',
                                       id = 'spirrid.tview.exec_params',
                                       dock = 'tab',
                                     ),
                                VGroup(
                                          HGroup(
                                                 Item('min_eps' , label = 'Min',
                                                       springy = False, resizable = False),
                                                 Item('max_eps' , label = 'Max',
                                                       springy = False, resizable = False),
                                                 Item('n_eps' , label = 'N',
                                                       springy = False, resizable = False),
                                                 label = 'Simulation range',
                                                 show_border = True
                                                 ),
                                          VGroup(
                                                 Item('label_eps' , label = 'x', resizable = False,
                                                 springy = False),
                                                 Item('label_sig' , label = 'y', resizable = False,
                                                 springy = False),
                                                 label = 'Axes labels',
                                                 show_border = True,
                                                 scrollable = True,
                                                 ),
                                           label = 'Execution control',
                                           id = 'spirrid.tview.view_params',
                                           dock = 'tab',
                                 ),
                                VGroup(
                                        Item('figure', editor = MPLFigureEditor(),
                                             resizable = True, show_label = False),
                                        label = 'Plot sheet',
                                        id = 'spirrid.tview.figure_window',
                                        dock = 'tab',
                                        scrollable = True,
                                ),
                                scrollable = True,
                                id = 'spirrid.tview.tabs',
                                dock = 'tab',
                        ),
                        ),
                        title = 'SPIRRID',
                        id = 'spirrid.viewmodel',
                        dock = 'tab',
                        resizable = True,
                        height = 1.0, width = 1.0
                        )
Esempio n. 19
0
class ECBLCalibHistModelView(ModelView):
    '''Model in a viewable window.
    '''
    model = Instance(ECBLCalibHist)

    def _model_default(self):
        return ECBLCalibHist()

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

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

    current_cs_state = Instance(ECBCrossSectionState)

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

    def _current_cs_state_changed(self):
        self._replot_fired()

    eps_range = Property

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

    f_range = Property

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

    data_changed = Event

    figure = Instance(Figure)

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

    replot = Button()

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

    clear = Button()

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

    view = View(HSplit(
        VGroup(
            Item('cs_states',
                 editor=cs_states_editor,
                 label='Cross section',
                 show_label=False),
            Item('model@', show_label=False),
        ),
        Group(
            HGroup(
                Item('replot', show_label=False),
                Item('clear', show_label=False),
            ),
            Item('figure',
                 editor=MPLFigureEditor(),
                 resizable=True,
                 show_label=False),
            id='simexdb.plot_sheet',
            label='plot sheet',
            dock='tab',
        ),
    ),
                width=0.8,
                height=0.7,
                buttons=['OK', 'Cancel'],
                resizable=True)
Esempio n. 20
0
class YMBHist(HasTraits):

    slider = Instance(YMBSlider)

    figure = Instance(Figure)

    bins = Int(20, auto_set=False, enter_set=True, modified=True)
    xlimit_on = Bool(False, modified=True)
    ylimit_on = Bool(False, modified=True)
    xlimit = Float(100, auto_set=False, enter_set=True, modified=True)
    ylimit = Float(100, auto_set=False, enter_set=True, modified=True)
    multi_hist_on = Bool(False, modified=True)
    stats_on = Bool(False, modified=True)
    normed_on = Bool(False, modified=True)

    normed_hist = Property(depends_on='+modified, slider.input_change')

    @cached_property
    def _get_normed_hist(self):
        data = self.slider.stat_data
        h, b = histogram(data, bins=self.bins, normed=True)
        return h, b

    range = Property

    def _get_range(self):
        h, b = self.normed_hist
        return (min(b), max(b))

    bin_width = Property

    def _get_bin_width(self):
        return (self.range[1] - self.range[0]) / self.bins

    def _figure_default(self):
        figure = Figure()
        figure.add_axes(self.axes_adjust)
        return figure

    edge_color = Str(None)
    face_color = Str(None)
    axes_adjust = List([0.1, 0.1, 0.8, 0.8])

    data_changed = Event(True)

    @on_trait_change('+modified, slider.input_change')
    def _redraw(self):
        figure = self.figure
        axes = figure.axes[0]
        axes.clear()
        if self.multi_hist_on == True:
            histtype = 'step'
            lw = 3
            plot_data = getattr(self.slider.data, self.slider.var_enum_)
            for i in range(0, plot_data.shape[1]):
                axes.hist(plot_data[:, i].compressed(),
                          bins=self.bins,
                          histtype=histtype,
                          color='gray')
        if self.multi_hist_on == False:
            histtype = 'bar'
            lw = 1
        var_data = self.slider.stat_data

        axes.hist(var_data, bins=self.bins, histtype=histtype, linewidth=lw, \
                   normed=self.normed_on, edgecolor=self.edge_color, facecolor=self.face_color)
        if self.stats_on == True:
            xint = axes.xaxis.get_view_interval()
            yint = axes.yaxis.get_view_interval()
            axes.text(
                xint[0], yint[0],
                'mean = %e, std = %e' % (mean(var_data), sqrt(var(var_data))))

        # redefine xticks labels
        # inter = axes.xaxis.get_view_interval()
        # axes.set_xticks( linspace( inter[0], inter[1], 5 ) )
        axes.set_xlabel(self.slider.var_enum)
        axes.set_ylabel('frequency')  # , fontsize = 16
        setp(axes.get_xticklabels(), position=(0, -.025))
        if self.xlimit_on == True:
            axes.set_xlim(0, self.xlimit)
        if self.ylimit_on == True:
            axes.set_ylim(0, self.ylimit)
        self.data_changed = True

    view = View(
        Group(
            Item('figure',
                 style='custom',
                 editor=MPLFigureEditor(),
                 show_label=False,
                 id='figure.view'),
            HGroup(
                Item('bins'), Item('ylimit_on', label='Y limit'),
                Item('ylimit',
                     enabled_when='ylimit_on == True',
                     show_label=False), Item('stats_on', label='stats'),
                Item('normed_on', label='norm'),
                Item('multi_hist_on', label='multi')),
            label='histogram',
            dock='horizontal',
            id='yarn_hist.figure',
        ),
        Group(
            Item('slider', style='custom', show_label=False),
            label='yarn data',
            dock='horizontal',
            id='yarn_hist.config',
        ),
        id='yarn_structure_view',
        resizable=True,
        scrollable=True,
        # width = 0.8,
        # height = 0.4
    )
Esempio n. 21
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'])
Esempio n. 22
0
class YMBAutoCorrelView(HasTraits):

    correl_data = Instance(YMBAutoCorrel)

    axes_adjust = List([0.1, 0.1, 0.8, 0.8])

    data = Property
    def _get_data(self):
        return self.correl_data.data

    zero = Constant(0)
    slider_max = Property()
    def _get_slider_max(self):
        return self.data.n_cuts - 1

    cut_slider = Range('zero', 'slider_max', mode='slider', auto_set=False, enter_set=True, modified=True)
    vcut_slider = Range('zero', 'slider_max', mode='slider', auto_set=False, enter_set=True, modified=True)

    cut_slider_on = Bool(False, modified=True)

    color = Str('blue')

    figure = Instance(Figure)

    def _figure_default(self):
        figure = Figure()
        figure.add_axes(self.axes_adjust)
        return figure

    data_changed = Event(True)
    @on_trait_change('correl_data.input_change, +modified')
    def _redraw(self):
        # TODO: set correct ranges, fix axis range (axes.xlim)
        print 'redrawing xxxx'
        figure = self.figure
        figure.clear()
        var_data = self.correl_data.corr_arr
        id = self.cut_slider
        if self.cut_slider_on == True:
            i = self.cut_slider
            j = self.vcut_slider
            plot_data = getattr(self.data, self.correl_data.var_enum_)
            # plot_data = vstack( [plot_data[:, i], plot_data[:, j]] ).T
            # plot only values > -1
            # plot_data = plot_data[prod( plot_data >= 0, axis = 1, dtype = bool )]
            plot_data_x = plot_data[:, i]
            plot_data_y = plot_data[:, j]
            plot_data_corr = min(corrcoef(plot_data_x, plot_data_y))
            plot_data_corr_spear = spearmanr(plot_data_x, plot_data_y)[0]

            left, width = 0.1, 0.65
            bottom, height = 0.1, 0.65
            bottom_h = left_h = left + width + 0.02

            rect_scatter = [left, bottom, width, height]
            rect_histx = [left, bottom_h, width, 0.2]
            rect_histy = [left_h, bottom, 0.2, height]

            axScatter = figure.add_axes(rect_scatter)
            axHistx = figure.add_axes(rect_histx)
            axHisty = figure.add_axes(rect_histy)
            axScatter.clear()
            axHistx.clear()
            axHisty.clear()

            from matplotlib.ticker import NullFormatter
            axHistx.xaxis.set_major_formatter(NullFormatter())
            axHisty.yaxis.set_major_formatter(NullFormatter())

            axScatter.scatter(plot_data_x,
                               plot_data_y)

            # binwidth = 0.25
            # xymax = max( [max( abs( self.data.cf[:, j] ) ), max( abs( self.data.cf[:, i] ) )] )
            # lim = ( int( xymax / binwidth ) + 1 ) * binwidth

            # axScatter.set_xlim( ( -lim, lim ) )
            # axScatter.set_ylim( ( -lim, lim ) )

            # bins = arange( -lim, lim + binwidth, binwidth )
            axHistx.hist(plot_data_x.compressed(), bins=40)
            axHisty.hist(plot_data_y.compressed(), bins=40, orientation='horizontal')
            axHistx.set_xlim(axScatter.get_xlim())
            axHisty.set_ylim(axScatter.get_ylim())

            axScatter.set_xlabel('$\mathrm{cut\, %i}$' % self.cut_slider, fontsize=16)
            axScatter.set_ylabel('$\mathrm{cut\, %i}$' % self.vcut_slider, fontsize=16)
            axScatter.text(axScatter.get_xlim()[0], axScatter.get_ylim()[0],
                             'actual set correlation %.3f (Pearson), %.3f (Spearman)' % (plot_data_corr, plot_data_corr_spear), color='r')

        if self.cut_slider_on == False:
            figure.add_axes(self.axes_adjust)
            axes = figure.axes[0]
            axes.clear()
            x_coor = self.data.x_coord
            axes.grid()
            for i in range(0, var_data.shape[1]):
                axes.plot(x_coor[i:] - x_coor[i],
                           var_data[i, (i):], '-x', color=self.color)
            # approximate by the polynomial (of the i-th order)
            # axes.plot( x_coor, self.correl_data.peval( x_coor, self.correl_data.fit_correl ), 'b', linewidth = 3 )
            setp(axes.get_xticklabels(), position=(0, -.025))
            axes.set_xlabel('$x \, [\mathrm{mm}]$', fontsize=15)
            axes.set_ylabel('$\mathrm{correlation}$', fontsize=15)
            axes.set_ylim(-1, 1)

        self.data_changed = True


    traits_view = View(Group(Item('correl_data', show_label=False, style='custom'),
                              HGroup(
                       Item('cut_slider_on', label='Scatter'),
                       Item('cut_slider', show_label=False, springy=True, enabled_when='cut_slider_on == True'),
                       Item('vcut_slider', show_label=False, springy=True, enabled_when='cut_slider_on == True'),
                       ),
                       Group(Item('figure', style='custom',
                              editor=MPLFigureEditor(),
                              show_label=False)
                              , id='figure.view'),
                       ),
                       resizable=True,
                        )
Esempio n. 23
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()))
Esempio n. 24
0
class YarnPullOut(HasTraits):
    '''Idealization of the double sided pullout using the SPIRRID
    statistical integration tool.
    '''
    rf = Instance(DoublePulloutSym)

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


#        return DoublePulloutSym( tau_fr = 2.5, l = 0.01, d = 25.5e-3, E_mod = 70.0e3,
#                                 theta = 0.01, xi = 0.0179, phi = 1., n_f = 1723 )

    figure = Instance(Figure)

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

    pdf_theta_on = Bool(True)
    pdf_l_on = Bool(True)
    pdf_phi_on = Bool(True)
    pdf_xi_on = Bool(True)

    pdf_xi = Instance(IPDistrib)

    def _pdf_xi_default(self):
        pd = PDistrib(distr_choice='weibull_min', n_segments=30)
        pd.distr_type.set(shape=4.54, scale=0.017)
        return pd

    n_f = Float(1,
                auto_set=False,
                enter_set=True,
                desc='Number of filaments in the yarn')

    pdf_theta = Instance(IPDistrib)

    pdf_l = Instance(IPDistrib)

    pdf_phi = Instance(IPDistrib)

    run = Button

    def _run_fired(self):
        self._redraw()

    clear = Button

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

    w_max = Float(1.0, enter_set=True, auto_set=False)

    n_w_pts = Int(100, enter_set=True, auto_set=False)

    n_G_ipts = Int(30, enter_set=True, auto_set=False)

    e_arr = Property(Array, depends_on='w_max, n_w_pts')

    def _get_e_arr(self):
        return linspace(0.00, self.w_max, self.n_w_pts)

    lab = Str(' ', enter_set=True, auto_set=False)

    data_changed = Event(True)

    def _redraw(self):

        s = SPIRRID(
            q=self.rf,
            sampling_type='LHS',
            e_arr=self.e_arr,
            n_int=self.n_G_ipts,
            theta_vars=dict(tau_fr=2.6,
                            l=0.0,
                            d=25.5e-3,
                            E_mod=72.0e3,
                            theta=0.0,
                            xi=0.0179,
                            phi=1.,
                            L=30.0),
            # codegen_type='weave'
        )
        # construct the random variables

        if self.pdf_xi_on:
            s.theta_vars['xi'] = RV(
                'weibull_min', shape=4.54, scale=0.017
            )  # RV( pd = self.pdf_xi, name = 'xi', n_int = self.n_G_ipts )

        print self.pdf_theta.interp_ppf([0.01, 0.02])
        print YMB_RV('theta', distr=self.pdf_theta,
                     n_int=self.n_G_ipts).distr.interp_ppf([0.01, 0.02])
        if self.pdf_theta_on:
            s.theta_vars['theta'] = YMB_RV('theta',
                                           distr=self.pdf_theta,
                                           n_int=self.n_G_ipts)

        if self.pdf_l_on:
            s.theta_vars['l'] = YMB_RV('l',
                                       distr=self.pdf_l,
                                       n_int=self.n_G_ipts)

        if self.pdf_phi_on:
            s.theta_vars['phi'] = YMB_RV('phi',
                                         distr=self.pdf_phi,
                                         n_int=self.n_G_ipts)

        # print 'checking unity', s.mu_q_arr()

        mu = s.mu_q_arr
        axes = self.figure.axes[0]
        # TODO:
        axes.plot(self.e_arr, mu * self.n_f, linewidth=2, label=self.lab)

        axes.set_xlabel('crack opening w[mm]')
        axes.set_ylabel('force P[N]')
        axes.legend(loc='best')

        self.data_changed = True

    view = View(HSplit(
        Group(Item('rf@', show_label=False), label='Response function'),
        Tabbed(
            Group(
                Item('pdf_theta_on', show_label=False),
                Item('pdf_theta@', show_label=False),
                label='Slack',
            ),
            Group(
                Item('pdf_l_on', show_label=False),
                Item('pdf_l@', show_label=False),
                label='Contact free length',
            ),
            Group(
                Item('pdf_phi_on', show_label=False),
                Item('pdf_phi@', show_label=False),
                label='Contact fraction',
            ),
            Group(
                Item('pdf_xi_on', show_label=False),
                Item('pdf_xi@', show_label=False),
                label='Strength',
            ),
            label='yarn data',
            scrollable=True,
            id='ymb.pullout.dist',
            dock='tab',
        ),
        Group(
            HGroup(Item('run', show_label=False, springy=True),
                   Item('clear', show_label=False, springy=True)),
            HGroup(
                Item('w_max',
                     show_label=True,
                     springy=True,
                     tooltip='maximum crack-opening displacement'),
                Item('n_w_pts',
                     show_label=True,
                     springy=True,
                     tooltip='number of points for crack-opening'),
                Item('n_G_ipts',
                     show_label=True,
                     springy=True,
                     tooltip=
                     'number of integration points for the random variables'),
                Item('lab',
                     show_label=True,
                     springy=True,
                     tooltip='label of pull-out curve'),
            ),
            Item('figure',
                 style='custom',
                 editor=MPLFigureEditor(),
                 show_label=False),
            label='Pull-out response',
            id='ymb.pullout.figure',
            dock='tab',
        ),
        id='ymb.pullout.split',
        dock='tab',
    ),
                id='ymb.pullout',
                resizable=True,
                scrollable=True,
                dock='tab',
                width=0.8,
                height=0.4)