def control_panel(self): return VGroup( Item("m_perspective", label=u"变换矩阵", editor=ArrayEditor(format_str="%g")), Item("m_perspective2", label=u"变换矩阵", editor=ArrayEditor(format_str="%g")), Item("hessian_threshold", label=u"hessianThreshold"), Item("n_octaves", label=u"nOctaves") )
def control_panel(self): return VGroup( Item("size", label="图像大小"), Item("method", label="变换类型", width=250), Item("m_afffine", label="变换矩阵", editor=ArrayEditor(format_str="%g"), visible_when="method=='Affine'"), Item("m_perspective", label="变换矩阵", editor=ArrayEditor(format_str="%g"), visible_when="method=='Perspective'"), )
class Data(HasTraits): a = Array() def _a_default(self): a = np.array([[1.0, 2.0], [3.0, 4.0]]) return a traits_view = View(Item('a', editor=ArrayEditor()), Item('a', editor=ArrayEditor(), style='readonly'), Item('a', editor=ArrayEditor(width=48)))
def create_editor(self): """ Returns the default UI editor for the trait. """ editor = None auto_set = False if self.auto_set is None: auto_set = True enter_set = self.enter_set or False if self.shape is not None and len(self.shape) == 2: from traitsui.api import ArrayEditor editor = ArrayEditor(auto_set=auto_set, enter_set=enter_set) else: from traitsui.api import TupleEditor if self.dtype is None: types = Any else: types = dtype2trait(self.dtype) editor = TupleEditor( types=types, labels=self.labels or [], cols=self.cols or 1, auto_set=auto_set, enter_set=enter_set, ) return editor
class Test(HasPrivateTraits): # ------------------------------------------------------------------------- # Trait definitions: # ------------------------------------------------------------------------- three = Array(int, (3, 3)) four = Array(float, (4, 4), editor=ArrayEditor(width=-50)) # ------------------------------------------------------------------------- # Traits view definitions: # ------------------------------------------------------------------------- view = View( 'three', '_', 'three', '_', 'three~', '_', 'four', '_', 'four', '_', 'four~', title='ArrayEditor Test Case', resizable=True, )
def default_traits_view(self): # pylint: disable=no-self-use """ Create the default traits View object for the model Returns ------- default_traits_view : :py:class:`traitsui.view.View` The default traits View object for the model """ return View( Group( Group( Item( 'slice_coord_index', label=self.coord_label, editor=QRangeEditor( low_name='coord_low_index', high_name='coord_high_index', low_label_name='low_label', high_label_name='high_label', map_to_values_name='coord_map', mode='slider', is_float=False, ), padding=15, ), ), Item('plane_type', editor=EnumEditor(values={ 'Normal to X': '1:Normal to X', 'Normal to Y': '2:Normal to Y', 'Normal to Z': '3:Normal to Z', 'Arbitrary Plane': '4:Arbitrary Plane', }, format_func=str, cols=4), style='custom', show_label=False), Group(Item('normal', editor=ArrayEditor(width=-60)), Item('origin', editor=ArrayEditor(width=-60)), visible_when='plane_type == "Arbitrary Plane"')))
def default_traits_view(self): """ Create the default traits View object for the model. Returns ------- default_traits_view : :py:class:`traitsui.view.View` The default traits View object for the model. """ return View( Item('value', editor=ArrayEditor(width=-60, auto_set=False, enter_set=True), show_label=False))
class ArrayEditorTest(HasPrivateTraits): three = Array(Int, (3, 3)) four = Array(Float, (4, 4), editor=ArrayEditor(width=-50)) view = View(Item('three', label='3x3 Integer'), '_', Item('three', label='Integer Read-only', style='readonly'), '_', Item('four', label='4x4 Float'), '_', Item('four', label='Float Read-only', style='readonly'), buttons=NoButtons, resizable=True)
class FiducialsPanel(HasPrivateTraits): """Set fiducials on an MRI surface.""" model = Instance(MRIHeadWithFiducialsModel) fid_file = DelegatesTo('model') fid_fname = DelegatesTo('model') lpa = DelegatesTo('model') nasion = DelegatesTo('model') rpa = DelegatesTo('model') can_save = DelegatesTo('model') can_save_as = DelegatesTo('model') can_reset = DelegatesTo('model') fid_ok = DelegatesTo('model') locked = DelegatesTo('model', 'lock_fiducials') set = Enum('LPA', 'Nasion', 'RPA') current_pos_mm = Array(float, (1, 3)) save_as = Button(label='Save as...') save = Button(label='Save') reset_fid = Button(label=_RESET_LABEL) headview = Instance(HeadViewController) hsp_obj = Instance(SurfaceObject) picker = Instance(object) # the layout of the dialog created view = View(VGroup( HGroup(Item('fid_file', width=_MRI_FIDUCIALS_WIDTH, tooltip='MRI fiducials file'), show_labels=False), HGroup(Item('set', width=_MRI_FIDUCIALS_WIDTH, format_func=lambda x: x, style='custom', tooltip=_SET_TOOLTIP), show_labels=False), HGroup(Item('current_pos_mm', editor=ArrayEditor(width=_MM_WIDTH, format_func=_mm_fmt), tooltip='MRI fiducial position (mm)'), show_labels=False), HGroup(Item('save', enabled_when='can_save', tooltip="If a filename is currently specified, save to " "that file, otherwise save to the default file name", width=_BUTTON_WIDTH), Item('save_as', enabled_when='can_save_as', width=_BUTTON_WIDTH), Item('reset_fid', enabled_when='can_reset', width=_RESET_WIDTH, tooltip='Reset to file values (if available)'), show_labels=False), enabled_when="locked==False", show_labels=False), handler=SetHandler()) def __init__(self, *args, **kwargs): # noqa: D102 super(FiducialsPanel, self).__init__(*args, **kwargs) @on_trait_change('current_pos_mm') def _update_pos(self): attr = self.set.lower() if not np.allclose(getattr(self, attr), self.current_pos_mm * 1e-3): setattr(self, attr, self.current_pos_mm * 1e-3) @on_trait_change('model:lpa,model:nasion,model:rpa') def _update_fiducial(self, value): attr = self.set.lower() self.current_pos_mm = getattr(self, attr) * 1000 def _reset_fid_fired(self): self.model.reset = True def _save_fired(self): self.model.save() def _save_as_fired(self): if self.fid_file: default_path = self.fid_file else: default_path = self.model.default_fid_fname dlg = FileDialog(action="save as", wildcard=fid_wildcard, default_path=default_path) dlg.open() if dlg.return_code != OK: return path = dlg.path if not path.endswith('.fif'): path = path + '.fif' if os.path.exists(path): answer = confirm( None, "The file %r already exists. Should it " "be replaced?", "Overwrite File?") if answer != YES: return self.model.save(path) def _on_pick(self, picker): if self.locked: return self.picker = picker n_pos = len(picker.picked_positions) if n_pos == 0: logger.debug("GUI: picked empty location") return if picker.actor is self.hsp_obj.surf.actor.actor: idxs = [] idx = None pt = [picker.pick_position] elif self.hsp_obj.surf.actor.actor in picker.actors: idxs = [ i for i in range(n_pos) if picker.actors[i] is self.hsp_obj.surf.actor.actor ] idx = idxs[-1] pt = [picker.picked_positions[idx]] else: logger.debug("GUI: picked object other than MRI") return def round_(x): return round(x, 3) poss = [map(round_, pos) for pos in picker.picked_positions] pos = map(round_, picker.pick_position) msg = ["Pick Event: %i picked_positions:" % n_pos] line = str(pos) if idx is None: line += " <-pick_position" msg.append(line) for i, pos in enumerate(poss): line = str(pos) if i == idx: line += " <- MRI mesh" elif i in idxs: line += " (<- also MRI mesh)" msg.append(line) logger.debug('\n'.join(msg)) set_ = self.set.lower() assert set_ in _VIEW_DICT, set_ setattr(self, set_, pt) @on_trait_change('set') def _on_set_change(self, obj, name, old, new): new = new.lower() self._update_fiducial(None) setattr(self.headview, _VIEW_DICT[new], True)
# 2. Define a function `printer(value)` that prints an array, and set # it to be an external trait listener for the trait *y*. def printer(value): opt = get_printoptions() set_printoptions(precision=2) print("new value: ", value) set_printoptions(**opt) func.on_trait_change(printer, name='y') ''' Above sets the printer method to being an external trait listener for y ''' # 3. Create a UI that displays a, b, and c as text boxes. # Set up a view. simple_view = View('a', 'b', 'c') # Use it for your traits. func.edit_traits(view=simple_view) # 4. Create a UI that displays a, b, and c as sliders. slide_view = View(Item('a', editor=RangeEditor(low=0.0, high=15.0)), Item('b', editor=RangeEditor(low=0.0, high=15.0)), Item('c', editor=RangeEditor(low=0.0, high=15.0)), Item('x', editor=ArrayEditor()), Item('y', editor=ArrayEditor(), style='readonly'), resizable=True) func.edit_traits(view=slide_view)
class DataSourceWizardView(DataSourceWizard): #---------------------------------------------------------------------- # Private traits #---------------------------------------------------------------------- _top_label = Str('Describe your data') _info_text = Str('Array size do not match') _array_label = Str('Available arrays') _data_type_text = Str("What does your data represents?") _lines_text = Str("Connect the points with lines") _scalar_data_text = Str("Array giving the value of the scalars") _optional_scalar_data_text = Str("Associate scalars with the data points") _connectivity_text = Str("Array giving the triangles") _vector_data_text = Str("Associate vector components") _position_text = Property(depends_on="position_type_") _position_text_dict = { 'explicit': 'Coordinnates of the data points:', 'orthogonal grid': 'Position of the layers along each axis:', } def _get__position_text(self): return self._position_text_dict.get(self.position_type_, "") _shown_help_text = Str _data_sources_wrappers = Property(depends_on='data_sources') def _get__data_sources_wrappers(self): return [ ArrayColumnWrapper(name=name, shape=repr(self.data_sources[name].shape)) for name in self._data_sources_names ] # A traits pointing to the object, to play well with traitsUI _self = Instance(DataSourceWizard) _suitable_traits_view = Property(depends_on="data_type_") def _get__suitable_traits_view(self): return "_%s_data_view" % self.data_type_ ui = Any(False) _preview_button = Button(label='Preview structure') def __preview_button_fired(self): if self.ui: self.build_data_source() self.preview() _ok_button = Button(label='OK') def __ok_button_fired(self): if self.ui: self.ui.dispose() self.build_data_source() _cancel_button = Button(label='Cancel') def __cancel_button_fired(self): if self.ui: self.ui.dispose() _is_ok = Bool _is_not_ok = Bool def _anytrait_changed(self): """ Validates if the OK button is enabled. """ if self.ui: self._is_ok = self.check_arrays() self._is_not_ok = not self._is_ok _preview_window = Instance(PreviewWindow, ()) _info_image = Instance(ImageResource, ImageLibrary.image_resource('@std:alert16', )) #---------------------------------------------------------------------- # TraitsUI views #---------------------------------------------------------------------- _coordinates_group = \ HGroup( Item('position_x', label='x', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('position_y', label='y', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('position_z', label='z', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), ) _position_group = \ Group( Item('position_type'), Group( Item('_position_text', style='readonly', resizable=False, show_label=False), _coordinates_group, visible_when='not position_type_=="image data"', ), Group( Item('grid_shape_source_', label='Grid shape', editor=EnumEditor( name='_grid_shape_source_labels', invalid='_is_not_ok')), HGroup( spring, Item('grid_shape', style='custom', editor=ArrayEditor(width=-60), show_label=False), enabled_when='grid_shape_source==""', ), visible_when='position_type_=="image data"', ), label='Position of the data points', show_border=True, show_labels=False, ), _connectivity_group = \ Group( HGroup( Item('_connectivity_text', style='readonly', resizable=False), spring, Item('connectivity_triangles', editor=EnumEditor(name='_data_sources_names'), show_label=False, ), show_labels=False, ), label='Connectivity information', show_border=True, show_labels=False, enabled_when='position_type_=="explicit"', ), _scalar_data_group = \ Group( Item('_scalar_data_text', style='readonly', resizable=False, show_label=False), HGroup( spring, Item('scalar_data', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), show_labels=False, ), label='Scalar value', show_border=True, show_labels=False, ) _optional_scalar_data_group = \ Group( HGroup( 'has_scalar_data', Item('_optional_scalar_data_text', resizable=False, style='readonly'), show_labels=False, ), Item('_scalar_data_text', style='readonly', resizable=False, enabled_when='has_scalar_data', show_label=False), HGroup( spring, Item('scalar_data', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok'), enabled_when='has_scalar_data'), show_labels=False, ), label='Scalar data', show_border=True, show_labels=False, ), _vector_data_group = \ VGroup( HGroup( Item('vector_u', label='u', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_v', label='v', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_w', label='w', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), ), label='Vector data', show_border=True, ), _optional_vector_data_group = \ VGroup( HGroup( Item('has_vector_data', show_label=False), Item('_vector_data_text', style='readonly', resizable=False, show_label=False), ), HGroup( Item('vector_u', label='u', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_v', label='v', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), Item('vector_w', label='w', editor=EnumEditor(name='_data_sources_names', invalid='_is_not_ok')), enabled_when='has_vector_data', ), label='Vector data', show_border=True, ), _array_view = \ View( Item('_array_label', editor=TitleEditor(), show_label=False), Group( Item('_data_sources_wrappers', editor=TabularEditor( adapter = ArrayColumnAdapter(), ), ), show_border=True, show_labels=False )) _questions_view = View( Item('_top_label', editor=TitleEditor(), show_label=False), HGroup( Item('_data_type_text', style='readonly', resizable=False), spring, 'data_type', spring, show_border=True, show_labels=False, ), HGroup( Item( '_self', style='custom', editor=InstanceEditor(view_name='_suitable_traits_view'), ), Group( # FIXME: Giving up on context sensitive help # because of lack of time. #Group( # Item('_shown_help_text', editor=HTMLEditor(), # width=300, # label='Help', # ), # show_labels=False, # label='Help', #), #Group( Item('_preview_button', enabled_when='_is_ok'), Item('_preview_window', style='custom', label='Preview structure'), show_labels=False, #label='Preview structure', #), #layout='tabbed', #dock='tab', ), show_labels=False, show_border=True, ), ) _point_data_view = \ View(Group( Group(_coordinates_group, label='Position of the data points', show_border=True, ), HGroup( 'lines', Item('_lines_text', style='readonly', resizable=False), label='Lines', show_labels=False, show_border=True, ), _optional_scalar_data_group, _optional_vector_data_group, # XXX: hack to have more vertical space Label('\n'), Label('\n'), Label('\n'), )) _surface_data_view = \ View(Group( _position_group, _connectivity_group, _optional_scalar_data_group, _optional_vector_data_group, )) _vector_data_view = \ View(Group( _vector_data_group, _position_group, _optional_scalar_data_group, )) _volumetric_data_view = \ View(Group( _scalar_data_group, _position_group, _optional_vector_data_group, )) _wizard_view = View( Group( HGroup( Item( '_self', style='custom', show_label=False, editor=InstanceEditor(view='_array_view'), width=0.17, ), '_', Item( '_self', style='custom', show_label=False, editor=InstanceEditor(view='_questions_view'), ), ), HGroup( Item('_info_image', editor=ImageEditor(), visible_when="_is_not_ok"), Item('_info_text', style='readonly', resizable=False, visible_when="_is_not_ok"), spring, '_cancel_button', Item('_ok_button', enabled_when='_is_ok'), show_labels=False, ), ), title='Import arrays', resizable=True, ) #---------------------------------------------------------------------- # Public interface #---------------------------------------------------------------------- def __init__(self, **traits): DataSourceFactory.__init__(self, **traits) self._self = self def view_wizard(self): """ Pops up the view of the wizard, and keeps the reference it to be able to close it. """ # FIXME: Workaround for traits bug in enabled_when self.position_type_ self.data_type_ self._suitable_traits_view self.grid_shape_source self._is_ok self.ui = self.edit_traits(view='_wizard_view') def preview(self): """ Display a preview of the data structure in the preview window. """ self._preview_window.clear() self._preview_window.add_source(self.data_source) data = lambda name: self.data_sources[name] g = Glyph() g.glyph.glyph_source.glyph_source = \ g.glyph.glyph_source.glyph_list[0] g.glyph.scale_mode = 'data_scaling_off' if not (self.has_vector_data or self.data_type_ == 'vector'): g.glyph.glyph_source.glyph_source.glyph_type = 'cross' g.actor.property.representation = 'points' g.actor.property.point_size = 3. self._preview_window.add_module(g) if not self.data_type_ in ('point', 'vector') or self.lines: s = Surface() s.actor.property.opacity = 0.3 self._preview_window.add_module(s) if not self.data_type_ == 'point': self._preview_window.add_filter(ExtractEdges()) s = Surface() s.actor.property.opacity = 0.2 self._preview_window.add_module(s)
class FiducialsPanel(HasPrivateTraits): """Set fiducials on an MRI surface.""" model = Instance(MRIHeadWithFiducialsModel) fid_file = DelegatesTo('model') fid_fname = DelegatesTo('model') lpa = DelegatesTo('model') nasion = DelegatesTo('model') rpa = DelegatesTo('model') can_save = DelegatesTo('model') can_save_as = DelegatesTo('model') can_reset = DelegatesTo('model') fid_ok = DelegatesTo('model') locked = DelegatesTo('model', 'lock_fiducials') set = Enum('LPA', 'Nasion', 'RPA') current_pos = Array(float, (1, 3), editor=ArrayEditor(width=50)) save_as = Button(label='Save As...') save = Button(label='Save') reset_fid = Button(label="Reset to File") headview = Instance(HeadViewController) hsp_obj = Instance(SurfaceObject) picker = Instance(object) # the layout of the dialog created view = View( VGroup(Item('fid_file', label='File'), Item('fid_fname', show_label=False, style='readonly'), Item('set', style='custom', width=50), Item('current_pos', label='Pos', width=50), HGroup(Item('save', enabled_when='can_save', tooltip="If a filename is currently " "specified, save to that file, otherwise " "save to the default file name", width=10), Item('save_as', enabled_when='can_save_as', width=10), Item('reset_fid', enabled_when='can_reset', width=10), show_labels=False), enabled_when="locked==False")) def __init__(self, *args, **kwargs): # noqa: D102 super(FiducialsPanel, self).__init__(*args, **kwargs) self.sync_trait('lpa', self, 'current_pos', mutual=True) def _reset_fid_fired(self): self.model.reset = True def _save_fired(self): self.model.save() def _save_as_fired(self): if self.fid_file: default_path = self.fid_file else: default_path = self.model.default_fid_fname dlg = FileDialog(action="save as", wildcard=fid_wildcard, default_path=default_path) dlg.open() if dlg.return_code != OK: return path = dlg.path if not path.endswith('.fif'): path = path + '.fif' if os.path.exists(path): answer = confirm( None, "The file %r already exists. Should it " "be replaced?", "Overwrite File?") if answer != YES: return self.model.save(path) def _on_pick(self, picker): if self.locked: return self.picker = picker n_pos = len(picker.picked_positions) if n_pos == 0: logger.debug("GUI: picked empty location") return if picker.actor is self.hsp_obj.surf.actor.actor: idxs = [] idx = None pt = [picker.pick_position] elif self.hsp_obj.surf.actor.actor in picker.actors: idxs = [ i for i in range(n_pos) if picker.actors[i] is self.hsp_obj.surf.actor.actor ] idx = idxs[-1] pt = [picker.picked_positions[idx]] else: logger.debug("GUI: picked object other than MRI") def round_(x): return round(x, 3) poss = [map(round_, pos) for pos in picker.picked_positions] pos = map(round_, picker.pick_position) msg = ["Pick Event: %i picked_positions:" % n_pos] line = str(pos) if idx is None: line += " <-pick_position" msg.append(line) for i, pos in enumerate(poss): line = str(pos) if i == idx: line += " <- MRI mesh" elif i in idxs: line += " (<- also MRI mesh)" msg.append(line) logger.debug(os.linesep.join(msg)) if self.set == 'Nasion': self.nasion = pt elif self.set == 'LPA': self.lpa = pt elif self.set == 'RPA': self.rpa = pt else: raise ValueError("set = %r" % self.set) @on_trait_change('set') def _on_set_change(self, obj, name, old, new): self.sync_trait(old.lower(), self, 'current_pos', mutual=True, remove=True) self.sync_trait(new.lower(), self, 'current_pos', mutual=True) if new == 'Nasion': self.headview.front = True elif new == 'LPA': self.headview.left = True elif new == 'RPA': self.headview.right = True
from ..tracking.interfaces import InputData, ShmTrackingInterface I = InputData() iview = I.trait_view() iview.resizable = True iview.width = 600 I.trait_view('traits_view', iview) main_view = View( Group( Group(Item('dwi_images'), Item('all_inputs'), Item('min_signal'), Item('seed_roi'), Item('seed_density', editor=ArrayEditor()), show_border=True), Group(Item('smoothing_kernel_type'), Item('smoothing_kernel'), show_border=True), Group(Item('interpolator'), Item('model_type'), Item('sh_order'), Item('Lambda'), Item('sphere_coverage'), Item('min_peak_spacing'), Item('min_relative_peak'), show_border=True), Group(Item('probabilistic'), show_border=True), Group( # Item( 'integrator' ),
# 2. Define a function `printer(value)` that prints an array, and set # it to be an external trait listener for the trait *y*. def printer(value): opt = get_printoptions() set_printoptions(precision=2) print 'new value:', value set_printoptions(**opt) func.on_trait_change(printer, name='y') func.a = 2.1 # 3. Create a UI that displays a, b, and c as text boxes. simple_view = View('a', 'b', 'c') func.edit_traits(view=simple_view) # 4. Create a UI that displays a, b, and c as sliders, and x and y # using ArrayEditors. slider_view = View( Item('a', editor=RangeEditor(low=0.0, high=10.0)), Item('b', editor=RangeEditor(low=0.0, high=10.0)), Item('c', editor=RangeEditor(low=0.0, high=10.0)), Item('x', style='readonly', editor=ArrayEditor(width=120)), Item('y', style='readonly', editor=ArrayEditor(width=120)), resizable=True, ) func.edit_traits(view=slider_view)
class SimplePskSimulationRunner(SimulationRunner, HasTraits): """Implements a simulation runner for a transmission with a PSK modulation through an AWGN channel. In order to implement a simulation runner, 3 steps are required: - The simulation parameters must be added to the self.params variable - The _run_simulation funtion must be implemented. It must receive a single SimulationParameters object which contains the simulation parameters. - The _keep_going may be optionally implemented. This class also inherits from HasTraits and the simulation parameters are traits. Because of this, we can configure the parameters graphically by calling the configure_traits method. In addition, attributes that depend on other attributes are automatically updated using the on_trait_change decorator. """ # Define the traits for the simulation parameters that the user may set SNR = Array() M = Int() NSymbs = Int() rep_max = Int() # rep_max is in the base class. Does traits works? max_bit_errors = Int() # Define traits for other attributes (that depend on other traits) modulator = Instance(mod.PSK) params = Instance(SimulationParameters) # # Action for when the "Simulate" button is clicked # simulate_action = Action(name="Simulate", # action="start_simulation") # Define the view used when the configure_traits method is called parameters_view = View( Group(Item('SNR', style='simple', editor=ArrayEditor(), label='SNR'), Item('M'), Item('NSymbs'), Item('max_bit_errors'), Item('rep_max'), label='Simulation Parameters', show_border=False), #handler=SimplePskSimulationRunnerHandler(), #buttons=[simulate_action, 'Cancel', 'Revert'], buttons=['OK', 'Cancel', 'Revert'], resizable=True, # Action if the user closes the window close_result=False) def __init__(self): # Call the __init__ function of the base classes SimulationRunner.__init__(self) HasTraits.__init__(self) # Set the simulations parameters as attributes here, but what is # really necessary is to set the self.params object self.SNR = np.array([5, 10, 15]) self.M = 4 self.NSymbs = 500 self.rep_max = 1000 # We will stop when the number of bit errors is greater than # max_bit_errors self.max_bit_errors = 200 # Message Exibited in the progressbar. Set to None to disable the # progressbar. See the comment on the SimulationRunner class. self.progressbar_message = "{M}-" + \ self.modulator.__class__.__name__ + " Simulation - SNR: {SNR}" @on_trait_change('M') def _update_modulator_object(self, ): """Updates the modulator object whenever M changes """ self.modulator = mod.PSK(self.M) @on_trait_change('SNR, NSymbs, M') def _update_params_object(self): """Updates the self.params object to the current values of the simulation aprameters""" # The self.params object must contain all the simulation parameters # that will be accessed in the 'simulate' function. self.params.add( "description", "Parameters for the simulation of a {0}-{1} transmission through an AWGN channel " .format(self.M, self.modulator.__class__.__name__)) self.params.add("SNR", self.SNR) # Modulation cardinality self.params.add("M", self.M) # Number of symbols that will be transmitted in the _run_simulation # function Unpack the SNR parameter self.params.add("NSymbs", self.NSymbs) self.params.set_unpack_parameter("SNR") def _run_simulation(self, current_parameters): # To make sure that this function does not modify the object state, # we sobrescibe self to None. #self = None # xxxxx Input parameters (set in the constructor) xxxxxxxxxxxxxxxxx NSymbs = current_parameters["NSymbs"] M = current_parameters["M"] SNR = current_parameters["SNR"] # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxx Input Data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx inputData = np.random.randint(0, M, NSymbs) # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxx Modulate input data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx modulatedData = self.modulator.modulate(inputData) # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxx Pass through the channel xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx noiseVar = 1 / dB2Linear(SNR) noise = ((np.random.standard_normal(NSymbs) + 1j * np.random.standard_normal(NSymbs)) * np.sqrt(noiseVar / 2)) receivedData = modulatedData + noise # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxx Demodulate received data xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx demodulatedData = self.modulator.demodulate(receivedData) # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxx Calculates the symbol and bit error rates xxxxxxxxxxxxxxxxx symbolErrors = sum(inputData != demodulatedData) bitErrors = misc.count_bit_errors(inputData, demodulatedData) numSymbols = inputData.size numBits = inputData.size * mod.level2bits(M) # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # xxxxx Return the simulation results xxxxxxxxxxxxxxxxxxxxxxxxxxxxx symbolErrorsResult = Result.create("symbol_errors", Result.SUMTYPE, symbolErrors) numSymbolsResult = Result.create("num_symbols", Result.SUMTYPE, numSymbols) bitErrorsResult = Result.create("bit_errors", Result.SUMTYPE, bitErrors) numBitsResult = Result.create("num_bits", Result.SUMTYPE, numBits) berResult = Result.create("ber", Result.RATIOTYPE, bitErrors, numBits) serResult = Result.create("ser", Result.RATIOTYPE, symbolErrors, numSymbols) simResults = SimulationResults() simResults.add_result(symbolErrorsResult) simResults.add_result(numSymbolsResult) simResults.add_result(bitErrorsResult) simResults.add_result(numBitsResult) simResults.add_result(berResult) simResults.add_result(serResult) return simResults def _keep_going(self, current_params, simulation_results, current_rep): """ Check if the simulation should continue or stop. Parameters ---------- current_params : SimulationParameters object SimulationParameters object with the parameters of the simulation. current_sim_results : SimulationResults object SimulationResults object from the last iteration (merged with all the previous results) current_rep : int Number of iterations already run. Returns ------- result : bool True if the simulation should continue or False otherwise. """ # Return true as long as cumulated_bit_errors is lower then # max_bit_errors cumulated_bit_errors = simulation_results['bit_errors'][-1].get_result( ) return cumulated_bit_errors < self.max_bit_errors