source: sasview/guiframe/data_loader.py @ 028a0e8

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

fixed minor bug on saving

  • Property mode set to 100644
File size: 10.5 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    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
33
34def parse_name(name, expression):
35    """
36    remove "_" in front of a name
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   
46def choose_data_file(parent, location=None):
47    """
48    """
49    path = None
50    if location == None:
51        location = os.getcwd()
52   
53    l = Loader()
54    cards = l.get_wildcards()
55    wlist = '|'.join(cards)
56   
57    dlg = wx.FileDialog(parent, "Choose a file", location, "", wlist, wx.OPEN)
58    if dlg.ShowModal() == wx.ID_OK:
59        path = dlg.GetPath()
60        mypath = os.path.basename(path)
61    dlg.Destroy()
62   
63    return path
64
65def open_dialog_append_data(panel_name, data_name):
66    """
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   
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
81   
82
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
130
131def load_error(error=None):
132    """
133    Pop up an error message.
134   
135    :param error: details error message to be displayed
136    """
137    message = "The data file you selected could not be loaded.\n"
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
146def on_load_error(parent):
147    """
148    """
149    wx.PostEvent(parent, StatusEvent(status="Load cancel..", info="warning",
150                                                type="stop"))
151   
152def plot_data(parent, path, format=None):
153    """
154    Use the DataLoader loader to created data to plot.
155   
156    :param path: the path of the data to load
157    : param format: file format (as file extension)
158    """
159    from sans.guicomm.events import NewPlotEvent, StatusEvent
160    from DataLoader.loader import  Loader
161   
162    # Instantiate a loader
163    L = Loader()
164   
165    # Load data
166    try:
167        output = L.load(path, format)
168    except:
169        load_error(sys.exc_value)
170        return
171   
172    # Notify user if the loader completed the load but no data came out
173    if output == None:
174        basename  = os.path.basename(path)
175        if  not basename.endswith('.svs'):
176            load_error("The data file appears to be empty.")
177        return
178 
179     
180    filename = os.path.basename(path)
181   
182    if not  output.__class__.__name__ == "list":
183        ## Creating a Data2D with output
184        if hasattr(output,'data'):
185            msg = "Loading 2D data: %s"%output.filename
186            wx.PostEvent(parent, StatusEvent(status=msg, info="info", type="stop"))
187            new_plot = Data2D(image=None, err_image=None)
188     
189        else:
190            msg = "Loading 1D data: %s"%output.filename
191            wx.PostEvent(parent, StatusEvent(status=msg, info="info", type="stop"))
192            new_plot = Data1D(x=[], y=[], dx=None, dy=None)
193           
194        new_plot.copy_from_datainfo(output) 
195        output.clone_without_data(clone=new_plot)     
196     
197        ## data 's name
198        if output.filename is None or output.filename == "":
199            output.filename = str(filename)
200        ## name of the data allow to differentiate data when plotted
201        name = parse_name(name=output.filename, expression="_")
202        #if not name in parent.indice_load_data.keys():
203        #    parent.indice_load_data[name] = 0
204        #else:
205            ## create a copy of the loaded data
206        #    parent.indice_load_data[name] += 1
207        #    name = name +"[%i]"%parent.indice_load_data[name]
208       
209        new_plot.name = name
210        ## allow to highlight data when plotted
211        new_plot.interactive = True
212        ## when 2 data have the same id override the 1 st plotted
213        new_plot.id = name
214        ##group_id specify on which panel to plot this data
215        new_plot.group_id = name
216        new_plot.is_data = True
217        ##post data to plot
218        title = output.filename
219        if hasattr(new_plot,"title"):
220            title = str(new_plot.title.lstrip().rstrip())
221            if title == "":
222                title = str(name)
223        else:
224            title = str(name)
225        if hasattr(parent, "panel_on_focus") and not(parent.panel_on_focus is None):
226                existing_panel  = parent.panel_on_focus
227                panel_name = existing_panel.window_caption
228                data_name = new_plot.name
229                if enable_add_data(existing_panel, new_plot):
230                    if open_dialog_append_data(panel_name, data_name):
231                        #add this plot the an existing panel
232                        new_plot.group_id = existing_panel.group_id
233        wx.PostEvent(parent, NewPlotEvent(plot=new_plot, title=title))
234       
235    ## the output of the loader is a list , some xml files contain more than one data
236    else:
237        i=1
238        for item in output:
239            try:
240                msg = "Loading 1D data: %s"%str(item.run[0])
241                wx.PostEvent(parent, StatusEvent(status=msg, info="info", type="stop"))
242                try:
243                    dx = item.dx
244                    dxl = item.dxl
245                    dxw = item.dxw
246                except:
247                    dx = None
248                    dxl = None
249                    dxw = None
250   
251                new_plot = Data1D(x=item.x,y=item.y,dx=dx,dy=item.dy)
252                new_plot.copy_from_datainfo(item)
253                item.clone_without_data(clone=new_plot)
254                new_plot.dxl = dxl
255                new_plot.dxw = dxw
256               
257                name = parse_name(name=str(item.run[0]), expression="_")
258                #if not name in parent.indice_load_data.keys():
259                #    parent.indice_load_data[name] = 0
260                #else:
261                    ## create a copy of the loaded data
262                   
263                    #TODO: this is a very annoying feature. We should make this
264                    # an option. Excel doesn't do this. Why should we?
265                    # What is the requirement for this feature, and are the
266                    # counter arguments stronger? Is this feature developed
267                    # to please at least 80% of the users or a special few?
268                    #parent.indice_load_data[name] += 1
269                    #name = name + "(copy %i)"%parent.indice_load_data[name]
270                   
271                new_plot.name = name
272                new_plot.interactive = True
273                new_plot.group_id = name
274                new_plot.id = name
275                new_plot.is_data = True
276           
277                if hasattr(item,"title"):
278                    title = item.title.lstrip().rstrip()
279                    if title == "":
280                        title = str(name)
281                else:
282                    title = name
283                if hasattr(parent, "panel_on_focus") and not(parent.panel_on_focus is None):
284                    existing_panel  = parent.panel_on_focus
285                    panel_name = existing_panel.window_caption
286                    data_name = new_plot.name
287                    if enable_add_data(existing_panel, new_plot):
288                        if open_dialog_append_data(panel_name, data_name):
289                            #add this plot the an existing panel
290                            new_plot.group_id = existing_panel.group_id
291                wx.PostEvent(parent, NewPlotEvent(plot=new_plot, title=str(title)))
292                i+=1
293            except:
294                raise
Note: See TracBrowser for help on using the repository browser.