class Detection(wx.Dialog): flag = False def __init__(self, parent, title): wx.Dialog.__init__(self, parent, title=title, size=(400, 150), style=wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.CAPTION) self.InitUi() self.Center() def InitUi(self): self.seuil = 0 panel = wx.Panel(self) msizer = wx.GridBagSizer(0, 0) hbox1 = wx.BoxSizer(wx.HORIZONTAL) seuil_label = wx.StaticText(panel, -1, "Veuillez entrer le seuil de détection ") hbox1.Add(seuil_label, 1, flag=wx.ALL, border=5) self.seuil_spin = FloatSpin(panel, value=0.0, min_val=0.0, max_val=1, increment=0.01, digits=3, size=(100, -1)) """ self.seuil_spin= wx.SpinCtrl(panel, value="0") self.seuil_spin.SetRange(0, 1) self.seuil_spin.SetValue(0) """ hbox1.Add(self.seuil_spin, 0, flag=wx.ALL, border=3) msizer.Add(hbox1, pos=(1, 0), flag=wx.ALL, border=5) sizer = wx.GridBagSizer(0, 0) valider_btn = wx.Button(panel, 1, label="Valider") self.Bind(wx.EVT_BUTTON, self.OnValider, id=1) sizer.Add(valider_btn, pos=(0, 15), flag=wx.ALL | wx.EXPAND, border=5) msizer.Add(sizer, pos=(2, 0), flag=wx.ALL, border=5) panel.SetSizer(msizer) self.ShowModal() def OnValider(self, e): global flag self.seuil = self.seuil_spin.GetValue() Detection.flag = True self.Close()
class XAxisRangeBox(wx.Panel): """ panel for adjusting x-axis range """ def __init__(self, parent, ID, minvalue=XMIN, initvalue=XWIDTH, increment=SPININC): wx.Panel.__init__(self, parent, ID) self.minvalue = minvalue self.value = initvalue # initial x-axis range width (in sliding mode) # controls self.radio_full = wx.RadioButton(self, -1, label='Full range', style=wx.RB_GROUP) self.radio_slide = wx.RadioButton(self, -1, label='Sliding') self.slide_width = FloatSpin(self, -1, size=(50, -1), digits=0, value=self.value, min_val=minvalue, increment=increment) self.slide_width.GetTextCtrl().SetEditable(False) # event bindings self.Bind(wx.EVT_UPDATE_UI, self.on_update_radio_buttons, self.radio_full) self.Bind(EVT_FLOATSPIN, self.on_float_spin, self.slide_width) # layout box = wx.StaticBox(self, -1, 'X-axis') sizer = wx.StaticBoxSizer(box, wx.VERTICAL) slide_box = wx.BoxSizer(wx.HORIZONTAL) slide_box.Add(self.radio_slide, flag=wx.ALIGN_CENTER_VERTICAL) slide_box.Add(self.slide_width, flag=wx.ALIGN_CENTER_VERTICAL) sizer.Add(self.radio_full, 0, wx.ALL, 10) sizer.Add(slide_box, 0, wx.ALL, 10) self.SetSizer(sizer) sizer.Fit(self) def on_update_radio_buttons(self, event): """ called when the radio buttons are toggled """ self.slide_width.Enable(self.radio_slide.GetValue()) def on_float_spin(self, event): """ called when the sliding mode spinbox is changed """ self.value = self.slide_width.GetValue() def is_full(self): """ return True if full range is checked """ return self.radio_full.GetValue()
class MaskSettingsPanel(wx.Panel): def __init__(self, *args, **kwds): super(MaskSettingsPanel, self).__init__(*args, **kwds) self.params = args[0].phil_params self._pyslip = self.GetParent().GetParent().pyslip self.border_ctrl = None self.d_min_ctrl = None self.d_max_ctrl = None self.resolution_range_d_min_ctrl = None self.resolution_range_d_max_ctrl = None self.ice_rings_d_min_ctrl = None self.ice_rings_width_ctrl = None self._mode_rectangle_layer = None self._mode_polygon_layer = None self._mode_circle_layer = None self._rectangle_x0y0 = None self._rectangle_x1y1 = None self._mode_rectangle = False self._mode_polygon = False self._mode_polygon_points = [] self._mode_circle = False self._resolution_range_d_min = 0 self._resolution_range_d_max = 0 self._pyslip.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self._pyslip.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self._pyslip.Bind(wx.EVT_MOTION, self.OnMove) self.draw_settings() self.UpdateMask() def __del__(self): if self._mode_rectangle_layer: self._pyslip.DeleteLayer(self._mode_rectangle_layer) if self._mode_polygon_layer: self._pyslip.DeleteLayer(self._mode_polygon_layer) if self._mode_circle_layer: self._pyslip.DeleteLayer(self._mode_circle_layer) self._pyslip.Unbind(wx.EVT_LEFT_DOWN, handler=self.OnLeftDown) self._pyslip.Unbind(wx.EVT_LEFT_UP, handler=self.OnLeftUp) self._pyslip.Unbind(wx.EVT_MOTION, handler=self.OnMove) def draw_settings(self): for child in self.GetChildren(): if not isinstance(child, FloatSpin): # don't destroy FloatSpin controls otherwise bad things happen child.Destroy() sizer = self.GetSizer() if sizer is None: sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) sizer.Clear() # Put the border, d_min, d_max in an aligned grid box = wx.FlexGridSizer(cols=4, hgap=0, vgap=0) # border control if self.border_ctrl is None: self.border_ctrl = FloatSpin(self, digits=0, name="mask_border", min_val=0) box.Add(wx.StaticText(self, label="Border"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) box.Add( self.border_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5, ) box.Add(wx.StaticText(self, label="px"), 0, wx.ALIGN_CENTER_VERTICAL) self.Bind(EVT_FLOATSPIN, self.OnUpdate, self.border_ctrl) # Empty cell after border controls box.Add((0, 0)) # d_min control if self.params.masking.d_min is not None: self.d_min = self.params.masking.d_min else: self.d_min = 0 if self.d_min_ctrl is None: self.d_min_ctrl = FloatSpin( self, digits=2, name="d_min", value=self.d_min, min_val=0, increment=0.05, ) txtd = wx.StaticText(self, label="d_min") box.Add(txtd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) box.Add( self.d_min_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5, ) self.Bind(EVT_FLOATSPIN, self.OnUpdate, self.d_min_ctrl) # d_max control if self.params.masking.d_max is not None: self.d_max = self.params.masking.d_max else: self.d_max = 0 if self.d_max_ctrl is None: self.d_max_ctrl = FloatSpin( self, digits=2, name="d_max", value=self.d_max, min_val=0, increment=0.05, ) txtd = wx.StaticText(self, label="d_max") box.Add(txtd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) box.Add( self.d_max_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5, ) self.Bind(EVT_FLOATSPIN, self.OnUpdate, self.d_max_ctrl) sizer.Add(box) # resolution rings control grid = wx.FlexGridSizer( cols=2, rows=len(self.params.masking.resolution_range) + 2, vgap=0, hgap=0) sizer.Add(grid) text = wx.StaticText(self, -1, "Resolution range:") grid.Add(text) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) for range_id, (d_min, d_max) in enumerate( self.params.masking.resolution_range): grid.Add(wx.StaticText(self, -1, "%.2f-%.2f" % (d_min, d_max))) btn = metallicbutton.MetallicButton( parent=self, label="delete", bmp=wxtbx.bitmaps.fetch_icon_bitmap("actions", "cancel", 16), ) grid.Add(btn) self.Bind( wx.EVT_BUTTON, lambda evt, range_id=range_id: self.OnDeleteResolutionRange( evt, range_id=range_id), source=btn, ) self.resolution_range_d_min_ctrl = FloatCtrl( self, value=self._resolution_range_d_min, name="resolution_range_d_min") self.resolution_range_d_min_ctrl.SetMin(0) grid.Add( self.resolution_range_d_min_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5, ) self.resolution_range_d_max_ctrl = FloatCtrl( self, value=self._resolution_range_d_max, name="resolution_range_d_max") self.resolution_range_d_max_ctrl.SetMin(0) grid.Add( self.resolution_range_d_max_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5, ) # empty cell # grid.Add(wx.StaticText(self, -1, ''), 0, wx.EXPAND) self.Bind(EVT_PHIL_CONTROL, self.OnUpdate, self.resolution_range_d_min_ctrl) self.Bind(EVT_PHIL_CONTROL, self.OnUpdate, self.resolution_range_d_max_ctrl) # ice rings control box = wx.BoxSizer(wx.HORIZONTAL) self.ice_rings_ctrl = wx.CheckBox(self, -1, "Ice rings") self.ice_rings_ctrl.SetValue(self.params.masking.ice_rings.filter) box.Add(self.ice_rings_ctrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_CHECKBOX, self.OnUpdate, self.ice_rings_ctrl) # ice rings d_min control if self.params.masking.ice_rings.d_min is not None: self.ice_rings_d_min = self.params.masking.ice_rings.d_min else: self.ice_rings_d_min = 0 if self.ice_rings_d_min_ctrl is None: self.ice_rings_d_min_ctrl = FloatSpin( self, digits=2, name="ice_rings_d_min", value=self.ice_rings_d_min, min_val=0, increment=0.05, ) txtd = wx.StaticText(self, label="d_min") box.Add(txtd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) box.Add( self.ice_rings_d_min_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5, ) self.Bind(EVT_FLOATSPIN, self.OnUpdate, self.ice_rings_d_min_ctrl) # ice rings width control self.ice_rings_width = self.params.masking.ice_rings.width if self.ice_rings_width_ctrl is None: self.ice_rings_width_ctrl = FloatSpin( self, digits=3, name="ice_rings_width", value=self.ice_rings_width, min_val=0.001, increment=0.001, ) txtd = wx.StaticText(self, label="width") box.Add(txtd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) box.Add( self.ice_rings_width_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5, ) self.Bind(EVT_FLOATSPIN, self.OnUpdate, self.ice_rings_width_ctrl) sizer.Add(box) untrusted_rectangles = [] untrusted_polygons = [] untrusted_circles = [] # map index in self.params.masking.untrusted to index in above arrays self._rectangle_to_untrusted_id = [] self._polygon_to_untrusted_id = [] self._circle_to_untrusted_id = [] for i, untrusted in enumerate(self.params.masking.untrusted): if untrusted.rectangle is not None: untrusted_rectangles.append( (untrusted.panel, untrusted.rectangle)) self._rectangle_to_untrusted_id.append(i) elif untrusted.polygon is not None: untrusted_polygons.append((untrusted.panel, untrusted.polygon)) self._polygon_to_untrusted_id.append(i) elif untrusted.circle is not None: untrusted_circles.append((untrusted.panel, untrusted.circle)) self._circle_to_untrusted_id.append(i) # untrusted rectangles grid = wx.FlexGridSizer(cols=3, rows=len(untrusted_rectangles) + 2, vgap=0, hgap=0) sizer.Add(grid) text = wx.StaticText(self, -1, "Panel:") text.GetFont().SetWeight(wx.BOLD) grid.Add(text) text = wx.StaticText(self, -1, "Rectangle (x0, x1, y0, y1):") text.GetFont().SetWeight(wx.BOLD) grid.Add(text) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) for rect_id, (panel, rectangle) in enumerate(untrusted_rectangles): grid.Add(wx.StaticText(self, -1, "%i" % (panel))) grid.Add(wx.StaticText(self, -1, "%i %i %i %i" % tuple(rectangle))) btn = metallicbutton.MetallicButton( parent=self, label="delete", bmp=wxtbx.bitmaps.fetch_icon_bitmap("actions", "cancel", 16), ) grid.Add(btn) untrusted_id = self._rectangle_to_untrusted_id[rect_id] self.Bind( wx.EVT_BUTTON, lambda evt, untrusted_id=untrusted_id: self. OnDeleteUntrustedRegion(evt, untrusted_id=untrusted_id), source=btn, ) self.untrusted_rectangle_panel_ctrl = IntCtrl( self, value=0, name="untrusted_rectangle_panel") grid.Add(self.untrusted_rectangle_panel_ctrl, 0, wx.ALL, 5) self.untrusted_rectangle_ctrl = StrCtrl(self, value="", name="untrusted_rectangle") grid.Add(self.untrusted_rectangle_ctrl, 0, wx.ALL, 5) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) self.Bind(EVT_PHIL_CONTROL, self.OnUpdate, self.untrusted_rectangle_ctrl) # untrusted polygons grid = wx.FlexGridSizer(cols=3, rows=len(untrusted_polygons) + 2, vgap=0, hgap=0) sizer.Add(grid) text = wx.StaticText(self, -1, "Panel:") text.GetFont().SetWeight(wx.BOLD) grid.Add(text) text = wx.StaticText(self, -1, "Polygons (x1, y1, ..., xn, yn):") text.GetFont().SetWeight(wx.BOLD) grid.Add(text) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) for polygon_id, (panel, polygon) in enumerate(untrusted_polygons): grid.Add(StrCtrl(self, value="%i" % (panel), style=wx.TE_READONLY), 0, wx.ALL, 5) grid.Add( StrCtrl( self, value=" ".join(["%i"] * len(polygon)) % tuple(polygon), style=wx.TE_READONLY, ), 0, wx.ALL, 5, ) btn = metallicbutton.MetallicButton( parent=self, label="delete", bmp=wxtbx.bitmaps.fetch_icon_bitmap("actions", "cancel", 16), ) grid.Add(btn) untrusted_id = self._polygon_to_untrusted_id[polygon_id] self.Bind( wx.EVT_BUTTON, lambda evt, untrusted_id=untrusted_id: self. OnDeleteUntrustedRegion(evt, untrusted_id=untrusted_id), source=btn, ) self.untrusted_polygon_panel_ctrl = IntCtrl( self, value=0, name="untrusted_polygon_panel") grid.Add(self.untrusted_polygon_panel_ctrl, 0, wx.ALL, 5) self.untrusted_polygon_ctrl = StrCtrl(self, value="", name="untrusted_polygon") grid.Add(self.untrusted_polygon_ctrl, 0, wx.ALL, 5) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) self.Bind(EVT_PHIL_CONTROL, self.OnUpdate, self.untrusted_polygon_ctrl) # untrusted circles grid = wx.FlexGridSizer(cols=3, rows=len(untrusted_circles) + 2, vgap=0, hgap=0) sizer.Add(grid) text = wx.StaticText(self, -1, "Panel:") text.GetFont().SetWeight(wx.BOLD) grid.Add(text) text = wx.StaticText(self, -1, "Circle (x, y, r):") text.GetFont().SetWeight(wx.BOLD) grid.Add(text) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) for circle_id, (panel, circle) in enumerate(untrusted_circles): grid.Add(wx.StaticText(self, -1, "%i" % (panel))) grid.Add(wx.StaticText(self, -1, "%i %i %i" % tuple(circle))) btn = metallicbutton.MetallicButton( parent=self, label="delete", bmp=wxtbx.bitmaps.fetch_icon_bitmap("actions", "cancel", 16), ) grid.Add(btn) untrusted_id = self._circle_to_untrusted_id[circle_id] self.Bind( wx.EVT_BUTTON, lambda evt, untrusted_id=untrusted_id: self. OnDeleteUntrustedRegion(evt, untrusted_id=untrusted_id), source=btn, ) self.untrusted_circle_panel_ctrl = IntCtrl( self, value=0, name="untrusted_circle_panel") grid.Add(self.untrusted_circle_panel_ctrl, 0, wx.ALL, 5) self.untrusted_circle_ctrl = StrCtrl(self, value="", name="untrusted_circle") grid.Add(self.untrusted_circle_ctrl, 0, wx.ALL, 5) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) self.Bind(EVT_PHIL_CONTROL, self.OnUpdate, self.untrusted_circle_ctrl) # Draw rectangle/circle mode buttons grid = wx.FlexGridSizer(cols=4, rows=1, vgap=0, hgap=0) sizer.Add(grid) grid.Add(wx.StaticText(self, label="Mode:")) self.mode_rectangle_button = wx.ToggleButton(self, -1, "Rectangle") self.mode_rectangle_button.SetValue(self._mode_rectangle) grid.Add(self.mode_rectangle_button, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_TOGGLEBUTTON, self.OnUpdate, self.mode_rectangle_button) self.mode_circle_button = wx.ToggleButton(self, -1, "Circle") self.mode_circle_button.SetValue(self._mode_circle) grid.Add(self.mode_circle_button, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_TOGGLEBUTTON, self.OnUpdate, self.mode_circle_button) self.mode_polygon_button = wx.ToggleButton(self, -1, "Polygon") self.mode_polygon_button.SetValue(self._mode_polygon) grid.Add(self.mode_polygon_button, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_TOGGLEBUTTON, self.OnUpdate, self.mode_polygon_button) # show/save mask controls grid = wx.FlexGridSizer(cols=3, rows=2, vgap=0, hgap=0) sizer.Add(grid) self.show_mask_ctrl = wx.CheckBox(self, -1, "Show mask") self.show_mask_ctrl.SetValue(self.params.show_mask) grid.Add(self.show_mask_ctrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_CHECKBOX, self.OnUpdate, self.show_mask_ctrl) self.save_mask_button = wx.Button(self, -1, "Save mask") grid.Add(self.save_mask_button, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_BUTTON, self.OnSaveMask, self.save_mask_button) self.save_mask_txt_ctrl = StrCtrl(self, value=self.params.output.mask, name="mask_pickle") grid.Add(self.save_mask_txt_ctrl, 0, wx.ALL, 5) self.Bind(EVT_PHIL_CONTROL, self.OnUpdate, self.save_mask_txt_ctrl) # empty cell grid.Add(wx.StaticText(self, -1, ""), 0, wx.EXPAND) self.save_params_button = wx.Button(self, -1, "Save") grid.Add(self.save_params_button, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_BUTTON, self.OnSaveMaskParams, self.save_params_button) self.save_params_txt_ctrl = StrCtrl( self, value=self.params.output.mask_params, name="mask_phil") grid.Add(self.save_params_txt_ctrl, 0, wx.ALL, 5) self.Bind(EVT_PHIL_CONTROL, self.OnUpdate, self.save_params_txt_ctrl) sizer.Layout() sizer.Fit(self) def OnDeleteUntrustedRegion(self, event, untrusted_id): if untrusted_id is not None: del self.params.masking.untrusted[untrusted_id] self.OnUpdate(event) def OnDeleteResolutionRange(self, event, range_id): if range_id is not None: del self.params.masking.resolution_range[range_id] self.OnUpdate(event) def OnUpdate(self, event): image_viewer_frame = self.GetParent().GetParent() self.params.show_mask = self.show_mask_ctrl.GetValue() # untidy image_viewer_frame.settings.show_mask = self.params.show_mask image_viewer_frame.params.show_mask = self.params.show_mask image_viewer_frame.settings_frame.panel.show_mask.SetValue( self.params.show_mask) self.params.output.mask = self.save_mask_txt_ctrl.GetValue() self.params.output.mask_params = self.save_params_txt_ctrl.GetValue() if self._mode_polygon and (not self.mode_polygon_button.GetValue() or self.mode_circle_button.GetValue() or self.mode_rectangle_button.GetValue()): self.AddUntrustedPolygon(self._mode_polygon_points) self._mode_polygon_points = [] self._pyslip.DeleteLayer(self._mode_polygon_layer) self._mode_polygon_layer = None if self.mode_rectangle_button.GetValue(): if not self._mode_rectangle: # mode wasn't set but button has been pressed, so set mode self._mode_rectangle = True # set other modes and buttons to False self._mode_circle = False self.mode_circle_button.SetValue(False) self._mode_polygon = False self.mode_polygon_button.SetValue(False) if self.mode_circle_button.GetValue(): if not self._mode_circle: # mode wasn't set but button has been pressed, so set mode self._mode_circle = True # set other modes and buttons to False self._mode_rectangle = False self.mode_rectangle_button.SetValue(False) self._mode_polygon = False self.mode_polygon_button.SetValue(False) if self.mode_polygon_button.GetValue(): if not self._mode_polygon: # mode wasn't set but button has been pressed, so set mode self._mode_polygon = True # set other modes and buttons to False self._mode_rectangle = False self.mode_rectangle_button.SetValue(False) self._mode_circle = False self.mode_circle_button.SetValue(False) if not (self.mode_circle_button.GetValue() or self.mode_rectangle_button.GetValue() or self.mode_polygon_button.GetValue()): self._mode_circle = False self._mode_rectangle = False self._mode_polygon = False if self.d_min_ctrl.GetValue() > 0: self.params.masking.d_min = self.d_min_ctrl.GetValue() else: self.params.masking.d_min = None if self.d_max_ctrl.GetValue() > 0: self.params.masking.d_max = self.d_max_ctrl.GetValue() else: self.params.masking.d_max = None self.params.masking.border = int(self.border_ctrl.GetValue()) if self.ice_rings_d_min_ctrl.GetValue() > 0: self.params.masking.ice_rings.d_min = self.ice_rings_d_min_ctrl.GetValue( ) else: self.params.masking.ice_rings.d_min = None if self.ice_rings_width_ctrl.GetValue() > 0: self.params.masking.ice_rings.width = self.ice_rings_width_ctrl.GetValue( ) self.params.masking.ice_rings.filter = self.ice_rings_ctrl.GetValue() self._resolution_range_d_min = float( self.resolution_range_d_min_ctrl.GetValue()) self._resolution_range_d_max = float( self.resolution_range_d_max_ctrl.GetValue()) if self._resolution_range_d_min > 0 and self._resolution_range_d_max > 0: self.params.masking.resolution_range.append( (self._resolution_range_d_min, self._resolution_range_d_max)) self._resolution_range_d_min = 0 self._resolution_range_d_max = 0 from dials.util import masking untrusted_rectangle = self.untrusted_rectangle_ctrl.GetValue().strip() if len(untrusted_rectangle.strip()) > 0: rectangle = untrusted_rectangle.strip().replace(",", " ").split(" ") try: rectangle = [int(s) for s in rectangle] assert len(rectangle) == 4 panel = int(self.untrusted_rectangle_panel_ctrl.GetValue()) except Exception: pass else: untrusted = masking.phil_scope.extract().untrusted[0] untrusted.panel = panel untrusted.rectangle = rectangle self.params.masking.untrusted.append(untrusted) untrusted_polygon = self.untrusted_polygon_ctrl.GetValue().strip() if len(untrusted_polygon.strip()) > 0: polygon = untrusted_polygon.strip().replace(",", " ").split(" ") try: polygon = [int(s) for s in polygon] assert len(polygon) % 2 == 0 assert len(polygon) // 2 > 3 panel = int(self.untrusted_polygon_panel_ctrl.GetValue()) except Exception: pass else: untrusted = masking.phil_scope.extract().untrusted[0] untrusted.panel = panel untrusted.polygon = polygon self.params.masking.untrusted.append(untrusted) untrusted_circle = self.untrusted_circle_ctrl.GetValue().strip() if len(untrusted_circle.strip()) > 0: circle = untrusted_circle.strip().replace(",", " ").split(" ") try: circle = [int(s) for s in circle] assert len(circle) == 3 panel = int(self.untrusted_circle_panel_ctrl.GetValue()) except Exception: pass else: untrusted = masking.phil_scope.extract().untrusted[0] untrusted.panel = panel untrusted.circle = circle self.params.masking.untrusted.append(untrusted) # Refresh the UI *after* the event is finished wx.CallAfter(self.draw_settings) self.UpdateMask() # Force re-drawing of mask image_viewer_frame.OnChooseImage(event) def OnSaveMask(self, event): self.UpdateMask() image_viewer_frame = self.GetParent().GetParent() m1 = image_viewer_frame.mask_input m2 = image_viewer_frame.mask_image_viewer if m1 is not None and m2 is not None: mask = [] for p1, p2 in zip(m1, m2): mask.append(p2 & p1) elif m1 is not None: mask = m1 elif m2 is not None: mask = m2 else: return # Save the mask to file from libtbx import easy_pickle print("Writing mask to %s" % self.params.output.mask) easy_pickle.dump(self.params.output.mask, mask) def OnSaveMaskParams(self, event): from dials.util.masking import phil_scope file_name = self.params.output.mask_params with open(file_name, "wb") as f: print("Saving parameters to %s" % file_name) phil_scope.fetch_diff(phil_scope.format( self.params.masking)).show(f) def UpdateMask(self): image_viewer_frame = self.GetParent().GetParent() # Generate the mask from dials.util.masking import MaskGenerator generator = MaskGenerator(self.params.masking) imageset = image_viewer_frame.imagesets[0] # XXX mask = generator.generate(imageset) image_viewer_frame.mask_image_viewer = mask image_viewer_frame.update_settings(layout=False) def OnLeftDown(self, event): if not event.ShiftDown(): click_posn = event.GetPositionTuple( ) if WX3 else event.GetPosition() if self._mode_rectangle: self._rectangle_x0y0 = click_posn self._rectangle_x1y1 = None return elif self._mode_circle: self._circle_xy = click_posn self._circle_radius = None return elif self._mode_polygon: self._mode_polygon_points.append(click_posn) self.DrawPolygon(self._mode_polygon_points) event.Skip() def OnLeftUp(self, event): if not event.ShiftDown(): click_posn = event.GetPositionTuple( ) if WX3 else event.GetPosition() if self._mode_rectangle and self._rectangle_x0y0 is not None: self._rectangle_x1y1 = click_posn x0, y0 = self._rectangle_x0y0 x1, y1 = self._rectangle_x1y1 self.AddUntrustedRectangle(x0, y0, x1, y1) self._pyslip.DeleteLayer(self._mode_rectangle_layer) self._mode_rectangle_layer = None self.mode_rectangle_button.SetValue(False) self.OnUpdate(event) return elif self._mode_circle and self._circle_xy is not None: xc, yc = self._circle_xy xedge, yedge = click_posn self.DrawCircle(xc, yc, xedge, yedge) try: self.AddUntrustedCircle(xc, yc, xedge, yedge) except Exception as e: print(e) finally: self._pyslip.DeleteLayer(self._mode_circle_layer) self._mode_circle_layer = None self.mode_circle_button.SetValue(False) self.OnUpdate(event) return event.Skip() def OnMove(self, event): if event.Dragging() and event.LeftIsDown() and not event.ShiftDown(): if self._mode_rectangle: if self._rectangle_x0y0 is not None: x0, y0 = self._rectangle_x0y0 x1, y1 = event.GetPositionTuple( ) if WX3 else event.GetPosition() self.DrawRectangle(x0, y0, x1, y1) return elif self._mode_circle: if self._circle_xy is not None: xc, yc = self._circle_xy xedge, yedge = (event.GetPositionTuple() if WX3 else event.GetPosition()) self.DrawCircle(xc, yc, xedge, yedge) return event.Skip() def DrawRectangle(self, x0, y0, x1, y1): if self._mode_rectangle_layer: self._pyslip.DeleteLayer(self._mode_rectangle_layer) self._mode_rectangle_layer = None polygon = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] d = {} polygon_data = [] points = [self._pyslip.ConvertView2Geo(p) for p in polygon] for i in range(len(points) - 1): polygon_data.append(((points[i], points[i + 1]), d)) self._mode_rectangle_layer = self._pyslip.AddPolygonLayer( polygon_data, map_rel=True, color="#00ffff", radius=5, visible=True, name="<mode_rectangle_layer>", ) def DrawCircle(self, xc, yc, xedge, yedge): if self._mode_circle_layer: self._pyslip.DeleteLayer(self._mode_circle_layer) self._mode_circle_layer = None xc, yc = self._pyslip.ConvertView2Geo((xc, yc)) xedge, yedge = self._pyslip.ConvertView2Geo((xedge, yedge)) from scitbx import matrix center = matrix.col((xc, yc)) edge = matrix.col((xedge, yedge)) r = (center - edge).length() if r == 0: return e1 = matrix.col((1, 0)) e2 = matrix.col((0, 1)) circle_data = ( center + r * (e1 + e2), center + r * (e1 - e2), center + r * (-e1 - e2), center + r * (-e1 + e2), center + r * (e1 + e2), ) self._mode_circle_layer = self._pyslip.AddEllipseLayer( circle_data, map_rel=True, color="#00ffff", radius=5, visible=True, # show_levels=[3,4], name="<mode_circle_layer>", ) def DrawPolygon(self, vertices): if self._mode_polygon_layer: self._pyslip.DeleteLayer(self._mode_polygon_layer) self._mode_polygon_layer = None polygon_data = [] d = {} for i in range(len(vertices) - 1): polygon_data.append(( ( self._pyslip.ConvertView2Geo(vertices[i]), self._pyslip.ConvertView2Geo(vertices[i + 1]), ), d, )) if polygon_data: self._mode_polygon_layer = self._pyslip.AddPolygonLayer( polygon_data, map_rel=True, color="#00ffff", radius=5, visible=True, name="<boxsel_pt_layer>", ) def AddUntrustedPolygon(self, vertices): if len(vertices) < 4: return vertices.append(vertices[0]) vertices = [self._pyslip.ConvertView2Geo(v) for v in vertices] vertices = [ self._pyslip.tiles.map_relative_to_picture_fast_slow(*v) for v in vertices ] detector = self._pyslip.tiles.raw_image.get_detector() if len(detector) > 1: point_ = [] panel_id = None for p in vertices: p1, p0, p_id = self._pyslip.tiles.flex_image.picture_to_readout( p[1], p[0]) assert p_id >= 0, "Point must be within a panel" if panel_id is not None: assert ( panel_id == p_id ), "All points must be contained within a single panel" panel_id = p_id point_.append((p0, p1)) vertices = point_ else: panel_id = 0 from dials.util import masking from libtbx.utils import flat_list region = masking.phil_scope.extract().untrusted[0] points = flat_list(vertices) region.polygon = [int(p) for p in points] region.panel = panel_id self.params.masking.untrusted.append(region) def AddUntrustedRectangle(self, x0, y0, x1, y1): x0, y0 = self._pyslip.ConvertView2Geo((x0, y0)) x1, y1 = self._pyslip.ConvertView2Geo((x1, y1)) if x0 == x1 or y0 == y1: return points = [(x0, y0), (x1, y1)] points = [ self._pyslip.tiles.map_relative_to_picture_fast_slow(*p) for p in points ] detector = self._pyslip.tiles.raw_image.get_detector() if len(detector) > 1: point_ = [] panel_id = None for p in points: p1, p0, p_id = self._pyslip.tiles.flex_image.picture_to_readout( p[1], p[0]) assert p_id >= 0, "Point must be within a panel" if panel_id is not None: assert ( panel_id == p_id ), "All points must be contained within a single panel" panel_id = int(p_id) point_.append((p0, p1)) points = point_ else: panel_id = 0 (x0, y0), (x1, y1) = points if x0 > x1: x1, x0 = x0, x1 if y0 > y1: y1, y0 = y0, y1 panel = detector[panel_id] if (x1 < 0 or y1 < 0 or x0 > panel.get_image_size()[0] or y0 > panel.get_image_size()[1]): return x0 = max(0, x0) y0 = max(0, y0) x1 = min(panel.get_image_size()[0], x1) y1 = min(panel.get_image_size()[1], y1) from dials.util import masking region = masking.phil_scope.extract().untrusted[0] region.rectangle = [int(x0), int(x1), int(y0), int(y1)] region.panel = panel_id self.params.masking.untrusted.append(region) def AddUntrustedCircle(self, xc, yc, xedge, yedge): points = [(xc, yc), (xedge, yedge)] points = [self._pyslip.ConvertView2Geo(p) for p in points] points = [ self._pyslip.tiles.map_relative_to_picture_fast_slow(*p) for p in points ] detector = self._pyslip.tiles.raw_image.get_detector() if len(detector) > 1: points_ = [] panel_id = None for p in points: p1, p0, p_id = self._pyslip.tiles.flex_image.picture_to_readout( p[1], p[0]) assert p_id >= 0, "Point must be within a panel" if panel_id is not None: assert ( panel_id == p_id ), "All points must be contained within a single panel" panel_id = p_id points_.append((p0, p1)) points = points_ else: panel_id = 0 (xc, yc), (xedge, yedge) = points from scitbx import matrix center = matrix.col((xc, yc)) edge = matrix.col((xedge, yedge)) r = (center - edge).length() if r == 0: return from dials.util import masking region = masking.phil_scope.extract().untrusted[0] region.circle = [int(xc), int(yc), int(r)] region.panel = panel_id self.params.masking.untrusted.append(region)
class PlotConfigFrame(wx.Frame): """ GUI Configure Frame""" def __init__(self, parent=None, config=None, trace_color_callback=None): if config is None: config = PlotConfig() self.conf = config if callable(trace_color_callback): self.conf.trace_color_callback = trace_color_callback self.parent = parent self.canvas = self.conf.canvas self.axes = self.canvas.figure.get_axes() self.conf.relabel() self.show_legend_cbs = [] self.DrawPanel() def DrawPanel(self): style = wx.DEFAULT_FRAME_STYLE ## |wx.TAB_TRAVERSAL wx.Frame.__init__(self, self.parent, -1, 'Configure Plot', style=style) bgcol = hex2rgb(self.conf.color_themes['light']['bg']) panel = wx.Panel(self, -1) panel.SetBackgroundColour(bgcol) font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False) panel.SetFont(font) self.nb = flat_nb.FlatNotebook(panel, wx.ID_ANY, agwStyle=FNB_STYLE) self.nb.SetActiveTabColour((253, 253, 230)) self.nb.SetTabAreaColour((bgcol[0] - 8, bgcol[1] - 8, bgcol[2] - 8)) self.nb.SetNonActiveTabTextColour((10, 10, 100)) self.nb.SetActiveTabTextColour((100, 10, 10)) self.nb.AddPage(self.make_linetrace_panel(parent=self.nb, font=font), 'Colors and Line Properties', True) self.nb.AddPage(self.make_range_panel(parent=self.nb, font=font), 'Ranges and Margins', True) self.nb.AddPage(self.make_text_panel(parent=self.nb, font=font), 'Text, Labels, Legends', True) self.nb.AddPage(self.make_scatter_panel(parent=self.nb, font=font), 'Scatterplot Settings', self.conf.plot_type == 'scatter') for i in range(self.nb.GetPageCount()): self.nb.GetPage(i).SetBackgroundColour(bgcol) self.nb.SetSelection(0) sizer = wx.BoxSizer(wx.VERTICAL) sty = wx.ALIGN_LEFT | wx.LEFT | wx.TOP | wx.BOTTOM | wx.EXPAND sizer.Add(self.nb, 1, wx.GROW | sty, 3) autopack(panel, sizer) self.SetMinSize((775, 200)) self.SetSize((950, 400)) self.Show() self.Raise() def make_range_panel(self, parent, font=None): # bounds, margins, scales panel = wx.Panel(parent) if font is None: font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False) conf = self.conf sizer = wx.GridBagSizer(4, 4) labstyle = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL mtitle = wx.StaticText(panel, -1, 'Linear/Log Scale: ') logchoice = wx.Choice(panel, choices=self.conf.log_choices, size=(200, -1)) logchoice.SetStringSelection("x %s / y %s" % (self.conf.xscale, self.conf.yscale)) logchoice.Bind(wx.EVT_CHOICE, self.onLogScale) sizer.Add(mtitle, (1, 0), (1, 1), labstyle, 2) sizer.Add(logchoice, (1, 1), (1, 3), labstyle, 2) # Bounds axes = self.canvas.figure.get_axes() laxes = axes[0] raxes = None if len(axes) > 1: raxes = axes[1] user_lims = self.conf.user_limits[laxes] auto_b = wx.CheckBox(panel, -1, ' From Data ', (-1, -1), (-1, -1)) auto_b.Bind(wx.EVT_CHECKBOX, self.onAutoBounds) auto_b.SetValue(self.conf.user_limits[laxes] == 4 * [None]) xb0, xb1 = laxes.get_xlim() yb0, yb1 = laxes.get_ylim() if user_lims[0] is not None: xb0 = user_lims[0] if user_lims[1] is not None: xb1 = user_lims[1] if user_lims[2] is not None: yb0 = user_lims[2] if user_lims[3] is not None: yb1 = user_lims[3] y2b0, y2b1 = [None, None] if raxes is not None: y2b0, y2b1 = raxes.get_ylim() user_lims = self.conf.user_limits[raxes] if user_lims[2] is not None: y2b0 = user_lims[2] if user_lims[3] is not None: y2b1 = user_lims[3] opts = dict(size=100, labeltext='', action=self.onBounds) self.xbounds = [ LabelEntry(panel, value=ffmt(xb0), **opts), LabelEntry(panel, value=ffmt(xb1), **opts) ] self.ybounds = [ LabelEntry(panel, value=ffmt(yb0), **opts), LabelEntry(panel, value=ffmt(yb1), **opts) ] self.y2bounds = [ LabelEntry(panel, value=ffmt(y2b0), **opts), LabelEntry(panel, value=ffmt(y2b1), **opts) ] self.vpad_val = FloatSpin(panel, -1, value=2.5, min_val=0, max_val=100, increment=0.5, digits=2, pos=(-1, -1), size=(FSPINSIZE, 30)) self.vpad_val.Bind(EVT_FLOATSPIN, self.onViewPadEvent) if user_lims == 4 * [None]: [w.Disable() for w in self.xbounds] [w.Disable() for w in self.ybounds] if raxes is None: [w.Disable() for w in self.y2bounds] btext = 'Plot Boundaries : ' ptext = ' Padding (% of Data Range): ' xtext = ' X axis:' ytext = ' Y axis:' y2text = ' Y2 axis:' def showtext(t): return wx.StaticText(panel, -1, t) sizer.Add(showtext(btext), (3, 0), (1, 1), labstyle, 2) sizer.Add(auto_b, (3, 1), (1, 1), labstyle, 2) sizer.Add(showtext(ptext), (3, 2), (1, 2), labstyle, 2) sizer.Add(self.vpad_val, (3, 4), (1, 1), labstyle, 2) sizer.Add(showtext(xtext), (4, 0), (1, 1), labstyle, 2) sizer.Add(self.xbounds[0], (4, 1), (1, 1), labstyle, 2) sizer.Add(showtext(' : '), (4, 2), (1, 1), labstyle, 2) sizer.Add(self.xbounds[1], (4, 3), (1, 1), labstyle, 2) sizer.Add(showtext(ytext), (5, 0), (1, 1), labstyle, 2) sizer.Add(self.ybounds[0], (5, 1), (1, 1), labstyle, 2) sizer.Add(showtext(' : '), (5, 2), (1, 1), labstyle, 2) sizer.Add(self.ybounds[1], (5, 3), (1, 1), labstyle, 2) sizer.Add(showtext(y2text), (6, 0), (1, 1), labstyle, 2) sizer.Add(self.y2bounds[0], (6, 1), (1, 1), labstyle, 2) sizer.Add(showtext(' : '), (6, 2), (1, 1), labstyle, 2) sizer.Add(self.y2bounds[1], (6, 3), (1, 1), labstyle, 2) # Margins _left, _top, _right, _bot = ["%.3f" % x for x in self.conf.margins] mtitle = wx.StaticText(panel, -1, 'Margins for labels: ') ltitle = wx.StaticText(panel, -1, ' Left: ') rtitle = wx.StaticText(panel, -1, ' Right: ') btitle = wx.StaticText(panel, -1, ' Bottom: ') ttitle = wx.StaticText(panel, -1, ' Top: ') opts = dict(min_val=0.0, max_val=None, increment=0.01, digits=3, pos=(-1, -1), size=(FSPINSIZE, 30)) lmarg = FloatSpin(panel, -1, value=_left, **opts) lmarg.Bind(EVT_FLOATSPIN, self.onMargins) rmarg = FloatSpin(panel, -1, value=_right, **opts) rmarg.Bind(EVT_FLOATSPIN, self.onMargins) bmarg = FloatSpin(panel, -1, value=_bot, **opts) bmarg.Bind(EVT_FLOATSPIN, self.onMargins) tmarg = FloatSpin(panel, -1, value=_top, **opts) tmarg.Bind(EVT_FLOATSPIN, self.onMargins) self.margins = [lmarg, tmarg, rmarg, bmarg] if self.conf.auto_margins: [m.Disable() for m in self.margins] auto_m = wx.CheckBox(panel, -1, ' Default ', (-1, -1), (-1, -1)) auto_m.Bind(wx.EVT_CHECKBOX, self.onAutoMargin) # ShowGrid) auto_m.SetValue(self.conf.auto_margins) msizer = wx.BoxSizer(wx.HORIZONTAL) msizer.AddMany( (ltitle, lmarg, rtitle, rmarg, btitle, bmarg, ttitle, tmarg)) sizer.Add(mtitle, (8, 0), (1, 1), labstyle, 2) sizer.Add(auto_m, (8, 1), (1, 1), labstyle, 2) sizer.Add(msizer, (9, 1), (1, 6), labstyle, 2) autopack(panel, sizer) return panel def make_scatter_panel(self, parent, font=None): # list of traces panel = wx.Panel(parent) if font is None: font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False) sizer = wx.GridBagSizer(4, 4) labstyle = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL slab = wx.StaticText(panel, -1, 'Symbol Size:', size=(-1, -1), style=labstyle) ssize = wx.SpinCtrl(panel, -1, "", (-1, -1), (ISPINSIZE, 30)) ssize.SetRange(1, 1000) ssize.SetValue(self.conf.scatter_size) ssize.Bind(wx.EVT_SPINCTRL, partial(self.onScatter, item='size')) sizer.Add(slab, (0, 0), (1, 1), labstyle, 5) sizer.Add(ssize, (0, 1), (1, 1), labstyle, 5) conf = self.conf nfcol = csel.ColourSelect(panel, -1, "", mpl_color(conf.scatter_normalcolor, default=(0, 0, 128)), size=(25, 25)) necol = csel.ColourSelect(panel, -1, "", mpl_color(conf.scatter_normaledge, default=(0, 0, 200)), size=(25, 25)) sfcol = csel.ColourSelect(panel, -1, "", mpl_color(conf.scatter_selectcolor, default=(128, 0, 0)), size=(25, 25)) secol = csel.ColourSelect(panel, -1, "", mpl_color(conf.scatter_selectedge, default=(200, 0, 0)), size=(25, 25)) nfcol.Bind(csel.EVT_COLOURSELECT, partial(self.onScatter, item='scatt_nf')) necol.Bind(csel.EVT_COLOURSELECT, partial(self.onScatter, item='scatt_ne')) sfcol.Bind(csel.EVT_COLOURSELECT, partial(self.onScatter, item='scatt_sf')) secol.Bind(csel.EVT_COLOURSELECT, partial(self.onScatter, item='scatt_se')) btnstyle = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.ALL sizer.Add( wx.StaticText(panel, -1, 'Colors: ', style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), (1, 0), (1, 1), labstyle, 2) sizer.Add( wx.StaticText(panel, -1, 'Normal Symbol:', style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), (1, 1), (1, 1), labstyle, 2) sizer.Add( wx.StaticText(panel, -1, 'Selected Symbol:', style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), (1, 2), (1, 1), labstyle, 2) sizer.Add( wx.StaticText(panel, -1, 'Face Color:', style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), (2, 0), (1, 1), labstyle, 2) sizer.Add( wx.StaticText(panel, -1, 'Edge Color:', style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), (3, 0), (1, 1), labstyle, 2) sizer.Add(nfcol, (2, 1), (1, 1), btnstyle, 2) sizer.Add(necol, (3, 1), (1, 1), btnstyle, 2) sizer.Add(sfcol, (2, 2), (1, 1), btnstyle, 2) sizer.Add(secol, (3, 2), (1, 1), btnstyle, 2) autopack(panel, sizer) return panel def make_text_panel(self, parent, font=None): panel = scrolled.ScrolledPanel(parent, size=(800, 200), style=wx.GROW | wx.TAB_TRAVERSAL, name='p1') if font is None: font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False) sizer = wx.GridBagSizer(2, 2) i = 0 irow = 0 bstyle = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ST_NO_AUTORESIZE labstyle = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL ax = self.axes[0] t0 = wx.StaticText(panel, -1, 'Text Size:', style=labstyle) t1 = wx.StaticText(panel, -1, 'Labels and Titles:', style=labstyle) t2 = wx.StaticText(panel, -1, 'Legends:', style=labstyle) t_size = wx.SpinCtrl(panel, -1, "", (-1, -1), (ISPINSIZE, 25)) t_size.SetRange(2, 20) t_size.SetValue(self.conf.labelfont.get_size()) t_size.Bind(wx.EVT_SPINCTRL, partial(self.onText, item='labelsize')) l_size = wx.SpinCtrl(panel, -1, " ", (-1, -1), (ISPINSIZE, 25)) l_size.SetRange(2, 20) l_size.SetValue(self.conf.legendfont.get_size()) l_size.Bind(wx.EVT_SPINCTRL, partial(self.onText, item='legendsize')) self.titl = LabelEntry(panel, self.conf.title.replace('\n', '\\n'), labeltext='Title: ', size=400, action=partial(self.onText, item='title')) self.ylab = LabelEntry(panel, self.conf.ylabel.replace('\n', '\\n'), labeltext='Y Label: ', size=400, action=partial(self.onText, item='ylabel')) self.y2lab = LabelEntry(panel, self.conf.y2label.replace('\n', '\\n'), labeltext='Y2 Label: ', size=400, action=partial(self.onText, item='y2label')) self.xlab = LabelEntry(panel, self.conf.xlabel.replace('\n', '\\n'), labeltext='X Label: ', size=400, action=partial(self.onText, item='xlabel')) sizer.Add(self.titl.label, (0, 0), (1, 1), labstyle) sizer.Add(self.titl, (0, 1), (1, 4), labstyle) sizer.Add(self.ylab.label, (1, 0), (1, 1), labstyle) sizer.Add(self.ylab, (1, 1), (1, 4), labstyle) sizer.Add(self.y2lab.label, (2, 0), (1, 1), labstyle) sizer.Add(self.y2lab, (2, 1), (1, 4), labstyle) sizer.Add(self.xlab.label, (3, 0), (1, 1), labstyle) sizer.Add(self.xlab, (3, 1), (1, 4), labstyle) sizer.Add(t0, (4, 0), (1, 1), labstyle) sizer.Add(t1, (4, 1), (1, 1), labstyle) sizer.Add(t_size, (4, 2), (1, 1), labstyle) sizer.Add(t2, (4, 3), (1, 1), labstyle) sizer.Add(l_size, (4, 4), (1, 1), labstyle) # Legend bstyle = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ST_NO_AUTORESIZE labstyle = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL ax = self.axes[0] leg_ttl = wx.StaticText(panel, -1, 'Legend:', size=(-1, -1), style=labstyle) loc_ttl = wx.StaticText(panel, -1, 'Location:', size=(-1, -1), style=labstyle) leg_loc = wx.Choice(panel, -1, choices=self.conf.legend_locs, size=(150, -1)) leg_loc.Bind(wx.EVT_CHOICE, partial(self.onShowLegend, item='loc')) leg_loc.SetStringSelection(self.conf.legend_loc) leg_onax = wx.Choice(panel, -1, choices=self.conf.legend_onaxis_choices, size=(120, -1)) leg_onax.Bind(wx.EVT_CHOICE, partial(self.onShowLegend, item='onaxis')) leg_onax.SetStringSelection(self.conf.legend_onaxis) togg_leg = wx.CheckBox(panel, -1, 'Click Legend to Show/Hide Line', (-1, -1), (-1, -1)) togg_leg.Bind(wx.EVT_CHECKBOX, self.onHideWithLegend) togg_leg.SetValue(self.conf.hidewith_legend) show_leg = wx.CheckBox(panel, -1, 'Show Legend', (-1, -1), (-1, -1)) show_leg.Bind(wx.EVT_CHECKBOX, partial(self.onShowLegend, item='legend')) show_leg.SetValue(self.conf.show_legend) if show_leg not in self.show_legend_cbs: self.show_legend_cbs.append(show_leg) show_lfr = wx.CheckBox(panel, -1, 'Show Legend Frame', (-1, -1), (-1, -1)) show_lfr.Bind(wx.EVT_CHECKBOX, partial(self.onShowLegend, item='frame')) show_lfr.SetValue(self.conf.show_legend_frame) lsizer = wx.BoxSizer(wx.HORIZONTAL) lsizer.AddMany((leg_ttl, show_leg, show_lfr, togg_leg)) sizer.Add(lsizer, (6, 0), (1, 8), labstyle, 2) lsizer = wx.BoxSizer(wx.HORIZONTAL) lsizer.AddMany((loc_ttl, leg_loc, leg_onax)) sizer.Add(lsizer, (7, 1), (1, 4), labstyle, 2) autopack(panel, sizer) return panel def make_linetrace_panel(self, parent, font=None): """colours and line properties""" panel = scrolled.ScrolledPanel(parent, size=(900, 250), style=wx.GROW | wx.TAB_TRAVERSAL, name='p1') if font is None: font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL, False) sizer = wx.GridBagSizer(2, 2) i = 0 ax = self.axes[0] if matplotlib.__version__ < '2.0': axis_bgcol = ax.get_axis_bgcolor() else: axis_bgcol = ax.get_facecolor() labstyle = wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL opts = dict(size=(40, 30), style=labstyle) ctitle = wx.StaticText(panel, -1, ' Colors: ') ltheme = wx.StaticText(panel, -1, ' Color Theme: ') themes = list(self.conf.color_themes.keys()) coltheme = wx.Choice(panel, choices=themes) coltheme.SetStringSelection(self.conf.color_theme) coltheme.Bind(wx.EVT_CHOICE, self.onColorThemeStyle) textcol = csel.ColourSelect(panel, label=" Text ", colour=mpl_color(self.conf.textcolor), size=(50, 30), style=labstyle) gridcol = csel.ColourSelect(panel, label=" Grid ", colour=mpl_color(self.conf.gridcolor), size=(50, 30), style=labstyle) bgcol = csel.ColourSelect(panel, label=" Background ", colour=mpl_color(axis_bgcol), size=(120, 30), style=labstyle) fbgcol = csel.ColourSelect(panel, label=" Outer Frame ", colour=mpl_color( self.canvas.figure.get_facecolor()), size=(120, 30), style=labstyle) self.colwids = { 'text': textcol, 'bg': bgcol, 'grid': gridcol, 'frame': fbgcol } bgcol.Bind(csel.EVT_COLOURSELECT, partial(self.onColor, item='bg')) fbgcol.Bind(csel.EVT_COLOURSELECT, partial(self.onColor, item='frame')) gridcol.Bind(csel.EVT_COLOURSELECT, partial(self.onColor, item='grid')) textcol.Bind(csel.EVT_COLOURSELECT, partial(self.onColor, item='text')) show_grid = wx.CheckBox(panel, -1, ' Show Grid ', (-1, -1), (-1, -1)) show_grid.Bind(wx.EVT_CHECKBOX, self.onShowGrid) show_grid.SetValue(self.conf.show_grid) show_box = wx.CheckBox(panel, -1, ' Show Top/Right Axes ', (-1, -1), (-1, -1)) show_box.Bind(wx.EVT_CHECKBOX, self.onShowBox) show_box.SetValue(self.conf.axes_style == 'box') show_leg = wx.CheckBox(panel, -1, 'Show Legend', (-1, -1), (-1, -1)) show_leg.Bind(wx.EVT_CHECKBOX, partial(self.onShowLegend, item='legend')) show_leg.SetValue(self.conf.show_legend) if show_leg not in self.show_legend_cbs: self.show_legend_cbs.append(show_leg) reset_btn = wx.Button(panel, label='Reset Line Colors', size=(175, -1)) reset_btn.Bind(wx.EVT_BUTTON, self.onResetLines) csizer = wx.BoxSizer(wx.HORIZONTAL) csizer.Add(ctitle, 0, labstyle, 3) csizer.Add(textcol, 0, labstyle, 3) csizer.Add(gridcol, 0, labstyle, 3) csizer.Add(bgcol, 0, labstyle, 3) csizer.Add(fbgcol, 0, labstyle, 3) csizer.Add(ltheme, 1, labstyle, 3) csizer.Add(coltheme, 1, labstyle, 3) csizer.Add(reset_btn, 0, labstyle, 3) sizer.Add(csizer, (1, 0), (1, 9), labstyle, 2) # csizer.Add(show_grid, 0, labstyle, 3) # csizer.Add(show_box, 0, labstyle, 3) sizer.Add(show_grid, (2, 1), (1, 1)) sizer.Add(show_box, (2, 2), (1, 3)) sizer.Add(show_leg, (2, 5), (1, 2)) irow = 3 for t in ('#', 'Label', 'Color', 'Style', 'Thickness', 'Symbol', ' Size', 'Z Order', 'Join Style'): x = wx.StaticText(panel, -1, t) x.SetFont(font) sizer.Add(x, (irow, i), (1, 1), wx.ALIGN_LEFT | wx.ALL, 3) i = i + 1 self.trace_labels = [] ntrace_display = min(self.conf.ntrace + 2, len(self.conf.traces)) for i in range(ntrace_display): irow += 1 label = "trace %i" % i lin = self.conf.traces[i] dlab = lin.label dcol = hexcolor(lin.color) dthk = lin.linewidth dmsz = lin.markersize dsty = lin.style djsty = lin.drawstyle dzord = lin.zorder dsym = lin.marker lab = LabelEntry(panel, dlab, size=125, labeltext="%i" % (i + 1), action=partial(self.onText, item='trace', trace=i)) self.trace_labels.append(lab) col = csel.ColourSelect(panel, -1, "", dcol, size=(25, 25)) col.Bind(csel.EVT_COLOURSELECT, partial(self.onColor, trace=i)) self.colwids[i] = col thk = FloatSpin(panel, -1, pos=(-1, -1), size=(FSPINSIZE, 25), value=dthk, min_val=0, max_val=10, increment=0.5, digits=1) thk.Bind(EVT_FLOATSPIN, partial(self.onThickness, trace=i)) sty = wx.Choice(panel, choices=self.conf.styles, size=(100, -1)) sty.Bind(wx.EVT_CHOICE, partial(self.onStyle, trace=i)) sty.SetStringSelection(dsty) msz = FloatSpin(panel, -1, pos=(-1, -1), size=(FSPINSIZE, 25), value=dmsz, min_val=0, max_val=30, increment=1, digits=0) msz.Bind(EVT_FLOATSPIN, partial(self.onMarkerSize, trace=i)) zor = FloatSpin(panel, -1, pos=(-1, -1), size=(FSPINSIZE, 25), value=dzord, min_val=-500, max_val=500, increment=1, digits=0) zor.Bind(EVT_FLOATSPIN, partial(self.onZorder, trace=i)) sym = wx.Choice(panel, -1, choices=self.conf.symbols, size=(120, -1)) sym.Bind(wx.EVT_CHOICE, partial(self.onSymbol, trace=i)) sym.SetStringSelection(dsym) jsty = wx.Choice(panel, -1, choices=self.conf.drawstyles, size=(100, -1)) jsty.Bind(wx.EVT_CHOICE, partial(self.onJoinStyle, trace=i)) jsty.SetStringSelection(djsty) sizer.Add(lab.label, (irow, 0), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(lab, (irow, 1), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(col, (irow, 2), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(sty, (irow, 3), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(thk, (irow, 4), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(sym, (irow, 5), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(msz, (irow, 6), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(zor, (irow, 7), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) sizer.Add(jsty, (irow, 8), (1, 1), wx.ALIGN_LEFT | wx.ALL, 5) autopack(panel, sizer) panel.SetupScrolling() return panel def onResetLines(self, event=None): self.conf.reset_trace_properties() ntrace_display = min(self.conf.ntrace + 2, len(self.conf.traces)) for i in range(ntrace_display): lin = self.conf.traces[i] curcol = hexcolor(self.colwids[i].GetColour()) newcol = hexcolor(lin.color) self.colwids[i].SetColour(newcol) if newcol != curcol: self.onColor(event=None, color=newcol, trace=i) def onColor(self, event=None, color=None, item='trace', trace=1, draw=True): if color is None and event is not None: color = hexcolor(event.GetValue()) if item == 'trace': self.conf.set_trace_color(color, trace=trace) elif item == 'grid': self.conf.set_gridcolor(color) elif item == 'bg': self.conf.set_bgcolor(color) elif item == 'frame': self.conf.set_framecolor(color) elif item == 'text': self.conf.set_textcolor(color) if draw: self.canvas.draw() def onColorThemeStyle(self, event): theme = event.GetString() conf = self.conf conf.set_color_theme(theme) self.colwids['text'].SetColour(conf.textcolor) self.colwids['grid'].SetColour(conf.gridcolor) self.colwids['bg'].SetColour(conf.bgcolor) self.colwids['frame'].SetColour(conf.framecolor) self.onColor(color=conf.bgcolor, item='bg', draw=False) self.onColor(color=conf.gridcolor, item='grid', draw=False) self.onColor(color=conf.framecolor, item='frame', draw=False) self.onColor(color=conf.textcolor, item='text', draw=False) def onLogScale(self, event): xword, yword = event.GetString().split(' / ') xscale = xword.replace('x', '').strip() yscale = yword.replace('y', '').strip() self.conf.set_logscale(xscale=xscale, yscale=yscale) def onStyle(self, event, trace=0): self.conf.set_trace_style(event.GetString(), trace=trace) def onJoinStyle(self, event, trace=0): self.conf.set_trace_drawstyle(event.GetString(), trace=trace) def onSymbol(self, event, trace=0): self.conf.set_trace_marker(event.GetString(), trace=trace) def onMarkerSize(self, event, trace=0): self.conf.set_trace_markersize(event.GetEventObject().GetValue(), trace=trace) def onZorder(self, event, trace=0): self.conf.set_trace_zorder(event.GetEventObject().GetValue(), trace=trace) def onThickness(self, event, trace=0): self.conf.set_trace_linewidth(event.GetEventObject().GetValue(), trace=trace) def onAutoBounds(self, event): axes = self.canvas.figure.get_axes() if event.IsChecked(): for ax in axes: self.conf.user_limits[ax] = [None, None, None, None] [m.Disable() for m in self.xbounds] [m.Disable() for m in self.ybounds] [m.Disable() for m in self.y2bounds] self.vpad_val.Enable() self.conf.unzoom(full=True) else: self.vpad_val.Disable() xb = axes[0].get_xlim() yb = axes[0].get_ylim() for m, v in zip(self.xbounds, xb): m.Enable() m.SetValue(ffmt(v)) for m, v in zip(self.ybounds, yb): m.Enable() m.SetValue(ffmt(v)) if len(axes) > 1: y2b = axes[1].get_ylim() for m, v in zip(self.y2bounds, y2b): m.Enable() m.SetValue(ffmt(v)) def onBounds(self, event=None): def FloatNone(v): if v in ('', 'None', 'none'): return None try: return float(v) except: return None axes = self.canvas.figure.get_axes() xmin, xmax = [FloatNone(w.GetValue()) for w in self.xbounds] ymin, ymax = [FloatNone(w.GetValue()) for w in self.ybounds] self.conf.user_limits[axes[0]] = [xmin, xmax, ymin, ymax] if len(axes) > 1: y2min, y2max = [FloatNone(w.GetValue()) for w in self.y2bounds] self.conf.user_limits[axes[1]] = [xmin, xmax, y2min, y2max] self.conf.set_viewlimits() self.conf.canvas.draw() def onAutoMargin(self, event): self.conf.auto_margins = event.IsChecked() if self.conf.auto_margins: [m.Disable() for m in self.margins] else: ppanel = self.GetParent() vals = ppanel.get_default_margins() for m, v in zip(self.margins, vals): m.Enable() m.SetValue(v) def onMargins(self, event=None): left, top, right, bottom = [float(w.GetValue()) for w in self.margins] self.conf.set_margins(left=left, top=top, right=right, bottom=bottom) def onViewPadEvent(self, event=None): self.conf.viewpad = float(self.vpad_val.GetValue()) self.conf.set_viewlimits() self.conf.canvas.draw() axes = self.canvas.figure.get_axes() xb = axes[0].get_xlim() yb = axes[0].get_ylim() for m, v in zip(self.xbounds, xb): m.SetValue(ffmt(v)) for m, v in zip(self.ybounds, yb): m.SetValue(ffmt(v)) def onScatter(self, event, item=None): conf = self.conf axes = self.canvas.figure.get_axes()[0] if item == 'size': conf.scatter_size = event.GetInt() elif item == 'scatt_nf': self.conf.scatter_normalcolor = hexcolor(event.GetValue()) elif item == 'scatt_ne': self.conf.scatter_normaledge = hexcolor(event.GetValue()) elif item == 'scatt_sf': self.conf.scatter_selectcolor = hexcolor(event.GetValue()) elif item == 'scatt_se': self.conf.scatter_selectedge = hexcolor(event.GetValue()) axes.cla() xd, yd = conf.scatter_xdata, conf.scatter_ydata sdat = zip(xd, yd) mask = conf.scatter_mask if mask is None: axes.scatter(xd, yd, s=conf.scatter_size, c=conf.scatter_normalcolor, edgecolors=conf.scatter_normaledge) else: axes.scatter(xd[np.where(~mask)], yd[np.where(~mask)], s=conf.scatter_size, c=conf.scatter_normalcolor, edgecolors=conf.scatter_normaledge) axes.scatter(xd[np.where(mask)], yd[np.where(mask)], s=conf.scatter_size, c=conf.scatter_selectcolor, edgecolors=conf.scatter_selectedge) self.conf.relabel(delay_draw=False) def onText(self, event, item='trace', trace=0): if item == 'labelsize': size = event.GetInt() self.conf.labelfont.set_size(size) self.conf.titlefont.set_size(size + 1) for ax in self.axes: for lab in ax.get_xticklabels() + ax.get_yticklabels(): lab.set_fontsize(size) self.conf.relabel() return if item == 'legendsize': size = event.GetInt() self.conf.legendfont.set_size(size) # self.conf.relabel() self.conf.draw_legend() return if item == 'title': wid = self.titl elif item == 'ylabel': wid = self.ylab elif item == 'y2label': wid = self.y2lab elif item == 'xlabel': wid = self.xlab elif item == 'trace': wid = self.trace_labels[trace] if wx.EVT_TEXT_ENTER.evtType[0] == event.GetEventType(): s = str(event.GetString()).strip() elif wx.EVT_KILL_FOCUS.evtType[0] == event.GetEventType(): s = wid.GetValue() try: s = str(s).strip() except TypeError: s = '' if '\\' in s and '$' in s: s = clean_texmath(s) # print(" s = ", s) if item in ('xlabel', 'ylabel', 'y2label', 'title'): try: kws = {item: s} self.conf.relabel(**kws) wid.SetBackgroundColour((255, 255, 255)) except: # as from latex error! wid.SetBackgroundColour((250, 250, 200)) elif item == 'trace': try: self.conf.set_trace_label(s, trace=trace) except: pass def onShowGrid(self, event): self.conf.enable_grid(show=event.IsChecked()) def onShowBox(self, event=None): style = 'box' if not event.IsChecked(): style = 'open' self.conf.set_axes_style(style=style) def onShowLegend(self, event, item=''): auto_location = True if item == 'legend': self.conf.show_legend = checked = event.IsChecked() for cb in self.show_legend_cbs: if cb.GetValue() != checked: cb.SetValue(checked) elif item == 'frame': self.conf.show_legend_frame = event.IsChecked() elif item == 'loc': self.conf.legend_loc = event.GetString() auto_location = False elif item == 'onaxis': self.conf.legend_onaxis = event.GetString() self.conf.draw_legend(auto_location=auto_location) def onDragLegend(self, event=None): self.conf.draggable_legend = event.IsChecked() self.conf.draw_legend() def onHideWithLegend(self, event=None): self.conf.hidewith_legend = event.IsChecked() self.conf.draw_legend() def redraw_legend(self): self.conf.draw_legend() def onExit(self, event): self.Close(True)
class UCSettingsPanel(wx.Panel): def __init__(self, *args, **kwds): super(UCSettingsPanel, self).__init__(*args, **kwds) self.phil_params = args[0].phil_params from wx.lib.agw.floatspin import EVT_FLOATSPIN, FloatSpin # Needed to draw and delete the rings. XXX Applies to # calibration_frame as well? self._pyslip = self.GetParent().GetParent().pyslip sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) # Number of decimal digits for distances. self.digits = 2 # Wavelength control. beam = self._pyslip.tiles.raw_image.get_beam() self._wavelength = beam.get_wavelength() # Unit cell controls. if self.phil_params.calibrate_unitcell.unitcell is not None: self._cell = list( self.phil_params.calibrate_unitcell.unitcell.parameters()) else: self._cell = [4.18, 4.72, 58.38, 89.44, 89.63, 75.85] if self.phil_params.calibrate_unitcell.spacegroup is not None: self._spacegroup = self.phil_params.calibrate_unitcell.spacegroup else: self._spacegroup = "P1" self._cell_control_names = [ "uc_a_ctrl", "uc_b_ctrl", "uc_c_ctrl", "uc_alpha_ctrl", "uc_beta_ctrl", "uc_gamma_ctrl" ] box = wx.BoxSizer(wx.HORIZONTAL) self.uc_a = FloatSpin(self, digits=self.digits, name=self._cell_control_names[0], value=self._cell[0]) box.Add(self.uc_a, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="a"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCell, self.uc_a) self.uc_alpha = FloatSpin(self, digits=self.digits, name=self._cell_control_names[3], value=self._cell[3]) box.Add(self.uc_alpha, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="alpha"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCell, self.uc_alpha) sizer.Add(box) box = wx.BoxSizer(wx.HORIZONTAL) self.uc_b = FloatSpin(self, digits=self.digits, name=self._cell_control_names[1], value=self._cell[1]) box.Add(self.uc_b, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="b"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCell, self.uc_b) self.uc_beta = FloatSpin(self, digits=self.digits, name=self._cell_control_names[4], value=self._cell[4]) box.Add(self.uc_beta, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="beta"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCell, self.uc_beta) sizer.Add(box) box = wx.BoxSizer(wx.HORIZONTAL) self.uc_c = FloatSpin(self, digits=self.digits, name=self._cell_control_names[2], value=self._cell[2]) box.Add(self.uc_c, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="c"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCell, self.uc_c) self.uc_gamma = FloatSpin(self, digits=self.digits, name=self._cell_control_names[5], value=self._cell[5]) box.Add(self.uc_gamma, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="gamma"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCell, self.uc_gamma) sizer.Add(box) # Space group control box = wx.BoxSizer(wx.HORIZONTAL) self.space_group_ctrl = wx.TextCtrl(self, name="space group", value=self._spacegroup) box.Add(self.space_group_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="Space group"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(wx.EVT_TEXT, self.OnSpaceGroup, self.space_group_ctrl) sizer.Add(box) # Distance control img = self.GetParent().GetParent()._img box = wx.BoxSizer(wx.HORIZONTAL) self.distance_ctrl = FloatSpin(self, digits=self.digits, name="Detector Distance", value=img.get_detector_distance()) self.distance_ctrl.SetIncrement(0.5) box.Add(self.distance_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) txtd = wx.StaticText(self, label="Detector Distance") box.Add(txtd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpin, self.distance_ctrl) sizer.Add(box) # Wavelength control img = self.GetParent().GetParent()._img box = wx.BoxSizer(wx.HORIZONTAL) self.wavelength_ctrl = FloatSpin(self, digits=4, name="Wavelength", value=img.get_wavelength()) self.wavelength_ctrl.SetIncrement(0.05) box.Add(self.wavelength_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) txtw = wx.StaticText(self, label="Wavelength") box.Add(txtw, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpin, self.wavelength_ctrl) sizer.Add(box) # d_min control if self.phil_params.calibrate_unitcell.d_min is not None: self.d_min = self.phil_params.calibrate_unitcell.d_min else: self.d_min = 3.5 box = wx.BoxSizer(wx.HORIZONTAL) self.d_min_ctrl = FloatSpin(self, digits=self.digits, name="d_min", value=self.d_min) box.Add(self.d_min_ctrl, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) txtd = wx.StaticText(self, label="Highest resolution for ring display") box.Add(txtd, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpin, self.d_min_ctrl) sizer.Add(box) # Centering controls. self._center = [0, 0] box = wx.BoxSizer(wx.HORIZONTAL) self.spinner_fast = FloatSpin(self, digits=self.digits, name="fast_ctrl", value=self._center[0]) box.Add(self.spinner_fast, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="Center fast"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCenter, self.spinner_fast) self.spinner_slow = FloatSpin(self, digits=self.digits, name="slow_ctrl", value=self._center[1]) box.Add(self.spinner_slow, 0, wx.RIGHT | wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, 5) box.Add(wx.StaticText(self, label="Center slow"), 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) self.Bind(EVT_FLOATSPIN, self.OnSpinCenter, self.spinner_slow) sizer.Add(box) self.DrawRings() def __del__(self): if (hasattr(self, "_ring_layer") and self._ring_layer is not None): self._pyslip.DeleteLayer(self._ring_layer) def OnSpinCenter(self, event): obj = event.EventObject name = obj.GetName() if (name == "fast_ctrl"): self._center[0] = obj.GetValue() elif (name == "slow_ctrl"): self._center[1] = obj.GetValue() self.DrawRings() def OnSpinCell(self, event): obj = event.EventObject name = obj.GetName() self._cell[self._cell_control_names.index(name)] = obj.GetValue() self.DrawRings() def OnSpin(self, event): self.DrawRings() def OnSpaceGroup(self, event): obj = event.EventObject self._spacegroup = obj.GetValue() self.DrawRings() def _draw_rings_layer(self, dc, data, map_rel): """Draw a points layer. dc the device context to draw on data an iterable of point tuples: (x, y, place, radius, colour, x_off, y_off, pdata) map_rel points relative to map if True, MUST BE TRUE for lightweight Assumes all points are the same colour, saving 100's of ms. """ assert map_rel is True if len(data) == 0: return (lon, lat, place, radius, colour, x_off, y_off, pdata) = data[0] scale = 2**self._pyslip.tiles.zoom_level # Draw points on map/view, using transparency if implemented. try: dc = wx.GCDC(dc) except NotImplementedError: pass dc.SetPen(wx.Pen(colour)) dc.SetBrush(wx.Brush(colour, wx.TRANSPARENT)) for (lon, lat, place, radius, colour, x_off, y_off, pdata) in data: (x, y) = self._pyslip.ConvertGeo2View((lon, lat)) dc.DrawCircle(x, y, radius * scale) def DrawRings(self): from cctbx.crystal import symmetry import cctbx.miller frame = self.GetParent().GetParent() try: uc = symmetry(unit_cell=self._cell, space_group_symbol=str(self._spacegroup)) hkl_list = cctbx.miller.build_set(uc, False, d_min=self.d_min_ctrl.GetValue()) except Exception, e: frame.update_statusbar(e.message) return frame.update_statusbar("%d %d %d %d %d %d, " % tuple(self._cell) + "number of indices: %d" % len(hkl_list.indices())) spacings = list(hkl_list.d_spacings()) print "Printing spacings, len: %s" % len(spacings) def cmp(a, b): if a[1] > b[1]: return 1 elif a[1] < b[1]: return -1 return 0 spacings = sorted(spacings, cmp=cmp, reverse=True) for d in spacings: print d detector = self._pyslip.tiles.raw_image.get_detector() beam = self._pyslip.tiles.raw_image.get_beam() wavelength = float(self.wavelength_ctrl.GetValue()) distance = float(self.distance_ctrl.GetValue()) pixel_size = detector[0].get_pixel_size( )[0] # FIXME assumes square pixels, and that all panels use same pixel size twotheta = hkl_list.two_theta(wavelength=wavelength) L_mm = [] L_pixels = [] for tt in twotheta: L_mm.append(distance * math.tan(tt[1])) for lmm in L_mm: L_pixels.append(lmm / pixel_size) xrayframe = self.GetParent().GetParent() panel_id, beam_pixel_fast, beam_pixel_slow = xrayframe.get_beam_center_px( ) if len(detector) > 1: beam_pixel_slow, beam_pixel_fast = xrayframe.pyslip.tiles.flex_image.tile_readout_to_picture( panel_id, beam_pixel_slow - 0.5, beam_pixel_fast - 0.5) center = self._pyslip.tiles.picture_fast_slow_to_map_relative( beam_pixel_fast + self._center[0], beam_pixel_slow + self._center[1]) # XXX Transparency? ring_data = [(center[0], center[1], { "colour": "red", "radius": pxl }) for pxl in L_pixels] # Remove the old ring layer, and draw a new one. if (hasattr(self, "_ring_layer") and self._ring_layer is not None): self._pyslip.DeleteLayer(self._ring_layer) self._ring_layer = None self._ring_layer = self._pyslip.AddPointLayer( ring_data, map_rel=True, visible=True, show_levels=[-3, -2, -1, 0, 1, 2, 3, 4, 5], renderer=self._draw_rings_layer, name="<ring_layer>")
class VoltageSourceTunerDialog(Dialog): """ A dialog for tuning a voltage source port. """ def __init__(self, parent, global_store, ok_callback, port, *args, **kwargs): Dialog.__init__(self, parent, title='Port {0} tuning'.format(port.num)) self.global_store = global_store self.ok_callback = ok_callback self.port = port # Dialog. dialog_box = wx.BoxSizer(wx.VERTICAL) ## Self-calibration. calibration_static_box = wx.StaticBox(self, label='DAC self-calibration') calibration_box = wx.StaticBoxSizer(calibration_static_box, wx.VERTICAL) dialog_box.Add(calibration_box, flag=wx.EXPAND | wx.ALL, border=5) self.calibrate_button = wx.Button(self, label='Self-calibrate') self.Bind(wx.EVT_BUTTON, self.OnCalibrate, self.calibrate_button) calibration_box.Add(self.calibrate_button, flag=wx.EXPAND) ## Tuning. tuning_static_box = wx.StaticBox(self, label='Tuning') tuning_box = wx.StaticBoxSizer(tuning_static_box, wx.VERTICAL) dialog_box.Add(tuning_box, flag=wx.EXPAND) ### Autotune. autotuning_static_box = wx.StaticBox(self, label='Autotuning') autotuning_box = wx.StaticBoxSizer(autotuning_static_box, wx.VERTICAL) tuning_box.Add(autotuning_box, flag=wx.EXPAND | wx.ALL, border=5) autotuning_sizer = wx.FlexGridSizer(rows=3, cols=2, hgap=5) autotuning_box.Add(autotuning_sizer, flag=wx.CENTER) autotuning_sizer.Add(wx.StaticText(self, label='Resource name:'), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) self.resource_name_input = wx.TextCtrl(self, size=(300, -1)) autotuning_sizer.Add(self.resource_name_input) autotuning_sizer.Add(wx.StaticText(self, label='Max:'), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) self.automax_input = FloatSpin(self, value=1, min_val=-10, max_val=10, increment=1, digits=5) autotuning_sizer.Add(self.automax_input) autotuning_sizer.Add(wx.StaticText(self, label='Min:'), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) self.automin_input = FloatSpin(self, value=-1, min_val=-10, max_val=10, increment=1, digits=5) autotuning_sizer.Add(self.automin_input) self.autotune_button = wx.Button(self, label='Autotune') self.Bind(wx.EVT_BUTTON, self.OnAutotune, self.autotune_button) autotuning_box.Add(self.autotune_button, flag=wx.EXPAND) ### Manual tune. tuning_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=5) tuning_box.Add(tuning_sizer, flag=wx.CENTER) tuning_sizer.Add(wx.StaticText(self, label='Gain:'), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) self.gain_input = FloatSpin(self, value=0, min_val=-1e6, max_val=1e6, increment=1, digits=5) tuning_sizer.Add(self.gain_input) tuning_sizer.Add(wx.StaticText(self, label='Offset:'), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) self.offset_input = FloatSpin(self, value=0, min_val=-1e6, max_val=1e6, increment=1, digits=5) tuning_sizer.Add(self.offset_input) ## End buttons. button_box = wx.BoxSizer(wx.HORIZONTAL) dialog_box.Add(button_box, flag=wx.CENTER | wx.ALL, border=5) ok_button = wx.Button(self, wx.ID_OK) self.Bind(wx.EVT_BUTTON, self.OnOk, ok_button) button_box.Add(ok_button) cancel_button = wx.Button(self, wx.ID_CANCEL) button_box.Add(cancel_button) self.SetSizerAndFit(dialog_box) def autotune(self, resource): gain, offset = self.port.autotune( resource, set_result=False, min_value=self.automin_input.GetValue(), max_value=self.automax_input.GetValue()) wx.CallAfter(self.gain_input.SetValue, gain) wx.CallAfter(self.offset_input.SetValue, offset) wx.CallAfter(self.autotune_button.Enable) def self_calbrate(self): self.port.apply_settings(calibrate=True) sleep(self.port.calibration_delay) wx.CallAfter(self.calibrate_button.Enable) def SetValue(self, gain, offset): self.gain_input.SetValue(gain) self.offset_input.SetValue(offset) def GetValue(self): return (self.gain_input.GetValue(), self.offset_input.GetValue()) def OnAutotune(self, evt=None): name = self.resource_name_input.Value if not name: MessageDialog(self, 'No resource provided').Show() return try: resource = self.global_store.resources[name] except KeyError: MessageDialog(self, name, 'Missing resource').Show() return if not resource.readable: MessageDialog(self, name, 'Unreadable resource').Show() return self.autotune_button.Disable() thr = Thread(target=self.autotune, args=(resource, )) thr.daemon = True thr.start() def OnCalibrate(self, evt=None): self.calibrate_button.Disable() thr = Thread(target=self.self_calbrate) thr.daemon = True thr.start() def OnOk(self, evt=None): self.ok_callback(self) self.Destroy()
class DacPage(wx.Panel): def __init__(self, parent, gains, offset, frame): wx.Panel.__init__(self, parent) self.frame = frame self.status = self.values = 0 main_sizer = wx.BoxSizer(wx.HORIZONTAL) values_sizer = wx.GridBagSizer(hgap=8, vgap=8) grid = wx.GridBagSizer(hgap=4, vgap=9) self.real_dac = numpy.zeros(5) self.read_dac = numpy.zeros(5) self.gain = gains self.offset = offset g_label = wx.StaticText(self, label="Slope") offset_label = wx.StaticText(self, label="Intercept") values_sizer.Add(g_label, pos=(0, 1)) values_sizer.Add(offset_label, pos=(0, 2)) self.gain_label = wx.StaticText(self, label=" Gain ") self.gains_edit = wx.TextCtrl(self, value=str(self.gain), style=wx.TE_READONLY) self.offset_edit = wx.TextCtrl(self, value=str(self.offset), style=wx.TE_READONLY) self.check_dac = wx.Button(self, label="Check DAC") if frame.hw_ver == "m": self.edit_check = FloatSpin(self, value=0, min_val=-4.096, max_val=4.095, increment=0.001, digits=3) else: self.edit_check = FloatSpin(self, value=0, min_val=0, max_val=4.095, increment=0.001, digits=3) self.Bind(wx.EVT_BUTTON, self.check_dac_event, self.check_dac) values_sizer.Add(self.gain_label, pos=(1, 0)) values_sizer.Add(self.gains_edit, pos=(1, 1)) values_sizer.Add(self.offset_edit, pos=(1, 2)) values_sizer.Add(self.check_dac, pos=(3, 0)) values_sizer.Add(self.edit_check, pos=(3, 1)) self.value_edit = [] self.adc_values = [] self.buttons = [] for i in range(5): self.value_edit.append( FloatSpin(self, value=0, min_val=-4.096, max_val=4.096, increment=0.001, digits=3)) self.buttons.append(wx.Button(self, id=100 + i, label="Fix")) self.Bind(wx.EVT_BUTTON, self.update_event, self.buttons[i]) grid.Add(self.value_edit[i], pos=(i + 3, 0)) grid.Add(self.buttons[i], pos=(i + 3, 1)) if i < 2: self.value_edit[i].Enable(True) self.buttons[i].Enable(True) else: self.buttons[i].Enable(False) self.value_edit[i].Enable(False) self.number_points_list = [] for i in range(4): self.number_points_list.append("%d" % (i + 2)) self.number_points_label = wx.StaticText(self, label="Number of points") self.edit_number_points = wx.ComboBox(self, size=(95, -1), value="2", choices=self.number_points_list, style=wx.CB_READONLY) self.Bind(wx.EVT_COMBOBOX, self.number_points_change, self.edit_number_points) self.set_dac = wx.Button(self, label="Set DAC") self.edit_dac = FloatSpin(self, value=0, min_val=-4.096, max_val=4.096, increment=0.001, digits=3) self.Bind(wx.EVT_BUTTON, self.update_dac, self.set_dac) grid.Add(self.edit_dac, pos=(1, 0)) grid.Add(self.set_dac, pos=(1, 1)) self.update = wx.Button(self, label="Get values") self.Bind(wx.EVT_BUTTON, self.get_values_event, self.update) grid.Add(self.update, pos=(8, 0)) self.reset = wx.Button(self, label="Reset") self.Bind(wx.EVT_BUTTON, self.reset_event, self.reset) grid.Add(self.reset, pos=(8, 1)) grid.Add(self.number_points_label, pos=(0, 0)) grid.Add(self.edit_number_points, pos=(0, 1)) main_sizer.Add(grid, 0, wx.ALL, border=10) main_sizer.Add(values_sizer, 0, wx.ALL, border=10) self.SetSizerAndFit(main_sizer) def number_points_change(self, event): for i in range(5): if i < int(self.edit_number_points.GetValue()): self.value_edit[i].Enable(True) self.buttons[i].Enable(True) else: self.buttons[i].Enable(False) self.value_edit[i].Enable(False) def update_event(self, event): index1 = event.GetEventObject().GetId() - 100 self.real_dac[index1] = self.edit_dac.GetValue() self.read_dac[index1] = self.value_edit[index1].GetValue() self.value_edit[index1].Enable(False) self.buttons[index1].Enable(False) def get_values_event(self, event): self.x = [] self.y = [] for i in range(int(self.edit_number_points.GetValue())): self.y.append(self.real_dac[i] * 1000) self.x.append(self.read_dac[i] * 1000) r = numpy.polyfit(self.x, self.y, 1) self.slope = abs(int(r[0] * 1000)) self.intercept = int(round(r[1], 0)) self.gains_edit.Clear() self.gains_edit.AppendText(str(self.slope)) self.offset_edit.Clear() self.offset_edit.AppendText(str(self.intercept)) self.frame.adc_gains[0] = self.slope self.frame.adc_offset[0] = self.intercept self.frame.dac_gain = self.slope self.frame.dac_offset = self.intercept self.frame.daq.dac_gain = self.slope self.frame.daq.dac_offset = self.intercept self.save_calibration() def reset_event(self, event): for i in range(int(self.edit_number_points.GetValue())): self.buttons[i].Enable(True) self.value_edit[i].Enable(True) self.real_dac = numpy.zeros(5) self.read_dac = numpy.zeros(5) def check_dac_event(self, event): self.frame.daq.set_analog(self.edit_check.GetValue()) def update_dac(self, event): self.frame.daq.set_dac((self.edit_dac.GetValue() * 1000 + 4096) * 2) def save_calibration(self): self.frame.daq.dac_gain = self.slope self.frame.daq.dac_offset = self.intercept self.frame.daq.set_dac_cal(self.slope, self.intercept)
class AdcPage(wx.Panel): def __init__(self, parent, gains, offset, frame): wx.Panel.__init__(self, parent) self.frame = frame self.status = self.values = 0 main_sizer = wx.BoxSizer(wx.HORIZONTAL) values_sizer = wx.GridBagSizer(hgap=8, vgap=8) grid = wx.GridBagSizer(hgap=4, vgap=9) self.gains = gains self.offset = offset g_label = wx.StaticText(self, label="Slope") offset_label = wx.StaticText(self, label="Intercept") values_sizer.Add(g_label, pos=(0, 1)) values_sizer.Add(offset_label, pos=(0, 2)) self.gain_label = [] self.gains_edit = [] self.offset_edit = [] if frame.hw_ver == "m": for i in range(5): self.gain_label.append( wx.StaticText(self, label=" Gain %d" % (i + 1))) self.gains_edit.append( wx.TextCtrl(self, value=str(self.gains[i + 1]), style=wx.TE_READONLY)) self.offset_edit.append( wx.TextCtrl(self, value=str(self.offset[i + 1]), style=wx.TE_READONLY)) values_sizer.Add(self.gain_label[i], pos=(i + 1, 0)) values_sizer.Add(self.gains_edit[i], pos=(i + 1, 1)) values_sizer.Add(self.offset_edit[i], pos=(i + 1, 2)) if frame.hw_ver == "s": for i in range(8): self.gain_label.append( wx.StaticText(self, label=" A%d " % (i + 1))) self.gains_edit.append( wx.TextCtrl(self, value=str(self.gains[i + 1]), style=wx.TE_READONLY)) self.offset_edit.append( wx.TextCtrl(self, value=str(self.offset[i + 1]), style=wx.TE_READONLY)) values_sizer.Add(self.gain_label[i], pos=(i + 1, 0)) values_sizer.Add(self.gains_edit[i], pos=(i + 1, 1)) values_sizer.Add(self.offset_edit[i], pos=(i + 1, 2)) self.value_edit = [] self.adc_values = [] self.buttons = [] for i in range(5): self.value_edit.append( FloatSpin(self, value=0, min_val=-4.096, max_val=4.096, increment=0.001, digits=3)) self.adc_values.append( wx.TextCtrl(self, value="--", style=wx.TE_READONLY)) self.buttons.append(wx.Button(self, id=100 + i, label="Update")) self.Bind(wx.EVT_BUTTON, self.update_event, self.buttons[i]) grid.Add(self.value_edit[i], pos=(i + 3, 0)) grid.Add(self.adc_values[i], pos=(i + 3, 1)) grid.Add(self.buttons[i], pos=(i + 3, 2)) if i < 2: self.value_edit[i].Enable(True) self.adc_values[i].Enable(True) self.buttons[i].Enable(True) else: self.buttons[i].Enable(False) self.value_edit[i].Enable(False) self.adc_values[i].Enable(False) self.number_points_list = [] for i in range(4): self.number_points_list.append("%d" % (i + 2)) self.number_points_label = wx.StaticText(self, label="Number of points") self.edit_number_points = wx.ComboBox(self, size=(95, -1), value="2", choices=self.number_points_list, style=wx.CB_READONLY) self.Bind(wx.EVT_COMBOBOX, self.number_points_change, self.edit_number_points) if frame.hw_ver == "m": self.sample_list = ("+-12 V", "+-4 V", "+-2 V", "+-0.4 V", "+-0.04 V") if frame.hw_ver == "s": self.sample_list = ("SE", "DE") self.sample_list2 = [] for i in range(1, 9): self.sample_list2.append("A%d" % i) self.edit_range = wx.ComboBox(self, size=(95, -1), choices=self.sample_list, style=wx.CB_READONLY) self.edit_range.SetSelection(0) self.Bind(wx.EVT_COMBOBOX, self.range_change, self.edit_range) grid.Add(self.edit_range, pos=(1, 0)) if frame.hw_ver == "s": self.selection = wx.ComboBox(self, size=(95, -1), choices=self.sample_list2, style=wx.CB_READONLY) self.selection.SetSelection(0) grid.Add(self.selection, pos=(1, 1)) self.set_dac = wx.Button(self, label="Set DAC") self.edit_dac = FloatSpin(self, value=0, min_val=-4.096, max_val=4.096, increment=0.001, digits=3) self.Bind(wx.EVT_BUTTON, self.update_dac, self.set_dac) grid.Add(self.edit_dac, pos=(2, 0)) grid.Add(self.set_dac, pos=(2, 1)) self.update = wx.Button(self, label="Get values") self.Bind(wx.EVT_BUTTON, self.get_values_event, self.update) grid.Add(self.update, pos=(8, 0)) self.export = wx.Button(self, label="Export...") self.Bind(wx.EVT_BUTTON, self.export_event, self.export) grid.Add(self.export, pos=(8, 1)) grid.Add(self.number_points_label, pos=(0, 0)) grid.Add(self.edit_number_points, pos=(0, 1)) main_sizer.Add(grid, 0, wx.ALL, border=10) main_sizer.Add(values_sizer, 0, wx.ALL, border=10) self.SetSizerAndFit(main_sizer) def number_points_change(self, event): for i in range(5): if i < int(self.edit_number_points.GetValue()): self.value_edit[i].Enable(True) self.adc_values[i].Enable(True) self.buttons[i].Enable(True) else: self.buttons[i].Enable(False) self.value_edit[i].Enable(False) self.adc_values[i].Enable(False) def range_change(self, event): if self.edit_range.GetValue() == "SE": self.selection.Clear() for i in range(0, 8): self.gain_label[i].Label = "A%d" % (i + 1) self.selection.Append("A%d" % (i + 1)) self.gains_edit[i].Clear() self.gains_edit[i].AppendText(str(self.frame.adc_gains[i + 1])) self.offset_edit[i].Clear() self.offset_edit[i].AppendText( str(self.frame.adc_offset[i + 1])) self.selection.SetSelection(0) if self.edit_range.GetValue() == "DE": self.selection.Clear() for i in range(1, 9): if i % 2: word = "A%d" % i + "-A%d" % (i + 1) else: word = "A%d" % i + "-A%d" % (i - 1) self.selection.Append(word) self.gain_label[i - 1].Label = word self.selection.SetSelection(0) for i in range(8): self.gains_edit[i].Clear() self.gains_edit[i].AppendText(str(self.frame.adc_gains[i + 9])) self.offset_edit[i].Clear() self.offset_edit[i].AppendText( str(self.frame.adc_offset[i + 9])) def update_event(self, event): self.range = self.edit_range.GetCurrentSelection() if self.frame.hw_ver == "s": input = self.selection.GetCurrentSelection() + 1 if input % 2 == 0: ninput = input - 1 else: ninput = input + 1 button = event.GetEventObject() index1 = button.GetId() - 100 if self.frame.hw_ver == "m": self.frame.daq.conf_adc(8, 0, self.range, 20) if self.frame.hw_ver == "s": if self.range == 0: # SE self.frame.daq.conf_adc(input) if self.range == 1: # DE self.frame.daq.conf_adc(input, ninput) time.sleep(0.5) data_int = self.frame.daq.read_adc() time.sleep(0.5) data_int = self.frame.daq.read_adc() # Repeat for stabilizing self.adc_values[index1].Clear() self.adc_values[index1].AppendText(str(data_int)) def get_values_event(self, event): self.range = self.edit_range.GetCurrentSelection() if self.frame.hw_ver == "s": sel = self.selection.GetCurrentSelection() self.x = [] self.y = [] for i in range(int(self.edit_number_points.GetValue())): self.y.append(int(self.value_edit[i].GetValue() * 1000)) self.x.append(int(self.adc_values[i].GetLineText(0))) r = numpy.polyfit(self.x, self.y, 1) if self.frame.hw_ver == "m": self.slope = abs(int(r[0] * 100000)) if self.frame.hw_ver == "s": self.slope = abs(int(r[0] * 10000)) self.intercept = int(r[1]) if self.frame.hw_ver == "m": self.gains_edit[self.range].Clear() self.gains_edit[self.range].AppendText(str(self.slope)) self.offset_edit[self.range].Clear() self.offset_edit[self.range].AppendText(str(self.intercept)) self.frame.adc_gains[self.range + 1] = self.slope self.frame.adc_offset[self.range + 1] = self.intercept if self.frame.hw_ver == "s": self.gains_edit[sel].Clear() self.gains_edit[sel].AppendText(str(self.slope)) self.offset_edit[sel].Clear() self.offset_edit[sel].AppendText(str(self.intercept)) if self.range == 0: # SE self.frame.adc_gains[sel + 1] = self.slope self.frame.adc_offset[sel + 1] = self.intercept if self.range == 1: # DE self.frame.adc_gains[sel + 9] = self.slope self.frame.adc_offset[sel + 9] = self.intercept self.frame.daq.gains = self.frame.adc_gains self.frame.daq.offsets = self.frame.adc_offset self.save_calibration() def update_dac(self, event): self.frame.daq.set_analog(self.edit_dac.GetValue()) def save_calibration(self): self.slope = [] self.intercept = [] if self.frame.hw_ver == "m": for i in range(5): self.slope.append(int(self.gains_edit[i].GetLineText(0))) self.intercept.append(int(self.offset_edit[i].GetLineText(0))) self.flag = "M" if self.frame.hw_ver == "s": if self.edit_range.Value == "SE": self.flag = "SE" for i in range(8): self.slope.append(int(self.gains_edit[i].GetLineText(0))) self.intercept.append( int(self.offset_edit[i].GetLineText(0))) if self.edit_range.Value == "DE": self.flag = "DE" for i in range(8): self.slope.append(int(self.gains_edit[i].GetLineText(0))) self.intercept.append( int(self.offset_edit[i].GetLineText(0))) self.frame.daq.set_cal(self.slope, self.intercept, self.flag) def export_event(self, event): dlg = wx.TextEntryDialog(self, 'openDAQ ID:', 'ID', style=wx.OK | wx.CANCEL) res = dlg.ShowModal() id = dlg.GetValue() dlg.Destroy() if res == wx.ID_CANCEL: return self.directory_name = '' dlg = wx.FileDialog(self, "Choose a file", self.directory_name, "", "*.txt", wx.SAVE) if dlg.ShowModal() == wx.ID_OK: self.file_name = dlg.GetFilename() self.directory_name = dlg.GetDirectory() self.export_calibration(self.directory_name + "/" + self.file_name, id) dlg.Destroy() def export_calibration(self, file, id): output_file = open(file, 'w') model = self.frame.hw_ver.upper() output_file.write("CALIBRATION REPORT OPENDAQ-" + model + ": " + id + "\n\n") output_file.write("DAC CALIBRATION\n") output_file.write("Slope: " + str(self.frame.dac_gain) + " Intercept: " + str(self.frame.dac_offset) + "\n\n") output_file.write("ADC CALIBRATION\n") if self.frame.hw_ver == "s": for i in range(1, 9): output_file.write("A%d:\n" % i) output_file.write("Slope: " + str(self.frame.adc_gains[i]) + " " "Intercept: " + str(self.frame.adc_offset[i]) + "\n") output_file.write("\n") for i in range(9, 17): if i % 2: output = "A" + str(i - 8) + "-A" + str(i - 7) + ":\n" else: output = "A" + str(i - 8) + "-A" + str(i - 9) + ":\n" output_file.write(output) output_file.write("Slope: " + str(self.frame.adc_gains[i]) + " " "Intercept: " + str(self.frame.adc_offset[i]) + "\n") if self.frame.hw_ver == "m": for i in range(1, 6): output_file.write("Gain%d:\n" % i) output_file.write("Slope: " + str(self.frame.adc_gains[i]) + " " "Intercept: " + str(self.frame.adc_offset[i]) + "\n") dlg = (wx.MessageDialog(self, "Report saved", "Report saved", wx.OK | wx.ICON_QUESTION)) dlg.ShowModal() dlg.Destroy()
class YAxisRangeBox(wx.Panel): """ panel for adjusting y-axis range """ def __init__(self, parent, ID, minvalue=YMIN, initvalue=YRANGE, increment=SPININC): wx.Panel.__init__(self, parent, ID) self.value = initvalue # initial y-axis range (in manual mode), i.e. (min, max-min) # controls self.radio_auto = wx.RadioButton(self, -1, label='Auto', style=wx.RB_GROUP) self.radio_manual = wx.RadioButton(self, -1, label='Manual') self.manual_min = FloatSpin(self, -1, size=(50, -1), digits=0, value=self.value[0], min_val=minvalue[0], increment=increment) self.manual_min.GetTextCtrl().SetEditable(False) self.manual_width = FloatSpin(self, -1, size=(50, -1), digits=0, value=self.value[1], min_val=minvalue[1], increment=increment) self.manual_width.GetTextCtrl().SetEditable(False) # event bindings self.Bind(wx.EVT_UPDATE_UI, self.on_update_radio_buttons, self.radio_auto) self.Bind(EVT_FLOATSPIN, self.on_float_spin, self.manual_min) self.Bind(EVT_FLOATSPIN, self.on_float_spin, self.manual_width) # layout box = wx.StaticBox(self, -1, 'Y-axis') sizer = wx.StaticBoxSizer(box, wx.VERTICAL) manual_box = wx.BoxSizer(wx.HORIZONTAL) manual_box.Add(self.radio_manual, flag=wx.ALIGN_CENTER_VERTICAL) manual_box.Add(self.manual_min, flag=wx.ALIGN_CENTER_VERTICAL) manual_box.Add(self.manual_width, flag=wx.ALIGN_CENTER_VERTICAL) sizer.Add(self.radio_auto, 0, wx.ALL, 10) sizer.Add(manual_box, 0, wx.ALL, 10) self.SetSizer(sizer) sizer.Fit(self) def on_update_radio_buttons(self, event): """ called when the radio buttons are toggled """ toggle = self.radio_manual.GetValue() self.manual_min.Enable(toggle) self.manual_width.Enable(toggle) def on_float_spin(self, event): """ called when one of the manual mode spinboxes is changed """ self.value = (self.manual_min.GetValue(), self.manual_width.GetValue()) def is_auto(self): """ return True if auto range is checked """ return self.radio_auto.GetValue()
class GraphOptions(wx.Dialog): """Graph options for plot in main window""" #---------------------------------------------------------------------- def __init__(self,parent=None,extended=True): """Constructor""" wx.Dialog.__init__(self, parent, wx.ID_ANY, "Graph Options", size = (600,450), ) self.parent = parent colors=["blue","black","green","red","yellow","orange","pink","purple","brown", "gray","darkblue","silver","darkgreen","darkred","gold"] styles=["-","-.",":","steps","--","_"] #axis self.xlabel = "Depth [mm]" self.ylabel = "Force [N]" self.xlim = (0,300) self.auto_x = True self.ylim = (-1,41) self.auto_y = True self.xticks = 10 self.auto_xticks = True self.yticks = 10 self.auto_yticks = True self.mirrorx = False self.mirrory = False self.plot_title = "SMP Measurement" self.logscale = False #data self.color = colors[0] self.style = styles[0] self.width = 1 self.sampling = 1 #gradient self.grad_color = colors[3] self.grad_style = styles[2] self.grad_width = 1 self.grad_sampling = 100 #median self.median_color = colors[9] self.median_style = styles[0] self.median_width = 1 self.median_sampling = 100 panel = wx.Panel(self) notebook = Tabs(panel,extended) confirm = wx.Button(panel, wx.ID_OK) self.Bind(wx.EVT_BUTTON,self.onOK,confirm) cancel = wx.Button(panel, wx.ID_CANCEL) self.Bind(wx.EVT_BUTTON,self.onCancel,cancel) apply = wx.Button(panel, wx.ID_APPLY) self.Bind(wx.EVT_BUTTON,self.onApply,apply) vsizer = wx.BoxSizer(wx.VERTICAL) vsizer.Add(notebook, 1, wx.ALL|wx.EXPAND) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(cancel) hsizer.Add(apply) hsizer.Add(confirm) vsizer.Add(hsizer,0,wx.ALIGN_RIGHT) panel.SetSizer(vsizer) self.Layout() #axis self.box_autox = wx.CheckBox(notebook.tabAxis, -1 ,'Auto X') self.Bind(wx.EVT_CHECKBOX,self.onUpdate,self.box_autox) self.box_autoy = wx.CheckBox(notebook.tabAxis, -1 ,'Auto Y') self.Bind(wx.EVT_CHECKBOX,self.onUpdate,self.box_autoy) self.box_autox_tick = wx.CheckBox(notebook.tabAxis, -1 ,'Auto X ticks') self.Bind(wx.EVT_CHECKBOX,self.onUpdate,self.box_autox_tick) self.box_autoy_tick = wx.CheckBox(notebook.tabAxis, -1 ,'Auto Y ticks') self.Bind(wx.EVT_CHECKBOX,self.onUpdate,self.box_autoy_tick) self.box_mirrorx = wx.CheckBox(notebook.tabAxis, -1 ,'Mirror X') self.box_mirrory = wx.CheckBox(notebook.tabAxis, -1 ,'Mirror Y') self.xmin = FloatSpin(notebook.tabAxis,-1,value=self.xlim[0],min_val=-100.00,max_val=1800.00,increment=1,digits=3) label_xmin = wx.StaticText(notebook.tabAxis,-1, 'X min') self.ymin = FloatSpin(notebook.tabAxis,-1,value=self.ylim[0],min_val=-100.00,max_val=1800.00,increment=1,digits=3) label_ymin = wx.StaticText(notebook.tabAxis,-1, 'Y min') self.xmax = FloatSpin(notebook.tabAxis,-1,value=self.xlim[1],min_val=-100.00,max_val=1800.00,increment=1,digits=3) label_xmax = wx.StaticText(notebook.tabAxis,-1, 'X max') self.ymax = FloatSpin(notebook.tabAxis,-1,value=self.ylim[1],min_val=-100.00,max_val=1800.00,increment=1,digits=3) label_ymax = wx.StaticText(notebook.tabAxis,-1, 'Y max') self.xlabel_ctrl = wx.TextCtrl(notebook.tabAxis,-1,size=(200,-1),value=self.xlabel) label_xlabel = wx.StaticText(notebook.tabAxis,-1, 'X label') self.ylabel_ctrl = wx.TextCtrl(notebook.tabAxis,-1,size=(200,-1),value=self.ylabel) label_ylabel = wx.StaticText(notebook.tabAxis,-1, 'Y label') label_xticks = wx.StaticText(notebook.tabAxis,-1, 'X ticks') self.xticks_ctrl = wx.SpinCtrl(notebook.tabAxis,-1,size=(100,-1),min=1,max=100,initial=self.xticks,name="X ticks") label_yticks = wx.StaticText(notebook.tabAxis,-1, 'Y ticks') self.yticks_ctrl = wx.SpinCtrl(notebook.tabAxis,-1,size=(100,-1),min=1,max=100,initial=self.yticks,name="Y ticks") self.scale_ctrl = wx.CheckBox(notebook.tabAxis, -1, "Log Scale") self.box_autox.SetValue(True) self.xmin.Enable(False) self.xmax.Enable(False) self.box_autoy.SetValue(True) self.ymin.Enable(False) self.ymax.Enable(False) self.xticks_ctrl.Enable(False) self.yticks_ctrl.Enable(False) self.box_autox_tick.SetValue(True) self.box_autoy_tick.SetValue(True) self.box_mirrorx.SetValue(self.mirrorx) self.box_mirrory.SetValue(self.mirrory) self.scale_ctrl.SetValue(self.logscale) font = wx.Font(14,wx.DEFAULT, wx.NORMAL,wx.BOLD,True) #graph label_data = wx.StaticText(notebook.tabGraph, -1, "Data Plot") label_sampling = wx.StaticText(notebook.tabGraph,-1, 'Down sampling Factor') self.sampling_ctrl = wx.SpinCtrl(notebook.tabGraph,-1,size=(100,-1),min=0,max=1000,initial=self.sampling,name="Sampling") label_color = wx.StaticText(notebook.tabGraph,-1, 'Line Color') self.color_ctrl = wx.ComboBox(notebook.tabGraph, -1, size=(150, -1), choices=colors, style=wx.CB_READONLY,value=self.color) label_style = wx.StaticText(notebook.tabGraph,-1, 'Line Style') self.style_ctrl = wx.ComboBox(notebook.tabGraph, -1, size=(150, -1), choices=styles, style=wx.CB_READONLY,value=self.style) label_width = wx.StaticText(notebook.tabGraph,-1, 'Line Width') self.width_ctrl = wx.SpinCtrl(notebook.tabGraph, -1,name="Width",initial=1,min=0.5,max=10,pos=(325,135),size=(50,-1)) #gradient label_grad = wx.StaticText(notebook.tabGraph, -1, "Gradient") label_grad_sampling = wx.StaticText(notebook.tabGraph,-1, 'Down sampling Factor') self.grad_sampling_ctrl = wx.SpinCtrl(notebook.tabGraph,-1,size=(100,-1),min=0,max=1000,initial=self.grad_sampling,name="Sampling") label_grad_color = wx.StaticText(notebook.tabGraph,-1, 'Line Color') self.grad_color_ctrl = wx.ComboBox(notebook.tabGraph, -1, size=(150, -1), choices=colors, style=wx.CB_READONLY,value=self.grad_color) label_grad_style = wx.StaticText(notebook.tabGraph,-1, 'Line Style') self.grad_style_ctrl = wx.ComboBox(notebook.tabGraph, -1, size=(150, -1), choices=styles, style=wx.CB_READONLY,value=self.grad_style) label_grad_width = wx.StaticText(notebook.tabGraph,-1, 'Line Width') self.grad_width_ctrl = wx.SpinCtrl(notebook.tabGraph, -1,name="Width",initial=1,min=0.5,max=10,pos=(325,135),size=(50,-1)) #median label_median = wx.StaticText(notebook.tabGraph, -1, "Median") label_median_sampling = wx.StaticText(notebook.tabGraph,-1, 'Window') self.median_sampling_ctrl = wx.SpinCtrl(notebook.tabGraph,-1,size=(100,-1),min=0,max=1000,initial=self.median_sampling,name="Sampling") label_median_color = wx.StaticText(notebook.tabGraph,-1, 'Line Color') self.median_color_ctrl = wx.ComboBox(notebook.tabGraph, -1, size=(150, -1), choices=colors, style=wx.CB_READONLY,value=self.median_color) label_median_style = wx.StaticText(notebook.tabGraph,-1, 'Line Style') self.median_style_ctrl = wx.ComboBox(notebook.tabGraph, -1, size=(150, -1), choices=styles, style=wx.CB_READONLY,value=self.median_style) label_median_width = wx.StaticText(notebook.tabGraph,-1, 'Line Width') self.median_width_ctrl = wx.SpinCtrl(notebook.tabGraph, -1,name="Width",initial=1,min=0.5,max=10,pos=(325,135),size=(50,-1)) vert1 = wx.BoxSizer(wx.VERTICAL) vert2 = wx.BoxSizer(wx.VERTICAL) hor1 = wx.BoxSizer(wx.HORIZONTAL) hor1.Add(self.box_autoy,0,wx.ALIGN_CENTER|wx.ALL) hor1.Add(self.scale_ctrl,0,wx.ALIGN_CENTER|wx.ALL) vert1.Add(self.box_autox,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(hor1,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(label_xmin,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.xmin,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_ymin,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.ymin,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(label_xmax,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.xmax,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_ymax,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.ymax,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(label_xlabel,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.xlabel_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_ylabel,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.ylabel_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(self.box_autox_tick,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(label_xticks,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.xticks_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(self.box_mirrorx,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(self.box_autoy_tick,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_yticks,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.yticks_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(self.box_mirrory,0,wx.ALIGN_CENTER|wx.ALL,10) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(vert1,wx.ALIGN_CENTER) sizer.Add(wx.StaticLine(notebook.tabAxis,style=wx.LI_VERTICAL,size=(-1,600))) sizer.Add(vert2,wx.ALIGN_CENTER) notebook.tabAxis.SetSizer(sizer) vert1 = wx.BoxSizer(wx.VERTICAL) vert2 = wx.BoxSizer(wx.VERTICAL) vert3 = wx.BoxSizer(wx.VERTICAL) vert1.Add(label_data,0,wx.ALIGN_CENTER|wx.ALL,20) vert1.Add(label_sampling,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.sampling_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(label_color,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.color_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(label_width,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.width_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert1.Add(label_style,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert1.Add(self.style_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_grad,0,wx.ALIGN_CENTER|wx.ALL,20) vert2.Add(label_grad_sampling,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.grad_sampling_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_grad_color,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.grad_color_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_grad_width,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.grad_width_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert2.Add(label_grad_style,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert2.Add(self.grad_style_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert3.Add(label_median,0,wx.ALIGN_CENTER|wx.ALL,20) vert3.Add(label_median_sampling,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert3.Add(self.median_sampling_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert3.Add(label_median_color,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert3.Add(self.median_color_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert3.Add(label_median_width,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert3.Add(self.median_width_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) vert3.Add(label_median_style,0,wx.ALIGN_CENTER|wx.RIGHT,10) vert3.Add(self.median_style_ctrl,0,wx.ALIGN_CENTER|wx.ALL,10) label_data.SetFont(font) label_grad.SetFont(font) label_median.SetFont(font) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(vert1,wx.ALIGN_CENTER|wx.ALIGN_BOTTOM) sizer.Add(wx.StaticLine(notebook.tabGraph,style=wx.LI_VERTICAL,size=(-1,600))) sizer.Add(vert2,wx.ALIGN_CENTER|wx.ALIGN_BOTTOM) sizer.Add(wx.StaticLine(notebook.tabGraph,style=wx.LI_VERTICAL,size=(-1,600))) sizer.Add(vert3,wx.ALIGN_CENTER|wx.ALIGN_BOTTOM) notebook.tabGraph.SetSizer(sizer) def onOK(self,e): """OK button event""" self.onApply(e) self.Hide() def onApply(self,e): """Apply button event""" self.color = self.color_ctrl.GetValue() self.style = self.style_ctrl.GetValue() self.width = self.width_ctrl.GetValue() self.xlabel = self.xlabel_ctrl.GetValue() self.ylabel = self.ylabel_ctrl.GetValue() self.xlim = (self.xmin.GetValue(),self.xmax.GetValue()) self.ylim = (self.ymin.GetValue(),self.ymax.GetValue()) self.sampling = self.sampling_ctrl.GetValue() self.auto_x = self.box_autox.GetValue() self.auto_y = self.box_autoy.GetValue() self.xticks = self.xticks_ctrl.GetValue() self.auto_xticks = self.box_autox_tick.GetValue() self.yticks = self.yticks_ctrl.GetValue() self.auto_yticks = self.box_autoy.GetValue() self.mirrorx = self.box_mirrorx.GetValue() self.mirrory = self.box_mirrory.GetValue() self.grad_color = self.grad_color_ctrl.GetValue() self.grad_style = self.grad_style_ctrl.GetValue() self.grad_width = self.grad_width_ctrl.GetValue() self.grad_sampling = self.grad_sampling_ctrl.GetValue() self.logscale = self.scale_ctrl.GetValue() self.median_color = self.median_color_ctrl.GetValue() self.median_style = self.median_style_ctrl.GetValue() self.median_width = self.median_width_ctrl.GetValue() self.median_sampling = self.median_sampling_ctrl.GetValue() self.parent.draw_figure(autozoom=False) def onCancel(self,e): """cancel button event""" self.color_ctrl.SetValue(self.color) self.style_ctrl.SetValue(self.style) self.width_ctrl.SetValue(self.width) self.xlabel_ctrl.SetValue(self.xlabel) self.ylabel_ctrl.SetValue(self.ylabel) self.xmin.SetValue(self.xlim[0]) self.xmax.SetValue(self.xlim[1]) self.ymin.SetValue(self.ylim[0]) self.ymax.SetValue(self.ylim[1]) self.sampling_ctrl.SetValue(self.sampling) self.box_autox.SetValue(self.auto_x) self.box_autoy.SetValue(self.auto_y) self.xticks_ctrl.SetValue(self.xticks) self.box_autox_tick.SetValue(self.auto_xticks) self.yticks_ctrl.SetValue(self.yticks) self.box_autoy_tick.SetValue(self.auto_yticks) self.box_mirrorx.SetValue(self.mirrorx) self.box_mirrory.SetValue(self.mirrory) self.grad_color_ctrl.SetValue(self.grad_color) self.grad_style_ctrl.SetValue(self.grad_style) self.grad_width_ctrl.SetValue(self.grad_width) self.grad_sampling_ctrl.SetValue(self.grad_sampling) self.scale_ctrl.SetValue(self.logscale) self.median_color_ctrl.SetValue(self.median_color) self.median_style_ctrl.SetValue(self.median_style) self.median_width_ctrl.SetValue(self.median_width) self.median_sampling_ctrl.SetValue(self.median_sampling) self.Hide() def onUpdate(self,e): xlim = not self.box_autox.GetValue() self.xmax.Enable(xlim) self.xmin.Enable(xlim) ylim = not self.box_autoy.GetValue() self.ymax.Enable(ylim) self.ymin.Enable(ylim) xtick = not self.box_autox_tick.GetValue() self.xticks_ctrl.Enable(xtick) ytick = not self.box_autoy_tick.GetValue() self.yticks_ctrl.Enable(ytick)
class ScalingSettingsDialog(Dialog): def __init__(self, parent, ok_callback, *args, **kwargs): Dialog.__init__(self, parent, title='Scaling settings') self.ok_callback = ok_callback # Dialog. dialog_box = wx.BoxSizer(wx.VERTICAL) ## Settings. settings_box = wx.FlexGridSizer(rows=3, cols=2, hgap=5) dialog_box.Add(settings_box, flag=wx.EXPAND|wx.ALL, border=5) ### Linear scale. settings_box.Add(wx.StaticText(self, label='Linear scale:'), flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) self.linear_scale_input = FloatSpin(self, value=0, min_val=-1e9, max_val=1e9, increment=1, digits=5) settings_box.Add(self.linear_scale_input, flag=wx.EXPAND) ### Exponential scale. settings_box.Add(wx.StaticText(self, label='Exponential scale:'), flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) self.exponential_scale_input = FloatSpin(self, value=0, min_val=-100, max_val=100, increment=1, digits=2) settings_box.Add(self.exponential_scale_input, flag=wx.EXPAND) ### Offset. settings_box.Add(wx.StaticText(self, label='Offset:'), flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) self.offset_input = FloatSpin(self, value=0, min_val=-1e9, max_val=1e9, increment=1, digits=5, size=(200, -1)) settings_box.Add(self.offset_input, flag=wx.EXPAND) ## End buttons. button_box = wx.BoxSizer(wx.HORIZONTAL) dialog_box.Add(button_box, flag=wx.CENTER|wx.ALL, border=5) ok_button = wx.Button(self, wx.ID_OK) self.Bind(wx.EVT_BUTTON, self.OnOk, ok_button) button_box.Add(ok_button) cancel_button = wx.Button(self, wx.ID_CANCEL) button_box.Add(cancel_button) self.SetSizerAndFit(dialog_box) def GetValue(self): result = ScalingSettings() result.linear_scale = self.linear_scale_input.GetValue() result.exponential_scale = self.exponential_scale_input.GetValue() result.offset = self.offset_input.GetValue() return result def SetValue(self, value): self.linear_scale_input.SetValue(value.linear_scale) self.exponential_scale_input.SetValue(value.exponential_scale) self.offset_input.SetValue(value.offset) def OnOk(self, evt=None): self.ok_callback(self) self.Destroy()
class ConfigFrame(wx.Frame): """ configuration window class, shown at the start of the simulation, for picking the configuration file and setting visualization flags """ def __init__(self, parent, id, title, defaultFile, defaultPath, app): wx.Frame.__init__(self, parent, id, title, style=wx.CAPTION | wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN) self.defaultFile = defaultFile # the filename of the default config file self.defaultPath = defaultPath # the initial path that is given for the file picker dialog self.app = app # reference to the application that constructed this frame # dimensions of main panel fullWidth = 300 buttonWidth = 100 borderWidth = 10 # create main panel mainPanel = wx.Panel(self, wx.ID_ANY) # create configuration widgets configBox = wx.StaticBox(mainPanel, wx.ID_ANY, label='Configuration file', style=wx.BORDER_SUNKEN) configBoxSizer = wx.StaticBoxSizer(configBox, wx.VERTICAL) self.configText = wx.TextCtrl(mainPanel, wx.ID_ANY, value=self.defaultFilename(), size=(fullWidth, -1), style=wx.TE_READONLY) self.createButton = wx.Button(mainPanel, wx.ID_ANY, label='Create...', size=(buttonWidth, -1)) self.loadButton = wx.Button(mainPanel, wx.ID_ANY, label='Load...', size=(buttonWidth, -1)) # layout configuration widgets configButtonSizer = wx.BoxSizer(wx.HORIZONTAL) configButtonSizer.Add(self.createButton, flag=wx.ALL, border=0) configButtonSizer.Add((fullWidth - 2 * buttonWidth, -1), 1) configButtonSizer.Add(self.loadButton, flag=wx.ALL, border=0) configBoxSizer.Add(self.configText, 0, wx.ALL, border=borderWidth) configBoxSizer.Add(configButtonSizer, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, border=borderWidth) configBoxSizer.Fit(configBox) # create visualization widgets visualBox = wx.StaticBox(mainPanel, wx.ID_ANY, label='Demonstration options', style=wx.BORDER_SUNKEN) visualBoxSizer = wx.StaticBoxSizer(visualBox, wx.VERTICAL) self.checkLevels = wx.CheckBox( mainPanel, wx.ID_ANY, label=' Print A-weighted SPL at receivers to console') self.checkVehicles = wx.CheckBox( mainPanel, wx.ID_ANY, label=' Print detailed vehicle information to console') self.checkTimeseries = wx.CheckBox( mainPanel, wx.ID_ANY, label=' Send level timeseries at receivers to Viewer') # create slowdown spinbox self.slowdownTxt1 = wx.StaticText(mainPanel, -1, label=' Slowdown: ') self.slowdownSpin = FloatSpin(mainPanel, -1, size=(60, -1), digits=0, value=0, min_val=0, increment=50) self.slowdownSpin.GetTextCtrl().SetEditable(False) self.slowdownTxt2 = wx.StaticText(mainPanel, -1, label=' milliseconds/timestep') self.enableSlowdown(False) self.slowdownBoxSizer = wx.BoxSizer(wx.HORIZONTAL) self.slowdownBoxSizer.Add(self.slowdownTxt1, border=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.slowdownBoxSizer.Add(self.slowdownSpin, border=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.slowdownBoxSizer.Add(self.slowdownTxt2, border=0, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) # layout visualization widgets visualBoxSizer.Add(self.checkLevels, 0, wx.ALL, border=borderWidth) visualBoxSizer.Add(self.checkVehicles, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, border=borderWidth) visualBoxSizer.Add(self.checkTimeseries, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, border=borderWidth) visualBoxSizer.Add(self.slowdownBoxSizer, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, border=borderWidth) visualBoxSizer.Add((fullWidth + 2 * borderWidth, -1), 1) visualBoxSizer.Fit(visualBox) # create buttons self.disableButton = wx.Button(mainPanel, wx.ID_ANY, label='Disable plugin', size=(buttonWidth, -1)) self.okButton = wx.Button(mainPanel, wx.ID_ANY, label='Ok', size=(buttonWidth, -1)) okButtonSizer = wx.BoxSizer(wx.HORIZONTAL) okButtonSizer.Add(self.disableButton, flag=wx.ALL, border=0) okButtonSizer.Add((fullWidth + 3 * borderWidth - 2 * buttonWidth, -1), 1) okButtonSizer.Add(self.okButton, flag=wx.ALL, border=0) # finally, add main sizer with border mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(configBoxSizer, 0, flag=wx.ALL, border=borderWidth) mainSizer.Add(visualBoxSizer, 0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=borderWidth) mainSizer.Add(okButtonSizer, 0, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM, border=borderWidth) mainPanel.SetSizerAndFit(mainSizer) self.Fit() # associate events with class methods self.createButton.Bind(wx.EVT_BUTTON, self.OnCreate) self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad) self.disableButton.Bind(wx.EVT_BUTTON, self.OnDisable) self.okButton.Bind(wx.EVT_BUTTON, self.OnOK) self.checkTimeseries.Bind(wx.EVT_CHECKBOX, self.OnTimeseries) self.okButton.SetFocus() # set result value to default self.checkFilename() self.app.result = None def defaultFilename(self): """ return the default filename, including the full path """ return os.path.join(self.defaultPath, self.defaultFile) def checkFilename(self): """ check if the filename in the configText exists, and apply the necessary gui updates """ # fetch the full filename filename = self.configText.GetValue() if os.path.exists(filename): # enable OK button self.okButton.Enable(True) return True else: # clear the filename box self.configText.SetValue('') # disable the OK button self.okButton.Enable(False) return False def enableSlowdown(self, flag=True): """ enable or disable the slowdown spinbox """ for widget in [ self.slowdownTxt1, self.slowdownSpin, self.slowdownTxt2 ]: widget.Enable(flag) def OnTimeseries(self, event): """ executed when the user toggles the checkTimeseries check box """ self.enableSlowdown(self.checkTimeseries.GetValue()) def OnCreate(self, event): """ executed when the user presses the Create button """ # ask for filename dialog = wx.FileDialog(None, message='Save the configuration file as...', defaultDir=self.defaultPath, wildcard=('*.%s' % version.name), style=wx.SAVE | wx.FD_OVERWRITE_PROMPT) if dialog.ShowModal() == wx.ID_OK: # create a default configuration file filename = dialog.GetPath() cfg = Configuration() cfg.save(filename) # finally, update the filename box and the gui self.configText.SetValue(filename) self.checkFilename() def OnLoad(self, event): """ executed when the user presses the Load button """ # show a file picker dialog dialog = wx.FileDialog(None, message='Select a configuration file', defaultDir=self.defaultPath, wildcard=('*.%s' % version.name), style=wx.OPEN) if dialog.ShowModal() == wx.ID_OK: self.configText.SetValue(dialog.GetPath()) self.checkFilename() def OnDisable(self, event): """ executed when the user presses the Disable button """ # close without a configuration filename (thus disable the plugin) self.app.result = (None, False, False, False, 0) self.Destroy() def OnOK(self, event): """ executed when the user presses the OK button """ # fetch the options if self.checkFilename(): self.app.result = (self.configText.GetValue(), self.checkLevels.GetValue(), self.checkVehicles.GetValue(), self.checkTimeseries.GetValue(), self.slowdownSpin.GetValue()) self.Destroy()
class PreferencesDialog(wx.Dialog): def __init__(self, parent, id=-1, title='Preferences', style=wx.DEFAULT_DIALOG_STYLE, major_increment=0.75, minor_increment=0.1): super(PreferencesDialog, self).__init__(parent, id, title, (-1, -1), (-1, -1), style) self.SetBackgroundColour('black') labelFont = wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False) # Spinners for setting the increments self.maj_increment_spin = FloatSpin(self, wx.ID_ANY, value=major_increment, digits=2, increment=0.1, size=(65, -1)) # Button maj_label = wx.StaticText(self, wx.ID_ANY, 'Major Increment', style=wx.ALIGN_CENTER) # Label maj_label.SetForegroundColour('white') maj_label.SetFont(labelFont) self.min_increment_spin = FloatSpin(self, wx.ID_ANY, value=minor_increment, digits=2, increment=0.1, size=(65, -1)) # Button min_label = wx.StaticText(self, wx.ID_ANY, 'Minor Increment', style=wx.ALIGN_CENTER) # Label min_label.SetForegroundColour('white') min_label.SetFont(labelFont) # To keep the items properly aligned major_increment_sizer = wx.BoxSizer(wx.HORIZONTAL) minor_increment_sizer = wx.BoxSizer(wx.HORIZONTAL) major_increment_sizer.Add(maj_label, 0, wx.ALIGN_RIGHT | wx.BOTTOM | wx.LEFT, 10) major_increment_sizer.AddSpacer(6) major_increment_sizer.Add(self.maj_increment_spin, 0, wx.ALIGN_LEFT | wx.BOTTOM | wx.RIGHT, 10) minor_increment_sizer.Add(min_label, 0, wx.ALIGN_RIGHT | wx.BOTTOM | wx.LEFT, 10) minor_increment_sizer.AddSpacer(6) minor_increment_sizer.Add(self.min_increment_spin, 0, wx.ALIGN_LEFT | wx.BOTTOM | wx.RIGHT, 10) # OK/Cancel bar self.ok_button = wx.Button(self, id=wx.OK, label="OK", size=(65, -1)) self.ok_button.SetBackgroundColour('medium gray') self.ok_button.SetForegroundColour('white') self.ok_button.Bind(wx.EVT_BUTTON, self.on_okay) self.cancel_button = wx.Button(self, id=wx.CANCEL, label="Cancel", size=(65, -1)) self.cancel_button.SetBackgroundColour('medium gray') self.cancel_button.SetForegroundColour('white') self.cancel_button.Bind(wx.EVT_BUTTON, self.on_cancel) okbar_sizer = wx.BoxSizer(wx.HORIZONTAL) okbar_sizer.Add(self.ok_button, 0, wx.ALIGN_LEFT | wx.BOTTOM | wx.LEFT, 2) okbar_sizer.AddSpacer(20) okbar_sizer.Add(self.cancel_button, 0, wx.ALIGN_RIGHT | wx.BOTTOM | wx.RIGHT, 2) sizer = wx.GridBagSizer() sizer.AddGrowableCol(0, 4) sizer.Add(major_increment_sizer, (0, 0), (1, 2), wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add(minor_increment_sizer, (1, 0), (1, 2), wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add(okbar_sizer, (2, 0), (1, 2), wx.ALIGN_CENTER | wx.ALL, 5) self.SetSizerAndFit(sizer) self.SetAffirmativeId(wx.OK) self.SetEscapeId(wx.CANCEL) self.AddMainButtonId(wx.OK) def on_okay(self, evt): self.EndModal(1) def on_cancel(self, evt): self.EndModal(-1) def get_prefs(self): return dict(minor_increment=self.min_increment_spin.GetValue(), major_increment=self.maj_increment_spin.GetValue())
class Reglage(wx.Dialog): """ Cette class pour la fenetre de réglage """ echelle, perte_precision, perte_precision_unite, nbre_partie, cle , tatouer= "", "", "", "", "", "" reglage_done = False def __init__(self, parent, title): super(Reglage, self).__init__(parent, title = "Réglages", size =(360,450), style =wx.CLOSE_BOX|wx.SYSTEM_MENU|wx.CAPTION | wx.CLOSE_BOX) self.InitUi() self.Center() def InitUi(self): panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) echelle_label = wx.StaticText(panel, -1, "Echelle : 1/") hbox1.Add(echelle_label, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,9) self.echelle = FloatSpin(panel, value=1 , min_val=1.0, increment=1.0, digits=8, size=(100,-1)) hbox1.Add(self.echelle, 2, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,4) vbox.Add(hbox1, 1, wx.EXPAND|wx.ALL, 1) #------------------------------------------- sb = wx.StaticBox(panel, label=" Perte de précision autorisé :") boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL) self.perte_precision = wx.SpinCtrl(panel, value="1") self.perte_precision.SetRange(1, 8) self.perte_precision.SetValue(2) boxsizer.Add(self.perte_precision, 1, wx.ALL|wx.EXPAND, 1) #------------------------------------------- tmp = ["mm","cm","m","km"] self.rbox = wx.RadioBox(panel, label='', choices = tmp, majorDimension=1, style=wx.RA_SPECIFY_ROWS) boxsizer.Add(self.rbox, flag=wx.ALL|wx.ALIGN_CENTER, border=1) vbox.Add(boxsizer, 1, wx.EXPAND, 5) #------------------------------------------ hbox2 = wx.BoxSizer(wx.HORIZONTAL) partie_label = wx.StaticText(panel, -1, "Nombre de partie : ") hbox2.Add(partie_label, 0, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,9) self.nbre_partie = wx.TextCtrl(panel) self.nbre_partie.SetValue("") hbox2.Add(self.nbre_partie, 1, wx.EXPAND|wx.ALIGN_RIGHT|wx.ALL,4) vbox.Add(hbox2, 1, wx.EXPAND|wx.ALL, 1) #------------------------------------------- sb2 = wx.StaticBox(panel, label=" Clé de tatouage :") boxsizer = wx.StaticBoxSizer(sb2, wx.VERTICAL) self.cle = wx.TextCtrl(panel, size=(270,100), style=wx.TE_MULTILINE) self.cle.SetValue("") boxsizer.Add(self.cle, 22, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL,4) vbox.Add(boxsizer, 1, wx.EXPAND|wx.ALL, 1) #---------------------------------------- sb3 = wx.StaticBox(panel, label=" Appliquer sur :") boxsizer = wx.StaticBoxSizer(sb3, wx.VERTICAL) tmp = ["Un morceau de la carte", "Carte Complète"] self.tatouer = wx.RadioBox(panel, label='', choices = tmp, majorDimension=1, style=wx.RA_SPECIFY_ROWS) boxsizer.Add(self.tatouer,flag=wx.RIGHT, border=5) vbox.Add(boxsizer, 1, wx.EXPAND|wx.ALL, 1) #----------------------------------------------- hbox4 = wx.BoxSizer(wx.HORIZONTAL) help_btn = wx.Button(panel,1, label='Help') ok_btn = wx.Button(panel, 2,label = "Ok") cancel_btn= wx.Button(panel,3, label="Cancel") self.Bind (wx.EVT_BUTTON, self.OnHelp, id=1) self.Bind (wx.EVT_BUTTON, self.OnOk, id=2) self.Bind (wx.EVT_BUTTON, self.OnCancel, id=3) hbox4.Add(help_btn, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL, 9) hbox4.Add(cancel_btn, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL, 9) hbox4.Add(ok_btn, 1, wx.EXPAND|wx.ALIGN_LEFT|wx.ALL, 9) vbox.Add(hbox4, 1, wx.EXPAND|wx.ALL, 1) panel.SetSizer(vbox) def OnOk(self, event): if not __champ_valide__(self.nbre_partie.GetValue()): dial = wx.MessageDialog(None,"Nombre de parties doit etre un Entier positif", 'Error',wx.ICON_ERROR) ret = dial.ShowModal() if ret == wx.ID_YES: self.Destroy() return if self.cle.GetValue() == "": dial = wx.MessageDialog(None, "Valeur de Cle abscente ", 'Error',wx.ICON_ERROR) ret = dial.ShowModal() if ret == wx.ID_YES: self.Destroy() return self.GetParent().leftpanel.echelle_label.SetLabelText(" Echelle = 1/"+str(self.echelle.GetValue())) self.GetParent().leftpanel.perte_precision_label.SetLabelText(" Delta = "+str(self.perte_precision.GetValue())) self.GetParent().leftpanel.nbre_partie_label.SetLabelText(" Nombre de parties = "+str(self.nbre_partie.GetValue())) self.GetParent().leftpanel.cle_label.SetValue(str(self.cle.GetValue())) self.GetParent().leftpanel.cle_label.SetEditable(False) self.GetParent().leftpanel.lancer_tatouage_btn.Enable() self.GetParent().leftpanel.lancer_detection_btn.Enable() # ici, ca dépent il veut vérifier si la carte est tatoué ou non sans faire passé par un tatouage Reglage.echelle = self.echelle.GetValue() Reglage.perte_precision = self.perte_precision.GetValue() Reglage.perte_precision_unite = self.rbox.GetStringSelection() Reglage.nbre_partie = self.nbre_partie.GetValue() Reglage.cle = self.cle.GetValue() Reglage.tatouer = self.tatouer.GetStringSelection() Reglage.reglage_done = True self.Close() def OnHelp(self, event): try : import webbrowser webbrowser.open_new_tab('aide.html') except : pass def OnCancel(self, event): self.Close()
class TransformDialog(wx.Dialog): def __init__(self, parent, name, selected, bone_list, *args, **kw): super().__init__(parent, *args, **kw) self.selected = selected self.SetTitle("Set {} for Animation".format(name)) grid_sizer = wx.FlexGridSizer(rows=4, cols=2, hgap=10, vgap=10) if bone_list: self.bone_list = wx.Choice(self, -1, choices=bone_list) for i, bone_name in enumerate(bone_list): if 'b_c_base' in bone_name.lower(): self.bone_list.Select(i) break else: self.bone_list.Select(0) grid_sizer.Add(wx.StaticText(self, -1, 'Bone'), 0, wx.CENTER) grid_sizer.Add(self.bone_list, 0, wx.ALIGN_RIGHT) else: self.bone_list = None grid_sizer.Add(wx.StaticText(self, -1, f'X {name}'), 0, wx.CENTER) self.ctrl_x = FloatSpin(self, -1, increment=0.01, value=0.0, digits=8, size=(150, -1)) grid_sizer.Add(self.ctrl_x, 0, wx.ALIGN_RIGHT) grid_sizer.Add(wx.StaticText(self, -1, f'Y {name}'), 0, wx.CENTER) self.ctrl_y = FloatSpin(self, -1, increment=0.01, value=0.0, digits=8, size=(150, -1)) grid_sizer.Add(self.ctrl_y, 0, wx.ALIGN_RIGHT) grid_sizer.Add(wx.StaticText(self, -1, f'Z {name}'), 0, wx.CENTER) self.ctrl_z = FloatSpin(self, -1, increment=0.01, value=0.0, digits=8, size=(150, -1)) grid_sizer.Add(self.ctrl_z, 0, wx.ALIGN_RIGHT) ok_button = wx.Button(self, wx.ID_OK, "Ok") ok_button.SetDefault() cancel_button = wx.Button(self, wx.ID_CANCEL, "Cancel") hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(grid_sizer, 1, wx.ALL, 10) button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(ok_button, 0, wx.LEFT | wx.RIGHT, 2) button_sizer.Add(cancel_button, 0, wx.LEFT | wx.RIGHT, 5) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(hsizer, 1, wx.ALL, 10) sizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.ALL, 10) sizer.Add(button_sizer, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10) self.Bind(wx.EVT_BUTTON, self.on_close) self.ctrl_x.SetFocus() self.SetSizer(sizer) sizer.Fit(self) self.Layout() def on_close(self, e): if e.GetId() == wx.ID_OK and self.bone_list and self.bone_list.GetSelection() == wx.NOT_FOUND: with wx.MessageDialog(self, " No Bone Selected", "Warning", wx.OK) as dlg: dlg.ShowModal() # Shows it return e.Skip() def GetBoneIndex(self): if not self.bone_list: return wx.NOT_FOUND return self.bone_list.GetSelection() def GetValues(self): return self.ctrl_x.GetValue(), self.ctrl_y.GetValue(), self.ctrl_z.GetValue()
class arrayFloat: def __init__(self, parent, parameter): self.parent = parent # obtain the paramter to edit self.parameter = parameter paramName = self.parameter.getName() paramType = self.parameter.getType() paramUnit = self.parameter.getUnit() # construct the parameter controls self.parNameLabel = wx.Button(parent.PNL_PARAM_EDIT, label=(paramName + '\n in ' + paramUnit)) self.parValueCtrlFromLabel = wx.StaticText(parent.PNL_PARAM_EDIT, label="From:") self.parValueCtrlFrom = FloatSpin(parent.PNL_PARAM_EDIT) self.parValueCtrlToLabel = wx.StaticText(parent.PNL_PARAM_EDIT, label="To:") self.parValueCtrlTo = FloatSpin(parent.PNL_PARAM_EDIT) self.parValueCtrlPointsLabel = wx.StaticText(parent.PNL_PARAM_EDIT, label="Points:") self.parValueCtrlPoints = wx.SpinCtrl(parent.PNL_PARAM_EDIT) self.parValueCtrlPoints.SetRange(int(2), int(9999)) self.parValueCtrlScale = wx.Choice(parent.PNL_PARAM_EDIT) self.parValueCtrlScale.AppendItems( ['linear scale', 'log10 scale', 'arbitrary array']) self.parValueCtrlScale.Select(0) self.parValueCtrlResetArray = wx.Button(parent.PNL_PARAM_EDIT, label="Reset") self.parValueCtrlAppendArray = wx.Button(parent.PNL_PARAM_EDIT, label="Append") #self.parTypeLabel = wx.StaticText(parent.PNL_PARAM_EDIT, label=paramType[0]) # get parameter limits # setup the limits and value for the float control [upperLimit, lowerLimit, allowedList] = self.parameter.getLimits() self.paramValue = self.parameter.getValue() if self.paramValue == None: self.paramValue = numpy.array([]) # creates an empty array # setup the bounds for the controls for control in [self.parValueCtrlFrom, self.parValueCtrlTo]: control.SetRange(lowerLimit, upperLimit) control.SetFormat(fmt='%e') control.SetDigits(digits=4) try: increment = (upperLimit - lowerLimit) / 10.0 control.SetIncrement(increment) except: increment = 1 # cerate sizers self.HorizontalOneParam = wx.BoxSizer(wx.HORIZONTAL) self.HorizontalUpper = wx.BoxSizer(wx.HORIZONTAL) self.HorizontalLower = wx.BoxSizer(wx.HORIZONTAL) self.VerticalParam = wx.BoxSizer(wx.VERTICAL) self.VerticalButtons = wx.BoxSizer(wx.VERTICAL) # fill upper H sizer self.HorizontalUpper.Add(self.parValueCtrlFromLabel, 0, wx.ALL, 5) self.HorizontalUpper.Add(self.parValueCtrlFrom, 1, wx.ALL | wx.EXPAND, 5) self.HorizontalUpper.Add(self.parValueCtrlToLabel, 0, wx.ALL, 5) self.HorizontalUpper.Add(self.parValueCtrlTo, 1, wx.ALL | wx.EXPAND, 5) # fill lower H sizzer self.HorizontalLower.Add(self.parValueCtrlPointsLabel, 0, wx.ALL, 5) self.HorizontalLower.Add(self.parValueCtrlPoints, 0, wx.ALL, 5) self.HorizontalLower.Add(self.parValueCtrlScale, 0, wx.ALL, 5) self.VerticalButtons.Add(self.parValueCtrlResetArray, 0, wx.ALL, 5) self.VerticalButtons.Add(self.parValueCtrlAppendArray, 0, wx.ALL, 5) # add Lower and upper sizer to single sizer self.VerticalParam.Add(self.HorizontalUpper, 0, wx.LEFT) self.VerticalParam.Add(self.HorizontalLower, 0, wx.LEFT) # add a parameter name, controls and typename #self.HorizontalOneParam.Add(self.parNameLabel, 0, wx.ALL, 5) self.HorizontalOneParam.Add( wx.StaticLine(parent.PNL_PARAM_EDIT, style=wx.LI_VERTICAL), 0, wx.ALL | wx.EXPAND, 5) self.HorizontalOneParam.Add(self.VerticalParam, 0, wx.LEFT) self.HorizontalOneParam.Add( wx.StaticLine(parent.PNL_PARAM_EDIT, style=wx.LI_VERTICAL), 0, wx.ALL | wx.EXPAND, 5) self.HorizontalOneParam.Add(self.VerticalButtons, 0, wx.LEFT) # add the controls to global parameters sizer parent.paramVSizer.Add(self.parNameLabel, 0, wx.ALIGN_LEFT) parent.paramVSizer.Add(self.HorizontalOneParam, 0, wx.ALIGN_LEFT) # bind the actions to the Create button parent.Bind(wx.EVT_BUTTON, self.OnDescribeBTN, source=self.parNameLabel) parent.Bind(wx.EVT_BUTTON, self.OnResetArrayBtn, source=self.parValueCtrlResetArray) parent.Bind(wx.EVT_BUTTON, self.OnAppendArrayBtn, source=self.parValueCtrlAppendArray) return def _get_array(self): paramFrom = self.parValueCtrlFrom.GetValue() paramTo = self.parValueCtrlTo.GetValue() paramPoints = self.parValueCtrlPoints.GetValue() scale = self.parValueCtrlScale.GetSelection() testArray = None # if nothing gets createds if scale == 0: # linear scale demanded testArray = numpy.linspace(paramFrom, paramTo, paramPoints) if scale == 1: # log scale demanded if (paramFrom * paramTo ) > 0: # both parameters either positive or negative signFrom = paramFrom / abs(paramFrom) testArray = numpy.logspace(numpy.log10(paramFrom), numpy.log10(paramTo), paramPoints) else: testArray = None if scale == 2: # arbitrary array edit testArray = None return testArray def OnResetArrayBtn(self, event): """ Construct a new array from the parameters """ #[paramFrom, paramTo, paramPoints, scale] = self._get_boundaries() testArray = self._get_array() if testArray == None: self.parent._update_description_box("Wrong array creation values") else: # append the array to the already self.paramValue = testArray # update the parameter object: answer = self.parameter.setValue(self.paramValue) if answer: self.parent._update_description_box(answer) self.parent._update_description_box(( 'Parameter "%(name)s" updated to the following array (in %(unit)s)\n%(value)s' % \ {'name':self.parameter.getName(), 'value':str(self.parameter.getValue()), 'unit':self.parameter.getUnit() })) return def OnAppendArrayBtn(self, event): """ Construct a new array from the parameters and append it to the end of previously created """ testArray = self._get_array() if testArray == None: self.parent._update_description_box( "Array not appended, wrong parameters") else: # append the array to the already self.paramValue = numpy.hstack([self.paramValue, testArray]) answer = self.parameter.setValue(self.paramValue) if answer: self.parent._update_description_box(answer) self.parent._update_description_box(( 'Parameter "%(name)s" updated to the following array (in %(unit)s)\n%(value)s' % \ {'name':self.parameter.getName(), 'value':str(self.parameter.getValue()), 'unit':self.parameter.getUnit() })) return def OnDescribeBTN(self, event): """ Gives hint about the parameter """ parDescribe = self.parameter.getDescription() self.parent._update_description_box(parDescribe) return
class singleFloat: def __init__(self, parent, parameter): self.parent = parent self.HorizontalOneParam = wx.BoxSizer(wx.HORIZONTAL) self.parameter = parameter paramName = self.parameter.getName() paramType = self.parameter.getType() paramUnit = self.parameter.getUnit() self.parNameLabel = wx.Button(parent.PNL_PARAM_EDIT, label=(paramName + '\n in ' + paramUnit)) self.parValueCtrl = FloatSpin(parent.PNL_PARAM_EDIT) # setup the limits and value for the float control [upperLimit, lowerLimit, allowedList] = self.parameter.getLimits() self.parValueCtrl.SetRange(lowerLimit, upperLimit) self.parValueCtrl.SetFormat(fmt='%e') self.parValueCtrl.SetDigits(digits=3) paramValue = self.parameter.getValue() if not paramValue == None: self.parValueCtrl.SetValue(paramValue) try: increment = (upperLimit - lowerLimit) / 10.0 except: increment = 1 self.parValueCtrl.SetIncrement(increment) # setup the limits and value for the float control if there is list of allowed values if not allowedList == None: self.parValueCtrl.Destroy() self.parValueCtrl = wx.Choice(parent.PNL_PARAM_EDIT) for value in allowedList: item = ('%8.3e' % value) self.parValueCtrl.Append(item) paramValue = self.parameter.getValue() paramValueItem = ('%8.3e' % paramValue) #print paramValueItem if not paramValue == None: idXDefault = self.parValueCtrl.FindString(paramValueItem) self.parValueCtrl.Select(idXDefault) else: self.parValueCtrl.Select(0) #self.parTypeLabel = wx.StaticText(parent.PNL_PARAM_EDIT, label=paramType[0]) #self.HorizontalOneParam.Add(self.parNameLabel, 0, wx.ALL, 5) self.HorizontalOneParam.Add( wx.StaticLine(parent.PNL_PARAM_EDIT, style=wx.LI_VERTICAL), 0, wx.ALL | wx.EXPAND, 5) self.HorizontalOneParam.Add(self.parValueCtrl, 1, wx.ALL | wx.EXPAND, 5) #self.HorizontalOneParam.Add(self.parTypeLabel,0, wx.ALL, 5) parent.paramVSizer.Add(self.parNameLabel, 0, wx.ALIGN_LEFT) parent.paramVSizer.Add(self.HorizontalOneParam, 0, wx.ALIGN_LEFT) # binding events parent.Bind(wx.EVT_BUTTON, self.OnDescribeBTN, source=self.parNameLabel) # decire if it is an choice or it is FloatSpin try: self.parValueCtrl.GetSelection() parent.Bind(wx.EVT_CHOICE, self.OnEditParam, source=self.parValueCtrl) except: self.parValueCtrl.Bind(EVT_FLOATSPIN, self.OnEditParam, source=self.parValueCtrl) return def OnEditParam(self, event): """ Update the given parameter according to control """ floatValue = 'No value found' try: value = event.GetString() floatValue = float(value) except: floatValue = self.parValueCtrl.GetValue() pass #print floatValue self.parameter.setValue(floatValue) acutalValue = self.parameter.getValue() try: self.parValueCtrl.SetValue(acutalValue) except: pass self.parent._update_description_box(( 'Parameter "%(name)s" updated to %(value)s (%(unit)s)' % \ {'name':self.parameter.getName(), 'value':str(acutalValue), 'unit':self.parameter.getUnit() })) return def OnDescribeBTN(self, event): """ Gives hint about the parameter """ parDescribe = self.parameter.getDescription() self.parent._update_description_box(parDescribe)
class PageOne(wx.Panel): def __init__(self, parent, hw_ver, frame): self.frame = frame self.multiplier_list = [1, 2, 4, 5, 8, 10, 16, 20] wx.Panel.__init__(self, parent) self.hw_ver = hw_ver main_sizer = wx.BoxSizer(wx.HORIZONTAL) grid = wx.GridBagSizer(hgap=5, vgap=5) grid_2 = wx.GridBagSizer(hgap=5, vgap=5) horizontal_sizer_2 = wx.BoxSizer(wx.HORIZONTAL) horizontal_sizer = wx.BoxSizer(wx.VERTICAL) plot_sizer = wx.BoxSizer(wx.VERTICAL) self.input_label = wx.StaticBox(self, -1, 'Analog input') self.input_sizer = wx.StaticBoxSizer(self.input_label, wx.HORIZONTAL) self.sample_list = [] for i in range(1, 9): self.sample_list.append("A" + str(i)) self.label_ch_1 = wx.StaticText(self, label="Ch+") grid.Add(self.label_ch_1, pos=(0, 0)) self.edit_ch_1 = wx.ComboBox(self, size=(95, -1), choices=self.sample_list, style=wx.CB_READONLY) self.edit_ch_1.SetSelection(0) grid.Add(self.edit_ch_1, pos=(0, 1)) if self.hw_ver == 1: self.sample_list = ("AGND", "VREF", "A5", "A6", "A7", "A8") else: if self.hw_ver == 2: self.sample_list = ("AGND", "A2") self.label_ch_2 = wx.StaticText(self, label="Ch-") grid.Add(self.label_ch_2, pos=(1, 0)) self.edit_ch_2 = wx.ComboBox(self, size=(95, -1), choices=self.sample_list, style=wx.CB_READONLY) self.edit_ch_2.SetSelection(0) grid.Add(self.edit_ch_2, pos=(1, 1)) self.Bind(wx.EVT_COMBOBOX, self.edit_ch_1_change, self.edit_ch_1) self.Bind(wx.EVT_COMBOBOX, self.edit_ch_2_change, self.edit_ch_2) if self.hw_ver == 1: self.sample_list = ("+-12 V", "+-4 V", "+-2 V", "+-0.4 V", "+-0.04 V") self.label_range = wx.StaticText(self, label="Range") else: if self.hw_ver == 2: self.sample_list = ("x1", "x2", "x4", "x5", "x8", "x10", "x16", "x20") self.label_range = wx.StaticText(self, label="Multiplier") grid.Add(self.label_range, pos=(2, 0)) self.edit_range = wx.ComboBox(self, size=(95, -1), choices=self.sample_list, style=wx.CB_READONLY) self.edit_range.SetSelection(0) grid.Add(self.edit_range, pos=(2, 1)) if self.hw_ver == 2: self.edit_range.Enable(False) self.label_rate = wx.StaticText(self, label="Rate(s)") grid.Add(self.label_rate, pos=(3, 0)) self.edit_rate = (FloatSpin(self, value=1, min_val=0.1, max_val=65.535, increment=0.1, digits=1)) grid.Add(self.edit_rate, pos=(3, 1)) self.button_play = wx.Button(self, label="Play", size=(95, 25)) self.Bind(wx.EVT_BUTTON, self.play_event, self.button_play) self.button_stop = wx.Button(self, label="Stop", size=(95, 25)) self.Bind(wx.EVT_BUTTON, self.stop_event, self.button_stop) self.button_stop.Enable(False) grid.Add(self.button_play, pos=(4, 0)) grid.Add(self.button_stop, pos=(4, 1)) self.label_value = wx.StaticText(self, label="Last value (V)") grid.Add(self.label_value, pos=(5, 0)) self.input_value = wx.TextCtrl(self, style=wx.TE_READONLY, size=(95, 25)) grid.Add(self.input_value, pos=(5, 1)) self.input_sizer.Add(grid, 0, wx.ALL, border=10) self.output_label = wx.StaticBox(self, -1, 'Analog output') self.output_sizer = wx.StaticBoxSizer(self.output_label, wx.HORIZONTAL) if hw_ver == 1: self.edit_value = FloatSpin(self, value=0, min_val=-4.0, max_val=4.0, increment=0.1, digits=3) elif hw_ver == 2: self.edit_value = FloatSpin(self, value=0, min_val=0, max_val=4.0, increment=0.1, digits=3) self.Bind(wx.lib.agw.floatspin.EVT_FLOATSPIN, self.slider_change, self.edit_value) self.lblDAC = wx.StaticText(self, label="DAC value (V)") grid_2.Add(self.lblDAC, pos=(0, 0)) grid_2.Add(self.edit_value, pos=(0, 3)) self.output_sizer.Add(grid_2, 0, wx.ALL, border=10) self.export_label = wx.StaticBox(self, -1, 'Export') self.export_sizer = wx.StaticBoxSizer(self.export_label, wx.HORIZONTAL) self.png = wx.Button(self, label="As PNG file...", size=(98, 25)) self.Bind(wx.EVT_BUTTON, self.save_as_png_event, self.png) self.csv = wx.Button(self, label="As CSV file...", size=(98, 25)) self.Bind(wx.EVT_BUTTON, self.save_as_csv_event, self.csv) horizontal_sizer_2.Add(self.png, 0, wx.ALL) horizontal_sizer_2.Add(self.csv, 0, wx.ALL) self.export_sizer.Add(horizontal_sizer_2, 0, wx.ALL, border=10) self.figure = Figure(facecolor='#ece9d8') self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.axes.set_xlabel("Time (s)", fontsize=12) self.axes.set_ylabel("Voltage (mV)", fontsize=12) self.canvas.SetInitialSize(size=(600, 600)) self.add_toolbar() self.cidUpdate = self.canvas.mpl_connect('motion_notify_event', self.UpdateStatusBar) plot_sizer.Add(self.toolbar, 0, wx.CENTER) plot_sizer.Add(self.canvas, 0, wx.ALL) horizontal_sizer.Add(self.input_sizer, 0, wx.CENTRE) horizontal_sizer.Add(self.output_sizer, 0, wx.EXPAND) horizontal_sizer.Add(self.export_sizer, 0, wx.EXPAND) main_sizer.Add(horizontal_sizer, 0, wx.ALL, border=10) main_sizer.Add(plot_sizer, 0, wx.ALL) self.SetSizerAndFit(main_sizer) self.data_packet = [] self.x = [] self.y = [] # Create a publisher receiver pub.subscribe(self.new_data, "newdata") pub.subscribe(self.clear_canvas, "clearcanvas") def new_data(self, msg): data = msg.data if isinstance(msg.data, float): self.input_value.Clear() self.input_value.AppendText(str(data)) if (self.toolbar.mode == "pan/zoom"): return if (self.toolbar.mode == "zoom rect"): return self.canvas.mpl_disconnect(self.frame.page_1.cidUpdate) self.axes.cla() self.axes.grid(color='gray', linestyle='dashed') self.axes.plot(self.y, self.x) self.canvas.draw() self.cidUpdate = self.frame.page_1.canvas.mpl_connect( 'motion_notify_event', self.frame.page_1.UpdateStatusBar) def clear_canvas(self, msg): self.input_value.Clear() self.axes.cla() self.axes.grid(color='gray', linestyle='dashed') self.axes.plot(self.y, self.x) self.canvas.draw() def UpdateStatusBar(self, event): if event.inaxes: x, y = event.xdata, event.ydata self.frame.status_bar.SetStatusText( ("x= " + "%.4g" % x + " y=" + "%.4g" % y), 1) def add_toolbar(self): self.toolbar = MyCustomToolbar(self.canvas) self.toolbar.Realize() # On Windows platform, default window size is incorrect, so set # toolbar width to figure width. tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version. # As noted above, doesn't work for Mac. self.toolbar.SetSize(wx.Size(fw, th)) #self.main_sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) # update the axes menu on the toolbar self.toolbar.update() def save_as_png_event(self, event): self.directory_name = '' dlg = wx.FileDialog(self, "Choose a file", self.directory_name, "", "*.png", wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.file_name = dlg.GetFilename() self.directory_name = dlg.GetDirectory() self.figure.savefig(self.directory_name + "\\" + self.file_name) dlg.Destroy() def save_as_csv_event(self, event): self.directory_name = '' dlg = wx.FileDialog(self, "Choose a file", self.directory_name, "", "*.odq", wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.file_name = dlg.GetFilename() self.directory_name = dlg.GetDirectory() with open(self.directory_name + "\\" + self.file_name, 'wb') as file: spamwriter = csv.writer(file, quoting=csv.QUOTE_MINIMAL) for i in range(len(self.frame.comunication_thread.data)): spamwriter.writerow([ self.frame.comunication_thread.x[i], self.frame.comunication_thread.y[i] ]) dlg.Destroy() def zoom_up(self, event): pass def play_event(self, event): self.data_packet = [] self.x = [] self.y = [] self.ch_1 = self.edit_ch_1.GetCurrentSelection() self.ch_2 = self.edit_ch_2.GetCurrentSelection() self.range = self.edit_range.GetCurrentSelection() self.rate = self.edit_rate.GetValue() * 1000 self.edit_rate.SetValue(self.edit_rate.GetValue()) self.edit_value.SetValue(self.edit_value.GetValue()) if self.ch_1 == -1: self.frame.show_error_parameters() return if self.ch_2 == -1: self.frame.show_error_parameters() return if self.range == -1: self.frame.show_error_parameters() return if self.hw_ver == 2 and self.ch_2 == 1: self.ch_2 = self.edit_ch_2.GetValue() self.ch_2 = self.ch_2[1] if self.hw_ver == 1: if self.ch_2 == 1: self.ch_2 = 25 elif self.ch_2 > 1: self.ch_2 += 3 self.frame.comunication_thread.config(self.ch_1, int(self.ch_2), self.range, self.rate) self.button_play.Enable(False) self.button_stop.Enable(True) self.edit_ch_1.Enable(False) self.edit_ch_2.Enable(False) self.edit_range.Enable(False) self.edit_rate.Enable(False) self.frame.daq.set_led(3) wx.CallAfter(pub.sendMessage, "clearcanvas", None) if self.frame.comunication_thread.is_alive(): self.frame.comunication_thread.restart() else: self.frame.comunication_thread.start() self.frame.comunication_thread.stop() self.play_event(0) def stop_event(self, event): self.button_play.Enable(True) self.button_stop.Enable(False) self.edit_ch_1.Enable(True) self.edit_ch_2.Enable(True) self.edit_rate.Enable(True) if (self.hw_ver == 1 or (self.hw_ver == 2 and self.edit_ch_2.GetValue() != "AGND")): self.edit_range.Enable(True) self.frame.daq.set_led(1) self.frame.comunication_thread.stop() def slider_change(self, event): dac_value = self.edit_value.GetValue() self.frame.daq.set_analog(dac_value) def edit_ch_1_change(self, event): if self.hw_ver == 1: return value = self.edit_ch_1.GetValue() self.edit_ch_2.Clear() self.edit_ch_2.Append("AGND") if (int(value[1]) % 2) == 0: self.edit_ch_2.Append("A" + str(int(value[1]) - 1)) else: self.edit_ch_2.Append("A" + str(int(value[1]) + 1)) self.edit_ch_2.SetSelection(0) self.edit_range.SetSelection(0) self.edit_range.Enable(False) def edit_ch_2_change(self, event): if self.hw_ver == 1: return if self.edit_ch_2.GetValue() == "AGND": self.edit_range.Enable(False) self.edit_range.SetSelection(0) else: self.edit_range.Enable(True)