source: sasview/src/sas/qtgui/GuiUtils.py @ e4676c8

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since e4676c8 was e4676c8, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Added SLDCalculator unit tests. Refactored things a bit.

  • Property mode set to 100644
File size: 18.3 KB
Line 
1"""
2Global defaults and various utility functions usable by the general GUI
3"""
4
5import os
6import sys
7import imp
8import warnings
9import webbrowser
10import urlparse
11
12warnings.simplefilter("ignore")
13import logging
14
15from PyQt4 import QtCore
16from 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
28from periodictable import formula as Formula
29
30from sas.sasgui.guiframe.dataFitting import Data1D
31from sas.sasgui.guiframe.dataFitting import Data2D
32from sas.sascalc.dataloader.loader import Loader
33
34
35def get_app_dir():
36    """
37        The application directory is the one where the default custom_config.py
38        file resides.
39
40        :returns: app_path - the path to the applicatin directory
41    """
42    # First, try the directory of the executable we are running
43    app_path = sys.path[0]
44    if os.path.isfile(app_path):
45        app_path = os.path.dirname(app_path)
46    if os.path.isfile(os.path.join(app_path, "custom_config.py")):
47        app_path = os.path.abspath(app_path)
48        logging.info("Using application path: %s", app_path)
49        return app_path
50
51    # Next, try the current working directory
52    if os.path.isfile(os.path.join(os.getcwd(), "custom_config.py")):
53        logging.info("Using application path: %s", os.getcwd())
54        return os.path.abspath(os.getcwd())
55
56    # Finally, try the directory of the sasview module
57    # TODO: gui_manager will have to know about sasview until we
58    # clean all these module variables and put them into a config class
59    # that can be passed by sasview.py.
60    logging.info(sys.executable)
61    logging.info(str(sys.argv))
62    from sas import sasview as sasview
63    app_path = os.path.dirname(sasview.__file__)
64    logging.info("Using application path: %s", app_path)
65    return app_path
66
67def get_user_directory():
68    """
69        Returns the user's home directory
70    """
71    userdir = os.path.join(os.path.expanduser("~"), ".sasview")
72    if not os.path.isdir(userdir):
73        os.makedirs(userdir)
74    return userdir
75
76def _find_local_config(confg_file, path):
77    """
78        Find configuration file for the current application
79    """
80    config_module = None
81    fObj = None
82    try:
83        fObj, path_config, descr = imp.find_module(confg_file, [path])
84        config_module = imp.load_module(confg_file, fObj, path_config, descr)
85    except ImportError:
86        logging.error("Error loading %s/%s: %s" % (path, confg_file, sys.exc_value))
87    finally:
88        if fObj is not None:
89            fObj.close()
90    logging.info("GuiManager loaded %s/%s" % (path, confg_file))
91    return config_module
92
93# Get APP folder
94PATH_APP = get_app_dir()
95DATAPATH = PATH_APP
96
97# GUI always starts from the App folder
98#os.chdir(PATH_APP)
99# Read in the local config, which can either be with the main
100# application or in the installation directory
101config = _find_local_config('local_config', PATH_APP)
102if config is None:
103    config = _find_local_config('local_config', os.getcwd())
104    if config is None:
105        # Didn't find local config, load the default
106        import sas.sasgui.guiframe.config as config
107        logging.info("using default local_config")
108    else:
109        logging.info("found local_config in %s", os.getcwd())
110else:
111    logging.info("found local_config in %s", PATH_APP)
112
113
114from sas.sasgui.guiframe.customdir  import SetupCustom
115c_conf_dir = SetupCustom().setup_dir(PATH_APP)
116custom_config = _find_local_config('custom_config', c_conf_dir)
117if custom_config is None:
118    custom_config = _find_local_config('custom_config', os.getcwd())
119    if custom_config is None:
120        msgConfig = "Custom_config file was not imported"
121        logging.info(msgConfig)
122    else:
123        logging.info("using custom_config in %s", os.getcwd())
124else:
125    logging.info("using custom_config from %s", c_conf_dir)
126
127#read some constants from config
128APPLICATION_STATE_EXTENSION = config.APPLICATION_STATE_EXTENSION
129APPLICATION_NAME = config.__appname__
130SPLASH_SCREEN_PATH = config.SPLASH_SCREEN_PATH
131WELCOME_PANEL_ON = config.WELCOME_PANEL_ON
132SPLASH_SCREEN_WIDTH = config.SPLASH_SCREEN_WIDTH
133SPLASH_SCREEN_HEIGHT = config.SPLASH_SCREEN_HEIGHT
134SS_MAX_DISPLAY_TIME = config.SS_MAX_DISPLAY_TIME
135if not WELCOME_PANEL_ON:
136    WELCOME_PANEL_SHOW = False
137else:
138    WELCOME_PANEL_SHOW = True
139try:
140    DATALOADER_SHOW = custom_config.DATALOADER_SHOW
141    TOOLBAR_SHOW = custom_config.TOOLBAR_SHOW
142    FIXED_PANEL = custom_config.FIXED_PANEL
143    if WELCOME_PANEL_ON:
144        WELCOME_PANEL_SHOW = custom_config.WELCOME_PANEL_SHOW
145    PLOPANEL_WIDTH = custom_config.PLOPANEL_WIDTH
146    DATAPANEL_WIDTH = custom_config.DATAPANEL_WIDTH
147    GUIFRAME_WIDTH = custom_config.GUIFRAME_WIDTH
148    GUIFRAME_HEIGHT = custom_config.GUIFRAME_HEIGHT
149    CONTROL_WIDTH = custom_config.CONTROL_WIDTH
150    CONTROL_HEIGHT = custom_config.CONTROL_HEIGHT
151    DEFAULT_PERSPECTIVE = custom_config.DEFAULT_PERSPECTIVE
152    CLEANUP_PLOT = custom_config.CLEANUP_PLOT
153    # custom open_path
154    open_folder = custom_config.DEFAULT_OPEN_FOLDER
155    if open_folder != None and os.path.isdir(open_folder):
156        DEFAULT_OPEN_FOLDER = os.path.abspath(open_folder)
157    else:
158        DEFAULT_OPEN_FOLDER = PATH_APP
159except AttributeError:
160    DATALOADER_SHOW = True
161    TOOLBAR_SHOW = True
162    FIXED_PANEL = True
163    WELCOME_PANEL_SHOW = False
164    PLOPANEL_WIDTH = config.PLOPANEL_WIDTH
165    DATAPANEL_WIDTH = config.DATAPANEL_WIDTH
166    GUIFRAME_WIDTH = config.GUIFRAME_WIDTH
167    GUIFRAME_HEIGHT = config.GUIFRAME_HEIGHT
168    CONTROL_WIDTH = -1
169    CONTROL_HEIGHT = -1
170    DEFAULT_PERSPECTIVE = None
171    CLEANUP_PLOT = False
172    DEFAULT_OPEN_FOLDER = PATH_APP
173
174DEFAULT_STYLE = config.DEFAULT_STYLE
175
176PLUGIN_STATE_EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS
177OPEN_SAVE_MENU = config.OPEN_SAVE_PROJECT_MENU
178VIEW_MENU = config.VIEW_MENU
179EDIT_MENU = config.EDIT_MENU
180extension_list = []
181if APPLICATION_STATE_EXTENSION is not None:
182    extension_list.append(APPLICATION_STATE_EXTENSION)
183EXTENSIONS = PLUGIN_STATE_EXTENSIONS + extension_list
184try:
185    PLUGINS_WLIST = '|'.join(config.PLUGINS_WLIST)
186except AttributeError:
187    PLUGINS_WLIST = ''
188APPLICATION_WLIST = config.APPLICATION_WLIST
189IS_WIN = True
190IS_LINUX = False
191CLOSE_SHOW = True
192TIME_FACTOR = 2
193NOT_SO_GRAPH_LIST = ["BoxSum"]
194
195class Communicate(QtCore.QObject):
196    """
197    Utility class for tracking of the Qt signals
198    """
199    # File got successfully read
200    fileReadSignal = QtCore.pyqtSignal(list)
201
202    # Open File returns "list" of paths
203    fileDataReceivedSignal = QtCore.pyqtSignal(dict)
204
205    # Update Main window status bar with "str"
206    # Old "StatusEvent"
207    statusBarUpdateSignal = QtCore.pyqtSignal(str)
208
209    # Send data to the current perspective
210    updatePerspectiveWithDataSignal = QtCore.pyqtSignal(list)
211
212    # New data in current perspective
213    updateModelFromPerspectiveSignal = QtCore.pyqtSignal(QtGui.QStandardItem)
214
215    # New plot requested from the GUI manager
216    # Old "NewPlotEvent"
217    plotRequestedSignal = QtCore.pyqtSignal(str)
218
219    # Progress bar update value
220    progressBarUpdateSignal = QtCore.pyqtSignal(int)
221
222    # Workspace charts added/removed
223    activeGraphsSignal = QtCore.pyqtSignal(list)
224
225
226def updateModelItem(item, update_data, name=""):
227    """
228    Adds a checkboxed row named "name" to QStandardItem
229    Adds QVariant 'update_data' to that row.
230    """
231    assert isinstance(item, QtGui.QStandardItem)
232    assert isinstance(update_data, QtCore.QVariant)
233
234    checkbox_item = QtGui.QStandardItem(True)
235    checkbox_item.setCheckable(True)
236    checkbox_item.setCheckState(QtCore.Qt.Checked)
237    checkbox_item.setText(name)
238
239    # Add "Info" item
240    py_update_data = update_data.toPyObject()
241    if isinstance(py_update_data, (Data1D or Data2D)):
242        # If Data1/2D added - extract Info from it
243        info_item = infoFromData(py_update_data)
244    else:
245        # otherwise just add a naked item
246        info_item = QtGui.QStandardItem("Info")
247
248    # Add the actual Data1D/Data2D object
249    object_item = QtGui.QStandardItem()
250    object_item.setData(update_data)
251
252    # Set the data object as the first child
253    checkbox_item.setChild(0, object_item)
254
255    # Set info_item as the second child
256    checkbox_item.setChild(1, info_item)
257
258    # Append the new row to the main item
259    item.appendRow(checkbox_item)
260
261def plotsFromCheckedItems(model_item):
262    """
263    Returns the list of plots for items in the model which are checked
264    """
265    assert isinstance(model_item, QtGui.QStandardItemModel)
266
267    plot_data = []
268    # Iterate over model looking for items with checkboxes
269    for index in range(model_item.rowCount()):
270        item = model_item.item(index)
271        if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
272            # TODO: assure item type is correct (either data1/2D or Plotter)
273            plot_data.append(item.child(0).data().toPyObject())
274        # Going 1 level deeper only
275        for index_2 in range(item.rowCount()):
276            item_2 = item.child(index_2)
277            if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked:
278                # TODO: assure item type is correct (either data1/2D or Plotter)
279                plot_data.append(item_2.child(0).data().toPyObject())
280
281    return plot_data
282
283def infoFromData(data):
284    """
285    Given Data1D/Data2D object, extract relevant Info elements
286    and add them to a model item
287    """
288    assert isinstance(data, (Data1D, Data2D))
289
290    info_item = QtGui.QStandardItem("Info")
291
292    title_item = QtGui.QStandardItem("Title: " + data.title)
293    info_item.appendRow(title_item)
294    run_item = QtGui.QStandardItem("Run: " + str(data.run))
295    info_item.appendRow(run_item)
296    type_item = QtGui.QStandardItem("Type: " + str(data.__class__.__name__))
297    info_item.appendRow(type_item)
298
299    if data.path:
300        path_item = QtGui.QStandardItem("Path: " + data.path)
301        info_item.appendRow(path_item)
302
303    if data.instrument:
304        instr_item = QtGui.QStandardItem("Instrument: " + data.instrument)
305        info_item.appendRow(instr_item)
306
307    process_item = QtGui.QStandardItem("Process")
308    if isinstance(data.process, list) and data.process:
309        for process in data.process:
310            process_date = process.date
311            process_date_item = QtGui.QStandardItem("Date: " + process_date)
312            process_item.appendRow(process_date_item)
313
314            process_descr = process.description
315            process_descr_item = QtGui.QStandardItem("Description: " + process_descr)
316            process_item.appendRow(process_descr_item)
317
318            process_name = process.name
319            process_name_item = QtGui.QStandardItem("Name: " + process_name)
320            process_item.appendRow(process_name_item)
321
322    info_item.appendRow(process_item)
323
324    return info_item
325
326def openLink(url):
327    """
328    Open a URL in an external browser.
329    Check the URL first, though.
330    """
331    parsed_url = urlparse.urlparse(url)
332    if parsed_url.scheme:
333        webbrowser.open(url)
334    else:
335        msg = "Attempt at opening an invalid URL"
336        raise AttributeError, msg
337
338def retrieveData1d(data):
339    """
340    Retrieve 1D data from file and construct its text
341    representation
342    """
343    if not isinstance(data, Data1D):
344        msg = "Incorrect type passed to retrieveData1d"
345        raise AttributeError, msg
346    try:
347        xmin = min(data.x)
348        ymin = min(data.y)
349    except:
350        msg = "Unable to find min/max of \n data named %s" % \
351                    data.filename
352        logging.error(msg)
353        raise ValueError, msg
354
355    text = data.__str__()
356    text += 'Data Min Max:\n'
357    text += 'X_min = %s:  X_max = %s\n' % (xmin, max(data.x))
358    text += 'Y_min = %s:  Y_max = %s\n' % (ymin, max(data.y))
359    if data.dy != None:
360        text += 'dY_min = %s:  dY_max = %s\n' % (min(data.dy), max(data.dy))
361    text += '\nData Points:\n'
362    x_st = "X"
363    for index in range(len(data.x)):
364        if data.dy != None and len(data.dy) > index:
365            dy_val = data.dy[index]
366        else:
367            dy_val = 0.0
368        if data.dx != None and len(data.dx) > index:
369            dx_val = data.dx[index]
370        else:
371            dx_val = 0.0
372        if data.dxl != None and len(data.dxl) > index:
373            if index == 0:
374                x_st = "Xl"
375            dx_val = data.dxl[index]
376        elif data.dxw != None and len(data.dxw) > index:
377            if index == 0:
378                x_st = "Xw"
379            dx_val = data.dxw[index]
380
381        if index == 0:
382            text += "<index> \t<X> \t<Y> \t<dY> \t<d%s>\n" % x_st
383        text += "%s \t%s \t%s \t%s \t%s\n" % (index,
384                                                data.x[index],
385                                                data.y[index],
386                                                dy_val,
387                                                dx_val)
388    return text
389
390def retrieveData2d(data):
391    """
392    Retrieve 2D data from file and construct its text
393    representation
394    """
395    if not isinstance(data, Data2D):
396        msg = "Incorrect type passed to retrieveData2d"
397        raise AttributeError, msg
398
399    text = data.__str__()
400    text += 'Data Min Max:\n'
401    text += 'I_min = %s\n' % min(data.data)
402    text += 'I_max = %s\n\n' % max(data.data)
403    text += 'Data (First 2501) Points:\n'
404    text += 'Data columns include err(I).\n'
405    text += 'ASCII data starts here.\n'
406    text += "<index> \t<Qx> \t<Qy> \t<I> \t<dI> \t<dQparal> \t<dQperp>\n"
407    di_val = 0.0
408    dx_val = 0.0
409    dy_val = 0.0
410    len_data = len(data.qx_data)
411    for index in xrange(0, len_data):
412        x_val = data.qx_data[index]
413        y_val = data.qy_data[index]
414        i_val = data.data[index]
415        if data.err_data != None:
416            di_val = data.err_data[index]
417        if data.dqx_data != None:
418            dx_val = data.dqx_data[index]
419        if data.dqy_data != None:
420            dy_val = data.dqy_data[index]
421
422        text += "%s \t%s \t%s \t%s \t%s \t%s \t%s\n" % (index,
423                                                        x_val,
424                                                        y_val,
425                                                        i_val,
426                                                        di_val,
427                                                        dx_val,
428                                                        dy_val)
429        # Takes too long time for typical data2d: Break here
430        if index >= 2500:
431            text += ".............\n"
432            break
433
434    return text
435
436def onTXTSave(data, path):
437    """
438    Save file as formatted txt
439    """
440    with open(path,'w') as out:
441        has_errors = True
442        if data.dy == None or data.dy == []:
443            has_errors = False
444        # Sanity check
445        if has_errors:
446            try:
447                if len(data.y) != len(data.dy):
448                    has_errors = False
449            except:
450                has_errors = False
451        if has_errors:
452            if data.dx != None and data.dx != []:
453                out.write("<X>   <Y>   <dY>   <dX>\n")
454            else:
455                out.write("<X>   <Y>   <dY>\n")
456        else:
457            out.write("<X>   <Y>\n")
458
459        for i in range(len(data.x)):
460            if has_errors:
461                if data.dx != None and data.dx != []:
462                    if  data.dx[i] != None:
463                        out.write("%g  %g  %g  %g\n" % (data.x[i],
464                                                        data.y[i],
465                                                        data.dy[i],
466                                                        data.dx[i]))
467                    else:
468                        out.write("%g  %g  %g\n" % (data.x[i],
469                                                    data.y[i],
470                                                    data.dy[i]))
471                else:
472                    out.write("%g  %g  %g\n" % (data.x[i],
473                                                data.y[i],
474                                                data.dy[i]))
475            else:
476                out.write("%g  %g\n" % (data.x[i],
477                                        data.y[i]))
478
479def saveData1D(data):
480    """
481    Save 1D data points
482    """
483    default_name = os.path.basename(data.filename)
484    default_name, extension = os.path.splitext(default_name)
485    default_name += "_out" + extension
486
487    wildcard = "Text files (*.txt);;"\
488                "CanSAS 1D files(*.xml)"
489    kwargs = {
490        'caption'   : 'Save As',
491        'directory' : default_name,
492        'filter'    : wildcard,
493        'parent'    : None,
494    }
495    # Query user for filename.
496    filename = QtGui.QFileDialog.getSaveFileName(**kwargs)
497
498    # User cancelled.
499    if not filename:
500        return
501
502    filename = str(filename)
503
504    #Instantiate a loader
505    loader = Loader()
506    if os.path.splitext(filename)[1].lower() == ".txt":
507        onTXTSave(data, filename)
508    if os.path.splitext(filename)[1].lower() == ".xml":
509        loader.save(filename, data, ".xml")
510
511def saveData2D(data):
512    """
513    Save data2d dialog
514    """
515    default_name = os.path.basename(data.filename)
516    default_name, _ = os.path.splitext(default_name)
517    ext_format = ".dat"
518    default_name += "_out" + ext_format
519
520    wildcard = "IGOR/DAT 2D file in Q_map (*.dat)"
521    kwargs = {
522        'caption'   : 'Save As',
523        'directory' : default_name,
524        'filter'    : wildcard,
525        'parent'    : None,
526    }
527    # Query user for filename.
528    filename = QtGui.QFileDialog.getSaveFileName(**kwargs)
529
530    # User cancelled.
531    if not filename:
532        return
533    filename = str(filename)
534    #Instantiate a loader
535    loader = Loader()
536
537    if os.path.splitext(filename)[1].lower() == ext_format:
538        loader.save(filename, data, ext_format)
539
540class FormulaValidator(QtGui.QValidator):
541    def __init__(self, parent=None):
542        super(FormulaValidator, self).__init__(parent)
543 
544    def validate(self, input, pos):
545        try:
546            Formula(str(input))
547            self._setStyleSheet("")
548            return QtGui.QValidator.Acceptable, pos
549
550        except Exception as e:
551            self._setStyleSheet("background-color:pink;")
552            return QtGui.QValidator.Intermediate, pos
553
554    def _setStyleSheet(self, value):
555        try:
556            if self.parent():
557                self.parent().setStyleSheet(value)
558        except:
559            pass
Note: See TracBrowser for help on using the repository browser.