def __init__(self, *args, **kwargs):
     """Initializer.
     """
     InspectorPage.__init__(self, *args, **kwargs)
     # path text.
     path_label = wx.StaticText(self, -1, 'Path')
     path_text = wx.TextCtrl(self, -1, style=wx.TE_READONLY)
     # attributes grid.
     attr_label = wx.StaticText(self, -1, 'Attributes')
     attr_grid = Grid(self, -1, size=(-1, 100))
     attr_grid.CreateGrid(0, 2)
     attr_grid.SetColLabelValue(0, 'Key')
     attr_grid.SetColLabelValue(1, 'Value')
     attr_grid.EnableEditing(False)
     # values (for datasets) grid.
     vals_label = wx.StaticText(self, -1, 'Values')
     vals_grid = Grid(self, -1)
     vals_grid.CreateGrid(0, 0)
     vals_grid.EnableEditing(False)
     self.sizer.Add(path_label, 0, wx.ALL | wx.EXPAND, 5)
     self.sizer.Add(path_text, 0, wx.ALL | wx.EXPAND, 5)
     self.sizer.Add(attr_label, 0, wx.ALL | wx.EXPAND, 5)
     self.sizer.Add(attr_grid, 0, wx.ALL | wx.EXPAND, 5)
     self.sizer.Add(vals_label, 0, wx.ALL | wx.EXPAND, 5)
     self.sizer.Add(vals_grid, 1, wx.ALL | wx.EXPAND, 5)
     self.path_text = path_text
     self.attr_grid = attr_grid
     self.vals_grid = vals_grid
Пример #2
0
    def __init__(self, parent, owner):
        Grid.__init__(self, parent, style=wx.BORDER_RAISED)

        self._owner = owner
        self._setups = []

        self.CreateGrid(0, 1)

        self.HideRowLabels()  # Hide the index column
        self.HideColLabels()  # Hide the column names
        self.EnableGridLines(False)  # Hide grid lines
        self.DisableDragGridSize(
        )  # Disable resizing of rows/columns by dragging
        self.DisableDragColMove()  # Disable reordering of columns by dragging
        self.SetCellHighlightPenWidth(
            0)  # Disable the highlight around the "current" cell
        self.SetCellHighlightROPenWidth(
            0)  # Disable the highlight around the "current" read-only cell
        self.SetSelectionMode(wx.grid.Grid.SelectRows)  # Select the entire row

        self.Bind(wx.grid.EVT_GRID_SELECT_CELL, self._onCellSelected)
        self.Bind(wx.grid.EVT_GRID_CELL_CHANGING, self._onCellChanging)
        self.Bind(wx.EVT_SIZE, self._onResized)
        self.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self._showContextMenu)
        gui.mainFrame.MainFrame.getInstance().Bind(GE.SETUPS_CHANGED,
                                                   self._onSetupsChanged)
Пример #3
0
    def __init__(self):
        wx.Dialog.__init__(self, None, -1, "Mini Excel")
        sizer = wx.BoxSizer(wx.VERTICAL)

        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        hsizer.Add(wx.StaticText(self, -1, "Value:"), 0,
                   wx.ALIGN_CENTER_VERTICAL)
        self.cell_value = wx.TextCtrl(self, -1)
        hsizer.Add(self.cell_value, 1, wx.EXPAND)
        b = wx.Button(self, -1, "&Set")
        self.Bind(wx.EVT_BUTTON, self.OnSetCell, b)
        hsizer.Add(b)
        sizer.Add(hsizer, 0, wx.EXPAND)

        grid = Grid(self)
        grid.SetTable(Table())
        grid.ForceRefresh()
        self.grid = grid

        self.Bind(EVT_GRID_CELL_LEFT_CLICK, self.OnCellClick, grid)
        self.current_cell = (0, 0)

        sizer.Add(grid, 1, wx.EXPAND)
        self.SetSizer(sizer)
        sizer.Fit(self)
        grid.SetFocus()

        self.CenterOnScreen()
Пример #4
0
 def __init__(self, parent, data):
     Grid.__init__(self, parent, -1)
     self.parent = parent
     self.FactionObject = data
     self.factionNumber = len(self.FactionObject.factionList)
     self.hasChanged = False
     self.CreateGrid()
Пример #5
0
    def __init__(self, parent):
        Grid.__init__(self, parent)

        self.selected_row = None
        self.__data = None
        self.__data_attrs = [
            u'name', u'by', u'selector', u'location', u'dimensions'
        ]
Пример #6
0
    def __init__(self, parent, model):
        """ Constructor. """

        # Base class constructor.
        wxGrid.__init__(self, parent, -1)

        # The model that provides the data and row/column information.
        self.model = None

        # Automatically size columns and rows to fit their content.
        #
        # fixme: wx seems sensitive to the location of these two lines. Put
        # them *before* the call to 'SetTable', otherwise the grid takes
        # forever to initialize!
        ##self.AutoSizeColumns()
        ##self.AutoSizeRows()

        # Don't display any extra space around the rows and columns.
        self.SetMargins(0, 0)

        # Tell the grid to get its data from the model.
        #
        # N.B The terminology used in the wxPython API is a little confusing!
        # --- The 'SetTable' method is actually setting the model used by
        #     the grid (which is the view)!
        #
        # The second parameter to 'SetTable' tells the grid to take ownership
        # of the model and to destroy it when it is done.  Otherwise you would
        # need to keep a reference to the model and manually destroy it later
        # (by calling it's Destroy method).
        #
        # fixme: We should create a default model if one is not supplied.
        self.SetTable(model._grid_table_base, True)
        model.on_trait_change(self._on_model_changed, 'model_changed')

        wx.grid.EVT_GRID_CELL_CHANGE(self, self._on_cell_change)
        wx.grid.EVT_GRID_SELECT_CELL(self, self._on_select_cell)

        # This starts the cell editor on a double-click as well as on a second
        # click.
        wx.grid.EVT_GRID_CELL_LEFT_DCLICK(self, self._on_cell_left_dclick)

        # This pops up a context menu.
        #wx.grid.EVT_GRID_CELL_RIGHT_CLICK(self, self._on_cell_right_click)

        # We handle key presses to change the behavior of the <Enter> and
        # <Tab> keys to make manual data entry smoother.
        wx.EVT_KEY_DOWN(self, self._on_key_down)

        # Initialize the row and column models.
        self._initialize_rows(model)
        self._initialize_columns(model)
        self._initialize_fonts()

        return
Пример #7
0
    def __init__(self, parent, model):
        """ Constructor. """

        # Base class constructor.
        wxGrid.__init__(self, parent, -1)

        # The model that provides the data and row/column information.
        self.model = None
        
        # Automatically size columns and rows to fit their content.
        #
        # fixme: wx seems sensitive to the location of these two lines. Put
        # them *before* the call to 'SetTable', otherwise the grid takes
        # forever to initialize!
        ##self.AutoSizeColumns()
        ##self.AutoSizeRows()

        # Don't display any extra space around the rows and columns.
        self.SetMargins(0, 0)

        # Tell the grid to get its data from the model.
        #
        # N.B The terminology used in the wxPython API is a little confusing!
        # --- The 'SetTable' method is actually setting the model used by
        #     the grid (which is the view)!
        #
        # The second parameter to 'SetTable' tells the grid to take ownership
        # of the model and to destroy it when it is done.  Otherwise you would
        # need to keep a reference to the model and manually destroy it later
        # (by calling it's Destroy method).
        #
        # fixme: We should create a default model if one is not supplied.
        self.SetTable(model._grid_table_base, True)
        model.on_trait_change(self._on_model_changed, 'model_changed')
        
        wx.grid.EVT_GRID_CELL_CHANGE(self, self._on_cell_change)
        wx.grid.EVT_GRID_SELECT_CELL(self, self._on_select_cell)

        # This starts the cell editor on a double-click as well as on a second
        # click.
        wx.grid.EVT_GRID_CELL_LEFT_DCLICK(self, self._on_cell_left_dclick)

        # This pops up a context menu.
        #wx.grid.EVT_GRID_CELL_RIGHT_CLICK(self, self._on_cell_right_click)

        # We handle key presses to change the behavior of the <Enter> and
        # <Tab> keys to make manual data entry smoother.
        wx.EVT_KEY_DOWN(self, self._on_key_down)

        # Initialize the row and column models.
        self._initialize_rows(model)
        self._initialize_columns(model)
        self._initialize_fonts()

        return
Пример #8
0
    def __init__(self, parent, file_name):
        'Inicia las tablas dinámicas'
        Grid.__init__(self, parent, -1)

        table = DynamicTable(self, file_name)

        self.SetTable(table, True)

        self.SetRowLabelSize(0)
        self.SetMargins(0, 0)
        self.AutoSizeColumns(False)
Пример #9
0
    def __init__(self, parent, id, title):
        self.dao = self.init_db()
        self.read_records = 0
        constraint = Constraints()
        constraint.offset = 0
        constraint.limit = 100

        # First, call the base class' __init__ method to create the frame
        wx.Frame.__init__(self, parent, id, title, wx.Point(100, 100),
                          wx.Size(300, 200))

        # Associate some events with methods of this class
        wx.EVT_SIZE(self, self.OnSize)
        #wx.EVT_SCROLLWIN_BOTTOM(self, self.OnEndScroll)

        # Add a panel and some controls to display the size and position
        panel = wx.Panel(self, -1)
        panel.SetBackgroundColour('#FDDF99')

        self.grid = Grid(panel)
        self.grid.CreateGrid(0, 12)
        wx.grid.EVT_GRID_CELL_LEFT_CLICK(self, self.OnGridLeftClick)
        #wx.EVT_SCROLLWIN_BOTTOM(self.grid, self.OnEndScroll)
        self.grid.Bind(wx.EVT_SCROLLWIN, self.OnEndScroll)

        #self.grid.SetCellBackgroundColour(2, 2, wx.CYAN)

        #self.grid.SetCellEditor(5, 0, wx.grid.GridCellNumberEditor(1,1000))
        #self.grid.SetCellValue(5, 0, "123")

        #self.grid.SetCellAlignment(9, 1, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        #self.grid.SetCellValue(9, 1, "This cell is set to span 3 rows and 3 columns")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.grid, 1, wx.EXPAND)
        panel.SetSizer(sizer)

        #self.grid.ClearGrid()
        ##self.grid.AppendRows(20)
        #self.grid.SetColLabelValue(0,"test")
        #self.grid.SetCellValue(21, 1, "This cell is set to span 3 rows and 3 columns")

        rows = self.dao.fetch_records(constraint,
                                      raw_answers=True,
                                      record_type_classname=AutosModel)
        self.read_records = len(rows)

        print(rows[0])
        #print(rows[7]["marca"])
        #print(rows[7]["modelo"])
        #print(rows[7]["version"])

        self.printRows(rows)
Пример #10
0
 def __init__(self, model, parent):
     Grid.__init__(self, parent)
     self.__defaultClass = model.defaultClass()
     self.CreateGrid(0, 2)
     self.SetColLabelValue(0, "Type")
     self.SetColLabelValue(1, "Actions")
     #self.SetDefaultColSize(200, False)
     self.__editor = grid.GridCellChoiceEditor(model.classes(), allowOthers=True)
     self.Bind(grid.EVT_GRID_SELECT_CELL, self._OnSelectedCell)
     self.Bind(grid.EVT_GRID_CELL_LEFT_DCLICK, self._OnLinkClicked)
     self.Bind(grid.EVT_GRID_CELL_CHANGE, self._OnCellEdit)
     self.Bind(grid.EVT_GRID_EDITOR_SHOWN, self._OnEditorShown)
     self.__ref = None
     self.__currentSelection = None
Пример #11
0
    def createchannelwin(self,chn):
        newspwin=wx.SplitterWindow(self.channelwin,wx.ID_ANY,style=wx.SP_3DBORDER|wx.SP_3DSASH|wx.NO_BORDER)
        xgrid=Grid(newspwin,wx.ID_ANY,style=wx.SUNKEN_BORDER)
        xgrid.SetRowLabelSize(0)
        xtable=CustomDataTable()
        xtable.colLabels=['深度',chn]
        xx,yy=self.wish.readchannel(chn)
        self.actch_data=(xx,yy)
        xtable.data=list(zip(xx[:500],yy[:500]))
        xgrid.SetTable(xtable,True)
        xgrid.ForceRefresh()
        
        
        xpan=wx.Panel(newspwin,wx.ID_ANY,style=wx.SUNKEN_BORDER)
        self.toolb.SetToolShortHelp(200,u'保存曲线数据['+chn+']')
        mpl=PlotExample(xpan,(400,4000))
        mpl.plot(yy, xx)
#         mpl.Show()
        
#         MPL=MPL_Panel_base(xpan,(400,4000))
#         
#         #MPL.Figure.set_figheight(20)
#         #MPL.set_psize(500, 3000)
#         #MPL.xticker(10.0,2.0)
        BoxSizer=wx.BoxSizer(wx.VERTICAL) 
        BoxSizer.Add(mpl,proportion =1, border = 1,flag = wx.ALL|wx.EXPAND)
        xpan.SetSizer(BoxSizer)
        xpan.Fit()
#         MPL.cla()
#         MPL.plot(yy,xx,'red')
#         MPL.yticker(50.0, 25.0)
#         MPL.xticker(10, 5)
#         MPL.xlim(50,150)
#         MPL.ylim(4000, 1000)
#         MPL.grid()
#         dd=MPL.pl.gca().xaxis
        #dd.set_label_position('top')
#         MPL.UpdatePlot()

        #MPL.Update()
        #wx.StaticText(xpan, -1, chn, (5,5))
        
        newspwin.SetMinimumPaneSize(20)
        newspwin.SplitVertically(xgrid, xpan, 180)
        old=self.channelwin.GetWindow2()
        self.channelwin.ReplaceWindow(old,newspwin)
        old.Destroy()
        newspwin.Show(True)
Пример #12
0
 def __init__(self, parent):
     Grid.__init__(self, parent, -1)
     self.__urls = []
     self.__onlyFinalUrls = False
     self.__sortColumnId = 1
     self.__sortDirectionDesc = True
     self.CreateGrid(0, 6)
     self.SetColLabelValue(0, "URL")
     self.SetColLabelValue(1, "Tweets count")
     self.SetColLabelValue(2, "Expanded")
     self.SetColLabelValue(3, "Lang")
     self.SetColLabelValue(4, "Class")
     self.SetColLabelValue(5, "Title")
     self.DisableCellEditControl()
     self.Bind(grid.EVT_GRID_CELL_LEFT_DCLICK, self._OnLinkClicked)
     self.Bind(grid.EVT_GRID_LABEL_LEFT_CLICK, self._OnLabelLeftClicked)
Пример #13
0
 def SetTable(self, table, *args):
     """ Some versions of wxPython do not return the correct
     table - hence we store our own copy here - weak ref?
     todo - does this apply to Enthought?
     """
     self._table = table
     return Grid.SetTable(self, table, *args)
Пример #14
0
    def __init__(self, parent, paramlist):
        wxGrid.__init__(
            self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.WANTS_CHARS, name=""
        )

        self.paramlist = paramlist

        self.CreateGrid(200, 9)
        self.EnableEditing(True)
        self.EnableGridLines(True)
        self.EnableDragGridSize(False)
        self.SetMargins(0, 0)
        self.EnableDragColMove(True)
        self.EnableDragColSize(True)
        self.EnableDragRowSize(True)
        self.EnableDragCell(False)

        self.SetColLabelValue(0, "Type")
        self.SetColSize(0, 40)
        self.SetColLabelValue(1, "Index")
        self.SetColSize(1, 40)
        self.SetColLabelValue(2, "Label")
        self.SetColSize(2, 80)
        self.SetColLabelValue(3, "Description")
        self.SetColSize(3, 120)
        self.SetColLabelValue(4, "Units")
        self.SetColSize(4, 60)
        self.SetColLabelValue(5, "Default")
        self.SetColSize(5, 80)
        self.SetColLabelValue(6, "Value")
        self.SetColSize(6, 80)
        self.SetColLabelValue(7, "Constraints (Warn)")
        self.SetColSize(7, 160)
        self.SetColLabelValue(8, "Constraints (Error)")
        self.SetColSize(8, 160)

        self.SetColLabelSize(20)
        self.SetColLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.SetRowLabelSize(0)
        self.SetRowLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
        self.SetDefaultCellAlignment(wx.ALIGN_LEFT, wx.ALIGN_TOP)

        # Connect Events
        self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.on_grid_update)

        # load:
        self.data2grid()
Пример #15
0
 def CreateGrid(self):
     Grid.CreateGrid(self, self.factionNumber, self.factionNumber)
     self.SetDefaultEditor(wx.grid.GridCellNumberEditor(0, 100))
     self.SetDefaultRenderer(wx.grid.GridCellNumberRenderer())
     self.SetDefaultColSize(50)
     self.setLabels()
     self.setDataCells()
     wx.grid.EVT_GRID_CELL_CHANGE(self, self.cellChanged)
     wx.grid.EVT_GRID_SELECT_CELL(self, self.cellSelected)
Пример #16
0
    def __init__(self, parent, ID=-1, **kw):

        Grid.__init__(self, parent, ID, **kw)

        # We have things set up to edit on a single click - so we have to select
        # an initial cursor location that is off of the screen otherwise a cell
        # will be in edit mode as soon as the grid fires up.
        self.moveTo = [1000, 1]
        self.edit = False

        # this seems like a busy idle ...
        self.Bind(wx.EVT_IDLE, self.OnIdle)

        # Enthought specific display controls ...
        self.init_labels()
        self.init_data_types()
        self.init_handlers()

        self.Bind(wx.grid.EVT_GRID_EDITOR_CREATED, self._on_editor_created)
Пример #17
0
    def __init__(self, parent, ID=-1, **kw):

        Grid.__init__(self, parent, ID, **kw)

        # We have things set up to edit on a single click - so we have to select
        # an initial cursor location that is off of the screen otherwise a cell
        # will be in edit mode as soon as the grid fires up.
        self.moveTo = [1000,1]
        self.edit = False

        # this seems like a busy idle ...
        wx.EVT_IDLE(self, self.OnIdle)

        # Enthought specific display controls ...
        self.init_labels()
        self.init_data_types()
        self.init_handlers()

        wx.grid.EVT_GRID_EDITOR_CREATED(self, self._on_editor_created)

        return
Пример #18
0
    def __init__(self, parent, model):
        wx.Dialog.__init__(self,
                           parent,
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
                           | wx.MAXIMIZE_BOX)
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(vbox)
        self.SetTitle('Statistical Analysis of Parameters')

        dpi_scale_factor = wx.GetApp().dpi_scale_factor

        self.ptxt = wx.StaticText(self, label="...")
        self.pbar = wx.Gauge(self, range=1000)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        vbox.Add(hbox, proportion=1, flag=wx.EXPAND)

        lpanel = wx.Panel(self)
        gpanel = wx.Panel(self)
        gbox = wx.BoxSizer(wx.VERTICAL)
        gpanel.SetSizer(gbox)
        self.grid = Grid(gpanel)
        gbox.Add(wx.StaticText(gpanel, label='Estimated covariance matrix:'),
                 proportion=0,
                 flag=wx.FIXED_MINSIZE)
        gbox.Add(self.grid, proportion=1, flag=wx.EXPAND)
        self.normalize_checkbox = wx.CheckBox(
            gpanel, label='Normalize value (σ_ij/σ_i/σ_j)')
        self.normalize_checkbox.SetValue(True)
        self.normalize_checkbox.Bind(wx.EVT_CHECKBOX, self.OnToggleNormalize)
        gbox.Add(self.normalize_checkbox, proportion=0, flag=wx.FIXED_MINSIZE)

        nfparams = len([pi for pi in model.parameters if pi.fit])
        self.grid.CreateGrid(nfparams + 1, nfparams)
        self.grid.SetColLabelTextOrientation(wx.VERTICAL)
        self.grid.SetColLabelSize(int(dpi_scale_factor * 80))
        for i in range(nfparams):
            self.grid.SetRowSize(i, int(dpi_scale_factor * 80))
            self.grid.SetColSize(i, int(dpi_scale_factor * 80))
            self.grid.SetColLabelValue(i, '%i' % i)
            self.grid.SetRowLabelValue(i + 1, '%i' % i)
        self.grid.SetRowSize(nfparams, int(dpi_scale_factor * 80))
        self.grid.DisableCellEditControl()
        self.grid.SetMinSize(
            (int(dpi_scale_factor * 200), int(dpi_scale_factor * 200)))
        self.grid.Bind(EVT_GRID_CELL_LEFT_DCLICK, self.OnSelectCell)
        rpanel = PlotPanel(self)
        rpanel.SetMinSize(
            (int(dpi_scale_factor * 200), int(dpi_scale_factor * 200)))
        self.plot_panel = rpanel
        self.ax = rpanel.figure.add_subplot(111)

        hbox.Add(lpanel, proportion=0, flag=wx.EXPAND | wx.ALIGN_TOP)
        hbox.Add(gpanel, proportion=1, flag=wx.EXPAND)
        hbox.Add(rpanel, proportion=1, flag=wx.EXPAND)

        lsizer = wx.GridSizer(vgap=1, hgap=2, cols=2)
        lpanel.SetSizer(lsizer)
        self.entries = {}
        for key, emin, emax, val in [('pop', 1, 20 * nfparams, 2 * nfparams),
                                     ('samples', 1000, 10000000, 10000),
                                     ('burn', 0, 10000, 200)]:
            lsizer.Add(wx.StaticText(lpanel, label='%s:' % key),
                       flag=wx.FIXED_MINSIZE)
            self.entries[key] = wx.SpinCtrl(lpanel,
                                            wx.ID_ANY,
                                            min=emin,
                                            max=emax,
                                            value=str(val))
            lsizer.Add(self.entries[key], flag=wx.FIXED_MINSIZE)

        lsizer.AddStretchSpacer(10)
        but = wx.Button(self, label='Run Analysis...')
        vbox.Add(but)
        vbox.Add(self.ptxt, proportion=0, flag=wx.EXPAND)
        vbox.Add(self.pbar, proportion=0, flag=wx.EXPAND)

        self.Bind(wx.EVT_BUTTON, self.OnRunAnalysis, but)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.model = model
        self.thread = None

        psize = parent.GetSize()
        self.SetSize(int(psize.GetWidth() * 0.75),
                     int(psize.GetHeight() * 0.75))
Пример #19
0
class StatisticalAnalysisDialog(wx.Dialog):
    rel_cov = None

    def __init__(self, parent, model):
        wx.Dialog.__init__(self,
                           parent,
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
                           | wx.MAXIMIZE_BOX)
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(vbox)
        self.SetTitle('Statistical Analysis of Parameters')

        dpi_scale_factor = wx.GetApp().dpi_scale_factor

        self.ptxt = wx.StaticText(self, label="...")
        self.pbar = wx.Gauge(self, range=1000)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        vbox.Add(hbox, proportion=1, flag=wx.EXPAND)

        lpanel = wx.Panel(self)
        gpanel = wx.Panel(self)
        gbox = wx.BoxSizer(wx.VERTICAL)
        gpanel.SetSizer(gbox)
        self.grid = Grid(gpanel)
        gbox.Add(wx.StaticText(gpanel, label='Estimated covariance matrix:'),
                 proportion=0,
                 flag=wx.FIXED_MINSIZE)
        gbox.Add(self.grid, proportion=1, flag=wx.EXPAND)
        self.normalize_checkbox = wx.CheckBox(
            gpanel, label='Normalize value (σ_ij/σ_i/σ_j)')
        self.normalize_checkbox.SetValue(True)
        self.normalize_checkbox.Bind(wx.EVT_CHECKBOX, self.OnToggleNormalize)
        gbox.Add(self.normalize_checkbox, proportion=0, flag=wx.FIXED_MINSIZE)

        nfparams = len([pi for pi in model.parameters if pi.fit])
        self.grid.CreateGrid(nfparams + 1, nfparams)
        self.grid.SetColLabelTextOrientation(wx.VERTICAL)
        self.grid.SetColLabelSize(int(dpi_scale_factor * 80))
        for i in range(nfparams):
            self.grid.SetRowSize(i, int(dpi_scale_factor * 80))
            self.grid.SetColSize(i, int(dpi_scale_factor * 80))
            self.grid.SetColLabelValue(i, '%i' % i)
            self.grid.SetRowLabelValue(i + 1, '%i' % i)
        self.grid.SetRowSize(nfparams, int(dpi_scale_factor * 80))
        self.grid.DisableCellEditControl()
        self.grid.SetMinSize(
            (int(dpi_scale_factor * 200), int(dpi_scale_factor * 200)))
        self.grid.Bind(EVT_GRID_CELL_LEFT_DCLICK, self.OnSelectCell)
        rpanel = PlotPanel(self)
        rpanel.SetMinSize(
            (int(dpi_scale_factor * 200), int(dpi_scale_factor * 200)))
        self.plot_panel = rpanel
        self.ax = rpanel.figure.add_subplot(111)

        hbox.Add(lpanel, proportion=0, flag=wx.EXPAND | wx.ALIGN_TOP)
        hbox.Add(gpanel, proportion=1, flag=wx.EXPAND)
        hbox.Add(rpanel, proportion=1, flag=wx.EXPAND)

        lsizer = wx.GridSizer(vgap=1, hgap=2, cols=2)
        lpanel.SetSizer(lsizer)
        self.entries = {}
        for key, emin, emax, val in [('pop', 1, 20 * nfparams, 2 * nfparams),
                                     ('samples', 1000, 10000000, 10000),
                                     ('burn', 0, 10000, 200)]:
            lsizer.Add(wx.StaticText(lpanel, label='%s:' % key),
                       flag=wx.FIXED_MINSIZE)
            self.entries[key] = wx.SpinCtrl(lpanel,
                                            wx.ID_ANY,
                                            min=emin,
                                            max=emax,
                                            value=str(val))
            lsizer.Add(self.entries[key], flag=wx.FIXED_MINSIZE)

        lsizer.AddStretchSpacer(10)
        but = wx.Button(self, label='Run Analysis...')
        vbox.Add(but)
        vbox.Add(self.ptxt, proportion=0, flag=wx.EXPAND)
        vbox.Add(self.pbar, proportion=0, flag=wx.EXPAND)

        self.Bind(wx.EVT_BUTTON, self.OnRunAnalysis, but)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.model = model
        self.thread = None

        psize = parent.GetSize()
        self.SetSize(int(psize.GetWidth() * 0.75),
                     int(psize.GetHeight() * 0.75))

    def OnRunAnalysis(self, event):
        if self.thread is not None:
            return
        self.thread = threading.Thread(target=self.run_bumps)
        self.thread.start()

    def run_bumps(self):
        self.bproblem = self.model.bumps_problem()
        mon = ProgressMonitor(self.bproblem, self.pbar, self.ptxt)
        pop = self.entries['pop'].GetValue()
        burn = self.entries['burn'].GetValue()
        samples = self.entries['samples'].GetValue()
        self.pbar.SetRange(
            int(samples / (len(self.bproblem.model_parameters()) * pop)) +
            burn)

        res = self.model.bumps_fit(method='dream',
                                   pop=pop,
                                   samples=samples,
                                   burn=burn,
                                   thin=1,
                                   alpha=0,
                                   outliers='none',
                                   trim=False,
                                   monitors=[mon],
                                   problem=self.bproblem)
        self._res = res
        wx.CallAfter(self.display_bumps)

    def display_bumps(self):
        self.thread.join(timeout=5.0)
        self.thread = None
        self.pbar.SetValue(0)

        res = self._res
        self.draw = res.state.draw()
        self.abs_cov = res.cov
        self.rel_cov = res.cov / res.dx[:, newaxis] / res.dx[newaxis, :]
        rel_max = [0, 1, abs(self.rel_cov[0, 1])]
        if self.normalize_checkbox.IsChecked():
            display_cov = self.rel_cov
            fmt = "%.6f"
        else:
            display_cov = self.abs_cov
            fmt = "%.4g"
        self.grid.SetRowLabelValue(0, 'Value/Error:')
        for i, ci in enumerate(self.rel_cov):
            self.grid.SetColLabelValue(i, self.draw.labels[i])
            self.grid.SetRowLabelValue(i + 1, self.draw.labels[i])
            self.grid.SetCellValue(0, i, "%.8g\n%.4g" % (res.x[i], res.dx[i]))
            self.grid.SetCellAlignment(0, i, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
            self.grid.SetReadOnly(0, i)
            self.grid.SetCellBackgroundColour(0, i, "#cccccc")
            for j, cj in enumerate(ci):
                self.grid.SetCellValue(i + 1, j, fmt % display_cov[i, j])
                self.grid.SetReadOnly(i + 1, j)
                self.grid.SetCellAlignment(i + 1, j, wx.ALIGN_CENTRE,
                                           wx.ALIGN_CENTRE)
                if i == j:
                    self.grid.SetCellBackgroundColour(i + 1, j, "#888888")
                elif abs(cj) > 0.4:
                    self.grid.SetCellBackgroundColour(i + 1, j, "#ffcccc")
                elif abs(cj) > 0.3:
                    self.grid.SetCellBackgroundColour(i + 1, j, "#ffdddd")
                elif abs(cj) > 0.2:
                    self.grid.SetCellBackgroundColour(i + 1, j, "#ffeeee")
                if i != j and abs(cj) > rel_max[2]:
                    rel_max = [min(i, j), max(i, j), abs(cj)]
        self.hists = _hists(self.draw.points.T, bins=50)

        fig = self.plot_panel.figure
        fig.clear()
        ax = fig.add_subplot(111)
        data, x, y = self.hists[(rel_max[0], rel_max[1])]
        vmin, vmax = data[data > 0].min(), data.max()
        ax.pcolorfast(y,
                      x,
                      maximum(vmin, data),
                      norm=LogNorm(vmin, vmax),
                      cmap='inferno')
        ax.set_xlabel(self.draw.labels[rel_max[1]])
        ax.set_ylabel(self.draw.labels[rel_max[0]])
        self.plot_panel.flush_plot()

        # add analysis data do model for later storange in export header
        exdict = {}
        exdict['library'] = 'bumps'
        exdict['version'] = bumps_version
        exdict['settings'] = dict(pop=self.entries['pop'].GetValue(),
                                  burn=self.entries['burn'].GetValue(),
                                  samples=self.entries['samples'].GetValue())
        exdict['parameters'] = [
            dict(name=li,
                 value=float(xi),
                 error=float(dxi),
                 cross_correlations=dict(
                     (self.draw.labels[j], float(res.cov[i, j]))
                     for j in range(len(res.x))))
            for i, (li, xi,
                    dxi) in enumerate(zip(self.draw.labels, res.x, res.dx))
        ]
        self.model.extra_analysis['statistics_mcmc'] = exdict

    def OnToggleNormalize(self, evt):
        if self.rel_cov is None:
            evt.Skip()
            return
        if self.normalize_checkbox.IsChecked():
            display_cov = self.rel_cov
            fmt = "%.6f"
        else:
            display_cov = self.abs_cov
            fmt = "%.4g"
        for i, ci in enumerate(self.rel_cov):
            for j, cj in enumerate(ci):
                self.grid.SetCellValue(i + 1, j, fmt % display_cov[i, j])

    def OnSelectCell(self, evt):
        i, j = evt.GetCol(), evt.GetRow() - 1
        if i == j or j == -1:
            return
        elif i > j:
            itmp = i
            i = j
            j = itmp

        fig = self.plot_panel.figure
        fig.clear()
        ax = fig.add_subplot(111)
        data, x, y = self.hists[(i, j)]
        vmin, vmax = data[data > 0].min(), data.max()
        ax.pcolorfast(y,
                      x,
                      maximum(vmin, data),
                      norm=LogNorm(vmin, vmax),
                      cmap='inferno')
        ax.set_xlabel(self.draw.labels[j])
        ax.set_ylabel(self.draw.labels[i])
        self.plot_panel.flush_plot()

    def OnClose(self, event):
        if self.thread is not None and self.thread.is_alive():
            # a running bumps simulation can't be interrupted from other thread, stop window from closing
            self.ptxt.SetLabel("Simulation running")
            event.Veto()
            return
        event.Skip()
Пример #20
0
class myPanel(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)

        # Top Sizer
        topSizer = wx.BoxSizer(wx.VERTICAL)

        # Input Label
        labelSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.inputLabel = wx.StaticText(self, -1, data.enterPadyamLabel,
                                        wx.Point(40, 20), wx.Size(720, 20))
        self.increaseFontSize(self.inputLabel, 1.5)
        labelSizer.Add(self.inputLabel, 1, wx.EXPAND | wx.ALL, 5)
        topSizer.Add(labelSizer, 0, wx.ALIGN_LEFT)

        # Input Multiline TextCtrl
        self.input = wx.TextCtrl(self, 5, '', wx.Point(40, 50),
                                 wx.Size(720, 140),
                                 wx.TE_MULTILINE | wx.TE_DONTWRAP)
        self.increaseFontSize(self.input, 1.5)
        topSizer.Add(self.input, 1, wx.EXPAND | wx.ALL, 5)

        # Output Label
        labelSizer1 = wx.BoxSizer(wx.HORIZONTAL)
        self.outputLabel = wx.StaticText(self, -1, data.seeResultsHereLabel,
                                         wx.Point(40, 20), wx.Size(720, 20))
        self.increaseFontSize(self.outputLabel, 1.5)
        labelSizer1.Add(self.outputLabel, 1, wx.EXPAND | wx.ALL, 5)
        topSizer.Add(labelSizer1, 0, wx.ALIGN_LEFT)

        # Output Multiline Grid
        self.output = Grid(self, 6, wx.Point(40, 210), wx.Size(790, 140),
                           wx.TE_MULTILINE | wx.TE_READONLY)
        self.output.SetDefaultRowSize(25)
        self.output.SetDefaultColSize(50)
        self.output.SetRowLabelSize(0)
        self.output.SetColLabelSize(0)
        self.output.CreateGrid(10, 30)
        self.output.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.evtOnCellSelected)
        topSizer.Add(self.output, 1, wx.EXPAND | wx.ALL, 5)

        # Control Sizer
        controlSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Radio Box
        self.radioList = [data.findVruthamLabel, data.checkVruthamLabel]
        self.rb = wx.RadioBox(self, 50, data.whatToDoLabel, wx.Point(40, 375),
                              wx.Size(250, 90), self.radioList, 3,
                              wx.RA_SPECIFY_ROWS)
        self.increaseFontSize(self.rb, 1.5)
        controlSizer.Add(self.rb, 0, wx.ALL, 10)
        wx.EVT_RADIOBOX(self, 50, self.evtRadioBox)

        # Combobox
        self.vruthamList = data.vruthamNameList()
        self.vruthamCombo = wx.ComboBox(self, 30, data.selectVruthamLabel,
                                        wx.Point(420, 390), wx.Size(250, -1),
                                        self.vruthamList,
                                        wx.CB_DROPDOWN | wx.CB_READONLY)
        self.increaseFontSize(self.vruthamCombo, 1.5)
        controlSizer.Add(self.vruthamCombo, 0, wx.ALIGN_CENTER)
        wx.EVT_COMBOBOX(self, 30, self.evtComboBox)
        self.vruthamCombo.Enable(0)

        # Status TextCtrl
        self.status = wx.TextCtrl(self, 5, '', wx.DefaultPosition,
                                  wx.Size(250, 80),
                                  wx.TE_MULTILINE | wx.TE_READONLY)
        self.increaseFontSize(self.status, 1.5)
        self.status.SetBackgroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_SCROLLBAR))
        controlSizer.Add(self.status, 0, wx.EXPAND | wx.ALL, 15)

        topSizer.Add(controlSizer, 0, wx.ALIGN_CENTER)

        # Button Sizer
        buttonSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Buttons
        self.goButton = wx.Button(self, 10, data.findLabel, wx.Point(379, 470),
                                  wx.Size(117, 35))
        self.increaseFontSize(self.goButton, 1.5)
        self.increaseFontWeight(self.goButton)
        wx.EVT_BUTTON(self, 10, self.goClick)
        buttonSizer.Add(self.goButton, 0, wx.ALL, 10)

        self.clearButton = wx.Button(self, 11, data.clearLabel,
                                     wx.Point(506, 470), wx.Size(117, 35))
        self.increaseFontSize(self.clearButton, 1.5)
        self.increaseFontWeight(self.clearButton)
        wx.EVT_BUTTON(self, 11, self.clearClick)
        buttonSizer.Add(self.clearButton, 0, wx.ALL, 10)

        self.closeButton = wx.Button(self, 12, data.closeLabel,
                                     wx.Point(633, 470), wx.Size(117, 35))
        self.increaseFontSize(self.closeButton, 1.5)
        self.increaseFontWeight(self.closeButton)
        wx.EVT_BUTTON(self, 12, self.closeClick)
        buttonSizer.Add(self.closeButton, 0, wx.ALL, 10)

        topSizer.Add(buttonSizer, 0, wx.ALIGN_CENTER)
        self.SetSizer(topSizer)
        topSizer.SetSizeHints(self)

        # Initialize Variables
        self.inVruthamName = ''
        self.checkVruthamFlg = 0
        self.checkFlgSet = 0
        self.dictErrors = {}

    def displayStatus(self, row, col):
        self.status.Clear()
        if self.output.GetNumberRows() <= 0:
            return
        if self.output.GetNumberCols() <= 0:
            return
        if self.output.GetCellValue(row, col) == '':
            return
        if self.checkFlgSet == 1:
            if self.dictErrors.has_key((row, col)):
                self.status.AppendText(self.dictErrors[(row, col)])
            elif self.output.GetCellValue(row, col) == data.rightLabel:
                self.status.AppendText(data.thisLineIsCorrectLabel)
            elif self.output.GetCellValue(row, col) == data.wrongLabel:
                self.status.AppendText(data.thisLineIsWrongLabel)
            else:
                if row == 0:
                    self.status.AppendText(data.syllableCountLabel + ' ' +
                                           self.output.GetCellValue(row, col))
                else:
                    self.status.AppendText(data.thisIsCorrectLabel)
        else:
            if row == 0:
                self.status.AppendText(self.output.GetCellValue(row, col))
            else:
                if col == 0:
                    self.status.AppendText(data.slokamLabel + ' ' +
                                           self.output.GetCellValue(row, col))
                elif col == 1:
                    self.status.AppendText(data.lineLabel + ' ' +
                                           self.output.GetCellValue(row, col))
                elif col == 2:
                    if self.output.GetCellValue(row,
                                                col) != data.iDontKnowLabel:
                        if self.dictErrors.has_key((row, col)):
                            self.status.AppendText(
                                data.lineVruthamGanangalLabel + ' ' +
                                self.output.GetCellValue(row, col) + ', ' +
                                data.yathiBhangamLabel)
                        else:
                            self.status.AppendText(
                                data.lineVruthamGanangalLabel + ' ' +
                                self.output.GetCellValue(row, col))
                    else:
                        self.status.AppendText(data.dontKnowVruthamLabel)
                else:
                    if self.output.GetCellValue(row,
                                                col) != data.iDontKnowLabel:
                        if self.dictErrors.has_key((row, col)):
                            self.status.AppendText(
                                data.slokamsVruthamLabel + ' ' +
                                self.output.GetCellValue(row, col) + ', ' +
                                data.yathiBhangamLabel)
                        else:
                            self.status.AppendText(
                                data.slokamsVruthamLabel + ' ' +
                                self.output.GetCellValue(row, col))
                    else:
                        self.status.AppendText(data.dontKnowVruthamLabel)

    def evtOnCellSelected(self, event):
        eventObject = event.GetEventObject()
        row = event.GetRow()
        col = event.GetCol()
        self.displayStatus(row, col)
        event.Skip()

    def evtRadioBox(self, event):
        if (event.GetInt() == 1):
            self.vruthamCombo.Enable(1)
            self.goButton.SetLabel(data.checkLabel)
            self.checkVruthamFlg = 1
        else:
            self.vruthamCombo.Enable(0)
            self.goButton.SetLabel(data.findLabel)
            self.checkVruthamFlg = 0

    def giveCell(self, row=0, col=0):
        if self.output.GetNumberCols() < col + 1:
            self.output.AppendCols(col + 1 - self.output.GetNumberCols())
        if self.output.GetNumberRows() < row + 1:
            self.output.AppendRows(row + 1 - self.output.GetNumberRows())

    def increaseFontSize(self, text, size):
        Font = text.GetFont()
        Font.SetPointSize(Font.GetPointSize() * size)
        text.SetFont(Font)

    def increaseFontWeight(self, text):
        Font = text.GetFont()
        Font.SetWeight(wx.FONTWEIGHT_BOLD)
        text.SetFont(Font)

    def increaseCellFontSize(self, row, col):
        Font = self.output.GetDefaultCellFont()
        Font.SetPointSize(Font.GetPointSize() * 1.5)
        self.output.SetCellFont(row, col, Font)

    def increaseCellFontWeight(self, row, col):
        Font = self.output.GetCellFont(row, col)
        Font.SetWeight(wx.FONTWEIGHT_BOLD)
        self.output.SetCellFont(row, col, Font)

    def evtComboBox(self, event):
        self.inVruthamName = event.GetString()

    def splitIntoLines(self, errLocs):
        errLocLines = []
        lineList = []
        for i in errLocs:
            if i[0] == (-1, -1):
                lineList.append(i)
                errLocLines.append(lineList)
                lineList = []
            else:
                lineList.append(i)
        errLocLines.append([((-1, -1), 'y')])
        return errLocLines

    def highLightErrors(self):
        # Print Syllable numbers and Lakshanam
        lakshanamStr = data.getVruthamLakshanam(self.inVruthamName)
        incrRow = 0
        incrCol = 1
        self.ardhaVishamaVrutham = 'n'
        lakshanamLines = lakshanamStr.split('|')
        if lakshanamLines[0] == 'ANUSHTUP':
            lakshanamLines = '        '
            anushtupVrutham = 'y'
            for i in lakshanamLines:
                self.giveCell(incrRow, incrCol)
                self.output.SetCellValue(0, incrCol, str(incrCol))
                self.increaseCellFontWeight(0, incrCol)
                self.output.SetCellAlignment(0, incrCol, wx.ALIGN_CENTRE,
                                             wx.ALIGN_CENTRE)
                self.output.SetCellBackgroundColour(
                    0, incrCol, wx.TheColourDatabase.Find('LIGHT BLUE'))
                incrCol = incrCol + 1
            # Display Ganam Grouping
            incrRow += 1
            incrCol = 1
            self.giveCell(incrRow, incrCol)
            ganamColour1 = wx.Colour(166, 166, 166)
            ganamColour2 = wx.Colour(200, 200, 200)
            self.output.SetCellBackgroundColour(incrRow, incrCol, ganamColour1)
            self.output.SetCellBackgroundColour(incrRow, incrCol + 1,
                                                ganamColour2)
            self.output.SetCellBackgroundColour(incrRow, incrCol + 2,
                                                ganamColour2)
            self.output.SetCellBackgroundColour(incrRow, incrCol + 3,
                                                ganamColour2)
            self.output.SetCellBackgroundColour(incrRow, incrCol + 4,
                                                ganamColour1)
            self.output.SetCellBackgroundColour(incrRow, incrCol + 5,
                                                ganamColour1)
            self.output.SetCellBackgroundColour(incrRow, incrCol + 6,
                                                ganamColour1)
            self.output.SetCellBackgroundColour(incrRow, incrCol + 7,
                                                ganamColour2)
        else:
            if lakshanamLines[0] == 'AV':
                self.ardhaVishamaVrutham = 'y'
                lakshanamLines = lakshanamLines[1:len(lakshanamLines)]
            for lakshanam in lakshanamLines:
                incrRow = incrRow + 1
                ganamCount = 1
                ganamStr = ''
                ganam = ''
                ganamColour1 = wx.Colour(166, 166, 166)
                ganamColour2 = wx.Colour(200, 200, 200)
                curGanamColour = ganamColour1
                for i in lakshanam:
                    self.giveCell(incrRow, incrCol)
                    self.output.SetCellValue(0, incrCol, str(incrCol))
                    self.increaseCellFontWeight(0, incrCol)
                    self.output.SetCellAlignment(0, incrCol, wx.ALIGN_CENTRE,
                                                 wx.ALIGN_CENTRE)
                    self.output.SetCellBackgroundColour(
                        0, incrCol, wx.TheColourDatabase.Find('LIGHT BLUE'))
                    self.output.SetCellValue(incrRow, incrCol, i)
                    self.increaseCellFontWeight(incrRow, incrCol)
                    self.output.SetCellAlignment(incrRow, incrCol,
                                                 wx.ALIGN_CENTRE,
                                                 wx.ALIGN_CENTRE)
                    self.output.SetCellBackgroundColour(
                        incrRow, incrCol,
                        wx.TheColourDatabase.Find('LIGHT BLUE'))
                    # Display Ganam Grouping
                    ganamStr += i
                    if incrCol % 3 == 0:
                        if data.ganamDict.has_key(ganamStr):
                            ganam = data.ganamDict[ganamStr]
                            self.dictErrors[(
                                incrRow,
                                incrCol - 2)] = ganam + ' ' + data.ganamLabel
                            self.dictErrors[(
                                incrRow,
                                incrCol - 1)] = ganam + ' ' + data.ganamLabel
                            self.dictErrors[(
                                incrRow,
                                incrCol)] = ganam + ' ' + data.ganamLabel
                            ganamStr = ''
                            self.output.SetCellBackgroundColour(
                                incrRow, incrCol - 2, curGanamColour)
                            self.output.SetCellBackgroundColour(
                                incrRow, incrCol - 1, curGanamColour)
                            self.output.SetCellBackgroundColour(
                                incrRow, incrCol, curGanamColour)
                            if curGanamColour == ganamColour1:
                                curGanamColour = ganamColour2
                            else:
                                curGanamColour = ganamColour1
                        ganamCount += 1
                    elif ganamCount > len(lakshanam) / 3:
                        if ganamStr == '-':
                            self.dictErrors[(incrRow,
                                             incrCol)] = data.guruLabel
                        else:
                            self.dictErrors[(incrRow,
                                             incrCol)] = data.laghuLabel
                        ganamStr = ''
                        self.output.SetCellBackgroundColour(
                            incrRow, incrCol, curGanamColour)
                        if curGanamColour == ganamColour1:
                            curGanamColour = ganamColour2
                        else:
                            curGanamColour = ganamColour1
                        ganamCount += 1
                    incrCol = incrCol + 1
                incrCol = 1
        gridRow = incrRow + 1
        gridCol = 1

        # Print Padyam
        lineNum = 0
        lakshanam = ''
        bgColour = wx.Colour(255, 212, 160)
        errLocLines = self.splitIntoLines(self.errLocs)
        for oneErrLocLine in errLocLines:
            if oneErrLocLine == [((-1, -1), 'y')]:
                if self.ardhaVishamaVrutham == 'y':
                    if lineNum != 0:
                        for i in range(0, 4 - lineNum):
                            gridCol = 1
                            self.giveCell(gridRow, gridCol)
                            self.output.SetCellValue(gridRow, 0,
                                                     data.wrongLabel)
                            self.increaseCellFontSize(gridRow, 0)
                            self.increaseCellFontWeight(gridRow, 0)
                            self.output.SetCellBackgroundColour(
                                gridRow, 0, wx.RED)
                            lakshanam = lakshanamLines[lineNum + i]
                            while gridCol <= len(lakshanam):
                                self.output.SetCellBackgroundColour(
                                    gridRow, gridCol, wx.RED)
                                self.dictErrors[(gridRow,
                                                 gridCol)] = data.emptySylLabel
                                gridCol = gridCol + 1
                            gridRow = gridRow + 1
                lineNum = 0
                gridCol = 1
                if self.output.GetCellValue(gridRow - 1, 0) != '':
                    gridRow = gridRow + 1
                    self.giveCell(gridRow, gridCol)
                continue
            if self.ardhaVishamaVrutham == 'y':
                lakshanam = lakshanamLines[lineNum % 4]
            else:
                lakshanam = lakshanamStr
            if lineNum == 4:
                lineNum = 1
                gridRow = gridRow + 1
                self.giveCell(gridRow, gridCol)
            else:
                lineNum = lineNum + 1
            if lineNum == 1:
                if bgColour.Green() == 212:
                    bgColour = wx.Colour(255, 255, 160)
                else:
                    bgColour = wx.Colour(255, 212, 160)
            yathiInPrevChar = 0
            for i in oneErrLocLine:
                if i[0] == (-1, -1):
                    yathiInPrevChar = 0
                    while gridCol > 1 and gridCol <= len(lakshanam):
                        self.output.SetCellValue(gridRow, 0, data.wrongLabel)
                        self.increaseCellFontSize(gridRow, 0)
                        self.increaseCellFontWeight(gridRow, 0)
                        self.output.SetCellBackgroundColour(gridRow, 0, wx.RED)
                        self.output.SetCellBackgroundColour(
                            gridRow, gridCol, wx.RED)
                        self.dictErrors[(gridRow,
                                         gridCol)] = data.emptySylLabel
                        gridCol = gridCol + 1
                    if gridCol == 1:
                        self.giveCell(gridRow, gridCol)
                        self.output.SetCellValue(gridRow, 0, '')
                        self.output.SetCellBackgroundColour(
                            gridRow, 0, wx.WHITE)
                    gridRow = gridRow + 1
                    gridCol = 1
                    continue
                if gridCol == 1:
                    self.giveCell(gridRow, gridCol)
                    self.output.SetCellValue(gridRow, 0, data.rightLabel)
                    self.increaseCellFontSize(gridRow, 0)
                    self.increaseCellFontWeight(gridRow, 0)
                    self.output.SetCellBackgroundColour(gridRow, 0, wx.GREEN)
                self.giveCell(gridRow, gridCol)
                if i[1] == 'n':
                    yathiInPrevChar = 0
                    self.output.SetCellValue(
                        gridRow, gridCol,
                        self.input.GetValue()[i[0][0]:i[0][1] + 1])
                    self.output.SetCellBackgroundColour(
                        gridRow, gridCol, wx.RED)
                    if gridCol - 1 < len(lakshanam):
                        if lakshanam[gridCol - 1] == '-':
                            self.dictErrors[(
                                gridRow,
                                gridCol)] = data.wronglyPlacedLaghuLabel
                        else:
                            self.dictErrors[(
                                gridRow,
                                gridCol)] = data.wronglyPlacedGuruLabel
                    else:
                        self.dictErrors[(gridRow,
                                         gridCol)] = data.extraSylLabel
                    self.output.SetCellValue(gridRow, 0, data.wrongLabel)
                    self.increaseCellFontSize(gridRow, 0)
                    self.increaseCellFontWeight(gridRow, 0)
                    self.output.SetCellBackgroundColour(gridRow, 0, wx.RED)
                elif i[1] == 'g':
                    self.output.SetCellValue(
                        gridRow, gridCol,
                        self.input.GetValue()[i[0][0]:i[0][1] + 1])
                    self.output.SetCellBackgroundColour(
                        gridRow, gridCol, wx.RED)
                    self.dictErrors[(gridRow, gridCol)] = data.wrongGanamLabel
                    self.output.SetCellValue(gridRow, 0, data.wrongLabel)
                    self.increaseCellFontSize(gridRow, 0)
                    self.increaseCellFontWeight(gridRow, 0)
                    self.output.SetCellBackgroundColour(gridRow, 0, wx.RED)
                else:
                    self.output.SetCellValue(
                        gridRow, gridCol,
                        self.input.GetValue()[i[0][0]:i[0][1] + 1])
                    self.output.SetCellBackgroundColour(
                        gridRow, gridCol, bgColour)
                    if yathiInPrevChar == 1:
                        yathiInPrevChar = 0
                        if ' ' not in self.input.GetValue()[yathiStartPos:i[0][0]] and \
                         '/' not in self.input.GetValue()[yathiStartPos:i[0][0]]:
                            self.output.SetCellValue(gridRow, 0,
                                                     data.wrongLabel)
                            self.increaseCellFontSize(gridRow, 0)
                            self.increaseCellFontWeight(gridRow, 0)
                            self.output.SetCellBackgroundColour(
                                gridRow, 0, wx.RED)
                            self.output.SetCellBackgroundColour(
                                gridRow, gridCol, wx.RED)
                            self.dictErrors[(
                                gridRow, gridCol)] = data.yathiRequiredLabel
                    if i[1] == 't':
                        yathiInPrevChar = 1
                        yathiStartPos = i[0][1] + 1
                self.increaseCellFontSize(gridRow, gridCol)
                gridCol = gridCol + 1
        while self.output.GetCellValue(gridRow, 0) == '':
            self.output.DeleteRows(gridRow, 1)
            gridRow -= 1
        self.output.SetGridCursor(0, 0)

    def printVruthamNames(self, vruthamNames):
        gRows, gCols = 0, 0
        # Print Header
        self.giveCell(gRows, 3)
        self.output.SetCellValue(0, 0, data.slokamLabel)
        self.increaseCellFontSize(0, 0)
        self.increaseCellFontWeight(0, 0)
        self.output.SetCellAlignment(0, 0, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.output.SetCellBackgroundColour(
            0, 0, wx.TheColourDatabase.Find('LIGHT BLUE'))
        self.output.SetCellValue(0, 1, data.lineLabel)
        self.increaseCellFontSize(0, 1)
        self.increaseCellFontWeight(0, 1)
        self.output.SetCellAlignment(0, 1, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.output.SetCellBackgroundColour(
            0, 1, wx.TheColourDatabase.Find('LIGHT BLUE'))
        self.output.SetCellValue(0, 2, data.lineVruthamGanangalLabel)
        self.increaseCellFontSize(0, 2)
        self.increaseCellFontWeight(0, 2)
        self.output.SetCellAlignment(0, 2, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.output.SetCellBackgroundColour(
            0, 2, wx.TheColourDatabase.Find('LIGHT BLUE'))
        self.output.SetCellValue(0, 3, data.slokaVruthamLabel)
        self.increaseCellFontSize(0, 3)
        self.increaseCellFontWeight(0, 3)
        self.output.SetCellAlignment(0, 3, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        self.output.SetCellBackgroundColour(
            0, 3, wx.TheColourDatabase.Find('LIGHT BLUE'))
        gRows = gRows + 1
        yathiBhangamSlokam = -1
        for i in vruthamNames:
            yathiBhangam = 'n'
            self.giveCell(gRows, 1)
            self.output.SetDefaultColSize(190, 1)
            self.output.SetCellValue(gRows, 0, i[0])
            self.increaseCellFontWeight(gRows, 0)
            self.output.SetCellAlignment(gRows, 0, wx.ALIGN_CENTRE,
                                         wx.ALIGN_CENTRE)
            self.output.SetCellValue(gRows, 1, i[1])
            self.increaseCellFontWeight(gRows, 1)
            self.output.SetCellAlignment(gRows, 1, wx.ALIGN_CENTRE,
                                         wx.ALIGN_CENTRE)
            if i[2] != -1:
                self.output.SetCellValue(gRows, 2, data.vruthamTable[i[2]][1])
            else:
                self.output.SetCellValue(gRows, 2, data.iDontKnowLabel)
            self.increaseCellFontSize(gRows, 2)
            self.increaseCellFontWeight(gRows, 2)
            self.output.SetCellAlignment(gRows, 2, wx.ALIGN_CENTRE,
                                         wx.ALIGN_CENTRE)
            if i[3] == -1:
                self.output.SetCellValue(gRows, 3, data.iDontKnowLabel)
            elif i[3] == -2:
                self.output.SetCellValue(gRows, 3, '')
            else:
                self.output.SetCellValue(gRows, 3, data.vruthamTable[i[3]][1])
            self.increaseCellFontSize(gRows, 3)
            self.increaseCellFontWeight(gRows, 3)
            self.output.SetCellAlignment(gRows, 3, wx.ALIGN_CENTRE,
                                         wx.ALIGN_CENTRE)
            if int(i[0]) % 2 != 0:
                bgColour = wx.Colour(255, 255, 160)  # HTML value ffffa0
            else:
                bgColour = wx.Colour(255, 212, 160)  # HTML value ffd4a0
            self.output.SetCellBackgroundColour(gRows, 0, bgColour)
            self.output.SetCellBackgroundColour(gRows, 1, bgColour)
            if i[2] != -1:
                self.output.SetCellBackgroundColour(gRows, 2, bgColour)
                if i[4] == 'n':
                    self.output.SetCellBackgroundColour(gRows, 2, wx.RED)
                    self.dictErrors[(gRows, 2)] = data.yathiBhangamLabel
                    yathiBhangamSlokam = i[0]
                if i[0] == yathiBhangamSlokam:
                    yathiBhangam = 'y'
            else:
                self.output.SetCellBackgroundColour(gRows, 2, wx.RED)
            if i[3] != -1:
                self.output.SetCellBackgroundColour(gRows, 3, bgColour)
                if yathiBhangam == 'y':
                    curSlokam = self.output.GetCellValue(gRows, 0)
                    for i in range(0, 4):
                        if self.output.GetCellValue(gRows - i, 0) != curSlokam:
                            break
                        self.output.SetCellBackgroundColour(
                            gRows - i, 3, wx.RED)
                        self.dictErrors[(gRows - i,
                                         3)] = data.yathiBhangamLabel
            else:
                curSlokam = self.output.GetCellValue(gRows, 0)
                for i in range(0, 4):
                    if self.output.GetCellValue(gRows - i, 0) != curSlokam:
                        break
                    self.output.SetCellBackgroundColour(gRows - i, 3, wx.RED)
            gRows = gRows + 1
        self.output.AutoSizeColumns()

    def goClick(self, event):
        self.checkFlgSet = 0
        if self.output.GetNumberRows() != 0:
            self.dictErrors = {}
            self.output.DeleteRows(0, self.output.GetNumberRows())
            self.output.DeleteCols(0, self.output.GetNumberCols())
        self.output.SetDefaultRowSize(25, 1)
        self.output.SetDefaultColSize(50, 1)
        if self.input.GetValue() == '':
            self.output.SetDefaultColSize(790, 1)
            self.giveCell()
            self.output.SetCellValue(0, 0, data.noPadyamGivenLabel)
            self.increaseCellFontSize(0, 0)
            return
        if filter(lambda x: x > u'\u0d00' and x < u'\u0d65',
                  self.input.GetValue()) == '':
            self.output.SetDefaultColSize(790, 1)
            self.giveCell()
            self.output.SetCellValue(0, 0, data.givePadyamInMalLabel)
            self.increaseCellFontSize(0, 0)
            return
        if self.checkVruthamFlg == 1:
            if self.inVruthamName == '':
                self.output.SetDefaultColSize(790, 1)
                self.giveCell()
                self.output.SetCellValue(0, 0, data.noVruthamGivenLabel)
                self.increaseCellFontSize(0, 0)
                return
            self.checkFlgSet = 1
            self.outVruthamName, self.errLocs = getVrutham(
                self.input.GetValue(), self.inVruthamName)
            self.highLightErrors()
        else:
            self.checkFlgSet = 0
            self.outVruthamName, self.errLocs = getVrutham(
                self.input.GetValue(), '')
            self.printVruthamNames(self.outVruthamName)

    def clearClick(self, event):
        self.status.Clear()
        if self.output.GetNumberRows() != 0:
            self.dictErrors = {}
            self.output.DeleteRows(0, self.output.GetNumberRows())
            self.output.DeleteCols(0, self.output.GetNumberCols())
        self.output.SetDefaultRowSize(25, 1)
        self.output.SetDefaultColSize(50, 1)
        if self.input.GetValue() != '':
            diag = wx.MessageDialog(
                self, data.clearAreYouSureLabel, data.pleaseConfirmLabel,
                wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
            if diag.ShowModal() == wx.ID_YES:
                self.input.Clear()

    def closeClick(self, event):
        dlg = wx.MessageDialog(self, data.quitAreYouSureLabel,
                               data.pleaseConfirmLabel,
                               wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
        if dlg.ShowModal() == wx.ID_YES:
            self.GetParent().Close(True)
Пример #21
0
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)

        # Top Sizer
        topSizer = wx.BoxSizer(wx.VERTICAL)

        # Input Label
        labelSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.inputLabel = wx.StaticText(self, -1, data.enterPadyamLabel,
                                        wx.Point(40, 20), wx.Size(720, 20))
        self.increaseFontSize(self.inputLabel, 1.5)
        labelSizer.Add(self.inputLabel, 1, wx.EXPAND | wx.ALL, 5)
        topSizer.Add(labelSizer, 0, wx.ALIGN_LEFT)

        # Input Multiline TextCtrl
        self.input = wx.TextCtrl(self, 5, '', wx.Point(40, 50),
                                 wx.Size(720, 140),
                                 wx.TE_MULTILINE | wx.TE_DONTWRAP)
        self.increaseFontSize(self.input, 1.5)
        topSizer.Add(self.input, 1, wx.EXPAND | wx.ALL, 5)

        # Output Label
        labelSizer1 = wx.BoxSizer(wx.HORIZONTAL)
        self.outputLabel = wx.StaticText(self, -1, data.seeResultsHereLabel,
                                         wx.Point(40, 20), wx.Size(720, 20))
        self.increaseFontSize(self.outputLabel, 1.5)
        labelSizer1.Add(self.outputLabel, 1, wx.EXPAND | wx.ALL, 5)
        topSizer.Add(labelSizer1, 0, wx.ALIGN_LEFT)

        # Output Multiline Grid
        self.output = Grid(self, 6, wx.Point(40, 210), wx.Size(790, 140),
                           wx.TE_MULTILINE | wx.TE_READONLY)
        self.output.SetDefaultRowSize(25)
        self.output.SetDefaultColSize(50)
        self.output.SetRowLabelSize(0)
        self.output.SetColLabelSize(0)
        self.output.CreateGrid(10, 30)
        self.output.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.evtOnCellSelected)
        topSizer.Add(self.output, 1, wx.EXPAND | wx.ALL, 5)

        # Control Sizer
        controlSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Radio Box
        self.radioList = [data.findVruthamLabel, data.checkVruthamLabel]
        self.rb = wx.RadioBox(self, 50, data.whatToDoLabel, wx.Point(40, 375),
                              wx.Size(250, 90), self.radioList, 3,
                              wx.RA_SPECIFY_ROWS)
        self.increaseFontSize(self.rb, 1.5)
        controlSizer.Add(self.rb, 0, wx.ALL, 10)
        wx.EVT_RADIOBOX(self, 50, self.evtRadioBox)

        # Combobox
        self.vruthamList = data.vruthamNameList()
        self.vruthamCombo = wx.ComboBox(self, 30, data.selectVruthamLabel,
                                        wx.Point(420, 390), wx.Size(250, -1),
                                        self.vruthamList,
                                        wx.CB_DROPDOWN | wx.CB_READONLY)
        self.increaseFontSize(self.vruthamCombo, 1.5)
        controlSizer.Add(self.vruthamCombo, 0, wx.ALIGN_CENTER)
        wx.EVT_COMBOBOX(self, 30, self.evtComboBox)
        self.vruthamCombo.Enable(0)

        # Status TextCtrl
        self.status = wx.TextCtrl(self, 5, '', wx.DefaultPosition,
                                  wx.Size(250, 80),
                                  wx.TE_MULTILINE | wx.TE_READONLY)
        self.increaseFontSize(self.status, 1.5)
        self.status.SetBackgroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_SCROLLBAR))
        controlSizer.Add(self.status, 0, wx.EXPAND | wx.ALL, 15)

        topSizer.Add(controlSizer, 0, wx.ALIGN_CENTER)

        # Button Sizer
        buttonSizer = wx.BoxSizer(wx.HORIZONTAL)

        # Buttons
        self.goButton = wx.Button(self, 10, data.findLabel, wx.Point(379, 470),
                                  wx.Size(117, 35))
        self.increaseFontSize(self.goButton, 1.5)
        self.increaseFontWeight(self.goButton)
        wx.EVT_BUTTON(self, 10, self.goClick)
        buttonSizer.Add(self.goButton, 0, wx.ALL, 10)

        self.clearButton = wx.Button(self, 11, data.clearLabel,
                                     wx.Point(506, 470), wx.Size(117, 35))
        self.increaseFontSize(self.clearButton, 1.5)
        self.increaseFontWeight(self.clearButton)
        wx.EVT_BUTTON(self, 11, self.clearClick)
        buttonSizer.Add(self.clearButton, 0, wx.ALL, 10)

        self.closeButton = wx.Button(self, 12, data.closeLabel,
                                     wx.Point(633, 470), wx.Size(117, 35))
        self.increaseFontSize(self.closeButton, 1.5)
        self.increaseFontWeight(self.closeButton)
        wx.EVT_BUTTON(self, 12, self.closeClick)
        buttonSizer.Add(self.closeButton, 0, wx.ALL, 10)

        topSizer.Add(buttonSizer, 0, wx.ALIGN_CENTER)
        self.SetSizer(topSizer)
        topSizer.SetSizeHints(self)

        # Initialize Variables
        self.inVruthamName = ''
        self.checkVruthamFlg = 0
        self.checkFlgSet = 0
        self.dictErrors = {}
Пример #22
0
    def __init__(self, parent):
        

        Grid.__init__(self, parent) 
        self.createPlayerGrid()
        self.simplifyGrid()
Пример #23
0
    def __init__(self, parent, title, processed_payments, output_file_loc):
        wx.Frame.__init__(self, parent, title=title,
                          size=GUIUtils.calculate_window_size())

        self.margin_to_frame_edge = 25
        self.column_width = len(
            self.get_object_attrs_not_abstract(processed_payments))
        self.processed_payments = processed_payments
        self.attr_column_mapping = {}
        self.output_file_loc = output_file_loc

        self.title_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.title = wx.StaticText(
            self, -1,
            style=wx.ALIGN_CENTER
        )
        self.title.SetLabelMarkup(
            "<span size=\"xx-large\" weight=\"bold\">"
            "Checking Window</span>")
        self.title_sizer.Add(self.title, 1, wx.EXPAND,
                             self.margin_to_frame_edge)
        self.title_sizer.SetMinSize(100, 50)

        # Build up the grid to display the data
        self.grid_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.grid = Grid(self, -1)

        self.grid.CreateGrid(len(processed_payments), self.column_width)
        self.grid_sizer.Add(self.grid, wx.EXPAND)

        for col_id, attribute in enumerate(self.get_object_attrs_not_abstract(
                processed_payments)):
            self.grid.SetColLabelValue(col_id, processed_payments[0].__dict__[attribute].name)
            self.attr_column_mapping[attribute] = \
                (col_id, processed_payments[0].__dict__[attribute].name)

        for row_id, payment in enumerate(processed_payments):
            for col_id, attribute in enumerate(self.get_object_attrs_not_abstract(
                    processed_payments)):
                if isinstance(payment.__dict__[attribute].value, datetime):
                    self.grid.SetCellValue(
                        row_id, col_id,
                        payment.__dict__[attribute].value.strftime("%d/%m/%Y"))
                else:
                    self.grid.SetCellValue(
                        row_id, col_id, payment.__dict__[attribute].value)
                if isinstance(payment.__dict__[attribute].value, str) and \
                        re.match(r"X{6,14}", payment.__dict__[attribute].value):
                    for col_col_id, _ in enumerate(self.get_object_attrs_not_abstract(
                    processed_payments)):
                        self.grid.SetCellBackgroundColour(
                            row_id, col_col_id,
                            wx.Colour(238, 210, 2, wx.ALPHA_OPAQUE))
                elif not payment.__dict__[attribute].user_editable:
                    self.grid.SetReadOnly(row_id, col_id)

        self.grid.AutoSize()

        # Create a Confirm Button
        self.confirm_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.confirm_button = wx.Button(self, label="Confirm")
        self.confirm_button.Bind(wx.EVT_BUTTON, self.confirm)
        self.confirm_sizer.Add(self.confirm_button, 1, wx.EXPAND|wx.ALL,
                               self.margin_to_frame_edge)
        self.confirm_sizer.SetMinSize(100, 50)

        # Set up the base sizers

        self.base_sizer = wx.BoxSizer(wx.VERTICAL)
        self.base_sizer.Add(self.title_sizer, 1, wx.EXPAND|wx.ALL,
                            self.margin_to_frame_edge)
        self.base_sizer.Add(self.grid_sizer, 5,
                            wx.EXPAND|wx.LEFT|wx.RIGHT,
                            self.margin_to_frame_edge)
        self.base_sizer.Add(self.confirm_sizer, 0.5 , wx.EXPAND|wx.ALL,
        self.margin_to_frame_edge)
        # Layout sizers
        self.SetSizer(self.base_sizer)
        self.SetAutoLayout(1)
        self.base_sizer.Fit(self)
        self.Show()
Пример #24
0
class CheckingWindow(wx.Frame):

    def __init__(self, parent, title, processed_payments, output_file_loc):
        wx.Frame.__init__(self, parent, title=title,
                          size=GUIUtils.calculate_window_size())

        self.margin_to_frame_edge = 25
        self.column_width = len(
            self.get_object_attrs_not_abstract(processed_payments))
        self.processed_payments = processed_payments
        self.attr_column_mapping = {}
        self.output_file_loc = output_file_loc

        self.title_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.title = wx.StaticText(
            self, -1,
            style=wx.ALIGN_CENTER
        )
        self.title.SetLabelMarkup(
            "<span size=\"xx-large\" weight=\"bold\">"
            "Checking Window</span>")
        self.title_sizer.Add(self.title, 1, wx.EXPAND,
                             self.margin_to_frame_edge)
        self.title_sizer.SetMinSize(100, 50)

        # Build up the grid to display the data
        self.grid_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.grid = Grid(self, -1)

        self.grid.CreateGrid(len(processed_payments), self.column_width)
        self.grid_sizer.Add(self.grid, wx.EXPAND)

        for col_id, attribute in enumerate(self.get_object_attrs_not_abstract(
                processed_payments)):
            self.grid.SetColLabelValue(col_id, processed_payments[0].__dict__[attribute].name)
            self.attr_column_mapping[attribute] = \
                (col_id, processed_payments[0].__dict__[attribute].name)

        for row_id, payment in enumerate(processed_payments):
            for col_id, attribute in enumerate(self.get_object_attrs_not_abstract(
                    processed_payments)):
                if isinstance(payment.__dict__[attribute].value, datetime):
                    self.grid.SetCellValue(
                        row_id, col_id,
                        payment.__dict__[attribute].value.strftime("%d/%m/%Y"))
                else:
                    self.grid.SetCellValue(
                        row_id, col_id, payment.__dict__[attribute].value)
                if isinstance(payment.__dict__[attribute].value, str) and \
                        re.match(r"X{6,14}", payment.__dict__[attribute].value):
                    for col_col_id, _ in enumerate(self.get_object_attrs_not_abstract(
                    processed_payments)):
                        self.grid.SetCellBackgroundColour(
                            row_id, col_col_id,
                            wx.Colour(238, 210, 2, wx.ALPHA_OPAQUE))
                elif not payment.__dict__[attribute].user_editable:
                    self.grid.SetReadOnly(row_id, col_id)

        self.grid.AutoSize()

        # Create a Confirm Button
        self.confirm_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.confirm_button = wx.Button(self, label="Confirm")
        self.confirm_button.Bind(wx.EVT_BUTTON, self.confirm)
        self.confirm_sizer.Add(self.confirm_button, 1, wx.EXPAND|wx.ALL,
                               self.margin_to_frame_edge)
        self.confirm_sizer.SetMinSize(100, 50)

        # Set up the base sizers

        self.base_sizer = wx.BoxSizer(wx.VERTICAL)
        self.base_sizer.Add(self.title_sizer, 1, wx.EXPAND|wx.ALL,
                            self.margin_to_frame_edge)
        self.base_sizer.Add(self.grid_sizer, 5,
                            wx.EXPAND|wx.LEFT|wx.RIGHT,
                            self.margin_to_frame_edge)
        self.base_sizer.Add(self.confirm_sizer, 0.5 , wx.EXPAND|wx.ALL,
        self.margin_to_frame_edge)
        # Layout sizers
        self.SetSizer(self.base_sizer)
        self.SetAutoLayout(1)
        self.base_sizer.Fit(self)
        self.Show()

    @staticmethod
    def get_object_attrs_not_abstract(processed_payments):
        return sorted([x for x in dir(processed_payments[0]) if
         not x.startswith("_") and
         x in processed_payments[0].__dict__ and
         hasattr(processed_payments[0].__dict__[x], "value") and
         processed_payments[0].__dict__[x].value != ""],
                      key=lambda x: processed_payments[0].__dict__[x].ordinal)

    def confirm(self, _):
        # Go over all the rows and run the validator methods. If one of them fails throw up an error message flagging
        # where the error is
        for row_id, processed_payment in enumerate(self.processed_payments):
            for user_editable_attr in [y for y in
                      self.get_object_attrs_not_abstract(self.processed_payments) if
                      self.processed_payments[0].__dict__[y].user_editable]:
                column_id, _ = \
                    self.attr_column_mapping[user_editable_attr]
                if(not processed_payment.__dict__[user_editable_attr].validator(
                        self.grid.GetCellValue(row_id, column_id))):
                    error_dialog = \
                        MessageDialog(self,
                                      "Data Entered in Column '{}' on Row '{}' - '{}' "
                                      "does not match what was expected. \n"
                                      "Please alter the data and click confirm again.\n\n"
                                      "No data has been altered and no files have been created.".format(
                                          self.attr_column_mapping[user_editable_attr][1],
                                          row_id, self.grid.GetCellValue(row_id, column_id)
                                      ),
                                      "Data Error - Please Recheck the Table",
                                      wx.OK|wx.ICON_ERROR|wx.CENTRE)
                    error_dialog.ShowModal()
                    return
        # After the validity of the data is assured, set the values to the new values and begin the conversion process
        for row_id, processed_payment in enumerate(self.processed_payments):
            for user_editable_attr in [y for y in
                      self.get_object_attrs_not_abstract(self.processed_payments) if
                      self.processed_payments[0].__dict__[y].user_editable]:
                column_id, _ = \
                    self.attr_column_mapping[user_editable_attr]
                if isinstance(processed_payment.__dict__[user_editable_attr].value, datetime):
                    processed_payment.__dict__[user_editable_attr].value = datetime.strptime(
                        self.grid.GetCellValue(row_id, column_id), "%d/%m/%Y")
                else:
                    processed_payment.__dict__[user_editable_attr].value = \
                        self.grid.GetCellValue(row_id, column_id)
        converter = Converter()
        converter.write_output_file(self.output_file_loc,
                                    self.processed_payments)
        self.Close()
Пример #25
0
    def __init__(self, graph, settings):
        wx.Panel.__init__(self, graph)

        self.spectrum = None
        self.graph = graph
        self.settings = settings

        self.measure = None

        self.checked = {Measure.MIN: "",
                        Measure.MAX: "",
                        Measure.AVG: "",
                        Measure.GMEAN: "",
                        Measure.HBW: "",
                        Measure.OBW: ""}

        self.selected = None

        self.SetBackgroundColour('white')

        self.grid = Grid(self)
        self.grid.CreateGrid(3, 19)
        self.grid.EnableEditing(True)
        self.grid.EnableDragGridSize(False)
        self.grid.SetColLabelSize(1)
        self.grid.SetRowLabelSize(1)
        self.grid.SetColMinimalAcceptableWidth(1)
        self.grid.SetColSize(2, 1)
        self.grid.SetColSize(7, 1)
        self.grid.SetColSize(11, 1)
        self.grid.SetColSize(15, 1)
        self.grid.SetMargins(0, wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y))

        for x in range(self.grid.GetNumberRows()):
            self.grid.SetRowLabelValue(x, '')
        for y in range(self.grid.GetNumberCols()):
            self.grid.SetColLabelValue(y, '')

        for row in range(self.grid.GetNumberRows()):
            for col in range(self.grid.GetNumberCols()):
                self.grid.SetReadOnly(row, col, True)

        self.locsDesc = {'F Start': (0, 0),
                         'F End': (1, 0),
                         'F Delta': (2, 0),
                         'P Min': (0, 4),
                         'P Max': (1, 4),
                         'P Delta': (2, 4),
                         'Mean': (0, 9),
                         'GMean': (1, 9),
                         'Flatness': (2, 9),
                         '-3dB Start': (0, 13),
                         '-3dB End': (1, 13),
                         '-3dB Delta': (2, 13),
                         'OBW Start': (0, 17),
                         'OBW End': (1, 17),
                         'OBW Delta': (2, 17)}
        self.__set_descs()

        self.locsCheck = {Measure.MIN: (0, 3), Measure.MAX: (1, 3),
                          Measure.AVG: (0, 8), Measure.GMEAN: (1, 8),
                          Measure.HBW: (0, 12),
                          Measure.OBW: (0, 16)}
        self.__set_check_editor()

        self.locsFreq = [(0, 1), (1, 1)]
        self.__set_freq_editor()

        colour = self.grid.GetBackgroundColour()
        self.grid.SetCellTextColour(2, 3, colour)
        self.grid.SetCellTextColour(2, 8, colour)
        self.grid.SetCellTextColour(1, 12, colour)
        self.grid.SetCellTextColour(2, 12, colour)
        self.grid.SetCellTextColour(1, 16, colour)
        self.grid.SetCellTextColour(2, 16, colour)

        self.__clear_checks()

        self.locsMeasure = {'start': (0, 1), 'end': (1, 1), 'deltaF': (2, 1),
                            'minFP': (0, 5), 'maxFP': (1, 5), 'deltaFP': (2, 5),
                            'minP': (0, 6), 'maxP': (1, 6), 'deltaP': (2, 6),
                            'avg': (0, 10), 'gmean': (1, 10), 'flat': (2, 10),
                            'hbwstart': (0, 14), 'hbwend': (1, 14), 'hbwdelta': (2, 14),
                            'obwstart': (0, 18), 'obwend': (1, 18), 'obwdelta': (2, 18)}

        fontCell = self.grid.GetDefaultCellFont()
        fontSize = fontCell.GetPointSize()
        fontStyle = fontCell.GetStyle()
        fontWeight = fontCell.GetWeight()
        font = wx.Font(fontSize, wx.FONTFAMILY_MODERN, fontStyle,
                       fontWeight)
        dc = wx.WindowDC(self.grid)
        dc.SetFont(font)
        widthMHz = dc.GetTextExtent('###.######')[0] * 1.2
        widthdB = dc.GetTextExtent('-##.##')[0] * 1.2
        for _desc, (_row, col) in self.locsDesc.items():
            self.grid.AutoSizeColumn(col)
        for col in [1, 5, 14, 18]:
            self.grid.SetColSize(col, widthMHz)
            for row in range(self.grid.GetNumberRows()):
                self.grid.SetCellFont(row, col, font)
        for col in [6, 10]:
            self.grid.SetColSize(col, widthdB)
            for row in range(self.grid.GetNumberRows()):
                self.grid.SetCellFont(row, col, font)
        for _desc, (_row, col) in self.locsCheck.items():
            self.grid.AutoSizeColumn(col)

        toolTips = {self.locsMeasure['start']: 'Selection start (MHz)', self.locsMeasure['end']: 'Selection end (MHz)',
                    self.locsMeasure['deltaF']: 'Selection bandwidth (MHz)',
                    self.locsMeasure['minFP']: 'Minimum power location (MHz)',
                    self.locsMeasure['maxFP']: 'Maximum power location (MHz)',
                    self.locsMeasure['deltaFP']: 'Power location difference (MHz)',
                    self.locsMeasure['minP']: 'Minimum power (dB)', self.locsMeasure['maxP']: 'Maximum power (dB)',
                    self.locsMeasure['deltaP']: 'Power difference (dB)', self.locsMeasure['avg']: 'Mean power (dB)',
                    self.locsMeasure['gmean']: 'Geometric mean power (dB)',
                    self.locsMeasure['flat']: 'Spectral flatness',
                    self.locsMeasure['hbwstart']: '-3db start location (MHz)',
                    self.locsMeasure['hbwend']: '-3db end location (MHz)',
                    self.locsMeasure['hbwdelta']: '-3db bandwidth (MHz)',
                    self.locsMeasure['obwstart']: '99% start location (MHz)',
                    self.locsMeasure['obwend']: '99% end location (MHz)',
                    self.locsMeasure['obwdelta']: '99% bandwidth (MHz)'}

        self.toolTips = GridToolTips(self.grid, toolTips)

        self.popupMenu = wx.Menu()
        self.popupMenuCopy = self.popupMenu.Append(wx.ID_ANY, "&Copy",
                                                   "Copy entry")
        self.Bind(wx.EVT_MENU, self.__on_copy, self.popupMenuCopy)

        self.Bind(EVT_GRID_CELL_RIGHT_CLICK, self.__on_popup_menu)
        self.Bind(EVT_GRID_CELL_LEFT_CLICK, self.__on_cell_click)
        if wx.VERSION >= (3, 0, 0, 0):
            self.Bind(EVT_GRID_CELL_CHANGED, self.__on_cell_change)

        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.grid, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT,
                border=10)
        self.SetSizer(box)
Пример #26
0
    def __init__(self, parent):
        Panel.__init__(self, parent)

        grid = Grid(self)

        grid.CreateGrid(0, _TOTAL_COLS)

        grid.HideRowLabels()  # Hide the index column
        grid.EnableGridLines(False)  # Hide grid lines
        grid.DisableDragGridSize(
        )  # Disable resizing of rows/columns by dragging
        grid.DisableDragColMove()  # Disable reordering of columns by dragging
        grid.SetCellHighlightPenWidth(
            0)  # Disable the highlight around the "current" cell
        grid.SetCellHighlightROPenWidth(
            0)  # Disable the highlight around the "current" read-only cell
        grid.SetSelectionMode(wx.grid.Grid.SelectRows)  # Select the entire row

        grid.SetColLabelValue(_SHIP_COL, "Ship")
        grid.SetColLabelValue(_FIT_COL, "Fit")
        grid.SetColLabelValue(_POINTS_COL, "Points")
        grid.SetColLabelValue(_EHP_COL, "EHP")
        grid.SetColLabelValue(_DPS_COL, "DPS")
        grid.SetColLabelValue(_TANK_COL, "Tank")
        grid.SetColLabelValue(_ACTIVE_COL, "Active?")

        grid.SetColFormatBool(_ACTIVE_COL)

        grid.Bind(wx.grid.EVT_GRID_CELL_CHANGING, self._onCellChanging)
        grid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, self._showContextMenu)
        grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self._onCellLeftClick)
        grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK,
                  self._onCellDoubleLeftClick)
        gui.mainFrame.MainFrame.getInstance().Bind(GE.FIT_CHANGED,
                                                   self._onFitChanged)

        shipCountLabel = wx.StaticText(self)
        pointCountLabel = wx.StaticText(self)
        dpsLabel = wx.StaticText(self)
        ehpLabel = wx.StaticText(self)

        infoPanelSizer = wx.FlexGridSizer(4, 0, 16)
        infoPanelSizer.Add(wx.StaticText(self, label="Ships"),
                           flag=wx.ALIGN_CENTER)
        infoPanelSizer.Add(wx.StaticText(self, label="Points"),
                           flag=wx.ALIGN_CENTER)
        infoPanelSizer.Add(wx.StaticText(self, label="Total DPS"),
                           flag=wx.ALIGN_CENTER)
        infoPanelSizer.Add(wx.StaticText(self, label="Total EHP"),
                           flag=wx.ALIGN_CENTER)
        infoPanelSizer.Add(shipCountLabel, flag=wx.ALIGN_CENTER)
        infoPanelSizer.Add(pointCountLabel, flag=wx.ALIGN_CENTER)
        infoPanelSizer.Add(dpsLabel, flag=wx.ALIGN_CENTER)
        infoPanelSizer.Add(ehpLabel, flag=wx.ALIGN_CENTER)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 1, wx.EXPAND)
        sizer.Add(infoPanelSizer, 0, wx.EXPAND | wx.ALL, border=8)
        self.SetSizer(sizer)

        self._grid = grid
        self.shipCountLabel = shipCountLabel
        self.pointCountLabel = pointCountLabel
        self.dpsLabel = dpsLabel
        self.ehpLabel = ehpLabel
        self._setup: Setup = None
Пример #27
0
 def init_grid(panel):
     grid_box = wx.BoxSizer(wx.VERTICAL)
     title = wx.StaticText(panel, -1, "Grid")
     data_grid = Grid(panel, -1, size=(700, -1))
     data_grid.SetTable(GlobalVariable.grid_data)
     data_grid.AdjustScrollbars()
     data_grid.EnableEditing(False)  # 设置数据无法修改
     data_grid.SetRowLabelSize(40)
     data_grid.SetColLabelSize(20)
     data_grid.DisableDragRowSize()  # 设置无法拖动修改行高
     data_grid.SetSelectionMode(Grid.wxGridSelectRows)  # 设置整行选取模式
     data_grid.Refresh()
     data_grid.Bind(grid.EVT_GRID_CELL_RIGHT_DCLICK, self.copy_line)
     button_box = wx.BoxSizer(wx.HORIZONTAL)
     previous_button = wx.Button(panel, -1, '<', size=(-1, -1))
     next_button = wx.Button(panel, -1, '>', size=(-1, -1))
     self.Bind(wx.EVT_BUTTON, self.__on_previous, previous_button)
     self.Bind(wx.EVT_BUTTON, self.__on_next, next_button)
     button_box.Add(previous_button)
     button_box.Add(next_button)
     grid_box.Add(title, 0)
     grid_box.Add(data_grid, 1,
                  wx.EXPAND | wx.TOP | wx.RIGHT | wx.BOTTOM, 5)
     grid_box.Add(button_box, 0, wx.EXPAND | wx.BOTTOM, 5)
     return data_grid, grid_box
Пример #28
0
    def run_as_data_tool(self, workspace):
        m = workspace.measurements
        assert isinstance(m, cpmeas.Measurements)
        m.is_first_image = True
        image_set_count = m.image_set_count
        for i in range(image_set_count):
            self.run(workspace)
            img_stats = workspace.display_data.statistics
            if i == 0:
                header = ["Image set"]
                for flag_name, object_name, feature, value, pf in img_stats:
                    header.append(flag_name)
                header.append("Pass/Fail")
                statistics = [header]
            row = [str(i + 1)]
            ok = True
            for flag_name, object_name, feature, value, pf in img_stats:
                ok = ok and (pf == "Pass")
                row.append(str(value))
            row.append("Pass" if ok else "Fail")
            statistics.append(row)
            if i < image_set_count - 1:
                m.next_image_set()
        self.show_window = False
        if image_set_count > 0:
            import wx
            from wx.grid import Grid, PyGridTableBase, EVT_GRID_LABEL_LEFT_CLICK
            from cellprofiler.gui import get_cp_icon

            frame = wx.Frame(workspace.frame, -1, "Flag image results")
            sizer = wx.BoxSizer(wx.VERTICAL)
            frame.SetSizer(sizer)
            grid = Grid(frame, -1)
            sizer.Add(grid, 1, wx.EXPAND)
            #
            # The flag table supplies the statistics to the grid
            # using the grid table interface
            #
            sort_order = np.arange(len(statistics) - 1)
            sort_col = [None]
            sort_ascending = [None]

            def on_label_clicked(event):
                col = event.GetCol()
                if sort_col[0] == col:
                    sort_ascending[0] = not sort_ascending[0]
                else:
                    sort_ascending[0] = True
                sort_col[0] = col
                data = [x[col] for x in statistics[1:]]
                try:
                    data = np.array(data, float)
                except ValueError:
                    data = np.array(data)
                if sort_ascending[0]:
                    sort_order[:] = np.lexsort((data, ))
                else:
                    sort_order[::-1] = np.lexsort((data, ))
                grid.ForceRefresh()

            grid.Bind(EVT_GRID_LABEL_LEFT_CLICK, on_label_clicked)

            class FlagTable(PyGridTableBase):
                def __init__(self):
                    PyGridTableBase.__init__(self)

                def GetColLabelValue(self, col):
                    if col == sort_col[0]:
                        if sort_ascending[0]:

                            return statistics[0][col] + " v"
                        else:
                            return statistics[0][col] + " ^"
                    return statistics[0][col]

                def GetNumberRows(self):
                    return len(statistics) - 1

                def GetNumberCols(self):
                    return len(statistics[0])

                def GetValue(self, row, col):
                    return statistics[sort_order[row] + 1][col]

            grid.SetTable(FlagTable())
            frame.Fit()
            max_size = int(
                wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y) * 3 / 4)
            if frame.Size[1] > max_size:
                frame.SetSize((frame.Size[0], max_size))
            frame.SetIcon(get_cp_icon())
            frame.Show()
Пример #29
0
    def __init__(self, parent):
        Grid.__init__(self, parent)

        self.selected_row = None
        self.__data = None
        self.__data_attrs = [u'name', u'by', u'selector', u'location', u'dimensions']
Пример #30
0
class PanelMeasure(wx.Panel):

    def __init__(self, graph, settings):
        wx.Panel.__init__(self, graph)

        self.spectrum = None
        self.graph = graph
        self.settings = settings

        self.measure = None

        self.checked = {Measure.MIN: "",
                        Measure.MAX: "",
                        Measure.AVG: "",
                        Measure.GMEAN: "",
                        Measure.HBW: "",
                        Measure.OBW: ""}

        self.selected = None

        self.SetBackgroundColour('white')

        self.grid = Grid(self)
        self.grid.CreateGrid(3, 19)
        self.grid.EnableEditing(True)
        self.grid.EnableDragGridSize(False)
        self.grid.SetColLabelSize(1)
        self.grid.SetRowLabelSize(1)
        self.grid.SetColMinimalAcceptableWidth(1)
        self.grid.SetColSize(2, 1)
        self.grid.SetColSize(7, 1)
        self.grid.SetColSize(11, 1)
        self.grid.SetColSize(15, 1)
        self.grid.SetMargins(0, wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y))

        for x in range(self.grid.GetNumberRows()):
            self.grid.SetRowLabelValue(x, '')
        for y in range(self.grid.GetNumberCols()):
            self.grid.SetColLabelValue(y, '')

        for row in range(self.grid.GetNumberRows()):
            for col in range(self.grid.GetNumberCols()):
                self.grid.SetReadOnly(row, col, True)

        self.locsDesc = {'F Start': (0, 0),
                         'F End': (1, 0),
                         'F Delta': (2, 0),
                         'P Min': (0, 4),
                         'P Max': (1, 4),
                         'P Delta': (2, 4),
                         'Mean': (0, 9),
                         'GMean': (1, 9),
                         'Flatness': (2, 9),
                         '-3dB Start': (0, 13),
                         '-3dB End': (1, 13),
                         '-3dB Delta': (2, 13),
                         'OBW Start': (0, 17),
                         'OBW End': (1, 17),
                         'OBW Delta': (2, 17)}
        self.__set_descs()

        self.locsCheck = {Measure.MIN: (0, 3), Measure.MAX: (1, 3),
                          Measure.AVG: (0, 8), Measure.GMEAN: (1, 8),
                          Measure.HBW: (0, 12),
                          Measure.OBW: (0, 16)}
        self.__set_check_editor()

        self.locsFreq = [(0, 1), (1, 1)]
        self.__set_freq_editor()

        colour = self.grid.GetBackgroundColour()
        self.grid.SetCellTextColour(2, 3, colour)
        self.grid.SetCellTextColour(2, 8, colour)
        self.grid.SetCellTextColour(1, 12, colour)
        self.grid.SetCellTextColour(2, 12, colour)
        self.grid.SetCellTextColour(1, 16, colour)
        self.grid.SetCellTextColour(2, 16, colour)

        self.__clear_checks()

        self.locsMeasure = {'start': (0, 1), 'end': (1, 1), 'deltaF': (2, 1),
                            'minFP': (0, 5), 'maxFP': (1, 5), 'deltaFP': (2, 5),
                            'minP': (0, 6), 'maxP': (1, 6), 'deltaP': (2, 6),
                            'avg': (0, 10), 'gmean': (1, 10), 'flat': (2, 10),
                            'hbwstart': (0, 14), 'hbwend': (1, 14), 'hbwdelta': (2, 14),
                            'obwstart': (0, 18), 'obwend': (1, 18), 'obwdelta': (2, 18)}

        fontCell = self.grid.GetDefaultCellFont()
        fontSize = fontCell.GetPointSize()
        fontStyle = fontCell.GetStyle()
        fontWeight = fontCell.GetWeight()
        font = wx.Font(fontSize, wx.FONTFAMILY_MODERN, fontStyle,
                       fontWeight)
        dc = wx.WindowDC(self.grid)
        dc.SetFont(font)
        widthMHz = dc.GetTextExtent('###.######')[0] * 1.2
        widthdB = dc.GetTextExtent('-##.##')[0] * 1.2
        for _desc, (_row, col) in self.locsDesc.items():
            self.grid.AutoSizeColumn(col)
        for col in [1, 5, 14, 18]:
            self.grid.SetColSize(col, widthMHz)
            for row in range(self.grid.GetNumberRows()):
                self.grid.SetCellFont(row, col, font)
        for col in [6, 10]:
            self.grid.SetColSize(col, widthdB)
            for row in range(self.grid.GetNumberRows()):
                self.grid.SetCellFont(row, col, font)
        for _desc, (_row, col) in self.locsCheck.items():
            self.grid.AutoSizeColumn(col)

        toolTips = {self.locsMeasure['start']: 'Selection start (MHz)', self.locsMeasure['end']: 'Selection end (MHz)',
                    self.locsMeasure['deltaF']: 'Selection bandwidth (MHz)',
                    self.locsMeasure['minFP']: 'Minimum power location (MHz)',
                    self.locsMeasure['maxFP']: 'Maximum power location (MHz)',
                    self.locsMeasure['deltaFP']: 'Power location difference (MHz)',
                    self.locsMeasure['minP']: 'Minimum power (dB)', self.locsMeasure['maxP']: 'Maximum power (dB)',
                    self.locsMeasure['deltaP']: 'Power difference (dB)', self.locsMeasure['avg']: 'Mean power (dB)',
                    self.locsMeasure['gmean']: 'Geometric mean power (dB)',
                    self.locsMeasure['flat']: 'Spectral flatness',
                    self.locsMeasure['hbwstart']: '-3db start location (MHz)',
                    self.locsMeasure['hbwend']: '-3db end location (MHz)',
                    self.locsMeasure['hbwdelta']: '-3db bandwidth (MHz)',
                    self.locsMeasure['obwstart']: '99% start location (MHz)',
                    self.locsMeasure['obwend']: '99% end location (MHz)',
                    self.locsMeasure['obwdelta']: '99% bandwidth (MHz)'}

        self.toolTips = GridToolTips(self.grid, toolTips)

        self.popupMenu = wx.Menu()
        self.popupMenuCopy = self.popupMenu.Append(wx.ID_ANY, "&Copy",
                                                   "Copy entry")
        self.Bind(wx.EVT_MENU, self.__on_copy, self.popupMenuCopy)

        self.Bind(EVT_GRID_CELL_RIGHT_CLICK, self.__on_popup_menu)
        self.Bind(EVT_GRID_CELL_LEFT_CLICK, self.__on_cell_click)
        if wx.VERSION >= (3, 0, 0, 0):
            self.Bind(EVT_GRID_CELL_CHANGED, self.__on_cell_change)

        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.grid, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT,
                border=10)
        self.SetSizer(box)

    def __set_descs(self):
        font = self.grid.GetCellFont(0, 0)
        font.SetWeight(wx.FONTWEIGHT_BOLD)

        for desc, (row, col) in self.locsDesc.items():
            self.grid.SetCellValue(row, col, desc)
            self.grid.SetCellFont(row, col, font)

    def __set_check_editor(self):
        for _desc, (row, col) in self.locsCheck.items():
            self.grid.SetCellEditor(row, col, GridCellBoolEditor())
            self.grid.SetCellAlignment(row, col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid.SetCellRenderer(row, col, CheckBoxCellRenderer(self))

    def __set_freq_editor(self):
        for (row, col) in self.locsFreq:
            self.grid.SetReadOnly(row, col, False)
            self.grid.SetCellAlignment(row, col, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid.SetCellEditor(row, col, GridCellFloatEditor(precision=4))

    def __set_check_value(self, cell, value):
        (row, col) = self.locsCheck[cell]
        self.grid.SetCellValue(row, col, value)

    def __set_measure_value(self, cell, value):
        (row, col) = self.locsMeasure[cell]
        try:
            self.grid.SetCellValue(row, col, value)
        except TypeError:
            pass

    def __set_check_enable(self, cell, enable):
        (row, col) = self.locsCheck[cell]
        renderer = self.grid.GetCellRenderer(row, col)
        renderer.Enable(not enable)

    def __get_checks(self):
        checks = {}
        for cell in self.checked:
            if self.checked[cell] == '1':
                checks[cell] = True
            else:
                checks[cell] = False

        return checks

    def __update_checks(self):
        for cell in self.checked:
            self.__set_check_value(cell, self.checked[cell])

    def __clear_checks(self):
        for cell in self.checked:
            self.checked[cell] = '0'
        self.__update_checks()

    def __on_cell_click(self, event):
        self.grid.ClearSelection()
        row = event.GetRow()
        col = event.GetCol()

        if (row, col) in self.locsCheck.values():
            if self.grid.GetCellRenderer(row, col).enabled and self.measure is not None:
                check = self.grid.GetCellValue(row, col)
                if check == '1':
                    check = '0'
                else:
                    check = '1'
                self.grid.SetCellValue(row, col, check)

                for control, (r, c) in self.locsCheck.items():
                    if (r, c) == (row, col):
                        self.checked[control] = check

                if self.selected is None:
                    self.selected = self.locsMeasure['start']
                    row = self.selected[0]
                    col = self.selected[1]
                    self.grid.SetGridCursor(row, col)
                self.update_measure()
        elif (row, col) in self.locsMeasure.values():
            self.selected = (row, col)
            self.grid.SetGridCursor(row, col)
        elif self.selected is None:
            self.selected = self.locsMeasure['start']
            row = self.selected[0]
            col = self.selected[1]
            self.grid.SetGridCursor(row, col)

    def __on_cell_change(self, event):
        row = event.GetRow()
        col = event.GetCol()

        if (row, col) in self.locsFreq:
            start = None
            end = None

            try:
                start = float(self.grid.GetCellValue(self.locsFreq[0][0], self.locsFreq[0][1]))
            except ValueError:
                pass
            try:
                end = float(self.grid.GetCellValue(self.locsFreq[1][0], self.locsFreq[1][1]))
            except ValueError:
                pass

            if start is None and end is None:
                return
            elif start is None and end is not None:
                start = end - 1
            elif start is not None and end is None:
                end = start + 1
            if start > end:
                swap = start
                start = end
                end = swap

            self.graph.set_selected(start, end)
            self.set_selected(self.spectrum, start, end)

    def __on_popup_menu(self, _event):
        if self.selected:
            self.popupMenuCopy.Enable(True)
        else:
            self.popupMenuCopy.Enable(False)
        self.PopupMenu(self.popupMenu)

    def __on_copy(self, _event):
        value = self.grid.GetCellValue(self.selected[0], self.selected[1])
        clip = wx.TextDataObject(value)
        wx.TheClipboard.Open()
        wx.TheClipboard.SetData(clip)
        wx.TheClipboard.Close()

    def update_measure(self):
        show = self.__get_checks()
        self.graph.update_measure(self.measure, show)

    def clear_measurement(self):
        for control in self.locsMeasure:
            self.__set_measure_value(control, "")
        self.__clear_checks()
        self.update_measure()
        self.measure = None

    def set_selected(self, spectrum, start, end):
        self.spectrum = spectrum
        if start is None:
            return

        self.measure = Measure(spectrum, start, end)
        if not self.measure.is_valid():
            self.clear_measurement()
            return

        minF, maxF = self.measure.get_f()
        minP = self.measure.get_min_p()
        maxP = self.measure.get_max_p()
        avgP = self.measure.get_avg_p()
        gMeanP = self.measure.get_gmean_p()
        flatness = self.measure.get_flatness()
        hbw = self.measure.get_hpw()
        obw = self.measure.get_obw()

        self.__set_measure_value('start',
                                 format_precision(self.settings,
                                                  minF,
                                                  units=False))
        self.__set_measure_value('end',
                                 format_precision(self.settings,
                                                  maxF,
                                                  units=False))
        self.__set_measure_value('deltaF',
                                 format_precision(self.settings,
                                                  maxF - minF,
                                                  units=False))
        self.__set_measure_value('minFP',
                                 format_precision(self.settings,
                                                  minP[0],
                                                  units=False))
        self.__set_measure_value('maxFP',
                                 format_precision(self.settings,
                                                  maxP[0],
                                                  units=False))
        self.__set_measure_value('deltaFP',
                                 format_precision(self.settings,
                                                  maxP[0] - minP[0],
                                                  units=False))
        self.__set_measure_value('minP',
                                 format_precision(self.settings,
                                                  level=minP[1],
                                                  units=False))
        self.__set_measure_value('maxP',
                                 format_precision(self.settings,
                                                  level=maxP[1],
                                                  units=False))
        self.__set_measure_value('deltaP',
                                 format_precision(self.settings,
                                                  level=maxP[1] - minP[1],
                                                  units=False))
        self.__set_measure_value('avg',
                                 format_precision(self.settings,
                                                  level=avgP,
                                                  units=False))
        self.__set_measure_value('gmean',
                                 format_precision(self.settings,
                                                  level=gMeanP,
                                                  units=False))
        self.__set_measure_value('flat',
                                 "{0:.4f}".format(flatness))
        text = ""
        if hbw[0] is not None:
            text = format_precision(self.settings, hbw[0], units=False)
        else:
            text = ''
        self.__set_measure_value('hbwstart', text)
        if hbw[1] is not None:
            text = format_precision(self.settings, hbw[1], units=False)
        else:
            text = ''
        self.__set_measure_value('hbwend', text)
        if hbw[0] is not None and hbw[1] is not None:
            text = format_precision(self.settings, hbw[1] - hbw[0], units=False)
        else:
            text = ''
        self.__set_measure_value('hbwdelta', text)

        if obw[0] is not None:
            text = format_precision(self.settings, obw[0], units=False)
        else:
            text = ''
        self.__set_measure_value('obwstart', text)
        if obw[1] is not None:
            text = format_precision(self.settings, obw[1], units=False)
        else:
            text = ''
        self.__set_measure_value('obwend', text)
        if obw[0] is not None and obw[1] is not None:
            text = format_precision(self.settings, obw[1] - obw[0],
                                    units=False)
        else:
            text = ''
        self.__set_measure_value('obwdelta', text)

        self.update_measure()

    def show(self, show):
        if show:
            self.Show()
        else:
            self.Hide()
        self.Layout()

    def set_type(self, display):
        for cell in self.locsCheck:
            self.__set_check_enable(cell, True)
        if display == Display.PLOT:
            for cell in self.locsCheck:
                self.__set_check_enable(cell, False)
        elif display == Display.SPECT:
            self.__set_check_enable(Measure.HBW, False)
            self.__set_check_enable(Measure.OBW, False)

        self.grid.Refresh()
Пример #31
0
class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        self.dao = self.init_db()
        self.read_records = 0
        constraint = Constraints()
        constraint.offset = 0
        constraint.limit = 100

        # First, call the base class' __init__ method to create the frame
        wx.Frame.__init__(self, parent, id, title, wx.Point(100, 100),
                          wx.Size(300, 200))

        # Associate some events with methods of this class
        wx.EVT_SIZE(self, self.OnSize)
        #wx.EVT_SCROLLWIN_BOTTOM(self, self.OnEndScroll)

        # Add a panel and some controls to display the size and position
        panel = wx.Panel(self, -1)
        panel.SetBackgroundColour('#FDDF99')

        self.grid = Grid(panel)
        self.grid.CreateGrid(0, 12)
        wx.grid.EVT_GRID_CELL_LEFT_CLICK(self, self.OnGridLeftClick)
        #wx.EVT_SCROLLWIN_BOTTOM(self.grid, self.OnEndScroll)
        self.grid.Bind(wx.EVT_SCROLLWIN, self.OnEndScroll)

        #self.grid.SetCellBackgroundColour(2, 2, wx.CYAN)

        #self.grid.SetCellEditor(5, 0, wx.grid.GridCellNumberEditor(1,1000))
        #self.grid.SetCellValue(5, 0, "123")

        #self.grid.SetCellAlignment(9, 1, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
        #self.grid.SetCellValue(9, 1, "This cell is set to span 3 rows and 3 columns")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.grid, 1, wx.EXPAND)
        panel.SetSizer(sizer)

        #self.grid.ClearGrid()
        ##self.grid.AppendRows(20)
        #self.grid.SetColLabelValue(0,"test")
        #self.grid.SetCellValue(21, 1, "This cell is set to span 3 rows and 3 columns")

        rows = self.dao.fetch_records(constraint,
                                      raw_answers=True,
                                      record_type_classname=AutosModel)
        self.read_records = len(rows)

        print(rows[0])
        #print(rows[7]["marca"])
        #print(rows[7]["modelo"])
        #print(rows[7]["version"])

        self.printRows(rows)

    def printRows(self, rows):
        self.grid.SetColLabelValue(0, rows[0][0][0])
        self.grid.SetColLabelValue(1, rows[0][1][0])
        self.grid.SetColLabelValue(2, rows[0][2][0])

        self.grid.AppendRows(self.read_records)
        i = -1
        for row in rows:
            #print(i)
            #print(row[0])
            #print(row[1])
            #print(row[2])
            if i > -1:
                self.grid.SetCellValue(i, 0, row[0])
                self.grid.SetCellValue(i, 1, row[1])
                self.grid.SetCellValue(i, 2, str(row[2]))
            i = i + 1

        self.grid.AutoSize()

    # This method is called automatically when the CLOSE event is
    # sent to this window
    def OnCloseWindow(self, event):
        # tell the window to kill itself
        self.Destroy()

    def OnEndScroll(self, event):
        # tell the window to kill itself
        print("Llegue al final")
        print(event.GetPosition())
        print(event.GetOrientation())
        #print(event.__dict__)
        #print(event.commandType)
        event.Skip()

    # This method is called by the system when the window is resized,
    # because of the association above.
    def OnSize(self, event):

        # tell the event system to continue looking for an event handler,
        # so the default handler will get called.
        event.Skip()

    def OnGridLeftClick(self, evt):
        print("OnCellLeftClick: (%d,%d) %s\n" %
              (evt.GetRow(), evt.GetCol(), evt.GetPosition()))
        evt.Skip()

    def init_db(self):

        trx = TransactionManager(
            'mssql', {
                'dsn': 'MSSQLServer',
                'host': '192.168.0.7',
                'port': '1433',
                'user': '******',
                'password': '******',
                'database': 'veritrade'
            })

        daoDelegate = DAODelegateTest()
        return DatabasePersistence(trx, daoDelegate)