source: sasview/guiframe/data_loader.py @ a7a5886

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 a7a5886 was 7a07864, checked in by Jae Cho <jhjcho@…>, 14 years ago

a bit generalized the plotdata

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