source: sasview/guiframe/data_loader.py @ b35d3d1

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

save state file: working, but more work to do

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