1 | """ |
---|
2 | Global defaults and various utility functions usable by the general GUI |
---|
3 | """ |
---|
4 | |
---|
5 | import os |
---|
6 | import sys |
---|
7 | import imp |
---|
8 | import warnings |
---|
9 | import webbrowser |
---|
10 | import urlparse |
---|
11 | |
---|
12 | warnings.simplefilter("ignore") |
---|
13 | import logging |
---|
14 | |
---|
15 | from PyQt4 import QtCore |
---|
16 | from PyQt4 import QtGui |
---|
17 | |
---|
18 | # Translate event handlers |
---|
19 | #from sas.sasgui.guiframe.events import EVT_CATEGORY |
---|
20 | #from sas.sasgui.guiframe.events import EVT_STATUS |
---|
21 | #from sas.sasgui.guiframe.events import EVT_APPEND_BOOKMARK |
---|
22 | #from sas.sasgui.guiframe.events import EVT_PANEL_ON_FOCUS |
---|
23 | #from sas.sasgui.guiframe.events import EVT_NEW_LOAD_DATA |
---|
24 | #from sas.sasgui.guiframe.events import EVT_NEW_COLOR |
---|
25 | #from sas.sasgui.guiframe.events import StatusEvent |
---|
26 | #from sas.sasgui.guiframe.events import NewPlotEvent |
---|
27 | |
---|
28 | from periodictable import formula as Formula |
---|
29 | |
---|
30 | from sas.sasgui.plottools import transform |
---|
31 | from sas.sasgui.plottools.convert_units import convert_unit |
---|
32 | from sas.sasgui.guiframe.dataFitting import Data1D |
---|
33 | from sas.sasgui.guiframe.dataFitting import Data2D |
---|
34 | from sas.sascalc.dataloader.loader import Loader |
---|
35 | |
---|
36 | |
---|
37 | def get_app_dir(): |
---|
38 | """ |
---|
39 | The application directory is the one where the default custom_config.py |
---|
40 | file resides. |
---|
41 | |
---|
42 | :returns: app_path - the path to the applicatin directory |
---|
43 | """ |
---|
44 | # First, try the directory of the executable we are running |
---|
45 | app_path = sys.path[0] |
---|
46 | if os.path.isfile(app_path): |
---|
47 | app_path = os.path.dirname(app_path) |
---|
48 | if os.path.isfile(os.path.join(app_path, "custom_config.py")): |
---|
49 | app_path = os.path.abspath(app_path) |
---|
50 | #logging.info("Using application path: %s", app_path) |
---|
51 | return app_path |
---|
52 | |
---|
53 | # Next, try the current working directory |
---|
54 | if os.path.isfile(os.path.join(os.getcwd(), "custom_config.py")): |
---|
55 | #logging.info("Using application path: %s", os.getcwd()) |
---|
56 | return os.path.abspath(os.getcwd()) |
---|
57 | |
---|
58 | # Finally, try the directory of the sasview module |
---|
59 | # TODO: gui_manager will have to know about sasview until we |
---|
60 | # clean all these module variables and put them into a config class |
---|
61 | # that can be passed by sasview.py. |
---|
62 | #logging.info(sys.executable) |
---|
63 | #logging.info(str(sys.argv)) |
---|
64 | from sas import sasview as sasview |
---|
65 | app_path = os.path.dirname(sasview.__file__) |
---|
66 | #logging.info("Using application path: %s", app_path) |
---|
67 | return app_path |
---|
68 | |
---|
69 | def get_user_directory(): |
---|
70 | """ |
---|
71 | Returns the user's home directory |
---|
72 | """ |
---|
73 | userdir = os.path.join(os.path.expanduser("~"), ".sasview") |
---|
74 | if not os.path.isdir(userdir): |
---|
75 | os.makedirs(userdir) |
---|
76 | return userdir |
---|
77 | |
---|
78 | def _find_local_config(confg_file, path): |
---|
79 | """ |
---|
80 | Find configuration file for the current application |
---|
81 | """ |
---|
82 | config_module = None |
---|
83 | fObj = None |
---|
84 | try: |
---|
85 | fObj, path_config, descr = imp.find_module(confg_file, [path]) |
---|
86 | config_module = imp.load_module(confg_file, fObj, path_config, descr) |
---|
87 | except ImportError: |
---|
88 | pass |
---|
89 | #logging.error("Error loading %s/%s: %s" % (path, confg_file, sys.exc_value)) |
---|
90 | finally: |
---|
91 | if fObj is not None: |
---|
92 | fObj.close() |
---|
93 | #logging.info("GuiManager loaded %s/%s" % (path, confg_file)) |
---|
94 | return config_module |
---|
95 | |
---|
96 | # Get APP folder |
---|
97 | PATH_APP = get_app_dir() |
---|
98 | DATAPATH = PATH_APP |
---|
99 | |
---|
100 | # GUI always starts from the App folder |
---|
101 | #os.chdir(PATH_APP) |
---|
102 | # Read in the local config, which can either be with the main |
---|
103 | # application or in the installation directory |
---|
104 | config = _find_local_config('local_config', PATH_APP) |
---|
105 | |
---|
106 | if config is None: |
---|
107 | config = _find_local_config('local_config', os.getcwd()) |
---|
108 | if config is None: |
---|
109 | # Didn't find local config, load the default |
---|
110 | import sas.sasgui.guiframe.config as config |
---|
111 | #logging.info("using default local_config") |
---|
112 | else: |
---|
113 | pass |
---|
114 | #logging.info("found local_config in %s", os.getcwd()) |
---|
115 | else: |
---|
116 | pass |
---|
117 | #logging.info("found local_config in %s", PATH_APP) |
---|
118 | |
---|
119 | |
---|
120 | from sas.sasgui.guiframe.customdir import SetupCustom |
---|
121 | c_conf_dir = SetupCustom().setup_dir(PATH_APP) |
---|
122 | custom_config = _find_local_config('custom_config', c_conf_dir) |
---|
123 | if custom_config is None: |
---|
124 | custom_config = _find_local_config('custom_config', os.getcwd()) |
---|
125 | if custom_config is None: |
---|
126 | msgConfig = "Custom_config file was not imported" |
---|
127 | #logging.info(msgConfig) |
---|
128 | else: |
---|
129 | pass |
---|
130 | #logging.info("using custom_config in %s", os.getcwd()) |
---|
131 | else: |
---|
132 | pass |
---|
133 | #logging.info("using custom_config from %s", c_conf_dir) |
---|
134 | |
---|
135 | #read some constants from config |
---|
136 | APPLICATION_STATE_EXTENSION = config.APPLICATION_STATE_EXTENSION |
---|
137 | APPLICATION_NAME = config.__appname__ |
---|
138 | SPLASH_SCREEN_PATH = config.SPLASH_SCREEN_PATH |
---|
139 | WELCOME_PANEL_ON = config.WELCOME_PANEL_ON |
---|
140 | SPLASH_SCREEN_WIDTH = config.SPLASH_SCREEN_WIDTH |
---|
141 | SPLASH_SCREEN_HEIGHT = config.SPLASH_SCREEN_HEIGHT |
---|
142 | SS_MAX_DISPLAY_TIME = config.SS_MAX_DISPLAY_TIME |
---|
143 | if not WELCOME_PANEL_ON: |
---|
144 | WELCOME_PANEL_SHOW = False |
---|
145 | else: |
---|
146 | WELCOME_PANEL_SHOW = True |
---|
147 | try: |
---|
148 | DATALOADER_SHOW = custom_config.DATALOADER_SHOW |
---|
149 | TOOLBAR_SHOW = custom_config.TOOLBAR_SHOW |
---|
150 | FIXED_PANEL = custom_config.FIXED_PANEL |
---|
151 | if WELCOME_PANEL_ON: |
---|
152 | WELCOME_PANEL_SHOW = custom_config.WELCOME_PANEL_SHOW |
---|
153 | PLOPANEL_WIDTH = custom_config.PLOPANEL_WIDTH |
---|
154 | DATAPANEL_WIDTH = custom_config.DATAPANEL_WIDTH |
---|
155 | GUIFRAME_WIDTH = custom_config.GUIFRAME_WIDTH |
---|
156 | GUIFRAME_HEIGHT = custom_config.GUIFRAME_HEIGHT |
---|
157 | CONTROL_WIDTH = custom_config.CONTROL_WIDTH |
---|
158 | CONTROL_HEIGHT = custom_config.CONTROL_HEIGHT |
---|
159 | DEFAULT_PERSPECTIVE = custom_config.DEFAULT_PERSPECTIVE |
---|
160 | CLEANUP_PLOT = custom_config.CLEANUP_PLOT |
---|
161 | # custom open_path |
---|
162 | open_folder = custom_config.DEFAULT_OPEN_FOLDER |
---|
163 | if open_folder != None and os.path.isdir(open_folder): |
---|
164 | DEFAULT_OPEN_FOLDER = os.path.abspath(open_folder) |
---|
165 | else: |
---|
166 | DEFAULT_OPEN_FOLDER = PATH_APP |
---|
167 | except AttributeError: |
---|
168 | DATALOADER_SHOW = True |
---|
169 | TOOLBAR_SHOW = True |
---|
170 | FIXED_PANEL = True |
---|
171 | WELCOME_PANEL_SHOW = False |
---|
172 | PLOPANEL_WIDTH = config.PLOPANEL_WIDTH |
---|
173 | DATAPANEL_WIDTH = config.DATAPANEL_WIDTH |
---|
174 | GUIFRAME_WIDTH = config.GUIFRAME_WIDTH |
---|
175 | GUIFRAME_HEIGHT = config.GUIFRAME_HEIGHT |
---|
176 | CONTROL_WIDTH = -1 |
---|
177 | CONTROL_HEIGHT = -1 |
---|
178 | DEFAULT_PERSPECTIVE = None |
---|
179 | CLEANUP_PLOT = False |
---|
180 | DEFAULT_OPEN_FOLDER = PATH_APP |
---|
181 | |
---|
182 | DEFAULT_STYLE = config.DEFAULT_STYLE |
---|
183 | |
---|
184 | PLUGIN_STATE_EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS |
---|
185 | OPEN_SAVE_MENU = config.OPEN_SAVE_PROJECT_MENU |
---|
186 | VIEW_MENU = config.VIEW_MENU |
---|
187 | EDIT_MENU = config.EDIT_MENU |
---|
188 | extension_list = [] |
---|
189 | if APPLICATION_STATE_EXTENSION is not None: |
---|
190 | extension_list.append(APPLICATION_STATE_EXTENSION) |
---|
191 | EXTENSIONS = PLUGIN_STATE_EXTENSIONS + extension_list |
---|
192 | try: |
---|
193 | PLUGINS_WLIST = '|'.join(config.PLUGINS_WLIST) |
---|
194 | except AttributeError: |
---|
195 | PLUGINS_WLIST = '' |
---|
196 | APPLICATION_WLIST = config.APPLICATION_WLIST |
---|
197 | IS_WIN = True |
---|
198 | IS_LINUX = False |
---|
199 | CLOSE_SHOW = True |
---|
200 | TIME_FACTOR = 2 |
---|
201 | NOT_SO_GRAPH_LIST = ["BoxSum"] |
---|
202 | |
---|
203 | class Communicate(QtCore.QObject): |
---|
204 | """ |
---|
205 | Utility class for tracking of the Qt signals |
---|
206 | """ |
---|
207 | # File got successfully read |
---|
208 | fileReadSignal = QtCore.pyqtSignal(list) |
---|
209 | |
---|
210 | # Open File returns "list" of paths |
---|
211 | fileDataReceivedSignal = QtCore.pyqtSignal(dict) |
---|
212 | |
---|
213 | # Update Main window status bar with "str" |
---|
214 | # Old "StatusEvent" |
---|
215 | statusBarUpdateSignal = QtCore.pyqtSignal(str) |
---|
216 | |
---|
217 | # Send data to the current perspective |
---|
218 | updatePerspectiveWithDataSignal = QtCore.pyqtSignal(list) |
---|
219 | |
---|
220 | # New data in current perspective |
---|
221 | updateModelFromPerspectiveSignal = QtCore.pyqtSignal(QtGui.QStandardItem) |
---|
222 | |
---|
223 | # New theory data in current perspective |
---|
224 | updateTheoryFromPerspectiveSignal = QtCore.pyqtSignal(QtGui.QStandardItem) |
---|
225 | |
---|
226 | # New plot requested from the GUI manager |
---|
227 | # Old "NewPlotEvent" |
---|
228 | plotRequestedSignal = QtCore.pyqtSignal(str) |
---|
229 | |
---|
230 | # Plot update requested from a perspective |
---|
231 | plotUpdateSignal = QtCore.pyqtSignal(list) |
---|
232 | |
---|
233 | # Progress bar update value |
---|
234 | progressBarUpdateSignal = QtCore.pyqtSignal(int) |
---|
235 | |
---|
236 | # Workspace charts added/removed |
---|
237 | activeGraphsSignal = QtCore.pyqtSignal(list) |
---|
238 | |
---|
239 | # Current workspace chart's name changed |
---|
240 | activeGraphName = QtCore.pyqtSignal(tuple) |
---|
241 | |
---|
242 | # Current perspective changed |
---|
243 | perspectiveChangedSignal = QtCore.pyqtSignal(str) |
---|
244 | |
---|
245 | |
---|
246 | def updateModelItemWithPlot(item, update_data, name=""): |
---|
247 | """ |
---|
248 | Adds a checkboxed row named "name" to QStandardItem |
---|
249 | Adds QVariant 'update_data' to that row. |
---|
250 | """ |
---|
251 | assert isinstance(item, QtGui.QStandardItem) |
---|
252 | assert isinstance(update_data, QtCore.QVariant) |
---|
253 | py_update_data = update_data.toPyObject() |
---|
254 | |
---|
255 | # Check if data with the same ID is already present |
---|
256 | for index in range(item.rowCount()): |
---|
257 | plot_item = item.child(index) |
---|
258 | if plot_item.isCheckable(): |
---|
259 | plot_data = plot_item.child(0).data().toPyObject() |
---|
260 | if plot_data.id is not None and plot_data.id == py_update_data.id: |
---|
261 | # replace data section in item |
---|
262 | plot_item.child(0).setData(update_data) |
---|
263 | plot_item.setText(name) |
---|
264 | # Force redisplay |
---|
265 | return |
---|
266 | |
---|
267 | # Create the new item |
---|
268 | checkbox_item = createModelItemWithPlot(update_data, name) |
---|
269 | |
---|
270 | # Append the new row to the main item |
---|
271 | item.appendRow(checkbox_item) |
---|
272 | |
---|
273 | def createModelItemWithPlot(update_data, name=""): |
---|
274 | """ |
---|
275 | Creates a checkboxed QStandardItem named "name" |
---|
276 | Adds QVariant 'update_data' to that row. |
---|
277 | """ |
---|
278 | assert isinstance(update_data, QtCore.QVariant) |
---|
279 | py_update_data = update_data.toPyObject() |
---|
280 | |
---|
281 | checkbox_item = QtGui.QStandardItem() |
---|
282 | checkbox_item.setCheckable(True) |
---|
283 | checkbox_item.setCheckState(QtCore.Qt.Checked) |
---|
284 | checkbox_item.setText(name) |
---|
285 | |
---|
286 | # Add "Info" item |
---|
287 | if isinstance(py_update_data, (Data1D, Data2D)): |
---|
288 | # If Data1/2D added - extract Info from it |
---|
289 | info_item = infoFromData(py_update_data) |
---|
290 | else: |
---|
291 | # otherwise just add a naked item |
---|
292 | info_item = QtGui.QStandardItem("Info") |
---|
293 | |
---|
294 | # Add the actual Data1D/Data2D object |
---|
295 | object_item = QtGui.QStandardItem() |
---|
296 | object_item.setData(update_data) |
---|
297 | |
---|
298 | # Set the data object as the first child |
---|
299 | checkbox_item.setChild(0, object_item) |
---|
300 | |
---|
301 | # Set info_item as the second child |
---|
302 | checkbox_item.setChild(1, info_item) |
---|
303 | |
---|
304 | # And return the newly created item |
---|
305 | return checkbox_item |
---|
306 | |
---|
307 | def updateModelItem(item, update_data, name=""): |
---|
308 | """ |
---|
309 | Adds a simple named child to QStandardItem |
---|
310 | """ |
---|
311 | assert isinstance(item, QtGui.QStandardItem) |
---|
312 | assert isinstance(update_data, list) |
---|
313 | |
---|
314 | # Add the actual Data1D/Data2D object |
---|
315 | object_item = QtGui.QStandardItem() |
---|
316 | object_item.setText(name) |
---|
317 | object_item.setData(QtCore.QVariant(update_data)) |
---|
318 | |
---|
319 | # Append the new row to the main item |
---|
320 | item.appendRow(object_item) |
---|
321 | |
---|
322 | |
---|
323 | def plotsFromCheckedItems(model_item): |
---|
324 | """ |
---|
325 | Returns the list of plots for items in the model which are checked |
---|
326 | """ |
---|
327 | assert isinstance(model_item, QtGui.QStandardItemModel) |
---|
328 | |
---|
329 | plot_data = [] |
---|
330 | # Iterate over model looking for items with checkboxes |
---|
331 | for index in range(model_item.rowCount()): |
---|
332 | item = model_item.item(index) |
---|
333 | if item.isCheckable() and item.checkState() == QtCore.Qt.Checked: |
---|
334 | # TODO: assure item type is correct (either data1/2D or Plotter) |
---|
335 | plot_data.append((item, item.child(0).data().toPyObject())) |
---|
336 | # Going 1 level deeper only |
---|
337 | for index_2 in range(item.rowCount()): |
---|
338 | item_2 = item.child(index_2) |
---|
339 | if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked: |
---|
340 | # TODO: assure item type is correct (either data1/2D or Plotter) |
---|
341 | plot_data.append((item_2, item_2.child(0).data().toPyObject())) |
---|
342 | |
---|
343 | return plot_data |
---|
344 | |
---|
345 | def infoFromData(data): |
---|
346 | """ |
---|
347 | Given Data1D/Data2D object, extract relevant Info elements |
---|
348 | and add them to a model item |
---|
349 | """ |
---|
350 | assert isinstance(data, (Data1D, Data2D)) |
---|
351 | |
---|
352 | info_item = QtGui.QStandardItem("Info") |
---|
353 | |
---|
354 | title_item = QtGui.QStandardItem("Title: " + data.title) |
---|
355 | info_item.appendRow(title_item) |
---|
356 | run_item = QtGui.QStandardItem("Run: " + str(data.run)) |
---|
357 | info_item.appendRow(run_item) |
---|
358 | type_item = QtGui.QStandardItem("Type: " + str(data.__class__.__name__)) |
---|
359 | info_item.appendRow(type_item) |
---|
360 | |
---|
361 | if data.path: |
---|
362 | path_item = QtGui.QStandardItem("Path: " + data.path) |
---|
363 | info_item.appendRow(path_item) |
---|
364 | |
---|
365 | if data.instrument: |
---|
366 | instr_item = QtGui.QStandardItem("Instrument: " + data.instrument) |
---|
367 | info_item.appendRow(instr_item) |
---|
368 | |
---|
369 | process_item = QtGui.QStandardItem("Process") |
---|
370 | if isinstance(data.process, list) and data.process: |
---|
371 | for process in data.process: |
---|
372 | process_date = process.date |
---|
373 | process_date_item = QtGui.QStandardItem("Date: " + process_date) |
---|
374 | process_item.appendRow(process_date_item) |
---|
375 | |
---|
376 | process_descr = process.description |
---|
377 | process_descr_item = QtGui.QStandardItem("Description: " + process_descr) |
---|
378 | process_item.appendRow(process_descr_item) |
---|
379 | |
---|
380 | process_name = process.name |
---|
381 | process_name_item = QtGui.QStandardItem("Name: " + process_name) |
---|
382 | process_item.appendRow(process_name_item) |
---|
383 | |
---|
384 | info_item.appendRow(process_item) |
---|
385 | |
---|
386 | return info_item |
---|
387 | |
---|
388 | def openLink(url): |
---|
389 | """ |
---|
390 | Open a URL in an external browser. |
---|
391 | Check the URL first, though. |
---|
392 | """ |
---|
393 | parsed_url = urlparse.urlparse(url) |
---|
394 | if parsed_url.scheme: |
---|
395 | webbrowser.open(url) |
---|
396 | else: |
---|
397 | msg = "Attempt at opening an invalid URL" |
---|
398 | raise AttributeError, msg |
---|
399 | |
---|
400 | def retrieveData1d(data): |
---|
401 | """ |
---|
402 | Retrieve 1D data from file and construct its text |
---|
403 | representation |
---|
404 | """ |
---|
405 | if not isinstance(data, Data1D): |
---|
406 | msg = "Incorrect type passed to retrieveData1d" |
---|
407 | raise AttributeError, msg |
---|
408 | try: |
---|
409 | xmin = min(data.x) |
---|
410 | ymin = min(data.y) |
---|
411 | except: |
---|
412 | msg = "Unable to find min/max of \n data named %s" % \ |
---|
413 | data.filename |
---|
414 | #logging.error(msg) |
---|
415 | raise ValueError, msg |
---|
416 | |
---|
417 | text = data.__str__() |
---|
418 | text += 'Data Min Max:\n' |
---|
419 | text += 'X_min = %s: X_max = %s\n' % (xmin, max(data.x)) |
---|
420 | text += 'Y_min = %s: Y_max = %s\n' % (ymin, max(data.y)) |
---|
421 | if data.dy != None: |
---|
422 | text += 'dY_min = %s: dY_max = %s\n' % (min(data.dy), max(data.dy)) |
---|
423 | text += '\nData Points:\n' |
---|
424 | x_st = "X" |
---|
425 | for index in range(len(data.x)): |
---|
426 | if data.dy != None and len(data.dy) > index: |
---|
427 | dy_val = data.dy[index] |
---|
428 | else: |
---|
429 | dy_val = 0.0 |
---|
430 | if data.dx != None and len(data.dx) > index: |
---|
431 | dx_val = data.dx[index] |
---|
432 | else: |
---|
433 | dx_val = 0.0 |
---|
434 | if data.dxl != None and len(data.dxl) > index: |
---|
435 | if index == 0: |
---|
436 | x_st = "Xl" |
---|
437 | dx_val = data.dxl[index] |
---|
438 | elif data.dxw != None and len(data.dxw) > index: |
---|
439 | if index == 0: |
---|
440 | x_st = "Xw" |
---|
441 | dx_val = data.dxw[index] |
---|
442 | |
---|
443 | if index == 0: |
---|
444 | text += "<index> \t<X> \t<Y> \t<dY> \t<d%s>\n" % x_st |
---|
445 | text += "%s \t%s \t%s \t%s \t%s\n" % (index, |
---|
446 | data.x[index], |
---|
447 | data.y[index], |
---|
448 | dy_val, |
---|
449 | dx_val) |
---|
450 | return text |
---|
451 | |
---|
452 | def retrieveData2d(data): |
---|
453 | """ |
---|
454 | Retrieve 2D data from file and construct its text |
---|
455 | representation |
---|
456 | """ |
---|
457 | if not isinstance(data, Data2D): |
---|
458 | msg = "Incorrect type passed to retrieveData2d" |
---|
459 | raise AttributeError, msg |
---|
460 | |
---|
461 | text = data.__str__() |
---|
462 | text += 'Data Min Max:\n' |
---|
463 | text += 'I_min = %s\n' % min(data.data) |
---|
464 | text += 'I_max = %s\n\n' % max(data.data) |
---|
465 | text += 'Data (First 2501) Points:\n' |
---|
466 | text += 'Data columns include err(I).\n' |
---|
467 | text += 'ASCII data starts here.\n' |
---|
468 | text += "<index> \t<Qx> \t<Qy> \t<I> \t<dI> \t<dQparal> \t<dQperp>\n" |
---|
469 | di_val = 0.0 |
---|
470 | dx_val = 0.0 |
---|
471 | dy_val = 0.0 |
---|
472 | len_data = len(data.qx_data) |
---|
473 | for index in xrange(0, len_data): |
---|
474 | x_val = data.qx_data[index] |
---|
475 | y_val = data.qy_data[index] |
---|
476 | i_val = data.data[index] |
---|
477 | if data.err_data != None: |
---|
478 | di_val = data.err_data[index] |
---|
479 | if data.dqx_data != None: |
---|
480 | dx_val = data.dqx_data[index] |
---|
481 | if data.dqy_data != None: |
---|
482 | dy_val = data.dqy_data[index] |
---|
483 | |
---|
484 | text += "%s \t%s \t%s \t%s \t%s \t%s \t%s\n" % (index, |
---|
485 | x_val, |
---|
486 | y_val, |
---|
487 | i_val, |
---|
488 | di_val, |
---|
489 | dx_val, |
---|
490 | dy_val) |
---|
491 | # Takes too long time for typical data2d: Break here |
---|
492 | if index >= 2500: |
---|
493 | text += ".............\n" |
---|
494 | break |
---|
495 | |
---|
496 | return text |
---|
497 | |
---|
498 | def onTXTSave(data, path): |
---|
499 | """ |
---|
500 | Save file as formatted txt |
---|
501 | """ |
---|
502 | with open(path,'w') as out: |
---|
503 | has_errors = True |
---|
504 | if data.dy == None or data.dy == []: |
---|
505 | has_errors = False |
---|
506 | # Sanity check |
---|
507 | if has_errors: |
---|
508 | try: |
---|
509 | if len(data.y) != len(data.dy): |
---|
510 | has_errors = False |
---|
511 | except: |
---|
512 | has_errors = False |
---|
513 | if has_errors: |
---|
514 | if data.dx != None and data.dx != []: |
---|
515 | out.write("<X> <Y> <dY> <dX>\n") |
---|
516 | else: |
---|
517 | out.write("<X> <Y> <dY>\n") |
---|
518 | else: |
---|
519 | out.write("<X> <Y>\n") |
---|
520 | |
---|
521 | for i in range(len(data.x)): |
---|
522 | if has_errors: |
---|
523 | if data.dx != None and data.dx != []: |
---|
524 | if data.dx[i] != None: |
---|
525 | out.write("%g %g %g %g\n" % (data.x[i], |
---|
526 | data.y[i], |
---|
527 | data.dy[i], |
---|
528 | data.dx[i])) |
---|
529 | else: |
---|
530 | out.write("%g %g %g\n" % (data.x[i], |
---|
531 | data.y[i], |
---|
532 | data.dy[i])) |
---|
533 | else: |
---|
534 | out.write("%g %g %g\n" % (data.x[i], |
---|
535 | data.y[i], |
---|
536 | data.dy[i])) |
---|
537 | else: |
---|
538 | out.write("%g %g\n" % (data.x[i], |
---|
539 | data.y[i])) |
---|
540 | |
---|
541 | def saveData1D(data): |
---|
542 | """ |
---|
543 | Save 1D data points |
---|
544 | """ |
---|
545 | default_name = os.path.basename(data.filename) |
---|
546 | default_name, extension = os.path.splitext(default_name) |
---|
547 | default_name += "_out" + extension |
---|
548 | |
---|
549 | wildcard = "Text files (*.txt);;"\ |
---|
550 | "CanSAS 1D files(*.xml)" |
---|
551 | kwargs = { |
---|
552 | 'caption' : 'Save As', |
---|
553 | 'directory' : default_name, |
---|
554 | 'filter' : wildcard, |
---|
555 | 'parent' : None, |
---|
556 | } |
---|
557 | # Query user for filename. |
---|
558 | filename = QtGui.QFileDialog.getSaveFileName(**kwargs) |
---|
559 | |
---|
560 | # User cancelled. |
---|
561 | if not filename: |
---|
562 | return |
---|
563 | |
---|
564 | filename = str(filename) |
---|
565 | |
---|
566 | #Instantiate a loader |
---|
567 | loader = Loader() |
---|
568 | if os.path.splitext(filename)[1].lower() == ".txt": |
---|
569 | onTXTSave(data, filename) |
---|
570 | if os.path.splitext(filename)[1].lower() == ".xml": |
---|
571 | loader.save(filename, data, ".xml") |
---|
572 | |
---|
573 | def saveData2D(data): |
---|
574 | """ |
---|
575 | Save data2d dialog |
---|
576 | """ |
---|
577 | default_name = os.path.basename(data.filename) |
---|
578 | default_name, _ = os.path.splitext(default_name) |
---|
579 | ext_format = ".dat" |
---|
580 | default_name += "_out" + ext_format |
---|
581 | |
---|
582 | wildcard = "IGOR/DAT 2D file in Q_map (*.dat)" |
---|
583 | kwargs = { |
---|
584 | 'caption' : 'Save As', |
---|
585 | 'directory' : default_name, |
---|
586 | 'filter' : wildcard, |
---|
587 | 'parent' : None, |
---|
588 | } |
---|
589 | # Query user for filename. |
---|
590 | filename = QtGui.QFileDialog.getSaveFileName(**kwargs) |
---|
591 | |
---|
592 | # User cancelled. |
---|
593 | if not filename: |
---|
594 | return |
---|
595 | filename = str(filename) |
---|
596 | #Instantiate a loader |
---|
597 | loader = Loader() |
---|
598 | |
---|
599 | if os.path.splitext(filename)[1].lower() == ext_format: |
---|
600 | loader.save(filename, data, ext_format) |
---|
601 | |
---|
602 | class FormulaValidator(QtGui.QValidator): |
---|
603 | def __init__(self, parent=None): |
---|
604 | super(FormulaValidator, self).__init__(parent) |
---|
605 | |
---|
606 | def validate(self, input, pos): |
---|
607 | try: |
---|
608 | Formula(str(input)) |
---|
609 | self._setStyleSheet("") |
---|
610 | return QtGui.QValidator.Acceptable, pos |
---|
611 | |
---|
612 | except Exception as e: |
---|
613 | self._setStyleSheet("background-color:pink;") |
---|
614 | return QtGui.QValidator.Intermediate, pos |
---|
615 | |
---|
616 | def _setStyleSheet(self, value): |
---|
617 | try: |
---|
618 | if self.parent(): |
---|
619 | self.parent().setStyleSheet(value) |
---|
620 | except: |
---|
621 | pass |
---|
622 | |
---|
623 | def xyTransform(data, xLabel="", yLabel=""): |
---|
624 | """ |
---|
625 | Transforms x and y in View and set the scale |
---|
626 | """ |
---|
627 | # Changing the scale might be incompatible with |
---|
628 | # currently displayed data (for instance, going |
---|
629 | # from ln to log when all plotted values have |
---|
630 | # negative natural logs). |
---|
631 | # Go linear and only change the scale at the end. |
---|
632 | xscale = 'linear' |
---|
633 | yscale = 'linear' |
---|
634 | # Local data is either 1D or 2D |
---|
635 | if data.id == 'fit': |
---|
636 | return |
---|
637 | |
---|
638 | # control axis labels from the panel itself |
---|
639 | yname, yunits = data.get_yaxis() |
---|
640 | xname, xunits = data.get_xaxis() |
---|
641 | |
---|
642 | # Goes through all possible scales |
---|
643 | # self.x_label is already wrapped with Latex "$", so using the argument |
---|
644 | |
---|
645 | # X |
---|
646 | if xLabel == "x": |
---|
647 | data.transformX(transform.toX, transform.errToX) |
---|
648 | xLabel = "%s(%s)" % (xname, xunits) |
---|
649 | if xLabel == "x^(2)": |
---|
650 | data.transformX(transform.toX2, transform.errToX2) |
---|
651 | xunits = convert_unit(2, xunits) |
---|
652 | xLabel = "%s^{2}(%s)" % (xname, xunits) |
---|
653 | if xLabel == "x^(4)": |
---|
654 | data.transformX(transform.toX4, transform.errToX4) |
---|
655 | xunits = convert_unit(4, xunits) |
---|
656 | xLabel = "%s^{4}(%s)" % (xname, xunits) |
---|
657 | if xLabel == "ln(x)": |
---|
658 | data.transformX(transform.toLogX, transform.errToLogX) |
---|
659 | xLabel = "\ln{(%s)}(%s)" % (xname, xunits) |
---|
660 | if xLabel == "log10(x)": |
---|
661 | data.transformX(transform.toX_pos, transform.errToX_pos) |
---|
662 | xscale = 'log' |
---|
663 | xLabel = "%s(%s)" % (xname, xunits) |
---|
664 | if xLabel == "log10(x^(4))": |
---|
665 | data.transformX(transform.toX4, transform.errToX4) |
---|
666 | xunits = convert_unit(4, xunits) |
---|
667 | xLabel = "%s^{4}(%s)" % (xname, xunits) |
---|
668 | xscale = 'log' |
---|
669 | |
---|
670 | # Y |
---|
671 | if yLabel == "ln(y)": |
---|
672 | data.transformY(transform.toLogX, transform.errToLogX) |
---|
673 | yLabel = "\ln{(%s)}(%s)" % (yname, yunits) |
---|
674 | if yLabel == "y": |
---|
675 | data.transformY(transform.toX, transform.errToX) |
---|
676 | yLabel = "%s(%s)" % (yname, yunits) |
---|
677 | if yLabel == "log10(y)": |
---|
678 | data.transformY(transform.toX_pos, transform.errToX_pos) |
---|
679 | yscale = 'log' |
---|
680 | yLabel = "%s(%s)" % (yname, yunits) |
---|
681 | if yLabel == "y^(2)": |
---|
682 | data.transformY(transform.toX2, transform.errToX2) |
---|
683 | yunits = convert_unit(2, yunits) |
---|
684 | yLabel = "%s^{2}(%s)" % (yname, yunits) |
---|
685 | if yLabel == "1/y": |
---|
686 | data.transformY(transform.toOneOverX, transform.errOneOverX) |
---|
687 | yunits = convert_unit(-1, yunits) |
---|
688 | yLabel = "1/%s(%s)" % (yname, yunits) |
---|
689 | if yLabel == "y*x^(2)": |
---|
690 | data.transformY(transform.toYX2, transform.errToYX2) |
---|
691 | xunits = convert_unit(2, xunits) |
---|
692 | yLabel = "%s \ \ %s^{2}(%s%s)" % (yname, xname, yunits, xunits) |
---|
693 | if yLabel == "y*x^(4)": |
---|
694 | data.transformY(transform.toYX4, transform.errToYX4) |
---|
695 | xunits = convert_unit(4, xunits) |
---|
696 | yLabel = "%s \ \ %s^{4}(%s%s)" % (yname, xname, yunits, xunits) |
---|
697 | if yLabel == "1/sqrt(y)": |
---|
698 | data.transformY(transform.toOneOverSqrtX, |
---|
699 | transform.errOneOverSqrtX) |
---|
700 | yunits = convert_unit(-0.5, yunits) |
---|
701 | yLabel = "1/\sqrt{%s}(%s)" % (yname, yunits) |
---|
702 | if yLabel == "ln(y*x)": |
---|
703 | data.transformY(transform.toLogXY, transform.errToLogXY) |
---|
704 | yLabel = "\ln{(%s \ \ %s)}(%s%s)" % (yname, xname, yunits, xunits) |
---|
705 | if yLabel == "ln(y*x^(2))": |
---|
706 | data.transformY(transform.toLogYX2, transform.errToLogYX2) |
---|
707 | xunits = convert_unit(2, xunits) |
---|
708 | yLabel = "\ln (%s \ \ %s^{2})(%s%s)" % (yname, xname, yunits, xunits) |
---|
709 | if yLabel == "ln(y*x^(4))": |
---|
710 | data.transformY(transform.toLogYX4, transform.errToLogYX4) |
---|
711 | xunits = convert_unit(4, xunits) |
---|
712 | yLabel = "\ln (%s \ \ %s^{4})(%s%s)" % (yname, xname, yunits, xunits) |
---|
713 | if yLabel == "log10(y*x^(4))": |
---|
714 | data.transformY(transform.toYX4, transform.errToYX4) |
---|
715 | xunits = convert_unit(4, xunits) |
---|
716 | yscale = 'log' |
---|
717 | yLabel = "%s \ \ %s^{4}(%s%s)" % (yname, xname, yunits, xunits) |
---|
718 | |
---|
719 | # Perform the transformation of data in data1d->View |
---|
720 | data.transformView() |
---|
721 | |
---|
722 | return (xLabel, yLabel, xscale, yscale) |
---|
723 | |
---|
724 | def dataFromItem(item): |
---|
725 | """ |
---|
726 | Retrieve Data1D/2D component from QStandardItem. |
---|
727 | The assumption - data stored in SasView standard, in child 0 |
---|
728 | """ |
---|
729 | return item.child(0).data().toPyObject() |
---|
730 | |
---|
731 | def formatNumber(value, high=False): |
---|
732 | """ |
---|
733 | Return a float in a standardized, human-readable formatted string. |
---|
734 | This is used to output readable (e.g. x.xxxe-y) values to the panel. |
---|
735 | """ |
---|
736 | try: |
---|
737 | value = float(value) |
---|
738 | except: |
---|
739 | output = "NaN" |
---|
740 | return output.lstrip().rstrip() |
---|
741 | |
---|
742 | if high: |
---|
743 | output = "%-6.4g" % value |
---|
744 | |
---|
745 | else: |
---|
746 | output = "%-5.3g" % value |
---|
747 | return output.lstrip().rstrip() |
---|