Exemple #1
0
    def _pipeline_view(self, show_label=True):
        import wx
        if wx.GetApp() is None:
            return None

        import traitsui.api as tui
        modname = ','.join(
            self.inputs
        ) + ' -> ' + self.__class__.__name__ + ' -> ' + ','.join(self.outputs)

        if show_label:
            return tui.View(tui.Group(self._view_items(), label=modname))
        else:
            return tui.View(self._view_items())
Exemple #2
0
class Load(t.HasTraits):
    filename = t.File
    traits_view = tu.View(
        tu.Group('filename'),
        kind='livemodal',
        buttons=[OKButton, CancelButton],
        title='Load file')
Exemple #3
0
class SmoothingTV(Smoothing):
    smoothing_parameter = t.Float(200)

    view = tu.View(
        tu.Group(
            'smoothing_parameter',
            'line_color'),
        kind='live',
        handler=SmoothingHandler,
        buttons=OKCancelButtons,
        title='Total Variation Smoothing',)

    def _smoothing_parameter_changed(self, old, new):
        self.update_lines()

    def _number_of_iterations_changed(self, old, new):
        self.update_lines()

    def model2plot(self, axes_manager=None):
        self.single_spectrum.data = self.signal().copy()
        self.single_spectrum.smooth_tv(
            smoothing_parameter=self.smoothing_parameter,
            show_progressbar=False)

        return self.single_spectrum.data
Exemple #4
0
class Element(traits.HasTraits):
    """parent class for a defined element. Element can be chosen as
    a physics property in the physics tab and allow fits to calculate
    properties of atomic clouds"""
    nameID = traits.String(
        desc="name of element for dictionary key (no superscripts etc)")
    massATU = traits.Float(22.9897692807,
                           label="mass (u)",
                           desc="mass in atomic mass units")
    decayRateMHz = traits.Float(
        9.7946,
        label=u"Decay Rate \u0393 (MHz)",
        desc="decay rate/ natural line width of 2S1/2 -> 2P3/2")

    crossSectionSigmaPlus = traits.Float(
        1.6573163925E-13,
        label=u"cross section \u03C3 + (m^2)",
        desc=
        "resonant cross section 2S1/2 -> 2P3/2. Warning not accurate for 6Li yet"
    )

    scatteringLength = traits.Float(62.0, label="scattering length (a0)")
    IsatSigmaPlus = traits.Float(6.260021,
                                 width=10,
                                 label=u"Isat (mW/cm^2)",
                                 desc="I sat sigma + 2S1/2 -> 2P3/2")

    traits_view = traitsui.View(
        traitsui.VGroup(
            traitsui.Item("nameID", style="readonly"),
            traitsui.Item("massATU", style="readonly"),
            traitsui.Item("decayRateMHz", style="readonly"),
            traitsui.Item("crossSectionSigmaPlus", style="readonly"),
            traitsui.Item("scatteringLength"),
            traitsui.Item("IsatSigmaPlus", style="readonly")))
Exemple #5
0
class HCFF2(tr.HasStrictTraits):
    '''High-Cycle Fatigue Filter
    '''

    hcf = tr.Instance(HCFFRoot)

    def _hcf_default(self):
        return HCFFRoot(import_manager=FileImportManager())

    figure = tr.Instance(Figure)

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

    traits_view = ui.View(
        ui.HSplit(
            ui.Item(name='hcf',
                    editor=tree_editor,
                    show_label=False,
                    width=0.3
                    ),
            ui.UItem('figure', editor=MPLFigureEditor(),
                     resizable=True,
                     springy=True,
                     label='2d plots')
        ),
        title='HCF Filter',
        resizable=True,
        width=0.6,
        height=0.6
    )
Exemple #6
0
def load(obj, **kwargs):
    view = tu.View(tu.Group(
        tu.Item('filename', editor=FileEditor(dialog_style='open')), "lazy"),
                   kind='livemodal',
                   buttons=[OKButton, CancelButton],
                   title='Load file')
    return obj, {"view": view}
class AxisSelector(traits.HasTraits):
    """here we select what axes the user should use when plotting this data """
    masterList = traits.List
    masterListWithNone =  traits.List
    xAxis = traits.Enum(values="masterList")
    yAxis = traits.Enum(values="masterList")
    series = traits.Enum(values="masterListWithNone")
    
    traits_view=traitsui.View(traitsui.VGroup(traitsui.Item("xAxis",label="x axis"),traitsui.Item("yAxis",label="y axis"),
                                  traitsui.Item("series",label="series"),show_border=True, label="axes selection"))
    
    def __init__(self, **traitsDict):
        """allows user to select which axes are useful for plotting in this log"""
        super(AxisSelector, self).__init__(**traitsDict)
    
    
    def _masterList_default(self):
        """gets the header row of log file which are interpreted as the column
        names that can be plotted."""
        logger.info("updating master list of axis choices")
        logger.debug("comment file = %s" % self.logFile)
        logger.debug( "comment file = %s" % self.logFile)
        if not os.path.exists(self.logFile):
            return []
        try:
            with open(self.logFile) as csvfile:
                headerReader = csv.reader(csvfile)
                headerRow=headerReader.next()
            return headerRow
        except IOError:
            return []
            
    def _masterListWithNone_default(self):
        return ["None"]+self._masterList_default()
class _H5Trees(api.HasTraits):
    h5_trees = api.Instance(Hdf5FilesNode)
    node = api.Any()
    path = api.Str()

    traits_view = ui.View(
        ui.Group(
            ui.Item(
                'h5_trees',
                editor=_hdf5_tree_editor(selected='node'),
                resizable=True,
            ),
            ui.Item('path', label='Selected node'),
            orientation='vertical',
        ),
        title='Multiple HDF5 file Tree Example',
        buttons=['OK', 'Cancel'],
        resizable=True,
        width=0.3,
        height=0.3,
    )

    def _node_changed(self):
        self.path = self.node.path
        print(self.node.path)
class cash_flow_series(trapi.HasTraits):
    name = trapi.Str
    short_rate = trapi.Range(0.0, 0.5, 0.05)
    time_list = trapi.Array(dtype=np.float, shape=(1, 6))
    cash_flows = trapi.Array(dtype=np.float, shape=(1, 6))
    disc_values = trapi.Array(dtype=np.float, shape=(1, 6))
    present_values = trapi.Array(dtype=np.float, shape=(1, 6))
    net_present_value = trapi.Float
    update = trapi.Button

    def _update_fired(self):
        self.disc_values = np.exp(-self.short_rate * self.time_list)
        self.present_values = self.disc_values * self.cash_flows
        self.net_present_value = np.sum(self.present_values)

    v = trui.View(trui.Group(trui.Item(name='name'),
                             trui.Item(name='short_rate'),
                             trui.Item(name='time_list', label='Time List'),
                             trui.Item(name='cash_flows', label='Cash Flows'),
                             trui.Item('update', show_label=False),
                             trui.Item(name='disc_values',
                                       label='Discount Factors'),
                             trui.Item(name='present_values',
                                       label='Present Values'),
                             trui.Item(name='net_present_value',
                                       label='Net Present Value'),
                             show_border=True,
                             label='Calculate Present Values'),
                  buttons=[trui.OKButton, trui.CancelButton],
                  resizable=True)
def createOption(name, initialValue):
    """creates an option with a boolean attribute as the value, type should be the result of type(value)"""
    option = Option(name=name)
    if type(initialValue) is bool:
        option.add_trait("value", traits.Bool(initialValue))
    elif type(initialValue) is int:
        option.add_trait("value", traits.Int(initialValue))
    elif type(initialValue) is float:
        option.add_trait("value", traits.Float(initialValue))
    elif type(initialValue) is str:
        option.add_trait("value", traits.File(initialValue))
        # # need to modify the view, not sure how to make this more elegantly
        option.traits_view = traitsui.View(
            traitsui.HGroup(
                traitsui.Item("name",
                              style="readonly",
                              springy=True,
                              show_label=False),
                traitsui.Item(
                    "value",
                    show_label=False,
                    springy=True,
                    editor=traitsui.FileEditor(dialog_style='save'))))
    else:
        logger.warning(
            "unrecognised option type ({}) in processor. Using traits.Any Editor and value"
            .format(type(initialValue)))
        option.add_trait("value", traits.Any(initialValue))
    return option
Exemple #11
0
class TEMParametersUI(t.HasTraits):

    beam_energy = t.Float(t.Undefined,
                          label='Beam energy (keV)')
    real_time = t.Float(t.Undefined,
                        label='Real time (s)')
    tilt_stage = t.Float(t.Undefined,
                         label='Stage tilt (degree)')
    live_time = t.Float(t.Undefined,
                        label='Live time (s)')
    probe_area = t.Float(t.Undefined,
                         label='Beam/probe area (nm^2)')
    azimuth_angle = t.Float(t.Undefined,
                            label='Azimuth angle (degree)')
    elevation_angle = t.Float(t.Undefined,
                              label='Elevation angle (degree)')
    energy_resolution_MnKa = t.Float(t.Undefined,
                                     label='Energy resolution MnKa (eV)')
    beam_current = t.Float(t.Undefined,
                           label='Beam current (nA)')

    traits_view = tu.View(
        tu.Group('beam_energy',
                 'tilt_stage',
                 'probe_area',
                 'beam_current',
                 label='TEM', show_border=True),
        tu.Group('real_time', 'live_time', 'azimuth_angle',
                 'elevation_angle', 'energy_resolution_MnKa',
                 label='EDS', show_border=True),
        kind='modal', buttons=[OKButton, CancelButton],
        title='TEM parameters definition wizard')
class ConjointCalcState(_traits.HasTraits):
    messages = _traits.Str()
    is_done = _traits.Bool(True)

    traits_view = _traitsui.View(
        _traitsui.Item('messages',
                       show_label=False,
                       springy=True,
                       style='custom'),
        title='Conjoint calculation status',
        height=300,
        width=600,
        resizable=True,
        buttons=[
            # _traitsui.Action(name='Cancel', action='_on_close', enabled_when='not is_done'),
            _traitsui.Action(name='OK',
                             action='_on_close',
                             enabled_when='is_done')
        ],
    )

    def _messages_changed(self, new):
        self.messages = '\n'.join(
            [line for line in new.split('\n') if not line.startswith('try')])

    def _is_done_changed(self, new):
        pass
Exemple #13
0
def rectangular_roi_traitsui(obj, **kwargs):
    view = tu.View(
        tu.Group(
            tu.Item(
                'left',
                label='Left',
                format_str='%5g',
            ),
            tu.Item(
                'right',
                label='Right',
                format_str='%5g',
            ),
            tu.Item(
                'top',
                label='Top',
                format_str='%5g',
            ),
            tu.Item(
                'bottom',
                label='Bottom',
                format_str='%5g',
            ),
        ), )
    return obj, {"view": view}
Exemple #14
0
def line2d_roi_traitsui(obj, **kwargs):
    view = tu.View(
        tu.Group(
            tu.Item(
                'x1',
                label='x1',
                format_str='%5g',
            ),
            tu.Item(
                'y1',
                label='y1',
                format_str='%5g',
            ),
            tu.Item(
                'x2',
                label='x2',
                format_str='%5g',
            ),
            tu.Item(
                'y2',
                label='y2',
                format_str='%5g',
            ),
            tu.Item(
                'linewidth',
                label='linewidth',
                format_str='%5g',
            ),
        ), )
    return obj, {"view": view}
def get_data_axis_view(navigate, label):
    group_args = [
        tui.Item(name='name'),
        tui.Item(name='size', style='readonly'),
        tui.Item(name='index_in_array', style='readonly'),
        tui.Item(name='units'),

    ]
    if navigate:
        group_args.extend([
            tui.Item(name='index'),
            tui.Item(name='value', style='readonly'), ])
    data_axis_view = tui.View(
        tui.Group(
            tui.Group(*group_args,
                      show_border=True,),
            tui.Group(
                tui.Item(name='scale'),
                tui.Item(name='offset'),
                label='Calibration',
                show_border=True,),
            # label="Data Axis properties",
            show_border=True,),
        title=label,)
    return data_axis_view
Exemple #16
0
class AutoRefreshDialog(traits.HasTraits):

    minutes = traits.Float(1.0)
    autoRefreshBool = traits.Bool()

    emailAlertBool = traits.Bool(False)
    soundAlertBool = traits.Bool(False)
    linesOfDataFrame = traits.Range(1, 10)
    alertCode = traits.Code(
        DEFAULT_ALERT_CODE,
        desc="python code for finding alert worthy elements")

    basicGroup = traitsui.Group("minutes", "autoRefreshBool")
    alertGroup = traitsui.VGroup(
        traitsui.HGroup(traitsui.Item("emailAlertBool"),
                        traitsui.Item("soundAlertBool")),
        traitsui.Item("linesOfDataFrame",
                      visible_when="emailAlertBool or soundAlertBool"),
        traitsui.Item("alertCode",
                      visible_when="emailAlertBool or soundAlertBool"))

    traits_view = traitsui.View(traitsui.VGroup(basicGroup, alertGroup),
                                title="auto refresh",
                                buttons=[OKButton],
                                kind='livemodal',
                                resizable=True)
Exemple #17
0
class SmoothingSavitzkyGolay(Smoothing):
    polynomial_order = t.Int(3)
    number_of_points = t.Int(5)
    crop_diff_axis = False
    view = tu.View(
        tu.Group('polynomial_order', 'number_of_points', 'differential_order',
                 'line_color'),
        kind='live',
        handler=SmoothingHandler,
        buttons=OKCancelButtons,
        title='Savitzky-Golay Smoothing',
    )

    def _polynomial_order_changed(self, old, new):
        self.update_lines()

    def _number_of_points_changed(self, old, new):
        self.update_lines()

    def _differential_order(self, old, new):
        self.update_lines()

    def diff_model2plot(self, axes_manager=None):
        smoothed = spectrum_tools.sg(self.signal(), self.number_of_points,
                                     self.polynomial_order,
                                     self.differential_order)
        return smoothed

    def model2plot(self, axes_manager=None):
        smoothed = spectrum_tools.sg(self.signal(), self.number_of_points,
                                     self.polynomial_order, 0)
        return smoothed
Exemple #18
0
class ButterworthFilter(Smoothing):
    cutoff_frequency_ratio = t.Range(0., 1., 0.05)
    type = t.Enum('low', 'high')
    order = t.Int(2)

    view = tu.View(
        tu.Group('cutoff_frequency_ratio', 'order', 'type'),
        kind='live',
        handler=SmoothingHandler,
        buttons=OKCancelButtons,
        title='Butterworth filter',
    )

    def _cutoff_frequency_ratio_changed(self, old, new):
        self.update_lines()

    def _type_changed(self, old, new):
        self.update_lines()

    def _order_changed(self, old, new):
        self.update_lines()

    def model2plot(self, axes_manager=None):
        b, a = sp.signal.butter(self.order, self.cutoff_frequency_ratio,
                                self.type)
        smoothed = sp.signal.filtfilt(b, a, self.signal())
        return smoothed
Exemple #19
0
class SmoothingLowess(Smoothing):
    smoothing_parameter = t.Float(2 / 3.)
    number_of_iterations = t.Int(3)
    differential_order = t.Int(0)
    view = tu.View(
        tu.Group('smoothing_parameter', 'number_of_iterations',
                 'differential_order', 'line_color'),
        kind='live',
        handler=SmoothingHandler,
        buttons=OKCancelButtons,
        title='Lowess Smoothing',
    )

    def _smoothing_parameter_changed(self, old, new):
        self.update_lines()

    def _number_of_iterations_changed(self, old, new):
        self.update_lines()

    def model2plot(self, axes_manager=None):
        smoothed = utils.lowess(self.axis, self.signal(),
                                self.smoothing_parameter,
                                self.number_of_iterations)

        return smoothed
Exemple #20
0
 def __init__(self, assembly, source, escaping=1., ray_selector=None):
     """
     TracerScene manages a MayaVi scene with one tracer assembly and one
     tracer ray bundle. It redraws the assembly whenever it is replaced, 
     and the path of the source rays from the given source bundle to their
     escape from the system.
     
     Arguments:
     assembly - the assembly to be used for tracing, an Assembly instance.
         The assembly's surfaces are drawn on the scene. All surfaces must
         provide a mesh() method.
     source - a RayBundle instance with the rays to trace.
     """
     t_api.HasTraits.__init__(self)
     self._esc = escaping
     
     self.set_assembly(assembly)
     self._source = source
     
     # Trace control:
     self._num_trace_iters = 200000000 # default to infinity, pretty much
     self._min_energy = 0.05
     
     # First plot:
     self._lines = None
     self._ray_selector = ray_selector
     self.plot_ray_trace()
     
     # Default view:
     self.view = tui.View(self.scene_view_item())
Exemple #21
0
    def __init__(self, assembly, source):
        """
        TracerScene manages a MayaVi scene with one tracer assembly and one
        tracer ray bundle. It redraws the assembly whenever it is replaced, 
        and the path of the source rays from the given source bundle to their
        escape from the system.
        
        Arguments:
        assembly - the assembly to be used for tracing, an Assembly instance.
            The assembly's surfaces are drawn on the scene. All surfaces must
            provide a mesh() method.
        source - a RayBundle instance with the rays to trace.
        """
        t_api.HasTraits.__init__(self)
        self._esc = 1.

        self.set_assembly(assembly)
        self._source = source

        # First plot:
        self._lines = []
        self.plot_ray_trace()

        # Default view:
        self.view = tui.View(self.scene_view_item())
Exemple #22
0
class Something(tr.HasTraits):

    txt_file_name = tr.File

    openTxt = tr.Button('Open...')

    a = tr.Int(20, auto_set=False, enter_set=True,
               input=True)

    b = tr.Float(20, auto_set=False, enter_set=True,
                 input=True)

    @tr.on_trait_change('+input')
    def _handle_input_change(self):
        print('some input parameter changed')
        self.input_event = True

    input_event = tr.Event

    def _some_event_changed(self):
        print('input happend')

    def _openTxt_fired(self):
        print('do something')
        print(self.txt_file_name)

    traits_view = ui.View(
        ui.VGroup(
            ui.HGroup(
                ui.Item('openTxt', show_label=False),
                ui.Item('txt_file_name', width=200),
                ui.Item('a')
            ),
        )
    )
class FileSelectedFrame(ta.HasTraits):
    """
    Frame for current files selected
    """

    file_list = ta.List(ta.Str, [])

    Add_File = ta.Button()
    Add_Folder = ta.Button()
    Undo_Add = ta.Button()

    view = tua.View(tua.Item('file_list'),
                    tua.Item('Add_File', show_label=False),
                    tua.Item('Add_Folder', show_label=False),
                    tua.Item('Undo_Add', show_label=False),
                    resizable=True)

    def _Add_File_fired(self):
        global select_files
        self.file_list.append(select_files.file_name)

    def _Add_Folder_fired(self):
        global select_files
        self.file_list += GetAllPDF(select_files.file_directory)

    def _Undo_Add_fired(self):
        del self.file_list[-1]
class CrossSection(BMCSLeafNode, RInputRecord):
    '''Parameters of the pull-out cross section
    '''
    node_name = 'cross-section'

    R_m = tr.Float(20,
                   CS=True,
                   input=True,
                   unit=r'$\mathrm{mm}$',
                   symbol=r'R_\mathrm{m}',
                   auto_set=False,
                   enter_set=True,
                   desc='matrix area')
    R_f = tr.Float(1.0,
                   CS=True,
                   input=True,
                   unit='$\\mathrm{mm}$',
                   symbol='R_\mathrm{f}',
                   auto_set=False,
                   enter_set=True,
                   desc='reinforcement area')
    P_b = tr.Property(unit='$\\mathrm{mm}$',
                      symbol='p_\mathrm{b}',
                      desc='perimeter of the bond interface',
                      depends_on='R_f')

    @tr.cached_property
    def _get_P_b(self):
        return 2 * np.pi * self.R_f

    view = ui.View(ui.Item('R_m'), ui.Item('R_f'),
                   ui.Item('P_b', style='readonly'))

    tree_view = view
class EntryBlock(traits.HasTraits):
    
    fieldName = traits.String("fieldName",desc = "describes what the information to be entered in the text block is referring to")
    textBlock = traits.String()
    commitButton = traits.Button("save",desc="commit information in text block to logFile")

    
    traits_view = traitsui.View(traitsui.VGroup(
                    traitsui.Item("fieldName",show_label=False, style="readonly"),
                    traitsui.Item("textBlock",show_label=False, style="custom"),
                    traitsui.Item("commitButton",show_label=False), show_border=True, label="information"
                        ))
    
    def __init__(self, **traitsDict):
        """user supplies arguments in init to supply class attributes defined above """
        super(EntryBlock,self).__init__(**traitsDict)
        
    def _commitButton_fired(self):
        logger.info("saving %s info starting" % self.fieldName)
        timeStamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        blockDelimiterStart = "__"+self.fieldName+"__<start>"
        blockDelimiterEnd = "__"+self.fieldName+"__<end>"
        fullString = "\n"+blockDelimiterStart+"\n"+timeStamp+"\n"+self.textBlock+"\n"+blockDelimiterEnd+"\n"
        with open(self.commentFile, "a+") as writeFile:
            writeFile.write(fullString)
        logger.info("saving %s info finished" % self.fieldName)
    
    def clearTextBlock(self):
        self.textBlock = ""
Exemple #26
0
class EntryBlock(traits.HasTraits):

    fieldName = traits.String(
        "fieldName",
        desc=
        "describes what the information to be entered in the text block is referring to"
    )
    textBlock = traits.String()

    traits_view = traitsui.View(
        traitsui.VGroup(traitsui.Item("fieldName",
                                      show_label=False,
                                      style="readonly"),
                        traitsui.Item("textBlock",
                                      show_label=False,
                                      style="custom"),
                        show_border=True,
                        label="information"))

    def __init__(self, **traitsDict):
        """user supplies arguments in init to supply class attributes defined above """
        super(EntryBlock, self).__init__(**traitsDict)

    def clearTextBlock(self):
        self.textBlock = ""
class Viz3DTensorField(Viz3DField):
    def setup(self):
        m = mlab
        fname = self.vis3d.file_list[0]
        var = self.vis3d.var
        self.d = VTKXMLFileReader()
        self.d.initialize(fname)
        self.src = m.pipeline.add_dataset(self.d)
        self.warp_vector = m.pipeline.warp_vector(self.src)
        #self.surf = m.pipeline.surface(self.warp_vector)
        engine = m.get_engine()
        self.etc = ExtractTensorComponents()
        engine.add_filter(self.etc, self.warp_vector)
        surface2 = Surface()
        self.surface = surface2
        engine.add_filter(surface2, self.etc)
        lut = self.etc.children[0]
        lut.scalar_lut_manager.set(show_scalar_bar=True,
                                   show_legend=True,
                                   data_name=var)
        lut.scalar_lut_manager.scalar_bar.orientation = 'horizontal'
        lut.scalar_lut_manager.scalar_bar_representation.trait_set(
            maximum_size=np.array([100000, 100000]),
            minimum_size=np.array([1, 1]),
            position=np.array([0.3, 0.05]),
            position2=np.array([0.65, 0.1]),
        )

        lut.scalar_lut_manager.label_text_property.trait_set(
            font_family='times', italic=False, bold=False)
        lut.scalar_lut_manager.title_text_property.trait_set(
            font_family='times', italic=False, bold=False)
        self.etc.filter.scalar_mode = 'component'

    traits_view = ui.View()
def integrate_in_range_traitsui(obj, **kwargs):
    view = tu.View(
        buttons=[OKButton, CancelButton],
        title='Integrate in range',
        handler=SpanSelectorInSignal1DHandler,
    )
    return obj, {"view": view}
Exemple #29
0
class SpectrumRangeSelector(SpanSelectorInSpectrum):
    on_close = t.List()

    view = tu.View(
        tu.Item('ss_left_value', label='Left', style='readonly'),
        tu.Item('ss_right_value', label='Right', style='readonly'),
        handler=SpectrumRangeSelectorHandler,
        buttons=[OKButton, OurApplyButton, CancelButton],)
def interactive_range_selector(obj, **kwargs):
    spanner_items = get_spanner_left_right_items()
    view = tu.View(
        *spanner_items,
        handler=Signal1DRangeSelectorHandler,
        buttons=[OKButton, OurApplyButton, CancelButton],
    )
    return obj, {"view": view}