示例#1
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()
示例#2
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()
示例#3
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)