source: sasview/src/sas/qtgui/GuiUtils.py @ 570a58f9

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

Linear fits for 1D charts

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