diff --git a/src/sas/sasgui/guiframe/CategoryInstaller.py b/src/sas/sasgui/guiframe/CategoryInstaller.py index b74af8782c..c35cb5d3fa 100644 --- a/src/sas/sasgui/guiframe/CategoryInstaller.py +++ b/src/sas/sasgui/guiframe/CategoryInstaller.py @@ -20,6 +20,15 @@ logger = logging.getLogger(__name__) +if sys.version_info[0] > 2: + def json_dump(obj, filename): + with open(filename, 'w', newline='\n') as fd: + json.dump(obj, fd) +else: # CRUFT: python 2.7 support + def json_dump(obj, filename): + with open(filename, 'wb') as fd: + json.dump(obj, fd) + class CategoryInstaller(object): """ Class for making sure all category stuff is installed @@ -120,7 +129,7 @@ def check_install(homedir = None, model_list=None): Plugin Models which are user supplied. """ _model_dict = {model.name: model for model in model_list} - _model_list = _model_dict.keys() + _model_list = list(_model_dict.keys()) serialized_file = None if homedir is None: @@ -145,8 +154,8 @@ def check_install(homedir = None, model_list=None): try: by_model_dict.pop(model_name) model_enabled_dict.pop(model_name) - except Exception: - logger.error("CategoryInstaller: %s", sys.exc_value) + except Exception as exc: + logger.error("CategoryInstaller: %s", exc) else: add_list.remove(model_name) if del_name or (len(add_list) > 0): @@ -170,4 +179,4 @@ def check_install(homedir = None, model_list=None): CategoryInstaller._regenerate_master_dict(by_model_dict, model_enabled_dict) - json.dump(master_category_dict, open(serialized_file, 'wb')) + json_dump(master_category_dict, serialized_file) diff --git a/src/sas/sasgui/guiframe/CategoryManager.py b/src/sas/sasgui/guiframe/CategoryManager.py index e213899a2f..d79ee47105 100644 --- a/src/sas/sasgui/guiframe/CategoryManager.py +++ b/src/sas/sasgui/guiframe/CategoryManager.py @@ -229,7 +229,7 @@ def _fill_lists(self): model_name_list.sort() for model in model_name_list: - index = self.cat_list.InsertStringItem(sys.maxint, model) + index = self.cat_list.InsertStringItem(sys.maxsize, model) self.cat_list.SetStringItem(index, 1, \ str(self.by_model_dict[model]).\ replace("u'","").\ @@ -383,7 +383,7 @@ def _get_cat_list(self): Returns a simple list of categories """ cat_list = list() - for category in self.master_category_dict.iterkeys(): + for category in self.master_category_dict.keys(): if not category == 'Uncategorized': cat_list.append(category) diff --git a/src/sas/sasgui/guiframe/custom_pstats.py b/src/sas/sasgui/guiframe/custom_pstats.py index 4b05e19162..1580f03fe8 100644 --- a/src/sas/sasgui/guiframe/custom_pstats.py +++ b/src/sas/sasgui/guiframe/custom_pstats.py @@ -35,32 +35,32 @@ def write_stats(self, *amount): width = self.max_name_len if self.fcn_list: - list = self.fcn_list[:] + stats = self.fcn_list[:] temp_msg = " Ordered by: " + self.sort_type + '\n' else: - list = self.stats.keys() + stats = list(self.stats.keys()) temp_msg = " Random listing order was used\n" for selection in amount: - list, temp_msg = self.eval_print_amount(selection, list, temp_msg) + stats, temp_msg = self.eval_print_amount(selection, stats, temp_msg) - count = len(list) + count = len(stats) - if not list: - width, list = 0, list + if not stats: + width = 0 else: - msg += str(temp_msg) + '\n' + msg += str(temp_msg) + '\n' if count < len(self.stats): width = 0 - for func in list: + for func in stats: if len(func_std_string(func)) > width: width = len(func_std_string(func)) - width, list = width+2, list - if list: + width = width+2 + if stats: msg += ' ncalls tottime percall cumtime percall' msg += ' filename:lineno(function)' + "\n" - for func in list: + for func in stats: cc, nc, tt, ct, callers = self.stats[func] c = str(nc) if nc != cc: diff --git a/src/sas/sasgui/guiframe/data_manager.py b/src/sas/sasgui/guiframe/data_manager.py index c2e2f40428..1fb48cf3a6 100644 --- a/src/sas/sasgui/guiframe/data_manager.py +++ b/src/sas/sasgui/guiframe/data_manager.py @@ -50,7 +50,7 @@ def __str__(self): _str = "" _str += "No of states is %s \n" % str(len(self.stored_data)) n_count = 0 - for value in self.stored_data.values(): + for value in self.stored_data.values(): n_count += 1 _str += "State No %s \n" % str(n_count) _str += str(value) + "\n" @@ -133,7 +133,7 @@ def add_data(self, data_list): """ receive a list of """ - for id, data in data_list.iteritems(): + for id, data in data_list.items(): if id in self.stored_data: msg = "Data manager already stores %s" % str(data.name) msg += "" @@ -149,12 +149,12 @@ def add_data(self, data_list): def update_data(self, prev_data, new_data): """ """ - if prev_data.id not in self.stored_data.keys(): + if prev_data.id not in self.stored_data: return None, {} data_state = self.stored_data[prev_data.id] self.stored_data[new_data.id] = data_state.clone() self.stored_data[new_data.id].data = new_data - if prev_data.id in self.stored_data.keys(): + if prev_data.id in self.stored_data: del self.stored_data[prev_data.id] return prev_data.id, {new_data.id: self.stored_data[new_data.id]} @@ -164,7 +164,7 @@ def update_theory(self, theory, data_id=None, state=None): uid = data_id if data_id is None and theory is not None: uid = theory.id - if uid in self.stored_data.keys(): + if uid in self.stored_data: data_state = self.stored_data[uid] else: data_state = DataState() @@ -194,7 +194,7 @@ def get_by_id(self, id_list=None): theory_list = data_state.get_theory() if search_id == d_id: _selected_data[search_id] = data - if search_id in theory_list.keys(): + if search_id in theory_list: _selected_theory_list[search_id] = theory_list[search_id] return _selected_data, _selected_theory_list @@ -203,7 +203,7 @@ def get_by_id(self, id_list=None): def freeze(self, theory_id): """ """ - return self.freeze_theory(self.stored_data.keys(), theory_id) + return self.freeze_theory(list(self.stored_data.keys()), theory_id) def freeze_theory(self, data_id, theory_id): """ @@ -214,7 +214,7 @@ def freeze_theory(self, data_id, theory_id): data_state = self.stored_data[d_id] theory_list = data_state.get_theory() for t_id in theory_id: - if t_id in theory_list.keys(): + if t_id in theory_list: theory_data, theory_state = theory_list[t_id] new_theory = copy.deepcopy(theory_data) new_theory.id = time.time() @@ -234,7 +234,7 @@ def delete_data(self, data_id, theory_id=None, delete_all=False): """ """ for d_id in data_id: - if d_id in self.stored_data.keys(): + if d_id in self.stored_data: data_state = self.stored_data[d_id] if data_state.data.name in self.data_name_dict: del self.data_name_dict[data_state.data.name] @@ -252,7 +252,7 @@ def delete_theory(self, data_id, theory_id): if d_id in self.stored_data: data_state = self.stored_data[d_id] theory_list = data_state.get_theory() - if theory_id in theory_list.keys(): + if theory_id in theory_list: del theory_list[theory_id] #del pure theory self.delete_by_id(theory_id) @@ -272,7 +272,7 @@ def get_by_name(self, name_list=None): """ _selected_data = {} for selected_name in name_list: - for id, data_state in self.stored_data.iteritems(): + for id, data_state in self.stored_data.items(): if data_state.data.name == selected_name: _selected_data[id] = data_state.data return _selected_data @@ -282,7 +282,7 @@ def delete_by_name(self, name_list=None): save data and path """ for selected_name in name_list: - for id, data_state in self.stored_data.iteritems(): + for id, data_state in self.stored_data.items(): if data_state.data.name == selected_name: del self.stored_data[id] @@ -292,7 +292,7 @@ def get_data_state(self, data_id): """ _selected_data_state = {} for id in data_id: - if id in self.stored_data.keys(): + if id in self.stored_data: _selected_data_state[id] = self.stored_data[id] return _selected_data_state @@ -302,5 +302,3 @@ def get_all_data(self): """ return self.stored_data - - \ No newline at end of file diff --git a/src/sas/sasgui/guiframe/data_panel.py b/src/sas/sasgui/guiframe/data_panel.py index 576513ff1f..210f8a2b6a 100644 --- a/src/sas/sasgui/guiframe/data_panel.py +++ b/src/sas/sasgui/guiframe/data_panel.py @@ -12,12 +12,13 @@ """ from __future__ import print_function -import wx -from wx.build import build_options - import sys + +import wx from wx.lib.scrolledpanel import ScrolledPanel import wx.lib.agw.customtreectrl as CT +#from wx.build import build_options + from sas.sasgui.guiframe.dataFitting import Data1D from sas.sasgui.guiframe.dataFitting import Data2D from sas.sasgui.guiframe.panel_base import PanelBase @@ -443,9 +444,9 @@ def _get_data_selection(self, event): data_list, theory_list = \ self.parent.get_data_manager().get_by_id(id_list=[id]) if data_list: - data = data_list.values()[0] + data = list(data_list.values())[0] if data is None: - data = theory_list.values()[0][0] + data = list(theory_list.values())[0][0] return data def on_edit_data(self, event): @@ -666,7 +667,7 @@ def load_data_list(self, list): add need data with its theory under the tree """ if list: - for state_id, dstate in list.iteritems(): + for state_id, dstate in list.items(): data = dstate.get_data() theory_list = dstate.get_theory() if data is not None: @@ -763,7 +764,7 @@ def append_theory(self, state_id, theory_list): """ if not theory_list: return - if state_id not in self.list_cb_data.keys(): + if state_id not in self.list_cb_data: root = self.tree_ctrl_theory.root tree = self.tree_ctrl_theory else: @@ -782,11 +783,11 @@ def append_theory_helper(self, tree, root, state_id, theory_list): """ Append theory helper """ - if state_id in self.list_cb_theory.keys(): + if state_id in self.list_cb_theory: # update current list of theory for this data theory_list_ctrl = self.list_cb_theory[state_id] - for theory_id, item in theory_list.iteritems(): + for theory_id, item in theory_list.items(): theory_data, _ = item if theory_data is None: name = "Unknown" @@ -827,7 +828,7 @@ def append_theory_helper(self, tree, root, state_id, theory_list): else: # data didn't have a theory associated it before theory_list_ctrl = {} - for theory_id, item in theory_list.iteritems(): + for theory_id, item in theory_list.items(): theory_data, _ = item if theory_data is not None: name = theory_data.name @@ -867,7 +868,7 @@ def set_data_helper(self): state_to_plot.append(state_id) for theory_dict in self.list_cb_theory.values(): - for _, value in theory_dict.iteritems(): + for _, value in theory_dict.items(): item, _, _ = value if item.IsChecked(): theory_id, _, state_id = self.tree_ctrl.GetItemPyData(item) @@ -923,17 +924,17 @@ def on_remove(self, event, prompt=True): data_key = [] theory_key = [] # remove data from treectrl - for d_key, item in self.list_cb_data.iteritems(): + for d_key, item in self.list_cb_data.items(): data_c, _, _, _, _, _, _, _ = item if data_c.IsChecked(): self.tree_ctrl.Delete(data_c) data_key.append(d_key) - if d_key in self.list_cb_theory.keys(): + if d_key in self.list_cb_theory: theory_list_ctrl = self.list_cb_theory[d_key] - theory_to_remove += theory_list_ctrl.keys() + theory_to_remove += list(theory_list_ctrl.keys()) # Remove theory from treectrl - for _, theory_dict in self.list_cb_theory.iteritems(): - for key, value in theory_dict.iteritems(): + for _, theory_dict in self.list_cb_theory.items(): + for key, value in theory_dict.items(): item, _, _ = value if item.IsChecked(): try: @@ -949,9 +950,9 @@ def on_remove(self, event, prompt=True): del self.list_cb_theory[key] # remove theory references independently of data for key in theory_key: - for _, theory_dict in self.list_cb_theory.iteritems(): + for _, theory_dict in self.list_cb_theory.items(): if key in theory_dict: - for key, value in theory_dict.iteritems(): + for key, value in theory_dict.items(): item, _, _ = value if item.IsChecked(): try: @@ -1046,7 +1047,7 @@ def set_panel_on_focus(self, name=None): """ if self.cb_plotpanel and self.cb_plotpanel.IsBeingDeleted(): return - for _, value in self.parent.plot_panels.iteritems(): + for _, value in self.parent.plot_panels.items(): name_plot_panel = str(value.window_caption) if name_plot_panel not in self.cb_plotpanel.GetItems(): self.cb_plotpanel.Append(name_plot_panel, value) @@ -1128,7 +1129,7 @@ def on_help(self, event): #import documentation window here to avoid circular imports #if put at top of file with rest of imports. - from documentation_window import DocumentationWindow + from .documentation_window import DocumentationWindow _TreeLocation = "user/sasgui/guiframe/data_explorer_help.html" _doc_viewer = DocumentationWindow(self, -1, _TreeLocation, "", @@ -1498,8 +1499,8 @@ def set_data_state(data=None, path=None, theory=None, state=None): window.load_data_list(list=data_list1) window.Show(True) window.load_data_list(list=temp_data_list) - except: + except Exception as exc: # raise - print("error", sys.exc_value) + print("error", exc) app.MainLoop() diff --git a/src/sas/sasgui/guiframe/data_processor.py b/src/sas/sasgui/guiframe/data_processor.py index 4788b0a2e6..b6e8cf4896 100644 --- a/src/sas/sasgui/guiframe/data_processor.py +++ b/src/sas/sasgui/guiframe/data_processor.py @@ -233,7 +233,12 @@ def __init__(self, parent, panel=None): # NOTE: the following bind to standard sheet methods that are # overriden in this subclassn - actually we have currently # disabled the on_context_menu that would override the OnRightClick - self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnCellChange) + try: + EVT_GRID_CELL_CHANGED = wx.grid.EVT_GRID_CELL_CHANGED + except AttributeError: + # CRUFT: wx 3.x uses CHANGE rather than CHANGING/CHANGED + EVT_GRID_CELL_CHANGED = wx.grid.EVT_GRID_CELL_CHANGE + self.Bind(EVT_GRID_CELL_CHANGED, self.OnCellChange) self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnLeftClick) self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self.OnRightClick) #self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.OnLeftDoubleClick) @@ -560,7 +565,7 @@ def remove_column(self, col, numCols=1): if row < self.max_row_touse: value = self.GetCellValue(row, col) self.data[col_name].append(value) - for k, value_list in self.data.iteritems(): + for k, value_list in self.data.items(): if k != col_name: length = len(value_list) if length < self.max_row_touse: @@ -620,7 +625,7 @@ def insert_column(self, col, col_name): self.InsertCols(pos=col, numCols=1, updateLabels=True) if col_name.strip() != "Empty": self.SetCellValue(row, col, str(col_name.strip())) - if col_name in self.data.keys(): + if col_name in self.data: value_list = self.data[col_name] cell_row = 1 for value in value_list: @@ -673,7 +678,7 @@ def set_data(self, data_inputs, data_outputs, details, file_name): if len(self.data_outputs) > 0: self._cols = self.GetNumberCols() self._rows = self.GetNumberRows() - self.col_names = self.data_outputs.keys() + self.col_names = list(self.data_outputs.keys()) self.col_names.sort() nbr_user_cols = len(self.col_names) #Add more columns to the grid if necessary @@ -681,7 +686,7 @@ def set_data(self, data_inputs, data_outputs, details, file_name): new_col_nbr = nbr_user_cols - self._cols + 1 self.AppendCols(new_col_nbr, True) #Add more rows to the grid if necessary - nbr_user_row = len(self.data_outputs.values()[0]) + nbr_user_row = len(list(self.data_outputs.values())[0]) if nbr_user_row > self._rows + 1: new_row_nbr = nbr_user_row - self._rows + 1 self.AppendRows(new_row_nbr, True) @@ -908,20 +913,20 @@ def on_edit_axis(self): if c != col: msg = "Edit axis doesn't understand this selection.\n" msg += "Please select only one column" - raise ValueError, msg + raise ValueError(msg) for (_, cell_col) in grid.selected_cells: if cell_col != col: msg = "Cannot use cells from different columns for " msg += "this operation.\n" msg += "Please select elements of the same col.\n" - raise ValueError, msg + raise ValueError(msg) # Finally check the highlighted cell if any cells missing self.get_highlighted_row(True) else: msg = "No item selected.\n" msg += "Please select only one column or one cell" - raise ValueError, msg + raise ValueError(msg) return grid.selected_cells def get_highlighted_row(self, is_number=True): @@ -1325,7 +1330,7 @@ def on_plot(self, event): try: if sentence.strip() == "": msg = "Select column values for x axis" - raise ValueError, msg + raise ValueError(msg) except: msg = "X axis value error." wx.PostEvent(self.parent.parent, StatusEvent(status=msg, info="error")) @@ -1344,7 +1349,7 @@ def on_plot(self, event): try: if sentence.strip() == "": msg = "select value for y axis" - raise ValueError, msg + raise ValueError(msg) except: msg = "Y axis value error." wx.PostEvent(self.parent.parent, StatusEvent(status=msg, info="error")) @@ -1439,13 +1444,13 @@ def get_sentence(self, dict, sentence, column_names): Get sentence from dict """ - for tok, (col_name, list) in dict.iteritems(): + for tok, (col_name, list) in dict.items(): col = column_names[col_name] axis = self.get_plot_axis(col, list) if axis is None: return None sentence = sentence.replace(tok, "numpy.array(%s)" % str(axis)) - for key, value in FUNC_DICT.iteritems(): + for key, value in FUNC_DICT.items(): sentence = sentence.replace(key.lower(), value) return sentence @@ -1545,8 +1550,8 @@ def on_edit_axis(self, event): try: cell_list = self.notebook.on_edit_axis() label, title = self.create_axis_label(cell_list) - except: - msg = str(sys.exc_value) + except Exception as exc: + msg = str(exc) wx.PostEvent(self.parent.parent, StatusEvent(status=msg, info="error")) return tcrtl = event.GetEventObject() @@ -2035,7 +2040,7 @@ def onselect(self, event=None): data_input["index5"] = [10, 20, 40, 50] frame = GridFrame(data_outputs=data, data_inputs=data_input) frame.Show(True) - except: - print(sys.exc_value) + except Exception as exc: + print(exc) app.MainLoop() diff --git a/src/sas/sasgui/guiframe/data_state.py b/src/sas/sasgui/guiframe/data_state.py index 7e75d46e34..7be8b14ff5 100644 --- a/src/sas/sasgui/guiframe/data_state.py +++ b/src/sas/sasgui/guiframe/data_state.py @@ -36,7 +36,7 @@ def __str__(self): _str += "Data ID : %s \n" % str(self.data.id) _str += "Theories available: %s \n" % len(self.theory_list) if self.theory_list: - for id, item in self.theory_list.iteritems(): + for id, item in self.theory_list.items(): theory_data, theory_state = item _str += "Theory name : %s \n" % str(theory_data.name) _str += "Theory ID : %s \n" % str(id) @@ -52,7 +52,7 @@ def clone(self): obj.path = self.path obj.message = self.message obj.id = self.id - for id, item in self.theory_list.iteritems(): + for id, item in self.theory_list.items(): theory_data, theory_state = item state = None if theory_state is not None: @@ -94,7 +94,7 @@ def set_theory(self, theory_data, theory_state=None): """ """ self.theory_list[theory_data.id] = [theory_data, theory_state] - data, state = self.theory_list.values()[0] + data, state = list(self.theory_list.values())[0] def get_theory(self): return self.theory_list @@ -105,4 +105,3 @@ def get_message(self): """ return self.message - \ No newline at end of file diff --git a/src/sas/sasgui/guiframe/gui_manager.py b/src/sas/sasgui/guiframe/gui_manager.py index 51157c1622..2af859f94a 100644 --- a/src/sas/sasgui/guiframe/gui_manager.py +++ b/src/sas/sasgui/guiframe/gui_manager.py @@ -12,8 +12,6 @@ ################################################################################ -import wx -import wx.aui import os import sys import time @@ -24,6 +22,10 @@ import traceback import urllib import json +import copy + +import wx +import wx.aui from matplotlib import _pylab_helpers @@ -274,7 +276,7 @@ def get_client_size(self): """ return client size tuple """ - width, height = self.GetClientSizeTuple() + width, height = self.GetClientSize() height -= 45 # Adjust toolbar height toolbar = self.GetToolBar() @@ -349,11 +351,10 @@ def on_read_batch_tofile(self, base): dlg.Destroy() try: self.read_batch_tofile(file_name=path) - except: + except Exception as exc: msg = "Error occurred when reading the file; %s\n" % path - msg += "%s\n" % sys.exc_value - wx.PostEvent(self, StatusEvent(status=msg, - info="error")) + msg += "%s\n" % exc + wx.PostEvent(self, StatusEvent(status=msg, info="error")) def read_batch_tofile(self, file_name): """ @@ -693,10 +694,10 @@ def build_gui(self): try: self.load_from_cmd(self._input_file) - except: + except Exception as exc: msg = "%s Cannot load file %s\n" % (str(APPLICATION_NAME), str(self._input_file)) - msg += str(sys.exc_value) + '\n' + msg += str(exc) + '\n' logger.error(msg) if self._data_panel is not None and len(self.plugins) > 0: self._data_panel.fill_cbox_analysis(self.plugins) @@ -785,9 +786,9 @@ def _get_local_plugins(self): import data_loader self._data_plugin = data_loader.Plugin() plugins.append(self._data_plugin) - except: + except Exception as exc: msg = "ViewerFrame._get_local_plugins:" - msg += "cannot import dataloader plugin.\n %s" % sys.exc_value + msg += "cannot import dataloader plugin.\n %s" % exc logger.error(msg) if style2 == GUIFRAME.PLOTTING_ON: try: @@ -795,9 +796,9 @@ def _get_local_plugins(self): import plotting self._plotting_plugin = plotting.Plugin() plugins.append(self._plotting_plugin) - except: + except Exception as exc: msg = "ViewerFrame._get_local_plugins:" - msg += "cannot import plotting plugin.\n %s" % sys.exc_value + msg += "cannot import plotting plugin.\n %s" % exc logger.error(msg) return plugins @@ -844,20 +845,20 @@ def _find_plugins(self, dir="perspectives"): plugins.append(module.Plugin()) msg = "Found plug-in: %s" % module.PLUGIN_ID logger.info(msg) - except: + except Exception as exc: msg = "Error accessing PluginPanel" - msg += " in %s\n %s" % (name, sys.exc_value) + msg += " in %s\n %s" % (name, exc) config.printEVT(msg) - except: - msg = "ViewerFrame._find_plugins: %s" % sys.exc_value + except Exception as exc: + msg = "ViewerFrame._find_plugins: %s" % exc logger.error(msg) finally: if file is not None: file.close() - except: + except Exception as exc: # Should raise and catch at a higher level and # display error on status bar - logger.error(sys.exc_value) + logger.error(exc) return plugins @@ -1587,7 +1588,7 @@ def _on_status_event(self, evt): Display status message """ # This CallAfter fixes many crashes on MAC. - wx.CallAfter(self.sb.set_status, evt) + wx.CallAfter(self.sb.set_status, evt.Clone()) def on_view(self, evt): """ @@ -1631,7 +1632,7 @@ def delete_panel(self, uid): """ ID = str(uid) config.printEVT("delete_panel: %s" % ID) - if ID in self.panels.keys(): + if ID in self.panels: self.panel_on_focus = None panel = self.panels[ID] @@ -1643,9 +1644,9 @@ def delete_panel(self, uid): self.schedule_full_draw_list.remove(panel) # delete uid number not str(uid) - if ID in self.plot_panels.keys(): + if ID in self.plot_panels: del self.plot_panels[ID] - if ID in self.panels.keys(): + if ID in self.panels: del self.panels[ID] else: logger.error("delete_panel: No such plot id as %s" % ID) @@ -1679,9 +1680,9 @@ def get_data(self, path): elif extension == APPLICATION_STATE_EXTENSION: try: reader.read(path) - except: + except Exception as exc: msg = "DataLoader Error: Encounted Non-ASCII character" - msg += "\n(%s)" % sys.exc_value + msg += "\n(%s)" % exc wx.PostEvent(self, StatusEvent(status=msg, info="error", type="stop")) @@ -1762,10 +1763,10 @@ def load_data(self, path): output[data.id] = data self.add_data(data_list=output) - except: + except Exception as exc: error_message = "Error while loading" error_message += " Data from cmd:\n %s\n" % str(path) - error_message += str(sys.exc_value) + "\n" + error_message += str(exc) + "\n" logger.error(error_message) def load_folder(self, path): @@ -1783,10 +1784,10 @@ def load_folder(self, path): self._data_plugin.get_data(file_list) else: return - except: + except Exception as exc: error_message = "Error while loading" error_message += " Data folder from cmd:\n %s\n" % str(path) - error_message += str(sys.exc_value) + "\n" + error_message += str(exc) + "\n" logger.error(error_message) def _on_open_state_application(self, event): @@ -1853,8 +1854,8 @@ def _on_open_state_project(self, event): if msg_box.ShowModal() == wx.ID_OK: self._data_panel.selection_cbox.SetValue('Select all Data') self._data_panel._on_selection_type(None) - for _, theory_dict in self._data_panel.list_cb_theory.iteritems(): - for key, value in theory_dict.iteritems(): + for _, theory_dict in self._data_panel.list_cb_theory.items(): + for key, value in theory_dict.items(): item, _, _ = value item.Check(True) @@ -1962,7 +1963,7 @@ def on_save_helper(self, doc, reader, panel, path): if reader is not None: # case of a panel with multi-pages if hasattr(panel, "opened_pages"): - for _, page in panel.opened_pages.iteritems(): + for _, page in panel.opened_pages.items(): data = page.get_data() # state must be cloned state = page.get_state().clone() @@ -2084,7 +2085,7 @@ def _process_version(self, version_info, standalone=True): msg = "Could not connect to the application server." msg += " Please try again later." self.SetStatusText(msg) - elif cmp(version, config.__version__) > 0: + elif version > config.__version__: msg = "Version %s is available! " % str(version) if not standalone: import webbrowser @@ -2100,9 +2101,9 @@ def _process_version(self, version_info, standalone=True): msg = "You have the latest version" msg += " of %s" % str(config.__appname__) self.SetStatusText(msg) - except: + except Exception as exc: msg = "guiframe: could not get latest application" - msg += " version number\n %s" % sys.exc_value + msg += " version number\n %s" % exc logger.error(msg) if not standalone: msg = "Could not connect to the application server." @@ -2142,7 +2143,7 @@ def _onRelease(self, evt): """ # S King, Sep 2018 - from documentation_window import DocumentationWindow + from .documentation_window import DocumentationWindow _TreeLocation = "user/release.html" DocumentationWindow(self, -1, _TreeLocation, "", "SasView Documentation") @@ -2163,7 +2164,7 @@ def _onTutorial(self, evt): # tutorials # S King, Sep 2018 - from documentation_window import DocumentationWindow + from .documentation_window import DocumentationWindow _TreeLocation = "user/tutorial.html" DocumentationWindow(self, -1, _TreeLocation, "", "SasView Documentation") @@ -2178,7 +2179,7 @@ def _onSphinxDocs(self, evt): """ # Running SasView "in-place" using run.py means the docs will be in a # different place than they would otherwise. - from documentation_window import DocumentationWindow + from .documentation_window import DocumentationWindow _TreeLocation = "user/user.html" DocumentationWindow(self, -1, _TreeLocation, "", "SasView Documentation") @@ -2226,7 +2227,7 @@ def set_perspective(self, panels): style = self.__gui_style & GUIFRAME.MANAGER_ON if (style == GUIFRAME.MANAGER_ON) \ and self.panels[item] == self._data_panel: - if 'data_panel' in self.panels.keys(): + if 'data_panel' in self.panels: frame = self.panels['data_panel'].get_frame() if frame is None: continue @@ -2278,7 +2279,7 @@ def add_data(self, data_list): self.add_data_helper(data_list) # set data in the data panel if self._data_panel is not None: - data_state = self._data_manager.get_data_state(data_list.keys()) + data_state = self._data_manager.get_data_state(list(data_list.keys())) self._data_panel.load_data_list(data_state) # if the data panel is shown wait for the user to press a button # to send data to the current perspective. if the panel is not @@ -2290,7 +2291,7 @@ def add_data(self, data_list): self._data_panel.frame.Show(True) else: # automatically send that to the current perspective - self.set_data(data_id=data_list.keys()) + self.set_data(data_id=list(data_list.keys())) def set_data(self, data_id, theory_id=None): """ @@ -2298,7 +2299,7 @@ def set_data(self, data_id, theory_id=None): """ list_data, _ = self._data_manager.get_by_id(data_id) if self._current_perspective is not None: - self._current_perspective.set_data(list_data.values()) + self._current_perspective.set_data(list(list_data.values())) else: msg = "Guiframe does not have a current perspective" @@ -2310,9 +2311,9 @@ def set_theory(self, state_id, theory_id=None): _, list_theory = self._data_manager.get_by_id(theory_id) if self._current_perspective is not None: try: - self._current_perspective.set_theory(list_theory.values()) - except: - msg = "Guiframe set_theory: \n" + str(sys.exc_value) + self._current_perspective.set_theory(list(list_theory.values())) + except Exception as exc: + msg = "Guiframe set_theory: \n" + str(exc) logger.info(msg) wx.PostEvent(self, StatusEvent(status=msg, info="error")) else: @@ -2326,7 +2327,7 @@ def plot_data(self, state_id, data_id=None, """ data_list, _ = self._data_manager.get_by_id(data_id) _, temp_list_theory = self._data_manager.get_by_id(theory_id) - total_plot_list = data_list.values() + total_plot_list = list(data_list.values()) for item in temp_list_theory.values(): theory_data, theory_state = item total_plot_list.append(theory_data) @@ -2375,7 +2376,7 @@ def remove_data(self, data_id, theory_id=None): plug.delete_data(temp) data_list, _ = self._data_manager.get_by_id(data_id) _, temp_list_theory = self._data_manager.get_by_id(theory_id) - total_plot_list = data_list.values() + total_plot_list = list(data_list.values()) for item in temp_list_theory.values(): theory_data, theory_state = item total_plot_list.append(theory_data) @@ -2398,8 +2399,8 @@ def _remove_res_plot(self, id): wx.PostEvent(self, NewPlotEvent(id=("res" + str(id)), group_id=("res" + str(id)), action='remove')) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) def save_data1d(self, data, fname): """ @@ -2503,7 +2504,7 @@ def show_data1d(self, data, name): data.filename wx.PostEvent(self, StatusEvent(status=msg, info="error")) - raise ValueError, msg + raise ValueError(msg) # text = str(data) text = data.__str__() text += 'Data Min Max:\n' @@ -2534,7 +2535,7 @@ def show_data1d(self, data, name): data.y[index], dy_val, dx_val) - from pdfview import TextFrame + from .pdfview import TextFrame frame = TextFrame(None, -1, "Data Info: %s" % data.name, text) # put icon self.put_icon(frame) @@ -2626,7 +2627,7 @@ def show_data2d(self, data, name): text += ".............\n" break - from pdfview import TextFrame + from .pdfview import TextFrame frame = TextFrame(None, -1, "Data Info: %s" % data.name, text) # put icon self.put_icon(frame) @@ -2693,7 +2694,7 @@ def enable_add_data(self, new_plot): return check = "Theory1D" is_theory = len(self.panel_on_focus.plots) <= 1 and \ - self.panel_on_focus.plots.values()[0].__class__.__name__ == check + list(self.panel_on_focus.plots.values())[0].__class__.__name__ == check is_data2d = hasattr(new_plot, 'data') @@ -3209,11 +3210,11 @@ def OnInit(self): path=SPLASH_SCREEN_PATH) else: self.frame.Show() - except: + except Exception as exc: if self.s_screen is not None: self.s_screen.Close() msg = "Cannot display splash screen\n" - msg += str(sys.exc_value) + msg += str(exc) logger.error(msg) self.frame.Show() @@ -3268,9 +3269,9 @@ def clean_plugin_models(self, path): file_path = os.path.join(model_folder, filename) if os.path.isfile(file_path): os.remove(file_path) - except: + except Exception as exc: logger.error("gui_manager.clean_plugin_models:\n %s" - % sys.exc_value) + % exc) def set_manager(self, manager): """ @@ -3363,6 +3364,11 @@ def window_placement(self, size): def display_splash_screen(self, parent, path=SPLASH_SCREEN_PATH): """Displays the splash screen. It will exactly cover the main frame.""" + try: + from wx.adv import SplashScreen, SPLASH_TIMEOUT, SPLASH_CENTRE_ON_SCREEN + except ImportError: + # CRUFT: wx 4 moved SplashScreen from wx to wx.adv + from wx import SplashScreen, SPLASH_TIMEOUT, SPLASH_CENTRE_ON_SCREEN # Prepare the picture. On a 2GHz intel cpu, this takes about a second. image = wx.Image(path, wx.BITMAP_TYPE_PNG) @@ -3379,15 +3385,15 @@ def display_splash_screen(self, parent, # # Note that on Linux, the timeout appears to occur immediately in which # case the splash screen disappears upon entering the event loop. - s_screen = wx.SplashScreen(bitmap=bm, - splashStyle=(wx.SPLASH_TIMEOUT | - wx.SPLASH_CENTRE_ON_SCREEN), - style=(wx.SIMPLE_BORDER | - wx.FRAME_NO_TASKBAR | - wx.FRAME_FLOAT_ON_PARENT), - milliseconds=SS_MAX_DISPLAY_TIME, - parent=parent, - id=wx.ID_ANY) + s_screen = SplashScreen(bitmap=bm, + splashStyle=(SPLASH_TIMEOUT | + SPLASH_CENTRE_ON_SCREEN), + style=(wx.SIMPLE_BORDER | + wx.FRAME_NO_TASKBAR | + wx.FRAME_FLOAT_ON_PARENT), + milliseconds=SS_MAX_DISPLAY_TIME, + parent=parent, + id=wx.ID_ANY) from sas.sasgui.guiframe.gui_statusbar import SPageStatusbar statusBar = SPageStatusbar(s_screen) s_screen.SetStatusBar(statusBar) diff --git a/src/sas/sasgui/guiframe/gui_statusbar.py b/src/sas/sasgui/guiframe/gui_statusbar.py index 741c0d1ec1..d2ce17f1e7 100644 --- a/src/sas/sasgui/guiframe/gui_statusbar.py +++ b/src/sas/sasgui/guiframe/gui_statusbar.py @@ -85,7 +85,9 @@ def set_message(self, status="", event=None): icon_bmp = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_TOOLBAR) self.msg_txt.Newline() - self.msg_txt.WriteBitmap(icon_bmp) + # wx 3 has WriteImage and WriteBitmap; not sure if there + # is any difference between them. wx 4 has only WriteImage. + self.msg_txt.WriteImage(icon_bmp) self.msg_txt.BeginTextColour(color) self.msg_txt.WriteText("\t") self.msg_txt.AppendText(status) diff --git a/src/sas/sasgui/guiframe/gui_style.py b/src/sas/sasgui/guiframe/gui_style.py index 71bfc97b8b..1fc2be2621 100644 --- a/src/sas/sasgui/guiframe/gui_style.py +++ b/src/sas/sasgui/guiframe/gui_style.py @@ -57,26 +57,32 @@ class GUIFRAME_ICON: ZOOM_ID_PATH = os.path.join(PATH, 'search_pan.png') DRAG_ID_PATH = os.path.join(PATH, 'drag_hand.png') RESET_ID_PATH = os.path.join(PATH, 'reset.png') - PREVIEW_ID_PATH = os.path.join(PATH, 'report.png') + REPORT_ID_PATH = os.path.join(PATH, 'report.png') + PREVIEW_ID_PATH = os.path.join(PATH, 'preview.png') PRINT_ID_PATH = os.path.join(PATH, 'printer.png') HIDE_ID_PATH = os.path.join(PATH, 'hide.png') - - SAVE_ICON = wx.Image(os.path.join(PATH, 'save.png')) - UNDO_ICON = wx.Image(os.path.join(PATH, 'undo.png')) - REDO_ICON = wx.Image(os.path.join(PATH, 'redo.png')) - COPY_ICON = wx.Image(os.path.join(PATH, 'copy.png')) - PASTE_ICON = wx.Image(os.path.join(PATH, 'paste.png')) - BOOKMARK_ICON = wx.Image(os.path.join(PATH, 'bookmark.png')) - ZOOM_IN_ICON = wx.Image(os.path.join(PATH, 'zoom_in.png')) - ZOOM_OUT_ICON = wx.Image(os.path.join(PATH, 'zoom_out.png')) - ZOOM_ICON = wx.Image(os.path.join(PATH, 'search_pan.png')) - DRAG_ICON = wx.Image(os.path.join(PATH, 'drag_hand.png')) - RESET_ICON = wx.Image(os.path.join(PATH, 'reset.png')) - REPORT_ICON = wx.Image(os.path.join(PATH, 'report.png')) - PREVIEW_ICON = wx.Image(os.path.join(PATH, 'preview.png')) - PRINT_ICON = wx.Image(os.path.join(PATH, 'printer.png')) - HIDE_ICON = wx.Image(os.path.join(PATH, 'hide.png')) + # Note: wx 4 requires that the app be defined before + # the images are loaded, so they can't be processed + # at module load time. Instead, need to load icons + # when the app is created. + @classmethod + def load_icons(cls): + cls.SAVE_ICON = wx.Image(cls.SAVE_ICON_PATH) + cls.UNDO_ICON = wx.Image(cls.UNDO_ICON_PATH) + cls.REDO_ICON = wx.Image(cls.REDO_ICON_PATH) + cls.COPY_ICON = wx.Image(cls.COPY_ICON_PATH) + cls.PASTE_ICON = wx.Image(cls.PASTE_ICON_PATH) + cls.BOOKMARK_ICON = wx.Image(cls.BOOKMARK_ICON_PATH) + cls.ZOOM_IN_ICON = wx.Image(cls.ZOOM_IN_ID_PATH) + cls.ZOOM_OUT_ICON = wx.Image(cls.ZOOM_OUT_ID_PATH) + cls.ZOOM_ICON = wx.Image(cls.ZOOM_ID_PATH) + cls.DRAG_ICON = wx.Image(cls.DRAG_ID_PATH) + cls.RESET_ICON = wx.Image(cls.RESET_ID_PATH) + cls.REPORT_ICON = wx.Image(cls.REPORT_ID_PATH) + cls.PREVIEW_ICON = wx.Image(cls.PREVIEW_ID_PATH) + cls.PRINT_ICON = wx.Image(cls.PRINT_ID_PATH) + cls.HIDE_ICON = wx.Image(cls.HIDE_ID_PATH) if __name__ == "__main__": @@ -89,4 +95,4 @@ class GUIFRAME_ICON: style1 = GUIFRAME.MULTIPLE_APPLICATIONS style1 &= (~GUIFRAME.MANAGER_ON) print(style1 == GUIFRAME.DEFAULT_STYLE) - print(style1) \ No newline at end of file + print(style1) diff --git a/src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py b/src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py index f1f8384b4b..75888ca26f 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py +++ b/src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py @@ -69,7 +69,7 @@ def load_data(self, event): if item in cards: cards.remove(item) wlist = '|'.join(cards) - style = wx.OPEN | wx.FD_MULTIPLE + style = wx.FD_OPEN | wx.FD_MULTIPLE dlg = wx.FileDialog(self.parent, "Choose a file", self._default_save_location, "", @@ -195,7 +195,7 @@ def get_data(self, path, format=None): output, error_message) if data_error: - if basename in file_errors.keys(): + if basename in file_errors: file_errors[basename] += [error_message] else: file_errors[basename] = [error_message] @@ -218,7 +218,7 @@ def get_data(self, path, format=None): if len(file_errors) > 0: error_message = "" - for filename, error_array in file_errors.iteritems(): + for filename, error_array in file_errors.items(): error_message += "The following issues were found whilst " error_message += "loading {}:\n".format(filename) for message in error_array: diff --git a/src/sas/sasgui/guiframe/local_perspectives/data_loader/load_thread.py b/src/sas/sasgui/guiframe/local_perspectives/data_loader/load_thread.py index 59949155e3..ed75834f9f 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/data_loader/load_thread.py +++ b/src/sas/sasgui/guiframe/local_perspectives/data_loader/load_thread.py @@ -71,9 +71,9 @@ def compute(self): message = "Loading ..." + str(path) + "\n" if self.updatefn is not None: self.updatefn(output=output, message=message) - except: + except Exception as exc: error_message = "Error while loading: %s\n" % str(path) - error_message += str(sys.exc_value) + "\n" + error_message += str(exc) + "\n" self.updatefn(output=output, message=error_message) message = "Loading Complete!" diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/AnnulusSlicer.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/AnnulusSlicer.py index 22d5b8a505..62a357a860 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/AnnulusSlicer.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/AnnulusSlicer.py @@ -6,16 +6,18 @@ # import math -import wx # from copy import deepcopy -# Debug printout + +import wx + from sas.sasgui.guiframe.events import NewPlotEvent from sas.sasgui.guiframe.events import StatusEvent from sas.sasgui.guiframe.events import SlicerParameterEvent from sas.sasgui.guiframe.events import EVT_SLICER_PARS -from BaseInteractor import _BaseInteractor from sas.sasgui.guiframe.dataFitting import Data1D +from .BaseInteractor import _BaseInteractor + class AnnulusInteractor(_BaseInteractor): """ Select an annulus through a 2D plot. diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/Arc.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/Arc.py index 4697075090..9d5d7475d6 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/Arc.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/Arc.py @@ -3,9 +3,10 @@ """ import math -from BaseInteractor import _BaseInteractor from sas.sasgui.guiframe.events import SlicerParameterEvent +from .BaseInteractor import _BaseInteractor + class ArcInteractor(_BaseInteractor): """ Select an annulus through a 2D plot diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/AzimutSlicer.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/AzimutSlicer.py index 6a210fd2b4..60a143d0ea 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/AzimutSlicer.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/AzimutSlicer.py @@ -4,11 +4,14 @@ # TODO: NEED MAJOR REFACTOR # import math + import wx -from BaseInteractor import _BaseInteractor + from sas.sasgui.guiframe.events import NewPlotEvent from sas.sasgui.guiframe.events import EVT_SLICER_PARS +from .BaseInteractor import _BaseInteractor + class SectorInteractor(_BaseInteractor): """ Select an annulus through a 2D plot @@ -28,7 +31,7 @@ def __init__(self, base, axes, color='black', zorder=3): theta2 = -2 * math.pi / 3 # Inner circle - from Arc import ArcInteractor + from .Arc import ArcInteractor self.inner_circle = ArcInteractor(self, self.base.subplot, zorder=zorder, r=self.qmax / 2.0, @@ -42,7 +45,7 @@ def __init__(self, base, axes, color='black', zorder=3): theta2=theta2) self.outer_circle.qmax = self.qmax * 1.2 # self.outer_circle.set_cursor(self.base.qmax/1.8, 0) - from Edge import RadiusInteractor + from .Edge import RadiusInteractor self.right_edge = RadiusInteractor(self, self.base.subplot, zorder=zorder + 1, arc1=self.inner_circle, diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/Edge.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/Edge.py index c72d191481..e00f1e5052 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/Edge.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/Edge.py @@ -1,5 +1,6 @@ import math -from BaseInteractor import _BaseInteractor + +from .BaseInteractor import _BaseInteractor class RadiusInteractor(_BaseInteractor): diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter1D.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter1D.py index 3e198839de..465505d0ca 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter1D.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter1D.py @@ -10,19 +10,22 @@ ################################################################################ -import wx import sys import math -import numpy as np import logging + +import wx +import numpy as np + from sas.sasgui.plottools.PlotPanel import PlotPanel from sas.sasgui.guiframe.events import StatusEvent from sas.sasgui.guiframe.events import PanelOnFocusEvent from sas.sasgui.guiframe.utils import PanelMenu, IdList from sas.sasgui.guiframe.panel_base import PanelBase from sas.sasgui.guiframe.gui_style import GUIFRAME_ICON -from appearanceDialog import appearanceDialog -from graphAppearance import graphAppearance + +from .appearanceDialog import appearanceDialog +from .graphAppearance import graphAppearance logger = logging.getLogger(__name__) @@ -35,7 +38,7 @@ def find_key(dic, val): """return the key of dictionary dic given the value""" - return [k for k, v in dic.iteritems() if v == val][0] + return [k for k, v in dic.items() if v == val][0] class ModelPanel1D(PlotPanel, PanelBase): """ @@ -219,7 +222,7 @@ def on_plot_qrange(self, event=None): return if hasattr(event, 'is_corfunc'): self.is_corfunc = event.is_corfunc - if event.id in self.plots.keys(): + if event.id in self.plots: ctrl = event.ctrl self.cursor_id = event.id # Set line position and color @@ -242,8 +245,8 @@ def on_plot_qrange(self, event=None): position = self.get_data_xy_vals(xval) if position is not None and not self.is_corfunc: wx.PostEvent(self.parent, StatusEvent(status=position)) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) if not event.leftdown: # text event try: @@ -255,8 +258,8 @@ def on_plot_qrange(self, event=None): is_moved = True if is_moved: self.canvas.draw() - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) event.Skip() return self.q_ctrl = ctrl @@ -409,8 +412,8 @@ def cusor_line(self, event): ly[vl_ind].set_zorder(nop + 1) self.canvas.draw() self.q_ctrl[vl_ind].SetValue(str(pos_x)) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) def set_resizing(self, resizing=False): """ @@ -430,15 +433,15 @@ def remove_data_by_id(self, id): """ Remove data from plot """ - if id in self.plots.keys(): + if id in self.plots: data = self.plots[id] self.graph.delete(data) data_manager = self._manager.parent.get_data_manager() data_list, theory_list = data_manager.get_by_id(id_list=[id]) - if id in data_list.keys(): + if id in data_list: data = data_list[id] - if id in theory_list.keys(): + if id in theory_list: data = theory_list[id] del self.plots[id] @@ -456,7 +459,7 @@ def plot_data(self, data): """ if data.__class__.__name__ == 'Data2D': return - plot_keys = self.plots.keys() + plot_keys = list(self.plots.keys()) if data.id in plot_keys: # Recover panel prop.s xlo, xhi = self.subplot.get_xlim() @@ -475,7 +478,7 @@ def plot_data(self, data): ## Set the view scale for all plots try: self._onEVT_FUNC_PROPERTY() - except Exception, exc: + except Exception as exc: wx.PostEvent(self.parent, StatusEvent(status="Plotting Error: %s" % str(exc), info="error")) if self.is_zoomed: @@ -492,7 +495,7 @@ def plot_data(self, data): if IS_MAC: # MAC: forcing to plot 2D avg self.canvas._onDrawIdle() - except Exception, exc: + except Exception as exc: wx.PostEvent(self.parent, StatusEvent(status=\ "Plotting Error: %s" % str(exc), info="error")) self.toolbar.update() @@ -566,7 +569,7 @@ def _onRemove(self, event): event_id = event.GetId() self.set_selected_from_menu(menu, event_id) ## Check if there is a selected graph to remove - if self.graph.selected_plottable in self.plots.keys(): + if self.graph.selected_plottable in self.plots: graph_id = self.graph.selected_plottable self.remove_data_by_id(graph_id) @@ -602,7 +605,7 @@ def onContextMenu(self, event): name = plot.name plot_menu = wx.Menu() if self.graph.selected_plottable: - if not self.graph.selected_plottable in self.plots.keys(): + if not self.graph.selected_plottable in self.plots: continue if plot != self.plots[self.graph.selected_plottable]: continue @@ -622,9 +625,9 @@ def onContextMenu(self, event): try: plot_menu.Append(wx_id, item[0], name) wx.EVT_MENU(self, wx_id, item[2]) - except: + except Exception as exc: msg = "ModelPanel1D.onContextMenu: " - msg += "bad menu item %s" % sys.exc_value + msg += "bad menu item %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg)) plot_menu.AppendSeparator() diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter2D.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter2D.py index 8070ab27e1..88221edd74 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter2D.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter2D.py @@ -10,11 +10,14 @@ ################################################################################ -import wx import sys import math -import numpy as np import logging + +import wx +import numpy as np +from matplotlib.font_manager import FontProperties + from sas.sasgui.plottools.PlotPanel import PlotPanel from sas.sasgui.plottools.plottables import Graph from sas.sasgui.plottools.TextDialog import TextDialog @@ -23,11 +26,12 @@ from sas.sasgui.guiframe.events import PanelOnFocusEvent from sas.sasgui.guiframe.events import SlicerEvent from sas.sasgui.guiframe.utils import PanelMenu -from sas.sasgui.guiframe.local_perspectives.plotting.binder import BindArtist -from Plotter1D import ModelPanel1D +from sas.sasgui.guiframe.local_perspectives.plotting.binder import BindArtist from sas.sasgui.plottools.toolbar import NavigationToolBar -from matplotlib.font_manager import FontProperties -from graphAppearance import graphAppearance + +from .Plotter1D import ModelPanel1D +from .graphAppearance import graphAppearance + (InternalEvent, EVT_INTERNAL) = wx.lib.newevent.NewEvent() logger = logging.getLogger(__name__) @@ -40,7 +44,7 @@ def find_key(dic, val): """return the key of dictionary dic given the value""" - return [k for k, v in dic.iteritems() if v == val][0] + return [k for k, v in dic.items() if v == val][0] class NavigationToolBar2D(NavigationToolBar): @@ -199,7 +203,7 @@ def plot_data(self, data): return ## Update self.data2d with the current plot self.data2D = data - if data.id in self.plots.keys(): + if data.id in self.plots: #replace xlo, xhi = self.subplot.get_xlim() ylo, yhi = self.subplot.get_ylim() @@ -325,9 +329,9 @@ def onContextMenu(self, event): try: slicerpop.Append(wx_id, item[0], item[1]) wx.EVT_MENU(self, wx_id, item[2]) - except: + except Exception as exc: msg = "ModelPanel1D.onContextMenu: " - msg += "bad menu item %s" % sys.exc_value + msg += "bad menu item %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg)) slicerpop.AppendSeparator() @@ -446,7 +450,7 @@ def _onEditDetector(self, event): :param event: wx.menu event """ - import detector_dialog + from . import detector_dialog dialog = detector_dialog.DetectorDialog(self, -1, base=self.parent, reset_zmin_ctl=self.default_zmin_ctl, reset_zmax_ctl=self.default_zmax_ctl, cmap=self.cmap) @@ -629,7 +633,7 @@ def _onEditSlicer(self, event): """ if self.slicer is not None: - from parameters_panel_slicer import SlicerParameterPanel + from .parameters_panel_slicer import SlicerParameterPanel dialog = SlicerParameterPanel(self, -1, "Slicer Parameters") dialog.set_slicer(self.slicer.__class__.__name__, self.slicer.get_params()) @@ -640,7 +644,7 @@ def onSectorQ(self, event): """ Perform sector averaging on Q and draw sector slicer """ - from SectorSlicer import SectorInteractor + from .SectorSlicer import SectorInteractor self.onClearSlicer(event) wx.PostEvent(self, InternalEvent(slicer=SectorInteractor)) @@ -648,7 +652,7 @@ def onSectorPhi(self, event): """ Perform sector averaging on Phi and draw annulus slicer """ - from AnnulusSlicer import AnnulusInteractor + from .AnnulusSlicer import AnnulusInteractor self.onClearSlicer(event) wx.PostEvent(self, InternalEvent(slicer=AnnulusInteractor)) @@ -656,7 +660,7 @@ def onBoxSum(self, event): """ """ from sas.sasgui.guiframe.gui_manager import MDIFrame - from boxSum import BoxSum + from .boxSum import BoxSum self.onClearSlicer(event) self.slicer_z += 1 self.slicer = BoxSum(self, self.subplot, zorder=self.slicer_z) @@ -667,7 +671,7 @@ def onBoxSum(self, event): ## Value used to initially set the slicer panel params = self.slicer.get_params() ## Create a new panel to display results of summation of Data2D - from parameters_panel_boxsum import SlicerPanel + from .parameters_panel_boxsum import SlicerPanel win = MDIFrame(self.parent, None, 'None', (100, 200)) new_panel = SlicerPanel(parent=win, id=-1, base=self, type=self.slicer.__class__.__name__, @@ -698,7 +702,7 @@ def onBoxavgX(self, event): :param event: wx.menu event """ - from boxSlicer import BoxInteractorX + from .boxSlicer import BoxInteractorX self.onClearSlicer(event) wx.PostEvent(self, InternalEvent(slicer=BoxInteractorX)) @@ -710,7 +714,7 @@ def onBoxavgY(self, event): :param event: wx.menu event """ - from boxSlicer import BoxInteractorY + from .boxSlicer import BoxInteractorY self.onClearSlicer(event) wx.PostEvent(self, InternalEvent(slicer=BoxInteractorY)) diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py index 03ce2a3bd3..eb630ae2e1 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py @@ -2,14 +2,17 @@ Sector interactor """ import math + import wx -from BaseInteractor import _BaseInteractor + from sas.sasgui.guiframe.events import NewPlotEvent from sas.sasgui.guiframe.events import StatusEvent from sas.sasgui.guiframe.events import SlicerParameterEvent from sas.sasgui.guiframe.events import EVT_SLICER_PARS from sas.sasgui.guiframe.dataFitting import Data1D +from .BaseInteractor import _BaseInteractor + class SectorInteractor(_BaseInteractor): """ @@ -237,7 +240,7 @@ def get_params(self): if math.fabs(self.left_line.phi) != math.fabs(self.right_line.phi): msg = "Phi left and phi right are different" msg += " %f, %f" % (self.left_line.phi, self.right_line.phi) - raise ValueError, msg + raise ValueError(msg) params["Phi [deg]"] = self.main_line.theta * 180 / math.pi params["Delta_Phi [deg]"] = math.fabs(self.left_line.phi * 180 / math.pi) params["nbins"] = self.nbins diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/appearanceDialog.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/appearanceDialog.py index 028cf107b0..82c4249723 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/appearanceDialog.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/appearanceDialog.py @@ -152,7 +152,7 @@ def populate_symbol(self): """ Populate Symbols """ - self.sorted_symbo_labels = sorted(self.symbo_labels.iteritems(), + self.sorted_symbo_labels = sorted(self.symbo_labels.items(), key=operator.itemgetter(1)) self.sorted_sym_dic = {} i = 0 @@ -165,7 +165,7 @@ def populate_color(self): """ Populate Colors """ - sortedcolor_labels = sorted(self.color_labels.iteritems(), + sortedcolor_labels = sorted(self.color_labels.items(), key=operator.itemgetter(1)) for color in sortedcolor_labels: self.colorlistbox.Append(str(color[0])) @@ -196,7 +196,7 @@ def find_key(dic, val): """ Find key """ - return [k for k, v in dic.iteritems() if v == val][0] + return [k for k, v in dic.items() if v == val][0] def get_current_values(self): """ diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/binder.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/binder.py index 715e22ad5d..a73166445c 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/binder.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/binder.py @@ -1,8 +1,10 @@ """ Extension to MPL to support the binding of artists to key/mouse events. """ -import logging +from __future__ import print_function + import sys +import logging logger = logging.getLogger(__name__) @@ -15,6 +17,7 @@ class Selection(object): artist = None prop = {} + def __init__(self, artist=None, prop={}): self.artist, self.prop = artist, self.prop @@ -24,17 +27,20 @@ def __eq__(self, other): def __ne__(self, other): return self.artist is not other.artist - def __nonzero__(self): + def __bool__(self): return self.artist is not None + __nonzero__ = __bool__ + + class BindArtist(object): """ - Track keyboard modifiers for events. - TODO: Move keyboard modifier support into the backend. We cannot - TODO: properly support it from outside the windowing system since there - TODO: is no way to recognized whether shift is held down when the mouse - TODO: first clicks on the the application window. + Track keyboard modifiers for events. """ + # TODO: Move keyboard modifier support into the backend. We cannot + # TODO: properly support it from outside the windowing system since there + # TODO: is no way to recognized whether shift is held down when the mouse + # TODO: first clicks on the the application window. control, shift, alt, meta = False, False, False, False # Track doubleclick @@ -45,8 +51,10 @@ class BindArtist(object): events = ['enter', 'leave', 'motion', 'click', 'dclick', 'drag', 'release', 'scroll', 'key', 'keyup'] # TODO: Need our own event structure + def __init__(self, figure): canvas = figure.canvas + # Link to keyboard/mouse try: self._connections = [ @@ -58,7 +66,7 @@ def __init__(self, figure): canvas.mpl_connect('scroll_event', self._onScroll) ] except: - # print "bypassing scroll_event: wrong matplotlib version" + logger.warn("bypassing scroll_event: wrong matplotlib version") self._connections = [ canvas.mpl_connect('motion_notify_event', self._onMotion), canvas.mpl_connect('button_press_event', self._onClick), @@ -66,12 +74,16 @@ def __init__(self, figure): canvas.mpl_connect('key_press_event', self._onKey), canvas.mpl_connect('key_release_event', self._onKeyRelease), ] + # Turn off picker if it hasn't already been done try: canvas.mpl_disconnect(canvas.button_pick_id) canvas.mpl_disconnect(canvas.scroll_pick_id) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) + + self._current = None + self._actions = {} self.canvas = canvas self.figure = figure self.clearall() @@ -82,7 +94,6 @@ def clear(self, *artists): Remove connections for artists h1, h2, ... Use clearall() to reset all connections. - """ for h in artists: for a in self.events: @@ -107,6 +118,7 @@ def clearall(self): self._actions = {} for action in self.events: self._actions[action] = {} + # Need activity state self._artists = [] self._current = Selection() @@ -120,8 +132,8 @@ def disconnect(self): try: for cid in self._connections: self.canvas.mpl_disconnect(cid) - except: - pass + except Exception as exc: + logger.error("Error disconnection canvas: %s" % exc) self._connections = [] def __del__(self): @@ -168,30 +180,28 @@ def __call__(self, trigger, artist, action): When receiving an event, first check the modifier state to be sure it applies. E.g., the callback for 'press' might be: if event.button == 1 and event.shift: process Shift-click - - :TODO: Only receive events with the correct modifiers (e.g., S-click, - :TODO: or *-click for any modifiers). - :TODO: Only receive button events for the correct button (e.g., click1 - :TODO: release3, or dclick* for any button) - :TODO: Support virtual artist, so that and artist can be flagged as - :TODO: having a tag list and receive the correct events - :TODO: Support virtual events for binding to button-3 vs shift button-1 - :TODO: without changing callback code - :TODO: Attach multiple callbacks to the same event? - :TODO: Clean up interaction with toolbar modes - :TODO: push/pushclear/pop context so that binding changes - for the duration - :TODO: e.g., to support ? context sensitive help - """ + #TODO: Only receive events with the correct modifiers (e.g., S-click, + #TODO: or *-click for any modifiers). + #TODO: Only receive button events for the correct button (e.g., click1 + #TODO: release3, or dclick* for any button) + #TODO: Support virtual artist, so that and artist can be flagged as + #TODO: having a tag list and receive the correct events + #TODO: Support virtual events for binding to button-3 vs shift button-1 + #TODO: without changing callback code + #TODO: Attach multiple callbacks to the same event? + #TODO: Clean up interaction with toolbar modes + #TODO: push/pushclear/pop context so that binding changes for the duration + #TODO: e.g., to support ? context sensitive help + # Check that the trigger is valid if trigger not in self._actions: - raise ValueError, "%s invalid --- valid triggers are %s" \ - % (trigger, ", ".join(self.events)) + raise ValueError("%s invalid --- valid triggers are %s" + % (trigger, ", ".join(self.events))) + # Register the trigger callback self._actions[trigger][artist] = action - # print "==> added",artist,[artist],"to",trigger,":", - # self._actions[trigger].keys() + # Maintain a list of all artists if artist not in self._artists: self._artists.append(artist) @@ -202,13 +212,15 @@ def trigger(self, actor, action, ev): to figure, and to 'all' if the event is not processed. """ if action not in self.events: - raise ValueError, "Trigger expects " + ", ".join(self.events) + raise ValueError("Trigger expects " + ", ".join(self.events)) + # Tag the event with modifiers for mod in ('alt', 'control', 'shift', 'meta'): setattr(ev, mod, getattr(self, mod)) setattr(ev, 'artist', None) setattr(ev, 'action', action) setattr(ev, 'prop', {}) + # Fallback scheme. If the event does not return false, pass to parent. processed = False artist, prop = actor.artist, actor.prop @@ -232,10 +244,8 @@ def _find_current(self, event): registered artists. All others are invisible to the mouse. """ # TODO: sort by zorder of axes then by zorder within axes - self._artists.sort(cmp=lambda x, y: cmp(y.zorder, x.zorder)) - # print "search"," ".join([str(h) for h in self._artists]) + self._artists.sort(key=lambda x: x.zorder, reverse=True) found = Selection() - # print "searching in",self._artists for artist in self._artists: # TODO: should contains() return false if invisible? if not artist.get_visible(): @@ -249,13 +259,13 @@ def _find_current(self, event): if inside: found.artist, found.prop = artist, prop break - # print "found",found.artist # TODO: how to check if prop is equal? if found != self._current: self.trigger(self._current, 'leave', event) self.trigger(found, 'enter', event) self._current = found + return found def _onMotion(self, event): @@ -273,18 +283,17 @@ def _onMotion(self, event): # artist rather than the default axes coordinates. transform = self._hasclick.artist.get_transform() - # x,y = event.xdata,event.ydata + #x,y = event.xdata,event.ydata x, y = event.x, event.y try: x, y = transform.inverted().transform_point((x, y)) - - except: + except: # CRUFT: matplotlib-0.91 support x, y = transform.inverse_xy_tup((x, y)) + event.xdata, event.ydata = x, y self.trigger(self._hasclick, 'drag', event) else: found = self._find_current(event) - # print "found",found.artist self.trigger(found, 'motion', event) def _onClick(self, event): @@ -295,9 +304,6 @@ def _onClick(self, event): # Check for double-click event_time = time.time() - # print event_time,self._last_time,self.dclick_threshhold - # print (event_time > self._last_time + self.dclick_threshhold) - # print event.button,self._last_button if (event.button != self._last_button) or \ (event_time > self._last_time + self.dclick_threshhold): action = 'click' @@ -380,6 +386,7 @@ def _onKeyRelease(self, event): if event.key in ('alt', 'meta', 'control', 'shift'): setattr(self, event.key, False) return + if self._haskey: self.trigger(self._haskey, 'keyup', event) self._haskey = Selection() @@ -390,4 +397,3 @@ def _onScroll(self, event): """ found = self._find_current(event) self.trigger(found, 'scroll', event) - diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/boxMask.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/boxMask.py index 71cb4da051..52779a93f8 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/boxMask.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/boxMask.py @@ -1,8 +1,8 @@ import math -from BaseInteractor import _BaseInteractor -from boxSum import PointInteractor -from boxSum import VerticalDoubleLine -from boxSum import HorizontalDoubleLine +from .BaseInteractor import _BaseInteractor +from .boxSum import PointInteractor +from .boxSum import VerticalDoubleLine +from .boxSum import HorizontalDoubleLine class BoxMask(_BaseInteractor): diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSlicer.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSlicer.py index 572d30e247..6c5c392686 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSlicer.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSlicer.py @@ -1,13 +1,16 @@ -import wx import math + +import wx import numpy as np + from sas.sasgui.guiframe.events import NewPlotEvent from sas.sasgui.guiframe.events import StatusEvent from sas.sasgui.guiframe.events import SlicerParameterEvent from sas.sasgui.guiframe.events import EVT_SLICER_PARS -from BaseInteractor import _BaseInteractor from sas.sasgui.guiframe.dataFitting import Data1D +from .BaseInteractor import _BaseInteractor + class BoxInteractor(_BaseInteractor): """ @@ -151,7 +154,7 @@ def post_data(self, new_slab=None, nbins=None, direction=None): if self.averager is None: if new_slab is None: msg = "post data:cannot average , averager is empty" - raise ValueError, msg + raise ValueError(msg) self.averager = new_slab if self.direction == "X": if self.fold: @@ -167,7 +170,7 @@ def post_data(self, new_slab=None, nbins=None, direction=None): bin_width = (y_max + y_low) / self.nbins else: msg = "post data:no Box Average direction was supplied" - raise ValueError, msg + raise ValueError(msg) # # Average data2D given Qx or Qy box = self.averager(x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, bin_width=bin_width) diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSum.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSum.py index e2f42b8a6d..bbdf867752 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSum.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/boxSum.py @@ -3,12 +3,15 @@ the sum of pixel of a Data. """ import math + import wx -from BaseInteractor import _BaseInteractor + from sas.sasgui.guiframe.events import SlicerParamUpdateEvent from sas.sasgui.guiframe.events import EVT_SLICER_PARS from sas.sasgui.guiframe.events import StatusEvent +from .BaseInteractor import _BaseInteractor + class BoxSum(_BaseInteractor): """ diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/detector_dialog.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/detector_dialog.py index fc5f90b9c1..a19075a1be 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/detector_dialog.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/detector_dialog.py @@ -98,8 +98,8 @@ def resetValues(self, event): self.cmap = DEFAULT_CMAP self.cmap_selector.SetStringSelection("jet") self._on_select_cmap(event=None) - except: - msg = "error occurs while resetting Detector: %s" % sys.exc_value + except Exception as exc: + msg = "error occurs while resetting Detector: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg)) def checkValues(self, event): diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/masking.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/masking.py index a30892ea53..74a1dc6377 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/masking.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/masking.py @@ -17,24 +17,27 @@ # #Todo: cleaning up, improving the maskplotpanel initialization, and testing. -import wx import sys import time -import matplotlib.cm as cm import math import copy +from functools import partial + +import wx import numpy as np +import matplotlib.cm as cm + from sas.sasgui.plottools.PlotPanel import PlotPanel from sas.sasgui.plottools.plottables import Graph -from binder import BindArtist from sas.sasgui.guiframe.dataFitting import Data1D, Data2D -from boxMask import BoxMask -from sector_mask import SectorMask -from AnnulusSlicer import CircularMask - from sas.sasgui.guiframe.events import SlicerEvent from sas.sasgui.guiframe.events import StatusEvent -from functools import partial + +from .binder import BindArtist +from .boxMask import BoxMask +from .sector_mask import SectorMask +from .AnnulusSlicer import CircularMask + (InternalEvent, EVT_INTERNAL) = wx.lib.newevent.NewEvent() diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_boxsum.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_boxsum.py index 777032c670..b45db0fb34 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_boxsum.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_boxsum.py @@ -1,11 +1,12 @@ import wx import wx.lib.newevent -from parameters_panel_slicer import SlicerParameterPanel + from sas.sasgui.guiframe.utils import format_number from sas.sasgui.guiframe.panel_base import PanelBase from sas.sasgui.guiframe.events import (SlicerParameterEvent, EVT_SLICER_PARS, EVT_SLICER) +from .parameters_panel_slicer import SlicerParameterPanel class SlicerPanel(wx.Panel, PanelBase): """ @@ -63,8 +64,7 @@ def set_slicer(self, type, params): flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15) n = 1 self.parameters = [] - keys = params.keys() - keys.sort() + keys = list(sorted(params.keys())) for item in keys: if not item.lower() in ["num_points", "avg", "avg_error", "sum", "sum_error"]: diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_slicer.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_slicer.py index 5aa5637fba..07657badac 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_slicer.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_slicer.py @@ -1,13 +1,17 @@ import os + import wx import wx.lib.newevent + from sas.sascalc.dataloader.readers.cansas_reader import Reader from sas.sasgui.guiframe.utils import format_number from sas.sasgui.guiframe.events import EVT_SLICER_PARS, EVT_SLICER from sas.sasgui.guiframe.events import SlicerParameterEvent, StatusEvent -from Plotter2D import ModelPanel2D + +from .Plotter2D import ModelPanel2D + apply_params, EVT_APPLY_PARAMS = wx.lib.newevent.NewEvent() save_files, EVT_AUTO_SAVE = wx.lib.newevent.NewEvent() @@ -99,8 +103,7 @@ def set_slicer(self, type, params): flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=15) iy = 1 self.parameters = [] - keys = params.keys() - keys.sort() + keys = list(sorted(params.keys())) for item in keys: ix = 0 iy += 1 @@ -126,7 +129,7 @@ def set_slicer(self, type, params): text = wx.StaticText(self, -1, item, style=wx.ALIGN_LEFT) self.bck.Add(text, (iy, ix), (1, 1), wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15) - options = BINNING_OPTIONS.keys() + options = list(BINNING_OPTIONS.keys()) self.bin_ctl = wx.ComboBox(parent=self, choices=options) hint_msg = "Modify the value of %s to change" % item hint_msg += " the 2D slicer" @@ -324,7 +327,7 @@ def on_batch_slicer(self, evt=None): fit = self.fitting_options.GetValue() # Find desired 2D data panels - for key, mgr in spp.plot_panels.iteritems(): + for key, mgr in spp.plot_panels.items(): if mgr.graph.prop['title'] in self.data_list.CheckedStrings: apply_to_list.append(mgr) @@ -376,7 +379,7 @@ def process_list(self): # Reinitialize loaded data list on redraw self.loaded_data = [] # Iterate over the loaded plots and find all 2D panels - for key, value in self.main_window.plot_panels.iteritems(): + for key, value in self.main_window.plot_panels.items(): if isinstance(value, ModelPanel2D): self.loaded_data.append(value.data2D.name) if value.data2D.id == self.parent.data2D.id: @@ -452,7 +455,7 @@ def save_files(self, evt=None): names.append(f_name.data2D.label) # Find the correct plots to save - for key, plot in self.main_window.plot_panels.iteritems(): + for key, plot in self.main_window.plot_panels.items(): if not hasattr(plot, "data2D"): for item in plot.plots: base = item.replace(CONVERT_DICT[evt.type], "") @@ -460,7 +463,7 @@ def save_files(self, evt=None): data_dic[item] = plot.plots[item] # Save files as Text - for item, data1d in data_dic.iteritems(): + for item, data1d in data_dic.items(): base = '.'.join(item.split('.')[:-1]) file_name = base + append + ".txt" save_to = evt.path + "\\" + file_name diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/plotting.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/plotting.py index ba5d86556f..5d3c25b9ab 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/plotting.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/plotting.py @@ -11,9 +11,11 @@ #copyright 2008, University of Tennessee ################################################################################ -import wx import sys from copy import deepcopy + +import wx + from sas.sasgui.guiframe.events import EVT_NEW_PLOT from sas.sasgui.guiframe.events import EVT_PLOT_QRANGE from sas.sasgui.guiframe.events import EVT_PLOT_LIM @@ -22,6 +24,7 @@ from sas.sasgui.guiframe.dataFitting import Data1D from sas.sasgui.guiframe.dataFitting import Data2D from sas.sasgui.guiframe.gui_manager import MDIFrame + DEFAULT_MENU_ITEM_LABEL = "No graph available" DEFAULT_MENU_ITEM_ID = wx.NewId() @@ -90,9 +93,9 @@ def _on_plot_qrange(self, event=None): """ if event is None: return - if event.id in self.plot_panels.keys(): + if event.id in self.plot_panels: panel = self.plot_panels[event.id] - elif event.group_id in self.plot_panels.keys(): + elif event.group_id in self.plot_panels: panel = self.plot_panels[event.group_id] else: return @@ -101,9 +104,9 @@ def _on_plot_qrange(self, event=None): def _on_plot_lim(self, event=None): if event is None: return - if event.id in self.plot_panels.keys(): + if event.id in self.plot_panels: panel = self.plot_panels[event.id] - elif event.group_id in self.plot_panels.keys(): + elif event.group_id in self.plot_panels: panel = self.plot_panels[event.group_id] else: return @@ -122,7 +125,7 @@ def remove_plot(self, group_id, id): remove plot of ID = id from a panel of group ID =group_id """ - if group_id in self.plot_panels.keys(): + if group_id in self.plot_panels: panel = self.plot_panels[group_id] panel.remove_data_by_id(id=id) @@ -133,7 +136,7 @@ def clear_panel(self): """ Clear and Hide all plot panels, and remove them from menu """ - for group_id in self.plot_panels.keys(): + for group_id in self.plot_panels: self.clear_panel_by_id(group_id) self.plot_panels = {} @@ -141,7 +144,7 @@ def clear_panel_by_id(self, group_id): """ clear the graph """ - if group_id in self.plot_panels.keys(): + if group_id in self.plot_panels: panel = self.plot_panels[group_id] for plottable in panel.graph.plottables.keys(): self.remove_plot(group_id, plottable.id) @@ -183,7 +186,7 @@ def create_1d_panel(self, data, group_id): """ # Create a new plot panel if none was available if issubclass(data.__class__, Data1D): - from Plotter1D import ModelPanel1D + from .Plotter1D import ModelPanel1D ## get the data representation label of the data to plot ## when even the user select "change scale" xtransform = data.xtransform @@ -199,14 +202,14 @@ def create_1d_panel(self, data, group_id): return new_panel msg = "1D Panel of group ID %s could not be created" % str(group_id) - raise ValueError, msg + raise ValueError(msg) def create_2d_panel(self, data, group_id): """ """ if issubclass(data.__class__, Data2D): ##Create a new plotpanel for 2D data - from Plotter2D import ModelPanel2D + from .Plotter2D import ModelPanel2D scale = data.scale win = MDIFrame(self.parent, None, 'None', (200, 150)) win.Show(False) @@ -217,7 +220,7 @@ def create_2d_panel(self, data, group_id): new_panel.frame = win return new_panel msg = "2D Panel of group ID %s could not be created" % str(group_id) - raise ValueError, msg + raise ValueError(msg) def update_panel(self, data, panel): """ @@ -237,7 +240,7 @@ def update_panel(self, data, panel): msg = "Cannot add %s" % str(data.name) msg += " to panel %s\n" % str(panel.window_caption) msg += "Please edit %s's units, labels" % str(data.name) - raise ValueError, msg + raise ValueError(msg) else: if panel.group_id not in data.list_group_id: data.list_group_id.append(panel.group_id) @@ -246,14 +249,14 @@ def update_panel(self, data, panel): def delete_panel(self, group_id): """ """ - if group_id in self.plot_panels.keys(): + if group_id in self.plot_panels: panel = self.plot_panels[group_id] uid = panel.uid wx.PostEvent(self.parent, DeletePlotPanelEvent(name=panel.window_caption, caption=panel.window_caption)) del self.plot_panels[group_id] - if uid in self.parent.plot_panels.keys(): + if uid in self.parent.plot_panels: del self.parent.plot_panels[uid] panel.frame.Destroy() return True @@ -279,7 +282,7 @@ def _on_plot_event(self, event): # Update all existing plots of data with this ID for data in event.plots: for panel in self.plot_panels.values(): - if data.id in panel.plots.keys(): + if data.id in panel.plots: plot_exists = True # Pass each panel it's own copy of the data # that's being updated, otherwise things like @@ -309,10 +312,10 @@ def _on_plot_event(self, event): title = 'Graph' #event.title data = event.plot group_id = data.group_id - if group_id in self.plot_panels.keys(): + if group_id in self.plot_panels: if action_check: # Check if the plot already exist. if it does, do nothing. - if data.id in self.plot_panels[group_id].plots.keys(): + if data.id in self.plot_panels[group_id].plots: return #update a panel graph panel = self.plot_panels[group_id] @@ -326,7 +329,7 @@ def _on_plot_event(self, event): if len(self.plot_panels.values()) > 0: for p_group_id in self.plot_panels.keys(): p_plot = self.plot_panels[p_group_id] - if data.id in p_plot.plots.keys(): + if data.id in p_plot.plots: p_plot.plots[data.id] = data self.plot_panels[group_id] = p_plot if group_id != p_group_id: diff --git a/src/sas/sasgui/guiframe/local_perspectives/plotting/sector_mask.py b/src/sas/sasgui/guiframe/local_perspectives/plotting/sector_mask.py index dfa5708296..69a878a688 100644 --- a/src/sas/sasgui/guiframe/local_perspectives/plotting/sector_mask.py +++ b/src/sas/sasgui/guiframe/local_perspectives/plotting/sector_mask.py @@ -2,13 +2,15 @@ Sector mask interactor """ import math + import wx -#from copy import deepcopy -from BaseInteractor import _BaseInteractor -from SectorSlicer import SideInteractor -from SectorSlicer import LineInteractor + from sas.sasgui.guiframe.events import SlicerParameterEvent +from .BaseInteractor import _BaseInteractor +from .SectorSlicer import SideInteractor +from .SectorSlicer import LineInteractor + class SectorMask(_BaseInteractor): """ Draw a sector slicer.Allow to find the data 2D inside of the sector lines @@ -174,7 +176,7 @@ def get_params(self): msg = "Phi left and phi right are " msg += "different %f, %f" % (self.left_line.phi, self.right_line.phi) - raise ValueError, msg + raise ValueError(msg) params["Phi"] = self.main_line.theta params["Delta_Phi"] = math.fabs(self.left_line.phi) return params diff --git a/src/sas/sasgui/guiframe/plugin_base.py b/src/sas/sasgui/guiframe/plugin_base.py index 798527d406..829ae51de6 100644 --- a/src/sas/sasgui/guiframe/plugin_base.py +++ b/src/sas/sasgui/guiframe/plugin_base.py @@ -111,13 +111,13 @@ def load_data(self, event): """ Load data """ - raise NotImplementedError + raise NotImplementedError() def load_folder(self, event): """ Load entire folder """ - raise NotImplementedError + raise NotImplementedError() def set_is_active(self, active=False): """ @@ -276,7 +276,7 @@ def set_theory(self, theory_list=None): related to available theory state """ msg = "%s plugin: does not support import theory" % str(self.sub_menu) - raise ValueError, msg + raise ValueError(msg) def on_set_state_helper(self, event): """ diff --git a/src/sas/sasgui/guiframe/proxy.py b/src/sas/sasgui/guiframe/proxy.py index 09a4744b1f..6689062787 100644 --- a/src/sas/sasgui/guiframe/proxy.py +++ b/src/sas/sasgui/guiframe/proxy.py @@ -2,12 +2,16 @@ # -*- coding: utf-8 -*- from __future__ import print_function -import urllib2 import sys import json import logging import re +try: + # CRUFT: python 3 uses urllib.request instead of urllib2 + import urllib2 +except ImportError: + from urllib import request as urllib2 logger = logging.getLogger(__name__) @@ -49,7 +53,7 @@ def _get_addresses_of_proxy_pac(self): for i in range(n_vals): this_name, this_val, this_type = winreg.EnumValue(net, i) subkeys[this_name] = this_val - if 'AutoConfigURL' in subkeys.keys() and len(subkeys['AutoConfigURL']) > 0: + if 'AutoConfigURL' in subkeys and len(subkeys['AutoConfigURL']) > 0: pac_files.append(subkeys['AutoConfigURL']) elif sys.platform == 'darwin': import plistlib @@ -60,7 +64,7 @@ def _get_addresses_of_proxy_pac(self): for network in networks.items(): # the first part is a long identifier net_key, network = network - if 'ProxyAutoConfigURLString' in network['Proxies'].keys(): + if 'ProxyAutoConfigURLString' in network['Proxies']: pac_files.append( network['Proxies']['ProxyAutoConfigURLString']) return list(set(pac_files)) # remove redundant ones @@ -126,16 +130,16 @@ def connect(self): try: logger.debug("Trying Direct connection to %s..."%self.url) response = urllib2.urlopen(req, timeout=self.timeout) - except Exception, e: + except Exception as exc: logger.debug("Failed!") - logger.debug(e) + logger.debug(exc) try: logger.debug("Trying to use system proxy if it exists...") self._set_proxy() response = urllib2.urlopen(req, timeout=self.timeout) - except Exception, e: + except Exception as exc: logger.debug("Failed!") - logger.debug(e) + logger.debug(exc) pac_urls = self._get_addresses_of_proxy_pac() proxy_urls = self._parse_proxy_pac(pac_urls) for proxy in proxy_urls: @@ -143,9 +147,9 @@ def connect(self): logger.debug("Trying to use the proxy %s found in proxy.pac configuration"%proxy) self._set_proxy(proxy) response = urllib2.urlopen(req, timeout=self.timeout) - except Exception, e: + except Exception as exc: logger.debug("Failed!") - logger.debug(e) + logger.debug(exc) if response is not None: logger.debug("The connection to %s was successful."%self.url) else: diff --git a/src/sas/sasgui/guiframe/report_dialog.py b/src/sas/sasgui/guiframe/report_dialog.py index 0397d91b93..fcd1a9499a 100644 --- a/src/sas/sasgui/guiframe/report_dialog.py +++ b/src/sas/sasgui/guiframe/report_dialog.py @@ -146,6 +146,6 @@ def HTML2PDF(self, data, filename): resultFile.close() self.Update() return pisaStatus.err - except Exception: - logger.error("Error creating pdf: %s" % sys.exc_value) + except Exception as exc: + logger.error("Error creating pdf: %s" % exc) return False diff --git a/src/sas/sasgui/guiframe/startup_configuration.py b/src/sas/sasgui/guiframe/startup_configuration.py index abd5c34b41..50b56e8646 100644 --- a/src/sas/sasgui/guiframe/startup_configuration.py +++ b/src/sas/sasgui/guiframe/startup_configuration.py @@ -196,7 +196,7 @@ def write_custom_config(self): path = make_custom_config_path() with open(path, 'w') as out_f: out_f.write("#Application appearance custom configuration\n") - for key, item in self.return_string.iteritems(): + for key, item in self.return_string.items(): if (key == 'DEFAULT_PERSPECTIVE') or \ (key == 'DEFAULT_OPEN_FOLDER' and item != None): out_f.write("%s = \"%s\"\n" % (key, str(item))) diff --git a/src/sas/sasgui/guiframe/utils.py b/src/sas/sasgui/guiframe/utils.py index 08d912cbbb..e40ebbe700 100644 --- a/src/sas/sasgui/guiframe/utils.py +++ b/src/sas/sasgui/guiframe/utils.py @@ -207,7 +207,9 @@ class _IdListIterator: def __init__(self, id_list): self.id_list = id_list self.index = -1 - def next(self): + def __next__(self): self.index += 1 return self.id_list[self.index] + # CRUFT: python 2 uses next rather than __next__ for iterator + next = __next__ diff --git a/src/sas/sasgui/perspectives/calculator/__init__.py b/src/sas/sasgui/perspectives/calculator/__init__.py index fe222ea9b8..ca05e1aa68 100644 --- a/src/sas/sasgui/perspectives/calculator/__init__.py +++ b/src/sas/sasgui/perspectives/calculator/__init__.py @@ -1,7 +1,7 @@ PLUGIN_ID = "Calculator plug-in 1.0" import os from distutils.filelist import findall -from calculator import * +from .calculator import * N_DIR = 12 def get_data_path(media): """ diff --git a/src/sas/sasgui/perspectives/calculator/calculator.py b/src/sas/sasgui/perspectives/calculator/calculator.py index fbb6317b55..2e4857620e 100644 --- a/src/sas/sasgui/perspectives/calculator/calculator.py +++ b/src/sas/sasgui/perspectives/calculator/calculator.py @@ -11,7 +11,10 @@ #copyright 2010, University of Tennessee ################################################################################ +import logging + import wx + from sas.sasgui.guiframe.plugin_base import PluginBase from sas.sasgui.perspectives.calculator.data_operator import DataOperatorWindow from sas.sasgui.perspectives.calculator.data_editor import DataEditorWindow @@ -25,7 +28,6 @@ from sas.sasgui.perspectives.calculator.gen_scatter_panel import SasGenWindow from sas.sasgui.perspectives.calculator.image_viewer import ImageView from sas.sasgui.perspectives.calculator.pyconsole import PyConsole -import logging logger = logging.getLogger(__name__) diff --git a/src/sas/sasgui/perspectives/calculator/collimation_editor.py b/src/sas/sasgui/perspectives/calculator/collimation_editor.py index 16647a1474..ad76b9ee83 100644 --- a/src/sas/sasgui/perspectives/calculator/collimation_editor.py +++ b/src/sas/sasgui/perspectives/calculator/collimation_editor.py @@ -1,13 +1,16 @@ """ """ -import wx import sys from copy import deepcopy + +import wx + from sas.sascalc.dataloader.loader import Loader from sas.sascalc.dataloader.data_info import Aperture, Collimation -from aperture_editor import ApertureDialog - from sas.sasgui.guiframe.utils import check_float + +from .aperture_editor import ApertureDialog + _BOX_WIDTH = 60 if sys.platform.count("win32") > 0: diff --git a/src/sas/sasgui/perspectives/calculator/data_editor.py b/src/sas/sasgui/perspectives/calculator/data_editor.py index cec0f3f662..85f29cfde7 100644 --- a/src/sas/sasgui/perspectives/calculator/data_editor.py +++ b/src/sas/sasgui/perspectives/calculator/data_editor.py @@ -6,12 +6,14 @@ from sas.sascalc.dataloader.loader import Loader from sas.sascalc.dataloader.data_info import Data2D -from detector_editor import DetectorDialog -from collimation_editor import CollimationDialog -from console import ConsoleDialog from sas.sasgui.guiframe.events import StatusEvent +from .detector_editor import DetectorDialog +from .collimation_editor import CollimationDialog +from .console import ConsoleDialog + + _QMIN_DEFAULT = 0.001 _QMAX_DEFAULT = 0.13 @@ -396,7 +398,7 @@ def edit_sample(self): data, _, _ = self.get_current_data() if data is None: return - from sample_editor import SampleDialog + from .sample_editor import SampleDialog dlg = SampleDialog(parent=self, sample=data.sample) dlg.set_manager(self) dlg.ShowModal() @@ -408,7 +410,7 @@ def edit_source(self): data, data_name, position = self.get_current_data() if data is None: return - from source_editor import SourceDialog + from .source_editor import SourceDialog dlg = SourceDialog(parent=self, source=data.source) dlg.set_manager(self) dlg.ShowModal() @@ -425,7 +427,7 @@ def choose_data_file(self, location=None): cards = l.get_wildcards() wlist = '|'.join(cards) - dlg = wx.FileDialog(self, "Choose a file", location, "", wlist, wx.OPEN) + dlg = wx.FileDialog(self, "Choose a file", location, "", wlist, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) @@ -526,7 +528,7 @@ def on_click_browse(self, event): self._default_save_location = path try: #Load data - from load_thread import DataReader + from .load_thread import DataReader ## If a thread is already started, stop it if self.reader is not None and self.reader.isrunning(): self.reader.stop() @@ -534,8 +536,8 @@ def on_click_browse(self, event): completefn=self.complete_loading, updatefn=None) self.reader.queue() - except: - msg = "Data Editor: %s" % (sys.exc_value) + except Exception as exc: + msg = "Data Editor: %s" % exc load_error(msg) return event.Skip() diff --git a/src/sas/sasgui/perspectives/calculator/data_operator.py b/src/sas/sasgui/perspectives/calculator/data_operator.py index 61b05c94bf..d80c3b85ef 100644 --- a/src/sas/sasgui/perspectives/calculator/data_operator.py +++ b/src/sas/sasgui/perspectives/calculator/data_operator.py @@ -201,12 +201,11 @@ def _check_newname(self, name=None): text = self.data_namectr.GetValue().strip() else: text = name - state_list = self.get_datalist().values() name_list = [] - for state in state_list: + for state in self.get_datalist().values(): if state.data is None: theory_list = state.get_theory() - theory, _ = theory_list.values()[0] + theory, _ = list(theory_list.values())[0] d_name = str(theory.name) else: d_name = str(state.data.name) @@ -392,11 +391,11 @@ def check_data_inputs(self): return flag try: self.output = self.make_data_out(data1, data2) - except: + except Exception as exc: self._check_newname() self._set_textctrl_color(self.data1_cbox, 'pink') self._set_textctrl_color(self.data2_cbox, 'pink') - msg = "DataOperation: %s" % sys.exc_value + msg = "DataOperation: %s" % exc self.send_warnings(msg, 'error') self.output = None return flag @@ -410,7 +409,8 @@ def make_data_out(self, data1, data2): pos = self.operator_cbox.GetCurrentSelection() operator = self.operator_cbox.GetClientData(pos) try: - exec "output = data1 %s data2" % operator + output = eval("data1 %s data2" % operator, + {"data1": data1, "data2": data2}) except: raise return output @@ -531,18 +531,17 @@ def fill_data_combox(self): val = None self.data2_cbox.SetClientData(pos3, val) dnames = [] - ids = self._data.keys() - for id in ids: + for id in self._data.keys(): if id is not None: if self._data[id].data is not None: dnames.append(self._data[id].data.name) else: theory_list = self._data[id].get_theory() - theory, _ = theory_list.values()[0] + theory, _ = list(theory_list.values())[0] dnames.append(theory.name) ind = np.argsort(dnames) if len(ind) > 0: - val_list = np.array(self._data.values())[ind] + val_list = np.array(list(self._data.values()))[ind] for datastate in val_list: data = datastate.data if data is not None: @@ -587,13 +586,12 @@ def on_click_apply(self, event): """ self.send_warnings('') self.data_namectr.SetBackgroundColour('white') - state_list = self.get_datalist().values() name = self.data_namectr.GetValue().strip() name_list = [] - for state in state_list: + for state in self.get_datalist().values(): if state.data is None: theory_list = state.get_theory() - theory, _ = theory_list.values()[0] + theory, _ = list(theory_list.values())[0] d_name = str(theory.name) else: d_name = str(state.data.name) @@ -888,15 +886,14 @@ def ontogglescale(self, event): def _onProperties(self, event): """ - when clicking on Properties on context menu , - The Property dialog is displayed - The user selects a transformation for x or y value and - a new plot is displayed + When clicking on Properties on context menu, the + Property dialog is displayed the user selects a + transformation for x or y value and a new plot is displayed """ - list = [] - list = self.graph.returnPlottable() - if len(list.keys()) > 0: - first_item = list.keys()[0] + plottables = self.graph.returnPlottable() + if plottables: + # TODO: key order is random prior to py 3.7 + first_item = list(plottables.keys())[0] if first_item.x != []: from sas.sasgui.plottools.PropertyDialog import Properties dial = Properties(self, -1, 'Change Scale') @@ -928,8 +925,6 @@ def _onEVT_FUNC_PROPERTY(self, remove_fit=True): Transforms x and y in View and set the scale """ - list = [] - list = self.graph.returnPlottable() # Changing the scale might be incompatible with # currently displayed data (for instance, going # from ln to log when all plotted values have @@ -939,7 +934,7 @@ def _onEVT_FUNC_PROPERTY(self, remove_fit=True): self.set_yscale("linear") _xscale = 'linear' _yscale = 'linear' - for item in list: + for item in self.graph.returnPlottable(): item.setLabel(self.xLabel, self.yLabel) # control axis labels from the panel itself yname, yunits = item.get_yaxis() diff --git a/src/sas/sasgui/perspectives/calculator/density_panel.py b/src/sas/sasgui/perspectives/calculator/density_panel.py index 7355a3c6a3..686756ec59 100644 --- a/src/sas/sasgui/perspectives/calculator/density_panel.py +++ b/src/sas/sasgui/perspectives/calculator/density_panel.py @@ -361,9 +361,9 @@ def calculate(self, event): output = self._format_number(molar_mass / self.input) self.molar_mass_ctl.SetValue(str(self._format_number(molar_mass))) self.output_ctl.SetValue(str(output)) - except: + except Exception as exc: if self.base is not None: - msg = "Density/Volume Calculator: %s" % (sys.exc_value) + msg = "Density/Volume Calculator: %s" % exc wx.PostEvent(self.base, StatusEvent(status=msg)) if event is not None: event.Skip() diff --git a/src/sas/sasgui/perspectives/calculator/detector_editor.py b/src/sas/sasgui/perspectives/calculator/detector_editor.py index e854716632..9d755d3389 100644 --- a/src/sas/sasgui/perspectives/calculator/detector_editor.py +++ b/src/sas/sasgui/perspectives/calculator/detector_editor.py @@ -33,8 +33,8 @@ def __init__(self, parent=None, manager=None, detector=None, self._description = "Edit Detector" self._do_layout() self.set_values() - except: - print("error", sys.exc_value) + except Exception as exc: + print("error", exc) def _define_structure(self): """ diff --git a/src/sas/sasgui/perspectives/calculator/gen_scatter_panel.py b/src/sas/sasgui/perspectives/calculator/gen_scatter_panel.py index 841cc5ca1c..5668154f40 100644 --- a/src/sas/sasgui/perspectives/calculator/gen_scatter_panel.py +++ b/src/sas/sasgui/perspectives/calculator/gen_scatter_panel.py @@ -227,9 +227,7 @@ def _layout_param_size(self): unit_title = wx.StaticText(self, -1, 'Unit') sizer.Add(unit_title, (iy, ix), (1, 1), \ wx.EXPAND | wx.ADJUST_MINSIZE, 0) - key_list = params.keys() - key_list.sort() - for param in key_list: + for param in sorted(params.keys()): iy += 1 ix = 0 p_name = wx.StaticText(self, -1, param) @@ -340,7 +338,6 @@ def _layout_qrange(self): sizer = wx.GridBagSizer(2, 3) ix = 0 iy = 0 - #key_list.sort() name = wx.StaticText(self, -1, 'No. of Qx (Qy) bins: ') sizer.Add(name, (iy, ix), (1, 1), \ wx.EXPAND | wx.ADJUST_MINSIZE, 0) @@ -508,7 +505,7 @@ def choose_data_file(self, location=None): wildcard.append(type) wildcard = '|'.join(wildcard) dlg = wx.FileDialog(self, "Choose a file", location, - "", wildcard, wx.OPEN) + "", wildcard, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() filename = os.path.basename(path) @@ -555,11 +552,11 @@ def on_load_data(self, event): updatefn=self.load_update) self.reader.queue() #self.load_update() - except: + except Exception as exc: self.ext = None if self.parent.parent is None: return - msg = "Generic SAS Calculator: %s" % (sys.exc_value) + msg = "Generic SAS Calculator: %s" % exc wx.PostEvent(self.parent.parent, StatusEvent(status=msg, type='stop')) self.SetFocus() @@ -773,8 +770,8 @@ def _sld_plot_helper(self, ax, output, has_arrow=False): a_name = '' if output.pix_type == 'atom': # Get atom names not in the list - a_names = [symb for symb in pix_symbol \ - if symb not in color_dic.keys()] + a_names = [symb for symb in pix_symbol + if symb not in color_dic] a_name = a_names[0] for name in a_names: new_name = ", " + name @@ -897,8 +894,8 @@ def on_compute(self, event): updatefn=self._update) cal_out.queue() - except: - msg = "%s." % sys.exc_value + except Exception as exc: + msg = "%s." % exc status_type = 'stop' self._status_info(msg, status_type) wx.PostEvent(self.parent.parent, @@ -1343,8 +1340,8 @@ def _get_other_val(self): self.sld_data = omf2sld.output self.sld_data.is_data = False self.sld_data.filename = "Default SLD Profile" - except: - msg = "OMF Panel: %s" % sys.exc_value + except Exception as exc: + msg = "OMF Panel: %s" % exc infor = 'Error' #logger.error(msg) if self.parent.parent is not None: @@ -1440,16 +1437,11 @@ def _layout_slds(self): if omfdata is None: raise sld_key_list = self._get_slds_key_list(omfdata) - # Dic is not sorted - key_list = [key for key in sld_key_list.keys()] - # Sort here - key_list.sort() is_data = self.sld_data.is_data sizer = wx.GridBagSizer(2, 3) ix = 0 iy = -1 - for key in key_list: - value = sld_key_list[key] + for key, value in sorted(sld_key_list.items()): iy += 1 ix = 0 name = wx.StaticText(self, -1, key) @@ -1484,7 +1476,7 @@ def _layout_nodes(self): sizer = wx.GridBagSizer(2, 3) ix = 0 iy = -1 - for key, value in key_list.iteritems(): + for key, value in sorted(key_list.items()): iy += 1 ix = 0 name = wx.StaticText(self, -1, key) @@ -1519,8 +1511,7 @@ def _layout_stepsize(self): sizer = wx.GridBagSizer(2, 3) ix = 0 iy = -1 - #key_list.sort() - for key, value in key_list.iteritems(): + for key, value in sorted(key_list.items()): iy += 1 ix = 0 name = wx.StaticText(self, -1, key) diff --git a/src/sas/sasgui/perspectives/calculator/image_viewer.py b/src/sas/sasgui/perspectives/calculator/image_viewer.py index 7f805e5e21..c69294572b 100644 --- a/src/sas/sasgui/perspectives/calculator/image_viewer.py +++ b/src/sas/sasgui/perspectives/calculator/image_viewer.py @@ -94,14 +94,16 @@ def choose_data_file(self, location=None): path = None if location is None: location = os.getcwd() - wildcard="Images (*.bmp;*.gif;*jpeg,*jpg;*.png;*tif;*.tiff)|*bmp;\ - *.gif; *.jpg; *.jpeg;*png;*.png;*.tif;*.tiff|"\ - "Bitmap (*.bmp)|*.bmp|"\ - "GIF (*.gif)|*.gif|"\ - "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|"\ - "PNG (*.png)|*.png|"\ - "TIFF (*.tif;*.tiff)|*.tif;*tiff|"\ - "All Files (*.*)|*.*|" + wildcard="|".join(( + "Images (*.bmp;*.gif;*jpeg,*jpg;*.png;*tif;*.tiff)" + "|*bmp;*.gif;*.jpg;*.jpeg;*png;*.png;*.tif;*.tiff", + "Bitmap (*.bmp)|*.bmp", + "GIF (*.gif)|*.gif", + "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg", + "PNG (*.png)|*.png", + "TIFF (*.tif;*.tiff)|*.tif;*tiff", + "All Files (*.*)|*.*", + )) dlg = wx.FileDialog(self.parent, "Image Viewer: Choose an image file", location, "", wildcard, style=wx.FD_OPEN diff --git a/src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py b/src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py index 7913c3c8b8..70b0dbc695 100644 --- a/src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py +++ b/src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py @@ -11,12 +11,12 @@ import wx import sys -from sas.sasgui.guiframe.panel_base import PanelBase from sas.sascalc.calculator.kiessig_calculator import KiessigThicknessCalculator -from calculator_widgets import OutputTextCtrl -from calculator_widgets import InputTextCtrl +from sas.sasgui.guiframe.panel_base import PanelBase from sas.sasgui.perspectives.calculator import calculator_widgets as widget from sas.sasgui.guiframe.documentation_window import DocumentationWindow +from .calculator_widgets import OutputTextCtrl +from .calculator_widgets import InputTextCtrl _BOX_WIDTH = 77 #Slit length panel size diff --git a/src/sas/sasgui/perspectives/calculator/model_editor.py b/src/sas/sasgui/perspectives/calculator/model_editor.py index 4a915c25f5..148ac37c13 100644 --- a/src/sas/sasgui/perspectives/calculator/model_editor.py +++ b/src/sas/sasgui/perspectives/calculator/model_editor.py @@ -577,7 +577,7 @@ def __init__(self, parent, base, path, title, *args, **kwds): self.parent = parent self.base = base self.path = path - self.font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) + self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) self.font.SetPointSize(10) self.reader = None self.name = 'untitled' @@ -780,7 +780,7 @@ def _fill_math_combo(self): for item in dir(math): if item.count("_") < 1: try: - exec "float(math.%s)" % item + exec("float(math.%s)" % item) self.math_combo.Append(str(item)) except Exception: self.math_combo.Append(str(item) + "()") diff --git a/src/sas/sasgui/perspectives/calculator/resolcal_thread.py b/src/sas/sasgui/perspectives/calculator/resolcal_thread.py index 54d36b773a..8dbdffb864 100644 --- a/src/sas/sasgui/perspectives/calculator/resolcal_thread.py +++ b/src/sas/sasgui/perspectives/calculator/resolcal_thread.py @@ -45,10 +45,10 @@ def compute(self): """ executing computation """ - self.image = map(self.func, self.qx, self.qy, - self.qx_min, self.qx_max, - self.qy_min, self.qy_max)[0] + self.image = list(map(self.func, self.qx, self.qy, + self.qx_min, self.qx_max, + self.qy_min, self.qy_max))[0] elapsed = time.time() - self.starttime self.complete(image=self.image, - elapsed=elapsed) \ No newline at end of file + elapsed=elapsed) diff --git a/src/sas/sasgui/perspectives/calculator/resolution_calculator_panel.py b/src/sas/sasgui/perspectives/calculator/resolution_calculator_panel.py index 40aaabf142..90690faa74 100644 --- a/src/sas/sasgui/perspectives/calculator/resolution_calculator_panel.py +++ b/src/sas/sasgui/perspectives/calculator/resolution_calculator_panel.py @@ -147,7 +147,7 @@ def _layout_mass(self): # Sort source name because wx2.9 on Mac does not support CB_SORT # Custom sorting source_list = [] - for key, _ in self.source_mass.iteritems(): + for key, _ in self.source_mass.items(): name_source = str(key) source_list.append(name_source) source_list.sort() @@ -666,6 +666,12 @@ def on_compute(self, event=None): """ Execute the computation of resolution """ + # Clone the event before CallAfter; the event seems + # to delete the event when it is done processing, so + # the original will not be available when the call + # after method starts. + if event is not None: + event = event.Clone() wx.CallAfter(self.on_compute_call, event) def on_compute_call(self, event=None): @@ -752,7 +758,7 @@ def on_compute_call(self, event=None): self._status_info(msg, status_type) wx.MessageBox(msg, 'Warning') return - #raise ValueError, "Invalid Q Input..." + #raise ValueError("Invalid Q Input...") # Validate the q inputs q_input = self._validate_q_input(self.qx, self.qy) @@ -933,7 +939,7 @@ def _map_func(self, qx, qy, qx_min, qx_max, qy_min, qy_max): def _sigma_strings(self): """ - Recode sigmas as strins + Recode sigmas as strings """ sigma_r = self.format_number(self.resolution.sigma_1) sigma_phi = self.format_number(self.resolution.sigma_2) @@ -1081,7 +1087,7 @@ def _string2list(self, string): else: msg = "The numbers must be one or two (separated by ',')..." self._status_info(msg, 'stop') - raise RuntimeError, msg + raise RuntimeError(msg) return new_string @@ -1098,8 +1104,8 @@ def _string2inputlist(self, string): try: value = float(string_split[ind]) new_string.append(value) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) return new_string @@ -1140,8 +1146,8 @@ def _str2longlist(self, string): if string.count(',') > 0: out = self._string2inputlist(string) return out - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) def _on_xy_coordinate(self, event=None): """ @@ -1268,7 +1274,7 @@ def _on_spectrum_cb(self, event=None): return try: basename = os.path.basename(path) - if basename not in self.spectrum_dic.keys(): + if basename not in self.spectrum_dic: self.spectrum_cb.Append(basename) self.spectrum_dic[basename] = self._read_file(path) self.spectrum_cb.SetValue(basename) @@ -1285,7 +1291,7 @@ def _selectDlg(self): """ dlg = wx.FileDialog(self, "Choose a wavelength spectrum file: Intensity vs. wavelength", - self.parent.parent.get_save_location() , "", "*.*", wx.OPEN) + self.parent.parent.get_save_location() , "", "*.*", wx.FD_OPEN) path = None if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() @@ -1317,9 +1323,9 @@ def _read_file(self, path): intens = float(toks[1]) wavelength.append(wave) intensity.append(intens) - except: + except Exception as exc: # Skip non-data lines - logger.error(sys.exc_value) + logger.error(exc) return [wavelength, intensity] except: diff --git a/src/sas/sasgui/perspectives/calculator/sld_panel.py b/src/sas/sasgui/perspectives/calculator/sld_panel.py index 4a901ebd16..4e0dee5f6f 100644 --- a/src/sas/sasgui/perspectives/calculator/sld_panel.py +++ b/src/sas/sasgui/perspectives/calculator/sld_panel.py @@ -362,10 +362,13 @@ def calculate_xray_sld(self, element): :param element: elements a string of existing atom """ + # TODO: use periodictable.elements object + # energy = xray_energy(periodictable.elements[element].K_alpha) + # TODO: code is very similar to sld helper myformula = formula(str(element)) if len(myformula.atoms) != 1: return - element = myformula.atoms.keys()[0] + element = list(myformula.atoms.keys())[0] energy = xray_energy(element.K_alpha) self.sld_formula = formula(str(self.compound), density=self.density) @@ -412,6 +415,9 @@ def check_inputs(self): flag = False msg += "Error for wavelength value :expect float" elif (self.xray_source == 'Element'): + # TODO: use periodictable.elements instead of exec() hacks + # if self.xray_source_input not in periodictable.elements: + # ... try: import periodictable exec("periodictable." + self.xray_source_input) @@ -446,11 +452,14 @@ def calculate_sld_helper(self, element, density, molecule_formula): :param element: elements a string of existing atom """ + # TODO: use periodictable.elements object + # energy = xray_energy(periodictable.elements[element].K_alpha) element_formula = formula(str(element)) if len(element_formula.atoms) != 1: return - element = element_formula.atoms.keys()[0] + element = list(element_formula.atoms.keys())[0] energy = xray_energy(element.K_alpha) + atom = molecule_formula.atoms return xray_sld_from_atoms(atom, density=density, energy=energy) @@ -504,9 +513,9 @@ def calculateSld(self, event): # display wavelength #self.wavelength_ctl.SetValue(str(self.wavelength)) #self.wavelength_ctl.SetValue(str(self.wavelength)) - except: + except Exception as exc: if self.base is not None: - msg = "SLD Calculator: %s" % (sys.exc_value) + msg = "SLD Calculator: %s" % exc wx.PostEvent(self.base, StatusEvent(status=msg)) if event is not None: event.Skip() diff --git a/src/sas/sasgui/perspectives/calculator/slit_length_calculator_panel.py b/src/sas/sasgui/perspectives/calculator/slit_length_calculator_panel.py index 4fe8052436..bb62163ee5 100644 --- a/src/sas/sasgui/perspectives/calculator/slit_length_calculator_panel.py +++ b/src/sas/sasgui/perspectives/calculator/slit_length_calculator_panel.py @@ -16,10 +16,10 @@ from sas.sasgui.guiframe.events import StatusEvent from sas.sascalc.calculator.slit_length_calculator import SlitlengthCalculator -from calculator_widgets import OutputTextCtrl -from calculator_widgets import InterActiveOutputTextCtrl from sas.sasgui.perspectives.calculator import calculator_widgets as widget from sas.sasgui.guiframe.documentation_window import DocumentationWindow +from .calculator_widgets import OutputTextCtrl +from .calculator_widgets import InterActiveOutputTextCtrl _BOX_WIDTH = 76 #Slit length panel size @@ -162,7 +162,7 @@ def choose_data_file(self, location=None): wildcard = "SAXSess Data 1D (*.DAT, *.dat)|*.DAT" dlg = wx.FileDialog(self, "Choose a file", location, - "", wildcard, wx.OPEN) + "", wildcard, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() filename = os.path.basename(path) @@ -222,10 +222,10 @@ def on_load_data(self, event): updatefn=self.load_update) self.reader.queue() self.load_update() - except: + except Exception as exc: if self.parent.parent is None: return - msg = "Slit Length Calculator: %s" % (sys.exc_value) + msg = "Slit Length Calculator: %s" % exc wx.PostEvent(self.parent.parent, StatusEvent(status=msg, type='stop')) return @@ -263,14 +263,14 @@ def complete_loading(self, data=None, filename=''): y = data.y if x == [] or x is None or y == [] or y is None: msg = "The current data is empty please check x and y" - raise ValueError, msg + raise ValueError(msg) slit_length_calculator = SlitlengthCalculator() slit_length_calculator.set_data(x=x, y=y) slit_length = slit_length_calculator.calculate_slit_length() - except: + except Exception as exc: if self.parent.parent is None: return - msg = "Slit Size Calculator: %s" % (sys.exc_value) + msg = "Slit Size Calculator: %s" % exc wx.PostEvent(self.parent.parent, StatusEvent(status=msg, type='stop')) return diff --git a/src/sas/sasgui/perspectives/corfunc/__init__.py b/src/sas/sasgui/perspectives/corfunc/__init__.py index 869ffdfd85..01c5a723f0 100644 --- a/src/sas/sasgui/perspectives/corfunc/__init__.py +++ b/src/sas/sasgui/perspectives/corfunc/__init__.py @@ -1,2 +1,2 @@ PLUGIN_ID = "Corfunc Plug-In 0.1" -from corfunc import * +from .corfunc import * diff --git a/src/sas/sasgui/perspectives/corfunc/corfunc.py b/src/sas/sasgui/perspectives/corfunc/corfunc.py index 667da38968..5602960608 100644 --- a/src/sas/sasgui/perspectives/corfunc/corfunc.py +++ b/src/sas/sasgui/perspectives/corfunc/corfunc.py @@ -17,7 +17,7 @@ from sas.sasgui.perspectives.corfunc.corfunc_state import Reader from sas.sascalc.dataloader.loader import Loader import sas.sascalc.dataloader -from plot_labels import * +from .plot_labels import * logger = logging.getLogger(__name__) @@ -147,8 +147,8 @@ def set_data(self, data_list=None): id=self.data_id)) self.data_id = data.id self.corfunc_panel.set_data(data) - except: - msg = "Corfunc set_data: " + str(sys.exc_value) + except Exception as exc: + msg = "Corfunc set_data: " + str(exc) wx.PostEvent(self.parent, StatusEvent(status=msg, info='error')) diff --git a/src/sas/sasgui/perspectives/corfunc/corfunc_panel.py b/src/sas/sasgui/perspectives/corfunc/corfunc_panel.py index ea3c2e30df..30787fa92a 100644 --- a/src/sas/sasgui/perspectives/corfunc/corfunc_panel.py +++ b/src/sas/sasgui/perspectives/corfunc/corfunc_panel.py @@ -16,7 +16,7 @@ import sas.sasgui.perspectives.corfunc.corfunc from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator from sas.sasgui.guiframe.documentation_window import DocumentationWindow -from plot_labels import * +from .plot_labels import * OUTPUT_STRINGS = { 'max': "Long Period (A): ", @@ -395,7 +395,7 @@ def set_extrapolation_params(self, params=None): for output in self._extrapolation_outputs.values(): output.SetValue('-') return - for key, value in params.iteritems(): + for key, value in params.items(): output = self._extrapolation_outputs[key] rounded = self._round_sig_figs(value, 6) output.SetValue(rounded) @@ -416,7 +416,7 @@ def set_extracted_params(self, params=None, reset=False): if len(params) < len(OUTPUT_STRINGS): # Not all parameters were calculated error = True - for key, value in params.iteritems(): + for key, value in params.items(): rounded = self._round_sig_figs(value, 6) self._output_boxes[key].SetValue(rounded) if error: @@ -548,7 +548,7 @@ def _do_layout(self): file_sizer.Add(self._data_name_box, (0, 1), (1, 1), wx.CENTER | wx.ADJUST_MINSIZE, 15) - file_sizer.AddSpacer((1, 25), pos=(0,2)) + #file_sizer.AddSpacer((1, 25), pos=(0,2)) databox_sizer.Add(file_sizer, wx.TOP, 15) vbox.Add(databox_sizer, (y, 0), (1, 1), @@ -712,7 +712,7 @@ def _do_layout(self): self._output_boxes = dict() i = 0 - for key, value in OUTPUT_STRINGS.iteritems(): + for key, value in OUTPUT_STRINGS.items(): # Create a label and a text box for each poperty label = wx.StaticText(self, -1, value) output_box = OutputTextCtrl(self, wx.NewId(), diff --git a/src/sas/sasgui/perspectives/corfunc/corfunc_state.py b/src/sas/sasgui/perspectives/corfunc/corfunc_state.py index d5bbb80a14..d12ccde8a0 100644 --- a/src/sas/sasgui/perspectives/corfunc/corfunc_state.py +++ b/src/sas/sasgui/perspectives/corfunc/corfunc_state.py @@ -73,7 +73,7 @@ def __str__(self): if self.outputs != {} and self.outputs is not None: state += "\nOutputs:\n" - for key, value in self.outputs.iteritems(): + for key, value in self.outputs.items(): name = output_list[key][1] state += "{}: {}\n".format(name, str(value)) @@ -157,7 +157,7 @@ def toXML(self, filename='corfunc_state.crf', doc=None, entry_node=None): # Current state state = new_doc.createElement("state") top_element.appendChild(state) - for name, value in self.saved_state.iteritems(): + for name, value in self.saved_state.items(): element = new_doc.createElement(name) element.appendChild(new_doc.createTextNode(str(value))) state.appendChild(element) @@ -180,7 +180,7 @@ def toXML(self, filename='corfunc_state.crf', doc=None, entry_node=None): if self.outputs != {} and self.outputs is not None: output = new_doc.createElement("output") top_element.appendChild(output) - for key, value in self.outputs.iteritems(): + for key, value in self.outputs.items(): element = new_doc.createElement(key) element.appendChild(new_doc.createTextNode(str(value))) output.appendChild(element) @@ -213,15 +213,15 @@ def fromXML(self, node): if entry is not None and entry.get('epoch'): try: self.timestamp = (entry.get('epoch')) - except: + except Exception as exc: msg = ("CorfuncState.fromXML: Could not read timestamp", - "\n{}").format(sys.exc_value) + "\n{}").format(exc) logger.error(msg) # Parse current state entry = get_content('ns:state', node) if entry is not None: - for item in DEFAULT_STATE.iterkeys(): + for item in DEFAULT_STATE.keys(): input_field = get_content("ns:{}".format(item), entry) if input_field is not None: try: @@ -282,7 +282,7 @@ def read(self, path): basename = os.path.basename(path) root, ext = os.path.splitext(basename) if not ext.lower() in self.ext: - raise IOError, "{} is not a supported file type".format(ext) + raise IOError("{} is not a supported file type".format(ext)) tree = etree.parse(path, parser=etree.ETCompatXMLParser()) root = tree.getroot() entry_list = root.xpath('/ns:SASroot/ns:SASentry', @@ -298,7 +298,7 @@ def read(self, path): else: # File not found msg = "{} is not a valid file path or doesn't exist".format(path) - raise IOError, msg + raise IOError(msg) if len(output) == 0: return None @@ -322,7 +322,7 @@ def write(self, filename, datainfo=None, state=None): elif not (isinstance(datainfo, Data1D) or isinstance(datainfo, LoaderData1D)): msg = ("The CanSAS writer expects a Data1D instance. {} was " "provided").format(datainfo.__class__.__name__) - raise RuntimeError, msg + raise RuntimeError(msg) if datainfo.title is None or datainfo.title == '': datainfo.title = datainfo.name if datainfo.run_name is None or datainfo.run_name == '': @@ -357,8 +357,8 @@ def _parse_state(self, entry): if nodes != []: state = CorfuncState() state.fromXML(nodes[0]) - except: + except Exception as exc: msg = "XML document does not contain CorfuncState information\n{}" - msg.format(sys.exc_value) + msg.format(exc) logger.info(msg) return state diff --git a/src/sas/sasgui/perspectives/file_converter/__init__.py b/src/sas/sasgui/perspectives/file_converter/__init__.py index bf6038e0b1..85d906e9e2 100644 --- a/src/sas/sasgui/perspectives/file_converter/__init__.py +++ b/src/sas/sasgui/perspectives/file_converter/__init__.py @@ -1,2 +1,2 @@ PLUGIN_ID = "File-Converter Plug-In 1.0" -from file_converter import * +from .file_converter import * diff --git a/src/sas/sasgui/perspectives/file_converter/converter_panel.py b/src/sas/sasgui/perspectives/file_converter/converter_panel.py index 9ad5ee4059..23951b4f1c 100644 --- a/src/sas/sasgui/perspectives/file_converter/converter_panel.py +++ b/src/sas/sasgui/perspectives/file_converter/converter_panel.py @@ -111,7 +111,7 @@ def convert_to_cansas(self, frame_data, filepath, single_file): # Folder and base filename [group_path, group_name] = os.path.split(filepath) ext = "." + group_name.split('.')[-1] # File extension - for frame_number, frame_data in frame_data.iteritems(): + for frame_number, frame_data in frame_data.items(): # Append frame number to base filename filename = group_name.replace(ext, str(frame_number)+ext) destination = os.path.join(group_path, filename) @@ -154,7 +154,7 @@ def extract_ascii_data(self, filename): end_char = data[0][-1] # If lines end with comma or semi-colon, trim the last character if end_char == ',' or end_char == ';': - data = map(lambda s: s[0:-1], data) + data = [s[0:-1] for s in data] else: msg = ("Error reading {}: Lines must end with a digit, comma " "or semi-colon").format(filename.split('\\')[-1]) @@ -274,7 +274,7 @@ def ask_frame_range(self, n_frames): StatusEvent(status=msg)) else: return { 'frames': [], 'inc': None, 'file': single_file } - frames = range(first_frame, last_frame + 1, increment) + frames = list(range(first_frame, last_frame + 1, increment)) return { 'frames': frames, 'inc': increment, 'file': single_file } def get_metadata(self): @@ -334,15 +334,15 @@ def convert_1d_data(self, qdata, iqdata): frame_data[i] = data if single_file: # Only need to set metadata on first Data1D object - frame_data = frame_data.values() # Don't need to know frame numbers + frame_data = list(frame_data.values()) # Don't need to know frame numbers frame_data[0].filename = output_path.split('\\')[-1] - for key, value in metadata.iteritems(): + for key, value in metadata.items(): setattr(frame_data[0], key, value) else: # Need to set metadata for all Data1D objects for datainfo in frame_data.values(): datainfo.filename = output_path.split('\\')[-1] - for key, value in metadata.iteritems(): + for key, value in metadata.items(): setattr(datainfo, key, value) _, ext = os.path.splitext(output_path) @@ -354,7 +354,7 @@ def convert_1d_data(self, qdata, iqdata): def convert_2d_data(self, dataset): metadata = self.get_metadata() - for key, value in metadata.iteritems(): + for key, value in metadata.items(): setattr(dataset[0], key, value) w = NXcanSASWriter() diff --git a/src/sas/sasgui/perspectives/file_converter/converter_widgets.py b/src/sas/sasgui/perspectives/file_converter/converter_widgets.py index a0df9e02f1..a185b70136 100644 --- a/src/sas/sasgui/perspectives/file_converter/converter_widgets.py +++ b/src/sas/sasgui/perspectives/file_converter/converter_widgets.py @@ -53,7 +53,7 @@ def GetValue(self): """ v = Vector() if not self.Validate(): return v - for direction, control in self._inputs.iteritems(): + for direction, control in self._inputs.items(): try: value = float(control.GetValue()) setattr(v, direction, value) diff --git a/src/sas/sasgui/perspectives/fitting/__init__.py b/src/sas/sasgui/perspectives/fitting/__init__.py index 9bde9b2e2d..92e8515f1e 100644 --- a/src/sas/sasgui/perspectives/fitting/__init__.py +++ b/src/sas/sasgui/perspectives/fitting/__init__.py @@ -1,7 +1,7 @@ PLUGIN_ID = "Fitting plug-in 1.0" import os -from fitting import * from distutils.filelist import findall +from .fitting import * def get_data_path(media): """ """ diff --git a/src/sas/sasgui/perspectives/fitting/basepage.py b/src/sas/sasgui/perspectives/fitting/basepage.py index 55ce493865..062a31fa3e 100644 --- a/src/sas/sasgui/perspectives/fitting/basepage.py +++ b/src/sas/sasgui/perspectives/fitting/basepage.py @@ -11,7 +11,10 @@ import json import logging import traceback -from Queue import Queue +try: # CRUFT: python 2.x + from Queue import Queue +except ImportError: + from queue import Queue from threading import Thread from collections import defaultdict @@ -65,6 +68,8 @@ PANEL_WIDTH = 500 FONT_VARIANT = 1 ON_MAC = True +if sys.version_info[0] >= 3: + unicode = str CUSTOM_MODEL = 'Plugin Models' @@ -114,7 +119,7 @@ def __init__(self, parent, color='blue', **kwargs): self.graph_id = None # Q range for data set self.qmin_data_set = np.inf - self.qmax_data_set = None + self.qmax_data_set = -np.inf self.npts_data_set = 0 # Q range self.qmin = None @@ -623,7 +628,7 @@ def onResetModel(self, event): self._on_select_model_helper() if self.model is not None: self.m_name = self.model.name - if name in self.saved_states.keys(): + if name in self.saved_states: previous_state = self.saved_states[name] # reset state of checkbox,textcrtl and regular parameters value @@ -892,7 +897,7 @@ def save_current_state(self): self.state.slit_smearer = copy.deepcopy(self.slit_smearer.GetValue()) if len(self._disp_obj_dict) > 0: - for k, v in self._disp_obj_dict.iteritems(): + for k, v in self._disp_obj_dict.items(): self.state.disp_obj_dict[k] = v.type self.state.values = copy.deepcopy(self.values) @@ -959,7 +964,7 @@ def save_current_state_fit(self): self.state.disp_box = self.disp_box.GetCurrentSelection() if len(self.disp_cb_dict) > 0: - for k, v in self.disp_cb_dict.iteritems(): + for k, v in self.disp_cb_dict.items(): if v is None: self.state.disp_cb_dict[k] = v else: @@ -968,7 +973,7 @@ def save_current_state_fit(self): except Exception: self.state.disp_cb_dict[k] = None if len(self._disp_obj_dict) > 0: - for k, v in self._disp_obj_dict.iteritems(): + for k, v in self._disp_obj_dict.items(): self.state.disp_obj_dict[k] = v.type self.state.values = copy.deepcopy(self.values) @@ -1096,8 +1101,7 @@ def set_model_state(self, state): [state.values, state.weights] else: - keys = self.model.getParamList() - for item in keys: + for item in self.model.getParamList(): if item in self.disp_list and \ item not in self.model.details: self.model.details[item] = ["", None, None] @@ -1141,7 +1145,7 @@ def get_cat_combo_box_pos(self, state): Iterate through the categories to find the structurefactor :return: combo_box_position """ - for key, value in self.master_category_dict.iteritems(): + for key, value in self.master_category_dict.items(): formfactor = state.formfactorcombobox.split(":") if isinstance(formfactor, list): formfactor = formfactor[0] @@ -1317,18 +1321,17 @@ def _reset_page_disp_helper(self, state): """ Help to rest page for dispersions """ - keys = self.model.getParamList() - for item in keys: + for item in self.model.getParamList(): if item in self.disp_list and \ item not in self.model.details: self.model.details[item] = ["", None, None] - # for k,v in self.state.disp_cb_dict.iteritems(): + # for k,v in self.state.disp_cb_dict.items(): self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) self.values = copy.deepcopy(state.values) self.weights = copy.deepcopy(state.weights) - for key, disp_type in state.disp_obj_dict.iteritems(): + for key, disp_type in state.disp_obj_dict.items(): # disp_model = disp disp_model = POLYDISPERSITY_MODELS[disp_type]() self._disp_obj_dict[key] = disp_model @@ -1377,7 +1380,7 @@ def _selectDlg(self): self._manager.parent.get_save_location() dlg = wx.FileDialog(self, "Choose a weight file", self._default_save_location, "", - "*.*", wx.OPEN) + "*.*", wx.FD_OPEN) path = None if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() @@ -1389,7 +1392,7 @@ def _reset_context_menu(self): reset the context menu """ ids = iter(self._id_pool) # Reusing ids for context menu - for name, _ in self.state.saved_states.iteritems(): + for name, _ in self.state.saved_states.items(): self.number_saved_state += 1 # Add item in the context menu wx_id = ids.next() @@ -1918,13 +1921,13 @@ def _onQrangeEnter(self, event): self.qmax_x = tempmax else: tcrtl.SetBackgroundColour("pink") - msg = "Model Error: wrong value entered: %s" % \ - sys.exc_info()[1] + _, exc, _ = sys.exc_info() + msg = "Model Error: wrong value entered: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg)) return - except Exception: + except Exception as exc: tcrtl.SetBackgroundColour("pink") - msg = "Model Error: wrong value entered: %s" % sys.exc_info()[1] + msg = "Model Error: wrong value entered: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg)) return # Check if # of points for theory model are valid(>0). @@ -1975,13 +1978,13 @@ def _theory_qrange_enter(self, event): self.theory_qmax_x = tempmax else: tcrtl.SetBackgroundColour("pink") - msg = "Model Error: wrong value entered: %s" % \ - sys.exc_info()[1] + _, exc, _ = sys.exc_info() + msg = "Model Error: wrong value entered: %s" % exc wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) return - except Exception: + except Exception as exc: tcrtl.SetBackgroundColour("pink") - msg = "Model Error: wrong value entered: %s" % sys.exc_info()[1] + msg = "Model Error: wrong value entered: %s" % exc wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) return # Check if # of points for theory model are valid(>0). @@ -2290,7 +2293,7 @@ def _check_value_enter(self, list): value = high value_ctrl.SetValue(format_number(value)) - if name not in self.model.details.keys(): + if name not in self.model.details: self.model.details[name] = ["", None, None] old_low, old_high = self.model.details[name][1:3] if old_low != low or old_high != high: @@ -2749,7 +2752,7 @@ def get_images(self): # call gui_manager gui_manager = self._manager.parent # loops through the panels [dic] - for _, item2 in gui_manager.plot_panels.iteritems(): + for _, item2 in gui_manager.plot_panels.items(): data_title = self.data.group_id # try to get all plots belonging to this control panel try: @@ -3323,7 +3326,7 @@ def _get_paste_helper(self, param, orient_param, content): # 2D if self.data.__class__.__name__ == "Data2D": name = item[1] - if name in content.keys(): + if name in content: values = content[name] check = values[0] pd = values[1] @@ -3372,7 +3375,7 @@ def _get_paste_helper(self, param, orient_param, content): # for 1D all parameters except orientation if not item[1] in orient_param: name = item[1] - if name in content.keys(): + if name in content: check = content[name][0] # Avoid changing combox content value = content[name][1:] @@ -3479,10 +3482,9 @@ def _paste_poly_help(self, item, value): self.state.values = self.values self.state.weights = self.weights - except Exception: + except Exception as exc: logger.error(traceback.format_exc()) - print("Error in BasePage._paste_poly_help: %s" % \ - sys.exc_info()[1]) + print("Error in BasePage._paste_poly_help: %s" % exc) def _set_disp_cb(self, isarray, item): """ @@ -3547,7 +3549,7 @@ def _populate_listbox(self): self._read_category_info() self.categorybox.Clear() - cat_list = sorted(self.master_category_dict.keys()) + cat_list = list(sorted(self.master_category_dict.keys())) if uncat_str not in cat_list: cat_list.append(uncat_str) diff --git a/src/sas/sasgui/perspectives/fitting/fit_thread.py b/src/sas/sasgui/perspectives/fitting/fit_thread.py index 86c4354715..175efa51f9 100644 --- a/src/sas/sasgui/perspectives/fitting/fit_thread.py +++ b/src/sas/sasgui/perspectives/fitting/fit_thread.py @@ -11,7 +11,8 @@ def map_getattr(classInstance, classFunc, *args): return getattr(classInstance, classFunc)(*args) def map_apply(arguments): - return apply(arguments[0], arguments[1:]) + fn, args = arguments[0], arguments[1:] + return fn(*args) class FitThread(CalcThread): """Thread performing the fit """ @@ -49,7 +50,7 @@ def isquit(self): CalcThread.isquit(self) except KeyboardInterrupt: msg = "Fitting: terminated by the user." - raise KeyboardInterrupt, msg + raise KeyboardInterrupt(msg) def compute(self): """ @@ -75,7 +76,7 @@ def compute(self): inputs = zip(list_map_get_attr, self.fitter, list_fit_function, list_q, list_q, list_handler, list_curr_thread, list_reset_flag) - result = map(map_apply, inputs) + result = list(map(map_apply, inputs)) self.complete(result=result, batch_inputs=self.batch_inputs, @@ -84,7 +85,7 @@ def compute(self): pars=self.pars, elapsed=time.time() - self.starttime) - except KeyboardInterrupt, msg: + except KeyboardInterrupt as msg: # Thread was interrupted, just proceed and re-raise. # Real code should not print, but this is an example... #print "keyboard exception" diff --git a/src/sas/sasgui/perspectives/fitting/fitpage.py b/src/sas/sasgui/perspectives/fitting/fitpage.py index 5567b36f5e..f3baf06b93 100644 --- a/src/sas/sasgui/perspectives/fitting/fitpage.py +++ b/src/sas/sasgui/perspectives/fitting/fitpage.py @@ -779,7 +779,7 @@ def _set_sizer_dispersion(self): ix = 8 disp_box = wx.ComboBox(self, wx.ID_ANY, size=(65, -1), style=wx.CB_READONLY, name='%s' % name1) - for key, value in POLYDISPERSITY_MODELS.iteritems(): + for key, value in POLYDISPERSITY_MODELS.items(): name_disp = str(key) disp_box.Append(name_disp, value) disp_box.SetStringSelection("gaussian") @@ -937,7 +937,7 @@ def _set_sizer_dispersion(self): ix = 8 disp_box = wx.ComboBox(self, wx.ID_ANY, size=(65, -1), style=wx.CB_READONLY, name='%s' % name1) - for key, value in POLYDISPERSITY_MODELS.iteritems(): + for key, value in POLYDISPERSITY_MODELS.items(): name_disp = str(key) disp_box.Append(name_disp, value) disp_box.SetStringSelection("gaussian") @@ -1377,9 +1377,9 @@ def _onparamRangeEnter(self, event): tcrtl.SetBackgroundColour(wx.WHITE) self._check_value_enter(self.fittable_param) self._check_value_enter(self.parameters) - except: + except Exception as exc: tcrtl.SetBackgroundColour("pink") - msg = "Model Error:wrong value entered : %s" % sys.exc_value + msg = "Model Error:wrong value entered : %s" % exc wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) return else: @@ -1491,12 +1491,13 @@ def _onQrangeEnter(self, event): self.qmax_x = tempmax else: tcrtl.SetBackgroundColour("pink") - msg = "Model Error:wrong value entered : %s" % sys.exc_value + _, exc, _ = sys.exc_info() + msg = "Model Error:wrong value entered : %s" % exc wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) return - except: + except Exception as exc: tcrtl.SetBackgroundColour("pink") - msg = "Model Error:wrong value entered : %s" % sys.exc_value + msg = "Model Error:wrong value entered : %s" % exc wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) return # Check if # of points for theory model are valid(>0). @@ -1901,7 +1902,7 @@ def compute_data_range(self, data): data.filename wx.PostEvent(self._manager.parent, StatusEvent(status=msg, info="error")) - raise ValueError, msg + raise ValueError(msg) else: qmin = 0 @@ -1913,7 +1914,7 @@ def compute_data_range(self, data): data.filename wx.PostEvent(self._manager.parent, StatusEvent(status=msg, info="error")) - raise ValueError, msg + raise ValueError(msg) # Maximum value of data qmax = math.sqrt(x * x + y * y) npts = len(data.data) @@ -2153,7 +2154,7 @@ def onsetValues(self, chisqr, p_name, out, cov): # make sure stop button to fit button all the time self._on_fit_complete() if out is None or not np.isfinite(chisqr): - raise ValueError, "Fit error occured..." + raise ValueError("Fit error occured...") is_modified = False has_error = False @@ -2228,7 +2229,7 @@ def onsetValues(self, chisqr, p_name, out, cov): has_error = True i += 1 else: - raise ValueError, "onsetValues: Invalid parameters..." + raise ValueError("onsetValues: Invalid parameters...") # Show error title when any errors displayed if has_error: if not self.text2_3.IsShown(): @@ -2984,9 +2985,9 @@ def custom_compare(a, b): # type can be either Guassian or Array if len(self.model.dispersion.values()) > 0: - type = self.model.dispersion.values()[0]["type"] + dist_type = list(self.model.dispersion.values())[0]["type"] else: - type = "Gaussian" + dist_type = "Gaussian" iy += 1 ix = 0 @@ -3044,7 +3045,7 @@ def custom_compare(a, b): break # For Gaussian only - if type.lower() != "array": + if dist_type.lower() != "array": for item in self.model.orientation_params: if not self.magnetic_on: if item in self.model.magnetic_params: diff --git a/src/sas/sasgui/perspectives/fitting/fitpanel.py b/src/sas/sasgui/perspectives/fitting/fitpanel.py index 38363473ed..c57cb837fe 100644 --- a/src/sas/sasgui/perspectives/fitting/fitpanel.py +++ b/src/sas/sasgui/perspectives/fitting/fitpanel.py @@ -93,7 +93,7 @@ def save_project(self, doc=None): if self.sim_page is not None: batch_state = self.sim_page.set_state() - for uid, page in self.opened_pages.iteritems(): + for uid, page in self.opened_pages.items(): data = page.get_data() # state must be cloned state = page.get_state().clone() @@ -134,7 +134,7 @@ def get_page_by_id(self, uid): """ if uid not in self.opened_pages: msg = "Fitpanel cannot find ID: %s in self.opened_pages" % str(uid) - raise ValueError, msg + raise ValueError(msg) else: return self.opened_pages[uid] @@ -216,7 +216,7 @@ def set_state(self, state): """ page_is_opened = False if state is not None: - for uid, panel in self.opened_pages.iteritems(): + for uid, panel in self.opened_pages.items(): # Don't return any panel is the exact same page is created if uid == panel.uid and panel.data == state.data: # the page is still opened @@ -395,7 +395,7 @@ def delete_data(self, data): Delete the given data """ if data.__class__.__name__ != "list": - raise ValueError, "Fitpanel delete_data expect list of id" + raise ValueError("Fitpanel delete_data expect list of id") else: for page in self.opened_pages.values(): pos = self.GetPageIndex(page) @@ -591,7 +591,7 @@ def _close_helper(self, selected_page): flag = False if selected_page in page_finder: # Delete the name of the page into the list of open page - for uid, list in self.opened_pages.iteritems(): + for uid, list in self.opened_pages.items(): # Don't return any panel is the exact same page is created if flag and selected_page.uid == uid: self._manager.remove_plot(uid, theory=False) @@ -599,7 +599,7 @@ def _close_helper(self, selected_page): del page_finder[selected_page] # Delete the name of the page into the list of open page - for uid, list in self.opened_pages.iteritems(): + for uid, list in self.opened_pages.items(): # Don't return any panel is the exact same page is created if selected_page.uid == uid: del self.opened_pages[selected_page.uid] diff --git a/src/sas/sasgui/perspectives/fitting/fitproblem.py b/src/sas/sasgui/perspectives/fitting/fitproblem.py index 85f4a13e38..754d35eb37 100644 --- a/src/sas/sasgui/perspectives/fitting/fitproblem.py +++ b/src/sas/sasgui/perspectives/fitting/fitproblem.py @@ -544,7 +544,7 @@ def get_fit_problem(self): """ return fitproblem contained in this dictionary """ - return self.values() + return list(self.values()) def set_result(self, result, fid): """ diff --git a/src/sas/sasgui/perspectives/fitting/fitting.py b/src/sas/sasgui/perspectives/fitting/fitting.py index b9a985e589..38ef0be798 100644 --- a/src/sas/sasgui/perspectives/fitting/fitting.py +++ b/src/sas/sasgui/perspectives/fitting/fitting.py @@ -146,7 +146,7 @@ def delete_fit_problem(self, page_id): """ Given an ID create a fitproblem container """ - if page_id in self.page_finder.iterkeys(): + if page_id in self.page_finder: del self.page_finder[page_id] def add_color(self, color, id): @@ -355,7 +355,7 @@ def update_custom_combo(self): # Set the new plugin model list for all fit pages; anticipating # categories, the updated plugin may be in either the form factor # or the structure factor combo boxes - for uid, page in self.fit_panel.opened_pages.iteritems(): + for uid, page in self.fit_panel.opened_pages.items(): pbox = getattr(page, "formfactorbox", None) sbox = getattr(page, "structurebox", None) if pbox is None: @@ -416,8 +416,8 @@ def update_custom_combo(self): break self.fit_panel.SetSelection(current_page_index) - except Exception: - logger.error("update_custom_combo: %s", sys.exc_value) + except Exception as exc: + logger.error("update_custom_combo: %s", exc) def set_edit_menu(self, owner): """ @@ -641,8 +641,8 @@ def set_data(self, data_list=None): if group_id not in data.list_group_id: data.list_group_id.append(group_id) self.add_fit_page(data=[data]) - except: - msg = "Fitting set_data: " + str(sys.exc_value) + except Exception as exc: + msg = "Fitting set_data: " + str(exc) wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) def set_theory(self, theory_list=None): @@ -653,10 +653,10 @@ def set_theory(self, theory_list=None): try: _, theory_state = item self.fit_panel.set_model_state(theory_state) - except Exception: + except Exception as exc: msg = "Fitting: cannot deal with the theory received" evt = StatusEvent(status=msg, info="error") - logger.error("set_theory " + msg + "\n" + str(sys.exc_value)) + logger.error("set_theory " + msg + "\n" + str(exc)) wx.PostEvent(self.parent, evt) def set_state(self, state=None, datainfo=None, format=None): @@ -777,7 +777,7 @@ def set_fit_weight(self, uid, flag, is2d=False, fid=None): """ # Note: this is used to set the data weights for the fit based on # the weight selection in the GUI. - if uid in self.page_finder.keys(): + if uid in self.page_finder: self.page_finder[uid].set_weight(flag=flag, is2d=is2d) def set_fit_range(self, uid, qmin, qmax, fid=None): @@ -790,7 +790,7 @@ def set_fit_range(self, uid, qmin, qmax, fid=None): :param qmin: minimum value of the fit range :param qmax: maximum value of the fit range """ - if uid in self.page_finder.keys(): + if uid in self.page_finder: self.page_finder[uid].set_range(qmin=qmin, qmax=qmax, fid=fid) def schedule_for_fit(self, value=0, uid=None): @@ -801,7 +801,7 @@ def schedule_for_fit(self, value=0, uid=None): :param value: integer 0 or 1 :param uid: the id related to a page containing fitting information """ - if uid in self.page_finder.keys(): + if uid in self.page_finder: self.page_finder[uid].schedule_tofit(value) def get_page_finder(self): @@ -820,7 +820,7 @@ def set_page_finder(self, modelname, names, values): :param names: the parameter name """ sim_page_id = self.sim_page.uid - for uid, value in self.page_finder.iteritems(): + for uid, value in self.page_finder.items(): if uid != sim_page_id and uid != self.batch_page.uid: model_list = value.get_model() model = model_list[0] @@ -885,7 +885,7 @@ def stop_fit(self, uid): """ Stop the fit """ - if uid in self.fit_thread_list.keys(): + if uid in self.fit_thread_list: calc_fit = self.fit_thread_list[uid] if calc_fit is not None and calc_fit.isrunning(): calc_fit.stop() @@ -897,9 +897,9 @@ def stop_fit(self, uid): sim_flag = self.sim_page is not None and uid == self.sim_page.uid batch_flag = self.batch_page is not None and uid == self.batch_page.uid if sim_flag or batch_flag: - for uid, value in self.page_finder.iteritems(): + for uid, value in self.page_finder.items(): if value.get_scheduled() == 1: - if uid in self.fit_panel.opened_pages.keys(): + if uid in self.fit_panel.opened_pages: panel = self.fit_panel.opened_pages[uid] panel._on_fit_complete() @@ -916,7 +916,7 @@ def set_smearer(self, uid, smearer, fid, qmin=None, qmax=None, draw=True, :param qmax: the maximum value of the theory plotting range :param draw: Determine if the theory needs to be plot """ - if uid not in self.page_finder.keys(): + if uid not in self.page_finder: return self.page_finder[uid].enable_smearing(flag=enable_smearer) self.page_finder[uid].set_smearer(smearer, fid=fid) @@ -927,7 +927,7 @@ def set_smearer(self, uid, smearer, fid, qmin=None, qmax=None, draw=True, msg = "set_mearer requires at least data.\n" msg += "Got data = %s .\n" % str(data) return - #raise ValueError, msg + #raise ValueError(msg) model = self.page_finder[uid].get_model(fid=fid) if model is None: return @@ -1029,7 +1029,7 @@ def onFit(self, uid): self.current_pg = None list_page_id = [] fit_id = 0 - for page_id, page_info in self.page_finder.iteritems(): + for page_id, page_info in self.page_finder.items(): # For simulfit (uid give with None), do for-loop # if uid is specified (singlefit), do it only on the page. if page_id in (sim_page_uid, batch_page_uid): continue @@ -1056,8 +1056,7 @@ def onFit(self, uid): return False pars = [str(element[1]) for element in page.param_toFit] - fitproblem_list = page_info.values() - for fitproblem in fitproblem_list: + for fitproblem in page_info.values(): if sim_fitter is None: fitter = Fit() fitter.fitter_id = page_id @@ -1076,9 +1075,9 @@ def onFit(self, uid): evt = StatusEvent(status=msg, info="info", type="stop") wx.PostEvent(self.parent, evt) return True - except: + except Exception as exc: raise - msg = "Fitting error: %s" % str(sys.exc_value) + msg = "Fitting error: %s" % exc evt = StatusEvent(status=msg, info="error", type="stop") wx.PostEvent(self.parent, evt) return False @@ -1135,7 +1134,7 @@ def remove_plot(self, uid, fid=None, theory=False): :param uid: the id related to the fitpage to close :param fid: the id of the fitproblem(data, model, range,etc) """ - if uid not in self.page_finder.keys(): + if uid not in self.page_finder: return fitproblemList = self.page_finder[uid].get_fit_problem(fid) for fitproblem in fitproblemList: @@ -1180,8 +1179,8 @@ def on_add_new_page(self, event=None): msg = "Page was already Created" evt = StatusEvent(status=msg, info="warning") wx.PostEvent(self.parent, evt) - except Exception: - msg = "Creating Fit page: %s" % sys.exc_value + except Exception as exc: + msg = "Creating Fit page: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) def add_fit_page(self, data): @@ -1261,11 +1260,11 @@ def _reset_schedule_problem(self, value=0, uid=None): """ # case that uid is not specified if uid is None: - for page_id in self.page_finder.keys(): + for page_id in self.page_finder: self.page_finder[page_id].schedule_tofit(value) # when uid is given else: - if uid in self.page_finder.keys(): + if uid in self.page_finder: self.page_finder[uid].schedule_tofit(value) def _add_problem_to_fit(self, fitproblem, pars, fitter, fit_id): @@ -1299,7 +1298,7 @@ def _onSelect(self, event): """ panel = self.plot_panel if panel is None: - raise ValueError, "Fitting:_onSelect: NonType panel" + raise ValueError("Fitting:_onSelect: NonType panel") Plugin.on_perspective(self, event=event) self.select_data(panel) @@ -1332,7 +1331,7 @@ def _batch_fit_complete(self, result, pars, page_id, :param elapsed: time spent at the fitting level """ uid = page_id[0] - if uid in self.fit_thread_list.keys(): + if uid in self.fit_thread_list: del self.fit_thread_list[uid] wx.CallAfter(self._update_fit_button, page_id) @@ -1358,18 +1357,18 @@ def _batch_fit_complete(self, result, pars, page_id, model = model.model #get all fittable parameters of the current model for param in model.getParamList(): - if param not in batch_outputs.keys(): + if param not in batch_outputs: batch_outputs[param] = [] for param in model.getDispParamList(): if not model.is_fittable(param) and \ - param in batch_outputs.keys(): + param in batch_outputs: del batch_outputs[param] # Add fitted parameters and their error for param in res.param_list: - if param not in batch_outputs.keys(): + if param not in batch_outputs: batch_outputs[param] = [] err_param = "error on %s" % str(param) - if err_param not in batch_inputs.keys(): + if err_param not in batch_inputs: batch_inputs[err_param] = [] msg = "" for list_res in result: @@ -1523,7 +1522,7 @@ def on_set_batch_result(self, page_id, fid, batch_outputs, batch_inputs): data = fitproblem.get_fit_data() model = fitproblem.get_model() #fill batch result information - if "Data" not in batch_outputs.keys(): + if "Data" not in batch_outputs: batch_outputs["Data"] = [] cell = BatchCell() cell.label = data.name @@ -1552,14 +1551,14 @@ def on_set_batch_result(self, page_id, fid, batch_outputs, batch_inputs): cell.object = [data, theory_data] batch_outputs["Data"].append(cell) - for key, value in data.meta_data.iteritems(): - if key not in batch_inputs.keys(): + for key, value in data.meta_data.items(): + if key not in batch_inputs: batch_inputs[key] = [] #if key.lower().strip() != "loader": batch_inputs[key].append(value) param = "temperature" if hasattr(data.sample, param): - if param not in batch_inputs.keys(): + if param not in batch_inputs: batch_inputs[param] = [] batch_inputs[param].append(data.sample.temperature) @@ -1630,9 +1629,8 @@ def _fit_completed(self, result, page_id, batch_outputs, evt = StatusEvent(status=fit_msg, info="warning", type="stop") wx.PostEvent(self.parent, evt) - except Exception: - msg = ("Fit completed but the following error occurred: %s" - % sys.exc_value) + except Exception as exc: + msg = "Fit completed but the following error occurred: %s" % exc #msg = "\n".join((traceback.format_exc(), msg)) evt = StatusEvent(status=msg, info="warning", type="stop") wx.PostEvent(self.parent, evt) @@ -1720,7 +1718,7 @@ def _on_model_panel(self, evt): enable_smearer = evt.enable_smearer if model is None: return - if uid not in self.page_finder.keys(): + if uid not in self.page_finder: return # save the name containing the data name with the appropriate model self.page_finder[uid].set_model(model) @@ -2077,9 +2075,9 @@ def _draw_model1D(self, model, page_id, data, exception_handler=self._calc_exception, source=source) self.calc_1D.queue() - except: + except Exception as exc: msg = " Error occurred when drawing %s Model 1D: " % model.name - msg += " %s" % sys.exc_value + msg += " %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg)) def _cal_chisqr(self, page_id, data, weight, fid=None, index=None): diff --git a/src/sas/sasgui/perspectives/fitting/model_thread.py b/src/sas/sasgui/perspectives/fitting/model_thread.py index 39c438429a..2fff5db639 100644 --- a/src/sas/sasgui/perspectives/fitting/model_thread.py +++ b/src/sas/sasgui/perspectives/fitting/model_thread.py @@ -64,7 +64,7 @@ def compute(self): if self.data is None: msg = "Compute Calc2D receive data = %s.\n" % str(self.data) - raise ValueError, msg + raise ValueError(msg) # Define matrix where data will be plotted radius = np.sqrt(self.data.qx_data**2 + self.data.qy_data**2) diff --git a/src/sas/sasgui/perspectives/fitting/resultpanel.py b/src/sas/sasgui/perspectives/fitting/resultpanel.py index 2ed83bf711..055ebf2465 100644 --- a/src/sas/sasgui/perspectives/fitting/resultpanel.py +++ b/src/sas/sasgui/perspectives/fitting/resultpanel.py @@ -58,7 +58,7 @@ def on_close(self, event): def on_plot_results(self, event): self.frame.Show(True) - result = event.result[0][0] + result = list(event.result[0])[0] filename = result.data.sas_data.filename current_time = datetime.datetime.now().strftime("%I:%M%p, %B %d, %Y") self.parent.SetTitle(self.window_name + " - " + filename + " - " + current_time) diff --git a/src/sas/sasgui/perspectives/fitting/simfitpage.py b/src/sas/sasgui/perspectives/fitting/simfitpage.py index c26ce59353..3abe7826e2 100644 --- a/src/sas/sasgui/perspectives/fitting/simfitpage.py +++ b/src/sas/sasgui/perspectives/fitting/simfitpage.py @@ -167,7 +167,7 @@ def load_from_save_state(self, sim_state): # Process each model and associate old M# with new M# i = 0 for model in self.model_list: - model_id = self._format_id(model[1].keys()[0]) + model_id = self._format_id(list(model[1].keys())[0]) for saved_model in sim_state.model_list: save_id = saved_model.pop('name') saved_model['name'] = save_id @@ -327,7 +327,7 @@ def _fill_sizer_model_list(self, sizer): tab_used.SetForegroundColour(wx.WHITE) sizer.Add(tab_used, (iy, ix), (1, 1), wx.EXPAND | wx.ADJUST_MINSIZE, 0) - for id, value in self.page_finder.iteritems(): + for id, value in self.page_finder.items(): if id not in self.parent.opened_pages: continue @@ -756,12 +756,12 @@ def _show_all_constraint(self): self.set_button.SetToolTipString(set_tip) self.set_button.Disable() - for id, model in self.constraint_dict.iteritems(): + for id, model in self.constraint_dict.items(): # check if all parameters have been selected for constraint # then do not allow add constraint on parameters self.model_cbox_left.Append(str(model.name), model) self.model_cbox_left.Select(0) - for id, model in self.constraint_dict.iteritems(): + for id, model in self.constraint_dict.items(): # check if all parameters have been selected for constraint # then do not allow add constraint on parameters self.model_cbox_right.Append(str(model.name), model) @@ -813,7 +813,7 @@ def _on_set_all_equal(self, event): selection_b = self.model_cbox_right.GetCurrentSelection() model_right = self.model_cbox_right.GetValue() model_b = self.model_cbox_right.GetClientData(selection_b) - for id, dic_model in self.constraint_dict.iteritems(): + for id, dic_model in self.constraint_dict.items(): if model == dic_model: param_list = self.page_finder[id].get_param2fit() if model_b == dic_model: @@ -856,7 +856,7 @@ def _show_constraint(self): self.btAdd.Show(True) if len(self.constraints_list) != 0: nb_fit_param = 0 - for id, model in self.constraint_dict.iteritems(): + for id, model in self.constraint_dict.items(): nb_fit_param += len(self.page_finder[id].get_param2fit()) # Don't add anymore if len(self.constraints_list) == nb_fit_param: @@ -878,7 +878,7 @@ def _show_constraint(self): # Model list model_cbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY) model_cbox.Clear() - for id, model in self.constraint_dict.iteritems(): + for id, model in self.constraint_dict.items(): # check if all parameters have been selected for constraint # then do not allow add constraint on parameters model_cbox.Append(str(model.name), model) @@ -930,7 +930,7 @@ def _hide_constraint(self): """ hide buttons related constraint """ - for id in self.page_finder.iterkeys(): + for id in self.page_finder.keys(): self.page_finder[id].clear_model_param() self.nb_constraint = 0 @@ -968,7 +968,7 @@ def _on_select_model(self, event): model = model_cbox.GetClientData(n) param_list = [] - for id, dic_model in self.constraint_dict.iteritems(): + for id, dic_model in self.constraint_dict.items(): if model == dic_model: param_list = self.page_finder[id].get_param2fit() break @@ -1055,7 +1055,7 @@ def _set_constraint(self): msg = " Constraint will be ignored!. missing parameters" msg += " in combobox to set constraint! " wx.PostEvent(self.parent.parent, StatusEvent(status=msg)) - for id, value in self.constraint_dict.iteritems(): + for id, value in self.constraint_dict.items(): if model == value: if constraint == "": msg = " Constraint will be ignored!. missing value" @@ -1079,7 +1079,7 @@ def _set_constraint(self): StatusEvent(info="error", status=msg)) return False - for fid in self.page_finder[id].iterkeys(): + for fid in self.page_finder[id].keys(): # wrap in param/constraint in str() to remove unicode self.page_finder[id].set_model_param(str(param), str(constraint), fid=fid) diff --git a/src/sas/sasgui/perspectives/invariant/__init__.py b/src/sas/sasgui/perspectives/invariant/__init__.py index 301a4a8058..adacdec9b8 100644 --- a/src/sas/sasgui/perspectives/invariant/__init__.py +++ b/src/sas/sasgui/perspectives/invariant/__init__.py @@ -2,7 +2,7 @@ import os from distutils.filelist import findall -from invariant import * +from .invariant import * def get_data_path(media): """ @@ -40,4 +40,4 @@ def data_files(): """ data_files = [] data_files.append(('media/invariant_media', findall(get_data_path("media")))) - return data_files \ No newline at end of file + return data_files diff --git a/src/sas/sasgui/perspectives/invariant/invariant.py b/src/sas/sasgui/perspectives/invariant/invariant.py index eeb7b6ba87..8a383204f0 100644 --- a/src/sas/sasgui/perspectives/invariant/invariant.py +++ b/src/sas/sasgui/perspectives/invariant/invariant.py @@ -132,7 +132,7 @@ def _compute_invariant(self, event): if not issubclass(data.__class__, Data1D): name = data.__class__.__name__ msg = "Invariant use only Data1D got: [%s] " % str(name) - raise ValueError, msg + raise ValueError(msg) self.compute_helper(data=data) def set_data(self, data_list=None): @@ -143,6 +143,8 @@ def set_data(self, data_list=None): data = None if data_list is None: data_list = [] + else: + data_list = list(data_list) # force iterator to list if len(data_list) >= 1: if len(data_list) == 1: data = data_list[0] @@ -189,8 +191,8 @@ def set_data(self, data_list=None): wx.PostEvent(self.parent, NewPlotEvent(plot=data, title=data.title)) try: self.compute_helper(data) - except: - msg = "Invariant Set_data: " + str(sys.exc_value) + except Exception as exc: + msg = "Invariant Set_data: " + str(exc) wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) else: msg = "invariant cannot be computed for data of " @@ -239,7 +241,7 @@ def save_file(self, filepath, state=None): else: msg = "invariant.save_file: the data being saved is" msg += " not a sas.sascalc.dataloader.data_info.Data1D object" - raise RuntimeError, msg + raise RuntimeError(msg) def set_state(self, state=None, datainfo=None): """ @@ -257,7 +259,7 @@ def set_state(self, state=None, datainfo=None): if data is None: msg = "invariant.set_state: datainfo parameter cannot" msg += " be None in standalone mode" - raise RuntimeError, msg + raise RuntimeError(msg) # Make sure the user sees the invariant panel after loading # self.parent.set_perspective(self.perspective) self.on_perspective(event=None) @@ -280,8 +282,8 @@ def set_state(self, state=None, datainfo=None): # Requires to have self.__data and self.temp_state first. self.on_set_state_helper(None) - except: - logger.error("invariant.set_state: %s" % sys.exc_value) + except Exception as exc: + logger.error("invariant.set_state: %s" % exc) def on_set_state_helper(self, event=None): """ @@ -319,7 +321,7 @@ def plot_theory(self, data=None, name=None): new_plot.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM else: msg = "Scale can not be zero." - raise ValueError, msg + raise ValueError(msg) if len(new_plot.x) == 0: return diff --git a/src/sas/sasgui/perspectives/invariant/invariant_details.py b/src/sas/sasgui/perspectives/invariant/invariant_details.py index c77737bb08..157f65243d 100644 --- a/src/sas/sasgui/perspectives/invariant/invariant_details.py +++ b/src/sas/sasgui/perspectives/invariant/invariant_details.py @@ -1,11 +1,13 @@ """ Invariant panel """ -import wx import sys +import wx + from sas.sasgui.guiframe.utils import format_number -from invariant_widgets import OutputTextCtrl +from .invariant_widgets import OutputTextCtrl + # Dimensions related to chart RECTANGLE_WIDTH = 400.0 RECTANGLE_HEIGHT = 20 @@ -32,7 +34,7 @@ INVARIANT_COLOR = wx.Colour(67, 208, 128, 128) -class InvariantContainer(wx.Object): +class InvariantContainer: """ This class stores some values resulting resulting from invariant calculations. Given the value of total invariant, this class can also diff --git a/src/sas/sasgui/perspectives/invariant/invariant_panel.py b/src/sas/sasgui/perspectives/invariant/invariant_panel.py index 19d0d86cb8..3cfc0221da 100644 --- a/src/sas/sasgui/perspectives/invariant/invariant_panel.py +++ b/src/sas/sasgui/perspectives/invariant/invariant_panel.py @@ -318,12 +318,12 @@ def get_background(self): """ background = self.background_tcl.GetValue().lstrip().rstrip() if background == "": - raise ValueError, "Need a background" + raise ValueError("Need a background") if check_float(self.background_tcl): return float(background) else: msg = "Receive invalid value for background : %s" % (background) - raise ValueError, msg + raise ValueError(msg) def get_scale(self): """ @@ -331,16 +331,16 @@ def get_scale(self): """ scale = self.scale_tcl.GetValue().lstrip().rstrip() if scale == "": - raise ValueError, "Need a background" + raise ValueError("Need a background") if check_float(self.scale_tcl): if float(scale) <= 0.0: self.scale_tcl.SetBackgroundColour("pink") self.scale_tcl.Refresh() msg = "Receive invalid value for scale: %s" % (scale) - raise ValueError, msg + raise ValueError(msg) return float(scale) else: - raise ValueError, "Receive invalid value for scale : %s" % (scale) + raise ValueError("Receive invalid value for scale : %s" % (scale)) def get_contrast(self): """ @@ -385,11 +385,11 @@ def get_volume(self, inv, contrast, extrapolation): extrapolation=extrapolation) self.volume_tcl.SetValue(format_number(v)) self.volume_err_tcl.SetValue(format_number(dv)) - except: + except Exception as exc: self.volume_tcl.SetValue(format_number(None)) self.volume_err_tcl.SetValue(format_number(None)) msg = "Error occurred computing volume " - msg += " fraction: %s" % sys.exc_value + msg += " fraction: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="error", type="stop")) @@ -405,11 +405,11 @@ def get_surface(self, inv, contrast, porod_const, extrapolation): extrapolation=extrapolation) self.surface_tcl.SetValue(format_number(s)) self.surface_err_tcl.SetValue(format_number(ds)) - except: + except Exception as exc: self.surface_tcl.SetValue(format_number(None)) self.surface_err_tcl.SetValue(format_number(None)) msg = "Error occurred computing " - msg += "specific surface: %s" % sys.exc_value + msg += "specific surface: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="error", type="stop")) @@ -425,13 +425,13 @@ def get_total_qstar(self, inv, extrapolation): format_number(qstar_total_err)) self.inv_container.qstar_total = qstar_total self.inv_container.qstar_total_err = qstar_total_err - except: + except Exception as exc: self.inv_container.qstar_total = "Error" self.inv_container.qstar_total_err = "Error" self.invariant_total_tcl.SetValue(format_number(None)) self.invariant_total_err_tcl.SetValue(format_number(None)) msg = "Error occurred computing invariant using" - msg += " extrapolation: %s" % sys.exc_value + msg += " extrapolation: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, type="stop")) def get_low_qstar(self, inv, npts_low, low_q=False): @@ -449,20 +449,20 @@ def get_low_qstar(self, inv, npts_low, low_q=False): self.power_low_tcl.SetValue(format_number(power_low)) self._manager.plot_theory(data=extrapolated_data, name="Low-Q extrapolation") - except: + except Exception as exc: self.inv_container.qstar_low = "ERROR" self.inv_container.qstar_low_err = "ERROR" self._manager.plot_theory(name="Low-Q extrapolation") msg = "Error occurred computing low-Q " - msg += "invariant: %s" % sys.exc_value + msg += "invariant: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, type="stop")) raise else: try: self._manager.plot_theory(name="Low-Q extrapolation") - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) def get_high_qstar(self, inv, high_q=False): """ @@ -482,21 +482,21 @@ def get_high_qstar(self, inv, high_q=False): npts=500) self._manager.plot_theory(data=high_out_data, name="High-Q extrapolation") - except: + except Exception as exc: #raise self.inv_container.qstar_high = "ERROR" self.inv_container.qstar_high_err = "ERROR" self._manager.plot_theory(name="High-Q extrapolation") msg = "Error occurred computing high-Q " - msg += "invariant: %s" % sys.exc_value + msg += "invariant: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, type="stop")) raise else: try: self._manager.plot_theory(name="High-Q extrapolation") - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) def get_qstar(self, inv): """ @@ -624,8 +624,8 @@ def compute_invariant(self, event=None): try: background = self.get_background() scale = self.get_scale() - except: - msg = "Invariant Error: %s" % (sys.exc_value) + except Exception as exc: + msg = "Invariant Error: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, type="stop")) return @@ -640,8 +640,8 @@ def compute_invariant(self, event=None): try: inv, npts_low = self.set_extrapolation_low(inv=inv, low_q=low_q) inv, npts_high = self.set_extrapolation_high(inv=inv, high_q=high_q) - except: - msg = "Error occurred computing invariant: %s" % sys.exc_value + except Exception as exc: + msg = "Error occurred computing invariant: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="warning", type="stop")) return @@ -651,8 +651,8 @@ def compute_invariant(self, event=None): #Compute invariant try: self.get_qstar(inv=inv) - except: - msg = "Error occurred computing invariant: %s" % sys.exc_value + except Exception as exc: + msg = "Error occurred computing invariant: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="warning", type="stop")) @@ -673,9 +673,8 @@ def compute_invariant(self, event=None): # Parse additional parameters porod_const = self.get_porod_const() contrast = self.get_contrast() - except: - msg = r_msg + "Error occurred computing invariant: %s" % \ - sys.exc_value + except Exception as exc: + msg = r_msg + "Error occurred computing invariant: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="error", type="stop")) @@ -684,8 +683,8 @@ def compute_invariant(self, event=None): self.get_volume(inv=inv, contrast=contrast, extrapolation=extrapolation) #compute surface and set value to txtcrtl - except: - msg = "Error occurred computing invariant: %s" % sys.exc_value + except Exception as exc: + msg = "Error occurred computing invariant: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="warning", type="stop")) @@ -694,8 +693,8 @@ def compute_invariant(self, event=None): porod_const=porod_const, extrapolation=extrapolation) - except: - msg = "Error occurred computing invariant: %s" % sys.exc_value + except Exception as exc: + msg = "Error occurred computing invariant: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=msg, info="warning", type="stop")) @@ -844,13 +843,15 @@ def _set_property_value(self, key, value): attr = getattr(self, key) if attr.__class__.__name__ == "StaticText": return - if value in ["True", "False", True, False]: - value = bool(value) + if value in ["True", True]: + value = 1 + elif value in ["False", False]: + value = 0 else: value = str(value) attr.SetValue(value) - except: - logger.error("Invariant state: %s", sys.exc_value) + except Exception as exc: + logger.error("Invariant state: %s", exc) def get_bookmark_by_num(self, num=None): """ @@ -866,9 +867,9 @@ def get_bookmark_by_num(self, num=None): # get the previous state try: _, _, current_state, comp_state = self.state.bookmark_list[int(num)] - except: - logger.error(sys.exc_value) - raise ValueError, "No such bookmark exists" + except Exception as exc: + logger.error(exc) + raise ValueError("No such bookmark exists") # set the parameters for key in comp_state: @@ -961,8 +962,8 @@ def _set_state(self, event): self.state.state_num = self.state.saved_state['state_num'] self.state.state_list[str(self.state.state_num)] = \ self.state.clone_state() - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) self._set_undo_flag(True) self._set_redo_flag(False) @@ -1005,8 +1006,8 @@ def _set_compute_state(self, state=None): for i in range(self.state.state_num + 1, len(self.state.state_list)): try: del self.state.state_list[str(i)] - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) # Enable the undo button if it was not self._set_undo_flag(True) self._set_redo_flag(False) @@ -1070,8 +1071,8 @@ def _on_text(self, event): for i in range(int(state_num) + 1, len(self.state.state_list)): try: del self.state.state_list[str(i)] - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) # try to add new state of the text changes in the state_list try: @@ -1085,8 +1086,8 @@ def _on_text(self, event): self.state.saved_state['state_num'] += 1 self.state.state_num = self.state.saved_state['state_num'] self.state.state_list[str(self.state.state_num)] = self.state.clone_state() - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) self._set_undo_flag(True) self._set_redo_flag(False) @@ -1107,8 +1108,8 @@ def _on_out_text(self, event): try: self.state.saved_state[name] = str(value) self.state.state_list[str(self.state.state_num)] = self.state.clone_state() - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) def _get_input_list(self): """ @@ -1117,8 +1118,8 @@ def _get_input_list(self): # get state num of the last compute state compute_num = self.state.saved_state['compute_num'] # find values and put into the input list - for key1, value1 in self.state.state_list[str(compute_num)].iteritems(): - for key, _ in self.state.input_list.iteritems(): + for key1, value1 in self.state.state_list[str(compute_num)].items(): + for key, _ in self.state.input_list.items(): if key == key1: self.state.input_list[key] = value1 break diff --git a/src/sas/sasgui/perspectives/invariant/invariant_state.py b/src/sas/sasgui/perspectives/invariant/invariant_state.py index 81eb188047..bdd6bd0d15 100644 --- a/src/sas/sasgui/perspectives/invariant/invariant_state.py +++ b/src/sas/sasgui/perspectives/invariant/invariant_state.py @@ -1,6 +1,7 @@ """ State class for the invariant UI """ +from __future__ import print_function # import time import os @@ -139,7 +140,7 @@ def __str__(self): state += "\n=== Inputs ===\n" # text ctl general inputs ( excluding extrapolation text ctl) - for key, value in self.input_list.iteritems(): + for key, value in self.input_list.items(): if value == '': continue key_split = key.split('_') @@ -165,7 +166,7 @@ def __str__(self): state += "\nExtrapolation: High=%s; Low=%s\n" % (extra_hi, extra_lo) low_off = False high_off = False - for key, value in self.input_list.iteritems(): + for key, value in self.input_list.items(): key_split = key.split('_') max_ind = len(key_split) - 1 if key_split[max_ind] == 'tcl': @@ -215,7 +216,7 @@ def __str__(self): else: # other outputs than Q* name = item[0] + "_tcl" - if name in self.saved_state.keys(): + if name in self.saved_state: value = self.saved_state[name] # Exclude the outputs w/'' @@ -300,7 +301,7 @@ def toXML(self, file="inv_state.inv", doc=None, entry_node=None): state = newdoc.createElement("state") top_element.appendChild(state) - for name, value in self.saved_state.iteritems(): + for name, value in self.saved_state.items(): element = newdoc.createElement(str(name)) element.appendChild(newdoc.createTextNode(str(value))) state.appendChild(element) @@ -309,9 +310,9 @@ def toXML(self, file="inv_state.inv", doc=None, entry_node=None): history = newdoc.createElement("history") top_element.appendChild(history) - for name, value in self.state_list.iteritems(): + for name, value in self.state_list.items(): history_element = newdoc.createElement('state_' + str(name)) - for state_name, state_value in value.iteritems(): + for state_name, state_value in value.items(): state_element = newdoc.createElement(str(state_name)) child = newdoc.createTextNode(str(state_value)) state_element.appendChild(child) @@ -324,7 +325,7 @@ def toXML(self, file="inv_state.inv", doc=None, entry_node=None): bookmark = newdoc.createElement("bookmark") top_element.appendChild(bookmark) item_list = ['time', 'date', 'state', 'comp_state'] - for name, value_list in self.bookmark_list.iteritems(): + for name, value_list in self.bookmark_list.items(): element = newdoc.createElement('mark_' + str(name)) _, date, state, comp_state = value_list time_element = newdoc.createElement('time') @@ -333,12 +334,12 @@ def toXML(self, file="inv_state.inv", doc=None, entry_node=None): date_element.appendChild(newdoc.createTextNode(str(value_list[1]))) state_list_element = newdoc.createElement('state') comp_state_list_element = newdoc.createElement('comp_state') - for state_name, state_value in value_list[2].iteritems(): + for state_name, state_value in value_list[2].items(): state_element = newdoc.createElement(str(state_name)) child = newdoc.createTextNode(str(state_value)) state_element.appendChild(child) state_list_element.appendChild(state_element) - for comp_name, comp_value in value_list[3].iteritems(): + for comp_name, comp_value in value_list[3].items(): comp_element = newdoc.createElement(str(comp_name)) comp_element.appendChild(newdoc.createTextNode(str(comp_value))) comp_state_list_element.appendChild(comp_element) @@ -367,7 +368,7 @@ def fromXML(self, file=None, node=None): if file is not None: msg = "InvariantSate no longer supports non-CanSAS" msg += " format for invariant files" - raise RuntimeError, msg + raise RuntimeError(msg) if node.get('version')\ and node.get('version') == '1.0': @@ -382,9 +383,9 @@ def fromXML(self, file=None, node=None): if entry is not None and entry.get('epoch'): try: timestamp = (entry.get('epoch')) - except: + except Exception as exc: msg = "InvariantSate.fromXML: Could not read" - msg += " timestamp\n %s" % sys.exc_value + msg += " timestamp\n %s" % exc logger.error(msg) # Parse bookmarks @@ -452,87 +453,83 @@ def set_report_string(self): """ Get the values (strings) from __str__ for report """ - strings = self.__str__() - # default string values - for num in range(1, 19): - exec "s_%s = 'NA'" % str(num) - lines = strings.split('\n') + s = {num: 'NA' for num in range(1, 19)} # get all string values from __str__() - for line in range(0, len(lines)): - if line == 1: - s_1 = lines[1] - elif line == 2: - s_2 = lines[2] + lines = str(self).split('\n') + for line_num, line in enumerate(lines): + if line_num == 1: + s[1] = line + elif line_num == 2: + s[2] = line else: - item = lines[line].split(':') + item = line.split(':') item[0] = item[0].strip() if item[0] == "scale": - s_3 = item[1] + s[3] = item[1] elif item[0] == "porod constant": - s_4 = item[1] + s[4] = item[1] elif item[0] == "background": - s_5 = item[1] + s[5] = item[1] elif item[0] == "contrast": - s_6 = item[1] + s[6] = item[1] elif item[0] == "Extrapolation": extra = item[1].split(";") bool_0 = extra[0].split("=") bool_1 = extra[1].split("=") - s_8 = " " + bool_0[0] + "Q region = " + bool_0[1] - s_7 = " " + bool_1[0] + "Q region = " + bool_1[1] + s[8] = " " + bool_0[0] + "Q region = " + bool_0[1] + s[7] = " " + bool_1[0] + "Q region = " + bool_1[1] elif item[0] == "npts low": - s_9 = item[1] + s[9] = item[1] elif item[0] == "npts high": - s_10 = item[1] + s[10] = item[1] elif item[0] == "volume fraction": val = item[1].split("+-")[0].strip() error = item[1].split("+-")[1].strip() - s_17 = val + " ± " + error + s[17] = val + " ± " + error elif item[0] == "specific surface": val = item[1].split("+-")[0].strip() error = item[1].split("+-")[1].strip() - s_18 = val + " ± " + error + s[18] = val + " ± " + error elif item[0].split("(")[0].strip() == "power low": - s_11 = item[0] + " =" + item[1] + s[11] = item[0] + " =" + item[1] elif item[0].split("(")[0].strip() == "power high": - s_12 = item[0] + " =" + item[1] + s[12] = item[0] + " =" + item[1] elif item[0].split("[")[0].strip() == "Q* from low Q extrapolation": # looks messy but this way the symbols +_ and % work on html val = item[1].split("+-")[0].strip() error = item[1].split("+-")[1].strip() err = error.split("%")[0].strip() percent = error.split("%")[1].strip() - s_13 = val + " ± " + err + "%" + percent + s[13] = val + " ± " + err + "%" + percent elif item[0].split("[")[0].strip() == "Q* from data": val = item[1].split("+-")[0].strip() error = item[1].split("+-")[1].strip() err = error.split("%")[0].strip() percent = error.split("%")[1].strip() - s_14 = val + " ± " + err + "%" + percent + s[14] = val + " ± " + err + "%" + percent elif item[0].split("[")[0].strip() == "Q* from high Q extrapolation": val = item[1].split("+-")[0].strip() error = item[1].split("+-")[1].strip() err = error.split("%")[0].strip() percent = error.split("%")[1].strip() - s_15 = val + " ± " + err + "%" + percent + s[15] = val + " ± " + err + "%" + percent elif item[0].split("[")[0].strip() == "total Q*": val = item[1].split("+-")[0].strip() error = item[1].split("+-")[1].strip() - s_16 = val + " ± " + error + s[16] = val + " ± " + error else: continue - s_1 = self._check_html_format(s_1) + s[1] = self._check_html_format(s[1]) file_name = self._check_html_format(self.file) # make plot image self.set_plot_state(extra_high=bool_0[1], extra_low=bool_1[1]) # get ready for report with setting all the html strings - self.report_str = str(self.template_str) % (s_1, s_2, - s_3, s_4, s_5, s_6, s_7, s_8, - s_9, s_10, s_11, s_12, s_13, s_14, s_15, - s_16, s_17, s_18, file_name, "%s") + self.report_str = str(self.template_str) % ( + s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], + s[12], s[13], s[14], s[15], s[16], s[17], s[18], file_name, "%s") def _check_html_format(self, name): """ @@ -691,9 +688,9 @@ def _parse_state(self, entry): if nodes != []: state = InvariantState() state.fromXML(node=nodes[0]) - except: + except Exception as exc: msg = "XML document does not contain invariant" - msg += " information.\n %s" % sys.exc_value + msg += " information.\n %s" % exc logger.info(msg) return state @@ -735,7 +732,7 @@ def _read_cansas(self, path): sas_entry.filename = invstate.file output.append(sas_entry) else: - raise RuntimeError, "%s is not a file" % path + raise RuntimeError("%s is not a file" % path) # Return output consistent with the loader's api if len(output) == 0: @@ -781,7 +778,7 @@ def write_toXML(self, datainfo=None, state=None): elif not issubclass(datainfo.__class__, sas.sascalc.dataloader.data_info.Data1D): msg = "The cansas writer expects a Data1D" msg += " instance: %s" % str(datainfo.__class__.__name__) - raise RuntimeError, msg + raise RuntimeError(msg) # make sure title and data run is filled up. if datainfo.title is None or datainfo.title == '': datainfo.title = datainfo.name diff --git a/src/sas/sasgui/perspectives/invariant/report_dialog.py b/src/sas/sasgui/perspectives/invariant/report_dialog.py index 491f1ad73a..05d6eb81f6 100644 --- a/src/sas/sasgui/perspectives/invariant/report_dialog.py +++ b/src/sas/sasgui/perspectives/invariant/report_dialog.py @@ -91,9 +91,9 @@ def onSave(self, event=None): try: # Mac os.system("open %s" % fName) - except: + except Exception as exc: # DO not open - logger.error("Could not open file: %s" % sys.exc_value) + logger.error("Could not open file: %s" % exc) # delete image file os.remove(pic_fname) return diff --git a/src/sas/sasgui/perspectives/pr/__init__.py b/src/sas/sasgui/perspectives/pr/__init__.py index 44b7fec487..e0823b26e8 100644 --- a/src/sas/sasgui/perspectives/pr/__init__.py +++ b/src/sas/sasgui/perspectives/pr/__init__.py @@ -1,2 +1,2 @@ PLUGIN_ID = "P(r) plug-in 1.0" -from pr import * \ No newline at end of file +from .pr import * diff --git a/src/sas/sasgui/perspectives/pr/explore_dialog.py b/src/sas/sasgui/perspectives/pr/explore_dialog.py index da5214f3bc..2e856df084 100644 --- a/src/sas/sasgui/perspectives/pr/explore_dialog.py +++ b/src/sas/sasgui/perspectives/pr/explore_dialog.py @@ -34,7 +34,7 @@ from sas.sasgui.guiframe.gui_style import GUIFRAME_ID from sas.sasgui.plottools.plottables import Graph -from pr_widgets import PrTextCtrl +from .pr_widgets import PrTextCtrl # Default number of points on the output plot DEFAULT_NPTS = 10 @@ -415,10 +415,10 @@ def _recalc(self, event=None): results.pos.append(pos) results.pos_err.append(pos_err) results.osc.append(osc) - except: + except Exception as exc: # This inversion failed, skip this D_max value msg = "ExploreDialog: inversion failed " - msg += "for D_max=%s\n%s" % (str(d), sys.exc_value) + msg += "for D_max=%s\n%s" % (str(d), exc) logger.error(msg) self.results = results diff --git a/src/sas/sasgui/perspectives/pr/inversion_panel.py b/src/sas/sasgui/perspectives/pr/inversion_panel.py index 2bfc81901e..04ca007c3c 100644 --- a/src/sas/sasgui/perspectives/pr/inversion_panel.py +++ b/src/sas/sasgui/perspectives/pr/inversion_panel.py @@ -4,19 +4,22 @@ __id__ = "$Id: aboutdialog.py 1193 2007-05-03 17:29:59Z dmitriy $" __revision__ = "$Revision: 1193 $" -import wx import os import sys import logging + +import wx from wx.lib.scrolledpanel import ScrolledPanel + from sas.sasgui.guiframe.events import StatusEvent from sas.sasgui.guiframe.panel_base import PanelBase -from inversion_state import InversionState -from pr_widgets import PrTextCtrl -from pr_widgets import DataFileTextCtrl -from pr_widgets import OutputTextCtrl from sas.sasgui.guiframe.documentation_window import DocumentationWindow +from .inversion_state import InversionState +from .pr_widgets import PrTextCtrl +from .pr_widgets import DataFileTextCtrl +from .pr_widgets import OutputTextCtrl + logger = logging.getLogger(__name__) if sys.platform.count("win32") > 0: @@ -751,9 +754,9 @@ def _on_accept_alpha(self, evt): self.alpha_ctl.SetValue(alpha) except ValueError: logger.error("InversionControl._on_accept_alpha got a value that was not a number: %s" % alpha ) - except: + except Exception as exc: # No estimate or bad estimate, either do nothing - logger.error("InversionControl._on_accept_alpha: %s" % sys.exc_value) + logger.error("InversionControl._on_accept_alpha: %s" % exc) def _on_accept_nterms(self, evt): """ @@ -767,9 +770,9 @@ def _on_accept_nterms(self, evt): self.nfunc_ctl.SetValue(nterms) except ValueError: logger.error("InversionControl._on_accept_nterms got a value that was not a number: %s" % nterms ) - except: + except Exception as exc: # No estimate or bad estimate, either do nothing - logger.error("InversionControl._on_accept_nterms: %s" % sys.exc_value) + logger.error("InversionControl._on_accept_nterms: %s" % exc) def clear_panel(self): """ @@ -900,7 +903,7 @@ def _read_pars(self, evt=None): message = "Number of function terms should be smaller " message += "than the number of points" wx.PostEvent(self._manager.parent, StatusEvent(status=message)) - raise ValueError, message + raise ValueError(message) self.nfunc_ctl.SetBackgroundColour(wx.WHITE) self.nfunc_ctl.Refresh() except: @@ -956,7 +959,7 @@ def _on_explore(self, evt): """ Invoke the d_max exploration dialog """ - from explore_dialog import ExploreDialog + from .explore_dialog import ExploreDialog if self._manager._last_pr is not None: pr = self._manager._create_plot_pr() dialog = ExploreDialog(pr, 10, None, -1, "") @@ -1007,8 +1010,8 @@ def _change_file(self, evt=None, filepath=None, data=None): self._on_pars_changed(None) self._on_invert(None) self._set_analysis(True) - except: - msg = "InversionControl._change_file: %s" % sys.exc_value + except Exception as exc: + msg = "InversionControl._change_file: %s" % exc logger.error(msg) def on_help(self, event): diff --git a/src/sas/sasgui/perspectives/pr/inversion_state.py b/src/sas/sasgui/perspectives/pr/inversion_state.py index 095404b3b2..b0a30056a4 100644 --- a/src/sas/sasgui/perspectives/pr/inversion_state.py +++ b/src/sas/sasgui/perspectives/pr/inversion_state.py @@ -17,6 +17,7 @@ import sys import logging from lxml import etree + from sas.sasgui.guiframe.dataFitting import Data1D from sas.sascalc.dataloader.readers.cansas_reader import Reader as CansasReader from sas.sascalc.dataloader.readers.cansas_reader import get_content @@ -237,7 +238,7 @@ def fromXML(self, file=None, node=None): if file is not None: msg = "InversionState no longer supports non-CanSAS" msg += " format for P(r) files" - raise RuntimeError, msg + raise RuntimeError(msg) if node.get('version') and node.get('version') == '1.0': @@ -251,9 +252,9 @@ def fromXML(self, file=None, node=None): if entry is not None and entry.get('epoch'): try: self.timestamp = float(entry.get('epoch')) - except: + except Exception as exc: msg = "InversionState.fromXML: Could not read " - msg += "timestamp\n %s" % sys.exc_value + msg += "timestamp\n %s" % exc logger.error(msg) # Parse inversion inputs @@ -431,9 +432,9 @@ def _parse_prstate(self, entry): # Create an empty state state = InversionState() state.fromXML(node=nodes[0]) - except: + except Exception as exc: msg = "XML document does not contain P(r) " - msg += "information.\n %s" % sys.exc_value + msg += "information.\n %s" % exc logger.info(msg) return state @@ -480,7 +481,7 @@ def _read_cansas(self, path): sas_entry.filename = prstate.file output.append(sas_entry) else: - raise RuntimeError, "%s is not a file" % path + raise RuntimeError("%s is not a file" % path) # Return output consistent with the loader's api if len(output) == 0: @@ -524,7 +525,7 @@ def write_toXML(self, datainfo=None, state=None): elif not issubclass(datainfo.__class__, Data1D): msg = "The cansas writer expects a Data1D " msg += "instance: %s" % str(datainfo.__class__.__name__) - raise RuntimeError, msg + raise RuntimeError(msg) # Create basic XML document doc, sasentry = self._to_xml_doc(datainfo) diff --git a/src/sas/sasgui/perspectives/pr/pr.py b/src/sas/sasgui/perspectives/pr/pr.py index e6ea55f01c..e266fe8b17 100644 --- a/src/sas/sasgui/perspectives/pr/pr.py +++ b/src/sas/sasgui/perspectives/pr/pr.py @@ -17,12 +17,14 @@ from __future__ import print_function import sys -import wx import logging import time import math + +import wx import numpy as np import pylab + from sas.sasgui.guiframe.gui_manager import MDIFrame from sas.sasgui.guiframe.dataFitting import Data1D from sas.sasgui.guiframe.events import NewPlotEvent @@ -32,9 +34,18 @@ from sas.sascalc.dataloader.loader import Loader import sas.sascalc.dataloader -from pr_widgets import load_error from sas.sasgui.guiframe.plugin_base import PluginBase +from .inversion_state import Reader # .prv file reader +from .inversion_panel import InversionControl +#from .inversion_panel import HelpDialog +from .inversion_panel import PrDistDialog +from .pr_thread import CalcPr +from .pr_thread import EstimatePr +from .pr_thread import EstimateNT +from .pr_widgets import load_error +from .pr_widgets import DataDialog + logger = logging.getLogger(__name__) @@ -105,9 +116,6 @@ def __init__(self): self._default_Iq = {} self.list_plot_id = [] - # Associate the inversion state reader with .prv files - from inversion_state import Reader - # Create a CanSAS/Pr reader self.state_reader = Reader(self.set_state) self._extensions = '.prv' @@ -150,7 +158,7 @@ def set_state(self, state=None, datainfo=None): if data is None: msg = "Pr.set_state: datainfo parameter cannot " msg += "be None in standalone mode" - raise RuntimeError, msg + raise RuntimeError(msg) # Ensuring that plots are coordinated correctly t = time.localtime(data.meta_data['prstate'].timestamp) @@ -183,8 +191,8 @@ def set_state(self, state=None, datainfo=None): wx.PostEvent(self.parent, NewPlotEvent(plot=self.current_plottable, title=self.current_plottable.title)) self.control_panel.set_state(state) - except: - logger.error("prview.set_state: %s" % sys.exc_value) + except Exception as exc: + logger.error("prview.set_state: %s" % exc) def help(self, evt): @@ -194,7 +202,6 @@ def help(self, evt): :TODO: replace the text with a nice image """ - from inversion_panel import HelpDialog dialog = HelpDialog(None, -1) if dialog.ShowModal() == wx.ID_OK: dialog.Destroy() @@ -368,7 +375,6 @@ def _on_pr_npts(self, evt): """ Redisplay P(r) with a different number of points """ - from inversion_panel import PrDistDialog dialog = PrDistDialog(None, -1) dialog.set_content(self._pr_npts) if dialog.ShowModal() == wx.ID_OK: @@ -451,7 +457,7 @@ def __init__(self, path): dataread = data # Notify the user if we could not read the file if dataread is None: - raise RuntimeError, "Invalid data" + raise RuntimeError("Invalid data") x = None y = None @@ -471,7 +477,7 @@ def __init__(self, path): else: if dataread is None: return x, y, err - raise RuntimeError, "This tool can only read 1D data" + raise RuntimeError("This tool can only read 1D data") self._current_file_data.x = x self._current_file_data.y = y @@ -510,8 +516,8 @@ def load_columns(self, path="sphere_60_q0_2.txt"): data_x = np.append(data_x, x) data_y = np.append(data_y, y) data_err = np.append(data_err, err) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) if scale is not None: message = "The loaded file had no error bars, statistical errors are assumed." @@ -561,8 +567,8 @@ def load_abs(self, path): data_x = np.append(data_x, x) data_y = np.append(data_y, y) data_err = np.append(data_err, err) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) elif line.find("The 6 columns") >= 0: data_started = True @@ -719,8 +725,6 @@ def start_thread(self): """ Start a calculation thread """ - from pr_thread import CalcPr - # If a thread is already started, stop it if self.calc_thread is not None and self.calc_thread.isrunning(): self.calc_thread.stop() @@ -848,14 +852,14 @@ def show_data(self, path=None, data=None, reset=False): if data is not None: try: pr = self._create_file_pr(data) - except: - status = "Problem reading data: %s" % sys.exc_value + except Exception as exc: + status = "Problem reading data: %s" % exc wx.PostEvent(self.parent, StatusEvent(status=status)) - raise RuntimeError, status + raise RuntimeError(status) # If the file contains nothing, just return if pr is None: - raise RuntimeError, "Loaded data is invalid" + raise RuntimeError("Loaded data is invalid") self.pr = pr @@ -905,7 +909,7 @@ def save_data(self, filepath, prstate=None): else: msg = "pr.save_data: the data being saved is not a" msg += " sas.data_info.Data1D object" - raise RuntimeError, msg + raise RuntimeError(msg) def setup_plot_inversion(self, alpha, nfunc, d_max, q_min=None, q_max=None, est_bck=False, bck_val=0, height=0, width=0): @@ -927,8 +931,8 @@ def setup_plot_inversion(self, alpha, nfunc, d_max, q_min=None, q_max=None, if pr is not None: self.pr = pr self.perform_inversion() - except: - wx.PostEvent(self.parent, StatusEvent(status=sys.exc_value)) + except Exception as exc: + wx.PostEvent(self.parent, StatusEvent(status=exc)) def estimate_plot_inversion(self, alpha, nfunc, d_max, q_min=None, q_max=None, @@ -951,8 +955,8 @@ def estimate_plot_inversion(self, alpha, nfunc, d_max, if pr is not None: self.pr = pr self.perform_estimate() - except: - wx.PostEvent(self.parent, StatusEvent(status=sys.exc_value)) + except Exception as exc: + wx.PostEvent(self.parent, StatusEvent(status=exc)) def _create_plot_pr(self, estimate=False): """ @@ -1032,8 +1036,8 @@ def setup_file_inversion(self, alpha, nfunc, d_max, data, if pr is not None: self.pr = pr self.perform_inversion() - except: - wx.PostEvent(self.parent, StatusEvent(status=sys.exc_value)) + except Exception as exc: + wx.PostEvent(self.parent, StatusEvent(status=exc)) def estimate_file_inversion(self, alpha, nfunc, d_max, data, path=None, q_min=None, q_max=None, @@ -1055,8 +1059,8 @@ def estimate_file_inversion(self, alpha, nfunc, d_max, data, if pr is not None: self.pr = pr self.perform_estimate() - except: - wx.PostEvent(self.parent, StatusEvent(status=sys.exc_value)) + except Exception as exc: + wx.PostEvent(self.parent, StatusEvent(status=exc)) def _create_file_pr(self, data): """ @@ -1084,8 +1088,8 @@ def __init__(self, path): self._current_file_data.y = data.y self._current_file_data.err = data.dy x, y, err = data.x, data.y, data.dy - except: - load_error(sys.exc_value) + except Exception as exc: + load_error(exc) return None # If the file contains no data, just return @@ -1123,16 +1127,14 @@ def __init__(self, path): pr.slit_height = self.slit_height pr.slit_width = self.slit_width return pr - except: - load_error(sys.exc_value) + except Exception as exc: + load_error(exc) return None def perform_estimate(self): """ Perform parameter estimation """ - from pr_thread import EstimatePr - # If a thread is already started, stop it if self.estimation_thread is not None and \ self.estimation_thread.isrunning(): @@ -1161,8 +1163,6 @@ def perform_estimateNT(self): """ Perform parameter estimation """ - from pr_thread import EstimateNT - # If a thread is already started, stop it if self.estimation_thread is not None and self.estimation_thread.isrunning(): self.estimation_thread.stop() @@ -1238,8 +1238,6 @@ def get_panels(self, parent): """ Create and return a list of panel objects """ - from inversion_panel import InversionControl - self.parent = parent self.frame = MDIFrame(self.parent, None, 'None', (100, 200)) self.control_panel = InversionControl(self.frame, -1, @@ -1261,6 +1259,8 @@ def set_data(self, data_list=None): """ if data_list is None: data_list = [] + else: + data_list = list(data_list) # force iterator to list if len(data_list) >= 1: if len(data_list) == 1: data = data_list[0] @@ -1286,7 +1286,6 @@ def set_data(self, data_list=None): msg = "Prview does not allow multiple data!\n" msg += "Please select one.\n" if len(data_list) > 1: - from pr_widgets import DataDialog dlg = DataDialog(data_list=data_1d_list, text=msg) if dlg.ShowModal() == wx.ID_OK: data = dlg.get_data() @@ -1305,8 +1304,8 @@ def set_data(self, data_list=None): id=self.data_id)) self.data_id = data.id self.control_panel._change_file(evt=None, data=data) - except: - msg = "Prview Set_data: " + str(sys.exc_value) + except Exception as exc: + msg = "Prview Set_data: " + str(exc) wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) else: msg = "Pr cannot be computed for data of " diff --git a/src/sas/sasgui/perspectives/pr/pr_thread.py b/src/sas/sasgui/perspectives/pr/pr_thread.py index 75119f8c27..c4337db9aa 100644 --- a/src/sas/sasgui/perspectives/pr/pr_thread.py +++ b/src/sas/sasgui/perspectives/pr/pr_thread.py @@ -40,9 +40,9 @@ def compute(self): except KeyboardInterrupt: # Thread was interrupted, just proceed pass - except: + except Exception as exc: if self.error_func is not None: - self.error_func("CalcPr.compute: %s" % sys.exc_value) + self.error_func("CalcPr.compute: %s" % exc) class EstimatePr(CalcThread): """ @@ -68,9 +68,9 @@ def compute(self): except KeyboardInterrupt: # Thread was interrupted, just proceed pass - except: + except Exception as exc: if self.error_func is not None: - self.error_func("EstimatePr.compute: %s" % sys.exc_value) + self.error_func("EstimatePr.compute: %s" % exc) class EstimateNT(CalcThread): """ @@ -108,6 +108,6 @@ def compute(self): except KeyboardInterrupt: # Thread was interrupted, just proceed pass - except: + except Exception as exc: if self.error_func is not None: - self.error_func("EstimatePr2.compute: %s" % sys.exc_value) + self.error_func("EstimatePr2.compute: %s" % exc) diff --git a/src/sas/sasgui/perspectives/simulation/ShapeAdapter.py b/src/sas/sasgui/perspectives/simulation/ShapeAdapter.py index fbb3f282d1..4dc0db1cde 100644 --- a/src/sas/sasgui/perspectives/simulation/ShapeAdapter.py +++ b/src/sas/sasgui/perspectives/simulation/ShapeAdapter.py @@ -86,7 +86,7 @@ def update_sphere(self, sph): self.sim_canvas._model_changed() else: - raise ValueError, "SimShapeVisitor: Wrong class for visited object" + raise ValueError("SimShapeVisitor: Wrong class for visited object") @@ -114,7 +114,7 @@ def update_cylinder(self, cyl): self.sim_canvas._model_changed() else: - raise ValueError, "SimShapeVisitor: Wrong class for visited object" + raise ValueError("SimShapeVisitor: Wrong class for visited object") def update(self, volCanvas, shape): @@ -129,5 +129,5 @@ def update(self, volCanvas, shape): self.sim_canvas = volCanvas shape.accept_update(self) else: - raise ValueError, "ShapeAdapter: Shape [%s] not in list" % shape.name + raise ValueError("ShapeAdapter: Shape [%s] not in list" % shape.name) diff --git a/src/sas/sasgui/perspectives/simulation/ShapeParameters.py b/src/sas/sasgui/perspectives/simulation/ShapeParameters.py index 79352e334d..964b418c7c 100644 --- a/src/sas/sasgui/perspectives/simulation/ShapeParameters.py +++ b/src/sas/sasgui/perspectives/simulation/ShapeParameters.py @@ -9,11 +9,13 @@ """ from __future__ import print_function -import wx import sys -import wx.lib.newevent from copy import deepcopy -import SimCanvas + +import wx +import wx.lib.newevent + +from . import SimCanvas (CreateShapeEvent, EVT_ADD_SHAPE) = wx.lib.newevent.NewEvent() (EditShapeEvent, EVT_EDIT_SHAPE) = wx.lib.newevent.NewEvent() @@ -200,10 +202,8 @@ def editShape(self, shape=None, new=True): n = 1 self.parameters = [] - keys = shape.params.keys() - keys.sort() - for item in keys: + for item in sorted(shape.params.keys()): if item in ['contrast', 'order']: continue n += 1 @@ -392,9 +392,9 @@ def _parseCtrl(self): tmp = self._readCtrlFloat(item[1]) if not tmp==None: self.current_shape.params[item[0]] = tmp - except: + except Exception as exc: print("Could not create") - print(sys.exc_value) + print(exc) def _onCreate(self, evt): """ @@ -488,4 +488,3 @@ def _on_rename_shape_from_listbox(self, ev): if len(indices)>0: print("NOT YET IMPLMENTED") print("renaming", self.shape_listbox.GetString(indices[0])) - \ No newline at end of file diff --git a/src/sas/sasgui/perspectives/simulation/__init__.py b/src/sas/sasgui/perspectives/simulation/__init__.py index 77c981eedd..e03c9d3aaf 100644 --- a/src/sas/sasgui/perspectives/simulation/__init__.py +++ b/src/sas/sasgui/perspectives/simulation/__init__.py @@ -1,2 +1,2 @@ PLUGIN_ID = "Simulation plug-in 1.0" -from simulation import * \ No newline at end of file +from .simulation import * diff --git a/src/sas/sasgui/perspectives/simulation/simulation.py b/src/sas/sasgui/perspectives/simulation/simulation.py index 0509764dee..84b1567018 100644 --- a/src/sas/sasgui/perspectives/simulation/simulation.py +++ b/src/sas/sasgui/perspectives/simulation/simulation.py @@ -14,16 +14,15 @@ import logging # Application imports -import SimCanvas -import ShapeParameters -import ShapeAdapter -from sas.sasgui.guiframe.dataFitting import Data1D -# Real-space simulation import -import sas.sascalc.realspace.VolumeCanvas as VolumeCanvas - +from sas.sascalc.realspace import VolumeCanvas from sas.sascalc.data_util.calcthread import CalcThread +from sas.sasgui.guiframe.dataFitting import Data1D from sas.guicomm.events import NewPlotEvent, StatusEvent +from . import SimCanvas +from . import ShapeParameters +from . import ShapeAdapter + logger = logging.getLogger(__name__) class Calc1D(CalcThread): diff --git a/src/sas/sasgui/plottools/LineModel.py b/src/sas/sasgui/plottools/LineModel.py index d5366a9f4f..a456b42904 100644 --- a/src/sas/sasgui/plottools/LineModel.py +++ b/src/sas/sasgui/plottools/LineModel.py @@ -82,7 +82,7 @@ def run(self, x=0.0): self._line(x[0] * math.sin(x[1])) elif x.__class__.__name__ == 'tuple': msg = "Tuples are not allowed as input to BaseComponent models" - raise ValueError, msg + raise ValueError(msg) else: return self._line(x) @@ -104,6 +104,6 @@ def runXY(self, x=0.0): return self._line(x[0]) * self._line(x[1]) elif x.__class__.__name__ == 'tuple': msg = "Tuples are not allowed as input to BaseComponent models" - raise ValueError, msg + raise ValueError(msg) else: return self._line(x) diff --git a/src/sas/sasgui/plottools/PlotPanel.py b/src/sas/sasgui/plottools/PlotPanel.py index 80536971c7..1848e9bb82 100644 --- a/src/sas/sasgui/plottools/PlotPanel.py +++ b/src/sas/sasgui/plottools/PlotPanel.py @@ -5,7 +5,14 @@ import logging import traceback +import math +import os +import operator +import copy + import wx +import numpy as np + # Try a normal import first # If it fails, try specifying a version import matplotlib @@ -14,27 +21,22 @@ matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure -import os -import transform -#TODO: make the plottables interactive -from binder import BindArtist from matplotlib.font_manager import FontProperties -DEBUG = False - -from plottables import Graph -from TextDialog import TextDialog -from LabelDialog import LabelDialog -import operator - -import math import pylab DEFAULT_CMAP = pylab.cm.jet -import copy -import numpy as np from sas.sasgui.guiframe.events import StatusEvent + +#TODO: make the plottables interactive +from . import transform +from .TextDialog import TextDialog +from .LabelDialog import LabelDialog +from .binder import BindArtist +from .convert_units import convert_unit +from .plottables import Graph from .toolbar import NavigationToolBar, PlotPrintout, bind +DEBUG = False logger = logging.getLogger(__name__) def show_tree(obj, d=0): @@ -43,7 +45,6 @@ def show_tree(obj, d=0): if 'get_children' in dir(obj): for a in obj.get_children(): show_tree(a, d + 1) -from convert_units import convert_unit def _rescale(lo, hi, step, pt=None, bal=None, scale='linear'): @@ -115,7 +116,7 @@ def __init__(self, parent, id=-1, xtransform=None, self.line_collections_list = [] self.figure = Figure(None, dpi, linewidth=2.0) self.color = '#b3b3b3' - from canvas import FigureCanvas + from .canvas import FigureCanvas self.canvas = FigureCanvas(self, -1, self.figure) self.SetColor(color) self._resizeflag = True @@ -656,10 +657,10 @@ def onFitting(self, event): plot_dict[item] = plotlist[item] else: plot_dict = plotlist - from fitDialog import LinearFit + from .fitDialog import LinearFit if len(plot_dict.keys()) > 0: - first_item = plot_dict.keys()[0] + first_item = list(plot_dict.keys())[0] dlg = LinearFit(parent=None, plottable=first_item, push_data=self.onFitDisplay, transform=self.returnTrans, @@ -702,7 +703,7 @@ def linear_plottable_fit(self, plot): :param plot: PlotPanel owning the graph """ - from fitDialog import LinearFit + from .fitDialog import LinearFit if self._fit_dialog is not None: return self._fit_dialog = LinearFit(None, plot, self.onFitDisplay, @@ -735,7 +736,7 @@ def _onProperties(self, event): if len(plot_list.keys()) > 0: first_item = plot_list.keys()[0] if first_item.x != []: - from PropertyDialog import Properties + from .PropertyDialog import Properties dial = Properties(self, -1, 'Properties') dial.setValues(self.prevXtrans, self.prevYtrans, self.viewModel) if dial.ShowModal() == wx.ID_OK: @@ -1000,9 +1001,8 @@ def remove_legend(self, ax=None): """ Remove legend for ax or the current axes. """ - from pylab import gca if ax is None: - ax = gca() + ax = pylab.gca() ax.legend_ = None def _on_addtext(self, event): @@ -1326,7 +1326,7 @@ def interactive_points(self, x, y, dx=None, dy=None, name='', color=0, self.subplot.set_xscale('linear') if id is None: id = name - from plottable_interactor import PointInteractor + from .plottable_interactor import PointInteractor p = PointInteractor(self, self.subplot, zorder=zorder, id=id) if p.markersize is not None: markersize = p.markersize @@ -1343,7 +1343,7 @@ def interactive_curve(self, x, y, dy=None, name='', color=0, self.subplot.set_xscale('linear') if id is None: id = name - from plottable_interactor import PointInteractor + from .plottable_interactor import PointInteractor p = PointInteractor(self, self.subplot, zorder=zorder, id=id) p.curve(x, y, dy=dy, color=color, symbol=symbol, zorder=zorder, label=label) @@ -1743,7 +1743,7 @@ def _onEVT_FUNC_PROPERTY(self, remove_fit=True, show=True): if remove_fit: self.graph.delete(self.fit_result) if hasattr(self, 'plots'): - if 'fit' in self.plots.keys(): + if 'fit' in self.plots: del self.plots['fit'] self.ly = None self.q_ctrl = None diff --git a/src/sas/sasgui/plottools/__init__.py b/src/sas/sasgui/plottools/__init__.py index f00c4528f0..d1e54aa578 100644 --- a/src/sas/sasgui/plottools/__init__.py +++ b/src/sas/sasgui/plottools/__init__.py @@ -1,2 +1,2 @@ -from PlotPanel import PlotPanel -from plottables import Data1D, Theory1D +from .PlotPanel import PlotPanel +from .plottables import Data1D, Theory1D diff --git a/src/sas/sasgui/plottools/binder.py b/src/sas/sasgui/plottools/binder.py index a31b653fa9..12c7bd27e1 100644 --- a/src/sas/sasgui/plottools/binder.py +++ b/src/sas/sasgui/plottools/binder.py @@ -27,14 +27,16 @@ def __eq__(self, other): def __ne__(self, other): return self.artist is not other.artist - def __nonzero__(self): + def __bool__(self): return self.artist is not None + __nonzero__ = __bool__ + class BindArtist(object): """ + Track keyboard modifiers for events. """ - # Track keyboard modifiers for events. # TODO: Move keyboard modifier support into the backend. We cannot # TODO: properly support it from outside the windowing system since there # TODO: is no way to recognized whether shift is held down when the mouse @@ -64,7 +66,7 @@ def __init__(self, figure): canvas.mpl_connect('scroll_event', self._onScroll) ] except: - print("bypassing scroll_event: wrong matplotlib version") + logger.warn("bypassing scroll_event: wrong matplotlib version") self._connections = [ canvas.mpl_connect('motion_notify_event', self._onMotion), canvas.mpl_connect('button_press_event', self._onClick), @@ -73,6 +75,13 @@ def __init__(self, figure): canvas.mpl_connect('key_release_event', self._onKeyRelease), ] + # Turn off picker if it hasn't already been done + try: + canvas.mpl_disconnect(canvas.button_pick_id) + canvas.mpl_disconnect(canvas.scroll_pick_id) + except Exception as exc: + logger.error(exc) + self._current = None self._actions = {} self.canvas = canvas @@ -86,7 +95,6 @@ def clear(self, *artists): Use clearall() to reset all connections. """ - for h in artists: for a in self.events: if h in self._actions[a]: @@ -122,9 +130,10 @@ def disconnect(self): In case we need to disconnect from the canvas... """ try: - for cid in self._connections: self.canvas.mpl_disconnect(cid) - except: - logger.error("Error disconnection canvas: %s" % sys.exc_value) + for cid in self._connections: + self.canvas.mpl_disconnect(cid) + except Exception as exc: + logger.error("Error disconnection canvas: %s" % exc) self._connections = [] def __del__(self): @@ -171,25 +180,24 @@ def __call__(self, trigger, artist, action): When receiving an event, first check the modifier state to be sure it applies. E.g., the callback for 'press' might be: if event.button == 1 and event.shift: process Shift-click - - TODO: Only receive events with the correct modifiers (e.g., S-click, - TODO: or *-click for any modifiers). - TODO: Only receive button events for the correct button (e.g., click1 - TODO: release3, or dclick* for any button) - TODO: Support virtual artist, so that and artist can be flagged as - TODO: having a tag list and receive the correct events - TODO: Support virtual events for binding to button-3 vs shift button-1 - TODO: without changing callback code - TODO: Attach multiple callbacks to the same event? - TODO: Clean up interaction with toolbar modes - TODO: push/pushclear/pop context so that binding changes for - the duration - TODO: e.g., to support ? context sensitive help """ + #TODO: Only receive events with the correct modifiers (e.g., S-click, + #TODO: or *-click for any modifiers). + #TODO: Only receive button events for the correct button (e.g., click1 + #TODO: release3, or dclick* for any button) + #TODO: Support virtual artist, so that and artist can be flagged as + #TODO: having a tag list and receive the correct events + #TODO: Support virtual events for binding to button-3 vs shift button-1 + #TODO: without changing callback code + #TODO: Attach multiple callbacks to the same event? + #TODO: Clean up interaction with toolbar modes + #TODO: push/pushclear/pop context so that binding changes for the duration + #TODO: e.g., to support ? context sensitive help + # Check that the trigger is valid if trigger not in self._actions: - raise ValueError, "%s invalid --- valid triggers are %s"\ - % (trigger, ", ".join(self.events)) + raise ValueError("%s invalid --- valid triggers are %s" + % (trigger, ", ".join(self.events))) # Register the trigger callback self._actions[trigger][artist] = action @@ -204,7 +212,7 @@ def trigger(self, actor, action, ev): to figure, and to 'all' if the event is not processed. """ if action not in self.events: - raise ValueError, "Trigger expects " + ", ".join(self.events) + raise ValueError("Trigger expects " + ", ".join(self.events)) # Tag the event with modifiers for mod in ('alt', 'control', 'shift', 'meta'): @@ -213,7 +221,7 @@ def trigger(self, actor, action, ev): setattr(ev, 'action', action) setattr(ev, 'prop', {}) - # Fallback scheme. If the event does not return false, pass to parent. + # Fallback scheme. If the event does not return false, pass to parent. processed = False artist, prop = actor.artist, actor.prop if artist in self._actions[action]: @@ -236,7 +244,7 @@ def _find_current(self, event): registered artists. All others are invisible to the mouse. """ # TODO: sort by zorder of axes then by zorder within axes - self._artists.sort(cmp=lambda x, y: cmp(y.zorder, x.zorder)) + self._artists.sort(key=lambda x: x.zorder, reverse=True) found = Selection() for artist in self._artists: # TODO: should contains() return false if invisible? @@ -275,7 +283,7 @@ def _onMotion(self, event): # artist rather than the default axes coordinates. transform = self._hasclick.artist.get_transform() - # x,y = event.xdata,event.ydata + #x,y = event.xdata,event.ydata x, y = event.x, event.y try: if transform.__class__.__name__ == "IdentityTransform": @@ -285,13 +293,13 @@ def _onMotion(self, event): # # don't know why maybe marker definition # #transform ="CompositeGenericTransform" crash pass - except: - # # CRUFT matplotlib-0.91 support + except: # CRUFT: matplotlib-0.91 support # # exception for transform ="CompositeGenericTransform" # # crashes also here x, y = transform.inverse_xy_tup((x, y)) - # event.xdata, event.ydata = x, y + #TODO: why compute (x,y) if it isn't being used? + #event.xdata, event.ydata = x, y self.trigger(self._hasclick, 'drag', event) else: found = self._find_current(event) diff --git a/src/sas/sasgui/plottools/canvas.py b/src/sas/sasgui/plottools/canvas.py index 6349411685..50a8113299 100644 --- a/src/sas/sasgui/plottools/canvas.py +++ b/src/sas/sasgui/plottools/canvas.py @@ -96,8 +96,8 @@ def OnPrintPage(self, page): except: try: dc.DrawBitmap(self.canvas.bitmap, (0, 0)) - except: - logger.error(sys.exc_value) + except Exception as exc: + logger.error(exc) # restore original figure resolution self.canvas.figure.set_facecolor(bgcolor) @@ -207,8 +207,8 @@ def draw(self, drawDC=None): # st = time.time() try: fig.draw(self) - except ValueError: - logger.error(sys.exc_value) + except ValueError as exc: + logger.error(exc) else: self._isRendered = False if self.ndraw <= 1: diff --git a/src/sas/sasgui/plottools/convert_units.py b/src/sas/sasgui/plottools/convert_units.py index af89f87187..21b6bd8b8d 100644 --- a/src/sas/sasgui/plottools/convert_units.py +++ b/src/sas/sasgui/plottools/convert_units.py @@ -12,22 +12,22 @@ def convert_unit(power, unit): Convert units to strings that can be displayed """ if power != 0: - if string.find(unit, "^") != -1: # if the unit contains a powerer ^ - toks = re.split("\^", unit) - if string.find(toks[0], "/") != -1 or \ - string.find(toks[0], "-") != -1: + if unit.find("^") != -1: # if the unit contains a powerer ^ + toks = re.split(r"\^", unit) + if toks[0].find("/") != -1 or \ + toks[0].find("-") != -1: if power == 1: unit = unit else: unit = "(" + unit + ")" + "^{" + str(power) + "}" else: - if string.find(toks[1], "{") != -1: # if found a { + if toks[1].find("{") != -1: # if found a { find_power_toks = re.split("{", toks[1]) - if string.find(find_power_toks[1], "}") != -1: # found } + if find_power_toks[1].find("}") != -1: # found } unit_toks = re.split("}", find_power_toks[1]) - if string.find(unit_toks[0], ".") != -1: + if unit_toks[0].find(".") != -1: powerer = float(unit_toks[0]) * power - elif string.find(unit_toks[0], "/") != -1: + elif unit_toks[0].find("/") != -1: power_toks = re.split("/", unit_toks[0]) powerer = power * int(power_toks[0])\ / int(power_toks[1]) @@ -43,12 +43,12 @@ def convert_unit(power, unit): else: unit = toks[0] + "^{" + str(powerer) + "}" else: - raise ValueError, "missing } in unit expression" + raise ValueError("missing } in unit expression") else: # no powerer if power != 1: unit = "(" + unit + ")" + "^{" + str(power) + "}" else: - raise ValueError, "empty unit ,enter a powerer different from zero" + raise ValueError("empty unit, enter a power different from zero") return unit diff --git a/src/sas/sasgui/plottools/fitDialog.py b/src/sas/sasgui/plottools/fitDialog.py index 68d7f7aea1..8f8fe8afbb 100644 --- a/src/sas/sasgui/plottools/fitDialog.py +++ b/src/sas/sasgui/plottools/fitDialog.py @@ -1,10 +1,12 @@ -import wx -from plottables import Theory1D +import sys import math + +import wx import numpy as np -import fittings -import transform -import sys + +from . import fittings +from . import transform +from .plottables import Theory1D # Linear fit panel size if sys.platform.count("win32") > 0: @@ -85,7 +87,7 @@ def __init__(self, parent, plottable, push_data, transform, title): # Now set up the dialog interface self.layout() # Receives the type of model for the fitting - from LineModel import LineModel + from .LineModel import LineModel self.model = LineModel() # Display the fittings values self.default_A = self.model.getParam('A') @@ -670,7 +672,7 @@ def floatTransform(self, x): if x > 0: return x else: - raise ValueError, "cannot compute log of a negative number" + raise ValueError("cannot compute log of a negative number") def floatInvTransform(self, x): """ @@ -733,7 +735,7 @@ def set_fit_region(self, xmin, xmax): float(xmax) except: msg = "LinearFit.set_fit_region: fit range must be floats" - raise ValueError, msg + raise ValueError(msg) self.xminFit.SetValue(format_number(xmin)) self.xmaxFit.SetValue(format_number(xmax)) diff --git a/src/sas/sasgui/plottools/fittings.py b/src/sas/sasgui/plottools/fittings.py index 79d1225440..1dc9fd6b75 100644 --- a/src/sas/sasgui/plottools/fittings.py +++ b/src/sas/sasgui/plottools/fittings.py @@ -100,7 +100,7 @@ def chi2(params): def calcCommandline(event): # Testing implementation # Fit a Line model - from LineModel import LineModel + from .LineModel import LineModel line = LineModel() cstA = Parameter(line, 'A', event.cstA) cstB = Parameter(line, 'B', event.cstB) diff --git a/src/sas/sasgui/plottools/plottable_interactor.py b/src/sas/sasgui/plottools/plottable_interactor.py index a40374c814..23c51474b8 100644 --- a/src/sas/sasgui/plottools/plottable_interactor.py +++ b/src/sas/sasgui/plottools/plottable_interactor.py @@ -3,7 +3,7 @@ """ from __future__ import print_function -from BaseInteractor import _BaseInteractor +from .BaseInteractor import _BaseInteractor class PointInteractor(_BaseInteractor): diff --git a/src/sas/sasgui/plottools/plottables.py b/src/sas/sasgui/plottools/plottables.py index 13da95c0dd..38d8b637c8 100644 --- a/src/sas/sasgui/plottools/plottables.py +++ b/src/sas/sasgui/plottools/plottables.py @@ -388,7 +388,7 @@ def __call__(self, plottable, **kwargs): user, along with an indication of which plottable was at fault. """ - raise NotImplemented, "Not a valid transform" + raise NotImplemented("Not a valid transform") # Related issues # ============== @@ -688,17 +688,17 @@ def transform(self, x=None, y=None, dx=None, dy=None): if dx is not None and not len(dx) == 0 and not len(x) == len(dx): msg = "Plottable.View: Given x and dx are not" msg += " of the same length" - raise ValueError, msg + raise ValueError(msg) # Check length of y array if not len(y) == len(x): msg = "Plottable.View: Given y " msg += "and x are not of the same length" - raise ValueError, msg + raise ValueError(msg) if dy is not None and not len(dy) == 0 and not len(y) == len(dy): msg = "Plottable.View: Given y and dy are not of the same " msg += "length: len(y)=%s, len(dy)=%s" % (len(y), len(dy)) - raise ValueError, msg + raise ValueError(msg) self.x = [] self.y = [] if has_err_x: @@ -733,15 +733,15 @@ def transform(self, x=None, y=None, dx=None, dy=None): if not len(self.x) == len(self.y): msg = "Plottable.View: transformed x " msg += "and y are not of the same length" - raise ValueError, msg + raise ValueError(msg) if has_err_x and not (len(self.x) == len(self.dx)): msg = "Plottable.View: transformed x and dx" msg += " are not of the same length" - raise ValueError, msg + raise ValueError(msg) if has_err_y and not (len(self.y) == len(self.dy)): msg = "Plottable.View: transformed y" msg += " and dy are not of the same length" - raise ValueError, msg + raise ValueError(msg) # Check that negative values are not plot on x and y axis for # log10 transformation self.check_data_logX() @@ -811,9 +811,9 @@ def check_data_logX(self): tempdx.append(self.dx[i]) tempy.append(self.y[i]) tempdy.append(self.dy[i]) - except: + except Exception as exc: logger.error("check_data_logX: skipping point x %g", self.x[i]) - logger.error(sys.exc_value) + logger.error(exc) self.x = tempx self.y = tempy self.dx = tempdx @@ -841,9 +841,9 @@ def check_data_logY(self): tempdx.append(self.dx[i]) tempy.append(self.y[i]) tempdy.append(self.dy[i]) - except: + except Exception as exc: logger.error("check_data_logY: skipping point %g", self.y[i]) - logger.error(sys.exc_value) + logger.error(exc) self.x = tempx self.y = tempy @@ -995,7 +995,7 @@ def set_zrange(self, zmin=None, zmax=None): self.zmin = zmin self.zmax = zmax else: - raise "zmin is greater or equal to zmax " + raise("zmin is greater or equal to zmax ") def render(self, plot, **kw): """ @@ -1107,7 +1107,7 @@ def __init__(self, x, y, dy=None): """ Plottable.__init__(self) msg = "Theory1D is no longer supported, please use Data1D and change symbol.\n" - raise DeprecationWarning, msg + raise DeprecationWarning(msg) class Fit1D(Plottable): """ diff --git a/src/sas/sasgui/plottools/toolbar.py b/src/sas/sasgui/plottools/toolbar.py index 4e44245322..e31ceb570e 100644 --- a/src/sas/sasgui/plottools/toolbar.py +++ b/src/sas/sasgui/plottools/toolbar.py @@ -38,7 +38,7 @@ def __init__(self, canvas, parent=None): # CRUFT: mpl 1.1 uses save rather than save_figure try: save_figure = NavigationToolbar2WxAgg.save except AttributeError: pass - + def _init_toolbar(self): self._parent = self.canvas.GetParent() @@ -64,11 +64,19 @@ def _init_toolbar(self): self.AddSimpleTool(self._NTB2_FORWARD, _load_bitmap('forward.png'), 'Forward', 'Forward navigation view') # todo: get new bitmap - self.AddCheckTool(self._NTB2_PAN, _load_bitmap('move.png'), - shortHelp='Pan', - longHelp='Pan with left, zoom with right') - self.AddCheckTool(self._NTB2_ZOOM, _load_bitmap('zoom_to_rect.png'), - shortHelp='Zoom', longHelp='Zoom to rectangle') + # todo: update with code from matplotlib/backends/backend_wx.py + if 'phoenix' in wx.PlatformInfo: # wx phoenix >= 4.0.0b2 + self.AddCheckTool(self._NTB2_PAN, "Pan", _load_bitmap('move.png'), + shortHelp='Pan', + longHelp='Pan with left, zoom with right') + self.AddCheckTool(self._NTB2_ZOOM, "Zoom", _load_bitmap('zoom_to_rect.png'), + shortHelp='Zoom', longHelp='Zoom to rectangle') + else: + self.AddCheckTool(self._NTB2_PAN, _load_bitmap('move.png'), + shortHelp='Pan', + longHelp='Pan with left, zoom with right') + self.AddCheckTool(self._NTB2_ZOOM, _load_bitmap('zoom_to_rect.png'), + shortHelp='Zoom', longHelp='Zoom to rectangle') self.AddSeparator() self.AddSimpleTool(self._NTB2_SAVE, _load_bitmap('filesave.png'), diff --git a/src/sas/sasgui/plottools/transform.py b/src/sas/sasgui/plottools/transform.py index 00028a83ec..65ca3ec1cf 100644 --- a/src/sas/sasgui/plottools/transform.py +++ b/src/sas/sasgui/plottools/transform.py @@ -23,7 +23,7 @@ def toX_pos(x, y=None): """ if not x > 0: - raise ValueError, "Transformation only accepts positive values." + raise ValueError("Transformation only accepts positive values.") else: return x @@ -49,7 +49,7 @@ def fromX2(x, y=None): """ if not x >= 0: - raise ValueError, "square root of a negative value " + raise ValueError("square root of a negative value ") else: return math.sqrt(x) @@ -75,7 +75,7 @@ def fromX4(x, y=None): """ if not x >= 0: - raise ValueError, "double square root of a negative value " + raise ValueError("double square root of a negative value ") else: return math.sqrt(math.sqrt(x)) @@ -89,7 +89,7 @@ def toLogX(x, y=None): """ if not x > 0: - raise ValueError, "Log(x)of a negative value " + raise ValueError("Log(x)of a negative value ") else: return math.log(x) @@ -99,7 +99,7 @@ def toOneOverX(x, y=None): if x != 0: return 1 / x else: - raise ValueError, "cannot divide by zero" + raise ValueError("cannot divide by zero") def toOneOverSqrtX(y, x=None): @@ -108,7 +108,7 @@ def toOneOverSqrtX(y, x=None): if y > 0: return 1 / math.sqrt(y) else: - raise ValueError, "transform.toOneOverSqrtX: cannot be computed" + raise ValueError("transform.toOneOverSqrtX: cannot be computed") def toLogYX2(y, x): @@ -117,7 +117,7 @@ def toLogYX2(y, x): if (y * (x ** 2)) > 0: return math.log(y * (x ** 2)) else: - raise ValueError, "transform.toLogYX2: cannot be computed" + raise ValueError("transform.toLogYX2: cannot be computed") def toLogYX4(y, x): @@ -126,7 +126,7 @@ def toLogYX4(y, x): if (math.pow(x, 4) * y) > 0: return math.log(math.pow(x, 4) * y) else: - raise ValueError, "transform.toLogYX4: input error" + raise ValueError("transform.toLogYX4: input error") def toYX4(y, x): @@ -148,7 +148,7 @@ def toLogXY(y, x): """ if not (x * y) > 0: - raise ValueError, "Log(X*Y)of a negative value " + raise ValueError("Log(X*Y)of a negative value ") else: return math.log(x * y) @@ -210,7 +210,7 @@ def errFromX2(x, y=None, dx=None, dy=None): return math.fabs(err) else: msg = "transform.errFromX2: can't compute error of negative x" - raise ValueError, msg + raise ValueError(msg) def errToX4(x, y=None, dx=None, dy=None): @@ -244,7 +244,7 @@ def errFromX4(x, y=None, dx=None, dy=None): return math.fabs(err) else: msg = "transform.errFromX4: can't compute error of negative x" - raise ValueError, msg + raise ValueError(msg) def errToLog10X(x, y=None, dx=None, dy=None): @@ -263,11 +263,11 @@ def errToLog10X(x, y=None, dx=None, dy=None): if not (x - dx) > 0: msg = "Transformation does not accept" msg += " point that are consistent with zero." - raise ValueError, msg + raise ValueError(msg) if x != 0: dx = dx / (x * math.log(10)) else: - raise ValueError, "errToLogX: divide by zero" + raise ValueError("errToLogX: divide by zero") return dx @@ -286,7 +286,7 @@ def errToLogX(x, y=None, dx=None, dy=None): if x != 0: dx = dx / x else: - raise ValueError, "errToLogX: divide by zero" + raise ValueError("errToLogX: divide by zero") return dx @@ -311,7 +311,7 @@ def errToLogXY(x, y, dx=None, dy=None): if not (x - dx) > 0 or not (y - dy) > 0: msg = "Transformation does not accept point " msg += " that are consistent with zero." - raise ValueError, msg + raise ValueError(msg) if x != 0 and y != 0: if dx is None: dx = 0 @@ -319,7 +319,7 @@ def errToLogXY(x, y, dx=None, dy=None): dy = 0 err = (dx / x) ** 2 + (dy / y) ** 2 else: - raise ValueError, "cannot compute this error" + raise ValueError("cannot compute this error") return math.sqrt(math.fabs(err)) @@ -334,7 +334,7 @@ def errToLogYX2(y, x, dy=None, dx=None): if not (x - dx) > 0 or not (y - dy) > 0: msg = "Transformation does not accept point" msg += " that are consistent with zero." - raise ValueError, msg + raise ValueError(msg) if x > 0 and y > 0: if dx is None: dx = 0 @@ -342,7 +342,7 @@ def errToLogYX2(y, x, dy=None, dx=None): dy = 0 err = (2.0 * dx / x) ** 2 + (dy / y) ** 2 else: - raise ValueError, "cannot compute this error" + raise ValueError("cannot compute this error") return math.sqrt(math.fabs(err)) @@ -356,7 +356,7 @@ def errOneOverX(x, y=None, dx=None, dy=None): dx = 0 err = dx / x ** 2 else: - raise ValueError, "Cannot compute this error" + raise ValueError("Cannot compute this error") return math.fabs(err) @@ -370,7 +370,7 @@ def errOneOverSqrtX(x, y=None, dx=None, dy=None): dx = 0 err = -1 / 2 * math.pow(x, -3.0 / 2.0) * dx else: - raise ValueError, "Cannot compute this error" + raise ValueError("Cannot compute this error") return math.fabs(err) @@ -386,7 +386,7 @@ def errToLogYX4(y, x, dy=None, dx=None): if (not (x - dx) > 0) or (not (y - dy) > 0): msg = "Transformation does not accept point " msg += " that are consistent with zero." - raise ValueError, msg + raise ValueError(msg) if dx is None: dx = 0 if dy is None: diff --git a/src/sas/sasview/sasview.py b/src/sas/sasview/sasview.py index 126e45ea84..8c46013d6e 100644 --- a/src/sas/sasview/sasview.py +++ b/src/sas/sasview/sasview.py @@ -41,7 +41,9 @@ def __init__(self): logger = logging.getLogger(__name__) from sas.sasgui.guiframe.gui_manager import SasViewApp + from sas.sasgui.guiframe.gui_style import GUIFRAME_ICON self.gui = SasViewApp(0) + GUIFRAME_ICON.load_icons() if sys.platform == "darwin": self.check_sasmodels_compiler() # Set the application manager for the GUI @@ -227,8 +229,13 @@ def setup_wx(): except AttributeError: logger.error("Wx version: error reading version") - from . import wxcruft - wxcruft.call_later_fix() + # TODO: Do we need the call later fix for wx 3? Or is it wx < 3 only? + if "phoenix" in wx.PlatformInfo: + #wx.NewId = wx.Window.NewControlId + pass + else: + from . import wxcruft + wxcruft.call_later_fix() #wxcruft.trace_new_id() #Always use private .matplotlib setup to avoid conflicts with other #uses of matplotlib diff --git a/src/sas/sasview/welcome_panel.py b/src/sas/sasview/welcome_panel.py index 71fcbf2e38..5f261a03c5 100644 --- a/src/sas/sasview/welcome_panel.py +++ b/src/sas/sasview/welcome_panel.py @@ -1,12 +1,16 @@ """ Welcome page """ -import wx -import wx.aui -import wx.lib.hyperlink import os.path import os, sys +import wx +import wx.aui +try: + # CRUFT: wx 4 moved hyperlink to wx.lib.agw + from wx.lib import hyperlink +except ImportError: + from wx.lib.agw import hyperlink from wx.lib.scrolledpanel import ScrolledPanel from sas import get_local_config @@ -114,7 +118,7 @@ def __init__(self, parent, *args, **kwds): send_ticket = "Send us a ticket at: " send_ticket += "help@sasview.org" self.hyperlink_paper = \ - wx.lib.hyperlink.HyperLinkCtrl(self, -1, + hyperlink.HyperLinkCtrl(self, -1, send_ticket, URL=config._license) self.label_title = \ diff --git a/src/sas/sasview/wxcruft.py b/src/sas/sasview/wxcruft.py index c46ae6d6a0..00fa6e2cbe 100644 --- a/src/sas/sasview/wxcruft.py +++ b/src/sas/sasview/wxcruft.py @@ -3,7 +3,6 @@ import inspect import wx from wx import Timer -import wx._misc def call_later_fix(): # TODO: test if we need the fix @@ -15,6 +14,7 @@ def trace_new_id(): wx.NewId = NewId def NewId(): + import wx._misc id = wx._misc.NewId() path, line, function = _get_caller() if path == "sas/guiframe/utils.py":