Changeset d4cde37 in sasview
- Timestamp:
- Mar 30, 2019 6:15:51 PM (5 years ago)
- Branches:
- release-4.2.2
- Children:
- f5f8553, cc2cd5a
- Parents:
- 09d7021 (diff), 31c1bae (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent. - git-author:
- Paul Kienzle <pkienzle@…> (03/30/19 18:15:51)
- git-committer:
- GitHub <noreply@…> (03/30/19 18:15:51)
- Location:
- src/sas
- Files:
-
- 98 edited
Legend:
- Unmodified
- Added
- Removed
-
src/sas/sasgui/perspectives/fitting/fitpage.py
r82d88d5 rd4cde37 2365 2365 percent = self.dx_percent/100 2366 2366 if self._is_2D(): 2367 data.dqx_data[data.dqx_data == 0] = percent * data.qx_data2368 data.dq y_data[data.dqy_data == 0] = percent * data.qy_data2367 q = np.sqrt(data.qx_data**2 + data.qy_data**2) 2368 data.dqx_data = data.dqy_data = percent*q 2369 2369 else: 2370 2370 data.dx = percent * data.x -
src/sas/sasgui/guiframe/CategoryInstaller.py
ra26f67f rcb64d86 20 20 21 21 logger = logging.getLogger(__name__) 22 23 if sys.version_info[0] > 2: 24 def json_dump(obj, filename): 25 with open(filename, 'w', newline='\n') as fd: 26 json.dump(obj, fd) 27 else: # CRUFT: python 2.7 support 28 def json_dump(obj, filename): 29 with open(filename, 'wb') as fd: 30 json.dump(obj, fd) 22 31 23 32 class CategoryInstaller(object): … … 121 130 """ 122 131 _model_dict = {model.name: model for model in model_list} 123 _model_list = _model_dict.keys()132 _model_list = list(_model_dict.keys()) 124 133 125 134 serialized_file = None … … 146 155 by_model_dict.pop(model_name) 147 156 model_enabled_dict.pop(model_name) 148 except Exception :149 logger.error("CategoryInstaller: %s", sys.exc_value)157 except Exception as exc: 158 logger.error("CategoryInstaller: %s", exc) 150 159 else: 151 160 add_list.remove(model_name) … … 171 180 model_enabled_dict) 172 181 173 json .dump(master_category_dict, open(serialized_file, 'wb'))182 json_dump(master_category_dict, serialized_file) -
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
rdcd6efd r82d88d5 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 … … 275 277 return client size tuple 276 278 """ 277 width, height = self.GetClientSize Tuple()279 width, height = self.GetClientSize() 278 280 height -= 45 279 281 # Adjust toolbar height … … 350 352 try: 351 353 self.read_batch_tofile(file_name=path) 352 except :354 except Exception as exc: 353 355 msg = "Error occurred when reading the file; %s\n" % path 354 msg += "%s\n" % sys.exc_value 355 wx.PostEvent(self, StatusEvent(status=msg, 356 info="error")) 356 msg += "%s\n" % exc 357 wx.PostEvent(self, StatusEvent(status=msg, info="error")) 357 358 358 359 def read_batch_tofile(self, file_name): … … 694 695 try: 695 696 self.load_from_cmd(self._input_file) 696 except :697 except Exception as exc: 697 698 msg = "%s Cannot load file %s\n" % (str(APPLICATION_NAME), 698 699 str(self._input_file)) 699 msg += str( sys.exc_value) + '\n'700 msg += str(exc) + '\n' 700 701 logger.error(msg) 701 702 if self._data_panel is not None and len(self.plugins) > 0: … … 786 787 self._data_plugin = data_loader.Plugin() 787 788 plugins.append(self._data_plugin) 788 except :789 except Exception as exc: 789 790 msg = "ViewerFrame._get_local_plugins:" 790 msg += "cannot import dataloader plugin.\n %s" % sys.exc_value791 msg += "cannot import dataloader plugin.\n %s" % exc 791 792 logger.error(msg) 792 793 if style2 == GUIFRAME.PLOTTING_ON: … … 796 797 self._plotting_plugin = plotting.Plugin() 797 798 plugins.append(self._plotting_plugin) 798 except :799 except Exception as exc: 799 800 msg = "ViewerFrame._get_local_plugins:" 800 msg += "cannot import plotting plugin.\n %s" % sys.exc_value801 msg += "cannot import plotting plugin.\n %s" % exc 801 802 logger.error(msg) 802 803 … … 845 846 msg = "Found plug-in: %s" % module.PLUGIN_ID 846 847 logger.info(msg) 847 except :848 except Exception as exc: 848 849 msg = "Error accessing PluginPanel" 849 msg += " in %s\n %s" % (name, sys.exc_value)850 msg += " in %s\n %s" % (name, exc) 850 851 config.printEVT(msg) 851 except :852 msg = "ViewerFrame._find_plugins: %s" % sys.exc_value852 except Exception as exc: 853 msg = "ViewerFrame._find_plugins: %s" % exc 853 854 logger.error(msg) 854 855 finally: 855 856 if file is not None: 856 857 file.close() 857 except :858 except Exception as exc: 858 859 # Should raise and catch at a higher level and 859 860 # display error on status bar 860 logger.error( sys.exc_value)861 logger.error(exc) 861 862 862 863 return plugins … … 1588 1589 """ 1589 1590 # This CallAfter fixes many crashes on MAC. 1590 wx.CallAfter(self.sb.set_status, evt )1591 wx.CallAfter(self.sb.set_status, evt.Clone()) 1591 1592 1592 1593 def on_view(self, evt): … … 1632 1633 ID = str(uid) 1633 1634 config.printEVT("delete_panel: %s" % ID) 1634 if ID in self.panels .keys():1635 if ID in self.panels: 1635 1636 self.panel_on_focus = None 1636 1637 panel = self.panels[ID] … … 1644 1645 1645 1646 # delete uid number not str(uid) 1646 if ID in self.plot_panels .keys():1647 if ID in self.plot_panels: 1647 1648 del self.plot_panels[ID] 1648 if ID in self.panels .keys():1649 if ID in self.panels: 1649 1650 del self.panels[ID] 1650 1651 else: … … 1680 1681 try: 1681 1682 reader.read(path) 1682 except :1683 except Exception as exc: 1683 1684 msg = "DataLoader Error: Encounted Non-ASCII character" 1684 msg += "\n(%s)" % sys.exc_value1685 msg += "\n(%s)" % exc 1685 1686 wx.PostEvent(self, StatusEvent(status=msg, 1686 1687 info="error", … … 1763 1764 1764 1765 self.add_data(data_list=output) 1765 except :1766 except Exception as exc: 1766 1767 error_message = "Error while loading" 1767 1768 error_message += " Data from cmd:\n %s\n" % str(path) 1768 error_message += str( sys.exc_value) + "\n"1769 error_message += str(exc) + "\n" 1769 1770 logger.error(error_message) 1770 1771 … … 1784 1785 else: 1785 1786 return 1786 except :1787 except Exception as exc: 1787 1788 error_message = "Error while loading" 1788 1789 error_message += " Data folder from cmd:\n %s\n" % str(path) 1789 error_message += str( sys.exc_value) + "\n"1790 error_message += str(exc) + "\n" 1790 1791 logger.error(error_message) 1791 1792 … … 1854 1855 self._data_panel.selection_cbox.SetValue('Select all Data') 1855 1856 self._data_panel._on_selection_type(None) 1856 for _, theory_dict in self._data_panel.list_cb_theory.ite ritems():1857 for key, value in theory_dict.ite ritems():1857 for _, theory_dict in self._data_panel.list_cb_theory.items(): 1858 for key, value in theory_dict.items(): 1858 1859 item, _, _ = value 1859 1860 item.Check(True) … … 1963 1964 # case of a panel with multi-pages 1964 1965 if hasattr(panel, "opened_pages"): 1965 for _, page in panel.opened_pages.ite ritems():1966 for _, page in panel.opened_pages.items(): 1966 1967 data = page.get_data() 1967 1968 # state must be cloned … … 2085 2086 msg += " Please try again later." 2086 2087 self.SetStatusText(msg) 2087 elif cmp(version, config.__version__) > 0:2088 elif version > config.__version__: 2088 2089 msg = "Version %s is available! " % str(version) 2089 2090 if not standalone: … … 2101 2102 msg += " of %s" % str(config.__appname__) 2102 2103 self.SetStatusText(msg) 2103 except :2104 except Exception as exc: 2104 2105 msg = "guiframe: could not get latest application" 2105 msg += " version number\n %s" % sys.exc_value2106 msg += " version number\n %s" % exc 2106 2107 logger.error(msg) 2107 2108 if not standalone: … … 2143 2144 # S King, Sep 2018 2144 2145 2145 from documentation_window import DocumentationWindow2146 from .documentation_window import DocumentationWindow 2146 2147 _TreeLocation = "user/release.html" 2147 2148 DocumentationWindow(self, -1, _TreeLocation, "", … … 2164 2165 # S King, Sep 2018 2165 2166 2166 from documentation_window import DocumentationWindow2167 from .documentation_window import DocumentationWindow 2167 2168 _TreeLocation = "user/tutorial.html" 2168 2169 DocumentationWindow(self, -1, _TreeLocation, "", … … 2179 2180 # Running SasView "in-place" using run.py means the docs will be in a 2180 2181 # different place than they would otherwise. 2181 from documentation_window import DocumentationWindow2182 from .documentation_window import DocumentationWindow 2182 2183 _TreeLocation = "user/user.html" 2183 2184 DocumentationWindow(self, -1, _TreeLocation, "", … … 2227 2228 if (style == GUIFRAME.MANAGER_ON) \ 2228 2229 and self.panels[item] == self._data_panel: 2229 if 'data_panel' in self.panels .keys():2230 if 'data_panel' in self.panels: 2230 2231 frame = self.panels['data_panel'].get_frame() 2231 2232 if frame is None: … … 2279 2280 # set data in the data panel 2280 2281 if self._data_panel is not None: 2281 data_state = self._data_manager.get_data_state( data_list.keys())2282 data_state = self._data_manager.get_data_state(list(data_list.keys())) 2282 2283 self._data_panel.load_data_list(data_state) 2283 2284 # if the data panel is shown wait for the user to press a button … … 2291 2292 else: 2292 2293 # automatically send that to the current perspective 2293 self.set_data(data_id= data_list.keys())2294 self.set_data(data_id=list(data_list.keys())) 2294 2295 2295 2296 def set_data(self, data_id, theory_id=None): … … 2299 2300 list_data, _ = self._data_manager.get_by_id(data_id) 2300 2301 if self._current_perspective is not None: 2301 self._current_perspective.set_data(list _data.values())2302 self._current_perspective.set_data(list(list_data.values())) 2302 2303 2303 2304 else: … … 2311 2312 if self._current_perspective is not None: 2312 2313 try: 2313 self._current_perspective.set_theory(list _theory.values())2314 except :2315 msg = "Guiframe set_theory: \n" + str( sys.exc_value)2314 self._current_perspective.set_theory(list(list_theory.values())) 2315 except Exception as exc: 2316 msg = "Guiframe set_theory: \n" + str(exc) 2316 2317 logger.info(msg) 2317 2318 wx.PostEvent(self, StatusEvent(status=msg, info="error")) … … 2327 2328 data_list, _ = self._data_manager.get_by_id(data_id) 2328 2329 _, temp_list_theory = self._data_manager.get_by_id(theory_id) 2329 total_plot_list = data_list.values()2330 total_plot_list = list(data_list.values()) 2330 2331 for item in temp_list_theory.values(): 2331 2332 theory_data, theory_state = item … … 2376 2377 data_list, _ = self._data_manager.get_by_id(data_id) 2377 2378 _, temp_list_theory = self._data_manager.get_by_id(theory_id) 2378 total_plot_list = data_list.values()2379 total_plot_list = list(data_list.values()) 2379 2380 for item in temp_list_theory.values(): 2380 2381 theory_data, theory_state = item … … 2399 2400 group_id=("res" + str(id)), 2400 2401 action='remove')) 2401 except :2402 logger.error( sys.exc_value)2402 except Exception as exc: 2403 logger.error(exc) 2403 2404 2404 2405 def save_data1d(self, data, fname): … … 2504 2505 wx.PostEvent(self, StatusEvent(status=msg, 2505 2506 info="error")) 2506 raise ValueError , msg2507 raise ValueError(msg) 2507 2508 # text = str(data) 2508 2509 text = data.__str__() … … 2535 2536 dy_val, 2536 2537 dx_val) 2537 from pdfview import TextFrame2538 from .pdfview import TextFrame 2538 2539 frame = TextFrame(None, -1, "Data Info: %s" % data.name, text) 2539 2540 # put icon … … 2627 2628 break 2628 2629 2629 from pdfview import TextFrame2630 from .pdfview import TextFrame 2630 2631 frame = TextFrame(None, -1, "Data Info: %s" % data.name, text) 2631 2632 # put icon … … 2694 2695 check = "Theory1D" 2695 2696 is_theory = len(self.panel_on_focus.plots) <= 1 and \ 2696 self.panel_on_focus.plots.values()[0].__class__.__name__ == check2697 list(self.panel_on_focus.plots.values())[0].__class__.__name__ == check 2697 2698 2698 2699 is_data2d = hasattr(new_plot, 'data') … … 3210 3211 else: 3211 3212 self.frame.Show() 3212 except :3213 except Exception as exc: 3213 3214 if self.s_screen is not None: 3214 3215 self.s_screen.Close() 3215 3216 msg = "Cannot display splash screen\n" 3216 msg += str( sys.exc_value)3217 msg += str(exc) 3217 3218 logger.error(msg) 3218 3219 self.frame.Show() … … 3269 3270 if os.path.isfile(file_path): 3270 3271 os.remove(file_path) 3271 except :3272 except Exception as exc: 3272 3273 logger.error("gui_manager.clean_plugin_models:\n %s" 3273 % sys.exc_value)3274 % exc) 3274 3275 3275 3276 def set_manager(self, manager): … … 3364 3365 path=SPLASH_SCREEN_PATH): 3365 3366 """Displays the splash screen. It will exactly cover the main frame.""" 3367 try: 3368 from wx.adv import SplashScreen, SPLASH_TIMEOUT, SPLASH_CENTRE_ON_SCREEN 3369 except ImportError: 3370 # CRUFT: wx 4 moved SplashScreen from wx to wx.adv 3371 from wx import SplashScreen, SPLASH_TIMEOUT, SPLASH_CENTRE_ON_SCREEN 3366 3372 3367 3373 # Prepare the picture. On a 2GHz intel cpu, this takes about a second. … … 3380 3386 # Note that on Linux, the timeout appears to occur immediately in which 3381 3387 # case the splash screen disappears upon entering the event loop. 3382 s_screen = wx.SplashScreen(bitmap=bm,3383 splashStyle=(wx.SPLASH_TIMEOUT |3384 wx.SPLASH_CENTRE_ON_SCREEN),3385 3386 3387 3388 3389 3390 3388 s_screen = SplashScreen(bitmap=bm, 3389 splashStyle=(SPLASH_TIMEOUT | 3390 SPLASH_CENTRE_ON_SCREEN), 3391 style=(wx.SIMPLE_BORDER | 3392 wx.FRAME_NO_TASKBAR | 3393 wx.FRAME_FLOAT_ON_PARENT), 3394 milliseconds=SS_MAX_DISPLAY_TIME, 3395 parent=parent, 3396 id=wx.ID_ANY) 3391 3397 from sas.sasgui.guiframe.gui_statusbar import SPageStatusbar 3392 3398 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
r5218180 r82d88d5 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
r1752f38 r82d88d5 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
ref74a8b r82d88d5 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 rcb64d86 12 12 import logging 13 13 import traceback 14 from Queue import Queue 14 try: # CRUFT: python 2.x 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/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
ra5cffe5 r98b9f32 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 … … 778 778 # Note: this is used to set the data weights for the fit based on 779 779 # the weight selection in the GUI. 780 if uid in self.page_finder .keys():780 if uid in self.page_finder: 781 781 self.page_finder[uid].set_weight(flag=flag, is2d=is2d) 782 782 … … 791 791 :param qmax: maximum value of the fit range 792 792 """ 793 if uid in self.page_finder .keys():793 if uid in self.page_finder: 794 794 self.page_finder[uid].set_range(qmin=qmin, qmax=qmax, fid=fid) 795 795 … … 802 802 :param uid: the id related to a page containing fitting information 803 803 """ 804 if uid in self.page_finder .keys():804 if uid in self.page_finder: 805 805 self.page_finder[uid].schedule_tofit(value) 806 806 … … 821 821 """ 822 822 sim_page_id = self.sim_page.uid 823 for uid, value in self.page_finder.ite ritems():823 for uid, value in self.page_finder.items(): 824 824 if uid != sim_page_id and uid != self.batch_page.uid: 825 825 model_list = value.get_model() … … 886 886 Stop the fit 887 887 """ 888 if uid in self.fit_thread_list .keys():888 if uid in self.fit_thread_list: 889 889 calc_fit = self.fit_thread_list[uid] 890 890 if calc_fit is not None and calc_fit.isrunning(): … … 898 898 batch_flag = self.batch_page is not None and uid == self.batch_page.uid 899 899 if sim_flag or batch_flag: 900 for uid, value in self.page_finder.ite ritems():900 for uid, value in self.page_finder.items(): 901 901 if value.get_scheduled() == 1: 902 if uid in self.fit_panel.opened_pages .keys():902 if uid in self.fit_panel.opened_pages: 903 903 panel = self.fit_panel.opened_pages[uid] 904 904 panel._on_fit_complete() … … 917 917 :param draw: Determine if the theory needs to be plot 918 918 """ 919 if uid not in self.page_finder .keys():919 if uid not in self.page_finder: 920 920 return 921 921 self.page_finder[uid].enable_smearing(flag=enable_smearer) … … 928 928 msg += "Got data = %s .\n" % str(data) 929 929 return 930 #raise ValueError , msg930 #raise ValueError(msg) 931 931 model = self.page_finder[uid].get_model(fid=fid) 932 932 if model is None: … … 1030 1030 list_page_id = [] 1031 1031 fit_id = 0 1032 for page_id, page_info in self.page_finder.ite ritems():1032 for page_id, page_info in self.page_finder.items(): 1033 1033 # For simulfit (uid give with None), do for-loop 1034 1034 # if uid is specified (singlefit), do it only on the page. … … 1057 1057 1058 1058 pars = [str(element[1]) for element in page.param_toFit] 1059 fitproblem_list = page_info.values() 1060 for fitproblem in fitproblem_list: 1059 for fitproblem in page_info.values(): 1061 1060 if sim_fitter is None: 1062 1061 fitter = Fit() … … 1077 1076 wx.PostEvent(self.parent, evt) 1078 1077 return True 1079 except :1078 except Exception as exc: 1080 1079 raise 1081 msg = "Fitting error: %s" % str(sys.exc_value)1080 msg = "Fitting error: %s" % exc 1082 1081 evt = StatusEvent(status=msg, info="error", type="stop") 1083 1082 wx.PostEvent(self.parent, evt) … … 1136 1135 :param fid: the id of the fitproblem(data, model, range,etc) 1137 1136 """ 1138 if uid not in self.page_finder .keys():1137 if uid not in self.page_finder: 1139 1138 return 1140 1139 fitproblemList = self.page_finder[uid].get_fit_problem(fid) … … 1181 1180 evt = StatusEvent(status=msg, info="warning") 1182 1181 wx.PostEvent(self.parent, evt) 1183 except Exception :1184 msg = "Creating Fit page: %s" % sys.exc_value1182 except Exception as exc: 1183 msg = "Creating Fit page: %s" % exc 1185 1184 wx.PostEvent(self.parent, StatusEvent(status=msg, info="error")) 1186 1185 … … 1262 1261 # case that uid is not specified 1263 1262 if uid is None: 1264 for page_id in self.page_finder .keys():1263 for page_id in self.page_finder: 1265 1264 self.page_finder[page_id].schedule_tofit(value) 1266 1265 # when uid is given 1267 1266 else: 1268 if uid in self.page_finder .keys():1267 if uid in self.page_finder: 1269 1268 self.page_finder[uid].schedule_tofit(value) 1270 1269 … … 1300 1299 panel = self.plot_panel 1301 1300 if panel is None: 1302 raise ValueError , "Fitting:_onSelect: NonType panel"1301 raise ValueError("Fitting:_onSelect: NonType panel") 1303 1302 Plugin.on_perspective(self, event=event) 1304 1303 self.select_data(panel) … … 1333 1332 """ 1334 1333 uid = page_id[0] 1335 if uid in self.fit_thread_list .keys():1334 if uid in self.fit_thread_list: 1336 1335 del self.fit_thread_list[uid] 1337 1336 … … 1359 1358 #get all fittable parameters of the current model 1360 1359 for param in model.getParamList(): 1361 if param not in batch_outputs .keys():1360 if param not in batch_outputs: 1362 1361 batch_outputs[param] = [] 1363 1362 for param in model.getDispParamList(): 1364 1363 if not model.is_fittable(param) and \ 1365 param in batch_outputs .keys():1364 param in batch_outputs: 1366 1365 del batch_outputs[param] 1367 1366 # Add fitted parameters and their error 1368 1367 for param in res.param_list: 1369 if param not in batch_outputs .keys():1368 if param not in batch_outputs: 1370 1369 batch_outputs[param] = [] 1371 1370 err_param = "error on %s" % str(param) 1372 if err_param not in batch_inputs .keys():1371 if err_param not in batch_inputs: 1373 1372 batch_inputs[err_param] = [] 1374 1373 msg = "" … … 1524 1523 model = fitproblem.get_model() 1525 1524 #fill batch result information 1526 if "Data" not in batch_outputs .keys():1525 if "Data" not in batch_outputs: 1527 1526 batch_outputs["Data"] = [] 1528 1527 cell = BatchCell() … … 1553 1552 cell.object = [data, theory_data] 1554 1553 batch_outputs["Data"].append(cell) 1555 for key, value in data.meta_data.ite ritems():1556 if key not in batch_inputs .keys():1554 for key, value in data.meta_data.items(): 1555 if key not in batch_inputs: 1557 1556 batch_inputs[key] = [] 1558 1557 #if key.lower().strip() != "loader": … … 1560 1559 param = "temperature" 1561 1560 if hasattr(data.sample, param): 1562 if param not in batch_inputs .keys():1561 if param not in batch_inputs: 1563 1562 batch_inputs[param] = [] 1564 1563 batch_inputs[param].append(data.sample.temperature) … … 1631 1630 wx.PostEvent(self.parent, evt) 1632 1631 1633 except Exception: 1634 msg = ("Fit completed but the following error occurred: %s" 1635 % sys.exc_value) 1632 except Exception as exc: 1633 msg = "Fit completed but the following error occurred: %s" % exc 1636 1634 #msg = "\n".join((traceback.format_exc(), msg)) 1637 1635 evt = StatusEvent(status=msg, info="warning", type="stop") … … 1721 1719 if model is None: 1722 1720 return 1723 if uid not in self.page_finder .keys():1721 if uid not in self.page_finder: 1724 1722 return 1725 1723 # save the name containing the data name with the appropriate model … … 2078 2076 source=source) 2079 2077 self.calc_1D.queue() 2080 except :2078 except Exception as exc: 2081 2079 msg = " Error occurred when drawing %s Model 1D: " % model.name 2082 msg += " %s" % sys.exc_value2080 msg += " %s" % exc 2083 2081 wx.PostEvent(self.parent, StatusEvent(status=msg)) 2084 2082 -
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)