source: sasview/sansguiframe/src/sans/guiframe/data_processor.py @ ed2d86e

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

fixed putting new # of rows

  • Property mode set to 100644
File size: 53.5 KB
Line 
1"""
2Implement grid used to store data
3"""
4import wx
5import numpy
6import math
7import time
8import re
9import os
10import sys
11import copy
12from wx.lib.scrolledpanel import ScrolledPanel
13import  wx.grid as  Grid
14import wx.aui
15from wx.aui import AuiNotebook as nb
16import wx.lib.sheet as sheet
17from sans.guiframe.panel_base import PanelBase
18from sans.guiframe.utils import format_number
19from sans.guiframe.events import NewPlotEvent
20from sans.guiframe.events import StatusEvent 
21from danse.common.plottools import plottables
22from sans.guiframe.dataFitting import Data1D
23
24FUNC_DICT = {"sqrt": "math.sqrt",
25             "pow": "math.sqrt"}
26
27class BatchCell:
28    """
29    Object describing a cell in  the grid.
30   
31    """
32    def __init__(self):
33        self.label = ""
34        self.value = None
35        self.col = -1
36        self.row = -1
37        self.object = []
38       
39
40def parse_string(sentence, list):
41    """
42    Return a dictionary of column label and index or row selected
43    :param sentence: String to parse
44    :param list: list of columns label
45    """
46    toks = []
47    p2 = re.compile(r'\d+')
48    p = re.compile(r'[\+\-\*\%\/]')
49    labels = p.split(sentence)
50    col_dict = {}
51    for elt in labels:
52        rang = None
53        temp_arr = []
54        for label in  list:
55            label_pos =  elt.find(label)
56            separator_pos  = label_pos + len(label)
57            if label_pos != -1 and len(elt) >= separator_pos  and\
58                elt[separator_pos]== "[":
59                # the label contain , meaning the range selected is not
60                # continuous
61                if elt.count(',') > 0:
62                    new_temp = []
63                    temp = elt.split(label)
64                    for item in temp:
65                        range_pos = item.find(":")
66                        if range_pos != -1:
67                            rang = p2.findall(item)
68                            for i in xrange(int(rang[0]), int(rang[1])+1 ):
69                                new_temp.append(i)
70                    temp_arr += new_temp
71                else:
72                    # continuous range
73                    temp = elt.split(label)
74                    for item in temp:
75                        if item.strip() != "":
76                            range_pos = item.find(":")
77                            if range_pos != -1:
78                                rang = p2.findall(item)
79                                for i in xrange(int(rang[0]), int(rang[1])+1 ):
80                                    temp_arr.append(i)
81                col_dict[elt] = (label, temp_arr)
82    return col_dict
83
84         
85         
86class SPanel(ScrolledPanel):
87    def __init__(self, parent, *args, **kwds):
88        ScrolledPanel.__init__(self, parent , *args, **kwds)
89        self.SetupScrolling() 
90       
91class GridPage(sheet.CSheet):
92    """
93    """
94    def __init__(self, parent, panel=None):
95        """
96        """
97        sheet.CSheet.__init__(self, parent)
98       
99        self.AdjustScrollbars()
100        #self.SetLabelBackgroundColour('#DBD4D4')
101        self.uid = wx.NewId()
102        self.parent = parent
103        self.panel = panel
104        self.col_names = []
105        self.data_inputs = {}
106        self.data_outputs = {}
107        self.data = None
108        self.details = ""
109        self.file_name = None
110        self._cols = 50
111        self._rows = 501
112        self.last_selected_row = -1
113        self.last_selected_col = -1
114        self.col_width = 30
115        self.row_height = 20
116        self.max_row_touse = 0
117        self.axis_value = []
118        self.axis_label = ""
119        self.selected_cells = []
120        self.selected_cols = []
121        self.selected_rows = []
122        self.plottable_cells = []
123        self.plottable_flag = False
124        self.SetColMinimalAcceptableWidth(self.col_width)
125        self.SetRowMinimalAcceptableHeight(self.row_height)
126        self.SetNumberRows(self._rows)
127        self.SetNumberCols(self._cols)
128        self.AutoSize()
129        self.list_plot_panels = {}
130        self.default_col_width = 75
131        self.EnableEditing(False)
132        if self.GetNumberCols() > 0:
133            self.default_col_width =  self.GetColSize(0)
134        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.on_left_click)
135        self.Bind(wx.grid.EVT_GRID_LABEL_RIGHT_CLICK, self.on_right_click)
136        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_selected_cell)
137        self.Bind(wx.grid.EVT_GRID_CMD_CELL_CHANGE, self.on_edit_cell)
138       
139       
140    def on_edit_cell(self, event):
141        """
142        """
143        row, col = event.GetRow(), event.GetCol()
144        if row > self.max_row_touse:
145            self.max_row_touse = row
146        event.Skip()
147       
148    def on_selected_cell(self, event):
149        """
150        Handler catching cell selection
151        """
152        flag = event.CmdDown() or event.ControlDown()
153        row, col = event.GetRow(), event.GetCol()
154        cell = (row, col)
155        event.Skip()
156        if not flag:
157            self.selected_cols = []
158            self.selected_rows = []
159            self.selected_cells = []
160            self.axis_label = ""
161            self.axis_value = []
162            self.plottable_list = []
163            self.plottable_cells = []
164            self.plottable_flag = False
165        self.last_selected_col = col
166        self.last_selected_row = row
167        if col >= 0:
168            label_row = 0
169            self.axis_label = self.GetCellValue(label_row, col)
170            self.selected_cols.append(col)
171        if cell not in self.selected_cells:
172            if row > 0:
173                self.selected_cells.append(cell)
174                self.selected_rows.append(row)
175        else:
176            if flag:
177                self.selected_cells.remove(cell)
178        self.axis_value = []
179        for cell_row, cell_col in self.selected_cells:
180            if cell_row > 0 and cell_row < self.max_row_touse:
181                self.axis_value.append(self.GetCellValue(cell_row, cell_col))
182
183               
184    def on_left_click(self, event):
185        """
186        Catch the left click on label mouse event
187        """
188        event.Skip()
189        flag = event.CmdDown() or event.ControlDown()
190        col = event.GetCol()
191        row = event.GetRow()
192        if not flag:
193            self.selected_cols = []
194            self.selected_rows = []
195            self.selected_cells = []
196            self.axis_label = ""
197            self.axis_value = []
198            self.plottable_list = []
199            self.plottable_cells = []
200            self.plottable_flag = False
201       
202        self.last_selected_col = col
203        self.last_selected_row = row
204        if row != -1 and row not in self.selected_rows:
205             self.selected_rows.append(row)
206             
207        if col != -1:
208            for row in range(1, self.GetNumberRows()+ 1):
209                cell = (row, col)
210                if row > 0 and row < self.max_row_touse:
211                    if cell not in self.selected_cells:
212                        self.selected_cells.append(cell)
213                    else:
214                        if flag:
215                             self.selected_cells.remove(cell)
216            self.selected_cols.append(col)
217            self.axis_value = []
218            for cell_row, cell_col in self.selected_cells:
219                self.axis_value.append(self.GetCellValue(cell_row, cell_col))
220            self.axis_label = self.GetCellValue(0, col)
221       
222    def on_right_click(self, event):
223        """
224        Catch the right click mouse
225        """
226       
227        col = event.GetCol()
228        self.selected_cols = []
229        self.selected_cols.append(col)
230        # Slicer plot popup menu
231        slicerpop = wx.Menu()
232        col_label_menu  = wx.Menu()
233        c_name = self.GetCellValue(0, col) 
234        label = "Insert column before %s " % str(c_name)
235        slicerpop.AppendSubMenu(col_label_menu , 
236                                 '&%s' % str(label), str(label))
237        col_name = [self.GetCellValue(0, c) 
238                        for c in range(self.GetNumberCols())]
239        row = 0
240        label = self.GetCellValue(row, col)
241        self.insert_col_menu(col_label_menu, label, self)
242       
243       
244        col_after_menu  = wx.Menu()
245        label = "Insert column after %s " % str(c_name)
246        slicerpop.AppendSubMenu(col_after_menu , 
247                                 '&%s' % str(label), str(label))
248        col_name = [self.GetCellValue(0, c) 
249                        for c in range(self.GetNumberCols())]
250        self.insert_after_col_menu(col_after_menu, label, self)
251       
252       
253        id = wx.NewId()   
254        hint = 'Remove selected column %s'
255        slicerpop.Append(id, '&Remove Column', hint)
256        wx.EVT_MENU(self, id, self.on_remove_column)
257       
258        pos = wx.GetMousePosition()
259        pos = self.ScreenToClient(pos)
260        self.PopupMenu(slicerpop, pos)
261        event.Skip()
262       
263    def insert_col_menu(self, menu, label, window):
264        """
265        """
266        if self.data is None:
267            return
268        id = wx.NewId()
269        title = "Empty"
270        hint = 'Insert empty column before %s' % str(label)
271        menu.Append(id, title, hint)
272        wx.EVT_MENU(window, id, self.on_insert_column)
273        row = 0
274        col_name = [self.GetCellValue(row, col) 
275                        for col in range(self.GetNumberCols())]
276        for c_name in self.data.keys():
277            if c_name not in col_name:
278                id = wx.NewId()
279                hint = "Insert %s column before the " % str(c_name)
280                hint += " %s column" % str(label)
281                menu.Append(id, '&%s' % str(c_name), hint)
282                wx.EVT_MENU(window, id, self.on_insert_column)
283           
284    def insert_after_col_menu(self, menu, label, window):
285        """
286        """
287        if self.data is None:
288            return
289        id = wx.NewId()
290        title = "Empty"
291        hint = 'Insert empty column after %s' % str(label)
292        menu.Append(id, title, hint)
293        wx.EVT_MENU(window, id, self.on_insert_after_column)
294        row = 0
295        col_name = [self.GetCellValue(row, col) 
296                        for col in range(self.GetNumberCols())]
297        for c_name in self.data.keys():
298            if c_name not in col_name:
299                id = wx.NewId()
300                hint = "Insert %s column after the " % str(c_name)
301                hint += " %s column" % str(label)
302                menu.Append(id, '&%s' % str(c_name), hint)
303                wx.EVT_MENU(window, id, self.on_insert_after_column)
304                               
305    def on_remove_column(self, event=None):
306        """
307        """
308        if self.selected_cols is not None or len(self.selected_cols) > 0:
309            col = self.selected_cols[0]
310            self.remove_column(col=col, numCols=1)
311           
312    def remove_column(self, col, numCols=1):
313        """
314        Remove column to the current grid
315        """
316        # add data to the grid   
317        row = 0
318        col_name = self.GetCellValue(row, col)
319        self.data[col_name] = []
320        for row in range(1, self.GetNumberRows() + 1):
321            if row < self.max_row_touse:
322                value = self.GetCellValue(row, col)
323                self.data[col_name].append(value)
324                for k , value_list in self.data.iteritems():
325                    if k != col_name:
326                        length = len(value_list)
327                        if length < self.max_row_touse:
328                            diff = self.max_row_touse - length
329                            for i in range(diff):
330                                self.data[k].append("")
331        self.DeleteCols(pos=col, numCols=numCols, updateLabels=True)
332           
333    def on_insert_column(self, event):
334        """
335        """
336        if self.selected_cols is not None or len(self.selected_cols) > 0:
337            col = self.selected_cols[0]
338            # add data to the grid   
339            row = 0
340            id = event.GetId()
341            col_name = event.GetEventObject().GetLabelText(id)
342            self.insert_column(col=col, col_name=col_name)
343            if  not issubclass(event.GetEventObject().__class__ , wx.Menu):
344                col += 1
345                self.selected_cols[0] += 1
346               
347    def on_insert_after_column(self, event):
348        """
349        Insert the given column after the highlighted column
350        """
351        if self.selected_cols is not None or len(self.selected_cols) > 0:
352            col = self.selected_cols[0] + 1
353            # add data to the grid   
354            row = 0
355            id = event.GetId()
356            col_name = event.GetEventObject().GetLabelText(id)
357            self.insert_column(col=col, col_name=col_name)
358            if  not issubclass(event.GetEventObject().__class__ , wx.Menu):
359                self.selected_cols[0] += 1
360           
361    def insert_column(self, col, col_name):
362        """
363        """ 
364         
365        row = 0
366        self.InsertCols(pos=col, numCols=1, updateLabels=True)
367        if col_name.strip() != "Empty":
368            self.SetCellValue(row, col, str(col_name.strip()))
369        if col_name in self.data.keys():
370            value_list = self.data[col_name]
371            cell_row =  1
372            for value in value_list:
373                label = value#format_number(value, high=True)
374                self.SetCellValue(cell_row, col, str(label))
375                cell_row += 1
376        self.AutoSizeColumn(col, True)
377        width = self.GetColSize(col)
378        if width < self.default_col_width:
379           self.SetColSize(col, self.default_col_width)
380        self.ForceRefresh()
381       
382    def on_set_x_axis(self, event):
383        """
384        """
385        self.panel.set_xaxis(x=self.axis_value, label=self.axis_label)
386   
387    def on_set_y_axis(self, event):
388        """
389        """
390        self.panel.set_yaxis(y=self.axis_value, label=self.axis_label)     
391           
392    def set_data(self, data_inputs, data_outputs, details, file_name):
393        """
394        Add data to the grid
395        :param data_inputs: data to use from the context menu of the grid
396        :param data_ouputs: default columns deplayed
397        """
398        self.file_name = file_name
399        self.details = details
400       
401        if data_outputs is None:
402            data_outputs = {}
403        self.data_outputs = data_outputs
404        if data_inputs is None:
405            data_inputs = {}
406        self.data_inputs = data_inputs
407        self.data = {}
408        for item in (self.data_outputs, self.data_inputs):
409            self.data.update(item)
410           
411        if len(self.data) + len(self.data_inputs) +len(self.data_outputs) == 0:
412            self.EnableEditing(False)
413        else:
414            self.EnableEditing(True)
415        if  len(self.data_outputs) > 0:
416            self._cols = self.GetNumberCols()
417            self._rows = self.GetNumberRows()
418            self.col_names = self.data_outputs.keys()
419            self.col_names.sort() 
420            nbr_user_cols = len(self.col_names)
421            #Add more columns to the grid if necessary
422            if nbr_user_cols > self._cols:
423                new_col_nbr = nbr_user_cols -  self._cols + 1
424                self.AppendCols(new_col_nbr, True)
425            #Add more rows to the grid if necessary 
426            nbr_user_row = len(self.data_outputs.values()[0])
427            if nbr_user_row > self._rows + 1:
428                new_row_nbr =  nbr_user_row - self._rows + 1
429                self.AppendRows(new_row_nbr, True)
430            # add data to the grid   
431            wx.CallAfter(self.set_grid_values)
432        self.ForceRefresh()
433   
434    def set_grid_values(self):
435        """
436        Set the values in grids
437        """
438        # add data to the grid   
439        row = 0
440        col = 0
441        cell_col = 0
442        for col_name in  self.col_names:
443            # use the first row of the grid to add user defined labels
444            self.SetCellValue(row, col, str(col_name))
445            col += 1
446            cell_row =  1
447            value_list = self.data_outputs[col_name]
448           
449            for value in value_list:
450                label = value
451                if issubclass(value.__class__, BatchCell):
452                    label = value.label
453                try:
454                    float(label)
455                    label = str(label)#format_number(label, high=True)
456                except:
457                    label = str(label)
458                self.SetCellValue(cell_row, cell_col, label)
459                self.AutoSizeColumn(cell_col, True)
460                width = self.GetColSize(cell_col)
461                if width < self.default_col_width:
462                   self.SetColSize(cell_col, self.default_col_width)
463               
464                cell_row += 1
465            cell_col += 1
466            if cell_row > self.max_row_touse:
467                self.max_row_touse = cell_row
468                         
469    def get_grid_view(self):
470        """
471        Return value contained in the grid
472        """
473        grid_view = {}
474        for col in xrange(self.GetNumberCols()):
475            label = self.GetCellValue(row=0, col=col) 
476            label = label.strip()
477            if label != "":
478                grid_view[label] = []
479                for row in range(1, self.max_row_touse):
480                    value = self.GetCellValue(row=row, col=col)
481                    if value != "":
482                        grid_view[label].append(value) 
483                    else:
484                        grid_view[label].append(None) 
485        return grid_view
486   
487class Notebook(nb, PanelBase):
488    """
489    ## Internal name for the AUI manager
490    window_name = "Fit panel"
491    ## Title to appear on top of the window
492    """
493    window_caption = "Notebook "
494   
495    def __init__(self, parent, manager=None, data=None, *args, **kwargs):
496        """
497        """
498        nb.__init__(self, parent, -1,
499                    style=wx.aui.AUI_NB_WINDOWLIST_BUTTON| 
500                    wx.aui.AUI_BUTTON_DOWN|
501                    wx.aui.AUI_NB_DEFAULT_STYLE|
502                    wx.CLIP_CHILDREN)
503        PanelBase.__init__(self, parent)
504        self.enable_close_button()
505        self.parent = parent
506        self.manager = manager
507        self.data = data
508        #add empty page
509        self.add_empty_page()
510       
511        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_close_page)
512   
513    def add_empty_page(self):
514        """
515        """
516        grid = GridPage(self, panel=self.parent)
517        self.AddPage(grid, "", True)
518        pos = self.GetPageIndex(grid)
519        title = "Batch" + str(self.GetPageCount())
520        self.SetPageText(pos, title)
521        self.SetSelection(pos)
522        return grid , pos
523       
524    def enable_close_button(self):
525        """
526        display the close button on tab for more than 1 tabs else remove the
527        close button
528        """
529        if self.GetPageCount() <= 1:
530            style = self.GetWindowStyleFlag() 
531            flag = wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
532            if style & wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB == flag:
533                style = style & ~wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
534                self.SetWindowStyle(style)
535        else:
536            style = self.GetWindowStyleFlag()
537            flag = wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
538            if style & wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB != flag:
539                style |= wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
540                self.SetWindowStyle(style)
541             
542    def on_edit_axis(self):
543        """
544        Return the select cell of a given selected column. Check that all cells
545        are from the same column
546        """
547        pos = self.GetSelection()
548        grid = self.GetPage(pos)
549        if len(grid.selected_cols) >= 1:
550            col = grid.selected_cols[0]
551            for c in grid.selected_cols:
552                if c != col:
553                    msg = "Edit axis doesn't understand this selection.\n"
554                    msg += "Please select only one column"
555                    raise ValueError, msg
556            for (cell_row, cell_col) in grid.selected_cells:
557                if cell_col != col:
558                    msg = "Cannot use cells from different columns for "
559                    msg += "this operation.\n"
560                    msg += "Please select elements of the same col.\n"
561                    raise ValueError, msg
562        else:
563            msg = "No item selected.\n"
564            msg += "Please select only one column or one cell"
565            raise ValueError, msg
566       
567        return grid.selected_cells
568       
569   
570    def get_column_labels(self):
571        """
572        return dictionary of columns labels of the current page
573        """
574        pos = self.GetSelection()
575        grid = self.GetPage(pos)
576        labels = {}
577        row = 0
578        for col in range(grid.GetNumberCols()):
579            label = grid.GetCellValue(row, col)
580            if label.strip() != "" :
581                labels[label.strip()] = col
582        return labels
583       
584    def create_axis_label(self, cell_list):
585        """
586        Receive a list of cells and  create a string presenting the selected
587        cells.
588        :param cell_list: list of tuple
589       
590        """
591        pos = self.GetSelection()
592        grid = self.GetPage(pos)
593        label = ""
594        col_name = ""
595        def create_label(col_name,  row_min=None, row_max=None):
596            """
597            """
598            result = ""
599            if row_min is not  None or row_max is not None:
600                if row_min is None:
601                    result = str(row_max) + "]"
602                elif row_max is None:
603                     result = str(col_name) + "[" + str(row_min) + ":"
604                else:
605                    result = str(col_name) +  "[" + str(row_min) + ":"
606                    result += str(row_max) + "]"
607            return str(result)
608           
609        if len(cell_list) > 0:
610            if len(cell_list) == 1:
611                 row_min, col  = cell_list[0]   
612                 col_name = grid.GetCellValue(0, col)
613                 label = create_label(col_name, row_min+1 , row_min+1)
614                 return  label,  col_name
615            else:
616                temp_list = copy.deepcopy(cell_list)
617                temp_list.sort()
618                length = len(temp_list)
619                row_min, col  = temp_list[0]   
620                row_max, _  = temp_list[length-1]
621                col_name = grid.GetCellValue(0, col)
622                index = 0
623                for row in xrange(row_min, row_max +1):
624                    if index > 0 and index < len(temp_list):
625                        new_row, _ = temp_list[index]
626                        if row != new_row:
627                            temp_list.insert(index, (None, None))
628                            if index -1 >= 0:
629                                new_row, _ = temp_list[index-1]
630                                label += create_label(col_name, None, new_row +1)
631                                label += ","
632                            if index + 1 < len(temp_list):
633                                new_row, _ = temp_list[index + 1]
634                                label += create_label(col_name, new_row+1, None)
635                    if index == 0:
636                        label += create_label(col_name,  row_min+1, None)
637                    elif index == len(temp_list)-1:
638                        label += create_label(col_name, None, row_max+1)
639                    index += 1
640                return label, col_name
641   
642    def on_close_page(self, event):
643        """
644        close the page
645        """
646        if self.GetPageCount() == 1:
647            event.Veto()
648        self.enable_close_button()
649       
650    def set_data(self, data_inputs, data_outputs, details="", file_name=None):
651        if data_outputs is None or data_outputs == {}:
652            return
653        inputs, outputs = self.get_odered_results(data_inputs, data_outputs)
654        for pos in range(self.GetPageCount()):
655            grid = self.GetPage(pos)
656            if grid.data is None:
657                #Found empty page
658                grid.set_data(data_inputs=inputs, 
659                              data_outputs=outputs,
660                              details=details,
661                              file_name=file_name) 
662                self.SetSelection(pos) 
663                return
664               
665        grid, pos = self.add_empty_page()
666        grid.set_data(data_inputs=inputs, 
667                      data_outputs=outputs,
668                      file_name=file_name,
669                      details=details)
670       
671    def get_odered_results(self, inputs, outputs=None):
672        """
673        Get ordered the results
674        """
675        # Let's re-order the data from the keys in 'Data' name.
676        if outputs == None:
677            return
678        try:
679            # For outputs from batch
680            to_be_sort = [str(item.label) for item in outputs['Data']]
681        except:
682            # When inputs are from an external file
683            return inputs, outputs
684        inds = numpy.lexsort((to_be_sort, to_be_sort))
685        for key in outputs.keys():
686            key_list = outputs[key]
687            temp_key = [item for item in key_list]
688            for ind in inds:
689                temp_key[ind] = key_list[inds[ind]]
690            outputs[key] = temp_key
691        for key in inputs.keys():
692            key_list = inputs[key]
693            if len(key_list) > 0:
694                temp_key = [item for item in key_list]
695                for ind in inds:
696                    temp_key[ind] = key_list[inds[ind]]
697                inputs[key] = temp_key
698        return inputs, outputs
699   
700    def add_column(self):
701        """
702        Append a new column to the grid
703        """
704        pos = self.GetSelection()
705        grid = self.GetPage(pos)
706        grid.AppendCols(1, True)
707       
708class GridPanel(SPanel):
709    def __init__(self, parent, data_inputs=None,
710                 data_outputs=None, *args, **kwds):
711        SPanel.__init__(self, parent , *args, **kwds)
712       
713        self.vbox = wx.BoxSizer(wx.VERTICAL)
714       
715        self.plotting_sizer = wx.FlexGridSizer(3, 7, 10, 5)
716        self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
717        self.grid_sizer = wx.BoxSizer(wx.HORIZONTAL)
718        self.vbox.AddMany([(self.grid_sizer, 1, wx.EXPAND, 0),
719                           (wx.StaticLine(self, -1), 0, wx.EXPAND, 0),
720                           (self.plotting_sizer),
721                           (self.button_sizer)])
722        self.parent = parent
723        self._data_inputs = data_inputs
724        self._data_outputs = data_outputs
725        self.x = []
726        self.= []
727        self.x_axis_label = None
728        self.y_axis_label = None
729        self.x_axis_title = None
730        self.y_axis_title = None
731        self.x_axis_unit = None
732        self.y_axis_unit = None
733        self.view_button = None
734        self.plot_button = None
735        self.notebook = None
736       
737        self.layout_grid()
738        self.layout_plotting_area()
739        self.SetSizer(self.vbox)
740
741    def set_xaxis(self, label="", x=None):
742        """
743        """
744        if x is None:
745            x = []
746        self.x = x
747        self.x_axis_label.SetValue("%s[:]" % str(label))
748        self.x_axis_title.SetValue(str(label))
749       
750    def set_yaxis(self, label="", y=None):
751        """
752        """
753        if y is None:
754            y = []
755        self.y = y
756        self.y_axis_label.SetValue("%s[:]" % str(label))
757        self.y_axis_title.SetValue(str(label))
758       
759    def get_plot_axis(self, col, list):
760        """
761       
762        """
763        axis = []
764        pos = self.notebook.GetSelection()
765        grid = self.notebook.GetPage(pos)
766        for row in list:
767            label = grid.GetCellValue(0, col)
768            value = grid.GetCellValue(row - 1, col).strip()
769            if value != "":
770                if label.lower().strip() == "data":
771                    axis.append(float(row - 1))
772                else:
773                    try:
774                        axis.append(float(value))
775                    except:
776                        msg = "Invalid data in row %s column %s" % (str(row),
777                                                                    str(col))
778                        wx.PostEvent(self.parent.parent, 
779                             StatusEvent(status=msg, info="error")) 
780            else:
781                axis.append(None) 
782        return axis
783   
784    def on_save_column(self, parent):
785        """
786        """
787        pos = self.notebook.GetSelection()
788        grid = self.notebook.GetPage(pos)
789        if parent is not None and  self.data is not None:
790            parent.write_batch_tofile(data=grid.data, 
791                                               file_name=path,
792                                               details=self.details)
793       
794    def on_view(self, event):
795        """
796        Get object represented buy the given cell and plot them.
797        """
798        pos = self.notebook.GetSelection()
799        grid = self.notebook.GetPage(pos)
800        title = self.notebook.GetPageText(pos)
801        if len(grid.selected_cells) == 0:
802            msg = "Highlight a Data or Chi2 column first..."
803            wx.PostEvent(self.parent.parent, 
804                             StatusEvent(status=msg, info="error")) 
805            return
806        for cell in grid.selected_cells:
807            row, col = cell
808            label_row = 0
809            label = grid.GetCellValue(label_row, col)
810            if label in grid.data:
811                values = grid.data[label]
812                if row > len(values) or row < 1:
813                    msg = "Invalid cell was chosen." 
814                    wx.PostEvent(self.parent.parent, StatusEvent(status=msg, 
815                                                                info="error"))
816                    time.sleep(0.5)
817                    continue
818                else:
819                     value = values[row -1]
820                if issubclass(value.__class__, BatchCell):
821                    if value.object is None or len(value.object) == 0:
822                        msg = "Row %s , " % str(row)
823                        msg += "Column %s is NOT " % str(label)
824                        msg += "the results of fits to view..."
825                        #raise ValueError, msg
826                        wx.PostEvent(self.parent.parent, StatusEvent(status=msg, 
827                                                                info="error")) 
828                        return
829                    for new_plot in value.object:
830                        if new_plot is None or \
831                         not issubclass(new_plot.__class__, 
832                                        plottables.Plottable):
833                            msg = "Row %s , " % str(row)
834                            msg += "Column %s is NOT " % str(label)
835                            msg += "the results of fits to view..."
836                            #raise ValueError, msg
837                            wx.PostEvent(self.parent.parent, 
838                                 StatusEvent(status=msg, info="error")) 
839                            time.sleep(0.5)
840                            continue
841                        #new_plot.name =  title + ': ' + new_plot.title
842                        if issubclass(new_plot.__class__, Data1D):
843                            if label in grid.list_plot_panels.keys():
844                                group_id = grid.list_plot_panels[label]
845                            else:
846                                group_id = str(new_plot.group_id) + str(grid.uid)
847                                grid.list_plot_panels[label] = group_id
848                            if group_id not in new_plot.list_group_id:
849                                new_plot.group_id = group_id
850                                new_plot.list_group_id.append(group_id)
851                        else:
852                            if label.lower() in ["data", "chi2"]:
853                                if len(grid.selected_cells) != 1:
854                                    msg = "2D View: Please select one data set"
855                                    msg += " at a time for View Results."
856                                    wx.PostEvent(self.parent.parent, 
857                                                 StatusEvent(status=msg,
858                                                              info="error"))
859                                    time.sleep(0.5) 
860                                    continue 
861                        """
862                        wx.PostEvent(self.parent.parent,
863                                     NewPlotEvent(action="clear",
864                                                  group_id=str(group_id),
865                                                  title=title))
866                        """ 
867                        wx.PostEvent(self.parent.parent, 
868                                     NewPlotEvent(plot=new_plot, 
869                                                group_id=str(new_plot.group_id),
870                                                title=title)) 
871                        msg = "Plotting the View Results  completed!"
872                        wx.PostEvent( self.parent.parent, 
873                                      StatusEvent(status=msg)) 
874                else:
875                   
876                    msg = "Row %s , " % str(row)
877                    msg += "Column %s is NOT " % str(label)
878                    msg += "the results of fits to view..."
879                    #raise ValueError, msg
880                    wx.PostEvent(self.parent.parent, 
881                         StatusEvent(status=msg, info="error")) 
882                    time.sleep(0.5)
883                    continue
884   
885       
886     
887   
888    def on_plot(self, event):
889        """
890        Evaluate the contains of textcrtl and plot result
891        """ 
892        pos = self.notebook.GetSelection()
893        grid = self.notebook.GetPage(pos)
894        column_names = {}
895        if grid is not None:
896            column_names = self.notebook.get_column_labels()
897        #evaluate x
898        sentence = self.x_axis_label.GetValue()
899        try:
900            if sentence.strip() == "":
901                msg = "Select column values for x axis"
902                raise ValueError, msg
903        except:
904             wx.PostEvent(self.parent.parent, 
905                             StatusEvent(status=msg, info="error")) 
906             return
907
908        dict = parse_string(sentence, column_names.keys())
909        for tok, (col_name, list) in dict.iteritems():
910            col = column_names[col_name]
911            xaxis = self.get_plot_axis(col, list)
912            sentence = sentence.replace(tok, 
913                                        "numpy.array(%s)" % str(xaxis))
914        for key, value in FUNC_DICT.iteritems():
915            sentence = sentence.replace(key.lower(), value)
916        x = eval(sentence)
917        #evaluate y
918        sentence = self.y_axis_label.GetValue()
919        if sentence.strip() == "":
920            msg = "select value for y axis"
921            raise ValueError, msg
922        dict = parse_string(sentence, column_names.keys())
923        for tok, (col_name, list) in dict.iteritems():
924            col = column_names[col_name]
925            yaxis = self.get_plot_axis(col, list)
926            sentence = sentence.replace(tok, 
927                                        "numpy.array(%s)" % str(yaxis))
928        for key, value in FUNC_DICT.iteritems():
929            sentence = sentence.replace(key, value)
930        y = eval(sentence)
931        if len(x) != len(y) and (len(x) == 0 or len(y) == 0):
932            msg = "Need same length for X and Y axis and both greater than 0"
933            msg += " to plot.\n"
934            msg += "Got X length = %s, Y length = %s" % (str(len(x)),
935                                                          str(len(y)))
936            wx.PostEvent(self.parent.parent, 
937                             StatusEvent(status=msg, info="error")) 
938            return
939           
940        #plotting
941        new_plot = Data1D(x=x, y=y)
942        new_plot.id =  wx.NewId()
943        new_plot.group_id = wx.NewId()
944        title = "%s vs %s" % (self.y_axis_title.GetValue(), 
945                              self.x_axis_title.GetValue())
946        new_plot.xaxis(self.x_axis_title.GetValue(), 
947                       self.x_axis_unit.GetValue())
948        new_plot.yaxis(self.y_axis_title.GetValue(), 
949                       self.y_axis_unit.GetValue())
950        try:
951            title = self.notebook.GetPageText(pos)
952            new_plot.name = title
953            new_plot.xtransform = "x"
954            new_plot.ytransform  = "y" 
955            wx.PostEvent(self.parent.parent, 
956                        NewPlotEvent(plot=new_plot, 
957                        group_id=str(new_plot.group_id), title =title)) 
958            msg = "Plotting completed!"
959            wx.PostEvent( self.parent.parent, 
960                                      StatusEvent(status=msg))   
961        except:
962             wx.PostEvent(self.parent.parent, 
963                             StatusEvent(status=msg, info="error")) 
964
965    def layout_grid(self):
966        """
967        Draw the area related to the grid
968        """
969        self.notebook = Notebook(parent=self)
970        self.notebook.set_data(self._data_inputs, self._data_outputs)
971        self.grid_sizer.Add(self.notebook, 1, wx.EXPAND, 0)
972       
973    def layout_plotting_area(self):
974        """
975        Draw area containing options to plot
976        """
977       
978        self.x_axis_title = wx.TextCtrl(self, -1)
979        self.y_axis_title = wx.TextCtrl(self, -1)
980        self.x_axis_label = wx.TextCtrl(self, -1, size=(200, -1))
981        self.y_axis_label = wx.TextCtrl(self, -1, size=(200, -1))
982        self.x_axis_add = wx.Button(self, -1, "Add")
983        self.x_axis_add.Bind(event=wx.EVT_BUTTON, handler=self.on_edit_axis, 
984                            id=self.x_axis_add.GetId())
985        self.y_axis_add = wx.Button(self, -1, "Add")
986        self.y_axis_add.Bind(event=wx.EVT_BUTTON, handler=self.on_edit_axis, 
987                            id=self.y_axis_add.GetId())
988        self.x_axis_unit = wx.TextCtrl(self, -1)
989        self.y_axis_unit = wx.TextCtrl(self, -1)
990        self.view_button = wx.Button(self, -1, "View Results")
991        view_tip = "Highlight the data set or the Chi2 column first."
992        self.view_button.SetToolTipString(view_tip)
993        wx.EVT_BUTTON(self, self.view_button.GetId(), self.on_view)
994        self.plot_button = wx.Button(self, -1, "Plot")
995        plot_tip = "Highlight a column for each axis and \n"
996        plot_tip += "click the Add buttons first."
997        self.plot_button.SetToolTipString(plot_tip)
998        self.button_sizer.AddMany( [ (500, 30),
999                                (self.view_button, 0, wx.RIGHT|wx.BOTTOM, 10),
1000                                (self.plot_button, 0, wx.RIGHT|wx.BOTTOM, 10)])
1001       
1002        wx.EVT_BUTTON(self, self.plot_button.GetId(), self.on_plot)
1003        self.plotting_sizer.AddMany([
1004                    (wx.StaticText(self, -1, 
1005                                   "X-axis Label\nSelection Range"), 1,
1006                      wx.TOP|wx.BOTTOM|wx.LEFT, 10),
1007                    (self.x_axis_label, 1, wx.TOP|wx.BOTTOM, 10),
1008                    (self.x_axis_add, 1, wx.TOP|wx.BOTTOM|wx.RIGHT, 10),
1009                    (wx.StaticText(self, -1, "X-axis Label"), 1, 
1010                     wx.TOP|wx.BOTTOM|wx.LEFT, 10),
1011                    (self.x_axis_title, 1, wx.TOP|wx.BOTTOM, 10),
1012                    (wx.StaticText(self, -1 , "X-axis Unit"), 1, 
1013                     wx.TOP|wx.BOTTOM, 10),
1014                    (self.x_axis_unit, 1, wx.TOP|wx.BOTTOM, 10),
1015                    (wx.StaticText(self, -1, 
1016                                   "Y-axis Label\nSelection Range"), 1, 
1017                     wx.BOTTOM|wx.LEFT, 10),
1018                    (self.y_axis_label, wx.BOTTOM, 10),
1019                    (self.y_axis_add, 1, wx.BOTTOM|wx.RIGHT, 10),
1020                    (wx.StaticText(self, -1, "Y-axis Label"), 1, 
1021                     wx.BOTTOM|wx.LEFT, 10),
1022                    (self.y_axis_title,  wx.BOTTOM, 10),
1023                    (wx.StaticText(self, -1 , "Y-axis Unit"), 1, wx.BOTTOM, 10),
1024                    (self.y_axis_unit, 1, wx.BOTTOM, 10),
1025                      (-1, -1),
1026                      (-1, -1),
1027                      (-1, -1),
1028                      (-1, -1),
1029                      (-1, -1),
1030                      (-1, -1),
1031                      (-1, 1)])
1032   
1033    def on_edit_axis(self, event):
1034        """
1035        Get the selected column on  the visible grid and set values for axis
1036        """
1037        try:
1038            cell_list = self.notebook.on_edit_axis()
1039        except:
1040            msg = str(sys.exc_value)
1041            wx.PostEvent(self.parent.parent, 
1042                             StatusEvent(status=msg, info="error")) 
1043            return 
1044        label, title = self.create_axis_label(cell_list)
1045        tcrtl = event.GetEventObject()
1046        if tcrtl == self.x_axis_add:
1047            self.edit_axis_helper(self.x_axis_label, self.x_axis_title,
1048                                   label, title)
1049        elif tcrtl == self.y_axis_add:
1050            self.edit_axis_helper(self.y_axis_label, self.y_axis_title,
1051                                   label, title)
1052           
1053    def create_axis_label(self, cell_list):
1054        """
1055        Receive a list of cells and  create a string presenting the selected
1056        cells.
1057        :param cell_list: list of tuple
1058       
1059        """
1060        if self.notebook is not None:
1061            return self.notebook.create_axis_label(cell_list)
1062   
1063    def edit_axis_helper(self, tcrtl_label, tcrtl_title, label, title):
1064        """
1065        get controls to modify
1066        """
1067        tcrtl_label.SetValue(str(label))
1068        tcrtl_title.SetValue(str(title))
1069       
1070    def add_column(self):
1071        """
1072        """
1073        if self.notebook is not None:
1074            self.notebook.add_column()
1075       
1076    def on_remove_column(self):
1077        """
1078        """
1079        if self.notebook is not None:
1080            self.notebook.on_remove_column()
1081       
1082       
1083class GridFrame(wx.Frame):
1084    def __init__(self, parent=None, data_inputs=None, data_outputs=None, id=-1, 
1085                 title="Batch Window", size=(800, 500)):
1086        wx.Frame.__init__(self, parent=parent, id=id, title=title, size=size)
1087        self.parent = parent
1088        self.panel = GridPanel(self, data_inputs, data_outputs)
1089        menubar = wx.MenuBar()
1090        self.SetMenuBar(menubar)
1091       
1092        self.curr_col = None
1093        self.curr_grid = None
1094        self.curr_col_name = ""
1095        file = wx.Menu()
1096        menubar.Append(file, "&File")
1097       
1098        hint = "Open file containing batch results"
1099        open_menu = file.Append(wx.NewId(), 'Open ', hint)
1100        wx.EVT_MENU(self, open_menu.GetId(), self.on_open)
1101       
1102        hint = "Open the the current grid into excel"
1103        open_excel_menu = file.Append(wx.NewId(), 'Open with Excel', hint)
1104        wx.EVT_MENU(self, open_excel_menu.GetId(), self.open_with_excel)
1105        file.AppendSeparator()
1106        save_menu = file.Append(wx.NewId(), 'Save As', 'Save into File')
1107        wx.EVT_MENU(self, save_menu.GetId(), self.on_save_page)
1108       
1109        self.edit = wx.Menu()
1110        hint = "Insert column before the selected column"
1111        self.insert_before_menu = wx.Menu()
1112        self.insert_sub_menu = self.edit.AppendSubMenu(self.insert_before_menu, 
1113                                                      'Insert Before', hint)
1114 
1115        hint = "Remove the selected column"
1116        self.remove_menu = self.edit.Append(-1, 'Remove Column', hint)
1117        wx.EVT_MENU(self, self.remove_menu.GetId(), self.on_remove_column)
1118       
1119        self.Bind(wx.EVT_MENU_OPEN, self.on_menu_open)
1120        menubar.Append(self.edit, "&Edit")
1121        self.Bind(wx.EVT_CLOSE, self.on_close)
1122    def GetLabelText(self, id):
1123        """
1124        """
1125        for item in self.insert_before_menu.GetMenuItems():
1126            m_id = item.GetId() 
1127            if m_id == id:
1128                return item.GetLabel() 
1129   
1130    def on_remove_column(self, event):
1131        """
1132        """
1133        pos = self.panel.notebook.GetSelection()
1134        grid = self.panel.notebook.GetPage(pos)
1135        grid.on_remove_column(event=None)
1136       
1137    def on_menu_open(self, event):
1138        """
1139       
1140        """
1141        if self.edit == event.GetMenu():
1142            #get the selected column
1143            pos = self.panel.notebook.GetSelection()
1144            grid = self.panel.notebook.GetPage(pos)
1145            col_list = grid.GetSelectedCols()
1146            if len(col_list) > 0:
1147                self.remove_menu.Enable(True)
1148            else:
1149                self.remove_menu.Enable(False)
1150            if len(col_list)== 0 or len(col_list) > 1:
1151                self.insert_sub_menu.Enable(False)
1152               
1153                label = "Insert Column Before"
1154                self.insert_sub_menu.SetText(label)
1155            else:
1156                self.insert_sub_menu.Enable(True)
1157               
1158                col = col_list[0]
1159                #GetColLabelValue(self, col)
1160                col_name = grid.GetCellValue(row=0, col=col)
1161                label = "Insert Column Before " + str(col_name)
1162                self.insert_sub_menu.SetText(label)
1163                for item in self.insert_before_menu.GetMenuItems():
1164                    self.insert_before_menu.DeleteItem(item)
1165                grid.insert_col_menu(menu=self.insert_before_menu, 
1166                                     label=col_name, window=self)
1167        event.Skip()
1168       
1169 
1170       
1171    def on_save_page(self, event):
1172        """
1173        """
1174        if self.parent is not None:
1175            pos = self.panel.notebook.GetSelection()
1176            grid = self.panel.notebook.GetPage(pos)
1177            if grid.file_name is None or grid.file_name.strip() == "" or \
1178                grid.data is None or len(grid.data) == 0:
1179                name = self.panel.notebook.GetPageText(pos)
1180                msg = " %s has not data to save" % str(name)
1181                wx.PostEvent(self.parent, 
1182                             StatusEvent(status=msg, info="error")) 
1183           
1184                return
1185            reader, ext = os.path.splitext(grid.file_name)
1186            path = None
1187            if self.parent is not None: 
1188                location = os.path.dirname(grid.file_name)
1189                dlg = wx.FileDialog(self, "Save Project file",
1190                            location, grid.file_name, ext, wx.SAVE)
1191                path = None
1192                if dlg.ShowModal() == wx.ID_OK:
1193                    path = dlg.GetPath()
1194                dlg.Destroy()
1195                if path != None:
1196                    if self.parent is not None:
1197                        data = grid.get_grid_view()
1198                        self.parent.write_batch_tofile(data=data, 
1199                                               file_name=path,
1200                                               details=grid.details)
1201   
1202    def on_open(self, event):
1203        """
1204        Open file containg batch result
1205        """
1206        if self.parent is not None:
1207            self.parent.on_read_batch_tofile(event)
1208           
1209    def open_with_excel(self, event):
1210        """
1211        open excel and display batch result in Excel
1212        """
1213        if self.parent is not None:
1214            pos = self.panel.notebook.GetSelection()
1215            grid = self.panel.notebook.GetPage(pos)
1216            data = grid.get_grid_view()
1217            if grid.file_name is None or grid.file_name.strip() == "" or \
1218                grid.data is None or len(grid.data) == 0:
1219                name = self.panel.notebook.GetPageText(pos)
1220                msg = " %s has not data to open on excel" % str(name)
1221                wx.PostEvent(self.parent, 
1222                             StatusEvent(status=msg, info="error")) 
1223           
1224                return
1225            self.parent.open_with_externalapp(data=data,
1226                                               file_name=grid.file_name, 
1227                                               details=grid.details)
1228           
1229    def on_close(self, event):
1230        """
1231        """
1232        self.Hide()
1233       
1234   
1235    def on_append_column(self, event):
1236        """
1237        Append a new column to the grid
1238        """
1239        self.panel.add_column()
1240       
1241    def set_data(self, data_inputs, data_outputs, details="", file_name=None):
1242        """
1243        """
1244       
1245        self.panel.notebook.set_data(data_inputs=data_inputs, 
1246                            file_name=file_name,
1247                            details=details,
1248                            data_outputs=data_outputs)
1249     
1250     
1251class BatchOutputFrame(wx.Frame):
1252    """
1253    Allow to select where the result of batch will be displayed or stored
1254    """
1255    def __init__(self, parent, data_inputs, data_outputs, file_name="",
1256                 details="", *args, **kwds):
1257        """
1258        :param parent: Window instantiating this dialog
1259        :param result: result to display in a grid or export to an external
1260                application.
1261        """
1262        #kwds['style'] = wx.CAPTION|wx.SYSTEM_MENU
1263        wx.Frame.__init__(self, parent, *args, **kwds)
1264        self.parent = parent
1265        self.panel = wx.Panel(self)
1266        self.file_name = file_name
1267        self.details = details
1268        self.data_inputs = data_inputs
1269        self.data_outputs = data_outputs
1270        self.data = {}
1271        for item in (self.data_outputs, self.data_inputs):
1272            self.data.update(item)
1273        self.flag = 1
1274        self.SetSize((300, 200))
1275        self.local_app_selected = None
1276        self.external_app_selected = None
1277        self.save_to_file = None
1278        self._do_layout()
1279   
1280    def _do_layout(self):
1281        """
1282        Draw the content of the current dialog window
1283        """
1284        vbox = wx.BoxSizer(wx.VERTICAL)
1285        box_description = wx.StaticBox(self.panel, -1, str("Batch Outputs"))
1286        hint_sizer = wx.StaticBoxSizer(box_description, wx.VERTICAL)
1287        selection_sizer = wx.GridBagSizer(5, 5)
1288        button_sizer = wx.BoxSizer(wx.HORIZONTAL)
1289        text = "Open with %s" % self.parent.application_name
1290        self.local_app_selected = wx.RadioButton(self.panel, -1, text,
1291                                                style=wx.RB_GROUP)
1292        self.Bind(wx.EVT_RADIOBUTTON, self.onselect,
1293                    id=self.local_app_selected.GetId())
1294        text = "Open with Excel"
1295        self.external_app_selected  = wx.RadioButton(self.panel, -1, text)
1296        self.Bind(wx.EVT_RADIOBUTTON, self.onselect,
1297                    id=self.external_app_selected.GetId())
1298        text = "Save to File"
1299        self.save_to_file = wx.CheckBox(self.panel, -1, text)
1300        self.Bind(wx.EVT_CHECKBOX, self.onselect,
1301                    id=self.save_to_file.GetId())
1302        self.local_app_selected.SetValue(True)
1303        self.external_app_selected.SetValue(False)
1304        self.save_to_file.SetValue(False)
1305        button_close = wx.Button(self.panel, -1, "Close")
1306        button_close.Bind(wx.EVT_BUTTON, id=button_close.GetId(),
1307                           handler=self.on_close)
1308        button_apply = wx.Button(self.panel, -1, "Apply")
1309        button_apply.Bind(wx.EVT_BUTTON, id=button_apply.GetId(),
1310                        handler=self.on_apply)
1311        button_apply.SetFocus()
1312        hint = ""
1313        hint_sizer.Add(wx.StaticText(self.panel, -1, hint))
1314        hint_sizer.Add(selection_sizer)
1315        #draw area containing radio buttons
1316        ix = 0
1317        iy = 0
1318        selection_sizer.Add(self.local_app_selected, (iy, ix),
1319                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1320        iy += 1
1321        selection_sizer.Add(self.external_app_selected, (iy, ix),
1322                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1323        iy += 1
1324        selection_sizer.Add(self.save_to_file, (iy, ix),
1325                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1326        #contruction the sizer contaning button
1327        button_sizer.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
1328
1329        button_sizer.Add(button_close, 0,
1330                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
1331        button_sizer.Add(button_apply, 0,
1332                                wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
1333        vbox.Add(hint_sizer,  0, wx.EXPAND|wx.ALL, 10)
1334        vbox.Add(wx.StaticLine(self.panel, -1),  0, wx.EXPAND, 0)
1335        vbox.Add(button_sizer, 0 , wx.TOP|wx.BOTTOM, 10)
1336        self.SetSizer(vbox)
1337       
1338    def on_apply(self, event):
1339        """
1340        Get the user selection and display output to the selected application
1341        """
1342        if self.flag == 1:
1343            self.parent.open_with_localapp(data_inputs=self.data_inputs,
1344                                            data_outputs=self.data_outputs)
1345        elif self.flag == 2:
1346            self.parent.open_with_externalapp(data=self.data, 
1347                                           file_name=self.file_name,
1348                                           details=self.details)
1349    def on_close(self, event):
1350        """
1351        close the Window
1352        """
1353        self.Close()
1354       
1355    def onselect(self, event=None):
1356        """
1357        Receive event and display data into third party application
1358        or save data to file.
1359       
1360        """
1361        if self.save_to_file.GetValue():
1362            reader, ext = os.path.splitext(self.file_name)
1363            path = None
1364            location = os.getcwd()
1365            if self.parent is not None: 
1366                location = os.path.dirname(self.file_name)
1367                dlg = wx.FileDialog(self, "Save Project file",
1368                            location, self.file_name, ext, wx.SAVE)
1369                path = None
1370                if dlg.ShowModal() == wx.ID_OK:
1371                    path = dlg.GetPath()
1372                dlg.Destroy()
1373                if path != None:
1374                    if self.parent is not None and  self.data is not None:
1375                        self.parent.write_batch_tofile(data=self.data, 
1376                                               file_name=path,
1377                                               details=self.details)
1378        if self.local_app_selected.GetValue():
1379            self.flag = 1
1380        else:
1381            self.flag = 2
1382        return self.flag
1383   
1384 
1385       
1386if __name__ == "__main__":
1387    app = wx.App()
1388   
1389    try:
1390        data = {}
1391        j = 0
1392        for i in range(4):
1393            j += 1
1394            data["index"+str(i)] = [i/j, i*j, i, i+j]
1395       
1396        data_input =  copy.deepcopy(data)   
1397        data_input["index5"] = [10,20,40, 50]
1398        frame = GridFrame(data_outputs=data, data_inputs=data_input)
1399        frame.Show(True)
1400    except:
1401        print sys.exc_value
1402       
1403    app.MainLoop()
Note: See TracBrowser for help on using the repository browser.