source: sasview/guiframe/data_loader.py @ e5c102c

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 e5c102c was d792e813, checked in by Gervaise Alina <gervyh@…>, 14 years ago

disable append data1d into theory panel

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