Example #1
0
    def _runCmd(self, cmdString):
        """!Run command
        
        @param cmdString command to run (given as a string)
        """
        if self.parent.GetName() == "ModelerDialog":
            self.parent.OnOk(None)
            return

        if not cmdString or self.standAlone:
            return

        if cmdString[:2] == 'd.' and not self.parent.parent.GetMapDisplay():
            self.parent.parent.NewDisplay(show=True)

        self.commands.append(cmdString)  # trace commands

        # parse command into list
        try:
            cmd = utils.split(str(cmdString))
        except UnicodeError:
            cmd = utils.split(EncodeString((cmdString)))
        cmd = map(DecodeString, cmd)

        # send the command list to the processor
        if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
            self.parent.parent.OnMapCalculator(event=None, cmd=cmd)
        else:
            self.parent.RunCmd(cmd)

        # add command to history & clean prompt
        self.UpdateCmdHistory(cmd)
        self.OnCmdErase(None)
        self.parent.parent.statusbar.SetStatusText('')
Example #2
0
    def _runCmd(self, cmdString):
        """!Run command
        
        @param cmdString command to run (given as a string)
        """
        if self.parent.GetName() == "ModelerDialog":
            self.parent.OnOk(None)
            return
        
        if not cmdString or self.standAlone:
            return
        
        if cmdString[:2] == 'd.' and not self.parent.parent.curr_page:
            self.parent.parent.NewDisplay(show = True)
                
        self.commands.append(cmdString) # trace commands

        # parse command into list
        try:
            cmd = utils.split(str(cmdString))
        except UnicodeError:
            cmd = utils.split(EncodeString((cmdString)))
        cmd = map(DecodeString, cmd)
        
        # send the command list to the processor 
        if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
            self.parent.parent.OnMapCalculator(event = None, cmd = cmd)
        else:
            self.parent.RunCmd(cmd)
            
        # add command to history & clean prompt
        self.UpdateCmdHistory(cmd)
        self.OnCmdErase(None)
        self.parent.parent.statusbar.SetStatusText('')
Example #3
0
 def _getCmd(self):
     line = self.cmd_prompt.GetCurLine()[0].strip()
     if len(line) == 0:
         cmd = list()
     else:
         try:
             cmd = utils.split(str(line))
         except UnicodeError:
             cmd = utils.split(EncodeString((line)))
     return cmd
Example #4
0
 def _getCmd(self):
     line = self.cmd_prompt.GetCurLine()[0].strip()
     if len(line) == 0:
         cmd = list()
     else:
         try:
             cmd = utils.split(str(line))
         except UnicodeError:
             cmd = utils.split(EncodeString((line)))
     return cmd
Example #5
0
 def GetCmd(self):
     """!Get command"""
     line = self.cmd_prompt.GetCurLine()[0].strip()
     if len(line) == 0:
         list()
     
     try:
         cmd = utils.split(str(line))
     except UnicodeError:
         cmd = utils.split(utils.EncodeString((line)))
         
     return cmd
Example #6
0
    def GetCmd(self):
        """!Get command"""
        line = self.cmd_prompt.GetCurLine()[0].strip()
        if len(line) == 0:
            list()

        try:
            cmd = utils.split(str(line))
        except UnicodeError:
            cmd = utils.split(utils.EncodeString((line)))

        return cmd
Example #7
0
    def _createMenuItem(
        self,
        menu,
        label,
        description,
        handler,
        command,
        keywords,
        shortcut="",
        icon="",
        wxId=wx.ID_ANY,
        kind=wx.ITEM_NORMAL,
    ):
        """Creates menu items
        There are three menu styles (menu item text styles).
        1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
        """
        if not label:
            menu.AppendSeparator()
            return

        if command:
            helpString = command + " -- " + description
        else:
            helpString = description

        if shortcut:
            label += "\t" + shortcut

        menuItem = wx.MenuItem(menu, wxId, label, helpString, kind)
        if icon:
            menuItem.SetBitmap(MetaIcon(img=icon).GetBitmap(self.bmpsize))
        menu.AppendItem(menuItem)

        self.menucmd[menuItem.GetId()] = command

        if command:
            try:
                cmd = utils.split(str(command))
            except UnicodeError:
                cmd = utils.split(EncodeString((command)))
            # disable only grass commands which are not present (e.g.
            # r.in.lidar)
            if (
                cmd
                and cmd[0] not in globalvar.grassCmd
                and re.match("[rvdipmgt][3bs]?\.([a-z0-9\.])+", cmd[0])
            ):
                menuItem.Enable(False)

        rhandler = eval("self.parent." + handler)
        self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
Example #8
0
def validate_not_too_many_caps(value):
    """
    Tries to figure out whether the value has too many capitals.
    Maximum two capitals per word.
    """
    authorized_beginning = ("a", "de", "la", "mac", "mc")
    message = _(
        "It seems there are too many uppercase letters. Please try with '%(correct_value)s'."
    )
    correct_value = title_with_particule(value)

    words = split(value)
    if not any(words):
        pass  # For non-letters.
    elif value == value.upper():
        validate_not_all_caps(value)
    else:
        for word in words:
            nb_caps = sum(1 for char in word if char.isupper())
            if nb_caps > 1:
                if any(
                    [word.lower().startswith(s)
                     for s in authorized_beginning]):
                    # This should validate 'McCoy'.
                    if nb_caps > 2:
                        raise ValidationError(
                            message,
                            code='caps',
                            params={'correct_value': correct_value})
                else:
                    raise ValidationError(
                        message,
                        code='caps',
                        params={'correct_value': correct_value})
Example #9
0
def __elimination_phase__(matrix, verbose=False, output=sys.stdout):
    if verbose:
        output.write('starting elimination phase\n')
    size = len(matrix)
    m, b = utils.split(matrix)
    pivots = functions.pivot_matrix(m)
    pivoted_m = functions.mult_matrix(pivots, m)
    pivoted_b = functions.mult_matrix(pivots, b)
    pivoted_matrix = utils.stich(pivoted_m, pivoted_b)

    def step(matrix, index):
        if verbose:
            output.write(f'step {index}/{size - 1}:\n')
            output.write(utils.pretty_print(matrix))
        pivot_row = matrix[index]

        def nullify(element):
            i, row = element
            if i <= index:
                return row
            else:
                if pivot_row[index] == 0:
                    raise GaussianEliminationError(
                        f'encoutered zero element a[{index + 1}][{index + 1}]')
                scale = row[index] / pivot_row[index]
                return functions.subtract_rows(
                    row, functions.scale_row(pivot_row, scale))

        reduced_matrix = map(nullify, enumerate(matrix))
        return tuple(reduced_matrix)

    reduced_matrix = functools.reduce(step, range(0, size), pivoted_matrix)
    if verbose:
        output.write('elimination phase finished\n')
    return reduced_matrix
Example #10
0
 def _getCmd(self):
     line = self.cmd_prompt.GetCurLine()[0].strip()
     if len(line) == 0:
         cmd = list()
     else:
         cmd = utils.split(str(line))
     return cmd
Example #11
0
def decomposition(matrix, verbose=False, output=sys.stdout):
    '''
    Performs an LU decomposition of matrix (which must be square) into matrix = L * U. 
    The function returns L and U.
    If pivoting is enbled, rearanges matrix via pivot matrix.
    '''
    try:
        output.write('starting LU decomposition\n')
        output.write('current matrix:\n')
        op_matrix, _ = utils.split(matrix)
        output.write(utils.pretty_print(op_matrix))
        l, u = lu_decomposition(op_matrix, None, verbose, output)
        output.write('matrix L:\n')
        output.write(utils.pretty_print(l))
        output.write('matrix U:\n')
        output.write(utils.pretty_print(u))
        inversed = inverse(l, u)
        output.write('inversed matrix:\n')
        output.write(utils.pretty_print(inversed))
        cond = functions.infinity_norm(op_matrix) * functions.infinity_norm(
            inversed)
        output.write('condition number: {}\n'.format(cond))
        output.write('LU decomposition finished\n')
    except Exception as ex:
        output.write('unexpected exception: {}\n'.format(ex))
        sys.exit(1)
Example #12
0
    def _createMenuItem(self,
                        menu,
                        menustyle,
                        label,
                        help,
                        handler,
                        gcmd,
                        keywords,
                        shortcut='',
                        wxId=wx.ID_ANY,
                        kind=wx.ITEM_NORMAL):
        """!Creates menu items
        There are three menu styles (menu item text styles).
        1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
        """
        if not label:
            menu.AppendSeparator()
            return

        if len(gcmd) > 0:
            helpString = gcmd + ' -- ' + help
            if menustyle == 1:
                label += '   [' + gcmd + ']'
            elif menustyle == 2:
                label = '      [' + gcmd + ']'
        else:
            helpString = help

        if shortcut:
            label += '\t' + shortcut

        menuItem = menu.Append(wxId, label, helpString, kind)

        self.menucmd[menuItem.GetId()] = gcmd

        if gcmd:
            try:
                cmd = utils.split(str(gcmd))
            except UnicodeError:
                cmd = utils.split(EncodeString((gcmd)))
            if cmd and cmd[0] not in globalvar.grassCmd:
                menuItem.Enable(False)

        rhandler = eval('self.parent.' + handler)

        self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
Example #13
0
 def EntityToComplete(self):
     """!Determines which part of command (flags, parameters) should
     be completed at current cursor position"""
     entry = self.GetTextLeft()
     toComplete = dict()
     try:
         cmd = entry.split()[0].strip()
     except IndexError:
         return None
     
     try:
         splitted = utils.split(str(entry))
     except ValueError: # No closing quotation error
         return None
     if len(splitted) > 1:
         if cmd in globalvar.grassCmd:
             toComplete['cmd'] = cmd
             if entry[-1] == ' ':
                 words = entry.split(' ')
                 if any(word.startswith('-') for word in words):
                     toComplete['entity'] = 'params'
                 else:
                     toComplete['entity'] = 'params+flags'
             else:
                 # get word left from current position
                 word = self.GetWordLeft(withDelimiter = True)
                 
                 if word[0] == '=' and word[-1] == '@':
                     toComplete['entity'] = 'mapsets'
                 elif word[0] == '=':
                     # get name of parameter
                     paramName = self.GetWordLeft(withDelimiter = False, ignoredDelimiter = '=').strip('=')
                     if paramName:
                         try:
                             param = self.cmdDesc.get_param(paramName)
                         except (ValueError, AttributeError):
                             return None
                     else:
                         return None
                     
                     if param['values']:
                         toComplete['entity'] = 'param values'
                     elif param['prompt'] == 'raster' and param['element'] == 'cell':
                         toComplete['entity'] = 'raster map'
                     elif param['prompt'] == 'vector' and param['element'] == 'vector':
                         toComplete['entity'] = 'vector map'
                 elif word[0] == '-':
                     toComplete['entity'] = 'flags'
                 elif word[0] == ' ':
                     toComplete['entity'] = 'params'
         else:
             return None
     else:
         toComplete['entity'] = 'command'
         toComplete['cmd'] = cmd
     
     return toComplete
Example #14
0
    def EntityToComplete(self):
        """Determines which part of command (flags, parameters) should
        be completed at current cursor position"""
        entry = self.GetTextLeft()
        toComplete = dict(cmd=None, entity=None)
        try:
            cmd = entry.split()[0].strip()
        except IndexError:
            return toComplete

        try:
            splitted = utils.split(str(entry))
        except ValueError:  # No closing quotation error
            return toComplete
        if len(splitted) > 0 and cmd in globalvar.grassCmd:
            toComplete["cmd"] = cmd
            if entry[-1] == " ":
                words = entry.split(" ")
                if any(word.startswith("-") for word in words):
                    toComplete["entity"] = "params"
                else:
                    toComplete["entity"] = "params+flags"
            else:
                # get word left from current position
                word = self.GetWordLeft(withDelimiter=True)

                if word[0] == "=" and word[-1] == "@":
                    toComplete["entity"] = "mapsets"
                elif word[0] == "=":
                    # get name of parameter
                    paramName = self.GetWordLeft(
                        withDelimiter=False, ignoredDelimiter="=").strip("=")
                    if paramName:
                        try:
                            param = self.cmdDesc.get_param(paramName)
                        except (ValueError, AttributeError):
                            return toComplete
                    else:
                        return toComplete

                    if param["values"]:
                        toComplete["entity"] = "param values"
                    elif param["prompt"] == "raster" and param[
                            "element"] == "cell":
                        toComplete["entity"] = "raster map"
                    elif param["prompt"] == "vector" and param[
                            "element"] == "vector":
                        toComplete["entity"] = "vector map"
                elif word[0] == "-":
                    toComplete["entity"] = "flags"
                elif word[0] == " ":
                    toComplete["entity"] = "params"
        else:
            toComplete["entity"] = "command"
            toComplete["cmd"] = cmd

        return toComplete
Example #15
0
    def EntityToComplete(self):
        """Determines which part of command (flags, parameters) should
        be completed at current cursor position"""
        entry = self.GetTextLeft()
        toComplete = dict(cmd=None, entity=None)
        try:
            cmd = entry.split()[0].strip()
        except IndexError:
            return toComplete

        try:
            splitted = utils.split(str(entry))
        except ValueError:  # No closing quotation error
            return toComplete
        if len(splitted) > 0 and cmd in globalvar.grassCmd:
            toComplete['cmd'] = cmd
            if entry[-1] == ' ':
                words = entry.split(' ')
                if any(word.startswith('-') for word in words):
                    toComplete['entity'] = 'params'
                else:
                    toComplete['entity'] = 'params+flags'
            else:
                # get word left from current position
                word = self.GetWordLeft(withDelimiter=True)

                if word[0] == '=' and word[-1] == '@':
                    toComplete['entity'] = 'mapsets'
                elif word[0] == '=':
                    # get name of parameter
                    paramName = self.GetWordLeft(
                        withDelimiter=False, ignoredDelimiter='=').strip('=')
                    if paramName:
                        try:
                            param = self.cmdDesc.get_param(paramName)
                        except (ValueError, AttributeError):
                            return toComplete
                    else:
                        return toComplete

                    if param['values']:
                        toComplete['entity'] = 'param values'
                    elif param['prompt'] == 'raster' and param[
                            'element'] == 'cell':
                        toComplete['entity'] = 'raster map'
                    elif param['prompt'] == 'vector' and param[
                            'element'] == 'vector':
                        toComplete['entity'] = 'vector map'
                elif word[0] == '-':
                    toComplete['entity'] = 'flags'
                elif word[0] == ' ':
                    toComplete['entity'] = 'params'
        else:
            toComplete['entity'] = 'command'
            toComplete['cmd'] = cmd

        return toComplete
Example #16
0
    def _runCmd(self, cmdString):
        """Run command

        :param str cmdString: command to run
        """
        if not cmdString:
            return

        # parse command into list
        try:
            cmd = utils.split(str(cmdString))
        except UnicodeError:
            cmd = utils.split(EncodeString((cmdString)))
        cmd = list(map(DecodeString, cmd))

        self.promptRunCmd.emit(cmd=cmd)

        self.OnCmdErase(None)
        self.ShowStatusText('')
Example #17
0
 def test_split_util(self):
     test_data = (
         ("ibn Khaldun", ["ibn", "Khaldun"]),
         ("ibn_Khaldun", ["ibn_Khaldun"]),
         ("ibn-Khaldun", ["ibn", "Khaldun"]),
         ("ibn.Khaldun", ["ibn", "Khaldun"]),
         ("ibn'Khaldun", ["ibn", "Khaldun"]),
         ("ibn5Khaldun", ["ibn5Khaldun"]),
     )
     for original_value, expected_value in test_data:
         with self.subTest(value=original_value):
             self.assertEqual(split(original_value), expected_value)
Example #18
0
 def test_decomposition_a(self):
     matrix = input.get(open('data/matrix_a.in'))
     matrix, x = utils.split(matrix)
     expected_l = ((1.0, 0.0, 0.0, 0.0), (-1.5, 1.0, 0.0, 0.0),
                   (-0.5, 4 / 3, 1.0, 0.0), (0.5, -1 / 3, 2.0, 1.0))
     expected_u = ((2.0, 2.0, -1.0, 1.0), (0.0, 3.0, 1.5, 1.5),
                   (0.0, 0.0, 0.5, 0.5), (0.0, 0.0, 0.0, 3.0))
     expected_x = (4.0, -2.0, 1.0, 0.0)
     actual_l, actual_u = lu.lu_decomposition(matrix)
     actual_x = lu.solve(actual_l, actual_u, x)
     self.__compare_matrices__(expected_l, actual_l)
     self.__compare_matrices__(expected_u, actual_u)
     self.__compare_vectors__(expected_x, actual_x)
Example #19
0
    def _createMenuItem(
            self, menu, label, description, handler, command, keywords,
            shortcut='', icon='', wxId=wx.ID_ANY, kind=wx.ITEM_NORMAL):
        """Creates menu items
        There are three menu styles (menu item text styles).
        1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
        """
        if not label:
            menu.AppendSeparator()
            return

        if command:
            helpString = command + ' -- ' + description
        else:
            helpString = description

        if shortcut:
            label += '\t' + shortcut

        menuItem = wx.MenuItem(menu, wxId, label, helpString, kind)
        if icon:
            menuItem.SetBitmap(MetaIcon(img=icon).GetBitmap(self.bmpsize))
        menu.AppendItem(menuItem)

        self.menucmd[menuItem.GetId()] = command

        if command:
            try:
                cmd = utils.split(str(command))
            except UnicodeError:
                cmd = utils.split(EncodeString((command)))
            # disable only grass commands which are not present (e.g.
            # r.in.lidar)
            if cmd and cmd[0] not in globalvar.grassCmd and \
               re.match('[rvdipmgt][3bs]?\.([a-z0-9\.])+', cmd[0]):
                menuItem.Enable(False)

        rhandler = eval('self.parent.' + handler)
        self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
Example #20
0
    def _runCmd(self, cmdString):
        """Run command
        
        :param str cmdString: command to run
        """
        if not cmdString:
            return

        self.commands.append(cmdString) # trace commands

        # parse command into list
        try:
            cmd = utils.split(str(cmdString))
        except UnicodeError:
            cmd = utils.split(EncodeString((cmdString)))
        cmd = map(DecodeString, cmd)

        self.promptRunCmd.emit(cmd=cmd)

        # add command to history & clean prompt
        ### self.UpdateCmdHistory(cmd)
        self.OnCmdErase(None)
        self.ShowStatusText('')
Example #21
0
 def _createMenuItem(self, menu, menustyle, label, help, handler, gcmd, keywords,
                     shortcut = '', wxId = wx.ID_ANY, kind = wx.ITEM_NORMAL):
     """!Creates menu items
     There are three menu styles (menu item text styles).
     1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
     """
     if not label:
         menu.AppendSeparator()
         return
     
     if len(gcmd) > 0:
         helpString = gcmd + ' -- ' + help
         if menustyle == 1:
             label += '   [' + gcmd + ']'
         elif menustyle == 2:
             label = '      [' + gcmd + ']'
     else:
         helpString = help
     
     if shortcut:
         label += '\t' + shortcut
     
     menuItem = menu.Append(wxId, label, helpString, kind)
     
     self.menucmd[menuItem.GetId()] = gcmd
     
     if gcmd: 
         try: 
             cmd = utils.split(str(gcmd)) 
         except UnicodeError: 
             cmd = utils.split(EncodeString((gcmd))) 
         if cmd and cmd[0] not in globalvar.grassCmd: 
             menuItem.Enable(False)
     
     rhandler = eval('self.parent.' + handler)
     
     self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
Example #22
0
    def _setValueFromSelected(self):
        """!Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
         Will do nothing if no item is selected in the wx.ListCtrl.
         """
        sel = self.dropdownlistbox.GetFirstSelected()
        if sel < 0:
            return

        if self._colFetch != -1:
            col = self._colFetch
        else:
            col = self._colSearch
        itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()

        cmd = utils.split(str(self.GetValue()))
        if len(cmd) > 0 and cmd[0] in self._choicesCmd:
            # -> append text (skip last item)
            if self._choiceType == 'param':
                itemtext = itemtext.split(' ')[0]
                self.SetValue(' '.join(cmd) + ' ' + itemtext + '=')
                optType = self._module.get_param(itemtext)['prompt']
                if optType in ('raster', 'vector'):
                    # -> raster/vector map
                    self.SetChoices(self._choicesMap[optType], optType)
            elif self._choiceType == 'flag':
                itemtext = itemtext.split(' ')[0]
                if len(itemtext) > 1:
                    prefix = '--'
                else:
                    prefix = '-'
                self.SetValue(' '.join(cmd[:-1]) + ' ' + prefix + itemtext)
            elif self._choiceType in ('raster', 'vector'):
                self.SetValue(' '.join(cmd[:-1]) + ' ' +
                              cmd[-1].split('=', 1)[0] + '=' + itemtext)
        else:
            # -> reset text
            self.SetValue(itemtext + ' ')

            # define module
            self._setModule(itemtext)

            # use parameters as default choices
            self._choiceType = 'param'
            self.SetChoices(self._choicesMap['param'], type='param')

        self.SetInsertionPointEnd()

        self._showDropDown(False)
Example #23
0
 def OnEnteredText(self, event):
     """!Text entered"""
     text = event.GetString()
     
     if not text:
         # control is empty; hide dropdown if shown:
         if self.dropdown.IsShown():
             self._showDropDown(False)
         event.Skip()
         return
     
     try:
         cmd = utils.split(str(text))
     except ValueError, e:
         self.statusbar.SetStatusText(str(e))
         cmd = text.split(' ')
Example #24
0
    def OnEnteredText(self, event):
        """!Text entered"""
        text = event.GetString()

        if not text:
            # control is empty; hide dropdown if shown:
            if self.dropdown.IsShown():
                self._showDropDown(False)
            event.Skip()
            return

        try:
            cmd = utils.split(str(text))
        except ValueError, e:
            self.statusbar.SetStatusText(str(e))
            cmd = text.split(' ')
Example #25
0
 def _setValueFromSelected(self):
      """!Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
      Will do nothing if no item is selected in the wx.ListCtrl.
      """
      sel = self.dropdownlistbox.GetFirstSelected()
      if sel < 0:
          return
      
      if self._colFetch != -1:
          col = self._colFetch
      else:
          col = self._colSearch
      itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
      
      cmd = utils.split(str(self.GetValue()))
      if len(cmd) > 0 and cmd[0] in self._choicesCmd:
          # -> append text (skip last item)
          if self._choiceType == 'param':
              itemtext = itemtext.split(' ')[0]
              self.SetValue(' '.join(cmd) + ' ' + itemtext + '=')
              optType = self._module.get_param(itemtext)['prompt']
              if optType in ('raster', 'vector'):
                  # -> raster/vector map
                  self.SetChoices(self._choicesMap[optType], optType)
          elif self._choiceType == 'flag':
              itemtext = itemtext.split(' ')[0]
              if len(itemtext) > 1:
                  prefix = '--'
              else:
                  prefix = '-'
              self.SetValue(' '.join(cmd[:-1]) + ' ' + prefix + itemtext)
          elif self._choiceType in ('raster', 'vector'):
              self.SetValue(' '.join(cmd[:-1]) + ' ' + cmd[-1].split('=', 1)[0] + '=' + itemtext)
      else:
          # -> reset text
          self.SetValue(itemtext + ' ')
          
          # define module
          self._setModule(itemtext)
          
          # use parameters as default choices
          self._choiceType = 'param'
          self.SetChoices(self._choicesMap['param'], type = 'param')
      
      self.SetInsertionPointEnd()
      
      self._showDropDown(False)
Example #26
0
def elimination(matrix, verbose=False, output=sys.stdout):
    '''
    Executes gaussian elimination process on given matrix. 
    If verbose is true, logs every operation to given output.
    '''
    try:
        output.write('starting gaussian elimination\n')
        output.write('current matrix:\n')
        output.write(utils.pretty_print(matrix))
        reduced_matrix = __elimination_phase__(matrix, verbose, output)
        output.write('reduced matrix:\n')
        output.write(utils.pretty_print(reduced_matrix))
        determinant = functions.det(utils.split(reduced_matrix)[0])
        output.write(f'matrix determinant: {determinant}\n')
        xs = __back_substitution_phase__(reduced_matrix, verbose, output)
        output.write(f'solution (x-vector): {xs}\n')
        output.write('gaussian elimination finished\n')
    except GaussianEliminationError as gee:
        output.write(f'gaussian elimination error: {gee}\n')
        sys.exit(65)
    except Exception as ex:
        output.write(f'unexpected exception: {ex}\n')
        sys.exit(1)
Example #27
0
 def test_decomposition_g(self):
     matrix = input.get(open('data/matrix_g.in'))
     matrix, _ = utils.split(matrix)
     with self.assertRaises(ZeroDivisionError):
         _, _ = lu.lu_decomposition(matrix)
Example #28
0
    def GetLayersFromCmdFile(self):
        """Get list of map layers from cmdfile
        """
        if not self.cmdfile:
            return

        nlayers = 0
        try:
            fd = open(self.cmdfile, 'r')
            lines = fd.readlines()
            fd.close()
            # detect d.out.file, delete the line from the cmd file and export
            # graphics
            if len(lines) > 0:
                if lines[-1].startswith('d.out.file') or \
                   lines[-1].startswith('d.to.rast'):
                    dCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if lines[-1].startswith('d.out.file'):
                        self.saveToFile.emit(cmd=utils.split(dCmd))
                    else:
                        self.dToRast.emit(cmd=utils.split(dCmd))
                    return
                if lines[-1].startswith('d.what'):
                    dWhatCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if '=' in utils.split(dWhatCmd)[1]:
                        maps = utils.split(dWhatCmd)[1].split('=')[
                            1].split(',')
                    else:
                        maps = utils.split(dWhatCmd)[1].split(',')
                    self.query.emit(ltype=utils.split(dWhatCmd)[
                                    0].split('.')[-1], maps=maps)
                    return
            else:
                # clean overlays after erase
                self.oldOverlays = []
                overlays = self._giface.GetMapDisplay().decorations.keys()
                for each in overlays:
                    self._giface.GetMapDisplay().RemoveOverlay(each)

            existingLayers = self.GetListOfLayers()

            # holds new rendreing order for every layer in existingLayers
            layersOrder = [-1] * len(existingLayers)

            # next number in rendering order
            next_layer = 0
            mapFile = None
            render_env = dict()
            for line in lines:
                if line.startswith('#'):
                    if 'GRASS_RENDER_FILE' in line:
                        mapFile = line.split('=', 1)[1].strip()
                    try:
                        k, v = line[2:].strip().split('=', 1)
                    except:
                        pass
                    render_env[k] = v
                    continue

                cmd = utils.split(line.strip())

                ltype = None
                try:
                    ltype = utils.command2ltype[cmd[0]]
                except KeyError:
                    grass.warning(_("Unsupported command %s.") % cmd[0])
                    continue

                name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True,
                                                 layerType=ltype)[0]

                args = {}

                if ltype in ('barscale', 'rastleg', 'northarrow', 'text', 'vectleg'):
                    # TODO: this is still not optimal
                    # it is there to prevent adding the same overlay multiple times
                    if cmd in self.oldOverlays:
                        continue
                    if ltype == 'rastleg':
                        self._giface.GetMapDisplay().AddLegendRast(cmd=cmd)
                    elif ltype == 'barscale':
                        self._giface.GetMapDisplay().AddBarscale(cmd=cmd)
                    elif ltype == 'northarrow':
                        self._giface.GetMapDisplay().AddArrow(cmd=cmd)
                    elif ltype == 'text':
                        self._giface.GetMapDisplay().AddDtext(cmd=cmd)
                    elif ltype == 'vectleg':
                        self._giface.GetMapDisplay().AddLegendVect(cmd=cmd)
                    self.oldOverlays.append(cmd)
                    continue

                classLayer = MapLayer
                args['ltype'] = ltype

                mapLayer = classLayer(name=name,
                                      cmd=cmd,
                                      Map=None,
                                      hidden=True,
                                      render=False,
                                      mapfile=mapFile,
                                      **args)
                mapLayer.GetRenderMgr().updateProgress.connect(self.GetRenderMgr().ReportProgress)
                if render_env:
                    mapLayer.GetRenderMgr().UpdateRenderEnv(render_env)
                    render_env = dict()

                exists = False
                for i, layer in enumerate(existingLayers):
                    if layer.GetCmd(
                            string=True) == mapLayer.GetCmd(
                            string=True):
                        exists = True

                        if layersOrder[i] == -1:
                            layersOrder[i] = next_layer
                            next_layer += 1
                        # layer must be put higher in render order (same cmd was insered more times)
                        # TODO delete rendurant cmds from cmd file?
                        else:
                            for j, l_order in enumerate(layersOrder):
                                if l_order > layersOrder[i]:
                                    layersOrder[j] -= 1
                            layersOrder[i] = next_layer - 1

                        break
                if exists:
                    continue

                newLayer = self._addLayer(mapLayer)

                existingLayers.append(newLayer)
                self.ownedLayers.append(newLayer)

                layersOrder.append(next_layer)
                next_layer += 1

                nlayers += 1

            reorderedLayers = [-1] * next_layer
            for i, layer in enumerate(existingLayers):

                # owned layer was not found in cmd file -> is deleted
                if layersOrder[i] == -1 and layer in self.ownedLayers:
                    self.ownedLayers.remove(layer)
                    self.DeleteLayer(layer)

                # other layer e. g. added by wx.vnet are added to the top
                elif layersOrder[i] == -1 and layer not in self.ownedLayers:
                    reorderedLayers.append(layer)

                # owned layer found in cmd file is added into proper rendering
                # position
                else:
                    reorderedLayers[layersOrder[i]] = layer

            self.SetLayers(reorderedLayers)

        except IOError as e:
            grass.warning(
                _("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") %
                {'cmd': self.cmdfile, 'det': e})
            return

        Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s, nlayers=%d" %
                  (self.cmdfile, nlayers))

        self._giface.updateMap.emit(render=False)
Example #29
0
    def GetLayersFromCmdFile(self):
        """Get list of map layers from cmdfile
        """
        if not self.cmdfile:
            return

        nlayers = 0

        try:
            fd = open(self.cmdfile, 'r')
            lines = fd.readlines()
            fd.close()
            # detect d.out.file, delete the line from the cmd file and export graphics
            if len(lines) > 0:
                if lines[-1].startswith('d.out.file') or lines[-1].startswith('d.to.rast'):
                    dCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if lines[-1].startswith('d.out.file'):
                        self.saveToFile.emit(cmd=utils.split(dCmd))
                    else:
                        self.dToRast.emit(cmd=utils.split(dCmd))
                    return
                if lines[-1].startswith('d.what'):
                    dWhatCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if '=' in utils.split(dWhatCmd)[1]:
                        maps = utils.split(dWhatCmd)[1].split('=')[1].split(',')
                    else:
                        maps = utils.split(dWhatCmd)[1].split(',')
                    self.query.emit(ltype=utils.split(dWhatCmd)[0].split('.')[-1], maps=maps)
                    return

            existingLayers = self.GetListOfLayers()

            # holds new rendreing order for every layer in existingLayers
            layersOrder = [-1] * len(self.GetListOfLayers())

            # next number in rendering order
            next_layer = 0

            for line in lines:
                cmd = utils.split(line.strip())
                ltype = None

                try:
                    ltype = utils.command2ltype[cmd[0]]
                except KeyError:
                    grass.warning(_("Unsupported command %s.") % cmd[0])
                    continue

                name = utils.GetLayerNameFromCmd(cmd, fullyQualified = True,
                                                 layerType = ltype)[0]

                # creating temporary layer object to compare commands
                # neccessary to get the same format
                # supposing that there are no side effects
                tmpMapLayer = MapLayer(ltype = ltype, name = name,
                                       cmd = cmd, Map = None,
                                       active = False, hidden = True,
                                       opacity = 0)
                exists = False
                for i, layer in enumerate(existingLayers):
                    if layer.GetCmd(string=True) == tmpMapLayer.GetCmd(string=True):
                        exists = True

                        if layersOrder[i] == -1: 
                            layersOrder[i] = next_layer;
                            next_layer += 1
                        # layer must be put higher in render order (same cmd was insered more times)
                        # TODO delete rendurant cmds from cmd file?
                        else:
                            for j, l_order in enumerate(layersOrder):
                                if l_order > layersOrder[i]:
                                    layersOrder[j] -= 1;
                            layersOrder[i] = next_layer - 1;

                        break
                if exists:
                    continue

                newLayer = Map.AddLayer(self, ltype = ltype, command = cmd, active = True, name = name)
                
                existingLayers.append(newLayer)
                self.ownedLayers.append(newLayer)

                layersOrder.append(next_layer)
                next_layer += 1

                nlayers += 1

            reorderedLayers = [-1] * next_layer
            for i, layer in enumerate(existingLayers):

                # owned layer was not found in cmd file -> is deleted 
                if layersOrder[i] == -1 and layer in self.ownedLayers:
                    self.ownedLayers.remove(layer)
                    self.DeleteLayer(layer)

                # other layer e. g. added by wx.vnet are added to the top
                elif layersOrder[i] == -1 and layer not in self.ownedLayers:
                    reorderedLayers.append(layer)
                
                # owned layer found in cmd file is added into proper rendering position
                else:
                    reorderedLayers[layersOrder[i]] = layer

            self.SetLayers(reorderedLayers)

        except IOError as e:
            grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
                              { 'cmd' : self.cmdfile, 'det' : e })
            return

        self._giface.updateMap.emit()

        Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s" % self.cmdfile)
        Debug.msg(1, "                            nlayers=%d" % nlayers)
Example #30
0
    def GetLayersFromCmdFile(self):
        """Get list of map layers from cmdfile
        """
        if not self.cmdfile:
            return

        nlayers = 0
        try:
            fd = open(self.cmdfile, 'r')
            lines = fd.readlines()
            fd.close()
            # detect d.out.file, delete the line from the cmd file and export
            # graphics
            if len(lines) > 0:
                if lines[-1].startswith('d.out.file') or \
                   lines[-1].startswith('d.to.rast'):
                    dCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if lines[-1].startswith('d.out.file'):
                        self.saveToFile.emit(cmd=utils.split(dCmd))
                    else:
                        self.dToRast.emit(cmd=utils.split(dCmd))
                    return
                if lines[-1].startswith('d.what'):
                    dWhatCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if '=' in utils.split(dWhatCmd)[1]:
                        maps = utils.split(dWhatCmd)[1].split('=')[1].split(
                            ',')
                    else:
                        maps = utils.split(dWhatCmd)[1].split(',')
                    self.query.emit(
                        ltype=utils.split(dWhatCmd)[0].split('.')[-1],
                        maps=maps)
                    return
            else:
                # clean overlays after erase
                self.oldOverlays = []
                overlays = list(
                    self._giface.GetMapDisplay().decorations.keys())
                for each in overlays:
                    self._giface.GetMapDisplay().RemoveOverlay(each)

            existingLayers = self.GetListOfLayers()

            # holds new rendreing order for every layer in existingLayers
            layersOrder = [-1] * len(existingLayers)

            # next number in rendering order
            next_layer = 0
            mapFile = None
            render_env = dict()
            for line in lines:
                if line.startswith('#'):
                    if 'GRASS_RENDER_FILE' in line:
                        mapFile = line.split('=', 1)[1].strip()
                    try:
                        k, v = line[2:].strip().split('=', 1)
                    except:
                        pass
                    render_env[k] = v
                    continue

                cmd = utils.split(line.strip())

                ltype = None
                try:
                    ltype = utils.command2ltype[cmd[0]]
                except KeyError:
                    grass.warning(_("Unsupported command %s.") % cmd[0])
                    continue

                name = utils.GetLayerNameFromCmd(cmd,
                                                 fullyQualified=True,
                                                 layerType=ltype)[0]

                args = {}

                if ltype in ('barscale', 'rastleg', 'northarrow', 'text',
                             'vectleg'):
                    # TODO: this is still not optimal
                    # it is there to prevent adding the same overlay multiple times
                    if cmd in self.oldOverlays:
                        continue
                    if ltype == 'rastleg':
                        self._giface.GetMapDisplay().AddLegendRast(cmd=cmd)
                    elif ltype == 'barscale':
                        self._giface.GetMapDisplay().AddBarscale(cmd=cmd)
                    elif ltype == 'northarrow':
                        self._giface.GetMapDisplay().AddArrow(cmd=cmd)
                    elif ltype == 'text':
                        self._giface.GetMapDisplay().AddDtext(cmd=cmd)
                    elif ltype == 'vectleg':
                        self._giface.GetMapDisplay().AddLegendVect(cmd=cmd)
                    self.oldOverlays.append(cmd)
                    continue

                classLayer = MapLayer
                args['ltype'] = ltype

                exists = False
                for i, layer in enumerate(existingLayers):
                    if layer.GetCmd(string=True) == utils.GetCmdString(
                            cmdlist_to_tuple(cmd)):
                        exists = True

                        if layersOrder[i] == -1:
                            layersOrder[i] = next_layer
                            next_layer += 1
                        # layer must be put higher in render order (same cmd was insered more times)
                        # TODO delete rendurant cmds from cmd file?
                        else:
                            for j, l_order in enumerate(layersOrder):
                                if l_order > layersOrder[i]:
                                    layersOrder[j] -= 1
                            layersOrder[i] = next_layer - 1

                        break
                if exists:
                    continue

                mapLayer = classLayer(name=name,
                                      cmd=cmd,
                                      Map=None,
                                      hidden=True,
                                      render=False,
                                      mapfile=mapFile,
                                      **args)
                mapLayer.GetRenderMgr().updateProgress.connect(
                    self.GetRenderMgr().ReportProgress)
                if render_env:
                    mapLayer.GetRenderMgr().UpdateRenderEnv(render_env)
                    render_env = dict()

                newLayer = self._addLayer(mapLayer)

                existingLayers.append(newLayer)
                self.ownedLayers.append(newLayer)

                layersOrder.append(next_layer)
                next_layer += 1

                nlayers += 1

            reorderedLayers = [-1] * next_layer
            for i, layer in enumerate(existingLayers):

                # owned layer was not found in cmd file -> is deleted
                if layersOrder[i] == -1 and layer in self.ownedLayers:
                    self.ownedLayers.remove(layer)
                    self.DeleteLayer(layer)

                # other layer e. g. added by wx.vnet are added to the top
                elif layersOrder[i] == -1 and layer not in self.ownedLayers:
                    reorderedLayers.append(layer)

                # owned layer found in cmd file is added into proper rendering
                # position
                else:
                    reorderedLayers[layersOrder[i]] = layer

            self.SetLayers(reorderedLayers)

        except IOError as e:
            grass.warning(
                _("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % {
                    'cmd': self.cmdfile,
                    'det': e
                })
            return

        Debug.msg(
            1, "Map.GetLayersFromCmdFile(): cmdfile=%s, nlayers=%d" %
            (self.cmdfile, nlayers))

        self._giface.updateMap.emit(render=False)
Example #31
0
    def GetLayersFromCmdFile(self):
        """Get list of map layers from cmdfile
        """
        if not self.cmdfile:
            return

        nlayers = 0

        try:
            fd = open(self.cmdfile, 'r')
            lines = fd.readlines()
            fd.close()
            # detect d.out.file, delete the line from the cmd file and export graphics
            if len(lines) > 0:
                if lines[-1].startswith('d.out.file') or lines[-1].startswith(
                        'd.to.rast'):
                    dCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if lines[-1].startswith('d.out.file'):
                        self.saveToFile.emit(cmd=utils.split(dCmd))
                    else:
                        self.dToRast.emit(cmd=utils.split(dCmd))
                    return
                if lines[-1].startswith('d.what'):
                    dWhatCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if '=' in utils.split(dWhatCmd)[1]:
                        maps = utils.split(dWhatCmd)[1].split('=')[1].split(
                            ',')
                    else:
                        maps = utils.split(dWhatCmd)[1].split(',')
                    self.query.emit(
                        ltype=utils.split(dWhatCmd)[0].split('.')[-1],
                        maps=maps)
                    return

            existingLayers = self.GetListOfLayers()

            # holds new rendreing order for every layer in existingLayers
            layersOrder = [-1] * len(self.GetListOfLayers())

            # next number in rendering order
            next_layer = 0

            for line in lines:
                cmd = utils.split(line.strip())
                ltype = None

                try:
                    ltype = utils.command2ltype[cmd[0]]
                except KeyError:
                    grass.warning(_("Unsupported command %s.") % cmd[0])
                    continue

                name = utils.GetLayerNameFromCmd(cmd,
                                                 fullyQualified=True,
                                                 layerType=ltype)[0]

                # creating temporary layer object to compare commands
                # neccessary to get the same format
                # supposing that there are no side effects
                tmpMapLayer = MapLayer(ltype=ltype,
                                       name=name,
                                       cmd=cmd,
                                       Map=None,
                                       active=False,
                                       hidden=True,
                                       opacity=0)
                exists = False
                for i, layer in enumerate(existingLayers):
                    if layer.GetCmd(string=True) == tmpMapLayer.GetCmd(
                            string=True):
                        exists = True

                        if layersOrder[i] == -1:
                            layersOrder[i] = next_layer
                            next_layer += 1
                        # layer must be put higher in render order (same cmd was insered more times)
                        # TODO delete rendurant cmds from cmd file?
                        else:
                            for j, l_order in enumerate(layersOrder):
                                if l_order > layersOrder[i]:
                                    layersOrder[j] -= 1
                            layersOrder[i] = next_layer - 1

                        break
                if exists:
                    continue

                newLayer = Map.AddLayer(self,
                                        ltype=ltype,
                                        command=cmd,
                                        active=True,
                                        name=name)

                existingLayers.append(newLayer)
                self.ownedLayers.append(newLayer)

                layersOrder.append(next_layer)
                next_layer += 1

                nlayers += 1

            reorderedLayers = [-1] * next_layer
            for i, layer in enumerate(existingLayers):

                # owned layer was not found in cmd file -> is deleted
                if layersOrder[i] == -1 and layer in self.ownedLayers:
                    self.ownedLayers.remove(layer)
                    self.DeleteLayer(layer)

                # other layer e. g. added by wx.vnet are added to the top
                elif layersOrder[i] == -1 and layer not in self.ownedLayers:
                    reorderedLayers.append(layer)

                # owned layer found in cmd file is added into proper rendering position
                else:
                    reorderedLayers[layersOrder[i]] = layer

            self.SetLayers(reorderedLayers)

        except IOError as e:
            grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
                              { 'cmd' : self.cmdfile, 'det' : e })
            return

        self._giface.updateMap.emit()

        Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s" % self.cmdfile)
        Debug.msg(1, "                            nlayers=%d" % nlayers)
Example #32
0
def __back_substitution_phase__(matrix, verbose=False, output=sys.stdout):
    data, b = utils.split(matrix)
    return functions.bakckward(data, b, verbose, output)