source: sasview/src/sas/qtgui/Utilities/GuiUtils.py @ 56b22f9

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

Code cleanup and minor refactoring

  • Property mode set to 100644
File size: 25.8 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.plottools import transform
31from sas.sasgui.plottools.convert_units import convert_unit
32from sas.sasgui.guiframe.dataFitting import Data1D
33from sas.sasgui.guiframe.dataFitting import Data2D
34from sas.sascalc.dataloader.loader import Loader
35
36
37def 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
69def 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
78def _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
100PATH_APP = get_app_dir()
101DATAPATH = 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
107config = _find_local_config('local_config', PATH_APP)
108
109if 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())
118else:
119    pass
120    #logging.info("found local_config in %s", PATH_APP)
121
122from sas.sasgui.guiframe.customdir  import SetupCustom
123c_conf_dir = SetupCustom().setup_dir(PATH_APP)
124
125custom_config = _find_local_config('custom_config', c_conf_dir)
126if 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())
134else:
135    pass
136    #logging.info("using custom_config from %s", c_conf_dir)
137
138#read some constants from config
139APPLICATION_STATE_EXTENSION = config.APPLICATION_STATE_EXTENSION
140APPLICATION_NAME = config.__appname__
141SPLASH_SCREEN_PATH = config.SPLASH_SCREEN_PATH
142WELCOME_PANEL_ON = config.WELCOME_PANEL_ON
143SPLASH_SCREEN_WIDTH = config.SPLASH_SCREEN_WIDTH
144SPLASH_SCREEN_HEIGHT = config.SPLASH_SCREEN_HEIGHT
145SS_MAX_DISPLAY_TIME = config.SS_MAX_DISPLAY_TIME
146if not WELCOME_PANEL_ON:
147    WELCOME_PANEL_SHOW = False
148else:
149    WELCOME_PANEL_SHOW = True
150try:
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
170except 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
185DEFAULT_STYLE = config.DEFAULT_STYLE
186
187PLUGIN_STATE_EXTENSIONS = config.PLUGIN_STATE_EXTENSIONS
188OPEN_SAVE_MENU = config.OPEN_SAVE_PROJECT_MENU
189VIEW_MENU = config.VIEW_MENU
190EDIT_MENU = config.EDIT_MENU
191extension_list = []
192if APPLICATION_STATE_EXTENSION is not None:
193    extension_list.append(APPLICATION_STATE_EXTENSION)
194EXTENSIONS = PLUGIN_STATE_EXTENSIONS + extension_list
195try:
196    PLUGINS_WLIST = '|'.join(config.PLUGINS_WLIST)
197except AttributeError:
198    PLUGINS_WLIST = ''
199APPLICATION_WLIST = config.APPLICATION_WLIST
200IS_WIN = True
201IS_LINUX = False
202CLOSE_SHOW = True
203TIME_FACTOR = 2
204NOT_SO_GRAPH_LIST = ["BoxSum"]
205
206class 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(list)
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
249def 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
276def 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
310def 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
325def plotsFromFilename(filename, model_item):
326    """
327    Returns the list of plots for the item with text=filename in the model
328    """
329    assert isinstance(model_item, QtGui.QStandardItemModel)
330    assert isinstance(filename, basestring)
331
332    plot_data = []
333    # Iterate over model looking for named items
334    for index in range(model_item.rowCount()):
335        item = model_item.item(index)
336        if str(item.text()) == filename:
337            # TODO: assure item type is correct (either data1/2D or Plotter)
338            plot_data.append(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():
343                    # TODO: assure item type is correct (either data1/2D or Plotter)
344                    plot_data.append(item_2.child(0).data().toPyObject())
345
346    return plot_data
347
348def plotsFromCheckedItems(model_item):
349    """
350    Returns the list of plots for items in the model which are checked
351    """
352    assert isinstance(model_item, QtGui.QStandardItemModel)
353
354    plot_data = []
355    # Iterate over model looking for items with checkboxes
356    for index in range(model_item.rowCount()):
357        item = model_item.item(index)
358        if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
359            # TODO: assure item type is correct (either data1/2D or Plotter)
360            plot_data.append((item, item.child(0).data().toPyObject()))
361        # Going 1 level deeper only
362        for index_2 in range(item.rowCount()):
363            item_2 = item.child(index_2)
364            if item_2 and item_2.isCheckable() and item_2.checkState() == QtCore.Qt.Checked:
365                # TODO: assure item type is correct (either data1/2D or Plotter)
366                plot_data.append((item_2, item_2.child(0).data().toPyObject()))
367
368    return plot_data
369
370def infoFromData(data):
371    """
372    Given Data1D/Data2D object, extract relevant Info elements
373    and add them to a model item
374    """
375    assert isinstance(data, (Data1D, Data2D))
376
377    info_item = QtGui.QStandardItem("Info")
378
379    title_item = QtGui.QStandardItem("Title: " + data.title)
380    info_item.appendRow(title_item)
381    run_item = QtGui.QStandardItem("Run: " + str(data.run))
382    info_item.appendRow(run_item)
383    type_item = QtGui.QStandardItem("Type: " + str(data.__class__.__name__))
384    info_item.appendRow(type_item)
385
386    if data.path:
387        path_item = QtGui.QStandardItem("Path: " + data.path)
388        info_item.appendRow(path_item)
389
390    if data.instrument:
391        instr_item = QtGui.QStandardItem("Instrument: " + data.instrument)
392        info_item.appendRow(instr_item)
393
394    process_item = QtGui.QStandardItem("Process")
395    if isinstance(data.process, list) and data.process:
396        for process in data.process:
397            process_date = process.date
398            process_date_item = QtGui.QStandardItem("Date: " + process_date)
399            process_item.appendRow(process_date_item)
400
401            process_descr = process.description
402            process_descr_item = QtGui.QStandardItem("Description: " + process_descr)
403            process_item.appendRow(process_descr_item)
404
405            process_name = process.name
406            process_name_item = QtGui.QStandardItem("Name: " + process_name)
407            process_item.appendRow(process_name_item)
408
409    info_item.appendRow(process_item)
410
411    return info_item
412
413def openLink(url):
414    """
415    Open a URL in an external browser.
416    Check the URL first, though.
417    """
418    parsed_url = urlparse.urlparse(url)
419    if parsed_url.scheme:
420        webbrowser.open(url)
421    else:
422        msg = "Attempt at opening an invalid URL"
423        raise AttributeError, msg
424
425def retrieveData1d(data):
426    """
427    Retrieve 1D data from file and construct its text
428    representation
429    """
430    if not isinstance(data, Data1D):
431        msg = "Incorrect type passed to retrieveData1d"
432        raise AttributeError, msg
433    try:
434        xmin = min(data.x)
435        ymin = min(data.y)
436    except:
437        msg = "Unable to find min/max of \n data named %s" % \
438                    data.filename
439        #logging.error(msg)
440        raise ValueError, msg
441
442    text = data.__str__()
443    text += 'Data Min Max:\n'
444    text += 'X_min = %s:  X_max = %s\n' % (xmin, max(data.x))
445    text += 'Y_min = %s:  Y_max = %s\n' % (ymin, max(data.y))
446    if data.dy != None:
447        text += 'dY_min = %s:  dY_max = %s\n' % (min(data.dy), max(data.dy))
448    text += '\nData Points:\n'
449    x_st = "X"
450    for index in range(len(data.x)):
451        if data.dy != None and len(data.dy) > index:
452            dy_val = data.dy[index]
453        else:
454            dy_val = 0.0
455        if data.dx != None and len(data.dx) > index:
456            dx_val = data.dx[index]
457        else:
458            dx_val = 0.0
459        if data.dxl != None and len(data.dxl) > index:
460            if index == 0:
461                x_st = "Xl"
462            dx_val = data.dxl[index]
463        elif data.dxw != None and len(data.dxw) > index:
464            if index == 0:
465                x_st = "Xw"
466            dx_val = data.dxw[index]
467
468        if index == 0:
469            text += "<index> \t<X> \t<Y> \t<dY> \t<d%s>\n" % x_st
470        text += "%s \t%s \t%s \t%s \t%s\n" % (index,
471                                                data.x[index],
472                                                data.y[index],
473                                                dy_val,
474                                                dx_val)
475    return text
476
477def retrieveData2d(data):
478    """
479    Retrieve 2D data from file and construct its text
480    representation
481    """
482    if not isinstance(data, Data2D):
483        msg = "Incorrect type passed to retrieveData2d"
484        raise AttributeError, msg
485
486    text = data.__str__()
487    text += 'Data Min Max:\n'
488    text += 'I_min = %s\n' % min(data.data)
489    text += 'I_max = %s\n\n' % max(data.data)
490    text += 'Data (First 2501) Points:\n'
491    text += 'Data columns include err(I).\n'
492    text += 'ASCII data starts here.\n'
493    text += "<index> \t<Qx> \t<Qy> \t<I> \t<dI> \t<dQparal> \t<dQperp>\n"
494    di_val = 0.0
495    dx_val = 0.0
496    dy_val = 0.0
497    len_data = len(data.qx_data)
498    for index in xrange(0, len_data):
499        x_val = data.qx_data[index]
500        y_val = data.qy_data[index]
501        i_val = data.data[index]
502        if data.err_data != None:
503            di_val = data.err_data[index]
504        if data.dqx_data != None:
505            dx_val = data.dqx_data[index]
506        if data.dqy_data != None:
507            dy_val = data.dqy_data[index]
508
509        text += "%s \t%s \t%s \t%s \t%s \t%s \t%s\n" % (index,
510                                                        x_val,
511                                                        y_val,
512                                                        i_val,
513                                                        di_val,
514                                                        dx_val,
515                                                        dy_val)
516        # Takes too long time for typical data2d: Break here
517        if index >= 2500:
518            text += ".............\n"
519            break
520
521    return text
522
523def onTXTSave(data, path):
524    """
525    Save file as formatted txt
526    """
527    with open(path,'w') as out:
528        has_errors = True
529        if data.dy == None or data.dy == []:
530            has_errors = False
531        # Sanity check
532        if has_errors:
533            try:
534                if len(data.y) != len(data.dy):
535                    has_errors = False
536            except:
537                has_errors = False
538        if has_errors:
539            if data.dx != None and data.dx != []:
540                out.write("<X>   <Y>   <dY>   <dX>\n")
541            else:
542                out.write("<X>   <Y>   <dY>\n")
543        else:
544            out.write("<X>   <Y>\n")
545
546        for i in range(len(data.x)):
547            if has_errors:
548                if data.dx != None and data.dx != []:
549                    if  data.dx[i] != None:
550                        out.write("%g  %g  %g  %g\n" % (data.x[i],
551                                                        data.y[i],
552                                                        data.dy[i],
553                                                        data.dx[i]))
554                    else:
555                        out.write("%g  %g  %g\n" % (data.x[i],
556                                                    data.y[i],
557                                                    data.dy[i]))
558                else:
559                    out.write("%g  %g  %g\n" % (data.x[i],
560                                                data.y[i],
561                                                data.dy[i]))
562            else:
563                out.write("%g  %g\n" % (data.x[i],
564                                        data.y[i]))
565
566def saveData1D(data):
567    """
568    Save 1D data points
569    """
570    default_name = os.path.basename(data.filename)
571    default_name, extension = os.path.splitext(default_name)
572    default_name += "_out" + extension
573
574    wildcard = "Text files (*.txt);;"\
575                "CanSAS 1D files(*.xml)"
576    kwargs = {
577        'caption'   : 'Save As',
578        'directory' : default_name,
579        'filter'    : wildcard,
580        'parent'    : None,
581    }
582    # Query user for filename.
583    filename = QtGui.QFileDialog.getSaveFileName(**kwargs)
584
585    # User cancelled.
586    if not filename:
587        return
588
589    filename = str(filename)
590
591    #Instantiate a loader
592    loader = Loader()
593    if os.path.splitext(filename)[1].lower() == ".txt":
594        onTXTSave(data, filename)
595    if os.path.splitext(filename)[1].lower() == ".xml":
596        loader.save(filename, data, ".xml")
597
598def saveData2D(data):
599    """
600    Save data2d dialog
601    """
602    default_name = os.path.basename(data.filename)
603    default_name, _ = os.path.splitext(default_name)
604    ext_format = ".dat"
605    default_name += "_out" + ext_format
606
607    wildcard = "IGOR/DAT 2D file in Q_map (*.dat)"
608    kwargs = {
609        'caption'   : 'Save As',
610        'directory' : default_name,
611        'filter'    : wildcard,
612        'parent'    : None,
613    }
614    # Query user for filename.
615    filename = QtGui.QFileDialog.getSaveFileName(**kwargs)
616
617    # User cancelled.
618    if not filename:
619        return
620    filename = str(filename)
621    #Instantiate a loader
622    loader = Loader()
623
624    if os.path.splitext(filename)[1].lower() == ext_format:
625        loader.save(filename, data, ext_format)
626
627class FormulaValidator(QtGui.QValidator):
628    def __init__(self, parent=None):
629        super(FormulaValidator, self).__init__(parent)
630 
631    def validate(self, input, pos):
632        try:
633            Formula(str(input))
634            self._setStyleSheet("")
635            return QtGui.QValidator.Acceptable, pos
636
637        except Exception as e:
638            self._setStyleSheet("background-color:pink;")
639            return QtGui.QValidator.Intermediate, pos
640
641    def _setStyleSheet(self, value):
642        try:
643            if self.parent():
644                self.parent().setStyleSheet(value)
645        except:
646            pass
647
648def xyTransform(data, xLabel="", yLabel=""):
649    """
650    Transforms x and y in View and set the scale
651    """
652    # Changing the scale might be incompatible with
653    # currently displayed data (for instance, going
654    # from ln to log when all plotted values have
655    # negative natural logs).
656    # Go linear and only change the scale at the end.
657    xscale = 'linear'
658    yscale = 'linear'
659    # Local data is either 1D or 2D
660    if data.id == 'fit':
661        return
662
663    # control axis labels from the panel itself
664    yname, yunits = data.get_yaxis()
665    xname, xunits = data.get_xaxis()
666
667    # Goes through all possible scales
668    # self.x_label is already wrapped with Latex "$", so using the argument
669
670    # X
671    if xLabel == "x":
672        data.transformX(transform.toX, transform.errToX)
673        xLabel = "%s(%s)" % (xname, xunits)
674    if xLabel == "x^(2)":
675        data.transformX(transform.toX2, transform.errToX2)
676        xunits = convert_unit(2, xunits)
677        xLabel = "%s^{2}(%s)" % (xname, xunits)
678    if xLabel == "x^(4)":
679        data.transformX(transform.toX4, transform.errToX4)
680        xunits = convert_unit(4, xunits)
681        xLabel = "%s^{4}(%s)" % (xname, xunits)
682    if xLabel == "ln(x)":
683        data.transformX(transform.toLogX, transform.errToLogX)
684        xLabel = "\ln{(%s)}(%s)" % (xname, xunits)
685    if xLabel == "log10(x)":
686        data.transformX(transform.toX_pos, transform.errToX_pos)
687        xscale = 'log'
688        xLabel = "%s(%s)" % (xname, xunits)
689    if xLabel == "log10(x^(4))":
690        data.transformX(transform.toX4, transform.errToX4)
691        xunits = convert_unit(4, xunits)
692        xLabel = "%s^{4}(%s)" % (xname, xunits)
693        xscale = 'log'
694
695    # Y
696    if yLabel == "ln(y)":
697        data.transformY(transform.toLogX, transform.errToLogX)
698        yLabel = "\ln{(%s)}(%s)" % (yname, yunits)
699    if yLabel == "y":
700        data.transformY(transform.toX, transform.errToX)
701        yLabel = "%s(%s)" % (yname, yunits)
702    if yLabel == "log10(y)":
703        data.transformY(transform.toX_pos, transform.errToX_pos)
704        yscale = 'log'
705        yLabel = "%s(%s)" % (yname, yunits)
706    if yLabel == "y^(2)":
707        data.transformY(transform.toX2, transform.errToX2)
708        yunits = convert_unit(2, yunits)
709        yLabel = "%s^{2}(%s)" % (yname, yunits)
710    if yLabel == "1/y":
711        data.transformY(transform.toOneOverX, transform.errOneOverX)
712        yunits = convert_unit(-1, yunits)
713        yLabel = "1/%s(%s)" % (yname, yunits)
714    if yLabel == "y*x^(2)":
715        data.transformY(transform.toYX2, transform.errToYX2)
716        xunits = convert_unit(2, xunits)
717        yLabel = "%s \ \ %s^{2}(%s%s)" % (yname, xname, yunits, xunits)
718    if yLabel == "y*x^(4)":
719        data.transformY(transform.toYX4, transform.errToYX4)
720        xunits = convert_unit(4, xunits)
721        yLabel = "%s \ \ %s^{4}(%s%s)" % (yname, xname, yunits, xunits)
722    if yLabel == "1/sqrt(y)":
723        data.transformY(transform.toOneOverSqrtX,
724                                transform.errOneOverSqrtX)
725        yunits = convert_unit(-0.5, yunits)
726        yLabel = "1/\sqrt{%s}(%s)" % (yname, yunits)
727    if yLabel == "ln(y*x)":
728        data.transformY(transform.toLogXY, transform.errToLogXY)
729        yLabel = "\ln{(%s \ \ %s)}(%s%s)" % (yname, xname, yunits, xunits)
730    if yLabel == "ln(y*x^(2))":
731        data.transformY(transform.toLogYX2, transform.errToLogYX2)
732        xunits = convert_unit(2, xunits)
733        yLabel = "\ln (%s \ \ %s^{2})(%s%s)" % (yname, xname, yunits, xunits)
734    if yLabel == "ln(y*x^(4))":
735        data.transformY(transform.toLogYX4, transform.errToLogYX4)
736        xunits = convert_unit(4, xunits)
737        yLabel = "\ln (%s \ \ %s^{4})(%s%s)" % (yname, xname, yunits, xunits)
738    if yLabel == "log10(y*x^(4))":
739        data.transformY(transform.toYX4, transform.errToYX4)
740        xunits = convert_unit(4, xunits)
741        yscale = 'log'
742        yLabel = "%s \ \ %s^{4}(%s%s)" % (yname, xname, yunits, xunits)
743
744    # Perform the transformation of data in data1d->View
745    data.transformView()
746
747    return (xLabel, yLabel, xscale, yscale)
748
749def dataFromItem(item):
750    """
751    Retrieve Data1D/2D component from QStandardItem.
752    The assumption - data stored in SasView standard, in child 0
753    """
754    return item.child(0).data().toPyObject()
755
756def formatNumber(value, high=False):
757    """
758    Return a float in a standardized, human-readable formatted string.
759    This is used to output readable (e.g. x.xxxe-y) values to the panel.
760    """
761    try:
762        value = float(value)
763    except:
764        output = "NaN"
765        return output.lstrip().rstrip()
766
767    if high:
768        output = "%-6.4g" % value
769
770    else:
771        output = "%-5.3g" % value
772    return output.lstrip().rstrip()
Note: See TracBrowser for help on using the repository browser.