source: sasview/sansview/perspectives/fitting/fitpanel.py @ 645f9b6

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

fixed minor bugs on set_state that did not totally update state information and not pass to state object.

  • Property mode set to 100644
File size: 17.9 KB
Line 
1
2import numpy
3import string 
4import wx
5import wx.aui
6
7import basepage
8
9_BOX_WIDTH = 80
10
11
12class StateIterator(object):
13    """
14    Contains all saved state of a given page.
15    Provide position of the current state of a page, the first save state
16    and the last state for a given page.
17    Allow easy undo or redo for a given page 
18    """
19    def __init__(self):
20        """
21        """
22        self._current=0
23       
24    def __iter__(self):
25        """
26        """
27        return self
28   
29    def first(self):
30        """
31        """
32        self._current =0
33        return self._current
34   
35    def next(self, max ):
36        """
37        """
38        if self._current < max:
39            self._current += 1
40        return self._current
41   
42    def previous(self):
43        """
44        """
45        if self._current > 0:
46            self._current = self._current -1
47        return self._current
48   
49    def currentPosition(self):
50        """
51        """
52        return self._current
53   
54    def setPosition(self, value):
55        """
56        """
57        if value >=0:
58            self._current = int(value)
59       
60   
61class ListOfState(list):   
62    """
63    """ 
64    def __init__(self, *args, **kw):
65        list.__init__(self, *args, **kw)
66        self.iterator = StateIterator()
67       
68    def appendItem(self, x):
69        """
70        """
71        self.append(x)
72        self.iterator.setPosition(value= len(self)-1)
73       
74    def removeItem(self, x):
75        """
76        """
77        self.iterator.previous()
78        self.remove(x)
79       
80    def getPreviousItem(self):
81        """
82        """
83        position = self.iterator.previous()
84       
85        if position < 0:
86            return None
87        else:
88            return self[position]
89       
90    def getNextItem(self):
91        """
92        """
93        position = self.iterator.next(max= len(self)-1)
94        if position >= len(self):
95            return None
96        else:
97            return self[position]
98       
99    def getCurrentItem(self):
100        """
101        """
102        postion = self.iterator.currentPosition()
103        if postion >= 0 and position < len(self):
104            return self[postion]
105        else:
106            return None
107       
108    def getCurrentPosition(self):
109        """
110        """
111        return self.iterator.currentPosition()
112         
113
114class PageInfo(object):
115    """
116    this class contains the minimum numbers of data members
117    a fitpage or model page need to be initialized.
118    """
119    data = None
120    model =  None
121    manager = None
122    event_owner= None
123    model_list_box = None
124    name = None
125    ## Internal name for the AUI manager
126    window_name = "Page"
127    ## Title to appear on top of the window
128    window_caption = "Page"
129    #type of page can be real data , theory 1D or therory2D
130    type = "Data"
131    def __init__(self, model=None, data=None, manager=None,
132                  event_owner=None, model_list_box=None, name=None):
133        """
134        Initialize data members
135        """
136        self.data = data
137        self.model= model
138        self.manager= manager
139        self.event_owner= event_owner
140        self.model_list_box = model_list_box
141        self.name=None
142        self.window_name = "Page"
143        self.window_caption = "Page"
144        self.type = "Data"
145       
146class FitPanel(wx.aui.AuiNotebook):   
147
148    """
149    FitPanel class contains fields allowing to fit  models and  data
150   
151    :note: For Fit to be performed the user should check at least one parameter
152        on fit Panel window.
153       
154    """
155    ## Internal name for the AUI manager
156    window_name = "Fit panel"
157    ## Title to appear on top of the window
158    window_caption = "Fit Panel "
159    CENTER_PANE = True
160   
161    def __init__(self, parent, *args, **kwargs):
162        """
163        """
164        wx.aui.AuiNotebook.__init__(self, parent, -1,
165                    style= wx.aui.AUI_NB_WINDOWLIST_BUTTON|
166                    wx.aui.AUI_NB_DEFAULT_STYLE|
167                    wx.CLIP_CHILDREN)
168   
169        self.manager=None
170        self.parent=parent
171        self.event_owner=None
172       
173        pageClosedEvent = wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE
174        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_close_page)
175       
176        #dictionary of miodel {model class name, model class}
177        self.model_list_box = {}
178        ## save the title of the last page tab added
179        self.fit_page_name = {}
180        ## list of existing fit page
181        self.opened_pages = {}
182        #page of simultaneous fit
183        self.sim_page = None
184        ## get the state of a page
185        self.Bind(basepage.EVT_PAGE_INFO, self._onGetstate)
186        self.Bind(basepage.EVT_PREVIOUS_STATE, self._onUndo)
187        self.Bind(basepage.EVT_NEXT_STATE, self._onRedo)
188       
189        #add default pages
190        self.add_default_pages()
191       
192        # increment number for model name
193        self.count=0
194        #updating the panel
195        self.Update()
196        self.Center()
197       
198    def add_default_pages(self):
199        """
200        Add default pages such as a hint page and an empty fit page
201        """
202        #add default page
203        from hint_fitpage import HintFitPage
204        self.hint_page = HintFitPage(self) 
205        self.AddPage(page=self.hint_page, caption="Hint")
206         
207        #Add the first fit page
208        self.add_empty_page()
209
210   
211    def close_all(self):
212        """
213        remove all pages, used when a svs file is opened
214        """
215        #get number of pages
216        nop = self.GetPageCount()
217        #use while-loop, for-loop will not do the job well.
218        while (nop>0):
219            #delete the first page until no page exists
220            page = self.GetPage(0)
221            self._close_helper(selected_page=page)
222            self.DeletePage(0)
223            nop = nop - 1
224        ## save the title of the last page tab added
225        self.fit_page_name = {}
226        ## list of existing fit page
227        self.opened_pages = {} 
228         
229    def set_state(self, state):
230        """
231        Restore state of the panel
232        """
233        page_is_opened = False
234        if state is not None:
235            page_info = self.get_page_info(data=state.data)
236            for name, panel in self.opened_pages.values():
237                #Don't return any panel is the exact same page is created
238                if name == page_info.window_name:
239                    # the page is still opened
240                    panel.reset_page(state=state)
241                    panel.save_current_state() 
242                    page_is_opened = True
243            if not page_is_opened:
244                panel = self.add_fit_page(data=state.data)
245                # add data associated to the page created
246                if panel is not None: 
247                    self.manager.store_page(page=panel, data=state.data)
248                    panel.reset_page(state=state)
249                    panel.save_current_state()
250                   
251    def clear_panel(self, format='.svs'):
252        """
253        Clear and close all panels, used by guimanager
254        """
255        if format == '.svs':
256            #close all panels only when svs file opened
257            self.close_all()
258            self.manager.mypanels = []
259                       
260    def on_close_page(self, event=None):
261        """
262        close page and remove all references to the closed page
263        """
264        nbr_page = self.GetPageCount()
265        if nbr_page == 1:
266           
267            event.Veto()
268            return 
269        selected_page = self.GetPage(self.GetSelection())
270        self._close_helper(selected_page=selected_page)
271       
272    def close_page_with_data(self, deleted_data):
273        """
274        close a fit page when its data is completely remove from the graph
275        """
276        if deleted_data is None:
277            return
278        for index in range(self.GetPageCount()):
279            selected_page = self.GetPage(index) 
280            if hasattr(selected_page,"get_data"):
281                data = selected_page.get_data()
282               
283                if data is None:
284                    #the fitpanel exists and only the initial fit page is open
285                    #with no selected data
286                    return
287                if data.name == deleted_data.name:
288                    self._close_helper(selected_page)
289                    self.DeletePage(index)
290                    break
291       
292    def set_manager(self, manager):
293        """
294        set panel manager
295       
296        :param manager: instance of plugin fitting
297       
298        """
299        self.manager = manager
300
301       
302    def set_owner(self,owner):
303        """
304        set and owner for fitpanel
305       
306        :param owner: the class responsible of plotting
307       
308        """
309        self.event_owner = owner
310   
311    def set_model_list(self, dict):
312         """
313         copy a dictionary of model into its own dictionary
314         
315         :param dict: dictionnary made of model name as key and model class
316             as value
317         """
318         self.model_list_box = dict
319       
320    def get_current_page(self):
321        """
322        :return: the current page selected
323       
324        """
325        return self.GetPage(self.GetSelection() )
326   
327    def add_sim_page(self):
328        """
329        Add the simultaneous fit page
330        """
331        from simfitpage import SimultaneousFitPage
332        page_finder= self.manager.get_page_finder()
333        self.sim_page = SimultaneousFitPage(self,page_finder=page_finder, id=-1)
334       
335        self.AddPage(self.sim_page,caption="Simultaneous Fit",select=True)
336        self.sim_page.set_manager(self.manager)
337        return self.sim_page
338       
339    def get_page_info(self, data=None):
340        """
341        fill information required to add a page in the fit panel
342        """
343        name = "Fit Page"
344        type = 'empty'
345        if data is not None:
346            if data.is_data:
347                name = data.name
348                type = 'Data'
349            else:
350                if data.__class__.__name__ == "Data2D":
351                    name = 'Model 2D Fit'
352                    type = 'Theory2D'
353                else:
354                    name = 'Model 1D Fit'
355                    type = 'Theory1D'
356        page_info = PageInfo(data=data, name=name)
357        page_info.event_owner = self.event_owner
358        page_info.manager = self.manager
359        page_info.window_name = name
360        page_info.window_caption = name
361        page_info.type = type
362        return page_info
363   
364    def add_empty_page(self):
365        """
366        add an empty page
367        """
368        page_info = self.get_page_info()
369        from fitpage import FitPage
370        panel = FitPage(parent=self, page_info=page_info)
371        self.AddPage(page=panel, caption=page_info.window_name, select=True)
372        self.opened_pages[page_info.type] = [page_info.window_name, panel]
373        return panel
374   
375    def add_page(self, page_info):
376        """
377        add a new page
378        """
379        from fitpage import FitPage
380        panel = FitPage(parent=self, page_info=page_info)
381        self.AddPage(page=panel, caption=page_info.window_name, select=True)
382        index = self.GetPageIndex(panel)
383        self.change_page_content(data=page_info.data, index=index)
384        return panel
385   
386    def change_page_content(self, data, index):
387        """
388        replace the contains of an existing page
389        """
390        page_info = self.get_page_info(data=data)
391        self.SetPageText(index, page_info.window_name)
392        panel = self.GetPage(index)
393        panel.set_data(data)
394        if panel.model_list_box is None or len(panel.model_list_box) == 0: 
395            page_info.model_list_box = self.model_list_box.get_list()
396            panel.populate_box(dict=page_info.model_list_box)
397            panel.initialize_combox()
398        panel.set_page_info(page_info=page_info)
399        self.opened_pages[page_info.type] = [page_info.window_name, panel]
400        return panel
401   
402    def replace_page(self, index, page_info, type):
403        """
404        replace an existing page
405        """
406        self.DeletePage(index)
407        del self.opened_pages[type]
408        return self.add_page(page_info=page_info)
409       
410    def add_fit_page(self, data, reset=False):
411        """
412        Add a fitting page on the notebook contained by fitpanel
413       
414        :param data: data to fit
415       
416        :return panel : page just added for further used. is used by fitting module
417       
418        """
419        if data is None:
420            return None
421        page_info = self.get_page_info(data=data)
422        type = page_info.type
423        npages = len(self.opened_pages.keys())
424        #check if only and empty page is opened
425        if len(self.opened_pages.keys()) > 0:
426            first_page_type = self.opened_pages.keys()[0]
427            if npages == 1 and first_page_type in ['empty']:
428                #replace the first empty page
429                name, panel = self.opened_pages[first_page_type]
430                index = self.GetPageIndex(panel)
431                panel = self.change_page_content(data=data, index=index)
432                del self.opened_pages[first_page_type]
433                return panel
434        if type in self.opened_pages.keys():
435            #this type of page is already created but it is a theory
436            # meaning the same page is just to fit different data
437            if not type.lower() in ['data']:
438                #delete the previous theory page and add a new one
439                name, panel = self.opened_pages[type]
440                #self.manager.reset_plot_panel(panel.get_data())
441                #delete the existing page and replace it
442                index = self.GetPageIndex(panel)
443                panel = self.replace_page(index=index, page_info=page_info, type=type)
444                return panel
445            else:
446                for name, panel in self.opened_pages.values():
447                    #Don't return any panel is the exact same page is created
448                    if name == page_info.window_name:
449                        return None
450                    else:
451                        panel = self.add_page(page_info=page_info)
452                        return panel       
453        else:
454            #a new type of page is created
455            panel = self.add_page(page_info=page_info)
456            return panel
457       
458    def  _onGetstate(self, event):
459        """
460        copy the state of a page
461        """
462        page= event.page
463        if page.window_name in self.fit_page_name:
464            self.fit_page_name[page.window_name].appendItem(page.createMemento()) 
465           
466    def _onUndo(self, event ):
467        """
468        return the previous state of a given page is available
469        """
470        page = event.page
471        if page.window_name in self.fit_page_name:
472            if self.fit_page_name[page.window_name].getCurrentPosition()==0:
473                state = None
474            else:
475                state = self.fit_page_name[page.window_name].getPreviousItem()
476                page._redo.Enable(True)
477            page.reset_page(state)
478       
479    def _onRedo(self, event): 
480        """
481        return the next state available
482        """       
483        page = event.page
484        if page.window_name in self.fit_page_name:
485            length= len(self.fit_page_name[page.window_name])
486            if self.fit_page_name[page.window_name].getCurrentPosition()== length -1:
487                state = None
488                page._redo.Enable(False)
489                page._redo.Enable(True)
490            else:
491                state = self.fit_page_name[page.window_name].getNextItem()
492            page.reset_page(state) 
493                 
494    def _close_helper(self, selected_page):
495        """
496        Delete the given page from the notebook
497        """
498        #remove hint page
499        if selected_page == self.hint_page:
500            return
501        ## removing sim_page
502        if selected_page == self.sim_page :
503            self.manager.sim_page=None 
504            return
505       
506        ## closing other pages
507        state = selected_page.createMemento()
508        page_name = selected_page.window_name
509        page_finder = self.manager.get_page_finder() 
510        fitproblem = None
511        ## removing fit page
512        data = selected_page.get_data()
513        #Don' t remove plot for 2D
514        flag = True
515        if data.__class__.__name__ == 'Data2D':
516            flag = False
517        if selected_page in page_finder:
518            #Delete the name of the page into the list of open page
519            for type, list in self.opened_pages.iteritems():
520                #Don't return any panel is the exact same page is created
521                name = str(list[0])
522                if flag and selected_page.window_name == name:
523                    if type.lower() in ['theory1d', 'theory2d']:
524                        self.manager.remove_plot(selected_page, theory=True)
525                    else:
526                        self.manager.remove_plot(selected_page, theory=False)
527                    break 
528            del page_finder[selected_page]
529        ##remove the check box link to the model name of this page (selected_page)
530        try:
531            self.sim_page.draw_page()
532        except:
533            ## that page is already deleted no need to remove check box on
534            ##non existing page
535            pass
536               
537        #Delete the name of the page into the list of open page
538        for type, list in self.opened_pages.iteritems():
539            #Don't return any panel is the exact same page is created
540            name = str(list[0])
541            if selected_page.window_name == name:
542                del self.opened_pages[type]
543                break 
544     
545 
Note: See TracBrowser for help on using the repository browser.