def OnStructureSelect(self, evt=None): """Load the properties of the currently selected structure.""" if (evt == None): self.choiceStructure.SetSelection(0) choiceItem = 0 else: choiceItem = evt.GetInt() # Load the structure id chosen from the choice control id = self.choiceStructure.GetClientData(choiceItem) pub.sendMessage('structure.selected', {'id': id}) self.lblStructureVolume.SetLabel( str(self.structures[id]['volume'])[0:7]) # make sure that the dvh has been calculated for each structure # before setting it if self.dvhs.has_key(id): self.lblStructureMinDose.SetLabel("%.3f" % self.dvhs[id]['min']) self.lblStructureMaxDose.SetLabel("%.3f" % self.dvhs[id]['max']) self.lblStructureMeanDose.SetLabel("%.3f" % self.dvhs[id]['mean']) else: self.lblStructureMinDose.SetLabel('-') self.lblStructureMaxDose.SetLabel('-') self.lblStructureMeanDose.SetLabel('-')
def pluginMenu(self, evt): #Wont need this check once Issue 72 is fixed. if self.data.has_key('rtdose'): #Load RTPlan and first DICOM slice. rtd = self.data['rtdose'] ct1 = self.data['images'][0] #Number of slices. N = len(self.data['images']) #Get slice spacing t, use difference instead of tags to get direction. t = self.data['images'][1].ImagePositionPatient[2]-self.data['images'][0].ImagePositionPatient[2] zpos = ct1.ImagePositionPatient[2] #Check current type of GFOV and switch. if rtd.has_key('GridFrameOffsetVector'): if rtd.GridFrameOffsetVector[0] == 0.: logger.info("Found Type A - Relative Coordinates\nConverting to Type B - Absolute") #Convert to Type B (Absolute) rtd.GridFrameOffsetVector = list(np.arange(zpos, zpos + t*N, t)) elif rtd.GridFrameOffsetVector[0] == zpos: logger.info("Found Type B - Absolute Coordinates\nConverting to Type A - Relative") #Convert to Type A (Relative) rtd.GridFrameOffsetVector = list(np.arange(0., abs(t)*N,abs(t))) else: logger.info("GridFrameOffsetVector key not found in RT-Dose!") #Print results. np.set_printoptions(precision=2) logger.info(np.array(rtd.GridFrameOffsetVector)) #Publish new rtdose. pub.sendMessage('patient.updated.raw_data', self.data) else: logger.info("Please load a RT-Dose file!")
def OnOK(self, evt): """Return the patient data if the patient is selected or the button is pressed.""" item = self.tcPatients.GetSelection() if self.tcPatients.GetPyData(item): # Since we have decided to use this location to import from, # update the location in the preferences for the next session # if the 'import_location_setting' is "Remember Last Used" if (self.import_location_setting == "Remember Last Used"): pub.sendMessage('preferences.updated.value', {'general.dicom.import_location':self.path}) # Since we have updated the search subfolders setting, # update the setting in preferences pub.sendMessage('preferences.updated.value', {'general.dicom.import_search_subfolders': self.import_search_subfolders}) filearray = self.tcPatients.GetPyData(item)['filearray'] self.btnSelect.Enable(False) self.txtRxDose.Enable(False) self.terminate = False self.importThread=threading.Thread(target=self.GetPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress)) self.importThread.start()
def __init__(self, *args, **kwargs): """ General Notebook class for Diagram Notebook on the right part of DEVSimPy. """ # for splash screen pub.sendMessage('object.added', message='Loading notebook diagram...\n') Printable.__init__(self) # local copy self.parent = args[0] self.pages = [] # keeps track of pages ### to propagate the dsp file path in __setstate__ of Block object self.current_dsp_file_path = "" #icon under tab imgList = wx.ImageList(16, 16) for img in [os.path.join(ICON_PATH_16_16,'network.png')]: imgList.Add(wx.Image(img, wx.BITMAP_TYPE_PNG).ConvertToBitmap()) self.AssignImageList(imgList) ### binding self.Bind(wx.EVT_LEFT_DCLICK, self.__AddPage)
def _createRooms(d, roomInventory, respectRoom, num_prefs = 3): """return a prefernece ordered, list of rooms. d is a dictionary of room_prefs {"Room 1":"E51-135", "Room 2":"E62-133"} blank requests are ignored. Rooms not in inventory will be created if respectRoom = True. If room not inventory, and not "respect", will log error.""" out, all_in_inv = [], True for ix_pref in range(1, num_prefs + 1): roomName = d.get("Room " + str(ix_pref), "").strip() del d["Room " + str(ix_pref)] if not roomName: continue #search for it in the list. room_list = filter(lambda x: str(x) == roomName, roomInventory) if room_list: assert len(room_list) == 1 out.append(room_list[0]) # elif respectRoom: # out.append(ses.Room(roomName, ses.Room.MAX_SIZE)) else: out.append(ses.Room(roomName, ses.Room.MAX_SIZE)) all_in_inv = False #only issue warning if not respect room if not respectRoom: pub.sendMessage("warning", "Room %s not in inventory" % roomName) return out, all_in_inv
def save(self): fout = open("library.db",'wb') pickle.dump(self.books,fout) fout.close() print "Saved", len(self.books), "books" pub.sendMessage("SAVED",len(self.books))
def write_generic_inparam(self, type, param): """ writes ZforIsop.dat or PFORTXY.DAT or TFORPXY.dat needed to run IsoplethGPEC, TxyGPEC or PxyGPEC respectively. """ type2file = { 'z': 'ZforIsop.dat', 'p': 'PFORTXY.dat', 't': 'TFORPXY.dat' } if type not in type2file.keys(): pub.sendMessage('log', ('error', 'Unknown input file to write')) return else: filename = type2file[type] filepath = os.path.join(self.path_temp, filename) template = "{0!s}" output = template.format(param) with open(filepath, 'w') as fh: fh.write(output) fh.close() self.written.add((filename)) pub.sendMessage('add_txt', (filepath, self.case_id))
def _trial_added(self, message): trial = message.data trial_name = trial.display_name new_row = self._num_nonempty_rows self._trial_ids.append(trial.trial_id) self._trials[trial.trial_id] = trial self._set_trial_name(new_row, trial_name) self._autosize_cols() if self._num_empty_rows > 1: self._num_empty_rows -= 1 else: self.AppendRows() assert len(self._trial_ids) == self._num_nonempty_rows # make new trial come in correctly marked. row = self._get_row_from_trial_id(trial.trial_id) self.SetCellRenderer(row, 0, gridlib.GridCellBoolRenderer()) self._set_marked_status(row, trial.is_marked) # only select new trial if nothing is selected. if self._last_trial_id_selected is None: self._last_trial_id_selected = 'Not-None' wx.CallLater(1000, self._select_row, row) pub.sendMessage('SET_RUN_BUTTONS_STATE', data=[True, True])
def cacheCorrect(event, self=self, row=row, cache=cache): '''Add/Edit Correction of the Lat/Lon for the selected cache (row)''' self.SelectRow(row) #cache = self._table.GetRowCache(row) # create data dictionary for the dialog and it's validators data = {'lat': cache.lat, 'lon': cache.lon, 'clat': cache.clat, 'clon': cache.clon, 'cnote': cache.cnote} dlg = CorrectLatLon(self, wx.ID_ANY, cache.code, data, not cache.corrected) # show the dialog and update the cache if OK clicked and there # where changes if dlg.ShowModal() == wx.ID_OK and (data['clat'] != cache.clat or data['clon'] != cache.clon or data['cnote'] != cache.cnote): Publisher.sendMessage('status.push',_('Correcting cache: %s') % cache.code) cache.clat = data['clat'] cache.clon = data['clon'] cache.cnote = data['cnote'] cache.corrected = True cache.user_date = datetime.now() cache.save() geocacher.db().commit() self._table.ReloadRow(row) self.Reset() Publisher.sendMessage('status.pop') dlg.Destroy()
def cacheAddLog(found, self=self, cache=cache): if found: logType = 'Found It' logDate = cache.found_date else: logType = "Didn't find it" logDate = cache.dnf_date dlg = FoundCache(self, cache.code, logType, logDate, cache.own_log, cache.own_log_encoded) if dlg.ShowModal() == wx.ID_OK: Publisher.sendMessage('status.push', _('Marking cache %s as "%s"') % (cache.code, logType)) newLog = cache.addLog(None, date = wxDateTimeToPy(dlg.date.GetValue()), logType = logType, finder_id = geocacher.config().GCUserID, finder_name = geocacher.config().GCUserName, encoded = dlg.encodeLog.GetValue(), text = dlg.logText.GetValue()) if found: cache.found = True cache.found_date = newLog.date else: cache.dnf = True cache.dnf_date = newLog.date cache.own_log_id = newLog.logId cache.user_date = datetime.now() cache.save() geocacher.db().commit() cache.refreshOwnLog() self._table.ReloadRow(row) self.Reset() Publisher.sendMessage('status.pop') dlg.Destroy()
def OnMouseWheel(self, evt): """Capture the mousewheel event when the notebook tab is focused. Currently this is used to workaround a bug in Windows since the notebook tab instead of the panel receives focus.""" if guiutil.IsMSWindows(): pub.sendMessage('main.mousewheel', evt)
def OnKeyDown(self, evt): """Capture the keypress when the notebook tab is focused. Currently this is used to workaround a bug in Windows since the notebook tab instead of the panel receives focus.""" if guiutil.IsMSWindows(): pub.sendMessage('main.key_down', evt)
def OnIsodoseCheck(self, msg): """Load the properties of the currently checked isodoses.""" isodose = msg.data self.isodoseList[isodose['data']['level']] = isodose pub.sendMessage('isodoses.checked', self.isodoseList)
def _show_toolbars(self, event): if self._toolbars_shown: pub.sendMessage(topic='HIDE_TOOLBAR', data=None) self._toolbars_shown = False else: pub.sendMessage(topic='SHOW_TOOLBAR', data=None) self._toolbars_shown = True
def onAssignEquipmentAEV(self, evt): #Check if there is selected any item in the equipment list count = self.aev_view.getItemCount(self.aev_view.equipmentList) if (count == 0): wx.MessageBox("Please select a PEP to assign an AEV value!") elif (count > 1): wx.MessageBox("Please select just one PEP to assign an AEV value!") else: #Grab the id of the Equipment selected idEquipment = self.aev_view.getIDItemSelected( self.aev_view.equipmentList) self.aev.FK_Equipment = idEquipment self.aev.FK_Organization = self.idOrganization #Check if the Equipment is already assigned to the Organization (error, value) = self.aev.read_by_equipment_organization() if error: msg = "Error reading the AEV value of the PEP: \n" + value wx.MessageBox(msg) self.onCancel(True) else: if not value: if self.getAEVValuesFromView(): self.aev.create() else: wx.MessageBox("PEP already assigned to the Organization!") #Send a message to update the view of list of organizations Publisher.sendMessage("organization_updated", None) return
def _update_strategy(self, value=None): ''' Called when a control_panel's value is changed and is valid. Also called when the user changes the method of a stage. ''' strategy = self.get_current_strategy() pub.sendMessage('SET_CURRENT_STRATEGY', data=strategy)
def save(self): fout = open("library.db", 'wb') pickle.dump(self.books, fout) fout.close() print "Saved", len(self.books), "books" pub.sendMessage("SAVED", len(self.books))
def saveSettings(self): """ Save settings """ db = WpDatabaseAPI() ## Saving tab size self.configobj.settings['editor-tabsize'] = self.tabsizeinput.GetValue() db.AddRegisterSetting('tabsize', self.configobj.settings['editor-tabsize'], 'editor') # Saving if tab is to be used self.configobj.settings['editor-usetab'] = 1 if self.checkbox.IsChecked() == True else 0 db.AddRegisterSetting('usetab', self.configobj.settings['editor-usetab'], 'editor') ## Saving margin settings self.configobj.settings['editor-textmargin'] = self.marginSizeInput.GetValue() db.AddRegisterSetting( 'textmargin', self.configobj.settings['editor-textmargin'], 'editor' ) ## Saving code folding self.configobj.settings['editor-foldcode'] = 1 if self.codeFoldCheckbox.IsChecked() == True else 0 db.AddRegisterSetting('foldcode', self.configobj.settings['editor-foldcode'], 'editor') ## Saving code folding style self.configobj.settings['editor-foldcodestyle'] = self.foldCodeStyleSelect.GetCurrentSelection() db.AddRegisterSetting('foldcodestyle', self.configobj.settings['editor-foldcodestyle'], 'editor') ## Saving fonts self.configobj.settings['editor-fontface'] = self.fontListCtrl.GetStringSelection() self.configobj.settings['editor-fontsize'] = int( self.fontSizeSelect.GetString( self.fontSizeSelect.GetSelection() ) ) db.AddRegisterSetting( 'fontface', self.configobj.settings['editor-fontface'], 'editor' ) db.AddRegisterSetting( 'fontsize', self.configobj.settings['editor-fontsize'], 'editor' ) ## Notify the editor to refrsh pub.sendMessage('editor.refresh', True)
def UpdateData( self, data, ): """Publish the updated patient data.""" pub.sendMessage('patient.updated.raw_data', data)
def __onNewFile(self, event): data = { 'file': None, 'prjid': None } pub.sendMessage('notebook.addpage', data)
def addTimePrefs(self, timePrefs): """timePrefs is an interable collection of timeSlots. Order determines pref. Appends to first pref. Must be consistent to first in terms of half, No. Meetings/Wk, Hour length""" #only want unique elements, excluding the one already set timePrefs = uniquify([self.timePrefs[0]] + timePrefs) timePrefs, self.timePrefs = timePrefs[1:], self.timePrefs[:1] self.pref_days = self.pref_days[:1] if self.respectTime and timePrefs: pub.sendMessage( "warning", "Attempt to addTimePrefs to %s after specifying respectTime" % self) for ts in timePrefs: assert (isinstance(ts, TimeSlot)) if not self.isViableTime(ts): pub.sendMessage( "warning", "Time Slot %s is not viable for course %s" % (ts, self)) self.timePrefs.append(ts) self.pref_days.append(ts.days) self.pref_days = uniquify(self.pref_days)
def onDelete(self, evt): count = self.ale_view.getItemCount(self.ale_view.incidentOrganizationList) if (count == 0): wx.MessageBox("Please select a Detrimental Event of the Organization to be deleted!") else: msg = "Proceed to delete "+str(count)+" elements?" del_confirm = wx.MessageDialog(None, msg, 'Delete Confirmation', wx.YES_NO | wx.ICON_QUESTION) if del_confirm.ShowModal() == wx.ID_NO: return item_list = self.ale_view.getSetItemsSelected(self.ale_view.incidentOrganizationList) for id_incident in item_list: self.ale.FK_Incident = id_incident self.ale.FK_Organization = self.idOrganization (error, values) = self.ale.delete_by_organization_incident() if error: msg= "There was an error deleting the Detrimental Event of the organization: \n" + values wx.MessageBox(msg) self.ale_view.Dialog.Close() self.ale_view.clearTextsInputs() #Send a message to update the view of list of organizations Publisher.sendMessage("organization_updated", None) return
def run(self) : global qemu global demo self.datapoints = [0] while True : resp=qemu.no_input_exec_command('vemu-energy') #print resp activep = resp['return']['1']['value'] sleepp = resp['return']['2']['value'] delta = (activep + sleepp) - (self.prevact + self.prevslp) averagep = delta / 1.0 if len(self.datapoints) > 10 : self.datapoints.pop(0) self.prevact = activep self.prevslp = sleepp self.datapoints.append(averagep) #print averagep, np.average(self.datapoints, weights=np.exp(range(len(self.datapoints)))) #, #weights=[1, 2, 10, 25, 50] #print activep, sleepp, averagep pub.sendMessage("average_power", averagep) #demo.plt0.newData(activep+sleepp) #demo.plt0.updateTimePlot() time.sleep(1) pass qemu.close()
def LoadMarkets(self): self.markets = self.session.GetAvailableMarkets() if self.markets == None: return False self.treeMarkets.DeleteAllItems() root = self.treeMarkets.AddRoot('Markets') # Add all markets to the tree items = {} for market in self.markets: path = '' parent = root # Iterate over the market path for item in market.menuPathParts: path = path + item if path in items: parent = items[path] continue # Add this node if it doesn't exist parent = items[path] = self.treeMarkets.AppendItem(parent, item) # After all of the parent nodes are present, at the market type items[path + market.marketName] = self.treeMarkets.AppendItem(items[path], market.marketName) # Attach the market information to the tree object for extraction later self.treeMarkets.SetPyData(items[path + market.marketName], market) self.treeMarkets.Expand(root) pub.sendMessage(SUBJECT_STATUSBAR, 'Found ' + str(len(self.markets)) + ' available ' + self.session.sessionType + ' markets') return True
def zoomCtrlOnChanged(self, evt): match = re.match('\s*([+-]?\d+)\s*$', evt.String) if match: pub.sendMessage("CHANGE_ZOOM", int(match.group(1))) else: # This should eventually restore previous value pub.sendMessage("CHANGE_ZOOM", -1)
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 OnUpdatePatientData(self, patient): """Update the patient data in the main program interface.""" self.PopulateDemographics(patient) self.structures = {} if patient.has_key('structures'): self.structures = patient['structures'] self.PopulateStructures() if patient.has_key('plan'): self.PopulatePlan(patient['plan']) else: self.PopulatePlan({}) if (patient.has_key('dose') and patient.has_key('plan')): self.PopulateIsodoses(patient.has_key('images'), patient['plan'], patient['dose']) else: self.PopulateIsodoses(patient.has_key('images'), {}, {}) if patient.has_key('dvhs'): self.dvhs = patient['dvhs'] else: self.dvhs = {} # Re-publish the raw data pub.sendMessage('patient.updated.raw_data', self.ptdata) # Publish the parsed data pub.sendMessage('patient.updated.parsed_data', patient)
def _RealtimeMode(self): now = datetime.datetime.now() oldtime = self.lastupdate + datetime.timedelta(seconds=self.period) if self.lastupdate.date().year != 2000: if oldtime.date() != now.date(): oldtime = datetime.datetime(now.date().year, now.date().month, now.date().day, 9, 30, 0) + datetime.timedelta(seconds=self.period) if self.lastupdate.time() == datetime.time(11, 30, 0): oldtime = datetime.datetime(self.lastupdate.date().year, self.lastupdate.date().month, self.lastupdate.date().day, 13, 0, 0)\ + datetime.timedelta(seconds=self.period) #now = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute) if now > oldtime : print now, ",", oldtime q = GoogleIntradayQuote(self.symbol,self.period, self.num_day) if self.lastupdate == q.df.index[-1]: return if True:#q.dtstamp[-1] == now: self.lastupdate = q.df.index[-1] if self.period == 60: self.realtimedata = q.df pub.sendMessage(self._message_topic, self.realtimedata) else: self.quotedata = q pub.sendMessage(self._message_topic, self.quotedata.df)
def OnStructureCheck(self, msg): """Load the properties of the currently checked structures.""" structure = msg.data # Get the structure number id = structure['data']['id'] structure['data']['color'] = structure['color'].Get() # Make sure that the volume has been calculated for each structure # before setting it if not self.structures[id].has_key('volume'): # Use the volume units from the DVH if they are absolute volume if self.dvhs.has_key(id) and (self.dvhs[id]['volumeunits'] == 'CM3'): self.structures[id]['volume'] = self.dvhs[id]['data'][0] # Otherwise calculate the volume from the structure data else: self.structures[id]['volume'] = dvhdata.CalculateVolume( self.structures[id]) structure['data']['volume'] = self.structures[id]['volume'] self.structureList[id] = structure['data'] # Populate the structure choice box with the checked structures self.choiceStructure.Enable() i = self.choiceStructure.Append(structure['data']['name']) self.choiceStructure.SetClientData(i, id) # Select the first structure self.OnStructureSelect() pub.sendMessage('structures.checked', self.structureList)
def __Reload(self): Publisher.sendMessage( "PAGE_CHANGED", { 'page': self.__page, 'width': int(self.__page.width * self.__zoom), 'height': int(self.__page.height * self.__zoom) })
def OnStructureUncheck(self, msg): """Remove the unchecked structures.""" structure = msg.data # Get the structure number id = structure['data']['id'] # Remove the structure from the structure list if self.structureList.has_key(id): del self.structureList[id] # Remove the structure from the structure choice box for n in range(self.choiceStructure.GetCount()): if (id == self.choiceStructure.GetClientData(n)): # Save if the currently selected item's position currSelection = self.choiceStructure.GetSelection() self.choiceStructure.Delete(n) break # If the currently selected item will be deleted, # select the last item instead if (n == currSelection): if (self.choiceStructure.GetCount() >= 1): self.OnStructureSelect() # Disable the control if it is the last item if (self.choiceStructure.GetCount() == 0): self.choiceStructure.Enable(False) self.OnStructureUnselect() pub.sendMessage('structures.checked', self.structureList)
def decrementClientMinutes(self, subminutes): """ subtrack some of the minutes the client is having """ Publisher.sendMessage("sendingRemaing.Minutes", data=subminutes) self.decrement = self.getClientMinutes() - subminutes self.saveRunningStatus(self.decrement) if(self.setClientMinutes(self.decrement) == False): raise ValueError("Unable to set client time") else: try: #print "Doing something like sending to the server" #Publish a message to the window.py which will send a message to #the server. try: #print "Duplicating" Publisher.sendMessage("sendRemainingMinutes", data=str(self.getClientMinutes())) except: raise else: self._parent.owed_timetext.SetLabel(str(self.getClientMinutes())) except: return False #set the client runtime self.setClientRuntime(self.getClientRuntime() + int(subminutes)) try: self.incrementRuntime(self.getClientRuntime()) except: raise
def _rename_trial(self, event=None): if event is not None: # came in through menu row = self._row_right_clicked else: row = self._row_left_dclicked trial_id = self._get_trial_id_from_row(row) pub.sendMessage(topic='OPEN_RENAME_TRIAL_DIALOG', data=trial_id)
def OnEnablePlugin(self, evt=None): """Publish the enabled/disabled state of the plugin.""" item = self.tcPlugins.GetSelection() n = self.tcPlugins.GetPyData(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', {'general.plugins.disabled_list': list(self.pluginsDisabled)})
def terminate(self, error=False, msg=None): """ Thread termination routine param error: False if thread is terminate without error param msg: message to submit """ if not self.end_flag: if error: ###for traceback etype = msg[0] evalue = msg[1] etb = traceback.extract_tb(msg[2]) sys.stderr.write('Error in routine: your routine here\n') sys.stderr.write('Error Type: ' + str(etype) + '\n') sys.stderr.write('Error Value: ' + str(evalue) + '\n') sys.stderr.write('Traceback: ' + str(etb) + '\n') wx.CallAfter(Publisher.sendMessage, "error", msg) ### error sound if __builtin__.__dict__['GUI_FLAG'] is True: wx.CallAfter(Utilities.playSound, SIMULATION_ERROR_WAV_PATH) else: for m in filter(lambda a: isinstance(a, DEVS.AtomicDEVS), self.model.componentSet): ### call finished method Publisher.sendMessage('%d.finished' % (id(m))) if __builtin__.__dict__['GUI_FLAG'] is True: wx.CallAfter(Utilities.playSound, SIMULATION_SUCCESS_WAV_PATH) self.end_flag = True
def _createRooms(d, roomInventory, respectRoom, num_prefs=3): """return a prefernece ordered, list of rooms. d is a dictionary of room_prefs {"Room 1":"E51-135", "Room 2":"E62-133"} blank requests are ignored. Rooms not in inventory will be created if respectRoom = True. If room not inventory, and not "respect", will log error.""" out, all_in_inv = [], True for ix_pref in range(1, num_prefs + 1): roomName = d.get("Room " + str(ix_pref), "").strip() del d["Room " + str(ix_pref)] if not roomName: continue #search for it in the list. room_list = filter(lambda x: str(x) == roomName, roomInventory) if room_list: assert len(room_list) == 1 out.append(room_list[0]) # elif respectRoom: # out.append(ses.Room(roomName, ses.Room.MAX_SIZE)) else: out.append(ses.Room(roomName, ses.Room.MAX_SIZE)) all_in_inv = False #only issue warning if not respect room if not respectRoom: pub.sendMessage("warning", "Room %s not in inventory" % roomName) return out, all_in_inv
def __init__(self, ip, portFrom, portTo): Thread.__init__(self) self.IP = ip self.portFrom = portFrom self.portTo = portTo Publisher.sendMessage("scanThread", "started") self.start()
def OnModified( self, comps=None ): """ Broadcast the update message and set the dirty flag. Methods subscribed to this message will rebuild ui widgets completely. """ self.dirty = True pub.sendMessage( 'Update', comps )
def OnEnablePlugin(self, evt=None): """Publish the enabled/disabled state of the plugin.""" item = self.tcPlugins.GetSelection() n = self.tcPlugins.GetPyData(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', {'general.plugins.disabled_list': list(self.pluginsDisabled)})
def pluginMenu(self, evt): """Open a new RT Dose object and sum it with the current dose""" self.ptdata = ImportDicom(self.parent) if (self.ptdata['rtplan'].SeriesInstanceUID != \ self.rtplan.SeriesInstanceUID): dlg = wx.MessageDialog( self.parent, "The image sets for both doses do not match.", "Cannot sum doses.", wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() return old = self.rtdose new = self.ptdata['rtdose'] dlgProgress = guiutil.get_progress_dialog(wx.GetApp().GetTopWindow(), "Creating Plan Sum...") q = Queue.Queue() threading.Thread(target=SumPlan, args=(old, new, q, dlgProgress.OnUpdateProgress)).start() dlgProgress.ShowModal() dlgProgress.Destroy() sumDicomObj = q.get() del sumDicomObj.DVHs self.ptdata['rtdose'] = sumDicomObj if self.ptdata.has_key('rxdose') and self.rxdose: self.ptdata['rxdose'] = self.rxdose + self.ptdata['rxdose'] pub.sendMessage('patient.updated.raw_data', self.ptdata)
def onAssignIncidentALE(self, evt): #Check if there is selected any item in the incident list count = self.ale_view.getItemCount(self.ale_view.incidentList) if (count == 0): wx.MessageBox("Please select a Detrimental Event to assign an ALE value!") elif (count > 1): wx.MessageBox("Please select just one Detrimental Event to assign an ALE value!") else: #Grab the id of the Incident selected idIncident = self.ale_view.getIDItemSelected(self.ale_view.incidentList) self.ale.FK_Incident = idIncident self.ale.FK_Organization = self.idOrganization #Check if the Incident is already assigned to the Organization (error, value) = self.ale.read_by_incident_organization() if error: msg= "Error reading the ALE value of the Detrimental Event: \n" + value wx.MessageBox(msg) self.ale_view.Dialog.Close() else: if not value: if self.getALEValuesFromView(): self.ale.create() else: wx.MessageBox("Detrimental Event already assigned to the Organization!") #Send a message to update the view of list of organizations Publisher.sendMessage("organization_updated", None) return
def OnModified(self, comps=None): """ Broadcast the update message and set the dirty flag. Methods subscribed to this message will rebuild ui widgets completely. """ self.dirty = True pub.sendMessage('Update', comps)
def set_compound_vars(self, tc, pc, vc, acentric_factor, vc_rat): self.tc = tc #Tc [K]', 'Critical temperature' self.pc = pc #Pc [bar]', 'Critical Pressure' self.vc = vc #Vol [l/mol]', 'Critical Volume' self.acentric_factor = acentric_factor #'Acentric Factor' self.vc_rat = vc_rat pub.sendMessage('compound vars changed', self.get_compound_vars())
def terminate(self, error=False, msg=None): """ Thread termination routine param error: False if thread is terminate without error param msg: message to submit """ if not self.end_flag: if error: ###for traceback etype = msg[0] evalue = msg[1] etb = traceback.extract_tb(msg[2]) sys.stderr.write('Error in routine: your routine here\n') sys.stderr.write('Error Type: ' + str(etype) + '\n') sys.stderr.write('Error Value: ' + str(evalue) + '\n') sys.stderr.write('Traceback: ' + str(etb) + '\n') ### only for displayed application (-nogui) if wx.GetApp(): wx.CallAfter(Publisher.sendMessage, "error", msg) ### error sound wx.CallAfter(playSound, SIMULATION_ERROR_SOUND_PATH) else: for m in filter(lambda a: hasattr(a, 'finish'), self.model.componentSet): ### call finished method Publisher.sendMessage('%d.finished' % (id(m))) ### only for displayed application (-nogui) if wx.GetApp(): wx.CallAfter(playSound, SIMULATION_SUCCESS_SOUND_PATH) self.end_flag = True
def OnUpdatePositionValues(self, evt=None): """Update the current position and value(s) of the mouse cursor.""" if (evt == None): pos = np.array(self.mousepos) else: pos = np.array(evt.GetPosition()) # On the Mac, the cursor position is shifted by 1 pixel to the left if guiutil.IsMac(): pos = pos - 1 # Determine the coordinates with respect to the current zoom and pan w, h = self.GetClientSize() xpos = int(pos[0] / self.zoom - self.pan[0] - (w - self.bwidth * self.zoom) / (2 * self.zoom)) ypos = int(pos[1] / self.zoom - self.pan[1] - (h - self.bheight * self.zoom) / (2 * self.zoom)) # Save the coordinates so they can be used by the 2dview plugins self.xpos = xpos self.ypos = ypos # Set an empty text placeholder if the coordinates are not within range text = "" value = "" # Only display if the mouse coordinates are within the image size range if ((0 <= xpos < len(self.structurepixlut[0])) and (0 <= ypos < len(self.structurepixlut[1])) and self.mouse_in_window): text = "X: " + unicode('%.2f' % self.structurepixlut[0][xpos]) + \ " mm Y: " + unicode('%.2f' % self.structurepixlut[1][ypos]) + \ " mm / X: " + unicode(xpos) + \ " px Y:" + unicode(ypos) + " px" # Lookup the current image and find the value of the current pixel image = self.images[self.imagenum - 1] # Rescale the slope and intercept of the image if present if (image.ds.has_key('RescaleIntercept') and image.ds.has_key('RescaleSlope')): pixel_array = image.ds.pixel_array*image.ds.RescaleSlope + \ image.ds.RescaleIntercept else: pixel_array = image.ds.pixel_array value = "Value: " + unicode(pixel_array[ypos, xpos]) # Lookup the current dose plane and find the value of the current # pixel, if the dose has been loaded if not (self.dose == []): xdpos = np.argmin(np.fabs(np.array(self.dosepixlut[0]) - xpos)) ydpos = np.argmin(np.fabs(np.array(self.dosepixlut[1]) - ypos)) dosegrid = self.dose.GetDoseGrid(float(self.z)) if not (dosegrid == []): dose = dosegrid[ydpos, xdpos] * \ self.dosedata['dosegridscaling'] value = value + " / Dose: " + \ unicode('%.4g' % dose) + " Gy / " + \ unicode('%.4g' % float(dose*10000/self.rxdose)) + " %" # Send a message with the text to the 2nd and 3rd statusbar sections pub.sendMessage('main.update_statusbar', {1: text, 2: value})
def OnOK(self, evt): """Return the patient data if the patient is selected or the button is pressed.""" item = self.tcPatients.GetSelection() if self.tcPatients.GetPyData(item): # Since we have decided to use this location to import from, # update the location in the preferences for the next session # if the 'import_location_setting' is "Remember Last Used" if (self.import_location_setting == "Remember Last Used"): pub.sendMessage('preferences.updated.value', {'general.dicom.import_location': self.path}) # Since we have updated the search subfolders setting, # update the setting in preferences pub.sendMessage( 'preferences.updated.value', { 'general.dicom.import_search_subfolders': self.import_search_subfolders }) filearray = self.tcPatients.GetPyData(item)['filearray'] self.btnSelect.Enable(False) self.txtRxDose.Enable(False) self.terminate = False self.importThread = threading.Thread( target=self.GetPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress)) self.importThread.start()
def GetQuoteData(self, quote, period=300, num_day=5): try: self.quotedata = GoogleIntradayQuote(quote,period, num_day) pub.sendMessage("ANALYSISDATA", self.quotedata.df) return self.quotedata except: pass
def TransferFromWindow(self): """the compound 2 must be heavier than 1""" def get_weight(tc, pc): return float(tc)**WEIGHT_POWER / float(pc) tc1 = self.compounds_data[0][4] tc2 = self.compounds_data[1][4] pc1 = self.compounds_data[0][5] pc2 = self.compounds_data[1][5] if get_weight(tc1, pc1) > get_weight(tc2, pc2): tmp = self.compounds_data[0] self.compounds_data[0] = self.compounds_data[1] self.compounds_data[1] = tmp pub.sendMessage( 'log', ('info', '%s is heavier than %s. The system was inverted' % (self.compounds_data[1][1], self.compounds_data[0][1]))) pub.sendMessage( 'log', ('ok', 'The system %s-%s was defined succesfully' % (self.compounds_data[0][1], self.compounds_data[1][1]))) return True
def run(self): old = datetime.datetime.now() + datetime.timedelta(minutes = -1) old = datetime.datetime(old.year, old.month, old.day, old.hour, old.minute) while not self.done: try: now = datetime.datetime.now() # print now, " ", old if self._IsMarketOpen(now):#now > old: self._RealtimeMode() #time.sleep(1) else: q = GoogleIntradayQuote(self.symbol,self.period, self.num_day) self.quotedata = q pub.sendMessage(self._message_topic, self.quotedata.df) self.done = True time.sleep(1) except: print str(sys.exc_info()) self.done = False
def terminate(self, error = False, msg = None): """ Thread termination routine param error: False if thread is terminate without error param msg: message to submit """ if not self.end_flag: if error: ###for traceback etype = msg[0] evalue = msg[1] etb = traceback.extract_tb(msg[2]) sys.stderr.write('Error in routine: your routine here\n') sys.stderr.write('Error Type: ' + str(etype) + '\n') sys.stderr.write('Error Value: ' + str(evalue) + '\n') sys.stderr.write('Traceback: ' + str(etb) + '\n') ### only for displayed application (-nogui) if wx.GetApp(): wx.CallAfter(Publisher.sendMessage, "error", msg) ### error sound wx.CallAfter(playSound, SIMULATION_ERROR_SOUND_PATH) else: for m in filter(lambda a: hasattr(a, 'finish'), self.model.componentSet): ### call finished method Publisher.sendMessage('%d.finished'%(id(m))) ### only for displayed application (-nogui) if wx.GetApp() : wx.CallAfter(playSound, SIMULATION_SUCCESS_SOUND_PATH) self.end_flag = True