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