def on_search_in_DB(self): a = P4Rm() temp = [] test = [] test = [RadMaxData.exp_name, RadMaxData.crys_name, RadMaxData.geometry, RadMaxData.model, RadMaxData.date] for i in range(len(a.DBDict["choice_combo"])): if not a.DBDict["choice_combo"][i] is None: if a.DBDict["choice_combo"][i] == "equal": the_day = datetime.strptime(a.DBDict["date_1"], "%Y-%m-%d %H:%M:%S") next_day = the_day + timedelta(days=1) next_day = "{:%Y-%m-%d %H:%M:%S}".format(next_day) temp.append(test[i] >= a.DBDict["date_1"]) temp.append(test[i] <= next_day) elif a.DBDict["choice_combo"][i] == "=<": temp.append(test[i] <= a.DBDict["date_1"]) elif a.DBDict["choice_combo"][i] == ">=": temp.append(test[i] >= a.DBDict["date_1"]) elif a.DBDict["choice_combo"][i] == "between": temp.append(test[i] >= a.DBDict["date_1"]) temp.append(test[i] <= a.DBDict["date_2"]) else: temp.append(test[i] == a.DBDict["choice_combo"][i]) s = a.DBDict["session"].query(RadMaxData).filter(*temp).all() if a.DBDict["choice_state"]: self.on_read_database_and_fill_list(s) else: [a.DBDict["session"].delete(x) for x in s] pub.sendMessage(pubsub_sup_data_DB)
def TagAsReference(self, position, state=True): """ Tag/Untag selected item as reference. Parameters: position - item position (int) state - state (bool) """ if state: if not(hasattr(self,"canvas")): pub.sendMessage("request_canvas") if self.canvas.CurrentPage.is_filter: # check if a reference exists in current filter bank for n in range(self.list.GetItemCount()): if self.list.IsReference(n): if self.canvas.CurrentPage.bank in self.list.GetReferenceBank(n): self.list.ClearReference(n) self.list.SetItemImage(n,1) # set reference to given position self.list.SetReference(position, self.canvas.CurrentPage.bank) self.list.SetItemImage(position,4) else: self.list.ClearReference(position) self.list.SetItemImage(position,1)
def OnComboBrushOp(self, evt): brush_op_id = evt.GetSelection() Publisher.sendMessage('Set edition operation', brush_op_id) if brush_op_id == const.BRUSH_THRESH: self.gradient_thresh.Enable() else: self.gradient_thresh.Disable()
def LoadParamObj(self, pubsub_evt): coil_orient, self.coil_axis = self.dialog.GetValue self.showObj.SetValue(True) self.angle_tracking() Publisher.sendMessage('Track Coil Angle', (self.coil_axis, self.ap_axis)) Publisher.sendMessage('Change Init Coil Angle', coil_orient)
def OnRightClick(self, event = None): """ Actions triggered by right click on list item. Parameters: event - wx.Event """ # show menu if event.GetEventType() == wx.EVT_RIGHT_DOWN.evtType[0]: if self.list.HitTest(event.GetPosition())[0]>-1: # right click on a history item => handled by specific event event.Skip() return else: # right click in list but not on list entry => only Load available menu = wx.Menu() itm = menu.Append(wx.NewId(), "&Load scan") self.Bind(wx.EVT_MENU, self.OnLoad, id=itm.Id) self.PopupMenu(menu) return # right click on list item menu = wx.Menu() itm = menu.Append(wx.NewId(), "&Load scan") self.Bind(wx.EVT_MENU, self.OnLoad, id=itm.Id) if event.GetIndex()>-1: arr = self.list.GetItemPyData(event.GetIndex()) # create menu entries for operations on item itm = menu.Append(wx.NewId(), "&Rename") self.Bind(wx.EVT_MENU, lambda x: self.list.EditLabel(event.GetIndex()), id=itm.Id) itm = menu.Append(wx.NewId(), "&Delete") self.Bind(wx.EVT_MENU, lambda x: self.Delete(event.GetIndex()), id=itm.Id) itm = menu.Append(wx.NewId(), "&Save as...") self.Bind(wx.EVT_MENU, lambda x: self.SaveAs(event.GetIndex()), id=itm.Id) # if array has a xml image of event tree, propose reload if hasattr(arr,'xml'): itm = menu.Append(wx.NewId(),"Reload event tree") self.Bind(wx.EVT_MENU, lambda x: pub.sendMessage("history.reload_events", string=arr.xml), id=itm.Id) # specific menu entries for 1D plot if len(arr.shape) == 1: itm = menu.Append(wx.NewId(), "Change c&olor") self.Bind(wx.EVT_MENU, lambda x: self.ChangeColour(event.GetIndex()), id=itm.Id) if arr.color!=None: itm = menu.Append(wx.NewId(), "Reset c&olor") self.Bind(wx.EVT_MENU, lambda x: self.ResetColour(event.GetIndex()), id=itm.Id) if not(hasattr(self,"window")): pub.sendMessage("request_top_window") if not(self.window.is_scanning) or event.GetIndex()>0: if not(hasattr(self,"canvas")): pub.sendMessage("request_canvas") if self.list.IsReference(event.GetIndex()): itm = menu.Append(wx.NewId(), "&Clear reference") self.Bind(wx.EVT_MENU, self.ClearReference, id=itm.Id) if self.canvas.CurrentPage!=None: if self.canvas.CurrentPage.is_filter: itm = menu.Append(wx.NewId(), "S&et as reference") self.Bind(wx.EVT_MENU, lambda x: self.SetReference(event.GetIndex()), id=itm.Id) self.PopupMenu(menu)
def OnButtonNextTask(self, evt): overwrite = self.check_box.IsChecked() algorithm = 'Default' options = {} to_generate = True if self.GetMaskSelected() != -1: sl = slice_.Slice() if sl.current_mask.was_edited: dlgs = dlg.SurfaceDialog() if dlgs.ShowModal() == wx.ID_OK: algorithm = dlgs.GetAlgorithmSelected() options = dlgs.GetOptions() else: to_generate = False dlgs.Destroy() if to_generate: mask_index = sl.current_mask.index method = {'algorithm': algorithm, 'options': options} srf_options = {"index": mask_index, "name": '', "quality": _('Optimal *'), "fill": False, "keep_largest": False, "overwrite": overwrite} Publisher.sendMessage('Create surface from index', {'method': method, 'options': srf_options}) Publisher.sendMessage('Fold surface task') else: dlg.InexistentMask()
def OnSlideChanging(self, evt): thresh_min = self.gradient.GetMinValue() thresh_max = self.gradient.GetMaxValue() Publisher.sendMessage('Changing threshold values', (thresh_min, thresh_max)) session = ses.Session() session.ChangeProject()
def UpdateSurfaceInterpolation(self, pub_evt): interpolation = int(ses.Session().surface_interpolation) key_actors = self.actors_dict.keys() for key in self.actors_dict: self.actors_dict[key].GetProperty().SetInterpolation(interpolation) Publisher.sendMessage('Render volume viewer')
def StartImportPanel(self, path): # retrieve DICOM files splited into groups reader = dcm.ProgressDicomReader() reader.SetWindowEvent(self.frame) reader.SetDirectoryPath(path) Publisher.sendMessage('End busy cursor')
def relayEvent(self): if self.selectedBrand and self.selectedMaterial is not None: self.chosenProfilePath = self.materialsDict.setdefault(self.selectedBrand, self.selectedMaterial)[self.selectedMaterial] try: pub.sendMessage('matProf.update', path=self.chosenProfilePath) except Exception as e: print "ERROR: ", e
def onOpenProcessed(self,evt): """Function for meuitem open processed Read the *.npz files in a directory and converts to a video""" dlg = wx.DirDialog(self,"Choose a Directory") if dlg.ShowModal() == wx.ID_OK: dirpath = dlg.GetPath() procVid = ProcessedVideo.ProcessedVideo(path=dirpath) self.dirname = dirpath if self.procFilename: pathbits = dirpath.split(os.sep) self.vidid = pathbits[-1] self.testid = pathbits[-2] self.subjectid = pathbits[-3] #fname,ext = os.path.splitext(filename) #self.filename = fname newVid = AOVideo.AOVideo(frameheight = procVid.frameheight, framewidth = procVid.framewidth) for frame in procVid: newVid.addFrame(frame) self._video = newVid self._video.currentframeidx = 0 self.videoControls.maxval = self._video.framecount self.videoControls.curval = self._video.currentframeidx pub.sendMessage('max_frame_count',data=self._video.framecount) self.image.reset() self.UpdateDisplay()
def updatePrice(self, message): if self.bdmReady: self.lock.acquire() bond = message.data.name idx = (self.th.positionsByISINBook['Bond'] == bond) if idx.sum()>0: price = message.data['MID'] self.th.positionsByISINBook.loc[idx,'PriceT'] = price self.th.positionsByISINBook.loc[idx,'SODPnL'] = self.th.positionsByISINBook.loc[idx,'SOD_Pos'] * self.bdm.df.loc[bond,'PRINCIPAL_FACTOR'] * (price - self.th.positionsByISINBook.loc[idx,'PriceY'])/100. self.th.positionsByISINBook.loc[idx,'SODPnL'].fillna(0, inplace=True) fx = ccy.at[bonds.at[bond,'CRNCY'],'2016'] if bond in self.new_trades['Bond'].values: for (k,grp) in self.positionDeltas: isin = k[1] try: if allisins[isin] == bond:#grp['Qty'].sum()!=0 idx = (self.new_trades['ISIN'] == isin) & (self.new_trades['Book'] == k[0]) self.new_trades.loc[idx,'TradePnL'] = self.new_trades.loc[idx,'Qty']*(price-self.new_trades.loc[idx,'Price'])/100. self.th.positionsByISINBook.at[k[0]+'-'+k[1],'TradePnL'] = self.th.positionsByISINBook.at[k[0]+'-'+k[1],'PRINCIPAL_FACTOR'] * self.new_trades.loc[idx,'TradePnL'].sum() except: #bond is dummy pass ######## bondlines = (self.th.positionsByISINBook['Bond'] == bond) self.th.positionsByISINBook.loc[bondlines,'TotalPnL'] = self.th.positionsByISINBook.loc[bondlines,'SODPnL']/fx + self.th.positionsByISINBook.loc[bondlines,'TradePnL']/fx booklist = list(self.th.positionsByISINBook.loc[bondlines,'Book'].drop_duplicates()) message = BondPriceUpdateMessage(bond=bond, booklist=booklist, price=price) pub.sendMessage('RISKTREE_BOND_PRICE_UPDATE', message=message) self.lock.release() pass
def OnInsertAngularMeasurePoint(self, obj, evt): x,y = self.interactor.GetEventPosition() self.measure_picker.Pick(x, y, 0, self.ren) x, y, z = self.measure_picker.GetPickPosition() proj = prj.Project() radius = min(proj.spacing) * PROP_MEASURE if self.measure_picker.GetActor(): # if not self.measures or self.measures[-1].IsComplete(): # m = measures.AngularMeasure(self.ren) # m.AddPoint(x, y, z) # self.measures.append(m) # else: # m = self.measures[-1] # m.AddPoint(x, y, z) # if m.IsComplete(): # index = len(self.measures) - 1 # name = "M" # colour = m.colour # type_ = _("Angular") # location = u"3D" # value = u"%.2f˚"% m.GetValue() # msg = 'Update measurement info in GUI', # Publisher.sendMessage(msg, # (index, name, colour, # type_, location, # value)) Publisher.sendMessage("Add measurement point", ((x, y,z), const.ANGULAR, const.SURFACE, radius)) self.interactor.Render()
def displayData(self): #rint'panel_student_bookings : displayData' sql = "SELECT s.id , c.name, s.name , name.reg_status \ FROM students s \ JOIN courses c ON s.register_course_id = c.id \ WHERE s.register_schYr = %d" % gVar.schYr school_id = 0 if gVar.school == "CG": school_id = 1 if gVar.school == "SD": school_id = 2 if gVar.school == "SMP": school_id = 3 if gVar.school == "SMA": school_id = 4 if school_id: #rint"School" sqlSch = " AND c.school_id = %d" % school_id sql = "%s%s" % (sql, sqlSch) #sql = "%s%s" % (sql, " ORDER BY cSiswa.Kelas, cSiswa.Nama" ) results = fetch.DATA(sql) gVar.msg = " %d records found" % len(results) pub.sendMessage("change.statusbar") self.vListBookings.SetItemMap(results) self.Layout()
def Buttons(self, evt): id = evt.GetId() x, y, z = self.a if id == PR1: self.aux_plh_ref1 = 0 self.coord1b = self.Coordinates() coord = self.coord1b elif id == PR2: self.aux_plh_ref2 = 0 self.coord2b = self.Coordinates() coord = self.coord2b elif id == PR3: self.aux_plh_ref3 = 0 self.coord3b = self.Coordinates() coord = self.coord3b elif id == GetPoint: x, y, z = self.a self.numCtrl1g.SetValue(x) self.numCtrl2g.SetValue(y) self.numCtrl3g.SetValue(z) info = self.a, self.flagpoint self.SaveCoordinates(info) self.flagpoint = 1 elif id == Corregistration and self.aux_img_ref1 == 1 and self.aux_img_ref2 == 1 and self.aux_img_ref3 == 1: print "Coordenadas Imagem: ", self.coord1a, self.coord2a, self.coord3a print "Coordenadas Polhemus: ", self.coord1b, self.coord2b, self.coord3b self.M, self.q1, self.Minv = db.Bases(self.coord1a, self.coord2a, self.coord3a).Basecreation() self.N, self.q2, self.Ninv = db.Bases(self.coord1b, self.coord2b, self.coord3b).Basecreation() if self.aux_plh_ref1 == 0 or self.aux_plh_ref2 == 0 or self.aux_plh_ref3 == 0: Publisher.sendMessage('Update plh position', coord)
def OnMenuPicture(self, evt): id = evt.GetId() value = dlg.ExportPicture(self.id_to_name[id]) if value: filename, filetype = value Publisher.sendMessage('Export picture to file', (id, filename, filetype))
def OnLinkExportMask(self, evt=None): project = proj.Project() if sys.platform == 'win32': project_name = project.name else: project_name = project.name+".vti" dlg = wx.FileDialog(None, "Save mask as...", # title "", # last used directory project_name, # filename WILDCARD_SAVE_MASK, wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) dlg.SetFilterIndex(0) # default is VTI if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() extension = "vti" if sys.platform != 'win32': if filename.split(".")[-1] != extension: filename = filename + "."+ extension filetype = const.FILETYPE_IMAGEDATA Publisher.sendMessage('Export mask to file', (filename, filetype))
def UpdateProgress(obj, label=""): """ Show progress on GUI according to pipeline execution. """ # object progress is cummulative and is between 0.0 - 1.0 # is necessary verify in case is sending the progress #represented by number in case multiprocess, not vtk object if isinstance(obj, float) or isinstance(obj, int): obj_progress = obj else: obj_progress = obj.GetProgress() # as it is cummulative, we need to compute the diference, to be # appended on the interface if obj_progress < last_obj_progress[0]: # current obj != previous obj difference = obj_progress # 0 else: # current obj == previous obj difference = obj_progress - last_obj_progress[0] last_obj_progress[0] = obj_progress # final progress status value progress[0] = progress[0] + ratio*difference # Tell GUI to update progress status value if (dialog_type == "GaugeProgress"): Publisher.sendMessage('Update status in GUI', (progress[0], label)) else: if (progress[0] >= 99.999): progress[0] = 100 if not(dlg.Update(progress[0],label)): dlg.Close() return progress[0]
def OnButtonTarget(self, evt): if not self.button_target.IsPressed() and evt is not False: self.button_target._pressed = True Publisher.sendMessage('Target navigation mode', target_mode=self.button_target._pressed) elif self.button_target.IsPressed() or evt is False: self.button_target._pressed = False Publisher.sendMessage('Target navigation mode', target_mode=self.button_target._pressed)
def scale_manual(self, event, val=None): a = P4Rm() if val is not None: P4Rm.ParamDict['DW_multiplication'] = val P4Rm.ParamDict['dwp'] = multiply(a.ParamDict['dwp'], a.ParamDict['DW_multiplication']) pub.sendMessage(pubsub_Re_Read_field_paramters_panel, event=event)
def SetPlotColors(self): """ Set canvas plot colors. """ # get number of arrays with custom color Nc = 0 for x in self.plots: x.color = None if x.array!=None: if x.array.color!=None: x.color = x.array.color Nc+=1 Np = len(self.plots)-Nc np = Np-1 for x in self.plots: if x.color != None: color = x.color else: color = (1.0-(np+1.0)/(Np*1.0),0.0,(np+1.0)/(Np*1.0)) np -= 1 if x.source==None: x.SetColor(color) y = x.children while len(y)>0: for z in y: z.SetColor(color) y = y[-1].children # send color change event to notify history from change pub.sendMessage("plot.color_change")
def removeStream(self, stream): """ Removes the given stream. stream (Stream): the stream to remove Note: the stream panel is to be destroyed separately via the stream_bar It's ok to call if the stream has already been removed """ # don't schedule any more self._unscheduleStream(stream) # Remove from the views for v in self._tab_data_model.views.value: if hasattr(v, "removeStream"): v.removeStream(stream) try: self._tab_data_model.streams.value.remove(stream) except ValueError: logging.warn("Stream not found, so not removed") logging.debug("Sending stream.ctrl.removed message") pub.sendMessage('stream.ctrl.removed', streams_present=self._has_streams(), streams_visible=self._has_visible_streams(), tab=self._tab_data_model)
def _gotChooserItems(self, l): self.runChooserItems = l items = [] found = False for run in self.runChooserItems: items.append(run['nice_name']) if self.runChooserSelected and self.runChooserSelected['id'] == run['id']: found = True self.runChooser.Freeze() self.runChooser.Clear() self.runChooser.AppendItems(items) self.runChooser.Thaw() if items == []: self.runChooser.SetSelection(wx.NOT_FOUND) self.runChooserSelected = None elif not found: self.runChooser.SetSelection(0) self.runChooserSelected = self.runChooserItems[0] else: for i, e in zip(range(len(self.runChooserItems)), self.runChooserItems): if e['id'] == self.runChooserSelected['id']: self.runChooser.SetSelection(i) pub.sendMessage("run_selection_changed", run = self.runChooserSelected)
def OnFoldPressCaption(self, evt): id = evt.GetTag().GetId() closed = evt.GetFoldStatus() if self.__id_editor == id: if closed: Publisher.sendMessage('Disable style', style=const.SLICE_STATE_EDITOR) self.last_style = None else: Publisher.sendMessage('Enable style', style=const.SLICE_STATE_EDITOR) self.last_style = const.SLICE_STATE_EDITOR elif self.__id_watershed == id: if closed: Publisher.sendMessage('Disable style', style=const.SLICE_STATE_WATERSHED) self.last_style = None else: Publisher.sendMessage('Enable style', style=const.SLICE_STATE_WATERSHED) # Publisher.sendMessage('Show help message', 'Mark the object and the background') self.last_style = const.SLICE_STATE_WATERSHED else: Publisher.sendMessage('Disable style', style=const.SLICE_STATE_EDITOR) self.last_style = None evt.Skip() wx.CallAfter(self.ResizeFPB)
def set_date_bound(self, start, end): print "start:", start, end if start > self.maxStart: self.maxStart = start if end < self.maxEnd: self.maxEnd = end Publisher.sendMessage(("resetdate"), startDate=self.maxStart, endDate=self.maxEnd)
def OnOpen(self, path): fileName, fileExtension = os.path.splitext(path) self.filename = fileName+fileExtension pub.sendMessage("panelListener2", message= fileName) if fileExtension == '.xml': self.loaded = 1 self.parseXMLDocument(path)
def OnLinkNewMask(self, evt=None): try: evt.data evt = None except: pass dialog = dlg.NewMask() try: if dialog.ShowModal() == wx.ID_OK: ok = 1 else: ok = 0 except(wx._core.PyAssertionError): #TODO FIX: win64 ok = 1 if ok: mask_name, thresh, colour = dialog.GetValue() if mask_name: Publisher.sendMessage('Create new mask', mask_name=mask_name, thresh=thresh, colour=colour) dialog.Destroy()
def _onView(self, view): """ Called when the current view changes """ if not view: return # import sys # print sys.getrefcount(self) # hide/show the stream panels which are compatible with the view allowed_classes = view.stream_classes for e in self._stream_bar.stream_panels: e.Show(isinstance(e.stream, allowed_classes)) # self.Refresh() self._stream_bar._fit_streams() # update the "visible" icon of each stream panel to match the list # of streams in the view visible_streams = view.getStreams() for e in self._stream_bar.stream_panels: e.set_visible(e.stream in visible_streams) logging.debug("Sending stream.ctrl message") pub.sendMessage('stream.ctrl', streams_present=True, streams_visible=self._has_visible_streams(), tab=self._tab_data_model)
def OnEnablePlugin(self, evt=None): """Publish the enabled/disabled state of the plugin.""" item = self.tcPlugins.GetSelection() n = self.tcPlugins.GetItemData(item) plugin = self.plugins[n] p = plugin['plugin'] # Set the checkbox to the appropriate state if the event # comes from the treeview if (evt.EventType == wx.EVT_TREE_ITEM_ACTIVATED.typeId): self.checkEnabled.SetValue(not self.checkEnabled.IsChecked()) if self.checkEnabled.IsChecked(): self.tcPlugins.SetItemImage(item, 1) self.tcPlugins.SetItemTextColour(item, wx.BLACK) self.pluginsDisabled.remove(p.__name__) logger.debug("%s enabled", p.__name__) else: self.tcPlugins.SetItemImage(item, 2) self.tcPlugins.SetItemTextColour(item, wx.Colour(169, 169, 169)) self.pluginsDisabled.add(p.__name__) logger.debug("%s disabled", p.__name__) pub.sendMessage('preferences.updated.value', msg={'general.plugins.disabled_list': list(self.pluginsDisabled)})
def clear(self): """ Remove all the streams (from the model and the GUI) """ # We could go for each stream panel, and call removeStream(), but it's # as simple to reset all the lists # clear the graphical part while self._stream_bar.stream_panels: spanel = self._stream_bar.stream_panels[0] self._stream_bar.remove_stream_panel(spanel) # clear the interface model # (should handle cases where a new stream is added simultaneously) while self._tab_data_model.streams.value: stream = self._tab_data_model.streams.value.pop() self._unscheduleStream(stream) # Remove from the views for v in self._tab_data_model.views.value: if hasattr(v, "removeStream"): v.removeStream(stream) if self._has_streams() or self._has_visible_streams(): logging.warning("Failed to remove all streams") logging.debug("Sending stream.ctrl.removed message") pub.sendMessage('stream.ctrl.removed', streams_present=False, streams_visible=False, tab=self._tab_data_model)
#----------------------------------------------------------------------------- # Copyright (c) 2013-2020, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt, distributed with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- """ Functional test exercising the non-default protocol `arg1` of version 3 of the PyPubSub API. """ from wx.lib.pubsub import setuparg1 from wx.lib.pubsub import pub as Publisher def on_message(message): print('Message received.') if not message.data == 762: raise SystemExit('Message data "762" expected but received "%s".' % str(message.data)) Publisher.subscribe(on_message, 'topic.subtopic') Publisher.sendMessage('topic.subtopic', 762)
def setTitle(self, title): Publisher.sendMessage("script.title", title=title)
def OnCheckItem(self, index, flag): Publisher.sendMessage('Show surface', (index, flag))
def OnEditLabel(self, evt): Publisher.sendMessage('Change surface name', (evt.GetIndex(), evt.GetLabel())) evt.Skip()
def OnDuplicate(self): selected_items = self.parent.listctrl.GetSelected() if selected_items: Publisher.sendMessage('Duplicate surfaces', selected_items) else: dlg.SurfaceSelectionRequiredForDuplication()
def OnMenu(self, evt): id = evt.GetId() if id == const.MEASURE_LINEAR: Publisher.sendMessage('Set tool linear measure') else: Publisher.sendMessage('Set tool angular measure')
def OnCheckItem(self, index, flag): Publisher.sendMessage('Show measurement', (index, flag))
def OnClose(self, event): pub.sendMessage("exit", msg="exiting...") self._mgr.UnInit() del self._mgr self.Destroy()
def OnEndSeed(self, pubsub_evt): Publisher.sendMessage("Create surface from seeds", self.seed_points)
def OnExit(self, event): pub.sendMessage("exit", msg="exiting...") self.Close()
def Render(self): Publisher.sendMessage('Render volume viewer')
def RemoveAllActor(self, pubsub_evt): utils.debug("RemoveAllActor") self.ren.RemoveAllProps() Publisher.sendMessage('Render volume viewer')
def refresh_plot(self): Publisher.sendMessage(("changePlotSelection"), sellist=self._record_service.get_filter_list()) Publisher.sendMessage(("updateValues"), event=None)
def UpdateAllSlice(self, pubsub_evt): Publisher.sendMessage('Update slice 3D', (self.plane_y, "CORONAL")) Publisher.sendMessage('Update slice 3D', (self.plane_x, "SAGITAL")) Publisher.sendMessage('Update slice 3D', (self.plane_z, "AXIAL"))
def clear_history(self): self.history = [] self.index = -1 Publisher.sendMessage("Enable undo", False) Publisher.sendMessage("Enable redo", False)
def Create(self): plane_x = self.plane_x = vtk.vtkImagePlaneWidget() plane_x.InteractionOff() #Publisher.sendMessage('Input Image in the widget', #(plane_x, 'SAGITAL')) plane_x.SetPlaneOrientationToXAxes() plane_x.TextureVisibilityOn() plane_x.SetLeftButtonAction(0) plane_x.SetRightButtonAction(0) plane_x.SetMiddleButtonAction(0) cursor_property = plane_x.GetCursorProperty() cursor_property.SetOpacity(0) plane_y = self.plane_y = vtk.vtkImagePlaneWidget() plane_y.DisplayTextOff() #Publisher.sendMessage('Input Image in the widget', #(plane_y, 'CORONAL')) plane_y.SetPlaneOrientationToYAxes() plane_y.TextureVisibilityOn() plane_y.SetLeftButtonAction(0) plane_y.SetRightButtonAction(0) plane_y.SetMiddleButtonAction(0) prop1 = plane_y.GetPlaneProperty() cursor_property = plane_y.GetCursorProperty() cursor_property.SetOpacity(0) plane_z = self.plane_z = vtk.vtkImagePlaneWidget() plane_z.InteractionOff() #Publisher.sendMessage('Input Image in the widget', #(plane_z, 'AXIAL')) plane_z.SetPlaneOrientationToZAxes() plane_z.TextureVisibilityOn() plane_z.SetLeftButtonAction(0) plane_z.SetRightButtonAction(0) plane_z.SetMiddleButtonAction(0) cursor_property = plane_z.GetCursorProperty() cursor_property.SetOpacity(0) prop3 = plane_z.GetPlaneProperty() prop3.SetColor(1, 0, 0) selected_prop3 = plane_z.GetSelectedPlaneProperty() selected_prop3.SetColor(1, 0, 0) prop1 = plane_x.GetPlaneProperty() prop1.SetColor(0, 0, 1) selected_prop1 = plane_x.GetSelectedPlaneProperty() selected_prop1.SetColor(0, 0, 1) prop2 = plane_y.GetPlaneProperty() prop2.SetColor(0, 1, 0) selected_prop2 = plane_y.GetSelectedPlaneProperty() selected_prop2.SetColor(0, 1, 0) Publisher.sendMessage('Set Widget Interactor', plane_x) Publisher.sendMessage('Set Widget Interactor', plane_y) Publisher.sendMessage('Set Widget Interactor', plane_z) self.Render()
def _close(cls, store): """ Manually close the store, and broadcast a pubsub notification. """ cls._stores.pop(store, None) store.close() pub.sendMessage('store.close')
def OnOpenMesh(self): filename = dlg.ShowImportMeshFilesDialog() if filename: Publisher.sendMessage('Import surface file', filename)
def run(self): """Run Worker Thread.""" # This is the code executing in the new thread. screen.start() wx.CallAfter( lambda: pub.sendMessage('screen.end', msg="Thread finished!"))
def _reload_slice(self, index): Publisher.sendMessage( ('Set scroll position', self.history[index].orientation), self.history[index].index)
def LoadProject(self): proj = prj.Project() const.THRESHOLD_OUTVALUE = proj.threshold_range[0] const.THRESHOLD_INVALUE = proj.threshold_range[1] const.THRESHOLD_RANGE = proj.threshold_modes[_("Bone")] const.WINDOW_LEVEL[_('Default')] = (proj.window, proj.level) const.WINDOW_LEVEL[_('Manual')] = (proj.window, proj.level) self.Slice = sl.Slice() self.Slice.spacing = proj.spacing Publisher.sendMessage('Load slice to viewer', mask_dict=proj.mask_dict) Publisher.sendMessage('Load slice plane') Publisher.sendMessage('Bright and contrast adjustment image', window=proj.window, level=proj.level) Publisher.sendMessage('Update window level value', window=proj.window, level=proj.level) Publisher.sendMessage('Set project name', proj_name=proj.name) Publisher.sendMessage('Load surface dict', surface_dict=proj.surface_dict) Publisher.sendMessage('Hide surface items', surface_dict=proj.surface_dict) self.LoadImagedataInfo() # TODO: where do we insert this <<<? Publisher.sendMessage('Show content panel') Publisher.sendMessage('Update AUI') if len(proj.mask_dict): mask_index = len(proj.mask_dict) - 1 for m in proj.mask_dict.values(): Publisher.sendMessage('Add mask', mask=m) if m.is_shown: self.Slice.current_mask = proj.mask_dict[mask_index] Publisher.sendMessage('Show mask', index=m.index, value=True) Publisher.sendMessage('Change mask selected', index=m.index) else: mask_name = const.MASK_NAME_PATTERN % (1, ) if proj.modality != "UNKNOWN": thresh = const.THRESHOLD_RANGE else: thresh = proj.threshold_range colour = const.MASK_COLOUR[0] Publisher.sendMessage('Create new mask', mask_name=mask_name, thresh=thresh, colour=colour) Publisher.sendMessage('Load measurement dict', measurement_dict=proj.measurement_dict, spacing=self.Slice.spacing) Publisher.sendMessage(('Set scroll position', 'AXIAL'), index=proj.matrix_shape[0] / 2) Publisher.sendMessage(('Set scroll position', 'SAGITAL'), index=proj.matrix_shape[1] / 2) Publisher.sendMessage(('Set scroll position', 'CORONAL'), index=proj.matrix_shape[2] / 2) Publisher.sendMessage('End busy cursor')
def OnPopup(self, evt): id = evt.GetId() item = self.ID_TO_TOOL_ITEM[evt.GetId()] key = item.GetLabel() if(key in const.WINDOW_LEVEL.keys()): window, level = const.WINDOW_LEVEL[key] Publisher.sendMessage('Bright and contrast adjustment image', (window, level)) Publisher.sendMessage('Update window level value',\ (window, level)) Publisher.sendMessage('Update window and level text',\ "WL: %d WW: %d"%(level, window)) Publisher.sendMessage('Update slice viewer') #Necessary update the slice plane in the volume case exists Publisher.sendMessage('Render volume viewer') elif(key in const.SLICE_COLOR_TABLE.keys()): values = const.SLICE_COLOR_TABLE[key] Publisher.sendMessage('Change colour table from background image', values) Publisher.sendMessage('Update slice viewer') if sys.platform == 'linux2': for i in self.pseudo_color_items: it = self.pseudo_color_items[i] if it.IsChecked(): it.Toggle() item.Toggle() self.HideClutDialog() self._gen_event = True elif key in self.plist_presets: values = presets.get_wwwl_preset_colours(self.plist_presets[key]) Publisher.sendMessage('Change colour table from background image from plist', values) Publisher.sendMessage('Update slice viewer') if sys.platform == 'linux2': for i in self.pseudo_color_items: it = self.pseudo_color_items[i] if it.IsChecked(): it.Toggle() item.Toggle() self.HideClutDialog() self._gen_event = True elif(key in const.IMAGE_TILING.keys()): values = const.IMAGE_TILING[key] Publisher.sendMessage('Set slice viewer layout', values) Publisher.sendMessage('Update slice viewer') elif key in PROJECTIONS_ID: pid = PROJECTIONS_ID[key] Publisher.sendMessage('Set projection type', pid) Publisher.sendMessage('Reload actual slice') elif key == _('Custom'): if self.cdialog is None: slc = sl.Slice() histogram = slc.histogram init = slc.matrix.min() end = slc.matrix.max() nodes = slc.nodes self.cdialog = ClutImagedataDialog(histogram, init, end, nodes) self.cdialog.Show() else: self.cdialog.Show(self._gen_event) if sys.platform == 'linux2': for i in self.pseudo_color_items: it = self.pseudo_color_items[i] if it.IsChecked(): it.Toggle() item.Toggle() item = self.ID_TO_TOOL_ITEM[evt.GetId()] item.Check(True) self._gen_event = False evt.Skip()
def OnLoadImportPanel(self, patient_series): ok = self.LoadImportPanel(patient_series) if ok: Publisher.sendMessage('Show import panel') Publisher.sendMessage("Show import panel in frame") self.img_type = 1
def OpenDicomGroup(self, dicom_group, interval, file_range, gui=True): # Retrieve general DICOM headers dicom = dicom_group.GetDicomSample() # Create imagedata interval += 1 filelist = dicom_group.GetFilenameList()[::interval] if not filelist: utils.debug("Not used the IPPSorter") filelist = [ i.image.file for i in dicom_group.GetHandSortedList()[::interval] ] if file_range is not None and file_range[ 0] is not None and file_range[1] > file_range[0]: filelist = filelist[file_range[0]:file_range[1] + 1] zspacing = dicom_group.zspacing * interval size = dicom.image.size bits = dicom.image.bits_allocad sop_class_uid = dicom.acquisition.sop_class_uid xyspacing = dicom.image.spacing orientation = dicom.image.orientation_label wl = float(dicom.image.level) ww = float(dicom.image.window) if sop_class_uid == '1.2.840.10008.5.1.4.1.1.7': #Secondary Capture Image Storage use_dcmspacing = 1 else: use_dcmspacing = 0 imagedata = None if dicom.image.number_of_frames == 1: sx, sy = size n_slices = len(filelist) resolution_percentage = utils.calculate_resizing_tofitmemory( int(sx), int(sy), n_slices, bits / 8) if resolution_percentage < 1.0 and gui: re_dialog = dialog.ResizeImageDialog() re_dialog.SetValue(int(resolution_percentage * 100)) re_dialog_value = re_dialog.ShowModal() re_dialog.Close() if re_dialog_value == wx.ID_OK: percentage = re_dialog.GetValue() resolution_percentage = percentage / 100.0 else: return xyspacing = xyspacing[0] / resolution_percentage, xyspacing[ 1] / resolution_percentage self.matrix, scalar_range, self.filename = image_utils.dcm2memmap( filelist, size, orientation, resolution_percentage) print(xyspacing, zspacing) if orientation == 'AXIAL': spacing = xyspacing[0], xyspacing[1], zspacing elif orientation == 'CORONAL': spacing = xyspacing[0], zspacing, xyspacing[1] elif orientation == 'SAGITTAL': spacing = zspacing, xyspacing[1], xyspacing[0] else: self.matrix, spacing, scalar_range, self.filename = image_utils.dcmmf2memmap( filelist[0], orientation) self.Slice = sl.Slice() self.Slice.matrix = self.matrix self.Slice.matrix_filename = self.filename self.Slice.spacing = spacing # 1(a): Fix gantry tilt, if any tilt_value = dicom.acquisition.tilt if (tilt_value) and (gui): # Tell user gantry tilt and fix, according to answer message = _("Fix gantry tilt applying the degrees below") value = -1 * tilt_value tilt_value = dialog.ShowNumberDialog(message, value) image_utils.FixGantryTilt(self.matrix, self.Slice.spacing, tilt_value) elif (tilt_value) and not (gui): tilt_value = -1 * tilt_value image_utils.FixGantryTilt(self.matrix, self.Slice.spacing, tilt_value) self.Slice.window_level = wl self.Slice.window_width = ww scalar_range = int(self.matrix.min()), int(self.matrix.max()) Publisher.sendMessage('Update threshold limits list', threshold_range=scalar_range) return self.matrix, self.filename, dicom
def ShowDialogCloseProject(self): session = ses.Session() st = session.project_status print('Status', st, type(st)) if st == const.PROJ_CLOSE: return -1 try: filename = session.project_path[1] except (AttributeError): utils.debug("Project doesn't exist") filename = None if (filename): if (st == const.PROJ_NEW) or (st == const.PROJ_CHANGE): answer = dialog.SaveChangesDialog(filename, self.frame) if not answer: utils.debug("Close without changes") self.CloseProject() Publisher.sendMessage("Enable state project", state=False) Publisher.sendMessage('Set project name') Publisher.sendMessage("Stop Config Recording") elif answer == 1: self.ShowDialogSaveProject() utils.debug("Save changes and close") self.CloseProject() Publisher.sendMessage("Enable state project", state=False) Publisher.sendMessage('Set project name') Publisher.sendMessage("Stop Config Recording") elif answer == -1: utils.debug("Cancel") else: self.CloseProject() Publisher.sendMessage("Enable state project", state=False) Publisher.sendMessage('Set project name') Publisher.sendMessage("Stop Config Recording") else: Publisher.sendMessage('Stop Config Recording')
def OnLoadImportBitmapPanel(self, data): ok = self.LoadImportBitmapPanel(data) if ok: Publisher.sendMessage('Show import bitmap panel in frame') self.img_type = 2
def MakeMatrix(self): """ Update values in a matrix to each orientation. """ self.sagital[const.SAGITAL_LEFT] = [ [self.xi, self.yi - (self.ys / 2), self.zi], [self.xi, self.yi - (self.ys / 2), self.zf], ] self.sagital[const.SAGITAL_RIGHT] = [ [self.xi, self.yf + (self.ys / 2), self.zi], [self.xi, self.yf + (self.ys / 2), self.zf], ] self.sagital[const.SAGITAL_BOTTOM] = [ [self.xi, self.yi, self.zi - (self.zs / 2)], [self.xi, self.yf, self.zi - (self.zs / 2)], ] self.sagital[const.SAGITAL_UPPER] = [ [self.xi, self.yi, self.zf + (self.zs / 2)], [self.xi, self.yf, self.zf + (self.zs / 2)], ] self.coronal[const.CORONAL_BOTTOM] = [ [self.xi, self.yi, self.zi - (self.zs / 2)], [self.xf, self.yf, self.zi - (self.zs / 2)], ] self.coronal[const.CORONAL_UPPER] = [ [self.xi, self.yi, self.zf + (self.zs / 2)], [self.xf, self.yf, self.zf + (self.zs / 2)], ] self.coronal[const.CORONAL_LEFT] = [ [self.xi - (self.xs / 2), self.yi, self.zi], [self.xi - (self.xs / 2), self.yf, self.zf], ] self.coronal[const.CORONAL_RIGHT] = [ [self.xf + (self.xs / 2), self.yi, self.zi], [self.xf + (self.xs / 2), self.yf, self.zf], ] self.axial[const.AXIAL_BOTTOM] = [ [self.xi, self.yi - (self.ys / 2), self.zi], [self.xf, self.yi - (self.ys / 2), self.zf], ] self.axial[const.AXIAL_UPPER] = [ [self.xi, self.yf + (self.ys / 2), self.zi], [self.xf, self.yf + (self.ys / 2), self.zf], ] self.axial[const.AXIAL_LEFT] = [ [self.xi - (self.xs / 2), self.yi, self.zi], [self.xi - (self.xs / 2), self.yf, self.zf], ] self.axial[const.AXIAL_RIGHT] = [ [self.xf + (self.xs / 2), self.yi, self.zi], [self.xf + (self.xs / 2), self.yf, self.zf], ] Publisher.sendMessage("Update crop limits into gui", limits=self.GetLimits())
def StartImportBitmapPanel(self, path): # retrieve DICOM files splited into groups reader = bmp.ProgressBitmapReader() reader.SetWindowEvent(self.frame) reader.SetDirectoryPath(path) Publisher.sendMessage('End busy cursor')
def MouseMove(self, x, y): self.MouseInLine(x, y) x_pos_sl_, y_pos_sl_ = self.viewer.get_slice_pixel_coord_by_screen_pos( x, y) slice_spacing = self.viewer.slice_.spacing xs, ys, zs = slice_spacing x_pos_sl = x_pos_sl_ * xs y_pos_sl = y_pos_sl_ * ys x, y, z = self.viewer.get_voxel_coord_by_screen_pos(x, y) if self.viewer.orientation == "AXIAL": if (self.status_move == const.AXIAL_UPPER or self.status_move == const.AXIAL_BOTTOM): Publisher.sendMessage("Set interactor resize NS cursor") elif (self.status_move == const.AXIAL_LEFT or self.status_move == const.AXIAL_RIGHT): Publisher.sendMessage("Set interactor resize WE cursor") elif self.crop_pan == const.CROP_PAN: Publisher.sendMessage("Set interactor resize NSWE cursor") else: Publisher.sendMessage("Set interactor default cursor") if self.viewer.orientation == "SAGITAL": if (self.status_move == const.SAGITAL_UPPER or self.status_move == const.SAGITAL_BOTTOM): Publisher.sendMessage("Set interactor resize NS cursor") elif (self.status_move == const.SAGITAL_LEFT or self.status_move == const.SAGITAL_RIGHT): Publisher.sendMessage("Set interactor resize WE cursor") elif self.crop_pan == const.CROP_PAN: Publisher.sendMessage("Set interactor resize NSWE cursor") else: Publisher.sendMessage("Set interactor default cursor") if self.viewer.orientation == "CORONAL": if (self.status_move == const.CORONAL_UPPER or self.status_move == const.CORONAL_BOTTOM): Publisher.sendMessage("Set interactor resize NS cursor") elif (self.status_move == const.CORONAL_LEFT or self.status_move == const.CORONAL_RIGHT): Publisher.sendMessage("Set interactor resize WE cursor") elif self.crop_pan == const.CROP_PAN: Publisher.sendMessage("Set interactor resize NSWE cursor") else: Publisher.sendMessage("Set interactor default cursor") if self.mouse_pressed and self.status_move: self.box.UpdatePositionBySideBox((x * xs, y * ys, z * zs), self.viewer.orientation, self.status_move) nv_x = x - self.last_x nv_y = y - self.last_y nv_z = z - self.last_z if self.mouse_pressed and self.crop_pan: self.box.UpdatePositionByInsideBox( (nv_x * xs, nv_y * ys, nv_z * zs), self.viewer.orientation) self.last_x = x self.last_y = y self.last_z = z Publisher.sendMessage("Redraw canvas")
def OnCancelImportBitmap(self): #self.cancel_import = True Publisher.sendMessage('Hide import bitmap panel')