Changeset 5251ec6 in sasview
- Timestamp:
- Oct 11, 2018 2:20:56 PM (6 years ago)
- Branches:
- master, magnetic_scatt, release-4.2.2, ticket-1009, ticket-1249
- Children:
- 98b9f32
- Parents:
- 67ed543
- Location:
- src/sas
- Files:
-
- 98 edited
Legend:
- Unmodified
- Added
- Removed
-
src/sas/sasgui/guiframe/CategoryInstaller.py
ra26f67f r5251ec6 121 121 """ 122 122 _model_dict = {model.name: model for model in model_list} 123 _model_list = _model_dict.keys()123 _model_list = list(_model_dict.keys()) 124 124 125 125 serialized_file = None … … 146 146 by_model_dict.pop(model_name) 147 147 model_enabled_dict.pop(model_name) 148 except Exception :149 logger.error("CategoryInstaller: %s", sys.exc_value)148 except Exception as exc: 149 logger.error("CategoryInstaller: %s", exc) 150 150 else: 151 151 add_list.remove(model_name) … … 171 171 model_enabled_dict) 172 172 173 json.dump(master_category_dict, open(serialized_file, 'w b'))173 json.dump(master_category_dict, open(serialized_file, 'w')) -
src/sas/sasgui/guiframe/CategoryManager.py
r463e7ffc r5251ec6 230 230 231 231 for model in model_name_list: 232 index = self.cat_list.InsertStringItem(sys.max int, model)232 index = self.cat_list.InsertStringItem(sys.maxsize, model) 233 233 self.cat_list.SetStringItem(index, 1, \ 234 234 str(self.by_model_dict[model]).\ … … 384 384 """ 385 385 cat_list = list() 386 for category in self.master_category_dict. iterkeys():386 for category in self.master_category_dict.keys(): 387 387 if not category == 'Uncategorized': 388 388 cat_list.append(category) -
src/sas/sasgui/guiframe/custom_pstats.py
r959eb01 r5251ec6 36 36 width = self.max_name_len 37 37 if self.fcn_list: 38 list= self.fcn_list[:]38 stats = self.fcn_list[:] 39 39 temp_msg = " Ordered by: " + self.sort_type + '\n' 40 40 else: 41 list = self.stats.keys()41 stats = list(self.stats.keys()) 42 42 temp_msg = " Random listing order was used\n" 43 43 44 44 for selection in amount: 45 list, temp_msg = self.eval_print_amount(selection, list, temp_msg)45 stats, temp_msg = self.eval_print_amount(selection, stats, temp_msg) 46 46 47 count = len( list)47 count = len(stats) 48 48 49 if not list:50 width , list = 0, list49 if not stats: 50 width = 0 51 51 else: 52 msg += 52 msg += str(temp_msg) + '\n' 53 53 if count < len(self.stats): 54 54 width = 0 55 for func in list:55 for func in stats: 56 56 if len(func_std_string(func)) > width: 57 57 width = len(func_std_string(func)) 58 58 59 width , list = width+2, list60 if list:59 width = width+2 60 if stats: 61 61 msg += ' ncalls tottime percall cumtime percall' 62 62 msg += ' filename:lineno(function)' + "\n" 63 for func in list:63 for func in stats: 64 64 cc, nc, tt, ct, callers = self.stats[func] 65 65 c = str(nc) -
src/sas/sasgui/guiframe/data_manager.py
r959eb01 r5251ec6 51 51 _str += "No of states is %s \n" % str(len(self.stored_data)) 52 52 n_count = 0 53 for 53 for value in self.stored_data.values(): 54 54 n_count += 1 55 55 _str += "State No %s \n" % str(n_count) … … 134 134 receive a list of 135 135 """ 136 for id, data in data_list.ite ritems():136 for id, data in data_list.items(): 137 137 if id in self.stored_data: 138 138 msg = "Data manager already stores %s" % str(data.name) … … 150 150 """ 151 151 """ 152 if prev_data.id not in self.stored_data .keys():152 if prev_data.id not in self.stored_data: 153 153 return None, {} 154 154 data_state = self.stored_data[prev_data.id] 155 155 self.stored_data[new_data.id] = data_state.clone() 156 156 self.stored_data[new_data.id].data = new_data 157 if prev_data.id in self.stored_data .keys():157 if prev_data.id in self.stored_data: 158 158 del self.stored_data[prev_data.id] 159 159 return prev_data.id, {new_data.id: self.stored_data[new_data.id]} … … 165 165 if data_id is None and theory is not None: 166 166 uid = theory.id 167 if uid in self.stored_data .keys():167 if uid in self.stored_data: 168 168 data_state = self.stored_data[uid] 169 169 else: … … 195 195 if search_id == d_id: 196 196 _selected_data[search_id] = data 197 if search_id in theory_list .keys():197 if search_id in theory_list: 198 198 _selected_theory_list[search_id] = theory_list[search_id] 199 199 … … 204 204 """ 205 205 """ 206 return self.freeze_theory( self.stored_data.keys(), theory_id)206 return self.freeze_theory(list(self.stored_data.keys()), theory_id) 207 207 208 208 def freeze_theory(self, data_id, theory_id): … … 215 215 theory_list = data_state.get_theory() 216 216 for t_id in theory_id: 217 if t_id in theory_list .keys():217 if t_id in theory_list: 218 218 theory_data, theory_state = theory_list[t_id] 219 219 new_theory = copy.deepcopy(theory_data) … … 235 235 """ 236 236 for d_id in data_id: 237 if d_id in self.stored_data .keys():237 if d_id in self.stored_data: 238 238 data_state = self.stored_data[d_id] 239 239 if data_state.data.name in self.data_name_dict: … … 253 253 data_state = self.stored_data[d_id] 254 254 theory_list = data_state.get_theory() 255 if theory_id in theory_list .keys():255 if theory_id in theory_list: 256 256 del theory_list[theory_id] 257 257 #del pure theory … … 273 273 _selected_data = {} 274 274 for selected_name in name_list: 275 for id, data_state in self.stored_data.ite ritems():275 for id, data_state in self.stored_data.items(): 276 276 if data_state.data.name == selected_name: 277 277 _selected_data[id] = data_state.data … … 283 283 """ 284 284 for selected_name in name_list: 285 for id, data_state in self.stored_data.ite ritems():285 for id, data_state in self.stored_data.items(): 286 286 if data_state.data.name == selected_name: 287 287 del self.stored_data[id] … … 293 293 _selected_data_state = {} 294 294 for id in data_id: 295 if id in self.stored_data .keys():295 if id in self.stored_data: 296 296 _selected_data_state[id] = self.stored_data[id] 297 297 return _selected_data_state … … 303 303 return self.stored_data 304 304 305 306 -
src/sas/sasgui/guiframe/data_panel.py
rb963b20 r5251ec6 13 13 from __future__ import print_function 14 14 15 import sys 16 15 17 import wx 16 from wx.build import build_options17 18 import sys19 18 from wx.lib.scrolledpanel import ScrolledPanel 20 19 import wx.lib.agw.customtreectrl as CT 20 #from wx.build import build_options 21 21 22 from sas.sasgui.guiframe.dataFitting import Data1D 22 23 from sas.sasgui.guiframe.dataFitting import Data2D … … 444 445 self.parent.get_data_manager().get_by_id(id_list=[id]) 445 446 if data_list: 446 data = data_list.values()[0]447 data = list(data_list.values())[0] 447 448 if data is None: 448 data = theory_list.values()[0][0]449 data = list(theory_list.values())[0][0] 449 450 return data 450 451 … … 667 668 """ 668 669 if list: 669 for state_id, dstate in list.ite ritems():670 for state_id, dstate in list.items(): 670 671 data = dstate.get_data() 671 672 theory_list = dstate.get_theory() … … 764 765 if not theory_list: 765 766 return 766 if state_id not in self.list_cb_data .keys():767 if state_id not in self.list_cb_data: 767 768 root = self.tree_ctrl_theory.root 768 769 tree = self.tree_ctrl_theory … … 783 784 Append theory helper 784 785 """ 785 if state_id in self.list_cb_theory .keys():786 if state_id in self.list_cb_theory: 786 787 # update current list of theory for this data 787 788 theory_list_ctrl = self.list_cb_theory[state_id] 788 789 789 for theory_id, item in theory_list.ite ritems():790 for theory_id, item in theory_list.items(): 790 791 theory_data, _ = item 791 792 if theory_data is None: … … 828 829 # data didn't have a theory associated it before 829 830 theory_list_ctrl = {} 830 for theory_id, item in theory_list.ite ritems():831 for theory_id, item in theory_list.items(): 831 832 theory_data, _ = item 832 833 if theory_data is not None: … … 868 869 869 870 for theory_dict in self.list_cb_theory.values(): 870 for _, value in theory_dict.ite ritems():871 for _, value in theory_dict.items(): 871 872 item, _, _ = value 872 873 if item.IsChecked(): … … 924 925 theory_key = [] 925 926 # remove data from treectrl 926 for d_key, item in self.list_cb_data.ite ritems():927 for d_key, item in self.list_cb_data.items(): 927 928 data_c, _, _, _, _, _, _, _ = item 928 929 if data_c.IsChecked(): 929 930 self.tree_ctrl.Delete(data_c) 930 931 data_key.append(d_key) 931 if d_key in self.list_cb_theory .keys():932 if d_key in self.list_cb_theory: 932 933 theory_list_ctrl = self.list_cb_theory[d_key] 933 theory_to_remove += theory_list_ctrl.keys()934 theory_to_remove += list(theory_list_ctrl.keys()) 934 935 # Remove theory from treectrl 935 for _, theory_dict in self.list_cb_theory.ite ritems():936 for key, value in theory_dict.ite ritems():936 for _, theory_dict in self.list_cb_theory.items(): 937 for key, value in theory_dict.items(): 937 938 item, _, _ = value 938 939 if item.IsChecked(): … … 950 951 # remove theory references independently of data 951 952 for key in theory_key: 952 for _, theory_dict in self.list_cb_theory.ite ritems():953 for _, theory_dict in self.list_cb_theory.items(): 953 954 if key in theory_dict: 954 for key, value in theory_dict.ite ritems():955 for key, value in theory_dict.items(): 955 956 item, _, _ = value 956 957 if item.IsChecked(): … … 1047 1048 if self.cb_plotpanel and self.cb_plotpanel.IsBeingDeleted(): 1048 1049 return 1049 for _, value in self.parent.plot_panels.ite ritems():1050 for _, value in self.parent.plot_panels.items(): 1050 1051 name_plot_panel = str(value.window_caption) 1051 1052 if name_plot_panel not in self.cb_plotpanel.GetItems(): … … 1129 1130 #import documentation window here to avoid circular imports 1130 1131 #if put at top of file with rest of imports. 1131 from documentation_window import DocumentationWindow1132 from .documentation_window import DocumentationWindow 1132 1133 1133 1134 _TreeLocation = "user/sasgui/guiframe/data_explorer_help.html" … … 1499 1500 window.Show(True) 1500 1501 window.load_data_list(list=temp_data_list) 1501 except :1502 except Exception as exc: 1502 1503 # raise 1503 print("error", sys.exc_value)1504 print("error", exc) 1504 1505 1505 1506 app.MainLoop() -
src/sas/sasgui/guiframe/data_processor.py
r20fa5fe r5251ec6 234 234 # overriden in this subclassn - actually we have currently 235 235 # disabled the on_context_menu that would override the OnRightClick 236 self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnCellChange) 236 try: 237 EVT_GRID_CELL_CHANGED = wx.grid.EVT_GRID_CELL_CHANGED 238 except AttributeError: 239 # CRUFT: wx 3.x uses CHANGE rather than CHANGING/CHANGED 240 EVT_GRID_CELL_CHANGED = wx.grid.EVT_GRID_CELL_CHANGE 241 self.Bind(EVT_GRID_CELL_CHANGED, self.OnCellChange) 237 242 self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnLeftClick) 238 243 self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self.OnRightClick) … … 561 566 value = self.GetCellValue(row, col) 562 567 self.data[col_name].append(value) 563 for k, value_list in self.data.ite ritems():568 for k, value_list in self.data.items(): 564 569 if k != col_name: 565 570 length = len(value_list) … … 621 626 if col_name.strip() != "Empty": 622 627 self.SetCellValue(row, col, str(col_name.strip())) 623 if col_name in self.data .keys():628 if col_name in self.data: 624 629 value_list = self.data[col_name] 625 630 cell_row = 1 … … 674 679 self._cols = self.GetNumberCols() 675 680 self._rows = self.GetNumberRows() 676 self.col_names = self.data_outputs.keys()681 self.col_names = list(self.data_outputs.keys()) 677 682 self.col_names.sort() 678 683 nbr_user_cols = len(self.col_names) … … 682 687 self.AppendCols(new_col_nbr, True) 683 688 #Add more rows to the grid if necessary 684 nbr_user_row = len( self.data_outputs.values()[0])689 nbr_user_row = len(list(self.data_outputs.values())[0]) 685 690 if nbr_user_row > self._rows + 1: 686 691 new_row_nbr = nbr_user_row - self._rows + 1 … … 909 914 msg = "Edit axis doesn't understand this selection.\n" 910 915 msg += "Please select only one column" 911 raise ValueError , msg916 raise ValueError(msg) 912 917 for (_, cell_col) in grid.selected_cells: 913 918 if cell_col != col: … … 915 920 msg += "this operation.\n" 916 921 msg += "Please select elements of the same col.\n" 917 raise ValueError , msg922 raise ValueError(msg) 918 923 919 924 # Finally check the highlighted cell if any cells missing … … 922 927 msg = "No item selected.\n" 923 928 msg += "Please select only one column or one cell" 924 raise ValueError , msg929 raise ValueError(msg) 925 930 return grid.selected_cells 926 931 … … 1326 1331 if sentence.strip() == "": 1327 1332 msg = "Select column values for x axis" 1328 raise ValueError , msg1333 raise ValueError(msg) 1329 1334 except: 1330 1335 msg = "X axis value error." … … 1345 1350 if sentence.strip() == "": 1346 1351 msg = "select value for y axis" 1347 raise ValueError , msg1352 raise ValueError(msg) 1348 1353 except: 1349 1354 msg = "Y axis value error." … … 1440 1445 """ 1441 1446 1442 for tok, (col_name, list) in dict.ite ritems():1447 for tok, (col_name, list) in dict.items(): 1443 1448 col = column_names[col_name] 1444 1449 axis = self.get_plot_axis(col, list) … … 1446 1451 return None 1447 1452 sentence = sentence.replace(tok, "numpy.array(%s)" % str(axis)) 1448 for key, value in FUNC_DICT.ite ritems():1453 for key, value in FUNC_DICT.items(): 1449 1454 sentence = sentence.replace(key.lower(), value) 1450 1455 return sentence … … 1546 1551 cell_list = self.notebook.on_edit_axis() 1547 1552 label, title = self.create_axis_label(cell_list) 1548 except :1549 msg = str( sys.exc_value)1553 except Exception as exc: 1554 msg = str(exc) 1550 1555 wx.PostEvent(self.parent.parent, StatusEvent(status=msg, info="error")) 1551 1556 return … … 2036 2041 frame = GridFrame(data_outputs=data, data_inputs=data_input) 2037 2042 frame.Show(True) 2038 except :2039 print( sys.exc_value)2043 except Exception as exc: 2044 print(exc) 2040 2045 2041 2046 app.MainLoop() -
src/sas/sasgui/guiframe/data_state.py
r959eb01 r5251ec6 37 37 _str += "Theories available: %s \n" % len(self.theory_list) 38 38 if self.theory_list: 39 for id, item in self.theory_list.ite ritems():39 for id, item in self.theory_list.items(): 40 40 theory_data, theory_state = item 41 41 _str += "Theory name : %s \n" % str(theory_data.name) … … 53 53 obj.message = self.message 54 54 obj.id = self.id 55 for id, item in self.theory_list.ite ritems():55 for id, item in self.theory_list.items(): 56 56 theory_data, theory_state = item 57 57 state = None … … 95 95 """ 96 96 self.theory_list[theory_data.id] = [theory_data, theory_state] 97 data, state = self.theory_list.values()[0]97 data, state = list(self.theory_list.values())[0] 98 98 99 99 def get_theory(self): … … 106 106 return self.message 107 107 108 -
src/sas/sasgui/guiframe/gui_manager.py
r8ac05a5 r5251ec6 13 13 14 14 15 import wx16 import wx.aui17 15 import os 18 16 import sys … … 25 23 import urllib 26 24 import json 25 import copy 26 27 import wx 28 import wx.aui 27 29 28 30 from matplotlib import _pylab_helpers … … 286 288 return client size tuple 287 289 """ 288 width, height = self.GetClientSize Tuple()290 width, height = self.GetClientSize() 289 291 height -= 45 290 292 # Adjust toolbar height … … 361 363 try: 362 364 self.read_batch_tofile(file_name=path) 363 except :365 except Exception as exc: 364 366 msg = "Error occurred when reading the file; %s\n" % path 365 msg += "%s\n" % sys.exc_value 366 wx.PostEvent(self, StatusEvent(status=msg, 367 info="error")) 367 msg += "%s\n" % exc 368 wx.PostEvent(self, StatusEvent(status=msg, info="error")) 368 369 369 370 def read_batch_tofile(self, file_name): … … 705 706 try: 706 707 self.load_from_cmd(self._input_file) 707 except :708 except Exception as exc: 708 709 msg = "%s Cannot load file %s\n" % (str(APPLICATION_NAME), 709 710 str(self._input_file)) 710 msg += str( sys.exc_value) + '\n'711 msg += str(exc) + '\n' 711 712 logger.error(msg) 712 713 if self._data_panel is not None and len(self.plugins) > 0: … … 797 798 self._data_plugin = data_loader.Plugin() 798 799 plugins.append(self._data_plugin) 799 except :800 except Exception as exc: 800 801 msg = "ViewerFrame._get_local_plugins:" 801 msg += "cannot import dataloader plugin.\n %s" % sys.exc_value802 msg += "cannot import dataloader plugin.\n %s" % exc 802 803 logger.error(msg) 803 804 if style2 == GUIFRAME.PLOTTING_ON: … … 807 808 self._plotting_plugin = plotting.Plugin() 808 809 plugins.append(self._plotting_plugin) 809 except :810 except Exception as exc: 810 811 msg = "ViewerFrame._get_local_plugins:" 811 msg += "cannot import plotting plugin.\n %s" % sys.exc_value812 msg += "cannot import plotting plugin.\n %s" % exc 812 813 logger.error(msg) 813 814 … … 856 857 msg = "Found plug-in: %s" % module.PLUGIN_ID 857 858 logger.info(msg) 858 except :859 except Exception as exc: 859 860 msg = "Error accessing PluginPanel" 860 msg += " in %s\n %s" % (name, sys.exc_value)861 msg += " in %s\n %s" % (name, exc) 861 862 config.printEVT(msg) 862 except :863 msg = "ViewerFrame._find_plugins: %s" % sys.exc_value863 except Exception as exc: 864 msg = "ViewerFrame._find_plugins: %s" % exc 864 865 logger.error(msg) 865 866 finally: 866 867 if file is not None: 867 868 file.close() 868 except :869 except Exception as exc: 869 870 # Should raise and catch at a higher level and 870 871 # display error on status bar 871 logger.error( sys.exc_value)872 logger.error(exc) 872 873 873 874 return plugins … … 1599 1600 """ 1600 1601 # This CallAfter fixes many crashes on MAC. 1601 wx.CallAfter(self.sb.set_status, evt )1602 wx.CallAfter(self.sb.set_status, evt.Clone()) 1602 1603 1603 1604 def on_view(self, evt): … … 1643 1644 ID = str(uid) 1644 1645 config.printEVT("delete_panel: %s" % ID) 1645 if ID in self.panels .keys():1646 if ID in self.panels: 1646 1647 self.panel_on_focus = None 1647 1648 panel = self.panels[ID] … … 1655 1656 1656 1657 # delete uid number not str(uid) 1657 if ID in self.plot_panels .keys():1658 if ID in self.plot_panels: 1658 1659 del self.plot_panels[ID] 1659 if ID in self.panels .keys():1660 if ID in self.panels: 1660 1661 del self.panels[ID] 1661 1662 else: … … 1691 1692 try: 1692 1693 reader.read(path) 1693 except :1694 except Exception as exc: 1694 1695 msg = "DataLoader Error: Encounted Non-ASCII character" 1695 msg += "\n(%s)" % sys.exc_value1696 msg += "\n(%s)" % exc 1696 1697 wx.PostEvent(self, StatusEvent(status=msg, 1697 1698 info="error", … … 1774 1775 1775 1776 self.add_data(data_list=output) 1776 except :1777 except Exception as exc: 1777 1778 error_message = "Error while loading" 1778 1779 error_message += " Data from cmd:\n %s\n" % str(path) 1779 error_message += str( sys.exc_value) + "\n"1780 error_message += str(exc) + "\n" 1780 1781 logger.error(error_message) 1781 1782 … … 1795 1796 else: 1796 1797 return 1797 except :1798 except Exception as exc: 1798 1799 error_message = "Error while loading" 1799 1800 error_message += " Data folder from cmd:\n %s\n" % str(path) 1800 error_message += str( sys.exc_value) + "\n"1801 error_message += str(exc) + "\n" 1801 1802 logger.error(error_message) 1802 1803 … … 1865 1866 self._data_panel.selection_cbox.SetValue('Select all Data') 1866 1867 self._data_panel._on_selection_type(None) 1867 for _, theory_dict in self._data_panel.list_cb_theory.ite ritems():1868 for key, value in theory_dict.ite ritems():1868 for _, theory_dict in self._data_panel.list_cb_theory.items(): 1869 for key, value in theory_dict.items(): 1869 1870 item, _, _ = value 1870 1871 item.Check(True) … … 1974 1975 # case of a panel with multi-pages 1975 1976 if hasattr(panel, "opened_pages"): 1976 for _, page in panel.opened_pages.ite ritems():1977 for _, page in panel.opened_pages.items(): 1977 1978 data = page.get_data() 1978 1979 # state must be cloned … … 2096 2097 msg += " Please try again later." 2097 2098 self.SetStatusText(msg) 2098 elif cmp(version, config.__version__) > 0:2099 elif version > config.__version__: 2099 2100 msg = "Version %s is available! " % str(version) 2100 2101 if not standalone: … … 2112 2113 msg += " of %s" % str(config.__appname__) 2113 2114 self.SetStatusText(msg) 2114 except :2115 except Exception as exc: 2115 2116 msg = "guiframe: could not get latest application" 2116 msg += " version number\n %s" % sys.exc_value2117 msg += " version number\n %s" % exc 2117 2118 logger.error(msg) 2118 2119 if not standalone: … … 2154 2155 # S King, Sep 2018 2155 2156 2156 from documentation_window import DocumentationWindow2157 from .documentation_window import DocumentationWindow 2157 2158 _TreeLocation = "user/release.html" 2158 2159 DocumentationWindow(self, -1, _TreeLocation, "", … … 2170 2171 # original 2.x tutorial. 2171 2172 # Code below, implemented from 4.2.0, redirects 2172 # action to the Tutorials page of the help 2173 # action to the Tutorials page of the help 2173 2174 # documentation to give access to all available 2174 2175 # tutorials 2175 2176 # S King, Sep 2018 2176 2177 2177 from documentation_window import DocumentationWindow2178 from .documentation_window import DocumentationWindow 2178 2179 _TreeLocation = "user/tutorial.html" 2179 2180 DocumentationWindow(self, -1, _TreeLocation, "", … … 2190 2191 # Running SasView "in-place" using run.py means the docs will be in a 2191 2192 # different place than they would otherwise. 2192 from documentation_window import DocumentationWindow2193 from .documentation_window import DocumentationWindow 2193 2194 _TreeLocation = "user/user.html" 2194 2195 DocumentationWindow(self, -1, _TreeLocation, "", … … 2238 2239 if (style == GUIFRAME.MANAGER_ON) \ 2239 2240 and self.panels[item] == self._data_panel: 2240 if 'data_panel' in self.panels .keys():2241 if 'data_panel' in self.panels: 2241 2242 frame = self.panels['data_panel'].get_frame() 2242 2243 if frame is None: … … 2290 2291 # set data in the data panel 2291 2292 if self._data_panel is not None: 2292 data_state = self._data_manager.get_data_state( data_list.keys())2293 data_state = self._data_manager.get_data_state(list(data_list.keys())) 2293 2294 self._data_panel.load_data_list(data_state) 2294 2295 # if the data panel is shown wait for the user to press a button … … 2302 2303 else: 2303 2304 # automatically send that to the current perspective 2304 self.set_data(data_id= data_list.keys())2305 self.set_data(data_id=list(data_list.keys())) 2305 2306 2306 2307 def set_data(self, data_id, theory_id=None): … … 2310 2311 list_data, _ = self._data_manager.get_by_id(data_id) 2311 2312 if self._current_perspective is not None: 2312 self._current_perspective.set_data(list _data.values())2313 self._current_perspective.set_data(list(list_data.values())) 2313 2314 2314 2315 else: … … 2322 2323 if self._current_perspective is not None: 2323 2324 try: 2324 self._current_perspective.set_theory(list _theory.values())2325 except :2326 msg = "Guiframe set_theory: \n" + str( sys.exc_value)2325 self._current_perspective.set_theory(list(list_theory.values())) 2326 except Exception as exc: 2327 msg = "Guiframe set_theory: \n" + str(exc) 2327 2328 logger.info(msg) 2328 2329 wx.PostEvent(self, StatusEvent(status=msg, info="error")) … … 2338 2339 data_list, _ = self._data_manager.get_by_id(data_id) 2339 2340 _, temp_list_theory = self._data_manager.get_by_id(theory_id) 2340 total_plot_list = data_list.values()2341 total_plot_list = list(data_list.values()) 2341 2342 for item in temp_list_theory.values(): 2342 2343 theory_data, theory_state = item … … 2387 2388 data_list, _ = self._data_manager.get_by_id(data_id) 2388 2389 _, temp_list_theory = self._data_manager.get_by_id(theory_id) 2389 total_plot_list = data_list.values()2390 total_plot_list = list(data_list.values()) 2390 2391 for item in temp_list_theory.values(): 2391 2392 theory_data, theory_state = item … … 2410 2411 group_id=("res" + str(id)), 2411 2412 action='remove')) 2412 except :2413 logger.error( sys.exc_value)2413 except Exception as exc: 2414 logger.error(exc) 2414 2415 2415 2416 def save_data1d(self, data, fname): … … 2516 2517 wx.PostEvent(self, StatusEvent(status=msg, 2517 2518 info="error")) 2518 raise ValueError , msg2519 raise ValueError(msg) 2519 2520 # text = str(data) 2520 2521 text = data.__str__() … … 2551 2552 dy_val, 2552 2553 dx_val) 2553 from pdfview import TextFrame2554 from .pdfview import TextFrame 2554 2555 frame = TextFrame(None, -1, "Data Info: %s" % data.name, text) 2555 2556 # put icon … … 2635 2636 break 2636 2637 2637 from pdfview import TextFrame2638 from .pdfview import TextFrame 2638 2639 frame = TextFrame(None, -1, "Data Info: %s" % data.name, text) 2639 2640 # put icon … … 2702 2703 check = "Theory1D" 2703 2704 is_theory = len(self.panel_on_focus.plots) <= 1 and \ 2704 self.panel_on_focus.plots.values()[0].__class__.__name__ == check2705 list(self.panel_on_focus.plots.values())[0].__class__.__name__ == check 2705 2706 2706 2707 is_data2d = hasattr(new_plot, 'data') … … 3218 3219 else: 3219 3220 self.frame.Show() 3220 except :3221 except Exception as exc: 3221 3222 if self.s_screen is not None: 3222 3223 self.s_screen.Close() 3223 3224 msg = "Cannot display splash screen\n" 3224 msg += str( sys.exc_value)3225 msg += str(exc) 3225 3226 logger.error(msg) 3226 3227 self.frame.Show() … … 3277 3278 if os.path.isfile(file_path): 3278 3279 os.remove(file_path) 3279 except :3280 except Exception as exc: 3280 3281 logger.error("gui_manager.clean_plugin_models:\n %s" 3281 % sys.exc_value)3282 % exc) 3282 3283 3283 3284 def set_manager(self, manager): … … 3372 3373 path=SPLASH_SCREEN_PATH): 3373 3374 """Displays the splash screen. It will exactly cover the main frame.""" 3375 try: 3376 from wx.adv import SplashScreen, SPLASH_TIMEOUT, SPLASH_CENTRE_ON_SCREEN 3377 except ImportError: 3378 # CRUFT: wx 4 moved SplashScreen from wx to wx.adv 3379 from wx import SplashScreen, SPLASH_TIMEOUT, SPLASH_CENTRE_ON_SCREEN 3374 3380 3375 3381 # Prepare the picture. On a 2GHz intel cpu, this takes about a second. … … 3388 3394 # Note that on Linux, the timeout appears to occur immediately in which 3389 3395 # case the splash screen disappears upon entering the event loop. 3390 s_screen = wx.SplashScreen(bitmap=bm,3391 splashStyle=(wx.SPLASH_TIMEOUT |3392 wx.SPLASH_CENTRE_ON_SCREEN),3393 3394 3395 3396 3397 3398 3396 s_screen = SplashScreen(bitmap=bm, 3397 splashStyle=(SPLASH_TIMEOUT | 3398 SPLASH_CENTRE_ON_SCREEN), 3399 style=(wx.SIMPLE_BORDER | 3400 wx.FRAME_NO_TASKBAR | 3401 wx.FRAME_FLOAT_ON_PARENT), 3402 milliseconds=SS_MAX_DISPLAY_TIME, 3403 parent=parent, 3404 id=wx.ID_ANY) 3399 3405 from sas.sasgui.guiframe.gui_statusbar import SPageStatusbar 3400 3406 statusBar = SPageStatusbar(s_screen) -
src/sas/sasgui/guiframe/gui_statusbar.py
r463e7ffc r5251ec6 86 86 wx.ART_TOOLBAR) 87 87 self.msg_txt.Newline() 88 self.msg_txt.WriteBitmap(icon_bmp) 88 # wx 3 has WriteImage and WriteBitmap; not sure if there 89 # is any difference between them. wx 4 has only WriteImage. 90 self.msg_txt.WriteImage(icon_bmp) 89 91 self.msg_txt.BeginTextColour(color) 90 92 self.msg_txt.WriteText("\t") -
src/sas/sasgui/guiframe/gui_style.py
ra1b8fee r5251ec6 58 58 DRAG_ID_PATH = os.path.join(PATH, 'drag_hand.png') 59 59 RESET_ID_PATH = os.path.join(PATH, 'reset.png') 60 PREVIEW_ID_PATH = os.path.join(PATH, 'report.png') 60 REPORT_ID_PATH = os.path.join(PATH, 'report.png') 61 PREVIEW_ID_PATH = os.path.join(PATH, 'preview.png') 61 62 PRINT_ID_PATH = os.path.join(PATH, 'printer.png') 62 63 HIDE_ID_PATH = os.path.join(PATH, 'hide.png') 63 64 64 65 SAVE_ICON = wx.Image(os.path.join(PATH, 'save.png')) 66 UNDO_ICON = wx.Image(os.path.join(PATH, 'undo.png')) 67 REDO_ICON = wx.Image(os.path.join(PATH, 'redo.png')) 68 COPY_ICON = wx.Image(os.path.join(PATH, 'copy.png')) 69 PASTE_ICON = wx.Image(os.path.join(PATH, 'paste.png')) 70 BOOKMARK_ICON = wx.Image(os.path.join(PATH, 'bookmark.png')) 71 ZOOM_IN_ICON = wx.Image(os.path.join(PATH, 'zoom_in.png')) 72 ZOOM_OUT_ICON = wx.Image(os.path.join(PATH, 'zoom_out.png')) 73 ZOOM_ICON = wx.Image(os.path.join(PATH, 'search_pan.png')) 74 DRAG_ICON = wx.Image(os.path.join(PATH, 'drag_hand.png')) 75 RESET_ICON = wx.Image(os.path.join(PATH, 'reset.png')) 76 REPORT_ICON = wx.Image(os.path.join(PATH, 'report.png')) 77 PREVIEW_ICON = wx.Image(os.path.join(PATH, 'preview.png')) 78 PRINT_ICON = wx.Image(os.path.join(PATH, 'printer.png')) 79 HIDE_ICON = wx.Image(os.path.join(PATH, 'hide.png')) 65 # Note: wx 4 requires that the app be defined before 66 # the images are loaded, so they can't be processed 67 # at module load time. Instead, need to load icons 68 # when the app is created. 69 @classmethod 70 def load_icons(cls): 71 cls.SAVE_ICON = wx.Image(cls.SAVE_ICON_PATH) 72 cls.UNDO_ICON = wx.Image(cls.UNDO_ICON_PATH) 73 cls.REDO_ICON = wx.Image(cls.REDO_ICON_PATH) 74 cls.COPY_ICON = wx.Image(cls.COPY_ICON_PATH) 75 cls.PASTE_ICON = wx.Image(cls.PASTE_ICON_PATH) 76 cls.BOOKMARK_ICON = wx.Image(cls.BOOKMARK_ICON_PATH) 77 cls.ZOOM_IN_ICON = wx.Image(cls.ZOOM_IN_ID_PATH) 78 cls.ZOOM_OUT_ICON = wx.Image(cls.ZOOM_OUT_ID_PATH) 79 cls.ZOOM_ICON = wx.Image(cls.ZOOM_ID_PATH) 80 cls.DRAG_ICON = wx.Image(cls.DRAG_ID_PATH) 81 cls.RESET_ICON = wx.Image(cls.RESET_ID_PATH) 82 cls.REPORT_ICON = wx.Image(cls.REPORT_ID_PATH) 83 cls.PREVIEW_ICON = wx.Image(cls.PREVIEW_ID_PATH) 84 cls.PRINT_ICON = wx.Image(cls.PRINT_ID_PATH) 85 cls.HIDE_ICON = wx.Image(cls.HIDE_ID_PATH) 80 86 81 87 if __name__ == "__main__": -
src/sas/sasgui/guiframe/local_perspectives/data_loader/data_loader.py
r9c7e2b8 r5251ec6 70 70 cards.remove(item) 71 71 wlist = '|'.join(cards) 72 style = wx. OPEN | wx.FD_MULTIPLE72 style = wx.FD_OPEN | wx.FD_MULTIPLE 73 73 dlg = wx.FileDialog(self.parent, 74 74 "Choose a file", … … 196 196 error_message) 197 197 if data_error: 198 if basename in file_errors .keys():198 if basename in file_errors: 199 199 file_errors[basename] += [error_message] 200 200 else: … … 219 219 if len(file_errors) > 0: 220 220 error_message = "" 221 for filename, error_array in file_errors.ite ritems():221 for filename, error_array in file_errors.items(): 222 222 error_message += "The following issues were found whilst " 223 223 error_message += "loading {}:\n".format(filename) -
src/sas/sasgui/guiframe/local_perspectives/data_loader/load_thread.py
r959eb01 r5251ec6 72 72 if self.updatefn is not None: 73 73 self.updatefn(output=output, message=message) 74 except :74 except Exception as exc: 75 75 error_message = "Error while loading: %s\n" % str(path) 76 error_message += str( sys.exc_value) + "\n"76 error_message += str(exc) + "\n" 77 77 self.updatefn(output=output, message=error_message) 78 78 -
src/sas/sasgui/guiframe/local_perspectives/plotting/AnnulusSlicer.py
r7432acb r5251ec6 7 7 8 8 import math 9 # from copy import deepcopy 10 9 11 import wx 10 # from copy import deepcopy 11 # Debug printout 12 12 13 from sas.sasgui.guiframe.events import NewPlotEvent 13 14 from sas.sasgui.guiframe.events import StatusEvent 14 15 from sas.sasgui.guiframe.events import SlicerParameterEvent 15 16 from sas.sasgui.guiframe.events import EVT_SLICER_PARS 16 from BaseInteractor import _BaseInteractor17 17 from sas.sasgui.guiframe.dataFitting import Data1D 18 19 from .BaseInteractor import _BaseInteractor 18 20 19 21 class AnnulusInteractor(_BaseInteractor): -
src/sas/sasgui/guiframe/local_perspectives/plotting/Arc.py
r7432acb r5251ec6 4 4 import math 5 5 6 from BaseInteractor import _BaseInteractor7 6 from sas.sasgui.guiframe.events import SlicerParameterEvent 7 8 from .BaseInteractor import _BaseInteractor 8 9 9 10 class ArcInteractor(_BaseInteractor): -
src/sas/sasgui/guiframe/local_perspectives/plotting/AzimutSlicer.py
rd85c194 r5251ec6 5 5 # 6 6 import math 7 7 8 import wx 8 from BaseInteractor import _BaseInteractor 9 9 10 from sas.sasgui.guiframe.events import NewPlotEvent 10 11 from sas.sasgui.guiframe.events import EVT_SLICER_PARS 12 13 from .BaseInteractor import _BaseInteractor 11 14 12 15 class SectorInteractor(_BaseInteractor): … … 29 32 30 33 # Inner circle 31 from Arc import ArcInteractor34 from .Arc import ArcInteractor 32 35 self.inner_circle = ArcInteractor(self, self.base.subplot, 33 36 zorder=zorder, … … 43 46 self.outer_circle.qmax = self.qmax * 1.2 44 47 # self.outer_circle.set_cursor(self.base.qmax/1.8, 0) 45 from Edge import RadiusInteractor48 from .Edge import RadiusInteractor 46 49 self.right_edge = RadiusInteractor(self, self.base.subplot, 47 50 zorder=zorder + 1, -
src/sas/sasgui/guiframe/local_perspectives/plotting/Edge.py
r7432acb r5251ec6 1 1 import math 2 from BaseInteractor import _BaseInteractor 2 3 from .BaseInteractor import _BaseInteractor 3 4 4 5 -
src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter1D.py
r2469df7 r5251ec6 11 11 12 12 13 import wx14 13 import sys 15 14 import math 15 import logging 16 17 import wx 16 18 import numpy as np 17 import logging 19 18 20 from sas.sasgui.plottools.PlotPanel import PlotPanel 19 21 from sas.sasgui.guiframe.events import StatusEvent … … 22 24 from sas.sasgui.guiframe.panel_base import PanelBase 23 25 from sas.sasgui.guiframe.gui_style import GUIFRAME_ICON 24 from appearanceDialog import appearanceDialog 25 from graphAppearance import graphAppearance 26 27 from .appearanceDialog import appearanceDialog 28 from .graphAppearance import graphAppearance 26 29 27 30 logger = logging.getLogger(__name__) … … 36 39 def find_key(dic, val): 37 40 """return the key of dictionary dic given the value""" 38 return [k for k, v in dic.ite ritems() if v == val][0]41 return [k for k, v in dic.items() if v == val][0] 39 42 40 43 class ModelPanel1D(PlotPanel, PanelBase): … … 220 223 if hasattr(event, 'is_corfunc'): 221 224 self.is_corfunc = event.is_corfunc 222 if event.id in self.plots .keys():225 if event.id in self.plots: 223 226 ctrl = event.ctrl 224 227 self.cursor_id = event.id … … 243 246 if position is not None and not self.is_corfunc: 244 247 wx.PostEvent(self.parent, StatusEvent(status=position)) 245 except :246 logger.error( sys.exc_value)248 except Exception as exc: 249 logger.error(exc) 247 250 if not event.leftdown: 248 251 # text event … … 256 259 if is_moved: 257 260 self.canvas.draw() 258 except :259 logger.error( sys.exc_value)261 except Exception as exc: 262 logger.error(exc) 260 263 event.Skip() 261 264 return … … 410 413 self.canvas.draw() 411 414 self.q_ctrl[vl_ind].SetValue(str(pos_x)) 412 except :413 logger.error( sys.exc_value)415 except Exception as exc: 416 logger.error(exc) 414 417 415 418 def set_resizing(self, resizing=False): … … 431 434 Remove data from plot 432 435 """ 433 if id in self.plots .keys():436 if id in self.plots: 434 437 data = self.plots[id] 435 438 self.graph.delete(data) … … 437 440 data_list, theory_list = data_manager.get_by_id(id_list=[id]) 438 441 439 if id in data_list .keys():442 if id in data_list: 440 443 data = data_list[id] 441 if id in theory_list .keys():444 if id in theory_list: 442 445 data = theory_list[id] 443 446 … … 457 460 if data.__class__.__name__ == 'Data2D': 458 461 return 459 plot_keys = self.plots.keys()462 plot_keys = list(self.plots.keys()) 460 463 if data.id in plot_keys: 461 464 # Recover panel prop.s … … 476 479 try: 477 480 self._onEVT_FUNC_PROPERTY() 478 except Exception ,exc:481 except Exception as exc: 479 482 wx.PostEvent(self.parent, 480 483 StatusEvent(status="Plotting Error: %s" % str(exc), info="error")) … … 493 496 # MAC: forcing to plot 2D avg 494 497 self.canvas._onDrawIdle() 495 except Exception ,exc:498 except Exception as exc: 496 499 wx.PostEvent(self.parent, StatusEvent(status=\ 497 500 "Plotting Error: %s" % str(exc), info="error")) … … 567 570 self.set_selected_from_menu(menu, event_id) 568 571 ## Check if there is a selected graph to remove 569 if self.graph.selected_plottable in self.plots .keys():572 if self.graph.selected_plottable in self.plots: 570 573 graph_id = self.graph.selected_plottable 571 574 self.remove_data_by_id(graph_id) … … 603 606 plot_menu = wx.Menu() 604 607 if self.graph.selected_plottable: 605 if not self.graph.selected_plottable in self.plots .keys():608 if not self.graph.selected_plottable in self.plots: 606 609 continue 607 610 if plot != self.plots[self.graph.selected_plottable]: … … 623 626 plot_menu.Append(wx_id, item[0], name) 624 627 wx.EVT_MENU(self, wx_id, item[2]) 625 except :628 except Exception as exc: 626 629 msg = "ModelPanel1D.onContextMenu: " 627 msg += "bad menu item %s" % sys.exc_value630 msg += "bad menu item %s" % exc 628 631 wx.PostEvent(self.parent, StatusEvent(status=msg)) 629 632 plot_menu.AppendSeparator() -
src/sas/sasgui/guiframe/local_perspectives/plotting/Plotter2D.py
r3e5648b r5251ec6 11 11 12 12 13 import wx14 13 import sys 15 14 import math 15 import logging 16 17 import wx 16 18 import numpy as np 17 import logging 19 from matplotlib.font_manager import FontProperties 20 18 21 from sas.sasgui.plottools.PlotPanel import PlotPanel 19 22 from sas.sasgui.plottools.plottables import Graph … … 24 27 from sas.sasgui.guiframe.events import SlicerEvent 25 28 from sas.sasgui.guiframe.utils import PanelMenu 26 from sas.sasgui.guiframe.local_perspectives.plotting.binder import BindArtist 27 from Plotter1D import ModelPanel1D 29 from sas.sasgui.guiframe.local_perspectives.plotting.binder import BindArtist 28 30 from sas.sasgui.plottools.toolbar import NavigationToolBar 29 from matplotlib.font_manager import FontProperties 30 from graphAppearance import graphAppearance 31 32 from .Plotter1D import ModelPanel1D 33 from .graphAppearance import graphAppearance 34 31 35 (InternalEvent, EVT_INTERNAL) = wx.lib.newevent.NewEvent() 32 36 … … 41 45 def find_key(dic, val): 42 46 """return the key of dictionary dic given the value""" 43 return [k for k, v in dic.ite ritems() if v == val][0]47 return [k for k, v in dic.items() if v == val][0] 44 48 45 49 … … 200 204 ## Update self.data2d with the current plot 201 205 self.data2D = data 202 if data.id in self.plots .keys():206 if data.id in self.plots: 203 207 #replace 204 208 xlo, xhi = self.subplot.get_xlim() … … 326 330 slicerpop.Append(wx_id, item[0], item[1]) 327 331 wx.EVT_MENU(self, wx_id, item[2]) 328 except :332 except Exception as exc: 329 333 msg = "ModelPanel1D.onContextMenu: " 330 msg += "bad menu item %s" % sys.exc_value334 msg += "bad menu item %s" % exc 331 335 wx.PostEvent(self.parent, StatusEvent(status=msg)) 332 336 slicerpop.AppendSeparator() … … 447 451 448 452 """ 449 import detector_dialog453 from . import detector_dialog 450 454 dialog = detector_dialog.DetectorDialog(self, -1, base=self.parent, 451 455 reset_zmin_ctl=self.default_zmin_ctl, … … 630 634 """ 631 635 if self.slicer is not None: 632 from parameters_panel_slicer import SlicerParameterPanel636 from .parameters_panel_slicer import SlicerParameterPanel 633 637 dialog = SlicerParameterPanel(self, -1, "Slicer Parameters") 634 638 dialog.set_slicer(self.slicer.__class__.__name__, … … 641 645 Perform sector averaging on Q and draw sector slicer 642 646 """ 643 from SectorSlicer import SectorInteractor647 from .SectorSlicer import SectorInteractor 644 648 self.onClearSlicer(event) 645 649 wx.PostEvent(self, InternalEvent(slicer=SectorInteractor)) … … 649 653 Perform sector averaging on Phi and draw annulus slicer 650 654 """ 651 from AnnulusSlicer import AnnulusInteractor655 from .AnnulusSlicer import AnnulusInteractor 652 656 self.onClearSlicer(event) 653 657 wx.PostEvent(self, InternalEvent(slicer=AnnulusInteractor)) … … 657 661 """ 658 662 from sas.sasgui.guiframe.gui_manager import MDIFrame 659 from boxSum import BoxSum663 from .boxSum import BoxSum 660 664 self.onClearSlicer(event) 661 665 self.slicer_z += 1 … … 668 672 params = self.slicer.get_params() 669 673 ## Create a new panel to display results of summation of Data2D 670 from parameters_panel_boxsum import SlicerPanel674 from .parameters_panel_boxsum import SlicerPanel 671 675 win = MDIFrame(self.parent, None, 'None', (100, 200)) 672 676 new_panel = SlicerPanel(parent=win, id=-1, … … 699 703 :param event: wx.menu event 700 704 """ 701 from boxSlicer import BoxInteractorX705 from .boxSlicer import BoxInteractorX 702 706 self.onClearSlicer(event) 703 707 wx.PostEvent(self, InternalEvent(slicer=BoxInteractorX)) … … 711 715 712 716 """ 713 from boxSlicer import BoxInteractorY717 from .boxSlicer import BoxInteractorY 714 718 self.onClearSlicer(event) 715 719 wx.PostEvent(self, InternalEvent(slicer=BoxInteractorY)) -
src/sas/sasgui/guiframe/local_perspectives/plotting/SectorSlicer.py
r8de66b6 r5251ec6 3 3 """ 4 4 import math 5 5 6 import wx 6 from BaseInteractor import _BaseInteractor 7 7 8 from sas.sasgui.guiframe.events import NewPlotEvent 8 9 from sas.sasgui.guiframe.events import StatusEvent … … 10 11 from sas.sasgui.guiframe.events import EVT_SLICER_PARS 11 12 from sas.sasgui.guiframe.dataFitting import Data1D 13 14 from .BaseInteractor import _BaseInteractor 12 15 13 16 … … 238 241 msg = "Phi left and phi right are different" 239 242 msg += " %f, %f" % (self.left_line.phi, self.right_line.phi) 240 raise ValueError , msg243 raise ValueError(msg) 241 244 params["Phi [deg]"] = self.main_line.theta * 180 / math.pi 242 245 params["Delta_Phi [deg]"] = math.fabs(self.left_line.phi * 180 / math.pi) -
src/sas/sasgui/guiframe/local_perspectives/plotting/appearanceDialog.py
rd85c194 r5251ec6 153 153 Populate Symbols 154 154 """ 155 self.sorted_symbo_labels = sorted(self.symbo_labels.ite ritems(),155 self.sorted_symbo_labels = sorted(self.symbo_labels.items(), 156 156 key=operator.itemgetter(1)) 157 157 self.sorted_sym_dic = {} … … 166 166 Populate Colors 167 167 """ 168 sortedcolor_labels = sorted(self.color_labels.ite ritems(),168 sortedcolor_labels = sorted(self.color_labels.items(), 169 169 key=operator.itemgetter(1)) 170 170 for color in sortedcolor_labels: … … 197 197 Find key 198 198 """ 199 return [k for k, v in dic.ite ritems() if v == val][0]199 return [k for k, v in dic.items() if v == val][0] 200 200 201 201 def get_current_values(self): -
src/sas/sasgui/guiframe/local_perspectives/plotting/binder.py
r20fa5fe r5251ec6 2 2 Extension to MPL to support the binding of artists to key/mouse events. 3 3 """ 4 from __future__ import print_function 5 6 import sys 4 7 import logging 5 import sys6 8 7 9 logger = logging.getLogger(__name__) … … 16 18 artist = None 17 19 prop = {} 20 18 21 def __init__(self, artist=None, prop={}): 19 22 self.artist, self.prop = artist, self.prop … … 25 28 return self.artist is not other.artist 26 29 27 def __ nonzero__(self):30 def __bool__(self): 28 31 return self.artist is not None 32 33 __nonzero__ = __bool__ 34 29 35 30 36 class BindArtist(object): 31 37 """ 32 Track keyboard modifiers for events. 33 TODO: Move keyboard modifier support into the backend. We cannot 34 TODO: properly support it from outside the windowing system since there 35 TODO: is no way to recognized whether shift is held down when the mouse 36 TODO: first clicks on the the application window. 38 Track keyboard modifiers for events. 37 39 """ 40 # TODO: Move keyboard modifier support into the backend. We cannot 41 # TODO: properly support it from outside the windowing system since there 42 # TODO: is no way to recognized whether shift is held down when the mouse 43 # TODO: first clicks on the the application window. 38 44 control, shift, alt, meta = False, False, False, False 39 45 … … 46 52 'scroll', 'key', 'keyup'] 47 53 # TODO: Need our own event structure 54 48 55 def __init__(self, figure): 49 56 canvas = figure.canvas 57 50 58 # Link to keyboard/mouse 51 59 try: … … 59 67 ] 60 68 except: 61 # print "bypassing scroll_event: wrong matplotlib version"69 logger.warn("bypassing scroll_event: wrong matplotlib version") 62 70 self._connections = [ 63 71 canvas.mpl_connect('motion_notify_event', self._onMotion), … … 67 75 canvas.mpl_connect('key_release_event', self._onKeyRelease), 68 76 ] 77 69 78 # Turn off picker if it hasn't already been done 70 79 try: 71 80 canvas.mpl_disconnect(canvas.button_pick_id) 72 81 canvas.mpl_disconnect(canvas.scroll_pick_id) 73 except: 74 logger.error(sys.exc_value) 82 except Exception as exc: 83 logger.error(exc) 84 85 self._current = None 86 self._actions = {} 75 87 self.canvas = canvas 76 88 self.figure = figure … … 83 95 84 96 Use clearall() to reset all connections. 85 86 97 """ 87 98 for h in artists: … … 108 119 for action in self.events: 109 120 self._actions[action] = {} 121 110 122 # Need activity state 111 123 self._artists = [] … … 121 133 for cid in self._connections: 122 134 self.canvas.mpl_disconnect(cid) 123 except :124 pass135 except Exception as exc: 136 logger.error("Error disconnection canvas: %s" % exc) 125 137 self._connections = [] 126 138 … … 169 181 sure it applies. E.g., the callback for 'press' might be: 170 182 if event.button == 1 and event.shift: process Shift-click 171 172 :TODO: Only receive events with the correct modifiers (e.g., S-click, 173 :TODO: or *-click for any modifiers). 174 :TODO: Only receive button events for the correct button (e.g., click1 175 :TODO: release3, or dclick* for any button) 176 :TODO: Support virtual artist, so that and artist can be flagged as 177 :TODO: having a tag list and receive the correct events 178 :TODO: Support virtual events for binding to button-3 vs shift button-1 179 :TODO: without changing callback code 180 :TODO: Attach multiple callbacks to the same event? 181 :TODO: Clean up interaction with toolbar modes 182 :TODO: push/pushclear/pop context so that binding changes 183 for the duration 184 :TODO: e.g., to support ? context sensitive help 185 186 """ 183 """ 184 #TODO: Only receive events with the correct modifiers (e.g., S-click, 185 #TODO: or *-click for any modifiers). 186 #TODO: Only receive button events for the correct button (e.g., click1 187 #TODO: release3, or dclick* for any button) 188 #TODO: Support virtual artist, so that and artist can be flagged as 189 #TODO: having a tag list and receive the correct events 190 #TODO: Support virtual events for binding to button-3 vs shift button-1 191 #TODO: without changing callback code 192 #TODO: Attach multiple callbacks to the same event? 193 #TODO: Clean up interaction with toolbar modes 194 #TODO: push/pushclear/pop context so that binding changes for the duration 195 #TODO: e.g., to support ? context sensitive help 196 187 197 # Check that the trigger is valid 188 198 if trigger not in self._actions: 189 raise ValueError, "%s invalid --- valid triggers are %s" \ 190 % (trigger, ", ".join(self.events)) 199 raise ValueError("%s invalid --- valid triggers are %s" 200 % (trigger, ", ".join(self.events))) 201 191 202 # Register the trigger callback 192 203 self._actions[trigger][artist] = action 193 # print "==> added",artist,[artist],"to",trigger,":", 194 # self._actions[trigger].keys() 204 195 205 # Maintain a list of all artists 196 206 if artist not in self._artists: … … 203 213 """ 204 214 if action not in self.events: 205 raise ValueError, "Trigger expects " + ", ".join(self.events) 215 raise ValueError("Trigger expects " + ", ".join(self.events)) 216 206 217 # Tag the event with modifiers 207 218 for mod in ('alt', 'control', 'shift', 'meta'): … … 210 221 setattr(ev, 'action', action) 211 222 setattr(ev, 'prop', {}) 223 212 224 # Fallback scheme. If the event does not return false, pass to parent. 213 225 processed = False … … 233 245 """ 234 246 # TODO: sort by zorder of axes then by zorder within axes 235 self._artists.sort(cmp=lambda x, y: cmp(y.zorder, x.zorder)) 236 # print "search"," ".join([str(h) for h in self._artists]) 247 self._artists.sort(key=lambda x: x.zorder, reverse=True) 237 248 found = Selection() 238 # print "searching in",self._artists239 249 for artist in self._artists: 240 250 # TODO: should contains() return false if invisible? … … 250 260 found.artist, found.prop = artist, prop 251 261 break 252 # print "found",found.artist253 262 254 263 # TODO: how to check if prop is equal? … … 257 266 self.trigger(found, 'enter', event) 258 267 self._current = found 268 259 269 return found 260 270 … … 274 284 275 285 transform = self._hasclick.artist.get_transform() 276 # 286 #x,y = event.xdata,event.ydata 277 287 x, y = event.x, event.y 278 288 try: 279 289 x, y = transform.inverted().transform_point((x, y)) 280 281 except: 290 except: # CRUFT: matplotlib-0.91 support 282 291 x, y = transform.inverse_xy_tup((x, y)) 292 283 293 event.xdata, event.ydata = x, y 284 294 self.trigger(self._hasclick, 'drag', event) 285 295 else: 286 296 found = self._find_current(event) 287 # print "found",found.artist288 297 self.trigger(found, 'motion', event) 289 298 … … 296 305 # Check for double-click 297 306 event_time = time.time() 298 # print event_time,self._last_time,self.dclick_threshhold299 # print (event_time > self._last_time + self.dclick_threshhold)300 # print event.button,self._last_button301 307 if (event.button != self._last_button) or \ 302 308 (event_time > self._last_time + self.dclick_threshhold): … … 381 387 setattr(self, event.key, False) 382 388 return 389 383 390 if self._haskey: 384 391 self.trigger(self._haskey, 'keyup', event) … … 391 398 found = self._find_current(event) 392 399 self.trigger(found, 'scroll', event) 393 -
src/sas/sasgui/guiframe/local_perspectives/plotting/boxMask.py
r7432acb r5251ec6 1 1 import math 2 from BaseInteractor import _BaseInteractor3 from boxSum import PointInteractor4 from boxSum import VerticalDoubleLine5 from boxSum import HorizontalDoubleLine2 from .BaseInteractor import _BaseInteractor 3 from .boxSum import PointInteractor 4 from .boxSum import VerticalDoubleLine 5 from .boxSum import HorizontalDoubleLine 6 6 7 7 -
src/sas/sasgui/guiframe/local_perspectives/plotting/boxSlicer.py
r20fa5fe r5251ec6 1 import math 2 1 3 import wx 2 import math3 4 import numpy as np 5 4 6 from sas.sasgui.guiframe.events import NewPlotEvent 5 7 from sas.sasgui.guiframe.events import StatusEvent 6 8 from sas.sasgui.guiframe.events import SlicerParameterEvent 7 9 from sas.sasgui.guiframe.events import EVT_SLICER_PARS 8 from BaseInteractor import _BaseInteractor9 10 from sas.sasgui.guiframe.dataFitting import Data1D 11 12 from .BaseInteractor import _BaseInteractor 10 13 11 14 … … 152 155 if new_slab is None: 153 156 msg = "post data:cannot average , averager is empty" 154 raise ValueError , msg157 raise ValueError(msg) 155 158 self.averager = new_slab 156 159 if self.direction == "X": … … 168 171 else: 169 172 msg = "post data:no Box Average direction was supplied" 170 raise ValueError , msg173 raise ValueError(msg) 171 174 # # Average data2D given Qx or Qy 172 175 box = self.averager(x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, -
src/sas/sasgui/guiframe/local_perspectives/plotting/boxSum.py
r7432acb r5251ec6 4 4 """ 5 5 import math 6 6 7 import wx 7 from BaseInteractor import _BaseInteractor 8 8 9 from sas.sasgui.guiframe.events import SlicerParamUpdateEvent 9 10 from sas.sasgui.guiframe.events import EVT_SLICER_PARS 10 11 from sas.sasgui.guiframe.events import StatusEvent 12 13 from .BaseInteractor import _BaseInteractor 11 14 12 15 -
src/sas/sasgui/guiframe/local_perspectives/plotting/detector_dialog.py
r7432acb r5251ec6 99 99 self.cmap_selector.SetStringSelection("jet") 100 100 self._on_select_cmap(event=None) 101 except :102 msg = "error occurs while resetting Detector: %s" % sys.exc_value101 except Exception as exc: 102 msg = "error occurs while resetting Detector: %s" % exc 103 103 wx.PostEvent(self.parent, StatusEvent(status=msg)) 104 104 -
src/sas/sasgui/guiframe/local_perspectives/plotting/masking.py
r20fa5fe r5251ec6 18 18 19 19 # #Todo: cleaning up, improving the maskplotpanel initialization, and testing. 20 import wx21 20 import sys 22 21 import time 23 import matplotlib.cm as cm24 22 import math 25 23 import copy 24 from functools import partial 25 26 import wx 26 27 import numpy as np 28 import matplotlib.cm as cm 29 27 30 from sas.sasgui.plottools.PlotPanel import PlotPanel 28 31 from sas.sasgui.plottools.plottables import Graph 29 from binder import BindArtist30 32 from sas.sasgui.guiframe.dataFitting import Data1D, Data2D 31 from boxMask import BoxMask32 from sector_mask import SectorMask33 from AnnulusSlicer import CircularMask34 35 33 from sas.sasgui.guiframe.events import SlicerEvent 36 34 from sas.sasgui.guiframe.events import StatusEvent 37 from functools import partial 35 36 from .binder import BindArtist 37 from .boxMask import BoxMask 38 from .sector_mask import SectorMask 39 from .AnnulusSlicer import CircularMask 40 38 41 39 42 (InternalEvent, EVT_INTERNAL) = wx.lib.newevent.NewEvent() -
src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_boxsum.py
r37d461c r5251ec6 1 1 import wx 2 2 import wx.lib.newevent 3 from parameters_panel_slicer import SlicerParameterPanel 3 4 4 from sas.sasgui.guiframe.utils import format_number 5 5 from sas.sasgui.guiframe.panel_base import PanelBase … … 7 7 EVT_SLICER) 8 8 9 from .parameters_panel_slicer import SlicerParameterPanel 9 10 10 11 class SlicerPanel(wx.Panel, PanelBase): … … 64 65 n = 1 65 66 self.parameters = [] 66 keys = params.keys() 67 keys.sort() 67 keys = list(sorted(params.keys())) 68 68 for item in keys: 69 69 if not item.lower() in ["num_points", "avg", "avg_error", "sum", -
src/sas/sasgui/guiframe/local_perspectives/plotting/parameters_panel_slicer.py
ra20a255 r5251ec6 2 2 3 3 import os 4 4 5 import wx 5 6 import wx.lib.newevent 7 6 8 from sas.sascalc.dataloader.readers.cansas_reader import Reader 7 9 from sas.sasgui.guiframe.utils import format_number 8 10 from sas.sasgui.guiframe.events import EVT_SLICER_PARS, EVT_SLICER 9 11 from sas.sasgui.guiframe.events import SlicerParameterEvent, StatusEvent 10 from Plotter2D import ModelPanel2D 12 13 from .Plotter2D import ModelPanel2D 14 11 15 apply_params, EVT_APPLY_PARAMS = wx.lib.newevent.NewEvent() 12 16 save_files, EVT_AUTO_SAVE = wx.lib.newevent.NewEvent() … … 100 104 iy = 1 101 105 self.parameters = [] 102 keys = params.keys() 103 keys.sort() 106 keys = list(sorted(params.keys())) 104 107 for item in keys: 105 108 ix = 0 … … 127 130 self.bck.Add(text, (iy, ix), (1, 1), 128 131 wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15) 129 options = BINNING_OPTIONS.keys()132 options = list(BINNING_OPTIONS.keys()) 130 133 self.bin_ctl = wx.ComboBox(parent=self, choices=options) 131 134 hint_msg = "Modify the value of %s to change" % item … … 325 328 326 329 # Find desired 2D data panels 327 for key, mgr in spp.plot_panels.ite ritems():330 for key, mgr in spp.plot_panels.items(): 328 331 if mgr.graph.prop['title'] in self.data_list.CheckedStrings: 329 332 apply_to_list.append(mgr) … … 377 380 self.loaded_data = [] 378 381 # Iterate over the loaded plots and find all 2D panels 379 for key, value in self.main_window.plot_panels.ite ritems():382 for key, value in self.main_window.plot_panels.items(): 380 383 if isinstance(value, ModelPanel2D): 381 384 self.loaded_data.append(value.data2D.name) … … 453 456 454 457 # Find the correct plots to save 455 for key, plot in self.main_window.plot_panels.ite ritems():458 for key, plot in self.main_window.plot_panels.items(): 456 459 if not hasattr(plot, "data2D"): 457 460 for item in plot.plots: … … 461 464 462 465 # Save files as Text 463 for item, data1d in data_dic.ite ritems():466 for item, data1d in data_dic.items(): 464 467 base = '.'.join(item.split('.')[:-1]) 465 468 file_name = base + append + ".txt" -
src/sas/sasgui/guiframe/local_perspectives/plotting/plotting.py
r2d9526d r5251ec6 12 12 ################################################################################ 13 13 14 import wx15 14 import sys 16 15 from copy import deepcopy 16 17 import wx 18 17 19 from sas.sasgui.guiframe.events import EVT_NEW_PLOT 18 20 from sas.sasgui.guiframe.events import EVT_PLOT_QRANGE … … 23 25 from sas.sasgui.guiframe.dataFitting import Data2D 24 26 from sas.sasgui.guiframe.gui_manager import MDIFrame 27 25 28 DEFAULT_MENU_ITEM_LABEL = "No graph available" 26 29 DEFAULT_MENU_ITEM_ID = wx.NewId() … … 91 94 if event is None: 92 95 return 93 if event.id in self.plot_panels .keys():96 if event.id in self.plot_panels: 94 97 panel = self.plot_panels[event.id] 95 elif event.group_id in self.plot_panels .keys():98 elif event.group_id in self.plot_panels: 96 99 panel = self.plot_panels[event.group_id] 97 100 else: … … 102 105 if event is None: 103 106 return 104 if event.id in self.plot_panels .keys():107 if event.id in self.plot_panels: 105 108 panel = self.plot_panels[event.id] 106 elif event.group_id in self.plot_panels .keys():109 elif event.group_id in self.plot_panels: 107 110 panel = self.plot_panels[event.group_id] 108 111 else: … … 123 126 """ 124 127 125 if group_id in self.plot_panels .keys():128 if group_id in self.plot_panels: 126 129 panel = self.plot_panels[group_id] 127 130 panel.remove_data_by_id(id=id) … … 134 137 Clear and Hide all plot panels, and remove them from menu 135 138 """ 136 for group_id in self.plot_panels .keys():139 for group_id in self.plot_panels: 137 140 self.clear_panel_by_id(group_id) 138 141 self.plot_panels = {} … … 142 145 clear the graph 143 146 """ 144 if group_id in self.plot_panels .keys():147 if group_id in self.plot_panels: 145 148 panel = self.plot_panels[group_id] 146 149 for plottable in panel.graph.plottables.keys(): … … 184 187 # Create a new plot panel if none was available 185 188 if issubclass(data.__class__, Data1D): 186 from Plotter1D import ModelPanel1D189 from .Plotter1D import ModelPanel1D 187 190 ## get the data representation label of the data to plot 188 191 ## when even the user select "change scale" … … 200 203 201 204 msg = "1D Panel of group ID %s could not be created" % str(group_id) 202 raise ValueError , msg205 raise ValueError(msg) 203 206 204 207 def create_2d_panel(self, data, group_id): … … 207 210 if issubclass(data.__class__, Data2D): 208 211 ##Create a new plotpanel for 2D data 209 from Plotter2D import ModelPanel2D212 from .Plotter2D import ModelPanel2D 210 213 scale = data.scale 211 214 win = MDIFrame(self.parent, None, 'None', (200, 150)) … … 218 221 return new_panel 219 222 msg = "2D Panel of group ID %s could not be created" % str(group_id) 220 raise ValueError , msg223 raise ValueError(msg) 221 224 222 225 def update_panel(self, data, panel): … … 238 241 msg += " to panel %s\n" % str(panel.window_caption) 239 242 msg += "Please edit %s's units, labels" % str(data.name) 240 raise ValueError , msg243 raise ValueError(msg) 241 244 else: 242 245 if panel.group_id not in data.list_group_id: … … 247 250 """ 248 251 """ 249 if group_id in self.plot_panels .keys():252 if group_id in self.plot_panels: 250 253 panel = self.plot_panels[group_id] 251 254 uid = panel.uid … … 254 257 caption=panel.window_caption)) 255 258 del self.plot_panels[group_id] 256 if uid in self.parent.plot_panels .keys():259 if uid in self.parent.plot_panels: 257 260 del self.parent.plot_panels[uid] 258 261 panel.frame.Destroy() … … 280 283 for data in event.plots: 281 284 for panel in self.plot_panels.values(): 282 if data.id in panel.plots .keys():285 if data.id in panel.plots: 283 286 plot_exists = True 284 287 # Pass each panel it's own copy of the data … … 310 313 data = event.plot 311 314 group_id = data.group_id 312 if group_id in self.plot_panels .keys():315 if group_id in self.plot_panels: 313 316 if action_check: 314 317 # Check if the plot already exist. if it does, do nothing. 315 if data.id in self.plot_panels[group_id].plots .keys():318 if data.id in self.plot_panels[group_id].plots: 316 319 return 317 320 #update a panel graph … … 327 330 for p_group_id in self.plot_panels.keys(): 328 331 p_plot = self.plot_panels[p_group_id] 329 if data.id in p_plot.plots .keys():332 if data.id in p_plot.plots: 330 333 p_plot.plots[data.id] = data 331 334 self.plot_panels[group_id] = p_plot -
src/sas/sasgui/guiframe/local_perspectives/plotting/sector_mask.py
r7432acb r5251ec6 3 3 """ 4 4 import math 5 5 6 import wx 6 #from copy import deepcopy 7 from BaseInteractor import _BaseInteractor 8 from SectorSlicer import SideInteractor 9 from SectorSlicer import LineInteractor 7 10 8 from sas.sasgui.guiframe.events import SlicerParameterEvent 9 10 from .BaseInteractor import _BaseInteractor 11 from .SectorSlicer import SideInteractor 12 from .SectorSlicer import LineInteractor 11 13 12 14 class SectorMask(_BaseInteractor): … … 175 177 msg += "different %f, %f" % (self.left_line.phi, 176 178 self.right_line.phi) 177 raise ValueError , msg179 raise ValueError(msg) 178 180 params["Phi"] = self.main_line.theta 179 181 params["Delta_Phi"] = math.fabs(self.left_line.phi) -
src/sas/sasgui/guiframe/plugin_base.py
r20fa5fe r5251ec6 112 112 Load data 113 113 """ 114 raise NotImplementedError 114 raise NotImplementedError() 115 115 116 116 def load_folder(self, event): … … 118 118 Load entire folder 119 119 """ 120 raise NotImplementedError 120 raise NotImplementedError() 121 121 122 122 def set_is_active(self, active=False): … … 277 277 """ 278 278 msg = "%s plugin: does not support import theory" % str(self.sub_menu) 279 raise ValueError , msg279 raise ValueError(msg) 280 280 281 281 def on_set_state_helper(self, event): -
src/sas/sasgui/guiframe/proxy.py
r20fa5fe r5251ec6 3 3 from __future__ import print_function 4 4 5 import urllib26 5 import sys 7 6 import json … … 9 8 import re 10 9 10 try: 11 # CRUFT: python 3 uses urllib.request instead of urllib2 12 import urllib2 13 except ImportError: 14 from urllib import request as urllib2 11 15 12 16 logger = logging.getLogger(__name__) … … 50 54 this_name, this_val, this_type = winreg.EnumValue(net, i) 51 55 subkeys[this_name] = this_val 52 if 'AutoConfigURL' in subkeys .keys()and len(subkeys['AutoConfigURL']) > 0:56 if 'AutoConfigURL' in subkeys and len(subkeys['AutoConfigURL']) > 0: 53 57 pac_files.append(subkeys['AutoConfigURL']) 54 58 elif sys.platform == 'darwin': … … 61 65 # the first part is a long identifier 62 66 net_key, network = network 63 if 'ProxyAutoConfigURLString' in network['Proxies'] .keys():67 if 'ProxyAutoConfigURLString' in network['Proxies']: 64 68 pac_files.append( 65 69 network['Proxies']['ProxyAutoConfigURLString']) … … 127 131 logger.debug("Trying Direct connection to %s..."%self.url) 128 132 response = urllib2.urlopen(req, timeout=self.timeout) 129 except Exception , e:133 except Exception as exc: 130 134 logger.debug("Failed!") 131 logger.debug(e )135 logger.debug(exc) 132 136 try: 133 137 logger.debug("Trying to use system proxy if it exists...") 134 138 self._set_proxy() 135 139 response = urllib2.urlopen(req, timeout=self.timeout) 136 except Exception , e:140 except Exception as exc: 137 141 logger.debug("Failed!") 138 logger.debug(e )142 logger.debug(exc) 139 143 pac_urls = self._get_addresses_of_proxy_pac() 140 144 proxy_urls = self._parse_proxy_pac(pac_urls) … … 144 148 self._set_proxy(proxy) 145 149 response = urllib2.urlopen(req, timeout=self.timeout) 146 except Exception , e:150 except Exception as exc: 147 151 logger.debug("Failed!") 148 logger.debug(e )152 logger.debug(exc) 149 153 if response is not None: 150 154 logger.debug("The connection to %s was successful."%self.url) -
src/sas/sasgui/guiframe/report_dialog.py
rd0ce666f r5251ec6 147 147 self.Update() 148 148 return pisaStatus.err 149 except Exception :150 logger.error("Error creating pdf: %s" % sys.exc_value)149 except Exception as exc: 150 logger.error("Error creating pdf: %s" % exc) 151 151 return False -
src/sas/sasgui/guiframe/startup_configuration.py
rb963b20 r5251ec6 197 197 with open(path, 'w') as out_f: 198 198 out_f.write("#Application appearance custom configuration\n") 199 for key, item in self.return_string.ite ritems():199 for key, item in self.return_string.items(): 200 200 if (key == 'DEFAULT_PERSPECTIVE') or \ 201 201 (key == 'DEFAULT_OPEN_FOLDER' and item != None): -
src/sas/sasgui/guiframe/utils.py
r7432acb r5251ec6 208 208 self.id_list = id_list 209 209 self.index = -1 210 def next(self):210 def __next__(self): 211 211 self.index += 1 212 212 return self.id_list[self.index] 213 213 # CRUFT: python 2 uses next rather than __next__ for iterator 214 next = __next__ 215 -
src/sas/sasgui/perspectives/calculator/__init__.py
r5a405bd r5251ec6 2 2 import os 3 3 from distutils.filelist import findall 4 from calculator import *4 from .calculator import * 5 5 N_DIR = 12 6 6 def get_data_path(media): -
src/sas/sasgui/perspectives/calculator/calculator.py
r61bfd36 r5251ec6 12 12 ################################################################################ 13 13 14 import logging 15 14 16 import wx 17 15 18 from sas.sasgui.guiframe.plugin_base import PluginBase 16 19 from sas.sasgui.perspectives.calculator.data_operator import DataOperatorWindow … … 26 29 from sas.sasgui.perspectives.calculator.image_viewer import ImageView 27 30 from sas.sasgui.perspectives.calculator.pyconsole import PyConsole 28 import logging29 31 30 32 logger = logging.getLogger(__name__) -
src/sas/sasgui/perspectives/calculator/collimation_editor.py
r959eb01 r5251ec6 1 1 """ 2 2 """ 3 import wx4 3 import sys 5 4 from copy import deepcopy 5 6 import wx 7 6 8 from sas.sascalc.dataloader.loader import Loader 7 9 from sas.sascalc.dataloader.data_info import Aperture, Collimation 8 from aperture_editor import ApertureDialog9 10 10 from sas.sasgui.guiframe.utils import check_float 11 12 from .aperture_editor import ApertureDialog 13 11 14 _BOX_WIDTH = 60 12 15 -
src/sas/sasgui/perspectives/calculator/data_editor.py
r235f514 r5251ec6 7 7 from sas.sascalc.dataloader.loader import Loader 8 8 from sas.sascalc.dataloader.data_info import Data2D 9 from detector_editor import DetectorDialog10 from collimation_editor import CollimationDialog11 from console import ConsoleDialog12 9 13 10 from sas.sasgui.guiframe.events import StatusEvent 11 12 from .detector_editor import DetectorDialog 13 from .collimation_editor import CollimationDialog 14 from .console import ConsoleDialog 15 14 16 15 17 … … 397 399 if data is None: 398 400 return 399 from sample_editor import SampleDialog401 from .sample_editor import SampleDialog 400 402 dlg = SampleDialog(parent=self, sample=data.sample) 401 403 dlg.set_manager(self) … … 409 411 if data is None: 410 412 return 411 from source_editor import SourceDialog413 from .source_editor import SourceDialog 412 414 dlg = SourceDialog(parent=self, source=data.source) 413 415 dlg.set_manager(self) … … 426 428 wlist = '|'.join(cards) 427 429 428 dlg = wx.FileDialog(self, "Choose a file", location, "", wlist, wx. OPEN)430 dlg = wx.FileDialog(self, "Choose a file", location, "", wlist, wx.FD_OPEN) 429 431 if dlg.ShowModal() == wx.ID_OK: 430 432 path = dlg.GetPath() … … 527 529 try: 528 530 #Load data 529 from load_thread import DataReader531 from .load_thread import DataReader 530 532 ## If a thread is already started, stop it 531 533 if self.reader is not None and self.reader.isrunning(): … … 535 537 updatefn=None) 536 538 self.reader.queue() 537 except :538 msg = "Data Editor: %s" % (sys.exc_value)539 except Exception as exc: 540 msg = "Data Editor: %s" % exc 539 541 load_error(msg) 540 542 return -
src/sas/sasgui/perspectives/calculator/data_operator.py
r7432acb r5251ec6 202 202 else: 203 203 text = name 204 state_list = self.get_datalist().values()205 204 name_list = [] 206 for state in s tate_list:205 for state in self.get_datalist().values(): 207 206 if state.data is None: 208 207 theory_list = state.get_theory() 209 theory, _ = theory_list.values()[0]208 theory, _ = list(theory_list.values())[0] 210 209 d_name = str(theory.name) 211 210 else: … … 393 392 try: 394 393 self.output = self.make_data_out(data1, data2) 395 except :394 except Exception as exc: 396 395 self._check_newname() 397 396 self._set_textctrl_color(self.data1_cbox, 'pink') 398 397 self._set_textctrl_color(self.data2_cbox, 'pink') 399 msg = "DataOperation: %s" % sys.exc_value398 msg = "DataOperation: %s" % exc 400 399 self.send_warnings(msg, 'error') 401 400 self.output = None … … 411 410 operator = self.operator_cbox.GetClientData(pos) 412 411 try: 413 exec "output = data1 %s data2" % operator 412 output = eval("data1 %s data2" % operator, 413 {"data1": data1, "data2": data2}) 414 414 except: 415 415 raise … … 532 532 self.data2_cbox.SetClientData(pos3, val) 533 533 dnames = [] 534 ids = self._data.keys() 535 for id in ids: 534 for id in self._data.keys(): 536 535 if id is not None: 537 536 if self._data[id].data is not None: … … 539 538 else: 540 539 theory_list = self._data[id].get_theory() 541 theory, _ = theory_list.values()[0]540 theory, _ = list(theory_list.values())[0] 542 541 dnames.append(theory.name) 543 542 ind = np.argsort(dnames) 544 543 if len(ind) > 0: 545 val_list = np.array( self._data.values())[ind]544 val_list = np.array(list(self._data.values()))[ind] 546 545 for datastate in val_list: 547 546 data = datastate.data … … 588 587 self.send_warnings('') 589 588 self.data_namectr.SetBackgroundColour('white') 590 state_list = self.get_datalist().values()591 589 name = self.data_namectr.GetValue().strip() 592 590 name_list = [] 593 for state in s tate_list:591 for state in self.get_datalist().values(): 594 592 if state.data is None: 595 593 theory_list = state.get_theory() 596 theory, _ = theory_list.values()[0]594 theory, _ = list(theory_list.values())[0] 597 595 d_name = str(theory.name) 598 596 else: … … 889 887 def _onProperties(self, event): 890 888 """ 891 when clicking on Properties on context menu , 892 The Property dialog is displayed 893 The user selects a transformation for x or y value and 894 a new plot is displayed 895 """ 896 list = [] 897 list = self.graph.returnPlottable() 898 if len(list.keys()) > 0: 899 first_item = list.keys()[0] 889 When clicking on Properties on context menu, the 890 Property dialog is displayed the user selects a 891 transformation for x or y value and a new plot is displayed 892 """ 893 plottables = self.graph.returnPlottable() 894 if plottables: 895 # TODO: key order is random prior to py 3.7 896 first_item = list(plottables.keys())[0] 900 897 if first_item.x != []: 901 898 from sas.sasgui.plottools.PropertyDialog import Properties … … 929 926 and set the scale 930 927 """ 931 list = []932 list = self.graph.returnPlottable()933 928 # Changing the scale might be incompatible with 934 929 # currently displayed data (for instance, going … … 940 935 _xscale = 'linear' 941 936 _yscale = 'linear' 942 for item in list:937 for item in self.graph.returnPlottable(): 943 938 item.setLabel(self.xLabel, self.yLabel) 944 939 # control axis labels from the panel itself -
src/sas/sasgui/perspectives/calculator/density_panel.py
r7432acb r5251ec6 362 362 self.molar_mass_ctl.SetValue(str(self._format_number(molar_mass))) 363 363 self.output_ctl.SetValue(str(output)) 364 except :364 except Exception as exc: 365 365 if self.base is not None: 366 msg = "Density/Volume Calculator: %s" % (sys.exc_value)366 msg = "Density/Volume Calculator: %s" % exc 367 367 wx.PostEvent(self.base, StatusEvent(status=msg)) 368 368 if event is not None: -
src/sas/sasgui/perspectives/calculator/detector_editor.py
ra1b8fee r5251ec6 34 34 self._do_layout() 35 35 self.set_values() 36 except :37 print("error", sys.exc_value)36 except Exception as exc: 37 print("error", exc) 38 38 39 39 def _define_structure(self): -
src/sas/sasgui/perspectives/calculator/gen_scatter_panel.py
r20fa5fe r5251ec6 228 228 sizer.Add(unit_title, (iy, ix), (1, 1), \ 229 229 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 230 key_list = params.keys() 231 key_list.sort() 232 for param in key_list: 230 for param in sorted(params.keys()): 233 231 iy += 1 234 232 ix = 0 … … 341 339 ix = 0 342 340 iy = 0 343 #key_list.sort()344 341 name = wx.StaticText(self, -1, 'No. of Qx (Qy) bins: ') 345 342 sizer.Add(name, (iy, ix), (1, 1), \ … … 509 506 wildcard = '|'.join(wildcard) 510 507 dlg = wx.FileDialog(self, "Choose a file", location, 511 "", wildcard, wx. OPEN)508 "", wildcard, wx.FD_OPEN) 512 509 if dlg.ShowModal() == wx.ID_OK: 513 510 path = dlg.GetPath() … … 556 553 self.reader.queue() 557 554 #self.load_update() 558 except :555 except Exception as exc: 559 556 self.ext = None 560 557 if self.parent.parent is None: 561 558 return 562 msg = "Generic SAS Calculator: %s" % (sys.exc_value)559 msg = "Generic SAS Calculator: %s" % exc 563 560 wx.PostEvent(self.parent.parent, 564 561 StatusEvent(status=msg, type='stop')) … … 774 771 if output.pix_type == 'atom': 775 772 # Get atom names not in the list 776 a_names = [symb for symb in pix_symbol \777 if symb not in color_dic .keys()]773 a_names = [symb for symb in pix_symbol 774 if symb not in color_dic] 778 775 a_name = a_names[0] 779 776 for name in a_names: … … 898 895 cal_out.queue() 899 896 900 except :901 msg = "%s." % sys.exc_value897 except Exception as exc: 898 msg = "%s." % exc 902 899 status_type = 'stop' 903 900 self._status_info(msg, status_type) … … 1344 1341 self.sld_data.is_data = False 1345 1342 self.sld_data.filename = "Default SLD Profile" 1346 except :1347 msg = "OMF Panel: %s" % sys.exc_value1343 except Exception as exc: 1344 msg = "OMF Panel: %s" % exc 1348 1345 infor = 'Error' 1349 1346 #logger.error(msg) … … 1441 1438 raise 1442 1439 sld_key_list = self._get_slds_key_list(omfdata) 1443 # Dic is not sorted1444 key_list = [key for key in sld_key_list.keys()]1445 # Sort here1446 key_list.sort()1447 1440 is_data = self.sld_data.is_data 1448 1441 sizer = wx.GridBagSizer(2, 3) 1449 1442 ix = 0 1450 1443 iy = -1 1451 for key in key_list: 1452 value = sld_key_list[key] 1444 for key, value in sorted(sld_key_list.items()): 1453 1445 iy += 1 1454 1446 ix = 0 … … 1485 1477 ix = 0 1486 1478 iy = -1 1487 for key, value in key_list.iteritems():1479 for key, value in sorted(key_list.items()): 1488 1480 iy += 1 1489 1481 ix = 0 … … 1520 1512 ix = 0 1521 1513 iy = -1 1522 #key_list.sort() 1523 for key, value in key_list.iteritems(): 1514 for key, value in sorted(key_list.items()): 1524 1515 iy += 1 1525 1516 ix = 0 -
src/sas/sasgui/perspectives/calculator/image_viewer.py
r412e9e8b r5251ec6 95 95 if location is None: 96 96 location = os.getcwd() 97 wildcard="Images (*.bmp;*.gif;*jpeg,*jpg;*.png;*tif;*.tiff)|*bmp;\ 98 *.gif; *.jpg; *.jpeg;*png;*.png;*.tif;*.tiff|"\ 99 "Bitmap (*.bmp)|*.bmp|"\ 100 "GIF (*.gif)|*.gif|"\ 101 "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|"\ 102 "PNG (*.png)|*.png|"\ 103 "TIFF (*.tif;*.tiff)|*.tif;*tiff|"\ 104 "All Files (*.*)|*.*|" 97 wildcard="|".join(( 98 "Images (*.bmp;*.gif;*jpeg,*jpg;*.png;*tif;*.tiff)" 99 "|*bmp;*.gif;*.jpg;*.jpeg;*png;*.png;*.tif;*.tiff", 100 "Bitmap (*.bmp)|*.bmp", 101 "GIF (*.gif)|*.gif", 102 "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg", 103 "PNG (*.png)|*.png", 104 "TIFF (*.tif;*.tiff)|*.tif;*tiff", 105 "All Files (*.*)|*.*", 106 )) 105 107 106 108 dlg = wx.FileDialog(self.parent, "Image Viewer: Choose an image file", -
src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py
r7432acb r5251ec6 12 12 import sys 13 13 14 from sas.sascalc.calculator.kiessig_calculator import KiessigThicknessCalculator 14 15 from sas.sasgui.guiframe.panel_base import PanelBase 15 from sas.sascalc.calculator.kiessig_calculator import KiessigThicknessCalculator16 from calculator_widgets import OutputTextCtrl17 from calculator_widgets import InputTextCtrl18 16 from sas.sasgui.perspectives.calculator import calculator_widgets as widget 19 17 from sas.sasgui.guiframe.documentation_window import DocumentationWindow 18 from .calculator_widgets import OutputTextCtrl 19 from .calculator_widgets import InputTextCtrl 20 20 21 21 _BOX_WIDTH = 77 -
src/sas/sasgui/perspectives/calculator/model_editor.py
r9bf40e7 r5251ec6 578 578 self.base = base 579 579 self.path = path 580 self.font = wx.SystemSettings _GetFont(wx.SYS_SYSTEM_FONT)580 self.font = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT) 581 581 self.font.SetPointSize(10) 582 582 self.reader = None … … 781 781 if item.count("_") < 1: 782 782 try: 783 exec "float(math.%s)" % item783 exec("float(math.%s)" % item) 784 784 self.math_combo.Append(str(item)) 785 785 except Exception: -
src/sas/sasgui/perspectives/calculator/resolcal_thread.py
r20fa5fe r5251ec6 46 46 executing computation 47 47 """ 48 self.image = map(self.func, self.qx, self.qy,49 self.qx_min, self.qx_max,50 self.qy_min, self.qy_max)[0]48 self.image = list(map(self.func, self.qx, self.qy, 49 self.qx_min, self.qx_max, 50 self.qy_min, self.qy_max))[0] 51 51 elapsed = time.time() - self.starttime 52 52 -
src/sas/sasgui/perspectives/calculator/resolution_calculator_panel.py
r1cf490b6 r5251ec6 148 148 # Custom sorting 149 149 source_list = [] 150 for key, _ in self.source_mass.ite ritems():150 for key, _ in self.source_mass.items(): 151 151 name_source = str(key) 152 152 source_list.append(name_source) … … 667 667 Execute the computation of resolution 668 668 """ 669 # Clone the event before CallAfter; the event seems 670 # to delete the event when it is done processing, so 671 # the original will not be available when the call 672 # after method starts. 673 if event is not None: 674 event = event.Clone() 669 675 wx.CallAfter(self.on_compute_call, event) 670 676 … … 753 759 wx.MessageBox(msg, 'Warning') 754 760 return 755 #raise ValueError , "Invalid Q Input..."761 #raise ValueError("Invalid Q Input...") 756 762 757 763 # Validate the q inputs … … 934 940 def _sigma_strings(self): 935 941 """ 936 Recode sigmas as strin s942 Recode sigmas as strings 937 943 """ 938 944 sigma_r = self.format_number(self.resolution.sigma_1) … … 1082 1088 msg = "The numbers must be one or two (separated by ',')..." 1083 1089 self._status_info(msg, 'stop') 1084 raise RuntimeError , msg1090 raise RuntimeError(msg) 1085 1091 1086 1092 return new_string … … 1099 1105 value = float(string_split[ind]) 1100 1106 new_string.append(value) 1101 except :1102 logger.error( sys.exc_value)1107 except Exception as exc: 1108 logger.error(exc) 1103 1109 1104 1110 return new_string … … 1141 1147 out = self._string2inputlist(string) 1142 1148 return out 1143 except :1144 logger.error( sys.exc_value)1149 except Exception as exc: 1150 logger.error(exc) 1145 1151 1146 1152 def _on_xy_coordinate(self, event=None): … … 1269 1275 try: 1270 1276 basename = os.path.basename(path) 1271 if basename not in self.spectrum_dic .keys():1277 if basename not in self.spectrum_dic: 1272 1278 self.spectrum_cb.Append(basename) 1273 1279 self.spectrum_dic[basename] = self._read_file(path) … … 1286 1292 dlg = wx.FileDialog(self, 1287 1293 "Choose a wavelength spectrum file: Intensity vs. wavelength", 1288 self.parent.parent.get_save_location() , "", "*.*", wx. OPEN)1294 self.parent.parent.get_save_location() , "", "*.*", wx.FD_OPEN) 1289 1295 path = None 1290 1296 if dlg.ShowModal() == wx.ID_OK: … … 1318 1324 wavelength.append(wave) 1319 1325 intensity.append(intens) 1320 except :1326 except Exception as exc: 1321 1327 # Skip non-data lines 1322 logger.error( sys.exc_value)1328 logger.error(exc) 1323 1329 1324 1330 return [wavelength, intensity] -
src/sas/sasgui/perspectives/calculator/sld_panel.py
r2d220dd r5251ec6 363 363 364 364 """ 365 # TODO: use periodictable.elements object 366 # energy = xray_energy(periodictable.elements[element].K_alpha) 367 # TODO: code is very similar to sld helper 365 368 myformula = formula(str(element)) 366 369 if len(myformula.atoms) != 1: 367 370 return 368 element = myformula.atoms.keys()[0]371 element = list(myformula.atoms.keys())[0] 369 372 energy = xray_energy(element.K_alpha) 370 373 … … 413 416 msg += "Error for wavelength value :expect float" 414 417 elif (self.xray_source == 'Element'): 418 # TODO: use periodictable.elements instead of exec() hacks 419 # if self.xray_source_input not in periodictable.elements: 420 # ... 415 421 try: 416 422 import periodictable … … 447 453 448 454 """ 455 # TODO: use periodictable.elements object 456 # energy = xray_energy(periodictable.elements[element].K_alpha) 449 457 element_formula = formula(str(element)) 450 458 if len(element_formula.atoms) != 1: 451 459 return 452 element = element_formula.atoms.keys()[0]460 element = list(element_formula.atoms.keys())[0] 453 461 energy = xray_energy(element.K_alpha) 462 454 463 atom = molecule_formula.atoms 455 464 return xray_sld_from_atoms(atom, density=density, energy=energy) … … 505 514 #self.wavelength_ctl.SetValue(str(self.wavelength)) 506 515 #self.wavelength_ctl.SetValue(str(self.wavelength)) 507 except :516 except Exception as exc: 508 517 if self.base is not None: 509 msg = "SLD Calculator: %s" % (sys.exc_value)518 msg = "SLD Calculator: %s" % exc 510 519 wx.PostEvent(self.base, StatusEvent(status=msg)) 511 520 if event is not None: -
src/sas/sasgui/perspectives/calculator/slit_length_calculator_panel.py
rd788619 r5251ec6 17 17 from sas.sasgui.guiframe.events import StatusEvent 18 18 from sas.sascalc.calculator.slit_length_calculator import SlitlengthCalculator 19 from calculator_widgets import OutputTextCtrl20 from calculator_widgets import InterActiveOutputTextCtrl21 19 from sas.sasgui.perspectives.calculator import calculator_widgets as widget 22 20 from sas.sasgui.guiframe.documentation_window import DocumentationWindow 21 from .calculator_widgets import OutputTextCtrl 22 from .calculator_widgets import InterActiveOutputTextCtrl 23 23 24 24 _BOX_WIDTH = 76 … … 163 163 164 164 dlg = wx.FileDialog(self, "Choose a file", location, 165 "", wildcard, wx. OPEN)165 "", wildcard, wx.FD_OPEN) 166 166 if dlg.ShowModal() == wx.ID_OK: 167 167 path = dlg.GetPath() … … 223 223 self.reader.queue() 224 224 self.load_update() 225 except :225 except Exception as exc: 226 226 if self.parent.parent is None: 227 227 return 228 msg = "Slit Length Calculator: %s" % (sys.exc_value)228 msg = "Slit Length Calculator: %s" % exc 229 229 wx.PostEvent(self.parent.parent, 230 230 StatusEvent(status=msg, type='stop')) … … 264 264 if x == [] or x is None or y == [] or y is None: 265 265 msg = "The current data is empty please check x and y" 266 raise ValueError , msg266 raise ValueError(msg) 267 267 slit_length_calculator = SlitlengthCalculator() 268 268 slit_length_calculator.set_data(x=x, y=y) 269 269 slit_length = slit_length_calculator.calculate_slit_length() 270 except :270 except Exception as exc: 271 271 if self.parent.parent is None: 272 272 return 273 msg = "Slit Size Calculator: %s" % (sys.exc_value)273 msg = "Slit Size Calculator: %s" % exc 274 274 wx.PostEvent(self.parent.parent, 275 275 StatusEvent(status=msg, type='stop')) -
src/sas/sasgui/perspectives/corfunc/__init__.py
rc23f303 r5251ec6 1 1 PLUGIN_ID = "Corfunc Plug-In 0.1" 2 from corfunc import *2 from .corfunc import * -
src/sas/sasgui/perspectives/corfunc/corfunc.py
r9b90bf8 r5251ec6 18 18 from sas.sascalc.dataloader.loader import Loader 19 19 import sas.sascalc.dataloader 20 from plot_labels import *20 from .plot_labels import * 21 21 22 22 logger = logging.getLogger(__name__) … … 148 148 self.data_id = data.id 149 149 self.corfunc_panel.set_data(data) 150 except :151 msg = "Corfunc set_data: " + str( sys.exc_value)150 except Exception as exc: 151 msg = "Corfunc set_data: " + str(exc) 152 152 wx.PostEvent(self.parent, StatusEvent(status=msg, 153 153 info='error')) -
src/sas/sasgui/perspectives/corfunc/corfunc_panel.py
r5652efc r5251ec6 17 17 from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator 18 18 from sas.sasgui.guiframe.documentation_window import DocumentationWindow 19 from plot_labels import *19 from .plot_labels import * 20 20 21 21 OUTPUT_STRINGS = { … … 396 396 output.SetValue('-') 397 397 return 398 for key, value in params.ite ritems():398 for key, value in params.items(): 399 399 output = self._extrapolation_outputs[key] 400 400 rounded = self._round_sig_figs(value, 6) … … 417 417 # Not all parameters were calculated 418 418 error = True 419 for key, value in params.ite ritems():419 for key, value in params.items(): 420 420 rounded = self._round_sig_figs(value, 6) 421 421 self._output_boxes[key].SetValue(rounded) … … 549 549 wx.CENTER | wx.ADJUST_MINSIZE, 15) 550 550 551 file_sizer.AddSpacer((1, 25), pos=(0,2))551 #file_sizer.AddSpacer((1, 25), pos=(0,2)) 552 552 databox_sizer.Add(file_sizer, wx.TOP, 15) 553 553 … … 713 713 self._output_boxes = dict() 714 714 i = 0 715 for key, value in OUTPUT_STRINGS.ite ritems():715 for key, value in OUTPUT_STRINGS.items(): 716 716 # Create a label and a text box for each poperty 717 717 label = wx.StaticText(self, -1, value) -
src/sas/sasgui/perspectives/corfunc/corfunc_state.py
r5652efc r5251ec6 74 74 if self.outputs != {} and self.outputs is not None: 75 75 state += "\nOutputs:\n" 76 for key, value in self.outputs.ite ritems():76 for key, value in self.outputs.items(): 77 77 name = output_list[key][1] 78 78 state += "{}: {}\n".format(name, str(value)) … … 158 158 state = new_doc.createElement("state") 159 159 top_element.appendChild(state) 160 for name, value in self.saved_state.ite ritems():160 for name, value in self.saved_state.items(): 161 161 element = new_doc.createElement(name) 162 162 element.appendChild(new_doc.createTextNode(str(value))) … … 181 181 output = new_doc.createElement("output") 182 182 top_element.appendChild(output) 183 for key, value in self.outputs.ite ritems():183 for key, value in self.outputs.items(): 184 184 element = new_doc.createElement(key) 185 185 element.appendChild(new_doc.createTextNode(str(value))) … … 214 214 try: 215 215 self.timestamp = (entry.get('epoch')) 216 except :216 except Exception as exc: 217 217 msg = ("CorfuncState.fromXML: Could not read timestamp", 218 "\n{}").format( sys.exc_value)218 "\n{}").format(exc) 219 219 logger.error(msg) 220 220 … … 222 222 entry = get_content('ns:state', node) 223 223 if entry is not None: 224 for item in DEFAULT_STATE. iterkeys():224 for item in DEFAULT_STATE.keys(): 225 225 input_field = get_content("ns:{}".format(item), entry) 226 226 if input_field is not None: … … 283 283 root, ext = os.path.splitext(basename) 284 284 if not ext.lower() in self.ext: 285 raise IOError , "{} is not a supported file type".format(ext)285 raise IOError("{} is not a supported file type".format(ext)) 286 286 tree = etree.parse(path, parser=etree.ETCompatXMLParser()) 287 287 root = tree.getroot() … … 299 299 # File not found 300 300 msg = "{} is not a valid file path or doesn't exist".format(path) 301 raise IOError , msg301 raise IOError(msg) 302 302 303 303 if len(output) == 0: … … 323 323 msg = ("The CanSAS writer expects a Data1D instance. {} was " 324 324 "provided").format(datainfo.__class__.__name__) 325 raise RuntimeError , msg325 raise RuntimeError(msg) 326 326 if datainfo.title is None or datainfo.title == '': 327 327 datainfo.title = datainfo.name … … 358 358 state = CorfuncState() 359 359 state.fromXML(nodes[0]) 360 except :360 except Exception as exc: 361 361 msg = "XML document does not contain CorfuncState information\n{}" 362 msg.format( sys.exc_value)362 msg.format(exc) 363 363 logger.info(msg) 364 364 return state -
src/sas/sasgui/perspectives/file_converter/__init__.py
r77d92cd r5251ec6 1 1 PLUGIN_ID = "File-Converter Plug-In 1.0" 2 from file_converter import *2 from .file_converter import * -
src/sas/sasgui/perspectives/file_converter/converter_panel.py
ra26f67f r5251ec6 112 112 [group_path, group_name] = os.path.split(filepath) 113 113 ext = "." + group_name.split('.')[-1] # File extension 114 for frame_number, frame_data in frame_data.ite ritems():114 for frame_number, frame_data in frame_data.items(): 115 115 # Append frame number to base filename 116 116 filename = group_name.replace(ext, str(frame_number)+ext) … … 155 155 # If lines end with comma or semi-colon, trim the last character 156 156 if end_char == ',' or end_char == ';': 157 data = map(lambda s: s[0:-1], data)157 data = [s[0:-1] for s in data] 158 158 else: 159 159 msg = ("Error reading {}: Lines must end with a digit, comma " … … 275 275 else: 276 276 return { 'frames': [], 'inc': None, 'file': single_file } 277 frames = range(first_frame, last_frame + 1, increment)277 frames = list(range(first_frame, last_frame + 1, increment)) 278 278 return { 'frames': frames, 'inc': increment, 'file': single_file } 279 279 … … 335 335 if single_file: 336 336 # Only need to set metadata on first Data1D object 337 frame_data = frame_data.values() # Don't need to know frame numbers337 frame_data = list(frame_data.values()) # Don't need to know frame numbers 338 338 frame_data[0].filename = output_path.split('\\')[-1] 339 for key, value in metadata.ite ritems():339 for key, value in metadata.items(): 340 340 setattr(frame_data[0], key, value) 341 341 else: … … 343 343 for datainfo in frame_data.values(): 344 344 datainfo.filename = output_path.split('\\')[-1] 345 for key, value in metadata.ite ritems():345 for key, value in metadata.items(): 346 346 setattr(datainfo, key, value) 347 347 … … 355 355 def convert_2d_data(self, dataset): 356 356 metadata = self.get_metadata() 357 for key, value in metadata.ite ritems():357 for key, value in metadata.items(): 358 358 setattr(dataset[0], key, value) 359 359 -
src/sas/sasgui/perspectives/file_converter/converter_widgets.py
r0e11ec7 r5251ec6 54 54 v = Vector() 55 55 if not self.Validate(): return v 56 for direction, control in self._inputs.ite ritems():56 for direction, control in self._inputs.items(): 57 57 try: 58 58 value = float(control.GetValue()) -
src/sas/sasgui/perspectives/fitting/__init__.py
r12d3e0e r5251ec6 1 1 PLUGIN_ID = "Fitting plug-in 1.0" 2 2 import os 3 from fitting import *4 3 from distutils.filelist import findall 4 from .fitting import * 5 5 def get_data_path(media): 6 6 """ -
src/sas/sasgui/perspectives/fitting/basepage.py
r5323490 r5251ec6 12 12 import logging 13 13 import traceback 14 from Queue import Queue 14 try: 15 from Queue import Queue 16 except ImportError: 17 from queue import Queue 15 18 from threading import Thread 16 19 from collections import defaultdict … … 66 69 FONT_VARIANT = 1 67 70 ON_MAC = True 71 if sys.version_info[0] >= 3: 72 unicode = str 68 73 69 74 CUSTOM_MODEL = 'Plugin Models' … … 115 120 # Q range for data set 116 121 self.qmin_data_set = np.inf 117 self.qmax_data_set = None122 self.qmax_data_set = -np.inf 118 123 self.npts_data_set = 0 119 124 # Q range … … 624 629 if self.model is not None: 625 630 self.m_name = self.model.name 626 if name in self.saved_states .keys():631 if name in self.saved_states: 627 632 previous_state = self.saved_states[name] 628 633 # reset state of checkbox,textcrtl and regular parameters value … … 893 898 894 899 if len(self._disp_obj_dict) > 0: 895 for k, v in self._disp_obj_dict.ite ritems():900 for k, v in self._disp_obj_dict.items(): 896 901 self.state.disp_obj_dict[k] = v.type 897 902 … … 960 965 961 966 if len(self.disp_cb_dict) > 0: 962 for k, v in self.disp_cb_dict.ite ritems():967 for k, v in self.disp_cb_dict.items(): 963 968 if v is None: 964 969 self.state.disp_cb_dict[k] = v … … 969 974 self.state.disp_cb_dict[k] = None 970 975 if len(self._disp_obj_dict) > 0: 971 for k, v in self._disp_obj_dict.ite ritems():976 for k, v in self._disp_obj_dict.items(): 972 977 self.state.disp_obj_dict[k] = v.type 973 978 … … 1097 1102 1098 1103 else: 1099 keys = self.model.getParamList() 1100 for item in keys: 1104 for item in self.model.getParamList(): 1101 1105 if item in self.disp_list and \ 1102 1106 item not in self.model.details: … … 1142 1146 :return: combo_box_position 1143 1147 """ 1144 for key, value in self.master_category_dict.ite ritems():1148 for key, value in self.master_category_dict.items(): 1145 1149 formfactor = state.formfactorcombobox.split(":") 1146 1150 if isinstance(formfactor, list): … … 1318 1322 Help to rest page for dispersions 1319 1323 """ 1320 keys = self.model.getParamList() 1321 for item in keys: 1324 for item in self.model.getParamList(): 1322 1325 if item in self.disp_list and \ 1323 1326 item not in self.model.details: 1324 1327 self.model.details[item] = ["", None, None] 1325 # for k,v in self.state.disp_cb_dict.ite ritems():1328 # for k,v in self.state.disp_cb_dict.items(): 1326 1329 self.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) 1327 1330 self.state.disp_cb_dict = copy.deepcopy(state.disp_cb_dict) … … 1329 1332 self.weights = copy.deepcopy(state.weights) 1330 1333 1331 for key, disp_type in state.disp_obj_dict.ite ritems():1334 for key, disp_type in state.disp_obj_dict.items(): 1332 1335 # disp_model = disp 1333 1336 disp_model = POLYDISPERSITY_MODELS[disp_type]() … … 1378 1381 dlg = wx.FileDialog(self, "Choose a weight file", 1379 1382 self._default_save_location, "", 1380 "*.*", wx. OPEN)1383 "*.*", wx.FD_OPEN) 1381 1384 path = None 1382 1385 if dlg.ShowModal() == wx.ID_OK: … … 1390 1393 """ 1391 1394 ids = iter(self._id_pool) # Reusing ids for context menu 1392 for name, _ in self.state.saved_states.ite ritems():1395 for name, _ in self.state.saved_states.items(): 1393 1396 self.number_saved_state += 1 1394 1397 # Add item in the context menu … … 1919 1922 else: 1920 1923 tcrtl.SetBackgroundColour("pink") 1921 msg = "Model Error: wrong value entered: %s" % \1922 sys.exc_info()[1]1924 _, exc, _ = sys.exc_info() 1925 msg = "Model Error: wrong value entered: %s" % exc 1923 1926 wx.PostEvent(self.parent, StatusEvent(status=msg)) 1924 1927 return 1925 except Exception :1928 except Exception as exc: 1926 1929 tcrtl.SetBackgroundColour("pink") 1927 msg = "Model Error: wrong value entered: %s" % sys.exc_info()[1]1930 msg = "Model Error: wrong value entered: %s" % exc 1928 1931 wx.PostEvent(self.parent, StatusEvent(status=msg)) 1929 1932 return … … 1976 1979 else: 1977 1980 tcrtl.SetBackgroundColour("pink") 1978 msg = "Model Error: wrong value entered: %s" % \1979 sys.exc_info()[1]1981 _, exc, _ = sys.exc_info() 1982 msg = "Model Error: wrong value entered: %s" % exc 1980 1983 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 1981 1984 return 1982 except Exception :1985 except Exception as exc: 1983 1986 tcrtl.SetBackgroundColour("pink") 1984 msg = "Model Error: wrong value entered: %s" % sys.exc_info()[1]1987 msg = "Model Error: wrong value entered: %s" % exc 1985 1988 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 1986 1989 return … … 2291 2294 value_ctrl.SetValue(format_number(value)) 2292 2295 2293 if name not in self.model.details .keys():2296 if name not in self.model.details: 2294 2297 self.model.details[name] = ["", None, None] 2295 2298 old_low, old_high = self.model.details[name][1:3] … … 2750 2753 gui_manager = self._manager.parent 2751 2754 # loops through the panels [dic] 2752 for _, item2 in gui_manager.plot_panels.ite ritems():2755 for _, item2 in gui_manager.plot_panels.items(): 2753 2756 data_title = self.data.group_id 2754 2757 # try to get all plots belonging to this control panel … … 3324 3327 if self.data.__class__.__name__ == "Data2D": 3325 3328 name = item[1] 3326 if name in content .keys():3329 if name in content: 3327 3330 values = content[name] 3328 3331 check = values[0] … … 3373 3376 if not item[1] in orient_param: 3374 3377 name = item[1] 3375 if name in content .keys():3378 if name in content: 3376 3379 check = content[name][0] 3377 3380 # Avoid changing combox content … … 3480 3483 self.state.weights = self.weights 3481 3484 3482 except Exception :3485 except Exception as exc: 3483 3486 logger.error(traceback.format_exc()) 3484 print("Error in BasePage._paste_poly_help: %s" % \ 3485 sys.exc_info()[1]) 3487 print("Error in BasePage._paste_poly_help: %s" % exc) 3486 3488 3487 3489 def _set_disp_cb(self, isarray, item): … … 3548 3550 3549 3551 self.categorybox.Clear() 3550 cat_list = sorted(self.master_category_dict.keys())3552 cat_list = list(sorted(self.master_category_dict.keys())) 3551 3553 if uncat_str not in cat_list: 3552 3554 cat_list.append(uncat_str) -
src/sas/sasgui/perspectives/fitting/fit_thread.py
rba8d326 r5251ec6 12 12 13 13 def map_apply(arguments): 14 return apply(arguments[0], arguments[1:]) 14 fn, args = arguments[0], arguments[1:] 15 return fn(*args) 15 16 16 17 class FitThread(CalcThread): … … 50 51 except KeyboardInterrupt: 51 52 msg = "Fitting: terminated by the user." 52 raise KeyboardInterrupt , msg53 raise KeyboardInterrupt(msg) 53 54 54 55 def compute(self): … … 76 77 list_q, list_q, list_handler, list_curr_thread, 77 78 list_reset_flag) 78 result = map(map_apply, inputs)79 result = list(map(map_apply, inputs)) 79 80 80 81 self.complete(result=result, … … 85 86 elapsed=time.time() - self.starttime) 86 87 87 except KeyboardInterrupt ,msg:88 except KeyboardInterrupt as msg: 88 89 # Thread was interrupted, just proceed and re-raise. 89 90 # Real code should not print, but this is an example... -
src/sas/sasgui/perspectives/fitting/fitpage.py
rba1c145 r5251ec6 766 766 disp_box = wx.ComboBox(self, wx.ID_ANY, size=(65, -1), 767 767 style=wx.CB_READONLY, name='%s' % name1) 768 for key, value in POLYDISPERSITY_MODELS.ite ritems():768 for key, value in POLYDISPERSITY_MODELS.items(): 769 769 name_disp = str(key) 770 770 disp_box.Append(name_disp, value) … … 930 930 disp_box = wx.ComboBox(self, wx.ID_ANY, size=(65, -1), 931 931 style=wx.CB_READONLY, name='%s' % name1) 932 for key, value in POLYDISPERSITY_MODELS.ite ritems():932 for key, value in POLYDISPERSITY_MODELS.items(): 933 933 name_disp = str(key) 934 934 disp_box.Append(name_disp, value) … … 1372 1372 self._check_value_enter(self.fittable_param) 1373 1373 self._check_value_enter(self.parameters) 1374 except :1374 except Exception as exc: 1375 1375 tcrtl.SetBackgroundColour("pink") 1376 msg = "Model Error:wrong value entered : %s" % sys.exc_value1376 msg = "Model Error:wrong value entered : %s" % exc 1377 1377 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 1378 1378 return … … 1486 1486 else: 1487 1487 tcrtl.SetBackgroundColour("pink") 1488 msg = "Model Error:wrong value entered : %s" % sys.exc_value 1488 _, exc, _ = sys.exc_info() 1489 msg = "Model Error:wrong value entered : %s" % exc 1489 1490 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 1490 1491 return 1491 except :1492 except Exception as exc: 1492 1493 tcrtl.SetBackgroundColour("pink") 1493 msg = "Model Error:wrong value entered : %s" % sys.exc_value1494 msg = "Model Error:wrong value entered : %s" % exc 1494 1495 wx.PostEvent(self._manager.parent, StatusEvent(status=msg)) 1495 1496 return … … 1859 1860 wx.PostEvent(self._manager.parent, StatusEvent(status=msg, 1860 1861 info="error")) 1861 raise ValueError , msg1862 raise ValueError(msg) 1862 1863 1863 1864 else: … … 1871 1872 wx.PostEvent(self._manager.parent, StatusEvent(status=msg, 1872 1873 info="error")) 1873 raise ValueError , msg1874 raise ValueError(msg) 1874 1875 # Maximum value of data 1875 1876 qmax = math.sqrt(x * x + y * y) … … 2113 2114 self._on_fit_complete() 2114 2115 if out is None or not np.isfinite(chisqr): 2115 raise ValueError , "Fit error occured..."2116 raise ValueError("Fit error occured...") 2116 2117 2117 2118 is_modified = False … … 2188 2189 i += 1 2189 2190 else: 2190 raise ValueError , "onsetValues: Invalid parameters..."2191 raise ValueError("onsetValues: Invalid parameters...") 2191 2192 # Show error title when any errors displayed 2192 2193 if has_error: … … 2947 2948 # type can be either Guassian or Array 2948 2949 if len(self.model.dispersion.values()) > 0: 2949 type = self.model.dispersion.values()[0]["type"]2950 dist_type = list(self.model.dispersion.values())[0]["type"] 2950 2951 else: 2951 type = "Gaussian"2952 dist_type = "Gaussian" 2952 2953 2953 2954 iy += 1 … … 3008 3009 3009 3010 # For Gaussian only 3010 if type.lower() != "array":3011 if dist_type.lower() != "array": 3011 3012 for item in self.model.orientation_params: 3012 3013 if not self.magnetic_on: -
src/sas/sasgui/perspectives/fitting/fitpanel.py
r69363c7 r5251ec6 94 94 batch_state = self.sim_page.set_state() 95 95 96 for uid, page in self.opened_pages.ite ritems():96 for uid, page in self.opened_pages.items(): 97 97 data = page.get_data() 98 98 # state must be cloned … … 135 135 if uid not in self.opened_pages: 136 136 msg = "Fitpanel cannot find ID: %s in self.opened_pages" % str(uid) 137 raise ValueError , msg137 raise ValueError(msg) 138 138 else: 139 139 return self.opened_pages[uid] … … 217 217 page_is_opened = False 218 218 if state is not None: 219 for uid, panel in self.opened_pages.ite ritems():219 for uid, panel in self.opened_pages.items(): 220 220 # Don't return any panel is the exact same page is created 221 221 if uid == panel.uid and panel.data == state.data: … … 396 396 """ 397 397 if data.__class__.__name__ != "list": 398 raise ValueError , "Fitpanel delete_data expect list of id"398 raise ValueError("Fitpanel delete_data expect list of id") 399 399 else: 400 400 for page in self.opened_pages.values(): … … 592 592 if selected_page in page_finder: 593 593 # Delete the name of the page into the list of open page 594 for uid, list in self.opened_pages.ite ritems():594 for uid, list in self.opened_pages.items(): 595 595 # Don't return any panel is the exact same page is created 596 596 if flag and selected_page.uid == uid: … … 600 600 601 601 # Delete the name of the page into the list of open page 602 for uid, list in self.opened_pages.ite ritems():602 for uid, list in self.opened_pages.items(): 603 603 # Don't return any panel is the exact same page is created 604 604 if selected_page.uid == uid: -
src/sas/sasgui/perspectives/fitting/fitproblem.py
r20fa5fe r5251ec6 545 545 return fitproblem contained in this dictionary 546 546 """ 547 return self.values()547 return list(self.values()) 548 548 549 549 def set_result(self, result, fid): -
src/sas/sasgui/perspectives/fitting/fitting.py
raba4559 r5251ec6 147 147 Given an ID create a fitproblem container 148 148 """ 149 if page_id in self.page_finder .iterkeys():149 if page_id in self.page_finder: 150 150 del self.page_finder[page_id] 151 151 … … 356 356 # categories, the updated plugin may be in either the form factor 357 357 # or the structure factor combo boxes 358 for uid, page in self.fit_panel.opened_pages.ite ritems():358 for uid, page in self.fit_panel.opened_pages.items(): 359 359 pbox = getattr(page, "formfactorbox", None) 360 360 sbox = getattr(page, "structurebox", None) … … 417 417 self.fit_panel.SetSelection(current_page_index) 418 418 419 except Exception :420 logger.error("update_custom_combo: %s", sys.exc_value)419 except Exception as exc: 420 logger.error("update_custom_combo: %s", exc) 421 421 422 422 def set_edit_menu(self, owner): … … 642 642 data.list_group_id.append(group_id) 643 643 self.add_fit_page(data=[data]) 644 except :645 msg = "Fitting set_data: " + str( sys.exc_value)644 except Exception as exc: 645 msg = "Fitting set_data: " + str(exc) 646 646 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 647 647 … … 654 654 _, theory_state = item 655 655 self.fit_panel.set_model_state(theory_state) 656 except Exception :656 except Exception as exc: 657 657 msg = "Fitting: cannot deal with the theory received" 658 658 evt = StatusEvent(status=msg, info="error") 659 logger.error("set_theory " + msg + "\n" + str( sys.exc_value))659 logger.error("set_theory " + msg + "\n" + str(exc)) 660 660 wx.PostEvent(self.parent, evt) 661 661 … … 780 780 if fid is None: 781 781 return 782 if uid in self.page_finder .keys():782 if uid in self.page_finder: 783 783 self.page_finder[uid].set_weight(flag=flag, is2d=is2d) 784 784 … … 793 793 :param qmax: maximum value of the fit range 794 794 """ 795 if uid in self.page_finder .keys():795 if uid in self.page_finder: 796 796 self.page_finder[uid].set_range(qmin=qmin, qmax=qmax, fid=fid) 797 797 … … 804 804 :param uid: the id related to a page containing fitting information 805 805 """ 806 if uid in self.page_finder .keys():806 if uid in self.page_finder: 807 807 self.page_finder[uid].schedule_tofit(value) 808 808 … … 823 823 """ 824 824 sim_page_id = self.sim_page.uid 825 for uid, value in self.page_finder.ite ritems():825 for uid, value in self.page_finder.items(): 826 826 if uid != sim_page_id and uid != self.batch_page.uid: 827 827 model_list = value.get_model() … … 888 888 Stop the fit 889 889 """ 890 if uid in self.fit_thread_list .keys():890 if uid in self.fit_thread_list: 891 891 calc_fit = self.fit_thread_list[uid] 892 892 if calc_fit is not None and calc_fit.isrunning(): … … 900 900 batch_flag = self.batch_page is not None and uid == self.batch_page.uid 901 901 if sim_flag or batch_flag: 902 for uid, value in self.page_finder.ite ritems():902 for uid, value in self.page_finder.items(): 903 903 if value.get_scheduled() == 1: 904 if uid in self.fit_panel.opened_pages .keys():904 if uid in self.fit_panel.opened_pages: 905 905 panel = self.fit_panel.opened_pages[uid] 906 906 panel._on_fit_complete() … … 919 919 :param draw: Determine if the theory needs to be plot 920 920 """ 921 if uid not in self.page_finder .keys():921 if uid not in self.page_finder: 922 922 return 923 923 self.page_finder[uid].enable_smearing(flag=enable_smearer) … … 930 930 msg += "Got data = %s .\n" % str(data) 931 931 return 932 #raise ValueError , msg932 #raise ValueError(msg) 933 933 model = self.page_finder[uid].get_model(fid=fid) 934 934 if model is None: … … 1032 1032 list_page_id = [] 1033 1033 fit_id = 0 1034 for page_id, page_info in self.page_finder.ite ritems():1034 for page_id, page_info in self.page_finder.items(): 1035 1035 # For simulfit (uid give with None), do for-loop 1036 1036 # if uid is specified (singlefit), do it only on the page. … … 1059 1059 1060 1060 pars = [str(element[1]) for element in page.param_toFit] 1061 fitproblem_list = page_info.values() 1062 for fitproblem in fitproblem_list: 1061 for fitproblem in page_info.values(): 1063 1062 if sim_fitter is None: 1064 1063 fitter = Fit() … … 1079 1078 wx.PostEvent(self.parent, evt) 1080 1079 return True 1081 except :1080 except Exception as exc: 1082 1081 raise 1083 msg = "Fitting error: %s" % str(sys.exc_value)1082 msg = "Fitting error: %s" % exc 1084 1083 evt = StatusEvent(status=msg, info="error", type="stop") 1085 1084 wx.PostEvent(self.parent, evt) … … 1138 1137 :param fid: the id of the fitproblem(data, model, range,etc) 1139 1138 """ 1140 if uid not in self.page_finder .keys():1139 if uid not in self.page_finder: 1141 1140 return 1142 1141 fitproblemList = self.page_finder[uid].get_fit_problem(fid) … … 1183 1182 evt = StatusEvent(status=msg, info="warning") 1184 1183 wx.PostEvent(self.parent, evt) 1185 except Exception :1186 msg = "Creating Fit page: %s" % sys.exc_value1184 except Exception as exc: 1185 msg = "Creating Fit page: %s" % exc 1187 1186 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 1188 1187 … … 1264 1263 # case that uid is not specified 1265 1264 if uid is None: 1266 for page_id in self.page_finder .keys():1265 for page_id in self.page_finder: 1267 1266 self.page_finder[page_id].schedule_tofit(value) 1268 1267 # when uid is given 1269 1268 else: 1270 if uid in self.page_finder .keys():1269 if uid in self.page_finder: 1271 1270 self.page_finder[uid].schedule_tofit(value) 1272 1271 … … 1302 1301 panel = self.plot_panel 1303 1302 if panel is None: 1304 raise ValueError , "Fitting:_onSelect: NonType panel"1303 raise ValueError("Fitting:_onSelect: NonType panel") 1305 1304 Plugin.on_perspective(self, event=event) 1306 1305 self.select_data(panel) … … 1335 1334 """ 1336 1335 uid = page_id[0] 1337 if uid in self.fit_thread_list .keys():1336 if uid in self.fit_thread_list: 1338 1337 del self.fit_thread_list[uid] 1339 1338 … … 1361 1360 #get all fittable parameters of the current model 1362 1361 for param in model.getParamList(): 1363 if param not in batch_outputs .keys():1362 if param not in batch_outputs: 1364 1363 batch_outputs[param] = [] 1365 1364 for param in model.getDispParamList(): 1366 1365 if not model.is_fittable(param) and \ 1367 param in batch_outputs .keys():1366 param in batch_outputs: 1368 1367 del batch_outputs[param] 1369 1368 # Add fitted parameters and their error 1370 1369 for param in res.param_list: 1371 if param not in batch_outputs .keys():1370 if param not in batch_outputs: 1372 1371 batch_outputs[param] = [] 1373 1372 err_param = "error on %s" % str(param) 1374 if err_param not in batch_inputs .keys():1373 if err_param not in batch_inputs: 1375 1374 batch_inputs[err_param] = [] 1376 1375 msg = "" … … 1526 1525 model = fitproblem.get_model() 1527 1526 #fill batch result information 1528 if "Data" not in batch_outputs .keys():1527 if "Data" not in batch_outputs: 1529 1528 batch_outputs["Data"] = [] 1530 1529 cell = BatchCell() … … 1555 1554 cell.object = [data, theory_data] 1556 1555 batch_outputs["Data"].append(cell) 1557 for key, value in data.meta_data.ite ritems():1558 if key not in batch_inputs .keys():1556 for key, value in data.meta_data.items(): 1557 if key not in batch_inputs: 1559 1558 batch_inputs[key] = [] 1560 1559 #if key.lower().strip() != "loader": … … 1562 1561 param = "temperature" 1563 1562 if hasattr(data.sample, param): 1564 if param not in batch_inputs .keys():1563 if param not in batch_inputs: 1565 1564 batch_inputs[param] = [] 1566 1565 batch_inputs[param].append(data.sample.temperature) … … 1633 1632 wx.PostEvent(self.parent, evt) 1634 1633 1635 except Exception: 1636 msg = ("Fit completed but the following error occurred: %s" 1637 % sys.exc_value) 1634 except Exception as exc: 1635 msg = "Fit completed but the following error occurred: %s" % exc 1638 1636 #msg = "\n".join((traceback.format_exc(), msg)) 1639 1637 evt = StatusEvent(status=msg, info="warning", type="stop") … … 1723 1721 if model is None: 1724 1722 return 1725 if uid not in self.page_finder .keys():1723 if uid not in self.page_finder: 1726 1724 return 1727 1725 # save the name containing the data name with the appropriate model … … 2080 2078 source=source) 2081 2079 self.calc_1D.queue() 2082 except :2080 except Exception as exc: 2083 2081 msg = " Error occurred when drawing %s Model 1D: " % model.name 2084 msg += " %s" % sys.exc_value2082 msg += " %s" % exc 2085 2083 wx.PostEvent(self.parent, StatusEvent(status=msg)) 2086 2084 -
src/sas/sasgui/perspectives/fitting/model_thread.py
r69363c7 r5251ec6 65 65 if self.data is None: 66 66 msg = "Compute Calc2D receive data = %s.\n" % str(self.data) 67 raise ValueError , msg67 raise ValueError(msg) 68 68 69 69 # Define matrix where data will be plotted -
src/sas/sasgui/perspectives/fitting/resultpanel.py
r959eb01 r5251ec6 59 59 def on_plot_results(self, event): 60 60 self.frame.Show(True) 61 result = event.result[0][0]61 result = list(event.result[0])[0] 62 62 filename = result.data.sas_data.filename 63 63 current_time = datetime.datetime.now().strftime("%I:%M%p, %B %d, %Y") -
src/sas/sasgui/perspectives/fitting/simfitpage.py
r20fa5fe r5251ec6 168 168 i = 0 169 169 for model in self.model_list: 170 model_id = self._format_id( model[1].keys()[0])170 model_id = self._format_id(list(model[1].keys())[0]) 171 171 for saved_model in sim_state.model_list: 172 172 save_id = saved_model.pop('name') … … 328 328 sizer.Add(tab_used, (iy, ix), (1, 1), 329 329 wx.EXPAND | wx.ADJUST_MINSIZE, 0) 330 for id, value in self.page_finder.ite ritems():330 for id, value in self.page_finder.items(): 331 331 if id not in self.parent.opened_pages: 332 332 continue … … 757 757 self.set_button.Disable() 758 758 759 for id, model in self.constraint_dict.ite ritems():759 for id, model in self.constraint_dict.items(): 760 760 # check if all parameters have been selected for constraint 761 761 # then do not allow add constraint on parameters 762 762 self.model_cbox_left.Append(str(model.name), model) 763 763 self.model_cbox_left.Select(0) 764 for id, model in self.constraint_dict.ite ritems():764 for id, model in self.constraint_dict.items(): 765 765 # check if all parameters have been selected for constraint 766 766 # then do not allow add constraint on parameters … … 814 814 model_right = self.model_cbox_right.GetValue() 815 815 model_b = self.model_cbox_right.GetClientData(selection_b) 816 for id, dic_model in self.constraint_dict.ite ritems():816 for id, dic_model in self.constraint_dict.items(): 817 817 if model == dic_model: 818 818 param_list = self.page_finder[id].get_param2fit() … … 857 857 if len(self.constraints_list) != 0: 858 858 nb_fit_param = 0 859 for id, model in self.constraint_dict.ite ritems():859 for id, model in self.constraint_dict.items(): 860 860 nb_fit_param += len(self.page_finder[id].get_param2fit()) 861 861 # Don't add anymore … … 879 879 model_cbox = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_READONLY) 880 880 model_cbox.Clear() 881 for id, model in self.constraint_dict.ite ritems():881 for id, model in self.constraint_dict.items(): 882 882 # check if all parameters have been selected for constraint 883 883 # then do not allow add constraint on parameters … … 931 931 hide buttons related constraint 932 932 """ 933 for id in self.page_finder. iterkeys():933 for id in self.page_finder.keys(): 934 934 self.page_finder[id].clear_model_param() 935 935 … … 969 969 model = model_cbox.GetClientData(n) 970 970 param_list = [] 971 for id, dic_model in self.constraint_dict.ite ritems():971 for id, dic_model in self.constraint_dict.items(): 972 972 if model == dic_model: 973 973 param_list = self.page_finder[id].get_param2fit() … … 1056 1056 msg += " in combobox to set constraint! " 1057 1057 wx.PostEvent(self.parent.parent, StatusEvent(status=msg)) 1058 for id, value in self.constraint_dict.ite ritems():1058 for id, value in self.constraint_dict.items(): 1059 1059 if model == value: 1060 1060 if constraint == "": … … 1080 1080 return False 1081 1081 1082 for fid in self.page_finder[id]. iterkeys():1082 for fid in self.page_finder[id].keys(): 1083 1083 # wrap in param/constraint in str() to remove unicode 1084 1084 self.page_finder[id].set_model_param(str(param), -
src/sas/sasgui/perspectives/invariant/__init__.py
r5a405bd r5251ec6 3 3 4 4 from distutils.filelist import findall 5 from invariant import *5 from .invariant import * 6 6 7 7 def get_data_path(media): -
src/sas/sasgui/perspectives/invariant/invariant.py
r7432acb r5251ec6 133 133 name = data.__class__.__name__ 134 134 msg = "Invariant use only Data1D got: [%s] " % str(name) 135 raise ValueError , msg135 raise ValueError(msg) 136 136 self.compute_helper(data=data) 137 137 … … 144 144 if data_list is None: 145 145 data_list = [] 146 else: 147 data_list = list(data_list) # force iterator to list 146 148 if len(data_list) >= 1: 147 149 if len(data_list) == 1: … … 190 192 try: 191 193 self.compute_helper(data) 192 except :193 msg = "Invariant Set_data: " + str( sys.exc_value)194 except Exception as exc: 195 msg = "Invariant Set_data: " + str(exc) 194 196 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 195 197 else: … … 240 242 msg = "invariant.save_file: the data being saved is" 241 243 msg += " not a sas.sascalc.dataloader.data_info.Data1D object" 242 raise RuntimeError , msg244 raise RuntimeError(msg) 243 245 244 246 def set_state(self, state=None, datainfo=None): … … 258 260 msg = "invariant.set_state: datainfo parameter cannot" 259 261 msg += " be None in standalone mode" 260 raise RuntimeError , msg262 raise RuntimeError(msg) 261 263 # Make sure the user sees the invariant panel after loading 262 264 # self.parent.set_perspective(self.perspective) … … 281 283 self.on_set_state_helper(None) 282 284 283 except :284 logger.error("invariant.set_state: %s" % sys.exc_value)285 except Exception as exc: 286 logger.error("invariant.set_state: %s" % exc) 285 287 286 288 def on_set_state_helper(self, event=None): … … 320 322 else: 321 323 msg = "Scale can not be zero." 322 raise ValueError , msg324 raise ValueError(msg) 323 325 if len(new_plot.x) == 0: 324 326 return -
src/sas/sasgui/perspectives/invariant/invariant_details.py
r20fa5fe r5251ec6 2 2 Invariant panel 3 3 """ 4 import sys 5 4 6 import wx 5 import sys6 7 7 8 from sas.sasgui.guiframe.utils import format_number 8 from invariant_widgets import OutputTextCtrl 9 from .invariant_widgets import OutputTextCtrl 10 9 11 # Dimensions related to chart 10 12 RECTANGLE_WIDTH = 400.0 … … 33 35 34 36 35 class InvariantContainer (wx.Object):37 class InvariantContainer: 36 38 """ 37 39 This class stores some values resulting resulting from invariant -
src/sas/sasgui/perspectives/invariant/invariant_panel.py
r44e8f48 r5251ec6 319 319 background = self.background_tcl.GetValue().lstrip().rstrip() 320 320 if background == "": 321 raise ValueError , "Need a background"321 raise ValueError("Need a background") 322 322 if check_float(self.background_tcl): 323 323 return float(background) 324 324 else: 325 325 msg = "Receive invalid value for background : %s" % (background) 326 raise ValueError , msg326 raise ValueError(msg) 327 327 328 328 def get_scale(self): … … 332 332 scale = self.scale_tcl.GetValue().lstrip().rstrip() 333 333 if scale == "": 334 raise ValueError , "Need a background"334 raise ValueError("Need a background") 335 335 if check_float(self.scale_tcl): 336 336 if float(scale) <= 0.0: … … 338 338 self.scale_tcl.Refresh() 339 339 msg = "Receive invalid value for scale: %s" % (scale) 340 raise ValueError , msg340 raise ValueError(msg) 341 341 return float(scale) 342 342 else: 343 raise ValueError , "Receive invalid value for scale : %s" % (scale)343 raise ValueError("Receive invalid value for scale : %s" % (scale)) 344 344 345 345 def get_contrast(self): … … 386 386 self.volume_tcl.SetValue(format_number(v)) 387 387 self.volume_err_tcl.SetValue(format_number(dv)) 388 except :388 except Exception as exc: 389 389 self.volume_tcl.SetValue(format_number(None)) 390 390 self.volume_err_tcl.SetValue(format_number(None)) 391 391 msg = "Error occurred computing volume " 392 msg += " fraction: %s" % sys.exc_value392 msg += " fraction: %s" % exc 393 393 wx.PostEvent(self.parent, StatusEvent(status=msg, 394 394 info="error", … … 406 406 self.surface_tcl.SetValue(format_number(s)) 407 407 self.surface_err_tcl.SetValue(format_number(ds)) 408 except :408 except Exception as exc: 409 409 self.surface_tcl.SetValue(format_number(None)) 410 410 self.surface_err_tcl.SetValue(format_number(None)) 411 411 msg = "Error occurred computing " 412 msg += "specific surface: %s" % sys.exc_value412 msg += "specific surface: %s" % exc 413 413 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error", 414 414 type="stop")) … … 426 426 self.inv_container.qstar_total = qstar_total 427 427 self.inv_container.qstar_total_err = qstar_total_err 428 except :428 except Exception as exc: 429 429 self.inv_container.qstar_total = "Error" 430 430 self.inv_container.qstar_total_err = "Error" … … 432 432 self.invariant_total_err_tcl.SetValue(format_number(None)) 433 433 msg = "Error occurred computing invariant using" 434 msg += " extrapolation: %s" % sys.exc_value434 msg += " extrapolation: %s" % exc 435 435 wx.PostEvent(self.parent, StatusEvent(status=msg, type="stop")) 436 436 … … 450 450 self._manager.plot_theory(data=extrapolated_data, 451 451 name="Low-Q extrapolation") 452 except :452 except Exception as exc: 453 453 self.inv_container.qstar_low = "ERROR" 454 454 self.inv_container.qstar_low_err = "ERROR" 455 455 self._manager.plot_theory(name="Low-Q extrapolation") 456 456 msg = "Error occurred computing low-Q " 457 msg += "invariant: %s" % sys.exc_value457 msg += "invariant: %s" % exc 458 458 wx.PostEvent(self.parent, 459 459 StatusEvent(status=msg, type="stop")) … … 462 462 try: 463 463 self._manager.plot_theory(name="Low-Q extrapolation") 464 except :465 logger.error( sys.exc_value)464 except Exception as exc: 465 logger.error(exc) 466 466 467 467 def get_high_qstar(self, inv, high_q=False): … … 483 483 self._manager.plot_theory(data=high_out_data, 484 484 name="High-Q extrapolation") 485 except :485 except Exception as exc: 486 486 #raise 487 487 self.inv_container.qstar_high = "ERROR" … … 489 489 self._manager.plot_theory(name="High-Q extrapolation") 490 490 msg = "Error occurred computing high-Q " 491 msg += "invariant: %s" % sys.exc_value491 msg += "invariant: %s" % exc 492 492 wx.PostEvent(self.parent, StatusEvent(status=msg, 493 493 type="stop")) … … 496 496 try: 497 497 self._manager.plot_theory(name="High-Q extrapolation") 498 except :499 logger.error( sys.exc_value)498 except Exception as exc: 499 logger.error(exc) 500 500 501 501 def get_qstar(self, inv): … … 625 625 background = self.get_background() 626 626 scale = self.get_scale() 627 except :628 msg = "Invariant Error: %s" % (sys.exc_value)627 except Exception as exc: 628 msg = "Invariant Error: %s" % exc 629 629 wx.PostEvent(self.parent, StatusEvent(status=msg, type="stop")) 630 630 return … … 641 641 inv, npts_low = self.set_extrapolation_low(inv=inv, low_q=low_q) 642 642 inv, npts_high = self.set_extrapolation_high(inv=inv, high_q=high_q) 643 except :644 msg = "Error occurred computing invariant: %s" % sys.exc_value643 except Exception as exc: 644 msg = "Error occurred computing invariant: %s" % exc 645 645 wx.PostEvent(self.parent, StatusEvent(status=msg, 646 646 info="warning", type="stop")) … … 652 652 try: 653 653 self.get_qstar(inv=inv) 654 except :655 msg = "Error occurred computing invariant: %s" % sys.exc_value654 except Exception as exc: 655 msg = "Error occurred computing invariant: %s" % exc 656 656 wx.PostEvent(self.parent, StatusEvent(status=msg, 657 657 info="warning", … … 674 674 porod_const = self.get_porod_const() 675 675 contrast = self.get_contrast() 676 except: 677 msg = r_msg + "Error occurred computing invariant: %s" % \ 678 sys.exc_value 676 except Exception as exc: 677 msg = r_msg + "Error occurred computing invariant: %s" % exc 679 678 wx.PostEvent(self.parent, StatusEvent(status=msg, 680 679 info="error", … … 685 684 extrapolation=extrapolation) 686 685 #compute surface and set value to txtcrtl 687 except :688 msg = "Error occurred computing invariant: %s" % sys.exc_value686 except Exception as exc: 687 msg = "Error occurred computing invariant: %s" % exc 689 688 wx.PostEvent(self.parent, StatusEvent(status=msg, 690 689 info="warning", … … 695 694 extrapolation=extrapolation) 696 695 697 except :698 msg = "Error occurred computing invariant: %s" % sys.exc_value696 except Exception as exc: 697 msg = "Error occurred computing invariant: %s" % exc 699 698 wx.PostEvent(self.parent, StatusEvent(status=msg, 700 699 info="warning", … … 845 844 if attr.__class__.__name__ == "StaticText": 846 845 return 847 if value in ["True", "False", True, False]: 848 value = bool(value) 846 if value in ["True", True]: 847 value = 1 848 elif value in ["False", False]: 849 value = 0 849 850 else: 850 851 value = str(value) 851 852 attr.SetValue(value) 852 except :853 logger.error("Invariant state: %s", sys.exc_value)853 except Exception as exc: 854 logger.error("Invariant state: %s", exc) 854 855 855 856 def get_bookmark_by_num(self, num=None): … … 867 868 try: 868 869 _, _, current_state, comp_state = self.state.bookmark_list[int(num)] 869 except :870 logger.error( sys.exc_value)871 raise ValueError , "No such bookmark exists"870 except Exception as exc: 871 logger.error(exc) 872 raise ValueError("No such bookmark exists") 872 873 873 874 # set the parameters … … 962 963 self.state.state_list[str(self.state.state_num)] = \ 963 964 self.state.clone_state() 964 except :965 logger.error( sys.exc_value)965 except Exception as exc: 966 logger.error(exc) 966 967 967 968 self._set_undo_flag(True) … … 1006 1007 try: 1007 1008 del self.state.state_list[str(i)] 1008 except :1009 logger.error( sys.exc_value)1009 except Exception as exc: 1010 logger.error(exc) 1010 1011 # Enable the undo button if it was not 1011 1012 self._set_undo_flag(True) … … 1071 1072 try: 1072 1073 del self.state.state_list[str(i)] 1073 except :1074 logger.error( sys.exc_value)1074 except Exception as exc: 1075 logger.error(exc) 1075 1076 1076 1077 # try to add new state of the text changes in the state_list … … 1086 1087 self.state.state_num = self.state.saved_state['state_num'] 1087 1088 self.state.state_list[str(self.state.state_num)] = self.state.clone_state() 1088 except :1089 logger.error( sys.exc_value)1089 except Exception as exc: 1090 logger.error(exc) 1090 1091 1091 1092 self._set_undo_flag(True) … … 1108 1109 self.state.saved_state[name] = str(value) 1109 1110 self.state.state_list[str(self.state.state_num)] = self.state.clone_state() 1110 except :1111 logger.error( sys.exc_value)1111 except Exception as exc: 1112 logger.error(exc) 1112 1113 1113 1114 def _get_input_list(self): … … 1118 1119 compute_num = self.state.saved_state['compute_num'] 1119 1120 # find values and put into the input list 1120 for key1, value1 in self.state.state_list[str(compute_num)].ite ritems():1121 for key, _ in self.state.input_list.ite ritems():1121 for key1, value1 in self.state.state_list[str(compute_num)].items(): 1122 for key, _ in self.state.input_list.items(): 1122 1123 if key == key1: 1123 1124 self.state.input_list[key] = value1 -
src/sas/sasgui/perspectives/invariant/invariant_state.py
re9920cd r5251ec6 2 2 State class for the invariant UI 3 3 """ 4 from __future__ import print_function 4 5 5 6 # import time … … 140 141 141 142 # text ctl general inputs ( excluding extrapolation text ctl) 142 for key, value in self.input_list.ite ritems():143 for key, value in self.input_list.items(): 143 144 if value == '': 144 145 continue … … 166 167 low_off = False 167 168 high_off = False 168 for key, value in self.input_list.ite ritems():169 for key, value in self.input_list.items(): 169 170 key_split = key.split('_') 170 171 max_ind = len(key_split) - 1 … … 216 217 # other outputs than Q* 217 218 name = item[0] + "_tcl" 218 if name in self.saved_state .keys():219 if name in self.saved_state: 219 220 value = self.saved_state[name] 220 221 … … 301 302 top_element.appendChild(state) 302 303 303 for name, value in self.saved_state.ite ritems():304 for name, value in self.saved_state.items(): 304 305 element = newdoc.createElement(str(name)) 305 306 element.appendChild(newdoc.createTextNode(str(value))) … … 310 311 top_element.appendChild(history) 311 312 312 for name, value in self.state_list.ite ritems():313 for name, value in self.state_list.items(): 313 314 history_element = newdoc.createElement('state_' + str(name)) 314 for state_name, state_value in value.ite ritems():315 for state_name, state_value in value.items(): 315 316 state_element = newdoc.createElement(str(state_name)) 316 317 child = newdoc.createTextNode(str(state_value)) … … 325 326 top_element.appendChild(bookmark) 326 327 item_list = ['time', 'date', 'state', 'comp_state'] 327 for name, value_list in self.bookmark_list.ite ritems():328 for name, value_list in self.bookmark_list.items(): 328 329 element = newdoc.createElement('mark_' + str(name)) 329 330 _, date, state, comp_state = value_list … … 334 335 state_list_element = newdoc.createElement('state') 335 336 comp_state_list_element = newdoc.createElement('comp_state') 336 for state_name, state_value in value_list[2].ite ritems():337 for state_name, state_value in value_list[2].items(): 337 338 state_element = newdoc.createElement(str(state_name)) 338 339 child = newdoc.createTextNode(str(state_value)) 339 340 state_element.appendChild(child) 340 341 state_list_element.appendChild(state_element) 341 for comp_name, comp_value in value_list[3].ite ritems():342 for comp_name, comp_value in value_list[3].items(): 342 343 comp_element = newdoc.createElement(str(comp_name)) 343 344 comp_element.appendChild(newdoc.createTextNode(str(comp_value))) … … 368 369 msg = "InvariantSate no longer supports non-CanSAS" 369 370 msg += " format for invariant files" 370 raise RuntimeError , msg371 raise RuntimeError(msg) 371 372 372 373 if node.get('version')\ … … 383 384 try: 384 385 timestamp = (entry.get('epoch')) 385 except :386 except Exception as exc: 386 387 msg = "InvariantSate.fromXML: Could not read" 387 msg += " timestamp\n %s" % sys.exc_value388 msg += " timestamp\n %s" % exc 388 389 logger.error(msg) 389 390 … … 453 454 Get the values (strings) from __str__ for report 454 455 """ 455 strings = self.__str__()456 457 456 # default string values 458 for num in range(1, 19): 459 exec "s_%s = 'NA'" % str(num) 460 lines = strings.split('\n') 457 s = {num: 'NA' for num in range(1, 19)} 461 458 # get all string values from __str__() 462 for line in range(0, len(lines)): 463 if line == 1: 464 s_1 = lines[1] 465 elif line == 2: 466 s_2 = lines[2] 459 lines = str(self).split('\n') 460 for line_num, line in enumerate(lines): 461 if line_num == 1: 462 s[1] = line 463 elif line_num == 2: 464 s[2] = line 467 465 else: 468 item = line s[line].split(':')466 item = line.split(':') 469 467 item[0] = item[0].strip() 470 468 if item[0] == "scale": 471 s _3= item[1]469 s[3] = item[1] 472 470 elif item[0] == "porod constant": 473 s _4= item[1]471 s[4] = item[1] 474 472 elif item[0] == "background": 475 s _5= item[1]473 s[5] = item[1] 476 474 elif item[0] == "contrast": 477 s _6= item[1]475 s[6] = item[1] 478 476 elif item[0] == "Extrapolation": 479 477 extra = item[1].split(";") 480 478 bool_0 = extra[0].split("=") 481 479 bool_1 = extra[1].split("=") 482 s _8= " " + bool_0[0] + "Q region = " + bool_0[1]483 s _7= " " + bool_1[0] + "Q region = " + bool_1[1]480 s[8] = " " + bool_0[0] + "Q region = " + bool_0[1] 481 s[7] = " " + bool_1[0] + "Q region = " + bool_1[1] 484 482 elif item[0] == "npts low": 485 s _9= item[1]483 s[9] = item[1] 486 484 elif item[0] == "npts high": 487 s _10= item[1]485 s[10] = item[1] 488 486 elif item[0] == "volume fraction": 489 487 val = item[1].split("+-")[0].strip() 490 488 error = item[1].split("+-")[1].strip() 491 s _17= val + " ± " + error489 s[17] = val + " ± " + error 492 490 elif item[0] == "specific surface": 493 491 val = item[1].split("+-")[0].strip() 494 492 error = item[1].split("+-")[1].strip() 495 s _18= val + " ± " + error493 s[18] = val + " ± " + error 496 494 elif item[0].split("(")[0].strip() == "power low": 497 s _11= item[0] + " =" + item[1]495 s[11] = item[0] + " =" + item[1] 498 496 elif item[0].split("(")[0].strip() == "power high": 499 s _12= item[0] + " =" + item[1]497 s[12] = item[0] + " =" + item[1] 500 498 elif item[0].split("[")[0].strip() == "Q* from low Q extrapolation": 501 499 # looks messy but this way the symbols +_ and % work on html … … 504 502 err = error.split("%")[0].strip() 505 503 percent = error.split("%")[1].strip() 506 s _13= val + " ± " + err + "%" + percent504 s[13] = val + " ± " + err + "%" + percent 507 505 elif item[0].split("[")[0].strip() == "Q* from data": 508 506 val = item[1].split("+-")[0].strip() … … 510 508 err = error.split("%")[0].strip() 511 509 percent = error.split("%")[1].strip() 512 s _14= val + " ± " + err + "%" + percent510 s[14] = val + " ± " + err + "%" + percent 513 511 elif item[0].split("[")[0].strip() == "Q* from high Q extrapolation": 514 512 val = item[1].split("+-")[0].strip() … … 516 514 err = error.split("%")[0].strip() 517 515 percent = error.split("%")[1].strip() 518 s _15= val + " ± " + err + "%" + percent516 s[15] = val + " ± " + err + "%" + percent 519 517 elif item[0].split("[")[0].strip() == "total Q*": 520 518 val = item[1].split("+-")[0].strip() 521 519 error = item[1].split("+-")[1].strip() 522 s _16= val + " ± " + error520 s[16] = val + " ± " + error 523 521 else: 524 522 continue 525 523 526 s _1 = self._check_html_format(s_1)524 s[1] = self._check_html_format(s[1]) 527 525 file_name = self._check_html_format(self.file) 528 526 … … 530 528 self.set_plot_state(extra_high=bool_0[1], extra_low=bool_1[1]) 531 529 # get ready for report with setting all the html strings 532 self.report_str = str(self.template_str) % (s_1, s_2, 533 s_3, s_4, s_5, s_6, s_7, s_8, 534 s_9, s_10, s_11, s_12, s_13, s_14, s_15, 535 s_16, s_17, s_18, file_name, "%s") 530 self.report_str = str(self.template_str) % ( 531 s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11], 532 s[12], s[13], s[14], s[15], s[16], s[17], s[18], file_name, "%s") 536 533 537 534 def _check_html_format(self, name): … … 692 689 state = InvariantState() 693 690 state.fromXML(node=nodes[0]) 694 except :691 except Exception as exc: 695 692 msg = "XML document does not contain invariant" 696 msg += " information.\n %s" % sys.exc_value693 msg += " information.\n %s" % exc 697 694 logger.info(msg) 698 695 return state … … 736 733 output.append(sas_entry) 737 734 else: 738 raise RuntimeError , "%s is not a file" % path735 raise RuntimeError("%s is not a file" % path) 739 736 740 737 # Return output consistent with the loader's api … … 782 779 msg = "The cansas writer expects a Data1D" 783 780 msg += " instance: %s" % str(datainfo.__class__.__name__) 784 raise RuntimeError , msg781 raise RuntimeError(msg) 785 782 # make sure title and data run is filled up. 786 783 if datainfo.title is None or datainfo.title == '': -
src/sas/sasgui/perspectives/invariant/report_dialog.py
rd0ce666f r5251ec6 92 92 # Mac 93 93 os.system("open %s" % fName) 94 except :94 except Exception as exc: 95 95 # DO not open 96 logger.error("Could not open file: %s" % sys.exc_value)96 logger.error("Could not open file: %s" % exc) 97 97 # delete image file 98 98 os.remove(pic_fname) -
src/sas/sasgui/perspectives/pr/__init__.py
r959eb01 r5251ec6 1 1 PLUGIN_ID = "P(r) plug-in 1.0" 2 from pr import *2 from .pr import * -
src/sas/sasgui/perspectives/pr/explore_dialog.py
r20fa5fe r5251ec6 35 35 from sas.sasgui.plottools.plottables import Graph 36 36 37 from pr_widgets import PrTextCtrl37 from .pr_widgets import PrTextCtrl 38 38 39 39 # Default number of points on the output plot … … 416 416 results.pos_err.append(pos_err) 417 417 results.osc.append(osc) 418 except :418 except Exception as exc: 419 419 # This inversion failed, skip this D_max value 420 420 msg = "ExploreDialog: inversion failed " 421 msg += "for D_max=%s\n%s" % (str(d), sys.exc_value)421 msg += "for D_max=%s\n%s" % (str(d), exc) 422 422 logger.error(msg) 423 423 -
src/sas/sasgui/perspectives/pr/inversion_panel.py
rcb62bd5 r5251ec6 5 5 __revision__ = "$Revision: 1193 $" 6 6 7 import wx8 7 import os 9 8 import sys 10 9 import logging 10 11 import wx 11 12 from wx.lib.scrolledpanel import ScrolledPanel 13 12 14 from sas.sasgui.guiframe.events import StatusEvent 13 15 from sas.sasgui.guiframe.panel_base import PanelBase 14 from inversion_state import InversionState15 from pr_widgets import PrTextCtrl16 from pr_widgets import DataFileTextCtrl17 from pr_widgets import OutputTextCtrl18 16 from sas.sasgui.guiframe.documentation_window import DocumentationWindow 17 18 from .inversion_state import InversionState 19 from .pr_widgets import PrTextCtrl 20 from .pr_widgets import DataFileTextCtrl 21 from .pr_widgets import OutputTextCtrl 19 22 20 23 logger = logging.getLogger(__name__) … … 752 755 except ValueError: 753 756 logger.error("InversionControl._on_accept_alpha got a value that was not a number: %s" % alpha ) 754 except :757 except Exception as exc: 755 758 # No estimate or bad estimate, either do nothing 756 logger.error("InversionControl._on_accept_alpha: %s" % sys.exc_value)759 logger.error("InversionControl._on_accept_alpha: %s" % exc) 757 760 758 761 def _on_accept_nterms(self, evt): … … 768 771 except ValueError: 769 772 logger.error("InversionControl._on_accept_nterms got a value that was not a number: %s" % nterms ) 770 except :773 except Exception as exc: 771 774 # No estimate or bad estimate, either do nothing 772 logger.error("InversionControl._on_accept_nterms: %s" % sys.exc_value)775 logger.error("InversionControl._on_accept_nterms: %s" % exc) 773 776 774 777 def clear_panel(self): … … 901 904 message += "than the number of points" 902 905 wx.PostEvent(self._manager.parent, StatusEvent(status=message)) 903 raise ValueError , message906 raise ValueError(message) 904 907 self.nfunc_ctl.SetBackgroundColour(wx.WHITE) 905 908 self.nfunc_ctl.Refresh() … … 957 960 Invoke the d_max exploration dialog 958 961 """ 959 from explore_dialog import ExploreDialog962 from .explore_dialog import ExploreDialog 960 963 if self._manager._last_pr is not None: 961 964 pr = self._manager._create_plot_pr() … … 1008 1011 self._on_invert(None) 1009 1012 self._set_analysis(True) 1010 except :1011 msg = "InversionControl._change_file: %s" % sys.exc_value1013 except Exception as exc: 1014 msg = "InversionControl._change_file: %s" % exc 1012 1015 logger.error(msg) 1013 1016 -
src/sas/sasgui/perspectives/pr/inversion_state.py
r2469df7 r5251ec6 18 18 import logging 19 19 from lxml import etree 20 20 21 from sas.sasgui.guiframe.dataFitting import Data1D 21 22 from sas.sascalc.dataloader.readers.cansas_reader import Reader as CansasReader … … 238 239 msg = "InversionState no longer supports non-CanSAS" 239 240 msg += " format for P(r) files" 240 raise RuntimeError , msg241 raise RuntimeError(msg) 241 242 242 243 if node.get('version') and node.get('version') == '1.0': … … 252 253 try: 253 254 self.timestamp = float(entry.get('epoch')) 254 except :255 except Exception as exc: 255 256 msg = "InversionState.fromXML: Could not read " 256 msg += "timestamp\n %s" % sys.exc_value257 msg += "timestamp\n %s" % exc 257 258 logger.error(msg) 258 259 … … 432 433 state = InversionState() 433 434 state.fromXML(node=nodes[0]) 434 except :435 except Exception as exc: 435 436 msg = "XML document does not contain P(r) " 436 msg += "information.\n %s" % sys.exc_value437 msg += "information.\n %s" % exc 437 438 logger.info(msg) 438 439 … … 481 482 output.append(sas_entry) 482 483 else: 483 raise RuntimeError , "%s is not a file" % path484 raise RuntimeError("%s is not a file" % path) 484 485 485 486 # Return output consistent with the loader's api … … 525 526 msg = "The cansas writer expects a Data1D " 526 527 msg += "instance: %s" % str(datainfo.__class__.__name__) 527 raise RuntimeError , msg528 raise RuntimeError(msg) 528 529 529 530 # Create basic XML document -
src/sas/sasgui/perspectives/pr/pr.py
r2469df7 r5251ec6 18 18 19 19 import sys 20 import wx21 20 import logging 22 21 import time 23 22 import math 23 24 import wx 24 25 import numpy as np 25 26 import pylab 27 26 28 from sas.sasgui.guiframe.gui_manager import MDIFrame 27 29 from sas.sasgui.guiframe.dataFitting import Data1D … … 33 35 import sas.sascalc.dataloader 34 36 35 from pr_widgets import load_error36 37 from sas.sasgui.guiframe.plugin_base import PluginBase 38 39 from .inversion_state import Reader # .prv file reader 40 from .inversion_panel import InversionControl 41 #from .inversion_panel import HelpDialog 42 from .inversion_panel import PrDistDialog 43 from .pr_thread import CalcPr 44 from .pr_thread import EstimatePr 45 from .pr_thread import EstimateNT 46 from .pr_widgets import load_error 47 from .pr_widgets import DataDialog 37 48 38 49 logger = logging.getLogger(__name__) … … 106 117 self.list_plot_id = [] 107 118 108 # Associate the inversion state reader with .prv files109 from inversion_state import Reader110 111 119 # Create a CanSAS/Pr reader 112 120 self.state_reader = Reader(self.set_state) … … 151 159 msg = "Pr.set_state: datainfo parameter cannot " 152 160 msg += "be None in standalone mode" 153 raise RuntimeError , msg161 raise RuntimeError(msg) 154 162 155 163 # Ensuring that plots are coordinated correctly … … 184 192 title=self.current_plottable.title)) 185 193 self.control_panel.set_state(state) 186 except :187 logger.error("prview.set_state: %s" % sys.exc_value)194 except Exception as exc: 195 logger.error("prview.set_state: %s" % exc) 188 196 189 197 … … 195 203 196 204 """ 197 from inversion_panel import HelpDialog198 205 dialog = HelpDialog(None, -1) 199 206 if dialog.ShowModal() == wx.ID_OK: … … 369 376 Redisplay P(r) with a different number of points 370 377 """ 371 from inversion_panel import PrDistDialog372 378 dialog = PrDistDialog(None, -1) 373 379 dialog.set_content(self._pr_npts) … … 452 458 # Notify the user if we could not read the file 453 459 if dataread is None: 454 raise RuntimeError , "Invalid data"460 raise RuntimeError("Invalid data") 455 461 456 462 x = None … … 472 478 if dataread is None: 473 479 return x, y, err 474 raise RuntimeError , "This tool can only read 1D data"480 raise RuntimeError("This tool can only read 1D data") 475 481 476 482 self._current_file_data.x = x … … 511 517 data_y = np.append(data_y, y) 512 518 data_err = np.append(data_err, err) 513 except :514 logger.error( sys.exc_value)519 except Exception as exc: 520 logger.error(exc) 515 521 516 522 if scale is not None: … … 562 568 data_y = np.append(data_y, y) 563 569 data_err = np.append(data_err, err) 564 except :565 logger.error( sys.exc_value)570 except Exception as exc: 571 logger.error(exc) 566 572 elif line.find("The 6 columns") >= 0: 567 573 data_started = True … … 720 726 Start a calculation thread 721 727 """ 722 from pr_thread import CalcPr723 724 728 # If a thread is already started, stop it 725 729 if self.calc_thread is not None and self.calc_thread.isrunning(): … … 849 853 try: 850 854 pr = self._create_file_pr(data) 851 except :852 status = "Problem reading data: %s" % sys.exc_value855 except Exception as exc: 856 status = "Problem reading data: %s" % exc 853 857 wx.PostEvent(self.parent, StatusEvent(status=status)) 854 raise RuntimeError , status858 raise RuntimeError(status) 855 859 856 860 # If the file contains nothing, just return 857 861 if pr is None: 858 raise RuntimeError , "Loaded data is invalid"862 raise RuntimeError("Loaded data is invalid") 859 863 860 864 self.pr = pr … … 906 910 msg = "pr.save_data: the data being saved is not a" 907 911 msg += " sas.data_info.Data1D object" 908 raise RuntimeError , msg912 raise RuntimeError(msg) 909 913 910 914 def setup_plot_inversion(self, alpha, nfunc, d_max, q_min=None, q_max=None, … … 928 932 self.pr = pr 929 933 self.perform_inversion() 930 except :931 wx.PostEvent(self.parent, StatusEvent(status= sys.exc_value))934 except Exception as exc: 935 wx.PostEvent(self.parent, StatusEvent(status=exc)) 932 936 933 937 def estimate_plot_inversion(self, alpha, nfunc, d_max, … … 952 956 self.pr = pr 953 957 self.perform_estimate() 954 except :955 wx.PostEvent(self.parent, StatusEvent(status= sys.exc_value))958 except Exception as exc: 959 wx.PostEvent(self.parent, StatusEvent(status=exc)) 956 960 957 961 def _create_plot_pr(self, estimate=False): … … 1033 1037 self.pr = pr 1034 1038 self.perform_inversion() 1035 except :1036 wx.PostEvent(self.parent, StatusEvent(status= sys.exc_value))1039 except Exception as exc: 1040 wx.PostEvent(self.parent, StatusEvent(status=exc)) 1037 1041 1038 1042 def estimate_file_inversion(self, alpha, nfunc, d_max, data, … … 1056 1060 self.pr = pr 1057 1061 self.perform_estimate() 1058 except :1059 wx.PostEvent(self.parent, StatusEvent(status= sys.exc_value))1062 except Exception as exc: 1063 wx.PostEvent(self.parent, StatusEvent(status=exc)) 1060 1064 1061 1065 def _create_file_pr(self, data): … … 1085 1089 self._current_file_data.err = data.dy 1086 1090 x, y, err = data.x, data.y, data.dy 1087 except :1088 load_error( sys.exc_value)1091 except Exception as exc: 1092 load_error(exc) 1089 1093 return None 1090 1094 … … 1124 1128 pr.slit_width = self.slit_width 1125 1129 return pr 1126 except :1127 load_error( sys.exc_value)1130 except Exception as exc: 1131 load_error(exc) 1128 1132 return None 1129 1133 … … 1132 1136 Perform parameter estimation 1133 1137 """ 1134 from pr_thread import EstimatePr1135 1136 1138 # If a thread is already started, stop it 1137 1139 if self.estimation_thread is not None and \ … … 1162 1164 Perform parameter estimation 1163 1165 """ 1164 from pr_thread import EstimateNT1165 1166 1166 # If a thread is already started, stop it 1167 1167 if self.estimation_thread is not None and self.estimation_thread.isrunning(): … … 1239 1239 Create and return a list of panel objects 1240 1240 """ 1241 from inversion_panel import InversionControl1242 1243 1241 self.parent = parent 1244 1242 self.frame = MDIFrame(self.parent, None, 'None', (100, 200)) … … 1262 1260 if data_list is None: 1263 1261 data_list = [] 1262 else: 1263 data_list = list(data_list) # force iterator to list 1264 1264 if len(data_list) >= 1: 1265 1265 if len(data_list) == 1: … … 1287 1287 msg += "Please select one.\n" 1288 1288 if len(data_list) > 1: 1289 from pr_widgets import DataDialog1290 1289 dlg = DataDialog(data_list=data_1d_list, text=msg) 1291 1290 if dlg.ShowModal() == wx.ID_OK: … … 1306 1305 self.data_id = data.id 1307 1306 self.control_panel._change_file(evt=None, data=data) 1308 except :1309 msg = "Prview Set_data: " + str( sys.exc_value)1307 except Exception as exc: 1308 msg = "Prview Set_data: " + str(exc) 1310 1309 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 1311 1310 else: -
src/sas/sasgui/perspectives/pr/pr_thread.py
rac07a3a r5251ec6 41 41 # Thread was interrupted, just proceed 42 42 pass 43 except :43 except Exception as exc: 44 44 if self.error_func is not None: 45 self.error_func("CalcPr.compute: %s" % sys.exc_value)45 self.error_func("CalcPr.compute: %s" % exc) 46 46 47 47 class EstimatePr(CalcThread): … … 69 69 # Thread was interrupted, just proceed 70 70 pass 71 except :71 except Exception as exc: 72 72 if self.error_func is not None: 73 self.error_func("EstimatePr.compute: %s" % sys.exc_value)73 self.error_func("EstimatePr.compute: %s" % exc) 74 74 75 75 class EstimateNT(CalcThread): … … 109 109 # Thread was interrupted, just proceed 110 110 pass 111 except :111 except Exception as exc: 112 112 if self.error_func is not None: 113 self.error_func("EstimatePr2.compute: %s" % sys.exc_value)113 self.error_func("EstimatePr2.compute: %s" % exc) -
src/sas/sasgui/perspectives/simulation/ShapeAdapter.py
r959eb01 r5251ec6 87 87 self.sim_canvas._model_changed() 88 88 else: 89 raise ValueError , "SimShapeVisitor: Wrong class for visited object"89 raise ValueError("SimShapeVisitor: Wrong class for visited object") 90 90 91 91 … … 115 115 self.sim_canvas._model_changed() 116 116 else: 117 raise ValueError , "SimShapeVisitor: Wrong class for visited object"117 raise ValueError("SimShapeVisitor: Wrong class for visited object") 118 118 119 119 … … 130 130 shape.accept_update(self) 131 131 else: 132 raise ValueError , "ShapeAdapter: Shape [%s] not in list" % shape.name132 raise ValueError("ShapeAdapter: Shape [%s] not in list" % shape.name) 133 133 -
src/sas/sasgui/perspectives/simulation/ShapeParameters.py
ra1b8fee r5251ec6 10 10 from __future__ import print_function 11 11 12 import sys 13 from copy import deepcopy 14 12 15 import wx 13 import sys14 16 import wx.lib.newevent 15 from copy import deepcopy 16 import SimCanvas17 18 from . import SimCanvas 17 19 18 20 (CreateShapeEvent, EVT_ADD_SHAPE) = wx.lib.newevent.NewEvent() … … 201 203 n = 1 202 204 self.parameters = [] 203 keys = shape.params.keys() 204 keys.sort() 205 206 for item in keys: 205 206 for item in sorted(shape.params.keys()): 207 207 if item in ['contrast', 'order']: 208 208 continue … … 393 393 if not tmp==None: 394 394 self.current_shape.params[item[0]] = tmp 395 except :395 except Exception as exc: 396 396 print("Could not create") 397 print( sys.exc_value)397 print(exc) 398 398 399 399 def _onCreate(self, evt): … … 489 489 print("NOT YET IMPLMENTED") 490 490 print("renaming", self.shape_listbox.GetString(indices[0])) 491 -
src/sas/sasgui/perspectives/simulation/__init__.py
r959eb01 r5251ec6 1 1 PLUGIN_ID = "Simulation plug-in 1.0" 2 from simulation import *2 from .simulation import * -
src/sas/sasgui/perspectives/simulation/simulation.py
r7432acb r5251ec6 15 15 16 16 # Application imports 17 import SimCanvas 18 import ShapeParameters 19 import ShapeAdapter 17 from sas.sascalc.realspace import VolumeCanvas 18 from sas.sascalc.data_util.calcthread import CalcThread 20 19 from sas.sasgui.guiframe.dataFitting import Data1D 21 # Real-space simulation import22 import sas.sascalc.realspace.VolumeCanvas as VolumeCanvas23 24 from sas.sascalc.data_util.calcthread import CalcThread25 20 from sas.guicomm.events import NewPlotEvent, StatusEvent 21 22 from . import SimCanvas 23 from . import ShapeParameters 24 from . import ShapeAdapter 26 25 27 26 logger = logging.getLogger(__name__) -
src/sas/sasgui/plottools/LineModel.py
ra26f67f r5251ec6 83 83 elif x.__class__.__name__ == 'tuple': 84 84 msg = "Tuples are not allowed as input to BaseComponent models" 85 raise ValueError , msg85 raise ValueError(msg) 86 86 else: 87 87 return self._line(x) … … 105 105 elif x.__class__.__name__ == 'tuple': 106 106 msg = "Tuples are not allowed as input to BaseComponent models" 107 raise ValueError , msg107 raise ValueError(msg) 108 108 else: 109 109 return self._line(x) -
src/sas/sasgui/plottools/PlotPanel.py
r2469df7 r5251ec6 6 6 import logging 7 7 import traceback 8 import math 9 import os 10 import operator 11 import copy 12 8 13 import wx 14 import numpy as np 15 9 16 # Try a normal import first 10 17 # If it fails, try specifying a version … … 15 22 from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg 16 23 from matplotlib.figure import Figure 17 import os18 import transform19 #TODO: make the plottables interactive20 from binder import BindArtist21 24 from matplotlib.font_manager import FontProperties 22 DEBUG = False23 24 from plottables import Graph25 from TextDialog import TextDialog26 from LabelDialog import LabelDialog27 import operator28 29 import math30 25 import pylab 31 26 DEFAULT_CMAP = pylab.cm.jet 32 import copy33 import numpy as np34 27 35 28 from sas.sasgui.guiframe.events import StatusEvent 29 30 #TODO: make the plottables interactive 31 from . import transform 32 from .TextDialog import TextDialog 33 from .LabelDialog import LabelDialog 34 from .binder import BindArtist 35 from .convert_units import convert_unit 36 from .plottables import Graph 36 37 from .toolbar import NavigationToolBar, PlotPrintout, bind 37 38 39 DEBUG = False 38 40 logger = logging.getLogger(__name__) 39 41 … … 44 46 for a in obj.get_children(): show_tree(a, d + 1) 45 47 46 from convert_units import convert_unit47 48 48 49 … … 116 117 self.figure = Figure(None, dpi, linewidth=2.0) 117 118 self.color = '#b3b3b3' 118 from canvas import FigureCanvas119 from .canvas import FigureCanvas 119 120 self.canvas = FigureCanvas(self, -1, self.figure) 120 121 self.SetColor(color) … … 657 658 else: 658 659 plot_dict = plotlist 659 from fitDialog import LinearFit660 from .fitDialog import LinearFit 660 661 661 662 if len(plot_dict.keys()) > 0: 662 first_item = plot_dict.keys()[0]663 first_item = list(plot_dict.keys())[0] 663 664 dlg = LinearFit(parent=None, plottable=first_item, 664 665 push_data=self.onFitDisplay, … … 703 704 704 705 """ 705 from fitDialog import LinearFit706 from .fitDialog import LinearFit 706 707 if self._fit_dialog is not None: 707 708 return … … 736 737 first_item = plot_list.keys()[0] 737 738 if first_item.x != []: 738 from PropertyDialog import Properties739 from .PropertyDialog import Properties 739 740 dial = Properties(self, -1, 'Properties') 740 741 dial.setValues(self.prevXtrans, self.prevYtrans, self.viewModel) … … 1001 1002 Remove legend for ax or the current axes. 1002 1003 """ 1003 from pylab import gca1004 1004 if ax is None: 1005 ax = gca()1005 ax = pylab.gca() 1006 1006 ax.legend_ = None 1007 1007 … … 1327 1327 if id is None: 1328 1328 id = name 1329 from plottable_interactor import PointInteractor1329 from .plottable_interactor import PointInteractor 1330 1330 p = PointInteractor(self, self.subplot, zorder=zorder, id=id) 1331 1331 if p.markersize is not None: … … 1344 1344 if id is None: 1345 1345 id = name 1346 from plottable_interactor import PointInteractor1346 from .plottable_interactor import PointInteractor 1347 1347 p = PointInteractor(self, self.subplot, zorder=zorder, id=id) 1348 1348 p.curve(x, y, dy=dy, color=color, symbol=symbol, zorder=zorder, … … 1754 1754 self.graph.delete(self.fit_result) 1755 1755 if hasattr(self, 'plots'): 1756 if 'fit' in self.plots .keys():1756 if 'fit' in self.plots: 1757 1757 del self.plots['fit'] 1758 1758 self.ly = None -
src/sas/sasgui/plottools/__init__.py
refe730d r5251ec6 1 from PlotPanel import PlotPanel2 from plottables import Data1D, Theory1D1 from .PlotPanel import PlotPanel 2 from .plottables import Data1D, Theory1D -
src/sas/sasgui/plottools/binder.py
r20fa5fe r5251ec6 28 28 return self.artist is not other.artist 29 29 30 def __ nonzero__(self):30 def __bool__(self): 31 31 return self.artist is not None 32 33 __nonzero__ = __bool__ 32 34 33 35 34 36 class BindArtist(object): 35 37 """ 38 Track keyboard modifiers for events. 36 39 """ 37 # Track keyboard modifiers for events.38 40 # TODO: Move keyboard modifier support into the backend. We cannot 39 41 # TODO: properly support it from outside the windowing system since there … … 65 67 ] 66 68 except: 67 print("bypassing scroll_event: wrong matplotlib version")69 logger.warn("bypassing scroll_event: wrong matplotlib version") 68 70 self._connections = [ 69 71 canvas.mpl_connect('motion_notify_event', self._onMotion), … … 74 76 ] 75 77 78 # Turn off picker if it hasn't already been done 79 try: 80 canvas.mpl_disconnect(canvas.button_pick_id) 81 canvas.mpl_disconnect(canvas.scroll_pick_id) 82 except Exception as exc: 83 logger.error(exc) 84 76 85 self._current = None 77 86 self._actions = {} … … 87 96 Use clearall() to reset all connections. 88 97 """ 89 90 98 for h in artists: 91 99 for a in self.events: … … 123 131 """ 124 132 try: 125 for cid in self._connections: self.canvas.mpl_disconnect(cid) 126 except: 127 logger.error("Error disconnection canvas: %s" % sys.exc_value) 133 for cid in self._connections: 134 self.canvas.mpl_disconnect(cid) 135 except Exception as exc: 136 logger.error("Error disconnection canvas: %s" % exc) 128 137 self._connections = [] 129 138 … … 172 181 sure it applies. E.g., the callback for 'press' might be: 173 182 if event.button == 1 and event.shift: process Shift-click 174 175 TODO: Only receive events with the correct modifiers (e.g., S-click, 176 TODO: or *-click for any modifiers). 177 TODO: Only receive button events for the correct button (e.g., click1 178 TODO: release3, or dclick* for any button) 179 TODO: Support virtual artist, so that and artist can be flagged as 180 TODO: having a tag list and receive the correct events 181 TODO: Support virtual events for binding to button-3 vs shift button-1 182 TODO: without changing callback code 183 TODO: Attach multiple callbacks to the same event? 184 TODO: Clean up interaction with toolbar modes 185 TODO: push/pushclear/pop context so that binding changes for 186 the duration 187 TODO: e.g., to support ? context sensitive help 188 """ 183 """ 184 #TODO: Only receive events with the correct modifiers (e.g., S-click, 185 #TODO: or *-click for any modifiers). 186 #TODO: Only receive button events for the correct button (e.g., click1 187 #TODO: release3, or dclick* for any button) 188 #TODO: Support virtual artist, so that and artist can be flagged as 189 #TODO: having a tag list and receive the correct events 190 #TODO: Support virtual events for binding to button-3 vs shift button-1 191 #TODO: without changing callback code 192 #TODO: Attach multiple callbacks to the same event? 193 #TODO: Clean up interaction with toolbar modes 194 #TODO: push/pushclear/pop context so that binding changes for the duration 195 #TODO: e.g., to support ? context sensitive help 196 189 197 # Check that the trigger is valid 190 198 if trigger not in self._actions: 191 raise ValueError , "%s invalid --- valid triggers are %s"\192 % (trigger, ", ".join(self.events))199 raise ValueError("%s invalid --- valid triggers are %s" 200 % (trigger, ", ".join(self.events))) 193 201 194 202 # Register the trigger callback … … 205 213 """ 206 214 if action not in self.events: 207 raise ValueError , "Trigger expects " + ", ".join(self.events)215 raise ValueError("Trigger expects " + ", ".join(self.events)) 208 216 209 217 # Tag the event with modifiers … … 214 222 setattr(ev, 'prop', {}) 215 223 216 # Fallback scheme. 224 # Fallback scheme. If the event does not return false, pass to parent. 217 225 processed = False 218 226 artist, prop = actor.artist, actor.prop … … 237 245 """ 238 246 # TODO: sort by zorder of axes then by zorder within axes 239 self._artists.sort( cmp=lambda x, y: cmp(y.zorder, x.zorder))247 self._artists.sort(key=lambda x: x.zorder, reverse=True) 240 248 found = Selection() 241 249 for artist in self._artists: … … 276 284 277 285 transform = self._hasclick.artist.get_transform() 278 # 286 #x,y = event.xdata,event.ydata 279 287 x, y = event.x, event.y 280 288 try: … … 286 294 # #transform ="CompositeGenericTransform" crash 287 295 pass 288 except: 289 # # CRUFT matplotlib-0.91 support 296 except: # CRUFT: matplotlib-0.91 support 290 297 # # exception for transform ="CompositeGenericTransform" 291 298 # # crashes also here 292 299 x, y = transform.inverse_xy_tup((x, y)) 293 300 294 # event.xdata, event.ydata = x, y 301 #TODO: why compute (x,y) if it isn't being used? 302 #event.xdata, event.ydata = x, y 295 303 self.trigger(self._hasclick, 'drag', event) 296 304 else: -
src/sas/sasgui/plottools/canvas.py
r7432acb r5251ec6 97 97 try: 98 98 dc.DrawBitmap(self.canvas.bitmap, (0, 0)) 99 except :100 logger.error( sys.exc_value)99 except Exception as exc: 100 logger.error(exc) 101 101 102 102 # restore original figure resolution … … 208 208 try: 209 209 fig.draw(self) 210 except ValueError :211 logger.error( sys.exc_value)210 except ValueError as exc: 211 logger.error(exc) 212 212 else: 213 213 self._isRendered = False -
src/sas/sasgui/plottools/convert_units.py
ra1b8fee r5251ec6 13 13 """ 14 14 if power != 0: 15 if string.find(unit,"^") != -1: # if the unit contains a powerer ^16 toks = re.split( "\^", unit)17 if string.find(toks[0],"/") != -1 or \18 string.find(toks[0],"-") != -1:15 if unit.find("^") != -1: # if the unit contains a powerer ^ 16 toks = re.split(r"\^", unit) 17 if toks[0].find("/") != -1 or \ 18 toks[0].find("-") != -1: 19 19 if power == 1: 20 20 unit = unit … … 22 22 unit = "(" + unit + ")" + "^{" + str(power) + "}" 23 23 else: 24 if string.find(toks[1],"{") != -1: # if found a {24 if toks[1].find("{") != -1: # if found a { 25 25 find_power_toks = re.split("{", toks[1]) 26 if string.find(find_power_toks[1],"}") != -1: # found }26 if find_power_toks[1].find("}") != -1: # found } 27 27 unit_toks = re.split("}", find_power_toks[1]) 28 if string.find(unit_toks[0],".") != -1:28 if unit_toks[0].find(".") != -1: 29 29 powerer = float(unit_toks[0]) * power 30 elif string.find(unit_toks[0],"/") != -1:30 elif unit_toks[0].find("/") != -1: 31 31 power_toks = re.split("/", unit_toks[0]) 32 32 powerer = power * int(power_toks[0])\ … … 44 44 unit = toks[0] + "^{" + str(powerer) + "}" 45 45 else: 46 raise ValueError , "missing } in unit expression"46 raise ValueError("missing } in unit expression") 47 47 else: # no powerer 48 48 if power != 1: 49 49 unit = "(" + unit + ")" + "^{" + str(power) + "}" 50 50 else: 51 raise ValueError , "empty unit ,enter a powerer different from zero"51 raise ValueError("empty unit, enter a power different from zero") 52 52 return unit 53 53 -
src/sas/sasgui/plottools/fitDialog.py
r2469df7 r5251ec6 1 import sys 2 import math 3 1 4 import wx 2 from plottables import Theory1D3 import math4 5 import numpy as np 5 import fittings 6 import transform 7 import sys 6 7 from . import fittings 8 from . import transform 9 from .plottables import Theory1D 8 10 9 11 # Linear fit panel size … … 86 88 self.layout() 87 89 # Receives the type of model for the fitting 88 from LineModel import LineModel90 from .LineModel import LineModel 89 91 self.model = LineModel() 90 92 # Display the fittings values … … 671 673 return x 672 674 else: 673 raise ValueError , "cannot compute log of a negative number"675 raise ValueError("cannot compute log of a negative number") 674 676 675 677 def floatInvTransform(self, x): … … 734 736 except: 735 737 msg = "LinearFit.set_fit_region: fit range must be floats" 736 raise ValueError , msg738 raise ValueError(msg) 737 739 self.xminFit.SetValue(format_number(xmin)) 738 740 self.xmaxFit.SetValue(format_number(xmax)) -
src/sas/sasgui/plottools/fittings.py
ra1b8fee r5251ec6 101 101 # Testing implementation 102 102 # Fit a Line model 103 from LineModel import LineModel103 from .LineModel import LineModel 104 104 line = LineModel() 105 105 cstA = Parameter(line, 'A', event.cstA) -
src/sas/sasgui/plottools/plottable_interactor.py
r2469df7 r5251ec6 4 4 from __future__ import print_function 5 5 6 from BaseInteractor import _BaseInteractor6 from .BaseInteractor import _BaseInteractor 7 7 8 8 -
src/sas/sasgui/plottools/plottables.py
r2469df7 r5251ec6 389 389 390 390 """ 391 raise NotImplemented , "Not a valid transform"391 raise NotImplemented("Not a valid transform") 392 392 393 393 # Related issues … … 689 689 msg = "Plottable.View: Given x and dx are not" 690 690 msg += " of the same length" 691 raise ValueError , msg691 raise ValueError(msg) 692 692 # Check length of y array 693 693 if not len(y) == len(x): 694 694 msg = "Plottable.View: Given y " 695 695 msg += "and x are not of the same length" 696 raise ValueError , msg696 raise ValueError(msg) 697 697 698 698 if dy is not None and not len(dy) == 0 and not len(y) == len(dy): 699 699 msg = "Plottable.View: Given y and dy are not of the same " 700 700 msg += "length: len(y)=%s, len(dy)=%s" % (len(y), len(dy)) 701 raise ValueError , msg701 raise ValueError(msg) 702 702 self.x = [] 703 703 self.y = [] … … 734 734 msg = "Plottable.View: transformed x " 735 735 msg += "and y are not of the same length" 736 raise ValueError , msg736 raise ValueError(msg) 737 737 if has_err_x and not (len(self.x) == len(self.dx)): 738 738 msg = "Plottable.View: transformed x and dx" 739 739 msg += " are not of the same length" 740 raise ValueError , msg740 raise ValueError(msg) 741 741 if has_err_y and not (len(self.y) == len(self.dy)): 742 742 msg = "Plottable.View: transformed y" 743 743 msg += " and dy are not of the same length" 744 raise ValueError , msg744 raise ValueError(msg) 745 745 # Check that negative values are not plot on x and y axis for 746 746 # log10 transformation … … 812 812 tempy.append(self.y[i]) 813 813 tempdy.append(self.dy[i]) 814 except :814 except Exception as exc: 815 815 logger.error("check_data_logX: skipping point x %g", self.x[i]) 816 logger.error( sys.exc_value)816 logger.error(exc) 817 817 self.x = tempx 818 818 self.y = tempy … … 842 842 tempy.append(self.y[i]) 843 843 tempdy.append(self.dy[i]) 844 except :844 except Exception as exc: 845 845 logger.error("check_data_logY: skipping point %g", self.y[i]) 846 logger.error( sys.exc_value)846 logger.error(exc) 847 847 848 848 self.x = tempx … … 996 996 self.zmax = zmax 997 997 else: 998 raise "zmin is greater or equal to zmax "998 raise("zmin is greater or equal to zmax ") 999 999 1000 1000 def render(self, plot, **kw): … … 1108 1108 Plottable.__init__(self) 1109 1109 msg = "Theory1D is no longer supported, please use Data1D and change symbol.\n" 1110 raise DeprecationWarning , msg1110 raise DeprecationWarning(msg) 1111 1111 1112 1112 class Fit1D(Plottable): -
src/sas/sasgui/plottools/toolbar.py
r20fa5fe r5251ec6 65 65 'Forward', 'Forward navigation view') 66 66 # todo: get new bitmap 67 self.AddCheckTool(self._NTB2_PAN, _load_bitmap('move.png'), 68 shortHelp='Pan', 69 longHelp='Pan with left, zoom with right') 70 self.AddCheckTool(self._NTB2_ZOOM, _load_bitmap('zoom_to_rect.png'), 71 shortHelp='Zoom', longHelp='Zoom to rectangle') 67 # todo: update with code from matplotlib/backends/backend_wx.py 68 is_phoenix = 'phoenix' in wx.PlatformInfo 69 if is_phoenix: # wx phoenix >= 4.0.0b2 70 self.AddCheckTool(self._NTB2_PAN, "Pan", _load_bitmap('move.png'), 71 shortHelp='Pan', 72 longHelp='Pan with left, zoom with right') 73 self.AddCheckTool(self._NTB2_ZOOM, "Zoom", _load_bitmap('zoom_to_rect.png'), 74 shortHelp='Zoom', longHelp='Zoom to rectangle') 75 else: 76 self.AddCheckTool(self._NTB2_PAN, _load_bitmap('move.png'), 77 shortHelp='Pan', 78 longHelp='Pan with left, zoom with right') 79 self.AddCheckTool(self._NTB2_ZOOM, _load_bitmap('zoom_to_rect.png'), 80 shortHelp='Zoom', longHelp='Zoom to rectangle') 72 81 73 82 self.AddSeparator() -
src/sas/sasgui/plottools/transform.py
r7432acb r5251ec6 24 24 """ 25 25 if not x > 0: 26 raise ValueError , "Transformation only accepts positive values."26 raise ValueError("Transformation only accepts positive values.") 27 27 else: 28 28 return x … … 50 50 """ 51 51 if not x >= 0: 52 raise ValueError , "square root of a negative value "52 raise ValueError("square root of a negative value ") 53 53 else: 54 54 return math.sqrt(x) … … 76 76 """ 77 77 if not x >= 0: 78 raise ValueError , "double square root of a negative value "78 raise ValueError("double square root of a negative value ") 79 79 else: 80 80 return math.sqrt(math.sqrt(x)) … … 90 90 """ 91 91 if not x > 0: 92 raise ValueError , "Log(x)of a negative value "92 raise ValueError("Log(x)of a negative value ") 93 93 else: 94 94 return math.log(x) … … 100 100 return 1 / x 101 101 else: 102 raise ValueError , "cannot divide by zero"102 raise ValueError("cannot divide by zero") 103 103 104 104 … … 109 109 return 1 / math.sqrt(y) 110 110 else: 111 raise ValueError , "transform.toOneOverSqrtX: cannot be computed"111 raise ValueError("transform.toOneOverSqrtX: cannot be computed") 112 112 113 113 … … 118 118 return math.log(y * (x ** 2)) 119 119 else: 120 raise ValueError , "transform.toLogYX2: cannot be computed"120 raise ValueError("transform.toLogYX2: cannot be computed") 121 121 122 122 … … 127 127 return math.log(math.pow(x, 4) * y) 128 128 else: 129 raise ValueError , "transform.toLogYX4: input error"129 raise ValueError("transform.toLogYX4: input error") 130 130 131 131 … … 149 149 """ 150 150 if not (x * y) > 0: 151 raise ValueError , "Log(X*Y)of a negative value "151 raise ValueError("Log(X*Y)of a negative value ") 152 152 else: 153 153 return math.log(x * y) … … 211 211 else: 212 212 msg = "transform.errFromX2: can't compute error of negative x" 213 raise ValueError , msg213 raise ValueError(msg) 214 214 215 215 … … 245 245 else: 246 246 msg = "transform.errFromX4: can't compute error of negative x" 247 raise ValueError , msg247 raise ValueError(msg) 248 248 249 249 … … 264 264 msg = "Transformation does not accept" 265 265 msg += " point that are consistent with zero." 266 raise ValueError , msg266 raise ValueError(msg) 267 267 if x != 0: 268 268 dx = dx / (x * math.log(10)) 269 269 else: 270 raise ValueError , "errToLogX: divide by zero"270 raise ValueError("errToLogX: divide by zero") 271 271 return dx 272 272 … … 287 287 dx = dx / x 288 288 else: 289 raise ValueError , "errToLogX: divide by zero"289 raise ValueError("errToLogX: divide by zero") 290 290 return dx 291 291 … … 312 312 msg = "Transformation does not accept point " 313 313 msg += " that are consistent with zero." 314 raise ValueError , msg314 raise ValueError(msg) 315 315 if x != 0 and y != 0: 316 316 if dx is None: … … 320 320 err = (dx / x) ** 2 + (dy / y) ** 2 321 321 else: 322 raise ValueError , "cannot compute this error"322 raise ValueError("cannot compute this error") 323 323 324 324 return math.sqrt(math.fabs(err)) … … 335 335 msg = "Transformation does not accept point" 336 336 msg += " that are consistent with zero." 337 raise ValueError , msg337 raise ValueError(msg) 338 338 if x > 0 and y > 0: 339 339 if dx is None: … … 343 343 err = (2.0 * dx / x) ** 2 + (dy / y) ** 2 344 344 else: 345 raise ValueError , "cannot compute this error"345 raise ValueError("cannot compute this error") 346 346 return math.sqrt(math.fabs(err)) 347 347 … … 357 357 err = dx / x ** 2 358 358 else: 359 raise ValueError , "Cannot compute this error"359 raise ValueError("Cannot compute this error") 360 360 return math.fabs(err) 361 361 … … 371 371 err = -1 / 2 * math.pow(x, -3.0 / 2.0) * dx 372 372 else: 373 raise ValueError , "Cannot compute this error"373 raise ValueError("Cannot compute this error") 374 374 return math.fabs(err) 375 375 … … 387 387 msg = "Transformation does not accept point " 388 388 msg += " that are consistent with zero." 389 raise ValueError , msg389 raise ValueError(msg) 390 390 if dx is None: 391 391 dx = 0 -
src/sas/sasview/sasview.py
r1270e3c r5251ec6 42 42 43 43 from sas.sasgui.guiframe.gui_manager import SasViewApp 44 from sas.sasgui.guiframe.gui_style import GUIFRAME_ICON 44 45 self.gui = SasViewApp(0) 46 GUIFRAME_ICON.load_icons() 45 47 if sys.platform == "darwin": 46 48 self.check_sasmodels_compiler() … … 228 230 logger.error("Wx version: error reading version") 229 231 230 from . import wxcruft 231 wxcruft.call_later_fix() 232 # TODO: Do we need the call later fix for wx 3? Or is it wx < 3 only? 233 if "phoenix" in wx.PlatformInfo: 234 #wx.NewId = wx.Window.NewControlId 235 pass 236 else: 237 from . import wxcruft 238 wxcruft.call_later_fix() 232 239 #wxcruft.trace_new_id() 233 240 #Always use private .matplotlib setup to avoid conflicts with other -
src/sas/sasview/welcome_panel.py
rb963b20 r5251ec6 2 2 Welcome page 3 3 """ 4 import wx5 import wx.aui6 import wx.lib.hyperlink7 4 import os.path 8 5 import os, sys 9 6 7 import wx 8 import wx.aui 9 try: 10 # CRUFT: wx 4 moved hyperlink to wx.lib.agw 11 from wx.lib import hyperlink 12 except ImportError: 13 from wx.lib.agw import hyperlink 10 14 from wx.lib.scrolledpanel import ScrolledPanel 11 15 … … 115 119 send_ticket += "help@sasview.org" 116 120 self.hyperlink_paper = \ 117 wx.lib.hyperlink.HyperLinkCtrl(self, -1,121 hyperlink.HyperLinkCtrl(self, -1, 118 122 send_ticket, URL=config._license) 119 123 -
src/sas/sasview/wxcruft.py
r914ba0a r5251ec6 4 4 import wx 5 5 from wx import Timer 6 import wx._misc7 6 8 7 def call_later_fix(): … … 16 15 17 16 def NewId(): 17 import wx._misc 18 18 id = wx._misc.NewId() 19 19 path, line, function = _get_caller()
Note: See TracChangeset
for help on using the changeset viewer.