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

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 adf81b8 was 31c5b58, checked in by Piotr Rozyczko <rozyczko@…>, 7 years ago

Refactored to allow running with run.py.
Minor fixes to plotting.

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