source: sasview/guiframe/data_loader.py @ b63dc6e

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

minor fixes of state

  • Property mode set to 100644
File size: 11.3 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
10from sans.perspectives.invariant import InvStateUpdateEvent
11from perspectives.fitting import FitStateUpdateEvent
12
13from sans.guicomm.events import NewPlotEvent, StatusEvent
14SVS_FILE_EXT = ['.svs','.inv','.prv','.fitv']
15
16def enable_add_data(existing_panel, new_plot):
17    """
18    Enable append data on a plot panel
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
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
36
37def parse_name(name, expression):
38    """
39    remove "_" in front of a name
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   
49def choose_data_file(parent, location=None):
50    """
51    """
52    path = None
53    if location == None:
54        location = os.getcwd()
55   
56    l = Loader()
57    cards = l.get_wildcards()
58    wlist = '|'.join(cards)
59   
60    dlg = wx.FileDialog(parent, "Choose a file", location, "", wlist, wx.OPEN)
61    if dlg.ShowModal() == wx.ID_OK:
62        path = dlg.GetPath()
63        mypath = os.path.basename(path)
64    dlg.Destroy()
65   
66    return path
67
68def open_dialog_append_data(panel_name, data_name):
69    """
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   
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
84   
85
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
133
134def load_error(error=None):
135    """
136    Pop up an error message.
137   
138    :param error: details error message to be displayed
139    """
140    message = "The data file you selected could not be loaded.\n"
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
149def on_load_error(parent):
150    """
151    """
152    wx.PostEvent(parent, StatusEvent(status="Load cancel..", info="warning",
153                                                type="stop"))
154   
155def plot_data(parent, path, format=None):
156    """
157    Use the DataLoader loader to created data to plot.
158   
159    :param path: the path of the data to load
160    : param format: file format (as file extension)
161    """
162    from sans.guicomm.events import NewPlotEvent, StatusEvent
163    from DataLoader.loader import  Loader
164   
165    # Instantiate a loader
166    L = Loader()
167   
168    # Load data
169    try:
170        output = L.load(path, format)
171    except:
172        load_error(sys.exc_value)
173        return
174    basename  = os.path.basename(path)
175    # Notify user if the loader completed the load but no data came out
176    if output == None:
177        if  not basename.endswith('.svs'):
178            load_error("The data file appears to be empty.")
179        return
180 
181    root, extension = os.path.splitext(basename)
182    ext =  extension.lower()
183    filename = os.path.basename(path)
184    if not  output.__class__.__name__ == "list":
185        ## Creating a Data2D with output
186        if hasattr(output,'data'):
187            msg = "Loading 2D data: %s"%output.filename
188            wx.PostEvent(parent, StatusEvent(status=msg, info="info", type="stop"))
189            new_plot = Data2D(image=None, err_image=None)
190     
191        else:
192            msg = "Loading 1D data: %s"%output.filename
193            wx.PostEvent(parent, StatusEvent(status=msg, info="info", type="stop"))
194            new_plot = Data1D(x=[], y=[], dx=None, dy=None)
195           
196        new_plot.copy_from_datainfo(output) 
197        output.clone_without_data(clone=new_plot)     
198     
199        ## data 's name
200        if output.filename is None or output.filename == "":
201            output.filename = str(filename)
202        ## name of the data allow to differentiate data when plotted
203        name = parse_name(name=output.filename, expression="_")
204       
205        new_plot.name = name
206        ## allow to highlight data when plotted
207        new_plot.interactive = True
208        ## when 2 data have the same id override the 1 st plotted
209        new_plot.id = name
210        ##group_id specify on which panel to plot this data
211        new_plot.group_id = name
212        new_plot.is_data = True
213        ##post data to plot
214        title = output.filename
215        if hasattr(new_plot,"title"):
216            title = str(new_plot.title.lstrip().rstrip())
217            if title == "":
218                title = str(name)
219        else:
220            title = str(name)
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
225                if enable_add_data(existing_panel, new_plot):
226                    if open_dialog_append_data(panel_name, data_name):
227                        #add this plot the an existing panel
228                        new_plot.group_id = existing_panel.group_id
229        # plot data
230        wx.PostEvent(parent, NewPlotEvent(plot=new_plot, title=title))
231        if ext in SVS_FILE_EXT:
232            # set state and plot computation if exists
233            wx.PostEvent(parent,InvStateUpdateEvent())
234            wx.PostEvent(parent,FitStateUpdateEvent())
235    ## the output of the loader is a list , some xml files contain more than one data
236    else:
237        i=0
238        for item in output: 
239            try:
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)
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)   
265                item.clone_without_data(clone=new_plot)   
266                # find original data file name without timestemp
267                name = parse_name(name=str(item.run[0]), expression="_")
268                max_char = name.find("[")
269                if max_char < 0:
270                    max_char = len(name)
271                original_name =name[0:max_char]
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?                   
277                new_plot.name = name
278                new_plot.interactive = True
279                new_plot.group_id = original_name
280                new_plot.id = name
281                new_plot.is_data = True
282                title = item.filename
283               
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
298                # plot data
299                wx.PostEvent(parent, NewPlotEvent(plot=new_plot, title=str(title)))
300               
301                if ext in SVS_FILE_EXT:
302                    # set state and plot computation if exists
303                    wx.PostEvent(parent,InvStateUpdateEvent())
304                    wx.PostEvent(parent,FitStateUpdateEvent())
305            except:
306                raise
Note: See TracBrowser for help on using the repository browser.