source: sasview/guiframe/data_loader.py @ 0912feab

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 0912feab was 32c0841, checked in by Gervaise Alina <gervyh@…>, 14 years ago

working on pylint

  • Property mode set to 100644
File size: 11.7 KB
RevLine 
[b3644f3]1
[32c0841]2import os
3import sys
4import numpy
[de9483d]5import wx
[a618972]6import re
[b3644f3]7
[ff3f900b]8from dataFitting import Data1D
9from dataFitting import Data2D
[c7bc3e7]10from DataLoader.loader import Loader
[b3644f3]11from load_thread import DataReader
[7a07864]12from sans.guicomm.events import FitStateUpdateEvent
13from sans.guicomm.events import InvStateUpdateEvent
[32c0841]14from sans.guicomm.events import StatusEvent
15from sans.guicomm.events import NewPlotEvent
[b3644f3]16
[32c0841]17SVS_FILE_EXT = ['.svs', '.inv', '.prv', '.fitv']
[b3644f3]18
[d792e813]19def enable_add_data(existing_panel, new_plot):
20    """
[d955bf19]21    Enable append data on a plot panel
[d792e813]22    """
[32c0841]23    is_theory = len(existing_panel.plots) <= 1 and \
24        existing_panel.plots.values()[0].__class__.__name__ == "Theory1D"
[d792e813]25       
26    is_data2d = hasattr(new_plot, 'data')
27    is_data1d = existing_panel.__class__.__name__ == "ModelPanel1D"\
28        and existing_panel.group_id is not None
[d45e7e9]29    has_meta_data = hasattr(new_plot, 'meta_data')
30   
31    #disable_add_data if the data is being recovered from  a saved state file.
32    is_state_data = False
33    if has_meta_data:
34        if 'invstate' in new_plot.meta_data: is_state_data = True
35        if  'prstate' in new_plot.meta_data: is_state_data = True
36        if  'fitstate' in new_plot.meta_data: is_state_data = True
37
38    return is_data1d and not is_data2d and not is_theory and not is_state_data
[58eac5d]39
[a618972]40def parse_name(name, expression):
41    """
[d955bf19]42    remove "_" in front of a name
[a618972]43    """
44    if re.match(expression, name) is not None:
45        word = re.split(expression, name, 1)
46        for item in word:           
47            if item.lstrip().rstrip() != '':
48                return item
49    else:
50        return name
51   
[de9483d]52def choose_data_file(parent, location=None):
[d955bf19]53    """
54    """
[de9483d]55    path = None
[196608d]56    if location == None:
[de9483d]57        location = os.getcwd()
[c7bc3e7]58   
59    l = Loader()
60    cards = l.get_wildcards()
61    wlist = '|'.join(cards)
62   
[4e9583c]63    dlg = wx.FileDialog(parent, "Choose a file", location, "", wlist, wx.OPEN)
[de9483d]64    if dlg.ShowModal() == wx.ID_OK:
65        path = dlg.GetPath()
66        mypath = os.path.basename(path)
67    dlg.Destroy()
68   
[4e9583c]69    return path
[de9483d]70
[d792e813]71def open_dialog_append_data(panel_name, data_name):
[b91c736]72    """
[d955bf19]73    Pop up an error message.
74   
75    :param panel_name: the name of the current panel
76    :param data_name: the name of the current data
77   
[b91c736]78    """
[32c0841]79    message = " Do you want to append %s data\n in " % (str(data_name))
80    message += " %s panel?\n\n" % (str(panel_name))
[b91c736]81    dial = wx.MessageDialog(None, message, 'Question',
82                       wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION)
83    if dial.ShowModal() == wx.ID_YES:
84        return True
85    else:
86        return False
[4e9583c]87   
[32c0841]88# where is this method used?
[4e9583c]89def load_ascii_1D(path):
90    """
91    Load a 1D ascii file, with errors
92    """
93    if path and os.path.isfile(path):
94   
95        file_x = numpy.zeros(0)
96        file_y = numpy.zeros(0)
97        file_dy = numpy.zeros(0)
98        file_dx = numpy.zeros(0)
99       
100        input_f = open(path,'r')
101        buff = input_f.read()
102        lines = buff.split('\n')
103       
104        has_dy = False
105        has_dx = False
106       
107        for line in lines:
108            try:
109                toks = line.split()
110                x = float(toks[0])
111                y = float(toks[1])
[32c0841]112                if len(toks) == 3:
[4e9583c]113                    has_dy = True
114                    errdy = float(toks[2])
115                else:
116                    errdy = 0.0
117                if len(toks) == 4:
118                    has_dx = True
119                    errdx = float(toks[3])
120                else:
121                    errdx = 0.0
122                file_x  = numpy.append(file_x, x)
123                file_y  = numpy.append(file_y, y)
124                file_dy = numpy.append(file_dy, dyerr)
125                file_dx = numpy.append(file_dx, dxerr)
126            except:
127                print "READ ERROR", line
128   
129        if has_dy == False:
130            file_dy = None
131        if has_dx == False:
132            file_dx = None
133           
134        return file_x, file_y, file_dy, file_dx
135    return None, None, None, None
[fc2b91a]136
[cb0d17c]137def load_error(error=None):
138    """
[d955bf19]139    Pop up an error message.
140   
141    :param error: details error message to be displayed
[cb0d17c]142    """
[0881f51]143    message = "The data file you selected could not be loaded.\n"
[cb0d17c]144    message += "Make sure the content of your file is properly formatted.\n\n"
145   
146    if error is not None:
[32c0841]147        message += "When contacting the DANSE team, mention the"
148        message += " following:\n%s" % str(error)
[cb0d17c]149   
[32c0841]150    dial = wx.MessageDialog(None, message, 'Error Loading File',
151                            wx.OK | wx.ICON_EXCLAMATION)
[cb0d17c]152    dial.ShowModal()   
153
[b3644f3]154def on_load_error(parent):
155    """
156    """
157    wx.PostEvent(parent, StatusEvent(status="Load cancel..", info="warning",
158                                                type="stop"))
[cc1ead1]159   
[b35d3d1]160def plot_data(parent, path, format=None):
[6d920cd]161    """
[d955bf19]162    Use the DataLoader loader to created data to plot.
163   
164    :param path: the path of the data to load
[b35d3d1]165    : param format: file format (as file extension)
[6d920cd]166    """
[32c0841]167    #from sans.guicomm.events import NewPlotEvent, StatusEvent
168    #from DataLoader.loader import  Loader
[cc1ead1]169    # Instantiate a loader
170    L = Loader()
171   
172    # Load data
173    try:
[b35d3d1]174        output = L.load(path, format)
[cc1ead1]175    except:
[4e9583c]176        load_error(sys.exc_value)
[cc1ead1]177        return
[b63dc6e]178    basename  = os.path.basename(path)
[cb0d17c]179    # Notify user if the loader completed the load but no data came out
180    if output == None:
[028a0e8]181        if  not basename.endswith('.svs'):
182            load_error("The data file appears to be empty.")
[cb0d17c]183        return
[cc1ead1]184 
[b63dc6e]185    root, extension = os.path.splitext(basename)
186    ext =  extension.lower()
[acb1ad1]187    filename = os.path.basename(path)
[196608d]188    if not  output.__class__.__name__ == "list":
[12aa9b5]189        ## Creating a Data2D with output
[81812d9]190        if hasattr(output,'data'):
[32c0841]191            msg = "Loading 2D data: %s" % output.filename
192            wx.PostEvent(parent, StatusEvent(status=msg, info="info",
193                                             type="stop"))
[196608d]194            new_plot = Data2D(image=None, err_image=None)
[ff3f900b]195     
[81812d9]196        else:
[32c0841]197            msg = "Loading 1D data: %s" % output.filename
198            wx.PostEvent(parent, StatusEvent(status=msg, info="info",
199                                             type="stop"))
[196608d]200            new_plot = Data1D(x=[], y=[], dx=None, dy=None)
[ff3f900b]201           
202        new_plot.copy_from_datainfo(output) 
203        output.clone_without_data(clone=new_plot)     
204     
[25ccf33]205        ## data 's name
[196608d]206        if output.filename is None or output.filename == "":
[ff3f900b]207            output.filename = str(filename)
[12aa9b5]208        ## name of the data allow to differentiate data when plotted
[a618972]209        name = parse_name(name=output.filename, expression="_")
[ff3f900b]210       
[35eeea8]211        new_plot.name = name
[12aa9b5]212        ## allow to highlight data when plotted
[81812d9]213        new_plot.interactive = True
[12aa9b5]214        ## when 2 data have the same id override the 1 st plotted
[35eeea8]215        new_plot.id = name
[12aa9b5]216        ##group_id specify on which panel to plot this data
[35eeea8]217        new_plot.group_id = name
[196608d]218        new_plot.is_data = True
[12aa9b5]219        ##post data to plot
[b91c736]220        title = output.filename
[ff3f900b]221        if hasattr(new_plot,"title"):
[b91c736]222            title = str(new_plot.title.lstrip().rstrip())
[196608d]223            if title == "":
224                title = str(name)
[ff3f900b]225        else:
226            title = str(name)
[32c0841]227        if hasattr(parent, "panel_on_focus") and \
228            not(parent.panel_on_focus is None):
229            existing_panel  = parent.panel_on_focus
230            panel_name = existing_panel.window_caption
231            data_name = new_plot.name
232            if enable_add_data(existing_panel, new_plot):
233                if open_dialog_append_data(panel_name, data_name):
234                    #add this plot the an existing panel
235                    new_plot.group_id = existing_panel.group_id
[ef16f59]236        # plot data
[af47c8d]237        wx.PostEvent(parent, NewPlotEvent(plot=new_plot, title=title))
[b63dc6e]238        if ext in SVS_FILE_EXT:
[9b18735]239            # set state and plot computation if exists
[32c0841]240            wx.PostEvent(parent, InvStateUpdateEvent())
241            wx.PostEvent(parent, FitStateUpdateEvent())
242    ## the output of the loader is a list , some xml files contain
243    #more than one data
[81812d9]244    else:
[32c0841]245        i = 0
[ef16f59]246        for item in output: 
[81812d9]247            try:
[4da35bc]248                ## Creating a Data2D with output
[32c0841]249                if hasattr(item, 'data'):
250                    msg = "Loading 2D data: %s" % item.filename
251                    wx.PostEvent(parent, StatusEvent(status=msg, info="info",
252                                                     type="stop"))
[4da35bc]253                    new_plot = Data2D(image=None, err_image=None)
254             
255                else:
[32c0841]256                    msg = "Loading 1D data: %s" % str(item.run[0])
257                    wx.PostEvent(parent, StatusEvent(status=msg, info="info",
258                                                     type="stop"))
[4da35bc]259                    try:
260                        dx = item.dx
261                        dxl = item.dxl
262                        dxw = item.dxw
263                    except:
264                        dx = None
265                        dxl = None
266                        dxw = None
267       
[32c0841]268                    new_plot = Data1D(x=item.x, y=item.y, dx=dx, dy=item.dy)
[ef16f59]269                    if dxl != None:
270                        new_plot.dxl = dxl
271                    if dxl != None:
272                        new_plot.dxw = dxw
273               
274                new_plot.copy_from_datainfo(item)   
[4da35bc]275                item.clone_without_data(clone=new_plot)   
[9b18735]276                # find original data file name without timestemp
[b35d3d1]277                name = parse_name(name=str(item.run[0]), expression="_")
[9b18735]278                max_char = name.find("[")
279                if max_char < 0:
280                    max_char = len(name)
[32c0841]281                original_name = name[0:max_char]
[ef16f59]282                #TODO: this is a very annoying feature. We should make this
283                # an option. Excel doesn't do this. Why should we?
284                # What is the requirement for this feature, and are the
285                # counter arguments stronger? Is this feature developed
286                # to please at least 80% of the users or a special few?                   
[b35d3d1]287                new_plot.name = name
288                new_plot.interactive = True
[9b18735]289                new_plot.group_id = original_name
[b35d3d1]290                new_plot.id = name
291                new_plot.is_data = True
[ef16f59]292                title = item.filename
293               
[32c0841]294                if hasattr(item, "title"):
[b35d3d1]295                    title = item.title.lstrip().rstrip()
296                    if title == "":
297                        title = str(name)
298                else:
299                    title = name
[32c0841]300                if hasattr(parent, "panel_on_focus") and \
301                    not(parent.panel_on_focus is None):
[b35d3d1]302                    existing_panel  = parent.panel_on_focus
303                    panel_name = existing_panel.window_caption
304                    data_name = new_plot.name
305                    if enable_add_data(existing_panel, new_plot):
306                        if open_dialog_append_data(panel_name, data_name):
307                            #add this plot the an existing panel
308                            new_plot.group_id = existing_panel.group_id
[ef16f59]309                # plot data
[32c0841]310                wx.PostEvent(parent, NewPlotEvent(plot=new_plot,
311                                                  title=str(title)))
[b63dc6e]312                if ext in SVS_FILE_EXT:
[9b18735]313                    # set state and plot computation if exists
[32c0841]314                    wx.PostEvent(parent, InvStateUpdateEvent())
315                    wx.PostEvent(parent, FitStateUpdateEvent())
[b35d3d1]316            except:
[32c0841]317                raise
Note: See TracBrowser for help on using the repository browser.