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 | # Progress bar update value |
---|
231 | progressBarUpdateSignal = QtCore.pyqtSignal(int) |
---|
232 | |
---|
233 | # Workspace charts added/removed |
---|
234 | activeGraphsSignal = QtCore.pyqtSignal(list) |
---|
235 | |
---|
236 | # Current workspace chart's name changed |
---|
237 | activeGraphName = QtCore.pyqtSignal(tuple) |
---|
238 | |
---|
239 | # Current perspective changed |
---|
240 | perspectiveChangedSignal = QtCore.pyqtSignal(str) |
---|
241 | |
---|
242 | |
---|
243 | def updateModelItemWithPlot(item, update_data, name=""): |
---|
244 | """ |
---|
245 | Adds a checkboxed row named "name" to QStandardItem |
---|
246 | Adds QVariant 'update_data' to that row. |
---|
247 | """ |
---|
248 | assert isinstance(item, QtGui.QStandardItem) |
---|
249 | assert isinstance(update_data, QtCore.QVariant) |
---|
250 | py_update_data = update_data.toPyObject() |
---|
251 | |
---|
252 | # Check if data with the same ID is already present |
---|
253 | for index in range(item.rowCount()): |
---|
254 | plot_item = item.child(index) |
---|
255 | if plot_item.isCheckable(): |
---|
256 | plot_data = plot_item.child(0).data().toPyObject() |
---|
257 | if plot_data.id == py_update_data.id: |
---|
258 | item.removeRow(index) |
---|
259 | break |
---|
260 | |
---|
261 | # Create the new item |
---|
262 | checkbox_item = createModelItemWithPlot(update_data, name) |
---|
263 | |
---|
264 | # Append the new row to the main item |
---|
265 | item.appendRow(checkbox_item) |
---|
266 | |
---|
267 | def createModelItemWithPlot(update_data, name=""): |
---|
268 | """ |
---|
269 | Creates a checkboxed QStandardItem named "name" |
---|
270 | Adds QVariant 'update_data' to that row. |
---|
271 | """ |
---|
272 | assert isinstance(update_data, QtCore.QVariant) |
---|
273 | py_update_data = update_data.toPyObject() |
---|
274 | |
---|
275 | checkbox_item = QtGui.QStandardItem() |
---|
276 | checkbox_item.setCheckable(True) |
---|
277 | checkbox_item.setCheckState(QtCore.Qt.Checked) |
---|
278 | checkbox_item.setText(name) |
---|
279 | |
---|
280 | # Add "Info" item |
---|
281 | if isinstance(py_update_data, (Data1D, Data2D)): |
---|
282 | # If Data1/2D added - extract Info from it |
---|
283 | info_item = infoFromData(py_update_data) |
---|
284 | else: |
---|
285 | # otherwise just add a naked item |
---|
286 | info_item = QtGui.QStandardItem("Info") |
---|
287 | |
---|
288 | # Add the actual Data1D/Data2D object |
---|
289 | object_item = QtGui.QStandardItem() |
---|
290 | object_item.setData(update_data) |
---|
291 | |
---|
292 | # Set the data object as the first child |
---|
293 | checkbox_item.setChild(0, object_item) |
---|
294 | |
---|
295 | # Set info_item as the second child |
---|
296 | checkbox_item.setChild(1, info_item) |
---|
297 | |
---|
298 | # And return the newly created item |
---|
299 | return checkbox_item |
---|
300 | |
---|
301 | def updateModelItem(item, update_data, name=""): |
---|
302 | """ |
---|
303 | Adds a simple named child to QStandardItem |
---|
304 | """ |
---|
305 | assert isinstance(item, QtGui.QStandardItem) |
---|
306 | assert isinstance(update_data, list) |
---|
307 | |
---|
308 | # Add the actual Data1D/Data2D object |
---|
309 | object_item = QtGui.QStandardItem() |
---|
310 | object_item.setText(name) |
---|
311 | object_item.setData(QtCore.QVariant(update_data)) |
---|
312 | |
---|
313 | # Append the new row to the main item |
---|
314 | item.appendRow(object_item) |
---|
315 | |
---|
316 | |
---|
317 | def plotsFromCheckedItems(model_item): |
---|
318 | """ |
---|
319 | Returns the list of plots for items in the model which are checked |
---|
320 | """ |
---|
321 | assert isinstance(model_item, QtGui.QStandardItemModel) |
---|
322 | |
---|
323 | plot_data = [] |
---|
324 | # Iterate over model looking for items with checkboxes |
---|
325 | for index in range(model_item.rowCount()): |
---|
326 | item = model_item.item(index) |
---|
327 | if item.isCheckable() and item.checkState() == QtCore.Qt.Checked: |
---|
328 | # TODO: assure item type is correct (either data1/2D or Plotter) |
---|
329 | plot_data.append((item, item.child(0).data().toPyObject())) |
---|
330 | # Going 1 level deeper only |
---|
331 | for index_2 in range(item.rowCount()): |
---|
332 | item_2 = item.child(index_2) |
---|
333 | if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked: |
---|
334 | # TODO: assure item type is correct (either data1/2D or Plotter) |
---|
335 | plot_data.append((item_2, item_2.child(0).data().toPyObject())) |
---|
336 | |
---|
337 | return plot_data |
---|
338 | |
---|
339 | def infoFromData(data): |
---|
340 | """ |
---|
341 | Given Data1D/Data2D object, extract relevant Info elements |
---|
342 | and add them to a model item |
---|
343 | """ |
---|
344 | assert isinstance(data, (Data1D, Data2D)) |
---|
345 | |
---|
346 | info_item = QtGui.QStandardItem("Info") |
---|
347 | |
---|
348 | title_item = QtGui.QStandardItem("Title: " + data.title) |
---|
349 | info_item.appendRow(title_item) |
---|
350 | run_item = QtGui.QStandardItem("Run: " + str(data.run)) |
---|
351 | info_item.appendRow(run_item) |
---|
352 | type_item = QtGui.QStandardItem("Type: " + str(data.__class__.__name__)) |
---|
353 | info_item.appendRow(type_item) |
---|
354 | |
---|
355 | if data.path: |
---|
356 | path_item = QtGui.QStandardItem("Path: " + data.path) |
---|
357 | info_item.appendRow(path_item) |
---|
358 | |
---|
359 | if data.instrument: |
---|
360 | instr_item = QtGui.QStandardItem("Instrument: " + data.instrument) |
---|
361 | info_item.appendRow(instr_item) |
---|
362 | |
---|
363 | process_item = QtGui.QStandardItem("Process") |
---|
364 | if isinstance(data.process, list) and data.process: |
---|
365 | for process in data.process: |
---|
366 | process_date = process.date |
---|
367 | process_date_item = QtGui.QStandardItem("Date: " + process_date) |
---|
368 | process_item.appendRow(process_date_item) |
---|
369 | |
---|
370 | process_descr = process.description |
---|
371 | process_descr_item = QtGui.QStandardItem("Description: " + process_descr) |
---|
372 | process_item.appendRow(process_descr_item) |
---|
373 | |
---|
374 | process_name = process.name |
---|
375 | process_name_item = QtGui.QStandardItem("Name: " + process_name) |
---|
376 | process_item.appendRow(process_name_item) |
---|
377 | |
---|
378 | info_item.appendRow(process_item) |
---|
379 | |
---|
380 | return info_item |
---|
381 | |
---|
382 | def openLink(url): |
---|
383 | """ |
---|
384 | Open a URL in an external browser. |
---|
385 | Check the URL first, though. |
---|
386 | """ |
---|
387 | parsed_url = urlparse.urlparse(url) |
---|
388 | if parsed_url.scheme: |
---|
389 | webbrowser.open(url) |
---|
390 | else: |
---|
391 | msg = "Attempt at opening an invalid URL" |
---|
392 | raise AttributeError, msg |
---|
393 | |
---|
394 | def retrieveData1d(data): |
---|
395 | """ |
---|
396 | Retrieve 1D data from file and construct its text |
---|
397 | representation |
---|
398 | """ |
---|
399 | if not isinstance(data, Data1D): |
---|
400 | msg = "Incorrect type passed to retrieveData1d" |
---|
401 | raise AttributeError, msg |
---|
402 | try: |
---|
403 | xmin = min(data.x) |
---|
404 | ymin = min(data.y) |
---|
405 | except: |
---|
406 | msg = "Unable to find min/max of \n data named %s" % \ |
---|
407 | data.filename |
---|
408 | #logging.error(msg) |
---|
409 | raise ValueError, msg |
---|
410 | |
---|
411 | text = data.__str__() |
---|
412 | text += 'Data Min Max:\n' |
---|
413 | text += 'X_min = %s: X_max = %s\n' % (xmin, max(data.x)) |
---|
414 | text += 'Y_min = %s: Y_max = %s\n' % (ymin, max(data.y)) |
---|
415 | if data.dy != None: |
---|
416 | text += 'dY_min = %s: dY_max = %s\n' % (min(data.dy), max(data.dy)) |
---|
417 | text += '\nData Points:\n' |
---|
418 | x_st = "X" |
---|
419 | for index in range(len(data.x)): |
---|
420 | if data.dy != None and len(data.dy) > index: |
---|
421 | dy_val = data.dy[index] |
---|
422 | else: |
---|
423 | dy_val = 0.0 |
---|
424 | if data.dx != None and len(data.dx) > index: |
---|
425 | dx_val = data.dx[index] |
---|
426 | else: |
---|
427 | dx_val = 0.0 |
---|
428 | if data.dxl != None and len(data.dxl) > index: |
---|
429 | if index == 0: |
---|
430 | x_st = "Xl" |
---|
431 | dx_val = data.dxl[index] |
---|
432 | elif data.dxw != None and len(data.dxw) > index: |
---|
433 | if index == 0: |
---|
434 | x_st = "Xw" |
---|
435 | dx_val = data.dxw[index] |
---|
436 | |
---|
437 | if index == 0: |
---|
438 | text += "<index> \t<X> \t<Y> \t<dY> \t<d%s>\n" % x_st |
---|
439 | text += "%s \t%s \t%s \t%s \t%s\n" % (index, |
---|
440 | data.x[index], |
---|
441 | data.y[index], |
---|
442 | dy_val, |
---|
443 | dx_val) |
---|
444 | return text |
---|
445 | |
---|
446 | def retrieveData2d(data): |
---|
447 | """ |
---|
448 | Retrieve 2D data from file and construct its text |
---|
449 | representation |
---|
450 | """ |
---|
451 | if not isinstance(data, Data2D): |
---|
452 | msg = "Incorrect type passed to retrieveData2d" |
---|
453 | raise AttributeError, msg |
---|
454 | |
---|
455 | text = data.__str__() |
---|
456 | text += 'Data Min Max:\n' |
---|
457 | text += 'I_min = %s\n' % min(data.data) |
---|
458 | text += 'I_max = %s\n\n' % max(data.data) |
---|
459 | text += 'Data (First 2501) Points:\n' |
---|
460 | text += 'Data columns include err(I).\n' |
---|
461 | text += 'ASCII data starts here.\n' |
---|
462 | text += "<index> \t<Qx> \t<Qy> \t<I> \t<dI> \t<dQparal> \t<dQperp>\n" |
---|
463 | di_val = 0.0 |
---|
464 | dx_val = 0.0 |
---|
465 | dy_val = 0.0 |
---|
466 | len_data = len(data.qx_data) |
---|
467 | for index in xrange(0, len_data): |
---|
468 | x_val = data.qx_data[index] |
---|
469 | y_val = data.qy_data[index] |
---|
470 | i_val = data.data[index] |
---|
471 | if data.err_data != None: |
---|
472 | di_val = data.err_data[index] |
---|
473 | if data.dqx_data != None: |
---|
474 | dx_val = data.dqx_data[index] |
---|
475 | if data.dqy_data != None: |
---|
476 | dy_val = data.dqy_data[index] |
---|
477 | |
---|
478 | text += "%s \t%s \t%s \t%s \t%s \t%s \t%s\n" % (index, |
---|
479 | x_val, |
---|
480 | y_val, |
---|
481 | i_val, |
---|
482 | di_val, |
---|
483 | dx_val, |
---|
484 | dy_val) |
---|
485 | # Takes too long time for typical data2d: Break here |
---|
486 | if index >= 2500: |
---|
487 | text += ".............\n" |
---|
488 | break |
---|
489 | |
---|
490 | return text |
---|
491 | |
---|
492 | def onTXTSave(data, path): |
---|
493 | """ |
---|
494 | Save file as formatted txt |
---|
495 | """ |
---|
496 | with open(path,'w') as out: |
---|
497 | has_errors = True |
---|
498 | if data.dy == None or data.dy == []: |
---|
499 | has_errors = False |
---|
500 | # Sanity check |
---|
501 | if has_errors: |
---|
502 | try: |
---|
503 | if len(data.y) != len(data.dy): |
---|
504 | has_errors = False |
---|
505 | except: |
---|
506 | has_errors = False |
---|
507 | if has_errors: |
---|
508 | if data.dx != None and data.dx != []: |
---|
509 | out.write("<X> <Y> <dY> <dX>\n") |
---|
510 | else: |
---|
511 | out.write("<X> <Y> <dY>\n") |
---|
512 | else: |
---|
513 | out.write("<X> <Y>\n") |
---|
514 | |
---|
515 | for i in range(len(data.x)): |
---|
516 | if has_errors: |
---|
517 | if data.dx != None and data.dx != []: |
---|
518 | if data.dx[i] != None: |
---|
519 | out.write("%g %g %g %g\n" % (data.x[i], |
---|
520 | data.y[i], |
---|
521 | data.dy[i], |
---|
522 | data.dx[i])) |
---|
523 | else: |
---|
524 | out.write("%g %g %g\n" % (data.x[i], |
---|
525 | data.y[i], |
---|
526 | data.dy[i])) |
---|
527 | else: |
---|
528 | out.write("%g %g %g\n" % (data.x[i], |
---|
529 | data.y[i], |
---|
530 | data.dy[i])) |
---|
531 | else: |
---|
532 | out.write("%g %g\n" % (data.x[i], |
---|
533 | data.y[i])) |
---|
534 | |
---|
535 | def saveData1D(data): |
---|
536 | """ |
---|
537 | Save 1D data points |
---|
538 | """ |
---|
539 | default_name = os.path.basename(data.filename) |
---|
540 | default_name, extension = os.path.splitext(default_name) |
---|
541 | default_name += "_out" + extension |
---|
542 | |
---|
543 | wildcard = "Text files (*.txt);;"\ |
---|
544 | "CanSAS 1D files(*.xml)" |
---|
545 | kwargs = { |
---|
546 | 'caption' : 'Save As', |
---|
547 | 'directory' : default_name, |
---|
548 | 'filter' : wildcard, |
---|
549 | 'parent' : None, |
---|
550 | } |
---|
551 | # Query user for filename. |
---|
552 | filename = QtGui.QFileDialog.getSaveFileName(**kwargs) |
---|
553 | |
---|
554 | # User cancelled. |
---|
555 | if not filename: |
---|
556 | return |
---|
557 | |
---|
558 | filename = str(filename) |
---|
559 | |
---|
560 | #Instantiate a loader |
---|
561 | loader = Loader() |
---|
562 | if os.path.splitext(filename)[1].lower() == ".txt": |
---|
563 | onTXTSave(data, filename) |
---|
564 | if os.path.splitext(filename)[1].lower() == ".xml": |
---|
565 | loader.save(filename, data, ".xml") |
---|
566 | |
---|
567 | def saveData2D(data): |
---|
568 | """ |
---|
569 | Save data2d dialog |
---|
570 | """ |
---|
571 | default_name = os.path.basename(data.filename) |
---|
572 | default_name, _ = os.path.splitext(default_name) |
---|
573 | ext_format = ".dat" |
---|
574 | default_name += "_out" + ext_format |
---|
575 | |
---|
576 | wildcard = "IGOR/DAT 2D file in Q_map (*.dat)" |
---|
577 | kwargs = { |
---|
578 | 'caption' : 'Save As', |
---|
579 | 'directory' : default_name, |
---|
580 | 'filter' : wildcard, |
---|
581 | 'parent' : None, |
---|
582 | } |
---|
583 | # Query user for filename. |
---|
584 | filename = QtGui.QFileDialog.getSaveFileName(**kwargs) |
---|
585 | |
---|
586 | # User cancelled. |
---|
587 | if not filename: |
---|
588 | return |
---|
589 | filename = str(filename) |
---|
590 | #Instantiate a loader |
---|
591 | loader = Loader() |
---|
592 | |
---|
593 | if os.path.splitext(filename)[1].lower() == ext_format: |
---|
594 | loader.save(filename, data, ext_format) |
---|
595 | |
---|
596 | class FormulaValidator(QtGui.QValidator): |
---|
597 | def __init__(self, parent=None): |
---|
598 | super(FormulaValidator, self).__init__(parent) |
---|
599 | |
---|
600 | def validate(self, input, pos): |
---|
601 | try: |
---|
602 | Formula(str(input)) |
---|
603 | self._setStyleSheet("") |
---|
604 | return QtGui.QValidator.Acceptable, pos |
---|
605 | |
---|
606 | except Exception as e: |
---|
607 | self._setStyleSheet("background-color:pink;") |
---|
608 | return QtGui.QValidator.Intermediate, pos |
---|
609 | |
---|
610 | def _setStyleSheet(self, value): |
---|
611 | try: |
---|
612 | if self.parent(): |
---|
613 | self.parent().setStyleSheet(value) |
---|
614 | except: |
---|
615 | pass |
---|
616 | |
---|
617 | def xyTransform(data, xLabel="", yLabel=""): |
---|
618 | """ |
---|
619 | Transforms x and y in View and set the scale |
---|
620 | """ |
---|
621 | # Changing the scale might be incompatible with |
---|
622 | # currently displayed data (for instance, going |
---|
623 | # from ln to log when all plotted values have |
---|
624 | # negative natural logs). |
---|
625 | # Go linear and only change the scale at the end. |
---|
626 | xscale = 'linear' |
---|
627 | yscale = 'linear' |
---|
628 | # Local data is either 1D or 2D |
---|
629 | if data.id == 'fit': |
---|
630 | return |
---|
631 | |
---|
632 | # control axis labels from the panel itself |
---|
633 | yname, yunits = data.get_yaxis() |
---|
634 | xname, xunits = data.get_xaxis() |
---|
635 | |
---|
636 | # Goes through all possible scales |
---|
637 | # self.x_label is already wrapped with Latex "$", so using the argument |
---|
638 | |
---|
639 | # X |
---|
640 | if xLabel == "x": |
---|
641 | data.transformX(transform.toX, transform.errToX) |
---|
642 | xLabel = "%s(%s)" % (xname, xunits) |
---|
643 | if xLabel == "x^(2)": |
---|
644 | data.transformX(transform.toX2, transform.errToX2) |
---|
645 | xunits = convert_unit(2, xunits) |
---|
646 | xLabel = "%s^{2}(%s)" % (xname, xunits) |
---|
647 | if xLabel == "x^(4)": |
---|
648 | data.transformX(transform.toX4, transform.errToX4) |
---|
649 | xunits = convert_unit(4, xunits) |
---|
650 | xLabel = "%s^{4}(%s)" % (xname, xunits) |
---|
651 | if xLabel == "ln(x)": |
---|
652 | data.transformX(transform.toLogX, transform.errToLogX) |
---|
653 | xLabel = "\ln{(%s)}(%s)" % (xname, xunits) |
---|
654 | if xLabel == "log10(x)": |
---|
655 | data.transformX(transform.toX_pos, transform.errToX_pos) |
---|
656 | xscale = 'log' |
---|
657 | xLabel = "%s(%s)" % (xname, xunits) |
---|
658 | if xLabel == "log10(x^(4))": |
---|
659 | data.transformX(transform.toX4, transform.errToX4) |
---|
660 | xunits = convert_unit(4, xunits) |
---|
661 | xLabel = "%s^{4}(%s)" % (xname, xunits) |
---|
662 | xscale = 'log' |
---|
663 | |
---|
664 | # Y |
---|
665 | if yLabel == "ln(y)": |
---|
666 | data.transformY(transform.toLogX, transform.errToLogX) |
---|
667 | yLabel = "\ln{(%s)}(%s)" % (yname, yunits) |
---|
668 | if yLabel == "y": |
---|
669 | data.transformY(transform.toX, transform.errToX) |
---|
670 | yLabel = "%s(%s)" % (yname, yunits) |
---|
671 | if yLabel == "log10(y)": |
---|
672 | data.transformY(transform.toX_pos, transform.errToX_pos) |
---|
673 | yscale = 'log' |
---|
674 | yLabel = "%s(%s)" % (yname, yunits) |
---|
675 | if yLabel == "y^(2)": |
---|
676 | data.transformY(transform.toX2, transform.errToX2) |
---|
677 | yunits = convert_unit(2, yunits) |
---|
678 | yLabel = "%s^{2}(%s)" % (yname, yunits) |
---|
679 | if yLabel == "1/y": |
---|
680 | data.transformY(transform.toOneOverX, transform.errOneOverX) |
---|
681 | yunits = convert_unit(-1, yunits) |
---|
682 | yLabel = "1/%s(%s)" % (yname, yunits) |
---|
683 | if yLabel == "y*x^(2)": |
---|
684 | data.transformY(transform.toYX2, transform.errToYX2) |
---|
685 | xunits = convert_unit(2, xunits) |
---|
686 | yLabel = "%s \ \ %s^{2}(%s%s)" % (yname, xname, yunits, xunits) |
---|
687 | if yLabel == "y*x^(4)": |
---|
688 | data.transformY(transform.toYX4, transform.errToYX4) |
---|
689 | xunits = convert_unit(4, xunits) |
---|
690 | yLabel = "%s \ \ %s^{4}(%s%s)" % (yname, xname, yunits, xunits) |
---|
691 | if yLabel == "1/sqrt(y)": |
---|
692 | data.transformY(transform.toOneOverSqrtX, |
---|
693 | transform.errOneOverSqrtX) |
---|
694 | yunits = convert_unit(-0.5, yunits) |
---|
695 | yLabel = "1/\sqrt{%s}(%s)" % (yname, yunits) |
---|
696 | if yLabel == "ln(y*x)": |
---|
697 | data.transformY(transform.toLogXY, transform.errToLogXY) |
---|
698 | yLabel = "\ln{(%s \ \ %s)}(%s%s)" % (yname, xname, yunits, xunits) |
---|
699 | if yLabel == "ln(y*x^(2))": |
---|
700 | data.transformY(transform.toLogYX2, transform.errToLogYX2) |
---|
701 | xunits = convert_unit(2, xunits) |
---|
702 | yLabel = "\ln (%s \ \ %s^{2})(%s%s)" % (yname, xname, yunits, xunits) |
---|
703 | if yLabel == "ln(y*x^(4))": |
---|
704 | data.transformY(transform.toLogYX4, transform.errToLogYX4) |
---|
705 | xunits = convert_unit(4, xunits) |
---|
706 | yLabel = "\ln (%s \ \ %s^{4})(%s%s)" % (yname, xname, yunits, xunits) |
---|
707 | if yLabel == "log10(y*x^(4))": |
---|
708 | data.transformY(transform.toYX4, transform.errToYX4) |
---|
709 | xunits = convert_unit(4, xunits) |
---|
710 | yscale = 'log' |
---|
711 | yLabel = "%s \ \ %s^{4}(%s%s)" % (yname, xname, yunits, xunits) |
---|
712 | |
---|
713 | # Perform the transformation of data in data1d->View |
---|
714 | data.transformView() |
---|
715 | |
---|
716 | return (xLabel, yLabel, xscale, yscale) |
---|
717 | |
---|
718 | def dataFromItem(item): |
---|
719 | """ |
---|
720 | Retrieve Data1D/2D component from QStandardItem. |
---|
721 | The assumption - data stored in SasView standard, in child 0 |
---|
722 | """ |
---|
723 | return item.child(0).data().toPyObject() |
---|
724 | |
---|
725 | def formatNumber(value, high=False): |
---|
726 | """ |
---|
727 | Return a float in a standardized, human-readable formatted string. |
---|
728 | This is used to output readable (e.g. x.xxxe-y) values to the panel. |
---|
729 | """ |
---|
730 | try: |
---|
731 | value = float(value) |
---|
732 | except: |
---|
733 | output = "NaN" |
---|
734 | return output.lstrip().rstrip() |
---|
735 | |
---|
736 | if high: |
---|
737 | output = "%-6.4g" % value |
---|
738 | |
---|
739 | else: |
---|
740 | output = "%-5.3g" % value |
---|
741 | return output.lstrip().rstrip() |
---|