source: sasview/src/sas/qtgui/GuiUtils.py @ 83d6249

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

Perspectives are now switchable and can be added "dynamically"

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